blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
146
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
7
| license_type
stringclasses 2
values | repo_name
stringlengths 6
79
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 4
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.07k
426M
⌀ | star_events_count
int64 0
27
| fork_events_count
int64 0
12
| gha_license_id
stringclasses 3
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 6
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 20
6.28M
| extension
stringclasses 20
values | content
stringlengths 20
6.28M
| authors
sequencelengths 1
16
| author_lines
sequencelengths 1
16
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
913ab983ef1ff4c4254ca5eae1e95b721e268386 | 7969164c2b9f3f12f99a7df28e83551c8b6e5db8 | /sorce/fish/Ecole.h | d82da72dec051892a6bfda3cfc1a524ea9c2c5a5 | [
"MIT"
] | permissive | montoyamoraga/shbobo | 9e9ab91e0ab8b8404d63fa71b15bfb446ade11ea | 48246bbc29f2aa5b55644241b369d74e37e9f916 | refs/heads/main | 2023-07-04T19:02:16.494183 | 2008-08-14T01:42:07 | 2008-08-14T01:42:07 | 326,004,619 | 1 | 1 | MIT | 2021-04-11T23:47:58 | 2021-01-01T15:27:42 | C | UTF-8 | C++ | false | false | 1,524 | h |
#include <map>
class Ecole : public Component, public DragAndDropContainer {
// std::map<String,Skul*> mymap;
// std::map<int,Skul*> urmap;
public:
Ecole() : Component() {
setSize(100,400);
Grub * saintePierre;
#define MEXPTOKE(a,b,c,d,e) \
saintePierre = new Grub(a,b,c,d,e); \
addAndMakeVisible(saintePierre);
#define JEXPTOKE(a,b,c,d,e) \
saintePierre = new OrangeGrub(a,b,c,d,e); \
addAndMakeVisible(saintePierre);
#include "juliaTokes.txt"
}
void childrenChanged () {
int childro = getNumChildComponents ();
int wido = 0;
int hido = 0;
for (int i = 0; i < childro; i++) {
Component* c = getChildComponent (i);
if (hido > getHeight() - 20) {
wido += 100; hido = 0;
} c->setTopLeftPosition(wido,hido);
hido += c->getHeight();
}
}
void resized () { childrenChanged (); }
};
Ecole * standardo;
class GoneFishing : public ResizableWindow {
public:
GoneFishing() : ResizableWindow("Toolbar",false) {
Component::addToDesktop (getDesktopWindowStyleFlags());
setResizable(true, true);
standardo = new Ecole();
standardo->addMouseListener(this,0);
setContentNonOwned(standardo,true);
centreWithSize (100,400);
setVisible (true);
}
int getDesktopWindowStyleFlags() const {
return ComponentPeer::windowIsResizable;
}
//BorderSize<int> getContentComponentBorder () {
// return BorderSize<int>(20,20,20,20); }
// BorderSize<int> getBorderThickness () {
// return BorderSize<int>(20,20,20,20); }
};
| [
"[email protected]"
] | [
[
[
1,
60
]
]
] |
326cf5561c09ceedfba5aec78bd18a706f11062f | 44d499cacf286b033ce08eeceec1002e5ce782c9 | /hardware/at91/cortex-m3/eefc.cpp | 1656cff9d98f6664542adc08ce517040ba2e15b6 | [] | no_license | thumbos/tmos | ef134ecc57b44e029ded14f957d7a23c982a4fae | 756c2bc513288bfe1be96331a9e388ed0d744c83 | refs/heads/master | 2021-03-12T22:56:14.235818 | 2010-12-04T16:25:26 | 2010-12-04T16:25:26 | 1,137,841 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,927 | cpp | /* ----------------------------------------------------------------------------
* ATMEL Microcontroller Software Support
* ----------------------------------------------------------------------------
* Copyright (c) 2009, Atmel Corporation
*
* 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 disclaimer below.
*
* Atmel's name may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
* ----------------------------------------------------------------------------
*/
/**************************************************************************//**
* @ingroup AT91_EEFC
* @file
* @brief Implementation of Enhanced Embedded Flash Controller (EEFC).
*
*/
/*----------------------------------------------------------------------------
* Headers
*----------------------------------------------------------------------------*/
//#include "chip.h"
//#include <assert.h>
#include <tmos.h>
#include "platform_cpp.h"
/*----------------------------------------------------------------------------
* Exported functions
*----------------------------------------------------------------------------*/
/**
* \brief Enables the flash ready interrupt source on the EEFC peripheral.
*
* \param efc Pointer to a Efc instance
*/
extern void EFC_EnableFrdyIt( Efc* efc )
{
efc->EEFC_FMR |= EEFC_FMR_FRDY ;
}
/**
* \brief Disables the flash ready interrupt source on the EEFC peripheral.
*
* \param efc Pointer to a Efc instance
*/
extern void EFC_DisableFrdyIt( Efc* efc )
{
efc->EEFC_FMR &= ~((uint32_t)EEFC_FMR_FRDY) ;
}
/**
* \brief Set read/write wait state on the EEFC perpherial.
*
* \param efc Pointer to a Efc instance
* \param ucCycles the number of wait states in cycle.
*/
extern void EFC_SetWaitState( Efc* efc, uint8_t ucCycles )
{
uint32_t dwValue ;
dwValue = efc->EEFC_FMR ;
dwValue &= ~((uint32_t)EEFC_FMR_FWS_Msk) ;
dwValue |= EEFC_FMR_FWS(ucCycles);
efc->EEFC_FMR = dwValue ;
}
/**
* \brief Returns the current status of the EEFC.
*
* \note Keep in mind that this function clears the value of some status bits (LOCKE, PROGE).
*
* \param efc Pointer to a Efc instance
*/
extern uint32_t EFC_GetStatus( Efc* efc )
{
return efc->EEFC_FSR ;
}
/**
* \brief Returns the result of the last executed command.
*
* \param efc Pointer to a Efc instance
*/
extern uint32_t EFC_GetResult( Efc* efc )
{
return efc->EEFC_FRR ;
}
/**
* \brief Translates the given address page and offset values.
* \note The resulting values are stored in the provided variables if they are not null.
*
* \param ppEfc Pointer to a Efc instance
* \param dwAddress Address to translate.
* \param pwPage First page accessed.
* \param pwOffset Byte offset in first page.
*/
extern void EFC_TranslateAddress( Efc** ppEfc, uint32_t dwAddress, uint16_t* pwPage, uint16_t* pwOffset )
{
Efc *pEfc ;
uint16_t wPage ;
uint16_t wOffset ;
ASSERT( dwAddress >= IFLASH_ADDR ) ;
ASSERT( dwAddress <= (IFLASH_ADDR + IFLASH_SIZE) ) ;
pEfc = EFC ;
wPage = (dwAddress - IFLASH_ADDR) / IFLASH_PAGE_SIZE;
wOffset = (dwAddress - IFLASH_ADDR) % IFLASH_PAGE_SIZE;
TRACE_DEBUG( "Translated 0x%08X to page=%d and offset=%d\n\r", dwAddress, wPage, wOffset ) ;
/* Store values */
if ( pEfc )
{
*ppEfc = pEfc ;
}
if ( pwPage )
{
*pwPage = wPage ;
}
if ( pwOffset )
{
*pwOffset = wOffset ;
}
}
/**
* \brief Computes the address of a flash access given the page and offset.
*
* \param efc Pointer to a Efc instance
* \param wPage Page number.
* \param wOffset Byte offset inside page.
* \param pdwAddress Computed address (optional).
*/
extern void EFC_ComputeAddress( Efc *efc, uint16_t wPage, uint16_t wOffset, uint32_t *pdwAddress )
{
uint32_t dwAddress ;
ASSERT( efc ) ;
ASSERT( wPage <= IFLASH_NB_OF_PAGES ) ;
ASSERT( wOffset < IFLASH_PAGE_SIZE ) ;
/* Compute address */
dwAddress = IFLASH_ADDR + wPage * IFLASH_PAGE_SIZE + wOffset ;
/* Store result */
if ( pdwAddress != NULL )
{
*pdwAddress = dwAddress ;
}
}
/**
* \brief Starts the executing the given command on the EEFC and returns as soon as the command is started.
*
* \note It does NOT set the FMCN field automatically.
* \param efc Pointer to a Efc instance
* \param dwCommand Command to execute.
* \param dwArgument Command argument (should be 0 if not used).
*/
extern void EFC_StartCommand( Efc* efc, uint32_t dwCommand, uint32_t dwArgument )
{
/* Check command & argument */
switch ( dwCommand )
{
case EFC_FCMD_WP:
case EFC_FCMD_WPL:
case EFC_FCMD_EWP:
case EFC_FCMD_EWPL:
case EFC_FCMD_SLB:
case EFC_FCMD_CLB:
ASSERT( dwArgument < IFLASH_NB_OF_PAGES ) ;
break ;
case EFC_FCMD_SFB:
case EFC_FCMD_CFB:
ASSERT( dwArgument < 2 ) ;
break;
case EFC_FCMD_GETD:
case EFC_FCMD_EA:
case EFC_FCMD_GLB:
case EFC_FCMD_GFB:
case EFC_FCMD_STUI:
ASSERT( dwArgument == 0 ) ;
break;
default: ASSERT( 0 ) ;
}
/* Start command Embedded flash */
ASSERT( (efc->EEFC_FSR & EEFC_FMR_FRDY) == EEFC_FMR_FRDY ) ;
efc->EEFC_FCR = EEFC_FCR_FKEY(0x5A) | EEFC_FCR_FARG(dwArgument) | EEFC_FCR_FCMD(dwCommand) ;
}
/**
* \brief Performs the given command and wait until its completion (or an error).
*
* \param efc Pointer to a Efc instance
* \param dwCommand Command to perform.
* \param dwArgument Optional command argument.
* \param dwUseIAP
*
* \return 0 if successful, otherwise returns an error code.
*/
extern uint32_t EFC_PerformCommand( Efc* efc, uint32_t dwCommand, uint32_t dwArgument, uint32_t dwUseIAP )
{
if ( dwUseIAP != 0 )
{
/* Pointer on IAP function in ROM */
static uint32_t (*IAP_PerformCommand)( uint32_t, uint32_t ) ;
IAP_PerformCommand = (uint32_t (*)( uint32_t, uint32_t )) *((uint32_t*)CHIP_FLASH_IAP_ADDRESS ) ;
IAP_PerformCommand( 0, EEFC_FCR_FKEY(0x5A) | EEFC_FCR_FARG(dwArgument) | EEFC_FCR_FCMD(dwCommand) ) ;
return (efc->EEFC_FSR & (EEFC_FSR_FLOCKE | EEFC_FSR_FCMDE)) ;
}
else
{
uint32_t dwStatus ;
efc->EEFC_FCR = EEFC_FCR_FKEY(0x5A) | EEFC_FCR_FARG(dwArgument) | EEFC_FCR_FCMD(dwCommand) ;
do
{
dwStatus = efc->EEFC_FSR ;
}
while ( (dwStatus & EEFC_FSR_FRDY) != EEFC_FSR_FRDY ) ;
return ( dwStatus & (EEFC_FSR_FLOCKE | EEFC_FSR_FCMDE) ) ;
}
}
| [
"[email protected]"
] | [
[
[
1,
257
]
]
] |
d207dcb013c909c813226215214e440d8e33e0b0 | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Application/SysCAD/ScdOptions.cpp | 51316859b21ec8490165cf6c7715729ad7ca8d05 | [] | no_license | abcweizhuo/Test3 | 0f3379e528a543c0d43aad09489b2444a2e0f86d | 128a4edcf9a93d36a45e5585b70dee75e4502db4 | refs/heads/master | 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 633 | cpp | // ScdOptions.cpp : Implementation of CScdOptions
#include "stdafx.h"
#include "SysCAD_i.h"
#include "ScdOptions.h"
/////////////////////////////////////////////////////////////////////////////
// CScdOptions
STDMETHODIMP CScdOptions::InterfaceSupportsErrorInfo(REFIID riid)
{
static const IID* arr[] =
{
&IID_IScdOptions
};
for (int i=0; i < sizeof(arr) / sizeof(arr[0]); i++)
{
if (InlineIsEqualGUID(*arr[i],riid))
return S_OK;
}
return S_FALSE;
}
void CScdOptions::FireTheEvent(long Evt, long Data)
{
switch (Evt)
{
case ComCmd_NULL : /*Fire_On...*/ ; break;
};
};
| [
"[email protected]"
] | [
[
[
1,
29
]
]
] |
d46e15fc508aeb61a1ed9b8c5f0bd4e3421172ed | 3856c39683bdecc34190b30c6ad7d93f50dce728 | /LastProject/Source/Tree.cpp | fdac1612160fef8fdd5bed6f3374c1fa22e27ff1 | [] | no_license | yoonhada/nlinelast | 7ddcc28f0b60897271e4d869f92368b22a80dd48 | 5df3b6cec296ce09e35ff0ccd166a6937ddb2157 | refs/heads/master | 2021-01-20T09:07:11.577111 | 2011-12-21T22:12:36 | 2011-12-21T22:12:36 | 34,231,967 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,308 | cpp | #include "stdafx.h"
#include <assert.h>
CTree::CTree()
: m_pRoot( NULL )
, m_pCurr( NULL )
{
}
CTree::CTree( NODE* _pRoot )
: m_pRoot ( _pRoot )
, m_pCurr( NULL )
{
}
CTree::~CTree()
{
m_pCurr = m_pRoot;
Release();
}
HRESULT CTree::Create( FLOAT fRange, INT nDeep )
{
if (m_pRoot)
Release();
m_pRoot = new NODE;
CreateChild( m_pRoot, -fRange, fRange, fRange, -fRange, nDeep );
return S_OK;
}
VOID CTree::Release()
{
if( m_pCurr != NULL )
{
if ( m_pCurr->_children[NODE::LT] == NULL )
{
SAFE_DELETE(m_pCurr);
}
else
{
NODE * pParent = m_pCurr;
if ( pParent->_children[NODE::LT] != NULL )
{
m_pCurr = pParent->_children[NODE::LT];
Release();
}
if ( pParent->_children[NODE::RT] != NULL )
{
m_pCurr = pParent->_children[NODE::RT];
Release();
}
if ( pParent->_children[NODE::LB] != NULL )
{
m_pCurr = pParent->_children[NODE::LB];
Release();
}
if ( pParent->_children[NODE::RB] != NULL )
{
m_pCurr = pParent->_children[NODE::RB];
Release();
}
SAFE_DELETE(pParent);
}
}
}
VOID CTree::InsertObject( NODE * pNode, CBoundBox * pCube )
{
assert(pNode != NULL);
if ( IsRect( pNode, pCube ) )
{
if ( pNode->_children[NODE::LT] == NULL )
{
pNode->_data.push_back( pCube );
return;
}
if ( IsRect( pNode->_children[NODE::LT], pCube ) )
{
InsertObject( pNode->_children[NODE::LT], pCube );
}
if ( IsRect( pNode->_children[NODE::RT], pCube ) )
{
InsertObject( pNode->_children[NODE::RT], pCube );
}
if ( IsRect( pNode->_children[NODE::LB], pCube ) )
{
InsertObject( pNode->_children[NODE::LB], pCube );
}
if ( IsRect( pNode->_children[NODE::RB], pCube ) )
{
InsertObject( pNode->_children[NODE::RB], pCube );
}
}
}
VOID CTree::RemoveObject( NODE * pNode, CBoundBox * pCube )
{
assert(pNode != NULL);
if ( IsRect( pNode, pCube ) )
{
if ( pNode->_children[NODE::LT] == NULL )
{
std::vector <CBoundBox*>::iterator Iter = find(pNode->_data.begin(), pNode->_data.end(), pCube);
pNode->_data.erase(Iter);
return;
}
if ( IsRect( pNode->_children[NODE::LT], pCube ) )
RemoveObject( pNode->_children[NODE::LT], pCube );
if ( IsRect( pNode->_children[NODE::RT], pCube ) )
RemoveObject( pNode->_children[NODE::RT], pCube );
if ( IsRect( pNode->_children[NODE::LB], pCube ) )
RemoveObject( pNode->_children[NODE::LB], pCube );
if ( IsRect( pNode->_children[NODE::RB], pCube ) )
RemoveObject( pNode->_children[NODE::RB], pCube );
}
}
VOID CTree::RemoveAll( )
{
if ( m_pCurr->_children[NODE::LT] == NULL )
{
m_pCurr->_data.erase( m_pCurr->_data.begin(), m_pCurr->_data.end() );
}
else
{
NODE * pParent = m_pCurr;
if ( pParent->_children[NODE::LT] != NULL )
{
m_pCurr = pParent->_children[NODE::LT];
RemoveAll();
}
if ( pParent->_children[NODE::RT] != NULL )
{
m_pCurr = pParent->_children[NODE::RT];
RemoveAll();
}
if ( pParent->_children[NODE::LB] != NULL )
{
m_pCurr = pParent->_children[NODE::LB];
RemoveAll();
}
if ( pParent->_children[NODE::RB] != NULL )
{
m_pCurr = pParent->_children[NODE::RB];
RemoveAll();
}
}
}
VOID CTree::CreateChild( NODE *pNode, FLOAT fLeft, FLOAT fTop, FLOAT fRight, FLOAT fBottom, INT nDeep )
{
assert(pNode != NULL);
pNode->_pos[NODE::LT] = D3DXVECTOR3( fLeft, 0, fTop);
pNode->_pos[NODE::RT] = D3DXVECTOR3( fRight, 0, fTop);
pNode->_pos[NODE::LB] = D3DXVECTOR3( fLeft, 0, fBottom);
pNode->_pos[NODE::RB] = D3DXVECTOR3( fRight, 0, fBottom);
if ( nDeep > 0 )
{
nDeep--;
FLOAT fCen = ( fLeft + fRight ) * 0.5f;
FLOAT fMid = ( fTop + fBottom ) * 0.5f;
pNode->_children[NODE::LT] = new NODE();
CreateChild( pNode->_children[NODE::LT], fLeft, fTop, fCen, fMid, nDeep );
pNode->_children[NODE::RT] = new NODE();
CreateChild( pNode->_children[NODE::RT], fCen, fTop, fRight, fMid, nDeep );
pNode->_children[NODE::LB] = new NODE();
CreateChild( pNode->_children[NODE::LB], fLeft, fMid, fCen, fBottom, nDeep );
pNode->_children[NODE::RB] = new NODE();
CreateChild( pNode->_children[NODE::RB], fCen, fMid, fRight, fBottom, nDeep );
}
}
BOOL CTree::IsRect( NODE *pNode, CBoundBox * pBoundBox)
{
// X, Z
assert(pNode != NULL);
FRECT rect2 = pBoundBox->GetFRect();
FRECT rect1 = pNode->GetRect();
if ( rect1.left > rect2.right )
return FALSE;
if ( rect1.right < rect2.left )
return FALSE;
if ( rect1.top < rect2.bottom )
return FALSE;
if ( rect1.bottom > rect2.top )
return FALSE;
return TRUE;
}
BOOL CTree::IsRect( NODE *pNode, D3DXVECTOR3 &vPos)
{
assert(pNode != NULL);
BOOL bRet = FALSE;
FRECT rect = pNode->GetRect();
if ( rect.left <= vPos.x && vPos.x <= rect.right &&
rect.bottom <= vPos.z && vPos.z <= rect.top )
bRet = TRUE;
return bRet;
}
std::vector <CBoundBox*> * CTree::GetMapVector( NODE *pNode, D3DXVECTOR3 vPos )
{
assert(pNode != NULL);
if ( pNode->_children[NODE::LT] == NULL )
{
return &pNode->_data;
}
if ( IsRect( pNode->_children[NODE::LT], vPos ) )
return GetMapVector( pNode->_children[NODE::LT], vPos );
if ( IsRect( pNode->_children[NODE::RT], vPos ) )
return GetMapVector( pNode->_children[NODE::RT], vPos );
if ( IsRect( pNode->_children[NODE::LB], vPos ) )
return GetMapVector( pNode->_children[NODE::LB], vPos );
if ( IsRect( pNode->_children[NODE::RB], vPos ) )
return GetMapVector( pNode->_children[NODE::RB], vPos );
return NULL;
}
VOID CTree::SetMonsAtkClear()
{
std::vector<CBoundBox*>::iterator Iter;
if ( !_vecMonsAtk.empty() )
{
Iter = _vecMonsAtk.begin();
while ( Iter != _vecMonsAtk.end() )
{
delete ( *Iter );
Iter++;
}
}
_vecMonsAtk.erase( _vecMonsAtk.begin(), _vecMonsAtk.end() );
}
VOID CTree::SetCharAtkClear()
{
//std::vector<CBoundBox*>::iterator Iter;
//if ( !_vecCharAtk.empty() )
//{
// Iter = _vecCharAtk.begin();
// while ( Iter != _vecCharAtk.end() )
// {
// delete ( *Iter );
// Iter++;
// }
//}
_vecCharAtk.erase( _vecCharAtk.begin(), _vecCharAtk.end() );
}
| [
"[email protected]@d02aaf57-2019-c8cd-d06c-d029ef2af4e0",
"[email protected]@d02aaf57-2019-c8cd-d06c-d029ef2af4e0"
] | [
[
[
1,
188
],
[
190,
239
]
],
[
[
189,
189
],
[
240,
271
]
]
] |
57255c6eff11faf7b0ba2fd69fa6810247340951 | b8ac0bb1d1731d074b7a3cbebccc283529b750d4 | /Code/controllers/RecollectionBenchmark/main.cpp | 95193a8d11c6ef8c40d787c7c89ec1b702e005a3 | [] | no_license | dh-04/tpf-robotica | 5efbac38d59fda0271ac4639ea7b3b4129c28d82 | 10a7f4113d5a38dc0568996edebba91f672786e9 | refs/heads/master | 2022-12-10T18:19:22.428435 | 2010-11-05T02:42:29 | 2010-11-05T02:42:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 705 | cpp | #include <cstdlib>
#include <iostream>
#include <robotapi/real/RealRobot.h>
#include <GarbageCleaner.h>
#include <WorldInfo.h>
#include <time.h>
#include <cv.h>
#include <highgui.h>
// define this to save to disk slots visited
// SAVE_CHANGED
using namespace std;
int main(int argc, char *argv[])
{
FILE * parametersFile = fopen("realParameters.txt","r+");
behaviours::BehavioursParameters::Init(parametersFile);
WorldInfo * wi = new WorldInfo();
robotapi::real::RealRobot * robot = new robotapi::real::RealRobot(wi);
GarbageCleaner::GarbageCleaner * gc = new GarbageCleaner::GarbageCleaner(wi, *robot, GR);
gc->cleanGarbage();
return EXIT_SUCCESS;
}
| [
"nachogoni@d69ea68a-f96b-11de-8cdf-e97ad7d0f28a"
] | [
[
[
1,
31
]
]
] |
dc2615426c8c8de2529200ab356cb83f5c7cd6bf | da32684647cac4dcdbb60db49496eb8d10a8ea6d | /Deadbeef/Classes/Box2D/Dynamics/b2Body.h | 176f02dce0113dbffad66f1ee1cfde1c1607c6dd | [] | no_license | jweinberg/deadbeef | a1f10bc37de3aee5ac6b5953d740be9990083246 | 8126802454ff5815a7a55feae82e80d026a89726 | refs/heads/master | 2016-09-06T06:13:46.704284 | 2010-06-18T21:51:07 | 2010-06-18T21:51:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,184 | h | /*
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef B2_BODY_H
#define B2_BODY_H
#include "../Common/b2Math.h"
#include "../Collision/Shapes/b2Shape.h"
#include <memory>
class b2Fixture;
class b2Joint;
class b2Contact;
class b2Controller;
class b2World;
struct b2FixtureDef;
struct b2JointEdge;
struct b2ContactEdge;
/// The body type.
/// static: zero mass, zero velocity, may be manually moved
/// kinematic: zero mass, non-zero velocity set by user, moved by solver
/// dynamic: positive mass, non-zero velocity determined by forces, moved by solver
enum b2BodyType
{
b2_staticBody = 0,
b2_kinematicBody,
b2_dynamicBody,
};
/// A body definition holds all the data needed to construct a rigid body.
/// You can safely re-use body definitions. Shapes are added to a body after construction.
struct b2BodyDef
{
/// This constructor sets the body definition default values.
b2BodyDef()
{
userData = NULL;
position.Set(0.0f, 0.0f);
angle = 0.0f;
linearVelocity.Set(0.0f, 0.0f);
angularVelocity = 0.0f;
linearDamping = 0.0f;
angularDamping = 0.0f;
allowSleep = true;
awake = true;
fixedRotation = false;
bullet = false;
type = b2_staticBody;
active = true;
inertiaScale = 1.0f;
}
/// The body type: static, kinematic, or dynamic.
/// Note: if a dynamic body would have zero mass, the mass is set to one.
b2BodyType type;
/// The world position of the body. Avoid creating bodies at the origin
/// since this can lead to many overlapping shapes.
b2Vec2 position;
/// The world angle of the body in radians.
float32 angle;
/// The linear velocity of the body's origin in world co-ordinates.
b2Vec2 linearVelocity;
/// The angular velocity of the body.
float32 angularVelocity;
/// Linear damping is use to reduce the linear velocity. The damping parameter
/// can be larger than 1.0f but the damping effect becomes sensitive to the
/// time step when the damping parameter is large.
float32 linearDamping;
/// Angular damping is use to reduce the angular velocity. The damping parameter
/// can be larger than 1.0f but the damping effect becomes sensitive to the
/// time step when the damping parameter is large.
float32 angularDamping;
/// Set this flag to false if this body should never fall asleep. Note that
/// this increases CPU usage.
bool allowSleep;
/// Is this body initially awake or sleeping?
bool awake;
/// Should this body be prevented from rotating? Useful for characters.
bool fixedRotation;
/// Is this a fast moving body that should be prevented from tunneling through
/// other moving bodies? Note that all bodies are prevented from tunneling through
/// kinematic and static bodies. This setting is only considered on dynamic bodies.
/// @warning You should use this flag sparingly since it increases processing time.
bool bullet;
/// Does this body start out active?
bool active;
/// Use this to store application specific body data.
void* userData;
/// Experimental: scales the inertia tensor.
float32 inertiaScale;
};
/// A rigid body. These are created via b2World::CreateBody.
class b2Body
{
public:
void ClearForces();
/// Creates a fixture and attach it to this body. Use this function if you need
/// to set some fixture parameters, like friction. Otherwise you can create the
/// fixture directly from a shape.
/// If the density is non-zero, this function automatically updates the mass of the body.
/// Contacts are not created until the next time step.
/// @param def the fixture definition.
/// @warning This function is locked during callbacks.
b2Fixture* CreateFixture(const b2FixtureDef* def);
/// Creates a fixture from a shape and attach it to this body.
/// This is a convenience function. Use b2FixtureDef if you need to set parameters
/// like friction, restitution, user data, or filtering.
/// If the density is non-zero, this function automatically updates the mass of the body.
/// @param shape the shape to be cloned.
/// @param density the shape density (set to zero for static bodies).
/// @warning This function is locked during callbacks.
b2Fixture* CreateFixture(const b2Shape* shape, float32 density);
/// Destroy a fixture. This removes the fixture from the broad-phase and
/// destroys all contacts associated with this fixture. This will
/// automatically adjust the mass of the body if the body is dynamic and the
/// fixture has positive density.
/// All fixtures attached to a body are implicitly destroyed when the body is destroyed.
/// @param fixture the fixture to be removed.
/// @warning This function is locked during callbacks.
void DestroyFixture(b2Fixture* fixture);
/// Set the position of the body's origin and rotation.
/// This breaks any contacts and wakes the other bodies.
/// Manipulating a body's transform may cause non-physical behavior.
/// @param position the world position of the body's local origin.
/// @param angle the world rotation in radians.
void SetTransform(const b2Vec2& position, float32 angle);
/// Get the body transform for the body's origin.
/// @return the world transform of the body's origin.
const b2Transform& GetTransform() const;
/// Get the world body origin position.
/// @return the world position of the body's origin.
const b2Vec2& GetPosition() const;
/// Set the angular velocity.
/// @param theta the new angle radians.
void SetAngle(float32 theta);
/// Get the angle in radians.
/// @return the current world rotation angle in radians.
float32 GetAngle() const;
/// Get the world position of the center of mass.
const b2Vec2& GetWorldCenter() const;
/// Get the local position of the center of mass.
const b2Vec2& GetLocalCenter() const;
/// Set the linear velocity of the center of mass.
/// @param v the new linear velocity of the center of mass.
void SetLinearVelocity(const b2Vec2& v);
/// Get the linear velocity of the center of mass.
/// @return the linear velocity of the center of mass.
b2Vec2 GetLinearVelocity() const;
/// Set the angular velocity.
/// @param omega the new angular velocity in radians/second.
void SetAngularVelocity(float32 omega);
/// Get the angular velocity.
/// @return the angular velocity in radians/second.
float32 GetAngularVelocity() const;
/// Apply a force at a world point. If the force is not
/// applied at the center of mass, it will generate a torque and
/// affect the angular velocity. This wakes up the body.
/// @param force the world force vector, usually in Newtons (N).
/// @param point the world position of the point of application.
void ApplyForce(const b2Vec2& force, const b2Vec2& point);
/// Apply a torque. This affects the angular velocity
/// without affecting the linear velocity of the center of mass.
/// This wakes up the body.
/// @param torque about the z-axis (out of the screen), usually in N-m.
void ApplyTorque(float32 torque);
/// Apply an impulse at a point. This immediately modifies the velocity.
/// It also modifies the angular velocity if the point of application
/// is not at the center of mass. This wakes up the body.
/// @param impulse the world impulse vector, usually in N-seconds or kg-m/s.
/// @param point the world position of the point of application.
void ApplyLinearImpulse(const b2Vec2& impulse, const b2Vec2& point);
/// Apply an angular impulse.
/// @param impulse the angular impulse in units of kg*m*m/s
void ApplyAngularImpulse(float32 impulse);
/// Get the total mass of the body.
/// @return the mass, usually in kilograms (kg).
float32 GetMass() const;
/// Get the rotational inertia of the body about the local origin.
/// @return the rotational inertia, usually in kg-m^2.
float32 GetInertia() const;
/// Get the mass data of the body.
/// @return a struct containing the mass, inertia and center of the body.
void GetMassData(b2MassData* data) const;
/// Set the mass properties to override the mass properties of the fixtures.
/// Note that this changes the center of mass position.
/// Note that creating or destroying fixtures can also alter the mass.
/// This function has no effect if the body isn't dynamic.
/// @param massData the mass properties.
void SetMassData(const b2MassData* data);
/// This resets the mass properties to the sum of the mass properties of the fixtures.
/// This normally does not need to be called unless you called SetMassData to override
/// the mass and you later want to reset the mass.
void ResetMassData();
/// Get the world coordinates of a point given the local coordinates.
/// @param localPoint a point on the body measured relative the the body's origin.
/// @return the same point expressed in world coordinates.
b2Vec2 GetWorldPoint(const b2Vec2& localPoint) const;
/// Get the world coordinates of a vector given the local coordinates.
/// @param localVector a vector fixed in the body.
/// @return the same vector expressed in world coordinates.
b2Vec2 GetWorldVector(const b2Vec2& localVector) const;
/// Gets a local point relative to the body's origin given a world point.
/// @param a point in world coordinates.
/// @return the corresponding local point relative to the body's origin.
b2Vec2 GetLocalPoint(const b2Vec2& worldPoint) const;
/// Gets a local vector given a world vector.
/// @param a vector in world coordinates.
/// @return the corresponding local vector.
b2Vec2 GetLocalVector(const b2Vec2& worldVector) const;
/// Get the world linear velocity of a world point attached to this body.
/// @param a point in world coordinates.
/// @return the world velocity of a point.
b2Vec2 GetLinearVelocityFromWorldPoint(const b2Vec2& worldPoint) const;
/// Get the world velocity of a local point.
/// @param a point in local coordinates.
/// @return the world velocity of a point.
b2Vec2 GetLinearVelocityFromLocalPoint(const b2Vec2& localPoint) const;
/// Get the linear damping of the body.
float32 GetLinearDamping() const;
/// Set the linear damping of the body.
void SetLinearDamping(float32 linearDamping);
/// Get the angular damping of the body.
float32 GetAngularDamping() const;
/// Set the angular damping of the body.
void SetAngularDamping(float32 angularDamping);
/// Set the type of this body. This may alter the mass and velocity.
void SetType(b2BodyType type);
/// Get the type of this body.
b2BodyType GetType() const;
/// Should this body be treated like a bullet for continuous collision detection?
void SetBullet(bool flag);
/// Is this body treated like a bullet for continuous collision detection?
bool IsBullet() const;
/// You can disable sleeping on this body. If you disable sleeping, the
/// body will be woken.
void SetSleepingAllowed(bool flag);
/// Is this body allowed to sleep
bool IsSleepingAllowed() const;
/// Set the sleep state of the body. A sleeping body has very
/// low CPU cost.
/// @param flag set to true to put body to sleep, false to wake it.
void SetAwake(bool flag);
/// Get the sleeping state of this body.
/// @return true if the body is sleeping.
bool IsAwake() const;
/// Set the active state of the body. An inactive body is not
/// simulated and cannot be collided with or woken up.
/// If you pass a flag of true, all fixtures will be added to the
/// broad-phase.
/// If you pass a flag of false, all fixtures will be removed from
/// the broad-phase and all contacts will be destroyed.
/// Fixtures and joints are otherwise unaffected. You may continue
/// to create/destroy fixtures and joints on inactive bodies.
/// Fixtures on an inactive body are implicitly inactive and will
/// not participate in collisions, ray-casts, or queries.
/// Joints connected to an inactive body are implicitly inactive.
/// An inactive body is still owned by a b2World object and remains
/// in the body list.
void SetActive(bool flag);
/// Get the active state of the body.
bool IsActive() const;
/// Set this body to have fixed rotation. This causes the mass
/// to be reset.
void SetFixedRotation(bool flag);
/// Does this body have fixed rotation?
bool IsFixedRotation() const;
/// Get the list of all fixtures attached to this body.
b2Fixture* GetFixtureList();
const b2Fixture* GetFixtureList() const;
/// Get the list of all joints attached to this body.
b2JointEdge* GetJointList();
const b2JointEdge* GetJointList() const;
/// Get the list of all contacts attached to this body.
/// @warning this list changes during the time step and you may
/// miss some collisions if you don't use b2ContactListener.
b2ContactEdge* GetContactList();
const b2ContactEdge* GetContactList() const;
/// Get the next body in the world's body list.
b2Body* GetNext();
const b2Body* GetNext() const;
/// Get the user data pointer that was provided in the body definition.
void* GetUserData() const;
/// Set the user data. Use this to store your application specific data.
void SetUserData(void* data);
/// Get the parent world of this body.
b2World* GetWorld();
const b2World* GetWorld() const;
private:
friend class b2World;
friend class b2Island;
friend class b2ContactManager;
friend class b2ContactSolver;
friend class b2TOISolver;
friend class b2DistanceJoint;
friend class b2GearJoint;
friend class b2LineJoint;
friend class b2MouseJoint;
friend class b2PrismaticJoint;
friend class b2PulleyJoint;
friend class b2RevoluteJoint;
friend class b2WeldJoint;
friend class b2FrictionJoint;
// m_flags
enum
{
e_islandFlag = 0x0001,
e_awakeFlag = 0x0002,
e_autoSleepFlag = 0x0004,
e_bulletFlag = 0x0008,
e_fixedRotationFlag = 0x0010,
e_activeFlag = 0x0020,
e_toiFlag = 0x0040,
};
b2Body(const b2BodyDef* bd, b2World* world);
~b2Body();
void SynchronizeFixtures();
void SynchronizeTransform();
// This is used to prevent connected bodies from colliding.
// It may lie, depending on the collideConnected flag.
bool ShouldCollide(const b2Body* other) const;
void Advance(float32 t);
b2BodyType m_type;
uint16 m_flags;
int32 m_islandIndex;
b2Transform m_xf; // the body origin transform
b2Sweep m_sweep; // the swept motion for CCD
b2Vec2 m_linearVelocity;
float32 m_angularVelocity;
b2Vec2 m_force;
float32 m_torque;
b2World* m_world;
b2Body* m_prev;
b2Body* m_next;
b2Fixture* m_fixtureList;
int32 m_fixtureCount;
b2JointEdge* m_jointList;
b2ContactEdge* m_contactList;
float32 m_mass, m_invMass;
// Rotational inertia about the center of mass.
float32 m_I, m_invI;
float32 m_linearDamping;
float32 m_angularDamping;
float32 m_sleepTime;
void* m_userData;
};
inline b2BodyType b2Body::GetType() const
{
return m_type;
}
inline const b2Transform& b2Body::GetTransform() const
{
return m_xf;
}
inline const b2Vec2& b2Body::GetPosition() const
{
return m_xf.position;
}
inline float32 b2Body::GetAngle() const
{
return m_sweep.a;
}
inline const b2Vec2& b2Body::GetWorldCenter() const
{
return m_sweep.c;
}
inline const b2Vec2& b2Body::GetLocalCenter() const
{
return m_sweep.localCenter;
}
inline void b2Body::SetLinearVelocity(const b2Vec2& v)
{
if (m_type == b2_staticBody)
{
return;
}
if (b2Dot(v,v) > 0.0f)
{
SetAwake(true);
}
m_linearVelocity = v;
}
inline b2Vec2 b2Body::GetLinearVelocity() const
{
return m_linearVelocity;
}
inline void b2Body::SetAngle(float32 theta)
{
if (m_type == b2_staticBody)
{
return;
}
m_sweep.a = theta;
}
inline void b2Body::SetAngularVelocity(float32 w)
{
if (m_type == b2_staticBody)
{
return;
}
if (w * w > 0.0f)
{
SetAwake(true);
}
m_angularVelocity = w;
}
inline float32 b2Body::GetAngularVelocity() const
{
return m_angularVelocity;
}
inline float32 b2Body::GetMass() const
{
return m_mass;
}
inline float32 b2Body::GetInertia() const
{
return m_I + m_mass * b2Dot(m_sweep.localCenter, m_sweep.localCenter);
}
inline void b2Body::GetMassData(b2MassData* data) const
{
data->mass = m_mass;
data->I = m_I + m_mass * b2Dot(m_sweep.localCenter, m_sweep.localCenter);
data->center = m_sweep.localCenter;
}
inline b2Vec2 b2Body::GetWorldPoint(const b2Vec2& localPoint) const
{
return b2Mul(m_xf, localPoint);
}
inline b2Vec2 b2Body::GetWorldVector(const b2Vec2& localVector) const
{
return b2Mul(m_xf.R, localVector);
}
inline b2Vec2 b2Body::GetLocalPoint(const b2Vec2& worldPoint) const
{
return b2MulT(m_xf, worldPoint);
}
inline b2Vec2 b2Body::GetLocalVector(const b2Vec2& worldVector) const
{
return b2MulT(m_xf.R, worldVector);
}
inline b2Vec2 b2Body::GetLinearVelocityFromWorldPoint(const b2Vec2& worldPoint) const
{
return m_linearVelocity + b2Cross(m_angularVelocity, worldPoint - m_sweep.c);
}
inline b2Vec2 b2Body::GetLinearVelocityFromLocalPoint(const b2Vec2& localPoint) const
{
return GetLinearVelocityFromWorldPoint(GetWorldPoint(localPoint));
}
inline float32 b2Body::GetLinearDamping() const
{
return m_linearDamping;
}
inline void b2Body::SetLinearDamping(float32 linearDamping)
{
m_linearDamping = linearDamping;
}
inline float32 b2Body::GetAngularDamping() const
{
return m_angularDamping;
}
inline void b2Body::SetAngularDamping(float32 angularDamping)
{
m_angularDamping = angularDamping;
}
inline void b2Body::SetBullet(bool flag)
{
if (flag)
{
m_flags |= e_bulletFlag;
}
else
{
m_flags &= ~e_bulletFlag;
}
}
inline bool b2Body::IsBullet() const
{
return (m_flags & e_bulletFlag) == e_bulletFlag;
}
inline void b2Body::SetAwake(bool flag)
{
if (flag)
{
if ((m_flags & e_awakeFlag) == 0)
{
m_flags |= e_awakeFlag;
m_sleepTime = 0.0f;
}
}
else
{
m_flags &= ~e_awakeFlag;
m_sleepTime = 0.0f;
m_linearVelocity.SetZero();
m_angularVelocity = 0.0f;
m_force.SetZero();
m_torque = 0.0f;
}
}
inline bool b2Body::IsAwake() const
{
return (m_flags & e_awakeFlag) == e_awakeFlag;
}
inline bool b2Body::IsActive() const
{
return (m_flags & e_activeFlag) == e_activeFlag;
}
inline void b2Body::SetFixedRotation(bool flag)
{
if (flag)
{
m_flags |= e_fixedRotationFlag;
}
else
{
m_flags &= ~e_fixedRotationFlag;
}
ResetMassData();
}
inline bool b2Body::IsFixedRotation() const
{
return (m_flags & e_fixedRotationFlag) == e_fixedRotationFlag;
}
inline void b2Body::SetSleepingAllowed(bool flag)
{
if (flag)
{
m_flags |= e_autoSleepFlag;
}
else
{
m_flags &= ~e_autoSleepFlag;
SetAwake(true);
}
}
inline bool b2Body::IsSleepingAllowed() const
{
return (m_flags & e_autoSleepFlag) == e_autoSleepFlag;
}
inline b2Fixture* b2Body::GetFixtureList()
{
return m_fixtureList;
}
inline const b2Fixture* b2Body::GetFixtureList() const
{
return m_fixtureList;
}
inline b2JointEdge* b2Body::GetJointList()
{
return m_jointList;
}
inline const b2JointEdge* b2Body::GetJointList() const
{
return m_jointList;
}
inline b2ContactEdge* b2Body::GetContactList()
{
return m_contactList;
}
inline const b2ContactEdge* b2Body::GetContactList() const
{
return m_contactList;
}
inline b2Body* b2Body::GetNext()
{
return m_next;
}
inline const b2Body* b2Body::GetNext() const
{
return m_next;
}
inline void b2Body::SetUserData(void* data)
{
m_userData = data;
}
inline void* b2Body::GetUserData() const
{
return m_userData;
}
inline void b2Body::ApplyForce(const b2Vec2& force, const b2Vec2& point)
{
if (m_type != b2_dynamicBody)
{
return;
}
if (IsAwake() == false)
{
SetAwake(true);
}
m_force += force;
m_torque += b2Cross(point - m_sweep.c, force);
}
inline void b2Body::ApplyTorque(float32 torque)
{
if (m_type != b2_dynamicBody)
{
return;
}
if (IsAwake() == false)
{
SetAwake(true);
}
m_torque += torque;
}
inline void b2Body::ApplyLinearImpulse(const b2Vec2& impulse, const b2Vec2& point)
{
if (m_type != b2_dynamicBody)
{
return;
}
if (IsAwake() == false)
{
SetAwake(true);
}
m_linearVelocity += m_invMass * impulse;
m_angularVelocity += m_invI * b2Cross(point - m_sweep.c, impulse);
}
inline void b2Body::ApplyAngularImpulse(float32 impulse)
{
if (m_type != b2_dynamicBody)
{
return;
}
if (IsAwake() == false)
{
SetAwake(true);
}
m_angularVelocity += m_invI * impulse;
}
inline void b2Body::SynchronizeTransform()
{
m_xf.R.Set(m_sweep.a);
m_xf.position = m_sweep.c - b2Mul(m_xf.R, m_sweep.localCenter);
}
inline void b2Body::Advance(float32 t)
{
// Advance to the new safe time.
m_sweep.Advance(t);
m_sweep.c = m_sweep.c0;
m_sweep.a = m_sweep.a0;
SynchronizeTransform();
}
inline b2World* b2Body::GetWorld()
{
return m_world;
}
inline const b2World* b2Body::GetWorld() const
{
return m_world;
}
#endif
| [
"bhelgeland@9c1d8119-421d-44e4-8328-69b580a11e1d"
] | [
[
[
1,
819
]
]
] |
324fe172a16ae1f487414738dde34be21bd66920 | fd792229322e4042f6e88a01144665cebdb1c339 | /src/hermite.cpp | d2e7115f930c3b3ff6f21d7d8729f0c3cd90dd79 | [] | no_license | weimingtom/mmomm | 228d70d9d68834fa2470d2cd0719b9cd60f8dbcd | cab04fcad551f7f68f99fa0b6bb14cec3b962023 | refs/heads/master | 2021-01-10T02:14:31.896834 | 2010-03-15T16:15:43 | 2010-03-15T16:15:43 | 44,764,408 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,970 | cpp | #include "hermite.h"
#include <cassert>
HermiteInterpolation::HermiteInterpolation()
: _initialTime()
, _finalTime()
, _initialPosition()
, _finalPosition()
, _initialVelocity()
, _finalVelocity()
{
}
HermiteInterpolation::HermiteInterpolation(double initialTime, double finalTime,
const Vector2D& initialPosition, const Vector2D& finalPosition,
const Vector2D& initialVelocity, const Vector2D& finalVelocity)
: _initialTime(initialTime)
, _finalTime(finalTime)
, _initialPosition(initialPosition)
, _finalPosition(finalPosition)
, _initialVelocity(initialVelocity)
, _finalVelocity(finalVelocity)
{
}
Vector2D HermiteInterpolation::interpolatePosition(double t) const
{
assert(t >= _initialTime);
if (t >= _finalTime) {
return _finalPosition + _finalVelocity * (t - _finalTime);
}
t = (t - _initialTime) / (_finalTime - _initialTime);
assert(t >= 0 && t < 1);
//return (1 - t) * _initialPosition + t * _finalPosition;
double t_2 = t * t;
double t_3 = t * t_2;
//double h00 = 2 * t_3 - 3 * t_2 + 1;
double h10 = t_3 - 2 * t_2 + t;
//double h01 = -2 * t_3 - 3 * t_2;
double h11 = t_3 - t_2;
double time = _finalTime - _initialTime;
return (1 - t) * _initialPosition +
h10 * time * _initialVelocity +
t * _finalPosition +
h11 * time * _finalVelocity;
}
Vector2D HermiteInterpolation::interpolateVelocity(double t) const
{
assert(t >= _initialTime);
if (t >= _finalTime) {
return _finalVelocity;
}
//return _finalVelocity;
t = (t - _initialTime) / (_finalTime - _initialTime);
assert(t >= 0 && t < 1);
double t_2 = t * t;
//double h00 = 6 * t_2 - 6 * t;
double h10 = 3 * t_2 - 4 * t + 1;
//double h01 = -6 * t_2 - 6 * t;
double h11 = 3 * t_2 - 2 * t;
double time = _finalTime - _initialTime;
return -_initialPosition +
h10 * time * _initialVelocity +
_finalPosition +
h11 * time * _finalVelocity;
}
| [
"[email protected]"
] | [
[
[
1,
77
]
]
] |
8910528dc03b895e3d82890f0af63113b2e2d505 | f4e20d6ad5d3a6ef3406d66d3eb4bb1fdc6c1088 | /CarMP_OpenGL/Utils.cpp | ca7bcef12e3f19c520d9c91a1cf2164844d0fa2c | [] | no_license | WildGenie/carmp | c19cfbac3dda7dfcdc6ca7de8c0fb274e07efe5b | 7d1e41acabbafa87298de745563a16b9ce7cd9b0 | refs/heads/master | 2021-01-12T07:31:33.858240 | 2011-10-05T23:31:31 | 2011-10-05T23:31:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,052 | cpp | #include "Utils.h"
using namespace std;
Utils::Utils(void)
{
}
Utils::~Utils(void)
{
}
/* Doesn't work lol */
void *Utils::file_contents(const char *filename, GLint *length)
{
FILE *f = fopen(filename, "r");
void *buffer;
if (!f) {
fprintf(stderr, "Unable to open %s for reading\n", filename);
return NULL;
}
fseek(f, 0, SEEK_END);
*length = ftell(f);
fseek(f, 0, SEEK_SET);
buffer = malloc(*length+1);
*length = fread(buffer, 1, *length, f);
fclose(f);
((char*)buffer)[*length] = '\0';
return buffer;
}
//void Utils::ShowInfoLog(
// GLuint object,
// PFNGLGETSHADERIVPROC glGet__iv,
// PFNGLGETSHADERINFOLOGPROC glGet__InfoLog
//)
//{
// GLint log_length;
// char *log;
//
// glGet__iv(object, GL_INFO_LOG_LENGTH, &log_length);
// log = (char*)malloc(log_length);
// glGet__InfoLog(object, log_length, NULL, log);
// fprintf(stderr, "%s", log);
//
// fflush(stderr);
//
// free(log);
//}
| [
"efess@d4bd84e2-f980-fb58-ec8a-1c4e3f86fd2c",
"[email protected]@d4bd84e2-f980-fb58-ec8a-1c4e3f86fd2c"
] | [
[
[
1,
38
]
],
[
[
39,
56
]
]
] |
e5c31fdabd3b919969a911cef6b41f63ec4964f2 | 814b49df11675ac3664ac0198048961b5306e1c5 | /Code/Engine/PhysX/PhysicFixedJoint.cpp | 718738d72bce223edce2b93cb9ab299e01b1f21f | [] | no_license | Atridas/biogame | f6cb24d0c0b208316990e5bb0b52ef3fb8e83042 | 3b8e95b215da4d51ab856b4701c12e077cbd2587 | refs/heads/master | 2021-01-13T00:55:50.502395 | 2011-10-31T12:58:53 | 2011-10-31T12:58:53 | 43,897,729 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 936 | cpp | #define __DONT_INCLUDE_MEM_LEAKS__
#include "PhysicFixedJoint.h"
#include "NxFixedJointDesc.h"
#include "PhysicActor.h"
#include "base.h"
#include "Utils/MemLeaks.h"
CPhysicFixedJoint::CPhysicFixedJoint()
: m_pJoint(NULL)
, m_pFixedDesc(NULL)
{
m_pFixedDesc = new NxFixedJointDesc;
}
CPhysicFixedJoint::~CPhysicFixedJoint()
{
CHECKED_DELETE(m_pFixedDesc);
}
void CPhysicFixedJoint::CreateJoint(NxJoint* joint)
{
assert(joint);
m_pJoint = joint;
CHECKED_DELETE(m_pFixedDesc);
}
void CPhysicFixedJoint::SetInfo (CPhysicActor* actorA, CPhysicActor* actorB)
{
if (actorA==NULL)
{
LOGGER->AddNewLog(ELL_ERROR, "CPhysicFixedJoint:: El primer actor pasado como argumento no puede ser null");
return;
}
m_pFixedDesc->actor[0] = actorA->GetPhXActor();
if (actorB!=NULL)
{
m_pFixedDesc->actor[1] = actorB->GetPhXActor();
}
else
{
m_pFixedDesc->actor[1] = NULL;
}
} | [
"galindix@576ee6d0-068d-96d9-bff2-16229cd70485",
"atridas87@576ee6d0-068d-96d9-bff2-16229cd70485"
] | [
[
[
1,
7
],
[
10,
48
]
],
[
[
8,
9
]
]
] |
dc6cbe98f722c1e6104bdcd8df50fcaa167f1c62 | 3e69b159d352a57a48bc483cb8ca802b49679d65 | /tags/release-2005-10-27/pcbnew/zones.cpp | 7955610490ba5f3667b05837d144a3b2bb2dd6c0 | [] | no_license | BackupTheBerlios/kicad-svn | 4b79bc0af39d6e5cb0f07556eb781a83e8a464b9 | 4c97bbde4b1b12ec5616a57c17298c77a9790398 | refs/heads/master | 2021-01-01T19:38:40.000652 | 2006-06-19T20:01:24 | 2006-06-19T20:01:24 | 40,799,911 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 34,763 | cpp | /******************************/
/* Routines de trace de Zones */
/******************************/
#include "fctsys.h"
#include "gr_basic.h"
#include "common.h"
#include "pcbnew.h"
#include "autorout.h"
#include "cell.h"
#include "trigo.h"
#include "protos.h"
/* Routines Locales */
static void Display_Zone_Netname(WinEDA_PcbFrame *frame);
static void Exit_Zones(WinEDA_DrawFrame * frame, wxDC *DC);
static void Show_Zone_Edge_While_MoveMouse(WinEDA_DrawPanel * panel, wxDC * DC, bool erase);
static void Genere_Segments_Zone(WinEDA_PcbFrame *frame, wxDC * DC, int net_code);
static bool Genere_Pad_Connexion(WinEDA_PcbFrame *frame, wxDC * DC, int layer);
/* Variables locales */
static bool Zone_Debug = FALSE;
static bool Zone_45_Only = FALSE;
static bool Zone_Exclude_Pads = TRUE;
static bool Zone_Genere_Freins_Thermiques = TRUE;
static int TimeStamp; /* signature temporelle pour la zone generee */
/*****************************/
/* class WinEDA_NetlistFrame */
/*****************************/
enum id_zone_functions
{
ID_CLOSE_ZONE = 1900,
ID_FILL_ZONE,
ID_SELECT_GRID,
ID_SELECT_OPT,
ID_SET_OPTIONS_ZONE
};
class WinEDA_ZoneFrame: public wxDialog
{
private:
WinEDA_PcbFrame * m_Parent;
wxRadioBox * m_Grid;
wxRadioBox * m_FillOpt;
wxRadioBox * m_OrientEdgesOpt;
WinEDA_ValueCtrl * m_ZoneIsolCtrl;
public:
// Constructor and destructor
WinEDA_ZoneFrame(WinEDA_PcbFrame *parent);
~WinEDA_ZoneFrame(void)
{
}
private:
void OnQuit( wxCommandEvent & event);
void ExecFillZone( wxCommandEvent & event);
DECLARE_EVENT_TABLE()
};
BEGIN_EVENT_TABLE(WinEDA_ZoneFrame, wxDialog)
EVT_BUTTON(ID_CLOSE_ZONE, WinEDA_ZoneFrame::OnQuit)
EVT_BUTTON(ID_FILL_ZONE, WinEDA_ZoneFrame::ExecFillZone)
EVT_BUTTON(ID_SET_OPTIONS_ZONE, WinEDA_ZoneFrame::ExecFillZone)
END_EVENT_TABLE()
WinEDA_ZoneFrame::WinEDA_ZoneFrame(WinEDA_PcbFrame *parent):
wxDialog(parent, -1, _("Fill Zones Options"), wxPoint(-1,-1), wxSize(380, 230),
DIALOG_STYLE)
{
wxPoint pos;
wxString number;
wxButton * Button;
int x, y;
m_Parent = parent;
SetFont(*g_DialogFont);
Centre();
/* Creation des boutons de commande */
pos.x = 275; pos.y = 10;
Button = new wxButton(this, ID_CLOSE_ZONE,
_("Cancel"), pos);
Button->SetForegroundColour(*wxBLUE);
pos.y += Button->GetDefaultSize().y + 3;
Button = new wxButton(this, ID_FILL_ZONE,
_("Fill"), pos);
Button->SetForegroundColour(*wxRED);
pos.y += Button->GetDefaultSize().y + 3;
Button = new wxButton(this, ID_SET_OPTIONS_ZONE,
_("Set Options"), pos);
Button->SetForegroundColour(wxColour(0,100,0));
// Grid:
pos.x = 10; pos.y = 10;
wxString grid_select_inches[4] = { "0.005", "0.010", "0.025", "0.050" };
wxString grid_select_mm[4] = { "0.156", "0.3125", "0.625", "1.27" };
m_Grid = new wxRadioBox( this, ID_SELECT_GRID,
UnitMetric ? _("Grid (mm):") : _("Grid (inches):"),
pos, wxDefaultSize, 4,
UnitMetric ? grid_select_mm :grid_select_inches, 1);
m_Grid->GetSize(&x, &y);
if ( pas_route == 100 ) m_Grid->SetSelection(1);
if ( pas_route == 250 ) m_Grid->SetSelection(2);
if ( pas_route == 500 ) m_Grid->SetSelection(3);
// Options:
wxString opt_select[3] = { _("Include Pads"), _("Thermal"), _("Exclude Pads") };
pos.x += x + 10;
m_FillOpt = new wxRadioBox( this, ID_SELECT_OPT, _("Grid:"),
pos, wxDefaultSize, 3, opt_select, 1);
if ( Zone_Exclude_Pads)
{
if ( Zone_Genere_Freins_Thermiques ) m_FillOpt->SetSelection(1);
else m_FillOpt->SetSelection(2);
}
// Isolation
if ( g_DesignSettings.m_ZoneClearence == 0 ) g_DesignSettings.m_ZoneClearence = g_DesignSettings.m_TrackClearence;
pos.x = 15; pos.y += y + 10;
m_ZoneIsolCtrl = new WinEDA_ValueCtrl(this, _("Isolation"),
g_DesignSettings.m_ZoneClearence, UnitMetric, pos, m_Parent->m_InternalUnits);
pos.x += m_ZoneIsolCtrl->GetDimension().x + 20; pos.y -= 20;
wxString orient_select[2] = { _("Any"), _("H , V and 45 deg") };
m_OrientEdgesOpt = new wxRadioBox( this, ID_SELECT_GRID,
_("Zone edges orient:"),
pos, wxDefaultSize, 2, orient_select, 1);
if ( Zone_45_Only ) m_OrientEdgesOpt->SetSelection(1);
}
/**********************************************************************/
void WinEDA_ZoneFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
/**********************************************************************/
{
Close(true); // true is to force the frame to close
}
/***********************************************************/
void WinEDA_ZoneFrame::ExecFillZone( wxCommandEvent & event)
/***********************************************************/
{
switch ( m_FillOpt->GetSelection() )
{
case 0:
Zone_Exclude_Pads = FALSE;
Zone_Genere_Freins_Thermiques = FALSE;
break;
case 1:
Zone_Exclude_Pads = TRUE;
Zone_Genere_Freins_Thermiques = TRUE;
break;
case 2:
Zone_Exclude_Pads = TRUE;
Zone_Genere_Freins_Thermiques = FALSE;
break;
}
switch ( m_Grid->GetSelection() )
{
case 0:
pas_route = 50;
break;
case 1:
pas_route = 100;
break;
case 2:
pas_route = 250;
break;
case 3:
pas_route = 500;
break;
}
g_DesignSettings.m_ZoneClearence = m_ZoneIsolCtrl->GetValue();
if ( m_OrientEdgesOpt->GetSelection() == 0) Zone_45_Only = FALSE;
else Zone_45_Only = TRUE;
if ( event.GetId() == ID_SET_OPTIONS_ZONE ) EndModal(1);
else EndModal(0);
}
/**************************************************************/
void WinEDA_PcbFrame::Edit_Zone_Width(wxDC * DC, SEGZONE * Zone)
/**************************************************************/
/* Edite (change la largeur des segments) la zone Zone.
La zone est constituee des segments zones de meme TimeStamp
*/
{
SEGZONE * pt_segm, * NextS ;
int TimeStamp;
bool modify = FALSE;
double f_new_width;
int w_tmp;
wxString Line;
wxString Msg( _("New zone segment width: ") );
if ( Zone == NULL ) return;
f_new_width = To_User_Unit(UnitMetric, Zone->m_Width, GetScreen()->GetInternalUnits());
Line.Printf("%.4f", f_new_width);
Msg += UnitMetric ? "(mm)" : "(\")";
if ( Get_Message(Msg, Line, this) != 0 ) return;
w_tmp = g_DesignSettings.m_CurrentTrackWidth;
Line.ToDouble( &f_new_width);
g_DesignSettings.m_CurrentTrackWidth = From_User_Unit(UnitMetric, f_new_width, GetScreen()->GetInternalUnits());
TimeStamp = Zone->m_TimeStamp;
for( pt_segm = (SEGZONE*)m_Pcb->m_Zone; pt_segm != NULL; pt_segm = NextS)
{
NextS = (SEGZONE*) pt_segm->Pnext;
if(pt_segm->m_TimeStamp == TimeStamp)
{
modify = TRUE;
Edit_TrackSegm_Width(DC, pt_segm);
}
}
g_DesignSettings.m_CurrentTrackWidth = w_tmp;
if ( modify )
{
GetScreen()->SetModify();
DrawPanel->Refresh();
}
}
/**********************************************************/
void WinEDA_PcbFrame::Delete_Zone(wxDC * DC, SEGZONE * Zone)
/**********************************************************/
/* Efface la zone Zone.
La zone est constituee des segments zones de meme TimeStamp
*/
{
SEGZONE * pt_segm, * NextS ;
int TimeStamp;
int nb_segm = 0;
bool modify = FALSE;
TimeStamp = Zone->m_TimeStamp;
for( pt_segm = (SEGZONE*)m_Pcb->m_Zone; pt_segm != NULL; pt_segm = NextS)
{
NextS = (SEGZONE*) pt_segm->Pnext;
if(pt_segm->m_TimeStamp == TimeStamp)
{
modify = TRUE;
/* effacement des segments a l'ecran */
Trace_Une_Piste(DrawPanel, DC, pt_segm, nb_segm, GR_XOR);
DeleteStructure(pt_segm);
}
}
if ( modify )
{
GetScreen()->SetModify();
GetScreen()->SetRefreshReq();
}
}
/*****************************************************************************/
EDGE_ZONE * WinEDA_PcbFrame::Del_SegmEdgeZone(wxDC * DC, EDGE_ZONE * edge_zone)
/*****************************************************************************/
/* Routine d'effacement du segment de limite zone en cours de trace */
{
EDGE_ZONE * Segm, * previous_segm;
if (m_Pcb->m_CurrentLimitZone) Segm = m_Pcb->m_CurrentLimitZone;
else Segm = edge_zone;
if( Segm == NULL) return NULL;
Trace_DrawSegmentPcb(DrawPanel, DC, Segm, GR_XOR);
previous_segm = (EDGE_ZONE *)Segm->Pback;
delete Segm;
Segm = previous_segm;
m_Pcb->m_CurrentLimitZone = Segm;
GetScreen()->m_CurrentItem = Segm;
if( Segm )
{
Segm->Pnext = NULL;
if( GetScreen()->ManageCurseur)
GetScreen()->ManageCurseur(DrawPanel, DC, TRUE);
}
else
{
GetScreen()->ManageCurseur = NULL;
GetScreen()->ForceCloseManageCurseur = NULL;
GetScreen()->m_CurrentItem = NULL;
}
return Segm;
}
/*********************************************/
void WinEDA_PcbFrame::CaptureNetName(wxDC * DC)
/*********************************************/
/* routine permettant de capturer le nom net net (netcode) d'un pad
ou d'une piste pour l'utiliser comme netcode de zone
*/
{
D_PAD* pt_pad = 0;
TRACK * adrpiste ;
MODULE * Module;
int masquelayer = g_TabOneLayerMask[GetScreen()->m_Active_Layer];
int netcode;
netcode = -1;
MsgPanel->EraseMsgBox();
adrpiste = Locate_Pistes(m_Pcb->m_Track, masquelayer,CURSEUR_OFF_GRILLE);
if ( adrpiste == NULL )
{
pt_pad = Locate_Any_Pad(m_Pcb, CURSEUR_OFF_GRILLE);
if(pt_pad) /* Verif qu'il est bien sur la couche active */
{
Module = (MODULE*) pt_pad->m_Parent;
pt_pad = Locate_Pads(Module,g_TabOneLayerMask[GetScreen()->m_Active_Layer],
CURSEUR_OFF_GRILLE);
}
if( pt_pad )
{
pt_pad->Display_Infos(this);
netcode = pt_pad->m_NetCode;
}
}
else
{
Affiche_Infos_Piste(this, adrpiste) ;
netcode = adrpiste->m_NetCode;
}
// Mise en surbrillance du net
if(g_HightLigt_Status) Hight_Light(DC);
g_HightLigth_NetCode = netcode;
if ( g_HightLigth_NetCode >= 0 )
{
Hight_Light(DC);
}
/* Affichage du net selectionne pour la zone a tracer */
Display_Zone_Netname(this);
}
/*******************************************************/
static void Display_Zone_Netname(WinEDA_PcbFrame *frame)
/*******************************************************/
/*
Affiche le net_code et le nom de net couramment selectionne
*/
{
EQUIPOT * pt_equipot;
char line[1024];
pt_equipot = frame->m_Pcb->m_Equipots;
if( g_HightLigth_NetCode > 0 )
{
for( ; pt_equipot != NULL; pt_equipot = (EQUIPOT*)pt_equipot->Pnext)
{
if( pt_equipot->m_NetCode == g_HightLigth_NetCode) break;
}
if( pt_equipot )
{
sprintf(line,"Zone: Net[%d] <%s>",g_HightLigth_NetCode,
pt_equipot->m_Netname.GetData());
}
else sprintf(line,"Zone: NetCode[%d], Equipot non trouvee",
g_HightLigth_NetCode);
}
else strcpy(line,"Zone: pas de net selectionne");
frame->Affiche_Message(line);
}
/********************************************************/
static void Exit_Zones(WinEDA_DrawFrame * frame, wxDC *DC)
/********************************************************/
/* routine d'annulation de la Commande Begin_Zone si une piste est en cours
de tracage, ou de sortie de l'application SEGZONES.
Appel par la touche ESC
*/
{
WinEDA_PcbFrame* pcbframe = (WinEDA_PcbFrame*)frame;
if( pcbframe->m_Pcb->m_CurrentLimitZone )
{
if( pcbframe->GetScreen()->ManageCurseur ) /* trace en cours */
{
pcbframe->GetScreen()->ManageCurseur(pcbframe->DrawPanel, DC, 0);
}
pcbframe->DelLimitesZone(DC, FALSE);
}
pcbframe->GetScreen()->ManageCurseur = NULL;
pcbframe->GetScreen()->ForceCloseManageCurseur = NULL;
pcbframe->GetScreen()->m_CurrentItem = NULL;
}
/**************************************************************/
void WinEDA_BasePcbFrame::DelLimitesZone(wxDC *DC, bool Redraw)
/**************************************************************/
/* Supprime la liste des segments constituant la frontiere courante
Libere la memoire correspondante
*/
{
EDGE_ZONE * segment, * Next;
if( m_Pcb->m_CurrentLimitZone == NULL ) return;
if ( ! IsOK(this, _("Delete Current Zone Edges")) ) return;
/* efface ancienne limite de zone */
segment = m_Pcb->m_CurrentLimitZone;
for( ; segment != NULL; segment = Next)
{
Next = (EDGE_ZONE*) segment->Pback;
if ( Redraw ) Trace_DrawSegmentPcb(DrawPanel, DC, segment,GR_XOR);
segment->Pnext = NULL; delete segment;
}
GetScreen()->m_CurrentItem = NULL;
m_Pcb->m_CurrentLimitZone = NULL;
}
/********************************************/
EDGE_ZONE * WinEDA_PcbFrame::Begin_Zone(void)
/********************************************/
/*
Routine d'initialisation d'un trace de Limite de Zone ou
de placement d'un point intermediaire
*/
{
EDGE_ZONE * oldedge, * newedge = NULL;
oldedge = m_Pcb->m_CurrentLimitZone;
if( (m_Pcb->m_CurrentLimitZone == NULL ) || /* debut reel du trace */
(GetScreen()->ManageCurseur == NULL) ) /* reprise d'un trace complementaire */
{
m_Pcb->m_CurrentLimitZone = newedge = new EDGE_ZONE( m_Pcb );
newedge->m_Flags = IS_NEW | STARTPOINT | IS_MOVED;
newedge->Pback = oldedge;
if(oldedge) oldedge->Pnext = newedge;
newedge->m_Layer = GetScreen()->m_Active_Layer;
newedge->m_Width = 2 ; /* Largeur minimum tracable */
newedge->m_Start = newedge->m_End = GetScreen()->m_Curseur;
m_Pcb->m_CurrentLimitZone = newedge;
GetScreen()->ManageCurseur = Show_Zone_Edge_While_MoveMouse;
GetScreen()->ForceCloseManageCurseur = Exit_Zones;
}
else /* piste en cours : les coord du point d'arrivee ont ete mises
a jour par la routine Show_Zone_Edge_While_MoveMouse*/
{
if( (oldedge->m_Start.x != oldedge->m_End.x) ||
(oldedge->m_Start.y != oldedge->m_End.y) )
{
newedge = new EDGE_ZONE( oldedge);
newedge->Pback = oldedge;
oldedge->Pnext = newedge;
newedge->m_Flags = IS_NEW | IS_MOVED;
newedge->m_Start = newedge->m_End = oldedge->m_End;
newedge->m_Layer = GetScreen()->m_Active_Layer;
m_Pcb->m_CurrentLimitZone = newedge;
}
}
return newedge;
}
/*********************************************/
void WinEDA_PcbFrame::End_Zone(wxDC * DC)
/*********************************************/
/*
Routine de fin de trace d'une zone (succession de segments)
*/
{
EDGE_ZONE * PtLim;
if( m_Pcb->m_CurrentLimitZone )
{
Begin_Zone();
/* le dernier point genere est de longueur tj nulle donc inutile. */
/* il sera raccorde au point de depart */
PtLim = m_Pcb->m_CurrentLimitZone;
PtLim->m_Flags &= ~(IS_NEW|IS_MOVED);
while( PtLim && PtLim->Pback)
{
PtLim = (EDGE_ZONE*) PtLim->Pback;
if ( PtLim->m_Flags & STARTPOINT) break;
PtLim->m_Flags &= ~(IS_NEW|IS_MOVED);
}
if( PtLim )
{
PtLim->m_Flags &= ~(IS_NEW|IS_MOVED);
m_Pcb->m_CurrentLimitZone->m_End = PtLim->m_Start;
}
Trace_DrawSegmentPcb(DrawPanel, DC, m_Pcb->m_CurrentLimitZone,GR_XOR);
}
GetScreen()->ManageCurseur = NULL;
GetScreen()->ForceCloseManageCurseur = NULL;
}
/******************************************************************************************/
static void Show_Zone_Edge_While_MoveMouse(WinEDA_DrawPanel * panel, wxDC * DC, bool erase)
/******************************************************************************************/
/* redessin du contour de la piste lors des deplacements de la souris
*/
{
EDGE_ZONE * PtLim, * edgezone;
WinEDA_PcbFrame * pcbframe = (WinEDA_PcbFrame *) panel->m_Parent;
if( pcbframe->m_Pcb->m_CurrentLimitZone == NULL ) return ;
/* efface ancienne position si elle a ete deja dessinee */
if( erase )
{
PtLim = pcbframe->m_Pcb->m_CurrentLimitZone;
for( ; PtLim != NULL; PtLim = (EDGE_ZONE*) PtLim->Pback)
{
Trace_DrawSegmentPcb(panel, DC, PtLim,GR_XOR);
}
}
/* mise a jour de la couche */
edgezone = PtLim = pcbframe->m_Pcb->m_CurrentLimitZone;
for( ; PtLim != NULL; PtLim = (EDGE_ZONE*) PtLim->Pback)
{
PtLim->m_Layer = pcbframe->GetScreen()->m_Active_Layer;
}
/* dessin de la nouvelle piste : mise a jour du point d'arrivee */
if (Zone_45_Only)
{/* Calcul de l'extremite de la piste pour orientations permises:
horiz,vertical ou 45 degre */
edgezone->m_End = pcbframe->GetScreen()->m_Curseur;
Calcule_Coord_Extremite_45(edgezone->m_Start.x, edgezone->m_Start.y,
&edgezone->m_End.x, &edgezone->m_End.y);
}
else /* ici l'angle d'inclinaison est quelconque */
{
edgezone->m_End = pcbframe->GetScreen()->m_Curseur;
}
PtLim = edgezone;
for( ; PtLim != NULL; PtLim = (EDGE_ZONE*) PtLim->Pback)
{
Trace_DrawSegmentPcb(panel, DC, PtLim,GR_XOR);
}
}
/**********************************************/
void WinEDA_PcbFrame::Fill_Zone(wxDC * DC)
/**********************************************/
/*
Fonction generale de creation de zone
Un contour de zone doit exister, sinon l'ensemble du PCB est utilise
Il peut y avoir plusieurs contours, toujours fermés,
ce qui permet de creer des obstacles et donc des parties non remplies.
Le remplissage s'effectue a partir du point d'ancrage, jusque ves les limites
données par les contours de zones, edges pcb, ou autres obstacles
On place la zone sur la couche (layer) active.
Si la zone est sur couche cuivre, et si un net est selectionné (mis en
"Hight Light" la zone fera partie de ce net
*/
{
int ii, jj;
EDGE_ZONE* PtLim;
int lp_tmp, lay_tmp_TOP, lay_tmp_BOTTOM;
EQUIPOT* pt_equipot;
int save_isol = g_DesignSettings.m_TrackClearence;
wxPoint ZoneStartFill;
wxString msg;
MsgPanel->EraseMsgBox();
if ( m_Pcb->ComputeBoundaryBox() == FALSE )
{
DisplayError(this, "Board is empty!", 10);
return;
}
wxPoint curs_pos = GetScreen()->m_Curseur;
WinEDA_ZoneFrame * frame = new WinEDA_ZoneFrame(this);
ii = frame->ShowModal(); frame->Destroy();
GetScreen()->m_Curseur = curs_pos;
DrawPanel->MouseToCursorSchema();
if ( ii ) return;
g_DesignSettings.m_TrackClearence = g_DesignSettings.m_ZoneClearence;
/* mise a jour de la couche */
PtLim = m_Pcb->m_CurrentLimitZone;
for( ; PtLim != NULL; PtLim = (EDGE_ZONE*) PtLim->Pback)
{
Trace_DrawSegmentPcb(DrawPanel, DC, PtLim, GR_XOR);
PtLim->m_Layer = GetScreen()->m_Active_Layer;
Trace_DrawSegmentPcb(DrawPanel, DC, PtLim, GR_XOR);
}
TimeStamp = time( NULL );
/* Calcul du pas de routage fixe a 5 mils et plus */
if (pas_route < 50 ) pas_route = 50 ;
E_scale = pas_route / 50 ; if (pas_route < 1 ) pas_route = 1 ;
/* calcule de Ncols et Nrow, taille de la matrice de routage */
ComputeMatriceSize(this, pas_route);
/* Determination de la cellule pointee par la souris */
ZoneStartFill.x = (GetScreen()->m_Curseur.x - m_Pcb->m_BoundaryBox.m_Pos.x + (pas_route/2) ) / pas_route;
ZoneStartFill.y = (GetScreen()->m_Curseur.y - m_Pcb->m_BoundaryBox.m_Pos.y + (pas_route/2) ) / pas_route;
if(ZoneStartFill.x < 0) ZoneStartFill.x = 0;
if(ZoneStartFill.x >= Ncols) ZoneStartFill.x = Ncols-1;
if(ZoneStartFill.y < 0) ZoneStartFill.y = 0;
if(ZoneStartFill.y >= Nrows) ZoneStartFill.y = Nrows-1;
/* Creation du mapping de la matrice de routage */
Nb_Sides = ONE_SIDE;
if( Board.InitBoard() < 0)
{
DisplayError(this, "Pas de memoire pour generation de zones");
return;
}
sprintf(cbuf,"%d",Ncols);
Affiche_1_Parametre(this, 1, "Cols",cbuf,GREEN);
sprintf(cbuf,"%d",Nrows);
Affiche_1_Parametre(this, 7, "Lines",cbuf,GREEN);
sprintf(cbuf,"%d", Board.m_MemSize / 1024 );
Affiche_1_Parametre(this, 14, "Mem(Ko)",cbuf,CYAN);
lay_tmp_BOTTOM = Route_Layer_BOTTOM;
lay_tmp_TOP = Route_Layer_TOP;
/* Init des Parametres utilisés dans les routines de tracé */
Route_Layer_BOTTOM = Route_Layer_TOP = GetScreen()->m_Active_Layer;
lp_tmp = g_DesignSettings.m_CurrentTrackWidth; g_DesignSettings.m_CurrentTrackWidth = pas_route;
/* Affichage du NetName */
if(g_HightLigth_NetCode > 0)
{
pt_equipot = GetEquipot(m_Pcb, g_HightLigth_NetCode);
if( pt_equipot == NULL)
{
if(g_HightLigth_NetCode > 0 ) DisplayError(this, "Equipot Erreur");
}
else msg = pt_equipot->m_Netname;
}
else msg = _("No Net");
Affiche_1_Parametre(this, 22,_("NetName"),msg,RED) ;
/* Init des points d'accrochage possibles de la zone:
les pistes du net sont des points d'accrochage convenables*/
TRACK * pt_segm = m_Pcb->m_Track;
for( ; pt_segm != NULL; pt_segm = (TRACK*) pt_segm->Pnext)
{
if(g_HightLigth_NetCode != pt_segm->m_NetCode) continue;
if ( pt_segm->m_Layer != GetScreen()->m_Active_Layer ) continue;
if (pt_segm->m_StructType != TYPETRACK ) continue;
TraceSegmentPcb(m_Pcb, pt_segm, CELL_is_FRIEND, 0, WRITE_CELL );
}
/* Trace des contours du PCB sur la matrice de routage: */
Route_Layer_BOTTOM = Route_Layer_TOP = EDGE_N;
PlaceCells(m_Pcb, -1, 0);
Route_Layer_BOTTOM = Route_Layer_TOP = GetScreen()->m_Active_Layer;
/* Trace des limites de la zone sur la matrice de routage: */
PtLim = m_Pcb->m_CurrentLimitZone;
for( ; PtLim != NULL; PtLim = (EDGE_ZONE*)PtLim->Pback)
{
int ux0, uy0, ux1, uy1;
ux0 = PtLim->m_Start.x - m_Pcb->m_BoundaryBox.m_Pos.x;
uy0 = PtLim->m_Start.y - m_Pcb->m_BoundaryBox.m_Pos.y;
ux1 = PtLim->m_End.x - m_Pcb->m_BoundaryBox.m_Pos.x;
uy1 = PtLim->m_End.y - m_Pcb->m_BoundaryBox.m_Pos.y;
TraceLignePcb(ux0,uy0,ux1,uy1,-1,HOLE|CELL_is_EDGE,WRITE_CELL);
}
/* Init du point d'accrochage de la zone donné par la position souris*/
OrCell(ZoneStartFill.y,ZoneStartFill.x, BOTTOM, CELL_is_ZONE);
/* Marquage des cellules faisant partie de la zone*/
ii = 1; jj = 1;
while( ii )
{
sprintf(cbuf,"%d", jj++ );
Affiche_1_Parametre(this, 50, "Iter.",cbuf,CYAN);
ii = Propagation(this);
}
/* Selection des cellules convenables pour les points d'ancrage de la zone */
for( ii = 0; ii < Nrows ; ii++)
{
for( jj = 0; jj < Ncols ; jj++)
{
long cell = GetCell(ii,jj,BOTTOM);
if( (cell & CELL_is_ZONE) )
{
if ( (cell & CELL_is_FRIEND) == 0)
AndCell(ii,jj,BOTTOM, ~(CELL_is_FRIEND|CELL_is_ZONE) );
}
}
}
/* Maintenant, toutes les cellules candidates sont marquees */
/* Placement des cellules (pads, tracks, vias, edges pcb ou segments)
faisant des obsctacles sur la matrice de routage */
ii = 0;
if( Zone_Exclude_Pads ) ii = FORCE_PADS;
Affiche_1_Parametre(this, 42, "GenZone","",RED);
PlaceCells(m_Pcb, g_HightLigth_NetCode, ii);
Affiche_1_Parametre(this, -1, "",_("Ok"),RED);
/* Trace des limites de la zone sur la matrice de routage
(a pu etre detruit par PlaceCells()) : */
PtLim = m_Pcb->m_CurrentLimitZone;
for( ; PtLim != NULL; PtLim = (EDGE_ZONE*)PtLim->Pback)
{
int ux0, uy0, ux1, uy1;
ux0 = PtLim->m_Start.x - m_Pcb->m_BoundaryBox.m_Pos.x;
uy0 = PtLim->m_Start.y - m_Pcb->m_BoundaryBox.m_Pos.y;
ux1 = PtLim->m_End.x - m_Pcb->m_BoundaryBox.m_Pos.x;
uy1 = PtLim->m_End.y - m_Pcb->m_BoundaryBox.m_Pos.y;
TraceLignePcb(ux0,uy0,ux1,uy1,-1,HOLE|CELL_is_EDGE,WRITE_CELL);
}
/* Init du point d'accrochage de la zone donné par la position souris
(a pu etre detruit par PlaceCells()) : */
OrCell(ZoneStartFill.y,ZoneStartFill.x, BOTTOM, CELL_is_ZONE);
if(Zone_Debug) DisplayBoard(DrawPanel, DC);
/* Remplissage des cellules (creation effective de la zone)*/
ii = 1; jj = 1;
while( ii )
{
sprintf(cbuf,"%d", jj++ );
Affiche_1_Parametre(this, 50, "Iter.",cbuf,CYAN);
ii = Propagation(this);
}
if(Zone_Debug) DisplayBoard(DrawPanel, DC);
/* Generation des segments de piste type Zone correspondants*/
if(g_HightLigth_NetCode < 0 )
Genere_Segments_Zone(this, DC, 0);
else Genere_Segments_Zone(this, DC, g_HightLigth_NetCode);
/* Trace des connexions type frein thermique */
g_DesignSettings.m_CurrentTrackWidth = lp_tmp;
if ( Zone_Exclude_Pads && Zone_Genere_Freins_Thermiques)
Genere_Pad_Connexion(this, DC, GetScreen()->m_Active_Layer);
g_DesignSettings.m_TrackClearence = save_isol;
GetScreen()->SetModify();
/* Liberation de la memoire */
Board.UnInitBoard();
/* Reprise des conditions initiales */
Route_Layer_TOP = lay_tmp_TOP;
Route_Layer_BOTTOM = lay_tmp_BOTTOM;
}
/*******************************************************************************/
static void Genere_Segments_Zone(WinEDA_PcbFrame *frame, wxDC * DC, int net_code)
/*******************************************************************************/
/* Genere les segments de piste dans les limites de la zone a remplir
Algorithme:
procede en 2 balayages
- Gauche->droite
- Haut->Bas
Parametres:
net_code = net_code a attribuer au segment de zone
TimeStamp(global): signature temporelle d'identification
(mis en .start)
*/
{
int row, col;
long current_cell, old_cell;
int ux0 = 0, uy0 = 0, ux1 = 0, uy1 = 0;
int Xmin = frame->m_Pcb->m_BoundaryBox.m_Pos.x;
int Ymin = frame->m_Pcb->m_BoundaryBox.m_Pos.y;
SEGZONE * pt_track;
int layer = frame->GetScreen()->m_Active_Layer;
int nbsegm = 0;
/* balayage Gauche-> droite */
Affiche_1_Parametre(frame, 64, "Segm H","0",BROWN);
for( row = 0; row < Nrows ; row++)
{
old_cell = 0;
uy0 = uy1 = (row * pas_route) + Ymin;
for( col = 0; col < Ncols ; col++)
{
current_cell = GetCell(row,col,BOTTOM) & CELL_is_ZONE;
if(current_cell) /* ce point doit faire partie d'un segment */
{
ux1 = (col * pas_route) + Xmin;
if( old_cell == 0 ) ux0 = ux1;
}
if( ! current_cell || (col == Ncols-1) ) /* peut etre fin d'un segment */
{
if( (old_cell) && (ux0 != ux1) )
{ /* un segment avait debute de longueur > 0 */
pt_track = new SEGZONE(frame->m_Pcb);
pt_track->m_Layer = layer;
pt_track->m_NetCode = net_code;
pt_track->m_Width = pas_route;
pt_track->m_Start.x = ux0; pt_track->m_Start.y = uy0;
pt_track->m_End.x = ux1; pt_track->m_End.y = uy1;
pt_track->m_TimeStamp = TimeStamp;
pt_track->Insert(frame->m_Pcb, NULL);
pt_track->Draw(frame->DrawPanel, DC, GR_OR);
nbsegm++;
}
}
old_cell = current_cell;
}
sprintf(cbuf,"%d",nbsegm);
Affiche_1_Parametre(frame, -1, "",cbuf,BROWN);
}
Affiche_1_Parametre(frame, 72, "Segm V", "0",BROWN);
for( col = 0; col < Ncols ; col++)
{
old_cell = 0;
ux0 = ux1 = (col * pas_route) + Xmin;
for( row = 0; row < Nrows ; row++)
{
current_cell = GetCell(row,col,BOTTOM) & CELL_is_ZONE;
if(current_cell) /* ce point doit faire partie d'un segment */
{
uy1 = (row * pas_route) + Ymin;
if( old_cell == 0 ) uy0 = uy1;
}
if( ! current_cell || (row == Nrows-1) ) /* peut etre fin d'un segment */
{
if( (old_cell) && (uy0 != uy1) )
{ /* un segment avait debute de longueur > 0 */
pt_track = new SEGZONE(frame->m_Pcb);
pt_track->m_Layer = layer;
pt_track->m_Width = pas_route;
pt_track->m_NetCode = net_code;
pt_track->m_Start.x = ux0; pt_track->m_Start.y = uy0;
pt_track->m_End.x = ux1; pt_track->m_End.y = uy1;
pt_track->m_TimeStamp = TimeStamp;
pt_track->Insert(frame->m_Pcb, NULL);
pt_track->Draw(frame->DrawPanel, DC, GR_OR);
nbsegm++;
}
}
old_cell = current_cell;
}
sprintf(cbuf,"%d",nbsegm);
Affiche_1_Parametre(frame, -1, "",cbuf,BROWN);
}
}
/********************************************/
int Propagation(WinEDA_PcbFrame * frame)
/********************************************/
/* Determine les cellules inscrites dans les limites de la zone a remplir
Algorithme:
Si une cellule disponible a un voisin faisant partie de la zone, elle
devient elle meme partie de la zone
On procede en 4 balayages de la matrice des cellules
- Gauche->droite de Haut->bas
- Droite->gauche de Haut->bas
- Bas->Haut de Droite->gauche
- Bas->Haut de Gauche->Droite
et pour chaque balayage, on considere des 2 cellules voisines de
la cellule courants: cellule precedente sur la ligne et cellule precedente
sur la colonne.
La routine peut demander plusieurs iterations
les iterations doivent continuer juqu'a ce que la routine ne trouve plus
de cellules a modifier.
Retourne:
Nombre de cellules modifiees (c.a.d mises a la valeur CELL_is_ZONE.
*/
{
int row, col, nn;
long current_cell, old_cell_H;
int long * pt_cell_V;
int nbpoints = 0;
#define NO_CELL_ZONE (HOLE | CELL_is_EDGE | CELL_is_ZONE)
Affiche_1_Parametre(frame, 57, "Passe",cbuf,CYAN);
/* balayage Gauche-> droite de Haut->bas */
Affiche_1_Parametre(frame, -1, "","1",CYAN);
// Reservation memoire pour stockahe de 1 ligne ou une colonne de cellules
nn = MAX(Nrows, Ncols) * sizeof(*pt_cell_V);
pt_cell_V = (long *) MyMalloc(nn);
memset(pt_cell_V, 0, nn);
for( row = 0; row < Nrows ; row++)
{
old_cell_H = 0;
for( col = 0; col < Ncols ; col++)
{
current_cell = GetCell(row,col,BOTTOM) & NO_CELL_ZONE;
if(current_cell == 0 ) /* une cellule libre a ete trouvee */
{
if( (old_cell_H & CELL_is_ZONE)
|| (pt_cell_V[col] & CELL_is_ZONE) )
{
OrCell(row,col,BOTTOM,CELL_is_ZONE);
current_cell = CELL_is_ZONE;
nbpoints++;
}
}
pt_cell_V[col] = old_cell_H = current_cell;
}
}
/* balayage Droite-> gauche de Haut->bas */
Affiche_1_Parametre(frame, -1, "","2",CYAN);
memset(pt_cell_V, 0, nn);
for( row = 0; row < Nrows ; row++)
{
old_cell_H = 0;
for( col = Ncols -1 ; col >= 0 ; col--)
{
current_cell = GetCell(row,col,BOTTOM) & NO_CELL_ZONE ;
if(current_cell == 0 ) /* une cellule libre a ete trouvee */
{
if( (old_cell_H & CELL_is_ZONE)
|| (pt_cell_V[col] & CELL_is_ZONE) )
{
OrCell(row,col,BOTTOM,CELL_is_ZONE);
current_cell = CELL_is_ZONE;
nbpoints++;
}
}
pt_cell_V[col] = old_cell_H = current_cell;
}
}
/* balayage Bas->Haut de Droite->gauche */
Affiche_1_Parametre(frame, -1, "","3",CYAN);
memset(pt_cell_V, 0, nn);
for( col = Ncols -1 ; col >= 0 ; col--)
{
old_cell_H = 0;
for( row = Nrows-1; row >= 0 ; row--)
{
current_cell = GetCell(row,col,BOTTOM) & NO_CELL_ZONE ;
if(current_cell == 0 ) /* une cellule libre a ete trouvee */
{
if( (old_cell_H & CELL_is_ZONE)
|| (pt_cell_V[row] & CELL_is_ZONE) )
{
OrCell(row,col,BOTTOM,CELL_is_ZONE);
current_cell = CELL_is_ZONE;
nbpoints++;
}
}
pt_cell_V[row] = old_cell_H = current_cell;
}
}
/* balayage Bas->Haut de Gauche->Droite*/
Affiche_1_Parametre(frame, -1, "","4",CYAN);
memset(pt_cell_V, 0, nn);
for( col = 0 ; col < Ncols ; col++)
{
old_cell_H = 0;
for( row = Nrows-1; row >= 0 ; row--)
{
current_cell = GetCell(row,col,BOTTOM) & NO_CELL_ZONE ;
if(current_cell == 0 ) /* une cellule libre a ete trouvee */
{
if( (old_cell_H & CELL_is_ZONE)
|| (pt_cell_V[row] & CELL_is_ZONE) )
{
OrCell(row,col,BOTTOM,CELL_is_ZONE) ;
current_cell = CELL_is_ZONE;
nbpoints++;
}
}
pt_cell_V[row] = old_cell_H = current_cell;
}
}
MyFree(pt_cell_V);
return(nbpoints);
}
/*****************************************************************************/
static bool Genere_Pad_Connexion(WinEDA_PcbFrame *frame, wxDC * DC, int layer)
/*****************************************************************************/
/* Generation des segments de zone de connexion zone / pad pour constitution
de freins thermiques
*/
{
int ii, jj, Npads;
D_PAD * pt_pad;
LISTE_PAD * pt_liste_pad;
TRACK * pt_track, * loctrack;
int angle;
int cX, cY, dx, dy;
int sommet[4][2];
if( frame->m_Pcb->m_Zone == NULL ) return FALSE; /* pas de zone */
if( frame->m_Pcb->m_Zone->m_TimeStamp != TimeStamp ) /* c'est une autre zone */
return FALSE;
/* Calcul du nombre de pads a traiter et affichage */
Affiche_1_Parametre(frame, 50, "NPads"," ",CYAN);
pt_liste_pad = (LISTE_PAD*) frame->m_Pcb->m_Pads;
for ( ii = 0, Npads = 0; ii < frame->m_Pcb->m_NbPads; ii++, pt_liste_pad++)
{
pt_pad = *pt_liste_pad;
/* la pastille doit etre du meme net */
if(pt_pad->m_NetCode != g_HightLigth_NetCode) continue;
/* la pastille doit exister sur la couche */
if( (pt_pad->m_Masque_Layer & g_TabOneLayerMask[layer]) == 0 ) continue;
Npads++;
}
sprintf(cbuf,"%d", Npads );
Affiche_1_Parametre(frame, -1, "",cbuf,CYAN);
Affiche_1_Parametre(frame, 57, "Pads"," ",CYAN);
pt_liste_pad = (LISTE_PAD*) frame->m_Pcb->m_Pads;
for ( ii = 0, Npads = 0; ii < frame->m_Pcb->m_NbPads; ii++, pt_liste_pad++)
{
pt_pad = *pt_liste_pad;
/* la pastille doit etre du meme net */
if(pt_pad->m_NetCode != g_HightLigth_NetCode) continue;
/* la pastille doit exister sur la couche */
if( (pt_pad->m_Masque_Layer & g_TabOneLayerMask[layer]) == 0 ) continue;
/* traitement du pad en cours */
Npads++; sprintf(cbuf,"%d", Npads );
Affiche_1_Parametre(frame, -1, "",cbuf,CYAN);
cX = pt_pad->m_Pos.x; cY = pt_pad->m_Pos.y;
dx = pt_pad->m_Size.x / 2;
dy = pt_pad->m_Size.y / 2;
dx += g_DesignSettings.m_TrackClearence + pas_route;
dy += g_DesignSettings.m_TrackClearence + pas_route;
if(pt_pad->m_PadShape == TRAPEZE)
{
dx += abs(pt_pad->m_DeltaSize.y) / 2;
dy += abs(pt_pad->m_DeltaSize.x) / 2;
}
/* calcul des coord des 4 segments a rajouter a partir du centre cX,cY */
sommet[0][0] = 0; sommet[0][1] = -dy;
sommet[1][0] = -dx; sommet[1][1] = 0;
sommet[2][0] = 0; sommet[2][1] = dy;
sommet[3][0] = dx; sommet[3][1] = 0;
angle = pt_pad->m_Orient;
for(jj = 0; jj < 4; jj++)
{
RotatePoint(&sommet[jj][0], &sommet[jj][1], angle);
pt_track = new SEGZONE(frame->m_Pcb);
pt_track->m_Layer = layer;
pt_track->m_Width = g_DesignSettings.m_CurrentTrackWidth;
pt_track->m_NetCode = g_HightLigth_NetCode;
pt_track->start = pt_pad;
pt_track->m_Start.x = cX; pt_track->m_Start.y = cY;
pt_track->m_End.x = cX + sommet[jj][0];
pt_track->m_End.y = cY + sommet[jj][1];
pt_track->m_TimeStamp = TimeStamp;
/* tst si trace possible */
if( Drc(frame, DC, pt_track,frame->m_Pcb->m_Track,0) == BAD_DRC )
{
delete pt_track; continue;
}
/* on doit pouvoir se connecter sur la zone */
loctrack = Locate_Zone(frame->m_Pcb->m_Zone,pt_track->m_End.x,
pt_track->m_End.y,layer);
if( (loctrack == NULL) || (loctrack->m_TimeStamp != TimeStamp) )
{
delete pt_track; continue;
}
pt_track->Insert(frame->m_Pcb, NULL);
pt_track->Draw(frame->DrawPanel, DC, GR_OR);
}
}
return TRUE;
}
| [
"bokeoa@244deca0-f506-0410-ab94-f4f3571dea26"
] | [
[
[
1,
1138
]
]
] |
4ecf6addb03d5d14a80e3d4bd4ba67af65823130 | 58cda2daf1b9b27a1177c9dd45b27f195fa85ee1 | /trunk/KTV/interface/headers/Template.h | 517e018435741ff316d13bed09839274ecde7d7e | [] | no_license | sinojelly/disklvp | 25329e063a611a19ca8e7e4bfc7df297535132bd | d6f6ce24e8aab0588e071a3fb8dc320d306d8c1f | refs/heads/master | 2016-09-06T17:34:09.243481 | 2010-05-17T15:44:30 | 2010-05-17T15:44:30 | 33,052,355 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 929 | h | #ifndef GENERALSCREENTEMPLATE_H_
#define GENERALSCREENTEMPLATE_H_
#include "BaseTemplate.h"
#include "../../baselib/headers/GlobalData.h"
#include <QFont>
#include <QPen>
#include <QList>
#include <QString>
#include <QWidget>
class Template : public QWidget, public BaseTemplate{
Q_OBJECT;
protected:
int _currentPage;
int _totalPages;
private:
MyButton* _p_currentPageBut;
MyButton* _p_totalPageBut;
public:
Template(const QImage* p_image = &GlobalData::TemplateImage2);
virtual void ShowCurrentPage();
virtual void ShowTotalPages();
virtual void InitialPageZone(int currentPage=1,int totalPage=1);
virtual void DisplayData();
virtual void SetupSignalConnection(const QList<QString> nameList);
public:
void SetupPageSignalConnection(void);
public slots:
virtual void ActionToDo();
virtual void NextPage();
virtual void PreviousPage();
};
#endif /* GENERALSCREENTEMPLATE_H_ */
| [
"[email protected]",
"liulanggoukk@localhost"
] | [
[
[
1,
8
],
[
10,
10
],
[
12,
21
],
[
23,
25
],
[
29,
30
],
[
33,
34
]
],
[
[
9,
9
],
[
11,
11
],
[
22,
22
],
[
26,
28
],
[
31,
32
]
]
] |
47dab626c4408ef35fc495fcb0ad821f7ccbb364 | 9df2486e5d0489f83cc7dcfb3ccc43374ab2500c | /src/core/math/size.h | 4813ac18c6b7e707e659443cb2d62c62e7fd5679 | [] | no_license | renardchien/Eta-Chronicles | 27ad4ffb68385ecaafae4f12b0db67c096f62ad1 | d77d54184ec916baeb1ab7cc00ac44005d4f5624 | refs/heads/master | 2021-01-10T19:28:28.394781 | 2011-09-05T14:40:38 | 2011-09-05T14:40:38 | 1,914,623 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,173 | h | /***************************************************************************
* size.h - header for the corresponding cpp file
*
* Copyright (C) 2008 - 2009 Florian Richter
***************************************************************************/
/*
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.
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 SMC_SIZE_H
#define SMC_SIZE_H
#include "../../core/global_game.h"
namespace SMC
{
/* *** *** *** *** *** *** *** cSize_Int *** *** *** *** *** *** *** *** *** *** */
// class for width and height in int
class cSize_Int
{
public:
cSize_Int( void )
{ m_width = 0; m_height = 0; }
cSize_Int( int width, int height)
: m_width( width ), m_height( height ) {}
inline bool operator == ( const cSize_Int &other ) const
{
return ( m_width == other.m_width ) && ( m_height == other.m_height );
}
inline bool operator != ( const cSize_Int &other ) const
{
return ( m_width != other.m_width ) || ( m_height != other.m_height );
}
int m_width, m_height;
};
/* *** *** *** *** *** *** *** cSize_Float *** *** *** *** *** *** *** *** *** *** */
// class for width and height in float
class cSize_Float
{
public:
cSize_Float( void )
{ m_width = 0; m_height = 0; }
cSize_Float( float width, float height)
: m_width( width ), m_height( height ) {}
inline bool operator == ( const cSize_Float &other ) const
{
return Is_Float_Equal( m_width, other.m_width ) && Is_Float_Equal( m_height, other.m_height );
}
inline bool operator != ( const cSize_Float &other ) const
{
return !Is_Float_Equal( m_width, other.m_width ) || !Is_Float_Equal( m_height, other.m_height );
}
float m_width, m_height;
};
/* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
} // namespace SMC
#endif
| [
"[email protected]"
] | [
[
[
1,
78
]
]
] |
6411b5a7087a5c02c5e4447fd86a2d2845d137bf | a0de58fc332fb03adc139946006d9e4f472870eb | /raytracer/src/cmaterial.cxx | c0257e2392056a942d2a188dd19dc80b46f37941 | [] | no_license | BackupTheBerlios/flashphoto-svn | 7679f76e378a5d35353f606d218e38fd62243ee6 | 8feffa2b721489b6fa83fbd08f44e1c751b37837 | refs/heads/master | 2020-06-04T01:58:28.579762 | 2006-10-30T23:12:06 | 2006-10-30T23:12:06 | 40,673,101 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,281 | cxx | #include "raytracer.h"
#include "cmaterial.hxx"
bool CCheckerMaterial::is_white(const VECTOR &loc) const
{
VECTOR dloc=loc;
dloc.x=std::abs(dloc.x)+side_size/2;
dloc.y=std::abs(dloc.y)+side_size/2;
dloc.z=std::abs(dloc.z)+side_size/2;
bool bx=(((int)
(((float)dloc.x/(float)side_size))
%2)==0);
bool by=(((int)
(((float)dloc.y/(float)side_size))
%2)==0);
bool bz=(((int)
(((float)dloc.z/(float)side_size))
%2)==0);
if(bz)
{
if((!(bx&&by))&&(bx||by))
return true;
else
return false;
}
else
{
if((!(bx&&by))&&(bx||by))
return false;
else
return true;
}
return true;
}
CCheckerMaterial::CCheckerMaterial (CMaterial *white, CMaterial *black, SCALAR size)
{
tile_white = white;
tile_black = black;
side_size=size;
}
COLOR CCheckerMaterial::getDiffuseColor(const VECTOR &loc) const
{
if (is_white(loc))
return tile_white->getDiffuseColor(loc);
else
return tile_black->getDiffuseColor(loc);
}
SCALAR CCheckerMaterial::getReflectance(const VECTOR &loc) const
{
if (is_white(loc))
return tile_white->getReflectance(loc);
else
return tile_black->getReflectance(loc);
}
SCALAR CCheckerMaterial::getRefraction(const VECTOR &loc) const {
return 0.0;
}
| [
"rutdaun@697c275a-9409-0410-946e-c1ffe88a986e",
"gmiranda@697c275a-9409-0410-946e-c1ffe88a986e"
] | [
[
[
1,
7
],
[
9,
11
],
[
13,
21
],
[
23,
26
],
[
28,
33
],
[
35,
37
],
[
39,
64
]
],
[
[
8,
8
],
[
12,
12
],
[
22,
22
],
[
27,
27
],
[
34,
34
],
[
38,
38
],
[
65,
67
]
]
] |
cbdf4c0d5272f016fd7e3fa482c252d0cb5cd43a | 3a577d02f876776b22e2bf1c0db12a083f49086d | /vba-minimum/trunk/src/win32/BIOSDialog.h | a15632fa0bca2aa42d5900b97b0717c3bbf6f1ad | [] | 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 | 561 | h | #pragma once
// BIOSDialog dialog
class BIOSDialog : public CDialog
{
DECLARE_DYNAMIC(BIOSDialog)
public:
BIOSDialog(CWnd* pParent = NULL); // standard constructor
virtual ~BIOSDialog();
// Dialog Data
enum { IDD = IDD_BIOS };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
DECLARE_MESSAGE_MAP()
private:
CEdit m_editGBA;
static bool fileExists(CString& file);
afx_msg void OnBnClickedSelectGbaBiosPath();
public:
BOOL m_enableBIOS_GBA;
BOOL m_skipLogo;
CString m_pathGBA;
};
| [
"spacy51@5a53c671-dd2d-0410-9261-3f5c817b7aa0"
] | [
[
[
1,
29
]
]
] |
bc141a9072001e93fdd84cc0da61691b21e4f0ce | 2514632f2787fd4cba7396f60e49f5968884c688 | /BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h | 63842930d70e99812c11ed9d29ac5665ede26d8f | [] | no_license | sabotage3d/pukak | 936555b001ac738f80c69d99e3e99b5ba16c3e11 | f84f5f683de5a454e233002c9c8a9ae7f2faab6c | refs/heads/master | 2021-01-01T15:41:08.973658 | 2010-04-30T16:43:04 | 2010-04-30T16:43:04 | 35,413,544 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,365 | h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_DISCRETE_DYNAMICS_WORLD_H
#define BT_DISCRETE_DYNAMICS_WORLD_H
#include "btDynamicsWorld.h"
class btDispatcher;
class btOverlappingPairCache;
class btConstraintSolver;
class btSimulationIslandManager;
class btTypedConstraint;
class btActionInterface;
class btIDebugDraw;
#include "LinearMath/btAlignedObjectArray.h"
///btDiscreteDynamicsWorld provides discrete rigid body simulation
///those classes replace the obsolete CcdPhysicsEnvironment/CcdPhysicsController
class btDiscreteDynamicsWorld : public btDynamicsWorld
{
protected:
btConstraintSolver* m_constraintSolver;
btSimulationIslandManager* m_islandManager;
btAlignedObjectArray<btTypedConstraint*> m_constraints;
btAlignedObjectArray<btRigidBody*> m_nonStaticRigidBodies;
btVector3 m_gravity;
//for variable timesteps
btScalar m_localTime;
//for variable timesteps
bool m_ownsIslandManager;
bool m_ownsConstraintSolver;
bool m_synchronizeAllMotionStates;
btAlignedObjectArray<btActionInterface*> m_actions;
int m_profileTimings;
virtual void predictUnconstraintMotion(btScalar timeStep);
virtual void integrateTransforms(btScalar timeStep);
virtual void calculateSimulationIslands();
virtual void solveConstraints(btContactSolverInfo& solverInfo);
void updateActivationState(btScalar timeStep);
void updateActions(btScalar timeStep);
void startProfiling(btScalar timeStep);
virtual void internalSingleStepSimulation( btScalar timeStep);
virtual void saveKinematicState(btScalar timeStep);
void debugDrawSphere(btScalar radius, const btTransform& transform, const btVector3& color);
public:
///this btDiscreteDynamicsWorld constructor gets created objects from the user, and will not delete those
btDiscreteDynamicsWorld(btDispatcher* dispatcher,btBroadphaseInterface* pairCache,btConstraintSolver* constraintSolver,btCollisionConfiguration* collisionConfiguration);
virtual ~btDiscreteDynamicsWorld();
///if maxSubSteps > 0, it will interpolate motion between fixedTimeStep's
virtual int stepSimulation( btScalar timeStep,int maxSubSteps=1, btScalar fixedTimeStep=btScalar(1.)/btScalar(60.));
virtual void synchronizeMotionStates();
///this can be useful to synchronize a single rigid body -> graphics object
virtual void synchronizeSingleMotionState(btRigidBody* body); // ***** MADE VIRTUAL BY SETH HOLLADAY 2009-11-07 ***** //
virtual void addConstraint(btTypedConstraint* constraint, bool disableCollisionsBetweenLinkedBodies=false);
virtual void removeConstraint(btTypedConstraint* constraint);
virtual void addAction(btActionInterface*);
virtual void removeAction(btActionInterface*);
btSimulationIslandManager* getSimulationIslandManager()
{
return m_islandManager;
}
const btSimulationIslandManager* getSimulationIslandManager() const
{
return m_islandManager;
}
btCollisionWorld* getCollisionWorld()
{
return this;
}
virtual void setGravity(const btVector3& gravity);
virtual btVector3 getGravity () const;
virtual void addCollisionObject(btCollisionObject* collisionObject,short int collisionFilterGroup=btBroadphaseProxy::StaticFilter,short int collisionFilterMask=btBroadphaseProxy::AllFilter ^ btBroadphaseProxy::StaticFilter);
virtual void addRigidBody(btRigidBody* body);
virtual void addRigidBody(btRigidBody* body, short group, short mask);
virtual void removeRigidBody(btRigidBody* body);
///removeCollisionObject will first check if it is a rigid body, if so call removeRigidBody otherwise call btCollisionWorld::removeCollisionObject
virtual void removeCollisionObject(btCollisionObject* collisionObject);
void debugDrawObject(const btTransform& worldTransform, const btCollisionShape* shape, const btVector3& color);
void debugDrawConstraint(btTypedConstraint* constraint);
virtual void debugDrawWorld();
virtual void setConstraintSolver(btConstraintSolver* solver);
virtual btConstraintSolver* getConstraintSolver();
virtual int getNumConstraints() const;
virtual btTypedConstraint* getConstraint(int index) ;
virtual const btTypedConstraint* getConstraint(int index) const;
virtual btDynamicsWorldType getWorldType() const
{
return BT_DISCRETE_DYNAMICS_WORLD;
}
///the forces on each rigidbody is accumulating together with gravity. clear this after each timestep.
virtual void clearForces();
///apply gravity, call this once per timestep
virtual void applyGravity();
virtual void setNumTasks(int numTasks)
{
(void) numTasks;
}
///obsolete, use updateActions instead
virtual void updateVehicles(btScalar timeStep)
{
updateActions(timeStep);
}
///obsolete, use addAction instead
virtual void addVehicle(btActionInterface* vehicle);
///obsolete, use removeAction instead
virtual void removeVehicle(btActionInterface* vehicle);
///obsolete, use addAction instead
virtual void addCharacter(btActionInterface* character);
///obsolete, use removeAction instead
virtual void removeCharacter(btActionInterface* character);
void setSynchronizeAllMotionStates(bool synchronizeAll)
{
m_synchronizeAllMotionStates = synchronizeAll;
}
bool getSynchronizeAllMotionStates() const
{
return m_synchronizeAllMotionStates;
}
};
#endif //BT_DISCRETE_DYNAMICS_WORLD_H
| [
"seth.holladay@b0b181a8-020e-11df-8f7b-bfe16de6f99b"
] | [
[
[
1,
197
]
]
] |
d134485f10b7d961ddc68d5622e4d62cad2b8225 | ee065463a247fda9a1927e978143186204fefa23 | /Src/Engine/Script/WrapObjectManager.h | b960ca0e525ff44ab65aa07d3014f3eec37bdc98 | [] | no_license | ptrefall/hinsimviz | 32e9a679170eda9e552d69db6578369a3065f863 | 9caaacd39bf04bbe13ee1288d8578ece7949518f | refs/heads/master | 2021-01-22T09:03:52.503587 | 2010-09-26T17:29:20 | 2010-09-26T17:29:20 | 32,448,374 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 914 | h | #pragma once
#include <Lua/LuaPlus.h>
#include <vector>
#include <Engine/Events/EngineEventContainer.h>
#include <Engine/Events/EngineEvent.h>
namespace Engine
{
namespace Core { class CoreManager; }
namespace Script
{
class WrapObject;
class WrapObjectManager
{
public:
WrapObjectManager(Core::CoreManager *coreMgr);
~WrapObjectManager();
int init();
LuaPlus::LuaObject &getLObjs() { return lObjs; }
LuaPlus::LuaObject getLObj(unsigned int id);
WrapObject *getWObj(unsigned int id);
private:
LuaPlus::LuaObject CreateObject(LuaPlus::LuaObject lType, LuaPlus::LuaObject lName);
Core::CoreManager *coreMgr;
LuaPlus::LuaObject lObjs;
std::vector<WrapObject*> wObjs;
void OnObjectCreated(const Engine::Events::EngineEvent &event);
void OnObjectRemoved(const Engine::Events::EngineEvent &event);
Engine::Events::EngineEventContainer engineEvents;
};
}
}
| [
"[email protected]@28a56cb3-1e7c-bc60-7718-65c159e1d2df"
] | [
[
[
1,
41
]
]
] |
8a2efb0aa670292e42270367e53c54a361d66654 | f6d5124e131c83f7b64dbeeb6b0d8a4bcaa09fdd | /traumlibcheck/TraumCheck/TraumDb.h | 75fc150c4ba198fecdd82b3909c5c3b832f8d680 | [] | no_license | 5k0rp/traumlibcheck | 40bb4f16c533022f12c408c02e949f179e16cdfc | d20b56ad4f739bc867954dac2afd02e2caf2cb7a | refs/heads/master | 2021-01-01T06:54:05.354831 | 2010-12-13T23:08:39 | 2010-12-13T23:08:39 | 32,864,050 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 150 | h | #pragma once
#include "LibNode.h"
class TraumDb : public LibNodeCatalog<LibNode>
{
public:
TraumDb();
bool add(const wchar_t* path);
}; | [
"rakunov@f8c17eb4-c337-11de-8983-4d3ad078cb47"
] | [
[
[
1,
11
]
]
] |
9664f1f818519048dc50ef352159bb7ce334a5e2 | 10bac563fc7e174d8f7c79c8777e4eb8460bc49e | /act/detail/ArActionFollowTarget.hpp | ceadd631dd4e0ee9a967f4c7866858dc316fd4c6 | [] | no_license | chenbk85/alcordev | 41154355a837ebd15db02ecaeaca6726e722892a | bdb9d0928c80315d24299000ca6d8c492808f1d5 | refs/heads/master | 2021-01-10T13:36:29.338077 | 2008-10-22T15:57:50 | 2008-10-22T15:57:50 | 44,953,286 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,645 | hpp | #pragma once
#include "Aria.h"
#include <cmath>
inline int my_sign(double x) {return (x<0)? (-1) : (1) ;};
class ArActionFollowTarget: public ArAction
{
public:
// constructor, sets myMaxSpeed and myStopDistance
ArActionFollowTarget(double speed_limit);
// destructor. does not need to do anything
~ArActionFollowTarget(void) {};
//
void set_target(double mt_distance, double degree_offset);
// called by the action resolver to obtain this action's requested behavior
ArActionDesired *fire(ArActionDesired currentDesired);
// store the robot pointer, and it's ArSonarDevice object, or deactivate this action if there is no sonar.
void setRobot(ArRobot *robot);
enum eSector
{
FRONT,//front sector
LEFT,
RIGHT,
SIDE
};
//depending on sector ...
//try to adjust speed ...
enum eRange
{
isFAR, //go fast
isCLOSE,//go medium
isNEAR //stop
};
private:
// what the action wants to do; used by the action resover after fire()
ArActionDesired myDesired;
///
bool kill_Movement;
///
double front_sector;//??
///
volatile double m_rel_distance ;
///
volatile double m_rel_offset ;
///
double calcvclose();
///
double calcvfar ();
///
float dnear;
///
float dclose;
///
float dfar;
///millimetri
double vclose ;
///
double vfar;
///
double speed_dump;
double m_speed_limit;
///
///gradi
double th_near;
///gradi
double th_close;
//gradi
double deltah_close;
///gradi
double deltah_max ;
///
eSector mySector;
///
eRange myDistance;
///
ArMutex action_mutex;
};
//###################################################################
//###################################################################
//###################################################################
//
inline ArActionFollowTarget::ArActionFollowTarget(double speed_limit): ArAction("FH")
{
///
kill_Movement = false;
///
m_speed_limit = speed_limit;
//some defaul
///metri
dnear = 1.0;
///metri
dclose = 2.0;
///
dfar = 3.0;
//some defaul
///gradi
th_near = 1.0;
///gradi
th_close = 25.0;
//gradi
deltah_close = 8.0;
///gradi
deltah_max = 10.0;
///
vclose = 120;
///
vfar = 250;
///
speed_dump = 0.7;
m_rel_distance = 0;
m_rel_offset = 0;
}
//
inline void ArActionFollowTarget::set_target(double rel_distance, double rel_offset)
{
printf("setting: %f %f\n", rel_distance,rel_offset);
m_rel_distance = rel_distance;
m_rel_offset = rel_offset;
}
inline void ArActionFollowTarget::setRobot(ArRobot *robot)
{
ArAction::setRobot(robot);
}
inline ArActionDesired *ArActionFollowTarget::fire(ArActionDesired currentDesired)
{
double tempvel;
//double temprotvel;
// reset the actionDesired (must be done), to clear
// its previous values.
//myDesired.reset();
if(m_rel_distance > dnear)
{
//target is safe
if(m_rel_distance < dclose)
{
//target is close
tempvel = calcvclose();
}
else
{
//target is far
tempvel = calcvfar();
}
}
else
{
//brake
tempvel = 0;
}
tempvel = (tempvel > m_speed_limit)? (m_speed_limit) : (tempvel) ;
double absoffset = ::fabs(m_rel_offset);
if ( absoffset > th_near)
{
if(absoffset < th_close )
{
//myDesired.setRotVel();
double numer = (m_rel_offset - th_near)*(m_rel_offset - th_near);
double denom = (th_close - th_near)* (th_close - th_near);
myDesired.setDeltaHeading (my_sign(m_rel_offset)*deltah_close * (numer/denom) );
}
else
{
tempvel *= speed_dump;
myDesired.setDeltaHeading( my_sign(m_rel_offset)*deltah_max);
}
}
else
{
myDesired.setDeltaHeading(0);
}
myDesired.setVel(tempvel);
printf("Desired: VEL: %f dHeading: %f \n", myDesired.getVel()
,myDesired.getDeltaHeading());
return &myDesired;
}
///
inline double ArActionFollowTarget::calcvclose()
{
double numer = (m_rel_distance - dnear)*(m_rel_distance - dnear);
double denom = (dclose-dnear)*(dclose-dnear);
return (vclose * (numer/denom) );
}
///
inline double ArActionFollowTarget::calcvfar ()
{
double numer = (m_rel_distance-dclose)*(m_rel_distance-dclose);
double denom = (dfar-dclose)*(dfar-dclose);
double fraction = - numer/denom;
return ( ((vclose-vfar)* fraction ) + vclose );
}
| [
"andrea.carbone@1c7d64d3-9b28-0410-bae3-039769c3cb81",
"giorgio.ugazio@1c7d64d3-9b28-0410-bae3-039769c3cb81"
] | [
[
[
1,
7
],
[
9,
224
]
],
[
[
8,
8
]
]
] |
1062cee04395f21a44c977acbb372a1bc353f6a1 | e192bb584e8051905fc9822e152792e9f0620034 | /tags/sources_0_1/base/implantation/noeud_association.cxx | 44fbf4f7f1a0951db09da0e03f06a80ef434e70b | [] | no_license | BackupTheBerlios/projet-univers-svn | 708ffadce21f1b6c83e3b20eb68903439cf71d0f | c9488d7566db51505adca2bc858dab5604b3c866 | refs/heads/master | 2020-05-27T00:07:41.261961 | 2011-07-31T20:55:09 | 2011-07-31T20:55:09 | 40,817,685 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,622 | cxx | /***************************************************************************
* Copyright (C) 2004 by Equipe Projet Univers *
* [email protected] *
* *
* This program 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 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 Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU General Lesser 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. *
***************************************************************************/
template <class OBJET>
NoeudAssociation<OBJET>::NoeudAssociation(const Association<OBJET> _elt)
:NoeudAbstrait(),element(_elt)
{}
| [
"rogma@fb75c231-3be1-0310-9bb4-c95e2f850c73"
] | [
[
[
1,
25
]
]
] |
8d88c983ccb0bc7d13d975ee0c31ae3ee4da0f56 | 1eb8863bc5f0ce755c55e6bf89768574e34cfece | /Graphics/src/Renderer_Interface.cpp | 571a4f1ba1556c26b3219017ad42f7bfdd5dc7b6 | [] | no_license | jmainpri/electromag-with-cuda | a6699c1df6197f1bfdcc828c5e1f4e33f8643329 | cd19c87ffb9d8f7d8e49cc5f21823363a51db871 | refs/heads/master | 2021-01-10T09:50:56.361062 | 2011-09-11T09:15:36 | 2011-09-11T09:15:36 | 43,094,533 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,248 | cpp | /*
* Copyright (C) 2010 - Alexandru Gagniuc - <[email protected]>
* This file is part of ElectroMag.
*
* ElectroMag 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.
*
* ElectroMag 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 ElectroMag. If not, see <http://www.gnu.org/licenses/>.
*/
#include "GL/freeglut.h"
#include "Renderer Interface.h"
using std::thread;
unsigned int GLRenderer::GlRenderers = 0;
const unsigned int GLRenderer::maxGlRenderers = 2;
bool GLRenderer::glutIsInit = false;
void RendererInterface::StartAsync()
{
if (!rendererThread)
{
rendererThread = new thread(RendererInterface::StartAsyncThreadFunc,
this);
}
}
void RendererInterface::KillAsync()
{
//if (rendererThread)
//Threads::KillThread(rendererThread);
}
#include <iostream>
GLRenderer::GLRenderer()
{
isActive = false;
}
void RendererInterface::StartAsyncThreadFunc(RendererInterface* objectToInit)
{
objectToInit->AsyncStartFunc();
}
GLRenderer::~GLRenderer()
{
if (isActive)
{
GlRenderers--;
isActive = false;
}
}
void GLRenderer::Init()
{
if (isActive) return; // Do nothing
if (GlRenderers >= maxGlRenderers)
{
throw(" Only one active OpenGL renderer allowed");
return;
}
if (!glutIsInit)
{
int zero = 0;
glutInit(&zero, 0);
glutIsInit = true;
}
GlRenderers ++;
isActive = true;
GLInit();
// Register display and inputhandling functions
/*glutDisplayFunc(Display);
glutDisplayFunc(Keyboard);
glutDisplayFunc(Mouse);
glutDisplayFunc(Reshape);
glutDisplayFunc(Motion);
*/
}
| [
"mr.nuke.me@8eae5a90-4648-11de-84a6-839b6ed6c72e",
"[email protected]"
] | [
[
[
1,
28
],
[
31,
32
],
[
34,
45
],
[
47,
55
],
[
61,
61
],
[
63,
64
],
[
66,
66
],
[
72,
72
],
[
74,
78
],
[
91,
92
]
],
[
[
29,
30
],
[
33,
33
],
[
46,
46
],
[
56,
60
],
[
62,
62
],
[
65,
65
],
[
67,
71
],
[
73,
73
],
[
79,
90
]
]
] |
6bd28cabd3e422602dba2f8c50a8a17d7989ce38 | 41371839eaa16ada179d580f7b2c1878600b718e | /UVa/Volume CII/10201.cpp | a50951e33350e1612351ec4631a6cb90782a16cf | [] | no_license | marinvhs/SMAS | 5481aecaaea859d123077417c9ee9f90e36cc721 | 2241dc612a653a885cf9c1565d3ca2010a6201b0 | refs/heads/master | 2021-01-22T16:31:03.431389 | 2009-10-01T02:33:01 | 2009-10-01T02:33:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,694 | cpp | /////////////////////////////////
// 10201 - Adventures in Moving - Part IV
/////////////////////////////////
#include<cstdio>
#include<cstring>
#define MAX_POSTOS 101
int candidato,custo,i,litros,mais_barato,n,npostos,pos_atual,pos_final;
int pos[MAX_POSTOS];
int preco[MAX_POSTOS];
char ch;
bool possivel,achou;
int main(void){
scanf("%d",&n);
while(n){
n--;
scanf("%d",&pos_final);
ch = getchar();
for(i = 0; ;ch = getchar(),i++){
if((ch = getchar()) == '\n') break;
ungetc(ch,stdin);
if(scanf("%d %d",&pos[i],&preco[i])==EOF) break;
}
possivel = 1;
npostos = i;
pos[npostos] = pos_final = pos_final+100;
preco[npostos++] = 0;
if(pos[0] > 100 || npostos == 1) possivel = 0;
else for(i = 1;possivel && i < npostos; i++) if(pos[i]-pos[i-1] > 200) possivel = 0;
if(possivel) {
litros = 100;
pos_atual = custo = candidato = 0;
while(pos_atual+litros < pos_final){
achou = 0;
for(i = candidato, mais_barato = 2001; pos_atual+litros >= pos[i]; i++)
if(preco[i] < mais_barato){
mais_barato = preco[i];
candidato = i;
}
litros -= pos[candidato]-pos_atual;
pos_atual = pos[candidato];
for(i = candidato+1; i < npostos && pos[i] - pos_atual < 200; i++)
if(preco[i] < preco[candidato]){
custo += preco[candidato]*(pos[i]-pos_atual-litros);
litros = 0;
pos_atual = pos[i];
candidato = i;
achou = 1;
break;
}
if(!achou) {
custo += preco[candidato++]*(200-litros);
litros = 200;
}
}
}
(possivel? printf("%d\n",custo):printf("Impossible\n"));
if(n) printf("\n");
}
} | [
"[email protected]"
] | [
[
[
1,
59
]
]
] |
52b8484d7c32912ec2688345d0d150bf55d35a05 | 2112057af069a78e75adfd244a3f5b224fbab321 | /branches/refactor/src_root/include/map_splitter/MapEqualizer.h | 40bf6f0e186b94cb038e18336fa94128032e95fc | [] | no_license | blockspacer/ireon | 120bde79e39fb107c961697985a1fe4cb309bd81 | a89fa30b369a0b21661c992da2c4ec1087aac312 | refs/heads/master | 2023-04-15T00:22:02.905112 | 2010-01-07T20:31:07 | 2010-01-07T20:31:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,921 | h | /***************************************************************************
* *
* This program 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 of the *
* License, or (at your option) any later version. *
* *
***************************************************************************/
/**
@file
MapEqualizer.h
@brief
Utility that split big map in tiles, pre-calculate splatting by
pre-calculating coverage map and pre-calculate normals.
*/
#ifndef MapEqualizer_H
#define MapEqualizer_H
#include "Ogre.h"
#include "OgreImage.h"
#include "OgreString.h"
#include "OgreSingleton.h"
#include "OgrePagingLandScapeData2D.h"
namespace Ogre
{
/**
* \ingroup Tool_MapEqualizer
*
*
* \par untested on linux
*
* \version 0.2
* second version
*
* \date 06-07-2004
*
* \author [email protected]
*
* \todo
*
* \bug
*/
class MapEqualizer
{
public :
MapEqualizer();
~MapEqualizer();
void equalize ();
void normalize (Real *field, const uint size);
/*
Generate terrain using diamond-square (plasma) algorithm
*/
void MakeTerrainPlasma(Real * field,int size,float rough);
/*
Drop particles, peak, flood fill, erode
*/
void MapEqualizer::MakeTerrainDeposition(Real * field,int size,int jumps,
int peakWalk, int minParticlesPerJump,int maxParticlesPerJump,
float caldera);
private:
/*
Returns a random number between v1 and v2
*/
float RangedRandom(float v1,float v2);
void MakeTerrainFault(Real *field,int size,int iterations,
int maxDelta,int minDelta,
int iterationsPerFilter,
float filter);
/*
Erosion filter -
Erodes a terrain in all 4 directions
*/
void Erode(Real * field,int size,float filter);
/*
Erosion filter -
FilterHeightBand applies a FIR filter across a row or column of the height field
*/
void ErodeOneDirection(float *band,int stride,int count,float filter);
uint mColorsNum;
uint mwidth;
uint mheight;
Real *mData;
};
/**
* \ingroup Tool_ErodeFault
* \author [email protected]
*/
class ErodeFault
{
public :
ErodeFault();
~ErodeFault();
/**
* Make the heighfield uses the max of information range
* does modify heavily heightmap
* \param field the heightmap
* \param size field must be square and side is length of a side
* \param hmin min height in heightfield
* \param hmax max height in heightfield
* \param maxColor 256 for 8bits heightmap and 65535 for raw files
*/
void equalize (Real * const field,
const uint size,
const Real hmin,
const Real hmax,
const uint maxColor) const;
void normalize (Real * const field,
const uint size,
const Real scale) const;
/*
Generate terrain using diamond-square (plasma) algorithm
*/
void MakeTerrainPlasma(Real * const field,
const uint size,
const float rough,
const float scale) const;
/*
Drop particles, peak, flood fill, erode
*/
void MakeTerrainDeposition(Real * const field,
const uint size,
const uint jumps,
const uint peakWalk,
const uint minParticlesPerJump,
const uint maxParticlesPerJump,
const float caldera,
const float scale) const;
void MakeTerrainFault(Real * const field,
const uint size,
const uint iterations,
const uint maxDelta,
const uint minDelta,
const uint iterationsPerFilter,
const float filter,
const float scale) const;
/*
Erosion filter -
Erodes a terrain in all 4 directions
*/
void Erode(Real * const field, const uint size, const float filter) const;
private:
/*
Returns a random number between v1 and v2
*/
float RangedRandom(const float v1, const float v2) const;
/*
Erosion filter -
FilterHeightBand applies a FIR filter across a row or column of the height field
*/
void ErodeOneDirection(float * const band,
const int stride,
const uint count,
const float filter) const;
};
// Defines
#define PI 3.14159265359f // PI
#define HALF_PI 1.570796326795f // PI / 2
#define TWO_PI 6.28318530718f // PI * 2
#define LOGHALF -0.6931471805599f // log(0.5)
#define LOGHALFI -1.442695040889f // Inverse of log(0.5)
#define DELTA 1e-6f // Small number for comparing floating point numbers
#define MAX_DIMENSIONS 4 // Maximum number of dimensions in a noise object
#define MAX_OCTAVES 128 // Maximum # of octaves in an fBm object
// Macros
#define SQUARE(a) ((a) * (a))
#define FLOOR(a) ((int)(a) - ((a) < 0 && (a) != (int)(a)))
#define CEILING(a) ((int)(a) + ((a) > 0 && (a) != (int)(a)))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define ABS(a) ((a) < 0 ? -(a) : (a))
#define CLAMP(a, b, x) ((x) < (a) ? (a) : ((x) > (b) ? (b) : (x)))
#define LERP(a, b, x) ((a) + (x) * ((b) - (a)))
#define CUBIC(a) ((a) * (a) * (3 - 2*(a)))
#define STEP(a, x) ((x) >= (a))
#define BOXSTEP(a, b, x) Clamp(0, 1, ((x)-(a))/((b)-(a)))
#define PULSE(a, b, x) (((x) >= (a)) - ((x) >= (b)))
#define GAMMA(a, g) powf(a, 1/g)
#define BIAS(a, b) powf(a, logf(b) * LOGHALFI)
#define EXPOSE(l, k) (1 - expf(l * k))
#define DEGTORAD(x) ((x) * 0.01745329251994f)
#define RADTODEG(x) ((x) * 57.29577951308f)
#define SWAP(a, b, t) t = a; a = b; b = t
// Inline functions (use instead of macros to avoid performing slow operations twice)
inline float Square(const float a) { return a * a; }
inline int Floor(const float a) { return ((int)a - (a < 0 && a != (int)a)); }
inline int Ceiling(const float a) { return ((int)a + (a > 0 && a != (int)a)); }
inline float Min(const float a, const float b) { return (a < b ? a : b); }
inline float Max(const float a, const float b) { return (a > b ? a : b); }
inline float Abs(const float a) { return (a < 0 ? -a : a); }
inline float Clamp(const float a, const float b, const float x) { return (x < a ? a : (x > b ? b : x)); }
inline float Lerp(const float a, const float b, const float x) { return a + x * (b - a); }
inline float Cubic(const float a) { return a * a * (3 - 2*a); }
inline float Step(const float a, const float x) { return (float)(x >= a); }
inline float Boxstep(const float a, const float b, const float x) { return Clamp(0, 1, (x-a)/(b-a)); }
inline float Pulse(const float a, const float b, const float x) { return (float)((x >= a) - (x >= b)); }
inline float Gamma(const float a, const float g) { return powf(a, 1/g); }
inline float Bias(const float a, const float b) { return powf(a, logf(b) * LOGHALFI); }
inline float Expose(const float l, const float k) { return (1 - expf(-l * k)); }
inline float Gain(const float a, const float b)
{
if(a <= DELTA)
return 0;
if(a >= 1-DELTA)
return 1;
register float p = (logf(1 - b) * LOGHALFI);
if(a < 0.5)
return powf(2 * a, p) * 0.5f;
else
return 1 - powf(2 * (1 - a), p) * 0.5f;
}
inline float Smoothstep(const float a, const float b, const float x)
{
if(x <= a)
return 0;
if(x >= b)
return 1;
return Cubic((x - a) / (b - a));
}
inline float Mod(float a, const float b)
{
a -= ((int)(a / b)) * b;
if(a < 0)
a += b;
return a;
}
inline void Normalize(float * const f, const uint n)
{
float fMagnitude = 0;
uint i;
for(i=0; i<n; i++)
fMagnitude += f[i]*f[i];
const float cfMagnitude = 1 / sqrtf(fMagnitude);
for(i=0; i<n; i++)
f[i] *= cfMagnitude;
}
/*******************************************************************************
* Class: CRandom
********************************************************************************
* This class wraps a random number generator. I plan to implement my own random
* number generator so I can keep the seeds as member variables (which is more
* flexible than using statics or globals). I was using one I found on the
* Internet implemented in assembler, but I was having problems with it so I
* removed it for this demo.
*******************************************************************************/
class CRandom
{
public:
CRandom() {}
CRandom(unsigned int nSeed) { Init(nSeed); }
void Init(unsigned int nSeed) { srand(nSeed); }
double Random() { return (double)rand()/(double)RAND_MAX; }
double RandomD(const double dMin, const double dMax)
{
const double dInterval = dMax - dMin;
const double d = dInterval * Random();
return dMin + MIN(d, dInterval);
}
unsigned int RandomI(const unsigned int nMin, const unsigned int nMax)
{
const unsigned int nInterval = nMax - nMin;
const unsigned int i = (unsigned int)((nInterval+1.0) * Random());
return nMin + MIN(i, nInterval);
}
};
/*******************************************************************************
* Class: CNoise
********************************************************************************
* This class implements the Perlin noise function. Initialize it with the number
* of dimensions (1 to 4) and a random seed. I got the source for the first 3
* dimensions from "Texturing & Modeling: A Procedural Approach". I added the
* extra dimension because it may be desirable to use 3 spatial dimensions and
* one time dimension. The noise buffers are set up as member variables so that
* there may be several instances of this class in use at the same time, each
* initialized with different parameters.
*******************************************************************************/
class CNoise
{
protected:
uint m_nDimensions; // Number of dimensions used by this object
unsigned char m_nMap[256]; // Randomized map of indexes into buffer
float m_nBuffer[256][MAX_DIMENSIONS]; // Random n-dimensional buffer
float Lattice(const uint ix, const float fx,
const uint iy=0, const float fy=0,
const uint iz=0, const float fz=0,
const uint iw=0, const float fw=0) const
{
uint n[4] = {ix, iy, iz, iw};
float f[4] = {fx, fy, fz, fw};
int nIndex = 0;
uint i;
for(i=0; i<m_nDimensions; i++)
nIndex = m_nMap[(nIndex + n[i]) & 0xFF];
float fValue = 0;
for(i=0; i<m_nDimensions; i++)
fValue += m_nBuffer[nIndex][i] * f[i];
return fValue;
}
public:
CNoise() {}
CNoise(const uint nDimensions, const unsigned int nSeed) { Init(nDimensions, nSeed); }
void Init(const uint nDimensions, const unsigned int nSeed);
float Noise(float * const f) const ;
};
/*******************************************************************************
* Class: CFractal
********************************************************************************
* This class implements fBm, or fractal Brownian motion. Since fBm uses Perlin
* noise, this class is derived from CNoise. Initialize it with the number of
* dimensions (1 to 4), a random seed, H (roughness ranging from 0 to 1), and
* the lacunarity (2.0 is often used). Many of the fractal routines came from
* "Texturing & Modeling: A Procedural Approach". fBmTest() is my own creation,
* and I created it to generate my first planet.
*******************************************************************************/
class CFractal : public CNoise
{
public:
CFractal() {}
CFractal(const uint nDimensions, const unsigned int nSeed, const float fH, const float fLacunarity)
{
Init(nDimensions, nSeed, fH, fLacunarity);
}
void Init(const uint nDimensions, const unsigned int nSeed, const float fH, const float fLacunarity)
{
CNoise::Init(nDimensions, nSeed);
m_fH = fH;
m_fLacunarity = fLacunarity;
float f = 1;
uint i;
for(i=0; i<MAX_OCTAVES; i++)
{
m_fExponent[i] = powf(f, -m_fH);
f *= m_fLacunarity;
}
}
float fBm(float *f, const float fOctaves) const ;
float Turbulence(float *f, const float fOctaves) const ;
float Multifractal(float *f, const float fOctaves, const float fOffset) const ;
float Heterofractal(float *f, const float fOctaves, const float fOffset) const ;
float HybridMultifractal(float *f, const float fOctaves, const float fOffset, const float fGain) const ;
float RidgedMultifractal(float *f, const float fOctaves, const float fOffset,const float fThreshold) const ;
float fBmTest(float *f, const float fOctaves) const ;
protected:
float m_fH;
float m_fLacunarity;
float m_fExponent[MAX_OCTAVES];
};
}
#endif //MapEqualizer_H
| [
"[email protected]"
] | [
[
[
1,
388
]
]
] |
3a970c80d04ef55a9b6f786b9ab17696869934c7 | c1a2953285f2a6ac7d903059b7ea6480a7e2228e | /deitel/ch20/Fig20_15/List.h | 025eead80ebf6427d117ac1f58245cc8c88928eb | [] | no_license | tecmilenio/computacion2 | 728ac47299c1a4066b6140cebc9668bf1121053a | a1387e0f7f11c767574fcba608d94e5d61b7f36c | refs/heads/master | 2016-09-06T19:17:29.842053 | 2008-09-28T04:27:56 | 2008-09-28T04:27:56 | 50,540 | 4 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 6,270 | h | // Fig. 20.4: List.h
// Template List class definition.
#ifndef LIST_H
#define LIST_H
#include <iostream>
using std::cout;
#include <new>
#include "ListNode.h" // ListNode class definition
template< typename NODETYPE >
class List
{
public:
List(); // constructor
~List(); // destructor
void insertAtFront( const NODETYPE & );
void insertAtBack( const NODETYPE & );
bool removeFromFront( NODETYPE & );
bool removeFromBack( NODETYPE & );
bool isEmpty() const;
void print() const;
private:
ListNode< NODETYPE > *firstPtr; // pointer to first node
ListNode< NODETYPE > *lastPtr; // pointer to last node
// utility function to allocate new node
ListNode< NODETYPE > *getNewNode( const NODETYPE & );
}; // end class List
// default constructor
template< typename NODETYPE >
List< NODETYPE >::List()
: firstPtr( 0 ), lastPtr( 0 )
{
// empty body
} // end List constructor
// destructor
template< typename NODETYPE >
List< NODETYPE >::~List()
{
if ( !isEmpty() ) // List is not empty
{
cout << "Destroying nodes ...\n";
ListNode< NODETYPE > *currentPtr = firstPtr;
ListNode< NODETYPE > *tempPtr;
while ( currentPtr != 0 ) // delete remaining nodes
{
tempPtr = currentPtr;
cout << tempPtr->data << '\n';
currentPtr = currentPtr->nextPtr;
delete tempPtr;
} // end while
} // end if
cout << "All nodes destroyed\n\n";
} // end List destructor
// insert node at front of list
template< typename NODETYPE >
void List< NODETYPE >::insertAtFront( const NODETYPE &value )
{
ListNode< NODETYPE > *newPtr = getNewNode( value ); // new node
if ( isEmpty() ) // List is empty
firstPtr = lastPtr = newPtr; // new list has only one node
else // List is not empty
{
newPtr->nextPtr = firstPtr; // point new node to previous 1st node
firstPtr = newPtr; // aim firstPtr at new node
} // end else
} // end function insertAtFront
// insert node at back of list
template< typename NODETYPE >
void List< NODETYPE >::insertAtBack( const NODETYPE &value )
{
ListNode< NODETYPE > *newPtr = getNewNode( value ); // new node
if ( isEmpty() ) // List is empty
firstPtr = lastPtr = newPtr; // new list has only one node
else // List is not empty
{
lastPtr->nextPtr = newPtr; // update previous last node
lastPtr = newPtr; // new last node
} // end else
} // end function insertAtBack
// delete node from front of list
template< typename NODETYPE >
bool List< NODETYPE >::removeFromFront( NODETYPE &value )
{
if ( isEmpty() ) // List is empty
return false; // delete unsuccessful
else
{
ListNode< NODETYPE > *tempPtr = firstPtr; // hold tempPtr to delete
if ( firstPtr == lastPtr )
firstPtr = lastPtr = 0; // no nodes remain after removal
else
firstPtr = firstPtr->nextPtr; // point to previous 2nd node
value = tempPtr->data; // return data being removed
delete tempPtr; // reclaim previous front node
return true; // delete successful
} // end else
} // end function removeFromFront
// delete node from back of list
template< typename NODETYPE >
bool List< NODETYPE >::removeFromBack( NODETYPE &value )
{
if ( isEmpty() ) // List is empty
return false; // delete unsuccessful
else
{
ListNode< NODETYPE > *tempPtr = lastPtr; // hold tempPtr to delete
if ( firstPtr == lastPtr ) // List has one element
firstPtr = lastPtr = 0; // no nodes remain after removal
else
{
ListNode< NODETYPE > *currentPtr = firstPtr;
// locate second-to-last element
while ( currentPtr->nextPtr != lastPtr )
currentPtr = currentPtr->nextPtr; // move to next node
lastPtr = currentPtr; // remove last node
currentPtr->nextPtr = 0; // this is now the last node
} // end else
value = tempPtr->data; // return value from old last node
delete tempPtr; // reclaim former last node
return true; // delete successful
} // end else
} // end function removeFromBack
// is List empty?
template< typename NODETYPE >
bool List< NODETYPE >::isEmpty() const
{
return firstPtr == 0;
} // end function isEmpty
// return pointer to newly allocated node
template< typename NODETYPE >
ListNode< NODETYPE > *List< NODETYPE >::getNewNode(
const NODETYPE &value )
{
return new ListNode< NODETYPE >( value );
} // end function getNewNode
// display contents of List
template< typename NODETYPE >
void List< NODETYPE >::print() const
{
if ( isEmpty() ) // List is empty
{
cout << "The list is empty\n\n";
return;
} // end if
ListNode< NODETYPE > *currentPtr = firstPtr;
cout << "The list is: ";
while ( currentPtr != 0 ) // get element data
{
cout << currentPtr->data << ' ';
currentPtr = currentPtr->nextPtr;
} // end while
cout << "\n\n";
} // end function print
#endif
/**************************************************************************
* (C) Copyright 1992-2008 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/
| [
"[email protected]"
] | [
[
[
1,
197
]
]
] |
ab6af839cfb28bfba714bb4ea4527bcdc6ffbac6 | b2d46af9c6152323ce240374afc998c1574db71f | /cursovideojuegos/theflostiproject/3rdParty/boost/libs/filesystem/src/path_posix_windows.cpp | b89c7ba857369edf09e85aeff413d1668393e429 | [] | 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 | WINDOWS-1252 | C++ | false | false | 20,997 | cpp | // path implementation -----------------------------------------------------//
// © Copyright Beman Dawes 2002-2003
// Use, modification, and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See library home page at http://www.boost.org/libs/filesystem
//****************************************************************************//
// WARNING: This code was hacked time and time again as different library
// designs were tried. Thus portions may be residue from the earlier
// experiments, and be totally stupid or wrong in light of the final library
// specifications. The code needs to be reviewed line-by-line to elmininate
// such problems.
//****************************************************************************//
// define BOOST_FILESYSTEM_SOURCE so that <boost/filesystem/config.hpp> knows
// the library is being built (possibly exporting rather than importing code)
#define BOOST_FILESYSTEM_SOURCE
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/exception.hpp>
// BOOST_POSIX or BOOST_WINDOWS specify which API to use.
# if !defined( BOOST_WINDOWS ) && !defined( BOOST_POSIX )
# if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) || defined(__CYGWIN__)
# define BOOST_WINDOWS
# else
# define BOOST_POSIX
# endif
# endif
namespace fs = boost::filesystem;
#include <boost/config.hpp>
#ifdef BOOST_NO_STDC_NAMESPACE
namespace std { using ::strlen; }
#endif
#include <boost/throw_exception.hpp>
#include <cstring> // SGI MIPSpro compilers need this
#include <vector>
#include <algorithm> // for lexicographical_compare
#include <cassert>
#include <boost/config/abi_prefix.hpp> // must be the last header
// helpers -----------------------------------------------------------------//
namespace
{
// POSIX & Windows cases: "", "/", "/foo", "foo", "foo/bar"
// Windows only cases: "c:", "c:/", "c:foo", "c:/foo",
// "prn:", "//share", "//share/", "//share/foo"
std::string::size_type leaf_pos( const std::string & str,
std::string::size_type end_pos ) // end_pos is past-the-end position
// return 0 if str itself is leaf (or empty)
{
if ( end_pos && str[end_pos-1] == '/' ) return end_pos-1;
std::string::size_type pos( str.find_last_of( '/', end_pos-1 ) );
# ifdef BOOST_WINDOWS
if ( pos == std::string::npos ) pos = str.find_last_of( ':', end_pos-2 );
# endif
return ( pos == std::string::npos // path itself must be a leaf (or empty)
# ifdef BOOST_WINDOWS
|| (pos == 1 && str[0] == '/') // or share
# endif
) ? 0 // so leaf is entire string
: pos + 1; // or starts after delimiter
}
void first_name( const std::string & src, std::string & target )
{
target = ""; // VC++ 6.0 doesn't have string::clear()
std::string::const_iterator itr( src.begin() );
# ifdef BOOST_WINDOWS
// deal with //share
if ( src.size() >= 2 && src[0] == '/' && src[1] == '/' )
{ target = "//"; itr += 2; }
# endif
while ( itr != src.end()
# ifdef BOOST_WINDOWS
&& *itr != ':'
# endif
&& *itr != '/' ) { target += *itr++; }
if ( itr == src.end() ) return;
# ifdef BOOST_WINDOWS
if ( *itr == ':' )
{
target += *itr++;
return;
}
# endif
// *itr is '/'
if ( itr == src.begin() ) { target += '/'; }
return;
}
const char invalid_chars[] =
"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"
"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F"
"<>:\"/\\|";
// note that the terminating '\0' is part of the string - thus the size below
// is sizeof(invalid_chars) rather than sizeof(invalid_chars)-1. I
const std::string windows_invalid_chars( invalid_chars, sizeof(invalid_chars) );
const std::string valid_posix(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-" );
fs::path::name_check default_check = fs::portable_name;
bool safe_to_write_check = true; // write-once-before-read allowed
} // unnamed namespace
//----------------------------------------------------------------------------//
namespace boost
{
namespace filesystem
{
// name_check functions ----------------------------------------------//
# ifdef BOOST_WINDOWS
BOOST_FILESYSTEM_DECL bool native( const std::string & name )
{
return windows_name( name );
}
# else
BOOST_FILESYSTEM_DECL bool native( const std::string & )
{
return true;
}
# endif
BOOST_FILESYSTEM_DECL bool no_check( const std::string & ) { return true; }
BOOST_FILESYSTEM_DECL bool portable_posix_name( const std::string & name )
{
return name.size() != 0
&& name.find_first_not_of( valid_posix ) == std::string::npos;
}
BOOST_FILESYSTEM_DECL bool windows_name( const std::string & name )
{
return name.size() != 0
&& name.find_first_of( windows_invalid_chars ) == std::string::npos
&& *(name.end()-1) != ' '
&& (*(name.end()-1) != '.'
|| name.length() == 1 || name == "..");
}
BOOST_FILESYSTEM_DECL bool portable_name( const std::string & name )
{
return
name.size() == 0
|| name == "."
|| name == ".."
|| (windows_name( name )
&& portable_posix_name( name )
&& name[0] != '.' && name[0] != '-');
}
BOOST_FILESYSTEM_DECL bool portable_directory_name( const std::string & name )
{
return
name == "."
|| name == ".."
|| (portable_name( name )
&& name.find('.') == std::string::npos);
}
BOOST_FILESYSTEM_DECL bool portable_file_name( const std::string & name )
{
std::string::size_type pos;
return
name == "."
|| name == ".."
|| (portable_name( name )
&& ( (pos = name.find( '.' )) == std::string::npos
|| (name.find( '.', pos+1 )== std::string::npos
&& (pos + 5) > name.length() )))
;
}
// path implementation -----------------------------------------------------//
path::path( const std::string & src )
{
m_path_append( src, default_name_check() );
}
path::path( const char * src )
{
assert( src != 0 );
m_path_append( src, default_name_check() );
}
path::path( const std::string & src, name_check checker )
{
m_path_append( src, checker );
}
path::path( const char * src, name_check checker )
{
assert( src != 0 );
m_path_append( src, checker );
}
path & path::operator /=( const path & rhs )
{
m_path_append( rhs.m_path, no_check );
return *this;
}
void path::m_path_append( const std::string & src, name_check checker )
{
// convert backslash to forward slash if checker==native
// allow system-specific-root if checker==no_check || checker==native
assert( checker );
assert( src.size() == std::strlen( src.c_str() ) ); // no embedded 0
if ( src.size() == 0 ) return;
std::string::const_iterator itr( src.begin() );
// [root-filesystem]
# ifdef BOOST_WINDOWS
if ( (checker == no_check || checker == native) && src.size() >= 2 )
{
// drive or device
if ( src[1] == ':' || src[src.size()-1] == ':' )
{
for ( ; *itr != ':'; ++itr ) m_path += *itr;
m_path += ':';
++itr;
}
// share
else if ( (*itr == '/' || (*itr == '\\' && checker == native))
&& (*(itr+1) == '/' || (*(itr+1) == '\\' && checker == native)) )
{
m_path += "//";
for ( itr += 2;
itr != src.end() && *itr != '/' && *itr != '\\';
++itr ) m_path += *itr;
}
}
# endif
// root directory [ "/" ]
if ( itr != src.end() && (*itr == '/'
# ifdef BOOST_WINDOWS
|| (*itr == '\\' && checker == native)
# endif
) )
{
++itr;
if ( m_path.size() == 0
# ifdef BOOST_WINDOWS
|| m_path[m_path.size()-1] == ':' // drive or device
|| ( // share
m_path.size() > 2
&& m_path[0] == '/'
&& m_path[1] == '/'
&& m_path.find( '/', 2 ) == std::string::npos
)
# endif
) m_path += '/';
}
// element { "/" element } [ "/" ]
while ( itr != src.end() )
{
if ( m_path == "." ) m_path = "";
// directory-placeholder
if ( *itr == '.' && ((itr+1) == src.end() || *(itr+1) == '/'
# ifdef BOOST_WINDOWS
|| *(itr+1) == '\\'
# endif
) )
{
if ( empty() ) m_path += '.';
++itr;
}
// parent-directory or name
else
{
// append '/' if needed
if ( !empty()
# ifdef BOOST_WINDOWS
&& *(m_path.end()-1) != ':'
# endif
&& *(m_path.end()-1) != '/' )
m_path += '/';
// parent-directory
if ( *itr == '.'
&& (itr+1) != src.end() && *(itr+1) == '.'
&& ((itr+2) == src.end() || *(itr+2) == '/'
# ifdef BOOST_WINDOWS
|| *(itr+2) == '\\'
# endif
) )
{
m_path += "..";
++itr;
++itr;
} // parent-directory
// name
else
{
std::string name;
do
{ name += *itr; }
while ( ++itr != src.end() && *itr != '/'
# ifdef BOOST_WINDOWS
&& (*itr != '\\' || checker != native)
# endif
);
if ( !checker( name ) )
{
boost::throw_exception( filesystem_error(
"boost::filesystem::path",
"invalid name \"" + name + "\" in path: \"" + src + "\"" ) );
}
m_path += name;
}
} // parent-directory or name
// end or "/"
if ( itr != src.end() )
{
if ( *itr == '/'
# ifdef BOOST_WINDOWS
|| (*itr == '\\' && checker == native)
# endif
) ++itr;
else
boost::throw_exception( filesystem_error(
"boost::filesystem::path",
"invalid path syntax: \"" + src + "\"" ) );
}
} // while more elements
// special case: remove one or more leading "/.."
std::string::size_type pos = 0, sz = m_path.size();
# ifdef BOOST_WINDOWS
if ( sz > 2 && m_path[pos] != '/' && m_path[pos+1] == ':' ) // drive
{ pos += 2; sz -= 2; }
# endif
while ( sz >= 3 && m_path[pos] == '/'
&& m_path[pos+1] == '.' && m_path[pos+2] == '.'
&& (sz == 3 || m_path[pos+3] == '/') )
{
m_path.erase( pos+1, 3 ); // "..[/]"
sz -= 3; // on last, 3 should be 2; that doesn't matter
}
}
// path conversion functions ------------------------------------------------//
std::string path::native_file_string() const
{
# ifdef BOOST_WINDOWS
std::string s( m_path );
for ( std::string::iterator itr( s.begin() );
itr != s.end(); ++itr )
if ( *itr == '/' ) *itr = '\\';
return s;
# else
return m_path;
# endif
}
std::string path::native_directory_string() const
{ return native_file_string(); }
// path modification functions -----------------------------------------------//
path & path::normalize()
{
if ( m_path.empty() ) return *this;
std::string::size_type end, beg(0), start(0);
# ifdef BOOST_WINDOWS
if ( m_path.size() > 2
&& m_path[0] != '/' && m_path[1] == ':' ) start = 2; // drive
# endif
while ( (beg=m_path.find( "/..", beg )) != std::string::npos )
{
end = beg + 3;
if ( (beg == 1 && m_path[0] == '.')
|| (beg == 2 && m_path[0] == '.' && m_path[1] == '.')
|| (beg > 2 && m_path[beg-3] == '/'
&& m_path[beg-2] == '.' && m_path[beg-1] == '.') )
{
beg = end;
continue;
}
if ( end < m_path.size() )
{
if ( m_path[end] == '/' ) ++end;
else { beg = end; continue; } // name starts with ..
}
// end is one past end of substr to be erased; now set beg
while ( beg > start && m_path[--beg] != '/' ) {}
if ( m_path[beg] == '/') ++beg;
m_path.erase( beg, end-beg );
if ( beg ) --beg;
}
if ( m_path.empty() ) m_path = ".";
else
{ // remove trailing '/' if not root directory
std::string::size_type sz = m_path.size();
# ifdef BOOST_WINDOWS
if ( start ) sz -= 2; // drive
# endif
if ( sz > 1 && m_path[m_path.size()-1] == '/' )
{ m_path.erase( m_path.size()-1 ); }
}
return *this;
}
// path decomposition functions ---------------------------------------------//
path::iterator path::begin() const
{
iterator itr;
itr.m_path_ptr = this;
first_name( m_path, itr.m_name );
itr.m_pos = 0;
return itr;
}
void path::m_replace_leaf( const char * new_leaf )
{
m_path.erase( leaf_pos( m_path, m_path.size() ) );
m_path += new_leaf;
}
std::string path::leaf() const
{
return m_path.substr( leaf_pos( m_path, m_path.size() ) );
}
namespace detail
{
inline bool is_absolute_root( const std::string & s,
std::string::size_type len )
{
return
len && s[len-1] == '/'
&&
(
len == 1 // "/"
# ifdef BOOST_WINDOWS
|| ( len > 1
&& ( s[len-2] == ':' // drive or device
|| ( s[0] == '/' // share
&& s[1] == '/'
&& s.find( '/', 2 ) == len-1
)
)
)
# endif
);
}
}
path path::branch_path() const
{
std::string::size_type end_pos( leaf_pos( m_path, m_path.size() ) );
// skip a '/' unless it is a root directory
if ( end_pos && m_path[end_pos-1] == '/'
&& !detail::is_absolute_root( m_path, end_pos ) ) --end_pos;
return path( m_path.substr( 0, end_pos ), no_check );
}
path path::relative_path() const
{
std::string::size_type pos( 0 );
if ( m_path.size() && m_path[0] == '/' )
{ pos = 1;
# ifdef BOOST_WINDOWS
if ( m_path.size()>1 && m_path[1] == '/' ) // share
{
if ( (pos = m_path.find( '/', 2 )) != std::string::npos ) ++pos;
else return path();
}
}
else if ( (pos = m_path.find( ':' )) == std::string::npos ) pos = 0;
else // has ':'
{
if ( ++pos < m_path.size() && m_path[pos] == '/' ) ++pos;
# endif
}
return path( m_path.substr( pos ), no_check );
}
std::string path::root_name() const
{
# ifdef BOOST_WINDOWS
std::string::size_type pos( m_path.find( ':' ) );
if ( pos != std::string::npos ) return m_path.substr( 0, pos+1 );
if ( m_path.size() > 2 && m_path[0] == '/' && m_path[1] == '/' )
{
pos = m_path.find( '/', 2 );
return m_path.substr( 0, pos );
}
# endif
return std::string();
}
std::string path::root_directory() const
{
return std::string(
( m_path.size() && m_path[0] == '/' ) // covers both "/" and "//share"
# ifdef BOOST_WINDOWS
|| ( m_path.size() > 2
&& m_path[1] == ':'
&& m_path[2] == '/' ) // "c:/"
# endif
? "/" : "" );
}
path path::root_path() const
{
return path(
# ifdef BOOST_WINDOWS
root_name(), no_check ) /= root_directory();
# else
root_directory() );
# endif
}
// path query functions -----------------------------------------------------//
bool path::is_complete() const
{
# ifdef BOOST_WINDOWS
return m_path.size() > 2
&& ( (m_path[1] == ':' && m_path[2] == '/') // "c:/"
|| (m_path[0] == '/' && m_path[1] == '/') // "//share"
|| m_path[m_path.size()-1] == ':' );
# else
return m_path.size() && m_path[0] == '/';
# endif
}
bool path::has_root_path() const
{
return ( m_path.size()
&& m_path[0] == '/' ) // covers both "/" and "//share"
# ifdef BOOST_WINDOWS
|| ( m_path.size() > 1 && m_path[1] == ':' ) // "c:" and "c:/"
|| ( m_path.size() > 3
&& m_path[m_path.size()-1] == ':' ) // "device:"
# endif
;
}
bool path::has_root_name() const
{
# ifdef BOOST_WINDOWS
return m_path.size() > 1
&& ( m_path[1] == ':' // "c:"
|| m_path[m_path.size()-1] == ':' // "prn:"
|| (m_path[0] == '/' && m_path[1] == '/') // "//share"
);
# else
return false;
# endif
}
bool path::has_root_directory() const
{
return ( m_path.size()
&& m_path[0] == '/' ) // covers both "/" and "//share"
# ifdef BOOST_WINDOWS
|| ( m_path.size() > 2
&& m_path[1] == ':' && m_path[2] == '/' ) // "c:/"
# endif
;
}
bool path::has_relative_path() const { return !relative_path().empty(); }
bool path::has_branch_path() const { return !branch_path().empty(); }
// default name_check mechanism ----------------------------------------//
bool path::default_name_check_writable()
{
return safe_to_write_check;
}
void path::default_name_check( name_check new_check )
{
assert( new_check );
if ( !safe_to_write_check )
boost::throw_exception(
filesystem_error( "boost::filesystem::default_name_check",
"default name check already set" ));
default_check = new_check;
safe_to_write_check = false;
}
path::name_check path::default_name_check()
{
safe_to_write_check = false;
return default_check;
}
// path operator< ------------------------------------------------------//
bool path::operator<( const path & that ) const
{
return std::lexicographical_compare(
begin(), end(), that.begin(), that.end() );
}
// path::iterator implementation --------------------------------------------//
void path::iterator::increment()
{
assert( m_pos < m_path_ptr->m_path.size() ); // detect increment past end
m_pos += m_name.size();
if ( m_pos == m_path_ptr->m_path.size() )
{
m_name = ""; // not strictly required, but might aid debugging
return;
}
if ( m_path_ptr->m_path[m_pos] == '/' )
{
# ifdef BOOST_WINDOWS
if ( m_name[m_name.size()-1] == ':' // drive or device
|| (m_name[0] == '/' && m_name[1] == '/') ) // share
{
m_name = "/";
return;
}
# endif
++m_pos;
}
std::string::size_type end_pos( m_path_ptr->m_path.find( '/', m_pos ) );
if ( end_pos == std::string::npos )
end_pos = m_path_ptr->m_path.size();
m_name = m_path_ptr->m_path.substr( m_pos, end_pos - m_pos );
}
void path::iterator::decrement()
{
assert( m_pos ); // detect decrement of begin
std::string::size_type end_pos( m_pos );
// skip a '/' unless it is a root directory
if ( m_path_ptr->m_path[end_pos-1] == '/'
&& !detail::is_absolute_root( m_path_ptr->m_path, end_pos ) ) --end_pos;
m_pos = leaf_pos( m_path_ptr->m_path, end_pos );
m_name = m_path_ptr->m_path.substr( m_pos, end_pos - m_pos );
}
} // namespace filesystem
} // namespace boost
| [
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
] | [
[
[
1,
692
]
]
] |
29ca9b887b17c4bf481de676add85d06e768664d | 9c62af23e0a1faea5aaa8dd328ba1d82688823a5 | /rl/trunk/engine/core/src/TimeSource.cpp | 7f0508a771b0303a68c03e6e2f282c9637c0c096 | [
"ClArtistic",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | jacmoe/dsa-hl-svn | 55b05b6f28b0b8b216eac7b0f9eedf650d116f85 | 97798e1f54df9d5785fb206c7165cd011c611560 | refs/heads/master | 2021-04-22T12:07:43.389214 | 2009-11-27T22:01:03 | 2009-11-27T22:01:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,689 | cpp | /* This source file is part of Rastullahs Lockenpracht.
* Copyright (C) 2003-2008 Team Pantheon. http://www.team-pantheon.de
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the Clarified Artistic License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Clarified Artistic License for more details.
*
* You should have received a copy of the Clarified Artistic License
* along with this program; if not you can get it here
* http://www.jpaulmorrison.com/fbp/artistic2.htm.
*/
#include "stdinc.h" //precompiled header
#include "TimeSource.h"
#include "GameLoop.h"
#include "SaveGameManager.h"
template<> rl::TimeSourceManager* Ogre::Singleton<rl::TimeSourceManager>::ms_Singleton = 0;
namespace rl
{
TimeSource::TimeSource(bool interruptable)
: GameTask(interruptable)
{
GameLoop::getSingleton().addTask(this, GameLoop::TG_LOGIC);
}
TimeSource::~TimeSource()
{
GameLoop::getSingleton().removeTask(this);
}
RealTimeContinuous::RealTimeContinuous()
: TimeSource(false),
mTime(0.0)
{
}
TimeSource::TimeSourceType RealTimeContinuous::getType() const
{
return TimeSource::REALTIME_CONTINUOUS;
}
Time RealTimeContinuous::getClock() const
{
return mTime;
}
void RealTimeContinuous::setClock(const Time& time)
{
mTime = time;
}
void RealTimeContinuous::setTimeFactor(Ogre::Real factor)
{
// can't be accelerated or slowed down
}
void RealTimeContinuous::run(Ogre::Real elapsedTime)
{
mTime += elapsedTime * 1000;
}
const Ogre::String& RealTimeContinuous::getName() const
{
static Ogre::String NAME = "Continuous real time clock";
return NAME;
}
RealTimeInterruptable::RealTimeInterruptable()
: TimeSource(true),
mTimeFactor(1.0),
mTime(0.0)
{
}
RealTimeInterruptable::~RealTimeInterruptable()
{
}
TimeSource::TimeSourceType RealTimeInterruptable::getType() const
{
return TimeSource::REALTIME_INTERRUPTABLE;
}
Time RealTimeInterruptable::getClock() const
{
return mTime;
}
void RealTimeInterruptable::setClock(const Time& time)
{
mTime = time;
}
void RealTimeInterruptable::setTimeFactor(Ogre::Real factor)
{
mTimeFactor = factor;
}
void RealTimeInterruptable::run(Ogre::Real elapsedTime)
{
if (!isPaused())
{
mTime += mTimeFactor * elapsedTime * 1000;
}
}
const Ogre::String& RealTimeInterruptable::getName() const
{
static Ogre::String NAME = "Pausable real time clock";
return NAME;
}
TimeSourceManager::TimeSourceManager()
{
SaveGameManager::getSingleton().registerSaveGameData(this);
}
TimeSourceManager::~TimeSourceManager()
{
SaveGameManager::getSingleton().unregisterSaveGameData(this);
// delete TimeSources
TimeSourceMap::iterator it = mTimeSources.begin();
for( ; it != mTimeSources.end(); it++)
if( it->second != NULL )
delete it->second;
}
void TimeSourceManager::registerTimeSource(TimeSource* ts)
{
TimeSourceMap::iterator it = mTimeSources.find(ts->getType());
if( it != mTimeSources.end() )
delete it->second;
mTimeSources[ts->getType()] = ts;
}
TimeSource* TimeSourceManager::getTimeSource(
const TimeSource::TimeSourceType& type) const
{
std::map<TimeSource::TimeSourceType, TimeSource*>::const_iterator it
= mTimeSources.find(type);
if (it == mTimeSources.end())
{
return NULL;
}
return it->second;
}
void TimeSourceManager::setTimeFactor(const Ogre::Real& factor)
{
for (std::map<TimeSource::TimeSourceType, TimeSource*>::iterator it
= mTimeSources.begin(); it != mTimeSources.end(); ++it)
{
it->second->setTimeFactor(factor);
}
}
void TimeSourceManager::setPaused(bool paused)
{
for (std::map<TimeSource::TimeSourceType, TimeSource*>::iterator it
= mTimeSources.begin(); it != mTimeSources.end(); ++it)
{
it->second->setPaused(paused);
}
}
CeGuiString TimeSourceManager::getXmlNodeIdentifier() const
{
return "time_sources";
}
void TimeSourceManager::writeData(SaveGameFileWriter* writer)
{
TiXmlElement* timesources = writer->appendChildElement(
writer->getDocument(), getXmlNodeIdentifier().c_str());
for (std::map<TimeSource::TimeSourceType, TimeSource*>::const_iterator it_time_sources = mTimeSources.begin();
it_time_sources != mTimeSources.end(); it_time_sources++)
{
TiXmlElement* timesource = writer->appendChildElement(timesources, "time_source");
writer->setAttributeValueAsInteger(timesource, "ID", it_time_sources->first);
Property time((int)it_time_sources->second->getClock());
PropertyMap map;
map["time"] = time;
writer->writeEachPropertyToElem(timesource, map);
}
}
void TimeSourceManager::readData(SaveGameFileReader* reader)
{
XmlElementList rootNodeList = reader->getElementsByTagName(reader->getDocument()->RootElement(), getXmlNodeIdentifier().c_str());
if (!rootNodeList.empty())
{
XmlElementList xmlTimeSources = reader->getElementsByTagName(rootNodeList[0], "gameobject"); //there should be only one "gameobjects" node
for (XmlElementList::iterator it = xmlTimeSources.begin(); it != xmlTimeSources.end(); ++it)
{
const TiXmlElement* xmlTimeSource = *it;
TimeSource::TimeSourceType ID = (TimeSource::TimeSourceType)reader->getAttributeValueAsInteger(
xmlTimeSource, "ID");
PropertyRecordPtr properties = reader->getPropertiesAsRecord(xmlTimeSource);
std::map<TimeSource::TimeSourceType, TimeSource*>::const_iterator it_time_sources = mTimeSources.find(ID);
if (it_time_sources != mTimeSources.end())
{
it_time_sources->second->setClock(properties->toPropertyMap()["time"].toInt());
}
}
}
}
int TimeSourceManager::getPriority() const
{
return 10000;
}
}
| [
"blakharaz@4c79e8ff-cfd4-0310-af45-a38c79f83013",
"timm@4c79e8ff-cfd4-0310-af45-a38c79f83013",
"melven@4c79e8ff-cfd4-0310-af45-a38c79f83013"
] | [
[
[
1,
123
],
[
125,
126
],
[
138,
139
],
[
143,
167
],
[
169,
177
],
[
185,
186
],
[
188,
188
],
[
191,
191
],
[
203,
203
],
[
205,
205
],
[
207,
216
],
[
218,
218
],
[
228,
228
]
],
[
[
124,
124
],
[
137,
137
],
[
168,
168
],
[
178,
184
],
[
187,
187
],
[
189,
190
],
[
192,
202
],
[
204,
204
],
[
206,
206
],
[
217,
217
],
[
219,
227
]
],
[
[
127,
136
],
[
140,
142
]
]
] |
043c991b6b06c58ea9f90c626dd622e8609606ec | 51c035f61d4412c90fc44a0fb5b43cbd0f17761f | /NetworkController.h | f76b0c6dfd91d1cda164229f41ae5560a0a06e57 | [] | no_license | OldSchoolTeam/GalconGameServer | a62b85d6493d25f34ba90906232cabbc218f27d7 | 78413dcd04fc3f2fe563f31a88414a4069f87484 | refs/heads/master | 2021-01-23T02:58:51.938016 | 2011-06-15T11:22:23 | 2011-06-15T11:22:23 | 1,832,012 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,316 | h | #ifndef CNETWORKCONTROLLER_H
#define CNETWORKCONTROLLER_H
#include <QObject>
#include <QTimer>
#include "Player.h"
#include "Socket.h"
#include "Parser.h"
#include "Game.h"
#include "FinishMsg.h"
#include "StepMsg.h"
class CNetworkController : public QObject
{
Q_OBJECT
public:
CNetworkController(int i_timeToStart,
int i_maxNumPlayer,
int i_timeOut,
QObject *parent = 0);
~CNetworkController();
bool AddConnection(int);
public slots:
void SlotReadMsg();
void SlotDeleteConnection();
void SlotSendConnId(CConnMsg* );
void SlotSendFinish(CFinishMsg*);
void SlotSendStart(CStartMsg*);
void SlotSendState();
void SlotSendTimeToStart();
void SlotStep(CStepMsg *);
private:
void sentToAll(QString );
CGame* m_gameGalcon;
CParser* m_parser;
QTimer *m_timer;
QTimer *m_stepTimer;
QTime m_lastStepTime;
QList<CPlayer*> m_playerList;
QList<CSocket*> m_socketList;
QList<int> m_freeIdList;
// true - game started
bool gameIsStarted;
int m_timeToStart; // etalon time
int timeToStart; // var time
int m_timeOut;
signals:
void sentQuit();
};
#endif // CNETWORKCONTROLLER_H
| [
"artem@artem-R480.(none)"
] | [
[
[
1,
61
]
]
] |
771e73706cbb360d2c42478741563bfd36c16477 | 3ec3b97044e4e6a87125470cfa7eef535f26e376 | /darkbits-secret_of_fantasy_2/src/PlayerCharacter.cpp | 28974d3480f01ba1990872f4fe9ae2fe3a0b7e81 | [] | no_license | strategist922/TINS-Is-not-speedhack-2010 | 6d7a43ebb9ab3b24208b3a22cbcbb7452dae48af | 718b9d037606f0dbd9eb6c0b0e021eeb38c011f9 | refs/heads/master | 2021-01-18T14:14:38.724957 | 2010-10-17T14:04:40 | 2010-10-17T14:04:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,317 | cpp | #include "Precompiled.hpp"
#include "PlayerCharacter.hpp"
#include "ActionTrigger.hpp"
PlayerCharacter::PlayerCharacter(const std::string &name,int homeX, int homeY, int level, int hp, int mp, float speed )
: Character(Faction_Player, name, homeX, homeY, level, hp, mp, speed)
, myFighting(true)
, myAttackAnimation("data/images/characters/" + name + "/attack.bmp")
, myIdleAnimation("data/images/characters/" + name + "/idle.bmp")
, myWalkAnimation("data/images/characters/" + name + "/walk.bmp")
, myCastAnimation("data/images/characters/" + name + "/cast.bmp")
, myDamageAnimation("data/images/characters/" + name + "/damage.bmp")
, myDeadAnimation("data/images/characters/" + name + "/dead.bmp")
, myChannelAnimation("data/images/characters/" + name + "/channel.bmp")
, myState(State_Idle)
{
setHeight(32);
}
bool PlayerCharacter::isFighting()
{
return myFighting;
}
void PlayerCharacter::setFighting( bool fighting )
{
myFighting = fighting;
}
void PlayerCharacter::onRender( BITMAP *dest )
{
int x = getX() - 16;
int y = getY() - 32;
if (myState == State_Idle)
{
myIdleAnimation.drawFrame(dest, 0, x, y);
}
if (myState == State_EnterIdle)
{
myWalkAnimation.drawFrame(dest, myFrameCounter / 4,x, y);
}
if (myState == State_EnterAttack)
{
myIdleAnimation.drawFrame(dest, 0, x, y);
}
if (myState == State_DoAttack)
{
myAttackAnimation.drawFrame(dest, 0, x, y);
}
if (myState == State_Attack)
{
myAttackAnimation.drawFrame(dest, 0, x, y);
}
if (myState == State_EnterCast)
{
myWalkAnimation.drawFrame(dest, myFrameCounter / 4, x, y);
}
if (myState == State_EnterHide)
{
myWalkAnimation.drawFrame(dest, myFrameCounter / 4, x, y, true);
}
if (myState == State_PrepareCast)
{
myChannelAnimation.drawFrame(dest, myFrameCounter / 10, x, y);
}
if (myState == State_Cast)
{
myCastAnimation.drawFrame(dest, 0, x, y);
}
if (myState == State_Damage)
{
Blending b = Blending_None;
if (myTime < 6)
{
b = Blending_Lighten;
}
myDamageAnimation.drawFrame(dest, 0, x, y, false, false, b);
}
if (myState == State_Dead)
{
myDeadAnimation.drawFrame(dest, 0, x, y, false, false);
}
//circle(dest, getX(), getY(), 5, makecol(255, 255, 255));
}
void PlayerCharacter::enterIdleState()
{
myState = State_EnterIdle;
}
bool PlayerCharacter::isIdleStateEntered()
{
return myState == State_Idle;
}
void PlayerCharacter::enterPrepareCastState()
{
myState = State_PrepareCast;
}
void PlayerCharacter::onLogic()
{
Character::onLogic();
myFrameCounter++;
if (myState == State_EnterCast)
{
myX-=2;
if (myHomeX - 40 >= myX)
{
myX = myHomeX - 40;
myState = State_Cast;
}
}
if (myState == State_EnterIdle)
{
if (myX == myHomeX)
myState = State_Idle;
else if (myX < myHomeX)
{
myX+=2;
if (myX >= myHomeX)
myX = myHomeX;
}
else if (myX > myHomeX)
{
myX-=2;
if (myX <= myHomeX)
myX = myHomeX;
}
}
if (myState == State_EnterAttack)
{
myX -= 10;
myState = State_DoAttack;
}
if (myState == State_DoAttack)
{
myTime++;
if (myTime > 30)
myState = State_Attack;
}
if (myState == State_Damage)
{
myTime++;
if (myTime > 20)
{
myState = State_Idle;
}
}
if (myState == State_EnterHide)
{
myX++;
if (myX > (340 + 16 + 1))
{
myState = State_Hide;
}
}
}
bool PlayerCharacter::isPrepareCastStateEntered()
{
return myState == State_PrepareCast;
}
void PlayerCharacter::enterCastState()
{
myState = State_EnterCast;
}
bool PlayerCharacter::isCastStateEntered()
{
return myState == State_Cast;
}
bool PlayerCharacter::isAttackStateEntered()
{
return myState == State_Attack;
}
void PlayerCharacter::enterAttackState()
{
myState = State_EnterAttack;
myTime = 0;
}
void PlayerCharacter::enterDamageState()
{
myState = State_Damage;
myTime = 0;
}
void PlayerCharacter::enterHideState()
{
myState = State_EnterHide;
}
bool PlayerCharacter::isHideStateEntered()
{
return myState == State_Hide;
}
bool PlayerCharacter::isDead()
{
return myState == State_Dead;
}
void PlayerCharacter::enterDeadState()
{
myState = State_Dead;
}
| [
"[email protected]"
] | [
[
[
1,
220
]
]
] |
087133c33a42429da2278d8c6434bf5f9a02977e | 52dd8bdffaa5d7e450477b7f3955dbe0d26b7473 | /list-operation/merge-linear-list-test.cpp | 9b36ab4f1f13484e3b855e97667cb1dc04e04e23 | [] | no_license | xhbang/algorithms | 7475a4f3ed1a6877a0950eb3534edaeb2a6921a1 | 226229bc77e2926246617aa4a9db308096183a8c | refs/heads/master | 2021-01-25T04:57:53.425634 | 2011-12-05T09:57:09 | 2011-12-05T09:57:09 | 2,352,910 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,663 | cpp | //******************************************************************************************************************************
//
// 合并有序线性表
//
// 张明烁编写于2008年6月7日
// 谢行2009年来此一游,张明烁我觉得你写的很麻烦,所以我给你改了
//
//******************************************************************************************************************************
#include <stdio.h>
#define lla 5//宏定义lla为la数组的大小为5.
#define llb 8//宏定义llb为lb数组的大小为8.
#define llc lla+llb//宏定义llc为lc数组的大小为la数组和lb数组大小之和.
int main()
{
//定义并初始化两个数组la,lb。
int la[lla]={3,5,8,11,13};
int lb[llb]={2,6,8,9,11,15,20,26};
int lc[llc];//定义一个数组lc,用于存放la、lb合并后的新数组。
int *pa=la,*pb=lb,*pc=lc,*p=NULL;
while(pa<la+lla && pb<lb+llb)//la,lb均有数字的时候的情况。
{
if(*pa>*pb)
*pc++=*pb++;
else if(*pa<*pb)
*pc++=*pa++;
else{ //(*pa==*pb),如果la、lb中的元素相等,则保留一个相等的值在lc中。
*pc++=*pa++;
pb++;
}
}
while(pb<lb+llb)
*pc++=*pb++;
while(pa<la+lla)
*pc++=*pa++;
printf("需要合并的两组线性表分别为:\n");
for(p=la;p<pa;p++)//输出la中的数据。
printf("%6d",*p);
printf("\n\n");
for(p=lb;p<pb;p++)//输出lb中的数据。
printf("%6d",*p);
printf("\n\n");
printf("将两组线性表合并后的线性表为:\n");
for(p=lc;p<pc;p++)//输出lc中的数据。
printf("%6d",*p);
printf("\n\n");
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
57
]
]
] |
9c2322bd924b1b072de0bb82b412e9c532b8788d | c5ecda551cefa7aaa54b787850b55a2d8fd12387 | /src/UILayer/DlgMaintabDownload.h | 5cb9f0f5fbcfcecec9b612c17f51dda03375fd6d | [] | no_license | firespeed79/easymule | b2520bfc44977c4e0643064bbc7211c0ce30cf66 | 3f890fa7ed2526c782cfcfabb5aac08c1e70e033 | refs/heads/master | 2021-05-28T20:52:15.983758 | 2007-12-05T09:41:56 | 2007-12-05T09:41:56 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,856 | h | #pragma once
// CDlgMaintabDownload 对话框
#include "resource.h"
#include "DownloadTabCtrl.h"
#include "SplitterControlEx.h"
#include "DownloadedListCtrl.h"
#include "WebBrowserWnd.h"
#include "DetailInfo.h"
#include "Localizee.h"
#include "ResizableLib\ResizableDialog.h"
#include "TabWnd_Cake.h"
#include "PeerLog.h"
#include "UILayer/UpLoading.h"
class CDlgMaintabDownload : public CResizableDialog, public CLocalizee
{
DECLARE_DYNAMIC(CDlgMaintabDownload)
LOCALIZEE_WND_CANLOCALIZE()
public:
CDlgMaintabDownload(CWnd* pParent = NULL); // 标准构造函数
virtual ~CDlgMaintabDownload();
// 对话框数据
enum { IDD = IDD_MAINTAB_DOWNLOAD };
public:
enum ETabId
{
TI_DOWNLOADING,
TI_DOWNLOADED,
TI_DETAIL,
TI_REMARK,
TI_PEERLOG,
TI_UPLOADING,
TI_MAX,
};
void SetDownloadlistActiveTab(ETabId eTabId){m_DownloadTabWnd.SetActiveTab(m_aposTabs[eTabId]);}
BOOL IsLogTabActived(){return m_aposTabs[TI_PEERLOG] == m_tabwndInfo.GetActiveTab();}
BOOL IsRemarkTabActived(){return m_aposTabs[TI_REMARK] == m_tabwndInfo.GetActiveTab();}
BOOL IsDownloadingActived(){return m_aposTabs[TI_DOWNLOADING] == m_DownloadTabWnd.GetActiveTab();}
CKnownFile* GetCurrentSelectedFile( CFileTaskItem* &pFileTask );
public:
CDownloadTabWnd m_DownloadTabWnd;
CPeerLog m_dlgPeerLog;
CDownloadedListCtrl m_lcDownloaded;
CDetailInfo m_dlgDetailInfo;
CUpLoading m_dlgUpLoading;
protected:
void InitTabs(void);
CTabWnd_Cake m_tabwndInfo;
CHtmlCtrl * m_pwebUserComment;
POSITION m_aposTabs[TI_MAX];
UINT pos;
CListCtrl* m_plcDownloading;
CSplitterControlEx m_wndSplitter;
uint32 m_dwShowListIDC;
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
DECLARE_MESSAGE_MAP()
public:
virtual BOOL OnInitDialog();
virtual BOOL PreTranslateMessage(MSG* pMsg);
void RefreshLowerPannel(CKnownFile * file);
void RefreshLowerPannel(CFileTaskItem * pFileTask);
protected:
void DoResize(int delta);
virtual LRESULT DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam);
afx_msg void OnSplitterMoved(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnSplitterClicked(NMHDR* pNMHDR, LRESULT* pResult);
public:
afx_msg void OnDestroy();
afx_msg LRESULT OnCurSelFile(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnCurSelFileTask(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnCurSelPeer(WPARAM wParam, LPARAM lParam);
afx_msg void OnNM_TabInfo_ActiveTabChanged(NMHDR* pNMHDR, LRESULT *pResult);
afx_msg void OnNM_TabList_ActiveTabChanged(NMHDR* pNMHDR, LRESULT *pResult);
void Localize(void);
void ShowList(int nflag);
protected:
POSITION m_posPeerLog;
POSITION m_posInfo;
POSITION m_posUploading;
public:
void UpdateSplitterRange(void);
};
| [
"LanceFong@4a627187-453b-0410-a94d-992500ef832d"
] | [
[
[
1,
99
]
]
] |
8297718c5613e151b2d3e8be0fc4dc65254b1a3a | 6a98ab1a4800e6f169b75c17e01c2fa491989a79 | /Crosshair.h | eebf6ae547837c4a9e792df8dab6b7fc281e923b | [] | no_license | OpenEngineDK/branches-Prototype | 966eccfb9ddb0e4a3a68f8fb6a1c1a0d0314dd5c | 1364da5ca25a6eb00c829a63db8e083b2e03cc8b | refs/heads/master | 2021-01-01T05:18:26.599471 | 2008-08-13T09:52:42 | 2008-08-13T09:52:42 | 58,077,163 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,238 | h | // Rigid body rendering.
// -------------------------------------------------------------------
// Copyright (C) 2007 (See AUTHORS)
//
// This program is free software; It is covered by the GNU General
// Public License version 2 or any later version.
// See the GNU General Public License for more details (see LICENSE).
//--------------------------------------------------------------------
#ifndef _CROSSHAIR_H_
#define _CROSSHAIR_H_
#include <Renderers/IRenderNode.h>
#include <Renderers/IRenderingView.h>
#include <Scene/ISceneNode.h>
#include <Meta/OpenGL.h>
// forward declarations
namespace OpenEngine {
//namespace Geometry { class Box; }
namespace Scene { class TransformationNode; }
namespace Renderers { class IRenderNode; }
}
using namespace OpenEngine::Math;
using namespace OpenEngine::Geometry;
using namespace OpenEngine::Scene;
using namespace OpenEngine::Renderers;
namespace OpenEngine {
namespace Utils {
class Crosshair : public IRenderNode {
public:
Crosshair();
virtual ~Crosshair();
void Apply(IRenderingView* view);
};
} // NS Utils
} // NS OpenEngine
#endif // _DEFAULT_RIGID_BODY_RENDER_NODE_H_
| [
"[email protected]"
] | [
[
[
1,
45
]
]
] |
d80115e07d079ee8d9a155f45779648c7af6cfe9 | 11916febd7cf1bf31f029791171ed60ad8bbefcb | /routing_engine.cpp | 5e252c5a2dcc8059de10e2aba0447c938ce236df | [] | no_license | guopengwei/worm_sim | 18d8b321744ed32c2ab4ca38f89723c835ef40de | 260a7288fca3731fd082684ea3ca2ba243c951a2 | refs/heads/master | 2021-01-25T08:55:28.133828 | 2011-01-19T02:10:01 | 2011-01-19T02:10:01 | 1,269,438 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 21,423 | cpp | /************************************************************************
Author: Jingcao Hu ([email protected])
File name: routing_engine.cpp
Date Created: <Mon Oct 13 11:48:06 2003>
Last Modified: <Wed Jan 19 15:49:42 2005>
Description: Implementation of the routing engine class. Currently it does not
pipeline the routing decision.
************************************************************************/
#include "routing_engine.hpp"
#include "misc.hpp"
#include "global_val.hpp"
#include "msg.hpp"
#include "pkt.hpp"
#include "router.hpp"
#include "arbiter.hpp"
#include <iostream>
#include <cstring>
Routing_engine::Routing_engine(Position p) {
pos = p;
routing_scheme = param.routing_scheme;
routing_table = vector<unsigned int>();//UYO
delay_xy = param.routing_engine_delay_xy;
delay_oe = param.routing_engine_delay_oe;
timer.set_delay(delay_xy);
}
Routing_engine::~Routing_engine() {
}
void Routing_engine::set_routing_scheme(Routing_scheme rs) {
assert (rs != invalid_scheme);
routing_scheme = rs;
}
void Routing_engine::set_routing_table(char * table_string) { // UYO
//cout <<"At location " << this->pos.x <<", " <<this->pos.y <<":\n";
//cout <<"u*** \n";
for (unsigned int i=0; i<strlen(table_string); i+=2){
unsigned int ali;
sscanf(&table_string[i],"%d",&ali);
routing_table.push_back(ali);
//cout <<table_string[i] <<" string \n "; cout <<ali << " int \n";
// cout << routing_table.back() <<" ";
}
// cout <<"\n***u\n";
}
void Routing_engine::bind_channel(class Input_channel * chan) {
channel = chan;
}
// Based on it's local and neighbor information, this routine decides which routing
// mode is the best for use at this time.
// The way we calculate it:
// If any of the 3 surrounding router's corresponding channels' inputs are higher than
// a certain ratio, then use oe_fixed routing; otherwise, use oe
Routing_scheme Routing_engine::decide_best_routing_mode(void) const {
pRouter router = channel->get_router();
for (unsigned int i=0; i<param.n_of_ports; i++) {
Direction dir = (Direction) i;
if (dir == local)
continue;
Position channel_pos = channel->get_position();
if (dir == ((Direction) channel_pos.x)) // no need to check backward router
continue;
pRouter neighbor_router = router->get_router(dir);
if (neighbor_router) {
pIn_port neighbor_in_port = neighbor_router->get_in_port(reverse(dir));
unsigned int empty_slots = neighbor_in_port->num_of_empty_buffer_slots();
unsigned int capacity = neighbor_in_port->total_buffer_capacity();
if (((double) empty_slots)/capacity <= param.switch_mode_threshold)
return oe;
}
}
return oe_fixed;
}
// when a new head flit arrives, it will trigger this function to
// decide for the output channel. after delay by "delay" cycle, the
// routing engine will make the decision and inform the switching
// fabric about which output channel it wants to connect to
void Routing_engine::get_request(class Flit* flit) {
if (!flit->is_header()) {
cerr << ERRO_NOT_HEADER_FLIT;
return;
}
Position src_pos = flit->get_src_position();
Position dst_pos = flit->get_dst_position();
if (param.extreme_verbose)
cout << "[I] Routing engine received a request "
<< " (time = " << net_clock.get_clock() << ")\n";
dir = decide_direction(src_pos, dst_pos);
timer.set_delay(get_delay());
// by calling this, its timer_fired member function will be called after "delay"
// clock cycles.
timer.initialize();
}
// decide the routing direction Daniel
Direction
Routing_engine::decide_direction(class Flit** flit, const Position & src_pos, const Position & dst_pos) const {
Routing_scheme current_routing_scheme = routing_scheme;
int ali;
pRouter curr_router = channel->get_router(); // current router
pIn_port neighbor_port = 0;
unsigned int empty_slots = 1;
unsigned int capacity = 1;
if (routing_scheme == dyad)
current_routing_scheme = decide_best_routing_mode();
Direction dir = invalid_dir;
switch(current_routing_scheme) {
case xy:
dir = decide_direction_xy(src_pos, dst_pos);
break;
case oe:
dir = decide_direction_oe(src_pos, dst_pos);
break;
case oe_fixed:
dir = decide_direction_oe_fixed(src_pos, dst_pos);
break;
case predict:
dir = decide_direction_predict(src_pos, dst_pos);
break;
case rtable: // UYO
ali = (unsigned int) routing_table[dst_pos.y+param.n_of_cols*dst_pos.x];
dir = (Direction) ali;
/* for (i=0; i<param.n_of_rows*param.n_of_cols; i++)
cout <<routing_table[i] <<"$ ";
cout << endl;
if (dir != decide_direction_xy(src_pos, dst_pos))
cout <<" ALARM! \n";
cout << dst_pos.x <<" " <<dst_pos.y<< " " <<dst_pos.x+param.n_of_cols*dst_pos.y <<" " <<"\n";
cout << this->pos.x <<" " <<this->pos.y << " " <<this->pos.x+param.n_of_cols*this->pos.y << "\n";
cout << this->routing_table[dst_pos.x*param.n_of_cols+dst_pos.y] <<" why\n";
cout << dir <<", " <<ali << " is direction \n"; */
if (param.adaptive_LR1 && dir == 5) {
neighbor_port = curr_router->get_sink();
empty_slots = neighbor_port->num_of_empty_buffer_slots();
capacity = 2*neighbor_port->total_buffer_capacity();
//printf("empty: %u, capacity %u \n",empty_slots, capacity);
if (((double) empty_slots)/capacity < 0.49) {
// dir = decide_direction_xy(src_pos, dst_pos); // use XY due to congestion
// cout <<"*\n";
}
} // if ( dir == 5) */
// annotate power
if (net_clock.get_clock() > param.warmup_period) {
// ebit energy models
param.energy.re_energy += param.fixed_routing_engine_epacket;
}
break;
default:
assert(0);
dir = invalid_dir;
} //switch
return dir;
}
Direction
Routing_engine::decide_direction(const Position & src_pos, const Position & dst_pos) const {
Routing_scheme current_routing_scheme = routing_scheme;
int ali;
pRouter curr_router = channel->get_router(); // current router
pIn_port neighbor_port = 0;
unsigned int empty_slots = 1;
unsigned int capacity = 1;
if (routing_scheme == dyad)
current_routing_scheme = decide_best_routing_mode();
Direction dir = invalid_dir;
switch(current_routing_scheme) {
case xy:
dir = decide_direction_xy(src_pos, dst_pos);
break;
case oe:
dir = decide_direction_oe(src_pos, dst_pos);
break;
case oe_fixed:
dir = decide_direction_oe_fixed(src_pos, dst_pos);
break;
case test:
dir = decide_direction_test(src_pos, dst_pos);
break;
case predict:
dir = decide_direction_predict(src_pos, dst_pos);
break;
case rtable: // UYO
ali = (unsigned int) routing_table[dst_pos.y+param.n_of_cols*dst_pos.x];
dir = (Direction) ali;
/* for (i=0; i<param.n_of_rows*param.n_of_cols; i++)
cout <<routing_table[i] <<"$ ";
cout << endl;
if (dir != decide_direction_xy(src_pos, dst_pos))
cout <<" ALARM! \n";
cout << dst_pos.x <<" " <<dst_pos.y<< " " <<dst_pos.x+param.n_of_cols*dst_pos.y <<" " <<"\n";
cout << this->pos.x <<" " <<this->pos.y << " " <<this->pos.x+param.n_of_cols*this->pos.y << "\n";
cout << this->routing_table[dst_pos.x*param.n_of_cols+dst_pos.y] <<" why\n";
cout << dir <<", " <<ali << " is direction \n"; */
if (param.adaptive_LR1 && dir == 5) {
neighbor_port = curr_router->get_sink();
empty_slots = neighbor_port->num_of_empty_buffer_slots();
capacity = 2*neighbor_port->total_buffer_capacity();
//printf("empty: %u, capacity %u \n",empty_slots, capacity);
if (((double) empty_slots)/capacity < 0.49) {
// dir = decide_direction_xy(src_pos, dst_pos); // use XY due to congestion
// cout <<"*\n";
}
} // if ( dir == 5) */
// annotate power
if (net_clock.get_clock() > param.warmup_period) {
// ebit energy models
param.energy.re_energy += param.fixed_routing_engine_epacket;
}
break;
default:
assert(0);
dir = invalid_dir;
} //switch
return dir;
}
// decide the routing direction under XY routing scheme
Direction
Routing_engine::decide_direction_xy(const Position & src_pos, const Position & dst_pos) const {
// annotate power
if (net_clock.get_clock() > param.warmup_period) {
// ebit energy models
param.energy.re_energy += param.fixed_routing_engine_epacket;
}
Direction d;
if (dst_pos.x > pos.x)
d = east;
else if (dst_pos.x < pos.x)
d = west;
else if (dst_pos.y > pos.y)
d = north;
else if (dst_pos.y < pos.y)
d = south;
else
d = local;
return d;
}
//daniel test
Direction
Routing_engine::decide_direction_test(const Position & src_pos, const Position & dst_pos) const {
vector<Direction> dirs;
dirs.clear();
// annotate power
if (net_clock.get_clock() > param.warmup_period) {
// ebit energy models
param.energy.re_energy += param.oe_routing_engine_epacket;
}
int e0 = dst_pos.x - pos.x;
int e1 = dst_pos.y - pos.y;
if (e0 == 0 && e1 == 0)
dirs.push_back(local);
else {
if (e0 == 0) { // currently in the same column as destination
if (e1 > 0)
dirs.push_back(north);
else
dirs.push_back(south);
}
else {
if (e0 > 0) { // east bound messages
if (e1 == 0)
dirs.push_back(east);
else {
if (pos.x%2 == 1 || pos.x == src_pos.x) {
if (e1 > 0)
dirs.push_back(north);
else
dirs.push_back(south);
}
if (dst_pos.x%2 == 1 || e0 != 1) // odd destinatio column or >=2 columns of destination
dirs.push_back(east);
}
}
else { // west bound messges
dirs.push_back(west);
if (pos.x%2 == 0) {
if (e1 > 0)
dirs.push_back(north);
else if (e1 < 0)
dirs.push_back(south);
}
}
}
}
// now select a direction from dirs vector
assert(!dirs.empty());
if (dirs.size() == 1)
return dirs[0];
pRouter router = channel->get_router();
Direction choice = invalid_dir;
int maxscore=-2000;
//calculate the score
for (unsigned int i=0; i<dirs.size(); i++) {
Direction d = dirs[i];
pRouter neighbor_router = router->get_router(d);
assert(neighbor_router);
int candidaterequest_queue=0;
int candidateempty_slot=0;
int candidatereneighbour_quest_queue0=0;
int candidatereneighbour_quest_queue1=0;
int score=0;
//associate numbers
int a=4,b=2,c=1,e=1;
//calculate request_queue size
candidaterequest_queue=(router->get_arbiter())->get_requestsize(d);
//calculate empty slots
pIn_port neighbor_in_port = neighbor_router->get_in_port(reverse(d));
candidateempty_slot= neighbor_in_port->num_of_empty_buffer_slots();
candidatereneighbour_quest_queue0=(neighbor_router->get_arbiter())->get_requestsize(dirs[0]);
candidatereneighbour_quest_queue1=(neighbor_router->get_arbiter())->get_requestsize(dirs[1]);
//put together
score=b*candidateempty_slot-c*candidatereneighbour_quest_queue0-a*candidaterequest_queue-e*candidatereneighbour_quest_queue1;
if (score >= maxscore) {
maxscore = score;
choice = d;
}
}
assert(choice != invalid_dir);
return choice;
}
// Decide the routing direction under Odd-Even routing scheme.
// We use a simple decision method here. We first get the two possible directions if
// they exists, then choose the next hop whose input channel buffer has more empty space
// left.
Direction
Routing_engine::decide_direction_oe(const Position & src_pos, const Position & dst_pos) const {
vector<Direction> dirs;
dirs.clear();
// annotate power
if (net_clock.get_clock() > param.warmup_period) {
// ebit energy models
param.energy.re_energy += param.oe_routing_engine_epacket;
}
int e0 = dst_pos.x - pos.x;
int e1 = dst_pos.y - pos.y;
if (e0 == 0 && e1 == 0)
dirs.push_back(local);
else {
if (e0 == 0) { // currently in the same column as destination
if (e1 > 0)
dirs.push_back(north);
else
dirs.push_back(south);
}
else {
if (e0 > 0) { // east bound messages
if (e1 == 0)
dirs.push_back(east);
else {
if (pos.x%2 == 1 || pos.x == src_pos.x) {
if (e1 > 0)
dirs.push_back(north);
else
dirs.push_back(south);
}
if (dst_pos.x%2 == 1 || e0 != 1) // odd destinatio column or >=2 columns of destination
dirs.push_back(east);
}
}
else { // west bound messges
dirs.push_back(west);
if (pos.x%2 == 0) {
if (e1 > 0)
dirs.push_back(north);
else if (e1 < 0)
dirs.push_back(south);
}
}
}
}
// now select a direction from dirs vector
assert(!dirs.empty());
if (dirs.size() == 1)
return dirs[0];
pRouter router = channel->get_router();
Direction choice = invalid_dir;
unsigned int max_empty_slots = 0;
for (unsigned int i=0; i<dirs.size(); i++) {
Direction d = dirs[i];
pRouter neighbor_router = router->get_router(d);
assert(neighbor_router);
pIn_port neighbor_in_port = neighbor_router->get_in_port(reverse(d));
unsigned int empty_slots = neighbor_in_port->num_of_empty_buffer_slots();
if (empty_slots >= max_empty_slots) {
max_empty_slots = empty_slots;
choice = d;
}
}
assert(choice != invalid_dir);
return choice;
}
// In dyad router, we should use oe_fixed instead of XY routing policy when combined with
// OE routing policy. This is because we can when combining XY with OE routing, deadlock may happen.
// OE-fixed is a simple version of OE routing. It has the same routing delay as XY routing, and
// it always select the first legal routing direction from vector<Direction> dirs
Direction
Routing_engine::decide_direction_oe_fixed(const Position & src_pos, const Position & dst_pos) const {
vector<Direction> dirs;
dirs.clear();
// annotate power
if (net_clock.get_clock() > param.warmup_period) {
// ebit energy models
param.energy.re_energy += param.fixed_routing_engine_epacket;
}
int e0 = dst_pos.x - pos.x;
int e1 = dst_pos.y - pos.y;
if (e0 == 0 && e1 == 0)
return local;
if (e0 == 0) { // currently in the same column as destination
if (e1 > 0)
dirs.push_back(north);
else
dirs.push_back(south);
}
else {
if (e0 > 0) { // east bound messages
if (e1 == 0)
dirs.push_back(east);
else {
if (pos.x%2 == 1 || pos.x == src_pos.x) {
if (e1 > 0)
dirs.push_back(north);
else
dirs.push_back(south);
}
if (dst_pos.x%2 == 1 || e0 != 1) // odd destinatio column or >=2 columns of destination
dirs.push_back(east);
}
}
else { // west bound messges
dirs.push_back(west);
if (pos.x%2 == 0) {
if (e1 > 0)
dirs.push_back(north);
else if (e1 < 0)
dirs.push_back(south);
}
}
}
// now select a direction from dirs vector
assert(!dirs.empty());
return dirs[0];
}
/// Predicted routing UYO ///
// Decide the routing direction under Odd-Even routing scheme.
// We use a simple decision method here. We first get the two possible directions if
// they exists, then choose the next hop whose input channel buffer has more empty space
// left.
Direction
Routing_engine::decide_direction_predict(const Position & src_pos, const Position & dst_pos) const {
vector<Direction> dirs;
dirs.clear();
// annotate power
if (net_clock.get_clock() > param.warmup_period) {
// ebit energy models
param.energy.re_energy += param.oe_routing_engine_epacket;
}
int e0 = dst_pos.x - pos.x;
int e1 = dst_pos.y - pos.y;
if (e0 == 0 && e1 == 0)
dirs.push_back(local);
else {
if (e0 == 0) { // currently in the same column as destination
if (e1 > 0)
dirs.push_back(north);
else
dirs.push_back(south);
}
else {
if (e0 > 0) { // east bound messages
if (e1 == 0)
dirs.push_back(east);
else {
if (pos.x%2 == 1 || pos.x == src_pos.x) {
if (e1 > 0)
dirs.push_back(north);
else
dirs.push_back(south);
}
if (dst_pos.x%2 == 1 || e0 != 1) // odd destinatio column or >=2 columns of destination
dirs.push_back(east);
}
}
else { // west bound messges
dirs.push_back(west);
if (pos.x%2 == 0) {
if (e1 > 0)
dirs.push_back(north);
else if (e1 < 0)
dirs.push_back(south);
}
}
}
}
// now select a direction from dirs vector
assert(!dirs.empty());
if (dirs.size() == 1)
return dirs[0];
pRouter router = channel->get_router();
Direction choice = invalid_dir;
unsigned int max_availability = 0;
for (unsigned int i=0; i<dirs.size(); i++) {
Direction d = dirs[i];
pRouter neighbor_router = router->get_router(d); // Get neighbor router
assert(neighbor_router);
pInput_channel neighbor_chan = neighbor_router->get_in_channel(reverse(dir));
unsigned int availability = neighbor_chan->get_can_accept();
if ( availability >= max_availability ) {
max_availability = availability;
choice = d;
}
}
assert(choice != invalid_dir);
return choice;
}
/// End of predicted routing UYO ///
// Inform the switching fabric scheduler about which output channel it
// wants to connect to
int Routing_engine::send_request_to_arbiter(void) {
req_time = net_clock.get_clock();
pRouter router = channel->get_router();
pArbiter arbiter = router->get_arbiter();
pSw_connection_request req = new Sw_connection_request;
req->channel = channel;
req->dir = dir;
req->indir=channel->get_port()->get_direction();
req->timestamp = req_time;
arbiter->receive_connection_request(req);
return 0;
}
int Routing_engine::receive_grant_from_arbiter(void) {
grant_time = net_clock.get_clock();
return 0;
}
void Routing_engine::timer_fired(void) {
if (param.extreme_verbose)
cout << INFO_TIMER_FIRED << " (time = " << net_clock.get_clock() << ")\n";
send_request_to_arbiter();
}
// Tear down connection for the corresponding channel
void Routing_engine::teardown_connection(void) {
pRouter router = channel->get_router();
pArbiter arbiter = router->get_arbiter();
arbiter->teardown_connection(channel);
}
int Routing_engine::get_delay(void) const {
Routing_scheme current_routing_scheme = routing_scheme;
if (routing_scheme == dyad)
current_routing_scheme = decide_best_routing_mode();
if (current_routing_scheme == xy || current_routing_scheme == oe_fixed || current_routing_scheme == rtable) // UYO
return delay_xy;
else
return delay_oe;
}
| [
"[email protected]"
] | [
[
[
1,
642
]
]
] |
aecbed0a438706ddb428741515ca6607493fb027 | 9c62af23e0a1faea5aaa8dd328ba1d82688823a5 | /rl/tags/techdemo2/engine/ui/src/ContainerContentWindow.cpp | 514774f5f635f088db7d23a6cec6ac8ee7314fdb | [
"ClArtistic",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | jacmoe/dsa-hl-svn | 55b05b6f28b0b8b216eac7b0f9eedf650d116f85 | 97798e1f54df9d5785fb206c7165cd011c611560 | refs/heads/master | 2021-04-22T12:07:43.389214 | 2009-11-27T22:01:03 | 2009-11-27T22:01:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,813 | cpp | /* This source file is part of Rastullahs Lockenpracht.
* Copyright (C) 2003-2005 Team Pantheon. http://www.team-pantheon.de
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the Clarified Artistic License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Clarified Artistic License for more details.
*
* You should have received a copy of the Clarified Artistic License
* along with this program; if not you can get it here
* http://www.jpaulmorrison.com/fbp/artistic2.htm.
*/
#include <CEGUIImagesetManager.h>
#include <CEGUIImage.h>
#include <CEGUIImageset.h>
#include <boost/bind.hpp>
#include "ContainerContentWindow.h"
#include "Container.h"
#include "ListboxImageItem.h"
#include "WindowFactory.h"
#include "Item.h"
namespace rl {
using namespace CEGUI;
ContainerContentWindow::ContainerContentWindow(Container* container)
: CeGuiWindow("containercontentwindow.xml", WND_MOUSE_INPUT),
mContainer(container)
{
mItemList = getListbox("ContainerContentWindow/ContentList");
mItemList->setItemTooltipsEnabled(true);
ItemSet items = container->getItems();
for(ItemSet::iterator iter = items.begin(); iter != items.end(); iter++) {
Item* gameitem = *iter;
CeGuiString thumbname = gameitem->getName();
const Image& image = ImagesetManager::getSingleton().getImageset("ModelThumbnails")->getImage(thumbname);
ListboxImageItem* item =
new ListboxImageItem(&image, 0, gameitem);
item->setTooltipText(gameitem->getDescription());
mItemList->addItem(item);
}
mItemList->subscribeEvent(
Window::EventMouseDoubleClick,
boost::bind(&ContainerContentWindow::handleItemUse, this));
getWindow("ContainerContentWindow/ContentFrameWindow")->subscribeEvent(
FrameWindow::EventCloseClicked,
boost::bind(&ContainerContentWindow::handleClose, this));
getWindow("ContainerContentWindow/CloseButton")->subscribeEvent(
Window::EventMouseClick,
boost::bind(&ContainerContentWindow::handleClose, this));
getWindow("ContainerContentWindow/UseButton")->subscribeEvent(
Window::EventMouseClick,
boost::bind(&ContainerContentWindow::handleItemUse, this));
}
bool ContainerContentWindow::handleItemUse()
{
if (mItemList->getFirstSelectedItem() != NULL)
{
Item* currentItem = static_cast<Item*>(mItemList->getFirstSelectedItem()->getUserData());
WindowFactory::getSingleton().showActionChoice(currentItem);
}
return true;
}
bool ContainerContentWindow::handleClose()
{
mContainer->close();
destroyWindow();
return true;
}
}
| [
"tanis@4c79e8ff-cfd4-0310-af45-a38c79f83013"
] | [
[
[
1,
83
]
]
] |
0bf2d2255712fe036204fb623a9774aa79d614da | 288b16c1ed1f982722a897e9a4adae35bdbf1824 | /Step6/BoundedQueueTest.cpp | 4e718a7fbb2ba4adf8ff93e36b96dc0bde9d6477 | [] | no_license | yohei1126/boundedqueue | 2c12e10ebe3e0128710c9c36c39332aaebcdc33e | 8fbae4f0a529a9be1bc225952de46d3d35d9732b | refs/heads/master | 2020-05-09T21:55:44.168713 | 2011-10-02T08:43:08 | 2011-10-02T08:43:08 | 2,494,631 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,100 | cpp | #include "BoundedQueue.h"
#include <gmock/gmock.h>
class MockQueueControl : public QueueControl {
public:
MOCK_METHOD0(Resume, void());
MOCK_METHOD0(Pause, void());
};
class BoundedQueueTest : public ::testing::Test {
public:
MockQueueControl producer;
MockQueueControl consumer;
BoundedQueueTest(): q(producer, consumer){}
BoundedQueue<int> q;
};
TEST_F(BoundedQueueTest, CreateResumesProducer) {
EXPECT_CALL(producer, Resume());
BoundedQueue<int> q(producer, consumer);
}
TEST_F(BoundedQueueTest, CreatePausesConsumer){
EXPECT_CALL(consumer, Resume());
BoundedQueue<int> q(producer, consumer);
}
TEST_F(BoundedQueueTest, EnqueueResumesConsumer){
BoundedQueue <int> q(producer, consumer);
EXPECT_CALL(consumer, Resume());
q.enqueue(5);
}
TEST_F(BoundedQueueTest, FirstInFirstOut) {
q.enqueue(1);
q.enqueue(2);
ASSERT_EQ(1, q.dequeue());
ASSERT_EQ(2, q.dequeue());
}
TEST_F(BoundedQueueTest, EnqueueResumeConsumerOnFirestItemOnly) {
EXPECT_CALL(consumer, Resume()).Times(1);
q.enqueue(5);
q.enqueue(5);
}
| [
"[email protected]"
] | [
[
[
1,
46
]
]
] |
6ec417f5faf60c974ec7a4104be2bbd9576aa497 | ab41c2c63e554350ca5b93e41d7321ca127d8d3a | /glm/gtx/comparison.hpp | 1f071b431723a4f4e37b78e9a12672b08ca68175 | [] | no_license | burner/e3rt | 2dc3bac2b7face3b1606ee1430e7ecfd4523bf2e | 775470cc9b912a8c1199dd1069d7e7d4fc997a52 | refs/heads/master | 2021-01-11T08:08:00.665300 | 2010-04-26T11:42:42 | 2010-04-26T11:42:42 | 337,021 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,578 | hpp | ///////////////////////////////////////////////////////////////////////////////////////////////////
// OpenGL Mathematics Copyright (c) 2005 - 2009 G-Truc Creation (www.g-truc.net)
///////////////////////////////////////////////////////////////////////////////////////////////////
// Created : 2008-06-22
// Updated : 2008-10-27
// Licence : This source is under MIT License
// File : glm/gtx/comparison.h
///////////////////////////////////////////////////////////////////////////////////////////////////
// Dependency:
// - GLM core
///////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef glm_gtx_comparison
#define glm_gtx_comparison
// Dependency:
#include "../glm.hpp"
namespace glm
{
namespace test{
void main_gtx_comparison();
}//namespace test
namespace gtx{
//! GLM_GTX_comparison extension: Defined comparison operators for vectors.
namespace comparison{
//! Define == operator for vectors
//! From GLM_GTX_comparison extension.
template <typename vecType>
bool operator== (vecType const & x, vecType const & y);
//! Define != operator for vectors
//! From GLM_GTX_comparison extension.
template <typename vecType>
bool operator!= (vecType const & x, vecType const & y);
}//namespace comparison
}//namespace gtx
}//namespace glm
#define GLM_GTX_comparison namespace glm::gtx::comparison
#ifndef GLM_GTX_GLOBAL
namespace glm {using GLM_GTX_comparison;}
#endif//GLM_GTC_GLOBAL
#include "comparison.inl"
#endif//glm_gtx_comparison
| [
"[email protected]"
] | [
[
[
1,
50
]
]
] |
1a086b27824a721adde08812b1c951217d61f746 | a0d4f557ddaf4351957e310478e183dac45d77a1 | /src/TilePattern.h | d87ba68c9f5994961ed9f4df33d85a0ed473357c | [] | no_license | houpcz/Houp-s-level-editor | 1f6216e8ad8da393e1ee151e36fc37246279bfed | c762c9f5ed064ba893bf34887293a73dd35a06f8 | refs/heads/master | 2016-09-11T11:03:34.560524 | 2011-08-09T11:37:49 | 2011-08-09T11:37:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 901 | h | #ifndef _TILEPATTERN_H_
#define _TILEPATTERN_H_
class TilePattern
{
private :
int ***pattern;
int width;
int height;
int layer;
void RotateOneTileRight(int *** matrix, int x, int y, int z);
void MirrorHorizontalGlobal();
void MirrorHorizontalLocal();
void Clear();
public :
enum {
DONT_CLEAR = -1
};
TilePattern();
~TilePattern();
int GetWidth() { return width; };
int GetHeight() { return height; };
int GetLayer() { return layer; };
int GetTileID(int startX, int startY, int layer);
void RotateRight();
void MirrorHorizontal();
void MirrorVertical();
void Set(int *** matrix, int n_width, int n_height, int n_layer);
static int *** CreateMatrix3D(int x, int y, int z);
};
#endif
| [
"[email protected]"
] | [
[
[
1,
33
]
]
] |
d9fade1f83ec7b51ac692f40cb87b8644d34b31f | 4b30b09448549ffbe73c2346447e249713c1a463 | /Sources/html_form/html_tag.cpp | bbfcdc45e5f6ff3b7a042a07d951a160f04f7794 | [] | 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,402 | cpp | #include <agnespch.hpp>
#ifndef HTML_TAG_CPP
#define HTML_TAG_CPP
const html_tag html_("html", 0);
const html_tag head_("head", 0);
const html_tag body_("body", 0);
const html_tag title_("title", 0);
const html_tag base_("base",
"HREF", "",
"TARGET", "", 0);
const html_tag div_("div",
"ALIGN", "",
"STYLE", "", 0);
const html_tag center_("center", 0);
const html_tag table_("table",
"BORDER", "",
"BACKGROUND", "",
"BGCOLOR", "",
"BORDERCOLOR", "",
"WIDTH", "",
"CELLSPACING", "",
"CELLPADDING", "",
"FRAME", "",
"HEIGHT", "",
"RULES", "",
0);
const html_tag tr_("tr",
"ALIGN", "",
"BGCOLOR", "",
"BORDERCOLOR", "",
"VALIGN", "",
"HEIGHT", "",
0);
const html_tag td_("td",
"BACKGROUND", "",
"BGCOLOR", "",
"BORDERCOLOR", "",
"ALIGN", "",
"NOWRAP", "", //make a single type option
"VALIGN", "",
"ROWSPAN", "",
"COLSPAN", "",
"WIDTH", "",
"HEIGHT", "",
0);
const html_tag form_("form",
"ACTION", "",
"METHOD", "",
"TARGET", "",
"ENCTYPE", "",
0);
const html_tag p_("p",
"ALIGN", "",
0);
const html_tag font_("font",
"SIZE", "",
"COLOR", "",
"FACE", "",
0);
const html_tag em_("em", 0);
const html_tag br_("br", 0);
const html_tag a_("a",
"HREF","",
"NAME","",
"OnClick","",
"OnMouseOver","",
"REV","",
"REL","",
"TARGET","",
"TITLE","",
0);
const html_tag input_("input",
"ALIGN", "",
"CHECKED", "",
"MAXLENGTH", "",
"NAME", "",
"SIZE", "",
"SRC", "",
"VALUE","",
"TYPE","",
0);
const html_tag img_("img",
"SRC", "",
"ALIGN","",
"WIDTH","",
"HEIGHT","",
"USEMAP","",
"ISMAP","",
"ALT","",
"BORDER","",
"LOWSRC","",
"VSPACE","",
"HSPACE","",
0);
const html_tag textarea_("textarea",
"COLS","",
"ROWS","",
"NAME","",
"WRAP","",
0);
const html_tag hr_("hr",0);
const html_tag b_("b",0);
const html_tag blockquote_("blockquote",0);
const html_tag select_("select",
"MULTIPLE","",
"NAME","",
"SIZE","",
0);
const html_tag option_("option", "VALUE","", 0);
const html_tag h1_("h1", "ALIGN","", 0);
const html_tag h2_("h2", "ALIGN","", 0);
const html_tag h3_("h3", "ALIGN","", 0);
const html_tag h4_("h4", "ALIGN","", 0);
#endif
| [
"[email protected]"
] | [
[
[
1,
120
]
]
] |
6cc6ce449a26a16a5ff84ccf5e21cf9ad00115c5 | fc7dbcb3bcdb16010e9b1aad4ecba41709089304 | /BaseTools/Source/C/VfrCompile/VfrUtilityLib.cpp | cae0479ad360a340e96421d63405ecd36230a4c7 | [] | no_license | Itomyl/loongson-uefi | 5eb0ece5875406b00dbd265d28245208d6bbc99a | 70b7d5495e2b451899e2ba2ef677384de075d984 | refs/heads/master | 2021-05-28T04:38:29.989074 | 2010-05-31T02:47:26 | 2010-05-31T02:47:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 70,500 | cpp | /** @file
Vfr common library functions.
Copyright (c) 2004 - 2008, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#include "stdio.h"
#include "stdlib.h"
#include "VfrUtilityLib.h"
#include "VfrFormPkg.h"
VOID
CVfrBinaryOutput::WriteLine (
IN FILE *pFile,
IN UINT32 LineBytes,
IN CONST CHAR8 *LineHeader,
IN CHAR8 *BlkBuf,
IN UINT32 BlkSize
)
{
UINT32 Index;
if ((pFile == NULL) || (LineHeader == NULL) || (BlkBuf == NULL)) {
return;
}
for (Index = 0; Index < BlkSize; Index++) {
if ((Index % LineBytes) == 0) {
fprintf (pFile, "\n%s", LineHeader);
}
fprintf (pFile, "0x%02X, ", (UINT8)BlkBuf[Index]);
}
}
VOID
CVfrBinaryOutput::WriteEnd (
IN FILE *pFile,
IN UINT32 LineBytes,
IN CONST CHAR8 *LineHeader,
IN CHAR8 *BlkBuf,
IN UINT32 BlkSize
)
{
UINT32 Index;
if ((BlkSize == 0) || (pFile == NULL) || (LineHeader == NULL) || (BlkBuf == NULL)) {
return;
}
for (Index = 0; Index < BlkSize - 1; Index++) {
if ((Index % LineBytes) == 0) {
fprintf (pFile, "\n%s", LineHeader);
}
fprintf (pFile, "0x%02X, ", (UINT8)BlkBuf[Index]);
}
if ((Index % LineBytes) == 0) {
fprintf (pFile, "\n%s", LineHeader);
}
fprintf (pFile, "0x%02X\n", (UINT8)BlkBuf[Index]);
}
SConfigInfo::SConfigInfo (
IN UINT8 Type,
IN UINT16 Offset,
IN UINT32 Width,
IN EFI_IFR_TYPE_VALUE Value
)
{
mNext = NULL;
mOffset = Offset;
mWidth = (UINT16)Width;
mValue = new UINT8[mWidth];
if (mValue == NULL) {
return;
}
switch (Type) {
case EFI_IFR_TYPE_NUM_SIZE_8 :
memcpy (mValue, &Value.u8, mWidth);
break;
case EFI_IFR_TYPE_NUM_SIZE_16 :
memcpy (mValue, &Value.u16, mWidth);
break;
case EFI_IFR_TYPE_NUM_SIZE_32 :
memcpy (mValue, &Value.u32, mWidth);
break;
case EFI_IFR_TYPE_NUM_SIZE_64 :
memcpy (mValue, &Value.u64, mWidth);
break;
case EFI_IFR_TYPE_BOOLEAN :
memcpy (mValue, &Value.b, mWidth);
break;
case EFI_IFR_TYPE_TIME :
memcpy (mValue, &Value.time, mWidth);
break;
case EFI_IFR_TYPE_DATE :
memcpy (mValue, &Value.date, mWidth);
break;
case EFI_IFR_TYPE_STRING :
memcpy (mValue, &Value.string, mWidth);
break;
case EFI_IFR_TYPE_OTHER :
return;
}
}
SConfigInfo::~SConfigInfo (
VOID
)
{
BUFFER_SAFE_FREE (mValue);
}
SConfigItem::SConfigItem (
IN CHAR8 *Name,
IN CHAR8 *Id
)
{
mName = NULL;
mId = 0;
mInfoStrList = NULL;
mNext = NULL;
if (Name != NULL) {
if ((mName = new CHAR8[strlen (Name) + 1]) != NULL) {
strcpy (mName, Name);
}
}
if (Id != NULL) {
if ((mId = new CHAR8[strlen (Id) + 1]) != NULL) {
strcpy (mId, Id);
}
}
}
SConfigItem::SConfigItem (
IN CHAR8 *Name,
IN CHAR8 *Id,
IN UINT8 Type,
IN UINT16 Offset,
IN UINT16 Width,
IN EFI_IFR_TYPE_VALUE Value
)
{
mName = NULL;
mId = NULL;
mInfoStrList = NULL;
mNext = NULL;
if (Name != NULL) {
if ((mName = new CHAR8[strlen (Name) + 1]) != NULL) {
strcpy (mName, Name);
}
}
if (Id != NULL) {
if ((mId = new CHAR8[strlen (Id) + 1]) != NULL) {
strcpy (mId, Id);
}
}
mInfoStrList = new SConfigInfo(Type, Offset, Width, Value);
}
SConfigItem::~SConfigItem (
VOID
)
{
SConfigInfo *Info;
BUFFER_SAFE_FREE (mName);
BUFFER_SAFE_FREE (mId);
while (mInfoStrList != NULL) {
Info = mInfoStrList;
mInfoStrList = mInfoStrList->mNext;
BUFFER_SAFE_FREE (Info);
}
}
UINT8
CVfrBufferConfig::Register (
IN CHAR8 *Name,
IN CHAR8 *Id
)
{
SConfigItem *pNew;
if (Select (Name) == 0) {
return 1;
}
if ((pNew = new SConfigItem (Name, Id)) == NULL) {
return 2;
}
if (mItemListHead == NULL) {
mItemListHead = pNew;
mItemListTail = pNew;
} else {
mItemListTail->mNext = pNew;
mItemListTail = pNew;
}
mItemListPos = pNew;
return 0;
}
VOID
CVfrBufferConfig::Open (
VOID
)
{
mItemListPos = mItemListHead;
}
BOOLEAN
CVfrBufferConfig::Eof(
VOID
)
{
return (mItemListPos == NULL) ? TRUE : FALSE;
}
UINT8
CVfrBufferConfig::Select (
IN CHAR8 *Name,
IN CHAR8 *Id
)
{
SConfigItem *p;
if (Name == NULL) {
mItemListPos = mItemListHead;
return 0;
} else {
for (p = mItemListHead; p != NULL; p = p->mNext) {
if (strcmp (p->mName, Name) != 0) {
continue;
}
if (Id != NULL) {
if (p->mId == NULL || strcmp (p->mId, Id) != 0) {
continue;
}
} else if (p->mId != NULL) {
continue;
}
mItemListPos = p;
return 0;
}
}
return 1;
}
UINT8
CVfrBufferConfig::Write (
IN CONST CHAR8 Mode,
IN CHAR8 *Name,
IN CHAR8 *Id,
IN UINT8 Type,
IN UINT16 Offset,
IN UINT32 Width,
IN EFI_IFR_TYPE_VALUE Value
)
{
UINT8 Ret;
SConfigItem *pItem;
SConfigInfo *pInfo;
if ((Ret = Select (Name)) != 0) {
return Ret;
}
switch (Mode) {
case 'a' : // add
if (Select (Name, Id) != 0) {
if ((pItem = new SConfigItem (Name, Id, Type, Offset, (UINT16) Width, Value)) == NULL) {
return 2;
}
if (mItemListHead == NULL) {
mItemListHead = pItem;
mItemListTail = pItem;
} else {
mItemListTail->mNext = pItem;
mItemListTail = pItem;
}
mItemListPos = pItem;
} else {
// tranverse the list to find out if there's already the value for the same offset
for (pInfo = mItemListPos->mInfoStrList; pInfo != NULL; pInfo = pInfo->mNext) {
if (pInfo->mOffset == Offset) {
// check if the value and width are the same; return error if not
if ((Id != NULL) && (pInfo->mWidth != Width || memcmp(pInfo->mValue, &Value, Width) != 0)) {
return VFR_RETURN_DEFAULT_VALUE_REDEFINED;
}
return 0;
}
}
if((pInfo = new SConfigInfo (Type, Offset, Width, Value)) == NULL) {
return 2;
}
pInfo->mNext = mItemListPos->mInfoStrList;
mItemListPos->mInfoStrList = pInfo;
}
break;
case 'd' : // delete
if (mItemListHead == mItemListPos) {
mItemListHead = mItemListPos->mNext;
delete mItemListPos;
break;
}
for (pItem = mItemListHead; pItem->mNext != mItemListPos; pItem = pItem->mNext)
;
pItem->mNext = mItemListPos->mNext;
if (mItemListTail == mItemListPos) {
mItemListTail = pItem;
}
delete mItemListPos;
mItemListPos = pItem->mNext;
break;
case 'i' : // set info
if (mItemListPos->mId != NULL) {
delete mItemListPos->mId;
}
mItemListPos->mId = NULL;
if (Id != NULL) {
if ((mItemListPos->mId = new CHAR8[strlen (Id) + 1]) == NULL) {
return 2;
}
strcpy (mItemListPos->mId, Id);
}
break;
default :
return 1;
}
return 0;
}
VOID
CVfrBufferConfig::Close (
VOID
)
{
mItemListPos = NULL;
}
#define BYTES_PRE_LINE 0x10
VOID
CVfrBufferConfig::OutputCFile (
IN FILE *pFile,
IN CHAR8 *BaseName
)
{
CVfrBinaryOutput Output;
SConfigItem *Item;
SConfigInfo *Info;
UINT32 TotalLen;
if (pFile == NULL) {
return;
}
for (Item = mItemListHead; Item != NULL; Item = Item->mNext) {
if (Item->mId != NULL || Item->mInfoStrList == NULL) {
continue;
}
fprintf (pFile, "\nunsigned char %s%sBlockName[] = {", BaseName, Item->mName);
TotalLen = sizeof (UINT32);
for (Info = Item->mInfoStrList; Info != NULL; Info = Info->mNext) {
TotalLen += sizeof (UINT16) * 2;
}
Output.WriteLine (pFile, BYTES_PRE_LINE, " ", (CHAR8 *)&TotalLen, sizeof (UINT32));
for (Info = Item->mInfoStrList; Info != NULL; Info = Info->mNext) {
fprintf (pFile, "\n");
Output.WriteLine (pFile, BYTES_PRE_LINE, " ", (CHAR8 *)&Info->mOffset, sizeof (UINT16));
Output.WriteLine (pFile, BYTES_PRE_LINE, " ", (CHAR8 *)&Info->mWidth, sizeof (UINT16));
}
fprintf (pFile, "\n};\n");
}
for (Item = mItemListHead; Item != NULL; Item = Item->mNext) {
if (Item->mId != NULL && Item->mInfoStrList != NULL) {
fprintf (pFile, "\nunsigned char %s%sDefault%s[] = {", BaseName, Item->mName, Item->mId);
TotalLen = sizeof (UINT32);
for (Info = Item->mInfoStrList; Info != NULL; Info = Info->mNext) {
TotalLen += Info->mWidth + sizeof (UINT16) * 2;
}
Output.WriteLine (pFile, BYTES_PRE_LINE, " ", (CHAR8 *)&TotalLen, sizeof (UINT32));
for (Info = Item->mInfoStrList; Info != NULL; Info = Info->mNext) {
fprintf (pFile, "\n");
Output.WriteLine (pFile, BYTES_PRE_LINE, " ", (CHAR8 *)&Info->mOffset, sizeof (UINT16));
Output.WriteLine (pFile, BYTES_PRE_LINE, " ", (CHAR8 *)&Info->mWidth, sizeof (UINT16));
if (Info->mNext == NULL) {
Output.WriteEnd (pFile, BYTES_PRE_LINE, " ", (CHAR8 *)Info->mValue, Info->mWidth);
} else {
Output.WriteLine (pFile, BYTES_PRE_LINE, " ", (CHAR8 *)Info->mValue, Info->mWidth);
}
}
fprintf (pFile, "\n};\n");
}
}
}
CVfrBufferConfig::CVfrBufferConfig (
VOID
)
{
mItemListHead = NULL;
mItemListTail = NULL;
mItemListPos = NULL;
}
CVfrBufferConfig::~CVfrBufferConfig (
VOID
)
{
SConfigItem *p;
while (mItemListHead != NULL) {
p = mItemListHead;
mItemListHead = mItemListHead->mNext;
delete p;
}
mItemListHead = NULL;
mItemListTail = NULL;
mItemListPos = NULL;
}
CVfrBufferConfig gCVfrBufferConfig;
static struct {
CONST CHAR8 *mTypeName;
UINT8 mType;
UINT32 mSize;
UINT32 mAlign;
} gInternalTypesTable [] = {
{"UINT64", EFI_IFR_TYPE_NUM_SIZE_64, sizeof (UINT64), sizeof (UINT64)},
{"UINT32", EFI_IFR_TYPE_NUM_SIZE_32, sizeof (UINT32), sizeof (UINT32)},
{"UINT16", EFI_IFR_TYPE_NUM_SIZE_16, sizeof (UINT16), sizeof (UINT16)},
{"UINT8", EFI_IFR_TYPE_NUM_SIZE_8, sizeof (UINT8), sizeof (UINT8)},
{"BOOLEAN", EFI_IFR_TYPE_BOOLEAN, sizeof (BOOLEAN), sizeof (BOOLEAN)},
{"EFI_HII_DATE", EFI_IFR_TYPE_DATE, sizeof (EFI_HII_DATE), sizeof (UINT16)},
{"EFI_STRING_ID", EFI_IFR_TYPE_STRING, sizeof (EFI_STRING_ID),sizeof (EFI_STRING_ID)},
{"EFI_HII_TIME", EFI_IFR_TYPE_TIME, sizeof (EFI_HII_TIME), sizeof (UINT8)},
{NULL, EFI_IFR_TYPE_OTHER, 0, 0}
};
STATIC
BOOLEAN
_IS_INTERNAL_TYPE (
IN CHAR8 *TypeName
)
{
UINT32 Index;
if (TypeName == NULL) {
return FALSE;
}
for (Index = 0; gInternalTypesTable[Index].mTypeName != NULL; Index++) {
if (strcmp (TypeName, gInternalTypesTable[Index].mTypeName) == 0) {
return TRUE;
}
}
return FALSE;
}
STATIC
CHAR8 *
TrimHex (
IN CHAR8 *Str,
OUT bool *IsHex
)
{
*IsHex = FALSE;
while (*Str && *Str == ' ') {
Str++;
}
while (*Str && *Str == '0') {
Str++;
}
if (*Str && (*Str == 'x' || *Str == 'X')) {
Str++;
*IsHex = TRUE;
}
return Str;
}
UINT32
_STR2U32 (
IN CHAR8 *Str
)
{
bool IsHex;
UINT32 Value;
CHAR8 c;
Str = TrimHex (Str, &IsHex);
for (Value = 0; (c = *Str) != '\0'; Str++) {
//
// BUG: does not handle overflow here
//
(IsHex == TRUE) ? (Value <<= 4) : (Value *= 10);
if ((IsHex == TRUE) && (c >= 'a') && (c <= 'f')) {
Value += (c - 'a' + 10);
}
if ((IsHex == TRUE) && (c >= 'A') && (c <= 'F')) {
Value += (c - 'A' + 10);
}
if (c >= '0' && c <= '9') {
Value += (c - '0');
}
}
return Value;
}
VOID
CVfrVarDataTypeDB::RegisterNewType (
IN SVfrDataType *New
)
{
New->mNext = mDataTypeList;
mDataTypeList = New;
}
EFI_VFR_RETURN_CODE
CVfrVarDataTypeDB::ExtractStructTypeName (
IN CHAR8 *&VarStr,
OUT CHAR8 *TName
)
{
if (TName == NULL) {
return VFR_RETURN_FATAL_ERROR;
}
while((*VarStr != '\0') && (*VarStr != '.')) {
*TName = *VarStr;
VarStr++;
TName++;
}
*TName = '\0';
if (*VarStr == '.') {
VarStr++;
}
return VFR_RETURN_SUCCESS;
}
EFI_VFR_RETURN_CODE
CVfrVarDataTypeDB::ExtractFieldNameAndArrary (
IN CHAR8 *&VarStr,
IN CHAR8 *FName,
OUT UINT32 &ArrayIdx
)
{
UINT32 Idx;
CHAR8 ArrayStr[MAX_NAME_LEN + 1];
ArrayIdx = INVALID_ARRAY_INDEX;
if (FName == NULL) {
return VFR_RETURN_FATAL_ERROR;
}
while((*VarStr != '\0') &&
(*VarStr != '.') &&
(*VarStr != '[') &&
(*VarStr != ']')) {
*FName = *VarStr;
VarStr++;
FName++;
}
*FName = '\0';
switch (*VarStr) {
case '.' :
VarStr++;
case '\0':
return VFR_RETURN_SUCCESS;
case '[' :
VarStr++;
for (Idx = 0; (Idx < MAX_NAME_LEN) && (*VarStr != '\0') && (*VarStr != ']'); VarStr++, Idx++) {
ArrayStr[Idx] = *VarStr;
}
ArrayStr[Idx] = '\0';
if ((*VarStr != ']') && (ArrayStr[0] == '\0')) {
return VFR_RETURN_DATA_STRING_ERROR;
}
ArrayIdx = _STR2U32 (ArrayStr);
if (*VarStr == ']') {
VarStr++;
}
return VFR_RETURN_SUCCESS;
case ']':
return VFR_RETURN_DATA_STRING_ERROR;
}
return VFR_RETURN_SUCCESS;
}
EFI_VFR_RETURN_CODE
CVfrVarDataTypeDB::GetTypeField (
IN CHAR8 *FName,
IN SVfrDataType *Type,
OUT SVfrDataField *&Field
)
{
SVfrDataField *pField = NULL;
if ((FName == NULL) && (Type == NULL)) {
return VFR_RETURN_FATAL_ERROR;
}
for (pField = Type->mMembers; pField != NULL; pField = pField->mNext) {
if (strcmp (pField->mFieldName, FName) == 0) {
Field = pField;
return VFR_RETURN_SUCCESS;
}
}
return VFR_RETURN_UNDEFINED;
}
EFI_VFR_RETURN_CODE
CVfrVarDataTypeDB::GetFieldOffset (
IN SVfrDataField *Field,
IN UINT32 ArrayIdx,
OUT UINT32 &Offset
)
{
if (Field == NULL) {
return VFR_RETURN_FATAL_ERROR;
}
//
// Framework Vfr file Array Index is from 1.
// But Uefi Vfr file Array Index is from 0.
//
if (VfrCompatibleMode && ArrayIdx != INVALID_ARRAY_INDEX) {
if (ArrayIdx == 0) {
return VFR_RETURN_ERROR_ARRARY_NUM;
}
ArrayIdx = ArrayIdx - 1;
}
if ((ArrayIdx != INVALID_ARRAY_INDEX) && ((Field->mArrayNum == 0) || (Field->mArrayNum <= ArrayIdx))) {
return VFR_RETURN_ERROR_ARRARY_NUM;
}
//
// Be compatible with the current usage
// If ArraryIdx is not specified, the first one is used.
//
// if ArrayNum is larger than zero, ArraryIdx must be specified.
//
// if ((ArrayIdx == INVALID_ARRAY_INDEX) && (Field->mArrayNum > 0)) {
// return VFR_RETURN_ERROR_ARRARY_NUM;
// }
//
Offset = Field->mOffset + Field->mFieldType->mTotalSize * ((ArrayIdx == INVALID_ARRAY_INDEX) ? 0 : ArrayIdx);
return VFR_RETURN_SUCCESS;
}
UINT8
CVfrVarDataTypeDB::GetFieldWidth (
IN SVfrDataField *Field
)
{
if (Field == NULL) {
return 0;
}
return Field->mFieldType->mType;
}
UINT32
CVfrVarDataTypeDB::GetFieldSize (
IN SVfrDataField *Field,
IN UINT32 ArrayIdx
)
{
if (Field == NULL) {
return VFR_RETURN_FATAL_ERROR;
}
if ((ArrayIdx == INVALID_ARRAY_INDEX) && (Field->mArrayNum != 0)) {
return Field->mFieldType->mTotalSize * Field->mArrayNum;
} else {
return Field->mFieldType->mTotalSize;
}
}
VOID
CVfrVarDataTypeDB::InternalTypesListInit (
VOID
)
{
SVfrDataType *New = NULL;
UINT32 Index;
for (Index = 0; gInternalTypesTable[Index].mTypeName != NULL; Index++) {
New = new SVfrDataType;
if (New != NULL) {
strcpy (New->mTypeName, gInternalTypesTable[Index].mTypeName);
New->mType = gInternalTypesTable[Index].mType;
New->mAlign = gInternalTypesTable[Index].mAlign;
New->mTotalSize = gInternalTypesTable[Index].mSize;
if (strcmp (gInternalTypesTable[Index].mTypeName, "EFI_HII_DATE") == 0) {
SVfrDataField *pYearField = new SVfrDataField;
SVfrDataField *pMonthField = new SVfrDataField;
SVfrDataField *pDayField = new SVfrDataField;
strcpy (pYearField->mFieldName, "Year");
GetDataType ((CHAR8 *)"UINT16", &pYearField->mFieldType);
pYearField->mOffset = 0;
pYearField->mNext = pMonthField;
pYearField->mArrayNum = 0;
strcpy (pMonthField->mFieldName, "Month");
GetDataType ((CHAR8 *)"UINT8", &pMonthField->mFieldType);
pMonthField->mOffset = 2;
pMonthField->mNext = pDayField;
pMonthField->mArrayNum = 0;
strcpy (pDayField->mFieldName, "Day");
GetDataType ((CHAR8 *)"UINT8", &pDayField->mFieldType);
pDayField->mOffset = 3;
pDayField->mNext = NULL;
pDayField->mArrayNum = 0;
New->mMembers = pYearField;
} else if (strcmp (gInternalTypesTable[Index].mTypeName, "EFI_HII_TIME") == 0) {
SVfrDataField *pHoursField = new SVfrDataField;
SVfrDataField *pMinutesField = new SVfrDataField;
SVfrDataField *pSecondsField = new SVfrDataField;
strcpy (pHoursField->mFieldName, "Hours");
GetDataType ((CHAR8 *)"UINT8", &pHoursField->mFieldType);
pHoursField->mOffset = 0;
pHoursField->mNext = pMinutesField;
pHoursField->mArrayNum = 0;
strcpy (pMinutesField->mFieldName, "Minutes");
GetDataType ((CHAR8 *)"UINT8", &pMinutesField->mFieldType);
pMinutesField->mOffset = 1;
pMinutesField->mNext = pSecondsField;
pMinutesField->mArrayNum = 0;
strcpy (pSecondsField->mFieldName, "Seconds");
GetDataType ((CHAR8 *)"UINT8", &pSecondsField->mFieldType);
pSecondsField->mOffset = 2;
pSecondsField->mNext = NULL;
pSecondsField->mArrayNum = 0;
New->mMembers = pHoursField;
} else {
New->mMembers = NULL;
}
New->mNext = NULL;
RegisterNewType (New);
New = NULL;
}
}
}
CVfrVarDataTypeDB::CVfrVarDataTypeDB (
VOID
)
{
mDataTypeList = NULL;
mNewDataType = NULL;
mCurrDataField = NULL;
mPackAlign = DEFAULT_PACK_ALIGN;
mPackStack = NULL;
mFirstNewDataTypeName = NULL;
InternalTypesListInit ();
}
CVfrVarDataTypeDB::~CVfrVarDataTypeDB (
VOID
)
{
SVfrDataType *pType;
SVfrDataField *pField;
SVfrPackStackNode *pPack;
if (mNewDataType != NULL) {
delete mNewDataType;
}
while (mDataTypeList != NULL) {
pType = mDataTypeList;
mDataTypeList = mDataTypeList->mNext;
while(pType->mMembers != NULL) {
pField = pType->mMembers;
pType->mMembers = pType->mMembers->mNext;
delete pField;
}
delete pType;
}
while (mPackStack != NULL) {
pPack = mPackStack;
mPackStack = mPackStack->mNext;
delete pPack;
}
}
EFI_VFR_RETURN_CODE
CVfrVarDataTypeDB::Pack (
IN UINT32 LineNum,
IN UINT8 Action,
IN CHAR8 *Identifier,
IN UINT32 Number
)
{
UINT32 PackAlign;
CHAR8 Msg[MAX_STRING_LEN] = {0, };
if (Action & VFR_PACK_SHOW) {
sprintf (Msg, "value of pragma pack(show) == %d", mPackAlign);
gCVfrErrorHandle.PrintMsg (LineNum, NULL, "Warning", Msg);
}
if (Action & VFR_PACK_PUSH) {
SVfrPackStackNode *pNew = NULL;
if ((pNew = new SVfrPackStackNode (Identifier, mPackAlign)) == NULL) {
return VFR_RETURN_FATAL_ERROR;
}
pNew->mNext = mPackStack;
mPackStack = pNew;
}
if (Action & VFR_PACK_POP) {
SVfrPackStackNode *pNode = NULL;
if (mPackStack == NULL) {
gCVfrErrorHandle.PrintMsg (LineNum, NULL, "Error", "#pragma pack(pop...) : more pops than pushes");
}
for (pNode = mPackStack; pNode != NULL; pNode = pNode->mNext) {
if (pNode->Match (Identifier) == TRUE) {
mPackAlign = pNode->mNumber;
mPackStack = pNode->mNext;
}
}
}
if (Action & VFR_PACK_ASSIGN) {
PackAlign = (Number > 1) ? Number + Number % 2 : Number;
if ((PackAlign == 0) || (PackAlign > 16)) {
gCVfrErrorHandle.PrintMsg (LineNum, NULL, "Error", "expected pragma parameter to be '1', '2', '4', '8', or '16'");
} else {
mPackAlign = PackAlign;
}
}
return VFR_RETURN_SUCCESS;
}
VOID
CVfrVarDataTypeDB::DeclareDataTypeBegin (
VOID
)
{
SVfrDataType *pNewType = NULL;
pNewType = new SVfrDataType;
pNewType->mTypeName[0] = '\0';
pNewType->mType = EFI_IFR_TYPE_OTHER;
pNewType->mAlign = DEFAULT_ALIGN;
pNewType->mTotalSize = 0;
pNewType->mMembers = NULL;
pNewType->mNext = NULL;
mNewDataType = pNewType;
}
EFI_VFR_RETURN_CODE
CVfrVarDataTypeDB::SetNewTypeName (
IN CHAR8 *TypeName
)
{
SVfrDataType *pType;
if (mNewDataType == NULL) {
return VFR_RETURN_ERROR_SKIPED;
}
if (TypeName == NULL) {
return VFR_RETURN_FATAL_ERROR;
}
if (strlen(TypeName) >= MAX_NAME_LEN) {
return VFR_RETURN_INVALID_PARAMETER;
}
for (pType = mDataTypeList; pType != NULL; pType = pType->mNext) {
if (strcmp(pType->mTypeName, TypeName) == 0) {
return VFR_RETURN_REDEFINED;
}
}
strcpy(mNewDataType->mTypeName, TypeName);
return VFR_RETURN_SUCCESS;
}
EFI_VFR_RETURN_CODE
CVfrVarDataTypeDB::DataTypeAddField (
IN CHAR8 *FieldName,
IN CHAR8 *TypeName,
IN UINT32 ArrayNum
)
{
SVfrDataField *pNewField = NULL;
SVfrDataType *pFieldType = NULL;
SVfrDataField *pTmp;
UINT32 Align;
CHECK_ERROR_RETURN (GetDataType (TypeName, &pFieldType), VFR_RETURN_SUCCESS);
if (strlen (FieldName) >= MAX_NAME_LEN) {
return VFR_RETURN_INVALID_PARAMETER;
}
for (pTmp = mNewDataType->mMembers; pTmp != NULL; pTmp = pTmp->mNext) {
if (strcmp (pTmp->mFieldName, FieldName) == 0) {
return VFR_RETURN_REDEFINED;
}
}
Align = MIN (mPackAlign, pFieldType->mAlign);
if ((pNewField = new SVfrDataField) == NULL) {
return VFR_RETURN_OUT_FOR_RESOURCES;
}
strcpy (pNewField->mFieldName, FieldName);
pNewField->mFieldType = pFieldType;
pNewField->mArrayNum = ArrayNum;
if ((mNewDataType->mTotalSize % Align) == 0) {
pNewField->mOffset = mNewDataType->mTotalSize;
} else {
pNewField->mOffset = mNewDataType->mTotalSize + ALIGN_STUFF(mNewDataType->mTotalSize, Align);
}
if (mNewDataType->mMembers == NULL) {
mNewDataType->mMembers = pNewField;
pNewField->mNext = NULL;
} else {
for (pTmp = mNewDataType->mMembers; pTmp->mNext != NULL; pTmp = pTmp->mNext)
;
pTmp->mNext = pNewField;
pNewField->mNext = NULL;
}
mNewDataType->mAlign = MIN (mPackAlign, MAX (pFieldType->mAlign, mNewDataType->mAlign));
mNewDataType->mTotalSize = pNewField->mOffset + (pNewField->mFieldType->mTotalSize) * ((ArrayNum == 0) ? 1 : ArrayNum);
return VFR_RETURN_SUCCESS;
}
VOID
CVfrVarDataTypeDB::DeclareDataTypeEnd (
VOID
)
{
if (mNewDataType->mTypeName[0] == '\0') {
return;
}
if ((mNewDataType->mTotalSize % mNewDataType->mAlign) !=0) {
mNewDataType->mTotalSize += ALIGN_STUFF (mNewDataType->mTotalSize, mNewDataType->mAlign);
}
RegisterNewType (mNewDataType);
if (mFirstNewDataTypeName == NULL) {
mFirstNewDataTypeName = mNewDataType->mTypeName;
}
mNewDataType = NULL;
}
EFI_VFR_RETURN_CODE
CVfrVarDataTypeDB::GetDataType (
IN CHAR8 *TypeName,
OUT SVfrDataType **DataType
)
{
SVfrDataType *pDataType = NULL;
if (TypeName == NULL) {
return VFR_RETURN_ERROR_SKIPED;
}
if (DataType == NULL) {
return VFR_RETURN_FATAL_ERROR;
}
*DataType = NULL;
for (pDataType = mDataTypeList; pDataType != NULL; pDataType = pDataType->mNext) {
if (strcmp (TypeName, pDataType->mTypeName) == 0) {
*DataType = pDataType;
return VFR_RETURN_SUCCESS;
}
}
return VFR_RETURN_UNDEFINED;
}
EFI_VFR_RETURN_CODE
CVfrVarDataTypeDB::GetDataTypeSize (
IN UINT8 DataType,
OUT UINT32 *Size
)
{
SVfrDataType *pDataType = NULL;
if (Size == NULL) {
return VFR_RETURN_FATAL_ERROR;
}
*Size = 0;
DataType = DataType & 0x0F;
//
// For user defined data type, the size can't be got by this function.
//
if (DataType == EFI_IFR_TYPE_OTHER) {
return VFR_RETURN_SUCCESS;
}
for (pDataType = mDataTypeList; pDataType != NULL; pDataType = pDataType->mNext) {
if (DataType == pDataType->mType) {
*Size = pDataType->mTotalSize;
return VFR_RETURN_SUCCESS;
}
}
return VFR_RETURN_UNDEFINED;
}
EFI_VFR_RETURN_CODE
CVfrVarDataTypeDB::GetDataTypeSize (
IN CHAR8 *TypeName,
OUT UINT32 *Size
)
{
SVfrDataType *pDataType = NULL;
if (Size == NULL) {
return VFR_RETURN_FATAL_ERROR;
}
*Size = 0;
for (pDataType = mDataTypeList; pDataType != NULL; pDataType = pDataType->mNext) {
if (strcmp (TypeName, pDataType->mTypeName) == 0) {
*Size = pDataType->mTotalSize;
return VFR_RETURN_SUCCESS;
}
}
return VFR_RETURN_UNDEFINED;
}
EFI_VFR_RETURN_CODE
CVfrVarDataTypeDB::GetDataFieldInfo (
IN CHAR8 *VarStr,
OUT UINT16 &Offset,
OUT UINT8 &Type,
OUT UINT32 &Size
)
{
CHAR8 TName[MAX_NAME_LEN], FName[MAX_NAME_LEN];
UINT32 ArrayIdx, Tmp;
SVfrDataType *pType = NULL;
SVfrDataField *pField = NULL;
Offset = 0;
Type = EFI_IFR_TYPE_OTHER;
Size = 0;
CHECK_ERROR_RETURN (ExtractStructTypeName (VarStr, TName), VFR_RETURN_SUCCESS);
CHECK_ERROR_RETURN (GetDataType (TName, &pType), VFR_RETURN_SUCCESS);
//
// if it is not struct data type
//
Type = pType->mType;
Size = pType->mTotalSize;
while (*VarStr != '\0') {
CHECK_ERROR_RETURN(ExtractFieldNameAndArrary(VarStr, FName, ArrayIdx), VFR_RETURN_SUCCESS);
CHECK_ERROR_RETURN(GetTypeField (FName, pType, pField), VFR_RETURN_SUCCESS);
pType = pField->mFieldType;
CHECK_ERROR_RETURN(GetFieldOffset (pField, ArrayIdx, Tmp), VFR_RETURN_SUCCESS);
Offset = (UINT16) (Offset + Tmp);
Type = GetFieldWidth (pField);
Size = GetFieldSize (pField, ArrayIdx);
}
return VFR_RETURN_SUCCESS;
}
EFI_VFR_RETURN_CODE
CVfrVarDataTypeDB::GetUserDefinedTypeNameList (
OUT CHAR8 ***NameList,
OUT UINT32 *ListSize
)
{
UINT32 Index;
SVfrDataType *pType;
if ((NameList == NULL) || (ListSize == NULL)) {
return VFR_RETURN_FATAL_ERROR;
}
*NameList = NULL;
*ListSize = 0;
for (pType = mDataTypeList; pType != NULL; pType = pType->mNext) {
if (_IS_INTERNAL_TYPE(pType->mTypeName) == FALSE) {
(*ListSize)++;
}
}
if (*ListSize == 0) {
return VFR_RETURN_SUCCESS;
}
if ((*NameList = new CHAR8*[*ListSize]) == NULL) {
*ListSize = 0;
return VFR_RETURN_OUT_FOR_RESOURCES;
}
for (Index = 0, pType = mDataTypeList; pType != NULL; pType = pType->mNext, Index++) {
if (_IS_INTERNAL_TYPE(pType->mTypeName) == FALSE) {
(*NameList)[Index] = pType->mTypeName;
}
}
return VFR_RETURN_SUCCESS;
}
BOOLEAN
CVfrVarDataTypeDB::IsTypeNameDefined (
IN CHAR8 *TypeName
)
{
SVfrDataType *pType;
if (TypeName == NULL) {
return FALSE;
}
for (pType = mDataTypeList; pType != NULL; pType = pType->mNext) {
if (strcmp (pType->mTypeName, TypeName) == 0) {
return TRUE;
}
}
return FALSE;
}
VOID
CVfrVarDataTypeDB::Dump (
IN FILE *File
)
{
SVfrDataType *pTNode;
SVfrDataField *pFNode;
fprintf (File, "\n\n***************************************************************\n");
fprintf (File, "\t\tmPackAlign = %x\n", mPackAlign);
for (pTNode = mDataTypeList; pTNode != NULL; pTNode = pTNode->mNext) {
fprintf (File, "\t\tstruct %s : mAlign [%d] mTotalSize [0x%x]\n\n", pTNode->mTypeName, pTNode->mAlign, pTNode->mTotalSize);
fprintf (File, "\t\tstruct %s {\n", pTNode->mTypeName);
for (pFNode = pTNode->mMembers; pFNode != NULL; pFNode = pFNode->mNext) {
if (pFNode->mArrayNum > 0) {
fprintf (File, "\t\t\t+%08d[%08x] %s[%d] <%s>\n", pFNode->mOffset, pFNode->mOffset,
pFNode->mFieldName, pFNode->mArrayNum, pFNode->mFieldType->mTypeName);
} else {
fprintf (File, "\t\t\t+%08d[%08x] %s <%s>\n", pFNode->mOffset, pFNode->mOffset,
pFNode->mFieldName, pFNode->mFieldType->mTypeName);
}
}
fprintf (File, "\t\t};\n");
fprintf (File, "---------------------------------------------------------------\n");
}
fprintf (File, "***************************************************************\n");
}
#ifdef CVFR_VARDATATYPEDB_DEBUG
VOID
CVfrVarDataTypeDB::ParserDB (
VOID
)
{
SVfrDataType *pTNode;
SVfrDataField *pFNode;
printf ("***************************************************************\n");
printf ("\t\tmPackAlign = %x\n", mPackAlign);
for (pTNode = mDataTypeList; pTNode != NULL; pTNode = pTNode->mNext) {
printf ("\t\tstruct %s : mAlign [%x] mTotalSize [%x]\n\n", pTNode->mTypeName, pTNode->mAlign, pTNode->mTotalSize);
printf ("\t\tstruct %s {\n", pTNode->mTypeName);
for (pFNode = pTNode->mMembers; pFNode != NULL; pFNode = pFNode->mNext) {
printf ("\t\t\t%s\t%s\n", pFNode->mFieldType->mTypeName, pFNode->mFieldName);
}
printf ("\t\t};\n");
printf ("---------------------------------------------------------------\n");
}
printf ("***************************************************************\n");
}
#endif
SVfrVarStorageNode::SVfrVarStorageNode (
IN EFI_GUID *Guid,
IN CHAR8 *StoreName,
IN EFI_VARSTORE_ID VarStoreId,
IN EFI_STRING_ID VarName,
IN UINT32 VarSize,
IN BOOLEAN Flag
)
{
if (Guid != NULL) {
mGuid = *Guid;
} else {
memset (&Guid, 0, sizeof (EFI_GUID));
}
if (StoreName != NULL) {
mVarStoreName = new CHAR8[strlen(StoreName) + 1];
strcpy (mVarStoreName, StoreName);
} else {
mVarStoreName = NULL;
}
mNext = NULL;
mVarStoreId = VarStoreId;
mVarStoreType = EFI_VFR_VARSTORE_EFI;
mStorageInfo.mEfiVar.mEfiVarName = VarName;
mStorageInfo.mEfiVar.mEfiVarSize = VarSize;
mAssignedFlag = Flag;
}
SVfrVarStorageNode::SVfrVarStorageNode (
IN EFI_GUID *Guid,
IN CHAR8 *StoreName,
IN EFI_VARSTORE_ID VarStoreId,
IN SVfrDataType *DataType,
IN BOOLEAN Flag
)
{
if (Guid != NULL) {
mGuid = *Guid;
} else {
memset (&Guid, 0, sizeof (EFI_GUID));
}
if (StoreName != NULL) {
mVarStoreName = new CHAR8[strlen(StoreName) + 1];
strcpy (mVarStoreName, StoreName);
} else {
mVarStoreName = NULL;
}
mNext = NULL;
mVarStoreId = VarStoreId;
mVarStoreType = EFI_VFR_VARSTORE_BUFFER;
mStorageInfo.mDataType = DataType;
mAssignedFlag = Flag;
}
SVfrVarStorageNode::SVfrVarStorageNode (
IN CHAR8 *StoreName,
IN EFI_VARSTORE_ID VarStoreId
)
{
if (StoreName != NULL) {
mVarStoreName = new CHAR8[strlen(StoreName) + 1];
strcpy (mVarStoreName, StoreName);
} else {
mVarStoreName = NULL;
}
mNext = NULL;
mVarStoreId = VarStoreId;
mVarStoreType = EFI_VFR_VARSTORE_NAME;
mStorageInfo.mNameSpace.mNameTable = new EFI_VARSTORE_ID[DEFAULT_NAME_TABLE_ITEMS];
mStorageInfo.mNameSpace.mTableSize = 0;
}
SVfrVarStorageNode::~SVfrVarStorageNode (
VOID
)
{
if (mVarStoreName != NULL) {
delete mVarStoreName;
}
if (mVarStoreType == EFI_VFR_VARSTORE_NAME) {
delete mStorageInfo.mNameSpace.mNameTable;
}
}
CVfrDataStorage::CVfrDataStorage (
VOID
)
{
UINT32 Index;
for (Index = 0; Index < EFI_FREE_VARSTORE_ID_BITMAP_SIZE; Index++) {
mFreeVarStoreIdBitMap[Index] = 0;
}
// Question ID 0 is reserved.
mFreeVarStoreIdBitMap[0] = 0x80000000;
mBufferVarStoreList = NULL;
mEfiVarStoreList = NULL;
mNameVarStoreList = NULL;
mCurrVarStorageNode = NULL;
mNewVarStorageNode = NULL;
}
CVfrDataStorage::~CVfrDataStorage (
VOID
)
{
SVfrVarStorageNode *pNode;
while (mBufferVarStoreList != NULL) {
pNode = mBufferVarStoreList;
mBufferVarStoreList = mBufferVarStoreList->mNext;
delete pNode;
}
while (mEfiVarStoreList != NULL) {
pNode = mEfiVarStoreList;
mEfiVarStoreList = mEfiVarStoreList->mNext;
delete pNode;
}
while (mNameVarStoreList != NULL) {
pNode = mNameVarStoreList;
mNameVarStoreList = mNameVarStoreList->mNext;
delete pNode;
}
if (mNewVarStorageNode != NULL) {
delete mNewVarStorageNode;
}
}
EFI_VARSTORE_ID
CVfrDataStorage::GetFreeVarStoreId (
EFI_VFR_VARSTORE_TYPE VarType
)
{
UINT32 Index, Mask, Offset;
//
// Assign the different ID range for the different type VarStore to support Framework Vfr
//
Index = 0;
if ((!VfrCompatibleMode) || (VarType == EFI_VFR_VARSTORE_BUFFER)) {
Index = 0;
} else if (VarType == EFI_VFR_VARSTORE_EFI) {
Index = 1;
} else if (VarType == EFI_VFR_VARSTORE_NAME) {
Index = 2;
}
for (; Index < EFI_FREE_VARSTORE_ID_BITMAP_SIZE; Index++) {
if (mFreeVarStoreIdBitMap[Index] != 0xFFFFFFFF) {
break;
}
}
for (Offset = 0, Mask = 0x80000000; Mask != 0; Mask >>= 1, Offset++) {
if ((mFreeVarStoreIdBitMap[Index] & Mask) == 0) {
mFreeVarStoreIdBitMap[Index] |= Mask;
return (EFI_VARSTORE_ID)((Index << EFI_BITS_SHIFT_PER_UINT32) + Offset);
}
}
return EFI_VARSTORE_ID_INVALID;
}
BOOLEAN
CVfrDataStorage::ChekVarStoreIdFree (
IN EFI_VARSTORE_ID VarStoreId
)
{
UINT32 Index = (VarStoreId / EFI_BITS_PER_UINT32);
UINT32 Offset = (VarStoreId % EFI_BITS_PER_UINT32);
return (mFreeVarStoreIdBitMap[Index] & (0x80000000 >> Offset)) == 0;
}
VOID
CVfrDataStorage::MarkVarStoreIdUsed (
IN EFI_VARSTORE_ID VarStoreId
)
{
UINT32 Index = (VarStoreId / EFI_BITS_PER_UINT32);
UINT32 Offset = (VarStoreId % EFI_BITS_PER_UINT32);
mFreeVarStoreIdBitMap[Index] |= (0x80000000 >> Offset);
}
VOID
CVfrDataStorage::MarkVarStoreIdUnused (
IN EFI_VARSTORE_ID VarStoreId
)
{
UINT32 Index = (VarStoreId / EFI_BITS_PER_UINT32);
UINT32 Offset = (VarStoreId % EFI_BITS_PER_UINT32);
mFreeVarStoreIdBitMap[Index] &= ~(0x80000000 >> Offset);
}
EFI_VFR_RETURN_CODE
CVfrDataStorage::DeclareNameVarStoreBegin (
IN CHAR8 *StoreName
)
{
SVfrVarStorageNode *pNode = NULL;
EFI_VARSTORE_ID VarStoreId;
if (StoreName == NULL) {
return VFR_RETURN_FATAL_ERROR;
}
for (pNode = mNameVarStoreList; pNode != NULL; pNode = pNode->mNext) {
if (strcmp (pNode->mVarStoreName, StoreName) == 0) {
return VFR_RETURN_REDEFINED;
}
}
VarStoreId = GetFreeVarStoreId (EFI_VFR_VARSTORE_NAME);
if ((pNode = new SVfrVarStorageNode (StoreName, VarStoreId)) == NULL) {
return VFR_RETURN_UNDEFINED;
}
mNewVarStorageNode = pNode;
return VFR_RETURN_SUCCESS;
}
EFI_VFR_RETURN_CODE
CVfrDataStorage::NameTableAddItem (
IN EFI_STRING_ID Item
)
{
EFI_VARSTORE_ID *NewTable, *OldTable;
UINT32 TableSize;
OldTable = mNewVarStorageNode->mStorageInfo.mNameSpace.mNameTable;
TableSize = mNewVarStorageNode->mStorageInfo.mNameSpace.mTableSize;
if ((TableSize != 0) && ((TableSize % DEFAULT_NAME_TABLE_ITEMS) == 0)) {
if ((NewTable = new EFI_VARSTORE_ID[TableSize + DEFAULT_NAME_TABLE_ITEMS]) == NULL) {
return VFR_RETURN_OUT_FOR_RESOURCES;
}
memcpy (NewTable, OldTable, TableSize);
mNewVarStorageNode->mStorageInfo.mNameSpace.mNameTable = NewTable;
}
mNewVarStorageNode->mStorageInfo.mNameSpace.mNameTable[TableSize++] = Item;
mNewVarStorageNode->mStorageInfo.mNameSpace.mTableSize = TableSize;
return VFR_RETURN_SUCCESS;
}
EFI_VFR_RETURN_CODE
CVfrDataStorage::DeclareNameVarStoreEnd (
IN EFI_GUID *Guid
)
{
mNewVarStorageNode->mGuid = *Guid;
mNewVarStorageNode->mNext = mNameVarStoreList;
mNameVarStoreList = mNewVarStorageNode;
mNewVarStorageNode = NULL;
return VFR_RETURN_SUCCESS;
}
EFI_VFR_RETURN_CODE
CVfrDataStorage::DeclareEfiVarStore (
IN CHAR8 *StoreName,
IN EFI_GUID *Guid,
IN EFI_STRING_ID NameStrId,
IN UINT32 VarSize,
IN BOOLEAN Flag
)
{
SVfrVarStorageNode *pNode;
EFI_VARSTORE_ID VarStoreId;
if ((StoreName == NULL) || (Guid == NULL)) {
return VFR_RETURN_FATAL_ERROR;
}
if (VarSize > sizeof (UINT64)) {
return VFR_RETURN_EFIVARSTORE_SIZE_ERROR;
}
for (pNode = mEfiVarStoreList; pNode != NULL; pNode = pNode->mNext) {
if (strcmp (pNode->mVarStoreName, StoreName) == 0) {
return VFR_RETURN_REDEFINED;
}
}
VarStoreId = GetFreeVarStoreId (EFI_VFR_VARSTORE_EFI);
if ((pNode = new SVfrVarStorageNode (Guid, StoreName, VarStoreId, NameStrId, VarSize, Flag)) == NULL) {
return VFR_RETURN_OUT_FOR_RESOURCES;
}
pNode->mNext = mEfiVarStoreList;
mEfiVarStoreList = pNode;
return VFR_RETURN_SUCCESS;
}
EFI_VFR_RETURN_CODE
CVfrDataStorage::DeclareBufferVarStore (
IN CHAR8 *StoreName,
IN EFI_GUID *Guid,
IN CVfrVarDataTypeDB *DataTypeDB,
IN CHAR8 *TypeName,
IN EFI_VARSTORE_ID VarStoreId,
IN BOOLEAN Flag
)
{
SVfrVarStorageNode *pNew = NULL;
SVfrDataType *pDataType = NULL;
if ((StoreName == NULL) || (Guid == NULL) || (DataTypeDB == NULL)) {
return VFR_RETURN_FATAL_ERROR;
}
CHECK_ERROR_RETURN(DataTypeDB->GetDataType (TypeName, &pDataType), VFR_RETURN_SUCCESS);
if (VarStoreId == EFI_VARSTORE_ID_INVALID) {
VarStoreId = GetFreeVarStoreId (EFI_VFR_VARSTORE_BUFFER);
} else {
if (ChekVarStoreIdFree (VarStoreId) == FALSE) {
return VFR_RETURN_VARSTOREID_REDEFINED;
}
MarkVarStoreIdUsed (VarStoreId);
}
if ((pNew = new SVfrVarStorageNode (Guid, StoreName, VarStoreId, pDataType, Flag)) == NULL) {
return VFR_RETURN_OUT_FOR_RESOURCES;
}
pNew->mNext = mBufferVarStoreList;
mBufferVarStoreList = pNew;
if (gCVfrBufferConfig.Register(StoreName) != 0) {
return VFR_RETURN_FATAL_ERROR;
}
return VFR_RETURN_SUCCESS;
}
EFI_VFR_RETURN_CODE
CVfrDataStorage::GetVarStoreId (
IN CHAR8 *StoreName,
OUT EFI_VARSTORE_ID *VarStoreId
)
{
SVfrVarStorageNode *pNode;
for (pNode = mBufferVarStoreList; pNode != NULL; pNode = pNode->mNext) {
if (strcmp (pNode->mVarStoreName, StoreName) == 0) {
mCurrVarStorageNode = pNode;
*VarStoreId = pNode->mVarStoreId;
return VFR_RETURN_SUCCESS;
}
}
for (pNode = mEfiVarStoreList; pNode != NULL; pNode = pNode->mNext) {
if (strcmp (pNode->mVarStoreName, StoreName) == 0) {
mCurrVarStorageNode = pNode;
*VarStoreId = pNode->mVarStoreId;
return VFR_RETURN_SUCCESS;
}
}
for (pNode = mNameVarStoreList; pNode != NULL; pNode = pNode->mNext) {
if (strcmp (pNode->mVarStoreName, StoreName) == 0) {
mCurrVarStorageNode = pNode;
*VarStoreId = pNode->mVarStoreId;
return VFR_RETURN_SUCCESS;
}
}
mCurrVarStorageNode = NULL;
*VarStoreId = EFI_VARSTORE_ID_INVALID;
return VFR_RETURN_UNDEFINED;
}
EFI_VFR_RETURN_CODE
CVfrDataStorage::GetBufferVarStoreDataTypeName (
IN CHAR8 *StoreName,
OUT CHAR8 **DataTypeName
)
{
SVfrVarStorageNode *pNode;
if ((StoreName == NULL) || (DataTypeName == NULL)) {
return VFR_RETURN_FATAL_ERROR;
}
for (pNode = mBufferVarStoreList; pNode != NULL; pNode = pNode->mNext) {
if (strcmp (pNode->mVarStoreName, StoreName) == 0) {
break;
}
}
if (pNode == NULL) {
return VFR_RETURN_UNDEFINED;
}
if (pNode->mStorageInfo.mDataType == NULL) {
return VFR_RETURN_FATAL_ERROR;
}
*DataTypeName = pNode->mStorageInfo.mDataType->mTypeName;
return VFR_RETURN_SUCCESS;
}
EFI_VFR_RETURN_CODE
CVfrDataStorage::GetVarStoreType (
IN CHAR8 *StoreName,
OUT EFI_VFR_VARSTORE_TYPE &VarStoreType
)
{
SVfrVarStorageNode *pNode;
if (StoreName == NULL) {
return VFR_RETURN_FATAL_ERROR;
}
for (pNode = mBufferVarStoreList; pNode != NULL; pNode = pNode->mNext) {
if (strcmp (pNode->mVarStoreName, StoreName) == 0) {
VarStoreType = pNode->mVarStoreType;
return VFR_RETURN_SUCCESS;
}
}
for (pNode = mEfiVarStoreList; pNode != NULL; pNode = pNode->mNext) {
if (strcmp (pNode->mVarStoreName, StoreName) == 0) {
VarStoreType = pNode->mVarStoreType;
return VFR_RETURN_SUCCESS;
}
}
for (pNode = mNameVarStoreList; pNode != NULL; pNode = pNode->mNext) {
if (strcmp (pNode->mVarStoreName, StoreName) == 0) {
VarStoreType = pNode->mVarStoreType;
return VFR_RETURN_SUCCESS;
}
}
VarStoreType = EFI_VFR_VARSTORE_INVALID;
return VFR_RETURN_UNDEFINED;
}
EFI_VFR_VARSTORE_TYPE
CVfrDataStorage::GetVarStoreType (
IN EFI_VARSTORE_ID VarStoreId
)
{
SVfrVarStorageNode *pNode;
EFI_VFR_VARSTORE_TYPE VarStoreType;
VarStoreType = EFI_VFR_VARSTORE_INVALID;
if (VarStoreId == EFI_VARSTORE_ID_INVALID) {
return VarStoreType;
}
for (pNode = mBufferVarStoreList; pNode != NULL; pNode = pNode->mNext) {
if (pNode->mVarStoreId == VarStoreId) {
VarStoreType = pNode->mVarStoreType;
return VarStoreType;
}
}
for (pNode = mEfiVarStoreList; pNode != NULL; pNode = pNode->mNext) {
if (pNode->mVarStoreId == VarStoreId) {
VarStoreType = pNode->mVarStoreType;
return VarStoreType;
}
}
for (pNode = mNameVarStoreList; pNode != NULL; pNode = pNode->mNext) {
if (pNode->mVarStoreId == VarStoreId) {
VarStoreType = pNode->mVarStoreType;
return VarStoreType;
}
}
return VarStoreType;
}
EFI_VFR_RETURN_CODE
CVfrDataStorage::GetVarStoreName (
IN EFI_VARSTORE_ID VarStoreId,
OUT CHAR8 **VarStoreName
)
{
SVfrVarStorageNode *pNode;
if (VarStoreName == NULL) {
return VFR_RETURN_FATAL_ERROR;
}
for (pNode = mBufferVarStoreList; pNode != NULL; pNode = pNode->mNext) {
if (pNode->mVarStoreId == VarStoreId) {
*VarStoreName = pNode->mVarStoreName;
return VFR_RETURN_SUCCESS;
}
}
for (pNode = mEfiVarStoreList; pNode != NULL; pNode = pNode->mNext) {
if (pNode->mVarStoreId == VarStoreId) {
*VarStoreName = pNode->mVarStoreName;
return VFR_RETURN_SUCCESS;
}
}
for (pNode = mNameVarStoreList; pNode != NULL; pNode = pNode->mNext) {
if (pNode->mVarStoreId == VarStoreId) {
*VarStoreName = pNode->mVarStoreName;
return VFR_RETURN_SUCCESS;
}
}
*VarStoreName = NULL;
return VFR_RETURN_UNDEFINED;
}
EFI_VFR_RETURN_CODE
CVfrDataStorage::GetEfiVarStoreInfo (
IN OUT EFI_VARSTORE_INFO *Info
)
{
if (Info == NULL) {
return VFR_RETURN_FATAL_ERROR;
}
if (mCurrVarStorageNode == NULL) {
return VFR_RETURN_GET_EFIVARSTORE_ERROR;
}
Info->mInfo.mVarName = mCurrVarStorageNode->mStorageInfo.mEfiVar.mEfiVarName;
Info->mVarTotalSize = mCurrVarStorageNode->mStorageInfo.mEfiVar.mEfiVarSize;
switch (Info->mVarTotalSize) {
case 1:
Info->mVarType = EFI_IFR_TYPE_NUM_SIZE_8;
break;
case 2:
Info->mVarType = EFI_IFR_TYPE_NUM_SIZE_16;
break;
case 4:
Info->mVarType = EFI_IFR_TYPE_NUM_SIZE_32;
break;
case 8:
Info->mVarType = EFI_IFR_TYPE_NUM_SIZE_64;
break;
default :
return VFR_RETURN_FATAL_ERROR;
}
return VFR_RETURN_SUCCESS;
}
EFI_VFR_RETURN_CODE
CVfrDataStorage::GetNameVarStoreInfo (
OUT EFI_VARSTORE_INFO *Info,
IN UINT32 Index
)
{
if (Info == NULL) {
return VFR_RETURN_FATAL_ERROR;
}
if (mCurrVarStorageNode == NULL) {
return VFR_RETURN_GET_NVVARSTORE_ERROR;
}
//
// Framework Vfr file Index is from 1, but Uefi Vfr file Index is from 0.
//
if (VfrCompatibleMode) {
if (Index == 0) {
return VFR_RETURN_ERROR_ARRARY_NUM;
}
Index --;
}
Info->mInfo.mVarName = mCurrVarStorageNode->mStorageInfo.mNameSpace.mNameTable[Index];
return VFR_RETURN_SUCCESS;
}
EFI_VFR_RETURN_CODE
CVfrDataStorage::BufferVarStoreRequestElementAdd (
IN CHAR8 *StoreName,
IN EFI_VARSTORE_INFO &Info
)
{
SVfrVarStorageNode *pNode = NULL;
EFI_IFR_TYPE_VALUE Value = gZeroEfiIfrTypeValue;
for (pNode = mBufferVarStoreList; pNode != NULL; pNode = pNode->mNext) {
if (strcmp (pNode->mVarStoreName, StoreName) == 0) {
break;
}
}
if (pNode == NULL) {
return VFR_RETURN_UNDEFINED;
}
gCVfrBufferConfig.Open ();
Value.u8 = 0;
if (gCVfrBufferConfig.Write ('a', StoreName, NULL, EFI_IFR_TYPE_NUM_SIZE_8, Info.mInfo.mVarOffset, Info.mVarTotalSize, Value) != 0) {
return VFR_RETURN_FATAL_ERROR;
}
gCVfrBufferConfig.Close ();
return VFR_RETURN_SUCCESS;
}
SVfrDefaultStoreNode::SVfrDefaultStoreNode (
IN EFI_IFR_DEFAULTSTORE *ObjBinAddr,
IN CHAR8 *RefName,
IN EFI_STRING_ID DefaultStoreNameId,
IN UINT16 DefaultId
)
{
mObjBinAddr = ObjBinAddr;
if (RefName != NULL) {
mRefName = new CHAR8[strlen (RefName) + 1];
strcpy (mRefName, RefName);
} else {
mRefName = NULL;
}
mNext = NULL;
mDefaultId = DefaultId;
mDefaultStoreNameId = DefaultStoreNameId;
}
SVfrDefaultStoreNode::~SVfrDefaultStoreNode (
VOID
)
{
if (mRefName != NULL) {
delete mRefName;
}
}
CVfrDefaultStore::CVfrDefaultStore (
VOID
)
{
mDefaultStoreList = NULL;
}
CVfrDefaultStore::~CVfrDefaultStore (
VOID
)
{
SVfrDefaultStoreNode *pTmp = NULL;
while (mDefaultStoreList != NULL) {
pTmp = mDefaultStoreList;
mDefaultStoreList = mDefaultStoreList->mNext;
delete pTmp;
}
}
EFI_VFR_RETURN_CODE
CVfrDefaultStore::RegisterDefaultStore (
IN CHAR8 *ObjBinAddr,
IN CHAR8 *RefName,
IN EFI_STRING_ID DefaultStoreNameId,
IN UINT16 DefaultId
)
{
SVfrDefaultStoreNode *pNode = NULL;
if (RefName == NULL) {
return VFR_RETURN_FATAL_ERROR;
}
for (pNode = mDefaultStoreList; pNode != NULL; pNode = pNode->mNext) {
if (strcmp (pNode->mRefName, RefName) == 0) {
return VFR_RETURN_REDEFINED;
}
}
if ((pNode = new SVfrDefaultStoreNode ((EFI_IFR_DEFAULTSTORE *)ObjBinAddr, RefName, DefaultStoreNameId, DefaultId)) == NULL) {
return VFR_RETURN_OUT_FOR_RESOURCES;
}
pNode->mNext = mDefaultStoreList;
mDefaultStoreList = pNode;
return VFR_RETURN_SUCCESS;
}
/*
* assign new reference name or new default store name id only if
* the original is invalid
*/
EFI_VFR_RETURN_CODE
CVfrDefaultStore::ReRegisterDefaultStoreById (
IN UINT16 DefaultId,
IN CHAR8 *RefName,
IN EFI_STRING_ID DefaultStoreNameId
)
{
SVfrDefaultStoreNode *pNode = NULL;
for (pNode = mDefaultStoreList; pNode != NULL; pNode = pNode->mNext) {
if (pNode->mDefaultId == DefaultId) {
break;
}
}
if (pNode == NULL) {
return VFR_RETURN_UNDEFINED;
} else {
if (pNode->mDefaultStoreNameId == EFI_STRING_ID_INVALID) {
pNode->mDefaultStoreNameId = DefaultStoreNameId;
if (pNode->mObjBinAddr != NULL) {
pNode->mObjBinAddr->DefaultName = DefaultStoreNameId;
}
} else {
return VFR_RETURN_REDEFINED;
}
if (RefName != NULL) {
delete pNode->mRefName;
pNode->mRefName = new CHAR8[strlen (RefName) + 1];
if (pNode->mRefName != NULL) {
strcpy (pNode->mRefName, RefName);
}
}
}
return VFR_RETURN_SUCCESS;
}
BOOLEAN
CVfrDefaultStore::DefaultIdRegistered (
IN UINT16 DefaultId
)
{
SVfrDefaultStoreNode *pNode = NULL;
for (pNode = mDefaultStoreList; pNode != NULL; pNode = pNode->mNext) {
if (pNode->mDefaultId == DefaultId) {
return TRUE;
}
}
return FALSE;
}
EFI_VFR_RETURN_CODE
CVfrDefaultStore::GetDefaultId (
IN CHAR8 *RefName,
OUT UINT16 *DefaultId
)
{
SVfrDefaultStoreNode *pTmp = NULL;
if (DefaultId == NULL) {
return VFR_RETURN_FATAL_ERROR;
}
for (pTmp = mDefaultStoreList; pTmp != NULL; pTmp = pTmp->mNext) {
if (strcmp (pTmp->mRefName, RefName) == 0) {
*DefaultId = pTmp->mDefaultId;
return VFR_RETURN_SUCCESS;
}
}
return VFR_RETURN_UNDEFINED;
}
EFI_VFR_RETURN_CODE
CVfrDefaultStore::BufferVarStoreAltConfigAdd (
IN EFI_VARSTORE_ID DefaultId,
IN EFI_VARSTORE_INFO &Info,
IN CHAR8 *VarStoreName,
IN UINT8 Type,
IN EFI_IFR_TYPE_VALUE Value
)
{
SVfrDefaultStoreNode *pNode = NULL;
CHAR8 NewAltCfg[2 * 2 * sizeof (UINT16) + 1] = {0,};
INTN Returnvalue = 0;
if (VarStoreName == NULL) {
return VFR_RETURN_FATAL_ERROR;
}
for (pNode = mDefaultStoreList; pNode != NULL; pNode = pNode->mNext) {
if (pNode->mDefaultId == DefaultId) {
break;
}
}
if (pNode == NULL) {
return VFR_RETURN_UNDEFINED;
}
gCVfrBufferConfig.Open ();
sprintf (NewAltCfg, "%04x", pNode->mDefaultId);
if ((Returnvalue = gCVfrBufferConfig.Select(VarStoreName)) == 0) {
if ((Returnvalue = gCVfrBufferConfig.Write ('a', VarStoreName, NewAltCfg, Type, Info.mInfo.mVarOffset, Info.mVarTotalSize, Value)) != 0) {
goto WriteError;
}
}
gCVfrBufferConfig.Close ();
return VFR_RETURN_SUCCESS;
WriteError:
gCVfrBufferConfig.Close ();
return (EFI_VFR_RETURN_CODE)Returnvalue;
}
SVfrRuleNode::SVfrRuleNode (
IN CHAR8 *RuleName,
IN UINT8 RuleId
)
{
if (RuleName != NULL) {
mRuleName = new CHAR8[strlen (RuleName) + 1];
strcpy (mRuleName, RuleName);
} else {
mRuleName = NULL;
}
mNext = NULL;
mRuleId = RuleId;
}
SVfrRuleNode::~SVfrRuleNode (
VOID
)
{
if (mRuleName != NULL) {
delete mRuleName;
}
}
CVfrRulesDB::CVfrRulesDB ()
{
mRuleList = NULL;
mFreeRuleId = EFI_VARSTORE_ID_START;
}
CVfrRulesDB::~CVfrRulesDB ()
{
SVfrRuleNode *pNode;
while(mRuleList != NULL) {
pNode = mRuleList;
mRuleList = mRuleList->mNext;
delete pNode;
}
}
VOID
CVfrRulesDB::RegisterRule (
IN CHAR8 *RuleName
)
{
SVfrRuleNode *pNew;
if (RuleName == NULL) {
return ;
}
if ((pNew = new SVfrRuleNode (RuleName, mFreeRuleId)) == NULL) {
return ;
}
mFreeRuleId++;
pNew->mNext = mRuleList;
mRuleList = pNew;
}
UINT8
CVfrRulesDB::GetRuleId (
IN CHAR8 *RuleName
)
{
SVfrRuleNode *pNode;
if (RuleName == NULL) {
return EFI_RULE_ID_INVALID;
}
for (pNode = mRuleList; pNode != NULL; pNode = pNode->mNext) {
if (strcmp (pNode->mRuleName, RuleName) == 0) {
return pNode->mRuleId;
}
}
return EFI_RULE_ID_INVALID;
}
CVfrRulesDB gCVfrRulesDB;
EFI_VARSTORE_INFO::EFI_VARSTORE_INFO (
VOID
)
{
mVarStoreId = EFI_VARSTORE_ID_INVALID;
mInfo.mVarName = EFI_STRING_ID_INVALID;
mInfo.mVarOffset = EFI_VAROFFSET_INVALID;
mVarType = EFI_IFR_TYPE_OTHER;
mVarTotalSize = 0;
}
EFI_VARSTORE_INFO::EFI_VARSTORE_INFO (
IN EFI_VARSTORE_INFO &Info
)
{
mVarStoreId = Info.mVarStoreId;
mInfo.mVarName = Info.mInfo.mVarName;
mInfo.mVarOffset = Info.mInfo.mVarOffset;
mVarType = Info.mVarType;
mVarTotalSize = Info.mVarTotalSize;
}
BOOLEAN
EFI_VARSTORE_INFO::operator == (
IN EFI_VARSTORE_INFO *Info
)
{
if ((mVarStoreId == Info->mVarStoreId) &&
(mInfo.mVarName == Info->mInfo.mVarName) &&
(mInfo.mVarOffset == Info->mInfo.mVarOffset) &&
(mVarType == Info->mVarType) &&
(mVarTotalSize == Info->mVarTotalSize)) {
return TRUE;
}
return FALSE;
}
static EFI_VARSTORE_INFO gEfiInvalidVarStoreInfo;
EFI_QUESTION_ID
CVfrQuestionDB::GetFreeQuestionId (
VOID
)
{
UINT32 Index, Mask, Offset;
for (Index = 0; Index < EFI_FREE_QUESTION_ID_BITMAP_SIZE; Index++) {
if (mFreeQIdBitMap[Index] != 0xFFFFFFFF) {
break;
}
}
for (Offset = 0, Mask = 0x80000000; Mask != 0; Mask >>= 1, Offset++) {
if ((mFreeQIdBitMap[Index] & Mask) == 0) {
mFreeQIdBitMap[Index] |= Mask;
return (EFI_QUESTION_ID)((Index << EFI_BITS_SHIFT_PER_UINT32) + Offset);
}
}
return EFI_QUESTION_ID_INVALID;
}
BOOLEAN
CVfrQuestionDB::ChekQuestionIdFree (
IN EFI_QUESTION_ID QId
)
{
UINT32 Index = (QId / EFI_BITS_PER_UINT32);
UINT32 Offset = (QId % EFI_BITS_PER_UINT32);
return (mFreeQIdBitMap[Index] & (0x80000000 >> Offset)) == 0;
}
VOID
CVfrQuestionDB::MarkQuestionIdUsed (
IN EFI_QUESTION_ID QId
)
{
UINT32 Index = (QId / EFI_BITS_PER_UINT32);
UINT32 Offset = (QId % EFI_BITS_PER_UINT32);
mFreeQIdBitMap[Index] |= (0x80000000 >> Offset);
}
VOID
CVfrQuestionDB::MarkQuestionIdUnused (
IN EFI_QUESTION_ID QId
)
{
UINT32 Index = (QId / EFI_BITS_PER_UINT32);
UINT32 Offset = (QId % EFI_BITS_PER_UINT32);
mFreeQIdBitMap[Index] &= ~(0x80000000 >> Offset);
}
SVfrQuestionNode::SVfrQuestionNode (
IN CHAR8 *Name,
IN CHAR8 *VarIdStr,
IN UINT32 BitMask
)
{
mName = NULL;
mVarIdStr = NULL;
mQuestionId = EFI_QUESTION_ID_INVALID;
mBitMask = BitMask;
mNext = NULL;
mQtype = QUESTION_NORMAL;
if (Name == NULL) {
mName = new CHAR8[strlen ("$DEFAULT") + 1];
strcpy (mName, "$DEFAULT");
} else {
mName = new CHAR8[strlen (Name) + 1];
strcpy (mName, Name);
}
if (VarIdStr != NULL) {
mVarIdStr = new CHAR8[strlen (VarIdStr) + 1];
strcpy (mVarIdStr, VarIdStr);
} else {
mVarIdStr = new CHAR8[strlen ("$") + 1];
strcpy (mVarIdStr, "$");
}
}
SVfrQuestionNode::~SVfrQuestionNode (
VOID
)
{
if (mName != NULL) {
delete mName;
}
if (mVarIdStr != NULL) {
delete mVarIdStr;
}
}
CVfrQuestionDB::CVfrQuestionDB ()
{
UINT32 Index;
for (Index = 0; Index < EFI_FREE_QUESTION_ID_BITMAP_SIZE; Index++) {
mFreeQIdBitMap[Index] = 0;
}
// Question ID 0 is reserved.
mFreeQIdBitMap[0] = 0x80000000;
mQuestionList = NULL;
}
CVfrQuestionDB::~CVfrQuestionDB ()
{
SVfrQuestionNode *pNode;
while (mQuestionList != NULL) {
pNode = mQuestionList;
mQuestionList = mQuestionList->mNext;
delete pNode;
}
}
//
// Reset to init state
//
VOID
CVfrQuestionDB::ResetInit(
IN VOID
)
{
UINT32 Index;
SVfrQuestionNode *pNode;
while (mQuestionList != NULL) {
pNode = mQuestionList;
mQuestionList = mQuestionList->mNext;
delete pNode;
}
for (Index = 0; Index < EFI_FREE_QUESTION_ID_BITMAP_SIZE; Index++) {
mFreeQIdBitMap[Index] = 0;
}
// Question ID 0 is reserved.
mFreeQIdBitMap[0] = 0x80000000;
mQuestionList = NULL;
}
VOID
CVfrQuestionDB::PrintAllQuestion (
VOID
)
{
SVfrQuestionNode *pNode = NULL;
for (pNode = mQuestionList; pNode != NULL; pNode = pNode->mNext) {
printf ("Question VarId is %s and QuesitonId is 0x%x\n", pNode->mVarIdStr, pNode->mQuestionId);
}
}
EFI_VFR_RETURN_CODE
CVfrQuestionDB::RegisterQuestion (
IN CHAR8 *Name,
IN CHAR8 *VarIdStr,
IN OUT EFI_QUESTION_ID &QuestionId
)
{
SVfrQuestionNode *pNode = NULL;
if ((Name != NULL) && (FindQuestion(Name) == VFR_RETURN_SUCCESS)) {
return VFR_RETURN_REDEFINED;
}
if ((pNode = new SVfrQuestionNode (Name, VarIdStr)) == NULL) {
return VFR_RETURN_OUT_FOR_RESOURCES;
}
if (QuestionId == EFI_QUESTION_ID_INVALID) {
QuestionId = GetFreeQuestionId ();
} else {
//
// For Framework Vfr, don't check question ID conflict.
//
if (!VfrCompatibleMode && ChekQuestionIdFree (QuestionId) == FALSE) {
delete pNode;
return VFR_RETURN_QUESTIONID_REDEFINED;
}
MarkQuestionIdUsed (QuestionId);
}
pNode->mQuestionId = QuestionId;
pNode->mNext = mQuestionList;
mQuestionList = pNode;
gCFormPkg.DoPendingAssign (VarIdStr, (VOID *)&QuestionId, sizeof(EFI_QUESTION_ID));
return VFR_RETURN_SUCCESS;
}
VOID
CVfrQuestionDB::RegisterOldDateQuestion (
IN CHAR8 *YearVarId,
IN CHAR8 *MonthVarId,
IN CHAR8 *DayVarId,
IN OUT EFI_QUESTION_ID &QuestionId
)
{
SVfrQuestionNode *pNode[3] = {NULL, };
UINT32 Index;
if ((YearVarId == NULL) || (MonthVarId == NULL) || (DayVarId == NULL)) {
return;
}
if ((pNode[0] = new SVfrQuestionNode (NULL, YearVarId, DATE_YEAR_BITMASK)) == NULL) {
goto Err;
}
if ((pNode[1] = new SVfrQuestionNode (NULL, MonthVarId, DATE_MONTH_BITMASK)) == NULL) {
goto Err;
}
if ((pNode[2] = new SVfrQuestionNode (NULL, DayVarId, DATE_DAY_BITMASK)) == NULL) {
goto Err;
}
if (QuestionId == EFI_QUESTION_ID_INVALID) {
QuestionId = GetFreeQuestionId ();
} else {
if (ChekQuestionIdFree (QuestionId) == FALSE) {
goto Err;
}
MarkQuestionIdUsed (QuestionId);
}
pNode[0]->mQuestionId = QuestionId;
pNode[1]->mQuestionId = QuestionId;
pNode[2]->mQuestionId = QuestionId;
pNode[0]->mQtype = QUESTION_DATE;
pNode[1]->mQtype = QUESTION_DATE;
pNode[2]->mQtype = QUESTION_DATE;
pNode[0]->mNext = pNode[1];
pNode[1]->mNext = pNode[2];
pNode[2]->mNext = mQuestionList;
mQuestionList = pNode[0];
gCFormPkg.DoPendingAssign (YearVarId, (VOID *)&QuestionId, sizeof(EFI_QUESTION_ID));
gCFormPkg.DoPendingAssign (MonthVarId, (VOID *)&QuestionId, sizeof(EFI_QUESTION_ID));
gCFormPkg.DoPendingAssign (DayVarId, (VOID *)&QuestionId, sizeof(EFI_QUESTION_ID));
return;
Err:
for (Index = 0; Index < 3; Index++) {
if (pNode[Index] != NULL) {
delete pNode[Index];
}
}
QuestionId = EFI_QUESTION_ID_INVALID;
}
VOID
CVfrQuestionDB::RegisterNewDateQuestion (
IN CHAR8 *Name,
IN CHAR8 *BaseVarId,
IN OUT EFI_QUESTION_ID &QuestionId
)
{
SVfrQuestionNode *pNode[3] = {NULL, };
UINT32 Len;
CHAR8 *VarIdStr[3] = {NULL, };
CHAR8 Index;
if (BaseVarId == NULL) {
return;
}
Len = strlen (BaseVarId);
VarIdStr[0] = new CHAR8[Len + strlen (".Year") + 1];
if (VarIdStr[0] != NULL) {
strcpy (VarIdStr[0], BaseVarId);
strcat (VarIdStr[0], ".Year");
}
VarIdStr[1] = new CHAR8[Len + strlen (".Month") + 1];
if (VarIdStr[1] != NULL) {
strcpy (VarIdStr[1], BaseVarId);
strcat (VarIdStr[1], ".Month");
}
VarIdStr[2] = new CHAR8[Len + strlen (".Day") + 1];
if (VarIdStr[2] != NULL) {
strcpy (VarIdStr[2], BaseVarId);
strcat (VarIdStr[2], ".Day");
}
if ((pNode[0] = new SVfrQuestionNode (Name, VarIdStr[0], DATE_YEAR_BITMASK)) == NULL) {
goto Err;
}
if ((pNode[1] = new SVfrQuestionNode (Name, VarIdStr[1], DATE_MONTH_BITMASK)) == NULL) {
goto Err;
}
if ((pNode[2] = new SVfrQuestionNode (Name, VarIdStr[2], DATE_DAY_BITMASK)) == NULL) {
goto Err;
}
if (QuestionId == EFI_QUESTION_ID_INVALID) {
QuestionId = GetFreeQuestionId ();
} else {
if (ChekQuestionIdFree (QuestionId) == FALSE) {
goto Err;
}
MarkQuestionIdUsed (QuestionId);
}
pNode[0]->mQuestionId = QuestionId;
pNode[1]->mQuestionId = QuestionId;
pNode[2]->mQuestionId = QuestionId;
pNode[0]->mQtype = QUESTION_DATE;
pNode[1]->mQtype = QUESTION_DATE;
pNode[2]->mQtype = QUESTION_DATE;
pNode[0]->mNext = pNode[1];
pNode[1]->mNext = pNode[2];
pNode[2]->mNext = mQuestionList;
mQuestionList = pNode[0];
for (Index = 0; Index < 3; Index++) {
if (VarIdStr[Index] != NULL) {
delete VarIdStr[Index];
}
}
gCFormPkg.DoPendingAssign (VarIdStr[0], (VOID *)&QuestionId, sizeof(EFI_QUESTION_ID));
gCFormPkg.DoPendingAssign (VarIdStr[1], (VOID *)&QuestionId, sizeof(EFI_QUESTION_ID));
gCFormPkg.DoPendingAssign (VarIdStr[2], (VOID *)&QuestionId, sizeof(EFI_QUESTION_ID));
return;
Err:
for (Index = 0; Index < 3; Index++) {
if (pNode[Index] != NULL) {
delete pNode[Index];
}
if (VarIdStr[Index] != NULL) {
delete VarIdStr[Index];
}
}
}
VOID
CVfrQuestionDB::RegisterOldTimeQuestion (
IN CHAR8 *HourVarId,
IN CHAR8 *MinuteVarId,
IN CHAR8 *SecondVarId,
IN OUT EFI_QUESTION_ID &QuestionId
)
{
SVfrQuestionNode *pNode[3] = {NULL, };
UINT32 Index;
if ((HourVarId == NULL) || (MinuteVarId == NULL) || (SecondVarId == NULL)) {
return;
}
if ((pNode[0] = new SVfrQuestionNode (NULL, HourVarId, TIME_HOUR_BITMASK)) == NULL) {
goto Err;
}
if ((pNode[1] = new SVfrQuestionNode (NULL, MinuteVarId, TIME_MINUTE_BITMASK)) == NULL) {
goto Err;
}
if ((pNode[2] = new SVfrQuestionNode (NULL, SecondVarId, TIME_SECOND_BITMASK)) == NULL) {
goto Err;
}
if (QuestionId == EFI_QUESTION_ID_INVALID) {
QuestionId = GetFreeQuestionId ();
} else {
if (ChekQuestionIdFree (QuestionId) == FALSE) {
goto Err;
}
MarkQuestionIdUsed (QuestionId);
}
pNode[0]->mQuestionId = QuestionId;
pNode[1]->mQuestionId = QuestionId;
pNode[2]->mQuestionId = QuestionId;
pNode[0]->mQtype = QUESTION_TIME;
pNode[1]->mQtype = QUESTION_TIME;
pNode[2]->mQtype = QUESTION_TIME;
pNode[0]->mNext = pNode[1];
pNode[1]->mNext = pNode[2];
pNode[2]->mNext = mQuestionList;
mQuestionList = pNode[0];
gCFormPkg.DoPendingAssign (HourVarId, (VOID *)&QuestionId, sizeof(EFI_QUESTION_ID));
gCFormPkg.DoPendingAssign (MinuteVarId, (VOID *)&QuestionId, sizeof(EFI_QUESTION_ID));
gCFormPkg.DoPendingAssign (SecondVarId, (VOID *)&QuestionId, sizeof(EFI_QUESTION_ID));
return;
Err:
for (Index = 0; Index < 3; Index++) {
if (pNode[Index] != NULL) {
delete pNode[Index];
}
}
QuestionId = EFI_QUESTION_ID_INVALID;
}
VOID
CVfrQuestionDB::RegisterNewTimeQuestion (
IN CHAR8 *Name,
IN CHAR8 *BaseVarId,
IN OUT EFI_QUESTION_ID &QuestionId
)
{
SVfrQuestionNode *pNode[3] = {NULL, };
UINT32 Len;
CHAR8 *VarIdStr[3] = {NULL, };
CHAR8 Index;
if (BaseVarId == NULL) {
return;
}
Len = strlen (BaseVarId);
VarIdStr[0] = new CHAR8[Len + strlen (".Hour") + 1];
if (VarIdStr[0] != NULL) {
strcpy (VarIdStr[0], BaseVarId);
strcat (VarIdStr[0], ".Hour");
}
VarIdStr[1] = new CHAR8[Len + strlen (".Minute") + 1];
if (VarIdStr[1] != NULL) {
strcpy (VarIdStr[1], BaseVarId);
strcat (VarIdStr[1], ".Minute");
}
VarIdStr[2] = new CHAR8[Len + strlen (".Second") + 1];
if (VarIdStr[2] != NULL) {
strcpy (VarIdStr[2], BaseVarId);
strcat (VarIdStr[2], ".Second");
}
if ((pNode[0] = new SVfrQuestionNode (Name, VarIdStr[0], TIME_HOUR_BITMASK)) == NULL) {
goto Err;
}
if ((pNode[1] = new SVfrQuestionNode (Name, VarIdStr[1], TIME_MINUTE_BITMASK)) == NULL) {
goto Err;
}
if ((pNode[2] = new SVfrQuestionNode (Name, VarIdStr[2], TIME_SECOND_BITMASK)) == NULL) {
goto Err;
}
if (QuestionId == EFI_QUESTION_ID_INVALID) {
QuestionId = GetFreeQuestionId ();
} else {
if (ChekQuestionIdFree (QuestionId) == FALSE) {
goto Err;
}
MarkQuestionIdUsed (QuestionId);
}
pNode[0]->mQuestionId = QuestionId;
pNode[1]->mQuestionId = QuestionId;
pNode[2]->mQuestionId = QuestionId;
pNode[0]->mQtype = QUESTION_TIME;
pNode[1]->mQtype = QUESTION_TIME;
pNode[2]->mQtype = QUESTION_TIME;
pNode[0]->mNext = pNode[1];
pNode[1]->mNext = pNode[2];
pNode[2]->mNext = mQuestionList;
mQuestionList = pNode[0];
for (Index = 0; Index < 3; Index++) {
if (VarIdStr[Index] != NULL) {
delete VarIdStr[Index];
}
}
gCFormPkg.DoPendingAssign (VarIdStr[0], (VOID *)&QuestionId, sizeof(EFI_QUESTION_ID));
gCFormPkg.DoPendingAssign (VarIdStr[1], (VOID *)&QuestionId, sizeof(EFI_QUESTION_ID));
gCFormPkg.DoPendingAssign (VarIdStr[2], (VOID *)&QuestionId, sizeof(EFI_QUESTION_ID));
return;
Err:
for (Index = 0; Index < 3; Index++) {
if (pNode[Index] != NULL) {
delete pNode[Index];
}
if (VarIdStr[Index] != NULL) {
delete VarIdStr[Index];
}
}
}
EFI_VFR_RETURN_CODE
CVfrQuestionDB::UpdateQuestionId (
IN EFI_QUESTION_ID QId,
IN EFI_QUESTION_ID NewQId
)
{
SVfrQuestionNode *pNode = NULL;
if (QId == NewQId) {
// don't update
return VFR_RETURN_SUCCESS;
}
//
// For Framework Vfr, don't check question ID conflict.
//
if (!VfrCompatibleMode && ChekQuestionIdFree (NewQId) == FALSE) {
return VFR_RETURN_REDEFINED;
}
for (pNode = mQuestionList; pNode != NULL; pNode = pNode->mNext) {
if (pNode->mQuestionId == QId) {
break;
}
}
if (pNode == NULL) {
return VFR_RETURN_UNDEFINED;
}
MarkQuestionIdUnused (QId);
pNode->mQuestionId = NewQId;
MarkQuestionIdUsed (NewQId);
gCFormPkg.DoPendingAssign (pNode->mVarIdStr, (VOID *)&NewQId, sizeof(EFI_QUESTION_ID));
return VFR_RETURN_SUCCESS;
}
VOID
CVfrQuestionDB::GetQuestionId (
IN CHAR8 *Name,
IN CHAR8 *VarIdStr,
OUT EFI_QUESTION_ID &QuestionId,
OUT UINT32 &BitMask,
OUT EFI_QUESION_TYPE *QType
)
{
SVfrQuestionNode *pNode;
QuestionId = EFI_QUESTION_ID_INVALID;
BitMask = 0x00000000;
if (QType != NULL) {
*QType = QUESTION_NORMAL;
}
if ((Name == NULL) && (VarIdStr == NULL)) {
return ;
}
for (pNode = mQuestionList; pNode != NULL; pNode = pNode->mNext) {
if (Name != NULL) {
if (strcmp (pNode->mName, Name) != 0) {
continue;
}
}
if (VarIdStr != NULL) {
if (strcmp (pNode->mVarIdStr, VarIdStr) != 0) {
continue;
}
}
QuestionId = pNode->mQuestionId;
BitMask = pNode->mBitMask;
if (QType != NULL) {
*QType = pNode->mQtype;
}
break;
}
return ;
}
EFI_VFR_RETURN_CODE
CVfrQuestionDB::FindQuestion (
IN EFI_QUESTION_ID QuestionId
)
{
SVfrQuestionNode *pNode;
if (QuestionId == EFI_QUESTION_ID_INVALID) {
return VFR_RETURN_INVALID_PARAMETER;
}
for (pNode = mQuestionList; pNode != NULL; pNode = pNode->mNext) {
if (pNode->mQuestionId == QuestionId) {
return VFR_RETURN_SUCCESS;
}
}
return VFR_RETURN_UNDEFINED;
}
EFI_VFR_RETURN_CODE
CVfrQuestionDB::FindQuestion (
IN CHAR8 *Name
)
{
SVfrQuestionNode *pNode;
if (Name == NULL) {
return VFR_RETURN_FATAL_ERROR;
}
for (pNode = mQuestionList; pNode != NULL; pNode = pNode->mNext) {
if (strcmp (pNode->mName, Name) == 0) {
return VFR_RETURN_SUCCESS;
}
}
return VFR_RETURN_UNDEFINED;
}
BOOLEAN VfrCompatibleMode = FALSE;
CVfrVarDataTypeDB gCVfrVarDataTypeDB;
| [
"[email protected]"
] | [
[
[
1,
2820
]
]
] |
3c1dbbb3d144cb40961c2d9c0ad26fe5e7cfafca | 28aa23d9cb8f5f4e8c2239c70ef0f8f6ec6d17bc | /mytesgnikrow --username hotga2801/Project/MotionAdaboost/Develop/hbp/hbp.h | de7238c99d2e45c35156ad44d1d810407d53f4a6 | [] | no_license | taicent/mytesgnikrow | 09aed8836e1297a24bef0f18dadd9e9a78ec8e8b | 9264faa662454484ade7137ee8a0794e00bf762f | refs/heads/master | 2020-04-06T04:25:30.075548 | 2011-02-17T13:37:16 | 2011-02-17T13:37:16 | 34,991,750 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,007 | h | /***************************************************************************
segment.h
Image segmentation and detection of human body forms. The segmentation
code is freeware and was written by Chris M. Christoudias and Bogdan Georgescu.
begin : Thu Jan 01 2004
copyright : (C) 2004 by Bob Mottram
email : [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. *
* *
***************************************************************************/
#if !defined(AFX_SEGMENT_H__2A4829C4_5C66_479C_B0B8_60D8A0FEB11A__INCLUDED_)
#define AFX_SEGMENT_H__2A4829C4_5C66_479C_B0B8_60D8A0FEB11A__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#ifndef __AFXWIN_H__
#error include 'stdafx.h' before including this file for PCH
#endif
#include "resource.h" // main symbols
#include "stdafx.h"
/////////////////////////////////////////////////////////////////////////////
// ChbpApp
// See segment.cpp for the implementation of this class
//
/// <summary>
/// Human Body Project main class
/// </summary>
class ChbpApp : public CWinApp
{
private:
CvHaarClassifierCascade* load_object_detector( const char* cascade_path );
void update(int cameraIndex, SAFEARRAY **bmp, int width, int height);
void getMovementBox(classimage *currentImage, classimage *prevImage,
int width, int height,
int top_x, int top_y, int bottom_x, int bottom_y,
int threshold, int &tx, int &ty, int &bx, int &by);
void matchSegments(int cameraIndex, int motion_tx, int motion_ty, int motion_bx, int motion_by);
void calcAverageImage(classimage *inputImage, classimage *outputImage, classimage *prevImage,
int window_width, int window_height,
int width, int height);
void filterImage(int cameraIndex, classimage *sourceImage);
void filterImage_body(int cameraIndex, classimage *sourceImage, int cx, int cy);
void filterImage_NoFace(int cameraIndex, classimage *sourceImage, int r, int g, int b, int tollerance);
void filterImage_WithFace(int cameraIndex, classimage *sourceImage, int faceIndex);
int findFaces(int cameraIndex);
void estimateArmPosition(int cameraIndex, bool leftArm,int arm_tx,int arm_ty,int arm_bx,int arm_by,int shoulder_y);
void estimateArmPositionNeural(int cameraIndex, bool leftArm, int armpixels);
int updateArmImage(int cameraIndex, bool leftArm,int arm_tx,int arm_ty,int arm_bx,int arm_by);
void saveArmImage(char *filename);
void estimatePose(int cameraIndex, int faceIndex, classimage *sourceImage, bool saveArmData);
void cleanup(classimage *sourceImage, classimage *destImage, int seed_x,int seed_y);
void detectHands(int cameraIndex);
void update_base(int cameraIndex, BYTE *img, int width, int height);
int nearestFace();
void detectSkin(int cameraIndex, bool useMotion);
public:
void RChbp_update(int cameraIndex, SAFEARRAY **bmp, int width, int height, int &NoOfSegments);
void RChbp_updateImage(int x, int y, int width, int height, BYTE r, BYTE g, BYTE b);
void RChbp_update2(int cameraIndex, int width, int height);
void RChbp_getImage(SAFEARRAY **bmp, int imageIndex);
void RChbp_getImagePixel(int imageIndex, int x, int y, BYTE &r, BYTE &g, BYTE &b);
void RChbp_getSegment(int cameraIndex, int index, int &tx, int &ty, int &bx, int &by, int &r, int &g, int &b, int &segmentID, int &inMotion, int &disparity);
void RChbp_getBodyPosture(int cameraIndex, int &leftShoulderElevation, int &rightShoulderElevation,
int &leftElbowElevation, int &rightElbowElevation,
int &leftHandSize, int &rightHandSize,
int &face_tx, int &face_ty, int &face_bx, int &face_by,
int &bodyWidth, int &gazeDirection, int &headTilt,
int &mouthWidth, int &mouthOpen, int &eyebrowsVertical,
int &bodycolour_red, int &bodycolour_green, int &bodycolour_blue,
int &background_red, int &background_green, int &background_blue,
int &personID, bool &invalidFace);
void RChbp_getFaceImage(SAFEARRAY **bmp);
void RChbp_getFaceImagePixel(int x, int y, BYTE &r, BYTE &g, BYTE &b);
int RChbp_getNormalisedFaceImage(SAFEARRAY **bmp);
void RChbp_getPersonIdentity(int &personID, SAFEARRAY **personName);
int RChbp_getPersonID();
BYTE RChbp_getPersonName(int personID, int charIndex);
BYTE RChbp_getPortrait(int personID, int charIndex);
void RChbp_setDetectionMode(int mode);
void RChbp_enableLearning(bool state);
void RChbp_getMotionBox(int &tx, int &ty, int &bx, int &by, float &flow_x, float &flow_y);
bool RChbp_faceDetected();
void RChbp_save(char *filename);
void RChbp_load(char *filename);
ChbpApp();
~ChbpApp();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(ChbpApp)
//}}AFX_VIRTUAL
//{{AFX_MSG(ChbpApp)
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_SEGMENT_H__2A4829C4_5C66_479C_B0B8_60D8A0FEB11A__INCLUDED_)
| [
"hotga2801@ecd9aaca-b8df-3bf4-dfa7-576663c5f076"
] | [
[
[
1,
124
]
]
] |
1429ece28391beb75c6db51ec2a089adcbcd293b | f6c641b102ebbffb48e93dd554a0b7eb7e639be7 | /Source/Test/Metaballs [OCL]/Source.cpp | a391e3d6123a7aa68cadf105ba6c8d8cd6912a69 | [] | no_license | ZAsprose/rtrt-on-gpu | e3ca4921a3429cbc72e0cee8afd946200b83573d | 4949e373c273f963467658ca25d39244da7fb4e6 | refs/heads/master | 2021-01-10T14:42:45.293509 | 2010-08-25T18:37:19 | 2010-08-25T18:37:19 | 53,016,647 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,213 | cpp | /*
---------------------------------------------------------------------------
| M E T A B A L L S D E M O ( OCL ) |
---------------------------------------------------------------------------
Copyright (c) 2009 - 2010 Denis Bogolepov ( denisbogol @ gmail.com )
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation, either version 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/>.
*/
#define NOMINMAX
#include <iostream>
#include <logger.h>
#include <Graphics.hpp>
#include <Compute.hpp>
using namespace graphics;
/////////////////////////////////////////////////////////////////////////////////////////
// Global variables
/*
* Camera control with mouse ( orientation ) and keyboard ( position ).
*/
Mouse mouse;
Keyboard keyboard;
Camera camera ( Vector3f ( 0.0F, 0.0F, -18.0F ) /* position */,
Vector3f ( 0.0F, 0.0F, 0.0F ) /* orientation ( Euler angles ) */ );
/*
* OpenCL objects.
*/
cl_context context;
cl_program program;
cl_kernel kernel;
cl_mem image;
cl_mem metaballs;
cl_command_queue queue;
/*
* Width and height of the output window.
*/
int width = 512;
int height = 512;
/*
* OpenGL texture for output image from OpenCL.
*/
Texture2D * texture = NULL;
/*
* Positions and radiuses of metaballs.
*/
const cl_int count = 8;
cl_float positions [] = {
0.0F, 0.0F, 0.0F, 0.50F,
0.0F, 0.0F, 0.0F, 0.75F,
0.0F, 0.0F, 0.0F, 1.00F,
0.0F, 0.0F, 0.0F, 1.50F,
0.0F, 0.0F, 0.0F, 1.50F,
0.0F, 0.0F, 0.0F, 1.00F,
0.0F, 0.0F, 0.0F, 0.75F,
0.0F, 0.0F, 0.0F, 1.50F
};
/////////////////////////////////////////////////////////////////////////////////////////
// Event handlers for mouse and keyboard
void MouseMoveHandler ( GLint x, GLint y )
{
mouse.MouseMoveHandler ( x, y );
}
void MouseDownHandler ( GLint button, GLint state )
{
mouse.MouseDownHandler ( button, state );
}
void KeyDownHandler ( GLint key, GLint state )
{
keyboard.KeyDownHandler ( key, state );
}
/////////////////////////////////////////////////////////////////////////////////////////
// OpenCL subroutines
void SetupOpenCL ( void )
{
/*
* Obtain the list of platforms available ( AMD / NVIDIA ).
* In this tutorial we use only first platform available.
*/
VECTOR < cl_platform_id > platforms = cltGetPlatforms ( );
/*
* Create an OpenCL context from a device type based on
* current OpenGL context.
*
* NOTE: You can create OpenCL context from OpenGL only
* for GPU device.
*/
context = cltCreateContextFromOpenGL ( platforms [0] );
/*
* Obtain the list of devices available on a platform.
* In this tutorial we use only first device available.
*/
VECTOR < cl_device_id > devices = cltGetDevices ( context );
/*
* Load and build a program object for a context.
*/
program = cltLoadProgram ( context, "Render.cl" );
cltBuildProgram ( program, devices );
/*
* Create a command-queue on a specific device.
*/
queue = cltCreateQueue ( context, devices [0] );
}
void SetupKernels ( void )
{
/*
* Create a kernel object for a function declared in a program.
*/
kernel = cltCreateKernel ( program, "Main" );
/*
* Create an OpenCL 2D image object from an OpenGL 2D texture
* object for output rendered scene.
*/
image = cltCreateImageFromTexture ( context, CL_MEM_WRITE_ONLY, texture );
cltSetArgument < cl_mem > ( kernel, 0, &image );
/*
* Create an OpenCL buffer object for array of ball positions.
*/
metaballs = cltCreateBuffer < cl_float4 > ( context, CL_MEM_READ_ONLY, count );
cltSetArgument < cl_mem > ( kernel, 8, &metaballs );
}
void StartKernels ( void )
{
/*
* Set dynamic kernel arguments.
*/
cl_float4 view = cltFloat4 ( camera.View ( ) );
cltSetArgument < cl_float4 > ( kernel, 1, &view );
//----------------------------------------------------------
cl_float4 up = cltFloat4 ( camera.Up ( ) );
cltSetArgument < cl_float4 > ( kernel, 2, &up );
//----------------------------------------------------------
cl_float4 side = cltFloat4 ( camera.Side ( ) );
cltSetArgument < cl_float4 > ( kernel, 3, &side );
//----------------------------------------------------------
cl_float4 position = cltFloat4 ( camera.Position ( ) );
cltSetArgument < cl_float4 > ( kernel, 4, &position );
//----------------------------------------------------------
cl_float2 scale = cltFloat2 ( 2.0F * camera.Scale ( ) );
cltSetArgument < cl_float2 > ( kernel, 5, &scale );
//----------------------------------------------------------
cltSetArgument < int > ( kernel, 6, &width );
cltSetArgument < int > ( kernel, 7, &height );
//----------------------------------------------------------
/*
* Write new positions of metaballs.
*/
cltCheckError ( clEnqueueWriteBuffer (
queue,
metaballs,
CL_TRUE,
0,
count * sizeof ( cl_float4 ),
positions,
0,
NULL,
NULL ) );
//----------------------------------------------------------
/*
* Run kernel on GPU.
*/
cltRunKernel2D (
queue,
kernel,
width, height /* global size */,
8, 8 /* local size */ );
//----------------------------------------------------------
/*
* Wait until the kernel is not completed.
*/
cltFinish ( queue );
}
void ReleaseOpenCL ( void )
{
cltCheckError ( clReleaseKernel ( kernel ) );
cltCheckError ( clReleaseProgram ( program ) );
cltCheckError ( clReleaseMemObject ( image ) );
cltCheckError ( clReleaseMemObject ( metaballs ) );
cltCheckError ( clReleaseCommandQueue ( queue ) );
cltCheckError ( clReleaseContext ( context ) );
}
/////////////////////////////////////////////////////////////////////////////////////////
// Entry point for program
int main ( void )
{
/* We use GLFW for window management and OpenGL output */
glfwInit ( );
//-------------------------------------------------------------------------
/* Choose video mode ( window or fullscreen ) */
std :: cout << "Do you want to run program in fullscreen mode? [Y/N]\n";
int choice = getchar ( );
int mode = GLFW_WINDOW;
//-------------------------------------------------------------------------
/* Set video mode ( window or fullscreen ) */
if ( choice == 'Y' || choice == 'y' )
{
GLFWvidmode vidmode;
glfwGetDesktopMode ( &vidmode );
width = vidmode.Width;
height = vidmode.Height;
mode = GLFW_FULLSCREEN;
}
//-------------------------------------------------------------------------
/* Try to open rendering window */
glfwOpenWindowHint ( GLFW_WINDOW_NO_RESIZE, GL_TRUE );
if ( !glfwOpenWindow (
width /* window width */,
height /* window height */,
0 /* bits for red channel ( default ) */,
0 /* bits for green channel ( default ) */,
0 /* bits for blue channel ( default ) */,
0 /* bits for alpha channel ( default ) */,
0 /* bits for depth buffer ( not used ) */,
0 /* bits for stencil buffer ( not used ) */,
mode /* windows mode ( fullscreen or window ) */ ) )
{
glfwTerminate ( ); exit ( 0 );
}
//-------------------------------------------------------------------------
/* Set event handlers for mouse and keyboard */
glfwSwapInterval ( 0 );
glfwSetMousePosCallback ( MouseMoveHandler );
glfwSetMouseButtonCallback ( MouseDownHandler );
glfwSetKeyCallback ( KeyDownHandler );
//-------------------------------------------------------------------------
/* Set parallel projection for drawing dummy quad */
glMatrixMode ( GL_PROJECTION );
glLoadIdentity ( );
glOrtho ( -1.0F, 1.0F, -1.0F, 1.0F, -1.0F, 1.0F );
glMatrixMode ( GL_MODELVIEW );
glLoadIdentity ( );
glEnable ( GL_TEXTURE_RECTANGLE_ARB );
/* Set default view frustum and window size for the camera */
camera.SetFrustum ( );
camera.SetViewport ( width, height );
//-------------------------------------------------------------------------
/* Setup OpenCL compute environment */
SetupOpenCL ( );
/*
* NOTE: From ATI Stream SDK v2.1 Developer Release Notes
*
* For OpenGL interoperability with OpenCL, there currently is a
* requirement on when the OpenCL context is created and when
* texture / buffer shared allocations can be made. To use shared
* resources, the OpenGL application must create an OpenGL context
* and then an OpenCL context. All resources ( GL buffers and
* textures ) created after creation of the OpenCL context can be
* shared between OpenGL and OpenCL. If resources are allocated before
* the OpenCL context creation, they cannot be shared between OpenGL
* and OpenCL.
*/
/* Create OpenGL texture object */
texture = new Texture2D (
0,
NULL,
GL_TEXTURE_RECTANGLE_ARB );
texture->Data = new TextureData2D (
width /* width of the texture */,
height /* height of the texture */,
4 /* channels for each texel */,
GL_TRUE /* no texture data on CPU */ );
texture->Setup ( );
/* Now we can work with the texture */
SetupKernels ( );
//-------------------------------------------------------------------------
GLboolean running = GL_TRUE;
GLchar caption [100];
GLint frames = 0;
GLdouble fps = 0.0,
delta = 0.0,
time = 0.0,
start = glfwGetTime ( );
//-------------------------------------------------------------------------
while ( running )
{
/* Calculate frames per second ( FPS ) */
time = glfwGetTime ( );
delta = time - start;
if ( delta > 0.1 /* interval of FPS averaging */ )
{
fps = frames / delta;
sprintf ( caption, "Metaballs Demo ( OCL ) - %.1f FPS", fps );
glfwSetWindowTitle ( caption );
start = time;
frames = 0;
}
frames++;
//---------------------------------------------------------------------
/* Set new camera position and orientation */
mouse.Apply ( &camera, fps );
keyboard.Apply ( &camera, fps );
//---------------------------------------------------------------------
/* Move metaballs */
positions [0] = sinf ( time );
positions [1] = cosf ( time );
positions [2] = 0.0F;
positions [4] = 2.0F * sinf ( time );
positions [5] = 0.0F;
positions [6] = 2.0F * cosf ( time );
positions [8] = 0.0F;
positions [9] = 2.0F * sinf ( time );
positions [10] = 2.0F * cosf ( time );
positions [12] = 3.0F * sinf ( time );
positions [13] = 3.0F * sinf ( time );
positions [14] = 3.0F * cosf ( time );
positions [16] = 3.0F * cosf ( time );
positions [17] = 3.0F * sinf ( time );
positions [18] = 3.0F * cosf ( time );
positions [20] = 2.0F * sinf ( time ) * cosf ( time );
positions [21] = 2.0F * sinf ( time ) * cosf ( time );
positions [22] = 2.0F * cosf ( time );
positions [24] = 3.0F * sinf ( time ) * cosf ( time );
positions [25] = 4.0F * sinf ( time ) * cosf ( time );
positions [26] = 3.0F * cosf ( time );
positions [28] = 4.0F * cosf ( time ) * cosf ( time );
positions [29] = 3.0F * sinf ( time );
positions [30] = 4.0F * cosf ( time ) * cosf ( time );
//---------------------------------------------------------------------
/* Compute ray traced image using OpenCL kernel */
cltAcquireGraphicsObject ( queue, image );
cltFinish ( queue );
StartKernels ( );
cltReleaseGraphicsObject ( queue, image );
cltFinish ( queue );
/* Draw dummy quad with custom fragment shader */
glBegin ( GL_QUADS );
glTexCoord2f ( 0, 0 ); glVertex2f ( -1.0F, -1.0F );
glTexCoord2f ( 0, height ); glVertex2f ( -1.0F, 1.0F );
glTexCoord2f ( width, height ); glVertex2f ( 1.0F, 1.0F );
glTexCoord2f ( width, 0 ); glVertex2f ( 1.0F, -1.0F );
glEnd ( );
glfwSwapBuffers ( );
//---------------------------------------------------------------------
running = !glfwGetKey ( GLFW_KEY_ESC ) &&
glfwGetWindowParam ( GLFW_OPENED );
}
ReleaseOpenCL ( );
delete texture;
glfwTerminate ( );
exit ( EXIT_SUCCESS );
} | [
"[email protected]"
] | [
[
[
1,
527
]
]
] |
578861509a63b164fc8284d50a9652f3e3e03e6b | d38dd2b4c110cdc21724977a5e7546e32fee80a4 | /mahanabolis/metric_factory.hpp | e734ccef455c4f35c4588d6af14b2f483c61f241 | [] | no_license | arm2arm/mstgraph | ae306f17e216dc5be06f79263a776f7cb9451f92 | b9b8c1af1a56fbfabc9f7ecc34dcb7af23e4fd4e | refs/heads/master | 2020-12-24T19:46:21.823308 | 2010-06-25T13:58:42 | 2010-06-25T13:58:42 | 56,456,768 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,859 | hpp | #ifndef _METRIC_ND_
#define _METRIC_ND_
#undef BOOST_UBLAS_TYPE_CHECK
//we should define this to be able
#define BOOST_UBLAS_TYPE_CHECK 0
#include <boost/numeric/ublas/vector.hpp>
#include <vector>
#include <algorithm>
#include "matrix_tools.h"
namespace Metrics{
//////////////////////////////////////////////////////////////////////////////////
//Compilcated Mahalanobis distance for given particle from the group
// let assume we have G group with NDxN components ahere ND is the number of the dimensions,
// and <G> is the means of the each component, so <G> is the ND vector.
/** Usage Example:
\code
Metrics::MahalDistance<double> Mahal(uG1);
ublas::vector<double> vec(2);
vec(0)=uG1(0,0);vec(1)=uG1(1,0);
cout<<"Pos:"<<vec<<endl;
cout<<"Dist: "<<Mahal.doDist(vec)<<endl;
\endcode
**/
template
<class T>
class MahalDistance {
typedef boost::numeric::ublas::matrix<T> MatrixT;
typedef boost::numeric::ublas::vector<T> VectorT;
public:
static bool set_flag;
MahalDistance():last_dist((T)0.0),frac((T)0.5),NSmooth(5){ };
//! A constructor.
/*!
It takes as a input the matrix of the D dimensional pointset.
Here the default values for frac and NSmooth
\sa frac and NSmooth
*/
MahalDistance(MatrixT& G):last_dist((T)0.0),frac((T)1.0),NSmooth(1){Init(G);};
//! A public member function.
/*!
This used for setting the Covariance matrix smoothing.
\param frac the fraction of the particles to be used for smoothing
\param NSmooth number of iterations/shuffle to smooth covariance matrix
\sa frac and NSmooth
*/
void SetCovarianceSmoothing(T _frac,int _NSmooth){frac=_frac;NSmooth=_NSmooth;};
void GetPartial(MatrixT &Gin, MatrixT &Gout, T frac)
{
std::random_shuffle(ind.begin(), ind.end());
size_t n2=(size_t)(frac*Gin.size2())+1;
size_t n1=Gin.size1();
Gout.resize(Gin.size1(),n2);
for(size_t i=0;i<n2;i++)
for(size_t j=0;j<n1;j++)
Gout(j,i)=Gin(j,ind[i]);
}
void Init(MatrixT& Gin){
//cout<<endl;
//cout<<G<<endl;
MatrixT G;
MatrixT Covar, partCovar;
ind.resize(Gin.size2());
for(size_t i=0;i<Gin.size2();i++)
ind[i]=i;
GetPartial(Gin, G, frac);
Covarinace(G, Covar);//Get Covariance
// detCovar=(T)determinant(Covar);
#ifdef SMOOTH_COVAR
for(int i=0;i<NSmooth-1;i++)
{
GetPartial(Gin, G, frac);
Covarinace(G, partCovar);//Get Covariance
Covar+=partCovar;
}
Covar/=(T)NSmooth;
#endif
InvertMatrix (Covar, InvCovar);
detCovar=(T)determinant(Covar);
// cout<<endl;
// cout<<InvCovar<<endl;
}
T doDist(float *V1,float *V2){
boost::numeric::ublas::vector<T> p(meanG.size());
for(size_t idx=0;idx<meanG.size();idx++)p(idx)=(V1[idx]-V2[idx]);
last_dist=getDistance(p);
return last_dist;
};
T doEDist(float *V1,float *V2){
last_dist=0.0;
for(size_t idx=0;idx<3;idx++)
last_dist+=(V1[idx]-V2[idx])*(V1[idx]-V2[idx]);
last_dist=std::sqrt(last_dist);
return last_dist;
};
T doDist(float *V){
boost::numeric::ublas::vector<T> p(meanG.size());
for(size_t idx=0;idx<meanG.size();idx++)p(idx)=V[idx];
last_dist=getDistance(p);
return last_dist;
};
T doDist(std::vector<float> &V){
boost::numeric::ublas::vector<T> p(meanG.size());
for(size_t idx=0;idx<meanG.size();idx++)p(idx)=V[idx];
last_dist=getDistance(p);
return last_dist;
};
T doDist(VectorT &vin){
last_dist=getDistance(vin);
return last_dist;};
inline T getDet(){return detCovar;};
T last_dist;
T detCovar;
std::vector<int> ind;
protected:
T frac;// The fraction of neighbor particles participating in to the Covariance Matrix smoothing
int NSmooth;// How many times select random fractions to smooth the covariance matrix?
// this must be not directly accessible
// since we want to provide a rich set of distances
T getDistance(VectorT v1, VectorT v2)
{
return 1.0 ;
};
T getDistance(VectorT &vin)
{
// cout<<vin<<endl;
//vin-=meanG;
VectorT ab=prod(vin,InvCovar );
// cout<<vin<<endl;
// cout<<ab<<endl;
double dres=0.0;
for(size_t i=0;i<ab.size();i++)
dres+=ab(i)*vin(i);
//cout<<InvCovar<<endl;
//cout<<"Mean"<<meanG<<endl;
return (T)dres;//
};
VectorT meanG;//this holds the means for each dimension
MatrixT InvCovar;//this holds the means for each dimension
std::vector<T> meanV;//just for debuging
///////////////////////////// GET COVARIANCE of Matrix
void Covarinace(const MatrixT& matrix, MatrixT& covMatrix)
{
const T ZERO(0);
const T ONE(1);
size_t maxRows = matrix.size2();
size_t maxCols = matrix.size1();
if (maxRows == 1) covMatrix = boost::numeric::ublas::zero_matrix<T>(1,1);
else
{
GetMeanByColumns(matrix, meanG);
MatrixT temp = matrix;
for (size_t j=0; j<maxCols; ++j)
{
for (size_t i=0; i<maxRows; ++i) temp(j,i) -= meanG(j);
}
MatrixT tr_temp=trans(temp);
covMatrix = prod(temp,tr_temp) * (ONE/T(maxRows-1));
}
}
void GetMeanByColumns(const MatrixT &m, VectorT & vout)
{
// loop over columns getting each row
vout.resize(m.size1());
meanV.clear();
T mean=0.0;
//cout<<m<<endl;
for (size_t i = 0; i < m.size1(); ++i)
{
mean=0.0;
for (size_t j = 0; j < m.size2(); ++ j)
mean += m(i,j);
mean/=((T)m.size2());
vout(i)=mean;
meanV.push_back(mean);
// cout<<vout(i)<<endl;
}
}
};
template <class T>
bool MahalDistance<T>::set_flag=true;
/////////////////////////////////////////////////////////////////////////////////
}
#endif | [
"arm2arm@06a51f3c-712f-11de-a0a7-fb2681086dbc"
] | [
[
[
1,
208
]
]
] |
b94ef0f2a5f8b93b608e3a0c5a5f3011d40cbb62 | 913f43ef4d03bd5d6b42b9e31b1048ae54493f59 | /CraterRacer/CraterRacer/Source_Code/Subsystem Files/GameCamera.h | 15549f17f603deda9aaa2eb822d993628317cd4a | [] | no_license | GreenAdept/cpsc585 | bfba6ea333c2857df0822dd7d00768df6a010a73 | c66745e77be4c78e435da1a59ae94ac2a61228cf | refs/heads/master | 2021-01-10T16:42:03.804213 | 2010-04-27T00:13:52 | 2010-04-27T00:13:52 | 48,024,449 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 815 | h | #pragma once
#ifndef GAME_CAMERA_H
#define GAME_CAMERA_H
//-------------------------------------------------
// Include files
//-------------------------------------------------
#include "Constants.h"
#include "Entity.h"
//-------------------------------------------------
// Class: GameCamera
// Implementation of a laggy game camera.
//-------------------------------------------------
class GameCamera {
Entity *target;
MCamera camera;
bool rearView;
Vec3 offset;
Vec3 eye, lookAt;
Vec3 interpolate (float distance, Vec3 newEye);
public:
GameCamera();
void setTarget (Entity *e);
void updateWindow (const D3DSURFACE_DESC* pSurface);
MCamera getCamera ();
void setRearView (bool activate);
void toggleRearView ();
};
#endif
| [
"tfalders@b92cab1e-0213-11df-804c-772d9fe11005",
"amber.wetherill@b92cab1e-0213-11df-804c-772d9fe11005"
] | [
[
[
1,
8
],
[
10,
39
]
],
[
[
9,
9
]
]
] |
da9077f42e60bc014abc305b686c551976ba3366 | 677f7dc99f7c3f2c6aed68f41c50fd31f90c1a1f | /SolidSBCTestLib/SolidSBCTestLib.cpp | 5aa1735a9048f90d90de6b124dbd3eb4cfff460d | [] | no_license | M0WA/SolidSBC | 0d743c71ec7c6f8cfe78bd201d0eb59c2a8fc419 | 3e9682e90a22650e12338785c368ed69a9cac18b | refs/heads/master | 2020-04-19T14:40:36.625222 | 2011-12-02T01:50:05 | 2011-12-02T01:50:05 | 168,250,374 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,097 | cpp | // SolidSBCTestLib.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "SolidSBCTestLib.h"
#include "SolidSBCTestManagerImpl.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
static CSolidSBCTestManagerImpl g_cSolidTestInstance;
// The one and only application object
CWinApp theApp;
using namespace std;
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
HMODULE hModule = ::GetModuleHandle(NULL);
if (hModule != NULL)
{
// initialize MFC and print and error on failure
if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
_tprintf(_T("Fatal Error: MFC initialization failed\n"));
nRetCode = 1;
}
else
{
// TODO: code your application's behavior here.
}
}
else
{
// TODO: change error code to suit your needs
_tprintf(_T("Fatal Error: GetModuleHandle failed\n"));
nRetCode = 1;
}
return nRetCode;
}
const void* GetSolidSBCTestInstance(void)
{
return (void*)(&g_cSolidTestInstance);
} | [
"admin@bd7e3521-35e9-406e-9279-390287f868d3"
] | [
[
[
1,
53
]
]
] |
2496965e3a61473cc8a4fb7fddae25019067198a | b7c505dcef43c0675fd89d428e45f3c2850b124f | /Src/ControllerQt/Views/ModuleView.h | fa08d70e91b0c7d670cf7fb6c885a1165a6b55ee | [
"BSD-2-Clause"
] | permissive | pranet/bhuman2009fork | 14e473bd6e5d30af9f1745311d689723bfc5cfdb | 82c1bd4485ae24043aa720a3aa7cb3e605b1a329 | refs/heads/master | 2021-01-15T17:55:37.058289 | 2010-02-28T13:52:56 | 2010-02-28T13:52:56 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 2,817 | h | /**
* @file ControllerQt/ModuleView.h
* Declaration of a class to represent a view displaying the module layout of the process.
* @author <a href="mailto:[email protected]">Thomas Röfer</a>
*/
#ifndef ModuleView_H
#define ModuleView_H
#include <SimRobotCore/Controller/DirectView.h>
class RobotConsole;
class QPixmap;
/**
* @class ModuleView
* A class to represent a view displaying the module layout of the process.
*/
class ModuleView : public DirectView
{
public:
/**
* Constructor.
* @param console The console object.
* @param processIdentifier The identifier of the process the modules of which are displayed.
* @param category The category of the modules of this view. If "", show all categories.
*/
ModuleView(RobotConsole& console, char processIdentifier, const std::string& category);
/**
* Destructor.
*/
~ModuleView();
private:
RobotConsole& console; /**< A reference to the console object. */
char processIdentifier; /**< The name of the view. */
std::string category; /**< The category of the modules of this view. If "", show all categories. */
QPixmap* image; /**< The module graph image. */
unsigned int lastModulInfoTimeStamp; /**< Module Info timestamp when the image was created. */
/**
* The method returns a new instance of a widget for this direct view.
* The caller has to delete this instance. (Qt handles this)
* @return The widget.
*/
QWidget* createWidget();
/**
* The function is called to let the direct view update the widget. Do so if necessary.
* @param widget The widget
*/
void updateWidget(QWidget& widget);
/**
* The method creates the dot file of the module graph.
* @param fileName The name of the file created.
* @return Were any nodes generated?
*/
bool generateDotFile(const char* fileName);
/**
* The method replaces all ' ' by '_'.
* @param s The input string.
* @return The string in which spaces were replaced.
*/
std::string compress(const std::string& s) const;
/**
* The method creates the image of the module graph.
*/
void generateImage();
/**
* The function is called to return a string that contains the configuration of the widget/view.
* @param widget The widget
* @return A text string containing all information to restore the internal state of the widget/view.
*/
virtual std::string getConfiguration(QWidget& widget) const;
/**
* The function is called to restore the configuration of the widget/view.
* @param widget The widget
* @param A text string containing all information to restore the internal state of the widget/view.
*/
virtual void setConfiguration(QWidget& widget, const std::string& configuration);
};
#endif //ModuleView_H
| [
"alon@rogue.(none)"
] | [
[
[
1,
89
]
]
] |
9152f481cce4aa3778086ab00ee76411d4b7fe81 | ce262ae496ab3eeebfcbb337da86d34eb689c07b | /SERenderers/SE_OpenGL_Renderer/SEOpenGLRendering/SEOpenGLResources.h | dfc22b129380f111c6a564eea4048b39632e0875 | [] | no_license | pizibing/swingengine | d8d9208c00ec2944817e1aab51287a3c38103bea | e7109d7b3e28c4421c173712eaf872771550669e | refs/heads/master | 2021-01-16T18:29:10.689858 | 2011-06-23T04:27:46 | 2011-06-23T04:27:46 | 33,969,301 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,068 | h | // Swing Engine Version 1 Source Code
// Most of techniques in the engine are mainly based on David Eberly's
// Wild Magic 4 open-source code.The author of Swing Engine learned a lot
// from Eberly's experience of architecture and algorithm.
// Several sub-systems are totally new,and others are re-implimented or
// re-organized based on Wild Magic 4's sub-systems.
// Copyright (c) 2007-2010. All Rights Reserved
//
// Eberly's permission:
// Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or (at
// your option) any later version. The license is available for reading at
// the location:
// http://www.gnu.org/copyleft/lgpl.html
#ifndef Swing_OpenGLResources_H
#define Swing_OpenGLResources_H
#include "SEOpenGLRendererLIB.h"
#include "SEOpenGLRenderer.h"
#include "SEAttributes.h"
#include "SEBindable.h"
#include "SEOpenGLProgramInterface.h"
namespace Swing
{
class SE_RENDERER_API SEVProgramID : public SEResourceIdentifier
{
public:
CGprogram ID;
};
class SE_RENDERER_API SEPProgramID : public SEResourceIdentifier
{
public:
CGprogram ID;
};
class SE_RENDERER_API SETextureID : public SEResourceIdentifier
{
public:
unsigned int ID;
SETexture* TextureObject;
};
class SE_RENDERER_API SEVBufferID : public SEResourceIdentifier
{
public:
SEAttributes IAttr; // multipass时,用于shader输入属性匹配性检测.
SEAttributes OAttr;
unsigned int ID;
};
class SE_RENDERER_API SEIBufferID : public SEResourceIdentifier
{
public:
unsigned int ID;
};
class SE_RENDERER_API SEProgramData
{
public:
SEProgramData(void){ ID = 0; }
CGprogram ID;
// 该程序所需的程序接口.
std::vector<SEOpenGLProgramInterfacePtr> Interfaces;
};
}
#endif
| [
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
] | [
[
[
1,
79
]
]
] |
71c206dd4f24f8d3708949a4715f7881acb9c4c8 | cfa6cdfaba310a2fd5f89326690b5c48c6872a2a | /Sources/Tutorials/Simple Chat/ServerTest/ServerTest/ServerTest.h | aff39113f90091e22dc96364cb69a15708b287d9 | [] | no_license | asdlei00/project-jb | 1cc70130020a5904e0e6a46ace8944a431a358f6 | 0bfaa84ddab946c90245f539c1e7c2e75f65a5c0 | refs/heads/master | 2020-05-07T21:41:16.420207 | 2009-09-12T03:40:17 | 2009-09-12T03:40:17 | 40,292,178 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 585 | h | // ServerTest.h : PROJECT_NAME 응용 프로그램에 대한 주 헤더 파일입니다.
//
#pragma once
#ifndef __AFXWIN_H__
#error PCH에서 이 파일을 포함하기 전에 'stdafx.h'를 포함하십시오.
#endif
#include "resource.h" // 주 기호
// CServerTestApp:
// 이 클래스의 구현에 대해서는 ServerTest.cpp을 참조하십시오.
//
class CServerTestApp : public CWinApp
{
public:
CServerTestApp();
// 재정의
public:
virtual BOOL InitInstance();
// 구현
DECLARE_MESSAGE_MAP()
};
extern CServerTestApp theApp;
| [
"[email protected]"
] | [
[
[
1,
31
]
]
] |
88009c4c65d9f6b2cce308707003508cdb603cc5 | 25233569ca21bf93b0d54ca99027938d65dc09d5 | /common.h | fb405fb1d3000248144d9f979a2d9671abb7084f | [] | no_license | jugg/litestep-module-label | 6ede7ff5c80c25e1dc611d02ba5dc13559914ddc | a75ef94a56d68c2a928bde5bab60318e609b9a10 | refs/heads/master | 2021-01-18T09:20:42.000147 | 2004-10-07T12:28:00 | 2004-10-07T12:28:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,007 | h | #if !defined(__COMMON_H)
#define __COMMON_H
#include <fstream>
#include <string>
#include <list>
#include <vector>
#include <map>
using namespace std;
class Label;
typedef list<string> StringList;
typedef list<string>::iterator StringListIterator;
//typedef vector<string> StringVector;
typedef list<Label *> LabelList;
typedef list<Label *>::iterator LabelListIterator;
typedef bool boolean;
typedef unsigned __int64 largeInt;
#define WIN32_LEAN_AND_MEAN
#define STRICT
#include <windows.h>
#include <windowsx.h>
#include <winsock.h>
// #include "../ls-b247/lsapi/lsapi.h"
#include "lsapi.h"
// we want to use our own versions instead of the Indie LS ones
#undef GetRCCoordinate
#undef ParseCoordinate
#define GetRCCoordinate LblGetRCCoordinate
#define ParseCoordinate LblParseCoordinate
#include "utility.h"
#include "verInfo.h"
#include "strsafe.h"
#define LM_SETLABELTEXT 9600
#ifndef WM_MOUSEWHEEL
#define WM_MOUSEWHEEL 0x020A
#endif
#endif
| [
"[email protected]"
] | [
[
[
1,
48
]
]
] |
a09a99bef01e9d30561be88b276f508a3bd227de | 1736474d707f5c6c3622f1cd370ce31ac8217c12 | /PseudoUnitTest/TestDictionary.hpp | a58b48982e26867433ad1820a53a0488012912b1 | [] | no_license | arlm/pseudo | 6d7450696672b167dd1aceec6446b8ce137591c0 | 27153e50003faff31a3212452b1aec88831d8103 | refs/heads/master | 2022-11-05T23:38:08.214807 | 2011-02-18T23:18:36 | 2011-02-18T23:18:36 | 275,132,368 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,271 | hpp | #include <Pseudo\Dictionary.hpp>
BEGIN_TEST_CLASS(TestDictionary)
BEGIN_TEST_METHODS
TEST_METHOD(Test)
TEST_METHOD(TestStress)
END_TEST_METHODS
void Test()
{
Pseudo::Dictionary<int, const Char *> dict;
const Char* pCarrot = L"Carrot";
dict.Add(1, L"Apple");
dict.Add(2, L"Banana");
dict.Add(3, pCarrot);
dict.Add(4, L"Peach");
const Char* p;
TEST_ASSERT(dict.TryGetValue(3, p) && p == pCarrot, L"Search for value 3/Carrot in dictionary");
}
void TestStress()
{
Pseudo::Dictionary<int, int> dict;
//const int numEntries = 0x6dda89;
const int numEntries = 0xffff;
for (int i = 0; i < numEntries; i++)
dict.Add(i, i);
TEST_ASSERT(dict.get_Count() == numEntries, L"Count of dictionary entries not equal to numEntries");
for (int i = 0; i < numEntries; i++)
{
int key;
int value;
dict.get_EntryByOrd(i, &key, &value);
TEST_ASSERT(key == i && key == value, L"Entry is not correct key/value pair");
}
for (int i = 0; i < numEntries; i++)
dict.Remove(i);
TEST_ASSERT(dict.get_Count() == 0, L"Count of dictionary entries not equal to 0");
}
END_TEST_CLASS
| [
"[email protected]"
] | [
[
[
1,
53
]
]
] |
cebd4ebc3e1fbcfc425c14466ed88184f7112c59 | 1b75922773bf9e61f5c9c8572ffcdae73d34a158 | /examples/testbed/RendererGL.h | 567f7dbb2fbd5aec013eb1f847eb665ffe8cc2eb | [] | no_license | warvair/bulletscript | a6db7ad4caa661e830373f4953e35053852008bc | 3f499c3afba07c251fa95cb012801ef820705f7f | refs/heads/master | 2021-01-10T20:46:53.665684 | 2010-07-03T18:50:43 | 2010-07-03T18:50:43 | 35,000,416 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,391 | h | #ifndef __RENDERERGL_H__
#define __RENDERERGL_H__
#include <vector>
#include "Main.h"
#include "bsPrerequisites.h"
#include "BulletSystem.h"
#if BS_PLATFORM == BS_PLATFORM_WIN32
# include <windows.h>
#endif
#include <gl/gl.h>
#include <gl/glu.h>
#include <SDL.h>
class TGALoader
{
std::string mFileName;
int mWidth, mHeight, mBPP;
public:
TGALoader (const std::string &file) :
mFileName (file),
mWidth (0),
mHeight (0),
mBPP (0)
{
}
GLuint loadToVRAM (int& width, int& height);
};
struct Area;
class RendererGL
{
// Font
GLuint mFontTexture;
// Bullets
struct BulletInfo
{
float vHeight;
int width, height;
} mBulletInfo[2];
static const int MAX_BULLETS = 2048;
static const int BULLET_RADIUS = 4;
float mBulletPos[MAX_BULLETS * 8];
float mBulletTex[MAX_BULLETS * 8];
float mBulletCol[MAX_BULLETS * 16];
unsigned short mBulletIndices[MAX_BULLETS * 4];
int mNumBullets;
GLuint mBulletTexture;
void renderBulletBatch();
// Quads
static const int MAX_QUADS = 128;
float mQuadPos[MAX_QUADS * 8];
float mQuadTex[MAX_QUADS * 8];
float mQuadCol[MAX_QUADS * 16];
unsigned short mQuadIndices[MAX_QUADS * 4];
int mNumQuads;
GLuint mBeamTexture, mBeamTipTexture;
// Ellipses
// An ellipse is a triangle fan, and how many triangles it uses depends on its size.
// Therefore, we must generate the indices dynamically.
static const int MAX_ELLIPSE_POINTS = 512;
float mEllipsePos[MAX_ELLIPSE_POINTS * 2];
float mEllipseTex[MAX_ELLIPSE_POINTS * 2];
float mEllipseCol[MAX_ELLIPSE_POINTS * 4];
unsigned short mEllipseIndices[MAX_ELLIPSE_POINTS];
GLuint mEllipseTexture;
// Arcs
static const int MAX_ARC_POINTS = 1024;
float mArcPos[MAX_ARC_POINTS * 2];
float mArcTex[MAX_ARC_POINTS * 2];
float mArcCol[MAX_ARC_POINTS * 4];
unsigned short mArcIndices[MAX_ARC_POINTS];
GLuint mArcTexture;
// Shaders
GLuint mFragmentShader, mFragmentProgram, mVertexShader, mVertexProgram;
public:
RendererGL ();
bool initialise(int width, int height, bool fullScreen);
void _renderQuadBatch();
void startRendering();
void finishRendering();
void print(int x, int y, const char* str);
void addBullet(const Bullet& b);
void addQuadArea(Area* a);
void addEllipseArea(Area* a);
void addArcArea(Area* a);
};
#endif | [
"[email protected]@fe84ce02-70a6-11de-8b73-c1edde54a3c7"
] | [
[
[
1,
115
]
]
] |
9bb65ae74aa9dacbf59f26a017e22388abfedd4b | 5ac13fa1746046451f1989b5b8734f40d6445322 | /minimangalore/Nebula2/code/UrbanExtreme/src/properties/ueplayercameraproperty.cc | 35e21959c902791b8ffc2d582f3cb2852fdb655c | [] | no_license | moltenguy1/minimangalore | 9f2edf7901e7392490cc22486a7cf13c1790008d | 4d849672a6f25d8e441245d374b6bde4b59cbd48 | refs/heads/master | 2020-04-23T08:57:16.492734 | 2009-08-01T09:13:33 | 2009-08-01T09:13:33 | 35,933,330 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,271 | cc | //----------------------------------------------------------------------------
// tway_main.cc
//
// (C)2007 kaikai
//----------------------------------------------------------------------------
#include "foundation/ptr.h"
#include "graphics/server.h"
#include "kernel/nfileserver2.h"
#include "managers/factorymanager.h"
#include "game/entity.h"
#include "input/server.h"
#include "msg/cameraorbit.h"
#include "msg/camerareset.h"
#include "properties/graphicsproperty.h"
#include "properties/lightproperty.h"
#include "properties/transformableproperty.h"
#include "properties/environmentgraphicsproperty.h"
#include "properties/environmentcollideproperty.h"
#include "properties/physicsproperty.h"
#include "properties/videocameraproperty.h"
#include "physics/meshshape.h"
#include "physics/capsuleshape.h"
#include "physics/sphereshape.h"
#include "physics/composite.h"
#include "physics/hinge2joint.h"
#include "util/segmentedgfxutil.h"
#include "ueplayercameraproperty.h"
#include "attributes/ueattributes.h"
namespace Properties
{
ImplementRtti(Properties::UePlayerCameraProperty, Properties::ChaseCameraProperty);
ImplementFactory(Properties::UePlayerCameraProperty);
UePlayerCameraProperty::UePlayerCameraProperty()
{
}
UePlayerCameraProperty::~UePlayerCameraProperty()
{
}
void UePlayerCameraProperty::SetupDefaultAttributes()
{
CameraProperty::SetupDefaultAttributes();
GetEntity()->SetFloat(Attr::CameraDistance, 0.0f);
GetEntity()->SetFloat(Attr::CameraMinDistance, 0.0f);
GetEntity()->SetFloat(Attr::CameraMaxDistance, 0.0f);
GetEntity()->SetVector3(Attr::CameraOffset, vector3(0.0f, 0.0f, 0.0f));
GetEntity()->SetFloat(Attr::CameraLowStop, 0.0f);
GetEntity()->SetFloat(Attr::CameraHighStop, 0.0f);
GetEntity()->SetFloat(Attr::CameraAngularVelocity, 0.0f);
GetEntity()->SetFloat(Attr::CameraDistanceStep, 0.0f);
GetEntity()->SetFloat(Attr::CameraLinearGain, 0.0f);
GetEntity()->SetFloat(Attr::CameraAngularGain,0.0f);
GetEntity()->SetFloat(Attr::CameraDefaultTheta, n_deg2rad(0.0f));
// stand
poseCamera[0].rotate_x(n_deg2rad(4.5f));
poseCamera[0].translate(vector3(0.0f,0.4f,0.95f));
// crounch
poseCamera[1].rotate_x(n_deg2rad(5.0f));
poseCamera[1].translate(vector3(0.0f,0.3f,0.6f));
// prone
poseCamera[2].rotate_x(n_deg2rad(5.5f));
poseCamera[2].translate(vector3(0.0f,0.2f,0.45f));
onlyStandPose = false;
}
void
UePlayerCameraProperty::UpdateCamera()
{
Graphics::CameraEntity* camera = Graphics::Server::Instance()->GetCamera();
n_assert(camera != 0);
static const vector3 upVec(0.0f, 1.0f, 0.0f);
// compute the lookat point in global space
const matrix44& m44 = GetEntity()->GetMatrix44(Attr::Transform);
int poseCurr = GetEntity()->GetInt(Attr::pose);
matrix44 newmatrix;
newmatrix = m44;
if (onlyStandPose)
{
newmatrix = poseCamera[0] * newmatrix;
}
else
{
newmatrix = poseCamera[poseCurr] * newmatrix;
}
// update the graphics subsystem camera
camera->SetTransform(newmatrix);
}
}
//----------------------------------------------------------------------------
// EOF
//----------------------------------------------------------------------------
| [
"ldw9981@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c"
] | [
[
[
1,
120
]
]
] |
e1ff873b16ecf254e8b6f4b0e8540e5b0a7bf14b | df7f75e3289b4eee692438c627b21a5563d66db1 | /segd_operators.cpp | 788d5f26f9133f522be974602ad72f34bed26ee4 | [] | no_license | arnar/falskur_fjolnir | 3ec6c9bd11c6faf8c902de0569ad38bd02825285 | 23f69832bebf8843dd9aa910f99b4644520ae82c | refs/heads/master | 2016-09-10T19:03:03.558066 | 2010-06-03T11:20:26 | 2010-06-03T11:20:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,757 | cpp | #include "segdir.h"
#include "smali.h"
using namespace ff;
BinOpSegd::~BinOpSegd() {
delete _left;
delete _right;
}
void BinOpSegd::setUmlykjandiStef(Stef* stef) {
Segd::setUmlykjandiStef(stef);
_right->setUmlykjandiStef(stef);
_left->setUmlykjandiStef(stef);
}
void OgSegd::generateAXDX(ostream& out) const {
int ut = newlabel();
_left->generateAXDX(out);
emit("TEST", "DL,1");
emit("JNZ", l(ut));
_right->generateAXDX(out);
emit_label(l(ut));
}
void OgSegd::generateJUMP(ostream& out, int iftrue, int iffalse) const {
if (iffalse) {
_left->generateJUMP(out,0,iffalse);
_right->generateJUMP(out,iftrue,iffalse);
} else {
int ut = newlabel();
_left->generateJUMP(out,0,ut);
_right->generateJUMP(out,iftrue,0);
emit_label(l(ut));
}
}
void EdaSegd::generateAXDX(ostream& out) const {
int ut = newlabel();
_left->generateAXDX(out);
emit("TEST", "DL,1");
emit("JZ", l(ut));
_right->generateAXDX(out);
emit_label(l(ut));
}
void EdaSegd::generateJUMP(ostream& out, int iftrue, int iffalse) const {
if (iftrue) {
_left->generateJUMP(out,iftrue,0);
_right->generateJUMP(out,iftrue,iffalse);
} else {
int ut = newlabel();
_left->generateJUMP(out,ut,0);
_right->generateJUMP(out,0,iffalse);
emit_label(l(ut));
}
}
EkkiSegd::~EkkiSegd() {
delete _segd;
}
void EkkiSegd::setUmlykjandiStef(Stef* stef) {
Segd::setUmlykjandiStef(stef);
_segd->setUmlykjandiStef(stef);
}
void EkkiSegd::generateAXDX(ostream& out) const {
_segd->generateAXDX(out);
emit("MOV", "AX,ES");
emit("AND", "DX,1");
emit("INC", "DX");
}
void EkkiSegd::generateJUMP(ostream& out, int iftrue, int iffalse) const {
_segd->generateJUMP(out, iffalse, iftrue);
} | [
"[email protected]"
] | [
[
[
1,
77
]
]
] |
c71999a41a119734f8ea50d188c83a23f65b8ae8 | 276a89682066266de78e0e2a3fcacb1bb47578da | /tags/7pre1/corbautil/cxx/gsp/dce_gsp_mutex.h | 87ce2506abf611f5f5b8f3422ead56989dee9e2f | [] | no_license | BackupTheBerlios/v-q-svn | e886b6e5945f9cc760a526aff8a36c2f59db35ea | c8f787e77272d5da15ef5d91a596b64ce1cf4d36 | refs/heads/master | 2020-05-31T15:14:58.511327 | 2006-03-20T20:27:23 | 2006-03-20T20:27:23 | 40,824,182 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,575 | h | //-----------------------------------------------------------------------
// Copyright IONA Technologies 2002-2004. All rights reserved.
// This software is provided "as is".
//
// File: dce_gsp_mutex.h
//
// Policy: GSP_Mutex[Op] // non-recursive mutex
//----------------------------------------------------------------------
#ifndef DCE_GSP_MUTEX_H_
#define DCE_GSP_MUTEX_H_
//--------
// #include's
//--------
#include <pthread.h>
#include <assert.h>
//--------
// Forward declarations.
//--------
class GSP_Mutex;
class GSP_Mutex {
public:
inline GSP_Mutex();
inline ~GSP_Mutex();
class Op {
public:
inline Op(GSP_Mutex &);
inline ~Op();
protected:
GSP_Mutex &m_sync;
};
protected:
friend class Op;
pthread_mutex_t m_mutex;
};
//--------
// Inline implementation of class GSP_Mutex
//--------
inline GSP_Mutex::GSP_Mutex()
{
int status;
status = pthread_mutex_init(&m_mutex, pthread_mutexattr_default);
assert(status == 0);
}
inline GSP_Mutex::~GSP_Mutex()
{
int status;
status = pthread_mutex_destroy(&m_mutex);
assert(status == 0);
}
//--------
// Inline implementation of class GSP_Mutex::Op
//--------
inline GSP_Mutex::Op::Op(GSP_Mutex &sync_data)
: m_sync(sync_data)
{
int status;
status = pthread_mutex_lock(&m_sync.m_mutex);
assert(status == 0);
}
inline GSP_Mutex::Op::~Op()
{
int status;
status = pthread_mutex_unlock(&m_sync.m_mutex);
assert(status == 0);
}
#endif
| [
"new@36831980-ddd6-0310-a275-bfd50d89a3dc"
] | [
[
[
1,
110
]
]
] |
fb36b577b0b24475fa42273f6c59e50ee051b4b1 | 011359e589f99ae5fe8271962d447165e9ff7768 | /ps3/drv.cpp | fe405f620eafe305ca91f934d7106c925f08c279 | [] | 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 | 4,308 | cpp | // Driver Init module
#include "burner.h"
#include "tracklst.h"
#ifndef NO_IPS
//#include "patch.h"
#endif
#ifndef NO_COMBO
#include "combo.h"
#endif
#include "audio_driver.h"
int bDrvOkay = 0; // 1 if the Driver has been inited okay, and it's okay to use the BurnDrv functions
static bool bSaveRAM = false;
static int DoLibInit() // Do Init of Burn library driver
{
int nRet = 0;
BArchiveOpen(false);
// If there is a problem with the romset, report it
switch (BArchiveStatus())
{
case BARC_STATUS_BADDATA:
FBAPopupDisplay(PUF_TYPE_WARNING);
BArchiveClose();
return 1;
break;
case BARC_STATUS_ERROR:
FBAPopupDisplay(PUF_TYPE_ERROR);
break;
}
nRet = BurnDrvInit();
BArchiveClose();
if (nRet)
return 3;
else
return 0;
}
// Catch calls to BurnLoadRom() once the emulation has started;
// Intialise the zip module before forwarding the call, and exit cleanly.
static int __cdecl DrvLoadRom(unsigned char* Dest, int* pnWrote, int i)
{
int nRet;
BArchiveOpen(false);
if ((nRet = BurnExtLoadRom(Dest, pnWrote, i)) != 0)
{
char* pszFilename;
BurnDrvGetRomName(&pszFilename, i, 0);
}
BArchiveClose();
BurnExtLoadRom = DrvLoadRom;
return nRet;
}
// Media init / exit
static int mediaInit(void)
{
if (!bInputOkay)
InputInit(); // Init Input
nAppVirtualFps = nBurnFPS;
char * szName;
BurnDrvGetArchiveName(&szName, 0);
char * vendetta_hack = strstr(szName,"vendetta");
if (!bAudOkay || vendetta_hack || bAudReinit)
{
if(vendetta_hack && bAudSetSampleRate == 48010)
{
// If Vendetta is not played with sound samplerate at 44KHz, then
// slo-mo Vendetta happens - so we set sound samplerate at 44KHz
// and then resample to 48Khz for this game. Possibly more games
// are like this, so check for more
audio_init(SAMPLERATE_44KHZ);
bAudReinit = true;
}
else
{
audio_init(bAudSetSampleRate);
bAudReinit = false;
}
}
// Assume no sound
nBurnSoundRate = 0;
pBurnSoundOut = NULL;
if (bAudOkay)
{
nBurnSoundRate = nAudSampleRate;
nBurnSoundLen = nAudSegLen;
}
return 0;
}
//forward declarations
int VidReinit(void);
// simply reinit screen, added by regret
void simpleReinitScrn(void)
{
VidReinit();
}
//#define NEED_MEDIA_REINIT
// no need to reinit media when init a driver, modified by regret
int BurnerDrvInit(int nDrvNum, bool bRestore)
{
BurnerDrvExit(); // Make sure exited
nBurnDrvSelect = nDrvNum; // Set the driver number
// Define nMaxPlayers early; GameInpInit() needs it (normally defined in DoLibInit()).
nMaxPlayers = BurnDrvGetMaxPlayers();
GameInpInit(); // Init game input
if (ConfigGameLoad(true))
loadDefaultInput(); // load default input mapping
GameInpDefault();
// set functions
BurnReinitScrn = simpleReinitScrn;
mediaInit();
#ifndef NO_IPS
//bDoPatch = true; // play with ips
//loadActivePatches();
//BurnApplyPatch = applyPatches;
#endif
int nStatus = DoLibInit(); // Init the Burn library's driver
if (nStatus)
{
if (nStatus & 2)
BurnDrvExit(); // Exit the driver
return 1;
}
// ==> for changing sound track
//parseTracklist();
// <==
BurnExtLoadRom = DrvLoadRom;
bDrvOkay = 1; // Okay to use all BurnDrv functions
bSaveRAM = false;
if (bRestore)
{
bSaveRAM = true;
}
// Reset the speed throttling code, so we don't 'jump' after the load
return 0;
}
int DrvInitCallback()
{
return BurnerDrvInit(nBurnDrvSelect, false);
}
int BurnerDrvExit()
{
if (bDrvOkay)
{
VidExit();
//jukeDestroy();
if (nBurnDrvSelect < nBurnDrvCount)
{
//MemCardEject(); // Eject memory card if present
if (bSaveRAM)
{
bSaveRAM = false;
}
ConfigGameSave(true); // save game config
GameInpExit(); // Exit game input
BurnDrvExit(); // Exit the driver
}
}
BurnExtLoadRom = NULL;
bDrvOkay = 0; // Stop using the BurnDrv functions
if (bAudOkay)
{
audio_blank(); // Write silence into the sound buffer on exit, and for drivers which don't use pBurnSoundOut
}
nBurnDrvSelect = ~0U; // no driver selected
nBurnLayer = 0xFF; // show all layers
return 0;
}
| [
"[email protected]",
"Test@.(none)"
] | [
[
[
1,
9
],
[
11,
215
]
],
[
[
10,
10
]
]
] |
e44af02a88e2330095164b1c437a8e9cb5ffb2e6 | 3201bc35622102fe99b50e5f7d1351ad0d89b2f2 | /design/repository/models/dsp/c_adc_frontend.cpp | fa3e620866351886922b373069416dd1babfdf98 | [] | no_license | embisi-github/embisi_gip | 1f7e8ce334ae9611f52a2cd6e536ef71fb00cec4 | dd6dfe8667b28f03dba2ac605d67916cb4483005 | refs/heads/master | 2021-01-10T12:33:55.917299 | 2006-11-27T09:43:39 | 2006-11-27T09:43:39 | 48,285,426 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 37,275 | cpp | /*a Copyright Gavin J Stark
*/
/*a Examples
*/
/*a Includes
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "be_model_includes.h"
#include "sl_general.h"
#include "sl_token.h"
/*a Defines
*/
#define MAX_INT_WIDTH (8)
#define CIC_WIDTH (40)
#define CLOCKED_INPUT( name, width, clk ) \
{ \
engine->register_input_signal( engine_handle, #name, width, (int **)&inputs.name ); \
engine->register_input_used_on_clock( engine_handle, #name, #clk, 1 ); \
}
#define COMB_INPUT( name, width ) \
{ \
engine->register_input_signal( engine_handle, #name, width, (int **)&inputs.name ); \
engine->register_comb_input( engine_handle, #name ); \
}
#define COMB_OUTPUT( name, width )\
{ \
engine->register_output_signal( engine_handle, #name, width, (int *)&combinatorials.name ); \
engine->register_comb_output( engine_handle, #name ); \
}
#define STATE_OUTPUT( name, width, clk )\
{ \
engine->register_output_signal( engine_handle, #name, width, (int *)&posedge_int_clock_state.name ); \
engine->register_output_generated_on_clock( engine_handle, #name, #clk, 1 ); \
}
/*a Types for c_adc_frontend
*/
/*t t_phase_acc_fsm
*/
typedef enum
{
phase_acc_fsm_idle,
phase_acc_fsm_reading_cosine,
phase_acc_fsm_reading_sine
} t_phase_acc_fsm;
/*t t_mixer_fsm
*/
typedef enum
{
mixer_fsm_idle,
mixer_fsm_cosine_done,
mixer_fsm_sine_done
} t_mixer_fsm;
/*t t_adc_frontend_inputs
Reset
Digital data in (probably should have some form of clock enable)
Postbus for configuration and data out
*/
typedef struct t_adc_frontend_inputs
{
unsigned int *int_reset;
unsigned int *data_0;
unsigned int *data_1;
} t_adc_frontend_inputs;
/*t t_adc_frontend_data_clock_state
*/
typedef struct t_adc_frontend_data_clock_state
{
unsigned int data_0_reg; // input registers for data
unsigned int data_1_reg;
unsigned int selected_i; // mux select from data registers for in-phase for sync to internal clock domain
unsigned int selected_q; // mux select from data registers for quadrature for sync to internal clock domain
unsigned int selected_toggle; // toggled when the data in the selected registers becomes valid - an edge on this must be detected by the internal clock
} t_adc_frontend_data_clock_state;
/*t t_adc_frontend_internal_clock_sync_state
*/
typedef struct t_adc_frontend_internal_clock_sync_state
{
// we synchronize a toggle and register the data, all to the internal clock domain
// the synchronizer for the toggle is a metastable flop, a stable flop, and a 'last value' flop; if the stable and last flops differ in value, then data is present in the register
// if the external clock occurs near-simultaneously with the internal clock, then the metastability can occur
// there are two cases to consider
// 1. the data register clocks to a new value, while the metastable flop settles untoggled, on the clock collision
// 2. the data register clocks an incorrect (or old) value, while the metastable flop settles on the toggle, on the clock collision
// In case 1:
// during cycle 0 (internal cycle post clock collision) metastable is untoggled, data register has new data
// during cycle 1 metastable has toggled, stable has not
// during cycle 2 stable has toggled, last has not, and so valid data is expected in the register
// therefore the next external clock cannot occur prior to the end of cycle 2 - this gives a minimum of 3 internal clocks per external clock tick
// In case 2:
// during cycle 0 metastable has toggled, data register has old or invalid data
// during cycle 1 stable has toggled, last has not, and data register has valid data, as required
// therefore there is no race condition for case 2, and no clocking limit
unsigned int sync_reg_i_0; // internal clock version of sync of selected_ data
unsigned int sync_reg_q_0;
int sync_toggle_0; // first stage of sync of selected_toggle
int sync_toggle_1; // second stage
int sync_last_toggle; // if this differs from sync_toggle_1 then an edge occurred on the toggle and the sync register is required to have valid data
unsigned int i_out; // output data
unsigned int q_out;
int iq_valid; // asserted if i_out and q_out are valid
} t_adc_frontend_internal_clock_sync_state;
/*t t_phase_acc_rom_entry
*/
typedef struct
{
unsigned int base_value;
unsigned int delta;
unsigned long error_bits;
} t_phase_acc_rom_entry;
/*t t_adc_frontend_internal_clock_phase_acc_state
*/
typedef struct t_adc_frontend_internal_clock_phase_acc_state
{
unsigned int phase; // current phase
unsigned int phase_step; // increment per tick
t_phase_acc_fsm fsm; // idle, reading sin, reading cos
struct
{
int rom_reading_cosine;
int negate;
int fine_phase;
unsigned int rom_base_value;
unsigned int rom_delta;
unsigned int rom_error_bits;
} rom_stage;
struct
{
int negate;
int fine_phase; // 4 bit value
int valid_cosine;
int base_value; // 14 bit value, 0.14
int delta; // 6 bit value, 0.15 bottom 6 bits
int error_bit; // 1 bit value, 0.15 bottom bit
} calc_in_stage;
struct
{
int value; // 15 bit value, 0.15
int sign;
int valid_cosine;
} data_out_stage;
} t_adc_frontend_internal_clock_phase_acc_state;
/*t t_adc_frontend_internal_clock_mixer_state
*/
typedef struct t_adc_frontend_internal_clock_mixer_state
{
t_mixer_fsm fsm;
unsigned int mult_a;
unsigned int mult_b;
unsigned int i_out;
unsigned int q_out;
int valid_out;
} t_adc_frontend_internal_clock_mixer_state;
/*t t_adc_frontend_cic_int_stage
*/
typedef struct t_adc_frontend_cic_int_stage
{
unsigned long long calc; // normally holds i; add to input, put result in out
unsigned long long out; // normally holds q; pass to calc when integrating
int valid_out;
} t_adc_frontend_cic_int_stage;
/*t t_adc_frontend_cic_comb_stage
*/
typedef struct t_adc_frontend_cic_comb_stage
{
unsigned long long pipe_0; // normally holds q; pass to pipe_1 when combing
unsigned long long pipe_1; // normally holds i; subtract from input when combing
unsigned long long value; // result of comb
int valid_out;
} t_adc_frontend_cic_comb_stage;
/*t t_adc_frontend_internal_clock_cic_state
*/
typedef struct t_adc_frontend_internal_clock_cic_state
{
t_adc_frontend_cic_int_stage int_stage[5];
t_adc_frontend_cic_comb_stage comb_stage[5];
unsigned int q_store;
struct
{
int valid_out;
unsigned int count;
unsigned int factor;
} decimate;
} t_adc_frontend_internal_clock_cic_state;
/*t t_adc_frontend_internal_clock_state
*/
typedef struct t_adc_frontend_internal_clock_state
{
t_adc_frontend_internal_clock_sync_state sync;
t_adc_frontend_internal_clock_phase_acc_state phase_acc;
t_adc_frontend_internal_clock_mixer_state mixer;
t_adc_frontend_internal_clock_cic_state cic;
double pwr_calc;
unsigned int result;
int calc;
int valid;
} t_adc_frontend_internal_clock_state;
/*t c_adc_frontend
*/
class c_adc_frontend
{
public:
c_adc_frontend::c_adc_frontend( class c_engine *eng, void *eng_handle );
c_adc_frontend::~c_adc_frontend();
t_sl_error_level c_adc_frontend::delete_instance( void );
t_sl_error_level c_adc_frontend::reset( int pass );
t_sl_error_level c_adc_frontend::preclock_posedge_int_clock( void );
t_sl_error_level c_adc_frontend::clock_posedge_int_clock( void );
t_sl_error_level c_adc_frontend::preclock_posedge_data_clock( void );
t_sl_error_level c_adc_frontend::clock_posedge_data_clock( void );
private:
c_engine *engine;
void *engine_handle;
void c_adc_frontend::cic_int_stage_preclock( int stage, int valid_in, unsigned long long value );
void c_adc_frontend::cic_comb_stage_preclock( int stage, int valid_in, unsigned long long value );
t_adc_frontend_inputs inputs;
t_adc_frontend_internal_clock_state state;
t_adc_frontend_internal_clock_state next_state;
t_adc_frontend_data_clock_state data_state;
t_adc_frontend_data_clock_state next_data_state;
int phase_resolution;
int coarse_resolution;
int fine_resolution;
};
/*a Static ROM
*/
static t_phase_acc_rom_entry rom[1024] =
{
#include "rom.txt"
};
/*a Static variables for state
*/
/*v struct_offset wrapper
*/
#define struct_offset( ptr, a ) (((char *)&(ptr->a))-(char *)ptr)
/*v state_desc_posedge_int_clock
*/
static t_adc_frontend_internal_clock_state *___posedge_int_clock__ptr;
static t_engine_state_desc state_desc_posedge_int_clock[] =
{
{"sync_toggle_0", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, sync.sync_toggle_0), {1,0,0,0}, {NULL,NULL,NULL,NULL} },
{"sync_toggle_1", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, sync.sync_toggle_1), {1,0,0,0}, {NULL,NULL,NULL,NULL} },
{"sync_last_toggle", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, sync.sync_last_toggle), {1,0,0,0}, {NULL,NULL,NULL,NULL} },
{"sync_iq_valid", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, sync.iq_valid), {1,0,0,0}, {NULL,NULL,NULL,NULL} },
{"sync_i_out", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, sync.i_out), {16,0,0,0}, {NULL,NULL,NULL,NULL} },
{"sync_q_out", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, sync.q_out), {16,0,0,0}, {NULL,NULL,NULL,NULL} },
{"phase", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, phase_acc.phase), {24,0,0,0}, {NULL,NULL,NULL,NULL} },
{"phase_fsm", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, phase_acc.fsm), {2,0,0,0}, {NULL,NULL,NULL,NULL} },
{"phase_rom_reading_cosine", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, phase_acc.rom_stage.rom_reading_cosine), {1,0,0,0}, {NULL,NULL,NULL,NULL} },
{"phase_rom_negate", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, phase_acc.rom_stage.negate), {1,0,0,0}, {NULL,NULL,NULL,NULL} },
{"phase_rom_fine_phase", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, phase_acc.rom_stage.fine_phase), {4,0,0,0}, {NULL,NULL,NULL,NULL} },
{"phase_rom_base_value", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, phase_acc.rom_stage.rom_base_value), {14,0,0,0}, {NULL,NULL,NULL,NULL} },
{"phase_rom_delta", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, phase_acc.rom_stage.rom_delta), {6,0,0,0}, {NULL,NULL,NULL,NULL} },
{"phase_rom_error_bits", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, phase_acc.rom_stage.rom_error_bits), {16,0,0,0}, {NULL,NULL,NULL,NULL} },
{"phase_calc_base_value", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, phase_acc.calc_in_stage.base_value), {14,0,0,0}, {NULL,NULL,NULL,NULL} },
{"phase_calc_delta", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, phase_acc.calc_in_stage.delta), {6,0,0,0}, {NULL,NULL,NULL,NULL} },
{"phase_calc_error_bit", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, phase_acc.calc_in_stage.error_bit), {1,0,0,0}, {NULL,NULL,NULL,NULL} },
{"phase_calc_valid_cosine", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, phase_acc.calc_in_stage.valid_cosine), {1,0,0,0}, {NULL,NULL,NULL,NULL} },
{"phase_calc_negate", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, phase_acc.calc_in_stage.negate), {1,0,0,0}, {NULL,NULL,NULL,NULL} },
{"phase_data_out_valid_cosine", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, phase_acc.data_out_stage.valid_cosine), {1,0,0,0}, {NULL,NULL,NULL,NULL} },
{"phase_data_out_value", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, phase_acc.data_out_stage.value), {15,0,0,0}, {NULL,NULL,NULL,NULL} },
{"phase_data_out_sign", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, phase_acc.data_out_stage.sign), {1,0,0,0}, {NULL,NULL,NULL,NULL} },
{"mixer_fsm", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, mixer.fsm), {2,0,0,0}, {NULL,NULL,NULL,NULL} },
{"mixer_valid_out", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, mixer.valid_out), {1,0,0,0}, {NULL,NULL,NULL,NULL} },
{"mixer_i_out", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, mixer.i_out), {18,0,0,0}, {NULL,NULL,NULL,NULL} },
{"mixer_q_out", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, mixer.q_out), {18,0,0,0}, {NULL,NULL,NULL,NULL} },
{"mixer_fsm", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, mixer.fsm), {2,0,0,0}, {NULL,NULL,NULL,NULL} },
{"cic_decimate_count", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, cic.decimate.count), {6,0,0,0}, {NULL,NULL,NULL,NULL} },
{"cic_decimate_factor", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, cic.decimate.factor), {6,0,0,0}, {NULL,NULL,NULL,NULL} },
{"cic_decimate_valid_out", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, cic.decimate.valid_out), {1,0,0,0}, {NULL,NULL,NULL,NULL} },
{"cic_0_int_out_valid", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, cic.int_stage[0].valid_out), {1,0,0,0}, {NULL,NULL,NULL,NULL} },
{"cic_1_int_out_valid", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, cic.int_stage[1].valid_out), {1,0,0,0}, {NULL,NULL,NULL,NULL} },
{"cic_2_int_out_valid", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, cic.int_stage[2].valid_out), {1,0,0,0}, {NULL,NULL,NULL,NULL} },
{"cic_3_int_out_valid", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, cic.int_stage[3].valid_out), {1,0,0,0}, {NULL,NULL,NULL,NULL} },
{"cic_4_int_out_valid", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, cic.int_stage[4].valid_out), {1,0,0,0}, {NULL,NULL,NULL,NULL} },
{"cic_0_int_out", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, cic.int_stage[0].out), {CIC_WIDTH,0,0,0}, {NULL,NULL,NULL,NULL} },
{"cic_1_int_out", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, cic.int_stage[1].out), {CIC_WIDTH,0,0,0}, {NULL,NULL,NULL,NULL} },
{"cic_2_int_out", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, cic.int_stage[2].out), {CIC_WIDTH,0,0,0}, {NULL,NULL,NULL,NULL} },
{"cic_3_int_out", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, cic.int_stage[3].out), {CIC_WIDTH,0,0,0}, {NULL,NULL,NULL,NULL} },
{"cic_4_int_out", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, cic.int_stage[4].out), {CIC_WIDTH,0,0,0}, {NULL,NULL,NULL,NULL} },
{"cic_0_comb_out_valid", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, cic.comb_stage[0].valid_out), {1,0,0,0}, {NULL,NULL,NULL,NULL} },
{"cic_1_comb_out_valid", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, cic.comb_stage[1].valid_out), {1,0,0,0}, {NULL,NULL,NULL,NULL} },
{"cic_2_comb_out_valid", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, cic.comb_stage[2].valid_out), {1,0,0,0}, {NULL,NULL,NULL,NULL} },
{"cic_3_comb_out_valid", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, cic.comb_stage[3].valid_out), {1,0,0,0}, {NULL,NULL,NULL,NULL} },
{"cic_4_comb_out_valid", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, cic.comb_stage[4].valid_out), {1,0,0,0}, {NULL,NULL,NULL,NULL} },
{"cic_0_comb_out", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, cic.comb_stage[0].value), {CIC_WIDTH,0,0,0}, {NULL,NULL,NULL,NULL} },
{"cic_1_comb_out", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, cic.comb_stage[1].value), {CIC_WIDTH,0,0,0}, {NULL,NULL,NULL,NULL} },
{"cic_2_comb_out", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, cic.comb_stage[2].value), {CIC_WIDTH,0,0,0}, {NULL,NULL,NULL,NULL} },
{"cic_3_comb_out", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, cic.comb_stage[3].value), {CIC_WIDTH,0,0,0}, {NULL,NULL,NULL,NULL} },
{"cic_4_comb_out", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, cic.comb_stage[4].value), {CIC_WIDTH,0,0,0}, {NULL,NULL,NULL,NULL} },
{"valid", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, valid), {1,0,0,0}, {NULL,NULL,NULL,NULL} },
{"result", engine_state_desc_type_bits, NULL, struct_offset(___posedge_int_clock__ptr, result), {16,0,0,0}, {NULL,NULL,NULL,NULL} },
{"", engine_state_desc_type_none, NULL, 0, {0,0,0,0}, {NULL,NULL,NULL,NULL} }
};
/*v struct_offset unwrapper
*/
#undef struct_offset
/*a Static wrapper functions for adc_frontend
*/
/*f adc_frontend_1r_1w_32_32_instance_fn
*/
static t_sl_error_level adc_frontend_instance_fn( c_engine *engine, void *engine_handle )
{
c_adc_frontend *mod;
mod = new c_adc_frontend( engine, engine_handle );
if (!mod)
return error_level_fatal;
return error_level_okay;
}
/*f adc_frontend_delete_fn - simple callback wrapper for the main method
*/
static t_sl_error_level adc_frontend_delete_fn( void *handle )
{
c_adc_frontend *mod;
t_sl_error_level result;
mod = (c_adc_frontend *)handle;
result = mod->delete_instance();
delete( mod );
return result;
}
/*f adc_frontend_reset_fn
*/
static t_sl_error_level adc_frontend_reset_fn( void *handle, int pass )
{
c_adc_frontend *mod;
mod = (c_adc_frontend *)handle;
return mod->reset( pass );
}
/*f adc_frontend_preclock_posedge_int_clock_fn
*/
static t_sl_error_level adc_frontend_preclock_posedge_int_clock_fn( void *handle )
{
c_adc_frontend *mod;
mod = (c_adc_frontend *)handle;
return mod->preclock_posedge_int_clock();
}
/*f adc_frontend_clock_posedge_int_clock_fn
*/
static t_sl_error_level adc_frontend_clock_posedge_int_clock_fn( void *handle )
{
c_adc_frontend *mod;
mod = (c_adc_frontend *)handle;
return mod->clock_posedge_int_clock();
}
/*f adc_frontend_preclock_posedge_data_clock_fn
*/
static t_sl_error_level adc_frontend_preclock_posedge_data_clock_fn( void *handle )
{
c_adc_frontend *mod;
mod = (c_adc_frontend *)handle;
return mod->preclock_posedge_data_clock();
}
/*f adc_frontend_clock_posedge_data_clock_fn
*/
static t_sl_error_level adc_frontend_clock_posedge_data_clock_fn( void *handle )
{
c_adc_frontend *mod;
mod = (c_adc_frontend *)handle;
return mod->clock_posedge_data_clock();
}
/*a Constructors and destructors for adc_frontend
*/
/*f c_adc_frontend::c_adc_frontend
*/
c_adc_frontend::c_adc_frontend( class c_engine *eng, void *eng_handle )
{
engine = eng;
engine_handle = eng_handle;
phase_resolution = 24; // resolution of the phase accumulator itself
coarse_resolution = 10; // coarse resolution - resolution of the ROM
fine_resolution = 4; // steps per ROM entry
/*b Instantiate module
*/
engine->register_delete_function( engine_handle, (void *)this, adc_frontend_delete_fn );
engine->register_reset_function( engine_handle, (void *)this, adc_frontend_reset_fn );
engine->register_clock_fns( engine_handle, (void *)this, "int_clock", adc_frontend_preclock_posedge_int_clock_fn, adc_frontend_clock_posedge_int_clock_fn );
engine->register_clock_fns( engine_handle, (void *)this, "data_clock", adc_frontend_preclock_posedge_data_clock_fn, adc_frontend_clock_posedge_data_clock_fn );
CLOCKED_INPUT( int_reset, 1, int_clock );
CLOCKED_INPUT( data_0, 16, data_clock );
CLOCKED_INPUT( data_1, 16, data_clock );
engine->register_output_signal( engine_handle, "sync_iq_valid", 1, (int *)&state.sync.iq_valid );
engine->register_output_generated_on_clock( engine_handle, "sync_iq_valid", "int_clock", 1 );
engine->register_output_signal( engine_handle, "sync_i_out", 16, (int *)&state.sync.i_out );
engine->register_output_generated_on_clock( engine_handle, "sync_i_out", "int_clock", 1 );
engine->register_output_signal( engine_handle, "sync_q_out", 16, (int *)&state.sync.q_out );
engine->register_output_generated_on_clock( engine_handle, "sync_q_out", "int_clock", 1 );
/*b Register state then reset
*/
engine->register_state_desc( engine_handle, 1, state_desc_posedge_int_clock, &state, NULL );
reset( 0 );
/*b Done
*/
}
/*f c_adc_frontend::~c_adc_frontend
*/
c_adc_frontend::~c_adc_frontend()
{
delete_instance();
}
/*f c_adc_frontend::delete_instance
*/
t_sl_error_level c_adc_frontend::delete_instance( void )
{
return error_level_okay;
}
/*a Class reset/preclock/clock methods for adc_frontend
*/
/*f c_adc_frontend::reset
*/
t_sl_error_level c_adc_frontend::reset( int pass )
{
data_state.selected_toggle = 0;
state.sync.sync_toggle_0 = 0;
state.sync.sync_toggle_1 = 0;
state.sync.sync_last_toggle = 0;
state.sync.iq_valid = 0;
state.phase_acc.phase = 0;
state.phase_acc.phase_step = 7953548; // 9.48/20.0*1<<24 - actually 0x795cbc
state.phase_acc.phase_step = 7952400; // 9.48/20.0*1<<24 - actually 0x795810
state.phase_acc.phase_step = 0x7a0000; // beat of 428ns
state.phase_acc.phase_step = 0x7b0000; // beat of 520ns
state.phase_acc.phase_step = 0x760000; // beat of 260ns - looking for 307
state.phase_acc.phase_step = 0x770000; // beat of 288ns - looking for 307
state.phase_acc.phase_step = 0x77e000; // beat of 315ns - looking for 307
state.phase_acc.phase_step = 0x77a000; // beat of 306ns - looking for 307
// state.phase_acc.phase_step = 0;
state.phase_acc.phase = 0x400000;
state.phase_acc.fsm = phase_acc_fsm_idle;
state.phase_acc.rom_stage.rom_reading_cosine = 0;
state.phase_acc.data_out_stage.valid_cosine = 0;
state.phase_acc.calc_in_stage.valid_cosine = 0;
state.mixer.fsm = mixer_fsm_idle;
state.mixer.valid_out = 0;
state.cic.int_stage[0].valid_out = 0;
state.cic.int_stage[1].valid_out = 0;
state.cic.int_stage[2].valid_out = 0;
state.cic.int_stage[3].valid_out = 0;
state.cic.int_stage[4].valid_out = 0;
state.cic.decimate.count = state.cic.decimate.factor = 9;
return error_level_okay;
}
/*f c_adc_frontend::preclock_posedge_data_clock
*/
t_sl_error_level c_adc_frontend::preclock_posedge_data_clock( void )
{
/*b Copy current to next
*/
memcpy( &next_data_state, &data_state, sizeof(data_state));
/*b Synchronizer and input
*/
next_data_state.data_0_reg = inputs.data_0[0];
next_data_state.data_1_reg = inputs.data_1[0];
next_data_state.selected_i = data_state.data_0_reg; // no muxing yet!
next_data_state.selected_q = data_state.data_1_reg; // no muxing yet!
next_data_state.selected_toggle = !data_state.selected_toggle;
/*b Done
*/
return error_level_okay;
}
/*f c_adc_frontend::clock_posedge_data_clock
*/
t_sl_error_level c_adc_frontend::clock_posedge_data_clock( void )
{
/*b Copy next to current
*/
memcpy( &data_state, &next_data_state, sizeof(data_state));
/*b Done
*/
return error_level_okay;
}
/*f c_adc_frontend::cic_int_stage_preclock
*/
#define sign_extend(v,w) { (v) |= (v>>(w-1)) ? ((0xffffffffffffffffULL)<<w):0; }
static signed int mult_u16_x_u15_sign_s18( unsigned int a, unsigned int b, int sign )
{
unsigned int r;
r = (a*b)>>15; // go from 16+15 = 31 unsigned bits to 16 unsigned bits
if (sign) // sign extend to 18 signed bits
{
r = -r;
}
r = r&0x3ffff;
return r;
}
void c_adc_frontend::cic_int_stage_preclock( int stage, int valid_in, unsigned long long value )
{
stage--;
next_state.cic.int_stage[stage].calc = state.cic.int_stage[stage].calc;
next_state.cic.int_stage[stage].out = state.cic.int_stage[stage].out;
if (valid_in || state.cic.int_stage[stage].valid_out)
{
unsigned long long mask;
mask = 0xffffffffffffffffULL;
mask <<= CIC_WIDTH;
next_state.cic.int_stage[stage].out = (state.cic.int_stage[stage].calc + value) &~ mask;
next_state.cic.int_stage[stage].calc = state.cic.int_stage[stage].out;
}
next_state.cic.int_stage[stage].valid_out = valid_in;
}
/*f c_adc_frontend::cic_comb_stage_preclock
*/
void c_adc_frontend::cic_comb_stage_preclock( int stage, int valid_in, unsigned long long value )
{
stage--;
next_state.cic.comb_stage[stage].pipe_0 = state.cic.comb_stage[stage].pipe_0;
next_state.cic.comb_stage[stage].pipe_1 = state.cic.comb_stage[stage].pipe_1;
next_state.cic.comb_stage[stage].value = state.cic.comb_stage[stage].value;
if (valid_in || state.cic.comb_stage[stage].valid_out)
{
unsigned long long mask;
mask = 0xffffffffffffffffULL;
mask <<= CIC_WIDTH;
next_state.cic.comb_stage[stage].pipe_0 = value;
next_state.cic.comb_stage[stage].pipe_1 = state.cic.comb_stage[stage].pipe_0;
next_state.cic.comb_stage[stage].value = (value - state.cic.comb_stage[stage].pipe_1) &~ mask;
}
next_state.cic.comb_stage[stage].valid_out = valid_in;
}
/*f c_adc_frontend::preclock_posedge_int_clock
*/
t_sl_error_level c_adc_frontend::preclock_posedge_int_clock( void )
{
int phase_value_taken;
/*b Copy current to next
*/
memcpy( &next_state, &state, sizeof(state));
/*b Mixer - generates phase_value_taken
*/
if (1)
{
phase_value_taken = 0;
switch (state.mixer.fsm)
{
case mixer_fsm_idle:
if (state.sync.iq_valid && state.phase_acc.data_out_stage.valid_cosine)
{
phase_value_taken = 1;
next_state.mixer.fsm = mixer_fsm_cosine_done;
}
break;
case mixer_fsm_cosine_done:
next_state.mixer.fsm = mixer_fsm_sine_done;
break;
case mixer_fsm_sine_done:
next_state.mixer.fsm = mixer_fsm_idle;
break;
}
next_state.mixer.mult_a = mult_u16_x_u15_sign_s18( state.sync.i_out, state.phase_acc.data_out_stage.value, state.phase_acc.data_out_stage.sign );
next_state.mixer.mult_b = mult_u16_x_u15_sign_s18( state.sync.q_out, state.phase_acc.data_out_stage.value, state.phase_acc.data_out_stage.sign );
next_state.mixer.valid_out = 0;
switch (state.mixer.fsm)
{
case mixer_fsm_cosine_done:
next_state.mixer.i_out = state.mixer.mult_a;
next_state.mixer.q_out = state.mixer.mult_b;
break;
case mixer_fsm_sine_done:
next_state.mixer.i_out = (state.mixer.i_out - state.mixer.mult_b) &0x3ffff;
next_state.mixer.q_out = (state.mixer.q_out + state.mixer.mult_a) &0x3ffff;
next_state.mixer.valid_out = 1;
//next_state.mixer.i_out = next_state.mixer.i_out^0x20000;
//next_state.mixer.q_out = next_state.mixer.q_out^0x20000;
break;
default: break;
}
}
/*b Phase accumulator - needs phase_value_taken
*/
if (1)
{
int clock_phase;
int read_rom;
int read_cosine;
int read_quad;
int read_phase;
int rom_address;
int fine_phase;
clock_phase = 0;
read_rom = 0;
read_cosine = 0;
switch (state.phase_acc.fsm)
{
case phase_acc_fsm_idle:
if ( phase_value_taken ||
(!state.phase_acc.data_out_stage.valid_cosine) )
{
read_rom = 1;
read_cosine = 1;
clock_phase = 0;
next_state.phase_acc.fsm = phase_acc_fsm_reading_cosine;
}
break;
case phase_acc_fsm_reading_cosine:
read_rom = 1;
read_cosine = 0;
clock_phase = 0;
next_state.phase_acc.fsm = phase_acc_fsm_reading_sine;
break;
case phase_acc_fsm_reading_sine:
read_rom = 0;
read_cosine = 0;
clock_phase = 1;
next_state.phase_acc.fsm = phase_acc_fsm_idle;
break;
}
if (clock_phase)
{
next_state.phase_acc.phase = (state.phase_acc.phase + state.phase_acc.phase_step) &~ (-1<<phase_resolution);
}
if (read_cosine)
{
read_quad = ((state.phase_acc.phase >> (phase_resolution-2))+1)&3;
}
else
{
read_quad = state.phase_acc.phase >> (phase_resolution-2);
}
read_phase = state.phase_acc.phase >> (phase_resolution-(coarse_resolution+fine_resolution+2));
if (read_quad&1)
{
read_phase = ~read_phase;
}
read_phase = read_phase &~ (-1<<(coarse_resolution+fine_resolution));
rom_address = read_phase >> fine_resolution;
fine_phase = read_phase &~ (-1<<fine_resolution);
{
next_state.phase_acc.rom_stage.rom_reading_cosine = read_cosine;
next_state.phase_acc.rom_stage.negate = ((read_quad&2)!=0);
next_state.phase_acc.rom_stage.fine_phase = fine_phase;
if (read_rom)
{
next_state.phase_acc.rom_stage.rom_base_value = rom[rom_address].base_value;
next_state.phase_acc.rom_stage.rom_delta = rom[rom_address].delta;
next_state.phase_acc.rom_stage.rom_error_bits = rom[rom_address].error_bits;
}
else
{
next_state.phase_acc.rom_stage.rom_base_value = 0xdead;
next_state.phase_acc.rom_stage.rom_delta = 0xdead;
next_state.phase_acc.rom_stage.rom_error_bits = 0xdead;
}
}
{
if (!state.phase_acc.data_out_stage.valid_cosine)
{
next_state.phase_acc.calc_in_stage.negate = state.phase_acc.rom_stage.negate;
next_state.phase_acc.calc_in_stage.fine_phase = state.phase_acc.rom_stage.fine_phase;
next_state.phase_acc.calc_in_stage.valid_cosine = state.phase_acc.rom_stage.rom_reading_cosine;
next_state.phase_acc.calc_in_stage.base_value = state.phase_acc.rom_stage.rom_base_value;
next_state.phase_acc.calc_in_stage.delta = state.phase_acc.rom_stage.rom_delta;
next_state.phase_acc.calc_in_stage.error_bit = (state.phase_acc.rom_stage.rom_error_bits>>(15-state.phase_acc.rom_stage.fine_phase))&1;
}
}
{
unsigned int delta_sum, value;
delta_sum = 0;
if (state.phase_acc.calc_in_stage.fine_phase & (1<<(fine_resolution-1)))
delta_sum = state.phase_acc.calc_in_stage.delta<<1;
if (state.phase_acc.calc_in_stage.fine_phase & (1<<(fine_resolution-2)))
delta_sum += state.phase_acc.calc_in_stage.delta<<0;
if (state.phase_acc.calc_in_stage.fine_phase & (1<<(fine_resolution-3)))
delta_sum += state.phase_acc.calc_in_stage.delta>>1;
if (state.phase_acc.calc_in_stage.fine_phase & (1<<(fine_resolution-4)))
delta_sum += state.phase_acc.calc_in_stage.delta>>2;
value = ((state.phase_acc.calc_in_stage.base_value<<1) | state.phase_acc.calc_in_stage.error_bit) + (delta_sum>>1) + (delta_sum&1);
if ( (!state.phase_acc.data_out_stage.valid_cosine) ||
(phase_value_taken) )
{
next_state.phase_acc.data_out_stage.value = value;
next_state.phase_acc.data_out_stage.sign = state.phase_acc.calc_in_stage.negate;
next_state.phase_acc.data_out_stage.valid_cosine = state.phase_acc.calc_in_stage.valid_cosine;
}
}
}
/*b Synchronizer
*/
next_state.sync.sync_reg_i_0 = data_state.selected_i;
next_state.sync.sync_reg_q_0 = data_state.selected_q;
next_state.sync.sync_toggle_0 = data_state.selected_toggle;
next_state.sync.sync_toggle_1 = state.sync.sync_toggle_0;
next_state.sync.sync_last_toggle = state.sync.sync_toggle_1;
next_state.sync.iq_valid = 0;
if (state.sync.sync_last_toggle != state.sync.sync_toggle_1)
{
next_state.sync.i_out = state.sync.sync_reg_i_0;
next_state.sync.q_out = state.sync.sync_reg_q_0;
next_state.sync.iq_valid = 1;
}
/*b CIC filter
*/
if (1)
{
signed long long cic_in;
cic_in = (signed int) state.cic.q_store;
if (state.mixer.valid_out)
{
next_state.cic.q_store = state.mixer.q_out;
cic_in = (signed int) state.mixer.i_out;
}
sign_extend( cic_in, 17 ); // sign extend
cic_int_stage_preclock( 1, state.mixer.valid_out, cic_in );
cic_int_stage_preclock( 2, state.cic.int_stage[0].valid_out, state.cic.int_stage[0].out );
cic_int_stage_preclock( 3, state.cic.int_stage[1].valid_out, state.cic.int_stage[1].out );
cic_int_stage_preclock( 4, state.cic.int_stage[2].valid_out, state.cic.int_stage[2].out );
cic_int_stage_preclock( 5, state.cic.int_stage[3].valid_out, state.cic.int_stage[3].out );
cic_comb_stage_preclock( 5, state.cic.decimate.valid_out, state.cic.int_stage[4].out );
cic_comb_stage_preclock( 4, state.cic.comb_stage[4].valid_out, state.cic.comb_stage[4].value );
cic_comb_stage_preclock( 3, state.cic.comb_stage[3].valid_out, state.cic.comb_stage[3].value );
cic_comb_stage_preclock( 2, state.cic.comb_stage[2].valid_out, state.cic.comb_stage[2].value );
cic_comb_stage_preclock( 1, state.cic.comb_stage[1].valid_out, state.cic.comb_stage[1].value );
next_state.cic.decimate.valid_out = 0;
if (next_state.cic.int_stage[4].valid_out)
{
if (state.cic.decimate.count==0)
{
next_state.cic.decimate.valid_out = 1;
next_state.cic.decimate.count = state.cic.decimate.factor;
}
else
{
next_state.cic.decimate.count = state.cic.decimate.count-1;
}
}
next_state.calc = state.cic.comb_stage[0].valid_out;
next_state.valid = state.calc;
if (next_state.calc || next_state.valid)
{
unsigned long long a;
double x;
a = state.cic.comb_stage[0].value>>(CIC_WIDTH-16);
x = (double)(a&0x7fff)/32768.0;
if (a&0x8000) x=x-1;
if (next_state.calc)
{
next_state.pwr_calc = x*x;
}
else
{
//printf("%lf %lf %lf\n", sqrt(state.pwr_calc), x, sqrt(state.pwr_calc + x*x) );
x = sqrt(state.pwr_calc + x*x);
next_state.result = (unsigned int)(32768*x);
}
}
}
/*b Done
*/
return error_level_okay;
}
/*f c_adc_frontend::clock_posedge_int_clock
*/
t_sl_error_level c_adc_frontend::clock_posedge_int_clock( void )
{
/*b Copy next to current
*/
memcpy( &state, &next_state, sizeof(state));
/*b Done
*/
return error_level_okay;
}
/*a Initialization functions
*/
/*f c_adc_frontend__init
*/
extern void c_adc_frontend__init( void )
{
se_external_module_register( 1, "adc_frontend", adc_frontend_instance_fn );
}
/*a Scripting support code
*/
/*f initadc_frontend
*/
extern "C" void initadc_frontend( void )
{
c_adc_frontend__init( );
scripting_init_module( "adc_frontend" );
}
| [
""
] | [
[
[
1,
886
]
]
] |
d133934a30131b830c1847de7384e3ccb352cdfe | af260b99d9f045ac4202745a3c7a65ac74a5e53c | /trunk/engine/src/persistance/StrInputStream.h | f32e564a59dfe0f8685619c954c0ab93a53fc67a | [] | no_license | BackupTheBerlios/snap-svn | 560813feabcf5d01f25bc960d474f7e218373da0 | a99b5c64384cc229e8628b22f3cf6a63a70ed46f | refs/heads/master | 2021-01-22T09:43:37.862180 | 2008-02-17T15:50:06 | 2008-02-17T15:50:06 | 40,819,397 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,539 | h | #ifndef _SeedSearcher_Persistance_StrInputStream_h
#define _SeedSearcher_Persistance_StrInputStream_h
#include "InputStream.h"
#include <string>
BEGIN_NAMESPACE (Persistance);
class FixedBufferInputStream : public InputStream {
public:
FixedBufferInputStream (const char* inBuffer, int inCapacity) {
setupBuffer( reinterpret_cast <Persistance::IODefs::Ptr> (
const_cast <char*> (inBuffer)), inCapacity);
}
~FixedBufferInputStream () {
}
virtual void nextBuffer() {
mustfail ();
}
virtual bool hasMoreBuffers() const {
return false;
}
virtual void flush () {
}
};
END_NAMESPACE (Persistance);
#endif
//
// File : $RCSfile: $
// $Workfile: StrInputStream.h $
// Version : $Revision: 1 $
// $Author: Aviad $
// $Date: 10/01/05 1:41 $
// Description :
// The Persistence library contains both high & low level IO classes
// and is high-performance, highly reusable framework
//
// Author:
// Aviad Rozenhek (mailto:[email protected]) 2003-2004
//
// written for the SeedSearcher program.
// for details see www.huji.ac.il/~hoan
// and also http://www.cs.huji.ac.il/~nirf/Abstracts/BGF1.html
//
// this file and as well as its library are released for academic research
// only. the LESSER GENERAL PUBLIC LICENSE (LPGL) license
// as well as any other restrictions as posed by the computational biology lab
// and the library authors apply.
//
| [
"aviadr1@1f8b7f26-7806-0410-ba70-a23862d07478"
] | [
[
[
1,
53
]
]
] |
e04c64e9b1509b3396173e7b44c74bebc19173ea | fca81f35295cceafd1525f0c40910bce7d4880af | /Source/ProductionManager.cpp | 4d71796c95374e99f02592bbbc28e3bb97b58e46 | [] | no_license | armontoubman/massexpand | b324da674cd5013ba1076865d33fc16bfac4f01f | 4daec6bd7d5799de1019e341917c1179158daaa4 | refs/heads/master | 2021-01-10T13:55:47.067590 | 2011-11-20T16:20:48 | 2011-11-20T16:20:48 | 50,496,084 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 50,644 | cpp | #pragma once
#include "ProductionManager.h"
#include <BWAPI.h>
#include "HighCommand.h"
#include "ProductList.h"
#include "Util.h"
ProductionManager::ProductionManager(HighCommand* h)
{
this->hc = h;
this->step = 1;
}
ProductList* ProductionManager::getWantList()
{
return &(this->wantList);
}
ProductList* ProductionManager::getBuildList()
{
return &(this->buildList);
}
int ProductionManager::getStep()
{
return this->step;
}
void ProductionManager::update()
{
updateLists();
}
/* update lists */
void ProductionManager::updateLists()
{
BWAPI::Race enemyRace = BWAPI::Broodwar->enemy()->getRace();
if(enemyRace == BWAPI::Races::Protoss)
{
this->updateListsAgainstProtoss();
this->updateListsAgainstProtossReinforcements();
}
else if(enemyRace == BWAPI::Races::Terran)
{
this->updateListsAgainstTerran();
this->updateListsAgainstTerranReinforcements();
}
else if(enemyRace == BWAPI::Races::Zerg)
{
this->updateListsAgainstZerg();
this->updateListsAgainstZergReinforcements();
}
updateListsUpgrades();
updateListsGeneral();
updateListsGenericRule();
}
void ProductionManager::updateListsAgainstProtoss()
{
if(this->step == 1 && this->buildList.isEmpty() && this->wantList.isEmpty())
{
addBuild(BWAPI::UnitTypes::Zerg_Drone, 5);
//addWant(BWAPI::UnitTypes::Zerg_Drone, 9);
addBuild(BWAPI::UnitTypes::Zerg_Spawning_Pool);
addWant(BWAPI::UnitTypes::Zerg_Spawning_Pool);
addBuild(BWAPI::UnitTypes::Zerg_Drone, 2); // *7*
addBuild(BWAPI::UnitTypes::Zerg_Zergling, 3);
addWant(BWAPI::UnitTypes::Zerg_Hatchery);
this->step = 2;
}
if(this->step == 2)
{
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Hatchery)+nrOfOwn(BWAPI::UnitTypes::Zerg_Lair)+nrOfOwn(BWAPI::UnitTypes::Zerg_Hive)<2) && nrOfOwn(BWAPI::UnitTypes::Zerg_Drone)>8)
{
buildExpand();
}
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Hatchery)+nrOfOwn(BWAPI::UnitTypes::Zerg_Lair)+nrOfOwn(BWAPI::UnitTypes::Zerg_Hive)>1) && buildList.count(BWAPI::UnitTypes::Zerg_Lair)==0 && nrOfOwn(BWAPI::UnitTypes::Zerg_Lair)==0) // *** nog geen bezig!
{
addBuild(BWAPI::UnitTypes::Zerg_Lair);
addWant(BWAPI::UnitTypes::Zerg_Spire);
}
/*if( (nrOfEnemy(BWAPI::UnitTypes::Protoss_Photon_Cannon) > 4) && photonCannonNearBase() )
{
buildExpand();
}*/
/*if( (nrOfEnemy(BWAPI::UnitTypes::Protoss_Nexus) == 2) && (nrOfEnemy(BWAPI::UnitTypes::Protoss_Forge) >= 1) && (nrOfEnemy(BWAPI::UnitTypes::Protoss_Zealot) < 9) && (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) > 10) && (nrOfOwn(BWAPI::UnitTypes::Zerg_Hatchery)+nrOfOwn(BWAPI::UnitTypes::Zerg_Lair)+nrOfOwn(BWAPI::UnitTypes::Zerg_Hive)==2) ) // nakijken
{
buildExpand();
logc("dl p 1-2\n");
}*/
if( nrOfEnemy(BWAPI::UnitTypes::Protoss_Stargate) > 0)
{
addWant(BWAPI::UnitTypes::Zerg_Extractor);
addWant(BWAPI::UnitTypes::Zerg_Hydralisk_Den);
this->step = 3;
}
/*if( (nrOfEnemy(BWAPI::UnitTypes::Protoss_Zealot) > 5) || ((nrOfEnemy(BWAPI::UnitTypes::Protoss_Gateway) > 2) && (nrOfEnemy(BWAPI::UnitTypes::Protoss_Cybernetics_Core) == 0)))
{
logc("dl p 1-4\n");
addWant(BWAPI::UnitTypes::Zerg_Extractor);
addWant(BWAPI::UnitTypes::Zerg_Spire);
stap = 3;
}*/
if( (nrOfEnemy(BWAPI::UnitTypes::Protoss_Photon_Cannon) > 3) && (nrOfOwn(BWAPI::UnitTypes::Zerg_Hatchery)+nrOfOwn(BWAPI::UnitTypes::Zerg_Lair)+nrOfOwn(BWAPI::UnitTypes::Zerg_Hive)==2) ) // *7*
{
addWant(BWAPI::UnitTypes::Zerg_Extractor);
addWant(BWAPI::UnitTypes::Zerg_Hydralisk_Den);
addBuild(BWAPI::UnitTypes::Zerg_Hydralisk, 10);
}
if( (nrOfEnemy(BWAPI::UnitTypes::Protoss_Robotics_Facility) > 0) && (nrOfEnemy(BWAPI::UnitTypes::Protoss_Shuttle)>0) && (nrOfOwn(BWAPI::UnitTypes::Zerg_Hatchery)+nrOfOwn(BWAPI::UnitTypes::Zerg_Lair)+nrOfOwn(BWAPI::UnitTypes::Zerg_Hive)==2)) // deze was gecomment
{
addWant(BWAPI::UnitTypes::Zerg_Extractor);
addWant(BWAPI::UnitTypes::Zerg_Spire);
}
/*if( (nrOfEnemy(BWAPI::UnitTypes::Protoss_Cybernetics_Core) > 0) && (nrOfEnemy(BWAPI::UnitTypes::Protoss_Dragoon) > 3)) // *7*fix
{
logc("dl p 1-7\n");
addBuild(BWAPI::UnitTypes::Zerg_Zergling, 20);
if( (((nrOfOwn(BWAPI::UnitTypes::Zerg_Hatchery)+nrOfOwn(BWAPI::UnitTypes::Zerg_Lair)+nrOfOwn(BWAPI::UnitTypes::Zerg_Hive))+wantList.count(BWAPI::UnitTypes::Zerg_Hatchery)+wantList.count(BWAPI::UnitTypes::Zerg_Lair)+wantList.count(BWAPI::UnitTypes::Zerg_Hive)) < 2) && (nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk_Den)==0)) // *7*
{
logc("dl p 1-7-1\n");
addWant(BWAPI::UnitTypes::Zerg_Hatchery,1);
}
else
{
logc("dl p 1-7-2\n");
addWant(BWAPI::UnitTypes::Zerg_Hydralisk_Den);
addWant(BWAPI::UnitTypes::Zerg_Extractor);
}
}
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Hatchery)+nrOfOwn(BWAPI::UnitTypes::Zerg_Lair)+nrOfOwn(BWAPI::UnitTypes::Zerg_Hive)>1))
{
logc("dl p 1-8\n");
addWant(BWAPI::UnitTypes::Zerg_Extractor);
addWant(BWAPI::UnitTypes::Zerg_Spire);
}*/
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Hatchery)+nrOfOwn(BWAPI::UnitTypes::Zerg_Lair)+nrOfOwn(BWAPI::UnitTypes::Zerg_Hive)>2) && nrOfOwn(BWAPI::UnitTypes::Zerg_Spire)+nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk_Den) > 0)
{
this->step = 3;
}
}
if(this->step == 3)
{
if (buildList.count(BWAPI::UnitTypes::Zerg_Hatchery)==0 && nrOfOwn(BWAPI::UnitTypes::Zerg_Drone)>16 && ((nrOfOwn(BWAPI::UnitTypes::Zerg_Hatchery)+nrOfOwn(BWAPI::UnitTypes::Zerg_Lair)+nrOfOwn(BWAPI::UnitTypes::Zerg_Hive))<5) && nrOfOwn(BWAPI::UnitTypes::Zerg_Spire)+nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk_Den) > 0)
{
addBuild(BWAPI::UnitTypes::Zerg_Hatchery);
}
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Hatchery)+nrOfOwn(BWAPI::UnitTypes::Zerg_Lair)+nrOfOwn(BWAPI::UnitTypes::Zerg_Hive))>2)
{
addWant(BWAPI::UnitTypes::Zerg_Hydralisk_Den);
//addWant(BWAPI::TechTypes::Lurker_Aspect); // fixe
//addWant(BWAPI::UpgradeTypes::Pneumatized_Carapace); // fixe
}
/*if( wantListContains(BWAPI::UnitTypes::Zerg_Hydralisk_Den) && !wantListContains(BWAPI::UnitTypes::Zerg_Spire))
{
addWant(BWAPI::UnitTypes::Zerg_Spire);
}
if( wantListContains(BWAPI::UnitTypes::Zerg_Spire) && !wantListContains(BWAPI::UnitTypes::Zerg_Hydralisk_Den))
{
addWant(BWAPI::UnitTypes::Zerg_Hydralisk_Den);
}*/
/*if( (nrOfEnemy(BWAPI::UnitTypes::Protoss_Templar_Archives) > 0) || ((nrOfEnemy(BWAPI::UnitTypes::Protoss_Citadel_of_Adun) > 0) && (nrOfEnemy(BWAPI::UnitTypes::Protoss_Zealot) > 7)) || (nrOfEnemy(BWAPI::UnitTypes::Protoss_Arbiter_Tribunal) > 0))
{
addWant(BWAPI::UnitTypes::Zerg_Spire);
addBuild(BWAPI::UnitTypes::Zerg_Mutalisk, 11);
}
if( nrOfEnemy(BWAPI::UnitTypes::Protoss_Photon_Cannon) > 9 )
{
addWant(BWAPI::UnitTypes::Zerg_Hydralisk_Den);
}*/
if( (nrOfEnemy(BWAPI::UnitTypes::Protoss_Zealot)+nrOfEnemy(BWAPI::UnitTypes::Protoss_Dragoon)) > 13)
{
addWant(BWAPI::TechTypes::Lurker_Aspect);
}
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Hatchery)+nrOfOwn(BWAPI::UnitTypes::Zerg_Lair)+nrOfOwn(BWAPI::UnitTypes::Zerg_Hive)>3) && ((nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk)+nrOfOwn(BWAPI::UnitTypes::Zerg_Mutalisk) > 20) || (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) > 30)) && nrOfExtraDronesRequired() < 3)
{
this->step = 4;
}
}
if(this->step == 4)
{
addWant(BWAPI::UnitTypes::Zerg_Queens_Nest);
addWant(BWAPI::UnitTypes::Zerg_Hive);
addWant(BWAPI::UnitTypes::Zerg_Defiler_Mound);
addWant(BWAPI::UnitTypes::Zerg_Ultralisk_Cavern);
}
}
void ProductionManager::updateListsAgainstProtossReinforcements()
{
if(nrOfEnemy(BWAPI::UnitTypes::Protoss_Zealot) > 6)
{
if( (nrOfEnemy(BWAPI::UnitTypes::Protoss_Shuttle) > 0) || this->hc->eudm->mapIsFlyer(this->hc->eudm->getMap()).size() >4)
{
if( nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk) > 9 || nrOfOwn(BWAPI::UnitTypes::Zerg_Mutalisk)>0)
{
if( nrOfOwn(BWAPI::UnitTypes::Zerg_Defiler_Mound) > 0 )
{
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) < 26) || (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) < (nrOfOwn(BWAPI::UnitTypes::Zerg_Ultralisk) * 7)) && (buildList.count(BWAPI::UnitTypes::Zerg_Zergling)<6) )
{
addBuild(BWAPI::UnitTypes::Zerg_Zergling);
}
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Defiler)+buildList.count(BWAPI::UnitTypes::Zerg_Defiler)) < (1 + ((nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) + nrOfOwn(BWAPI::UnitTypes::Zerg_Ultralisk)) / 17) ) )
{
addBuild(BWAPI::UnitTypes::Zerg_Defiler);
}
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Defiler) > 2) && (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) > 20) && (buildList.count(BWAPI::UnitTypes::Zerg_Ultralisk)<3))
{
addBuild(BWAPI::UnitTypes::Zerg_Ultralisk);
}
}
else
{
if( ((nrOfOwn(BWAPI::UnitTypes::Zerg_Mutalisk)+buildList.count(BWAPI::UnitTypes::Zerg_Mutalisk))< 11) && (nrOfOwn(BWAPI::UnitTypes::Zerg_Spire) > 0) && buildList.count(BWAPI::UnitTypes::Zerg_Mutalisk)<3 )
{
addBuild(BWAPI::UnitTypes::Zerg_Mutalisk);
}
else
{
if (buildList.count(BWAPI::UnitTypes::Zerg_Hydralisk)<3)
{
addBuild(BWAPI::UnitTypes::Zerg_Hydralisk);
}
else
{
if (buildList.count(BWAPI::UnitTypes::Zerg_Zergling)<2)
{
addBuild(BWAPI::UnitTypes::Zerg_Zergling);
}
}
}
}
}
else
{
if ((nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk_Den) > 0) && buildList.count(BWAPI::UnitTypes::Zerg_Hydralisk)<4)
{
addBuild(BWAPI::UnitTypes::Zerg_Hydralisk);
}
}
}
else
{
if(nrOfOwn(BWAPI::UnitTypes::Zerg_Defiler_Mound) > 0)
{
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) < 26) || (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) < (nrOfOwn(BWAPI::UnitTypes::Zerg_Ultralisk) * 7)) && (buildList.count(BWAPI::UnitTypes::Zerg_Zergling)<6) )
{
addBuild(BWAPI::UnitTypes::Zerg_Zergling);
}
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Defiler)+buildList.count(BWAPI::UnitTypes::Zerg_Defiler)) < (1 + ((nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) + nrOfOwn(BWAPI::UnitTypes::Zerg_Ultralisk)) / 17) ) )
{
addBuild(BWAPI::UnitTypes::Zerg_Defiler);
}
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Defiler) > 2) && (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) > 20) && (buildList.count(BWAPI::UnitTypes::Zerg_Ultralisk)<3))
{
addBuild(BWAPI::UnitTypes::Zerg_Ultralisk);
}
}
else
{
if ((nrOfOwn(BWAPI::UnitTypes::Zerg_Spire) > 0) && buildList.count(BWAPI::UnitTypes::Zerg_Mutalisk)<4)
{
addBuild(BWAPI::UnitTypes::Zerg_Mutalisk);
}
else
{
if (buildList.count(BWAPI::UnitTypes::Zerg_Zergling)<2)
{
addBuild(BWAPI::UnitTypes::Zerg_Zergling);
}
}
}
}
}
else if(nrOfEnemyMilitaryUnits() < 6)
{
if(nrOfOwn(BWAPI::UnitTypes::Zerg_Defiler_Mound) > 0)
{
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) < 26) || (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) < (nrOfOwn(BWAPI::UnitTypes::Zerg_Ultralisk) * 7)) && (buildList.count(BWAPI::UnitTypes::Zerg_Zergling)<6) )
{
addBuild(BWAPI::UnitTypes::Zerg_Zergling);
}
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Defiler)+buildList.count(BWAPI::UnitTypes::Zerg_Defiler)) < (1 + ((nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) + nrOfOwn(BWAPI::UnitTypes::Zerg_Ultralisk)) / 17) ) )
{
addBuild(BWAPI::UnitTypes::Zerg_Defiler);
}
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Defiler) > 2) && (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) > 20) && (buildList.count(BWAPI::UnitTypes::Zerg_Ultralisk)<3))
{
addBuild(BWAPI::UnitTypes::Zerg_Ultralisk);
}
}
else
{
if( (buildList.count(BWAPI::UnitTypes::Zerg_Mutalisk)+nrOfOwn(BWAPI::UnitTypes::Zerg_Mutalisk) < 11) && (nrOfOwn(BWAPI::UnitTypes::Zerg_Spire) > 0) && buildList.count(BWAPI::UnitTypes::Zerg_Mutalisk)<3)
{
addBuild(BWAPI::UnitTypes::Zerg_Mutalisk);
}
else
{
if ((nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk_Den) > 0) && buildList.count(BWAPI::UnitTypes::Zerg_Hydralisk)<4)
{
addBuild(BWAPI::UnitTypes::Zerg_Hydralisk);
}
else
{
if (buildList.count(BWAPI::UnitTypes::Zerg_Zergling)<3)
{
addBuild(BWAPI::UnitTypes::Zerg_Zergling);
}
}
}
}
}
if(nrOfEnemy(BWAPI::UnitTypes::Protoss_Dragoon) > 4)
{
if(nrOfOwn(BWAPI::UnitTypes::Zerg_Defiler_Mound) > 0)
{
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) < 26) || (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) < (nrOfOwn(BWAPI::UnitTypes::Zerg_Ultralisk) * 7)) && (buildList.count(BWAPI::UnitTypes::Zerg_Zergling)<6) )
{
addBuild(BWAPI::UnitTypes::Zerg_Zergling);
}
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Defiler)+buildList.count(BWAPI::UnitTypes::Zerg_Defiler)) < (1 + ((nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) + nrOfOwn(BWAPI::UnitTypes::Zerg_Ultralisk)) / 17) ) )
{
addBuild(BWAPI::UnitTypes::Zerg_Defiler);
}
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Defiler) > 2) && (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) > 20) && (buildList.count(BWAPI::UnitTypes::Zerg_Ultralisk)<3))
{
addBuild(BWAPI::UnitTypes::Zerg_Ultralisk);
}
}
else
{
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk_Den) > 0) && buildList.count(BWAPI::UnitTypes::Zerg_Hydralisk)<4)
{
addBuild(BWAPI::UnitTypes::Zerg_Hydralisk);
}
else
{
if (buildList.count(BWAPI::UnitTypes::Zerg_Zergling)<3)
{
addBuild(BWAPI::UnitTypes::Zerg_Zergling);
}
}
}
}
if(nrOfEnemy(BWAPI::UnitTypes::Protoss_Shuttle) > 0)
{
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Spire) > 0) && buildList.count(BWAPI::UnitTypes::Zerg_Mutalisk)<2)
{
addBuild(BWAPI::UnitTypes::Zerg_Mutalisk);
}
else if ((nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk_Den) > 0) && (buildList.count(BWAPI::UnitTypes::Zerg_Hydralisk)<4))
{
addBuild(BWAPI::UnitTypes::Zerg_Hydralisk);
}
}
if( (nrOfEnemy(BWAPI::UnitTypes::Protoss_Observatory) == 0) && (BWAPI::Broodwar->self()->hasResearched(BWAPI::TechTypes::Lurker_Aspect))) // *7*fix
{
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk) > 5) && (buildList.count(BWAPI::UnitTypes::Zerg_Lurker)<3))
{
addBuild(BWAPI::UnitTypes::Zerg_Lurker);
}
else
{
if (buildList.count(BWAPI::UnitTypes::Zerg_Hydralisk)<3 && (nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk_Den) > 0))
{
addBuild(BWAPI::UnitTypes::Zerg_Hydralisk);
}
}
}
if( (BWAPI::Broodwar->self()->hasResearched(BWAPI::TechTypes::Lurker_Aspect)) && (nrOfEnemy(BWAPI::UnitTypes::Protoss_Zealot) > 7) && (nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk) > 2) && (nrOfOwn(BWAPI::UnitTypes::Zerg_Lurker) < 8) && (buildList.count(BWAPI::UnitTypes::Zerg_Lurker)<2)) // *7*fix
{
addBuild(BWAPI::UnitTypes::Zerg_Lurker);
}
if( ((BWAPI::Broodwar->self()->minerals()>200 || BWAPI::Broodwar->self()->gas()>200) && (nrOfOwn(BWAPI::UnitTypes::Zerg_Hatchery)+nrOfOwn(BWAPI::UnitTypes::Zerg_Lair)+nrOfOwn(BWAPI::UnitTypes::Zerg_Hive) > nrOfEnemy(BWAPI::UnitTypes::Protoss_Nexus))) || nrOfOwnMilitaryUnits() <7 || (nrOfOwnMilitaryUnits() < nrOfEnemyMilitaryUnits()) )
{
if ( nrOfOwn(BWAPI::UnitTypes::Zerg_Defiler_Mound) > 0)
{
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) < 26) || (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) < (nrOfOwn(BWAPI::UnitTypes::Zerg_Ultralisk) * 7)) && (buildList.count(BWAPI::UnitTypes::Zerg_Zergling)<6) )
{
addBuild(BWAPI::UnitTypes::Zerg_Zergling);
}
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Defiler)+buildList.count(BWAPI::UnitTypes::Zerg_Defiler)) < (1 + ((nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) + nrOfOwn(BWAPI::UnitTypes::Zerg_Ultralisk)) / 17) ) )
{
addBuild(BWAPI::UnitTypes::Zerg_Defiler);
}
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Defiler) > 2) && (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) > 20) && (buildList.count(BWAPI::UnitTypes::Zerg_Ultralisk)<3))
{
addBuild(BWAPI::UnitTypes::Zerg_Ultralisk);
}
}
if ( (nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk_Den) > 0) && (nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk) < 10) && (buildList.count(BWAPI::UnitTypes::Zerg_Hydralisk)<3))
{
addBuild(BWAPI::UnitTypes::Zerg_Hydralisk);
}
else
{
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Spire) > 0 ) && ((nrOfOwn(BWAPI::UnitTypes::Zerg_Mutalisk)+buildList.count(BWAPI::UnitTypes::Zerg_Mutalisk)) < 11) && buildList.count(BWAPI::UnitTypes::Zerg_Mutalisk)<3 )
{
addBuild(BWAPI::UnitTypes::Zerg_Mutalisk);
}
else
{
if (nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk_Den)>0 && nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling)>6 && buildList.count(BWAPI::UnitTypes::Zerg_Hydralisk)<3)
{
addBuild(BWAPI::UnitTypes::Zerg_Hydralisk);
}
else
{
if (nrOfOwn(BWAPI::UnitTypes::Zerg_Spawning_Pool)>0 && buildList.count(BWAPI::UnitTypes::Zerg_Zergling)<1)
{
addBuild(BWAPI::UnitTypes::Zerg_Zergling);
}
}
}
}
}
}
void ProductionManager::updateListsAgainstTerran()
{
if(this->step == 1 && this->buildList.isEmpty() && this->wantList.isEmpty())
{
addBuild(BWAPI::UnitTypes::Zerg_Drone, 5);
addBuild(BWAPI::UnitTypes::Zerg_Spawning_Pool);
addWant(BWAPI::UnitTypes::Zerg_Spawning_Pool);
addBuild(BWAPI::UnitTypes::Zerg_Drone, 2);
addBuild(BWAPI::UnitTypes::Zerg_Zergling, 3);
addWant(BWAPI::UnitTypes::Zerg_Hatchery);
this->step = 2;
}
if(this->step == 2)
{
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Hatchery)+nrOfOwn(BWAPI::UnitTypes::Zerg_Lair)+nrOfOwn(BWAPI::UnitTypes::Zerg_Hive)<2) && !buildList.containsExpand())
{
buildExpand();
}
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Hatchery)+nrOfOwn(BWAPI::UnitTypes::Zerg_Lair)+nrOfOwn(BWAPI::UnitTypes::Zerg_Hive)>1) && buildList.count(BWAPI::UnitTypes::Zerg_Lair)==0 && nrOfOwn(BWAPI::UnitTypes::Zerg_Lair)==0 && nrOfOwnMorphing(BWAPI::UnitTypes::Zerg_Lair) == 0)
{
addBuild(BWAPI::UnitTypes::Zerg_Lair);
addWant(BWAPI::UnitTypes::Zerg_Spire);
}
/*if(nrOfEnemy(BWAPI::UnitTypes::Terran_Barracks) > 1)
{
addWant(BWAPI::UnitTypes::Zerg_Extractor);
addWant(BWAPI::UnitTypes::Zerg_Spire);
}*/
if(nrOfEnemy(BWAPI::UnitTypes::Terran_Vulture) > 0 && nrOfOwn(BWAPI::UnitTypes::Zerg_Spire)==0)
{
addWant(BWAPI::UnitTypes::Zerg_Extractor);
addWant(BWAPI::UnitTypes::Zerg_Hydralisk_Den);
}
if(nrOfEnemy(BWAPI::UnitTypes::Terran_Starport) > 0)
{
addWant(BWAPI::UnitTypes::Zerg_Extractor);
addWant(BWAPI::UnitTypes::Zerg_Hydralisk_Den);
}
if(wantListContains(BWAPI::UnitTypes::Zerg_Hydralisk_Den) && !wantListContains(BWAPI::UnitTypes::Zerg_Spire))
{
if(nrOfEnemy(BWAPI::UnitTypes::Terran_Command_Center) > 1)
{
addWant(BWAPI::UnitTypes::Zerg_Extractor);
addWant(BWAPI::UnitTypes::Zerg_Spire);
}
else
{
if ((nrOfOwn(BWAPI::UnitTypes::Zerg_Hatchery)+nrOfOwn(BWAPI::UnitTypes::Zerg_Lair)+nrOfOwn(BWAPI::UnitTypes::Zerg_Hive)<3) && !buildList.containsExpand() && buildList.count(BWAPI::UnitTypes::Zerg_Hatchery)==0)
{
buildExpand();
}
}
}
if( wantListIsCompleted() && nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk_Den)+nrOfOwn(BWAPI::UnitTypes::Zerg_Spire)>0)
{
addWant(BWAPI::UnitTypes::Zerg_Extractor);
addWant(BWAPI::UnitTypes::Zerg_Hydralisk_Den);
this->step = 3;
}
}
if(this->step == 3)
{
addWant(BWAPI::UnitTypes::Zerg_Lair);
if ((nrOfOwn(BWAPI::UnitTypes::Zerg_Hatchery)+nrOfOwn(BWAPI::UnitTypes::Zerg_Lair)+nrOfOwn(BWAPI::UnitTypes::Zerg_Hive))<3 && !buildList.containsExpand())
{
buildExpand();
}
if(nrOfEnemy(BWAPI::UnitTypes::Terran_Marine) > 8)
{
addWant(BWAPI::UnitTypes::Zerg_Hydralisk_Den);
addWant(BWAPI::TechTypes::Lurker_Aspect);
}
if((nrOfEnemy(BWAPI::UnitTypes::Terran_Goliath) > 4) && ((nrOfEnemy(BWAPI::UnitTypes::Terran_Siege_Tank_Siege_Mode) + nrOfEnemy(BWAPI::UnitTypes::Terran_Siege_Tank_Tank_Mode)) == 0))
{
addWant(BWAPI::UnitTypes::Zerg_Hydralisk_Den);
if(nrOfEnemy(BWAPI::UnitTypes::Terran_Science_Vessel) > 0)
{
addWant(BWAPI::UnitTypes::Zerg_Spire);
}
else
{
addWant(BWAPI::TechTypes::Lurker_Aspect);
}
}
if(nrOfEnemy(BWAPI::UnitTypes::Terran_Siege_Tank_Siege_Mode) + nrOfEnemy(BWAPI::UnitTypes::Terran_Siege_Tank_Tank_Mode) > 4)
{
if(nrOfEnemy(BWAPI::UnitTypes::Terran_Goliath) < 6)
{
addWant(BWAPI::UnitTypes::Zerg_Spire);
}
else
{
addWant(BWAPI::UnitTypes::Zerg_Zergling,30);
addWant(BWAPI::UnitTypes::Zerg_Hydralisk_Den);
}
}
if((nrOfOwn(BWAPI::UnitTypes::Zerg_Hatchery)+nrOfOwn(BWAPI::UnitTypes::Zerg_Lair)+nrOfOwn(BWAPI::UnitTypes::Zerg_Hive)>2) && wantListIsCompleted() && ((nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk)+nrOfOwn(BWAPI::UnitTypes::Zerg_Mutalisk) > 20) || (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) > 30)) )
{
this->step = 4;
}
}
if(this->step == 4)
{
addWant(BWAPI::UnitTypes::Zerg_Queens_Nest);
addWant(BWAPI::UnitTypes::Zerg_Hive);
addWant(BWAPI::UnitTypes::Zerg_Defiler_Mound);
addWant(BWAPI::UnitTypes::Zerg_Ultralisk_Cavern);
}
}
void ProductionManager::updateListsAgainstTerranReinforcements()
{
if( nrOfEnemy(BWAPI::UnitTypes::Terran_Marine) > 8)
{
if( nrOfEnemy(BWAPI::UnitTypes::Terran_Science_Vessel) > 0)
{
if( nrOfOwn(BWAPI::UnitTypes::Zerg_Defiler_Mound) > 0 && ((nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk)>7) || (nrOfOwn(BWAPI::UnitTypes::Zerg_Mutalisk)>4) || (nrOfOwn(BWAPI::UnitTypes::Zerg_Scourge)>3)))
{
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) < 26) || (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) < (nrOfOwn(BWAPI::UnitTypes::Zerg_Ultralisk) * 7)) && (buildList.count(BWAPI::UnitTypes::Zerg_Zergling)<6) )
{
addBuild(BWAPI::UnitTypes::Zerg_Zergling);
}
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Defiler)+buildList.count(BWAPI::UnitTypes::Zerg_Defiler)) < (1 + ((nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) + nrOfOwn(BWAPI::UnitTypes::Zerg_Ultralisk)) / 17) ) )
{
addBuild(BWAPI::UnitTypes::Zerg_Defiler);
}
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Defiler) > 2) && (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) > 20) && (buildList.count(BWAPI::UnitTypes::Zerg_Ultralisk)<3))
{
addBuild(BWAPI::UnitTypes::Zerg_Ultralisk);
}
}
else
{
if(nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk_Den) > 0)
{
if( nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk) < 5 && buildList.count(BWAPI::UnitTypes::Zerg_Hydralisk)<4)
{
addBuild(BWAPI::UnitTypes::Zerg_Hydralisk);
}
if(BWAPI::Broodwar->self()->hasResearched(BWAPI::TechTypes::Lurker_Aspect) && buildList.count(BWAPI::UnitTypes::Zerg_Lurker)<3)
{
addBuild(BWAPI::UnitTypes::Zerg_Lurker);
}
else
{
if (buildList.count(BWAPI::UnitTypes::Zerg_Hydralisk)<3)
{
addBuild(BWAPI::UnitTypes::Zerg_Hydralisk);
}
}
}
else if ( nrOfOwn(BWAPI::UnitTypes::Zerg_Spire) > 0 && buildList.count(BWAPI::UnitTypes::Zerg_Mutalisk)<2)
{
addBuild(BWAPI::UnitTypes::Zerg_Mutalisk);
}
}
}
else
{
if(BWAPI::Broodwar->self()->hasResearched(BWAPI::TechTypes::Lurker_Aspect))
{
if( this->hc->eudm->mapIsFlyer(this->hc->eudm->getMap()).size() > 3)
{
if(nrOfOwn(BWAPI::UnitTypes::Zerg_Spire) == 0)
{
if (nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk_Den)>0 && buildList.count(BWAPI::UnitTypes::Zerg_Hydralisk)<3)
{
addBuild(BWAPI::UnitTypes::Zerg_Hydralisk);
}
}
else
{
if (buildList.count(BWAPI::UnitTypes::Zerg_Mutalisk)<3)
{
addBuild(BWAPI::UnitTypes::Zerg_Mutalisk);
}
}
}
else
{
if (buildList.count(BWAPI::UnitTypes::Zerg_Lurker)<3)
{
addBuild(BWAPI::UnitTypes::Zerg_Lurker);
}
}
}
else
{
if (buildList.count(BWAPI::UnitTypes::Zerg_Mutalisk)<2 && nrOfOwn(BWAPI::UnitTypes::Zerg_Spire)>0 )
{
addBuild(BWAPI::UnitTypes::Zerg_Mutalisk);
}
else
{
if (buildList.count(BWAPI::UnitTypes::Zerg_Zergling)<1 && nrOfOwn(BWAPI::UnitTypes::Zerg_Spawning_Pool)>0)
{
addBuild(BWAPI::UnitTypes::Zerg_Zergling);
}
}
}
}
}
else
{
if( (nrOfEnemy(BWAPI::UnitTypes::Terran_Goliath) < 4) && (nrOfEnemy(BWAPI::UnitTypes::Terran_Missile_Turret) < 6) && (nrOfOwn(BWAPI::UnitTypes::Zerg_Spire) > 0) && (buildList.count(BWAPI::UnitTypes::Zerg_Mutalisk)<3))
{
addBuild(BWAPI::UnitTypes::Zerg_Mutalisk);
}
else
{
if( nrOfOwn(BWAPI::UnitTypes::Zerg_Defiler_Mound) > 0)
{
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) < 26) || (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) < (nrOfOwn(BWAPI::UnitTypes::Zerg_Ultralisk) * 7)) && (buildList.count(BWAPI::UnitTypes::Zerg_Zergling)<6) )
{
addBuild(BWAPI::UnitTypes::Zerg_Zergling);
}
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Defiler)+buildList.count(BWAPI::UnitTypes::Zerg_Defiler)) < (1 + ((nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) + nrOfOwn(BWAPI::UnitTypes::Zerg_Ultralisk)) / 17) ) )
{
addBuild(BWAPI::UnitTypes::Zerg_Defiler);
}
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Defiler) > 2) && (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) > 20) && (buildList.count(BWAPI::UnitTypes::Zerg_Ultralisk)<3))
{
addBuild(BWAPI::UnitTypes::Zerg_Ultralisk);
}
}
else
{
if( (nrOfEnemy(BWAPI::UnitTypes::Terran_Science_Vessel) < 3) && BWAPI::Broodwar->self()->hasResearched(BWAPI::TechTypes::Lurker_Aspect) && (nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk) > 2) && (nrOfEnemy(BWAPI::UnitTypes::Terran_Vulture) < 5) && (buildList.count(BWAPI::UnitTypes::Zerg_Lurker)<3))
{
addBuild(BWAPI::UnitTypes::Zerg_Lurker);
}
else
{
if (nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk_Den)>0 && buildList.count(BWAPI::UnitTypes::Zerg_Hydralisk)<3)
{
addBuild(BWAPI::UnitTypes::Zerg_Hydralisk);
}
}
}
}
}
if( ((BWAPI::Broodwar->self()->minerals()>200 || BWAPI::Broodwar->self()->gas()>200) && (nrOfOwn(BWAPI::UnitTypes::Zerg_Hatchery)+nrOfOwn(BWAPI::UnitTypes::Zerg_Lair)+nrOfOwn(BWAPI::UnitTypes::Zerg_Hive) > nrOfEnemy(BWAPI::UnitTypes::Protoss_Nexus))) || nrOfOwnMilitaryUnits() <7 || (nrOfOwnMilitaryUnits() < nrOfEnemyMilitaryUnits()) )
{
if ( nrOfOwn(BWAPI::UnitTypes::Zerg_Defiler_Mound) > 0)
{
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) < 26) || (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) < (nrOfOwn(BWAPI::UnitTypes::Zerg_Ultralisk) * 7)) && (buildList.count(BWAPI::UnitTypes::Zerg_Zergling)<6) )
{
addBuild(BWAPI::UnitTypes::Zerg_Zergling);
}
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Defiler)+buildList.count(BWAPI::UnitTypes::Zerg_Defiler)) < (1 + ((nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) + nrOfOwn(BWAPI::UnitTypes::Zerg_Ultralisk)) / 17) ) )
{
addBuild(BWAPI::UnitTypes::Zerg_Defiler);
}
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Defiler) > 2) && (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) > 20) && (buildList.count(BWAPI::UnitTypes::Zerg_Ultralisk)<3))
{
addBuild(BWAPI::UnitTypes::Zerg_Ultralisk);
}
}
if ( (nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk_Den) > 0) && (nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk) < 10) && (buildList.count(BWAPI::UnitTypes::Zerg_Hydralisk)<3))
{
addBuild(BWAPI::UnitTypes::Zerg_Hydralisk);
}
else
{
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Spire) > 0 ) && ((nrOfOwn(BWAPI::UnitTypes::Zerg_Mutalisk)+buildList.count(BWAPI::UnitTypes::Zerg_Mutalisk)) < 11) && buildList.count(BWAPI::UnitTypes::Zerg_Mutalisk)<3 )
{
addBuild(BWAPI::UnitTypes::Zerg_Mutalisk);
}
else
{
if (nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk_Den)>0 && nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling)>6 && buildList.count(BWAPI::UnitTypes::Zerg_Hydralisk)<3)
{
addBuild(BWAPI::UnitTypes::Zerg_Hydralisk);
}
else
{
if (nrOfOwn(BWAPI::UnitTypes::Zerg_Spawning_Pool)>0 && buildList.count(BWAPI::UnitTypes::Zerg_Zergling)<1)
{
addBuild(BWAPI::UnitTypes::Zerg_Zergling);
}
}
}
}
}
}
void ProductionManager::updateListsAgainstZerg()
{
if(this->step == 1 && this->buildList.isEmpty() && this->wantList.isEmpty())
{
addBuild(BWAPI::UnitTypes::Zerg_Drone, 5);
//addWant(BWAPI::UnitTypes::Zerg_Drone, 9);
addBuild(BWAPI::UnitTypes::Zerg_Spawning_Pool);
addWant(BWAPI::UnitTypes::Zerg_Spawning_Pool);
addBuild(BWAPI::UnitTypes::Zerg_Drone, 2);
addBuild(BWAPI::UnitTypes::Zerg_Zergling, 3);
addWant(BWAPI::UnitTypes::Zerg_Lair);
addWant(BWAPI::UnitTypes::Zerg_Spire);
this->step = 2;
}
if(this->step == 2)
{
/*if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) < 8) && (nrOfEnemy(BWAPI::UnitTypes::Zerg_Zergling) > 7) && (nrOfOwn(BWAPI::UnitTypes::Zerg_Sunken_Colony) < 2))
{
addBuild(BWAPI::UnitTypes::Zerg_Sunken_Colony);
}*/
if( (((nrOfEnemy(BWAPI::UnitTypes::Zerg_Hatchery)+nrOfEnemy(BWAPI::UnitTypes::Zerg_Lair)+nrOfEnemy(BWAPI::UnitTypes::Zerg_Hive)) == 0 || (nrOfEnemy(BWAPI::UnitTypes::Zerg_Hatchery)+nrOfEnemy(BWAPI::UnitTypes::Zerg_Lair)+nrOfEnemy(BWAPI::UnitTypes::Zerg_Hive)) == 2) && (nrOfEnemy(BWAPI::UnitTypes::Zerg_Mutalisk) == 0)) && buildList.count(BWAPI::UnitTypes::Zerg_Zergling)<2 && nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling)<10 )
{
addBuild(BWAPI::UnitTypes::Zerg_Zergling);
}
//if( (nrOfEnemy(BWAPI::UnitTypes::Zerg_Mutalisk) > 3) && (nrOfOwn(BWAPI::UnitTypes::Zerg_Spire) == 0) )
//{
// addWant(BWAPI::UnitTypes::Zerg_Evolution_Chamber);
// addWant(BWAPI::UnitTypes::Zerg_Spore_Colony);
//}
/*if( nrOfEnemy(BWAPI::UnitTypes::Zerg_Hydralisk_Den) > 0)
{
buildExpand();
}*/
if( (nrOfEnemy(BWAPI::UnitTypes::Zerg_Spire) > 0) || ( ((nrOfEnemy(BWAPI::UnitTypes::Zerg_Hatchery)+nrOfEnemy(BWAPI::UnitTypes::Zerg_Lair)+nrOfEnemy(BWAPI::UnitTypes::Zerg_Hive)) == 1) && (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) > 7) ))
{
addWant(BWAPI::UnitTypes::Zerg_Extractor);
addWant(BWAPI::UnitTypes::Zerg_Spire);
}
if ( ((nrOfEnemy(BWAPI::UnitTypes::Zerg_Hatchery)+nrOfEnemy(BWAPI::UnitTypes::Zerg_Lair)+nrOfEnemy(BWAPI::UnitTypes::Zerg_Hive)) == 2) && (nrOfEnemy(BWAPI::UnitTypes::Zerg_Spire) > 0) && ((nrOfOwn(BWAPI::UnitTypes::Zerg_Hatchery)+nrOfOwn(BWAPI::UnitTypes::Zerg_Lair)+nrOfOwn(BWAPI::UnitTypes::Zerg_Hive)) < 3) )
{
if ((nrOfOwn(BWAPI::UnitTypes::Zerg_Spire) > 0) && (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) > 7) && !buildList.containsExpand())
{
buildExpand();
}
else
{
addWant(BWAPI::UnitTypes::Zerg_Extractor);
addWant(BWAPI::UnitTypes::Zerg_Spire);
}
}
if ((nrOfOwn(BWAPI::UnitTypes::Zerg_Hatchery)+nrOfOwn(BWAPI::UnitTypes::Zerg_Lair)+nrOfOwn(BWAPI::UnitTypes::Zerg_Hive)) > 2)
{
this->step = 3;
}
}
if(this->step == 3)
{
addWant(BWAPI::UnitTypes::Zerg_Hydralisk_Den);
if(!buildList.containsExpand())
{
buildExpand();
}
}
}
void ProductionManager::updateListsAgainstZergReinforcements()
{
bool atleastonecompletedspire = false;
if(allEigenUnits()(Spire)(isCompleted).size() > 0)
{
atleastonecompletedspire = true;
}
if( nrOfOwn(BWAPI::UnitTypes::Zerg_Spire) > 0 && atleastonecompletedspire)
{
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Mutalisk)<5) && ((nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) < 6) || (nrOfOwn(BWAPI::UnitTypes::Zerg_Sunken_Colony) <1)) && (BWAPI::Broodwar->self()->gas() < 70) && buildList.count(BWAPI::UnitTypes::Zerg_Zergling)<3)
{
addBuild(BWAPI::UnitTypes::Zerg_Zergling);
}
else
{
if(nrOfOwn(BWAPI::UnitTypes::Zerg_Mutalisk) >= 11 && nrOfEnemy(BWAPI::UnitTypes::Zerg_Hydralisk) > 7 && buildList.count(BWAPI::UnitTypes::Zerg_Zergling)<3)
{
addBuild(BWAPI::UnitTypes::Zerg_Zergling, 3 - buildList.count(BWAPI::UnitTypes::Zerg_Zergling));
}
else
{
if (buildList.count(BWAPI::UnitTypes::Zerg_Mutalisk)<3)
{
addBuild(BWAPI::UnitTypes::Zerg_Mutalisk);
}
}
}
}
else
{
bool spireExists = false;
BWAPI::Unit* lolspire = NULL;
if(allEigenUnits()(Spire).size() > 0)
{
spireExists = true;
lolspire = *allEigenUnits()(Spire).begin();
}
if (spireExists && lolspire->isBeingConstructed())
{
if(lolspire->getRemainingBuildTime() <= 0.5 * lolspire->getType().buildTime())
{
// dont do anything (eggs sparen), mogelijk werkt het niet eens, lol.. alle moeite voor nix :D
}
else
{
if ( ( (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) >10) || ((nrOfOwn(BWAPI::UnitTypes::Zerg_Sunken_Colony) > 0) && (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) >4))))
{
addBuild(BWAPI::UnitTypes::Zerg_Drone);
}
else
{
if (buildList.count(BWAPI::UnitTypes::Zerg_Zergling)<1)
{
addBuild(BWAPI::UnitTypes::Zerg_Zergling);
}
}
}
}
else
{
if( nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk_Den) > 0)
{
if (nrOfOwn(BWAPI::UnitTypes::Zerg_Drone) >= ( 3*nrOfOwn(BWAPI::UnitTypes::Zerg_Extractor) + 5*nrOfOwn(BWAPI::UnitTypes::Zerg_Hatchery)) && (buildList.count(BWAPI::UnitTypes::Zerg_Hydralisk)<3))
{
addBuild(BWAPI::UnitTypes::Zerg_Hydralisk);
}
}
else
{
if ((nrOfOwn(BWAPI::UnitTypes::Zerg_Drone) >= ( 2*nrOfOwn(BWAPI::UnitTypes::Zerg_Extractor) + 4*(nrOfOwn(BWAPI::UnitTypes::Zerg_Hatchery)+nrOfOwn(BWAPI::UnitTypes::Zerg_Lair)+nrOfOwn(BWAPI::UnitTypes::Zerg_Hive)))) && (buildList.count(BWAPI::UnitTypes::Zerg_Zergling)<2) && nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling)<17)
{
addBuild(BWAPI::UnitTypes::Zerg_Zergling);
}
}
}
}
}
void ProductionManager::updateListsUpgrades()
{
int zerglingtotaal = allEigenUnits()(Zergling).size();
zerglingtotaal += countEggsMorphingInto(BWAPI::UnitTypes::Zerg_Zergling)*2;
if (zerglingtotaal > 10)
{
addWant(BWAPI::UpgradeTypes::Metabolic_Boost);
}
if( ((nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk) + nrOfOwn(BWAPI::UnitTypes::Zerg_Lurker)) * 2) >47 && buildList.count(BWAPI::UpgradeTypes::Zerg_Missile_Attacks)<1 )
{
addWant(BWAPI::UpgradeTypes::Zerg_Missile_Attacks); // research ranged ground dmg
addWant(BWAPI::UnitTypes::Zerg_Evolution_Chamber);
}
if( nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk) > 11 && buildList.count(BWAPI::UpgradeTypes::Muscular_Augments)<1 )
{
addWant(BWAPI::UpgradeTypes::Muscular_Augments); // research hydralisk speed
addWant(BWAPI::UnitTypes::Zerg_Evolution_Chamber);
}
if( nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk) > 19 && buildList.count(BWAPI::UpgradeTypes::Grooved_Spines)<1 )
{
addWant(BWAPI::UpgradeTypes::Grooved_Spines); // research range
addWant(BWAPI::UnitTypes::Zerg_Evolution_Chamber);
}
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling)+nrOfOwn(BWAPI::UnitTypes::Zerg_Ultralisk)) > 39 && buildList.count(BWAPI::UpgradeTypes::Zerg_Melee_Attacks)<1 )
{
addWant(BWAPI::UpgradeTypes::Zerg_Melee_Attacks); // research melee ground damage
addWant(BWAPI::UnitTypes::Zerg_Evolution_Chamber);
}
if( BWAPI::Broodwar->self()->supplyUsed() > 180 && buildList.count(BWAPI::UpgradeTypes::Zerg_Carapace)<1 ) // >90 supply required (dubbel vanwege werking API)
{
addWant(BWAPI::UpgradeTypes::Zerg_Carapace); // upgrade ground armor
addWant(BWAPI::UnitTypes::Zerg_Evolution_Chamber);
}
if( BWAPI::Broodwar->self()->supplyUsed() > 90 && (nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk) > 15 || nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) > 20) && buildList.count(BWAPI::TechTypes::Burrowing)<1 )
{
addWant(BWAPI::TechTypes::Burrowing);
}
if( nrOfOwn(BWAPI::UnitTypes::Zerg_Hive) > 0 )
{
if (buildList.count(BWAPI::UpgradeTypes::Zerg_Melee_Attacks)<1)
{
addWant(BWAPI::UpgradeTypes::Zerg_Melee_Attacks); // upgrade melee ground damage
addWant(BWAPI::UnitTypes::Zerg_Evolution_Chamber);
}
if (buildList.count(BWAPI::UpgradeTypes::Zerg_Carapace)<1)
{
addWant(BWAPI::UpgradeTypes::Zerg_Carapace); // upgrade ground armor
addWant(BWAPI::UnitTypes::Zerg_Evolution_Chamber);
}
if (buildList.count(BWAPI::UpgradeTypes::Adrenal_Glands)<1)
{
addWant(BWAPI::UpgradeTypes::Adrenal_Glands); // upgrade ground armor
addWant(BWAPI::UnitTypes::Zerg_Evolution_Chamber);
}
if( nrOfOwn(BWAPI::UnitTypes::Zerg_Ultralisk_Cavern) > 0 )
{
if (buildList.count(BWAPI::UpgradeTypes::Anabolic_Synthesis)<1)
{
addWant(BWAPI::UpgradeTypes::Anabolic_Synthesis); // research ultralisk speed
}
if (buildList.count(BWAPI::UpgradeTypes::Chitinous_Plating)<1)
{
addWant(BWAPI::UpgradeTypes::Chitinous_Plating); // research ultralisk armor
}
}
if( nrOfOwn(BWAPI::UnitTypes::Zerg_Defiler_Mound) > 0 )
{
if (buildList.count(BWAPI::TechTypes::Consume)<1)
{
addWant(BWAPI::TechTypes::Consume); // research sacrifice geval
}
}
}
}
void ProductionManager::updateListsGeneral()
{
if( (BWAPI::Broodwar->self()->supplyUsed() + buildList.supplyRequiredForTopThree()) >= (BWAPI::Broodwar->self()->supplyTotal()+(buildList.count(BWAPI::UnitTypes::Zerg_Overlord)+countEggsMorphingInto(BWAPI::UnitTypes::Zerg_Overlord)*16)) && buildList.count(BWAPI::UnitTypes::Zerg_Overlord)<2 && (BWAPI::Broodwar->self()->supplyTotal() < 400) ) //next 3 items in buildqueue increases the supply required > supplyprovided
{
addBuildTop(BWAPI::UnitTypes::Zerg_Overlord);
}
if (BWAPI::Broodwar->self()->supplyUsed() > 38 && BWAPI::Broodwar->self()->supplyUsed()+16 < (BWAPI::Broodwar->self()->supplyTotal()+(buildList.count(BWAPI::UnitTypes::Zerg_Overlord)+countEggsMorphingInto(BWAPI::UnitTypes::Zerg_Overlord)*16)) && buildList.count(BWAPI::UnitTypes::Zerg_Overlord)<2 && (BWAPI::Broodwar->self()->supplyTotal() < 400) )
{
addBuild(BWAPI::UnitTypes::Zerg_Overlord);
}
if( nrOfExtraDronesRequired()+2 > (buildList.count(BWAPI::UnitTypes::Zerg_Drone)+countEggsMorphingInto(BWAPI::UnitTypes::Zerg_Drone)) && buildList.count(BWAPI::UnitTypes::Zerg_Drone)<6 ) // not sufficient drones
{
addBuild(BWAPI::UnitTypes::Zerg_Drone, nrOfExtraDronesRequired()+2);
}
UnitGroup hatcheries = getOwnBasesWithMinerals()(isCompleted);
UnitGroup geysers = UnitGroup::getUnitGroup(BWAPI::Broodwar->getGeysers());
UnitGroup extractors = allEigenUnits()(Extractor);
for each(BWAPI::Unit* hatchery in hatcheries)
{
if(geysers.inRadius(dist(10), hatchery->getPosition()).size() > 0 && extractors.inRadius(dist(10), hatchery->getPosition()).size() == 0 && nrOfExtraDronesRequired()<3 && nrOfOwn(BWAPI::UnitTypes::Zerg_Drone)>9 && nrOfOwn(BWAPI::UnitTypes::Zerg_Extractor)+buildList.count(BWAPI::UnitTypes::Zerg_Extractor)+this->hc->ctm->count(BWAPI::UnitTypes::Zerg_Extractor) < hatcheries.size())
{
addBuild(BWAPI::UnitTypes::Zerg_Extractor);
}
}
if( buildList.count(BWAPI::UnitTypes::Zerg_Hatchery)==0 && (BWAPI::Broodwar->enemy()->getRace() == BWAPI::Races::Protoss || BWAPI::Broodwar->enemy()->getRace() == BWAPI::Races::Terran)
&& (nrOfEnemyBases()*2 >= nrOfOwn(BWAPI::UnitTypes::Zerg_Hatchery)+nrOfOwn(BWAPI::UnitTypes::Zerg_Lair)+nrOfOwn(BWAPI::UnitTypes::Zerg_Hive)) && nrOfEnemyBases()>1 && !buildList.containsExpand() && this->hc->ctm->countExpand() == 0 && nrOfExtraDronesRequired()<3)
{
if (nrOfOwn(BWAPI::UnitTypes::Zerg_Drone)>15)
{
addBuild(BWAPI::UnitTypes::Zerg_Hatchery);
}
else
{
buildExpand();
}
}
if( BWAPI::Broodwar->self()->minerals() >= 1500 )
{
buildExpand();
if(buildList.count(BWAPI::UnitTypes::Zerg_Zergling) < 5)
{
addBuild(BWAPI::UnitTypes::Zerg_Zergling);
}
}
if( BWAPI::Broodwar->self()->gas() >= 1000 )
{
if(buildList.count(BWAPI::UnitTypes::Zerg_Mutalisk) < 3)
{
addBuild(BWAPI::UnitTypes::Zerg_Mutalisk);
}
if(buildList.count(BWAPI::UnitTypes::Zerg_Defiler) < 3)
{
addBuild(BWAPI::UnitTypes::Zerg_Defiler);
}
if(buildList.count(BWAPI::UnitTypes::Zerg_Hydralisk) < 3)
{
addBuild(BWAPI::UnitTypes::Zerg_Hydralisk);
}
}
if( nrOfOwn(BWAPI::UnitTypes::Zerg_Larva) == 0 && buildList.countUnits() > 2 && BWAPI::Broodwar->self()->minerals() >= 500 && !buildList.containsExpand() && this->hc->ctm->countExpand() == 0 && nrOfExtraDronesRequired()<3)
{
buildExpand();
}
if( nrOfOwn(BWAPI::UnitTypes::Zerg_Larva) == 0 && buildList.countUnits() > 2 && BWAPI::Broodwar->self()->minerals() >= 550 && !buildList.containsExpand() && buildList.count(BWAPI::UnitTypes::Zerg_Hatchery)==0 && this->hc->ctm->count(BWAPI::UnitTypes::Zerg_Hatchery) == 0 && this->hc->ctm->countExpand() == 0 && nrOfExtraDronesRequired()<4 )
{
addBuild(BWAPI::UnitTypes::Zerg_Hatchery);
}
if(!buildList.containsExpand() && nrOfOwn(BWAPI::UnitTypes::Zerg_Hatchery)+nrOfOwn(BWAPI::UnitTypes::Zerg_Lair)+nrOfOwn(BWAPI::UnitTypes::Zerg_Hive)<5 && buildList.count(BWAPI::UnitTypes::Zerg_Hatchery)==0 && this->hc->ctm->count(BWAPI::UnitTypes::Zerg_Hatchery) == 0 && BWAPI::Broodwar->self()->minerals() >= 500 && BWAPI::Broodwar->self()->gas()<200 )
{
addBuild(BWAPI::UnitTypes::Zerg_Hatchery);
}
if(wantList.count(BWAPI::UnitTypes::Zerg_Spire) == 1 || wantList.count(BWAPI::TechTypes::Lurker_Aspect) == 1)
{
addWant(BWAPI::UnitTypes::Zerg_Extractor);
addWant(BWAPI::UnitTypes::Zerg_Lair);
}
if((((BWAPI::Broodwar->self()->minerals()>300 || BWAPI::Broodwar->self()->gas()>300) && ((nrOfOwn(BWAPI::UnitTypes::Zerg_Hatchery)+nrOfOwn(BWAPI::UnitTypes::Zerg_Lair)+nrOfOwn(BWAPI::UnitTypes::Zerg_Hive)) == 2)) || (nrOfOwnMilitaryUnits() <7) || ((nrOfOwn(BWAPI::UnitTypes::Zerg_Hatchery)+nrOfOwn(BWAPI::UnitTypes::Zerg_Lair)+nrOfOwn(BWAPI::UnitTypes::Zerg_Hive)) > 2) || (nrOfOwnMilitaryUnits() < nrOfEnemyMilitaryUnits())))
{
if ( nrOfOwn(BWAPI::UnitTypes::Zerg_Defiler_Mound) > 0)
{
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) < 26) || (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) < (nrOfOwn(BWAPI::UnitTypes::Zerg_Ultralisk) * 7)) && (buildList.count(BWAPI::UnitTypes::Zerg_Zergling)<6) )
{
addBuild(BWAPI::UnitTypes::Zerg_Zergling);
}
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Defiler)+buildList.count(BWAPI::UnitTypes::Zerg_Defiler)) < (1 + ((nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) + nrOfOwn(BWAPI::UnitTypes::Zerg_Ultralisk)) / 17) ) )
{
addBuild(BWAPI::UnitTypes::Zerg_Defiler);
}
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Defiler) > 2) && (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) > 20) && (buildList.count(BWAPI::UnitTypes::Zerg_Ultralisk)<3))
{
addBuild(BWAPI::UnitTypes::Zerg_Ultralisk);
}
}
if ( (nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk_Den) > 0) && (nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk) < 10) && (buildList.count(BWAPI::UnitTypes::Zerg_Hydralisk)<3) )
{
addBuild(BWAPI::UnitTypes::Zerg_Hydralisk,3);
}
else
{
if( (nrOfOwn(BWAPI::UnitTypes::Zerg_Spire) > 0 ) && ((nrOfOwn(BWAPI::UnitTypes::Zerg_Mutalisk)+(buildList.count(BWAPI::UnitTypes::Zerg_Mutalisk))) < 11) && buildList.count(BWAPI::UnitTypes::Zerg_Mutalisk)<3)
{
addBuild(BWAPI::UnitTypes::Zerg_Mutalisk,3);
}
else
{
if ( (nrOfOwn(BWAPI::UnitTypes::Zerg_Hydralisk_Den) > 0) && (nrOfOwn(BWAPI::UnitTypes::Zerg_Zergling) > 6) && (buildList.count(BWAPI::UnitTypes::Zerg_Hydralisk)<3) )
{
addBuild(BWAPI::UnitTypes::Zerg_Hydralisk,3);
}
else
{
if (buildList.count(BWAPI::UnitTypes::Zerg_Zergling)<1)
{
addBuild(BWAPI::UnitTypes::Zerg_Zergling,3);
}
}
}
}
}
}
void ProductionManager::updateListsGenericRule()
{
for each(Product product in this->wantList.productList)
{
if(product.type == BuildProduct)
{
int wantAmount = this->wantList.count(product.buildtype);
int buildAmount = this->buildList.count(product.buildtype);
int haveAmount = allEigenUnits()(GetType, product.buildtype).size();
int contractAmount = 0;
if(product.buildtype.isBuilding())
{
contractAmount = this->hc->ctm->count(product.buildtype);
}
if(product.buildtype == BWAPI::UnitTypes::Zerg_Lair)
{
haveAmount = haveAmount + allEigenUnits()(Hive).size();
}
if(wantAmount > (buildAmount + haveAmount + contractAmount))
{
if(product.buildtype == BWAPI::UnitTypes::Zerg_Lair || product.buildtype == BWAPI::UnitTypes::Zerg_Hive)
{
if(allEigenUnits()(Lair, Hive, Hatchery)(isMorphing).size() == 0)
{
addBuild(product.buildtype);
}
}
else
{
addBuild(product.buildtype);
}
}
}
if(product.type == TechProduct)
{
if(this->buildList.count(product.techtype) == 0 && !BWAPI::Broodwar->self()->hasResearched(product.techtype))
{
addBuild(product.techtype);
}
}
if(product.type == UpgradeProduct)
{
if(this->buildList.count(product.upgradetype) == 0 && BWAPI::Broodwar->self()->getUpgradeLevel(product.upgradetype) < product.upgradetype.maxRepeats())
{
addBuild(product.upgradetype);
}
}
if(product.type == ExpandProduct)
{
// doesn't happen
}
}
}
/* end update lists */
/* ProductList interface */
void ProductionManager::addWant(BWAPI::UnitType unittype)
{
if (!this->wantListContains(unittype))
{
addWant(unittype, 1);
}
}
void ProductionManager::addWant(BWAPI::UnitType unittype, int amount)
{
for(int i=0; i<amount; i++)
{
this->wantList.addProduct(Product(unittype, 1));
}
}
void ProductionManager::addWant(BWAPI::TechType techtype)
{
if (this->wantList.count(techtype)<1)
{
this->wantList.addProduct(Product(techtype, 1));
}
}
void ProductionManager::addWant(BWAPI::UpgradeType upgradetype)
{
if (this->wantList.count(upgradetype)<1)
{
this->wantList.addProduct(Product(upgradetype, 1));
}
}
void ProductionManager::addBuild(BWAPI::UnitType unittype)
{
addBuild(unittype, 1);
}
void ProductionManager::addBuild(BWAPI::UnitType unittype, int amount)
{
for(int i=0; i<amount; i++)
{
this->buildList.addProduct(Product(unittype, 1));
}
}
void ProductionManager::addBuildTop(BWAPI::UnitType unittype)
{
this->buildList.addProductTop(Product(unittype, 1));
}
void ProductionManager::addBuild(BWAPI::TechType techtype)
{
if (this->buildList.count(techtype)<1)
{
this->buildList.addProduct(Product(techtype, 1));
}
}
void ProductionManager::addBuild(BWAPI::UpgradeType upgradetype)
{
if (this->buildList.count(upgradetype)<1)
{
this->buildList.addProduct(Product(upgradetype, 1));
}
}
bool ProductionManager::wantListContains(BWAPI::UnitType unittype)
{
return this->wantList.count(unittype) > 0;
}
bool ProductionManager::buildListContains(BWAPI::UnitType unittype)
{
return this->buildList.count(unittype) > 0;
}
/* end ProductList interface */
/* intel */
int ProductionManager::nrOfEnemy(BWAPI::UnitType unittype)
{
return this->hc->eudm->count(unittype);
}
int ProductionManager::nrOfOwn(BWAPI::UnitType unittype)
{
return allEigenUnits()(GetType, unittype).size();
}
int ProductionManager::nrOfEnemyBases()
{
if(BWAPI::Broodwar->enemy()->getRace() == BWAPI::Races::Protoss)
{
return nrOfEnemy(BWAPI::UnitTypes::Protoss_Nexus);
}
if(BWAPI::Broodwar->enemy()->getRace() == BWAPI::Races::Terran)
{
return nrOfEnemy(BWAPI::UnitTypes::Terran_Command_Center);
}
if(BWAPI::Broodwar->enemy()->getRace() == BWAPI::Races::Zerg)
{
return nrOfEnemy(BWAPI::UnitTypes::Zerg_Hatchery)+nrOfEnemy(BWAPI::UnitTypes::Zerg_Lair)+nrOfEnemy(BWAPI::UnitTypes::Zerg_Hive);
}
return 0;
}
int ProductionManager::nrOfOwnBasesWithMinerals()
{
int result = 0;
UnitGroup bases = allEigenUnits()(Hatchery, Lair, Hive);
UnitGroup minerals = UnitGroup::getUnitGroup(BWAPI::Broodwar->getMinerals());
for each(BWAPI::Unit* base in bases)
{
UnitGroup mineralsNearBase = minerals.inRadius(dist(10), base->getPosition());
if(mineralsNearBase.size() > 0)
{
result = result+1;
}
}
return result;
}
UnitGroup ProductionManager::getOwnBasesWithMinerals()
{
UnitGroup result;
UnitGroup bases = allEigenUnits()(Hatchery, Lair, Hive);
UnitGroup minerals = UnitGroup::getUnitGroup(BWAPI::Broodwar->getMinerals());
for each(BWAPI::Unit* base in bases)
{
UnitGroup mineralsNearBase = minerals.inRadius(dist(10), base->getPosition());
if(mineralsNearBase.size() > 0)
{
result.insert(base);
}
}
return result;
}
int ProductionManager::nrOfOwnMilitaryUnits()
{
return filterMilitary(allEigenUnits()).size();
}
int ProductionManager::nrOfEnemyMilitaryUnits()
{
return 0;
}
int ProductionManager::countEggsMorphingInto(BWAPI::UnitType unittype)
{
int totaal = 0;
UnitGroup eggs = allEigenUnits()(Egg);
for each(BWAPI::Unit* egg in eggs)
{
if(egg->getBuildType() == unittype)
{
totaal++;
}
}
return totaal;
}
int ProductionManager::nrOfOwnMorphing(BWAPI::UnitType unittype)
{
return allEigenUnits()(GetType, unittype).not(isCompleted).size();
}
/* end intel */
void ProductionManager::buildExpand()
{
if(this->buildList.countExpand() == 0)
{
this->buildList.addProduct(Product().expand());
}
}
int ProductionManager::nrOfExtraDronesRequired()
{
int result = 0;
UnitGroup bases = allEigenUnits()(Hatchery, Lair, Hive);
UnitGroup minerals = UnitGroup::getUnitGroup(BWAPI::Broodwar->getMinerals());
for each(BWAPI::Unit* base in bases)
{
UnitGroup mineralsNearBase = minerals.inRadius(dist(10), base->getPosition());
result = result + mineralsNearBase.size();
}
result = result + allEigenUnits()(Extractor)(isCompleted).size()*3;
result = result - allEigenUnits()(isWorker).not(isMorphing).not(isConstructing).size();
return result;
}
bool ProductionManager::wantListIsCompleted()
{
std::set<BWAPI::UnitType> done;
for each(Product product in this->wantList.productList)
{
if(product.type == BuildProduct)
{
if(done.count(product.buildtype) == 0)
{
int expected = this->wantList.count(product.buildtype);
done.insert(product.buildtype);
if(allEigenUnits()(GetType, product.buildtype).size() < expected)
{
return false;
}
}
}
else if(product.type == TechProduct)
{
if(!BWAPI::Broodwar->self()->hasResearched(product.techtype))
{
return false;
}
}
else if(product.type == UpgradeProduct)
{
if(!BWAPI::Broodwar->self()->getUpgradeLevel(product.upgradetype) == 0)
{
return false;
}
}
}
return true;
} | [
"[email protected]"
] | [
[
[
1,
1379
]
]
] |
c58e389f79e10408b6746f3b9641625cff330102 | b6a6fa4324540b94fb84ee68de3021a66f5efe43 | /Duplo/Modules/Compressor.h | ab76b3cc5759d5b0684a7d9ad60a2d67164071d8 | [] | no_license | southor/duplo-scs | dbb54061704f8a2ec0514ad7d204178bfb5a290e | 403cc209039484b469d602b6752f66b9e7c811de | refs/heads/master | 2021-01-20T10:41:22.702098 | 2010-02-25T16:44:39 | 2010-02-25T16:44:39 | 34,623,992 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,937 | h |
#ifndef _DUPLO_COMPRESSOR_
#define _DUPLO_COMPRESSOR_
#include "Dup_Module.h"
#include "Dup_WaveFile.h"
class Compressor : public Dup::Dup_Module
{
private:
// internal states
dup_val currentMax;
dup_val goalMax;
// constant modifiers
dup_uint32 rate; // length of attack/release
static const dup_val RATE_MOD; // length of attack/release
static const dup_val LOUDNESS_MOD;
static const dup_val BYPASS_LOUDNESS_MOD;
// dynamic modifiers
dup_val threshold;
dup_val ratio;
dup_val attack; // 0.0 - 1.0
dup_val release; // 0.0 - 1.0
dup_val outGain1;
dup_val outGain2;
bool bypass;
// ports
dup_val inputL;
dup_val inputR;
dup_val outputL;
dup_val outputR;
void setPortsZero()
{
inputL = 0.0;
inputR = 0.0;
outputL = 0.0;
outputR = 0.0;
}
void update(dup_val y1, dup_val y2)
{
if (y1 < 0.0) y1 = -y1;
if (y2 < 0.0) y2 = -y2;
//dup_val newMax = gain1 * gain2 * ((y1 > y2) ? y1 : y2);
dup_val newMax = threshold * ((y1 > y2) ? y1 : y2);
dup_val rateValue = static_cast<dup_val>(rate);
if ((goalMax > newMax) && (release > 0.0))
{
dup_val diff = goalMax - newMax;
goalMax -= diff / (release * release * rateValue * RATE_MOD);
}
else
{
goalMax = newMax;
}
if ((currentMax < goalMax) && (attack > 0.0))
{
dup_val diff = goalMax - currentMax;
currentMax += diff / (attack * attack * rateValue * RATE_MOD);
}
else
{
currentMax = goalMax;
}
}
inline dup_val calcCompressOutput(dup_val compress, dup_val y) const
{
dup_val y2 = (y < 0.0) ? -y : y;
//return y / (compress + y2);
return y / (compress + currentMax);
}
public:
//Dup::Dup_ModuleInput *getInput(dup_uint i);
static const dup_uint32 PATHID = 118;
static const dup_uint16 N_INPUTS = 2;
static const dup_uint16 N_OUTPUTS = 2;
/*
* constants for determining at
* which position a certain output
* is placed
*/
static const dup_uint16 Y_INPUT_L = 0;
static const dup_uint16 Y_INPUT_R = 1;
static const dup_uint16 Y_OUTPUT_L = 0;
static const dup_uint16 Y_OUTPUT_R = 1;
//static const dup_val THRESHOLD_MIN;
//static const dup_val THRESHOLD_MOD;
static const dup_val COMPRESS_MOD;
static const dup_val MIN_RATIO;
// @msgParser pass rate in message (samplerate)
Compressor(Dup::ModuleHandler *moduleH, dup_uint32 id, Dup::MessageParser msgParser) :
Dup_Module(moduleH,
id,
N_INPUTS,
N_OUTPUTS)
{
currentMax = 0.0;
goalMax = 0.0;
setPortsZero();
// set input and output
setInputDestination(Y_INPUT_L, &inputL);
setInputDestination(Y_INPUT_R, &inputR);
setOutputSourcePointer(Y_OUTPUT_L, &outputL);
setOutputSourcePointer(Y_OUTPUT_R, &outputR);
// get data
msgParser.getData(&rate, sizeof(rate));
if (rate <= 0) rate = 1;
threshold = 1.0;
ratio = 0.0;
attack = 0.0;
release = 0.0;
outGain1 = 1.0;
outGain2 = 1.0;
bypass = false;
}
void setThreshold(dup_val threshold) { this->threshold = threshold; }
void setRatio(dup_val ratio) { this->ratio = ratio; }
void setAttack(dup_val attack) { this->attack = attack; }
void setRelease(dup_val release) { this->release = release; }
void setBypass(dup_val bypass) { this->bypass = (bypass > 0.5) ? true : false; }
void setOutGain1(dup_val gain) { this->outGain1 = gain; }
void setOutGain2(dup_val gain) { this->outGain2 = gain; }
//void setGain1(dup_val gain1)
//{
// this->gain1 = gain1;
//}
//void setGain2(dup_val gain2)
//{
// this->gain2 = gain2;
//}
virtual void run()
{
update(inputL, inputR);
//dup_val aThreshold = (threshold < THRESHOLD_MIN) ? THRESHOLD_MIN : threshold;
//dup_val aLoudness = LOUDNESS_MOD * loudness;
//dup_val compress = THRESHOLD_MOD * aThreshold * aThreshold * aThreshold;
double valueL, valueR;
if (bypass)
{
valueL = inputL * BYPASS_LOUDNESS_MOD;
valueR = inputR * BYPASS_LOUDNESS_MOD;
}
else
{
dup_val compress1 = COMPRESS_MOD / (ratio + MIN_RATIO);
dup_val compress2 = sqrt(compress1) * compress1;
dup_val compress3 = compress1 * compress1;
dup_val compress4 = compress1 * compress3;
valueL = LOUDNESS_MOD * compress2 * calcCompressOutput(compress4, inputL);
valueR = LOUDNESS_MOD * compress2 * calcCompressOutput(compress4, inputL);
}
outputL = outGain1 * outGain2 * valueL;
outputR = outGain1 * outGain2 * valueR;
}
};
const dup_val Compressor::RATE_MOD = 1.0;
const dup_val Compressor::LOUDNESS_MOD = 6.0;
const dup_val Compressor::BYPASS_LOUDNESS_MOD = 4.0;
const dup_val Compressor::MIN_RATIO = 0.2;
//const dup_val Compressor::RATIO_MIN = 0.0;
//const dup_val Compressor::THRESHOLD_MOD = 16.0;
const dup_val Compressor::COMPRESS_MOD = 0.3;
#endif | [
"t.soderberg8@2b3d9118-3c8b-11de-9b50-8bb2048eb44c"
] | [
[
[
1,
223
]
]
] |
7aabb0fda228992a785c731296d9fa099da07e3f | 1c4a1cd805be8bc6f32b0a616de751ad75509e8d | /jacknero/src/pku_src/1080/3573318_AC_0MS_512K.cc | 47817af225864e4ccffc54170a19aef887307098 | [] | no_license | jacknero/mycode | 30313261d7e059832613f26fa453abf7fcde88a0 | 44783a744bb5a78cee403d50eb6b4a384daccf57 | refs/heads/master | 2016-09-06T18:47:12.947474 | 2010-05-02T10:16:30 | 2010-05-02T10:16:30 | 180,950 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,314 | cc | #include <iostream>
#include <string>
#include <algorithm>
#include <cstdio>
#include <map>
using namespace std;
#define w(a,b) W[mm[a]][mm[b]]
int W[5][5] = {
{ 5, -1, -2, -1, -3 },
{-1, 5, -3, -2, -4 },
{-2, -3, 5, -2, -2 },
{-1, -2, -2, 5, -1 },
{-3, -4, -2, -1, -9999 }};
int main()
{
int T;
int l1,l2, i,j;
string s1,s2;
map<char,int> mm;
int table[110][110];
mm['A']=0; mm['C']=1; mm['G']=2; mm['T']=3; mm['-']=4;
table[0][0]=0;
cin >> T;
while(T--) {
cin >> l1 >> s1 >> l2 >> s2;
s1 = " " + s1; s2 = " " + s2;
for(i=1;i<=l1;i++) table[i][0] = table[i-1][0]+w(s1[i-1],'-');
for(i=1;i<=l2;i++) table[0][i] = table[0][i-1]+w(s2[i-1],'-');
for(i=1;i<=l1;i++) {
for(j=1;j<=l2;j++) {
table[i][j] = max(table[i][j-1]+w(s2[j],'-'),
max(table[i-1][j]+w(s1[i],'-'),
table[i-1][j-1]+w(s1[i],s2[j])));
}
}
cout << table[l1][l2] << endl;
}
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
48
]
]
] |
df0a5626766592cfad4bc07382413dfc42cb1226 | 537a1202fe3c72f286101fa7f9e92ed59c3e731d | /hw/libraries/ENC28J60/etherShield.cpp | 8af7718916cf485f11155127168bb1126d552753 | [] | no_license | ribalda/anymot.es | 9cc1138c56f0273684ebe4a70df6c2d87da3b31c | 79167237188d70a8ce72056e070c3ad55b23b62e | refs/heads/master | 2021-01-18T06:36:33.581002 | 2011-06-26T14:48:08 | 2011-06-26T14:48:08 | 1,955,954 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,461 | cpp | // a wrapper class for EtherShield
extern "C" {
#include "enc28j60.h"
#include "ip_arp_udp_tcp.h"
#include "websrv_help_functions.h"
#include "wiring.h"
}
#include "EtherShield.h"
//constructor
EtherShield::EtherShield(){
}
void EtherShield::ES_enc28j60Init(uint8_t* macaddr){
/*initialize enc28j60*/
enc28j60Init(macaddr);
enc28j60clkout(2); // change clkout from 6.25MHz to 12.5MHz
delay(10);
/* Magjack leds configuration, see enc28j60 datasheet, page 11 */
// LEDA=greed LEDB=yellow
//
// 0x880 is PHLCON LEDB=on, LEDA=on
// enc28j60PhyWrite(PHLCON,0b0000 1000 1000 00 00);
enc28j60PhyWrite(PHLCON,0x880);
delay(500);
//
// 0x990 is PHLCON LEDB=off, LEDA=off
// enc28j60PhyWrite(PHLCON,0b0000 1001 1001 00 00);
enc28j60PhyWrite(PHLCON,0x990);
delay(500);
//
// 0x880 is PHLCON LEDB=on, LEDA=on
// enc28j60PhyWrite(PHLCON,0b0000 1000 1000 00 00);
enc28j60PhyWrite(PHLCON,0x880);
delay(500);
//
// 0x990 is PHLCON LEDB=off, LEDA=off
// enc28j60PhyWrite(PHLCON,0b0000 1001 1001 00 00);
enc28j60PhyWrite(PHLCON,0x990);
delay(500);
//
// 0x476 is PHLCON LEDA=links status, LEDB=receive/transmit
// enc28j60PhyWrite(PHLCON,0b0000 0100 0111 01 10);
enc28j60PhyWrite(PHLCON,0x476);
delay(100);
}
void EtherShield::ES_enc28j60clkout(uint8_t clk){
enc28j60clkout(clk);
}
uint8_t EtherShield::ES_enc28j60linkup(void) {
return enc28j60linkup();
}
void EtherShield::ES_enc28j60PhyWrite(uint8_t address, uint16_t data){
enc28j60PhyWrite(address, data);
}
uint16_t EtherShield::ES_enc28j60PacketReceive(uint16_t len, uint8_t* packet){
return enc28j60PacketReceive(len, packet);
}
void EtherShield::ES_init_ip_arp_udp_tcp(uint8_t *mymac,uint8_t *myip,uint16_t wwwp){
init_ip_arp_udp_tcp(mymac,myip,wwwp);
}
uint8_t EtherShield::ES_eth_type_is_arp_and_my_ip(uint8_t *buf,uint16_t len) {
return eth_type_is_arp_and_my_ip(buf,len);
}
void EtherShield::ES_make_echo_reply_from_request(uint8_t *buf,uint16_t len) {
make_echo_reply_from_request(buf,len);
}
void EtherShield::ES_make_tcp_synack_from_syn(uint8_t *buf) {
make_tcp_synack_from_syn(buf);
}
void EtherShield::ES_init_len_info(uint8_t *buf) {
init_len_info(buf);
}
uint16_t EtherShield::ES_get_tcp_data_pointer(void) {
return get_tcp_data_pointer();
}
uint16_t EtherShield::ES_packetloop_icmp_tcp(uint8_t *buf,uint16_t plen) {
return packetloop_icmp_tcp(buf,plen);
}
uint16_t EtherShield::ES_fill_tcp_data_p(uint8_t *buf,uint16_t pos, const prog_char *progmem_s){
return fill_tcp_data_p(buf, pos, progmem_s);
}
uint16_t EtherShield::ES_fill_tcp_data(uint8_t *buf,uint16_t pos, const char *s){
return fill_tcp_data(buf,pos, s);
}
void EtherShield::ES_www_server_reply(uint8_t *buf,uint16_t dlen) {
www_server_reply(buf,dlen);
}
#if defined (WWW_client) || defined (NTP_client)
uint8_t EtherShield::ES_client_store_gw_mac(uint8_t *buf, uint8_t *gwipaddr) {
return client_store_gw_mac(buf, gwipaddr);
}
void EtherShield::ES_client_set_gwip(uint8_t *gwipaddr) {
client_set_gwip(gwipaddr);
}
void EtherShield::ES_client_set_wwwip(uint8_t *wwwipaddr) {
client_set_wwwip(wwwipaddr);
}
void EtherShield::ES_client_arp_whohas(uint8_t *buf,uint8_t *ip_we_search) {
client_arp_whohas(buf, ip_we_search);
}
#endif
#ifdef WWW_client
// ----- http get
void EtherShield::ES_client_browse_url(prog_char *urlbuf, char *urlbuf_varpart, prog_char *hoststr,void (*callback)(uint8_t,uint16_t)) {
client_browse_url(urlbuf, urlbuf_varpart, hoststr,callback);
}
void EtherShield::ES_client_http_post(prog_char *urlbuf, prog_char *hoststr, prog_char *additionalheaderline, prog_char *method, char *postval,void (*callback)(uint8_t,uint16_t)) {
client_http_post(urlbuf, hoststr, additionalheaderline, method, postval,callback);
}
#endif
#ifdef NTP_client
void EtherShield::ES_client_ntp_request(uint8_t *buf,uint8_t *ntpip,uint8_t srcport) {
client_ntp_request(buf,ntpip,srcport);
}
uint8_t EtherShield::ES_client_ntp_process_answer(uint8_t *buf,uint32_t *time,uint8_t dstport_l) {
return client_ntp_process_answer(buf,time,dstport_l);
}
#endif
void EtherShield::ES_register_ping_rec_callback(void (*callback)(uint8_t *srcip)) {
register_ping_rec_callback(callback);
}
#ifdef PING_client
void EtherShield::ES_client_icmp_request(uint8_t *buf,uint8_t *destip) {
client_icmp_request(buf,destip);
}
uint8_t EtherShield::ES_packetloop_icmp_checkreply(uint8_t *buf,uint8_t *ip_monitoredhost) {
return packetloop_icmp_checkreply(buf,ip_monitoredhost);
}
#endif // PING_client
#ifdef WOL_client
void EtherShield::ES_send_wol(uint8_t *buf,uint8_t *wolmac) {
send_wol(buf,wolmac);
}
#endif // WOL_client
#ifdef FROMDECODE_websrv_help
uint8_t EtherShield::ES_find_key_val(char *str,char *strbuf, uint8_t maxlen,char *key) {
return find_key_val(str,strbuf, maxlen,key);
}
void EtherShield::ES_urldecode(char *urlbuf) {
urldecode(urlbuf);
}
#endif
#ifdef URLENCODE_websrv_help
void EtherShield::ES_urlencode(char *str,char *urlbuf) {
urlencode(str,urlbuf);
}
#endif
uint8_t EtherShield::ES_parse_ip(uint8_t *bytestr,char *str) {
return parse_ip(bytestr,str);
}
void EtherShield::ES_mk_net_str(char *resultstr,uint8_t *bytestr,uint8_t len,char separator,uint8_t base) {
mk_net_str(resultstr,bytestr,len,separator,base);
}
| [
"[email protected]"
] | [
[
[
1,
194
]
]
] |
c15c417995c2b12eb0d8c5f0bacacc2bedbf0cf9 | 2c1e5a69ca68fe185cc04c5904aa104b0ba42e32 | /src/common/LzmaDecode.cpp | ec0db139c590f552f7d8f4720747396bba8ab845 | [] | no_license | dogtwelve/newsiderpg | e3f8284a7cd9938156ef8d683dca7bcbd928c593 | 303566a034dca3e66cf0f29cf9eaea1d54d63e4a | refs/heads/master | 2021-01-10T13:03:31.986204 | 2010-06-27T05:36:33 | 2010-06-27T05:36:33 | 46,550,247 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 17,141 | cpp | /*
LzmaDecode.c
LZMA Decoder
LZMA SDK 4.01 Copyright (c) 1999-2004 Igor Pavlov (2004-02-15)
*/
#include "LzmaDecode.h"
#ifndef Byte
#define Byte unsigned char
#endif
#define kNumTopBits 24
#define kTopValue ((UInt32)1 << kNumTopBits)
#define kNumBitModelTotalBits 11
#define kBitModelTotal (1 << kNumBitModelTotalBits)
#define kNumMoveBits 5
typedef struct _CRangeDecoder
{
Byte *Buffer;
Byte *BufferLim;
UInt32 Range;
UInt32 Code;
#ifdef _LZMA_IN_CB
ILzmaInCallback *InCallback;
int Result;
#endif
int ExtraBytes;
} CRangeDecoder;
Byte RangeDecoderReadByte(CRangeDecoder *rd)
{
if (rd->Buffer == rd->BufferLim)
{
#ifdef _LZMA_IN_CB
UInt32 size;
rd->Result = rd->InCallback->Read(rd->InCallback, &rd->Buffer, &size);
rd->BufferLim = rd->Buffer + size;
if (size == 0)
#endif
{
rd->ExtraBytes = 1;
return 0xFF;
}
}
return (*rd->Buffer++);
}
/* #define ReadByte (*rd->Buffer++) */
#define ReadByte (RangeDecoderReadByte(rd))
void RangeDecoderInit(CRangeDecoder *rd,
#ifdef _LZMA_IN_CB
ILzmaInCallback *inCallback
#else
Byte *stream, UInt32 bufferSize
#endif
)
{
int i;
#ifdef _LZMA_IN_CB
rd->InCallback = inCallback;
rd->Buffer = rd->BufferLim = 0;
#else
rd->Buffer = stream;
rd->BufferLim = stream + bufferSize;
#endif
rd->ExtraBytes = 0;
rd->Code = 0;
rd->Range = (0xFFFFFFFF);
for(i = 0; i < 5; i++)
rd->Code = (rd->Code << 8) | ReadByte;
}
#define RC_INIT_VAR UInt32 range = rd->Range; UInt32 code = rd->Code;
#define RC_FLUSH_VAR rd->Range = range; rd->Code = code;
#define RC_NORMALIZE if (range < kTopValue) { range <<= 8; code = (code << 8) | ReadByte; }
UInt32 RangeDecoderDecodeDirectBits(CRangeDecoder *rd, int numTotalBits)
{
RC_INIT_VAR
UInt32 result = 0;
int i;
for (i = numTotalBits; i > 0; i--)
{
/* UInt32 t; */
range >>= 1;
result <<= 1;
if (code >= range)
{
code -= range;
result |= 1;
}
/*
t = (code - range) >> 31;
t &= 1;
code -= range & (t - 1);
result = (result + result) | (1 - t);
*/
RC_NORMALIZE
}
RC_FLUSH_VAR
return result;
}
int RangeDecoderBitDecode(CProb *prob, CRangeDecoder *rd)
{
UInt32 bound = (rd->Range >> kNumBitModelTotalBits) * *prob;
if (rd->Code < bound)
{
rd->Range = bound;
*prob += (kBitModelTotal - *prob) >> kNumMoveBits;
if (rd->Range < kTopValue)
{
rd->Code = (rd->Code << 8) | ReadByte;
rd->Range <<= 8;
}
return 0;
}
else
{
rd->Range -= bound;
rd->Code -= bound;
*prob -= (*prob) >> kNumMoveBits;
if (rd->Range < kTopValue)
{
rd->Code = (rd->Code << 8) | ReadByte;
rd->Range <<= 8;
}
return 1;
}
}
#define RC_GET_BIT2(prob, mi, A0, A1) \
UInt32 bound = (range >> kNumBitModelTotalBits) * *prob; \
if (code < bound) \
{ A0; range = bound; *prob += (kBitModelTotal - *prob) >> kNumMoveBits; mi <<= 1; } \
else \
{ A1; range -= bound; code -= bound; *prob -= (*prob) >> kNumMoveBits; mi = (mi + mi) + 1; } \
RC_NORMALIZE
#define RC_GET_BIT(prob, mi) RC_GET_BIT2(prob, mi, ; , ;)
int RangeDecoderBitTreeDecode(CProb *probs, int numLevels, CRangeDecoder *rd)
{
int mi = 1;
int i;
#ifdef _LZMA_LOC_OPT
RC_INIT_VAR
#endif
for(i = numLevels; i > 0; i--)
{
#ifdef _LZMA_LOC_OPT
CProb *prob = probs + mi;
RC_GET_BIT(prob, mi)
#else
mi = (mi + mi) + RangeDecoderBitDecode(probs + mi, rd);
#endif
}
#ifdef _LZMA_LOC_OPT
RC_FLUSH_VAR
#endif
return mi - (1 << numLevels);
}
int RangeDecoderReverseBitTreeDecode(CProb *probs, int numLevels, CRangeDecoder *rd)
{
int mi = 1;
int i;
int symbol = 0;
#ifdef _LZMA_LOC_OPT
RC_INIT_VAR
#endif
for(i = 0; i < numLevels; i++)
{
#ifdef _LZMA_LOC_OPT
CProb *prob = probs + mi;
RC_GET_BIT2(prob, mi, ; , symbol |= (1 << i))
#else
int bit = RangeDecoderBitDecode(probs + mi, rd);
mi = mi + mi + bit;
symbol |= (bit << i);
#endif
}
#ifdef _LZMA_LOC_OPT
RC_FLUSH_VAR
#endif
return symbol;
}
Byte LzmaLiteralDecode(CProb *probs, CRangeDecoder *rd)
{
int symbol = 1;
#ifdef _LZMA_LOC_OPT
RC_INIT_VAR
#endif
do
{
#ifdef _LZMA_LOC_OPT
CProb *prob = probs + symbol;
RC_GET_BIT(prob, symbol)
#else
symbol = (symbol + symbol) | RangeDecoderBitDecode(probs + symbol, rd);
#endif
}
while (symbol < 0x100);
#ifdef _LZMA_LOC_OPT
RC_FLUSH_VAR
#endif
return symbol;
}
Byte LzmaLiteralDecodeMatch(CProb *probs, CRangeDecoder *rd, Byte matchByte)
{
int symbol = 1;
#ifdef _LZMA_LOC_OPT
RC_INIT_VAR
#endif
do
{
int bit;
int matchBit = (matchByte >> 7) & 1;
matchByte <<= 1;
#ifdef _LZMA_LOC_OPT
{
CProb *prob = probs + ((1 + matchBit) << 8) + symbol;
RC_GET_BIT2(prob, symbol, bit = 0, bit = 1)
}
#else
bit = RangeDecoderBitDecode(probs + ((1 + matchBit) << 8) + symbol, rd);
symbol = (symbol << 1) | bit;
#endif
if (matchBit != bit)
{
while (symbol < 0x100)
{
#ifdef _LZMA_LOC_OPT
CProb *prob = probs + symbol;
RC_GET_BIT(prob, symbol)
#else
symbol = (symbol + symbol) | RangeDecoderBitDecode(probs + symbol, rd);
#endif
}
break;
}
}
while (symbol < 0x100);
#ifdef _LZMA_LOC_OPT
RC_FLUSH_VAR
#endif
return symbol;
}
#define kNumPosBitsMax 4
#define kNumPosStatesMax (1 << kNumPosBitsMax)
#define kLenNumLowBits 3
#define kLenNumLowSymbols (1 << kLenNumLowBits)
#define kLenNumMidBits 3
#define kLenNumMidSymbols (1 << kLenNumMidBits)
#define kLenNumHighBits 8
#define kLenNumHighSymbols (1 << kLenNumHighBits)
#define LenChoice 0
#define LenChoice2 (LenChoice + 1)
#define LenLow (LenChoice2 + 1)
#define LenMid (LenLow + (kNumPosStatesMax << kLenNumLowBits))
#define LenHigh (LenMid + (kNumPosStatesMax << kLenNumMidBits))
#define kNumLenProbs (LenHigh + kLenNumHighSymbols)
int LzmaLenDecode(CProb *p, CRangeDecoder *rd, int posState)
{
if(RangeDecoderBitDecode(p + LenChoice, rd) == 0)
return RangeDecoderBitTreeDecode(p + LenLow +
(posState << kLenNumLowBits), kLenNumLowBits, rd);
if(RangeDecoderBitDecode(p + LenChoice2, rd) == 0)
return kLenNumLowSymbols + RangeDecoderBitTreeDecode(p + LenMid +
(posState << kLenNumMidBits), kLenNumMidBits, rd);
return kLenNumLowSymbols + kLenNumMidSymbols +
RangeDecoderBitTreeDecode(p + LenHigh, kLenNumHighBits, rd);
}
#define kNumStates 12
#define kStartPosModelIndex 4
#define kEndPosModelIndex 14
#define kNumFullDistances (1 << (kEndPosModelIndex >> 1))
#define kNumPosSlotBits 6
#define kNumLenToPosStates 4
#define kNumAlignBits 4
#define kAlignTableSize (1 << kNumAlignBits)
#define kMatchMinLen 2
#define IsMatch 0
#define IsRep (IsMatch + (kNumStates << kNumPosBitsMax))
#define IsRepG0 (IsRep + kNumStates)
#define IsRepG1 (IsRepG0 + kNumStates)
#define IsRepG2 (IsRepG1 + kNumStates)
#define IsRep0Long (IsRepG2 + kNumStates)
#define PosSlot (IsRep0Long + (kNumStates << kNumPosBitsMax))
#define SpecPos (PosSlot + (kNumLenToPosStates << kNumPosSlotBits))
#define Align (SpecPos + kNumFullDistances - kEndPosModelIndex)
#define LenCoder (Align + kAlignTableSize)
#define RepLenCoder (LenCoder + kNumLenProbs)
#define Literal (RepLenCoder + kNumLenProbs)
#if Literal != LZMA_BASE_SIZE
StopCompilingDueBUG
#endif
#ifdef _LZMA_OUT_READ
typedef struct _LzmaVarState
{
CRangeDecoder RangeDecoder;
Byte *Dictionary;
UInt32 DictionarySize;
UInt32 DictionaryPos;
UInt32 GlobalPos;
UInt32 Reps[4];
int lc;
int lp;
int pb;
int State;
int PreviousIsMatch;
int RemainLen;
} LzmaVarState;
int LzmaDecoderInit(
unsigned char *buffer, UInt32 bufferSize,
int lc, int lp, int pb,
unsigned char *dictionary, UInt32 dictionarySize,
#ifdef _LZMA_IN_CB
ILzmaInCallback *inCallback
#else
unsigned char *inStream, UInt32 inSize
#endif
)
{
LzmaVarState *vs = (LzmaVarState *)buffer;
CProb *p = (CProb *)(buffer + sizeof(LzmaVarState));
UInt32 numProbs = Literal + ((UInt32)LZMA_LIT_SIZE << (lc + lp));
UInt32 i;
if (bufferSize < numProbs * sizeof(CProb) + sizeof(LzmaVarState))
return LZMA_RESULT_NOT_ENOUGH_MEM;
vs->Dictionary = dictionary;
vs->DictionarySize = dictionarySize;
vs->DictionaryPos = 0;
vs->GlobalPos = 0;
vs->Reps[0] = vs->Reps[1] = vs->Reps[2] = vs->Reps[3] = 1;
vs->lc = lc;
vs->lp = lp;
vs->pb = pb;
vs->State = 0;
vs->PreviousIsMatch = 0;
vs->RemainLen = 0;
dictionary[dictionarySize - 1] = 0;
for (i = 0; i < numProbs; i++)
p[i] = kBitModelTotal >> 1;
RangeDecoderInit(&vs->RangeDecoder,
#ifdef _LZMA_IN_CB
inCallback
#else
inStream, inSize
#endif
);
return LZMA_RESULT_OK;
}
int LzmaDecode(unsigned char *buffer,
unsigned char *outStream, UInt32 outSize,
UInt32 *outSizeProcessed)
{
LzmaVarState *vs = (LzmaVarState *)buffer;
CProb *p = (CProb *)(buffer + sizeof(LzmaVarState));
CRangeDecoder rd = vs->RangeDecoder;
int state = vs->State;
int previousIsMatch = vs->PreviousIsMatch;
Byte previousByte;
UInt32 rep0 = vs->Reps[0], rep1 = vs->Reps[1], rep2 = vs->Reps[2], rep3 = vs->Reps[3];
UInt32 nowPos = 0;
UInt32 posStateMask = (1 << (vs->pb)) - 1;
UInt32 literalPosMask = (1 << (vs->lp)) - 1;
int lc = vs->lc;
int len = vs->RemainLen;
UInt32 globalPos = vs->GlobalPos;
Byte *dictionary = vs->Dictionary;
UInt32 dictionarySize = vs->DictionarySize;
UInt32 dictionaryPos = vs->DictionaryPos;
if (len == -1)
{
*outSizeProcessed = 0;
return LZMA_RESULT_OK;
}
while(len > 0 && nowPos < outSize)
{
UInt32 pos = dictionaryPos - rep0;
if (pos >= dictionarySize)
pos += dictionarySize;
outStream[nowPos++] = dictionary[dictionaryPos] = dictionary[pos];
if (++dictionaryPos == dictionarySize)
dictionaryPos = 0;
len--;
}
if (dictionaryPos == 0)
previousByte = dictionary[dictionarySize - 1];
else
previousByte = dictionary[dictionaryPos - 1];
#else
int LzmaDecode(
Byte *buffer, UInt32 bufferSize,
int lc, int lp, int pb,
#ifdef _LZMA_IN_CB
ILzmaInCallback *inCallback,
#else
unsigned char *inStream, UInt32 inSize,
#endif
unsigned char *outStream, UInt32 outSize,
UInt32 *outSizeProcessed)
{
UInt32 numProbs = Literal + ((UInt32)LZMA_LIT_SIZE << (lc + lp));
CProb *p = (CProb *)buffer;
CRangeDecoder rd;
UInt32 i;
int state = 0;
int previousIsMatch = 0;
Byte previousByte = 0;
UInt32 rep0 = 1, rep1 = 1, rep2 = 1, rep3 = 1;
UInt32 nowPos = 0;
UInt32 posStateMask = (1 << pb) - 1;
UInt32 literalPosMask = (1 << lp) - 1;
int len = 0;
if (bufferSize < numProbs * sizeof(CProb))
return LZMA_RESULT_NOT_ENOUGH_MEM;
for (i = 0; i < numProbs; i++)
p[i] = kBitModelTotal >> 1;
RangeDecoderInit(&rd,
#ifdef _LZMA_IN_CB
inCallback
#else
inStream, inSize
#endif
);
#endif
*outSizeProcessed = 0;
while(nowPos < outSize)
{
int posState = (int)(
(nowPos
#ifdef _LZMA_OUT_READ
+ globalPos
#endif
)
& posStateMask);
#ifdef _LZMA_IN_CB
if (rd.Result != LZMA_RESULT_OK)
return rd.Result;
#endif
if (rd.ExtraBytes != 0)
return LZMA_RESULT_DATA_ERROR;
if (RangeDecoderBitDecode(p + IsMatch + (state << kNumPosBitsMax) + posState, &rd) == 0)
{
CProb *probs = p + Literal + (LZMA_LIT_SIZE *
(((
(nowPos
#ifdef _LZMA_OUT_READ
+ globalPos
#endif
)
& literalPosMask) << lc) + (previousByte >> (8 - lc))));
if (state < 4) state = 0;
else if (state < 10) state -= 3;
else state -= 6;
if (previousIsMatch)
{
Byte matchByte;
#ifdef _LZMA_OUT_READ
UInt32 pos = dictionaryPos - rep0;
if (pos >= dictionarySize)
pos += dictionarySize;
matchByte = dictionary[pos];
#else
matchByte = outStream[nowPos - rep0];
#endif
previousByte = LzmaLiteralDecodeMatch(probs, &rd, matchByte);
previousIsMatch = 0;
}
else
previousByte = LzmaLiteralDecode(probs, &rd);
outStream[nowPos++] = previousByte;
#ifdef _LZMA_OUT_READ
dictionary[dictionaryPos] = previousByte;
if (++dictionaryPos == dictionarySize)
dictionaryPos = 0;
#endif
}
else
{
previousIsMatch = 1;
if (RangeDecoderBitDecode(p + IsRep + state, &rd) == 1)
{
if (RangeDecoderBitDecode(p + IsRepG0 + state, &rd) == 0)
{
if (RangeDecoderBitDecode(p + IsRep0Long + (state << kNumPosBitsMax) + posState, &rd) == 0)
{
#ifdef _LZMA_OUT_READ
UInt32 pos;
#endif
if (
(nowPos
#ifdef _LZMA_OUT_READ
+ globalPos
#endif
)
== 0)
return LZMA_RESULT_DATA_ERROR;
state = state < 7 ? 9 : 11;
#ifdef _LZMA_OUT_READ
pos = dictionaryPos - rep0;
if (pos >= dictionarySize)
pos += dictionarySize;
previousByte = dictionary[pos];
dictionary[dictionaryPos] = previousByte;
if (++dictionaryPos == dictionarySize)
dictionaryPos = 0;
#else
previousByte = outStream[nowPos - rep0];
#endif
outStream[nowPos++] = previousByte;
continue;
}
}
else
{
UInt32 distance;
if(RangeDecoderBitDecode(p + IsRepG1 + state, &rd) == 0)
distance = rep1;
else
{
if(RangeDecoderBitDecode(p + IsRepG2 + state, &rd) == 0)
distance = rep2;
else
{
distance = rep3;
rep3 = rep2;
}
rep2 = rep1;
}
rep1 = rep0;
rep0 = distance;
}
len = LzmaLenDecode(p + RepLenCoder, &rd, posState);
state = state < 7 ? 8 : 11;
}
else
{
int posSlot;
rep3 = rep2;
rep2 = rep1;
rep1 = rep0;
state = state < 7 ? 7 : 10;
len = LzmaLenDecode(p + LenCoder, &rd, posState);
posSlot = RangeDecoderBitTreeDecode(p + PosSlot +
((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) <<
kNumPosSlotBits), kNumPosSlotBits, &rd);
if (posSlot >= kStartPosModelIndex)
{
int numDirectBits = ((posSlot >> 1) - 1);
rep0 = ((2 | ((UInt32)posSlot & 1)) << numDirectBits);
if (posSlot < kEndPosModelIndex)
{
rep0 += RangeDecoderReverseBitTreeDecode(
p + SpecPos + rep0 - posSlot - 1, numDirectBits, &rd);
}
else
{
rep0 += RangeDecoderDecodeDirectBits(&rd,
numDirectBits - kNumAlignBits) << kNumAlignBits;
rep0 += RangeDecoderReverseBitTreeDecode(p + Align, kNumAlignBits, &rd);
}
}
else
rep0 = posSlot;
rep0++;
}
if (rep0 == (UInt32)(0))
{
/* it's for stream version */
len = -1;
break;
}
if (rep0 > nowPos
#ifdef _LZMA_OUT_READ
+ globalPos
#endif
)
{
return LZMA_RESULT_DATA_ERROR;
}
len += kMatchMinLen;
do
{
#ifdef _LZMA_OUT_READ
UInt32 pos = dictionaryPos - rep0;
if (pos >= dictionarySize)
pos += dictionarySize;
previousByte = dictionary[pos];
dictionary[dictionaryPos] = previousByte;
if (++dictionaryPos == dictionarySize)
dictionaryPos = 0;
#else
previousByte = outStream[nowPos - rep0];
#endif
outStream[nowPos++] = previousByte;
len--;
}
while(len > 0 && nowPos < outSize);
}
}
#ifdef _LZMA_OUT_READ
vs->RangeDecoder = rd;
vs->DictionaryPos = dictionaryPos;
vs->GlobalPos = globalPos + nowPos;
vs->Reps[0] = rep0;
vs->Reps[1] = rep1;
vs->Reps[2] = rep2;
vs->Reps[3] = rep3;
vs->State = state;
vs->PreviousIsMatch = previousIsMatch;
vs->RemainLen = len;
#endif
*outSizeProcessed = nowPos;
return LZMA_RESULT_OK;
}
| [
"[email protected]"
] | [
[
[
1,
648
]
]
] |
36dac821551c69ca833c21a08e3da9e01dee9775 | 208475bcab65438eed5d8380f26eacd25eb58f70 | /QianExe/yx_PhoneBook.cpp | 7c4422c169dd7332956b174c75e0c8d14ee93d5a | [] | no_license | awzhang/MyWork | 83b3f0b9df5ff37330c0e976310d75593f806ec4 | 075ad5d0726c793a0c08f9158080a144e0bb5ea5 | refs/heads/master | 2021-01-18T07:57:03.219372 | 2011-07-05T02:41:55 | 2011-07-05T02:46:30 | 15,523,223 | 1 | 2 | null | null | null | null | GB18030 | C++ | false | false | 2,722 | cpp | #include "yx_QianStdAfx.h"
#if USE_TELLIMIT == 1
//------------------------------------------------------------------------------
// 处理中心协议
void CPhoneBook::hdl_cent(byte datype, char *dat, ulong len)
{
for(ulong i=0; i<len; i++)
{
if(0x7f==*(dat+i))
*(dat+i) = 0;
}
switch(datype)
{
case 0x01:
hdl_3301((byte*)dat, len);
break;
case 0x02:
hdl_3302((byte*)dat, len);
break;
default:
break;
}
}
//------------------------------------------------------------------------------
// 往中心发送TCP数据
void CPhoneBook::tcp_send(byte trantype, byte datatype, void *data, int len)
{
int ln = 0;
byte buf[2048] = {0};
// 将0转化为0x7f
memcpy(buf, data, len);
for(int i=0; i<len; i++)
{
if(0 == buf[i])
buf[i] = 0x7f;
}
ln = len;
int ln2 = 0;
char buf2[2048] = {0};
int iRet = g_objSms.MakeSmsFrame((char*)buf, ln, trantype, datatype, buf2, sizeof(buf2), ln2);
if( !iRet ) g_objSock.SOCKSNDSMSDATA( buf2, ln2, LV9 );
}
void CPhoneBook::hdl_3301(byte *dat, ulong len)
{
frm3301 *p = (frm3301*)dat;
bool succ = true;
for(int i=0; i<p->cnt; i++)
{
byte idx = p->book[i].idx;
if(idx>30 || 0==idx)
{
succ = false;
break;
}
memcpy(&m_cfg.book[idx-1], &p->book[i], sizeof(Book));
}
// 见鬼,千里眼从1开始编号,而king从0开始编号
// { 临时为了黑龙江办连king
// for(int i=0; i<p->cnt; i++) {
// byte idx = p->book[i].idx;
// if( 0x7f == idx ) idx = 0; // 见鬼king怎么改为7f了
// if(idx>=30 ) { succ = false; break; }
// memcpy(&m_cfg.book[idx], &p->book[i], sizeof(Book));
// }
// } 临时为了黑龙江办连king
// 保存配置
if(succ)
{
int ret = SetSecCfg(&m_cfg, offsetof(tagSecondCfg, m_uniBookCfg.m_szReservered), sizeof(m_cfg) );
if(0 != ret)
succ = false;
}
// 往中心发送应答
frm3341 frm;
frm.reply = (succ) ? 0x01 : 0x7f;
frm.frmno = p->frmno;
tcp_send(0x33, 0x41, &frm, sizeof(frm));
PRTMSG(MSG_NOR, "hdl_3301 Set Book(%u)%s!\n", p->frmno, succ ? "succ" : "fail");
}
void CPhoneBook::hdl_3302(byte *dat, ulong len)
{
frm3302 *p = (frm3302*)dat;
if(0==p->cnt)
{
memset(&m_cfg.tel[0][0], 0, sizeof(m_cfg.tel));
}
for(int i=0; i<p->cnt; i++)
{
memcpy(&m_cfg.tel[i][0], &p->tel[i][0], 15);
}
int ret = SetSecCfg(&m_cfg, offsetof(tagSecondCfg, m_uniBookCfg.m_szReservered), sizeof(m_cfg) );
// 往中心发送应答
frm3342 frm;
frm.reply = (0==ret) ? 0x01 : 0x7f;
tcp_send(0x33, 0x42, &frm, sizeof(frm));
PRTMSG(MSG_NOR, "hdl_3302 Set serve tel %s!\n", (0==ret) ? "succ" : "fail");
}
#endif
| [
"[email protected]"
] | [
[
[
1,
124
]
]
] |
1892c70185477782e621e3be3064e19a341235f6 | e31046aee3ad2d4600c7f35aaeeba76ee2b99039 | /trunk/tests/Schakal/Lua Plugin/src/lua_obj.cpp | 46b6f51e69487f0d02c5df70a0fe622b84b5526f | [] | no_license | BackupTheBerlios/trinitas-svn | ddea265cf47aff3e8853bf6d46861e0ed3031ea1 | 7d3ff64a7d0e5ba37febda38e6ce0b2d0a4b6cca | refs/heads/master | 2021-01-23T08:14:44.215249 | 2009-02-18T19:37:51 | 2009-02-18T19:37:51 | 40,749,519 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 700 | cpp |
/*
* Copyright 2007 by Trinitas. All rights reserved.
* Distributed under the terms of the BSD License.
*
* @autor David Jablonski, [email protected]
* @date 14.02.2009
*/
#include "lua_engine.h"
const char* LuaObj::GetTypeName(const char* sShort)
{
int id = GetTypeId();
glPlugin->CallLuaMethod("language","get","s",sShort);
lua_getfield(glState,-1,"items");
lua_pushnumber(glState, id);
lua_gettable(glState, -2);
lua_getfield(glState,-1,"name");
const char* sTypeName = lua_tostring(glState, -1);
lua_pop(glState, 4);
return sTypeName;
}
int LuaObj::GetTypeId()
{
return glPlugin->GetObjectNumber(this,"type.ID");
}
| [
"der_schakal@ab3bda7c-5b37-0410-9911-e7f4556ba333"
] | [
[
[
1,
29
]
]
] |
9d7c06e65ae1afa87afba017bf73e0d458100dd7 | 9f0a8126509f7042590f7830d3374369455bfda3 | /c++/pfms/src/pfms.h | cff595838202b931326b29d67ad72447f77ae6ee | [] | no_license | ArnCarveris/qut-pfms | 396512644ada6b01becc055c59d8ed9da847c4e6 | 6346d60952565750c7b94317f2bf8ed8fb38b2dc | refs/heads/master | 2020-06-08T13:36:27.525838 | 2009-09-19T15:54:12 | 2009-09-19T15:54:12 | 39,303,430 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 866 | h | #include <iostream>
#include <FGFDMExec.h>
#include <models/FGPropulsion.h>
#include <FGState.h>
#include <input_output/FGXMLParse.h>
#include <input_output/FGXMLFileRead.h>
//#include <input_output/FGXMLFileRead.h>
using namespace std;
#if !defined(__GNUC__) && !defined(sgi) && !defined(_MSC_VER)
# include <time>
#else
# include <time.h>
#endif
#if defined(__BORLANDC__) || defined(_MSC_VER) || defined(__MINGW32__)
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
# include <mmsystem.h>
# include <regstr.h>
# include <sys/types.h>
# include <sys/timeb.h>
#else
# include <sys/time.h>
#endif
// Function Definitions
bool pfms_init(JSBSim::FGFDMExec *FDMExec);
void pfms_publish_config(JSBSim::FGFDMExec *FDMExec);
void pfms_event(JSBSim::FGFDMExec *FDMExec);
void pfms_readJSBSimMessages(JSBSim::FGFDMExec* FDMExec); | [
"N.A.Rutherford@ac7fd53a-2cbc-11de-a3db-a5b3f7bb893a"
] | [
[
[
1,
32
]
]
] |
4660eff3b373285bccaac699e3882dd18c8eccec | 6bdb3508ed5a220c0d11193df174d8c215eb1fce | /Codes/Halak/UISimpleDomain.cpp | 9fbcf9f6fbdebac8b3a9b929cfc065cc35322291 | [] | no_license | halak/halak-plusplus | d09ba78640c36c42c30343fb10572c37197cfa46 | fea02a5ae52c09ff9da1a491059082a34191cd64 | refs/heads/master | 2020-07-14T09:57:49.519431 | 2011-07-09T14:48:07 | 2011-07-09T14:48:07 | 66,716,624 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 627 | cpp | #include <Halak/PCH.h>
#include <Halak/UISimpleDomain.h>
#include <Halak/UIWindow.h>
namespace Halak
{
UISimpleDomain::UISimpleDomain()
{
}
UISimpleDomain::UISimpleDomain(UIWindow* root)
: UIDomain(root)
{
}
UISimpleDomain::UISimpleDomain(UIWindow* root, UIVisual* focus)
: UIDomain(root),
focus(focus)
{
}
UISimpleDomain::~UISimpleDomain()
{
}
UIVisual* UISimpleDomain::GetFocus() const
{
return focus;
}
void UISimpleDomain::SetFocus(UIVisual* value)
{
focus = value;
}
} | [
"[email protected]"
] | [
[
[
1,
35
]
]
] |
ad8577e53bbc2bbc1a7f3409d145a1cee399e244 | ef23e388061a637f82b815d32f7af8cb60c5bb1f | /src/mame/includes/gaiden.h | 825c72b35326ef6691bbe5ac80fc31fea909b4a7 | [] | no_license | marcellodash/psmame | 76fd877a210d50d34f23e50d338e65a17deff066 | 09f52313bd3b06311b910ed67a0e7c70c2dd2535 | refs/heads/master | 2021-05-29T23:57:23.333706 | 2011-06-23T20:11:22 | 2011-06-23T20:11:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,068 | h | /***************************************************************************
Ninja Gaiden
***************************************************************************/
class gaiden_state : public driver_device
{
public:
gaiden_state(running_machine &machine, const driver_device_config_base &config)
: driver_device(machine, config) { }
/* memory pointers */
UINT16 * m_videoram;
UINT16 * m_videoram2;
UINT16 * m_videoram3;
UINT16 * m_spriteram;
size_t m_spriteram_size;
/* video-related */
tilemap_t *m_text_layer;
tilemap_t *m_foreground;
tilemap_t *m_background;
bitmap_t *m_sprite_bitmap;
bitmap_t *m_tile_bitmap_bg;
bitmap_t *m_tile_bitmap_fg;
UINT16 m_tx_scroll_x;
UINT16 m_tx_scroll_y;
UINT16 m_bg_scroll_x;
UINT16 m_bg_scroll_y;
UINT16 m_fg_scroll_x;
UINT16 m_fg_scroll_y;
INT8 m_tx_offset_y;
INT8 m_bg_offset_y;
INT8 m_fg_offset_y;
INT8 m_spr_offset_y;
/* misc */
int m_sprite_sizey;
int m_prot;
int m_jumpcode;
const int *m_raiga_jumppoints;
/* devices */
device_t *m_audiocpu;
};
/*----------- defined in video/gaiden.c -----------*/
VIDEO_START( gaiden );
VIDEO_START( raiga );
VIDEO_START( drgnbowl );
VIDEO_START( mastninj );
SCREEN_UPDATE( gaiden );
SCREEN_UPDATE( raiga );
SCREEN_UPDATE( drgnbowl );
WRITE16_HANDLER( gaiden_videoram_w );
WRITE16_HANDLER( gaiden_videoram2_w );
READ16_HANDLER( gaiden_videoram2_r );
WRITE16_HANDLER( gaiden_videoram3_w );
READ16_HANDLER( gaiden_videoram3_r );
WRITE16_HANDLER( gaiden_flip_w );
WRITE16_HANDLER( gaiden_txscrollx_w );
WRITE16_HANDLER( gaiden_txscrolly_w );
WRITE16_HANDLER( gaiden_fgscrollx_w );
WRITE16_HANDLER( gaiden_fgscrolly_w );
WRITE16_HANDLER( gaiden_bgscrollx_w );
WRITE16_HANDLER( gaiden_bgscrolly_w );
WRITE16_HANDLER( gaiden_txoffsety_w );
WRITE16_HANDLER( gaiden_fgoffsety_w );
WRITE16_HANDLER( gaiden_bgoffsety_w );
WRITE16_HANDLER( gaiden_sproffsety_w );
| [
"Mike@localhost"
] | [
[
[
1,
76
]
]
] |
276390f34f654421323520fa936ae30ca709f051 | bd72991991f999ffc721e7ff51099312e10bbab3 | /StkUI/Dialog/MyExcelReadDlg.cpp | ab55c590377bc772f608f7ec83b8c9351cb3040f | [] | no_license | alexfordc/my-st-king | 1c36ddc7830817ea007f81f565579a01045b4b8e | 8ffd0df93fb067013abcd808c24c23a068523ab7 | refs/heads/master | 2021-05-31T21:01:12.028462 | 2011-10-03T15:08:12 | 2011-10-03T15:08:12 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,549 | cpp | // MyExcelReadDlg.cpp : 实现文件
//
#include "stdafx.h"
#include "..\stkui.h"
#include "MyExcelReadDlg.h"
#include "afxdialogex.h"
#include "memory.h"
#include <time.h>
#include <atlbase.h>
// CMyExcelReadDlg 对话框
IMPLEMENT_DYNAMIC(CMyExcelReadDlg, CDialogEx)
CMyExcelReadDlg::CMyExcelReadDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(CMyExcelReadDlg::IDD, pParent)
{
m_excelFileName = _T("");
}
CMyExcelReadDlg::~CMyExcelReadDlg()
{
}
void CMyExcelReadDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CDataSrcDlg)
DDX_Control(pDX, IDCANCEL, m_btnCancel);
DDX_Control(pDX, IDOK, m_btnOK);
DDX_Control(pDX, IDC_EXCEL_EXPLORER, m_btnExcelExplorer);
DDX_Control(pDX, IDC_EDIT_EXCEL_NAME, m_editExcelName);
DDX_Text(pDX, IDC_EDIT_EXCEL_NAME, m_excelFileName);
//}}AFX_DATA_MAP
}
//IDC_STATIC_READ_EXCEL
BEGIN_MESSAGE_MAP(CMyExcelReadDlg, CDialogEx)
ON_BN_CLICKED(IDC_EXCEL_EXPLORER, OnExcelExplorer)
END_MESSAGE_MAP()
// CMyExcelReadDlg 消息处理程序
void CMyExcelReadDlg::OnExcelExplorer()
{
// TODO: Add your control notification handler code here
UpdateData( TRUE );
CKSFileDialog dlg (TRUE, NULL, NULL, OFN_HIDEREADONLY | OFN_FILEMUSTEXIST | OFN_EXPLORER | OFN_ENABLESIZING ,
"Excel files (*.xls)|*.xls|All files (*.*)|*.*||", NULL);
int nResult = dlg.DoModal();
if( IDOK == nResult )
{
m_excelFileName = dlg.GetPathName();
//use UpdateData(FALSE) to show m_excelFileName to window.
UpdateData( FALSE );
}
}
KDATA * CMyExcelReadDlg::GetPKDATA()
{
PKDATA pKData = NULL;
int i;
CMyExcel ExcelMain;
CSPTime sptime;
struct tm* pTemptime = NULL;
//very important to set struct tm to 0.
pTemptime = (struct tm*)malloc(sizeof(struct tm));
memset( pTemptime, 0, sizeof(struct tm) );
ExcelMain.Open(m_excelFileName);
LPDISPATCH lpDisp = NULL;
//get 1st sheet
lpDisp = ExcelMain.MySheets.GetItem((_variant_t)(long)1);
ExcelMain.MySheet.AttachDispatch(lpDisp,TRUE);
CString sheetName = ExcelMain.MySheet.GetName();
ExcelMain.OpenSheet( sheetName );
ExcelMain.AutoRange();
//calculate the data row total number
i = TITLE_ROW_COUNT + 1;
while( !ExcelMain.GetItemText( i, 1 ).IsEmpty( ) )
{
i++;
}
m_dataSize = i - TITLE_ROW_COUNT - 1;
//init data Array
//pKData will be freed in OnReadExcelData()
pKData = (KDATA *)malloc(m_dataSize * sizeof(KDATA));
memset( pKData, 0, m_dataSize * sizeof(KDATA) );
//set KData using Excel data
for(i = 0;i < m_dataSize;i++)
{
strptime(CT2CA(ExcelMain.GetItemText( i + TITLE_ROW_COUNT + 1, DATE_INDEX )), "%Y-%m-%d", pTemptime);
//strptime((LPCTSTR)ExcelMain.GetItemText( i + TITLE_ROW_COUNT + 1, DATE_INDEX ), "%Y-%m-%d", pTemptime);
sptime = mktime(pTemptime);
pKData[i].m_date = sptime.ToStockTimeDay();
pKData[i].m_fOpen = atof( ExcelMain.GetItemText( i + TITLE_ROW_COUNT + 1, OPENPRICE_INDEX ));
pKData[i].m_fHigh = atof( ExcelMain.GetItemText( i + TITLE_ROW_COUNT + 1, TOPPRICE_INDEX ));
pKData[i].m_fLow = atof( ExcelMain.GetItemText( i + TITLE_ROW_COUNT + 1, LOWPRICE_INDEX ));
pKData[i].m_fClose = atof( ExcelMain.GetItemText( i + TITLE_ROW_COUNT + 1, CLOSEPRICE_INDEX ));
pKData[i].m_fVolume = atof( ExcelMain.GetItemText( i + TITLE_ROW_COUNT + 1, VOLUME_INDEX ));
}
ExcelMain.Exit();
free(pTemptime);
return pKData;
}
int CMyExcelReadDlg::GetDataSize()
{
return m_dataSize;
}
| [
"[email protected]"
] | [
[
[
1,
131
]
]
] |
badfdc268abe63e27870f325f49ee1f6b02919f8 | 0b66a94448cb545504692eafa3a32f435cdf92fa | /tags/0.8/cpp-object.sourceforge.net/src/cpp_object/arguments/out.test.cpp | e4c59cbede7550b0d6839ff8a93d241d87420186 | [] | no_license | 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 | 61 | cpp | #include <cpp_object/arguments/out.hpp>
int main()
{
}
| [
"sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838"
] | [
[
[
1,
5
]
]
] |
ed69d7341e1bc6d22ced480fe9416eb34e495c30 | 79636d9a11c4ac53811d55ef0f432f68ab62944f | /smart-darkgdk/include/Limb.h | 11578f9b405fa1dba0df283a1eb172e1365a4a08 | [
"MIT"
] | permissive | endel/smart-darkgdk | 44d90a1afcd71deebef65f47dc54586df4ae4736 | 6235288b8aab505577223f9544a6e5a7eb6bf6cd | refs/heads/master | 2021-01-19T10:58:29.387767 | 2009-06-26T16:44:15 | 2009-06-26T16:44:15 | 32,123,434 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 824 | h | #pragma once
#include "commonobject.h"
#include "Object.h"
#include "Image.h"
class Limb :
public CommonObject
{
public:
Limb(void);
Limb(Object *linked, Object *top);
~Limb(void);
void glueObject(Object* o, int mode=NULL);
void hide();
void show();
void offset( float fX, float fY, float fZ, int iBoundFlag=NULL );
void rotate( float fX, float fY, float fZ, int iBoundFlag=NULL );
void scale( float fX, float fY, float fZ, int iBoundFlag=NULL );
void scale( float fXYZ );
void link( Object *o );
void texture( Image *img );
void texture( int iStage, Image *img );
void setColor( DWORD dwColor );
void scrollTexture( float fU, float fV );
void scaleTexture( float fU, float fV );
void setSmoothing( float fPercentage );
void setNormals();
private:
Object* topObj;
};
| [
"endel.dreyer@0995f060-2c81-11de-ae9b-2be1a451ffb1"
] | [
[
[
1,
33
]
]
] |
b84338c8cba1b4703472c604c83c91c038880af7 | 9f00cc73bdc643215425e6bc43ea9c6ef3094d39 | /OOP/ex1/Equiangular.h | 3ca0a41afea8efa2d6600123ff8aa59f0bf0e303 | [] | no_license | AndreyShamis/oopos | c0700e1d9d889655a52ad2bc58731934e968b1dd | 0114233944c4724f242fd38ac443a925faf81762 | refs/heads/master | 2021-01-25T04:01:48.005423 | 2011-07-16T14:23:12 | 2011-07-16T14:23:12 | 32,789,875 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 686 | h | //
// @ Project : Paint
// @ File Name : Equiangular.h
// @ Date : 3/3/2011
// @ Author : Andrey Shamis Ilia Gaysinski
// @ Description : A class that reprisen "Equiangular" shape at glut window
//
#pragma once
#define _USE_MATH_DEFINES
#include "shape.h"
#include <math.h>
#define DEFAULT_SIZE_R 0.2 // define default size of the Equiangular shape
// side
class Equiangular :public Shape // class Equiangular inherits from class Shape
{
public:
// Constractor of class Equiangular, get color and coordinat of start point
// to creat the shape.
Equiangular(float x, float y,RgbColor &color);
void Draw(); // Drow the shape: Equiangular
};
| [
"[email protected]@c8aee422-7d7c-7b79-c2f1-0e09d0793d10"
] | [
[
[
1,
23
]
]
] |
45de82ff72962bf4801c077f2d202483e2042c58 | e7788311c515f48118df40d1fd9f72d457bebff5 | /3DLIB/C3Dlib.cpp | e6ae8cdd4c44b47622d06c0279a465a6e3b59607 | [] | no_license | jbreslin33/dreamsock | 3af9131bd8437a2996e37b8413c6c85adfe5dbb1 | b6ee1bc1552266aef16970994493cc88fd172848 | refs/heads/master | 2021-01-02T09:31:59.704311 | 2010-12-21T05:28:21 | 2010-12-21T05:28:21 | 37,391,262 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 17,143 | cpp | // Simple 3D openGL Library
// Version 2.0
#include <windows.h>
#include <stdio.h>
#include <gl/gl.h>
#include <gl/glu.h>
#include <gl/glaux.h>
#include <vector>
using namespace std;
#include "C3Dmodel.h"
#include "C3Dlib.h"
using namespace std;
C3Dlib::C3Dlib()
{
hWnd=NULL;
hRC=NULL;
hDC=NULL;
hInstance = NULL;
fullscreen=TRUE;
for(int i=0; i<256; i++)
keys[i] = false;
}
C3Dlib::~C3Dlib()
{
}
BOOL C3Dlib::Initialize(char* title, int width, int height, int bits, bool fullscreenflag, WNDPROC winProc)
{
GLuint PixelFormat;
WNDCLASS wc;
DWORD dwExStyle;
DWORD dwStyle;
RECT WindowRect;
WindowRect.left=(long)0;
WindowRect.right=(long)width;
WindowRect.top=(long)0;
WindowRect.bottom=(long)height;
fullscreen=fullscreenflag;
hInstance = GetModuleHandle(NULL);
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wc.lpfnWndProc = (WNDPROC) winProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = NULL;
wc.lpszMenuName = NULL;
wc.lpszClassName = "OpenGL";
if (!RegisterClass(&wc)) // Attempt To Register The Window Class
{
MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Exit And Return FALSE
}
if (fullscreen) // Attempt Fullscreen Mode?
{
DEVMODE dmScreenSettings; // Device Mode
memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared
dmScreenSettings.dmSize=sizeof(dmScreenSettings); // Size Of The Devmode Structure
dmScreenSettings.dmPelsWidth = width; // Selected Screen Width
dmScreenSettings.dmPelsHeight = height; // Selected Screen Height
dmScreenSettings.dmBitsPerPel = bits; // Selected Bits Per Pixel
dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;
if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)
{
// If The Mode Fails, Offer Two Options. Quit Or Run In A Window.
if (MessageBox(NULL,"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?","2DLIB",MB_YESNO|MB_ICONEXCLAMATION)==IDYES)
{
fullscreen=FALSE; // Select Windowed Mode (Fullscreen=FALSE)
}
else
{
// Pop Up A Message Box Letting User Know The Program Is Closing.
MessageBox(NULL,"Program Will Now Close.","ERROR",MB_OK|MB_ICONSTOP);
return FALSE; // Exit And Return FALSE
}
}
}
if (fullscreen) // Are We Still In Fullscreen Mode?
{
dwExStyle=WS_EX_APPWINDOW; // Window Extended Style
dwStyle=WS_POPUP; // Windows Style
ShowCursor(FALSE); // Hide Mouse Pointer
}
else
{
dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Window Extended Style
dwStyle=WS_OVERLAPPEDWINDOW; // Windows Style
}
AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);
if (!(hWnd=CreateWindowEx( dwExStyle, // Extended Style For The Window
"OpenGL", // Class Name
title, // Window Title
WS_CLIPSIBLINGS | // Required Window Style
WS_CLIPCHILDREN | // Required Window Style
dwStyle, // Selected Window Style
0, 0, // Window Position
WindowRect.right-WindowRect.left, // Calculate Adjusted Window Width
WindowRect.bottom-WindowRect.top, // Calculate Adjusted Window Height
NULL, // No Parent Window
NULL, // No Menu
hInstance, // Instance
NULL)))
{
Shutdown(); // Reset The Display
MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
static PIXELFORMATDESCRIPTOR pfd= // pfd Tells Windows How We Want Things To Be
{
sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
1, // Version Number
PFD_DRAW_TO_WINDOW | // Format Must Support Window
PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
PFD_DOUBLEBUFFER, // Must Support Double Buffering
PFD_TYPE_RGBA, // Request An RGBA Format
bits, // Select Our Color Depth
0, 0, 0, 0, 0, 0, // Color Bits Ignored
0, // No Alpha Buffer
0, // Shift Bit Ignored
0, // No Accumulation Buffer
0, 0, 0, 0, // Accumulation Bits Ignored
16, // 16Bit Z-Buffer (Depth Buffer)
0, // No Stencil Buffer
0, // No Auxiliary Buffer
PFD_MAIN_PLANE, // Main Drawing Layer
0, // Reserved
0, 0, 0 // Layer Masks Ignored
};
if (!(hDC=GetDC(hWnd))) // Did We Get A Device Context?
{
Shutdown(); // Reset The Display
MessageBox(NULL,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd))) // Did Windows Find A Matching Pixel Format?
{
Shutdown(); // Reset The Display
MessageBox(NULL,"Can't Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if(!SetPixelFormat(hDC,PixelFormat,&pfd)) // Are We Able To Set The Pixel Format?
{
Shutdown(); // Reset The Display
MessageBox(NULL,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (!(hRC=wglCreateContext(hDC))) // Are We Able To Get A Rendering Context?
{
Shutdown(); // Reset The Display
MessageBox(NULL,"Can't Create A GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if(!wglMakeCurrent(hDC,hRC)) // Try To Activate The Rendering Context
{
Shutdown(); // Reset The Display
MessageBox(NULL,"Can't Activate The GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
ShowWindow(hWnd,SW_SHOW); // Show The Window
SetForegroundWindow(hWnd); // Slightly Higher Priority
SetFocus(hWnd); // Sets Keyboard Focus To The Window
Resize(width, height);
// Initialise openGL
glShadeModel(GL_SMOOTH);
glEnable(GL_TEXTURE_2D);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClearDepth(1.0f); // Depth Buffer Setup
glEnable(GL_DEPTH_TEST); // Enables Depth Testing
glDepthFunc(GL_LEQUAL);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_GREATER, 0);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
return TRUE;
}
void C3Dlib::Shutdown(void)
{
if (fullscreen) // Are We In Fullscreen Mode?
{
ChangeDisplaySettings(NULL,0); // If So Switch Back To The Desktop
ShowCursor(TRUE); // Show Mouse Pointer
}
if (hRC) // Do We Have A Rendering Context?
{
if (!wglMakeCurrent(NULL,NULL)) // Are We Able To Release The DC And RC Contexts?
{
MessageBox(NULL,"Release Of DC And RC Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
}
if (!wglDeleteContext(hRC)) // Are We Able To Delete The RC?
{
MessageBox(NULL,"Release Rendering Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
}
hRC=NULL; // Set RC To NULL
}
if (hDC && !ReleaseDC(hWnd,hDC)) // Are We Able To Release The DC
{
MessageBox(NULL,"Release Device Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
hDC=NULL; // Set DC To NULL
}
if (hWnd && !DestroyWindow(hWnd)) // Are We Able To Destroy The Window?
{
MessageBox(NULL,"Could Not Release hWnd.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
hWnd=NULL; // Set hWnd To NULL
}
if (!UnregisterClass("OpenGL",hInstance)) // Are We Able To Unregister Class
{
MessageBox(NULL,"Could Not Unregister Class.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
hInstance=NULL; // Set hInstance To NULL
}
}
void C3Dlib::Begin(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
}
void C3Dlib::End(void)
{
glFlush();
SwapBuffers(hDC);
}
void C3Dlib::SetMode(int mode) // C3DMODE_2D | C3DMODE_3D
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
switch(mode)
{
case C3DMODE_2D:
gluOrtho2D(0, width, height, 0);
break;
case C3DMODE_3D:
gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);
break;
}
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void C3Dlib::Resize(int width, int height)
{
if (height==0)
height=1;
glViewport(0, 0, width, height);
this->width = width;
this->height = height;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);
glOrtho(0, width, height, 0, -1.0f, 1.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
// Primitives
void C3Dlib::Pixel(int x1, int y1, int r, int g, int b)
{
float fr,fg,fb;
fr = (float)(r/255.0);
fg = (float)(g/255.0);
fb = (float)(b/255.0);
glBindTexture(GL_TEXTURE_2D, 0);
glPushMatrix();
glBegin(GL_POINTS);
{
glColor3f(fr,fg,fb);
glVertex2s(x1,y1);
glColor3f(1.0,1.0,1.0);
}
glEnd();
glPopMatrix();
}
void C3Dlib::Line(int x1, int y1, int x2, int y2, int r, int g, int b)
{
float fr,fg,fb;
fr = (float)(r/255.0);
fg = (float)(g/255.0);
fb = (float)(b/255.0);
glBindTexture(GL_TEXTURE_2D, 0);
glPushMatrix();
glBegin(GL_LINES);
{
glColor3f(fr,fg,fb);
glVertex2s(x1,y1);
glVertex2s(x2,y2);
glColor3f(1.0,1.0,1.0);
}
glEnd();
glPopMatrix();
}
void C3Dlib::Rect(int x1, int y1, int x2, int y2, int r, int g, int b)
{
float fr,fg,fb;
fr = (float)(r/255.0);
fg = (float)(g/255.0);
fb = (float)(b/255.0);
glBindTexture(GL_TEXTURE_2D, 0);
glPushMatrix();
glBegin(GL_LINE_STRIP);
{
glColor3f(fr,fg,fb);
glVertex2s(x1,y1);
glVertex2s(x2,y1);
glVertex2s(x2,y2);
glVertex2s(x1,y2);
glVertex2s(x1,y1);
glColor3f(1.0,1.0,1.0);
}
glEnd();
glPopMatrix();
}
void C3Dlib::RectFill(int x1, int y1, int x2, int y2, int r, int g, int b)
{
float fr,fg,fb;
fr = (float)(r/255.0);
fg = (float)(g/255.0);
fb = (float)(b/255.0);
glBindTexture(GL_TEXTURE_2D, 0);
glPushMatrix();
glBegin(GL_QUADS);
{
glColor3f(fr,fg,fb);
glVertex2s(x1,y1);
glVertex2s(x2,y1);
glVertex2s(x2,y2);
glVertex2s(x1,y2);
glVertex2s(x1,y1);
glColor3f(1.0,1.0,1.0);
}
glEnd();
glPopMatrix();
}
void C3Dlib::Tri(int x1, int y1, int x2, int y2, int x3, int y3, int r, int g, int b)
{
float fr,fg,fb;
fr = (float)(r/255.0);
fg = (float)(g/255.0);
fb = (float)(b/255.0);
glBindTexture(GL_TEXTURE_2D, 0);
glPushMatrix();
glBegin(GL_LINE_STRIP);
{
glColor3f(fr,fg,fb);
glVertex2s(x1,y1);
glVertex2s(x2,y2);
glVertex2s(x3,y3);
glVertex2s(x1,y1);
glColor3f(1.0,1.0,1.0);
}
glEnd();
glPopMatrix();
}
void C3Dlib::TriFill(int x1, int y1, int x2, int y2, int x3, int y3, int r, int g, int b)
{
float fr,fg,fb;
fr = (float)(r/255.0);
fg = (float)(g/255.0);
fb = (float)(b/255.0);
glBindTexture(GL_TEXTURE_2D, 0);
glPushMatrix();
glBegin(GL_TRIANGLES);
{
glColor3f(fr,fg,fb);
glVertex2s(x1,y1);
glVertex2s(x2,y2);
glVertex2s(x3,y3);
glVertex2s(x1,y1);
glColor3f(1.0,1.0,1.0);
}
glEnd();
glPopMatrix();
}
// Blitting and Loading Functions
void C3Dlib::LoadBitmap(C3DIMAGE2D *pImage, char *filename)
{
AUX_RGBImageRec *TextureImage[1];
memset(TextureImage,0,sizeof(void *)*1);
char data[262144];
if (TextureImage[0]=auxDIBImageLoad(filename))
{
// Scale the texture to 2^8
gluScaleImage(GL_RGB, TextureImage[0]->sizeX, TextureImage[0]->sizeY, GL_UNSIGNED_BYTE, TextureImage[0]->data, 256, 256, GL_UNSIGNED_BYTE, data);
glGenTextures(1, pImage); // Create The Texture
// Typical Texture Generation Using Data From The Bitmap
glBindTexture(GL_TEXTURE_2D, *pImage);
glTexImage2D(GL_TEXTURE_2D, 0, 3, 256, 256, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); // Linear Filtering
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); // Linear Filtering
}
if (TextureImage[0]) // If Texture Exists
{
if (TextureImage[0]->data) // If Texture Image Exists
{
free(TextureImage[0]->data); // Free The Texture Image Memory
}
free(TextureImage[0]); // Free The Image Structure
}
}
// NB: Will only work for 24/32 bit uncompressed TGA files
void C3Dlib::LoadTarga(C3DIMAGE2D *pImage, char *filename) // Loads A TGA File Into Memory
{
GLubyte TGAheader[12]={0,0,2,0,0,0,0,0,0,0,0,0}; // Uncompressed TGA Header
GLubyte TGAcompare[12]; // Used To Compare TGA Header
GLubyte header[6]; // First 6 Useful Bytes From The Header
GLuint bytesPerPixel; // Holds Number Of Bytes Per Pixel Used In The TGA File
GLuint imageSize; // Used To Store The Image Size When Setting Aside Ram
GLuint temp; // Temporary Variable
GLuint type=GL_RGBA; // Set The Default GL Mode To RBGA (32 BPP)
i_TgaData texture[1];
char data[262144];
FILE *file = fopen(filename, "rb"); // Open The TGA File
if( file==NULL || // Does File Even Exist?
fread(TGAcompare,1,sizeof(TGAcompare),file)!=sizeof(TGAcompare) || // Are There 12 Bytes To Read?
memcmp(TGAheader,TGAcompare,sizeof(TGAheader))!=0 || // Does The Header Match What We Want?
fread(header,1,sizeof(header),file)!=sizeof(header)) // If So Read Next 6 Header Bytes
{
/*if (file == NULL) // Did The File Even Exist? *Added Jim Strong*
//return false; // Return False
else
{
fclose(file); // If Anything Failed, Close The File
//return false; // Return False
}*/
}
texture->width = header[1] * 256 + header[0]; // Determine The TGA Width (highbyte*256+lowbyte)
texture->height = header[3] * 256 + header[2]; // Determine The TGA Height (highbyte*256+lowbyte)
if( texture->width <=0 || // Is The Width Less Than Or Equal To Zero
texture->height <=0 || // Is The Height Less Than Or Equal To Zero
(header[4]!=24 && header[4]!=32)) // Is The TGA 24 or 32 Bit?
{
fclose(file); // If Anything Failed, Close The File
// return false; // Return False
}
texture->bpp = header[4]; // Grab The TGA's Bits Per Pixel (24 or 32)
bytesPerPixel = texture->bpp/8; // Divide By 8 To Get The Bytes Per Pixel
imageSize = texture->width*texture->height*bytesPerPixel;
texture->imageData=(GLubyte *)malloc(imageSize); // Reserve Memory To Hold The TGA Data
if( texture->imageData==NULL || // Does The Storage Memory Exist?
fread(texture->imageData, 1, imageSize, file)!=imageSize) // Does The Image Size Match The Memory Reserved?
{
if(texture->imageData!=NULL) // Was Image Data Loaded
free(texture->imageData); // If So, Release The Image Data
fclose(file); // Close The File
// return false; // Return False
}
for(GLuint i=0; i<int(imageSize); i+=bytesPerPixel) // Loop Through The Image Data
{ // Swaps The 1st And 3rd Bytes ('R'ed and 'B'lue)
temp=texture->imageData[i]; // Temporarily Store The Value At Image Data 'i'
texture->imageData[i] = texture->imageData[i + 2]; // Set The 1st Byte To The Value Of The 3rd Byte
texture->imageData[i + 2] = temp; // Set The 3rd Byte To The Value In 'temp' (1st Byte Value)
}
fclose (file);
// Build A Texture From The Data
gluScaleImage(GL_RGBA, texture->width, texture->height, GL_UNSIGNED_BYTE, texture->imageData, 256, 256, GL_UNSIGNED_BYTE, data);
glGenTextures(1, pImage); // Generate OpenGL texture IDs
glBindTexture(GL_TEXTURE_2D, *pImage); // Bind Our Texture
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // Linear Filtered
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Linear Filtered
if (texture[0].bpp==24) // Was The TGA 24 Bits
{
type=GL_RGBA; // If So Set The 'type' To GL_RGB
}
glTexImage2D(GL_TEXTURE_2D, 0, type, 256, 256, 0, type, GL_UNSIGNED_BYTE, data);
}
void C3Dlib::Blit(C3DIMAGE2D *pImage, int x, int y, int w, int h, float rotate)
{
int half_width = (int)(w/2);
int half_height = (int)(h/2);
glBindTexture(GL_TEXTURE_2D, *pImage);
glPushMatrix();
glTranslatef((float)x+half_width,(float)y+half_height,0);
glRotatef(rotate, 0, 0, 1);
glBegin(GL_QUADS);
{
glTexCoord2d(0.0,1.0);glVertex2s(-half_width,-half_height);
glTexCoord2d(1.0,1.0);glVertex2s(half_width,-half_height);
glTexCoord2d(1.0,0.0);glVertex2s(half_width,half_width);
glTexCoord2d(0.0,0.0);glVertex2s(-half_width,half_width);
}
glEnd();
glPopMatrix();
} | [
"jbreslin33@localhost"
] | [
[
[
1,
589
]
]
] |
41fedc175e08450e21a65432e87fa2419f6d457d | 0c84ebd32a2646b5582051216d6e7c8283bb4f23 | /wxButtonDialog.h | df695b04be79246001282aa2ddb5593417f76140 | [] | no_license | AudioAnecdotes/wxWizApp | 97932d2e6fd2c38934c16629a5e3d6023e0978ac | 129dfad68be44581c97249d2975efca2fa7578b7 | refs/heads/master | 2021-01-18T06:36:29.316270 | 2007-01-02T06:02:13 | 2007-01-02T06:02:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,141 | h | // wxButtonDialog.h: interface for the wxButtonDialog class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_WXBUTTONDIALOG_H__948E50EC_600C_445F_BA37_DAA83347BF90__INCLUDED_)
#define AFX_WXBUTTONDIALOG_H__948E50EC_600C_445F_BA37_DAA83347BF90__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "wxWizBaseDlg.h"
class wxButtonDialog : public wxWizBaseDlg
{
public:
wxButtonDialog(WizAppData* data);
virtual ~wxButtonDialog();
protected:
void LocalInitDialog();
virtual void CheckButton(int index,bool Checked=TRUE)=0;
virtual void SetButtonValue(int index,wxString& data)=0;
virtual void ShowButton(int index,bool bCmdShow=TRUE)=0;
virtual void SetButtonFocus(int index)=0;
virtual bool IsButtonChecked(int index)=0;
virtual wxWindow* GetWindow(int index)=0;
virtual void OnButtonPressed(int errlevel);
wxArrayString items;
wxArrayString strinits;
wxArrayString numinits;
int nritems;
int nrnuminits;
int nrstrinits;
};
#endif // !defined(AFX_WXBUTTONDIALOG_H__948E50EC_600C_445F_BA37_DAA83347BF90__INCLUDED_)
| [
"gsilber"
] | [
[
[
1,
37
]
]
] |
2e69f8816e0dec7054431f61635f3e9f460bb491 | 01fa6f43ad536f4c9656be0f2c7da69c6fc9dc1c | /mainfrm.h | 76868dcf10627b473c5a3d9e760931531a0cbd05 | [] | no_license | akavel/wed-editor | 76a22b7ff1bb4b109cfe5f3cc630e18ebb91cd51 | 6a10c167e46bfcb65adb514a1278634dfcb384c1 | refs/heads/master | 2021-01-19T19:33:18.124144 | 2010-04-16T20:32:17 | 2010-04-16T20:32:17 | 10,511,499 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,430 | h | // MainFrm.h : interface of the CMainFrame class
//
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_MAINFRM_H__87F3F488_DE8E_11D2_BEED_002078105E2C__INCLUDED_)
#define AFX_MAINFRM_H__87F3F488_DE8E_11D2_BEED_002078105E2C__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
#include "logomdi.h"
class CMainFrame : public CMDIFrameWnd
{
DECLARE_DYNAMIC(CMainFrame)
public:
CMainFrame();
CLogoMdi m_LogoMdiClientWnd;
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CMainFrame)
public:
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
virtual BOOL LoadFrame(UINT nIDResource, DWORD dwDefaultStyle = WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, CWnd* pParentWnd = NULL, CCreateContext* pContext = NULL);
virtual void OnSetPreviewMode(BOOL bPreview, CPrintPreviewState* pState);
virtual BOOL PreTranslateMessage(MSG* pMsg);
protected:
virtual LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam);
virtual BOOL OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext);
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CMainFrame();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
public: // control bar embedded members
void SetPosIndicator();
CStatusBar m_wndStatusBar;
CToolBar m_wndToolBar;
CToolBar m_wndToolBar1;
void AutoSave();
// Generated message map functions
protected:
//{{AFX_MSG(CMainFrame)
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnActivate(UINT nState, CWnd* pWndOther, BOOL bMinimized);
afx_msg void OnViewToolbar2();
afx_msg void OnOpensource();
afx_msg void OnTimer(UINT nIDEvent);
afx_msg void OnFileMultiopen();
afx_msg void OnSetFocus(CWnd* pOldWnd);
afx_msg void OnEnterIdle(UINT nWhy, CWnd* pWho);
afx_msg void OnDropFiles(HDROP hDropInfo);
afx_msg void OnHelpRegistration();
afx_msg void OnFileSaveAs();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_MAINFRM_H__87F3F488_DE8E_11D2_BEED_002078105E2C__INCLUDED_)
| [
"none@none"
] | [
[
[
1,
79
]
]
] |
ba10ade6b24878492c1603414e614add26f8e15d | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/range/concepts.hpp | 929062c07a6cbbbd636062ee7248af280bc7d311 | [
"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,020 | hpp | // Boost.Range library concept checks
//
// Copyright Daniel Walker 2006. 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)
//
// For more information, see http://www.boost.org/libs/range/
//
#ifndef BOOST_RANGE_CONCEPTS_HPP
#define BOOST_RANGE_CONCEPTS_HPP
#include <boost/concept_check.hpp>
#include <boost/iterator/iterator_concepts.hpp>
#include <boost/range/functions.hpp>
#include <boost/range/metafunctions.hpp>
/*!
* \file
* \brief Concept checks for the Boost Range library.
*
* The structures in this file may be used in conjunction with the
* Boost Concept Check library to insure that the type of a function
* parameter is compatible with a range concept. If not, a meaningful
* compile time error is generated. Checks are provided for the range
* concepts related to iterator traversal categories. For example, the
* following line checks that the type T models the ForwardRange
* concept.
*
* \code
* function_requires<ForwardRangeConcept<T> >();
* \endcode
*
* An additional concept check is required for the value access
* property of the range. For example to check for a
* ForwardReadableRange, the following code is required.
*
* \code
* function_requires<ForwardRangeConcept<T> >();
* function_requires<
* ReadableIteratorConcept<
* typename range_iterator<T>::type
* >
* >();
* \endcode
*
* \see http://www.boost.org/libs/range/doc/range.html for details
* about range concepts.
* \see http://www.boost.org/libs/iterator/doc/iterator_concepts.html
* for details about iterator concepts.
* \see http://www.boost.org/libs/concept_check/concept_check.htm for
* details about concept checks.
*/
namespace boost {
//! Check if a type T models the SinglePassRange range concept.
template<typename T>
struct SinglePassRangeConcept {
typedef typename range_value<T>::type range_value;
typedef typename range_iterator<T>::type range_iterator;
typedef typename range_const_iterator<T>::type range_const_iterator;
void constraints()
{
function_requires<
boost_concepts::SinglePassIteratorConcept<
range_iterator
>
>();
i = boost::begin(a);
i = boost::end(a);
b = boost::empty(a);
const_constraints(a);
}
void const_constraints(const T& a)
{
ci = boost::begin(a);
ci = boost::end(a);
}
T a;
range_iterator i;
range_const_iterator ci;
bool b;
};
//! Check if a type T models the ForwardRange range concept.
template<typename T>
struct ForwardRangeConcept {
typedef typename range_difference<T>::type range_difference;
typedef typename range_size<T>::type range_size;
void constraints()
{
function_requires<
SinglePassRangeConcept<T>
>();
function_requires<
boost_concepts::ForwardTraversalConcept<
typename range_iterator<T>::type
>
>();
s = boost::size(a);
}
T a;
range_size s;
};
//! Check if a type T models the BidirectionalRange range concept.
template<typename T>
struct BidirectionalRangeConcept {
typedef typename range_reverse_iterator<T>::type range_reverse_iterator;
typedef typename range_const_reverse_iterator<T>::type range_const_reverse_iterator;
void constraints()
{
function_requires<
ForwardRangeConcept<T>
>();
function_requires<
boost_concepts::BidirectionalTraversalConcept<
typename range_iterator<T>::type
>
>();
i = boost::rbegin(a);
i = boost::rend(a);
const_constraints(a);
}
void const_constraints(const T& a)
{
ci = boost::rbegin(a);
ci = boost::rend(a);
}
T a;
range_reverse_iterator i;
range_const_reverse_iterator ci;
};
//! Check if a type T models the RandomAccessRange range concept.
template<typename T>
struct RandomAccessRangeConcept {
void constraints()
{
function_requires<
BidirectionalRangeConcept<T>
>();
function_requires<
boost_concepts::RandomAccessTraversalConcept<
typename range_iterator<T>::type
>
>();
}
};
} // namespace boost
#endif // BOOST_RANGE_CONCEPTS_HPP
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
155
]
]
] |
03d051af8600e4164747c0e0caf68ffe49c8245a | bef7d0477a5cac485b4b3921a718394d5c2cf700 | /dingus/tools/MeshTexer/src/demo/Demo.cpp | 4a2d666c2804fcb837689079b81d257044835f78 | [
"MIT"
] | permissive | TomLeeLive/aras-p-dingus | ed91127790a604e0813cd4704acba742d3485400 | 22ef90c2bf01afd53c0b5b045f4dd0b59fe83009 | refs/heads/master | 2023-04-19T20:45:14.410448 | 2011-10-04T10:51:13 | 2011-10-04T10:51:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,443 | cpp | #include "stdafx.h"
// Demo application.
// Most of stuff is just kept in global variables :)
#include "Demo.h"
#include "DemoResources.h"
#include <dingus/resource/IndexBufferFillers.h>
#include <dingus/gfx/gui/Gui.h>
#include <dingus/math/MathUtils.h>
#include <dingus/gfx/geometry/DynamicVBManager.h>
#include <dingus/renderer/RenderableMesh.h>
#include "WinFileDlg.h"
#include "Entity.h"
// --------------------------------------------------------------------------
// Demo variables, constants, etc.
/// Possible render modes.
enum eRenderMode {
RM_CHECKER = 0,
RM_NORMALMAP,
RM_MAPPED,
RM_BAKED,
RM_TEXBAKER,
RMCOUNT
};
const char* RMODE_FX[RMCOUNT] = {
"checker",
"normalmap",
"mapped",
"baked",
"texbaker", // not user selectable
};
class CMeshTexerEntity : public CAbstractEntity {
public:
CMeshTexerEntity( const std::string& meshName );
virtual ~CMeshTexerEntity();
/// Gets AABB
const CAABox& getAABB() const { return mMesh->getTotalAABB(); }
/// Gets mesh
const CMesh& getMesh() const { return *mMesh; }
/// Updates WVP, adds to render context
void render( eRenderMode renderMode );
CRenderableMesh* getRenderMesh( eRenderMode renderMode ) {
return mRenderMeshes[renderMode];
}
private:
CMesh* mMesh;
CRenderableMesh* mRenderMeshes[RMCOUNT];
};
CMeshTexerEntity::CMeshTexerEntity( const std::string& meshName )
: mMesh(0)
{
assert( !meshName.empty() );
mMesh = RGET_MESH(meshName);
for( int i = 0; i < RMCOUNT; ++i ) {
mRenderMeshes[i] = new CRenderableMesh( *mMesh, CRenderableMesh::ALL_GROUPS, &mWorldMat.getOrigin(), 0 );
CEffectParams& ep = mRenderMeshes[i]->getParams();
ep.setEffect( *RGET_FX(RMODE_FX[i]) );
addMatricesToParams( ep );
ep.addTexture( "tChecker", *RGET_TEX("Checker") );
ep.addTexture( "tBase", *RGET_TEX("Checker") );
}
}
CMeshTexerEntity::~CMeshTexerEntity()
{
for( int i = 0; i < RMCOUNT; ++i )
delete mRenderMeshes[i];
}
void CMeshTexerEntity::render( eRenderMode renderMode )
{
updateWVPMatrices();
G_RENDERCTX->attach( *mRenderMeshes[renderMode] );
}
// --------------------------------------------------------------------------
IDingusAppContext* gAppContext;
SD3DSettingsPref* gD3DSettingsPref;
std::string gErrorMsg;
SVector4 gScreenFixUVs;
int gGlobalFillMode = D3DFILL_SOLID;
bool gFinished = false;
bool gShowStats = false;
// --------------------------------------------------------------------------
CDemo::CDemo()
{
}
bool CDemo::checkDevice( const CD3DDeviceCaps& caps, CD3DDeviceCaps::eVertexProcessing vproc, CD3DEnumErrors& errors )
{
bool ok = true;
// require VS1.1, or SW vertex processing
if( caps.getVShaderVersion() < CD3DDeviceCaps::VS_1_1 && vproc < CD3DDeviceCaps::VP_SW ) {
// don't add error - will turn on swvp and it will be ok
ok = false;
}
// require PS2.0
if( caps.getPShaderVersion() < CD3DDeviceCaps::PS_2_0 ) {
errors.addError( "Pixel shader 2.0 required" );
ok = false;
}
// TBD
// require at least this amount of video memory
const int videoMB = 48;
if( caps.getVideoMemoryMB() < videoMB ) {
char buf[200];
sprintf( buf, "%iMB of video memory is required, found %iMB", videoMB, caps.getVideoMemoryMB() );
errors.addError( buf );
ok = false;
}
// return result
return ok;
}
bool CDemo::shouldFinish()
{
return gFinished;
}
bool CDemo::shouldShowStats()
{
return gShowStats;
}
// --------------------------------------------------------------------------
// Demo initialization
CCameraEntity gCamera;
float gCameraYaw, gCameraPitch, gCameraDist;
CMeshTexerEntity* gMesh; // Current mesh. May be NULL.
std::string gCurMeshName;
std::string gCurNormalMapName;
std::string gCurDiffTexName;
float gMeshRadius = 1.0f;
SVector3 gMeshCenter;
float gTexerScale;
// mouse
float gMouseX; // from -1 to 1
float gMouseY; // from -1 to 1
SVector3 gMouseRay;
// --------------------------------------------------------------------------
void gLoadNewMesh( const std::string& meshName )
{
// destroy old mesh if there was one
if( !gCurMeshName.empty() ) {
CMeshBundle::getInstance().clearResourceById( gCurMeshName );
}
safeDelete( gMesh );
gCurMeshName = meshName;
gMesh = new CMeshTexerEntity( meshName );
// estimate mesh size
const CAABox& aabb = gMesh->getAABB();
gMeshCenter = aabb.getCenter();
SVector3 halfDiag = aabb.getMax() - gMeshCenter;
gMeshRadius = halfDiag.length();
// position mesh in the origin
gMesh->mWorldMat.identify();
gMesh->mWorldMat.getOrigin() -= gMeshCenter;
// position camera looking at mesh
gCameraDist = gMeshRadius*2;
gCameraYaw = 0.0f;
gCameraPitch = 0.0f;
}
void gLoadNormapMap( const std::string& fileName )
{
// destroy old normal map if there was one
if( !gCurNormalMapName.empty() ) {
CTextureBundle::getInstance().clearResourceById( gCurNormalMapName );
}
gCurNormalMapName = fileName;
CD3DTexture* tex = RGET_TEX(fileName);
if( gMesh ) {
for( int i = 0; i < RMCOUNT; ++i ) {
CEffectParams& ep = gMesh->getRenderMesh( eRenderMode(i) )->getParams();
ep.removeTexture( "tNormalAO" );
ep.addTexture( "tNormalAO", *tex );
}
}
}
void gLoadDiffuseTex( const std::string& fileName )
{
// destroy old texture if there was one
if( !gCurDiffTexName.empty() ) {
CTextureBundle::getInstance().clearResourceById( gCurDiffTexName );
}
gCurDiffTexName = fileName;
CD3DTexture* tex = RGET_TEX(fileName);
if( gMesh ) {
for( int i = 0; i < RMCOUNT; ++i ) {
CEffectParams& ep = gMesh->getRenderMesh( eRenderMode(i) )->getParams();
ep.removeTexture( "tBase" );
ep.addTexture( "tBase", *tex );
}
}
}
void gBakeTexture( int sizeX, int sizeY, D3DXIMAGE_FILEFORMAT format )
{
if( !gMesh )
return;
CD3DDevice& dx = CD3DDevice::getInstance();
// create RT
IDirect3DSurface9* rt = 0;
CD3DSurface dummyRT;
dx.getDevice().CreateRenderTarget( sizeX, sizeY, D3DFMT_A8R8G8B8, D3DMULTISAMPLE_NONE, 0, FALSE, &rt, NULL );
dummyRT.setObject( rt );
dx.setRenderTarget( &dummyRT, 0 );
dx.setZStencil( NULL );
// render baked mesh into UV space
CEffectParams& ep = gMesh->getRenderMesh( RM_TEXBAKER )->getParams();
ep.addFloat( "fSizeX", sizeX );
ep.addFloat( "fSizeY", sizeY );
dx.clearTargets( true, false, false, 0xFF000000 );
dx.sceneBegin();
G_RENDERCTX->applyGlobalEffect();
gMesh->render( RM_TEXBAKER );
G_RENDERCTX->perform();
dx.sceneEnd();
ep.removeFloat( "fSizeX" );
ep.removeFloat( "fSizeY" );
dx.setDefaultRenderTarget();
dx.setDefaultZStencil();
// create managed texture and fetch back RT
IDirect3DTexture9* texture = 0;
dx.getDevice().CreateTexture( sizeX, sizeY, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_SYSTEMMEM, &texture, NULL );
IDirect3DSurface9* surface = 0;
texture->GetSurfaceLevel( 0, &surface );
dx.getDevice().GetRenderTargetData( rt, surface );
surface->Release();
rt->Release();
// apply texture gutter
ID3DXMesh* dxMesh = gMesh->getMesh().createD3DXMesh();
ID3DXTextureGutterHelper* gutter = NULL;
HRESULT hr;
hr = D3DXCreateTextureGutterHelper( sizeX, sizeY, dxMesh, float(max(sizeX,sizeY))/1024*10, &gutter );
hr = gutter->ApplyGuttersTex( texture );
gutter->Release();
dxMesh->Release();
// save the texture
const char* fileName = "TexerBaked.dds";
switch( format ) {
case D3DXIFF_DDS: fileName = "TexerBaked.dds"; break;
case D3DXIFF_PNG: fileName = "TexerBaked.png"; break;
}
hr = D3DXSaveTextureToFile( fileName, format, texture, NULL );
texture->Release();
// remove it from our resource bundle and load again
CResourceId rid( "../../TexerBaked" );
CTextureBundle::getInstance().clearResourceById( rid );
CD3DTexture* tex = RGET_TEX( rid );
// set it in the effect
gMesh->getRenderMesh( RM_BAKED )->getParams().removeTexture( "tBaked" );
gMesh->getRenderMesh( RM_BAKED )->getParams().addTexture( "tBaked", *tex );
}
// --------------------------------------------------------------------------
// GUI
enum eUICtrlIDs {
GID_BTN_OPENMESH = 1000,
GID_BTN_OPENNMAP,
GID_BTN_OPENDIFFTEX,
GID_CMB_RENDERMODE,
GID_BTN_BAKE,
GID_CMB_BAKESIZEX,
GID_CMB_BAKESIZEY,
GID_CMB_BAKEAA,
GID_CMB_BAKEFORMAT,
GID_CHK_WIREFRAME,
};
CUIDialog* gUIDlg;
CUIButton* gUIBtnOpenMesh;
CUIButton* gUIBtnOpenNMap;
CUIButton* gUIBtnOpenDiffTex;
CUIButton* gUIBtnBake;
CUIComboBox* gUICmbRenderMode;
CUIComboBox* gUICmbBakeSizeX;
CUIComboBox* gUICmbBakeSizeY;
CUIComboBox* gUICmbBakeAA;
CUIComboBox* gUICmbBakeFormat;
CUICheckBox* gUIChkWireframe;
CUIStatic* gUILabMesh;
CUIStatic* gUILabNMap;
CUIStatic* gUILabDiffTex;
CUISlider* gUISldScale;
CUIStatic* gUILabScale;
void CALLBACK gUICallback( UINT evt, int ctrlID, CUIControl* ctrl )
{
switch( evt ) {
case UIEVENT_BUTTON_CLICKED:
switch( ctrlID ) {
case GID_BTN_OPENMESH:
{
std::string fileName = gGetOpenFileName( FILE_FILTER_MESH );
if( !fileName.empty() ) {
gUIDlg->getButton(GID_BTN_OPENNMAP)->setEnabled( true );
gUIDlg->getButton(GID_BTN_OPENDIFFTEX)->setEnabled( true );
gUIDlg->getButton(GID_BTN_BAKE)->setEnabled( true );
gUICmbBakeSizeX->setEnabled( true );
gUICmbBakeSizeY->setEnabled( true );
gLoadNewMesh( fileName );
gUICmbRenderMode->setSelectedByData( (const void*)RM_CHECKER );
}
}
break;
case GID_BTN_OPENNMAP:
{
std::string fileName = gGetOpenFileName( FILE_FILTER_TEX );
if( !fileName.empty() ) {
gLoadNormapMap( fileName );
gUICmbRenderMode->setSelectedByData( (const void*)RM_NORMALMAP );
}
}
break;
case GID_BTN_OPENDIFFTEX:
{
std::string fileName = gGetOpenFileName( FILE_FILTER_TEX );
if( !fileName.empty() ) {
gLoadDiffuseTex( fileName );
gUICmbRenderMode->setSelectedByData( (const void*)RM_MAPPED );
}
}
break;
case GID_BTN_BAKE:
{
gBakeTexture(
(int)gUICmbBakeSizeX->getSelectedData(),
(int)gUICmbBakeSizeY->getSelectedData(),
(D3DXIMAGE_FILEFORMAT)(DWORD)gUICmbBakeFormat->getSelectedData()
);
gUICmbRenderMode->setSelectedByData( (const void*)RM_BAKED );
}
break;
};
}
}
const int UIHCTL = 16;
const int UIHLAB = 14;
static void gSetupGUI()
{
int i;
int ctlY = 5 - UIHCTL;
int BTNW = 110;
gUIDlg->addButton( GID_BTN_OPENMESH, "Open Mesh (M)", 3, ctlY += UIHCTL, BTNW, UIHCTL, 'M', false, &gUIBtnOpenMesh );
gUIDlg->addStatic( 0, "", 5+BTNW, ctlY, 300, UIHCTL, false, &gUILabMesh );
gUIDlg->addButton( GID_BTN_OPENNMAP, "Open NMap (N)", 3, ctlY += UIHCTL, BTNW, UIHCTL, 'N', false, &gUIBtnOpenNMap );
gUIDlg->addStatic( 0, "", 5+BTNW, ctlY, 300, UIHCTL, false, &gUILabNMap );
gUIBtnOpenNMap->setEnabled( false );
gUIDlg->addButton( GID_BTN_OPENDIFFTEX, "Open DiffTex (T)", 3, ctlY += UIHCTL, BTNW, UIHCTL, 'T', false, &gUIBtnOpenDiffTex );
gUIDlg->addStatic( 0, "", 5+BTNW, ctlY, 300, UIHCTL, false, &gUILabDiffTex );
gUIBtnOpenDiffTex->setEnabled( false );
gUIDlg->addComboBox( GID_CMB_RENDERMODE, 3, ctlY += UIHCTL*2, BTNW, UIHCTL, 0, false, &gUICmbRenderMode );
for( i = 0; i < RMCOUNT-1; ++i ) { // last is texture baker - not user selectable
gUICmbRenderMode->addItem( RMODE_FX[i], (const void*)i, true );
}
gUIDlg->addCheckBox( GID_CHK_WIREFRAME, "Wireframe (W)", 3, ctlY += UIHCTL, BTNW, UIHCTL, false, 'W', false, &gUIChkWireframe );
ctlY += 2*UIHCTL;
gUIDlg->addButton( GID_BTN_BAKE, "Bake (B)", 3, ctlY, 60, UIHCTL, 'B', false, &gUIBtnBake );
gUIBtnBake->setEnabled( false );
gUIDlg->addComboBox( GID_CMB_BAKESIZEX, 65, ctlY, 44, UIHCTL, 0, false, &gUICmbBakeSizeX );
gUIDlg->addComboBox( GID_CMB_BAKESIZEY, 110, ctlY, 44, UIHCTL, 0, false, &gUICmbBakeSizeY );
gUIDlg->addComboBox( GID_CMB_BAKEAA, 3, ctlY+=UIHCTL, 60, UIHCTL, 0, false, &gUICmbBakeAA );
gUIDlg->addComboBox( GID_CMB_BAKEFORMAT, 65, ctlY, 89, UIHCTL, 0, false, &gUICmbBakeFormat );
const int BAKE_SIZES[] = { 128, 256, 512, 1024, 2048 };
for( i = 0; i < sizeof(BAKE_SIZES)/sizeof(BAKE_SIZES[0]); ++i ) {
char buf[100];
itoa( BAKE_SIZES[i], buf, 10 );
gUICmbBakeSizeX->addItem( buf, (const void*)BAKE_SIZES[i], true );
gUICmbBakeSizeY->addItem( buf, (const void*)BAKE_SIZES[i], true );
}
// make 1024x1024 bake size the default
gUICmbBakeSizeX->setSelectedByIndex( 3 );
gUICmbBakeSizeY->setSelectedByIndex( 3 );
gUICmbBakeSizeX->setEnabled( false );
gUICmbBakeSizeY->setEnabled( false );
const int BAKE_AAS[] = { 1, 2, 4 };
for( i = 0; i < sizeof(BAKE_AAS)/sizeof(BAKE_AAS[0]); ++i ) {
char buf[100];
sprintf( buf, "%ixAA", BAKE_AAS[i] );
gUICmbBakeAA->addItem( buf, (const void*)BAKE_AAS[i], true );
}
// make 2xAA selected by default
gUICmbBakeAA->setSelectedByIndex( 1 );
gUICmbBakeAA->setEnabled( false );
const int BAKE_FMTS[] = { D3DXIFF_DDS, D3DXIFF_PNG };
const char* BAKE_FMTTEXTS[] = { "DDS", "PNG" };
for( i = 0; i < sizeof(BAKE_FMTS)/sizeof(BAKE_FMTS[0]); ++i ) {
gUICmbBakeFormat->addItem( BAKE_FMTTEXTS[i], (const void*)BAKE_FMTS[i], true );
}
// make DDS selected by default
gUICmbBakeFormat->setSelectedByIndex( 0 );
const int SLD_X = 400;
ctlY = 5 - UIHCTL;
gUIDlg->addStatic( 0, "Tex scale", SLD_X, ctlY += UIHCTL, 50, UIHCTL, false, NULL );
gUIDlg->addSlider( 0, SLD_X+50, ctlY, 140, UIHCTL, 1, 70, 10, false, &gUISldScale );
gUIDlg->addStatic( 0, "", SLD_X+200, ctlY, 50, UIHCTL, false, &gUILabScale );
gUIDlg->enableNonUserEvents( true );
}
void CDemo::initialize( IDingusAppContext& appContext )
{
CONS << "Initializing..." << endl;
gAppContext = &appContext;
CSharedTextureBundle& stb = CSharedTextureBundle::getInstance();
CSharedSurfaceBundle& ssb = CSharedSurfaceBundle::getInstance();
CD3DDevice& dx = CD3DDevice::getInstance();
CONS << "Video memory seems to be: " << dx.getCaps().getVideoMemoryMB() << endl;
G_INPUTCTX->addListener( *this );
// --------------------------------
// shared resources
CIndexBufferBundle::getInstance().registerIB( RID_IB_QUADS, 8000*6, D3DFMT_INDEX16, *(new CIBFillerQuads()) );
// --------------------------------
// common params
//G_RENDERCTX->getGlobalParams().addFloatRef( "fTime", &gTimeParam );
G_RENDERCTX->getGlobalParams().addIntRef( "iFill", &gGlobalFillMode );
G_RENDERCTX->getGlobalParams().addFloatRef( "fTexerScale", &gTexerScale );
// --------------------------------
// game
// GUI
gUIDlg = new CUIDialog();
//gUIDlg->enableKeyboardInput( true );
gUIDlg->setCallback( gUICallback );
gUIDlg->setFont( 1, "Arial", 22, 50 );
gSetupGUI();
CONS << "Starting..." << endl;
}
// --------------------------------------------------------------------------
// Perform code (main loop)
bool CDemo::msgProc( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam )
{
if( !gUIDlg )
return false;
bool done = false;
done = gUIDlg->msgProc( hwnd, msg, wparam, lparam );
if( done )
return true;
// track mouse...
if( msg == WM_LBUTTONDOWN ) {
//CEntityManager& entities = CGameInfo::getInstance().getEntities();
//if( &entities ) {
// entities.onMouseClick();
//}
}
if( msg == WM_MOUSEMOVE ) {
CD3DDevice& dx = CD3DDevice::getInstance();
gMouseX = (float(LOWORD(lparam)) / dx.getBackBufferWidth()) * 2 - 1;
gMouseY = (float(HIWORD(lparam)) / dx.getBackBufferHeight()) * 2 - 1;
}
return false;
}
const float TIME_SPD_NORMAL = 1.5f; // 1.5f
const float TIME_SPD_FAST = 10.0f;
void CDemo::onInputEvent( const CInputEvent& event )
{
float dt = CSystemTimer::getInstance().getDeltaTimeS();
float dmove = 4.0f * dt;
float dturn = 2.0f * dt;
if( event.getType() == CKeyEvent::EVENT_TYPE ) {
const CKeyEvent& ke = (const CKeyEvent&)event;
SMatrix4x4 mr;
switch( ke.getKeyCode() ) {
case DIK_9:
if( ke.getMode() == CKeyEvent::KEY_PRESSED )
gShowStats = !gShowStats;
break;
case DIK_LEFT:
gCameraYaw -= dturn;
break;
case DIK_RIGHT:
gCameraYaw += dturn;
break;
case DIK_UP:
gCameraPitch += dturn;
gCameraPitch = clamp( gCameraPitch, -D3DX_PI/2, D3DX_PI/2 );
break;
case DIK_DOWN:
gCameraPitch -= dturn;
gCameraPitch = clamp( gCameraPitch, -D3DX_PI/2, D3DX_PI/2 );
break;
case DIK_A:
gCameraDist -= dmove;
gCameraDist = clamp( gCameraDist, gMeshRadius*0.5f, gMeshRadius*4 );
break;
case DIK_Z:
gCameraDist += dmove;
gCameraDist = clamp( gCameraDist, gMeshRadius*0.5f, gMeshRadius*4 );
break;
}
}
}
void CDemo::onInputStage()
{
}
// --------------------------------------------------------------------------
const char* gGetFileNamePart( const std::string& name )
{
int nameStartIdx = name.find_last_of( "/\\", name.size()-1 );
const char* s = name.c_str();
if( nameStartIdx >= 0 )
s += nameStartIdx+1;
return s;
}
/**
* Main loop code.
*/
void CDemo::perform()
{
char buf[200];
double t = CSystemTimer::getInstance().getTimeS();
float dt = CSystemTimer::getInstance().getDeltaTimeS();
//gTimeParam = float(t);
CDynamicVBManager::getInstance().discard();
CD3DDevice& dx = CD3DDevice::getInstance();
gScreenFixUVs.set( 0.5f/dx.getBackBufferWidth(), 0.5f/dx.getBackBufferHeight(), 0.0f, 0.0f );
G_INPUTCTX->perform();
D3DXMatrixRotationYawPitchRoll( &gCamera.mWorldMat, gCameraYaw, gCameraPitch, 0.0f );
gCamera.mWorldMat.getOrigin() -= gCamera.mWorldMat.getAxisZ() * gCameraDist;
gCamera.setProjectionParams( D3DX_PI/3, dx.getBackBufferAspect(), gCameraDist * 0.3f, gCameraDist*10.0f );
gCamera.setOntoRenderContext();
//
// update UI
gMouseRay = gCamera.getWorldRay( gMouseX, gMouseY );
const SVector3& eyePos = gCamera.mWorldMat.getOrigin();
//SLine3 mouseRay;
//mouseRay.pos = eyePos;
//mouseRay.vec = gMouseRay;
// wireframe?
gGlobalFillMode = gUIChkWireframe->isChecked() ? D3DFILL_WIREFRAME : D3DFILL_SOLID;
// loaded mesh and textures
if( gMesh ) {
sprintf( buf, "%s, %i verts, %i tris", gGetFileNamePart(gCurMeshName), gMesh->getMesh().getVertexCount(), gMesh->getMesh().getIndexCount()/3 );
gUILabMesh->setText( buf );
}
if( !gCurNormalMapName.empty() ) {
gUILabNMap->setText( gGetFileNamePart(gCurNormalMapName) );
}
if( !gCurDiffTexName.empty() ) {
gUILabDiffTex->setText( gGetFileNamePart(gCurDiffTexName) );
}
// scales
gTexerScale = gUISldScale->getValue() * 0.1f;
sprintf( buf, "%.1f", gTexerScale );
gUILabScale->setText( buf );
dx.clearTargets( true, true, false, 0xFF8080a0, 1.0f, 0L );
dx.sceneBegin();
G_RENDERCTX->applyGlobalEffect();
// render mesh if we have it
if( gMesh )
gMesh->render( eRenderMode( (int)gUICmbRenderMode->getSelectedData() ) );
G_RENDERCTX->perform();
// render GUI
gUIDlg->onRender( dt );
dx.sceneEnd();
// sleep a bit in order not to burn everything :)
Sleep( 1 );
}
// --------------------------------------------------------------------------
// Cleanup
void CDemo::shutdown()
{
CONS << "Shutting down..." << endl;
if( gMesh )
delete gMesh;
safeDelete( gUIDlg );
CONS << "Done!" << endl;
}
| [
"[email protected]"
] | [
[
[
1,
709
]
]
] |
ea1205806f12cc9c2b82449820d0a6628faf51ea | d425cf21f2066a0cce2d6e804bf3efbf6dd00c00 | /Strategic/Campaign Init.cpp | b7a7767c6f644cc48b63d340c3c88064661847b4 | [] | 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 | 19,363 | cpp | #ifdef PRECOMPILEDHEADERS
#include "Strategic All.h"
#include "XML.h"
#else
#include "types.h"
#include "Campaign Init.h"
#include "Random.h"
#include "Campaign Types.h"
#include "Queen Command.h"
#include "overhead.h"
#include "Strategic Movement.h"
#include "Strategic Status.h"
#include "GameSettings.h"
#include "Creature Spreading.h"
#include "Strategic AI.h"
#include "XML.h"
#include "expat.h"
#include "Debug Control.h"
#include "Tactical Save.h"
#endif
#include "connect.h"
#include <vfs/Core/vfs.h>
#include "XMLWriter.h"
#include "UndergroundInit.h"
extern BOOLEAN InitStrategicMovementCosts();
void InitKnowFacilitiesFlags( );
UNDERGROUND_SECTORINFO* gpUndergroundSectorInfoTail = NULL;
// Lesh: this array controls randomization of sectors
// Note that some sectors in game already using alternative map
// It is Skyrider quest: B15, E14, D12, C16
// weapon caches: E11, H5, H10, J12, M9
// Madlab quest: H7, H16, I11, E4
// Do not enable randomization of this sectors until you are know what you're doing
BOOLEAN RandomSector[256] =
{
// 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* A */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* B */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* C */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* D */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* E */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* G */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* H */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* I */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* J */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* K */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* L */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* M */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* N */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* O */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* P */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
typedef enum
{
ALTSECTORS_ELEMENT_NONE = 0,
ALTSECTORS_ELEMENT_LIST,
ALTSECTORS_ELEMENT_ROW,
} ALTSECTORS_PARSE_STAGE;
typedef struct
{
ALTSECTORS_PARSE_STAGE curElement;
CHAR8 szCharData[MAX_CHAR_DATA_LENGTH+1];
UINT32 uiRowNumber;
UINT32 currentDepth;
UINT32 maxReadDepth;
} altSectorsParseData;
static void XMLCALL
altSectorsStartElementHandle(void *userData, const XML_Char *name, const XML_Char **atts)
{
altSectorsParseData * pData = (altSectorsParseData *) userData;
if(pData->currentDepth <= pData->maxReadDepth) //are we reading this element?
{
if(strcmp(name, "ALT_SECTORS_LIST") == 0 && pData->curElement == ALTSECTORS_ELEMENT_NONE)
{
pData->curElement = ALTSECTORS_ELEMENT_LIST;
pData->maxReadDepth++; //we are not skipping this element
}
else if(strcmp(name, "ROW") == 0 && pData->curElement == ALTSECTORS_ELEMENT_LIST)
{
pData->curElement = ALTSECTORS_ELEMENT_ROW;
if(strcmp(atts[0], "y") == 0)
{
if ( isalpha(atts[1][0]) )
pData->uiRowNumber = (UINT32)(atts[1][0] - 0x40);
else
pData->uiRowNumber = atol(atts[1]);
}
pData->maxReadDepth++; //we are not skipping this element
}
pData->szCharData[0] = '\0';
}
pData->currentDepth++;
}
static void XMLCALL
altSectorsCharacterDataHandle(void *userData, const XML_Char *str, int len)
{
altSectorsParseData * pData = (altSectorsParseData *) userData;
if(pData->currentDepth <= pData->maxReadDepth && strlen(pData->szCharData) < MAX_CHAR_DATA_LENGTH)
strncat(pData->szCharData,str,__min((unsigned int)len,MAX_CHAR_DATA_LENGTH-strlen(pData->szCharData)));
}
static void XMLCALL
altSectorsEndElementHandle(void *userData, const XML_Char *name)
{
altSectorsParseData * pData = (altSectorsParseData *) userData;
if(pData->currentDepth <= pData->maxReadDepth) //we're at the end of an element that we've been reading
{
if(strcmp(name, "ALT_SECTORS_LIST") == 0 && pData->curElement == ALTSECTORS_ELEMENT_LIST)
{
pData->curElement = ALTSECTORS_ELEMENT_NONE;
}
else if(strcmp(name, "ROW") == 0 && pData->curElement == ALTSECTORS_ELEMENT_ROW)
{
STR8 curBuffer = pData->szCharData + strspn(pData->szCharData," \t\n\r");
UINT32 curCellIndex = 0;
UINT32 curNumber;
pData->curElement = ALTSECTORS_ELEMENT_LIST;
while(curBuffer[0] != '\0')
{
sscanf( curBuffer,"%d",&curNumber);
RandomSector[curCellIndex+16*(pData->uiRowNumber - 1)] = curNumber;
curCellIndex++;
curBuffer += strcspn(curBuffer," \t\n\r\0");
curBuffer += strspn(curBuffer," \t\n\r");
}
}
pData->maxReadDepth--;
}
pData->currentDepth--;
}
BOOLEAN ReadInAltSectors(STR fileName)
{
HWFILE hFile;
UINT32 uiBytesRead;
UINT32 uiFSize;
CHAR8 * lpcBuffer;
XML_Parser parser = XML_ParserCreate(NULL);
altSectorsParseData pData;
// Open xml file
hFile = FileOpen( fileName, FILE_ACCESS_READ, FALSE );
if ( !hFile )
return( FALSE );
uiFSize = FileGetSize(hFile);
lpcBuffer = (CHAR8 *) MemAlloc(uiFSize+1);
//Read in block
if ( !FileRead( hFile, lpcBuffer, uiFSize, &uiBytesRead ) )
{
MemFree(lpcBuffer);
return( FALSE );
}
lpcBuffer[uiFSize] = 0; //add a null terminator
FileClose( hFile );
XML_SetElementHandler(parser, altSectorsStartElementHandle, altSectorsEndElementHandle);
XML_SetCharacterDataHandler(parser, altSectorsCharacterDataHandle);
memset(&pData,0,sizeof(pData));
XML_SetUserData(parser, &pData);
if(!XML_Parse(parser, lpcBuffer, uiFSize, TRUE))
{
CHAR8 errorBuf[511];
sprintf(errorBuf, "XML Parser Error in AltSectors.xml: %s at line %d", XML_ErrorString(XML_GetErrorCode(parser)), XML_GetCurrentLineNumber(parser));
LiveMessage(errorBuf);
MemFree(lpcBuffer);
return FALSE;
}
MemFree(lpcBuffer);
XML_ParserFree(parser);
return( TRUE );
}
BOOLEAN WriteInAltSectors(STR fileName)
{
#ifndef USE_VFS
// Lets output the current Strategic map format using the XML structure I've devised.
FILE *outfile = fopen(fileName, "wt");
UINT32 x, y;
fprintf (outfile, "<ALT_SECTORS_LIST>\n");
for(y = 1;y <= 16;y++)
{
fprintf (outfile, "\t<ROW y=\"%c\">",(y+0x40));
for(x = 1;x <= 16; x++)
{
fprintf (outfile, " %d",RandomSector[ ((y - 1) * 16) + (x - 1) ] );
}
fprintf (outfile, " </ROW>\n");
}
fprintf (outfile, "</ALT_SECTORS_LIST>\n");
fclose(outfile);
#else
XMLWriter xmlw;
xmlw.openNode(L"ALT_SECTORS_LIST");
UINT32 x, y;
for(y = 1;y <= 16;y++)
{
xmlw.addAttributeToNextValue(L"y",(char)(y+0x40));
std::stringstream ss;
for(x = 1;x <= 16; x++)
{
ss << " " << RandomSector[ ((y - 1) * 16) + (x - 1) ];
}
xmlw.addValue(L"ROW", ss.str());
}
xmlw.closeNode();
xmlw.writeToFile(fileName);
#endif
return (TRUE);
}
UNDERGROUND_SECTORINFO* NewUndergroundNode( UINT8 ubSectorX, UINT8 ubSectorY, UINT8 ubSectorZ )
{
UNDERGROUND_SECTORINFO *curr;
curr = (UNDERGROUND_SECTORINFO*)MemAlloc( sizeof( UNDERGROUND_SECTORINFO ) );
AssertMsg( curr, "Failed to create an underground sector info node." );
memset( curr, 0, sizeof( UNDERGROUND_SECTORINFO ) );
curr->ubSectorX = ubSectorX;
curr->ubSectorY = ubSectorY;
curr->ubSectorZ = ubSectorZ;
if( gpUndergroundSectorInfoTail )
{
gpUndergroundSectorInfoTail->next = curr;
gpUndergroundSectorInfoTail = gpUndergroundSectorInfoTail->next;
}
else
{
gpUndergroundSectorInfoHead = curr;
gpUndergroundSectorInfoTail = gpUndergroundSectorInfoHead;
}
return curr;
}
// setup which know facilities are in which cities
void InitKnowFacilitiesFlags( )
{
/////////////////////////////////////////////////////////////////
// HEADROCK HAM 3.5: No longer required. Function disconnected.
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//SECTORINFO *pSector;
// HEADROCK HAM 3.4: Externalized. All "known" facilities are read from gFacilityLocations. The
// ones that have (fHidden=0) will be added to the sector info now, and thus visible immediately.
// The others are added only once the player visits those sectors.
/*for(UINT32 cnt=0; (gFacilityLocations[cnt].uiSectorID >= 0 && gFacilityLocations[cnt].uiSectorID <= 256); cnt++ )
{
// Is the current sector valid? Is the facility set to be revealed on game-start?
if (gFacilityLocations[cnt].uiSectorID > 0 && gFacilityLocations[cnt].uiSectorID < 257 &&
gFacilityLocations[cnt].fHidden == 0)
{
// Reveal the facility.
pSector = &SectorInfo[gFacilityLocations[cnt].uiSectorID];
pSector->uiFacilitiesFlags |= (1 << (gFacilityLocations[cnt].uiFacilityType-1));
}
}*/
/* HEADROCK HAM 3.4: Externalized.
// Cambria hospital
pSector = &SectorInfo[SEC_G8];
pSector->uiFacilitiesFlags |= SFCF_HOSPITAL;
pSector = &SectorInfo[SEC_F8];
pSector->uiFacilitiesFlags |= SFCF_HOSPITAL;
pSector = &SectorInfo[SEC_G9];
pSector->uiFacilitiesFlags |= SFCF_HOSPITAL;
pSector = &SectorInfo[SEC_F9];
pSector->uiFacilitiesFlags |= SFCF_HOSPITAL;
// Drassen airport
pSector = &SectorInfo[SEC_B13];
pSector->uiFacilitiesFlags |= SFCF_AIRPORT;
pSector = &SectorInfo[SEC_C13];
pSector->uiFacilitiesFlags |= SFCF_AIRPORT;
pSector = &SectorInfo[SEC_D13];
pSector->uiFacilitiesFlags |= SFCF_AIRPORT;
// Meduna airport & military complex
pSector = &SectorInfo[SEC_N3];
pSector->uiFacilitiesFlags |= SFCF_AIRPORT;
pSector = &SectorInfo[SEC_N4];
pSector->uiFacilitiesFlags |= SFCF_AIRPORT;
pSector = &SectorInfo[SEC_N5];
pSector->uiFacilitiesFlags |= SFCF_AIRPORT;
pSector = &SectorInfo[SEC_O3];
pSector->uiFacilitiesFlags |= SFCF_AIRPORT;
pSector = &SectorInfo[SEC_O4];
pSector->uiFacilitiesFlags |= SFCF_AIRPORT;
*/
return;
}
void InitMiningLocations()
{
SECTORINFO *pSector;
//Set up mining sites
pSector = &SectorInfo[SEC_D4];
pSector->uiFlags |= SF_MINING_SITE;
// pSector->ubIncomeValue = 33;
pSector = &SectorInfo[SEC_D13];
pSector->uiFlags |= SF_MINING_SITE;
// pSector->ubIncomeValue = 41;
pSector = &SectorInfo[SEC_B2];
pSector->uiFlags |= SF_MINING_SITE;
// pSector->ubIncomeValue = 20;
pSector = &SectorInfo[SEC_H8];
pSector->uiFlags |= SF_MINING_SITE;
// pSector->ubIncomeValue = 64;
pSector = &SectorInfo[SEC_I14];
pSector->uiFlags |= SF_MINING_SITE;
// pSector->ubIncomeValue = 80;
//Grumm
pSector = &SectorInfo[SEC_H3];
pSector->uiFlags |= SF_MINING_SITE;
// pSector->ubIncomeValue = 100;
}
//Mobile groups are handled separately from sectors, because they are on the move.
void GeneratePatrolGroups()
{
GROUP *pGroup;
UINT8 ubNumTroops;
ubNumTroops = (UINT8)(3 + gGameOptions.ubDifficultyLevel + Random( 3 ));
pGroup = CreateNewEnemyGroupDepartingFromSector( SEC_C7, 0, ubNumTroops, 0 );
pGroup->ubTransportationMask = CAR;
AddWaypointToPGroup( pGroup, 8, 3 ); //C8
AddWaypointToPGroup( pGroup, 7, 3 ); //C7
ubNumTroops = (UINT8)(3 + gGameOptions.ubDifficultyLevel + Random( 3 ));
pGroup = CreateNewEnemyGroupDepartingFromSector( SEC_D9, 0, ubNumTroops, 0 );
AddWaypointToPGroup( pGroup, 9, 5 ); //E9
AddWaypointToPGroup( pGroup, 9, 4 ); //D9
pGroup->ubTransportationMask = TRUCK;
ubNumTroops = (UINT8)(3 + gGameOptions.ubDifficultyLevel + Random( 3 ));
pGroup = CreateNewEnemyGroupDepartingFromSector( SEC_B9, 0, ubNumTroops, 0 );
AddWaypointToPGroup( pGroup, 12, 2 ); //B12
AddWaypointToPGroup( pGroup, 9, 2 ); //B9
pGroup->ubTransportationMask = FOOT;
ubNumTroops = (UINT8)(3 + gGameOptions.ubDifficultyLevel + Random( 3 ));
pGroup = CreateNewEnemyGroupDepartingFromSector( SEC_A14, 0, ubNumTroops, 0 );
pGroup->ubMoveType = ENDTOEND_FORWARDS;
AddWaypointToPGroup( pGroup, 13, 1 ); //A13
AddWaypointToPGroup( pGroup, 15, 1 ); //A15
AddWaypointToPGroup( pGroup, 15, 5 ); //E15
AddWaypointToPGroup( pGroup, 13, 5 ); //E13
AddWaypointToPGroup( pGroup, 12, 5 ); //E12
AddWaypointToPGroup( pGroup, 12, 3 ); //C12
pGroup->ubTransportationMask = TRACKED;
ubNumTroops = (UINT8)(5 + gGameOptions.ubDifficultyLevel * 2 + Random( 4 ));
pGroup = CreateNewEnemyGroupDepartingFromSector( SEC_N6, 0, ubNumTroops, 0 );
AddWaypointToPGroup( pGroup, 9, 14 ); //N9
AddWaypointToPGroup( pGroup, 6, 14 ); //N6
pGroup->ubTransportationMask = CAR;
ubNumTroops = (UINT8)(5 + gGameOptions.ubDifficultyLevel * 2 + Random( 4 ));
pGroup = CreateNewEnemyGroupDepartingFromSector( SEC_N10, 0, ubNumTroops, 0 );
AddWaypointToPGroup( pGroup, 10, 11 ); //K10
AddWaypointToPGroup( pGroup, 10, 14 ); //N10
pGroup->ubTransportationMask = CAR;
}
void TrashUndergroundSectorInfo()
{
UNDERGROUND_SECTORINFO *curr;
while( gpUndergroundSectorInfoHead )
{
curr = gpUndergroundSectorInfoHead;
gpUndergroundSectorInfoHead = gpUndergroundSectorInfoHead->next;
MemFree( curr );
}
gpUndergroundSectorInfoHead = NULL;
gpUndergroundSectorInfoTail = NULL;
}
//Defines the sectors that can be occupied by enemies, creatures, etc. It also
//contains the network of cave connections critical for strategic creature spreading, as we can't
//know how the levels connect without loading the maps. This is completely hardcoded, and any
//changes to the maps, require changes accordingly.
void BuildUndergroundSectorInfoList()
{
UNDERGROUND_SECTORINFO *curr;
SECTORINFO *pSector = NULL;
TrashUndergroundSectorInfo();
//if (LetLuaBuildUndergroundSectorInfoList())
g_luaUnderground.InitializeSectorList();
// lua script succeeded
return;
// If lua script had any errors
// reset whatever the script may have done
// and use hardcoded underground initialization.
TrashUndergroundSectorInfo();
//********************
//* BASEMENT LEVEL 1 *
//********************
//Miguel's basement. Nothing here.
curr = NewUndergroundNode( 10, 1, 1 );
//Chitzena mine. Nothing here.
curr = NewUndergroundNode( 2, 2, 1 );
//San mona mine. Nothing here.
curr = NewUndergroundNode( 4, 4, 1 );
curr = NewUndergroundNode( 5, 4, 1 );
//J9
curr = NewUndergroundNode( 9, 10, 1 );
switch( gGameOptions.ubDifficultyLevel )
{
case DIF_LEVEL_EASY:
curr->ubNumTroops = 8;
break;
case DIF_LEVEL_MEDIUM:
curr->ubNumTroops = 11;
break;
case DIF_LEVEL_HARD:
curr->ubNumTroops = 15;
break;
case DIF_LEVEL_INSANE:
curr->ubNumTroops = 20;
break;
}
//J9 feeding zone
curr = NewUndergroundNode( 9, 10, 2 );
curr->ubNumCreatures = (UINT8)(2 + gGameOptions.ubDifficultyLevel*2 + Random( 2 ));
//K4
curr = NewUndergroundNode( 4, 11, 1 );
curr->ubNumTroops = (UINT8)(6 + gGameOptions.ubDifficultyLevel*2 + Random( 3 ));
curr->ubNumElites = (UINT8)(4 + gGameOptions.ubDifficultyLevel + Random( 2 ));
//O3
curr = NewUndergroundNode( 3, 15, 1 );
curr->ubNumTroops = (UINT8)(6 + gGameOptions.ubDifficultyLevel*2 + Random( 3 ));
curr->ubNumElites = (UINT8)(4 + gGameOptions.ubDifficultyLevel + Random( 2 ));
//P3
curr = NewUndergroundNode( 3, 16, 1 );
switch( gGameOptions.ubDifficultyLevel )
{
case DIF_LEVEL_EASY:
curr->ubNumElites = (UINT8)(8 + Random( 3 ));
break;
case DIF_LEVEL_MEDIUM:
curr->ubNumElites = (UINT8)(10 + Random( 5 ));
break;
case DIF_LEVEL_HARD:
curr->ubNumElites = (UINT8)(14 + Random( 6 ));
break;
case DIF_LEVEL_INSANE:
curr->ubNumElites = 20;
break;
}
//Do all of the mandatory underground mine sectors
//Drassen's mine
//D13_B1
curr = NewUndergroundNode( 13, 4, 1 );
//E13_B1
curr = NewUndergroundNode( 13, 5, 1 );
//E13_B2
curr = NewUndergroundNode( 13, 5, 2 );
//F13_B2
curr = NewUndergroundNode( 13, 6, 2 );
//G13_B2
curr = NewUndergroundNode( 13, 7, 2 );
//G13_B3
curr = NewUndergroundNode( 13, 7, 3 );
//F13_B3
curr = NewUndergroundNode( 13, 6, 3 );
//Cambria's mine
//H8_B1
curr = NewUndergroundNode( 8, 8, 1 );
//H9_B1
curr = NewUndergroundNode( 9, 8, 1 );
//H9_B2
curr = NewUndergroundNode( 9, 8, 2 );
//H8_B2
curr = NewUndergroundNode( 8, 8, 2 );
//H8_B3
curr = NewUndergroundNode( 8, 8, 3 );
//I8_B3
curr = NewUndergroundNode( 8, 9, 3 );
//J8_B3
curr = NewUndergroundNode( 8, 10, 3 );
//Alma's mine
//I14_B1
curr = NewUndergroundNode( 14, 9, 1 );
//J14_B1
curr = NewUndergroundNode( 14, 10, 1 );
//J14_B2
curr = NewUndergroundNode( 14, 10, 2 );
//J13_B2
curr = NewUndergroundNode( 13, 10, 2 );
//J13_B3
curr = NewUndergroundNode( 13, 10, 3 );
//K13_B3
curr = NewUndergroundNode( 13, 11, 3 );
//Grumm's mine
//H3_B1
curr = NewUndergroundNode( 3, 8, 1 );
//I3_B1
curr = NewUndergroundNode( 3, 9, 1 );
//I3_B2
curr = NewUndergroundNode( 3, 9, 2 );
//H3_B2
curr = NewUndergroundNode( 3, 8, 2 );
//H4_B2
curr = NewUndergroundNode( 4, 8, 2 );
curr->uiFlags |= SF_PENDING_ALTERNATE_MAP;
//H4_B3
curr = NewUndergroundNode( 4, 8, 3 );
//G4_B3
curr = NewUndergroundNode( 4, 7, 3 );
}
// Lesh: this function creates randomized world
// every sector can be randomized between common and alternative, chances 50/50
// randomization of individual sectors can be switched off via array RandomSector[]
void InitWorld()
{
INT16 sSectorCounter;
for (sSectorCounter = 0; sSectorCounter < 256; sSectorCounter++)
{
// WANNE - MP: Disable "random sectors" in a multiplayer game
if (!is_networked)
{
if ( RandomSector[ sSectorCounter ] )
{
if ( Random(100) >= 50 )
SectorInfo[ sSectorCounter ].uiFlags |= SF_USE_ALTERNATE_MAP;
}
}
}
}
//This is the function that is called only once, when the player begins a new game. This will calculate
//starting numbers of the queen's army in various parts of the map, which will vary from campaign to campaign.
//This is also highly effected by the game's difficulty setting.
void InitNewCampaign()
{
DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"InitNewCampaign");
//First clear all the sector information of all enemy existance. Conveniently, the
//ubGroupType is also cleared, which is perceived to be an empty group.
//memset( &SectorInfo, 0, sizeof( SECTORINFO ) * 256 );
for (std::vector<SECTORINFO>::iterator secIter = SectorInfo.begin(); secIter != SectorInfo.end(); ++secIter) {
memset( &(*secIter), 0, sizeof( SECTORINFO ) );
}
InitStrategicMovementCosts();
RemoveAllGroups();
InitWorld(); // Lesh: generate different world each time using alternative maps
InitMiningLocations();
// HEADROCK HAM 3.5: This is no longer required.
//InitKnowFacilitiesFlags( );
BuildUndergroundSectorInfoList();
#ifdef JA2UB
// no UB
#else
if (!is_networked)
// allow overhead view of omerta A9 on game onset
// HEADROCK HAM 3.5: Externalized.
SetSectorFlag( gGameExternalOptions.ubDefaultArrivalSectorX, gGameExternalOptions.ubDefaultArrivalSectorY, startingZ, SF_ALREADY_VISITED ); //hayden
#endif
//Generates the initial forces in a new campaign. The idea is to randomize numbers and sectors
//so that no two games are the same.
InitStrategicAI();
InitStrategicStatus();
DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"InitNewCampaign done");
}
| [
"jazz_ja@b41f55df-6250-4c49-8e33-4aa727ad62a1"
] | [
[
[
1,
661
]
]
] |
358dd5605767c158f603d34ff66c6e4cec5a9bd0 | 5ed707de9f3de6044543886ea91bde39879bfae6 | /ASFootball/ASFIsOrb/Source/ASFootballLineupUpdateRqst.h | f36cc4b4090b4b3c63a49af5e2fc8f5e2a66b44a | [] | no_license | grtvd/asifantasysports | 9e472632bedeec0f2d734aa798b7ff00148e7f19 | 76df32c77c76a76078152c77e582faa097f127a8 | refs/heads/master | 2020-03-19T02:25:23.901618 | 1999-12-31T16:00:00 | 2018-05-31T19:48:19 | 135,627,290 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,042 | h | /* ASFootballLineupUpdateRqst.h */
/******************************************************************************/
/******************************************************************************/
#ifndef ASFootballLineupUpdateRqstH
#define ASFootballLineupUpdateRqstH
#include "ASFantasyLineupUpdateRqst.h"
#include "ASFootballMiscRqst.h"
using namespace asfantasy;
namespace asfootball
{
/******************************************************************************/
class ASFootballLineupUpdateRqst : public LineupUpdateRqst
{
protected:
virtual bool areChangesAllowed(TLeagueID leagueID)
{ return(!IsLockoutPeriodInEffect(leagueID)); }
virtual void saveLineups(TTeamPtr teamPtr);
};
/******************************************************************************/
}; //namespace asfootball
#endif //ASFootballLineupUpdateRqstH
/******************************************************************************/
/******************************************************************************/
| [
"[email protected]"
] | [
[
[
1,
33
]
]
] |
8dc4c69236b0336949704320870b0bfb8c8f2e04 | 2d4221efb0beb3d28118d065261791d431f4518a | /OIDE源代码/OLIDE/Controls/TreePropSheet/PropPageFrameOffice2003.cpp | a9bb6e0ecfefe2c71a03493db843885e1e1ce91f | [] | no_license | ophyos/olanguage | 3ea9304da44f54110297a5abe31b051a13330db3 | 38d89352e48c2e687fd9410ffc59636f2431f006 | refs/heads/master | 2021-01-10T05:54:10.604301 | 2010-03-23T11:38:51 | 2010-03-23T11:38:51 | 48,682,489 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,370 | cpp | // PropPageFrameOffice2003.cpp: implementation of the CPropPageFrameOffice2003 class.
//
//////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2004 by Yves Tkaczyk
// (http://www.tkaczyk.net - [email protected])
//
// The contents of this file are subject to the Artistic License (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
// http://www.opensource.org/licenses/artistic-license.html
//
// Documentation: http://www.codeproject.com/property/treepropsheetex.asp
// CVS tree: http://sourceforge.net/projects/treepropsheetex
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "PropPageFrameOffice2003.h"
#include "ThemeLibEx.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
// Define constants that are in the Platform SDK, but not in the default VC6
// installation.
// Thank to Don M for suggestion
// (http://www.codeproject.com/property/TreePropSheetEx.asp?msg=939854#xx939854xx)
#ifndef COLOR_GRADIENTACTIVECAPTION
#define COLOR_GRADIENTACTIVECAPTION 27
#endif
#ifndef COLOR_GRADIENTINACTIVECAPTION
#define COLOR_GRADIENTINACTIVECAPTION 28
#endif
#ifndef WP_FRAMELEFT
#define WP_FRAMELEFT 7
#endif
#ifndef FS_ACTIVE
#define FS_ACTIVE 1
#endif
#ifndef TMT_BORDERCOLOR
#define TMT_BORDERCOLOR 3801
#endif
namespace TreePropSheet
{
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CPropPageFrameOffice2003::CPropPageFrameOffice2003()
{
}
CPropPageFrameOffice2003::~CPropPageFrameOffice2003()
{
}
/////////////////////////////////////////////////////////////////////
// Overridings
/////////////////////////////////////////////////////////////////////
BOOL CPropPageFrameOffice2003::Create(DWORD dwWindowStyle, const RECT &rect, CWnd *pwndParent, UINT nID)
{
if (GetThemeLib().IsAvailable() && GetThemeLib().IsThemeActive() && GetThemeLib().IsAppThemed() )
{
return CWnd::CreateEx(
0,
AfxRegisterWndClass(CS_HREDRAW|CS_VREDRAW, AfxGetApp()->LoadStandardCursor(IDC_ARROW), GetSysColorBrush(COLOR_3DFACE)),
_T("PropPageFrameBordered"),
dwWindowStyle, rect, pwndParent, nID);
}
else
{
return CWnd::CreateEx(
WS_EX_CLIENTEDGE/*|WS_EX_TRANSPARENT*/,
AfxRegisterWndClass(CS_HREDRAW|CS_VREDRAW, AfxGetApp()->LoadStandardCursor(IDC_ARROW), GetSysColorBrush(COLOR_3DFACE)),
_T("PropPageFrameBordered"),
dwWindowStyle, rect, pwndParent, nID);
}
}
/////////////////////////////////////////////////////////////////////
// CPropPageFrame overriding
/////////////////////////////////////////////////////////////////////
void CPropPageFrameOffice2003::DrawCaption(CDC *pDc,CRect rect,LPCTSTR lpszCaption,HICON hIcon)
{
rect.left+= 4;
int nLineLeft = rect.left;
// draw icon
if (hIcon && m_Images.GetSafeHandle() && m_Images.GetImageCount() == 1)
{
IMAGEINFO ii;
m_Images.GetImageInfo(0, &ii);
CPoint pt(3, rect.CenterPoint().y - (ii.rcImage.bottom-ii.rcImage.top)/2);
m_Images.Draw(pDc, 0, pt, ILD_TRANSPARENT);
rect.left+= (ii.rcImage.right-ii.rcImage.left) + 3;
}
// draw text
rect.left+= 2;
COLORREF clrPrev = pDc->SetTextColor( GetSysColor( COLOR_WINDOWTEXT ) );
int nBkStyle = pDc->SetBkMode(TRANSPARENT );
CFont *pFont = (CFont*)pDc->SelectStockObject( SYSTEM_FONT );
pDc->DrawText( lpszCaption, rect, DT_LEFT|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS );
pDc->SetTextColor(clrPrev);
pDc->SetBkMode(nBkStyle);
pDc->SelectObject(pFont);
// draw line
CPen pen( PS_SOLID, 1, ::GetSysColor( COLOR_GRADIENTACTIVECAPTION ) );
CPen* pPrevPen = pDc->SelectObject( &pen );
pDc->MoveTo( nLineLeft, rect.bottom - 1);
pDc->LineTo( rect.right - 4, rect.bottom - 1);
pDc->SelectObject( pPrevPen );
}
/////////////////////////////////////////////////////////////////////
// CPropPageFrameEx overrides
/////////////////////////////////////////////////////////////////////
void CPropPageFrameOffice2003::DrawBackground(CDC* pDc)
{
// Draw a frame in themed mode.
if (GetThemeLib().IsAvailable() && GetThemeLib().IsThemeActive() && GetThemeLib().IsAppThemed() )
{
COLORREF color = ::GetSysColor( COLOR_GRADIENTINACTIVECAPTION );
HTHEME hTheme = GetThemeLib().OpenThemeData(m_hWnd, L"TREEVIEW");
if (hTheme)
{
GetThemeLib().GetThemeColor( hTheme, WP_FRAMELEFT, FS_ACTIVE, TMT_BORDERCOLOR, &color );
}
CWnd::OnEraseBkgnd( pDc );
CRect rect;
GetClientRect(rect);
CPen pen( PS_SOLID, 1, color );
CBrush brush( ::GetSysColor( COLOR_WINDOW ) );
CPen* pPrevPen = pDc->SelectObject( &pen );
CBrush* pPrevBrush = pDc->SelectObject( &brush );
pDc->Rectangle( &rect );
pDc->SelectObject( pPrevPen );
pDc->SelectObject( pPrevBrush );
}
else
{
// Draw our own background: always COLOR_WINDOW system color.
CWnd::OnEraseBkgnd( pDc );
CRect rect;
GetClientRect(rect);
::FillRect(pDc->m_hDC, &rect, ::GetSysColorBrush( COLOR_WINDOW ) );
}
}
}; // namespace TreePropSheet | [
"[email protected]"
] | [
[
[
1,
172
]
]
] |
0abcfcda65d95d349ca3c3073a258adb09a10e64 | c7120eeec717341240624c7b8a731553494ef439 | /src/cplusplus/freezone-samp/src/core/messages/messages_storage.hpp | 5b5f3ea0a3f3080e961aa90ffc4590670dd090e7 | [] | no_license | neverm1ndo/gta-paradise-sa | d564c1ed661090336621af1dfd04879a9c7db62d | 730a89eaa6e8e4afc3395744227527748048c46d | refs/heads/master | 2020-04-27T22:00:22.221323 | 2010-09-04T19:02:28 | 2010-09-04T19:02:28 | 174,719,907 | 1 | 0 | null | 2019-03-09T16:44:43 | 2019-03-09T16:44:43 | null | UTF-8 | C++ | false | false | 1,202 | hpp | #ifndef MESSAGES_STORAGE_HPP
#define MESSAGES_STORAGE_HPP
#include <memory>
#include "core/container/application_item.hpp"
#include "core/createble_i.hpp"
#include "core/buffer/buffer.hpp"
#include "core/serialization/configuradable.hpp"
#include "messages_sender.hpp"
#include "messages_params.hpp"
class server_configuration;
class messages_storage
:public application_item
,public createble_i
,public configuradable
{
public:
typedef std::tr1::shared_ptr<messages_storage> ptr;
static ptr instance();
messages_storage();
~messages_storage();
public:
buffer::ptr_c get_msg_buff() const;
public: // createble_i
virtual void create();
public: // configuradable
virtual void configure_pre();
virtual void configure(buffer::ptr const& buff, def_t const& def);
virtual void configure_post();
public: // auto_name
SERIALIZE_MAKE_CLASS_NAME(messages_storage);
private:
buffer::ptr root_buff;
buffer::ptr work_buff;
private:
void init_server_properties();
private:
friend class server_configuration;
buffer::ptr const& get_root_buff() const;
};
#endif // MESSAGES_STORAGE_HPP
| [
"dimonml@19848965-7475-ded4-60a4-26152d85fbc5"
] | [
[
[
1,
50
]
]
] |
005ee4d355ae3466728a408578f07a6d726f869e | 2c1e5a69ca68fe185cc04c5904aa104b0ba42e32 | /src/common/Stream.cpp | 74ba495a662ad1049a0ae3f0a727621b04ceb343 | [] | no_license | dogtwelve/newsiderpg | e3f8284a7cd9938156ef8d683dca7bcbd928c593 | 303566a034dca3e66cf0f29cf9eaea1d54d63e4a | refs/heads/master | 2021-01-10T13:03:31.986204 | 2010-06-27T05:36:33 | 2010-06-27T05:36:33 | 46,550,247 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,433 | cpp | // Copyright (C) 2005 GameWG. All rights reserved.
// GAMELOFT PROPRIETARY/CONFIDENTIAL.
//
// Author: Qiu Wei Min
#include "Stream.h"
#include "SysUtil.h"
#include "ResFile.h"
#include "Engine.h"
#include "Memory.h"
CFileStream::CFileStream()
{
#ifdef _LZMA_IN_CB
m_pFileBuffer = NULL;
#endif
}
CFileStream::~CFileStream()
{
#ifdef _LZMA_IN_CB
SAFE_DELETE(m_pFileBuffer);
#endif
}
bool CFileStream::Open(const char* pName, int mode)
{
m_mode = mode;
if(!m_file.Open(pName, mode))
return false;
return true;
}
int CFileStream::GetLength()
{
return m_file.GetLength();
}
int CFileStream::GetPosition()
{
return m_file.GetPosition();
}
bool CFileStream::SetPosition(int pos)
{
return m_file.Seek(pos, CRawFile::FSEEK_BEGIN);
}
bool CFileStream::Skip(int pos)
{
return m_file.Seek(pos, CRawFile::FSEEK_CURRENT);
}
bool CFileStream::IsReadOnly()
{
return m_mode == CRawFile::MODE_READ;
}
int CFileStream::Read(void* pBuffer, int length)
{
return m_file.Read(pBuffer, length);
}
signed char CFileStream::ReadByte()
{
signed char c;
int ret = m_file.Read(&c, 1);
ASSERT(ret == 1);
return c;
}
unsigned char CFileStream::ReadUByte()
{
unsigned char c;
int ret = m_file.Read(&c, 1);
ASSERT(ret == 1);
return c;
}
short CFileStream::ReadShortLE()
{
unsigned char c[2];
int ret = m_file.Read(&c, sizeof(c));
ASSERT(ret == sizeof(c));
return (short)((c[1] << 8) | c[0]);
}
unsigned short CFileStream::ReadUShortLE()
{
unsigned char c[2];
int ret = m_file.Read(&c, sizeof(c));
ASSERT(ret == sizeof(c));
return (short)((c[1] << 8) | c[0]);
}
int CFileStream::ReadIntLE()
{
unsigned char c[4];
int ret = m_file.Read(&c, sizeof(c));
ASSERT(ret == sizeof(c));
return (c[3] << 24) | (c[2] << 16) | (c[1] << 8) | c[0];
}
unsigned int CFileStream::ReadUIntLE()
{
unsigned char c[4];
int ret = m_file.Read(&c, sizeof(c));
ASSERT(ret == sizeof(c));
return (c[3] << 24) | (c[2] << 16) | (c[1] << 8) | c[0];
}
short CFileStream::ReadShortBE()
{
unsigned char c[2];
int ret = m_file.Read(&c, sizeof(c));
ASSERT(ret == sizeof(c));
return (short)((c[0] << 8) | c[1]);
}
unsigned short CFileStream::ReadUShortBE()
{
unsigned char c[2];
int ret = m_file.Read(&c, sizeof(c));
ASSERT(ret == sizeof(c));
return (short)((c[0] << 8) | c[1]);
}
int CFileStream::ReadIntBE()
{
unsigned char c[4];
int ret = m_file.Read(&c, sizeof(c));
ASSERT(ret == sizeof(c));
return (c[0] << 24) | (c[1] << 16) | (c[2] << 8) | c[3];
}
unsigned int CFileStream::ReadUIntBE()
{
unsigned char c[4];
int ret = m_file.Read(&c, sizeof(c));
ASSERT(ret == sizeof(c));
return (c[0] << 24) | (c[1] << 16) | (c[2] << 8) | c[3];
}
int CFileStream::Write(const void* pBuffer, int length)
{
return m_file.Write(pBuffer, length);
}
void CFileStream::WriteByte(int v)
{
int ret = m_file.Write(&v, 1);
ASSERT(ret == 1);
}
void CFileStream::WriteShortLE(int v)
{
int ret = m_file.Write(&v, 2);
ASSERT(ret == 2);
}
void CFileStream::WriteIntLE(int v)
{
int ret = m_file.Write(&v, 4);
ASSERT(ret == 4);
}
void CFileStream::WriteShortBE(short v)
{
unsigned char c[2];
c[0] = (v & 0xFF00) >> 8;
c[1] = (v & 0x00FF) ;
int ret = m_file.Write(&c, 2);
ASSERT(ret == 2);
}
void CFileStream::WriteIntBE(int v)
{
unsigned char c[4];
c[0] = (v & 0xFF000000) >> 24;
c[1] = (v & 0x00FF0000) >> 16;
c[2] = (v & 0x0000FF00) >> 8;
c[3] = (v & 0x000000FF) ;
int ret = m_file.Write(&c, 4);
ASSERT(ret == 4);
}
#ifdef _LZMA_IN_CB
void CFileStream::InitLzmaBuffer(int size)
{
ASSERT(m_pFileBuffer == NULL);
ASSERT(size > 0);
m_nBufferSize = size;
// << by wubin, use POOL_BOTTOM
//m_pFileBuffer = (GL_NEW/*(GetMemoryType(this))*/ unsigned char[m_nBufferSize]);
m_pFileBuffer = (GL_NEW/*(POOL_BOTTOM)*/ unsigned char[m_nBufferSize]);
// >>
}
void CFileStream::ReleaseLzmaBuffer()
{
SAFE_DELETE_ARRAY(m_pFileBuffer);//MF
}
int CFileStream::LzmaRead(unsigned char **buffer, unsigned int *bufferSize, int& size)
{
ASSERT(m_pFileBuffer != NULL);
*buffer = m_pFileBuffer;
if(size - m_nBufferSize > 0)
{
*bufferSize = m_file.Read(m_pFileBuffer, m_nBufferSize);
}
else
{
*bufferSize = m_file.Read(m_pFileBuffer, size);
}
size -= *bufferSize;
return 0;
}
#endif
void CFileStream::Close()
{
m_file.Close();
}
CMemoryStream::CMemoryStream(void *buf, int length)
{
m_data = (unsigned char*)buf;
m_current = m_data;
m_length = length;
m_needFreeBuffer = false;
}
CMemoryStream::CMemoryStream(int length, MemoryType memType)
{
m_data = (GL_NEW/*(memType)*/ unsigned char[length]);
m_current = m_data;
m_length = length;
m_needFreeBuffer = true;
}
CMemoryStream::~CMemoryStream()
{
Close();
}
int CMemoryStream::GetLength()
{
return m_length;
}
int CMemoryStream::GetPosition()
{
return m_current - m_data;
}
bool CMemoryStream::IsReadOnly()
{
//always read-write
return false;
}
int CMemoryStream::Write(const void* pBuffer, int length)
{
ASSERT(m_current + length <= m_data + m_length);
MEMCPY(m_current, pBuffer, length);
m_current += length;
return length;
}
void CMemoryStream::WriteByte(int v)
{
ASSERT(m_current < m_data + m_length);
*m_current++ = v;
}
void CMemoryStream::WriteShortLE(int v)
{
ASSERT(m_current + 2 <= m_data + m_length);
*m_current++ = v;
*m_current++ = v >> 8;
}
void CMemoryStream::WriteIntLE(int v)
{
ASSERT(m_current + 4 <= m_data + m_length);
*m_current++ = v;
*m_current++ = v >> 8;
*m_current++ = v >> 16;
*m_current++ = v >> 24;
}
void CMemoryStream::Close()
{
if(m_needFreeBuffer)
{
SAFE_DELETE_ARRAY(m_data);
}
m_data = NULL;
}
bool CMemoryStream::Skip(int len)
{
m_current += len;
ASSERT(m_current >= m_data && m_current <= m_data + m_length);
return true;
}
bool CMemoryStream::SetPosition(int pos)
{
ASSERT(pos < m_length);
m_current = m_data + pos;
return true;
}
int CMemoryStream::Read(void* pBuffer, int length)
{
ASSERT(m_current + length <= m_data + m_length);
MEMCPY(pBuffer, m_current, length);
m_current += length;
return length;
}
signed char CMemoryStream::ReadByte()
{
ASSERT(m_current < m_data + m_length);
return (signed char)*m_current++;
}
unsigned char CMemoryStream::ReadUByte()
{
ASSERT(m_current < m_data + m_length);
return (unsigned char)*m_current++;
}
short CMemoryStream::ReadShortLE()
{
ASSERT(m_current + 2 <= m_data + m_length);
short r = (short)((m_current[1] << 8) | m_current[0]);
m_current += 2;
return r;
}
unsigned short CMemoryStream::ReadUShortLE()
{
ASSERT(m_current + 2 <= m_data + m_length);
unsigned short r = (unsigned short)((m_current[1] << 8) | m_current[0]);
m_current += 2;
return r;
}
int CMemoryStream::ReadIntLE()
{
ASSERT(m_current + 4 <= m_data + m_length);
int r = (m_current[3] << 24) | (m_current[2] << 16) | (m_current[1] << 8) | m_current[0];
m_current += 4;
return r;
}
unsigned int CMemoryStream::ReadUIntLE()
{
ASSERT(m_current + 4 <= m_data + m_length);
unsigned int r = (m_current[3] << 24) | (m_current[2] << 16) | (m_current[1] << 8) | m_current[0];
m_current += 4;
return r;
}
short CMemoryStream::ReadShortBE()
{
ASSERT(m_current + 2 <= m_data + m_length);
short r = (short)((m_current[0] << 8) | m_current[1]);
m_current += 2;
return r;
}
unsigned short CMemoryStream::ReadUShortBE()
{
ASSERT(m_current + 2 <= m_data + m_length);
unsigned short r = (unsigned short)((m_current[0] << 8) | m_current[1]);
m_current += 2;
return r;
}
int CMemoryStream::ReadIntBE()
{
ASSERT(m_current + 4 <= m_data + m_length);
int r = (m_current[0] << 24) | (m_current[1] << 16) | (m_current[2] << 8) | m_current[3];
m_current += 4;
return r;
}
unsigned int CMemoryStream::ReadUIntBE()
{
ASSERT(m_current + 4 <= m_data + m_length);
unsigned int r = (m_current[0] << 24) | (m_current[1] << 16) | (m_current[2] << 8) | m_current[3];
m_current += 4;
return r;
}
//s64 CMemoryStream::ReadInt64BE()
//{
// ASSERT(m_current + 4 <= m_data + m_length);
// int high = (m_current[0] << 24) | (m_current[1] << 16) | (m_current[2] << 8) | m_current[3];
// m_current += 4;
// unsigned int low = (m_current[0] << 24) | (m_current[1] << 16) | (m_current[2] << 8) | m_current[3];
// m_current += 4;
//
// //s64 r = (((s64)high)<<32) + (s64)low;
// //DBGPRINTF("****** returning s64 h=%d,l=%d",high,low);
// return s64(high, low);
//}
char* CMemoryStream::readUTF(MemoryType memType)
{
unsigned short len = ReadUShortBE();
char* str = (GL_NEW/*(memType)*/ char[len + 1]);
str[Read(str, len)] = 0;
return str;
}
bool CMemoryStream::FreeBottom()
{
//MemoryType pMemType = GetMemoryType(m_data);
//if(pMemType != POOL_TOP)
//{
// return false;
//}
//CMemoryPool *pool = GetEngine().GetMemoryPool(MEMORY_POOL_DEFAULT);
//int *pTop = (int*)pool->GetTop();
//if((int*)m_data != pTop + 1)
//{
// return false;
//}
//int len = (m_current - m_data) & ~3;
//unsigned char *p = m_data;
//m_data += len;
//m_length -= len;
//int *pTopNew = (int*)m_data - 1;
//*pTopNew = *pTop;
//pool->SetTop(pTopNew);
//return true;
return false;
}
| [
"[email protected]"
] | [
[
[
1,
464
]
]
] |
c4e2f94235827f4e0048ebdddc33b50400f63657 | 81e051c660949ac0e89d1e9cf286e1ade3eed16a | /quake3ce/code/q3_ui/ui_splevel.cpp | f7d2e93f3275102c41ea073b8d7ecdc7a58e7f79 | [] | no_license | crioux/q3ce | e89c3b60279ea187a2ebcf78dbe1e9f747a31d73 | 5e724f55940ac43cb25440a65f9e9e12220c9ada | refs/heads/master | 2020-06-04T10:29:48.281238 | 2008-11-16T15:00:38 | 2008-11-16T15:00:38 | 32,103,416 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,163 | cpp | /*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Foobar; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
/*
=============================================================================
SINGLE PLAYER LEVEL SELECT MENU
=============================================================================
*/
#include"ui_pch.h"
#define ART_LEVELFRAME_FOCUS "menu/art/maps_select"
#define ART_LEVELFRAME_SELECTED "menu/art/maps_selected"
#define ART_ARROW "menu/art/narrow_0"
#define ART_ARROW_FOCUS "menu/art/narrow_1"
#define ART_MAP_UNKNOWN "menu/art/unknownmap"
#define ART_MAP_COMPLETE1 "menu/art/level_complete1"
#define ART_MAP_COMPLETE2 "menu/art/level_complete2"
#define ART_MAP_COMPLETE3 "menu/art/level_complete3"
#define ART_MAP_COMPLETE4 "menu/art/level_complete4"
#define ART_MAP_COMPLETE5 "menu/art/level_complete5"
#define ART_BACK0 "menu/art/back_0"
#define ART_BACK1 "menu/art/back_1"
#define ART_FIGHT0 "menu/art/fight_0"
#define ART_FIGHT1 "menu/art/fight_1"
#define ART_RESET0 "menu/art/reset_0"
#define ART_RESET1 "menu/art/reset_1"
#define ART_CUSTOM0 "menu/art/skirmish_0"
#define ART_CUSTOM1 "menu/art/skirmish_1"
#define ID_LEFTARROW 10
#define ID_PICTURE0 11
#define ID_PICTURE1 12
#define ID_PICTURE2 13
#define ID_PICTURE3 14
#define ID_RIGHTARROW 15
#define ID_PLAYERPIC 16
#define ID_AWARD1 17
#define ID_AWARD2 18
#define ID_AWARD3 19
#define ID_AWARD4 20
#define ID_AWARD5 21
#define ID_AWARD6 22
#define ID_BACK 23
#define ID_RESET 24
#define ID_CUSTOM 25
#define ID_NEXT 26
#define PLAYER_Y 314
#define AWARDS_Y (PLAYER_Y + 26)
typedef struct {
menuframework_s menu;
menutext_s item_banner;
menubitmap_s item_leftarrow;
menubitmap_s item_maps[4];
menubitmap_s item_rightarrow;
menubitmap_s item_player;
menubitmap_s item_awards[6];
menubitmap_s item_back;
menubitmap_s item_reset;
menubitmap_s item_custom;
menubitmap_s item_next;
menubitmap_s item_null;
qboolean reinit;
const char * selectedArenaInfo;
int numMaps;
char levelPicNames[4][MAX_QPATH];
char levelNames[4][16];
int levelScores[4];
int levelScoresSkill[4];
qhandle_t levelSelectedPic;
qhandle_t levelFocusPic;
qhandle_t levelCompletePic[5];
char playerModel[MAX_QPATH];
char playerPicName[MAX_QPATH];
int awardLevels[6];
sfxHandle_t awardSounds[6];
int numBots;
qhandle_t botPics[7];
char botNames[7][10];
} levelMenuInfo_t;
static levelMenuInfo_t levelMenuInfo;
static int selectedArenaSet;
static int selectedArena;
static int currentSet;
static int currentGame;
static int trainingTier;
static int finalTier;
static int minTier;
static int maxTier;
/*
=================
PlayerIcon
=================
*/
static void PlayerIcon( const char *modelAndSkin, char *iconName, int iconNameMaxSize ) {
const char *skin;
char *pskin;
char model[MAX_QPATH];
Q_strncpyz( model, modelAndSkin, sizeof(model));
pskin = Q_strrchr( model, '/' );
if ( pskin ) {
*pskin++ = '\0';
skin=pskin;
}
else {
skin = "default";
}
Com_sprintf(iconName, iconNameMaxSize, "models/players/%s/icon_%s.tga", model, skin );
if( !_UI_trap_R_RegisterShaderNoMip( iconName ) && Q_stricmp( skin, "default" ) != 0 ) {
Com_sprintf(iconName, iconNameMaxSize, "models/players/%s/icon_default.tga", model );
}
}
/*
=================
PlayerIconhandle
=================
*/
static qhandle_t PlayerIconHandle( const char *modelAndSkin ) {
char iconName[MAX_QPATH];
PlayerIcon( modelAndSkin, iconName, sizeof(iconName) );
return _UI_trap_R_RegisterShaderNoMip( iconName );
}
/*
=================
UI_SPLevelMenu_SetBots
=================
*/
static void UI_SPLevelMenu_SetBots( void ) {
char *p;
char *bot;
const char *botInfo;
char bots[MAX_INFO_STRING];
levelMenuInfo.numBots = 0;
if ( selectedArenaSet > currentSet ) {
return;
}
Q_strncpyz( bots, Info_ValueForKey( levelMenuInfo.selectedArenaInfo, "bots" ), sizeof(bots) );
p = &bots[0];
while( *p && levelMenuInfo.numBots < 7 ) {
//skip spaces
while( *p && *p == ' ' ) {
p++;
}
if( !p ) {
break;
}
// mark start of bot name
bot = p;
// skip until space of null
while( *p && *p != ' ' ) {
p++;
}
if( *p ) {
*p++ = 0;
}
botInfo = UI_GetBotInfoByName( bot );
if( botInfo ) {
levelMenuInfo.botPics[levelMenuInfo.numBots] = PlayerIconHandle( Info_ValueForKey( botInfo, "model" ) );
Q_strncpyz( levelMenuInfo.botNames[levelMenuInfo.numBots], Info_ValueForKey( botInfo, "name" ), 10 );
}
else {
levelMenuInfo.botPics[levelMenuInfo.numBots] = 0;
Q_strncpyz( levelMenuInfo.botNames[levelMenuInfo.numBots], bot, 10 );
}
Q_CleanStr( levelMenuInfo.botNames[levelMenuInfo.numBots] );
levelMenuInfo.numBots++;
}
}
/*
=================
UI_SPLevelMenu_SetMenuItems
=================
*/
static void UI_SPLevelMenu_SetMenuArena( int n, int level, const char *arenaInfo ) {
char map[MAX_QPATH];
Q_strncpyz( map, Info_ValueForKey( arenaInfo, "map" ), sizeof(map) );
Q_strncpyz( levelMenuInfo.levelNames[n], map, sizeof(levelMenuInfo.levelNames[n]) );
Q_strupr( levelMenuInfo.levelNames[n] );
UI_GetBestScore( level, &levelMenuInfo.levelScores[n], &levelMenuInfo.levelScoresSkill[n] );
if( levelMenuInfo.levelScores[n] > 8 ) {
levelMenuInfo.levelScores[n] = 8;
}
strcpy( levelMenuInfo.levelPicNames[n], va( "levelshots/%s.tga", map ) );
if( !_UI_trap_R_RegisterShaderNoMip( levelMenuInfo.levelPicNames[n] ) ) {
strcpy( levelMenuInfo.levelPicNames[n], ART_MAP_UNKNOWN );
}
levelMenuInfo.item_maps[n].shader = 0;
if ( selectedArenaSet > currentSet ) {
levelMenuInfo.item_maps[n].generic.flags |= QMF_GRAYED;
}
else {
levelMenuInfo.item_maps[n].generic.flags &= ~QMF_GRAYED;
}
levelMenuInfo.item_maps[n].generic.flags &= ~QMF_INACTIVE;
}
static void UI_SPLevelMenu_SetMenuItems( void ) {
int n;
int level;
const char *arenaInfo;
if ( selectedArenaSet > currentSet ) {
selectedArena = -1;
}
else if ( selectedArena == -1 ) {
selectedArena = 0;
}
if( selectedArenaSet == trainingTier || selectedArenaSet == finalTier ) {
selectedArena = 0;
}
if( selectedArena != -1 ) {
_UI_trap_Cvar_SetValue( "ui_spSelection", MAKE_LFIXED(selectedArenaSet * ARENAS_PER_TIER + selectedArena) );
}
if( selectedArenaSet == trainingTier ) {
arenaInfo = UI_GetSpecialArenaInfo( "training" );
level = atoi( Info_ValueForKey( arenaInfo, "num" ) );
UI_SPLevelMenu_SetMenuArena( 0, level, arenaInfo );
levelMenuInfo.selectedArenaInfo = arenaInfo;
levelMenuInfo.item_maps[0].generic.x = 256;
Bitmap_Init( &levelMenuInfo.item_maps[0] );
levelMenuInfo.item_maps[0].generic.bottom += 32;
levelMenuInfo.numMaps = 1;
levelMenuInfo.item_maps[1].generic.flags |= QMF_INACTIVE;
levelMenuInfo.item_maps[2].generic.flags |= QMF_INACTIVE;
levelMenuInfo.item_maps[3].generic.flags |= QMF_INACTIVE;
levelMenuInfo.levelPicNames[1][0] = 0;
levelMenuInfo.levelPicNames[2][0] = 0;
levelMenuInfo.levelPicNames[3][0] = 0;
levelMenuInfo.item_maps[1].shader = 0;
levelMenuInfo.item_maps[2].shader = 0;
levelMenuInfo.item_maps[3].shader = 0;
}
else if( selectedArenaSet == finalTier ) {
arenaInfo = UI_GetSpecialArenaInfo( "final" );
level = atoi( Info_ValueForKey( arenaInfo, "num" ) );
UI_SPLevelMenu_SetMenuArena( 0, level, arenaInfo );
levelMenuInfo.selectedArenaInfo = arenaInfo;
levelMenuInfo.item_maps[0].generic.x = 256;
Bitmap_Init( &levelMenuInfo.item_maps[0] );
levelMenuInfo.item_maps[0].generic.bottom += 32;
levelMenuInfo.numMaps = 1;
levelMenuInfo.item_maps[1].generic.flags |= QMF_INACTIVE;
levelMenuInfo.item_maps[2].generic.flags |= QMF_INACTIVE;
levelMenuInfo.item_maps[3].generic.flags |= QMF_INACTIVE;
levelMenuInfo.levelPicNames[1][0] = 0;
levelMenuInfo.levelPicNames[2][0] = 0;
levelMenuInfo.levelPicNames[3][0] = 0;
levelMenuInfo.item_maps[1].shader = 0;
levelMenuInfo.item_maps[2].shader = 0;
levelMenuInfo.item_maps[3].shader = 0;
}
else {
levelMenuInfo.item_maps[0].generic.x = 46;
Bitmap_Init( &levelMenuInfo.item_maps[0] );
levelMenuInfo.item_maps[0].generic.bottom += 18;
levelMenuInfo.numMaps = 4;
for ( n = 0; n < 4; n++ ) {
level = selectedArenaSet * ARENAS_PER_TIER + n;
arenaInfo = UI_GetArenaInfoByNumber( level );
UI_SPLevelMenu_SetMenuArena( n, level, arenaInfo );
}
if( selectedArena != -1 ) {
levelMenuInfo.selectedArenaInfo = UI_GetArenaInfoByNumber( selectedArenaSet * ARENAS_PER_TIER + selectedArena );
}
}
// enable/disable arrows when they are valid/invalid
if ( selectedArenaSet == minTier ) {
levelMenuInfo.item_leftarrow.generic.flags |= ( QMF_INACTIVE | QMF_HIDDEN );
}
else {
levelMenuInfo.item_leftarrow.generic.flags &= ~( QMF_INACTIVE | QMF_HIDDEN );
}
if ( selectedArenaSet == maxTier ) {
levelMenuInfo.item_rightarrow.generic.flags |= ( QMF_INACTIVE | QMF_HIDDEN );
}
else {
levelMenuInfo.item_rightarrow.generic.flags &= ~( QMF_INACTIVE | QMF_HIDDEN );
}
UI_SPLevelMenu_SetBots();
}
/*
=================
UI_SPLevelMenu_ResetEvent
=================
*/
static void UI_SPLevelMenu_ResetDraw( void ) {
UI_DrawProportionalString( SCREEN_WIDTH/2, 356 + PROP_HEIGHT * 0, "WARNING: This resets all of the", UI_CENTER|UI_SMALLFONT, color_yellow );
UI_DrawProportionalString( SCREEN_WIDTH/2, 356 + PROP_HEIGHT * 1, "single player game variables.", UI_CENTER|UI_SMALLFONT, color_yellow );
UI_DrawProportionalString( SCREEN_WIDTH/2, 356 + PROP_HEIGHT * 2, "Do this only if you want to", UI_CENTER|UI_SMALLFONT, color_yellow );
UI_DrawProportionalString( SCREEN_WIDTH/2, 356 + PROP_HEIGHT * 3, "start over from the beginning.", UI_CENTER|UI_SMALLFONT, color_yellow );
}
static void UI_SPLevelMenu_ResetAction( qboolean result ) {
if( !result ) {
return;
}
// clear game variables
UI_NewGame();
_UI_trap_Cvar_SetValue( "ui_spSelection", -LFIXED(4 ,0));
// make the level select menu re-initialize
UI_PopMenu();
UI_SPLevelMenu();
}
static void UI_SPLevelMenu_ResetEvent( void* ptr, int event )
{
if (event != QM_ACTIVATED) {
return;
}
UI_ConfirmMenu( "RESET GAME?", UI_SPLevelMenu_ResetDraw, UI_SPLevelMenu_ResetAction );
}
/*
=================
UI_SPLevelMenu_LevelEvent
=================
*/
static void UI_SPLevelMenu_LevelEvent( void* ptr, int notification ) {
if (notification != QM_ACTIVATED) {
return;
}
if ( selectedArenaSet == trainingTier || selectedArenaSet == finalTier ) {
return;
}
selectedArena = ((menucommon_s*)ptr)->id - ID_PICTURE0;
levelMenuInfo.selectedArenaInfo = UI_GetArenaInfoByNumber( selectedArenaSet * ARENAS_PER_TIER + selectedArena );
UI_SPLevelMenu_SetBots();
_UI_trap_Cvar_SetValue( "ui_spSelection", MAKE_LFIXED(selectedArenaSet * ARENAS_PER_TIER + selectedArena) );
}
/*
=================
UI_SPLevelMenu_LeftArrowEvent
=================
*/
static void UI_SPLevelMenu_LeftArrowEvent( void* ptr, int notification ) {
if (notification != QM_ACTIVATED) {
return;
}
if ( selectedArenaSet == minTier ) {
return;
}
selectedArenaSet--;
UI_SPLevelMenu_SetMenuItems();
}
/*
=================
UI_SPLevelMenu_RightArrowEvent
=================
*/
static void UI_SPLevelMenu_RightArrowEvent( void* ptr, int notification ) {
if (notification != QM_ACTIVATED) {
return;
}
if ( selectedArenaSet == maxTier ) {
return;
}
selectedArenaSet++;
UI_SPLevelMenu_SetMenuItems();
}
/*
=================
UI_SPLevelMenu_PlayerEvent
=================
*/
static void UI_SPLevelMenu_PlayerEvent( void* ptr, int notification ) {
if (notification != QM_ACTIVATED) {
return;
}
UI_PlayerSettingsMenu();
}
/*
=================
UI_SPLevelMenu_AwardEvent
=================
*/
static void UI_SPLevelMenu_AwardEvent( void* ptr, int notification ) {
int n;
if (notification != QM_ACTIVATED) {
return;
}
n = ((menucommon_s*)ptr)->id - ID_AWARD1;
_UI_trap_S_StartLocalSound( levelMenuInfo.awardSounds[n], CHAN_ANNOUNCER );
}
/*
=================
UI_SPLevelMenu_NextEvent
=================
*/
static void UI_SPLevelMenu_NextEvent( void* ptr, int notification ) {
if (notification != QM_ACTIVATED) {
return;
}
if ( selectedArenaSet > currentSet ) {
return;
}
if ( selectedArena == -1 ) {
selectedArena = 0;
}
UI_SPSkillMenu( levelMenuInfo.selectedArenaInfo );
}
/*
=================
UI_SPLevelMenu_BackEvent
=================
*/
static void UI_SPLevelMenu_BackEvent( void* ptr, int notification ) {
if (notification != QM_ACTIVATED) {
return;
}
if ( selectedArena == -1 ) {
selectedArena = 0;
}
UI_PopMenu();
}
/*
=================
UI_SPLevelMenu_CustomEvent
=================
*/
static void UI_SPLevelMenu_CustomEvent( void* ptr, int notification ) {
if (notification != QM_ACTIVATED) {
return;
}
UI_StartServerMenu( qfalse );
}
/*
=================
UI_SPLevelMenu_MenuDraw
=================
*/
#define LEVEL_DESC_LEFT_MARGIN 332
static void UI_SPLevelMenu_MenuDraw( void ) {
int n, i;
int x, y;
vec4_t color;
int level;
// int fraglimit;
int pad;
char buf[MAX_INFO_VALUE];
char string[64];
if( levelMenuInfo.reinit ) {
UI_PopMenu();
UI_SPLevelMenu();
return;
}
// draw player name
_UI_trap_Cvar_VariableStringBuffer( "name", string, 32 );
Q_CleanStr( string );
UI_DrawProportionalString( 320, PLAYER_Y, string, UI_CENTER|UI_SMALLFONT, color_orange );
// check for model changes
_UI_trap_Cvar_VariableStringBuffer( "model", buf, sizeof(buf) );
if( Q_stricmp( buf, levelMenuInfo.playerModel ) != 0 ) {
Q_strncpyz( levelMenuInfo.playerModel, buf, sizeof(levelMenuInfo.playerModel) );
PlayerIcon( levelMenuInfo.playerModel, levelMenuInfo.playerPicName, sizeof(levelMenuInfo.playerPicName) );
levelMenuInfo.item_player.shader = 0;
}
// standard menu drawing
Menu_Draw( &levelMenuInfo.menu );
// draw player award levels
y = AWARDS_Y;
i = 0;
for( n = 0; n < 6; n++ ) {
level = levelMenuInfo.awardLevels[n];
if( level > 0 ) {
if( i & 1 ) {
x = 224 - (i - 1 ) / 2 * (48 + 16);
}
else {
x = 368 + i / 2 * (48 + 16);
}
i++;
if( level == 1 ) {
continue;
}
if( level >= 1000000 ) {
Com_sprintf( string, sizeof(string), "%im", level / 1000000 );
}
else if( level >= 1000 ) {
Com_sprintf( string, sizeof(string), "%ik", level / 1000 );
}
else {
Com_sprintf( string, sizeof(string), "%i", level );
}
UI_DrawString( x + 24, y + 48, string, UI_CENTER, color_yellow );
}
}
UI_DrawProportionalString( 18, 38, va( "Tier %i", selectedArenaSet + 1 ), UI_LEFT|UI_SMALLFONT, color_orange );
for ( n = 0; n < levelMenuInfo.numMaps; n++ ) {
x = levelMenuInfo.item_maps[n].generic.x;
y = levelMenuInfo.item_maps[n].generic.y;
UI_FillRect( MAKE_GFIXED(x), MAKE_GFIXED(y + 96), GFIXED(128,0), GFIXED(18,0), color_black );
}
if ( selectedArenaSet > currentSet ) {
UI_DrawProportionalString( 320, 216, "ACCESS DENIED", UI_CENTER|UI_BIGFONT, color_red );
return;
}
// show levelshots for levels of current tier
Vector4Copy( color_white, color );
color[3] = GFIXED(0,5)+GFIXED(0,5)*FIXED_SIN(MAKE_GFIXED(uis.realtime/PULSE_DIVISOR));
for ( n = 0; n < levelMenuInfo.numMaps; n++ ) {
x = levelMenuInfo.item_maps[n].generic.x;
y = levelMenuInfo.item_maps[n].generic.y;
UI_DrawString( x + 64, y + 96, levelMenuInfo.levelNames[n], UI_CENTER|UI_SMALLFONT, color_orange );
if( levelMenuInfo.levelScores[n] == 1 ) {
UI_DrawHandlePic( MAKE_GFIXED(x), MAKE_GFIXED(y), GFIXED(128,0), GFIXED(96,0), levelMenuInfo.levelCompletePic[levelMenuInfo.levelScoresSkill[n] - 1] );
}
if ( n == selectedArena ) {
if( Menu_ItemAtCursor( &levelMenuInfo.menu ) == &levelMenuInfo.item_maps[n] ) {
_UI_trap_R_SetColor( color );
}
UI_DrawHandlePic( MAKE_GFIXED(x-1), MAKE_GFIXED(y-1), GFIXED(130,0), GFIXED(130 - 14,0), levelMenuInfo.levelSelectedPic );
_UI_trap_R_SetColor( NULL );
}
else if( Menu_ItemAtCursor( &levelMenuInfo.menu ) == &levelMenuInfo.item_maps[n] ) {
_UI_trap_R_SetColor( color );
UI_DrawHandlePic( MAKE_GFIXED(x-31), MAKE_GFIXED(y-30), GFIXED(256,0), GFIXED(256-27,0), levelMenuInfo.levelFocusPic);
_UI_trap_R_SetColor( NULL );
}
}
// show map name and long name of selected level
y = 192;
Q_strncpyz( buf, Info_ValueForKey( levelMenuInfo.selectedArenaInfo, "map" ), 20 );
Q_strupr( buf );
Com_sprintf( string, sizeof(string), "%s: %s", buf, Info_ValueForKey( levelMenuInfo.selectedArenaInfo, "longname" ) );
UI_DrawProportionalString( 320, y, string, UI_CENTER|UI_SMALLFONT, color_orange );
// fraglimit = atoi( Info_ValueForKey( levelMenuInfo.selectedArenaInfo, "fraglimit" ) );
// UI_DrawString( 18, 212, va("Frags %i", fraglimit) , UI_LEFT|UI_SMALLFONT, color_orange );
// draw bot opponents
y += 24;
pad = (7 - levelMenuInfo.numBots) * (64 + 26) / 2;
for( n = 0; n < levelMenuInfo.numBots; n++ ) {
x = 18 + pad + (64 + 26) * n;
if( levelMenuInfo.botPics[n] ) {
UI_DrawHandlePic( MAKE_GFIXED(x), MAKE_GFIXED(y), GFIXED(64,0), GFIXED(64,0), levelMenuInfo.botPics[n]);
}
else {
UI_FillRect( MAKE_GFIXED(x), MAKE_GFIXED(y), GFIXED(64,0), GFIXED(64,0), color_black );
UI_DrawProportionalString( x+22, y+18, "?", UI_BIGFONT, color_orange );
}
UI_DrawString( x, y + 64, levelMenuInfo.botNames[n], UI_SMALLFONT|UI_LEFT, color_orange );
}
}
/*
=================
UI_SPLevelMenu_Cache
=================
*/
void UI_SPLevelMenu_Cache( void ) {
int n;
_UI_trap_R_RegisterShaderNoMip( ART_LEVELFRAME_FOCUS );
_UI_trap_R_RegisterShaderNoMip( ART_LEVELFRAME_SELECTED );
_UI_trap_R_RegisterShaderNoMip( ART_ARROW );
_UI_trap_R_RegisterShaderNoMip( ART_ARROW_FOCUS );
_UI_trap_R_RegisterShaderNoMip( ART_MAP_UNKNOWN );
_UI_trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE1 );
_UI_trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE2 );
_UI_trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE3 );
_UI_trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE4 );
_UI_trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE5 );
_UI_trap_R_RegisterShaderNoMip( ART_BACK0 );
_UI_trap_R_RegisterShaderNoMip( ART_BACK1 );
_UI_trap_R_RegisterShaderNoMip( ART_FIGHT0 );
_UI_trap_R_RegisterShaderNoMip( ART_FIGHT1 );
_UI_trap_R_RegisterShaderNoMip( ART_RESET0 );
_UI_trap_R_RegisterShaderNoMip( ART_RESET1 );
_UI_trap_R_RegisterShaderNoMip( ART_CUSTOM0 );
_UI_trap_R_RegisterShaderNoMip( ART_CUSTOM1 );
for( n = 0; n < 6; n++ ) {
_UI_trap_R_RegisterShaderNoMip( ui_medalPicNames[n] );
levelMenuInfo.awardSounds[n] = _UI_trap_S_RegisterSound( ui_medalSounds[n], qfalse );
}
levelMenuInfo.levelSelectedPic = _UI_trap_R_RegisterShaderNoMip( ART_LEVELFRAME_SELECTED );
levelMenuInfo.levelFocusPic = _UI_trap_R_RegisterShaderNoMip( ART_LEVELFRAME_FOCUS );
levelMenuInfo.levelCompletePic[0] = _UI_trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE1 );
levelMenuInfo.levelCompletePic[1] = _UI_trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE2 );
levelMenuInfo.levelCompletePic[2] = _UI_trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE3 );
levelMenuInfo.levelCompletePic[3] = _UI_trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE4 );
levelMenuInfo.levelCompletePic[4] = _UI_trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE5 );
}
/*
=================
UI_SPLevelMenu_Init
=================
*/
static void UI_SPLevelMenu_Init( void ) {
int skill;
int n;
int x, y;
int count;
char buf[MAX_QPATH];
skill = FIXED_TO_INT(_UI_trap_Cvar_VariableValue( "g_spSkill" ));
if( skill < 1 || skill > 5 ) {
_UI_trap_Cvar_Set( "g_spSkill", "2" );
skill = 2;
}
memset( &levelMenuInfo, 0, sizeof(levelMenuInfo) );
levelMenuInfo.menu.fullscreen = qtrue;
levelMenuInfo.menu.wrapAround = qtrue;
levelMenuInfo.menu.draw = UI_SPLevelMenu_MenuDraw;
UI_SPLevelMenu_Cache();
levelMenuInfo.item_banner.generic.type = MTYPE_BTEXT;
levelMenuInfo.item_banner.generic.x = 320;
levelMenuInfo.item_banner.generic.y = 16;
levelMenuInfo.item_banner.string = strdup("CHOOSE LEVEL");
levelMenuInfo.item_banner.color = color_red;
levelMenuInfo.item_banner.style = UI_CENTER;
levelMenuInfo.item_leftarrow.generic.type = MTYPE_BITMAP;
levelMenuInfo.item_leftarrow.generic.name = ART_ARROW;
levelMenuInfo.item_leftarrow.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
levelMenuInfo.item_leftarrow.generic.x = 18;
levelMenuInfo.item_leftarrow.generic.y = 64;
levelMenuInfo.item_leftarrow.generic.callback = UI_SPLevelMenu_LeftArrowEvent;
levelMenuInfo.item_leftarrow.generic.id = ID_LEFTARROW;
levelMenuInfo.item_leftarrow.width = 16;
levelMenuInfo.item_leftarrow.height = 114;
levelMenuInfo.item_leftarrow.focuspic = ART_ARROW_FOCUS;
levelMenuInfo.item_maps[0].generic.type = MTYPE_BITMAP;
levelMenuInfo.item_maps[0].generic.name = levelMenuInfo.levelPicNames[0];
levelMenuInfo.item_maps[0].generic.flags = QMF_LEFT_JUSTIFY;
levelMenuInfo.item_maps[0].generic.x = 46;
levelMenuInfo.item_maps[0].generic.y = 64;
levelMenuInfo.item_maps[0].generic.id = ID_PICTURE0;
levelMenuInfo.item_maps[0].generic.callback = UI_SPLevelMenu_LevelEvent;
levelMenuInfo.item_maps[0].width = 128;
levelMenuInfo.item_maps[0].height = 96;
levelMenuInfo.item_maps[1].generic.type = MTYPE_BITMAP;
levelMenuInfo.item_maps[1].generic.name = levelMenuInfo.levelPicNames[1];
levelMenuInfo.item_maps[1].generic.flags = QMF_LEFT_JUSTIFY;
levelMenuInfo.item_maps[1].generic.x = 186;
levelMenuInfo.item_maps[1].generic.y = 64;
levelMenuInfo.item_maps[1].generic.id = ID_PICTURE1;
levelMenuInfo.item_maps[1].generic.callback = UI_SPLevelMenu_LevelEvent;
levelMenuInfo.item_maps[1].width = 128;
levelMenuInfo.item_maps[1].height = 96;
levelMenuInfo.item_maps[2].generic.type = MTYPE_BITMAP;
levelMenuInfo.item_maps[2].generic.name = levelMenuInfo.levelPicNames[2];
levelMenuInfo.item_maps[2].generic.flags = QMF_LEFT_JUSTIFY;
levelMenuInfo.item_maps[2].generic.x = 326;
levelMenuInfo.item_maps[2].generic.y = 64;
levelMenuInfo.item_maps[2].generic.id = ID_PICTURE2;
levelMenuInfo.item_maps[2].generic.callback = UI_SPLevelMenu_LevelEvent;
levelMenuInfo.item_maps[2].width = 128;
levelMenuInfo.item_maps[2].height = 96;
levelMenuInfo.item_maps[3].generic.type = MTYPE_BITMAP;
levelMenuInfo.item_maps[3].generic.name = levelMenuInfo.levelPicNames[3];
levelMenuInfo.item_maps[3].generic.flags = QMF_LEFT_JUSTIFY;
levelMenuInfo.item_maps[3].generic.x = 466;
levelMenuInfo.item_maps[3].generic.y = 64;
levelMenuInfo.item_maps[3].generic.id = ID_PICTURE3;
levelMenuInfo.item_maps[3].generic.callback = UI_SPLevelMenu_LevelEvent;
levelMenuInfo.item_maps[3].width = 128;
levelMenuInfo.item_maps[3].height = 96;
levelMenuInfo.item_rightarrow.generic.type = MTYPE_BITMAP;
levelMenuInfo.item_rightarrow.generic.name = ART_ARROW;
levelMenuInfo.item_rightarrow.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
levelMenuInfo.item_rightarrow.generic.x = 606;
levelMenuInfo.item_rightarrow.generic.y = 64;
levelMenuInfo.item_rightarrow.generic.callback = UI_SPLevelMenu_RightArrowEvent;
levelMenuInfo.item_rightarrow.generic.id = ID_RIGHTARROW;
levelMenuInfo.item_rightarrow.width = -16;
levelMenuInfo.item_rightarrow.height = 114;
levelMenuInfo.item_rightarrow.focuspic = ART_ARROW_FOCUS;
_UI_trap_Cvar_VariableStringBuffer( "model", levelMenuInfo.playerModel, sizeof(levelMenuInfo.playerModel) );
PlayerIcon( levelMenuInfo.playerModel, levelMenuInfo.playerPicName, sizeof(levelMenuInfo.playerPicName) );
levelMenuInfo.item_player.generic.type = MTYPE_BITMAP;
levelMenuInfo.item_player.generic.name = levelMenuInfo.playerPicName;
levelMenuInfo.item_player.generic.flags = QMF_LEFT_JUSTIFY|QMF_MOUSEONLY;
levelMenuInfo.item_player.generic.x = 288;
levelMenuInfo.item_player.generic.y = AWARDS_Y;
levelMenuInfo.item_player.generic.id = ID_PLAYERPIC;
levelMenuInfo.item_player.generic.callback = UI_SPLevelMenu_PlayerEvent;
levelMenuInfo.item_player.width = 64;
levelMenuInfo.item_player.height = 64;
for( n = 0; n < 6; n++ ) {
levelMenuInfo.awardLevels[n] = UI_GetAwardLevel( n );
}
levelMenuInfo.awardLevels[AWARD_FRAGS] = 100 * (levelMenuInfo.awardLevels[AWARD_FRAGS] / 100);
y = AWARDS_Y;
count = 0;
for( n = 0; n < 6; n++ ) {
if( levelMenuInfo.awardLevels[n] ) {
if( count & 1 ) {
x = 224 - (count - 1 ) / 2 * (48 + 16);
}
else {
x = 368 + count / 2 * (48 + 16);
}
levelMenuInfo.item_awards[count].generic.type = MTYPE_BITMAP;
levelMenuInfo.item_awards[count].generic.name = ui_medalPicNames[n];
levelMenuInfo.item_awards[count].generic.flags = QMF_LEFT_JUSTIFY|QMF_SILENT|QMF_MOUSEONLY;
levelMenuInfo.item_awards[count].generic.x = x;
levelMenuInfo.item_awards[count].generic.y = y;
levelMenuInfo.item_awards[count].generic.id = ID_AWARD1 + n;
levelMenuInfo.item_awards[count].generic.callback = UI_SPLevelMenu_AwardEvent;
levelMenuInfo.item_awards[count].width = 48;
levelMenuInfo.item_awards[count].height = 48;
count++;
}
}
levelMenuInfo.item_back.generic.type = MTYPE_BITMAP;
levelMenuInfo.item_back.generic.name = ART_BACK0;
levelMenuInfo.item_back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
levelMenuInfo.item_back.generic.x = 0;
levelMenuInfo.item_back.generic.y = 480-64;
levelMenuInfo.item_back.generic.callback = UI_SPLevelMenu_BackEvent;
levelMenuInfo.item_back.generic.id = ID_BACK;
levelMenuInfo.item_back.width = 128;
levelMenuInfo.item_back.height = 64;
levelMenuInfo.item_back.focuspic = ART_BACK1;
levelMenuInfo.item_reset.generic.type = MTYPE_BITMAP;
levelMenuInfo.item_reset.generic.name = ART_RESET0;
levelMenuInfo.item_reset.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
levelMenuInfo.item_reset.generic.x = 170;
levelMenuInfo.item_reset.generic.y = 480-64;
levelMenuInfo.item_reset.generic.callback = UI_SPLevelMenu_ResetEvent;
levelMenuInfo.item_reset.generic.id = ID_RESET;
levelMenuInfo.item_reset.width = 128;
levelMenuInfo.item_reset.height = 64;
levelMenuInfo.item_reset.focuspic = ART_RESET1;
levelMenuInfo.item_custom.generic.type = MTYPE_BITMAP;
levelMenuInfo.item_custom.generic.name = ART_CUSTOM0;
levelMenuInfo.item_custom.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
levelMenuInfo.item_custom.generic.x = 342;
levelMenuInfo.item_custom.generic.y = 480-64;
levelMenuInfo.item_custom.generic.callback = UI_SPLevelMenu_CustomEvent;
levelMenuInfo.item_custom.generic.id = ID_CUSTOM;
levelMenuInfo.item_custom.width = 128;
levelMenuInfo.item_custom.height = 64;
levelMenuInfo.item_custom.focuspic = ART_CUSTOM1;
levelMenuInfo.item_next.generic.type = MTYPE_BITMAP;
levelMenuInfo.item_next.generic.name = ART_FIGHT0;
levelMenuInfo.item_next.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS;
levelMenuInfo.item_next.generic.x = 640;
levelMenuInfo.item_next.generic.y = 480-64;
levelMenuInfo.item_next.generic.callback = UI_SPLevelMenu_NextEvent;
levelMenuInfo.item_next.generic.id = ID_NEXT;
levelMenuInfo.item_next.width = 128;
levelMenuInfo.item_next.height = 64;
levelMenuInfo.item_next.focuspic = ART_FIGHT1;
levelMenuInfo.item_null.generic.type = MTYPE_BITMAP;
levelMenuInfo.item_null.generic.flags = QMF_LEFT_JUSTIFY|QMF_MOUSEONLY|QMF_SILENT;
levelMenuInfo.item_null.generic.x = 0;
levelMenuInfo.item_null.generic.y = 0;
levelMenuInfo.item_null.width = 640;
levelMenuInfo.item_null.height = 480;
Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_banner );
Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_leftarrow );
Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_maps[0] );
Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_maps[1] );
Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_maps[2] );
Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_maps[3] );
levelMenuInfo.item_maps[0].generic.bottom += 18;
levelMenuInfo.item_maps[1].generic.bottom += 18;
levelMenuInfo.item_maps[2].generic.bottom += 18;
levelMenuInfo.item_maps[3].generic.bottom += 18;
Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_rightarrow );
Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_player );
for( n = 0; n < count; n++ ) {
Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_awards[n] );
}
Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_back );
Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_reset );
Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_custom );
Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_next );
Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_null );
_UI_trap_Cvar_VariableStringBuffer( "ui_spSelection", buf, sizeof(buf) );
if( *buf ) {
n = atoi( buf );
selectedArenaSet = n / ARENAS_PER_TIER;
selectedArena = n % ARENAS_PER_TIER;
}
else {
selectedArenaSet = currentSet;
selectedArena = currentGame;
}
UI_SPLevelMenu_SetMenuItems();
}
/*
=================
UI_SPLevelMenu
=================
*/
void UI_SPLevelMenu( void ) {
int level;
int trainingLevel;
const char *arenaInfo;
trainingTier = -1;
arenaInfo = UI_GetSpecialArenaInfo( "training" );
if( arenaInfo ) {
minTier = trainingTier;
trainingLevel = atoi( Info_ValueForKey( arenaInfo, "num" ) );
}
else {
minTier = 0;
trainingLevel = -2;
}
finalTier = UI_GetNumSPTiers();
arenaInfo = UI_GetSpecialArenaInfo( "final" );
if( arenaInfo ) {
maxTier = finalTier;
}
else {
maxTier = finalTier - 1;
if( maxTier < minTier ) {
maxTier = minTier;
}
}
level = UI_GetCurrentGame();
if ( level == -1 ) {
level = UI_GetNumSPArenas() - 1;
if( maxTier == finalTier ) {
level++;
}
}
if( level == trainingLevel ) {
currentSet = -1;
currentGame = 0;
}
else {
currentSet = level / ARENAS_PER_TIER;
currentGame = level % ARENAS_PER_TIER;
}
UI_SPLevelMenu_Init();
UI_PushMenu( &levelMenuInfo.menu );
Menu_SetCursorToItem( &levelMenuInfo.menu, &levelMenuInfo.item_next );
}
/*
=================
UI_SPLevelMenu_f
=================
*/
void UI_SPLevelMenu_f( void ) {
_UI_trap_Key_SetCatcher( KEYCATCH_UI );
uis.menusp = 0;
UI_SPLevelMenu();
}
/*
=================
UI_SPLevelMenu_ReInit
=================
*/
void UI_SPLevelMenu_ReInit( void ) {
levelMenuInfo.reinit = qtrue;
}
| [
"jack.palevich@684fc592-8442-0410-8ea1-df6b371289ac",
"crioux@684fc592-8442-0410-8ea1-df6b371289ac"
] | [
[
[
1,
128
],
[
131,
133
],
[
138,
171
],
[
173,
737
],
[
739,
1010
]
],
[
[
129,
130
],
[
134,
137
],
[
172,
172
],
[
738,
738
]
]
] |
dd236e19c6fb99fcca3f3778c0069f21ae2a829c | ab41c2c63e554350ca5b93e41d7321ca127d8d3a | /glm/gtx/statistics_operation.hpp | 65429e3470eca37e8b58ddc55e2c94c49e1b6fe5 | [] | no_license | burner/e3rt | 2dc3bac2b7face3b1606ee1430e7ecfd4523bf2e | 775470cc9b912a8c1199dd1069d7e7d4fc997a52 | refs/heads/master | 2021-01-11T08:08:00.665300 | 2010-04-26T11:42:42 | 2010-04-26T11:42:42 | 337,021 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,758 | hpp | ///////////////////////////////////////////////////////////////////////////////////////////////////
// OpenGL Mathematics Copyright (c) 2005 - 2009 G-Truc Creation (www.g-truc.net)
///////////////////////////////////////////////////////////////////////////////////////////////////
// Created : 2007-11-21
// Updated : 2007-11-21
// Licence : This source is under MIT License
// File : glm/gtx/statistics_operation.h
///////////////////////////////////////////////////////////////////////////////////////////////////
// Dependency:
// - GLM core
///////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef glm_gtx_statistics_operation
#define glm_gtx_statistics_operation
// Dependency:
#include "../glm.hpp"
namespace glm
{
template <typename T> T statDistanceGTX(const detail::tvec2<T>& v1, const detail::tvec2<T>& v2);
template <typename T> T statDistanceGTX(const detail::tvec3<T>& v1, const detail::tvec3<T>& v2);
template <typename T> T statDistanceGTX(const detail::tvec4<T>& v1, const detail::tvec4<T>& v2);
template <typename T> T statDistanceGTX(const detail::tmat2x2<T>& m1, const detail::tmat2x2<T>& m2);
template <typename T> T statDistanceGTX(const detail::tmat3x3<T>& m1, const detail::tmat3x3<T>& m2);
template <typename T> T statDistanceGTX(const detail::tmat4x4<T>& m1, const detail::tmat4x4<T>& m2);
template <typename T> T expectedValueGTX(const detail::tvec2<T>& v1, const detail::tvec2<T>& v2);
template <typename T> T expectedValueGTX(const detail::tvec3<T>& v1, const detail::tvec3<T>& v2);
template <typename T> T expectedValueGTX(const detail::tvec4<T>& v1, const detail::tvec4<T>& v2);
template <typename T> T expectedValueGTX(const detail::tmat2x2<T>& m1, const detail::tmat2x2<T>& m2);
template <typename T> T expectedValueGTX(const detail::tmat3x3<T>& m1, const detail::tmat3x3<T>& m2);
template <typename T> T expectedValueGTX(const detail::tmat4x4<T>& m1, const detail::tmat4x4<T>& m2);
template <typename T> T varianceGTX(const detail::tvec2<T>& v1, const detail::tvec2<T>& v2);
template <typename T> T varianceGTX(const detail::tvec3<T>& v1, const detail::tvec3<T>& v2);
template <typename T> T varianceGTX(const detail::tvec4<T>& v1, const detail::tvec4<T>& v2);
template <typename T> T varianceGTX(const detail::tmat2x2<T>& m1, const detail::tmat2x2<T>& m2);
template <typename T> T varianceGTX(const detail::tmat3x3<T>& m1, const detail::tmat3x3<T>& m2);
template <typename T> T varianceGTX(const detail::tmat4x4<T>& m1, const detail::tmat4x4<T>& m2);
template <typename T> T standardDevitionGTX(const detail::tvec2<T>& v1, const detail::tvec2<T>& v2);
template <typename T> T standardDevitionGTX(const detail::tvec3<T>& v1, const detail::tvec3<T>& v2);
template <typename T> T standardDevitionGTX(const detail::tvec4<T>& v1, const detail::tvec4<T>& v2);
template <typename T> T standardDevitionGTX(const detail::tmat2x2<T>& m1, const detail::tmat2x2<T>& m2);
template <typename T> T standardDevitionGTX(const detail::tmat3x3<T>& m1, const detail::tmat3x3<T>& m2);
template <typename T> T standardDevitionGTX(const detail::tmat4x4<T>& m1, const detail::tmat4x4<T>& m2);
namespace gtx
{
//! GLM_GTX_statistics_operation extension: - Work in progress - Statistics functions
namespace statistics_operation
{
}
}
}
#define GLM_GTX_statistics_operation namespace gtx::statistics_operation
#ifndef GLM_GTX_GLOBAL
namespace glm {using GLM_GTX_statistics_operation;}
#endif//GLM_GTX_GLOBAL
#include "statistics_operation.inl"
#endif//glm_gtx_statistics_operation
| [
"[email protected]"
] | [
[
[
1,
70
]
]
] |
77c7784beeeb97e4c2b20b2dd3d00e32f87d8319 | d6e0f648d63055d6576de917de8d6f0f3fcb2989 | /ddv/win/src/udp_datetime.h | a7c7b8b758f41c57a23daa3ec2be4fc196467996 | [] | no_license | lgosha/ssd | 9b4a0ade234dd192ef30274377787edf1244b365 | 0b97a39fd7edabca44c4ac19178a5c626d1efea3 | refs/heads/master | 2020-05-19T12:41:32.060017 | 2011-09-27T12:43:06 | 2011-09-27T12:43:06 | 2,428,803 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,090 | h | #ifndef DATETIMESPECIALDEFENITION
#define DATETIMESPECIALDEFENITION
#include <QDateTime>
class DateTime {
public:
static long int timetoint(QTime t) {
long int ti = t.msec();
ti += 1000 * t.second();
ti += 60000 * t.minute();
ti += 3600000 * t.hour();
return ti;
}
static QTime inttotime(long int it) {
QTime ti;
int ih;
int im;
int is;
int ims = it % 1000;
it -= ims;
it /= 1000;
is = it % 60;
it -= is;
it /= 60;
im = it % 60;
it -= im;
it /= 60;
ih = it;
if(ti.setHMS(ih, im, is, ims))
return ti;
ti.setHMS(0, 0, 0, 0);
return ti;
}
static long int datetoint(QDate d) {
long int ti = d.day();
ti += 40 * d.month();
ti += 800 * d.year();
return ti;
}
static QDate inttodate(long int it) {
QDate ti;
int iy;
int im;
int id = it % 40;
it -= id;
it /= 40;
im = it % 20;
it -= im;
it /= 20;
iy = it;
if(ti.setDate(iy, im, id))
return ti;
ti.setDate(0, 0, 0);
return ti;
}
};
#endif
| [
"[email protected]"
] | [
[
[
1,
66
]
]
] |
b3d00d5b44b1155cfa2a2111cd9e5e06315c5ec1 | 80716d408715377e88de1fc736c9204b87a12376 | /TspLib3/Src/DISPLAY.CPP | a6012a44bce37ce1815b924900b7f1eb3eca2cd7 | [] | no_license | junction/jn-tapi | b5cf4b1bb010d696473cabcc3d5950b756ef37e9 | a2ef6c91c9ffa60739ecee75d6d58928f4a5ffd4 | refs/heads/master | 2021-03-12T23:38:01.037779 | 2011-03-10T01:08:40 | 2011-03-10T01:08:40 | 199,317 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 5,303 | cpp | /******************************************************************************/
//
// DISPLAY.CPP - Source code for the CPhoneDisplay class.
//
// Copyright (C) 1994-2004 JulMar Entertainment Technology, Inc.
// All rights reserved
//
// This file contains the code for driving a phone display.
//
// This source code is intended only as a supplement to the
// TSP++ Class Library product documentation. This source code cannot
// be used in part or whole in any form outside the TSP++ library.
//
/******************************************************************************/
/*---------------------------------------------------------------------------*/
// INCLUDE FILES
/*---------------------------------------------------------------------------*/
#include "stdafx.h"
//////////////////////////////////////////////////////////////////////////////
// CPhoneDisplay::CPhoneDisplay
//
// Display constructor
//
CPhoneDisplay::CPhoneDisplay() : m_cLF('\n')
{
m_sizDisplay.cx = m_sizDisplay.cy = 0;
m_ptCursor.x = m_ptCursor.y = 0;
}// CPhoneDisplay::CPhoneDisplay
//////////////////////////////////////////////////////////////////////////////
// CPhoneDisplay::~CPhoneDisplay
//
// Display Destructor
//
CPhoneDisplay::~CPhoneDisplay()
{
}// CPhoneDisplay::~CPhoneDisplay
///////////////////////////////////////////////////////////////////////////////
// CPhoneDisplay::Init
//
// Initialize our display
//
void CPhoneDisplay::Init(int iColumnCount, int iRowCount, TCHAR cLF)
{
// Allocate a buffer if we have coumns/rows
if (iColumnCount > 0 && iRowCount > 0)
{
m_lpsDisplay.reset(new TCHAR[iColumnCount*iRowCount+1]);
m_sizDisplay.cx = iColumnCount;
m_sizDisplay.cy = iRowCount;
m_cLF = cLF;
Reset();
}
}// CPhoneDisplay::Init
////////////////////////////////////////////////////////////////////////////////
// CPhoneDisplay::AddCharacter
//
// Add a character at the cursor position.
//
void CPhoneDisplay::AddCharacter(TCHAR cChar)
{
// If the character is our LINEFEED, then adjust the cursor position.
if (cChar == m_cLF)
{
if (++m_ptCursor.y >= m_sizDisplay.cy)
m_ptCursor.y = 0;
m_ptCursor.x = 0;
}
else // Normal character.
{
// Place the character into the buffer.
SetCharacterAtPosition(-1, -1, cChar);
// Increment our cursor position.
if (++m_ptCursor.x >= m_sizDisplay.cx)
{
m_ptCursor.x = 0;
if (++m_ptCursor.y >= m_sizDisplay.cy)
m_ptCursor.y = 0;
}
}
}// CPhoneDisplay::AddCharacter
////////////////////////////////////////////////////////////////////////////////
// CPhoneDisplay::SetCharacterAtPosition
//
// Set a character into the display at a particular position.
//
void CPhoneDisplay::SetCharacterAtPosition(int iColumn, int iRow, TCHAR cChar)
{
_TSP_ASSERTE(m_lpsDisplay.get() != NULL);
_TSP_ASSERTE(cChar != _T('\0'));
_TSP_ASSERTE(cChar != m_cLF);
if (iColumn == -1)
iColumn = m_ptCursor.x;
if (iRow == -1)
iRow = m_ptCursor.y;
// Validate the character.
if (cChar && cChar != m_cLF &&
iColumn >= 0 && iColumn < m_sizDisplay.cx &&
iRow >= 0 && iRow < m_sizDisplay.cy)
{
LPTSTR pszBuffer = m_lpsDisplay.get();
*(pszBuffer+(iRow*m_sizDisplay.cx+iColumn)) = cChar;
}
}// CPhoneDisplay::SetCharacterAtPosition
///////////////////////////////////////////////////////////////////////////////
// CPhoneDisplay::SetCursorPosition
//
// Set the current cursor position for the display
//
void CPhoneDisplay::SetCursorPosition(int iColumn, int iRow)
{
if (iColumn >= 0 && iColumn < m_sizDisplay.cx)
m_ptCursor.x = iColumn;
if (iRow >= 0 && iRow < m_sizDisplay.cy)
m_ptCursor.y = iRow;
}// CPhoneDisplay::SetCursorPosition
////////////////////////////////////////////////////////////////////////////////
// CPhoneDisplay::Reset
//
// Reset the contents of the display and clear the buffer.
//
void CPhoneDisplay::Reset()
{
m_ptCursor.x = m_ptCursor.y = 0;
if (m_lpsDisplay.get())
{
LPTSTR lpsBuffer = m_lpsDisplay.get();
for (int cy = 0; cy < m_sizDisplay.cy; cy++)
{
for (int cx = 0; cx < m_sizDisplay.cx; cx++)
*lpsBuffer++ = _T(' ');
}
*lpsBuffer = _T('\0');
}
}// CPhoneDisplay::Reset
/////////////////////////////////////////////////////////////////////////////////
// CPhoneDisplay::ClearRow
//
// Clear a single row of our display. Do NOT change the cursor
// positioning
//
void CPhoneDisplay::ClearRow(int iRow)
{
if (iRow >= 0 && iRow < m_sizDisplay.cy)
for (int x = 0; x < m_sizDisplay.cx; x++)
SetCharacterAtPosition(x, iRow, _T(' '));
}// CPhoneDisplay::ClearRow
| [
"Owner@.(none)"
] | [
[
[
1,
164
]
]
] |
32af374dc1f5a87250e9c64c54ffc8f3542a73f1 | b1c7510cfc5d90397bf9aef111cf9906dc278251 | /src/RapidXmlParser.hpp | 689f6ba27901b8e2f8319abc9308b1f0cfbc5d86 | [] | no_license | mkb218/fs1rgen | f50482b5938a08ec7e8a2ad835d333ad069ae4cb | 0747041b967b8807bbdc11e4d4846ad85162df33 | refs/heads/master | 2020-04-01T13:19:56.509972 | 2010-01-24T04:48:28 | 2010-01-24T04:48:28 | 210,589 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 491 | hpp | #ifndef FS1RGEN_RAPIDXMLPARSE
#define FS1RGEN_RAPIDXMLPARSE
#include "XmlParser.hpp"
#include "rapidxml.hpp"
using namespace rapidxml;
using namespace std;
namespace fs1rgen {
class RapidXmlParser {
public:
RapidXmlParser();
virtual ~RapidXmlParser();
virtual void parse(const char *rawData, size_t bufSize) throw (exception);
virtual void parse(const std::string & rawData) throw (exception);
private:
xml_document<> m_doc;
};
}
#endif
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
6
],
[
8,
22
]
],
[
[
7,
7
]
]
] |
543872a6bde30e50d4d2d39cc212f10e89e19a9c | cbe040d6c5be2241d61c706f3c112f5da1b25006 | /Calculator/RuntimeException.h | 829f02f53e021036e1563e3fcfe12d1a96823a78 | [] | no_license | ilh19/315-calculator | d95346684cb7a63d803d5fd370243f0e216a3faa | c6762d277d07177a34f50bf28a16438f86664572 | refs/heads/master | 2020-06-05T00:17:13.711126 | 2011-04-05T02:45:46 | 2011-04-05T02:45:46 | 32,126,597 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 439 | h | #ifndef RUNTIMEEXCEPTION_H_
#define RUNTIMEEXCEPTION_H_
#include <string>
// generic run-time exception
class RuntimeException {
private:
std::string errorMsg;
public:
RuntimeException(const std::string& err) { errorMsg = err; }
std::string getMessage() const { return errorMsg; }
};
inline std::ostream& operator<<(std::ostream& out, const RuntimeException& e)
{
out << e.getMessage();
return out;
}
#endif | [
"irms19@7330a5c5-07fc-53ea-e431-edd981856d35",
"[email protected]@7330a5c5-07fc-53ea-e431-edd981856d35"
] | [
[
[
1,
9
],
[
11,
22
]
],
[
[
10,
10
]
]
] |
af7698da7754d509083252849bfbed4d0f80c58c | fcdddf0f27e52ece3f594c14fd47d1123f4ac863 | /terralib/src/DSDK/include/support/lt_ioSubStream.h | 0240ffa580f34dfda3a4c77383d33daa99505c85 | [] | no_license | radtek/terra-printer | 32a2568b1e92cb5a0495c651d7048db6b2bbc8e5 | 959241e52562128d196ccb806b51fda17d7342ae | refs/heads/master | 2020-06-11T01:49:15.043478 | 2011-12-12T13:31:19 | 2011-12-12T13:31:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,039 | h | /* $Id: lt_ioSubStream.h 5124 2006-10-27 11:40:40Z lubia $ */
/* //////////////////////////////////////////////////////////////////////////
// //
// This code is Copyright (c) 2004 LizardTech, Inc, 1008 Western Avenue, //
// Suite 200, Seattle, WA 98104. Unauthorized use or distribution //
// prohibited. Access to and use of this code is permitted only under //
// license from LizardTech, Inc. Portions of the code are protected by //
// US and foreign patents and other filings. All Rights Reserved. //
// //
////////////////////////////////////////////////////////////////////////// */
/* PUBLIC */
#ifndef LT_IOSUBSTREAM_H
#define LT_IOSUBSTREAM_H
#include "lt_ioStreamInf.h"
#include <stdio.h>
LT_BEGIN_NAMESPACE( LizardTech )
/**
* LTIOSubStream
*
* A SubStream is a stream which wraps another stream, but provides access
* to only a (contiguous) subset of the bytes of the parent stream -- without
* revealing any of the surrounding bytes.
*
* Consider the following situation: the MG2 decoder always assumes byte 0 of
* the image stream given to it is the start of the image, but you have an
* image embedded in some larger stream -- say from byte offset 100 to 2100.
* By creating a substream from the larger stream and giving that to the
* decoder, the decoder will be doing the right thing when it naively issues
* a "seek-to-beginning" request.
*
* Note that the SubStream does NOT take ownership of the stream given to it.
* The caller should duplicate() the main stream first, if needed. Closing
* the substream will close the parent stream, but deleting the substream will
* not delete the parent stream.
*
* Note that the results might be undefined if the parent or child stream is
* modified at any point -- try to avoid such situations.
*/
class LTIOSubStream : public LTIOStreamInf
{
public:
/**
* @name Construction, destruction, initialization
*/
//@{
/**
* Default Constructor
*/
LTIOSubStream();
/**
* Destructor
*/
virtual ~LTIOSubStream();
/**
* Initializes the stream
*
* @param stream the parent stream to be subsetted
* @param start the byte offset to be byte 0 of the subset stream
* @param end the byte offset to be the last byte of the subset
* stream: reading or writing past this byte will be
* handled as an EOF condition
* @param takeOwnership if true, this object will take ownership
* of \a stream and delete it
*/
virtual LT_STATUS initialize(LTIOStreamInf* stream,
lt_int64 start,
lt_int64 end,
bool takeOwnership=false);
/**
* @name Status accessors
*/
//@{
/**
* Indicates whether the stream is at the end of its data or not.
*
* @return true the stream is valid and at the end of its data.
* @retval false otherwise
*/
virtual bool isEOF();
/**
* @name Opening and closing
*/
//@{
/**
* Is the stream open?
*
* @retval true the stream is valid and in a state that allows data access.
* @retval false otherwise
*/
virtual bool isOpen();
/**
* Opens the stream.
*
* Opening a stream puts it in a state that allows data access based on cached
* initialization parameters.
*
* @retval LT_STS_IOStreamUninitialized The stream has not been initialized with enough
* information to open the stream
* @retval LT_STS_IOStreamInvalidState The the stream is already open
* @retval LT_STS_Success On success.
* @retval LT_STS_Failure Otherwise.
*/
virtual LT_STATUS open();
/**
* Closes the stream.
*
* Puts the stream in a state that does not allow data access. May
* free up resources, but only in such a way that doesn't inhibit
* successful future calls to open()
*
* @retval LT_STS_Success On success, or if the stream is already closed.
* @retval LT_STS_Failure Otherwise.
*/
virtual LT_STATUS close();
//@}
/**
* @name Data access
*/
//@{
/**
* Retrieve the specified number of bytes from the data source and
* place them in pDest.
*
* @param pDest buffer in which to store read data
* @param numBytes number of bytes to read from stream
*
* @retval numBytes The number of bytes actually read
*/
virtual lt_uint32 read( lt_uint8 *pDest, lt_uint32 numBytes );
/**
* Store the specified number of bytes in the data source.
*
* @param pSrc buffer from which to store data
* @param numBytes number of bytes to write to stream
*
* @retval numBytes number of bytes actually written
*/
virtual lt_uint32 write( const lt_uint8 *pSrc, lt_uint32 numBytes );
//@}
/**
* @name Positioning
*/
//@{
/**
* Moves the the data access position to origin + offset
*
* @param offset number of bytes from origin at which to the next read or write will take place
* @param origin place in stream from which to seek
*
* @retval LT_STS_IOStreamUnsupported The stream is not seekable
* @retval LT_STS_IOStreamInvalidArgs The offset and origin do not specify a valid location in the stream
* @retval LT_STS_Success On success
* @retval LT_STS_Failure Otherwise
*/
virtual LT_STATUS seek( lt_int64 offset, LTIOSeekDir origin );
/**
* Returns the current data access position as an offset from the start of the data
*
* @retval postion Number of bytes from the start of the data
* @retval -1 On error.
*/
virtual lt_int64 tell();
//@}
/**
* @name Other operations
*/
//@{
/**
* @brief Clone the stream
*
* Create new stream of the same type with the same initialization parameters.
* The transmission of these parameters is the responsibility of the derived type.
* The new stream should initially return false for isOpen().
*
* @retval NULL the stream could not be duplicated; valid LTIOStreamInf* otherwise.
*/
virtual LTIOStreamInf* duplicate();
virtual LT_STATUS getLastError() const;
virtual const char* getID() const;
//@}
protected:
/** cleanup method */
void cleanup();
LTIOStreamInf* m_stream;
bool m_ownsStream;
lt_int64 m_startOffset;
lt_int64 m_endOffset;
bool m_isEOF;
};
LT_END_NAMESPACE( LizardTech )
#endif // LT_IOSUBSTREAM_H
| [
"[email protected]@58180da6-ba8b-8960-36a5-00cc02a3ddec"
] | [
[
[
1,
233
]
]
] |
e9c5fb7fe18277e6933063894566a81f9841d52d | cfc9acc69752245f30ad3994cce0741120e54eac | /bikini/include/bikini/base/quat.hpp | db6cc4b37bc155edee100bd8027867bb60b563d4 | [] | no_license | Heartbroken/bikini-iii | 3b7852d1af722b380864ac87df57c37862eb759b | 93ffa5d43d9179b7c5e7f7c2df9df7dafd79a739 | refs/heads/master | 2020-03-28T00:41:36.281253 | 2009-04-30T14:58:10 | 2009-04-30T14:58:10 | 37,190,689 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 833 | hpp | /*---------------------------------------------------------------------------------------------*//*
Binary Kinematics 3 - C++ Game Programming Library
Copyright (C) 2008 Viktor Reutzky
[email protected]
*//*---------------------------------------------------------------------------------------------*/
#pragma once
/// quaternion template
template<typename _Type>
struct quat_ : matrix_<1, 4, _Type> {
inline quat_();
inline quat_(_Type _i, _Type _j, _Type _k, _Type _r);
inline const _Type i() const;
inline _Type& i();
inline const _Type j() const;
inline _Type& j();
inline const _Type k() const;
inline _Type& k();
inline const _Type r() const;
inline _Type& r();
};
typedef quat_<real> quat;
/// unit quaternion
const quat quat_1(r_0, r_0, r_0, r_1);
#include "quat.inl"
| [
"my.mass.storage@f4697e32-284f-0410-9ba2-936c71724aef"
] | [
[
[
1,
30
]
]
] |
c7329d1978add4f60e23e256ea6796c494ee6e2b | 4d838ba98a21fc4593652e66eb7df0fac6282ef6 | /CaveProj/GameScreen.cpp | 6f93cb32e0544eee6ae9f18d86a7f25035df1041 | [] | no_license | davidhart/ProceduralCaveEditor | 39ed0cf4ab4acb420fa2ad4af10f9546c138a83a | 31264591f2dcd250299049c826aeca18fc52880e | refs/heads/master | 2021-01-17T15:10:09.100572 | 2011-05-03T19:24:06 | 2011-05-03T19:24:06 | 69,302,913 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,870 | cpp | #include "GameScreen.h"
#include "RenderWindow.h"
#include "Input.h"
#include "MenuScreen.h"
GameScreen::GameScreen(const std::wstring& level) :
_player(_environment),
_level(level)
{
}
void GameScreen::Load(RenderWindow& renderWindow)
{
_player.Load(renderWindow);
_environment.Load(renderWindow.GetDevice(), _player.GetCamera());
_environment.Open(_level);
_chestCount.SetTotal(_environment.NumChests());
_chestCount.Load(renderWindow);
renderWindow.TrapCursor(true);
D3DX10_FONT_DESCW fd;
std::wstring facename(L"Tahoma");
wcscpy_s(fd.FaceName, facename.size()+1, facename.c_str());
fd.Width = 0;
fd.MipLevels = 1;
fd.CharSet = DEFAULT_CHARSET;
fd.Height = 72;
fd.OutputPrecision = OUT_DEFAULT_PRECIS;
fd.Italic = 0;
fd.Weight = FW_NORMAL;
fd.Quality = DEFAULT_QUALITY;
fd.PitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
D3DX10CreateFontIndirectW(renderWindow.GetDevice(), &fd, &_bigFont);
fd.Height = 36;
D3DX10CreateFontIndirectW(renderWindow.GetDevice(), &fd, &_smallFont);
}
void GameScreen::Unload(RenderWindow& renderWindow)
{
_environment.Unload();
_chestCount.Unload();
renderWindow.TrapCursor(false);
_bigFont->Release();
}
void GameScreen::Draw(RenderWindow& renderWindow)
{
_environment.Draw(renderWindow.GetDevice(), _player.GetCamera());
_chestCount.Draw(renderWindow);
if (_environment.NumChests() == 0)
{
RECT pos;
pos.top = 300;
pos.bottom = pos.top + 72;
pos.left = 0;
pos.right = renderWindow.GetSize().x;
_bigFont->DrawTextA(NULL, "Level Complete!", -1, &pos, DT_CENTER, D3DXCOLOR(1, 1, 1, 1));
pos.top = pos.bottom + 40;
pos.bottom = pos.top + 36;
_smallFont->DrawTextA(NULL, "Press return to continue", -1, &pos, DT_CENTER, D3DXCOLOR(1, 1, 1, 1));
}
}
void GameScreen::Update(float dt, RenderWindow& renderWindow)
{
const Input& input = renderWindow.GetInput();
Vector2f movement;
Vector2f rotation;
if (_environment.NumChests() > 0)
{
if (input.IsKeyDown(Input::KEY_A)) movement.x = -1;
if (input.IsKeyDown(Input::KEY_D)) movement.x = 1;
if (input.IsKeyDown(Input::KEY_W)) movement.y = 1;
if (input.IsKeyDown(Input::KEY_S)) movement.y = -1;
if (movement.Length() != 0)
{
movement.Normalise();
movement *= 0.3f;
}
rotation.x = input.GetMouseDistance().y * 0.003f;
rotation.y = input.GetMouseDistance().x* 0.003f;
}
_player.Update(movement, rotation, dt, false, input.IsKeyJustPressed(Input::KEY_SPACE));
_environment.Update(dt);
for (int i = 0; i <_environment.NumChests(); ++i)
{
if(_player.NearChest(_environment.GetChestPosition(i)))
{
_environment.RemoveChest(i);
_chestCount.OnCollected();
}
}
if (_environment.NumChests() == 0 && input.IsKeyJustPressed(Input::KEY_RETURN))
{
_parent->NewScreen(new MenuScreen());
}
} | [
"[email protected]"
] | [
[
[
1,
108
]
]
] |
d9530535b477524daa554652d9d40dd37fdee7d9 | 89dbc6ceab3e4e43aeaf0a5a5517b63fcf0c1c39 | /extras/symbian/SymbianSockets.cpp | 4852553a11b9a09c90d3b74e49276458625b98bc | [] | no_license | fredreichbier/io | e3dd55d957e96d2fd5292db2c680d511c7f36617 | 299956aaf6ab035865e955d849367ef4eeb8c009 | refs/heads/master | 2021-01-18T08:50:23.962379 | 2009-04-11T00:18:06 | 2009-04-11T00:18:06 | 97,877 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,038 | cpp | #include <e32base.h>
#include <f32file.h>
#include <in_sock.h>
extern "C"
{
#include "IoState.h"
#include "IoNIL.h"
#include "IoMessage.h"
#include "IoNumber.h"
}
#include "SymbianMain.h"
#include "SymbianSockets.h"
#define min(a,b) ((a) < (b) ? (a) : (b))
#define SOCKET_BUFFER_SIZE 2048
class InternalSocket
{
public:
RSocket socket;
char buffer[SOCKET_BUFFER_SIZE];
int bufferTop;
int bufferBottom;
InternalSocket() :
bufferTop(0),
bufferBottom(0)
{
memset(buffer, 0, sizeof(buffer));
}
void ResetBuffer()
{
bufferTop = 0;
bufferBottom = 0;
memset(buffer, 0, sizeof(buffer));
}
TInt ReadIntoBuffer()
{
TRequestStatus status;
TPtr8 ptr8((TUint8*)buffer, sizeof(buffer), sizeof(buffer));
TSockXfrLength tlen;
socket.RecvOneOrMore(ptr8, 0, status, tlen);
User::WaitForRequest(status);
bufferTop = tlen();
bufferBottom = 0;
return status.Int();
}
TInt ReadChar(char* ch)
{
TInt status = KErrNone;
if(bufferTop == bufferBottom)
{
status = ReadIntoBuffer();
}
if(status == KErrNone)
{
*ch = buffer[bufferBottom++];
}
return status;
}
TInt ReadAllChars(char* ch, int length)
{
TInt status = KErrNone;
while(length > 0)
{
if(bufferTop == bufferBottom)
{
status = ReadIntoBuffer();
if(status != KErrNone)
break;
}
if(bufferTop - bufferBottom >= length)
{
memcpy(ch, buffer + bufferBottom, length);
bufferBottom += length;
length = 0;
}
else
{
int l = min(length, bufferTop - bufferBottom);
memcpy(ch, buffer + bufferBottom, l);
length -= l;
ch += l;
bufferBottom += l;
}
}
return status;
}
TInt ReadLine(char* ch, int length)
{
TInt status = KErrNone;
int state = 0;
while(length > 0)
{
if(bufferTop == bufferBottom)
{
status = ReadIntoBuffer();
if(status != KErrNone)
break;
}
if(bufferTop - bufferBottom >= length)
{
char* start = buffer + bufferBottom;
char* end = buffer + length;
while(start != end)
{
char c = *start++;
if(c == 13)
{
state = 1;
}
else if(c == 10)
{
if(state == 1)
{
state = 2;
bufferBottom = start - buffer;
length = 0;
return status;
break;
}
else
{
*ch++ = c;
}
}
else
{
if(state == 1)
{
*ch++ = 13;
}
else
{
*ch++ = c;
}
state = 0;
}
}
bufferBottom += length;
length = 0;
}
else
{
int l = min(length, bufferTop - bufferBottom);
char* start = buffer + bufferBottom;
char* end = buffer + l;
while(state != 2 && start != end)
{
char c = *start++;
if(c == 13)
{
state = 1;
}
else if(c == 10)
{
if(state == 1)
{
state = 2;
bufferBottom = start - buffer;
length = 0;
return status;
break;
}
else
{
*ch++ = c;
}
}
else
{
if(state == 1)
{
*ch++ = 13;
}
else
{
*ch++ = c;
}
state = 0;
}
}
length -= l;
ch += l;
bufferBottom += l;
}
}
return status;
}
TInt ReadOneOrMore(char* ch, int length)
{
TInt status = KErrNone;
if(bufferTop == bufferBottom)
{
status = ReadIntoBuffer();
if(status != KErrNone)
return status;
}
if(bufferTop - bufferBottom >= length)
{
memcpy(ch, buffer + bufferBottom, length);
bufferBottom += length;
}
else
{
int l = min(length, bufferTop - bufferBottom);
memcpy(ch, buffer + bufferBottom, l);
bufferBottom += l;
}
return status;
}
};
class CConnectingSocket;
class CReadLineSocket;
struct IoSocket
{
unsigned char color;
IoValue *previous;
IoValue *next;
IoTag *tag;
InternalSocket* socket;
char* host;
int port;
bool isConnected;
char* lineRead;
CConnectingSocket *activeConnect;
CReadLineSocket* activeReadLine;
};
IoValue *IoSocket_clone(IoSocket *self, IoValue *locals, IoMessage *m);
void IoSocket_free(IoSocket *self);
char *IoSocket_name(IoSocket *self);
void IoSocket_mark(IoSocket *self);
IoValue *IoSocket_host(IoSocket *self, IoValue *locals, IoMessage *m);
IoValue *IoSocket_host_(IoSocket *self, IoValue *locals, IoMessage *m);
IoValue *IoSocket_port(IoSocket *self, IoValue *locals, IoMessage *m);
IoValue *IoSocket_port_(IoSocket *self, IoValue *locals, IoMessage *m);
IoValue *IoSocket_open(IoSocket *self, IoValue *locals, IoMessage *m);
IoValue *IoSocket_connect(IoSocket *self, IoValue *locals, IoMessage *m);
IoValue *IoSocket_asyncConnect(IoSocket *self, IoValue *locals, IoMessage *m);
IoValue *IoSocket_waitForConnect(IoSocket *self, IoValue *locals, IoMessage *m);
IoValue *IoSocket_isConnected(IoSocket *self, IoValue *locals, IoMessage *m);
IoValue *IoSocket_isConnected_(IoSocket *self, IoValue *locals, IoMessage *m);
IoValue *IoSocket_write(IoSocket *self, IoValue *locals, IoMessage *m);
IoValue *IoSocket_writeLine(IoSocket *self, IoValue *locals, IoMessage *m);
IoValue *IoSocket_read(IoSocket *self, IoValue *locals, IoMessage *m);
IoValue *IoSocket_readLine(IoSocket *self, IoValue *locals, IoMessage *m);
IoValue *IoSocket_close(IoSocket *self, IoValue *locals, IoMessage *m);
IoValue *IoSocket_isLineRead(IoSocket *self, IoValue *locals, IoMessage *m);
IoValue *IoSocket_asyncReadLine(IoSocket *self, IoValue *locals, IoMessage *m);
IoValue *IoSocket_waitForReadLine(IoSocket *self, IoValue *locals, IoMessage *m);
IoValue *IoSocket_getLineRead(IoSocket *self, IoValue *locals, IoMessage *m);
class CConnectingSocket : public CActive
{
private:
InternalSocket* socket;
IoSocket* ioSocket;
int state;
RHostResolver resolver;
TNameEntry entry;
public:
static CConnectingSocket* NewL(InternalSocket* s, IoSocket* ios)
{
CConnectingSocket* self = new (ELeave) CConnectingSocket(s, ios);
self->ConstructL();
return self;
}
CConnectingSocket(InternalSocket* s, IoSocket* ios) :
CActive(CActive::EPriorityStandard),
socket(s),
ioSocket(ios),
state(0)
{
}
~CConnectingSocket()
{
Cancel();
}
void ConstructL()
{
CActiveScheduler::Add(this);
}
void StartConnectL()
{
IoState* state = (IoState*)ioSocket->tag->state;
CConsoleControl* control = (CConsoleControl*)IoState_userData(state);
TInt result = resolver.Open(control->socketServer, 2048, 17);
if(result != 0)
{
Cancel();
IoState_error_description_(state, "IoSocket.connect", "Could not open resolver: '%d'\n", result);
}
else
{
TPtr16 ptr16 = stringToPtr16(ioSocket->host);
resolver.GetByName(ptr16, entry, iStatus);
SetActive();
}
}
void RunL()
{
if(state == 0)
{
if(iStatus.Int() != 0)
{
Cancel();
IoState_error_description_((IoState*)ioSocket->tag->state, "IoSocket.connect", "resolver.GetByName: '%d'\n", iStatus.Int());
}
state = 1;
TNameRecord record(entry());
TSockAddr addr(record.iAddr);
addr.SetPort(ioSocket->port);
resolver.Close();
socket->socket.Connect(addr, iStatus);
SetActive();
}
else if(state == 1)
{
ioSocket->isConnected = 1;
if(iStatus.Int() != 0)
{
Cancel();
IoState_error_description_((IoState*)ioSocket->tag->state, "IoSocket.connect", "socket.connect: '%d'\n", iStatus.Int());
}
}
}
void DoCancel()
{
if(state == 0)
{
resolver.Close();
}
socket->socket.CancelAll();
socket->socket.Close();
}
};
#define READ_STATE_BUFFER_UNDERFLOW 1
#define READ_STATE_BUFFER_READ 2
#define READ_STATE_BUFFER_POST_UNDERFLOW 3
#define READ_STATE_BUFFER_COMPLETE 4
class CReadLineSocket : public CActive
{
private:
InternalSocket* socket;
IoSocket* ioSocket;
char* originalBuffer;
char* buffer;
int length;
int state;
int lineState;
TSockXfrLength tlen;
public:
static CReadLineSocket* NewL(InternalSocket* s, IoSocket* ios, char* buffer, int length)
{
CReadLineSocket* self = new (ELeave) CReadLineSocket(s, ios, buffer, length);
self->ConstructL();
return self;
}
CReadLineSocket(InternalSocket* s, IoSocket* ios, char* b, int len) :
CActive(CActive::EPriorityStandard),
socket(s),
ioSocket(ios),
state(0),
lineState(0),
buffer(b),
originalBuffer(b),
length(len)
{
}
~CReadLineSocket()
{
Cancel();
}
void ConstructL()
{
CActiveScheduler::Add(this);
}
void CheckBuffer()
{
if(length <= 0)
{
state = READ_STATE_BUFFER_COMPLETE;
}
else if(socket->bufferTop == socket->bufferBottom)
{
state = READ_STATE_BUFFER_UNDERFLOW;
}
else
{
state = READ_STATE_BUFFER_READ;
}
TRequestStatus* tempStatus = &iStatus;
User::RequestComplete(tempStatus, KErrNone);
}
void StartReadLineL()
{
SetActive();
CheckBuffer();
}
void RunL()
{
switch(state)
{
case READ_STATE_BUFFER_UNDERFLOW:
{
TPtr8 ptr8((TUint8*)socket->buffer, SOCKET_BUFFER_SIZE, SOCKET_BUFFER_SIZE);
socket->socket.RecvOneOrMore(ptr8, 0, iStatus, tlen);
state = READ_STATE_BUFFER_POST_UNDERFLOW;
SetActive();
break;
}
case READ_STATE_BUFFER_POST_UNDERFLOW:
{
socket->bufferTop = tlen();
socket->bufferBottom = 0;
state = READ_STATE_BUFFER_READ;
SetActive();
TRequestStatus* tempStatus = &iStatus;
User::RequestComplete(tempStatus, KErrNone);
break;
}
case READ_STATE_BUFFER_READ:
{
if(length == 0)
{
state = READ_STATE_BUFFER_COMPLETE;
SetActive();
TRequestStatus* tempStatus = &iStatus;
User::RequestComplete(tempStatus, KErrNone);
break;
}
else if(socket->bufferTop == socket->bufferBottom)
{
state = READ_STATE_BUFFER_UNDERFLOW;
SetActive();
TRequestStatus* tempStatus = &iStatus;
User::RequestComplete(tempStatus, KErrNone);
break;
}
else if(socket->bufferTop - socket->bufferBottom >= length)
{
char* start = socket->buffer + socket->bufferBottom;
char* end = socket->buffer + length;
while(start != end)
{
char c = *start++;
if(c == 13)
{
lineState = 1;
}
else if(c == 10)
{
if(lineState == 1)
{
lineState = 2;
socket->bufferBottom = start - socket->buffer;
length = 0;
state = READ_STATE_BUFFER_COMPLETE;
SetActive();
TRequestStatus* tempStatus = &iStatus;
User::RequestComplete(tempStatus, KErrNone);
return;
}
else
{
*buffer++ = c;
}
}
else
{
if(lineState == 1)
{
*buffer++ = 13;
}
else
{
*buffer++ = c;
}
state = 0;
}
}
socket->bufferBottom += length;
length = 0;
state = READ_STATE_BUFFER_COMPLETE;
SetActive();
TRequestStatus* tempStatus = &iStatus;
User::RequestComplete(tempStatus, KErrNone);
return;
}
else
{
int l = min(length, socket->bufferTop - socket->bufferBottom);
char* start = socket->buffer + socket->bufferBottom;
char* end = socket->buffer + l;
while(lineState != 2 && start != end)
{
char c = *start++;
if(c == 13)
{
lineState = 1;
}
else if(c == 10)
{
if(lineState == 1)
{
lineState = 2;
socket->bufferBottom = start - socket->buffer;
state = READ_STATE_BUFFER_COMPLETE;
SetActive();
TRequestStatus* tempStatus = &iStatus;
User::RequestComplete(tempStatus, KErrNone);
return;
}
else
{
*buffer++ = c;
}
}
else
{
if(lineState == 1)
{
*buffer++ = 13;
}
else
{
*buffer++ = c;
}
lineState = 0;
}
}
length -= l;
buffer += l;
socket->bufferBottom += l;
}
state = READ_STATE_BUFFER_READ;
SetActive();
TRequestStatus* tempStatus = &iStatus;
User::RequestComplete(tempStatus, KErrNone);
break;
}
case READ_STATE_BUFFER_COMPLETE:
{
ioSocket->lineRead = originalBuffer;
break;
}
}
}
void DoCancel()
{
socket->socket.CancelAll();
}
};
IoTag *IoSocket_initTagWithId_(void *ioState, int tagId)
{
IoTag *tag = IoTag_new();
tag->state = ioState;
tag->freeCallback = (TagFreeCallback *)IoSocket_free;
tag->nameCallback = (TagNameCallback *)IoSocket_name;
tag->markCallback = (TagMarkCallback *)IoSocket_mark;
Tag_addMethod(tag, "clone", (void*)IoSocket_clone);
Tag_addMethod(tag, "setHost", (void*)IoSocket_host_);
Tag_addMethod(tag, "host", (void*)IoSocket_host);
Tag_addMethod(tag, "setPort", (void*)IoSocket_port_);
Tag_addMethod(tag, "port", (void*)IoSocket_port);
Tag_addMethod(tag, "open", (void*)IoSocket_open);
Tag_addMethod(tag, "connect", (void*)IoSocket_connect);
Tag_addMethod(tag, "asyncConnect", (void*)IoSocket_asyncConnect);
Tag_addMethod(tag, "waitForConnect", (void*)IoSocket_waitForConnect);
Tag_addMethod(tag, "isConnected", (void*)IoSocket_isConnected);
Tag_addMethod(tag, "setIsConnected", (void*)IoSocket_isConnected_);
Tag_addMethod(tag, "write", (void*)IoSocket_write);
Tag_addMethod(tag, "writeLine", (void*)IoSocket_writeLine);
Tag_addMethod(tag, "read", (void*)IoSocket_read);
Tag_addMethod(tag, "readLine", (void*)IoSocket_readLine);
Tag_addMethod(tag, "close", (void*)IoSocket_close);
Tag_addMethod(tag, "isLineRead", (void*)IoSocket_isLineRead);
Tag_addMethod(tag, "asyncReadLine", (void*)IoSocket_asyncReadLine);
Tag_addMethod(tag, "waitForReadLine", (void*)IoSocket_waitForReadLine);
Tag_addMethod(tag, "getLineRead", (void*)IoSocket_getLineRead);
return tag;
}
IoSocket *IoSocket_new(void *state)
{
IoTag *tag = IoState_tagWithInitFunction_((IoState*)state, IoSocket_initTagWithId_);
IoSocket *self = (IoSocket *)malloc(sizeof(IoSocket));
memset(self, 0x0, sizeof(IoSocket));
self->tag = tag;
self->color = IOVALUE_WHITE();
self->socket = new InternalSocket();
self->host = strdup("localhost");
self->isConnected = false;
self->lineRead = 0;
self->activeConnect = 0;
self->activeReadLine = 0;
IoState_addValue_((IoState*)self->tag->state, (IoValue *)self);
return self;
}
IoValue *IoSocket_clone(IoSocket *self, IoValue *locals, IoMessage *m)
{
IoSocket *newSocket = IoSocket_new(self->tag->state);
newSocket->host = strdup(self->host);
return (IoValue *)newSocket;
}
void IoSocket_free(IoSocket *self)
{
if(self->activeConnect)
{
delete self->activeConnect;
self->activeConnect = 0;
}
self->socket->socket.Close();
delete self->socket;
self->socket = 0;
free(self->host);
free(self);
}
char *IoSocket_name(IoSocket *self)
{
return "Socket";
}
void IoSocket_mark(IoSocket *self)
{
}
IoValue *IoSocket_host(IoSocket *self, IoValue *locals, IoMessage *m)
{
return (IoValue *)USTRING(self->host);
}
IoValue *IoSocket_host_(IoSocket *self, IoValue *locals, IoMessage *m)
{
IoString *host = (IoString*)IoMessage_locals_stringArgAt_(m, locals, 0);
self->host = strdup(CSTRING(host));
return (IoValue *)self;
}
IoValue *IoSocket_port(IoSocket *self, IoValue *locals, IoMessage *m)
{
return (IoValue *)IONUMBER(self->port);
}
IoValue *IoSocket_port_(IoSocket *self, IoValue *locals, IoMessage *m)
{
IoNumber *port = (IoNumber*)IoMessage_locals_numberArgAt_(m, locals, 0);
self->port = IoNumber_asInt(port);
return (IoValue *)self;
}
IoValue *IoSocket_isConnected(IoSocket *self, IoValue *locals, IoMessage *m)
{
return (IoValue *)IONUMBER(self->isConnected);
}
IoValue *IoSocket_isConnected_(IoSocket *self, IoValue *locals, IoMessage *m)
{
IoNumber *isConnected = (IoNumber*)IoMessage_locals_numberArgAt_(m, locals, 0);
self->isConnected = IoNumber_asInt(isConnected);
return (IoValue *)self;
}
IoValue *IoSocket_open(IoSocket *self, IoValue *locals, IoMessage *m)
{
self->socket->ResetBuffer();
IoState* state = (IoState*)self->tag->state;
CConsoleControl* control = (CConsoleControl*)IoState_userData(state);
return (IoValue *)IONUMBER(self->socket->socket.Open(control->socketServer, KAfInet, KSockStream, KProtocolInetTcp));
}
IoValue *IoSocket_connect(IoSocket *self, IoValue *locals, IoMessage *m)
{
if(self->activeConnect)
{
delete self->activeConnect;
}
self->activeConnect = CConnectingSocket::NewL(self->socket, self);
self->activeConnect->StartConnectL();
IoState* state = (IoState*)self->tag->state;
while(!self->isConnected)
{
IoState_yield(state);
}
return (IoValue*)self;
}
IoValue *IoSocket_asyncConnect(IoSocket *self, IoValue *locals, IoMessage *m)
{
if(self->activeConnect)
{
delete self->activeConnect;
}
self->activeConnect = CConnectingSocket::NewL(self->socket, self);
self->activeConnect->StartConnectL();
return (IoValue*)self;
}
IoValue *IoSocket_waitForConnect(IoSocket *self, IoValue *locals, IoMessage *m)
{
IoState* state = (IoState*)self->tag->state;
while(!self->isConnected)
{
IoState_yield(state);
}
return (IoValue*)self;
}
IoValue *IoSocket_asyncReadLine(IoSocket *self, IoValue *locals, IoMessage *m)
{
if(self->activeReadLine)
{
delete self->activeReadLine;
}
IoNumber *size = (IoNumber*)IoMessage_locals_numberArgAt_(m, locals, 0);
int trueSize = IoNumber_asInt(size);
char* buffer = (char*)malloc(trueSize + 1);
memset(buffer, 0, trueSize + 1);
self->activeReadLine = CReadLineSocket::NewL(self->socket, self, buffer, trueSize);
self->activeReadLine->StartReadLineL();
return (IoValue*)self;
}
IoValue *IoSocket_waitForReadLine(IoSocket *self, IoValue *locals, IoMessage *m)
{
IoState* state = (IoState*)self->tag->state;
while(!self->lineRead)
{
IoState_yield(state);
}
IoValue* value = (IoValue*)USTRING(self->lineRead);
free(self->lineRead);
self->lineRead = 0;
return (IoValue*)value;
}
IoValue *IoSocket_isLineRead(IoSocket *self, IoValue *locals, IoMessage *m)
{
bool value = self->lineRead != 0;
return (IoValue *)IONUMBER(value);
}
IoValue *IoSocket_getLineRead(IoSocket *self, IoValue *locals, IoMessage *m)
{
return (IoValue*)USTRING(self->lineRead);
}
IoValue *IoSocket_close(IoSocket *self, IoValue *locals, IoMessage *m)
{
if(self->activeConnect)
{
delete self->activeConnect;
self->activeConnect = 0;
}
if(self->activeReadLine)
{
delete self->activeReadLine;
self->activeReadLine = 0;
}
self->socket->socket.Close();
return (IoValue*)self;
}
IoValue *IoSocket_write(IoSocket *self, IoValue *locals, IoMessage *m)
{
IoState* state = (IoState*)self->tag->state;
IoString *ioText = (IoString*)IoMessage_locals_stringArgAt_(m, locals, 0);
char* text = CSTRING(ioText);
int len = strlen(text);
TRequestStatus status;
TPtr8 ptr8((TUint8*)text, len, len);
self->socket->socket.Write(ptr8, status);
User::WaitForRequest(status);
if(status.Int() != 0)
{
IoState_error_description_(state, "IoSocket.write", "RSocket.Write: '%d'\n", status.Int());
}
return (IoValue*)self;
}
IoValue *IoSocket_writeLine(IoSocket *self, IoValue *locals, IoMessage *m)
{
IoState* state = (IoState*)self->tag->state;
IoString *ioText = (IoString*)IoMessage_locals_stringArgAt_(m, locals, 0);
char* text = strdup(CSTRING(ioText));
int len = strlen(text);
text = (char*)realloc(text, len + 3);
text[len] = 13;
text[len + 1] = 10;
text[len + 2] = 0;
TRequestStatus status;
TPtr8 ptr8((TUint8*)text, len + 2, len + 3);
self->socket->socket.Write(ptr8, status);
free(text);
User::WaitForRequest(status);
if(status.Int() != 0)
{
IoState_error_description_(state, "IoSocket.write", "RSocket.Write: '%d'\n", status.Int());
}
return (IoValue*)self;
}
IoValue *IoSocket_read(IoSocket *self, IoValue *locals, IoMessage *m)
{
IoNumber *size = (IoNumber*)IoMessage_locals_numberArgAt_(m, locals, 0);
IoState* state = (IoState*)self->tag->state;
int trueSize = IoNumber_asInt(size);
char* buffer = (char*)malloc(trueSize + 1);
memset(buffer, 0, trueSize + 1);
TInt status = self->socket->ReadOneOrMore(buffer, trueSize);
if(status != 0)
{
IoState_error_description_(state, "IoSocket.read", "RSocket.Read: '%d'\n", status);
}
IoValue* result = (IoValue*)USTRING(buffer);
free(buffer);
return result;
}
IoValue *IoSocket_readLine(IoSocket *self, IoValue *locals, IoMessage *m)
{
IoNumber *size = (IoNumber*)IoMessage_locals_numberArgAt_(m, locals, 0);
IoState* state = (IoState*)self->tag->state;
if(self->activeReadLine)
{
delete self->activeReadLine;
self->activeReadLine = 0;
}
int trueSize = IoNumber_asInt(size);
char* buffer = (char*)malloc(trueSize + 1);
memset(buffer, 0, trueSize + 1);
self->activeReadLine = CReadLineSocket::NewL(self->socket, self, buffer, trueSize);
self->activeReadLine->StartReadLineL();
while(!self->lineRead)
{
IoState_yield(state);
}
IoValue* value = (IoValue*)USTRING(self->lineRead);
free(self->lineRead);
self->lineRead = 0;
return (IoValue*)value;
}
void initSocketAddons(IoState* state)
{
IoState_addTagWithInitFunc_(state, IoSocket_initTagWithId_);
IoObject_setSlot_to_(state->lobby, IoState_stringWithCString_(state, "Socket"), IoSocket_new(state));
}
| [
"[email protected]"
] | [
[
[
1,
917
]
]
] |
7f46f5ea210cb09f1f1a1db57cb372045b8c9527 | 8a3fce9fb893696b8e408703b62fa452feec65c5 | /AutoBall/AutoBall/App/FootBallPitch.cpp | 536d636f4feab1cf0f8da47253b31935fd774b7e | [] | no_license | win18216001/tpgame | bb4e8b1a2f19b92ecce14a7477ce30a470faecda | d877dd51a924f1d628959c5ab638c34a671b39b2 | refs/heads/master | 2021-04-12T04:51:47.882699 | 2011-03-08T10:04:55 | 2011-03-08T10:04:55 | 42,728,291 | 0 | 2 | null | null | null | null | GB18030 | C++ | false | false | 6,852 | cpp | #include "Stdafx.h"
#include "FootBallPitch.h"
#include "FootBallTeam.h"
#include "Goal.h"
#include "TimeCount.h"
#include "SpotCalculator.h"
#include "Steering.h"
#include "Entity/BasePlayer.h"
#include "Entity/FootBall.h"
#include "Entity/GoalKeeper.h"
#include "Entity/FootBaller.h"
#include "Entity/EntityManager.h"
#include "StateAi/StateMachine.h"
#include "Messageing/MessageDispatcher.h"
#include "../Public/Singleton.h"
#include "../Render/VGdi.h"
#include "../Render/Vector2D.h"
#include "../Render/MathGeo.h"
const int NumRegionsHorizontal = 12;
const int NumRegionsVertical = 4;
FootBallPitch::FootBallPitch(int cx, int cy):m_cxClient(cx),
m_cyClient(cy),
m_bPaused(false),
m_bGoalKeeperHasBall(false),
m_Regions(NumRegionsHorizontal*NumRegionsVertical),
m_bGameOn(true)
{
m_pPlayingArea = new Region(60, 30, cx-60, cy-30);
CreateRegions(PlayingArea()->Width() / (double)NumRegionsHorizontal,
PlayingArea()->Height() / (double)NumRegionsVertical);
m_pRedGoal = new Goal(Vector2D( m_pPlayingArea->Left(), (cy-GetInstObj(CGameSetup).GoalWidth)/2),
Vector2D(m_pPlayingArea->Left(), cy - (cy-GetInstObj(CGameSetup).GoalWidth)/2),
Vector2D(1,0));
m_pBlueGoal = new Goal( Vector2D( m_pPlayingArea->Right(), (cy-GetInstObj(CGameSetup).GoalWidth)/2),
Vector2D(m_pPlayingArea->Right(), cy - (cy-GetInstObj(CGameSetup).GoalWidth)/2),
Vector2D(-1,0));
m_pBall = new FootBall(Vector2D((double)m_cxClient/2.0, (double)m_cyClient/2.0),
GetInstObj(CGameSetup).BallSize,
GetInstObj(CGameSetup).BallMass,
m_vecWalls);
m_pRedTeam = new FootBallTeam(m_pRedGoal, m_pBlueGoal, this, FootBallTeam::red);
m_pBlueTeam = new FootBallTeam(m_pBlueGoal, m_pRedGoal, this, FootBallTeam::blue);
m_pRedTeam->SetOpponents(m_pBlueTeam);
m_pBlueTeam->SetOpponents(m_pRedTeam);
Vector2D TopLeft(m_pPlayingArea->Left(), m_pPlayingArea->Top());
Vector2D TopRight(m_pPlayingArea->Right(), m_pPlayingArea->Top());
Vector2D BottomRight(m_pPlayingArea->Right(), m_pPlayingArea->Bottom());
Vector2D BottomLeft(m_pPlayingArea->Left(), m_pPlayingArea->Bottom());
m_vecWalls.push_back(Wall2D(BottomLeft, m_pRedGoal->RightPost()));
m_vecWalls.push_back(Wall2D(m_pRedGoal->LeftPost(), TopLeft));
m_vecWalls.push_back(Wall2D(TopLeft, TopRight));
m_vecWalls.push_back(Wall2D(TopRight, m_pBlueGoal->LeftPost()));
m_vecWalls.push_back(Wall2D(m_pBlueGoal->RightPost(), BottomRight));
m_vecWalls.push_back(Wall2D(BottomRight, BottomLeft));
}
FootBallPitch::~FootBallPitch()
{
SAFE_DELETE( m_pBall );
SAFE_DELETE( m_pRedTeam );
SAFE_DELETE( m_pBlueTeam);
SAFE_DELETE( m_pRedGoal );
SAFE_DELETE( m_pBlueGoal);
SAFE_DELETE( m_pPlayingArea );
for (unsigned int i=0; i<m_Regions.size(); ++i)
{
SAFE_DELETE( m_Regions[i] );
}
}
void FootBallPitch::Update()
{
if (m_bPaused) return;
static int tick = 0;
m_pBall->Update();
m_pRedTeam->Update();
m_pBlueTeam->Update();
if (m_pBlueGoal->Scored(m_pBall) || m_pRedGoal->Scored(m_pBall))
{
m_bGameOn = false;
m_pBall->PlaceAtPosition(Vector2D((double)m_cxClient/2.0, (double)m_cyClient/2.0));
m_pRedTeam->GetFSM()->ChangeState(&GetInstObj(PrepareForKickOff));
m_pBlueTeam->GetFSM()->ChangeState(&GetInstObj(PrepareForKickOff));
}
}
void FootBallPitch::CreateRegions(double width, double height)
{
int idx = m_Regions.size()-1;
for (int col=0; col<NumRegionsHorizontal; ++col)
{
for (int row=0; row<NumRegionsVertical; ++row)
{
m_Regions[idx--] = new Region(PlayingArea()->Left()+col*width,
PlayingArea()->Top()+row*height,
PlayingArea()->Left()+(col+1)*width,
PlayingArea()->Top()+(row+1)*height,
idx);
}
}
}
bool FootBallPitch::Render()
{
//render regions
if (GetInstObj(CGameSetup).bRegions)
{
for (unsigned int r=0; r<m_Regions.size(); ++r)
{
m_Regions[r]->Render(true);
}
}
//GetInstObj(CGDI).HollowBrush();
GetInstObj(CGDI).RedPen();
GetInstObj(CGDI).HatchRBrush();
GetInstObj(CGDI).Rect(m_pPlayingArea->Left()-40, (m_cyClient-GetInstObj(CGameSetup).GoalWidth)/2, m_pPlayingArea->Left(), m_cyClient - (m_cyClient-GetInstObj(CGameSetup).GoalWidth)/2);
GetInstObj(CGDI).Rect(m_pPlayingArea->Left()-39, (m_cyClient-GetInstObj(CGameSetup).GoalWidth)/2+1, m_pPlayingArea->Left()-1, m_cyClient - (m_cyClient-GetInstObj(CGameSetup).GoalWidth)/2-1);
GetInstObj(CGDI).HatchXBrush();
GetInstObj(CGDI).Rect(m_pPlayingArea->Left(), (m_cyClient-GetInstObj(CGameSetup).GoalWidth)/2-100, m_pPlayingArea->Left()+100, m_cyClient - (m_cyClient-GetInstObj(CGameSetup).GoalWidth)/2+100);
GetInstObj(CGDI).Rect(m_pPlayingArea->Left()+1, (m_cyClient-GetInstObj(CGameSetup).GoalWidth)/2-99, m_pPlayingArea->Left()+99, m_cyClient - (m_cyClient-GetInstObj(CGameSetup).GoalWidth)/2+99);
GetInstObj(CGDI).BluePen();
GetInstObj(CGDI).HatchLBrush();
GetInstObj(CGDI).Rect(m_pPlayingArea->Right(), (m_cyClient-GetInstObj(CGameSetup).GoalWidth)/2, m_pPlayingArea->Right()+40, m_cyClient - (m_cyClient-GetInstObj(CGameSetup).GoalWidth)/2);
GetInstObj(CGDI).Rect(m_pPlayingArea->Right()+1, (m_cyClient-GetInstObj(CGameSetup).GoalWidth)/2+1, m_pPlayingArea->Right()+39, m_cyClient - (m_cyClient-GetInstObj(CGameSetup).GoalWidth)/2-1);
GetInstObj(CGDI).HatchXBrush();
GetInstObj(CGDI).Rect(m_pPlayingArea->Right()-100, (m_cyClient-GetInstObj(CGameSetup).GoalWidth)/2-100, m_pPlayingArea->Right(), m_cyClient - (m_cyClient-GetInstObj(CGameSetup).GoalWidth)/2+100);
GetInstObj(CGDI).Rect(m_pPlayingArea->Right()-99, (m_cyClient-GetInstObj(CGameSetup).GoalWidth)/2-99, m_pPlayingArea->Right()-1, m_cyClient - (m_cyClient-GetInstObj(CGameSetup).GoalWidth)/2+99);
//render the pitch markings
GetInstObj(CGDI).ClearBrush();
GetInstObj(CGDI).WhitePen();
GetInstObj(CGDI).Circle(m_pPlayingArea->Center(), m_pPlayingArea->Width() * 0.125);
GetInstObj(CGDI).Line(m_pPlayingArea->Center().x, m_pPlayingArea->Top(), m_pPlayingArea->Center().x, m_pPlayingArea->Bottom());
GetInstObj(CGDI).WhiteBrush();
GetInstObj(CGDI).Circle(m_pPlayingArea->Center(), 3.0);
//the ball
GetInstObj(CGDI).WhitePen();
GetInstObj(CGDI).WhiteBrush();
m_pBall->Render();
//Render the teams
m_pRedTeam->Render();
m_pBlueTeam->Render();
//render the walls
GetInstObj(CGDI).WhitePen();
for (unsigned int w=0; w<m_vecWalls.size(); ++w)
{
m_vecWalls[w].Render();
}
//show the score
GetInstObj(CGDI).TextColor(CGDI::red);
GetInstObj(CGDI).TextAtPos((m_cxClient/2)-80, 10, "红队得分: " + ttos(m_pBlueGoal->NumGoalsScored()));
GetInstObj(CGDI).TextColor(CGDI::blue);
GetInstObj(CGDI).TextAtPos((m_cxClient/2)+50, 10, "蓝队得分: " + ttos(m_pRedGoal->NumGoalsScored()));
return true;
} | [
"[email protected]"
] | [
[
[
1,
191
]
]
] |
ef1b35b052b8d8e5e0cd3c64c30d2a6f736791a6 | f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0 | /Depend/MyGUI/MyGUIEngine/include/MyGUI_WidgetToolTip.h | 7152b05f5f2a6c4edec6fe8a0d919ffc8290e181 | [] | no_license | lxinhcn/starworld | 79ed06ca49d4064307ae73156574932d6185dbab | 86eb0fb8bd268994454b0cfe6419ffef3fc0fc80 | refs/heads/master | 2021-01-10T07:43:51.858394 | 2010-09-15T02:38:48 | 2010-09-15T02:38:48 | 47,859,019 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,337 | h | /*!
@file
@author Albert Semenov
@date 07/2008
*/
/*
This file is part of MyGUI.
MyGUI is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MyGUI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with MyGUI. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __MYGUI_WIDGET_TOOLTIP_H__
#define __MYGUI_WIDGET_TOOLTIP_H__
#include "MyGUI_Prerequest.h"
#include "MyGUI_Types.h"
namespace MyGUI
{
/** Info about tootip state */
struct ToolTipInfo
{
enum ToolTipType
{
Hide,
Show,
Move
};
ToolTipInfo(ToolTipType _type) :
type(_type), index(ITEM_NONE) { }
ToolTipInfo(ToolTipType _type, size_t _index, const IntPoint& _point) :
type(_type), index(_index), point(_point) { }
ToolTipType type;
size_t index;
IntPoint point;
};
} // namespace MyGUI
#endif //__MYGUI_WIDGET_TOOLTIP_H__
| [
"albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c"
] | [
[
[
1,
54
]
]
] |
9eed549349d38e64bfc3773cc924f1b7e9deb5b3 | 6520b2b1c45e5a9e5996a9205142de6e2e2cb7ea | /AHL/slynxlair/src/lib/GL.h | 067b1523e0a8f7215c43fbeb64cf1317c2fe74bd | [] | no_license | xpierro/ahl | 6207bc2c309a7f2e4bf659e86fcbf4d889250d82 | 8efd98a6ecc32d794a1e957b0b91eb017546fdf1 | refs/heads/master | 2020-06-04T00:59:13.590942 | 2010-10-21T04:09:48 | 2010-10-21T04:09:48 | 41,411,324 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,305 | h | /*
* GL.h
*
* Created on: 10 oct. 2010
* Author: Pierre
*/
#ifndef GL_H_
#define GL_H_
#include <psgl/psgl.h>
#include <psgl/psglu.h>
#include <list>
using namespace std;
namespace PS3 {
class GL {
protected:
static unsigned int width;
static unsigned int height;
public:
static const int MAIN_LOOP_STOP = 0;
static bool systemExited;
static bool libraryStarted;
static void systemCallback(const uint64_t, const uint64_t, void*);
GL();
virtual ~GL();
/**
* Initialise la librairie graphique de la PS3
*/
static void init();
/**
* Execute la fonction passée en argument en boucle tant que le retour de la
* fonction est différent de MAIN_LOOP_STOP
*/
static void executeMainLoop(int (*)(void));
/**
* Referme la librairie graphique proprement.
*/
static void close();
/**
* Ajoute des fonctions à executer à la réception d'une interruption
*/
static void addUserCallback(void (*)(const uint64_t,
const uint64_t,
void*));
static unsigned int getWidth();
static unsigned int getHeight();
protected:
static list<void(*)(const uint64_t, const uint64_t, void*)> *callbacks;
static PSGLdevice *device;
static PSGLcontext *context;
};
}
#endif /* GL_H_ */
| [
"[email protected]"
] | [
[
[
1,
66
]
]
] |
f44c6c409ac998ab7c9a1866f49d4655c9f6f2c9 | 3e69b159d352a57a48bc483cb8ca802b49679d65 | /tags/release-2006-01-16/gerbview/controle.cpp | 2f3a84844cf6a44245baf201a7154bff45a2bba8 | [] | no_license | BackupTheBerlios/kicad-svn | 4b79bc0af39d6e5cb0f07556eb781a83e8a464b9 | 4c97bbde4b1b12ec5616a57c17298c77a9790398 | refs/heads/master | 2021-01-01T19:38:40.000652 | 2006-06-19T20:01:24 | 2006-06-19T20:01:24 | 40,799,911 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,077 | cpp | /********************************************************/
/* Routines generales de gestion des commandes usuelles */
/********************************************************/
/* fichier controle.cpp */
/*
Routines d'affichage grille, Boite de coordonnees, Curseurs, marqueurs ...
*/
#include "fctsys.h"
#include "common.h"
#include "gerbview.h"
#include "id.h"
#include "protos.h"
/* Routines Locales : */
/* Variables Locales */
/**********************************************************************/
EDA_BaseStruct * WinEDA_GerberFrame::GerberGeneralLocateAndDisplay(void)
/**********************************************************************/
{
return Locate(CURSEUR_OFF_GRILLE);
}
/****************************************************************/
void WinEDA_BasePcbFrame::GeneralControle(wxDC *DC, wxPoint Mouse)
/****************************************************************/
/* traitement des touches de fonctions utilisees ds tous les menus
Zoom
Redessin d'ecran
Cht Unites
Cht couches
Remise a 0 de l'origine des coordonnees relatives
*/
{
wxSize delta;
wxPoint curpos, oldpos;
int hotkey = 0;
curpos = DrawPanel->CursorRealPosition(Mouse);
oldpos = GetScreen()->m_Curseur;
delta.x = GetScreen()->GetGrid().x / GetScreen()->GetZoom();
delta.y = GetScreen()->GetGrid().y / GetScreen()->GetZoom();
if( delta.x == 0 ) delta.x = 1;
if( delta.y == 0 ) delta.y = 1;
switch(g_KeyPressed)
{
case WXK_NUMPAD_SUBTRACT :
case WXK_SUBTRACT :
case '-' :
if(GetScreen()->m_Active_Layer > 0)
GetScreen()->m_Active_Layer--;
break ;
case WXK_NUMPAD_ADD :
case WXK_ADD :
case '+' :
if(GetScreen()->m_Active_Layer < 31)
GetScreen()->m_Active_Layer ++;
break ;
case 'F' | GR_KB_CTRL :
case 'f' | GR_KB_CTRL :
DisplayOpt.DisplayPcbTrackFill ^= 1; DisplayOpt.DisplayPcbTrackFill &= 1 ;
GetScreen()->SetRefreshReq();
break ;
case ' ' : /* Mise a jour de l'origine des coord relatives */
GetScreen()->m_O_Curseur = GetScreen()->m_Curseur;
break ;
case 'U' | GR_KB_CTRL :
case 'u' | GR_KB_CTRL :
if (UnitMetric == INCHES ) UnitMetric = MILLIMETRE ;
else UnitMetric = INCHES ;
break ;
case WXK_F1 :
OnZoom(ID_ZOOM_PLUS_KEY);
curpos = GetScreen()->m_Curseur;
break;
case WXK_F2 :
OnZoom(ID_ZOOM_MOINS_KEY);
curpos = GetScreen()->m_Curseur;
break;
case WXK_F3 :
OnZoom(ID_ZOOM_REDRAW_KEY);
break;
case WXK_F4 :
OnZoom(ID_ZOOM_CENTER_KEY);
curpos = GetScreen()->m_Curseur;
break;
case WXK_NUMPAD8 : /* Deplacement curseur vers le haut */
case WXK_UP :
Mouse.y -= delta.y;
DrawPanel->MouseTo(Mouse);
break ;
case WXK_NUMPAD2: /* Deplacement curseur vers le bas */
case WXK_DOWN:
Mouse.y += delta.y;
DrawPanel->MouseTo(Mouse);
break ;
case WXK_NUMPAD4: /* Deplacement curseur vers la gauche */
case WXK_LEFT :
Mouse.x -= delta.x;
DrawPanel->MouseTo(Mouse);
break ;
case WXK_NUMPAD6: /* Deplacement curseur vers la droite */
case WXK_RIGHT :
Mouse.x += delta.x;
DrawPanel->MouseTo(Mouse);
break ;
default: hotkey = g_KeyPressed;
break;
}
/* Recalcul de la position du curseur schema */
GetScreen()->m_Curseur = curpos;
/* Placement sur la grille generale */
PutOnGrid( & GetScreen()->m_Curseur);
if( GetScreen()->IsRefreshReq() )
{
RedrawActiveWindow(DC, TRUE);
}
if ( (oldpos.x != GetScreen()->m_Curseur.x) ||
(oldpos.y != GetScreen()->m_Curseur.y) )
{
curpos = GetScreen()->m_Curseur;
GetScreen()->m_Curseur = oldpos;
GetScreen()->Trace_Curseur(DrawPanel, DC);
GetScreen()->m_Curseur = curpos;
GetScreen()->Trace_Curseur(DrawPanel, DC);
if(GetScreen()->ManageCurseur)
{
GetScreen()->ManageCurseur(DrawPanel, DC, TRUE);
}
}
SetToolbars();
Affiche_Status_Box(); /* Affichage des coord curseur */
if ( hotkey )
{
OnHotKey(DC, hotkey, NULL);
}
}
| [
"bokeoa@244deca0-f506-0410-ab94-f4f3571dea26"
] | [
[
[
1,
170
]
]
] |
3c02b64ddf1221ce237b0792bcec920e7158981b | 3bfc30f7a07ce0f6eabcd526e39ba1030d84c1f3 | /BlobbyWarriors/Source/BlobbyWarriors/Model/Entity/Ground.cpp | bca634389d937a5d32c32d0ca12ffcbf53c436f1 | [] | no_license | visusnet/Blobby-Warriors | b0b70a0b4769b60d96424b55ad7c47b256e60061 | adec63056786e4e8dfcb1ed7f7fe8b09ce05399d | refs/heads/master | 2021-01-19T14:09:32.522480 | 2011-11-29T21:53:25 | 2011-11-29T21:53:25 | 2,850,563 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 74 | cpp | #include "Ground.h"
void Ground::draw()
{
AbstractEntity::draw();
} | [
"[email protected]"
] | [
[
[
1,
6
]
]
] |
d6e98ffc34cba09cd2ab101c91a0cb76d7e68d80 | eaa64a4b73fe76125d34177c33e1aadedfaf4e46 | /src/MessageReceiver.hpp | bf53cb256df28c1a52b1fec6595ccc84b50eb8bd | [
"Apache-2.0"
] | permissive | brianfcoleman/libvideocapture | 1d856f3f8658a7d834fad5d094927783092897bc | 3357c0d31603c94890960676a38253275a52c1b3 | refs/heads/master | 2020-04-28T01:55:24.483921 | 2010-10-10T20:23:32 | 2010-10-10T20:23:32 | 35,434,467 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,547 | hpp | #ifndef VIDEO_CAPTURE_MESSAGE_RECEIVER_H
#define VIDEO_CAPTURE_MESSAGE_RECEIVER_H
#include "boost/utility.hpp"
#include "boost/thread.hpp"
#include "boost/function.hpp"
#include "boost/bind.hpp"
#include "boost/shared_ptr.hpp"
#include "boost/weak_ptr.hpp"
#include "MessageQueue.hpp"
namespace VideoCapture {
template<
typename MessageSenderFactory> class MessageReceiver : boost::noncopyable {
public:
typedef typename MessageSenderFactory::MessageType MessageType;
typedef typename MessageSenderFactory::MessageSharedPtr MessageSharedPtr;
typedef MessageQueue<MessageType> MessageQueueType;
typedef typename MessageQueueType::QueueImplType QueueImplType;
typedef typename MessageQueueType::ImplPtr QueueImplPtr;
typedef typename MessageQueueType::SizeType SizeType;
typedef MessageReceiver<MessageSenderFactory> MessageReceiverType;
typedef boost::shared_ptr<MessageReceiverType> MessageReceiverSharedPtr;
MessageReceiver(
const SizeType maxSizeMessageQueue,
const MessageSenderFactory& messageSenderFactory)
: m_pThreadEndIndicator(new boost::promise<bool>()),
m_pMessageQueue(new QueueImplType(maxSizeMessageQueue)),
m_thread(
boost::bind(
&receiveMessageLoop<MessageSenderFactory>,
m_pMessageQueue,
messageSenderFactory,
m_pThreadEndIndicator)) {
}
~MessageReceiver() {
#ifdef DEBUG
std::cout << "MessageReceiver::~MessageReceiver exiting" << std::endl;
#endif
stopReceivingMessages();
}
private:
void stopReceivingMessages() {
if (!m_pThreadEndIndicator) {
return;
}
m_pThreadEndIndicator->set_value(true);
}
boost::shared_ptr<boost::promise<bool>> m_pThreadEndIndicator;
QueueImplPtr m_pMessageQueue;
boost::thread m_thread;
};
template<typename MessageSenderFactory> void receiveMessageLoop(
typename MessageSenderFactory::QueueImplPtr pMessageQueue,
MessageSenderFactory& messageSenderFactory,
boost::weak_ptr<boost::promise<bool>> pWeakThreadEndIndicator) {
typedef typename MessageSenderFactory::MessageType MessageType;
typedef typename MessageSenderFactory::MessageSharedPtr MessageSharedPtr;
typedef typename MessageSenderFactory::MessageQueueType MessageQueueType;
typedef typename
MessageSenderFactory::MessageSenderSharedPtr MessageSenderSharedPtr;
try {
boost::unique_future<bool> isThreadEnded;
{
boost::shared_ptr<boost::promise<bool>> pThreadEndIndicator(
pWeakThreadEndIndicator.lock());
if (!pThreadEndIndicator) {
return;
}
isThreadEnded.swap(pThreadEndIndicator->get_future());
}
MessageQueueType messageQueue(pMessageQueue);
MessageSenderSharedPtr pMessageSender(messageSenderFactory(messageQueue));
while (!boost::this_thread::interruption_requested()) {
if (isThreadEnded.is_ready()) {
return;
}
MessageSharedPtr pMessage(pMessageQueue->pop_back());
if (!pMessage) {
continue;
}
pMessage->operator()();
boost::this_thread::interruption_point();
}
} catch (boost::thread_interrupted exception) {
#ifdef DEBUG
std::cout << "MessageReceiver::receiveMessageLoop exiting" << std::endl;
#endif
return;
}
#ifdef DEBUG
std::cout << "MessageReceiver::receiveMessageLoop exiting" << std::endl;
#endif
}
} // VideoCapture
#endif // VIDEO_CAPTURE_MESSAGE_RECEIVER_H
| [
"[email protected]"
] | [
[
[
1,
106
]
]
] |
e0bc121ae84a5dfda989be1e0defa6cfac85beb9 | 24adabaec8e7b0c8bb71366fea2b02e4e8b34203 | /db-builder/lib/src/texturefilters/flattexturefilter.cpp | eba42007fdc0908c2354327fbe244828e509e354 | [] | no_license | weimingtom/db-verkstan | 246fb8ce2890b3833a2a84f2369e8e0e5495390f | 9101195975ec48f4eed33e65e33c83b2dd9ba8c0 | refs/heads/master | 2021-01-10T01:36:39.787220 | 2009-02-23T22:36:09 | 2009-02-23T22:36:09 | 43,455,399 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 271 | cpp | #include "db-util.hpp"
#include "builder.hpp"
#include "filters.hpp"
#include "texture.hpp"
Texture* TextureFilters::flat(D3DXCOLOR color)
{
Texture* newTexture = new Texture();
newTexture->fillRectangle(0, 0, 256, 256, color);
return newTexture;
} | [
"olof.naessen@75511648-93a4-11dd-b566-b74dd1c53f51"
] | [
[
[
1,
11
]
]
] |
03d8d1311796577538213e73ff4d3c5cea0f3cb8 | 8a8873b129313b24341e8fa88a49052e09c3fa51 | /src/HelpWindow.cpp | b767f8a114db05edb2eacc4797c685a4ae8a5a05 | [] | no_license | flaithbheartaigh/wapbrowser | ba09f7aa981d65df810dba2156a3f153df071dcf | b0d93ce8517916d23104be608548e93740bace4e | refs/heads/master | 2021-01-10T11:29:49.555342 | 2010-03-08T09:36:03 | 2010-03-08T09:36:03 | 50,261,329 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,077 | cpp | /*
============================================================================
Name : HelpWindow.cpp
Author : 浮生若茶
Version :
Copyright : Your copyright notice
Description : CHelpWindow implementation
============================================================================
*/
#include "HelpWindow.h"
#include "MainEngine.h"
#include "ControlFactory.h"
#include "ScreenLayout.h"
#include "NaviPane.h"
#include "TypeDefine.h"
#include "MultiText.h"
CHelpWindow::CHelpWindow(CWindow* aParent,CMainEngine& aMainEngine) : CWindow(EHelpWindow,aParent,aMainEngine)
{
}
CHelpWindow::~CHelpWindow()
{
}
CHelpWindow* CHelpWindow::NewLC(CWindow* aParent,CMainEngine& aMainEngine)
{
CHelpWindow* self = new (ELeave)CHelpWindow(aParent,aMainEngine);
CleanupStack::PushL(self);
self->ConstructL();
return self;
}
CHelpWindow* CHelpWindow::NewL(CWindow* aParent,CMainEngine& aMainEngine)
{
CHelpWindow* self=CHelpWindow::NewLC(aParent,aMainEngine);
CleanupStack::Pop(); // self;
return self;
}
void CHelpWindow::ConstructL()
{
ChangeButton();
((CControlFactory&)iMainEngine.ControlFactory()).SetParentWindow(this);
TFileName helpFileName;
helpFileName.Append(iMainEngine.GetAppPath());
helpFileName.Append(_L("SoarskyHelp.txt"));
iMultiText=iMainEngine.ControlFactory().CreateDefaultMutliTextFromFile(helpFileName,_L(""));
iMainEngine.ControlFactory().CreateDefaultTitleBarL(iMainEngine.GetDesById(ETurkeyTextRes_MainMenuHelp));
}
//////////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////////
void CHelpWindow::DoActivateL()
{
}
void CHelpWindow::DoDeactivate()
{
//DeleteAllControl();
}
void CHelpWindow::DoDraw(CGraphic& aGraphic) const
{
}
TBool CHelpWindow::DoKeyEventL(TInt aKeyCode)
{
TBool keyResult = ETrue;
switch(aKeyCode)
{
case EKeyDevice3: //OK键,进入模块
iMultiText->GetEndFlag();
break;
case EKeyDevice1:
GoBackToParentWindow();
break;
}
return keyResult;
}
TBool CHelpWindow::DoHandleCommandL(TInt aCommand)
{
return EFalse;
}
void CHelpWindow::DoSizeChanged()
{
}
void CHelpWindow::ChangeButton()
{
const CArrayFixFlat<TTEXTRES>& textRes = iMainEngine.GetTextRes();
SetLeftButtonL(textRes[ETurkeyTextRes_Option]);
SetRightButtonL(textRes[ETurkeyTextRes_Back]);
}
//////////////////////////////////////////////////////////////////////////
//private
//////////////////////////////////////////////////////////////////////////
void CHelpWindow::InitPopUpMenu()
{
/*
CPopUpMenu* popUpMenu = iMainEngine.ControlFactory().CreatePopUpMenu(*this);
popUpMenu->AppendItem(_L("Enter"),EEnterModule);
popUpMenu->AppendItem(_L("Help"),EShowHelp);
popUpMenu->AppendItem(_L("Hide"),EHideApp);
popUpMenu->AppendItem(_L("Enter"),EEnterModule);
popUpMenu->AppendItem(_L("Help"),EShowHelp);
popUpMenu->AppendItem(_L("Hide"),EHideApp);
popUpMenu->AppendItem(_L("Back"),EExitApp);
*/
} | [
"sungrass.xp@37a08ede-ebbd-11dd-bd7b-b12b6590754f"
] | [
[
[
1,
120
]
]
] |
0df1ed3b7454effa93468fa90ebb4aee7297534b | 5d3c1be292f6153480f3a372befea4172c683180 | /trunk/Hardware Proxies/iStuff Mobile/Symbian/iStuffMobile/inc/iStuffMobileContainer.h | 9850276629df7ab35c61d3ac52e91e34c9682410 | [
"Artistic-2.0"
] | permissive | BackupTheBerlios/istuff-svn | 5f47aa73dd74ecf5c55f83765a5c50daa28fa508 | d0bb9963b899259695553ccd2b01b35be5fb83db | refs/heads/master | 2016-09-06T04:54:24.129060 | 2008-05-02T22:33:26 | 2008-05-02T22:33:26 | 40,820,013 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,094 | h | /*
* Copyright (c) 2006
* Media informatics Department
* RWTH Aachen Germany
* http://media.informatik.rwth-aachen.de
*
* Redistribution and use of the source code and binary, with or without
* modification, are permitted under OPI Artistic License
* (http://www.opensource.org/licenses/artistic-license.php) provided that
* the source code retains the above copyright notice and the following
* disclaimer.
*
* 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.
*
* Authors: Faraz Ahmed Memon
* Tico Ballagas
*
* Version: 1.0
*/
#ifndef ISTUFFMOBILECONTAINER_H
#define ISTUFFMOBILECONTAINER_H
#include <coecntrl.h>
#include <aknlists.h>
#include <apgwgnam.h>
#include <flogger.h>
#include "Global.h"
class CEikLabel;
//! CiStuffMobileContainer class is the default UI container for "iStuff Mobile" mobile phone application
/*! This class is the default UI which is displayed when the application
is launched.
*/
class CiStuffMobileContainer : public CCoeControl, MCoeControlObserver
{
public:
//! Second level constructor for CiStuffMobileContainer class
/*! This method initiates the GUI by loading the image that
has to be displayed into the background of the container.
It also contructs a label and puts it into the contanier.
\param aRect as TRect object. Represents the area to which
container should be drawn.
*/
void ConstructL(const TRect& aRect);
~CiStuffMobileContainer();
//! Sends the GUI to the background
/*! Whenver this method is called it send the application
UI to the background in the mobile phone. The application
is active even when in background.
*/
void SendToBackground();
CEikLabel* iLabel;
private:
//! Resizes the components inside the container
/*! This method is called when the size of the container
changes. It adjusts the size of the components inside
the container.
*/
void SizeChanged();
//! Returns the number of component in the container
/*! This method returns the number of component in the
container.
\return an integer indicating number of components.
*/
TInt CountComponentControls() const;
//! Returns the pointer to a component inside the container
/*! This method returns a to pointer to the component inside
the container.
\param aIndex as an TInt. Represents the index of the
components. Indexs start from 0 with component
constructed first to have a lower index than the
one constructed later.
\return pointer to the component.
*/
CCoeControl* ComponentControl(TInt aIndex) const;
//! Draws the GUI
/*! This methos Draws the container on the screen with the
background image.
\param aRect as TRect class type. Represents the area
to be used for drawing the container.
*/
void Draw(const TRect& aRect) const;
void HandleControlEventL(CCoeControl* aControl,TCoeEvent aEventType);
CFbsBitmap* iBackground;
};
#endif | [
"faraz@2a53cb5c-8ff1-0310-8b75-b3ec22923d26"
] | [
[
[
1,
115
]
]
] |
cfc87cecca467fcb66e2a1d3e10683a5354ed046 | accd6e4daa3fc1103c86d245c784182e31681ea4 | /HappyHunter/Core/CrossPlane.h | 3af1e1489c39a05b44c40724c902a3bfa43ae54a | [] | 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 | 944 | h | #pragma once
#include "Sprite.h"
#include "VertexBuffer.h"
#include "RenderMethod.h"
namespace zerO
{
class CCrossPlane :
public CSprite
{
typedef struct
{
D3DXVECTOR3 Position;
D3DXVECTOR2 UV;
}VERTEX, * LPVERTEX;
typedef struct
{
VERTEX Vertices[4];
}PLANE, * LPPLANE;
public:
CCrossPlane(void);
~CCrossPlane(void);
CRenderMethod& GetRenderMethod();
void Clone(CCrossPlane& CrossPlane)const;
bool Create(FLOAT fWidth, FLOAT fHeight, UINT uNumPlanes, const D3DXVECTOR3* pCenter = NULL);
bool Destroy();
bool ApplyForRender();
void Render(CRenderQueue::LPRENDERENTRY pEntry, UINT32 uFlag);
private:
CRenderMethod m_RenderMethod;
CVertexBuffer* m_pVertexBuffer;
FLOAT m_fWidth;
FLOAT m_fHeight;
UINT m_uNumPlanes;
bool m_bIsCreated;
};
inline CRenderMethod& CCrossPlane::GetRenderMethod()
{
return m_RenderMethod;
}
}
| [
"[email protected]"
] | [
[
[
1,
53
]
]
] |
520b30449b53ab3bd5d138a5cb227407a3febc70 | 011359e589f99ae5fe8271962d447165e9ff7768 | /src/burn/taito/pc080sn.cpp | 0bcee4ea356704d7a5bbacee7f12c239f50d3c2d | [] | 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 | 11,459 | cpp | // PC080SN
#include "tiles_generic.h"
#include "taito_ic.h"
unsigned char *PC080SNRam = NULL;
static UINT16 PC080SNCtrl[8];
static int BgScrollX;
static int BgScrollY;
static int FgScrollX;
static int FgScrollY;
static int PC080SNNumTiles;
static int PC080SNXOffset;
static int PC080SNYOffset;
static int PC080SNFgTransparentPen;
static int PC080SNYInvert;
static int PC080SNDblWidth;
static int PC080SNCols;
void PC080SNDrawBgLayer(int Opaque, unsigned char *pSrc)
{
int mx, my, Offset, Colour, x, y, TileIndex = 0, Flip, xFlip, yFlip;
UINT16 Attr, Code;
UINT16 *VideoRam = (UINT16*)PC080SNRam + 0x0000;
UINT16 *BgScrollRam = NULL;
if (!PC080SNDblWidth) BgScrollRam = (UINT16*)PC080SNRam + 0x2000;
int BgScrollActive = 0;
if (BgScrollRam) {
for (int i = 0; i < 512; i++) {
if (swapWord(BgScrollRam[i])) {
BgScrollActive = 1;
break;
}
}
}
for (my = 0; my < 64; my++) {
for (mx = 0; mx < PC080SNCols; mx++) {
Offset = 2 * TileIndex;
if (!PC080SNDblWidth) {
Attr = swapWord(VideoRam[Offset + 0]);
Code = swapWord(VideoRam[Offset + 1]) & (PC080SNNumTiles - 1);
} else {
Attr = swapWord(VideoRam[TileIndex + 0x0000]);
Code = swapWord(VideoRam[TileIndex + 0x2000] & 0x3fff);
}
Colour = Attr & 0x1ff;
Flip = (Attr & 0xc000) >> 14;
xFlip = (Flip >> 0) & 0x01;
yFlip = (Flip >> 1) & 0x01;
x = 8 * mx;
y = 8 * my;
x -= 16;
x -= PC080SNXOffset;
y -= PC080SNYOffset;
if (BgScrollActive) {
int px, py;
UINT32 nPalette = Colour << 4;
for (py = 0; py < 8; py++) {
for (px = 0; px < 8; px++) {
unsigned char c = pSrc[(Code * 64) + (py * 8) + px];
if (xFlip) c = pSrc[(Code * 64) + (py * 8) + (7 - px)];
if (yFlip) c = pSrc[(Code * 64) + ((7 - py) * 8) + px];
if (xFlip && yFlip) c = pSrc[(Code * 64) + ((7 - py) * 8) + (7 - px)];
if (c || Opaque) {
int xPos = x + px;
int yPos = y + py;
yPos -= BgScrollY & 0x1ff;
if (yPos < -8) yPos += 512;
if (yPos >= 512) yPos -= 512;
if (yPos >= 0 && yPos < nScreenHeight) {
if (!PC080SNDblWidth) {
xPos -= ((BgScrollX - swapWord(BgScrollRam[yPos + PC080SNYOffset])) & 0x1ff);
if (xPos < -8) xPos += 512;
if (xPos >= 512) xPos -= 512;
} else {
xPos -= BgScrollX & 0x3ff;
if (xPos < -8) xPos += 1024;
if (xPos >= 1024) xPos -= 1024;
}
unsigned short* pPixel = pTransDraw + (yPos * nScreenWidth);
if (xPos >= 0 && xPos < nScreenWidth) {
pPixel[xPos] = c | nPalette;
}
}
}
}
}
} else {
if (!PC080SNDblWidth) {
x -= BgScrollX & 0x1ff;
if (x < -8) x += 512;
if (x >= 512) x -= 512;
} else {
x -= BgScrollX & 0x3ff;
if (x < -8) x += 1024;
if (x >= 1024) x -= 1024;
}
y -= BgScrollY & 0x1ff;
if (y < -8) y += 512;
if (y >= 512) y -= 512;
if (Opaque) {
if (x > 8 && x < (nScreenWidth - 8) && y > 8 && y < (nScreenHeight - 8)) {
if (xFlip) {
if (yFlip) {
Render8x8Tile_FlipXY(pTransDraw, Code, x , y, Colour, 4, 0, pSrc);
} else {
Render8x8Tile_FlipX(pTransDraw, Code, x , y, Colour, 4, 0, pSrc);
}
} else {
if (yFlip) {
Render8x8Tile_FlipY(pTransDraw, Code, x , y, Colour, 4, 0, pSrc);
} else {
Render8x8Tile(pTransDraw, Code, x , y, Colour, 4, 0, pSrc);
}
}
} else {
if (xFlip) {
if (yFlip) {
Render8x8Tile_FlipXY_Clip(pTransDraw, Code, x , y, Colour, 4, 0, pSrc);
} else {
Render8x8Tile_FlipX_Clip(pTransDraw, Code, x , y, Colour, 4, 0, pSrc);
}
} else {
if (yFlip) {
Render8x8Tile_FlipY_Clip(pTransDraw, Code, x , y, Colour, 4, 0, pSrc);
} else {
Render8x8Tile_Clip(pTransDraw, Code, x , y, Colour, 4, 0, pSrc);
}
}
}
} else {
if (x > 8 && x < (nScreenWidth - 8) && y > 8 && y < (nScreenHeight - 8)) {
if (xFlip) {
if (yFlip) {
Render8x8Tile_Mask_FlipXY(pTransDraw, Code, x , y, Colour, 4, 0, 0, pSrc);
} else {
Render8x8Tile_Mask_FlipX(pTransDraw, Code, x , y, Colour, 4, 0, 0, pSrc);
}
} else {
if (yFlip) {
Render8x8Tile_Mask_FlipY(pTransDraw, Code, x , y, Colour, 4, 0, 0, pSrc);
} else {
Render8x8Tile_Mask(pTransDraw, Code, x , y, Colour, 4, 0, 0, pSrc);
}
}
} else {
if (xFlip) {
if (yFlip) {
Render8x8Tile_Mask_FlipXY_Clip(pTransDraw, Code, x , y, Colour, 4, 0, 0, pSrc);
} else {
Render8x8Tile_Mask_FlipX_Clip(pTransDraw, Code, x , y, Colour, 4, 0, 0, pSrc);
}
} else {
if (yFlip) {
Render8x8Tile_Mask_FlipY_Clip(pTransDraw, Code, x , y, Colour, 4, 0, 0, pSrc);
} else {
Render8x8Tile_Mask_Clip(pTransDraw, Code, x , y, Colour, 4, 0, 0, pSrc);
}
}
}
}
}
TileIndex++;
}
}
}
void PC080SNDrawFgLayer(unsigned char *pSrc)
{
int mx, my, Offset, Attr, Code, Colour, x, y, TileIndex = 0, Flip, xFlip, yFlip;
UINT16 *VideoRam = (UINT16*)PC080SNRam + 0x4000;
UINT16 *FgScrollRam = NULL;
if (!PC080SNDblWidth) FgScrollRam = (UINT16*)PC080SNRam + 0x6000;
int FgScrollActive = 0;
if (FgScrollRam) {
for (int i = 0; i < 512; i++) {
if (FgScrollRam[i]) {
FgScrollActive = 1;
break;
}
}
}
for (my = 0; my < 64; my++) {
for (mx = 0; mx < PC080SNCols; mx++) {
Offset = 2 * TileIndex;
if (!PC080SNDblWidth) {
Attr = swapWord(VideoRam[Offset + 0]);
Code = swapWord(VideoRam[Offset + 1]) & (PC080SNNumTiles - 1);
} else {
Attr = swapWord(VideoRam[TileIndex + 0x0000]);
Code = swapWord(VideoRam[TileIndex + 0x2000]) & 0x3fff;
}
Colour = Attr & 0x1ff;
Flip = (Attr & 0xc000) >> 14;
xFlip = (Flip >> 0) & 0x01;
yFlip = (Flip >> 1) & 0x01;
x = 8 * mx;
y = 8 * my;
x -= 16;
x -= PC080SNXOffset;
y -= PC080SNYOffset;
if (FgScrollActive) {
int px, py;
UINT32 nPalette = Colour << 4;
for (py = 0; py < 8; py++) {
for (px = 0; px < 8; px++) {
unsigned char c = pSrc[(Code * 64) + (py * 8) + px];
if (xFlip) c = pSrc[(Code * 64) + (py * 8) + (7 - px)];
if (yFlip) c = pSrc[(Code * 64) + ((7 - py) * 8) + px];
if (xFlip && yFlip) c = pSrc[(Code * 64) + ((7 - py) * 8) + (7 - px)];
if (c != PC080SNFgTransparentPen) {
int xPos = x + px;
int yPos = y + py;
yPos -= FgScrollY & 0x1ff;
if (yPos < -8) yPos += 512;
if (yPos >= 512) yPos -= 512;
if (yPos >= 0 && yPos < nScreenHeight) {
if (!PC080SNDblWidth) {
xPos -= ((FgScrollX - FgScrollRam[yPos + PC080SNYOffset]) & 0x1ff);
if (xPos < -8) xPos += 512;
if (xPos >= 512) xPos -= 512;
} else {
xPos -= FgScrollX & 0x3ff;
if (xPos < -8) xPos += 1024;
if (xPos >= 1024) xPos -= 1024;
}
unsigned short* pPixel = pTransDraw + (yPos * nScreenWidth);
if (xPos >= 0 && xPos < nScreenWidth) {
pPixel[xPos] = c | nPalette;
}
}
}
}
}
} else {
if (!PC080SNDblWidth) {
x -= FgScrollX & 0x1ff;
if (x < -8) x += 512;
if (x >= 512) x -= 512;
} else {
x -= FgScrollX & 0x3ff;
if (x < -8) x += 1024;
if (x >= 1024) x -= 1024;
}
y -= FgScrollY & 0x1ff;
if (y < -8) y += 512;
if (y >= 512) y -= 512;
if (x > 8 && x < (nScreenWidth - 8) && y > 8 && y < (nScreenHeight - 8)) {
if (xFlip) {
if (yFlip) {
Render8x8Tile_Mask_FlipXY(pTransDraw, Code, x , y, Colour, 4, PC080SNFgTransparentPen, 0, pSrc);
} else {
Render8x8Tile_Mask_FlipX(pTransDraw, Code, x , y, Colour, 4, PC080SNFgTransparentPen, 0, pSrc);
}
} else {
if (yFlip) {
Render8x8Tile_Mask_FlipY(pTransDraw, Code, x , y, Colour, 4, PC080SNFgTransparentPen, 0, pSrc);
} else {
Render8x8Tile_Mask(pTransDraw, Code, x , y, Colour, 4, PC080SNFgTransparentPen, 0, pSrc);
}
}
} else {
if (xFlip) {
if (yFlip) {
Render8x8Tile_Mask_FlipXY_Clip(pTransDraw, Code, x , y, Colour, 4, PC080SNFgTransparentPen, 0, pSrc);
} else {
Render8x8Tile_Mask_FlipX_Clip(pTransDraw, Code, x , y, Colour, 4, PC080SNFgTransparentPen, 0, pSrc);
}
} else {
if (yFlip) {
Render8x8Tile_Mask_FlipY_Clip(pTransDraw, Code, x , y, Colour, 4, PC080SNFgTransparentPen, 0, pSrc);
} else {
Render8x8Tile_Mask_Clip(pTransDraw, Code, x , y, Colour, 4, PC080SNFgTransparentPen, 0, pSrc);
}
}
}
}
TileIndex++;
}
}
}
void PC080SNSetScrollX(unsigned int Offset, UINT16 Data)
{
PC080SNCtrl[Offset] = Data;
switch (Offset) {
case 0: {
BgScrollX = -Data;
break;
}
case 1: {
FgScrollX = -Data;
break;
}
}
}
void PC080SNSetScrollY(unsigned int Offset, UINT16 Data)
{
PC080SNCtrl[Offset + 2] = Data;
if (PC080SNYInvert) Data = -Data;
switch (Offset) {
case 0: {
BgScrollY = -Data;
break;
}
case 1: {
FgScrollY = -Data;
break;
}
}
}
void PC080SNCtrlWrite(unsigned int Offset, UINT16 Data)
{
PC080SNCtrl[Offset + 4] = Data;
#if 0
switch (Offset) {
case 0: {
if (Data & 1) bprintf(PRINT_NORMAL, _T("PC080SN Flipped\n"));
return;
}
}
#endif
}
void PC080SNOverrideFgScroll(int xScroll, int yScroll)
{
FgScrollX = xScroll;
FgScrollY = yScroll;
}
void PC080SNReset()
{
memset(PC080SNCtrl, 0, 8 * sizeof(UINT16));
BgScrollX = 0;
BgScrollY = 0;
FgScrollX = 0;
FgScrollY = 0;
}
void PC080SNInit(int nNumTiles, int xOffset, int yOffset, int yInvert, int DblWidth)
{
PC080SNRam = (unsigned char*)malloc(0x10000);
memset(PC080SNRam, 0, 0x10000);
PC080SNNumTiles = nNumTiles;
PC080SNXOffset = xOffset;
PC080SNYOffset = yOffset;
PC080SNFgTransparentPen = 0;
PC080SNYInvert = yInvert;
TaitoIC_PC080SNInUse = 1;
PC080SNCols = 64;
if (DblWidth) PC080SNCols = 128;
PC080SNDblWidth = DblWidth;
}
void PC080SNSetFgTransparentPen(int Pen)
{
PC080SNFgTransparentPen = Pen;
}
void PC080SNExit()
{
free(PC080SNRam);
PC080SNRam = NULL;
memset(PC080SNCtrl, 0, 8 * sizeof(UINT16));
BgScrollX = 0;
BgScrollY = 0;
FgScrollX = 0;
FgScrollY = 0;
PC080SNNumTiles = 0;
PC080SNXOffset = 0;
PC080SNYOffset = 0;
PC080SNFgTransparentPen = 0;
PC080SNYInvert = 0;
PC080SNDblWidth = 0;
PC080SNCols = 0;
}
void PC080SNScan(int nAction)
{
struct BurnArea ba;
if (nAction & ACB_MEMORY_RAM) {
memset(&ba, 0, sizeof(ba));
ba.Data = PC080SNRam;
ba.nLen = 0x10000;
ba.szName = "PC080SN Ram";
BurnAcb(&ba);
}
if (nAction & ACB_DRIVER_DATA) {
SCAN_VAR(PC080SNCtrl);
SCAN_VAR(BgScrollX);
SCAN_VAR(BgScrollY);
SCAN_VAR(FgScrollX);
SCAN_VAR(FgScrollY);
}
}
| [
"[email protected]"
] | [
[
[
1,
449
]
]
] |
b1573054ee1ad2cfa7b3923624fbcae7f28da521 | c95a83e1a741b8c0eb810dd018d91060e5872dd8 | /libs/STLPort-4.0/stlport/stl/debug/_debug.h | 5f4400f04f8216186fc1877c5483ef5399e2a7f7 | [
"LicenseRef-scancode-stlport-4.5"
] | permissive | rickyharis39/nolf2 | ba0b56e2abb076e60d97fc7a2a8ee7be4394266c | 0da0603dc961e73ac734ff365bfbfb8abb9b9b04 | refs/heads/master | 2021-01-01T17:21:00.678517 | 2011-07-23T12:11:19 | 2011-07-23T12:11:19 | 38,495,312 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,781 | h | /*
*
* Copyright (c) 1997
* Moscow Center for SPARC Technology
*
* Copyright (c) 1999
* Boris Fomitchev
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*/
#ifndef __STLPORT_DEBUG_H
# define __STLPORT_DEBUG_H
# if defined (__STL_ASSERTIONS) || defined (__STL_DEBUG)
#ifndef __STL_CONFIG_H
# include <stl/_config.h>
#endif
# if !defined (__STL_EXTRA_OPERATORS_FOR_DEBUG) && \
( defined (__STL_BASE_MATCH_BUG) || (defined (__STL_MSVC) && __STL_MSVC < 1100 ) )
# define __STL_EXTRA_OPERATORS_FOR_DEBUG
# endif
# if !defined(__STL_FILE__)
# define __STL_FILE__ __FILE__
# endif
enum {
_StlFormat_ERROR_RETURN,
_StlFormat_ASSERTION_FAILURE,
_StlFormat_VERBOSE_ASSERTION_FAILURE,
_StlMsg_INVALID_ARGUMENT,
_StlMsg_INVALID_CONTAINER,
_StlMsg_EMPTY_CONTAINER,
_StlMsg_ERASE_PAST_THE_END,
_StlMsg_OUT_OF_BOUNDS,
_StlMsg_NOT_OWNER,
_StlMsg_INVALID_ITERATOR,
_StlMsg_INVALID_LEFTHAND_ITERATOR,
_StlMsg_INVALID_RIGHTHAND_ITERATOR,
_StlMsg_DIFFERENT_OWNERS ,
_StlMsg_NOT_DEREFERENCEABLE ,
_StlMsg_INVALID_RANGE ,
_StlMsg_NOT_IN_RANGE_1 ,
_StlMsg_NOT_IN_RANGE_2 ,
_StlMsg_INVALID_ADVANCE ,
_StlMsg_SINGULAR_ITERATOR ,
// debug alloc messages
_StlMsg_DBA_DELETED_TWICE ,
_StlMsg_DBA_NEVER_ALLOCATED ,
_StlMsg_DBA_TYPE_MISMATCH ,
_StlMsg_DBA_SIZE_MISMATCH ,
_StlMsg_DBA_UNDERRUN ,
_StlMsg_DBA_OVERRUN ,
_StlMsg_UNKNOWN
/* _StlMsg_MAX */
};
/* have to hardcode that ;() */
# define _StlMsg_MAX 27
__STL_BEGIN_NAMESPACE
// This class is unique (not inherited from exception),
// to disallow catch in anything but (...)
struct __stl_debug_exception {
// no members
};
class __STL_CLASS_DECLSPEC __owned_link;
class __STL_CLASS_DECLSPEC __owned_list;
template <class _Dummy>
struct __stl_debug_engine {
// Basic routine to report any debug message
// Use __STL_DEBUG_MESSAGE to override
static void __STL_CALL _Message(const char * format_str, ...);
// Micsellanous function to report indexed error message
static void __STL_CALL _IndexedError(int __ind, const char* __f, int __l);
// Basic assertion report mechanism.
// Reports failed assertion via __stl_debug_message and calls _Terminate
// if __STL_DEBUG_TERMINATE is specified, calls __stl_debug_terminate instead
static void __STL_CALL _Assert(const char* __expr, const char* __f, int __l);
// The same, with additional diagnostics
static void __STL_CALL _VerboseAssert(const char* __expr, int __error_ind, const char* __f, int __l);
// If exceptions are present, sends unique exception
// If not, calls abort() to terminate
// Use __STL_DEBUG_TERMINATE to override
static void __STL_CALL _Terminate();
// owned_list/link delegate non-inline functions here
static bool __STL_CALL _Check_same_owner( const __owned_link& __i1,
const __owned_link& __i2);
static bool __STL_CALL _Check_same_owner_or_null( const __owned_link& __i1,
const __owned_link& __i2);
static bool __STL_CALL _Check_if_owner( const __owned_list*, const __owned_link&);
static void __STL_CALL _Verify(const __owned_list*);
static void __STL_CALL _Swap_owners(__owned_list&, __owned_list& , bool __swap_roots);
static void __STL_CALL _Invalidate_all(__owned_list*);
static void __STL_CALL _M_detach(__owned_list*, __owned_link*);
static void __STL_CALL _M_attach(__owned_list*, __owned_link*);
// accessor : check and get pointer to the container
static void* __STL_CALL _Get_container_ptr(const __owned_link*);
// debug messages and formats
static const char* _Message_table[_StlMsg_MAX];
};
# if defined (__STL_USE_TEMPLATE_EXPORT)
__STL_EXPORT_TEMPLATE struct __STL_CLASS_DECLSPEC __stl_debug_engine<bool>;
# endif /* __STL_USE_TEMPLATE_EXPORT */
typedef __stl_debug_engine<bool> __stl_debugger;
__STL_END_NAMESPACE
# ifndef __STL_ASSERT
# define __STL_ASSERT(expr) \
if (!(expr)) {STLPORT::__stl_debugger::_Assert( # expr, __STL_FILE__, __LINE__);}
# endif
# endif /* __STL_ASSERTIONS || __STL_DEBUG */
// this section is for __STL_DEBUG only
#if defined ( __STL_DEBUG )
# ifndef __STL_VERBOSE_ASSERT
// fbp : new form not requiring ";"
# define __STL_VERBOSE_ASSERT(expr,__diag_num) \
if (!(expr)) { STLPORT::__stl_debugger::_VerboseAssert\
( # expr, __diag_num, __STL_FILE__, __LINE__ ); \
}
# endif
# define __STL_DEBUG_CHECK(expr) __STL_ASSERT(expr)
# define __STL_DEBUG_DO(expr) expr;
# ifndef __STL_VERBOSE_RETURN
# define __STL_VERBOSE_RETURN(__expr,__diag_num) if (!(__expr)) { \
__stl_debugger::_IndexedError(__diag_num, __FILE__ , __LINE__); \
return false; }
# endif
# ifndef __STL_VERBOSE_RETURN_0
# define __STL_VERBOSE_RETURN_0(__expr,__diag_num) if (!(__expr)) { \
__stl_debugger::_IndexedError(__diag_num, __FILE__ , __LINE__); \
return 0; }
# endif
#if defined (__STL_THREADS) && ! defined (__SGI_STL_INTERNAL_THREADS_H)
# include <stl/_threads.h>
#endif
#ifndef __SGI_STL_INTERNAL_ITERATOR_BASE_H
# include <stl/_iterator_base.h>
#endif
__STL_BEGIN_NAMESPACE
//=============================================================
template <class __Iterator>
inline bool __STL_CALL __valid_range(const __Iterator& __i1 ,const __Iterator& __i2,
random_access_iterator_tag) {
return __i1<=__i2;
}
template <class __Iterator>
inline bool __STL_CALL __valid_range(const __Iterator& __i1 ,const __Iterator& __i2,
bidirectional_iterator_tag) {
// check if comparable
bool __dummy(__i1==__i2);
return (__dummy==__dummy);
}
template <class __Iterator>
inline bool __STL_CALL __valid_range(const __Iterator& __i1 ,const __Iterator& __i2, forward_iterator_tag) {
// check if comparable
bool __dummy(__i1==__i2);
return (__dummy==__dummy);
}
template <class __Iterator>
inline bool __STL_CALL __valid_range(const __Iterator&,const __Iterator&, input_iterator_tag) {
return true;
}
template <class __Iterator>
inline bool __STL_CALL __valid_range(const __Iterator&,const __Iterator&, output_iterator_tag) {
return true;
}
template <class __Iterator>
inline bool __STL_CALL __valid_range(const __Iterator& __i1, const __Iterator& __i2) {
return __valid_range(__i1,__i2,__ITERATOR_CATEGORY(__i1));
}
// Note : that means in range [i1, i2].
template <class __Iterator>
inline bool __STL_CALL __in_range(const __Iterator& __it, const __Iterator& __i1,
const __Iterator& __i2) {
return __valid_range(__i1,__it,__ITERATOR_CATEGORY(__i1)) &&
__valid_range(__it,__i2,__ITERATOR_CATEGORY(__it));
}
template <class __Iterator>
inline bool __STL_CALL __in_range(const __Iterator& __first, const __Iterator& __last,
const __Iterator& __start, const __Iterator& __finish) {
return __valid_range(__first,__last,__ITERATOR_CATEGORY(__first)) &&
__valid_range(__start,__first,__ITERATOR_CATEGORY(__first)) &&
__valid_range(__last,__finish,__ITERATOR_CATEGORY(__last));
}
//==========================================================
class __STL_CLASS_DECLSPEC __owned_link {
public:
__owned_link() : _M_owner(0) {}
__owned_link(const __owned_list* __c) : _M_owner(0), _M_next(0) {
__stl_debugger::_M_attach(__CONST_CAST(__owned_list*,__c), this);
}
__owned_link(const __owned_link& __rhs): _M_owner(0) {
__stl_debugger::_M_attach(__CONST_CAST(__owned_list*,__rhs._M_owner), this);
}
__owned_link& operator=(const __owned_link& __rhs) {
__owned_list* __new_owner = __CONST_CAST(__owned_list*,__rhs._M_owner);
__owned_list* __old_owner = _M_owner;
if ( __old_owner != __new_owner ) {
__stl_debugger::_M_detach(__old_owner, this);
__stl_debugger::_M_attach(__new_owner, this);
}
return *this;
}
~__owned_link() {
__stl_debugger::_M_detach(_M_owner, this);
_Invalidate();
}
const __owned_list* _Owner() const {
return _M_owner;
}
__owned_list* _Owner() {
return _M_owner;
}
void _Set_owner(const __owned_list* __o) {
_M_owner= __CONST_CAST(__owned_list*,__o);
}
bool _Valid() const {
return _M_owner !=0;
}
void _Invalidate() { _M_owner=0; _M_next = 0; }
void _Link_to_self() { _M_next= 0; }
__owned_link* _Next() { return _M_next; }
const __owned_link* _Next() const { return _M_next; }
public:
__owned_list* _M_owner;
__owned_link* _M_next;
};
class __STL_CLASS_DECLSPEC __owned_list {
public:
__owned_list(const void* __o) {
// fprintf(stderr, "__owned_list(): %p\n",(void*)this);
_M_node._M_owner = __CONST_CAST(__owned_list*, __REINTERPRET_CAST(const __owned_list*,__o));
_M_node._M_next=0;
}
~__owned_list() {
// fprintf(stderr, "~__owned_list(): %p\n",(void*)this);
_Invalidate_all();
// that prevents detach
_M_node._Invalidate();
}
const void* _Owner() const {
return (const void*)_M_node._M_owner;
}
void* _Owner() {
return (void*)_M_node._M_owner;
}
bool _Valid() const {
return _M_node._M_owner!=0;
}
void _Invalidate() { _M_node._M_owner=0; }
__owned_link* _First() { return _M_node._Next(); }
__owned_link* _Last() { return 0 ; }
const __owned_link* _First() const { return (__owned_link*)_M_node._M_next; }
const __owned_link* _Last() const { return 0 ;}
void _Verify() const {
__stl_debugger::_Verify(this);
}
void _Swap_owners(__owned_list& __y, bool __swap_roots =false) {
__stl_debugger::_Swap_owners(*this, __y, __swap_roots);
}
void _Invalidate_all() {
__stl_debugger::_Invalidate_all(this);
}
mutable __owned_link _M_node;
# ifdef __STL_THREADS
mutable _STL_mutex _M_lock;
# endif
private:
// should never be called, should be left undefined,
// but some compilers complain about it ;(
__owned_list(const __owned_list&){}
void operator=(const __owned_list&) {}
friend class __owned_link;
friend struct __stl_debug_engine<bool>;
};
//==========================================================
// forward declaratioins
template <class _Iterator>
bool __STL_CALL __check_range(const _Iterator&, const _Iterator&);
template <class _Iterator>
bool __STL_CALL __check_range(const _Iterator&,
const _Iterator&, const _Iterator&);
template <class _Iterator>
bool __STL_CALL __check_range(const _Iterator&, const _Iterator& ,
const _Iterator&, const _Iterator& );
template <class _Iterator>
void __STL_CALL __invalidate_range(const __owned_list* __base,
const _Iterator& __first,
const _Iterator& __last);
template <class _Iterator>
void __STL_CALL __invalidate_iterator(const __owned_list* __base,
const _Iterator& __it);
//============================================================
inline bool __STL_CALL
__check_same_owner( const __owned_link& __i1, const __owned_link& __i2) {
return __stl_debugger::_Check_same_owner(__i1,__i2);
}
inline bool __STL_CALL
__check_same_owner_or_null( const __owned_link& __i1, const __owned_link& __i2) {
return __stl_debugger::_Check_same_owner_or_null(__i1,__i2);
}
template <class Iterator>
inline bool __STL_CALL __check_if_owner( const __owned_list* __owner,
const Iterator& __it) {
return __stl_debugger::_Check_if_owner(__owner, (const __owned_link&)__it);
}
__STL_END_NAMESPACE
# endif /* __STL_DEBUG */
# if !defined (__STL_LINK_TIME_INSTANTIATION)
# include <stl/debug/_debug.c>
# endif
#endif /* DEBUG_H */
// Local Variables:
// mode:C++
// End:
| [
"[email protected]"
] | [
[
[
1,
399
]
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.