blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
146
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
7
| license_type
stringclasses 2
values | repo_name
stringlengths 6
79
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 4
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.07k
426M
⌀ | star_events_count
int64 0
27
| fork_events_count
int64 0
12
| gha_license_id
stringclasses 3
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 6
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 20
6.28M
| extension
stringclasses 20
values | content
stringlengths 20
6.28M
| authors
listlengths 1
16
| author_lines
listlengths 1
16
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f085a31a68c7be57b32f635e2171bd4d9cd4bad6 | 36d0ddb69764f39c440089ecebd10d7df14f75f3 | /プログラム/Game/Object/GameScene/PlayerAction.cpp | 4b0cd04568e2012342eb58e901d6a8608d0ff172 | []
| no_license | weimingtom/tanuki-mo-issyo | 3f57518b4e59f684db642bf064a30fc5cc4715b3 | ab57362f3228354179927f58b14fa76b3d334472 | refs/heads/master | 2021-01-10T01:36:32.162752 | 2009-04-19T10:37:37 | 2009-04-19T10:37:37 | 48,733,344 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 4,738 | cpp | /*******************************************************************************/
/**
* @file PlayerAction.cpp.
*
* @brief プレイヤーアクションソース定義.
*
* @date 2008/12/23.
*
* @version 1.00.
*
* @author Jun Futagawa.
*/
/*******************************************************************************/
#include "PlayerAction.h"
#include "Player.h"
#include "Object/GameScene/Result.h"
#include "Object/GameScene/Effect/CutinEffect.h"
/*=========================================================================*/
/**
* @brief コンストラクタ.
*
*/
PlayerAction::PlayerAction(IGameDevice &device, ObjectManager &objectManager, Option &option, GameSceneState &gameSceneState, Player &player) :
m_device(device), m_objectManager(objectManager), m_option(option), m_gameSceneState(gameSceneState), m_player(player)
{
}
/*=========================================================================*/
/**
* @brief デストラクタ.
*
*/
PlayerAction::~PlayerAction()
{
}
/*=========================================================================*/
/**
* @brief 初期化処理.
*
*/
void PlayerAction::Initialize()
{
}
/*=========================================================================*/
/**
* @brief アタック.
*
*/
void PlayerAction::Attack(Player* player)
{
int id;
if(m_player.GetPlayerParameter().GetPlayerID() == 0)
{
id = CUTIN_LEFT;
} else
{
id = CUTIN_RIGHT;
}
m_objectManager.AddEffect(m_objectManager.GetEffectFactory().CreateCutinEffect(m_gameSceneState, *player, id));
m_player.GetPlayerParameter().SetPlayerTime(m_player.GetPlayerParameter().GetMaxPlayerTime());
player->GetPlayerAction().Damage(m_player.GetPlayerParameter().GetPlayerAttack());
m_player.GetCharacterScreen().GetAvatar().SetAnimationState(AVATAR_ANIMATION_STATE_ATTACK);
}
/*=========================================================================*/
/**
* @brief ダメージ.
*
*/
void PlayerAction::Damage(int damage)
{
m_player.GetPlayerParameter().SetHp(m_player.GetPlayerParameter().GetHp()-damage);
m_player.GetCharacterScreen().GetAvatar().SetAnimationState(AVATAR_ANIMATION_STATE_DAMAGE);
if(m_player.GetPlayerParameter().GetHp() <= 0)
{
PlayerLose();
}
}
void PlayerAction::AddSkillPoint(int id)
{
int* skill;
skill = m_player.GetPlayerParameter().GetSkillPoint();
skill[id]++;
m_player.GetPlayerParameter().SetSkillPoint(skill);
}
void PlayerAction::ClearSkillPoint()
{
int skill[4] = {0, 0, 0, 0};
m_player.GetPlayerParameter().SetSkillPoint(skill);
}
void PlayerAction::AddHP(int num)
{
m_player.GetPlayerParameter().SetHp(m_player.GetPlayerParameter().GetHp() + num);
}
void PlayerAction::AddAttack(int num)
{
m_player.GetPlayerParameter().SetPlayerAttack(m_player.GetPlayerParameter().GetPlayerAttack() + num);
}
void PlayerAction::AddDefence(int num)
{
m_player.GetPlayerParameter().SetPlayerDefence(m_player.GetPlayerParameter().GetPlayerDefence() + num);
}
void PlayerAction::AddScore(int num)
{
m_player.GetPlayerParameter().SetScore(m_player.GetPlayerParameter().GetScore() + num);
}
void PlayerAction::AddTime(int num)
{
m_player.GetPlayerParameter().SetPlayerTime(m_player.GetPlayerParameter().GetPlayerTime() + num);
}
void PlayerAction::SubTime(int num)
{
m_player.GetPlayerParameter().SetPlayerTime(m_player.GetPlayerParameter().GetPlayerTime() - num);
}
void PlayerAction::PlayerWin()
{
/*
m_gameSceneState.SetGameState(GAME_STATE_RESULT);
m_player.GetPlayerParameter().SetPlayerJudge(PLAYER_JUDGE_WIN);
if(m_player.GetPlayerParameter().GetPlayerID() != m_gameSceneState.GetPlayer(0)->GetPlayerParameter().GetPlayerID())
{
m_gameSceneState.GetPlayer(0)->GetPlayerParameter().SetPlayerJudge(PLAYER_JUDGE_LOSE);
} else
{
m_gameSceneState.GetPlayer(1)->GetPlayerParameter().SetPlayerJudge(PLAYER_JUDGE_LOSE);
}
m_objectManager.AddObject(m_objectManager.GetObjectFactory().CreateResult(m_gameSceneState));
*/
}
void PlayerAction::PlayerLose()
{
m_gameSceneState.SetGameState(GAME_STATE_RESULT);
m_player.GetPlayerParameter().SetPlayerJudge(PLAYER_JUDGE_LOSE);
if(m_player.GetPlayerParameter().GetPlayerID() != m_gameSceneState.GetPlayer(0)->GetPlayerParameter().GetPlayerID())
{
m_gameSceneState.GetPlayer(0)->GetPlayerParameter().SetPlayerJudge(PLAYER_JUDGE_WIN);
} else
{
m_gameSceneState.GetPlayer(1)->GetPlayerParameter().SetPlayerJudge(PLAYER_JUDGE_WIN);
}
m_objectManager.AddObject(m_objectManager.GetObjectFactory().CreateResult(m_gameSceneState));
}
/*===== EOF ===================================================================*/
| [
"rs.drip@aa49b5b2-a402-11dd-98aa-2b35b7097d33"
]
| [
[
[
1,
157
]
]
]
|
f90e8ff4f9093a23ea3c465dd3678811ad27e34b | b08e948c33317a0a67487e497a9afbaf17b0fc4c | /LuaPlus/Src/Modules/Misc/HeapAllocator.h | ef67be651cf696816d9cecc33c0b92115092ef02 | [
"MIT"
]
| permissive | 15831944/bastionlandscape | e1acc932f6b5a452a3bd94471748b0436a96de5d | c8008384cf4e790400f9979b5818a5a3806bd1af | refs/heads/master | 2023-03-16T03:28:55.813938 | 2010-05-21T15:00:07 | 2010-05-21T15:00:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 366 | h | #ifndef MISC_HEAPALLOCATOR_H
#define MISC_HEAPALLOCATOR_H
class HeapAllocator
{
public:
void* Alloc(size_t size) { return new unsigned char[size]; }
void Free(void* ptr) { delete[] (unsigned char*)ptr; }
void FreeAll() { }
void SetBlockSize(int) { }
void SetObjectSize(int) { }
};
#endif // MISC_HEAPALLOCATOR_H
| [
"voodoohaust@97c0069c-804f-11de-81da-11cc53ed4329"
]
| [
[
[
1,
14
]
]
]
|
9567be6ecb6acdab65f1e57b01ac0e7f11a4d427 | ea2786bfb29ab1522074aa865524600f719b5d60 | /MultimodalSpaceShooter/src/gui/ProgressBar.h | 41bea9a7ffc48bdd39acfc01f03c28998ed82075 | []
| 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 | 839 | h | #ifndef PROGRESSBAR_H
#define PROGRESSBAR_H
#include "gui/Widget.h"
#include <SFML/Graphics.hpp>
class ButtonListener;
//////////////////////////////////////////////////
/// Represents a progress bar
//////////////////////////////////////////////////
class ProgressBar : public Widget
{
public:
ProgressBar(const sf::Vector2f& position, const sf::Color& color);
virtual void onEvent(const sf::Event& event);
virtual void onMultimodalEvent(Multimodal::Event event);
virtual void update(float frameTime);
virtual void draw(sf::RenderTarget& window) const;
void setLevel(float level);
private:
static const float WIDTH;
static const float HEIGHT;
sf::Shape myFilling;
sf::Shape myOutline;
};
#endif // PROGRESSBAR_H | [
"[email protected]"
]
| [
[
[
1,
32
]
]
]
|
19b2ca16d72e5164b9b2a50b351d64aae517b6c4 | 5155ce0bfd77ae28dbf671deef6692220ac71aba | /main/src/common/CLogBase.cpp | 6efe2e8f07f641924ec3ff2b6b3153c511634620 | []
| no_license | OldRepoPreservation/taksi | 1ffcfbb0a100520ba4a050f571a15389ee9e9098 | 631c9080c14cf80d028b841ba41f8e884d252c8a | refs/heads/master | 2021-07-08T16:26:24.168833 | 2011-03-13T22:00:57 | 2011-03-13T22:00:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,358 | cpp | //
// CLogBase.cpp
// Copyright 1992 - 2006 Dennis Robinson (www.menasoft.com)
//
#include "stdafx.h"
#include "CLogBase.h"
CLogBase* g_pLog = NULL; // singleton // always access the base via pointer. (or g_Log)
int CLogBase::VDebugEvent( LOG_GROUP_MASK dwGroupMask, LOGL_TYPE eLogLevel, const LOGCHAR* pszFormat, va_list args ) // static
{
// default OutputDebugString event if no other handler. (this == NULL)
LOGCHAR szTemp[ 1024 + _MAX_PATH ]; // assume this magic number is big enough. _MAX_PATH
ASSERT( pszFormat && *pszFormat );
_vsnprintf( szTemp, sizeof(szTemp)-1, pszFormat, args );
#ifdef _WINDOWS
::OutputDebugStringA( szTemp );
#endif
return 0;
}
int CLogBase::EventStr( LOG_GROUP_MASK dwGroupMask, LOGL_TYPE eLogLevel, const LOGCHAR* pszMsg ) // virtual
{
// override this to route the messages elsewhere
if ( ! IsLogged( dwGroupMask, eLogLevel )) // I don't care about these ?
return( -1 );
if ( pszMsg == NULL )
return 0;
if ( pszMsg[0] == '\0' )
return 0;
size_t iLen = strlen(pszMsg);
ASSERT(iLen);
bool bHasCRLF = ( pszMsg[iLen-1]=='\r' || pszMsg[iLen-1]=='\n' );
if ( eLogLevel >= LOGL_ERROR )
{
#ifdef _WINDOWS
::OutputDebugStringA( "ERROR:" );
#endif
}
#ifdef _WINDOWS
::OutputDebugStringA( pszMsg );
if (( dwGroupMask & LOG_GROUP_CRLF ) && ! bHasCRLF )
{
::OutputDebugStringA( LOG_CR );
}
#else
// LINUX debug log ?
UNREFERENCED_PARAMETER(pszMsg);
#endif
return( 0 );
}
int CLogBase::VEvent( LOG_GROUP_MASK dwGroupMask, LOGL_TYPE eLogLevel, const LOGCHAR* pszFormat, va_list args ) // virtual
{
// This is currently not overriden but just in case we might want to.
if ( ! IsLogged( dwGroupMask, eLogLevel )) // I don't care about these ?
return( 0 );
LOGCHAR szTemp[ 1024 + _MAX_PATH ]; // assume this magic number is big enough. _MAX_PATH
ASSERT( pszFormat && *pszFormat );
_vsnprintf( szTemp, sizeof(szTemp)-1, pszFormat, args );
return( EventStr( dwGroupMask, eLogLevel, szTemp ));
}
int _cdecl CLogBase::Event( LOG_GROUP_MASK dwGroupMask, LOGL_TYPE eLogLevel, const LOGCHAR* pszFormat, ... )
{
int iRet = 0;
va_list vargs;
va_start( vargs, pszFormat );
if ( this == NULL )
{
iRet = VDebugEvent( dwGroupMask, eLogLevel, pszFormat, vargs );
}
else
{
iRet = VEvent( dwGroupMask, eLogLevel, pszFormat, vargs );
}
va_end( vargs );
return( iRet );
}
int _cdecl CLogBase::Debug_Error( const LOGCHAR* pszFormat, ... )
{
int iRet = 0;
va_list vargs;
va_start( vargs, pszFormat );
if ( this == NULL )
{
iRet = VDebugEvent( LOG_GROUP_DEBUG|LOG_GROUP_CRLF, LOGL_ERROR, pszFormat, vargs );
}
else
{
iRet = VEvent( LOG_GROUP_DEBUG|LOG_GROUP_CRLF, LOGL_ERROR, pszFormat, vargs );
}
va_end( vargs );
return( iRet );
}
int _cdecl CLogBase::Debug_Warn( const LOGCHAR* pszFormat, ... )
{
int iRet = 0;
va_list vargs;
va_start( vargs, pszFormat );
if ( this == NULL )
{
iRet = VDebugEvent( LOG_GROUP_DEBUG|LOG_GROUP_CRLF, LOGL_WARN, pszFormat, vargs );
}
else
{
iRet = VEvent( LOG_GROUP_DEBUG|LOG_GROUP_CRLF, LOGL_WARN, pszFormat, vargs );
}
va_end( vargs );
return( iRet );
}
int _cdecl CLogBase::Debug_Info( const LOGCHAR* pszFormat, ... )
{
int iRet = 0;
va_list vargs;
va_start( vargs, pszFormat );
if ( this == NULL )
{
iRet = VDebugEvent( LOG_GROUP_DEBUG|LOG_GROUP_CRLF, LOGL_INFO, pszFormat, vargs );
}
else
{
iRet = VEvent( LOG_GROUP_DEBUG|LOG_GROUP_CRLF, LOGL_INFO, pszFormat, vargs );
}
va_end( vargs );
return( iRet );
}
int _cdecl CLogBase::Debug_Trace( const LOGCHAR* pszFormat, ... )
{
int iRet = 0;
va_list vargs;
va_start( vargs, pszFormat );
if ( this == NULL )
{
iRet = VDebugEvent( LOG_GROUP_DEBUG|LOG_GROUP_CRLF, LOGL_TRACE, pszFormat, vargs );
}
else
{
iRet = VEvent( LOG_GROUP_DEBUG|LOG_GROUP_CRLF, LOGL_TRACE, pszFormat, vargs );
}
va_end( vargs );
return( iRet );
}
//**************************************************************************
void CLogBase::Assert_CheckFail( const char* pExp, const char* pFile, unsigned uLine )
{
// This is _assert() is MS code.
#ifdef _DEBUG
#if _MSC_VER >= 1400
// _wassert( pExp, pFile, uLine );
#elif _MSC_VER >= 1000
_assert( pExp, pFile, uLine );
#else
// CGExceptionAssert::Throw( pExp, pFile, uLine );
#endif
#else
if ( this == NULL )
{
// VDebugEvent( LOG_GROUP_DEBUG|LOG_GROUP_CRLF, LOGL_INFO, pszFormat, vargs );
}
else
{
Event( LOG_GROUP_DEBUG, LOGL_CRIT, "Assert Fail:'%s' file '%s', line %d" LOG_CR, pExp, pFile, uLine );
}
#endif
}
void CLogBase::Debug_CheckFail( const char* pExp, const char* pFile, unsigned uLine )
{
// A 'softer' version of assert. non-fatal checks
#ifdef _DEBUG
if ( this == NULL )
{
// VDebugEvent( LOG_GROUP_DEBUG|LOG_GROUP_CRLF, LOGL_INFO, pszFormat, vargs );
}
else
{
Event( LOG_GROUP_DEBUG, LOGL_ERROR, "Check Fail:'%s' file '%s', line %d" LOG_CR, pExp, pFile, uLine );
}
#endif
}
//************************************************************************
CLogFiltered::CLogFiltered( LOG_GROUP_MASK dwGroupMask, LOGL_TYPE eLogLevel ) :
m_Filter(dwGroupMask,eLogLevel)
{
if ( g_pLog == NULL )
g_pLog = this;
}
CLogFiltered::~CLogFiltered()
{
m_Filter.put_LogLevel(LOGL_NONE);
}
| [
"[email protected]"
]
| [
[
[
1,
206
]
]
]
|
b9baa6520da7cf2121cf07553c1fe7045f1e1f05 | 83ed25c6e6b33b2fabd4f81bf91d5fae9e18519c | /code/STLExporter.h | 37fc1dd49c1d88ad45b99ce18758af01ecd46923 | [
"BSD-3-Clause"
]
| permissive | spring/assimp | fb53b91228843f7677fe8ec18b61d7b5886a6fd3 | db29c9a20d0dfa9f98c8fd473824bba5a895ae9e | refs/heads/master | 2021-01-17T23:19:56.511185 | 2011-11-08T12:15:18 | 2011-11-08T12:15:18 | 2,017,841 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,758 | h | /*
Open Asset Import Library (ASSIMP)
----------------------------------------------------------------------
Copyright (c) 2006-2010, ASSIMP Development Team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the ASSIMP team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the ASSIMP Development Team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
*/
/** @file STLExporter.h
* Declares the exporter class to write a scene to a Stereolithography (STL) file
*/
#ifndef AI_STLEXPORTER_H_INC
#define AI_STLEXPORTER_H_INC
#include <sstream>
struct aiScene;
struct aiNode;
namespace Assimp
{
// ------------------------------------------------------------------------------------------------
/** Helper class to export a given scene to a STL file. */
// ------------------------------------------------------------------------------------------------
class STLExporter
{
public:
/// Constructor for a specific scene to export
STLExporter(const char* filename, const aiScene* pScene);
public:
/// public stringstreams to write all output into
std::ostringstream mOutput;
private:
void WriteMesh(const aiMesh* m);
private:
const std::string filename;
const aiScene* const pScene;
// this endl() doesn't flush() the stream
const std::string endl;
};
}
#endif
| [
"aramis_acg@67173fc5-114c-0410-ac8e-9d2fd5bffc1f"
]
| [
[
[
1,
84
]
]
]
|
03ab7bf305759095f42f46b97003c17b3b8acd06 | 971b000b9e6c4bf91d28f3723923a678520f5bcf | /fop_miniscribus.1.0.0/fop_lib/prefophandler.cpp | 76dc2a0579a653c87e4a6d567fda4f3c8bfaccd6 | []
| 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 | 26,813 | cpp | #include "prefophandler.h"
PageDB::PageDB( QObject * parent )
{
friendpanel = parent;
Pages.clear();
PageDimensionName *Pra = new PageDimensionName("CH-A4",FopInt("211mm"),FopInt("297mm"),QRectF(20,20,20,20),QColor(BASECOLOR),0);
Pra->display("211mm x 297mm");
PageDimensionName *Pra0 = new PageDimensionName("A4",FopInt("210mm"),FopInt("297mm"),QRectF(10,10,10,10),QColor(BASECOLOR),0);
Pra0->display("210mm x 297mm");
PageDimensionName *Pra1 = new PageDimensionName("A0",FopInt("841mm"),FopInt("1189mm"),QRectF(22,22,22,22),QColor(BASECOLOR),5);
Pra1->display("841mm x 1189mm");
PageDimensionName *Pra2 = new PageDimensionName("A1",FopInt("594mm"),FopInt("841mm"),QRectF(22,22,22,22),QColor(BASECOLOR),1);
Pra2->display("594mm x 297mm");
PageDimensionName *Pra3 = new PageDimensionName("B0",FopInt("1030mm"),FopInt("1456mm"),QRectF(22,22,22,22),QColor(BASECOLOR),14);
Pra3->display("1030mm x 1456mm");
PageDimensionName *Pra4 = new PageDimensionName("CD-Label",FopInt("128mm"),FopInt("128mm"),QRectF(22,22,22,22),QColor(BASECOLOR),0);
Pra4->display("128mm x 128mm");
PageDimensionName *Pra5 = new PageDimensionName("C5-Europe",FopInt("162mm"),FopInt("229mm"),QRectF(22,22,22,22),QColor(BASECOLOR),0);
Pra5->display("162mm x 229mm");
PageDimensionName *Pra6 = new PageDimensionName("PA4",FopInt("210mm"),FopInt("280mm"),QRectF(22,22,22,22),QColor(BASECOLOR),0);
Pra6->display("210mm x 280mm");
PageDimensionName *Pra7 = new PageDimensionName("C5-Horizzontal",FopInt("229mm"),FopInt("162mm"),QRectF(22,22,22,22),QColor(BASECOLOR),0);
Pra7->display("229mm x 162mm");
PageDimensionName *Pra8 = new PageDimensionName("C4-Horizzontal",FopInt("229mm"),FopInt("114mm"),QRectF(22,22,22,22),QColor(BASECOLOR),0);
Pra8->display("229mm x 114mm");
PageDimensionName *Pra10 = new PageDimensionName("C5-Vertical",FopInt("162mm"),FopInt("229mm"),QRectF(22,22,22,22),QColor(BASECOLOR),0);
Pra10->display("162mm x 229mm");
PageDimensionName *Pra11 = new PageDimensionName("C4-Vertical",FopInt("114mm"),FopInt("229mm"),QRectF(22,22,22,22),QColor(BASECOLOR),0);
Pra11->display("114mm x 229mm");
Pages.append(Pra);
Pages.append(Pra0);
Pages.append(Pra1);
Pages.append(Pra2);
Pages.append(Pra3);
Pages.append(Pra4);
Pages.append(Pra5);
Pages.append(Pra6);
Pages.append(Pra7);
Pages.append(Pra8);
Pages.append(Pra10);
Pages.append(Pra11);
emit newdata();
}
void PageDB::AppInsert( PageDimensionName *page )
{
Pages.append(page);
}
PageDimensionName * PageDB::page( int index )
{
return Pages.at(index);
}
PageDB::~PageDB()
{
Pages.clear();
}
Fop_Block::Fop_Block( int nr , QDomElement e , const QString tagname )
{
id = nr;
element = e;
QDomDocument doc;
QDomElement blox = doc.createElement(tagname);
QDomNamedNodeMap attlist = e.attributes();
for (int i=0; i<attlist.count(); i++){
QDomNode nod = attlist.item(i);
blox.setAttribute(nod.nodeName().toLower(),nod.nodeValue());
}
QDomNode child = e.firstChild();
while ( !child.isNull() ) {
if ( child.isElement() ) {
blox.appendChild(doc.importNode(child,true).toElement());
} else if (child.isText()) {
blox.appendChild(doc.createTextNode(child.toText().data()));
}
child = child.nextSibling();
}
doc.appendChild(blox);
streamxml = doc.toString(5);
}
Fop_Block::~Fop_Block()
{
element.clear();
}
PreFopHandler::PreFopHandler()
{
PromtToSaveImage.clear();
notexistFontMap.clear();
ErrorSumm = 0;
errorreport;
startdir = QDir::currentPath();
contare = 0;
}
void PreFopHandler::ImageBlockAppend( TypImageContainer tocaster )
{
/* image must save? */
QMapIterator<QString,QVariant> i(tocaster);
while (i.hasNext()) {
i.next();
contare++;
PromtToSaveImage.insert(i.key(),i.value());
}
}
QVariant PreFopHandler::ResourceOnSaveImage( const QString urlimage )
{
QVariant nullimage;
QMapIterator<QString,QVariant> i(PromtToSaveImage);
while (i.hasNext()) {
i.next();
if ( i.key() == urlimage ) {
return i.value();
}
}
return nullimage;
}
bool PreFopHandler::BuildSvgInlineonDom( const QString urlrefimage , QDomElement e , QDomDocument doc )
{
bool buildaction = false;
QByteArray imagestream = ResourceOnSaveImage(urlrefimage).toByteArray();
QString errorStr;
int errorLine, errorColumn, position;
QDomDocument img;
if (!img.setContent(imagestream,false, &errorStr, &errorLine, &errorColumn)) {
return false;
}
QDomElement root_extern = img.documentElement();
root_extern.setTagName("svg:svg");
QDomNamedNodeMap attlist = root_extern.attributes(); /* copy all attributes from other doc */
/////////////qDebug() << "### BuildSvgInlineonDom -> " << root_extern.tagName().toLower();
QDomNode newnode = root_extern.firstChild();
QDomNode treallsub = doc.importNode(newnode,true);
QDomElement svg = doc.createElement("svg:svg");
for (int i=0; i<attlist.count(); i++){
QDomNode nod = attlist.item(i);
svg.setAttribute(nod.nodeName().toLower(),nod.nodeValue());
}
svg.setAttribute ("xmlns","http://www.w3.org/2000/svg");
svg.setAttribute ("version","1.2");
svg.setAttribute ("baseProfile","tiny");
QDomNode child = root_extern.firstChild();
while ( !child.isNull() ) {
if ( child.isElement() ) {
svg.appendChild(doc.importNode(child,true).toElement());
}
child = child.nextSibling();
}
e.appendChild(svg);
return true;
}
bool PreFopHandler::SaveImageExterPath( const QString urlrefimage , const QString fulldirlocalfile )
{
bool savedaction = false;
QByteArray imagestream = ResourceOnSaveImage(urlrefimage).toByteArray();
if (imagestream.size() > 0) {
QFile f(fulldirlocalfile);
if ( f.open( QIODevice::WriteOnly ) )
{
f.write(imagestream);
f.close();
///////////////////qDebug() << "### save yes -> " << fulldirlocalfile;
return true;
}
}
return savedaction;
}
QTextBlockFormat PreFopHandler::TextBlockFormFromDom( const QDomElement e , QTextBlockFormat pf )
{
/* pf = parent format */
QDomNamedNodeMap attlist = e.attributes();
for (int i=0; i<attlist.count(); i++){
QDomNode nod = attlist.item(i);
if (nod.nodeName().toLower() == "space-after.optimum") {
pf.setBottomMargin(Unit(nod.nodeValue()));
}
if (nod.nodeName().toLower() == "break-before") {
pf.setPageBreakPolicy ( QTextFormat::PageBreak_AlwaysBefore );
}
if (nod.nodeName().toLower() == "break-after") {
pf.setPageBreakPolicy ( QTextFormat::PageBreak_AlwaysAfter );
}
if (nod.nodeName().toLower() == "line-height") {
}
if (nod.nodeName().toLower() == "background-color") {
pf.setBackground ( QBrush(QColor(nod.nodeValue()) ) );
}
if ( nod.nodeName().toLower().contains("-before") || nod.nodeName().toLower() =="margin-top" ) { /* top */
pf.setTopMargin(Unit(nod.nodeValue()));
}
if ( nod.nodeName().toLower().contains("-after") || nod.nodeName().toLower() =="margin-bottom" ) { /* bottom */
pf.setBottomMargin(Unit(nod.nodeValue()));
}
if ( nod.nodeName().toLower().contains("-start") || nod.nodeName().toLower() =="margin-right" ) { /* right */
pf.setRightMargin(Unit(nod.nodeValue()));
}
if ( nod.nodeName().toLower().contains("-end") || nod.nodeName().toLower() =="margin-left" ) { /* left */
pf.setLeftMargin(Unit(nod.nodeValue()));
}
if ( nod.nodeName().toLower().contains("start-indent") ) { /* indent */
pf.setIndent(Unit(nod.nodeValue()) / 7);
}
if (nod.nodeName().toLower() == "text-align") {
if (nod.nodeValue().toLower() == "center" ) {
pf.setAlignment( Qt::AlignCenter );
} else if (nod.nodeValue().toLower() == "left" || nod.nodeValue().toLower() == "start" || nod.nodeValue().toLower() == "inside" ) {
pf.setAlignment( Qt::AlignLeft );
} else if (nod.nodeValue().toLower() == "right" || nod.nodeValue().toLower() == "end" ) {
pf.setAlignment( Qt::AlignRight );
} else if (nod.nodeValue().toLower() == "justify") {
pf.setAlignment( Qt::AlignJustify );
} else if (nod.nodeValue().toLower() == "inherit") {
/* align same as parent before */
pf.setAlignment( Qt::AlignAbsolute );
}
}
}
return pf;
}
QTextCharFormat PreFopHandler::GlobalCharFormat( const QDomElement e , QTextCharFormat f )
{
QDomNamedNodeMap attlist = e.attributes();
QStringList option;
option.clear();
int fontstrech = e.attribute ("font-stretch",QString("0")).toInt();
QString idref="id-NOTSET"; /* id identificativ if having? */
for (int i=0; i<attlist.count(); i++){
QDomNode nod = attlist.item(i);
if (_PARSE_DEBUG_FOP_ == 1) {
option.append(nod.nodeName().toLower()+"="+nod.nodeValue()+"\n");
}
const QString valore = nod.nodeValue().toLower();
if (nod.nodeName().toLower() == "background-color") {
f.setBackground (QBrush(QColor(nod.nodeValue())) );
}
if (nod.nodeName().toLower() == "color") {
f.setForeground(QBrush(QColor(nod.nodeValue())));
}
if (nod.nodeName().toLower() == "id") {
idref = nod.nodeValue();
}
if (nod.nodeName().toLower() == "font-family") {
QFont userfont( nod.nodeValue() );
if (userfont.exactMatch()) {
if (fontstrech !=0) {
userfont.setStretch ( fontstrech );
}
f.setFont(userfont);
} else {
notexistFontMap.insert(nod.nodeValue(),QApplication::font()); /* prepare replace font item ? */
f.setFont(QApplication::font());
}
}
if (nod.nodeName().toLower() == "font-size") {
f.setFontPointSize(Unit(nod.nodeValue()));
}
if (nod.nodeName().toLower() == "external-destination" || nod.nodeName().toLower() == "internal-destination") {
f.setAnchorHref(nod.nodeValue());
f.setAnchor(true);
f.setForeground ( QBrush ( QColor ("#ff0000") ) ); /* red link */
}
////////if (nod.nodeName().toLower() == "font-style" or nod.nodeName().toLower() == "font-weight") {
if (valore.contains("bold")) {
f.setFontWeight(QFont::Bold);
}
if (valore.contains("italic")) {
f.setFontItalic(true);
}
if (valore.contains("underline")) {
f.setUnderlineStyle ( QTextCharFormat::SingleUnderline );
}
if (valore.contains("oblique")) {
f.setFontItalic(true);
}
if (valore.contains("overline")) {
f.setFontOverline(true);
}
////////}
}
return f;
}
QTextCharFormat PreFopHandler::NewMixedBlockFormat( const QDomElement e )
{
QDomNamedNodeMap attlist = e.attributes();
QTextCharFormat pf;
pf.setFontFixedPitch(false);
for (int i=0; i<attlist.count(); i++){
QDomNode nod = attlist.item(i);
if (nod.nodeName().toLower() == "background-color") {
pf.setBackground (QBrush(QColor(nod.nodeValue())) );
}
if (nod.nodeName().toLower() == "color") {
pf.setForeground(QBrush(QColor(nod.nodeValue())));
}
}
return pf;
}
qreal PreFopHandler::Unit( const QString datain )
{
QString ctmp = datain;
const QString data = ctmp.replace(" ","").trimmed();
//////////qDebug() << "### request unit data->" << datain << " size->" << datain.size();
#define MM_TO_POINT(mm) ((mm)*2.83465058)
#define CM_TO_POINT(cm) ((cm)*28.3465058)
#define DM_TO_POINT(dm) ((dm)*283.465058)
#define INCH_TO_POINT(inch) ((inch)*72.0)
#define PI_TO_POINT(pi) ((pi)*12)
#define DD_TO_POINT(dd) ((dd)*154.08124)
#define CC_TO_POINT(cc) ((cc)*12.840103)
qreal points = 0;
if (data.size() < 1) {
return points;
}
if (datain == "0") {
return points;
}
if ( data.endsWith( "pt" ) || data.endsWith( "px" ) ) {
points = data.left( data.length() - 2 ).toDouble();
} else if ( data.endsWith( "cm" ) ) {
double value = data.left( data.length() - 2 ).toDouble();
points = CM_TO_POINT( value );
} else if ( data.endsWith( "em" ) ) {
points = data.left( data.length() - 2 ).toDouble();
} else if ( data.endsWith( "mm" ) ) {
double value = data.left( data.length() - 2 ).toDouble();
points = MM_TO_POINT( value );
} else if ( data.endsWith( "dm" ) ) {
double value = data.left( data.length() - 2 ).toDouble();
points = DM_TO_POINT( value );
} else if ( data.endsWith( "in" ) ) {
double value = data.left( data.length() - 2 ).toDouble();
points = INCH_TO_POINT( value );
} else if ( data.endsWith( "inch" ) ) {
double value = data.left( data.length() - 4 ).toDouble();
points = INCH_TO_POINT( value );
} else if ( data.endsWith( "pi" ) ) {
double value = data.left( data.length() - 4 ).toDouble();
points = PI_TO_POINT( value );
} else if ( data.endsWith( "dd" ) ) {
double value = data.left( data.length() - 4 ).toDouble();
points = DD_TO_POINT( value );
} else if ( data.endsWith( "cc" ) ) {
double value = data.left( data.length() - 4 ).toDouble();
points = CC_TO_POINT( value );
} else {
points = 0;
ErrorSumm++;
ErnoMap.insert(ErrorSumm,tr("Fop_Handler::Unit / Unknown Unit \"%1\" ").arg(datain));
}
return points;
}
QTextBlockFormat PreFopHandler::PaddingToNext( qreal paddingmargin , QTextBlockFormat rootformats )
{
rootformats.setBottomMargin(paddingmargin);
rootformats.setTopMargin(paddingmargin);
rootformats.setRightMargin(paddingmargin);
rootformats.setLeftMargin(paddingmargin);
return rootformats;
}
/*
if (nod.nodeName().toLower() == "external-destination" || nod.nodeName().toLower() == "internal-destination") {
f.setAnchorHref(nod.nodeValue());
f.setAnchor(true);
f.setForeground ( QBrush ( QColor ("#ff0000") ) );
}
*/
void PreFopHandler::PaintCharFormat( QDomElement e , QTextCharFormat bf )
{
if (bf.foreground().color().name().size() > 0 ) {
e.setAttribute ("color",bf.foreground().color().name());
}
QFont userfont = bf.font();
int stre = userfont.stretch();
e.setAttribute ("font-family",userfont.family());
if (stre =!100) {
e.setAttribute ("font-stretch",stre);
}
e.setAttribute ("font-size",QString("%1pt").arg(userfont.pointSize()));
///////////qDebug() << "### userfont.bold() " << userfont.bold();
QStringList fontvario;
fontvario.clear();
////////////qDebug() << "### bf.fontWeight() " << bf.fontWeight();
//////////qDebug() << "### bf.fontUnderline() " << bf.fontUnderline();
/////////////qDebug() << "### bf.fontItalic() " << bf.fontItalic();
if (bf.fontWeight() > 51) {
fontvario.append("bold");
}
if (bf.fontItalic()) {
fontvario.append("italic");
}
if (bf.fontStrikeOut() ) {
fontvario.append("oblique");
}
if (bf.fontUnderline() ) {
fontvario.append("underline");
}
///////////qDebug() << "### fontvario.size() " << fontvario.size();
if (fontvario.size() > 0) {
e.setAttribute ("font-style",fontvario.join(" "));
}
}
void PreFopHandler::PaintFopBlockFormat( QDomElement e , QTextBlockFormat bf )
{
if ( bf.alignment() == Qt::AlignLeft) {
e.setAttribute ("text-align","left");
}
if ( bf.alignment() == Qt::AlignRight) {
e.setAttribute ("text-align","right");
}
if ( bf.alignment() == Qt::AlignHCenter) {
e.setAttribute ("text-align","center");
}
if ( bf.alignment() == Qt::AlignJustify) {
e.setAttribute ("text-align","justify");
}
if ( bf.alignment() == Qt::AlignTop) {
e.setAttribute ("text-align","left");
}
if ( bf.alignment() == Qt::AlignBottom) {
e.setAttribute ("text-align","left");
}
if ( bf.alignment() == Qt::AlignVCenter) {
e.setAttribute ("text-align","center");
}
if ( bf.alignment() == Qt::AlignCenter) {
e.setAttribute ("text-align","center");
}
if (bf.topMargin() !=0) {
e.setAttribute ("margin-top",QString("%1pt").arg(bf.topMargin()));
}
if (bf.bottomMargin() !=0) {
e.setAttribute ("margin-bottom",QString("%1pt").arg(bf.bottomMargin()));
}
if (bf.rightMargin() !=0) {
e.setAttribute ("margin-right",QString("%1pt").arg(bf.rightMargin()));
}
if (bf.leftMargin() !=0) {
e.setAttribute ("margin-left",QString("%1pt").arg(bf.leftMargin()));
}
if (bf.foreground().color().name().size() > 0 ) {
e.setAttribute ("color",bf.foreground().color().name());
}
if (bf.background().color().name() !="#000000" ) {
e.setAttribute ("background-color",bf.background().color().name());
}
}
Qt::PenStyle PreFopHandler::StyleBorder( const QDomElement e )
{
Qt::PenStyle smaks = Qt::SolidLine;
const QString borderpaint = e.attribute ("border-style","solid").toLower();
if (borderpaint.size() < 0) {
return smaks;
} else {
/* avaiable penn style from border .... */
if (borderpaint == "solid") {
return Qt::SolidLine;
}
if (borderpaint == "dotted") {
return Qt::DotLine;
}
if (borderpaint == "dashed") {
return Qt::DashDotLine;
}
}
return smaks;
}
qreal PreFopHandler::Get_Cell_Width( QTextTableFormat TableFormat , int position )
{
qreal notfound = 0;
QVector<QTextLength> constraints = TableFormat.columnWidthConstraints();
for (int i = 0; i < constraints.size(); ++i) {
if (i == position) {
QTextLength langecell = constraints.value(i);
if (langecell.type() == QTextLength::FixedLength) {
return langecell.rawValue();
}
}
}
return notfound;
}
qreal PreFopHandler::TakeOneBorder( const QDomElement e )
{
qreal Boleft = Unit(e.attribute ("border-start-width",QString("0")));
qreal Botop = Unit(e.attribute ("border-before-width",QString("0")));
qreal Bobotto = Unit(e.attribute ("border-bottom-width",QString("0")));
qreal Bobright = Unit(e.attribute ("border-end-width",QString("0")));
qreal first = qMax (Boleft,Bobright);
qreal second = qMax (Bobotto,Botop);
qreal nordsud = qMax (first,second);
qreal single = Unit(e.attribute ("border-width",QString("0")));
return qMax (single,nordsud);
}
qreal PreFopHandler::TakeOnePadding( const QDomElement e )
{
qreal Boleft = Unit(e.attribute ("padding-top",QString("0")));
qreal Botop = Unit(e.attribute ("padding-bottom",QString("0")));
qreal Bobotto = Unit(e.attribute ("padding-left",QString("0")));
qreal Bobright = Unit(e.attribute ("padding-right",QString("0")));
qreal Bolefta = Unit(e.attribute ("padding-start",QString("0")));
qreal Botopa = Unit(e.attribute ("padding-end",QString("0")));
qreal Bobottoa = Unit(e.attribute ("padding-after",QString("0")));
qreal Bobrighta = Unit(e.attribute ("padding-before",QString("0")));
qreal first = qMax (Boleft,Bobright);
qreal second = qMax (Bobotto,Botop);
qreal firsta = qMax (Bolefta,Bobrighta);
qreal seconda = qMax (Bobottoa,Botopa);
qreal Fnordsud = qMax (first,second);
qreal Enordsud = qMax (firsta,seconda);
return qMax (Fnordsud,Enordsud);
}
/* Paint special border on cell and border hack border html td cell from fop !!!! */
QPixmap PreFopHandler::PaintTableCellPixmap( QRectF r , QColor bg , QColor ma , qreal borderDicks , Qt::PenStyle styls )
{
/* QRectF ( qreal x, qreal y, qreal width, qreal height ) */
if (bg == ma) {
bg.setAlphaF ( 0 );
ma.setAlphaF ( 0 );
}
QPixmap m_tile = QPixmap(r.width() * 4 ,r.height() * 4);
m_tile.fill(bg);
QPainter pt(&m_tile);
pt.setBrush(QBrush(bg));
pt.setPen(QPen(QBrush(ma),borderDicks,styls,Qt::RoundCap,Qt::RoundJoin));
if (r.y() !=0) {
pt.drawRect(QRectF((borderDicks / 2) + r.y(),borderDicks / 2,r.width() - (borderDicks / 2),r.height() - (borderDicks / 2)));
} else {
pt.drawRect(QRectF(borderDicks / 2,borderDicks / 2,r.width() - (borderDicks / 2),r.height() - (borderDicks / 2)));
}
qreal internalborder = r.x();
if (internalborder !=0) {
QColor background = QColor(bg);
background.setAlphaF ( 1 );
pt.setBrush(QBrush(background));
pt.setPen(QPen(QBrush(ma),internalborder,styls,Qt::SquareCap,Qt::BevelJoin));
pt.drawRect(QRectF(internalborder,internalborder,r.width() - internalborder ,r.height() - internalborder ));
}
pt.end();
return m_tile;
}
void PreFopHandler::ReportError()
{
errorreport++;
}
PreFopHandler::FOPTAGSINT PreFopHandler::FoTag( const QDomElement e )
{
const QString fotag = e.tagName().toLower();
if (fotag.size() < 1) {
return TAG_NOT_KNOW;
}
/////qDebug() << "### FoTag " << fotag;
if (fotag == "fo:root") {
return FIRST_LAST_TAG;
} else if (fotag == "fo:simple-page-master") {
return PAGE_SETUP;
} else if (fotag == "fo:block") {
return BLOCK_TAG;
} else if (fotag == "fo:table") {
return TABLE_TAG;
} else if (fotag == "table-footer") {
return TABLE_FOOTER;
} else if (fotag == "table-header") {
return TABLE_HEADER;
} else if (fotag == "fo:table-body") {
return TABLE_BODY;
} else if (fotag == "fo:table-column") {
return TABLE_COL;
} else if (fotag == "fo:table-row") {
return TABLE_ROW;
} else if (fotag == "fo:table-cell") {
return TABLE_CELL;
} else if (fotag == "fo:block-container") {
return BLOCK_CONTAINER;
} else if (fotag == "fo:inline") {
return INLINE_STYLE;
} else if (fotag == "fo:character") {
return FOCHAR;
} else if (fotag == "fo:basic-link") {
return LINK_DOC;
} else if (fotag == "fo:external-graphic") {
return IMAGE_SRC;
} else if (fotag == "fo:instream-foreign-object") {
return IMAGE_INLINE;
} else if (fotag == "fo:list-block") {
return LIST_BLOCK;
} else if (fotag == "fo:list-item") {
return LIST_ITEM;
} else if (fotag == "fo:list-item-body") {
return LIST_BODY;
} else if (fotag == "fo:list-item-label") {
return LIST_LABEL;
} else {
ErrorSumm++;
ErnoMap.insert(ErrorSumm,tr("Fop_Handler::FoTag / Unregister Tagname %1.").arg(e.tagName().toLower()));
return TAG_NOT_KNOW;
}
}
/* set all margin to zero qt4 send 12 top 12 bottom by default */
QTextBlockFormat PreFopHandler::DefaultMargin( QTextBlockFormat rootformats )
{
rootformats.setBottomMargin(0);
rootformats.setTopMargin(0);
rootformats.setRightMargin(0);
rootformats.setLeftMargin(0);
return rootformats;
}
/* set all margin to zero qt4 send 12 top 12 bottom by default */
void PreFopHandler::TableBlockMargin( QDomElement appender , const QString name )
{
appender.setAttribute ("margin-top",0);
appender.setAttribute ("margin-bottom",0);
appender.setAttribute ("margin-left",0);
appender.setAttribute ("master-right",0);
appender.setAttribute ("itype",name);
}
| [
"ppkciz@9af58faf-7e3e-0410-b956-55d145112073"
]
| [
[
[
1,
806
]
]
]
|
4df56e08d141fd7894512cff15d97f7f124b54bc | 519a3884c80f7a3926880b28df5755935ec7aa57 | /DicomShell/DicomThumbnail.cpp | 4936cb152e27c10e0c628e6ab0e8633b034fbc3f | []
| no_license | Jeffrey2008/dicomshell | 71ef9844ed83c38c2529a246b6efffdd5645ed92 | 14c98fcd9238428e1541e50b7d0a67878cf8add4 | refs/heads/master | 2020-10-01T17:39:11.786479 | 2009-09-02T17:49:27 | 2009-09-02T17:49:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,090 | cpp | #include "StdAfx.h"
#include "DicomThumbnail.h"
#include "dcmtk/dcmimage/diregist.h" /* required to support color images */
DicomTagList DicomThumbnail::s_tags(TEXT("imagetext"));
HBITMAP createHbitmap(SIZE const& size)
{
const int bitCount = 24;
BITMAPINFO bmi;
ZeroMemory(&bmi.bmiHeader,sizeof(BITMAPINFOHEADER));
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth = size.cx;
bmi.bmiHeader.biHeight = size.cy;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = bitCount;
bmi.bmiHeader.biCompression = BI_RGB;
bmi.bmiHeader.biSizeImage = ((((bmi.bmiHeader.biWidth * bmi.bmiHeader.biBitCount) + 31) & ~31) >> 3) * bmi.bmiHeader.biHeight;
bmi.bmiHeader.biXPelsPerMeter = 0;
bmi.bmiHeader.biYPelsPerMeter = 0;
bmi.bmiHeader.biClrUsed = 0;
bmi.bmiHeader.biClrImportant;
void* data = 0;
HBITMAP bitmap = CreateDIBSection(0, &bmi, DIB_RGB_COLORS, &data, NULL, 0);
return bitmap;
}
HBITMAP asHbitmap(DicomImage& dicomImage)
{
const int bitCount = 24;
BITMAPINFO bmi;
ZeroMemory(&bmi.bmiHeader,sizeof(BITMAPINFOHEADER));
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth = dicomImage.getWidth();
bmi.bmiHeader.biHeight = dicomImage.getHeight();
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = bitCount;
bmi.bmiHeader.biCompression = BI_RGB;
bmi.bmiHeader.biSizeImage = ((((bmi.bmiHeader.biWidth * bmi.bmiHeader.biBitCount) + 31) & ~31) >> 3) * bmi.bmiHeader.biHeight;
bmi.bmiHeader.biXPelsPerMeter = 0;
bmi.bmiHeader.biYPelsPerMeter = 0;
bmi.bmiHeader.biClrUsed = 0;
bmi.bmiHeader.biClrImportant;
void* data = 0;
HBITMAP bitmap = CreateDIBSection(0, &bmi, DIB_RGB_COLORS, &data, NULL, 0);
dicomImage.createWindowsDIB(data, bmi.bmiHeader.biSizeImage, 0, bitCount, 1, 1);
return bitmap;
}
bool extractIconImageSequence(DcmDataset* dataset, HBITMAP* thumbnail, SIZE const& size)
{
DcmSequenceOfItems* iconImageSequence;
if (!dataset->findAndGetSequence(DCM_IconImageSequence, iconImageSequence).good())
{
return false;
}
DcmItem* icon = iconImageSequence->getItem(0);
DicomImage image(icon, EXS_Unknown);
bool scale = false;
if (scale)
{
DicomImage* tn = image.createScaledImage((unsigned long)size.cx, (unsigned long)size.cy, 2);
*thumbnail = asHbitmap(*tn);
delete tn;
}
else
{
*thumbnail = asHbitmap(image);
}
return true;
}
void DicomThumbnail::Create(LPWSTR path, HBITMAP* thumbnail, SIZE const& size)
{
USES_CONVERSION;
DcmFileFormat file;
OFCondition s = file.loadFile(W2A(path));
if (!s.good()) throw s;
Create(file, thumbnail, size);
}
void DicomThumbnail::Create(DcmFileFormat& file, HBITMAP* thumbnail, SIZE const& size)
{
USES_CONVERSION;
if (extractIconImageSequence(file.getDataset(), thumbnail, size))
{
}
else
{
E_TransferSyntax xfer = file.getDataset()->getOriginalXfer();
unsigned long opt_compatibilityMode = CIF_MayDetachPixelData | CIF_TakeOverExternalDataset;
DicomImage sourceImage(file.getDataset(), xfer);
EI_Status status = sourceImage.getStatus();
if (status == EIS_Normal)
{
sourceImage.setWindow(0);
DicomImage* tn = sourceImage.createScaledImage((unsigned long)size.cx, (unsigned long)size.cy, 2);
if (!tn) throw EIS_InvalidDocument;
*thumbnail = asHbitmap(*tn);
delete tn;
}
else
{
CreateTextThumbnail(file, thumbnail, size);
}
return;
}
}
bool appendValue(CComBSTR& out, DcmDataset& dataset, DcmTagKey const& tag)
{
USES_CONVERSION;
OFString value;
if (dataset.findAndGetOFString(tag, value).good())
{
out.Append(A2W(value.c_str()));
return true;
}
else
{
return false;
}
}
void DicomThumbnail::CreateTextThumbnail(DcmFileFormat& file, HBITMAP* thumbnail, SIZE const& size)
{
HBITMAP bm = createHbitmap(size);
HDC dc = CreateCompatibleDC(::GetDC(0));
//create a new bitmap and select it in the memory dc
HGDIOBJ obj = SelectObject(dc,bm);
DcmDataset& dataset = * file.getDataset();
CComBSTR info;
/*
DicomTagList::TagCollection const & tags = s_tags.getTags();
for (size_t i=0; i < tags.size(); ++i)
{
if (appendValue(info, dataset, tags[i]))
{
info.Append(TEXT("\n"));
}
}
*/
info.Append(TEXT("DICOM "));
appendValue(info, dataset, DCM_Modality);
info.Append(TEXT("\n"));
appendValue(info, dataset, DCM_PatientsName);
info.Append(TEXT("\n"));
appendValue(info, dataset, DCM_PatientsSex);
info.Append(TEXT("\n"));
appendValue(info, dataset, DCM_PatientsBirthDate);
RECT r;
r.left = 0;
r.top = 0;
r.right = r.left + size.cy;
r.bottom = r.top + size.cy;
::SetTextColor(dc, RGB(0xff, 0xff, 0xff));
::SetBkColor(dc, RGB(0x00, 0x00, 0x00));
//choose the font
HGDIOBJ hfnt, hOldFont;
hfnt = GetStockObject(ANSI_VAR_FONT);
hOldFont = SelectObject(dc, hfnt);
DrawText(dc, (WCHAR*)(BSTR)info, -1, &r, DT_WORDBREAK);
//final cleanup
SelectObject(dc, hOldFont);
SelectObject(dc,obj);
DeleteDC(dc);
*thumbnail = bm;
}
| [
"andreas.grimme@715416e8-819e-11dd-8f04-175a6ebbc832"
]
| [
[
[
1,
186
]
]
]
|
2875f95a0f68e673b75a95b4cba06184897959b5 | e98d99816ad42028e5988ade802ffdf9846da166 | /Mediotic/OBJLoader/KdTree_pfVec.cpp | 366c0fa49366607f9633bd0273069c6e76598b62 | []
| no_license | OpenEngineDK/extensions-MediPhysics | 5e9b3a0d178db8e9a42ce7724ee35fdfee70ec64 | 94fdd25f90608ad3db6b3c6a30db1c1e4c490987 | refs/heads/master | 2016-09-14T04:26:29.607457 | 2008-10-14T12:14:53 | 2008-10-14T12:14:53 | 58,073,189 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,689 | cpp | #include "kdTree_pfVec.h"
//#ifdef _WIN32
//#define alloca malloc
//#endif
#include <list>
#include <iostream>
using namespace std;
KdTree_pfVec::KdTree_pfVec(const int maxPositions)
{
stored_positions = half_stored_positions = 0;
prev_scale = 1;
max_positions = maxPositions;
positions = (Position*)malloc( sizeof( Position ) * (max_positions + 1 ) );
if (positions == NULL)
{
printf("Out of memort initializing KdTree_pfVec\n");
exit(-1);
}
bbox_min[0] = bbox_min[1] = bbox_min[2] = 1e8f;
bbox_max[0] = bbox_max[1] = bbox_max[2] = -1e8f;
}
KdTree_pfVec :: ~KdTree_pfVec()
{
free(positions);
}
bool KdTree_pfVec::exists(Vector3 *n)
{
list<Vector3*>* l = find(n,0.0000001,1);
if (l->begin()==l->end())
{
delete(l);
return false;
}
else
{
delete(l);
return true;
}
}
list<Vector3*>* KdTree_pfVec::find(Vector3 *n,float max_dist,int npositions)
{
NearestPositions np;
np.dist2 = (float*)alloca( sizeof(float)*(npositions+1) );
np.index = (const Position**)alloca( sizeof(Position*)*(npositions+1) );
np.pos[0] = n->e[0];
np.pos[1] = n->e[1];
np.pos[2] = n->e[2];
np.max = npositions;
np.found = 0;
np.got_heap = 0;
np.dist2[0] = max_dist*max_dist;
locate_positions( &np,1);
list<Vector3*> * returnList = new list<Vector3*>;
for(int i = 1; i <= np.found; i++)
{
returnList->push_back(np.index[i]->node);
}
return returnList;
}
void KdTree_pfVec :: locate_positions(NearestPositions *const np, const int index) const
{
const Position *p = &positions[index];
float dist1;
if( index < half_stored_positions)
{
dist1 = np->pos[p->plane] - p->pos[p->plane];
if (dist1>0.0)
{
locate_positions(np,2*index+1);
if (dist1*dist1 < np->dist2[0] )
locate_positions(np, 2*index);
}
else
{
locate_positions(np, 2*index);
if (dist1*dist1 < np->dist2[0] )
locate_positions(np, 2*index+1);
}
}
dist1 = p->pos[0] - np->pos[0];
float dist2 = dist1*dist1;
dist1 = p->pos[1] - np->pos[1];
dist2 += dist1*dist1;
dist1 = p->pos[2] - np->pos[2];
dist2 += dist1*dist1;
if (dist2 < np->dist2[0] )
{
if ( np->found < np->max )
{
np->found++;
np->dist2[np->found] = dist2;
np->index[np->found] = p;
}
else
{
int j,parent;
if (np->got_heap==0)
{
float dst2;
const Position *phot;
int half_found = np->found>>1;
for(int k=half_found; k >= 1; k--)
{
parent = k;
phot = np->index[k];
dst2 = np->dist2[k];
while ( parent <= half_found)
{
j = parent+parent;
if (j <np->found && np->dist2[j]<np->dist2[j+1])
j++;
if (dst2 >= np->dist2[j])
break;
np->dist2[parent] = np->dist2[j];
np->index[parent] = np->index[j];
parent = j;
}
np->dist2[parent] =dst2;
np->index[parent] = phot;
}
np->got_heap = 1;
}
parent = 1;
j = 2;
while ( j <= np->found )
{
if (j < np->found && np->dist2[j] < np->dist2[j+1] )
j++;
if (dist2 > np->dist2[j] )
break;
np->dist2[parent] = np->dist2[j];
np->index[parent] = np->index[j];
parent = j;
j += j;
}
np->index[parent] = p;
np->dist2[parent] = dist2;
np->dist2[0] = np->dist2[1];
}
}
}
void KdTree_pfVec :: store(Vector3 *n)
{
if (stored_positions>max_positions)
{
cerr << "ERROR: Not enough room in the KdTree_pfVec" << endl;
return;
}
stored_positions++;
Position *const node = &positions[stored_positions];
float pos[3];
pos[0]=n->e[0];
pos[1]=n->e[1];
pos[2]=n->e[2];
node->node = n;
for(int i = 0; i<3; i++)
{
node->pos[i] = pos[i];
if (node->pos[i] < bbox_min[i])
bbox_min[i] = node->pos[i];
if (node->pos[i] > bbox_max[i])
bbox_max[i] = node->pos[i];
}
}
void KdTree_pfVec :: balance()
{
if (stored_positions>1)
{
Position **pa1 = (Position**)malloc(sizeof(Position*)*(stored_positions+1));
Position **pa2 = (Position**)malloc(sizeof(Position*)*(stored_positions+1));
for (int i = 0; i <= stored_positions; i++)
pa2[i] = &positions[i];
balance_segment(pa1,pa2,1,1,stored_positions);
free(pa2);
int d, j=1, foo=1;
Position foo_position = positions[j];
for(int i =1; i <= stored_positions; i++)
{
d = pa1[j]-positions;
pa1[j] = NULL;
if (d != foo)
positions[j] = positions[d];
else
{
positions[j] = foo_position;
if (i<stored_positions)
{
for (; foo<=stored_positions; foo++)
if (pa1[foo] != NULL)
break;
foo_position = positions[foo];
j = foo;
}
continue;
}
j = d;
}
free(pa1);
}
half_stored_positions = stored_positions/2-1;
}
#define swap(ph,a,b) { Position *ph2=ph[a]; ph[a]=ph[b]; ph[b] = ph2; }
void KdTree_pfVec :: median_split(Position **p, const int start, const int end, const int median, const int axis)
{
int left = start;
int right = end;
while (right > left)
{
const float v = p[right]->pos[axis];
int i = left-1;
int j = right;
for (;;)
{
while (p[++i]->pos[axis] < v) ;
while (p[--j]->pos[axis] > v && j > left) ;
if ( i >= j)
break;
swap(p,i,j);
}
swap(p,i,right);
if (i >= median)
right = i-1;
if ( i <= median)
left = i+1;
}
}
void KdTree_pfVec :: balance_segment(Position **pbal, Position **porg, const int index, const int start, const int end)
{
int median = 1;
while ((4*median) <= (end-start+1))
median += median;
if ((3*median) <= (end-start+1))
{
median += median;
median += start-1;
}
else
median = end-median+1;
int axis = 2;
if ((bbox_max[0]-bbox_min[0])>(bbox_max[1]-bbox_min[1]) &&
(bbox_max[0]-bbox_min[0])>(bbox_max[2]-bbox_min[2]))
axis = 0;
else if ((bbox_max[1]-bbox_min[1])>(bbox_max[2]-bbox_min[2]))
axis = 1;
median_split( porg, start, end, median, axis);
pbal[index] = porg[median];
pbal[index]->plane = axis;
if (median > start)
{
if (start < median-1)
{
const float tmp = bbox_max[axis];
bbox_max[axis] = pbal[index]->pos[axis];
balance_segment(pbal,porg,2*index,start,median-1);
bbox_max[axis] = tmp;
}
else
{
pbal[2*index] = porg[start];
}
}
if (median < end)
{
if (median+1 <end)
{
const float tmp = bbox_min[axis];
bbox_min[axis] = pbal[index]->pos[axis];
balance_segment(pbal,porg,2*index+1,median+1,end);
bbox_min[axis] = tmp;
}
else
{
pbal[2*index+1] = porg[end];
}
}
}
| [
"[email protected]"
]
| [
[
[
1,
332
]
]
]
|
90b5988210e424e381932780cb2c9c3897bd2462 | d6eba554d0c3db3b2252ad34ffce74669fa49c58 | /Source/EventSystem/gameEvent.h | 47214f22509a31f5269b9ab4559a3fb82b0aba04 | []
| no_license | nbucciarelli/Polarity-Shift | e7246af9b8c3eb4aa0e6aaa41b17f0914f9d0b10 | 8b9c982f2938d7d1e5bd1eb8de0bdf10505ed017 | refs/heads/master | 2016-09-11T00:24:32.906933 | 2008-09-26T18:01:01 | 2008-09-26T18:01:01 | 3,408,115 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,221 | h | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// File: "gameEvent.h"
// Author: Scott Smallback (SS)
// Purpose: event class for the game
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
typedef unsigned int EvID;
class gameEvent
{
protected:
EvID id;
void* data;
public:
gameEvent(EvID eventID, void* dat = 0)
{
id = eventID;
data = dat;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: "getEventID"
// Last Modified: August 25, 2008
// Purpose: returns the event ID
//////////////////////////////////////////////////////////////////////////////////////////////////////
EvID getEventID(void) { return id; }
//////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: "getData"
// Last Modified: August 25, 2008
// Purpose: returns data
//////////////////////////////////////////////////////////////////////////////////////////////////////
void* getData(void) { return data; }
}; | [
"[email protected]"
]
| [
[
[
1,
36
]
]
]
|
dd445e8138fe03c8b0698b96d462b35f1f50018d | 2f77d5232a073a28266f5a5aa614160acba05ce6 | /01.DevelopLibrary/04.SmsCode/InfoCenterOfSmartPhone/stdafx.cpp | bf9f7b5a6e2769e77dfb8ac90984c0ba7fe574fb | []
| no_license | radtek/mobilelzz | 87f2d0b53f7fd414e62c8b2d960e87ae359c81b4 | 402276f7c225dd0b0fae825013b29d0244114e7d | refs/heads/master | 2020-12-24T21:21:30.860184 | 2011-03-26T02:19:47 | 2011-03-26T02:19:47 | 58,142,323 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 426 | cpp | // stdafx.cpp : 只包括标准包含文件的源文件
// InfoCenterOfSmartPhone.pch 将作为预编译头
// stdafx.obj 将包含预编译类型信息
#include "stdafx.h"
//BOOL g_bH = FALSE;
CRecieversDynamicArray g_ReciversList;
BOOL g_bContactShow = FALSE;
BOOL g_bIsTrial = FALSE;
CLSID g_clBackupSipID = {0};
CLSID g_clMeizuSipID = {0x7da6edd4,0x0fbb,0x4ed0,{0xba,0xb8,0x68,0x93,0xf4,0x5f,0xf9,0xb5}};
| [
"lidan8908589@8983de3c-2b35-11df-be6c-f52728ce0ce6"
]
| [
[
[
1,
12
]
]
]
|
e4c14831742da06c15ed5e462df3e6adbef46481 | 3761dcce2ce81abcbe6d421d8729af568d158209 | /include/cybergarage/http/HTTPRequest.h | b3aaeefda406d313e7920b8c0103bcb826f8ee37 | [
"BSD-3-Clause"
]
| permissive | claymeng/CyberLink4CC | af424e7ca8529b62e049db71733be91df94bf4e7 | a1a830b7f4caaeafd5c2db44ad78fbb5b9f304b2 | refs/heads/master | 2021-01-17T07:51:48.231737 | 2011-04-08T15:10:49 | 2011-04-08T15:10:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,780 | h | /******************************************************************
*
* CyberHTTP for C++
*
* Copyright (C) Satoshi Konno 2002-2003
*
* File: HTTPRequest.h
*
* Revision;
*
* 03/27/03
* - first revision
*
******************************************************************/
#ifndef _CHTTP_HTTPREQUEST_H_
#define _CHTTP_HTTPREQUEST_H_
#include <cybergarage/http/HTML.h>
#include <cybergarage/http/HTTPPacket.h>
#include <cybergarage/http/HTTPSocket.h>
#include <cybergarage/http/HTTPResponse.h>
#include <cybergarage/http/ParameterList.h>
#include <string>
namespace CyberHTTP {
class HTTPRequest : public HTTPPacket
{
std::string method;
std::string requestHost;
std::string version;
std::string uri;
HTTPSocket *httpSocket;
int requestPort;
CyberNet::Socket *postSock;
HTTPResponse httpRes;
public:
////////////////////////////////////////////////
// Constructor
////////////////////////////////////////////////
HTTPRequest();
HTTPRequest(HTTPSocket *httpSock);
////////////////////////////////////////////////
// Method
////////////////////////////////////////////////
public:
void setMethod(const char *value)
{
method = value;
}
const char *getMethod(std::string &methodBuf)
{
if (0 < method.length()) {
methodBuf = method;
return methodBuf.c_str();
}
return getFirstLineToken(0, methodBuf);
}
bool isMethod(const char *value);
bool isGetRequest()
{
return isMethod(HTTP::GET);
}
bool isPostRequest()
{
return isMethod(HTTP::POST);
}
bool isHeadRequest()
{
return isMethod(HTTP::HEAD);
}
bool isSubscribeRequest()
{
return isMethod(HTTP::SUBSCRIBE);
}
bool isUnsubscribeRequest()
{
return isMethod(HTTP::UNSUBSCRIBE);
}
bool isNotifyRequest()
{
return isMethod(HTTP::NOTIFY);
}
////////////////////////////////////////////////
// URI
////////////////////////////////////////////////
public:
void setURI(const char *value, bool isCheckRelativeURL = false);
const char *getURI(std::string &uriBuf);
////////////////////////////////////////////////
// URI Parameter
////////////////////////////////////////////////
public:
ParameterList *getParameterList(ParameterList ¶mList);
const char *getParameterValue(const char *name, std::string ¶mBuf)
{
ParameterList paramList;
getParameterList(paramList);
paramBuf = paramList.getValue(name);
return paramBuf.c_str();
}
////////////////////////////////////////////////
// SOAPAction
////////////////////////////////////////////////
public:
bool isSOAPAction()
{
return hasHeader(HTTP::SOAP_ACTION);
}
////////////////////////////////////////////////
// Host / Port
////////////////////////////////////////////////
public:
void setRequestHost(const char *host)
{
requestHost = host;
}
const char * getRequestHost()
{
return requestHost.c_str();
}
void setRequestPort(int host)
{
requestPort = host;
}
int getRequestPort()
{
return requestPort;
}
////////////////////////////////////////////////
// Socket
////////////////////////////////////////////////
public:
void setSocket(HTTPSocket *value)
{
httpSocket = value;
}
HTTPSocket *getSocket()
{
return httpSocket;
}
/////////////////////////// /////////////////////
// local address/port
////////////////////////////////////////////////
public:
const char *getLocalAddress()
{
return getSocket()->getLocalAddress();
}
int getLocalPort()
{
return getSocket()->getLocalPort();
}
////////////////////////////////////////////////
// parseRequest
////////////////////////////////////////////////
public:
bool parseRequestLine(const char *lineStr);
////////////////////////////////////////////////
// getHeader
////////////////////////////////////////////////
private:
const char *getHTTPVersion(std::string &verBuf);
public:
const char *getHeader(std::string &headerBuf);
////////////////////////////////////////////////
// isKeepAlive
////////////////////////////////////////////////
public:
bool isKeepAlive();
////////////////////////////////////////////////
// read
////////////////////////////////////////////////
public:
bool read()
{
return HTTPPacket::read(getSocket());
}
////////////////////////////////////////////////
// POST (Response)
////////////////////////////////////////////////
public:
bool post(HTTPResponse *httpRes);
////////////////////////////////////////////////
// POST (Request)
////////////////////////////////////////////////
public:
HTTPResponse *post(const char *host, int port, HTTPResponse *httpRes, bool isKeepAlive);
HTTPResponse *post(const char *host, int port, HTTPResponse *httpRes)
{
return post(host, port, httpRes, false);
}
HTTPResponse *post(const char *host, int port, bool isKeepAlive)
{
return post(host, port, &httpRes, isKeepAlive);
}
HTTPResponse *post(const char *host, int port)
{
return post(host, port, false);
}
////////////////////////////////////////////////
// set
////////////////////////////////////////////////
public:
void set(HTTPRequest *httpReq)
{
HTTPPacket::set((HTTPPacket *)httpReq);
setSocket(httpReq->getSocket());
}
////////////////////////////////////////////////
// OK/BAD_REQUEST
////////////////////////////////////////////////
public:
bool returnResponse(int statusCode);
bool returnOK()
{
return returnResponse(HTTP::OK_REQUEST);
}
bool returnBadRequest()
{
return returnResponse(HTTP::BAD_REQUEST);
}
////////////////////////////////////////////////
// toString
////////////////////////////////////////////////
public:
const char *toString(std::string &buf);
void print();
};
}
#endif
| [
"skonno@b944b01c-6696-4570-ab44-a0e08c11cb0e"
]
| [
[
[
1,
314
]
]
]
|
b69ea116cbc95f055122c43152ad522d8d378c11 | 748b6e3b51df5d1cd02735469ea66d5bb29c68e3 | /src/Visualizer/visualize.h | 3db1250204f763e0dad867e6da90f0528c7c9fa5 | [
"ISC"
]
| permissive | vedantk/cvp | d1dfdfb6aad0143f045fdba2559ca4e567bede4f | 222b45cb16e095f4d1dc3e4f45eaf9f606024ae9 | refs/heads/master | 2021-01-20T12:00:23.927548 | 2010-11-01T01:13:56 | 2010-11-01T01:13:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,272 | h | /*
* visualize.h
* class declaration for cvp_vis.
*
* Copyright (c) 2009, M. Sabry Hassouna
* Modified by Vedant Kumar.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* > Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* > Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* > The names of the authors may not be used to endorse or promote products
* derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "vtkRenderWindow.h"
#include "vtkRenderer.h"
#include "vtkPolyDataMapper.h"
#include "vtkActor.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkExtractVOI.h"
#include "vtkPlaneSource.h"
#include "vtkPNMReader.h"
class Visualize {
public:
Visualize();
~Visualize();
void LoadData(char* fp, int nslices);
vtkRenderWindow* renWin;
vtkActor* actor;
vtkPolyDataMapper* mapper;
vtkRenderer* ren1;
vtkRenderWindowInteractor* iren;
vtkPNMReader* readerSegmented;
char SourcePath[256], DstPath[256], Vessels_FileName[256], buffer[256];
int N1, N2, m_Slices;
float m_X, m_Y, m_Z;
};
| [
"[email protected]"
]
| [
[
[
1,
59
]
]
]
|
842dbc112327c3193e019f411f840461b364b1d6 | 6b1a180098b19378372e3372588f07fffb1361a2 | /ruler.cpp | 58f5475c301f2564305ccd56b34c1a33e6cba0d9 | []
| no_license | silvansky/qrulermini | 6fcf039261fe9575a134aca915e5c9f9288544ef | d5e4d8e54cbc16a7edf955992d47b8fcac78604c | refs/heads/master | 2016-09-06T18:12:21.968447 | 2011-06-06T13:59:16 | 2011-06-06T13:59:16 | 32,142,386 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,775 | cpp | #include "ruler.h"
#include "ui_ruler.h"
#include <QPainter>
#include <QPaintEvent>
#include <QDebug>
#include <QVBoxLayout>
#include <QHBoxLayout>
Ruler::Ruler(QWidget *parent) :
QWidget(parent),
ui(new Ui::Ruler)
{
ui->setupUi(this);
alpha = 255;
setAttribute(Qt::WA_TranslucentBackground, true);
setWindowFlags(Qt::FramelessWindowHint | Qt::WindowCloseButtonHint | Qt::WindowStaysOnTopHint | Qt::ToolTip);
co = Qt::Vertical;
relayout();
}
Ruler::~Ruler()
{
delete ui;
}
void Ruler::changeEvent(QEvent *e)
{
QWidget::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
void Ruler::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
{
dragPosition = event->globalPos() - frameGeometry().topLeft();
event->accept();
}
}
void Ruler::mouseMoveEvent(QMouseEvent *event)
{
if (event->buttons() & Qt::LeftButton)
{
move(event->globalPos() - dragPosition);
event->accept();
}
}
void Ruler::keyPressEvent(QKeyEvent * ke)
{
if (ke->key() == Qt::Key_Escape)
qApp->quit();
}
void Ruler::paintEvent(QPaintEvent * pe)
{
QPainter p(this);
p.setClipRect(pe->rect());
QSize sz = size();
// bg
p.fillRect(QRect(QPoint(0, 0), sz), QColor(0, 0, 0, alpha));
// lines
static QList<int> intervals = QList<int>() << 2 << 3 << 5 << 10 << 15 << 18 << 20 << 30 << 40 << 50 << 1;
int x = 0;
p.setPen(QPen(QColor::fromRgb(255, 0, 0)));
QFont f = p.font();
f.setPixelSize(9);
p.setFont(f);
//p.set
foreach (int i, intervals)
{
if (co == Qt::Horizontal)
{
p.drawLine(QPoint(x, 23), QPoint(x, sz.height()));
if (i >= 10)
{
// rotated text
QRect textRect = QRect(x, 23, i, sz.height() - 23);
p.save();
QTransform t;
t.translate(textRect.left() + textRect.width() / 2, textRect.top() + textRect.height() / 2);
t.rotate(90);
p.setTransform(t);
textRect.setWidth(sz.height() - 23);
textRect.moveLeft(textRect.left() + 1);
textRect.setHeight(i);
p.drawText(textRect.translated(-textRect.left() - textRect.width() / 2, -textRect.top() - textRect.height() / 2), QString("%1px").arg(i), QTextOption(Qt::AlignCenter));
p.restore();
}
}
else
{
p.drawLine(QPoint(23, x), QPoint(sz.width(), x));
if (i >= 10)
{
// text
QRect textRect = QRect(23, x, sz.width() - 23, i);
p.drawText(textRect, QString("%1px").arg(i), QTextOption(Qt::AlignCenter));
}
}
x += i - 1;
}
}
Qt::Orientation Ruler::orientation() const
{
return co;
}
void Ruler::setOrientation(Qt::Orientation newOrientation)
{
co = newOrientation;
QRect oldGeom = geometry();
QRect newGeom = QRect(oldGeom.topLeft(), QSize(oldGeom.height(), oldGeom.width()));
setGeometry(newGeom);
relayout();
}
void Ruler::relayout()
{
QBoxLayout * newLayout;
QBoxLayout * parentLayout;
if (co == Qt::Vertical)
{
newLayout = new QVBoxLayout();
parentLayout = new QHBoxLayout(this);
}
else
{
newLayout = new QHBoxLayout();
parentLayout = new QVBoxLayout(this);
}
newLayout->setContentsMargins(0, 0, 0, 0);
parentLayout->setContentsMargins(2, 2, 2, 2);
newLayout->addWidget(ui->toolButton);
ui->verticalSlider->setOrientation(co);
newLayout->addWidget(ui->verticalSlider);
newLayout->addStretch();
if (layout())
layout()->deleteLater();
parentLayout->addLayout(newLayout);
parentLayout->addStretch();
setLayout(parentLayout);
}
void Ruler::on_toolButton_toggled(bool checked)
{
setOrientation(checked ? Qt::Horizontal : Qt::Vertical);
}
void Ruler::on_verticalSlider_valueChanged(int value)
{
alpha = value;
update();
}
| [
"[email protected]@8980c0f3-7d9f-e34e-e20e-0a0ce4d3317c"
]
| [
[
[
1,
163
]
]
]
|
cf80cd55b7ddc12cf2d85d14fac3652cd263acfd | b2d46af9c6152323ce240374afc998c1574db71f | /cursovideojuegos/theflostiproject/3rdParty/boost/libs/variant/test/test5.cpp | e083d209f0ef7860f0f9ab1079a20bba6fcce43c | []
| no_license | bugbit/cipsaoscar | 601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4 | 52aa8b4b67d48f59e46cb43527480f8b3552e96d | refs/heads/master | 2021-01-10T21:31:18.653163 | 2011-09-28T16:39:12 | 2011-09-28T16:39:12 | 33,032,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,967 | cpp | //-----------------------------------------------------------------------------
// boost-libs variant/test/test5.cpp header file
// See http://www.boost.org for updates, documentation, and revision history.
//-----------------------------------------------------------------------------
//
// Copyright (c) 2003
// Eric Friedman, Itay Maman
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include "boost/test/minimal.hpp"
#include "boost/variant.hpp"
#include "jobs.h"
#include <assert.h>
#include <iostream>
#include <string>
#include <vector>
void run()
{
using std::string;
using boost::variant;
using boost::apply_visitor;
typedef variant<int, float, unsigned short, unsigned char> t_var1;
typedef variant<int, t_var1, unsigned short, unsigned char> t_var2;
typedef variant<string, int, t_var2> t_var3;
t_var1 v1;
t_var2 v2;
t_var2 v2_second;
t_var3 v3;
const char c0 = 'x';
v1 = c0;
//v2 and v3 are holding (aka: containing) a variant
v2 = v1;
v3 = v2;
verify(v1, spec<int>());
verify(v2, spec<t_var1>());
verify(v3, spec<t_var2>());
//
// assignment from const char (Converted to int)
//
v2 = c0;
v3 = c0;
verify(v2, spec<int>());
verify(v3, spec<int>());
BOOST_TEST(apply_visitor(sum_int(), v2) == c0);
BOOST_TEST(apply_visitor(sum_int(), v3) == c0);
sum_int adder;
apply_visitor(adder, v2);
apply_visitor(adder, v3);
BOOST_TEST(adder.result() == 2*c0);
//
// A variant holding a variant
//
typedef variant<unsigned char, float> t_var4;
typedef variant<string, t_var4> t_var5;
t_var4 v4;
t_var5 v5;
v5 = 22.5f;
verify(v5, spec<t_var4>(), "[V] [V] 22.5");
}
int test_main(int , char* [])
{
run();
return 0;
}
| [
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
]
| [
[
[
1,
90
]
]
]
|
0c058f9349213fd37cde9526638e7b6c22e7f0f8 | bda7b365b5952dc48827a8e8d33d11abd458c5eb | /Runnable_PS3/display.cpp | 030857127e8d4877ae942e82ed27012d27007634 | []
| no_license | MrColdbird/gameservice | 3bc4dc3906d16713050612c1890aa8820d90272e | 009d28334bdd8f808914086e8367b1eb9497c56a | refs/heads/master | 2021-01-25T09:59:24.143855 | 2011-01-31T07:12:24 | 2011-01-31T07:12:24 | 35,889,912 | 3 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 9,775 | cpp | /* SCE CONFIDENTIAL
* PlayStation(R)3 Programmer Tool Runtime Library 330.001
* Copyright (C) 2010 Sony Computer Entertainment Inc.
* All Rights Reserved.
*/
#define __CELL_ASSERT__
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <sys/process.h>
#include <cell/sysmodule.h>
// libgcm
#include <cell/gcm.h>
#include <sysutil/sysutil_sysparam.h>
// gcmutil
#include "gcmutil.h"
using namespace CellGcmUtil;
using namespace cell::Gcm;
namespace{
uint8_t dispGetSurfaceDepth(uint8_t format)
{
uint32_t depth = 4;
switch(format){
case CELL_GCM_SURFACE_B8:
depth = 1;
break;
case CELL_GCM_SURFACE_X1R5G5B5_Z1R5G5B5:
case CELL_GCM_SURFACE_X1R5G5B5_O1R5G5B5:
case CELL_GCM_SURFACE_R5G6B5:
case CELL_GCM_SURFACE_G8B8:
depth = 2;
break;
case CELL_GCM_SURFACE_X8R8G8B8_Z8R8G8B8:
case CELL_GCM_SURFACE_X8R8G8B8_O8R8G8B8:
case CELL_GCM_SURFACE_A8R8G8B8:
case CELL_GCM_SURFACE_F_X32:
case CELL_GCM_SURFACE_X8B8G8R8_Z8B8G8R8:
case CELL_GCM_SURFACE_X8B8G8R8_O8B8G8R8:
case CELL_GCM_SURFACE_A8B8G8R8:
depth = 4;
break;
case CELL_GCM_SURFACE_F_W16Z16Y16X16:
depth = 8;
break;
case CELL_GCM_SURFACE_F_W32Z32Y32X32:
depth = 16;
break;
default:
depth = 4;
}
return depth;
}
uint8_t dispGetDepthDepth(uint8_t format)
{
if(format == CELL_GCM_SURFACE_Z16) return 2;
if(format == CELL_GCM_SURFACE_Z24S8) return 4;
return 0;
}
uint8_t dispGetVideoFormat(uint8_t format)
{
switch(format){
case CELL_GCM_SURFACE_X8R8G8B8_Z8R8G8B8:
case CELL_GCM_SURFACE_X8R8G8B8_O8R8G8B8:
case CELL_GCM_SURFACE_A8R8G8B8:
return CELL_VIDEO_OUT_BUFFER_COLOR_FORMAT_X8R8G8B8;
case CELL_GCM_SURFACE_X8B8G8R8_Z8B8G8R8:
case CELL_GCM_SURFACE_X8B8G8R8_O8B8G8R8:
case CELL_GCM_SURFACE_A8B8G8R8:
return CELL_VIDEO_OUT_BUFFER_COLOR_FORMAT_X8R8G8B8;
case CELL_GCM_SURFACE_F_W16Z16Y16X16:
return CELL_VIDEO_OUT_BUFFER_COLOR_FORMAT_R16G16B16X16_FLOAT;
case CELL_GCM_SURFACE_B8:
case CELL_GCM_SURFACE_X1R5G5B5_Z1R5G5B5:
case CELL_GCM_SURFACE_X1R5G5B5_O1R5G5B5:
case CELL_GCM_SURFACE_R5G6B5:
case CELL_GCM_SURFACE_G8B8:
case CELL_GCM_SURFACE_F_X32:
case CELL_GCM_SURFACE_F_W32Z32Y32X32:
default:
return CELL_VIDEO_OUT_BUFFER_COLOR_FORMAT_X8R8G8B8;
}
}
} // no name namespace
namespace CellGcmUtil{
CellVideoOutResolution cellGcmUtilGetResolution()
{
// check video output settings
CellVideoOutState state;
CellVideoOutResolution resolution = {0, 0};
CELL_GCMUTIL_CHECK_ASSERT(cellVideoOutGetState(CELL_VIDEO_OUT_PRIMARY, 0, &state));
CELL_GCMUTIL_CHECK_ASSERT(cellVideoOutGetResolution(state.displayMode.resolutionId, &resolution));
return resolution;
}
float cellGcmUtilGetAspectRatio()
{
// check video output settings
CellVideoOutState state;
float aspect = 16.0f / 9.0f;
CELL_GCMUTIL_CHECK_ASSERT(cellVideoOutGetState(CELL_VIDEO_OUT_PRIMARY, 0, &state));
if(state.displayMode.aspect == CELL_VIDEO_OUT_ASPECT_4_3){
aspect = 4.0f / 3.0f;
}
return aspect;
}
bool cellGcmUtilInitDisplay(uint8_t color_format, uint8_t depth_format, uint8_t buffer_number, Memory_t *buffer, CellGcmSurface *surface)
{
if(buffer == 0) return false;
if(surface == 0) return false;
Memory_t *bufFrame = buffer;
Memory_t &bufDepth = buffer[buffer_number];
uint8_t color_depth = dispGetSurfaceDepth(color_format);
uint8_t z_depth = dispGetDepthDepth(depth_format);
// check video output settings
CellVideoOutState state;
CellVideoOutResolution resolution;
CELL_GCMUTIL_CHECK_ASSERT(cellVideoOutGetState(CELL_VIDEO_OUT_PRIMARY, 0, &state));
CELL_GCMUTIL_CHECK_ASSERT(cellVideoOutGetResolution(state.displayMode.resolutionId, &resolution));
// allocate local memory
uint32_t pitch_frame = cellGcmGetTiledPitchSize(resolution.width * color_depth);
uint32_t pitch_depth = cellGcmGetTiledPitchSize(resolution.width * z_depth);
// width and height must be a multiple of 64 for BindZcull
uint32_t zcull_width = cellGcmAlign(CELL_GCM_ZCULL_ALIGN_WIDTH, resolution.width);
uint32_t zcull_height = cellGcmAlign(CELL_GCM_ZCULL_ALIGN_HEIGHT, resolution.height);
for(int32_t i = 0; i < buffer_number; ++i){
// size should be multiples of 64K bytes for SetTileInfo
uint32_t buf_size = cellGcmAlign(CELL_GCM_TILE_ALIGN_SIZE, pitch_frame * zcull_height);
// offset should be aligned on 64K bytes boundary for SetTileInfo
if(cellGcmUtilAllocateLocal(buf_size, CELL_GCM_TILE_ALIGN_OFFSET, &bufFrame[i]) == false){
return false;
}
}
{
// size should be multiples of 64K bytes for SetTileInfo
uint32_t buf_size = cellGcmAlign(CELL_GCM_TILE_ALIGN_SIZE, pitch_depth * zcull_height);
// offset should be aligned on 64K bytes boundary for SetTileInfo
if(cellGcmUtilAllocateLocal(buf_size, CELL_GCM_TILE_ALIGN_OFFSET, &bufDepth) == false){
return false;
}
}
// regist output buffer
for(int32_t i = 0; i < buffer_number; ++i){
CELL_GCMUTIL_CHECK_ASSERT(cellGcmSetDisplayBuffer(i, bufFrame[i].offset, pitch_frame, resolution.width, resolution.height));
}
// regist tile
for(int32_t i = 0; i < buffer_number; ++i){
CELL_GCMUTIL_CHECK(cellGcmSetTileInfo(i, bufFrame[i].location, bufFrame[i].offset, bufFrame[i].size, pitch_frame, CELL_GCM_COMPMODE_DISABLED, NULL, 0));
CELL_GCMUTIL_CHECK(cellGcmBindTile(i));
}
CELL_GCMUTIL_CHECK(cellGcmSetTileInfo(buffer_number, bufDepth.location, bufDepth.offset, bufDepth.size, pitch_depth, CELL_GCM_COMPMODE_Z32_SEPSTENCIL, NULL, 2));
CELL_GCMUTIL_CHECK(cellGcmBindTile(buffer_number));
// regist zcull
CELL_GCMUTIL_CHECK(cellGcmBindZcull(0, bufDepth.offset, zcull_width, zcull_height, 0,
CELL_GCM_ZCULL_Z24S8, CELL_GCM_SURFACE_CENTER_1,
CELL_GCM_ZCULL_LESS, CELL_GCM_ZCULL_LONES,
CELL_GCM_SCULL_SFUNC_LESS, 0x80, 0xff));
// regist suface
for(int32_t i = 0; i < buffer_number; ++i){
surface[i].colorFormat = color_format;
surface[i].colorTarget = CELL_GCM_SURFACE_TARGET_0;
// frame buffer
surface[i].colorLocation[0] = bufFrame[i].location;
surface[i].colorOffset[0] = bufFrame[i].offset;
surface[i].colorPitch[0] = pitch_frame;
// not be used
surface[i].colorLocation[1] = CELL_GCM_LOCATION_LOCAL;
surface[i].colorLocation[2] = CELL_GCM_LOCATION_LOCAL;
surface[i].colorLocation[3] = CELL_GCM_LOCATION_LOCAL;
surface[i].colorOffset[1] = 0;
surface[i].colorOffset[2] = 0;
surface[i].colorOffset[3] = 0;
surface[i].colorPitch[1] = 64;
surface[i].colorPitch[2] = 64;
surface[i].colorPitch[3] = 64;
// depth buffer
surface[i].depthFormat = depth_format;
surface[i].depthLocation = bufDepth.location;
surface[i].depthOffset = bufDepth.offset;
surface[i].depthPitch = pitch_depth;
surface[i].type = CELL_GCM_SURFACE_PITCH;
surface[i].antialias = CELL_GCM_SURFACE_CENTER_1;
surface[i].width = resolution.width;
surface[i].height = resolution.height;
surface[i].x = 0;
surface[i].y = 0;
}
CellVideoOutConfiguration videocfg;
memset(&videocfg, 0, sizeof(CellVideoOutConfiguration));
videocfg.resolutionId = state.displayMode.resolutionId;
videocfg.format = dispGetVideoFormat(color_format);
videocfg.pitch = pitch_frame;
CELL_GCMUTIL_CHECK_ASSERT(cellVideoOutConfigure(CELL_VIDEO_OUT_PRIMARY, &videocfg, NULL, 0));
return true;
}
uint8_t getResolutionId(uint32_t width, uint32_t height)
{
if(width == 1920) return CELL_VIDEO_OUT_RESOLUTION_1080;
if(width == 1440) return CELL_VIDEO_OUT_RESOLUTION_1440x1080;
if(width == 1280){
if(height == 1080) return CELL_VIDEO_OUT_RESOLUTION_1280x1080;
return CELL_VIDEO_OUT_RESOLUTION_720;
}
if(width == 960) return CELL_VIDEO_OUT_RESOLUTION_960x1080;
if(width == 720){
if(height == 576) return CELL_VIDEO_OUT_RESOLUTION_576;
return CELL_VIDEO_OUT_RESOLUTION_480;
}
printf("ERROR: reso=%dx%d\n", width, height);
assert(false);
return CELL_VIDEO_OUT_RESOLUTION_1080;
}
uint8_t getAspect(uint32_t width, uint32_t height)
{
// check video output settings
CellVideoOutState state;
if(cellVideoOutGetState(CELL_VIDEO_OUT_PRIMARY, 0, &state) != CELL_OK){
assert(false);
return CELL_VIDEO_OUT_ASPECT_16_9;
}
if(width == 1920) return CELL_VIDEO_OUT_ASPECT_16_9;
if(width == 1440) return state.displayMode.aspect;
if(width == 1280){
if(height == 1080) return state.displayMode.aspect;
return CELL_VIDEO_OUT_ASPECT_16_9;
}
if(width == 960) return state.displayMode.aspect;
if(width == 720){
if(height == 576) return CELL_VIDEO_OUT_ASPECT_4_3;
return CELL_VIDEO_OUT_ASPECT_4_3;
}
assert(false);
return CELL_VIDEO_OUT_RESOLUTION_1080;
}
bool cellGcmUtilSetDisplayBuffer(uint8_t number, CellGcmTexture *texture_array)
{
if(texture_array == 0) return false;
int ret = 0;
for(int32_t i = 0; i < number; ++i){
CELL_GCMUTIL_CHECK_ASSERT(cellGcmSetDisplayBuffer(i, texture_array[i].offset, texture_array[i].pitch, texture_array[i].width, texture_array[i].height));
}
CellVideoOutConfiguration videocfg;
memset(&videocfg, 0, sizeof(CellVideoOutConfiguration));
videocfg.resolutionId = getResolutionId(texture_array[0].width, texture_array[0].height);
videocfg.aspect = getAspect(texture_array[0].width, texture_array[0].height);
videocfg.format = dispGetVideoFormat(texture_array[0].format);
videocfg.pitch = texture_array[0].pitch;
CELL_GCMUTIL_CHECK_ASSERT(cellVideoOutConfigure(CELL_VIDEO_OUT_PRIMARY, &videocfg, NULL, 0));
return (ret == CELL_OK);
}
} // namespace CellGcmUtil
| [
"leavesmaple@383b229b-c81f-2bc2-fa3f-61d2d0c0fe69"
]
| [
[
[
1,
318
]
]
]
|
2526e925455668e87d09f6d8f62169f865c8abd2 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/BOOST_SDK/boost/config/compiler/intel.hpp | 78ed5c822abd56402dd27325768e31e9d24ab020 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,805 | hpp | // (C) Copyright John Maddock 2001.
// (C) Copyright Peter Dimov 2001.
// (C) Copyright Jens Maurer 2001.
// (C) Copyright David Abrahams 2002 - 2003.
// (C) Copyright Aleksey Gurtovoy 2002 - 2003.
// (C) Copyright Guillaume Melquiond 2002 - 2003.
// (C) Copyright Beman Dawes 2003.
// (C) Copyright Martin Wille 2003.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
// Intel compiler setup:
#include "boost/config/compiler/common_edg.hpp"
#if defined(__INTEL_COMPILER)
# define BOOST_INTEL_CXX_VERSION __INTEL_COMPILER
#elif defined(__ICL)
# define BOOST_INTEL_CXX_VERSION __ICL
#elif defined(__ICC)
# define BOOST_INTEL_CXX_VERSION __ICC
#elif defined(__ECC)
# define BOOST_INTEL_CXX_VERSION __ECC
#endif
#define BOOST_COMPILER "Intel C++ version " BOOST_STRINGIZE(BOOST_INTEL_CXX_VERSION)
#define BOOST_INTEL BOOST_INTEL_CXX_VERSION
#if defined(_WIN32) || defined(_WIN64)
# define BOOST_INTEL_WIN BOOST_INTEL
#else
# define BOOST_INTEL_LINUX BOOST_INTEL
#endif
#if (BOOST_INTEL_CXX_VERSION <= 500) && defined(_MSC_VER)
# define BOOST_NO_EXPLICIT_FUNCTION_TEMPLATE_ARGUMENTS
# define BOOST_NO_TEMPLATE_TEMPLATES
#endif
#if (BOOST_INTEL_CXX_VERSION <= 600)
# if defined(_MSC_VER) && (_MSC_VER <= 1300) // added check for <= VC 7 (Peter Dimov)
// Boost libraries assume strong standard conformance unless otherwise
// indicated by a config macro. As configured by Intel, the EDG front-end
// requires certain compiler options be set to achieve that strong conformance.
// Particularly /Qoption,c,--arg_dep_lookup (reported by Kirk Klobe & Thomas Witt)
// and /Zc:wchar_t,forScope. See boost-root/tools/build/intel-win32-tools.jam for
// details as they apply to particular versions of the compiler. When the
// compiler does not predefine a macro indicating if an option has been set,
// this config file simply assumes the option has been set.
// Thus BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP will not be defined, even if
// the compiler option is not enabled.
# define BOOST_NO_SWPRINTF
# endif
// Void returns, 64 bit integrals don't work when emulating VC 6 (Peter Dimov)
# if defined(_MSC_VER) && (_MSC_VER <= 1200)
# define BOOST_NO_VOID_RETURNS
# define BOOST_NO_INTEGRAL_INT64_T
# endif
#endif
#if (BOOST_INTEL_CXX_VERSION <= 710) && defined(_WIN32)
# define BOOST_NO_POINTER_TO_MEMBER_TEMPLATE_PARAMETERS
#endif
// See http://aspn.activestate.com/ASPN/Mail/Message/boost/1614864
#if BOOST_INTEL_CXX_VERSION < 600
# define BOOST_NO_INTRINSIC_WCHAR_T
#else
// We should test the macro _WCHAR_T_DEFINED to check if the compiler
// supports wchar_t natively. *BUT* there is a problem here: the standard
// headers define this macro if they typedef wchar_t. Anyway, we're lucky
// because they define it without a value, while Intel C++ defines it
// to 1. So we can check its value to see if the macro was defined natively
// or not.
// Under UNIX, the situation is exactly the same, but the macro _WCHAR_T
// is used instead.
# if ((_WCHAR_T_DEFINED + 0) == 0) && ((_WCHAR_T + 0) == 0)
# define BOOST_NO_INTRINSIC_WCHAR_T
# endif
#endif
#if defined(__GNUC__) && !defined(BOOST_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL)
//
// Figure out when Intel is emulating this gcc bug
// (All Intel versions prior to 9.0.26, and versions
// later than that if they are set up to emulate gcc 3.2
// or earlier):
//
# if ((__GNUC__ == 3) && (__GNUC_MINOR__ <= 2)) || (BOOST_INTEL < 900) || (__INTEL_COMPILER_BUILD_DATE < 20050912)
# define BOOST_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL
# endif
#endif
//
// Verify that we have actually got BOOST_NO_INTRINSIC_WCHAR_T
// set correctly, if we don't do this now, we will get errors later
// in type_traits code among other things, getting this correct
// for the Intel compiler is actually remarkably fragile and tricky:
//
#if defined(BOOST_NO_INTRINSIC_WCHAR_T)
#include <cwchar>
template< typename T > struct assert_no_intrinsic_wchar_t;
template<> struct assert_no_intrinsic_wchar_t<wchar_t> { typedef void type; };
// if you see an error here then you need to unset BOOST_NO_INTRINSIC_WCHAR_T
// where it is defined above:
typedef assert_no_intrinsic_wchar_t<unsigned short>::type assert_no_intrinsic_wchar_t_;
#else
template< typename T > struct assert_intrinsic_wchar_t;
template<> struct assert_intrinsic_wchar_t<wchar_t> {};
// if you see an error here then define BOOST_NO_INTRINSIC_WCHAR_T on the command line:
template<> struct assert_intrinsic_wchar_t<unsigned short> {};
#endif
#if _MSC_VER+0 >= 1000
# if _MSC_VER >= 1200
# define BOOST_HAS_MS_INT64
# endif
# define BOOST_NO_SWPRINTF
#elif defined(_WIN32)
# define BOOST_DISABLE_WIN32
#endif
// I checked version 6.0 build 020312Z, it implements the NRVO.
// Correct this as you find out which version of the compiler
// implemented the NRVO first. (Daniel Frey)
#if (BOOST_INTEL_CXX_VERSION >= 600)
# define BOOST_HAS_NRVO
#endif
//
// versions check:
// we don't support Intel prior to version 5.0:
#if BOOST_INTEL_CXX_VERSION < 500
# error "Compiler not supported or configured - please reconfigure"
#endif
//
// last known and checked version:
#if (BOOST_INTEL_CXX_VERSION > 910)
# if defined(BOOST_ASSERT_CONFIG)
# error "Unknown compiler version - please run the configure tests and report the results"
# elif defined(_MSC_VER)
# pragma message("Unknown compiler version - please run the configure tests and report the results")
# endif
#endif
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
158
]
]
]
|
5d0d9153b2ef25a1a1eabfae1ee52ad7b887fe89 | 854ee643a4e4d0b7a202fce237ee76b6930315ec | /arcemu_svn/src/sun/src/InstanceScripts/Instance_OldHillsbradFoothills.cpp | cc12f1f6d73652dc7224ba29c9ca338b72dbcbce | []
| no_license | miklasiak/projekt | df37fa82cf2d4a91c2073f41609bec8b2f23cf66 | 064402da950555bf88609e98b7256d4dc0af248a | refs/heads/master | 2021-01-01T19:29:49.778109 | 2008-11-10T17:14:14 | 2008-11-10T17:14:14 | 34,016,391 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,536 | cpp | /*
* Moon++ Scripts for Ascent MMORPG Server
* Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2007-2008 Moon++ Team <http://www.moonplusplus.info/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "StdAfx.h"
#include "Setup.h"
/************************************************************************/
/* Instance_OldHillsbradFoothills.cpp Script */
/************************************************************************/
#define CN_LIEUTENANT_DRAKE 17848
#define FRIGHTENING_SHOUT 33789
#define WHIRLWIND 33239
#define MORTAL_STRIKE 17547
//#define EXPLODING_SHOT 33792 Only in Heroics
class LIEUTENANTDRAKEAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(LIEUTENANTDRAKEAI);
SP_AI_Spell spells[3];
bool m_spellcheck[3];
LIEUTENANTDRAKEAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
nrspells = 3;
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
spells[0].info = dbcSpell.LookupEntry(FRIGHTENING_SHOUT);
spells[0].targettype = TARGET_VARIOUS;
spells[0].instant = true;
spells[0].cooldown = 8;
spells[0].perctrigger = 0.0f;
spells[0].attackstoptimer = 1000;
spells[0].speech = "Run, you blasted cowards!";
spells[1].info = dbcSpell.LookupEntry(WHIRLWIND);
spells[1].targettype = TARGET_VARIOUS;
spells[1].instant = true;
spells[1].cooldown = 10;
spells[1].perctrigger = 0.0f;
spells[1].attackstoptimer = 1000;
spells[1].speech = "Time to bleed!";
spells[2].info = dbcSpell.LookupEntry(MORTAL_STRIKE);
spells[2].targettype = TARGET_ATTACKING;
spells[2].instant = true;
spells[2].cooldown = 5;
spells[2].perctrigger = 0.0f;
spells[2].attackstoptimer = 1000;
/*spells[2].info = dbcSpell.LookupEntry(EXPLODING_SHOT);
spells[2].targettype = TARGET_ATTACKING;
spells[2].instant = true;
spells[2].cooldown = 15;
spells[2].perctrigger = 0.0f;
spells[2].attackstoptimer = 1000;*/
}
void OnCombatStart(Unit* mTarget)
{
CastTime();
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "I know what you're up to, and I mean to put an end to it, permanently!");
_unit->PlaySoundToSet(10271);
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
}
void CastTime()
{
for(int i=0;i<nrspells;i++)
spells[i].casttime = spells[i].cooldown;
}
void OnTargetDied(Unit* mTarget)
{
if(_unit->GetHealthPct() > 0)
{
_unit->PlaySoundToSet(10271);
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "You will not interfere!");
}
}
void OnCombatStop(Unit *mTarget)
{
CastTime();
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
}
void OnDied(Unit * mKiller)
{
CastTime();
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Thrall... must not... go free.");
_unit->PlaySoundToSet(10271);
RemoveAIUpdateEvent();
}
void AIUpdate()
{
float val = (float)RandomFloat(100.0f);
SpellCast(val);
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i=0;i<nrspells;i++)
{
spells[i].casttime--;
if (m_spellcheck[i])
{
spells[i].casttime = spells[i].cooldown;
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant); break;
case TARGET_ATTACKING:
_unit->CastSpell(target, spells[i].info, spells[i].instant); break;
case TARGET_DESTINATION:
_unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break;
}
if (spells[i].speech != "")
{
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, spells[i].speech.c_str());
_unit->PlaySoundToSet(spells[i].soundid);
}
m_spellcheck[i] = false;
return;
}
if ((val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger)) || !spells[i].casttime)
{
_unit->setAttackTimer(spells[i].attackstoptimer, false);
m_spellcheck[i] = true;
}
comulativeperc += spells[i].perctrigger;
}
}
}
protected:
int nrspells;
};
#define CN_CAPTAIN_SKARLOC 17862
//#define CLEANSE 39078 Needs support
#define HOLY_LIGHT 43451
#define HAMMER_OF_JUSTICE 13005
#define HOLY_SHIELD 31904
#define DEVOTION_AURA 41452
//#define CONSECRATION 41541 Only in Heroics
class CAPTAINSKARLOCAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(CAPTAINSKARLOCAI);
SP_AI_Spell spells[4];
bool m_spellcheck[4];
CAPTAINSKARLOCAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
nrspells = 4;
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
spells[0].info = dbcSpell.LookupEntry(HOLY_LIGHT);
spells[0].targettype = TARGET_SELF;
spells[0].instant = false;
spells[0].cooldown = 15;
spells[0].perctrigger = 0.0f;
spells[0].attackstoptimer = 1000;
spells[0].info = dbcSpell.LookupEntry(HAMMER_OF_JUSTICE);
spells[0].targettype = TARGET_ATTACKING;
spells[0].instant = true;
spells[0].cooldown = 10;
spells[0].perctrigger = 0.0f;
spells[0].attackstoptimer = 1000;
spells[1].info = dbcSpell.LookupEntry(HOLY_SHIELD);
spells[1].targettype = TARGET_SELF;
spells[1].instant = true;
spells[1].cooldown = 5;
spells[1].perctrigger = 0.0f;
spells[1].attackstoptimer = 1000;
spells[1].info = dbcSpell.LookupEntry(DEVOTION_AURA);
spells[1].targettype = TARGET_SELF;
spells[1].instant = true;
spells[1].cooldown = 5;
spells[1].perctrigger = 0.0f;
spells[1].attackstoptimer = 1000;
/*spells[1].info = dbcSpell.LookupEntry(CLEANSE);
spells[1].targettype = TARGET_SELF;
spells[1].instant = true;
spells[1].cooldown = 5;
spells[1].perctrigger = 0.0f;
spells[1].attackstoptimer = 1000;
spells[2].info = dbcSpell.LookupEntry(CONSECRATION);
spells[2].targettype = TARGET_SELF;
spells[2].instant = true;
spells[2].cooldown = 15;
spells[2].perctrigger = 0.0f;
spells[2].attackstoptimer = 1000;*/
}
void OnCombatStart(Unit* mTarget)
{
CastTime();
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Thrall! You didn't really think you would escape did you? You and your allies shall answer to Blackmoore - after I've had my fun!");
_unit->PlaySoundToSet(10271);
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
}
void CastTime()
{
for(int i=0;i<nrspells;i++)
spells[i].casttime = spells[i].cooldown;
}
void OnTargetDied(Unit* mTarget)
{
if(_unit->GetHealthPct() > 0)
{
uint32 sound = 0;
char *text;
switch(RandomUInt(1))
{
case 0:
sound = 10271;
text = "Thrall will never be free!";
break;
case 1:
sound = 10271;
text = "Did you really think you would leave here alive?";
break;
}
_unit->PlaySoundToSet(sound);
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, text);
}
}
void OnCombatStop(Unit *mTarget)
{
CastTime();
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
}
void OnDied(Unit * mKiller)
{
CastTime();
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Guards! Urgh..Guards..!");
_unit->PlaySoundToSet(10271);
RemoveAIUpdateEvent();
}
void AIUpdate()
{
float val = (float)RandomFloat(100.0f);
SpellCast(val);
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i=0;i<nrspells;i++)
{
spells[i].casttime--;
if (m_spellcheck[i])
{
spells[i].casttime = spells[i].cooldown;
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant); break;
case TARGET_ATTACKING:
_unit->CastSpell(target, spells[i].info, spells[i].instant); break;
case TARGET_DESTINATION:
_unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break;
}
if (spells[i].speech != "")
{
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, spells[i].speech.c_str());
_unit->PlaySoundToSet(spells[i].soundid);
}
m_spellcheck[i] = false;
return;
}
if ((val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger)) || !spells[i].casttime)
{
_unit->setAttackTimer(spells[i].attackstoptimer, false);
m_spellcheck[i] = true;
}
comulativeperc += spells[i].perctrigger;
}
}
}
protected:
int nrspells;
};
#define CN_EPOCH_HUNTER 18096
#define SAND_BREATH 31478
#define IMPENDING_DOOM 19702
#define KNOCKBACK 26027
#define MAGIC_DISRUPTION_AURA 33834
class EPOCHHUNTERAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(EPOCHHUNTERAI);
SP_AI_Spell spells[4];
bool m_spellcheck[4];
EPOCHHUNTERAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
nrspells = 4;
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
spells[0].info = dbcSpell.LookupEntry(SAND_BREATH);
spells[0].targettype = TARGET_DESTINATION;
spells[0].instant = true;
spells[0].cooldown = 15;
spells[0].perctrigger = 0.0f;
spells[0].attackstoptimer = 1000;
spells[1].info = dbcSpell.LookupEntry(IMPENDING_DOOM);
spells[1].targettype = TARGET_ATTACKING;
spells[1].instant = true;
spells[1].cooldown = 6;
spells[1].perctrigger = 0.0f;
spells[1].attackstoptimer = 1000;
spells[2].info = dbcSpell.LookupEntry(KNOCKBACK);
spells[2].targettype = TARGET_VARIOUS;
spells[2].instant = true;
spells[2].cooldown = 10;
spells[2].perctrigger = 0.0f;
spells[2].attackstoptimer = 1000;
spells[3].info = dbcSpell.LookupEntry(MAGIC_DISRUPTION_AURA);
spells[3].targettype = TARGET_DESTINATION;
spells[3].instant = true;
spells[3].cooldown = 8;
spells[3].perctrigger = 0.0f;
spells[3].attackstoptimer = 1000;
}
void OnCombatStart(Unit* mTarget)
{
CastTime();
switch (RandomUInt(1))
{
case 0:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Enough! I will erase your very existence!");
_unit->PlaySoundToSet(10271);
break;
case 1:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "You cannot fight fate!");
_unit->PlaySoundToSet(10271);
break;
}
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
}
void CastTime()
{
for(int i=0;i<nrspells;i++)
spells[i].casttime = spells[i].cooldown;
}
void OnTargetDied(Unit* mTarget)
{
if(_unit->GetHealthPct() > 0)
{
uint32 sound = 0;
char *text;
switch (RandomUInt(1))
{
case 0:
sound = 10271;
text = "You are...irrelevant.";
break;
case 1:
sound = 10271;
text = "Thrall will remain a slave. Taretha will die. You have failed.";
break;
}
_unit->PlaySoundToSet(sound);
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, text);
}
}
void OnCombatStop(Unit *mTarget)
{
CastTime();
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
}
void OnDied(Unit * mKiller)
{
CastTime();
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "No!...The master... will not... be pleased.");
_unit->PlaySoundToSet(10271);
RemoveAIUpdateEvent();
}
void AIUpdate()
{
float val = (float)RandomFloat(100.0f);
SpellCast(val);
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i=0;i<nrspells;i++)
{
spells[i].casttime--;
if (m_spellcheck[i])
{
spells[i].casttime = spells[i].cooldown;
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant); break;
case TARGET_ATTACKING:
_unit->CastSpell(target, spells[i].info, spells[i].instant); break;
case TARGET_DESTINATION:
_unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break;
}
if (spells[i].info->Id == SAND_BREATH) //Sand Breath has 2 speeches, maybe there is an easier way to do it
{
switch(RandomUInt(1))
{
case 0:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Not so fast!");
_unit->PlaySoundToSet(spells[i].soundid);
break;
case 1:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Struggle as much as you like!");
_unit->PlaySoundToSet(spells[i].soundid);
break;
}
}
else
{
if (spells[i].speech != "")
{
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, spells[i].speech.c_str());
_unit->PlaySoundToSet(spells[i].soundid);
}
}
m_spellcheck[i] = false;
return;
}
if ((val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger)) || !spells[i].casttime)
{
_unit->setAttackTimer(spells[i].attackstoptimer, false);
m_spellcheck[i] = true;
}
comulativeperc += spells[i].perctrigger;
}
}
}
protected:
int nrspells;
};
void SetupOldHillsbradFoothills(ScriptMgr * mgr)
{
mgr->register_creature_script(CN_LIEUTENANT_DRAKE, &LIEUTENANTDRAKEAI::Create);
mgr->register_creature_script(CN_EPOCH_HUNTER, &EPOCHHUNTERAI::Create);
mgr->register_creature_script(CN_CAPTAIN_SKARLOC, &CAPTAINSKARLOCAI::Create);
} | [
"[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef"
]
| [
[
[
1,
542
]
]
]
|
f4a751542125596bc744195f956ced32fb71c320 | e98d99816ad42028e5988ade802ffdf9846da166 | /Mediotic/mediParticleTriple.h | 6c558f024bddcb15eea7f6842b21602b0c1caeb2 | []
| no_license | OpenEngineDK/extensions-MediPhysics | 5e9b3a0d178db8e9a42ce7724ee35fdfee70ec64 | 94fdd25f90608ad3db6b3c6a30db1c1e4c490987 | refs/heads/master | 2016-09-14T04:26:29.607457 | 2008-10-14T12:14:53 | 2008-10-14T12:14:53 | 58,073,189 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 203 | h | #pragma once
class mediParticle; //include mediParticle.h
class mediParticleTriple
{
private:
mediParticle* particles[3];
public:
mediParticleTriple(void);
~mediParticleTriple(void);
};
| [
"[email protected]"
]
| [
[
[
1,
12
]
]
]
|
8f8a6bf497d6141108c13c67b1eb3d82bc28cc12 | ca35e9ad7161656b1e3eb4c2ded9fccba0e30549 | /Tools/db2lbff.cpp | 62bd91bd2107dfa4fcd4908f87dfac810c0e142e | []
| no_license | leppert/fire | 082725f1dcb79bd72dd9f12142bbe0dae211e6b8 | 9afa3a79d1961551e43d65b0e940b416fc40a65e | refs/heads/master | 2020-11-26T19:36:49.131773 | 2009-12-07T21:14:54 | 2009-12-07T21:14:54 | 1,627,927 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,343 | cpp | /*
This file is part of the FIRE -- Flexible Image Retrieval System
FIRE 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.
FIRE 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 FIRE; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/**
* A program to convert any image retrieval database in FIRE format to
* LBFF (large binary feature file). But only vectorfeatures (e.g. vectors,
* images, histograms are considered)
*
*/
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include"basefeature.hpp"
#include"vectorfeature.hpp"
#include"histogramfeature.hpp"
#include"binaryfeature.hpp"
#include"imagefeature.hpp"
#include"sparsehistogramfeature.hpp"
#include"largebinaryfeaturefile.hpp"
#include"database.hpp"
#include"getpot.hpp"
using namespace std;
void usage(){
cout << "Usage():" << endl
<< "-h, --help give help" << endl
<< "-f, --filelist <file> specify FIRE filelist to be converted" << endl
<< " to large binary feature file format. this option must be set" << endl
<< "-t, --targetdirectory <path> specify where the large binary feature files should be saved" << endl
<< " this is optional. when not used the large binary feature files" << endl
<< " will be created in the directory as specified by the path included" << endl
<< " in the given FIRE filelist." << endl
<< endl;
exit(20);
}
bool calcMaxFeatSize(const Database& db,unsigned long int & ftsize,uint suffIdx ){
bool differ = false;
unsigned long int help = 0;
for(uint imgIdx=1;imgIdx<db.size();imgIdx++){
help = ((*(db[imgIdx]))[suffIdx])->calcBinarySize();
if(ftsize!=help){
differ = true;
ftsize = max(ftsize,help);
}
}
return differ;
}
int main(int argc, char** argv){
GetPot cl(argc,argv);
string path;
string filelist;
bool pathset = false;
//parse commandline via getpot
vector<string> ufos = cl.unidentified_options(6,"-h","--help","-f","--filelist","-t","--targetdirectory"); //6
if(ufos.size()!=0) {
for(vector<string>::const_iterator i=ufos.begin();i!=ufos.end();++i) {
cout << "Unknown option detected: " << *i << endl;
}
usage();
}
if(cl.search(2,"-h","--help")){
usage();
}
if(cl.search(2,"-f","--filelist")){
filelist = cl.follow("filelist",2,"-f","--filelist");
} else {
ERR << "No fielist specified for converting" << endl;
usage();
}
if(cl.search(2,"-t","--targetdirectory")){
path = cl.follow("~",2,"-t","--targetdirectory");
pathset = true;
}
// create database and loadfilelist
Database db;
DBG(10) << "filelist = " << filelist << endl;
if(db.loadFileList(filelist) != 0){
DBG(10) << "loaded filelist" << endl;
db.loadFeatures();
DBG(10) << "loaded features" << endl;
// write lbff files
for(uint i = 0; i< db.numberOfSuffices();++i){
string filename;
if(pathset){
filename=path+"/"+db.suffix(i)+".lbff";
} else {
filename=db.path()+"/"+db.suffix(i)+".lbff";
}
// get feature type
FeatureType ftype = db.featureType(i);
// calculate how large in binary one feature is
unsigned long int ftsize = 0;
// determine if features of equal type differ in size
bool differ = false;
switch(ftype){
case FT_HISTO:
ftsize = ((*(db[0]))[i])->calcBinarySize();
differ = calcMaxFeatSize(db,ftsize,i);
DBG(10) << "type = FT_HISTO" << endl;
if(differ){
DBG(10) << "features differ in size " << endl;
}
break;
case FT_IMG:
ftsize = ((*(db[0]))[i])->calcBinarySize();
differ = calcMaxFeatSize(db,ftsize,i);
DBG(10) << "type = FT_IMG" << endl;
if(differ){
DBG(10) << "features differ in size " << endl;
}
break;
case FT_VEC:
ftsize = ((*(db[0]))[i])->calcBinarySize();
differ = calcMaxFeatSize(db,ftsize,i);
DBG(10) << "type = FT_VEC" << endl;
if(differ){
DBG(10) << "features differ in size " << endl;
}
break;
case FT_SPARSEHISTO:
ftsize = ((*(db[0]))[i])->calcBinarySize();
differ = calcMaxFeatSize(db,ftsize,i);
DBG(10) << "type = FT_SPARSEHISTO" << endl;
if(differ){
DBG(10) << "features differ in size " << endl;
}
break;
case FT_BINARY:
ftsize = ((*(db[0]))[i])->calcBinarySize();
DBG(10) << "type = FT_BINARY" << endl;
break;
default:
ERR << "unknown feature type "<<db.suffix(i)<<" in FIRE filelist present" << endl;
exit(20);
}
DBG(10) << "got size " << ftsize << endl;
/*//remove possible .gz from the filename to be created
uint gzpos = filename.rfind(".gz");
if (gzpos != string::npos){
filename.erase(gzpos,3);
}*/
// note that the length of the filename is added to the feature size in the constructor of the largebinaryfeaturefiles
LargeBinaryFeatureFile lbff(filename,ftype,(unsigned long int)db.size(),ftsize,differ);
DBG(10) << "fileheader written" << endl;
for(uint j = 0; j< db.size();++j){
lbff.writeNext(db[j],i);
}
lbff.closeWriting();
DBG(10) << "features written" << endl;
DBG(10) << "information written to file " << filename << endl;
}
} else {
ERR << "Error loading FIRE filelist; exiting" << endl;
exit(20);
}
exit(0);
}
| [
"[email protected]@b4508c54-8848-11de-8bba-6b05ac85e19d"
]
| [
[
[
1,
185
]
]
]
|
41370d6c0aba7930a834c22ced94fdef625a86ab | 13f8c757bb27ad215712d32d7ec6aea3a1543017 | /MagicSocket/MagicSocket/Buffer.cpp | f88835f16f0c76574b668b8ce38373b0e6e1d5fa | []
| no_license | xqq/magicsocket | 9223d231e41cd5a682f65fba4428ceaa9060239e | 380218b9adf320f1fe7ff6a6d38a8c03c191c43f | refs/heads/master | 2021-01-01T06:32:47.394714 | 2010-02-25T05:02:31 | 2010-02-25T05:02:31 | 32,111,620 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,311 | cpp | #include "Buffer.h"
#include <cstring>
namespace Magic {
Buffer::Buffer(size_t size)
{
allocSize = bufferSize = size;
if (allocSize < 4) allocSize = 4;
Heap &heap = GetBufferHeap();
buffer = (Byte *)heap.Allocate(allocSize);
}
Buffer::Buffer(const char *str)
{
allocSize = bufferSize = strlen(str);
if (allocSize < 4) allocSize = 4;
Heap &heap = GetBufferHeap();
buffer = (Byte *)heap.Allocate(allocSize);
RtlMoveMemory(buffer, str, bufferSize);
}
Buffer::~Buffer()
{
Heap &heap = GetBufferHeap();
heap.Free(buffer);
}
size_t Buffer::Size() const
{
return bufferSize;
}
void Buffer::Resize(size_t size)
{
if (size < allocSize) {
bufferSize = size;
} else {
if (size < allocSize * 2) {
allocSize *= 2;
} else {
allocSize = size;
}
Heap &heap = GetBufferHeap();
Byte *newBuffer = (Byte *)heap.Allocate(allocSize);
RtlMoveMemory(newBuffer, buffer, bufferSize);
heap.Free(buffer);
buffer = newBuffer;
bufferSize = size;
}
}
Byte * Buffer::Pointer(size_t offset)
{
return &buffer[offset];
}
const Byte * Buffer::Pointer(size_t offset) const
{
return &buffer[offset];
}
Heap & Buffer::GetBufferHeap()
{
static Heap heap;
return heap;
}
} | [
"[email protected]@b2af3b84-21c2-11df-a1e5-412df870b945"
]
| [
[
[
1,
70
]
]
]
|
ca2341ad4ee74c7fcb705c83287a3bb37abdd018 | b2d46af9c6152323ce240374afc998c1574db71f | /cursovideojuegos/theflostiproject/3rdParty/boost/libs/serialization/test/throw_exception.hpp | 2057a5d201f80006fee23e5ec9e8bdf5e7d12815 | []
| no_license | bugbit/cipsaoscar | 601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4 | 52aa8b4b67d48f59e46cb43527480f8b3552e96d | refs/heads/master | 2021-01-10T21:31:18.653163 | 2011-09-28T16:39:12 | 2011-09-28T16:39:12 | 33,032,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,317 | hpp | #ifndef BOOST_SERIALIZATION_EXCEPTION_HPP
#define BOOST_SERIALIZATION_EXCEPTION_HPP
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// throw_exception.hpp
//
// Copyright (c) 2002 Peter Dimov and Multi Media Ltd.
//
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// http://www.boost.org/libs/utility/throw_exception.html
//
#include <boost/config.hpp>
#include <boost/throw_exception.hpp>
#ifndef BOOST_NO_EXCEPTIONS
# include <exception>
#endif
namespace boost {
#ifdef BOOST_NO_EXCEPTIONS
// user defined
void throw_exception(std::exception const & e);
void throw_exception();
} // namespace boost
#define BOOST_TRY
#define BOOST_CATCH(x) if(0)
#else
// inline template<class E> void throw_exception(E const & e)
// {
// throw e;
// }
inline void throw_exception()
{
throw;
}
#define BOOST_TRY try
#define BOOST_CATCH(x) catch(x)
#endif
} // namespace boost
#endif // BOOST_SERIALIZATION_EXCEPTION_HPP
| [
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
]
| [
[
[
1,
52
]
]
]
|
62c98cd2552d2a6b1193b4d4a9669826bfe63ef1 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libc/testcapstat/src/tstatserver.cpp | 6198e245ae7e8cef32bb3447efc5446c0ad4745e | []
| no_license | SymbianSource/oss.FCL.sftools.ana.compatanamdw | a6a8abf9ef7ad71021d43b7f2b2076b504d4445e | 1169475bbf82ebb763de36686d144336fcf9d93b | refs/heads/master | 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,862 | cpp | /*
* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
#include <c32comm.h>
#if defined (__WINS__)
#define PDD_NAME _L("ECDRV")
#else
#define PDD_NAME _L("EUART1")
#define PDD2_NAME _L("EUART2")
#define PDD3_NAME _L("EUART3")
#define PDD4_NAME _L("EUART4")
#endif
#define LDD_NAME _L("ECOMM")
/**
* @file
*
* Pipe test server implementation
*/
#include "tstatserver.h"
#include "tstat.h"
//_LIT(KServerName, "tstatcap");
CstatTestServer* CstatTestServer::NewL()
{
CstatTestServer *server = new(ELeave) CstatTestServer();
CleanupStack::PushL(server);
//server->ConstructL(KServerName);
RProcess handle = RProcess();
TParsePtrC serverName(handle.FileName());
server->StartL(serverName.Name());
CleanupStack::Pop(server);
return server;
}
static void InitCommsL()
{
TInt ret = User::LoadPhysicalDevice(PDD_NAME);
User::LeaveIfError(ret == KErrAlreadyExists?KErrNone:ret);
#ifndef __WINS__
ret = User::LoadPhysicalDevice(PDD2_NAME);
ret = User::LoadPhysicalDevice(PDD3_NAME);
ret = User::LoadPhysicalDevice(PDD4_NAME);
#endif
ret = User::LoadLogicalDevice(LDD_NAME);
User::LeaveIfError(ret == KErrAlreadyExists?KErrNone:ret);
ret = StartC32();
User::LeaveIfError(ret == KErrAlreadyExists?KErrNone:ret);
}
LOCAL_C void MainL()
{
// Leave the hooks in for platform security
#if (defined __DATA_CAGING__)
RProcess().DataCaging(RProcess::EDataCagingOn);
RProcess().SecureApi(RProcess::ESecureApiOn);
#endif
//InitCommsL();
CActiveScheduler* sched=NULL;
sched=new(ELeave) CActiveScheduler;
CActiveScheduler::Install(sched);
CstatTestServer* server = NULL;
// Create the CTestServer derived server
TRAPD(err, server = CstatTestServer::NewL());
if(!err)
{
// Sync with the client and enter the active scheduler
RProcess::Rendezvous(KErrNone);
sched->Start();
}
delete server;
delete sched;
}
/**
* Server entry point
* @return Standard Epoc error code on exit
*/
TInt main()
{
__UHEAP_MARK;
CTrapCleanup* cleanup = CTrapCleanup::New();
if(cleanup == NULL)
{
return KErrNoMemory;
}
TRAP_IGNORE(MainL());
delete cleanup;
__UHEAP_MARKEND;
return KErrNone;
}
CTestStep* CstatTestServer::CreateTestStep(const TDesC& aStepName)
{
CTestStep* testStep = NULL;
// This server creates just one step but create as many as you want
// They are created "just in time" when the worker thread is created
// install steps
//steps for captest.
if(aStepName == Kmkdirsys)
{
testStep = new CTeststat(aStepName);
}
if(aStepName == Kmkdirprivate)
{
testStep = new CTeststat(aStepName);
}
if(aStepName == Klstatsys)
{
testStep = new CTeststat(aStepName);
}
if(aStepName == Klstatprivate)
{
testStep = new CTeststat(aStepName);
}
if(aStepName == Kstatsys)
{
testStep = new CTeststat(aStepName);
}
if(aStepName == Kstatprivate)
{
testStep = new CTeststat(aStepName);
}
if(aStepName == Kmkfifosys)
{
testStep = new CTeststat(aStepName);
}
if(aStepName == Kmkfifoprivate)
{
testStep = new CTeststat(aStepName);
}
if(aStepName == Kchmodsys)
{
testStep = new CTeststat(aStepName);
}
if(aStepName == Kchmodprivate)
{
testStep = new CTeststat(aStepName);
}
return testStep;
}
| [
"none@none"
]
| [
[
[
1,
187
]
]
]
|
f80b65ea237cdaf5b4686f391a5c961c4c505f35 | e0a426344215b99185a0cbf34c65fc6aedb5bb33 | /Equinoccio/Parsers/ParserPhp/ParserPHP.h | da5b95df439abcd697b9e2b5fdd9f7e8328b42c3 | []
| no_license | Bloodclot24/equinoccio | 6f9d2179957467a805db554824722c99ad7f10a2 | 69b2f35ace63361751712d76df6d2640321c6f43 | refs/heads/master | 2021-01-23T12:16:45.024020 | 2009-12-10T18:45:49 | 2009-12-10T18:45:49 | 32,809,142 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 259 | h | #ifndef PARSERPHP_H_
#define PARSERPHP_H_
#include "../ParserGenerico/ParserGenerico.h"
class ParserPhp: public ParserGenerico {
private:
static const char* validas[];
public:
ParserPhp(uint32_t cantMaxReg);
};
#endif /* PARSERPHP_H_ */
| [
"vero13@c73f237e-9c17-11de-bb5f-cdebcd2927f5",
"[email protected]@c73f237e-9c17-11de-bb5f-cdebcd2927f5"
]
| [
[
[
1,
2
],
[
4,
4
],
[
6,
6
],
[
8,
9
],
[
11,
13
],
[
15,
15
]
],
[
[
3,
3
],
[
5,
5
],
[
7,
7
],
[
10,
10
],
[
14,
14
]
]
]
|
3667b32d04152db323c86ccbc155f2998f116536 | e07af5d5401cec17dc0bbf6dea61f6c048f07787 | /server.cpp | 6b379fabbdd33e1ababde319022e080730cc15d7 | []
| no_license | Mosesofmason/nineo | 4189c378026f46441498a021d8571f75579ce55e | c7f774d83a7a1f59fde1ac089fde9aa0b0182d83 | refs/heads/master | 2016-08-04T16:33:00.101017 | 2009-12-26T15:25:54 | 2009-12-26T15:25:54 | 32,200,899 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,627 | cpp | ////////////////////////////////////////////////////////////////////////////////
////////// Author: newblue <[email protected]>
////////// Copyright by newblue, 2008.
////////////////////////////////////////////////////////////////////////////////
#include "server.hpp"
namespace NiServer
{
Server::Server ()
: m_port (119)
{}
Server::Server ( const wxString& label, const wxString& address,
const wxString& port, const wxString& user,
const wxString& pass )
: m_label ( label ), m_address ( address ), m_user (user), m_pass ( pass )
{
SetPort (port);
}
Server::Server ( const wxString& label,
const wxString& address, const unsigned int& port,
const wxString& user, const wxString& pass )
: m_label (label), m_address (address), m_port (port), m_user (user), m_pass (pass)
{}
Server::~Server ()
{}
void Server::SetLabel ( const wxString& label )
{
m_label = label;
}
wxString Server::GetLabel () const
{
return m_label;
}
void Server::SetAddress ( const wxString& address )
{
m_address = address;
}
wxString Server::GetAddress () const
{
return m_address;
}
void Server::SetPort ( const wxString& port )
{
if ( port.IsNumber () )
SetPort ( wxAtoi (port) );
}
void Server::SetPort ( const unsigned int& port )
{
m_port = port;
}
unsigned int Server::GetPort () const
{
return m_port;
}
void Server::SetUsername ( const wxString& user )
{
m_user = user;
}
wxString Server::GetUsername () const
{
return m_user;
}
void Server::SetPassword ( const wxString& pass )
{
m_pass = pass;
}
wxString Server::GetPassword () const
{
return m_pass;
}
NiUtils::HASH Server::Hash () const
{
return NiUtils::NiHash ( m_address );
}
#if 0
bool Server::operator== ( const Server& server )
{
return ( m_label == server.GetLabel () || m_address == server.GetAddress());
}
#endif
#if 0
bool Server::operator== ( const NiGroup::SubGroup& group ) const
{
wxString server = group.GetServer ();
return (
GetAddress () == server
||
GetAddress () == server
);
}
#endif
wxIPV4address Server::GetIPV4 () const
{
wxIPV4address address;
address.Hostname ( m_address );
address.Service ( m_port );
return address;
}
bool Server::RequireAuthinfo () const
{
return ( !m_user.IsEmpty() && !m_pass.IsEmpty() );
}
BEGIN_EVENT_TABLE ( NiServerDialog, wxDialog )
EVT_CHECKBOX ( ID_LOGIN, NiServerDialog::OnCheckbox )
EVT_TEXT ( ID_LABEL, NiServerDialog::OnEnter )
EVT_TEXT ( ID_ADDRESS, NiServerDialog::OnEnter )
EVT_TEXT ( ID_PORT, NiServerDialog::OnEnter )
EVT_TEXT ( ID_USER, NiServerDialog::OnEnter )
EVT_TEXT ( ID_PASS, NiServerDialog::OnEnter )
EVT_BUTTON ( wxID_OK, NiServerDialog::OnOk )
END_EVENT_TABLE ()
NiServerDialog::NiServerDialog ( wxWindow* parent, wxWindowID id, Server& server,
const wxString& title )
: m_server (server), wxDialog ( parent, id, title )
{
DoUI ();
Centre ();
}
NiServerDialog::~NiServerDialog ()
{
}
void NiServerDialog::OnOk ( wxCommandEvent& event )
{
if ( IsModal () )
{
wxTextCtrl *name, *address, *port, *user, *pass;
wxCheckBox *login;
name = dynamic_cast <wxTextCtrl*> ( FindWindow(ID_LABEL) );
address = dynamic_cast <wxTextCtrl*> ( FindWindow(ID_ADDRESS) );
port = dynamic_cast <wxTextCtrl*> ( FindWindow(ID_PORT) );
user = dynamic_cast <wxTextCtrl*> ( FindWindow(ID_USER) );
pass = dynamic_cast <wxTextCtrl*> ( FindWindow(ID_PASS) );
login = dynamic_cast <wxCheckBox*> ( FindWindow(ID_LOGIN) );
wxASSERT ( name != NULL && address != NULL && port != NULL );
wxASSERT ( user != NULL && pass != NULL && login != NULL );
m_server.SetLabel ( name->GetValue () );
m_server.SetAddress ( address->GetValue () );
m_server.SetPort ( port->GetValue () );
m_server.SetUsername ( user->GetValue () );
m_server.SetPassword ( pass->GetValue () );
EndModal (wxOK);
}
}
void NiServerDialog::OnCheckbox ( wxCommandEvent& event )
{
Checkbox (event.IsChecked ());
wxButton *ok = dynamic_cast <wxButton*> ( FindWindow (wxID_OK) );
wxTextCtrl *user = dynamic_cast <wxTextCtrl*> ( FindWindow (ID_USER) );
wxASSERT ( ok != NULL && user != NULL );
ok->Enable ( CheckInput () );
user->SetFocus ();
}
void NiServerDialog::OnEnter ( wxCommandEvent& event )
{
wxButton *ok = dynamic_cast <wxButton*> ( FindWindow (wxID_OK) );
wxASSERT ( ok != NULL );
ok->Enable (CheckInput ());
}
void NiServerDialog::Checkbox ( const bool& check )
{
wxStaticText *luser, *lpass;
wxTextCtrl *tuser, *tpass;
luser = dynamic_cast <wxStaticText*> ( FindWindow ( ID_LABEL_USER ) );
lpass = dynamic_cast <wxStaticText*> ( FindWindow ( ID_LABEL_PASS ) );
tuser = dynamic_cast <wxTextCtrl*> ( FindWindow ( ID_USER ) );
tpass = dynamic_cast <wxTextCtrl*> ( FindWindow ( ID_PASS ) );
wxASSERT ( luser != NULL && lpass != NULL && tuser != NULL && tpass != NULL );
luser->Enable (check);
lpass->Enable (check);
tuser->Enable (check);
tpass->Enable (check);
}
bool NiServerDialog::CheckInput ()
{
wxTextCtrl *tname, *taddress, *tport, *tuser, *tpass;
wxCheckBox *login;
tname = dynamic_cast <wxTextCtrl*> ( FindWindow (ID_LABEL) );
taddress = dynamic_cast <wxTextCtrl*> ( FindWindow (ID_ADDRESS) );
tport = dynamic_cast <wxTextCtrl*> ( FindWindow (ID_PORT) );
tuser = dynamic_cast <wxTextCtrl*> ( FindWindow (ID_USER) );
tpass = dynamic_cast <wxTextCtrl*> ( FindWindow (ID_PASS) );
login = dynamic_cast <wxCheckBox*> ( FindWindow (ID_LOGIN) );
wxASSERT ( tname != NULL && taddress != NULL && tport != NULL
&&
tuser != NULL && tpass != NULL && login != NULL );
bool isok = true;
if ( tname != NULL && tname->GetValue ().IsEmpty () ) isok = false;
if ( tport != NULL &&
(tport->GetValue ().IsEmpty () || !tport->GetValue().IsNumber ()) )
isok = false;
if ( taddress != NULL && taddress->GetValue ().IsEmpty () ) isok = false;
if ( login->GetValue ()
&& ( tuser->GetValue().IsEmpty () || tpass->GetValue().IsEmpty () ) )
{
isok = false;
}
return isok;
}
void NiServerDialog::DoUI ()
{
wxString name, address, port, user, pass;
name = m_server.GetLabel ();
address = m_server.GetAddress ();
port << m_server.GetPort ();
user = m_server.GetUsername ();
pass = m_server.GetPassword ();
wxStaticText *llabel, *laddress, *lport, *luser, *lpass;
llabel = new wxStaticText ( this, wxID_ANY, _("Name: ") );
laddress = new wxStaticText ( this, wxID_ANY, _("Address: "));
lport = new wxStaticText ( this, wxID_ANY, _("Port: "));
luser = new wxStaticText ( this, ID_LABEL_USER, _("User: "));
lpass = new wxStaticText ( this, ID_LABEL_PASS, _("Password:"));
wxASSERT ( llabel != NULL && laddress != NULL && lport != NULL
&&
luser != NULL && lpass != NULL );
wxTextCtrl *tlabel, *taddress, *tport, *tuser, *tpass;
tlabel = new wxTextCtrl ( this, ID_LABEL, wxEmptyString,
wxDefaultPosition, wxSize (200, -1),
wxBORDER_SIMPLE );
taddress = new wxTextCtrl ( this, ID_ADDRESS, wxEmptyString,
wxDefaultPosition, wxSize (200, -1),
wxBORDER_SIMPLE );
tport = new wxTextCtrl ( this, ID_PORT, wxEmptyString,
wxDefaultPosition, wxSize (60, -1),
wxBORDER_SIMPLE );
tuser = new wxTextCtrl ( this, ID_USER, wxEmptyString,
wxDefaultPosition, wxSize (200, -1),
wxBORDER_SIMPLE );
tpass = new wxTextCtrl ( this, ID_PASS, wxEmptyString,
wxDefaultPosition, wxSize (200, -1),
wxBORDER_SIMPLE|wxTE_PASSWORD );
wxASSERT ( tlabel != NULL && taddress != NULL && tport != NULL
&&
tuser != NULL && tpass != NULL );
wxCheckBox *login;
login = new wxCheckBox ( this, ID_LOGIN, _("This server need login!" ) );
wxButton *button_ok = NULL, *button_cancel = NULL;
button_ok = new wxButton ( this, wxID_OK, _("OK") );
button_cancel = new wxButton ( this, wxID_CANCEL, _("Cancel") );
wxASSERT ( login != NULL && button_ok != NULL && button_cancel != NULL );
login->SetValue ( !user.IsEmpty () && !pass.IsEmpty() );
wxString tip_name, tip_address, tip_port, tip_user, tip_pass;
tip_name = _("What is server name?\neg: newsgroup No.xx");
tip_address << _("What is server address?\neg:\n")
<< wxT("\tnews.yaako.com\n")
<< wxT("\tnews.cn99.com\n")
<< wxT("\tnews.newsfan.com");
tip_port = _("Which port to use?\ndefault newsgroup server port is 119");
tip_user = _("What is username to authinfo in this server?");
tip_pass = _("What is password to authinfo in this server?");
tlabel->SetValue ( name );
tlabel->SetToolTip (tip_name);
taddress->SetValue ( address );
taddress->SetToolTip (tip_address);
tport->SetValue ( port );
tport->SetToolTip (tip_port);
tuser->SetValue ( user );
tuser->SetToolTip (tip_user);
tpass->SetValue ( pass );
tpass->SetToolTip (tip_pass);
wxBoxSizer *main = new wxBoxSizer ( wxVERTICAL );
wxFlexGridSizer *form, *login_form, *button_sizer;
wxStaticBoxSizer *login_sizer;
form = new wxFlexGridSizer ( 2, 0, 0 );
login_form = new wxFlexGridSizer ( 2, 0, 0 );
login_sizer = new wxStaticBoxSizer ( wxVERTICAL, this, _("Require login: ") );
button_sizer = new wxFlexGridSizer ( 1, 5, 0, 0 );
this->SetSizer (main);
form->AddGrowableCol (1);
form->Add ( llabel, 0, wxALL, 2 );
form->Add ( tlabel, 0, wxALL, 2 );
form->Add ( laddress, 0, wxALL, 2 );
form->Add ( taddress, 0, wxALL, 2 );
form->Add ( lport, 0, wxALL, 2 );
form->Add ( tport, 0, wxALL, 2 );
login_form->Add ( luser, 0, wxALL, 2 );
login_form->Add ( tuser, 0, wxALL, 2 );
login_form->Add ( lpass, 0, wxALL, 2 );
login_form->Add ( tpass, 0, wxALL, 2 );
login_sizer->Add ( login, 0, wxALL, 2 );
login_sizer->Add ( login_form, 0, wxALL, 2 );
button_sizer->Add ( button_ok, 0, wxALL, 2 );
button_sizer->Add ( button_cancel, 0, wxALL, 2 );
main->Add ( form, 0, wxALL, 5 );
main->Add ( login_sizer, 0, wxALL, 5 );
main->Add ( button_sizer, 0, wxALL, 5 );
main->Fit (this);
main->SetSizeHints (this);
Checkbox ( login->GetValue () );
button_ok->Enable ( CheckInput () );
tlabel->SetFocus ();
}
}
| [
"[email protected]"
]
| [
[
[
1,
310
]
]
]
|
322206ce79b58d713428b78727000f4c684f4a0c | 0b66a94448cb545504692eafa3a32f435cdf92fa | /branches/kyr/cbear.berlios.de/windows/com/byte.hpp | 0e2dda9072aa72fbc4866726877dc4ffd5b3affc | [
"MIT"
]
| permissive | BackupTheBerlios/cbear-svn | e6629dfa5175776fbc41510e2f46ff4ff4280f08 | 0109296039b505d71dc215a0b256f73b1a60b3af | refs/heads/master | 2021-03-12T22:51:43.491728 | 2007-09-28T01:13:48 | 2007-09-28T01:13:48 | 40,608,034 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 340 | hpp | #ifndef CBEAR_BERLIOS_DE_WINDOWS_COM_BYTE_HPP_INCLUDED
#define CBEAR_BERLIOS_DE_WINDOWS_COM_BYTE_HPP_INCLUDED
#include <cbear.berlios.de/windows/com/traits.hpp>
namespace cbear_berlios_de
{
namespace windows
{
namespace com
{
CBEAR_BERLIOS_DE_WINDOWS_COM_DECLARE_DEFAULT_TRAITS(byte_t, vartype_t::ui1);
}
}
}
#endif
| [
"sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838"
]
| [
[
[
1,
19
]
]
]
|
6dc1511ce2fbddc853a6d7b70bc4ee458544ae4c | c13ef26a8b4b1e196c6c593a73520787a7c15b80 | /samples_atistream/Histogram/Histogram.hpp | 95eaa93a52fb013170af0b35916f7ec4e0d1b6e3 | []
| no_license | ajaykumarkannan/simulation-opencl | 73072dcdacf5f3c93e0c038caedb60b479839327 | 53d00629358d3a2b1135f4daf0c327436fd9ed79 | refs/heads/master | 2021-01-23T08:39:00.347158 | 2010-03-09T15:43:50 | 2010-03-09T15:43:50 | 37,275,925 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,555 | hpp | /* ============================================================
Copyright (c) 2009 Advanced Micro Devices, Inc. All rights reserved.
Redistribution and use of this material is permitted under the following
conditions:
Redistributions must retain the above copyright notice and all terms of this
license.
In no event shall anyone redistributing or accessing or using this material
commence or participate in any arbitration or legal action relating to this
material against Advanced Micro Devices, Inc. or any copyright holders or
contributors. The foregoing shall survive any expiration or termination of
this license or any agreement or access or use related to this material.
ANY BREACH OF ANY TERM OF THIS LICENSE SHALL RESULT IN THE IMMEDIATE REVOCATION
OF ALL RIGHTS TO REDISTRIBUTE, ACCESS OR USE THIS MATERIAL.
THIS MATERIAL IS PROVIDED BY ADVANCED MICRO DEVICES, INC. AND ANY COPYRIGHT
HOLDERS AND CONTRIBUTORS "AS IS" IN ITS CURRENT CONDITION AND WITHOUT ANY
REPRESENTATIONS, GUARANTEE, OR WARRANTY OF ANY KIND OR IN ANY WAY RELATED TO
SUPPORT, INDEMNITY, ERROR FREE OR UNINTERRUPTED OPERA TION, OR THAT IT IS FREE
FROM DEFECTS OR VIRUSES. ALL OBLIGATIONS ARE HEREBY DISCLAIMED - WHETHER
EXPRESS, IMPLIED, OR STATUTORY - INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
ACCURACY, COMPLETENESS, OPERABILITY, QUALITY OF SERVICE, OR NON-INFRINGEMENT.
IN NO EVENT SHALL ADVANCED MICRO DEVICES, INC. OR ANY COPYRIGHT HOLDERS OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, PUNITIVE,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, REVENUE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED OR BASED ON ANY THEORY OF LIABILITY
ARISING IN ANY WAY RELATED TO THIS MATERIAL, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE. THE ENTIRE AND AGGREGATE LIABILITY OF ADVANCED MICRO DEVICES,
INC. AND ANY COPYRIGHT HOLDERS AND CONTRIBUTORS SHALL NOT EXCEED TEN DOLLARS
(US $10.00). ANYONE REDISTRIBUTING OR ACCESSING OR USING THIS MATERIAL ACCEPTS
THIS ALLOCATION OF RISK AND AGREES TO RELEASE ADVANCED MICRO DEVICES, INC. AND
ANY COPYRIGHT HOLDERS AND CONTRIBUTORS FROM ANY AND ALL LIABILITIES,
OBLIGATIONS, CLAIMS, OR DEMANDS IN EXCESS OF TEN DOLLARS (US $10.00). THE
FOREGOING ARE ESSENTIAL TERMS OF THIS LICENSE AND, IF ANY OF THESE TERMS ARE
CONSTRUED AS UNENFORCEABLE, FAIL IN ESSENTIAL PURPOSE, OR BECOME VOID OR
DETRIMENTAL TO ADVANCED MICRO DEVICES, INC. OR ANY COPYRIGHT HOLDERS OR
CONTRIBUTORS FOR ANY REASON, THEN ALL RIGHTS TO REDISTRIBUTE, ACCESS OR USE
THIS MATERIAL SHALL TERMINATE IMMEDIATELY. MOREOVER, THE FOREGOING SHALL
SURVIVE ANY EXPIRATION OR TERMINATION OF THIS LICENSE OR ANY AGREEMENT OR
ACCESS OR USE RELATED TO THIS MATERIAL.
NOTICE IS HEREBY PROVIDED, AND BY REDISTRIBUTING OR ACCESSING OR USING THIS
MATERIAL SUCH NOTICE IS ACKNOWLEDGED, THAT THIS MATERIAL MAY BE SUBJECT TO
RESTRICTIONS UNDER THE LAWS AND REGULATIONS OF THE UNITED STATES OR OTHER
COUNTRIES, WHICH INCLUDE BUT ARE NOT LIMITED TO, U.S. EXPORT CONTROL LAWS SUCH
AS THE EXPORT ADMINISTRATION REGULATIONS AND NATIONAL SECURITY CONTROLS AS
DEFINED THEREUNDER, AS WELL AS STATE DEPARTMENT CONTROLS UNDER THE U.S.
MUNITIONS LIST. THIS MATERIAL MAY NOT BE USED, RELEASED, TRANSFERRED, IMPORTED,
EXPORTED AND/OR RE-EXPORTED IN ANY MANNER PROHIBITED UNDER ANY APPLICABLE LAWS,
INCLUDING U.S. EXPORT CONTROL LAWS REGARDING SPECIFICALLY DESIGNATED PERSONS,
COUNTRIES AND NATIONALS OF COUNTRIES SUBJECT TO NATIONAL SECURITY CONTROLS.
MOREOVER, THE FOREGOING SHALL SURVIVE ANY EXPIRATION OR TERMINATION OF ANY
LICENSE OR AGREEMENT OR ACCESS OR USE RELATED TO THIS MATERIAL.
NOTICE REGARDING THE U.S. GOVERNMENT AND DOD AGENCIES: This material is
provided with "RESTRICTED RIGHTS" and/or "LIMITED RIGHTS" as applicable to
computer software and technical data, respectively. Use, duplication,
distribution or disclosure by the U.S. Government and/or DOD agencies is
subject to the full extent of restrictions in all applicable regulations,
including those found at FAR52.227 and DFARS252.227 et seq. and any successor
regulations thereof. Use of this material by the U.S. Government and/or DOD
agencies is acknowledgment of the proprietary rights of any copyright holders
and contributors, including those of Advanced Micro Devices, Inc., as well as
the provisions of FAR52.227-14 through 23 regarding privately developed and/or
commercial computer software.
This license forms the entire agreement regarding the subject matter hereof and
supersedes all proposals and prior discussions and writings between the parties
with respect thereto. This license does not affect any ownership, rights, title,
or interest in, or relating to, this material. No terms of this license can be
modified or waived, and no breach of this license can be excused, unless done
so in a writing signed by all affected parties. Each term of this license is
separately enforceable. If any term of this license is determined to be or
becomes unenforceable or illegal, such term shall be reformed to the minimum
extent necessary in order for this license to remain in effect in accordance
with its terms as modified by such reformation. This license shall be governed
by and construed in accordance with the laws of the State of Texas without
regard to rules on conflicts of law of any state or jurisdiction or the United
Nations Convention on the International Sale of Goods. All disputes arising out
of this license shall be subject to the jurisdiction of the federal and state
courts in Austin, Texas, and all defenses are hereby waived concerning personal
jurisdiction and venue of these courts.
============================================================ */
#ifndef HISTOGRAM_H_
#define HISTOGRAM_H_
#include <CL/cl.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <SDKUtil/SDKCommon.hpp>
#include <SDKUtil/SDKApplication.hpp>
#include <SDKUtil/SDKCommandArgs.hpp>
#include <SDKUtil/SDKFile.hpp>
#define WIDTH 1024
#define HEIGHT 1024
#define BIN_SIZE 256
#define GROUP_SIZE 128
#define SUB_HISTOGRAM_COUNT ((WIDTH * HEIGHT) /(GROUP_SIZE * BIN_SIZE))
/**
* Histogram
* Class implements 256 Histogram bin implementation
* Derived from SDKSample base class
*/
class Histogram : public SDKSample
{
cl_int binSize; /**< Size of Histogram bin */
cl_int groupSize; /**< Number of threads in group */
cl_int subHistgCnt; /**< Sub histogram count */
cl_uint *data; /**< input data initialized with normalized(0 - binSize) random values */
cl_int width; /**< width of the input */
cl_int height; /**< height of the input */
cl_uint *hostBin; /**< Host result for histogram bin */
cl_uint *midDeviceBin; /**< Intermittent sub-histogram bins */
cl_uint *deviceBin; /**< Device result for histogram bin */
cl_double setupTime; /**< time taken to setup OpenCL resources and building kernel */
cl_double kernelTime; /**< time taken to run kernel and read result back */
size_t maxWorkGroupSize; /**< Max allowed work-items in a group */
cl_uint maxDimensions; /**< Max group dimensions allowed */
size_t * maxWorkItemSizes; /**< Max work-items sizes in each dimensions */
cl_ulong totalLocalMemory; /**< Max local memory allowed */
cl_ulong usedLocalMemory; /**< Used local memory */
cl_context context; /**< CL context */
cl_device_id *devices; /**< CL device list */
cl_mem dataBuf; /**< CL memory buffer for data */
cl_mem midDeviceBinBuf; /**< CL memory buffer for intermittent device bin */
cl_mem deviceBinBuf; /**< CL memory buffer for deviceBin */
cl_command_queue commandQueue; /**< CL command queue */
cl_program program; /**< CL program */
cl_kernel kernel; /**< CL kernel */
cl_bool byteRWSupport;
public:
/**
* Constructor
* Initialize member variables
* @param name name of sample (string)
*/
Histogram(std::string name)
: SDKSample(name),
binSize(BIN_SIZE),
groupSize(GROUP_SIZE),
setupTime(0),
kernelTime(0),
subHistgCnt(SUB_HISTOGRAM_COUNT),
data(NULL),
hostBin(NULL),
midDeviceBin(NULL),
deviceBin(NULL),
devices(NULL),
maxWorkItemSizes(NULL),
byteRWSupport(true)
{
/* Set default values for width and height */
width = WIDTH;
height = HEIGHT;
}
/**
* Constructor
* Initialize member variables
* @param name name of sample (const char*)
*/
Histogram(const char* name)
: SDKSample(name),
binSize(BIN_SIZE),
groupSize(GROUP_SIZE),
setupTime(0),
kernelTime(0),
subHistgCnt(SUB_HISTOGRAM_COUNT),
data(NULL),
hostBin(NULL),
midDeviceBin(NULL),
deviceBin(NULL),
devices(NULL),
maxWorkItemSizes(NULL),
byteRWSupport(true)
{
/* Set default values for width and height */
width = WIDTH;
height = HEIGHT;
}
~Histogram()
{
if(data)
{
free(data);
data = NULL;
}
if(hostBin)
{
free(hostBin);
hostBin = NULL;
}
if(midDeviceBin)
{
free(midDeviceBin);
midDeviceBin = NULL;
}
if(deviceBin)
{
free(deviceBin);
deviceBin = NULL;
}
if(devices)
{
free(devices);
devices = NULL;
}
if(maxWorkItemSizes)
{
free(maxWorkItemSizes);
maxWorkItemSizes = NULL;
}
}
/**
* Allocate and initialize required host memory with appropriate values
* @return 1 on success and 0 on failure
*/
int setupHistogram();
/**
* OpenCL related initialisations.
* Set up Context, Device list, Command Queue, Memory buffers
* Build CL kernel program executable
* @return 1 on success and 0 on failure
*/
int setupCL();
/**
* Set values for kernels' arguments, enqueue calls to the kernels
* on to the command queue, wait till end of kernel execution.
* Get kernel start and end time if timing is enabled
* @return 1 on success and 0 on failure
*/
int runCLKernels();
/**
* Override from SDKSample. Print sample stats.
*/
void printStats();
/**
* Override from SDKSample. Initialize
* command line parser, add custom options
*/
int initialize();
/**
* Override from SDKSample, adjust width and height
* of execution domain, perform all sample setup
*/
int setup();
/**
* Override from SDKSample
* Run OpenCL Black-Scholes
*/
int run();
/**
* Override from SDKSample
* Cleanup memory allocations
*/
int cleanup();
/**
* Override from SDKSample
* Verify against reference implementation
*/
int verifyResults();
private:
/**
* Calculate histogram bin on host
*/
void calculateHostBin();
};
#endif
| [
"juergen.broder@c62875e2-cac2-11de-a9c8-2fbcfba63733"
]
| [
[
[
1,
313
]
]
]
|
b49d3d26cc7dc5c64f4f212e58cd47e60387f8b0 | b2d46af9c6152323ce240374afc998c1574db71f | /cursovideojuegos/theflostiproject/3rdParty/boost/libs/config/test/has_pthread_delay_np_fail.cpp | 9a8b0e55adeef09234cf7369fb832471a7f6a0d6 | []
| no_license | bugbit/cipsaoscar | 601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4 | 52aa8b4b67d48f59e46cb43527480f8b3552e96d | refs/heads/master | 2021-01-10T21:31:18.653163 | 2011-09-28T16:39:12 | 2011-09-28T16:39:12 | 33,032,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,215 | cpp |
// This file was automatically generated on Sun Jul 25 11:47:49 GMTDT 2004,
// by libs/config/tools/generate
// Copyright John Maddock 2002-4.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/config for the most recent version.
// Test file for macro BOOST_HAS_PTHREAD_DELAY_NP
// This file should not compile, if it does then
// BOOST_HAS_PTHREAD_DELAY_NP may be defined.
// see boost_has_pthread_delay_np.ipp for more details
// Do not edit this file, it was generated automatically by
// ../tools/generate from boost_has_pthread_delay_np.ipp on
// Sun Jul 25 11:47:49 GMTDT 2004
// Must not have BOOST_ASSERT_CONFIG set; it defeats
// the objective of this file:
#ifdef BOOST_ASSERT_CONFIG
# undef BOOST_ASSERT_CONFIG
#endif
#include <boost/config.hpp>
#include "test.hpp"
#ifndef BOOST_HAS_PTHREAD_DELAY_NP
#include "boost_has_pthread_delay_np.ipp"
#else
#error "this file should not compile"
#endif
int main( int, char *[] )
{
return boost_has_pthread_delay_np::test();
}
| [
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
]
| [
[
[
1,
39
]
]
]
|
5fcff88629419502b9b8ec2a6159089af8a3fee9 | 0ce35229d1698224907e00f1fdfb34cfac5db1a2 | /Moto.h | 6dd1a0294040e80c7d5a48c7d2c09ce35b7c872f | []
| no_license | manudss/efreiloca | f7b1089b6ba74ff26e6320044f66f9401ebca21b | 54e8c4af1aace11f35846e63880a893e412b3309 | refs/heads/master | 2020-06-05T17:34:02.234617 | 2007-06-04T19:12:15 | 2007-06-04T19:12:15 | 32,325,713 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 115 | h | #pragma once
#include "vehicule.h"
class Moto :
public vehicule
{
public:
Moto(void);
~Moto(void);
};
| [
"pootoonet@65b228c9-682f-0410-abd1-c3b8cf015911"
]
| [
[
[
1,
10
]
]
]
|
3652664290dbfa052369c9a9e72971f98709d638 | f4b649f3f48ad288550762f4439fcfffddc08d0e | /eRacer/Source/Graphics/FontManager.h | 283ba18bb7a9c935f35feeb64f410c6db55d29cb | []
| no_license | Knio/eRacer | 0fa27c8f7d1430952a98ac2896ab8b8ee87116e7 | 65941230b8bed458548a920a6eac84ad23c561b8 | refs/heads/master | 2023-09-01T16:02:58.232341 | 2010-04-26T23:58:20 | 2010-04-26T23:58:20 | 506,897 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,234 | h | #pragma once
#ifndef FONTMANAGER_H
#define FONTMANAGER_H
#include <d3d9.h>
#include <d3dx9.h>
#include <map>
#include <string>
#include <vector>
#include <algorithm>
#include "Renderable.h"
#include "../Core/Math.h"
using namespace std;
namespace Graphics {
typedef pair<string, int> FontDescription;
class StringRenderable
{
public:
ID3DXFont* m_pFont;
string m_strTextBuffer;
long m_uiScreenX;
long m_uiScreenY;
D3DXCOLOR m_color;
ID3DXSprite* m_pTextSprite;
StringRenderable(ID3DXSprite* targetSprite);
~StringRenderable();
/**
* @brief Comparison operator for sorting - sorts by the address of the font used
*/
bool operator<(const StringRenderable& s) const;
};
class FontManager
{
public:
const static char* CUSTOM_FONTS[1];
static FontManager instance;
FontManager();
~FontManager();
StringRenderable CreateStringRenderable( const char* msg,
const char* fontFamily,
int fontSize,
long x,
long y,
const Vector3 &color,
ID3DXSprite* sprite);
void Shutdown();
private:
map<FontDescription, ID3DXFont*> cache;
};
};
#endif | [
"[email protected]",
"[email protected]",
"[email protected]"
]
| [
[
[
1,
7
],
[
9,
9
],
[
13,
14
],
[
17,
18
],
[
22,
24
],
[
28,
28
],
[
30,
30
],
[
32,
32
],
[
38,
43
],
[
49,
51
],
[
59,
59
],
[
63,
66
]
],
[
[
8,
8
],
[
15,
16
],
[
25,
25
]
],
[
[
10,
12
],
[
19,
21
],
[
26,
27
],
[
29,
29
],
[
31,
31
],
[
33,
37
],
[
44,
48
],
[
52,
58
],
[
60,
62
]
]
]
|
dd2d9824fd557816772bc92d86f38b6dfb990972 | 4c49943d28c7acb2c54c46c1b9c90b83edce8383 | /Canvas/stdafx.cpp | 7b77f9214c88c5897f7955223f4be633624d6c2a | []
| no_license | flier/HTML5i | 68f4bcec7093f330b159f64976250ca5f974bca7 | 980ad8c112761471665c8acfc5064d1a87a8f32a | refs/heads/master | 2020-03-27T05:08:04.843399 | 2011-03-26T18:02:38 | 2011-03-26T18:02:38 | 1,498,619 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 293 | cpp | // stdafx.cpp : source file that includes just the standard includes
// Canvas.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"[email protected]"
]
| [
[
[
1,
8
]
]
]
|
b427dff59c18317217fe81a2f7d53451c4da0503 | fac8de123987842827a68da1b580f1361926ab67 | /inc/physics/Physics/Collide/Dispatch/BroadPhase/hkpTypedBroadPhaseHandle.inl | a19a4d72951ad60939e2cbc7118468b89ac02922 | []
| 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,637 | inl | /*
*
* 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.
*
*/
void hkpTypedBroadPhaseHandle::setOwner(void* o)
{
hkInt32 offset = hkGetByteOffsetInt(this, o);
// +127 is 'offset invalid' flag.
HK_ASSERT2( 0xfe456f34, offset > -128 && offset < 127, "Can't store offset to typed broadphase handle owner (more than 128 bytes difference).");
m_ownerOffset = static_cast<hkInt8>( offset );
}
hkpTypedBroadPhaseHandle::hkpTypedBroadPhaseHandle( int type )
{
m_type = static_cast<hkInt8>(type);
m_collisionFilterInfo = 0;
m_objectQualityType = HK_COLLIDABLE_QUALITY_INVALID;
m_ownerOffset = OFFSET_INVALID;
}
hkpTypedBroadPhaseHandle::hkpTypedBroadPhaseHandle( void* owner, int type )
{
m_type = static_cast<hkInt8>(type);
m_collisionFilterInfo = 0;
m_objectQualityType = HK_COLLIDABLE_QUALITY_INVALID;
setOwner(owner);
}
int hkpTypedBroadPhaseHandle::getType() const
{
return m_type;
}
void hkpTypedBroadPhaseHandle::setType( int type )
{
m_type = static_cast<hkInt8>(type);
}
void* hkpTypedBroadPhaseHandle::getOwner() const
{
HK_ASSERT2( 0xfe456f35, m_ownerOffset != OFFSET_INVALID, "Owner offset for typed broadphase handle incorrect. Did you call setOwner()?" );
return const_cast<char*>( reinterpret_cast<const char*>(this) + m_ownerOffset );
}
hkUint32 hkpTypedBroadPhaseHandle::getCollisionFilterInfo() const
{
return m_collisionFilterInfo;
}
void hkpTypedBroadPhaseHandle::setCollisionFilterInfo( hkUint32 info )
{
m_collisionFilterInfo = info;
}
/*
* 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,
74
]
]
]
|
1ea1879f586cb35f1ffac8032cb2b5847c16d45d | fbe2cbeb947664ba278ba30ce713810676a2c412 | /iptv_root/sbVB/VBLib_6_2/src/VBLib/VBDate.cpp | 233a77250c0c30fd4bc7ab6c88084ccf5000cae5 | []
| no_license | abhipr1/multitv | 0b3b863bfb61b83c30053b15688b070d4149ca0b | 6a93bf9122ddbcc1971dead3ab3be8faea5e53d8 | refs/heads/master | 2020-12-24T15:13:44.511555 | 2009-06-04T17:11:02 | 2009-06-04T17:11:02 | 41,107,043 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,765 | cpp | // VBDate.cpp
#include "VBLib/VBLib.h"
#ifdef WIN32
// Windows code
#else
// Unix code
#include <sys/time.h>
#endif
/////////////////////////////////////////////////////////////////
//
// class VBDate
//
/////////////////////////////////////////////////////////////////
// static member initialization
// jan fev mar apr may jun jul ago sep oct nov dec
const int br::com::sbVB::VBLib::VBDate::VBDaysInMonths[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
// set base date if given date is valid. Do nothing otherwise
// ATTENTION: does not change m_baseWeekDay !
bool br::com::sbVB::VBLib::VBDate::p_setDate(int year, int month, int day)
{
bool OK = validDate(year,month,day);
if (!OK) return false;
m_baseYear = year;
m_baseMonth = (VBMonths) month;
m_baseDay = day;
return true;
}
// default constructor
br::com::sbVB::VBLib::VBDate::VBDate()
{
m_baseYear = 2001;
m_baseMonth = VBapr;
m_baseDay = 21;
m_baseWeekDay = VBsat;
}
#if 0 // commented out begin
struct tm {
int tm_sec; // seconds after the minute - [0,59]
int tm_min; // minutes after the hour - [0,59]
int tm_hour; // hours since midnight - [0,23]
int tm_mday; // day of the month - [1,31]
int tm_mon; // months since January - [0,11]
int tm_year; // years since 1900
int tm_wday; // days since Sunday - [0,6]
int tm_yday; // days since January 1 - [0,365]
int tm_isdst; // daylight savings time flag
};
time_t ltime;
tm *t;
time( <ime ); // get time and date
t = localtime( <ime ); // convert to struct tm
// display
cout << "Now is:" << endl;
cout << "Time: " << t->tm_hour << ":" << t->tm_min
<< ":" << t->tm_sec << endl;
cout << "Year: " << t->tm_year + 1900 << endl;
cout << "Month: " << months[t->tm_mon] << endl;
cout << "Day: " << t->tm_mday << endl;
cout << "Week day: " << weekDay[t->tm_wday] << endl;
#endif // commented out end
void br::com::sbVB::VBLib::VBDate::setSystemDate()
{
time_t ltime;
tm *t;
time( <ime ); // get time and date
t = localtime( <ime ); // convert to struct tm
setDate(t->tm_year + 1900, t->tm_mon, t->tm_mday);
}
bool br::com::sbVB::VBLib::VBDate::leapYear (int year) const
{
int k = year % 4; // every 4 years, force leap year true
bool ret = (k == 0);
k = year % 100; // over previous, every 100 years, force leap year false
ret = ret && !(k == 0);
k = year % 400; // over previous, every 400 years, force leap year true
ret = ret || (k == 0);
return ret;
}
int br::com::sbVB::VBLib::VBDate::daysInAYear(int year) const
{
int ret = 365;
if (leapYear(year))
ret++;
return ret;
}
int br::com::sbVB::VBLib::VBDate::daysInAMonth(int year, int month) const
{
// if (!validDate(year,month,1)) return -1;
// can't test valid date, because validDate calls daysInAMonth
int ret;
ret = VBDaysInMonths[month];
if (leapYear(year) && (month==VBfeb))
ret++;
return ret;
}
bool br::com::sbVB::VBLib::VBDate::validDate(int year, int month, int day) const
{
if (month < VBjan || month > VBdec ) return false;
if (day <= 0 || day > daysInAMonth(year,month)) return false;
return true;
}
bool br::com::sbVB::VBLib::VBDate::isFuture(int year, int month, int day) const
{
if (year > m_baseYear) return true;
if (year < m_baseYear) return false;
if (month > m_baseMonth) return true;
if (month < m_baseMonth) return false;
if (day > m_baseDay) return true;
return false;
}
int br::com::sbVB::VBLib::VBDate::remainingDaysOfGivenMonth(int year, int month, int day) const
{
if (!validDate(year,month,day)) return -1;
return daysInAMonth(year,month) - day;
}
int br::com::sbVB::VBLib::VBDate::remainingDaysOfGivenYearFromNextMonthOn(int year, int month) const
{
if (!validDate(year,month,1)) return -1;
int ret=0;
for (int m = month+1 ; m < 12 ; m++)
ret += daysInAMonth(year,m);
return ret;
}
int br::com::sbVB::VBLib::VBDate::remainingDaysofGivenYear(int year, int month, int day) const
{
int ret;
ret = remainingDaysOfGivenMonth(year,month,day);
ret += remainingDaysOfGivenYearFromNextMonthOn(year,month);
return ret;
}
long br::com::sbVB::VBLib::VBDate::numberOfDaysOfFullYearsFromNextYearToYearBeforeGivenYear(int year) const
{
long ret=0;
for (int y = m_baseYear+1 ; y < year ; y++)
ret += daysInAYear(y);
return ret;
}
int br::com::sbVB::VBLib::VBDate::numberOfDaysOfGivenYearUntilGivenDate(int year, int month, int day) const
{
if (!validDate(year,month,day)) return -1;
int ret=0;
for (int m = 0 ; m < month ; m++)
ret += daysInAMonth(year,m);
// after this loop, all days until previous month are already added
ret += day;
return ret;
}
bool br::com::sbVB::VBLib::VBDate::setDate(int year, int month, int day)
{
bool OK = validDate(year,month,day);
if (!OK) return false;
m_baseWeekDay = (VBWeekdays) getWeekDay(year,month,day);
p_setDate(year,month,day);
return true;
}
bool br::com::sbVB::VBLib::VBDate::setDate(VBDateTime dateTime)
{
return setDate(dateTime.m_tm.tm_year+1900,dateTime.m_tm.tm_mon,dateTime.m_tm.tm_mday);
}
bool br::com::sbVB::VBLib::VBDate::setDateYYYYMMDD(VBString date)
{
int year, month, day;
year = atoi(date.strInside(0,3));
month = atoi(date.strInside(4,5));
day = atoi(date.strInside(6,7));
return setDate(year, month-1, day);
}
bool br::com::sbVB::VBLib::VBDate::deltaDays(int year, int month, int day, long & delta) const
{
bool OK = validDate(year,month,day);
if (!OK) return false;
delta = 0;
if (year == m_baseYear && month == m_baseMonth && day == m_baseDay)
{
// given day is the same as base day
return true;
}
if (isFuture(year,month,day))
{
// cout << "DEBUG given date is future compared to base date" << endl;
if (year > m_baseYear)
{
// cout << "DEBUG given year is not the same as base year" << endl;
delta += remainingDaysofGivenYear(m_baseYear,m_baseMonth,m_baseDay);
delta += numberOfDaysOfFullYearsFromNextYearToYearBeforeGivenYear(year);
delta += numberOfDaysOfGivenYearUntilGivenDate(year,month,day);
}
else
{
// cout << "DEBUG given year is the same as base year << endl;
if (month > m_baseMonth)
{
// cout << "DEBUG given month is not the same as base month" << endl;
delta += remainingDaysOfGivenMonth(m_baseYear,m_baseMonth,m_baseDay);
// full months from next month, before given month
for (int m = m_baseMonth+1 ; m < month ; m++)
delta += daysInAMonth(year,m);
delta += day; // days in the given month
}
else
{
// cout << "DEBUG given month is the same as base month" << endl;
delta += day - m_baseDay;
}
}
}
else
{
// to solve the problem for the past, one can only invert the problem
// so that the problem becomes future (already solved)
br::com::sbVB::VBLib::VBDate aux;
aux.p_setDate(year,month,day); // here, setDate can not be used.
// if used, an infinite re-enntry loop is generated.
bool ret = aux.deltaDays(m_baseYear,m_baseMonth,m_baseDay,delta);
delta *= -1; // invert the delta to fix the inverted problem
return ret;
}
return true;
}
long br::com::sbVB::VBLib::VBDate::deltaDays(const VBDate & cal) const
{
long ret;
deltaDays(cal.m_baseYear,cal.m_baseMonth,cal.m_baseDay,ret);
return ret;
}
int br::com::sbVB::VBLib::VBDate::getWeekDay(const int year,const int month,const int day) const
{
bool OK = validDate(year,month,day);
if (!OK) return VBinvalid;
long delta;
deltaDays(year,month,day,delta);
// cout << "DEBUG delta=" << delta << endl;
// the code below is valid for both positive and negative delta
int k = delta % 7; // k is positive or negative
k += m_baseWeekDay + 7; // plus 7 to guarantee k > 0
return (k % 7); // return 0 ~ 6
}
int br::com::sbVB::VBLib::VBDate::getWeekDay() const
{
return getWeekDay(m_baseYear,m_baseMonth,m_baseDay);
}
br::com::sbVB::VBLib::VBDate br::com::sbVB::VBLib::VBDate::dateAfterDeltaDays(const long d) const
{
long deltaDays = d;
br::com::sbVB::VBLib::VBDate ret;
ret.setDate(m_baseYear,m_baseMonth,m_baseDay);
if (deltaDays > 0)
{
// go to future
while (deltaDays != 0)
{
ret.tomorrow();
deltaDays--;
}
}
else
{
// go to past
while (deltaDays != 0)
{
ret.yesterday();
deltaDays++;
}
}
return ret;
}
void br::com::sbVB::VBLib::VBDate::tomorrow()
{
int daysThisMonth = daysInAMonth(m_baseYear,m_baseMonth);
if (m_baseDay < daysThisMonth)
{
setDate(m_baseYear,m_baseMonth,m_baseDay+1);
return;
}
if (m_baseMonth < VBdec)
{
// it it the last day of month, so tomorrow is the first day of next month
setDate(m_baseYear,m_baseMonth+1,1);
return;
}
// it is the last day of year, so tomorrow is the first day of next year
setDate(m_baseYear+1,VBjan,1);
}
void br::com::sbVB::VBLib::VBDate::yesterday()
{
if (m_baseDay > 1)
{
setDate(m_baseYear,m_baseMonth,m_baseDay-1);
return;
}
if (m_baseMonth != VBjan)
{
// it is the first day of a month not January, so yesterday is the last day of previous month
int daysLastMonth = daysInAMonth(m_baseYear,m_baseMonth-1);
setDate(m_baseYear,m_baseMonth-1,daysLastMonth);
return;
}
// it is the first day of year, so yesterday is the last day of previous year
setDate(m_baseYear-1,VBdec,31);
}
br::com::sbVB::VBLib::VBString br::com::sbVB::VBLib::VBDate::getDate(int format) const
{
const char *monthName[][12] = {
{ // 0 - english
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
},
{ // 1 - portuguese
"Janeiro", "Fevereiro", "Mar�o", "Abril", "Maio", "Junho",
"Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"
}
};
br::com::sbVB::VBLib::VBString ret;
switch (format)
{
case 1: // Example: "November 24th, 2001"
ret = monthName[0][this->m_baseMonth];
ret += " ";
ret += this->m_baseDay;
switch (this->m_baseDay)
{
case 1:
case 21:
case 31:
ret += "st";
break;
case 2:
case 22:
ret += "nd";
break;
case 3:
case 23:
ret += "rd";
break;
default:
ret += "th";
}
ret += ", ";
ret += this->m_baseYear;
break;
case 2: // Example: yyyy-mm-dd, that is, "2001-11-24"
ret = this->m_baseYear;
ret += "-";
ret += twoDigits(this->m_baseMonth + 1);
ret += "-";
ret += twoDigits(this->m_baseDay);
break;
case 3: // Example: "24 de Novembro de 2001"
ret = this->m_baseDay;
ret += " de ";
ret += monthName[1][this->m_baseMonth];
ret += " de ";
ret += this->m_baseYear;
break;
case 4: // Example: yyyy-mm-dd, that is, "20011124"
ret = this->m_baseYear;
ret += twoDigits(this->m_baseMonth + 1);
ret += twoDigits(this->m_baseDay);
break;
default:
ret = "";
}
return ret;
}
br::com::sbVB::VBLib::VBString br::com::sbVB::VBLib::VBDate::twoDigits(int i) const
{
VBString ret;
if (i < 10)
ret = "0";
ret += i;
return ret;
}
/////////////////////////////////////////////////////////////////
//
// class VBDateTime
//
/////////////////////////////////////////////////////////////////
const char *br::com::sbVB::VBLib::VBDateTime::monthName[] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
// default constructor
br::com::sbVB::VBLib::VBDateTime::VBDateTime()
{
}
br::com::sbVB::VBLib::VBString br::com::sbVB::VBLib::VBDateTime::getTimeStr(unsigned format) const
{
br::com::sbVB::VBLib::VBString ret;
ret += " ";
ret += twoDigits(m_tm.tm_hour);
ret += ":";
ret += twoDigits(m_tm.tm_min);
if (format>1)
{
ret += ":";
ret += twoDigits(m_tm.tm_sec);
if (format>2)
{
ret += ",";
ret += m_miliseconds;
}
}
return ret;
}
// Example: 31-Mar-2002 23:59:59 GMT
br::com::sbVB::VBLib::VBString br::com::sbVB::VBLib::VBDateTime::getDateStr(int dateFormat) const
{
br::com::sbVB::VBLib::VBString ret;
br::com::sbVB::VBLib::VBDate date = *this; // get VBDate object from this
ret = date.getDate(dateFormat);
ret += " " + getTimeStr();
// ret += " GMT";
return ret;
}
br::com::sbVB::VBLib::VBString br::com::sbVB::VBLib::VBDateTime::twoDigits(int i) const
{
br::com::sbVB::VBLib::VBString ret;
if (i < 10)
ret = "0";
ret += i;
return ret;
}
// add or subtract time to this VBDate
void br::com::sbVB::VBLib::VBDateTime::addYear(int year)
{
m_tm.tm_year += year;
VBDate cal_from;
if (!cal_from.setDate(m_tm.tm_year+1900+year,m_tm.tm_mon,m_tm.tm_mday))
{
// invalid date. This can only be caused by leap year
m_tm.tm_mon = 3; // march
m_tm.tm_mday = 1;
}
}
void br::com::sbVB::VBLib::VBDateTime::setDate(int year, unsigned month, unsigned day)
{
m_tm.tm_year = year-1900; // input year is normal year. Stored year is tm style (-1900)
m_tm.tm_mon = month; // months since January - [0,11]
m_tm.tm_mday = day; // day of the month - [1,31]
// getWeekDay
// int tm_wday; // days since Sunday - [0,6]
// int tm_yday; // days since January 1 - [0,365]
}
void br::com::sbVB::VBLib::VBDateTime::setTime(unsigned hour,
unsigned minute, unsigned second, unsigned miliseconds)
{
m_tm.tm_hour = hour; // hours since midnight - [0,23]
m_tm.tm_min = minute; // minutes after the hour - [0,59]
m_tm.tm_sec = second; // seconds after the minute - [0,59]
m_miliseconds = miliseconds;
}
double br::com::sbVB::VBLib::VBDateTime::getDifSeconds(const VBDateTime & dt) const
{
double ret = 0;
double aux = (double)(m_miliseconds)/1000.0;
ret += aux;
aux = (double)(dt.m_miliseconds)/1000.0;
ret -= aux;
ret += m_tm.tm_sec - dt.m_tm.tm_sec;
ret += m_tm.tm_min*60 - dt.m_tm.tm_min*60;
ret += m_tm.tm_hour*60*60 - dt.m_tm.tm_hour*60*60;
// year, month, day not considered yet
return ret;
}
void br::com::sbVB::VBLib::VBDateTime::addMonth(int month)
{
#if 0
time_t secondsToAdd = 30 * 24 * 60 * 60; // seconds of 1 month
secondsToAdd *= month;
time_t now = mktime(&m_tm);
time_t newDateTime = now + secondsToAdd;
setThisTM(newDateTime);
#endif
m_tm.tm_mon += month;
br::com::sbVB::VBLib::VBDate cal_from;
if (!cal_from.setDate(m_tm.tm_year+1900,m_tm.tm_mon+month,m_tm.tm_mday))
{
// invalid date. This can only be caused by leap year
m_tm.tm_mon = 3; // march
m_tm.tm_mday = 1;
}
}
void br::com::sbVB::VBLib::VBDateTime::addDay(int day)
{
time_t secondsToAdd = 24 * 60 * 60; // seconds of 1 day
secondsToAdd *= day;
time_t now = mktime(&m_tm);
time_t newDateTime = now + secondsToAdd;
setThisTM(newDateTime);
}
void br::com::sbVB::VBLib::VBDateTime::addHour(int hour)
{
time_t secondsToAdd = 60 * 60; // seconds of 1 hour
secondsToAdd *= hour;
time_t now = mktime(&m_tm);
time_t newDateTime = now + secondsToAdd;
setThisTM(newDateTime);
}
void br::com::sbVB::VBLib::VBDateTime::addMinute(int minute)
{
time_t secondsToAdd = 60; // seconds of 1 minute
secondsToAdd *= minute;
time_t now = mktime(&m_tm);
time_t newDateTime = now + secondsToAdd;
setThisTM(newDateTime);
}
void br::com::sbVB::VBLib::VBDateTime::addSecond(int second)
{
time_t secondsToAdd = second;
time_t now = mktime(&m_tm);
time_t newDateTime = now + secondsToAdd;
setThisTM(newDateTime);
}
void br::com::sbVB::VBLib::VBDateTime::setThisTM(time_t ltime)
{
tm *p_tm = localtime( <ime ); // convert to struct tm
// copy each attribute
m_tm.tm_sec = p_tm->tm_sec; // seconds after the minute - [0,59]
m_tm.tm_min = p_tm->tm_min; // minutes after the hour - [0,59]
m_tm.tm_hour = p_tm->tm_hour; // hours since midnight - [0,23]
m_tm.tm_mday = p_tm->tm_mday; // day of the month - [1,31]
m_tm.tm_mon = p_tm->tm_mon; // months since January - [0,11]
m_tm.tm_year = p_tm->tm_year; // years since 1900
m_tm.tm_wday = p_tm->tm_wday; // days since Sunday - [0,6]
m_tm.tm_yday = p_tm->tm_yday; // days since January 1 - [0,365]
m_tm.tm_isdst = p_tm->tm_isdst; // daylight savings time flag
}
void br::com::sbVB::VBLib::VBDateTime::setNow()
{
time_t ltime;
time( <ime ); // get number of seconds elapsed since 00:00:00 on January 1, 1970,
setThisTM(ltime);
#ifdef WIN32
// Windows code
// time_t tz_sec; // Difference in seconds between Greenwitch time and local time
// tz_sec = timezone;
m_miliseconds = 0;
#else
// Unix code
struct timeval tv;
struct timezone tz;
gettimeofday( &tv, &tz );
m_miliseconds = tv.tv_usec/1000;
#endif
// m_timeRelativeToGreenwitch = tz_sec / 60 / 60; // Difference in hours
// cout << "DEBUG: " << m_timeRelativeToGreenwitch << endl; // Brazil is -3
}
br::com::sbVB::VBLib::VBDateTime::operator br::com::sbVB::VBLib::VBDate () const
{
br::com::sbVB::VBLib::VBDate ret;
ret.setDate(m_tm.tm_year+1900,m_tm.tm_mon,m_tm.tm_mday);
return ret;
}
// return date-time as string
::br::com::sbVB::VBLib::VBString br::com::sbVB::VBLib::VBDateTime::getDateTimeStr() const
{
VBString tok = "|";
VBString ret;
ret += getYear();
ret += tok;
ret += getMonth();
ret += tok;
ret += getDay();
ret += tok;
ret += getHour();
ret += tok;
ret += getMinute();
ret += tok;
ret += getSecond();
ret += tok;
ret += getMiliSecond();
return ret;
}
// set this based in argument, compatible with getDateTimeStr
void br::com::sbVB::VBLib::VBDateTime::setDateTimeStr(const char *setTimeStr)
{
char tok = '|';
VBString st = setTimeStr;
int year = atoi(st.strtok(tok,0));
unsigned month = atoi(st.strtok(tok,1));
unsigned day = atoi(st.strtok(tok,2));
unsigned hour = atoi(st.strtok(tok,3));
unsigned minute = atoi(st.strtok(tok,4));
unsigned second = atoi(st.strtok(tok,5));
unsigned miliseconds = atoi(st.strtok(tok,6));
setDate(year,month,day);
setTime(hour,minute,second,miliseconds);
}
// return true if this is less than argument
bool br::com::sbVB::VBLib::VBDateTime::operator<(const VBDateTime & dt) const
{
if (getYear() > dt.getYear())
return false;
if(getYear() < dt.getYear())
return true;
if (getMonth() > dt.getMonth())
return false;
if (getMonth() < dt.getMonth())
return true;
if (getDay() > dt.getDay())
return false;
if (getDay() < dt.getDay())
return true;
if (getHour() > dt.getHour())
return false;
if (getHour() < dt.getHour())
return true;
if (getMinute() > dt.getMinute())
return false;
if (getMinute() < dt.getMinute())
return true;
if (getSecond() > dt.getSecond())
return false;
if (getSecond() < dt.getSecond())
return true;
if (getMiliSecond() > dt.getMiliSecond())
return false;
if (getMiliSecond() < dt.getMiliSecond())
return true;
return false;
}
// return true if this is greater than argument
bool br::com::sbVB::VBLib::VBDateTime::operator>(const VBDateTime & dt) const
{
return dt < *this;
}
bool br::com::sbVB::VBLib::VBDateTime::operator==(const VBDateTime & dt) const
{
if (getYear() != dt.getYear()) return false;
if (getMonth() != dt.getMonth()) return false;
if (getDay() != dt.getDay()) return false;
if (getHour() != dt.getHour()) return false;
if (getMinute() != dt.getMinute()) return false;
if (getSecond() != dt.getSecond()) return false;
if (getMiliSecond() != dt.getMiliSecond()) return false;
return true;
}
int br::com::sbVB::VBLib::VBDateTime::getYear() const
{
return m_tm.tm_year+1900;
}
unsigned br::com::sbVB::VBLib::VBDateTime::getMonth() const
{
return m_tm.tm_mon;
}
unsigned br::com::sbVB::VBLib::VBDateTime::getDay() const
{
return m_tm.tm_mday;
}
unsigned br::com::sbVB::VBLib::VBDateTime::getHour() const
{
return m_tm.tm_hour;
}
unsigned br::com::sbVB::VBLib::VBDateTime::getMinute() const
{
return m_tm.tm_min;
}
unsigned br::com::sbVB::VBLib::VBDateTime::getSecond() const
{
return m_tm.tm_sec;
}
unsigned br::com::sbVB::VBLib::VBDateTime::getMiliSecond() const
{
return m_miliseconds;
}
unsigned long br::com::sbVB::VBLib::VBDateTime::getSecondsToJulianDate() const
{
unsigned long ret = 0;
VBDate julianDate, thisDate;
julianDate.setDate(1970,1,1);
thisDate.setDate(getYear(),getMonth(),getDay());
unsigned deltaDays = thisDate.deltaDays(julianDate);
// add years
ret += deltaDays * 24 * 60 * 60;
ret += (getHour()) * 60 * 60;
ret += (getMinute()) * 60;
ret += (getSecond());
return ret;
}
| [
"heineck@c016ff2c-3db2-11de-a81c-fde7d73ceb89"
]
| [
[
[
1,
786
]
]
]
|
3d65acb89e019f2ed606b63ee573b676d69956f7 | 57be15ccf8458cdc18ed9ddc425260a380c80ebf | /MatchingBackend/support/Logger.cpp | 09865649ce7b45e4eedf10157c85c0ec0f316c1a | []
| no_license | lkn/MatchingBackend | 9fe7687e0dcfb109c8ef16507ec5b88cafa1b612 | 7e4039c594dadc94843db605b36648681171d2d0 | refs/heads/master | 2021-01-01T18:27:29.084638 | 2011-06-06T20:36:03 | 2011-06-06T20:36:03 | 1,797,326 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,289 | cpp | #include <iostream>
#include <time.h>
#include <stdarg.h>
#include <time.h>
#include "../support/util.h"
#include "Logger.h"
Logger::Logger() {
Init("");
}
Logger::Logger(std::string fileName) {
Init(fileName);
}
Logger::~Logger() {
logFile_->close();
delete logFile_;
logFile_ = NULL;
}
void Logger::Init(std::string fileName) {
if (fileName.empty()) {
std::cerr << "Empty file name to logger" << std::endl;
struct tm timeinfo = Util::GetTimeInfo();
char buffer[80];
strftime(buffer, 80, "LOG-%m-%d-%Y.txt", &timeinfo);
fileName = buffer;
}
logFile_ = new std::ofstream(fileName, std::ios::out | std::ios::app);
(*logFile_) << "\n\n-------------------------------------------\n";
}
// Will also write to file
void Logger::Log(LogLevel level, const char *format, ...) {
char buffer[1024];
va_list args;
va_start(args, format);
vsnprintf(buffer, 1024, format, args);
va_end(args);
char timeBuffer[10];
struct tm timeinfo = Util::GetTimeInfo();
strftime(timeBuffer, 10, "%I:%M:%S", &timeinfo);
char logString[1024];
sprintf(logString, "[%s] %s\n", timeBuffer, buffer);
if (logFile_ && logFile_->is_open()) {
(*logFile_) << logString;
logFile_->flush();
}
std::cout << logString;
}
| [
"[email protected]"
]
| [
[
[
1,
59
]
]
]
|
5905bd1f8316c7d406d5f685d44862547607f064 | 4b30b09448549ffbe73c2346447e249713c1a463 | /Sources/article_manager/article_archive.h | ac79cc9c866a178d00aa2b8ad6880dd5e28fd34f | []
| no_license | dblock/agnes | 551fba6af6fcccfe863a1a36aad9fb066a2eaeae | 3b3608eba8e7ee6a731f0d5a3191eceb0c012dd5 | refs/heads/master | 2023-09-05T22:32:10.661399 | 2009-10-29T11:23:28 | 2009-10-29T11:23:28 | 1,998,777 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,928 | h | #ifndef article_archive_h
#define article_archive_h
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <platform/platform.h>
#include <cstring/cstring.h>
#include <cvector/cvector.h>
#include <mozilla/mozilla_v2.h>
#include "../article_manager/article_manager.h"
class article_archive {
public:
article_archive(cgiOutStream& CGIStream, const CString& _root, const CString& _name, pParam_v2 * _params, article_manager * _template_manager, article_tree * head, agnes_article * limit, bool bTar);
void displace_tree(cgiOutStream& CGIStream, const CString& full_alias, article_tree * head);
article_archive(const CString& _root, const CString& _name, pParam_v2 * _params, article_manager * _template_manager);
~article_archive(void);
void archive_link(cgiOutStream& CGIStream);
CString full_root;
ilist <article_tree *> articles;
void fill_headers(void);
CString clean_name;
CString dirty_name();
#ifdef ANSI
struct stat * stats;
#else
struct _stat * stats;
#endif
int operator > (const article_archive&);
int operator < (const article_archive&);
bool find_article(const CString& node);
bool find_article(const CString& node, article_tree * head);
private:
CString root;
CString name;
CString cmd;
pParam_v2 * params;
article_manager * template_manager;
protected:
void common_init(const CString& _root, const CString& _name, pParam_v2 * _params, article_manager * _template_manager);
};
class article_archive_manager {
public:
ilist <article_archive *> archives;
article_archive_manager(const CString& _root, pParam_v2 * _params, article_manager * _template_manager);
~article_archive_manager(void);
void generate_push(cgiOutStream& CGIStream);
void generate_pull(cgiOutStream& CGIStream);
void create_article_archive(cgiOutStream& CGIStream, const CString& _name, pParam_v2 * _params, article_manager * _template_manager, article_tree * _head, agnes_article * _limit, bool bTar);
void pull_archives(const CString& _root, const CString& _name, pParam_v2 * _params, article_manager * _template_manager);
void merge_archives(cgiOutStream& CGIStream, const CString& _root, const CString& _name, pParam_v2 * _params, article_manager * _template_manager, bool bTar);
#ifdef ANSI
static void detar_archive(cgiOutStream& CGIStream, const CString& root, const CString& archive);
static void tar_archive(cgiOutStream& CGIStream, const CString& root, const CString& archive);
#endif
bool find_article(const CString& node, CString& archive);
private:
CString root;
pParam_v2 * params;
article_manager * template_manager;
CString init_structure(cgiOutStream& CGIStream, const CString& _root, const CString& _name);
void move_directory(cgiOutStream& CGIStream, const CString& target, const CString& source);
protected:
void init_archives(void);
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
71
]
]
]
|
c25f894be0c3fc58b3cb0b014ecd46bc5d906180 | f27e317f667ebe5979c9620deea865c2d411bed5 | /Towerdefence/Network/src/RPC3.cpp | 975a1876115a7f6df87a8d3e9779b79c9cd448c5 | []
| no_license | iijobs/argontd | 8452450e90ced1e4e27766a3b18a32424fa04366 | fa3dac21197deb85336efd3f3239929580b296e7 | refs/heads/master | 2020-06-05T08:47:27.055010 | 2009-09-27T16:12:44 | 2009-09-27T16:12:44 | 32,657,966 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,919 | cpp | #include "RPC3.h"
#include "raknet/RakMemoryOverride.h"
#include "raknet/RakAssert.h"
#include "raknet/StringCompressor.h"
#include "raknet/BitStream.h"
#include "raknet/RakPeerInterface.h"
#include "raknet/MessageIdentifiers.h"
#include "raknet/NetworkIDObject.h"
#include "raknet/NetworkIDManager.h"
#include <stdlib.h>
using namespace RakNet;
int RPC3::RemoteRPCFunctionComp( const RPC3::RPCIdentifier &key, const RemoteRPCFunction &data )
{
return strcmp(key.C_String(), data.identifier.C_String());
}
RPC3::RPC3()
{
currentExecution[0]=0;
networkIdManager=0;
outgoingTimestamp=0;
outgoingPriority=HIGH_PRIORITY;
outgoingReliability=RELIABLE_ORDERED;
outgoingOrderingChannel=0;
outgoingBroadcast=true;
incomingTimeStamp=0;
DataStructures::Map<SystemAddress, DataStructures::OrderedList<RPCIdentifier, RemoteRPCFunction, RPC3::RemoteRPCFunctionComp> *>::IMPLEMENT_DEFAULT_COMPARISON();
}
RPC3::~RPC3()
{
Clear();
}
void RPC3::SetNetworkIDManager(NetworkIDManager *idMan)
{
networkIdManager=idMan;
}
bool RPC3::UnregisterFunction(const char *uniqueIdentifier)
{
return false;
}
bool RPC3::IsFunctionRegistered(const char *uniqueIdentifier)
{
unsigned i = GetLocalFunctionIndex(uniqueIdentifier);
return (bool) (i!=(unsigned)-1);
}
void RPC3::SetTimestamp(RakNetTime timeStamp)
{
outgoingTimestamp=timeStamp;
}
void RPC3::SetSendParams(PacketPriority priority, PacketReliability reliability, char orderingChannel)
{
outgoingPriority=priority;
outgoingReliability=reliability;
outgoingOrderingChannel=orderingChannel;
}
void RPC3::SetRecipientAddress(SystemAddress systemAddress, bool broadcast)
{
outgoingSystemAddress=systemAddress;
outgoingBroadcast=broadcast;
}
void RPC3::SetRecipientObject(NetworkID networkID)
{
outgoingNetworkID=networkID;
}
RakNetTime RPC3::GetLastSenderTimestamp(void) const
{
return incomingTimeStamp;
}
SystemAddress RPC3::GetLastSenderAddress(void) const
{
return incomingSystemAddress;
}
RakPeerInterface *RPC3::GetRakPeer(void) const
{
return rakPeerInterface;
}
const char *RPC3::GetCurrentExecution(void) const
{
return (const char *) currentExecution;
}
bool RPC3::SendCall(RakString uniqueIdentifier, char parameterCount, RakNet::BitStream *serializedParameters)
{
SystemAddress systemAddr;
unsigned int outerIndex;
unsigned int innerIndex;
if (uniqueIdentifier.IsEmpty())
return false;
RakNet::BitStream bs;
if (outgoingTimestamp!=0)
{
bs.Write((MessageID)ID_TIMESTAMP);
bs.Write(outgoingTimestamp);
}
bs.Write((MessageID)ID_AUTO_RPC_CALL);
bs.Write(parameterCount);
if (outgoingNetworkID!=UNASSIGNED_NETWORK_ID)
{
bs.Write(true);
bs.Write(outgoingNetworkID);
}
else
{
bs.Write(false);
}
// This is so the call SetWriteOffset works
bs.AlignWriteToByteBoundary();
BitSize_t writeOffset = bs.GetWriteOffset();
if (outgoingBroadcast)
{
unsigned systemIndex;
for (systemIndex=0; systemIndex < rakPeerInterface->GetMaximumNumberOfPeers(); systemIndex++)
{
systemAddr=rakPeerInterface->GetSystemAddressFromIndex(systemIndex);
if (systemAddr!=UNASSIGNED_SYSTEM_ADDRESS && systemAddr!=outgoingSystemAddress)
{
if (GetRemoteFunctionIndex(systemAddr, uniqueIdentifier, &outerIndex, &innerIndex))
{
// Write a number to identify the function if possible, for faster lookup and less bandwidth
bs.Write(true);
bs.WriteCompressed(remoteFunctions[outerIndex]->operator [](innerIndex).functionIndex);
}
else
{
bs.Write(false);
stringCompressor->EncodeString(uniqueIdentifier, 512, &bs, 0);
}
bs.WriteCompressed(serializedParameters->GetNumberOfBitsUsed());
bs.WriteAlignedBytes((const unsigned char*) serializedParameters->GetData(), serializedParameters->GetNumberOfBytesUsed());
SendUnified(&bs, outgoingPriority, outgoingReliability, outgoingOrderingChannel, systemAddr, false);
// Start writing again after ID_AUTO_RPC_CALL
bs.SetWriteOffset(writeOffset);
}
}
}
else
{
systemAddr = outgoingSystemAddress;
if (systemAddr!=UNASSIGNED_SYSTEM_ADDRESS)
{
if (GetRemoteFunctionIndex(systemAddr, uniqueIdentifier, &outerIndex, &innerIndex))
{
// Write a number to identify the function if possible, for faster lookup and less bandwidth
bs.Write(true);
bs.WriteCompressed(remoteFunctions[outerIndex]->operator [](innerIndex).functionIndex);
}
else
{
bs.Write(false);
stringCompressor->EncodeString(uniqueIdentifier, 512, &bs, 0);
}
bs.WriteCompressed(serializedParameters->GetNumberOfBitsUsed());
bs.WriteAlignedBytes((const unsigned char*) serializedParameters->GetData(), serializedParameters->GetNumberOfBytesUsed());
SendUnified(&bs, outgoingPriority, outgoingReliability, outgoingOrderingChannel, systemAddr, false);
}
else
return false;
}
return true;
}
void RPC3::OnAttach(void)
{
outgoingSystemAddress=UNASSIGNED_SYSTEM_ADDRESS;
outgoingNetworkID=UNASSIGNED_NETWORK_ID;
incomingSystemAddress=UNASSIGNED_SYSTEM_ADDRESS;
}
PluginReceiveResult RPC3::OnReceive(Packet *packet)
{
RakNetTime timestamp=0;
unsigned char packetIdentifier, packetDataOffset;
if ( ( unsigned char ) packet->data[ 0 ] == ID_TIMESTAMP )
{
if ( packet->length > sizeof( unsigned char ) + sizeof( RakNetTime ) )
{
packetIdentifier = ( unsigned char ) packet->data[ sizeof( unsigned char ) + sizeof( RakNetTime ) ];
// Required for proper endian swapping
RakNet::BitStream tsBs(packet->data+sizeof(MessageID),packet->length-1,false);
tsBs.Read(timestamp);
packetDataOffset=sizeof( unsigned char )*2 + sizeof( RakNetTime );
}
else
return RR_STOP_PROCESSING_AND_DEALLOCATE;
}
else
{
packetIdentifier = ( unsigned char ) packet->data[ 0 ];
packetDataOffset=sizeof( unsigned char );
}
switch (packetIdentifier)
{
case ID_AUTO_RPC_CALL:
incomingTimeStamp=timestamp;
incomingSystemAddress=packet->systemAddress;
OnRPC3Call(packet->systemAddress, packet->data+packetDataOffset, packet->length-packetDataOffset);
return RR_STOP_PROCESSING_AND_DEALLOCATE;
case ID_AUTO_RPC_REMOTE_INDEX:
OnRPCRemoteIndex(packet->systemAddress, packet->data+packetDataOffset, packet->length-packetDataOffset);
return RR_STOP_PROCESSING_AND_DEALLOCATE;
}
return RR_CONTINUE_PROCESSING;
}
void RPC3::OnRPC3Call(SystemAddress systemAddress, unsigned char *data, unsigned int lengthInBytes)
{
RakNet::BitStream bs(data,lengthInBytes,false);
bool hasParameterCount=false;
char parameterCount;
NetworkIDObject *networkIdObject;
NetworkID networkId;
bool hasNetworkId=false;
bool hasFunctionIndex=false;
unsigned int functionIndex;
BitSize_t bitsOnStack;
char strIdentifier[512];
incomingExtraData.Reset();
bs.Read(parameterCount);
bs.Read(hasNetworkId);
if (hasNetworkId)
{
bs.Read(networkId);
if (networkIdManager==0 && (networkIdManager=rakPeerInterface->GetNetworkIDManager())==0)
{
// Failed - Tried to call object member, however, networkIDManager system was never registered
SendError(systemAddress, RPC_ERROR_NETWORK_ID_MANAGER_UNAVAILABLE, "");
return;
}
networkIdObject = (NetworkIDObject*) networkIdManager->GET_OBJECT_FROM_ID(networkId);
if (networkIdObject==0)
{
// Failed - Tried to call object member, object does not exist (deleted?)
SendError(systemAddress, RPC_ERROR_OBJECT_DOES_NOT_EXIST, "");
return;
}
}
else
{
networkIdObject=0;
}
bs.AlignReadToByteBoundary();
bs.Read(hasFunctionIndex);
if (hasFunctionIndex)
bs.ReadCompressed(functionIndex);
else
stringCompressor->DecodeString(strIdentifier,512,&bs,0);
bs.ReadCompressed(bitsOnStack);
RakNet::BitStream serializedParameters;
if (bitsOnStack>0)
{
serializedParameters.AddBitsAndReallocate(bitsOnStack);
bs.ReadAlignedBytes(serializedParameters.GetData(), BITS_TO_BYTES(bitsOnStack));
serializedParameters.SetWriteOffset(bitsOnStack);
}
if (hasFunctionIndex)
{
if (functionIndex>localFunctions.Size())
{
// Failed - other system specified a totally invalid index
// Possible causes: Bugs, attempts to crash the system, requested function not registered
SendError(systemAddress, RPC_ERROR_FUNCTION_INDEX_OUT_OF_RANGE, "");
return;
}
}
else
{
// Find the registered function with this str
for (functionIndex=0; functionIndex < localFunctions.Size(); functionIndex++)
{
bool isObjectMember = boost::fusion::get<0>(localFunctions[functionIndex].functionPointer);
// boost::function<_RPC3::InvokeResultCodes (_RPC3::InvokeArgs)> functionPtr = boost::fusion::get<0>(localFunctions[functionIndex].functionPointer);
if (isObjectMember == (networkIdObject!=0) &&
strcmp(localFunctions[functionIndex].identifier.C_String(), strIdentifier)==0)
{
// SEND RPC MAPPING
RakNet::BitStream outgoingBitstream;
outgoingBitstream.Write((MessageID)ID_AUTO_RPC_REMOTE_INDEX);
outgoingBitstream.Write(hasNetworkId);
outgoingBitstream.WriteCompressed(functionIndex);
stringCompressor->EncodeString(strIdentifier,512,&outgoingBitstream,0);
SendUnified(&outgoingBitstream, HIGH_PRIORITY, RELIABLE_ORDERED, 0, systemAddress, false);
break;
}
}
if (functionIndex==localFunctions.Size())
{
for (functionIndex=0; functionIndex < localFunctions.Size(); functionIndex++)
{
if (strcmp(localFunctions[functionIndex].identifier.C_String(), strIdentifier)==0)
{
bool isObjectMember = boost::fusion::get<0>(localFunctions[functionIndex].functionPointer);
if (isObjectMember==true && networkIdObject==0)
{
// Failed - Calling C++ function as C function
SendError(systemAddress, RPC_ERROR_CALLING_CPP_AS_C, strIdentifier);
return;
}
if (isObjectMember==false && networkIdObject!=0)
{
// Failed - Calling C function as C++ function
SendError(systemAddress, RPC_ERROR_CALLING_C_AS_CPP, strIdentifier);
return;
}
}
}
SendError(systemAddress, RPC_ERROR_FUNCTION_NOT_REGISTERED, strIdentifier);
return;
}
}
bool isObjectMember = boost::fusion::get<0>(localFunctions[functionIndex].functionPointer);
boost::function<_RPC3::InvokeResultCodes (_RPC3::InvokeArgs)> functionPtr = boost::fusion::get<1>(localFunctions[functionIndex].functionPointer);
// int arity = boost::fusion::get<2>(localFunctions[functionIndex].functionPointer);
// if (isObjectMember)
// arity--; // this pointer
if (functionPtr==0)
{
// Failed - Function was previously registered, but isn't registered any longer
SendError(systemAddress, RPC_ERROR_FUNCTION_NO_LONGER_REGISTERED, localFunctions[functionIndex].identifier);
return;
}
// Boost doesn't support this for class members
// if (arity!=parameterCount)
// {
// // Failed - The number of parameters that this function has was explicitly specified, and does not match up.
// SendError(systemAddress, RPC_ERROR_INCORRECT_NUMBER_OF_PARAMETERS, localFunctions[functionIndex].identifier);
// return;
// }
_RPC3::InvokeArgs functionArgs;
functionArgs.bitStream=&serializedParameters;
functionArgs.networkIDManager=networkIdManager;
functionArgs.caller=this;
functionArgs.thisPtr=networkIdObject;
// serializedParameters.PrintBits();
_RPC3::InvokeResultCodes res2 = functionPtr(functionArgs);
}
void RPC3::OnRPCRemoteIndex(SystemAddress systemAddress, unsigned char *data, unsigned int lengthInBytes)
{
// A remote system has given us their internal index for a particular function.
// Store it and use it from now on, to save bandwidth and search time
bool objectExists;
RakString strIdentifier;
unsigned int insertionIndex;
unsigned int remoteIndex;
RemoteRPCFunction newRemoteFunction;
RakNet::BitStream bs(data,lengthInBytes,false);
RPCIdentifier identifier;
bool isObjectMember;
bs.Read(isObjectMember);
bs.ReadCompressed(remoteIndex);
bs.Read(strIdentifier);
if (strIdentifier.IsEmpty())
return;
DataStructures::OrderedList<RPCIdentifier, RemoteRPCFunction, RPC3::RemoteRPCFunctionComp> *theList;
if (remoteFunctions.Has(systemAddress))
{
theList = remoteFunctions.Get(systemAddress);
insertionIndex=theList->GetIndexFromKey(identifier, &objectExists);
if (objectExists==false)
{
newRemoteFunction.functionIndex=remoteIndex;
newRemoteFunction.identifier = strIdentifier;
theList->InsertAtIndex(newRemoteFunction, insertionIndex);
}
}
else
{
theList = new DataStructures::OrderedList<RPCIdentifier, RemoteRPCFunction, RPC3::RemoteRPCFunctionComp>;
newRemoteFunction.functionIndex=remoteIndex;
newRemoteFunction.identifier = strIdentifier;
theList->InsertAtEnd(newRemoteFunction);
remoteFunctions.SetNew(systemAddress,theList);
}
}
void RPC3::OnClosedConnection(SystemAddress systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason )
{
if (remoteFunctions.Has(systemAddress))
{
DataStructures::OrderedList<RPCIdentifier, RemoteRPCFunction, RPC3::RemoteRPCFunctionComp> *theList = remoteFunctions.Get(systemAddress);
delete theList;
remoteFunctions.Delete(systemAddress);
}
}
void RPC3::OnShutdown(void)
{
Clear();
}
void RPC3::Clear(void)
{
unsigned j;
for (j=0; j < remoteFunctions.Size(); j++)
{
DataStructures::OrderedList<RPCIdentifier, RemoteRPCFunction, RPC3::RemoteRPCFunctionComp> *theList = remoteFunctions[j];
delete theList;
}
localFunctions.Clear();
remoteFunctions.Clear();
outgoingExtraData.Reset();
incomingExtraData.Reset();
}
void RPC3::SendError(SystemAddress target, unsigned char errorCode, const char *functionName)
{
RakNet::BitStream bs;
bs.Write((MessageID)ID_RPC_REMOTE_ERROR);
bs.Write(errorCode);
bs.WriteAlignedBytes((const unsigned char*) functionName,(const unsigned int) strlen(functionName)+1);
SendUnified(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, target, false);
}
unsigned RPC3::GetLocalFunctionIndex(RPC3::RPCIdentifier identifier)
{
unsigned i;
for (i=0; i < localFunctions.Size(); i++)
{
if (localFunctions[i].identifier==identifier)
return i;
}
return (unsigned) -1;
}
bool RPC3::GetRemoteFunctionIndex(SystemAddress systemAddress, RPC3::RPCIdentifier identifier, unsigned int *outerIndex, unsigned int *innerIndex)
{
bool objectExists=false;
if (remoteFunctions.Has(systemAddress))
{
*outerIndex = remoteFunctions.GetIndexAtKey(systemAddress);
DataStructures::OrderedList<RPCIdentifier, RemoteRPCFunction, RPC3::RemoteRPCFunctionComp> *theList = remoteFunctions[*outerIndex];
*innerIndex = theList->GetIndexFromKey(identifier, &objectExists);
}
return objectExists;
}
| [
"[email protected]@1eb55710-98a1-11de-a05d-3bd73e269465"
]
| [
[
[
1,
470
]
]
]
|
b09fb1e8de9a0ce7cde551268c96f14e3a161e13 | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/zombie/nscene/src/nscene/nshadowlightnode_main.cc | 44682b885389f1300be19ef2e57cada7728e9d3f | []
| 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,073 | cc | #include "precompiled/pchrnsscene.h"
//------------------------------------------------------------------------------
// nshadowlightnode_main.cc
// (C) 2005 Conjurer Services, S.A.
//------------------------------------------------------------------------------
#include "nscene/nshadowlightnode.h"
nNebulaScriptClass(nShadowLightNode, "nabstractshadernode");
//------------------------------------------------------------------------------
/**
*/
nShadowLightNode::nShadowLightNode() :
camera(45.0f, 1.0f, 0.1f, 10.0f),
dirtySProj(true)
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
nShadowLightNode::~nShadowLightNode()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
void
nShadowLightNode::SetCamera(const nCamera2& c)
{
this->camera = c;
}
//------------------------------------------------------------------------------
/**
*/
const nCamera2&
nShadowLightNode::GetCamera() const
{
return this->camera;
}
//------------------------------------------------------------------------------
/**
*/
void
nShadowLightNode::SetOrthogonal(float w, float h, float nearp, float farp)
{
this->orthogonal = vector4(w,h,nearp,farp);
this->camera.SetOrthogonal(w, h, nearp, farp);
this->dirtySProj = true;
}
//------------------------------------------------------------------------------
/**
*/
void
nShadowLightNode::SetEuler( const vector3& eulerAngles )
{
this->euler = eulerAngles;
this->dirtySProj = true;
}
//------------------------------------------------------------------------------
/**
*/
const vector3
nShadowLightNode::GetEuler() const
{
return this->euler;
}
//------------------------------------------------------------------------------
/**
*/
void
nShadowLightNode::SetPosition( const vector3& pos )
{
this->position = pos;
this->dirtySProj = true;
}
//------------------------------------------------------------------------------
/**
*/
const vector3
nShadowLightNode::GetPosition() const
{
return this->position;
}
//------------------------------------------------------------------------------
/**
*/
void
nShadowLightNode::SetDeformation( const vector4& deformation )
{
this->deformation = deformation;
this->dirtySProj = true;
}
//------------------------------------------------------------------------------
/**
*/
const vector4
nShadowLightNode::GetDeformation() const
{
return this->deformation;
}
//------------------------------------------------------------------------------
/**
*/
void
nShadowLightNode::ComputeShadowProjection()
{
this->shadowProj.ident();
this->shadowProj.rotate_x(this->euler.x);
this->shadowProj.rotate_y(this->euler.y);
this->shadowProj.rotate_z(this->euler.z);
this->shadowProj.set_translation( this->position );
this->shadowProj.invert_simple();
matrix44 deformationMatrix( this->deformation.x, this->deformation.y, 0.f, 0.f,
this->deformation.z, this->deformation.w, 0.f, 0.f,
0.f, 0.f, 1.f, 0.f,
0.f, 0.f, 0.f, 1.f );
this->shadowProj = this->shadowProj * deformationMatrix* this->camera.GetProjection();
this->scaledShadowProj = this->shadowProj;//* scaleAndBias;
this->dirtySProj = false;
}
//------------------------------------------------------------------------------
/**
*/
const matrix44 &
nShadowLightNode::GetShadowProjection()
{
if( this->dirtySProj )
{
this->ComputeShadowProjection();
}
return this->scaledShadowProj;
}
//------------------------------------------------------------------------------
/**
*/
bool
nShadowLightNode::Render(nSceneGraph* sceneGraph, nEntityObject* entityObject)
{
//@TODO: use the deformationMatrix
//set node own parameters
if (!nAbstractShaderNode::Apply(sceneGraph))
{
return false;
}
//set node overrides (textures passed from the lightenv)
if (!nAbstractShaderNode::Render(sceneGraph, entityObject))
{
return false;
}
nGfxServer2 *gfxServer = nGfxServer2::Instance();
nShader2* shader = gfxServer->GetShader();
n_assert(shader);
if (shader->IsParameterUsed(nShaderState::ModelShadowProjection))
{
//matrix44 invLightTransform = sceneGraph->GetModelTransform();
//invLightTransform.invert_simple();
const matrix44& model = gfxServer->GetTransform(nGfxServer2::Model);
matrix44 modelLight = model /** invLightTransform*/;
matrix44 modelShadowProjection = modelLight * this->shadowProj;
shader->SetMatrix(nShaderState::ModelShadowProjection, modelShadowProjection * scaleAndBiasTextureProjection);
}
return true;
}
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
]
| [
[
[
1,
188
]
]
]
|
30551b5a1a7af2295e2148c71be67da04c811410 | b2b5c3694476d1631322a340c6ad9e5a9ec43688 | /Baluchon/AnimatedTranslation.cpp | 56b38811220a7fecec27d0d53a2e8d63bef2c5a2 | []
| no_license | jpmn/rough-albatross | 3c456ea23158e749b029b2112b2f82a7a5d1fb2b | eb2951062f6c954814f064a28ad7c7a4e7cc35b0 | refs/heads/master | 2016-09-05T12:18:01.227974 | 2010-12-19T08:03:25 | 2010-12-19T08:03:25 | 32,195,707 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 785 | cpp | #include "AnimatedTranslation.h"
namespace baluchon { namespace core { namespace datas { namespace animation {
AnimatedTranslation::AnimatedTranslation(CvPoint3D32f vector, CvPoint3D32f increment) {
mVector = vector;
mIncrement = increment;
}
AnimatedTranslation::~AnimatedTranslation(void) {
}
void AnimatedTranslation::applyIncrement(void) {
cvmSet(mMat, 0, 3, mVector.x);
cvmSet(mTransformedMat, 0, 3, mVector.x);
cvmSet(mMat, 1, 3, mVector.y);
cvmSet(mTransformedMat, 1, 3, mVector.y);
cvmSet(mMat, 2, 3, mVector.z);
cvmSet(mTransformedMat, 2, 3, mVector.z);
if (mVector.x != 0)
mVector.x += mIncrement.x;
if (mVector.y != 0)
mVector.y += mIncrement.y;
if (mVector.z != 0)
mVector.z += mIncrement.z;
}
}}}}; | [
"jpmorin196@bd4f47a5-da4e-a94a-6a47-2669d62bc1a5"
]
| [
[
[
1,
33
]
]
]
|
1f6073f28377792fed98b9723e7285393d63aa5d | accd6e4daa3fc1103c86d245c784182e31681ea4 | /HappyHunter/Core/Sprite.cpp | 2dc54e294ad1197098f29f8a7a68233087dfceac | []
| no_license | linfuqing/zero3d | d87ad6cf97069aea7861332a9ab8fc02b016d286 | cebb12c37fe0c9047fb5b8fd3c50157638764c24 | refs/heads/master | 2016-09-05T19:37:56.213992 | 2011-08-04T01:37:36 | 2011-08-04T01:37:36 | 34,048,942 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,387 | cpp | #include "StdAfx.h"
#include "Sprite.h"
#include "d3dutils.h"
using namespace zerO;
CSprite::CSprite(void) :
m_WorldRight(1.0f, 0.0f, 0.0f),
m_WorldUp(0.0f, 1.0f, 0.0f),
m_WorldForward(0.0f, 0.0f, 1.0f),
m_Position(0.0f, 0.0f, 0.0f),
m_Rotation(0.0f, 0.0f, 0.0f),
m_Scale(1.0f, 1.0f, 1.0f),
m_uDirtyFlag(0xffffffff)
{
}
CSprite::~CSprite(void)
{
}
void CSprite::Clone(CSprite& Sprite)const
{
CSceneNode::Clone(Sprite);
Sprite.m_Position = m_Position;
Sprite.m_Rotation = m_Rotation;
Sprite.m_Scale = m_Scale;
Sprite.m_uDirtyFlag = m_uDirtyFlag;
}
void CSprite::SetDirection(const D3DXVECTOR3& Direction)
{
D3DXVECTOR3 Rotation(0.0f, 0.0f, m_Rotation.z);
DirectionToRotation(Rotation.x, Rotation.y, Direction);
SetRotation(Rotation);
}
void CSprite::SetSceneDirection(const D3DXVECTOR3& Direction)
{
SetDirection( D3DXVECTOR3(- Direction.x, - Direction.y, - Direction.z) );
}
void CSprite::Update()
{
if( TEST_BIT(m_uDirtyFlag, TRANSFORM) )
{
if( TEST_BIT(m_uDirtyFlag, SCALE) || TEST_BIT(m_uDirtyFlag, ROTATION) )
{
D3DXMATRIX Matrix;
D3DXMatrixScaling(&m_LocalMatrix, m_Scale.x, m_Scale.y, m_Scale.z);
if( TEST_BIT(m_uDirtyFlag, ROTATION) )
{
D3DXQuaternionRotationYawPitchRoll(&m_Quaternion, m_Rotation.y, m_Rotation.x, m_Rotation.z);
CLEAR_BIT(m_uDirtyFlag, ROTATION);
}
D3DXMatrixRotationQuaternion(&Matrix, &m_Quaternion);
m_LocalMatrix *= Matrix;
m_LocalMatrix._41 = m_Position.x;
m_LocalMatrix._42 = m_Position.y;
m_LocalMatrix._43 = m_Position.z;
//m_LocalMatrix._44 = m_Position.w;
CLEAR_BIT(m_uDirtyFlag, SCALE);
SET_BIT(m_uDirtyFlag, RIGHT );
SET_BIT(m_uDirtyFlag, UP );
SET_BIT(m_uDirtyFlag, FORWARD);
}
else if( TEST_BIT(m_uDirtyFlag, POSITION) )
{
m_LocalMatrix._41 = m_Position.x;
m_LocalMatrix._42 = m_Position.y;
m_LocalMatrix._43 = m_Position.z;
//m_LocalMatrix._44 = m_Position.w;
CLEAR_BIT(m_uDirtyFlag, POSITION);
}
CLEAR_BIT(m_uDirtyFlag, TRANSFORM);
m_bIsTransformDirty = true;
}
CSceneNode::Update();
}
void CSprite::UpdateTransform()
{
CSceneNode::UpdateTransform();
SET_BIT(m_uDirtyFlag, WORLD_RIGHT );
SET_BIT(m_uDirtyFlag, WORLD_UP );
SET_BIT(m_uDirtyFlag, WORLD_FORWARD);
}
void CSprite::Right(zerO::FLOAT fNumSteps)
{
D3DXVECTOR3 Right(m_LocalMatrix._11, m_LocalMatrix._12, m_LocalMatrix._13);
if(m_LocalMatrix._14)
Right /= m_LocalMatrix._14;
D3DXVec3Normalize(&Right, &Right);
Right *= fNumSteps;
m_Position += Right;
SET_BIT(m_uDirtyFlag, TRANSFORM);
SET_BIT(m_uDirtyFlag, POSITION);
}
void CSprite::Up(zerO::FLOAT fNumSteps)
{
D3DXVECTOR3 Up(m_LocalMatrix._21, m_LocalMatrix._22, m_LocalMatrix._23);
if(m_LocalMatrix._24)
Up /= m_LocalMatrix._24;
D3DXVec3Normalize(&Up, &Up);
Up *= fNumSteps;
m_Position += Up;
SET_BIT(m_uDirtyFlag, TRANSFORM);
SET_BIT(m_uDirtyFlag, POSITION);
}
void CSprite::Forward(zerO::FLOAT fNumSteps)
{
D3DXVECTOR3 Forward(m_LocalMatrix._31, m_LocalMatrix._32, m_LocalMatrix._33);
if(m_LocalMatrix._34)
Forward /= m_LocalMatrix._34;
D3DXVec3Normalize(&Forward, &Forward);
Forward *= fNumSteps;
m_Position += Forward;
SET_BIT(m_uDirtyFlag, TRANSFORM);
SET_BIT(m_uDirtyFlag, POSITION);
} | [
"[email protected]"
]
| [
[
[
1,
155
]
]
]
|
a169c32244da160dea823121828f88d5c02d78e1 | 3533c9f37def95dcc9d6b530c59138f7570ca239 | /guCORE/include/guCORE_CMultiplayerGameRegistry.h | 9418aa650d93d5b6839202798a71cb50f59bc7c2 | []
| no_license | LiberatorUSA/GU | 7e8af0dccede7edf5fc9c96c266b9888cff6d76e | 2493438447e5cde3270e1c491fe2a6094dc0b4dc | refs/heads/master | 2021-01-01T18:28:53.809051 | 2011-06-04T00:12:42 | 2011-06-04T00:12:42 | 41,840,823 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,795 | h | /*
* guCORE: Main module of the Galaxy Unlimited system
* Copyright (C) 2002 - 2008. Dinand Vanvelzen
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef GU_CORE_CMULTIPLAYERGAMEREGISTRY_H
#define GU_CORE_CMULTIPLAYERGAMEREGISTRY_H
/*-------------------------------------------------------------------------//
// //
// INCLUDE //
// //
//-------------------------------------------------------------------------*/
#ifndef GUCEF_CORE_CTREGISTRY_H
#include "CTRegistry.h" /* registry template */
#define GUCEF_CORE_CTREGISTRY_H
#endif /* GUCEF_CORE_CTREGISTRY_H ? */
#ifndef GU_CORE_CMULTIPLAYERGAME_H
#include "guCORE_CMultiplayerGame.h"
#define GU_CORE_CMULTIPLAYERGAME_H
#endif /* GU_CORE_CMULTIPLAYERGAME_H ? */
/*-------------------------------------------------------------------------//
// //
// NAMESPACE //
// //
//-------------------------------------------------------------------------*/
namespace GU {
namespace CORE {
/*-------------------------------------------------------------------------//
// //
// CLASSES //
// //
//-------------------------------------------------------------------------*/
typedef GUCEF::CORE::CTRegistry< CMultiplayerGame > CMultiplayerGameRegistry;
typedef CMultiplayerGameRegistry::TRegisteredObjPtr CMultiplayerGamePtr;
/*-------------------------------------------------------------------------//
// //
// NAMESPACE //
// //
//-------------------------------------------------------------------------*/
}; /* namespace CORE */
}; /* namespace GU */
/*-------------------------------------------------------------------------*/
#endif /* GU_CORE_CMULTIPLAYERGAMEREGISTRY_H ? */
/*-------------------------------------------------------------------------//
// //
// Info & Changes //
// //
//-------------------------------------------------------------------------//
- 08-04-2005 :
- Initial implementation
---------------------------------------------------------------------------*/
| [
"[email protected]"
]
| [
[
[
1,
79
]
]
]
|
9fba4ede82872f0f9b89072176244bd16b750b57 | e68cf672cdb98181db47dab9fb8c45e69b91e256 | /src/DynamicTexture2D.cpp | a5ccdbc608e3a0d4a37a89e288013614b91bb355 | []
| no_license | jiawen/QD3D11 | 09fc794f580db59bfc2faffbe3373a442180e0a5 | c1411967bd2da8d012eddf640eeb5f7b86e66374 | refs/heads/master | 2021-01-21T13:52:48.111246 | 2011-12-19T19:07:17 | 2011-12-19T19:07:17 | 2,549,080 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,844 | cpp | #include "DynamicTexture2D.h"
// static
DynamicTexture2D* DynamicTexture2D::createFloat1( ID3D11Device* pDevice, int width, int height )
{
ID3D11Texture2D* pTexture;
D3D11_TEXTURE2D_DESC td = makeTextureDescription( width, height, DXGI_FORMAT_R32_FLOAT );
pDevice->CreateTexture2D( &td, NULL, &pTexture );
return new DynamicTexture2D( pDevice, width, height, pTexture );
}
// static
DynamicTexture2D* DynamicTexture2D::createFloat2( ID3D11Device* pDevice, int width, int height )
{
ID3D11Texture2D* pTexture;
D3D11_TEXTURE2D_DESC td = makeTextureDescription( width, height, DXGI_FORMAT_R32G32_FLOAT );
pDevice->CreateTexture2D( &td, NULL, &pTexture );
return new DynamicTexture2D( pDevice, width, height, pTexture );
}
// static
DynamicTexture2D* DynamicTexture2D::createFloat4( ID3D11Device* pDevice, int width, int height )
{
ID3D11Texture2D* pTexture;
D3D11_TEXTURE2D_DESC td = makeTextureDescription( width, height, DXGI_FORMAT_R32G32B32A32_FLOAT );
pDevice->CreateTexture2D( &td, NULL, &pTexture );
return new DynamicTexture2D( pDevice, width, height, pTexture );
}
// static
DynamicTexture2D* DynamicTexture2D::createUnsignedShort1( ID3D11Device* pDevice, int width, int height )
{
ID3D11Texture2D* pTexture;
D3D11_TEXTURE2D_DESC td = makeTextureDescription( width, height, DXGI_FORMAT_R16_UINT );
pDevice->CreateTexture2D( &td, NULL, &pTexture );
return new DynamicTexture2D( pDevice, width, height, pTexture );
}
// static
DynamicTexture2D* DynamicTexture2D::createUnsignedShort1UNorm( ID3D11Device* pDevice, int width, int height )
{
ID3D11Texture2D* pTexture;
D3D11_TEXTURE2D_DESC td = makeTextureDescription( width, height, DXGI_FORMAT_R16_UNORM );
pDevice->CreateTexture2D( &td, NULL, &pTexture );
return new DynamicTexture2D( pDevice, width, height, pTexture );
}
// static
DynamicTexture2D* DynamicTexture2D::createUnsignedByte4( ID3D11Device* pDevice, int width, int height )
{
ID3D11Texture2D* pTexture;
D3D11_TEXTURE2D_DESC td = makeTextureDescription( width, height, DXGI_FORMAT_R8G8B8A8_UNORM );
pDevice->CreateTexture2D( &td, NULL, &pTexture );
return new DynamicTexture2D( pDevice, width, height, pTexture );
}
// virtual
DynamicTexture2D::~DynamicTexture2D()
{
m_pTexture->Release();
m_pShaderResourceView->Release();
}
int DynamicTexture2D::width()
{
return m_width;
}
int DynamicTexture2D::height()
{
return m_height;
}
Vector2i DynamicTexture2D::size()
{
return Vector2i( m_width, m_height );
}
ID3D11Texture2D* DynamicTexture2D::texture()
{
return m_pTexture;
}
ID3D11ShaderResourceView* DynamicTexture2D::shaderResourceView()
{
return m_pShaderResourceView;
}
D3D11_MAPPED_SUBRESOURCE DynamicTexture2D::mapForWriteDiscard()
{
D3D11_MAPPED_SUBRESOURCE mappedResource;
m_pContext->Map( m_pTexture, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource );
return mappedResource;
}
void DynamicTexture2D::unmap()
{
m_pContext->Unmap( m_pTexture, 0 );
}
// static
D3D11_TEXTURE2D_DESC DynamicTexture2D::makeTextureDescription( int width, int height, DXGI_FORMAT format )
{
DXGI_SAMPLE_DESC sd;
sd.Count = 1;
sd.Quality = 0;
D3D11_TEXTURE2D_DESC td;
td.Width = width;
td.Height = height;
td.ArraySize = 1;
td.MipLevels = 1;
td.Format = format;
td.SampleDesc = sd;
td.Usage = D3D11_USAGE_DYNAMIC;
td.BindFlags = D3D11_BIND_SHADER_RESOURCE;
td.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
td.MiscFlags = 0;
return td;
}
DynamicTexture2D::DynamicTexture2D( ID3D11Device* pDevice, int width, int height, ID3D11Texture2D* pTexture ) :
m_width( width ),
m_height( height ),
m_pTexture( pTexture )
{
pDevice->CreateShaderResourceView( pTexture, NULL, &m_pShaderResourceView );
pDevice->GetImmediateContext( &m_pContext );
}
| [
"[email protected]"
]
| [
[
[
1,
136
]
]
]
|
352f32bb1cab021babb81dbdde94cb5f78a78f57 | 9b75c1c40dbeda4e9d393278d38a36a61484a5b6 | /cpp files to be pasted in INCLUDE directory/ROOTS.CPP | 652a290accab3ab67aa681cd0b925d8ea5e1c27b | []
| no_license | yeskarthik/Project-Shark | b5fe9f14913618f0205c4a82003e466da52f7929 | 042869cd69b60e958c65de2a17b0bd34612e28dc | refs/heads/master | 2020-05-22T13:49:42.317314 | 2011-04-06T06:35:21 | 2011-04-06T06:35:21 | 1,575,801 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,704 | cpp | #include<iostream.h>
#include<graphics.h>
#include<stdlib.h>
#include<bios.h>
#include<dos.h>
#include<math.h>
#include<conio.h>
void rootmain()
{
int gd=VGA,gm=2;
initgraph(&gd,&gm,"d:/tc1/bgi");
long int a[7],n,b[7],t=0;
cleardevice();
gotoxy(10,10);
cout<<"Hey!!";
cout<<"\n\n\tThis is a Program to find the roots of any nth degree equation\n\tThis may be useful in mathematics and physics very much.\n\tHope You Will Enjoy Using this \n\n\t\tThanking You\n\t\
The Shark Associates\n\t\t";
getch();
do{
cleardevice();
gotoxy(10,10);
cout<<"Enter degree :";
cin>>n;
for(int i=0;i<=n;i++)
{
cout<<"Enter coefficient in order :";
cin>>a[i];
}
long int flag=0,f=0;
long int k=n;
long int jo,mo;
cout<<"Enter Expected Range of the Roots lesser to greater if you dunno press 0 0 \n\n";
cin>>jo>>mo;
if(jo==0&&mo==0)
{
jo=-9999999;
mo=9999999;
}
cout<<"\n\nPlease wait while the computer thinks!:)\n";
for(long int j=jo-1;j<mo+1&&t<=n-1;j++,f++)
{
long double s=0;
k=n;
if(j!=0)
{
for(i=0;i<=n;i++)
{
s=s+pow(j,i)*a[k];
k--;
}
if(s==0)
{
b[t]=j;
t++;
flag=1;
}
}
}
cout<<endl;
if(n==0)cout<<"Root is :"<<0;
else if(flag==0)cout<<"No Real or integral Roots !";
else
{
cout<<"The Distinct Root(s) of the given equation are :";
for(i=0;i<t;i++)
cout<<b[i]<<' ';
}
cout << "\nNo. of times loop ran = " << f ;
cout<<"\n\tThank You";
cout<<"\n\nPress Any key to continue ";
cout<<"\nPress Esc to Exit";
int u=bioskey(0);
if(u==283)break;
getch();
}while(7);
}
| [
"[email protected]"
]
| [
[
[
1,
82
]
]
]
|
033472a6bf2b07bb8783994e9d2f16b381b19989 | 2b3ff42b129d9af57079558a41e826089ab570c2 | /0.99.x/lib/Source/tb2k/TB2DsgnItemEditor.hpp | bcf2cfdfd65d43e79ef04cf388b13cf7e107ac58 | []
| no_license | bravesoftdz/contexteditor-1 | 07c242f7080846aa56b62b4d0e7790ecbb0167da | 9f26c456cda4d7546217fed6557bf2440ca097fd | refs/heads/master | 2020-03-25T18:36:18.350531 | 2009-08-25T01:34:08 | 2009-08-25T01:34:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,679 | hpp | // CodeGear C++Builder
// Copyright (c) 1995, 2008 by CodeGear
// All rights reserved
// (DO NOT EDIT: machine generated header) 'Tb2dsgnitemeditor.pas' rev: 20.00
#ifndef Tb2dsgnitemeditorHPP
#define Tb2dsgnitemeditorHPP
#pragma delphiheader begin
#pragma option push
#pragma option -w- // All warnings off
#pragma option -Vx // Zero-length empty class member functions
#pragma pack(push,8)
#include <System.hpp> // Pascal unit
#include <Sysinit.hpp> // Pascal unit
#include <Windows.hpp> // Pascal unit
#include <Messages.hpp> // Pascal unit
#include <Sysutils.hpp> // Pascal unit
#include <Classes.hpp> // Pascal unit
#include <Graphics.hpp> // Pascal unit
#include <Controls.hpp> // Pascal unit
#include <Forms.hpp> // Pascal unit
#include <Dialogs.hpp> // Pascal unit
#include <Stdctrls.hpp> // Pascal unit
#include <Extctrls.hpp> // Pascal unit
#include <Buttons.hpp> // Pascal unit
#include <Comctrls.hpp> // Pascal unit
#include <Imglist.hpp> // Pascal unit
#include <Menus.hpp> // Pascal unit
#include <Tb2item.hpp> // Pascal unit
#include <Tb2toolbar.hpp> // Pascal unit
#include <Tb2dock.hpp> // Pascal unit
#include <Designintf.hpp> // Pascal unit
#include <Designwindows.hpp> // Pascal unit
#include <Designeditors.hpp> // Pascal unit
//-- user supplied -----------------------------------------------------------
namespace Tb2dsgnitemeditor
{
//-- type declarations -------------------------------------------------------
class DELPHICLASS TTBItemEditForm;
class PASCALIMPLEMENTATION TTBItemEditForm : public Designwindows::TDesignWindow
{
typedef Designwindows::TDesignWindow inherited;
__published:
Comctrls::TTreeView* TreeView;
Comctrls::TListView* ListView;
Extctrls::TSplitter* Splitter1;
Tb2toolbar::TTBToolbar* Toolbar;
Tb2item::TTBItem* NewSubmenuButton;
Tb2item::TTBItem* NewItemButton;
Tb2item::TTBItem* NewSepButton;
Tb2item::TTBItem* DeleteButton;
Tb2item::TTBSeparatorItem* TBSeparatorItem1;
Tb2item::TTBPopupMenu* TBPopupMenu1;
Tb2item::TTBItemContainer* TBItemContainer1;
Tb2item::TTBSubmenuItem* ToolbarItems;
Tb2item::TTBItem* CopyButton;
Tb2item::TTBItem* CutButton;
Tb2item::TTBItem* PasteButton;
Tb2item::TTBSubmenuItem* MoreMenu;
Tb2item::TTBSeparatorItem* TBSeparatorItem2;
Tb2item::TTBSubmenuItem* TBSubmenuItem1;
Tb2item::TTBItem* TConvertMenu;
Tb2item::TTBSeparatorItem* TBSeparatorItem3;
Tb2item::TTBItem* MoveUpButton;
Tb2item::TTBItem* MoveDownButton;
void __fastcall FormClose(System::TObject* Sender, Forms::TCloseAction &Action);
void __fastcall TreeViewChange(System::TObject* Sender, Comctrls::TTreeNode* Node);
void __fastcall NewSubmenuButtonClick(System::TObject* Sender);
void __fastcall NewItemButtonClick(System::TObject* Sender);
void __fastcall ListViewChange(System::TObject* Sender, Comctrls::TListItem* Item, Comctrls::TItemChange Change);
void __fastcall DeleteButtonClick(System::TObject* Sender);
void __fastcall NewSepButtonClick(System::TObject* Sender);
void __fastcall ListViewDragOver(System::TObject* Sender, System::TObject* Source, int X, int Y, Controls::TDragState State, bool &Accept);
void __fastcall ListViewDragDrop(System::TObject* Sender, System::TObject* Source, int X, int Y);
void __fastcall TreeViewEnter(System::TObject* Sender);
void __fastcall TreeViewDragDrop(System::TObject* Sender, System::TObject* Source, int X, int Y);
void __fastcall TreeViewDragOver(System::TObject* Sender, System::TObject* Source, int X, int Y, Controls::TDragState State, bool &Accept);
void __fastcall CopyButtonClick(System::TObject* Sender);
void __fastcall ListViewKeyDown(System::TObject* Sender, System::Word &Key, Classes::TShiftState Shift);
void __fastcall CutButtonClick(System::TObject* Sender);
void __fastcall PasteButtonClick(System::TObject* Sender);
void __fastcall FormActivate(System::TObject* Sender);
void __fastcall ListViewKeyPress(System::TObject* Sender, System::WideChar &Key);
void __fastcall ListViewDblClick(System::TObject* Sender);
void __fastcall ListViewEnter(System::TObject* Sender);
void __fastcall TreeViewKeyDown(System::TObject* Sender, System::Word &Key, Classes::TShiftState Shift);
void __fastcall TConvertMenuClick(System::TObject* Sender);
void __fastcall TreeViewKeyPress(System::TObject* Sender, System::WideChar &Key);
void __fastcall MoveUpButtonClick(System::TObject* Sender);
void __fastcall MoveDownButtonClick(System::TObject* Sender);
private:
Classes::TComponent* FParentComponent;
Tb2item::TTBCustomItem* FRootItem;
Tb2item::TTBCustomItem* FSelParentItem;
Classes::TList* FNotifyItemList;
int FSettingSel;
int FRebuildingTree;
int FRebuildingList;
Comctrls::TListItem* __fastcall AddListViewItem(const int Index, const Tb2item::TTBCustomItem* Item);
MESSAGE void __fastcall CMDeferUpdate(Messages::TMessage &Message);
void __fastcall Copy(void);
void __fastcall CreateNewItem(const Tb2item::TTBCustomItemClass AClass);
void __fastcall Cut(void);
void __fastcall Delete(void);
void __fastcall DeleteItem(const Tb2item::TTBCustomItem* Item);
System::UnicodeString __fastcall GetItemTreeCaption(Tb2item::TTBCustomItem* AItem);
void __fastcall GetSelItemList(const Classes::TList* AList);
void __fastcall ItemNotification(Tb2item::TTBCustomItem* Ancestor, bool Relayed, Tb2item::TTBItemChangedAction Action, int Index, Tb2item::TTBCustomItem* Item);
void __fastcall MoreItemClick(System::TObject* Sender);
void __fastcall MoveItem(int CurIndex, int NewIndex);
void __fastcall Paste(void);
void __fastcall RebuildList(void);
void __fastcall RebuildTree(void);
void __fastcall SelectInObjectInspector(Classes::TList* AList);
void __fastcall SetSelParentItem(Tb2item::TTBCustomItem* ASelParentItem);
bool __fastcall TreeViewDragHandler(System::TObject* Sender, System::TObject* Source, int X, int Y, bool Drop);
void __fastcall UnregisterAllNotifications(void);
protected:
virtual void __fastcall Notification(Classes::TComponent* AComponent, Classes::TOperation Operation);
virtual System::UnicodeString __fastcall UniqueName(Classes::TComponent* Component);
public:
__fastcall virtual TTBItemEditForm(Classes::TComponent* AOwner);
__fastcall virtual ~TTBItemEditForm(void);
virtual bool __fastcall EditAction(Designintf::TEditAction Action);
virtual Designintf::TEditState __fastcall GetEditState(void);
public:
/* TCustomForm.CreateNew */ inline __fastcall virtual TTBItemEditForm(Classes::TComponent* AOwner, int Dummy) : Designwindows::TDesignWindow(AOwner, Dummy) { }
public:
/* TWinControl.CreateParented */ inline __fastcall TTBItemEditForm(HWND ParentWindow) : Designwindows::TDesignWindow(ParentWindow) { }
};
class DELPHICLASS TTBItemsEditor;
class PASCALIMPLEMENTATION TTBItemsEditor : public Designeditors::TDefaultEditor
{
typedef Designeditors::TDefaultEditor inherited;
public:
virtual void __fastcall Edit(void);
virtual void __fastcall ExecuteVerb(int Index);
virtual System::UnicodeString __fastcall GetVerb(int Index);
virtual int __fastcall GetVerbCount(void);
public:
/* TComponentEditor.Create */ inline __fastcall virtual TTBItemsEditor(Classes::TComponent* AComponent, Designintf::_di_IDesigner ADesigner) : Designeditors::TDefaultEditor(AComponent, ADesigner) { }
public:
/* TObject.Destroy */ inline __fastcall virtual ~TTBItemsEditor(void) { }
};
class DELPHICLASS TTBItemsPropertyEditor;
class PASCALIMPLEMENTATION TTBItemsPropertyEditor : public Designeditors::TStringProperty
{
typedef Designeditors::TStringProperty inherited;
public:
virtual void __fastcall Edit(void);
virtual Designintf::TPropertyAttributes __fastcall GetAttributes(void);
virtual System::UnicodeString __fastcall GetValue();
public:
/* TPropertyEditor.Create */ inline __fastcall virtual TTBItemsPropertyEditor(const Designintf::_di_IDesigner ADesigner, int APropCount) : Designeditors::TStringProperty(ADesigner, APropCount) { }
/* TPropertyEditor.Destroy */ inline __fastcall virtual ~TTBItemsPropertyEditor(void) { }
};
//-- var, const, procedure ---------------------------------------------------
static const Word CM_DEFERUPDATE = 0x464;
extern PACKAGE void __fastcall TBRegisterItemClass(Tb2item::TTBCustomItemClass AClass, const System::UnicodeString ACaption, unsigned ResInstance);
} /* namespace Tb2dsgnitemeditor */
using namespace Tb2dsgnitemeditor;
#pragma pack(pop)
#pragma option pop
#pragma delphiheader end.
//-- end unit ----------------------------------------------------------------
#endif // Tb2dsgnitemeditorHPP
| [
"[email protected]@5d03d0dc-17f0-11de-b413-eb0469710719"
]
| [
[
[
1,
189
]
]
]
|
b272cca8dfc4edd8437a5f3a9da4d8ee9dab00ed | 709cd826da3ae55945fd7036ecf872ee7cdbd82a | /Term/WildMagic2/Renderers/DX/WmlDxMaterialState.cpp | 4c77bcbc2b178ae5a09af58a787c3959e8e55d17 | []
| no_license | argapratama/kucgbowling | 20dbaefe1596358156691e81ccceb9151b15efb0 | 65e40b6f33c5511bddf0fa350c1eefc647ace48a | refs/heads/master | 2018-01-08T15:27:44.784437 | 2011-06-19T15:23:39 | 2011-06-19T15:23:39 | 36,738,655 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,870 | cpp | // Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2003. All Rights Reserved
//
// The Wild Magic Library (WML) source code is supplied under the terms of
// the license agreement http://www.magic-software.com/License/WildMagic.pdf
// and may not be copied or disclosed except in accordance with the terms of
// that agreement.
#include "WmlDxRenderer.h"
using namespace Wml;
//----------------------------------------------------------------------------
void DxRenderer::SetMaterialState (MaterialState* pkState)
{
D3DMATERIAL9 kD3DMaterial;
kD3DMaterial.Emissive.r = pkState->Emissive().r;
kD3DMaterial.Emissive.g = pkState->Emissive().g;
kD3DMaterial.Emissive.b = pkState->Emissive().b;
kD3DMaterial.Emissive.a = 1.0f;
kD3DMaterial.Ambient.r = pkState->Ambient().r;
kD3DMaterial.Ambient.g = pkState->Ambient().g;
kD3DMaterial.Ambient.b = pkState->Ambient().b;
kD3DMaterial.Ambient.a = pkState->Alpha();
kD3DMaterial.Diffuse.r = pkState->Diffuse().r;
kD3DMaterial.Diffuse.g = pkState->Diffuse().g;
kD3DMaterial.Diffuse.b = pkState->Diffuse().b;
kD3DMaterial.Diffuse.a = pkState->Alpha();
kD3DMaterial.Specular.r = pkState->Specular().r;
kD3DMaterial.Specular.g = pkState->Specular().g;
kD3DMaterial.Specular.b = pkState->Specular().b;
kD3DMaterial.Specular.a = pkState->Alpha();
kD3DMaterial.Power = pkState->Shininess();
ms_hResult = m_pqDevice->SetMaterial(&kD3DMaterial);
WML_DX_ERROR_CHECK(SetMaterial);
// Enable per-vertex color which allows the system to include the
// color defined for individual vertices in its lighting calculations.
ms_hResult = m_pqDevice->SetRenderState(D3DRS_COLORVERTEX,TRUE);
WML_DX_ERROR_CHECK(SetRenderState);
// Allow the diffuse and specular colors to come from the color
// information specified along with the vertex. Note that if
// those particular colors are not defined along with the vertex
// then the colors diffuse or specular color from the specified
// material is used.
ms_hResult = m_pqDevice->SetRenderState(D3DRS_DIFFUSEMATERIALSOURCE,
D3DMCS_COLOR1);
WML_DX_ERROR_CHECK(SetRenderState);
ms_hResult = m_pqDevice->SetRenderState(D3DRS_SPECULARMATERIALSOURCE,
D3DMCS_COLOR2);
WML_DX_ERROR_CHECK(SetRenderState);
// Use the ambient and emissive colors defined in the material.
ms_hResult = m_pqDevice->SetRenderState(D3DRS_AMBIENTMATERIALSOURCE,
D3DMCS_MATERIAL);
WML_DX_ERROR_CHECK(SetRenderState);
ms_hResult = m_pqDevice->SetRenderState(D3DRS_EMISSIVEMATERIALSOURCE,
D3DMCS_MATERIAL);
WML_DX_ERROR_CHECK(SetRenderState);
}
//----------------------------------------------------------------------------
| [
"[email protected]"
]
| [
[
[
1,
69
]
]
]
|
35ee6378b0d586d2f9cfe3300bd3f128fb3b0d34 | d425cf21f2066a0cce2d6e804bf3efbf6dd00c00 | /Laptop/BobbyRAmmo.cpp | 050b39121fd9c088e8373b6cc9aef12a96e47988 | []
| no_license | infernuslord/ja2 | d5ac783931044e9b9311fc61629eb671f376d064 | 91f88d470e48e60ebfdb584c23cc9814f620ccee | refs/heads/master | 2021-01-02T23:07:58.941216 | 2011-10-18T09:22:53 | 2011-10-18T09:22:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,455 | cpp | #ifdef PRECOMPILEDHEADERS
#include "Laptop All.h"
#else
#include "laptop.h"
#include "BobbyRAmmo.h"
#include "BobbyRGuns.h"
#include "BobbyR.h"
#include "Utilities.h"
#include "WCheck.h"
#include "WordWrap.h"
#include "Cursors.h"
#include "interface items.h"
#include "Encrypted File.h"
#include "text.h"
#endif
UINT32 guiAmmoBackground;
UINT32 guiAmmoGrid;
BOOLEAN DisplayAmmoInfo();
void GameInitBobbyRAmmo()
{
}
BOOLEAN EnterBobbyRAmmo()
{
VOBJECT_DESC VObjectDesc;
//gfBigImageMouseRegionCreated = FALSE;
// load the background graphic and add it
VObjectDesc.fCreateFlags=VOBJECT_CREATE_FROMFILE;
FilenameForBPP("LAPTOP\\ammobackground.sti", VObjectDesc.ImageFile);
CHECKF(AddVideoObject(&VObjectDesc, &guiAmmoBackground));
// load the gunsgrid graphic and add it
VObjectDesc.fCreateFlags=VOBJECT_CREATE_FROMFILE;
FilenameForBPP("LAPTOP\\ammogrid.sti", VObjectDesc.ImageFile);
CHECKF(AddVideoObject(&VObjectDesc, &guiAmmoGrid));
InitBobbyBrTitle();
guiPrevAmmoFilterMode = -1;
guiCurrentAmmoFilterMode = -1;
SetFirstLastPagesForNew( IC_AMMO, guiCurrentAmmoFilterMode );
//Draw menu bar
InitBobbyMenuBar( );
InitBobbyRAmmoFilterBar();
RenderBobbyRAmmo( );
return(TRUE);
}
void ExitBobbyRAmmo()
{
DeleteVideoObjectFromIndex(guiAmmoBackground);
DeleteVideoObjectFromIndex(guiAmmoGrid);
DeleteBobbyMenuBar();
DeleteBobbyRAmmoFilter();
DeleteBobbyBrTitle();
DeleteMouseRegionForBigImage();
giCurrentSubPage = gusCurWeaponIndex;
guiLastBobbyRayPage = LAPTOP_MODE_BOBBY_R_AMMO;
}
void HandleBobbyRAmmo()
{
}
void RenderBobbyRAmmo()
{
HVOBJECT hPixHandle;
WebPageTileBackground(BOBBYR_NUM_HORIZONTAL_TILES, BOBBYR_NUM_VERTICAL_TILES, BOBBYR_BACKGROUND_WIDTH, BOBBYR_BACKGROUND_HEIGHT, guiAmmoBackground);
//Display title at top of page
//DisplayBobbyRBrTitle();
// GunForm
GetVideoObject(&hPixHandle, guiAmmoGrid);
BltVideoObject(FRAME_BUFFER, hPixHandle, 0, BOBBYR_GRIDLOC_X, BOBBYR_GRIDLOC_Y, VO_BLT_SRCTRANSPARENCY,NULL);
DisplayItemInfo(IC_AMMO, guiCurrentAmmoFilterMode);
UpdateButtonText(guiCurrentLaptopMode);
UpdateAmmoFilterButtons();
MarkButtonsDirty( );
RenderWWWProgramTitleBar( );
InvalidateRegion(LAPTOP_SCREEN_UL_X,LAPTOP_SCREEN_WEB_UL_Y,LAPTOP_SCREEN_LR_X,LAPTOP_SCREEN_WEB_LR_Y);
fReDrawScreenFlag = TRUE;
fPausedReDrawScreenFlag = TRUE;
}
| [
"jazz_ja@b41f55df-6250-4c49-8e33-4aa727ad62a1"
]
| [
[
[
1,
110
]
]
]
|
cfc194a5d2bf567b1d6ad517e08b1ed795eee38c | d37a1d5e50105d82427e8bf3642ba6f3e56e06b8 | /DVR/HaohanITPlayer/HWNDDLL/HWndDll.cpp | c52be4f2f92cf9c274ea6522a9d12ff41eed2885 | []
| no_license | 080278/dvrmd-filter | 176f4406dbb437fb5e67159b6cdce8c0f48fe0ca | b9461f3bf4a07b4c16e337e9c1d5683193498227 | refs/heads/master | 2016-09-10T21:14:44.669128 | 2011-10-17T09:18:09 | 2011-10-17T09:18:09 | 32,274,136 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,757 | cpp | // HWndDll.cpp : Defines the initialization routines for the DLL.
//
#include "stdafx.h"
#include "HWndDll.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
//
// Note!
//
// If this DLL is dynamically linked against the MFC
// DLLs, any functions exported from this DLL which
// call into MFC must have the AFX_MANAGE_STATE macro
// added at the very beginning of the function.
//
// For example:
//
// extern "C" BOOL PASCAL EXPORT ExportedFunction()
// {
// AFX_MANAGE_STATE(AfxGetStaticModuleState());
// // normal function body here
// }
//
// It is very important that this macro appear in each
// function, prior to any calls into MFC. This means that
// it must appear as the first statement within the
// function, even before any object variable declarations
// as their constructors may generate calls into the MFC
// DLL.
//
// Please see MFC Technical Notes 33 and 58 for additional
// details.
//
/////////////////////////////////////////////////////////////////////////////
// CHWndDllApp
BEGIN_MESSAGE_MAP(CHWndDllApp, CWinApp)
//{{AFX_MSG_MAP(CHWndDllApp)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CHWndDllApp construction
CHWndDllApp::CHWndDllApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
/////////////////////////////////////////////////////////////////////////////
// The one and only CHWndDllApp object
CHWndDllApp theApp;
| [
"[email protected]@27769579-7047-b306-4d6f-d36f87483bb3"
]
| [
[
[
1,
62
]
]
]
|
66cc264958490b06486f8702ee511614758559db | 971b000b9e6c4bf91d28f3723923a678520f5bcf | /QTextPanel/qtextpanelmargin.h | 16e93e2d253539022a9bbc9e19b176d375c51e74 | []
| 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 | 11,492 | h | /*******************************************************************************
* class GetMargin
*******************************************************************************
* 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.
*******************************************************************************/
#ifndef QTEXTPANELMARGIN_H
#define QTEXTPANELMARGIN_H
#include <iostream>
#include <stdio.h>
#include <iostream>
#include <QtCore>
#include <QDebug>
#include <QCoreApplication>
#include <QObject>
#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QComboBox>
#include <QtGui/QDialog>
#include <QtGui/QDoubleSpinBox>
#include <QtGui/QGridLayout>
#include <QtGui/QGroupBox>
#include <QtGui/QHBoxLayout>
#include <QtGui/QLabel>
#include <QtGui/QPushButton>
#include <QtGui/QSpacerItem>
#include <QtGui/QVBoxLayout>
#include "qtextpanelmime.h"
class Ui_GetMargin
{
public:
QGridLayout *gridLayout;
QVBoxLayout *vboxLayout;
QGroupBox *groupBox;
QGridLayout *gridLayout1;
QHBoxLayout *hboxLayout;
QVBoxLayout *vboxLayout1;
QSpacerItem *spacerItem;
QLabel *label_2;
QDoubleSpinBox *doubleSpinBox_3;
QSpacerItem *spacerItem1;
QVBoxLayout *vboxLayout2;
QLabel *label;
QDoubleSpinBox *doubleSpinBox_4;
QSpacerItem *spacerItem2;
QLabel *label_4;
QDoubleSpinBox *doubleSpinBox;
QVBoxLayout *vboxLayout3;
QSpacerItem *spacerItem3;
QLabel *label_3;
QDoubleSpinBox *doubleSpinBox_2;
QSpacerItem *spacerItem4;
QHBoxLayout *hboxLayout1;
QLabel *label_5;
QSpacerItem *spacerItem5;
QComboBox *comboBox;
QHBoxLayout *hboxLayout2;
QSpacerItem *spacerItem6;
QPushButton *pushButton;
QPushButton *pushButton_2;
void setupUi(QDialog *GetMargin)
{
if (GetMargin->objectName().isEmpty())
{
GetMargin->setObjectName(QString::fromUtf8("GetMargin"));
}
GetMargin->resize(306, 207);
GetMargin->setMaximumSize(QSize(310, 210));
gridLayout = new QGridLayout(GetMargin);
gridLayout->setObjectName(QString::fromUtf8("gridLayout"));
vboxLayout = new QVBoxLayout();
vboxLayout->setObjectName(QString::fromUtf8("vboxLayout"));
groupBox = new QGroupBox(GetMargin);
groupBox->setObjectName(QString::fromUtf8("groupBox"));
gridLayout1 = new QGridLayout(groupBox);
gridLayout1->setObjectName(QString::fromUtf8("gridLayout1"));
hboxLayout = new QHBoxLayout();
hboxLayout->setObjectName(QString::fromUtf8("hboxLayout"));
vboxLayout1 = new QVBoxLayout();
vboxLayout1->setObjectName(QString::fromUtf8("vboxLayout1"));
spacerItem = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
vboxLayout1->addItem(spacerItem);
label_2 = new QLabel(groupBox);
label_2->setObjectName(QString::fromUtf8("label_2"));
vboxLayout1->addWidget(label_2);
doubleSpinBox_3 = new QDoubleSpinBox(groupBox);
doubleSpinBox_3->setObjectName(QString::fromUtf8("doubleSpinBox_3"));
doubleSpinBox_3->setDecimals(4);
doubleSpinBox_3->setMinimum(-50);
doubleSpinBox_3->setMaximum(100000);
vboxLayout1->addWidget(doubleSpinBox_3);
spacerItem1 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
vboxLayout1->addItem(spacerItem1);
hboxLayout->addLayout(vboxLayout1);
vboxLayout2 = new QVBoxLayout();
vboxLayout2->setObjectName(QString::fromUtf8("vboxLayout2"));
label = new QLabel(groupBox);
label->setObjectName(QString::fromUtf8("label"));
vboxLayout2->addWidget(label);
doubleSpinBox_4 = new QDoubleSpinBox(groupBox);
doubleSpinBox_4->setObjectName(QString::fromUtf8("doubleSpinBox_4"));
doubleSpinBox_4->setDecimals(4);
doubleSpinBox_4->setMinimum(-50);
doubleSpinBox_4->setMaximum(100000);
vboxLayout2->addWidget(doubleSpinBox_4);
spacerItem2 = new QSpacerItem(20, 21, QSizePolicy::Minimum, QSizePolicy::Expanding);
vboxLayout2->addItem(spacerItem2);
label_4 = new QLabel(groupBox);
label_4->setObjectName(QString::fromUtf8("label_4"));
vboxLayout2->addWidget(label_4);
doubleSpinBox = new QDoubleSpinBox(groupBox);
doubleSpinBox->setObjectName(QString::fromUtf8("doubleSpinBox"));
doubleSpinBox->setDecimals(4);
doubleSpinBox->setMinimum(-50);
doubleSpinBox->setMaximum(100000);
vboxLayout2->addWidget(doubleSpinBox);
hboxLayout->addLayout(vboxLayout2);
vboxLayout3 = new QVBoxLayout();
vboxLayout3->setObjectName(QString::fromUtf8("vboxLayout3"));
spacerItem3 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
vboxLayout3->addItem(spacerItem3);
label_3 = new QLabel(groupBox);
label_3->setObjectName(QString::fromUtf8("label_3"));
vboxLayout3->addWidget(label_3);
doubleSpinBox_2 = new QDoubleSpinBox(groupBox);
doubleSpinBox_2->setObjectName(QString::fromUtf8("doubleSpinBox_2"));
doubleSpinBox_2->setDecimals(4);
doubleSpinBox_2->setMinimum(-50);
doubleSpinBox_2->setMaximum(100000);
vboxLayout3->addWidget(doubleSpinBox_2);
spacerItem4 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
vboxLayout3->addItem(spacerItem4);
hboxLayout->addLayout(vboxLayout3);
gridLayout1->addLayout(hboxLayout, 0, 0, 1, 1);
vboxLayout->addWidget(groupBox);
hboxLayout1 = new QHBoxLayout();
hboxLayout1->setObjectName(QString::fromUtf8("hboxLayout1"));
label_5 = new QLabel(GetMargin);
label_5->setObjectName(QString::fromUtf8("label_5"));
hboxLayout1->addWidget(label_5);
spacerItem5 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
hboxLayout1->addItem(spacerItem5);
comboBox = new QComboBox(GetMargin);
comboBox->setObjectName(QString::fromUtf8("comboBox"));
hboxLayout1->addWidget(comboBox);
vboxLayout->addLayout(hboxLayout1);
hboxLayout2 = new QHBoxLayout();
hboxLayout2->setObjectName(QString::fromUtf8("hboxLayout2"));
spacerItem6 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
hboxLayout2->addItem(spacerItem6);
pushButton = new QPushButton(GetMargin);
pushButton->setObjectName(QString::fromUtf8("pushButton"));
hboxLayout2->addWidget(pushButton);
pushButton_2 = new QPushButton(GetMargin);
pushButton_2->setObjectName(QString::fromUtf8("pushButton_2"));
hboxLayout2->addWidget(pushButton_2);
vboxLayout->addLayout(hboxLayout2);
gridLayout->addLayout(vboxLayout, 0, 0, 1, 1);
retranslateUi(GetMargin);
QObject::connect(pushButton, SIGNAL(clicked()), GetMargin, SLOT(accept()));
QObject::connect(pushButton_2, SIGNAL(clicked()), GetMargin, SLOT(reject()));
comboBox->setCurrentIndex(0);
QMetaObject::connectSlotsByName(GetMargin);
}
void retranslateUi(QDialog *GetMargin)
{
GetMargin->setWindowTitle(QApplication::translate("GetMargin", "GetMargin Padding", 0, QApplication::UnicodeUTF8));
groupBox->setTitle(QApplication::translate("GetMargin", "Margin/Padding", 0, QApplication::UnicodeUTF8));
label_2->setText(QApplication::translate("GetMargin", "Left", 0, QApplication::UnicodeUTF8));
label->setText(QApplication::translate("GetMargin", "Top", 0, QApplication::UnicodeUTF8));
label_4->setText(QApplication::translate("GetMargin", "Bottom", 0, QApplication::UnicodeUTF8));
label_3->setText(QApplication::translate("GetMargin", "Right", 0, QApplication::UnicodeUTF8));
label_5->setText(QApplication::translate("GetMargin", "Unit:", 0, QApplication::UnicodeUTF8));
pushButton->setText(QApplication::translate("GetMargin", "OK", 0, QApplication::UnicodeUTF8));
pushButton_2->setText(QApplication::translate("GetMargin", "Close", 0, QApplication::UnicodeUTF8));
doubleSpinBox_3->setSuffix(QApplication::translate("GetMargin", " pt.", 0, QApplication::UnicodeUTF8));
doubleSpinBox_4->setSuffix(QApplication::translate("GetMargin", " pt.", 0, QApplication::UnicodeUTF8));
doubleSpinBox->setSuffix(QApplication::translate("GetMargin", " pt.", 0, QApplication::UnicodeUTF8));
doubleSpinBox_2->setSuffix(QApplication::translate("GetMargin", " pt.", 0, QApplication::UnicodeUTF8));
comboBox->insertItems(0, QStringList()
<< QApplication::translate("GetMargin", "mm", 0, QApplication::UnicodeUTF8)
<< QApplication::translate("GetMargin", "cm", 0, QApplication::UnicodeUTF8)
<< QApplication::translate("GetMargin", "inch", 0, QApplication::UnicodeUTF8)
<< QApplication::translate("GetMargin", "pt", 0, QApplication::UnicodeUTF8)
<< QApplication::translate("GetMargin", "em", 0, QApplication::UnicodeUTF8)
<< QApplication::translate("GetMargin", "dm", 0, QApplication::UnicodeUTF8)
<< QApplication::translate("GetMargin", "pi", 0, QApplication::UnicodeUTF8)
<< QApplication::translate("GetMargin", "dd", 0, QApplication::UnicodeUTF8)
<< QApplication::translate("GetMargin", "cc", 0, QApplication::UnicodeUTF8)
<< QApplication::translate("GetMargin", "in", 0, QApplication::UnicodeUTF8)
);
Q_UNUSED(GetMargin);
}
};
namespace Ui
{
class GetMargin: public Ui_GetMargin {};
}
class GetMargin : public QDialog, public Ui::GetMargin
{
Q_OBJECT
private:
////////GetMargin( QWidget* = 0 );
/////static QPointer<GetMargin> _self;
void Load_Connector();
protected:
QString one;
qreal a1;
qreal a2;
qreal a3;
qreal a4;
bool Genable;
int nummer;
QSettings setter;
QString unitas;
QRectF current;
void closeEvent(QCloseEvent*);
public:
GetMargin(QWidget* = 0);
inline QRectF Get_margin()
{
return current;
}
inline void Set_margin(const QRectF n)
{
/* QRectF ( qreal x, qreal y, qreal width, qreal height ) GoPoint(,unitas) */
current = n;
Genable = false;
/* save internal on point */
a1 = n.x() ;
a2 = n.y();
a3 = n.width();
a4 = n.height();
//////qDebug() << "### incomming -> " << n;
doubleSpinBox_4->setValue(pointTo(n.x(),unitas)); /* top */
doubleSpinBox_2->setValue(pointTo(n.y(),unitas)); /* right*/
doubleSpinBox->setValue(pointTo(n.width(),unitas)); /* bottom */
doubleSpinBox_3->setValue(pointTo(n.height(),unitas)); /* left */
Genable = true;
///////UnitChange("pt");
/*marge->Set_margin( QRectF (fo.topMargin(), fo.rightMargin() ,fo.bottomMargin() , fo.leftMargin() ) ); */
}
public slots:
void UnitChange(const QString unite);
void UpdateVars();
};
#endif // QTEXTPANELMARGIN_H
| [
"[email protected]@9af58faf-7e3e-0410-b956-55d145112073"
]
| [
[
[
1,
325
]
]
]
|
6de77fa722405de684804bd3667c3648866e6e4e | 465943c5ffac075cd5a617c47fd25adfe496b8b4 | /PLANECMN.H | 473cfc9cfbdfbb7b26d165b4b48cbce59ed92262 | []
| no_license | paulanthonywilson/airtrafficcontrol | 7467f9eb577b24b77306709d7b2bad77f1b231b7 | 6c579362f30ed5f81cabda27033f06e219796427 | refs/heads/master | 2016-08-08T00:43:32.006519 | 2009-04-09T21:33:22 | 2009-04-09T21:33:22 | 172,292 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 405 | h | /* Plane command class
version 0.1
Nick Papa 22/04/96.
ver 0.2
27/4/96 PW
Plane accessor added
*/
# ifndef _PLANECMND_H
# define _PLANECMND_H
# include "cmnd.h"
# include "plane.h"
class PlaneCmnd : public Cmnd {
protected:
Plane *p_c;
public :
PlaneCmnd (Plane *pl) {
p_c = pl;
}
Plane *P() {
return p_c;
}
};
# endif _PLANECMND_H
| [
"[email protected]"
]
| [
[
[
1,
35
]
]
]
|
3fb4f847fbb26cea3e7d3d3ff085bdfca1806c7d | 94c1c7459eb5b2826e81ad2750019939f334afc8 | /source/ChildFrm.cpp | 65600bd675a8bb6b26648cb1afefd167c3c7ea38 | []
| no_license | wgwang/yinhustock | 1c57275b4bca093e344a430eeef59386e7439d15 | 382ed2c324a0a657ddef269ebfcd84634bd03c3a | refs/heads/master | 2021-01-15T17:07:15.833611 | 2010-11-27T07:06:40 | 2010-11-27T07:06:40 | 37,531,026 | 1 | 3 | null | null | null | null | GB18030 | C++ | false | false | 9,442 | cpp |
#include "stdafx.h"
#include "CTaiShanApp.h"
#include "ChildFrm.h"
#include "CTaiShanDoc.h"
#include "cellRange.h"
#include "CTaiShanReportView.h"
#include "MySplitter.h"
#include "MainFrm.h"
#include "CTaiShanKlineShowView.h"
#include "MyTreeView.h"
#include "MyRichView.h"
#include "CTaiKlineDialogCross.h"
#include "CTaiKlineDialogKLineMode.h"
#include "CTaiKlineDlgChangeIndexParam.h"
/////////////////////////////////////////////////////////////////////
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
class CTaiShanReportView;//对话框基类
/////////////////////////////////////////////////////////////////////////////
// CChildFrame
IMPLEMENT_DYNCREATE(CChildFrame, CMDIChildWnd)
BEGIN_MESSAGE_MAP(CChildFrame, CMDIChildWnd)
//{{AFX_MSG_MAP(CChildFrame)
ON_WM_SHOWWINDOW()
ON_WM_SIZE()
ON_WM_CLOSE()
ON_WM_MDIACTIVATE()
ON_WM_SETFOCUS()
//}}AFX_MSG_MAP
ON_MESSAGE(WM_USER_CHANGEPOS,OnSetSplitterPos)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
CChildFrame::CChildFrame()
{
m_wndSplitter=NULL;
m_pContext=NULL;
m_CurrentDoc = NULL;
}
CChildFrame::~CChildFrame()
{//从该类继承
if(m_wndSplitter) delete m_wndSplitter;
if(m_pContext) delete m_pContext;
}
#ifdef _DEBUG
void CChildFrame::AssertValid() const
{
CMDIChildWnd::AssertValid();
}
void CChildFrame::Dump(CDumpContext& dc) const
{
CMDIChildWnd::Dump(dc);
}
#endif
/////////////////////////////////////////////////////////////////////////////
// CChildFrame message handlers
BOOL CChildFrame::OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext)
{
m_pContext = new CCreateContext;
memcpy(m_pContext, pContext, sizeof(CCreateContext));
return CMDIChildWnd::OnCreateClient(lpcs, pContext);
}
BOOL CChildFrame::PreCreateWindow(CREATESTRUCT& cs)
{
if (!CMDIChildWnd::PreCreateWindow(cs))
return FALSE;
return TRUE;
}
void CChildFrame::OnShowWindow(BOOL bShow, UINT nStatus)
{
CMDIChildWnd::OnShowWindow(bShow, nStatus);
static int IsTheFirstTime = 0;
if(IsTheFirstTime == 0)
{
CMenu* mnu;
mnu=GetSystemMenu(false);
mnu->EnableMenuItem( SC_CLOSE,MF_GRAYED|MF_DISABLED);
SendMessage(WM_INITMENU,(UINT)mnu->m_hMenu ,0);
this->MDIMaximize( );
IsTheFirstTime++;
}
}
void CChildFrame::OnSize(UINT nType, int cx, int cy)
{//为该类的对象
CMDIChildWnd::OnSize(nType, cx, cy);
if(cx==0||cy==0)
return ;
if(m_wndSplitter==NULL)
return ;
int m_width=285+18;
if(m_width > cx)
m_width=2 * cx /3;
m_wndSplitter->SetColumnInfo( 0, cx - m_width , 0 );
m_wndSplitter->RecalcLayout( );
}
void CChildFrame::CreateF9()
{
m_SplitterWnd = new CTaiTestSplitter;
CWnd* pMainWnd=AfxGetApp()->m_pMainWnd;
CFrameWnd * pActiveWnd=((CFrameWnd*)pMainWnd)->GetActiveFrame();
m_CurrentDoc = (CTaiShanDoc*)pActiveWnd->GetActiveDocument();
CView* pOldActiveView = GetActiveView();
if (!m_SplitterWnd->CreateStatic(this, 1, 2))
{
TRACE0("Failed to CreateStaticSplitter\n");
return ;
}
CRect rc;
GetClientRect(&rc);//静态变量
if (!m_SplitterWnd->CreateView(0, 0,
RUNTIME_CLASS(CTaiTestTreeView), CSize(rc.Width()/4, rc.Height()), m_pContext))
{
TRACE0("Failed to create first pane\n");
return ;
}
if (!m_SplitterWnd->CreateView(0, 1,
RUNTIME_CLASS(CTaiTestRichView), CSize(0, 0), m_pContext))
{
TRACE0("Failed to create second pane\n");
return ;
}
CTaiTestRichView *m_pRichView;
m_pRichView = (CTaiTestRichView *)m_SplitterWnd->GetPane(0,1);
m_pRichView->m_bF9ORF10 = TRUE;
CHARFORMAT m_charformat;
m_charformat.cbSize = 60;
m_charformat.dwMask = 3892314127;
m_charformat.dwEffects = 0;
m_charformat.yHeight = 240;
m_charformat.yOffset = 0;
m_charformat.bCharSet = 134;
m_charformat.bPitchAndFamily = 2;
m_charformat.crTextColor = RGB(0 ,0,0);
lstrcpy(m_charformat.szFaceName,"宋体");
m_pRichView->GetRichEditCtrl().SetDefaultCharFormat(m_charformat);
CTaiTestTreeView *m_pTreeView;
m_pTreeView = (CTaiTestTreeView *)m_SplitterWnd->GetPane(0,0);
m_pTreeView->m_bF9ORF10 = TRUE;
m_pTreeView->ShowAll();
m_CurrentDoc->m_taiViewF9 = m_pTreeView;
OnSize(SIZE_RESTORED,0,0);
pOldActiveView->DestroyWindow();
OnUpdateFrameTitle(TRUE);
}
void CChildFrame::CreateF10()
{//应用程序类
m_SplitterWnd = new CTaiTestSplitter;
CWnd* pMainWnd=AfxGetApp()->m_pMainWnd;
CFrameWnd * pActiveWnd=((CFrameWnd*)pMainWnd)->GetActiveFrame();
m_CurrentDoc = (CTaiShanDoc*)pActiveWnd->GetActiveDocument();
CView* pOldActiveView = GetActiveView();
if (!m_SplitterWnd->CreateStatic(this, 1, 2))
{
TRACE0("Failed to CreateStaticSplitter\n");
return ;
}
CRect rc;
GetClientRect(&rc);
if (!m_SplitterWnd->CreateView(0, 0,
RUNTIME_CLASS(CTaiTestTreeView), CSize(rc.Width()/4 , rc.Height()), m_pContext))
{
TRACE0("Failed to create first pane\n");
return ;
}
if (!m_SplitterWnd->CreateView(0, 1,
RUNTIME_CLASS(CTaiTestRichView), CSize(0, 0), m_pContext))
{
TRACE0("Failed to create second pane\n");
return ;
}
CTaiTestRichView *m_pRichView;//子窗口框架
m_pRichView = (CTaiTestRichView *)m_SplitterWnd->GetPane(0,1);
m_pRichView->m_bF9ORF10 = FALSE;
CHARFORMAT m_charformat;
m_charformat.cbSize = 60;
m_charformat.dwMask = 3892314127;
m_charformat.dwEffects = 0;
m_charformat.yHeight = 240;
m_charformat.yOffset = 0;
m_charformat.bCharSet = 134;
m_charformat.bPitchAndFamily = 2;
m_charformat.crTextColor = RGB(0 ,0,0);
lstrcpy(m_charformat.szFaceName,"宋体");
m_pRichView->GetRichEditCtrl().SetDefaultCharFormat(m_charformat);
CTaiTestTreeView *m_pTreeView;
m_pTreeView = (CTaiTestTreeView *)m_SplitterWnd->GetPane(0,0);
m_pTreeView->m_bF9ORF10 = FALSE;
m_pTreeView->ShowAllF10();
m_CurrentDoc->m_taiViewF10 = m_pTreeView;
OnSize(SIZE_RESTORED,0,0);
pOldActiveView->DestroyWindow();
SetWindowText("上市公司基本资料");
GetMDIFrame()->OnUpdateFrameTitle(TRUE);
}
void CChildFrame::OnClose()
{
CView *pView = GetActiveView();
if(pView == NULL)
{
CMDIChildWnd::OnClose();
}
else if(pView->IsKindOf(RUNTIME_CLASS(CTaiShanReportView)))
{
return;
}
else if(pView->IsKindOf(RUNTIME_CLASS(CTaiShanKlineShowView)))
{
CWnd* pMainWnd=AfxGetApp()->m_pMainWnd;
CFrameWnd * pActiveWnd=((CFrameWnd*)pMainWnd)->GetActiveFrame();
CTaiShanDoc *pDoc = (CTaiShanDoc*)pActiveWnd->GetActiveDocument();
POSITION pos = pDoc->GetFirstViewPosition();
CView *pView;
while(pos != NULL)
{
pView = pDoc->GetNextView(pos);
if(pView->IsKindOf(RUNTIME_CLASS(CTaiShanReportView)))
{
((CTaiShanReportView *)pView)->m_nFirst = 1;
break;
}
}
CMDIChildWnd::OnClose();
}
else
{
CMDIChildWnd::OnClose();
}
}
void CChildFrame::OnMDIActivate(BOOL bActivate, CWnd* pActivateWnd, CWnd* pDeactivateWnd)
{//基本资料数据结构类实现
CMDIChildWnd::OnMDIActivate(bActivate, pActivateWnd, pDeactivateWnd);
CView *pView = GetActiveView();
if(pView == NULL)
return;
if(bActivate == TRUE && pView->IsKindOf(RUNTIME_CLASS(CTaiShanReportView)))
{
((CTaiShanReportView *)pView)->ActiveGrid();
return;
}
}
LRESULT CChildFrame::OnSetSplitterPos(WPARAM wParam, LPARAM lParam)
{
long Width=(long)lParam;
CRect rc;
GetClientRect(&rc);
if(rc.right < Width)
Width=rc.right;
m_wndSplitter->SetColumnInfo( 0, rc.right - Width , 0 );
m_wndSplitter->RecalcLayout( );
((CTaiShanReportView*)m_wndSplitter->GetPane(0,0))->SetFocus();
return 0;
}
void CChildFrame::OnUpdateFrameTitle(BOOL bAddToTitle)
{//基本资料
CTaiShanDoc* pDoc = ((CMainFrame *)AfxGetMainWnd())->m_taiShanDoc;
CView* pView = GetActiveView();
CWnd *pWnd = GetWindow(GW_CHILD);
if(bAddToTitle && pDoc != NULL)
{
CString strCurCaption,strWindowText,strNewCaption;
if(pView == NULL)
return;
if(pView->IsKindOf(RUNTIME_CLASS(CTaiTestRichView)))
{//基本资料数据结构类实现
if(((CTaiTestRichView *)pView)->m_bF9ORF10 == TRUE)
SetWindowText("公告信息");
if(((CTaiTestRichView *)pView)->m_bF9ORF10 == FALSE)
SetWindowText("上市公司基本资料");
GetMDIFrame()->OnUpdateFrameTitle(bAddToTitle);
return;
}
if(pWnd->IsKindOf(RUNTIME_CLASS(CSplitterWnd)))
{
GetMDIFrame()->OnUpdateFrameTitle(bAddToTitle);
return;
}
if(!pView->IsKindOf(RUNTIME_CLASS(CInfoView)))
{
GetWindowText(strCurCaption);
GetActiveView()->GetWindowText(strWindowText);
const CString&strDocTitle = pDoc->GetTitle();
strNewCaption = strDocTitle;
//if(m_nWindow > 0)
{
strNewCaption += ":";
strNewCaption = strWindowText;
}
//if(strNewCaption != strCurCaption)
SetWindowText(strNewCaption);
}
}
GetMDIFrame()->OnUpdateFrameTitle(bAddToTitle);
}
void CChildFrame::OnSetFocus(CWnd* pOldWnd)
{//基本资料数据结构类实现
CView *pView = GetActiveView();
if(pView == NULL)
{
CMDIChildWnd::OnSetFocus(pOldWnd);
return;
}
if(GetActiveView()->IsKindOf(RUNTIME_CLASS(CTaiShanReportView)))
{
((CTaiShanReportView *)GetActiveView())->ActiveGrid();
return;
}
CMDIChildWnd::OnSetFocus(pOldWnd);
}
| [
"[email protected]"
]
| [
[
[
1,
378
]
]
]
|
44e66ba1c2fdd52f8859b29edb0ca79c85ecef1c | 011359e589f99ae5fe8271962d447165e9ff7768 | /src/burn/toaplan/d_mahoudai.cpp | ef97dd8cca3ab72704412e711c488991b9591659 | []
| no_license | PS3emulators/fba-next-slim | 4c753375fd68863c53830bb367c61737393f9777 | d082dea48c378bddd5e2a686fe8c19beb06db8e1 | refs/heads/master | 2021-01-17T23:05:29.479865 | 2011-12-01T18:16:02 | 2011-12-01T18:16:02 | 2,899,840 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,715 | cpp | #include "toaplan.h"
// Mahou Daisakusen
static unsigned char DrvButton[8] = {0, 0, 0, 0, 0, 0, 0, 0};
static unsigned char DrvJoy1[8] = {0, 0, 0, 0, 0, 0, 0, 0};
static unsigned char DrvJoy2[8] = {0, 0, 0, 0, 0, 0, 0, 0};
static unsigned char DrvInput[6] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
static unsigned char DrvReset = 0;
static unsigned char bDrawScreen;
static bool bVBlank;
// Rom information
static struct BurnRomInfo mahoudaiRomDesc[] = {
{ "ra_ma_01_01.u65", 0x080000, 0x970CCC5C, BRF_ESS | BRF_PRG }, // 0 CPU #0 code
{ "ra-ma01-rom2.u2", 0x100000, 0x54E2BD95, BRF_GRA }, // 1 GP9001 Tile data
{ "ra-ma01-rom3.u1", 0x100000, 0x21CD378F, BRF_GRA }, // 2
{ "ra_ma_01_05.u81", 0x008000, 0xC00D1E80, BRF_GRA }, // 3 Extra text layer tile data
{ "ra-ma-01_02.u66", 0x010000, 0xEABFA46D, BRF_ESS | BRF_PRG }, // 4 Z80 program
{ "ra-ma01-rom1.u57", 0x040000, 0x6EDB2AB8, BRF_SND }, // 5 MSM6295 ADPCM data
};
STD_ROM_PICK(mahoudai)
STD_ROM_FN(mahoudai)
static struct BurnRomInfo sstrikerRomDesc[] = {
{ "ra-ma-01_01.u65", 0x080000, 0x92259F84, BRF_ESS | BRF_PRG }, // 0 CPU #0 code
{ "ra-ma01-rom2.u2", 0x100000, 0x54E2BD95, BRF_GRA }, // 1 GP9001 Tile data
{ "ra-ma01-rom3.u1", 0x100000, 0x21CD378F, BRF_GRA }, // 2
{ "ra-ma-01_05.u81", 0x008000, 0x88B58841, BRF_GRA }, // 3 Extra text layer tile data
{ "ra-ma-01_02.u66", 0x010000, 0xEABFA46D, BRF_ESS | BRF_PRG }, // 4 Z80 program
{ "ra-ma01-rom1.u57", 0x040000, 0x6EDB2AB8, BRF_SND }, // 5 MSM6295 ADPCM data
};
STD_ROM_PICK(sstriker)
STD_ROM_FN(sstriker)
static struct BurnRomInfo sstrikeraRomDesc[] = {
{ "ra-ma_01_01.u65", 0x080000, 0x708FD51D, BRF_ESS | BRF_PRG }, // 0 CPU #0 code
{ "ra-ma01-rom2.u2", 0x100000, 0x54E2BD95, BRF_GRA }, // 1 GP9001 Tile data
{ "ra-ma01-rom3.u1", 0x100000, 0x21CD378F, BRF_GRA }, // 2
{ "ra-ma-01_05.u81", 0x008000, 0x88B58841, BRF_GRA }, // 3 Extra text layer tile data
{ "ra-ma-01_02.u66", 0x010000, 0xEABFA46D, BRF_ESS | BRF_PRG }, // 4 Z80 program
{ "ra-ma01-rom1.u57", 0x040000, 0x6EDB2AB8, BRF_SND }, // 5 MSM6295 ADPCM data
};
STD_ROM_PICK(sstrikera)
STD_ROM_FN(sstrikera)
static struct BurnInputInfo mahoudaiInputList[] = {
{"P1 Coin", BIT_DIGITAL, DrvButton + 3, "p1 coin"},
{"P1 Start", BIT_DIGITAL, DrvButton + 5, "p1 start"},
{"P1 Up", BIT_DIGITAL, DrvJoy1 + 0, "p1 up"},
{"P1 Down", BIT_DIGITAL, DrvJoy1 + 1, "p1 down"},
{"P1 Left", BIT_DIGITAL, DrvJoy1 + 2, "p1 left"},
{"P1 Right", BIT_DIGITAL, DrvJoy1 + 3, "p1 right"},
{"P1 Shot", BIT_DIGITAL, DrvJoy1 + 4, "p1 fire 1"},
{"P1 Bomb", BIT_DIGITAL, DrvJoy1 + 5, "p1 fire 2"},
{"P1 Unused", BIT_DIGITAL, DrvJoy1 + 6, "p1 fire 3"},
{"P2 Coin", BIT_DIGITAL, DrvButton + 4, "p2 coin"},
{"P2 Start", BIT_DIGITAL, DrvButton + 6, "p2 start"},
{"P2 Up", BIT_DIGITAL, DrvJoy2 + 0, "p2 up"},
{"P2 Down", BIT_DIGITAL, DrvJoy2 + 1, "p2 down"},
{"P2 Left", BIT_DIGITAL, DrvJoy2 + 2, "p2 left"},
{"P2 Right", BIT_DIGITAL, DrvJoy2 + 3, "p2 right"},
{"P2 Shot", BIT_DIGITAL, DrvJoy2 + 4, "p2 fire 1"},
{"P2 Bomb", BIT_DIGITAL, DrvJoy2 + 5, "p2 fire 2"},
{"P2 Unused", BIT_DIGITAL, DrvJoy2 + 6, "p2 fire 3"},
{"Reset", BIT_DIGITAL, &DrvReset, "reset"},
{"Service", BIT_DIGITAL, DrvButton + 0, "service"},
// {"Tilt", BIT_DIGITAL, DrvButton + 1, "tilt"},
{"Dip A", BIT_DIPSWITCH, DrvInput + 3, "dip"},
{"Dip B", BIT_DIPSWITCH, DrvInput + 4, "dip"},
{"Dip C", BIT_DIPSWITCH, DrvInput + 5, "dip"},
};
STDINPUTINFO(mahoudai)
static struct BurnDIPInfo mahoudaiDIPList[] = {
// Defaults
{0x14, 0xFF, 0xFF, 0x00, NULL},
{0x15, 0xFF, 0xFF, 0x00, NULL},
// DIP 1
{0, 0xFE, 0, 2, NULL},
{0x14, 0x01, 0x01, 0x00, "Coin play"},
{0x14, 0x01, 0x01, 0x01, "Free play"},
{0, 0xFE, 0, 2, "Screen"},
{0x14, 0x01, 0x02, 0x00, "Normal"},
{0x14, 0x01, 0x02, 0x02, "Invert"},
{0, 0xFE, 0, 2, NULL},
{0x14, 0x01, 0x04, 0x00, "Normal game"},
{0x14, 0x01, 0x04, 0x04, "Screen test mode"},
{0, 0xFE, 0, 2, "Advertise sound"},
{0x14, 0x01, 0x08, 0x08, "Off"},
{0x14, 0x01, 0x08, 0x00, "On"},
// Normal coin settings
{0, 0xFE, 0, 4, "Coin A"},
{0x14, 0x82, 0x30, 0x00, "1 coin 1 play"},
{0x16, 0x00, 0x0F, 0x04, NULL},
{0x14, 0x82, 0x30, 0x10, "1 coin 2 plays"},
{0x16, 0x00, 0x0F, 0x04, NULL},
{0x14, 0x82, 0x30, 0x20, "2 coins 1 play"},
{0x16, 0x00, 0x0F, 0x04, NULL},
{0x14, 0x82, 0x30, 0x30, "2 coins 3 plays"},
{0x16, 0x00, 0x0F, 0x04, NULL},
{0, 0xFE, 0, 4, "Coin B"},
{0x14, 0x82, 0xC0, 0x00, "1 coin 1 play"},
{0x16, 0x00, 0x0F, 0x04, NULL},
{0x14, 0x82, 0xC0, 0x40, "1 coin 2 plays"},
{0x16, 0x00, 0x0F, 0x04, NULL},
{0x14, 0x82, 0xC0, 0x80, "2 coins 1 play"},
{0x16, 0x00, 0x0F, 0x04, NULL},
{0x14, 0x82, 0xC0, 0xC0, "2 coins 3 plays"},
{0x16, 0x00, 0x0F, 0x04, NULL},
// European coin settings
{0, 0xFE, 0, 4, "Coin A"},
{0x14, 0x02, 0x30, 0x00, "1 coin 1 play"},
{0x16, 0x00, 0x0F, 0x04, NULL},
{0x14, 0x02, 0x30, 0x10, "2 coins 1 play"},
{0x16, 0x00, 0x0F, 0x04, NULL},
{0x14, 0x02, 0x30, 0x20, "3 coins 1 play"},
{0x16, 0x00, 0x0F, 0x04, NULL},
{0x14, 0x02, 0x30, 0x30, "4 coins 1 play"},
{0x16, 0x00, 0x0F, 0x04, NULL},
{0, 0xFE, 0, 4, "Coin B"},
{0x14, 0x02, 0xC0, 0x00, "1 coin 2 plays"},
{0x16, 0x00, 0x0F, 0x04, NULL},
{0x14, 0x02, 0xC0, 0x40, "1 coin 3 plays"},
{0x16, 0x00, 0x0F, 0x04, NULL},
{0x14, 0x02, 0xC0, 0x80, "1 coin 4 play"},
{0x16, 0x00, 0x0F, 0x04, NULL},
{0x14, 0x02, 0xC0, 0xC0, "1 coin 6 plays"},
{0x16, 0x00, 0x0F, 0x04, NULL},
// DIP 2
{0, 0xFE, 0, 4, "Game difficulty"},
{0x15, 0x01, 0x03, 0x00, "B (normal)"},
{0x15, 0x01, 0x03, 0x01, "A (easy)"},
{0x15, 0x01, 0x03, 0x02, "C (hard)"},
{0x15, 0x01, 0x03, 0x03, "D (more hard)"},
{0, 0xFE, 0, 4, "Extend bonus"},
{0x15, 0x01, 0x0C, 0x00, "300000 pts every"},
{0x15, 0x01, 0x0C, 0x04, "200000 & 500000 pts"},
{0x15, 0x01, 0x0C, 0x08, "200000 pts only"},
{0x15, 0x01, 0x0C, 0x0C, "No extend"},
{0, 0xFE, 0, 4, "Number of heroes"},
{0x15, 0x01, 0x30, 0x00, "3"},
{0x15, 0x01, 0x30, 0x10, "5"},
{0x15, 0x01, 0x30, 0x20, "2"},
{0x15, 0x01, 0x30, 0x30, "1"},
{0, 0xFE, 0, 2, "No death & stop mode"},
{0x15, 0x01, 0x40, 0x00, "Off"},
{0x15, 0x01, 0x40, 0x40, "On"},
{0, 0xFE, 0, 2, NULL},
{0x15, 0x01, 0x80, 0x00, "Continue play"},
{0x15, 0x01, 0x80, 0x80, "Continue impossible"},
};
static struct BurnDIPInfo mahoudaiRegionDIPList[] = {
// Defaults
{0x16, 0xFF, 0x0E, 0x00, NULL},
// Region
{0, 0xFE, 0, 1, "Region"},
{0x16, 0x01, 0x0E, 0x00, "Japan"},
{0x16, 0x01, 0x0E, 0x02, "U.S.A."},
{0x16, 0x01, 0x0E, 0x04, "Europe"},
{0x16, 0x01, 0x0E, 0x06, "South East Asia"},
{0x16, 0x01, 0x0E, 0x08, "China"},
{0x16, 0x01, 0x0E, 0x0A, "Korea"},
{0x16, 0x01, 0x0E, 0x0C, "Hong Kong"},
{0x16, 0x01, 0x0E, 0x0E, "Taiwan"},
};
static struct BurnDIPInfo sstrikerRegionDIPList[] = {
// Defaults
{0x16, 0xFF, 0x0E, 0x04, NULL},
// Region
{0, 0xFE, 0, 7, "Region"},
{0x16, 0x01, 0x0E, 0x02, "U.S.A."},
{0x16, 0x01, 0x0E, 0x04, "Europe"},
{0x16, 0x01, 0x0E, 0x06, "South East Asia"},
{0x16, 0x01, 0x0E, 0x08, "China"},
{0x16, 0x01, 0x0E, 0x0A, "Korea"},
{0x16, 0x01, 0x0E, 0x0C, "Hong Kong"},
{0x16, 0x01, 0x0E, 0x0E, "Taiwan"},
{0x16, 0x01, 0x0E, 0x00, "Japan"},
};
STDDIPINFOEXT(mahoudai, mahoudai, mahoudaiRegion);
STDDIPINFOEXT(sstriker, mahoudai, sstrikerRegion);
static unsigned char *Mem = NULL, *MemEnd = NULL;
static unsigned char *RamStart, *RamEnd;
static unsigned char *Rom01;
static unsigned char *Ram01, *Ram02, *RamPal;
static int nColCount = 0x0800;
static int nRomADPCMSize = 0x040000;
// This routine is called first to determine how much memory is needed (MemEnd-(unsigned char *)0),
// and then afterwards to set up all the pointers
static int MemIndex()
{
unsigned char *Next; Next = Mem;
Rom01 = Next; Next += 0x080000; //
RomZ80 = Next; Next += 0x010000; // Z80 ROM
GP9001ROM[0]= Next; Next += nGP9001ROMSize[0]; // GP9001 tile data
ExtraTROM = Next; Next += 0x008000; // Extra Text layer tile data
MSM6295ROM = Next; Next += nRomADPCMSize; // ADPCM data
RamStart = Next;
Ram01 = Next; Next += 0x010000; // CPU #0 work RAM
Ram02 = Next; Next += 0x000800; //
ExtraTRAM = Next; Next += 0x002000; // Extra tile layer
ExtraTScroll= Next; Next += 0x001000; //
ExtraTSelect= Next; Next += 0x001000; //
RamPal = Next; Next += 0x001000; // palette
RamZ80 = Next; Next += 0x004000; // Z80 RAM
GP9001RAM[0]= Next; Next += 0x004000;
GP9001Reg[0]= (unsigned short*)Next; Next += 0x0100 * sizeof(short);
RamEnd = Next;
ToaPalette = (unsigned int *)Next; Next += nColCount * sizeof(unsigned int);
MemEnd = Next;
return 0;
}
// Scan ram
static int DrvScan(int nAction, int* pnMin)
{
struct BurnArea ba;
if (pnMin) { // Return minimum compatible version
*pnMin = 0x029497;
}
if (nAction & ACB_VOLATILE) { // Scan volatile ram
memset(&ba, 0, sizeof(ba));
ba.Data = RamStart;
ba.nLen = RamEnd-RamStart;
ba.szName = "All Ram";
BurnAcb(&ba);
SekScan(nAction); // scan 68000 states
ZetScan(nAction); // Scan Z80
MSM6295Scan(0, nAction);
BurnYM2151Scan(nAction);
ToaScanGP9001(nAction, pnMin);
SCAN_VAR(DrvInput);
}
return 0;
}
static int LoadRoms()
{
// Load 68000 ROM
BurnLoadRom(Rom01, 0, 1);
// Load GP9001 tile data
ToaLoadGP9001Tiles(GP9001ROM[0], 1, 2, nGP9001ROMSize[0]);
// Load Extra text layer tile data
BurnLoadRom(ExtraTROM, 3, 1);
// Load the Z80 ROM
BurnLoadRom(RomZ80, 4, 1);
// Load MSM6295 ADPCM data
BurnLoadRom(MSM6295ROM, 5, 1);
return 0;
}
unsigned char __fastcall mahoudaiZ80Read(unsigned short nAddress)
{
// bprintf(PRINT_NORMAL, "z80 read %4X\n", nAddress);
if (nAddress == 0xE001) {
return BurnYM2151ReadStatus();
}
if (nAddress == 0xE004) {
return MSM6295ReadStatus(0);
}
return 0;
}
void __fastcall mahoudaiZ80Write(unsigned short nAddress, unsigned char nValue)
{
// bprintf(PRINT_NORMAL, "Z80 attempted to write address %04X with value %02X.\n", nAddress, nValue);
switch (nAddress) {
case 0xE000:
BurnYM2151SelectRegister(nValue);
break;
case 0xE001:
BurnYM2151WriteRegister(nValue);
break;
case 0xE004:
MSM6295Command(0, nValue);
// bprintf(PRINT_NORMAL, "OKI M6295 command %02X sent\n", nValue);
break;
}
}
static int DrvZ80Init()
{
// Init the Z80
ZetInit(1);
ZetSetReadHandler(mahoudaiZ80Read);
ZetSetWriteHandler(mahoudaiZ80Write);
// ROM
ZetMapArea (0x0000, 0xBFFF, 0, RomZ80); // Direct Read from ROM
ZetMapArea (0x0000, 0xBFFF, 2, RomZ80); // Direct Fetch from ROM
// RAM
ZetMapArea (0xC000, 0xDFFF, 0, RamZ80); // Direct Read from RAM
ZetMapArea (0xC000, 0xDFFF, 1, RamZ80); // Direct Write to RAM
ZetMapArea (0xC000, 0xDFFF, 2, RamZ80); //
// Callbacks
ZetMemCallback(0xE000, 0xE0FF, 0); // Read
ZetMemCallback(0xE000, 0xE0FF, 1); // Write
ZetMemEnd();
return 0;
}
unsigned char __fastcall mahoudaiReadByte(unsigned int sekAddress)
{
switch (sekAddress) {
case 0x21C021: // Player 1 inputs
return DrvInput[0];
case 0x21C025: // Player 2 inputs
return DrvInput[1];
case 0x21C029: // Other inputs
return DrvInput[2];
case 0x21C02D: // Dipswitch A
return DrvInput[3];
case 0x21C031: // Dipswitch B
return DrvInput[4];
case 0x21C035: // Dipswitch C - Territory
return DrvInput[5];
case 0x30000D:
return ToaVBlankRegister();
default: {
if ((sekAddress & 0x00FFC000) == 0x00218000) {
return RamZ80[(sekAddress & 0x3FFF) >> 1];
}
// bprintf(PRINT_NORMAL, "Attempt to read byte value of location %x\n", sekAddress);
}
}
return 0;
}
unsigned short __fastcall mahoudaiReadWord(unsigned int sekAddress)
{
switch (sekAddress) {
case 0x21C020: // Player 1 inputs
return DrvInput[0];
case 0x21C024: // Player 2 inputs
return DrvInput[1];
case 0x21C028: // Other inputs
return DrvInput[2];
case 0x21C02C: // Dipswitch A
return DrvInput[3];
case 0x21C030: // Dipswitch B
return DrvInput[4];
case 0x21C034: // Dipswitch C - Territory
return DrvInput[5];
case 0x21C03C:
return ToaScanlineRegister();
case 0x300004:
return ToaGP9001ReadRAM_Hi(0);
case 0x300006:
return ToaGP9001ReadRAM_Lo(0);
case 0x30000C:
return ToaVBlankRegister();
default: {
if ((sekAddress & 0x00FFC000) == 0x00218000) {
return RamZ80[(sekAddress & 0x3FFF) >> 1];
}
// bprintf(PRINT_NORMAL, "Attempt to read word value of location %x\n", sekAddress);
}
}
return 0;
}
void __fastcall mahoudaiWriteByte(unsigned int sekAddress, unsigned char byteValue)
{
// switch (sekAddress) {
// default: {
// bprintf(PRINT_NORMAL, "Attempt to write byte value %x to location %x\n", byteValue, sekAddress);
if ((sekAddress & 0x00FFC000) == 0x00218000) {
RamZ80[(sekAddress & 0x3FFF) >> 1] = byteValue;
}
// }
// }
}
void __fastcall mahoudaiWriteWord(unsigned int sekAddress, unsigned short wordValue)
{
switch (sekAddress) {
case 0x300000: // Set GP9001 VRAM address-pointer
ToaGP9001SetRAMPointer(wordValue);
break;
case 0x300004:
ToaGP9001WriteRAM(wordValue, 0);
break;
case 0x300006:
ToaGP9001WriteRAM(wordValue, 0);
break;
case 0x300008:
ToaGP9001SelectRegister(wordValue);
break;
case 0x30000C:
ToaGP9001WriteRegister(wordValue);
break;
default: {
// bprintf(PRINT_NORMAL, "Attempt to write word value %x to location %x\n", wordValue, sekAddress);
if ((sekAddress & 0x00FFC000) == 0x00218000) {
RamZ80[(sekAddress & 0x3FFF) >> 1] = wordValue;
}
}
}
}
static int DrvDoReset()
{
SekOpen(0);
SekReset();
SekClose();
ZetReset();
MSM6295Reset(0);
BurnYM2151Reset();
return 0;
}
static int DrvInit()
{
int nLen;
#ifdef DRIVER_ROTATION
bToaRotateScreen = true;
#endif
nGP9001ROMSize[0] = 0x200000;
// Find out how much memory is needed
Mem = NULL;
MemIndex();
nLen = MemEnd - (unsigned char *)0;
if ((Mem = (unsigned char *)malloc(nLen)) == NULL) {
return 1;
}
memset(Mem, 0, nLen); // blank all memory
MemIndex(); // Index the allocated memory
// Load the roms into memory
if (LoadRoms()) {
return 1;
}
{
SekInit(0, 0x68000); // Allocate 68000
SekOpen(0);
// Map 68000 memory:
SekMapMemory(Rom01, 0x000000, 0x07FFFF, SM_ROM); // CPU 0 ROM
SekMapMemory(Ram01, 0x100000, 0x10FFFF, SM_RAM);
SekMapMemory(RamPal, 0x400000, 0x400FFF, SM_RAM); // Palette RAM
SekMapMemory(Ram02, 0x401000, 0x4017FF, SM_RAM); // Unused
SekMapMemory(ExtraTRAM, 0x500000, 0x501FFF, SM_RAM);
SekMapMemory(ExtraTSelect, 0x502000, 0x502FFF, SM_RAM); // 0x502000 - Scroll; 0x502200 - RAM
SekMapMemory(ExtraTScroll, 0x503000, 0x503FFF, SM_RAM); // 0x203000 - Offset; 0x503200 - RAM
SekSetReadWordHandler(0, mahoudaiReadWord);
SekSetReadByteHandler(0, mahoudaiReadByte);
SekSetWriteWordHandler(0, mahoudaiWriteWord);
SekSetWriteByteHandler(0, mahoudaiWriteByte);
SekClose();
}
nSpritePriority = 1;
ToaInitGP9001();
ToaExtraTextInit();
DrvZ80Init(); // Initialize Z80
nToaPalLen = nColCount;
ToaPalSrc = RamPal;
ToaPalInit();
BurnYM2151Init(27000000 / 8, 50.0);
MSM6295Init(0, 32000000 / 32 / 132, 50.0, 1);
bDrawScreen = true;
DrvDoReset(); // Reset machine
return 0;
}
static int DrvExit()
{
MSM6295Exit(0);
BurnYM2151Exit();
ToaPalExit();
ToaExitGP9001();
ToaExtraTextExit();
ToaZExit(); // Z80 exit
SekExit(); // Deallocate 68000s
// Deallocate all used memory
free(Mem);
Mem = NULL;
return 0;
}
static int DrvDraw()
{
ToaClearScreen();
if (bDrawScreen) {
ToaGetBitmap();
ToaRenderGP9001(); // Render GP9001 graphics
ToaExtraTextLayer(); // Render extra text layer
}
ToaPalUpdate(); // Update the palette
return 0;
}
static inline int CheckSleep(int)
{
return 0;
}
static int DrvFrame()
{
int nInterleave = 4;
if (DrvReset) { // Reset machine
DrvDoReset();
}
// Compile digital inputs
DrvInput[0] = 0x00; // Buttons
DrvInput[1] = 0x00; // Player 1
DrvInput[2] = 0x00; // Player 2
for (int i = 0; i < 8; i++) {
DrvInput[0] |= (DrvJoy1[i] & 1) << i;
DrvInput[1] |= (DrvJoy2[i] & 1) << i;
DrvInput[2] |= (DrvButton[i] & 1) << i;
}
DrvClearOpposites(&DrvInput[0]);
DrvClearOpposites(&DrvInput[1]);
SekNewFrame();
nCyclesTotal[0] = (int)((long long)16000000 * nBurnCPUSpeedAdjust / (0x0100 * 60));
nCyclesTotal[1] = TOA_Z80_SPEED / 60;
nCyclesDone[0] = nCyclesDone[1] = 0;
SekSetCyclesScanline(nCyclesTotal[0] / 262);
nToaCyclesDisplayStart = nCyclesTotal[0] - ((nCyclesTotal[0] * (TOA_VBLANK_LINES + 240)) / 262);
nToaCyclesVBlankStart = nCyclesTotal[0] - ((nCyclesTotal[0] * TOA_VBLANK_LINES) / 262);
bVBlank = false;
int nSoundBufferPos = 0;
SekOpen(0);
for (int i = 0; i < nInterleave; i++) {
int nCurrentCPU;
int nNext;
// Run 68000
nCurrentCPU = 0;
nNext = (i + 1) * nCyclesTotal[nCurrentCPU] / nInterleave;
// Trigger VBlank interrupt
if (nNext > nToaCyclesVBlankStart) {
if (nCyclesDone[nCurrentCPU] < nToaCyclesVBlankStart) {
nCyclesSegment = nToaCyclesVBlankStart - nCyclesDone[nCurrentCPU];
nCyclesDone[nCurrentCPU] += SekRun(nCyclesSegment);
}
ToaBufferGP9001Sprites();
bVBlank = true;
SekSetIRQLine(4, SEK_IRQSTATUS_AUTO);
}
nCyclesSegment = nNext - nCyclesDone[nCurrentCPU];
if (bVBlank || (!CheckSleep(nCurrentCPU))) { // See if this CPU is busywaiting
nCyclesDone[nCurrentCPU] += SekRun(nCyclesSegment);
} else {
nCyclesDone[nCurrentCPU] += SekIdle(nCyclesSegment);
}
// Run Z80
nCurrentCPU = 1;
nNext = (i + 1) * nCyclesTotal[nCurrentCPU] / nInterleave;
nCyclesSegment = nNext - nCyclesDone[nCurrentCPU];
nCyclesDone[nCurrentCPU] += ZetRun(nCyclesSegment);
{
// Render sound segment
if (pBurnSoundOut) {
int nSegmentLength = nBurnSoundLen / nInterleave;
short* pSoundBuf = pBurnSoundOut + (nSoundBufferPos << 1);
BurnYM2151Render(pSoundBuf, nSegmentLength);
MSM6295Render(0, pSoundBuf, nSegmentLength);
nSoundBufferPos += nSegmentLength;
}
}
}
SekClose();
{
// Make sure the buffer is entirely filled.
if (pBurnSoundOut) {
int nSegmentLength = nBurnSoundLen - nSoundBufferPos;
short* pSoundBuf = pBurnSoundOut + (nSoundBufferPos << 1);
if (nSegmentLength) {
BurnYM2151Render(pSoundBuf, nSegmentLength);
MSM6295Render(0, pSoundBuf, nSegmentLength);
}
}
}
if (pBurnDraw) {
DrvDraw(); // Draw screen if needed
}
return 0;
}
struct BurnDriver BurnDrvMahouDai = {
"mahoudai", NULL, NULL, "1993",
"Mahou Daisakusen (Japan)\0", NULL, "Raizing", "Toaplan GP9001 based",
L"\u9B54\u6CD5\u5927\u4F5C\u6226 (Japan)\0Mahou Daisakusen (Japan)\0", NULL, NULL, NULL,
BDF_GAME_WORKING | TOA_ROTATE_GRAPHICS_CCW, 2, HARDWARE_TOAPLAN_RAIZING,
NULL, mahoudaiRomInfo, mahoudaiRomName, mahoudaiInputInfo, mahoudaiDIPInfo,
DrvInit, DrvExit, DrvFrame, DrvDraw, DrvScan, &ToaRecalcPalette,
240, 320, 3, 4
};
struct BurnDriver BurnDrvSStriker = {
"sstriker", "mahoudai", NULL, "1993",
"Sorcer Striker (World)\0", NULL, "Raizing", "Toaplan GP9001 based",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING | BDF_CLONE | TOA_ROTATE_GRAPHICS_CCW, 2, HARDWARE_TOAPLAN_RAIZING,
NULL, sstrikerRomInfo, sstrikerRomName, mahoudaiInputInfo, sstrikerDIPInfo,
DrvInit, DrvExit, DrvFrame, DrvDraw, DrvScan, &ToaRecalcPalette,
240, 320, 3, 4
};
struct BurnDriver BurnDrvSStrikerA = {
"sstrikera", "mahoudai", NULL, "1993",
"Sorcer Striker (World, alt)\0", "Alternate version", "Raizing", "Toaplan GP9001 based",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING | BDF_CLONE | TOA_ROTATE_GRAPHICS_CCW, 2, HARDWARE_TOAPLAN_RAIZING,
NULL, sstrikeraRomInfo, sstrikeraRomName, mahoudaiInputInfo, sstrikerDIPInfo,
DrvInit, DrvExit, DrvFrame, DrvDraw, DrvScan, &ToaRecalcPalette,
240, 320, 3, 4
};
| [
"[email protected]"
]
| [
[
[
1,
719
]
]
]
|
d60d883c89b321b611ce934142c1116f72d2f1ad | 5fb9b06a4bf002fc851502717a020362b7d9d042 | /developertools/MapRenderer/include/loaders/ArtLoader.h | 760453122b31b81ae991d0ab61981db209d69b2d | []
| no_license | bravesoftdz/iris-svn | 8f30b28773cf55ecf8951b982370854536d78870 | c03438fcf59d9c788f6cb66b6cb9cf7235fbcbd4 | refs/heads/master | 2021-12-05T18:32:54.525624 | 2006-08-21T13:10:54 | 2006-08-21T13:10:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,481 | h | //
// File: ArtLoader.h
// Created by: Alexander Oster - [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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*****/
#ifndef _ARTLOADER_H_
#define _ARTLOADER_H_
#ifdef WIN32
#include <windows.h>
#endif
#include <iostream>
#include <fstream>
#include <cstring>
#include "include.h"
#include "../renderer/Texture.h"
class cArtLoader
{
private:
std::ifstream * artfile;
std::ifstream * artindex;
Texture * LoadGroundArt(int index);
Texture * LoadStaticArt(int index);
public:
cArtLoader (std::string filename, std::string indexname);
~cArtLoader ();
Texture * LoadArt(int index);
protected:
unsigned int art_count;
};
extern cArtLoader * pArtLoader;
#endif //_GROUNDTEXTURES_H_
| [
"sience@a725d9c3-d2eb-0310-b856-fa980ef11a19"
]
| [
[
[
1,
58
]
]
]
|
7574b2348462138adaca4b85b763625a9e2de493 | 25fd79ea3a1f2c552388420c5a02433d9cdf855d | /Pool/Billiards/BallConfig.h | 4a406e25f39fc1f49268b5e042ef0d1b49175c9a | []
| no_license | k-l-lambda/klspool | 084cbe99a1dc3b9703233fccea3f2f6570df9d63 | b57703169828f9d406e7d0a6cd326063832b12c6 | refs/heads/master | 2021-01-23T07:03:59.086914 | 2009-09-06T09:14:51 | 2009-09-06T09:14:51 | 32,123,777 | 0 | 0 | null | null | null | null | IBM852 | C++ | false | false | 2,396 | h | /*
** This source file is part of Pool.
**
** Copyright (c) 2009 K.L.<[email protected]>, Lazy<[email protected]>
** This program is free software without any warranty.
*/
#ifndef __BALLCONFIG_H__
#define __BALLCONFIG_H__
#include "Billiards.h"
#pragma warning(push)
#pragma warning(disable: 4267)
#include <boost\serialization\vector.hpp>
#include <boost\serialization\set.hpp>
#include <boost\serialization\map.hpp>
#pragma warning(pop)
namespace Billiards
{
struct BallConfig
{
struct Less
: public std::binary_function<const BallConfig&, const BallConfig&, bool>
{
bool operator () (const BallConfig& lhs, const BallConfig& rhs) const
{
return std::less<std::string>()(lhs.Name, rhs.Name);
};
};
std::string Name;
Real Redius;
Real Mass;
std::string Material;
template<typename Archive>
void serialize(Archive& ar, const unsigned int /*version*/)
{
ar & BOOST_SERIALIZATION_NVP(Name);
ar & BOOST_SERIALIZATION_NVP(Redius);
ar & BOOST_SERIALIZATION_NVP(Mass);
ar & BOOST_SERIALIZATION_NVP(Material);
};
};
struct BILLIARDS_API BallConfigSet
: public std::set<BallConfig, BallConfig::Less>
#pragma warning(suppress: 4251) // 'identifier' : class 'type' needs to have dll-interface to be used by clients of class 'type2'
#pragma warning(suppress: 4275) // non ĘC DLL-interface classkey 'identifier' used as base for DLL-interface classkey 'identifier'
{
typedef std::set<BallConfig, BallConfig::Less> Set;
std::string NameSpace;
static BallConfigSet load(std::istream& is);
static BallConfigSet loadFile(const std::string& filename);
static void save(std::ostream& os, const BallConfigSet& set);
static void saveFile(const std::string& filename, const BallConfigSet& set);
template<typename Archive>
void serialize(Archive& ar, const unsigned int /*version*/)
{
ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(Set);
ar & BOOST_SERIALIZATION_NVP(NameSpace);
};
};
}
BOOST_CLASS_IMPLEMENTATION(Billiards::BallConfig, boost::serialization::object_serializable)
BOOST_CLASS_IMPLEMENTATION(Billiards::BallConfigSet, boost::serialization::object_serializable)
BOOST_CLASS_IMPLEMENTATION(Billiards::BallConfigSet::Set, boost::serialization::object_serializable)
#endif // !defined(__BALLCONFIG_H__)
| [
"xxxK.L.xxx@64c72148-2b1e-11de-874f-bb9810f3bc79"
]
| [
[
[
1,
84
]
]
]
|
612c25307b98fb6f14151673c11e30cb6604c884 | f4d39655394aebbb524146cc7a61f93505289ce7 | /ECC/crypto.h | c3d3395f1081804b9fffeaaba3159c45f3919f9d | []
| no_license | pjacosta/ECDLP-Pollard | b9ded826e7f9d07791a6b8a5e4b8e7bd6259266a | d0a4ebf0dc241cf0fc108a639c4c4e52b89ffba9 | refs/heads/master | 2023-03-19T14:59:15.270344 | 2010-04-20T23:39:07 | 2010-04-20T23:39:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,568 | h | #ifndef _CRYPTO_H
#define _CRYPTO_H
#include "eccdefines.h"
#include "ecurve.h"
#include "epoint.h"
#include "bint.h"
/* Need some classes */
class lnum;
class gf2n;
class ecurve;
class epoint;
class bint;
namespace cryptoRoutines
{
void op_err(int err);
}
class crypto
{
public:
/* Constructors */
crypto(const ecurve &curve);
/* Accessors */
const ecurve &get_curve(void) const;
const epoint &get_G(void) const;
const epoint &get_aG(void) const;
const epoint &get_bG(void) const;
const epoint &get_abG(void) const;
const bint &get_keyA(void) const;
const bint &get_keyB(void) const;
int get_message_length(void) const;
/* Setter methods */
void set_G(const epoint &G);
void set_keyA(const bint &keyA);
void set_keyB(const bint &keyB);
void set_keys(const bint &keyA, const bint &keyB);
void override_aG(const epoint &aG, bool calculate_abG);
void override_bG(const epoint &bG, bool calculate_abG);
void override_abG(const epoint &abG);
/* Helper methods */
bint get_group_order(void) const;
/* Crypto methods */
epoint *encrypt(const unsigned char *data, int data_length, int &point_count) const;
unsigned char *decrypt(const epoint *points, int point_count, int &data_length) const;
unsigned char *decrypt(const unsigned char *data, int data_length, int &result_length) const;
epoint *convert(const unsigned char *data, int data_length, int &point_count) const;
private:
const ecurve *curve;
epoint G, aG, bG, abG;
bint keyA, keyB;
int message_length;
};
#endif
| [
"grizenko.a@211633f8-0eb2-11df-8d37-15e3504968c6"
]
| [
[
[
1,
62
]
]
]
|
f38c56324628eeaa43aa07cc2a6a52605e161fe7 | 9e2c39ce4b2a226a6db1f5a5d361dea4b2f02345 | /tools/LePlatz/DataModel/PlatzDataStream.cpp | fd317646d359c92bf82e28a5235205cbdc2d047b | []
| no_license | gonzalodelgado/uzebox-paul | 38623933e0fb34d7b8638b95b29c4c1d0b922064 | c0fa12be79a3ff6bbe70799f2e8620435ce80a01 | refs/heads/master | 2016-09-05T22:24:29.336414 | 2010-07-19T07:37:17 | 2010-07-19T07:37:17 | 33,088,815 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,498 | cpp |
/*
* LePlatz - A level editor for the Platz toolset (Uzebox - supports VIDEO_MODE 3)
* Copyright (C) 2009 Paul McPhee
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QVariant>
#include <QString>
#include <QList>
#include "PlatzDataStream.h"
#undef CHECK_STREAM_PRECOND
#ifndef QT_NO_DEBUG
#define CHECK_STREAM_PRECOND(retVal, dev) \
if (!dev) { \
qWarning("QDataStream: No device"); \
return retVal; \
}
#else
#define CHECK_STREAM_PRECOND(retVal, devl) \
if (!dev) { \
return retVal; \
}
#endif
PlatzDataStream::PlatzDataStream()
{
}
PlatzDataStream::PlatzDataStream(QByteArray *a, QIODevice::OpenMode mode)
: QDataStream(a, mode)
{
}
PlatzDataStream& PlatzDataStream::operator<<(WorldItem *w)
{
if (w) {
QIODevice *dev = device();
CHECK_STREAM_PRECOND(*this, dev)
dev->write((char*)&w, sizeof(w));
}
return *this;
#if 0
WorldItem *parent = w->parent();
int childCount = w->childCount();
WorldItem::WorldItemType type = w->type();
//QString s(w->data(0).toString());
dev->write((char*)&parent, sizeof(myParent));
dev->write((char*)&childCount, sizeof(childCount));
const QList<WorldItem*>* children = w->children();
foreach(WorldItem *child, *children)
dev->write((char*)&child, sizeof(child));
dev->write((char*)&type, sizeof(type));
//dev->write((char*)&s, sizeof(s));
#endif
}
PlatzDataStream& PlatzDataStream::operator>>(WorldItem **w)
{
QIODevice *dev = device();
CHECK_STREAM_PRECOND(*this, dev)
if (dev->read((char*)w, sizeof(w)) != sizeof(w)) {
setStatus(ReadPastEnd);
*w = 0;
}
return *this;
#if 0
QIODevice *dev = device();
WorldItem *parent = 0;
int childCount;
WorldItem* child = 0;
WorldItem::WorldItemType type;
//QString s;
CHECK_STREAM_PRECOND(*this, dev)
if (dev->read((char*)&parent, sizeof(parent)) == sizeof(parent)) {
if (dev->read((char*)&childCount, sizeof(childCount)) == sizeof(childCount)) {
for (int i = 0; i < childCount; i++) {
if (dev->read((char*)&child, sizeof(child)) != sizeof(child))
break;
//w->appendChild(child);
}
if (dev->read((char*)&type, sizeof(type)) == sizeof(type)) {
//if (dev->read((char*)&s, sizeof(s)) == sizeof(s)) {
w->setParent(parent);
w->setType(type);
//w->setData(QVariant(s));
w->setData(QVariant("Slice X"));
return *this;
//}
}
}
}
setStatus(ReadPastEnd);
return *this;
#endif
}
| [
"[email protected]@08aac7ea-4340-11de-bfec-d9b18e096ff9"
]
| [
[
[
1,
116
]
]
]
|
d3beec5403d308af91ed016cad5919b804c6a034 | f13f46fbe8535a7573d0f399449c230a35cd2014 | /JelloMan/IniWriter.h | 8c4f0a1f4a274fbbad4b55f601908b009d7dfb82 | []
| no_license | fangsunjian/jello-man | 354f1c86edc2af55045d8d2bcb58d9cf9b26c68a | 148170a4834a77a9e1549ad3bb746cb03470df8f | refs/heads/master | 2020-12-24T16:42:11.511756 | 2011-06-14T10:16:51 | 2011-06-14T10:16:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 717 | h | #pragma once
#include "D3DUtil.h"
#include <vector>
namespace IO{
typedef std::map<tstring, std::vector<std::pair<tstring, tstring>>> IniWriteData;
class IniWriter
{
public:
IniWriter();
~IniWriter();
void Open(const std::string& path);
void WriteInt(const std::tstring& root, const std::tstring& node, int i);
void WriteFloat(const std::tstring& root, const std::tstring& node, float f);
void WriteString(const std::tstring& root, const std::tstring& node, const tstring& str);
bool Close();
private:
IniWriteData m_Data;
string m_Path;
IniWriter& operator=(const IniWriter&) {};
IniWriter(const IniWriter&) {};
};
} //end namespace
| [
"bastian.damman@0fb7bab5-1bf9-c5f3-09d9-7611b49293d6"
]
| [
[
[
1,
30
]
]
]
|
df83f267240f3a783af6a66cb4d0b4aebdb7a051 | c0edc7294df991d2e422ce972d96e66a99e79d3a | /src/environ.cc | 6c33f45a921eb1935d8c3e418165a95cf6ca9dca | []
| no_license | mahmudulhaque/CPM_Development | 47c1310b521e32f6bd83a357056ae39e0c9781e9 | 982ef01d3a06013596a50a30d5b782cb01096a72 | refs/heads/master | 2020-07-22T00:14:30.627911 | 2011-04-29T16:23:44 | 2011-04-29T16:23:44 | 1,681,413 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,422 | cc | //-------------------------------------------------------------
// File: environ.cc
// (part of OMNeT++ simulation of CPMnet)
// Author: Weihai Yu
//-------------------------------------------------------------
#include "environ.h"
#include "cpm.h"
const long Environ::ACT_ENV_MSG_SIZE;
Environ* Environ::set (xmlDocPtr newdoc, xmlNodePtr elm)
{
reset ();
doc = newdoc;
set (elm);
xmlSetIntProp (domelm, _FID, cpm->getFid());
return this;
}
Environ* Environ::set (xmlNodePtr elm)
{
if (!doc) return NULL;
if (!elm)
{
elm = xmlNewNode (NULL, BAD_CAST _E);
}
if (domelm)
{
xmlReplaceNode (domelm, elm);
xmlFreeNode (domelm);
domelm = elm;
}
else
{
domelm = elm;
}
currelm = findCurrElm (domelm);
return this;
}
Environ* Environ::importSet (xmlNodePtr elm)
{
if (!elm)
{
ev << "Environ::importSet - empty element!\n";
return this;
}
return set (xmlDocCopyNode (elm, doc, 1));
}
Environ* Environ::reset ()
{
doc = NULL;
domelm = NULL;
currelm = NULL;
return this;
}
Environ* Environ::append (xmlNodePtr elm, const char *stat)
{
xmlSetProp (elm, BAD_CAST _STATUS, BAD_CAST stat);
xmlAddChild (currelm, elm);
currelm = findCurrElm (currelm);
return this;
}
Environ* Environ::importAppend (xmlNodePtr elm, const char *stat, bool deep)
{
int deepflag = deep?1:2;
xmlNodePtr homeelm = xmlDocCopyNode (elm, doc, deepflag);
return append (homeelm, stat);
}
Status Environ::getStatus (xmlNodePtr elm)
{
if (!elm)
elm = currelm;
xmlChar *statxstr = xmlGetProp (elm, BAD_CAST _STATUS);
Status res = status (statxstr);
xmlFree (statxstr);
return res;
}
Environ* Environ::setStatus (xmlNodePtr elm, Status stat)
{
xmlSetProp (elm, BAD_CAST _STATUS, statusXStr(stat));
currelm = findCurrElm (domelm);
// ev << "Environ::setStatus: Current is <"
// << (char*) currelm->name << ">\n";
return this;
}
// actname is provided only for the purpose of extra checking
// to avoid any surprise
Environ* Environ::setStatus (const char *actname, Status stat)
{
if (!xmlStrEqual (currelm->name, BAD_CAST actname))
{
ev << "Environ::setStatus: Current <"
<< (char *) currelm->name
<< "> is not <" << actname << ">\n";
return this;
}
return setStatus (currelm, stat);
}
Environ* Environ::branchDone ()
{
if (!xmlStrEqual (currelm->name, BAD_CAST _FLW))
{
ev << "Environ::branchDone - current element is <"
<< (char *) currelm->name << ">, should be <flow>!\n";
return this;
}
xmlNodePtr branch_elm = xmlNewNode (NULL, BAD_CAST _BRANCH);
xmlSetIntProp (branch_elm, _BID, cpm->getBid());
xmlSetProp (branch_elm, BAD_CAST _STATUS,
cpm->isRollingback()?BAD_CAST _UNDONE : BAD_CAST _DONE);
xmlNodePtr next_ch_elm = xmlFirstElementChild (currelm);
while (next_ch_elm)
{
xmlNodePtr ch_elm = next_ch_elm;
next_ch_elm = xmlNextElementSibling (ch_elm);
xmlUnlinkNode (ch_elm);
xmlAddChild (branch_elm, ch_elm);
}
xmlAddChild (currelm, branch_elm);
return this;
}
Environ* Environ::merge ( int matchkey )
{
if (!xmlStrEqual (currelm->name, BAD_CAST _FLW))
{
ev << "Environ::merge - current element is <"
<< (char *) currelm->name << ">, should be <flow>!\n";
return this;
}
long bid = cpm->getBid();
std::pair<MsgMapIt,MsgMapIt> range = cpm->site->pool->get_range(matchkey);
for (MsgMapIt mit = range.first; mit != range.second; mit++)
{
Cpm branch_cpm (cpm->site);
xmlDocPtr branch_doc = strToDoc (mit->second->getCpm());
branch_cpm.set (branch_doc);
xmlNodePtr branch_elm = xmlFirstElementChild (branch_cpm.e->currelm);
if (!xmlStrEqual (branch_elm->name, BAD_CAST _BRANCH))
{
ev << "Environ::merge - <" << (char *) branch_elm->name
<< ">, should be <branch>!\n";
continue;
}
if (xmlGetIntProp (branch_elm, _BID) != bid)
xmlAddChild (currelm, xmlDocCopyNode (branch_elm, doc, 1));
}
return setStatus (currelm, cpm->isRollingback()?UNDONE:DONE);
}
// find the lastest element that is not done/undone yet
xmlNodePtr Environ::findCurrElm (xmlNodePtr elm)
{
xmlNodePtr child = xmlLastElementChild (elm);
if (!child)
return elm;
xmlChar *statxstr = xmlGetProp (child, BAD_CAST _STATUS);
if (xmlStrEqual (statxstr, BAD_CAST _ACTIVE)
|| xmlStrEqual (statxstr, BAD_CAST _ROLLINGBACK))
{
xmlFree (statxstr);
return findCurrElm (child);
}
xmlFree (statxstr);
return elm;
}
long Environ::msgSize ()
{
return sumChildMsgSize (domelm);
}
long Environ::msgSize (xmlNodePtr elm)
{
if (elm == NULL) return 0;
else
ev<<" Environ::MsgSize Parent node: " << (char *) elm->name;
if (xmlStrEqual (elm->name, BAD_CAST _INS)
|| xmlStrEqual (elm->name, BAD_CAST _OUTS))
return sumChildMsgSize (elm);
if (xmlStrEqual (elm->name, BAD_CAST _VARS))
return 0;
if (xmlStrEqual (elm->name, BAD_CAST _VAR))
return xmlGetIntProp (elm, _SIZE);
return sumChildMsgSize (elm) + ACT_ENV_MSG_SIZE;
}
long Environ::sumChildMsgSize (xmlNodePtr parent)
{
long sz = 0;
for (xmlNodePtr child = xmlFirstElementChild (parent);
child != NULL; child=xmlNextElementSibling(child))
{
ev<<" Environ::sumChildMsgSize child node: " << (char *) child->name<<endl;
sz += msgSize (child);
}
ev<<"Environ::sumChildMsgSize the size is: " << sz <<endl;
return sz;
}
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
189
],
[
192,
210
],
[
216,
216
]
],
[
[
190,
191
],
[
211,
215
],
[
217,
217
]
]
]
|
07ef783c1068b55d6430adc31175b944ed3bc0c5 | f08e489d72121ebad042e5b408371eaa212d3da9 | /TP1_ABInteger/TP1_ABInteger/src/BPlusTree/KeyElement.cpp | c994b72314878636d55be062bee5ed28f1bf15c7 | []
| no_license | estebaneze/datos022011-tp1-vane | 627a1b3be9e1a3e4ab473845ef0ded9677e623e0 | 33f8a8fd6b7b297809a0feac14d10f9815f8388b | refs/heads/master | 2021-01-20T03:35:36.925750 | 2011-12-04T18:19:55 | 2011-12-04T18:19:55 | 41,821,700 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,217 | cpp | #include "KeyElement.h"
KeyElement::KeyElement() {
this->rightNode=-1;
}
KeyElement::KeyElement(KeyInt key,Offset rightNode) {
this->key = key;
this->rightNode = rightNode;
}
KeyElement::~KeyElement() {
}
void KeyElement::setRightNode(Offset rightNode) {
this->rightNode = rightNode;
}
Offset KeyElement::getrightNode(){
return rightNode;
}
void KeyElement::setKey(KeyInt key) {
this->key = key;
}
KeyInt KeyElement::getKey(){
return this->key;
}
ostream& operator<<(ostream& myOstream, KeyElement& elem){
myOstream<<elem.getKey()<<" RightOffSet: "<<elem.getrightNode()<<" ";
return myOstream;
}
/******************************************************
* PERSISTENCIA
*
****************************************************/
std::string KeyElement::serialize() {
std::string buffer = "";
buffer.append((char*)&key,sizeof(KeyInt));
buffer.append((char*)&rightNode,sizeof(Offset));
return buffer;
}
void KeyElement::unserialize(std::string &buffer) {
buffer.copy((char*)&key,sizeof(key));
buffer.erase(0,sizeof(key));
buffer.copy((char*)&rightNode,sizeof(Offset));
buffer.erase(0,sizeof(Offset));
}
int KeyElement::getDataSize(){
return (sizeof(KeyInt) + sizeof(Offset));
}
| [
"[email protected]"
]
| [
[
[
1,
64
]
]
]
|
e3b3d1007dc1fe34af2c3db29f25b7cac40523eb | cfa667b1f83649600e78ea53363ee71dfb684d81 | /code/tests/testnetworkgame/testgamestate.cc | 74e4c172f071d2c25e8525b5c981d16a4e76b066 | []
| no_license | zhouxh1023/nebuladevice3 | c5f98a9e2c02828d04fb0e1033f4fce4119e1b9f | 3a888a7c6e6d1a2c91b7ebd28646054e4c9fc241 | refs/heads/master | 2021-01-23T08:56:15.823698 | 2011-08-26T02:22:25 | 2011-08-26T02:22:25 | 32,018,644 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,577 | cc | //------------------------------------------------------------------------------
// testnetworkgame/testgamestate.cc
// (C) 2009 RadonLabs GmbH
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "testgamestate.h"
#include "basegamefeature/managers/entitymanager.h"
#include "debugrender/debugrender.h"
#include "input/inputserver.h"
#include "input/keyboard.h"
#include "input/gamepad.h"
#include "input/key.h"
#include "multiplayer/multiplayermanager.h"
#include "multiplayerfeature/distributionmanager.h"
#include "internalmultiplayer/multiplayertype.h"
#include "internalmultiplayer/internalmultiplayerinterface.h"
#include "basegamefeature/managers/entitymanager.h"
#include "basegamefeature/managers/factorymanager.h"
#include "basegamefeature/managers/focusmanager.h"
#include "basegamefeature/basegameattr/basegameattributes.h"
namespace Tools
{
__ImplementClass(Tools::TestGameState, 'TTGS', BaseGameFeature::GameStateHandler);
using namespace Util;
using namespace BaseGameFeature;
using namespace Input;
using namespace Multiplayer;
using namespace MultiplayerFeature;
using namespace Math;
//------------------------------------------------------------------------------
/**
*/
TestGameState::TestGameState()
{
}
//------------------------------------------------------------------------------
/**
*/
TestGameState::~TestGameState()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
Util::String
TestGameState::OnFrame()
{
return GameStateHandler::OnFrame();
}
//------------------------------------------------------------------------------
/**
*/
void
TestGameState::OnLoadBefore()
{
}
//------------------------------------------------------------------------------
/**
*/
void
TestGameState::OnLoadAfter()
{
// notify server that we have ended level loading
MultiplayerManager::Instance()->StartingFinished();
}
//------------------------------------------------------------------------------
/**
*/
void
TestGameState::SpawnPlayerEntities()
{
Util::Array<Ptr<Player>> players = MultiplayerManager::Instance()->GetSession()->GetPrivatePlayers();
players.AppendArray(MultiplayerManager::Instance()->GetSession()->GetPublicPlayers());
Util::String category("Player");
Util::String templateId("mensch");
matrix44 spawnPos = matrix44::translation(0,0,4);
matrix44 rotate45 = matrix44::rotationy(n_deg2rad(45));
IndexT i;
for (i = 0; i < players.Size(); ++i)
{
const Ptr<DistributionHost>& host = DistributionManager::Instance()->GetDistributionSystem().cast<DistributionHost>();
Ptr<Game::Entity> entity = host->CreatePlayerEntity(players[i], category, templateId);
entity->SetMatrix44(Attr::Transform, spawnPos);
spawnPos = matrix44::multiply(spawnPos, rotate45);
BaseGameFeature::EntityManager::Instance()->AttachEntity(entity);
playerEntities.Add(players[i], entity);
}
}
//------------------------------------------------------------------------------
/**
*/
void
TestGameState::SpawnPlayerEntity(const Ptr<Multiplayer::Player>& player)
{
Util::String category("Player");
Util::String templateId("mensch");
matrix44 spawnPos = matrix44::translation(0,0,4);
matrix44 rotate45 = matrix44::rotationy(n_deg2rad(45));
const Ptr<DistributionHost>& host = DistributionManager::Instance()->GetDistributionSystem().cast<DistributionHost>();
Ptr<Game::Entity> entity = host->CreatePlayerEntity(player, category, templateId);
entity->SetMatrix44(Attr::Transform, spawnPos);
spawnPos = matrix44::multiply(spawnPos, rotate45);
BaseGameFeature::EntityManager::Instance()->AttachEntity(entity);
playerEntities.Add(player, entity);
}
//------------------------------------------------------------------------------
/**
*/
void
TestGameState::RemovePlayerEntity(const Ptr<Multiplayer::Player>& player)
{
n_assert(this->playerEntities.Contains(player));
const Ptr<DistributionHost>& host = DistributionManager::Instance()->GetDistributionSystem().cast<DistributionHost>();
host->DestroyPlayerEntity(player, this->playerEntities[player]);
EntityManager::Instance()->RemoveEntity(this->playerEntities[player]);
this->playerEntities.Erase(player);
}
} // namespace Application | [
"[email protected]"
]
| [
[
[
1,
135
]
]
]
|
6be83f19f0897d1f9eee6bda4c1758421d74c502 | 3d7fc34309dae695a17e693741a07cbf7ee26d6a | /aluminizer/MgPage.h | 2e852335588277a2ffc6e576dbad50136fa1dd77 | [
"LicenseRef-scancode-public-domain"
]
| permissive | nist-ionstorage/ionizer | f42706207c4fb962061796dbbc1afbff19026e09 | 70b52abfdee19e3fb7acdf6b4709deea29d25b15 | refs/heads/master | 2021-01-16T21:45:36.502297 | 2010-05-14T01:05:09 | 2010-05-14T01:05:09 | 20,006,050 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,541 | h | #pragma once
#include "TransitionPage.h"
#include "FrequencySource.h"
class MgPage : public TransitionPage
{
public:
MgPage(const string& sPageName,
ExperimentsSheet* pSheet,
unsigned page_id);
virtual ~MgPage()
{
}
static bool matchTitle(const std::string& s)
{
return (s == "Mg") || (s.find("Mg Al") != std::string::npos);
}
virtual string TransitionName() const
{
return "Mg";
}
// virtual void CalibrateTransitions();
// virtual void MeasureTransitionFrequency(int sideband);
double AOMFrequency(int delta_n, bool AlwaysCalculate = false);
double PiTime(int delta_n, bool AlwaysCalculate = false);
virtual double ReferenceStateG(const physics::line& l);
virtual double ReferenceStateE(const physics::line& l);
virtual double GetCurrentGroundState()
{
return -3;
}
virtual void ShiftLine(const physics::line&, double, int);
static auto_ptr<FrequencySource> pHFS_synth;
//return the motional mode amplitude z0 for the given mode number
virtual double ModeAmplitude(int);
//for 90 deg. Raman beams
double delta_k() const
{
return 2*M_PI*sqrt(2.) / lambda();
}
double lambda() const
{
return 280.e-9;
}
double mass() const
{
return 4.15e-26;
}
virtual double CalibrateMagneticField();
virtual bool CanLink(const string& pname);
virtual ExpSCAN* getCalibrationExp(const calibration_item&);
protected:
virtual bool RecalculateParameters();
virtual void InitExperimentStart();
GUI_dds Detect, DopplerCool, Precool;
GUI_ttl Repump;
};
| [
"trosen@814e38a0-0077-4020-8740-4f49b76d3b44"
]
| [
[
[
1,
73
]
]
]
|
e99b09b212f068c21be13c1739be8edb25fadf5d | cecdfda53e1c15e7bd667440cf5bf8db4b3d3e55 | /Map Editor/includes.h | 50ab302f6879da6bc5a9752776e8c6a2d651fe89 | []
| no_license | omaskery/mini-stalker | f9f8713cf6547ccb9b5e51f78dfb65a4ae638cda | 954e8fce9e16740431743f020c6ddbc866e69002 | refs/heads/master | 2021-01-23T13:29:26.557156 | 2007-08-04T12:44:52 | 2007-08-04T12:44:52 | 33,090,577 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 218 | h | #include <fstream>
#include <sstream>
#include <vector>
#include <time.h>
#include "CouvertEngine.h"
#include "light.h"
#include "MyFont.h"
#include "functions.h"
#include "Config.h"
#include "MapEditor.h"
| [
"ollie.the.pie.lord@823218a8-ad34-0410-91fc-f9441fec9dcb"
]
| [
[
[
1,
11
]
]
]
|
cae61c10910131f3557881c7fdc9ad8a2b95f4f3 | 09c43e037d720e24e769ef9faa148f1377524c2c | /heroin/realm_server.cpp | 4039f546d1b90fe57d9423ca2a862a01934447dc | []
| no_license | goal/qqbot | bf63cf06e4976f16e2f0b8ec7c6cce88782bdf29 | 3a4b5920d5554cc55b6df962d27ebbc499c63474 | refs/heads/master | 2020-07-30T13:57:11.135976 | 2009-06-10T00:13:46 | 2009-06-10T00:13:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,903 | cpp | #include <heroin/client.hpp>
#include <iostream>
#include <nil/array.hpp>
#include <nil/random.hpp>
#include <nil/time.hpp>
#include <nil/string.hpp>
#include <heroin/utility.hpp>
#include <heroin/check_revision.hpp>
#include <heroin/bsha1.hpp>
#include <heroin/d2cdkey.hpp>
#include <heroin/compression.hpp>
bool get_mcp_packet(nil::net::tcp_socket & mcp_socket, std::string & buffer, std::string & data)
{
std::string packet;
while(buffer.size() < 3)
{
if (!mcp_socket.receive(packet)) {
return false;
}
buffer += packet;
}
ulong packet_size = read_word(buffer, 0);
while(packet_size > buffer.size())
{
if (!mcp_socket.receive(packet)) {
return false;
}
buffer += packet;
}
data = buffer.substr(0, packet_size);
buffer.erase(0, packet_size);
return true;
}
void d2_client::mcp_thread_function(void * unused)
{
std::cout << "[MCP] " << "Connecting to realm server " << mcp_ip << ":" << mcp_port << std::endl;
if (mcp_socket.connect(mcp_ip, mcp_port)) {
if (debugging) std::cout << "[MCP] " << "Successfully connected to realm server" << std::endl;
} else
std::cout << "[MCP] " << "Failed to connect to the realm server" << std::endl;
mcp_socket.send("\x01");
std::string packet = construct_mcp_packet(0x01, mcp_data);
mcp_socket.send(packet);
std::string mcp_buffer;
while (true) {
std::string data;
if (!get_mcp_packet(mcp_socket, mcp_buffer, data))
break;
ulong identifier = read_byte(data, 2);
//std::cout << "[MCP] " << "MCP data:" << std::endl;
//std::cout << "[MCP] " << data << std::endl;
//print_data(data);
if (identifier == 0x01) {
ulong result = read_dword(data, 3);
switch(result) {
case 0x00:
if (debugging) std::cout << "[MCP] " << "Successfully logged on to realm server" << std::endl;
break;
case 0x7e:
std::cout << "[MCP] " << "Your CD key has been banned from playing on this realm!" << std::endl;
break;
case 0x7f:
std::cout << "[MCP] " << "Your IP has been banned temporarily!" << std::endl;
break;
default:
std::cout << "[MCP] " << "Unknown realm server logon error occured (" << std::hex << result << ")" << std::endl;
break;
}
if (result != 0)
return;
// D2 only sends this the first time it connects, so...
if (!logged_in) {
if (debugging) std::cout << "[MCP] " << "Requesting character list" << std::endl;
mcp_socket.send(construct_mcp_packet(0x19, dword_to_string(8)));
} else
mcp_socket.send(construct_mcp_packet(0x07, character + zero));
} else if (identifier == 0x19) {
ulong count = read_word(data, 9);
if (count == 0) {
std::cout << "[MCP] " << "There are no characters on this account." << std::endl;
return;
} else {
bool found_character = false;
bool selected_first_character = false;
if (debugging) std::cout << "[MCP] " << "List of characters on this account:" << std::endl;
std::size_t offset = 11;
for (ulong i = 1; i <= count; i++) {
offset += 4;
std::string character_name = read_string(data, offset);
std::string stats = read_string(data, offset);
ulong character_class = read_byte(stats, 13);
ulong level = read_byte(stats, 25);
ulong flags = read_byte(stats, 26);
bool hardcore = (flags & 0x04) != 0;
bool dead = (flags & 0x08) != 0;
bool expansion = (flags & 0x20) != 0;
std::string character_class_string = get_character_class_string(character_class);
std::string core_string = hardcore ? "Hardcore" : "Softcore";
std::string expansion_string = expansion ? "Expansion" : "Classic";
if (debugging) std::cout << "[MCP] " << i << ". " << character_name << ", Level " << level << " " << character_class_string << " (" << expansion_string << ", " << core_string;
if (hardcore && dead)
if (debugging) std::cout << ", Dead";
if (debugging) std::cout << ")" << std::endl;
//print_data(stats);
if (character.empty() && i == 1) {
selected_first_character = true;
character = character_name;
}
if (character == character_name) {
found_character = true;
class_byte = character_class - 1;
character_level = level;
}
}
if (selected_first_character)
std::cout << "[MCP] " << "No character was specified in the ini file so the first character is being used" << std::endl;
if (!found_character) {
std::cout << "[MCP] " << "Unable to locate character specified in the ini file";
return;
}
std::cout << "[MCP] " << "Logging into character " << character << std::endl;
mcp_socket.send(construct_mcp_packet(0x07, character + zero));
}
} else if(identifier == 0x07) {
ulong result = read_dword(data, 3);
if (result != 0) {
std::cout << "[MCP] " << "Failed to log into character (" << std::hex << result << ")" << std::endl;
return;
}
if (debugging) std::cout << "[MCP] " << "Successfully logged into character" << std::endl;
if (debugging) std::cout << "[MCP] " << "Requesting channel list" << std::endl;
bncs_socket.send(construct_bncs_packet(0x0b, lod_id));
if (debugging) std::cout << "[MCP] " << "Entering the chat server" << std::endl;
bncs_socket.send(construct_bncs_packet(0x0a, character + zero + realm + "," + character + zero));
if (!logged_in) {
if (debugging) std::cout << "[MCP] " << "Requesting MOTD" << std::endl;
mcp_socket.send(construct_mcp_packet(0x12, ""));
logged_in = true;
}
} else if (identifier == 0x12) {
if (debugging) std::cout << "[MCP] " << "Received MOTD" << std::endl;
} else if (identifier == 0x03) {
//print_data(data);
ulong result = read_dword(data, 9);
switch (result) {
case 0x00:
if (debugging) std::cout << "[MCP] " << "Game has been created successfully" << std::endl;
break;
case 0x1e:
std::cout << "[MCP] " << "Invalid game name specified" << std::endl;
break;
case 0x1f:
std::cout << "[MCP] " << "This game already exists" << std::endl;
break;
case 0x20:
std::cout << "[MCP] " << "Game server down (it is probable that you tried to create a nightmare/hell game with a character who doesn't have access to that difficulty yet, or gamename/password were invalid)" << std::endl;
break;
case 0x6e:
std::cout << "[MCP] " << "Your character can't create a game because it's dead!" << std::endl;
break;
}
if (result == 0) {
if (debugging) std::cout << "[MCP] " << "Joining the game we just created" << std::endl;
join_game(game_name, game_password);
}
} else if (identifier == 0x04) {
//print_data(data);
ulong result = read_word(data, 17);
switch(result) {
case 0x00:
if (debugging) std::cout << "[MCP] " << "Successfully joined the game" << std::endl;
break;
case 0x29:
std::cout << "[MCP] " << "Password is incorrect" << std::endl;
break;
case 0x2A:
std::cout << "[MCP] " << "Game does not exist" << std::endl;
break;
case 0x2B:
std::cout << "[MCP] " << "Game is full" << std::endl;
break;
case 0x2C:
std::cout << "[MCP] " << "You do not meet the level requirements for this game" << std::endl;
break;
case 0x71:
std::cout << "[MCP] " << "A non-hardcore character cannot join a game created by a Hardcore character." << std::endl;
break;
case 0x73:
std::cout << "[MCP] " << "Unable to join a Nightmare game." << std::endl;
break;
case 0x74:
std::cout << "[MCP] " << "Unable to join a Hell game." << std::endl;
break;
case 0x78:
std::cout << "[MCP] " << "A non-expansion character cannot join a game created by an Expansion character." << std::endl;
break;
case 0x79:
std::cout << "[MCP] " << "A Expansion character cannot join a game created by a non-expansion character." << std::endl;
break;
case 0x7D:
std::cout << "[MCP] " << "A non-ladder character cannot join a game created by a Ladder character." << std::endl;
break;
}
if (result == 0 || result == 0x2B) {
ulong ip = read_dword(data, 9);
gs_ip = nil::net::ip_to_string(ip);
gs_hash = data.substr(13, 4);
gs_token = data.substr(5, 2);
bncs_socket.send(construct_bncs_packet(0x22, lod_id + dword_to_string(0xc) + game_name + zero + game_password + zero));
bncs_socket.send(construct_bncs_packet(0x10, ""));
gs_thread.start(nil::thread::function_type(*this, &d2_client::gs_thread_function));
mcp_socket.disconnect();
}
}
}
std::cout << "[MCP] " << "Disconnected from MCP server" << std::endl;
}
| [
"akirarat@ba06997c-553f-11de-8ef9-cf35a3c3eb08"
]
| [
[
[
1,
266
]
]
]
|
c77115667f93cc7eea09a1131d8c8e7fc2f64812 | a96e0816f6880d9560d6ae4074ef48ca17514348 | /cg-maze-src/compass.h | 45630e7f0435f6b46b13568a52e7b7937720cf35 | []
| no_license | kassaus/cg-paba-2011 | faafe4eb351afea972d47105353de8a177657002 | 45fb0f764562df45a1e09e1ef579c15c089224f5 | refs/heads/master | 2016-09-01T23:17:55.207855 | 2011-07-01T22:05:11 | 2011-07-01T22:05:11 | 32,128,305 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,921 | h | /*
Labirinto para Computacao Grafica (CG).
(C) 2010 Pedro Freire (www.pedrofreire.com)
Licenca Creative Commons:
Atribuicao - Uso Nao-Comercial - Partilha nos termos da mesma Licenca
http://creativecommons.org/licenses/by-nc-sa/2.5/pt/
Computer Graphics Maze.
(C) 2010 Pedro Freire (www.pedrofreire.com)
All comments in Portuguese.
Creative Commons license:
Attribution - Noncommercial - Share Alike
http://creativecommons.org/licenses/by-nc-sa/2.5/pt/deed.en_US
*/
#ifndef COMPASS_H
#define COMPASS_H
// **** Ficheiro independente para evitar referencia circular
// **** entre map.h e student_mapdraw.h
/* Definicao dos valores para os pontos cardeais
(da bussula, "compass" em Ingles).
Definidos por ordem dos ponteiros do relogio, comecando em Sul. Isto e'
a mesma ordem pela qual um QDial exibe visualmente os pontos cardeais.
Por coincidencia, os pontos que definem uma orientacao horizontal te^m
valores impares, e os que definem uma orientacao vertical te^m valores
pares.
*/
class Compass
{
public:
enum Direction { SOUTH = 0, WEST = 1, NORTH = 2, EAST = 3 };
private:
Direction direction;
public:
Compass( Direction d = NORTH ) { this->direction = d; }
Direction getDirection() { return this->direction; }
void setDirection( Direction d ) { this->direction = (Direction) ((int)d & 3); }
bool isHoriz() { return (bool) ((int)this->direction & 1); }
bool isVert() { return !(bool) ((int)this->direction & 1); }
Compass turnLeft() { this->direction = (Direction) (((int)this->direction - 1) & 3); return *this; }
Compass turnRight() { this->direction = (Direction) (((int)this->direction + 1) & 3); return *this; }
Compass turnBack() { this->direction = (Direction) (((int)this->direction + 2) & 3); return *this; }
};
#endif // COMPASS_H
| [
"antonio.gaspar.lourenco@6f8a15bf-34ff-41e7-c7d0-ef52abd84952"
]
| [
[
[
1,
56
]
]
]
|
473705c6f946633da02db9c98ea8ac4ef05f8823 | 1ff9f78a9352b12ad34790a8fe521593f60b9d4f | /Template/Sprite.cpp | 5e3cac77216e9599699fbcb1716f5059554dec70 | []
| no_license | SamOatesUniversity/Year-2---Game-Engine-Construction---Sams-Super-Space-Shooter | 33bd39b4d9bf43532a3a3a2386cef96f67132e1e | 46022bc40cee89be1c733d28f8bda9fac3fcad9b | refs/heads/master | 2021-01-20T08:48:41.912143 | 2011-01-19T23:52:25 | 2011-01-19T23:52:25 | 41,169,993 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,734 | cpp | #include "Sprite.h"
CSprite::CSprite(void)
{
m_iWidth = NULL;
m_iHeight = NULL;
m_iX = 0;
m_iY = 0;
m_iLx = 0;
m_iLy = 0;
m_imageData = NULL;
m_screenData = HAPI->GetScreenPointer();
m_drawType = Tnormal;
m_isClone = false;
m_isActive = true;
}
CSprite::~CSprite(void)
{
delete m_rect;
if( m_imageData && !m_isClone ) delete[] m_imageData;
}
void CSprite::copy( CSprite *source )
{
m_imageData = source->getImageData();
m_screenData = HAPI->GetScreenPointer();
m_iWidth = source->getWidth();
m_iHeight = source->getHeight();
m_drawType = source->getDrawType();
m_rect = new CRectangle( 0, 0, m_iWidth, m_iHeight );
m_isClone = true;
}
bool CSprite::init( char* imageLocation, TDraw drawType )
{
bool res = true;
if( !HAPI->LoadTexture( imageLocation, &m_imageData, &m_iWidth, &m_iHeight ) )
res = false;
m_rect = new CRectangle( 0, 0, m_iWidth, m_iHeight );
m_drawType = drawType;
return res;
}
void CSprite::draw( CRectangle *destination )
{
BYTE *screen = NULL, *imgPtr = NULL;
int frameWidth = m_iWidth / m_iFrameCount;
switch( m_drawType )
{
case Tnormal:
//the default, supports full alpha.
//per pixel
m_rect->clipTo( destination );
imgPtr = m_imageData + (( m_rect->getClipX1() + (m_rect->getClipY1() * m_iWidth )) * 4);
imgPtr += ( m_iActiveFrame * frameWidth ) * 4;
for( int ty = m_iY + m_rect->getClipY1(); ty < m_iY + m_rect->getClipY2(); ty++ )
{
for( int tx = m_iX + m_rect->getClipX1(); tx < m_iX + m_rect->getClipX2(); tx++ )
{
//check if the pixel has any alpha
if( imgPtr[3] > 0 )
{
//if full alpha, copy image over background
if( imgPtr[3] == 255 )
{
screen = m_screenData + ( ( ( tx ) + ( ( ty ) * destination->getAbsoluteW() ) ) * 4);
memcpy( screen, imgPtr, 4 );
}
//otherwise merge the image and background colours respectivly
else
{
screen = m_screenData + ( ( ( tx ) + ( ( ty ) * destination->getAbsoluteW() ) ) * 4);
screen[0]=screen[0]+((imgPtr[3]*(imgPtr[0]-screen[0])) >> 8);
screen[1]=screen[1]+((imgPtr[3]*(imgPtr[1]-screen[1])) >> 8);
screen[2]=screen[2]+((imgPtr[3]*(imgPtr[2]-screen[2])) >> 8);
}
}
imgPtr += 4;
}
imgPtr += ( m_iWidth - ( m_rect->getClipX2() - m_rect->getClipX1() ) ) * 4;
}
break;
case Tfast:
//Fast Draw, ignores alpha
m_rect->clipTo( destination );
imgPtr = m_imageData + (( m_rect->getClipX1() + (m_rect->getClipY1() * m_rect->getAbsoluteW() )) * 4);
for( int ty = m_iY + m_rect->getClipY1(); ty < m_iY + m_rect->getClipY2(); ty++ )
{
screen = m_screenData + ( ( ( m_iX + m_rect->getClipX1() ) + ( ty * destination->getAbsoluteW() ) ) * 4);
memcpy( screen, imgPtr, ( m_rect->getClipX2() - m_rect->getClipX1() ) * 4 );
imgPtr += m_rect->getAbsoluteW() * 4;
}
break;
case Tbackground:
//does a full background draw. fast
if( m_iX < 0 ) m_iX = 0;
imgPtr = m_imageData + ( m_iX * 4 );
for( int i = 0; i < destination->getAbsoluteH(); i++ )
{
screen = m_screenData + ( ( i * destination->getAbsoluteW() ) * 4);
memcpy( screen, imgPtr, destination->getAbsoluteW() * 4 );
imgPtr += m_iWidth * 4;
}
break;
}
}
void CSprite::setAnimation( const int activeFrame, const int frameCount )
{
m_iActiveFrame = activeFrame;
m_iFrameCount = frameCount;
int frameWidth = m_iWidth / frameCount;
m_rect->update( 0, 0, frameWidth, m_iHeight );
}
void CSprite::setXY( const int x, const int y )
{
m_iX = x;
m_iY = y;
m_rect->position( x, y );
}
void CSprite::setLastXY( const int x, const int y )
{
m_iLx = x;
m_iLy = y;
}
| [
"[email protected]"
]
| [
[
[
1,
140
]
]
]
|
608eaecdc1bd1493e014c16ac56c813976810ae8 | 5868b47824cdb157ddd301ee10382bd246ed48c1 | /matrix4x4f.h | 00d6fb973a6e953623fb91fce98f14b1a2798ffe | []
| no_license | cmdalbem/ninjagl | d68b16d5e1712434542f6b8c7f3f5cdb2a7ee0ab | 947113a2e2df99500cdee9d5e175f6a39e010d5a | refs/heads/master | 2020-05-20T04:59:54.719431 | 2011-07-05T19:50:54 | 2011-07-05T19:50:54 | 32,224,153 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,975 | h | //-----------------------------------------------------------------------------
// Name: matrix4x4f.h
// Author: Kevin Harris
// Last Modified: March 13, 2005 by Manuel Menezes
// Description: OpenGL compatible utility class for a 4x4 matrix of floats.
// NOTE: This class has been left unoptimized for readability.
//-----------------------------------------------------------------------------
#pragma once
#include "vector3f.h"
#include "vector4f.h"
#define DEGTORAD(degree) ((degree) * (3.141592654f / 180.0f))
#define RADTODEG(radian) ((radian) * (180.0f / 3.141592654f))
class matrix4x4f
{
public:
float m[16];
matrix4x4f() { identity(); }
matrix4x4f( float m0, float m4, float m8, float m12,
float m1, float m5, float m9, float m13,
float m2, float m6, float m10, float m14,
float m3, float m7, float m11, float m15 );
void identity(void);
void rotate(float angle, vector3f axis);
void transformVector( vector3f *vec );
void transformVector( vector4f *vec );
void print();
matrix4x4f operator * (const matrix4x4f &other);
};
matrix4x4f::matrix4x4f( float m0, float m4, float m8, float m12,
float m1, float m5, float m9, float m13,
float m2, float m6, float m10, float m14,
float m3, float m7, float m11, float m15 )
{
m[0]=m0; m[4]=m4; m[8] =m8; m[12]=m12;
m[1]=m1; m[5]=m5; m[9] =m9; m[13]=m13;
m[2]=m2; m[6]=m6; m[10]=m10; m[14]=m14;
m[3]=m3; m[7]=m7; m[11]=m11; m[15]=m15;
}
void matrix4x4f::identity( void )
{
m[0]=1.0f; m[4]=0.0f; m[8] =0.0f; m[12]=0.0f;
m[1]=0.0f; m[5]=1.0f; m[9] =0.0f; m[13]=0.0f;
m[2]=0.0f; m[6]=0.0f; m[10]=1.0f; m[14]=0.0f;
m[3]=0.0f; m[7]=0.0f; m[11]=0.0f; m[15]=1.0f;
}
void matrix4x4f::rotate( float angle, vector3f axis )
{
float s = sin(DEGTORAD(angle));
float c = cos(DEGTORAD(angle));
axis.normalize();
float ux = axis.x;
float uy = axis.y;
float uz = axis.z;
m[0] = c + (1-c) * ux;
m[1] = (1-c) * ux*uy + s*uz;
m[2] = (1-c) * ux*uz - s*uy;
m[3] = 0;
m[4] = (1-c) * uy*ux - s*uz;
m[5] = c + (1-c) * pow(uy,2);
m[6] = (1-c) * uy*uz + s*ux;
m[7] = 0;
m[8] = (1-c) * uz*ux + s*uy;
m[9] = (1-c) * uz*uz - s*ux;
m[10] = c + (1-c) * pow(uz,2);
m[11] = 0;
m[12] = 0;
m[13] = 0;
m[14] = 0;
m[15] = 1;
}
void matrix4x4f::transformVector( vector3f *vec )
{
vector3f &v = *vec;
float x = v.x;
float y = v.y;
float z = v.z;
v.x = x * m[0] +
y * m[4] +
z * m[8];
v.y = x * m[1] +
y * m[5] +
z * m[9];
v.z = x * m[2] +
y * m[6] +
z * m[10];
}
void matrix4x4f::transformVector( vector4f *vec )
{
vector4f &v = *vec;
float x = v.x;
float y = v.y;
float z = v.z;
float w = v.w;
v.x = x * m[0] +
y * m[4] +
z * m[8] +
w * m[12];
v.y = x * m[1] +
y * m[5] +
z * m[9] +
w * m[13];
v.z = x * m[2] +
y * m[6] +
z * m[10] +
w * m[14];
v.w = x * m[3] +
y * m[7] +
z * m[11] +
w * m[15];
}
void matrix4x4f::print()
{
for(int k=0; k<4; k++) {
for(int i=0; i<4; i++)
printf("%.3f\t\t",m[k + i*4]);
printf("\n");
}
printf("\n");
}
matrix4x4f matrix4x4f::operator * ( const matrix4x4f &other )
{
matrix4x4f mult(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
#define pos(x,y) (x + y*4)
for(int y=0; y<4; y++)
for(int x=0; x<4; x++)
for(int k=0; k<4; k++)
mult.m[pos(x,y)] += this->m[pos(k,y)] * other.m[pos(x,k)];
return mult;
}
| [
"ninja.dalbem@182d6c7c-08b0-3e63-d223-3bdb4f79db72"
]
| [
[
[
1,
167
]
]
]
|
c8884d607a2e31d313b3ab524506d1a7d2e03af8 | 7a310d01d1a4361fd06b40a74a2afc8ddc23b4d3 | /src/SearchBar.cpp | f8ca86b31664a12c7932912ed067da772245550b | []
| no_license | plus7/DonutG | b6fec6111d25b60f9a9ae5798e0ab21bb2fa28f6 | 2d204c36f366d6162eaf02f4b2e1b8bc7b403f6b | refs/heads/master | 2020-06-01T15:30:31.747022 | 2010-08-21T18:51:01 | 2010-08-21T18:51:01 | 767,753 | 1 | 2 | null | null | null | null | SHIFT_JIS | C++ | false | false | 73,544 | cpp | /**
* @file SearchBar.cpp
* @brief 検索バー
* @note
* templateで実装されていた SearchBar.h を普通のclassにして .h, .cpp 化したもの.
*/
#include "stdafx.h"
#include "DonutPFunc.h"
#include "DonutViewOption.h"
#include "MtlDragDrop.h"
#include "ExplorerMenu.h"
#include "HlinkDataObject.h"
#include "ExStyle.h"
#include <atlctrls.h>
//#include "StringEncoder.h" //+++ 不要化
#include <winnls32.h>
#include "ParseInternetShortcutFile.h"
#include "Donut.h"
#include "SearchBar.h"
#if defined USE_ATLDBGMEM
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define ENGINENAME_FOR_NO_SEARCH_INI _T("search.iniが無いのでGoogleのみ")
//+++ ParseInternetShortcutFile()用に手抜きで自身のポインタを用意...
CDonutSearchBar* CDonutSearchBar::s_pThis_ = 0;
CDonutSearchBar::CDonutSearchBar()
: m_wndKeyword(this, 1)
, m_wndEngine (this, 2)
, m_wndKeywordCombo(this, 3)
, m_hThread(0) //+++
, m_cxBtnsBtn(0) //+++ 旧横幅調整用
, m_clrMask(0) //+++
, m_bActiveWindow(0) //+++
, m_hWndKeywordList(0) //+++
, m_has(0) //+++
, m_nDefDlgH(22) //+++
, m_nItemFontH(21) //+++
, m_nEngineWidth(0) //+++
, m_bHilightSw(0) //+++
//, m_nHilightBtnNo(0) //+++
, m_bExistManifest(IsExistManifestFile()) //+++
#ifndef USE_DIET
, m_dwNoWordButton(0) //+++
, m_dwUsePageButton(0) //+++
, m_dwTinyWordButton(0) //+++
#endif
{
m_hCursor = NULL;
m_bDragAccept = false;
m_bDragFromItself = false;
m_bShowToolBar = FALSE;
m_bLoadedToolBar = FALSE;
m_bFiltering = FALSE;
m_bUseShortcut = FALSE;
m_bActiveWindow = FALSE;
//+++ 1つしかインスタンスが作られない、だろうとして、ParseInternetShortcutFile()用に手抜きな自分を指すポインタ.
ATLASSERT(s_pThis_ == 0);
s_pThis_ = this;
}
/// AddressBar側で使うコンボ文字列の設定
void CDonutSearchBar::InitComboBox_for_AddressBarPropertyPage(CComboBox& rCmbCtrl, CComboBox& rCmbShift)
{
int nCount = m_cmbEngine.GetCount();
for (int i = 0; i < nCount; i++) {
CString strBuf;
m_cmbEngine.GetLBText(i, strBuf);
rCmbCtrl.AddString(strBuf);
rCmbShift.AddString(strBuf);
}
}
//なにやら描画がおかしくなるバグをfix minit
LRESULT CDonutSearchBar::OnEraseBkgnd(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL &bHandled)
{
// CAddressBarCtrlImplからコピペ
HWND hWnd = GetParent();
CPoint pt(0, 0);
MapWindowPoints(hWnd, &pt, 1);
pt = ::OffsetWindowOrgEx( (HDC) wParam, pt.x, pt.y, NULL );
LRESULT lResult = ::SendMessage(hWnd, WM_ERASEBKGND, wParam, 0L);
::SetWindowOrgEx( (HDC) wParam, pt.x, pt.y, NULL );
return 1; //lResult;
}
///+++ 検索文字列を取得する
const CString& CDonutSearchBar::GetSearchStr()
{
HWND hWnd = GetEditCtrl();
//+++ なるべく、アロケートが発生しないようにしてみる.
enum { NAME_LEN = 0x1000 };
TCHAR name[ NAME_LEN ];
int nLen = ::GetWindowTextLength(hWnd);
if (nLen >= NAME_LEN)
nLen = NAME_LEN - 1;
name[0] = '\0';
int nRetLen = ::GetWindowText(hWnd, name, nLen + 1);
name[nLen+1] = '\0';
if (_tcscmp(name, LPCTSTR(m_strEngine)) != 0) {
m_strKeyword = name;
}
return m_strKeyword;
}
LRESULT CDonutSearchBar::OnToolTipText(int idCtrl, LPNMHDR pnmh, BOOL & /*bHandled*/)
{
LPNMTTDISPINFO pDispInfo = (LPNMTTDISPINFO) pnmh;
pDispInfo->szText[0] = 0;
if (pDispInfo->uFlags & TTF_IDISHWND)
return S_OK;
//#if 1 //+++
// CString strKeyword = GetSearchStr();
//#else
// CString strKeyword = MtlGetWindowText(m_wndKeyword);
//#endif
CString strHeader = _T('\"');
CString strHelp = _T("\" を");
CString strEngine = GetSearchEngineStr(); // MtlGetWindowText(m_wndEngine);
TCHAR szBuff[80+4];
szBuff[0] = 0;
AtlCompactPathFixed( szBuff, GetSearchStr()/*strKeyword*/, 80 - strHelp.GetLength() - strHeader.GetLength() );
strHeader += szBuff;
strHeader += strHelp;
switch (idCtrl) {
case ID_SEARCH_WEB: strHeader += _T("\"") + strEngine + _T("\"で検索する"); break;
case ID_SEARCHBAR_HILIGHT: strHeader += _T("ハイライトする"); break;
case ID_SEARCH_PAGE: strHeader += _T("このページで検索する(↑:Shift+Enter ↓:Ctrl+Enter)"); break;
default: // ID_SEARCH_WORD00..09
return S_OK;
}
::lstrcpyn(pDispInfo->szText, strHeader, 80);
return S_OK;
}
void CDonutSearchBar::OnCommand(UINT uFlag, int nID, HWND hWndCtrl)
{
if (hWndCtrl == m_wndToolBar.m_hWnd) {
//#if 1 //+++
// CString str = GetSearchStr();
//#else
// CEdit edit = GetEditCtrl();
// CString str = MtlGetWindowText(edit);
//#endif
switch (nID) {
case ID_SEARCH_WEB:
#if 1
SearchWeb();
#else
_OnCommand_SearchWeb( GetSearchStr() /*str*/ );
#endif
break;
case ID_SEARCHBAR_HILIGHT: //ID_SEARCH_HILIGHT:
//GetHilightBtnFlag();
//m_bHilightSw^=1;
#if 1 //+++
SearchHilight();
#else
//_OnCommand_SearchHilight( str);
#endif
break;
case ID_SEARCH_PAGE:
_OnCommand_SearchPage( (::GetKeyState(VK_SHIFT) >= 0));
break;
case ID_SEARCHBAR_WORD00:
case ID_SEARCHBAR_WORD01:
case ID_SEARCHBAR_WORD02:
case ID_SEARCHBAR_WORD03:
case ID_SEARCHBAR_WORD04:
case ID_SEARCHBAR_WORD05:
case ID_SEARCHBAR_WORD06:
case ID_SEARCHBAR_WORD07:
case ID_SEARCHBAR_WORD08:
case ID_SEARCHBAR_WORD09:
case ID_SEARCHBAR_WORD10:
case ID_SEARCHBAR_WORD11:
case ID_SEARCHBAR_WORD12:
case ID_SEARCHBAR_WORD13:
case ID_SEARCHBAR_WORD14:
case ID_SEARCHBAR_WORD15:
case ID_SEARCHBAR_WORD16:
case ID_SEARCHBAR_WORD17:
case ID_SEARCHBAR_WORD18:
case ID_SEARCHBAR_WORD19:
_OnCommand_SearchPage((::GetKeyState(VK_SHIFT) >= 0), nID-ID_SEARCHBAR_WORD00);
break;
default:
ATLASSERT(0);
}
SetMsgHandled(TRUE);
return;
}
SetMsgHandled(FALSE);
}
//+++ ハイライトボタンのon/off状態を返す
bool CDonutSearchBar::GetHilightBtnFlag()
{
#if 0
int rc1 = m_wndToolBar.IsButtonChecked( ID_SEARCHBAR_HILIGHT );
int rc2 = m_wndToolBar.IsButtonPressed( ID_SEARCHBAR_HILIGHT );
int rc3 = m_wndToolBar.IsButtonEnabled( ID_SEARCHBAR_HILIGHT );
int rc4 = m_wndToolBar.IsButtonHidden ( ID_SEARCHBAR_HILIGHT );
int rc5 = m_wndToolBar.IsButtonIndeterminate( ID_SEARCHBAR_HILIGHT );
int rc6 = m_wndToolBar.IsButtonHighlighted( ID_SEARCHBAR_HILIGHT );
if (rc3 < 0)
return m_bHilightSw != 0;
if (rc1 < 0)
rc1 = m_bHilightSw;
bool rc = (rc1 > 0 || rc2 > 0) && /*rc3 > 0 &&*/ (rc4 <= 0 || rc5 <= 0);
m_bHilightSw= rc;
return rc;
#else
return m_bHilightSw != 0;
#endif
}
/** ハイライトボタンを強制的に設定する
*/
bool CDonutSearchBar::ForceSetHilightBtnOn(bool sw)
{
bool rc = (BOOL(sw) != m_bHilightSw);
m_bHilightSw = sw;
int hilightStat = m_bHilightSw ? TBSTATE_PRESSED : TBSTATE_ENABLED;
m_wndToolBar.SetButtonInfo(ID_SEARCHBAR_HILIGHT, TBIF_STATE, 0, hilightStat, 0, 0, 0, 0, 0);
return rc;
}
//+++
void CDonutSearchBar::OnSearchWeb_engineId(UINT code, int id, HWND hWnd)
{
ATLASSERT(ID_INSERTPOINT_SEARCHENGINE <= id && id <= ID_INSERTPOINT_SEARCHENGINE_END);
unsigned n = id - ID_INSERTPOINT_SEARCHENGINE;
CString strEngine;
MtlGetLBTextFixed(m_cmbEngine, n, strEngine);
CString str = GetSearchStr();
SearchWeb_str_engine(str, strEngine);
}
void CDonutSearchBar::SearchWeb()
{
#if 1 //+++
CString str = GetSearchStr();
_OnCommand_SearchWeb( str );
#endif
}
void CDonutSearchBar::_OnCommand_SearchWeb(CString &str)
{
int nTarCate = m_cmbEngine.GetCurSel();
if (nTarCate == -1)
return;
SearchWeb_str_engine(str, GetSearchEngineStr());
}
//+++ エンジンの選択をできるように_OnCommand_SearchWebの実体を分離.
void CDonutSearchBar::SearchWeb_str_engine(CString &str, const CString& strSearchEng)
{
#if 1
//x CString strSearchEng = MtlGetWindowText(m_cmbEngine);
bool bUrlSearch = false;
if (::GetFocus() != m_wndKeyword.m_hWnd) {
#if 1 //+++ 強引なので、あとで、仕組みを直す
// 選択範囲があれば、それを優先する.
CString strSel = Donut_GetActiveSelectedText();
if (strSel.IsEmpty() == 0) {
str = strSel;
}
#endif
if (str.IsEmpty()) //+++ 検索文字列が空の場合.
{
if (strSearchEng.IsEmpty())
return;
CString strSearchPath = GetSearchIniPath();
CIniFileI pr(strSearchPath, strSearchEng);
DWORD exPropOpt = pr.GetValue(_T("ExPropOpt"), 0);
pr.Close();
if (exPropOpt & 1) { // addressbarの文字を取ってくる場合.
CString strUrl = GetAddressBarText();
if (strUrl.IsEmpty() == 0) {
str = strUrl;
bUrlSearch = true;
}
}
}
}
#endif
GetHilightBtnFlag(); //+++ ハイライトボタンの状態チェック
toolBarAddButtons(/*str*/); //+++ サーチのツールバー部に単語を設定
if ( !str.IsEmpty() ) {
#if 1 //+++ OnItemSelectedを分解したのでOpenSearchを呼ぶように変更.
BOOL bFirst = TRUE;
int nLoopCtn = 0;
OpenSearch(str, strSearchEng, nLoopCtn, bFirst);
#elif 1 //+++ templateをやめたのでthisでいい.
this->OnItemSelected(str, strSearchEng);
#else
T *pT = static_cast<T *>(this);
pT->OnItemSelected(str, strSearchEng);
#endif
if (bUrlSearch == false) //+++ url検索だった場合は、履歴に入れないで置く.
_AddToSearchBoxUnique(str);
}
#if 1 //+++ 不要かもだが...テスト的に...
//+++ 表示→ツールバー→検索バーボタンをonの時のみ
ShowToolBarIcon(m_bShowToolBar/*true*/);
#endif
}
void CDonutSearchBar::_OnCommand_SearchHilight(CString &str)
{
GetHilightBtnFlag();
m_bHilightSw ^= 1;
checkToolBarWords(); //+++
//toolBarAddButtons(false); //+++ ためし...
str = RemoveShortcutWord(str);
if (m_bFiltering)
FilterString(str);
#if 0 //+++ ここで、はじくと、ハイライトボタンのonが瞬間でおわってoffに戻るので、メッセージは投げておく
if (str.IsEmpty())
return;
#endif
SendMessage(GetTopLevelParent(), WM_USER_HILIGHT, (WPARAM) LPCTSTR(str)/*str.GetBuffer(0)*/, 0);
GetHilightBtnFlag(); //+++ ハイライトボタンの状態チェック
}
void CDonutSearchBar::_OnCommand_SearchPage(BOOL bForward, int no /*=-1*/)
{
GetHilightBtnFlag(); //+++ ハイライトボタンの状態チェック
checkToolBarWords(); //+++
CEdit edit = GetEditCtrl();
#if 1 //+++ カーソル位置の単語だけを選択するようにしてみる.
CString str;
if (no >= 0) {
str = _GetSelectText(edit);
//引用符・ショートカットワードは除外
str = RemoveShortcutWord(str);
if (m_bFiltering)
FilterString(str);
std::vector<CString> strs;
strs.reserve(10);
Misc::SeptTextToWords(strs, str);
if (size_t(no) < strs.size())
str = strs[no];
} else {
str = _GetSelectText_OnCursor(edit);
//引用符・ショートカットワードは除外
str = RemoveShortcutWord(str);
}
#else
CString str = _GetSelectText(edit);
//引用符・ショートカットワードは除外
str = RemoveShortcutWord(str);
#endif
CString strExcept = _T(" \t\"\r\n ");
str.TrimLeft(strExcept);
str.TrimRight(strExcept);
if (m_bFiltering)
FilterString(str);
SendMessage(GetTopLevelParent(), WM_USER_FIND_KEYWORD, (WPARAM) str.GetBuffer(0), (LPARAM) bForward);
}
//public
const CString CDonutSearchBar::RemoveShortcutWord(const CString &str)
{
if (m_bUseShortcut) {
if (str.Find( _T("\\") ) == 0 || str.Find( _T("/") ) == 0) {
int nPos = str.Find( _T(" ") );
if (nPos != -1)
return str.Mid(nPos + 1);
}
}
return str;
}
///+++
int CDonutSearchBar::btnWidth() const
{
#if 1
int btnW = ::GetSystemMetrics(SM_CXHTHUMB);
if (m_bExistManifest == 0)
btnW += 2 * 2;
else
btnW += 2;
return btnW;
#else
return 21;
#endif
}
///+++ キーワード入力欄が空の時にエンジン名を表示するための設定
void CDonutSearchBar::SetCmbKeywordEmptyStr()
{
m_cmbKeyword.setEmptyStr(GetSearchEngineStr(), IDC_EDIT/*1001*/, (m_nEngineWidth <= 8+btnWidth()));
m_cmbKeyword.redrawEmptyStr();
}
// private:
LRESULT CDonutSearchBar::OnSize(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
#ifndef USE_DIET
//+++ 検索単語を項目にするため、検索バーのサイズ調整方法を変更.
if (m_dwNoWordButton == 0) { //+++ 単語ボタンありのとき
return ResizeBar(0,0);
} else {
//+++ 単語ボタン無しの場合は旧処理.
//if (!m_wndToolBar.m_hWnd)
// return S_FALSE;
if (!m_wndKeyword.m_hWnd)
return S_FALSE;
CRect rcDlg;
GetClientRect(&rcDlg);
CRect rcToolbar(rcDlg);
CString str;
if (rcDlg.right == 0)
return S_FALSE;
if ( GetToolIconState() && m_wndToolBar.m_hWnd ) {
rcToolbar.left = rcDlg.right - m_cxBtnsBtn - 10;
m_wndToolBar.SetWindowPos(NULL, rcToolbar, SWP_NOZORDER | SWP_NOSENDCHANGING);
} else {
//非表示
rcToolbar.left = rcDlg.right;
}
CRect rcEngine;
m_cmbEngine.GetWindowRect(&rcEngine);
int nEngineCX = rcEngine.Width();
int nEngineCY = rcEngine.Height();
if (nEngineCX <= btnWidth()) //+++
nEngineCX = btnWidth();
m_nKeywordWidth = nEngineCX;
rcEngine = rcToolbar;
rcEngine.right = rcToolbar.left - s_kcxGap;
rcEngine.left = rcEngine.right - nEngineCX;
rcEngine.top = m_nDefEditT; //minit
rcEngine.bottom = rcEngine.top + nEngineCY;
m_cmbEngine.SetWindowPos(NULL, rcEngine, SWP_NOZORDER | SWP_NOSENDCHANGING);
CRect rcKeyword(rcEngine);
rcKeyword.left = 0;
rcKeyword.right = rcEngine.left - s_kcxGap;
m_cmbKeyword.SetWindowPos(NULL, rcKeyword, SWP_NOZORDER | SWP_NOSENDCHANGING);
#if 1 //+++ 暫定対処... 本質的に修正できていないがon_
m_cmbKeyword.SetEditSel(0,0); //+++ 無理やり範囲解除
#endif
SetCmbKeywordEmptyStr(); //+++
m_wndToolBar.InvalidateRect(NULL, TRUE);
return S_OK;
}
#else // USE_DIET時は 単語ボタンのみ
return ResizeBar(0,0);
#endif
}
///+++ バーのサイズ変更. キーワード|エンジン|ツールバー の境目での移動幅を順にdifA,difBとする.
int CDonutSearchBar::ResizeBar(int difA, int difB)
{
if (!m_wndKeyword.m_hWnd) {
return S_FALSE;
}
CRect rcDlg;
GetClientRect(&rcDlg);
if (rcDlg.right == 0) {
return S_FALSE;
}
//int h = rcDlg.Height();
CRect rcKeyword;
m_cmbKeyword.GetWindowRect(&rcKeyword);
m_nKeywordWidth = rcKeyword.Width();
int h = rcKeyword.Height();
m_nKeywordWidth += difA;
if (m_nKeywordWidth <= btnWidth())
m_nKeywordWidth = btnWidth();
rcKeyword.left = 0;
rcKeyword.top = m_nDefEditT;
rcKeyword.right = m_nKeywordWidth;
rcKeyword.bottom= rcKeyword.top + h;
m_cmbKeyword.SetWindowPos(NULL, rcKeyword, SWP_NOZORDER | SWP_NOSENDCHANGING);
CRect rcEngine;
m_cmbEngine.GetWindowRect(&rcEngine);
h = rcEngine.Height();
m_nEngineWidth = rcEngine.Width();
m_nEngineWidth += difB;
if (m_nEngineWidth <= btnWidth()) {
m_nEngineWidth = btnWidth();
}
rcEngine.left = rcKeyword.right + s_kcxGap;
rcEngine.top = m_nDefEditT;
rcEngine.right = rcEngine.left + m_nEngineWidth;
rcEngine.bottom = rcEngine.top + h;
m_cmbEngine.SetWindowPos(NULL, rcEngine, SWP_NOZORDER | SWP_NOSENDCHANGING);
CRect rcToolbar(rcDlg);
rcToolbar.left = rcEngine.right + s_kcxGap;
if (rcToolbar.left > rcToolbar.right)
rcToolbar.left = rcToolbar.right;
if ( GetToolIconState() ) {
} else {
//非表示
rcToolbar.left = rcDlg.right;
}
if (m_wndToolBar.m_hWnd)
m_wndToolBar.SetWindowPos(NULL, rcToolbar, SWP_NOZORDER | SWP_NOSENDCHANGING);
m_wndToolBar.InvalidateRect(NULL, TRUE);
return S_OK;
}
#if 1 //test
bool CDonutSearchBar::checkEngineNameEnable()
{
if (::IsWindow(m_hWnd) == 0)
return false;
if (::IsWindow(m_cmbKeyword.m_hWnd) == 0)
return false;
if (::GetFocus() == GetEditCtrl())
return false;
CRect rcEngine;
m_cmbEngine.GetWindowRect(&rcEngine);
int engineW = rcEngine.Width();
if (engineW > btnWidth())
return false;
CRect rcKeyword;
m_cmbKeyword.GetWindowRect(&rcKeyword);
int keywordW = rcKeyword.Width();
if (keywordW <= btnWidth())
return false;
//CPaintDC dc(m_cmbKeyword.m_hWnd);
//dc.TextOut(rcKeyword.left, rcKeyword.top, "Test");
//dc.TextOut(0, 0, "ABCDEF");
return true;
}
#endif
void CDonutSearchBar::InitToolBar(int cx, int cy, COLORREF clrMask, UINT nFlags /*= ILC_COLOR24*/)
{
m_clrMask = clrMask;
CImageList imgs;
MTLVERIFY( imgs.Create(cx, cy, nFlags | ILC_MASK, 1, 1) );
CBitmap bmp;
bmp.Attach( AtlLoadBitmapImage(LPCTSTR(GetSkinSeachBarPath(0)), LR_LOADFROMFILE) );
if (bmp.m_hBitmap == NULL)
bmp.LoadBitmap(IDB_SEARCHBUTTON/*nImageBmpID*/); //+++ skinの処理がここにあるので、デフォルト素材もこの場で設定にしとく...
imgs.Add(bmp, clrMask);
CImageList imgsHot;
MTLVERIFY( imgsHot.Create(cx, cy, nFlags | ILC_MASK, 1, 1) );
CBitmap bmpHot;
bmpHot.Attach( AtlLoadBitmapImage(LPCTSTR(GetSkinSeachBarPath(1)), LR_LOADFROMFILE) );
if (bmpHot.m_hBitmap == NULL)
bmpHot.LoadBitmap(IDB_SEARCHBUTTON_HOT/*nHotImageBmpID*/); //+++ skinの処理がここにあるので、デフォルト素材もこの場で設定にしとく...
imgsHot.Add(bmpHot, clrMask);
#if 1 //+++ Disableも用意する
CString str = GetSkinSeachBarPath(2);
int dis = 0;
if (Misc::IsExistFile(str) == 0) { //+++ 画像ファイルがない時
if (Misc::IsExistFile(GetSkinSeachBarPath(0))) { //+++ 通常があれば
str = GetSkinSeachBarPath(0); //+++ 通常画で代用
} else { //+++ 通常もなければ
dis = IDB_SEARCHBUTTON_DIS; //+++ デフォルトのDisable画を使う.
}
}
CImageList imgsDis;
MTLVERIFY( imgsDis.Create(cx, cy, nFlags | ILC_MASK, 1, 1) );
CBitmap bmpDis;
bmpDis.Attach( AtlLoadBitmapImage(LPCTSTR(str), LR_LOADFROMFILE) );
if (bmpDis.m_hBitmap == NULL && dis)
bmpDis.LoadBitmap(dis); //+++ skinの処理がここにあるので、デフォルト素材もこの場で設定にしとく...
imgsDis.Add(bmpDis, clrMask);
#endif
#ifndef USE_DIET
CIniFileI pr( g_szIniFileName, _T("SEARCH") );
//DWORD jikken = pr.GetValue("Jikken");
m_dwNoWordButton = pr.GetValue(_T("NoWordButton")); //+++ 単語ボタンを使わない場合1 (単語ボタン有の時にもページボタンを出し続けるなら|2)
m_dwTinyWordButton = pr.GetValue(_T("NumberButton")); //+++ 単語ボタンでなく、数字だけの5ボタンを使うか? (NoWordButton=1の時のみ有効)
pr.Close();
m_dwUsePageButton = (m_dwNoWordButton >> 1) & 1; //+++ 単語ボタン有の時にもページボタンを出し続けるか?
m_dwNoWordButton &= 1;
#endif
DWORD flags = WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS
| CCS_NODIVIDER /*| CCS_NORESIZE */ | CCS_NOPARENTALIGN | CCS_TOP
| TBSTYLE_TOOLTIPS | TBSTYLE_FLAT ;
#if 0 //+++ win9xでは先にこれらを設定してしまうと、後でSetWindowLongしても効かないよう?なので、ここでは設定しない... 関係なかった模様..
#ifndef USE_DIET
if (m_dwNoWordButton == 0 || m_dwTinyWordButton)
#endif
{
flags |= TBSTYLE_LIST | TBSTYLE_TRANSPARENT; //+++ 追加 (検索単語の文字列を表示するには必要)
}
#endif
m_wndToolBar = ::CreateWindowEx(
0,
TOOLBARCLASSNAME,
NULL,
// ATL_SIMPLE_TOOLBAR_PANE_STYLE|CCS_TOP,
flags,
0,
0,
600, //100, 適当な値
50, //100, 適当な値
m_hWnd,
(HMENU) NULL,
_Module.GetModuleInstance(),
NULL );
//+++ どうも古いosでは、CreateWindow時に設定したらまずいらしい?...ので後づけでSetWindowLongする必要がある?... 関係なかった模様.
#ifndef USE_DIET
if (m_dwNoWordButton == 0 || m_dwTinyWordButton)
#endif
{
flags |= (UINT)m_wndToolBar.GetWindowLong(GWL_STYLE);
flags |= TBSTYLE_LIST | TBSTYLE_TRANSPARENT; //+++ 追加 (検索単語の文字列を表示するには必要)
m_wndToolBar.SetWindowLong(GWL_STYLE, flags);
}
m_wndToolBar.SetButtonStructSize( sizeof (TBBUTTON) );
m_wndToolBar.SetImageList(imgs);
m_wndToolBar.SetHotImageList(imgsHot);
m_wndToolBar.SetDisabledImageList(imgsDis); //+++
#ifndef USE_DIET
if (m_dwNoWordButton) {
addDefaultToolBarIcon(0); //+++ 単語ボタン無しモードでの、ボタン設定.
} else
#endif
{
toolBarAddButtons(); //+++ ツールバーにボタンを追加.(単語ボタンアリの場合)
}
m_bShowToolBar = TRUE;
m_bLoadedToolBar = TRUE;
#if 0 //+++ この関数抜けたあとで、調整入るのでここでしちゃだめ
ShowToolBarIcon(true);
#endif
}
void CDonutSearchBar::checkToolBarWords() //+++
{
if (toolBarAddButtons(true)) {
#if 1 //+++ 不要かもだが...テスト的に...
ShowToolBarIcon(m_bShowToolBar/*true*/); //+++ trueだとボタン消してるときに不味い
#endif
}
}
//+++ 検索ワードの文字列を分解して、検索ツールバーに追加
bool CDonutSearchBar::toolBarAddButtons(bool chk)
{
#ifndef USE_DIET
if (m_dwNoWordButton && m_dwTinyWordButton == 0) //単語ボタンを表示しない場合は直帰.
return 0;
#endif
CEdit edit = GetEditCtrl();
CString str = _GetSelectText(edit);
//引用符・ショートカットワードは除外
str = RemoveShortcutWord(str);
if (m_bFiltering)
FilterString(str);
if (chk && m_toolBarAddWordStr == str) {
return ForceSetHilightBtnOn(m_bHilightSw != 0); //+++ ハイライトボタンのon/offは変わっている可能性があるので更新.
}
m_toolBarAddWordStr = str;
std::vector<CString> strs;
strs.reserve(20);
Misc::SeptTextToWords(strs, str);
if (m_wndToolBar.m_hWnd == 0)
return 0;
//+++ 検索ツールバーの中身を一旦すべて削除
unsigned num = m_wndToolBar.GetButtonCount();
for (int i = num; --i >= 0;) {
m_wndToolBar.DeleteButton(i);
}
addDefaultToolBarIcon(strs.size()); //+++ デフォルトのアイコンを追加
#ifndef USE_DIET
if (m_dwNoWordButton == 0) //+++ 数字ボタンの時はワードボタンを登録させない.
#endif
{
toolBarAddWordTbl(strs);
}
return true;
}
//+++ デフォルトのアイコンを追加
int CDonutSearchBar::addDefaultToolBarIcon(unsigned n)
{
int hilightStat = m_bHilightSw ? TBSTATE_PRESSED : TBSTATE_ENABLED;
#ifndef USE_DIET
if (n == 0 || m_dwNoWordButton || m_dwUsePageButton) { //+++ 旧来の検索 (単独のページ内検索ボタンあり)
if (m_dwNoWordButton && m_dwTinyWordButton)
return addDefaultToolBarIcon_tinyWordButton(n);
//static
static const TBBUTTON btns[3] = {
{ 0 , ID_SEARCH_WEB, TBSTATE_ENABLED, TBSTYLE_BUTTON | TBSTYLE_AUTOSIZE , 0, 0 }, // Web
{ 2 , ID_SEARCH_PAGE, TBSTATE_ENABLED, TBSTYLE_BUTTON | TBSTYLE_AUTOSIZE , 0, 0 }, // Page
{ 1 , ID_SEARCHBAR_HILIGHT, hilightStat , TBSTYLE_CHECK | TBSTYLE_AUTOSIZE , 0, 0 }, // Hilight
};
//m_nHilightBtnNo = 2;
#if 0 //+++ 本来はこっちでいい
MTLVERIFY( m_wndToolBar.AddButtons(3, (TBBUTTON *) btns ) );
#else //+++ テスト
for (unsigned i = 0; i < 3; ++i)
MTLVERIFY( m_wndToolBar.AddButton( (TBBUTTON *) &btns[i] ) );
#endif
m_wndToolBar.SetBitmapSize(14,14);
if (m_dwNoWordButton) {
m_cxBtnsBtn = (20) * 3 + 1;
}
return 3;
} else
#endif
{ //+++ 単語専用ボタン有り
//static
static const TBBUTTON btns[2] = {
{ 0 , ID_SEARCH_WEB, TBSTATE_ENABLED, TBSTYLE_BUTTON | TBSTYLE_AUTOSIZE , 0, 0 }, // Web
{ 1 , ID_SEARCHBAR_HILIGHT, hilightStat , TBSTYLE_CHECK | TBSTYLE_AUTOSIZE , 0, 0 }, // Hilight
};
//m_nHilightBtnNo = 1;
#if 0 //+++ 本来はこっちでいい
MTLVERIFY( m_wndToolBar.AddButtons(2, (TBBUTTON *) btns ) );
#else //+++ テスト
for (unsigned i = 0; i < 2; ++i)
MTLVERIFY( m_wndToolBar.AddButton( (TBBUTTON *) &btns[i] ) );
#endif
return 2;
}
}
#ifndef USE_DIET
//+++ 単語ボタンの代わりに1〜5の数字ボタンを設定.
// ※単語ボタンが実装されるまでの実験/代用処理だったもの.
// 単語ボタンを使用しない設定で、かつ、noguiに"NumberButton=1"を設定したときのみ利用可能.
int CDonutSearchBar::addDefaultToolBarIcon_tinyWordButton(unsigned n)
{
if (n > 5)
n = 5;
int hilightStat = m_bHilightSw ? TBSTATE_PRESSED : TBSTATE_ENABLED;
//static
static const TBBUTTON btns[3] = {
{ 0 , ID_SEARCH_WEB, TBSTATE_ENABLED, TBSTYLE_BUTTON | TBSTYLE_AUTOSIZE , 0, 0 }, // Web
{ 2 , ID_SEARCH_PAGE, TBSTATE_ENABLED, TBSTYLE_BUTTON | TBSTYLE_AUTOSIZE , 0, 0 }, // Page
{ 1 , ID_SEARCHBAR_HILIGHT, hilightStat , TBSTYLE_CHECK | TBSTYLE_AUTOSIZE , 0, 0 }, // Hilight
};
//m_nHilightBtnNo = 2;
#if 0 //+++ 本来はこっちでいい
MTLVERIFY( m_wndToolBar.AddButtons(3, (TBBUTTON *) btns ) );
#else //+++ テスト
for (unsigned i = 0; i < 3; ++i)
MTLVERIFY( m_wndToolBar.AddButton( (TBBUTTON *) &btns[i] ) );
#endif
m_cxBtnsBtn = (20) * (3+5) + 1;
enum { STYLE = TBSTYLE_BUTTON | TBSTYLE_AUTOSIZE }; // | TBSTYLE_LIST | TBSTYLE_TRANSPARENT };
for (unsigned i = 0; i < 5; ++i) {
const TBBUTTON btn = { I_IMAGENONE, ID_SEARCHBAR_WORD00+i, (i < n) ? TBSTATE_ENABLED : 0/*TBSTATE_CHECKED*/, STYLE, 0, 0 };
MTLVERIFY( m_wndToolBar.AddButton( (TBBUTTON *)&btn) );
CVersional<TBBUTTONINFO> bi;
bi.cbSize = sizeof(TBBUTTONINFO);
bi.dwMask = TBIF_TEXT /* | TBIF_STYLE*/;
bi.fsStyle |= TBSTYLE_AUTOSIZE /*| TBBS_NOPREFIX*/ ;
TCHAR str[4];
str[0] = _T('1'+i);
str[1] = _T('\0');
bi.pszText = str;
MTLVERIFY( m_wndToolBar.SetButtonInfo(ID_SEARCHBAR_WORD00+i, &bi) );
}
// サイズ調整など
m_wndToolBar.SetMaxTextRows(1);
CRect rcButton;
m_wndToolBar.GetItemRect(3, rcButton);
m_wndToolBar.SetButtonSize(rcButton.Size());
m_wndToolBar.SetButtonSize(rcButton.Size());
m_wndToolBar.Invalidate();
m_wndToolBar.AutoSize();
return 3;
}
#endif
//+++ vectorで渡された複数の文字列(20個まで)を検索ツールバーに登録.
void CDonutSearchBar::toolBarAddWordTbl(std::vector<CString>& tbl)
{
CVersional<TBBUTTONINFO> bi;
bi.cbSize = sizeof(TBBUTTONINFO);
bi.dwMask = TBIF_TEXT/* | TBIF_STYLE*/;
bi.fsStyle |= TBSTYLE_AUTOSIZE | TBSTYLE_NOPREFIX;
unsigned n = unsigned(tbl.size());
if (n > 20)
n = 20;
for (unsigned i = 0; i < n; ++i) {
enum { STYLE = TBSTYLE_BUTTON | TBSTYLE_AUTOSIZE | TBSTYLE_NOPREFIX }; // | TBSTYLE_LIST | TBSTYLE_TRANSPARENT };
TBBUTTON btn = { 2/*I_IMAGENONE*/, ID_SEARCHBAR_WORD00+i, TBSTATE_ENABLED, STYLE, 0, 0 };
MTLVERIFY( m_wndToolBar.AddButton( (TBBUTTON *)&btn) );
bi.pszText = (LPTSTR) LPCTSTR(tbl[i]);
MTLVERIFY( m_wndToolBar.SetButtonInfo(ID_SEARCHBAR_WORD00+i, &bi) );
//m_wndToolBar.AutoSize();
//CRect rcButton;
//m_wndToolBar.GetItemRect(TOP+i, rcButton);
//m_wndToolBar.SetButtonSize(rcButton.Size());
}
m_wndToolBar.AutoSize();
m_wndToolBar.Invalidate();
//ShowToolBarIcon(true);
}
CString CDonutSearchBar::GetSkinSeachBarPath(int mode/*BOOL bHot*/)
{
ATLASSERT(mode >= 0 && mode <= 2);
static const TCHAR* tbl[] = {
_T("SearchBar.bmp"),
_T("SearchBarHot.bmp"),
_T("SearchBarDis.bmp"),
};
return _GetSkinDir() + tbl[ mode ];
}
LRESULT CDonutSearchBar::OnInitDialog(HWND hWnd, LPARAM lParam)
{
CRect rcDlg;
GetWindowRect(&rcDlg);
SetWindowPos(NULL, 0, 0, 0, m_nDefDlgH , 0);
CIniFileI pr( g_szIniFileName, _T("SEARCH") );
m_nKeywordWidth = pr.GetValue( _T("KeywordWidth" ), 150 );
m_nEngineWidth = pr.GetValue( _T("EngWidth" ), 150 );
DWORD dwUseShortCut = pr.GetValue( _T("UseShortcut" ), 0 );
pr.Close();
if (dwUseShortCut)
m_bUseShortcut = TRUE;
//コンボボックス初期化
m_cmbKeyword.FlatComboBox_Install( GetDlgItem(IDC_CMB_KEYWORD) );
m_cmbEngine.FlatComboBox_Install ( GetDlgItem(IDC_CMB_ENGIN ) );
m_cmbEngine.SetDroppedWidth(150);
_InitCombo();
if (m_nKeywordWidth != 0) {
CRect rcKeyword;
m_cmbKeyword.GetWindowRect(&rcKeyword);
int h = rcKeyword.Height();
rcKeyword.left = 0;
rcKeyword.right = m_nKeywordWidth;
rcKeyword.top = 0;
rcKeyword.bottom = h;
m_cmbKeyword.SetWindowPos(NULL, rcKeyword, SWP_NOZORDER | SWP_NOSENDCHANGING);
}
if (m_nEngineWidth != 0) {
CRect rcEngine;
m_cmbEngine.GetWindowRect(&rcEngine);
int h = rcEngine.Height();
rcEngine.left = 0;
rcEngine.right = m_nEngineWidth;
rcEngine.top = 0;
rcEngine.bottom = h;
m_cmbEngine.SetWindowPos(NULL, rcEngine, SWP_NOZORDER | SWP_NOSENDCHANGING);
}
m_wndKeyword.SubclassWindow( m_cmbKeyword.GetDlgItem(IDC_EDIT/*1001*/) );
m_wndEngine.SubclassWindow(m_cmbEngine.m_hWnd);
m_wndKeywordCombo.SubclassWindow(m_cmbKeyword.m_hWnd); //minit
//ツールバー初期化
DWORD dwShowToolBar = STB_SHOWTOOLBARICON;
{
CIniFileI pr( g_szIniFileName, _T("SEARCH") );
pr.QueryValue( dwShowToolBar, _T("Show_ToolBarIcon") );
}
m_bShowToolBar = (dwShowToolBar & STB_SHOWTOOLBARICON) == STB_SHOWTOOLBARICON;
#if 1 //+++ 無理やり全部初期化(メモリーの無駄だが安全&見栄え優先)
BOOL bShowToolBar = m_bShowToolBar;
InitToolBar(/*+++ IDB_SEARCHBUTTON, IDB_SEARCHBUTTON_HOT,*/ m_nBmpCX, m_nBmpCY, RGB(255, 0, 255) );
ShowToolBarIcon(bShowToolBar);
#else //+++ 元の処理。表示しなけりゃメモリー等お得。だが、途中で設定した場合font反映なし.
if (m_bShowToolBar) {
InitToolBar(/*+++ IDB_SEARCHBUTTON, IDB_SEARCHBUTTON_HOT,*/ m_nBmpCX, m_nBmpCY, RGB(255, 0, 255) );
}
#endif
//ドラッグドロップ初期化
RegisterDragDrop();
//スレッドを利用してコンボボックスにデータを登録(INIからの読み込みに時間がかかるため)
// Thread Create
m_ThreadParams.m_hExitEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL);
m_ThreadParams.m_pSearchBar = this;
DWORD wThreadId = 0;
m_hThread = (HANDLE)_beginthreadex(NULL, 0, _SearchThread, (LPVOID)&m_ThreadParams, 0, (UINT*)&wThreadId);
::SetThreadPriority(m_hThread , THREAD_PRIORITY_IDLE);
// SetCmbKeywordEmptyStr(); //+++ どうせまだエンジン名が登録されていないので、このタイミングはなし
return S_OK;
}
//スレッドを利用してコンボボックスにデータを登録(INIからの読み込みに時間がかかるため)
UINT WINAPI CDonutSearchBar::_SearchThread(void* lpParam)
{
_ThreadParam *pParam = (_ThreadParam *) lpParam;
_InitialEngine ( (LPVOID) pParam->m_pSearchBar->m_cmbEngine.m_hWnd );
_InitialKeyword( (LPVOID) pParam->m_pSearchBar->m_cmbKeyword.m_hWnd );
_endthreadex(0);
return 0;
}
bool CDonutSearchBar::IsAliveSearchThread() const
{
DWORD dwReturnCode = 0;
::GetExitCodeThread(m_hThread, &dwReturnCode);
return (dwReturnCode == STILL_ACTIVE);
}
//private:
void CDonutSearchBar::OnDestroy()
{
// Thread Remove
::SetEvent(m_ThreadParams.m_hExitEvent);
DWORD dwResult = ::WaitForSingleObject(m_hThread, DONUT_THREADWAIT);
::CloseHandle(m_ThreadParams.m_hExitEvent);
::CloseHandle(m_hThread);
#if 0
CRect rcKeyword;
m_wndKeyword.GetWindowRect(rcKeyword);
DWORD keywordW = rcKeyword.Width();
CRect rcEngine;
m_wndEngine.GetWindowRect(rcEngine);
DWORD enginW = rcEngine.Width();
#else
#ifndef USE_DIET
if (m_dwNoWordButton) { //+++ 旧処理のときの辻褄あわせ
CRect rcEngine;
m_wndEngine.GetWindowRect(rcEngine);
m_nEngineWidth = rcEngine.Width();
}
#endif
#endif
{
CIniFileIO pr( g_szIniFileName, _T("SEARCH") );
pr.SetValue( (DWORD) m_nKeywordWidth, _T("KeywordWidth") );
pr.SetValue( (DWORD) m_nEngineWidth , _T("EngWidth") );
DWORD dwShowToolBar = m_bShowToolBar ? STB_SHOWTOOLBARICON : 0;
pr.SetValue( dwShowToolBar, _T("Show_ToolBarIcon") );
DWORD dwStatus = 0;
pr.QueryValue( dwStatus, _T("Status") );
if (dwStatus & STS_LASTSEL)
pr.SetValue( m_cmbEngine.GetCurSel(), _T("SelIndex") );
}
m_wndKeyword.UnsubclassWindow();
m_wndEngine.UnsubclassWindow();
m_wndKeywordCombo.UnsubclassWindow();
RevokeDragDrop();
SaveHistory();
}
void CDonutSearchBar::OnEngineKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
if (nChar == VK_RETURN) {
_OnEnterKeyDown(ENTER_KEYDOWN_RETURN);
SetMsgHandled(TRUE);
} else if (nChar == VK_TAB) {
m_cmbKeyword.SetFocus();
SetMsgHandled(TRUE);
} else {
SetMsgHandled(FALSE);
}
}
void CDonutSearchBar::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
{
if (nChar == VK_RETURN) {
SetMsgHandled(TRUE);
} else {
SetMsgHandled(FALSE);
}
//checkToolBarWords(); //+++
}
LRESULT CDonutSearchBar::OnCtlColorListBox(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL &bHandled)
{
bHandled = FALSE;
m_hWndKeywordList = (HWND) lParam;
return 0;
}
void CDonutSearchBar::OnKeywordKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
// if not dropped, eat VK_DOWN
if ( !m_cmbKeyword.GetDroppedState() && (nChar == VK_DOWN || nChar == VK_UP) ) {
int nIndexEngine = m_cmbEngine.GetCurSel();
int nIndexKeyword = m_cmbKeyword.GetCurSel();
SetMsgHandled(TRUE);
if (nChar == VK_UP) {
if (::GetKeyState(VK_CONTROL) < 0) {
if (0 > nIndexEngine - 1)
m_cmbEngine.SetCurSel(m_cmbEngine.GetCount() - 1);
else
m_cmbEngine.SetCurSel(nIndexEngine - 1);
//SetCmbKeywordEmptyStr(); //+++
} else {
if (0 > nIndexKeyword - 1)
m_cmbKeyword.SetCurSel(m_cmbKeyword.GetCount() - 1);
else
m_cmbKeyword.SetCurSel(nIndexKeyword - 1);
}
} else if (nChar == VK_DOWN) {
if (::GetKeyState(VK_CONTROL) < 0) {
int nIndex = m_cmbEngine.GetCurSel();
if (m_cmbEngine.GetCount() > nIndexEngine + 1)
m_cmbEngine.SetCurSel(nIndexEngine + 1);
else
m_cmbEngine.SetCurSel(0);
//SetCmbKeywordEmptyStr(); //+++
} else {
if (m_cmbKeyword.GetCount() > nIndexKeyword + 1)
m_cmbKeyword.SetCurSel(nIndexKeyword + 1);
else
m_cmbKeyword.SetCurSel(0);
}
}
} else {
if (nChar == VK_RETURN) {
_OnEnterKeyDown(ENTER_KEYDOWN_RETURN);
SetMsgHandled(TRUE);
} else if (nChar == VK_DELETE) {
if ( m_cmbKeyword.GetDroppedState() ) {
if ( DeleteKeywordHistory() )
SetMsgHandled(TRUE);
} else
SetMsgHandled(FALSE);
} else if (nChar == VK_TAB) {
m_cmbEngine.SetFocus();
SetMsgHandled(TRUE);
} else {
SetMsgHandled(FALSE);
}
}
//SetCmbKeywordEmptyStr(); //+++ PreTranseで毎度チェックするからここは無しに.
}
LRESULT CDonutSearchBar::OnKeywordCbnDropDown(LPNMHDR pnmh)
{
if (m_cmbKeyword.GetCount() == 0)
::MessageBox(NULL, _T(""), _T(""), MB_OK);
return FALSE;
}
BOOL CDonutSearchBar::DeleteKeywordHistory()
{
if ( !::IsWindow(m_hWndKeywordList) )
return FALSE;
CListBox List = m_hWndKeywordList;
int nIndex = List.GetCurSel();
if (nIndex == LB_ERR)
return FALSE;
m_cmbKeyword.DeleteString(nIndex);
return TRUE;
}
struct CDonutSearchBar::_Function_MakeSearchFileListMenu {
CMenuHandle menu;
int nIndex;
_Function_MakeSearchFileListMenu()
{
menu.CreatePopupMenu();
menu.AppendMenu( 0, 1, _T("拡張プロパティ") );
menu.AppendMenu(MF_SEPARATOR);
nIndex = 1;
}
void operator ()(CString strFile)
{
ATLTRACE(_T("%s\n"), strFile);
nIndex++;
menu.AppendMenu( 0, nIndex, MtlGetFileName(strFile) );
}
};
void CDonutSearchBar::OnEngineRButtonUp(UINT nFlags, CPoint point)
{
_Function_MakeSearchFileListMenu __f;
MtlForEachFileSortEx( Misc::GetExeDirectory() + _T("Search\\"), __f, _T("*.ini") );
CPoint pos;
//GetCursorPos(&pos);
ATLTRACE("mouseposition1 : left=%4d top=%4d", point.x, point.y);
::ClientToScreen(m_cmbEngine.m_hWnd, &point);
ATLTRACE("mouseposition2 : left=%4d top=%4d", point.x, point.y);
CMenu menu(__f.menu.m_hMenu);
int nRet = menu.TrackPopupMenu( TPM_LEFTALIGN | TPM_TOPALIGN | TPM_LEFTBUTTON | TPM_RIGHTBUTTON | TPM_NONOTIFY | TPM_RETURNCMD,
point.x,
point.y,
m_cmbEngine.m_hWnd);
if (nRet == 0)
return;
if (nRet == 1) {
if (!m_cmbEngine.IsWindow() || m_cmbEngine.GetCurSel() == CB_ERR)
return;
CString strText;
MtlGetLBTextFixed(m_cmbEngine, m_cmbEngine.GetCurSel(), strText);
CExPropertyDialog dlg(GetSearchIniPath(), strText, 0);
dlg.SetTitle(strText);
dlg.DoModal();
return;
}
CString strTitle;
menu.GetMenuString(nRet, strTitle, MF_BYCOMMAND);
CString strPath = Misc::GetExeDirectory() + _T("Search\\") + strTitle;
{
CIniFileO pr( g_szIniFileName, _T("Search") );
pr.SetStringUW( strPath, _T("Path") );
}
RefreshEngine();
}
void CDonutSearchBar::OnEngineSetFocus(HWND hWndBefore)
{
SetMsgHandled(FALSE);
::WINNLSEnableIME(m_cmbEngine, FALSE);
SetCmbKeywordEmptyStr(); //+++
}
void CDonutSearchBar::OnEngineKillFocus(HWND hWndNew)
{
SetMsgHandled(FALSE);
::WINNLSEnableIME(m_cmbEngine, TRUE);
SetCmbKeywordEmptyStr(); //+++
}
void CDonutSearchBar::OnMouseMove(UINT nFlags, const CPoint& pt)
{
#ifndef USE_DIET
if (m_dwNoWordButton) {
//+++ 単語ボタン無しの場合は旧処理.
CRect rcKeyword;
m_cmbKeyword.GetWindowRect(&rcKeyword);
ScreenToClient(&rcKeyword);
if ( abs(rcKeyword.right - pt.x) > 5 && ::GetCapture() != m_hWnd )
return;
if (m_hCursor == NULL)
m_hCursor = ::LoadCursor(NULL, IDC_SIZEWE);
::SetCursor(m_hCursor);
if ( (nFlags & MK_LBUTTON) ) {
UpdateLayout(pt);
}
} else
#endif
{ //+++ 単語ボタンありの場合
CRect rcKeyword;
m_cmbKeyword.GetWindowRect(&rcKeyword);
ScreenToClient(&rcKeyword);
if ((abs(rcKeyword.right - pt.x) <= 5 || (m_has == 1 && ::GetCapture() == m_hWnd))
&& (rcKeyword.top <= pt.y && pt.y < rcKeyword.bottom)
) {
m_has = 1;
if (m_hCursor == NULL)
m_hCursor = ::LoadCursor(NULL, IDC_SIZEWE);
::SetCursor(m_hCursor);
if ( (nFlags & MK_LBUTTON) ) {
UpdateLayout(pt);
}
return;
}
CRect rcEngine;
m_cmbEngine.GetWindowRect(&rcEngine);
ScreenToClient(&rcEngine);
if ( (abs(rcEngine.right - pt.x) <= 5 || (m_has == 2 && ::GetCapture() == m_hWnd))
&& (rcEngine.top <= pt.y && pt.y < rcEngine.bottom)
) {
m_has = 2;
if (m_hCursor == NULL)
m_hCursor = ::LoadCursor(NULL, IDC_SIZEWE);
::SetCursor(m_hCursor);
if ( (nFlags & MK_LBUTTON) ) {
UpdateLayout2(pt);
}
return;
}
m_has = 0;
return;
}
}
#if 0
///+++ エンジン選択の改造実験... 失敗on_.
void CDonutSearchBar::OnSelDblClkForEngine(UINT code, int id, HWND hWnd)
{
int nTarCate = m_cmbEngine.GetCurSel();
if (nTarCate == -1)
return;
TCHAR buf[4096];
m_cmbEngine.GetLBText(nTarCate, buf);
CString strSearchEng = buf;
BOOL bFirst = TRUE;
int nLoopCtn = 0;
CString str;
int nIndexCmb = m_cmbKeyword.GetCurSel();
if (nIndexCmb == -1)
str = MtlGetWindowText(m_cmbKeyword);
else
MtlGetLBTextFixed(m_cmbKeyword.m_hWnd, nIndexCmb, str);
if ( !str.IsEmpty() )
OpenSearch(str, strSearchEng, nLoopCtn, bFirst);
return;
}
#endif
///+++ エンジン選択の改造実験... 失敗on_...だけど、ちょっとだけ有用.
void CDonutSearchBar::OnSelChangeForEngine(UINT code, int id, HWND hWnd)
{
if (::GetKeyState(VK_RBUTTON) < 0) {
CString strText;
MtlGetLBTextFixed(m_cmbEngine, m_cmbEngine.GetCurSel(), strText);
CExPropertyDialog dlg(GetSearchIniPath(), strText, 0);
dlg.SetTitle(strText);
dlg.DoModal();
SetCmbKeywordEmptyStr(); //+++
return;
}
CIniFileI pr( g_szIniFileName, _T("SEARCH") );
DWORD dwStatus = pr.GetValue( _T("Status"), 0 );
pr.Close();
DWORD bSts = 0;
if (id == IDC_CMB_ENGIN) bSts = dwStatus & STS_ENG_CHANGE_GO;
if (::GetKeyState(VK_SHIFT) < 0) bSts = !bSts;
if (bSts) {
//+++ エンジンが切り替わった場合は、検索窓が空でもurl検索の場合があるので、こちら
//x _OnEnterKeyDown(ENTER_KEYDOWN_SELCHANGE);
SearchWeb();
}
}
void CDonutSearchBar::OnSelChange(UINT code, int id, HWND hWnd)
{
DWORD dwStatus = 0;
{
CIniFileI pr( g_szIniFileName, _T("SEARCH") );
pr.QueryValue( dwStatus, _T("Status") );
}
DWORD bSts = 0;
//x if (id == IDC_CMB_ENGIN) bSts = dwStatus & STS_ENG_CHANGE_GO; else //+++ エンジンは別関数に.
if (id == IDC_CMB_KEYWORD) bSts = dwStatus & STS_KEY_CHANGE_GO;
if (::GetKeyState(VK_SHIFT) < 0) bSts = !bSts;
if (bSts) {
_OnEnterKeyDown(ENTER_KEYDOWN_SELCHANGE);
}
}
void CDonutSearchBar::OnLButtonDown(UINT nFlags, const CPoint& pt)
{
#ifndef USE_DIET
if (m_dwNoWordButton) {
//+++ 単語ボタンなしの場合は旧処理
CRect rcKeyword;
m_cmbKeyword.GetWindowRect(&rcKeyword);
ScreenToClient(&rcKeyword);
if (abs(rcKeyword.right - pt.x) > 5)
return;
SetCapture();
::SetCursor(m_hCursor);
m_ptDragStart = pt;
m_ptDragHist = pt;
} else
#endif
{ //+++ 単語ボタンありの場合
CRect rcKeyword;
m_cmbKeyword.GetWindowRect(&rcKeyword);
ScreenToClient(&rcKeyword);
if (abs(rcKeyword.right - pt.x) <= 5) {
m_has = 1;
SetCapture();
::SetCursor(m_hCursor);
m_ptDragStart = pt;
m_ptDragHist = pt;
return;
}
CRect rcEngine;
m_cmbEngine.GetWindowRect(&rcEngine);
ScreenToClient(&rcEngine);
if (abs(rcEngine.right - pt.x) <= 5) {
m_has = 2;
SetCapture();
::SetCursor(m_hCursor);
m_ptDragStart = pt;
m_ptDragHist = pt;
return;
}
m_has = 0;
}
}
void CDonutSearchBar::OnLButtonUp(UINT nFlags, const CPoint& pt)
{
if (::GetCapture() != m_hWnd)
return;
::ReleaseCapture();
#ifndef USE_DIET
if (m_dwNoWordButton) { //+++ 単語ボタンなしのとき
UpdateLayout(pt);
} else
#endif
{ //+++ 単語ボタンありの場合
if (m_has == 1)
UpdateLayout(pt);
else if (m_has == 2)
UpdateLayout2(pt);
}
}
void CDonutSearchBar::UpdateLayout(const CPoint& pt)
{
#ifndef USE_DIET
if (m_dwNoWordButton) { // 単語ボタン無しの場合
int btnW = btnWidth(); //+++
int nMoveX = m_ptDragStart.x - pt.x;
CRect rcKeyword;
m_cmbKeyword.GetWindowRect(&rcKeyword);
ScreenToClient(&rcKeyword);
rcKeyword.right -= nMoveX;
#if 1 //+++
if (rcKeyword.right < rcKeyword.left+btnW) {
nMoveX = rcKeyword.right - rcKeyword.left+btnW;
rcKeyword.right = rcKeyword.left + btnW;
}
#endif
CRect rcEngine;
m_cmbEngine.GetWindowRect(&rcEngine);
ScreenToClient(&rcEngine);
rcEngine.left -= nMoveX;
#if 1 //+++
if (rcEngine.left > rcEngine.right - btnW) {
rcEngine.left = rcEngine.right - btnW;
rcKeyword.right = rcEngine.left-2;
}
m_nEngineWidth = rcEngine.right - rcEngine.left;
#endif
if (rcEngine.left >= rcEngine.right)
return;
if (rcKeyword.left >= rcKeyword.right)
return;
m_cmbKeyword.SetWindowPos(NULL, rcKeyword, SWP_NOZORDER);
m_cmbEngine.SetWindowPos(NULL, rcEngine, SWP_NOZORDER);
m_ptDragStart = pt;
UpdateWindow();
} else
#endif
{
//+++ 単語ボタンありの場合
ResizeBar(pt.x - m_ptDragStart.x, 0);
m_ptDragStart = pt;
UpdateWindow();
}
}
void CDonutSearchBar::UpdateLayout2(const CPoint& pt)
{
ResizeBar(0, pt.x - m_ptDragStart.x);
m_ptDragStart = pt;
UpdateWindow();
}
//public: //+++ あとでprivateに戻すがとりあえずテスト.
void CDonutSearchBar::_AddToSearchBoxUnique(const CString &strURL)
{
// search the same string
int nCount = m_cmbKeyword.GetCount();
for (int n = 0; n < nCount; ++n) {
CString str;
MtlGetLBTextFixed(m_cmbKeyword, n, str);
if (strURL == str) {
m_cmbKeyword.DeleteString(n);
break;
}
}
m_cmbKeyword.InsertString(0, strURL);
m_cmbKeyword.SetCurSel(0);
}
//private:
void CDonutSearchBar::_OnEnterKeyDown(int flag)
{
CString str;
int nIndexCmb = m_cmbKeyword.GetCurSel();
if (nIndexCmb == -1)
str = MtlGetWindowText(m_cmbKeyword);
else
MtlGetLBTextFixed(m_cmbKeyword.m_hWnd, nIndexCmb, str);
// m_cmbKeyword.GetLBText(nIndexCmb, str);
GetHilightBtnFlag(); //+++ ハイライトボタンの状態チェック
checkToolBarWords(); //+++
if ( !str.IsEmpty() ) {
SHORT sShift = ::GetKeyState(VK_SHIFT);
SHORT sCtrl = ::GetKeyState(VK_CONTROL);
if (sShift >= 0 && sCtrl >= 0) {
_OnCommand_SearchWeb(str);
} else {
#if 1 //+++ カーソル位置の単語だけを選択するようにしてみる.
str = _GetSelectText_OnCursor( GetEditCtrl() );
#else
str = _GetSelectText( GetEditCtrl() );
#endif
if (sCtrl < 0)
SendMessage(GetTopLevelParent(), WM_USER_FIND_KEYWORD, (WPARAM) str.GetBuffer(0), TRUE );
else if (sShift < 0)
SendMessage(GetTopLevelParent(), WM_USER_FIND_KEYWORD, (WPARAM) str.GetBuffer(0), FALSE);
}
} else {
m_cmbEngine.ShowDropDown(FALSE); //minit
}
}
LRESULT CDonutSearchBar::OnCtlColor(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL &bHandled)
{
bHandled = FALSE;
if (g_bNoReposition == true)
return 0;
CRect rcDesktop;
::GetWindowRect(::GetDesktopWindow(), &rcDesktop);
CRect rcWnd;
::GetWindowRect( (HWND) lParam, &rcWnd );
if (rcDesktop.right <= rcWnd.right) {
int nDiff = rcWnd.right - rcDesktop.right;
rcWnd.left -= nDiff;
rcWnd.right -= nDiff;
::SetWindowPos( (HWND) lParam, NULL, rcWnd.left, rcWnd.top, 0, 0, SWP_NOSIZE );
}
return 0;
}
#if 0
void CDonutSearchBar::OnItemSelected(const CString& str, const CString& strSearchEng)
{
int nTarCate = m_cmbEngine.GetCurSel();
if (nTarCate == -1)
return;
//x CString strSearchEng = MtlGetWindowText(m_cmbEngine);
BOOL bFirst = TRUE;
int nLoopCtn = 0;
OpenSearch(str, strSearchEng, nLoopCtn, bFirst);
}
#endif
//public:
CString CDonutSearchBar::GetSearchIniPath()
{
CIniFileI pr( g_szIniFileName, _T("Search") );
CString strPath = pr.GetStringUW(_T("Path"));
pr.Close();
if ( strPath.IsEmpty() ) {
strPath = _GetFilePath( _T("Search\\Search.ini") );
if (::GetFileAttributes(strPath) == 0xFFFFFFFF)
strPath = _GetFilePath( _T("Search.ini") ); //以前の仕様でGo
}
return strPath;
}
//public:
//+++ ".url"中に記述した拡張情報での検索に対応するため、修正.
void CDonutSearchBar::OpenSearch(CString strWord, CString strSearchEng, int &nLoopCnt, BOOL &bFirst)
{
if (m_bUseShortcut)
ShortcutSearch(strWord, strSearchEng);
if ( strSearchEng.IsEmpty() ) {
m_cmbEngine.GetLBText(0, strSearchEng);
if (strSearchEng.IsEmpty())
return;
}
CString strSearchPath = GetSearchIniPath();
#if 1 //+++ search.iniがない場合は、Googleで適当にサーチする.
if (Misc::IsExistFile(strSearchPath) == 0 && strSearchEng == ENGINENAME_FOR_NO_SEARCH_INI) {
if (m_bFiltering)
FilterString(strWord); //全角スペースの置換
EncodeString(strWord, ENCODE_UTF8);
DonutOpenFile(m_hWnd, _T("http://www.google.co.jp/search?num=100&q=") + strWord, 0);
return;
}
#endif
DWORD dwStatus;
{
CIniFileI pr( g_szIniFileName, _T("Search") );
dwStatus = pr.GetValue( _T("Status"), 0 );
m_bActiveWindow = (dwStatus & STS_ACTIVEWINDOW) != 0;
}
CIniFileI pr(strSearchPath, strSearchEng);
if (pr.GetValue(_T("Group"), 0 ) != 0) {
pr.Close();
OpenSearchGroup(strWord, strSearchEng, nLoopCnt, bFirst);
} else {
CString strOpenURL;
if (GetOpenURLstr(strOpenURL, strWord, pr, CString()) == false)
return;
pr.Close();
DWORD dwOpenFlags = 0;
if (bFirst) {
dwOpenFlags |= D_OPENFILE_ACTIVATE;
bFirst = FALSE;
}
if (m_bActiveWindow) {
dwOpenFlags |= D_OPENFILE_NOCREATE;
}
//DonutOpenFile(m_hWnd, strOpenURL, dwOpenFlags);
_EXPROP_ARGS args;
args.strUrl = strOpenURL;
args.dwOpenFlag = dwOpenFlags;
args.strIniFile = strSearchPath;
args.strSection = strSearchEng;
#if 1 //+++
args.strSearchWord = RemoveShortcutWord( GetSearchStr() );
#else
args.strSearchWord = RemoveShortcutWord( MtlGetWindowText( GetEditCtrl() ) );
#endif
::SendMessage(GetTopLevelParent(), WM_OPEN_WITHEXPROP, (WPARAM) &args, 0);
}
}
bool CDonutSearchBar::GetOpenURLstr(CString& strOpenURL, const CString& strWord0, CIniFileI& pr, const CString& frontURL0)
{
//検索URLの読み込み
CString strFrontURL = pr.GetString( _T("FrontURL") );
if ( strFrontURL.IsEmpty() ) {
if (frontURL0.IsEmpty())
return false;
strFrontURL = frontURL0;
}
CString strBackURL = pr.GetString( _T("BackURL") );
//検索付加キーワードの読み込み
CString strFrontKeyWord = pr.GetString( _T("FrontKeyWord") );
CString strBackKeyWord = pr.GetString( _T("BackKeyWord") );
//検索語の作成
CString strWord = strFrontKeyWord + strWord0 + strBackKeyWord;
if (m_bFiltering)
FilterString(strWord); //全角スペースの置換
DWORD dwEncode = pr.GetValue(_T("Encode"), 0); //エンコード
pr.Close();
if (dwEncode != 0)
EncodeString(strWord, dwEncode);
strOpenURL.Format(_T("%s%s%s"), strFrontURL, strWord, strBackURL);
return true;
}
//private:
void CDonutSearchBar::OpenSearchGroup(const CString& strWord, const CString& strSearchEng, int &nLoopCnt, BOOL &bFirst)
{
nLoopCnt++;
if (nLoopCnt > 10)
return;
CString strSearchPath = GetSearchIniPath();
CIniFileI pr(strSearchPath, strSearchEng);
DWORD dwListCnt = pr.GetValue( _T("ListCount"), 0 );
for (int ii = 1; ii <= (int) dwListCnt; ii++) {
CString strKey;
strKey.Format(_T("%02d"), ii);
CString strSearchEng2 = pr.GetStringUW( strKey );
if ( strSearchEng2.IsEmpty() )
continue;
OpenSearch(strWord, strSearchEng2, nLoopCnt, bFirst);
}
}
void CDonutSearchBar::EncodeString(CString &str, int dwEncode) //minit
{
#if 1 //+++ Unicode対応で作り直し
if (dwEncode == ENCODE_SHIFT_JIS)
str = Misc::urlstr_encode( Misc::tcs_to_sjis(str) );
else if (dwEncode == ENCODE_EUC)
str = Misc::urlstr_encode( Misc::tcs_to_eucjp(str) );
else if (dwEncode == ENCODE_UTF8)
str = Misc::urlstr_encode( Misc::tcs_to_utf8(str) );
else
return;
#else
CURLEncoder enc;
if (dwEncode == 0)
return;
else if (dwEncode == ENCODE_SHIFT_JIS)
enc.URLEncode_SJIS(str);
else if (dwEncode == ENCODE_EUC)
enc.URLEncode_EUC(str);
else if (dwEncode == ENCODE_UTF8)
enc.URLEncode_UTF8(str);
else
return;
//ATLASSERT(FALSE);
#endif
}
void CDonutSearchBar::ShortcutSearch(CString &strWord, CString &strSearchEng)
{
CString strSearchPath = GetSearchIniPath();
if ( strWord.Left(1) == _T("\\") ) {
DWORD dwListCount = 0;
int nFind = strWord.Find(_T(" "));
CString strShort = strWord.Mid(1, nFind - 1);
{
CIniFileI pr( strSearchPath, _T("Search-List") );
pr.QueryValue( dwListCount, _T("ListCount") );
//x pr.Close();
}
if ( strShort.IsEmpty() )
return;
strWord = strWord.Mid(nFind + 1);
CString strBuf;
CString strKey;
int nListCount = dwListCount;
for (int i = 1; i <= nListCount; i++) {
//エンジン名を取得
strKey.Format(_T("%02d"), i);
CIniFileI pr( strSearchPath, _T("Search-List") );
CString strEngine = pr.GetStringUW( strKey );
pr.Close();
//ショートカットコードを取得
CString strShortcutWord = GetShortcutWord(strEngine);
//比較
if (strShort == strShortcutWord) {
strSearchEng = strEngine;
return;
}
}
}
}
CString CDonutSearchBar::GetShortcutWord(const CString& strSearchEng)
{
CIniFileI pr(GetSearchIniPath(), strSearchEng);
return pr.GetString( _T("ShortCutCode") );
}
void CDonutSearchBar::_InitialEngine(LPVOID lpV)
{
CComboBox cmb( (HWND) lpV );
cmb.ResetContent(); //minit
//::WINNLSEnableIME(cmb,FALSE);
CString strSearchPath = GetSearchIniPath();
DWORD dwListCnt = 0;
if (Misc::IsExistFile(strSearchPath)) {
CIniFileI pr( strSearchPath, _T("Search-List") );
dwListCnt = pr.GetValue( _T("ListCount"), 0 );
CString strKey;
for (int ii = 1; ii <= (int) dwListCnt; ii++) {
strKey.Format(_T("%02d"), ii);
CString strTitle = pr.GetStringUW( strKey );
if ( strTitle.IsEmpty() )
continue;
cmb.AddString(strTitle);
}
pr.Close();
} else {
cmb.AddString(ENGINENAME_FOR_NO_SEARCH_INI);
}
DWORD dwStatus = 0, dwIndex = 0;
{
CIniFileI pr( g_szIniFileName, _T("SEARCH") );
pr.QueryValue( dwStatus, _T("Status") );
pr.QueryValue( dwIndex , _T("SelIndex") );
}
int nSelIndex = 0;
if ((dwStatus & STS_LASTSEL) && dwIndex < dwListCnt) {
nSelIndex = dwIndex;
}
cmb.SetCurSel(nSelIndex);
}
void CDonutSearchBar::_InitialKeyword(LPVOID lpV)
{
CComboBox cmb( (HWND) lpV );
{
DWORD dwStatus = 0;
CIniFileI pr( g_szIniFileName, _T("SEARCH") );
pr.QueryValue( dwStatus, _T("Status") );
//x pr.Close();
if (dwStatus & STS_NO_REPOSITION)
g_bNoReposition = true;
if ( (dwStatus & STS_HISTORY_SAVE) != STS_HISTORY_SAVE )
return;
}
DWORD dwHistoryCnt = 0;
CIniFileI pr( _GetFilePath( _T("WordHistory.ini") ), _T("SEARCH_HISTORY") );
pr.QueryValue( dwHistoryCnt, _T("HistorySaveCnt") );
for (int ii = 0; ii < (int) dwHistoryCnt; ii++) {
CString strKey;
strKey.Format(_T("KEYWORD%d"), ii);
CString strKeyWord = pr.GetStringUW( strKey );
if ( strKeyWord.IsEmpty() )
continue;
cmb.AddString(strKeyWord);
}
}
// public:
BYTE CDonutSearchBar::PreTranslateMessage(MSG *pMsg)
{
#if 1 //+++ 手抜きな、描画更新チェック
SetCmbKeywordEmptyStr(); //+++ キーワード窓にエンジン名を表示するためのフォーカスチェック
#endif
UINT msg = pMsg->message;
int vKey = (int) pMsg->wParam;
if (msg == WM_SYSKEYDOWN || msg == WM_SYSKEYUP || msg == WM_KEYDOWN) {
if ( !IsWindowVisible() || !IsChild(pMsg->hwnd) ) // ignore
return _MTL_TRANSLATE_PASS;
// left or right pressed, check shift and control key.
if ( vKey == VK_UP || vKey == VK_DOWN || vKey == VK_LEFT || vKey == VK_RIGHT
|| vKey == VK_HOME || vKey == VK_END
|| vKey == (0x41 + 'C' - 'A')
|| vKey == (0x41 + 'V' - 'A')
|| vKey == (0x41 + 'X' - 'A')
|| vKey == VK_INSERT)
{
if (::GetKeyState(VK_SHIFT) < 0 || ::GetKeyState(VK_CONTROL) < 0)
return _MTL_TRANSLATE_WANT; // pass to edit control
}
// return key have to be passed
if (vKey == VK_RETURN) {
return _MTL_TRANSLATE_WANT;
}
// other key have to be passed
if (VK_LBUTTON <= vKey && vKey <= VK_HELP) {
BOOL bAlt = HIWORD(pMsg->lParam) & KF_ALTDOWN;
if (!bAlt && ::GetKeyState(VK_SHIFT) >= 0 && ::GetKeyState(VK_CONTROL) >= 0) // not pressed
return _MTL_TRANSLATE_WANT; // pass to edit control
}
}
#if 1 //+++ とりあえず、むりやり、右クリックがWEB検索ボタンの範囲内で押された場合、検索エンジンメニューを出す
else if (msg == WM_RBUTTONUP) {
CRect rect;
if (m_wndToolBar.GetRect(ID_SEARCH_WEB, rect)) {
m_wndToolBar.ClientToScreen( rect );
POINT pt;
::GetCursorPos(&pt);
if (pt.x >= rect.left && pt.x < rect.right && pt.y >= rect.top && pt.y < rect.bottom) {
//MtlSendCommand(m_hWnd, ID_SEARCHENGINE_MENU);
BOOL dmy=0;
OnSearchEngineMenu(0,0,0,dmy);
return _MTL_TRANSLATE_HANDLE;
}
}
}
#endif
#if 1 //*+++ 強引対処:検索バーにカーソルがある状態でCTRL+RETURNで頁内次検索をしたとき、
// どこかの処理がCTRL+ENTERでエラー音を出しているようなのだが、誰が犯人か
// わからないので、ここで強引にキーを食って誤魔化す.
else if (msg == WM_CHAR && (vKey == VK_RETURN || vKey == 0x0a) && ::GetKeyState(VK_CONTROL) < 0) {
if ( !IsWindowVisible() || !IsChild(pMsg->hwnd) ) // ignore
return _MTL_TRANSLATE_PASS;
return _MTL_TRANSLATE_HANDLE;
}
#endif
return _MTL_TRANSLATE_PASS;
}
#if 0 //+++ WEB検索ボタンで右クリックしたら検索エンジンメニューを表示してみる
void CDonutSearchBar::OnToolBarRButtonUp(UINT nFlags, const CPoint& pt)
{
CRect rect;
m_wndToolBar.GetRect(0, rect);
if (pt.x >= rect.left && pt.x < rect.right && pt.y >= rect.top && pt.y < rect.bottom) {
//MtlSendCommand(m_hWnd, ID_SEARCHENGINE_MENU);
BOOL dmy=0;
OnSearchEngineMenu(0,0,0,dmy);
}
}
#endif
CEdit CDonutSearchBar::GetEditCtrl()
{
return CEdit( m_cmbKeyword.GetDlgItem(IDC_EDIT/*1001*/) );
}
void CDonutSearchBar::SetFocusToEngine()
{
::SetFocus(m_cmbEngine.m_hWnd);
m_cmbEngine.ShowDropDown(TRUE);
}
//private:
void CDonutSearchBar::SaveHistory()
{
DWORD dwStatus = 0;
DWORD dwHistoryMaxCnt = 10;
{
CIniFileI pr( g_szIniFileName, _T("SEARCH") );
pr.QueryValue( dwStatus, _T("Status") );
pr.QueryValue( dwHistoryMaxCnt, _T("HistoryCnt") );
}
DWORD dwItemCount = m_cmbKeyword.GetCount();
if (dwItemCount > dwHistoryMaxCnt)
dwItemCount = dwHistoryMaxCnt;
CString strFileName = _GetFilePath( _T("WordHistory.ini") );
CString strSection = _T("SEARCH_HISTORY");
CIniFileO pr(strFileName, strSection);
pr.DeleteSection();
pr.SetValue( dwItemCount, _T("HistorySaveCnt") );
if (dwStatus & STS_HISTORY_SAVE) {
for (int ii = 0; ii < (int) dwItemCount; ii++) {
CString strKeyWord;
MtlGetLBTextFixed(m_cmbKeyword.m_hWnd, ii, strKeyWord);
CString strKey;
strKey.Format(_T("KEYWORD%d"), ii);
pr.SetStringUW(strKeyWord, strKey);
}
}
}
//public:
DROPEFFECT CDonutSearchBar::OnDragEnter(IDataObject *pDataObject, DWORD dwKeyState, CPoint /*point*/)
{
if (m_bDragFromItself)
return DROPEFFECT_NONE;
_DrawDragEffect(false);
m_bDragAccept = _MtlIsHlinkDataObject(pDataObject);
return _MtlStandardDropEffect(dwKeyState);
}
DROPEFFECT CDonutSearchBar::OnDragOver(IDataObject *pDataObject, DWORD dwKeyState, CPoint /*point*/, DROPEFFECT dropOkEffect)
{
if (m_bDragFromItself || !m_bDragAccept)
return DROPEFFECT_NONE;
return _MtlStandardDropEffect(dwKeyState) | _MtlFollowDropEffect(dropOkEffect) | DROPEFFECT_COPY;
}
void CDonutSearchBar::OnDragLeave()
{
if (m_bDragFromItself)
return;
_DrawDragEffect(true);
}
//private:
void CDonutSearchBar::_DrawDragEffect(bool bRemove)
{
CClientDC dc(m_wndKeyword.m_hWnd);
CRect rect;
m_wndKeyword.GetClientRect(rect);
if (bRemove)
MtlDrawDragRectFixed(dc.m_hDC, &rect, CSize(0, 0), &rect, CSize(2, 2), NULL, NULL);
else
MtlDrawDragRectFixed(dc.m_hDC, &rect, CSize(2, 2), NULL, CSize(2, 2), NULL, NULL);
}
//public:
DROPEFFECT CDonutSearchBar::OnDrop(IDataObject *pDataObject, DROPEFFECT dropEffect, DROPEFFECT dropEffectList, CPoint /*point*/)
{
if (m_bDragFromItself)
return DROPEFFECT_NONE;
_DrawDragEffect(true);
DWORD dwStatus = 0;
{
CIniFileI pr( g_szIniFileName, _T("SEARCH") );
pr.QueryValue( dwStatus, _T("Status") );
//x pr.Close(); //+++
}
CString strText;
if ( MtlGetHGlobalText( pDataObject, strText)
|| MtlGetHGlobalText( pDataObject, strText, ::RegisterClipboardFormat(CFSTR_SHELLURL) ) )
{
CEdit edit = GetEditCtrl();
edit.SendMessage(WM_CHAR, 'P'); //m_cmbKeyword.GetCurSel() == -1にするための苦肉の策 minit
edit.SetWindowText(strText);
BOOL bSts = dwStatus & STS_DROP_GO;
if (::GetKeyState(VK_SHIFT) < 0)
bSts = !bSts;
if (bSts) {
_OnCommand_SearchWeb(strText);
}
return DROPEFFECT_COPY;
}
return DROPEFFECT_NONE;
}
void CDonutSearchBar::SetFont(HFONT hFont, BOOL bRedraw /*= TRUE*/)
{
int h = GetFontHeight( hFont ); //+++
m_nItemFontH = h > 20 ? h+1 : 20+1; //+++
m_nDefDlgH = h > 20 ? h+2 : 20+2; //+++
CDialogImpl<CDonutSearchBar>::SetFont(hFont, bRedraw);
m_cmbEngine.SetFont(hFont, bRedraw);
m_cmbKeyword.SetFont(hFont, bRedraw);
m_wndKeyword.SetFont(hFont, bRedraw);
if (m_wndToolBar.m_hWnd)
m_wndToolBar.SetFont(hFont, bRedraw);
_InitCombo(); //+++
}
//private:
void CDonutSearchBar::_SetVerticalItemCount(CComboBox &cmb, int count)
{
CRect rc;
cmb.AddString(_T("DUMMY"));
int itemheight = cmb.GetItemHeight(0);
cmb.DeleteString(0);
cmb.GetClientRect(&rc);
int dh = (itemheight > m_nDefDlgH) ? itemheight : m_nDefDlgH;
rc.bottom = rc.top + dh + (itemheight/3) +itemheight * count + 2; //+++ だいたいの感じになるように、適当に計算
cmb.MoveWindow(&rc);
}
void CDonutSearchBar::_InitCombo() //minit
{
CIniFileI pr( g_szIniFileName, _T("SEARCH") );
DWORD dwStatus = pr.GetValue( _T("Status") , 0 );
DWORD dwHeightCnt = pr.GetValue( _T("HeightCnt"), DEFAULT_HEIGHTCOUNT );
pr.Close();
m_cmbEngine.SetItemHeight(-1, m_nItemFontH);
m_cmbKeyword.SetItemHeight(-1, m_nItemFontH);
if (dwStatus & STS_HEIGHTCOUNT) {
int HeightCount = (int) dwHeightCnt;
if (HeightCount < 1 || MAXHEIGHTCOUNT < HeightCount)
HeightCount = DEFAULT_HEIGHTCOUNT;
_SetVerticalItemCount(m_cmbEngine , HeightCount);
_SetVerticalItemCount(m_cmbKeyword, HeightCount);
}
#if 1 //+++ vista以外でコンボボックスの高さがおかしい件を強制的に回避してみる...
else {
_SetVerticalItemCount(m_cmbEngine , MAXHEIGHTCOUNT);
_SetVerticalItemCount(m_cmbKeyword, DEFAULT_HEIGHTCOUNT/*50*/);
}
#endif
if (dwStatus & STS_TEXT_FILTER)
m_bFiltering = TRUE;
}
//public:
void CDonutSearchBar::ShowToolBarIcon(BOOL flag)
{
if (flag) {
if (m_bLoadedToolBar) {
if ( ::IsWindow(m_wndToolBar.m_hWnd) )
m_wndToolBar.ShowWindow(SW_NORMAL);
} else {
InitToolBar(/*+++ IDB_SEARCHBUTTON, IDB_SEARCHBUTTON_HOT,*/ m_nBmpCX, m_nBmpCY, RGB(255, 0, 255) );
m_wndToolBar.ShowWindow(SW_NORMAL);
}
} else {
if (m_bLoadedToolBar) {
m_wndToolBar.ShowWindow(SW_HIDE);
}
}
m_bShowToolBar = flag;
//サイズ変更
CRect rect;
GetWindowRect(rect);
CWindow( GetParent() ).ScreenToClient(rect);
int width = rect.right - rect.left - 1;
int height = rect.bottom - rect.top;
SetWindowPos(NULL, rect.left, rect.top, width, height, SWP_NOZORDER | SWP_NOREDRAW);
SetWindowPos(NULL, rect.left, rect.top, width+1, height, SWP_NOZORDER);
}
void CDonutSearchBar::SearchHilight()
{
#if 1 //+++
CString str = GetSearchStr();
#else
CEdit edit = GetEditCtrl();
CString str = MtlGetWindowText(edit);
#endif
str = RemoveShortcutWord(str);
//if (! str.IsEmpty())
_OnCommand_SearchHilight(str);
}
void CDonutSearchBar::SearchPage(BOOL bForward)
{
_OnCommand_SearchPage(bForward);
}
BOOL CDonutSearchBar::GetToolIconState()
{
return m_bShowToolBar;
}
void CDonutSearchBar::ReloadSkin(int nCmbStyle)
{
SetComboStyle(nCmbStyle);
if ( !m_wndToolBar.IsWindow() )
return;
m_bExistManifest = IsExistManifestFile(); //+++
CImageList imgs = m_wndToolBar.GetImageList();
CImageList imgsHot = m_wndToolBar.GetHotImageList();
CImageList imgsDis = m_wndToolBar.GetDisabledImageList(); //+++
_ReplaceImageList(GetSkinSeachBarPath(0), imgs , IDB_SEARCHBUTTON);
_ReplaceImageList(GetSkinSeachBarPath(1), imgsHot, IDB_SEARCHBUTTON_HOT);
#if 1 //+++ Disabled画像の対応.
CString str = GetSkinSeachBarPath(2);
int dis = 0;
if (Misc::IsExistFile(str) == 0) { //+++ 画像ファイルがない時
if (Misc::IsExistFile(GetSkinSeachBarPath(0))) { //+++ 通常があれば
str = GetSkinSeachBarPath(0); //+++ 通常画で代用
} else { //+++ 通常もなければ
dis = IDB_SEARCHBUTTON_DIS; //+++ デフォルトのDisable画を使う.
}
}
_ReplaceImageList(str, imgsDis, dis); //+++
#endif
InvalidateRect(NULL, TRUE);
m_wndToolBar.InvalidateRect(NULL, TRUE);
}
void CDonutSearchBar::SetComboStyle(int nCmbStyle)
{
m_cmbEngine.SetDrawStyle (nCmbStyle);
m_cmbKeyword.SetDrawStyle(nCmbStyle);
}
//=========================================================================
///+++ エンジン名の取得.
const CString& CDonutSearchBar::GetSearchEngineStr() //+++
{
HWND hWnd = m_cmbEngine;
//+++ なるべく、アロケートが発生しないようにしてみる.
enum { NAME_LEN = 0x1000 };
TCHAR name[ NAME_LEN ];
int nLen = ::GetWindowTextLength(hWnd);
if (nLen >= NAME_LEN)
nLen = NAME_LEN - 1;
name[0] = '\0';
int nRetLen = ::GetWindowText(hWnd, name, nLen + 1);
name[nLen+1] = '\0';
if (_tcscmp(name, LPCTSTR(m_strEngine)) != 0) {
m_strEngine = name;
}
return m_strEngine;
}
CMenuHandle CDonutSearchBar::GetSearchEngineMenuHandle()
{
#if 1 //+++
CMenu menu0;
MakeSearchEngineMenu(menu0);
CMenuHandle menu = menu0.GetSubMenu(0);
menu0.RemoveMenu(0, MF_BYPOSITION);
return menu;
#else
if (m_engineMenu.m_hMenu == 0)
MakeSearchEngineMenu(m_engineMenu);
if (m_engineMenu.m_hMenu == 0)
return 0;
CMenuHandle menu = m_engineMenu.GetSubMenu(0);
return menu;
#endif
}
//+++ サーチエンジンメニューを作る
bool CDonutSearchBar::MakeSearchEngineMenu(CMenu& menu0)
{
menu0.LoadMenu(IDR_SEARCHENGINE_MENU);
if (menu0.m_hMenu == NULL)
return 0;
CMenuHandle menu = menu0.GetSubMenu(0);
if (menu.m_hMenu == NULL)
return 0;
menu.DeleteMenu(0, MF_BYPOSITION );
ATLASSERT( menu.GetMenuItemCount() == 0 );
unsigned num = m_cmbEngine.GetCount();
if (num > ID_INSERTPOINT_SEARCHENGINE_END+1 - ID_INSERTPOINT_SEARCHENGINE)
num = ID_INSERTPOINT_SEARCHENGINE_END+1 - ID_INSERTPOINT_SEARCHENGINE;
for (unsigned i = 0; i < num; ++i) {
CString strName;
MtlGetLBTextFixed(m_cmbEngine, i, strName);
menu.AppendMenu(MF_ENABLED | MF_STRING , ID_INSERTPOINT_SEARCHENGINE + i, LPCTSTR(strName));
}
return 1;
}
//+++
bool CDonutSearchBar::OnSearchEngineMenu(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL & /*bHandled*/)
{
#if 1 //+++
// ポップアップメニューを開く.
::SetForegroundWindow(m_hWnd);
POINT pt;
::GetCursorPos(&pt);
CMenuHandle menu = GetSearchEngineMenuHandle();
HRESULT hr = menu.TrackPopupMenu(TPM_LEFTALIGN|TPM_RETURNCMD, pt.x, pt.y, m_hWnd, NULL);
if (hr < ID_INSERTPOINT_SEARCHENGINE || hr > ID_INSERTPOINT_SEARCHENGINE_END)
return 0;
// 選択されたものからサーチエンジン名を取得.
hr -= ID_INSERTPOINT_SEARCHENGINE;
CString strEngine;
if (menu.GetMenuString(hr, strEngine, MF_BYPOSITION) == 0)
return 0;
// 選択されたエンジンで、現在の検索文字列をweb検索.
CString strKeyword = GetSearchStr();
SearchWeb_str_engine(strKeyword, strEngine );
menu.DestroyMenu();
return 1;
#else
// サーチエンジンメニューを用意.
GetSearchEngineMenu();
// ポップアップメニューを開く.
::SetForegroundWindow(m_hWnd);
POINT pt;
::GetCursorPos(&pt);
CMenuHandle menu = m_engineMenu.GetSubMenu(0);
HRESULT hr = menu.TrackPopupMenu(TPM_LEFTALIGN | TPM_LEFTBUTTON | TPM_RIGHTBUTTON, pt.x, pt.y, m_hWnd, NULL);
if (hr <= 0 || hr > menu.GetMenuItemCount())
return 0;
// 選択されたものからサーチエンジン名を取得.
hr -= 1;
CString strEngine;
if (menu.GetMenuString(hr, strEngine, MF_BYCOMMAND) == 0)
return 0;
// 選択されたエンジンで、現在の検索文字列をweb検索.
SearchWeb_str_engine( GetSearchStr(), strEngine );
return 1;
#endif
}
//=========================================================================
//++++
#if SEARCH_JIKKEN == 1
LRESULT CDonutSearchBar::OnChevronPushed(int /*idCtrl*/, LPNMHDR pnmh, BOOL &bHandled)
{
LPNMREBARCHEVRON lpnm = (LPNMREBARCHEVRON) pnmh;
if ( lpnm->wID != GetDlgCtrlID() ) {
bHandled = FALSE;
return 1;
}
CMenuHandle menu = PrepareChevronMenu();
DisplayChevronMenu(menu, lpnm);
CleanupChevronMenu(menu, lpnm);
return 0;
}
CMenuHandle CDonutSearchBar::PrepareChevronMenu()
{
#if 0
CMenuHandle menuCmdBar(m_wndToolBar.m_hMenu);
// build a menu from hidden items
CMenuHandle menu;
BOOL bRet = menu.CreatePopupMenu();
ATLASSERT(bRet);
RECT rcClient = {0};
bRet = GetClientRect(&rcClient);
ATLASSERT(bRet);
int client_right = rcClient.right;
unsigned num = m_arrBtn.GetSize();
for (unsigned i = 0; i < num; ++i) {
CCmdBarButton cbb = m_arrBtn[i];
bool bEnabled = ( (cbb.m_fsState & CBSTATE_ENABLED) != 0 );
int cbb_btn_right = cbb.m_rcBtn.right;
if (cbb_btn_right > client_right) {
TCHAR szBuff[100];
CMenuItemInfo mii;
mii.fMask = MIIM_TYPE | MIIM_SUBMENU;
mii.dwTypeData = szBuff;
mii.cch = sizeof (szBuff) / sizeof (TCHAR);
bRet = menuCmdBar.GetMenuItemInfo(i, TRUE, &mii);
ATLASSERT(bRet);
// Note: CmdBar currently supports only drop-down items
ATLASSERT( ::IsMenu(mii.hSubMenu) );
bRet = menu.AppendMenu( MF_STRING|MF_POPUP|(bEnabled ? MF_ENABLED : MF_GRAYED),
(UINT_PTR) mii.hSubMenu,
mii.dwTypeData );
ATLASSERT(bRet);
}
}
if (menu.m_hMenu && menu.GetMenuItemCount() == 0) { // no hidden buttons after all
menu.DestroyMenu();
return NULL;
}
return menu;
#else
return NULL;
#endif
}
void CDonutSearchBar::DisplayChevronMenu(CMenuHandle menu, LPNMREBARCHEVRON lpnm)
{
if (menu.m_hMenu == 0)
return;
// convert chevron rect to screen coordinates
CWindow wndFrom = lpnm->hdr.hwndFrom;
RECT rc = lpnm->rc;
wndFrom.ClientToScreen(&rc);
// set up flags and rect
UINT uMenuFlags = TPM_LEFTBUTTON | TPM_VERTICAL | TPM_LEFTALIGN | TPM_TOPALIGN
| (!AtlIsOldWindows() ? TPM_VERPOSANIMATION : 0);
TPMPARAMS TPMParams;
TPMParams.cbSize = sizeof (TPMPARAMS);
TPMParams.rcExclude = rc;
::TrackPopupMenuEx(menu.m_hMenu, uMenuFlags, rc.left, rc.bottom, m_wndParent, &TPMParams);
}
void CDonutSearchBar::CleanupChevronMenu(CMenuHandle menu, LPNMREBARCHEVRON lpnm)
{
if (menu.m_hMenu) {
for (int i = menu.GetMenuItemCount() - 1; i >= 0; i--)
menu.RemoveMenu(i, MF_BYPOSITION);
}
menu.DestroyMenu();
CWindow wndFrom = lpnm->hdr.hwndFrom;
RECT rc = lpnm->rc;
wndFrom.ClientToScreen(&rc);
MtlEatNextLButtonDownOnChevron(m_wndParent, rc);
}
#elif SEARCH_JIKKEN == 2
//+++
LRESULT CDonutSearchBar::OnChevronPushed(int /*idCtrl*/, LPNMHDR pnmh, BOOL &bHandled)
{
ATLASSERT( ( (LPNMREBARCHEVRON) pnmh )->wID == GetDlgCtrlID() );
if ( !PushChevron( pnmh, GetTopLevelParent() ) ) {
bHandled = FALSE;
return 1;
}
return 0;
}
//+++
HMENU CDonutSearchBar::ChevronHandler_OnGetChevronMenu(int nCmdID, HMENU &hMenuDestroy)
{
bool bDestroy = 0;
bool bSubMenu = 0;
CMenuHandle menu = _GetDropDownMenu(nCmdID, bDestroy, bSubMenu);
if (bDestroy)
hMenuDestroy = menu.m_hMenu;
if (bSubMenu)
return menu.GetSubMenu(0);
else
return menu;
}
// Implemantation
HMENU CDonutSearchBar::_GetDropDownMenu(int nCmdID, bool &bDestroy, bool &bSubMenu)
{
bDestroy = true;
bSubMenu = false;
#if 0
CEdit edit = GetEditCtrl();
CString str = MtlGetWindowText(edit);
switch (nCmdID) {
case ID_SEARCH_WEB: _OnCommand_SearchWeb(str); break;
case ID_SEARCHBAR_HILIGHT: _OnCommand_SearchHilight(str); break; //ID_SEARCH_HILIGHT:
//+++ case ID_SEARCH_PAGE: _OnCommand_SearchPage( (::GetKeyState(VK_SHIFT) < 0) ? FALSE : TRUE ); break;
case ID_SEARCH_PAGE: _OnCommand_SearchPage( (::GetKeyState(VK_SHIFT) >= 0)); break;
case ID_SEARCHBAR_WORD00:
case ID_SEARCHBAR_WORD01:
case ID_SEARCHBAR_WORD02:
case ID_SEARCHBAR_WORD03:
case ID_SEARCHBAR_WORD04:
case ID_SEARCHBAR_WORD05:
case ID_SEARCHBAR_WORD06:
case ID_SEARCHBAR_WORD07:
case ID_SEARCHBAR_WORD08:
case ID_SEARCHBAR_WORD09: _OnCommand_SearchPage((::GetKeyState(VK_SHIFT) >= 0), nCmdID-ID_SEARCHBAR_WORD00); break;
default: ATLASSERT(0);
}
#endif
return 0;
}
//+++
void CDonutSearchBar::Chevronhandler_OnCleanupChevronMenu()
{
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
2685
]
]
]
|
aad0ef4d6fd6ac39ca5234905a75d150ae9bdec2 | 8bbbcc2bd210d5608613c5c591a4c0025ac1f06b | /nes/mapper/096.cpp | 2b7ba0929cb8ad7a33d1c8829d4a106ac1f4f1c8 | []
| no_license | PSP-Archive/NesterJ-takka | 140786083b1676aaf91d608882e5f3aaa4d2c53d | 41c90388a777c63c731beb185e924820ffd05f93 | refs/heads/master | 2023-04-16T11:36:56.127438 | 2008-12-07T01:39:17 | 2008-12-07T01:39:17 | 357,617,280 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,940 | cpp |
/////////////////////////////////////////////////////////////////////
// Mapper 96
void NES_mapper96_Init()
{
g_NESmapper.Reset = NES_mapper96_Reset;
g_NESmapper.PPU_Latch_Address = NES_mapper96_PPU_Latch_Address;
g_NESmapper.MemoryWrite = NES_mapper96_MemoryWrite;
}
void NES_mapper96_Reset()
{
// set CPU bank pointers
g_NESmapper.set_CPU_banks4(0,1,2,3);
// set PPU bank pointers
g_NESmapper.Mapper96.vbank0 = g_NESmapper.Mapper96.vbank1 = 0;
NES_mapper96_sync_PPU_banks();
g_PPU.vram_size = 0x8000;
g_NESmapper.set_mirroring(0,0,0,0);
}
void NES_mapper96_PPU_Latch_Address(uint32 addr)
{
if((addr & 0xF000) == 0x2000)
{
g_NESmapper.Mapper96.vbank1 = (addr & 0x0300) >> 8;
NES_mapper96_sync_PPU_banks();
}
}
void NES_mapper96_MemoryWrite(uint32 addr, uint8 data)
{
g_NESmapper.set_CPU_bank4((data & 0x03) * 4 + 0);
g_NESmapper.set_CPU_bank5((data & 0x03) * 4 + 1);
g_NESmapper.set_CPU_bank6((data & 0x03) * 4 + 2);
g_NESmapper.set_CPU_bank7((data & 0x03) * 4 + 3);
g_NESmapper.Mapper96.vbank0 = (data & 0x04) >> 2;
NES_mapper96_sync_PPU_banks();
}
void NES_mapper96_sync_PPU_banks()
{
g_NESmapper.set_VRAM_bank(0, g_NESmapper.Mapper96.vbank0 * 16 + g_NESmapper.Mapper96.vbank1 * 4 + 0);
g_NESmapper.set_VRAM_bank(1, g_NESmapper.Mapper96.vbank0 * 16 + g_NESmapper.Mapper96.vbank1 * 4 + 1);
g_NESmapper.set_VRAM_bank(2, g_NESmapper.Mapper96.vbank0 * 16 + g_NESmapper.Mapper96.vbank1 * 4 + 2);
g_NESmapper.set_VRAM_bank(3, g_NESmapper.Mapper96.vbank0 * 16 + g_NESmapper.Mapper96.vbank1 * 4 + 3);
g_NESmapper.set_VRAM_bank(4, g_NESmapper.Mapper96.vbank0 * 16 + 12);
g_NESmapper.set_VRAM_bank(5, g_NESmapper.Mapper96.vbank0 * 16 + 13);
g_NESmapper.set_VRAM_bank(6, g_NESmapper.Mapper96.vbank0 * 16 + 14);
g_NESmapper.set_VRAM_bank(7, g_NESmapper.Mapper96.vbank0 * 16 + 15);
}
/////////////////////////////////////////////////////////////////////
| [
"takka@e750ed6d-7236-0410-a570-cc313d6b6496"
]
| [
[
[
1,
56
]
]
]
|
58e35c0a20cd0662cc106afbe0d89d542c92c234 | ad80c85f09a98b1bfc47191c0e99f3d4559b10d4 | /code/src/script/nscriptlet_cmds.cc | 1f46e8f9efdf94d453aa7fff941ae840c60c9eda | []
| 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 | WINDOWS-1252 | C++ | false | false | 5,257 | cc | #define N_IMPLEMENTS nScriptlet
//------------------------------------------------------------------------------
// © 2001 Radon Labs GmbH
#include "script/nscriptlet.h"
#include "kernel/npersistserver.h"
static void n_setautorun(void*, nCmd*);
static void n_getautorun(void*, nCmd*);
static void n_parsefile(void*, nCmd*);
static void n_setscript(void*, nCmd*);
static void n_getscript(void*, nCmd*);
static void n_run(void*, nCmd*);
//------------------------------------------------------------------------------
/**
@scriptclass
nscriptlet
@superclass
nroot
@classinfo
Embeds a script inside a Nebula object. Dont use this class directly,
instead use the language specific subclasses (e.g. ntclscriptlet)
*/
void
n_initcmds(nClass* cl)
{
cl->BeginCmds();
cl->AddCmd("v_setautorun_b", 'SARN', n_setautorun);
cl->AddCmd("b_getautorun_v", 'GARN', n_getautorun);
cl->AddCmd("b_parsefile_s", 'PRSF', n_parsefile);
cl->AddCmd("v_setscript_c", 'SSCR', n_setscript);
cl->AddCmd("c_getscript_v", 'GSCR', n_getscript);
cl->AddCmd("s_run_v", 'RUN_', n_run);
cl->EndCmds();
}
//------------------------------------------------------------------------------
/**
@cmd
setautorun
@input
b (AutoRun)
@output
v
@info
If AutoRun is true, the script will immediatly be evaluated by the
default script server (/sys/servers/script) when the 'setscript'
command is issued. This is useful when the script defines only
procs (which are precompiled on first parse by the Tcl interpreter
and added to the proc list). The '.run' command will still work.
*/
static
void
n_setautorun(void* slf, nCmd* cmd)
{
nScriptlet* self = (nScriptlet*) slf;
self->SetAutoRun(cmd->In()->GetB());
}
//------------------------------------------------------------------------------
/**
@cmd
getautorun
@input
v
@output
b (AutoRun)
@info
Return the current status of the AutoRun flag.
*/
static
void
n_getautorun(void* slf, nCmd* cmd)
{
nScriptlet* self = (nScriptlet*) slf;
cmd->Out()->SetB(self->GetAutoRun());
}
//------------------------------------------------------------------------------
/**
@cmd
parsefile
@input
s (ScriptFile)
@output
b (Success)
@info
Read a (Tcl) script file, and converts it into the embedded
representation (this basically makes it no longer editable by hand,
since comments and newlines will be removed, the whole script
will be concatenated into a single line). The file name can
contain Nebula assigns. When saving the nscriptlet object,
it will save out the parsed file contents through the command
.setscript instead of the .parsefile command!
*/
static
void
n_parsefile(void* slf, nCmd* cmd)
{
nScriptlet* self = (nScriptlet*) slf;
cmd->Out()->SetB(self->ParseFile(cmd->In()->GetS()));
}
//------------------------------------------------------------------------------
/**
@cmd
setscript
@input
s (Script)
@output
v
@info
Set a script as a string. For real world stuff, use the .parsefile command
to read a tcl script file. If .setautorun has been set to true, the
script will immediately be evaluated.
*/
static
void
n_setscript(void* slf, nCmd* cmd)
{
nScriptlet* self = (nScriptlet*) slf;
self->SetScript(cmd->In()->GetC());
}
//------------------------------------------------------------------------------
/**
@cmd
getscript
@input
v
@output
s (Script)
@info
Get the script defined by .setscript. Beware, the returned string can be
verylong.
*/
static
void
n_getscript(void* slf, nCmd* cmd)
{
nScriptlet* self = (nScriptlet*) slf;
cmd->Out()->SetC(self->GetScript());
}
//------------------------------------------------------------------------------
/**
@cmd
run
@input
v
@output
s (Result)
@info
Run the embedded script through the default script server
(/sys/servers/script).
*/
static
void
n_run(void* slf, nCmd* cmd)
{
nScriptlet* self = (nScriptlet*) slf;
cmd->Out()->SetS(self->Run());
}
//------------------------------------------------------------------------------
/**
Fills nCmd object with the appropriate persistent data and passes the
nCmd object on to the nPersistServer for output to a file.
@param fileServer writes the nCmd object contents out to a file.
@return success or failure
*/
bool
nScriptlet::SaveCmds(nPersistServer* fs)
{
if (nRoot::SaveCmds(fs))
{
nCmd* cmd;
//--- setautorun ---
cmd = fs->GetCmd(this, 'SARN');
cmd->In()->SetB(this->GetAutoRun());
fs->PutCmd(cmd);
//--- setscript ---
const char* s = this->GetScript();
if (s)
{
cmd = fs->GetCmd(this, 'SSCR');
cmd->In()->SetC(s);
fs->PutCmd(cmd);
}
return true;
}
return false;
}
| [
"plushe@411252de-2431-11de-b186-ef1da62b6547"
]
| [
[
[
1,
218
]
]
]
|
e4da8323a8db1c5da31b4d2c6a9295c7cb3bd6ba | 0b79fbac1b2e0816e3923b30393cf3db3afbf821 | /omap3530/omap3530_drivers/spi/test/d_spi_client_m.h | b5a8e6764d022000aae953ef8889a448251ee33e | []
| no_license | SymbianSource/oss.FCL.sf.adapt.beagleboard | d8f378ffff2092cd3f9826c2e1db32e5b59b76d1 | bc11555ace01edea88f2ed753d4938fae4c61295 | refs/heads/master | 2020-12-25T14:22:54.807108 | 2010-11-29T13:27:18 | 2010-11-29T13:27:18 | 65,622,008 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,095 | h | // This component and the accompanying materials are made available
// under the terms of the License "Eclipse Public License v1.0"
// which accompanies this distribution, and is available
// at the URL "http://www.eclipse.org/legal/epl-v10.html".
//
// Initial Contributors:
// [email protected]
//
// Contributors:
//
//
// Description:
// omap3530_drivers/spi/test/d_spi_client_m.h
//
#ifndef __D_SPI_CLIENT_MASTER__
#define __D_SPI_CLIENT_MASTER__
#include <e32cmn.h>
#include <e32ver.h>
const TInt KIntTestThreadPriority = 24;
const TInt KIntTestMajorVersionNumber = 1;
const TInt KIntTestMinorVersionNumber = 0;
const TInt KIntTestBuildVersionNumber = KE32BuildVersionNumber;
_LIT(KLddFileName, "d_spi_client_m.ldd");
_LIT(KLddFileNameRoot, "d_spi_client_m");
#ifdef __KERNEL_MODE__
#include <kernel/kernel.h>
// For now - the driver has to know what frequencies are supported and has to specify them directly
// in the transaction header. This might be changes in the IIC PIL (kernelhwsrv)-in a way, that the driver
// returns supported frequencies with some 'GetCaps' method. For now - standard frequencies for CLK
// (that support duty cycle 50-50) are 48MHz divisions per power-of-two.
const TInt KSpiClkBaseFreqHz = 48000000;
const TInt KSpiClkMaxDivider = 4096;
inline TInt SpiFreqHz(TInt aDivider)
{
__ASSERT_DEBUG(aDivider > 0 && aDivider < KSpiClkMaxDivider, Kern::Fault("d_spi_client_master: divider out of range", 13));
__ASSERT_DEBUG(!(aDivider & (aDivider-1)), Kern::Fault("d_spi_client_master: divider not power of two", 14));
return KSpiClkBaseFreqHz / aDivider;
}
#endif
class RSpiClientTest: public RBusLogicalChannel
{
public:
enum TControl
{
EHalfDuplexSingleWrite,
EHalfDuplexMultipleWrite,
EHalfDuplexSingleRead,
EHalfDuplexMultipleRead,
EHalfDuplexMultipleWriteRead,
EFullDuplexSingle,
EFullDuplexMultiple,
EHalfDuplexExtendable,
EFullDuplexExtendable
};
enum TRequest
{
EAsyncHalfDuplexSingleWrite,
EAsyncHalfDuplexMultipleWrite,
EAsyncHalfDuplexSingleRead,
EAsyncHalfDuplexMultipleRead,
EAsyncHalfDuplexMultipleWriteRead,
EAsyncFullDuplexSingle,
EAsyncFullDuplexMultiple,
EAsyncHalfDuplexExtendable,
EAsyncFullDuplexExtendable
};
#ifndef __KERNEL_MODE__
public:
TInt Open()
{
return (DoCreate(KLddFileNameRoot,
TVersion(KIntTestMajorVersionNumber,KIntTestMinorVersionNumber,KIntTestBuildVersionNumber),
-1,
NULL,
NULL,
EOwnerThread));
}
// Synchronous calls
TInt HalfDuplexSingleWrite()
{return DoControl(EHalfDuplexSingleWrite);}
TInt HalfDuplexMultipleWrite()
{return DoControl(EHalfDuplexMultipleWrite);}
TInt HalfDuplexSingleRead()
{return DoControl(EHalfDuplexSingleRead);}
TInt HalfDuplexMultipleRead()
{return DoControl(EHalfDuplexMultipleRead);}
TInt HalfDuplexMultipleWriteRead()
{return DoControl(EHalfDuplexMultipleWriteRead);}
TInt FullDuplexSingle()
{return DoControl(EFullDuplexSingle);}
TInt FullDuplexMultiple()
{return DoControl(EFullDuplexMultiple);}
// Asynchronous calls..
void HalfDuplexSingleWrite(TRequestStatus& aStatus)
{DoRequest(EAsyncHalfDuplexSingleWrite, aStatus, NULL);}
void HalfDuplexMultipleWrite(TRequestStatus& aStatus)
{DoRequest(EAsyncHalfDuplexMultipleWrite, aStatus, NULL);}
void HalfDuplexSingleRead(TRequestStatus& aStatus)
{DoRequest(EAsyncHalfDuplexSingleRead, aStatus, NULL);}
void HalfDuplexMultipleRead(TRequestStatus& aStatus)
{DoRequest(EAsyncHalfDuplexMultipleRead, aStatus, NULL);}
void HalfDuplexMultipleWriteRead(TRequestStatus& aStatus)
{DoRequest(EAsyncHalfDuplexMultipleWriteRead, aStatus, NULL);}
void FullDuplexSingle(TRequestStatus& aStatus)
{DoRequest(EAsyncFullDuplexSingle, aStatus, NULL);}
void FullDuplexMultiple(TRequestStatus& aStatus)
{DoRequest(EAsyncFullDuplexMultiple, aStatus, NULL);}
#endif
};
#ifdef __KERNEL_MODE__
struct TCapsProxyClient
{
TVersion version;
};
class DSpiClientTestFactory: public DLogicalDevice
{
public:
DSpiClientTestFactory();
~DSpiClientTestFactory();
virtual TInt Install();
virtual void GetCaps(TDes8 &aDes) const;
virtual TInt Create(DLogicalChannelBase*& aChannel);
};
// declaration for the client channel
class DSpiClientChannel: public DLogicalChannel
{
public:
DSpiClientChannel();
~DSpiClientChannel();
virtual TInt DoCreate(TInt aUnit, const TDesC8* aInfo, const TVersion& aVer);
protected:
static void Handler(TAny *aParam);
virtual void HandleMsg(TMessageBase* aMsg); // Note: this is a pure virtual in DLogicalChannel
TInt DoControl(TInt aId, TAny* a1, TAny* a2);
TInt DoRequest(TInt aId, TRequestStatus* aStatus, TAny* a1, TAny* a2);
// set of example transfers with transactions queued synchronously
TInt HalfDuplexSingleWrite();
TInt HalfDuplexMultipleWrite();
TInt HalfDuplexSingleRead();
TInt HalfDuplexMultipleRead();
TInt HalfDuplexMultipleWriteRead();
TInt FullDuplexSingle();
TInt FullDuplexMultiple();
// set of example transfers with transactions queued asynchronously
// callback for asynchronous transactions..
static void SingleHalfDuplexTransCallback(TIicBusTransaction* aTransaction,
TInt aBusId,
TInt aResult,
TAny* aParam);
// test functions..
TInt AsyncHalfDuplexSingleWrite(TRequestStatus* aStatus);
TInt AsyncHalfDuplexSingleRead(TRequestStatus* aStatus);
TInt AsyncHalfDuplexMultipleWrite(TRequestStatus* aStatus);
TInt AsyncHalfDuplexMultipleRead(TRequestStatus* aStatus);
TInt AsyncHalfDuplexMultipleWriteRead(TRequestStatus* aStatus);
TInt AsyncFullDuplexSingle(TRequestStatus* aStatus);
TInt AsyncFullDuplexMultiple(TRequestStatus* aStatus);
private:
DThread* iClient;
};
// template for wrapper class used in asynchronous transactions in order to manage
// pointers to buffers and allocated objects (to further access the data/release memory)
template <int Size>
class TTransactionWrapper
{
public:
TTransactionWrapper(DThread* aClient, TRequestStatus* aReqStatus, TConfigSpiBufV01* aHeader) :
iHeader(aHeader),
iCallback(NULL),
iClient(aClient),
iReqStatus(aReqStatus)
{
}
TTransactionWrapper() : iHeader(NULL), iCallback(NULL), iClient(NULL), iReqStatus(NULL)
{
for(TUint i = 0; i < Size; ++i)
{
iTxBuffers[i] = NULL;
iRxBuffers[i] = NULL;
iTxTransfers[i] = NULL;
iRxTransfers[i] = NULL;
}
}
inline HBuf8* GetRxBuffer(TInt index)
{
__ASSERT_DEBUG(index < Size, Kern::Fault("d_spi_client.h, line: %d", __LINE__));
return iRxBuffers[index];
}
// destructor - to clean up all the objects..
inline ~TTransactionWrapper()
{
// it is safe to call delete on a 'NULL' pointer
delete iHeader;
delete iCallback;
for(TUint i = 0; i < Size; ++i)
{
delete iTxBuffers[i];
delete iTxTransfers[i];
delete iRxBuffers[i];
delete iRxTransfers[i];
}
}
// store all object used by transaction
TConfigSpiBufV01* iHeader;
TIicBusCallback *iCallback;
HBuf8* iTxBuffers[Size];
HBuf8* iRxBuffers[Size];
TIicBusTransfer* iTxTransfers[Size];
TIicBusTransfer* iRxTransfers[Size];
// also store client and request information
DThread* iClient;
TRequestStatus* iReqStatus;
};
// Below is additional stuff for testing with local loopback
// the IsLoopbackAvailable function checks if McSPI3 is configured to use pins from extension header
// (Beagleboard) and if these pins are physically connected (e.g. with jumper)- in order to determine
// if duplex transfers should receive the same data that was sent to the bus..
#include <assp/omap3530_assp/omap3530_scm.h>
#include <assp/omap3530_assp/omap3530_gpio.h>
const TInt KSpi3_SIMO_Pin = 131;
const TInt KSpi3_SOMI_Pin = 132;
inline TBool IsLoopbackAvailable()
{
// first check, if pad is configured to use SPI (this will confirm, if pins are used that way)
// this is their configuration (EMode1)
// CONTROL_PADCONF_MMC2_CLK, SCM::EMsw, SCM::EMode1, // mcspi3_simo
// CONTROL_PADCONF_MMC2_DAT0, SCM::ELsw, SCM::EMode1, // mcspi3_somi
TUint mode_MMC2_CLK = SCM::GetPadConfig(CONTROL_PADCONF_MMC2_CLK, SCM::EMsw);
TUint mode_MMC2_DAT0 = SCM::GetPadConfig(CONTROL_PADCONF_MMC2_DAT0, SCM::ELsw);
if(!(mode_MMC2_CLK & SCM::EMode1) ||
!(mode_MMC2_DAT0 & SCM::EMode1))
{
return EFalse; // either other pins are used or SPI3 is not configured at all..
}
// swap pins to be GPIO (EMode4)
SCM::SetPadConfig(CONTROL_PADCONF_MMC2_CLK, SCM::EMsw, SCM::EMode4 | SCM::EInputEnable);
SCM::SetPadConfig(CONTROL_PADCONF_MMC2_DAT0, SCM::ELsw, SCM::EMode4 | SCM::EInputEnable);
// set SIMO pin as output
GPIO::SetPinDirection(KSpi3_SIMO_Pin, GPIO::EOutput);
GPIO::SetPinMode(KSpi3_SIMO_Pin, GPIO::EEnabled);
// and SOMI pin as input
GPIO::SetPinDirection(KSpi3_SOMI_Pin, GPIO::EInput);
GPIO::SetPinMode(KSpi3_SOMI_Pin, GPIO::EEnabled);
TBool result = ETrue;
GPIO::TGpioState pinState = GPIO::EHigh;
// test 1: set SIMO to ELow and check if SOMI is the same
GPIO::SetOutputState(KSpi3_SIMO_Pin, GPIO::ELow);
GPIO::GetInputState(KSpi3_SOMI_Pin, pinState);
if(pinState != GPIO::ELow)
{
result = EFalse;
}
else
{
// test 2: set SIMO to EHigh and check if SOMI is the same
GPIO::SetOutputState(KSpi3_SIMO_Pin, GPIO::EHigh);
GPIO::GetInputState(KSpi3_SOMI_Pin, pinState);
if(pinState != GPIO::EHigh)
{
result = EFalse;
}
}
// restore back oryginal pad configuration for these pins
SCM::SetPadConfig(CONTROL_PADCONF_MMC2_CLK, SCM::EMsw, mode_MMC2_CLK);
SCM::SetPadConfig(CONTROL_PADCONF_MMC2_DAT0, SCM::ELsw, mode_MMC2_DAT0);
return result;
}
#endif /* __KERNEL_MODE__ */
#endif /* __D_SPI_CLIENT_MASTER__ */
| [
"[email protected]"
]
| [
[
[
1,
324
]
]
]
|
31ce0e9bcdaa263bc5f7de1701456f814887552c | ef8e875dbd9e81d84edb53b502b495e25163725c | /litewiz/src/items/item.cpp | 152b659a08ecfd8279c76b057b6f0697fe3c930f | []
| no_license | panone/litewiz | 22b9d549097727754c9a1e6286c50c5ad8e94f2d | e80ed9f9d845b08c55b687117acb1ed9b6e9a444 | refs/heads/master | 2021-01-10T19:54:31.146153 | 2010-10-01T13:29:38 | 2010-10-01T13:29:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 662 | cpp | /*******************************************************************************
*******************************************************************************/
#include "file_cluster.h"
#include "item.h"
/*******************************************************************************
*******************************************************************************/
Item::Item
(
QString const & name,
QString const & stem,
QList< FileCluster * > const & collection
) :
FileCluster( name, stem, collection )
{
}
/******************************************************************************/
| [
"[email protected]"
]
| [
[
[
1,
19
]
]
]
|
1eadbf974e2f71a4b564d0efc93272a5f8c21988 | 40b507c2dde13d14bb75ee1b3c16b4f3f82912d1 | /public/IADTFactory.h | 5159642a234623b6e872ce1e3855a658fab2c311 | []
| no_license | Nephyrin/-furry-octo-nemesis | 5da2ef75883ebc4040e359a6679da64ad8848020 | dd441c39bd74eda2b9857540dcac1d98706de1de | refs/heads/master | 2016-09-06T01:12:49.611637 | 2008-09-14T08:42:28 | 2008-09-14T08:42:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,556 | h | /**
* vim: set ts=4 :
* =============================================================================
* SourceMod
* Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, 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 for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#ifndef _INCLUDE_SOURCEMOD_ADT_FACTORY_H_
#define _INCLUDE_SOURCEMOD_ADT_FACTORY_H_
#include <IShareSys.h>
#define SMINTERFACE_ADTFACTORY_NAME "IADTFactory"
#define SMINTERFACE_ADTFACTORY_VERSION 2
/**
* @file IADTFactory.h
* @brief Creates abstract data types.
*/
namespace SourceMod
{
/**
* @brief A "Trie" data type.
*/
class IBasicTrie
{
public:
/**
* @brief Inserts a key/value pair.
*
* @param key Key string (null terminated).
* @param value Value pointer (may be anything).
* @return True on success, false if key already exists.
*/
virtual bool Insert(const char *key, void *value) =0;
/**
* @brief Retrieves the value of a key.
*
* @param key Key string (null terminated).
* @param value Optional pointer to store value pointer.
* @return True on success, false if key was not found.
*/
virtual bool Retrieve(const char *key, void **value) =0;
/**
* @brief Deletes a key.
*
* @param key Key string (null terminated).
* @return True on success, false if key was not found.
*/
virtual bool Delete(const char *key) =0;
/**
* @brief Flushes the entire trie of all keys.
*/
virtual void Clear() =0;
/**
* @brief Destroys the IBasicTrie object and frees all associated
* memory.
*/
virtual void Destroy() =0;
/**
* @brief Inserts a key/value pair, replacing an old inserted
* value if it already exists.
*
* @param key Key string (null terminated).
* @param value Value pointer (may be anything).
* @return True on success, false on failure.
*/
virtual bool Replace(const char *key, void *value) =0;
};
class IADTFactory : public SMInterface
{
public:
/**
* @brief Creates a basic Trie object.
*
* @return A new IBasicTrie object which must be destroyed
* via IBasicTrie::Destroy().
*/
virtual IBasicTrie *CreateBasicTrie() =0;
};
}
#endif //_INCLUDE_SOURCEMOD_ADT_FACTORY_H_
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
2
],
[
4,
5
],
[
7,
7
],
[
11,
11
],
[
16,
16
],
[
19,
19
],
[
28,
114
]
],
[
[
3,
3
],
[
6,
6
],
[
8,
10
],
[
12,
15
],
[
17,
18
],
[
20,
27
]
]
]
|
b4cc6ee868087f4930afac1c634fda6aa7ab19ac | 629e4fdc23cb90c0144457e994d1cbb7c6ab8a93 | /ext-lib/CRC32/CCRC32.cpp | b06d01ed9f3935772006c0ab8a5d1aae87f8efbe | []
| 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 | 6,141 | cpp | #ifndef _CCRC32_CPP
#define _CCRC32_CPP
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#define _CRT_SECURE_NO_WARNINGS //Disables fopen() security warning on Microsoft compilers.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include "CCRC32.h"
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CCRC32::CCRC32(void)
{
this->initialize();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CCRC32::~CCRC32(void)
{
//No destructor code.
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
This function initializes "CRC Lookup Table". You only need to call it once to
initalize the table before using any of the other CRC32 calculation functions.
*/
void CCRC32::initialize(void)
{
//0x04C11DB7 is the official polynomial used by PKZip, WinZip and Ethernet.
unsigned long ulPolynomial = 0x04C11DB7;
//memset(&this->ulTable, 0, sizeof(this->ulTable));
// 256 values representing ASCII character codes.
for(int iCodes = 0; iCodes <= 0xFF; iCodes++)
{
this->ulTable[iCodes] = this->reflect(iCodes, 8) << 24;
for(int iPos = 0; iPos < 8; iPos++)
{
this->ulTable[iCodes] = (this->ulTable[iCodes] << 1)
^ ((this->ulTable[iCodes] & (1 << 31)) ? ulPolynomial : 0);
}
this->ulTable[iCodes] = this->reflect(this->ulTable[iCodes], 32);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
Reflection is a requirement for the official CRC-32 standard.
You can create CRCs without it, but they won't conform to the standard.
*/
unsigned long CCRC32::reflect(unsigned long ulReflect, const char cChar)
{
unsigned long ulValue = 0;
// Swap bit 0 for bit 7, bit 1 For bit 6, etc....
for(int iPos = 1; iPos < (cChar + 1); iPos++)
{
if(ulReflect & 1)
{
ulValue |= (1 << (cChar - iPos));
}
ulReflect >>= 1;
}
return ulValue;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
Calculates the CRC32 by looping through each of the bytes in sData.
Note: For Example usage example, see FileCRC().
*/
void CCRC32::partialCRC(unsigned long *ulCRC, const unsigned char *sData, unsigned long ulDataLength)
{
while(ulDataLength--)
{
//If your compiler complains about the following line, try changing each
// occurrence of *ulCRC with "((unsigned long)*ulCRC)" or "*(unsigned long *)ulCRC".
*(unsigned long *)ulCRC =
((*(unsigned long *)ulCRC) >> 8) ^ this->ulTable[((*(unsigned long *)ulCRC) & 0xFF) ^ *sData++];
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
Returns the calculated CRC32 (through ulOutCRC) for the given string.
*/
void CCRC32::fullCRC(const unsigned char *sData, unsigned long ulDataLength, unsigned long *ulOutCRC)
{
*(unsigned long *)ulOutCRC = 0xffffffff; //Initilaize the CRC.
this->partialCRC(ulOutCRC, sData, ulDataLength);
*(unsigned long *)ulOutCRC ^= 0xffffffff; //Finalize the CRC.
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
Returns the calculated CRC23 for the given string.
*/
unsigned long CCRC32::fullCRC(const unsigned char *sData, unsigned long ulDataLength)
{
unsigned long ulCRC = 0xffffffff; //Initilaize the CRC.
this->partialCRC(&ulCRC, sData, ulDataLength);
return(ulCRC ^ 0xffffffff); //Finalize the CRC and return.
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
Calculates the CRC32 of a file using the a user defined buffer.
Note: The buffer size DOES NOT affect the resulting CRC,
it has been provided for performance purposes only.
*/
bool CCRC32::fileCRC(const char *sFileName, unsigned long *ulOutCRC, unsigned long ulBufferSize)
{
*(unsigned long *)ulOutCRC = 0xffffffff; //Initilaize the CRC.
FILE *fSource = NULL;
unsigned char *sBuf = NULL;
int iBytesRead = 0;
if((fSource = fopen(sFileName, "rb")) == NULL)
{
return false; //Failed to open file for read access.
}
if(!(sBuf = (unsigned char *)malloc(ulBufferSize))) //Allocate memory for file buffering.
{
fclose(fSource);
return false; //Out of memory.
}
while((iBytesRead = fread(sBuf, sizeof(char), ulBufferSize, fSource)))
{
this->partialCRC(ulOutCRC, sBuf, iBytesRead);
}
free(sBuf);
fclose(fSource);
*(unsigned long *)ulOutCRC ^= 0xffffffff; //Finalize the CRC.
return true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
Calculates the CRC32 of a file using the a default buffer size of 1MB.
Note: The buffer size DOES NOT affect the resulting CRC,
it has been provided for performance purposes only.
*/
bool CCRC32::fileCRC(const char *sFileName, unsigned long *ulOutCRC)
{
return this->fileCRC(sFileName, ulOutCRC, 1048576);
}
bool CCRC32::fileCRC(const std::string& filename , unsigned long& outCRC)
{
return this->fileCRC(filename.c_str() , &outCRC , 1048576);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#endif
| [
"akin@lich"
]
| [
[
[
1,
179
]
]
]
|
41a848370f260ff0f30843d1d1f8861eb577d9af | a699a508742a0fd3c07901ab690cdeba2544a5d1 | /RailwayDetection/RWDSClient/DeviceList.h | 3eb5124355978682c54dd57743624077d7dc43b7 | []
| no_license | xiaomailong/railway-detection | 2bf92126bceaa9aebd193b570ca6cd5556faef5b | 62e998f5de86ee2b6282ea71b592bc55ee25fe14 | refs/heads/master | 2021-01-17T06:04:48.782266 | 2011-09-27T15:13:55 | 2011-09-27T15:13:55 | 42,157,845 | 0 | 1 | null | 2015-09-09T05:24:10 | 2015-09-09T05:24:09 | null | GB18030 | C++ | false | false | 937 | h | #pragma once
#include "RWDSClientDoc.h"
#include "RWDSClientView.h"
#include "afxcmn.h"
#include "afxwin.h"
// CDeviceList 对话框
class CDeviceList : public CDialogEx
{
DECLARE_DYNAMIC(CDeviceList)
public:
CDeviceList(CWnd* pParent = NULL); // 标准构造函数
virtual ~CDeviceList();
// 对话框数据
enum { IDD = IDD_SETDEVICE };
public:
BOOL CheckDivceId(int aDeviceID);
private:
CListCtrl m_ListCtrl;
CComboBox m_ComboDeviceType;
CRWDSClientView* m_CRWDSClientView;
DeviceInfo* m_Selected;
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
DECLARE_MESSAGE_MAP()
public:
virtual BOOL OnInitDialog();
afx_msg void OnLvnItemchangedDevicelist(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnBnClickedBtnDeviceadd();
afx_msg void OnBnClickedBtnDevicemodify();
afx_msg void OnBnClickedBtnDevicedelete();
};
| [
"[email protected]@4d6b9eea-9d24-033f-dd66-d003eccfd9d3"
]
| [
[
[
1,
38
]
]
]
|
13fa7e293d11c0e0edc87026b6ea746520d8a04c | f8b364974573f652d7916c3a830e1d8773751277 | /emulator/allegrex/disassembler/SQRT_S.h | 2807d9855366f1d23a1076a4b20343362bd33f9c | []
| 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 | 339 | h | /* SQRT_S */
void AllegrexInstructionTemplate< 0x46000004, 0xffff003f >::disassemble(u32 address, u32 opcode, char *opcode_name, char *operands, char *comment)
{
using namespace Allegrex;
::strcpy(opcode_name, "sqrt.s");
::sprintf(operands, "%s, %s", fpr_name[fd(opcode)], fpr_name[fs(opcode)]);
::strcpy(comment, "");
}
| [
"[email protected]"
]
| [
[
[
1,
9
]
]
]
|
46ea0fe1cd34c5005d5d550d1d2b55c35fc6ff96 | 2555fb242123517fc053a3b3ba08faa5f0d2a025 | /Logger.cpp | 1ad79b2988f384734ecafdd92853f99c7fe1527b | []
| no_license | Temp1ar/multiplexer | c2f3935a4b9114e2c92982bf651ab1b766da05de | d06f2b0cee626f1bc28ab7ae4cd1f314399bf2e5 | refs/heads/master | 2020-12-30T09:57:43.797575 | 2011-12-28T15:45:28 | 2011-12-28T15:45:28 | 2,893,323 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 935 | cpp | #include "Logger.h"
using namespace std;
Logger::Logger()
{
openlog(Logger::getLoggerName(), LOG_PID, 0);
}
Logger::~Logger()
{
closelog();
destroy();
}
void Logger::debug(const string& message) const
{
syslog(LOG_DEBUG, message.c_str());
}
void Logger::destroy()
{
delete instance_;
}
void Logger::error(const string& message) const
{
syslog(LOG_ERR, message.c_str());
}
Logger* Logger::getInstance()
{
if(instance_ == 0) {
return instance_ = new Logger();
} else {
return instance_;
}
}
void Logger::info(const string& message) const
{
syslog(LOG_INFO, message.c_str());
}
void Logger::notice(const string& message) const
{
syslog(LOG_NOTICE, message.c_str());
}
void Logger::warning(const string& message) const
{
syslog(LOG_WARNING, message.c_str());
}
const char* Logger::getLoggerName()
{
return "mplex";
}
Logger* Logger::instance_ = 0; | [
"[email protected]"
]
| [
[
[
1,
60
]
]
]
|
6543dbf57c738cb1c5595fe9fb4c7c78e0ad7e8d | d54d8b1bbc9575f3c96853e0c67f17c1ad7ab546 | /hlsdk-2.3-p3/singleplayer/ricochet/cl_dll/health.h | d17d51c3089221042abfb05e68378d8318cfc312 | []
| no_license | joropito/amxxgroup | 637ee71e250ffd6a7e628f77893caef4c4b1af0a | f948042ee63ebac6ad0332f8a77393322157fa8f | refs/heads/master | 2021-01-10T09:21:31.449489 | 2010-04-11T21:34:27 | 2010-04-11T21:34:27 | 47,087,485 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,362 | h | /***
*
* Copyright (c) 1999, 2000 Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
#define DMG_IMAGE_LIFE 2 // seconds that image is up
#define DMG_IMAGE_POISON 0
#define DMG_IMAGE_ACID 1
#define DMG_IMAGE_COLD 2
#define DMG_IMAGE_DROWN 3
#define DMG_IMAGE_BURN 4
#define DMG_IMAGE_NERVE 5
#define DMG_IMAGE_RAD 6
#define DMG_IMAGE_SHOCK 7
//tf defines
#define DMG_IMAGE_CALTROP 8
#define DMG_IMAGE_TRANQ 9
#define DMG_IMAGE_CONCUSS 10
#define DMG_IMAGE_HALLUC 11
#define NUM_DMG_TYPES 12
// instant damage
#define DMG_GENERIC 0 // generic damage was done
#define DMG_CRUSH (1 << 0) // crushed by falling or moving object
#define DMG_BULLET (1 << 1) // shot
#define DMG_SLASH (1 << 2) // cut, clawed, stabbed
#define DMG_BURN (1 << 3) // heat burned
#define DMG_FREEZE (1 << 4) // frozen
#define DMG_FALL (1 << 5) // fell too far
#define DMG_BLAST (1 << 6) // explosive blast damage
#define DMG_CLUB (1 << 7) // crowbar, punch, headbutt
#define DMG_SHOCK (1 << 8) // electric shock
#define DMG_SONIC (1 << 9) // sound pulse shockwave
#define DMG_ENERGYBEAM (1 << 10) // laser or other high energy beam
#define DMG_NEVERGIB (1 << 12) // with this bit OR'd in, no damage type will be able to gib victims upon death
#define DMG_ALWAYSGIB (1 << 13) // with this bit OR'd in, any damage type can be made to gib victims upon death.
// time-based damage
//mask off TF-specific stuff too
#define DMG_TIMEBASED (~(0xff003fff)) // mask for time-based damage
#define DMG_DROWN (1 << 14) // Drowning
#define DMG_FIRSTTIMEBASED DMG_DROWN
#define DMG_PARALYZE (1 << 15) // slows affected creature down
#define DMG_NERVEGAS (1 << 16) // nerve toxins, very bad
#define DMG_POISON (1 << 17) // blood poisioning
#define DMG_RADIATION (1 << 18) // radiation exposure
#define DMG_DROWNRECOVER (1 << 19) // drowning recovery
#define DMG_ACID (1 << 20) // toxic chemicals or acid burns
#define DMG_SLOWBURN (1 << 21) // in an oven
#define DMG_SLOWFREEZE (1 << 22) // in a subzero freezer
#define DMG_MORTAR (1 << 23) // Hit by air raid (done to distinguish grenade from mortar)
//TF ADDITIONS
#define DMG_IGNITE (1 << 24) // Players hit by this begin to burn
#define DMG_RADIUS_MAX (1 << 25) // Radius damage with this flag doesn't decrease over distance
#define DMG_RADIUS_QUAKE (1 << 26) // Radius damage is done like Quake. 1/2 damage at 1/2 radius.
#define DMG_IGNOREARMOR (1 << 27) // Damage ignores target's armor
#define DMG_AIMED (1 << 28) // Does Hit location damage
#define DMG_WALLPIERCING (1 << 29) // Blast Damages ents through walls
#define DMG_CALTROP (1<<30)
#define DMG_HALLUC (1<<31)
// TF Healing Additions for TakeHealth
#define DMG_IGNORE_MAXHEALTH DMG_IGNITE
// TF Redefines since we never use the originals
#define DMG_NAIL DMG_SLASH
#define DMG_NOT_SELF DMG_FREEZE
#define DMG_TRANQ DMG_MORTAR
#define DMG_CONCUSS DMG_SONIC
typedef struct
{
float fExpire;
float fBaseline;
int x, y;
} DAMAGE_IMAGE;
//
//-----------------------------------------------------
//
class CHudHealth: public CHudBase
{
public:
virtual int Init( void );
virtual int VidInit( void );
virtual int Draw(float fTime);
virtual void Reset( void );
int MsgFunc_Health(const char *pszName, int iSize, void *pbuf);
int MsgFunc_Damage(const char *pszName, int iSize, void *pbuf);
int m_iHealth;
int m_HUD_dmg_bio;
int m_HUD_cross;
float m_fAttackFront, m_fAttackRear, m_fAttackLeft, m_fAttackRight;
void GetPainColor( int &r, int &g, int &b );
float m_fFade;
int m_bitsDamage;
private:
HSPRITE m_hSprite;
HSPRITE m_hDamage;
DAMAGE_IMAGE m_dmg[NUM_DMG_TYPES];
int DrawPain(float fTime);
int DrawDamage(float fTime);
void CalcDamageDirection(vec3_t vecFrom);
void UpdateTiles(float fTime, long bits);
};
| [
"joropito@23c7d628-c96c-11de-a380-73d83ba7c083"
]
| [
[
[
1,
128
]
]
]
|
d3c0c8d841da144b43a595d535f936a90ff75970 | fac8de123987842827a68da1b580f1361926ab67 | /inc/physics/Physics/Dynamics/Constraint/ConstraintKit/hkpGenericConstraintData.h | 1d51708c10e20836bb18d7e4a2522ee9ef0ff33a | []
| 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 | 6,734 | 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_DYNAMICS2_GENERIC_CONSTRAINT_H
#define HK_DYNAMICS2_GENERIC_CONSTRAINT_H
#include <Physics/Dynamics/Constraint/hkpConstraintData.h>
#include <Physics/ConstraintSolver/Constraint/Atom/hkpConstraintAtom.h>
#include <Physics/Dynamics/Constraint/ConstraintKit/hkpGenericConstraintScheme.h>
class hkpGenericConstraintDataParameters;
extern const hkClass hkpGenericConstraintDataClass;
/// A generic constraint for use with the hkpConstraintConstructionKit. A generic constraint
/// initially doesn't restrict any movement for its bodies - it must be configured using the kit.
class hkpGenericConstraintData : public hkpConstraintData
{
public:
HK_DECLARE_REFLECTION();
/// A parameter index. The constraint construction kit returns an index each time you specify a pivot
/// point, basis, or axis for the constraint, allowing you to access these later.
typedef int hkpParameterIndex;
/// Creates a new generic constraint.
hkpGenericConstraintData();
virtual ~hkpGenericConstraintData();
/// Gets the parameter at the index returned during kit construction
hkVector4* getParameters( hkpParameterIndex parameterIndex );
/// Sets the parameters starting at the index returned during kit construction
void setParameters( hkpParameterIndex parameterIndex, int numParameters, const hkVector4* newValues );
/// Checks consistency of constraint members.
virtual hkBool isValid() const;
hkpGenericConstraintDataScheme* getScheme();
public:
struct hkpBridgeAtoms m_atoms;
protected:
// commands
// linear constraints
void constrainAllLinearW( hkArray<int>::iterator& currentCommand, hkArray<hkVector4>::iterator& currentData, const hkpGenericConstraintDataScheme& scheme, hkpGenericConstraintDataParameters& vars, const hkpConstraintQueryIn &in, hkpConstraintQueryOut &out ) const;
inline void constrainLinearW( hkArray<int>::iterator& currentCommand, hkArray<hkVector4>::iterator& currentData, const hkpGenericConstraintDataScheme& scheme, hkpGenericConstraintDataParameters& vars, const hkpConstraintQueryIn &in, hkpConstraintQueryOut &out ) const;
inline void constrainToAngularW( hkArray<int>::iterator& currentCommand, hkArray<hkVector4>::iterator& currentData, const hkpGenericConstraintDataScheme& scheme, hkpGenericConstraintDataParameters& vars, const hkpConstraintQueryIn &in, hkpConstraintQueryOut &out ) const;
inline void constrainAllAngularW( hkArray<int>::iterator& currentCommand, hkArray<hkVector4>::iterator& currentData, const hkpGenericConstraintDataScheme& scheme, hkpGenericConstraintDataParameters& vars, const hkpConstraintQueryIn &in, hkpConstraintQueryOut &out ) const;
// limits, friction, motors
inline void setLinearLimitW( hkArray<int>::iterator& currentCommand, hkArray<hkVector4>::iterator& currentData, const hkpGenericConstraintDataScheme& scheme, hkpGenericConstraintDataParameters& vars, const hkpConstraintQueryIn &in, hkpConstraintQueryOut &out ) const;
inline void setAngularLimitW( hkArray<int>::iterator& currentCommand, hkArray<hkVector4>::iterator& currentData, const hkpGenericConstraintDataScheme& scheme, hkpGenericConstraintDataParameters& vars, const hkpConstraintQueryIn &in, hkpConstraintQueryOut &out ) const;
inline void setConeLimitW( hkArray<int>::iterator& currentCommand, hkArray<hkVector4>::iterator& currentData, const hkpGenericConstraintDataScheme& scheme, hkpGenericConstraintDataParameters& vars, const hkpConstraintQueryIn &in, hkpConstraintQueryOut &out ) const;
inline void setTwistLimitW( hkArray<int>::iterator& currentCommand, hkArray<hkVector4>::iterator& currentData, const hkpGenericConstraintDataScheme& scheme, hkpGenericConstraintDataParameters& vars, const hkpConstraintQueryIn &in, hkpConstraintQueryOut &out ) const;
inline void setAngularMotorW( hkArray<int>::iterator& currentCommand, hkArray<hkVector4>::iterator& currentData, hkpGenericConstraintDataScheme& scheme, hkpGenericConstraintDataParameters& vars, const hkpConstraintQueryIn &in, hkpConstraintQueryOut &out ) const;
inline void setLinearMotorW( hkArray<int>::iterator& currentCommand, hkArray<hkVector4>::iterator& currentData, hkpGenericConstraintDataScheme& scheme, hkpGenericConstraintDataParameters& vars, const hkpConstraintQueryIn &in, hkpConstraintQueryOut &out ) const;
inline void setAngularFrictionW( hkArray<int>::iterator& currentCommand, hkArray<hkVector4>::iterator& currentData, hkpGenericConstraintDataScheme& scheme, hkpGenericConstraintDataParameters& vars, const hkpConstraintQueryIn &in, hkpConstraintQueryOut &out ) const;
void setLinearFrictionW( hkArray<int>::iterator& currentCommand, hkArray<hkVector4>::iterator& currentData, hkpGenericConstraintDataScheme& scheme, hkpGenericConstraintDataParameters& vars, const hkpConstraintQueryIn &in, hkpConstraintQueryOut &out ) const;
/// end commands
void hatchScheme( hkpGenericConstraintDataScheme* scheme, const hkpConstraintQueryIn &in, hkpConstraintQueryOut &out );
class hkpGenericConstraintDataScheme m_scheme;
public:
// Internal functions
virtual void buildJacobian( const hkpConstraintQueryIn &in, hkpConstraintQueryOut &out );
virtual void getConstraintInfo( hkpConstraintData::ConstraintInfo& info ) const;
virtual int getType() const;
virtual void getRuntimeInfo( hkBool wantRuntime, hkpConstraintData::RuntimeInfo& infoOut ) const;
public:
hkpGenericConstraintData(hkFinishLoadedObjectFlag f);
};
#endif
/*
* 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,
124
]
]
]
|
445a8ebe79282cf22e7b6c3f6aa1a3f3eadac7d4 | b0252ba622183d115d160eb28953189930ebf9c0 | /Source/CPausedState.cpp | 152d4ed415a1935eef1b56704fc2013eacf708d5 | []
| no_license | slewicki/khanquest | 6c0ced33bffd3c9ee8a60c1ef936139a594fe2fc | f2d68072a1d207f683c099372454add951da903a | refs/heads/master | 2020-04-06T03:40:18.180208 | 2008-08-28T03:43:26 | 2008-08-28T03:43:26 | 34,305,386 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,060 | cpp | //////////////////////////////////////////////////////////
// File: "CPausedState.h"
//
// Author: Dennis Wallace (DW)
//
// Purpose: To contain functionality of the CPausedState state
//////////////////////////////////////////////////////////
#include "CPausedState.h"
#include "CGame.h"
#include "CGamePlayState.h"
#include "CWorldMapState.h"
#include "MainMenuState.h"
#include "LoseBattleState.h"
CPausedState::CPausedState(void)
{
m_nButtonID = -1;
}
CPausedState::~CPausedState(void)
{
}
void CPausedState::Enter(void)
{
m_pDI = CSGD_DirectInput::GetInstance();
m_pTM = CSGD_TextureManager::GetInstance();
m_rResumeButton.left = 300;
m_rResumeButton.top = 100;
m_rResumeButton.right = 430;
m_rResumeButton.bottom = 160;
m_rRetreatButton.left = 300;
m_rRetreatButton.top = 200;
m_rRetreatButton.right = 430;
m_rRetreatButton.bottom = 260;
m_rQuitButton.left = 300;
m_rQuitButton.top = 300;
m_rQuitButton.right = 430;
m_rQuitButton.bottom = 360;
m_nButtonID = m_pTM->LoadTexture("Resource/KQ_ScrollButton.png");
m_nLucidiaWhiteID = m_pTM->LoadTexture("Resource/KQ_FontLucidiaWhite.png");
m_cFont.InitBitmapFont(m_nLucidiaWhiteID, ' ', 16, 128, 128);
CGame::GetInstance()->SetSongPlay(BATTLESTATE);
m_fJoyTimer = 0;
}
void CPausedState::Exit(void)
{
m_pTM->ReleaseTexture(m_nButtonID);
m_pTM->ReleaseTexture(m_nLucidiaWhiteID);
}
bool CPausedState::Input(float fElapsedTime)
{
m_fJoyTimer = fElapsedTime;
#pragma region Controller to Mouse
if(m_pDI->GetJoystickDir(JOYSTICK_UP) && m_pDI->GetJoystickDir(JOYSTICK_LEFT))
{
if(m_fJoyTimer > .002f)
{
GetCursorPos(&m_ptMousePos);
SetCursorPos(m_ptMousePos.x-3,m_ptMousePos.y-3);
m_fJoyTimer = 0;
}
}
else if(m_pDI->GetJoystickDir(JOYSTICK_UP) && m_pDI->GetJoystickDir(JOYSTICK_RIGHT))
{
if(m_fJoyTimer > .002f)
{
GetCursorPos(&m_ptMousePos);
SetCursorPos(m_ptMousePos.x+3,m_ptMousePos.y-3);
m_fJoyTimer = 0;
}
}
else if(m_pDI->GetJoystickDir(JOYSTICK_DOWN) && m_pDI->GetJoystickDir(JOYSTICK_LEFT))
{
if(m_fJoyTimer > .002f)
{
GetCursorPos(&m_ptMousePos);
SetCursorPos(m_ptMousePos.x-3,m_ptMousePos.y+3);
m_fJoyTimer = 0;
}
}
else if(m_pDI->GetJoystickDir(JOYSTICK_DOWN) && m_pDI->GetJoystickDir(JOYSTICK_RIGHT))
{
if(m_fJoyTimer > .002f)
{
GetCursorPos(&m_ptMousePos);
SetCursorPos(m_ptMousePos.x+3,m_ptMousePos.y+3);
m_fJoyTimer = 0;
}
}
else if(m_pDI->GetJoystickDir(JOYSTICK_UP))
{
if(m_fJoyTimer > .002f)
{
GetCursorPos(&m_ptMousePos);
SetCursorPos(m_ptMousePos.x,m_ptMousePos.y-3);
m_fJoyTimer = 0;
}
}
else if(m_pDI->GetJoystickDir(JOYSTICK_DOWN))
{
if(m_fJoyTimer > .002f)
{
GetCursorPos(&m_ptMousePos);
SetCursorPos(m_ptMousePos.x,m_ptMousePos.y+3);
m_fJoyTimer = 0;
}
}
else if(m_pDI->GetJoystickDir(JOYSTICK_LEFT))
{
if(m_fJoyTimer > .002f)
{
GetCursorPos(&m_ptMousePos);
SetCursorPos(m_ptMousePos.x-3,m_ptMousePos.y);
m_fJoyTimer = 0;
}
}
else if(m_pDI->GetJoystickDir(JOYSTICK_RIGHT))
{
if(m_fJoyTimer > .002f)
{
GetCursorPos(&m_ptMousePos);
SetCursorPos(m_ptMousePos.x+3,m_ptMousePos.y);
m_fJoyTimer = 0;
}
}
#pragma endregion
if(CGame::GetInstance()->IsMouseInRect(m_rResumeButton))
{
CGame::GetInstance()->SetCursorClick();
if(m_pDI->GetBufferedMouseButton(M_BUTTON_LEFT) || m_pDI->GetBufferedJoyButton(JOYSTICK_X))
{
CGamePlayState::GetInstance()->SetPaused(false);
CGame::GetInstance()->PopCurrentState();
}
}
else if(CGame::GetInstance()->IsMouseInRect(m_rRetreatButton)|| m_pDI->GetBufferedJoyButton(JOYSTICK_X))
{
CGame::GetInstance()->SetCursorClick();
if(m_pDI->GetBufferedMouseButton(M_BUTTON_LEFT))
{
CGame::GetInstance()->ChangeState(CLoseBattleState::GetInstance());
CGame::GetInstance()->AddLoses();
}
}
else if(CGame::GetInstance()->IsMouseInRect(m_rQuitButton) || m_pDI->GetBufferedJoyButton(JOYSTICK_X))
{
CGame::GetInstance()->SetCursorClick();
if(m_pDI->GetBufferedMouseButton(M_BUTTON_LEFT))
{
CGame::GetInstance()->ChangeState(CMainMenuState::GetInstance());
}
}
return true;
}
void CPausedState::Update(float fElapsedTime)
{
}
void CPausedState::Render(float fElapsedTime)
{
m_pTM->Draw(m_nButtonID, m_rResumeButton.left, m_rResumeButton.top, .4f, .3f);
m_pTM->Draw(m_nButtonID, m_rRetreatButton.left, m_rRetreatButton.top, .4f, .3f);
m_pTM->Draw(m_nButtonID, m_rQuitButton.left, m_rQuitButton.top, .4f, .3f);
m_cFont.DrawTextA("Paused", 175,0,1.0f,1.0f);
m_cFont.DrawTextA("Resume", m_rResumeButton.left+30, m_rResumeButton.top+24, .2f, .2f, D3DCOLOR_ARGB(255, 255, 0, 0));
m_cFont.DrawTextA("Retreat", m_rRetreatButton.left+30, m_rRetreatButton.top+24, .2f, .2f, D3DCOLOR_ARGB(255, 255, 0, 0));
m_cFont.DrawTextA("Quit", m_rQuitButton.left+30, m_rQuitButton.top+24, .2f, .2f, D3DCOLOR_ARGB(255, 255, 0, 0));
}
| [
"[email protected]@631b4192-2952-0410-9426-c5ed74a7d3ec",
"[email protected]@631b4192-2952-0410-9426-c5ed74a7d3ec",
"[email protected]@631b4192-2952-0410-9426-c5ed74a7d3ec"
]
| [
[
[
1,
7
],
[
12,
12
],
[
165,
165
]
],
[
[
8,
11
],
[
14,
141
],
[
143,
150
],
[
152,
153
],
[
158,
161
],
[
163,
164
],
[
166,
167
],
[
169,
189
]
],
[
[
13,
13
],
[
142,
142
],
[
151,
151
],
[
154,
157
],
[
162,
162
],
[
168,
168
]
]
]
|
83d4c39d7d2b0f14bd1afccb0b2fc25871021949 | 506801cd3248f2362795b540a7247a989078468d | /test/TestEnvironment2/glVector.h | 8e077853efa86bb8d16d1fd2afc9d92e39935266 | []
| no_license | galek/gpufrustum | 0bb1479fde1794476ff34ff2b4ecdb4bc57c200d | dfac4ead5d12ae4d1540d325f70a295c715bd07b | refs/heads/master | 2020-05-29T12:32:30.603607 | 2010-01-07T12:45:51 | 2010-01-07T12:45:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 651 | h | // glVector.h: interface for the glVector class.
//
//////////////////////////////////////////////////////////////////////
#ifndef __GLVECTOR_H__
#define __GLVECTOR_H__
#include <windows.h> // Header File For Windows
#include <gl\gl.h> // Header File For The OpenGL32 Library
#include <gl\glu.h> // Header File For The GLu32 Library
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class glVector
{
public:
void operator *=(GLfloat scalar);
glVector();
virtual ~glVector();
GLfloat k;
GLfloat j;
GLfloat i;
};
#endif // !defined(AFX_GLVECTOR_H__F526A5CF_89B5_4F20_8F2C_517D83879D35__INCLUDED_)
| [
"nicolas.said@bbca828e-1ad7-11de-a108-cd2f117ce590"
]
| [
[
[
1,
28
]
]
]
|
e2c200216339fa4440f4592c7f38d63d914187eb | 6e563096253fe45a51956dde69e96c73c5ed3c18 | /dhplay/dhplay/dhplay.cpp | 897b0cd5ae86851fae0885796d930eb2ad667724 | []
| no_license | 15831944/phoebemail | 0931b76a5c52324669f902176c8477e3bd69f9b1 | e10140c36153aa00d0251f94bde576c16cab61bd | refs/heads/master | 2023-03-16T00:47:40.484758 | 2010-10-11T02:31:02 | 2010-10-11T02:31:02 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 113,412 | cpp | /*
** ************************************************************************
** DHPlay 通用播放SDK
** (c) Copyright 1992-2004, ZheJiang Dahua Technology Stock Co.Ltd.
** All Rights Reserved
**
** File Name : dhpaly.cpp
** Description : 播放sdk外部接口实现
** Modification : 2005/12/15 chenmy Create the file
** 2005/12/29 chenmy 改变用户回调函数的处理,将回调函数统一在各端口的play中处理
** 2006/01/10 chenmy 将回调函数的处理独立出来,统一在callback中处理
** 2006/01/11 chenmy 增加音量控制处理类接口,实现控制音量的相关功能
** ************************************************************************
*/
#include "StdAfx.h"
#include "utils.h"
#define DHPLAY_EX
#if defined DHVECPLAY
#include "dhvecplay.h"
#elif defined DHPLAY_EX
#include "dhplayEx.h"
#else
#include "dhplay.h"
#endif
#include "playmanage.h"
#include <ddraw.h>
#include "YUV2PICS/JpegEncoder.h"
static int g_play[FUNC_MAX_PORT];
CritSec g_PlayCritsec ;
#if defined( _WINDLL)
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
int i = 0;
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
for (i = 0; i < FUNC_MAX_PORT; ++i)
{
g_play[i] = 0;
}
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
#endif
int img_conv(unsigned char* psrc, unsigned int srcwidth, unsigned int srcheight,
unsigned char* pdst, unsigned int dstwidth, unsigned int dstheight);
//以下为对外接口,供用户作二次开发调用
PLAYSDK_API BOOL CALLMETHOD PLAY_InitDDraw(HWND hWnd)
{
return TRUE;
}
PLAYSDK_API BOOL CALLMETHOD PLAY_RealeseDDraw()
{
return TRUE;
}
/* $Function : CALLMETHOD PLAY_OpenFile
== ===============================================================
== Description : 打开播放文件,用于在播放文件之前调用
== Argument : nPort 端口号 sFileName 文件名
== :
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_OpenFile(LONG nPort,LPSTR sFileName)
{
#ifdef _DEBUG
char str[120] ;
sprintf(str,"PLAY_OpenFile Enter %d\n",nPort) ;
OutputDebugString(str) ;
#endif
if (g_cDHPlayManage.CheckPort(nPort))
{
return FALSE;
}
EnterCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[nPort]);
FILE_OPEN_ERROR nReturn = g_cDHPlayManage.pDHFile[nPort]->Open(nPort, sFileName);
if (nReturn == FILE_CANNOT_OPEN)
{
LeaveCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[nPort]);
return FALSE ;
}
LeaveCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[nPort]);
#ifdef _DEBUG
// char str[120] ;
sprintf(str,"PLAY_OpenFile Leave %d\n",nPort) ;
OutputDebugString(str) ;
#endif
return TRUE ;
}
/* $Function : CALLMETHOD DH_Play_CloseFile
== ===============================================================
== Description : 关闭文件
== Argument : nPort 端口号
== :
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_CloseFile(LONG nPort)
{
#ifdef _DEBUG
char str[120] ;
sprintf(str,"PLAY_CloseFile Enter %d\n",nPort) ;
OutputDebugString(str) ;
#endif
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
EnterCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[nPort]);
if (g_cDHPlayManage.pDHFile[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
LeaveCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[nPort]);
return FALSE ;
}
BOOL nReturn = g_cDHPlayManage.pDHFile[nPort]->Close();
delete g_cDHPlayManage.pDHFile[nPort] ;
g_cDHPlayManage.pDHFile[nPort] = NULL ;
g_cDHPlayManage.m_dwTimerType[nPort] = 0;
PLAY_ReleasePort(nPort);
LeaveCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[nPort]);
#ifdef _DEBUG
// char str[120] ;
sprintf(str,"PLAY_CloseFile Leave %d\n",nPort) ;
OutputDebugString(str) ;
#endif
return nReturn ;
}
void WINAPI CallFunction(LPBYTE pDataBuffer, DWORD DataLength, long nUser)
{
static unsigned char PCMHeader[8] = {0x00,0x00,0x01,0xF0,7,0x02,0x00,0x00};
int len = (DataLength/*>>1*/)&0xffff;
PCMHeader[6] = len & 0xff;
PCMHeader[7] = len >> 8;
unsigned short *p16 = (unsigned short *)pDataBuffer;
for (int i = 0; i < len; i++)
{
pDataBuffer[i] = pDataBuffer[i] + 128;/*BYTE((*p16)>>8);*//*pInBuf[j*2] + 128*/;
// p16++;
}
FILE* f = fopen("c://zgf0718_audio_dhplaydemo_1.dav", "ab");
fwrite(PCMHeader, 1, 8, f);
fwrite(pDataBuffer, 1, len, f);
fclose(f);
}
/* $Function : PLAY_GetFreePort
== ===============================================================
== Description : 获取空闲的端口号
== Parameter : plPort 端口号指针
== :
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2008/8/13
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_GetFreePort(LONG *plPort)
{
if (NULL == plPort)
{
return FALSE;
}
for (int i = 101; i < FUNC_MAX_PORT; i++)
{
PORT_STATE ePortState;
g_cDHPlayManage.GetPortState(i, &ePortState);
if (PORT_STATE_FREE == ePortState)
{
g_cDHPlayManage.SetPortState(i, PORT_STATE_BUSY);
break;
}
}
if (i >= FUNC_MAX_PORT)
{
return FALSE;
}
*plPort = i;
return TRUE;
}
/* $Function : PLAY_ReleasePort
== ===============================================================
== Description : 释放端口号
== Parameter : lPort 端口号
== :
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2008/8/13
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_ReleasePort(LONG lPort)
{
if (lPort < 0 || lPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
g_cDHPlayManage.SetPortState(lPort, PORT_STATE_FREE);
return TRUE;
}
/* $Function : CALLMETHOD PLAY_Play
== ===============================================================
== Description : 开始播放文件
== Argument : nPort 端口号 hWnd 播放显示窗口句柄
== :
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_Play(LONG nPort, HWND hWnd)
{
#ifdef _DEBUG
char str[120] ;
sprintf(str,"PLAY_Play Enter %d , hwnd = 0x%08X\n",nPort , hWnd) ;
OutputDebugString(str) ;
#endif
if (nPort < 0 || nPort >= FUNC_MAX_PORT) //端口号超出范围
{
return FALSE ;
}
EnterCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[nPort]);
if (g_cDHPlayManage.pDHFile[nPort] == NULL)//在调用Play之前会称调用openfile、openstream
{
LeaveCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[nPort]);
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE;
}
if (g_cDHPlayManage.CheckPort(nPort))
{
LeaveCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[nPort]);
return FALSE;
}
g_cDHPlayManage.m_error[nPort] = DH_PLAY_NOERROR;
BOOL iRet = g_cDHPlayManage.pDHPlay[nPort]->Start(hWnd) ;
if (iRet)
{
g_cDHPlayManage.SetPortState(nPort, PORT_STATE_BUSY);
}
LeaveCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[nPort]);
#ifdef _DEBUG
sprintf(str,"PLAY_Play Leave %d\n",nPort) ;
OutputDebugString(str) ;
#endif
PLAY_ResetSourceBufFlag(nPort);
// PLAY_OpenAudioRecord(CallFunction, 8, 8000, 1024, 0, NULL);
return iRet ;
}
/* $Function : CALLMETHOD PLAY_Stop
== ===============================================================
== Description : 停止播放
== Argument : nPort 端口号
== :
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_Stop(LONG nPort)
{
int iRet;
#ifdef _DEBUG
char str[120] ;
sprintf(str,"PLAY_Stop Enter %d , TickCount=%d\n",nPort,GetTickCount()) ;
OutputDebugString(str) ;
// FILE * fp = fopen("c://dhplay.log", "ab");
// if (fp)
// {
// fprintf(fp, str);
// fclose(fp);
// }
#endif
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
PORT_STATE ePortState;
g_cDHPlayManage.GetPortState(nPort, &ePortState);
if (PORT_STATE_FREE == ePortState)
{
return TRUE;
}
EnterCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[nPort]);
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
LeaveCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[nPort]);
return FALSE ;
}
iRet = g_cDHPlayManage.pDHPlay[nPort]->Stop();
if (g_cDHPlayManage.pCallback[nPort])
{
g_cDHPlayManage.pDHPlay[nPort]->SetDecCBType(DEC_COMPLEX) ;
g_cDHPlayManage.pCallback[nPort]->SetDecCallBack(NULL,FALSE);
}
PLAY_StopSoundShare(nPort) ;
if (g_cDHPlayManage.m_nSoundPort == nPort)
{
g_cDHPlayManage.m_nSoundPort = -1 ;
}
delete g_cDHPlayManage.pDHPlay[nPort] ;
g_cDHPlayManage.pDHPlay[nPort] = NULL ;
LeaveCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[nPort]);
return iRet;
}
/* $Function : CALLMETHOD PLAY_Pause
== ===============================================================
== Description : 暂停/恢复播放
== Argument : nPort 端口号 nPause 是否暂停 1 暂停 0 恢复
== :
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_Pause(LONG nPort,DWORD nPause)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHPlay[nPort]->Pause(nPause);
}
//
/* $Function : CALLMETHOD PLAY_Fast
== ===============================================================
== Description : 快速播放控制,每操作一次播放速度快一倍,最大操作4次,再操作循环
== Argument : nPort 端口号
== :
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_Fast(LONG nPort)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHPlay[nPort]->PlayFast() ;
}
/* $Function : CALLMETHOD PLAY_Slow
== ===============================================================
== Description : 慢速播放控制,每操作一次播放速度降低一倍,最大操作4次,再操作循环
== Argument : nPort 端口号
== :
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_Slow(LONG nPort)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHPlay[nPort]->PlaySlow() ;
}
/* $Function : CALLMETHOD PLAY_OneByOne
== ===============================================================
== Description : 单桢播放
== Argument : nPort 端口号
== :
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_OneByOne(LONG nPort)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHPlay[nPort]->PlayOnebyone();
}
/* $Function : CALLMETHOD PLAY_Back
== ===============================================================
== Description : 反向回放,(可以不用此函数,sdk没做要求)
== Argument : nPort 端口号
== :
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_Back(LONG nPort)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHPlay[nPort]->PlayBack();
}
/* $Function : CALLMETHOD PLAY_BackOne
== ===============================================================
== Description : 单桢反向播放 (此接口重复 真正用CALLMETHOD PLAY264_OneByOneBack)
== Argument : nPort 端口号
== :
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_BackOne(LONG nPort)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHPlay[nPort]->PlayBackOne();
}
/* $Function : CALLMETHOD PLAY_SetPlayPos
== ===============================================================
== Description : 设置播放位置
== Argument : nPort 端口号 fRelativePos 文件长度的百分比
== :
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_SetPlayPos(LONG nPort,float fRelativePos)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHPlay[nPort]->SetPlayPos(fRelativePos);
}
/* $Function : CALLMETHOD PLAY_GetPlayPos
== ===============================================================
== Description : 获取当前播放位置
== Argument : nPort 端口号
== :
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API float CALLMETHOD PLAY_GetPlayPos(LONG nPort)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHPlay[nPort]->GetPlayPos();
}
/* $Function : CALLMETHOD PLAY_SetFileEndMsg
== ===============================================================
== Description : 设置文件结束时需要发送的消息
== Argument : nPort 端口号 hWnd 消息发送窗口 nMsg 消息
== :
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_SetFileEndMsg(LONG nPort,HWND hWnd,UINT nMsg)
{
if (g_cDHPlayManage.CheckPort(nPort))
{
return FALSE;
}
g_cDHPlayManage.pMsgFileEnd[nPort]->hWnd = hWnd ;
g_cDHPlayManage.pMsgFileEnd[nPort]->nMsg = nMsg ;
g_cDHPlayManage.pMsgFileEnd[nPort]->nMsgFlag = TRUE ;
return TRUE ;
}
/* $Function :
== ===============================================================
== Description : 设置音量
== Argument : nPort 端口号 nVolume 音量值
== :
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_SetVolume(LONG nPort,WORD nVolume)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDisplay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
g_cDHPlayManage.pDisplay[nPort]->SetVolume(nVolume) ;
return TRUE ;
}
/* $Function : CALLMETHOD PLAY_StopSound
== ===============================================================
== Description : 停止播放声音,设置静音
== Argument :
== :
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_StopSound()
{
if (g_cDHPlayManage.m_nShareSoundPortList.size() > 0)
{
return FALSE ;
}
if (g_cDHPlayManage.m_nSoundPort != -1)
{
if (g_cDHPlayManage.pDHPlay[g_cDHPlayManage.m_nSoundPort] == NULL)
{
return FALSE ;
}
g_cDHPlayManage.pDHPlay[g_cDHPlayManage.m_nSoundPort]->SetDecAudio(FALSE) ;
g_cDHPlayManage.m_nSoundPort = -1 ;
}
return TRUE ;
}
/* $Function : CALLMETHOD PLAY_PlaySound
== ===============================================================
== Description : 恢复声音
== Argument : nPort 端口号
== :
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_PlaySound(LONG nPort)
{
EnterCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[nPort]);
if (g_cDHPlayManage.CheckPort(nPort))
{
LeaveCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[nPort]);
return FALSE;
}
if (g_cDHPlayManage.m_nShareSoundPortList.size() > 0)//共享方式和独占方式不能混用
{
LeaveCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[nPort]);
return FALSE ;
}
int presoundport = g_cDHPlayManage.m_nSoundPort ;
if (presoundport != -1)
{
if (g_cDHPlayManage.pDHPlay[presoundport])
{
g_cDHPlayManage.pDHPlay[presoundport]->SetDecAudio(FALSE) ;
}
}
g_cDHPlayManage.m_nSoundPort = nPort ;
g_cDHPlayManage.pDHPlay[nPort]->SetDecAudio(TRUE) ;
LeaveCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[nPort]);
return TRUE ;
}
/* $Function : CALLMETHOD PLAY_OpenStream
== ===============================================================
== Description : 打开流播放接口
== Argument : nPt 端口号 pFileHeadBuf 文件头数据指针 nSize 数据长度
== : nBufPoolSize 设置接收数据的缓冲的大小
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_OpenStream(LONG nPort,PBYTE pFileHeadBuf,DWORD nSize,DWORD nBufPoolSize)
{
#ifdef _DEBUG
char str[120] ;
sprintf(str,"PLAY_OpenStream Enter %d\n",nPort) ;
OutputDebugString(str) ;
#endif
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
EnterCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[nPort]);
if (g_cDHPlayManage.CheckPort(nPort))
{
LeaveCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[nPort]);
return FALSE;
}
#ifdef _DEBUG
sprintf(str,"PLAY_OpenStream Leave %d\n",nPort) ;
OutputDebugString(str) ;
#endif
if (nBufPoolSize <= SOURCE_BUF_MIN)
{
nBufPoolSize = 900*1024;
}
BOOL iRet = g_cDHPlayManage.pDHFile[nPort]->OpenStream(pFileHeadBuf,nSize,nBufPoolSize);
LeaveCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[nPort]);
return iRet;
}
/* $Function : CALLMETHOD PLAY_InputData
== ===============================================================
== Description : 输入流数据
== Argument : nPort 端口号 pBuf 数据指针 nSize 数据长度
== :
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_InputData(LONG nPort,PBYTE pBuf,DWORD nSize)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
EnterCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[nPort]);
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
#ifdef _DEBUG
char str[100] ;
sprintf(str,"通道%d 播放类没打开\n",nPort) ;
OutputDebugString(str) ;
#endif
LeaveCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[nPort]);
return FALSE ;
}
int iRet;
__try
{
iRet = g_cDHPlayManage.pDHPlay[nPort]->InputData(pBuf,nSize);
if (iRet <0)
{
}
}
__except(0,1)
{
int wlj = 0;
}
LeaveCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[nPort]);
return iRet ;
}
/* $Function : CALLMETHOD PLAY_CloseStream
== ===============================================================
== Description : 关闭流接口
== Argument : nPort 端口号
== :
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_CloseStream(LONG nPort)
{
#ifdef _DEBUG
char str[120] ;
sprintf(str,"PLAY_CloseStream Enter %d\n",nPort) ;
OutputDebugString(str) ;
#endif
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
EnterCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[nPort]);
if (g_cDHPlayManage.pDHFile[nPort] == NULL)
{
LeaveCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[nPort]);
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
g_cDHPlayManage.pDHFile[nPort]->CloseStream();
delete g_cDHPlayManage.pDHFile[nPort] ;
g_cDHPlayManage.pDHFile[nPort] = NULL ;
g_cDHPlayManage.m_dwTimerType[nPort] = 0;
PLAY_ReleasePort(nPort);
#ifdef _DEBUG
sprintf(str,"PLAY_CloseStream Leave %d\n",nPort) ;
OutputDebugString(str) ;
#endif
LeaveCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[nPort]);
return TRUE ;
}
/* $Function : CALLMETHOD PLAY_GetCaps
== ===============================================================
== Description : 获取系统属性,当前系统能支持的功能,按位取
== Argument :
== :
== Return : 属性值,按位取
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API int CALLMETHOD PLAY_GetCaps()
{
return g_cDHPlayManage.GetCaps();
}
/* $Function : CALLMETHOD PLAY_GetFileTime
== ===============================================================
== Description : 获取文件总的时间长度
== Argument : nPort 端口号
== :
== Return : 时间长度值
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API DWORD CALLMETHOD PLAY_GetFileTime(LONG nPort)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHFile[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHFile[nPort]->GetFileTotalTime();
}
/* $Function : CALLMETHOD PLAY_GetPlayedTime
== ===============================================================
== Description : 获取当前已播放文件的时间值
== Argument : nPort 端口号
== :
== Return : 时间值
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API DWORD CALLMETHOD PLAY_GetPlayedTime(LONG nPort)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
DWORD dwRet = 0;
__try
{
dwRet = g_cDHPlayManage.pDHPlay[nPort]->GetPlayedTime()/1000;
}
__except(0,1)
{
dwRet = 0;
}
return dwRet;
}
/* $Function : CALLMETHOD PLAY_GetPlayedFrames
== ===============================================================
== Description : 获取已播放的桢数
== Argument : nPort 端口号
== :
== Return : 桢数
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API DWORD CALLMETHOD PLAY_GetPlayedFrames(LONG nPort)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return 0 ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return 0 ;
}
DWORD iRet = g_cDHPlayManage.pDHPlay[nPort]->GetPlayedFrames() ;
return iRet;
}
PLAYSDK_API BOOL CALLMETHOD PLAY_GetRealFrameBitRate(LONG nPort, double* pBitRate)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT )
{
return FALSE;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR;
return FALSE;
}
DWORD iRet = g_cDHPlayManage.pDHPlay[nPort]->GetRealFrameBitRate(pBitRate);
return iRet;
}
/* $Function : CALLMETHOD PLAY_SetDecCallBack
== ===============================================================
== Description : 设置解码数据显示回调函数
== Argument : nPort 端口号
== : DecCBFun 回调函数指针
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_SetDecCallBack(LONG nPort,void (CALLBACK* DecCBFun)(long nPort,char * pBuf,long nSize,FRAME_INFO * pFrameInfo, long nReserved1,long nReserved2))
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (!g_cDHPlayManage.pCallback[nPort])
{
g_cDHPlayManage.pCallback[nPort] = new CCallback(nPort);
}
g_cDHPlayManage.pCallback[nPort]->SetDecCallBack(DecCBFun,TRUE);
return TRUE;
}
/* $Function : CALLMETHOD PLAY_SetDecCallBackEx
== ===============================================================
== Description : 设置解码数据显示回调扩展函数(增加用户参数)
== Argument : nPort 端口号
== : DecCBFun 回调函数指针
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2009/2/16 wanglanjun Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_SetDecCallBackEx(LONG nPort,void (CALLBACK* DecCBFun)(long nPort,char * pBuf,long nSize,FRAME_INFO * pFrameInfo, long nReserved1,long nReserved2),long nUser)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (!g_cDHPlayManage.pCallback[nPort])
{
g_cDHPlayManage.pCallback[nPort] = new CCallback(nPort);
}
g_cDHPlayManage.pCallback[nPort]->SetDecCallBackEx(DecCBFun,nUser,TRUE);
return TRUE;
}
PLAYSDK_API BOOL CALLMETHOD PLAY_SetVisibleDecCallBack(LONG nPort,void (CALLBACK* DecCBFun)(long nPort,char * pBuf,long nSize,FRAME_INFO * pFrameInfo, long nReserved1,long nReserved2),long nUser)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (!g_cDHPlayManage.pCallback[nPort])
{
g_cDHPlayManage.pCallback[nPort] = new CCallback(nPort);
}
g_cDHPlayManage.pCallback[nPort]->SetVisibleDecCallBack(DecCBFun,nUser,TRUE);
return TRUE;
}
/* $Function : CALLMETHOD PLAY_SetDisplayCallBack
== ===============================================================
== Description : 设置抓图回调
== Argument : nPort 端口号
== : DisplayCBFun 回调函数指针
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_SetDisplayCallBack(LONG nPort,void (CALLBACK* DisplayCBFun)(long nPort,char * pBuf,long nSize,long nWidth,long nHeight,long nStamp,long nType,long nReserved), long nUser)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (!g_cDHPlayManage.pCallback[nPort])
{
g_cDHPlayManage.pCallback[nPort] = new CCallback(nPort);
}
return g_cDHPlayManage.pCallback[nPort]->SetDisplayCallBack(DisplayCBFun,nUser);
}
/* $Function : CALLMETHOD PLAY_CatchPicEx
== ===============================================================
== Description : 抓图函数,将当前图像数据保存为制定的图片格式
== Argument : nPort 端口号
== : sFileName 文件名称
== : 图片格式
== Return : 成功 TRUE, 失败 FALSE
== Modification :
== ===============================================================
*/
PLAYSDK_API BOOL _stdcall PLAY_CatchPicEx(LONG nPort,char* sFileName,tPicFormats ePicfomat)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
if (sFileName == NULL)
{
return FALSE ;
}
unsigned char* pDataBuf = g_cDHPlayManage.pDHPlay[nPort]->GetLastFrame();
long width , height ;
g_cDHPlayManage.pDHPlay[nPort]->GetPictureSize(&width,&height);
BOOL ret = FALSE;
switch (ePicfomat)
{
case PicFormat_BMP:
ret = PLAY_ConvertToBmpFile((char*)pDataBuf,width*height*3/2,width,height,0,sFileName);
break;
case PicFormat_JPEG:
ret = PLAY_ConvertToJpegFile((char*)pDataBuf, width, height, YV12, 100, sFileName);
break;
default:
break;
}
return ret;
}
//
// 抓取指定格式的图片,并保存为指定的宽高
// param:nPort 端口号
// sFileName 保存路径
// lTargetWidth 指定宽度
// lTargetHeight 指定高度
// ePicfomat 图片类型
//
PLAYSDK_API BOOL CALLMETHOD PLAY_CatchResizePic(LONG nPort, char* sFileName, LONG lTargetWidth, LONG lTargetHeight, tPicFormats ePicfomat)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
if (sFileName == NULL)
{
return FALSE ;
}
unsigned char* pDataBuf = g_cDHPlayManage.pDHPlay[nPort]->GetLastFrame();
long width , height ;
g_cDHPlayManage.pDHPlay[nPort]->GetPictureSize(&width,&height);
BYTE* pYUVBuf = pDataBuf;
if ((lTargetWidth != width) || (lTargetHeight != height))
{
if ((lTargetWidth > 0) && (lTargetHeight > 0))
{
pYUVBuf = NULL;
pYUVBuf = new BYTE[lTargetWidth*lTargetHeight*3/2];
if (pYUVBuf == NULL) return FALSE;
img_conv(pDataBuf, width, height, pYUVBuf, lTargetWidth, lTargetHeight);
width = lTargetWidth;
height = lTargetHeight;
}
}
BOOL ret = FALSE;
switch (ePicfomat)
{
case PicFormat_BMP:
ret = PLAY_ConvertToBmpFile((char*)pYUVBuf,width*height*3/2,width,height,0,sFileName);
break;
case PicFormat_JPEG:
ret = PLAY_ConvertToJpegFile((char*)pYUVBuf, width, height, YV12, 100, sFileName);
break;
default:
break;
}
if (pYUVBuf != pDataBuf)
{
delete[] pYUVBuf;
}
return ret;
}
/* $Function : CALLMETHOD PLAY_ConvertToJpegFile
== ===============================================================
== Description : 将YUV数据压缩为jpeg格式并保存文件
== Argument : [IN] pYUVBuf 需要转换的数据指针 nWidth 图片宽度 nHeight 图片高度 YUVtype YUV格式类型 quality压缩质量(0, 100]
== : [OUT] sFileName 文件名
== :
== Return : 成功 TRUE, 失败 FALSE
== Modification :
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_ConvertToJpegFile(char *pYUVBuf, long nWidth, long nHeight, int YUVtype, int quality, char *sFileName)
{
if (pYUVBuf == NULL || sFileName == NULL || !nWidth || !nHeight)
{
return FALSE;
}
std::string filefullname;
filefullname = sFileName ;
std::string::size_type pos = 0 ;
std::string::size_type idx = 0 ;
// 获取录像文件所在的盘符
char cDiskNum[4];
memset(cDiskNum, 0, 4);
idx = filefullname.find(":", pos);
memcpy(cDiskNum, sFileName, idx+1);
unsigned __int64 iFreeBytes;
GetDiskFreeSpaceEx(cDiskNum, (PULARGE_INTEGER)&iFreeBytes, NULL, NULL);
// 存储空间不足,则返回
if (iFreeBytes <= nWidth*nHeight*5)
{
return FALSE;
}
while ((idx = filefullname.find("\\", pos)) != std::string::npos)
{
CreateDirectory((filefullname.substr(0, idx)).c_str(), NULL) ;
pos = idx + 1 ;
}
FILE* fp ;
if ((fp = fopen(sFileName,"wb")) == NULL)
{
return FALSE ;
}
BYTE* pJpegBuf = new BYTE[nWidth*nHeight*2];
if (pJpegBuf == NULL)
{
return FALSE;
}
int jpegsize = 0;
memset(pJpegBuf, 0, nWidth*nHeight*2);
JpegEncode(pJpegBuf, (BYTE*)pYUVBuf, &jpegsize, nWidth, nHeight, YUVtype, quality);
fwrite(pJpegBuf, 1, jpegsize, fp);
//关闭文件
fclose(fp);
if (pJpegBuf != NULL)
{
delete[] pJpegBuf;
pJpegBuf = NULL;
}
return TRUE ;
}
/* $Function : CALLMETHOD PLAY_CatchPic
== ===============================================================
== Description : 抓图函数,将当前图像数据保存为BMP文件
== Argument : nPort 端口号
== : sFileName 文件名称
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2006/4/28 zhougf Create
== ===============================================================
*/
PLAYSDK_API BOOL _stdcall PLAY_CatchPic(LONG nPort,char* sFileName)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
if (sFileName == NULL)
{
return FALSE ;
}
unsigned char* pDataBuf = g_cDHPlayManage.pDHPlay[nPort]->GetLastFrame();
long width , height ;
g_cDHPlayManage.pDHPlay[nPort]->GetPictureSize(&width,&height) ;
return PLAY_ConvertToBmpFile((char*)pDataBuf,width*height*3/2,width,height,0,sFileName) ;
}
int params_bic[32][6] = {{0, -3, 256, 4, -1, 0}, {1, -5, 255, 6, -1, 0},
{1, -9, 254, 12, -2, 0}, {2, -13, 251, 19, -3, 0},
{2, -17, 247, 27, -4, 1}, {2, -19, 243, 36, -6, 0},
{3, -22, 237, 45, -8, 1}, {3, -24, 231, 54, -9, 1},
{3, -25, 224, 64, -11, 1}, {3, -25, 216, 74, -13, 1},
{3, -27, 208, 86, -15, 1}, {3, -27, 199, 95, -16, 2},
{3, -27, 190, 106, -18, 2}, {3, -27, 181, 117, -20, 2},
{3, -26, 170, 128, -21, 2}, {3, -25, 160, 139, -23, 2},
{3, -24, 149, 149, -24, 3}, {2, -23, 139, 160, -25, 3},
{2, -21, 128, 170, -26, 3}, {2, -20, 117, 180, -26, 3},
{2, -18, 106, 190, -27, 3}, {2, -16, 95, 199, -27, 3},
{1, -15, 85, 208, -26, 3}, {1, -13, 75, 216, -26, 3},
{1, -11, 64, 224, -25, 3}, {1, -9, 54, 231, -24, 3},
{1, -8, 45, 237, -22, 3}, {0, -6, 36, 243, -19, 2},
{1, -4, 27, 247, -17, 2}, {0, -3, 19, 251, -13, 2},
{0, -2, 12, 254, -9, 1}, {0, -1, 6, 255, -5, 1}
};
int params_uv[32][2] = {{0, 256}, {8, 248}, {16, 240}, {24, 232},
{32, 224}, {40, 216}, {48, 208}, {56, 200},
{64, 192}, {72, 184}, {80, 176}, {88, 168},
{96, 160}, {104, 152}, {112, 144}, {120, 136},
{128, 128}, {136, 120}, {144, 112}, {152, 104},
{160, 96}, {168, 88}, {176, 80}, {184, 72},
{192, 64}, {200, 56}, {208, 48}, {216, 40},
{224, 32}, {232, 24}, {240, 16}, {248, 8}
};
int params_bil[32][4] ={{40, 176, 40, 0}, {36, 176, 43, 1},
{32, 175, 48, 1}, {30, 174, 51, 1},
{27, 172, 56, 1}, {24, 170, 61, 1},
{22, 167, 66, 1}, {19, 164, 71, 2},
{17, 161, 76, 2}, {15, 157, 82, 2},
{14, 152, 87, 3}, {12, 148, 93, 3},
{11, 143, 99, 3}, {9, 138, 105, 4},
{8, 133, 110, 5}, {7, 128, 116, 5},
{6, 122, 122, 6}, {5, 117, 127, 7},
{5, 110, 133, 8}, {4, 105, 138, 9},
{3, 99, 143, 11}, {3, 93, 148, 12},
{3, 87, 152, 14}, {2, 82, 157, 15},
{2, 76, 161, 17}, {2, 71, 164, 19},
{1, 66, 167, 22}, {1, 61, 170, 24},
{1, 56, 172, 27}, {1, 52, 173, 30},
{1, 47, 175, 33}, {0, 44, 176, 36}
};
void YResizeCubic(unsigned char* ptr_in, unsigned char* ptr_rz,
int old_rows, int old_cols, int rsz_rows, int rsz_cols)
{
unsigned char* ptr_temp;
unsigned char* ptr_line;
ptr_temp = (unsigned char*)malloc((old_rows + 6) * rsz_cols);
ptr_line = (unsigned char*)malloc(old_cols + 6);
int i, j, m, idx, tmp_data;
int* ptr_flt;
unsigned long ratio;
ratio = old_cols * 1024 / rsz_cols;
for(i = 0; i < old_rows; i++)
{
memcpy(ptr_line + 3, ptr_in + i * old_cols, old_cols);
memset(ptr_line, ptr_in[i * old_cols], 3);
memset(ptr_line + old_cols + 3, ptr_in[(i + 1) * old_cols - 1], 3);
for(j = 0; j < rsz_cols; j++)
{
idx = ((j * ratio) % 1024 * 32) / 1024;
ptr_flt = params_bic[idx];
idx = j * ratio / 1024 + 3;
tmp_data = 0;
for(m = 0; m < 6; m++)
tmp_data += ptr_line[idx + m - 2] * ptr_flt[m];
tmp_data /= 256;
if(tmp_data < 0) tmp_data = 0;
if(tmp_data > 255) tmp_data = 255;
ptr_temp[(i + 3) * rsz_cols + j] = (unsigned char)tmp_data;
}
}
memcpy(ptr_temp, ptr_temp + 3 * rsz_cols, rsz_cols);
memcpy(ptr_temp + rsz_cols, ptr_temp + 3 * rsz_cols, rsz_cols);
memcpy(ptr_temp + rsz_cols * 2, ptr_temp + 3 * rsz_cols, rsz_cols);
memcpy(ptr_temp + rsz_cols * (old_rows + 3), ptr_temp + (old_rows + 2) * rsz_cols, rsz_cols);
memcpy(ptr_temp + rsz_cols * (old_rows + 4), ptr_temp + (old_rows + 2) * rsz_cols, rsz_cols);
memcpy(ptr_temp + rsz_cols * (old_rows + 5), ptr_temp + (old_rows + 2) * rsz_cols, rsz_cols);
ratio = old_rows * 1024 / rsz_rows;
for(j = 0; j < rsz_cols; j++)
for(i = 0; i < rsz_rows; i++)
{
idx = ((i * ratio) % 1024 * 32) / 1024;
ptr_flt = params_bic[idx];
idx = i * ratio / 1024 + 3;
tmp_data = 0;
for(m = 0; m < 6; m++)
tmp_data += ptr_temp[(idx + m - 2) * rsz_cols + j] * ptr_flt[m];
tmp_data /= 256;
if(tmp_data < 0) tmp_data = 0;
if(tmp_data > 255) tmp_data = 255;
ptr_rz[i * rsz_cols + j] = (unsigned char)tmp_data;
}
free(ptr_temp);
free(ptr_line);
}
int img_conv(unsigned char* psrc, unsigned int srcwidth, unsigned int srcheight,
unsigned char* pdst, unsigned int dstwidth, unsigned int dstheight)
{
unsigned char* YBuf, *UBuf, *VBuf;
YBuf = pdst;
UBuf = YBuf + dstwidth*dstheight;
VBuf = UBuf + dstwidth*dstheight/4;
YResizeCubic((unsigned char*)psrc, (unsigned char*)YBuf, srcheight, srcwidth, dstheight, dstwidth);
YResizeCubic((unsigned char*)(psrc+srcwidth*srcheight), (unsigned char*)UBuf, srcheight/2, srcwidth/2, dstheight/2, dstwidth/2);
YResizeCubic((unsigned char*)(psrc+srcwidth*srcheight*5/4), (unsigned char*)VBuf, srcheight/2, srcwidth/2, dstheight/2, dstwidth/2);
return 0;
}
////////////////////////////////////////////////////////////////////////////
// U and V component resize using bilinear interpolation
void UVResize(unsigned char* ptr_in, unsigned char* ptr_rz,
int old_rows, int old_cols, int rsz_rows, int rsz_cols)
{
unsigned char* ptr_temp;
unsigned char* ptr_line;
ptr_temp = (unsigned char*)malloc((old_rows + 2) * rsz_cols);
ptr_line = (unsigned char*)malloc(old_cols + 2);
int i, j, idx, tmp_data;
int* ptr_flt;
unsigned long ratio;
ratio = 1024 * old_cols / rsz_cols;
for(i = 0; i < old_rows; i++)
{
memcpy(ptr_line + 1, ptr_in + i * old_cols, old_cols);
ptr_line[0] = ptr_line[1];
ptr_line[old_cols + 1] = ptr_line[old_cols];
for(j = 0; j < rsz_cols; j++)
{
idx = ((j * ratio) % 1024 * 32) / 1024;
ptr_flt = params_uv[idx];
idx = j * ratio / 1024 + 1;
tmp_data = (ptr_line[idx] * ptr_flt[0] + ptr_line[idx + 1] * ptr_flt[1]) / 256;
if(tmp_data > 255) tmp_data = 255;
ptr_temp[(i + 1) * rsz_cols + j] = (unsigned char)tmp_data;
}
}
memcpy(ptr_temp, ptr_temp + rsz_cols, rsz_cols);
memcpy(ptr_temp + rsz_cols * (old_rows + 1), ptr_temp + old_rows * rsz_cols, rsz_cols);
ratio = 1024 * old_rows / rsz_rows;
for(j = 0; j < rsz_cols; j++)
for(i = 0; i < rsz_rows; i++)
{
idx = ((i * ratio) % 1024 * 32) / 1024;
ptr_flt = params_uv[idx];
idx = i * ratio / 1024 + 1;
tmp_data = (ptr_temp[idx * rsz_cols + j] * ptr_flt[0] +
ptr_temp[(idx + 1) * rsz_cols + j] * ptr_flt[1]) / 256;
if(tmp_data > 255) tmp_data = 255;
ptr_rz[i * rsz_cols + j] = (unsigned char)tmp_data;
}
free(ptr_temp);
free(ptr_line);
}
#define RGB_Y_OUT 1.164
#define B_U_OUT 2.018
#define Y_ADD_OUT 16
#define G_U_OUT 0.391
#define G_V_OUT 0.813
#define U_ADD_OUT 128
#define R_V_OUT 1.596
#define V_ADD_OUT 128
#define SCALEBITS_OUT 13
#define FIX_OUT(x) ((uint16_t) ((x) * (1L<<SCALEBITS_OUT) + 0.5))
int32_t RGB_Y_tab[256];
int32_t B_U_tab[256];
int32_t G_U_tab[256];
int32_t G_V_tab[256];
int32_t R_V_tab[256];
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#define MIN(a,b) ((a) > (b) ? (b) : (a))
/* yuv 4:2:0 planar -> rgb24 */
void colorspace_init(void) {
int32_t i;
for(i = 0; i < 256; i++) {
RGB_Y_tab[i] = FIX_OUT(RGB_Y_OUT) * (i - Y_ADD_OUT);
B_U_tab[i] = FIX_OUT(B_U_OUT) * (i - U_ADD_OUT);
G_U_tab[i] = FIX_OUT(G_U_OUT) * (i - U_ADD_OUT);
G_V_tab[i] = FIX_OUT(G_V_OUT) * (i - V_ADD_OUT);
R_V_tab[i] = FIX_OUT(R_V_OUT) * (i - V_ADD_OUT);
}
}
BYTE str_zgf[2000*3];
//BYTE g_rgb24[720*576*3];
void yv12_to_rgb24_c(uint8_t *dst, int dst_stride,
uint8_t *y_src, uint8_t *u_src, uint8_t * v_src,
int y_stride, int uv_stride,
int width, int height)
{
static int zgf_i = 0;
if (zgf_i == 0)
{
colorspace_init();
zgf_i = 1;
}
unsigned char* zgf_dst = dst;
const uint32_t dst_dif = 6 * dst_stride - 3 * width;
int32_t y_dif = 2 * y_stride - width;
uint8_t *dst2 = dst + 3 * dst_stride;
const uint8_t *y_src2 = y_src + y_stride;
uint32_t x, y;
if (height < 0) { // flip image?
height = -height;
y_src += (height - 1) * y_stride;
y_src2 = y_src - y_stride;
u_src += (height / 2 - 1) * uv_stride;
v_src += (height / 2 - 1) * uv_stride;
y_dif = -width - 2 * y_stride;
uv_stride = -uv_stride;
}
for (y = height / 2; y; y--)
{
// process one 2x2 block per iteration
for (x = 0; x < (uint32_t)width / 2; x++)
{
int u, v;
int b_u, g_uv, r_v, rgb_y;
int r, g, b;
u = u_src[x];
v = v_src[x];
b_u = B_U_tab[u];
g_uv = G_U_tab[u] + G_V_tab[v];
r_v = R_V_tab[v];
rgb_y = RGB_Y_tab[*y_src];
b = (rgb_y + b_u) >> SCALEBITS_OUT;
g = (rgb_y - g_uv) >> SCALEBITS_OUT;
r = (rgb_y + r_v) >> SCALEBITS_OUT;
dst[0] = MAX(0,MIN(255, b));
dst[1] = MAX(0,MIN(255, g));
dst[2] = MAX(0,MIN(255, r));
y_src++;
rgb_y = RGB_Y_tab[*y_src];
b = (rgb_y + b_u) >> SCALEBITS_OUT;
g = (rgb_y - g_uv) >> SCALEBITS_OUT;
r = (rgb_y + r_v) >> SCALEBITS_OUT;
dst[3] = MAX(0,MIN(255, b));
dst[4] = MAX(0,MIN(255, g));
dst[5] = MAX(0,MIN(255, r));
y_src++;
rgb_y = RGB_Y_tab[*y_src2];
b = (rgb_y + b_u) >> SCALEBITS_OUT;
g = (rgb_y - g_uv) >> SCALEBITS_OUT;
r = (rgb_y + r_v) >> SCALEBITS_OUT;
dst2[0] = MAX(0,MIN(255, b));
dst2[1] = MAX(0,MIN(255, g));
dst2[2] = MAX(0,MIN(255, r));
y_src2++;
rgb_y = RGB_Y_tab[*y_src2];
b = (rgb_y + b_u) >> SCALEBITS_OUT;
g = (rgb_y - g_uv) >> SCALEBITS_OUT;
r = (rgb_y + r_v) >> SCALEBITS_OUT;
dst2[3] = MAX(0,MIN(255, b));
dst2[4] = MAX(0,MIN(255, g));
dst2[5] = MAX(0,MIN(255, r));
y_src2++;
dst += 6;
dst2 += 6;
}
dst += dst_dif;
dst2 += dst_dif;
y_src += y_dif;
y_src2 += y_dif;
u_src += uv_stride;
v_src += uv_stride;
}
for (int i = 0; i < height/2; i++)
{
memcpy(str_zgf, zgf_dst + i*width*3, width*3);
memcpy(zgf_dst+i*width*3, zgf_dst+(height-i-1)*width*3, width*3);
memcpy(zgf_dst+(height-1-i)*width*3, str_zgf, width*3);
}
}
void YuvToRgb(const unsigned char &Y, const unsigned char &U,
const unsigned char &V, RGBTRIPLE &rgb)
{
///*-----------------------------------------------------------------------------------------
int rgbR = (int)(Y + 1.140 * (V - 128)) ;
int rgbG = (int)(Y - 0.581 * (V - 128) - 0.395 * (U - 128)) ;
int rgbB = (int)(Y + 2.032 * (U - 128)) ;
//确保RGB各值在0-255范围内,超过255,则设为255,小于0,一设为0
if (rgbB > 255)
rgb.rgbtBlue = 255 ;
else if (rgbB < 0)
rgb.rgbtBlue = 0 ;
else
rgb.rgbtBlue = rgbB ;
if (rgbG > 255)
rgb.rgbtGreen = 255 ;
else if (rgbG < 0)
rgb.rgbtGreen = 0 ;
else
rgb.rgbtGreen = rgbG ;
if (rgbR > 255)
rgb.rgbtRed = 255 ;
else if (rgbR < 0)
rgb.rgbtRed = 0 ;
else
rgb.rgbtRed = rgbR ;
}
void Convert2BMP(BYTE* pBmpBuf, DWORD* pBmpSize, BYTE* pDataBuf, long nWidth, long nHeight)
{
BYTE* tmp_zgf = NULL ;
BYTE *YBuf, *UBuf, *VBuf ; //存放Y、U、V值的缓冲区
YBuf = pDataBuf ;
UBuf = pDataBuf + nWidth * nHeight ;
VBuf = pDataBuf + nWidth * nHeight * 5 / 4 ;
// if ((nWidth>=640 && nWidth<=720) && (nHeight<=288 && nHeight>=240))
// {
// tmp_zgf = new BYTE[nWidth*nHeight*3] ;
// memset(tmp_zgf, 0, nWidth*nHeight*3);
//
// int i ;
// for (i = 0 ; i < nHeight ; i++)
// {
// memcpy(tmp_zgf + 2*i * nWidth, pDataBuf + i*nWidth, nWidth);
// memcpy(tmp_zgf + (2*i + 1) * nWidth, pDataBuf + i*nWidth, nWidth) ;
// }
//
// for (i = 0 ; i < nHeight/2 ;i++)
// {
// memcpy(tmp_zgf+nWidth*2*nHeight + 2*i * nWidth/2, pDataBuf + nWidth*nHeight + i*nWidth/2, nWidth/2);
// memcpy(tmp_zgf+nWidth*2*nHeight + (2*i + 1) * nWidth/2, pDataBuf + nWidth*nHeight + i*nWidth/2, nWidth/2) ;
// }
//
// for (i = 0 ; i < nHeight/2 ;i++)
// {
// memcpy(tmp_zgf+nWidth*5*nHeight/2 + 2*i * nWidth/2, pDataBuf + nWidth*nHeight*5/4 + i*nWidth/2, nWidth/2);
// memcpy(tmp_zgf+nWidth*5*nHeight/2 + (2*i + 1) * nWidth/2, pDataBuf + nWidth*nHeight*5/4 + i*nWidth/2, nWidth/2) ;
// }
//
// nHeight *= 2 ;
//
// YBuf = tmp_zgf ;
// UBuf = tmp_zgf + nWidth * nHeight ;
// VBuf = tmp_zgf + nWidth * nHeight * 5 / 4 ;
// }
// else if ((nWidth<=352 && nWidth>=320) && (nHeight<=576 && nHeight>=480))
// {
// tmp_zgf = new BYTE[nWidth*nHeight*3] ;
// memset(tmp_zgf, 0, nWidth*nHeight*3);
//
// for (int i = 0 ; i < nWidth*nHeight*3/2 ; i++)
// {
// tmp_zgf[i*2] = tmp_zgf[i*2 + 1] = pDataBuf[i] ;
// }
//
// nWidth *= 2 ;
//
// YBuf = tmp_zgf ;
// UBuf = tmp_zgf + nWidth * nHeight ;
// VBuf = tmp_zgf + nWidth * nHeight * 5 / 4 ;
// }
// else
// {
// YBuf = pDataBuf ;
// UBuf = pDataBuf + nWidth * nHeight ;
// VBuf = pDataBuf + nWidth * nHeight * 5 / 4 ;
// }
BITMAPFILEHEADER bmpFileHeader ; //BMP文件头
BITMAPINFOHEADER bmpInfoHeader ; //BMP信息头
//设置BMP文件头
bmpFileHeader.bfType = 0x4D42 ; // 文件头类型 'BM'(42 4D)
bmpFileHeader.bfSize = sizeof(bmpFileHeader) + sizeof(bmpInfoHeader) + nWidth * nHeight * 3 ; //文件大小
bmpFileHeader.bfReserved1 = 0 ; //保留字
bmpFileHeader.bfReserved2 = 0 ; //保留字
bmpFileHeader.bfOffBits = 54 ; //位图像素数据的起始位置
//设置BMP信息头
bmpInfoHeader.biSize = 40 ; //信息头所占字节数
bmpInfoHeader.biWidth = nWidth ; //位图宽度
bmpInfoHeader.biHeight = nHeight ; //位图高度
bmpInfoHeader.biPlanes = 1 ; //位图平面数
bmpInfoHeader.biBitCount = 24 ; //像素位数
bmpInfoHeader.biCompression = 0 ; //压缩类型,0 即不压缩
bmpInfoHeader.biSizeImage = 0 ; //
bmpInfoHeader.biXPelsPerMeter = 0 ; //
bmpInfoHeader.biYPelsPerMeter = 0 ; //
bmpInfoHeader.biClrUsed = 0 ; //
bmpInfoHeader.biClrImportant = 0 ; //
//写入BMP文件头
memcpy(pBmpBuf, &bmpFileHeader, sizeof(BITMAPFILEHEADER));
//写入BMP信息头
memcpy(pBmpBuf+sizeof(BITMAPFILEHEADER), &bmpInfoHeader, sizeof(BITMAPINFOHEADER));
BYTE* prgb24 = pBmpBuf + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
yv12_to_rgb24_c(prgb24 , nWidth , YBuf , UBuf , VBuf, nWidth , nWidth/2, nWidth , nHeight);
*pBmpSize = nWidth*nHeight*3 + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
}
/* $Function : CALLMETHOD PLAY_ConvertToBmpFile
== ===============================================================
== Description : 将数据转换为bmp文件
== Argument : [IN] pBuf 需要转换的数据指针 nSize 数据长度 nWidth 图片宽度 nHeight 图片高度 nType 类型
[OUT] sFileName bmp文件名
== :
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_ConvertToBmpFile(char * pBuf,long nSize,long nWidth,long nHeight,long nType,char *sFileName)
{
if (pBuf == NULL || sFileName == NULL || !nSize || !nWidth || !nHeight)
{
return FALSE;
}
std::string filefullname;
filefullname = sFileName ;
std::string::size_type pos = 0 ;
std::string::size_type idx = 0 ;
// 获取录像文件所在的盘符
char cDiskNum[4];
memset(cDiskNum, 0, 4);
idx = filefullname.find(":", pos);
memcpy(cDiskNum, sFileName, idx+1);
unsigned __int64 iFreeBytes;
GetDiskFreeSpaceEx(cDiskNum, (PULARGE_INTEGER)&iFreeBytes, NULL, NULL);
// 存储空间不足,则返回
if (iFreeBytes <= nWidth*nHeight*5)
{
return FALSE;
}
while ((idx = filefullname.find("\\", pos)) != std::string::npos)
{
CreateDirectory((filefullname.substr(0, idx)).c_str(), NULL) ;
pos = idx + 1 ;
}
FILE* fp ;
if ((fp = fopen(sFileName,"wb")) == NULL)
{
return FALSE ;
}
DWORD dwBmpSize = 0;
int len = nWidth*nHeight*4 + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
BYTE* pBmpBuf = new BYTE[len];
memset(pBmpBuf, 0, len);
Convert2BMP(pBmpBuf, &dwBmpSize, (BYTE*)pBuf, nWidth, nHeight);
fwrite(pBmpBuf, 1, dwBmpSize, fp);
//关闭文件
fclose(fp) ;
if (pBmpBuf)
{
delete pBmpBuf ;
pBmpBuf = NULL ;
}
return TRUE ;
}
/* $Function : CALLMETHOD PLAY_GetFileTotalFrames
== ===============================================================
== Description : 获取文件的总桢数
== Argument : nPort 端口号
== :
== Return : 总桢数
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API DWORD CALLMETHOD PLAY_GetFileTotalFrames(LONG nPort)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHFile[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHFile[nPort]->GetTotalFrames() ;
}
/* $Function : CALLMETHOD PLAY_GetCurrentFrameRate
== ===============================================================
== Description : 获取当前播放数据桢率
== Argument : nPort 端口号
== :
== Return : 桢率值
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API DWORD CALLMETHOD PLAY_GetCurrentFrameRate(LONG nPort)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHPlay[nPort]->GetFrameRate() ;
}
/* $Function : CALLMETHOD PLAY_GetPlayedTimeEx
== ===============================================================
== Description : 获取播放时间(ms)暂时没做ms精确度 直接处理成s*1000
== Argument : nPort 端口号
== :
== Return : 播放时间
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API DWORD CALLMETHOD PLAY_GetPlayedTimeEx(LONG nPort)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
DWORD dwRet = 0;
__try
{
dwRet = g_cDHPlayManage.pDHPlay[nPort]->GetPlayedTimeEX();
}
__except(0,1)
{
dwRet = 0;
}
#ifdef _DEBUG
char str[120] ;
sprintf(str,"PLAY_GetPlayedTimeEx %d %d\n",nPort, dwRet) ;
//OutputDebugString(str) ;
#endif
return dwRet;
}
/* $Function : CALLMETHOD PLAY_SetPlayedTimeEx
== ===============================================================
== Description : 设置播放时间(ms)暂时没做ms精确度 直接处理成s*1000
== Argument : nPort 端口号
== :
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2006/5/11 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_SetPlayedTimeEx(LONG nPort,DWORD nTime)
{
#ifdef _DEBUG
char str[120] ;
sprintf(str,"PLAY_SetPlayedTimeEx %d %d\n",nPort, nTime) ;
//OutputDebugString(str) ;
#endif
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL || g_cDHPlayManage.pDHFile[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHPlay[nPort]->SetPlayTime(nTime);
}
/* $Function : CALLMETHOD PLAY_GetCurrentFrameNum
== ===============================================================
== Description : 获取当前播放的桢序号
== Argument : nPort 端口号
== :
== Return : 桢序号
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API DWORD CALLMETHOD PLAY_GetCurrentFrameNum(LONG nPort)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHPlay[nPort]->GetCurFrameNum() ;
}
/* $Function : CALLMETHOD PLAY_SetStreamOpenMode
== ===============================================================
== Description : 设置流打开模式 必须在播放之前设置
== Argument : nPort 端口号 nMode 模式类型 STREAME_REALTIME实时模式,适合播放网络实时数据,解码器会立刻解码。
== STREAME_FILE 文件模式,适合用户把文件数据用流方式输入,注意:当PLAY264_InputData()返回FALSE时,用户要等一下重新输入。
== 注意:可以做暂停,快放,慢放,单帧播放操作
== :
== Return :
== Modification : 2005/12/15 chenmy Create 目前暂时没对此分开处理,都是堵塞时返回FALSE
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_SetStreamOpenMode(LONG nPort,DWORD nMode)
{
if (g_cDHPlayManage.CheckPort(nPort))
{
return FALSE;
}
g_cDHPlayManage.m_nStreamMode[nPort] = nMode;
return TRUE;
}
/* $Function : CALLMETHOD PLAY_GetFileHeadLength
== ===============================================================
== Description : 获取文件头的长度
== Argument :
== :
== Return : 文件头的长度
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API DWORD CALLMETHOD PLAY_GetFileHeadLength()
{
return g_cDHPlayManage.GetFileHeadLenth();
}
/* $Function : CALLMETHOD PLAY_GetSdkVersion
== ===============================================================
== Description : 获取sdk的版本
== Argument :
== :
== Return : sdk的版本值
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API DWORD CALLMETHOD PLAY_GetSdkVersion()
{
return g_cDHPlayManage.GetSdkVersion();
}
/* $Function : CALLMETHOD PLAY_GetLastError
== ===============================================================
== Description : 获取错误类型
== Argument : nPort 端口号
== :
== Return : 错误类型号
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API DWORD CALLMETHOD PLAY_GetLastError(LONG nPort)
{
return g_cDHPlayManage.GetError(nPort) ;
}
/* $Function : CALLMETHOD PLAY_RefreshPlay
== ===============================================================
== Description : 刷新显示
== Argument : nPort 端口号
== :
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_RefreshPlay(LONG nPort)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHPlay[nPort]->RefreshPlay() ;
}
/* $Function : CALLMETHOD PLAY_SetOverlayMode
== ===============================================================
== Description : 设置overlay模式的关键色
== Argument : nPort 端口号 bOverlay 是否overlay显示 colorKey 关键色
== :
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_SetOverlayMode(LONG nPort,BOOL bOverlay,COLORREF colorKey)
{
#ifdef _DEBUG
OutputDebugString("PLAY_SetOverlayMode Enter\n") ;
#endif
if (g_cDHPlayManage.CheckPort(nPort))
{
return FALSE;
}
g_cDHPlayManage.pDHPlay[nPort]->m_pDisplay->SetOverlayMode(bOverlay,colorKey);
#ifdef _DEBUG
OutputDebugString("PLAY_SetOverlayMode Leave\n") ;
#endif
return TRUE ;
}
PLAYSDK_API BOOL CALLMETHOD PLAY_VerticalSyncEnable(LONG nPort, BOOL bEnable)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.CheckPort(nPort))
{
return FALSE;
}
BOOL ret = FALSE;
if (g_cDHPlayManage.pDHPlay[nPort]->m_pDisplay != NULL)
{
ret = g_cDHPlayManage.pDHPlay[nPort]->m_pDisplay->VerticalSyncEnable(bEnable);
}
return ret ;
}
/* $Function : CALLMETHOD PLAY_GetPictureSize
== ===============================================================
== Description : 获取图像大小
== Argument : nPort 端口号
== : [out] pWidth pHeight 宽度和高度
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_GetPictureSize(LONG nPort,LONG *pWidth,LONG *pHeight)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
if (pWidth == NULL || pHeight == NULL)
{
return FALSE ;
}
return g_cDHPlayManage.pDHPlay[nPort]->GetPictureSize(pWidth, pHeight) ;
}
/* $Function : CALLMETHOD PLAY_SetPicQuality
== ===============================================================
== Description : 设置画质
== Argument : nPort 端口号 bHighQuality 是否高清
== :
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_SetPicQuality(LONG nPort,BOOL bHighQuality)
{
g_cDHPlayManage.m_nQuality[nPort] = (int)bHighQuality;
return TRUE;
}
/* $Function : CALLMETHOD PLAY_PlaySoundShare
== ===============================================================
== Description : 设置共享声音播放
== Argument : nPort 端口号
== :
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_PlaySoundShare(LONG nPort)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
if (g_cDHPlayManage.m_nSoundPort != -1)
{
return FALSE ;
}
std::vector<int>::iterator pos = g_cDHPlayManage.m_nShareSoundPortList.begin() ;
for (; pos != g_cDHPlayManage.m_nShareSoundPortList.end() ; ++pos)
{
if (*pos == nPort)
{
break ;
}
}
if (pos == g_cDHPlayManage.m_nShareSoundPortList.end())
{
g_cDHPlayManage.m_nShareSoundPortList.push_back(nPort) ;
}
return g_cDHPlayManage.pDHPlay[nPort]->SetDecAudio(TRUE) ;
}
/* $Function : CALLMETHOD PLAY_StopSoundShare
== ===============================================================
== Description : 以共享方式关闭声音
== Argument : nPort 端口号
== :
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_StopSoundShare(LONG nPort)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
g_cDHPlayManage.pDHPlay[nPort]->SetDecAudio(FALSE) ;
std::vector<int>::iterator pos = g_cDHPlayManage.m_nShareSoundPortList.begin() ;
for (; pos != g_cDHPlayManage.m_nShareSoundPortList.end() ; ++pos)
{
if (*pos == nPort)
{
g_cDHPlayManage.m_nShareSoundPortList.erase(pos) ;
break;
}
}
return TRUE ;
}
/* $Function : CALLMETHOD PLAY_GetStreamOpenMode
== ===============================================================
== Description : 获得流模式类型。
== Argument : nPort 端口号
== :
== Return : 模式类型
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API LONG CALLMETHOD PLAY_GetStreamOpenMode(LONG nPort)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
return g_cDHPlayManage.m_nStreamMode[nPort];
}
/* $Function : CALLMETHOD PLAY_GetOverlayMode
== ===============================================================
== Description : 检查当前播放器是否使用了OVERLAY模式;
== Argument : nPort 端口号
== :
== Return : 是否使用了OVERLAY模式
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API LONG CALLMETHOD PLAY_GetOverlayMode(LONG nPort)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return 0 ;
}
if (g_cDHPlayManage.pDisplay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return 0 ;
}
return g_cDHPlayManage.pDisplay[nPort]->GetOverlayMode() ;
}
/* $Function : CALLMETHOD PLAY_GetColorKey
== ===============================================================
== Description : 获得OVERLAY表面使用的透明色;
== Argument : nPort 端口号
== :
== Return : 透明色
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API COLORREF CALLMETHOD PLAY_GetColorKey(LONG nPort)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDisplay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDisplay[nPort]->GetColorKey() ;
}
/* $Function : CALLMETHOD PLAY_GetVolume
== ===============================================================
== Description : 获得当前设置的音量
== Argument : nPort 端口号
== :
== Return : 音量
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API WORD CALLMETHOD PLAY_GetVolume(LONG nPort)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDisplay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDisplay[nPort]->GetVolume() ;
}
/* $Function : CALLMETHOD PLAY_GetPictureQuality
== ===============================================================
== Description : /获得当前图像质量
== Argument : nPort 端口号
== : bHighQuality[OUT] 是否高清
== Return : 成功 TRUE, 失败 FALSE
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_GetPictureQuality(LONG nPort,BOOL *bHighQuality)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (bHighQuality == NULL)
{
return FALSE ;
}
*bHighQuality = (BOOL) g_cDHPlayManage.m_nQuality[nPort];
return TRUE;
}
/* $Function : CALLMETHOD PLAY_GetSourceBufferRemain
== ===============================================================
== Description : 获得流播放模式下源缓冲剩余数据的大小
== Argument : nPort 端口号
== :
== Return :
== Modification : 2006/01/16 chenmy Create
== ===============================================================
*/
PLAYSDK_API DWORD CALLMETHOD PLAY_GetSourceBufferRemain(LONG nPort)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHPlay[nPort]->GetSourceBufferRemain();
}
/* $Function : CALLMETHOD PLAY_ResetSourceBuffer
== ===============================================================
== Description : 清除流播放模式下源缓冲区剩余数据
== Argument : nPort 端口号
== :
== Return :
== Modification : 2006/01/16 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_ResetSourceBuffer(LONG nPort)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
EnterCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[nPort]);
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
LeaveCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[nPort]);
return FALSE ;
}
#ifdef _DEBUG
char str[120] ;
sprintf(str,"PLAY_ResetSourceBuffer %d\n",nPort) ;
OutputDebugString(str) ;
#endif
#ifdef _DEBUG
OutputDebugString("before g_cDHPlayManage.pDHPlay[nPort]->ResetBufferRemain()");
#endif
BOOL bRet = g_cDHPlayManage.pDHPlay[nPort]->ResetBufferRemain();
#ifdef _DEBUG
OutputDebugString("after g_cDHPlayManage.pDHPlay[nPort]->ResetBufferRemain()");
#endif
LeaveCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[nPort]);
return bRet;
}
/* $Function : CALLMETHOD PLAY_SetSourceBufCallBack
== ===============================================================
== Description : 设置源缓冲区阀值和剩余数据小于等于阀值时的回调函数指针
== Argument : nPort 端口号
== :
== Return :
== Modification : 2006/01/16 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_SetSourceBufCallBack(LONG nPort,DWORD nThreShold,
void (CALLBACK * SourceBufCallBack)(long nPort,DWORD nBufSize,DWORD dwUser,void*pResvered),
DWORD dwUser,void *pReserved)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (!g_cDHPlayManage.pCallback[nPort])
{
g_cDHPlayManage.pCallback[nPort] = new CCallback(nPort);
}
return g_cDHPlayManage.pCallback[nPort]->SetSourceBufCallBack(SourceBufCallBack, nThreShold, dwUser, pReserved);
}
/* $Function : CALLMETHOD PLAY_ResetSourceBufFlag
== ===============================================================
== Description : 重置回调标志位为有效状态
== Argument : nPort 端口号
== :
== Return :
== Modification : 2006/01/16 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_ResetSourceBufFlag(LONG nPort)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pCallback[nPort] && g_cDHPlayManage.pCallback[nPort]->GetCBStatus(CBT_SourceBuf))
{
return g_cDHPlayManage.pCallback[nPort]->ResetSourceBufFlag();
}
return FALSE;
}
/* $Function : CALLMETHOD PLAY_SetDisplayBuf
== ===============================================================
== Description : 设置播放缓冲区(即解码后的图像缓冲区)大小
== Argument : nPort 端口号
== :
== Return :
== Modification : 2006/01/16 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_SetDisplayBuf(LONG nPort,DWORD nNum)
{
#ifdef _DEBUG
OutputDebugString("PLAY_SetDisplayBuf Enter\n") ;
#endif
if ((nNum < MIN_DIS_FRAMES)||(nNum > MAX_DIS_FRAMES))
{
return FALSE;
}
if (g_cDHPlayManage.CheckPort(nPort))
{
return FALSE;
}
BOOL iRet ;
iRet = g_cDHPlayManage.pDHPlay[nPort]->SetImgBufCount(nNum);
#ifdef _DEBUG
OutputDebugString("PLAY_SetDisplayBuf Leave\n") ;
#endif
return iRet ;
}
/* $Function : CALLMETHOD PLAY_GetDisplayBuf
== ===============================================================
== Description : 获得播放缓冲区最大缓冲的帧数;
== Argument : nPort 端口号
== :
== Return :
== Modification : 2006/01/16 chenmy Create
== ===============================================================
*/
PLAYSDK_API DWORD CALLMETHOD PLAY_GetDisplayBuf(LONG nPort)
{
if (g_cDHPlayManage.CheckPort(nPort))
{
return FALSE ;
}
return g_cDHPlayManage.pDHPlay[nPort]->GetImgBufCount();
}
/* $Function : CALLMETHOD PLAY_OneByOneBack
== ===============================================================
== Description : 单帧回放。每调用一次倒退一帧
== Argument : nPort 端口号
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_OneByOneBack(LONG nPort)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHPlay[nPort]->PlayBackOne();
}
/* $Function : CALLMETHOD PLAY_SetFileRefCallBack
== ===============================================================
== Description : 设置回调函数指针,文件索引建立后回调
== Argument : nPort 端口号
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_SetFileRefCallBack(LONG nPort, void (CALLBACK *pFileRefDone)(DWORD nPort,DWORD nUser),DWORD nUser)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (!g_cDHPlayManage.pCallback[nPort])
{
g_cDHPlayManage.pCallback[nPort] = new CCallback(nPort);
}
return g_cDHPlayManage.pCallback[nPort]->SetFileRefCallBack(pFileRefDone, nUser);
}
PLAYSDK_API BOOL CALLMETHOD PLAY_SetFileRefCallBackEx(LONG nPort, void (CALLBACK *pFileRefDoneEx)(DWORD nPort, BOOL bIndexCreated, DWORD nUser),DWORD nUser)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (!g_cDHPlayManage.pCallback[nPort])
{
g_cDHPlayManage.pCallback[nPort] = new CCallback(nPort);
}
return g_cDHPlayManage.pCallback[nPort]->SetFileRefCallBackEx(pFileRefDoneEx, nUser);
}
/* $Function : CALLMETHOD PLAY_SetCurrentFrameNum
== ===============================================================
== Description : 设置当前播放播放位置到指定帧号;根据帧号来定位播放位置
== Argument : nPort 端口号
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_SetCurrentFrameNum(LONG nPort,DWORD nFrameNum)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHPlay[nPort]->SetCurrentFrameNum(nFrameNum);
}
/* $Function : CALLMETHOD PLAY_GetKeyFramePos
== ===============================================================
== Description : 查找指定位置之前的关键帧位置
== Argument : nPort 端口号
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_GetKeyFramePos(LONG nPort,DWORD nValue, DWORD nType, PFRAME_POS pFramePos)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHFile[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHFile[nPort]->GetKeyFramePos(nValue, nType, pFramePos);
}
/* $Function : CALLMETHOD PLAY_GetNextKeyFramePos
== ===============================================================
== Description : 查找指定位置之后的关键帧位置
== Argument : nPort 端口号
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_GetNextKeyFramePos(LONG nPort,DWORD nValue, DWORD nType, PFRAME_POS pFramePos)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHFile[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHFile[nPort]->GetNextKeyFramePos(nValue, nType, pFramePos);
}
//Note: These funtion must be builded under win2000 or above with Microsoft Platform sdk.
// You can download the sdk from "http://www.microsoft.com/msdownload/platformsdk/sdkupdate/";
/* $Function : CALLMETHOD
== ===============================================================
== Description : 枚举系统中的显示设备
== Argument :
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
BOOL WINAPI Callback(GUID FAR *lpGUID,LPSTR pName,LPSTR pDesc,LPVOID pContext,HMONITOR hm )
{
DeviceInfo* devInfo = new DeviceInfo ;
devInfo->lpDeviceDescription = new char(strlen(pDesc)) ;
strcpy(devInfo->lpDeviceDescription,pDesc) ;
devInfo->lpDeviceName = new char(strlen(pName)) ;
strcpy(devInfo->lpDeviceName,pName) ;
// devInfo->hMonitor = new HMONITOR(hm) ;
g_cDHPlayManage.DeviceInfoList.push_back(devInfo) ;
return 0 ;
}
/* $Function : CALLBACK PLAY_InitDDrawDevice
== ===============================================================
== Description : 初始化DDraw设备
== Argument : nPort 端口号
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_InitDDrawDevice()
{
// HINSTANCE handle = LoadLibrary("ddraw.dll") ;
// if (!handle)
// return false;
//
// LPDIRECTDRAWENUMERATEEX lpDDEnumEx;
// lpDDEnumEx = (LPDIRECTDRAWENUMERATEEX) GetProcAddress(handle,
// "DirectDrawEnumerateExA");
//
// //列举出所有连接到桌面的显示设备,
// if (lpDDEnumEx)
// lpDDEnumEx(Callback, NULL, DDENUM_ATTACHEDSECONDARYDEVICES |
// DDENUM_NONDISPLAYDEVICES );
// else return false ;
//
// FreeLibrary(handle);
g_cDHPlayManage.m_supportmultidevice = 1;
return true ;
}
/* $Function : CALLMETHOD PLAY_ReleaseDDrawDevice
== ===============================================================
== Description : 释放枚举显示设备的过程中分配的资源
== Argument : nPort 端口号
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API void CALLMETHOD PLAY_ReleaseDDrawDevice()
{
// //释放向量中的数据
// for (int i = 0 ; i < g_cDHPlayManage.DeviceInfoList.size(); i++)
// {
// DeviceInfo* temp = g_cDHPlayManage.DeviceInfoList[i] ;
// delete temp->lpDeviceDescription ;
// delete temp->lpDeviceName ;
// // delete temp->hMonitor ;
// delete temp ;
// temp->lpDeviceDescription = NULL ;
// temp->lpDeviceName = NULL ;
// // temp->hMonitor = NULL ;
// temp = NULL ;
// }
//
// g_cDHPlayManage.DeviceInfoList.clear() ;
g_cDHPlayManage.m_supportmultidevice = 0;
}
/* $Function : CALLMETHOD PLAY_GetDDrawDeviceTotalNums
== ===============================================================
== Description : 获得系统中与windows桌面绑定的总的显示设备数目
== Argument :
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API DWORD CALLMETHOD PLAY_GetDDrawDeviceTotalNums()
{
return g_cDHPlayManage.DeviceInfoList.size() ;//些函数必须在CALLMETHODPLAY264_InitDDrawDevice之后调用
}
/* $Function : CALLMETHOD PLAY_SetDDrawDevice
== ===============================================================
== Description : 设置播放窗口使用的显卡
== Argument : nPort 端口号
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_SetDDrawDevice(LONG nPort,DWORD nDeviceNum)
{
return 0;
}
// #if (WINVER > 0x0400)
/* $Function : CALLMETHOD PLAY_GetDDrawDeviceInfo
== ===============================================================
== Description : 得到指定显卡和监视器信息;
== Argument : nPort 端口号
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_GetDDrawDeviceInfo(DWORD nDeviceNum,LPSTR lpDriverDescription,DWORD nDespLen,
LPSTR lpDriverName ,DWORD nNameLen,long *hhMonitor)
{
// if (nDeviceNum < 0 ||nDeviceNum > g_cDHPlayManage.DeviceInfoList.size())
// return false ;
//
// DeviceInfo* devInfo = g_cDHPlayManage.DeviceInfoList[nDeviceNum] ;
// memcpy(lpDriverDescription,devInfo->lpDeviceDescription,nDespLen) ;
// memcpy(lpDriverName,devInfo->lpDeviceName,nNameLen) ;
// // hhMonitor = devInfo->hMonitor ;
return true;
}
// #endif
/* $Function : CALLMETHOD PLAY_GetCapsEx
== ===============================================================
== Description : 获得指定显示设备的系统信息
== Argument : nPort 端口号
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API int CALLMETHOD PLAY_GetCapsEx(DWORD nDDrawDeviceNum)
{
return 0;
}
/* $Function : CALLMETHOD PLAY_ThrowBFrameNum
== ===============================================================
== Description : 设置不解码B帧帧数(不支持,因为没有B桢)
== Argument : nPort 端口号
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_ThrowBFrameNum(LONG nPort,DWORD nNum)
{
return TRUE;
}
/* $Function : CALLMETHOD PLAY_SetDisplayType
== ===============================================================
== Description : 设置显示的模式
== Argument : nPort 端口号
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_SetDisplayType(LONG nPort,LONG nType)
{
if (g_cDHPlayManage.CheckPort(nPort))
{
return FALSE;
}
else;
return g_cDHPlayManage.pDHPlay[nPort]->SetDisplayType(nType) ;
}
/* $Function : CALLMETHOD PLAY_GetDisplayType
== ===============================================================
== Description : 获得目前设置的显示模式
== Argument : nPort 端口号
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API long CALLMETHOD PLAY_GetDisplayType(LONG nPort)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHPlay[nPort]->GetDisplayType() ;
}
/* $Function :
== ===============================================================
== Description : 设置解码回调的流类型。
== Argument : nPort 端口号
== : nStream 1视频流,2音频流,3复合流
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_SetDecCBStream(LONG nPort,DWORD nStream)
{
if (g_cDHPlayManage.CheckPort(nPort))
{
return FALSE;
}
else;
return g_cDHPlayManage.pDHPlay[nPort]->SetDecCBType(nStream) ;
}
/* $Function : CALLMETHOD PLAY_SetDisplayRegion
== ===============================================================
== Description : 设置或增加显示区域。可以做局部放大显示。
== Argument : nPort 端口号
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_SetDisplayRegion(LONG nPort,DWORD nRegionNum, RECT *pSrcRect, HWND hDestWnd, BOOL bEnable)
{
if (g_cDHPlayManage.CheckPort(nPort))
{
return FALSE;
}
if (nRegionNum >= 16) //只能开16个子区域显示
{
return FALSE;
}
long width,height ;
g_cDHPlayManage.pDHPlay[nPort]->GetPictureSize(&width,&height) ;
g_cDHPlayManage.pDHPlay[nPort]->m_pDisplay->MulitiDisplay(nRegionNum,hDestWnd,pSrcRect,bEnable) ;
return TRUE;
}
/* $Function : CALLMETHOD PLAY_RefreshPlayEx
== ===============================================================
== Description : 刷新显示,为支持PLAY264_SetDisplayRegion而增加一个参数。
== Argument : nPort 端口号
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_RefreshPlayEx(LONG nPort,DWORD nRegionNum)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
g_cDHPlayManage.pDHPlay[nPort]->ReFreshEx(nRegionNum) ;
return TRUE ;
}
/*#if (WINVER > 0x0400)*/
//Note: The funtion must be builded under win2000 or above with Microsoft Platform sdk.
// You can download the sdk from http://www.microsoft.com/msdownload/platformsdk/sdkupdate/;
/* $Function : CALLMETHOD PLAY_SetDDrawDeviceEx
== ===============================================================
== Description : 设置播放窗口使用的显卡
== Argument : nPort 端口号
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_SetDDrawDeviceEx(LONG nPort,DWORD nRegionNum,DWORD nDeviceNum)
{
return 0;
}
/*#endif*/
/* $Function : CALLMETHOD PLAY_GetRefValue
== ===============================================================
== Description : 获取文件索引信息,以便下次打开同一个文件时直接使用这个信息
== Argument : nPort 端口号
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_GetRefValue(LONG nPort,BYTE *pBuffer, DWORD *pSize)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHFile[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHFile[nPort]->GetIndexInfo(pBuffer, pSize);
}
/* $Function : CALLMETHOD PLAY_SetRefValue
== ===============================================================
== Description : 设置文件索引
== Argument : nPort 端口号
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_SetRefValue(LONG nPort,BYTE *pBuffer, DWORD nSize)
{
if (g_cDHPlayManage.CheckPort(nPort))
{
return FALSE;
}
return g_cDHPlayManage.pDHFile[nPort]->SetIndexInfo(pBuffer, nSize);
}
/* $Function : CALLMETHOD PLAY_OpenStreamEx
== ===============================================================
== Description : 以音视频分开输入得方式打开流。
== Argument : nPort 端口号
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_OpenStreamEx(LONG nPort,PBYTE pFileHeadBuf,DWORD nSize,DWORD nBufPoolSize)
{
return PLAY_OpenStream(nPort,pFileHeadBuf,nSize,nBufPoolSize) ;
}
/* $Function : CALLMETHOD PLAY_CloseStreamEx
== ===============================================================
== Description : 关闭数据流
== Argument : nPort 端口号
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_CloseStreamEx(LONG nPort)
{
return PLAY_CloseStream(nPort) ;
}
/* $Function : CALLMETHOD PLAY_InputVideoData
== ===============================================================
== Description : 输入从卡上得到的视频流 (可以是复合流,但音频数据会被忽略)
== Argument : nPort 端口号
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_InputVideoData(LONG nPort,PBYTE pBuf,DWORD nSize)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHPlay[nPort]->InputVideoData(pBuf,nSize);
}
/* $Function : CALLMETHOD PLAY_InputAudioData
== ===============================================================
== Description : 输入从卡上得到的音频流;打开声音之后才能输入数据
== Argument : nPort 端口号
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_InputAudioData(LONG nPort,PBYTE pBuf,DWORD nSize)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHPlay[nPort]->InputAudioData(pBuf,nSize);
}
/* $Function : CALLMETHOD PLAY_RigisterDrawFun
== ===============================================================
== Description : 注册一个回调函数,获得当前表面的device context,如果是使用overlay表面,这个接口无效
== Argument : nPort 端口号
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_RigisterDrawFun(LONG nPort,void (CALLBACK* DrawFun)(long nPort,HDC hDc,LONG nUser),LONG nUser)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (!g_cDHPlayManage.pCallback[nPort])
{
g_cDHPlayManage.pCallback[nPort] = new CCallback(nPort);
}
return g_cDHPlayManage.pCallback[nPort]->SetDrawCallback(DrawFun, nUser);
}
PLAYSDK_API BOOL CALLMETHOD PLAY_RigisterDrawFunEx(LONG nPort, LONG nReginNum, void (CALLBACK* DrawFunEx)(long nPort,long nReginNum,HDC hDc,LONG nUser),LONG nUser)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (!g_cDHPlayManage.pCallback[nPort])
{
g_cDHPlayManage.pCallback[nPort] = new CCallback(nPort);
}
return g_cDHPlayManage.pCallback[nPort]->SetDrawExCallback(DrawFunEx, nReginNum, nUser);
}
/* $Function : CALLMETHOD PLAY_SetTimerType
== ===============================================================
== Description : 设置当前通道使用的定时器,注意:必须在Open之前调用
== Argument : nPort 端口号
== :
== Return :
== Modification : 2006/5/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_SetTimerType(LONG nPort,DWORD nTimerType,DWORD nReserved)
{
if (g_cDHPlayManage.CheckPort(nPort))
{
return FALSE;
}
else;
if ((nTimerType != TIMER_1) && (nTimerType != TIMER_2)) return FALSE;
if (nTimerType == TIMER_1)
{
MMRESULT timerTemp = timeSetEvent(1, 500, NULL, NULL, TIME_PERIODIC|TIME_CALLBACK_FUNCTION);
if (timerTemp == 0)
{
return FALSE;
}
timeKillEvent(timerTemp);
}
g_cDHPlayManage.m_dwTimerType[nPort] = nTimerType;
g_cDHPlayManage.pDHPlay[nPort]->m_nTimerType = nTimerType;
return TRUE;
}
/* $Function : CALLMETHOD PLAY_GetTimerType
== ===============================================================
== Description : 获得当前通道使用的定时器
== Argument : nPort 端口号
== :
== Return :
== Modification : 2006/5/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_GetTimerType(LONG nPort,DWORD *pTimerType,DWORD *pReserved)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
if (pTimerType == NULL)
{
return FALSE ;
}
*pTimerType = g_cDHPlayManage.pDHPlay[nPort]->m_nTimerType;
return TRUE;
}
/* $Function : CALLMETHOD PLAY_ResetBuffer
== ===============================================================
== Description : 清空播放器中的缓冲区
== Argument : nPort 端口号
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_ResetBuffer(LONG nPort,DWORD nBufType)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHPlay[nPort]->ResetBuffer(nBufType);
}
//
/* $Function : CALLMETHOD PLAY_GetBufferValue
== ===============================================================
== Description : 获取播放器中的缓冲区大小(帧数或者byte)。这个接口可以帮助用户了解缓冲区中的数据,
从而在网络延时方面有所估计
== Argument : nPort 端口号
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API DWORD CALLMETHOD PLAY_GetBufferValue(LONG nPort,DWORD nBufType)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHPlay[nPort]->GetBufferValue(nBufType);
}
/* $Function : CALLMETHOD PLAY_AdjustWaveAudio
== ===============================================================
== Description : 调整WAVE波形,可以改变声音的大小。它和PLAY264_SetVolume的不同在于,它是调整声音数据,只对该路其作用,
而CALLMETHODPLAY_SetVolume是调整声卡音量,对整个系统起作用
== Argument : nPort 端口号
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_AdjustWaveAudio(LONG nPort,LONG nCoefficient)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
if ((nCoefficient > MAX_WAVE_COEF)||(nCoefficient < MIN_WAVE_COEF))
{
return FALSE;
}
else;
return g_cDHPlayManage.pDHPlay[nPort]->SetCoefficient(nCoefficient);
}
/* $Function : CALLMETHOD PLAY_SetVerifyCallBack
== ===============================================================
== Description : 注册一个回调函数,校验数据是否被修改,实现水印功能
== Argument : nPort 端口号
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_SetVerifyCallBack(LONG nPort, DWORD nBeginTime, DWORD nEndTime,
void (CALLBACK * funVerify)(long nPort, FRAME_POS * pFilePos, DWORD bIsVideo, DWORD nUser), DWORD nUser)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (!g_cDHPlayManage.pCallback[nPort])
{
g_cDHPlayManage.pCallback[nPort] = new CCallback(nPort);
}
return g_cDHPlayManage.pCallback[nPort]->SetVerifyCallBack(funVerify, nBeginTime, nEndTime, nUser);
}
/* $Function : CALLMETHOD PLAY_SetAudioCallBack
== ===============================================================
== Description : 音频回调
== Argument : nPort 端口号
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_SetAudioCallBack(LONG nPort, void (CALLBACK * funAudio)(long nPort, char * pAudioBuf,
long nSize, long nStamp, long nType, long nUser), long nUser)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (!g_cDHPlayManage.pCallback[nPort])
{
g_cDHPlayManage.pCallback[nPort] = new CCallback(nPort);
}
return g_cDHPlayManage.pCallback[nPort]->SetAudioCallBack(funAudio,nUser);
}
/* $Function : CALLMETHOD PLAY_SetEncTypeChangeCallBack
== ===============================================================
== Description : 解码时图象格式发生改变通知用户的回调函数;在打开文件前使用
== Argument : nPort 端口号
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_SetEncTypeChangeCallBack(LONG nPort,void(CALLBACK *funEncChange)(long nPort,long nUser),long nUser)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (!g_cDHPlayManage.pCallback[nPort])
{
g_cDHPlayManage.pCallback[nPort] = new CCallback(nPort);
}
return g_cDHPlayManage.pCallback[nPort]->SetEncChangeCallBack(funEncChange, nUser);
}
/* $Function : CALLMETHOD PLAY_SetColor
== ===============================================================
== Description : 设置视频参数(显示设置)
== Argument : nPort 端口号
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_SetColor(LONG nPort, DWORD nRegionNum, int nBrightness, int nContrast, int nSaturation, int nHue)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
g_cDHPlayManage.pDHPlay[nPort]->SetColor(nRegionNum, nBrightness, nContrast, nSaturation, nHue);
return TRUE;
}
/* $Function : CALLMETHOD PLAY_GetColor
== ===============================================================
== Description : 获得视频参数
== Argument : nPort 端口号
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_GetColor(LONG nPort, DWORD nRegionNum, int *pBrightness, int *pContrast, int *pSaturation, int *pHue)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
g_cDHPlayManage.pDHPlay[nPort]->GetColor(nRegionNum, pBrightness, pContrast, pSaturation, pHue);
return TRUE;
}
/* $Function : CALLMETHOD PLAY_SetEncChangeMsg
== ===============================================================
== Description : 设置当解码时编码格式变化时发送的消息
== Argument : nPort 端口号
== :
== Return :
== Modification : 2005/12/15 chenmy Create
== ===============================================================
*/
PLAYSDK_API BOOL CALLMETHOD PLAY_SetEncChangeMsg(LONG nPort,HWND hWnd,UINT nMsg)
{
if (g_cDHPlayManage.CheckPort(nPort))
{
return FALSE;
}
g_cDHPlayManage.pMsgEncChang[nPort]->hWnd = hWnd ;
g_cDHPlayManage.pMsgEncChang[nPort]->nMsg = nMsg ;
g_cDHPlayManage.pMsgEncChang[nPort]->nMsgFlag = TRUE ;
return TRUE ;
}
PLAYSDK_API BOOL CALLMETHOD PLAY_SetMDRange(LONG nPort,RECT* MDRect,DWORD nVauleBegin,DWORD nValueEnd,DWORD nType)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHFile[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHFile[nPort]->SetMDRange(nVauleBegin, nValueEnd, nType, MDRect) ;
}
PLAYSDK_API BOOL CALLMETHOD PLAY_SetMDThreShold(LONG nPort, DWORD ThreShold)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHFile[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHFile[nPort]->SetMDThreShold(ThreShold) ;
}
PLAYSDK_API DWORD CALLMETHOD PLAY_GetMDPosition(LONG nPort, DWORD Direction, DWORD nFrame, DWORD* MDValue)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHFile[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHFile[nPort]->GetMDPosition(Direction, nFrame, MDValue) ;
}
PLAYSDK_API BOOL CALLMETHOD PLAY_SetFileEndCallBack(LONG nPort, void (CALLBACK *pFileEnd)(DWORD nPort,DWORD nUser),DWORD nUser)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (!g_cDHPlayManage.pCallback[nPort])
{
g_cDHPlayManage.pCallback[nPort] = new CCallback(nPort);
}
return g_cDHPlayManage.pCallback[nPort]->SetFileEndCallBack(pFileEnd, nUser);
}
PLAYSDK_API BOOL CALLMETHOD PLAY_StartDataRecord(LONG nPort, char *sFileName, int idataType)
{
if (g_cDHPlayManage.CheckPort(nPort))
{
return FALSE;
}
return g_cDHPlayManage.pDHPlay[nPort]->StartDataRecord(sFileName, idataType) ;
}
PLAYSDK_API BOOL CALLMETHOD PLAY_StopDataRecord(LONG nPort)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHPlay[nPort]->StopDataRecord() ;
}
PLAYSDK_API BOOL CALLMETHOD PLAY_StartAVIResizeConvert(LONG nPort, char *sFileName, long lWidth, long lHeight)
{
if (g_cDHPlayManage.CheckPort(nPort))
{
return FALSE;
}
return g_cDHPlayManage.pDHPlay[nPort]->StartAVIResizeConvert(sFileName, lWidth, lHeight) ;
}
PLAYSDK_API BOOL CALLMETHOD PLAY_StopAVIResizeConvert(LONG nPort)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHPlay[nPort]->StopDataRecord() ;
}
PLAYSDK_API BOOL CALLMETHOD PLAY_AdjustFluency(LONG nPort, int level)
{
if (g_cDHPlayManage.CheckPort(nPort))
{
return FALSE;
}
/*
int adjust_bufnum, adjust_range;
switch (level)
{
case 0:
adjust_bufnum = 15;
adjust_range = 0;
break;
case 1:
adjust_bufnum = 10;
adjust_range = 2;
break;
case 2:
adjust_bufnum = 7;
adjust_range = 4;
break;
case 3://默认
adjust_bufnum = 4;
adjust_range = 5;
break;
case 4:
adjust_bufnum = 3;
adjust_range = 10;
break;
case 5:
adjust_bufnum = 2;
adjust_range = 15;
break;
case 6:
adjust_bufnum = 0;
adjust_range = 20;
break;
default:
return FALSE;
}
return g_cDHPlayManage.pDHPlay[nPort]->AdjustFluency(adjust_bufnum, adjust_range);
*/
//1最流畅 7最实时,默认为4
if (level > 7 || level < 1)
{
return FALSE;
}
g_cDHPlayManage.m_nFluency[nPort] = 8 - level;
return TRUE;
}
PLAYSDK_API BOOL CALLMETHOD PLAY_ChangeRate(LONG nPort, int rate)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHPlay[nPort]->FixRate(rate) ;
}
PLAYSDK_API BOOL CALLMETHOD PLAY_SetDemuxCallBack(LONG nPort, void (CALLBACK* DemuxCBFun)(long nPort,char * pBuf, long nSize,void * pParam, long nReserved,long nUser), long nUser)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (!g_cDHPlayManage.pCallback[nPort])
{
g_cDHPlayManage.pCallback[nPort] = new CCallback(nPort);
}
return g_cDHPlayManage.pCallback[nPort]->SetDemuxCallBack(DemuxCBFun, nUser);
}
PLAYSDK_API BOOL CALLMETHOD PLAY_QueryInfo(LONG nPort , int cmdType
, char* buf, int buflen, int* returnlen)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
if (buf == 0 || returnlen == 0)
{
return FALSE;
}
BOOL bRet = TRUE;
int rate;
switch (cmdType)
{
case PLAY_CMD_GetTime:
*returnlen = sizeof(int)*6;
if (buflen < 24)
{
break;
}
g_cDHPlayManage.pDHPlay[nPort]->GetTimeStr(buf,buflen);
break;
case PLAY_CMD_GetFileRate:
*returnlen = 4;
if (buflen < 4)
{
break;
}
rate = g_cDHPlayManage.pDHPlay[nPort]->GetFileRate();
buf[0] = rate&0xff;
buf[1] = rate&0xff00;
buf[2] = rate&0xff0000;
buf[3] = rate&0xff000000;
break;
case PLAY_CMD_GetMediaInfo:
bRet = g_cDHPlayManage.pDHPlay[nPort]->GetMediaInfo(buf,buflen);
*returnlen = sizeof(MEDIA_INFO);
break;
}
return bRet;
}
PLAYSDK_API BOOL CALLMETHOD PLAY_OpenAudioRecord(pCallFunction pProc, LONG nBitsPerSample, LONG nSamplesPerSec, long nLength, long nReserved, LONG nUser)
{
BOOL bRet = TRUE;
if (nBitsPerSample == 0 || nSamplesPerSec == 0)
{
return FALSE;
}
EnterCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[0]);
if (g_cDHPlayManage.pAudioRecored == NULL)
{
g_cDHPlayManage.pAudioRecored = new CHI_PLAY_AudioIn;
}
bRet = g_cDHPlayManage.pAudioRecored->Start(pProc, nBitsPerSample, nSamplesPerSec, nLength, nReserved, nUser);
LeaveCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[0]);
return bRet;
}
PLAYSDK_API BOOL CALLMETHOD PLAY_CloseAudioRecord()
{
BOOL bRet = TRUE;
EnterCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[0]);
if (g_cDHPlayManage.pAudioRecored == NULL)
{
LeaveCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[0]);
return FALSE;
}
g_cDHPlayManage.pAudioRecored->Stop();
LeaveCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[0]);
return bRet;
}
PLAYSDK_API BOOL CALLMETHOD PLAY_SetWaterMarkCallBack(LONG nPort, GetWaterMarkInfoCallbackFunc pFunc, long nUser)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHPlay[nPort]->SetWaterMarkCallbackFunc(pFunc, nUser);
}
PLAYSDK_API BOOL CALLMETHOD PLAY_SetPandoraWaterMarkCallBack(LONG nPort, GetWaterMarkInfoCallbackFunc pFunc, long nUser)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHPlay[nPort]->SetWaterPandoraMarkCallbackFunc(pFunc, nUser);
}
PLAYSDK_API BOOL CALLMETHOD PLAY_SetIVSCallBack(LONG nPort, GetIVSInfoCallbackFunc pFunc, long nUser)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
return g_cDHPlayManage.pDHPlay[nPort]->SetIVSCallbackFunc(pFunc, nUser);
}
//
DWORD CALLMETHOD PLAY_CreateFile(LONG nPort,LPSTR sFileName)
{
DWORD dRet = 1;
{
AutoLock lock(&g_PlayCritsec);
int index;
for (index = 1; index < FUNC_MAX_PORT; index++)
{
if(g_play[index] == 0)
{
g_play[index] = 1;
break;
}
}
if (index >= FUNC_MAX_PORT)
{
return 0;
}
dRet = index;
}
BOOL bRet = PLAY_OpenFile(dRet, sFileName);
if (bRet == FALSE)
{
return 0;
}
return dRet;
}
PLAYSDK_API BOOL CALLMETHOD PLAY_DestroyFile(LONG nPort)
{
if(!PLAY_CloseFile(nPort))
{
return FALSE ;
}
g_play[nPort] = 0;
return TRUE;
}
PLAYSDK_API DWORD CALLMETHOD PLAY_CreateStream(DWORD nBufPoolSize)
{
DWORD dRet = 1;
{
AutoLock lock(&g_PlayCritsec);
int index;
for (index = 1; index < FUNC_MAX_PORT; index++)
{
if(g_play[index] == 0)
{
g_play[index] = 1;
break;
}
}
if (index >= FUNC_MAX_PORT)
{
return 0;
}
dRet = index;
}
BOOL bRet = PLAY_OpenStream(dRet, 0, 0, nBufPoolSize);
if (bRet == FALSE)
{
return 0;
}
return dRet;
}
PLAYSDK_API BOOL CALLMETHOD PLAY_DestroyStream(LONG nPort)
{
if(!PLAY_CloseStream(nPort))
{
return FALSE ;
}
g_play[nPort] = 0;
return TRUE;
}
PLAYSDK_API BOOL CALLMETHOD PLAY_SetRotateAngle(LONG nPort , int nrotateType)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
BOOL bRet = FALSE;
EnterCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[nPort]);
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
LeaveCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[nPort]);
return FALSE ;
}
bRet = g_cDHPlayManage.pDHPlay[nPort]->SetRotateAngle(nrotateType);
LeaveCriticalSection(&g_cDHPlayManage.m_interfaceCritSec[nPort]);
return bRet;
}
PLAYSDK_API BOOL CALLMETHOD PLAY_GetPicBMP(LONG nPort, PBYTE pBmpBuf, DWORD dwBufSize, DWORD* pBmpSize)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
if (pBmpBuf == NULL)
{
return FALSE ;
}
BYTE* pDataBuf = g_cDHPlayManage.pDHPlay[nPort]->GetLastFrame();
long width , height ;
g_cDHPlayManage.pDHPlay[nPort]->GetPictureSize(&width,&height);
DWORD dwReqLen = width*height*3 + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
if (dwBufSize < dwReqLen)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_MEMORY_TOOSMALL;
return FALSE;
}
memset(pBmpBuf, 0, dwBufSize);
Convert2BMP(pBmpBuf, pBmpSize, (BYTE*)pDataBuf, width, height);
return TRUE;
}
PLAYSDK_API BOOL CALLMETHOD PLAY_GetPicJPEG(LONG nPort, PBYTE pJpegBuf, DWORD dwBufSize, DWORD* pJpegSize, int quality)
{
if (nPort < 0 || nPort >= FUNC_MAX_PORT ) //端口号超出范围
{
return FALSE ;
}
if (g_cDHPlayManage.pDHPlay[nPort] == NULL)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_ORDER_ERROR ;
return FALSE ;
}
if (pJpegBuf == NULL)
{
return FALSE ;
}
BYTE* pDataBuf = g_cDHPlayManage.pDHPlay[nPort]->GetLastFrame();
long width , height ;
g_cDHPlayManage.pDHPlay[nPort]->GetPictureSize(&width,&height);
DWORD dwReqLen = width*height*3/2;
if (dwBufSize < dwReqLen)
{
g_cDHPlayManage.m_error[nPort] = DH_PLAY_MEMORY_TOOSMALL;
return FALSE;
}
memset(pJpegBuf, 0, dwBufSize);
JpegEncode(pJpegBuf, pDataBuf, (int*)pJpegSize, width, height, YV12, quality);
return TRUE;
}
PLAYSDK_API int CALLMETHOD PLAY_OpenYuvRender(int port, HWND hwnd, void (CALLBACK* DrawFun)(int nPort,HDC hDc))
{
return g_cDHPlayManage.OpenYuvRender(port, hwnd, DrawFun);
}
PLAYSDK_API int CALLMETHOD PLAY_RenderYuv(int port, unsigned char* py, unsigned char* pu, unsigned char* pv, int width, int height)
{
return g_cDHPlayManage.RenderYuv(port, py, pu, pv, width, height);
}
PLAYSDK_API int CALLMETHOD PLAY_CloseYuvRender(int port)
{
return g_cDHPlayManage.CloseYuvRender(port);
} | [
"guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd"
]
| [
[
[
1,
4000
]
]
]
|
1cc0af16460d41e8f70dd859f0fb7044af7b4f88 | be2e23022d2eadb59a3ac3932180a1d9c9dee9c2 | /GameServer/MapGroupKernel/PoliceWanted.h | 4b5bb700aa56d663f6bdaf8e2af3577efc2e4fa9 | []
| no_license | cronoszeu/revresyksgpr | 78fa60d375718ef789042c452cca1c77c8fa098e | 5a8f637e78f7d9e3e52acdd7abee63404de27e78 | refs/heads/master | 2020-04-16T17:33:10.793895 | 2010-06-16T12:52:45 | 2010-06-16T12:52:45 | 35,539,807 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 797 | h |
#pragma once
#include "ThreadSafety.h"
#include <deque>
#include <string>
typedef struct {
OBJID idUser;
string strName;
string strSynName;
int nPk;
int nLev;
}PoliceWantedStruct;
#define PKVALUE_BADGUY 1000
class CCriticalSection;
class CUser;
class CPoliceWanted
{
public:
CPoliceWanted();
virtual ~CPoliceWanted();
// interface
bool AddWanted (CUser* pUser);
bool DelWanted (OBJID idUser);
PoliceWantedStruct* GetWantedByIndex(int idx);
PoliceWantedStruct* GetWanted (OBJID idUser);
int GetWantedAmount (void) { return m_setWanted.size(); }
static CPoliceWanted s_objPoliceWanted;
protected:
deque<PoliceWantedStruct> m_setWanted;
// static
static LOCK_DECLARATION;
};
extern CPoliceWanted& PoliceWanted(void);
| [
"rpgsky.com@cc92e6ba-efcf-11de-bf31-4dec8810c1c1"
]
| [
[
[
1,
43
]
]
]
|
4cc0760f2205d5c3bfe15c3f8b0a12220a18afe9 | fb71c08b1c1e7ea4d7abc82e65b36272069993e1 | /src/CFontMgr.cpp | 5d182945046c801a2576c999b196ad3f86363079 | []
| no_license | cezarygerard/fpteacher | 1bb4ea61bc86cbadcf47a810c8bb441f598d278a | 7bdfcf7c047caa9382e22a9d26a2d381ce2d9166 | refs/heads/master | 2021-01-23T03:47:54.994165 | 2010-03-25T01:12:04 | 2010-03-25T01:12:04 | 39,897,391 | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 4,975 | cpp | /** @file CFontMgr.cpp
* @author Sebastian Łuczak
* @date 2010.02.20
* @version 0.2
* @brief klasa CFontMgr
*
*
*/
#include "CFontMgr.hpp"
using namespace logging;
CFontMgr::CFontMgr() : callListOffset_(0)
{
CLog::getInstance()->sss << "CFontMgr::CFontMgr: konstruktor CFontMgr" << endl;
logs(CLog::getInstance()->sss.str(), INFO);
}
CFontMgr::~CFontMgr()
{
FontsMap::iterator i, begin = fonts_.begin(), end = fonts_.end();
for ( i = begin ; i != end ; ++i )
{
glDeleteLists(i->second.get<1>(),128);
}
fonts_.clear();
CLog::getInstance()->sss << "CFontMgr::CFontMgr: zniszczony" << endl;
logs(CLog::getInstance()->sss.str(), INFO);
}
GLuint CFontMgr::loadFont(const string filename)
{
HCSprite temp_sprite_handle;
temp_sprite_handle = CSpriteMgr::getInstance()->getCSprite(utils::PATH_FONTS+filename);
CLog::getInstance()->sss << "CFontMgr::loadFont: zaladowano czcionke z pliku " << filename << endl;
logs(CLog::getInstance()->sss.str(), INFO);
return CSpriteMgr::getInstance()->getCSpritePtr(temp_sprite_handle)->getTexID();
}
GLvoid CFontMgr::buildFont(const string filename, int size) // Build Our Font Display List
{
GLfloat cx; // Holds Our X Character Coord
GLfloat cy; // Holds Our Y Character Coord
GLuint texID;
GLuint loop;
float interval = 1/static_cast<float>(size);
texID = loadFont(filename);
callListOffset_ = glGenLists(128); // Creating 128 Display Lists
glBindTexture(GL_TEXTURE_2D, texID); // Select Our Font Texture
for (loop=0; loop<128; loop++) // Loop Through All 128 Lists
{
cx=static_cast<GLfloat>(loop%size)/static_cast<float>(size); // X Position Of Current Character
cy=static_cast<GLfloat>(loop/size)/static_cast<float>(size); // Y Position Of Current Character
glNewList(callListOffset_+loop,GL_COMPILE); // Start Building A List
glBegin(GL_TRIANGLE_STRIP); // Use A Quad For Each Character
glTexCoord2f(cx,cy); // Texture Coord (Bottom Left) /// ROZKMNINIC
glVertex2i(0,0); // Vertex Coord (Bottom Left)
glTexCoord2f(cx+interval,cy); // Texture Coord (Bottom Right)
glVertex2i(size,0); // Vertex Coord (Bottom Right)
glTexCoord2f(cx,cy+(interval)); // Texture Coord (Top Right)
glVertex2i(0,size); // Vertex Coord (Top Right)
glTexCoord2f(cx+interval,cy+(interval)); // Texture Coord (Top Left)
glVertex2i(size,size); // Vertex Coord (Top Left)
glEnd(); // Done Building Our Quad (Character)
glTranslated(16,0,0); // Move To The Right Of The Character
glEndList(); // Done Building The Display List
}
fonts_.insert( std::make_pair(filename, boost::make_tuple(size, callListOffset_, texID)));
CLog::getInstance()->sss << "CFontMgr::buildFont: zbudowano czcionke z pliku " << filename << endl;
logs(CLog::getInstance()->sss.str(), INFO);
}
void CFontMgr::reloadAllFonts()
{
FontsMap fonts_map;
BOOST_FOREACH( FontPair p, fonts_)
{
fonts_map.insert(p);
}
BOOST_FOREACH( FontPair p, fonts_map)
{
killFont(p.first);
buildFont(p.first, p.second.get<0>());
}
}
GLvoid CFontMgr::killFont(const string fontname) // Delete The Font From Memory
{
string name = fontname;
if(name.find(".png") == -1)
name = name+ ".png";
FontsMap::iterator font = fonts_.find(name);
if(font != fonts_.end() )
{
glDeleteLists(fonts_.find(name)->second.get<1>(),128);
fonts_.erase(name);
}
CLog::getInstance()->sss << "CFontMgr::killFont: usunieto font z managera " << fontname << endl;
logs(CLog::getInstance()->sss.str(), INFO);
}
GLvoid CFontMgr::printText(const int x,const int y, const string text, const string fontname)
{
string name = fontname;
if(name.find(".png") == -1)
name = name+ ".png";
FontsMap::iterator font = fonts_.find(name);
if(font != fonts_.end() )
{
//Dobierz barwe wyswietlania
glColor4ub(255,255,255,255);
//Wlacz mieszanie barw
glEnable(GL_BLEND);
//Wylacz test ZBufora
glDisable(GL_DEPTH_TEST);
//Ustaw funkcje mieszania barw z kanalem alpha (przezroczystosc)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//doczep teksture
glBindTexture(GL_TEXTURE_2D, font->second.get<2>()); // Select Our Font Texture
glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix
glPushMatrix(); // Store The Modelview Matrix
glLoadIdentity(); // Reset The Modelview Matrix
glTranslatef(static_cast<float>(x),static_cast<float>(y),0); // Position The Text (0,0 - Bottom Left)
glListBase(font->second.get<1>()-32);
glCallLists(text.length(),GL_BYTE, text.c_str()); // Write The Text To The Screen
glPopMatrix(); // Restore The Old Projection Matrix
glDisable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
glColor4ub(255,255,255,255);
}
}
//~~CFontMgr.hpp
| [
"fester3000@8e29c490-c8d6-11de-b6dc-25c59a28ecba"
]
| [
[
[
1,
145
]
]
]
|
8b8e201ff20094fa2912f8e5ad2378438de04a57 | 138a353006eb1376668037fcdfbafc05450aa413 | /source/TwoHitMover.cpp | d61b7b2ee73a9d45c21a91da0706c3d4d112e460 | []
| no_license | sonicma7/choreopower | 107ed0a5f2eb5fa9e47378702469b77554e44746 | 1480a8f9512531665695b46dcfdde3f689888053 | refs/heads/master | 2020-05-16T20:53:11.590126 | 2009-11-18T03:10:12 | 2009-11-18T03:10:12 | 32,246,184 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,336 | cpp | #include "TwoHitMover.h"
#include "GameServices.h"
#include "TriggerEvent.h"
#include "GameEvent.h"
#include "EventManager.h"
TwoHitMover::TwoHitMover(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 &listenfor, const Ogre::Vector3 &dest)
: PuzzleEntity(gs,collisionWorld,parentNode,pos,size,entityName,modelFile,listenfor)
{//Only listens, does not send triggers
mDest = dest;
hits = 0;
registerListener();
}
void TwoHitMover::moveToDest(){
//moves self to destination position. Work on this later to get a smooth motion.
//mGameServices->debugOut("TwoHitMover relocating to destination");
this->setPos(mDest);
//this->update();
}
void TwoHitMover::listenCallback(GameEvent *evnt){
//execute moveToDest() when recieve
//mGameServices->debugOut("%s recieved trigger event: %s", this->mName.c_str(),mListenFor.c_str());
hits++;
if (hits > 1){
moveToDest();
}
}
void TwoHitMover::registerListener(){
//mGameServices->debugOut("%s registered listener for: %s",this->mName.c_str(), mListenFor.c_str());
mGameServices->events()->addListener(mListenFor, this, &TwoHitMover::listenCallback);
} | [
"Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e"
]
| [
[
[
1,
35
]
]
]
|
345e5019300615581e71aaaf3442a94a0fb4a97d | 3eae1d8c99d08bca129aceb7c2269bd70e106ff0 | /trunk/Codes/CLR/Libraries/CorLib/corlib_native_System_RuntimeType.cpp | 1ec274698f9725d6b84107e3741ee7aa7b5345c3 | []
| no_license | yuaom/miniclr | 9bfd263e96b0d418f6f6ba08cfe4c7e2a8854082 | 4d41d3d5fb0feb572f28cf71e0ba02acb9b95dc1 | refs/heads/master | 2023-06-07T09:10:33.703929 | 2010-12-27T14:41:18 | 2010-12-27T14:41:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,160 | cpp | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "CorLib.h"
HRESULT Library_corlib_native_System_RuntimeType::get_Assembly___SystemReflectionAssembly( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
TINYCLR_HEADER();
CLR_RT_TypeDef_Instance td;
TINYCLR_CHECK_HRESULT(GetTypeDescriptor( stack.Arg0(), td, NULL ));
{
CLR_RT_Assembly_Index idx; idx.Set( td.Assembly() );
CLR_RT_HeapBlock& top = stack.PushValue();
top.SetReflection( idx );
}
TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_RuntimeType::get_Name___STRING( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
TINYCLR_HEADER();
TINYCLR_CHECK_HRESULT(GetName( stack.Arg0(), false, stack.PushValueAndClear() ));
TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_RuntimeType::get_FullName___STRING( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
TINYCLR_HEADER();
TINYCLR_CHECK_HRESULT(GetName( stack.Arg0(), true, stack.PushValueAndClear() ));
TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_RuntimeType::get_BaseType___SystemType( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
TINYCLR_HEADER();
CLR_RT_TypeDef_Instance td;
CLR_UINT32 levels;
CLR_RT_HeapBlock& top = stack.PushValueAndClear();
TINYCLR_CHECK_HRESULT(GetTypeDescriptor( stack.Arg0(), td, &levels ));
if(levels > 0)
{
top.SetReflection( g_CLR_RT_WellKnownTypes.m_Array );
}
else if(td.SwitchToParent())
{
top.SetReflection( td );
}
TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_RuntimeType::GetMethods___SZARRAY_SystemReflectionMethodInfo__SystemReflectionBindingFlags( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
return Library_corlib_native_System_Type::GetMethods( stack, NULL, stack.Arg1().NumericByRef().s4, NULL, 0, true );
}
HRESULT Library_corlib_native_System_RuntimeType::GetField___SystemReflectionFieldInfo__STRING__SystemReflectionBindingFlags( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
return Library_corlib_native_System_Type::GetFields( stack, stack.Arg1().RecoverString(), stack.Arg2().NumericByRef().s4, false );
}
HRESULT Library_corlib_native_System_RuntimeType::GetFields___SZARRAY_SystemReflectionFieldInfo__SystemReflectionBindingFlags( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
return Library_corlib_native_System_Type::GetFields( stack, NULL, stack.Arg1().NumericByRef().s4, true );
}
HRESULT Library_corlib_native_System_RuntimeType::GetInterfaces___SZARRAY_SystemType( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
TINYCLR_HEADER();
CLR_RT_TypeDef_Instance td;
CLR_RT_HeapBlock& top = stack.PushValueAndClear();
CLR_RT_HeapBlock* ptr;
TINYCLR_CHECK_HRESULT(GetTypeDescriptor( stack.Arg0(), td ));
//
// Scan the list of interfaces.
//
CLR_RT_SignatureParser parser; parser.Initialize_Interfaces( td.m_assm, td.m_target );
CLR_RT_SignatureParser::Element res;
TINYCLR_CHECK_HRESULT(CLR_RT_HeapBlock_Array::CreateInstance( top, parser.Available(), g_CLR_RT_WellKnownTypes.m_Type ));
ptr = (CLR_RT_HeapBlock*)top.DereferenceArray()->GetFirstElement();
while(parser.Available() > 0)
{
TINYCLR_CHECK_HRESULT(parser.Advance( res ));
ptr->SetReflection( res.m_cls );
ptr++;
}
TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_RuntimeType::GetElementType___SystemType( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
TINYCLR_HEADER();
CLR_RT_TypeDescriptor desc;
CLR_RT_TypeDescriptor descSub;
CLR_RT_HeapBlock& top = stack.PushValueAndClear();
TINYCLR_CHECK_HRESULT(desc.InitializeFromReflection( stack.Arg0().ReflectionDataConst() ));
if(desc.GetElementType( descSub ))
{
top.SetReflection( descSub.m_reflex );
}
TINYCLR_NOCLEANUP();
}
//--//
HRESULT Library_corlib_native_System_RuntimeType::GetTypeDescriptor( CLR_RT_HeapBlock& arg, CLR_RT_TypeDef_Instance& inst, CLR_UINT32* levels )
{
NATIVE_PROFILE_CLR_CORE();
return CLR_RT_ReflectionDef_Index::Convert( arg, inst, levels ) ? S_OK : CLR_E_NULL_REFERENCE;
}
HRESULT Library_corlib_native_System_RuntimeType::GetTypeDescriptor( CLR_RT_HeapBlock& arg, CLR_RT_TypeDef_Instance& inst )
{
NATIVE_PROFILE_CLR_CORE();
TINYCLR_HEADER();
CLR_UINT32 levels;
TINYCLR_CHECK_HRESULT(GetTypeDescriptor( arg, inst, &levels ));
if(levels > 0)
{
inst.InitializeFromIndex( g_CLR_RT_WellKnownTypes.m_Array );
}
TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_RuntimeType::GetName( CLR_RT_HeapBlock& arg, bool fFullName, CLR_RT_HeapBlock& res )
{
NATIVE_PROFILE_CLR_CORE();
TINYCLR_HEADER();
CLR_RT_TypeDef_Instance td;
CLR_UINT32 levels;
char rgBuffer[ 256 ];
LPSTR szBuffer;
size_t iBuffer;
TINYCLR_CHECK_HRESULT(GetTypeDescriptor( arg, td, &levels ));
szBuffer = rgBuffer;
iBuffer = MAXSTRLEN(rgBuffer);
TINYCLR_CHECK_HRESULT(g_CLR_RT_TypeSystem.BuildTypeName( td, szBuffer, iBuffer, fFullName ? CLR_RT_TypeSystem::TYPENAME_FLAGS_FULL : 0, levels ));
TINYCLR_SET_AND_LEAVE(CLR_RT_HeapBlock_String::CreateInstance( res, rgBuffer ));
TINYCLR_NOCLEANUP();
}
| [
"[email protected]"
]
| [
[
[
1,
186
]
]
]
|
c896545876fdaf6c90ad2f8f4accde5aaa37d6dc | b5ad65ebe6a1148716115e1faab31b5f0de1b493 | /src/Tree/TreeItem.cpp | c6bbd0e58f66d9311624204b7f7ce819955b0917 | []
| no_license | gasbank/aran | 4360e3536185dcc0b364d8de84b34ae3a5f0855c | 01908cd36612379ade220cc09783bc7366c80961 | refs/heads/master | 2021-05-01T01:16:19.815088 | 2011-03-01T05:21:38 | 2011-03-01T05:21:38 | 1,051,010 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 997 | cpp | #include "TreePch.h"
#include "TreeItem.h"
//! [0]
TreeItem::TreeItem(const QList<QVariant> &data, TreeItem *parent)
{
parentItem = parent;
itemData = data;
}
//! [0]
//! [1]
TreeItem::~TreeItem()
{
qDeleteAll(childItems);
}
//! [1]
//! [2]
void TreeItem::appendChild(TreeItem *item)
{
childItems.append(item);
}
//! [2]
//! [3]
TreeItem *TreeItem::child(int row)
{
return childItems.value(row);
}
//! [3]
//! [4]
int TreeItem::childCount() const
{
return childItems.count();
}
//! [4]
//! [5]
int TreeItem::columnCount() const
{
return itemData.count();
}
//! [5]
//! [6]
QVariant TreeItem::data(int column) const
{
return itemData.value(column);
}
//! [6]
//! [7]
TreeItem *TreeItem::parent()
{
return parentItem;
}
//! [7]
//! [8]
int TreeItem::row() const
{
if (parentItem)
return parentItem->childItems.indexOf(const_cast<TreeItem*>(this));
return 0;
}
//! [8]
| [
"[email protected]"
]
| [
[
[
1,
69
]
]
]
|
eb2c8ebe103e1d005f273cf94cbbcb2146e7032e | 0d5c8865066a588602d621f3ea1657f9abb14768 | /regen.cpp | c82583d8940710f5b81f52420078950a9934c5e1 | []
| no_license | peerct/Conquest-DICOM-Server | 301e6460c87b8a8d5d95f0057af95e8357dd4e7c | 909978a7c8e5838ec8eb61d333e3a3fdd637ef60 | refs/heads/master | 2021-01-18T05:03:42.221986 | 2009-06-15T14:00:15 | 2009-06-15T14:00:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,317 | cpp | /*
MvH 19980327: put messages in one SystemDebug for UDP message layout
MvH 19980415: changed messages to OperatorConsole
MvH 19980605: Need to add regen for optical devices and cachedevices !!!!!
MvH 19981218: temp use pdu.load
ljz 19990108: Replaced PDU.Load by LoadImplicitLittleEndian in RegenToDatabase
MvH 19990109: Set HeaderOnly flag for LoadImplicitLittleEndianFile to TRUE
Added regen of CACHE and JUKEBOX devices;
NOTE: full regen imposes name restrictions on JUKEBOX and CACHE directories
MvH 19990117: Filenames with .v2 are assumed raw; added extension .dcm for chapter 10 format
ljz 19990317: Parameters of LoadImplicitLittleEndianFile have been changed
mvh 19990521: .img files react same as .dcm files
ljz 20000629: Logging of trouble now starts with '***'
mvh 20010415: Added SubDir parameter to regen to allow regen of one directory only
mvh 20010416: Added RegenFile - to allow modification of images
mvh 20011109: Made file extension checking case insensitive
mvh 20020409: Experimental multithread version.
mvh 20020413: Made NTHREADS variable and tested. Time to regen 6900 files:
# time (min:s)
1 5:41
4 4:06
10 3:34
20 3:14
40 3:41
100 3:36 gives sql server deadlock errors (even with 20xretry)
20 using PDU 10:48 (CPU limited)
20 using 64 cache 3:09
20 using 128 cache 3:05
20 using 512 cache 3:06
20 using 1024 cache 3:00
20 using 1000 cache 2:37 (?)
20 using 1000 cache 3:08
1 using 256,unique index 4:13 <- chosen because is reliable and fast
20 using 1000,uniqueindex 3:14
1 using 256,unique index 3:40 with new buffered loadddo code by ljz
mvh 20020415: Tested with new loaddo code by ljz.
Note: multithread works and has allowed fixing MT some errors in other
modules. However, due to a problem in concurrent db writing (in
UpdateOrAddToTable) it should not be used clinically.
ljz 20020613: Removed some warnings
mvh 20020802: Simplified regen code; traverse subdirectories recursively (allow e.g., e-film data format)
mvh 20020804: Use PATHSEPCHAR where possible
mvh 20021014: Exclude directory PRINTER_FILES during regen (contains slices without ID and such)
ljz 20030120: Removed some warnings
mvh 20030706: Attach VRType to PDU for implicit little endian support
mvh 20030819: Allow longer filenames
mvh 20040614: Do not regen CACHE devices; first regen JUKEBOX then MAG (e.g., in historical order)
mvh 20050118: Adapted for LINUX compile
mvh 20060628: AddToDatabase has JustAdd parameter
mvh 20070210: Increased maxvrsize for regen v2 files from 0x400 to 0x4000 -> UIDs were sometimes not found
bcb 20070308: Ignore .DS_Store for DARWIN
*/
// #define MULTITHREAD
# include "dgate.hpp"
#ifdef MULTITHREAD
#define NTHREADS 20
static void regen_queue(char *basename, char *filename, char *device);
static int queueempty();
#endif
#ifdef WIN32
#define PATHSEPSTR "\\"
#define PATHSEPCHAR '\\'
#else
#define PATHSEPSTR "/"
#define PATHSEPCHAR '/'
#define stricmp(s1, s2) strcasecmp(s1, s2)
#include <unistd.h>
#include <dirent.h>
#endif
#ifndef WIN32
BOOL IsDirectory(char *path)
{
char temp[1024];
struct stat statbuf;
int lc= strlen(path) - 1; /* index for last char in path */
strcpy(temp, path);
if (temp[lc] == '\\' || temp[lc] == '/')
temp[lc] = 0;
if (stat(temp, &statbuf) == -1) return FALSE; /* file or path not found */
if (statbuf.st_mode & S_IFDIR)
return TRUE;
else
return FALSE;
}
#endif
// This routine checks the file extension and only accepts v2=raw, dcm/img=chapter 10 (or other)
BOOL
RegenToDatabase(Database *DB, char *basename, char *filename, char *device)
{
DICOMDataObject* pDDO;
int len;
PDU_Service PDU;
PDU.AttachRTC(&VRType);
len = strlen(filename);
// The excludes some impossible short names (including path) like a.v2 which are unlikely to occur
if (len < 4) return FALSE;
if (stricmp(filename + len - 3, ".v2")==0 )
{
pDDO = LoadImplicitLittleEndianFile(filename, 0x4000); // increased from 400 to allow load large icons
if(!pDDO)
{
OperatorConsole.printf("***[Regen] %s -FAILED: Error on Load\n", filename);
return ( FALSE );
}
}
else if (stricmp(filename + len - 4, ".dcm")==0 ||
stricmp(filename + len - 4, ".img")==0 )
{
pDDO = PDU.LoadDICOMDataObject(filename);
if(!pDDO)
{
OperatorConsole.printf("***[Regen] %s -FAILED: Error on Load\n", filename);
return ( FALSE );
}
}
else
return FALSE;
if(!SaveToDataBase(*DB, pDDO, basename, device, FALSE))
{
delete pDDO;
OperatorConsole.printf("***[Regen] %s -FAILED: Error SQL Add\n", filename);
return ( FALSE );
}
delete pDDO;
OperatorConsole.printf("[Regen] %s -SUCCESS\n", filename);
return ( TRUE );
}
// This function enters a file into the database, assuming it is on one of the MAG devices
BOOL
RegenFile(char *filename)
{
Database DB;
UINT Index;
char Device[255], Physical[1024], BaseName[1024];
if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
{
fprintf(stderr, "Error Connecting to SQL\n");
return ( FALSE );
}
Index = 0;
while ( Index < MAGDevices )
{
sprintf(Device, "MAG%d", Index);
GetPhysicalDevice(Device, Physical);
if (memicmp(Physical, filename, strlen(Physical))==0)
{
strcpy(BaseName, filename + strlen(Physical));
RegenToDatabase(&DB, BaseName, filename, Device);
break;
}
++Index;
}
if (Index == MAGDevices)
{
fprintf(stderr, "File to enter is not on a MAG device\n");
return ( FALSE );
}
return ( TRUE );
}
// Help function to regen an arbitrary directory (PathString must end with PATHSEPSTR)
#ifdef WIN32
BOOL RegenDir(Database *DB, char *PathString, char *Device)
{
HANDLE fdHandle;
WIN32_FIND_DATA FileData;
char TempPath[1024];
char Physical[1024];
GetPhysicalDevice(Device, Physical);
strcpy(TempPath, PathString);
strcat(TempPath, "*.*");
// Traverse first level of subdirectories
fdHandle = FindFirstFile(TempPath, &FileData);
if(fdHandle == INVALID_HANDLE_VALUE)
return ( FALSE );
while ( TRUE )
{
if (FileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if
(
stricmp(FileData.cFileName, "INCOMING") != 0 &&
stricmp(FileData.cFileName, "PRINTER_FILES") != 0 &&
strcmp(FileData.cFileName, ".") != 0 &&
strcmp(FileData.cFileName, "..") != 0 &&
stricmp(FileData.cFileName, "BIN") != 0
)
{
strcpy(TempPath, PathString);
strcat(TempPath, FileData.cFileName);
strcat(TempPath, PATHSEPSTR);
RegenDir(DB, TempPath, Device);
}
}
else
{
strcpy(TempPath, PathString);
strcat(TempPath, FileData.cFileName);
RegenToDatabase (DB, TempPath + strlen(Physical), TempPath, Device);
}
if(!FindNextFile(fdHandle, &FileData))
break;
}
FindClose(fdHandle);
return TRUE;
}
#else // linux version
BOOL RegenDir(Database *DB, char *PathString, char *Device)
{
DIR *dird;
dirent *diren;
char TempPath[1024];
char Physical[1024];
char *n;
GetPhysicalDevice(Device, Physical);
strcpy(TempPath, PathString);
TempPath[strlen(TempPath)-1]=0;
// Traverse first level of subdirectories
dird = opendir(TempPath);
if(dird == NULL)
return ( FALSE );
while ( TRUE )
{
diren = readdir(dird);
if (diren)
{
n = diren->d_name;
strcpy(TempPath, PathString);
strcat(TempPath, n);
if (IsDirectory(TempPath))
{
if
(
stricmp(n, "INCOMING" ) != 0 &&
stricmp(n, "PRINTER_FILES") != 0 &&
strcmp (n, "." ) != 0 &&
strcmp (n, ".." ) != 0 &&
stricmp(n, "BIN" ) != 0
#ifdef DARWIN //A Macintosh OS X file.
&& stricmp(n, ".DS_Store" ) != 0
#endif //DARWIN
)
{
strcat(TempPath, PATHSEPSTR);
RegenDir(DB, TempPath, Device);
}
}
else
{
RegenToDatabase (DB, TempPath + strlen(Physical), TempPath, Device);
}
}
else
break;
}
closedir(dird);
return TRUE;
}
#endif
// This Regen function recurses a single level of subdirecties if IsCacheOrJukeBox is FALSE
// it recurses a two levels of subdirecties if IsCacheOrJukeBox is TRUE
#ifdef WIN32
BOOL
Regen(char *Device, int IsCacheOrJukeBox, char *SubDir)
{
int itemp, i, j, CDNumber, JUKEBOXNumber;
Database DB;
HANDLE fdHandle;
WIN32_FIND_DATA FileData;
char PathString[1024], TempPath[1024], FileString[1024];
char ActualDevice[256];
char *p;
if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
{
fprintf(stderr, "Error Connecting to SQL\n");
return ( FALSE );
}
// convert device specification to a path
GetPhysicalDevice(Device, PathString);
itemp = strlen(PathString);
if(!itemp)
return FALSE;
// strip the last subdirectory (e.g., CD0_%04d) for regen of complete CACHE or JUKEBOX devices
if (IsCacheOrJukeBox)
{
PathString[itemp-1]=0;
p = strrchr(PathString, PATHSEPCHAR);
if (p) p[0]=0;
OperatorConsole.printf("Regen directory = %s\n", PathString);
itemp = strlen(PathString);
if(!itemp)
return (FALSE);
}
// add a '/' to end of directory name if not yet present
if(PathString[itemp-1] != PATHSEPCHAR)
strcat(PathString, PATHSEPSTR);
// PathString now contains Image file storage root directory path
// Regen all files and subdirectories below that or only the selected subdirectory
if (!IsCacheOrJukeBox)
{
if (SubDir)
{
strcat(PathString, SubDir);
strcat(PathString, PATHSEPSTR);
}
return RegenDir(&DB, PathString, Device);
}
// remaining code is for cache or jukebox devices
strcpy(TempPath, PathString);
strcat(TempPath, "*.*");
fdHandle = FindFirstFile(TempPath, &FileData);
if(fdHandle == INVALID_HANDLE_VALUE)
return ( FALSE );
while ( TRUE )
{
// traverse one level for CD or cache directories (CDs to be burned)
if (strcmp(FileData.cFileName, ".") != 0 &&
strcmp(FileData.cFileName, "..") != 0
)
{
strcpy(FileString, FileData.cFileName);
// Decompose jukebox directory name to find CD number
// Directory name must be like aaaCCCC where C=CD number a=non-number
if(strnicmp(Device, "JUKEBOX", 7)==0)
{
CDNumber = 0;
for (i=strlen(FileString)-1; i>=0; i--)
{
if (FileString[i] < '0' || FileString[i] > '9')
{
CDNumber = atoi(FileString + i + 1);
break;
}
}
sprintf(ActualDevice, "%s.%d", Device, CDNumber);
}
// Decompose cache directory name to find CD number and jukebox number
// Directory name must be like aaaJJaCCCC where C=CD# J=jukebox# a=non-number
if(strnicmp(Device, "CACHE", 5)==0)
{
CDNumber = 0;
JUKEBOXNumber = 0;
for (i=strlen(FileString)-1; i>=0; i--)
{
if (FileString[i] < '0' || FileString[i] > '9')
{
CDNumber = atoi(FileString + i + 1);
for (j=i-1; j>=0; j--)
{
if (FileString[j] < '0' || FileString[j] > '9')
{
JUKEBOXNumber = atoi(FileString + j + 1);
break;
}
}
break;
}
}
sprintf(ActualDevice, "%s.%d.%d", Device, JUKEBOXNumber, CDNumber);
}
strcpy(TempPath, PathString);
strcat(TempPath, FileString);
strcat(TempPath, PATHSEPSTR);
RegenDir(&DB, TempPath, ActualDevice);
}
if(!FindNextFile(fdHandle, &FileData))
break;
}
FindClose ( fdHandle );
#ifdef MULTITHREAD
while(!queueempty()) Sleep(100);
#endif
return ( TRUE );
}
#else // linux version
BOOL
Regen(char *Device, int IsCacheOrJukeBox, char *SubDir)
{
int itemp, i, j, CDNumber, JUKEBOXNumber;
Database DB;
DIR *dird;
dirent *diren;
char PathString[1024], TempPath[1024], FileString[1024];
char ActualDevice[256];
char *p;
if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
{
fprintf(stderr, "Error Connecting to SQL\n");
return ( FALSE );
}
// convert device specification to a path
GetPhysicalDevice(Device, PathString);
itemp = strlen(PathString);
if(!itemp)
return FALSE;
// strip the last subdirectory (e.g., CD0_%04d) for regen of complete CACHE or JUKEBOX devices
if (IsCacheOrJukeBox)
{
PathString[itemp-1]=0;
p = strrchr(PathString, PATHSEPCHAR);
if (p) p[0]=0;
OperatorConsole.printf("Regen directory = %s\n", PathString);
itemp = strlen(PathString);
if(!itemp)
return (FALSE);
}
// add a '/' to end of directory name if not yet present
if(PathString[itemp-1] != PATHSEPCHAR)
strcat(PathString, PATHSEPSTR);
// PathString now contains Image file storage root directory path
// Regen all files and subdirectories below that or only the selected subdirectory
if (!IsCacheOrJukeBox)
{
if (SubDir)
{
strcat(PathString, SubDir);
strcat(PathString, PATHSEPSTR);
}
return RegenDir(&DB, PathString, Device);
}
// remaining code is for cache or jukebox devices
strcpy(TempPath, PathString);
TempPath[strlen(TempPath)-1]=0;
dird = opendir(TempPath);
if(dird == NULL)
return ( FALSE );
while ( TRUE )
{
diren = readdir(dird);
if (!diren) break;
// traverse one level for CD or cache directories (CDs to be burned)
if (strcmp(diren->d_name, ".") != 0 &&
strcmp(diren->d_name, "..") != 0
)
{
strcpy(FileString, diren->d_name);
// Decompose jukebox directory name to find CD number
// Directory name must be like aaaCCCC where C=CD number a=non-number
if(strnicmp(Device, "JUKEBOX", 7)==0)
{
CDNumber = 0;
for (i=strlen(FileString)-1; i>=0; i--)
{
if (FileString[i] < '0' || FileString[i] > '9')
{
CDNumber = atoi(FileString + i + 1);
break;
}
}
sprintf(ActualDevice, "%s.%d", Device, CDNumber);
}
// Decompose cache directory name to find CD number and jukebox number
// Directory name must be like aaaJJaCCCC where C=CD# J=jukebox# a=non-number
if(strnicmp(Device, "CACHE", 5)==0)
{
CDNumber = 0;
JUKEBOXNumber = 0;
for (i=strlen(FileString)-1; i>=0; i--)
{
if (FileString[i] < '0' || FileString[i] > '9')
{
CDNumber = atoi(FileString + i + 1);
for (j=i-1; j>=0; j--)
{
if (FileString[j] < '0' || FileString[j] > '9')
{
JUKEBOXNumber = atoi(FileString + j + 1);
break;
}
}
break;
}
}
sprintf(ActualDevice, "%s.%d.%d", Device, JUKEBOXNumber, CDNumber);
}
strcpy(TempPath, PathString);
strcat(TempPath, FileString);
strcat(TempPath, PATHSEPSTR);
RegenDir(&DB, TempPath, ActualDevice);
}
}
closedir(dird);
#ifdef MULTITHREAD
while(!queueempty()) sleep(1);
#endif
return ( TRUE );
}
#endif
// Regen *Each* device
BOOL
Regen()
{
UINT Index;
char s[20];
// Index = 0;
// while ( Index < CACHEDevices )
// {
// sprintf(s, "CACHE%d", Index);
// printf("Regen Device '%s'\n", s);
// Regen(s, TRUE);
// ++Index;
// }
Index = 0;
while ( Index < JUKEBOXDevices )
{
sprintf(s, "JUKEBOX%d", Index);
printf("Regen Device '%s'\n", s);
Regen(s, TRUE);
++Index;
}
Index = 0;
while ( Index < MAGDevices )
{
sprintf(s, "MAG%d", Index);
printf("Regen Device '%s'\n", s);
Regen(s, FALSE);
++Index;
}
return(FALSE);
}
//////////////////////////////////////////////////////////////////////////////////
// This code is a simple thread safe queue with its own processing thread (WIN32 only)
//////////////////////////////////////////////////////////////////////////////////
#ifdef MULTITHREAD
static struct queue
{ int top;
int bottom;
int num;
int entrysize;
char *data;
HANDLE threadhandle;
int delay;
CRITICAL_SECTION critical;
void (*process)(char *);
} q1;
static BOOL WINAPI processthread(struct queue *q)
{ char *data = (char *)malloc(q->entrysize);
while (1)
{ while (1)
{ EnterCriticalSection(&q->critical);
if (q->top!=q->bottom)
{ memcpy(data, q->data + q->bottom * q->entrysize, q->entrysize);
q->bottom = (q->bottom+1)%q->num;
LeaveCriticalSection(&q->critical);
q->process(data);
break;
}
LeaveCriticalSection(&q->critical);
Sleep(q->delay);
}
}
DeleteCriticalSection(&q->critical);
return TRUE;
}
static struct queue *new_queue(int num, int size, int delay, void (*process)(char *))
{ struct queue *result;
unsigned long ThreadID;
result = new queue;
result->top = 0;
result->bottom = 0;
result->num = num;
result->entrysize = size;
result->delay = delay;
result->process = process;
result->data = (char *)malloc(num * size);
InitializeCriticalSection(&result->critical);
/* Note: since the queue is thread safe it is possible to start more than one thread to service it */
result->threadhandle =
CreateThread(NULL, 0x000ff000, (LPTHREAD_START_ROUTINE) processthread, result, 0, &ThreadID);
return result;
};
static void into_queue(struct queue *q, char *in)
{ while (1)
{ EnterCriticalSection(&q->critical);
if ((q->top+1)%q->num != q->bottom)
{ memcpy(q->data + q->top * q->entrysize, in, q->entrysize);
q->top = (q->top+1)%q->num;
LeaveCriticalSection(&q->critical);
return;
}
LeaveCriticalSection(&q->critical);
Sleep(q->delay);
}
}
///////////////////////////////////////////////////////////////////////////////
static struct queue *q[NTHREADS];
static int qp=0;
static Database *DBs[NTHREADS];
static void regenprocess(char *data)
{ Database *DB;
memcpy(&DB, data, sizeof(Database *));
RegenToDatabase(DB, data+128, data+256, data+32);
}
static void regen_queue(char *basename, char *filename, char *device)
{ char data[1512];
int i;
if (!q[0])
{ for(i=0; i<NTHREADS; i++)
{ q[i] = new_queue(50, 1512, 10, regenprocess);
DBs[i] = new Database;
if (!DBs[i]->Open ( DataSource, UserName, Password, DataHost ) )
{ fprintf(stderr, "Error Connecting to SQL\n");
return;
}
}
qp=0;
}
memcpy(data, &DBs[qp], sizeof(Database *));
strcpy(data+32, device);
strcpy(data+128, basename);
strcpy(data+256, filename);
into_queue(q[qp], data);
qp = (qp+1)%NTHREADS;
}
static int queueempty()
{ int i;
for(i=0; i<NTHREADS; i++)
if (q[i]->top!=q[i]->bottom) return 0;
return 1;
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
756
]
]
]
|
a444bd15c3042d86485a6a56cff424129280d633 | 45229380094a0c2b603616e7505cbdc4d89dfaee | /wavelets/facedetector_src/src/cvLib/ImagePyramid.h | 863b41807c57809e9c63a1b2017aa4c4345fb3c0 | []
| no_license | xcud/msrds | a71000cc096723272e5ada7229426dee5100406c | 04764859c88f5c36a757dbffc105309a27cd9c4d | refs/heads/master | 2021-01-10T01:19:35.834296 | 2011-11-04T09:26:01 | 2011-11-04T09:26:01 | 45,697,313 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,127 | h |
#ifndef ImagePyramid_h
#define ImagePyramid_h
#include "imageframe.h"
class ImageFrame;
class ImagePyramid
{
public:
ImagePyramid();
//ImagePyramid(const ImagePyramid& impyramid);
~ImagePyramid();
// Operators
//const ImagePyramid& operator=(const ImagePyramid& impyramid);
// Operations
void init(unsigned int image_width, unsigned int image_height,
const float* scales = 0, unsigned int nscales = 0);
// Access
inline ImageFrame* get_frame(unsigned int i) const;
// Inquiry
inline unsigned int get_frames_number() const;
protected:
private:
ImagePyramid(const ImagePyramid& impyramid);
const ImagePyramid& operator=(const ImagePyramid& impyramid);
vector<ImageFrame *> m_pyramid;
void clear();
};
// Inlines
inline ImageFrame* ImagePyramid::get_frame(unsigned int i) const
{
return m_pyramid[i];
}
inline unsigned int ImagePyramid::get_frames_number() const
{
return (unsigned int)m_pyramid.size();
}
#endif ImagePyramid_h
| [
"perpet99@cc61708c-8d4c-0410-8fce-b5b73d66a671"
]
| [
[
[
1,
54
]
]
]
|
920b78f5c99e3951d54ab3aac0bfa87075bccdb8 | e4bad8b090b8f2fd1ea44b681e3ac41981f50220 | /trunk/Abeetles/Abeetles/Abeetles.cpp | 5af36b36fb705d5648764ae62cbe3436bb59942f | []
| no_license | BackupTheBerlios/abeetles-svn | 92d1ce228b8627116ae3104b4698fc5873466aff | 803f916bab7148290f55542c20af29367ef2d125 | refs/heads/master | 2021-01-22T12:02:24.457339 | 2007-08-15T11:18:14 | 2007-08-15T11:18:14 | 40,670,857 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 933 | cpp | // Abeetles.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "RunLife.h"
#include "CfgManager.h"
#ifndef _CRT_RAND_S
#define _CRT_RAND_S
#endif;
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <time.h>
#include "abeetleslib.h"
//Global variables
CfgManager CfgMng;
int _tmain(int argc, _TCHAR* argv[])
{
printf("%d\n",soucet(5,6));
//CRunLife::run();
printf("\nPress any key to finnish\n");
getc(stdin);
return 0;
}
int RandInBound (int bound)
{
unsigned int number;
errno_t err=0;
#ifdef _CRT_RAND_S
//printf("Hura");
//err = rand_s(&number);
#endif;
number=rand();
if (err != 0)
{
printf("The rand_s function failed!\n");
return 0;
}
unsigned int Res = ((int)((((double)number /(double) RAND_MAX ) * bound))) % bound;
return Res;
} | [
"ibart@60a5a0de-1a2f-0410-942a-f28f22aea592"
]
| [
[
[
1,
54
]
]
]
|
44d3e9719ba221e8d7fc389c1cb6959d3955bece | 48ab31a0a6a8605d57b5e140309c910f46eb5b35 | /Root/Implementation/BerkeleyDatabase/BerkeleyIndexCursor.cpp | 6900b780694efb526a217790cf72fd23a351a46c | []
| no_license | firebreath/indexeddb | 4c3106027a70e233eb0f91c6e0b5d60847d75800 | 50136d2fadced369788a42d249157b8a0d06eb88 | refs/heads/master | 2023-08-31T11:28:42.664028 | 2011-01-03T23:29:46 | 2011-01-03T23:29:46 | 1,218,008 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,681 | cpp | /**********************************************************\
Copyright Brandon Haynes
http://code.google.com/p/indexeddb
GNU Lesser General Public License
\**********************************************************/
#include "BerkeleyIndexCursor.h"
#include "BerkeleyIndex.h"
#include "BerkeleyDatabase.h"
#include "../ImplementationException.h"
using boost::mutex;
using boost::lock_guard;
namespace BrandonHaynes {
namespace IndexedDB {
namespace Implementation {
namespace BerkeleyDB
{
BerkeleyIndexCursor::BerkeleyIndexCursor(BerkeleyIndex& index, const Key& left, const Key& right, const bool openLeft, const bool openRight, const bool isReversed, const bool omitDuplicates, const bool dataArePrimaryKeys, TransactionContext& transactionContext)
: BerkeleyCursor(index.implementation, left, right, openLeft, openRight, isReversed, omitDuplicates, transactionContext),
dataArePrimaryKeys(dataArePrimaryKeys)
{ }
Data BerkeleyIndexCursor::getData(TransactionContext& transactionContext)
{
ensureOpen();
if(!dataArePrimaryKeys)
return BerkeleyCursor::getData(transactionContext);
else
{
Dbt key, primaryKey, data;
try
{
if(getCursor()->pget(&key, &primaryKey, &data, DB_CURRENT) == 0)
return BerkeleyDatabase::ToData(primaryKey);
else
return Data::getUndefinedData();
}
catch(DbDeadlockException& e)
{ throw ImplementationException("DEADLOCK_ERR", ImplementationException::DEADLOCK_ERR, e.get_errno()); }
catch(DbException& e)
{ throw ImplementationException("UNKNOWN_ERR", ImplementationException::UNKNOWN_ERR, e.get_errno()); }
}
}
}
}
}
} | [
"[email protected]"
]
| [
[
[
1,
51
]
]
]
|
12cc7055b68f6ae4c24d6270e23b61f858428d56 | 3a577d02f876776b22e2bf1c0db12a083f49086d | /vba2/gba2/graphics/cgbagraphics.h | fe94f3a22e79d510de1960eff6cfc0e00bf45626 | []
| no_license | xiaoluoyuan/VisualBoyAdvance-2 | d19565617b26e1771f437842dba5f0131d774e73 | cadd2193ba48e1846b45f87ff7c36246cd61b6ee | refs/heads/master | 2021-01-10T01:19:23.884491 | 2010-05-12T09:59:37 | 2010-05-12T09:59:37 | 46,539,728 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,322 | h | /* VisualBoyAdvance 2
Copyright (C) 2009-2010 VBA development team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CGBAGRAPHICS_H
#define CGBAGRAPHICS_H
#include "../common/Types.h"
#include "cpicture.h"
class CGBAGraphics
{
// /----------
public:
CGBAGraphics();
~CGBAGraphics();
/// copy VRAM
void setVRAM( const u8 *vram_src );
/// read & interpret all video registers
void setIO( const u8 *io );
/// convert & copy palettes
void setPAL( const u8 *pal );
/// prepare image data for render API
bool process();
// \----------
/// display control
struct structDISPCNT {
u8 bgMode; // 0-5
bool frameNumber; // frame buffer 0 or 1
bool oamAccessDuringHBlank;
bool objCharMapping;
bool forcedBlank;
bool displayBG[4];
bool displayOBJ;
bool displayWIN0;
bool displayWIN1;
bool displayOBJWIN;
};
/// background control
struct structBGCNT {
u8 priority; ///< (max) 0 1 2 3 (min)
u16 charOffset; ///< adress of tiles/characters in VRAM
bool mosaic; ///< enables or disables mosaic effect
bool colorMode; ///< false: 16x16 true: 256x1
u16 mapOffset; ///< adress of map/screen data in VRAM
bool wrapAround; ///< area overflow flag (only BG2&3)
u8 size; ///< for char mode: 0=256x256 1=512x256 2=256x512 3=512x512
u32 width; ///< width of BG when combining all its macro-blocks
u32 height; ///< height of BG when combining all its macro-blocks
bool isRotScale; ///< false: no rotation/scaling
};
typedef struct {
struct structDISPCNT DISPCNT; /// display control registers
struct structBGCNT BGCNT[4]; /// background control registers
CPicture BGIMAGE[4]; /// a picture of the whole BG layer
} RESULT;
RESULT result; // this struct will be used by the renderer later on
private:
// all have to be true to be able to work
bool vramLoaded, ioLoaded, palLoaded;
u8 *vram; // video memory [96 KiB]
COLOR32 bgpal[256]; // BG palette (converted to RGBA color)
COLOR32 objpal[256]; // sprite palette (converted to RGBA color)
/// convert 15 bit GBA color to 32 bit RGBA color
/// GBA color format: (MSB) 1x 5b 5g 5r (LSB)
COLOR32 colorTable[ 0x8000 ];
u16 BG0HOFS, BG1HOFS, BG2HOFS, BG3HOFS; // horiontal offset (only in character mode)
u16 BG0VOFS, BG1VOFS, BG2VOFS, BG3VOFS; // vertical offset (only in character mode)
/// create a picture out of the BG data and character data
bool buildCharBG( u8 bg_number );
bool buildRotScaleBG( u8 bg_number );
bool buildBitmapBG( u8 mode );
};
#endif // CGBAGRAPHICS_H
| [
"spacy51@5a53c671-dd2d-0410-9261-3f5c817b7aa0"
]
| [
[
[
1,
106
]
]
]
|
2c7f4135677724fd5de1991b97eeca22f4d8ee09 | bfe8eca44c0fca696a0031a98037f19a9938dd26 | /libjingle-0.4.0/talk/base/asyncudpsocket.h | c21edf1495af44185f677a373168545af976bcd1 | [
"BSD-3-Clause"
]
| permissive | luge/foolject | a190006bc0ed693f685f3a8287ea15b1fe631744 | 2f4f13a221a0fa2fecab2aaaf7e2af75c160d90c | refs/heads/master | 2021-01-10T07:41:06.726526 | 2011-01-21T10:25:22 | 2011-01-21T10:25:22 | 36,303,977 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,453 | h | /*
* libjingle
* Copyright 2004--2005, Google Inc.
*
* 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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TALK_BASE_ASYNCUDPSOCKET_H__
#define TALK_BASE_ASYNCUDPSOCKET_H__
#include "talk/base/asyncpacketsocket.h"
#include "talk/base/socketfactory.h"
namespace talk_base {
// Provides the ability to receive packets asynchronously. Sends are not
// buffered since it is acceptable to drop packets under high load.
class AsyncUDPSocket : public AsyncPacketSocket {
public:
AsyncUDPSocket(AsyncSocket* socket);
virtual ~AsyncUDPSocket();
private:
char* buf_;
size_t size_;
// Called when the underlying socket is ready to be read from.
void OnReadEvent(AsyncSocket* socket);
};
// Creates a new socket for sending asynchronous UDP packets using an
// asynchronous socket from the given factory.
inline AsyncUDPSocket* CreateAsyncUDPSocket(SocketFactory* factory) {
return new AsyncUDPSocket(factory->CreateAsyncSocket(SOCK_DGRAM));
}
} // namespace talk_base
#endif // TALK_BASE_ASYNCUDPSOCKET_H__
| [
"[email protected]@756bb6b0-a119-0410-8338-473b6f1ccd30"
]
| [
[
[
1,
59
]
]
]
|
cdf9ad39d2876d010675d6b36609a4d9f475918d | cfcd2a448c91b249ea61d0d0d747129900e9e97f | /thirdparty/OpenCOLLADA/COLLADASaxFrameworkLoader/include/COLLADASaxFWLAssetLoader.h | f3de6b2449cde4b6ff52c3092104313d51f1f912 | []
| no_license | fire-archive/OgreCollada | b1686b1b84b512ffee65baddb290503fb1ebac9c | 49114208f176eb695b525dca4f79fc0cfd40e9de | refs/heads/master | 2020-04-10T10:04:15.187350 | 2009-05-31T15:33:15 | 2009-05-31T15:33:15 | 268,046 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,329 | h | /*
Copyright (c) 2008 NetAllied Systems GmbH
This file is part of COLLADASaxFrameworkLoader.
Licensed under the MIT Open Source License,
for details please see LICENSE file or the website
http://www.opensource.org/licenses/mit-license.php
*/
#ifndef __COLLADASAXFWL_ASSETLOADER_H__
#define __COLLADASAXFWL_ASSETLOADER_H__
#include "COLLADASaxFWLPrerequisites.h"
#include "COLLADASaxFWLFilePartLoader.h"
#include "COLLADAFWFileInfo.h"
#include "COLLADAFWIWriter.h"
namespace COLLADASaxFWL
{
/** TODO Documentation */
class AssetLoader : public FilePartLoader
{
private:
/** Pointer to the asset this loader creates.*/
COLLADAFW::FileInfo* mAsset;
public:
/** Constructor. */
AssetLoader ( IFilePartLoader* callingFilePartLoader );
/** Destructor. */
virtual ~AssetLoader ();
/** Sax callback function for the end of the collada document asset information.*/
virtual bool end__COLLADA__asset()
{
bool success = writer()->writeGlobalAsset ( mAsset );
delete mAsset;
finish();
return success;
}
virtual bool begin__contributor(){return true;}
virtual bool end__contributor(){return true;}
virtual bool begin__author(){return true;}
virtual bool end__author(){return true;}
virtual bool data__author( const ParserChar* data, size_t length )
{
mAsset->appendValuePair ( "author", String ( (char*) data, length ) );
return true;
}
virtual bool begin__authoring_tool(){return true;}
virtual bool end__authoring_tool(){return true;}
virtual bool data__authoring_tool( const ParserChar* data, size_t length )
{
mAsset->appendValuePair ( "authoring_tool", String ( (char*) data, length ) );
return true;
}
virtual bool begin__comments(){return true;}
virtual bool end__comments(){return true;}
virtual bool data__comments( const ParserChar* data, size_t length )
{
mAsset->appendValuePair ( "comments", String ( (char*) data, length ) );
return true;
}
virtual bool begin__copyright(){return true;}
virtual bool end__copyright(){return true;}
virtual bool data__copyright( const ParserChar* data, size_t length )
{
mAsset->appendValuePair ( "copyright", String ( (char*) data, length ) );
return true;
}
virtual bool begin__source_data(){return true;}
virtual bool end__source_data(){return true;}
virtual bool data__source_data( const ParserChar* data, size_t length )
{
mAsset->appendValuePair ( "source", String ( (char*) data, length ) );
return true;
}
virtual bool begin__created(){return true;}
virtual bool end__created(){return true;}
virtual bool data__created( const ParserChar* data, size_t length )
{
mAsset->appendValuePair ( "created", String ( (char*) data, length ) );
return true;
}
virtual bool begin__keywords(){return true;}
virtual bool end__keywords(){return true;}
virtual bool data__keywords( const ParserChar* data, size_t length )
{
mAsset->appendValuePair ( "keywords", String ( (char*) data, length ) );
return true;
}
virtual bool begin__modified(){return true;}
virtual bool end__modified(){return true;}
virtual bool data__modified( const ParserChar* data, size_t length )
{
mAsset->appendValuePair ( "modified", String ( (char*) data, length ) );
return true;
}
virtual bool begin__revision(){return true;}
virtual bool end__revision(){return true;}
virtual bool data__revision( const ParserChar* data, size_t length )
{
mAsset->appendValuePair ( "revision", String ( (char*) data, length ) );
return true;
}
virtual bool begin__subject(){return true;}
virtual bool end__subject(){return true;}
virtual bool data__subject( const ParserChar* data, size_t length )
{
mAsset->appendValuePair ( "subject", String ( (char*) data, length ) );
return true;
}
virtual bool begin__title(){return true;}
virtual bool end__title(){return true;}
virtual bool data__title( const ParserChar* data, size_t length )
{
mAsset->appendValuePair ( "title", String ( (char*) data, length ) );
return true;
}
virtual bool begin__unit( const unit__AttributeData& attributeData )
{
mAsset->getUnit().setLinearUnit ( String ( (char*) attributeData.name ) );
mAsset->getUnit().setLinearUnitMeter ( attributeData.meter );
return true;
}
virtual bool end__unit(){return true;}
virtual bool begin__up_axis(){return true;}
virtual bool end__up_axis(){return true;}
virtual bool data__up_axis( const COLLADASaxFWL::UpAxisType val )
{
switch ( val )
{
case COLLADASaxFWL::UpAxisType__X_UP:
mAsset->setUpAxisType ( COLLADAFW::FileInfo::X_UP_STRING );
break;
case COLLADASaxFWL::UpAxisType__Y_UP:
mAsset->setUpAxisType ( COLLADAFW::FileInfo::Y_UP_STRING );
break;
case COLLADASaxFWL::UpAxisType__Z_UP:
mAsset->setUpAxisType ( COLLADAFW::FileInfo::Z_UP_STRING );
break;
default:
mAsset->setUpAxisType ( COLLADAFW::FileInfo::Y_UP_STRING );
}
return true;
}
private:
/** Disable default copy ctor. */
AssetLoader( const AssetLoader& pre );
/** Disable default assignment operator. */
const AssetLoader& operator= ( const AssetLoader& pre );
};
} // namespace COLLADASAXFWL
#endif // __COLLADASAXFWL_ASSETLOADER_H__
| [
"[email protected]"
]
| [
[
[
1,
181
]
]
]
|
e90e3329db4841afa1e8cce79d59b9dd89dd6d0d | fcf03ead74f6dc103ec3b07ffe3bce81c820660d | /Base/BufsAndStrings/Desc/NonModifier/NonModifier.cpp | bf8247689e28a904ee041fad3cc60386bf49fd51 | []
| no_license | huellif/symbian-example | 72097c9aec6d45d555a79a30d576dddc04a65a16 | 56f6c5e67a3d37961408fc51188d46d49bddcfdc | refs/heads/master | 2016-09-06T12:49:32.021854 | 2010-10-14T06:31:20 | 2010-10-14T06:31:20 | 38,062,421 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,699 | cpp | // NonModifier.cpp
//
// Copyright (C) Symbian Software Ltd 2000-2005. All rights reserved.
// Examples to demonstrate some of the non-modifying member
// functions of descriptors.
#include "CommonFramework.h"
//
// Common literal text
//
_LIT(KTxtPressToContinue," (press any key to continue)\n");
_LIT(KTxtnotfound,"NOT FOUND");
_LIT(KTxtfound,"found");
_LIT(KTxtlessthan," is less than ");
_LIT(KTxtgreaterthan," is greater than ");
_LIT(KTxtequalto," is equal to ");
//
// Common Format strings
//
_LIT(KCommonFormat2,"Length()=%d; Size()=%d\n");
_LIT(KCommonFormat8,"\"%S\" Char %c is at pos %d (%S)\n");
_LIT(KCommonFormat9,"%- 8S pos %2d (%S)\n");
//
// Compare strings
//
_LIT(KTxtCompstr1,"Hello World!@@");
_LIT(KTxtCompstr2,"Hello");
_LIT(KTxtCompstr3,"Hello Worl");
_LIT(KTxtCompstr4,"Hello World!");
_LIT(KTxtCompstr5,"hello world!");
_LIT(KTxtCompstr6,"Hello World ");
_LIT(KTxtCompstr7,"Hello World@");
//
// Match strings
//
_LIT(KTxtMatchstr1,"*World*");
_LIT(KTxtMatchstr2,"*W?rld*");
_LIT(KTxtMatchstr3,"Wor*");
_LIT(KTxtMatchstr4,"Hello");
_LIT(KTxtMatchstr5,"*W*");
_LIT(KTxtMatchstr6,"hello*");
_LIT(KTxtMatchstr7,"*");
// Do the example
LOCAL_C void doExampleL()
{
TInt index;
TInt pos;
TPtrC genptr;
// Use a TBufC to demonstrate some of these
// and use the standard "Hello World!" text
_LIT(KTxtHelloWorld,"Hello World!");
const TBufC<16> bufc(KTxtHelloWorld);
//
// Right() & Mid() * * * * * * * * * * * *
//
_LIT(KTxtRightMid,"\n--->Right() & Mid()\n");
console->Printf(KTxtRightMid);
// Look at the content of bufc
_LIT(KFormat1," TBufC: \"%S\"; Ptr()=%x; ");
console->Printf(KFormat1,&bufc,bufc.Ptr());
console->Printf(KCommonFormat2,bufc.Length(),bufc.Size());
// Construct a TPtrC to represent the right
// hand 5 data items. The function Left()
// is similar.
TPtrC ptrc1 = bufc.Right(5);
// ptrc's data is "orld!"
// Length of ptrc is 5
// ptrc's data area address = bufc's data area
// address + 7
_LIT(KFormat3,"Right TPtrC: \"%S\"; Ptr()=%x; ");
console->Printf(KFormat3,&ptrc1,ptrc1.Ptr());
console->Printf(KCommonFormat2,ptrc1.Length(),ptrc1.Size());
// Construct a TPtrC to represent the 6 data
// items offset 3 from the start of bufc's
// data area.
TPtrC ptrc2 = bufc.Mid(3,6);
// ptrc's data is "lo Wor"
// Length of ptrc is 6
// ptrc's data area address = buf's data area
// address + 3
_LIT(KFormat4," Mid TPtrC: \"%S\"; Ptr()=%x; ");
console->Printf(KFormat4,&ptrc2,ptrc2.Ptr());
console->Printf(KCommonFormat2,ptrc2.Length(),ptrc2.Size());
// In practice, there is often no need to
// assign the returned TPtrC to another TPtrC.
// For example, the following code puts a
// value of 3 in pos; this is the offset
// of char 'W' within the chars "lo Wor"
// (see later for more detail on Locate())
pos = (bufc.Mid(3,6)).Locate('W');
_LIT(KFormat5,"(bufc.Mid(3,6)).Locate('W') returns %d\n");
console->Printf(KFormat5,pos);
// Want the 13 right hand data items.
// This is > current length of bufc
// causing panic !!
//
// Remove the "//" marks on the next line
// to see this happen
//TPtrC ptrc3 = bufc.Right(13);
//
// Compare() & CompareF() * * * * * * * * *
//
_LIT(KTxtCompare,"\n--->Compare() & CompareF()");
console->Printf(KTxtCompare);
console->Printf(KTxtPressToContinue); //" (press any key to continue)\n"
console->Getch();
// Can compare any kind of data.
// For binary data just use Compare().
// For text use Compare(), CompareF() or
// CompareC(). Using the Compare() function,
// case is important so that, below, the 4th
// comparison is equal but the 5th is unequal.
const TBufC<16> compstr[7] = {*&KTxtCompstr1, // "Hello World!@@"
*&KTxtCompstr2, // "Hello"
*&KTxtCompstr3, // "Hello Worl"
*&KTxtCompstr4, // "Hello World!"
*&KTxtCompstr5, // "hello world!"
*&KTxtCompstr6, // "Hello World "
*&KTxtCompstr7 // "Hello World@"
};
for (index = 0; index < 7; index++)
{
if ( (bufc.Compare(compstr[index])) < 0 )
genptr.Set(KTxtlessthan);
else if ( (bufc.Compare(compstr[index])) > 0)
genptr.Set(KTxtgreaterthan);
else genptr.Set(KTxtequalto);
_LIT(KFormat6,"\"%S\"%S\"%S\"\n");
console->Printf(KFormat6,&bufc,&genptr,&compstr[index]);
}
// CompareF() ignores case so that now,
// both the 4th and the 5th comparsions
// are equal.
// NOTE that the behaviour of CompareF() is locale dependent.
for (index = 3; index < 5; index++)
{
if ( (bufc.CompareF(compstr[index])) < 0 )
genptr.Set(KTxtlessthan);
else if ( (bufc.CompareF(compstr[index])) > 0)
genptr.Set(KTxtgreaterthan);
else genptr.Set(KTxtequalto);
_LIT(KTxtusingCF," (using CompareF())");
_LIT(KFormat7,"\"%S\"%S\"%S\"%S\n");
console->Printf(KFormat7,&bufc,&genptr,&compstr[index],&KTxtusingCF);
}
//
// Locate(), LocateF(), LocateReverse() * * *
//
// NOTE that the behaviour of LocateF() is locale dependent.
_LIT(KTxtLocate,"\n--->Locate(), LocateF() & LocateReverse()");
console->Printf(KTxtLocate);
console->Printf(KTxtPressToContinue); //" (press any key to continue)\n"
console->Getch();
// Locate the positions (i.e. the offsets) of
// these characters in "Hello World!"
TChar ch[4] = {'H', '!', 'o', 'w'};
// using Locate().
// Note that 'w' is not found because the
// function is case sensitive
_LIT(KTxtUsingLocate,"using Locate() \n");
console->Printf(KTxtUsingLocate);
for (index = 0 ; index < 4; index++)
{
pos = bufc.Locate(ch[index]);
if (pos < 0)
genptr.Set(KTxtnotfound);
else
genptr.Set(KTxtfound);
console->Printf(KCommonFormat8,&bufc,TUint(ch[index]),pos,&genptr);
}
// using LocateF()
// Note that 'w' is found because the
// function is NOT case sensitive.
//
// NOTE that the behaviour of LocateF() is locale dependent.
_LIT(KTxtUsingLocateF,"using LocateF() \n");
console->Printf(KTxtUsingLocateF);
for (index = 0 ; index < 4; index++)
{
pos = bufc.LocateF(ch[index]);
if (pos < 0)
genptr.Set(KTxtnotfound);
else
genptr.Set(KTxtfound);
console->Printf(KCommonFormat8,&bufc,TUint(ch[index]),pos,&genptr);
}
// using LocateReverse()
// Note that the 2nd char 'o' is found this time
_LIT(KTxtUsingLocateReverse,"using LocateReverse() \n");
console->Printf(KTxtUsingLocateReverse);
for (index = 0 ; index < 4; index++)
{
pos = bufc.LocateReverse(ch[index]);
if (pos < 0)
genptr.Set(KTxtnotfound);
else
genptr.Set(KTxtfound);
console->Printf(KCommonFormat8,&bufc,TUint(ch[index]),pos,&genptr);
}
//
// Match() & MatchF() * * * * * * *
//
//
// NOTE that the behaviour of MatchF() is locale dependent.
_LIT(KTxtMatch,"\n--->Match()");
console->Printf(KTxtMatch);
console->Printf(KTxtPressToContinue); //" (press any key to continue)\n"
console->Getch();
TBufC<8> matchstr[7] = {*&KTxtMatchstr1, // "*World*"
*&KTxtMatchstr2, // "*W?rld*"
*&KTxtMatchstr3, // "Wor*"
*&KTxtMatchstr4, // "Hello"
*&KTxtMatchstr5, // "*W*"
*&KTxtMatchstr6, // "hello*"
*&KTxtMatchstr7 // "*"
};
_LIT(KFormat10,"\"%S\"\n");
console->Printf(KFormat10,&bufc);
// using Match()
for (index = 0 ; index < 7; index++)
{
pos = bufc.Match(matchstr[index]);
if (pos < 0)
genptr.Set(KTxtnotfound);
else
genptr.Set(KTxtfound);
console->Printf(KCommonFormat9,&matchstr[index],pos,&genptr);
}
// using MatchF()
//
// Note the different result when matching
// the 6th string, where case is ignored.
//
// NOTE that the behaviour of MatchF() is locale dependent.
_LIT(KTxtMatchF,"\n--->MatchF()");
console->Printf(KTxtMatchF);
console->Printf(KTxtPressToContinue); //" (press any key to continue)\n"
console->Getch();
for (index = 0 ; index < 7; index++)
{
pos = bufc.MatchF(matchstr[index]);
if (pos < 0)
genptr.Set(KTxtnotfound);
else
genptr.Set(KTxtfound);
console->Printf(KCommonFormat9,&matchstr[index],pos,&genptr);
}
}
| [
"liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca"
]
| [
[
[
1,
300
]
]
]
|
a5603005f08284c94a69345009ab40ded593acdb | 1960e1ee431d2cfd2f8ed5715a1112f665b258e3 | /inc/win/clipboard.h | ebf216d353ed39b75e49df4a3a53b582fdab1add | []
| no_license | BackupTheBerlios/bvr20983 | c26a1379b0a62e1c09d1428525f3b4940d5bb1a7 | b32e92c866c294637785862e0ff9c491705c62a5 | refs/heads/master | 2021-01-01T16:12:42.021350 | 2009-11-01T22:38:40 | 2009-11-01T22:38:40 | 39,518,214 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,288 | h | /*
* $Id$
*
* Copyright (C) 2008 Dorothea Wachmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
#if !defined(CLIPBOARD_H)
#define CLIPBOARD_H
#include "os.h"
namespace bvr20983
{
namespace win
{
/**
*
*/
class Clipboard
{
public:
Clipboard(HWND hWnd);
~Clipboard();
void EmptyClipboard();
void AddData(LPCTSTR s);
void AddData(const TString& s);
void AddData(HBITMAP bitmap);
void AddData(HENHMETAFILE mf);
protected:
}; // of class Clipboard
} // of namespace win
} // of namespace bvr20983
#endif // CLIPBOARD_H
| [
"dwachmann@01137330-e44e-0410-aa50-acf51430b3d2"
]
| [
[
[
1,
47
]
]
]
|
f8510b135822cfd8e2376cccc114c607cb06fead | cfcd2a448c91b249ea61d0d0d747129900e9e97f | /thirdparty/OpenCOLLADA/COLLADAFramework/include/COLLADAFWShaderConstantFX.h | 7aa4e7d144dfa8ae74b148a14808e1ebc6998398 | []
| no_license | fire-archive/OgreCollada | b1686b1b84b512ffee65baddb290503fb1ebac9c | 49114208f176eb695b525dca4f79fc0cfd40e9de | refs/heads/master | 2020-04-10T10:04:15.187350 | 2009-05-31T15:33:15 | 2009-05-31T15:33:15 | 268,046 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 4,885 | h | /*
Copyright (c) 2008 NetAllied Systems GmbH
This file is part of COLLADAFramework.
Licensed under the MIT Open Source License,
for details please see LICENSE file or the website
http://www.opensource.org/licenses/mit-license.php
*/
#ifndef __COLLADAFW_SHADERCONSTANTFX_H__
#define __COLLADAFW_SHADERCONSTANTFX_H__
#include "COLLADAFWPrerequisites.h"
#include "COLLADAFWColorOrTexture.h"
#include "COLLADAFWFloatOrParam.h"
namespace COLLADAFW
{
/**
Produces a constantly shaded surface that is independent of lighting.
Used inside a <profile_COMMON> effect, declares a fixed-function pipeline that produces a
constantly shaded surface that is independent of lighting.
The reflected color is calculated as:
color = <emission> + <ambient> * al
where:
• al — A constant amount of ambient light contribution coming from the scene. In the COMMON
profile, this is the sum of all the <light><technique_common><ambient><color> values in
the <visual_scene>.
*/
class ShaderConstantFX : public ShaderElement
{
private:
/** Declares the amount of light emitted from the surface of this object. */
ColorOrTexture mEmission;
/** Declares the color of a perfect mirror reflection. */
ColorOrTexture mReflective;
/** Declares the amount of perfect mirror reflection to be added to the reflected light
as a value between 0.0 and 1.0. */
FloatOrParam mReflectivity;
/** Declares the color of perfectly refracted light. */
ColorOrTexture mTransparent;
/** Declares the amount of perfectly refracted light added to the reflected color as a
scalar value between 0.0 and 1.0. */
FloatOrParam mTransparency;
/** Declares the index of refraction for perfectly refracted light as a single scalar index. */
FloatOrParam mIndexOfRefraction;
public:
/** Constructor. */
ShaderConstantFX() {};
/** Destructor. */
virtual ~ShaderConstantFX() {};
/** Declares the amount of light emitted from the surface of this object. */
const COLLADAFW::ColorOrTexture getEmission () const { return mEmission; }
/** Declares the amount of light emitted from the surface of this object. */
void setEmission ( const COLLADAFW::ColorOrTexture Emission ) { mEmission = Emission; }
/** Declares the color of a perfect mirror reflection. */
const COLLADAFW::ColorOrTexture getReflective () const { return mReflective; }
/** Declares the color of a perfect mirror reflection. */
void setReflective ( const COLLADAFW::ColorOrTexture Reflective ) { mReflective = Reflective; }
/** Declares the amount of perfect mirror reflection to be added to the reflected light
as a value between 0.0 and 1.0. */
const COLLADAFW::FloatOrParam getReflectivity () const { return mReflectivity; }
/** Declares the amount of perfect mirror reflection to be added to the reflected light
as a value between 0.0 and 1.0. */
void setReflectivity ( const COLLADAFW::FloatOrParam Reflectivity ) { mReflectivity = Reflectivity; }
/** Declares the color of perfectly refracted light. */
const COLLADAFW::ColorOrTexture getTransparent () const { return mTransparent; }
/** Declares the color of perfectly refracted light. */
void setTransparent ( const COLLADAFW::ColorOrTexture Transparent ) { mTransparent = Transparent; }
/** Declares the amount of perfectly refracted light added to the reflected color as a
scalar value between 0.0 and 1.0. */
const COLLADAFW::FloatOrParam getTransparency () const { return mTransparency; }
/** Declares the amount of perfectly refracted light added to the reflected color as a
scalar value between 0.0 and 1.0. */
void setTransparency ( const COLLADAFW::FloatOrParam Transparency ) { mTransparency = Transparency; }
/** Declares the index of refraction for perfectly refracted light as a single scalar index. */
const COLLADAFW::FloatOrParam getIndexOfRefraction () const { return mIndexOfRefraction; }
/** Declares the index of refraction for perfectly refracted light as a single scalar index. */
void setIndexOfRefraction ( const COLLADAFW::FloatOrParam IndexOfRefraction ) { mIndexOfRefraction = IndexOfRefraction; }
private:
/** Disable default copy ctor. */
ShaderConstantFX( const ShaderConstantFX& pre );
/** Disable default assignment operator. */
const ShaderConstantFX& operator= ( const ShaderConstantFX& pre );
};
} // namespace COLLADAFW
#endif // __COLLADAFW_SHADERCONSTANTFX_H__
| [
"[email protected]"
]
| [
[
[
1,
118
]
]
]
|
9ea3a9721c0f82747ef85283d62a07441ba509c7 | c70941413b8f7bf90173533115c148411c868bad | /plugins/XmlPlugin/include/vtxxmlPlugin.h | f565c39c7b6e7c619611caa2861fbf3331fe404e | []
| no_license | cnsuhao/vektrix | ac6e028dca066aad4f942b8d9eb73665853fbbbe | 9b8c5fa7119ff7f3dc80fb05b7cdba335cf02c1a | refs/heads/master | 2021-06-23T11:28:34.907098 | 2011-03-27T17:39:37 | 2011-03-27T17:39:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,860 | h | /*
-----------------------------------------------------------------------------
This source file is part of "vektrix"
(the rich media and vector graphics rendering library)
For the latest info, see http://www.fuse-software.com/
Copyright (c) 2009-2010 Fuse-Software (tm)
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 __vtxxmlPlugin_H__
#define __vtxxmlPlugin_H__
#include "vtxxml.h"
#include "vtxPlugin.h"
#ifdef VTX_STATIC_LIB
void vektrix_XmlPlugin_startPlugin();
#else
extern "C" void vtxxmlExport startPlugin() throw();
#endif
namespace vtx
{
namespace xml
{
class XmlPlugin : public Plugin
{
public:
XmlPlugin();
virtual ~XmlPlugin();
protected:
XmlMovieParserFactory* mParserFactory;
};
}
}
#endif
| [
"stonecold_@9773a11d-1121-4470-82d2-da89bd4a628a"
]
| [
[
[
1,
57
]
]
]
|
2d5b0f0f5ccfd6990cde5872ca6c23f170ef9aed | 3cad09dde08a7f9f4fe4acbcb2ffd4643a642957 | /opencv/win/tests/cv/src/ahistograms.cpp | 581c6dff005c7d15aad9f2f8ab42d6ba2f954830 | []
| no_license | gmarcotte/cos436-eye-tracker | 420ad9c37cf1819a238c0379662dee71f6fd9b0f | 05d0b010bae8dcf06add2ae93534851668d4eff4 | refs/heads/master | 2021-01-23T13:47:38.533817 | 2009-01-15T02:40:43 | 2009-01-15T02:40:43 | 32,219,880 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 51,418 | cpp | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation 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.
//
//M*/
#include "cvtest.h"
class CV_BaseHistTest : public CvTest
{
public:
enum { MAX_HIST = 12 };
CV_BaseHistTest( const char* test_name, const char* test_funcs );
~CV_BaseHistTest();
void clear();
int write_default_params(CvFileStorage* fs);
protected:
int read_params( CvFileStorage* fs );
void run_func(void);
int prepare_test_case( int test_case_idx );
int validate_test_results( int test_case_idx );
virtual void init_hist( int test_case_idx, int i );
virtual void get_hist_params( int test_case_idx );
virtual float** get_hist_ranges( int test_case_idx );
int max_log_size;
int max_cdims;
int cdims;
int dims[CV_MAX_DIM];
int dims_sum[CV_MAX_DIM+1];
int total_size;
int hist_type;
int hist_count;
int uniform;
int gen_random_hist;
double gen_hist_max_val, gen_hist_sparse_nz_ratio;
int init_ranges;
int img_type;
int img_max_log_size;
double low, high, range_delta;
CvSize img_size;
CvHistogram* hist[MAX_HIST];
float* _ranges;
float* ranges[CV_MAX_DIM];
};
CV_BaseHistTest::CV_BaseHistTest( const char* test_name, const char* test_funcs ):
CvTest( test_name, test_funcs )
{
int i;
test_case_count = 100;
max_log_size = 20;
img_max_log_size = 8;
max_cdims = 6;
_ranges = 0;
hist_count = 1;
init_ranges = 0;
gen_random_hist = 0;
gen_hist_max_val = 100;
for( i = 0; i < MAX_HIST; i++ )
hist[i] = 0;
support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE;
}
CV_BaseHistTest::~CV_BaseHistTest()
{
clear();
}
void CV_BaseHistTest::clear()
{
int i;
CvTest::clear();
for( i = 0; i < MAX_HIST; i++ )
cvReleaseHist( &hist[i] );
delete[] _ranges;
_ranges = 0;
}
int CV_BaseHistTest::write_default_params( CvFileStorage* fs )
{
CvTest::write_default_params( fs );
if( ts->get_testing_mode() != CvTS::TIMING_MODE )
{
write_param( fs, "test_case_count", test_case_count );
write_param( fs, "max_log_size", max_log_size );
write_param( fs, "max_log_array_size", img_max_log_size );
write_param( fs, "max_dims", max_cdims );
}
return 0;
}
int CV_BaseHistTest::read_params( CvFileStorage* fs )
{
int code = CvTest::read_params( fs );
if( code < 0 )
return code;
test_case_count = cvReadInt( find_param( fs, "struct_count" ), test_case_count );
max_log_size = cvReadInt( find_param( fs, "max_log_size" ), max_log_size );
max_log_size = cvTsClipInt( max_log_size, 1, 20 );
img_max_log_size = cvReadInt( find_param( fs, "max_log_array_size" ), img_max_log_size );
img_max_log_size = cvTsClipInt( img_max_log_size, 1, 9 );
max_cdims = cvReadInt( find_param( fs, "max_cdims" ), max_cdims );
max_cdims = cvTsClipInt( max_cdims, 1, 6 );
return 0;
}
void CV_BaseHistTest::get_hist_params( int /*test_case_idx*/ )
{
CvRNG* rng = ts->get_rng();
int i, max_dim_size, max_ni_dim_size = 31;
double hist_size;
cdims = cvTsRandInt(rng) % max_cdims + 1;
hist_size = exp(cvTsRandReal(rng)*max_log_size*CV_LOG2);
max_dim_size = cvRound(pow(hist_size,1./cdims));
total_size = 1;
uniform = cvTsRandInt(rng) % 2;
hist_type = cvTsRandInt(rng) % 2 ? CV_HIST_SPARSE : CV_HIST_ARRAY;
for( i = 0; i < cdims; i++ )
{
dims[i] = cvTsRandInt(rng) % (max_dim_size + 1) + 1;
if( !uniform )
dims[i] = MIN(dims[i], max_ni_dim_size);
total_size *= dims[i];
}
img_type = cvTsRandInt(rng) % 2 ? CV_32F : CV_8U;
img_size.width = cvRound( exp(cvRandReal(rng) * img_max_log_size*CV_LOG2) );
img_size.height = cvRound( exp(cvRandReal(rng) * img_max_log_size*CV_LOG2) );
low = cvTsMinVal(img_type);
high = cvTsMaxVal(img_type);
range_delta = (cvTsRandInt(rng) % 2)*(high-low)*0.05;
}
float** CV_BaseHistTest::get_hist_ranges( int /*test_case_idx*/ )
{
double _low = low + range_delta, _high = high - range_delta;
if( init_ranges )
{
int i;
dims_sum[0] = 0;
for( i = 0; i < cdims; i++ )
dims_sum[i+1] = dims_sum[i] + dims[i] + 1;
if( uniform )
{
_ranges = new float[cdims*2];
for( i = cdims-1; i >= 0; i-- )
{
_ranges[i*2] = (float)_low;
_ranges[i*2+1] = (float)_high;
ranges[i] = _ranges + i*2;
}
}
else
{
_ranges = new float[dims_sum[cdims]];
for( i = 0; i < cdims; i++ )
{
int j, n = dims[i], ofs = dims_sum[i];
// generate logarithmic scale
double delta, q, val;
for( j = 0; j < 10; j++ )
{
q = 1. + (j+1)*0.1;
if( (pow(q,(double)n)-1)/(q-1.) >= _high-_low )
break;
}
if( j == 0 )
{
delta = (_high-_low)/n;
q = 1.;
}
else
{
q = 1 + j*0.1;
delta = cvFloor((_high-_low)*(q-1)/(pow(q,(double)n) - 1));
delta = MAX(delta, 1.);
}
val = _low;
for( j = 0; j <= n; j++ )
{
_ranges[j+ofs] = (float)MIN(val,_high);
val += delta;
delta *= q;
}
ranges[i] = _ranges + ofs;
}
}
return ranges;
}
return 0;
}
void CV_BaseHistTest::init_hist( int /*test_case_idx*/, int hist_i )
{
if( gen_random_hist )
{
CvRNG* rng = ts->get_rng();
CvArr* h = hist[hist_i]->bins;
if( hist_type == CV_HIST_ARRAY )
{
cvRandArr( rng, h, CV_RAND_UNI,
cvScalarAll(0), cvScalarAll(gen_hist_max_val) );
}
else
{
int i, j, total_size = 1, nz_count;
int idx[CV_MAX_DIM];
for( i = 0; i < cdims; i++ )
total_size *= dims[i];
nz_count = cvTsRandInt(rng) % MAX( total_size/4, 100 );
nz_count = MIN( nz_count, total_size );
// a zero number of non-zero elements should be allowed
for( i = 0; i < nz_count; i++ )
{
for( j = 0; j < cdims; j++ )
idx[j] = cvTsRandInt(rng) % dims[j];
cvSetRealND( h, idx, cvTsRandReal(rng)*gen_hist_max_val );
}
}
}
}
int CV_BaseHistTest::prepare_test_case( int test_case_idx )
{
int i;
float** r;
clear();
CvTest::prepare_test_case( test_case_idx );
get_hist_params( test_case_idx );
r = get_hist_ranges( test_case_idx );
for( i = 0; i < hist_count; i++ )
{
hist[i] = cvCreateHist( cdims, dims, hist_type, r, uniform );
init_hist( test_case_idx, i );
}
return 1;
}
void CV_BaseHistTest::run_func(void)
{
}
int CV_BaseHistTest::validate_test_results( int /*test_case_idx*/ )
{
return 0;
}
CV_BaseHistTest hist_basetest( "hist", "" );
////////////// testing operation for reading/writing individual histogram bins //////////////
class CV_QueryHistTest : public CV_BaseHistTest
{
public:
CV_QueryHistTest();
~CV_QueryHistTest();
void clear();
protected:
void run_func(void);
int prepare_test_case( int test_case_idx );
int validate_test_results( int test_case_idx );
void init_hist( int test_case_idx, int i );
CvMat* indices;
CvMat* values;
CvMat* values0;
};
CV_QueryHistTest::CV_QueryHistTest() : CV_BaseHistTest( "hist-query",
"cvGetReal1D, cvGetReal2D, cvGetReal3D, cvGetRealND, "
"cvPtr1D, cvPtr2D, cvPtr3D, cvPtrND, "
"cvSetReal1D, cvSetReal2D, cvSetReal3D, cvSetRealND" )
{
hist_count = 1;
indices = 0;
values = 0;
values0 = 0;
}
CV_QueryHistTest::~CV_QueryHistTest()
{
clear();
}
void CV_QueryHistTest::clear()
{
cvReleaseMat( &indices );
cvReleaseMat( &values );
cvReleaseMat( &values0 );
CV_BaseHistTest::clear();
}
void CV_QueryHistTest::init_hist( int /*test_case_idx*/, int i )
{
if( hist_type == CV_HIST_ARRAY )
cvZero( hist[i]->bins );
}
int CV_QueryHistTest::prepare_test_case( int test_case_idx )
{
int code = CV_BaseHistTest::prepare_test_case( test_case_idx );
if( code > 0 )
{
int i, j, iters;
float default_value = 0.f;
CvRNG* rng = ts->get_rng();
CvMat* bit_mask = 0;
int* idx;
iters = (cvTsRandInt(rng) % MAX(total_size/10,100)) + 1;
iters = MIN( iters, total_size*9/10 + 1 );
indices = cvCreateMat( 1, iters*cdims, CV_32S );
values = cvCreateMat( 1, iters, CV_32F );
values0 = cvCreateMat( 1, iters, CV_32F );
idx = indices->data.i;
//printf( "total_size = %d, cdims = %d, iters = %d\n", total_size, cdims, iters );
bit_mask = cvCreateMat( 1, (total_size + 7)/8, CV_8U );
cvZero( bit_mask );
#define GET_BIT(n) (bit_mask->data.ptr[(n)/8] & (1 << ((n)&7)))
#define SET_BIT(n) bit_mask->data.ptr[(n)/8] |= (1 << ((n)&7))
// set random histogram bins' values to the linear indices of the bins
for( i = 0; i < iters; i++ )
{
int lin_idx = 0;
for( j = 0; j < cdims; j++ )
{
int t = cvTsRandInt(rng) % dims[j];
idx[i*cdims + j] = t;
lin_idx = lin_idx*dims[j] + t;
}
if( cvTsRandInt(rng) % 8 || GET_BIT(lin_idx) )
{
values0->data.fl[i] = (float)(lin_idx+1);
SET_BIT(lin_idx);
}
else
// some histogram bins will not be initialized intentionally,
// they should be equal to the default value
values0->data.fl[i] = default_value;
}
// do the second pass to make values0 consistent with bit_mask
for( i = 0; i < iters; i++ )
{
int lin_idx = 0;
for( j = 0; j < cdims; j++ )
lin_idx = lin_idx*dims[j] + idx[i*cdims + j];
if( GET_BIT(lin_idx) )
values0->data.fl[i] = (float)(lin_idx+1);
}
cvReleaseMat( &bit_mask );
}
return code;
}
void CV_QueryHistTest::run_func(void)
{
int i, iters = values->cols;
CvArr* h = hist[0]->bins;
const int* idx = indices->data.i;
float* val = values->data.fl;
float default_value = 0.f;
// stage 1: write bins
if( cdims == 1 )
for( i = 0; i < iters; i++ )
{
float v0 = values0->data.fl[i];
if( fabs(v0 - default_value) < FLT_EPSILON )
continue;
if( !(i % 2) )
{
if( !(i % 4) )
cvSetReal1D( h, idx[i], v0 );
else
*(float*)cvPtr1D( h, idx[i] ) = v0;
}
else
cvSetRealND( h, idx+i, v0 );
}
else if( cdims == 2 )
for( i = 0; i < iters; i++ )
{
float v0 = values0->data.fl[i];
if( fabs(v0 - default_value) < FLT_EPSILON )
continue;
if( !(i % 2) )
{
if( !(i % 4) )
cvSetReal2D( h, idx[i*2], idx[i*2+1], v0 );
else
*(float*)cvPtr2D( h, idx[i*2], idx[i*2+1] ) = v0;
}
else
cvSetRealND( h, idx+i*2, v0 );
}
else if( cdims == 3 )
for( i = 0; i < iters; i++ )
{
float v0 = values0->data.fl[i];
if( fabs(v0 - default_value) < FLT_EPSILON )
continue;
if( !(i % 2) )
{
if( !(i % 4) )
cvSetReal3D( h, idx[i*3], idx[i*3+1], idx[i*3+2], v0 );
else
*(float*)cvPtr3D( h, idx[i*3], idx[i*3+1], idx[i*3+2] ) = v0;
}
else
cvSetRealND( h, idx+i*3, v0 );
}
else
for( i = 0; i < iters; i++ )
{
float v0 = values0->data.fl[i];
if( fabs(v0 - default_value) < FLT_EPSILON )
continue;
if( !(i % 2) )
cvSetRealND( h, idx+i*cdims, v0 );
else
*(float*)cvPtrND( h, idx+i*cdims ) = v0;
}
// stage 2: read bins
if( cdims == 1 )
for( i = 0; i < iters; i++ )
{
if( !(i % 2) )
val[i] = *(float*)cvPtr1D( h, idx[i] );
else
val[i] = (float)cvGetReal1D( h, idx[i] );
}
else if( cdims == 2 )
for( i = 0; i < iters; i++ )
{
if( !(i % 2) )
val[i] = *(float*)cvPtr2D( h, idx[i*2], idx[i*2+1] );
else
val[i] = (float)cvGetReal2D( h, idx[i*2], idx[i*2+1] );
}
else if( cdims == 3 )
for( i = 0; i < iters; i++ )
{
if( !(i % 2) )
val[i] = *(float*)cvPtr3D( h, idx[i*3], idx[i*3+1], idx[i*3+2] );
else
val[i] = (float)cvGetReal3D( h, idx[i*3], idx[i*3+1], idx[i*3+2] );
}
else
for( i = 0; i < iters; i++ )
{
if( !(i % 2) )
val[i] = *(float*)cvPtrND( h, idx+i*cdims );
else
val[i] = (float)cvGetRealND( h, idx+i*cdims );
}
}
int CV_QueryHistTest::validate_test_results( int /*test_case_idx*/ )
{
int code = CvTS::OK;
int i, j, iters = values->cols;
for( i = 0; i < iters; i++ )
{
float v = values->data.fl[i], v0 = values0->data.fl[i];
if( cvIsNaN(v) || cvIsInf(v) )
{
ts->printf( CvTS::LOG, "The bin #%d has invalid value\n", i );
code = CvTS::FAIL_INVALID_OUTPUT;
}
else if( fabs(v - v0) > FLT_EPSILON )
{
ts->printf( CvTS::LOG, "The bin #%d = %g, while it should be %g\n", i, v, v0 );
code = CvTS::FAIL_BAD_ACCURACY;
}
if( code < 0 )
{
ts->printf( CvTS::LOG, "The bin index = (" );
for( j = 0; j < cdims; j++ )
ts->printf( CvTS::LOG, "%d%s", indices->data.i[i*cdims + j],
j < cdims-1 ? ", " : ")\n" );
break;
}
}
if( code < 0 )
ts->set_failed_test_info( code );
return code;
}
CV_QueryHistTest hist_query_test;
////////////// cvGetMinMaxHistValue //////////////
class CV_MinMaxHistTest : public CV_BaseHistTest
{
public:
CV_MinMaxHistTest();
protected:
void run_func(void);
void init_hist(int, int);
int validate_test_results( int test_case_idx );
int min_idx[CV_MAX_DIM], max_idx[CV_MAX_DIM];
float min_val, max_val;
int min_idx0[CV_MAX_DIM], max_idx0[CV_MAX_DIM];
float min_val0, max_val0;
};
CV_MinMaxHistTest::CV_MinMaxHistTest() :
CV_BaseHistTest( "hist-minmax", "cvGetMinMaxHistValue" )
{
hist_count = 1;
gen_random_hist = 1;
}
void CV_MinMaxHistTest::init_hist(int test_case_idx, int hist_i)
{
int i, eq = 1;
CvRNG* rng = ts->get_rng();
CV_BaseHistTest::init_hist( test_case_idx, hist_i );
for(;;)
{
for( i = 0; i < cdims; i++ )
{
min_idx0[i] = cvTsRandInt(rng) % dims[i];
max_idx0[i] = cvTsRandInt(rng) % dims[i];
eq &= min_idx0[i] == max_idx0[i];
}
if( !eq || total_size == 1 )
break;
}
min_val0 = (float)(-cvTsRandReal(rng)*10 - FLT_EPSILON);
max_val0 = (float)(cvTsRandReal(rng)*10 + FLT_EPSILON + gen_hist_max_val);
if( total_size == 1 )
min_val0 = max_val0;
cvSetRealND( hist[0]->bins, min_idx0, min_val0 );
cvSetRealND( hist[0]->bins, max_idx0, max_val0 );
}
void CV_MinMaxHistTest::run_func(void)
{
cvGetMinMaxHistValue( hist[0], &min_val, &max_val, min_idx, max_idx );
}
int CV_MinMaxHistTest::validate_test_results( int /*test_case_idx*/ )
{
int code = CvTS::OK;
if( cvIsNaN(min_val) || cvIsInf(min_val) ||
cvIsNaN(max_val) || cvIsInf(max_val) )
{
ts->printf( CvTS::LOG,
"The extrema histogram bin values are invalid (min = %g, max = %g)\n", min_val, max_val );
code = CvTS::FAIL_INVALID_OUTPUT;
}
else if( fabs(min_val - min_val0) > FLT_EPSILON ||
fabs(max_val - max_val0) > FLT_EPSILON )
{
ts->printf( CvTS::LOG,
"The extrema histogram bin values are incorrect: (min = %g, should be = %g), (max = %g, should be = %g)\n",
min_val, min_val0, max_val, max_val0 );
code = CvTS::FAIL_BAD_ACCURACY;
}
else
{
int i;
for( i = 0; i < cdims; i++ )
{
if( min_idx[i] != min_idx0[i] || max_idx[i] != max_idx0[i] )
{
ts->printf( CvTS::LOG,
"The %d-th coordinates of extrema histogram bin values are incorrect: "
"(min = %d, should be = %d), (max = %d, should be = %d)\n",
i, min_idx[i], min_idx0[i], max_idx[i], max_idx0[i] );
code = CvTS::FAIL_BAD_ACCURACY;
}
}
}
if( code < 0 )
ts->set_failed_test_info( code );
return code;
}
CV_MinMaxHistTest hist_minmax_test;
////////////// cvNormalizeHist //////////////
class CV_NormHistTest : public CV_BaseHistTest
{
public:
CV_NormHistTest();
protected:
int prepare_test_case( int test_case_idx );
void run_func(void);
int validate_test_results( int test_case_idx );
double factor;
};
CV_NormHistTest::CV_NormHistTest() :
CV_BaseHistTest( "hist-normalize", "cvNormalizeHist" )
{
hist_count = 1;
gen_random_hist = 1;
factor = 0;
}
int CV_NormHistTest::prepare_test_case( int test_case_idx )
{
int code = CV_BaseHistTest::prepare_test_case( test_case_idx );
if( code > 0 )
{
CvRNG* rng = ts->get_rng();
factor = cvTsRandReal(rng)*10 + 0.1;
if( hist_type == CV_HIST_SPARSE &&
((CvSparseMat*)hist[0]->bins)->heap->active_count == 0 )
factor = 0;
}
return code;
}
void CV_NormHistTest::run_func(void)
{
cvNormalizeHist( hist[0], factor );
}
int CV_NormHistTest::validate_test_results( int /*test_case_idx*/ )
{
int code = CvTS::OK;
double sum = 0;
if( hist_type == CV_HIST_ARRAY )
{
int i;
const float* ptr = (float*)cvPtr1D( hist[0]->bins, 0 );
for( i = 0; i < total_size; i++ )
sum += ptr[i];
}
else
{
CvSparseMat* sparse = (CvSparseMat*)hist[0]->bins;
CvSparseMatIterator iterator;
CvSparseNode *node;
for( node = cvInitSparseMatIterator( sparse, &iterator );
node != 0; node = cvGetNextSparseNode( &iterator ))
{
sum += *(float*)CV_NODE_VAL(sparse,node);
}
}
if( cvIsNaN(sum) || cvIsInf(sum) )
{
ts->printf( CvTS::LOG,
"The normalized histogram has invalid sum =%g\n", sum );
code = CvTS::FAIL_INVALID_OUTPUT;
}
else if( fabs(sum - factor) > FLT_EPSILON*10*fabs(factor) )
{
ts->printf( CvTS::LOG,
"The normalized histogram has incorrect sum =%g, while it should be =%g\n", sum, factor );
code = CvTS::FAIL_BAD_ACCURACY;
}
if( code < 0 )
ts->set_failed_test_info( code );
return code;
}
CV_NormHistTest hist_norm_test;
////////////// cvThreshHist //////////////
class CV_ThreshHistTest : public CV_BaseHistTest
{
public:
CV_ThreshHistTest();
~CV_ThreshHistTest();
void clear();
protected:
int prepare_test_case( int test_case_idx );
void run_func(void);
int validate_test_results( int test_case_idx );
CvMat* indices;
CvMat* values;
int orig_nz_count;
double threshold;
};
CV_ThreshHistTest::CV_ThreshHistTest() :
CV_BaseHistTest( "hist-threshold", "cvThreshHist" )
{
hist_count = 1;
gen_random_hist = 1;
threshold = 0;
indices = values = 0;
}
CV_ThreshHistTest::~CV_ThreshHistTest()
{
clear();
}
void CV_ThreshHistTest::clear()
{
cvReleaseMat( &indices );
cvReleaseMat( &values );
CV_BaseHistTest::clear();
}
int CV_ThreshHistTest::prepare_test_case( int test_case_idx )
{
int code = CV_BaseHistTest::prepare_test_case( test_case_idx );
if( code > 0 )
{
CvRNG* rng = ts->get_rng();
threshold = cvTsRandReal(rng)*gen_hist_max_val;
if( hist_type == CV_HIST_ARRAY )
{
orig_nz_count = total_size;
values = cvCreateMat( 1, total_size, CV_32F );
memcpy( values->data.fl, cvPtr1D( hist[0]->bins, 0 ), total_size*sizeof(float) );
}
else
{
CvSparseMat* sparse = (CvSparseMat*)hist[0]->bins;
CvSparseMatIterator iterator;
CvSparseNode* node;
int i, k;
orig_nz_count = sparse->heap->active_count;
values = cvCreateMat( 1, orig_nz_count+1, CV_32F );
indices = cvCreateMat( 1, (orig_nz_count+1)*cdims, CV_32S );
for( node = cvInitSparseMatIterator( sparse, &iterator ), i = 0;
node != 0; node = cvGetNextSparseNode( &iterator ), i++ )
{
const int* idx = CV_NODE_IDX(sparse,node);
OPENCV_ASSERT( i < orig_nz_count, "CV_ThreshHistTest::prepare_test_case", "Buffer overflow" );
values->data.fl[i] = *(float*)CV_NODE_VAL(sparse,node);
for( k = 0; k < cdims; k++ )
indices->data.i[i*cdims + k] = idx[k];
}
OPENCV_ASSERT( i == orig_nz_count, "Unmatched buffer size",
"CV_ThreshHistTest::prepare_test_case" );
}
}
return code;
}
void CV_ThreshHistTest::run_func(void)
{
cvThreshHist( hist[0], threshold );
}
int CV_ThreshHistTest::validate_test_results( int /*test_case_idx*/ )
{
int code = CvTS::OK;
int i;
float* ptr0 = values->data.fl;
float* ptr = 0;
CvSparseMat* sparse = 0;
if( hist_type == CV_HIST_ARRAY )
ptr = (float*)cvPtr1D( hist[0]->bins, 0 );
else
sparse = (CvSparseMat*)hist[0]->bins;
if( code > 0 )
{
for( i = 0; i < orig_nz_count; i++ )
{
float v0 = ptr0[i], v;
if( hist_type == CV_HIST_ARRAY )
v = ptr[i];
else
{
v = (float)cvGetRealND( sparse, indices->data.i + i*cdims );
cvClearND( sparse, indices->data.i + i*cdims );
}
if( v0 <= threshold ) v0 = 0.f;
if( cvIsNaN(v) || cvIsInf(v) )
{
ts->printf( CvTS::LOG, "The %d-th bin is invalid (=%g)\n", i, v );
code = CvTS::FAIL_INVALID_OUTPUT;
break;
}
else if( fabs(v0 - v) > FLT_EPSILON*10*fabs(v0) )
{
ts->printf( CvTS::LOG, "The %d-th bin is incorrect (=%g, should be =%g)\n", i, v, v0 );
code = CvTS::FAIL_BAD_ACCURACY;
break;
}
}
}
if( code > 0 && hist_type == CV_HIST_SPARSE )
{
if( sparse->heap->active_count > 0 )
{
ts->printf( CvTS::LOG,
"There some extra histogram bins in the sparse histogram after the thresholding\n" );
code = CvTS::FAIL_INVALID_OUTPUT;
}
}
if( code < 0 )
ts->set_failed_test_info( code );
return code;
}
CV_ThreshHistTest hist_thresh_test;
////////////// cvCompareHist //////////////
class CV_CompareHistTest : public CV_BaseHistTest
{
public:
enum { MAX_METHOD = 4 };
CV_CompareHistTest();
protected:
int prepare_test_case( int test_case_idx );
void run_func(void);
int validate_test_results( int test_case_idx );
double result[MAX_METHOD+1];
};
CV_CompareHistTest::CV_CompareHistTest() :
CV_BaseHistTest( "hist-compare", "cvCompareHist" )
{
hist_count = 2;
gen_random_hist = 1;
}
int CV_CompareHistTest::prepare_test_case( int test_case_idx )
{
int code = CV_BaseHistTest::prepare_test_case( test_case_idx );
return code;
}
void CV_CompareHistTest::run_func(void)
{
int k;
for( k = 0; k < MAX_METHOD; k++ )
result[k] = cvCompareHist( hist[0], hist[1], k );
}
int CV_CompareHistTest::validate_test_results( int /*test_case_idx*/ )
{
int code = CvTS::OK;
int i;
double result0[MAX_METHOD+1];
double s0 = 0, s1 = 0, sq0 = 0, sq1 = 0, t;
for( i = 0; i < MAX_METHOD; i++ )
result0[i] = 0;
if( hist_type == CV_HIST_ARRAY )
{
float* ptr0 = (float*)cvPtr1D( hist[0]->bins, 0 );
float* ptr1 = (float*)cvPtr1D( hist[1]->bins, 0 );
for( i = 0; i < total_size; i++ )
{
double v0 = ptr0[i], v1 = ptr1[i];
result0[CV_COMP_CORREL] += v0*v1;
result0[CV_COMP_INTERSECT] += MIN(v0,v1);
if( fabs(v0 + v1) > DBL_EPSILON )
result0[CV_COMP_CHISQR] += (v0 - v1)*(v0 - v1)/(v0 + v1);
s0 += v0;
s1 += v1;
sq0 += v0*v0;
sq1 += v1*v1;
result0[CV_COMP_BHATTACHARYYA] += sqrt(v0*v1);
}
}
else
{
CvSparseMat* sparse0 = (CvSparseMat*)hist[0]->bins;
CvSparseMat* sparse1 = (CvSparseMat*)hist[1]->bins;
CvSparseMatIterator iterator;
CvSparseNode* node;
for( node = cvInitSparseMatIterator( sparse0, &iterator );
node != 0; node = cvGetNextSparseNode( &iterator ) )
{
const int* idx = CV_NODE_IDX(sparse0, node);
double v0 = *(float*)CV_NODE_VAL(sparse0, node);
double v1 = (float)cvGetRealND(sparse1, idx);
result0[CV_COMP_CORREL] += v0*v1;
result0[CV_COMP_INTERSECT] += MIN(v0,v1);
if( fabs(v0 + v1) > DBL_EPSILON )
result0[CV_COMP_CHISQR] += (v0 - v1)*(v0 - v1)/(v0 + v1);
s0 += v0;
sq0 += v0*v0;
result0[CV_COMP_BHATTACHARYYA] += sqrt(v0*v1);
}
for( node = cvInitSparseMatIterator( sparse1, &iterator );
node != 0; node = cvGetNextSparseNode( &iterator ) )
{
const int* idx = CV_NODE_IDX(sparse1, node);
double v1 = *(float*)CV_NODE_VAL(sparse1, node);
double v0 = (float)cvGetRealND(sparse0, idx);
if( fabs(v0) < DBL_EPSILON )
result0[CV_COMP_CHISQR] += v1;
s1 += v1;
sq1 += v1*v1;
}
}
t = (sq0 - s0*s0/total_size)*(sq1 - s1*s1/total_size);
result0[CV_COMP_CORREL] = fabs(t) > DBL_EPSILON ?
(result0[CV_COMP_CORREL] - s0*s1/total_size)/sqrt(t) : 1;
s1 *= s0;
s0 = result0[CV_COMP_BHATTACHARYYA];
s0 = 1. - s0*(s1 > FLT_EPSILON ? 1./sqrt(s1) : 1.);
result0[CV_COMP_BHATTACHARYYA] = sqrt(MAX(s0,0.));
for( i = 0; i < MAX_METHOD; i++ )
{
double v = result[i], v0 = result0[i];
const char* method_name =
i == CV_COMP_CHISQR ? "Chi-Square" :
i == CV_COMP_CORREL ? "Correlation" :
i == CV_COMP_INTERSECT ? "Intersection" :
i == CV_COMP_BHATTACHARYYA ? "Bhattacharyya" : "Unknown";
if( cvIsNaN(v) || cvIsInf(v) )
{
ts->printf( CvTS::LOG, "The comparison result using the method #%d (%s) is invalid (=%g)\n",
i, method_name, v );
code = CvTS::FAIL_INVALID_OUTPUT;
break;
}
else if( fabs(v0 - v) > FLT_EPSILON*10*MAX(fabs(v0),0.1) )
{
ts->printf( CvTS::LOG, "The comparison result using the method #%d (%s)\n\tis inaccurate (=%g, should be =%g)\n",
i, method_name, v, v0 );
code = CvTS::FAIL_BAD_ACCURACY;
break;
}
}
if( code < 0 )
ts->set_failed_test_info( code );
return code;
}
CV_CompareHistTest hist_compare_test;
////////////// cvCalcHist //////////////
class CV_CalcHistTest : public CV_BaseHistTest
{
public:
CV_CalcHistTest();
~CV_CalcHistTest();
void clear();
protected:
int prepare_test_case( int test_case_idx );
void run_func(void);
int validate_test_results( int test_case_idx );
IplImage* images[CV_MAX_DIM+1];
int channels[CV_MAX_DIM+1];
};
CV_CalcHistTest::CV_CalcHistTest() :
CV_BaseHistTest( "hist-calc", "cvCalcHist" )
{
int i;
hist_count = 2;
gen_random_hist = 0;
init_ranges = 1;
for( i = 0; i <= CV_MAX_DIM; i++ )
{
images[i] = 0;
channels[i] = 0;
}
}
CV_CalcHistTest::~CV_CalcHistTest()
{
clear();
}
void CV_CalcHistTest::clear()
{
int i;
for( i = 0; i <= CV_MAX_DIM; i++ )
cvReleaseImage( &images[i] );
CV_BaseHistTest::clear();
}
int CV_CalcHistTest::prepare_test_case( int test_case_idx )
{
int code = CV_BaseHistTest::prepare_test_case( test_case_idx );
if( code > 0 )
{
CvRNG* rng = ts->get_rng();
int i;
for( i = 0; i <= CV_MAX_DIM; i++ )
{
if( i < cdims )
{
int nch = 1; //cvTsRandInt(rng) % 3 + 1;
images[i] = cvCreateImage( img_size,
img_type == CV_8U ? IPL_DEPTH_8U : IPL_DEPTH_32F, nch );
channels[i] = cvTsRandInt(rng) % nch;
cvRandArr( rng, images[i], CV_RAND_UNI,
cvScalarAll(low), cvScalarAll(high) );
}
else if( i == CV_MAX_DIM && cvTsRandInt(rng) % 2 )
{
// create mask
images[i] = cvCreateImage( img_size, IPL_DEPTH_8U, 1 );
// make ~25% pixels in the mask non-zero
cvRandArr( rng, images[i], CV_RAND_UNI,
cvScalarAll(-2), cvScalarAll(2) );
}
}
}
return code;
}
void CV_CalcHistTest::run_func(void)
{
cvCalcHist( images, hist[0], 0, images[CV_MAX_DIM] );
}
static void
cvTsCalcHist( IplImage** _images, CvHistogram* hist, IplImage* _mask, int* channels )
{
int x, y, k, cdims;
union
{
float* fl;
uchar* ptr;
}
plane[CV_MAX_DIM];
int nch[CV_MAX_DIM];
int dims[CV_MAX_DIM];
int uniform = CV_IS_UNIFORM_HIST(hist);
CvSize img_size = cvGetSize(_images[0]);
CvMat images[CV_MAX_DIM], mask = cvMat(1,1,CV_8U);
int img_depth = _images[0]->depth;
cdims = cvGetDims( hist->bins, dims );
cvZero( hist->bins );
for( k = 0; k < cdims; k++ )
{
cvGetMat( _images[k], &images[k] );
nch[k] = _images[k]->nChannels;
}
if( _mask )
cvGetMat( _mask, &mask );
for( y = 0; y < img_size.height; y++ )
{
const uchar* mptr = _mask ? &CV_MAT_ELEM(mask, uchar, y, 0 ) : 0;
if( img_depth == IPL_DEPTH_8U )
for( k = 0; k < cdims; k++ )
plane[k].ptr = &CV_MAT_ELEM(images[k], uchar, y, 0 ) + channels[k];
else
for( k = 0; k < cdims; k++ )
plane[k].fl = &CV_MAT_ELEM(images[k], float, y, 0 ) + channels[k];
for( x = 0; x < img_size.width; x++ )
{
float val[CV_MAX_DIM];
int idx[CV_MAX_DIM];
if( mptr && !mptr[x] )
continue;
if( img_depth == IPL_DEPTH_8U )
for( k = 0; k < cdims; k++ )
val[k] = plane[k].ptr[x*nch[k]];
else
for( k = 0; k < cdims; k++ )
val[k] = plane[k].fl[x*nch[k]];
idx[cdims-1] = -1;
if( uniform )
{
for( k = 0; k < cdims; k++ )
{
double v = val[k], lo = hist->thresh[k][0], hi = hist->thresh[k][1];
idx[k] = cvFloor((v - lo)*dims[k]/(hi - lo));
if( idx[k] < 0 || idx[k] >= dims[k] )
break;
}
}
else
{
for( k = 0; k < cdims; k++ )
{
float v = val[k];
float* t = hist->thresh2[k];
int j, n = dims[k];
for( j = 0; j <= n; j++ )
if( v < t[j] )
break;
if( j <= 0 || j > n )
break;
idx[k] = j-1;
}
}
if( k < cdims )
continue;
(*(float*)cvPtrND( hist->bins, idx ))++;
}
}
}
int CV_CalcHistTest::validate_test_results( int /*test_case_idx*/ )
{
int code = CvTS::OK;
double diff;
cvTsCalcHist( images, hist[1], images[CV_MAX_DIM], channels );
diff = cvCompareHist( hist[0], hist[1], CV_COMP_CHISQR );
if( diff > DBL_EPSILON )
{
ts->printf( CvTS::LOG, "The histogram does not match to the reference one\n" );
code = CvTS::FAIL_BAD_ACCURACY;
}
if( code < 0 )
ts->set_failed_test_info( code );
return code;
}
CV_CalcHistTest hist_calc_test;
////////////// cvCalcBackProject //////////////
class CV_CalcBackProjectTest : public CV_BaseHistTest
{
public:
CV_CalcBackProjectTest();
~CV_CalcBackProjectTest();
void clear();
protected:
int prepare_test_case( int test_case_idx );
void run_func(void);
int validate_test_results( int test_case_idx );
IplImage* images[CV_MAX_DIM+3];
int channels[CV_MAX_DIM+3];
};
CV_CalcBackProjectTest::CV_CalcBackProjectTest() :
CV_BaseHistTest( "hist-backproj", "cvCalcBackProject" )
{
int i;
hist_count = 1;
gen_random_hist = 0;
init_ranges = 1;
for( i = 0; i < CV_MAX_DIM+3; i++ )
{
images[i] = 0;
channels[i] = 0;
}
}
CV_CalcBackProjectTest::~CV_CalcBackProjectTest()
{
clear();
}
void CV_CalcBackProjectTest::clear()
{
int i;
for( i = 0; i < CV_MAX_DIM+3; i++ )
cvReleaseImage( &images[i] );
CV_BaseHistTest::clear();
}
int CV_CalcBackProjectTest::prepare_test_case( int test_case_idx )
{
int code = CV_BaseHistTest::prepare_test_case( test_case_idx );
if( code > 0 )
{
CvRNG* rng = ts->get_rng();
int i, j, n, img_len = img_size.width*img_size.height;
for( i = 0; i < CV_MAX_DIM + 3; i++ )
{
if( i < cdims )
{
int nch = 1; //cvTsRandInt(rng) % 3 + 1;
images[i] = cvCreateImage( img_size,
img_type == CV_8U ? IPL_DEPTH_8U : IPL_DEPTH_32F, nch );
channels[i] = cvTsRandInt(rng) % nch;
cvRandArr( rng, images[i], CV_RAND_UNI,
cvScalarAll(low), cvScalarAll(high) );
}
else if( i == CV_MAX_DIM && cvTsRandInt(rng) % 2 )
{
// create mask
images[i] = cvCreateImage( img_size, IPL_DEPTH_8U, 1 );
// make ~25% pixels in the mask non-zero
cvRandArr( rng, images[i], CV_RAND_UNI,
cvScalarAll(-2), cvScalarAll(2) );
}
else if( i > CV_MAX_DIM )
{
images[i] = cvCreateImage( img_size, images[0]->depth, 1 );
}
}
cvTsCalcHist( images, hist[0], images[CV_MAX_DIM], channels );
// now modify the images a bit to add some zeros go to the backprojection
n = cvTsRandInt(rng) % (img_len/20+1);
for( i = 0; i < cdims; i++ )
{
char* data = images[i]->imageData;
for( j = 0; j < n; j++ )
{
int idx = cvTsRandInt(rng) % img_len;
double val = cvTsRandReal(rng)*(high - low) + low;
if( img_type == CV_8U )
((uchar*)data)[idx] = (uchar)cvRound(val);
else
((float*)data)[idx] = (float)val;
}
}
}
return code;
}
void CV_CalcBackProjectTest::run_func(void)
{
cvCalcBackProject( images, images[CV_MAX_DIM+1], hist[0] );
}
static void
cvTsCalcBackProject( IplImage** images, IplImage* dst, CvHistogram* hist, int* channels )
{
int x, y, k, cdims;
union
{
float* fl;
uchar* ptr;
}
plane[CV_MAX_DIM];
int nch[CV_MAX_DIM];
int dims[CV_MAX_DIM];
int uniform = CV_IS_UNIFORM_HIST(hist);
CvSize img_size = cvGetSize(images[0]);
int img_depth = images[0]->depth;
cdims = cvGetDims( hist->bins, dims );
for( k = 0; k < cdims; k++ )
nch[k] = images[k]->nChannels;
for( y = 0; y < img_size.height; y++ )
{
if( img_depth == IPL_DEPTH_8U )
for( k = 0; k < cdims; k++ )
plane[k].ptr = &CV_IMAGE_ELEM(images[k], uchar, y, 0 ) + channels[k];
else
for( k = 0; k < cdims; k++ )
plane[k].fl = &CV_IMAGE_ELEM(images[k], float, y, 0 ) + channels[k];
for( x = 0; x < img_size.width; x++ )
{
float val[CV_MAX_DIM];
float bin_val = 0;
int idx[CV_MAX_DIM];
if( img_depth == IPL_DEPTH_8U )
for( k = 0; k < cdims; k++ )
val[k] = plane[k].ptr[x*nch[k]];
else
for( k = 0; k < cdims; k++ )
val[k] = plane[k].fl[x*nch[k]];
idx[cdims-1] = -1;
if( uniform )
{
for( k = 0; k < cdims; k++ )
{
double v = val[k], lo = hist->thresh[k][0], hi = hist->thresh[k][1];
idx[k] = cvFloor((v - lo)*dims[k]/(hi - lo));
if( idx[k] < 0 || idx[k] >= dims[k] )
break;
}
}
else
{
for( k = 0; k < cdims; k++ )
{
float v = val[k];
float* t = hist->thresh2[k];
int j, n = dims[k];
for( j = 0; j <= n; j++ )
if( v < t[j] )
break;
if( j <= 0 || j > n )
break;
idx[k] = j-1;
}
}
if( k == cdims )
bin_val = (float)cvGetRealND( hist->bins, idx );
if( img_depth == IPL_DEPTH_8U )
{
int t = cvRound(bin_val);
CV_IMAGE_ELEM( dst, uchar, y, x ) = CV_CAST_8U(t);
}
else
CV_IMAGE_ELEM( dst, float, y, x ) = bin_val;
}
}
}
int CV_CalcBackProjectTest::validate_test_results( int /*test_case_idx*/ )
{
int code = CvTS::OK;
cvTsCalcBackProject( images, images[CV_MAX_DIM+2], hist[0], channels );
code = cvTsCmpEps2( ts, images[CV_MAX_DIM+1], images[CV_MAX_DIM+2], 0, true,
"Back project image" );
if( code < 0 )
ts->set_failed_test_info( code );
return code;
}
CV_CalcBackProjectTest hist_backproj_test;
////////////// cvCalcBackProjectPatch //////////////
class CV_CalcBackProjectPatchTest : public CV_BaseHistTest
{
public:
CV_CalcBackProjectPatchTest();
~CV_CalcBackProjectPatchTest();
void clear();
protected:
int prepare_test_case( int test_case_idx );
void run_func(void);
int validate_test_results( int test_case_idx );
IplImage* images[CV_MAX_DIM+2];
int channels[CV_MAX_DIM+2];
CvSize patch_size;
double factor;
int method;
};
CV_CalcBackProjectPatchTest::CV_CalcBackProjectPatchTest() :
CV_BaseHistTest( "hist-backprojpatch", "cvCalcBackProjectPatch" )
{
int i;
hist_count = 1;
gen_random_hist = 0;
init_ranges = 1;
img_max_log_size = 7;
for( i = 0; i < CV_MAX_DIM+2; i++ )
{
images[i] = 0;
channels[i] = 0;
}
}
CV_CalcBackProjectPatchTest::~CV_CalcBackProjectPatchTest()
{
clear();
}
void CV_CalcBackProjectPatchTest::clear()
{
int i;
for( i = 0; i < CV_MAX_DIM+2; i++ )
cvReleaseImage( &images[i] );
CV_BaseHistTest::clear();
}
int CV_CalcBackProjectPatchTest::prepare_test_case( int test_case_idx )
{
int code = CV_BaseHistTest::prepare_test_case( test_case_idx );
if( code > 0 )
{
CvRNG* rng = ts->get_rng();
int i, j, n, img_len = img_size.width*img_size.height;
patch_size.width = cvTsRandInt(rng) % img_size.width + 1;
patch_size.height = cvTsRandInt(rng) % img_size.height + 1;
patch_size.width = MIN( patch_size.width, 30 );
patch_size.height = MIN( patch_size.height, 30 );
factor = 1.;
method = cvTsRandInt(rng) % CV_CompareHistTest::MAX_METHOD;
for( i = 0; i < CV_MAX_DIM + 2; i++ )
{
if( i < cdims )
{
int nch = 1; //cvTsRandInt(rng) % 3 + 1;
images[i] = cvCreateImage( img_size,
img_type == CV_8U ? IPL_DEPTH_8U : IPL_DEPTH_32F, nch );
channels[i] = cvTsRandInt(rng) % nch;
cvRandArr( rng, images[i], CV_RAND_UNI,
cvScalarAll(low), cvScalarAll(high) );
}
else if( i >= CV_MAX_DIM )
{
images[i] = cvCreateImage(
cvSize(img_size.width - patch_size.width + 1,
img_size.height - patch_size.height + 1),
IPL_DEPTH_32F, 1 );
}
}
cvTsCalcHist( images, hist[0], 0, channels );
cvNormalizeHist( hist[0], factor );
// now modify the images a bit
n = cvTsRandInt(rng) % (img_len/10+1);
for( i = 0; i < cdims; i++ )
{
char* data = images[i]->imageData;
for( j = 0; j < n; j++ )
{
int idx = cvTsRandInt(rng) % img_len;
double val = cvTsRandReal(rng)*(high - low) + low;
if( img_type == CV_8U )
((uchar*)data)[idx] = (uchar)cvRound(val);
else
((float*)data)[idx] = (float)val;
}
}
}
return code;
}
void CV_CalcBackProjectPatchTest::run_func(void)
{
cvCalcBackProjectPatch( images, images[CV_MAX_DIM], patch_size, hist[0], method, factor );
}
static void
cvTsCalcBackProjectPatch( IplImage** images, IplImage* dst, CvSize patch_size,
CvHistogram* hist, int method,
double factor, int* channels )
{
CvHistogram* model = 0;
IplImage imgstub[CV_MAX_DIM], *img[CV_MAX_DIM];
IplROI roi;
int i, dims;
int x, y;
CvSize size = cvGetSize(dst);
dims = cvGetDims( hist->bins );
cvCopyHist( hist, &model );
cvNormalizeHist( hist, factor );
cvZero( dst );
for( i = 0; i < dims; i++ )
{
CvMat stub, *mat;
mat = cvGetMat( images[i], &stub, 0, 0 );
img[i] = cvGetImage( mat, &imgstub[i] );
img[i]->roi = &roi;
}
roi.coi = 0;
for( y = 0; y < size.height; y++ )
{
for( x = 0; x < size.width; x++ )
{
double result;
roi.xOffset = x;
roi.yOffset = y;
roi.width = patch_size.width;
roi.height = patch_size.height;
cvTsCalcHist( img, model, 0, channels );
cvNormalizeHist( model, factor );
result = cvCompareHist( model, hist, method );
CV_IMAGE_ELEM( dst, float, y, x ) = (float)result;
}
}
cvReleaseHist( &model );
}
int CV_CalcBackProjectPatchTest::validate_test_results( int /*test_case_idx*/ )
{
int code = CvTS::OK;
double err_level = 5e-3;
cvTsCalcBackProjectPatch( images, images[CV_MAX_DIM+1],
patch_size, hist[0], method, factor, channels );
code = cvTsCmpEps2( ts, images[CV_MAX_DIM], images[CV_MAX_DIM+1], err_level, true,
"BackProjectPatch result" );
if( code < 0 )
ts->set_failed_test_info( code );
return code;
}
CV_CalcBackProjectPatchTest hist_backprojpatch_test;
////////////// cvCalcBayesianProb //////////////
class CV_BayesianProbTest : public CV_BaseHistTest
{
public:
enum { MAX_METHOD = 4 };
CV_BayesianProbTest();
protected:
int prepare_test_case( int test_case_idx );
void run_func(void);
int validate_test_results( int test_case_idx );
void init_hist( int test_case_idx, int i );
void get_hist_params( int test_case_idx );
};
CV_BayesianProbTest::CV_BayesianProbTest() :
CV_BaseHistTest( "hist-bayesianprob", "cvBayesianProb" )
{
hist_count = CV_MAX_DIM;
gen_random_hist = 1;
}
void CV_BayesianProbTest::get_hist_params( int test_case_idx )
{
CV_BaseHistTest::get_hist_params( test_case_idx );
hist_type = CV_HIST_ARRAY;
}
void CV_BayesianProbTest::init_hist( int test_case_idx, int hist_i )
{
if( hist_i < hist_count/2 )
CV_BaseHistTest::init_hist( test_case_idx, hist_i );
}
int CV_BayesianProbTest::prepare_test_case( int test_case_idx )
{
CvRNG* rng = ts->get_rng();
hist_count = (cvTsRandInt(rng) % (MAX_HIST/2-1) + 2)*2;
hist_count = MIN( hist_count, MAX_HIST );
int code = CV_BaseHistTest::prepare_test_case( test_case_idx );
return code;
}
void CV_BayesianProbTest::run_func(void)
{
cvCalcBayesianProb( hist, hist_count/2, hist + hist_count/2 );
}
int CV_BayesianProbTest::validate_test_results( int /*test_case_idx*/ )
{
int code = CvTS::OK;
int i, j, n = hist_count/2;
double s[CV_MAX_DIM];
const double err_level = 1e-5;
for( i = 0; i < total_size; i++ )
{
double sum = 0;
for( j = 0; j < n; j++ )
{
double v = hist[j]->mat.data.fl[i];
sum += v;
s[j] = v;
}
sum = sum > DBL_EPSILON ? 1./sum : 0;
for( j = 0; j < n; j++ )
{
double v0 = s[j]*sum;
double v = hist[j+n]->mat.data.fl[i];
if( cvIsNaN(v) || cvIsInf(v) )
{
ts->printf( CvTS::LOG,
"The element #%d in the destination histogram #%d is invalid (=%g)\n",
i, j, v );
code = CvTS::FAIL_INVALID_OUTPUT;
break;
}
else if( fabs(v0 - v) > err_level*fabs(v0) )
{
ts->printf( CvTS::LOG,
"The element #%d in the destination histogram #%d is inaccurate (=%g, should be =%g)\n",
i, j, v, v0 );
code = CvTS::FAIL_BAD_ACCURACY;
break;
}
}
if( j < n )
break;
}
if( code < 0 )
ts->set_failed_test_info( code );
return code;
}
CV_BayesianProbTest hist_bayesianprob_test;
/* End Of File */
| [
"garrett.marcotte@45935db4-cf16-11dd-8ca8-e3ff79f713b6"
]
| [
[
[
1,
1855
]
]
]
|
6a2eea16ddb4adc6e4ff1ced28fffca656051bae | 709cd826da3ae55945fd7036ecf872ee7cdbd82a | /Term/WildMagic2/Source/Geometry/WmlCircle2.cpp | cb89f93d2d5a2d80a079e1213ea01fdf7989aa7b | []
| no_license | argapratama/kucgbowling | 20dbaefe1596358156691e81ccceb9151b15efb0 | 65e40b6f33c5511bddf0fa350c1eefc647ace48a | refs/heads/master | 2018-01-08T15:27:44.784437 | 2011-06-19T15:23:39 | 2011-06-19T15:23:39 | 36,738,655 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,799 | cpp | // Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2003. All Rights Reserved
//
// The Wild Magic Library (WML) source code is supplied under the terms of
// the license agreement http://www.magic-software.com/License/WildMagic.pdf
// and may not be copied or disclosed except in accordance with the terms of
// that agreement.
#include "WmlCircle2.h"
using namespace Wml;
//----------------------------------------------------------------------------
template <class Real>
Circle2<Real>::Circle2 ()
:
m_kCenter(Vector2<Real>::ZERO)
{
m_fRadius = (Real)0.0;
}
//----------------------------------------------------------------------------
template <class Real>
Vector2<Real>& Circle2<Real>::Center ()
{
return m_kCenter;
}
//----------------------------------------------------------------------------
template <class Real>
const Vector2<Real>& Circle2<Real>::Center () const
{
return m_kCenter;
}
//----------------------------------------------------------------------------
template <class Real>
Real& Circle2<Real>::Radius ()
{
return m_fRadius;
}
//----------------------------------------------------------------------------
template <class Real>
const Real& Circle2<Real>::Radius () const
{
return m_fRadius;
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// explicit instantiation
//----------------------------------------------------------------------------
namespace Wml
{
template class WML_ITEM Circle2<float>;
template class WML_ITEM Circle2<double>;
}
//----------------------------------------------------------------------------
| [
"[email protected]"
]
| [
[
[
1,
56
]
]
]
|
d5779b6f80f8c303c74656af5d7da731f3954852 | 51e1cf5dc3b99e8eecffcf5790ada07b2f03f39c | /SMC/src/levelexit.cpp | 4eedb532fa8429215506a7b052b5800d8f4da41d | []
| no_license | jdek/jim-pspware | c3e043b59a69cf5c28daf62dc9d8dca5daf87589 | fd779e1148caac2da4c590844db7235357b47f7e | refs/heads/master | 2021-05-31T06:45:03.953631 | 2007-06-25T22:45:26 | 2007-06-25T22:45:26 | 56,973,047 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,316 | cpp | /***************************************************************************
levelexit.cpp - class for a little door to enter the next level
-------------------
copyright : (C) 2003-2004 by Artur Hallmann
(C) 2003-2005 by FluXy
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#include "include/globals.h"
/* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
cLevelExit :: cLevelExit( double x, double y, Levelchange_type ntype /* = LVLCHANGE_EXIT */, string nlevelname /* = "" */ ) : cActiveSprite( x, y )
{
type = TYPE_LEVELEXIT;
levelchange = ntype;
levelname = nlevelname;
visible = 1;
massive = 0;
rect.w = 20;
rect.h = 20;
SetPos( x, y );
}
cLevelExit :: ~cLevelExit( void )
{
}
void cLevelExit :: Update( void )
{
if( ( levelchange == LVLCHANGE_BEAM && ( keys[pPreferences->Key_up] || pJoystick->Button( pPreferences->Joy_jump ) ) && CollideBoundingBox( &pPlayer->rect, &rect ) && pPlayer->onGround ) ||
( levelchange == LVLCHANGE_WARP && ( keys[pPreferences->Key_down] || pJoystick->down ) && ( (int)pPlayer->posy + pPlayer->rect.h == (int)posy && pPlayer->posx >= posx - pPlayer->rect.w && (int)pPlayer->posx <= (int)posx + rect.w ) ) )
{
pAudio->FadeOutMusic( 500 );
pAudio->PlaySound( MUSIC_DIR "/game/victory_3.ogg" );
if( levelchange == LVLCHANGE_WARP )
{
if( pPlayer->ducked )
{
pPlayer->Stop_ducking();
}
for( double i = 0; i < DESIRED_FPS; i += Framerate.speedfactor )
{
pPlayer->Move( 0, 2, 0, 1 );
pLevel->Draw( LVL_DRAW_BG );
pPlayer->Draw_Player( 0 + pPlayer->direction );
pLevel->Draw( LVL_DRAW_NO_BG );
SDL_Flip( screen );
Framerate.Update();
}
}
if( levelname.length() )
{
pLevel->Load( levelname );
}
else
{
pPlayer->GotoNextLevel();
}
}
else
{
Draw( screen );
}
}
void cLevelExit :: Draw( SDL_Surface *target )
{
if( !Leveleditor_Mode )
{
rect.x = (Sint16)startposx;
rect.y = (Sint16)startposy;
return;
}
rect.x = (Sint16)startposx;
rect.y = (Sint16)startposy;
if( !Visible_onScreen() )
{
return;
}
SDL_Rect r = rect;
r.x -= (Sint16)cameraposx;
r.y -= (Sint16)cameraposy;
r.w = rect.w;
r.h = rect.h;
if( levelname.empty() ) // red for levelexit
{
boxRGBA( target, r.x, r.y, r.x + r.w, r.y + r.h, 255, 0, 0, 126 );
}
else // lila for levelchange
{
boxRGBA( target, r.x, r.y, r.x + r.w, r.y + r.h, 200, 0, 255, 126 );
}
}
/* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
| [
"rinco@ff2c0c17-07fa-0310-a4bd-d48831021cb5"
]
| [
[
[
1,
117
]
]
]
|
3f861f37e11133b45b2597b9a844cf6fb3da9a6c | b505ef7eb1a6c58ebcb73267eaa1bad60efb1cb2 | /source/framework/gui/iguicontextmenu.cpp | e7ebb33c4982c1ac5fd3cbed685a3a4c8af9df61 | []
| no_license | roxygen/maid2 | 230319e05d6d6e2f345eda4c4d9d430fae574422 | 455b6b57c4e08f3678948827d074385dbc6c3f58 | refs/heads/master | 2021-01-23T17:19:44.876818 | 2010-07-02T02:43:45 | 2010-07-02T02:43:45 | 38,671,921 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,760 | cpp | #include"iguicontextmenu.h"
#include"../../auxiliary/collision.h"
#include"../../auxiliary/debug/warning.h"
namespace Maid
{
/*!
@class IGUIContextMenu iguicontextmenu.h
@brief コンテキストメニュー(windowsで言う、右クリックで出てくるアレ)
IElement は1要素をあらわします
縦並びです
*/
IGUIContextMenu::IElement::IElement()
:m_IsSelect(false)
,m_pParent(NULL)
,m_Offset(0,0)
{
}
//! 要素を子として追加する
/*!
@param id [i ] idの順に並びます。クリックされたときに GUIMESSAGE_CONTEXTMENU_CLICK.SelectID が飛んでくる
@param parts [i ] 追加するパーツ
*/
void IGUIContextMenu::IElement::Insert( int id, IElement& parts )
{
parts.m_pParent = this;
m_Child.insert( INFO( id, &parts ) );
UpdateChildPosition();
}
//! すでに追加してある子を消す
/*!
@param id [i ] 消すid
*/
void IGUIContextMenu::IElement::Delete( int id )
{
for( CHILDLIST::iterator ite = m_Child.begin(); ite!=m_Child.end(); ++ite )
{
const INFO& info = *ite;
if( info.ID==id )
{
m_Child.erase( ite );
break;
}
}
UpdateChildPosition();
}
//! すべての子要素を消す
/*!
*/
void IGUIContextMenu::IElement::DeleteAll()
{
m_Child.clear();
}
//! 子要素の横幅と縦幅を求める
/*!
*/
SIZE2DI IGUIContextMenu::IElement::CalcChildSize() const
{
int w = 0;
int h = 0;
for( CHILDLIST::const_iterator ite = m_Child.begin(); ite!=m_Child.end(); ++ite )
{
const INFO& info = *ite;
const SIZE2DI size = info.pChild->GetSize();
w = std::max( w, size.w );
h += size.h;
}
return SIZE2DI(w,h);
}
//! 子要素の表示範囲を求める
/*!
*/
RECT2DI IGUIContextMenu::IElement::CalcChildRect() const
{
const SIZE2DI size( CalcChildSize() );
POINT2DI pos(GetOffset().x,GetOffset().y);
if( m_pParent!=NULL )
{
const SIZE2DI s = m_pParent->CalcChildSize();
pos.x += s.w;
//pos.y += s.h; // 右にずれるだけなので + s.h はいらない
}
return RECT2DI( pos, size );
}
//! この要素を管理している親の取得
/*!
@return 親
*/
const IGUIContextMenu::IElement* IGUIContextMenu::IElement::GetParent() const
{
return m_pParent;
}
//! 指定した座標にある子要素を探す
/*!
@param pos [i ] 探す座標(ルート(m_pParent==NULL)のとこからの相対座標です)
@return 範囲内にあった要素
見つからなかったら NULL
*/
IGUIContextMenu::IElement* IGUIContextMenu::IElement::FindChild( const POINT2DI& pos )
{
for( CHILDLIST::iterator ite = m_Child.begin(); ite!=m_Child.end(); ++ite )
{
const INFO& info = *ite;
if( info.pChild->IsCollision(pos) )
{
return info.pChild;
}
}
return NULL;
}
//! 指定した座標にある子要素を探す
/*!
@param pos [i ] 探す座標(ルート(m_pParent==NULL)のとこからの相対座標です)
@return 範囲内にあった要素
見つからなかったら NULL
*/
const IGUIContextMenu::IElement::INFO* IGUIContextMenu::IElement::FindChildInfo( const POINT2DI& pos ) const
{
for( CHILDLIST::const_iterator ite = m_Child.begin(); ite!=m_Child.end(); ++ite )
{
const INFO& info = *ite;
if( info.pChild->IsCollision(pos) )
{
return &info;
}
}
return NULL;
}
//! この要素が範囲内にあるか?
/*!
@param pos [i ] 探す座標(ルート(m_pParent==NULL)のとこからの相対座標です)
@return 範囲内にあるなら true
ないなら false
*/
bool IGUIContextMenu::IElement::IsCollision( const POINT2DI& pos ) const
{
const SIZE2DI size = GetSize();
const POINT2DI off(m_Offset.x,m_Offset.y);
return Collision<int>::IsPointToRect( pos, RECT2DI(off,size) );
}
//! 1フレーム進める
/*!
*/
void IGUIContextMenu::IElement::UpdateFrame()
{
if( IsSelect() )
{
for( CHILDLIST::iterator ite = m_Child.begin(); ite!=m_Child.end(); ++ite )
{
const INFO& info = *ite;
info.pChild->UpdateFrame();
}
}
LocalUpdateFrame();
}
//! 描画する
/*!
*/
void IGUIContextMenu::IElement::UpdateDraw( const RenderTargetBase& Target, const IDepthStencil& Depth, const POINT2DI& pos )
{
if( IsSelect() )
{
for( CHILDLIST::iterator ite = m_Child.begin(); ite!=m_Child.end(); ++ite )
{
const INFO& info = *ite;
info.pChild->UpdateDraw( Target, Depth, pos );
}
}
LocalUpdateDraw( Target, Depth, pos + m_Offset );
}
//! 現在この要素が選択されているか?
/*!
@param 選択されているなら true
*/
bool IGUIContextMenu::IElement::IsSelect() const
{
return m_IsSelect;
}
//! 選択状態を変更する
/*!
@param on [i ] 選択するなら true
*/
void IGUIContextMenu::IElement::SetSelectState( bool on )
{
m_IsSelect = on;
}
//! 座標の設定
/*!
@param off [i ] 設定する座標(ルート(m_pParent==NULL)のとこからの相対座標です)
*/
void IGUIContextMenu::IElement::SetOffset( const VECTOR2DI& off )
{
m_Offset = off;
UpdateChildPosition();
}
//! 座標の取得
/*!
@return off [i ] 座標(ルート(m_pParent==NULL)のとこからの相対座標です)
*/
const VECTOR2DI& IGUIContextMenu::IElement::GetOffset() const
{
return m_Offset;
}
void IGUIContextMenu::IElement::UpdateChildPosition()
{
VECTOR2DI now = m_Offset;
if( m_pParent!=NULL )
{
const SIZE2DI s = m_pParent->CalcChildSize();
now.x += s.w;
}
for( CHILDLIST::iterator ite = m_Child.begin(); ite!=m_Child.end(); ++ite )
{
const INFO& info = *ite;
const SIZE2DI size = info.pChild->GetSize();
info.pChild->SetOffset( now );
now.y += size.h;
}
}
//! 子要素を何個もっているか?
/*!
@return 個数
*/
int IGUIContextMenu::IElement::GetChildSize() const
{
return (int)m_Child.size();
}
IGUIContextMenu::IGUIContextMenu()
{
}
//! 要素を子として追加する
/*!
@param id [i ] クリックされたときに GUIMESSAGE_CONTEXTMENU_CLICK.SelectID が飛んでくる
@param parts [i ] 追加するパーツ
*/
void IGUIContextMenu::Insert( int id, IElement& parts )
{
m_Top.Insert( id, parts );
}
//! すでに追加してある子を消す
/*!
@param id [i ] 消すid
*/
void IGUIContextMenu::Delete( int id )
{
m_Top.Delete( id );
}
//! すべての子要素を消す
/*!
*/
void IGUIContextMenu::DeleteAll()
{
m_Top.DeleteAll();
}
bool IGUIContextMenu::LocalIsCollision( const POINT2DI& pos ) const
{
for( SELECTLIST::const_iterator ite =m_SelectList.begin(); ite!=m_SelectList.end(); ++ite )
{
const IElement* p = *ite;
const RECT2DI rc = p->CalcChildRect();
if( Collision<int>::IsPointToRect( pos, rc ) )
{
return true;
}
}
return false;
}
void IGUIContextMenu::OnUpdateFrame()
{
m_Top.UpdateFrame();
}
void IGUIContextMenu::OnUpdateDraw( const RenderTargetBase& Target, const IDepthStencil& Depth, const POINT2DI& pos )
{
m_Top.UpdateDraw(Target,Depth,pos );
}
IGUIContextMenu::MESSAGERETURN IGUIContextMenu::MessageExecuting( SPGUIPARAM& pParam )
{
switch( pParam->Message )
{
case IGUIParam::MESSAGE_INITIALIZE:
{
m_Top.SetOffset( VECTOR2DI(0,0) );
m_Top.SetSelectState( true );
m_SelectList.push_back( &m_Top );
}break;
case IGUIParam::MESSAGE_FINALIZE:
{
for( SELECTLIST::reverse_iterator ite = m_SelectList.rbegin(); ite!=m_SelectList.rend(); ++ite )
{
(*ite)->SetSelectState(false);
}
m_SelectList.clear();
}break;
case IGUIParam::MESSAGE_MOUSEMOVE:
{
const GUIMESSAGE_MOUSEMOVE& p = static_cast<const GUIMESSAGE_MOUSEMOVE&>(*pParam);
const POINT2DI pos = CalcLocalPosition(p.Position);
IElement* pTop = m_SelectList.back();
IElement* pChild = pTop->FindChild(pos);
if( pChild!=NULL )
{ // カーソルが子の上に載っているならフォーカスを移す
m_SelectList.push_back(pChild);
pChild->SetSelectState(true);
}
else
{
// 乗っていない場合は、別の子の上にいることがあるので
// それを探し出して、設定する
for( SELECTLIST::reverse_iterator ite = m_SelectList.rbegin(); ite!=m_SelectList.rend(); ++ite )
{
IElement* p = *ite;
IElement* pChild = p->FindChild(pos);
if( pChild!=NULL )
{
while(true)
{
IElement* pLast = m_SelectList.back();
if( p==pLast ) { break; }
pLast->SetSelectState(false);
m_SelectList.pop_back();
}
pChild->SetSelectState(true);
m_SelectList.push_back(pChild);
break;
}
}
}
}break;
case IGUIParam::MESSAGE_MOUSEUP:
{
const GUIMESSAGE_MOUSEUP& p = static_cast<const GUIMESSAGE_MOUSEUP&>(*pParam);
const POINT2DI pos = CalcLocalPosition(p.Position);
for( SELECTLIST::reverse_iterator ite = m_SelectList.rbegin(); ite!=m_SelectList.rend(); ++ite )
{
const IElement::INFO* pInfo = (*ite)->FindChildInfo(pos);
if( pInfo==NULL ) { continue; }
// 子を持っている==選択項目ではない
if( pInfo->pChild->GetChildSize()!=0 ) { continue; }
GUIMESSAGE_CONTEXTMENU_CLICK m;
m.SelectID = pInfo->ID;
PostMessage( m );
break;
}
}break;
}
return IGUIParts::MessageExecuting( pParam );
}
} | [
"[email protected]"
]
| [
[
[
1,
427
]
]
]
|
38a936269fb48b1206fb5879ebe92fc6ca7488aa | 74e7667ad65cbdaa869c6e384fdd8dc7e94aca34 | /MicroFrameworkPK_v4_1/BuildOutput/public/debug/Client/stubs/corlib_native_System_Resources_ResourceManager.h | 4dc41d7926198c45cf3828dcb1316ed277407d45 | [
"BSD-3-Clause",
"OpenSSL",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
]
| permissive | gezidan/NETMF-LPC | 5093ab223eb9d7f42396344ea316cbe50a2f784b | db1880a03108db6c7f611e6de6dbc45ce9b9adce | refs/heads/master | 2021-01-18T10:59:42.467549 | 2011-06-28T08:11:24 | 2011-06-28T08:11:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,614 | h | //-----------------------------------------------------------------------------
//
// ** WARNING! **
// This file was generated automatically by a tool.
// Re-running the tool will overwrite this file.
// You should copy this file to a custom location
// before adding any customization in the copy to
// prevent loss of your changes when the tool is
// re-run.
//
//-----------------------------------------------------------------------------
#ifndef _CORLIB_NATIVE_SYSTEM_RESOURCES_RESOURCEMANAGER_H_
#define _CORLIB_NATIVE_SYSTEM_RESOURCES_RESOURCEMANAGER_H_
namespace System
{
namespace Resources
{
struct ResourceManager
{
// Helper Functions to access fields of managed object
static INT32& Get_m_resourceFileId( CLR_RT_HeapBlock* pMngObj ) { return Interop_Marshal_GetField_INT32( pMngObj, Library_corlib_native_System_Resources_ResourceManager::FIELD__m_resourceFileId ); }
static UNSUPPORTED_TYPE& Get_m_assembly( CLR_RT_HeapBlock* pMngObj ) { return Interop_Marshal_GetField_UNSUPPORTED_TYPE( pMngObj, Library_corlib_native_System_Resources_ResourceManager::FIELD__m_assembly ); }
static UNSUPPORTED_TYPE& Get_m_baseAssembly( CLR_RT_HeapBlock* pMngObj ) { return Interop_Marshal_GetField_UNSUPPORTED_TYPE( pMngObj, Library_corlib_native_System_Resources_ResourceManager::FIELD__m_baseAssembly ); }
static LPCSTR& Get_m_baseName( CLR_RT_HeapBlock* pMngObj ) { return Interop_Marshal_GetField_LPCSTR( pMngObj, Library_corlib_native_System_Resources_ResourceManager::FIELD__m_baseName ); }
static LPCSTR& Get_m_cultureName( CLR_RT_HeapBlock* pMngObj ) { return Interop_Marshal_GetField_LPCSTR( pMngObj, Library_corlib_native_System_Resources_ResourceManager::FIELD__m_cultureName ); }
static UNSUPPORTED_TYPE& Get_m_rmFallback( CLR_RT_HeapBlock* pMngObj ) { return Interop_Marshal_GetField_UNSUPPORTED_TYPE( pMngObj, Library_corlib_native_System_Resources_ResourceManager::FIELD__m_rmFallback ); }
// Declaration of stubs. These functions are implemented by Interop code developers
static UNSUPPORTED_TYPE GetObjectInternal( CLR_RT_HeapBlock* pMngObj, INT16 param0, HRESULT &hr );
static INT32 FindResource( LPCSTR param0, UNSUPPORTED_TYPE param1, HRESULT &hr );
static UNSUPPORTED_TYPE GetObject( UNSUPPORTED_TYPE param0, UNSUPPORTED_TYPE param1, HRESULT &hr );
};
}
}
#endif //_CORLIB_NATIVE_SYSTEM_RESOURCES_RESOURCEMANAGER_H_
| [
"[email protected]"
]
| [
[
[
1,
43
]
]
]
|
b201175c405c80fbd99954374e4573f9a25f6cdb | 4d5ee0b6f7be0c3841c050ed1dda88ec128ae7b4 | /src/nvimage/openexr/src/IlmImf/ImfMisc.cpp | 2befa93340f45acbc64ae6a82271432f94272e71 | []
| no_license | saggita/nvidia-mesh-tools | 9df27d41b65b9742a9d45dc67af5f6835709f0c2 | a9b7fdd808e6719be88520e14bc60d58ea57e0bd | refs/heads/master | 2020-12-24T21:37:11.053752 | 2010-09-03T01:39:02 | 2010-09-03T01:39:02 | 56,893,300 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 19,951 | cpp | ///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Industrial Light & Magic nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
//
// Miscellaneous helper functions for OpenEXR image file I/O
//
//-----------------------------------------------------------------------------
#include <ImfMisc.h>
#include <ImfHeader.h>
#include <ImfCompressor.h>
#include <ImfChannelList.h>
#include <ImfXdr.h>
#include <ImathFun.h>
#include <Iex.h>
#include <ImfStdIO.h>
#include <ImfConvert.h>
namespace Imf {
using Imath::Box2i;
using Imath::divp;
using Imath::modp;
using std::vector;
int
pixelTypeSize (PixelType type)
{
int size;
switch (type)
{
case UINT:
size = Xdr::size <unsigned int> ();
break;
case HALF:
size = Xdr::size <half> ();
break;
case FLOAT:
size = Xdr::size <float> ();
break;
default:
throw Iex::ArgExc ("Unknown pixel type.");
}
return size;
}
int
numSamples (int s, int a, int b)
{
int a1 = divp (a, s);
int b1 = divp (b, s);
return b1 - a1 + ((a1 * s < a)? 0: 1);
}
size_t
bytesPerLineTable (const Header &header,
vector<size_t> &bytesPerLine)
{
const Box2i &dataWindow = header.dataWindow();
const ChannelList &channels = header.channels();
bytesPerLine.resize (dataWindow.max.y - dataWindow.min.y + 1);
for (ChannelList::ConstIterator c = channels.begin();
c != channels.end();
++c)
{
int nBytes = pixelTypeSize (c.channel().type) *
(dataWindow.max.x - dataWindow.min.x + 1) /
c.channel().xSampling;
for (int y = dataWindow.min.y, i = 0; y <= dataWindow.max.y; ++y, ++i)
if (modp (y, c.channel().ySampling) == 0)
bytesPerLine[i] += nBytes;
}
size_t maxBytesPerLine = 0;
for (int y = dataWindow.min.y, i = 0; y <= dataWindow.max.y; ++y, ++i)
if (maxBytesPerLine < bytesPerLine[i])
maxBytesPerLine = bytesPerLine[i];
return maxBytesPerLine;
}
void
offsetInLineBufferTable (const vector<size_t> &bytesPerLine,
int linesInLineBuffer,
vector<size_t> &offsetInLineBuffer)
{
offsetInLineBuffer.resize (bytesPerLine.size());
size_t offset = 0;
for (size_t i = 0; i < bytesPerLine.size(); ++i)
{
if (i % linesInLineBuffer == 0)
offset = 0;
offsetInLineBuffer[i] = offset;
offset += bytesPerLine[i];
}
}
int
lineBufferMinY (int y, int minY, int linesInLineBuffer)
{
return ((y - minY) / linesInLineBuffer) * linesInLineBuffer + minY;
}
int
lineBufferMaxY (int y, int minY, int linesInLineBuffer)
{
return lineBufferMinY (y, minY, linesInLineBuffer) + linesInLineBuffer - 1;
}
Compressor::Format
defaultFormat (Compressor * compressor)
{
return compressor? compressor->format(): Compressor::XDR;
}
int
numLinesInBuffer (Compressor * compressor)
{
return compressor? compressor->numScanLines(): 1;
}
void
copyIntoFrameBuffer (const char *& readPtr,
char * writePtr,
char * endPtr,
size_t xStride,
bool fill,
double fillValue,
Compressor::Format format,
PixelType typeInFrameBuffer,
PixelType typeInFile)
{
//
// Copy a horizontal row of pixels from an input
// file's line or tile buffer to a frame buffer.
//
if (fill)
{
//
// The file contains no data for this channel.
// Store a default value in the frame buffer.
//
switch (typeInFrameBuffer)
{
case UINT:
{
unsigned int fillVal = (unsigned int) (fillValue);
while (writePtr <= endPtr)
{
*(unsigned int *) writePtr = fillVal;
writePtr += xStride;
}
}
break;
case HALF:
{
half fillVal = half (float(fillValue));
while (writePtr <= endPtr)
{
*(half *) writePtr = fillVal;
writePtr += xStride;
}
}
break;
case FLOAT:
{
float fillVal = float (fillValue);
while (writePtr <= endPtr)
{
*(float *) writePtr = fillVal;
writePtr += xStride;
}
}
break;
default:
throw Iex::ArgExc ("Unknown pixel data type.");
}
}
else if (format == Compressor::XDR)
{
//
// The the line or tile buffer is in XDR format.
//
// Convert the pixels from the file's machine-
// independent representation, and store the
// results in the frame buffer.
//
switch (typeInFrameBuffer)
{
case UINT:
switch (typeInFile)
{
case UINT:
while (writePtr <= endPtr)
{
Xdr::read <CharPtrIO> (readPtr, *(unsigned int *) writePtr);
writePtr += xStride;
}
break;
case HALF:
while (writePtr <= endPtr)
{
half h;
Xdr::read <CharPtrIO> (readPtr, h);
*(unsigned int *) writePtr = halfToUint (h);
writePtr += xStride;
}
break;
case FLOAT:
while (writePtr <= endPtr)
{
float f;
Xdr::read <CharPtrIO> (readPtr, f);
*(unsigned int *)writePtr = floatToUint (f);
writePtr += xStride;
}
break;
}
break;
case HALF:
switch (typeInFile)
{
case UINT:
while (writePtr <= endPtr)
{
unsigned int ui;
Xdr::read <CharPtrIO> (readPtr, ui);
*(half *) writePtr = uintToHalf (ui);
writePtr += xStride;
}
break;
case HALF:
while (writePtr <= endPtr)
{
Xdr::read <CharPtrIO> (readPtr, *(half *) writePtr);
writePtr += xStride;
}
break;
case FLOAT:
while (writePtr <= endPtr)
{
float f;
Xdr::read <CharPtrIO> (readPtr, f);
*(half *) writePtr = floatToHalf (f);
writePtr += xStride;
}
break;
}
break;
case FLOAT:
switch (typeInFile)
{
case UINT:
while (writePtr <= endPtr)
{
unsigned int ui;
Xdr::read <CharPtrIO> (readPtr, ui);
*(float *) writePtr = float (ui);
writePtr += xStride;
}
break;
case HALF:
while (writePtr <= endPtr)
{
half h;
Xdr::read <CharPtrIO> (readPtr, h);
*(float *) writePtr = float (h);
writePtr += xStride;
}
break;
case FLOAT:
while (writePtr <= endPtr)
{
Xdr::read <CharPtrIO> (readPtr, *(float *) writePtr);
writePtr += xStride;
}
break;
}
break;
default:
throw Iex::ArgExc ("Unknown pixel data type.");
}
}
else
{
//
// The the line or tile buffer is in NATIVE format.
// Copy the results into the frame buffer.
//
switch (typeInFrameBuffer)
{
case UINT:
switch (typeInFile)
{
case UINT:
while (writePtr <= endPtr)
{
for (size_t i = 0; i < sizeof (unsigned int); ++i)
writePtr[i] = readPtr[i];
readPtr += sizeof (unsigned int);
writePtr += xStride;
}
break;
case HALF:
while (writePtr <= endPtr)
{
half h = *(half *) readPtr;
*(unsigned int *) writePtr = halfToUint (h);
readPtr += sizeof (half);
writePtr += xStride;
}
break;
case FLOAT:
while (writePtr <= endPtr)
{
float f;
for (size_t i = 0; i < sizeof (float); ++i)
((char *)&f)[i] = readPtr[i];
*(unsigned int *)writePtr = floatToUint (f);
readPtr += sizeof (float);
writePtr += xStride;
}
break;
}
break;
case HALF:
switch (typeInFile)
{
case UINT:
while (writePtr <= endPtr)
{
unsigned int ui;
for (size_t i = 0; i < sizeof (unsigned int); ++i)
((char *)&ui)[i] = readPtr[i];
*(half *) writePtr = uintToHalf (ui);
readPtr += sizeof (unsigned int);
writePtr += xStride;
}
break;
case HALF:
while (writePtr <= endPtr)
{
*(half *) writePtr = *(half *)readPtr;
readPtr += sizeof (half);
writePtr += xStride;
}
break;
case FLOAT:
while (writePtr <= endPtr)
{
float f;
for (size_t i = 0; i < sizeof (float); ++i)
((char *)&f)[i] = readPtr[i];
*(half *) writePtr = floatToHalf (f);
readPtr += sizeof (float);
writePtr += xStride;
}
break;
}
break;
case FLOAT:
switch (typeInFile)
{
case UINT:
while (writePtr <= endPtr)
{
unsigned int ui;
for (size_t i = 0; i < sizeof (unsigned int); ++i)
((char *)&ui)[i] = readPtr[i];
*(float *) writePtr = float (ui);
readPtr += sizeof (unsigned int);
writePtr += xStride;
}
break;
case HALF:
while (writePtr <= endPtr)
{
half h = *(half *) readPtr;
*(float *) writePtr = float (h);
readPtr += sizeof (half);
writePtr += xStride;
}
break;
case FLOAT:
while (writePtr <= endPtr)
{
for (size_t i = 0; i < sizeof (float); ++i)
writePtr[i] = readPtr[i];
readPtr += sizeof (float);
writePtr += xStride;
}
break;
}
break;
default:
throw Iex::ArgExc ("Unknown pixel data type.");
}
}
}
void
skipChannel (const char *& readPtr,
PixelType typeInFile,
size_t xSize)
{
switch (typeInFile)
{
case UINT:
Xdr::skip <CharPtrIO> (readPtr, Xdr::size <unsigned int> () * xSize);
break;
case HALF:
Xdr::skip <CharPtrIO> (readPtr, Xdr::size <half> () * xSize);
break;
case FLOAT:
Xdr::skip <CharPtrIO> (readPtr, Xdr::size <float> () * xSize);
break;
default:
throw Iex::ArgExc ("Unknown pixel data type.");
}
}
void
convertInPlace (char *& writePtr,
const char *& readPtr,
PixelType type,
size_t numPixels)
{
switch (type)
{
case UINT:
for (size_t j = 0; j < numPixels; ++j)
{
Xdr::write <CharPtrIO> (writePtr, *(const unsigned int *) readPtr);
readPtr += sizeof(unsigned int);
}
break;
case HALF:
for (size_t j = 0; j < numPixels; ++j)
{
Xdr::write <CharPtrIO> (writePtr, *(const half *) readPtr);
readPtr += sizeof(half);
}
break;
case FLOAT:
for (size_t j = 0; j < numPixels; ++j)
{
Xdr::write <CharPtrIO> (writePtr, *(const float *) readPtr);
readPtr += sizeof(float);
}
break;
default:
throw Iex::ArgExc ("Unknown pixel data type.");
}
}
void
copyFromFrameBuffer (char *& writePtr,
const char *& readPtr,
const char * endPtr,
size_t xStride,
Compressor::Format format,
PixelType type)
{
//
// Copy a horizontal row of pixels from a frame
// buffer to an output file's line or tile buffer.
//
if (format == Compressor::XDR)
{
//
// The the line or tile buffer is in XDR format.
//
switch (type)
{
case UINT:
while (readPtr <= endPtr)
{
Xdr::write <CharPtrIO> (writePtr,
*(const unsigned int *) readPtr);
readPtr += xStride;
}
break;
case HALF:
while (readPtr <= endPtr)
{
Xdr::write <CharPtrIO> (writePtr, *(const half *) readPtr);
readPtr += xStride;
}
break;
case FLOAT:
while (readPtr <= endPtr)
{
Xdr::write <CharPtrIO> (writePtr, *(const float *) readPtr);
readPtr += xStride;
}
break;
default:
throw Iex::ArgExc ("Unknown pixel data type.");
}
}
else
{
//
// The the line or tile buffer is in NATIVE format.
//
switch (type)
{
case UINT:
while (readPtr <= endPtr)
{
for (size_t i = 0; i < sizeof (unsigned int); ++i)
*writePtr++ = readPtr[i];
readPtr += xStride;
}
break;
case HALF:
while (readPtr <= endPtr)
{
*(half *) writePtr = *(const half *) readPtr;
writePtr += sizeof (half);
readPtr += xStride;
}
break;
case FLOAT:
while (readPtr <= endPtr)
{
for (size_t i = 0; i < sizeof (float); ++i)
*writePtr++ = readPtr[i];
readPtr += xStride;
}
break;
default:
throw Iex::ArgExc ("Unknown pixel data type.");
}
}
}
void
fillChannelWithZeroes (char *& writePtr,
Compressor::Format format,
PixelType type,
size_t xSize)
{
if (format == Compressor::XDR)
{
//
// Fill with data in XDR format.
//
switch (type)
{
case UINT:
for (size_t j = 0; j < xSize; ++j)
Xdr::write <CharPtrIO> (writePtr, (unsigned int) 0);
break;
case HALF:
for (size_t j = 0; j < xSize; ++j)
Xdr::write <CharPtrIO> (writePtr, (half) 0);
break;
case FLOAT:
for (size_t j = 0; j < xSize; ++j)
Xdr::write <CharPtrIO> (writePtr, (float) 0);
break;
default:
throw Iex::ArgExc ("Unknown pixel data type.");
}
}
else
{
//
// Fill with data in NATIVE format.
//
switch (type)
{
case UINT:
for (size_t j = 0; j < xSize; ++j)
{
static const unsigned int ui = 0;
for (size_t i = 0; i < sizeof (ui); ++i)
*writePtr++ = ((char *) &ui)[i];
}
break;
case HALF:
for (size_t j = 0; j < xSize; ++j)
{
*(half *) writePtr = half (0);
writePtr += sizeof (half);
}
break;
case FLOAT:
for (size_t j = 0; j < xSize; ++j)
{
static const float f = 0;
for (size_t i = 0; i < sizeof (f); ++i)
*writePtr++ = ((char *) &f)[i];
}
break;
default:
throw Iex::ArgExc ("Unknown pixel data type.");
}
}
}
} // namespace Imf
| [
"castano@0f2971b0-9fc2-11dd-b4aa-53559073bf4c"
]
| [
[
[
1,
787
]
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.