blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
146
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
7
| license_type
stringclasses 2
values | repo_name
stringlengths 6
79
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 4
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.07k
426M
⌀ | star_events_count
int64 0
27
| fork_events_count
int64 0
12
| gha_license_id
stringclasses 3
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 6
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 20
6.28M
| extension
stringclasses 20
values | content
stringlengths 20
6.28M
| authors
listlengths 1
16
| author_lines
listlengths 1
16
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f77200548d59cf60464a3dc1e8d75f56bd9401fb | 672d939ad74ccb32afe7ec11b6b99a89c64a6020 | /FileSystem/fs/Buffer.cpp | 8053e0adabd15ce4ce416108f4f5a50b9b6cfaee | []
| no_license | cloudlander/legacy | a073013c69e399744de09d649aaac012e17da325 | 89acf51531165a29b35e36f360220eeca3b0c1f6 | refs/heads/master | 2022-04-22T14:55:37.354762 | 2009-04-11T13:51:56 | 2009-04-11T13:51:56 | 256,939,313 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 10,249 | cpp |
//////////////////////////////////////////////////////////////////
// 文件名: Buffer.cpp
// 创建者: zyk
// 时间: 2002.1.3.
// 内容: Buffer地实现
// 修改: zyk
// 修改内容: none
//////////////////////////////////////////////////////////////////
#include "Buffer.h"
#include <stdio.h>
#include <conio.h>
Buffer::Buffer(FS* pVFS_Related,int iBuf_Block_Size)
{
int i;
iBuffer_Block_Size=iBuf_Block_Size;
pBuf_Table=NULL;
pBuf_History=NULL;
pBuf_Line=new Buffer_Line[BUFFER_BLOCK_NUM];
for (i=0;i<BUFFER_BLOCK_NUM;i++)
{
pBuf_Line[i].bModified=0;
pBuf_Line[i].bValid=0;
pBuf_Line[i].fp=new File_Struct;
pBuf_Line[i].iLength=0;
pBuf_Line[i].next=i+1;
pBuf_Line[i].Content=new Byte[iBuffer_Block_Size];
}
pVFS=pVFS_Related;
iFree_Block=0;
}
Buffer::~Buffer()
{
int i;
Buffer_Table *pCur_Entry,*pTemp_Entry;
History *pCur_Item,*pTemp_Item;
for (i=0;i<BUFFER_BLOCK_NUM;i++)
{
delete[] pBuf_Line[i].Content;
delete pBuf_Line[i].fp;
}
delete[] pBuf_Line;
pCur_Entry=pBuf_Table;
while (pCur_Entry)
{
pTemp_Entry=pCur_Entry;
pCur_Entry=pCur_Entry->next;
delete pTemp_Entry;
}
pCur_Item=pBuf_History;
while (pCur_Item)
{
pTemp_Item=pCur_Item;
pCur_Item=pCur_Item->next;
delete pTemp_Item;
}
}
void Buffer::Change_History(int iBuf_No)
{
History *pPrev_Item,*pCur_Item;
pCur_Item=pBuf_History;
pPrev_Item=NULL;
while (pCur_Item && pCur_Item->iBuf_No!=iBuf_No)
{
pPrev_Item=pCur_Item;
pCur_Item=pCur_Item->next;
}
if (!pCur_Item)
{
pPrev_Item=new History;
pPrev_Item->iBuf_No=iBuf_No;
pPrev_Item->next=pBuf_History;
pBuf_History=pPrev_Item;
}
else
if (pPrev_Item)
{
pPrev_Item->next=pCur_Item->next;
pCur_Item->next=pBuf_History;
pBuf_History=pCur_Item;
}
}
int Buffer::Replace_Block(int &iBuf_No)
{
int iLen,iErr_Code;
History *pBuf_Replace;
Buffer_Table *pCur_Entry;
int iCur_Buf_No,iPrev_Buf_No;
pBuf_Replace=pBuf_History;
while(pBuf_Replace->next)
pBuf_Replace=pBuf_Replace->next;
iBuf_No=pBuf_Replace->iBuf_No;
pBuf_Line[iBuf_No].bValid=0;
pCur_Entry=pBuf_Table;
while (pCur_Entry->fd!=pBuf_Line[iBuf_No].fp->fd)
pCur_Entry=pCur_Entry->next;
if (pBuf_Line[iBuf_No].bModified==1)
{
if (pBuf_Line[iBuf_No].fp->First_Block_Num==0xFFFF)
pBuf_Line[iBuf_No].fp->First_Block_Num=pCur_Entry->iFirst_Block;
iErr_Code=pVFS->WriteFile(pBuf_Line[iBuf_No].fp,pBuf_Line[iBuf_No].Content,pBuf_Line[iBuf_No].iLength,iLen);
if (iErr_Code!=ERR_SUCCESS)
return iErr_Code;
pBuf_Line[iBuf_No].iLength=0;
if (pCur_Entry->iFirst_Block==0xFFFF)
pCur_Entry->iFirst_Block=pBuf_Line[iBuf_No].fp->First_Block_Num;
}
iPrev_Buf_No=BUFFER_BLOCK_NUM;
iCur_Buf_No=pCur_Entry->iBuf_No;
while (iCur_Buf_No!=iBuf_No)
{
iPrev_Buf_No=iCur_Buf_No;
iCur_Buf_No=pBuf_Line[iCur_Buf_No].next;
}
if (iPrev_Buf_No==BUFFER_BLOCK_NUM)
pCur_Entry->iBuf_No=pBuf_Line[iCur_Buf_No].next;
else
pBuf_Line[iPrev_Buf_No].next=pBuf_Line[iCur_Buf_No].next;
return iErr_Code;
}
int Buffer::Alloc_Block(int &iBuf_No)
{
if (iFree_Block==BUFFER_BLOCK_NUM)
return Replace_Block(iBuf_No);
else
{
iBuf_No=iFree_Block;
iFree_Block=pBuf_Line[iFree_Block].next;
return ERR_SUCCESS;
}
}
int Buffer::Find_Block(FILE_HANDLE fd,int iPos,int &iBuf_No)
{
Buffer_Table *pCur_Entry;
int bFound=0;
pCur_Entry=pBuf_Table;
while (!bFound && pCur_Entry)
{
if (pCur_Entry->fd!=fd)
pCur_Entry=pCur_Entry->next;
else
{
iBuf_No=pCur_Entry->iBuf_No;
while (!bFound && iBuf_No!=BUFFER_BLOCK_NUM)
if (pBuf_Line[iBuf_No].fp->Base_Pos<=iPos && iPos<pBuf_Line[iBuf_No].fp->Base_Pos+iBuffer_Block_Size)
bFound=1;
else
iBuf_No=pBuf_Line[iBuf_No].next;
if (iBuf_No==BUFFER_BLOCK_NUM)
break;
}
}
return bFound;
}
void Buffer::Add_Entry(FILE_HANDLE fd,int iBuf_No)
{
Buffer_Table *pCur_Entry,*pPrev_Entry;
int iPrev_Buf_No=BUFFER_BLOCK_NUM;
pPrev_Entry=NULL;
pCur_Entry=pBuf_Table;
while (pCur_Entry && pCur_Entry->fd!=fd)
{
pPrev_Entry=pCur_Entry;
pCur_Entry=pCur_Entry->next;
}
if (!pCur_Entry)
if (!pPrev_Entry)
{
pBuf_Table=new Buffer_Table;
pBuf_Table->iBuf_No=iBuf_No;
pBuf_Table->next=NULL;
pBuf_Table->fd=fd;
pBuf_Table->iFirst_Block=0xFFFF;
}
else
{
pCur_Entry=new Buffer_Table;
pCur_Entry->fd=fd;
pCur_Entry->iBuf_No=iBuf_No;
pCur_Entry->next=NULL;
pPrev_Entry->next=pCur_Entry;
pCur_Entry->iFirst_Block=0xFFFF;
}
else
{
iPrev_Buf_No=pCur_Entry->iBuf_No;
while (pBuf_Line[iPrev_Buf_No].next!=BUFFER_BLOCK_NUM)
iPrev_Buf_No=pBuf_Line[iPrev_Buf_No].next;
pBuf_Line[iPrev_Buf_No].next=iBuf_No;
}
}
void Buffer::Free_Block(int iBuf_No)
{
int iPrev_Buf_No;
iPrev_Buf_No=iFree_Block;
if (iPrev_Buf_No!=BUFFER_BLOCK_NUM)
{
while (pBuf_Line[iPrev_Buf_No].next!=BUFFER_BLOCK_NUM)
iPrev_Buf_No=pBuf_Line[iPrev_Buf_No].next;
pBuf_Line[iPrev_Buf_No].next=iBuf_No;
}
else
iFree_Block=iBuf_No;
pBuf_Line[iBuf_No].next=BUFFER_BLOCK_NUM;
}
int Buffer::Buffer_Read(File_Struct *fp,Byte *pDest,int iOffset,int &iLen)
{
int iCur_Pos,iErr_Code=ERR_SUCCESS;
Byte *pCur_Dest;
FILE_HANDLE fd;
int iBuf_No=BUFFER_BLOCK_NUM;
iLen=0;
fd=fp->fd;
pCur_Dest=pDest;
iCur_Pos=fp->Base_Pos;
while (iLen<iOffset && iErr_Code==ERR_SUCCESS)
{
if (Find_Block(fp->fd,iCur_Pos,iBuf_No))
{
Change_History(iBuf_No);
while (iLen<iOffset && iCur_Pos<pBuf_Line[iBuf_No].fp->Base_Pos+pBuf_Line[iBuf_No].iLength)
{
iLen++;
*pCur_Dest++=pBuf_Line[iBuf_No].Content[iCur_Pos++-pBuf_Line[iBuf_No].fp->Base_Pos];
}
fp->Base_Pos=iCur_Pos;
}
else
{
iErr_Code=Alloc_Block(iBuf_No);
if (iErr_Code==ERR_SUCCESS)
{
pBuf_Line[iBuf_No].bModified=0;
pBuf_Line[iBuf_No].bValid=1;
memcpy(pBuf_Line[iBuf_No].fp,fp,sizeof(File_Struct));
pBuf_Line[iBuf_No].next=BUFFER_BLOCK_NUM;
iErr_Code=pVFS->ReadFile(pBuf_Line[iBuf_No].fp,pBuf_Line[iBuf_No].Content,iBuffer_Block_Size,pBuf_Line[iBuf_No].iLength);
if (iErr_Code==EXC_END_OF_FILE)
iErr_Code=ERR_SUCCESS;
}
if (iErr_Code!=ERR_SUCCESS)
Free_Block(iBuf_No);
else
{
Add_Entry(fd,iBuf_No);
memcpy(pBuf_Line[iBuf_No].fp,fp,sizeof(File_Struct));
if (pBuf_Line[iBuf_No].iLength>iBuffer_Block_Size)
pBuf_Line[iBuf_No].iLength=iBuffer_Block_Size;
}
}
}
return iErr_Code;
}
int Buffer::Buffer_Write(File_Struct *fp,Byte *pSource,int iOffset,int &iLen)
{
int iCur_Pos,iErr_Code=ERR_SUCCESS;
Byte *pCur_Source;
FILE_HANDLE fd;
int iBuf_No=BUFFER_BLOCK_NUM;
iLen=0;
fd=fp->fd;
pCur_Source=pSource;
iCur_Pos=fp->Base_Pos;
while (iLen<iOffset && iErr_Code==ERR_SUCCESS)
{
if (Find_Block(fp->fd,iCur_Pos,iBuf_No))
{
Change_History(iBuf_No);
while (iLen<iOffset && iCur_Pos<pBuf_Line[iBuf_No].fp->Base_Pos+iBuffer_Block_Size)
{
iLen++;
pBuf_Line[iBuf_No].Content[iCur_Pos++-pBuf_Line[iBuf_No].fp->Base_Pos]=*pCur_Source++;
if (pBuf_Line[iBuf_No].iLength<iCur_Pos-pBuf_Line[iBuf_No].fp->Base_Pos)
pBuf_Line[iBuf_No].iLength=iCur_Pos-pBuf_Line[iBuf_No].fp->Base_Pos;
}
pBuf_Line[iBuf_No].bModified=1;
fp->Base_Pos=iCur_Pos;
}
else
{
iErr_Code=Alloc_Block(iBuf_No);
if (iErr_Code==ERR_SUCCESS)
{
pBuf_Line[iBuf_No].bModified=0;
pBuf_Line[iBuf_No].bValid=1;
memcpy(pBuf_Line[iBuf_No].fp,fp,sizeof(File_Struct));
pBuf_Line[iBuf_No].next=BUFFER_BLOCK_NUM;
}
if (iErr_Code!=ERR_SUCCESS)
Free_Block(iBuf_No);
else
Add_Entry(fd,iBuf_No);
}
}
return iErr_Code;
}
void Buffer::Show_Buffer(FILE_HANDLE fd)
{
Buffer_Table *pCur_Entry;
int iBuf_No,i;
printf("The buffer of file %d is as follows.\n",fd);
pCur_Entry=pBuf_Table;
while (pCur_Entry && pCur_Entry->fd!=fd)
pCur_Entry=pCur_Entry->next;
if (pCur_Entry)
{
iBuf_No=pCur_Entry->iBuf_No;
while (iBuf_No!=BUFFER_BLOCK_NUM)
{
printf("\nBuffer block %d :\n",iBuf_No);
for (i=0;i<pBuf_Line[iBuf_No].iLength;i++)
putch(pBuf_Line[iBuf_No].Content[i]);
iBuf_No=pBuf_Line[iBuf_No].next;
putch('\n');
}
}
else
printf("No buffer.\n");
}
int Buffer::Buffer_Flush(File_Struct *fp)
{
Buffer_Table *pCur_Entry,*pPrev_Entry;
int iBuf_No,iLen,iErr_Code=ERR_SUCCESS,iTemp;
pPrev_Entry=NULL;
pCur_Entry=pBuf_Table;
while (pCur_Entry && pCur_Entry->fd!=fp->fd)
{
pPrev_Entry=pCur_Entry;
pCur_Entry=pCur_Entry->next;
}
if (pCur_Entry)
{
iBuf_No=pCur_Entry->iBuf_No;
while (iBuf_No!=BUFFER_BLOCK_NUM && iErr_Code==ERR_SUCCESS)
{
pBuf_Line[iBuf_No].bValid=0;
if (pBuf_Line[iBuf_No].bModified==1)
{
if (pBuf_Line[iBuf_No].fp->First_Block_Num==0xFFFF)
pBuf_Line[iBuf_No].fp->First_Block_Num=pCur_Entry->iFirst_Block;
iErr_Code=pVFS->WriteFile(pBuf_Line[iBuf_No].fp,pBuf_Line[iBuf_No].Content,pBuf_Line[iBuf_No].iLength,iLen);
if (iErr_Code!=ERR_SUCCESS)
return iErr_Code;
memcpy(fp,pBuf_Line[iBuf_No].fp,sizeof(File_Struct));
if (pCur_Entry->iFirst_Block==0xFFFF)
pCur_Entry->iFirst_Block=fp->First_Block_Num;
}
iTemp=iBuf_No;
iBuf_No=pBuf_Line[iBuf_No].next;
Free_Block(iTemp);
}
if (iErr_Code!=ERR_SUCCESS)
return iErr_Code;
if (pPrev_Entry)
pPrev_Entry->next=pCur_Entry->next;
else
pBuf_Table=pCur_Entry->next;
}
return iErr_Code;
} | [
"xmzhang@5428276e-be0b-f542-9301-ee418ed919ad"
]
| [
[
[
1,
374
]
]
]
|
dfb2b10f256c3a78382d04e1970ccf09cfbcf3e4 | 1e976ee65d326c2d9ed11c3235a9f4e2693557cf | /CommonSources/URLEncDecHelper.h | 3aa768a6fe9f668654eb4d320fe6546b84e4e622 | []
| no_license | outcast1000/Jaangle | 062c7d8d06e058186cb65bdade68a2ad8d5e7e65 | 18feb537068f1f3be6ecaa8a4b663b917c429e3d | refs/heads/master | 2020-04-08T20:04:56.875651 | 2010-12-25T10:44:38 | 2010-12-25T10:44:38 | 19,334,292 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,095 | h | // /*
// *
// * Copyright (C) 2003-2010 Alexandros Economou
// *
// * This file is part of Jaangle (http://www.jaangle.com)
// *
// * This Program is free software; you can redistribute it and/or modify
// * it under the terms of the GNU General Public License as published by
// * the Free Software Foundation; either version 2, or (at your option)
// * any later version.
// *
// * This Program is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU General Public License for more details.
// *
// * You should have received a copy of the GNU General Public License
// * along with GNU Make; see the file COPYING. If not, write to
// * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
// * http://www.gnu.org/copyleft/gpl.html
// *
// */
class URLEncDecHelper
{
public:
//Encodes the data with optional compression in one step
//The PHP CODE TO DECODE this data is:
//Case 1. bURLMode = TRUE, bEnableCompression = TRUE
// gzuncompress(base64_decode(strtr($_REQUEST["data"], '-_', '+/')));
//Case 2. bURLMode = TRUE, bEnableCompression = FALSE
// base64_decode(strtr($_REQUEST["data"], '-_', '+/'));
//NOT URL MODE will possible make errors if the return string is passed to a URL (not always) and the uncompression
// will fail
static LPSTR EncodeData(const LPBYTE data, INT& dataLen, BOOL bURLMode, BOOL bEnableCompression);
static LPBYTE DecodeData(LPCSTR data, INT dataLen, BOOL bURLMode, BOOL bEnableCompression);
static LPSTR EncodeBase64(const LPBYTE data, INT& dataLen, BOOL bURLMode);
static LPBYTE DecodeBase64(LPCSTR data, INT& dataLen, BOOL bURLMode);
#ifdef HAVE_ZLIB
static LPBYTE CompressData(const LPBYTE data, INT& dataLen);
static LPBYTE DeCompressData(const LPBYTE data, INT& dataLen);
#endif
static LPSTR EncodeHex(const BYTE* byteBuffer, INT byteBufferLen);
static BYTE* DecodeHex(LPCSTR hex, INT hexLen = -1);
};
| [
"outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678"
]
| [
[
[
1,
49
]
]
]
|
c81adf25d8d48146a5b8fdc4e2da218b1d4bb777 | 63fc6506b8e438484a013b3c341a1f07f121686b | /apps/addonsExamples/allTestExample/src/testApp.cpp | f8f3d4e793d30892b77cc07424780243bc2ad841 | []
| no_license | progen/ofx-dev | c5a54d3d588d8fd7318e35e9b57bf04c62cda5a8 | 45125fcab657715abffc7e84819f8097d594e28c | refs/heads/master | 2021-01-20T07:15:39.755316 | 2009-03-03T22:33:37 | 2009-03-03T22:33:37 | 140,479 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,280 | cpp | #include "testApp.h"
//--------------------------------------------------------------
void testApp::setup(){
ofBackground(127,127,127);
}
//--------------------------------------------------------------
void testApp::update(){
}
//--------------------------------------------------------------
void testApp::draw(){
ofSetColor(0xffffff);
ofDrawBitmapString("this app doesn't do anything :) \nIt's just a test to see if many of the common addons \ncan work in the same place w/ no include \nor linking issues...\n\nif you're seeing this, it's good!", 100,100);
}
//--------------------------------------------------------------
void testApp::keyPressed (int key){
}
//--------------------------------------------------------------
void testApp::keyReleased (int key){
}
//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::mouseReleased(){
}
| [
"[email protected]"
]
| [
[
[
1,
43
]
]
]
|
1c6872787daee43cd6c15c5838bb5c81b951ce50 | 210f577f3ee8fd0b56c2787272110139c9ff07c5 | /src/DrawRect.h | c725c483219de53c8bda39370cfd95047b8fdb1a | []
| no_license | kaleidosgu/uiwndbaseinsdl | 37a17d11d52f830ffe66cfaa8414b869c495e8d6 | d36153fdba291436c1abe9e341e550606878d4e6 | refs/heads/master | 2021-01-22T21:13:22.745642 | 2010-08-10T07:51:35 | 2010-08-10T07:51:35 | 32,836,236 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 407 | h | #pragma once
#include "SDL_video.h"
#include "SDL_stdinc.h"
#include "Draw.h"
#include "DllExport.h"
class WND_EXPORT CDrawRect : public CDraw
{
public:
CDrawRect(void);
virtual ~CDrawRect(void);
virtual void OnDraw();
void SetColor( const Uint8 r, const Uint8 g, const Uint8 b );
void GetColor( Uint8& r, Uint8& g, Uint8& b );
private:
Uint8 m_crR;
Uint8 m_crG;
Uint8 m_crB;
};
| [
"[email protected]"
]
| [
[
[
1,
19
]
]
]
|
fc779a4f16aae96cf3aa00ab20044fdb59646634 | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Targets/WayFinder/symbian-r6/WayFinderApp.h | 9a8cda0d285bfb334931fcf67c17f191bc51f0a2 | [
"BSD-3-Clause"
]
| permissive | ravustaja/Wayfinder-S60-Navigator | ef506c418b8c2e6498ece6dcae67e583fb8a4a95 | 14d1b729b2cea52f726874687e78f17492949585 | refs/heads/master | 2021-01-16T20:53:37.630909 | 2010-06-28T09:51:10 | 2010-06-28T09:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,751 | h | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef WAYFINDERAPP_H
#define WAYFINDERAPP_H
// INCLUDES
#include <aknapp.h>
// CONSTANTS
// UID of the application
extern const TUid KUidWayFinder;
// CLASS DECLARATION
/**
* CWayFinderApp application class.
* Provides factory to create concrete document object.
*
*/
class CWayFinderApp : public CAknApplication
{
public: // Functions from base classes
/**
* From CEikApplication, determins the name of the resource file
* to be loaded. Useful way to override which language resources
* are loaded.
* @return The filename to be loaded.
*/
virtual TFileName ResourceFileName() const;
private:
/**
* From CApaApplication, creates CWayFinderDocument document object.
* @return A pointer to the created document object.
*/
CApaDocument* CreateDocumentL();
/**
* From CApaApplication, returns application's UID (KUidWayFinder).
* @return The value of KUidWayFinder.
*/
TUid AppDllUid() const;
// New function - helper for ResourceFileName();
TFileName AttemptResourceNameL(RFs & fs, const TDesC & startName, const TDesC & sysFileName) const;
};
#endif
// End of File
| [
"[email protected]"
]
| [
[
[
1,
65
]
]
]
|
fe17f2951e584fb765a01bb7b38756c45925e73d | 79cbdf99590cb47e7b8020da2db7fd400b028c4c | /include/dmem/list.h | 205a6703c37d2e286d6d70a7d0aac52aec7d96f7 | []
| no_license | jmckaskill/mt | af1b471478d03d554fb84b4f0bd0887575c78507 | 485a786c49ea7d2995eada4f1ccb230ed155a18a | refs/heads/master | 2020-06-09T01:03:41.579618 | 2011-02-26T05:26:14 | 2011-02-26T05:26:14 | 1,413,794 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,264 | h | /* vim: set et sts=4 ts=4 sw=4: */
#ifndef DMEM_LIST_H
#define DMEM_LIST_H
#include "common.h"
#include <stdlib.h>
#include <stddef.h>
#include <assert.h>
/* This is a doubly linked circular list.
*
* - The list can optionally hold onto the next value when iterating, so that
* you can remove items from the list whilst iterating. Iterating in this
* manner however is non-reentrant.
* - The list must be cleared before using.
*
* To iterate over the list:
*/
#if 0
typedef struct SomeType SomeType;
struct SomeType {
d_ListNode(SomeType) hl;
};
d_List(SomeType) list;
dl_clear(SomeType, hl, &list);
dl_append(hl, &list, calloc(1, sizeof(SomeType)));
/* Storing the iterator in the list */
SomeType* i;
for (i = dl_begin(&list); i != dl_end(&list); i = dl_getiter(&list)) {
dl_setiter(hl, &list, i->hl.next);
dowork(i);
dl_remove(hl, i);
free(i);
}
/* Iterating in a standard manner */
for (i = dl_begin(&list); i != dl_end(&list); i = i->hl.next) {
dowork(i);
}
#endif
/* Define the list structs
* @type: the type of node held in the list
*/
#define DLIST_INIT(type) \
typedef struct d_List_##type { \
type* next; \
type* prev; \
type* iter; \
type* fake_node; \
} d_List_##type; \
\
typedef struct d_ListNode_##type { \
type* next; \
type* prev; \
d_List_##type* list; \
} d_ListNode_##type \
#ifdef __cplusplus
template <class T>
struct d_List {
T* next;
T* prev;
T* iter;
T* fake_node;
};
template <class T>
struct d_ListNode {
d_ListNode() : next(NULL), prev(NULL), list(NULL) {}
T* next;
T* prev;
d_List<T>* list;
};
#endif
/* List type
* @type: the type of node held in the list
*/
#define d_List(type) d_List_##type
/* List header type - used as a member in each node
* @type: the type of node held in the list
*/
#define d_ListNode(type) d_ListNode_##type
/* Removes a node from the list
* @header: the d_ListHeader(type) member in @type
* @v: pointer to the node to remove from the list
*/
#define dl_remove(header, v) \
do { \
if ((v)->header.list) { \
(v)->header.next->header.prev = (v)->header.prev; \
(v)->header.prev->header.next = (v)->header.next; \
\
if ((v)->header.list->iter == (v)) { \
(v)->header.list->iter = (v)->header.next; \
} \
} \
\
(v)->header.next = NULL; \
(v)->header.prev = NULL; \
(v)->header.list = NULL; \
} while(0) \
/* Clears and initializes a list
* @type: the type held in the list
* @header: the d_ListHeader(type) member in @type
* @plist: pointer to a d_List(type) which holds the list
*/
#define dl_clear(type, header, plist) \
do { \
(plist)->iter = NULL; \
(plist)->prev = container_of(plist, type, header); \
(plist)->next = container_of(plist, type, header); \
(plist)->fake_node = container_of(plist, type, header); \
assert(&(plist)->next == &(plist)->fake_node->header.next); \
} while(0) \
/* Adds a node to the beginning of the list
* @header: the d_ListHeader(type) member in @type
* @plist: pointer to a d_List(type) which holds the list
* @v: pointer to the node to prepend to the list
*/
#define dl_prepend(header, plist, v) \
do { \
(v)->header.list = plist; \
(v)->header.prev = (plist)->fake_node; \
(v)->header.next = (plist)->fake_node; \
(v)->header.prev->header.next = v; \
(v)->header.next->header.prev = v; \
} while(0) \
/* Adds a node to the end of the list
* @header: the d_ListHeader(type) member in @type
* @plist: pointer to a d_List(type) which holds the list
* @v: pointer to the node to append to the list
*/
#define dl_append(header, plist, v) \
do { \
(v)->header.list = plist; \
(v)->header.prev = (plist)->prev; \
(v)->header.next = (plist)->fake_node; \
(v)->header.prev->header.next = v; \
(v)->header.next->header.prev = v; \
} while(0) \
#define dl_setiter(plist, v) \
do { \
(plist)->iter = v; \
} while(0) \
#define dl_getiter(plist) ((plist)->iter)
#define dl_isempty(plist) ((plist)->next == (plist)->fake_node)
#define dl_begin(plist) ((plist)->next)
#define dl_end(plist) ((plist)->fake_node)
#endif /* DMEM_LIST_H */
| [
"[email protected]"
]
| [
[
[
1,
171
]
]
]
|
0993ad0c00c243af6589ba57126f24317e4bb2a3 | ef25bd96604141839b178a2db2c008c7da20c535 | /src/src/Engine/Core/Singleton.h | 9f7c65df383657c9346ac2b2796c19ec3ffa7437 | []
| no_license | OtterOrder/crock-rising | fddd471971477c397e783dc6dd1a81efb5dc852c | 543dc542bb313e1f5e34866bd58985775acf375a | refs/heads/master | 2020-12-24T14:57:06.743092 | 2009-07-15T17:15:24 | 2009-07-15T17:15:24 | 32,115,272 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,400 | h | #ifndef _Singleton_H
#define _Singleton_H
//******************************************************************
#include <stdlib.h>
//******************************************************************
// Note: pour les classes template, on doit obligatoirement tout
// définir dans le .h (c'est crade, mais c'est imposé par le c++).
template< typename T >
class Singleton
{
public:
/***********************************************************
* Donne l'instance du singleton.
* @return pointeur sur l'instance
**********************************************************/
static T* GetInstance( void )
{
if( !m_Instance )
m_Instance = new T;
return m_Instance;
}
/***********************************************************
* Détruit l'instance.
**********************************************************/
static void Destroy( void )
{
if( m_Instance )
{
delete m_Instance;
m_Instance = NULL;
}
}
protected:
Singleton ( void ){} // Constructeur
virtual ~Singleton ( void ){} // Destructeur
private:
static T *m_Instance; // Instance du singleton
};
//******************************************************************
template< typename T >
T* Singleton< T >::m_Instance = NULL;
//******************************************************************
#endif // _Singleton_H
| [
"mathieu.chabanon@7c6770cc-a6a4-11dd-91bf-632da8b6e10b"
]
| [
[
[
1,
61
]
]
]
|
5b8d86f581f01c63d1912fba9cb507d7fd8004d2 | b2d46af9c6152323ce240374afc998c1574db71f | /cursovideojuegos/theflostiproject/Code/Flosti Engine/Graphics/ASEObject/text.h | 9b5f698f4769fdaaec36592453a2fb3d28a59f08 | []
| no_license | bugbit/cipsaoscar | 601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4 | 52aa8b4b67d48f59e46cb43527480f8b3552e96d | refs/heads/master | 2021-01-10T21:31:18.653163 | 2011-09-28T16:39:12 | 2011-09-28T16:39:12 | 33,032,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 970 | h | #ifndef _TEXT_INC
#define _TEXT_INC
/*
A classic, used everywhere to read formatted text files without using Lex
and Yacc. Written in C around 1995
Re-vamped a million times, and included in several programs
Converted to C++ in 1.7.98 to use it in the Rayman project.
*/
class text
{
char *data;
unsigned int sl;
unsigned int size;
public:
text();
text(const char*);
void create(char *);
char *getword();
char *getcommaword();
int getint();
double getfloat();
int countword(char *);
int countwordfromhere(char *);
int countchar(char);
void reset();
void destroy();
void goback();
bool seek(char *);
int eof();
unsigned int getPos();
BOOL setPos(unsigned int posicion);
~text();
};
#endif | [
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
]
| [
[
[
1,
39
]
]
]
|
0a14f3e56d5b966e6a53ca287b43bdeabd8677b2 | b22c254d7670522ec2caa61c998f8741b1da9388 | /common/MapInfoXmlReader.h | 86fbbc7ac4a4c3ae71d5085a18c608856d5a9dcd | []
| no_license | ldaehler/lbanet | 341ddc4b62ef2df0a167caff46c2075fdfc85f5c | ecb54fc6fd691f1be3bae03681e355a225f92418 | refs/heads/master | 2021-01-23T13:17:19.963262 | 2011-03-22T21:49:52 | 2011-03-22T21:49:52 | 39,529,945 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,281 | h | /*
------------------------[ Lbanet Source ]-------------------------
Copyright (C) 2009
Author: Vivien Delage [Rincevent_123]
Email : [email protected]
-------------------------------[ GNU License ]-------------------------------
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-----------------------------------------------------------------------------
*/
#ifndef __LBA_NET_MAP_INFO_XML_READER_H__
#define __LBA_NET_MAP_INFO_XML_READER_H__
#include "WorldInfo.h"
#include <vector>
#include <map>
#include "Dialog.h"
#include "InventoryHandlerBase.h"
#include "ActorHandlerBase.h"
class TiXmlElement;
class Actor;
class SignalerBase;
class QuestHandler;
//*************************************************************************************************
//* class MapInfoXmlReader
//*************************************************************************************************
class MapInfoXmlReader
{
public:
// load a world information into memory
static bool LoadWorld(const std::string &Filename, WorldInfo & res);
// get world description
static void GetWorldDescription(const std::string &Filename,
std::string &WorldName, std::string &WorldDesc);
// load map actors into memory
static bool LoadActors(const std::string &Filename, std::map<long, SpriteInfo> &spinfos,
std::map<long, SpriteInfo> &vidinfos,
std::map<long, ModelInfo> &modelinfos,
std::map<long, Actor *> & vec,
SignalerBase * signaler, float AnimationSpeed,
InventoryHandlerBase * invH, QuestHandler * qH,
ActorHandlerBase * actH);
// load all sprites info
static bool LoadSprites(const std::string &Filename, std::map<long, SpriteInfo> &vec);
// get a text from file
static std::map<long, std::string> LoadTextFile(const std::string &Filename);
// get a text from file
static void GetAllTexts(const std::string &Filename, std::map<long, std::string> &txts);
// get a sound path from file
static std::string GetSoundPath(const std::string &Filename, long id);
// load all models info
static bool LoadModels(const std::string &Filename, std::map<long, ModelInfo> &vec);
// load inventory info
static bool LoadInventory(const std::string &Filename, std::map<long, ItemInfo> &mapinv);
// load quest info
static bool LoadQuests(const std::string &Filename, std::map<long, QuestPtr> &quests,
InventoryHandlerBase * invH, QuestHandler * qH, ActorHandlerBase * actH);
protected:
// load a map information into memory
static MapInfo LoadMap(TiXmlElement* pElem);
// load a condition information into memory
static ConditionBasePtr LoadCondition(TiXmlElement* pElem, InventoryHandlerBase * invH,
QuestHandler * qH, ActorHandlerBase * actH);
// load a dialog information into memory
static DialogHandlerPtr LoadDialog(TiXmlElement* pElem, InventoryHandlerBase * invH,
QuestHandler * qH, ActorHandlerBase * actH);
// load a dialog entry information into memory
static DialogEntryPtr LoadDialogEntry(TiXmlElement* pElem, InventoryHandlerBase * invH,
QuestHandler * qH, ActorHandlerBase * actH);
// load a dialog player choice information into memory
static DialogTreePlayerChoicePtr LoadPlayerChoice(TiXmlElement* pElem, InventoryHandlerBase * invH,
QuestHandler * qH, ActorHandlerBase * actH);
// load a dialog tree root information into memory
static DialogTreeRootPtr LoadTreeRoot(TiXmlElement* pElem, InventoryHandlerBase * invH,
QuestHandler * qH, ActorHandlerBase * actH);
};
#endif
| [
"vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13"
]
| [
[
[
1,
118
]
]
]
|
1607699dfa7bcb3ebfed47ca239cf45d9e49a942 | f9351a01f0e2dec478e5b60c6ec6445dcd1421ec | /itl/src/itl/var_permutation.hpp | 470d43e6a87013a865922c51c98fa257b8e1c1f6 | [
"BSL-1.0"
]
| permissive | WolfgangSt/itl | e43ed68933f554c952ddfadefef0e466612f542c | 6609324171a96565cabcf755154ed81943f07d36 | refs/heads/master | 2016-09-05T20:35:36.628316 | 2008-11-04T11:44:44 | 2008-11-04T11:44:44 | 327,076 | 0 | 1 | null | null | null | null | ISO-8859-1 | C++ | false | false | 9,241 | hpp | /*----------------------------------------------------------------------------+
Copyright (c) 1999-2006: Cortex Software GmbH, Kantstrasse 57, Berlin
+-----------------------------------------------------------------------------+
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
+----------------------------------------------------------------------------*/
#ifndef __var_permutation_JOFA_040621_H__
#define __var_permutation_JOFA_040621_H__
#include <string.h>
#include <itl/fixtupelconst.hpp>
#include <itl/itl_list.hpp>
namespace itl
{
template <int varCountV>
class var_permutation
{
public:
typedef itl::list<VarEnumTD> ListTD;
public:
var_permutation(): m_Size(0) {}
var_permutation(const var_permutation&);
var_permutation& operator = (const var_permutation&);
/// Hinten anfuegen
var_permutation& add(VarEnumTD var);
/// Von hinten 'count' Elemente loeschen
var_permutation& del(int count = 1);
int size()const { return m_Size; }
void setIdentity();
var_permutation& clear() { m_Size = 0; return *this; }
/** Liefert zum Index 'permIdx' die unabhängige Variable var=permutation[permIdx].
Da es sich um eine schnelle Primitive handelt, wird der Gültigkeitsbereich des
Arguments 0 <= permIdx <m_Size nicht geprüft. */
VarEnumTD operator[] (VarEnumTD permIdx)const { return m_Permutation[permIdx]; }
/** Liefert zum Index 'permIdx' die unabhängige Variable var=permutation[permIdx].
Liefert -1, wenn permIdx kein gültiger Index ist. */
VarEnumTD getVar(VarEnumTD permIdx)
{ return (0 <= permIdx && permIdx < m_Size) ? m_Permutation[permIdx] : UNDEFINED_INDEX; }
var_permutation operator() (VarEnumTD fst, VarEnumTD lst)const;
/** Index zur Variable 'var' finden. Liefert -1, wenn 'var' nicht gefunden.
index=find(var) ist hierbei der Index 0 <= index < m_Size der Permutation die den
Wert der unabhängigen Variable 'var' enthält. */
int find(VarEnumTD var)const;
/// Ist 'var' enthalten?
bool contains(VarEnumTD var)const { return 0 <= find(var); }
/// Fuege 'var' an der Stelle 'pos' ein. Liefert false, wenn insert scheitert.
bool insert(VarEnumTD var, int pos);
/// Das Element mit dem Wert 'val' loeschen
var_permutation& remove(VarEnumTD val);
/** 'perm' ist eine Permutation von 'seq', so dass perm eine Untersequenz
von *this ist, in der keine Vertauschungen der Reihenfolge von *this vorkommen.
'perm' ist vertauschungsfreie Untersequenz von *this.
Voraussetzung ist, dass die Elemente von 'seq' in *this enthalten sind. */
void consequent_permutation(var_permutation& perm, const var_permutation& seq)const;
/** Liefert den reduzierten Aggregationsgrad einer Untersequenz 'subSeq'.
'subSeq' hat natuerlich weniger Aggregationsgrade, als *this. Wir tun so,
als waeren alle Elemente von *this ausgeblendet. Jedes Element, das in
*this ausgebelendet ist, wird von grade abgezogen.
*/
int gradeReduct(int grade, const var_permutation& subSeq)const;
ListTD asList()const;
std::string as_string()const;
private:
VarEnumTD m_Permutation[varCountV];
int m_Size;
};
template <int varCountV>
var_permutation<varCountV>::var_permutation (const var_permutation<varCountV>& src)
{
m_Size = src.m_Size;
FOREACH_VAR_TO(idx, m_Size)
m_Permutation[idx] = src.m_Permutation[idx];
}
template <int varCountV>
var_permutation<varCountV>& var_permutation<varCountV>::operator = (const var_permutation<varCountV>& src)
{
if(&src != this)
{
m_Size = src.m_Size;
FOREACH_VAR_TO(idx, m_Size)
m_Permutation[idx] = src.m_Permutation[idx];
}
return *this;
}
template <int varCountV>
void var_permutation<varCountV>::setIdentity()
{
FOREACH_VAR(idx)
m_Permutation[idx] = idx;
m_Size = varCountV;
}
template <int varCountV>
var_permutation<varCountV>& var_permutation<varCountV>::add(VarEnumTD var)
{
if(m_Size < varCountV)
{
m_Permutation[m_Size] = var;
m_Size++;
}
return *this;
}
template <int varCountV>
var_permutation<varCountV>& var_permutation<varCountV>::del(int count) // = 1 default
{
int back = std::min(count, m_Size);
m_Size -= back;
return *this;
}
template <int varCountV>
var_permutation<varCountV> var_permutation<varCountV>::operator() (VarEnumTD fst, VarEnumTD lst)const
{
var_permutation perm;
for(VarEnumTD idx = fst; idx < lst; idx++)
perm.add((*this)[idx]);
return perm;
}
template <int varCountV>
var_permutation<varCountV>& var_permutation<varCountV>::remove(VarEnumTD val)
{
int doomedIdx = find(val);
if(doomedIdx == UNDEFINED_INDEX)
return *this;
for(int idx=doomedIdx; idx < (m_Size-1); idx++)
m_Permutation[idx] = m_Permutation[idx+1];
m_Size--;
return *this;
}
template <int varCountV>
int var_permutation<varCountV>::find(VarEnumTD val)const
{
int hit = UNDEFINED_INDEX;
for(int idx=0; idx<m_Size; idx++)
if(m_Permutation[idx]==val)
return idx;
return hit;
}
template <int varCountV>
bool var_permutation<varCountV>::insert(VarEnumTD var, int pos)
{
//JODO URG untested
J_ASSERT2(!contains(var), "var_permutation has to be unique");
if(varCountV <= var || varCountV == m_Size)
return false;
// Alle nach rechts schaufeln
for(int idx=pos; idx < m_Size; idx++)
m_Permutation[idx+1] = m_Permutation[idx];
m_Permutation[pos] = var;
}
template <int varCountV>
std::string var_permutation<varCountV>::as_string()const
{
std::string repr = "[";
int idx = 0;
if(m_Size>0)
repr += value<VarEnumTD>::to_string(m_Permutation[idx++]);
while(idx<m_Size)
repr += value<VarEnumTD>::to_string(m_Permutation[idx++]);
repr += "]";
return repr;
}
template <int varCountV>
typename itl::var_permutation<varCountV>::ListTD var_permutation<varCountV>::asList()const
{
ListTD seq;
int idx = 0;
while(idx < m_Size)
seq.push_back(m_Permutation[idx++]);
return seq;
}
template <int varCountV>
void var_permutation<varCountV>::consequent_permutation(var_permutation& perm, const var_permutation& seq)const
{
ListTD master = asList(),
conseq,
unseq = seq.asList();
master.consequent_permutation(conseq, unseq);
perm.clear();
const_FORALL(ListTD, it_, conseq)
perm.add(*it_);
}
template <int varCountV>
int var_permutation<varCountV>::gradeReduct(int grade, const var_permutation& subSeq)const
{
// subSeq ist echte Untersequenz von *this.
if(grade==0)
return 0;
int subIdx = 0;
for(int varIdx = 0; varIdx < size(); varIdx++)
{
if(subSeq[subIdx] == (*this)[varIdx])
subIdx++;
if(varIdx+1 == grade)
return subIdx;
}
}
} // namespace itl
#endif // __var_permutation_JOFA_040621_H__
| [
"jofaber@6b8beb3d-354a-0410-8f2b-82c74c7fef9a"
]
| [
[
[
1,
268
]
]
]
|
575e2dac9ca9cb6cd135a26892f57f674805db04 | e3e69b1533b942e6b834cc53a461e2bfce68244e | /instrumento.cpp | 4d35172ac76d71de10acf05c50664d56bf38481b | []
| no_license | berilevi/cidei | 89d396e67a934e2c5698bd6d3b8d177ea829d7b5 | 3c84935809f0a68783733db57c3de6fdad2ecedf | refs/heads/master | 2020-05-02T22:13:52.643632 | 2008-09-04T18:51:00 | 2008-09-04T18:51:00 | 33,262,364 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 15,093 | cpp | // Class automatically generated by Dev-C++ New Class wizard
#include "instrumento.h" // Archivo de cabecera de clase
// Constructor de la clase
Instrumento::Instrumento(){
strcpy(vid_pid, "vid_04d8&pid_000a"); // Product & Vendor ID
strcpy(out_pipe, "\\MCHP_EP3"); // End Point de salida
strcpy(in_pipe, "\\MCHP_EP3"); // End Point de salida
trama_control[0] = 0x01; // Valor de inicio de trama
trama_control[5] = 0x04; // Final de trama del protocolo
trama_control[6] = 0x00; // Fin de cadena que se va a transmitir
strcpy(buf_mult,"0000"); // Inicializar el bufer del multimetro.
ch1_muestreado = 0; // Inicializar el estado del muestreo del canal 1 del osciloscopio
ch2_muestreado = 0; // Inicializar el estado del muestreo del canal 2 del osciloscopio
idato_osc_ch1 =0; // Dato muestreado uno a uno por el canal 1 del osciloscopio
idato_osc_ch2 =0; // Dato muestreado uno a uno por el canal 2 del osciloscopio
}
// Destructor de clase
Instrumento::~Instrumento(){
}
// Asigna el valor a la variable bestado que representa si el instrumento está activo.
void Instrumento::activar(bool bx){
bestado = bx;
}
// Verificacion del estado de conexión con el hardware
void Instrumento::Sethardware(bool x){
bhardware = x;
}
/*******************************************************************************
* Instrumento::archivar: Genera un archivo plano con los datos enviados por el
* hardware.
*******************************************************************************/
void Instrumento::archivar(){
ofstream log("oscill.txt");
log << "Hello World" << endl;
log.close();
}
/*******************************************************************************
* Instrumento::Transmision: Realiza la comunicación con el hardware a traves de
* USB haciendo uso del framework que proporciona
* Microchip.
* MPUSBOpen(): Devuelve el acceso al pipe del Endpoint con el VID_PID asignado.
* selection: Número del dispositivo que se va a abrir, se utiliza cero (0),
* porque el software solo se va a comunicar con un dispositivo.
* MPUSBWrite(): Envía los datos de "trama_control" a traves de USB.
* MPUSBRead(): Recibe los datos enviados por el hardware a traves de USB.
* MPUSBClose(): Cierra la conexión USB del pipe.
*******************************************************************************/
void Instrumento::Transmision(){
if (bestado){ // Se ejecuta si el instrumento esta activo
DWORD selection; // Pipe para la transmision
fflush(stdin); // Limpiar Buffers
selection = 0; // El pipe para la comunicacion va a ser siempre el cero
myOutPipe = MPUSBOpen(selection,vid_pid,out_pipe,MP_WRITE,0); //Abrir el pipe de salida para escritura
myInPipe = MPUSBOpen(selection,vid_pid,out_pipe,MP_READ,0); //Abrir el pipe de entrada para lectura
if(myOutPipe == INVALID_HANDLE_VALUE || myInPipe == INVALID_HANDLE_VALUE) //Verificar que se abrieron correctamente los pipes
{
fl_message("Fallo en la comunicación USB.");
return;
}
DWORD RecvLength=190; //Longitud maxima del buffer que recibe los datos de transmision
DWORD SentDataLength;
MPUSBWrite(myOutPipe,trama_control,10,&SentDataLength,100); //Transmitir la trama al hardware
fflush(stdin); //Limpiar el buffer de salida
MPUSBRead(myInPipe,receive_buf,190,&RecvLength,100); //Recibir lo que transmite el hardware
MPUSBRead(myInPipe,receive_buf,190,&RecvLength,100);
Desencapsular(receive_buf); //Desencapsular la trama enviada desde el hardware
MPUSBClose(myOutPipe); //Cerrar los pipes al terminar cada comunicacion
MPUSBClose(myInPipe);
myOutPipe = myInPipe = INVALID_HANDLE_VALUE; //Dejar listos los pipes para la siguiente transmisión
}
else {
MPUSBClose(myOutPipe); //Cerrar los pipes al terminar cada comunicacion
MPUSBClose(myInPipe);
myOutPipe = myInPipe = INVALID_HANDLE_VALUE; //Dejar listos los pipes para la siguiente transmisión
return;
}
}
/*******************************************************************************
* Instrumento::Encapsular: Encapsula los datos en la trama de control del
* protocolo establecido para enviar los datos al
* hardware a traves de USB.
*******************************************************************************/
void Instrumento::Encapsular(char cnom, char coper, char clong, char cdato, char cfin, char cfin2){
trama_control[1] = cnom; //Dispositivo de hardware
trama_control[2] = coper; //Operacion que se va a realizar
trama_control[3] = clong; //Longitud de datos que se van a enviar
trama_control[4] = cdato; //Dato que se va a configurar en el hardware
trama_control[7] = cfin; //Dato que se va a configurar en el hardware
trama_control[8] = cfin2; //Dato que se va a configurar en el hardware
}
/*******************************************************************************
* Instrumento::Desencapsular: Desencapsula los datos enviados desde el hardware
* a los instrumentos de software a traves de USB.
* recibida[]: Trama de datos enviada por el hardware con los datos de los
* instrumentos.
* recibida[1]: Caracter que identifica el instrumento al que pertenecen los datos
* de la trama recibida[].
* 'A': Canal 1 Osciloscopio.
* 'B': Canal 2 Osciloscopio.
* 'C': Analizador Lógico.
* 'D': Voltímetro AC.
* 'E': Voltímetro DC.
* 'F': Amperímetro AC.
* 'G': Amperímetro DC.
* 'H': Ohmetro.
* 'I': Generador de señales.
* 'J': LIV Hardware completo pruebas de comunicación.
* 'K': Multímetro.
* 'L': Osciloscopio.
*******************************************************************************/
void Instrumento::Desencapsular(BYTE recibida []){
int icont = 0; //Contador auxiliar para los ciclos
int itamano;
itamano = int (recibida [3]); //Tamano de la informacion enviada para el Multímetro
switch (recibida [1]){
case 'A': //Informacion Canal 1
if (recibida [2] == '1'){ //Primer vector de datos para canal 1
for (icont = 4; icont < 132; icont++){
bufOscCh1[icont-4]=int(recibida[icont]);
}
}
else if (recibida [2] == '2'){ //Segundo vector de datos para el canal 1
for (icont = 4; icont < 132; icont++){
bufOscCh1[(icont-4)+127]=int(recibida[icont]);
}
}
else if (recibida [2] == '3'){ //Tercer vector de datos para el canal 1
for (icont = 4; icont < 132; icont++){
bufOscCh1[(icont-4)+253]=int(recibida[icont]);
}
}
else if (recibida [2] == '4'){ //Cuarto vector de datos para el canal 1
for (icont = 4; icont < 132; icont++){
bufOscCh1[(icont-4)+380]=int(recibida[icont]);
}
}
break;
case 'B': //Informacion para Canal 2
if (recibida [2] == '1'){ //Primer vector de datos para canal 2
for (icont = 4; icont < 132; icont++){
buf_osc_ch2[icont-4]=int(recibida[icont]);
}
}
else if (recibida [2] == '2'){ //Segundo vector de datos para canal 2
for (icont = 4; icont < 132; icont++){
buf_osc_ch2[(icont-4)+127]=int(recibida[icont]);
}
}
else if (recibida [2] == '3'){ //Tercer vector de datos para canal 2
for (icont = 4; icont < 132; icont++){
buf_osc_ch2[(icont-4)+253]=int(recibida[icont]);
}
}
else if (recibida [2] == '4'){ //Cuarto vector de datos para canal 2
for (icont = 4; icont < 132; icont++){
buf_osc_ch2[(icont-4)+380]=int(recibida[icont]);
}
}
break;
case 'C': //Informacion para Analizador lógico
if (recibida [2] == 'p'){
buf_analizador[0] = recibida[4];
buf_analizador[1] = recibida[5];
}
break;
case 'D': //Informacion para Voltimetro AC
strcpy(buf_mult,"0000");
for (icont=4;icont<(itamano+4);icont++){
buf_mult[icont-4]=receive_buf[icont];
}
if (itamano < 4){
buf_mult[itamano] = 0x00;
}
imult_escala = int(recibida[2]-48);
break;
case 'E': //Informacion para Voltimetro DC
strcpy(buf_mult,"0000");
for (icont=4;icont<(itamano+4);icont++){
buf_mult[icont-4]=receive_buf[icont];
}
if (itamano < 4){
buf_mult[itamano] = 0x00;
}
imult_escala = int(recibida[2]-48);
break;
case 'F': //Informacion para Amperimetro AC
strcpy(buf_mult,"0000");
for (icont=4;icont<(itamano+4);icont++){
buf_mult[icont-4]=receive_buf[icont];
}
if (itamano < 4){
buf_mult[itamano] = 0x00;
}
imult_escala = int(recibida[2]-48);
break;
case 'G': //Informacion para Amperimetro DC
strcpy(buf_mult,"0000");
for (icont=4;icont<(itamano+4);icont++){
buf_mult[icont-4]=receive_buf[icont];
}
if (itamano < 4){
buf_mult[itamano] = 0x00;
}
imult_escala = int(recibida[2]-48);
break;
case 'H': //Informacion para Ohmetro
strcpy(buf_mult,"0000");
for (icont=4;icont<(itamano+4);icont++){
buf_mult[icont-4]=receive_buf[icont];
}
if (itamano < 4){
buf_mult[itamano] = 0x00;
}
imult_escala = int(recibida[2]-48);
break;
case 'I': //Informacion para Generador de señales
break;
case 'J': //Pruebas de conectividad de LIV
if (recibida [2]== 0x06){ //ACK
Sethardware(true);
}
else if (recibida [2] == 0x15){ //NACK
Sethardware(false);
}
break;
case 'K': //Informacion para el Multimetro
break;
case 'L': //Informacion para el Osciloscopio
if (recibida [2] == 'p'){
if (recibida [4]== '1'){ //Muestreo completo de señal en canal 1 del osciloscopio
ch1_muestreado = 1;
}
else if(recibida [4]== '2'){ //Muestreo completo de señal en canal 2 del osciloscopio
ch2_muestreado = 1;
}
else if(recibida [4]== '3'){ //Muestreo completo de señal en canal 2 del osciloscopio
ch2_muestreado = 1;
ch1_muestreado = 1;
}
}
else if (recibida [2] == '1'){ // Muestreo de la señal dato por dato en canal 1
idato_osc_ch1=int(recibida[4]);
}
else if (recibida [2] == '2'){ // Muestreo de la señal dato por dato en canal 2
idato_osc_ch2=int(recibida[5]);
}
else if (recibida [2] == '3'){ // Muestreo de las señales dato por dato con los dos canales
idato_osc_ch1=int(recibida[4]);
idato_osc_ch2=int(recibida[5]);
}
break;
}
}
| [
"juanpab1980@b98271d3-b73c-0410-b3e6-1dfb2072a0f9"
]
| [
[
[
1,
282
]
]
]
|
f2ef3497cf5f68e7f16df6715a6e389e8cd13191 | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Common/Scd/ScExec/EXECLIB.CPP | b82ebc2e3f55fdf68c8e816bb28a47d8916389e1 | []
| 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 | 41,847 | cpp | //================== SysCAD - Copyright Kenwalt (Pty) Ltd ===================
// $Nokeywords: $
//===========================================================================
#include "stdafx.h"
#include "sc_defs.h"
#define __EXECLIB_CPP
#include "execlib.h"
#ifdef _DEBUG
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif
#define dbgSmallBuffer 0
IMPLEMENT_SPARES(CXM_DataRequest, 1000)
IMPLEMENT_SPARES(CXM_DataAvailable, 1000)
IMPLEMENT_SPARES(CXM_TagNotAvail, 1000)
IMPLEMENT_SPARES(CXM_ObjectTag, 1000)
IMPLEMENT_SPARES(CXM_ObjectData, 1000)
IMPLEMENT_SPARES(CXM_Route, 1000)
IMPLEMENT_SPARES(CXM_ReadIndexedData, 1000)
IMPLEMENT_SPARES(CXM_HistoryExists, 1000)
IMPLEMENT_SPARES(CXM_KeepHistory, 1000)
IMPLEMENT_SPARES(CXM_KeepHistoryFile, 100)
IMPLEMENT_SPARES(CXM_QueryHistory, 1000)
IMPLEMENT_SPARES(CXM_QueryHistoryOther, 1000)
IMPLEMENT_SPARES(CXM_QueryString, 1000)
IMPLEMENT_SPARES(CXM_QueryRow, 1000)
IMPLEMENT_SPARES(CXM_QueryRowEx, 1000)
IMPLEMENT_SPARES(CXM_HistorySlotDlg, 1000)
IMPLEMENT_SPARES(CXM_HistoryData, 1000)
IMPLEMENT_SPARES(CXM_HistoryDataError, 1000)
IMPLEMENT_SPARES(CXM_HistRecordingOn, 1000)
IMPLEMENT_SPARES(CXM_QueryTime, 1000)
IMPLEMENT_SPARES(CXM_Execute, 1000)
IMPLEMENT_SPARES(CXM_TimeControl, 1000)
IMPLEMENT_SPARES(CXM_Long, 1000)
IMPLEMENT_SPARES(CXM_Boolean, 1000)
IMPLEMENT_SPARES(CXM_Double, 1000)
IMPLEMENT_SPARES(CXM_String, 1000)
#if WITHDDEREPORTS
IMPLEMENT_SPARES(CXM_DDEReport, 1000)
IMPLEMENT_SPARES(CXM_DDEErrorCode, 1000)
#endif
IMPLEMENT_SPARES(CXM_DrvShowTagInfo, 1000)
IMPLEMENT_SPARES(CXM_OleExcelReport, 1000)
IMPLEMENT_SPARES(CXM_OleErrorCode, 1000)
IMPLEMENT_SPARES(CXM_RepTrendDB, 1000)
IMPLEMENT_SPARES(CXM_ArchiveExists, 1000)
IMPLEMENT_SPARES(CXM_ArcShowTagInfo, 1000)
IMPLEMENT_SPARES(CXM_KeepArchive, 1000)
IMPLEMENT_SPARES(CXMsgLst, 100)
//===========================================================================
static long CXM_HeaderCnt=0;
CXM_Header::CXM_Header(byte MsgId/*=XM_Null*/)
{
Id=MsgId;
m_dwLength=0;// Invalid Size - Must be set in derived classes
//dbgpln(">>>> %4i) 0x%08x %3i", ++CXM_HeaderCnt, this, Id);
}
//---------------------------------------------------------------------------
CXM_Header::CXM_Header(const CXM_Header& Cpy)
{
memcpy(this, &Cpy, Cpy.Length());
//dbgpln(">>>> %4i) 0x%08x %3i", ++CXM_HeaderCnt, this, Id);
};
//---------------------------------------------------------------------------
CXM_Header::~CXM_Header()
{
//dbgpln(" << 0x%08x %3i", this, Id);
};
//---------------------------------------------------------------------------
CXM_Header& CXM_Header::operator=(const CXM_Header& Cpy)
{
memcpy(this, &Cpy, Cpy.Length());
return *this;
};
//===========================================================================
CXM_DataRequest::CXM_DataRequest(long Inx, char * pTag, TABOptions Opts, XIOAction Act)
{
Index=Inx;
Options=Opts;
Action=Act;
strcpy(Tag, pTag);
// CXM_Header
Id=XM_DataRequest;
m_dwLength=(&Tag[0]-(char*)this) +strlen(Tag) + 1;
}
//---------------------------------------------------------------------------
void CXM_DataRequest::Set(long Inx, char * pTag, TABOptions Opts, XIOAction Act)
{
Index=Inx;
Options=Opts;
Action=Act;
strcpy(Tag, pTag);
// CXM_Header
Id=XM_DataRequest;
m_dwLength=(&Tag[0]-(char*)this) +strlen(Tag) + 1;
};
//===========================================================================
CXM_DataAvailable::CXM_DataAvailable(long Inx, char * pTag, XIOAction Act)
{
Index=Inx;
Action=Act;
strcpy(Tag, pTag);
// CXM_Header
Id=XM_DataAvailable;
m_dwLength=(&Tag[0]-(char*)this) +strlen(Tag) + 1;
}
//===========================================================================
CXM_TagNotAvail::CXM_TagNotAvail(long Inx, char * pTag)
{
Index=Inx;
strcpy(Tag, pTag);
// CXM_Header
Id=XM_TagNotAvail;
m_dwLength=(&Tag[0]-(char*)this) +strlen(Tag) + 1;
}
//---------------------------------------------------------------------------
void CXM_TagNotAvail::Set(long Inx, char * pTag)
{
Index=Inx;
strcpy(Tag, pTag);
// CXM_Header
Id=XM_TagNotAvail;
m_dwLength=(&Tag[0]-(char*)this) +strlen(Tag) + 1;
};
//===========================================================================
CXM_ObjectTag::CXM_ObjectTag(char * pTag, TABOptions Opt)
{
Options=Opt;
strcpy(Tag, pTag);
// CXM_Header
Id=XM_ObjectTag;
m_dwLength=(&Tag[0]-(char*)this) +strlen(Tag) + 1;
}
//===========================================================================
#if _DEBUG
long CXM_ObjectData::m_nAllocs=0;
long CXM_ObjectData::m_LRange1=-1;
long CXM_ObjectData::m_LRange2=-1;
#endif
CXM_ObjectData::CXM_ObjectData(long Inx /*=0*/, dword Options/*=0*/)
{
Index=Inx;
dwOptions=Options;
// CXM_Header
Id=XM_ObjectData;
//m_pList=new CPkDataList;
m_dwLength=((char*)&m_List-(char*)this) + sizeof(m_List);
// m_dwLength=0;// still need to be set once Obj is Set;
#if _DEBUG
m_AllocNo=++m_nAllocs;
//dbgpln(" CXM_ObjectData [%5i] 0x%08x", m_AllocNo, this);
if (m_AllocNo>=m_LRange1 && m_AllocNo<=m_LRange2)
DoBreak();
#endif
}
//---------------------------------------------------------------------------
CXM_ObjectData::CXM_ObjectData(long Inx, dword Options, CPkDataItem * pItem)
{
Index=Inx;
dwOptions=Options;
//m_pList=new CPkDataList;
if (pItem)
{
m_List.AddTail(CPkDataItem::Create(*pItem));
//memcpy(&m_List, pList, pList->Size());
}
else
List.Clear();
// CXM_Header
Id=XM_ObjectData;
m_dwLength=((char*)&m_List-(char*)this) + sizeof(m_List);
#if _DEBUG
m_AllocNo=++m_nAllocs;
//dbgpln(" CXM_ObjectData [%5i] 0x%08x", m_AllocNo, this);
if (m_AllocNo>=m_LRange1 && m_AllocNo<=m_LRange2)
DoBreak();
#endif
//m_dwLength=((char*)&List-(char*)this) + List.Size();
}
//---------------------------------------------------------------------------
CXM_ObjectData::CXM_ObjectData(long Inx, dword Options, char *pTag, PkDataUnion &Data)
{
dwOptions=Options;
m_dwLength=((char*)&m_List-(char*)this) + sizeof(m_List);
//m_pList=new CPkDataList;
//CPkDataItem * pItem=List.FirstItem();
List.SetDataValue(pTag, 0, Data);
//SetSize();
#if _DEBUG
m_AllocNo=++m_nAllocs;
//dbgpln(" CXM_ObjectData [%5i] 0x%08x", m_AllocNo, this);
if (m_AllocNo>=m_LRange1 && m_AllocNo<=m_LRange2)
DoBreak();
#endif
};
//---------------------------------------------------------------------------
CXM_ObjectData::CXM_ObjectData(long Inx, dword Options, char *pTag, DDEF_Flags iFlags, PkDataUnion &Data)
{
dwOptions=Options;
m_dwLength=((char*)&m_List-(char*)this) + sizeof(m_List);
// m_pList=new CPkDataList;
//CPkDataItem * pItem=List.FirstItem();
List.SetDataValue(pTag, iFlags, Data);
//SetSize();
#if _DEBUG
m_AllocNo=++m_nAllocs;
// dbgpln(" CXM_ObjectData [%5i] 0x%08x", m_AllocNo, this);
if (m_AllocNo>=m_LRange1 && m_AllocNo<=m_LRange2)
DoBreak();
#endif
};
//---------------------------------------------------------------------------
CXM_ObjectData::~CXM_ObjectData()
{
#if _DEBUG
// dbgpln("~CXM_ObjectData [%5i] 0x%08x", m_AllocNo, this);
#endif
List.Clear();
};
//===========================================================================
CXM_Route::CXM_Route() { Clear(); };
CXM_Route::CXM_Route(const CXM_Route & X) : CXM_Header(X)
{
wEnd = X.wEnd;
bAcrossNetwork = X.bAcrossNetwork;
//wCurrentPos = X.wCurrentPos;
nNodes = X.nNodes;
memcpy(cBuffer, X.cBuffer, sizeof(cBuffer));
};
CXM_Route::~CXM_Route() {};
//---------------------------------------------------------------------------
void CXM_Route::Clear()
{
/*wCurrentPos=*/wEnd=0;
bAcrossNetwork=0;
nNodes=0;
Id=XM_Route;
m_dwLength=&cBuffer[wEnd]-(char*)this;
};
//---------------------------------------------------------------------------
flag CXM_Route::AddNodeFwd(long NodeObjId, char* NodeName)
{
Id=XM_Route;
if (wEnd+sizeof(long)+strlen(NodeName)+1<CXM_RouteBuffMax)
{
*((long*)(&cBuffer[wEnd])) = NodeObjId;
wEnd+=sizeof(long);
strcpy(&cBuffer[wEnd], NodeName);
wEnd+=strlen(NodeName)+1;
nNodes++;
m_dwLength=&cBuffer[wEnd]-(char*)this;
return True;
}
return False;
};
//---------------------------------------------------------------------------
flag CXM_Route::AddNodeRev(long NodeObjId, char* NodeName)
{
Id=XM_Route;
word l=sizeof(long)+strlen(NodeName)+1;
if (wEnd+l<CXM_RouteBuffMax)
{
memmove(&cBuffer[l], &cBuffer[0], wEnd);
wEnd+=l;
*((long*)(&cBuffer[0])) = NodeObjId;
strcpy(&cBuffer[sizeof(long)], NodeName);
nNodes++;
m_dwLength=&cBuffer[wEnd]-(char*)this;
return True;
}
return False;
};
//---------------------------------------------------------------------------
flag CXM_Route::RemoveNode(int n)
{
word p=0;
while (n-->0)
p+=strlen(&cBuffer[p+sizeof(long)])+1;
if (p<wEnd)
{
int l=sizeof(long) + strlen(&cBuffer[p+sizeof(long)])+1;
memmove(&cBuffer[p], &cBuffer[p+l], wEnd-(p+l));
nNodes--;
return True;
}
return False;
};
//---------------------------------------------------------------------------
long CXM_Route::NodeObjId(int n)
{
word p=0;
while (n-->0)
p+=sizeof(long)+strlen(&cBuffer[p+sizeof(long)])+1;
return p<wEnd ? *((long*)(&cBuffer[p])) : -1;
}
//---------------------------------------------------------------------------
char* CXM_Route::NodeName(int n)
{
word p=0;
while (n-->0)
p+=sizeof(long)+strlen(&cBuffer[p+sizeof(long)])+1;
return p<wEnd ? &cBuffer[p+sizeof(long)] : NULL;
}
//---------------------------------------------------------------------------
long CXM_Route::NoNodes() { return nNodes; };
//---------------------------------------------------------------------------
flag CXM_Route::operator==(CXM_Route &Other)
{
if (wEnd==Other.wEnd && nNodes==Other.nNodes)
return (memcmp(this, &Other, (char*)&cBuffer[wEnd]-(char*)this)==0);
return False;
};
//---------------------------------------------------------------------------
CXM_Route &CXM_Route::operator=(CXM_Route &Other)
{
Id=Other.Id;
m_dwLength=Other.m_dwLength;
wEnd=Other.wEnd;
nNodes=Other.nNodes;
bAcrossNetwork=Other.bAcrossNetwork;
memcpy(cBuffer, Other.cBuffer, wEnd);
return *this;
};
//---------------------------------------------------------------------------
void CXM_Route::ReverseRoute(CXM_Route &Other)
{
Clear();
for (int i=0; i<Other.NoNodes(); i++)
{
flag Ok=AddNodeRev(Other.NodeObjId(i),Other.NodeName(i));
ASSERT(Ok);
}
Id=Other.Id;
bAcrossNetwork=Other.bAcrossNetwork;
};
//---------------------------------------------------------------------------
char* CXM_Route::ComputerName()
{
static char CompName[MAX_COMPUTERNAME_LENGTH + 1 + 100];
DWORD CompNameLen=sizeof(CompName);
flag OK=GetComputerName(CompName, &CompNameLen);
ASSERT(OK);
return CompName;
}
//---------------------------------------------------------------------------
char* CXM_Route::MakeNodeName(char * Node, char * Where)
{
strcpy(Where, ComputerName());
strcat(Where, "(");
strcat(Where, Node);
strcat(Where, ")");
return Where;
}
//---------------------------------------------------------------------------
void CXM_Route::dbgDump(char * where/*=""*/)
{
dbgp("Route [%i] {%s}", NoNodes(), where);
for (int i=0; i<NoNodes(); i++)
dbgp(" - %s[%i]",NodeName(i),NodeObjId(i));
dbgpln("");
};
//===========================================================================
CXM_ReadIndexedData::CXM_ReadIndexedData(flag Strt, flag RdAll, long LastInx)
{
Start = Strt;
ReadAll=RdAll;
LastIndex=LastInx;
// CXM_Header
Id=XM_ReadIndexedData;
m_dwLength=sizeof(*this);
}
//===========================================================================
CXM_HistoryExists::CXM_HistoryExists(long Index, char * pNewTag)
{
char * p=cTag;
strcpy(p, pNewTag);
p+=strlen(pNewTag)+1;
*((long *)p)=Index;
p+=sizeof(long );
*((dword*)p)=0;
p+=sizeof(dword);
strcpy(p, ""); // terminator
p+=1;
Id=XM_HistoryExists;
m_dwLength=(p-(char*)this);
};
CXM_HistoryExists::CXM_HistoryExists()
{
strcpy(cTag, ""); // terminator
// CXM_Header
Id=XM_HistoryExists;
m_dwLength=(&cTag[0]-(char*)this)+strlen(cTag)+1;
};
flag CXM_HistoryExists::xAddTag(long Index, char * pNewTag)//, char * pPosition)
{
int l=strlen(pNewTag)+1+sizeof(long)+sizeof(dword)+1;
if (l+m_dwLength > sizeof(*this))
return False;
char * p=(char*)this+m_dwLength-1;
strcpy(p, pNewTag);
p+=strlen(pNewTag)+1;
*((long*)p)=Index;
p+=sizeof(long);
*((dword*)p)=0;
p+=sizeof(dword);
strcpy(p, "");
p+=1;
m_dwLength=(p-(char*)this);
return True;
}
char * CXM_HistoryExists::FirstTag()
{
return strlen(cTag)>0 ? cTag : NULL;
};
char * CXM_HistoryExists::NextTag(char * pPrevTag)
{
char *p=pPrevTag+strlen(pPrevTag)+1+sizeof(long)+sizeof(dword);
return strlen(p)>0 ? p : NULL;
};
long CXM_HistoryExists::GetIndex(char * pTag)
{
char* pVal=pTag+strlen(pTag)+1;
return *((long*)pVal);
};
void CXM_HistoryExists::SetFlags(char * pTag, dword Flags)
{
char* pVal=pTag+strlen(pTag)+1+sizeof(long);
*((dword*)pVal)=Flags;
};
dword CXM_HistoryExists::GetFlags(char * pTag)
{
char* pVal=pTag+strlen(pTag)+1+sizeof(long);
return *((dword*)pVal);
};
flag CXM_HistoryExists::Empty()
{
return (long)m_dwLength <= (&cTag[0]-(char*)this)+1;
};
//---------------------------------------------------------------------------
//CXM_KeepHistory::CXM_KeepHistory(long DataIndex,
// char tt_Type, flag bRealTime_, char * Tag, byte CnvNo, char * CnvTxt, char * Desc,
// double FilterTau, double WinFltPeriod, int WinFltCount, double FltDelta,
// double Min, double Max, double Decrease, double DeltaLo, double DeltaHi,
// int NoRec, int NoNotRec, int FilterAlg, int BoxcarAlg)
CXM_KeepHistory::CXM_KeepHistory(DataUnion* pVal, long DataIndex,
char tt_Type, char * Tag, CCnvIndex CnvNo, char * CnvTxt, char * Desc,
double FilterTau, double WinFltPeriod, int WinFltCount, double FltDelta,
double Change, double DeltaLo, double DeltaHi,
int NoRec, int NoNotRec, int FilterAlg, int BoxcarAlg,
flag RecordIt, flag Driver)
{
Val.Set(*pVal);
lDataIndex=DataIndex;
cType=tt_Type;
dFltTau=FilterTau;
dWinFltPeriod=WinFltPeriod;
iWinFltCount=WinFltCount;
dFltDelta=FltDelta;
dChange=Change;
dDeltaLo=DeltaLo;
dDeltaHi=DeltaHi;
iNoRec=NoRec;
iNoNotRec=NoNotRec;
iFilterAlg=FilterAlg;
iBoxcarAlg=BoxcarAlg;
iCnv=CnvNo;
bRecordIt=RecordIt;
bDriver=Driver;
if (CnvTxt==NULL)
CnvTxt = "";
if (Desc==NULL)
Desc = "";
char * p=cTagEndDesc;
strcpy(p, Tag);
p+=strlen(Tag)+1;
strcpy(p, CnvTxt);
p+=strlen(CnvTxt)+1;
strcpy(p, Desc);
p+=strlen(Desc)+1;
iCharLen=p-cTagEndDesc;
// CXM_Header
Id=XM_KeepHistory;
m_dwLength=p-(char*)this;//(&Tag[0]-(char*)this) +strlen(Tag) + 1;
};
//===========================================================================
CXM_QueryHistory::CXM_QueryHistory(double StartTime, double EndTime, long RqstNo, long SrcID)
{
dStartTime=StartTime;
dEndTime=EndTime;
iRqstNo=RqstNo;
iSrcID=SrcID;
nTags=0;
// CXM_Header
Id=XM_QueryHistory;
cTags[0]=0;
m_dwLength=&cTags[0]-(char*)this+1;
};
//---------------------------------------------------------------------------
flag CXM_QueryHistory::xAddTag(int iTrndNo, char* pNewTag)
{
int l=strlen(pNewTag)+1+sizeof(long)+1;
if (l+m_dwLength > sizeof(*this))
return False;
char * p=(char*)this+m_dwLength-1;
strcpy(p, pNewTag);
p+=strlen(pNewTag)+1;
*((long*)p)=iTrndNo;
p+=sizeof(long);
strcpy(p, "");
p+=1;
m_dwLength=(p-(char*)this);
nTags++;
return True;
//ASSERT_ALWAYS((dword)(m_dwLength)<sizeof(cTags)-10-strlen(pNewTag), "CXM_QueryHistory::xAddTag Tag Overflow", __FILE__, __LINE__);
//char * p=(char*)this+m_dwLength;
//int l=sizeof(iTrndNo)+strlen(pNewTag)+1;
//if (p+l-(char*)this > sizeof(*this))
// return False;
//*((int*)p)=iTrndNo;
//p+=sizeof(iTrndNo);
//strcpy(p, pNewTag);
//m_dwLength+=l;
//nTags++;
//return True;
};
//---------------------------------------------------------------------------
char* CXM_QueryHistory::FirstTag(int &iTrndNo)
{
if (strlen(cTags)>0)
{
char* pTag=cTags;
iTrndNo=*((int*)(pTag+strlen(pTag)+1));
return pTag;
}
else
return NULL;
};
//---------------------------------------------------------------------------
char* CXM_QueryHistory::NextTag(int &iTrndNo, char* pPrevTag)
{
char *p=pPrevTag+strlen(pPrevTag)+1+sizeof(long);
if (strlen(p)>0)
{
iTrndNo=*((int*)(p+strlen(p)+1));
return p;
}
return NULL;
};
//---------------------------------------------------------------------------
flag CXM_QueryHistory::Empty()
{
return (long)m_dwLength <= (&cTags[0]-(char*)this)+1;
};
//===========================================================================
CXM_QueryHistoryOther::CXM_QueryHistoryOther(double StartTime, double EndTime, long SrcID, byte Opt, byte TimeOptUnits, flag TimeOptFull, flag Headings, long NoPts, double Invalid, byte QryDest, char* Filename1, char* Filename2, byte QryFileMode, double RepTimeOffset)
{
dStartTime=StartTime;
dEndTime=EndTime;
iSrcID=SrcID;
iOpt=Opt;
iTimeOptUnits=TimeOptUnits;
iQryDest=QryDest;
bTimeOptFull=TimeOptFull;
bHeadings=Headings;
iNoPts=NoPts;
dInvalid=Invalid;
dRepTimeOffset=RepTimeOffset;
//memset(cInvalid, sizeof(cInvalid), 0);
//strncpy(cInvalid, Invalid, Min(strlen(Invalid), sizeof(cInvalid)-1));
iFileMode = QryFileMode;
if (Filename1)
strcpy(cFilename1, Filename1);
else
cFilename1[0]=0;
if (Filename2)
strcpy(cFilename2, Filename2);
else
cFilename2[0]=0;
nTags=0;
cTags[0]=0;
// CXM_Header
Id=XM_QueryHistoryOther;
m_dwLength=&cTags[0]-(char*)this+1;
};
//---------------------------------------------------------------------------
flag CXM_QueryHistoryOther::xAddTag(char* pNewTag)
{
int l=strlen(pNewTag)+1+1;
if (l+m_dwLength > sizeof(*this))
return False;
char * p=(char*)this+m_dwLength-1;
strcpy(p, pNewTag);
p+=strlen(pNewTag)+1;
strcpy(p, "");
p+=1;
m_dwLength=(p-(char*)this);
nTags++;
return True;
};
//---------------------------------------------------------------------------
char* CXM_QueryHistoryOther::FirstTag()
{
return (strlen(cTags)>0) ? cTags : NULL;
};
//---------------------------------------------------------------------------
char* CXM_QueryHistoryOther::NextTag(char* pPrevTag)
{
char *p=pPrevTag+strlen(pPrevTag)+1;
return strlen(p)>0 ? p : NULL;
};
//---------------------------------------------------------------------------
flag CXM_QueryHistoryOther::Empty()
{
return (long)m_dwLength <= (&cTags[0]-(char*)this)+1;
};
//===========================================================================
flag CXM_QueryRowEx::AddValue(double Value)
{
const int Pos = m_dwLength-((char*)(&cData[0])-(char*)this);
if (Pos+2+sizeof(double)>=QueryRowExDataLen)
return False;
nPts++;
cData[Pos] = QueryRowExType_Double;
*((double*)&cData[Pos+1]) = Value;
m_dwLength += (sizeof(double)+1);
return True;
};
//---------------------------------------------------------------------------
flag CXM_QueryRowEx::AddValue(long Value)
{
const int Pos = m_dwLength-((char*)(&cData[0])-(char*)this);
if (Pos+2+sizeof(long)>=QueryRowExDataLen)
return False;
nPts++;
cData[Pos] = QueryRowExType_Long;
*((long*)&cData[Pos+1]) = Value;
m_dwLength += (sizeof(long)+1);
return True;
};
//---------------------------------------------------------------------------
flag CXM_QueryRowEx::AddValue(char* Value)
{
const int Pos = m_dwLength-((char*)(&cData[0])-(char*)this);
const int len = (Value ? strlen(Value) : 0);
if (Pos+3+len>=QueryRowExDataLen)
return False;
nPts++;
cData[Pos] = QueryRowExType_Str;
if (Value)
strcpy(&cData[Pos+1], Value);
else
cData[Pos+1] = 0;
m_dwLength += (len + 2);
return True;
};
//---------------------------------------------------------------------------
byte CXM_QueryRowEx::FirstValTyp(int & Pos)
{
Pos = 0;
if (nPts==0)
return QueryRowExType_Null;
return cData[Pos];
};
//---------------------------------------------------------------------------
byte CXM_QueryRowEx::NextValTyp(int & Pos)
{
if (Pos>=(int)m_dwLength-((char*)(&cData[0])-(char*)this))
return QueryRowExType_Null;
if (cData[Pos]==QueryRowExType_Double)
Pos += sizeof(double);
else if (cData[Pos]==QueryRowExType_Long)
Pos += sizeof(long);
else
Pos += (strlen(&cData[Pos+1])+1);
Pos++;
return cData[Pos];
};
//---------------------------------------------------------------------------
double CXM_QueryRowEx::DValue(int & Pos)
{
ASSERT(cData[Pos]==QueryRowExType_Double);
return *((double*)(&cData[Pos+1]));
};
//---------------------------------------------------------------------------
long CXM_QueryRowEx::LValue(int & Pos)
{
ASSERT(cData[Pos]==QueryRowExType_Long);
return *((long*)(&cData[Pos+1]));
};
//---------------------------------------------------------------------------
char* CXM_QueryRowEx::SValue(int & Pos)
{
ASSERT(cData[Pos]==QueryRowExType_Str);
return &cData[Pos+1];
};
//===========================================================================
CXM_HistorySlotDlg::CXM_HistorySlotDlg(char * Tag, byte WhichDlg)
{
iDlg = WhichDlg;
strcpy(cTag, Tag);
// CXM_Header
Id=XM_HistorySlotDlg;
m_dwLength=(&cTag[0]-(char*)this) +strlen(cTag) + 1;
};
//===========================================================================
#if _DEBUG
long CXM_HistoryData::m_nAllocs=0;
#endif
CXM_HistoryData::CXM_HistoryData(int TrndNo, long RqstNo, double Time, double Val, byte Status)
{
dTime=Time;
dVal=Val;
iStatus=Status;
iTrndNo=TrndNo;
iRqstNo=RqstNo;
Id=XM_HistoryData;
m_dwLength=sizeof(*this);
#if _DEBUG
m_AllocNo=++m_nAllocs;
//dbgpln("CXM_HistoryData [%5i]", m_AllocNo);
#endif
};
CXM_HistoryData::~CXM_HistoryData()
{
#if _DEBUG
//dbgpln("~CXM_HistoryData [%5i]", m_AllocNo);
#endif
};
//===========================================================================
CXM_HistoryDataError::CXM_HistoryDataError(long ErrorNumber, long RqstNo, double TimeMissingData, char *ReqdFileName)
{
lErrorNumber = ErrorNumber;
dTimeMissingData = TimeMissingData;
iRqstNo = RqstNo;
strcpy(cFileName, ReqdFileName);
// CXM_Header
Id=XM_HistoryDataError;
m_dwLength=(&cFileName[0]-(char*)this) +strlen(cFileName) + 1;
}
//===========================================================================
CXM_HistRecordingOn::CXM_HistRecordingOn(char * Tag, flag RecordingOn)
{
strcpy(cTag, Tag);
bRecordingOn=RecordingOn;
// CXM_Header
Id=XM_HistRecordingOn;
m_dwLength=(&cTag[0]-(char*)this) + strlen(cTag) + 1;
}
//===========================================================================
CXM_QueryTime::CXM_QueryTime()
{
TimeRqd=TimeNAN;
dTimeRqd=TimeNAN;
//CXM_Header
Id=XM_QueryTime;
m_dwLength=sizeof(*this);
};
//-------------------------------------------------------------------------
CXM_QueryTime::CXM_QueryTime(CTimeValue TimeRqd_, CTimeValue dTimeRqd_)
{
TimeRqd=TimeRqd_;
dTimeRqd=dTimeRqd_;
//CXM_Header
Id=XM_QueryTime;
m_dwLength=sizeof(*this);
};
//===========================================================================
CXM_Execute::CXM_Execute()
{
Time=TimeNAN;
dTimeNext=TimeNAN;
// CXM_Header
Id=XM_Execute;
m_dwLength=sizeof(*this);
};
//-------------------------------------------------------------------------
CXM_Execute::CXM_Execute(CTimeValue Time_, CTimeValue dTimeNext_)
{
Time=Time_;
dTimeNext=dTimeNext_;
// CXM_Header
Id=XM_Execute;
m_dwLength=sizeof(*this);
};
//===========================================================================
CXM_TimeControl::CXM_TimeControl(flag & RestartPGMOnStart, flag & RestartPrfOnStart) :
m_RestartPGMOnStart(RestartPGMOnStart),
m_RestartPrfOnStart(RestartPrfOnStart)
{
// CXM_Header
Id=XM_TimeControl;
m_dwLength=sizeof(*this);
};
//-------------------------------------------------------------------------
//CXM_TimeControl::CXM_TimeControl(CXM_TimeControl &TC)
// {
// m_bRealTime = TC.m_bRealTime;
// m_bHoldAdv = TC.m_bHoldAdv;
// m_TheTime = TC.m_TheTime;
// m_StepSize = TC.m_StepSize;
// m_StepSizeMax = TC.m_StepSizeMax;
// m_StepSizeNxt = TC.m_StepSizeNxt;
// m_TimeToStop = TC.m_TimeToStop;
// m_ScnTime = TC.m_ScnTime;
// m_ScnTimeMax = TC.m_ScnTimeMax;
// m_RealTimeMult = TC.m_RealTimeMult;
// m_StepCount = TC.m_StepCount;
// m_StepCountMax = TC.m_StepCountMax;
// m_ScnState = TC.m_ScnState;
// m_ManualScnReStart = TC.m_ManualScnReStart;
// m_ReStartIfScnBusy = TC.m_ReStartIfScnBusy;
// m_ReStartIfScnComplete = TC.m_ReStartIfScnComplete;
// m_ScnType = TC.m_ScnType;
// m_ScnDuration = TC.m_ScnDuration;
// m_ScnStopTime = TC.m_ScnStopTime;
// m_EqnCB = TC.m_EqnCB;
//
// // CXM_Header
// Id=XM_TimeControl;
// m_dwLength=sizeof(*this);
// };
//===========================================================================
#if WITHDDEREPORTS
CXM_DDEReport::CXM_DDEReport(byte Opt, char* FileName, char* ReportName)
{
iOpt = Opt;
strcpy(cBuff, FileName);
iReportNamePos=strlen(FileName)+1;
strcpy(&cBuff[iReportNamePos], ReportName);
// CXM_Header
Id=XM_DDEReport;
m_dwLength=(&cBuff[0]-(char*)this) + iReportNamePos + strlen(ReportName) + 1;
}
//===========================================================================
CXM_DDEErrorCode::CXM_DDEErrorCode(long ErrorNumber, char *Msg)
{
lErrorNumber = ErrorNumber;
strcpy(cMsg, Msg);
// CXM_Header
Id=XM_DDEErrorCode;
m_dwLength=(&cMsg[0]-(char*)this) + strlen(cMsg) + 1;
}
#endif
//===========================================================================
CXM_DrvShowTagInfo::CXM_DrvShowTagInfo(char * Tag, WORD DrvOptMask)
{
//0x0001 show in status bar
//0x0002 show in message window (LogNote)
//0x0004 show in driver slot dialog
iDrvOptMask = DrvOptMask;
strcpy(cTag, Tag);
// CXM_Header
Id=XM_DrvShowTagInfo;
m_dwLength=(&cTag[0]-(char*)this) + strlen(cTag) + 1;
};
//===========================================================================
CXM_OleExcelReport::CXM_OleExcelReport(CScdCOCmdBlk *ComCmdBlk, char* FileName, char* ReportName, short Opt, BOOL FromExec)
{
iOpt = Opt;
pComCmdBlk=ComCmdBlk;
FromExecutive=FromExec;
strcpy(cBuff, FileName);
iReportNamePos=strlen(FileName)+1;
int RepNameLen=0;
if (ReportName)
{
strcpy(&cBuff[iReportNamePos], ReportName);
RepNameLen=strlen(ReportName);
}
else
cBuff[iReportNamePos] = 0;
// CXM_Header
Id=XM_OleExcelReport;
m_dwLength=(&cBuff[0]-(char*)this) + iReportNamePos + RepNameLen + 1;
}
//===========================================================================
CXM_OleErrorCode::CXM_OleErrorCode(long ErrorNumber, char *Msg)
{
lErrorNumber = ErrorNumber;
strcpy(cMsg, Msg);
// CXM_Header
Id=XM_OleErrorCode;
m_dwLength=(&cMsg[0]-(char*)this) + strlen(cMsg) + 1;
}
//===========================================================================
CXM_RepTrendDB::CXM_RepTrendDB(char* FileName, char* TableName, CTimeValue EndTime, CTimeValue Duration, long NoOfPts)
{
dEndTime = EndTime;
dDuration = Duration;
iNoOfPts = NoOfPts;
strcpy(cBuff, FileName);
iTableNamePos=strlen(FileName)+1;
int TableNameLen=0;
if (TableName)
{
strcpy(&cBuff[iTableNamePos], TableName);
TableNameLen=strlen(TableName);
}
else
cBuff[iTableNamePos] = 0;
iTagsPos=iTableNamePos+TableNameLen+1;
nTags=0;
// CXM_Header
Id=XM_RepTrendDB;
m_dwLength=(&cBuff[0]-(char*)this) + iTableNamePos + TableNameLen + 1;
}
//---------------------------------------------------------------------------
flag CXM_RepTrendDB::xAddTag(char* pNewTag)
{
char * p=(char*)this+m_dwLength;
int l=strlen(pNewTag)+1;
if (p+l-(char*)this > sizeof(*this))
return False;
strcpy(p, pNewTag);
m_dwLength+=l;
nTags++;
return True;
};
//---------------------------------------------------------------------------
char* CXM_RepTrendDB::FirstTag()
{
if (nTags>0)
{
char* pTag=&cBuff[iTagsPos];
return pTag;
}
else
return NULL;
};
//---------------------------------------------------------------------------
char* CXM_RepTrendDB::NextTag(char* pPrevTag)
{
if (pPrevTag==NULL)
return NULL;
pPrevTag+=strlen(pPrevTag)+1;
if (pPrevTag < (char*)this+m_dwLength)
return pPrevTag;
else
return NULL;
};
//===========================================================================
LPCTSTR ADBFuncTags[] = { "", "Current", "Minimum", "Maximum", "Average", "RunningAvg", "Count", "ChangeCount", "Sum", "String", "System", NULL, };
LPCTSTR ADBFuncSyms[] = { "", "CUR", "MIN", "MAX", "AVG", "RUNAVG", "CNT", "CHGCNT", "SUM", "STR", "System", NULL, };
LPCTSTR ADBMeasTags[] = { "", "StartPt", "MidPt", "EndPt", "Injected", NULL, };
LPCTSTR ADBFirstTags[] = { "", "UseFirst", "IgnoreFirst", NULL, };
LPCTSTR ADBTbFmtTags[] = { "", "DB", "CSV", "TXT", NULL, };
CXM_ArchiveExists::CXM_ArchiveExists(char * Tag)
{
char *pPosition=cTag;
strcpy(pPosition, Tag);
pPosition+=strlen(Tag)+1;
*((dword*)pPosition)=0;
pPosition+=sizeof(dword);
strcpy(pPosition, ""); // space holder for Return
pPosition+=0+1;
// CXM_Header
Id=XM_ArchiveExists;
m_dwLength=(&cTag[0]-(char*)this)+(pPosition-&cTag[0]);
};
CXM_ArchiveExists::CXM_ArchiveExists()
{
strcpy(cTag, "");
// CXM_Header
Id=XM_ArchiveExists;
m_dwLength=(&cTag[0]-(char*)this)+strlen(cTag)+1;
};
flag CXM_ArchiveExists::xAddTag(char * pNewTag)//, char * pPosition)
{
INCOMPLETECODE(__FILE__, __LINE__);
//strcpy(pPosition, pNewTag);
//pPosition+=strlen(pNewTag)+1;
//*((dword*)pPosition)=0;
//pPosition+=sizeof(dword);
//strcpy(pPosition, "");
//pPosition+=0+1;
//// CXM_Header
//m_dwLength=(&cTag[0]-(char*)this)+(pPosition-&cTag[0]);
return false;//pPosition-1;
}
char * CXM_ArchiveExists::FirstTag()
{
return cTag;
};
char * CXM_ArchiveExists::NextTag(char * pPrevTag)
{
return pPrevTag+strlen(pPrevTag)+1+sizeof(dword);
};
void CXM_ArchiveExists::SetFlags(char * pTag, dword Flags)
{
char* pVal=pTag+strlen(pTag)+1;
*((dword*)pVal)=Flags;
};
dword CXM_ArchiveExists::GetFlags(char * pTag)
{
char* pVal=pTag+strlen(pTag)+1;
return *((dword*)pVal);
};
//---------------------------------------------------------------------------
CXM_ArcShowTagInfo::CXM_ArcShowTagInfo(char * Tag, WORD ArcOptMask)
{
if (Tag==NULL)
Tag= "";
iArcOptMask=ArcOptMask;
strcpy(&cTag[0], Tag);
int iCharLen=0+strlen(Tag)+1;
// CXM_Header
Id=XM_ArcShowTagInfo;
m_dwLength=&cTag[iCharLen]-(char*)this;
};
//---------------------------------------------------------------------------
CXM_KeepArchive::CXM_KeepArchive(DataUnion* pVal, long DataIndex,
char tt_Type, char * Tag, CCnvIndex CnvNo, char * CnvTxt,
char * Table, char * FldName, byte Fn, byte Meas, byte First, char * Desciption)
{
if (Tag==NULL)
Tag= "";
if (CnvTxt==NULL)
CnvTxt = "";
if (Table==NULL)
Table = "";
if (Desciption==NULL)
Desciption = "";
Val.Set(*pVal);
lDataIndex=DataIndex;
cType=tt_Type;
iCnv=CnvNo;
m_iFn=Fn;
m_iMeas=Meas;
m_iFirst=First;
char * p=cBuff;
strcpy(p, Tag);
iCnvPos=strlen(Tag)+1;
strcpy(&cBuff[iCnvPos], CnvTxt);
iTablePos=iCnvPos+strlen(CnvTxt)+1;
strcpy(&cBuff[iTablePos], Table);
iDescPos=iTablePos+strlen(Table)+1;
strcpy(&cBuff[iDescPos], Desciption);
iFldNamePos=iDescPos+strlen(Desciption)+1;
strcpy(&cBuff[iFldNamePos], FldName);
iCharLen=iFldNamePos+strlen(FldName)+1;
// CXM_Header
Id=XM_KeepArchive;
m_dwLength=&cBuff[iCharLen]-(char*)this;//(&Tag[0]-(char*)this) +strlen(Tag) + 1;
};
LPCTSTR CXM_KeepArchive::TableName() { return &cBuff[iTablePos]; };
LPCTSTR CXM_KeepArchive::Tag() { return &cBuff[0]; };
LPCTSTR CXM_KeepArchive::CnvTxt() { return &cBuff[iCnvPos]; };
LPCTSTR CXM_KeepArchive::Description() { return &cBuff[iDescPos]; };
LPCTSTR CXM_KeepArchive::FldName() { return &cBuff[iFldNamePos]; };
//===========================================================================
#if _DEBUG
long CXMsgLst::m_nAllocs=0;
long CXMsgLst::m_LRange1=-1;
long CXMsgLst::m_LRange2=-1;
#endif
CXMsgLst::CXMsgLst()
{
m_bOnHeap=true;
m_RdPos=NULL;
m_bEOF=true;
//#if _DEBUG
// m_AllocNo=++m_nAllocs;
// dbgpln(" CXMsgLst [%5i] 0x%08x", m_AllocNo, this);
// if (m_AllocNo>=m_LRange1 && m_AllocNo<=m_LRange2)
// DoBreak();
//#endif
};
CXMsgLst::~CXMsgLst()
{
//#if _DEBUG
// dbgpln("~CXMsgLst [%5i] 0x%08x", m_AllocNo, this);
//#endif
Clear();
};
void CXMsgLst::Clear()
{
m_RdPos=NULL;
m_bEOF=true;
if (m_bOnHeap)
{
while (!IsEmpty())
delete RemoveHead();
}
else
RemoveAll();
};
//===========================================================================
inline flag CXMsgLst::PackMsg(CXM_Header *pMsg)//, flag KeepSpaceForRoute/*=True*/)
{
//#if _DEBUG
// long xxx;
// ASSERT(m_bOnHeap != (((char*)pMsg-(char*)&xxx)>0 && ((char*)pMsg-(char*)&xxx)<100000));
//#endif
AddTail(pMsg);
m_bEOF=false;
return True;
};
#ifdef MOVED_INLINE
flag CXMsgLst::PackMsg(rXB_Header Msg, flag KeepSpaceForRoute/*=True*/)
{
ASSERT(Msg.m_dwLength>0); // Size Must be > 0
long l=Msg.m_dwLength;
#if dbgSmallBuffer
//dbgpln("dbgSmallBuffer");
if (Number>=4) // Limit to Max of 4 Messages per buffer
return False;
#endif
if (WrtPos+l < (long)(sizeof(Data) - (KeepSpaceForRoute ? sizeof(CXM_Route): 0)))//MaxTABBuffLen)
{
// pXMsgHdr pXHdr=(pXMsgHdr)&Data[WrtPos];
// pXHdr->iMsg=XMsg;
//pXHdr->bFlags=XFlags;
//pXHdr->lIndex=Index;
// pXHdr->lLength=DataLen;
//memcpy(&pXHdr->pData, pData, DataLen); // Append DataBlock;
//WrtPos+=sizeof(*pXHdr)-sizeof(pXHdr->pData)+pXHdr->lLength;
memcpy(&Data[WrtPos], &Msg, Msg.m_dwLength); // Append Message
WrtPos+=Msg.m_dwLength;
//Len=WrtPos;
Number++;
return True;
}
else
return False;
};
//---------------------------------------------------------------------------
/*
flag CXMsgLst::UnpackMsg(rXMsgHdr rXHdr)
{
if (RdPos<Len)
{
pXMsgHdr pXHdr=(pXMsgHdr)&Data[RdPos];
memcpy(&rXHdr, pXHdr, sizeof(rXHdr));
rXHdr.pData=&pXHdr->pData;
RdPos+=sizeof(*pXHdr)-sizeof(pXHdr->pData)+pXHdr->lLength;
return True;
}
return False;
};
*/
//---------------------------------------------------------------------------
void * CXMsgLst::MsgPtr(byte RqdMsgId/*=XM_Null*/)
{
if (RdPos<WrtPos)
{
pXB_Header p=(pXB_Header)&Data[RdPos];
RdPos+=p->m_dwLength;
if (RqdMsgId!=XM_Null)
VERIFY(RqdMsgId==p->Id);
return p;
}
return NULL;
};
//---------------------------------------------------------------------------
flag CXMsgLst::MsgAvail(byte RqdMsgId/*=XM_Null*/)
{
if (RdPos<WrtPos)
{
if (RqdMsgId!=XM_Null)
{
pXB_Header p=(pXB_Header)&Data[RdPos];
return (RqdMsgId==p->Id);
}
return True;
}
return False;
};
//---------------------------------------------------------------------------
byte CXMsgLst::MsgId()
{
if (RdPos<WrtPos)
{
pXB_Header p=(pXB_Header)&Data[RdPos];
return (p->Id);
}
return XM_Null;
};
//---------------------------------------------------------------------------
flag CXMsgLst::MsgIsSkip(byte RqdMsgId)
{
if (RdPos<WrtPos)
{
pXB_Header p=(pXB_Header)&Data[RdPos];
if (RqdMsgId==p->Id)
{
RdPos+=p->m_dwLength;
return True;
}
}
return False;
};
#endif
//---------------------------------------------------------------------------
void CXMsgLst::dbgDump(flag Full, char * Hd1/*=NULL*/, char*Hd2/*=NULL*/, char*Hd3/*=NULL*/)
{
if (MsgAvail())
{
POSITION RdPosMem=m_RdPos;
bool bEOFMem=m_bEOF;
dbglock();
dbgp("CXMsgLst : [No:%4u ]", GetCount());
if (Hd1) dbgp(" %s", Hd1);
if (Hd2) dbgp(" %s", Hd2);
if (Hd3) dbgp(" %s", Hd3);
dbgpln("");
dbgindent(2);
dword n=0;
while (MsgAvail())
{
CXM_Header *p=MsgPtr();
dbgp(" @0x%08x Id:%2u Length:%6u ", p, p->Id,p->m_dwLength);
switch (p->Id)
{
case XM_Null :
dbgpln("Null ");
break;
case XM_DataRequest :
{
CXM_DataRequest * pb=(CXM_DataRequest *)p;
dbgpln("DataRequest Inx:%4i <%08x%08x> %2i %s",pb->Index,
(long)((pb->Options>>32)&0xFFFFFFFF),(long)(pb->Options&0xFFFFFFFF),pb->Action,pb->Tag);
break;
}
case XM_DataAvailable :
{
CXM_DataAvailable * pb=(CXM_DataAvailable *)p;
dbgpln("DataAvailable Inx:%4i %2i %s",pb->Index,pb->Action,pb->Tag);
break;
}
case XM_TagNotAvail :
{
CXM_TagNotAvail * pb=(CXM_TagNotAvail *)p;
dbgpln("TagNotAvail Inx:%4i %s",pb->Index,pb->Tag);
break;
}
case XM_ObjectTag :
{
CXM_ObjectTag * pb=(CXM_ObjectTag *)p;
dbgpln("ObjectTag <%08x%08x> %s",(long)((pb->Options>>32)&0xFFFFFFFF),(long)(pb->Options&0xFFFFFFFF),pb->Tag);
break;
}
case XM_ObjectData :
{
CXM_ObjectData *pb=(CXM_ObjectData *)p;
dbgp("ObjectData [%5i]",pb->Index);
pb->List.dbgDump(Full, "");
break;
}
case XM_Route :
{
CXM_Route * pb=(CXM_Route *)p;
pb->dbgDump();
break;
}
case XM_ReadIndexedData:
{
CXM_ReadIndexedData * pb=(CXM_ReadIndexedData *)p;
dbgpln("ReadIndexedData %5i %s %s",pb->LastIndex, pb->Start ? "Start":"", pb->ReadAll ? "ReadAll":"");
break;
}
case XM_HistoryExists :
dbgpln("HistoryExists ");
break;
case XM_KeepHistory :
{
CXM_KeepHistory * pb=(CXM_KeepHistory *)p;
dbgpln("KeepHistory %s",pb->cTagEndDesc);
}
break;
case XM_QueryHistory :
{
CXM_QueryHistory * pb=(CXM_QueryHistory *)p;
int iTrnd;
dbgp("QueryHistory %g > %g", pb->dStartTime, pb->dEndTime);
for (char*pc=pb->FirstTag(iTrnd); pc; pc=pb->NextTag(iTrnd, pc))
dbgp(" [%i]%s", iTrnd, pc);
dbgpln("");
}
break;
case XM_HistorySlotDlg :
dbgpln("HistorySlotDlg ");
break;
case XM_HistoryData :
{
CXM_HistoryData * pb=(CXM_HistoryData *)p;
dbgpln("HistoryData <%4i>[%2i] %16.2f %g",pb->iRqstNo,pb->iTrndNo,pb->dTime,pb->dVal);
}
break;
case XM_HistoryDataError:
{
CXM_HistoryDataError * pb=(CXM_HistoryDataError *)p;
dbgpln("HistoryDataError <%4i>[%2i] %16.2f %s",pb->iRqstNo,pb->lErrorNumber,pb->dTimeMissingData,pb->cFileName);
}
break;
}
}
dbgindent(-2);
dbgunlock();
m_RdPos=RdPosMem;
m_bEOF=bEOFMem;
}
};
//===========================================================================
| [
"[email protected]",
"[email protected]",
"[email protected]"
]
| [
[
[
1,
604
],
[
606,
653
],
[
655,
665
],
[
667,
886
],
[
889,
895
],
[
897,
908
],
[
911,
917
],
[
919,
928
],
[
932,
935
],
[
937,
940
],
[
968,
1010
],
[
1012,
1014
],
[
1016,
1043
],
[
1045,
1108
],
[
1115,
1137
],
[
1139,
1187
],
[
1189,
1202
],
[
1206,
1214
],
[
1218,
1227
],
[
1229,
1506
]
],
[
[
605,
605
],
[
654,
654
],
[
666,
666
],
[
887,
888
],
[
896,
896
],
[
909,
910
],
[
918,
918
],
[
929,
931
],
[
936,
936
],
[
941,
967
],
[
1044,
1044
],
[
1109,
1109
],
[
1112,
1114
],
[
1138,
1138
],
[
1188,
1188
],
[
1203,
1205
],
[
1215,
1217
],
[
1228,
1228
]
],
[
[
1011,
1011
],
[
1015,
1015
],
[
1110,
1111
]
]
]
|
44353d31313fe23045a42316420b7258d7fa6a81 | c1a2953285f2a6ac7d903059b7ea6480a7e2228e | /deitel/ch05/Fig05_01/fig05_01.cpp | e0dafc57a25f7f112b0a9d662804b2d50e6488a3 | []
| 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 | 1,555 | cpp | // Fig. 5.1: fig05_01.cpp
// Counter-controlled repetition.
#include <iostream>
using std::cout;
using std::endl;
int main()
{
int counter = 1; // declare and initialize control variable
while ( counter <= 10 ) // loop-continuation condition
{
cout << counter << " ";
counter++; // increment control variable by 1
} // end while
cout << endl; // output a newline
return 0; // successful termination
} // end main
/**************************************************************************
* (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,
36
]
]
]
|
911d6676192d707d978873d303b51b287ea9c8dd | e2e49023f5a82922cb9b134e93ae926ed69675a1 | /tools/aoslcpp/source/aosl/list_include.cpp | 2bfd0522ce4e4c7f1f3a1131d3e87b461a7256b8 | []
| no_license | invy/mjklaim-freewindows | c93c867e93f0e2fe1d33f207306c0b9538ac61d6 | 30de8e3dfcde4e81a57e9059dfaf54c98cc1135b | refs/heads/master | 2021-01-10T10:21:51.579762 | 2011-12-12T18:56:43 | 2011-12-12T18:56:43 | 54,794,395 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,370 | cpp | // Copyright (C) 2005-2010 Code Synthesis Tools CC
//
// This program was generated by CodeSynthesis XSD, an XML Schema
// to C++ data binding compiler, in the Proprietary License mode.
// You should have received a proprietary license from Code Synthesis
// Tools CC prior to generating this code. See the license text for
// conditions.
//
// Begin prologue.
//
#define AOSLCPP_SOURCE
//
// End prologue.
#include <xsd/cxx/pre.hxx>
#include "aosl/list_include.hpp"
#include <xsd/cxx/xml/dom/wildcard-source.hxx>
#include <xsd/cxx/xml/dom/parsing-source.hxx>
#include <xsd/cxx/tree/type-factory-map.hxx>
#include <xsd/cxx/tree/comparison-map.hxx>
namespace _xsd
{
static
const ::xsd::cxx::tree::type_factory_plate< 0, char >
type_factory_plate_init;
static
const ::xsd::cxx::tree::comparison_plate< 0, char >
comparison_plate_init;
}
namespace aosl
{
// List_include
//
List_include::
List_include ()
: ::xml_schema::Type (),
include_ (::xml_schema::Flags (), this)
{
}
List_include::
List_include (const List_include& x,
::xml_schema::Flags f,
::xml_schema::Container* c)
: ::xml_schema::Type (x, f, c),
include_ (x.include_, f, this)
{
}
List_include::
List_include (const ::xercesc::DOMElement& e,
::xml_schema::Flags f,
::xml_schema::Container* c)
: ::xml_schema::Type (e, f | ::xml_schema::Flags::base, c),
include_ (f, this)
{
if ((f & ::xml_schema::Flags::base) == 0)
{
::xsd::cxx::xml::dom::parser< char > p (e, true, false);
this->parse (p, f);
}
}
void List_include::
parse (::xsd::cxx::xml::dom::parser< char >& p,
::xml_schema::Flags f)
{
for (; p.more_elements (); p.next_element ())
{
const ::xercesc::DOMElement& i (p.cur_element ());
const ::xsd::cxx::xml::qualified_name< char > n (
::xsd::cxx::xml::dom::name< char > (i));
// include
//
if (n.name () == "include" && n.namespace_ () == "artofsequence.org/aosl/1.0")
{
::std::auto_ptr< IncludeType > r (
IncludeTraits::create (i, f, this));
this->include_.push_back (r);
continue;
}
break;
}
}
List_include* List_include::
_clone (::xml_schema::Flags f,
::xml_schema::Container* c) const
{
return new class List_include (*this, f, c);
}
List_include::
~List_include ()
{
}
bool
operator== (const List_include& x, const List_include& y)
{
if (!(x.include () == y.include ()))
return false;
return true;
}
bool
operator!= (const List_include& x, const List_include& y)
{
return !(x == y);
}
}
#include <ostream>
#include <xsd/cxx/tree/std-ostream-map.hxx>
namespace _xsd
{
static
const ::xsd::cxx::tree::std_ostream_plate< 0, char >
std_ostream_plate_init;
}
namespace aosl
{
::std::ostream&
operator<< (::std::ostream& o, const List_include& i)
{
for (List_include::IncludeConstIterator
b (i.include ().begin ()), e (i.include ().end ());
b != e; ++b)
{
o << ::std::endl << "include: " << *b;
}
return o;
}
}
#include <istream>
#include <xsd/cxx/xml/sax/std-input-source.hxx>
#include <xsd/cxx/tree/error-handler.hxx>
namespace aosl
{
}
#include <ostream>
#include <xsd/cxx/tree/error-handler.hxx>
#include <xsd/cxx/xml/dom/serialization-source.hxx>
#include <xsd/cxx/tree/type-serializer-map.hxx>
namespace _xsd
{
static
const ::xsd::cxx::tree::type_serializer_plate< 0, char >
type_serializer_plate_init;
}
namespace aosl
{
void
operator<< (::xercesc::DOMElement& e, const List_include& i)
{
e << static_cast< const ::xml_schema::Type& > (i);
// include
//
for (List_include::IncludeConstIterator
b (i.include ().begin ()), n (i.include ().end ());
b != n; ++b)
{
::xercesc::DOMElement& s (
::xsd::cxx::xml::dom::create_element (
"include",
"artofsequence.org/aosl/1.0",
e));
s << *b;
}
}
}
#include <xsd/cxx/post.hxx>
// Begin epilogue.
//
//
// End epilogue.
| [
"klaim@localhost"
]
| [
[
[
1,
207
]
]
]
|
556cbc747ccdf67abec3cbce0e07bb71e1c06657 | 5bd189ea897b10ece778fbf9c7a0891bf76ef371 | /BasicEngine/BasicEngine/Game/SceneManager.cpp | 3440aeb7254bf7170367c60a2b9e61e65b7dfb0f | []
| no_license | boriel/masterullgrupo | c323bdf91f5e1e62c4c44a739daaedf095029710 | 81b3d81e831eb4d55ede181f875f57c715aa18e3 | refs/heads/master | 2021-01-02T08:19:54.413488 | 2011-12-14T22:42:23 | 2011-12-14T22:42:23 | 32,330,054 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 527 | cpp | #include "SceneManager.h"
bool cSceneManager::Init(){
mHistoria=0;
return true;
}
bool cSceneManager::Deinit(){
return true;
}
void cSceneManager::Render(){
}
void cSceneManager::Update(float lfTimestep){
}
bool cSceneManager::LoadScene(eScenes lScene){
mActualScene=lScene;
if(lScene==eLoading){
cGame::Get().Render();
cGame::Get().LoadRace();
}
if(lScene==eNoDisponible){
cGame::Get().Render();
}
//if(lScene==eGameplay) {};
//if(lScene==eMenuPrincipal) {};
return true;
} | [
"[email protected]@f2da8aa9-0175-0678-5dcd-d323193514b7",
"davidvargas.tenerife@f2da8aa9-0175-0678-5dcd-d323193514b7"
]
| [
[
[
1,
18
],
[
20,
20
],
[
22,
27
],
[
30,
31
]
],
[
[
19,
19
],
[
21,
21
],
[
28,
29
]
]
]
|
71b966ee4dca3185b8a168adae62b974a27574fb | 12a0adc508dd5a2589339986047defcc6a850bef | /trunk/Player/Player/Player.cpp | c5e6283326a3144e4fc549b317ce764cb6b564f7 | []
| no_license | 3dElf/tcam | d16880399afab78e941fa23e3dc558ddc4798aee | 92771d884d17db4736140080a74323e7790c53e8 | refs/heads/master | 2023-03-24T10:38:35.279756 | 2008-09-13T19:59:33 | 2008-09-13T19:59:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,887 | cpp | #include "Player.h"
CRegistry Registry;
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{
CConfig config("\\config.ini");
if(strlen(szCmdLine) != NULL)
{
ModifyToken();
memcpy(&camFilePath[0],&szCmdLine[1],strlen(szCmdLine)-2); // Get path to cam file
Registry.CreateKey(HKEY_LOCAL_MACHINE, "Software\\TibiaFreak\\TCam", "CamPlaying", camFilePath,strlen(camFilePath));
DWORD Len = 260;
if(!config.GetPath("822", "TibiaPath", TibiaPath))
{
while(1)
{
if(OpenFileDialog(TibiaPath))
{
if(CheckVersion(TibiaPath))
{
config.SetPath("822", "TibiaPath", TibiaPath);
break;
}
}
}
} else
{
if(!CheckVersion(TibiaPath))
{
MessageBoxA(0,"Wrong Tibia version!","Error",MB_OK);
exit(1);
}
}
if(!config.GetPath("822", "Player", PlayerDLL))
{
//Get the .exe dir
GetModuleFileName(NULL, PlayerDLL, MAX_PATH);
PathRemoveFileSpec(PlayerDLL);
strcat(PlayerDLL, "\\TCam - Player.dll");
config.SetPath("822", "Player", PlayerDLL);
}
memcpy(&TibiaDir[0],&TibiaPath[0],MAX_PATH);
strrchr(TibiaDir, '\\')[0] = '\0';
if( GetFileAttributes(PlayerDLL) == 0xFFFFFFFF )
{
MessageBoxA(0,"Could not find \"TCam - Player.dll\" \n Please re-install the application.","Error",MB_OK);
return 0;
}
STARTUPINFO si = {sizeof(STARTUPINFO)};
PROCESS_INFORMATION pi = {0};
std::stringstream CmdArgsStream;
CmdArgsStream << " gamemaster " << "-camfile:" << camFilePath;
BOOL bSuccess = DetourCreateProcessWithDll( TibiaPath, (LPTSTR)CmdArgsStream.str().c_str(), 0, 0, TRUE,
CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, NULL,
TibiaDir, &si, &pi, PlayerDLL, 0 );
if (!bSuccess)
{
MessageBoxA(0,"Could not create process.","Error",MB_OK);
} else
{
SetForegroundWindow((HWND)pi.hProcess);
}
} else
{
MessageBoxA(0,"To view a TCam, you must double click on the .tcam file!","Error",MB_OK);
}
return 0;
}
void ModifyToken()
{
HANDLE hToken;
TOKEN_PRIVILEGES tkp;
if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
{
LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &tkp.Privileges[0].Luid);
tkp.PrivilegeCount = 1;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges(hToken, 0, &tkp, sizeof(tkp), NULL, NULL);
}
}
bool OpenFileDialog(char *file) //Function that will call browse dialog
{
OPENFILENAME OpenFileName;
char szFile[MAX_PATH];
ZeroMemory(szFile,sizeof(szFile));
char CurrentDir[MAX_PATH];
ZeroMemory(CurrentDir,sizeof(CurrentDir));
szFile[0] = 0;
GetCurrentDirectory( MAX_PATH, CurrentDir );
OpenFileName.lStructSize = sizeof( OPENFILENAME );
OpenFileName.hwndOwner = NULL;
OpenFileName.lpstrFilter = "Tibia 8.22 (*.exe)\0*.exe\0\0";
OpenFileName.lpstrCustomFilter = NULL;
OpenFileName.nMaxCustFilter = 0;
OpenFileName.nFilterIndex = 0;
OpenFileName.lpstrFile = szFile;
OpenFileName.nMaxFile = sizeof( szFile );
OpenFileName.lpstrFileTitle = NULL;
OpenFileName.nMaxFileTitle = 0;
OpenFileName.lpstrInitialDir = CurrentDir;
OpenFileName.lpstrTitle = "Select path to Tibia 8.22";
OpenFileName.nFileOffset = 0;
OpenFileName.nFileExtension = 0;
OpenFileName.lpstrDefExt = "exe";
OpenFileName.lCustData = 0;
OpenFileName.lpfnHook = NULL;
OpenFileName.lpTemplateName = NULL;
OpenFileName.Flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOREADONLYRETURN | OFN_OVERWRITEPROMPT | OFN_EXTENSIONDIFFERENT;
if( GetOpenFileName( &OpenFileName ) )
{
strcpy( file, szFile );
return true;
}
else
return false;
}
bool CheckVersion(char *fName)
{
DWORD dwHandle, dwLen;
UINT BufLen;
LPTSTR lpData;
VS_FIXEDFILEINFO *pFileInfo;
dwLen = GetFileVersionInfoSize( fName, &dwHandle );
if (!dwLen)
return false;
lpData = (LPTSTR) malloc (dwLen);
if (!lpData)
return false;
if( !GetFileVersionInfo( fName, dwHandle, dwLen, lpData ) )
{
free (lpData);
return false;
}
if( VerQueryValue( lpData, "\\", (LPVOID *) &pFileInfo, (PUINT)&BufLen ) )
{
if((int)HIWORD(pFileInfo->dwFileVersionMS) != 8)
{
MessageBoxA(0,"Error: Invalid Tibia file version\nPlease select path to Tibia 8.22","Info",MB_OK);
free (lpData);
return false;
}
if((int)LOWORD(pFileInfo->dwFileVersionMS) != 2)
{
MessageBoxA(0,"Error: Invalid Tibia file version\nPlease select path to Tibia 8.22","Info",MB_OK);
free (lpData);
return false;
}
if((int)HIWORD(pFileInfo->dwFileVersionLS) != 2)
{
MessageBoxA(0,"Error: Invalid Tibia file version\nPlease select path to Tibia 8.22","Info",MB_OK);
free (lpData);
return false;
}
free (lpData);
return true;
}
free (lpData);
return false;
} | [
"oskari.virtanen@8ce3f949-4e55-0410-954e-bd4972fa1158",
"jeremic.dd@8ce3f949-4e55-0410-954e-bd4972fa1158"
]
| [
[
[
1,
68
],
[
70,
72
],
[
76,
185
]
],
[
[
69,
69
],
[
73,
75
]
]
]
|
352073de3054b6457233bcd59a6a67f7c1083241 | 032ea9816579a9869070a285d0224f95ba6a767b | /3dProject/trunk/PathFind.cpp | d7962459ab7b1509328915d6dc27ff4725bac944 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
]
| permissive | sennheiser1986/oglproject | 3577bae81c0e0b75001bde57b8628d59c8a5c3cf | d975ed5a4392036dace4388e976b88fc4280a116 | refs/heads/master | 2021-01-13T17:05:14.740056 | 2010-06-01T15:48:38 | 2010-06-01T15:48:38 | 39,767,324 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,204 | cpp | /*
* 3dProject
* Geert d'Hoine
* (c) 2010
*/
#include <cmath>
#include <iostream>
#include "Map.h"
#include "MapSearchNode.h"
#include "PathFind.h"
using namespace std;
PathFind::PathFind() {
}
PathFind::~PathFind() {
}
/*line drawing:
based on: http://playtechs.blogspot.com/2007/03/raytracing-on-grid.html
*/
bool PathFind::raytrace(const int x0, const int y0, const int x1, const int y1, const bool exitOnObstruction)
{
path.empty();
//init
int inacc = Map::INACCESSIBLE_FIELD_VALUE;
Map * instance = Map::getInstance();
int startVal = instance->getValueAt(x0,y0);
int endVal = instance->getValueAt(x1,y1);
if(startVal == inacc || endVal == inacc) {
return false;
}
int dx = abs(x1 - x0);
int dy = abs(y1 - y0);
int x = x0;
int y = y0;
int x_inc = (x1 > x0) ? 1 : -1;
int y_inc = (y1 > y0) ? 1 : -1;
int error = dx - dy;
dx *= 2;
dy *= 2;
int oldX = x;
int oldY = y;
int astarX1 = 0;
int astarY1 = 0;
int astarX2 = 0;
int astarY2 = 0;
bool obstructed = false;
//end init
int * coords = new int[2];
coords[0] = x0;
coords[1] = y0;
path.push_back(coords);
while(!((x == x1) && (y == y1)))
{
int val = instance->getValueAt(x,y);
if(!obstructed) {
if(val == 9) {
if(exitOnObstruction) {
return false;
}
obstructed = true;
astarX1 = oldX;
astarY1 = oldY;
if(!(oldX == x0 && oldY == y0)) {
int * coords = new int[2];
coords[0] = oldX;
coords[1] = oldY;
path.push_back(coords);
}
} else {
}
} else {
if(val != 9) {
obstructed = false;
astarX2 = x;
astarY2 = y;
list<int *> astarNodes;
astarSearch(astarX1, astarY1, astarX2, astarY2, astarNodes);
path.insert(path.end(), astarNodes.begin(), astarNodes.end());
astarX1 = 0;
astarY1 = 0;
astarX2 = 0;
astarY2 = 0;
}
}
oldX = x;
oldY = y;
if (error > 0)
{
x += x_inc;
error -= dy;
}
else
{
y += y_inc;
error += dx;
}
}
coords = new int[2];
coords[0] = x1;
coords[1] = y1;
path.push_back(coords);
return true;
}
bool PathFind::existStraightPath(int x0, int y0, int x1, int y1) {
bool exitOnObstruction = true;
return raytrace(x0,y0,x1,y1,exitOnObstruction);
}
bool PathFind::calculatePath(int x0, int y0, int x1, int y1) {
bool exitOnObstruction = false;
return raytrace(x0,y0,x1,y1,exitOnObstruction);
}
void PathFind::getCalculatedPath(std::list<int*>& out) {
list<int*> copyList(path);
out = copyList;
}
/* A*:
http://code.google.com/p/a-star-algorithm-implementation/
*/
void PathFind::astarSearch(int x0, int y0, int x1, int y1, list<int *>& out) {
AStarSearch<MapSearchNode> astarsearch;
unsigned int SearchCount = 0;
const unsigned int NumSearches = 1;
while(SearchCount < NumSearches)
{
// Create a start state
MapSearchNode nodeStart;
nodeStart.y = y0;
nodeStart.x = x0;
// Define the goal state
MapSearchNode nodeEnd;
nodeEnd.y = y1;
nodeEnd.x = x1;
// Set Start and goal states
astarsearch.SetStartAndGoalStates( nodeStart, nodeEnd );
unsigned int SearchState;
unsigned int SearchSteps = 0;
do
{
SearchState = astarsearch.SearchStep();
SearchSteps++;
#if DEBUG_LISTS
cout << "Steps:" << SearchSteps << "\n";
int len = 0;
cout << "Open:\n";
MapSearchNode *p = astarsearch.GetOpenListStart();
while( p )
{
len++;
#if !DEBUG_LIST_LENGTHS_ONLY
((MapSearchNode *)p)->PrintNodeInfo();
#endif
p = astarsearch.GetOpenListNext();
}
cout << "Open list has " << len << " nodes\n";
len = 0;
cout << "Closed:\n";
p = astarsearch.GetClosedListStart();
while( p )
{
len++;
#if !DEBUG_LIST_LENGTHS_ONLY
p->PrintNodeInfo();
#endif
p = astarsearch.GetClosedListNext();
}
cout << "Closed list has " << len << " nodes\n";
#endif
}
while( SearchState == AStarSearch<MapSearchNode>::SEARCH_STATE_SEARCHING );
if( SearchState == AStarSearch<MapSearchNode>::SEARCH_STATE_SUCCEEDED )
{
MapSearchNode *node = astarsearch.GetSolutionStart();
#if DISPLAY_SOLUTION
cout << "Displaying solution\n";
#endif
int steps = 0;
//node->PrintNodeInfo();
for( ;; )
{
node = astarsearch.GetSolutionNext();
if( !node )
{
break;
}
//node->PrintNodeInfo();
int * coords = new int[2];
coords[0] = node->x;
coords[1] = node->y;
out.push_back(coords);
steps ++;
};
// Once you're done with the solution you can free the nodes up
astarsearch.FreeSolutionNodes();
}
else if( SearchState == AStarSearch<MapSearchNode>::SEARCH_STATE_FAILED )
{
}
// Display the number of loops the search went through
SearchCount ++;
astarsearch.EnsureMemoryFreed();
}
}
| [
"fionnghall@444a4038-2bd8-11df-954b-21e382534593"
]
| [
[
[
1,
271
]
]
]
|
b1bd4d7e86b502bf14bd71206cc5bfb8b70bce81 | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/conjurer/conjurer/src/conjurer/nterraineditorstate_input.cc | d1bcde412f995e05c481e190f7b5c58994846246 | []
| no_license | ugozapad/TheZombieEngine | 832492930df28c28cd349673f79f3609b1fe7190 | 8e8c3e6225c2ed93e07287356def9fbdeacf3d6a | refs/heads/master | 2020-04-30T11:35:36.258363 | 2011-02-24T14:18:43 | 2011-02-24T14:18:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,556 | cc | #include "precompiled/pchconjurerapp.h"
//------------------------------------------------------------------------------
// nterraineditorstate_input.cc
// (C) 2005 Conjurer Services, S.A.
//------------------------------------------------------------------------------
#include "kernel/nkernelserver.h"
#include "conjurer/nterraineditorstate.h"
#include "conjurer/nconjurerapp.h"
#include "napplication/napplication.h"
#include "napplication/nappviewportui.h"
#include "napplication/nappviewport.h"
#include "kernel/nkernelserver.h"
#include "kernel/ntimeserver.h"
#include "ngeomipmap/nterraincellinfo.h"
#include "ngeomipmap/ncterrainmaterialclass.h"
#include "conjurer/ninguiterraintoolgeom.h"
#include "conjurer/ninguiterraintoolflatten.h"
#include "conjurer/ninguiterraintoolslope.h"
#include "conjurer/terrainpaintingundocmd.h"
#include "conjurer/terraingrasseditundocmd.h"
#include "nvegetation/ncterrainvegetationcell.h"
#include "nvegetation/ncterrainvegetationclass.h"
//------------------------------------------------------------------------------
/// Constant factor for terrain tool effect
const float nTerrainEditorState::TerrainToolIntensity = 3.0f;
//------------------------------------------------------------------------------
/**
@brief Handle mouse and keyb inputs for editing the terrain in the current viewport
@return True only if an input was processed
*/
bool
nTerrainEditorState::HandleInput(nTime frameTime)
{
// Check running physics
if (!this->currentInguiTool->CanApplyWhenRunningPhysics() && this->GetApp()->IsPhysicsEnabled())
{
return nEditorState::HandleInput(frameTime);
}
// If there is no heightmap set, do nothing
if ( ! this->heightMap.isvalid() )
{
return nEditorState::HandleInput(frameTime);
}
// Get input server reference
nInputServer* inputServer = nInputServer::Instance();
// Get current viewport
nAppViewport* vp = this->refViewportUI->GetCurrentViewport();
const rectangle& relSize = vp->GetRelSize();
// Get mouse coordinates in viewport space [0..1], and center them in the viewport [-1..1]
vector2 mousePos = nInputServer::Instance()->GetMousePos();
mousePos = mousePos - relSize.v0;
mousePos.x /= relSize.width();
mousePos.y /= relSize.height();
vector2 mp = mousePos * 2 - vector2(1, 1);
mp.y = -mp.y;
// Get mouse button state flags
bool leftButtonPressed = inputServer->GetButton("buton0") || inputServer->GetButton("buton0_ctrl") || inputServer->GetButton("buton0_alt") || inputServer->GetButton("buton0_shift");
bool leftButtonDown = inputServer->GetButton("buton0_down") || inputServer->GetButton("buton0_down_ctrl") || inputServer->GetButton("buton0_down_alt") || inputServer->GetButton("buton0_down_shift");
// If the left button is pressed, we have a possible terrain edit action...
if ( leftButtonPressed || leftButtonDown )
{
// Apply the tool
bool applied = false;
if ( this->currentInguiTool->IsFirstPick( vp ) )
{
// This is the first click
this->previousViewport = vp;
int undoRectSize = heightMap->GetSize();
if ( this->currentInguiTool->IsA( terrainToolGeomClass ) )
{
undoRectSize = int( undoRectSize * static_cast<nInguiTerrainToolGeom*>(this->currentInguiTool)->GetDrawResolutionMultiplier() );
}
undoRectangle.Set( undoRectSize, undoRectSize, -1, -1);
applied = this->ApplyTool(frameTime, vp, mp , true, false);
}
else
{
// These are the next editing 'events'
applied = this->ApplyTool(frameTime, vp, mp, false, false);
}
// Update cursor 3d drawing needed flag if the tool was applied
this->currentInguiTool->SetDrawEnabled( applied );
// Actualize the current height in the Height widget
if ( applied )
{
if ( this->selectedTool == Flatten && ((nInguiTerrainToolFlatten*)this->inguiTerrainTool[ Flatten ])->GetAdaptiveIntensity() > 0.0f )
{
// Emit signal to make OUTGUI refresh the widget
static_cast<nInguiTerrainToolFlatten*>(inguiTerrainTool[ selectedTool ])->SignalRefreshFlattenHeight( inguiTerrainTool[ selectedTool ] );
}
// Emit signal to make OUTGUI refresh generic info of the tool
static_cast<nInguiTool*>(inguiTerrainTool[ selectedTool ])->SignalRefreshInfo( inguiTerrainTool[ selectedTool ] );
}
return applied;
}
else
{
// Left mouse button is not pressed.
// If a tool was being used,
if ( this->currentInguiTool->GetState() > nInguiTool::Inactive )
{
bool isLastPick = this->currentInguiTool->GetState() >= nInguiTool::Inactive;
if ( isLastPick )
{
this->currentInguiTool->SetState( nInguiTool::Finishing );
}
// Last apply
ApplyTool(frameTime, vp, mp, false, false);
// Create the undo command corresponding to the tool and pass it to the undo server
if ( this->currentInguiTool->IsA( this->terrainToolGeomClass ) &&
this->undoRectangle.x1 > this->undoRectangle.x0 &&
this->undoRectangle.z1 > this->undoRectangle.z0 )
{
// Make undo rectangle squared
int sx = abs( undoRectangle.x1 - undoRectangle.x0 );
int sz = abs( undoRectangle.z1 - undoRectangle.z0 );
if ( sx != sz )
{
if ( sx > sz )
{
undoRectangle.z1 = undoRectangle.z0 + sx;
}
else
{
undoRectangle.x1 = undoRectangle.x0 + sz;
}
}
float mult = static_cast<nInguiTerrainToolGeom*>(this->currentInguiTool)->GetDrawResolutionMultiplier();
int undoRectSize = int( heightMap->GetSize() * mult );
int curUndoRectSize = this->undoRectangle.x1 - this->undoRectangle.x0 + 1;
if ( this->selectedTool < Paint )
{
// Terrain geometry tool
TerrainUndoCmd* newCmd = n_new( TerrainGeometryUndoCmd( this->heightMapBuffer,
this->heightMap,
this->undoRectangle.x0,
this->undoRectangle.z0,
curUndoRectSize ) );
// Insert command into the undo server
if (newCmd)
{
nString name( inguiTerrainTool[ selectedTool ]->GetLabel() );
newCmd->SetLabel( name );
nUndoServer::Instance()->NewCommand( newCmd );
}
}
else if ( this->selectedTool <= Grass )
{
// Paint tool and grass tool
nEntityObject * outdoor = this->GetOutdoorEntityObject();
n_assert( outdoor );
if ( this->selectedTool == Paint )
{
int cellRes = this->layerManager->GetAllWeightMapsSize();
int bx0 = min( this->undoRectangle.x0 / cellRes, this->layerManager->GetMaterialNumBlocks() - 1 );
int bx1 = min( this->undoRectangle.x1 / cellRes, this->layerManager->GetMaterialNumBlocks() - 1 );
int bz0 = min( this->undoRectangle.z0 / cellRes, this->layerManager->GetMaterialNumBlocks() - 1 );
int bz1 = min( this->undoRectangle.z1 / cellRes, this->layerManager->GetMaterialNumBlocks() - 1 );
// Create paint tool undo cmds
if ( this->layerManager->GetSelectedLayer() )
{
for ( int bx = bx0; bx <= bx1; bx++ )
{
for ( int bz = bz0; bz <= bz1; bz++ )
{
nTerrainCellInfo* wmap = this->layerManager->GetTerrainCellInfo( bx, bz );
int n = wmap->GetNumberOfLayers();
for ( int i = 0; i < n; i++ )
{
nTerrainCellInfo::WeightMapLayerInfo& layerInfo = wmap->GetLayerInfo( i );
TerrainPaintingUndoCmd* newCmd = n_new( TerrainPaintingUndoCmd( layerInfo.undoLayer.get_unsafe(),
layerInfo.refLayer.get_unsafe(),
bx,
bz,
layerInfo.layerHandle
) );
if ( newCmd )
{
// these flags makes the undo server undo or redo several times ( chained )
newCmd->chainUndo = i > 0 || ( bx > bx0 || bz > bz0 );
newCmd->chainRedo = i < n-1 || ( bx < bx1 || bz < bz1 );
// insert into the undo server the commands
nString name( inguiTerrainTool[ selectedTool ]->GetLabel() );
newCmd->SetLabel( name );
nUndoServer::Instance()->NewCommand( newCmd );
}
}
}
}
}
}
else
{
ncTerrainVegetationClass * vegClass = outdoor->GetClassComponentSafe<ncTerrainVegetationClass>();
int cellRes = vegClass->GetGrowthMapSizeByCell();
int bx0 = n_min(this->undoRectangle.x0 / cellRes , this->layerManager->GetMaterialNumBlocks() - 1);
int bx1 = n_min(this->undoRectangle.x1 / cellRes, this->layerManager->GetMaterialNumBlocks() - 1 );
int bz0 = n_min(this->undoRectangle.z0 / cellRes, this->layerManager->GetMaterialNumBlocks() - 1 );
int bz1 = n_min(this->undoRectangle.z1 / cellRes, this->layerManager->GetMaterialNumBlocks() - 1 );
// Create grass tool undo cmds
for ( int bx = bx0; bx <= bx1; bx++ )
{
for ( int bz = bz0; bz <= bz1; bz++ )
{
nTerrainCellInfo* cellInfo = this->layerManager->GetTerrainCellInfo( bx, bz );
n_assert( cellInfo );
// Get cell entity's vegetation component
nEntityObject * cellEntity = cellInfo->GetTerrainCell();
n_assert(cellEntity);
ncTerrainVegetationCell * vegCell = cellEntity->GetComponentSafe<ncTerrainVegetationCell>();
TerrainGrassEditUndoCmd* newCmd = n_new( TerrainGrassEditUndoCmd( vegCell->GetUndoGrowthMap(),
vegCell->GetValidGrowthMap(),
bx,
bz
) );
if ( newCmd )
{
// these flags makes the undo server undo or redo several times ( chained )
newCmd->chainUndo = ( bx > bx0 || bz > bz0 );
newCmd->chainRedo = ( bx < bx1 || bz < bz1 );
// insert into the undo server the commands
nString name( inguiTerrainTool[ selectedTool ]->GetLabel() );
newCmd->SetLabel( name );
nUndoServer::Instance()->NewCommand( newCmd );
}
}
}
}
}
this->undoRectangle.Set( undoRectSize, undoRectSize, -1, -1);
}
else
{
// Create undo cmd for other tools (hole,...)
}
// The tool is not being applied, reset tool state to inactive
this->currentInguiTool->SetState( nInguiTool::Inactive );
return true;
}
else
{
// Refresh 3d mouse position for visual feedback, with a dummy call to ApplyTool. Also refreshes 3d cursor drawing needed flag
bool drawFlag = this->ApplyTool(frameTime, vp, mp, false, true );
this->currentInguiTool->SetDrawEnabled( drawFlag );
if ( this->currentInguiTool->IsA( terrainToolGeomClass ) )
{
if ( inputServer->GetButton("wheel_down_ctrl") )
{
this->MakePaintbrushSmaller();
}
if ( inputServer->GetButton("wheel_up_ctrl") )
{
this->MakePaintbrushBigger();
}
}
if ( drawFlag )
{
// Emit signal to make OUTGUI refresh generic info of the tool
inguiTerrainTool[ selectedTool ]->SignalRefreshInfo( inguiTerrainTool[ selectedTool ] );
}
}
}
return nEditorState::HandleInput(frameTime);
}
//------------------------------------------------------------------------------
/**
@brief Apply the selected tool
@param vp The nAppViewport where the user is editing
@param mp The mouse position inside the viewport (range -1..1)
@param firstTime Tells if this is the first click in the viewport
@param dummy If true, this flag makes the function to actually don't do the action. Only 3d mouse position is computed, for visual feedback.
@return True only if the heightmap was modified
*/
bool
nTerrainEditorState::ApplyTool(nTime frameTime, nAppViewport *vp, vector2 mp, bool firstClick, bool dummy )
{
if ( currentInguiTool->GetState() < nInguiTool::Finishing )
{
// Alter tool depending on keyboard input (alt, control..)
currentInguiTool->HandleInput( vp );
}
// Get heightmap reference
if ( ! heightMap.isvalid())
{
return false;
}
nFloatMap* hmap = heightMap.get();
// Select source paintbrush heightmap -- only if terrain geom tool selected
nFloatMap* hmapbrush;
// If the tool is a geometric one, set current terrain paintbrush
if ( this->currentInguiTool->IsA( this->terrainToolGeomClass ) )
{
if (this->selectedPaintbrush < numPredefinedPaintbrushes)
{
hmapbrush = predefinedPaintbrush;
}
else
{
// get user paintbrush from the narray
hmapbrush = userPaintbrushList[ selectedPaintbrush - numPredefinedPaintbrushes ];
}
(static_cast<nInguiTerrainToolGeom*>(this->currentInguiTool))->SetPaintbrush( hmapbrush );
}
else
{
hmapbrush = 0;
}
// Get world ray in mouse position
line3 ray;
nInguiTool::Mouse2Ray( vp, mp, ray);
// Calculate the width of the ray segment so that it passes through the entire heightmap
float mapSize = ( hmap->GetSize() - 1 ) * hmap->GetGridScale();
float l = vector2(ray.b.x - 0.5f * mapSize, ray.b.z - 0.5f * mapSize).len();
l = 4.0f * l + mapSize;
ray.set(ray.b, ray.b + ray.m * l);
// Call to tool's pick method
float t;
if ( !dummy || currentInguiTool->PickWhileIdle() )
{
t = currentInguiTool->Pick( vp, mp, ray );
}
else
{
// If tool doesn't need it, don't call Pick() while not pressing mouse button
t = -1.0f;
}
bool intersect = ( t >= 0.0f );
// This flag is true if the current tool is flatten and it's adaptive
bool adaptiveFlatten = this->selectedTool == Flatten && ((nInguiTerrainToolFlatten*)this->inguiTerrainTool[ Flatten ])->GetAdaptiveIntensity() > 0.0f && ! dummy;
// If there is intersection,
if ( intersect )
{
// Get the new picked position
currentInguiTool->GetLastPosition( this->lastPoint );
currentInguiTool->GetLastTerrainCoords( this->currentXMousePos, this->currentZMousePos );
// If this is the first action event (the first pick or click)
if ( firstClick )
{
if ( this->selectedTool == Flatten && ! dummy )
{
// Get the first point reference
this->firstPoint = this->lastPoint;
// If this flag is true, get the height from first point picked
if ( adaptiveFlatten )
{
((nInguiTerrainToolFlatten*)inguiTerrainTool[ Flatten ])->SetHeight( this->firstPoint.y );
}
}
}
}
// If this is a dummy call, just return if the mouse pos lays inside the terrain
if ( dummy )
{
return intersect;
}
// Apply the tool
if ( intersect )
{
int xApply = this->currentXMousePos;
int zApply = this->currentZMousePos;
if ( hmapbrush != 0 )
{
xApply -= hmapbrush->GetSize()/2;
zApply -= hmapbrush->GetSize()/2;
}
float oldH;
vector3 normal;
if ( ! hmap->GetHeightNormal( this->lastPoint.x, this->lastPoint.z, oldH, normal ) )
{
oldH = 0.0f;
normal.set(0.0f, 1.0f, 0.0f);
}
if ( adaptiveFlatten && ! firstClick )
{
if ( this->currentXMousePos >= 0 && this->currentXMousePos < hmap->GetSize() &&
this->currentZMousePos >= 0 && this->currentZMousePos < hmap->GetSize() )
{
( static_cast<nInguiTerrainToolFlatten*>
(this->inguiTerrainTool[ Flatten ]) )->AdaptHeight( oldH );
}
}
// Applying time duration
nTime dt = frameTime;
if ( dt < nInguiTool::StdFrameRate )
{
dt = nInguiTool::StdFrameRate;
}
dt *= this->TerrainToolIntensity;
// Set tool state to active, if it is inactive
if ( this->currentInguiTool->GetState() <= nInguiTool::Inactive )
{
this->currentInguiTool->SetState( nInguiTool::Active );
}
// Apply the tool
currentInguiTool->Apply( dt );
// Check if it's needed to refresh the undo rectangle
if ( this->currentInguiTool->IsA( this->terrainToolGeomClass ) )
{
int undoRectSize = heightMap->GetSize();
float mul = static_cast<nInguiTerrainToolGeom*>(this->currentInguiTool)->GetDrawResolutionMultiplier();
if ( mul != 1 )
{
// undo rectangle size is multiplied but first make it a power of 2
undoRectSize--;
undoRectSize = int( undoRectSize * mul );
}
int x0 = xApply;
int z0 = zApply;
int x1 = x0 + int( hmapbrush->GetSize() );
int z1 = z0 + int( hmapbrush->GetSize() );
if ( firstClick )
{
undoRectangle.Set( undoRectSize, undoRectSize, -1, -1);
}
if ( undoRectangle.x0 > x0 )
{
undoRectangle.x0 = max( 0, x0);
}
if ( undoRectangle.z0 > z0 )
{
undoRectangle.z0 = max( 0, z0);
}
if ( undoRectangle.x1 < x1 )
{
undoRectangle.x1 = min( undoRectSize - 1, x1);
}
if ( undoRectangle.z1 < z1 )
{
undoRectangle.z1 = min( undoRectSize - 1, z1);
}
}
// This is testing:
this->debugLine->RefreshHeights();
return true;
}
return false;
}
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
]
| [
[
[
1,
503
]
]
]
|
9ee17826c7447c8814cb432635fcb0222ec5ef49 | 59166d9d1eea9b034ac331d9c5590362ab942a8f | /ParticlePlayer/Lua/_config.h | 7b68a6791c37aeb36759fad821e5be8becf1f732 | []
| no_license | seafengl/osgtraining | 5915f7b3a3c78334b9029ee58e6c1cb54de5c220 | fbfb29e5ae8cab6fa13900e417b6cba3a8c559df | refs/heads/master | 2020-04-09T07:32:31.981473 | 2010-09-03T15:10:30 | 2010-09-03T15:10:30 | 40,032,354 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 565 | h | /**
* Lua Wrapper library
* (C)opyright 2004 by Dmitry S. Baikov
*
* Eagle Dynamics has non-exclusive rights to use, sell and sublicense this code.
*
*/
#ifndef _Lua_config_h_
#define _Lua_config_h_
#ifndef ED_LUA_EXTERN
#if defined(ED_LUA_INTERNALS) || defined(_USRDLL)
#define ED_LUA_EXTERN __declspec(dllexport)
#else
#define ED_LUA_EXTERN __declspec(dllimport)
#endif
#endif
#ifndef ED_LUA_API
#define ED_LUA_API __stdcall
#endif
/**
* @brief Lua bindings library.
*/
namespace Lua {}
#endif /* _Lua_config_h_ */
| [
"asmzx79@3290fc28-3049-11de-8daa-cfecb5f7ff5b"
]
| [
[
[
1,
32
]
]
]
|
27517a4c66567350918411aedc0abe7af593dadc | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /SMDK/Kenwalt/KW_SMDK2/Tailings Graphic.cpp | dd9dea1048313c5b85cd678bfd3f28cbff6ceff0 | []
| 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 | 22,524 | cpp | //================== SysCAD - Copyright Kenwalt (Pty) Ltd ===================
// $Nokeywords: $
//===========================================================================
#include "stdafx.h"
#define __TAILINGS_GRAPHIC_CPP
#include "Tailings Graphic.h"
#include <math.h>
#pragma optimize("", off)
#define MIN(a, b) (a < b ? a : b)
#define MAX(a, b) (a > b ? a : b)
#define BOUND(n, lo, hi) (n < lo ? lo : (n > hi ? hi : n))
#define TAG_OK(item) (item.CheckTag() == MTagIO_OK || item.CheckTag() == MTagIO_ReadOnly)
//====================================================================================
//TODO: A Proper icon
static double Drw_TailingsDam[] = { MDrw_Poly, -2.,2., 2.,2., 2.,-2., -2.,-2., -2.,2., MDrw_End };
//---------------------------------------------------------------------------
DEFINE_CONTROL_UNIT(TailingsGraphic, "Tailings_Dam_Graphic", DLL_GroupName)
void TailingsGraphic_UnitDef::GetOptions()
{
SetDefaultTag("TG");
SetDrawing("Tank", Drw_TailingsDam);
SetTreeDescription("Demo:Tailings Graphic");
SetModelSolveMode(MSolveMode_Probal|MSolveMode_DynamicFlow|MSolveMode_DynamicFull);
SetModelGroup(MGroup_General);
};
//---------------------------------------------------------------------------
TailingsGraphic::TailingsGraphic(MUnitDefBase * pUnitDef, TaggedObject * pNd) : MBaseMethod(pUnitDef, pNd),
FluidMassSubs(TagIO), SolidMassSubs(TagIO),
ConcSubs(TagIO), VolSubs(TagIO), LiquidDensitySubs(TagIO)
{
dMoistFrac = 0;
dSatConc = 1;
dEvapRate = dRainRate = 0;
nDataPointCount = 2;
vInterpolationHeights.push_back(0);
vInterpolationHeights.push_back(1);
vInterpolationAreas.resize(2, 1);
vVolumeLookup.resize(2);
SortInterpolationPoints();
lEvapRateUnits = 0;
eIntMethod = IM_Linear;
dFluidLevel = dSolidLevel = dFSA = 0;
dFluidMass = dSolidMass = 0;
RecalculateVolumes(); //This is called simply to ensure that it has been called once, and so the arrays are in the proper state for any other function.
}
//---------------------------------------------------------------------------
void TailingsGraphic::Init()
{
}
//---------------------------------------------------------------------------
bool TailingsGraphic::PreStartCheck()
{
return true;
}
//---------------------------------------------------------------------------
const int MaxIntPoints = 100;
const int idDX_TankString = 1;
const int idDX_DataPointCount = 2;
const int idDX_ConcSpecies = 3;
const int idDX_InterpolationHeight = MaxIntPoints;
const int idDX_InterpolationArea = 2 * MaxIntPoints;
void TailingsGraphic::BuildDataFields()
{
static MCnvFamily qmFamily = gs_Cnvs[MC_Qm.Index];
static MDDValueLst* DDBQm = NULL;
if (DDBQm == NULL)
{
DDBQm = new MDDValueLst[qmFamily.Count() + 1];
for (int i = 0; i < qmFamily.Count(); i++)
{
int dstSize = strlen(qmFamily[i].Name()) + 1;
char* nonConst = new char[dstSize];
strcpy(nonConst, qmFamily[i].Name());
MDDValueLst cur = {i, nonConst};
DDBQm[i] = cur;
}
MDDValueLst terminator = {0};
DDBQm[qmFamily.Count()] = terminator;
}
// -- User entered data --
//Area calc: Number of interpolation points, and points
//solid moisture fraction, saturation concentration
//Rate of evaporation, rate of rainfall
//Tank name.
// -- Data read from tank --
//liquid mass, solid mass, concentrations, densities.
DD.String("Tank", "", idDX_TankString, MF_PARAMETER);
DD.Double("Moisture_Fraction", "", &dMoistFrac, MF_PARAMETER, MC_Frac);
DD.String("Specie_Of_Interest", "", idDX_ConcSpecies, MF_PARAMETER);
DD.Double("Saturation_Concentration", "", &dSatConc, MF_PARAMETER, MC_Conc);
DD.Double("Evaporation_Rate", "", &dEvapRate, MF_PARAMETER, MC_Qm);
DD.Double("Rainfall_Rate", "", &dRainRate, MF_PARAMETER, MC_Qm);
DD.Long("Evap_And_Rain_Rate_Units", "", &lEvapRateUnits, MF_PARAMETER, DDBQm);
DD.Double("Max_Capacity", "", &dMaxCapacity, MF_RESULT, MC_Vol);
DD.Text("");
DD.Double("Fluid_Level", "", &dFluidLevel, MF_RESULT, MC_L);
DD.Double("Solid_Level", "", &dSolidLevel, MF_RESULT, MC_L);
DD.Double("Fluid_Surface_Area", "", &dFSA, MF_RESULT, MC_Area);
DD.Double("Concentration_Of_Interest", "", &dConc, MF_RESULT, MC_Conc);
DD.Page("Surface_Volume_Calcs");
DD.Long("Data_Point_Count", "", idDX_DataPointCount, MF_PARAMETER);
//Todo: Interpolation type.
DD.ArrayBegin("Data_Points", "Data_Points", nDataPointCount);
for (int i = 0; i < nDataPointCount; i++)
{
DD.ArrayElementStart(i);
DD.Double("Height", "", idDX_InterpolationHeight + i, i == 0 ? MF_RESULT : MF_PARAMETER, MC_L);
DD.Double("Area", "", idDX_InterpolationArea + i, MF_PARAMETER, MC_Area);
DD.ArrayElementEnd();
}
DD.ArrayEnd();
}
bool TailingsGraphic::ExchangeDataFields()
{
if (DX.Handle == idDX_TankString)
{
if (DX.HasReqdValue)
{
sTankName = DX.String;
SetTags();
}
DX.String = sTankName;
return true;
}
if (DX.Handle == idDX_DataPointCount)
{
if (DX.HasReqdValue)
{
SetIntPtCount(DX.Long);
RecalculateVolumes();
RecalculateLevels();
}
DX.Long = nDataPointCount;
return true;
}
if (idDX_InterpolationHeight <= DX.Handle && DX.Handle <= idDX_InterpolationHeight + nDataPointCount)
{
if (DX.HasReqdValue)
{
if (DX.Double < 0)
vInterpolationHeights.at(DX.Handle - idDX_InterpolationHeight) = 0;
else
vInterpolationHeights.at(DX.Handle - idDX_InterpolationHeight) = DX.Double;
SortInterpolationPoints();
RecalculateVolumes();
RecalculateLevels();
}
DX.Double = vInterpolationHeights.at(DX.Handle - idDX_InterpolationHeight);
return true;
}
if (idDX_InterpolationArea <= DX.Handle && DX.Handle <= idDX_InterpolationArea + nDataPointCount)
{
if (DX.HasReqdValue)
{
if (DX.Double < 0)
vInterpolationAreas.at(DX.Handle - idDX_InterpolationArea) = 0;
else
vInterpolationAreas.at(DX.Handle - idDX_InterpolationArea) = DX.Double;
SortInterpolationPoints(); //Because an update is needed.
RecalculateVolumes();
RecalculateLevels();
}
DX.Double = vInterpolationAreas.at(DX.Handle - idDX_InterpolationArea);
return true;
}
if (DX.Handle == idDX_ConcSpecies)
{
if (DX.HasReqdValue)
{
sConcSpecies = DX.String;
int loc = sConcSpecies.ReverseFind('.');
if (loc > 0);
sConcSpecies = sConcSpecies.Right(sConcSpecies.GetLength() - loc - 1);
/*if (sConcSpecies.GetLength() > 0 &&
(sConcSpecies.GetLength() < 4 || sConcSpecies.Right(4) != "(aq)"))
sConcSpecies.Append("(aq)");*/
}
DX.String = sConcSpecies;
SetTags();
return true;
}
return false;
}
void TailingsGraphic::SetTags()
{
CString temp;
int i = 0;
sTankName = sTankName.Tokenize(".", i);
temp.Format("%s%s", sTankName, ".Content.Liquids");
FluidMassSubs.Tag = temp;
temp.Format("%s%s", sTankName, ".Content.Solids");
SolidMassSubs.Tag = temp;
temp.Format("%s%s", sTankName, ".Content.Vt");
VolSubs.Tag = temp;
temp.Format("%s%s", sTankName, ".Content.LRho");
LiquidDensitySubs.Tag = temp;
temp.Format("%s%s%s", sTankName, ".Content.", sConcSpecies);
ConcSubs.Tag = temp;
RecalculateLevels();
}
bool TailingsGraphic::ValidateDataFields()
{
if (dMoistFrac < 0) dMoistFrac = 0;
if (dEvapRate < 0) dEvapRate = 0;
if (dRainRate < 0) dRainRate = 0;
if (dSatConc < 0) dSatConc = 0;
if (TagIO.ValidateReqd())
{
if (TagIO.StartValidateDataFields())
{
CString name;
name.Format("%s.LiquidMassTag", getTag());
FluidMassSubs.Configure(0, NULL, name, MTagIO_Get);
name.Format("%s.SolidMassTag", getTag());
SolidMassSubs.Configure(1, NULL, name, MTagIO_Get);
name.Format("%s.ConcTag", getTag());
ConcSubs.Configure(2, NULL, name, MTagIO_Get);
name.Format("%s.VolTag", getTag());
VolSubs.Configure(3, NULL, name, MTagIO_Get);
name.Format("%s.LiquidDensityTag", getTag());
LiquidDensitySubs.Configure(4, NULL, name, MTagIO_Get);
}
TagIO.EndValidateDataFields();
}
RecalculateVolumes();
bool ret = RecalculateLevels();
Log.SetCondition(!ret, 0, MMsg_Error, "Unable to retrieve critical tank information");
Log.SetCondition(sConcSpecies.Trim() != "" && !ConcSubs.IsActive, 1, MMsg_Warning, "Unable to information related to concentration specie");
return ret;
return true;
}
void TailingsGraphic::SortInterpolationPoints()
{
//We need a stable sort of a relatively small dataset, which should not be called too often.
bool changed = true;
vSortedHeights.clear();
vSortedAreas.clear();
vSortedHeights.push_back(0);
vSortedAreas.push_back(vInterpolationAreas.at(0));
//We can use an insertion sort on a vector (even though this is inefficient), since it should be a small dataset, mostly ordered, and a seldom called function.
for (int i = 1; i < nDataPointCount; i++)
{
double h = vInterpolationHeights.at(i),
a = vInterpolationAreas.at(i);
vector<double>::iterator hIterator = vSortedHeights.begin();
vector<double>::iterator aIterator = vSortedAreas.begin();
while (hIterator != vSortedHeights.end() && *hIterator <= h)
{
hIterator++;
aIterator++;
}
/*hIterator--;
aIterator--;*/
vSortedHeights.insert(hIterator, h);
vSortedAreas.insert(aIterator, a);
}
}
//---------------------------------------------------------------------------
bool TailingsGraphic::GetModelGraphic(CMdlGraphicArray & Grfs)
{
CMdlGraphic G0(0, MGT_Simple, true, "Graphic", 1);
Grfs.SetSize(0);
Grfs.SetAtGrow(0, G0);
return true;
}
bool TailingsGraphic::OperateModelGraphic(CMdlGraphicWnd &Wnd, CMdlGraphic &Grf)
{
const COLORREF White = COLORREF(RGB(255,255,255));
const COLORREF Black = COLORREF(RGB(0,0,0));
const COLORREF Grey = COLORREF(RGB(192, 192, 192));
const COLORREF Blue = COLORREF(RGB(0,0,255));
const COLORREF Cyan = COLORREF(RGB(0,255,255));
const COLORREF Red = COLORREF(RGB(255,0,0));
const COLORREF Green = COLORREF(RGB(0,255,0));
const COLORREF Brown = COLORREF(RGB(205, 146, 53));
switch (Wnd.m_eTask)
{
case MGT_Create:
Wnd.m_pWnd->SetWindowPos(NULL, 0, 0, 300, 250, SWP_NOMOVE | SWP_NOZORDER);
break;
case MGT_Size:
Wnd.m_pWnd->Invalidate();
break;
case MGT_Move:
break;
case MGT_EraseBkgnd:
Wnd.m_bReturn = 0;
break;
case MGT_Paint:
Wnd.m_pPaintDC->FillSolidRect(Wnd.m_ClientRect, Black);
Wnd.m_pPaintDC->SetTextColor(Green);
CPen penWhite(PS_SOLID, 0, White);
CPen penGreen(PS_SOLID, 0, Green);
int nTextSize = Wnd.m_TextSize.y;
int nBorderSpace = nTextSize;
double dFlowFrac = 0.2;
double dOverflowFrac = 0.07;
double dOutYFrac = 0.15;
double dOutXFrac = 0.2;
CRect topRect = Wnd.m_ClientRect;
topRect.left += nBorderSpace; topRect.top += nBorderSpace;
topRect.bottom -= nBorderSpace; topRect.right -= nBorderSpace;
topRect.bottom = topRect.top + topRect.Height() * dFlowFrac;
CRect lowerRect = Wnd.m_ClientRect;
lowerRect.top = topRect.bottom;
lowerRect.bottom -= nBorderSpace;
double maxHeight = vSortedHeights.back();
if (maxHeight == 0) return true;
CRect insideRect;
insideRect.left = lowerRect.left + lowerRect.Width() * dOutXFrac;
insideRect.top = lowerRect.top + lowerRect.Height() * dOverflowFrac;
insideRect.right = lowerRect.right - lowerRect.Width() * dOutXFrac;
insideRect.bottom = lowerRect.bottom;
//Draw dam shape:
int ptCount;
POINT* insidePts = GetDamPoints(maxHeight, insideRect, ptCount);
POINT* Dam = new POINT[2 + ptCount];
Dam[0].x = lowerRect.left; Dam[1 + ptCount].x = lowerRect.right;
Dam[0].y = Dam[1 + ptCount].y = lowerRect.top + lowerRect.Height() * (dOverflowFrac + dOutYFrac);
memcpy(Dam + 1, insidePts, ptCount * sizeof(POINT));
delete[] insidePts;
CPen damPen(PS_SOLID, 3, Grey);
CPen* oldPen = Wnd.m_pPaintDC->SelectObject(&damPen);
Wnd.m_pPaintDC->Polyline(Dam, 2 + ptCount);
delete[] Dam;
CPen nullPen(PS_NULL, 0, White);
Wnd.m_pPaintDC->SelectObject(nullPen);
//Draw fluid:
BYTE pureR = 0, pureG = 0, pureB = 255;
BYTE satR = 255, satG = 0, satB = 0;
POINT* fluid = GetDamPoints(dFluidLevel, insideRect, ptCount);
//A dSatConc of zero means just display pure water...
double concFrac = dSatConc >= 0 ? BOUND(dConc / dSatConc, 0, 1) : 0;
COLORREF fluidColour = RGB(
pureR * (1 - concFrac) + satR * concFrac,
pureG * (1 - concFrac) + satG * concFrac,
pureB * (1 - concFrac) + satB * concFrac);
CBrush fluidBrush(fluidColour);
CBrush* oldBrush = Wnd.m_pPaintDC->SelectObject(&fluidBrush);
Wnd.m_pPaintDC->Polygon(fluid, ptCount);
delete[] fluid;
//Draw sediment:
POINT* sediment = GetDamPoints(dSolidLevel, insideRect, ptCount);
CBrush sedimentBrush(Brown);
Wnd.m_pPaintDC->SelectObject(&sedimentBrush);
Wnd.m_pPaintDC->Polygon(sediment, ptCount);
delete[] sediment;
//Draw overflow:
/*if (bOverflowing)
{
Wnd.m_pPaintDC->SelectObject(&fluidBrush);
POINT overflowLeft[] = {
{lowerRect.left, lowerRect.top + lowerRect.Height() * (dOverflowFrac + dOutYFrac)},
{lowerRect.left + lowerRect.Width() * dOutXFrac, lowerRect.top + lowerRect.Height() * dOverflowFrac},
{lowerRect.left + lowerRect.Width() * dOutXFrac, lowerRect.top},
{lowerRect.left, lowerRect.top + lowerRect.Height() * dOutYFrac}};
POINT overflowRight[] = {
{lowerRect.right, lowerRect.top + lowerRect.Height() * (dOverflowFrac + dOutYFrac)},
{lowerRect.right - lowerRect.Width() * dOutXFrac, lowerRect.top + lowerRect.Height() * dOverflowFrac},
{lowerRect.right - lowerRect.Width() * dOutXFrac, lowerRect.top},
{lowerRect.right, lowerRect.top + lowerRect.Height() * dOutYFrac}};
Wnd.m_pPaintDC->Polygon(overflowLeft, 4);
Wnd.m_pPaintDC->Polygon(overflowRight, 4);
}*/
//Draw arrows:
int nArrowSize = 8;
double offset = 0, scale = 1;
static MCnvFamily qmFamily = gs_Cnvs[MC_Qm.Index];
if (qmFamily[lEvapRateUnits].Valid())
{
offset = qmFamily[lEvapRateUnits].Offset();
scale = qmFamily[lEvapRateUnits].Scale();
}
//Evaporation:
CPen arrowPen(PS_SOLID, 2, Blue);
Wnd.m_pPaintDC->SelectObject(arrowPen);
if (dRainRate > 0)
{
for (int i = 1; i < 4; i++)
{
POINT Arrow1[] = {
{topRect.left + i * topRect.Width() / 10, topRect.top},
{topRect.left + (i + 1) * topRect.Width() / 10, topRect.bottom}};
POINT Arrow2[] = {
{topRect.left + (i + 1) * topRect.Width() / 10 - nArrowSize + 1, topRect.bottom},
{topRect.left + (i + 1) * topRect.Width() / 10 + 1, topRect.bottom},
{topRect.left + (i + 1) * topRect.Width() / 10 + 1, topRect.bottom - nArrowSize}};
Wnd.m_pPaintDC->Polyline(Arrow1, 2);
Wnd.m_pPaintDC->Polyline(Arrow2, 3);
}
Wnd.m_pPaintDC->SetTextAlign(TA_CENTER | TA_TOP);
CString rainString;
rainString.Format("Rainfall: %.2f %s", dRainRate * scale + offset, qmFamily[lEvapRateUnits].Name());
CSize txtSize = Wnd.m_pPaintDC->GetTextExtent(rainString);
Wnd.m_pPaintDC->FillSolidRect(
topRect.left + topRect.Width() / 4 - txtSize.cx / 2 - 1,
topRect.CenterPoint().y - nTextSize / 2 - 1,
txtSize.cx + 2, txtSize.cy + 2,
Black);
Wnd.m_pPaintDC->TextOut(
topRect.left + topRect.Width() / 4,
topRect.CenterPoint().y - nTextSize / 2,
rainString);
}
if (dEvapRate > 0)
{
for (int i = 6; i < 9; i++)
{
POINT Arrow1[] = {
{topRect.left + i * topRect.Width() / 10, topRect.bottom},
{topRect.left + (i + 1) * topRect.Width() / 10, topRect.top}};
POINT Arrow2[] = {
{topRect.left + (i + 1) * topRect.Width() / 10 - nArrowSize + 1, topRect.top},
{topRect.left + (i + 1) * topRect.Width() / 10 + 1, topRect.top},
{topRect.left + (i + 1) * topRect.Width() / 10 + 1, topRect.top + nArrowSize}};
Wnd.m_pPaintDC->Polyline(Arrow1, 2);
Wnd.m_pPaintDC->Polyline(Arrow2, 3);
}
Wnd.m_pPaintDC->SetTextAlign(TA_CENTER | TA_TOP);
CString evapString;
evapString.Format("Evaporation: %.2f %s", dEvapRate * scale + offset, qmFamily[lEvapRateUnits].Name());
CSize txtSize = Wnd.m_pPaintDC->GetTextExtent(evapString);
Wnd.m_pPaintDC->FillSolidRect(
topRect.left + 3 * topRect.Width() / 4 - txtSize.cx / 2 - 1,
topRect.CenterPoint().y - nTextSize / 2 - 1,
txtSize.cx + 2, txtSize.cy + 2,
Black);
Wnd.m_pPaintDC->TextOut(
topRect.left + 3 * topRect.Width() / 4,
topRect.CenterPoint().y - nTextSize / 2,
evapString);
}
Wnd.m_pPaintDC->SelectObject(oldBrush);
Wnd.m_pPaintDC->SelectObject(oldPen);
}
return true;
}
POINT* TailingsGraphic::GetDamPoints(double damHeight, CRect insideRect, int& ptCount)
{
double maxHeight = vSortedHeights.back();
double maxArea = 0;
for (int i = 0; i < nDataPointCount; i++)
if (vSortedAreas.at(i) > maxArea)
maxArea = vSortedAreas.at(i);
if (maxArea == 0)
{
POINT* nullRet = new POINT[2];
nullRet[1].y = nullRet[0].y = insideRect.bottom;
nullRet[0].x = insideRect.left;
nullRet[1].y = insideRect.right;
ptCount = 2;
return nullRet;
}
int c = 0;
while (damHeight > vSortedHeights.at(c))
c++;
c++;
POINT* ret = new POINT[2 * c];
ptCount = 2 * c;
for (int i = 0; i < c; i++)
{
int Afactor = 0.5 * insideRect.Width() * vSortedAreas.at(i) / maxArea;
ret[c - 1 - i].x = insideRect.CenterPoint().x - Afactor;
ret[c + i].x = insideRect.CenterPoint().x + Afactor;
ret[c - 1 - i].y = ret[c + i].y = insideRect.bottom - insideRect.Height() * vSortedHeights.at(i) / maxHeight;
}
//Final points are interpolated:
if (c == 1) //If we have only one point, we have a level of zero and don't need to interpolate.
return ret;
ret[0].y = ret[2 * c - 1].y = insideRect.bottom - insideRect.Height() * damHeight / maxHeight;
double heightDiff = damHeight - vSortedHeights.at(c - 2);
double Agrad;
if (vSortedHeights.at(c - 1) == vSortedHeights.at(c - 2))
Agrad = 0; //The easy way to avoid divide by zero errors.
else
Agrad = (vSortedAreas.at(c - 1) - vSortedAreas.at(c - 2)) / (vSortedHeights.at(c - 1) - vSortedHeights.at(c - 2));
double AatH = vSortedAreas.at(c - 2) + heightDiff * Agrad;
int Afactor2 = 0.5 * insideRect.Width() * AatH / maxArea;
ret[0].x = insideRect.CenterPoint().x - Afactor2;
ret[2 * c - 1].x = insideRect.CenterPoint().x + Afactor2;
return ret;
}
//---------------------------------------------------------------------------
//Should this be in GetModelAction rather than EvalCtrlActions?
void TailingsGraphic::EvalCtrlActions(eScdCtrlTasks Tasks)
{
RecalculateLevels(); //TODO: Check whether we should report a zero fluid surface area if it is solid on the surface.
}
void TailingsGraphic::SetIntPtCount(int count)
{
if (count < 2)
count = 2;
if (count > MaxIntPoints)
count = MaxIntPoints;
double topHeight = vSortedHeights.back();
double topArea = vSortedAreas.back();
vInterpolationHeights.resize(count, topHeight);
vInterpolationAreas.resize(count, topArea);
vSortedHeights.resize(count, topHeight);
vSortedAreas.resize(count, topHeight);
vVolumeLookup.resize(count);
nDataPointCount = count;
}
void TailingsGraphic::RecalculateVolumes()
{
double curVol = 0;
vVolumeLookup.at(0) = 0;
switch (eIntMethod)
{
case IM_Linear:
for (int i = 0; i < nDataPointCount - 1; i++)
{
curVol += 0.5 * (vSortedAreas.at(i) + vSortedAreas.at(i + 1)) * (vSortedHeights.at(i + 1) - vSortedHeights.at(i));
vVolumeLookup.at(i + 1) = curVol;
}
break;
}
dMaxCapacity = vVolumeLookup.back();
}
double TailingsGraphic::CalcLevel(double volume)
{
if (volume >= dMaxCapacity)
return vSortedHeights.back();
if (volume <= 0)
return 0;
int i = 0;
while (vVolumeLookup.at(i) < volume) //This finds the first interpolation point that is above the current volume.
i++;
i--; //But because it's easier to think as extrapolating up, I'm going to decrement it.
if (vSortedHeights.at(i + 1) == vSortedHeights.at(i)) //Although this should be impossible.
return vSortedHeights.at(i);
switch (eIntMethod)
{
case IM_Linear:
default:
double deltaV = volume - vVolumeLookup.at(i);
double A0 = vSortedAreas.at(i);
double Agrad = (vSortedAreas.at(i + 1) - vSortedAreas.at(i)) / (vSortedHeights.at(i + 1) - vSortedHeights.at(i));
if (Agrad != 0)
return vSortedHeights.at(i) + (-A0 + sqrt(A0 * A0 + 4 * Agrad * deltaV)) / (2 * Agrad);
else if (A0 != 0)
return vSortedHeights.at(i) + deltaV / A0;
else
return vSortedHeights.at(i); //Well I go no idea how A0 can be zero. But It's easier to simply make sure we never divide by zero.
}
}
double TailingsGraphic::CalcArea(double height)
{
if (height >= vSortedHeights.back())
return vSortedAreas.back();
if (height <= 0)
return vSortedAreas.at(0);
int i = 0;
while (vSortedHeights.at(i) < height)
i++;
i--;
if (vSortedHeights.at(i + 1) == vSortedHeights.at(i)) //Although this should be impossible.
return vSortedAreas.at(i);
switch (eIntMethod)
{
case IM_Linear:
default:
double deltaH = height - vSortedHeights.at(i);
double Agrad = (vSortedAreas.at(i + 1) - vSortedAreas.at(i)) / (vSortedHeights.at(i + 1) - vSortedHeights.at(i));
return vSortedAreas.at(i) + deltaH * Agrad;
}
}
bool TailingsGraphic::RecalculateLevels()
{
if (!LiquidDensitySubs.IsActive) //If we can't get these critical values, no point even trying.
return false;
if (!VolSubs.IsActive) return false;
if (!FluidMassSubs.IsActive) return false;
if (!SolidMassSubs.IsActive) return false;
dFluidMass = FluidMassSubs.DoubleSI;
dSolidMass = SolidMassSubs.DoubleSI;
double dTotalVol = VolSubs.DoubleSI;
double dFluidDensity = LiquidDensitySubs.DoubleSI;
double dFluidVol = dFluidDensity > 0 ? dFluidMass / dFluidDensity : 0;
if (dFluidVol > 0)
{
dConc = ConcSubs.IsActive ? ConcSubs.DoubleSI : 0;
dConc /= dFluidVol;
}
else
dConc = 0;
double dFreeFluidVol = dFluidDensity > 0 ? MAX(0, (dFluidMass - dSolidMass * dMoistFrac) / dFluidDensity) : 0;
double dSolidVol = dTotalVol - dFreeFluidVol;
dFluidLevel = CalcLevel(dTotalVol);
dSolidLevel = CalcLevel(dSolidVol);
dFSA = dFreeFluidVol > 0 ? CalcArea(dFluidLevel) : 0;
return true;
} | [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
243
],
[
255,
681
]
],
[
[
244,
254
]
]
]
|
139b197a26680575dce48357e65e1ce13efedacd | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/exporter/3dsplugin/src/n3dsphysicexport/n3dsphysicexport.cc | 19bc20bff37c36587518ef539e4df4d885694331 | []
| no_license | ugozapad/TheZombieEngine | 832492930df28c28cd349673f79f3609b1fe7190 | 8e8c3e6225c2ed93e07287356def9fbdeacf3d6a | refs/heads/master | 2020-04-30T11:35:36.258363 | 2011-02-24T14:18:43 | 2011-02-24T14:18:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30,150 | cc | //------------------------------------------------------------------------------
// n3dsphysicexport.cc
// (C) 2005 Conjurer Services, S.A.
//------------------------------------------------------------------------------
#include "precompiled/pchn3dsmaxexport.h"
#pragma warning( push, 3 )
#include "Max.h"
#include "simpobj.h"
#include "iparamb2.h"
#include "icustattribcontainer.h"
#include "custattrib.h"
#pragma warning( pop )
#include "n3dsphysicexport/n3dsphysicexport.h"
#include "n3dsexporters/n3dscustomattributes.h"
#include "n3dsexporters/n3dssystemcoordinates.h"
#include "n3dsexporters/n3dsexportserver.h"
#include "n3dsexporters/n3dsscenelist.h"
#include "n3dsexporters/n3dslog.h"
#include "nphysics/ncphysicsobj.h"
#include "nphysics/nphygeombox.h"
#include "nphysics/nphygeomsphere.h"
#include "nphysics/nphygeomcylinder.h"
#include "nphysics/nphygeomtrimesh.h"
//------------------------------------------------------------------------------
const double max_error(0.0001);
const float min_flt_persistable(0.00001f);
//------------------------------------------------------------------------------
static struct PhysicCategory {
const char * name;
nPhysicsGeom::Category type;
} physicCategories [] = {
{ "STATIC", nPhysicsGeom::Static },
{ "RAMP", nPhysicsGeom::Ramp },
{ "STAIRS", nPhysicsGeom::Stairs },
// default value for category is Static, for not founded categories
{ 0, nPhysicsGeom::Static }
};
//------------------------------------------------------------------------------
/**
*/
n3dsPhysicExport::n3dsPhysicExport():
exportSpaces( true ),
entityClass( 0 )
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
n3dsPhysicExport::~n3dsPhysicExport()
{
// empty
}
//------------------------------------------------------------------------------
/**
@param node 3dsMax node
*/
void
n3dsPhysicExport::CreatePhysic( INode * const node )
{
int value = -1;
node->GetUserPropInt("physicType", value );
switch( value )
{
case 0:
this->physicSpaces.PushBack( node );
break;
case 1:
if ( T_LAST != GetCollisionType(node) )
{
this->collisionObjects.PushBack( node );
}
break;
default:
n_assert2_always( "Incorrect type of physic object" );
}
}
//------------------------------------------------------------------------------
/**
@param node 3dsMax node
@returns the collision type
*/
n3dsPhysicExport::CollisionType
n3dsPhysicExport::GetCollisionType( INode *const node)
{
Object * obj = node->GetObjectRef();
Class_ID classid = obj->ClassID();
TSTR name;
node->GetUserPropString( "physicGeom", name );
if( classid == Class_ID( BOXOBJ_CLASS_ID, 0 ) )
{
if( 0 != strcmp( "box", name ) )
{
N3DSERROR( physicExport , ( 0 , "ERROR: Bad Box, physic object \"%s\" " , node->GetName() ) );
return T_LAST;
}
return T_BOX;
}
else if( classid == Class_ID( SPHERE_CLASS_ID, 0 ) )
{
if( 0 != strcmp( "sphere", name ) )
{
N3DSERROR( physicExport , ( 0 , "ERROR: Bad Sphere, physic object \"%s\" " , node->GetName() ) );
return T_LAST;
}
return T_SPHERE;
}
else if( classid == Class_ID( DUMMY_CLASS_ID, 0 ) )
{
if( 0 != strcmp( "composite", name ) )
{
N3DSERROR( physicExport , ( 0 , "ERROR: Bad Composite, physic object \"%s\" " , node->GetName() ) );
return T_LAST;
}
return T_COMPOSITE;
}
else if( classid == Class_ID( CYLINDER_CLASS_ID, 0 ) )
{
if( 0 != strcmp( "realcylinder", name ) )
{
N3DSERROR( physicExport , ( 0 , "ERROR: Bad Cylinder, physic object \"%s\" " , node->GetName() ) );
return T_LAST;
}
return T_REALCYLINDER;
}
else if( 0 == strcmp( "cylinder", name ) )
{
return T_CYLINDER;
}
else if( 0 == strcmp( "mesh", name ) )
{
return T_TRIMESH;
}
else
{
N3DSERROR( physicExport , ( 0 , "ERROR: Incorrect type of physic object \"%s\" " , node->GetName() ) );
//n_assert2_always( "Error in Collision Type" );
return T_LAST;
}
}
//------------------------------------------------------------------------------
/**
@param node 3dsMax node
@param phyGeom physics geometry
*/
void
n3dsPhysicExport::SetGeomAttributes( INode * const node, nPhysicsGeom * const phyGeom ) const
{
int wallFlag = 0, groundFlag = 0, ceilingFlag = 0, walkableFlag = 0;
n3dsCustomAttributes::GetParamInt( node, "CollParams", "wall", wallFlag );
if( wallFlag ){
phyGeom->AddAttributes( nPhysicsGeom::wall );
}
n3dsCustomAttributes::GetParamInt( node, "CollParams", "ground", groundFlag );
if( groundFlag ){
phyGeom->AddAttributes( nPhysicsGeom::ground );
}
n3dsCustomAttributes::GetParamInt( node, "CollParams", "ceiling", ceilingFlag );
if( ceilingFlag ){
phyGeom->AddAttributes( nPhysicsGeom::ceiling );
}
n3dsCustomAttributes::GetParamInt( node, "CollParams", "walkable", walkableFlag );
if( walkableFlag ){
phyGeom->AddAttributes( nPhysicsGeom::walkable );
}
TSTR material;
if( n3dsCustomAttributes::GetParamString( node, "CollParams", "material", material ) )
{
phyGeom->SetGameMaterial( material.data() );
}
}
//------------------------------------------------------------------------------
/**
@param name to check
@returns the name fixed
*/
TSTR
n3dsPhysicExport::CheckPhysicCategoryName( TSTR name ) const
{
if( name.isNull() )
{
name = _T( "STATIC" );
}
int i = 0;
while( physicCategories[ i ].name && ( 0 != stricmp( physicCategories[ i ].name, name ) ) )
{
++i;
}
if( 0 == physicCategories[ i ].name )
{
N3DSERROR( physicExport , ( 0 , "ERROR: invalid physic category %s", name) );
name = _T( "STATIC" );
}
return name;
}
//------------------------------------------------------------------------------
/**
@param geometries 3dstudio objects to check
*/
void
n3dsPhysicExport::CheckAllPhysicCategories( const nArray< INode * > * const geometries ) const
{
// check that all geometries category are the same
TSTR firstname, name;
(*geometries)[ 0 ]->GetUserPropString( "physicCategory", firstname );
firstname = this->CheckPhysicCategoryName( firstname );
for( int i=1; i < geometries->Size() ; ++i )
{
(*geometries)[ i ]->GetUserPropString( "physicCategory", name );
name = this->CheckPhysicCategoryName( name );
if( 0 != stricmp( firstname, name ) )
{
N3DSERROR( physicExport , ( 0 , "ERROR: physic category is not the same in %s for %s",
(*geometries)[i]->GetName(), this->entityClass->nClass::GetName() ) );
}
}
}
//------------------------------------------------------------------------------
/**
@param node 3dstudio object to get from collision attributes
@param obj physic object to set in collision attributes
*/
void
n3dsPhysicExport::SetCollisionAttributes( INode * const node, ncPhysicsObj * const obj ) const
{
TSTR name;
node->GetUserPropString( "physicCategory", name );
int i = 0;
while( physicCategories[ i ].name && ( 0 != stricmp( physicCategories[ i ].name, name ) ) )
{
++i;
}
obj->SetCategories( physicCategories[ i ].type );
obj->SetCollidesWith( 0 );
}
//------------------------------------------------------------------------------
/**
@param node the max node used to create the geometry
@param physicPath physic path where trimesh are saved, if needed
@param geometries list of geometries where created geometry is inserted
*/
void
n3dsPhysicExport::CreateGeometries( INode * const node, const nString & physicPath, nArray<nPhysicsGeom*> & geometries )
{
nPhysicsGeom * geom = 0;
NLOG( physicExport , ( 4 , "CreateGeometries \"%s\" " , node->GetName() ) );
switch( n3dsPhysicExport::GetCollisionType( node ) )
{
case T_BOX:
geom = n3dsPhysicExport::CreateGeomBox( node );
break;
case T_SPHERE:
geom = n3dsPhysicExport::CreateGeomSphere( node );
break;
case T_CYLINDER:
geom = n3dsPhysicExport::CreateGeomCapsule( node );
break;
case T_TRIMESH:
geom = n3dsPhysicExport::CreateGeomTrimesh( node, physicPath );
break;
case T_REALCYLINDER:
n3dsPhysicExport::CreateGeomCylinder( node, physicPath, geometries );
break;
default:
n_assert_always();
}
if( geom )
{
geometries.Append( geom );
} else
{
N3DSWARN( physicExport , ( 0 , "WARNING: Can't Create physics %s", node->GetName() ) );
}
}
//------------------------------------------------------------------------------
/**
@param node 3dsMax node
@returns the physics geometry object
*/
nPhysicsGeom*
n3dsPhysicExport::CreateGeomBox( INode * const node )
{
NLOG( physicExport , ( 4 , "CreateGeomBox \"%s\" " , node->GetName() ) );
SimpleObject* sobj = static_cast<SimpleObject*>( node->GetObjectRef() );
IParamBlock* pb = sobj->pblock;
n3dsSystemCoordinates * sysCoord = n3dsExportServer::Instance()->GetSystemCoordinates();
// get the parameters of the box
float length=1.0, height=1.0, width=1.0;
transform44 tr = sysCoord->MaxToNebulaTransform( node->GetNodeTM(0) );
// check that scale is correct
if( ! sysCoord->HaveIndependentScale( node->GetNodeTM(0) ) )
{
N3DSWARN( physicExport , ( 0 , "WARNING: The object scale isn't in the Local Transform\n" ) );
return 0;
}
// look for parameters
for( int i=0; i<pb->NumParams() ; ++i )
{
TSTR name = sobj->GetParameterName( i );
if( 0 == strcmp(name, "Length" ) )
{
n_assert2( pb->GetParameterType( i ) == TYPE_FLOAT, "Bad Type in Collision Box" );
length = abs( sysCoord->MaxToNebulaDistance( pb->GetFloat( i ) ) );
}
else if( 0 == strcmp(name, "Height" ) )
{
n_assert2( pb->GetParameterType( i ) == TYPE_FLOAT, "Bad Type in Collision Box" );
height = abs( sysCoord->MaxToNebulaDistance( pb->GetFloat( i ) ) );
}
else if( 0 == strcmp(name, "Width" ) )
{
n_assert2( pb->GetParameterType( i ) == TYPE_FLOAT, "Bad Type in Collision Box" );
width = abs( sysCoord->MaxToNebulaDistance( pb->GetFloat( i ) ) );
}
}
// get the scale
vector3 scale = tr.getscale();
// check the scale
if( !( scale.x > 0.f ) )
{
N3DSWARN( physicExport , ( 0 , "WARNING: The scale is incorrect. scale.x <= 0.0" ) );
return 0;
}
if( !( scale.y > 0.f ) )
{
N3DSWARN( physicExport , ( 0 , "WARNING: The scale is incorrect. scale.y <= 0.0" ) );
return 0;
}
if( !( scale.z > 0.f ) )
{
N3DSWARN( physicExport , ( 0 , "WARNING: The scale is incorrect. scale.z <= 0.0" ) );
return 0;
}
// adjust scale
width = width * scale.x;
height = height * scale.y;
length = length * scale.z;
bool validLength = length >= min_flt_persistable;
bool validHeight = height >= min_flt_persistable;
bool validWidth = width >= min_flt_persistable;
bool planeOrBoxInLength = validLength &&(validHeight || validWidth );
bool planeInWidthAndEhight = validHeight && validWidth;
if (! ( planeOrBoxInLength || planeInWidthAndEhight ))
{
N3DSWARNCOND( physicExport, !validLength, ( 0 , "WARNING: Can't Create Box Geometry with lenght * scale <= 0.0" ) );
N3DSWARNCOND( physicExport, !validHeight, ( 0 , "WARNING: Can't Create Box Geometry with height * scale <= 0.0" ) );
N3DSWARNCOND( physicExport, !validWidth, ( 0 , "WARNING: Can't Create Box Geometry with width * scale <= 0.0" ) );
return 0;
}
// the minimun value if the box is a plane
if (!validLength) { length = min_flt_persistable;}
if (!validHeight) { height = min_flt_persistable;}
if (!validWidth) { width = min_flt_persistable;}
// create the geometry object
nKernelServer* ks = nKernelServer::ks;
nPhyGeomBox * phyGeom = static_cast<nPhyGeomBox*>( ks->New("nphygeombox") );
phyGeom->AppendCommentFormat("Max Id: .8X", node->GetHandle() );
phyGeom->AppendCommentFormat("Max name: \"%s\"", node->GetName() );
phyGeom->Enable();
phyGeom->SetLengths( vector3( width, height, length ) );
phyGeom->SetPosition( tr.gettranslation() );
matrix33 m( tr.getquatrotation() );
vector3 eulerangles = m.to_euler();
phyGeom->SetOrientation( eulerangles.x, eulerangles.y, eulerangles.z );
return phyGeom;
}
//------------------------------------------------------------------------------
/**
@param node 3dsMax node
@returns the physics geometry object
*/
nPhysicsGeom*
n3dsPhysicExport::CreateGeomSphere( INode * const node )
{
NLOG( physicExport , ( 4 , "CreateGeomSphere \"%s\" " , node->GetName() ) );
SimpleObject* sobj = (SimpleObject*)node->GetObjectRef();
IParamBlock* pb = sobj->pblock;
n3dsSystemCoordinates * sysCoord = n3dsExportServer::Instance()->GetSystemCoordinates();
// get the parameters of the box
float radius=1.0;
transform44 tr = sysCoord->MaxToNebulaTransform( node->GetNodeTM(0) );
vector3 scale = tr.getscale();
// check that scale is correct
if( (fabs( scale.x - scale.y ) > max_error) || (fabs( scale.x - scale.z ) > max_error)
|| (fabs( scale.y - scale.z) > max_error) )
{
N3DSWARN( physicExport , ( 0 , "WARNING: The scale in GeomSphere is incorrect. Need to be equal in all axes." ) );
return 0;
}
// look for parameters
for( int i=0; i<pb->NumParams() ; ++i )
{
TSTR name = sobj->GetParameterName( i );
if( 0 == strcmp(name, "Radius" ) )
{
n_assert2( pb->GetParameterType( i ) == TYPE_FLOAT, "Bad Type in Collision Sphere" );
radius = sysCoord->MaxToNebulaDistance( pb->GetFloat( i ) );
}
}
// check the scale
if( !( scale.x > 0.f ) )
{
N3DSWARN( physicExport , ( 0 , "WARNING: The scale is incorrect. scale.x <= 0.0" ) );
return 0;
}
// adjust scale
radius = radius * scale.x;
// check the dimensions
if( !( radius >= min_flt_persistable ) )
{
N3DSWARN( physicExport , ( 0 , "WARNING: Can't Create Sphere Geometry with radius * scale <= 0.0" ) );
return 0;
}
// create the geometry object
nKernelServer* ks = nKernelServer::ks;
nPhyGeomSphere * phyGeom = static_cast<nPhyGeomSphere*>( ks->New("nphygeomsphere") );
phyGeom->AppendCommentFormat("Max Id: .8X", node->GetHandle() );
phyGeom->AppendCommentFormat("Max name: \"%s\"", node->GetName() );
phyGeom->Enable();
phyGeom->SetRadius( radius );
phyGeom->SetPosition( tr.gettranslation() );
return phyGeom;
}
//------------------------------------------------------------------------------
/**
@param node 3dsMax node
@returns the physics geometry object
*/
nPhysicsGeom*
n3dsPhysicExport::CreateGeomCapsule( INode * const node )
{
NLOG( physicExport , ( 4 , "CreateGeomCapsule \"%s\" " , node->GetName() ) );
SimpleObject* sobj = (SimpleObject*)node->GetObjectRef();
IParamBlock* pb = sobj->pblock;
n3dsSystemCoordinates * sysCoord = n3dsExportServer::Instance()->GetSystemCoordinates();
// get the parameters of the Capsule
float radius=1.0, height=1.0;
transform44 tr = sysCoord->MaxToNebulaTransform( node->GetNodeTM(0) );
// check that scale is correct
if( ! sysCoord->HaveIndependentScale( node->GetNodeTM(0) ) )
{
N3DSWARN( physicExport , ( 0 , "WARNING: The object scale isn't in the Local Transform" ) );
return 0;
}
vector3 scale = tr.getscale();
if( (fabs( scale.x - scale.z ) > max_error) )
{
N3DSWARN( physicExport , ( 0 , "WARNING: The scale in GeomCapsule is incorrect. Need to be equal in radius axis." ) );
return 0;
}
// look for parameters
for( int i=0; i<pb->NumParams() ; ++i )
{
TSTR name = sobj->GetParameterName( i );
if( 0 == strcmp(name, "Radius" ) )
{
n_assert2( pb->GetParameterType( i ) == TYPE_FLOAT, "Bad Type in Collision Capsule" );
radius = sysCoord->MaxToNebulaDistance( pb->GetFloat( i ) );
}
else if( 0 == strcmp(name, "Height" ) )
{
n_assert2( pb->GetParameterType( i ) == TYPE_FLOAT, "Bad Type in Collision Capsule" );
height = sysCoord->MaxToNebulaDistance( pb->GetFloat( i ) );
}
}
// check the scale
if( !( scale.x > 0.f ) )
{
N3DSWARN( physicExport , ( 0 , "WARNING: The scale is incorrect. scale.x <= 0.0" ) );
return 0;
}
if( !( scale.y > 0.f ) )
{
N3DSWARN( physicExport , ( 0 , "WARNING: The scale is incorrect. scale.y <= 0.0" ) );
return 0;
}
// adjust scale
radius = radius * scale.x;
height = height * scale.y;
// check the dimensions
if( !( radius >= min_flt_persistable ) )
{
N3DSWARN( physicExport , ( 0 , "WARNING: Can't Create Capsule Geometry with radius * scale <= 0.0" ) );
return 0;
}
if( !( height >= min_flt_persistable ) )
{
N3DSWARN( physicExport , ( 0 , "WARNING: Can't Create Capsule Geometry with height * scale <= 0.0" ) );
return 0;
}
// create the geometry object
nKernelServer* ks = nKernelServer::ks;
nPhyGeomCylinder * phyGeom = static_cast<nPhyGeomCylinder*>( ks->New("nphygeomcylinder" ) );
phyGeom->AppendCommentFormat("Max Id: .8X", node->GetHandle() );
phyGeom->AppendCommentFormat("Max name: \"%s\"", node->GetName() );
phyGeom->Enable();
phyGeom->SetRadius( radius );
if( (height - radius*2.0f) < max_error )
{
height = static_cast<float>( radius*2.0f + max_error );
N3DSWARN( physicExport ,
( 0 , "Capsule Height less that 2*radius in %s.\nChange Height Type to Overall and fix Height.",
node->GetName() ) );
}
phyGeom->SetLength( height - radius*2.0f );
phyGeom->SetPosition( tr.gettranslation() ) ;
matrix33 m( tr.getquatrotation() );
vector3 eulerangles = m.to_euler();
phyGeom->SetOrientation( eulerangles.x + PI/2.0f, eulerangles.y, eulerangles.z );
return phyGeom;
}
//------------------------------------------------------------------------------
/**
@param node 3dsMax node
@param physicPath where save the mesh
@param isSimple flag to indicate if mesh is for a simple object
@returns the physics geometry object
*/
nPhysicsGeom*
n3dsPhysicExport::CreateGeomTrimesh( INode * const node, const nString & physicPath, bool isSimple )
{
NLOG( physicExport , ( 4 , "CreateGeomTrimesh \"%s\" " , node->GetName() ) );
Mesh * trimesh;
ObjectState os = node->EvalWorldState( 0 );
if( isSimple )
{
SimpleObject * sobj = (SimpleObject*)os.obj;
sobj->BuildMesh( 0 );
trimesh = &sobj->mesh;
trimesh->buildNormals();
}
else
{
TriObject * tobj = (TriObject*)os.obj;
trimesh = &(tobj->GetMesh());
}
n3dsSystemCoordinates * sysCoord = n3dsExportServer::Instance()->GetSystemCoordinates();
// get the parameters of the Trimesh
transform44 tr = sysCoord->MaxToNebulaTransform( node->GetNodeTM(0) );
// only need the position and rotation
// the scale is in the ObjectTM
tr.setscale( vector3( 1.f, 1.f, 1.f ) );
matrix44 mat = tr.getmatrix();
mat.invert();
transform44 trObject = sysCoord->MaxToNebulaTransform( node->GetObjectTM(0) );
matrix44 matObject = trObject.getmatrix();
// get transformation for normals
transform44 trObjectN = sysCoord->MaxToNebulaTransform( node->GetObjectTM(0) );
trObjectN.setscale( vector3( 1.f, 1.f, 1.f ) );
trObjectN.settranslation( vector3( 0.0f, 0.0f, 0.0f ) );
matrix44 matObjectN = trObjectN.getmatrix();
nMeshBuilder mesh( 3 * trimesh->getNumFaces(), trimesh->getNumFaces(), 1 );
nMeshBuilder::Vertex vertex[3];
nMeshBuilder::Triangle triangle;
Point3 point;
vector3 pos;
vector3 normal;
const bool hasNormal = trimesh->normalsBuilt != 0;
for( int i = 0 ; i < trimesh->getNumFaces() ; ++i )
{
const Face& face = trimesh->faces[i];
if ( hasNormal )
{
point = trimesh->getFaceNormal( i );
normal = sysCoord->MaxtoNebulaVertex( point );
normal = matObjectN * normal;
normal.norm();
}
for( int j=0 ; j<3 ; ++j )
{
point = trimesh->getVert( face.v[j] );
pos = sysCoord->MaxtoNebulaVertex( point );
pos = matObject * pos;
pos = mat * pos;
vertex[j].SetCoord( pos );
if ( hasNormal )
{
vertex[j].SetNormal( normal );
}
}
mesh.AddTriangle( vertex[0], vertex[1], vertex[2] );
}
mesh.Cleanup(0);
// create the geometry object
nKernelServer* ks = nKernelServer::ks;
nString filename( physicPath );
filename += "/meshes/";
filename += node->GetName();
filename += ".n3d2";
nFileServer2::Instance()->MakePath( filename.ExtractDirName().Get() );
mesh.SaveN3d2( ks->GetFileServer(), filename.Get() );
nPhyGeomTriMesh * phyGeom = static_cast<nPhyGeomTriMesh*>( ks->New("nphygeomtrimesh" ) );
phyGeom->AppendCommentFormat("Max Id: .8X", node->GetHandle() );
phyGeom->AppendCommentFormat("Max name: \"%s\"", node->GetName() );
phyGeom->Enable();
phyGeom->SetPosition( tr.gettranslation() ) ;
matrix33 m( tr.getquatrotation() );
vector3 eulerangles = m.to_euler();
phyGeom->SetOrientation( eulerangles.x, eulerangles.y, eulerangles.z );
phyGeom->SetFile( filename.Get() );
return phyGeom;
}
//------------------------------------------------------------------------------
/**
@param node 3dsMax node
@param physicPath where save the mesh
@param geoms array to put in the geometries created
*/
void
n3dsPhysicExport::CreateGeomCylinder( INode * const node, const nString & physicPath, nArray<nPhysicsGeom*> & geoms )
{
NLOG( physicExport , ( 4 , "CreateGeomCylinder \"%s\" " , node->GetName() ) );
SimpleObject* sobj = (SimpleObject*)node->GetObjectRef();
IParamBlock* pb = sobj->pblock;
n3dsSystemCoordinates * sysCoord = n3dsExportServer::Instance()->GetSystemCoordinates();
// get the parameters of the Capsule
float radius=1.0, height=1.0;
transform44 tr = sysCoord->MaxToNebulaTransform( node->GetNodeTM(0) );
// check that scale is correct
if( ! sysCoord->HaveIndependentScale( node->GetNodeTM(0) ) )
{
N3DSWARN( physicExport , ( 0 , "WARNING: The object scale isn't in the Local Transform" ) );
return;
}
vector3 scale = tr.getscale();
if( (fabs( scale.x - scale.z ) > max_error) )
{
N3DSWARN( physicExport , ( 0 , "WARNING:The scale in GeomCylinder is incorrect. Need to be equal in radius axis." ) );
return;
}
// look for parameters
for( int i=0; i<pb->NumParams() ; ++i )
{
TSTR name = sobj->GetParameterName( i );
if( 0 == strcmp(name, "Radius" ) )
{
n_assert2( pb->GetParameterType( i ) == TYPE_FLOAT, "Bad Type in Collision Cylinder" );
radius = sysCoord->MaxToNebulaDistance( pb->GetFloat( i ) );
}
else if( 0 == strcmp(name, "Height" ) )
{
n_assert2( pb->GetParameterType( i ) == TYPE_FLOAT, "Bad Type in Collision Cylinder" );
height = sysCoord->MaxToNebulaDistance( pb->GetFloat( i ) );
}
}
// check the scale
if( !( scale.x > 0.f ) )
{
N3DSWARN( physicExport , ( 0 , "WARNING: The scale is incorrect. scale.x <= 0.0" ) );
return;
}
if( !( scale.y > 0.f ) )
{
N3DSWARN( physicExport , ( 0 , "WARNING: The scale is incorrect. scale.y <= 0.0" ) );
return;
}
// adjust scale
radius = radius * scale.x;
height = height * scale.y;
// check the dimensions
if( !( radius >= min_flt_persistable ) )
{
N3DSWARN( physicExport , ( 0 , "WARNING: Can't Create Cylinder Geometry with radius <= 0.0" ) );
return;
}
if( !( height >= min_flt_persistable ) )
{
N3DSWARN( physicExport , ( 0 , "WARNING: Can't Create Cylinder Geometry with height <= 0.0" ) );
return;
}
// create the geometries
nKernelServer* ks = nKernelServer::ks;
if( (height - radius*2.0f) < max_error )
{
nPhysicsGeom * geom = 0;
geom = n3dsPhysicExport::CreateGeomTrimesh( node, physicPath, true );
n_assert( geom );
if( geom )
{
geoms.Append( geom );
}
}
else
{
// create the body using a capsule
nPhyGeomCylinder * phyBody = static_cast<nPhyGeomCylinder*>( ks->New("nphygeomcylinder" ) );
n_assert( phyBody );
phyBody->AppendCommentFormat("Max Id: .8X", node->GetHandle() );
phyBody->AppendCommentFormat("Max name: \"%s\"", node->GetName() );
if( phyBody )
{
phyBody->Enable();
phyBody->SetRadius( radius );
phyBody->SetLength( height - radius*2.0f );
phyBody->SetPosition( tr.gettranslation() ) ;
matrix33 m( tr.getquatrotation() );
vector3 eulerangles = m.to_euler();
phyBody->SetOrientation( eulerangles.x + PI/2.0f, eulerangles.y, eulerangles.z );
geoms.Append( phyBody );
}
float boxSide = ( 2.f * radius ) / sqrt( 2.f );
// create the end A using a box
nPhyGeomBox * phyEnd = static_cast<nPhyGeomBox*>( ks->New("nphygeombox" ) );
n_assert( phyEnd );
phyEnd->AppendCommentFormat("Max Id: .8X", node->GetHandle() );
phyEnd->AppendCommentFormat("Max name: \"%s\"", node->GetName() );
if( phyEnd )
{
phyEnd->Enable();
phyEnd->SetLengths( vector3( boxSide, boxSide, radius ) );
matrix44 mrot( tr.getquatrotation() );
vector3 dir( 0, ( height - radius ) / 2.f, 0 );
dir = mrot * dir;
matrix33 m( tr.getquatrotation() );
vector3 eulerangles = m.to_euler();
dir = dir + tr.gettranslation();
phyEnd->SetPosition( dir );
phyEnd->SetOrientation( eulerangles.x + PI/2.0f, eulerangles.y, eulerangles.z );
geoms.Append( phyEnd );
}
// create the end B using a box
phyEnd = static_cast<nPhyGeomBox*>( ks->New("nphygeombox" ) );
n_assert( phyEnd );
phyEnd->AppendCommentFormat("Max Id: .8X", node->GetHandle() );
phyEnd->AppendCommentFormat("Max name: \"%s\"", node->GetName() );
if( phyEnd )
{
phyEnd->Enable();
phyEnd->SetLengths( vector3( boxSide, boxSide, radius ) );
matrix44 mrot( tr.getquatrotation() );
vector3 dir( 0, -( height - radius ) / 2.f, 0 );
dir = mrot * dir;
matrix33 m( tr.getquatrotation() );
vector3 eulerangles = m.to_euler();
dir = dir + tr.gettranslation();
phyEnd->SetPosition( dir );
phyEnd->SetOrientation( eulerangles.x + PI/2.0f, eulerangles.y, eulerangles.z );
geoms.Append( phyEnd );
}
}
}
//------------------------------------------------------------------------------
/**
*/
void
n3dsPhysicExport::Init()
{
n3dsExportServer* const server = n3dsExportServer::Instance();
n3dsSceneList list = server->GetMaxIdOrderScene();
n3dsSceneList::iterator index( list.Begin( n3dsObject::physics) );
index.ShowProgressBar( "Export physics: ");
for ( ; index != list.End() ; ++index)
{
n3dsObject& object = (*index);
IGameNode* node = object.GetNode();
IGameObject* obj = node->GetIGameObject();
INode* maxnode = node->GetMaxNode();
NLOG( physicExport , ( 3 , "Init \"%s\" " , node->GetName() ) );
switch(obj->GetIGameType())
{
case IGameObject::IGAME_HELPER:
CreatePhysic( maxnode );
break;
case IGameObject::IGAME_MESH:
{
BOOL isComposite = 0;
maxnode->GetUserPropBool( "physicComposite", isComposite );
if( !isComposite )
{
CreatePhysic( maxnode );
}
break;
}
default:
break;
}
}
};
//------------------------------------------------------------------------------
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
]
| [
[
[
1,
925
]
]
]
|
846aeaabc05ac54ba526ef0ac0e60317961df3d7 | 1bc2f450f157ce39cbd92d0549e1459368a76e94 | /testsrc/ODINTest/ODINTest.cpp | f2ebd802f60807b3f6e2d0efad14e1ee9ec40971 | []
| no_license | mirror/odin | 168267277386d6c07c006cb196fec3bb208f5e3c | 63b4633a87b03a924df612271c2d6310c34834a8 | refs/heads/master | 2023-09-01T13:28:38.392325 | 2011-10-09T15:38:02 | 2011-10-09T15:38:02 | 9,256,124 | 5 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 3,228 | cpp | /******************************************************************************
ODIN - Open Disk Imager in a Nutshell
Copyright (C) 2008
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, version 3 of the 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
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/>
For more information and the latest version of the source code see
<http://sourceforge.net/projects/odin-win>
******************************************************************************/
// ODINTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include "cppunit/CompilerOutputter.h"
#include "cppunit/TextOutputter.h"
#include "cppunit/extensions/TestFactoryRegistry.h"
#include "cppunit/ui/text/TestRunner.h"
#include "..\..\src\ODIN\Config.h"
using namespace std;
DECLARE_SECTION_GLOBAL(L"ODINTest");
CAppModule _Module;
int _tmain(int argc, _TCHAR* argv[])
{
USES_CONVERSION;
HRESULT hRes = ::CoInitialize(NULL);
hRes = _Module.Init(NULL, GetModuleHandle(NULL));
// initialize ini file to read config settings for test and for ConfigTest
CfgFileInitialize(L"ODINTest.ini", true);
DECLARE_INIT_ENTRY(wstring, testsToRun, L"RunTests", L"");
// Get the top level suite from the registry
CppUnit::Test *suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest();
// Adds the test to the list of test to run
CppUnit::TextUi::TestRunner runner;
// to run all tests use:
runner.addTest( suite );
// Change the default outputter to a compiler error format outputter
//runner.setOutputter( new CppUnit::CompilerOutputter( &runner.result(),
// std::cerr ) );
runner.setOutputter( new CppUnit::TextOutputter( &runner.result(),
std::cout ) );
bool wasSuccessful;
if ((testsToRun().compare(L"All")==0) || (testsToRun().length() == 0))
wasSuccessful = runner.run("", true);
else
wasSuccessful = runner.run(W2A(testsToRun().c_str()), true);
// Run all tests.
// wasSuccessful = runner.run("", true);
// Run a single test:
// wasSuccessful = runner.run("CompressedRunLengthStreamTest");
// wasSuccessful = runner.run("ConfigTest", true);
// wasSuccessful = runner.run("ODINManagerTest", true);
// wasSuccessful = runner.run("PartitionInfoMgrTest", true);
// wasSuccessful = runner.run("ExceptionTest", true);
// wasSuccessful = runner.run("ImageTest", true);
// Return error code 1 if the one of test failed.
//cout << "Press <return> to continue...";
//char ch = cin.get();
_Module.Term();
return wasSuccessful ? 0 : 1;
}
| [
"kaltduscher65@b91d169b-bf28-450c-9b59-d70c078a1df8"
]
| [
[
[
1,
90
]
]
]
|
d9eda4c248d28b8536dcbabf609df9e2cb67c82e | 8a8c3d018f999f787a3751f32f24aca787bb05f8 | /cocoR/cs.cpp | cac2e2b95645a689070baea35ac63ce0738be912 | []
| no_license | daoopp/mse | fbc01193584400866b7516ecf24e6f0837443b87 | 2631ce8a7b5b225c9e4440aefdf12c2604846674 | refs/heads/master | 2021-01-18T07:19:20.025158 | 2011-03-17T15:36:02 | 2011-03-17T15:36:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,937 | cpp | //****************************************************************
// CPLUS2\SCAN_C.FRM
// Coco/R C++ Support Frames.
// Author: Frankie Arzu <[email protected]>
//
// Jun 12, 1996 Version 1.06
// Many fixes and suggestions thanks to
// Pat Terry <[email protected]>
// Oct 31, 1999 Version 1.14
// LeftContext Support
// Mar 24, 2000 Version 1.15
// LeftContext Support no longer needed
//****************************************************************
/*************** NOTICE *****************
This file is generated by cocoR
*****************************************/
#include "cc.hpp"
#include "cs.hpp"
#define Scan_Ch Ch
#define Scan_NextCh NextCh
#define Scan_ComEols ComEols
#define Scan_CurrLine CurrLine
#define Scan_CurrCol CurrCol
#define Scan_LineStart LineStart
#define Scan_BuffPos BuffPos
#define Scan_NextLen NextSym.Len
int cScanner::STATE0[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,54,24,33,0,64,50,26,44,45,46,61,41,62,67,63,35,2,2,2,2,2,2,2,2,2,47,37,
30,38,56,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,42,0,43,52,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,39,48,40,80,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int cScanner::CheckLiteral(int id)
{ char c;
c = CurrentCh(NextSym.Pos);
if (IgnoreCase) c = Upcase(c);
switch (c) {
case 'b':
if (EqualStr("break")) return breakSym;
break;
case 'c':
if (EqualStr("class")) return classSym;
if (EqualStr("char")) return charSym;
if (EqualStr("case")) return caseSym;
if (EqualStr("continue")) return continueSym;
break;
case 'd':
if (EqualStr("double")) return doubleSym;
if (EqualStr("default")) return defaultSym;
if (EqualStr("do")) return doSym;
break;
case 'e':
if (EqualStr("else")) return elseSym;
break;
case 'f':
if (EqualStr("function")) return functionSym;
if (EqualStr("float")) return floatSym;
if (EqualStr("for")) return forSym;
break;
case 'i':
if (EqualStr("inherit")) return inheritSym;
if (EqualStr("int")) return intSym;
if (EqualStr("if")) return ifSym;
break;
case 'l':
if (EqualStr("load")) return loadSym;
if (EqualStr("long")) return longSym;
break;
case 'm':
if (EqualStr("my")) return mySym;
if (EqualStr("mixed")) return mixedSym;
break;
case 'n':
if (EqualStr("new")) return newSym;
break;
case 'r':
if (EqualStr("return")) return returnSym;
break;
case 's':
if (EqualStr("static")) return staticSym;
if (EqualStr("short")) return shortSym;
if (EqualStr("string")) return stringSym;
if (EqualStr("switch")) return switchSym;
break;
case 'u':
if (EqualStr("use")) return useSym;
if (EqualStr("unsigned")) return unsignedSym;
break;
case 'v':
if (EqualStr("var")) return varSym;
if (EqualStr("void")) return voidSym;
break;
case 'w':
if (EqualStr("while")) return whileSym;
break;
}
return id;
}
int cScanner::Comment()
{ int Level, StartLine, OldCol;
long OldLineStart;
Level = 1; StartLine = CurrLine;
OldLineStart = LineStart; OldCol = CurrCol;
if (Scan_Ch == '/') { /* 1 */
Scan_NextCh();
if (Scan_Ch == '*') { /* 2 */
Scan_NextCh();
while (1) {
if (Scan_Ch== '*') { /* 5 */
Scan_NextCh();
if (Scan_Ch == '/') { /* 6 */
Level--; Scan_NextCh(); Scan_ComEols = Scan_CurrLine - StartLine;
if(Level == 0) return 1;
} /* 6 */
} else /* 5 */
if (Scan_Ch == EOF_CHAR) return 0;
else Scan_NextCh();
} /* while */
} else { /* 2 */
if (Scan_Ch == LF_CHAR) { Scan_CurrLine--; Scan_LineStart = OldLineStart; }
Scan_BuffPos -= 2; Scan_CurrCol = OldCol - 1; Scan_NextCh();
} /* 2 */
} /* 1*/
if (Scan_Ch == '/') { /* 1 */
Scan_NextCh();
if (Scan_Ch == '/') { /* 2 */
Scan_NextCh();
while (1) {
if (Scan_Ch== 10) { /* 5 */
Level--; Scan_NextCh(); Scan_ComEols = Scan_CurrLine - StartLine;
if(Level == 0) return 1;
} else /* 5 */
if (Scan_Ch == EOF_CHAR) return 0;
else Scan_NextCh();
} /* while */
} else { /* 2 */
if (Scan_Ch == LF_CHAR) { Scan_CurrLine--; Scan_LineStart = OldLineStart; }
Scan_BuffPos -= 2; Scan_CurrCol = OldCol - 1; Scan_NextCh();
} /* 2 */
} /* 1*/
return 0;
}
int cScanner::Get()
{ int state, ctx;
start:
while (Scan_Ch >= 9 && Scan_Ch <= 10 ||
Scan_Ch == 13 ||
Scan_Ch == ' ') Scan_NextCh();
if ((Scan_Ch == '/') && Comment()) goto start;
CurrSym = NextSym;
NextSym.Init(0, CurrLine, CurrCol - 1, BuffPos, 0);
NextSym.Len = 0; ctx = 0;
if (Ch == EOF_CHAR) return EOF_Sym;
state = STATE0[Ch];
while(1) {
Scan_NextCh(); NextSym.Len++;
switch (state) {
/* State 0; valid STATE0 Table
case 0:
if (Scan_Ch >= 'A' && Scan_Ch <= 'Z' ||
Scan_Ch == '_' ||
Scan_Ch >= 'a' && Scan_Ch <= 'z') state = 1; else
if (Scan_Ch >= '1' && Scan_Ch <= '9') state = 2; else
if (Scan_Ch == '0') state = 35; else
if (Scan_Ch == '"') state = 24; else
if (Scan_Ch == 39) state = 26; else
if (Scan_Ch == '<') state = 30; else
if (Scan_Ch == '#') state = 33; else
if (Scan_Ch == ';') state = 37; else
if (Scan_Ch == '=') state = 38; else
if (Scan_Ch == '{') state = 39; else
if (Scan_Ch == '}') state = 40; else
if (Scan_Ch == ',') state = 41; else
if (Scan_Ch == '[') state = 42; else
if (Scan_Ch == ']') state = 43; else
if (Scan_Ch == '(') state = 44; else
if (Scan_Ch == ')') state = 45; else
if (Scan_Ch == '*') state = 46; else
if (Scan_Ch == ':') state = 47; else
if (Scan_Ch == '|') state = 48; else
if (Scan_Ch == '&') state = 50; else
if (Scan_Ch == '^') state = 52; else
if (Scan_Ch == '!') state = 54; else
if (Scan_Ch == '>') state = 56; else
if (Scan_Ch == '+') state = 61; else
if (Scan_Ch == '-') state = 62; else
if (Scan_Ch == '/') state = 63; else
if (Scan_Ch == '%') state = 64; else
if (Scan_Ch == '.') state = 67; else
if (Scan_Ch == '~') state = 80; else
return No_Sym;
break;
--------- End State0 --------- */
case 1:
if (Scan_Ch >= '0' && Scan_Ch <= '9' ||
Scan_Ch >= 'A' && Scan_Ch <= 'Z' ||
Scan_Ch == '_' ||
Scan_Ch >= 'a' && Scan_Ch <= 'z') /*same state*/; else
return CheckLiteral(identifierSym);
break;
case 2:
if (Scan_Ch == 'U') state = 5; else
if (Scan_Ch == 'u') state = 6; else
if (Scan_Ch == 'L') state = 7; else
if (Scan_Ch == 'l') state = 8; else
if (Scan_Ch == '.') state = 4; else
if (Scan_Ch >= '0' && Scan_Ch <= '9') /*same state*/; else
return numberSym;
break;
case 4:
if (Scan_Ch == 'U') state = 13; else
if (Scan_Ch == 'u') state = 14; else
if (Scan_Ch == 'L') state = 15; else
if (Scan_Ch == 'l') state = 16; else
if (Scan_Ch >= '0' && Scan_Ch <= '9') /*same state*/; else
return numberSym;
break;
case 5:
return numberSym;
case 6:
return numberSym;
case 7:
return numberSym;
case 8:
return numberSym;
case 13:
return numberSym;
case 14:
return numberSym;
case 15:
return numberSym;
case 16:
return numberSym;
case 18:
if (Scan_Ch >= '0' && Scan_Ch <= '9' ||
Scan_Ch >= 'A' && Scan_Ch <= 'F' ||
Scan_Ch >= 'a' && Scan_Ch <= 'f') state = 19; else
return No_Sym;
break;
case 19:
if (Scan_Ch == 'U') state = 20; else
if (Scan_Ch == 'u') state = 21; else
if (Scan_Ch == 'L') state = 22; else
if (Scan_Ch == 'l') state = 23; else
if (Scan_Ch >= '0' && Scan_Ch <= '9' ||
Scan_Ch >= 'A' && Scan_Ch <= 'F' ||
Scan_Ch >= 'a' && Scan_Ch <= 'f') /*same state*/; else
return hexnumberSym;
break;
case 20:
return hexnumberSym;
case 21:
return hexnumberSym;
case 22:
return hexnumberSym;
case 23:
return hexnumberSym;
case 24:
if (Scan_Ch == '"') state = 25; else
if (Scan_Ch >= ' ' && Scan_Ch <= '!' ||
Scan_Ch >= '#' && Scan_Ch <= 255) /*same state*/; else
return No_Sym;
break;
case 25:
return stringD1Sym;
case 26:
if (Scan_Ch >= ' ' && Scan_Ch <= '&' ||
Scan_Ch >= '(' && Scan_Ch <= '[' ||
Scan_Ch >= ']' && Scan_Ch <= 255) state = 28; else
if (Scan_Ch == 92) state = 36; else
return No_Sym;
break;
case 28:
if (Scan_Ch == 39) state = 29; else
return No_Sym;
break;
case 29:
return charD1Sym;
case 30:
if (Scan_Ch == '.' ||
Scan_Ch >= '0' && Scan_Ch <= ':' ||
Scan_Ch >= 'A' && Scan_Ch <= 'Z' ||
Scan_Ch == 92 ||
Scan_Ch >= 'a' && Scan_Ch <= 'z') state = 31; else
if (Scan_Ch == '=') state = 57; else
if (Scan_Ch == '<') state = 59; else
return LessSym;
break;
case 31:
if (Scan_Ch == '>') state = 32; else
if (Scan_Ch == '.' ||
Scan_Ch >= '0' && Scan_Ch <= ':' ||
Scan_Ch >= 'A' && Scan_Ch <= 'Z' ||
Scan_Ch == 92 ||
Scan_Ch >= 'a' && Scan_Ch <= 'z') /*same state*/; else
return No_Sym;
break;
case 32:
return librarySym;
case 33:
if (Scan_Ch >= 'A' && Scan_Ch <= 'Z' ||
Scan_Ch >= 'a' && Scan_Ch <= 'z') state = 34; else
return No_Sym;
break;
case 34:
return PreProcessorSym;
case 35:
if (Scan_Ch == 'U') state = 5; else
if (Scan_Ch == 'u') state = 6; else
if (Scan_Ch == 'L') state = 7; else
if (Scan_Ch == 'l') state = 8; else
if (Scan_Ch == '.') state = 4; else
if (Scan_Ch >= '0' && Scan_Ch <= '9') state = 2; else
if (Scan_Ch == 'X' ||
Scan_Ch == 'x') state = 18; else
return numberSym;
break;
case 36:
if (Scan_Ch >= ' ' && Scan_Ch <= '&' ||
Scan_Ch >= '(' && Scan_Ch <= 255) state = 28; else
if (Scan_Ch == 39) state = 29; else
return No_Sym;
break;
case 37:
return SemicolonSym;
case 38:
if (Scan_Ch == '=') state = 53; else
return EqualSym;
break;
case 39:
return LbraceSym;
case 40:
return RbraceSym;
case 41:
return CommaSym;
case 42:
return LbrackSym;
case 43:
return RbrackSym;
case 44:
return LparenSym;
case 45:
return RparenSym;
case 46:
if (Scan_Ch == '=') state = 70; else
return StarSym;
break;
case 47:
if (Scan_Ch == ':') state = 69; else
return ColonSym;
break;
case 48:
if (Scan_Ch == '|') state = 49; else
if (Scan_Ch == '=') state = 77; else
return BarSym;
break;
case 49:
return BarBarSym;
case 50:
if (Scan_Ch == '&') state = 51; else
if (Scan_Ch == '=') state = 75; else
return AndSym;
break;
case 51:
return AndAndSym;
case 52:
if (Scan_Ch == '=') state = 76; else
return UparrowSym;
break;
case 53:
return EqualEqualSym;
case 54:
if (Scan_Ch == '=') state = 55; else
return BangSym;
break;
case 55:
return BangEqualSym;
case 56:
if (Scan_Ch == '=') state = 58; else
if (Scan_Ch == '>') state = 60; else
return GreaterSym;
break;
case 57:
return LessEqualSym;
case 58:
return GreaterEqualSym;
case 59:
if (Scan_Ch == '=') state = 78; else
return LessLessSym;
break;
case 60:
if (Scan_Ch == '=') state = 79; else
return GreaterGreaterSym;
break;
case 61:
if (Scan_Ch == '+') state = 65; else
if (Scan_Ch == '=') state = 73; else
return PlusSym;
break;
case 62:
if (Scan_Ch == '-') state = 66; else
if (Scan_Ch == '>') state = 68; else
if (Scan_Ch == '=') state = 74; else
return MinusSym;
break;
case 63:
if (Scan_Ch == '=') state = 71; else
return SlashSym;
break;
case 64:
if (Scan_Ch == '=') state = 72; else
return PercentSym;
break;
case 65:
return PlusPlusSym;
case 66:
return MinusMinusSym;
case 67:
return PointSym;
case 68:
return MinusGreaterSym;
case 69:
return ColonColonSym;
case 70:
return StarEqualSym;
case 71:
return SlashEqualSym;
case 72:
return PercentEqualSym;
case 73:
return PlusEqualSym;
case 74:
return MinusEqualSym;
case 75:
return AndEqualSym;
case 76:
return UparrowEqualSym;
case 77:
return BarEqualSym;
case 78:
return LessLessEqualSym;
case 79:
return GreaterGreaterEqualSym;
case 80:
return TildeSym;
default: return No_Sym; /* Scan_NextCh already done */
}
}
}
| [
"[email protected]"
]
| [
[
[
1,
467
]
]
]
|
51437d579a9a22c4c1267b3a49b1e51335351137 | 99d3989754840d95b316a36759097646916a15ea | /tags/2011_09_07_to_baoxin_gpd_0.1/ferrylibs/test/Test_RectificationFromSingleVideo.h | c7f587d9662f708b42f58f340d6e4b32d834414c | []
| no_license | svn2github/ferryzhouprojects | 5d75b3421a9cb8065a2de424c6c45d194aeee09c | 482ef1e6070c75f7b2c230617afe8a8df6936f30 | refs/heads/master | 2021-01-02T09:20:01.983370 | 2011-10-20T11:39:38 | 2011-10-20T11:39:38 | 11,786,263 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,583 | h | #pragma once
#include <iostream>
#include <stdio.h>
#include <fstream>
#include "highgui.h"
#include <ferry/feature_tracking/TwoViewFeatureTracker.h>
#include <ferry/cv_geometry/DLT_FMC.h>
#include <ferry/cv_geometry/RANSAC_FMC.h>
#include <ferry/cv_geometry/Normalized_FMC.h>
#include <ferry/cv_geometry/OpenCV_FMC.h>
#include <ferry/cv_geometry/IOUtil.h>
#include <ferry/cv_geometry/DrawingUtil.h>
#include <ferry/cv_geometry/PointCorrespondences.h>
#include <ferry/cv_geometry/ImageRectifier.h>
#include <ferry/cv_geometry/TwoViewGeometryUtil.h>
#include <ferry/cv_geometry/DrawingUtil.h>
#include <ferry/cv_geometry/IOUtil.h>
#include <ferry/cv_geometry/CrossOpticalAxes_PBIR.h>
using namespace std;
using namespace ferry::cv_geometry;
using namespace ferry::cv_geometry::io_util;
using namespace ferry::feature_tracking;
namespace ferry {
namespace cv_geometry {
namespace test {
class Test_RectificationFromSingleVideo
{
public:
Test_RectificationFromSingleVideo(void) {
}
~Test_RectificationFromSingleVideo(void) {
}
public:
void test() {
char* srcdir = "H:/transfer/Side-Looking 1(straight)12-03-06 2";
char* dstdir = "H:/transfer/Out Side-Looking 1(straight)12-03-06 2";
CornerDetector* pcd = new OpenCVCornerDetector(400, 0.02, 8);
//CornerDetector* pcd = new BlockCornerDetector(100, 10, 0.02, 15);
PointsOutFeatureMatcher* ppofm = new SimpleWindowPOFM(new SimpleWindowSSDFDC(4, 3, 20), 200);
//PointsOutFeatureMatcher* ppofm = new SimpleWindowPOFM(new SimpleWindowSSDFDC(5, 3, 30), 50);
TwoViewFeatureTracker tvft(pcd, ppofm);
char file1[500];
char file2[500];
//char* file1 = "data/olympus/im_134.bmp";
//char* file2 = "data/olympus/im_136.bmp";
int index1 = 5;
int index2 = 7;
sprintf(file1, "%s/im_%04d.bmp", srcdir, index1);
sprintf(file2, "%s/im_%04d.bmp", srcdir, index2);
IplImage* im1 = cvLoadImage(file1, 1);
IplImage* im2 = cvLoadImage(file2, 1);
IplImage* im1_w = cvCloneImage(im1);
IplImage* im2_w = cvCloneImage(im2);
IplImage* mixim = cvCloneImage(im1);
#if 0
shift(im1, im1_w, 5);
#else
//CvRect middleThird = cvRect(0, im1->height/3, im1->width, im1->height/3);
//cvSetImageROI(im1, middleThird);
//cvSetImageROI(im2, middleThird);
vector<CvPoint> x1s, x2s;
tvft.compute(im1, im2, x1s, x2s);
PointCorrespondences pc;
char pc_file[500];
sprintf(pc_file, "%s/mpicked.txt", srcdir);
ifstream pcifs(pc_file);
pcifs>>pc;
pcifs.close();
//x1s = cvPointsFrom32fs(pc.x1s);
//x2s = cvPointsFrom32fs(pc.x2s);
draw_correspondences_image("cos1", im1, x1s, x2s);
draw_correspondences_image("cos2", im1, im2, x1s, x2s);
IplImage* cos1 = create_correspondences_image(im1, x1s, x2s);
char buf[400];
sprintf(buf, "%s/temp/im_%04d_%04d_cos1.bmp", srcdir, index1, index2);
cvSaveImage(buf, cos1);
DLT_FMC dltfmc;
//Normalized_FMC nfmc(&dltfmc);
RANSAC_FMC ransac_fmc(0.01);
Normalized_FMC nfmc(&ransac_fmc);
//OpenCV_FMC nfmc(CV_FM_RANSAC, 1, 0.99);
//OpenCV_FMC nfmc(CV_FM_LMEDS, 1, 0.99);
//FundamentalMatrix fm = dltfmc.compute(x1s, x2s);
FundamentalMatrix fm = nfmc.compute(cvPointsTo32fs(x1s), cvPointsTo32fs(x2s));
cout<<fm.toString()<<endl;
FundamentalMatrixErrorCalculator* pfmec = new PointLine_FMEC();
//FundamentalMatrixErrorCalculator* pfmec = new SimpleMultiply_FMEC();
FundamentalMatrixBatchErrorCalculator fmbec(fm.getF(), pfmec);
double error = fmbec.compute(cvPointsTo32fs(x1s), cvPointsTo32fs(x2s));
cout<<"error: "<<error<<endl;
FundamentalMatrixInlierOutlierModel fmiom(fm.getF(), pfmec, 1.0);
vector<CvPoint2D32f> ix1s, ix2s, ox1s, ox2s;
fmiom.classify(cvPointsTo32fs(x1s), cvPointsTo32fs(x2s), ix1s, ix2s, ox1s, ox2s);
draw_correspondences_image("inliers cos1", im1, cvPointsFrom32fs(ix1s), cvPointsFrom32fs(ix2s));
IplImage* inliers_cos1 = create_correspondences_image(im1, cvPointsFrom32fs(ix1s), cvPointsFrom32fs(ix2s));
sprintf(buf, "%s/temp/im_%04d_%04d_inliers_cos1.bmp", srcdir, index1, index2);
cvSaveImage(buf, inliers_cos1);
CvMat* F = fm.getF();
drawEpipoleLines(im1, im2, F);
cvNamedWindow("im1", 1);
cvNamedWindow("im2", 1);
cvShowImage("im1", im1);
cvShowImage("im2", im2);
sprintf(buf, "%s/temp/im_%04d_F.bmp", srcdir, index1);
cvSaveImage(buf, im1);
sprintf(buf, "%s/temp/im_%04d_F.bmp", srcdir, index2);
cvSaveImage(buf, im2);
CvMat* H1;
CvMat* H2;
TrueStereo_PBIR ts;
ts.compute(F, cvGetSize(im1), ix1s, ix2s, &H1, &H2);
IplImage* im1_H = cvCreateImage(cvGetSize(im1), 8, 3);
IplImage* im2_H = cvCreateImage(cvGetSize(im2), 8, 3);
cvWarpPerspective(im1, im1_H, H1);
cvWarpPerspective(im2, im2_H, H2);
cvNamedWindow("im1 H", 1);
cvShowImage("im1 H", im1_H);
cvNamedWindow("im2 H", 1);
cvShowImage("im2 H", im2_H);
sprintf(buf, "%s/temp/im_%04d_rectified.bmp", srcdir, index1);
cvSaveImage(buf, im1_H);
sprintf(buf, "%s/temp/im_%04d_rectified.bmp", srcdir, index2);
cvSaveImage(buf, im2_H);
im1_w = im1_H;
im2_w = im2_H;
#endif
mix(im1_w, im2_w, mixim);
cvNamedWindow("mix", 1);
cvShowImage("mix", mixim);
}
void shift(IplImage* im, IplImage* im_w, double transv) {
double mh[] = {1, 0, transv, 0, 1, 0, 0, 0, 1};
CvMat TH = cvMat(3, 3, CV_64FC1, mh);
cvWarpPerspective(im, im_w, &TH);
}
void mix(IplImage* im1, IplImage* im2, IplImage* mixim) {
cvAddWeighted(im1, 0.5, im2, 0.5, 0, mixim);
}
};
}
}
} | [
"ferryzhou@b6adba56-547e-11de-b413-c5e99dc0a8e2"
]
| [
[
[
1,
184
]
]
]
|
cc54f97e2db7a56a8a7bbb086f626f2df64190a5 | f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0 | /GameSDK/SLB/include/SLB/Type.hpp | d81d95276bd60227621de0d0e32d5c0c7be922d3 | []
| 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 | 32,172 | hpp | /*
SLB - Simple Lua Binder
Copyright (C) 2007 Jose L. Hidalgo Valiño (PpluX)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Jose L. Hidalgo (www.pplux.com)
[email protected]
*/
#ifndef __SLB_TYPE__
#define __SLB_TYPE__
#include "lua.hpp"
#include "Debug.hpp"
#include "SPP.hpp"
#include "Manager.hpp"
#include "ClassInfo.hpp"
#include "LuaObject.h"
#ifndef _CRT_SECURE_NO_DEPRECATE
#define _CRT_SECURE_NO_DEPRECATE
#endif
namespace SLB {
namespace Private
{
// Default implementation
template<class T>
struct Type
{
static ClassInfo *getClass(lua_State *L)
{
SLB_DEBUG_CALL;
SLB_DEBUG(10,"getClass '%s'", typeid(T).name());
ClassInfo *c = SLB::Manager::getInstance().getClass(typeid(T));
if (c == 0) luaL_error(L, "Unknown class %s", typeid(T).name());
return c;
}
static void push(lua_State *L,const T &obj)
{
SLB_DEBUG_CALL;
SLB_DEBUG(8,"Push<T=%s>(L=%p, obj =%p)", typeid(T).name(), L, &obj);
getClass(L)->push_copy(L, (void*) &obj);
}
static T get(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
SLB_DEBUG(8,"Get<T=%s>(L=%p, pos = %i)", typeid(T).name(), L, pos);
T* obj = reinterpret_cast<T*>( getClass(L)->get_ptr(L, pos) );
SLB_DEBUG(9,"obj = %p", obj);
return *obj;
}
static bool check(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
SLB_DEBUG(10,"check '%s' at pos %d", typeid(T).name(), pos);
return getClass(L)->check(L, pos);
}
};
template<class T>
struct Type<T*>
{
static ClassInfo *getClass(lua_State *L)
{
SLB_DEBUG_CALL;
SLB_DEBUG(10,"getClass '%s'", typeid(T).name());
ClassInfo *c = SLB::Manager::getInstance().getClass(typeid(T));
if (c == 0) luaL_error(L, "Unknown class %s", typeid(T).name());
return c;
}
static void push(lua_State *L, T *obj, bool fromConstructor = false)
{
SLB_DEBUG_CALL;
SLB_DEBUG(10,"push '%s' of %p (from constructor=%s)",
typeid(T).name(),
obj,
fromConstructor? "true" : "false" );
if (obj == 0)
{
lua_pushnil(L);
return;
}
const std::type_info &t_T = typeid(T);
const std::type_info &t_obj = typeid(*obj);
assert("Invalid typeinfo!!! (type)" && (&t_T) );
assert("Invalid typeinfo!!! (object)" && (&t_obj) );
if (t_obj != t_T)
{
// check if the internal class exists...
ClassInfo *c = SLB::Manager::getInstance().getClass(t_obj);
if ( c )
{
SLB_DEBUG(8,"Push<T*=%s> with conversion from "
"T(%p)->T(%p) (L=%p, obj =%p)",
c->getName().c_str(), t_obj.name(), t_T.name(),L, obj);
// covert the object to the internal class...
void *real_obj = SLB::Manager::getInstance().convert( &t_T, &t_obj, obj );
c->push_ptr(L, real_obj, fromConstructor);
return;
}
}
// use this class...
getClass(L)->push_ptr(L, (void*) obj, fromConstructor);
}
static T* get(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
SLB_DEBUG(10,"get '%s' at pos %d", typeid(T).name(), pos);
return reinterpret_cast<T*>( getClass(L)->get_ptr(L, pos) );
}
static bool check(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
SLB_DEBUG(10,"check '%s' at pos %d", typeid(T).name(), pos);
return getClass(L)->check(L, pos);
}
};
template<class T>
struct Type<const T*>
{
static ClassInfo *getClass(lua_State *L)
{
SLB_DEBUG_CALL;
SLB_DEBUG(10,"getClass '%s'", typeid(T).name());
ClassInfo *c = SLB::Manager::getInstance().getClass(typeid(T));
if (c == 0) luaL_error(L, "Unknown class %s", typeid(T).name());
return c;
}
static void push(lua_State *L,const T *obj)
{
SLB_DEBUG_CALL;
SLB_DEBUG(10,"push '%s' of %p", typeid(T).name(), obj);
if (obj == 0)
{
lua_pushnil(L);
return;
}
if (typeid(*obj) != typeid(T))
{
// check if the internal class exists...
ClassInfo *c = SLB::Manager::getInstance().getClass(typeid(*obj));
if ( c )
{
SLB_DEBUG(8,"Push<const T*=%s> with conversion from "
"T(%p)->T(%p) (L=%p, obj =%p)",
c->getName().c_str(), typeid(*obj).name(), typeid(T).name(),L, obj);
// covert the object to the internal class...
const void *real_obj = SLB::Manager::getInstance().convert( &typeid(T), &typeid(*obj), obj );
c->push_const_ptr(L, real_obj);
return;
}
}
getClass(L)->push_const_ptr(L, (const void*) obj);
}
static const T* get(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
SLB_DEBUG(10,"get '%s' at pos %d", typeid(T).name(), pos);
return reinterpret_cast<const T*>( getClass(L)->get_const_ptr(L, pos) );
}
static bool check(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
SLB_DEBUG(10,"check '%s' at pos %d", typeid(T).name(), pos);
return getClass(L)->check(L, pos);
}
};
template<class T>
struct Type<const T&>
{
static void push(lua_State *L,const T &obj)
{
SLB_DEBUG_CALL;
SLB_DEBUG(10,"push '%s' of %p(const ref)", typeid(T).name(), &obj);
Type<const T*>::push(L, &obj);
}
static const T& get(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
SLB_DEBUG(10,"get '%s' at pos %d", typeid(T).name(), pos);
const T* obj = Type<const T*>::get(L,pos);
//TODO: remove the typeid(T).getName() and use classInfo :)
if (obj == 0L) luaL_error(L, "Can not get a reference of class %s", typeid(T).name());
return *(obj);
}
static bool check(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
SLB_DEBUG(10,"check '%s' at pos %d", typeid(T).name(), pos);
return Type<const T*>::check(L,pos);
}
};
template<class T>
struct Type<T&>
{
static ClassInfo *getClass(lua_State *L)
{
SLB_DEBUG_CALL;
SLB_DEBUG(10,"getClass '%s'", typeid(T).name());
ClassInfo *c = SLB::Manager::getInstance().getClass(typeid(T));
if (c == 0) luaL_error(L, "Unknown class %s", typeid(T).name());
return c;
}
static void push(lua_State *L,T &obj)
{
SLB_DEBUG_CALL;
SLB_DEBUG(10,"push '%s' of %p (reference)", typeid(T).name(), &obj);
getClass(L)->push_ref(L, (void*) &obj);
}
static T& get(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
SLB_DEBUG(10,"get '%s' at pos %d", typeid(T).name(), pos);
return *(Type<T*>::get(L,pos));
}
static bool check(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
SLB_DEBUG(10,"check '%s' at pos %d", typeid(T).name(), pos);
return Type<T*>::check(L,pos);
}
};
//--- Specializations ---------------------------------------------------
template<>
struct Type<void*>
{
static void push(lua_State *L,void* obj)
{
SLB_DEBUG_CALL;
if (obj == 0) lua_pushnil(L);
else
{
SLB_DEBUG(8,"Push<void*> (L=%p, obj =%p)",L, obj);
lua_pushlightuserdata(L, obj);
}
}
static void *get(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
SLB_DEBUG(8,"Get<void*> (L=%p, pos=%i ) =%p)",L, pos, lua_touserdata(L,pos));
if (check(L,pos)) return lua_touserdata(L,pos);
//TODO: Check here if is an userdata and convert it to void
return 0;
}
static bool check(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
return (lua_islightuserdata(L,pos) != 0);
}
};
template< class T >
struct TypeImpl_Integer
{
static void push(lua_State *L, T v)
{
lua_pushinteger(L,v);
}
static T get(lua_State *L, int p)
{
T v = (T) lua_tointeger(L,p);
return v;
}
static bool check(lua_State *L, int pos)
{
return (lua_isnumber(L,pos) != 0);
}
};
template< class T >
struct TypeImpl_Integer< T& >
{
static void push(lua_State *L, T& v)
{
lua_pushinteger(L,v);
}
static T get(lua_State *L, int p)
{
T v = (T) lua_tointeger(L,p);
return v;
}
static bool check(lua_State *L, int pos)
{
return (lua_isnumber(L,pos) != 0);
}
};
template< class T >
struct TypeImpl_Number
{
static void push(lua_State *L, T v)
{
lua_pushnumber(L,v);
}
static T get(lua_State *L, int p)
{
T v = (T)lua_tonumber(L,p);
return v;
}
static bool check(lua_State *L, int pos)
{
return (lua_isnumber(L,pos) != 0);
}
};
template< class T >
struct TypeImpl_Number< T& >
{
static void push(lua_State *L, T& v)
{
lua_pushnumber(L,v);
}
static T get(lua_State *L, int p)
{
T v = (T) lua_tonumber(L,p);
return v;
}
static bool check(lua_State *L, int pos)
{
return (lua_isnumber(L,pos) != 0);
}
};
#define DEFINE_TYPE_INTEGER( _type ) template<> struct Type< _type > : public TypeImpl_Integer< _type >{}
#define DEFINE_TYPE_NUMBER( _type ) template<> struct Type< _type > : public TypeImpl_Number< _type >{}
#define DEFINE_INTEGER( _type )\
DEFINE_TYPE_INTEGER( _type );\
DEFINE_TYPE_INTEGER( const _type );\
DEFINE_TYPE_INTEGER( _type& );\
DEFINE_TYPE_INTEGER( const _type& );\
DEFINE_TYPE_INTEGER( _type* );\
DEFINE_TYPE_INTEGER( const _type* );\
#define DEFINE_NUMBER( _type )\
DEFINE_TYPE_NUMBER( _type );\
DEFINE_TYPE_NUMBER( const _type );\
DEFINE_TYPE_NUMBER( _type& );\
DEFINE_TYPE_NUMBER( const _type& );\
#define DEFINE_UNSIGNED( _type )\
DEFINE_TYPE_INTEGER( unsigned _type );\
DEFINE_TYPE_INTEGER( const unsigned _type );\
DEFINE_TYPE_INTEGER( unsigned _type& );\
DEFINE_TYPE_INTEGER( const unsigned _type& );\
//////////////////////////////////////////////////////////////////////////
// define type
DEFINE_TYPE_INTEGER( char );
DEFINE_TYPE_INTEGER( unsigned char );
DEFINE_TYPE_INTEGER( char& );
DEFINE_TYPE_INTEGER( unsigned char& );
DEFINE_INTEGER( short );
DEFINE_INTEGER( int );
DEFINE_INTEGER( long );
DEFINE_INTEGER( __int64 );
//#if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300
// typedef __w64 unsigned int slb_uint_ptr;
// typedef __w64 unsigned long slb_long_ptr;
// DEFINE_INTEGER( slb_uint_ptr );
// DEFINE_INTEGER( slb_long_ptr );
//#else
// typedef unsigned int slb_uint_ptr;
// typedef unsigned long slb_long_ptr;
// DEFINE_INTEGER( slb_uint_ptr );
// DEFINE_INTEGER( slb_long_ptr );
//#endif
DEFINE_UNSIGNED( short );
DEFINE_UNSIGNED( int );
DEFINE_UNSIGNED( long );
DEFINE_UNSIGNED( __int64 );
//DEFINE_UNSIGNED( __w64 int );
//DEFINE_UNSIGNED( __w64 long );
DEFINE_NUMBER( float );
DEFINE_NUMBER( double );
// type define over
//////////////////////////////////////////////////////////////////////////
//// Type specialization for <int>
//template<>
//struct Type<int>
//{
// static void push(lua_State *L, int v)
// {
// SLB_DEBUG_CALL;
// SLB_DEBUG(6, "Push integer = %d",v);
// lua_pushinteger(L,v);
// }
// static int get(lua_State *L, int p)
// {
// SLB_DEBUG_CALL;
// int v = (int) lua_tointeger(L,p);
// SLB_DEBUG(6,"Get integer (pos %d) = %d",p,v);
// return v;
// }
// static bool check(lua_State *L, int pos)
// {
// SLB_DEBUG_CALL;
// return (lua_isnumber(L,pos) != 0);
// }
//};
//template<>
//struct Type< const int >
//{
// static void push(lua_State *L, const int v)
// {
// SLB_DEBUG_CALL;
// SLB_DEBUG(6, "Push integer = %d",v);
// lua_pushinteger(L,v);
// }
// static int get(lua_State *L, int p)
// {
// SLB_DEBUG_CALL;
// int v = (int) lua_tointeger(L,p);
// SLB_DEBUG(6,"Get integer (pos %d) = %d",p,v);
// return v;
// }
// static bool check(lua_State *L, int pos)
// {
// SLB_DEBUG_CALL;
// return (lua_isnumber(L,pos) != 0);
// }
//};
//template<>
//struct Type< int& >
//{
// static void push(lua_State *L, int& v)
// {
// SLB_DEBUG_CALL;
// SLB_DEBUG(6, "Push integer = %d",v);
// lua_pushinteger(L,v);
// }
// static int get(lua_State *L, int p)
// {
// SLB_DEBUG_CALL;
// int v = (int) lua_tointeger(L,p);
// SLB_DEBUG(6,"Get integer (pos %d) = %d",p,v);
// return v;
// }
// static bool check(lua_State *L, int pos)
// {
// SLB_DEBUG_CALL;
// return (lua_isnumber(L,pos) != 0);
// }
//};
//template<>
//struct Type<const int&>
//{
// static void push(lua_State *L, const int &v)
// {
// SLB_DEBUG_CALL;
// Type<int>::push(L,v);
// }
// static int get(lua_State *L, int p)
// {
// SLB_DEBUG_CALL;
// return Type<int>::get(L,p);
// }
// static bool check(lua_State *L, int pos)
// {
// SLB_DEBUG_CALL;
// return Type<int>::check(L,pos);
// }
//};
//// Type specialization for <unsigned int>
//template<>
//struct Type<unsigned int>
//{
// static void push(lua_State *L, unsigned int v)
// {
// SLB_DEBUG_CALL;
// SLB_DEBUG(6, "Push unsigned integer = %d",v);
// lua_pushinteger(L,v);
// }
// static unsigned int get(lua_State *L, int p)
// {
// SLB_DEBUG_CALL;
// unsigned int v = static_cast<unsigned int>(lua_tointeger(L,p));
// SLB_DEBUG(6,"Get unsigned integer (pos %d) = %d",p,v);
// return v;
// }
// static bool check(lua_State *L, int pos)
// {
// SLB_DEBUG_CALL;
// return (lua_isnumber(L,pos) != 0);
// }
//};
//template<>
//struct Type<const unsigned int&>
//{
// static void push(lua_State *L, const unsigned int &v)
// {
// SLB_DEBUG_CALL;
// Type<unsigned int>::push(L,v);
// }
// static unsigned int get(lua_State *L, int p)
// {
// SLB_DEBUG_CALL;
// return Type<unsigned int>::get(L,p);
// }
// static bool check(lua_State *L, int pos)
// {
// SLB_DEBUG_CALL;
// return Type<unsigned int>::check(L,pos);
// }
//};
//template<>
//struct Type<long>
//{
// static void push(lua_State *L, long v)
// {
// SLB_DEBUG_CALL;
// SLB_DEBUG(6, "Push long = %ld",v);
// lua_pushinteger(L,v);
// }
// static long get(lua_State *L, int p)
// {
// SLB_DEBUG_CALL;
// long v = (long) lua_tointeger(L,p);
// SLB_DEBUG(6,"Get long (pos %d) = %ld",p,v);
// return v;
// }
// static bool check(lua_State *L, int pos)
// {
// SLB_DEBUG_CALL;
// return (lua_isnumber(L,pos) != 0);
// }
//};
//template<>
//struct Type<const long&>
//{
// static void push(lua_State *L, long v)
// {
// SLB_DEBUG_CALL;
// Type< long >::push( L, v );
// }
// static long get(lua_State *L, int p)
// {
// SLB_DEBUG_CALL;
// return Type< long >::get( L, p );
// }
// static bool check(lua_State *L, int pos)
// {
// SLB_DEBUG_CALL;
// return Type< long >::check( L, pos );
// }
//};
///* unsigned long == unsigned int */
//template<>
//struct Type<unsigned long>
//{
// static void push(lua_State *L, unsigned long v)
// {
// SLB_DEBUG_CALL;
// SLB_DEBUG(6, "Push unsigned long = %lu",v);
// lua_pushnumber(L,v);
// }
// static unsigned long get(lua_State *L, int p)
// {
// SLB_DEBUG_CALL;
// unsigned long v = (unsigned long) lua_tonumber(L,p);
// SLB_DEBUG(6,"Get unsigned long (pos %d) = %lu",p,v);
// return v;
// }
// static bool check(lua_State *L, int pos)
// {
// SLB_DEBUG_CALL;
// return (lua_isnumber(L,pos) != 0);
// }
//};
//template<>
//struct Type<const unsigned long&>
//{
// static void push(lua_State *L, const unsigned long &v)
// {
// SLB_DEBUG_CALL;
// Type<unsigned long>::push(L,v);
// }
// static unsigned long get(lua_State *L, int p)
// {
// SLB_DEBUG_CALL;
// return Type<unsigned long>::get(L,p);
// }
// static bool check(lua_State *L, int pos)
// {
// SLB_DEBUG_CALL;
// return Type<unsigned long>::check(L,pos);
// }
//};
//template<>
//struct Type<unsigned long long>
//{
// static void push(lua_State *L, unsigned long long v)
// {
// SLB_DEBUG_CALL;
// SLB_DEBUG(6, "Push unsigned long long = %llu",v);
// lua_pushnumber(L,(lua_Number)v);
// }
// static unsigned long long get(lua_State *L, int p)
// {
// SLB_DEBUG_CALL;
// unsigned long long v = (unsigned long long) lua_tonumber(L,p);
// SLB_DEBUG(6,"Get unsigned long long (pos %d) = %llu",p,v);
// return v;
// }
// static bool check(lua_State *L, int pos)
// {
// SLB_DEBUG_CALL;
// return (lua_isnumber(L,pos) != 0);
// }
//};
//template<>
//struct Type<const unsigned long long&>
//{
// static void push(lua_State *L, const unsigned long long &v)
// {
// SLB_DEBUG_CALL;
// Type<unsigned long long>::push(L,v);
// }
// static unsigned long long get(lua_State *L, int p)
// {
// SLB_DEBUG_CALL;
// return Type<unsigned long long>::get(L,p);
// }
// static bool check(lua_State *L, int pos)
// {
// SLB_DEBUG_CALL;
// return Type<unsigned long long>::check(L,pos);
// }
//};
//// Type specialization for <double>
//template<>
//struct Type<double>
//{
// static void push(lua_State *L, double v)
// {
// SLB_DEBUG_CALL;
// SLB_DEBUG(6, "Push double = %f",v);
// lua_pushnumber(L,v);
// }
// static double get(lua_State *L, int p)
// {
// SLB_DEBUG_CALL;
// double v = (double) lua_tonumber(L,p);
// SLB_DEBUG(6,"Get double (pos %d) = %f",p,v);
// return v;
// }
// static bool check(lua_State *L, int pos)
// {
// SLB_DEBUG_CALL;
// return (lua_isnumber(L,pos) != 0);
// }
//};
//template<>
//struct Type<const double&>
//{
// static void push(lua_State *L, const double &v)
// {
// SLB_DEBUG_CALL;
// Type<double>::push(L,v);
// }
// static double get(lua_State *L, int p)
// {
// SLB_DEBUG_CALL;
// return Type<double>::get(L,p);
// }
// static bool check(lua_State *L, int pos)
// {
// SLB_DEBUG_CALL;
// return Type<double>::check(L,pos);
// }
//};
//// Type specialization for <float>
//template<>
//struct Type<float>
//{
// static void push(lua_State *L, float v)
// {
// SLB_DEBUG_CALL;
// SLB_DEBUG(6, "Push float = %f",v);
// lua_pushnumber(L,v);
// }
// static float get(lua_State *L, int p)
// {
// SLB_DEBUG_CALL;
// float v = (float) lua_tonumber(L,p);
// SLB_DEBUG(6,"Get float (pos %d) = %f",p,v);
// return v;
// }
// static bool check(lua_State *L, int pos)
// {
// SLB_DEBUG_CALL;
// return (lua_isnumber(L,pos) != 0);
// }
//};
//template<>
//struct Type<const float&>
//{
// static void push(lua_State *L, const float &v)
// {
// SLB_DEBUG_CALL;
// Type<float>::push(L,v);
// }
// static float get(lua_State *L, int p)
// {
// SLB_DEBUG_CALL;
// return Type<float>::get(L,p);
// }
// static bool check(lua_State *L, int pos)
// {
// SLB_DEBUG_CALL;
// return Type<float>::check(L,pos);
// }
//};
// Type specialization for <bool>
template<>
struct Type<bool>
{
static void push(lua_State *L, bool v)
{
SLB_DEBUG_CALL;
SLB_DEBUG(6, "Push bool = %d",(int)v);
lua_pushboolean(L,v);
}
static bool get(lua_State *L, int p)
{
SLB_DEBUG_CALL;
bool v = (lua_toboolean(L,p) != 0);
SLB_DEBUG(6,"Get bool (pos %d) = %d",p,v);
return v;
}
static bool check(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
return lua_isboolean(L,pos);
}
};
template<>
struct Type<bool&>
{
static void push(lua_State *L, bool v)
{
SLB_DEBUG_CALL;
SLB_DEBUG(6, "Push bool = %d",(int)v);
lua_pushboolean(L,v);
}
static bool get(lua_State *L, int p)
{
SLB_DEBUG_CALL;
bool v = (lua_toboolean(L,p) != 0);
SLB_DEBUG(6,"Get bool (pos %d) = %d",p,v);
return v;
}
static bool check(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
return lua_isboolean(L,pos);
}
};
template<>
struct Type< const bool& >
{
static void push(lua_State *L, bool v)
{
SLB_DEBUG_CALL;
SLB_DEBUG(6, "Push bool = %d",(int)v);
lua_pushboolean(L,v);
}
static bool get(lua_State *L, int p)
{
SLB_DEBUG_CALL;
bool v = (lua_toboolean(L,p) != 0);
SLB_DEBUG(6,"Get bool (pos %d) = %d",p,v);
return v;
}
static bool check(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
return lua_isboolean(L,pos);
}
};
template<>
struct Type<std::string>
{
static void push(lua_State *L, const std::string &v)
{
SLB_DEBUG_CALL;
SLB_DEBUG(6, "Push const std::string& = %s",v.c_str());
lua_pushstring(L, v.c_str());
}
static std::string get(lua_State *L, int p)
{
SLB_DEBUG_CALL;
const char* v = (const char*) lua_tostring(L,p);
if( v == NULL ) luaL_error(L, "request string.");
SLB_DEBUG(6,"Get std::string (pos %d) = %s",p,v);
return v;
}
static bool check(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
return (lua_isstring(L,pos) != 0);
}
};
template<>
struct Type<std::string&>
{
static void push(lua_State *L, const std::string &v)
{
SLB_DEBUG_CALL;
SLB_DEBUG(6, "Push const std::string& = %s",v.c_str());
lua_pushstring(L, v.c_str());
}
static std::string get(lua_State *L, int p)
{
SLB_DEBUG_CALL;
const char* v = (const char*) lua_tostring(L,p);
if( v == NULL ) luaL_error(L, "request string.");
SLB_DEBUG(6,"Get std::string (pos %d) = %s",p,v);
return v;
}
static bool check(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
return (lua_isstring(L,pos) != 0);
}
};
template<>
struct Type<const std::string &>
{
static void push(lua_State *L, const std::string &v)
{
SLB_DEBUG_CALL;
SLB_DEBUG(6, "Push const std::string& = %s",v.c_str());
lua_pushstring(L, v.c_str());
}
// let the compiler do the conversion...
static const std::string get(lua_State *L, int p)
{
SLB_DEBUG_CALL;
const char* v = (const char*) lua_tostring(L,p);
if( v == NULL ) luaL_error(L, "request string.");
SLB_DEBUG(6,"Get std::string (pos %d) = %s",p,v);
return std::string(v);
}
static bool check(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
return (lua_isstring(L,pos) != 0);
}
};
template<>
struct Type<std::wstring>
{
static void push(lua_State *L, const std::wstring &v)
{
SLB_DEBUG_CALL;
SLB_DEBUG(6, "Push const std::string& = %s",v.c_str());
char* lpa = (char*)_alloca( v.length() + 1 );
size_t convert = 0;
size_t ret = wcstombs_s( &convert, lpa, v.length() + 1, v.c_str(), v.length() );
if( ret != 0 )
{
lua_pushnil(L);
}
else
{
lua_pushstring(L, lpa );
}
}
static std::wstring get(lua_State *L, int p)
{
SLB_DEBUG_CALL;
const char* v = (const char*) lua_tostring(L,p);
if( v == NULL ) luaL_error(L, "request string.");
SLB_DEBUG(6,"Get std::string (pos %d) = %s",p,v);
int chars = (int)strlen( v ) + 1;
wchar_t* lpw = (wchar_t*)_alloca( chars*sizeof(wchar_t) );
size_t convert = 0;
size_t ret = mbstowcs_s( &convert, lpw, chars, v, chars );
if( ret != 0 ) return L"";
return lpw;
}
static bool check(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
return (lua_isstring(L,pos) != 0);
}
};
template<>
struct Type<std::wstring&>
{
static void push(lua_State *L, const std::wstring &v)
{
SLB_DEBUG_CALL;
SLB_DEBUG(6, "Push const std::string& = %s",v.c_str());
char* lpa = (char*)_alloca( v.length() + 1 );
size_t convert = 0;
size_t ret = wcstombs_s( &convert, lpa, v.length() + 1, v.c_str(), v.length() );
if( ret != 0 )
{
lua_pushnil(L);
}
else
{
lua_pushstring(L, lpa );
}
}
static std::wstring get(lua_State *L, int p)
{
SLB_DEBUG_CALL;
const char* v = (const char*) lua_tostring(L,p);
if( v == NULL ) luaL_error(L, "request string.");
SLB_DEBUG(6,"Get std::string (pos %d) = %s",p,v);
int chars = (int)strlen( v ) + 1;
wchar_t* lpw = (wchar_t*)_alloca( chars*sizeof(wchar_t) );
size_t convert = 0;
size_t ret = mbstowcs_s( &convert, lpw, chars, v, chars );
if( ret != 0 ) return L"";
return lpw;
}
static bool check(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
return (lua_isstring(L,pos) != 0);
}
};
template<>
struct Type<const std::wstring &>
{
static void push(lua_State *L, const std::wstring &v)
{
SLB_DEBUG_CALL;
SLB_DEBUG(6, "Push const std::wstring& = %s",v.c_str());
char* lpa = (char*)_alloca( v.length() + 1 );
size_t convert = 0;
size_t ret = wcstombs_s( &convert, lpa, v.length() + 1, v.c_str(), v.length() );
if( ret != 0 )
{
lua_pushnil(L);
}
else
{
lua_pushstring(L, lpa );
}
}
// let the compiler do the conversion...
static const std::wstring get(lua_State *L, int p)
{
SLB_DEBUG_CALL;
const char* v = (const char*) lua_tostring(L,p);
if( v == NULL ) luaL_error(L, "request string.");
SLB_DEBUG(6,"Get std::wstring (pos %d) = %s",p,v);
int chars = (int)strlen( v ) + 1;
wchar_t* lpw = (wchar_t*)_alloca( chars*sizeof(wchar_t) );
size_t convert = 0;
size_t ret = mbstowcs_s( &convert, lpw, chars, v, chars );
if( ret != 0 ) return L"";
return lpw;
}
static bool check(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
return (lua_isstring(L,pos) != 0);
}
};
// Type specialization for <const char*>
template<>
struct Type<char*>
{
static void push(lua_State *L, char* v)
{
SLB_DEBUG_CALL;
SLB_DEBUG(6, "Push char* = %s",v);
lua_pushstring(L,v);
}
static const char* get(lua_State *L, int p)
{
SLB_DEBUG_CALL;
const char* v = (const char*) lua_tostring(L,p);
SLB_DEBUG(6,"Get const char* (pos %d) = %s",p,v);
return v;
}
static bool check(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
return (lua_isstring(L,pos) != 0);
}
};
// Type specialization for <const char*>
template<>
struct Type<const char*>
{
static void push(lua_State *L, const char* v)
{
SLB_DEBUG_CALL;
SLB_DEBUG(6, "Push const char* = %s",v);
lua_pushstring(L,v);
}
static const char* get(lua_State *L, int p)
{
SLB_DEBUG_CALL;
const char* v = (const char*) lua_tostring(L,p);
SLB_DEBUG(6,"Get const char* (pos %d) = %s",p,v);
return v;
}
static bool check(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
return (lua_isstring(L,pos) != 0);
}
};
template<>
struct Type<const unsigned char*>
{
static void push(lua_State *L, const unsigned char* v)
{
SLB_DEBUG_CALL;
SLB_DEBUG(6, "Push const unsigned char* = %s",v);
lua_pushstring(L,(const char*)v);
}
static const unsigned char* get(lua_State *L, int p)
{
SLB_DEBUG_CALL;
const unsigned char* v = (const unsigned char*) lua_tostring(L,p);
SLB_DEBUG(6,"Get const unsigned char* (pos %d) = %s",p,v);
return v;
}
static bool check(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
return (lua_isstring(L,pos) != 0);
}
};
// Type specialization for <const wchar_t*>
template<>
struct Type<wchar_t*>
{
static void push(lua_State *L, wchar_t* v)
{
SLB_DEBUG_CALL;
SLB_DEBUG(6, "Push char* = %s",v);
size_t s = wcslen(v) + 1 ;
lua_pushlstring(L,(const char*)v,s*sizeof(wchar_t));
}
static const wchar_t* get(lua_State *L, int p)
{
SLB_DEBUG_CALL;
const wchar_t* v = (const wchar_t*) lua_tolstring(L,p,NULL);
SLB_DEBUG(6,"Get const char* (pos %d) = %s",p,v);
return v;
}
static bool check(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
return (lua_isstring(L,pos) != 0);
}
};
// Type specialization for <const char*>
template<>
struct Type<const wchar_t*>
{
static void push(lua_State *L, const wchar_t* v)
{
SLB_DEBUG_CALL;
SLB_DEBUG(6, "Push const char* = %s",v);
size_t s = wcslen(v) + 1 ;
lua_pushlstring(L,(const char*)v,s*sizeof(wchar_t));
}
static const wchar_t* get(lua_State *L, int p)
{
SLB_DEBUG_CALL;
const wchar_t* v = (const wchar_t*) lua_tolstring(L,p,NULL);
SLB_DEBUG(6,"Get const char* (pos %d) = %s",p,v);
return v;
}
static bool check(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
return (lua_isstring(L,pos) != 0);
}
};
template<>
struct Type< LuaObject >
{
static void push(lua_State *L,const LuaObject &obj)
{
SLB_DEBUG_CALL;
SLB_DEBUG(8,"Push<T=%s>(L=%p, obj =%p)", typeid(T).name(), L, &obj);
obj.push();
}
static LuaObject get(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
SLB_DEBUG(8,"Get<T=%s>(L=%p, pos = %i)", typeid(T).name(), L, pos);
lua_pushvalue( L, pos );
int ref = luaL_ref( L, LUA_REGISTRYINDEX );
int type = lua_type( L, pos );
return LuaObject( L, ref );
}
static bool check(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
return (lua_istable( L, pos ) != 0);
}
};
template<>
struct Type< LuaObject& >
{
static void push(lua_State *L,const LuaObject &obj)
{
SLB_DEBUG_CALL;
SLB_DEBUG(8,"Push<T=%s>(L=%p, obj =%p)", typeid(T).name(), L, &obj);
obj.push();
}
static LuaObject get(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
SLB_DEBUG(8,"Get<T=%s>(L=%p, pos = %i)", typeid(T).name(), L, pos);
int type = lua_type( L, pos );
lua_pushvalue(L,pos);
int ref = luaL_ref( L, LUA_REGISTRYINDEX );
return LuaObject( L, ref );
}
static bool check(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
return true;
}
};
template<>
struct Type< const LuaObject& >
{
static void push(lua_State *L,const LuaObject &obj)
{
SLB_DEBUG_CALL;
SLB_DEBUG(8,"Push<T=%s>(L=%p, obj =%p)", typeid(T).name(), L, &obj);
obj.push();
}
static LuaObject get(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
SLB_DEBUG(8,"Get<T=%s>(L=%p, pos = %i)", typeid(T).name(), L, pos);
lua_pushvalue( L, pos );
int ref = luaL_ref( L, LUA_REGISTRYINDEX );
return LuaObject( L, ref );
}
static bool check(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
return (lua_istable( L, pos ) != 0);
}
};
template<>
struct Type< LuaObject* >
{
static void push(lua_State *L,const LuaObject *obj)
{
SLB_DEBUG_CALL;
SLB_DEBUG(8,"Push<T=%s>(L=%p, obj =%p)", typeid(T).name(), L, obj);
obj->push();
}
static LuaObject get(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
SLB_DEBUG(8,"Get<T=%s>(L=%p, pos = %i)", typeid(T).name(), L, pos);
lua_pushvalue( L, pos );
int ref = luaL_ref( L, LUA_REGISTRYINDEX );
return LuaObject( L, ref );
}
static bool check(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
return (lua_istable( L, pos ) != 0);
}
};
template<>
struct Type< const LuaObject* >
{
static void push(lua_State *L,const LuaObject *obj)
{
SLB_DEBUG_CALL;
SLB_DEBUG(8,"Push<T=%s>(L=%p, obj =%p)", typeid(T).name(), L, obj);
obj->push();
}
static LuaObject get(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
SLB_DEBUG(8,"Get<T=%s>(L=%p, pos = %i)", typeid(T).name(), L, pos);
int ref = luaL_ref( L, pos );
return LuaObject( L, ref );
}
static bool check(lua_State *L, int pos)
{
SLB_DEBUG_CALL;
return (lua_istable( L, pos ) != 0);
}
};
}
} // end of SLB::Private
#endif
| [
"albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c"
]
| [
[
[
1,
1363
]
]
]
|
5118430f8f78548f41b82f8c79a3af39a30104d4 | 38926bfe477f933a307f51376dd3c356e7893ffc | /Source/GameDLL/ItemView.cpp | 74f257bf5348481241851d6001b3189a4babc0bc | []
| no_license | richmondx/dead6 | b0e9dd94a0ebb297c0c6e9c4f24c6482ef4d5161 | 955f76f35d94ed5f991871407f3d3ad83f06a530 | refs/heads/master | 2021-12-05T14:32:01.782047 | 2008-01-01T13:13:39 | 2008-01-01T13:13:39 | null | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 16,166 | cpp | /*************************************************************************
Crytek Source File.
Copyright (C), Crytek Studios, 2001-2004.
-------------------------------------------------------------------------
$Id$
$DateTime$
-------------------------------------------------------------------------
History:
- 30:8:2005 12:52 : Created by Márcio Martins
*************************************************************************/
#include "StdAfx.h"
#include "Item.h"
#include "Actor.h"
#include "Player.h"
#include "GameCVars.h"
#include <IViewSystem.h>
//------------------------------------------------------------------------
void CItem::UpdateFPView(float frameTime)
{
if (!m_stats.selected)
return;
CheckViewChange();
if (!m_stats.fp && !m_stats.mounted)
return;
if (GetGameObject()->GetAspectProfile(eEA_Physics)!=eIPhys_NotPhysicalized)
return;
if (m_camerastats.animating)
{
if (m_camerastats.position)
m_camerastats.pos=GetSlotHelperPos(eIGS_FirstPerson, m_camerastats.helper.c_str(), false, true);
if (m_camerastats.rotation)
m_camerastats.rot=Quat(GetSlotHelperRotation(eIGS_FirstPerson, m_camerastats.helper.c_str(), false, true)); //*Quat::CreateRotationZ(-gf_PI);
}
if (!m_stats.mounted)
{
UpdateFPPosition(frameTime);
UpdateFPCharacter(frameTime);
}
if (IItem *pSlave = GetDualWieldSlave())
pSlave->UpdateFPView(frameTime);
//UpdateMounted() is only updated in CItem::Update()
//if (m_stats.mounted && GetOwnerActor() && GetOwnerActor()->IsClient())
//UpdateMounted(frameTime);
}
//------------------------------------------------------------------------
void CItem::UpdateFPPosition(float frameTime)
{
CActor* pActor = GetOwnerActor();
if (!pActor)
return;
SPlayerStats *pStats = static_cast<SPlayerStats *>(pActor->GetActorStats());
if (!pStats)
return;
Matrix34 tm = Matrix33::CreateRotationXYZ(pStats->FPWeaponAngles);
Vec3 offset(0.0f,0.0f,0.0f);
float right(g_pGameCVars->i_offset_right);
float front(g_pGameCVars->i_offset_front);
float up(g_pGameCVars->i_offset_up);
if (front!=0.0f || up!=0.0f || right!=0.0f)
{
offset += tm.GetColumn(0).GetNormalized() * right;
offset += tm.GetColumn(1).GetNormalized() * front;
offset += tm.GetColumn(2).GetNormalized() * up;
}
tm.SetTranslation(pStats->FPWeaponPos + offset);
GetEntity()->SetWorldTM(tm);
//CryLogAlways("weaponpos: %.3f,%.3f,%.3f // weaponrot: %.3f,%.3f,%.3f", tm.GetTranslation().x,tm.GetTranslation().y,tm.GetTranslation().z, pStats->FPWeaponAngles.x, pStats->FPWeaponAngles.y, pStats->FPWeaponAngles.z);
}
//------------------------------------------------------------------------
void CItem::UpdateFPCharacter(float frameTime)
{
if (IsClient())
{
ICharacterInstance *pCharacter = GetEntity()->GetCharacter(eIGS_FirstPerson);
if (pCharacter && !m_idleAnimation[eIGS_FirstPerson].empty() && pCharacter->GetISkeletonAnim()->GetNumAnimsInFIFO(0)<1)
PlayAction(m_idleAnimation[eIGS_FirstPerson], 0, true);
}
// need to explicitly update characters at this point
// cause the entity system update occered earlier, with the last position
for (int i=0; i<eIGS_Last; i++)
{
if (GetEntity()->GetSlotFlags(i)&ENTITY_SLOT_RENDER)
{
ICharacterInstance *pCharacter = GetEntity()->GetCharacter(i);
if (pCharacter)
{
Matrix34 mloc = GetEntity()->GetSlotLocalTM(i,false);
Matrix34 m34=GetEntity()->GetWorldTM()*mloc;
QuatT renderLocation = QuatT(m34);
pCharacter->GetISkeletonPose()->SetForceSkeletonUpdate(8);
pCharacter->SkeletonPreProcess(renderLocation, renderLocation, GetISystem()->GetViewCamera(),0x55 );
pCharacter->SkeletonPostProcess(renderLocation, renderLocation, 0, 1.0f, 0x55 );
}
}
}
IEntityRenderProxy *pProxy=GetRenderProxy();
if (pProxy)
pProxy->InvalidateLocalBounds();
}
//------------------------------------------------------------------------
bool CItem::FilterView(struct SViewParams &viewParams)
{
if (m_camerastats.animating && m_camerastats.follow)
{
const Matrix34 tm = GetEntity()->GetSlotWorldTM(eIGS_FirstPerson);
Vec3 offset(0.0f,0.0f,0.0f);
offset += tm.GetColumn(0).GetNormalized()*m_camerastats.pos.x;
offset += tm.GetColumn(1).GetNormalized()*m_camerastats.pos.y;
offset += tm.GetColumn(2).GetNormalized()*m_camerastats.pos.z;
viewParams.position+=offset;
viewParams.rotation*=m_camerastats.rot;
viewParams.blend=true;
viewParams.viewID=5;
}
return m_camerastats.reorient;
}
//------------------------------------------------------------------------
void CItem::PostFilterView(struct SViewParams &viewParams)
{
if (m_camerastats.animating && !m_camerastats.follow)
{
const Matrix34 tm = GetEntity()->GetSlotWorldTM(eIGS_FirstPerson);
Vec3 offset(0.0f,0.0f,0.0f);
offset += tm.GetColumn(0).GetNormalized()*m_camerastats.pos.x;
offset += tm.GetColumn(1).GetNormalized()*m_camerastats.pos.y;
offset += tm.GetColumn(2).GetNormalized()*m_camerastats.pos.z;
viewParams.position+=offset;
viewParams.rotation*=m_camerastats.rot;
viewParams.blend=true;
viewParams.viewID=5;
}
if (m_camerastats.animating && m_stats.mounted && !m_camerastats.helper.empty() && IsOwnerFP())
{
viewParams.position = GetSlotHelperPos(eIGS_FirstPerson, m_camerastats.helper, true);
viewParams.rotation = Quat(GetSlotHelperRotation(eIGS_FirstPerson, m_camerastats.helper, true));
viewParams.blend = true;
viewParams.viewID=5;
viewParams.nearplane = 0.1f;
}
}
//------------------------------------------------------------------------
bool CItem::IsOwnerFP()
{
CActor *pOwner = GetOwnerActor();
if (!pOwner)
return false;
if (m_pGameFramework->GetClientActor() != pOwner)
return false;
return !pOwner->IsThirdPerson();
}
//------------------------------------------------------------------------
bool CItem::IsCurrentItem()
{
CActor *pOwner = GetOwnerActor();
if (!pOwner)
return false;
if (pOwner->GetCurrentItem() == this)
return true;
return false;
}
//------------------------------------------------------------------------
void CItem::UpdateMounted(float frameTime)
{
IRenderAuxGeom* pAuxGeom = gEnv->pRenderer->GetIRenderAuxGeom();
if (!m_ownerId || !m_stats.mounted)
return;
CActor *pActor = GetOwnerActor();
if (!pActor)
return;
CheckViewChange();
if (true)
{
if (IsClient())
{
ICharacterInstance *pCharacter = GetEntity()->GetCharacter(eIGS_FirstPerson);
if (pCharacter && !m_idleAnimation[eIGS_FirstPerson].empty() && pCharacter->GetISkeletonAnim()->GetNumAnimsInFIFO(0)<1)
PlayAction(m_idleAnimation[eIGS_FirstPerson], 0, true);
}
// need to explicitly update characters at this point
// cause the entity system update occered earlier, with the last position
for (int i=0; i<eIGS_Last; i++)
{
if (GetEntity()->GetSlotFlags(i)&ENTITY_SLOT_RENDER)
{
ICharacterInstance *pCharacter = GetEntity()->GetCharacter(i);
if (pCharacter)
{
Matrix34 mloc = GetEntity()->GetSlotLocalTM(i,false);
Matrix34 m34 = GetEntity()->GetWorldTM()*mloc;
QuatT renderLocation = QuatT(m34);
pCharacter->GetISkeletonPose()->SetForceSkeletonUpdate(9);
pCharacter->SkeletonPreProcess(renderLocation, renderLocation, GetISystem()->GetViewCamera(),0x55 );
pCharacter->SkeletonPostProcess(renderLocation, renderLocation, 0, 0.0f, 0x55 );
}
}
}
// f32 fColor[4] = {1,1,0,1};
// f32 g_YLine=60.0f;
// gEnv->pRenderer->Draw2dLabel( 1,g_YLine, 1.3f, fColor, false, "Mounted Gun Code" );
//adjust the orientation of the gun based on the aim-direction
SMovementState info;
IMovementController* pMC = pActor->GetMovementController();
pMC->GetMovementState(info);
Matrix34 tm = Matrix33::CreateRotationVDir(info.aimDirection.GetNormalized());
Vec3 vGunXAxis=tm.GetColumn0();
if (pActor->GetLinkedVehicle()==0)
{
if (IMovementController * pMC = pActor->GetMovementController())
{
SMovementState info;
pMC->GetMovementState(info);
Vec3 dir = info.aimDirection.GetNormalized();
if(!pActor->IsPlayer())
{
// prevent snapping direction
Vec3 currentDir = GetEntity()->GetWorldRotation().GetColumn1();
float dot = currentDir.Dot(dir);
dot = CLAMP(dot,-1,1);
float reqAngle = cry_acosf(dot);
const float maxRotSpeed = 2.0f;
float maxAngle = frameTime * maxRotSpeed;
if(fabs(reqAngle) > maxAngle)
{
Vec3 axis = currentDir.Cross(dir);
if(axis.GetLengthSquared()>0.001f) // current dir and new dir are enough different
dir = currentDir.GetRotated(axis.GetNormalized(),sgn(reqAngle)*maxAngle);
}
}
//adjust the orientation of the gun based on the aim-direction
Matrix34 tm = Matrix33::CreateRotationVDir(dir);
Vec3 vWPos=GetEntity()->GetWorldPos();
tm.SetTranslation(vWPos);
GetEntity()->SetWorldTM(tm); //set the new orientation of the mounted gun
vGunXAxis=tm.GetColumn0();
Vec3 vInitialAimDirection = m_stats.mount_dir;
Matrix33 vInitialPlayerOrientation = Matrix33::CreateRotationVDir(vInitialAimDirection);
assert( vInitialAimDirection.IsUnit() );
Vec3 newp;
if (pActor->IsThirdPerson())
{
//third person
f32 dist = m_mountparams.body_distance*1.3f;
Vec3 oldp = pActor->GetEntity()->GetWorldPos();
newp = GetEntity()->GetWorldPos()-vInitialAimDirection*dist; //mounted gun
newp.z = oldp.z;
}
else
{
//first person
f32 fMoveBack = (1.0f+(dir.z*dir.z*dir.z*dir.z*4.0f))*0.75f;
f32 dist = m_mountparams.eye_distance*fMoveBack;
Vec3 oldp = pActor->GetEntity()->GetWorldPos();
newp = GetEntity()->GetWorldPos()-dir*dist; //mounted gun
//newp.z -= 0.75f;
newp.z = oldp.z;
}
Matrix34 actortm(pActor->GetEntity()->GetWorldTM());
//if (pActor->IsThirdPerson())
actortm=vInitialPlayerOrientation;
actortm.SetTranslation(newp);
pActor->GetEntity()->SetWorldTM(actortm, ENTITY_XFORM_USER);
pActor->GetAnimationGraphState()->SetInput("Action","gunnerMounted");
//f32 g_YLine=80.0f;
//gEnv->pRenderer->Draw2dLabel( 1,g_YLine, 1.3f, fColor, false, "Mounted Gun Active for FP and AI" );
if (ICharacterInstance *pCharacter = pActor->GetEntity()->GetCharacter(0))
{
ISkeletonAnim *pSkeletonAnim = pCharacter->GetISkeletonAnim();
assert(pSkeletonAnim);
uint32 numAnimsLayer = pSkeletonAnim->GetNumAnimsInFIFO(0);
for(uint32 i=0; i<numAnimsLayer; i++)
{
CAnimation &animation = pSkeletonAnim->GetAnimFromFIFO(0, i);
if (animation.m_AnimParams.m_nFlags & CA_MANUAL_UPDATE)
{
f32 aimrad = Ang3::CreateRadZ(Vec2(vInitialAimDirection),Vec2(dir));
animation.m_fAnimTime = clamp_tpl(aimrad/gf_PI,-1.0f,+1.0f)*0.5f+0.5f;
//if (pActor->IsThirdPerson()==0)
//animation.m_fAnimTime=0.6f; //Ivo & Benito: high advanced future code. don't ask what it is
//Benito - Not needed any more ;)
//f32 g_YLine=100.0f;
//gEnv->pRenderer->Draw2dLabel( 1,g_YLine, 1.3f, fColor, false, "AnimTime: %f MyAimAngle: %f deg:% distance:%f", animation.m_fAnimTime, aimrad, RAD2DEG(aimrad),m_mountparams.body_distance );
}
}
}
m_stats.mount_last_aimdir = dir;
}
}
if (ICharacterInstance* pCharInstance = pActor->GetEntity()->GetCharacter(0))
{
if (ISkeletonAnim* pSkeletonAnim = pCharInstance->GetISkeletonAnim())
{
OldBlendSpace ap;
if (GetAimBlending(ap))
{
pSkeletonAnim->SetBlendSpaceOverride(eMotionParamID_TurnSpeed, 0.5f + 0.5f * ap.m_turn, true);
}
}
}
UpdateIKMounted(pActor, vGunXAxis*0.1f);
RequireUpdate(eIUS_General);
}
}
//------------------------------------------------------------------------
void CItem::UpdateIKMounted(IActor* pActor, const Vec3& vGunXAxis)
{
if (!m_mountparams.left_hand_helper.empty() || !m_mountparams.right_hand_helper.empty())
{
Vec3 lhpos=GetSlotHelperPos(eIGS_FirstPerson, m_mountparams.left_hand_helper.c_str(), true);
Vec3 rhpos=GetSlotHelperPos(eIGS_FirstPerson, m_mountparams.right_hand_helper.c_str(), true);
pActor->SetIKPos("leftArm", lhpos-vGunXAxis, 1);
pActor->SetIKPos("rightArm", rhpos+vGunXAxis, 1);
// gEnv->pRenderer->GetIRenderAuxGeom()->DrawSphere(lhpos, 0.075f, ColorB(255, 255, 255, 255));
// gEnv->pRenderer->GetIRenderAuxGeom()->DrawSphere(rhpos, 0.075f, ColorB(128, 128, 128, 255));
}
}
//------------------------------------------------------------------------
bool CItem::GetAimBlending(OldBlendSpace& params)
{
// unused here so far
return false;
}
//------------------------------------------------------------------------
void CItem::CheckViewChange()
{
CActor *pOwner = GetOwnerActor();
if (m_stats.mounted)
{
bool fp = pOwner?!pOwner->IsThirdPerson():false;
if (fp!=m_stats.fp)
{
if (fp || !(m_stats.viewmode&eIVM_FirstPerson))
OnEnterFirstPerson();
else if (!fp)
AttachArms(false, false);
}
m_stats.fp = fp;
return;
}
if (!pOwner)
return;
if (!pOwner->IsThirdPerson())
{
if (!m_stats.fp || !(m_stats.viewmode&eIVM_FirstPerson))
OnEnterFirstPerson();
m_stats.fp = true;
}
else
{
if (m_stats.fp || !(m_stats.viewmode&eIVM_ThirdPerson))
OnEnterThirdPerson();
m_stats.fp = false;
}
}
//------------------------------------------------------------------------
void CItem::SetViewMode(int mode)
{
m_stats.viewmode = mode;
if (mode & eIVM_FirstPerson)
{
SetHand(m_stats.hand);
if (!m_parentId)
{
uint flags = GetEntity()->GetFlags();
if (!m_stats.mounted)
flags &= ~ENTITY_FLAG_CASTSHADOW;
else
flags |= ENTITY_FLAG_CASTSHADOW;
//GetEntity()->SetFlags(flags|ENTITY_FLAG_RECVSHADOW);
DrawSlot(eIGS_FirstPerson, true, !m_stats.mounted);
}
else
DrawSlot(eIGS_FirstPerson, false, false);
}
else
{
SetGeometry(eIGS_FirstPerson, 0);
}
if (mode & eIVM_ThirdPerson)
{
DrawSlot(eIGS_ThirdPerson, true);
if (!m_stats.mounted)
CopyRenderFlags(GetOwner());
}
else
DrawSlot(eIGS_ThirdPerson, false);
for (TAccessoryMap::iterator it = m_accessories.begin(); it != m_accessories.end(); it++)
{
IItem *pItem = m_pGameFramework->GetIItemSystem()->GetItem(it->second);
if (pItem)
{
CItem *pCItem = static_cast<CItem *>(pItem);
if (pCItem)
pCItem->SetViewMode(mode);
}
}
}
//------------------------------------------------------------------------
void CItem::ResetRenderFlags()
{
if (!GetRenderProxy())
return;
IRenderNode *pRenderNode = GetRenderProxy()->GetRenderNode();
if (pRenderNode)
{
pRenderNode->SetViewDistRatio(127);
pRenderNode->SetLodRatio(127);
GetEntity()->SetFlags(GetEntity()->GetFlags()|ENTITY_FLAG_CASTSHADOW);
}
}
//------------------------------------------------------------------------
void CItem::CopyRenderFlags(IEntity *pOwner)
{
if (!pOwner || !GetRenderProxy())
return;
IRenderNode *pRenderNode = GetRenderProxy()->GetRenderNode();
if (pRenderNode)
{
IEntityRenderProxy *pOwnerRenderProxy = (IEntityRenderProxy *)pOwner->GetProxy(ENTITY_PROXY_RENDER);
IRenderNode *pOwnerRenderNode = pOwnerRenderProxy?pOwnerRenderProxy->GetRenderNode():NULL;
if (pOwnerRenderNode)
{
pRenderNode->SetViewDistRatio(pOwnerRenderNode->GetViewDistRatio());
pRenderNode->SetLodRatio(pOwnerRenderNode->GetLodRatio());
uint flags = pOwner->GetFlags()&(ENTITY_FLAG_CASTSHADOW);
uint mflags = GetEntity()->GetFlags()&(~(ENTITY_FLAG_CASTSHADOW));
GetEntity()->SetFlags(mflags|flags);
}
}
}
| [
"[email protected]",
"kkirst@c5e09591-5635-0410-80e3-0b71df3ecc31"
]
| [
[
[
1,
31
],
[
35,
52
],
[
56,
96
],
[
98,
112
],
[
116,
203
],
[
206,
220
],
[
222,
236
],
[
240,
243
],
[
258,
262
],
[
264,
264
],
[
287,
287
],
[
294,
295
],
[
313,
315
],
[
320,
322
],
[
326,
328
],
[
331,
331
],
[
334,
334
],
[
336,
337
],
[
346,
347
],
[
349,
357
],
[
359,
362
],
[
364,
367
],
[
369,
374
],
[
376,
376
],
[
379,
381
],
[
387,
522
]
],
[
[
32,
34
],
[
53,
55
],
[
97,
97
],
[
113,
115
],
[
204,
205
],
[
221,
221
],
[
237,
239
],
[
244,
257
],
[
263,
263
],
[
265,
286
],
[
288,
293
],
[
296,
312
],
[
316,
319
],
[
323,
325
],
[
329,
330
],
[
332,
333
],
[
335,
335
],
[
338,
345
],
[
348,
348
],
[
358,
358
],
[
363,
363
],
[
368,
368
],
[
375,
375
],
[
377,
378
],
[
382,
386
]
]
]
|
c2b557938f61c74e60b1c0e342cb66c5a3adde0f | 34e4b3134fbfcf9de0eed58371c8a16705408e21 | /plugin/detectfx.cpp | 2d67959db89deadfe899e4e4832b72396db5fd50 | []
| no_license | dbaies/NsisDotNetChecker | 1b4a38a53dcbeb86d479c450d36df41b405f99ac | 40968b82c0a4c5b36ab3b712bb7bab3f4006bc25 | refs/heads/master | 2021-01-24T04:14:16.927594 | 2011-07-16T06:33:37 | 2011-07-16T06:33:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,624 | cpp | /**
* Original file detectfx_new.cpp is located at https://skydrive.live.com/?cid=27e6a35d1a492af7&id=27E6A35D1A492AF7%21494
* Author: Aaron Stebner (http://blogs.msdn.com/b/astebner/archive/2009/06/16/9763379.aspx)
* NSIS adaptation: Alexey Sitnikov
*/
#include <stdio.h>
#include <windows.h>
#include <tchar.h>
#include <strsafe.h>
#include <mscoree.h>
#include "nsis\pluginapi.h"
// In case the machine this is compiled on does not have the most recent platform SDK
// with these values defined, define them here
#ifndef SM_TABLETPC
#define SM_TABLETPC 86
#endif
#ifndef SM_MEDIACENTER
#define SM_MEDIACENTER 87
#endif
#define CountOf(x) sizeof(x)/sizeof(*x)
// Constants that represent registry key names and value names
// to use for detection
const TCHAR *g_szNetfx10RegKeyName = _T("Software\\Microsoft\\.NETFramework\\Policy\\v1.0");
const TCHAR *g_szNetfx10RegKeyValue = _T("3705");
const TCHAR *g_szNetfx10SPxMSIRegKeyName = _T("Software\\Microsoft\\Active Setup\\Installed Components\\{78705f0d-e8db-4b2d-8193-982bdda15ecd}");
const TCHAR *g_szNetfx10SPxOCMRegKeyName = _T("Software\\Microsoft\\Active Setup\\Installed Components\\{FDC11A6F-17D1-48f9-9EA3-9051954BAA24}");
const TCHAR *g_szNetfx11RegKeyName = _T("Software\\Microsoft\\NET Framework Setup\\NDP\\v1.1.4322");
const TCHAR *g_szNetfx20RegKeyName = _T("Software\\Microsoft\\NET Framework Setup\\NDP\\v2.0.50727");
const TCHAR *g_szNetfx30RegKeyName = _T("Software\\Microsoft\\NET Framework Setup\\NDP\\v3.0\\Setup");
const TCHAR *g_szNetfx30SpRegKeyName = _T("Software\\Microsoft\\NET Framework Setup\\NDP\\v3.0");
const TCHAR *g_szNetfx30RegValueName = _T("InstallSuccess");
const TCHAR *g_szNetfx35RegKeyName = _T("Software\\Microsoft\\NET Framework Setup\\NDP\\v3.5");
const TCHAR *g_szNetfx40ClientRegKeyName = _T("Software\\Microsoft\\NET Framework Setup\\NDP\\v4\\Client");
const TCHAR *g_szNetfx40FullRegKeyName = _T("Software\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full");
const TCHAR *g_szNetfx40SPxRegValueName = _T("Servicing");
const TCHAR *g_szNetfxStandardRegValueName = _T("Install");
const TCHAR *g_szNetfxStandardSPxRegValueName = _T("SP");
const TCHAR *g_szNetfxStandardVersionRegValueName = _T("Version");
// Version information for final release of .NET Framework 3.0
const int g_iNetfx30VersionMajor = 3;
const int g_iNetfx30VersionMinor = 0;
const int g_iNetfx30VersionBuild = 4506;
const int g_iNetfx30VersionRevision = 26;
// Version information for final release of .NET Framework 3.5
const int g_iNetfx35VersionMajor = 3;
const int g_iNetfx35VersionMinor = 5;
const int g_iNetfx35VersionBuild = 21022;
const int g_iNetfx35VersionRevision = 8;
// Version information for final release of .NET Framework 4
const int g_iNetfx40VersionMajor = 4;
const int g_iNetfx40VersionMinor = 0;
const int g_iNetfx40VersionBuild = 30319;
const int g_iNetfx40VersionRevision = 0;
// Constants for known .NET Framework versions used with the GetRequestedRuntimeInfo API
const TCHAR *g_szNetfx10VersionString = _T("v1.0.3705");
const TCHAR *g_szNetfx11VersionString = _T("v1.1.4322");
const TCHAR *g_szNetfx20VersionString = _T("v2.0.50727");
const TCHAR *g_szNetfx40VersionString = _T("v4.0.30319");
// Function prototypes
bool CheckNetfxBuildNumber(const TCHAR*, const TCHAR*, const int, const int, const int, const int);
bool CheckNetfxVersionUsingMscoree(const TCHAR*);
int GetNetfx10SPLevel();
int GetNetfxSPLevel(const TCHAR*, const TCHAR*);
DWORD GetProcessorArchitectureFlag();
bool IsCurrentOSTabletMedCenter();
bool IsNetfx10Installed();
bool IsNetfx11Installed();
bool IsNetfx20Installed();
bool IsNetfx30Installed();
bool IsNetfx35Installed();
bool IsNetfx40ClientInstalled();
bool IsNetfx40FullInstalled();
bool RegistryGetValue(HKEY, const TCHAR*, const TCHAR*, DWORD, LPBYTE, DWORD);
/******************************************************************
Function Name: CheckNetfxVersionUsingMscoree
Description: Uses the logic described in the sample code at http://msdn2.microsoft.com/library/ydh6b3yb.aspx
to load mscoree.dll and call its APIs to determine
whether or not a specific version of the .NET
Framework is installed on the system
Inputs: pszNetfxVersionToCheck - version to look for
Results: true if the requested version is installed
false otherwise
******************************************************************/
bool CheckNetfxVersionUsingMscoree(const TCHAR *pszNetfxVersionToCheck)
{
bool bFoundRequestedNetfxVersion = false;
HRESULT hr = S_OK;
// Check input parameter
if (NULL == pszNetfxVersionToCheck)
return false;
HMODULE hmodMscoree = LoadLibraryEx(_T("mscoree.dll"), NULL, 0);
if (NULL != hmodMscoree)
{
typedef HRESULT (STDAPICALLTYPE *GETCORVERSION)(LPWSTR szBuffer, DWORD cchBuffer, DWORD* dwLength);
GETCORVERSION pfnGETCORVERSION = (GETCORVERSION)GetProcAddress(hmodMscoree, "GetCORVersion");
// Some OSs shipped with a placeholder copy of mscoree.dll. The existence of mscoree.dll
// therefore does NOT mean that a version of the .NET Framework is installed.
// If this copy of mscoree.dll does not have an exported function named GetCORVersion
// then we know it is a placeholder DLL.
if (NULL == pfnGETCORVERSION)
goto Finish;
typedef HRESULT (STDAPICALLTYPE *CORBINDTORUNTIME)(LPCWSTR pwszVersion, LPCWSTR pwszBuildFlavor, REFCLSID rclsid, REFIID riid, LPVOID FAR *ppv);
CORBINDTORUNTIME pfnCORBINDTORUNTIME = (CORBINDTORUNTIME)GetProcAddress(hmodMscoree, "CorBindToRuntime");
typedef HRESULT (STDAPICALLTYPE *GETREQUESTEDRUNTIMEINFO)(LPCWSTR pExe, LPCWSTR pwszVersion, LPCWSTR pConfigurationFile, DWORD startupFlags, DWORD runtimeInfoFlags, LPWSTR pDirectory, DWORD dwDirectory, DWORD *dwDirectoryLength, LPWSTR pVersion, DWORD cchBuffer, DWORD* dwlength);
GETREQUESTEDRUNTIMEINFO pfnGETREQUESTEDRUNTIMEINFO = (GETREQUESTEDRUNTIMEINFO)GetProcAddress(hmodMscoree, "GetRequestedRuntimeInfo");
if (NULL != pfnCORBINDTORUNTIME)
{
TCHAR szRetrievedVersion[50];
DWORD dwLength = CountOf(szRetrievedVersion);
if (NULL == pfnGETREQUESTEDRUNTIMEINFO)
{
// Having CorBindToRuntimeHost but not having GetRequestedRuntimeInfo means that
// this machine contains no higher than .NET Framework 1.0, but the only way to
// 100% guarantee that the .NET Framework 1.0 is installed is to call a function
// to exercise its functionality
if (0 == _tcscmp(pszNetfxVersionToCheck, g_szNetfx10VersionString))
{
hr = pfnGETCORVERSION(szRetrievedVersion, dwLength, &dwLength);
if (SUCCEEDED(hr))
{
if (0 == _tcscmp(szRetrievedVersion, g_szNetfx10VersionString))
bFoundRequestedNetfxVersion = true;
}
goto Finish;
}
}
// Set error mode to prevent the .NET Framework from displaying
// unfriendly error dialogs
UINT uOldErrorMode = SetErrorMode(SEM_FAILCRITICALERRORS);
TCHAR szDirectory[MAX_PATH];
DWORD dwDirectoryLength = 0;
DWORD dwRuntimeInfoFlags = RUNTIME_INFO_DONT_RETURN_DIRECTORY | GetProcessorArchitectureFlag();
// Check for the requested .NET Framework version
hr = pfnGETREQUESTEDRUNTIMEINFO(NULL, pszNetfxVersionToCheck, NULL, STARTUP_LOADER_OPTIMIZATION_MULTI_DOMAIN_HOST, NULL, szDirectory, CountOf(szDirectory), &dwDirectoryLength, szRetrievedVersion, CountOf(szRetrievedVersion), &dwLength);
if (SUCCEEDED(hr))
bFoundRequestedNetfxVersion = true;
// Restore the previous error mode
SetErrorMode(uOldErrorMode);
}
}
Finish:
if (hmodMscoree)
{
FreeLibrary(hmodMscoree);
}
return bFoundRequestedNetfxVersion;
}
/******************************************************************
Function Name: GetNetfx10SPLevel
Description: Uses the detection method recommended at
http://blogs.msdn.com/astebner/archive/2004/09/14/229802.aspx
to determine what service pack for the
.NET Framework 1.0 is installed on the machine
Inputs: NONE
Results: integer representing SP level for .NET Framework 1.0
******************************************************************/
int GetNetfx10SPLevel()
{
TCHAR szRegValue[MAX_PATH];
TCHAR *pszSPLevel = NULL;
int iRetValue = -1;
bool bRegistryRetVal = false;
// Need to detect what OS we are running on so we know what
// registry key to use to look up the SP level
if (IsCurrentOSTabletMedCenter())
bRegistryRetVal = RegistryGetValue(HKEY_LOCAL_MACHINE, g_szNetfx10SPxOCMRegKeyName, g_szNetfxStandardVersionRegValueName, NULL, (LPBYTE)szRegValue, MAX_PATH);
else
bRegistryRetVal = RegistryGetValue(HKEY_LOCAL_MACHINE, g_szNetfx10SPxMSIRegKeyName, g_szNetfxStandardVersionRegValueName, NULL, (LPBYTE)szRegValue, MAX_PATH);
if (bRegistryRetVal)
{
// This registry value should be of the format
// #,#,#####,# where the last # is the SP level
// Try to parse off the last # here
pszSPLevel = _tcsrchr(szRegValue, _T(','));
if (NULL != pszSPLevel)
{
// Increment the pointer to skip the comma
pszSPLevel++;
// Convert the remaining value to an integer
iRetValue = _tstoi(pszSPLevel);
}
}
return iRetValue;
}
/******************************************************************
Function Name: GetNetfxSPLevel
Description: Determine what service pack is installed for a
version of the .NET Framework using registry
based detection methods documented in the
.NET Framework deployment guides.
Inputs: pszNetfxRegKeyName - registry key name to use for detection
pszNetfxRegValueName - registry value to use for detection
Results: integer representing SP level for .NET Framework
******************************************************************/
int GetNetfxSPLevel(const TCHAR *pszNetfxRegKeyName, const TCHAR *pszNetfxRegValueName)
{
DWORD dwRegValue=0;
if (RegistryGetValue(HKEY_LOCAL_MACHINE, pszNetfxRegKeyName, pszNetfxRegValueName, NULL, (LPBYTE)&dwRegValue, sizeof(DWORD)))
{
return (int)dwRegValue;
}
// We can only get here if the .NET Framework is not
// installed or there was some kind of error retrieving
// the data from the registry
return -1;
}
/******************************************************************
Function Name: GetProcessorArchitectureFlag
Description: Determine the processor architecture of the
system (x86, x64, ia64)
Inputs: NONE
Results: DWORD processor architecture flag
******************************************************************/
DWORD GetProcessorArchitectureFlag()
{
HMODULE hmodKernel32 = NULL;
typedef void (WINAPI *PFnGetNativeSystemInfo) (LPSYSTEM_INFO);
PFnGetNativeSystemInfo pfnGetNativeSystemInfo;
SYSTEM_INFO sSystemInfo;
memset(&sSystemInfo, 0, sizeof(sSystemInfo));
bool bRetrievedSystemInfo = false;
// Attempt to load kernel32.dll
hmodKernel32 = LoadLibrary(_T("Kernel32.dll"));
if (NULL != hmodKernel32)
{
// If the DLL loaded correctly, get the proc address for GetNativeSystemInfo
pfnGetNativeSystemInfo = (PFnGetNativeSystemInfo) GetProcAddress(hmodKernel32, "GetNativeSystemInfo");
if (NULL != pfnGetNativeSystemInfo)
{
// Call GetNativeSystemInfo if it exists
(*pfnGetNativeSystemInfo)(&sSystemInfo);
bRetrievedSystemInfo = true;
}
FreeLibrary(hmodKernel32);
}
if (!bRetrievedSystemInfo)
{
// Fallback to calling GetSystemInfo if the above failed
GetSystemInfo(&sSystemInfo);
bRetrievedSystemInfo = true;
}
if (bRetrievedSystemInfo)
{
switch (sSystemInfo.wProcessorArchitecture)
{
case PROCESSOR_ARCHITECTURE_INTEL:
return RUNTIME_INFO_REQUEST_X86;
case PROCESSOR_ARCHITECTURE_IA64:
return RUNTIME_INFO_REQUEST_IA64;
case PROCESSOR_ARCHITECTURE_AMD64:
return RUNTIME_INFO_REQUEST_AMD64;
default:
return 0;
}
}
return 0;
}
/******************************************************************
Function Name: CheckNetfxBuildNumber
Description: Retrieves the .NET Framework build number from
the registry and validates that it is not a pre-release
version number
Inputs: NONE
Results: true if the build number in the registry is greater
than or equal to the passed in version; false otherwise
******************************************************************/
bool CheckNetfxBuildNumber(const TCHAR *pszNetfxRegKeyName, const TCHAR *pszNetfxRegKeyValue, const int iRequestedVersionMajor, const int iRequestedVersionMinor, const int iRequestedVersionBuild, const int iRequestedVersionRevision)
{
TCHAR szRegValue[MAX_PATH];
TCHAR *pszToken = NULL;
TCHAR *pszNextToken = NULL;
int iVersionPartCounter = 0;
int iRegistryVersionMajor = 0;
int iRegistryVersionMinor = 0;
int iRegistryVersionBuild = 0;
int iRegistryVersionRevision = 0;
bool bRegistryRetVal = false;
// Attempt to retrieve the build number registry value
bRegistryRetVal = RegistryGetValue(HKEY_LOCAL_MACHINE, pszNetfxRegKeyName, pszNetfxRegKeyValue, NULL, (LPBYTE)szRegValue, MAX_PATH);
if (bRegistryRetVal)
{
// This registry value should be of the format
// #.#.#####.##. Try to parse the 4 parts of
// the version here
pszToken = _tcstok_s(szRegValue, _T("."), &pszNextToken);
while (NULL != pszToken)
{
iVersionPartCounter++;
switch (iVersionPartCounter)
{
case 1:
// Convert the major version value to an integer
iRegistryVersionMajor = _tstoi(pszToken);
break;
case 2:
// Convert the minor version value to an integer
iRegistryVersionMinor = _tstoi(pszToken);
break;
case 3:
// Convert the build number value to an integer
iRegistryVersionBuild = _tstoi(pszToken);
break;
case 4:
// Convert the revision number value to an integer
iRegistryVersionRevision = _tstoi(pszToken);
break;
default:
break;
}
// Get the next part of the version number
pszToken = _tcstok_s(NULL, _T("."), &pszNextToken);
}
}
// Compare the version number retrieved from the registry with
// the version number of the final release of the .NET Framework
// that we are checking
if (iRegistryVersionMajor > iRequestedVersionMajor)
{
return true;
}
else if (iRegistryVersionMajor == iRequestedVersionMajor)
{
if (iRegistryVersionMinor > iRequestedVersionMinor)
{
return true;
}
else if (iRegistryVersionMinor == iRequestedVersionMinor)
{
if (iRegistryVersionBuild > iRequestedVersionBuild)
{
return true;
}
else if (iRegistryVersionBuild == iRequestedVersionBuild)
{
if (iRegistryVersionRevision >= iRequestedVersionRevision)
{
return true;
}
}
}
}
// If we get here, the version in the registry must be less than the
// version of the final release of the .NET Framework we are checking,
// so return false
return false;
}
/******************************************************************
Function Name: IsCurrentOSTabletMedCenter
Description: Determine if the current OS is a Windows XP
Tablet PC Edition or Windows XP Media Center
Edition system
Inputs: NONE
Results: true if the OS is Tablet PC or Media Center
false otherwise
******************************************************************/
bool IsCurrentOSTabletMedCenter()
{
// Use GetSystemMetrics to detect if we are on a Tablet PC or Media Center OS
return ( (GetSystemMetrics(SM_TABLETPC) != 0) || (GetSystemMetrics(SM_MEDIACENTER) != 0) );
}
/******************************************************************
Function Name: IsNetfx10Installed
Description: Uses the detection method recommended at
http://msdn.microsoft.com/library/ms994349.aspx
to determine whether the .NET Framework 1.0 is
installed on the machine
Inputs: NONE
Results: true if the .NET Framework 1.0 is installed
false otherwise
******************************************************************/
bool IsNetfx10Installed()
{
TCHAR szRegValue[MAX_PATH];
return (RegistryGetValue(HKEY_LOCAL_MACHINE, g_szNetfx10RegKeyName, g_szNetfx10RegKeyValue, NULL, (LPBYTE)szRegValue, MAX_PATH));
}
/******************************************************************
Function Name: IsNetfx11Installed
Description: Uses the detection method recommended at
http://msdn.microsoft.com/library/ms994339.aspx
to determine whether the .NET Framework 1.1 is
installed on the machine
Inputs: NONE
Results: true if the .NET Framework 1.1 is installed
false otherwise
******************************************************************/
bool IsNetfx11Installed()
{
bool bRetValue = false;
DWORD dwRegValue=0;
if (RegistryGetValue(HKEY_LOCAL_MACHINE, g_szNetfx11RegKeyName, g_szNetfxStandardRegValueName, NULL, (LPBYTE)&dwRegValue, sizeof(DWORD)))
{
if (1 == dwRegValue)
bRetValue = true;
}
return bRetValue;
}
/******************************************************************
Function Name: IsNetfx20Installed
Description: Uses the detection method recommended at
http://msdn2.microsoft.com/library/aa480243.aspx
to determine whether the .NET Framework 2.0 is
installed on the machine
Inputs: NONE
Results: true if the .NET Framework 2.0 is installed
false otherwise
******************************************************************/
bool IsNetfx20Installed()
{
bool bRetValue = false;
DWORD dwRegValue=0;
if (RegistryGetValue(HKEY_LOCAL_MACHINE, g_szNetfx20RegKeyName, g_szNetfxStandardRegValueName, NULL, (LPBYTE)&dwRegValue, sizeof(DWORD)))
{
if (1 == dwRegValue)
bRetValue = true;
}
return bRetValue;
}
/******************************************************************
Function Name: IsNetfx30Installed
Description: Uses the detection method recommended at
http://msdn.microsoft.com/library/aa964979.aspx
to determine whether the .NET Framework 3.0 is
installed on the machine
Inputs: NONE
Results: true if the .NET Framework 3.0 is installed
false otherwise
******************************************************************/
bool IsNetfx30Installed()
{
bool bRetValue = false;
DWORD dwRegValue=0;
// Check that the InstallSuccess registry value exists and equals 1
if (RegistryGetValue(HKEY_LOCAL_MACHINE, g_szNetfx30RegKeyName, g_szNetfx30RegValueName, NULL, (LPBYTE)&dwRegValue, sizeof(DWORD)))
{
if (1 == dwRegValue)
bRetValue = true;
}
// A system with a pre-release version of the .NET Framework 3.0 can
// have the InstallSuccess value. As an added verification, check the
// version number listed in the registry
return (bRetValue && CheckNetfxBuildNumber(g_szNetfx30RegKeyName, g_szNetfxStandardVersionRegValueName, g_iNetfx30VersionMajor, g_iNetfx30VersionMinor, g_iNetfx30VersionBuild, g_iNetfx30VersionRevision));
}
/******************************************************************
Function Name: IsNetfx35Installed
Description: Uses the detection method recommended at
http://msdn.microsoft.com/library/cc160716.aspx
to determine whether the .NET Framework 3.5 is
installed on the machine
Inputs: NONE
Results: true if the .NET Framework 3.5 is installed
false otherwise
******************************************************************/
bool IsNetfx35Installed()
{
bool bRetValue = false;
DWORD dwRegValue=0;
// Check that the Install registry value exists and equals 1
if (RegistryGetValue(HKEY_LOCAL_MACHINE, g_szNetfx35RegKeyName, g_szNetfxStandardRegValueName, NULL, (LPBYTE)&dwRegValue, sizeof(DWORD)))
{
if (1 == dwRegValue)
bRetValue = true;
}
// A system with a pre-release version of the .NET Framework 3.5 can
// have the Install value. As an added verification, check the
// version number listed in the registry
return (bRetValue && CheckNetfxBuildNumber(g_szNetfx35RegKeyName, g_szNetfxStandardVersionRegValueName, g_iNetfx35VersionMajor, g_iNetfx35VersionMinor, g_iNetfx35VersionBuild, g_iNetfx35VersionRevision));
}
/******************************************************************
Function Name: IsNetfx40ClientInstalled
Description: Uses the detection method recommended at
http://msdn.microsoft.com/library/ee942965(v=VS.100).aspx
to determine whether the .NET Framework 4 Client is
installed on the machine
Inputs: NONE
Results: true if the .NET Framework 4 Client is installed
false otherwise
******************************************************************/
bool IsNetfx40ClientInstalled()
{
bool bRetValue = false;
DWORD dwRegValue=0;
if (RegistryGetValue(HKEY_LOCAL_MACHINE, g_szNetfx40ClientRegKeyName, g_szNetfxStandardRegValueName, NULL, (LPBYTE)&dwRegValue, sizeof(DWORD)))
{
if (1 == dwRegValue)
bRetValue = true;
}
// A system with a pre-release version of the .NET Framework 4 can
// have the Install value. As an added verification, check the
// version number listed in the registry
return (bRetValue && CheckNetfxBuildNumber(g_szNetfx40ClientRegKeyName, g_szNetfxStandardVersionRegValueName, g_iNetfx40VersionMajor, g_iNetfx40VersionMinor, g_iNetfx40VersionBuild, g_iNetfx40VersionRevision));
}
/******************************************************************
Function Name: IsNetfx40FullInstalled
Description: Uses the detection method recommended at
http://msdn.microsoft.com/library/ee942965(v=VS.100).aspx
to determine whether the .NET Framework 4 Full is
installed on the machine
Inputs: NONE
Results: true if the .NET Framework 4 Full is installed
false otherwise
******************************************************************/
bool IsNetfx40FullInstalled()
{
bool bRetValue = false;
DWORD dwRegValue=0;
if (RegistryGetValue(HKEY_LOCAL_MACHINE, g_szNetfx40FullRegKeyName, g_szNetfxStandardRegValueName, NULL, (LPBYTE)&dwRegValue, sizeof(DWORD)))
{
if (1 == dwRegValue)
bRetValue = true;
}
// A system with a pre-release version of the .NET Framework 4 can
// have the Install value. As an added verification, check the
// version number listed in the registry
return (bRetValue && CheckNetfxBuildNumber(g_szNetfx40FullRegKeyName, g_szNetfxStandardVersionRegValueName, g_iNetfx40VersionMajor, g_iNetfx40VersionMinor, g_iNetfx40VersionBuild, g_iNetfx40VersionRevision));
}
/******************************************************************
Function Name: RegistryGetValue
Description: Get the value of a reg key
Inputs: HKEY hk - The hk of the key to retrieve
TCHAR *pszKey - Name of the key to retrieve
TCHAR *pszValue - The value that will be retrieved
DWORD dwType - The type of the value that will be retrieved
LPBYTE data - A buffer to save the retrieved data
DWORD dwSize - The size of the data retrieved
Results: true if successful, false otherwise
******************************************************************/
bool RegistryGetValue(HKEY hk, const TCHAR * pszKey, const TCHAR * pszValue, DWORD dwType, LPBYTE data, DWORD dwSize)
{
HKEY hkOpened;
// Try to open the key
if (RegOpenKeyEx(hk, pszKey, 0, KEY_READ, &hkOpened) != ERROR_SUCCESS)
{
return false;
}
// If the key was opened, try to retrieve the value
if (RegQueryValueEx(hkOpened, pszValue, 0, &dwType, (LPBYTE)data, &dwSize) != ERROR_SUCCESS)
{
RegCloseKey(hkOpened);
return false;
}
// Clean up
RegCloseKey(hkOpened);
return true;
}
//********************************************* NSIS Plugin Functions ****************************************************************************
//************************************************* .NET 4.0 Full ********************************************************************************
extern "C"
void __declspec(dllexport) IsDotNet40FullInstalled(HWND hwndParent, int string_size, char *variables, stack_t **stacktop, extra_parameters *extra) {
EXDLL_INIT();
pushstring((IsNetfx40FullInstalled() && CheckNetfxVersionUsingMscoree(g_szNetfx40VersionString)) ? "true" : "false");
}
extern "C"
void __declspec(dllexport) GetDotNet40FullServicePack(HWND hwndParent, int string_size, char *variables, stack_t **stacktop, extra_parameters *extra) {
EXDLL_INIT();
int iNetfx40FullSPLevel = -1;
bool bNetfx40FullInstalled = (IsNetfx40FullInstalled() && CheckNetfxVersionUsingMscoree(g_szNetfx40VersionString));
TCHAR szMessage[MAX_PATH];
TCHAR szOutputString[MAX_PATH*20];
if (bNetfx40FullInstalled)
{
iNetfx40FullSPLevel = GetNetfxSPLevel(g_szNetfx40FullRegKeyName, g_szNetfx40SPxRegValueName);
if (iNetfx40FullSPLevel > 0)
pushint(iNetfx40FullSPLevel);
else
pushint(-1);
}
else
{
pushint(-2);
}
}
//************************************************* .NET 4.0 Client ******************************************************************************
extern "C"
void __declspec(dllexport) IsDotNet40ClientInstalled(HWND hwndParent, int string_size, char *variables, stack_t **stacktop, extra_parameters *extra) {
EXDLL_INIT();
pushstring((IsNetfx40ClientInstalled() && CheckNetfxVersionUsingMscoree(g_szNetfx40VersionString)) ? "true" : "false");
}
extern "C"
void __declspec(dllexport) GetDotNet40ClientServicePack(HWND hwndParent, int string_size, char *variables, stack_t **stacktop, extra_parameters *extra) {
EXDLL_INIT();
int iNetfx40ClientSPLevel = -1;
bool bNetfx40ClientInstalled = (IsNetfx40ClientInstalled() && CheckNetfxVersionUsingMscoree(g_szNetfx40VersionString));
TCHAR szMessage[MAX_PATH];
TCHAR szOutputString[MAX_PATH*20];
if (bNetfx40ClientInstalled)
{
iNetfx40ClientSPLevel = GetNetfxSPLevel(g_szNetfx40FullRegKeyName, g_szNetfx40SPxRegValueName);
if (iNetfx40ClientSPLevel > 0)
pushint(iNetfx40ClientSPLevel);
else
pushint(-1);
}
else
{
pushint(-2);
}
}
//***************************************************** .NET 3.5 **********************************************************************************
extern "C"
void __declspec(dllexport) IsDotNet35Installed(HWND hwndParent, int string_size, char *variables, stack_t **stacktop, extra_parameters *extra) {
EXDLL_INIT();
// The .NET Framework 3.5 is an add-in that installs
// on top of the .NET Framework 2.0 and 3.0. For this version
// check, validate that 2.0, 3.0 and 3.5 are installed.
pushstring((IsNetfx20Installed() && IsNetfx30Installed() && IsNetfx35Installed() && CheckNetfxVersionUsingMscoree(g_szNetfx20VersionString)) ? "true" : "false");
}
extern "C"
void __declspec(dllexport) GetDotNet35ServicePack(HWND hwndParent, int string_size, char *variables, stack_t **stacktop, extra_parameters *extra) {
EXDLL_INIT();
int iNetfx35SPLevel = -1;
bool bNetfx35Installed = (IsNetfx20Installed() && IsNetfx30Installed() && IsNetfx35Installed() && CheckNetfxVersionUsingMscoree(g_szNetfx20VersionString));
TCHAR szMessage[MAX_PATH];
TCHAR szOutputString[MAX_PATH*20];
if (bNetfx35Installed)
{
iNetfx35SPLevel = GetNetfxSPLevel(g_szNetfx35RegKeyName, g_szNetfxStandardSPxRegValueName);
if (iNetfx35SPLevel > 0)
pushint(iNetfx35SPLevel);
else
pushint(-1);
}
else
{
pushint(-2);
}
}
//***************************************************** .NET 3.0 **********************************************************************************
extern "C"
void __declspec(dllexport) IsDotNet30Installed(HWND hwndParent, int string_size, char *variables, stack_t **stacktop, extra_parameters *extra) {
EXDLL_INIT();
// The .NET Framework 3.0 is an add-in that installs
// on top of the .NET Framework 2.0. For this version
// check, validate that both 2.0 and 3.0 are installed.
pushstring((IsNetfx20Installed() && IsNetfx30Installed() && CheckNetfxVersionUsingMscoree(g_szNetfx20VersionString)) ? "true" : "false");
}
extern "C"
void __declspec(dllexport) GetDotNet30ServicePack(HWND hwndParent, int string_size, char *variables, stack_t **stacktop, extra_parameters *extra) {
EXDLL_INIT();
int iNetfx30SPLevel = -1;
bool bNetfx30Installed = (IsNetfx20Installed() && IsNetfx30Installed() && CheckNetfxVersionUsingMscoree(g_szNetfx20VersionString));
TCHAR szMessage[MAX_PATH];
TCHAR szOutputString[MAX_PATH*20];
if (bNetfx30Installed)
{
iNetfx30SPLevel = GetNetfxSPLevel(g_szNetfx30SpRegKeyName, g_szNetfxStandardSPxRegValueName);
if (iNetfx30SPLevel > 0)
pushint(iNetfx30SPLevel);
else
pushint(-1);
}
else
{
pushint(-2);
}
}
//***************************************************** .NET 2.0 **********************************************************************************
extern "C"
void __declspec(dllexport) IsDotNet20Installed(HWND hwndParent, int string_size, char *variables, stack_t **stacktop, extra_parameters *extra) {
EXDLL_INIT();
pushstring((IsNetfx20Installed() && CheckNetfxVersionUsingMscoree(g_szNetfx20VersionString)) ? "true" : "false");
}
extern "C"
void __declspec(dllexport) GetDotNet20ServicePack(HWND hwndParent, int string_size, char *variables, stack_t **stacktop, extra_parameters *extra) {
EXDLL_INIT();
int iNetfx20SPLevel = -1;
bool bNetfx20Installed = (IsNetfx20Installed() && CheckNetfxVersionUsingMscoree(g_szNetfx20VersionString));
TCHAR szMessage[MAX_PATH];
TCHAR szOutputString[MAX_PATH*20];
if (bNetfx20Installed)
{
iNetfx20SPLevel = GetNetfxSPLevel(g_szNetfx20RegKeyName, g_szNetfxStandardSPxRegValueName);
if (iNetfx20SPLevel > 0)
pushint(iNetfx20SPLevel);
else
pushint(-1);
}
else
{
pushint(-2);
}
}
//***************************************************** .NET 1.1 **********************************************************************************
extern "C"
void __declspec(dllexport) IsDotNet11Installed(HWND hwndParent, int string_size, char *variables, stack_t **stacktop, extra_parameters *extra) {
EXDLL_INIT();
pushstring((IsNetfx11Installed() && CheckNetfxVersionUsingMscoree(g_szNetfx11VersionString)) ? "true" : "false");
}
extern "C"
void __declspec(dllexport) GetDotNet11ServicePack(HWND hwndParent, int string_size, char *variables, stack_t **stacktop, extra_parameters *extra) {
EXDLL_INIT();
int iNetfx11SPLevel = -1;
bool bNetfx11Installed = (IsNetfx11Installed() && CheckNetfxVersionUsingMscoree(g_szNetfx11VersionString));
TCHAR szMessage[MAX_PATH];
TCHAR szOutputString[MAX_PATH*20];
if (bNetfx11Installed)
{
iNetfx11SPLevel = GetNetfxSPLevel(g_szNetfx11RegKeyName, g_szNetfxStandardSPxRegValueName);
if (iNetfx11SPLevel > 0)
pushint(iNetfx11SPLevel);
else
pushint(-1);
}
else
{
pushint(-2);
}
}
//***************************************************** .NET 1.0 **********************************************************************************
extern "C"
void __declspec(dllexport) IsDotNet10Installed(HWND hwndParent, int string_size, char *variables, stack_t **stacktop, extra_parameters *extra) {
EXDLL_INIT();
pushstring((IsNetfx11Installed() && CheckNetfxVersionUsingMscoree(g_szNetfx11VersionString)) ? "true" : "false");
}
extern "C"
void __declspec(dllexport) GetDotNet10ServicePack(HWND hwndParent, int string_size, char *variables, stack_t **stacktop, extra_parameters *extra) {
EXDLL_INIT();
int iNetfx10SPLevel = -1;
bool bNetfx10Installed = (IsNetfx10Installed() && CheckNetfxVersionUsingMscoree(g_szNetfx10VersionString));
TCHAR szMessage[MAX_PATH];
TCHAR szOutputString[MAX_PATH*20];
if (bNetfx10Installed)
{
iNetfx10SPLevel = GetNetfx10SPLevel();
if (iNetfx10SPLevel > 0)
pushint(iNetfx10SPLevel);
else
pushint(-1);
}
else
{
pushint(-2);
}
} | [
"[email protected]"
]
| [
[
[
1,
867
]
]
]
|
16af9961984c8b93f29f562e4f6991c7e3420028 | 028d79ad6dd6bb4114891b8f4840ef9f0e9d4a32 | /src/drivers/tehkanwc.cpp | ba4c5ce5ca1d4d86df91d5d71e8f6528a894e7a5 | []
| no_license | neonichu/iMame4All-for-iPad | 72f56710d2ed7458594838a5152e50c72c2fb67f | 4eb3d4ed2e5ccb5c606fcbcefcb7c5a662ace611 | refs/heads/master | 2020-04-21T07:26:37.595653 | 2011-11-26T12:21:56 | 2011-11-26T12:21:56 | 2,855,022 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,162 | cpp | #include "../vidhrdw/tehkanwc.cpp"
/***************************************************************************
Tehkan World Cup - (c) Tehkan 1985
Ernesto Corvi
[email protected]
Roberto Juan Fresca
[email protected]
TODO:
- dip switches and input ports for Gridiron and Tee'd Off
NOTES:
- Samples MUST be on Memory Region 4
***************************************************************************/
#include "driver.h"
#include "vidhrdw/generic.h"
#include "cpu/z80/z80.h"
extern unsigned char *tehkanwc_videoram1;
extern size_t tehkanwc_videoram1_size;
/* from vidhrdw */
int tehkanwc_vh_start(void);
void tehkanwc_vh_stop(void);
void tehkanwc_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh);
READ_HANDLER( tehkanwc_videoram1_r );
WRITE_HANDLER( tehkanwc_videoram1_w );
READ_HANDLER( tehkanwc_scroll_x_r );
READ_HANDLER( tehkanwc_scroll_y_r );
WRITE_HANDLER( tehkanwc_scroll_x_w );
WRITE_HANDLER( tehkanwc_scroll_y_w );
WRITE_HANDLER( gridiron_led0_w );
WRITE_HANDLER( gridiron_led1_w );
static unsigned char *shared_ram;
static READ_HANDLER( shared_r )
{
return shared_ram[offset];
}
static WRITE_HANDLER( shared_w )
{
shared_ram[offset] = data;
}
static WRITE_HANDLER( sub_cpu_halt_w )
{
if (data)
cpu_set_reset_line(1,CLEAR_LINE);
else
cpu_set_reset_line(1,ASSERT_LINE);
}
static int track0[2],track1[2];
static READ_HANDLER( tehkanwc_track_0_r )
{
int joy;
joy = readinputport(10) >> (2*offset);
if (joy & 1) return -63;
if (joy & 2) return 63;
return readinputport(3 + offset) - track0[offset];
}
static READ_HANDLER( tehkanwc_track_1_r )
{
int joy;
joy = readinputport(10) >> (4+2*offset);
if (joy & 1) return -63;
if (joy & 2) return 63;
return readinputport(6 + offset) - track1[offset];
}
static WRITE_HANDLER( tehkanwc_track_0_reset_w )
{
/* reset the trackball counters */
track0[offset] = readinputport(3 + offset) + data;
}
static WRITE_HANDLER( tehkanwc_track_1_reset_w )
{
/* reset the trackball counters */
track1[offset] = readinputport(6 + offset) + data;
}
static WRITE_HANDLER( sound_command_w )
{
soundlatch_w(offset,data);
cpu_cause_interrupt(2,Z80_NMI_INT);
}
static void reset_callback(int param)
{
cpu_set_reset_line(2,PULSE_LINE);
}
static WRITE_HANDLER( sound_answer_w )
{
soundlatch2_w(0,data);
/* in Gridiron, the sound CPU goes in a tight loop after the self test, */
/* probably waiting to be reset by a watchdog */
if (cpu_get_pc() == 0x08bc) timer_set(TIME_IN_SEC(1),0,reset_callback);
}
/* Emulate MSM sound samples with counters */
static int msm_data_offs;
static READ_HANDLER( tehkanwc_portA_r )
{
return msm_data_offs & 0xff;
}
static READ_HANDLER( tehkanwc_portB_r )
{
return (msm_data_offs >> 8) & 0xff;
}
static WRITE_HANDLER( tehkanwc_portA_w )
{
msm_data_offs = (msm_data_offs & 0xff00) | data;
}
static WRITE_HANDLER( tehkanwc_portB_w )
{
msm_data_offs = (msm_data_offs & 0x00ff) | (data << 8);
}
static WRITE_HANDLER( msm_reset_w )
{
MSM5205_reset_w(0,data ? 0 : 1);
}
void tehkanwc_adpcm_int (int data)
{
static int toggle;
unsigned char *SAMPLES = memory_region(REGION_SOUND1);
int msm_data = SAMPLES[msm_data_offs & 0x7fff];
if (toggle == 0)
MSM5205_data_w(0,(msm_data >> 4) & 0x0f);
else
{
MSM5205_data_w(0,msm_data & 0x0f);
msm_data_offs++;
}
toggle ^= 1;
}
/* End of MSM with counters emulation */
static struct MemoryReadAddress readmem[] =
{
{ 0x0000, 0xbfff, MRA_ROM },
{ 0xc000, 0xc7ff, MRA_RAM },
{ 0xc800, 0xcfff, shared_r },
{ 0xd000, 0xd3ff, videoram_r },
{ 0xd400, 0xd7ff, colorram_r },
{ 0xd800, 0xddff, paletteram_r },
{ 0xde00, 0xdfff, MRA_RAM }, /* unused part of the palette RAM, I think? Gridiron uses it */
{ 0xe000, 0xe7ff, tehkanwc_videoram1_r },
{ 0xe800, 0xebff, spriteram_r }, /* sprites */
{ 0xec00, 0xec01, tehkanwc_scroll_x_r },
{ 0xec02, 0xec02, tehkanwc_scroll_y_r },
{ 0xf800, 0xf801, tehkanwc_track_0_r }, /* track 0 x/y */
{ 0xf802, 0xf802, input_port_9_r }, /* Coin & Start */
{ 0xf803, 0xf803, input_port_5_r }, /* joy0 - button */
{ 0xf810, 0xf811, tehkanwc_track_1_r }, /* track 1 x/y */
{ 0xf813, 0xf813, input_port_8_r }, /* joy1 - button */
{ 0xf820, 0xf820, soundlatch2_r }, /* answer from the sound CPU */
{ 0xf840, 0xf840, input_port_0_r }, /* DSW1 */
{ 0xf850, 0xf850, input_port_1_r }, /* DSW2 */
{ 0xf860, 0xf860, watchdog_reset_r },
{ 0xf870, 0xf870, input_port_2_r }, /* DSW3 */
{ -1 } /* end of table */
};
static struct MemoryWriteAddress writemem[] =
{
{ 0x0000, 0xbfff, MWA_ROM },
{ 0xc000, 0xc7ff, MWA_RAM },
{ 0xc800, 0xcfff, shared_w, &shared_ram },
{ 0xd000, 0xd3ff, videoram_w, &videoram, &videoram_size },
{ 0xd400, 0xd7ff, colorram_w, &colorram },
{ 0xd800, 0xddff, paletteram_xxxxBBBBGGGGRRRR_swap_w, &paletteram },
{ 0xde00, 0xdfff, MWA_RAM }, /* unused part of the palette RAM, I think? Gridiron uses it */
{ 0xe000, 0xe7ff, tehkanwc_videoram1_w, &tehkanwc_videoram1, &tehkanwc_videoram1_size },
{ 0xe800, 0xebff, spriteram_w, &spriteram, &spriteram_size }, /* sprites */
{ 0xec00, 0xec01, tehkanwc_scroll_x_w },
{ 0xec02, 0xec02, tehkanwc_scroll_y_w },
{ 0xf800, 0xf801, tehkanwc_track_0_reset_w },
{ 0xf802, 0xf802, gridiron_led0_w },
{ 0xf810, 0xf811, tehkanwc_track_1_reset_w },
{ 0xf812, 0xf812, gridiron_led1_w },
{ 0xf820, 0xf820, sound_command_w },
{ 0xf840, 0xf840, sub_cpu_halt_w },
{ -1 } /* end of table */
};
static struct MemoryReadAddress readmem_sub[] =
{
{ 0x0000, 0x7fff, MRA_ROM },
{ 0x8000, 0xc7ff, MRA_RAM },
{ 0xc800, 0xcfff, shared_r },
{ 0xd000, 0xd3ff, videoram_r },
{ 0xd400, 0xd7ff, colorram_r },
{ 0xd800, 0xddff, paletteram_r },
{ 0xde00, 0xdfff, MRA_RAM }, /* unused part of the palette RAM, I think? Gridiron uses it */
{ 0xe000, 0xe7ff, tehkanwc_videoram1_r },
{ 0xe800, 0xebff, spriteram_r }, /* sprites */
{ 0xec00, 0xec01, tehkanwc_scroll_x_r },
{ 0xec02, 0xec02, tehkanwc_scroll_y_r },
{ 0xf860, 0xf860, watchdog_reset_r },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress writemem_sub[] =
{
{ 0x0000, 0x7fff, MWA_ROM },
{ 0xc000, 0xc7ff, MWA_RAM },
{ 0xc800, 0xcfff, shared_w },
{ 0xd000, 0xd3ff, videoram_w },
{ 0xd400, 0xd7ff, colorram_w },
{ 0xd800, 0xddff, paletteram_xxxxBBBBGGGGRRRR_swap_w, &paletteram },
{ 0xde00, 0xdfff, MWA_RAM }, /* unused part of the palette RAM, I think? Gridiron uses it */
{ 0xe000, 0xe7ff, tehkanwc_videoram1_w },
{ 0xe800, 0xebff, spriteram_w }, /* sprites */
{ 0xec00, 0xec01, tehkanwc_scroll_x_w },
{ 0xec02, 0xec02, tehkanwc_scroll_y_w },
{ -1 } /* end of table */
};
static struct MemoryReadAddress readmem_sound[] =
{
{ 0x0000, 0x3fff, MRA_ROM },
{ 0x4000, 0x47ff, MRA_RAM },
{ 0xc000, 0xc000, soundlatch_r },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress writemem_sound[] =
{
{ 0x0000, 0x3fff, MWA_ROM },
{ 0x4000, 0x47ff, MWA_RAM },
{ 0x8001, 0x8001, msm_reset_w },/* MSM51xx reset */
{ 0x8002, 0x8002, MWA_NOP }, /* ?? written in the IRQ handler */
{ 0x8003, 0x8003, MWA_NOP }, /* ?? written in the NMI handler */
{ 0xc000, 0xc000, sound_answer_w }, /* answer for main CPU */
{ -1 } /* end of table */
};
static struct IOReadPort sound_readport[] =
{
{ 0x00, 0x00, AY8910_read_port_0_r },
{ 0x02, 0x02, AY8910_read_port_1_r },
{ -1 } /* end of table */
};
static struct IOWritePort sound_writeport[] =
{
{ 0x00, 0x00, AY8910_write_port_0_w },
{ 0x01, 0x01, AY8910_control_port_0_w },
{ 0x02, 0x02, AY8910_write_port_1_w },
{ 0x03, 0x03, AY8910_control_port_1_w },
{ -1 } /* end of table */
};
INPUT_PORTS_START( tehkanwc )
PORT_START /* DSW1 - Active LOW */
PORT_DIPNAME( 0x07, 0x07, DEF_STR( Coin_A ) )
PORT_DIPSETTING ( 0x01, DEF_STR( 2C_1C ) )
PORT_DIPSETTING ( 0x07, DEF_STR( 1C_1C ) )
PORT_DIPSETTING ( 0x00, DEF_STR( 2C_3C ) )
PORT_DIPSETTING ( 0x06, DEF_STR( 1C_2C ) )
PORT_DIPSETTING ( 0x05, DEF_STR( 1C_3C ) )
PORT_DIPSETTING ( 0x04, DEF_STR( 1C_4C ) )
PORT_DIPSETTING ( 0x03, DEF_STR( 1C_5C ) )
PORT_DIPSETTING ( 0x02, DEF_STR( 1C_6C ) )
PORT_DIPNAME( 0x38, 0x38, DEF_STR( Coin_B ) )
PORT_DIPSETTING ( 0x08, DEF_STR( 2C_1C ) )
PORT_DIPSETTING ( 0x38, DEF_STR( 1C_1C ) )
PORT_DIPSETTING ( 0x00, DEF_STR( 2C_3C ) )
PORT_DIPSETTING ( 0x30, DEF_STR( 1C_2C ) )
PORT_DIPSETTING ( 0x28, DEF_STR( 1C_3C ) )
PORT_DIPSETTING ( 0x20, DEF_STR( 1C_4C ) )
PORT_DIPSETTING ( 0x18, DEF_STR( 1C_5C ) )
PORT_DIPSETTING ( 0x10, DEF_STR( 1C_6C ) )
PORT_DIPNAME( 0x40, 0x40, "Extra Time per Coin" )
PORT_DIPSETTING ( 0x40, "Normal" )
PORT_DIPSETTING ( 0x00, "Double" )
PORT_DIPNAME( 0x80, 0x80, "1 Player Start" )
PORT_DIPSETTING ( 0x00, "2 Credits" )
PORT_DIPSETTING ( 0x80, "1 Credit" )
PORT_START /* DSW2 - Active LOW */
PORT_DIPNAME( 0x03, 0x03, "1P Game Time" )
PORT_DIPSETTING ( 0x00, "2:30" )
PORT_DIPSETTING ( 0x01, "2:00" )
PORT_DIPSETTING ( 0x03, "1:30" )
PORT_DIPSETTING ( 0x02, "1:00" )
PORT_DIPNAME( 0x7c, 0x7c, "2P Game Time" )
PORT_DIPSETTING ( 0x00, "5:00/3:00 Extra" )
PORT_DIPSETTING ( 0x60, "5:00/2:45 Extra" )
PORT_DIPSETTING ( 0x20, "5:00/2:35 Extra" )
PORT_DIPSETTING ( 0x40, "5:00/2:30 Extra" )
PORT_DIPSETTING ( 0x04, "4:00/2:30 Extra" )
PORT_DIPSETTING ( 0x64, "4:00/2:15 Extra" )
PORT_DIPSETTING ( 0x24, "4:00/2:05 Extra" )
PORT_DIPSETTING ( 0x44, "4:00/2:00 Extra" )
PORT_DIPSETTING ( 0x1c, "3:30/2:15 Extra" )
PORT_DIPSETTING ( 0x7c, "3:30/2:00 Extra" )
PORT_DIPSETTING ( 0x3c, "3:30/1:50 Extra" )
PORT_DIPSETTING ( 0x5c, "3:30/1:45 Extra" )
PORT_DIPSETTING ( 0x08, "3:00/2:00 Extra" )
PORT_DIPSETTING ( 0x68, "3:00/1:45 Extra" )
PORT_DIPSETTING ( 0x28, "3:00/1:35 Extra" )
PORT_DIPSETTING ( 0x48, "3:00/1:30 Extra" )
PORT_DIPSETTING ( 0x0c, "2:30/1:45 Extra" )
PORT_DIPSETTING ( 0x6c, "2:30/1:30 Extra" )
PORT_DIPSETTING ( 0x2c, "2:30/1:20 Extra" )
PORT_DIPSETTING ( 0x4c, "2:30/1:15 Extra" )
PORT_DIPSETTING ( 0x10, "2:00/1:30 Extra" )
PORT_DIPSETTING ( 0x70, "2:00/1:15 Extra" )
PORT_DIPSETTING ( 0x30, "2:00/1:05 Extra" )
PORT_DIPSETTING ( 0x50, "2:00/1:00 Extra" )
PORT_DIPSETTING ( 0x14, "1:30/1:15 Extra" )
PORT_DIPSETTING ( 0x74, "1:30/1:00 Extra" )
PORT_DIPSETTING ( 0x34, "1:30/0:50 Extra" )
PORT_DIPSETTING ( 0x54, "1:30/0:45 Extra" )
PORT_DIPSETTING ( 0x18, "1:00/1:00 Extra" )
PORT_DIPSETTING ( 0x78, "1:00/0:45 Extra" )
PORT_DIPSETTING ( 0x38, "1:00/0:35 Extra" )
PORT_DIPSETTING ( 0x58, "1:00/0:30 Extra" )
PORT_DIPNAME( 0x80, 0x80, "Game Type" )
PORT_DIPSETTING ( 0x80, "Timer In" )
PORT_DIPSETTING ( 0x00, "Credit In" )
PORT_START /* DSW3 - Active LOW */
PORT_DIPNAME( 0x03, 0x03, DEF_STR( Difficulty ) )
PORT_DIPSETTING ( 0x02, "Easy" )
PORT_DIPSETTING ( 0x03, "Normal" )
PORT_DIPSETTING ( 0x01, "Hard" )
PORT_DIPSETTING ( 0x00, "Very Hard" )
PORT_DIPNAME( 0x04, 0x04, "Timer Speed" )
PORT_DIPSETTING ( 0x04, "60/60" )
PORT_DIPSETTING ( 0x00, "55/60" )
PORT_DIPNAME( 0x08, 0x08, DEF_STR( Demo_Sounds ) )
PORT_DIPSETTING ( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING ( 0x08, DEF_STR( On ) )
PORT_START /* IN0 - X AXIS */
PORT_ANALOGX( 0xff, 0x80, IPT_TRACKBALL_X | IPF_PLAYER1, 100, 0, 0, 0, IP_KEY_NONE, IP_KEY_NONE, IP_JOY_NONE, IP_JOY_NONE )
PORT_START /* IN0 - Y AXIS */
PORT_ANALOGX( 0xff, 0x80, IPT_TRACKBALL_Y | IPF_PLAYER1, 100, 0, 0, 0, IP_KEY_NONE, IP_KEY_NONE, IP_JOY_NONE, IP_JOY_NONE )
PORT_START /* IN0 - BUTTON */
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER1 )
PORT_START /* IN1 - X AXIS */
PORT_ANALOGX( 0xff, 0x80, IPT_TRACKBALL_X | IPF_PLAYER2, 100, 0, 0, 0, IP_KEY_NONE, IP_KEY_NONE, IP_JOY_NONE, IP_JOY_NONE )
PORT_START /* IN1 - Y AXIS */
PORT_ANALOGX( 0xff, 0x80, IPT_TRACKBALL_Y | IPF_PLAYER2, 100, 0, 0, 0, IP_KEY_NONE, IP_KEY_NONE, IP_JOY_NONE, IP_JOY_NONE )
PORT_START /* IN1 - BUTTON */
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER2 )
PORT_START /* IN2 - Active LOW */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_START2 )
PORT_START /* fake port to emulate trackballs with keyboard */
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT | IPF_8WAY | IPF_PLAYER1 )
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT | IPF_8WAY | IPF_PLAYER1 )
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_PLAYER1 )
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP | IPF_8WAY | IPF_PLAYER1 )
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT | IPF_8WAY | IPF_PLAYER2 )
PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT | IPF_8WAY | IPF_PLAYER2 )
PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_PLAYER2 )
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP | IPF_8WAY | IPF_PLAYER2 )
INPUT_PORTS_END
INPUT_PORTS_START( gridiron )
PORT_START /* DSW1 - Active LOW */
PORT_DIPNAME( 0x01, 0x01, "1 Player Start" )
PORT_DIPSETTING ( 0x00, "2 Credits" )
PORT_DIPSETTING ( 0x01, "1 Credit" )
PORT_DIPNAME( 0x02, 0x02, "2 Players Start" )
PORT_DIPSETTING ( 0x02, "2 Credits" )
PORT_DIPSETTING ( 0x00, "1 Credit" )
PORT_DIPNAME( 0x04, 0x04, DEF_STR( Unknown ) )
PORT_DIPSETTING ( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING ( 0x04, DEF_STR( On ) )
PORT_DIPNAME( 0x08, 0x08, DEF_STR( Unknown ) )
PORT_DIPSETTING ( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING ( 0x08, DEF_STR( On ) )
PORT_DIPNAME( 0x10, 0x10, DEF_STR( Unknown ) )
PORT_DIPSETTING ( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING ( 0x10, DEF_STR( On ) )
PORT_DIPNAME( 0x20, 0x20, DEF_STR( Unknown ) )
PORT_DIPSETTING ( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING ( 0x20, DEF_STR( On ) )
PORT_DIPNAME( 0x40, 0x40, DEF_STR( Unknown ) )
PORT_DIPSETTING ( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING ( 0x40, DEF_STR( On ) )
PORT_DIPNAME( 0x80, 0x80, DEF_STR( Unknown ) )
PORT_DIPSETTING ( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING ( 0x80, DEF_STR( On ) )
PORT_START /* DSW2 - Active LOW */
PORT_DIPNAME( 0x03, 0x03, "1P Game Time" )
PORT_DIPSETTING ( 0x00, "2:30" )
PORT_DIPSETTING ( 0x01, "2:00" )
PORT_DIPSETTING ( 0x03, "1:30" )
PORT_DIPSETTING ( 0x02, "1:00" )
PORT_DIPNAME( 0x7c, 0x7c, "2P Game Time" )
PORT_DIPSETTING ( 0x60, "5:00/3:00 Extra" )
PORT_DIPSETTING ( 0x00, "5:00/2:45 Extra" )
PORT_DIPSETTING ( 0x20, "5:00/2:35 Extra" )
PORT_DIPSETTING ( 0x40, "5:00/2:30 Extra" )
PORT_DIPSETTING ( 0x64, "4:00/2:30 Extra" )
PORT_DIPSETTING ( 0x04, "4:00/2:15 Extra" )
PORT_DIPSETTING ( 0x24, "4:00/2:05 Extra" )
PORT_DIPSETTING ( 0x44, "4:00/2:00 Extra" )
PORT_DIPSETTING ( 0x68, "3:30/2:15 Extra" )
PORT_DIPSETTING ( 0x08, "3:30/2:00 Extra" )
PORT_DIPSETTING ( 0x28, "3:30/1:50 Extra" )
PORT_DIPSETTING ( 0x48, "3:30/1:45 Extra" )
PORT_DIPSETTING ( 0x6c, "3:00/2:00 Extra" )
PORT_DIPSETTING ( 0x0c, "3:00/1:45 Extra" )
PORT_DIPSETTING ( 0x2c, "3:00/1:35 Extra" )
PORT_DIPSETTING ( 0x4c, "3:00/1:30 Extra" )
PORT_DIPSETTING ( 0x7c, "2:30/1:45 Extra" )
PORT_DIPSETTING ( 0x1c, "2:30/1:30 Extra" )
PORT_DIPSETTING ( 0x3c, "2:30/1:20 Extra" )
PORT_DIPSETTING ( 0x5c, "2:30/1:15 Extra" )
PORT_DIPSETTING ( 0x70, "2:00/1:30 Extra" )
PORT_DIPSETTING ( 0x10, "2:00/1:15 Extra" )
PORT_DIPSETTING ( 0x30, "2:00/1:05 Extra" )
PORT_DIPSETTING ( 0x50, "2:00/1:00 Extra" )
PORT_DIPSETTING ( 0x74, "1:30/1:15 Extra" )
PORT_DIPSETTING ( 0x14, "1:30/1:00 Extra" )
PORT_DIPSETTING ( 0x34, "1:30/0:50 Extra" )
PORT_DIPSETTING ( 0x54, "1:30/0:45 Extra" )
PORT_DIPSETTING ( 0x78, "1:00/1:00 Extra" )
PORT_DIPSETTING ( 0x18, "1:00/0:45 Extra" )
PORT_DIPSETTING ( 0x38, "1:00/0:35 Extra" )
PORT_DIPSETTING ( 0x58, "1:00/0:30 Extra" )
PORT_DIPNAME( 0x80, 0x80, "Game Type?" )
PORT_DIPSETTING ( 0x80, "Timer In" )
PORT_DIPSETTING ( 0x00, "Credit In" )
PORT_START /* DSW3 - Active LOW */
PORT_DIPNAME( 0x03, 0x03, "Difficulty?" )
PORT_DIPSETTING ( 0x02, "Easy" )
PORT_DIPSETTING ( 0x03, "Normal" )
PORT_DIPSETTING ( 0x01, "Hard" )
PORT_DIPSETTING ( 0x00, "Very Hard" )
PORT_DIPNAME( 0x04, 0x04, "Timer Speed?" )
PORT_DIPSETTING ( 0x04, "60/60" )
PORT_DIPSETTING ( 0x00, "55/60" )
PORT_DIPNAME( 0x08, 0x08, "Demo Sounds?" )
PORT_DIPSETTING ( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING ( 0x08, DEF_STR( On ) )
PORT_START /* IN0 - X AXIS */
PORT_ANALOG( 0xff, 0x80, IPT_TRACKBALL_X | IPF_PLAYER1, 100, 63, 0, 0 )
PORT_START /* IN0 - Y AXIS */
PORT_ANALOG( 0xff, 0x80, IPT_TRACKBALL_Y | IPF_PLAYER1, 100, 63, 0, 0 )
PORT_START /* IN0 - BUTTON */
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER1 )
PORT_START /* IN1 - X AXIS */
PORT_ANALOG( 0xff, 0x80, IPT_TRACKBALL_X | IPF_PLAYER2, 100, 63, 0, 0 )
PORT_START /* IN1 - Y AXIS */
PORT_ANALOG( 0xff, 0x80, IPT_TRACKBALL_Y | IPF_PLAYER2, 100, 63, 0, 0 )
PORT_START /* IN1 - BUTTON */
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER2 )
PORT_START /* IN2 - Active LOW */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_START2 )
PORT_START /* no fake port here */
PORT_BIT( 0xff, IP_ACTIVE_HIGH, IPT_UNUSED )
INPUT_PORTS_END
INPUT_PORTS_START( teedoff )
PORT_START /* DSW1 - Active LOW */
PORT_DIPNAME( 0x03, 0x03, DEF_STR( Coin_A ) )
PORT_DIPSETTING ( 0x02, DEF_STR( 2C_1C ) )
PORT_DIPSETTING ( 0x03, DEF_STR( 1C_1C ) )
PORT_DIPSETTING ( 0x01, DEF_STR( 1C_2C ) )
PORT_DIPSETTING ( 0x00, DEF_STR( 1C_3C ) )
PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Coin_B ) )
PORT_DIPSETTING ( 0x08, DEF_STR( 2C_1C ) )
PORT_DIPSETTING ( 0x0c, DEF_STR( 1C_1C ) )
PORT_DIPSETTING ( 0x04, DEF_STR( 1C_2C ) )
PORT_DIPSETTING ( 0x00, DEF_STR( 1C_3C ) )
PORT_DIPNAME( 0x10, 0x10, DEF_STR( Unknown ) )
PORT_DIPSETTING ( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING ( 0x10, DEF_STR( On ) )
PORT_DIPNAME( 0x20, 0x20, DEF_STR( Unknown ) )
PORT_DIPSETTING ( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING ( 0x20, DEF_STR( On ) )
PORT_DIPNAME( 0x40, 0x40, DEF_STR( Unknown ) )
PORT_DIPSETTING ( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING ( 0x40, DEF_STR( On ) )
PORT_DIPNAME( 0x80, 0x80, DEF_STR( Unknown ) )
PORT_DIPSETTING ( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING ( 0x80, DEF_STR( On ) )
PORT_START /* DSW2 - Active LOW */
PORT_DIPNAME( 0xff, 0xff, DEF_STR( Unknown ) )
PORT_DIPSETTING ( 0xff, DEF_STR( Off ) )
PORT_DIPSETTING ( 0x00, DEF_STR( On ) )
PORT_START /* DSW3 - Active LOW */
PORT_DIPNAME( 0x0f, 0x0f, DEF_STR( Unknown ) )
PORT_DIPSETTING ( 0x0f, DEF_STR( Off ) )
PORT_DIPSETTING ( 0x00, DEF_STR( On ) )
PORT_START /* IN0 - X AXIS */
PORT_ANALOG( 0xff, 0x80, IPT_TRACKBALL_X | IPF_PLAYER1, 100, 63, 0, 0 )
PORT_START /* IN0 - Y AXIS */
PORT_ANALOG( 0xff, 0x80, IPT_TRACKBALL_Y | IPF_PLAYER1, 100, 63, 0, 0 )
PORT_START /* IN0 - BUTTON */
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER1 )
PORT_START /* IN1 - X AXIS */
PORT_ANALOG( 0xff, 0x80, IPT_TRACKBALL_X | IPF_PLAYER2, 100, 63, 0, 0 )
PORT_START /* IN1 - Y AXIS */
PORT_ANALOG( 0xff, 0x80, IPT_TRACKBALL_Y | IPF_PLAYER2, 100, 63, 0, 0 )
PORT_START /* IN1 - BUTTON */
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER2 )
PORT_START /* IN2 - Active LOW */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_START2 )
PORT_START /* no fake port here */
PORT_BIT( 0xff, IP_ACTIVE_HIGH, IPT_UNUSED )
INPUT_PORTS_END
static struct GfxLayout charlayout =
{
8,8, /* 8*8 characters */
512, /* 512 characters */
4, /* 4 bits per pixel */
{ 0, 1, 2, 3 }, /* the bitplanes are packed in one nibble */
{ 1*4, 0*4, 3*4, 2*4, 5*4, 4*4, 7*4, 6*4 },
{ 0*32, 1*32, 2*32, 3*32, 4*32, 5*32, 6*32, 7*32 },
32*8 /* every char takes 32 consecutive bytes */
};
static struct GfxLayout spritelayout =
{
16,16, /* 16*16 sprites */
512, /* 512 sprites */
4, /* 4 bits per pixel */
{ 0, 1, 2, 3 }, /* the bitplanes are packed in one nibble */
{ 1*4, 0*4, 3*4, 2*4, 5*4, 4*4, 7*4, 6*4,
8*32+1*4, 8*32+0*4, 8*32+3*4, 8*32+2*4, 8*32+5*4, 8*32+4*4, 8*32+7*4, 8*32+6*4 },
{ 0*32, 1*32, 2*32, 3*32, 4*32, 5*32, 6*32, 7*32,
16*32, 17*32, 18*32, 19*32, 20*32, 21*32, 22*32, 23*32 },
128*8 /* every char takes 32 consecutive bytes */
};
static struct GfxLayout tilelayout =
{
16,8, /* 16*8 characters */
1024, /* 1024 characters */
4, /* 4 bits per pixel */
{ 0, 1, 2, 3 }, /* the bitplanes are packed in one nibble */
{ 1*4, 0*4, 3*4, 2*4, 5*4, 4*4, 7*4, 6*4,
32*8+1*4, 32*8+0*4, 32*8+3*4, 32*8+2*4, 32*8+5*4, 32*8+4*4, 32*8+7*4, 32*8+6*4 },
{ 0*32, 1*32, 2*32, 3*32, 4*32, 5*32, 6*32, 7*32 },
64*8 /* every char takes 64 consecutive bytes */
};
static struct GfxDecodeInfo gfxdecodeinfo[] =
{
{ REGION_GFX1, 0, &charlayout, 0, 16 }, /* Colors 0 - 255 */
{ REGION_GFX2, 0, &spritelayout, 256, 8 }, /* Colors 256 - 383 */
{ REGION_GFX3, 0, &tilelayout, 512, 16 }, /* Colors 512 - 767 */
{ -1 } /* end of array */
};
static struct AY8910interface ay8910_interface =
{
2, /* 2 chips */
1536000, /* ??? */
{ 25, 25 },
{ 0, tehkanwc_portA_r },
{ 0, tehkanwc_portB_r },
{ tehkanwc_portA_w, 0 },
{ tehkanwc_portB_w, 0 }
};
static struct MSM5205interface msm5205_interface =
{
1, /* 1 chip */
384000, /* 384KHz */
{ tehkanwc_adpcm_int },/* interrupt function */
{ MSM5205_S48_4B }, /* 8KHz */
{ 25 }
};
static struct MachineDriver machine_driver_tehkanwc =
{
/* basic machine hardware */
{
{
CPU_Z80,
4608000, /* 18.432000 / 4 */
readmem,writemem,0,0,
interrupt,1
},
{
CPU_Z80,
4608000, /* 18.432000 / 4 */
readmem_sub,writemem_sub,0,0,
interrupt,1
},
{
CPU_Z80, /* communication is bidirectional, can't mark it as AUDIO_CPU */
4608000, /* 18.432000 / 4 */
readmem_sound,writemem_sound,sound_readport,sound_writeport,
interrupt,1
}
},
60, DEFAULT_REAL_60HZ_VBLANK_DURATION, /* frames per second, vblank duration */
10, /* 10 CPU slices per frame - seems enough to keep the CPUs in sync */
0,
/* video hardware */
32*8, 32*8, { 0*8, 32*8-1, 2*8, 30*8-1 },
gfxdecodeinfo,
768, 768,
0,
VIDEO_TYPE_RASTER | VIDEO_MODIFIES_PALETTE,
0,
tehkanwc_vh_start,
tehkanwc_vh_stop,
tehkanwc_vh_screenrefresh,
/* sound hardware */
0,0,0,0,
{
{
SOUND_AY8910,
&ay8910_interface
},
{
SOUND_MSM5205,
&msm5205_interface
}
}
};
/***************************************************************************
Game driver(s)
***************************************************************************/
ROM_START( tehkanwc )
ROM_REGION( 0x10000, REGION_CPU1 ) /* 64k for code */
ROM_LOAD( "twc-1.bin", 0x0000, 0x4000, 0x34d6d5ff )
ROM_LOAD( "twc-2.bin", 0x4000, 0x4000, 0x7017a221 )
ROM_LOAD( "twc-3.bin", 0x8000, 0x4000, 0x8b662902 )
ROM_REGION( 0x10000, REGION_CPU2 ) /* 64k for code */
ROM_LOAD( "twc-4.bin", 0x0000, 0x8000, 0x70a9f883 )
ROM_REGION( 0x10000, REGION_CPU3 ) /* 64k for code */
ROM_LOAD( "twc-6.bin", 0x0000, 0x4000, 0xe3112be2 )
ROM_REGION( 0x04000, REGION_GFX1 | REGIONFLAG_DISPOSE )
ROM_LOAD( "twc-12.bin", 0x00000, 0x4000, 0xa9e274f8 ) /* fg tiles */
ROM_REGION( 0x10000, REGION_GFX2 | REGIONFLAG_DISPOSE )
ROM_LOAD( "twc-8.bin", 0x00000, 0x8000, 0x055a5264 ) /* sprites */
ROM_LOAD( "twc-7.bin", 0x08000, 0x8000, 0x59faebe7 )
ROM_REGION( 0x10000, REGION_GFX3 | REGIONFLAG_DISPOSE )
ROM_LOAD( "twc-11.bin", 0x00000, 0x8000, 0x669389fc ) /* bg tiles */
ROM_LOAD( "twc-9.bin", 0x08000, 0x8000, 0x347ef108 )
ROM_REGION( 0x8000, REGION_SOUND1 ) /* ADPCM samples */
ROM_LOAD( "twc-5.bin", 0x0000, 0x4000, 0x444b5544 )
ROM_END
ROM_START( gridiron )
ROM_REGION( 0x10000, REGION_CPU1 ) /* 64k for code */
ROM_LOAD( "gfight1.bin", 0x0000, 0x4000, 0x51612741 )
ROM_LOAD( "gfight2.bin", 0x4000, 0x4000, 0xa678db48 )
ROM_LOAD( "gfight3.bin", 0x8000, 0x4000, 0x8c227c33 )
ROM_REGION( 0x10000, REGION_CPU2 ) /* 64k for code */
ROM_LOAD( "gfight4.bin", 0x0000, 0x4000, 0x8821415f )
ROM_REGION( 0x10000, REGION_CPU3 ) /* 64k for code */
ROM_LOAD( "gfight5.bin", 0x0000, 0x4000, 0x92ca3c07 )
ROM_REGION( 0x04000, REGION_GFX1 | REGIONFLAG_DISPOSE )
ROM_LOAD( "gfight7.bin", 0x00000, 0x4000, 0x04390cca ) /* fg tiles */
ROM_REGION( 0x10000, REGION_GFX2 | REGIONFLAG_DISPOSE )
ROM_LOAD( "gfight8.bin", 0x00000, 0x4000, 0x5de6a70f ) /* sprites */
ROM_LOAD( "gfight9.bin", 0x04000, 0x4000, 0xeac9dc16 )
ROM_LOAD( "gfight10.bin", 0x08000, 0x4000, 0x61d0690f )
/* 0c000-0ffff empty */
ROM_REGION( 0x10000, REGION_GFX3 | REGIONFLAG_DISPOSE )
ROM_LOAD( "gfight11.bin", 0x00000, 0x4000, 0x80b09c03 ) /* bg tiles */
ROM_LOAD( "gfight12.bin", 0x04000, 0x4000, 0x1b615eae )
/* 08000-0ffff empty */
ROM_REGION( 0x8000, REGION_SOUND1 ) /* ADPCM samples */
ROM_LOAD( "gfight6.bin", 0x0000, 0x4000, 0xd05d463d )
ROM_END
ROM_START( teedoff )
ROM_REGION( 0x10000, REGION_CPU1 ) /* 64k for code */
ROM_LOAD( "to-1.bin", 0x0000, 0x4000, 0xcc2aebc5 )
ROM_LOAD( "to-2.bin", 0x4000, 0x4000, 0xf7c9f138 )
ROM_LOAD( "to-3.bin", 0x8000, 0x4000, 0xa0f0a6da )
ROM_REGION( 0x10000, REGION_CPU2 ) /* 64k for code */
ROM_LOAD( "to-4.bin", 0x0000, 0x8000, 0xe922cbd2 )
ROM_REGION( 0x10000, REGION_CPU3 ) /* 64k for code */
ROM_LOAD( "to-6.bin", 0x0000, 0x4000, 0xd8dfe1c8 )
ROM_REGION( 0x04000, REGION_GFX1 | REGIONFLAG_DISPOSE )
ROM_LOAD( "to-12.bin", 0x00000, 0x4000, 0x4f44622c ) /* fg tiles */
ROM_REGION( 0x10000, REGION_GFX2 | REGIONFLAG_DISPOSE )
ROM_LOAD( "to-8.bin", 0x00000, 0x8000, 0x363bd1ba ) /* sprites */
ROM_LOAD( "to-7.bin", 0x08000, 0x8000, 0x6583fa5b )
ROM_REGION( 0x10000, REGION_GFX3 | REGIONFLAG_DISPOSE )
ROM_LOAD( "to-11.bin", 0x00000, 0x8000, 0x1ec00cb5 ) /* bg tiles */
ROM_LOAD( "to-9.bin", 0x08000, 0x8000, 0xa14347f0 )
ROM_REGION( 0x8000, REGION_SOUND1 ) /* ADPCM samples */
ROM_LOAD( "to-5.bin", 0x0000, 0x8000, 0xe5e4246b )
ROM_END
GAME( 1985, tehkanwc, 0, tehkanwc, tehkanwc, 0, ROT0, "Tehkan", "Tehkan World Cup" )
GAME( 1985, gridiron, 0, tehkanwc, gridiron, 0, ROT0, "Tehkan", "Gridiron Fight" )
GAMEX(1986, teedoff, 0, tehkanwc, teedoff, 0, ROT90, "Tecmo", "Tee'd Off", GAME_NOT_WORKING )
| [
"[email protected]"
]
| [
[
[
1,
805
]
]
]
|
4b8c1ce1e533d0aba3fe1270edc16d5d845cbe2b | 0557ee5f99eef983a388d3ab0da10a8bebbd050d | /huffman_zip_heap.cpp | 77cdd9d263e667ed9ddc2e1aa7011a702555b080 | []
| no_license | edwardbadboy/huffman-zip | 67e8a8df7ce1a44f4912f1ef65cbc787957aeded | efeb7cc35961a1753dfaf5b76a536e9569f0b256 | refs/heads/master | 2016-09-15T19:52:04.265224 | 2011-05-30T02:21:29 | 2011-05-30T02:21:29 | 2,412,496 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 23,978 | cpp | //notice:没有考虑字节序的问题
#include <iostream>//基本流操作
#include <fstream>//文件
#include <vector>//需要使用向量
#include <queue>
#include <algorithm>//需要使用标准库的几个算法
#include <limits>//需要使用long最大值
#include <cstdlib>//需要使用system函数
#include "Bitstream.imp.h"//使用了开源的Bitstream库
//每个压缩文件的文件头都设置为下面的字符串,用以识别文件是否是本程序压缩过的文件
#define MAGIC_VERSION "huffman zipped file version 1"
//using namespace std;
using std::vector;
using std::string;
using std::priority_queue;
using std::binary_function;
using std::istream;
using std::ostream;
using std::ifstream;
using std::ofstream;
using std::cout;
using std::cin;
using std::clog;
using std::ios;
using std::ios_base;
using std::endl;
using std::dec;
using std::hex;
using std::numeric_limits;
using namespace Costella;//使用了开源的Bitstream库,这个库的内容全在此名称空间里
//huffman树的一个节点
struct HuffmanNode{
long lchild;//左孩子下标
long rchild;//右孩子下标
long parent;//双亲下标
long weight;//权重
};
//词汇表的一个项目
struct HuffmanToken{
unsigned char byte;//单词内容
long weight;//权重
};
//编码表的一个项目
struct HuffmanCode{
unsigned char byte;//单词
vector<int> code;//单词对应编码,由一连串的0、1序列组成
};
typedef vector<HuffmanNode> HuffmanTree;//huffman树
typedef vector<HuffmanToken> TokenList;//词汇表
typedef vector<HuffmanCode> HuffmanCodes;//编码表
struct HuffmanNodeComparer //: public std::binary_function<HuffmanNode*, HuffmanNode*, bool>
{
bool operator()(const HuffmanNode *l, const HuffmanNode *r) const{
return l->weight > r->weight;
}
};
typedef priority_queue<HuffmanNode*, vector<HuffmanNode*>, HuffmanNodeComparer> HuffmanQueue;//用于提取最小根元素的优先队列
//检测词汇表项目的权重是否是0
bool is_empty_token(const HuffmanToken &tk){
return tk.weight==0;
}
/*
bool compare_HuffmanNode(const HuffmanNode &node1,const HuffmanNode &node2){
return (node1.lchild==node2.lchild) && (node1.rchild==node2.rchild) && (node1.parent==node2.parent) && (node1.weight==node2.weight);
}
bool compare_HuffmanToken(const HuffmanToken &ht1,const HuffmanToken &ht2){
return (ht1.byte==ht2.byte) && (ht1.weight==ht2.weight);
}*/
//遍历输入文件,建立词汇表
TokenList collect_word_list(istream &in){
TokenList tokens;
TokenList result_tokens;
unsigned char byte;
//每个字节作为一个单词,由于1字节内可以有0-255共256种可能的值,因此单词一共有256个
//在词汇表中插入256个单词,令每个单词的权为0,作为初始值
for(int i=0;i<256;++i){//i的类型不能是char,否则会在256的时候回绕到0
HuffmanToken token={i,0};
tokens.push_back(token);
}
//遍历输入文件,统计每个单词出现的次数
while(in){
if(!in.read(reinterpret_cast<char*>(&byte),sizeof(byte))){
break;
}
++(tokens[byte].weight);//统计每个单词出现的次数
}
//将没出现过的单词过滤掉,只出现过的单词到我们的结果中
remove_copy_if(tokens.begin(),tokens.end(),back_inserter(result_tokens),is_empty_token);
//remove_copy_if是标准库的
return result_tokens;
}
//用词汇表的权重初始化huffman树(其实是森林,最后才合并成树)
void init_huffman_tree(HuffmanTree &ht,const TokenList &tokens){
HuffmanNode default_node={-1,-1,-1,0};//初始每个节点的左右孩子和父亲下标都是-1,权重是0
TokenList::size_type n;
ht.clear();
n=tokens.size();
ht.assign(2*n-1,default_node);//n个词汇的huffman树需要2*n-1个节点,把这2*n-1个节点都设置成默认值
for(TokenList::size_type i=0;i<n;++i){
ht[i].weight=tokens[i].weight;//用词汇表中的权重初始化huffman树的前n个节点
}
return;
}
void init_huffman_queue(HuffmanQueue &q, const HuffmanTree &ht, HuffmanTree::size_type size){
for(HuffmanTree::size_type i=0; i < size; ++i){
q.push( const_cast<HuffmanNode*>(&ht[i]) );
}
return;
}
//寻找huffman树(其实是森林,最后才合并成树)中权重最小和次小的根节点
//使用优先队列
void find_min_weight_positions(const HuffmanTree &ht, HuffmanQueue &q,long &min_pos1,long &min_pos2){
HuffmanNode *n1=NULL, *n2=NULL;
n1=q.top();
min_pos1= n1 - &ht[0];
q.pop();
n2=q.top();
min_pos2= n2 - &ht[0];
q.pop();
return;
}
//创建huffman树,找最小元素使用优先队列
void create_huffman_tree(HuffmanTree &ht, const TokenList &tokens){
init_huffman_tree(ht, tokens);//用词汇表的全部n个项目的权重初始化树(其实是森林)
HuffmanTree::size_type nodecount=ht.size();
TokenList::size_type wordcount=tokens.size();
HuffmanQueue q;
init_huffman_queue(q, ht, wordcount);
//现在0到n-1个节点的权重是词汇表中的权重值
//从n到2*n-2做共n-1次合并,每次找到最小和次小的根的权重,合并根和权重,合并后的节点存储下来
for(TokenList::size_type i=wordcount; i<nodecount; ++i){
long min_pos1=-1,min_pos2=-1;//最小值和次小值
find_min_weight_positions(ht,q,min_pos1,min_pos2);//找到权重最小和次小的两个根
ht[min_pos1].parent=ht[min_pos2].parent=i;//这两个根变为当前节点的子节点
ht[i].lchild=min_pos1;//一个作为当前的左孩子
ht[i].rchild=min_pos2;//另一个作为当前节点的右孩子
ht[i].weight=ht[min_pos1].weight+ht[min_pos2].weight;//当前节点的权重为两个子节点权重的和
q.push(&ht[i]);
}
//循环结束后ht[hi.size()-1]中的节点就是huffman树的根,0到n-1是叶子节点,剩下的是中间节点
return;
}
//find_min_weight_positions的非优先队列版
//void find_min_weight_positions(const HuffmanTree &ht,long end,long &min_pos1,long &min_pos2){
//long min_weight1,min_weight2;//最小的和次小的节点权重
//min_weight1=min_weight2=numeric_limits<long>::max();//初始化权重为long型的最大值
//long i;
//for(i=0;i<end;++i){
//if(ht[i].parent!=-1){//parent=-1的才是根节点,其他的忽略
//continue;
//}
//if(ht[i].weight<=min_weight1){//这里判断关系时,必须写成小于等于,如果只写成小于,那么存在两个同weight而pos不同的元素时,就会漏掉其中一个
//min_weight2=min_weight1;//如果当前节点比已找到的最小值还小,那么最小值就要变成当前节点,原来的最小值变为次小值
//min_pos2=min_pos1;
//min_weight1=ht[i].weight;
//min_pos1=i;
//}else if(ht[i].weight<min_weight2){//如果当前节点比次小值小,那么就记录新的次小值
//min_weight2=ht[i].weight;
//min_pos2=i;
//}
//}
//return;
//}
//创建huffman树的非优先队列版
//void create_huffman_tree(HuffmanTree &ht,const TokenList &tokens){
//init_huffman_tree(ht,tokens);//用词汇表的全部n个项目的权重初始化树(其实是森林)
//HuffmanTree::size_type nodecount=ht.size();
////现在0到n-1个节点的权重是词汇表中的权重值
////从n到2*n-2做共n-1次合并,每次找到最小和次小的根的权重,合并根和权重,合并后的节点存储下来
//for(TokenList::size_type i=wtokens.size(); i<nodecount; ++i){
//long min_pos1=-1,min_pos2=-1;//最小值和次小值
//find_min_weight_positions(ht,i,min_pos1,min_pos2);//找到权重最小和次小的两个根
//ht[min_pos1].parent=ht[min_pos2].parent=i;//这两个根变为当前节点的子节点
//ht[i].lchild=min_pos1;//一个作为当前的左孩子
//ht[i].rchild=min_pos2;//另一个作为当前节点的右孩子
//ht[i].weight=ht[min_pos1].weight+ht[min_pos2].weight;//当前节点的权重为两个子节点权重的和
//}
////循环结束后ht[hi.size()-1]中的节点就是huffman树的根,0到n-1是叶子节点,剩下的是中间节点
//return;
//}
//通过huffman树,创建某个单词的huffman编码
void create_huffman_code(const HuffmanTree &ht,long ht_index,unsigned char byte,HuffmanCode &hc){
long i=ht_index;//我们要创建编码的单词在huffman树中的下标
hc.byte=byte;//记录我们要创建编码的单词
//从huffman树的叶子节点开始往父节点走
//如果当前节点是父节点的左孩子,那么编码为0,是右孩子,编码为1
//就这样走到根节点后,求得了一连串编码,然后把它反转过来,就是需要的huffman编码
while(ht[i].parent!=-1){//根节点的parent都是-1,如果还没走到根节点,就继续走
if(ht[ht[i].parent].lchild==i){//如果当前节点是父节点的左孩子
hc.code.push_back(0);//新增加编码0
}else{//如果当前节点是父节点的右孩子
hc.code.push_back(1);//新增加编码1
}
i=ht[i].parent;//往根节点走一步
}
reverse(hc.code.begin(),hc.code.end());//反转刚才得到的编码,才是我们要求的结果
//reverse是标准库的算法
return;
}
//通过huffman树,为所有单词创建编码
void create_huffman_codes(const HuffmanTree &ht, const TokenList &tokens, HuffmanCodes &hcs){
hcs.clear();
TokenList::size_type wordcount=tokens.size();
//huffman编码集合初始化
for(int i=0;i<256;++i){//总共有256种可能的单词
HuffmanCode hc;hc.byte=i;
hcs.push_back(hc);
}
//对每个在词汇表中的单词创建编码,不在词汇表中的单词就不管了
for(TokenList::size_type i=0; i<wordcount; ++i){
HuffmanCode hc;
unsigned char byte=tokens[i].byte;
create_huffman_code(ht,i,byte,hc);//为词汇表的第i项创建编码
hcs[byte].code=hc.code;//将创建好的编码存放到huffman编码集合中覆盖原来的默认值
}
//循环结束后,huffman编码集合hcs中包含256个元素,其中在词汇表中出现过的单词已经创建了编码
//没有在词汇表中出现的单词就没有创建
//要求假设字节(单词)的值为100,那么其对应编码就是hcs[100].code
}
//将我们创建的huffman编码集合的某一项的编码打印出来
void print_huffman_code(const HuffmanCode &hc,const TokenList &tk,long &tk_i){
if(hc.code.size()==0){//没在词汇表中的单词是没有编码的,不打印,直接返回
return;
}
if(isgraph(hc.byte)){
cout<<"'"<<hc.byte<<"'";
}else{
cout<<"0x"<<hex<< static_cast<int>(hc.byte)<<dec;
}
cout<<"\tweight "<<tk[tk_i].weight<<"\tcode:";
vector<int>::const_iterator iter, iter_end;
for(iter=hc.code.begin(), iter_end=hc.code.end(); iter!=iter_end; ++iter){
cout<<" "<<(*iter);
}
++tk_i;
cout<<endl;
}
//打印我们创建的huffman编码
void print_huffman_codes(const HuffmanCodes &hcs,const TokenList &tk){
long tk_i=0;
HuffmanCodes::const_iterator iter, iter_end;
for(iter=hcs.begin(), iter_end=hcs.end(); iter!=iter_end; ++iter){//遍历编码集合
print_huffman_code((*iter),tk,tk_i);//打印每一项
}
}
//将huffman树的某一节点输出到文件中
bool write_huffman_node(ostream &out,const HuffmanNode &node){
out.write(reinterpret_cast<const char*>(&(node.lchild)),sizeof(node.lchild));//没有考虑字节序
out.write(reinterpret_cast<const char*>(&(node.rchild)),sizeof(node.rchild));
out.write(reinterpret_cast<const char*>(&(node.parent)),sizeof(node.parent));
//out.write(reinterpret_cast<const char*>(&(node.weight)),sizeof(node.weight));//不用输出权重,权重只在求huffman树的时候有用
if(out){
return true;
}else{
return false;
}
}
//将词汇表的某一项输出到文件中
bool write_huffman_token(ostream &out,const HuffmanToken &tk){
out.write(reinterpret_cast<const char*>(&(tk.byte)),sizeof(tk.byte));
out.write(reinterpret_cast<const char*>(&(tk.weight)),sizeof(tk.weight));
if(out){
return true;
}else{
return false;
}
}
//将huffman树和词汇表输出到文件中
bool write_huffman_tree(ostream &out,const HuffmanTree &ht,const TokenList &tokens)
{
long n=tokens.size();
out.write(reinterpret_cast<const char*>(&n),sizeof(n));//输出词汇表的项目数,不考虑字节序
if(!out){
return false;
}
HuffmanTree::const_iterator huffiter, huffiter_end;//输出huffman树的每个节点
for(huffiter=ht.begin(), huffiter_end=ht.end(); huffiter!=huffiter_end; ++huffiter){
if(write_huffman_node(out,(*huffiter))==false){
return false;
}
}
TokenList::const_iterator tokeniter, tokeniter_end;//输出词汇表的每个节点
for(tokeniter=tokens.begin(), tokeniter_end=tokens.end(); tokeniter!=tokeniter_end; ++tokeniter){
if(write_huffman_token(out,(*tokeniter))==false){
return false;
}
}
return true;
}
//从文件中读取一个huffman树的一个节点
bool read_huffman_node(istream &in,HuffmanNode &node){
in.read(reinterpret_cast<char*>(&(node.lchild)),sizeof(node.lchild));
in.read(reinterpret_cast<char*>(&(node.rchild)),sizeof(node.rchild));
in.read(reinterpret_cast<char*>(&(node.parent)),sizeof(node.parent));
//in.read(reinterpret_cast<char*>(&(node.weight)),sizeof(node.weight));//不用读权重,因为我们没有把权重写到文件里去
if(in){
return true;
}else{
return false;
}
}
//从文件中读取词汇表的一项
bool read_huffman_token(istream &in,HuffmanToken &tk){
in.read(reinterpret_cast<char*>(&(tk.byte)),sizeof(tk.byte));
in.read(reinterpret_cast<char*>(&(tk.weight)),sizeof(tk.weight));
if(in){
return true;
}else{
return false;
}
}
//从文件中读取huffman树和词汇表
bool read_huffman_tree(istream &in,HuffmanTree &ht,TokenList &tokens)
{
long n=0,i=0,ht_n=0;;
in.read(reinterpret_cast<char*>(&n),sizeof(n));//读取词汇表的长度
if(!in){
return false;
}
ht.clear();
ht_n=2*n-1;
for(i=0;i<ht_n;++i){//读取2*n-1个huffman树的节点
HuffmanNode node;
if(read_huffman_node(in,node)==false){
return false;
}
ht.push_back(node);
}
tokens.clear();
for(i=0;i<n;++i){//读取全部的词汇表
HuffmanToken tk;
if(read_huffman_token(in,tk)==false){
return false;
}
tokens.push_back(tk);
}
return true;
}
//将标志头写到压缩文件里去
bool write_huffman_zip_header(ostream &out){
out<<MAGIC_VERSION<<"\n";
if(out){
return true;
}else{
return false;
}
}
//从压缩文件里读取第一行作为标志头
string read_huffman_zip_header(istream &in){
string header;
getline(in,header);
return header;
}
//将编码过的内容写到文件里去
void write_huffman_code(Bitstream::Out<long> &bout, const vector<int> &code){
vector<int>::const_iterator iter, iter_end;
for(iter=code.begin(), iter_end=code.end(); iter!=iter_end; ++iter){
bout.boolean((*iter)==1);//把编码的每个项目写到比特流里
}
//关于bout.boolean:如果bout.boolean(true),会写比特'1'到文件里,如果是bout.boolean(false),就写'0'到文件里。
return;
}
//通过为输入文件创建huffman的编码,并把编码后的内容写到输出文件
bool huffman_data_encode(istream &in,ostream &out,const HuffmanCodes &hcs)
{
long write_start_pos=out.tellp();//我们需要记录一开始写输出文件的位置,等下要跳回来
long bit_count=0;//记录一共写了多少个比特
//要在文件中记录一共写了多少个比特,但是这个值要写完整个文件才知道
//所以我们要为这个值在文件中预留一个位置,写完整个文件后再跳回来把实际写了多少个比特写到文件中
out.write(reinterpret_cast<const char*>(&bit_count),sizeof(bit_count));
if(!out){
return false;
}
Bitstream::Out<long> bout(out);//创建比特流输出对象
bit_count=bout.position();
while(in){
unsigned char byte=0;
if(!in.read(reinterpret_cast<char*>(&byte),sizeof(byte))){//从输入文件中读一个单词
break;
}
write_huffman_code(bout,hcs[byte].code);//把此单词对应的编码写到输出文件中
if(!out){
return false;
}
}
bit_count=bout.position()-bit_count;//看看我们写了多少个比特
bout.flush();//把缓存中的数据全部实际的写到文件中
out.seekp(write_start_pos,ios::beg);//跳回文件头部
out.write(reinterpret_cast<const char*>(&bit_count),sizeof(bit_count));//记录一下我们写了多少比特
out.seekp(0,ios::end);//跳到文件尾部,这个操作其实可以不做,因为等下我们就要关闭文件了,不再写了
if(out){
return true;
}else{
return false;
}
}
void print_tokens(const TokenList &tokens){
TokenList::size_type wordcount=tokens.size();
for(TokenList::size_type i=0; i<wordcount; ++i){
cout<<i<<" token "<<tokens[i].byte<<" weight "<<tokens[i].weight<<"\r\n";
}
return;
}
//使用huffman树的原理进行压缩的函数
bool huffman_zip(const char *in_filename,const char *out_filename)
{
HuffmanTree ht;//huffman树
TokenList tokens;//词汇表
HuffmanCodes hcs;//huffman编码集合
ifstream in;//输入文件
ofstream out;//输出文件
bool r=false;//操作是否成功,不成功就是false
//必须用binary方式打开输入文件,否则系统会在遇到0x0d连着0x0a的时候,把0x0d吞掉
//0x0d是'\r',0x0a是'\n',如果不使用binary标志,就默认用文本模式打开流,因此会出现
//这种转换
in.open(in_filename,ios_base::in|ios_base::binary);
if(!in){
clog<<"无法打开输入文件:"<<in_filename<<endl;
return false;
}
tokens=collect_word_list(in);//扫描输入文件,得到词汇表
if(tokens.size()==0){
clog<<"文件为空:"<<in_filename<<endl;
return false;
}
//print_tokens(tokens);
//文件已经读到头了,现在是无效状态,我们要把它倒回头,等下好开始读里面的内容好用来做huffman压缩
in.clear();
in.seekg(0,ios::beg);
if(!in){
clog<<"无法移动输入文件指针:"<<in_filename<<endl;
return false;
}
create_huffman_tree(ht,tokens);//从词汇表和权重创建huffman树
create_huffman_codes(ht,tokens,hcs);//从huffman树、词汇表创建huffman编码集合
/*cout<<"下面是生成的huffman编码表:"<<endl;//输出我们创建的编码表看看
print_huffman_codes(hcs,tokens);*/
out.open(out_filename,ios_base::out|ios_base::binary);//打开输出文件,此处一定要用binary模式
if(!out){
clog<<"无法打开输出文件:"<<out_filename<<endl;
return false;
}
if(write_huffman_zip_header(out)==false){//写标志头
clog<<"无法写输出文件:"<<out_filename<<endl;
return false;
}
if(write_huffman_tree(out,ht,tokens)==false){//写huffman树和词汇表
clog<<"无法写输出文件:"<<out_filename<<endl;
return false;
}
if(huffman_data_encode(in,out,hcs)==false){//把in里的内容编码后输出到out
clog<<"无法写输出文件:"<<out_filename<<endl;
return false;
}
in.close();
out.close();
return true;
}
//通过从输入文件中读出的huffman树,对输入解码并把结果写到输出文件
bool huffman_data_decode(istream &in,ostream &out,const HuffmanTree &ht,const TokenList &tokens)
{
long bit_count=0;//从文件中读出原来写下的比特数,放在这里
long read_count=0;//记录我们在后面操作中实际读出的比特数
in.read(reinterpret_cast<char*>(&bit_count),sizeof(bit_count));//读出此文件后面内容占的比特数
if(!in){
return false;
}
if(tokens.size()==1){//如果词汇表只有一项,那就简单了,直接把这一项输出weight次到out中就行
for(long i=0;i<tokens[0].weight;++i){
out.write(reinterpret_cast<const char*>(&(tokens[0].byte)),sizeof(tokens[0].byte));
if(!out){
return false;
}
}
return true;
}
Bitstream::In<long> bin(in);//比特流的输入
//解码的过程是,从huffman树的根开始往叶子走,在读到比特0时往左,在读到1的时候往右
//走到叶子的时候,就是解压缩的结果
long rootpos=ht.size()-1;
long huffpos=rootpos;//当前解码的位置
while(in && read_count<bit_count){//如果我们还没解码完所有的比特
bool bit=false;//读出的比特是0还是1,如果是0,bit就是false,如果是1,bit就是true
bin.boolean(bit);//从文件中读出一个比特存到变量bit里
if(!in){break;}//文件读完了
if(bit){
if(ht[huffpos].rchild==-1){
return false;//没路可走了,说明解码出错,输入文件可能被损坏了
}else{
huffpos=ht[huffpos].rchild;//在读到1的时候往右走
}
}else{
if(ht[huffpos].lchild==-1){
return false;//没路可走了,说明解码出错,输入文件可能被损坏了
}else{
huffpos=ht[huffpos].lchild;//在读到比特0时往左走
}
}
//看看是不是已经走到叶子了
if(ht[huffpos].lchild==-1 && ht[huffpos].rchild==-1){//叶子节点的lchild和rchild肯定都是-1
//把叶子节点对应的单词输出到out
out.write(reinterpret_cast<const char*>(&(tokens[huffpos].byte)),sizeof(tokens[huffpos].byte));
if(!out){
return false;
}
huffpos=rootpos;//把当前位置移动到根节点,开始下一轮解码
}
++read_count;//积累我们已经处理过的比特数
}
return true;
}
//使用huffman树的原理进行解压缩的函数
bool huffman_unzip(const char *in_filename,const char *out_filename)
{
HuffmanTree ht;//huffman树
TokenList tokens;//词汇表
ifstream in;//输入文件(压缩过的文件)
ofstream out;//输出文件(解压缩后的文件)
string header;//压缩过的文件头部的标志
bool r=false;//操作成功为true,操作失败为false
in.open(in_filename,ios_base::in|ios_base::binary);//必须用binary模式打开,否则系统会作多余的转换
if(!in){
clog<<"无法打开输入文件:"<<in_filename<<endl;
return false;
}
header=read_huffman_zip_header(in);//读压缩文件头
if(header!=MAGIC_VERSION){//判断是否是我们压缩过的文件
clog<<"无法读取输入文件,或着它不是hzip格式的压缩文件:"<<in_filename<<endl;
return false;
}
if(read_huffman_tree(in,ht,tokens)==false){//从文件中读出huffman树和词汇表,重建起这两个数据结构
clog<<"无法从输入文件中读取元信息:"<<in_filename<<endl;
}
out.open(out_filename,ios_base::out|ios_base::binary);//必须用binary模式打开,否则系统会作多余的转换
if(!out){
clog<<"无法打开输出文件:"<<out_filename<<endl;
return false;
}
r=huffman_data_decode(in,out,ht,tokens);//对输入文件解码
if(r==false){
clog<<"输入文件已损坏或写输出文件失败:"<<endl<<"\t"<<in_filename<<endl<<"\t"<<out_filename<<endl;
return false;
}
in.close();
out.close();
return r;
}
int main(int argc, char* argv[])
{
string in_filename,zip_filename,out_filename;
cout<<"请输入文件名或完整路径(回车表示输入完毕,不支持中文):"<<endl;
getline(cin,in_filename);
zip_filename=in_filename+".hzip";
cout<<"正在压缩……"<<endl;
if(huffman_zip(in_filename.c_str(),zip_filename.c_str())){
cout<<"压缩已完成,输出文件:"<<zip_filename<<endl;
}else{
cout<<"压缩失败,请查看历史记录以确定错误信息。"<<endl;
system("pause");
return 0;
}
out_filename=in_filename+".unhzip";
cout<<"正在解压……"<<endl;
if(huffman_unzip(zip_filename.c_str(),out_filename.c_str())){
cout<<"解压已完成,输出文件:"<<out_filename<<endl;
}else{
cout<<"解压失败,请查看历史记录以确定错误信息。"<<endl;
}
system("pause");
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
630
]
]
]
|
7769f64bf8fed76dd8744af214a0c0ee56048b1a | b4d726a0321649f907923cc57323942a1e45915b | /CODE/MENUUI/playermenu.cpp | 9b9ca1886b5383f2e139109756b34f43e7d34e66 | []
| no_license | chief1983/Imperial-Alliance | f1aa664d91f32c9e244867aaac43fffdf42199dc | 6db0102a8897deac845a8bd2a7aa2e1b25086448 | refs/heads/master | 2016-09-06T02:40:39.069630 | 2010-10-06T22:06:24 | 2010-10-06T22:06:24 | 967,775 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 61,205 | cpp | /*
* Copyright (C) Volition, Inc. 1999. All rights reserved.
*
* All source code herein is the property of Volition, Inc. You may not sell
* or otherwise commercially exploit the source or things you created based on the
* source.
*
*/
/*
* $Logfile: /Freespace2/code/MenuUI/PlayerMenu.cpp $
* $Revision: 1.1.1.1 $
* $Date: 2004/08/13 22:47:41 $
* $Author: Spearhawk $
*
* Code to drive the Player Select initial screen
*
* $Log: playermenu.cpp,v $
* Revision 1.1.1.1 2004/08/13 22:47:41 Spearhawk
* no message
*
* Revision 1.1.1.1 2004/08/13 21:47:52 Darkhill
* no message
*
* Revision 2.7 2003/11/11 02:15:43 Goober5000
* ubercommit - basically spelling and language fixes with some additional
* warnings disabled
* --Goober5000
*
* Revision 2.6 2003/10/27 23:04:22 randomtiger
* Added -no_set_gamma flags
* Fixed up some more non standard res stuff
* Improved selection of device type, this includes using a pure device when allowed which means dev should not use Get* functions in D3D
* Made fade in credits work
* Stopped a call to gr_reser_lighting() in non htl mode when the pointer was NULL, was causing a crash loading a fogged level
* Deleted directx8 directory content, has never been needed.
*
* Revision 2.5 2003/08/20 08:11:00 wmcoolmon
* Added error screens to the barracks and start screens when a pilot file can't be deleted
*
* Revision 2.4 2003/03/18 10:07:03 unknownplayer
* The big DX/main line merge. This has been uploaded to the main CVS since I can't manage to get it to upload to the DX branch. Apologies to all who may be affected adversely, but I'll work to debug it as fast as I can.
*
* Revision 2.3 2003/01/14 04:00:15 Goober5000
* allowed for up to 256 main halls
* --Goober5000
*
* Revision 2.2.2.1 2002/09/24 18:56:43 randomtiger
* DX8 branch commit
*
* This is the scub of UP's previous code with the more up to date RT code.
* For full details check previous dev e-mails
*
* Revision 2.2 2002/08/04 05:12:42 penguin
* Display fs2_open version instead of "Freespace 2"
*
* Revision 2.1 2002/08/01 01:41:06 penguin
* The big include file move
*
* Revision 2.0 2002/06/03 04:02:24 penguin
* Warpcore CVS sync
*
* Revision 1.2 2002/05/10 20:42:44 mharris
* use "ifndef NO_NETWORK" all over the place
*
* Revision 1.1 2002/05/02 18:03:09 mharris
* Initial checkin - converted filenames and includes to lower case
*
*
* 43 11/02/99 11:42a Jefff
* fixed copyright symbol in german fonts
*
* 42 10/27/99 12:27a Jefff
* localized tips correctly
*
* 41 9/13/99 4:52p Dave
* RESPAWN FIX
*
* 40 9/02/99 11:10a Jefff
* fixed 1024 list display bug - was only showing 8 pilots at a time
*
* 39 8/26/99 8:51p Dave
* Gave multiplayer TvT messaging a heavy dose of sanity. Cheat codes.
*
* 38 8/26/99 9:45a Dave
* First pass at easter eggs and cheats.
*
* 37 8/16/99 6:39p Jefff
*
* 36 8/16/99 6:37p Jefff
* minor string alterations
*
* 35 8/05/99 4:17p Dave
* Tweaks to client interpolation.
*
* 34 8/05/99 11:29a Mikek
* Jacked up number of comments from 20 to 40, thereby doubling the
* quality of our game.
*
* 33 8/04/99 10:53a Dave
* Added title to the user tips popup.
*
* 32 8/03/99 3:21p Jefff
*
* 31 8/03/99 10:32a Jefff
* raised location of bottom_text to not interfere w/ logo. changed
* "please enter callsign" to "type callsign and press enter"
*
* 30 8/02/99 9:13p Dave
* Added popup tips.
*
* 29 7/30/99 10:29a Jefff
* fixed colors of bottom display texts
*
* 28 7/27/99 7:17p Jefff
* Replaced some art text with XSTR() text.
*
* 27 7/19/99 2:06p Jasons
* Remove all palette stuff from player select menu.
*
* 26 7/15/99 9:20a Andsager
* FS2_DEMO initial checkin
*
* 25 7/09/99 9:51a Dave
* Added thick polyline code.
*
* 24 6/11/99 11:13a Dave
* last minute changes before press tour build.
*
* 23 5/21/99 6:45p Dave
* Sped up ui loading a bit. Sped up localization disk access stuff. Multi
* start game screen, multi password, and multi pxo-help screen.
*
* 22 4/25/99 3:02p Dave
* Build defines for the E3 build.
*
* 21 3/25/99 2:31p Neilk
* Coordinate changes to handle new artwork
*
* 20 2/25/99 4:19p Dave
* Added multiplayer_beta defines. Added cd_check define. Fixed a few
* release build warnings. Added more data to the squad war request and
* response packets.
*
* 19 2/01/99 5:55p Dave
* Removed the idea of explicit bitmaps for buttons. Fixed text
* highlighting for disabled gadgets.
*
* 18 1/30/99 5:08p Dave
* More new hi-res stuff.Support for nice D3D textures.
*
* 17 1/30/99 1:53a Dave
* Fix some harcoded coords.
*
* 16 1/30/99 1:28a Dave
* 1024x768 full support.
*
* 15 1/29/99 1:25p Dave
* New code for choose pilot screen.
*
* 14 1/29/99 12:47a Dave
* Put in sounds for beam weapon. A bunch of interface screens (tech
* database stuff).
*
* 13 1/12/99 12:53a Dave
* More work on beam weapons - made collision detection very efficient -
* collide against all object types properly - made 3 movement types
* smooth. Put in test code to check for possible non-darkening pixels on
* object textures.
*
* 12 12/18/98 1:13a Dave
* Rough 1024x768 support for Direct3D. Proper detection and usage through
* the launcher.
*
* 11 12/06/98 2:36p Dave
* Drastically improved nebula fogging.
*
* 10 12/01/98 6:20p Dave
* Removed tga test bitmap code.
*
* 9 12/01/98 4:46p Dave
* Put in targa bitmap support (16 bit).
*
* 8 11/30/98 1:07p Dave
* 16 bit conversion, first run.
*
* 7 11/20/98 11:16a Dave
* Fixed up IPX support a bit. Making sure that switching modes and
* loading/saving pilot files maintains proper state.
*
* 6 11/19/98 4:19p Dave
* Put IPX sockets back in psnet. Consolidated all multiplayer config
* files into one.
*
* 5 11/05/98 4:18p Dave
* First run nebula support. Beefed up localization a bit. Removed all
* conditional compiles for foreign versions. Modified mission file
* format.
*
* 4 10/13/98 9:28a Dave
* Started neatening up freespace.h. Many variables renamed and
* reorganized. Added AlphaColors.[h,cpp]
*
* 3 10/09/98 2:57p Dave
* Starting splitting up OS stuff.
*
* 2 10/07/98 10:53a Dave
* Initial checkin.
*
* 1 10/07/98 10:49a Dave
*
*
* $NoKeywords: $
*
*/
#include <ctype.h>
#include <fstream>
#include <iostream>
#include "menuui/playermenu.h"
#include "graphics/2d.h"
#include "ui/ui.h"
#include "gamesnd/gamesnd.h"
#include "playerman/player.h"
#include "cfile/cfile.h"
#include "io/key.h"
#include "playerman/managepilot.h"
#include "missionui/missionscreencommon.h"
#include "bmpman/bmpman.h"
#include "freespace2/freespace.h"
#include "parse/parselo.h"
#include "gamesequence/gamesequence.h"
#include "io/timer.h"
#include "cmdline/cmdline.h"
#include "osapi/osregistry.h"
#include "palman/palman.h"
#include "menuui/mainhallmenu.h"
#include "popup/popup.h"
#include "io/mouse.h"
#include "globalincs/alphacolors.h"
#include "localization/localize.h"
#include "debugconsole/dbugfile.h"
#include "Mission/MissionCampaign.h"
#include "anim/animplay.h"
#include "Anim/PackUnpack.h"
#include "EH_Medals/idline.h"
#include "EH_Medals/convert.h"
#include "Popup/popuptc.h"
#ifndef NO_NETWORK
#include "network/multi.h"
#endif
// --------------------------------------------------------------------------------------------------------
// Demo title screen
#ifdef FS2_DEMO
static int Demo_title_active = 0;
static int Demo_title_bitmap = -1;
static int Demo_title_expire_timestamp = 0;
static int Demo_title_need_fade_in = 1;
static char *Demo_title_bitmap_filename = NOX("DemoTitle1");
#endif
// --------------------------------------------------------------------------------------------------------
// PLAYER SELECT defines
//
//#define MAX_PLAYER_SELECT_LINES 8 // max # of pilots displayed at once
int Player_select_max_lines[GR_NUM_RESOLUTIONS] = { // max # of pilots displayed at once
12, // GR_640
15 // GR_1024
};
// button control defines
#define NUM_PLAYER_SELECT_BUTTONS 9 // button control defines
#define CREATE_PILOT_BUTTON 0 //
#define CLONE_BUTTON 1 //
#define DELETE_BUTTON 2 //
#define SCROLL_LIST_UP_BUTTON 3 //
#define SCROLL_LIST_DOWN_BUTTON 4 //
#define ACCEPT_BUTTON 5 //
#define SINGLE_BUTTON 6 //
#define MULTI_BUTTON 7
#define TC_BUTTON 8 //
// list text display area
int Choose_list_coords[GR_NUM_RESOLUTIONS][4] = {
{ // GR_640
60, 245, 180, 180//170, 265, 400, 87 60 245
},
{ // GR_1024
96,392, 288,288//183, 186, 640, 139
}
};
char *Player_select_background_bitmap_name[GR_NUM_RESOLUTIONS] = {
"ChoosePilot",
"2_ChoosePilot"
};
char *Player_select_background_mask_bitmap[GR_NUM_RESOLUTIONS] = {
"ChoosePilot-m",
"2_ChoosePilot-m"
};
// #define PLAYER_SELECT_PALETTE NOX("ChoosePilotPalette") // palette for the screen
#define PLAYER_SELECT_MAIN_HALL_OVERLAY NOX("MainHall1") // main hall help overlay
// convenient struct for handling all button controls
struct barracks_buttons {
char *filename;
int x, y, xt, yt;
int hotspot;
UI_BUTTON button; // because we have a class inside this struct, we need the constructor below..
barracks_buttons(char *name, int x1, int y1, int xt1, int yt1, int h) : filename(name), x(x1), y(y1), xt(xt1), yt(yt1), hotspot(h) {}
};
static barracks_buttons Player_select_buttons[GR_NUM_RESOLUTIONS][NUM_PLAYER_SELECT_BUTTONS] = {
{ // GR_640
// create, clone and delete (respectively)
barracks_buttons("CPB_00", 285, 245, 175, 500, 0), //114, 205, 117, 240,
barracks_buttons("CPB_01", 285, 309, 175, 240, 1), //172, 205, 175, 240
barracks_buttons("CPB_02", 285, 277, 229, 240, 2), //226, 205, 229, 240,
// scroll up, scroll down, and accept (respectively)
barracks_buttons("CPB_03", 245, 245, -1, -1, 3), //429, 213, -1, -1
barracks_buttons("CPB_04", 245, 405, -1, -1, 4), //456, 213, -1, -1
barracks_buttons("CPB_05", 387, 147, 484, 246, 5), //481, 207, 484, 246,
// single player select and multiplayer select, create tc pilot, respectively
barracks_buttons("CPB_06", 285, 341, 430, 108, 6), //428, 82, 430, 108,
barracks_buttons("CPB_07", 285, 373, 481, 108, 7), //477, 82, 481, 108,
barracks_buttons("CPB_08", 285, 405, -1, -1, 8)
},
{ // GR_1024
// create, clone and delete (respectively)
barracks_buttons("2_CPB_00", 460, 404, 199, 384, 0),
barracks_buttons("2_CPB_01", 460, 504, 292, 384, 1),
barracks_buttons("2_CPB_02", 460, 454, 379, 384, 2),
// scroll up, scroll down, and accept (respectively)
barracks_buttons("2_CPB_03", 396, 404, -1, -1, 3),
barracks_buttons("2_CPB_04", 396, 654, -1, -1, 4),
barracks_buttons("2_CPB_05", 614, 258, 787, 394, 5),
// single player select and multiplayer select, create tc pilot, respectively
barracks_buttons("2_CPB_06", 460, 554, 700, 173, 6),
barracks_buttons("2_CPB_07", 460, 604, 782, 173, 7),
barracks_buttons("2_CPB_08", 460, 654, -1, -1, 8)
}
};
// FIXME add to strings.tbl
#define PLAYER_SELECT_NUM_TEXT 9
UI_XSTR Player_select_text[GR_NUM_RESOLUTIONS][PLAYER_SELECT_NUM_TEXT] = {
{ // GR_640
{ "Add Pilot", -1, 310, 251, UI_XSTR_COLOR_GREEN, -1, NULL },
{ "Clone Pilot", -1, 310, 315, UI_XSTR_COLOR_GREEN, -1, NULL },
{ "Delete Pilot", -1, 310, 283, UI_XSTR_COLOR_GREEN, -1, NULL },
{ "", -1, 0, 0, UI_XSTR_COLOR_GREEN, -1, NULL },
{ "", -1, 0, 0, UI_XSTR_COLOR_GREEN, -1, NULL },
{ "", -1, 0, 0, UI_XSTR_COLOR_GREEN, -1, NULL },
{ "Single Player", -1, 310, 347, UI_XSTR_COLOR_GREEN, -1, NULL },
{ "Multi Player", -1, 310, 379, UI_XSTR_COLOR_GREEN, -1, NULL },
{ "Create TIE Corps Mutli Player", -1, 311, 411, UI_XSTR_COLOR_GREEN, -1, NULL},
},
{ // GR_1024
{ "Add Pilot", -1, 496, 415, UI_XSTR_COLOR_GREEN, -1, NULL },
{ "Clone Pilot", -1, 496, 515, UI_XSTR_COLOR_GREEN, -1, NULL },
{ "Delete Pilot", -1, 496, 465, UI_XSTR_COLOR_GREEN, -1, NULL },
{ "", -1, 0, 0, UI_XSTR_COLOR_GREEN, -1, NULL },
{ "", -1, 0, 0, UI_XSTR_COLOR_GREEN, -1, NULL },
{ "", -1, 0, 0, UI_XSTR_COLOR_GREEN, -1, NULL },
{ "Single Player", -1, 496, 565, UI_XSTR_COLOR_GREEN, -1, NULL },
{ "Multi Player", -1, 496, 615, UI_XSTR_COLOR_GREEN, -1, NULL },
{ "Create TIE Corps Mutli Player", -1, 496, 665, UI_XSTR_COLOR_GREEN, -1, NULL},
}
};
UI_WINDOW Player_select_window; // ui window for this screen
UI_BUTTON Player_select_list_region; // button for detecting mouse clicks on this screen
UI_INPUTBOX Player_select_input_box; // input box for adding new pilot names
// #define PLAYER_SELECT_PALETTE_FNAME NOX("InterfacePalette")
int Player_select_background_bitmap; // bitmap for this screen
// int Player_select_palette; // palette bitmap for this screen
int Player_select_autoaccept = 0;
// int Player_select_palette_set = 0;
// flag indicating if this is the absolute first pilot created and selected. Used to determine
// if the main hall should display the help overlay screen
int Player_select_very_first_pilot = 0;
int Player_select_initial_count = 0;
char Player_select_very_first_pilot_callsign[CALLSIGN_LEN + 2];
extern int Main_hall_bitmap; // bitmap handle to the main hall bitmap
int Player_select_mode; // single or multiplayer - never set directly. use player_select_init_player_stuff()
int Player_select_num_pilots; // # of pilots on the list
int Player_select_list_start; // index of first list item to start displaying in the box
int Player_select_pilot; // index into the Pilot array of which is selected as the active pilot
int Player_select_input_mode; // 0 if the player _isn't_ typing a callsign, 1 if he is
char Pilots_arr[MAX_PILOTS][MAX_FILENAME_LEN];
char *Pilots[MAX_PILOTS];
int Player_select_clone_flag; // clone the currently selected pilot
char Player_select_last_pilot[CALLSIGN_LEN + 10]; // callsign of the last used pilot, or none if there wasn't one
int Player_select_last_is_multi;
int Player_select_force_main_hall = 0;
// So the wave file can play a bit after the screen is loaded
int Reg_desk_sound_timestamp = -1;
int Reg_desk_intro_wave_id = -1;
// notification text areas
static int Player_select_bottom_text_y[GR_NUM_RESOLUTIONS] = {
392, // GR_640
502 // GR_1024
};
static int Player_select_middle_text_y[GR_NUM_RESOLUTIONS] = {
253, // GR_640
404 // GR_1024
};
char Player_select_bottom_text[150] = "";
char Player_select_middle_text[150] = "";
void player_select_set_bottom_text(char *txt);
void player_select_set_middle_text(char *txt);
// filenames of the door animations
char *door_anim_name[GR_NUM_RESOLUTIONS] = {
"CPB_05.ani",
"2_CPB_05.ani"
};
// first pair : coords of where to play a given door anim
// second pair : center of a given door anim in windowed mode
int door_anim_coords[GR_NUM_RESOLUTIONS][4] = {
// GR_640
{387, 147, 400, 200},
// GR_1024
{614,258, 400, 200}
};
// the door animations themselves
anim *reg_desk_door_anim;
// the instance of a given door animation
anim_instance *reg_desk_door_anim_instance;
// handle to sound to play when door opens
int reg_desk_door_sound_handle = -1;
int on_door = 0;
void maybe_anim_door();
void reg_desk_render_door_anim(float frametime);
void reg_desk_handle_region_anim();
// FORWARD DECLARATIONS
void player_select_init_player_stuff(int mode); // switch between single and multiplayer modes
void player_select_set_input_mode(int n);
void player_select_button_pressed(int n);
void player_select_scroll_list_up();
void player_select_scroll_list_down();
int player_select_create_new_pilot();
void player_select_delete_pilot();
void player_select_display_all_text();
void player_select_display_copyright();
void player_select_set_bottom_text(char *txt);
void player_select_set_controls(int gray);
void player_select_draw_list();
void player_select_process_noninput(int k);
void player_select_process_input(int k);
int player_select_pilot_file_filter(char *filename);
int player_select_get_last_pilot_info();
void player_select_eval_very_first_pilot();
void player_select_commit();
void player_select_cancel_create();
void reg_desk_maybe_show_button_text();
void reg_desk_force_button_frame();
int test[4];
int door_timestamp = -1;
int door_moving = 0;
// basically, gray out all controls (gray == 1), or ungray the controls (gray == 0)
void player_select_set_controls(int gray)
{
int idx;
for(idx=0;idx<NUM_PLAYER_SELECT_BUTTONS;idx++){
if(gray){
Player_select_buttons[gr_screen.res][idx].button.disable();
} else {
Player_select_buttons[gr_screen.res][idx].button.enable();
}
}
}
#include "graphics/font.h"
// functions for selecting single/multiplayer pilots at the very beginning of Freespace
void player_select_init()
{
int i;
barracks_buttons *b;
UI_WINDOW *w;
test[0] = bm_load("test0000");
test[1] = bm_load("test0001");
// start a looping ambient sound
main_hall_start_ambient();
Player_select_force_main_hall = 0;
reg_desk_door_anim = NULL;
reg_desk_door_anim = anim_load(door_anim_name[gr_screen.res]);
if (reg_desk_door_anim == NULL) {
Warning(LOCATION, "Could not load reg desk door anim\n");
}
// null out the animation instances
reg_desk_door_anim_instance = NULL;
// clear sound handle
reg_desk_door_sound_handle = -1;
#ifdef FS2_DEMO
/*
Demo_title_bitmap = bm_load(Demo_title_bitmap_filename);
if ( Demo_title_bitmap >= 0 ) {
#ifndef HARDWARE_ONLY
palette_use_bm_palette(Demo_title_bitmap);
#endif
Demo_title_active = 1;
Demo_title_expire_timestamp = timestamp(5000);
} else {
Demo_title_active = 0;
}
*/
Demo_title_active = 0;
#endif
// create the UI window
Player_select_window.create(0, 0, gr_screen.max_w, gr_screen.max_h, 0);
Player_select_window.set_mask_bmap(Player_select_background_mask_bitmap[gr_screen.res]);
// initialize the control buttons
for (i=0; i<NUM_PLAYER_SELECT_BUTTONS; i++) {
b = &Player_select_buttons[gr_screen.res][i];
// create the button
if ( (i == SCROLL_LIST_UP_BUTTON) || (i == SCROLL_LIST_DOWN_BUTTON) )
b->button.create(&Player_select_window, NULL, b->x, b->y, 60, 30, 1, 1);
else
b->button.create(&Player_select_window, NULL, b->x, b->y, 60, 30, 1, 1);
// set its highlight action
if (i != ACCEPT_BUTTON)
b->button.set_highlight_action(common_play_highlight_sound);
// set its animation bitmaps
b->button.set_bmaps(b->filename);
// link the mask hotspot
b->button.link_hotspot(b->hotspot);
}
// add some text
w = &Player_select_window;
//w->add_XSTR("Create", 1034, Player_select_buttons[gr_screen.res][CREATE_PILOT_BUTTON].xt, Player_select_buttons[gr_screen.res][CREATE_PILOT_BUTTON].yt, &Player_select_buttons[gr_screen.res][CREATE_PILOT_BUTTON].button, UI_XSTR_COLOR_GREEN);
//w->add_XSTR("Clone", 1040, Player_select_buttons[gr_screen.res][CLONE_BUTTON].xt, Player_select_buttons[gr_screen.res][CLONE_BUTTON].yt, &Player_select_buttons[gr_screen.res][CLONE_BUTTON].button, UI_XSTR_COLOR_GREEN);
//w->add_XSTR("Remove", 1038, Player_select_buttons[gr_screen.res][DELETE_BUTTON].xt, Player_select_buttons[gr_screen.res][DELETE_BUTTON].yt, &Player_select_buttons[gr_screen.res][DELETE_BUTTON].button, UI_XSTR_COLOR_GREEN);
//w->add_XSTR("Select", 1039, Player_select_buttons[gr_screen.res][ACCEPT_BUTTON].xt, Player_select_buttons[gr_screen.res][ACCEPT_BUTTON].yt, &Player_select_buttons[gr_screen.res][ACCEPT_BUTTON].button, UI_XSTR_COLOR_PINK);
//w->add_XSTR("Single", 1041, Player_select_buttons[gr_screen.res][SINGLE_BUTTON].xt, Player_select_buttons[gr_screen.res][SINGLE_BUTTON].yt, &Player_select_buttons[gr_screen.res][SINGLE_BUTTON].button, UI_XSTR_COLOR_GREEN);
//w->add_XSTR("Multi", 1042, Player_select_buttons[gr_screen.res][MULTI_BUTTON].xt, Player_select_buttons[gr_screen.res][MULTI_BUTTON].yt, &Player_select_buttons[gr_screen.res][MULTI_BUTTON].button, UI_XSTR_COLOR_GREEN);
// for(i=0; i<PLAYER_SELECT_NUM_TEXT; i++) {
// w->add_XSTR(&Player_select_text[gr_screen.res][i]);
// }
// create the list button text select region
Player_select_list_region.create(&Player_select_window, "", Choose_list_coords[gr_screen.res][0], Choose_list_coords[gr_screen.res][1], Choose_list_coords[gr_screen.res][2], Choose_list_coords[gr_screen.res][3], 0, 1);
Player_select_list_region.hide();
// create the pilot callsign input box
Player_select_input_box.create(&Player_select_window, Choose_list_coords[gr_screen.res][0], Choose_list_coords[gr_screen.res][1], Choose_list_coords[gr_screen.res][2] , CALLSIGN_LEN - 1, "", UI_INPUTBOX_FLAG_INVIS | UI_INPUTBOX_FLAG_KEYTHRU | UI_INPUTBOX_FLAG_LETTER_FIRST);
Player_select_input_box.set_valid_chars(VALID_PILOT_CHARS);
Player_select_input_box.hide();
Player_select_input_box.disable();
// not currently entering any text
Player_select_input_mode = 0;
// set up hotkeys for buttons so we draw the correct animation frame when a key is pressed
Player_select_buttons[gr_screen.res][SCROLL_LIST_UP_BUTTON].button.set_hotkey(KEY_UP);
Player_select_buttons[gr_screen.res][SCROLL_LIST_DOWN_BUTTON].button.set_hotkey(KEY_DOWN);
Player_select_buttons[gr_screen.res][ACCEPT_BUTTON].button.set_hotkey(KEY_ENTER);
Player_select_buttons[gr_screen.res][CREATE_PILOT_BUTTON].button.set_hotkey(KEY_C);
// disable the single player button in the multiplayer beta
#ifdef MULTIPLAYER_BETA_BUILD
Player_select_buttons[gr_screen.res][SINGLE_BUTTON].button.hide();
Player_select_buttons[gr_screen.res][SINGLE_BUTTON].button.disable();
#elif defined(E3_BUILD) || defined(PRESS_TOUR_BUILD)
Player_select_buttons[gr_screen.res][MULTI_BUTTON].button.hide();
Player_select_buttons[gr_screen.res][MULTI_BUTTON].button.disable();
#endif
// attempt to load in the background bitmap
Player_select_background_bitmap = bm_load(Player_select_background_bitmap_name[gr_screen.res]);
Assert(Player_select_background_bitmap >= 0);
// load in the palette for the screen
// Player_select_palette = bm_load(PLAYER_SELECT_PALETTE);
// Player_select_palette_set = 0;
// unset the very first pilot data
Player_select_very_first_pilot = 0;
Player_select_initial_count = -1;
memset(Player_select_very_first_pilot_callsign, 0, CALLSIGN_LEN + 2);
// if(Player_select_num_pilots == 0){
// Player_select_autoaccept = 1;
// }
// if we found a pilot
//#if defined(DEMO) || defined(OEM_BUILD) || defined(E3_BUILD) || defined(PRESS_TOUR_BUILD) // not for FS2_DEMO
#if defined(MP_DEMO)
player_select_init_player_stuff(PLAYER_SELECT_MODE_MULTI);
#else
player_select_init_player_stuff(PLAYER_SELECT_MODE_SINGLE);
if (player_select_get_last_pilot_info()) {
if (Player_select_last_is_multi) {
player_select_init_player_stuff(PLAYER_SELECT_MODE_MULTI);
} else {
player_select_init_player_stuff(PLAYER_SELECT_MODE_SINGLE);
}
}
// otherwise go to the single player mode by default
else {
player_select_init_player_stuff(PLAYER_SELECT_MODE_SINGLE);
}
#endif
if((Player_select_num_pilots == 1) && Player_select_input_mode){
Player_select_autoaccept = 1;
}
}
#ifdef FS2_DEMO
// Display the demo title screen
void demo_title_blit()
{
int k;
Mouse_hidden = 1;
if ( timestamp_elapsed(Demo_title_expire_timestamp) ) {
Demo_title_active = 0;
}
k = game_poll();
if ( k > 0 ) {
Demo_title_active = 0;
}
if ( Demo_title_need_fade_in ) {
gr_fade_out(0);
}
gr_set_bitmap(Demo_title_bitmap);
gr_bitmap(0,0);
gr_flip();
if ( Demo_title_need_fade_in ) {
gr_fade_in(0);
Demo_title_need_fade_in = 0;
}
if ( !Demo_title_active ) {
gr_fade_out(0);
Mouse_hidden = 0;
}
}
#endif
void player_select_do(float frametime)
{
int k = 0;
#ifdef FS2_DEMO
if ( Demo_title_active ) {
// demo_title_blit();
return;
}
#endif
//if ( !Player_select_palette_set ) {
// Assert(Player_select_palette >= 0);
//#ifndef HARDWARE_ONLY
// palette_use_bm_palette(Player_select_palette);
//#endif
// Player_select_palette_set = 1;
// }
// set the input box at the "virtual" line 0 to be active so the player can enter a callsign
if (Player_select_input_mode){
Player_select_input_box.set_focus();
}
// process any ui window stuff
k = Player_select_window.process();
if(k){
extern void game_process_cheats(int k);
game_process_cheats(k);
}
switch(k){
// switch between single and multiplayer modes
case KEY_TAB :
#if defined(DEMO) || defined(OEM_BUILD) // not for FS2_DEMO
break;
#else
if(Player_select_input_mode){
gamesnd_play_iface(SND_GENERAL_FAIL);
break;
}
// play a little sound
gamesnd_play_iface(SND_USER_SELECT);
if(Player_select_mode == PLAYER_SELECT_MODE_MULTI){
//player_select_set_middle_text(XSTR( "Single-Player Mode", 376));
// reinitialize as single player mode
player_select_init_player_stuff(PLAYER_SELECT_MODE_SINGLE);
} else if(Player_select_mode == PLAYER_SELECT_MODE_SINGLE){
//player_select_set_middle_text(XSTR( "Multiplayer Mode", 377));
// reinitialize as multiplayer mode
player_select_init_player_stuff(PLAYER_SELECT_MODE_MULTI);
}
break;
#endif
}
// draw the player select pseudo-dialog over it
/*gr_reset_clip();
gr_clear();
gr_set_font(FONT2);
gr_set_bitmap( Current_font->bitmap_id );
static int r = 0;
gr_aabitmap_ex(0, 0, 640, 480, 0, 0);
//gr_print_screen("font");*/
gr_set_bitmap(Player_select_background_bitmap);
gr_bitmap(0,0);
/*if (timestamp_elapsed(door_timestamp))
gr_set_bitmap(test[1]);
else
if (door_moving) {
door_timestamp = timestamp(2000);
gr_set_bitmap(test[0]);
gr_bitmap(10, 10);
//}*/
// press the accept button
if (Player_select_autoaccept) {
Player_select_buttons[gr_screen.res][ACCEPT_BUTTON].button.press_button();
}
// draw any ui window stuf
Player_select_window.draw();
// light up the correct mode button (single or multi)
/*if (Player_select_mode == PLAYER_SELECT_MODE_SINGLE){
Player_select_buttons[gr_screen.res][SINGLE_BUTTON].button.draw_forced(2);
} else {
Player_select_buttons[gr_screen.res][MULTI_BUTTON].button.draw_forced(2);
}*/
// draw the pilot list text
player_select_draw_list();
// draw copyright message on the bottom on the screen
player_select_display_copyright();
if (!Player_select_input_mode) {
player_select_process_noninput(k);
} else {
player_select_process_input(k);
}
// draw any pending messages on the bottom or middle of the screen
player_select_display_all_text();
reg_desk_handle_region_anim();
maybe_anim_door();
reg_desk_render_door_anim(frametime);
reg_desk_force_button_frame();
reg_desk_maybe_show_button_text();
gr_flip();
if (Reg_desk_sound_timestamp < 0)
{
// hot pickup line
//gamesnd_play_iface(SND_REGDESK);
Reg_desk_intro_wave_id = snd_play(&Snds_iface[SND_REGDESK], 0.0f, 1.0f, SND_PRIORITY_MUST_PLAY);
Reg_desk_sound_timestamp = 1;
}
//player_select_scroll_list_up();
}
void player_select_close()
{
// destroy the player select window
Player_select_window.destroy();
// if we're in input mode - we should undo the pilot create reqeust
if(Player_select_input_mode){
player_select_cancel_create();
}
// actually set up the Player struct here
if((Player_select_pilot == -1) || (Player_select_num_pilots == 0)){
nprintf(("General","WARNING! No pilot selected! We should be exiting the game now!\n"));
return;
}
// unload all bitmaps
if(Player_select_background_bitmap >= 0){
bm_release(Player_select_background_bitmap);
Player_select_background_bitmap = -1;
}
// if(Player_select_palette >= 0){
// bm_release(Player_select_palette);
//Player_select_palette = -1;
// }
// unload door animation handle
if(reg_desk_door_anim_instance != NULL) {
anim_stop_playing(reg_desk_door_anim_instance);
reg_desk_door_anim_instance = NULL;
}
// free up door animations/instances
if((reg_desk_door_anim_instance != NULL) && (anim_playing(reg_desk_door_anim_instance))) {
reg_desk_door_anim_instance = NULL;
}
if(reg_desk_door_anim != NULL){
if(anim_free(reg_desk_door_anim) == -1) {
nprintf(("General","WARNING!, Could not free up door anim %s\n",reg_desk_door_anim));
}
}
// stop any playing door sound
if((reg_desk_door_sound_handle != -1) && snd_is_playing(reg_desk_door_sound_handle)) {
snd_stop(reg_desk_door_sound_handle);
reg_desk_door_sound_handle = -1;
}
// stop reg desk wave
if (snd_is_playing(Reg_desk_intro_wave_id)) {
snd_stop(Reg_desk_intro_wave_id);
}
// setup the player struct
Player_num = 0;
Player = &Players[0];
Player->flags |= PLAYER_FLAGS_STRUCTURE_IN_USE;
// now read in a the pilot data
if (read_pilot_file(Pilots[Player_select_pilot], !Player_select_mode, Player) != 0) {
Error(LOCATION,"Couldn't load pilot file, bailing");
Player = NULL;
}
if (Player_select_force_main_hall) {
Player->main_hall = 1;
}
}
void player_select_set_input_mode(int n)
{
int i;
// set the input mode
Player_select_input_mode = n;
// enable all the player select buttons
for (i=0; i<NUM_PLAYER_SELECT_BUTTONS; i++){
Player_select_buttons[gr_screen.res][i].button.enable(!n);
}
Player_select_buttons[gr_screen.res][ACCEPT_BUTTON].button.set_hotkey(n ? -1 : KEY_ENTER);
Player_select_buttons[gr_screen.res][CREATE_PILOT_BUTTON].button.set_hotkey(n ? -1 : KEY_C);
// enable the player select input box
if(Player_select_input_mode){
Player_select_input_box.enable();
Player_select_input_box.unhide();
} else {
Player_select_input_box.hide();
Player_select_input_box.disable();
}
}
extern int bg_mouse1;
void player_select_button_pressed(int n)
{
int ret;
int squad_index = -1;
switch (n) {
case SCROLL_LIST_UP_BUTTON:
player_select_set_bottom_text("");
player_select_scroll_list_up();
break;
case SCROLL_LIST_DOWN_BUTTON:
player_select_set_bottom_text("");
player_select_scroll_list_down();
break;
case ACCEPT_BUTTON:
// make sure he has a valid pilot selected
if (Player_select_pilot < 0) {
popup(PF_USE_AFFIRMATIVE_ICON,1,POPUP_OK,XSTR( "You must select a valid pilot first", 378));
} else {
player_select_commit();
}
break;
case CLONE_BUTTON:
// if we're at max-pilots, don't allow another to be added
if (Player_select_num_pilots >= MAX_PILOTS) {
player_select_set_bottom_text(XSTR( "You already have the maximum # of pilots!", 379));
gamesnd_play_iface(SND_GENERAL_FAIL);
break;
}
if (Player_select_pilot >= 0) {
// first we have to make sure this guy is actually loaded for when we create the clone
if (Player == NULL) {
Player = &Players[0];
Player->flags |= PLAYER_FLAGS_STRUCTURE_IN_USE;
}
// attempt to read in the pilot file of the guy to be cloned
if (read_pilot_file(Pilots[Player_select_pilot], !Player_select_mode, Player) != 0) {
Error(LOCATION,"Couldn't load pilot file, bailing");
Player = NULL;
Int3();
}
// set the clone flag
Player_select_clone_flag = 1;
// create the new pilot (will be cloned with Player_select_clone_flag_set)
if (!player_select_create_new_pilot()) {
player_select_set_bottom_text(XSTR( "Error creating new pilot file!", 380));
Player_select_clone_flag = 0;
memset(Player,0,sizeof(player));
Player = NULL;
break;
}
// clear the player out
// JH: How do you clone a pilot if you clear out the source you are copying
// from? These next 2 lines are pure stupidity, so I commented them out!
// memset(Player,0,sizeof(player));
// Player = NULL;
// display some text on the bottom of the dialog
player_select_set_bottom_text(XSTR( "Type Callsign and Press Enter", 381));
// gray out all controls in the dialog
player_select_set_controls(1);
}
break;
case CREATE_PILOT_BUTTON:
// if we're at max-pilots, don't allow another to be added
if (Player_select_num_pilots >= MAX_PILOTS){
player_select_set_bottom_text(XSTR( "You already have the maximum # of pilots!", 379));
gamesnd_play_iface(SND_GENERAL_FAIL);
break;
}
// create a new pilot
if (!player_select_create_new_pilot()) {
player_select_set_bottom_text(XSTR( "Type Callsign and Press Enter", 381));
}
// don't clone anyone
Player_select_clone_flag = 0;
// display some text on the bottom of the dialog
player_select_set_bottom_text(XSTR( "Type Callsign and Press Enter", 381));
// gray out all controls
player_select_set_controls(1);
break;
case DELETE_BUTTON:
player_select_set_bottom_text("");
if (Player_select_pilot >= 0) {
// display a popup requesting confirmation
ret = popup(PF_TITLE_BIG | PF_TITLE_RED, 2, POPUP_NO, POPUP_YES, XSTR( "Warning!\n\nAre you sure you wish to delete this pilot?", 382));
// delete the pilot
if(ret == 1){
player_select_delete_pilot();
}
}
break;
case SINGLE_BUTTON:
#if defined(MP_DEMO)
player_select_set_bottom_text("Single player unavailable in demo");
break;
#else
player_select_set_bottom_text("");
Player_select_autoaccept = 0;
// switch to single player mode
if (Player_select_mode != PLAYER_SELECT_MODE_SINGLE) {
// play a little sound
gamesnd_play_iface(SND_USER_SELECT);
//player_select_set_middle_text(XSTR( "Single Player Mode", 376));
// reinitialize as single player mode
player_select_init_player_stuff(PLAYER_SELECT_MODE_SINGLE);
} else {
gamesnd_play_iface(SND_GENERAL_FAIL);
}
break;
#endif
case MULTI_BUTTON:
player_select_set_bottom_text("");
Player_select_autoaccept = 0;
#if defined(DEMO) || defined(OEM_BUILD) // not for FS2_DEMO
game_feature_not_in_demo_popup();
#else
// switch to multiplayer mode
if (Player_select_mode != PLAYER_SELECT_MODE_MULTI) {
// play a little sound
gamesnd_play_iface(SND_USER_SELECT);
//player_select_set_middle_text(XSTR( "Multiplayer Mode", 377));
// reinitialize as multiplayer mode
player_select_init_player_stuff(PLAYER_SELECT_MODE_MULTI);
} else {
gamesnd_play_iface(SND_GENERAL_FAIL);
}
#endif
break;
case TC_BUTTON:
popup_tc();
break;
}
}
int player_select_create_new_pilot()
{
int idx;
// make sure we haven't reached the max
if (Player_select_num_pilots >= MAX_PILOTS) {
gamesnd_play_iface(SND_GENERAL_FAIL);
return 0;
}
int play_scroll_sound = 1;
#ifdef FS2_DEMO
if ( Demo_title_active ) {
play_scroll_sound = 0;
}
#endif
if ( play_scroll_sound ) {
gamesnd_play_iface(SND_SCROLL);
}
idx = Player_select_num_pilots;
// move all the pilots in the list up
while (idx--) {
strcpy(Pilots[idx + 1], Pilots[idx]);
}
#ifndef NO_NETWORK
// by default, set the default netgame protocol to be VMT
Multi_options_g.protocol = NET_TCP;
#endif
// select the beginning of the list
Player_select_pilot = 0;
Player_select_num_pilots++;
Pilots[Player_select_pilot][0] = 0;
Player_select_list_start= 0;
// set us to be in input mode
player_select_set_input_mode(1);
// set the input box to have focus
Player_select_input_box.set_focus();
Player_select_input_box.set_text("");
Player_select_input_box.update_dimensions(Choose_list_coords[gr_screen.res][0], Choose_list_coords[gr_screen.res][1], Choose_list_coords[gr_screen.res][2], gr_get_font_height());
return 1;
}
void player_select_delete_pilot()
{
char filename[MAX_PATH_LEN + 1];
int i, deleted_cur_pilot;
deleted_cur_pilot = 0;
// tack on the full path and the pilot file extension
// build up the path name length
// make sure we do this based upon whether we're in single or multiplayer mode
strcpy( filename, Pilots[Player_select_pilot] );
strcat( filename, NOX(".plr") );
int del_rval;
int popup_rval = 0;
do {
// attempt to delete the pilot
if (Player_select_mode == PLAYER_SELECT_MODE_SINGLE) {
del_rval = cf_delete( filename, CF_TYPE_SINGLE_PLAYERS );
} else {
del_rval = cf_delete( filename, CF_TYPE_MULTI_PLAYERS );
}
if(!del_rval) {
popup_rval = popup(PF_TITLE_BIG | PF_TITLE_RED, 2, XSTR( "&Retry", -1), XSTR("&Cancel",-1),
XSTR("Error\nFailed to delete pilot file. File may be read-only.\n", -1));
}
//Abort
if(popup_rval)
{
return;
}
//Try again
} while (!del_rval);
// delete all the campaign save files for this pilot.
mission_campaign_delete_all_savefiles( Pilots[Player_select_pilot], (Player_select_mode != PLAYER_SELECT_MODE_SINGLE) );
// move all the players down
for (i=Player_select_pilot; i<Player_select_num_pilots-1; i++){
strcpy(Pilots[i], Pilots[i + 1]);
}
// correcly set the # of pilots and the currently selected pilot
Player_select_num_pilots--;
if (Player_select_pilot >= Player_select_num_pilots) {
Player_select_pilot = Player_select_num_pilots - 1;
}
}
// scroll the list of players up
void player_select_scroll_list_up()
{
if (Player_select_pilot == -1)
return;
// change the pilot selected index and play the appropriate sound
if (Player_select_pilot) {
Player_select_pilot--;
gamesnd_play_iface(SND_SCROLL);
} else {
gamesnd_play_iface(SND_GENERAL_FAIL);
}
if (Player_select_pilot < Player_select_list_start){
Player_select_list_start = Player_select_pilot;
}
}
// scroll the list of players down
void player_select_scroll_list_down()
{
// change the pilot selected index and play the appropriate sound
if (Player_select_pilot < Player_select_num_pilots - 1) {
Player_select_pilot++;
gamesnd_play_iface(SND_SCROLL);
} else {
gamesnd_play_iface(SND_GENERAL_FAIL);
}
if (Player_select_pilot >= (Player_select_list_start + Player_select_max_lines[gr_screen.res])){
Player_select_list_start++;
}
}
// fill in the data on the last played pilot (callsign and is_multi or not)
int player_select_get_last_pilot_info()
{
char *last_player;
last_player = os_config_read_string( NULL, "LastPlayer", NULL);
if(last_player == NULL){
return 0;
} else {
strcpy(Player_select_last_pilot,last_player);
}
// determine if he was a single or multi-player based upon the last character in his callsign
Player_select_last_is_multi = Player_select_last_pilot[strlen(Player_select_last_pilot)-1] == 'M' ? 1 : 0;
Player_select_last_pilot[strlen(Player_select_last_pilot)-1]='\0';
return 1;
}
int player_select_get_last_pilot()
{
// if the player has the Cmdline_use_last_pilot command line option set, try and drop out quickly
if(Cmdline_use_last_pilot){
int idx;
if(!player_select_get_last_pilot_info()){
return 0;
}
if(Player_select_last_is_multi){
Player_select_num_pilots = cf_get_file_list_preallocated(MAX_PILOTS, Pilots_arr, Pilots, CF_TYPE_MULTI_PLAYERS, NOX("*.plr"), CF_SORT_TIME);
} else {
Player_select_num_pilots = cf_get_file_list_preallocated(MAX_PILOTS, Pilots_arr, Pilots, CF_TYPE_SINGLE_PLAYERS, NOX("*.plr"), CF_SORT_TIME);
}
Player_select_pilot = -1;
idx = 0;
// pick the last player
for(idx=0;idx<Player_select_num_pilots;idx++){
if(strcmp(Player_select_last_pilot,Pilots_arr[idx])==0){
Player_select_pilot = idx;
break;
}
}
// set this so that we don't incorrectly create a "blank" pilot - .plr
// in the player_select_close() function
Player_select_num_pilots = 0;
// if we've actually found a valid pilot, load him up
if(Player_select_pilot != -1){
Player = &Players[0];
read_pilot_file(Pilots_arr[idx],!Player_select_last_is_multi,Player);
Player->flags |= PLAYER_FLAGS_STRUCTURE_IN_USE;
return 1;
}
}
return 0;
}
void player_select_init_player_stuff(int mode)
{
Player_select_list_start = 0;
// set the select mode to single player for default
Player_select_mode = mode;
// load up the list of players based upon the Player_select_mode (single or multiplayer)
Get_file_list_filter = player_select_pilot_file_filter;
if (mode == PLAYER_SELECT_MODE_SINGLE){
Player_select_num_pilots = cf_get_file_list_preallocated(MAX_PILOTS, Pilots_arr, Pilots, CF_TYPE_SINGLE_PLAYERS, NOX("*.plr"), CF_SORT_TIME);
} else {
Player_select_num_pilots = cf_get_file_list_preallocated(MAX_PILOTS, Pilots_arr, Pilots, CF_TYPE_MULTI_PLAYERS, NOX("*.plr"), CF_SORT_TIME);
}
Player = NULL;
// if this value is -1, it means we should set it to the num pilots count
if(Player_select_initial_count == -1){
Player_select_initial_count = Player_select_num_pilots;
}
// select the first pilot if any exist, otherwise set to -1
if (Player_select_num_pilots == 0) {
Player_select_pilot = -1;
player_select_set_bottom_text(XSTR( "Type Callsign and Press Enter", 381));
player_select_set_controls(1); // gray out the controls
player_select_create_new_pilot();
} else {
Player_select_pilot = -1;
int idx = 0;
// pick the last player
for(idx=0;idx<Player_select_num_pilots;idx++){
if(strcmp(Player_select_last_pilot,Pilots_arr[idx])==0){
Player_select_pilot = idx;
break;
}
}
}
}
void player_select_draw_list()
{
int idx;
for (idx=0; idx<Player_select_max_lines[gr_screen.res]; idx++) {
// only draw as many pilots as we have
if ((idx + Player_select_list_start) == Player_select_num_pilots)
break;
// if the currently selected pilot is this line, draw it highlighted
if ( (idx + Player_select_list_start) == Player_select_pilot) {
// if he's the active pilot and is also the current selection, super-highlight him
gr_set_color_fast(&Color_bright_white);
}
// otherwise draw him normally
else {
gr_set_color_fast(&Color_bright_blue);
}
// draw the actual callsign
gr_printf(Choose_list_coords[gr_screen.res][0], Choose_list_coords[gr_screen.res][1] + (idx * gr_get_font_height()), Pilots[idx + Player_select_list_start]);
}
}
void player_select_process_noninput(int k)
{
int idx;
// check for pressed buttons
for (idx=0; idx<NUM_PLAYER_SELECT_BUTTONS; idx++) {
if (Player_select_buttons[gr_screen.res][idx].button.pressed()) {
player_select_button_pressed(idx);
}
}
// check for keypresses
switch (k) {
// quit the game entirely
case KEY_ESC:
gameseq_post_event(GS_EVENT_QUIT_GAME);
break;
case KEY_ENTER | KEY_CTRLED:
player_select_button_pressed(ACCEPT_BUTTON);
break;
// delete the currently highlighted pilot
case KEY_DELETE:
if (Player_select_pilot >= 0) {
int ret;
// display a popup requesting confirmation
ret = popup(PF_USE_AFFIRMATIVE_ICON | PF_USE_NEGATIVE_ICON,2,POPUP_NO,POPUP_YES,XSTR( "Are you sure you want to delete this pilot?", 383));
// delete the pilot
if(ret == 1){
player_select_delete_pilot();
}
}
break;
}
// check to see if the user has clicked on the "list region" button
// and change the selected pilot appropriately
if (Player_select_list_region.pressed()) {
int click_y;
// get the mouse position
Player_select_list_region.get_mouse_pos(NULL, &click_y);
// determine what index to select
//idx = (click_y+5) / 10;
idx = click_y / gr_get_font_height();
// if he selected a valid item
if(((idx + Player_select_list_start) < Player_select_num_pilots) && (idx >= 0)){
Player_select_pilot = idx + Player_select_list_start;
}
}
// if the player has double clicked on a valid pilot, choose it and hit the accept button
if (Player_select_list_region.double_clicked()) {
if ((Player_select_pilot >= 0) && (Player_select_pilot < Player_select_num_pilots)) {
player_select_button_pressed(ACCEPT_BUTTON);
}
}
}
void player_select_process_input(int k)
{
char buf[CALLSIGN_LEN + 1];
int idx,z;
// if the player is in the process of typing in a new pilot name...
switch (k) {
// cancel create pilot
case KEY_ESC:
player_select_cancel_create();
break;
// accept a new pilot name
case KEY_ENTER:
Player_select_input_box.get_text(buf);
drop_white_space(buf);
z = 0;
if (!isalpha(*buf)) {
z = 1;
} else {
for (idx=1; buf[idx]; idx++) {
if (!isalpha(buf[idx]) && !isdigit(buf[idx]) && !strchr(VALID_PILOT_CHARS, buf[idx])) {
z = 1;
break;
}
}
}
for (idx=1; idx<Player_select_num_pilots; idx++) {
if (!stricmp(buf, Pilots[idx])) {
// verify if it is ok to overwrite the file
if (pilot_verify_overwrite() == 1) {
// delete the pilot and select the beginning of the list
Player_select_pilot = idx;
player_select_delete_pilot();
Player_select_pilot = 0;
idx = Player_select_num_pilots;
z = 0;
} else
z = 1;
break;
}
}
if (!*buf || (idx < Player_select_num_pilots)) {
z = 1;
}
if (z) {
gamesnd_play_iface(SND_GENERAL_FAIL);
break;
}
// Create the new pilot, and write out his file
strcpy(Pilots[0], buf);
// if this is the first guy, we should set the Player struct
if (Player == NULL) {
Player = &Players[0];
memset(Player, 0, sizeof(player));
Player->flags |= PLAYER_FLAGS_STRUCTURE_IN_USE;
}
strcpy(Player->callsign, buf);
init_new_pilot(Player, !Player_select_clone_flag);
// set him as being a multiplayer pilot if we're in the correct mode
if (Player_select_mode == PLAYER_SELECT_MODE_MULTI) {
Player->flags |= PLAYER_FLAGS_IS_MULTI;
Player->stats.flags |= STATS_FLAG_MULTIPLAYER;
}
// create his pilot file
write_pilot_file(Player);
// unset the player
memset(Player, 0, sizeof(player));
Player = NULL;
// make this guy the selected pilot and put him first on the list
Player_select_pilot = 0;
// unset the input mode
player_select_set_input_mode(0);
// clear any pending bottom text
player_select_set_bottom_text("");
// clear any pending middle text
player_select_set_middle_text("");
// ungray all the controls
player_select_set_controls(0);
// evaluate whether or not this is the very first pilot
player_select_eval_very_first_pilot();
break;
case 0:
break;
// always kill middle text when a char is pressed in input mode
default:
player_select_set_middle_text("");
break;
}
}
// draw copyright message on the bottom on the screen
void player_select_display_copyright()
{
// changed so I get credit - Den
int sx, sy, w;
char Copyright_msg1[256];
char Copyright_msg2[] = "Copyright (c) 1999, Volition, Inc. Copyright (c) 2004, FS2_Open Team.";
char msg3[] = "Copyright (c) 2004, Emperor's Hammer. All rights reserved.";
gr_set_color_fast(&Color_white);
get_version_string(Copyright_msg1);
gr_get_string_size(&w, NULL, Copyright_msg1);
sx = fl2i((gr_screen.max_w / 2) - w/2.0f + 0.5f);
sy = (gr_screen.max_h - 2) - 3*gr_get_font_height();
//gr_string(sx, sy, Copyright_msg1);
gr_get_string_size(&w, NULL, Copyright_msg2);
sx = fl2i((gr_screen.max_w / 2) - w/2.0f + 0.5f);
sy = (gr_screen.max_h - 2) - 2*gr_get_font_height();
//gr_string(sx, sy, Copyright_msg2);
gr_get_string_size(&w, NULL, msg3);
sx = fl2i((gr_screen.max_w / 2) - w/2.0f + 0.5f);
sy = (gr_screen.max_h - 2) - gr_get_font_height();
//gr_string(sx, sy, msg3);
}
void player_select_display_all_text()
{
int w, h;
// only draw if we actually have a valid string
if (strlen(Player_select_bottom_text)) {
gr_get_string_size(&w, &h, Player_select_bottom_text);
w = 178;
//w = (gr_screen.max_w - w) / 2;
gr_set_color_fast(&Color_bright_white);
gr_printf(w, Player_select_bottom_text_y[gr_screen.res], Player_select_bottom_text);
}
// only draw if we actually have a valid string
if (strlen(Player_select_middle_text)) {
gr_get_string_size(&w, &h, Player_select_middle_text);
w = 300;
//w = (gr_screen.max_w - w) / 2;
gr_set_color_fast(&Color_bright_white);
gr_printf(w, Player_select_middle_text_y[gr_screen.res], Player_select_middle_text);
}
}
int player_select_pilot_file_filter(char *filename)
{
return !verify_pilot_file(filename, Player_select_mode == PLAYER_SELECT_MODE_SINGLE);
}
void player_select_set_bottom_text(char *txt)
{
if (txt) {
strncpy(Player_select_bottom_text, txt, 149);
}
}
void player_select_set_middle_text(char *txt)
{
if (txt) {
strncpy(Player_select_middle_text, txt, 149);
}
}
void player_select_eval_very_first_pilot()
{
// never bring up the initial main hall help overlay
// Player_select_very_first_pilot = 0;
// if we already have this flag set, check to see if our callsigns match
if(Player_select_very_first_pilot){
// if the callsign has changed, unset the flag
if(strcmp(Player_select_very_first_pilot_callsign,Pilots[Player_select_pilot])){
Player_select_very_first_pilot = 0;
}
}
// otherwise check to see if there is only 1 pilot
else {
if((Player_select_num_pilots == 1) && (Player_select_initial_count == 0)){
// set up the data
Player_select_very_first_pilot = 1;
strcpy(Player_select_very_first_pilot_callsign,Pilots[Player_select_pilot]);
}
}
}
void player_select_commit()
{
// if we've gotten to this point, we should have ensured this was the case
Assert(Player_select_num_pilots > 0);
#if defined(MP_DEMO)
// function does all the good stuff to get the game ready for MP, just use this instead of doing it
// all over
Game_mode = GM_MULTIPLAYER;
main_hall_do_multi_ready();
#else
gameseq_post_event(GS_EVENT_MAIN_MENU);
player_select_eval_very_first_pilot();
#endif
//gameseq_post_event(GS_EVENT_MAIN_MENU);
//gamesnd_play_iface(SND_COMMIT_PRESSED);
// evaluate if this is the _very_ first pilot
//player_select_eval_very_first_pilot();
}
void player_select_cancel_create()
{
int idx;
Player_select_num_pilots--;
// make sure we correct the Selected_pilot index to account for the cancelled action
if (Player_select_num_pilots == 0) {
Player_select_pilot = -1;
}
// move all pilots down
for (idx=0; idx<Player_select_num_pilots; idx++) {
strcpy(Pilots[idx], Pilots[idx + 1]);
}
// unset the input mode
player_select_set_input_mode(0);
// clear any bottom text
player_select_set_bottom_text("");
// clear any middle text
player_select_set_middle_text("");
// ungray all controls
player_select_set_controls(0);
// disable the autoaccept
Player_select_autoaccept = 0;
}
DCF(bastion,"Sets the player to be on the bastion")
{
if(gameseq_get_state() == GS_STATE_INITIAL_PLAYER_SELECT){
Player_select_force_main_hall = 1;
dc_printf("Player is now in the Bastion\n");
}
}
#define MAX_PLAYER_TIPS 40
char *Player_tips[MAX_PLAYER_TIPS];
int Num_player_tips;
int Player_tips_shown = 0;
// tooltips
void player_tips_init()
{
Num_player_tips = 0;
// begin external localization stuff
lcl_ext_open();
read_file_text("tips.tbl");
reset_parse();
while(!optional_string("#end")){
required_string("+Tip:");
if(Num_player_tips >= MAX_PLAYER_TIPS){
break;
}
Player_tips[Num_player_tips++] = stuff_and_malloc_string(F_NAME, NULL, 1024);
}
// stop externalizing, homey
lcl_ext_close();
}
void player_tips_popup()
{
int tip, ret;
// player has disabled tips
if((Player != NULL) && !Player->tips){
return;
}
// only show tips once per instance of Freespace
if(Player_tips_shown == 1){
return;
}
Player_tips_shown = 1;
// randomly pick one
tip = (int)frand_range(0.0f, (float)Num_player_tips - 1.0f);
char all_txt[2048];
do {
sprintf(all_txt, XSTR("NEW USER TIP\n\n%s", 1565), Player_tips[tip]);
ret = popup(PF_NO_SPECIAL_BUTTONS | PF_TITLE | PF_TITLE_WHITE, 3, XSTR("&Ok", 669), XSTR("&Next", 1444), XSTR("Don't show me this again", 1443), all_txt);
// now what?
switch(ret){
// next
case 1:
if(tip >= Num_player_tips - 1){
tip = 0;
} else {
tip++;
}
break;
// don't show me this again
case 2:
ret = 0;
Player->tips = 0;
write_pilot_file(Player);
break;
}
} while(ret > 0);
}
void maybe_anim_door()
{
barracks_buttons *b;
// set flag so reg_desk_handle_region_anim() knows if cursor is over the door or not
on_door = 0;
b = &Player_select_buttons[gr_screen.res][ACCEPT_BUTTON];
if (b->button.button_hilighted()) {
on_door = 1;
door_moving = 1;
// if the animation is not playing, start it playing
if (!reg_desk_door_anim_instance) {
if (reg_desk_door_anim) {
anim_play_struct aps;
anim_play_init(&aps, reg_desk_door_anim, door_anim_coords[gr_screen.res][0], door_anim_coords[gr_screen.res][1]);
aps.screen_id = GS_STATE_INITIAL_PLAYER_SELECT;
aps.framerate_independent = 1;
reg_desk_door_anim_instance = anim_play(&aps);
if (reg_desk_door_sound_handle != -1) {
snd_stop(reg_desk_door_sound_handle);
}
//if (reg_desk_door_sound_handle == -1) {
reg_desk_door_sound_handle = snd_play(&Snds_iface[SND_MAIN_HALL_DOOR_OPEN], 0.70f); //&Snds_iface[Main_hall->door_sounds[region][0]],Main_hall->door_sound_pan[region]);
// start the sound playing at the right spot relative to the completion of the animation
if (reg_desk_door_anim_instance->frame_num != -1){
// float a = (float)reg_desk_door_anim_instance->frame_num / (float)reg_desk_door_anim_instance->parent->total_frames;
// if (reg_desk_door_anim_instance->parent->total_frames == 0)
// a = 0;
snd_set_pos(reg_desk_door_sound_handle, &Snds_iface[SND_MAIN_HALL_DOOR_OPEN],// 0, 1);
(float)reg_desk_door_anim_instance->frame_num / (float)reg_desk_door_anim_instance->parent->total_frames,1);
}
}
}
}
// otherwise if its playing in the reverse direction, change it to the forward direction
if (reg_desk_door_anim_instance) {
if (reg_desk_door_anim_instance->frame_num > 15) {
// anim_reverse_direction(reg_desk_door_anim_instance);
if(reg_desk_door_sound_handle != -1){
// snd_stop(reg_desk_door_sound_handle);
}
reg_desk_door_sound_handle = snd_play(&Snds_iface[SND_MAIN_HALL_DOOR_CLOSE], 0.70f); //&Snds_iface[Main_hall->door_sounds[region][0]],Main_hall->door_sound_pan[region]);
// start the sound playing at the right spot relative to the completion of the animation
if(reg_desk_door_anim_instance->frame_num != -1){
snd_set_pos(reg_desk_door_sound_handle, &Snds_iface[SND_MAIN_HALL_DOOR_CLOSE],
(float)reg_desk_door_anim_instance->frame_num / (float)reg_desk_door_anim_instance->parent->total_frames,1);
}
}
}
}
// render all playing door animations
void reg_desk_render_door_anim(float frametime)
{
// render it
if(reg_desk_door_anim_instance != NULL){
anim_render_one(GS_STATE_INITIAL_PLAYER_SELECT, reg_desk_door_anim_instance, frametime);
}
}
// handle starting, stopping, and reversing animation
void reg_desk_handle_region_anim()
{
if((reg_desk_door_anim_instance != NULL) && !anim_playing(reg_desk_door_anim_instance)) {
reg_desk_door_anim_instance = NULL;
}
// go through each region animation
// if the instance is not null and the animation is playing
if((reg_desk_door_anim_instance != NULL) && anim_playing(reg_desk_door_anim_instance)) {
// check to see if we should hold a given door "open"
if((on_door) && (reg_desk_door_anim_instance->frame_num == 15)) {//reg_desk_door_anim_instance->stop_at)) {
anim_pause(reg_desk_door_anim_instance);
reg_desk_door_anim_instance->stop_now = FALSE;
snd_stop(reg_desk_door_sound_handle);
}
// check to see if we should close a door being held open
if((!on_door) && (reg_desk_door_anim_instance->paused)){
anim_unpause(reg_desk_door_anim_instance);
}
}
}
void reg_desk_force_button_frame()
{
for (int x=0; x<NUM_PLAYER_SELECT_BUTTONS; x++) {
// don't want the exit door being drawn then can't see ani
if (x != ACCEPT_BUTTON) {
if ( !Player_select_buttons[gr_screen.res][x].button.button_down())
Player_select_buttons[gr_screen.res][x].button.draw_forced(1);
}
}
}
void reg_desk_maybe_show_button_text()
{
barracks_buttons *b;
for (int i=0; i<NUM_PLAYER_SELECT_BUTTONS; i++) {
b = &Player_select_buttons[gr_screen.res][i];
if (b->button.button_hilighted()) {
gr_set_color_fast(&Color_bright_white);
gr_string(Player_select_text[gr_screen.res][i].x, Player_select_text[gr_screen.res][i].y, Player_select_text[gr_screen.res][i].xstr);
}
}
}
// this is for making a pilot based on their TC stats. it is similar to the other function to create a pilot
// but there are enough differences that warrented making another function to create these guys
void player_select_make_tc_pilot(Idline id, char *name)
{
char callsign[CALLSIGN_LEN + 1] = "";
int idx = Player_select_num_pilots;
int squad_index = -1;
char squad[40];
strcpy(callsign, name);
Player_select_mode = PLAYER_SELECT_MODE_MULTI;
player_select_init_player_stuff(PLAYER_SELECT_MODE_MULTI);
int a = 0;
for (idx=1; idx<Player_select_num_pilots; idx++) {
if (!stricmp(callsign, Pilots[idx])) {
// verify if it is ok to overwrite the file
if (pilot_verify_overwrite() == 1) {
// delete the pilot and select the beginning of the list
Player_select_pilot = idx;
player_select_delete_pilot();
Player_select_pilot = 0;
idx = Player_select_num_pilots;
} else
a = 1;
break;
}
}
// doesn't want to overwrite so we are bailing..............ugly, but its pretty on the inside
if (a)
return;
// move all the pilots in the list up
while (idx--) {
strcpy(Pilots[idx + 1], Pilots[idx]);
}
Player_select_pilot = 0;
Player_select_num_pilots++;
Pilots[Player_select_pilot][0] = 0;
Player_select_list_start= 0;
// Create the new pilot, and write out his file
strcpy(Pilots[0], callsign);
// if this is the first guy, we should set the Player struct
if (Player == NULL) {
Player = &Players[0];
memset(Player, 0, sizeof(player));
Player->flags |= PLAYER_FLAGS_STRUCTURE_IN_USE;
}
strcpy(Player->callsign, callsign);
init_new_pilot(Player, !Player_select_clone_flag);
// set him as being a multiplayer pilot
Player->flags |= PLAYER_FLAGS_IS_MULTI;
Player->stats.flags |= STATS_FLAG_MULTIPLAYER;
Player->stats.rank = get_rank(id.rank);
Player->stats.fchg = get_fchg(id.fchg);
make_medals(&Player->stats, id.medals);
//strcpy(Player->quote, id.quote.c_str());
//strcpy(squad, id.placement.squad.c_str());
//squad[id.placement.squad.length()-1] = '\0';
for (int x=0; x<Num_pilot_squad_images; x++) {
//fprintf(fp, "%s\t%s\n", id.placement.squad.c_str(), Pilot_squad_image_names[x]);
if ( !(stricmp(squad, Pilot_squad_image_names[x])) )
//if ( !(stricmp("omega", Pilot_squad_image_names[x])) )
{
squad_index = x;
//fprintf(fp, "%d\n", squad_index);
}
}
if (squad_index >= 0)
strcpy(Player->squad_filename, Pilot_squad_image_names[squad_index]);
//28
// special things come to those that are of the TC
Player->flags |= PLAYER_FLAGS_IS_TC_PILOT;
// create his pilot file
write_pilot_file(Player);
// unset the player
memset(Player, 0, sizeof(player));
Player = NULL;
// make this guy the selected pilot and put him first on the list
Player_select_pilot = 0;
// evaluate whether or not this is the very first pilot
player_select_eval_very_first_pilot();
}
| [
"[email protected]"
]
| [
[
[
1,
2008
]
]
]
|
7447e351ee49330f71156488b79fa20c8faf35dd | b8fbe9079ce8996e739b476d226e73d4ec8e255c | /src/tools/rmax/cstudio/bipedapi.h | 6e9e72a8a83be69d31623bd2b335df6f82e520e9 | []
| no_license | dtbinh/rush | 4294f84de1b6e6cc286aaa1dd48cf12b12a467d0 | ad75072777438c564ccaa29af43e2a9fd2c51266 | refs/heads/master | 2021-01-15T17:14:48.417847 | 2011-06-16T17:41:20 | 2011-06-16T17:41:20 | 41,476,633 | 1 | 0 | null | 2015-08-27T09:03:44 | 2015-08-27T09:03:44 | null | UTF-8 | C++ | false | false | 26,145 | h | /*********************************************************************
*<
FILE: bipedapi.h
DESCRIPTION: These are functions that are exported in biped.dlc
CREATED BY: Ravi Karra
HISTORY: Created 21 June 1999
Modified July 2002 by Michael Zyracki
*> Copyright (c) 2002 All Rights Reserved.
**********************************************************************/
#ifndef __BIPEDAPI__
#define __BIPEDAPI__
#include "BipExp.h"
// Interfaces -work similarly to the biped export interface
#define I_BIPMASTER 0x9165
#define I_BIPFOOTSTEP 0x9166
#define GetBipMasterInterface(anim) ((IBipMaster*)(anim)->GetInterface(I_BIPMASTER))
#define GetBipFSInterface(anim) ((IBipFootStep*)(anim)->GetInterface(I_BIPFOOTSTEP))
// Biped modes
#define BMODE_FIGURE (1<<0)
#define BMODE_FOOTSTEP (1<<1)
#define BMODE_MOTIONFLOW (1<<2)
#define BMODE_BUFFER (1<<3)
#define BMODE_BENDLINKS (1<<4)
#define BMODE_RUBBERBAND (1<<5)
#define BMODE_SCALESTRIDE (1<<6)
#define BMODE_INPLACE (1<<7)
#define BMODE_INPLACE_X (1<<8)
#define BMODE_INPLACE_Y (1<<9)
#define BMODE_MIXER (1<<10)
#define BMODE_MOVEALL (1<<11)
#define BMODE_ALL (BMODE_FIGURE|BMODE_FOOTSTEP|BMODE_MOTIONFLOW| \
BMODE_BUFFER|BMODE_BENDLINKS|BMODE_RUBBERBAND| \
BMODE_SCALESTRIDE|BMODE_INPLACE|BMODE_MIXER|BMODE_MOVEALL)
// Display settings
#define BDISP_BONES (1<<0)
#define BDISP_OBJECTS (1<<1)
#define BDISP_FOOTSTEPS (1<<2)
#define BDISP_FOOTSTEPNUM (1<<3)
#define BDISP_TRAJ (1<<4)
// Biped Gait Flags
#define WALKGAIT 1
#define RUNGAIT 2
#define JUMPGAIT 3
//Copy/Paste types
#define COPY_POSTURE 0
#define COPY_POSE 1
#define COPY_TRACK 2
// Body types
#define BTYPE_SKELETON 0
#define BTYPE_MALE 1
#define BTYPE_FEMALE 2
#define BTYPE_CLASSIC 3
#define NUMPIVOTS 27 // Max number of pivot points that can exiss for an object
class IBipMaster;
class IMoFlow;
class IMixer;
class MocapManager;
class MixerManager;
class MultFprintParams;
// Create a new biped with the given options
BIPExport IBipMaster* CreateNewBiped(float height, float angle, const Point3& wpos,
BOOL arms=TRUE, BOOL triPelvis=TRUE, int nnecklinks=1, int nspinelinks=4,
int nleglinks=3, int ntaillinks=0, int npony1links=0, int npony2links=0,
int numfingers=5, int nfinglinks=3, int numtoes=5, int ntoelinks=3, float ankleAttach=0.2,
BOOL prop1exists = FALSE,BOOL prop2exists = FALSE, BOOL prop3exists = FALSE,
int forearmTwistLinks = 0);
// The ticks per frame used by the biped (Currently same as GetTicksPerFrame()).
BIPExport int BipGetTicksPerFrame();
#define MB_FSJUMP 0
#define MB_FFMODE 1
#define MB_RCNTFIG 2
bool GetMsgBoxStatus(int which);
void SetMsgBoxStatus(int which, bool hide);
// Global object that contains the Mocap Interface
extern BIPExport MocapManager TheMocapManager;
// Global object that contains the Mixer Interface
extern BIPExport MixerManager TheMixerManager;
// Interface into the biped master controller
class IBipMaster {
public:
// Track selection, only work when the UI is showing up in command panel. The #defines are in tracks.h
virtual void SetTrackSelection(int track)=0;
virtual int GetTrackSelection()=0;
// File I/O methods
//These functions pop-up the dialog for file selection.
virtual void SaveBipFileDlg() = 0;
virtual void LoadBipFileDlg() = 0;
virtual int SaveFigfile (TCHAR *fname)=0;
virtual int SaveStpfile (TCHAR *fname)=0;
//These functions don't pop-up a dialog for I/O
virtual int SaveBipfile(TCHAR *fname, BOOL SaveListCntrls,BOOL SaveMaxObjects) = 0;
virtual int SaveBipfileSegment(TCHAR *filenamebuf,int StartSeg,int EndSeg,int SegKeyPerFrame,
BOOL SaveListCntrls, BOOL SaveMaxObjects) = 0;
virtual int LoadFigfile (TCHAR *fname, BOOL redraw = false, BOOL msgs = false)=0;
virtual int LoadBipStpfile(TCHAR *fname, BOOL redraw, BOOL msgs, BOOL MatchFile = false, BOOL ZeroHgt = false, BOOL loadMaxObjects = false,
BOOL promptForDuplicates = false, BOOL retargetHeight = false, BOOL retargetLimbSizes = false,
BOOL scaleIKObjectSize = false, BOOL loadSubAnimControllers = false) =0;
virtual int LoadMocapfile (TCHAR *fname, BOOL redraw = false, BOOL msgs = false, BOOL prompt = false)=0;
// General+Modes
virtual BOOL IsCreating()=0; //will return TRUE if creating
virtual void BeginModes(DWORD modes, int redraw=TRUE)=0;
virtual void EndModes(DWORD modes, int redraw=TRUE)=0;
virtual DWORD GetActiveModes()=0;
virtual BOOL CanSwitchMode(DWORD mode)=0; //returns TRUE if we can switch to that mode from our current mode
virtual void ConvertToFreeForm(bool keyPerFrame=false)=0;
virtual void ConvertToFootSteps(bool keyPerFrame=false, bool flattenToZ=true)=0;
// Display properties
virtual DWORD GetDisplaySettings()=0;
virtual void SetDisplaySettings(DWORD disp)=0;
virtual BOOL DoDisplayPrefDlg(HWND hParent)=0;
// Body types
virtual int GetBodyType() =0;
virtual void SetBodyType(int bodytype) =0;
// Anim properties
virtual int GetDynamicsType()=0;
virtual void SetDynamicsType(int dyn)=0;
virtual float GetGravAccel()=0;
virtual void SetGravAccel(float grav)=0;
virtual TCHAR* GetRootName()=0;
virtual void SetRootName(TCHAR *rootname, bool incAll=true)=0;
virtual BOOL GetAdaptLocks(int id)=0;
virtual void SetAdaptLocks(int id, BOOL onOff)=0;
virtual BOOL GetSeparateTracks(int id)=0;
virtual void SeparateTracks(int id, BOOL separate)=0;
virtual void SetBodySpaceNeckRotation(BOOL val)=0;
virtual BOOL GetBodySpaceNeckRotation()=0;
// Structure properties
virtual BOOL GetHasArms()=0;
virtual void SetHasArms(BOOL arms)=0;
virtual int GetNumLinks(int keytrack)=0;
virtual void SetNumLinks(int keytrack, int n)=0;
virtual int GetNumFingers()=0;
virtual void SetNumFingers(int n)=0;
virtual int GetNumToes()=0;
virtual void SetNumToes(int n)=0;
virtual float GetAnkleAttach()=0;
virtual void SetAnkleAttach(float aa)=0;
virtual float GetHeight()=0;
virtual void SetHeight(float h, BOOL KeepFeetOnGround = TRUE)=0;
virtual BOOL GetTrianglePelvis()=0;
virtual void SetTrianglePelvis(BOOL tri)=0;
virtual BOOL GetProp1Exists()=0;
virtual void SetProp1Exists(BOOL prop)=0;
virtual BOOL GetProp2Exists()=0;
virtual void SetProp2Exists(BOOL prop)=0;
virtual BOOL GetProp3Exists()=0;
virtual void SetProp3Exists(BOOL prop)=0;
// mocap params
virtual BOOL ConvertFromBuffer()=0;
virtual BOOL PasteFromBuffer()=0;
virtual BOOL GetDispBuffer()=0;
virtual void SetDispBuffer(BOOL onOff)=0;
virtual BOOL GetDispBufferTraj()=0;
virtual void SetDispBufferTraj(BOOL onOff)=0;
virtual BOOL GetTalentFigMode()=0;
virtual void SetTalentFigMode(BOOL onOff)=0;
virtual void AdjustTalentPose()=0;
virtual void SaveTalentFigFile(TCHAR *fname)=0;
virtual void SaveTalentPoseFile(TCHAR *fname)=0;
// footstep creation/operations
virtual BOOL GetFSAppendState()=0;
virtual void SetFSAppendState(BOOL onOff)=0;
virtual BOOL GetFSInsertState()=0;
virtual void SetFSInsertState(BOOL onOff)=0;
virtual int GetGaitMode()=0;
virtual void SetGaitMode(int mode)=0;
virtual int GetGroundDur()=0;
virtual void SetGroundDur(int val)=0;
virtual int GetAirDur()=0;
virtual void SetAirDur(int val)=0;
virtual void DoMultipleFSDlg()=0;
virtual int AddFootprint(Point3 pos, float dir, Matrix3 mtx, int appendFS)=0;
virtual void AddFootprints(MultFprintParams *Params)=0;
virtual void NewFprintKeys()=0;
virtual void BendFootprints(float angle)=0;
virtual void ScaleFootprints(float scale)=0;
// motion flow interface
virtual IMoFlow* GetMoFlow()=0;
virtual void UnifyMotion()=0;
virtual TCHAR* GetClipAtTime(TimeValue t)=0; //returns the current clip
// mixer interface
virtual IMixer* GetMixer()=0;
// IK objects
//this set's the ik object for the current selected body part
virtual void SetAttachNode(INode *node)=0;
virtual INode* GetAttachNode()=0;
//head target
virtual void SetHeadTarget(INode *node)=0;
virtual INode * GetHeadTarget() =0;
// Anim,controls,nodes....
virtual bool IsNodeDeleted()=0; //test to see if the interface's node has been deleted.
virtual Interval GetCurrentRange()=0;
virtual int GetMaxNodes()=0;
virtual int GetMaxLinks()=0;
virtual INode* GetNode(int id, int link=0)=0;
virtual BOOL GetIdLink(INode *node, int &id, int &link)=0;
virtual Control * GetHorizontalControl()=0;
virtual Control * GetVerticalControl()=0;
virtual Control * GetTurnControl()=0;
//get set keys and transforms. (in world space)
virtual void SetBipedKey(TimeValue t,INode *node = NULL, BOOL setHor = TRUE, BOOL setVer = TRUE,BOOL setTurn = TRUE)=0;
virtual ScaleValue GetBipedScale(TimeValue t, INode *node)=0;
virtual Point3 GetBipedPos(TimeValue t, INode *node)=0;
virtual Quat GetBipedRot(TimeValue t, INode *node,BOOL local = FALSE)=0;
//note that this set's a relative scale!
virtual void SetBipedScale(BOOL relative,const ScaleValue &scale, TimeValue t, INode *node)=0;
virtual void SetBipedPos(const Point3 &p, TimeValue t, INode *node,BOOL setKey =TRUE)=0;
virtual void SetBipedRot(const Quat &q, TimeValue t, INode *node,BOOL setKey = TRUE)=0;
//Biped Internal structures get/sets. These functions deal with internal biped structures and hierarchy.
virtual INode* GetRotParentNode(int id,int link)=0; //the parent node where the rotation is inherited from
virtual INode* GetPosParentNode(int id,int link)=0; //the parent node where the position is inherited from
virtual Quat GetParentNodeRot(TimeValue t,int id,int link)=0; //rotation value of the parent
virtual Point3 GetParentNodePos(TimeValue t,int id,int link)=0; //position value of the parent.
virtual void GetClavicleVals(TimeValue t, int id, float &val1,float &val2)=0; //this is valid for KEY_RARM & KEY_LARM or
virtual void GetHingeVal(TimeValue t,int id, float &val)=0; //this is valid for KEY_RARM & KEY_LARM & KEY_RLEG & KEY_LLEG. it get's the elbow/knee angle
virtual void GetHorseAnkleVal(TimeValue, int id, float &val)=0; //this is valid only if you have a horse leg and KEY_RLEG and KEY_LLEG
virtual void GetPelvisVal(TimeValue t, float &val) =0; //get's the pelvis angle
virtual void GetFingerVal(TimeValue t,int id,int link, float &val) = 0;//get the finger rotation value for the finger segements with 1 DOF
virtual BOOL GetIKActive(TimeValue t,int id) = 0;//Fuction to see if a biped limb is effect by ik at a particular time
// Layers.
virtual int NumLayers()=0;
virtual void CreateLayer(int index, TCHAR* name)=0;
virtual void DeleteLayer(int index)=0;
virtual bool CollapseAtLayer(int index)=0; //only works if all layers under this layer are active, returns true if successul
virtual bool GetLayerActive(int index)=0;
virtual void SetLayerActive(int index, bool onOff)=0;
virtual TCHAR* GetLayerName(int index)=0;
virtual void SetLayerName(int index, TCHAR* name)=0;
virtual int GetCurrentLayer()=0;
virtual void SetCurrentLayer(int index)=0;
virtual void UpdateLayers()=0; // need to call this after changes made to layers
//layer display info
virtual int GetVisibleBefore()=0;
virtual void SetVisibleBefore(int val)=0;
virtual int GetVisibleAfter()=0;
virtual void SetVisibleAfter(int val)=0;
virtual bool GetKeyHighlight()=0;
virtual void SetKeyHighlight(bool onOff)=0;
// preferred clips for use with biped crowd.
virtual void ClearPreferredClips()=0;
virtual bool AddPreferredClip(TCHAR *clipname, int prob = 100)=0;
virtual bool DeletePreferredClip(TCHAR *clipname)=0;
virtual int IsPreferredClip(TCHAR *clipname)=0;
virtual TCHAR* GetCurrentClip()=0;
virtual int NumPreferredClips()=0;
virtual TCHAR* GetPreferredClip(int i)=0;
virtual int GetPreferredClipProbability(int i)=0;
//Biped Subanims
virtual bool GetEnableSubAnims()=0;
virtual void SetEnableSubAnims(bool onOff)=0;
virtual bool GetManipSubAnims()=0;
virtual void SetManipSubAnims(bool onOff)=0;
//These functions will clone the 'controlToClone' control and put it in each appropiate BipedSubAnim::List,
//and make that control the active control. If 'checkIfOneExists' is TRUE it will first check to see
//if a controller of the same type already exists in the subanim list, in which case it will just
//set that one as active,and not clone a new one.
virtual void CreatePosSubAnims(Control *controlToClone, BOOL checkIfOneExists)=0;
virtual void CreateRotSubAnims(Control *controlToClone, BOOL checkIfOneExists)=0;
virtual void CreateScaleSubAnims(Control *controlToClone, BOOL checkIfOneExists)=0;
//these functions Set a key for the appropiate active controller in the list controller for the
//specified node. If 'absolute' is true the value used to set the key is the total combined value
//of the underlying biped value plus the subanim value. Thus the subanim value will be calculating
//by subtracting out the biped value. If 'absolute' is false the value is the exact subanim key value
//that will be set. Due to the limitation in defining a global 'biped scale', the scale type of this
//function has no absolute parameter and always just sets the key with the specified value
virtual void SetPosSubAnim(const Point3 &p, TimeValue t, INode *node,BOOL absolute)=0;
virtual void SetRotSubAnim(const Quat &q, TimeValue t, INode *node,BOOL absolute) = 0;
virtual void SetScaleSubAnim(const ScaleValue &s, TimeValue t, INode *node) = 0;
//these function calls collapse the specified subAnims..
virtual void CollapseAllPosSubAnims(BOOL perFrame,BOOL keep) = 0;
virtual void CollapseAllRotSubAnims(BOOL perFrame,BOOL keep) = 0;
virtual void CollapseRotSubAnims(BOOL perFrame,BOOL keep,INode *node) = 0;
virtual void CollapsePosSubAnims(BOOL perFrame,BOOL keep,INode *node) = 0;
//Copy/Paste exposure
virtual char * CopyPosture(int copyType,BOOL copyHor,BOOL copyVer,BOOL copyTurn) = 0;
virtual BOOL PastePosture(int copyType,int opposite,char *name) = 0;
virtual void DeleteAllCopies(int copyType, BOOL holdIt = true) = 0;
virtual int NumCopies(int copyType) = 0;
virtual void DeleteCopy(int copyType,char *name) = 0;
virtual TCHAR *GetCopyName(int copyType,int which) = 0;
virtual void SetCopyName(int copyType,int oldIndex, char *newName) = 0;
virtual BOOL SaveCopyPasteFile(char *fname) = 0;
virtual BOOL LoadCopyPasteFile(char *fname) = 0;
};
//Interface to the biped footstep
class IBipFootStep
{
public:
virtual void SetFreeFormMode(BOOL mode)=0;
virtual BOOL GetFreeFormMode()=0;
virtual void SetDispNumType(int type)=0;
virtual int GetDispNumType()=0;
virtual void SetDispAirDur(BOOL onOff)=0;
virtual BOOL GetDispAirDur()=0;
virtual void SetDispNoSupport(BOOL onOff)=0;
virtual BOOL GetDispNoSupport()=0;
virtual void UpdateEditTrackUI()=0;
virtual void UpdateFootSteps(TimeValue t){}
};
// defines for mocap key reduction settings
#define KRS_ALL 0
#define KRS_HORZ 1
#define KRS_VERT 2
#define KRS_ROT 3
#define KRS_PLV 4
#define KRS_SPN 5
#define KRS_NCK 6
#define KRS_LARM 7
#define KRS_RARM 8
#define KRS_LLEG 9
#define KRS_RLEG 10
#define KRS_TAIL 11
// defines for mocap GetLimbOrientation/SetLimbOrientation
#define LIMB_KNEE 0
#define LIMB_ELBOW 1
#define LIMB_FOOT 2
#define LIMB_HAND 3
#define ANGLE_ALIGN 0
#define POINT_ALIGN 1
#define AUTO_ALIGN 2
//The mocap manager class.
class MocapManager {
public:
// import dialog properties
BIPExport TCHAR* GetTalentFigStrucFile();
BIPExport void SetTalentFigStrucFile(const TCHAR *fname);
BIPExport BOOL GetUseTalentFigStrucFile() const;
BIPExport void SetUseTalentFigStrucFile(BOOL onOff);
BIPExport TCHAR* GetTalentPoseAdjFile() const;
BIPExport void SetTalentPoseAdjFile(const TCHAR *fname);
BIPExport BOOL GetUseTalentPoseAdjFile() const;
BIPExport void SetUseTalentPoseAdjFile(BOOL onOff);
BIPExport int GetFSExtractionMode() const;
BIPExport void SetFSExtractionMode(int mode);
BIPExport int GetFSConversionMode() const;
BIPExport void SetFSConversionMode(int mode);
// 0 - x, 1 - y, 2 - z
BIPExport int GetUpVector() const;
BIPExport void SetUpVector(int axis);
BIPExport float GetScaleFactor() const;
BIPExport void SetScaleFactor(float val);
BIPExport float GetFSExtractionTol() const;
BIPExport void SetFSExtractionTol(float val);
BIPExport float GetFSSlidingDist() const;
BIPExport void SetFSSlidingDist(float val);
BIPExport float GetFSSlidingAngle() const;
BIPExport void SetFSSlidingAngle(float val);
BIPExport float GetFSVerticalTol() const;
BIPExport void SetFSVerticalTol(float val);
BIPExport float GetFSZLevel() const;
BIPExport void SetFSZLevel(float val);
BIPExport BOOL GetFSUseVerticalTol() const;
BIPExport void SetFSUseVerticalTol(BOOL val);
BIPExport BOOL GetFSUseFlatten() const;
BIPExport void SetFSUseFlatten(BOOL val);
BIPExport int GetStartFrame() const;
BIPExport void SetStartFrame(int val);
BIPExport int GetEndFrame() const;
BIPExport void SetEndFrame(int val);
BIPExport BOOL GetUseLoopFrame() const;
BIPExport void SetUseLoopFrame(BOOL val);
BIPExport int GetLoopFrameCount() const;
BIPExport void SetLoopFrameCount(int val);
BIPExport float GetKeyReductionTol(int part) const;
BIPExport void SetKeyReductionTol(int part, float val);
BIPExport int GetKeyReductionSpacing(int part) const;
BIPExport void SetKeyReductionSpacing(int part, float val);
BIPExport BOOL GetKeyReductionFilter(int part) const;
BIPExport void SetKeyReductionFilter(int part, BOOL onOff);
BIPExport int GetLimbOrientation(int limb) const;
BIPExport void SetLimbOrientation(int limb, int val);
BIPExport int LoadMocapParameters(const TCHAR *fname);
BIPExport int SaveMocapParameters(const TCHAR *fname);
// marker name dialog
BIPExport TCHAR* GetMarkerNameFile() const;
BIPExport bool LoadMarkerNameFile(const TCHAR *fname);
BIPExport BOOL GetUseMarkerNameFile() const;
BIPExport void SetUseMarkerNameFile(BOOL onOff);
BIPExport TCHAR* GetJointNameFile() const;
BIPExport bool LoadJointNameFile(const TCHAR *fname);
BIPExport BOOL GetUseJointNameFile() const;
BIPExport void SetUseJointNameFile(BOOL onOff);
BIPExport int BatchConvert(TCHAR* inDir, TCHAR* outDir, TCHAR* ext);
BIPExport BOOL GetDispKnownMarkers() const;
BIPExport void SetDispKnownMarkers(BOOL onOff);
BIPExport int GetDispKnownMarkersType() const; // 0 - Sel objects, 1 - all
BIPExport void SetDispKnownMarkersType(int type); // 0 - Sel objects, 1 - all
BIPExport BOOL GetDispUnKnownMarkers() const;
BIPExport void SetDispUnKnownMarkers(BOOL onOff);
BIPExport BOOL GetDispPropMarkers() const;
BIPExport void SetDispPropMarkers(BOOL onOff);
};
//The mixer manager class.
class MixerManager {
public:
BIPExport BOOL GetSnapFrames();
BIPExport void SetSnapFrames(BOOL onOff);
BIPExport BOOL GetShowTgRangebars();
BIPExport void SetShowTgRangebars(BOOL onOff);
BIPExport BOOL GetShowWgtCurves();
BIPExport void SetShowWgtCurves(BOOL onOff);
BIPExport BOOL GetShowTimeWarps();
BIPExport void SetShowTimeWarps(BOOL onOff);
BIPExport BOOL GetShowClipBounds();
BIPExport void SetShowClipBounds(BOOL onOff);
BIPExport BOOL GetShowGlobal();
BIPExport void SetShowGlobal(BOOL onOff);
BIPExport BOOL GetShowClipNames();
BIPExport void SetShowClipNames(BOOL onOff);
BIPExport BOOL GetShowClipScale();
BIPExport void SetShowClipScale(BOOL onOff);
BIPExport BOOL GetShowTransStart();
BIPExport void SetShowTransStart(BOOL onOff);
BIPExport BOOL GetShowTransEnd();
BIPExport void SetShowTransEnd(BOOL onOff);
BIPExport BOOL GetShowBalance();
BIPExport void SetShowBalance(BOOL onOff);
BIPExport BOOL GetSnapToClips();
BIPExport void SetSnapToClips(BOOL onOff);
BIPExport BOOL GetLockTransitions();
BIPExport void SetLockTransitions(BOOL onOff);
BIPExport void SetAnimationRange();
BIPExport void ZoomExtents();
BIPExport void UpdateDisplay();
BIPExport void AddBipedToMixerDisplay(IBipMaster *mc);
BIPExport void RemoveBipedFromMixerDisplay(IBipMaster *mc);
BIPExport void ShowMixer();
BIPExport void HideMixer();
};
// Base Biped Key. For pelvis, spine, neck, tail, pony1, pony2 keys
class IBipedKey : public IKey {
public:
float tens, cont, bias, easeIn, easeOut;
int type;
};
// Biped COM Vertical Key
class IBipedVertKey : public IBipedKey {
public:
float z, dynBlend, ballTens;
};
// Biped COM Horizontal Key
class IBipedHorzKey : public IBipedKey {
public:
float x, y, balFac;
};
// Biped COM Turn Key
class IBipedTurnKey : public IBipedKey {
public:
Quat q;
};
// Biped Body Key for the Arm and Leg Keys. contains ik blend and pivot point info.
// IK spaces
#define BODYSPACE 0
#define WORLDSPACE 1 // Currently not valid
#define OBJECTSPACE 2
class IBipedBodyKey : public IBipedKey {
public:
float ik_blend,
ik_ankle_ten;
int ik_space,
ik_joined_pivot,
ik_pivot_index,
ik_num_pivots;
Point3 ik_pivot_pts[NUMPIVOTS];
};
// Biped Head Key
class IBipedHeadKey : public IBipedKey {
public :
float head_blend;
};
// Biped Prop Key
#define WORLD_PROP 0
#define BODY_PROP 1
#define RHAND_PROP 2
#define LHAND_PROP 3
class IBipedPropKey : public IBipedKey {
public:
int pos_space;
int rot_space;
};
//Biped FootStep Key
#define FS_LSEL (1<<0)
#define FS_RSEL (1<<1)
#define FS_LFT 1
#define FS_RGT 0
class IBipedFSKey : public IKey {
public:
DWORD edgeSel;
BOOL active;
Matrix3 mat;
int side; // LFT, RGT
TimeValue duration;
};
// Multiple footstep params. One will be created to store each gait's paramters (walk, run, jump)
class MultFprintParams {
public:
int numnewfprints;
float aswid;
float pswid;
float aslen;
float pslen;
float ashgt;
int cycle;
float aslen2;
float pslen2;
float ashgt2;
int cycle2;
int AutoTiming;
int InterpTiming;
int Alternate;
int MultiInsertInTime;
MultFprintParams(int gait) {init(gait);}
BIPExport void init(int gait);
};
// returns multiple footsteps parameters for different types of gaits (walk, run, jump)
BIPExport MultFprintParams* GetMultFprintParams(int gait);
// Start Left/Start Right radio buttons in "Create Mutliple Footsteps Dialog"
BIPExport int GetFSAddSide();
BIPExport void SetFSAddSide(int side);
#endif // __BIPEDAPI__
| [
"[email protected]"
]
| [
[
[
1,
613
]
]
]
|
b5e270207a21c2158cd5d135d1c123904a06ee06 | b308f1edaab2be56eb66b7c03b0bf4673621b62f | /Code/Game/GameDll/GameRulesClientServer.cpp | 1388b7098c7c387c63dc8711cd9ab7c181ae7a61 | []
| no_license | blockspacer/project-o | 14e95aa2692930ee90d098980a7595759a8a1f74 | 403ec13c10757d7d948eafe9d0a95a7f59285e90 | refs/heads/master | 2021-05-31T16:46:36.814786 | 2011-09-16T14:34:07 | 2011-09-16T14:34:07 | null | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 34,436 | cpp | /*************************************************************************
Crytek Source File.
Copyright (C), Crytek Studios, 2001-2005.
-------------------------------------------------------------------------
$Id$
$DateTime$
-------------------------------------------------------------------------
History:
- 23:5:2006 9:27 : Created by Márcio Martins
*************************************************************************/
#include "StdAfx.h"
#include "ScriptBind_GameRules.h"
#include "GameRules.h"
#include "Game.h"
#include "GameCVars.h"
#include "Actor.h"
#include "Player.h"
#include "IVehicleSystem.h"
#include "IItemSystem.h"
#include "IMaterialEffects.h"
#include "WeaponSystem.h"
#include "Radio.h"
#include "Audio/GameAudio.h"
#include "Audio/SoundMoods.h"
#include "Audio/BattleStatus.h"
#include "IWorldQuery.h"
#include <StlUtils.h>
//------------------------------------------------------------------------
void CGameRules::ClientSimpleHit(const SimpleHitInfo &simpleHitInfo)
{
if (!simpleHitInfo.remote)
{
if (!gEnv->bServer)
GetGameObject()->InvokeRMI(SvRequestSimpleHit(), simpleHitInfo, eRMI_ToServer);
else
ServerSimpleHit(simpleHitInfo);
}
}
//------------------------------------------------------------------------
void CGameRules::ClientHit(const HitInfo &hitInfo)
{
FUNCTION_PROFILER(GetISystem(), PROFILE_GAME);
IActor *pClientActor = g_pGame->GetIGameFramework()->GetClientActor();
IEntity *pTarget = m_pEntitySystem->GetEntity(hitInfo.targetId);
IEntity *pShooter = m_pEntitySystem->GetEntity(hitInfo.shooterId);
IVehicle *pVehicle = g_pGame->GetIGameFramework()->GetIVehicleSystem()->GetVehicle(hitInfo.targetId);
IActor *pActor = g_pGame->GetIGameFramework()->GetIActorSystem()->GetActor(hitInfo.targetId);
bool dead = pActor?(pActor->GetHealth()<=0):false;
if((pClientActor && pClientActor->GetEntity()==pShooter) && pTarget && (pVehicle || pActor) && !dead)
{
}
if(pActor == pClientActor)
if (gEnv->pInput) gEnv->pInput->ForceFeedbackEvent( SFFOutputEvent(eDI_XI, eFF_Rumble_Basic, 0.5f * hitInfo.damage * 0.01f, hitInfo.damage * 0.02f, 0.0f));
/* if (gEnv->pAISystem && !gEnv->bMultiplayer)
{
static int htMelee = GetHitTypeId("melee");
if (pShooter && hitInfo.type != htMelee)
{
ISurfaceType *pSurfaceType = GetHitMaterial(hitInfo.material);
const ISurfaceType::SSurfaceTypeAIParams* pParams = pSurfaceType ? pSurfaceType->GetAIParams() : 0;
const float radius = pParams ? pParams->fImpactRadius : 5.0f;
gEnv->pAISystem->BulletHitEvent(hitInfo.pos, radius, pShooter->GetAI());
}
}*/
CreateScriptHitInfo(m_scriptHitInfo, hitInfo);
CallScript(m_clientStateScript, "OnHit", m_scriptHitInfo);
bool backface = hitInfo.dir.Dot(hitInfo.normal)>0;
if (!hitInfo.remote && hitInfo.targetId && !backface)
{
if (!gEnv->bServer)
GetGameObject()->InvokeRMI(SvRequestHit(), hitInfo, eRMI_ToServer);
else
ServerHit(hitInfo);
}
}
//------------------------------------------------------------------------
void CGameRules::ServerSimpleHit(const SimpleHitInfo &simpleHitInfo)
{
switch (simpleHitInfo.type)
{
case 0: // tag
{
if (!simpleHitInfo.targetId)
return;
// tagged entities are temporary in MP, not in SP.
bool temp = gEnv->bMultiplayer;
AddTaggedEntity(simpleHitInfo.shooterId, simpleHitInfo.targetId, temp);
}
break;
case 1: // tac
{
if (!simpleHitInfo.targetId)
return;
CActor *pActor = (CActor *)gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(simpleHitInfo.targetId);
if (pActor && pActor->CanSleep())
pActor->Fall(Vec3(0.0f,0.0f,0.0f),simpleHitInfo.value);
}
break;
case 0xe: // freeze
{
if (!simpleHitInfo.targetId)
return;
// call OnFreeze
bool allow=true;
if (m_serverStateScript.GetPtr() && m_serverStateScript->GetValueType("OnFreeze")==svtFunction)
{
HSCRIPTFUNCTION func=0;
m_serverStateScript->GetValue("OnFreeze", func);
Script::CallReturn(m_serverStateScript->GetScriptSystem(), func, m_script, ScriptHandle(simpleHitInfo.targetId), ScriptHandle(simpleHitInfo.shooterId), ScriptHandle(simpleHitInfo.weaponId), simpleHitInfo.value, allow);
gEnv->pScriptSystem->ReleaseFunc(func);
}
if (!allow)
return;
if (IEntity *pEntity=gEnv->pEntitySystem->GetEntity(simpleHitInfo.targetId))
{
IScriptTable *pScriptTable=pEntity->GetScriptTable();
// call OnFrost
if (pScriptTable && pScriptTable->GetValueType("OnFrost")==svtFunction)
{
HSCRIPTFUNCTION func=0;
pScriptTable->GetValue("OnFrost", func);
Script::Call(pScriptTable->GetScriptSystem(), func, pScriptTable, ScriptHandle(simpleHitInfo.shooterId), ScriptHandle(simpleHitInfo.weaponId), simpleHitInfo.value);
gEnv->pScriptSystem->ReleaseFunc(func);
}
FreezeEntity(simpleHitInfo.targetId, true, true, simpleHitInfo.value>0.999f);
}
}
break;
default:
assert(!"Unknown Simple Hit type!");
}
}
//------------------------------------------------------------------------
void CGameRules::ServerHit(const HitInfo &hitInfo)
{
if (m_processingHit)
{
m_queuedHits.push(hitInfo);
return;
}
++m_processingHit;
ProcessServerHit(hitInfo);
while (!m_queuedHits.empty())
{
HitInfo info(m_queuedHits.front());
ProcessServerHit(info);
m_queuedHits.pop();
}
--m_processingHit;
}
//------------------------------------------------------------------------
void CGameRules::ProcessServerHit(const HitInfo &hitInfo)
{
bool ok=true;
// check if shooter is alive
CActor *pShooter=GetActorByEntityId(hitInfo.shooterId);
if (hitInfo.shooterId)
{
if (pShooter && pShooter->GetHealth()<=0)
ok=false;
}
if (hitInfo.targetId)
{
CActor *pTarget=GetActorByEntityId(hitInfo.targetId);
if (pTarget && pTarget->GetSpectatorMode())
ok=false;
}
if (ok)
{
CreateScriptHitInfo(m_scriptHitInfo, hitInfo);
CallScript(m_serverStateScript, "OnHit", m_scriptHitInfo);
// call hit listeners if any
if (m_hitListeners.empty() == false)
{
for (size_t i = 0; i < m_hitListeners.size(); )
{
size_t count = m_hitListeners.size();
m_hitListeners[i]->OnHit(hitInfo);
if (count == m_hitListeners.size())
i++;
else
continue;
}
}
if (pShooter && hitInfo.shooterId!=hitInfo.targetId && hitInfo.weaponId!=hitInfo.shooterId && hitInfo.weaponId!=hitInfo.targetId && hitInfo.damage>=0)
{
EntityId params[2];
params[0] = hitInfo.weaponId;
params[1] = hitInfo.targetId;
m_pGameplayRecorder->Event(pShooter->GetEntity(), GameplayEvent(eGE_WeaponHit, 0, 0, (void *)params));
}
if (pShooter)
m_pGameplayRecorder->Event(pShooter->GetEntity(), GameplayEvent(eGE_Hit, 0, 0, (void *)hitInfo.weaponId));
if (pShooter)
m_pGameplayRecorder->Event(pShooter->GetEntity(), GameplayEvent(eGE_Damage, 0, hitInfo.damage, (void *)hitInfo.weaponId));
}
}
//------------------------------------------------------------------------
void CGameRules::ServerExplosion(const ExplosionInfo &explosionInfo)
{
m_queuedExplosions.push(explosionInfo);
}
//------------------------------------------------------------------------
void CGameRules::ProcessServerExplosion(const ExplosionInfo &explosionInfo)
{
//CryLog("[ProcessServerExplosion] (frame %i) shooter %i, damage %.0f, radius %.1f", gEnv->pRenderer->GetFrameID(), explosionInfo.shooterId, explosionInfo.damage, explosionInfo.radius);
GetGameObject()->InvokeRMI(ClExplosion(), explosionInfo, eRMI_ToRemoteClients);
ClientExplosion(explosionInfo);
}
//------------------------------------------------------------------------
void CGameRules::ProcessQueuedExplosions()
{
const static uint8 nMaxExp = 3;
for (uint8 exp=0; !m_queuedExplosions.empty() && exp<nMaxExp; ++exp)
{
ExplosionInfo info(m_queuedExplosions.front());
ProcessServerExplosion(info);
m_queuedExplosions.pop();
}
}
//------------------------------------------------------------------------
void CGameRules::CullEntitiesInExplosion(const ExplosionInfo &explosionInfo)
{
if (!g_pGameCVars->g_ec_enable || explosionInfo.damage <= 0.1f)
return;
IPhysicalEntity **pents;
float radiusScale = g_pGameCVars->g_ec_radiusScale;
float minVolume = g_pGameCVars->g_ec_volume;
float minExtent = g_pGameCVars->g_ec_extent;
int removeThreshold = max(1, g_pGameCVars->g_ec_removeThreshold);
IActor *pClientActor = g_pGame->GetIGameFramework()->GetClientActor();
Vec3 radiusVec(radiusScale * explosionInfo.physRadius);
int i = gEnv->pPhysicalWorld->GetEntitiesInBox(explosionInfo.pos-radiusVec,explosionInfo.pos+radiusVec,pents, ent_rigid|ent_sleeping_rigid);
int removedCount = 0;
static IEntityClass* s_pInteractiveEntityClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass("InteractiveEntity");
static IEntityClass* s_pDeadBodyClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass("DeadBody");
if (i > removeThreshold)
{
int entitiesToRemove = i - removeThreshold;
for(--i;i>=0;i--)
{
if(removedCount>=entitiesToRemove)
break;
IEntity * pEntity = (IEntity*) pents[i]->GetForeignData(PHYS_FOREIGN_ID_ENTITY);
if (pEntity)
{
// don't remove if entity is held by the player
if (pClientActor && pEntity->GetId()==pClientActor->GetGrabbedEntityId())
continue;
// don't remove items/pickups
if (IItem* pItem = g_pGame->GetIGameFramework()->GetIItemSystem()->GetItem(pEntity->GetId()))
{
continue;
}
// don't remove enemies/ragdolls
if (IActor* pActor = g_pGame->GetIGameFramework()->GetIActorSystem()->GetActor(pEntity->GetId()))
{
continue;
}
// if there is a flowgraph attached, never remove!
if (pEntity->GetProxy(ENTITY_PROXY_FLOWGRAPH) != 0)
continue;
IEntityClass* pClass = pEntity->GetClass();
if (pClass == s_pInteractiveEntityClass || pClass == s_pDeadBodyClass)
continue;
// get bounding box
if (IEntityPhysicalProxy* pPhysProxy = (IEntityPhysicalProxy*)pEntity->GetProxy(ENTITY_PROXY_PHYSICS))
{
AABB aabb;
pPhysProxy->GetWorldBounds(aabb);
// don't remove objects which are larger than a predefined minimum volume
if (aabb.GetVolume() > minVolume)
continue;
// don't remove objects which are larger than a predefined minimum volume
Vec3 size(aabb.GetSize().abs());
if (size.x > minExtent || size.y > minExtent || size.z > minExtent)
continue;
}
// marcok: somehow editor doesn't handle deleting non-dynamic entities very well
// but craig says, hiding is not synchronized for DX11 breakable MP, so we remove entities only when playing pure game
// alexl: in SinglePlayer, we also currently only hide the object because it could be part of flowgraph logic
// which would break if Entity was removed and could not propagate events anymore
if (gEnv->bMultiplayer == false || gEnv->IsEditor())
{
pEntity->Hide(true);
}
else
{
gEnv->pEntitySystem->RemoveEntity(pEntity->GetId());
}
removedCount++;
}
}
}
}
//------------------------------------------------------------------------
void CGameRules::ClientExplosion(const ExplosionInfo &explosionInfo)
{
// let 3D engine know about explosion (will create holes and remove vegetation)
if (explosionInfo.hole_size > 1.0f && gEnv->p3DEngine->GetIVoxTerrain())
{
gEnv->p3DEngine->OnExplosion(explosionInfo.pos, explosionInfo.hole_size, true);
}
TExplosionAffectedEntities affectedEntities;
if (gEnv->bServer)
{
CullEntitiesInExplosion(explosionInfo);
pe_explosion explosion;
explosion.epicenter = explosionInfo.pos;
explosion.rmin = explosionInfo.minRadius;
explosion.rmax = explosionInfo.radius;
if (explosion.rmax==0)
explosion.rmax=0.0001f;
explosion.r = explosion.rmin;
explosion.impulsivePressureAtR = explosionInfo.pressure;
explosion.epicenterImp = explosionInfo.pos;
explosion.explDir = explosionInfo.dir;
explosion.nGrow = 0;
explosion.rminOcc = 0.07f;
// we separate the calls to SimulateExplosion so that we can define different radii for AI and physics bodies
explosion.holeSize = 0.0f;
explosion.nOccRes = explosion.rmax>50.0f ? 0:16;
gEnv->pPhysicalWorld->SimulateExplosion( &explosion, 0, 0, ent_living);
CreateScriptExplosionInfo(m_scriptExplosionInfo, explosionInfo);
UpdateAffectedEntitiesSet(affectedEntities, &explosion);
// check vehicles
IVehicleSystem *pVehicleSystem = g_pGame->GetIGameFramework()->GetIVehicleSystem();
uint32 vcount = pVehicleSystem->GetVehicleCount();
if (vcount > 0)
{
IVehicleIteratorPtr iter = g_pGame->GetIGameFramework()->GetIVehicleSystem()->CreateVehicleIterator();
while (IVehicle* pVehicle = iter->Next())
{
if(IEntity *pEntity = pVehicle->GetEntity())
{
AABB aabb;
pEntity->GetWorldBounds(aabb);
IPhysicalEntity* pEnt = pEntity->GetPhysics();
if (pEnt && aabb.GetDistanceSqr(explosionInfo.pos) <= explosionInfo.radius*explosionInfo.radius)
{
float affected = gEnv->pPhysicalWorld->CalculateExplosionExposure(&explosion, pEnt);
AddOrUpdateAffectedEntity(affectedEntities, pEntity, affected);
}
}
}
}
explosion.rmin = explosionInfo.minPhysRadius;
explosion.rmax = explosionInfo.physRadius;
if (explosion.rmax==0)
explosion.rmax=0.0001f;
explosion.r = explosion.rmin;
explosion.holeSize = explosionInfo.hole_size;
if (explosion.nOccRes>0)
explosion.nOccRes = -1; // makes second call re-use occlusion info
gEnv->pPhysicalWorld->SimulateExplosion( &explosion, 0, 0, ent_rigid|ent_sleeping_rigid|ent_independent|ent_static | ent_delayed_deformations);
UpdateAffectedEntitiesSet(affectedEntities, &explosion);
CommitAffectedEntitiesSet(m_scriptExplosionInfo, affectedEntities);
float fSuitEnergyBeforeExplosion = 0.0f;
float fHealthBeforeExplosion = 0.0f;
IActor *pClientActor = g_pGame->GetIGameFramework()->GetClientActor();
if(pClientActor)
{
fHealthBeforeExplosion = (float)pClientActor->GetHealth();
}
CallScript(m_serverStateScript, "OnExplosion", m_scriptExplosionInfo);
if(pClientActor)
{
float fDeltaHealth = fHealthBeforeExplosion - static_cast<CPlayer *>(pClientActor)->GetHealth();
if(fDeltaHealth >= 20.0f)
{
SAFE_GAMEAUDIO_SOUNDMOODS_FUNC(AddSoundMood(SOUNDMOOD_EXPLOSION, MIN(fDeltaHealth, 100.0f) ));
}
}
// call hit listeners if any
if (m_hitListeners.empty() == false)
{
for (size_t i = 0; i < m_hitListeners.size(); )
{
size_t count = m_hitListeners.size();
m_hitListeners[i]->OnServerExplosion(explosionInfo);
if (count == m_hitListeners.size())
i++;
else
continue;
}
}
}
if (gEnv->IsClient())
{
if (explosionInfo.pParticleEffect)
explosionInfo.pParticleEffect->Spawn(true, IParticleEffect::ParticleLoc(explosionInfo.pos, explosionInfo.dir, explosionInfo.effect_scale));
if (!gEnv->bServer)
{
CreateScriptExplosionInfo(m_scriptExplosionInfo, explosionInfo);
}
else
{
affectedEntities.clear();
CommitAffectedEntitiesSet(m_scriptExplosionInfo, affectedEntities);
}
CallScript(m_clientStateScript, "OnExplosion", m_scriptExplosionInfo);
// call hit listeners if any
if (m_hitListeners.empty() == false)
{
THitListenerVec::iterator iter = m_hitListeners.begin();
while (iter != m_hitListeners.end())
{
(*iter)->OnExplosion(explosionInfo);
++iter;
}
}
}
ProcessClientExplosionScreenFX(explosionInfo);
ProcessExplosionMaterialFX(explosionInfo);
if (gEnv->pAISystem && !gEnv->bMultiplayer)
{
// Associate event with vehicle if the shooter is in a vehicle (tank cannon shot, etc)
EntityId ownerId = explosionInfo.shooterId;
IActor* pActor = g_pGame->GetIGameFramework()->GetIActorSystem()->GetActor(ownerId);
if (pActor && pActor->GetLinkedVehicle() && pActor->GetLinkedVehicle()->GetEntityId())
ownerId = pActor->GetLinkedVehicle()->GetEntityId();
if (ownerId != 0)
{
SAIStimulus stim(AISTIM_EXPLOSION, 0, ownerId, 0,
explosionInfo.pos, ZERO, explosionInfo.radius);
gEnv->pAISystem->RegisterStimulus(stim);
SAIStimulus stimSound(AISTIM_SOUND, AISOUND_EXPLOSION, ownerId, 0,
explosionInfo.pos, ZERO, explosionInfo.radius * 3.0f, AISTIMPROC_FILTER_LINK_WITH_PREVIOUS);
gEnv->pAISystem->RegisterStimulus(stimSound);
}
}
}
//-------------------------------------------
void CGameRules::ProcessClientExplosionScreenFX(const ExplosionInfo &explosionInfo)
{
IActor *pClientActor = g_pGame->GetIGameFramework()->GetClientActor();
if (pClientActor)
{
//Distance
float dist = (pClientActor->GetEntity()->GetWorldPos() - explosionInfo.pos).len();
//Is the explosion in Player's FOV (let's suppose the FOV a bit higher, like 80)
CActor *pActor = (CActor *)pClientActor;
SMovementState state;
if (IMovementController *pMV = pActor->GetMovementController())
{
pMV->GetMovementState(state);
}
Vec3 eyeToExplosion = explosionInfo.pos - state.eyePosition;
eyeToExplosion.Normalize();
bool inFOV = (state.eyeDirection.Dot(eyeToExplosion) > 0.68f);
// if in a vehicle eyeDirection is wrong
if(pActor && pActor->GetLinkedVehicle())
{
Vec3 eyeDir = static_cast<CPlayer*>(pActor)->GetVehicleViewDir();
inFOV = (eyeDir.Dot(eyeToExplosion) > 0.68f);
}
//All explosions have radial blur (default 30m radius, to make Sean happy =))
float maxBlurDistance = (explosionInfo.maxblurdistance>0.0f)?explosionInfo.maxblurdistance:30.0f;
if (maxBlurDistance>0.0f && g_pGameCVars->g_radialBlur>0.0f && m_explosionScreenFX && explosionInfo.radius>0.5f)
{
if (inFOV && dist < maxBlurDistance)
{
ray_hit hit;
int col = gEnv->pPhysicalWorld->RayWorldIntersection(explosionInfo.pos , -eyeToExplosion*dist, ent_static | ent_terrain, rwi_stop_at_pierceable|rwi_colltype_any, &hit, 1);
//If there was no obstacle between flashbang grenade and player
if(!col)
{
if (CScreenEffects* pSE = pActor->GetScreenEffects())
{
float blurRadius = (-1.0f/maxBlurDistance)*dist + 1.0f;
gEnv->p3DEngine->SetPostEffectParam("FilterRadialBlurring_Radius", blurRadius);
gEnv->p3DEngine->SetPostEffectParam("FilterRadialBlurring_Amount", 1.0f);
IBlendedEffect *pBlur = CBlendedEffect<CPostProcessEffect>::Create(CPostProcessEffect(pClientActor->GetEntityId(),"FilterRadialBlurring_Amount", 0.0f));
IBlendType *pLinear = CBlendType<CLinearBlend>::Create(CLinearBlend(1.0f));
pSE->StartBlend(pBlur, pLinear, 1.0f, CScreenEffects::eSFX_GID_RBlur);
pSE->SetUpdateCoords("FilterRadialBlurring_ScreenPosX","FilterRadialBlurring_ScreenPosY", explosionInfo.pos);
}
float distAmp = 1.0f - (dist / maxBlurDistance);
if (gEnv->pInput)
gEnv->pInput->ForceFeedbackEvent( SFFOutputEvent(eDI_XI, eFF_Rumble_Basic, 0.5f, distAmp*3.0f, 0.0f));
}
}
}
//Flashbang effect
if(dist<explosionInfo.radius && inFOV &&
(!strcmp(explosionInfo.effect_class,"flashbang") || !strcmp(explosionInfo.effect_class,"FlashbangAI")))
{
ray_hit hit;
int col = gEnv->pPhysicalWorld->RayWorldIntersection(explosionInfo.pos , -eyeToExplosion*dist, ent_static | ent_terrain, rwi_stop_at_pierceable|rwi_colltype_any, &hit, 1);
//If there was no obstacle between flashbang grenade and player
if(!col)
{
float power = explosionInfo.flashbangScale;
power *= max(0.0f, 1 - (dist/explosionInfo.radius));
float lookingAt = (eyeToExplosion.Dot(state.eyeDirection.normalize()) + 1)*0.5f;
power *= lookingAt;
SAFE_GAMEAUDIO_SOUNDMOODS_FUNC(AddSoundMood(SOUNDMOOD_EXPLOSION,MIN(power*40.0f,100.0f)));
gEnv->p3DEngine->SetPostEffectParam("Flashbang_Time", 1.0f + (power * 4));
gEnv->p3DEngine->SetPostEffectParam("FlashBang_BlindAmount",explosionInfo.blindAmount);
gEnv->p3DEngine->SetPostEffectParam("Flashbang_DifractionAmount", (power * 2));
gEnv->p3DEngine->SetPostEffectParam("Flashbang_Active", 1);
}
}
else if(inFOV && (dist < explosionInfo.radius))
{
if (explosionInfo.damage>10.0f || explosionInfo.pressure>100.0f)
{
//Add some angular impulse to the client actor depending on distance, direction...
float dt = (1.0f - dist/explosionInfo.radius);
dt = dt * dt;
float angleZ = gf_PI*0.15f*dt;
float angleX = gf_PI*0.15f*dt;
pActor->AddAngularImpulse(Ang3(Random(-angleX*0.5f,angleX),0.0f,Random(-angleZ,angleZ)),0.0f,dt*2.0f);
}
}
float fDist2=(pClientActor->GetEntity()->GetWorldPos()-explosionInfo.pos).len2();
if (fDist2<250.0f*250.0f)
{
if (fDist2<sqr(SAFE_GAMEAUDIO_BATTLESTATUS_FUNC_RET(GetBattleRange())))
SAFE_GAMEAUDIO_BATTLESTATUS_FUNC(TickBattleStatus(1.0f));
}
}
}
//---------------------------------------------------
void CGameRules::ProcessExplosionMaterialFX(const ExplosionInfo &explosionInfo)
{
// if an effect was specified, don't use MFX
if (explosionInfo.pParticleEffect)
return;
// impact stuff here
SMFXRunTimeEffectParams params;
params.soundSemantic = eSoundSemantic_Explosion;
params.pos = params.decalPos = explosionInfo.pos;
params.trg = 0;
params.trgRenderNode = 0;
Vec3 gravity;
pe_params_buoyancy buoyancy;
gEnv->pPhysicalWorld->CheckAreas(params.pos, gravity, &buoyancy);
// 0 for water, 1 for air
Vec3 pos=params.pos;
params.inWater = (buoyancy.waterPlane.origin.z > params.pos.z) && (gEnv->p3DEngine->GetWaterLevel(&pos)>=params.pos.z);
params.inZeroG = (gravity.len2() < 0.0001f);
params.trgSurfaceId = 0;
static const int objTypes = ent_all;
static const unsigned int flags = rwi_stop_at_pierceable|rwi_colltype_any;
ray_hit ray;
if (explosionInfo.impact)
{
params.dir[0] = explosionInfo.impact_velocity.normalized();
params.normal = explosionInfo.impact_normal;
if (gEnv->pPhysicalWorld->RayWorldIntersection(params.pos-params.dir[0]*0.0125f, params.dir[0]*0.25f, objTypes, flags, &ray, 1))
{
params.trgSurfaceId = ray.surface_idx;
if (ray.pCollider->GetiForeignData()==PHYS_FOREIGN_ID_STATIC)
params.trgRenderNode = (IRenderNode*)ray.pCollider->GetForeignData(PHYS_FOREIGN_ID_STATIC);
}
}
else
{
params.dir[0] = gravity;
params.normal = -gravity.normalized();
if (gEnv->pPhysicalWorld->RayWorldIntersection(params.pos, gravity, objTypes, flags, &ray, 1))
{
params.trgSurfaceId = ray.surface_idx;
if (ray.pCollider->GetiForeignData()==PHYS_FOREIGN_ID_STATIC)
params.trgRenderNode = (IRenderNode*)ray.pCollider->GetForeignData(PHYS_FOREIGN_ID_STATIC);
}
}
string effectClass = explosionInfo.effect_class;
if (effectClass.empty())
effectClass = "generic";
string query = effectClass + "_explode";
if(gEnv->p3DEngine->GetWaterLevel(&explosionInfo.pos)>explosionInfo.pos.z)
query = query + "_underwater";
IMaterialEffects* pMaterialEffects = gEnv->pGame->GetIGameFramework()->GetIMaterialEffects();
TMFXEffectId effectId = pMaterialEffects->GetEffectId(query.c_str(), params.trgSurfaceId);
if (effectId == InvalidEffectId)
effectId = pMaterialEffects->GetEffectId(query.c_str(), pMaterialEffects->GetDefaultSurfaceIndex());
if (effectId != InvalidEffectId)
pMaterialEffects->ExecuteEffect(effectId, params);
}
//------------------------------------------------------------------------
// RMI
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, SvRequestRename)
{
CActor *pActor = GetActorByEntityId(params.entityId);
if (!pActor)
return true;
RenamePlayer(pActor, params.name.c_str());
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClRenameEntity)
{
IEntity *pEntity=gEnv->pEntitySystem->GetEntity(params.entityId);
if (pEntity)
{
string old=pEntity->GetName();
pEntity->SetName(params.name.c_str());
CryLogAlways("$8%s$o renamed to $8%s", old.c_str(), params.name.c_str());
// if this was a remote player, check we're not spectating them.
// If we are, we need to trigger a spectator hud update for the new name
EntityId clientId = g_pGame->GetIGameFramework()->GetClientActorId();
if(gEnv->bMultiplayer && params.entityId != clientId)
{
CActor* pClientActor = static_cast<CActor *>(g_pGame->GetIGameFramework()->GetClientActor());
}
}
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, SvRequestChatMessage)
{
SendChatMessage((EChatMessageType)params.type, params.sourceId, params.targetId, params.msg.c_str());
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClChatMessage)
{
OnChatMessage((EChatMessageType)params.type, params.sourceId, params.targetId, params.msg.c_str(), params.onlyTeam);
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClForbiddenAreaWarning)
{
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, SvRequestRadioMessage)
{
SendRadioMessage(params.sourceId,params.msg);
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClRadioMessage)
{
OnRadioMessage(params.sourceId,params.msg);
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, SvRequestChangeTeam)
{
CActor *pActor = GetActorByEntityId(params.entityId);
if (!pActor)
return true;
ChangeTeam(pActor, params.teamId);
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, SvRequestSpectatorMode)
{
CActor *pActor = GetActorByEntityId(params.entityId);
if (!pActor)
return true;
ChangeSpectatorMode(pActor, params.mode, params.targetId, params.resetAll);
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClSetTeam)
{
if (!params.entityId) // ignore these for now
return true;
int oldTeam = GetTeam(params.entityId);
if (oldTeam==params.teamId)
return true;
TEntityTeamIdMap::iterator it=m_entityteams.find(params.entityId);
if (it!=m_entityteams.end())
m_entityteams.erase(it);
IActor *pActor=m_pActorSystem->GetActor(params.entityId);
bool isplayer=pActor!=0;
if (isplayer && oldTeam)
{
TPlayerTeamIdMap::iterator pit=m_playerteams.find(oldTeam);
assert(pit!=m_playerteams.end());
stl::find_and_erase(pit->second, params.entityId);
}
if (params.teamId)
{
m_entityteams.insert(TEntityTeamIdMap::value_type(params.entityId, params.teamId));
if (isplayer)
{
TPlayerTeamIdMap::iterator pit=m_playerteams.find(params.teamId);
assert(pit!=m_playerteams.end());
pit->second.push_back(params.entityId);
}
}
if(isplayer)
{
ReconfigureVoiceGroups(params.entityId,oldTeam,params.teamId);
if (pActor->IsClient())
m_pRadio->SetTeam(GetTeamName(params.teamId));
}
ScriptHandle handle(params.entityId);
CallScript(m_clientStateScript, "OnSetTeam", handle, params.teamId);
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClTextMessage)
{
OnTextMessage((ETextMessageType)params.type, params.msg.c_str(),
params.params[0].empty()?0:params.params[0].c_str(),
params.params[1].empty()?0:params.params[1].c_str(),
params.params[2].empty()?0:params.params[2].c_str(),
params.params[3].empty()?0:params.params[3].c_str()
);
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, SvRequestSimpleHit)
{
ServerSimpleHit(params);
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, SvRequestHit)
{
HitInfo info(params);
info.remote=true;
ServerHit(info);
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClExplosion)
{
ClientExplosion(params);
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClFreezeEntity)
{
//IEntity *pEntity=gEnv->pEntitySystem->GetEntity(params.entityId);
//CryLogAlways("ClFreezeEntity: %s %s", pEntity?pEntity->GetName():"<<null>>", params.freeze?"true":"false");
FreezeEntity(params.entityId, params.freeze, 0);
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClShatterEntity)
{
ShatterEntity(params.entityId, params.pos, params.impulse);
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClSetGameTime)
{
m_endTime = params.endTime;
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClSetRoundTime)
{
m_roundEndTime = params.endTime;
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClSetPreRoundTime)
{
m_preRoundEndTime = params.endTime;
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClSetReviveCycleTime)
{
m_reviveCycleEndTime = params.endTime;
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClSetGameStartTimer)
{
m_gameStartTime = params.endTime;
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClTaggedEntity)
{
if (!params.entityId)
return true;
SEntityEvent scriptEvent( ENTITY_EVENT_SCRIPT_EVENT );
scriptEvent.nParam[0] = (INT_PTR)"OnGPSTagged";
scriptEvent.nParam[1] = IEntityClass::EVT_BOOL;
bool bValue = true;
scriptEvent.nParam[2] = (INT_PTR)&bValue;
IEntity *pEntity = gEnv->pEntitySystem->GetEntity(params.entityId);
if (pEntity)
pEntity->SendEvent( scriptEvent );
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClTempRadarEntity)
{
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClAddSpawnGroup)
{
AddSpawnGroup(params.entityId);
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClRemoveSpawnGroup)
{
RemoveSpawnGroup(params.entityId);
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClAddMinimapEntity)
{
AddMinimapEntity(params.entityId, params.type, params.lifetime);
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClRemoveMinimapEntity)
{
RemoveMinimapEntity(params.entityId);
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClResetMinimap)
{
ResetMinimap();
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClSetObjective)
{
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClSetObjectiveStatus)
{
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClSetObjectiveEntity)
{
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClResetObjectives)
{
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClHitIndicator)
{
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClDamageIndicator)
{
Vec3 dir(ZERO);
bool vehicle=false;
if (IEntity *pEntity=gEnv->pEntitySystem->GetEntity(params.shooterId))
{
if (IActor *pLocal=m_pGameFramework->GetClientActor())
{
dir=(pLocal->GetEntity()->GetWorldPos()-pEntity->GetWorldPos());
dir.NormalizeSafe();
vehicle=(pLocal->GetLinkedVehicle()!=0);
}
}
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, SvVote)
{
CActor* pActor = GetActorByChannelId(m_pGameFramework->GetGameChannelId(pNetChannel));
if(pActor)
Vote(pActor, true);
return true;
}
IMPLEMENT_RMI(CGameRules, SvVoteNo)
{
CActor* pActor = GetActorByChannelId(m_pGameFramework->GetGameChannelId(pNetChannel));
if(pActor)
Vote(pActor, false);
return true;
}
IMPLEMENT_RMI(CGameRules, SvStartVoting)
{
CActor* pActor = GetActorByChannelId(m_pGameFramework->GetGameChannelId(pNetChannel));
if(pActor)
StartVoting(pActor,params.vote_type,params.entityId,params.param);
return true;
}
IMPLEMENT_RMI(CGameRules, ClVotingStatus)
{
return true;
}
IMPLEMENT_RMI(CGameRules, ClEnteredGame)
{
if(!gEnv->bServer && m_pGameFramework->GetClientActor())
{
CActor* pActor = GetActorByChannelId(m_pGameFramework->GetClientActor()->GetChannelId());
if(pActor)
{
int status[2];
status[0] = GetTeam(pActor->GetEntityId());
status[1] = pActor->GetSpectatorMode();
m_pGameplayRecorder->Event(pActor->GetEntity(), GameplayEvent(eGE_Connected, 0, 0, (void*)status));
}
}
return true;
}
| [
"[email protected]"
]
| [
[
[
1,
1102
]
]
]
|
6e06d3b7749a72f1fa0930f069b465b89ec3e31d | f8b364974573f652d7916c3a830e1d8773751277 | /emulator/allegrex/instructions/CFC0.h | ce1030bc2060b9fc5fbb1e25ae5a75db570ab2e8 | []
| no_license | lemmore22/pspe4all | 7a234aece25340c99f49eac280780e08e4f8ef49 | 77ad0acf0fcb7eda137fdfcb1e93a36428badfd0 | refs/heads/master | 2021-01-10T08:39:45.222505 | 2009-08-02T11:58:07 | 2009-08-02T11:58:07 | 55,047,469 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,035 | h | template< > struct AllegrexInstructionTemplate< 0x40400000, 0xffe007ff > : AllegrexInstructionUnknown
{
static AllegrexInstructionTemplate &self()
{
static AllegrexInstructionTemplate insn;
return insn;
}
static AllegrexInstruction *get_instance()
{
return &AllegrexInstructionTemplate::self();
}
virtual AllegrexInstruction *instruction(u32 opcode)
{
return this;
}
virtual char const *opcode_name()
{
return "CFC0";
}
virtual void interpret(Processor &processor, u32 opcode);
virtual void disassemble(u32 address, u32 opcode, char *opcode_name, char *operands, char *comment);
protected:
AllegrexInstructionTemplate() {}
};
typedef AllegrexInstructionTemplate< 0x40400000, 0xffe007ff >
AllegrexInstruction_CFC0;
namespace Allegrex
{
extern AllegrexInstruction_CFC0 &CFC0;
}
#ifdef IMPLEMENT_INSTRUCTION
AllegrexInstruction_CFC0 &Allegrex::CFC0 =
AllegrexInstruction_CFC0::self();
#endif
| [
"[email protected]"
]
| [
[
[
1,
41
]
]
]
|
20f9ebde18eeee80f17faff7ac582b566b22a54e | 3bfe835203f793ee00bdf261c26992b1efea69ed | /misc/NetTest_2.0/NetTest_2.0/AssertBB.h | 4e967601054ae21891dc518e7cd196304e8bc75b | []
| no_license | yxrkt/DigiPen | 0bdc1ed3ee06e308b4942a0cf9de70831c65a3d3 | e1bb773d15f63c88ab60798f74b2e424bcc80981 | refs/heads/master | 2020-06-04T20:16:05.727685 | 2009-11-18T00:26:56 | 2009-11-18T00:26:56 | 814,145 | 1 | 3 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,731 | h | /**********************************************************************************************//*!
\file AssertBB.h
\par Project:
Block Breakers II
\par Team:
Digital Dreams
\par Copyright:
All content copyright © 2008-2009 DigiPen(USA) Corporation. All rights reserved.
\author Justin Chambers
\par Email:
jchamber\@digipen.edu
\date Created: 08/16/2008
Revised: 08/16/2008
\brief Custom assert that breaks to the actual line where the problem exists
*//***********************************************************************************************/
#pragma once
template<typename T> struct _hackForAssert //
{ //
static bool _true_; //
static bool _false_; //
}; //
#define _globalForAssert(_var) (_hackForAssert<int>::_var) // little hack for header variables
//
bool _globalForAssert(_true_) = true; //
bool _globalForAssert(_false_) = false; //
//
#define _True (_globalForAssert(_true_)) //
#define _False (_globalForAssert(_false_)) //
// awesome assert
#if defined(DEBUG) | defined(_DEBUG)
#define ASSERT(_expr,_msg)\
do{if(!(_expr)){\
MessageBoxA(NULL, (_msg), "ASSERT", MB_OK);\
DebugBreak();}}\
while(_False)
#else
#define ASSERT(_expr,_msg)\
sizeof( (_expr || _msg) )
#endif | [
"[email protected]"
]
| [
[
[
1,
41
]
]
]
|
f2fa41aaeb180d8816490f666ee22ef464a14264 | 9f2d447c69e3e86ea8fd8f26842f8402ee456fb7 | /shooting2011/shooting2011/msgdump.cpp | 1a107e973415f160426a4023c4dc9df6b22a35ca | []
| no_license | nakao5924/projectShooting2011 | f086e7efba757954e785179af76503a73e59d6aa | cad0949632cff782f37fe953c149f2b53abd706d | refs/heads/master | 2021-01-01T18:41:44.855790 | 2011-11-07T11:33:44 | 2011-11-07T11:33:44 | 2,490,410 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 916 | cpp | #include "main.h"
#include "msgdump.h"
int _dumpDefaultCoordinateX = 20;
int _dumpDefaultCoordinateY = 20;
int _dumpCoordinateX = _dumpDefaultCoordinateX;
int _dumpCoordinateY = _dumpDefaultCoordinateY;
int _dumpCharWidth = 9;
int _dumpLineHeight = 19;
DxLibOut dxout;
DxLibEndLine dxendl;
DxLibClear dxclr;
void msgDumpReset(){
static int BLACK = GetColor(0, 0, 0);
_dumpCoordinateY = 20;
graresource.drawbox(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT, BLACK, 1);
}
DxLibOut &operator <<(DxLibOut &dlo, const DxLibEndLine &){
_dumpCoordinateX = _dumpDefaultCoordinateX;
_dumpCoordinateY += _dumpLineHeight;
return dlo;
}
DxLibOut &operator <<(DxLibOut &dlo, const DxLibClear &){
static int BLACK = GetColor(0, 0, 0);
//DrawBox(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT, BLACK, 1);
_dumpCoordinateX = _dumpDefaultCoordinateX;
_dumpCoordinateY = _dumpDefaultCoordinateY;
return dlo;
}
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
16
],
[
20,
22
],
[
26,
27
],
[
33,
33
]
],
[
[
17,
19
],
[
23,
25
],
[
28,
32
]
]
]
|
d6ef403af77cde168c876a7d5309559aa4300a04 | 115cdd77595f80aa6870893657f26f6b4e7cdd2b | /src/include/TriangleStrip.hpp | 22c4b342376e01d128e50a17770f216b11c0f492 | []
| no_license | douglyuckling/peek | 0bc036906bab49fec63944e4c23e3b0c6935d820 | 9d7c3022366290a43830be5f19a47bd406038f3c | refs/heads/master | 2021-01-23T07:21:11.076300 | 2010-07-09T04:48:33 | 2010-07-09T04:48:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 974 | hpp | /**
* @file TriangleStrip.hpp
*/
#pragma once
#include "Geometry.hpp"
#include "Primitive.hpp"
namespace peek {
/**
* @brief A triangle strip primitive
*/
class TriangleStrip : public Primitive {
public:
/** Constructs an empty triangle strip */
TriangleStrip();
/** Draws the triangle strip */
virtual void draw(const Vertex3d::list &verts, const Normal3d::list &normals) const;
/** Draws the triangle strip for picking */
virtual void pick(const Vertex3d::list &verts) const;
/** Adds the triangle strip's normals to the given vertex normals */
virtual void addVertexNormals(const Vertex3d::list &verts, Normal3d::list &normals) const;
void addVertex(const Vertex3d::listIndex &v);
typedef handle_traits<TriangleStrip>::handle_type handle;
typedef list_traits<TriangleStrip::handle>::list_type list;
protected:
/** The vertices of the triangle strip */
Vertex3d::listIndexList v;
};
} | [
"douglyuckling@483a7388-aa76-4cae-9b69-882d6fd7d2f9"
]
| [
[
[
1,
42
]
]
]
|
d148ad70381b0a9363d250e16d64a646d6ad1039 | 1e01b697191a910a872e95ddfce27a91cebc57dd | /GrfSetFloatingLocation.h | cca6667384d2cd0dc12f63090a78e98792c2e215 | []
| no_license | canercandan/codeworker | 7c9871076af481e98be42bf487a9ec1256040d08 | a68851958b1beef3d40114fd1ceb655f587c49ad | refs/heads/master | 2020-05-31T22:53:56.492569 | 2011-01-29T19:12:59 | 2011-01-29T19:12:59 | 1,306,254 | 7 | 5 | null | null | null | null | IBM852 | C++ | false | false | 1,749 | h | /* "CodeWorker": a scripting language for parsing and generating text.
Copyright (C) 1996-1997, 1999-2010 CÚdric Lemaire
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
To contact the author: [email protected]
*/
#ifndef _GrfSetFloatingLocation_h_
#define _GrfSetFloatingLocation_h_
#include "GrfCommand.h"
namespace CodeWorker {
class ExprScriptExpression;
class GrfSetFloatingLocation : public GrfCommand {
private:
ExprScriptExpression* _pKey;
ExprScriptExpression* _pLocation;
public:
GrfSetFloatingLocation() : _pKey(NULL), _pLocation(NULL) {}
virtual ~GrfSetFloatingLocation();
virtual const char* getFunctionName() const { return "setFloatingLocation"; }
inline void setKey(ExprScriptExpression* pKey) { _pKey = pKey; }
inline void setLocation(ExprScriptExpression* pLocation) { _pLocation = pLocation; }
virtual void compileCpp(CppCompilerEnvironment& theCompilerEnvironment) const;
protected:
virtual SEQUENCE_INTERRUPTION_LIST executeInternal(DtaScriptVariable& visibility);
};
}
#endif
| [
"cedric.p.r.lemaire@28b3f5f3-d42e-7560-b87f-5f53cf622bc4"
]
| [
[
[
1,
51
]
]
]
|
d59dc2babe02085142922f81f85ff38fe21a05eb | b5ad65ebe6a1148716115e1faab31b5f0de1b493 | /maxsdk2008/include/custcont.h | baed99b0d68617fbf1a2b73b7eec6f893c4236ff | []
| no_license | gasbank/aran | 4360e3536185dcc0b364d8de84b34ae3a5f0855c | 01908cd36612379ade220cc09783bc7366c80961 | refs/heads/master | 2021-05-01T01:16:19.815088 | 2011-03-01T05:21:38 | 2011-03-01T05:21:38 | 1,051,010 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 202,765 | h | //**************************************************************************/
// Copyright (c) 1998-2006 Autodesk, Inc.
// All rights reserved.
//
// These coded instructions, statements, and computer programs contain
// unpublished proprietary information written by Autodesk, Inc., and are
// protected by Federal copyright law. They may not be disclosed to third
// parties or copied or duplicated in any form, in whole or in part, without
// the prior written consent of Autodesk, Inc.
//**************************************************************************/
// FILE: custcont.h
// DESCRIPTION: Custom Controls for Max
// AUTHOR: Rolf Berteig
// HISTORY: created 17 November, 1994
//**************************************************************************/
#ifndef __CUSTCONT__
#define __CUSTCONT__
#include "maxheap.h"
#include "winutil.h"
#include "buildver.h"
// Define CHILDWND_CUI to build MAX with a child-window based CUI system
#define CHILDWND_CUI
// Standard Category for rollups
#define ROLLUP_CAT_SYSTEM 2000
#define ROLLUP_CAT_STANDARD 4000
#define ROLLUP_CAT_CUSTATTRIB 6000
/*! \brief This method has been deprecated.
Plugins used to be required to call this method from their DllMain in order to initialize 3ds Max custom controls used by the plugin.
Plugins no longer need to call this method from their DllMain or other code.
The custom controls are initialized by 3ds Max automatically.
*/
MAX_DEPRECATED CoreExport void InitCustomControls( HINSTANCE hInst );
#ifdef DESIGN_VER
// VIZ window tinting APIs
CoreExport void EnableWindowTinting(bool flag = true);
CoreExport void SetWindowTint(const HWND hwnd, const COLORREF color);
CoreExport void ChangeWindowTint(const HWND hwnd, const COLORREF color);
CoreExport COLORREF GetWindowTint(const HWND hwnd);
CoreExport COLORREF GetAncestorTint(const HWND hwnd);
#endif
// DS 9/29/00 -- Turnoff CustButton borders.
#define I_EXEC_CB_NO_BORDER 0xA000 // Pass this to CustButton::Execute() to turnoff borders, like in the toolbar
#define I_EXEC_CS_NO_BORDER 0xA001 // Pass this to CustStatus::Execute() to turnoff borders, like in the toolbar
#define I_EXEC_SPINNER_RESET 0xA002 // Set a spinner back to its Reset value
#define I_EXEC_SPINNER_IS_RESET_CHANGE 0xA003 // When called during a CC_SPINNER_xxx messages, it will return true if
// the msg was triggered by a right-click reset
#define I_EXEC_SPINNER_ALT_DISABLE 0xA004 // laurent r : disable the alt key spinner behaviour
#define I_EXEC_SPINNER_ALT_ENABLE 0xA005 // laurent r : enable the alt key spinner behaviour
#define I_EXEC_SPINNER_ONE_CLICK_DISABLE 0xA006 // laurent r : disable the one click spinner behaviour with alt or ctrl down
#define I_EXEC_SPINNER_ONE_CLICK_ENABLE 0xA007 // laurent r : enable the one click spinner behaviour with alt or ctrl down
#define I_EXEC_BUTTON_DAD_ENABLE 0xA008 // enable or disable button drag & drop within a toolbar
// Values returned by DADMgr::SlotOwner()
#define OWNER_MEDIT_SAMPLE 0
#define OWNER_NODE 1
#define OWNER_MTL_TEX 2 // button in mtl or texture
#define OWNER_SCENE 3 // button in light, modifier, atmospheric, etc
#define OWNER_BROWSE_NEW 4
#define OWNER_BROWSE_LIB 5
#define OWNER_BROWSE_MEDIT 6
#define OWNER_BROWSE_SCENE 7
class ReferenceTarget;
class IParamBlock;
class IParamBlock2;
class FPInterface;
/*! \sa Class ReferenceTarget,
<a href="ms-its:listsandfunctions.chm::/idx_R_list_of_super_class_ids.html">List of Super Class IDs</a>.\n\n
\par Description:
Drag and drop functionality has been expanded to include all map and material
buttons--including those in the non-standard materials, plus most cases of
bitmap buttons. As a result, whenever you see a button representing a material
or map you can drag the button over a like button to display the
Swap/Copy/Cancel dialog. Likewise, you can drag any materials or maps from the
modeless version of the Materials/Maps Browser.\n\n
The drag-and-drop functions distinguish between material maps and bitmaps. A
bitmap is an image file, such as a .tga, or .jpg. A map is an image used by the
Materials Editor. It might consist of an image file, but could just as easily
be a parametric image, such as Checkers or Noise, or it could be a map tree
consisting of several different types of maps or bitmaps. Users can drag any
map slot or button to any other map slot or button--including the sample slots.
Users can drag the Bitmap button in the Bitmap Parameters rollout to the Bitmap
button in the Image area of the Displace modifier, and vice-versa.\n\n
Users can drag <b>from</b>:\n\n
* Sample slots\n\n
* Browser lists (text or iconic)\n\n
* The sample-sphere preview window in the Browser.\n\n
* Material map buttons, including:\n\n
* The buttons in the Maps rollout\n\n
* The shortcut map buttons\n\n
* Any map buttons at any level\n\n
* Submaterial buttons, such as those found in the Multi/Subobject
material\n\n
* Projector light map button\n\n
* Environment background map button\n\n
* Fog Color and Opacity maps buttons\n\n
Users can drag <b>to</b>:\n\n
* Objects in the viewports\n\n
* The Type button in the Materials Editor from the Browser.\n\n
* All of the items in the FROM list, with this exception: You can only
drag to the Browser when it displays the material library.\n\n
All methods of this class are virtual. For developers of plug-in textures and
materials see Class TexDADMgr, Class MtlDADMgr. These classes provide
implementations of these methods and the objects can simply be used. */
class DADMgr : public InterfaceServer {
public:
// Called on the source to see what if anything can be dragged from this x,y
// returns 0 if can't drag anything from this point
/*! \remarks This method is called on the item that supports drag and
drop to see what (if anything) can be dragged from the point <b>p</b>.
This method returns a super class id to indicate the type of item that
can be dragged away. If it does not support anything being dragged from
the specified point a SClass_ID of <b>0</b> should be returned.
\par Parameters:
<b>HWND hwnd</b>\n\n
The source window handle\n\n
<b>POINT p</b>\n\n
The screen point (relative to the window upper left as 0,0). */
virtual SClass_ID GetDragType(HWND hwnd, POINT p)=0;
// Return TRUE if creating instance with "new", rather than returning
// a pointer to an existing entity.
// If GetInstance creates a new instance every time it is called, then IsNew should
// return TRUE. This prevents GetInstance from being called repeatedly as the
// drag progresses.
/*! \remarks If the method <b>GetInstance()</b> creates a new instance
every time it is called, then the this method should return TRUE.
Otherwise it should return FALSE. This prevents <b>GetInstance()</b>
from being called repeatedly as the drag progresses.
\par Parameters:
<b>HWND hwnd</b>\n\n
The source window handle.\n\n
<b>POINT p</b>\n\n
The point to drag from.\n\n
<b>SClass_ID type</b>\n\n
The super class ID to create.
\par Default Implementation:
<b>{ return FALSE; }</b> */
virtual BOOL IsNew(HWND hwnd, POINT p, SClass_ID type) { return FALSE; }
// called on potential target to see if can drop type at this x,y
/*! \remarks This method is called on potential dropee to see if can
accept the specified type at the specified point.
\par Parameters:
<b>ReferenceTarget *dropThis</b>\n\n
A pointer to the item to check.\n\n
<b>HWND hfrom</b>\n\n
The window handle of the source.\n\n
<b>HWND hto</b>\n\n
The window handle of the destination.\n\n
<b>POINT p</b>\n\n
The point to check.\n\n
<b>SClass_ID type</b>\n\n
The super class ID of <b>dropThis</b>.\n\n
<b>BOOL isNew = FALSE</b>\n\n
TRUE if the item is a new instance; otherwise FALSE.
\return TRUE if the specified item can be dropped; otherwise FALSE. */
virtual BOOL OkToDrop(ReferenceTarget *dropThis, HWND hfrom, HWND hto, POINT p, SClass_ID type, BOOL isNew = FALSE)=0;
// called on potential target to allow it to substitute custom cursors. (optional)
/*! \remarks This method is called on a potential target to allow it
to substitute custom cursors. It returns the handle for the custom
cursor to use (or NULL to ignore).
\par Parameters:
<b>ReferenceTarget *dropThis</b>\n\n
The pointer to the item to check.\n\n
<b>HWND hfrom</b>\n\n
The window handle of the source.\n\n
<b>HWND hto</b>\n\n
The window handle of the destination.\n\n
<b>POINT p</b>\n\n
The point to check.\n\n
<b>SClass_ID type</b>\n\n
The super class ID of <b>dropThis</b>.\n\n
<b>BOOL isNew = FALSE</b>\n\n
TRUE if the item is a new instance; otherwise FALSE.
\par Default Implementation:
<b>{ return NULL;}</b> */
virtual HCURSOR DropCursor(ReferenceTarget *dropThis, HWND hfrom, HWND hto, POINT p, SClass_ID type, BOOL isNew = FALSE){ return NULL;}
// Return one of the OWNER_ values above
/*! \remarks Returns a predefined value to indicate the source of the
drag.
\return One of the following values:\n\n
<b>OWNER_MEDIT_SAMPLE</b>\n\n
From a materials editor sample slot.\n\n
<b>OWNER_NODE</b>\n\n
From a node in the scene.\n\n
<b>OWNER_MTL_TEX</b>\n\n
From a button in a material or texture.\n\n
<b>OWNER_SCENE</b>\n\n
From a button in a light, modifier, atmospheric effect, etc.\n\n
<b>OWNER_BROWSE_NEW</b>\n\n
From the browser in the new category.\n\n
<b>OWNER_BROWSE_LIB</b>\n\n
From the browser in the library category.\n\n
<b>OWNER_BROWSE_MEDIT</b>\n\n
From the browser in the materials editor category.\n\n
<b>OWNER_BROWSE_SCENE</b>\n\n
From the browser in the scene category.
\par Default Implementation:
<b>{ return OWNER_MTL_TEX; }</b> */
virtual int SlotOwner() { return OWNER_MTL_TEX; }
// This should return a pointer to the drag source. HWND is the window the mouse
// down occurred in, and p is the position in that window. Type tells the expected
// type of object.
/*! \remarks This method should return a pointer to the drag source.
\par Parameters:
<b>HWND hwnd</b>\n\n
The source window where the mouse down occurred.\n\n
<b>POINT p</b>\n\n
The point to drag from (position within <b>hwnd</b>).\n\n
<b>SClass_ID type</b>\n\n
The super class ID of the item to create. */
virtual ReferenceTarget *GetInstance(HWND hwnd, POINT p, SClass_ID type)=0;
// This routine is called on the target with the pointer returned by the source's GetInstance,
// or possibly a clone of it as the dropThis. hwnd is where the mouse was released
// for the drop, p is the position within hwnd, and type is the type of object
// being dropped.
/*! \remarks This is the method called to actually process the drop
operation. This routine is called on the target with the pointer
returned by the source's <b>GetInstance()</b>, or possibly a clone of
it as the <b>dropThis</b>.
\par Parameters:
<b>ReferenceTarget *dropThis</b>\n\n
A pointer to the item to drop.\n\n
<b>HWND hwnd</b>\n\n
The destination window handle (where the mouse was released).\n\n
<b>POINT p</b>\n\n
The destination point (within <b>hwnd</b>).\n\n
<b>SClass_ID type</b>\n\n
The type of object being dropped -- the super class ID of
<b>dropThis</b>. */
virtual void Drop(ReferenceTarget *dropThis, HWND hwnd, POINT p, SClass_ID type)=0;
// This is called when the source and target WINDOW are the same
/*! \remarks This method is called when the source and target WINDOW
are the same.
\par Parameters:
<b>HWND h1</b>\n\n
The source/target window handle.\n\n
<b>POINT p1</b>\n\n
The source point.\n\n
<b>POINT p2</b>\n\n
The target point.
\par Default Implementation:
<b>{}</b> */
virtual void SameWinDragAndDrop(HWND h1, POINT p1, POINT p2) {}
// This lets the manager know whether to call LocalDragAndDrop when the
// same DADMgr handles both source and target windows.
/*! \remarks This lets the manager know whether to call
<b>LocalDragAndDrop()</b> if the same DADMgr is handling both the
source and target windows, or just ignore this condition. Return TRUE
if <b>LocalDragAndDrop()</b> should be called; otherwise FALSE.
\par Default Implementation:
<b>{ return 0; }</b> */
virtual BOOL LetMeHandleLocalDAD() { return 0; }
// This is called if the same DADMgr is handling both the source and target windows,
// if LetMeHandleLocalDAD() returned true.
/*! \remarks This is called if the same <b>DADMgr</b> is handling both
the source and target windows, if <b>LetMeHandleLocalDAD()</b> returned
TRUE.
\par Parameters:
<b>HWND h1</b>\n\n
The window handle.\n\n
<b>HWND h2</b>\n\n
The window handle.\n\n
<b>POINT p1</b>\n\n
The drag source point.\n\n
<b>POINT p2</b>\n\n
The drop destination point.
\par Default Implementation:
<b>{}</b> */
virtual void LocalDragAndDrop(HWND h1, HWND h2, POINT p1, POINT p2){}
// If this returns true, the CustButtons that have this DADManager
// will automatically make their text a tooltip
/*! \remarks If this method returns TRUE, then Custom Buttons that use
this DAD Manager will automatically support a tooltip that matches the
button text. Note that this method will only show a tooltip when the
button text is too long and thus exceeds the button size.
\par Default Implementation:
<b>{ return FALSE; }</b> */
virtual BOOL AutoTooltip(){ return FALSE; }
// If a drag source doesn't want any references being made to the instance returned,
// then this method should return true: it will force a copy to be made.
/*! \remarks If a drag source doesn't want any references being made
to the instance returned, then this method should return TRUE: it will
force a copy to be made; otherwise return FALSE.
\par Parameters:
<b>HWND hwnd</b>\n\n
The source window handle.\n\n
<b>POINT p</b>\n\n
The source point (within <b>hwnd</b>).\n\n
<b>SClass_ID type</b>\n\n
The type of object being dragged.\n\n
\par Default Implementation:
<b>{ return FALSE; }</b> */
virtual BOOL CopyOnly(HWND hwnd, POINT p, SClass_ID type) { return FALSE; }
// Normally the mouse down and mouse up messages are not sent to the
// source window when doing DAD, but if you need them, return TRUE
/*! \remarks Normally the mouse down and mouse up messages are not
sent to the source window when doing drag and drop, but if you need
them, return TRUE.
\par Default Implementation:
<b>{ return FALSE; }</b> */
virtual BOOL AlwaysSendButtonMsgsOnDrop(){ return FALSE; }
// Generic expansion function
/*! \remarks This is a general purpose function that allows the API to be extended in the
future. The 3ds Max development team can assign new <b>cmd</b> numbers and
continue to add functionality to this class without having to 'break' the
API.\n\n
This is reserved for future use.
\par Parameters:
<b>int cmd</b>\n\n
The command to execute.\n\n
<b>ULONG arg1=0</b>\n\n
Optional argument 1 (defined uniquely for each <b>cmd</b>).\n\n
<b>ULONG arg2=0</b>\n\n
Optional argument 2.\n\n
<b>ULONG arg3=0</b>\n\n
Optional argument 3.
\return An integer return value (defined uniquely for each <b>cmd</b>).
\par Default Implementation:
<b>{ return 0; }</b> */
virtual INT_PTR Execute(int cmd, ULONG_PTR arg1=0, ULONG_PTR arg2=0, ULONG_PTR arg3=0) { return 0; }
// called on potential target to see if can instance "dropThis" at this x,y
/*! \remarks This method is called on potential target to see if can instance
"dropThis" at the specified point. Returns TRUE if it is okay to drop
the specified item and FALSE if not.
\par Parameters:
<b>ReferenceTarget *dropThis</b>\n\n
The pointer to the item to check.\n\n
<b>HWND hfrom</b>\n\n
The window handle of the source.\n\n
<b>HWND hto</b>\n\n
The window handle of the destination.\n\n
<b>POINT p</b>\n\n
The point to check.\n\n
<b>SClass_ID type</b>\n\n
The super class ID of <b>dropThis</b>.
\par Default Implementation:
<b>{ return TRUE; }</b> */
virtual BOOL OkToDropInstance(ReferenceTarget *dropThis, HWND hfrom, HWND hto, POINT p, SClass_ID type) { return TRUE; }
};
/*! \sa <a href="ms-its:3dsmaxsdk.chm::/ui_custom_controls.html">Custom
Controls</a>.\n\n
\par Description:
This is the base class from which the 3ds Max custom controls are derived. All
methods of this class are implemented by the system. */
class ICustomControl : public InterfaceServer {
public:
/*! \remarks Returns the handle of the control. */
virtual HWND GetHwnd()=0;
/*! \remarks This method is used to enable the control so it may be
operated by the user.
\param onOff TRUE to enable; FALSE to disable. */
virtual void Enable(BOOL onOff=TRUE)=0;
/*! \remarks This method is used to disable the control so it may not
be selected or used. When disabled, the control usually appears grayed
out. */
virtual void Disable()=0;
/*! \remarks This returns TRUE if the control is enabled and FALSE if
it is disabled. */
virtual BOOL IsEnabled()=0;
// this second enable function is used to disable and enable custom controls
// when the associated parameter has a non-keyframable parameter.
// The effective enable state is the AND of these two enable bits.
/*! \remarks This method is used internally and should not be called by plug-in
developers. This second enable function is used to disable and enable
custom controls when the associated parameter has a non-keyframable
parameter. The effective enable state is the AND of these two enable
bits.\n\n
For example, when a parameter has a controller plugged into it, and the
controller is not keyframable, any spinner control associated with it
won't be effective. That's because the controller doesn't take input --
it only outputs values. To prevent the user from being confused by the
ineffectiveness of the spinner the control it's automatically disabled
by the system using this method.
\param onOff TRUE to enable; FALSE to disable. */
virtual void Enable2(BOOL onOff=TRUE)=0;
// Generic expansion function
/*! \remarks This is a general purpose function that allows the API to be extended in the
future. The 3ds Max development team can assign new <b>cmd</b> numbers and
continue to add functionality to this class without having to 'break' the
API.\n\n
This is reserved for future use.
\param cmd The command to execute.
\param arg1 Optional argument 1 (defined uniquely for each <b>cmd</b>).
\param arg2 Optional argument 2.
\param arg3 Optional argument 3.
\return An integer return value (defined uniquely for each <b>cmd</b>).
\par Default Implementation:
<b>{ return 0; }</b> */
virtual INT_PTR Execute(int cmd, ULONG_PTR arg1=0, ULONG_PTR arg2=0, ULONG_PTR arg3=0) { return 0; }
};
// This is a bitmap brush where the bitmap is a gray and white checker board.
CoreExport HBRUSH GetLTGrayBrush();
CoreExport HBRUSH GetDKGrayBrush();
// Makes the grid pattern brushes solid for screen shots
CoreExport void MakeBrushesSolid(BOOL onOff);
// The standard font...
// The fonts are available in two versions:
// 1. A fixed character set, dependent on the running build of 3ds max. An English build of 3ds max
// will always generate a font that supports the character set.
// 2. The local character set, dependent on the language of the operating system. If running 3ds max
// on a Japanese version of Windows, this font will support the Japanese character set.
// This font is used, for example, on buttons created by MessageBox() on a Japanese build
// of Windows with an English build of 3ds max. In such cases, using GetFixedFont() will
// return a font that is unable to display the Japanese characters. GetFixedFont_LocalCharSet()
// will return a font that is able to display Japanese character, but which may be different
// in typeface and size than GetFixedFont().
// You should usually not have to worry about the LocalCharSet() version, it is mostly for internal use.
//
CoreExport HFONT GetFixedFont();
CoreExport HFONT GetFixedFont_LocalCharSet();
CoreExport HFONT GetFixedFontBold();
CoreExport HFONT GetFixedFontBold_LocalCharSet();
// These routines provide access to the underlying parts of a font if
// needed to do your own manipulation.
//! \brief Returns the standard font height for UI objects
/*!
\return Font height (14 for English & European languages, 12 for Asian languages)
*/
CoreExport LONG GetFixedFontHeight();
//! \brief Returns the small font height for UI object
/*!
\return Font height (8 for English & European languages, 9 for Asian languages)
*/
CoreExport LONG GetFixedFontHeightSmall();
//! \brief Returns character set for the current language
/*!
\return character set for the current language
*/
CoreExport DWORD GetFixedFontCharset();
//! \brief Returns the font face string for the standard font.
/*!
\return Font face string for the standard font.
*/
CoreExport char* GetFixedFontFace();
// The hand cursor used for panning.
CoreExport HCURSOR GetPanCursor();
// Used to update the new mouse-tracking outlined buttons
CoreExport void UpdateButtonOutlines();
//----------------------------------------------------------------------------//
// Customizable UI Frame
#define CUIFRAMECLASS _M("CUIFrame")
// CUI Frame content types
#define CUI_TOOLBAR (1<<0) // set if frame holds toolbars and/or tool palettes
#define CUI_MENU (1<<1) // set if frame holds a menu
#define CUI_HWND (1<<2) // set if frame hold a generic hWnd
// CUI Frame position types
#define CUI_TOP_DOCK (1<<0)
#define CUI_BOTTOM_DOCK (1<<1)
#define CUI_LEFT_DOCK (1<<2)
#define CUI_RIGHT_DOCK (1<<3)
#define CUI_ALL_DOCK (CUI_TOP_DOCK|CUI_BOTTOM_DOCK|CUI_LEFT_DOCK|CUI_RIGHT_DOCK)
#define CUI_HORIZ_DOCK (CUI_TOP_DOCK|CUI_BOTTOM_DOCK)
#define CUI_VERT_DOCK (CUI_LEFT_DOCK|CUI_RIGHT_DOCK)
#define CUI_FLOATABLE (1<<4)
#define CUI_FLOATING (1<<4) // synonym
#define CUI_CONNECTABLE (1<<5)
#define CUI_SM_HANDLES (1<<6) // set if frame should display size/move handles
#define CUI_SLIDING (1<<7) // the frame doesn't butt up against the one next to it.
#define CUI_MAX_SIZED (1<<8) // the frame takes up the entire row. Nothing can be docked next to it.
#define CUI_DONT_SAVE (1<<9) // Don't save this CUI frame in the .cui file
#define CUI_HAS_MENUBAR (1<<10) // CUI frames that have a menu bar need to be treated differently
// CUI Docking Panel locations
#define CUI_NO_PANEL 0
#define CUI_TOP_PANEL CUI_TOP_DOCK
#define CUI_BOTTOM_PANEL CUI_BOTTOM_DOCK
#define CUI_LEFT_PANEL CUI_LEFT_DOCK
#define CUI_RIGHT_PANEL CUI_RIGHT_DOCK
#define CUI_FIXED_PANELS (CUI_TOP_PANEL|CUI_BOTTOM_PANEL|CUI_LEFT_PANEL|CUI_RIGHT_PANEL)
#define CUI_FLOATING_PANELS (1<<4)
#define CUI_ALL_PANELS (CUI_FIXED_PANELS|CUI_FLOATING_PANELS)
#define CUI_POSDATA_MSG (WM_APP + 0x3412) // used for retrieving CUIFrame position data
#define CUI_SUBFRAME_ADDED_MSG (WM_APP + 0x3413) // tells a parent window that an ICUIFrame has been added
#define CUI_SUBFRAME_REMOVED_MSG (WM_APP + 0x3414) // tells a parent window that an ICUIFrame has been removed
#define CUI_PRESET_MACROBUTTONS (WM_APP + 0x3415) // Set MacroButtonStates is about to be called on the toolbar.
#define CUI_SUBFRAME_ACTIVATE_MSG (WM_APP + 0x3416) // tells a parent window that a subframe's active state has changed
// orientation parameters
#define CUI_NONE 0
#define CUI_HORIZ CUI_HORIZ_DOCK
#define CUI_VERT CUI_VERT_DOCK
#define CUI_FLOAT CUI_FLOATING
#define CUI_MIN_TB_WIDTH 25 // minimum width of a CUIFrame-based toolbar
#define CUI_MENU_HIDE 0
#define CUI_MENU_SHOW_ENABLED 1
#define CUI_MENU_SHOW_DISABLED 2
// CUI size parameters
#define CUI_MIN_SIZE 0
#define CUI_MAX_SIZE 1
#define CUI_PREF_SIZE 2
// CUI bitmap button image size (in pixels: 16x15 or 24x24)
#define CUI_SIZE_16 16
#define CUI_SIZE_24 24
// CUI bitmap button image mask options
#define CUI_MASK_NONE 0 // no mask -- MAX should generate one
#define CUI_MASK_MONO 1 // normal Windows convention
#define CUI_MASK_ALPHA 2 // 8-bit alpha channel present
#define CUI_MASK_ALPHA_PREMULT 3 // 8-bit pre-multiplied alpha channel present
// CUI edit types -- not all implemented (yet?)
#define CUI_EDIT_NONE 0
#define CUI_EDIT_KBD (1<<0)
#define CUI_EDIT_SCRIPT (1<<1)
#define CUI_EDIT_MACRO (CUI_EDIT_KBD | CUI_EDIT_SCRIPT)
#define CUI_EDIT_ORDER (1<<2)
/*! \sa Class CUIFrameMsgHandler,
Class ICustomControl.\n\n
\par Description:
This is the object that provides the position data when the
<b>CUIFrameMsgHandler::ProcessMessage()</b> method receives a
<b>CUI_POSDATA_MSG</b> message. The developer creates an instance of this class
and implements the <b>GetWidth()</b> and <b>GetHeight()</b> methods which
return size information based on the size type and orientation passed. */
class CUIPosData: public MaxHeapOperators
{
public:
/*! \remarks Destructor.
\par Default Implementation:
<b>{}</b> */
virtual ~CUIPosData() {}
/*! \remarks Returns the width for the specified size type and
orientation. A return value of -1 indicates that the frame doesn't have a
specific needed value (it doesn't care).
\param sizeType The size type. <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_cui_frame_size_types.html">See List
of CUI Frame Size Types</a>.
\param orient The orientation. <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_cui_frame_orientations.html">See
List of CUI Frame Orientations</a>.
\par Default Implementation:
<b>{ return 50; }</b> */
virtual int GetWidth(int sizeType, int orient) { return 50; }
/*! \remarks Returns the height for the specified size type and
orientation.
\param sizeType The size type. See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_cui_frame_size_types.html">List
of CUI Frame Size Types</a>.
\param orient The orientation. See
<a href="ms-its:listsandfunctions.chm::/idx_R_list_of_cui_frame_orientations.html">List of CUI Frame
Orientations</a>.
\par Default Implementation:
<b>{ return 50; }</b> */
virtual int GetHeight(int sizeType, int orient) { return 50; }
};
// Provides a way for messages received by the CUIFrame to be processed
// in a context-specific fashion. ProcessMessage should return TRUE
// if the message is handled and FALSE if not. If FALSE is returned (or
// no handler is defined), then the CUIFrame simply passes WM_COMMAND
// messages on to its parent. Window position messages are passed from
// the CUIFrame to the HWND of the 'content' (either toolbar or menu)
// Other messages are passed on to DefaultWndProc.
/*! \sa Class ICUIFrame,
Class CUIFrameMgr,
Class CUIPosData,
Class ICustomControl.\n\n
\par Description:
This class provides a way for messages received by a <b>CUIFrame</b> to be
processed in a context-specific fashion.\n\n
Since the CUI Frame is just a window, it needs a window proc. There is one
built into the CUI system, but it may need additional information that is
specific to how the frame is being used. For example, in 3ds Max the command
panel can't be resized horizontally and the default window proc can't manage
this.\n\n
For such situations, the application must install a <b>CUIFrameMsgHandler</b>
object. You establish that this is the handler for the frame using the method
<b>ICUIFrame::InstallMsgHandler(CUIFrameMsgHandler *msgHandler)</b>.\n\n
These message handlers have one significant class method:
<b>ProcessMessage()</b>. If <b>ProcessMessage()</b> returns TRUE, then the CUI
system assumes that the message is completely handled. If it returns FALSE,
then the standard CUI processing takes place. (Note that the message handler
may still return FALSE, even if it does some processing...).\n\n
There is a special message (<b>CUI_POSDATA_MSG</b>) that is sent by the CUI
system to the message handler to get information on window size constraints,
etc. An example of processing this message is shown below. In this case
<b>editPosData</b> is a static instance of <b>CUIPosData</b>. That object has
<b>GetWidth()</b> and <b>GetHeight()</b> methods which return the proper width
and height size for various orientations. See Class CUIPosData for details.\n\n
\code
case CUI_POSDATA_MSG: {
CUIPosData **cpd = (CUIPosData **)lParam;
cpd[0] = &editPosData;
}
return TRUE;
\endcode */
class CUIFrameMsgHandler: public MaxHeapOperators
{
public:
/*! \remarks This method is called to handle any processing not done by
the default CUI window proc.\n\n
This method should return TRUE if the message is handled and FALSE if not.
If FALSE is returned (or no handler is defined), then the CUIFrame simply
passes WM_COMMAND messages on to its parent. Window position messages are
passed from the CUIFrame to the HWND of the 'content' (either a toolbar or
menu). Other messages are passed on to the default window proc.\n\n
Note: Developers should <b>not</b> return TRUE for the <b>entire</b>
ProcessMessage routine, since if this is done, the right-click menu
functionality will not work (e.g. docking, floating, move-to-shelf,
customize, etc.).\n\n
Also Note: Developers should not use IDs that may conflict with the ones
used by the default processing provide by 3ds Max. <b>The IDs which should
be avoided are in the 40000, 47000, and 61000 range</b>. For instance the
following IDs are all invalid since they are in those ranges: 40005, 47900,
61102. The reason this is a problem is that if you return FALSE after
processing a particular ID, then 3ds Max will go ahead and process that ID
also. And if the ID matches one already in 3ds Max, an unintended function
may get called.
\param message Specifies the message.
\param wParam Specifies additional message information. The contents of this parameter
depend on the value of the <b>message</b> parameter.
\param lParam Specifies additional message information. The contents of this parameter
depend on the value of the <b>message</b> parameter.
\par Default Implementation:
<b>{ return FALSE; }</b> */
virtual int ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam) { return FALSE; }
};
class ICustButton;
class ICustStatus;
/*! \sa Class CUIFrameMgr,
Class CUIFrameMsgHandler,
Class ICustToolbar,
Class ICustomControl.\n\n
\par Description:
This class provides access to an individual CUI Frame (the name given to the
windows that contain toolbars, menus, the command panel, etc.)\n\n
To create a floating tool palette, for example, you create a CUIFrame, create a
toolbar, and then attach the two (similar to creating a custom edit field, and
custom spinner, then attaching the two). This is done using the method
<b>ICustToolbar::LinkToCUIFrame()</b>.\n\n
When a Toolbar is part of a CUI frame it's called a Tool Palette. Tool Palettes
can either float or dock (whereas a Toolbar must be placed by the developer in
a dialog using the resource editor). */
class ICUIFrame : public ICustomControl {
public:
// CUIFrame attributes
/*! \remarks Sets the position type. This determines the possible
locations for the frame.
\param t The position to set. See
<a href="ms-its:listsandfunctions.chm::/idx_R_list_of_cui_frame_position_types.html">List of CUI Frame
Position Types</a>. */
virtual void SetPosType(DWORD t)=0;
/*! \remarks Returns a DWORD which describes the position options for this
CUI Frame. See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_cui_frame_position_types.html">List
of CUI Frame Position Types</a>. */
virtual DWORD GetPosType()=0;
/*! \remarks This method is for internal use only. Developers must not
assign the rank and subrank as these are computed internally. Developers
should create their toolbars 'floating'. Then when a user docks the toolbar
it will be docked automatically when 3ds Max starts up the next time. */
virtual void SetPosRank(int rank, int subrank=0)=0;
/*! \remarks Returns the position rank. Consider three docked toolbars, one
alone on the top line, and two side by side on the line below. The top
toolbar would have a rank of 0 (and a subrank of 0). The toolbar on the
left in the line below would have a rank of 1 and a subrank of 0. The
toolbar beside it to the right would have a rank of 1 and a subrank of 1.
*/
virtual int GetPosRank()=0;
/*! \remarks Returns the position subrank. See <b>GetPosRank()</b> above.
*/
virtual int GetPosSubrank()=0;
/*! \remarks Returns TRUE if the frame is floating (not docked); otherwise
FALSE. */
virtual BOOL IsFloating()=0;
/*! \remarks Sets the frame to hidden or not. Note that if a developer is
doing something like showing their toolbars at <b>BeginEditParams()</b> and
hiding them at <b>EndEditParms()</b> then this method can be used. In such
a case, if the toolbar is docked then <b>RecalcLayout()</b> needs to be
called to update the layout. If the toolbars are floating then
<b>RecalcLayout()</b> does not need to be called.
\param b TRUE for hidden; FALSE for not hidden. */
virtual void Hide(BOOL b)=0;
/*! \remarks Returns TRUE if the frame is hidden; FALSE if visible. */
virtual BOOL IsHidden()=0;
/*! \remarks This method is for internal use only. */
virtual void SetCurPosition(DWORD pos)=0;
/*! \remarks Returns the current position of the frame. One of the
following values.\n\n
<b>CUI_TOP_DOCK</b>\n\n
Docked at the top.\n\n
<b>CUI_BOTTOM_DOCK</b>\n\n
Docked at the bottom.\n\n
<b>CUI_LEFT_DOCK</b>\n\n
Docked on the left.\n\n
<b>CUI_RIGHT_DOCK</b>\n\n
Docked on the right.\n\n
<b>CUI_FLOATING</b>\n\n
The frame is floating (not docked). */
virtual DWORD GetCurPosition()=0;
/*! \remarks Sets the frame contents type. This specifies if this frame
holds a toolbar, menu or a floating panel.
\param t One or more of the following flags:\n\n
<b>CUI_TOOLBAR</b>\n
Set if frame holds toolbars and / or tool palettes.\n\n
<b>CUI_MENU</b>\n
This is used internally to set if the frame holds a menu. Note: Developers
should not create their own menus. 3ds Max assumes that only one menu
exists.\n\n
<b>CUI_HWND</b>\n
Set if frame hold a generic window handle. The command panel (which can be
floated) is an example of a generic window. */
virtual void SetContentType(DWORD t)=0;
/*! \remarks Returns a value which indicates the frame contents type. One
of the following flags:\n\n
<b>CUI_TOOLBAR</b>\n\n
Set if frame holds toolbars and / or tool palettes.\n\n
<b>CUI_MENU</b>\n\n
Set if the frame holds a menu.\n\n
<b>CUI_HWND</b>\n\n
Set if frame hold a generic window handle. */
virtual DWORD GetContentType()=0;
/*! \remarks Sets the content handle. This is the window handle for the
toolbar, or menu handle for a menu. Developers typically create Tool
Palettes by linking a toolbar to a CUIFrame using
<b>ICustToolbar::LinkToCUIFrame()</b> and do not need to call this method
as it's done automatically.
\param hContent The handle to set. */
virtual void SetContentHandle(HWND hContent)=0;
/*! \remarks Returns the content handle. */
virtual HWND GetContentHandle()=0;
/*! \remarks Sets if this frame represents a tabbed toolbar. A tabbed
toolbar may have individual tabs added and deleted.
\param b TRUE for tabbed; FALSE for not tabbed. */
virtual void SetTabbedToolbar(BOOL b)=0;
/*! \remarks Returns TRUE if this frame is a tabbed toolbar; otherwise
FALSE. */
virtual BOOL GetTabbedToolbar()=0;
/*! \remarks Adds the toolbar tab whose window handle is passed to the list of
tabs maintained by this class.
\param hTBar The window handle of the toolbar tab to add.
\param msgHandler The message handler for the tab or NULL if not used.
\param name The name for the tab.
\param pos The position for the tab. This is the zero based index where 0 is at left edge
of those in the frame and the max value is <b>GetToolbarCount()-1</b>. A value
of -1 adds the tab to the end of the list of tabs. Also, for example, if you
specify a value of 0 for an existing tabbed toolbar, the new tab is inserted
at position 0 and the others are moved to the right. */
virtual void AddToolbarTab(HWND hTBar, CUIFrameMsgHandler *msgHandler, MCHAR *name, int pos = -1)=0;
/*! \remarks Deletes the specified toolbar tab.
\param pos Specifies the position of the tab to delete. This is the zero based index
where 0 is at left edge of those in the frame and the max value is
<b>GetToolbarCount()-1</b>. */
virtual void DeleteToolbarTab(int pos)=0;
/*! \remarks Returns the number of toolbar tabs in this frame. */
virtual int GetToolbarCount()=0;
/*! \remarks Returns the window handle of the toolbar tab whose position
is passed.
\param pos Specifies the position of the tab. This is the zero based index where 0 is
at left edge of those in the frame and the max value is <b>GetToolbarCount()-1</b>. */
virtual HWND GetToolbarHWnd(int pos)=0;
/*! \remarks Returns the name of the specified toolbar tab.
\param pos Specifies the position of the tab. This is the zero based index where 0 is
at left edge of those in the frame and the max value is <b>GetToolbarCount()-1</b>. */
virtual MCHAR *GetTabName(int pos)=0;
/*! \remarks Sets the currently active tab.
\param pos Specifies the position of the tab. This is the zero based index where 0 is
at left edge of those in the frame and the max value is <b>GetToolbarCount()-1</b>. */
virtual void SetCurrentTab(int pos)=0;
/*! \remarks Returns the position of the currently active tab. This is the
zero based index where 0 is at left edge of those in the frame and the max
value is <b>GetToolbarCount()-1</b>. */
virtual int GetCurrentTab()=0;
/*! \remarks Returns the size of this frame for the specified size type,
direction (width or height) and orientation.\n\n
Note: If this frame has a custom message handler (a <b>CUIFrameMsgHandler</b>
object, it's <b>ProcessMessage()</b> method is called passing
<b>CUI_POSDATA_MSG</b> which is used to determine the size.
\param sizeType The size type. See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_cui_frame_size_types.html">List of
CUI Frame Size Types</a>.
\param dir The direction of the frame.\n\n
<b>CUI_HORIZ</b>: Width.\n\n
<b>CUI_VERT</b>: Height.\n
\param orient The orientation. See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_cui_frame_orientations.html">List
of CUI Frame Orientations</a>. */
virtual int GetSize(int sizeType, int dir, int orient)=0;
/*! \remarks Installs a custom message processing routine.
\param msgHandler Points to the handler to install. See
Class CUIFrameMsgHandler for details.
\return TRUE on success; otherwise FALSE. */
virtual BOOL InstallMsgHandler(CUIFrameMsgHandler *msgHandler)=0;
/*! \remarks Sets the name for the frame. This name shows up as a tooltip
and also on the window border if the frame is floated. Note that the name
is also used to store position information in the CUI file. Therefore
developers must use a name and not simply set it to NULL.
\param name The name to set. */
virtual void SetName(MCHAR *name)=0; // name is used to store position info
/*! \remarks Returns the name of the frame. */
virtual MCHAR *GetName()=0;
/*! \remarks Sets the menu display state.
\param md One of the following values:\n\n
<b>CUI_MENU_HIDE</b>\n
<b>CUI_MENU_SHOW_ENABLED</b>\n
<b>CUI_MENU_SHOW_DISABLED</b> */
virtual BOOL SetMenuDisplay(int md)=0;
/*! \remarks Returns the state of the menu display. One of the following
values:\n\n
<b>CUI_MENU_HIDE</b>\n
<b>CUI_MENU_SHOW_ENABLED</b>\n
<b>CUI_MENU_SHOW_DISABLED</b> */
virtual int GetMenuDisplay()=0;
/*! \remarks System windows are those that come up automatically inside
3ds Max. So command panel, the main toolbar, the tab panel and the main
menu are all system windows. It is not therefore appropriate for developers
to declare themselves as system windows and this method should not be
called passing TRUE.
\param b TRUE to set as a system window; otherwise FALSE. */
virtual void SetSystemWindow(BOOL b)=0; // set to TRUE for main UI, only works if parent is the main MAX hWnd
/*! \remarks Returns TRUE if this CUIFrame is a system window; otherwise
FALSE. See <b>SetSystemWindow()</b> above. */
virtual BOOL GetSystemWindow()=0;
/*! \remarks This method is for internal use only. */
virtual BOOL ReadConfig(MCHAR *cfg, int startup=FALSE)=0; // returns FALSE if no position has been saved
/*! \remarks This method is for internal use only. */
virtual void WriteConfig(MCHAR *cfg)=0;
};
/*! \remarks Initializes the pointer to the CUI Frame control.
\param hCtrl window handle of the control. */
CoreExport ICUIFrame *GetICUIFrame( HWND hCtrl );
/*! \remarks Releases the specified control.
\param icf to the frame to release. */
CoreExport void ReleaseICUIFrame( ICUIFrame *icf );
/*! \remarks Creates a CUI Frame Window with the specified window handle, size
and title parameters. Values of 0 may be passed for x, y, cx and cy. This
indicates that the initial size doesn't matter. For example, when the 3ds Max
CUI is created initially everything is docked. 3ds Max then calls
<b>CUIFrameMgr::RecalcLayout()</b> which computes all the sizes. Thus the
values passed don't matter since they are all going to be recalculated anyway.
\param hParent handle of the parent window for the frame.
\param title title for the frame. This effectively calls <b>SetName()</b> below to
establish a name for the frame.
\param x x coordinate of the upper left corner.
\param y y coordinate of the upper left corner.
\param cx x size.
\param cy y size.
\return If the function succeeds, the return value is the window handle to the
dialog box. If the function fails, the return value is NULL. */
CoreExport HWND CreateCUIFrameWindow(HWND hParent, MCHAR *title, int x, int y, int cx, int cy);
#define CUI_MODE_NORMAL 0
#define CUI_MODE_EDIT 1
/*! \sa Class ICUIFrame,
Class CUIFrameMsgHandler,
Class ICustToolbar,
Class ICustomControl,
Class ICustStatus,
Class MAXBmpFileIcon.\n\n
\par Description:
***reflect changes with MAXBMPFileIcon class***\n\n
This object controls the overall operation of the individual CUI Frames (the
name given to the windows that contain toolbars, menus, the command panel,
etc.). There is one instance of this CUIFrameMgr class (obtained by calling the
global function <b>GetCUIFrameMgr()</b>). Methods of this class are available
to do things like float and dock individual windows, get pointers to frames,
get pointers to button and status controls, and bring up the standard toolbar
right click menu .\n\n
Note: Developers may use their own images on icon buttons that are managed by
this class but the following guidelines must be followed:\n\n
BMP files must be put in the <b>/UI/icons</b> folder. This is the UI directory
under the 3ds Max EXE directory. This is hard coded because it must be
retrieved before 3ds Max is fully started and thus there is no configurable
path for it. There is a command line option however, (-c), which specifies for
3ds Max to look in an alternate directory for the CUI file. In that case the
bitmap files should be located in the same directory.\n\n
For more information on the new icon image system refer to the chapter on
<a href="ms-its:3dsmaxsdk.chm::/ui_customization_external_icons.html">external
icons</a>. */
class CUIFrameMgr : public BaseInterfaceServer {
private:
HWND hApp;
void RecalcPanel(int panel);
int GetMaxRank(int panel);
int GetMaxSubrank(int panel, int rank);
void GetDockRect(int panel, int rank, RECT *rp);
int GetDockingRank(int panel, RECT *rp = NULL);
int GetDockingSubrank(int panel, int rank, RECT *rp = NULL);
void AdjustRanks(int panel, int start, int incr);
void AdjustSubranks(int panel, int rank, int start, int incr);
int resSize[4];
int mode;
int horizTextBtns;
int fixedWidthTextBtns;
int btnWidth;
int imageSize;
int lockLayout;
CUIFrameMsgHandler *defMsgHandler;
protected:
MSTR cfgFile;
//! \brief Constructor made protected to prevent instantiation
/*! Blocking default constructor - use GetCUIFrameMgr() accessor
*/
/*! \remarks Constructor. */
CoreExport CUIFrameMgr();
//! \brief Copy Constructor made protected to prevent instantiation
/*! Blocking Copy constructor - use GetCUIFrameMgr() accessor
*/
CUIFrameMgr(CUIFrameMgr& frame);
/*! \remarks Destructor. */
CoreExport virtual ~CUIFrameMgr();
public:
/*! \remarks This method is for internal use only. */
CoreExport void SetAppHWnd(HWND hApp);
HWND GetAppHWnd() { return hApp; }
/*! \remarks Returns the directory name of the custom user interface (CUI)
file location. */
CoreExport MCHAR *GetCUIDirectory();
/*! \remarks This brings up the CUI right click menu (with the Add Tab,
Delete Tab, etc selections). Also see the global function
<b>DoCUICustomizeDialog()</b>.
\param hWnd The handle of the window there the mouse was clicked.
\param x The x coordinate of the mouse when right clicked.
\param y The y coordinate of the cursor when right clicked. */
CoreExport void ProcessCUIMenu(HWND hWnd, int x, int y);
/*! \remarks This method docks the CUI window whose handle is passed.
Developers who want to dock a window should use this method by passing a
rectangle which specifies the general area of the screen where the window
is to be docked. This will cause 3ds Max reorganize the existing windows.
\param hWnd The handle of the window to dock.
\param panel The CUI docking panel location. One of the following values:\n\n
<b>CUI_TOP_DOCK</b>\n
Docked at the top.\n\n
<b>CUI_BOTTOM_DOCK</b>\n
Docked at the bottom.\n\n
<b>CUI_LEFT_DOCK</b>\n
Docked on the left.\n\n
<b>CUI_RIGHT_DOCK</b>\n
Docked on the right.
\param rp This is the rectangle which specifies where to dock the window. This is the
rectangle that a user moves around the screen when dragging a floating
window over top of a docking region. This is specified in screen
coordinates. If NULL is passed the window is docked using <b>CUI_TOP_DOCK</b>.
\param init This is used internally by 3ds Max when it's starting up. This should
always default to FALSE (don't override this and pass TRUE). */
CoreExport void DockCUIWindow(HWND hWnd, int panel, RECT *rp = NULL, int init = FALSE);
/*! \remarks Floats (un-docks) the specified CUI Window.
\param hWnd The window to float.
\param rp Specifies the rectangle in screen coordinates where the floating window
should reside. If NULL is passed the window is restored to the position it
was before it was docked (this information is stored in the CUI file).\n\n
Note: Calling this method on an already floating window will explicitly NOT
resize the window, but rather just move it to the new origin. Said another
way, only the left and top members of the rectangle are used on an already
floating window. Developers should call the Win32 API MoveWindow or
SetWindowPlacement to size the window. See <b>GetFloatingCUIFrameSize()</b>
below to compute a size.
\param init This is used internally by 3ds Max when it's starting up. This should
always default to FALSE (don't override this and pass TRUE). */
CoreExport void FloatCUIWindow(HWND hWnd, RECT *rp = NULL, int init = FALSE);
/*! \remarks This method is for internal use only. */
CoreExport void SetReservedSize(int panel, int size);
/*! \remarks This method is for internal use only. */
CoreExport int GetReservedSize(int panel);
/*! \remarks This method is for internal use only. */
CoreExport int GetPanelSize(int panel, int incReserved = FALSE);
CoreExport int GetPanelWidth(int panel); // R4.5 and later only
/*! \remarks This method may be called to recalculates the layout of the
CUI. Developers need to call this method after they, for example, add new
tool palettes. A developer would create the new palettes and then call this
method when done. Otherwise the changes wouldn't be reflected until the
user redrew the viewports or resized 3ds Max.
\param entireApp TRUE to recalculate the entire application, including the viewports. This
can be expensive (basically like an
<b>Interface::ForceCompleteRedraw()</b>); FALSE will recalculate the top,
bottom, left and right panels but won't redraw the viewports. */
CoreExport void RecalcLayout(int entireApp=FALSE);
/*! \remarks This method redraws the specified panels. Typically
developers don't need to call this method.
\param panels See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_cui_docking_panel_locations.html">List of CUI
Docking Panel Locations</a>. */
CoreExport void DrawCUIWindows(int panels=CUI_ALL_PANELS);
/*! \remarks This is a very important method. It redraws all the visible CUI buttons in
3ds Max, calling the "IsEnabled" and<br> "IsChecked" handlers on the
ActionItems associated with each button (if it has one). If a the
"IsEnabled" handler returns FALSE, the button is grayed out. If the
"IsChecked" handler return TRUE, the button is draw pressed in.\n\n
This method is called internally by the system on selection changes and
command mode changes. This handles the majority of the cases where buttons
need to be redrawn. However, if a 3rd party plug-in changes some sort of
internal state that might affect the return value of an ActionItem's
IsEnables or IsChecked handler, then the plug-in should call this method to
update the button states. If this method isn't called, buttons may look
disabled or pressed (or visa versa) when they shouldn't be. See
Class ActionItem.
\param force This parameter, if TRUE, tells the system to redraw the button even if its
state hasn't changed since the last time it was redrawn. Normally this
argument is FALSE so it only redraws the buttons that changed state. */
CoreExport void SetMacroButtonStates(BOOL force);
/*! \remarks This method is for internal use only. This is automatically called when the
system changes its custom colors. It tells all the buttons on toolbars to
toss their icon image cache.\n\n
This method only resets the icons for toolbars that are part of the CUI
system, not for toolbars created by other code, which is why the
<b>ICustToolbar</b> method <b>ResetIconImages()</b> is needed. See the
method <b>ICustToolbar::ResetIconImages</b>. */
CoreExport void ResetIconImages();
/*! \remarks Given a point and a position type this method returns nonzero
if the point is over the specified docking region; otherwise zero.
\param pt The input point to check in screen coordinates.
\param posType See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_cui_frame_position_types.html">List of CUI Frame
Position Types</a>.
\param override Passing TRUE overrides the docking function so that it won't dock. Passing
FALSE will cause it to dock. Also note that if the UI layout is locked,
passing TRUE here will override that lock.\n\n
In the code fragment below the state of the Ctrl key is checked and used as
the docking override.
\par Sample Code:
\code
GetCursorPos(&pt);
overDockRegion = GetCUIFrameMgr()->OverDockRegion(&pt, cf->GetPosType(), (GetKeyState(VK_CONTROL) & 0x8000));
\endcode */
CoreExport int OverDockRegion(LPPOINT pt, DWORD posType, int override = FALSE);
/*! \remarks This method is for internal use only. */
CoreExport void SetMode(int md);
/*! \remarks This method is for internal use only. */
CoreExport int GetMode();
/*! \remarks This method is for internal use only. Calling this method
alone will not put 3ds Max in Expert mode. */
CoreExport void ExpertMode(int onOff);
CoreExport void HideFloaters(int onOff);
/*! \remarks Returns the window handle for the item whose ID is passed.
This correspond to the method in <b>ICustToolbar</b> but which should no
longer be called for Tool Palettes. It is now also a method of this class
because the CUI system doesn't know which toolbar a particular button is
on. For example, a 3ds Max user in 3.0 can drag a button from one tool
palette to another. No longer then can one use the previous
<b>GetItemHwnd()</b> method since the button has moved to a different
toolbar.
\param id The ID of the control. */
CoreExport HWND GetItemHwnd(int id);
/*! \remarks Returns a pointer to the custom button whose ID is passed (or
NULL if not found). In the <b>CUIFrameMgr</b> implementation of this method
it loops through each toolbar that it has control over and calls
<b>ICustToolbar::GetICustButton()</b> on it. That method returns NULL if it
doesn't find the specified ID. The CUIFrameMgr keeps looping through the
toolbars until it gets a non-NULL value. When it finds it it returns the
<b>ICustButton</b> pointer.
\param id The ID of the control. */
CoreExport ICustButton *GetICustButton( int id );
/*! \remarks Returns a pointer to the custom status control whose ID is
passed.\n\n
Returns a pointer to the custom status control whose ID is passed (or NULL
if not found). In the <b>CUIFrameMgr</b> implementation of this method it
loops through each toolbar that it has control over and calls
<b>ICustToolbar::GetICustStatus()</b> on it. That method returns NULL if it
doesn't find the specified ID. The <b>CUIFrameMgr</b> keeps looping through
the toolbars until it gets a non-NULL value. When it finds it it returns
the <b>ICustStatus</b> pointer.
\param id The ID of the control. */
CoreExport ICustStatus *GetICustStatus( int id );
/*! \remarks This method is for internal use only. */
CoreExport void HorizTextButtons(BOOL b);
/*! \remarks This method is for internal use only. */
CoreExport int GetHorizTextButtons();
/*! \remarks This method is for internal use only. */
CoreExport void FixedWidthTextButtons(BOOL b);
/*! \remarks This method is for internal use only. */
CoreExport int GetFixedWidthTextButtons();
/*! \remarks This method is for internal use only. */
CoreExport void SetTextButtonWidth(int w);
/*! \remarks This method is for internal use only. */
CoreExport int GetTextButtonWidth();
/*! \remarks Returns the number of frames that exist. */
CoreExport int GetCount();
/*! \remarks Returns a pointer to the CUI Frame as specified by the index
passed.
\param i The zero based index in the list of frames (between <b>0</b> and <b>GetCount()-1</b>). */
CoreExport ICUIFrame *GetICUIFrame(int i);
/*! \remarks Returns a pointer to the CUI Frame as specified by the name passed.
\param name The name of the frame. */
CoreExport ICUIFrame *GetICUIFrame(MCHAR *name);
/*! \remarks Returns a pointer to the CUI Frame as specified by the panel,
rank and subrank passed.
\param panel One of a set of values.
\param rank The zero based rank index.
\param subrank The zero based sub-rank index. */
CoreExport ICUIFrame *GetICUIFrame(int panel, int rank, int subrank);
/*! \remarks This method is for internal use only. */
CoreExport int SetConfigFile(MCHAR *cfg);
/*! \remarks This returns the path to the CUI file in use. This may be a
UNC name. */
CoreExport MCHAR *GetConfigFile();
/*! \remarks This method is for internal use only. */
CoreExport int DeleteSystemWindows(int toolbarsOnly = TRUE);
/*! \remarks This method is for internal use only. */
CoreExport int CreateSystemWindows(int reset = FALSE);
CoreExport int GetSystemWindowCount();
/*! \remarks This method is for internal use only. */
CoreExport void SetImageSize(int size) { imageSize = size; }
/*! \remarks This method is for internal use only. */
CoreExport int GetImageSize() { return imageSize; }
/*! \remarks Returns the bitmap button image height for the specified
size.
\param sz The size to check. If 0 is passed then the current icon size is checked.
One of the following values:\n\n
<b>CUI_SIZE_16</b>\n
<b>CUI_SIZE_24</b> */
CoreExport int GetButtonHeight(int sz=0) { if(!sz) sz=imageSize; return sz==CUI_SIZE_16 ? 22 : 31; }
/*! \remarks Returns the bitmap button image width for the specified size.
\param sz The size to check. One of the following values:\n\n
<b>CUI_SIZE_16</b>\n
<b>CUI_SIZE_24</b> */
CoreExport int GetButtonWidth(int sz=0) { if(!sz) sz=imageSize; return sz==CUI_SIZE_16 ? 23 : 32; }
/*! \remarks This method is for internal use only. */
CoreExport void SetDefaultData(CUIFrameMsgHandler *msg, HIMAGELIST img16, HIMAGELIST img24=NULL);
/*! \remarks This method is used internally to create a MaxBmpFileIcon for a given
object type. These methods retrieve the file name and base index in the
file of the icon for the given object class. They are used in the
constructor for MaxBmpFileIcon that takes a class ID and super class ID.
This method is for internal use only. */
CoreExport int GetDefaultImageListBaseIndex(SClass_ID sid, Class_ID cid);
/*! \remarks This method is used internally to create a MaxBmpFileIcon for a given
object type. These methods retrieve the file name and base index in the
file of the icon for the given object class. They are used in the
constructor for MaxBmpFileIcon that takes a class ID and super class ID.
This method is for internal use only. */
CoreExport MSTR* GetDefaultImageListFilePrefix(SClass_ID sid, Class_ID cid);
/*! \remarks This method is for internal use only. It is used to add images to the icon
manager. The icon manager, which is used to implement the
<b>MaxBmpFileIcon</b> class, reads all the .bmp files in the UI/Icons
directory at startup time. These icons are specified by an image file and
an alpha mask. The icons support two sizes. Large, which is 24 by 24 and
small, which is 15 by 16. The icon manager stores the unprocessed image and
alpha masks (the "raw" images). Whenever an instance of MaxBmpFileIcon
needs to draw itself, it gets the image list and index of the icon in the
imagelist using <b>GetSmallImageIndex</b> or <b>GetLargeImageIndex.</b> */
CoreExport int AddToRawImageList(MCHAR* pFilePrefix, int sz, HBITMAP image, HBITMAP mask);
/*! \remarks This method is for internal use only. */
CoreExport int LoadBitmapFile(MCHAR *filename);
/*! \remarks This method is for internal use only. */
CoreExport int LoadBitmapImages();
/*! \remarks Returns a pointer to the default CUI Frame Message Handler.
*/
CoreExport CUIFrameMsgHandler *GetDefaultMsgHandler() { return defMsgHandler; }
/*! \remarks Plug-In developers should not call this method -- it is for
internal use only. */
CoreExport int ReadConfig();
/*! \remarks Plug-In developers should not call this method -- it is for
internal use only. */
CoreExport int WriteConfig();
/*! \remarks This method is for internal use only. */
CoreExport void SetLockLayout(BOOL lock) { lockLayout = lock; }
/*! \remarks Returns TRUE if the layout is locker; FALSE if unlocked. */
CoreExport BOOL GetLockLayout() { return lockLayout; }
/*! \remarks This method is for internal use only. */
CoreExport void EnableAllCUIWindows(int enabled);
//! \brief Given a configuration filename, will attempt to find the best match
/*! If the application is configured to use User Profiles, this function will attempt
to match the filename in the user profile UI directory. If this fails, it will
check the system directory.
\see IPathConfigMgr::IsUsingProfileDirectories()
\see IPathConfigMgr::IsUsingRoamingProfiles()
\param aFilename [in] the filename to match, with extension
\param aResult [out] the resulting absolute path for the matched file, if found
\return true if a match is found, false otherwise
*/
CoreExport virtual bool ResolveReadPath(const MSTR& aFilename, MSTR& aResult) = 0;
//! \brief Given a configuration filename, will resolve the correct write absolute path
/*! If the application is configured to use User Profiles, this function map this configuration
file to a user profile directory. Otherwise, the configuration file will be resolved to
the legacy system UI directory.
\see IPathConfigMgr::IsUsingProfileDirectories()
\see IPathConfigMgr::IsUsingRoamingProfiles()
\param aFilename [in] the filename to match, with extension
\param aResult [out] the resulting absolute path to which a client should write a config file
\return true if resolved correctly, false if any error is encountered
*/
CoreExport virtual bool ResolveWritePath(const MSTR& aFilename, MSTR& aResult) = 0;
};
/*! \remarks Returns a pointer to the CUIFrameMgr which controls the overall
operation of CUI Frames (the windows which contain toolbars, menus, the command
panel, etc). */
CoreExport CUIFrameMgr *GetCUIFrameMgr();
/*! \remarks This global function presents the Customize User Interface
dialog. */
CoreExport void DoCUICustomizeDialog();
/*! \remarks Returns TRUE if all floaters are hidden; otherwise FALSE. */
CoreExport BOOL AllFloatersAreHidden();
CoreExport void ResizeFloatingTB(HWND hWnd);
#define MB_TYPE_KBD 1
#define MB_TYPE_SCRIPT 2
#define MB_TYPE_ACTION 3
#define MB_TYPE_ACTION_CUSTOM 4
#define MB_FLAG_ENABLED (1 << 0)
#define MB_FLAG_CHECKED (1 << 1)
typedef DWORD ActionTableId;
typedef DWORD ActionContextId;
class ActionItem;
/*! \sa Class ToolMacroItem,
Class MacroEntry,
Class MacroDir,
Class ICustButton,
Class ICustomControl,
Class ActionItem,
<a href="ms-its:3dsmaxsdk.chm::/ui_customization_root.html">User Interface Customization</a>.\n\n
\par Description:
A Macro Button is a button which can execute either a keyboard macro or macro
script. This class contains the data and access methods for such a UI button.
This data includes a macro type, command ID, macro script ID, label, tooltip,
image name, and image ID.\n\n
This object is used in the <b>ToolMacroItem</b> constructor. There are also
methods of class <b>ICustButton</b> to get and set the macro button data.
\par Data Members:
<b>int macroType;</b>\n\n
The macro type. One of the following values:\n\n
<b>MB_TYPE_KBD</b>\n\n
A keyboard macro.\n\n
<b>MB_TYPE_SCRIPT</b>\n\n
A Script macro.\n\n
<b>ActionTableId tblID;</b>\n\n
The Shortcut Action Table ID.\n\n
<b>void *cb;</b>\n\n
The ShortcutCallback. This is currently not used.\n\n
<b>int cmdID;</b>\n\n
The command ID. There are method of class <b>Interface</b> that provide access
to the command IDs for various keyboard shortcut tables. See
<a href="class_interface.html#A_GM_inter_keyboard_shortcut">Keyboard Shortcut
Related Methods</a>.\n\n
<b>int macroScriptID;</b>\n\n
The macroScriptID holds the id of the macroScript associated with this button.
This id is the <b>MacroID</b> that is used by the methods in the
<b>MacroDir</b> and <b>MacroEntry</b> classes (at one time it was an indirect
reference to this id and so was typed as an int). The id can have values from 0
to the number of macro scripts currently defined in the running 3ds Max or the
special value <b>UNDEFINED_MACRO</b>.\n\n
<b>TCHAR *label;</b>\n\n
The label text for a text button. This is used if <b>imageID</b> is -1.\n\n
<b>TCHAR *tip;</b>\n\n
The tooltip text.\n\n
<b>TCHAR *imageName;</b>\n\n
This is the name for the button image. This is the 'base' name only. For
example if the actual image name was <b>Spline_16i.bmp</b> then the name
supplied here would be <b>Spline</b>. See the remarks in
Class CUIFrameMgr for details on the
image naming scheme the CUI system uses.\n\n
<b>int imageID;</b>\n\n
The image ID. If this is set to -1 it indicates to use the <b>label</b>. If it
is set to 0 or greater it indicates this is an image based button and this is
the zero based index of the button that was added. This then is an ID into an
image group as specified by <b>imageName</b>. Said another way, 3ds Max builds
one large image list internally and uses the <b>imageName</b> to get an offset
into the list and then uses this <b>imageID</b> as an additional offset from
the start as indicated by the name (each <b>imageName</b> may contain multiple
icons in the single BMP).\n\n
<b>ActionItem* actionItem;</b>\n\n
A pointer to the ActionItem.\n\n
<b>DWORD flags;</b>\n\n
These flags contain the last state when redrawing */
class MacroButtonData: public MaxHeapOperators {
public:
/*! \remarks Constructor. The data members are initialized as follows:\n\n
<b>label = tip = imageName = NULL; imageID = -1;</b> */
CoreExport MacroButtonData() { label = tip = imageName = NULL; imageID = -1; }
/*! \remarks Constructor. This one is used for keyboard macro buttons
(<b>MB_TYPE_KBD</b>). The data members are initialized to the values passed as
shown:\n\n
<b>macroType=MB_TYPE_KBD; tblID=tID; this-\>cb=cb; cmdID=cID; imageID=imID;
label=NULL; SetLabel(lbl); tip=NULL; SetTip(tp); imageName=NULL;
SetImageName(imName);</b> */
CoreExport MacroButtonData(long tID, int cID, MCHAR *lbl, MCHAR *tp=NULL, int imID=-1, MCHAR *imName=NULL);
/*! \remarks Constructor. This one is used for macro script buttons
(<b>MB_TYPE_SCRIPT</b>). The data members are initialized to the values
passed as shown:\n\n
<b>macroType=MB_TYPE_SCRIPT; macroScriptID=msID; imageID=imID; label=NULL;
SetLabel(lbl); tip=NULL; SetTip(tp); imageName=NULL;
SetImageName(imName);</b> */
CoreExport MacroButtonData(int msID, MCHAR *lbl, MCHAR *tp=NULL, int imID=-1, MCHAR *imName=NULL)
{
macroType=MB_TYPE_SCRIPT; macroScriptID=msID; imageID=imID;
label=NULL; SetLabel(lbl); tip=NULL; SetTip(tp); imageName=NULL; SetImageName(imName);
}
/*! \remarks Destructor. Any label, tooltip or image name strings are
deleted. */
CoreExport ~MacroButtonData();
/*! \remarks Assignment operator. */
CoreExport MacroButtonData & operator=(const MacroButtonData& mbd);
/*! \remarks Sets the label text.
\param lbl The label to set. */
CoreExport void SetLabel(MCHAR *lbl);
/*! \remarks Returns the label text. */
MCHAR *GetLabel() { return label; }
/*! \remarks Sets the tooltip text.
\param tp The text to set. */
CoreExport void SetTip(MCHAR *tp);
/*! \remarks Returns the tooltip text. */
MCHAR *GetTip() { return tip; }
/*! \remarks Sets the command ID.
\param id The command ID to set. */
void SetCmdID(int id) { cmdID = id; }
/*! \remarks Returns the command ID. */
int GetCmdID() { return cmdID; }
/*! \remarks Sets the script ID.
\param id The script ID to set. */
void SetScriptID(int id){ macroScriptID = id; }
/*! \remarks Returns the script ID. */
int GetScriptID() { return macroScriptID; }
/*! \remarks Sets the image name. See the <b>imageName</b> data member
above for details on the name format.
\param imName The name to set. */
CoreExport void SetImageName(MCHAR *imName);
/*! \remarks Returns the image name. */
MCHAR *GetImageName() { return imageName; }
/*! \remarks Sets the image ID.
\param id The image ID to set. */
void SetImageID(int id) { imageID = id; }
/*! \remarks Retuns the image ID. */
int GetImageID() { return imageID; }
/*! \remarks This method sets the ActionTableID ID.
\param id The ActionTableID ID to set. */
void SetTblID(ActionTableId id) { tblID = id; }
/*! \remarks This method returns the ActionTableID ID. */
ActionTableId GetTblID() { return tblID; }
/*! \remarks This method allows you to set the ActionItem.
\param pAction A point to the ActionItem to set. */
void SetActionItem(ActionItem* pAction) { actionItem = pAction; }
/*! \remarks This method returns a pointer to the ActionItem. */
ActionItem* GetActionItem() { return actionItem; }
/*! \remarks This method returns TRUE if the button is an Action button. FALSE if it is
not. */
CoreExport BOOL IsActionButton() { return macroType == MB_TYPE_ACTION_CUSTOM ||
macroType == MB_TYPE_ACTION; }
int macroType;
ActionTableId tblID;
int cmdID;
int macroScriptID;
MCHAR * label;
MCHAR * tip;
MCHAR * imageName;
int imageID;
ActionItem* actionItem;
// flags constrains the last state when redrawing
DWORD flags;
};
//---------------------------------------------------------------------------//
// Spinner control
#define SPINNERWINDOWCLASS _M("SpinnerControl")
// LOWORD(wParam) = ctrlID,
// HIWORD(wParam) = TRUE if user is dragging the spinner interactively.
// lParam = pointer to ISpinnerControl
#define CC_SPINNER_CHANGE WM_USER + 600
// LOWORD(wParam) = ctrlID,
// lParam = pointer to ISpinnerControl
#define CC_SPINNER_BUTTONDOWN WM_USER + 601
// LOWORD(wParam) = ctrlID,
// HIWORD(wParam) = FALSE if user cancelled - TRUE otherwise
// lParam = pointer to ISpinnerControl
#define CC_SPINNER_BUTTONUP WM_USER + 602
enum EditSpinnerType {
EDITTYPE_INT,
EDITTYPE_FLOAT,
EDITTYPE_UNIVERSE,
EDITTYPE_POS_INT,
EDITTYPE_POS_FLOAT,
EDITTYPE_POS_UNIVERSE,
EDITTYPE_TIME
};
/*! \sa Class ICustomControl,
<a href="ms-its:3dsmaxsdk.chm::/ui_custom_controls.html">Custom
Controls</a>.\n\n
\par Description:
The spinner control is used (usually in conjunction with the custom edit
control) to provide input of values limited to a fixed type. For example, the
control may be limited to the input of only positive integers. The input
options are integer, float, universe (world space coordinates), positive
integer, positive float, positive universal, and time. This control allows the
user to increment or decrement a value by clicking on the up or down arrows.
The user may also click and drag on the arrows to interactively adjust the
value. The Ctrl key may be held to accelerate the value changing speed, while
the Alt key may be held to decrease the value changing speed.\n\n
The standard size used by 3ds Max for the spinner control is 7 wide by 10 high.
If you use a larger size, the spinner control arrows will be position in the
upper left corner of the control.\n\n
<b>Important Note: The spinner control ensures that it only displays, and the
user is only allowed to input, values within the specified ranges. However the
spinner is just a front end to a controller which actually controls the value.
The user can thus circumvent the spinner constraints by editing the controller
directly (via function curves in track view, key info, etc.). Therefore, when a
plug-in gets a value from a controller (or a parameter block, which may use a
controller) it is its responsibility to clamp the value to a valid
range.</b>\n
\n \image html "spinner.gif" "Spinner Control"
\n \image html "spinedit.gif" "Spinner and Edit Control"
To initialize the pointer to the control call:\n\n
<b>ISpinnerControl *GetISpinner(HWND hCtrl);</b>\n\n
To release the control call:\n\n
<b>ReleaseISpinner(ISpinnerControl *isc);</b>\n\n
The value to use in the Class field of the Custom Control Properties dialog is:
<b>SpinnerControl</b>\n\n
The following messages may be sent by the spinner control:\n\n
This message is sent when the value of a spinner changes.\n\n
<b>CC_SPINNER_CHANGE</b>\n\n
<b>lParam</b> contains a pointer to the spinner control. You can cast this
pointer to a <b>ISpinnerControl</b> type and then call methods of the
control.\n\n
<b>LOWORD(wParam)</b> contains the ID of the spinner. This is the named
established in the ID field of the Custom Control Properties dialog.\n\n
<b>HIWORD(wParam)</b> is TRUE if the user is dragging the spinner
interactively.\n\n
This message is sent when the user presses down on the spinner buttons.\n\n
<b>CC_SPINNER_BUTTONDOWN</b>\n\n
<b>lParam</b> contains a pointer to the spinner control. You can cast this
pointer to a <b>ISpinnerControl</b> type and then call methods of the
control.\n\n
<b>LOWORD(wParam)</b> contains the ID of the spinner. This is the named
established in the ID field of the Custom Control Properties dialog.\n\n
This message is sent when the user releases a spinner button.\n\n
<b>CC_SPINNER_BUTTONUP</b>\n\n
<b>lParam</b> contains a pointer to the spinner control. You can cast this
pointer to a ISpinnerControl type and then call methods of the control.\n\n
<b>LOWORD(wParam)</b> contains the ID of the spinner. This is the named
established in the ID field of the Custom Control Properties dialog.\n\n
<b>HIWORD(wParam)</b> is FALSE if the user canceled and TRUE otherwise.\n\n
For example, if the user is interactively dragging the spinner, then does a
right click to cancel, the following messages are sent:\n\n
<b>1</b> A <b>CC_SPINNER_BUTTONDOWN</b> message indicating the user has pressed
the spinner button.\n\n
<b>2.</b> A series of <b>CC_SPINNER_CHANGE</b> where <b>HIWORD(wParam) =
TRUE</b>. This indicates that the spinner is being dragged interactively.\n\n
<b>3.</b> A <b>CC_SPINNER_CHANGE</b> where <b>HIWORD(wParam) = FALSE</b>.\n\n
<b>4.</b> A <b>CC_SPINNER_BUTTONUP</b> message where <b>HIWORD(wParam) =
FALSE</b>. This indicates the user has cancelled. */
class ISpinnerControl : public ICustomControl {
public:
/*! \remarks Returns the floating point value of the control. */
virtual float GetFVal()=0;
/*! \remarks This method returns the integer value of the control. */
virtual int GetIVal()=0;
/*! \remarks This method sets the scale for the spinner based on the
current value of the spinner. This allows the spinner to cover a larger
range of values with less mouse motion. If you wish to use auto scale,
pass TRUE to this method.
\param on If you wish to use auto scale pass TRUE to this method; otherwise FALSE. */
virtual void SetAutoScale(BOOL on=TRUE)=0;
/*! \remarks This method sets the value which is added to or
subtracted from the current control value as the arrow buttons are
pressed, or the user interactively drags the spinner.
\param s The value is added to or subtracted from the current control value. */
virtual void SetScale( float s )=0;
/*! \remarks This method sets the value of the control to the specific
floating point number passed. You may pass FALSE as the notify
parameter so the control wont send a message when you set the value.
\param v The new value for the control.
\param notify If TRUE a message is sent indicating the control has changed.\n\n
Note that sometimes the <b>SetValue()</b> method is used to update the
display of parameters in the user interface. For example, if the user
changes the current time and the UI parameters are animated, the user
interface controls must be updated to reflect the value at the new
time. The programmer calls <b>SetValue()</b> to update the value
displayed in the control. This is an example of when to pass FALSE as
the notify parameter. If you were to pass TRUE, a message would be sent
as if the user had actually enter a new value at this time. These are
of course very different conditions. */
virtual void SetValue( float v, int notify )=0;
/*! \remarks This method sets the value to the specific integer
passed. You may pass FALSE as the notify parameter so the control won't
send a message when you set the value.
\param v The new value for the control.
\param notify If TRUE a message is sent indicating the control has changed. */
virtual void SetValue( int v, int notify )=0;
/*! \remarks This method establishes the allowable limits for integer
values entered.
\param min The minimum allowable value.
\param max The maximum allowable value.
\param limitCurValue You may pass FALSE to the this parameter so the control will not send a
spinner changed message when the limits are set. */
virtual void SetLimits( int min, int max, int limitCurValue = TRUE )=0;
/*! \remarks This method establishes the allowable limits for floating
point values entered.
\param min The minimum allowable value.
\param max The maximum allowable value.
\param limitCurValue You may pass FALSE to the this parameter so the control will not send a
spinner changed message when the limits are set. */
virtual void SetLimits( float min, float max, int limitCurValue = TRUE )=0;
/*! \remarks When an edit control is used in conjunction with the
spinner control, this method is used to link the two, so values entered
using the spinner are displayed in the edit control. This method is
also used to set the type of value which may be entered.
\param hEdit The handle of the edit control to link.
\param type The type of value that may be entered. One of the following values:\n\n
<b>EDITTYPE_INT</b>\n
Any integer value.\n\n
<b>EDITTYPE_FLOAT</b>\n
Any floating point value.\n\n
<b>EDITTYPE_UNIVERSE</b>\n
This is a value in world space units. It respects the system's unit
settings (for example feet and inches).\n\n
<b>EDITTYPE_POS_INT</b>\n
Any integer \>= 0\n\n
<b>EDITTYPE_POS_FLOAT</b>\n\
Any floating point value \>= 0.0\n\n
<b>EDITTYPE_POS_UNIVERSE</b>\n
This is a positive value in world space units. It respects the system's
unit settings (for example feet and inches).\n\n
<b>EDITTYPE_TIME</b>\n
This is a time value. It respects the system time settings (SMPTE for
example). */
virtual void LinkToEdit( HWND hEdit, EditSpinnerType type )=0;
/*! \remarks This method is used to show commonality. When several
different values are being reflected by the spinner, the value is
indeterminate. When TRUE, the value field of the spinner appears empty.
\param i Pass TRUE to this method to set the value to indeterminate. */
virtual void SetIndeterminate(BOOL i=TRUE)=0;
/*! \remarks This method returns TRUE if the current state of the
spinner is indeterminate. See <b>SetIndeterminate()</b> above. */
virtual BOOL IsIndeterminate()=0;
/*! \remarks A 3ds Max user may right click on the spinner buttons to
reset them to their 'reset' value (after they have been changed). This
method specifies the value used when the reset occurs.
\param v The reset value. */
virtual void SetResetValue(float v)=0;
/*! \remarks A 3ds Max user may right click on the spinner buttons to
reset them to their 'reset' value (after they have been changed). This
method specifies the value used when the reset occurs.
\param v The reset value. */
virtual void SetResetValue(int v)=0;
/*! \remarks Sets the display of the brackets surrounding the spinner control to on.
This is used to indicate if a key exists for the parameter controlled
by the spinner at the current time. These brackets turned on and off
automatically if you are using a parameter map and parameter block to
handle the control. If not you'll need to use this method.
\param onOff TRUE for on; FALSE for off.
\par Sample Code:
This example shows how you do this if you only use a parameter
block.\n\n
\code
case CC_SPINNER_CHANGE:
switch (LOWORD(wParam))
{
case IDC_LENSPINNER:
th->SetLength(th->ip->GetTime(),th->lengthSpin->GetFVal());
th->lengthSpin->SetKeyBrackets(th->pblock->
KeyFrameAtTime(PB_LENGTH,th->ip->GetTime()));
break;
}
return TRUE;
\endcode
The following functions are not part of class <b>ISpinnerControl</b>
but are available for use with spinner controls. */
virtual void SetKeyBrackets(BOOL onOff)=0;
};
CoreExport ISpinnerControl *GetISpinner( HWND hCtrl );
CoreExport void ReleaseISpinner( ISpinnerControl *isc );
/*! \remarks This activates or de-activates the global spinner snap toggle.
\par Parameters:
<b>BOOL b</b>\n\n
TRUE to activate; FALSE to de-activate. */
CoreExport void SetSnapSpinner(BOOL b);
/*! \remarks Returns the global spinner snap setting; TRUE if on; FALSE if
off. */
CoreExport BOOL GetSnapSpinner();
/*! \remarks This sets the global spinner snap increment or decrement value.
\par Parameters:
<b>float f</b>\n\n
The value that is added to or subtracted from the current spinner value when
the arrow buttons are pressed. */
CoreExport void SetSnapSpinValue(float f);
/*! \remarks Returns the global spinner snap increment or decrement value. */
CoreExport float GetSnapSpinValue();
/*! \remarks Sets the precision (number of decimal places displayed) used by
the spinner control. Note that this function also affects slider controls. See
Class ISliderControl.
\par Parameters:
<b>int p</b>\n\n
The number of decimal places to display in the edit box linked to the spinner
control. */
CoreExport void SetSpinnerPrecision(int p);
/*! \remarks Returns the number of decimal places displayed in the edit box
linked to a spinner control. Note that this function also affects slider
controls. See Class ISliderControl.\n\n
Spinner controls have a global snap setting. This is set in 3ds Max using
File/Preferences... in the General page by changing the Spinner Snap setting.
When enabled this specifies an increment that is applied to the current spinner
value each time the UP or DOWN buttons are pressed on the spinner control. */
CoreExport int GetSpinnerPrecision();
CoreExport void SetSpinnerWrap(int w);
CoreExport int GetSpinnerWrap();
// begin - mjm 12.18.98
//---------------------------------------------------------------------------
// Slider control
#define SLIDERWINDOWCLASS _M("SliderControl")
// LOWORD(wParam) = ctrlID,
// HIWORD(wParam) = TRUE if user is dragging the slider interactively.
// lParam = pointer to ISliderControl
#define CC_SLIDER_CHANGE WM_USER + 611
// LOWORD(wParam) = ctrlID,
// lParam = pointer to ISliderControl
#define CC_SLIDER_BUTTONDOWN WM_USER + 612
// LOWORD(wParam) = ctrlID,
// HIWORD(wParam) = FALSE if user cancelled - TRUE otherwise
// lParam = pointer to ISliderControl
#define CC_SLIDER_BUTTONUP WM_USER + 613
/*! \sa Class ICustomControl,
Class ISpinnerControl.\n\n
\par Description:
<b>Important Note: The slider control ensures that it only displays, and the
user is only allowed to input, values within the specified ranges. However the
slider is just a front end to a controller which actually controls the value.
The user can thus circumvent the slider constraints by editing the controller
directly (via function curves in track view, key info, etc.). Therefore, when a
plug-in gets a value from a controller (or a parameter block, which may use a
controller) it is its responsibility to clamp the value to a valid
range.</b>\n
\n \image html "slider1.gif" "Slider Control"
\n \image html "slider2.gif" "'Bracketed' Slider Control"
The custom slider control is functionality similar to the custom spinner
control. It supports the following features:\n\n
- can link to custom edit box. \n\n
- right click reset of value. \n\n
if not dragging, resets to default reset value. \n\n
if dragging, resets to previous value. \n\n
- shift+right click sets an animation key. \n\n
- red highlight for animated key positions. \n\n
It also supports the following functionality:\n\n
- dynamically set tick marks segment the slider track. \n\n
- default reset value and last value are visually indicated. \n\n
- left click in slider track moves button to that position. \n\n
- ctrl key snaps to nearest tick mark. \n
Also Note: Developers should use the functions <b>Get/SetSpinnerPrecision()</b>
for controlling precision of edit boxes linked to slider controls. Those
functions affect both spinners and sliders.\n\n
To initialize the pointer to the control call: \n
<code>ISliderControl *GetISlider(HWND hCtrl);</code> \n
To release the control call: \n
<code>void ReleaseISlider(ISliderControl *isc);</code> \n
The value to use in the Class field of the Custom Control Properties dialog is: SliderControl \n\n
The following messages may be sent by the slider control: \n
This message is sent when the value of a slider changes. \n
<b>CC_SLIDER_CHANGE</b> \n
lParam contains a pointer to the slider control. You can cast this pointer
to a ISliderControl type and then call methods of the control. \n
LOWORD(wParam) contains the ID of the slider. This is the ID established in
the ID field of the Custom Control Properties dialog. \n
HIWORD(wParam) is TRUE if the user is dragging the slider interactively. \n
This message is sent when the user presses down on the slider. \n
<b>CC_SLIDER_BUTTONDOWN</b> \n
lParam contains a pointer to the slider control. You can cast this pointer
to a ISliderControl type and then call methods of the control. \n
LOWORD(wParam) contains the ID of the slider. This is the ID established
in the ID field of the Custom Control Properties dialog. \n
This message is sent when the user releases a slider. \n
<b>CC_SLIDER_BUTTONUP</b> \n
lParam contains a pointer to the slider control. You can cast this pointer
to a ISliderControl type and then call methods of the control. \n
LOWORD(wParam) contains the ID of the slider. This is the ID established
in the ID field of the Custom Control Properties dialog. \n
HIWORD(wParam) is FALSE if the user canceled and TRUE otherwise.
*/
class ISliderControl : public ICustomControl
{
public:
/*! \remarks Returns the floating point value of the control. */
virtual float GetFVal()=0;
/*! \remarks Returns the integer value of the control. */
virtual int GetIVal()=0;
/*! \remarks Sets the number of segments (tick marks) used by the control.
\par Parameters:
<b>int num</b>\n\n
The number to set. */
virtual void SetNumSegs( int num )=0;
/*! \remarks This method sets the value of the control to the specific
floating point number passed. You may pass FALSE as the notify parameter so
the control wont send a message when you set the value.
\par Parameters:
<b>float v</b>\n\n
The new value for the control.\n\n
<b>int notify</b>\n\n
If TRUE a message is sent indicating the control has changed; if FALSE no
message is sent. */
virtual void SetValue( float v, int notify )=0;
/*! \remarks This method sets the value of the control to the specific
integer number passed. You may pass FALSE as the notify parameter so the
control wont send a message when you set the value.
\par Parameters:
<b>int v</b>\n\n
The new value for the control.\n\n
<b>int notify</b>\n\n
If TRUE a message is sent indicating the control has changed; if FALSE no
message is sent. */
virtual void SetValue( int v, int notify )=0;
/*! \remarks This method establishes the allowable limits for integer
values entered.
\par Parameters:
<b>int min</b>\n\n
The minimum allowable value.\n\n
<b>int max</b>\n\n
The maximum allowable value.\n\n
<b>int limitCurValue = TRUE</b>\n\n
You may pass FALSE to the this parameter so the control will not send a
spinner changed message when the limits are set. */
virtual void SetLimits( int min, int max, int limitCurValue = TRUE )=0;
/*! \remarks This method establishes the allowable limits for floating
point values entered.
\par Parameters:
<b>float min</b>\n\n
The minimum allowable value.\n\n
<b>float max</b>\n\n
The maximum allowable value.\n\n
<b>int limitCurValue = TRUE</b>\n\n
You may pass FALSE to the this parameter so the control will not send a
spinner changed message when the limits are set. */
virtual void SetLimits( float min, float max, int limitCurValue = TRUE )=0;
/*! \remarks When an edit control is used in conjunction with the slider
control, this method is used to link the two, so values entered using the
slider are displayed in the edit control. This method is also used to set
the type of value which may be entered.
\par Parameters:
<b>HWND hEdit</b>\n\n
The handle of the edit control to link.\n\n
<b>EditSpinnerType type</b>\n\n
The type of value that may be entered. One of the following values:\n\n
<b>EDITTYPE_INT</b>\n\n
Any integer value.\n\n
<b>EDITTYPE_FLOAT</b>\n\n
Any floating point value.\n\n
<b>EDITTYPE_UNIVERSE</b>\n\n
This is a value in world space units. It respects the system's unit
settings (for example feet and inches).\n\n
<b>EDITTYPE_POS_INT</b>\n\n
Any integer \>= 0\n\n
<b>EDITTYPE_POS_FLOAT</b>\n\n
Any floating point value \>= 0.0\n\n
<b>EDITTYPE_POS_UNIVERSE</b>\n\n
This is a positive value in world space units. It respects the system's
unit settings (for example feet and inches) .\n\n
<b>EDITTYPE_TIME</b>\n\n
This is a time value. It respects the system time settings (SMPTE for
example). */
virtual void LinkToEdit( HWND hEdit, EditSpinnerType type )=0;
/*! \remarks This method is used to show commonality. When several
different values are being reflected by the slider, the value is
indeterminate. When TRUE, the value field of the slider appears empty.
\par Parameters:
<b>BOOL i=TRUE</b>\n\n
Pass TRUE to this method to set the value to indeterminate. */
virtual void SetIndeterminate(BOOL i=TRUE)=0;
/*! \remarks This method returns TRUE if the current state of the slider
is indeterminate; otherwise FALSE. See <b>SetIndeterminate()</b> above. */
virtual BOOL IsIndeterminate()=0;
/*! \remarks A user may right click on a slider to reset it to its 'reset'
value (after it has been changed). This method specifies the value used
when the reset occurs.
\par Parameters:
<b>float v</b>\n\n
The reset value. */
virtual void SetResetValue(float v)=0;
/*! \remarks A user may right click on a slider to reset it to its 'reset'
value (after it has been changed). This method specifies the value used
when the reset occurs.
\par Parameters:
<b>int v</b>\n\n
The reset value. */
virtual void SetResetValue(int v)=0;
/*! \remarks Sets the display of the 'brackets' surrounding the slider
control. This is used to indicate if a key exists for the parameter
controlled by the slider at the current time. These brackets turned on and
off automatically if you are using a parameter map and parameter block to
handle the control. If not you'll need to use this method. For a slider,
the 'brackets' appear as a colored dot in the position marker.
\par Parameters:
<b>BOOL onOff</b>\n\n
TRUE for on; FALSE for off. */
virtual void SetKeyBrackets(BOOL onOff)=0;
};
/*! */
CoreExport ISliderControl *GetISlider( HWND hCtrl );
/*! The following messages may be sent by the slider control:\n\n
This message is sent when the value of a slider changes.\n\n
<b>CC_SLIDER_CHANGE</b>\n\n
<b>lParam</b> contains a pointer to the slider control. You can cast this
pointer to a <b>ISliderControl</b> type and then call methods of the
control.\n\n
<b>LOWORD(wParam)</b> contains the ID of the slider. This is the ID established
in the ID field of the Custom Control Properties dialog.\n\n
<b>HIWORD(wParam)</b> is TRUE if the user is dragging the slider
interactively.\n\n
This message is sent when the user presses down on the slider.\n\n
<b>CC_SLIDER_BUTTONDOWN</b>\n\n
<b>lParam</b> contains a pointer to the slider control. You can cast this
pointer to a <b>ISliderControl</b> type and then call methods of the
control.\n\n
<b>LOWORD(wParam)</b> contains the ID of the slider. This is the ID established
in the ID field of the Custom Control Properties dialog.\n\n
This message is sent when the user releases a slider.\n\n
<b>CC_SLIDER_BUTTONUP</b>\n\n
<b>lParam</b> contains a pointer to the slider control. You can cast this
pointer to a <b>ISliderControl</b> type and then call methods of the
control.\n\n
<b>LOWORD(wParam)</b> contains the ID of the slider. This is the ID established
in the ID field of the Custom Control Properties dialog.\n\n
<b>HIWORD(wParam)</b> is FALSE if the user canceled and TRUE otherwise. */
CoreExport void ReleaseISlider( ISliderControl *isc );
// mjm - 3.1.99 - use spinner precision for edit boxes linked to slider controls
/*
CoreExport void SetSliderPrecision(int p);
CoreExport int GetSliderPrecision();
*/
// routines for setting up sliders.
/*! \remarks This global function is used for setting up integer sliders. It
performs the equivalent of the <b>GetISlider()</b>, <b>SetLimits()</b>,
<b>SetValue()</b>, and <b>LinkToEdit()</b>.
\par Parameters:
<b>HWND hwnd</b>\n\n
The handle of the dialog box in which the slider appears.\n\n
<b>int idSlider</b>\n\n
The ID of the slider.\n\n
<b>int idEdit</b>\n\n
The ID of the edit control.\n\n
<b>int min</b>\n\n
The minimum allowable value.\n\n
<b>int max</b>\n\n
The maximum allowable value.\n\n
<b>int val</b>\n\n
The initial value for the spinner.\n\n
<b>int numSegs</b>\n\n
The number of segments to use for the control.
\return A pointer to the slider control. */
CoreExport ISliderControl *SetupIntSlider(HWND hwnd, int idSlider, int idEdit, int min, int max, int val, int numSegs);
/*! \remarks This global function is used for setting up floating point
sliders. It performs the equivalent of the <b>GetISlider()</b>,
<b>SetLimits()</b>, <b>SetValue()</b>, and <b>LinkToEdit()</b>.
\par Parameters:
<b>HWND hwnd</b>\n\n
The handle of the dialog box in which the slider appears.\n\n
<b>int idSlider</b>\n\n
The ID of the slider.\n\n
<b>int idEdit</b>\n\n
The ID of the edit control.\n\n
<b>float min</b>\n\n
The minimum allowable value.\n\n
<b>float max</b>\n\n
The maximum allowable value.\n\n
<b>float val</b>\n\n
The initial value for the spinner.\n\n
<b>int numSegs</b>\n\n
The number of segments to use for the control.
\return A pointer to the slider control. */
CoreExport ISliderControl *SetupFloatSlider(HWND hwnd, int idSlider, int idEdit, float min, float max, float val, int numSegs);
/*! \remarks This global function is used for setting up 'universal' value
sliders (<b>EDITTYPE_UNIVERSE</b> -- these display world space units). It
performs the equivalent of the <b>GetISlider()</b>, <b>SetLimits()</b>,
<b>SetValue()</b>, and <b>LinkToEdit()</b>.
\par Parameters:
<b>HWND hwnd</b>\n\n
The handle of the dialog box in which the slider appears.\n\n
<b>int idSlider</b>\n\n
The ID of the slider.\n\n
<b>int idEdit</b>\n\n
The ID of the edit control.\n\n
<b>float min</b>\n\n
The minimum allowable value.\n\n
<b>float max</b>\n\n
The maximum allowable value.\n\n
<b>float val</b>\n\n
The initial value for the spinner.\n\n
<b>int numSegs</b>\n\n
The number of segments to use for the control.
\return A pointer to the slider control. */
CoreExport ISliderControl *SetupUniverseSlider(HWND hwnd, int idSlider, int idEdit, float min, float max, float val, int numSegs);
// controls whether or not sliders send notifications while the user adjusts them with the mouse
/*! \remarks This function controls whether or not sliders send
<b>CC_SLIDER_CHANGE</b> notifications while the user adjusts them with the
mouse.
\par Parameters:
<b>BOOL onOff</b>\n\n
TRUE to turn on; FALSE to turn off. */
CoreExport void SetSliderDragNotify(BOOL onOff);
/*! \remarks Returns TRUE if <b>CC_SLIDER_CHANGE</b> notifications are sent by
sliders while the user adjusts them with the mouse; FALSE if they are not sent.
*/
CoreExport BOOL GetSliderDragNotify();
// end - mjm 12.18.98
//---------------------------------------------------------------------------//
// Rollup window control
#define WM_CUSTROLLUP_RECALCLAYOUT WM_USER+876
#define ROLLUPWINDOWCLASS _M("RollupWindow")
typedef void *RollupState;
// Flags passed to AppendRollup
#define APPENDROLL_CLOSED (1<<0) // Starts the page out rolled up.
#define DONTAUTOCLOSE (1<<1) // Don't close this rollup when doing Close All
#define ROLLUP_SAVECAT (1<<2) // Save the category field in the RollupOrder.cfg
#define ROLLUP_USEREPLACEDCAT (1<<3) // In case of ReplaceRollup, use the replaced rollups category
class IRollupWindow;
class IRollupPanel;
/*! class IRollupCallback : public InterfaceServer
\par Description:
This class represents the abstract interface for a rollup window callback
object to assist developers in handling custom drag and drop of rollouts. <br>
*/
class IRollupCallback : public InterfaceServer
{
public:
/*! \remarks Any plugin (or core component), that wants to implement a
custom behavior when a rollup page is drag and dropped onto another
rollout, it can do so, by registering a <b>IRollupCallback</b> and
overwriting this method and <b>GetEditObjClassID().</b> After rearranging
rollup pages the HandleDrop code should call:
<b>GetIRollupSettings()-\>GetCatReg()-\>Save()</b>; in order to save the
rollout order.
\par Parameters:
<b>IRollupPanel *src</b>\n\n
A pointer to the source rollup panel.\n\n
<b>IRollupPanel *targ</b>\n\n
A pointer to the target rollup panel.\n\n
<b>bool before</b>\n\n
TRUE to insert before the panel it was dropped on; FALSE to insert after.
\return TRUE to indicate to the system, that it took over the drop
handling, otherwise FALSE.
\par Default Implementation:
<b>{ return FALSE; }</b> */
virtual BOOL HandleDrop(IRollupPanel *src,IRollupPanel *targ, bool before){ return FALSE; }
/*! \remarks This method has to be implemented in order to support drag
and drop for rollouts, no matter if custom drop handling is used, or not.
The order of rollup panels is stored in the RollupOrder.cfg file in the UI
directory. The order is stored under a SuperClassID and ClassID. The
RollupCallback has to specify what the superclassid and classid is. E.g.
for the Modify Panel it is the classid for the currently edited object. For
the DisplayPanel it is only one classid, that has no real class assigned to
it, since the rollouts are independent from the object being edited
(DISPLAY_PANEL_ROLLUPCFG_CLASSID).
\par Parameters:
<b>SClass_ID \&sid</b>\n\n
The super class ID of the object.\n\n
<b>Class_ID \&cid</b>\n\n
The class ID of the object.
\return TRUE if drag and drop is supported, otherwise FALSE.
\par Default Implementation:
<b>{ return FALSE;}</b> */
virtual BOOL GetEditObjClassID(SClass_ID &sid,Class_ID &cid){ return FALSE;}
/*! \remarks This method is called when the user selected the "open all"
function and it currently used internally. The method will return TRUE if
successful and FALSE otherwise.
\par Default Implementation:
<b>{return FALSE;}</b> */
virtual BOOL HandleOpenAll(){return FALSE;}
/*! \remarks This method is called when the user selected the "close all"
function and it currently used internally. The method will return TRUE if
successful and FALSE otherwise.
\par Default Implementation:
<b>{ return FALSE;}</b> */
virtual BOOL HandleCloseAll(){ return FALSE;}
};
/*! class IRollupPanel : public InterfaceServer
\par Description:
This class represents the interface for a rollup panel and describes the
properties of that panel (which is one rollup). You can obtain a pointer to the
IRollupPanel class for any given specified window by calling
<b>IRollupWindow::IRollupPanel *GetPanel(HWND hWnd)</b>; */
class IRollupPanel : public InterfaceServer
{
public:
/*! \remarks This method returns a handle to the rollup panel instance. */
virtual HINSTANCE GetHInst()=0;
/*! \remarks This method returns the resource ID of the rollup panel. */
virtual DWORD_PTR GetResID()=0;
/*! \remarks Equality test operator. */
virtual BOOL operator==(const IRollupPanel& id)=0;
/*! \remarks This method returns the rollup panel category identifier. */
virtual int GetCategory()=0;
/*! \remarks This method allows you to set the category identifier for the
rollup panel.
\par Parameters:
<b>int cat</b>\n\n
The category identifier to set. */
virtual void SetCategory(int cat)=0;
/*! \remarks This method returns a handle to the rollup window. */
virtual HWND GetHWnd()=0;
/*! \remarks This method returns a handle to the actual panel in the
rollup window. */
virtual HWND GetRollupWindowHWND()=0;
/*! \remarks This method returns a handle to the window from which you can
get the title through the <b>GWLP_USERDATA</b>. */
virtual HWND GetTitleWnd()=0;
//! This function gets the main panel window handle.
//! \return Returns the panel window handle
virtual HWND GetPanelWnd()=0;
//! This functions sets the height of this panel.
//! \param[in] height The height of the panel dlg.
virtual void SetDlgHeight(int height)=0;
//! This function gets the height of the panel.
//! \return Returns the panel height.
virtual int GetDlgHeight()=0;
};
/*! class IRollupRCMenuItem : public InterfaceServer
\par Description:
This class represents a right click menu item for rollups. */
class IRollupRCMenuItem : public InterfaceServer {
public:
/*! \remarks This method returns the text of the menu item. */
virtual MCHAR* RRCMMenuText()=0;
/*! \remarks This method is the callback that will be triggered when the
user selects the menu item. */
virtual void RRCMExecute()=0;
/*! \remarks This method allows you to control the checkmark for the menu
item, in case it needs be shown or hidden (by returning TRUE to show or
FALSE to hide). */
virtual bool RRCMShowChecked()=0;
/*! \remarks This method should return TRUE if you wish a separator item
before the menu item. */
virtual bool RRCMHasSeparator()=0;
};
/*! \sa Class ICustomControl,
Class IRollupPanel,
<a href="ms-its:3dsmaxsdk.chm::/ui_custom_controls.html">Custom Controls</a>,
Class Interface.\n\n
\par Description:
This control is used to access existing rollup pages or if you are creating a
dialog box which will not be used in the command panel. This control may be
used to add a container area for rollup pages to be added to the dialog, and
provides a scroll bar just like the command panel itself.\n\n
Note that this is a special case. Normally, adding rollup pages to the command
panel is done using the simple <b>AddRollupPage()</b> method of the Interface
class. This control is only used when you want to have a scrolling region for
rollup pages in a dialog box.\n\n
To initialize the pointer to the control call:\n\n
<b>IRollupWindow *GetIRollup(HWND hCtrl);</b>\n\n
To release the control call:\n\n
<b>void ReleaseIRollup(IRollupWindow *irw);</b>\n\n
The value to use in the Class field of the Custom Control Properties dialog is:
<b>RollupWindow</b> */
class IRollupWindow : public ICustomControl {
public:
// Shows or hides all
/*! \remarks This causes all the rollup windows to be visible. */
virtual void Show()=0;
/*! \remarks This causes all the rollup windows to become invisible.
*/
virtual void Hide()=0;
// Shows or hides by index
/*! \remarks This will make the rollup window whose index is passed
visible.
\par Parameters:
<b>int index</b>\n\n
The index of the rollup to show. */
virtual void Show(int index)=0;
/*! \remarks This will make the rollup window whose index is passed
invisible.
\par Parameters:
<b>int index</b>\n\n
The index of the rollup to hide. */
virtual void Hide(int index)=0;
/*! \remarks Returns the handle of the rollup page whose index is
passed.
\par Parameters:
<b>int index</b>\n\n
The index of the rollup whose handle is to be returned. */
virtual HWND GetPanelDlg(int index)=0;
/*! \remarks Returns an index to the rollup page given its handle.
\par Parameters:
<b>HWND hWnd</b>\n\n
The handle of the rollup. */
virtual int GetPanelIndex(HWND hWnd)=0;
/*! \remarks This method sets the title text displayed in the rollup
page whose index is passed.
\par Parameters:
<b>int index</b>\n\n
Specifies the rollup whose title is to be set.\n\n
<b>MCHAR *title</b>\n\n
The title string. */
virtual void SetPanelTitle(int index,MCHAR *title)=0;
// returns index of new panel
/*! \remarks This method is used to add a rollup page.
\par Parameters:
<b>HINSTANCE hInst</b>\n\n
The DLL instance handle of the plug-in.\n\n
<b>MCHAR *dlgTemplate</b>\n\n
The dialog template for the rollup page.\n\n
<b>DLGPROC dlgProc</b>\n\n
The dialog proc to handle the message sent to the rollup page.\n\n
<b>MCHAR *title</b>\n\n
The title displayed in the title bar.\n\n
<b>LPARAM param=0</b>\n\n
Any specific data to pass along may be stored here.\n\n
<b>DWORD flags=0</b>\n\n
Append rollup page flags:\n\n
<b>APPENDROLL_CLOSED</b>\n\n
Starts the page in the rolled up state.\n\n
<b>int category = ROLLUP_CAT_STANDARD</b>\n\n
The category parameter provides flexibility with regard to where a
particular rollup should be displayed in the UI. RollupPanels with
lower category fields will be displayed before RollupPanels with higher
category fields. For RollupPanels with equal category value the one
that was added first will be displayed first. Although it is possible
to pass any int value as category there exist currently 5 different
category defines: <b>ROLLUP_CAT_SYSTEM</b>, <b>ROLLUP_CAT_STANDARD</b>,
and <b>ROLLUP_CAT_CUSTATTRIB</b>.\n\n
When using <b>ROLLUP_SAVECAT</b>, the rollup page will make the
provided category sticky, meaning it will not read the category from
the <b>RollupOrder.cfg</b> file, but rather save the category field
that was passed as argument in the <b>CatRegistry</b> and in the
<b>RollupOrder.cfg</b> file.\n\n
The method will take the category of the replaced rollup in case the
flags argument contains <b>ROLLUP_USEREPLACEDCAT</b>. This is mainly
done, so that this system works with param maps as well.
\return The index of the new page is returned. */
virtual int AppendRollup( HINSTANCE hInst, MCHAR *dlgTemplate,
DLGPROC dlgProc, MCHAR *title, LPARAM param=0,DWORD flags=0, int category = ROLLUP_CAT_STANDARD )=0;
/*! \remarks This method is used to add a rollup page, but is currently not used.
\par Parameters:
<b>HINSTANCE hInst</b>\n\n
The DLL instance handle of the plug-in.\n\n
<b>DLGTEMPLATE *dlgTemplate</b>\n\n
The dialog template for the rollup page.\n\n
<b>DLGPROC dlgProc</b>\n\n
The dialog proc to handle the message sent to the rollup page.\n\n
<b>MCHAR *title</b>\n\n
The title displayed in the title bar.\n\n
<b>LPARAM param=0</b>\n\n
Any specific data to pass along may be stored here.\n\n
<b>DWORD flags=0</b>\n\n
Append rollup page flags:\n\n
<b>APPENDROLL_CLOSED</b>\n\n
Starts the page in the rolled up state.\n\n
<b>int category = ROLLUP_CAT_STANDARD</b>\n\n
The category parameter provides flexibility with regard to where a
particular rollup should be displayed in the UI. RollupPanels with
lower category fields will be displayed before RollupPanels with higher
category fields. For RollupPanels with equal category value the one
that was added first will be displayed first. Although it is possible
to pass any int value as category there exist currently 5 different
category defines: <b>ROLLUP_CAT_SYSTEM</b>, <b>ROLLUP_CAT_STANDARD</b>,
and <b>ROLLUP_CAT_CUSTATTRIB</b>.\n\n
When using <b>ROLLUP_SAVECAT</b>, the rollup page will make the
provided category sticky, meaning it will not read the category from
the <b>RollupOrder.cfg</b> file, but rather save the category field
that was passed as argument in the <b>CatRegistry</b> and in the
<b>RollupOrder.cfg</b> file.\n\n
The method will take the category of the replaced rollup in case the
flags argument contains <b>ROLLUP_USEREPLACEDCAT</b>. This is mainly
done, so that this system works with param maps as well.
\return The index of the new page is returned. */
virtual int AppendRollup( HINSTANCE hInst, DLGTEMPLATE *dlgTemplate,
DLGPROC dlgProc, MCHAR *title, LPARAM param=0,DWORD flags=0, int category = ROLLUP_CAT_STANDARD )=0;
/*! \remarks This method is used to replace the rollup page whose index is
passed.
\par Parameters:
<b>int index</b>\n\n
Specifies the rollup whose to be replaced.\n\n
<b>HINSTANCE hInst</b>\n\n
The DLL instance handle of the plug-in.\n\n
<b>TCHAR *dlgTemplate</b>\n\n
The dialog template for the rollup page.\n\n
<b>DLGPROC dlgProc</b>\n\n
The dialog proc to handle the message sent to the rollup page.\n\n
<b>TCHAR *title</b>\n\n
The title displayed in the title bar.\n\n
<b>LPARAM param=0</b>\n\n
Any specific data to pass along may be stored here.\n\n
<b>DWORD flags=0</b>\n\n
Append rollup page flags:\n\n
<b>APPENDROLL_CLOSED</b>\n\n
Starts the page in the rolled up state.
\return The index of the replacement page is returned. */
virtual int ReplaceRollup( int index, HINSTANCE hInst, MCHAR *dlgTemplate,
DLGPROC dlgProc, MCHAR *title, LPARAM param=0,DWORD flags=0, int category = ROLLUP_CAT_STANDARD)=0;
/*! \remarks This method is used to replace the rollup page whose index is passed,
but is currently not used.
\par Parameters:
<b>int index</b>\n\n
Specifies the rollup whose to be replaced.\n\n
<b>HINSTANCE hInst</b>\n\n
The DLL instance handle of the plug-in.\n\n
<b>DLGTEMPLATE *dlgTemplate</b>\n\n
The dialog template for the rollup page.\n\n
<b>DLGPROC dlgProc</b>\n\n
The dialog proc to handle the message sent to the rollup page.\n\n
<b>MCHAR *title</b>\n\n
The title displayed in the title bar.\n\n
<b>LPARAM param=0</b>\n\n
Any specific data to pass along may be stored here.\n\n
<b>DWORD flags=0</b>\n\n
Append rollup page flags:\n\n
<b>APPENDROLL_CLOSED</b>\n\n
Starts the page in the rolled up state.\n\n
<b>int category = ROLLUP_CAT_STANDARD</b>\n\n
The category parameter provides flexibility with regard to where a
particular rollup should be displayed in the UI. RollupPanels with
lower category fields will be displayed before RollupPanels with higher
category fields. For RollupPanels with equal category value the one
that was added first will be displayed first. Although it is possible
to pass any int value as category there exist currently 5 different
category defines: <b>ROLLUP_CAT_SYSTEM</b>, <b>ROLLUP_CAT_STANDARD</b>,
and <b>ROLLUP_CAT_CUSTATTRIB</b>.\n\n
When using <b>ROLLUP_SAVECAT</b>, the rollup page will make the
provided category sticky, meaning it will not read the category from
the <b>RollupOrder.cfg</b> file, but rather save the category field
that was passed as argument in the <b>CatRegistry</b> and in the
<b>RollupOrder.cfg</b> file.\n\n
The method will take the category of the replaced rollup in case the
flags argument contains <b>ROLLUP_USEREPLACEDCAT</b>. This is mainly
done, so that this system works with param maps as well.
\return The index of the replacement page is returned. */
virtual int ReplaceRollup( int index, HINSTANCE hInst, DLGTEMPLATE *dlgTemplate,
DLGPROC dlgProc, MCHAR *title, LPARAM param=0,DWORD flags=0, int category = ROLLUP_CAT_STANDARD)=0;
/*! \remarks This method deletes the rollup pages starting at the
index passed. The count parameter controls how many pages are deleted.
\par Parameters:
<b>int index</b>\n\n
The starting index.\n\n
<b>int count</b>\n\n
The number of pages. */
virtual void DeleteRollup( int index, int count )=0;
/*! \remarks This method is used to change the height of a rollup
page.
\par Parameters:
<b>int index</b>\n\n
The index of the rollup to change.\n\n
<b>int height</b>\n\n
The new height of the dialog in pixels. */
virtual void SetPageDlgHeight(int index,int height)=0;
/*! \remarks This method saves the state of the rollup (the position
of the scroll bars, which pages are open, etc...).
\par Parameters:
<b>RollupState *hState</b>\n\n
Pointer to storage for the rollup state. Note: <b>typedef void
*RollupState;</b> */
virtual void SaveState( RollupState *hState )=0;
/*! \remarks This methods restores a saved state.
\par Parameters:
<b>RollupState *hState</b>\n\n
Pointer to storage for the rollup state. Note: <b>typedef void
*RollupState;</b> */
virtual void RestoreState( RollupState *hState )=0;
// Passing WM_LBUTTONDOWN, WM_MOUSEMOVE, and WM_LBUTTONUP to
// this function allows scrolling with unused areas in the dialog.
/*! \remarks Passing <b>WM_LBUTTONDOWN</b>, <b>WM_MOUSEMOVE</b>, and
<b>WM_LBUTTONUP</b> to this function allows hand cursor scrolling with
unused areas in the dialog.
\par Parameters:
<b>HWND hDlg</b>\n\n
The handle of the dialog.\n\n
<b>UINT message</b>\n\n
The message to pass along: <b>WM_LBUTTONDOWN</b>, <b>WM_MOUSEMOVE</b>,
or <b>WM_LBUTTONUP</b>.\n\n
<b>WPARAM wParam</b>\n\n
<b>LPARAM lParam</b>\n\n
These are passed as part of the message sent in. Pass them along to
this method. */
virtual void DlgMouseMessage( HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam )=0;
/*! \remarks This method returns the number of panels used in the
rollup. */
virtual int GetNumPanels()=0;
/*! \remarks This method return TRUE if the rollup page whose index is
passed is open and FALSE if it is closed. */
virtual BOOL IsPanelOpen(int index) = 0;
/*! \remarks This causes the page whose index is passed to either open
or close. If <b>isOpen</b> is passed a value of TRUE, the page is
opened.
\par Parameters:
<b>int index</b>\n\n
The page to open or close.\n\n
<b>BOOL isOpen</b>\n\n
If TRUE, the page is opened, if FALSE it is closed.\n\n
<b>BOOL ignoreFlags = TRUE</b>\n\n
The method would close the panel if the <b>DONTAUTOCLOSE</b> flag is
not set on the rollup. This flag indicates if it should be closed
anyway, even if the flag is set. */
virtual void SetPanelOpen(int index, BOOL isOpen, BOOL ignoreFlags = TRUE) =0;
/*! \remarks This method returns the scroll position of the window. */
virtual int GetScrollPos()=0;
/*! \remarks This method sets the scroll position of the window.
\par Parameters:
<b>int spos</b>\n\n
The scroll position to set. */
virtual void SetScrollPos(int spos)=0;
// This methods moves a RollupPanel to another RollupWindow. It either inserts it
// at the top, or appends it at the end (depending on the top parameter)
/*! \remarks This methods moves a RollupPanel to another RollupWindow. It either
inserts it at the top, or appends it at the end (depending on the top
parameter)
\par Parameters:
<b>IRollupWindow *from</b>\n\n
A pointer to the rollup window you are moving from.\n\n
<b>HWND hPanel</b>\n\n
The handle to the destination panel.\n\n
<b>BOOL top</b>\n\n
TRUE to insert at the top; FALSE to append at the end. */
virtual void MoveRollupPanelFrom(IRollupWindow *from, HWND hPanel, BOOL top)=0;
// Returns the Height of a RollupPanel
/*! \remarks Returns the height of the specified RollupPanel.
\par Parameters:
<b>int index</b>\n\n
The zero based index of the rollup panel.\n\n
*/
virtual int GetPanelHeight(int index)=0;
// Returns the Height of a RollupWindow, that it is longer than the visible area
/*! \remarks Returns the height of a RollupWindow, that it is longer than the
visible area */
virtual int GetScrollHeight()=0;
// Used internally
/*! \remarks This method is used internally */
virtual void UpdateLayout()=0;
/*! \remarks Returns a pointer to the rollup panel for the specified window handle.
An IRollupPanel describes the properties of a single rollup.
\par Parameters:
<b>HWND hWnd</b>\n\n
The window handle to get the rollup for. */
virtual IRollupPanel *GetPanel(HWND hWnd)=0;
/*! \remarks This method allows you to register a rollup callback function to handle
any custom handling for dragging and dropping rollouts.
\par Parameters:
<b>IRollupCallback *callb</b>\n\n
A pointer to the callback function you wish to register. */
virtual void RegisterRollupCallback( IRollupCallback *callb)=0;
/*! \remarks This method allows you to unregister a rollup callback function.
\par Parameters:
<b>IRollupCallback *callb</b>\n\n
A pointer to the callback function you wish to unregister. */
virtual void UnRegisterRollupCallback( IRollupCallback *callb)=0;
/*! \remarks This method allows you to register a rollup right-click menu item which
will be added to the list of items. For rollups that support Drag and
Drop this is used to register a ResetCategories RightClickMenu. Reset
Categories will get rid of all the changes that have been made through
drag and drop and restore the default.
\par Parameters:
<b>IRollupRCMenuItem *item</b>\n\n
A pointer to the right-click menu item you wish to register. */
virtual void RegisterRCMenuItem( IRollupRCMenuItem *item)=0;
/*! \remarks This method allows you to unregister a rollup right-click menu item.
\par Parameters:
<b>IRollupRCMenuItem *item</b>\n\n
A pointer to the right-click menu item you wish to unregister. */
virtual void UnRegisterRCMenuItem( IRollupRCMenuItem *item)=0;
/*! \remarks This method will reset the category information on all the panels in
the rollup window. The plugin will have to be reloaded (EndEditParams,
BeginEditparams) in order to show this in the UI.
\par Parameters:
<b>bool update = true</b>\n\n
TRUE to update the layout, otherwise FALSE. Leave this on TRUE. */
virtual void ResetCategories(bool update = true)=0;
};
// This function returns TRUE if a particular rollup panel is open given
// a handle to the dialog window in the panel.
/*! \remarks This function returns TRUE if a particular rollup panel is open
given a handle to the dialog window in the panel.
\par Parameters:
<b>HWND hDlg</b>\n\n
Handle to the dialog window in the panel. */
CoreExport BOOL IsRollupPanelOpen(HWND hDlg);
CoreExport IRollupWindow *GetIRollup( HWND hCtrl );
CoreExport void ReleaseIRollup( IRollupWindow *irw );
//----------------------------------------------------------------------------//
// CustEdit control
#define CUSTEDITWINDOWCLASS _M("CustEdit")
// Sent when the user hits the enter key in an edit control.
// wParam = cust edit ID
// lParam = HWND of cust edit control.
#define WM_CUSTEDIT_ENTER (WM_USER+685)
/*! \sa Class ICustomControl,
<a href="ms-its:3dsmaxsdk.chm::/ui_custom_controls.html">Custom
Controls</a>.\n\n
\par Description:
This control is a simple text input control. The user may type any string into
the field and the plug-in is notified when the user presses the ENTER key.
There are also methods to parse and return integer and floating point values
entered in the control.\n
\n \image html "cc1.gif"
To initialize the pointer to the control call: \n
<code>ICustEdit *GetICustEdit(HWND hCtrl);</code> \n\n
To release the control call: \n
<code>ReleaseICustEdit(ICustEdit *ice);</code> \n
The value to use in the Class field of the Custom Control Properties dialog is: CustEdit \n
The following messages may be sent by the edit control: \n
This message is sent when the control gets focus or when the user presses the
ENTER key while using the control. \n
<b>WM_CUSTEDIT_ENTER</b> \n
wParam contains the custom edit control resource ID. \n
lParam contains the HWND of custom edit control. \n
*/
class ICustEdit : public ICustomControl {
public:
/*! \remarks This retrieves the text entered into the control.
\param text Storage for the text to retrieve.
\param ct Specifies the maximum length of the string returned. */
virtual void GetText( MCHAR *text, int ct )=0;
/*! \remarks This method places the text into the control for editing.
\param text The text to place in the control. */
virtual void SetText( MCHAR *text )=0;
/*! \remarks This method allows you to pass in an integer value to the
control. The integer is converted to a string and displayed in the
control.
\param i This value is converted to a string and displayed in the control. */
virtual void SetText( int i )=0;
/*! \remarks This method allows you to pass in a floating point value
to the control. The float is converted to a string and displayed in the
control.
\param f This value is converted to a string and displayed in the control.
\param precision The precision argument is simply the number of decimal places that get
represented in the string that appears in the edit field. So if the
arguments were (1.0f/3.0f, 3) then the string "0.333" would appear in
the edit field. */
virtual void SetText( float f, int precision=3 )=0;
/*! \remarks This method parses and returns an integer value from the
control.
\param valid This pointer, if passed, is set to TRUE if the input is 'valid';
otherwise FALSE. FALSE indicates that something caused the parsing of
the input to terminate improperly. An example is a non-numeric
character. So for example, if the user entered "123jkfksdf" into the
field the valid pointer would be set to FALSE. */
virtual int GetInt(BOOL *valid=NULL)=0;
/*! \remarks This method parses and returns a floating point value
from the control.
\param valid This pointer, if passed, is set to TRUE if the input is 'valid';
otherwise FALSE. FALSE indicates that something caused the parsing of
the input to terminate improperly. An example is a non-numeric
character. So for example, if the user entered "123jkfksdf" into the
field this pointer would be set to FALSE. */
virtual float GetFloat(BOOL *valid=NULL)=0;
/*! \remarks A developer doesn't normally need to call this method.
This offsets the text vertically in the edit control.
\param lead This parameter specifies the number of pixels to offset. */
virtual void SetLeading(int lead)=0;
/*! \remarks This method allows custom handling of the RETURN key. If you pass TRUE
to this method an <b>EN_CHANGE</b> message will be sent to the control
when the RETURN key is pressed. The <b>EN_CHANGE</b> message is sent
when the user has taken any action that may have altered text in an
edit control so developer need to also call <b>GotReturn()</b>
(documented below) to see if it was indeed a RETURN key press.
\param yesNo If TRUE, then when the user presses the RETURN key in that control, the
edit field will send an <b>EN_CHANGE</b> message to the owner, and
calling <b>GotReturn()</b> will return TRUE.
\par Sample Code:
Below is the way this is handled by the Hit By Name dialog. In that
dialog, when the user enters a wild card pattern into the name match
field and presses RETURN, the dialog is exited with the items matching
the pattern selected. The way this is accomplished is by pass TRUE to
<b>WantReturn()</b> and then processing the <b>EN_CHANGE</b> message on
the control. If <b>GotReturn()</b> is TRUE the Win32 function
<b>PostMessage()</b> is used to send the <b>IDOK</b> message to exit
the dialog. If this wasn't done, pressing RETURN in the edit control
would only enter the text -- the user would have to move the mouse over
the OK button and press it.\n\n
\code
case IDC_HBN_PATTERN:
if (HIWORD(wParam)==EN_CHANGE)
{
iName = GetICustEdit(GetDlgItem(hDlg,IDC_HBN_PATTERN) );
iName->GetText(buf,256);
ct = _tcslen(buf);
if(ct && buf[ct-1] != _T('*'))
_tcscat(buf, _T("*"));
SendMessage(sbn->hList, LB_RESETCONTENT, 0, 0);
sbn->SetPattern(GetDlgItem(hDlg, IDC_HBN_PATTERN), buf);
sbn->BuildHitList(ct);
if(iName->GotReturn())
PostMessage(hDlg,WM_COMMAND,IDOK,0);
ReleaseICustEdit(iName);
}
break;
\endcode */
virtual void WantReturn(BOOL yesNo)=0;
/*! \remarks This method should be called on receipt of an <b>EN_CHANGE</b> message.
It return TRUE if pressing the RETURN key generated the message;
otherwise FALSE. */
virtual BOOL GotReturn()=0; // call this on receipt of EN_CHANGE
/*! \remarks Calling this method gives the control the focus to receive input. */
virtual void GiveFocus()=0;
/*! \remarks Returns TRUE if the control has the focus to receive input; otherwise
FALSE. */
virtual BOOL HasFocus()=0;
/*! \remarks Determines whether the TAB key may be used to jump to the next control
in the tab sequence.
\param yesNo TRUE to enable the TAB key to move to the next control; FALSE to
disable the TAB key from moving the focus. */
virtual void WantDlgNextCtl(BOOL yesNo)=0;
/*! \remarks Normally when a user exits an edit filed the notification
<b>WM_CUSTEDIT_ENTER</b> is sent. Many plug-ins key off this message to
finalize the input of values. For instance, if the user is entering a
value into an edit field and they hit the TAB key to leave the field
the value should be entered. Normally this is the desired behavior.
However, as a special case condition, if a developer does not want to
update the value, this method may be called so the
<b>WM_CUSTEDIT_ENTER</b> notification won't be sent when the edit
control loses focus.
\param onOff TRUE to turn on; FALSE to turn off. */
virtual void SetNotifyOnKillFocus(BOOL onOff)=0;
/*! \remarks Sets the text font in the edit control to display in a bold format or
normal.
\param onOff TRUE to turn bolding on; FALSE to turn off. */
virtual void SetBold(BOOL onOff)=0;
virtual void SetParamBlock(ReferenceTarget* pb, int subNum)=0;
};
/*! */
CoreExport ICustEdit *GetICustEdit( HWND hCtrl );
/*! The following messages may be sent by the edit control:\n\n
This message is sent when the control gets focus or when the user presses the
ENTER key while using the control.\n\n
<b>WM_CUSTEDIT_ENTER</b>\n\n
<b>wParam</b> contains the custom edit control resource ID.\n\n
<b>lParam</b> contains the <b>HWND</b> of custom edit control. */
CoreExport void ReleaseICustEdit( ICustEdit *ice );
#define CUSTSTATUSEDITWINDOWCLASS _M("CustStatusEdit")
/*! \sa Class ICustomControl.\n\n
\par Description:
This control mimics the edit control as well as a status control. It may be set
to 'read-only' so the user can read but cannot edit the displayed string.\n\n
The value to use in the Class field of the Custom Control Properties dialog is:
<b>CustStatusEdit</b> */
class ICustStatusEdit : public ICustomControl {
public:
/*! \remarks Retrieves the text entered into the control.
\par Parameters:
<b>MCHAR *text</b>\n\n
Storage for the text to retrieve.\n\n
<b>int ct</b>\n\n
Specifies the maximum length of the string returned. */
virtual void GetText( MCHAR *text, int ct )=0;
/*! \remarks This method places the text into the control for editing.
\par Parameters:
<b>MCHAR *text</b>\n\n
The text to place in the control. */
virtual void SetText( MCHAR *text )=0;
/*! \remarks This method allows you to pass in an integer value to the
control. The integer is converted to a string and displayed in the
control.
\par Parameters:
<b>int i</b>\n\n
This value is converted to a string and displayed in the control. */
virtual void SetText( int i )=0;
/*! \remarks This method allows you to pass in a floating point value
to the control. The float is converted to a string and displayed in the
control.
\par Parameters:
<b>float f</b>\n\n
This value is converted to a string and displayed in the control.\n\n
<b>int precision=3</b>\n\n
The precision argument is simply the number of decimal places that get
represented in the string that appears in the edit field. So if the
arguments were (1.0f/3.0f, 3) then the string "0.333" would appear in
the edit field. */
virtual void SetText( float f, int precision=3 )=0;
/*! \remarks This method parses and returns an integer value from the
control.
\par Parameters:
<b>BOOL *valid=NULL</b>\n\n
This pointer, if passed, is set to TRUE if the input is 'valid';
otherwise FALSE. FALSE indicates that something caused the parsing of
the input to terminate improperly. An example is a non-numeric
character. So for example, if the user entered "123jkfksdf" into the
field the valid pointer would be set to FALSE. */
virtual int GetInt(BOOL *valid=NULL)=0;
/*! \remarks This method parses and returns a floating point value
from the control.
\par Parameters:
<b>BOOL *valid=NULL</b>\n\n
This pointer, if passed, is set to TRUE if the input is 'valid';
otherwise FALSE. FALSE indicates that something caused the parsing of
the input to terminate improperly. An example is a non-numeric
character. So for example, if the user entered "123jkfksdf" into the
field this pointer would be set to FALSE. */
virtual float GetFloat(BOOL *valid=NULL)=0;
/*! \remarks A developer doesn't normally need to call this method.
This offsets the text vertically in the edit control.
\par Parameters:
<b>int lead</b>\n\n
This parameter specifies the number of pixels to offset. */
virtual void SetLeading(int lead)=0;
/*! \remarks This method allows custom handling of the RETURN key. If
you pass TRUE to this method an EN_CHANGE message will be sent to the
control when the RETURN key is pressed. The EN_CHANGE message is sent
when the user has taken any action that may have altered text in an
edit control so developer need to also call GotReturn() (documented
below) to see if it was indeed a RETURN key press.
\par Parameters:
<b>BOOL yesNo</b>\n\n
If TRUE, then when the user presses the RETURN key in that control, the
edit field will send an EN_CHANGE message to the owner, and calling
GotReturn() will return TRUE. */
virtual void WantReturn(BOOL yesNo)=0;
/*! \remarks This method should be called on receipt of an EN_CHANGE
message. It return TRUE if pressing the RETURN key generated the
message; otherwise FALSE. */
virtual BOOL GotReturn()=0; // call this on receipt of EN_CHANGE
/*! \remarks Calling this method gives the control the focus to
receive input. */
virtual void GiveFocus()=0;
/*! \remarks Returns TRUE if the control has the focus to receive
input; otherwise FALSE. */
virtual BOOL HasFocus()=0;
/*! \remarks Determines whether the TAB key may be used to jump to the
next control in the tab sequence.
\par Parameters:
<b>BOOL yesNo</b>\n\n
TRUE to enable the TAB key to move to the next control; FALSE to
disable the TAB key from moving the focus. */
virtual void WantDlgNextCtl(BOOL yesNo)=0;
/*! \remarks Normally when a user exits an edit filed the notification
WM_CUSTEDIT_ENTER is sent. Many plug-ins key off this message to
finalize the input of values. For instance, if the user is entering a
value into an edit field and they hit the TAB key to leave the field
the value should be entered. Normally this is the desired behavior.
However, as a special case condition, if a developer does not want to
update the value, this method may be called so the WM_CUSTEDIT_ENTER
notification won't be sent when the edit control loses focus.
\par Parameters:
<b>BOOL onOff</b>\n\n
TRUE to turn on; FALSE to turn off. */
virtual void SetNotifyOnKillFocus(BOOL onOff)=0;
/*! \remarks Sets the text font in the edit control to display in a
bold format or normal.
\par Parameters:
<b>BOOL onOff</b>\n\n
TRUE to turn bolding on; FALSE to turn off. */
virtual void SetBold(BOOL onOff)=0;
/*! \remarks Sets if the control is 'read-only'. That is, the string
is displayed but cannot be edited.
\par Parameters:
<b>BOOL onOff</b>\n\n
TRUE for read-only; FALSE to allow editing. */
virtual void SetReadOnly(BOOL onOff)=0;
};
/*! \remarks Used to initialize and return a pointer to the control.
\par Parameters:
<b>HWND hCtrl</b>\n\n
The window handle of the control. */
CoreExport ICustStatusEdit *GetICustStatusEdit( HWND hCtrl );
/*! \remarks Used to release the control when finished.
\par Parameters:
<b>ICustStatusEdit *ice</b>\n\n
Points to the control to release. */
CoreExport void ReleaseICustStatusEdit( ICustStatusEdit *ice );
//----------------------------------------------------------------------------//
// CustButton control
#define CUSTBUTTONWINDOWCLASS _M("CustButton")
#define CC_COMMAND WM_USER + 700
// send these with CC_COMMAND: wParam = CC_???
#define CC_CMD_SET_TYPE 23 // lParam = CBT_PUSH, CBT_CHECK
#define CC_CMD_SET_STATE 24 // lParam = 0/1 for popped/pushed
#define CC_CMD_HILITE_COLOR 25 // lParam = RGB packed int
#define RED_WASH RGB(255,192,192)
#define GREEN_WASH (ColorMan()->GetColor(kActiveCommand))
#define BLUE_WASH (ColorMan()->GetColor(kPressedHierarchyButton))
#define SUBOBJ_COLOR (ColorMan()->GetColor(kSubObjectColor))
enum CustButType { CBT_PUSH, CBT_CHECK };
// If the button is set to notify on button down, it will send a WM_COMMAND
// with this notify code when the user touches the button.
#define BN_BUTTONDOWN 8173
// It will also send this message when the mouse is released regardless
// if the mouse is released inside the tool button rectangle
#define BN_BUTTONUP 8174
// If a button is set to notify on right clicks, it will send a WM_COMMAND
// with this notify code when the user right clicks on the button.
#define BN_RIGHTCLICK 8183
// When the user chooses a new fly-off item, this notify code will be sent.
#define BN_FLYOFF 8187
// When the user presses a button a WM_MENUSELECT message is sent so that
// the client can display a status prompt describing the function of
// the tool. The fuFlags parameter is set to this value:
#define CMF_TOOLBUTTON 9274
class MaxBmpFileIcon;
/*! \sa <a href="ms-its:3dsmaxsdk.chm::/ui_custom_controls.html">Custom Controls</a>,
Class ICustButton.\n\n
\par Description:
This class uses four indices into the image list to describe the button in each
of the possible states: Out\&Enabled, In\&Enabled, Out\&Disabled and
In\&Disabled. An array of instances of this class are passed into the method
<b>ICustButton::SetFlyOff()</b>.
\par Data Members:
These four data members are indices into the image list. They indicate which
images to use for each of the four possible button states:\n\n
You may specify a unique image for each one of these states by passing a
different index for each state. Or you may supply a single image to be used for
all the states by specifying the same index four times.\n\n
<b>int iOutEn;</b>\n\n
Out\&Enabled.\n\n
<b>int iInEn;</b>\n\n
In\&Enabled\n\n
<b>int iOutDis;</b>\n\n
Out\&Disabled.\n\n
<b>int iInDis;</b>\n\n
In\&Disabled. */
class FlyOffData {
public:
int iOutEn;
int iInEn;
int iOutDis;
int iInDis;
MaxBmpFileIcon* mpIcon;
MaxBmpFileIcon* mpInIcon;
};
// Directions the fly off will go.
#define FLY_VARIABLE 1
#define FLY_UP 2
#define FLY_DOWN 3
#define FLY_HVARIABLE 4 // horizontal variable
#define FLY_LEFT 5
#define FLY_RIGHT 6
typedef LRESULT CALLBACK PaintProc(HDC hdc, Rect rect, BOOL in, BOOL checked, BOOL enabled);
/*! \sa Class ICustomControl,
<a href="ms-its:3dsmaxsdk.chm::/ui_custom_controls.html">Custom Controls</a>,
Class ICustToolbar,
Class FlyOffData,
Class DADMgr,
Class MAXBmpFileIcon.\n\n
\par Description:
Custom buttons may be one of two different forms. A Check button (which stays
pressed in until the user clicks on it again), or a Pick button (which pops
back out as soon as it is released). Buttons may be implemented as a Fly offs.
A fly off offers several alternative buttons which fly out from the button
after it is press and held briefly.\n
\n \image html "butchk.gif"
\n \image html "butpush.gif"
\n \image html "butfly.gif"
The buttons may contain text or graphic images. Fly off buttons only use
graphic images. The plug-in developer has control over the appearance of the
button in each of its four states (Enabled\&Out, Enabled\&In, Disabled\&Out,
Disabled\&In).\n\n
Note: When the user presses a button a <b>WM_MENUSELECT</b> message is sent so
that the client can display a status prompt describing the function of the
tool. The <b>fuFlags</b> parameter is set to this value:
<b>CMF_TOOLBUTTON</b>.\n\n
In 3dsmax version 4.0 you can remove borders from an ICustButton;\n\n
<b>ICustButton *cb = ();</b>\n\n
<b>cb-\>Execute(I_EXE_CB_NO_BORDER);</b>\n\n
To initialize the pointer to the control call: \n
<code>ICustButton *GetICustButton(HWND hCtrl);</code> \n
To release the control call: \n
<code>ReleaseICustButton(ICustButton *ics);</code> \n
The value to use in the Class field of the Custom Control Properties dialog is: CustButton
*/
class ICustButton : public ICustomControl {
public:
/*! \remarks This retrieves the text displayed by the button.
\param text Storage for the text to retrieve.
\param ct Specifies the maximum length of the string returned. */
virtual void GetText( MCHAR *text, int ct )=0;
/*! \remarks This specifies the text displayed by the button.
\param text The text to be displayed by the button. */
virtual void SetText( MCHAR *text )=0;
/*! \remarks This method is used to establish the images used for the
buttons.
\param hImage The image list. An image list is a collection of same-sized images,
each of which can be referred to by an index. Image lists are used to
efficiently manage large sets of icons or bitmaps in Windows. All
images in an image list are contained in a single, wide bitmap in
screen device format. An image list may also include a monochrome
bitmap that contains masks used to draw images transparently (icon
style). The Windows API provides image list functions, which enable you
to draw images, create and destroy image lists, add and remove images,
replace images, and merge images.\n\n
The next four parameters (<b>iOutEn, iInEn, iOutDis, iInDis</b>) are
indices into the image list. They indicate which images to use for each
of the four possible button states. You may specify a unique image for
each one of these states by passing a different index for each state.
Or you may supply a single image to be used for all the states by
specifying the same index four times.
\param iOutEn Out&Enabled.
\param iInEn In&Enabled.
\param iOutDis Out&Disabled.
\param iInDis In&Disabled.
\param w The width of the button image.
\param h The height of the button image. */
virtual void SetImage( HIMAGELIST hImage,
int iOutEn, int iInEn, int iOutDis, int iInDis,
int w, int h )=0;
// Alternate way to set an image on a button.
/*! \remarks This sets the icon image used for a button.
\param pIcon Points to the icon.
\param w The width of the button image.
\param h The height of the button image. */
virtual void SetIcon ( MaxBmpFileIcon* pIcon, int w, int h) = 0;
/*! \remarks This sets the icon image used when a button is pressed.
\param pInIcon Points to the icon.
\param w The width of the button image.
\param h The height of the button image. */
virtual void SetInIcon ( MaxBmpFileIcon* pInIcon, int w, int h) = 0;
/*! \remarks This method sets the button type.
\param type One of the following values:\n\n
<b>CBT_PUSH</b>\n
A Push button pops back out as soon as it is released.\n\n
<b>CBT_CHECK</b>.\n
A Check button stays pressed in until the user clicks on it again. */
virtual void SetType( CustButType type )=0;
/*! \remarks This method sets the button to work as a fly off control.
\param count The number of buttons in the fly off.
\param data An array of instances of the class <b>FlyOffData</b> . This class uses four
indices into the image list to describe the button in each of the possible
states: Out&Enabled, In&Enabled, Out&Disabled and In&Disabled.\n\n
In the simple case, where all the buttons have the same image, you can do the
following:
\code
FlyOffData fod[3] = { // A three button flyoff
{ 0,0,0,0 }, // The first button uses a single image.
{ 1,1,1,1 }, // So does the second button...
{ 2,2,2,2 }, // So does the third...
};
\endcode
Each button will use the same images regardless of its pressed in / disabled
state. Note the button is automatically drawn pushed in (i.e. shaded lighter)
when the user is dragging the cursor over the button, but the actual image on
the button is not changed.\n\n
If you require different images for these states, supply different indices into
the image list for each. See the sample program
<b>/MAXSDK/SAMPLES/HOWTO/CUSTCTRL/CUSTCTRL.CPP</b> for an example of how this
is done.
\param timeOut This is the time in milliseconds the button must be held pressed before the fly
off appears. You may specify 0 if you want the buttons to fly off immediately.
To retrieve the value that 3ds Max uses internally for its flyoffs use a method
of Class Interface called <b>GetFlyOffTime()</b>. This returns a value in milliseconds.
\param init This is the initial button displayed.
\param dir This parameter is optional. It is used to indicate which direction the buttons
should fly off. The choices for direction are:\n\n
<b>FLY_VARIABLE</b>\n
The default. The system will determine the direction of the fly off.\n\n
<b>FLY_UP</b>\n
The buttons fly off above.\n\n
<b>FLY_DOWN</b>\n
The buttons fly off beneath.\n\n
<b>FLY_HVARIABLE</b>\n
The buttons will fly off either left or right with the system determining the
direction.\n\n
<b>FLY_LEFT</b>\n
The buttons fly off to the left.\n\n
<b>FLY_RIGHT</b>\n
The buttons fly off to the right.
\param columns */
virtual void SetFlyOff(int count,FlyOffData *data,int timeOut,
int init,int dir=FLY_VARIABLE, int columns=1)=0;
/*! \remarks This method establishes which button is displayed by
passing its index.
\param f The index of the flyoff button to display.
\param notify This indicates if the call to this method should notify the dialog
proc. If TRUE it is notified; otherwise it isn't. */
virtual void SetCurFlyOff(int f,BOOL notify=FALSE)=0;
/*! \remarks Returns the index of the button which is currently
displayed. */
virtual int GetCurFlyOff()=0;
/*! \remarks Determines if the button is checked. This method returns
TRUE if the check button is currently in the In state (i.e. checked)
and FALSE otherwise. */
virtual BOOL IsChecked()=0;
/*! \remarks Passing TRUE to this method sets the button to the In or
checked state.
\param checked If TRUE the button is set to the checked state; if FALSE the button is unchecked. */
virtual void SetCheck( BOOL checked )=0;
/*! \remarks This method controls if the check button is displayed in
the highlight color when pressed in.
\param highlight TRUE if you want the button to use the highlight color; otherwise pass FALSE. */
virtual void SetCheckHighlight( BOOL highlight )=0;
/*! \remarks Specifies if messages are sent when the user clicks or
releases the button. If this method is called with TRUE, a message is
sent immediately whenever the button is pressed down or released. The
message <b>BN_BUTTONDOWN</b> is sent on button down and
<b>BN_BUTTONUP</b> is sent when the button is released. The
<b>BN_BUTTONUP</b> message is sent even if the button is released
outside the button rectangle.
\param notify TRUE if notification should be send by the button; FALSE if
notifications should not be sent. */
virtual void SetButtonDownNotify(BOOL notify)=0;
/*! \remarks Specifies if messages are sent when the user right clicks
the button.
\param notify If TRUE, the <b>BN_RIGHTCLICK</b> message is sent whenever the users
right clicks on the button. If FALSE no message are sent on right clicks. */
virtual void SetRightClickNotify(BOOL notify)=0;
/*! \remarks This methods sets the highlight color for the check
button.
\param clr The color for the button. It may be specified using the RGB macro, for
example:\n\n
<b>SetHighlightColor(RGB(0,0,255));</b>\n\n
There are several pre-defined colors which may be used:\n\n
<b>RED_WASH, BLUE_WASH</b> and <b>GREEN_WASH. GREEN_WASH</b> is the
standard color used for check buttons in 3ds Max that instigate a
command mode. While the command mode is active, the button should
be displayed in <b>GREEN_WASH.</b> When the mode is finished the button
should be returned to normal. */
virtual void SetHighlightColor(COLORREF clr)=0;
/*! \remarks This methods returns the highlight color for the check button. */
virtual COLORREF GetHighlightColor()=0;
/*! \remarks This method allows a developer to add tooltip text to
single custom buttons.
\param onOff TRUE to turn the tooltip on; FALSE to turn it off.
\param text This may be one of two things:\n\n
The tooltip text (as a <b>TCHAR *</b>).
This is simply the text to show up in the tooltip.\n\n
The symbol <b>LPSTR_TEXTCALLBACK</b>.
This indicates a callback will be used. If this is specified, the
parent window of the button will get the usual tooltip "need text"
notify message (<b>TTN_NEEDTEXT</b>). */
virtual void SetTooltip(BOOL onOff, LPSTR text)=0;
/*! \remarks Sets the drag and drop manager for this button control.
\param dad A pointer to the drag and drop manager to set. */
virtual void SetDADMgr(DADMgr *dad)=0;
/*! \remarks Returns a pointer to the drag and drop manager for this button control.
*/
virtual DADMgr *GetDADMgr()=0;
/*! \remarks Sets the macro data for this button.
\param md The data to set. See Class MacroButtonData. */
virtual void SetMacroButtonData(MacroButtonData *md)=0;
/*! \remarks Returns a pointer to any macro button data for this button. See
Class MacroButtonData. */
virtual MacroButtonData *GetMacroButtonData()=0;
/*! \remarks Sets the callback object used to display the button.\n\n
Note: This method is only available in 3D Studio VIZ (not 3ds Max).
\param proc Points to the callback object for displaying the button.\n\n
Note: <b>typedef LRESULT CALLBACK PaintProc(HDC hdc, Rect rect, BOOL in, BOOL checked, BOOL enabled);</b> */
virtual void SetDisplayProc(PaintProc *proc)=0;
virtual MCHAR* GetCaptionText(void)=0;
virtual bool SetCaptionText(const MCHAR* text)=0;
};
/*! */
CoreExport ICustButton *GetICustButton( HWND hCtrl );
/*! */
CoreExport void ReleaseICustButton( ICustButton *icb );
//---------------------------------------------------------------------------//
// CustStatus
#define CUSTSTATUSWINDOWCLASS _M("CustStatus")
enum StatusTextFormat {
STATUSTEXT_LEFT,
STATUSTEXT_CENTERED,
STATUSTEXT_RIGHT };
/*! \sa Class ICustomControl,
<a href="ms-its:3dsmaxsdk.chm::/ui_custom_controls.html">Custom Controls</a>,
Class ICustStatusEdit.\n\n
\par Description:
The custom status control provide a recessed area of the dialog which the
developer may use as a status prompt display.\n
\n \image html "status.gif"
To initialize the pointer to the control call:
<code>ICustStatus *GetICustStatus(HWND hCtrl);</code> \n
To release the control call: \n
<code>ReleaseICustStatus(ICustStatus *ics); </code> \n
The value to use in the Class field of the Custom Control Properties dialog is: CustStatus
*/
class ICustStatus : public ICustomControl {
public:
/*! \remarks This method specifies the text message to display.
\par Parameters:
<b>MCHAR *text</b>\n\n
Points to the text to display. */
virtual void SetText(MCHAR *text)=0;
/*! \remarks This methods controls the formatting of the text in the
status control.
\par Parameters:
<b>StatusTextFormat f</b>\n\n
One of the following options:\n\n
<b>STATUSTEXT_LEFT</b>\n\n
Left justified in the control.\n\n
<b>STATUSTEXT_CENTERED</b>\n\n
Centered in the control.\n\n
<b>STATUSTEXT_RIGHT</b>\n\n
Right justified in the control. */
virtual void SetTextFormat(StatusTextFormat f)=0;
/*! \remarks Retrieves the text currently displayed in the custom status control.
\par Parameters:
<b>MCHAR *text</b>\n\n
A pointer to storage for the text to return.\n\n
<b>int ct</b>\n\n
The maximum length of the string to return. */
virtual void GetText(MCHAR *text, int ct)=0;
/*! \remarks Specifies the tooltip text to use for a custom status control and
enables or disables its availability.
\par Parameters:
<b>BOOL onOff</b>\n\n
If TRUE the tooltip text may appear; if FALSE the tooltip will not
appear.\n\n
<b>LPSTR text</b>\n\n
The text to use for the tooltip. */
virtual void SetTooltip(BOOL onOff, LPSTR text)=0;
};
/*! */
CoreExport ICustStatus *GetICustStatus( HWND hCtrl );
/*! */
CoreExport void ReleaseICustStatus( ICustStatus *ics );
//---------------------------------------------------------------------------//
// CustSeparator -- for use on toolbars
#define CUSTSEPARATORWINDOWCLASS _M("CustSeparator")
/*! \sa Class ICustomControl,
<a href="ms-its:3dsmaxsdk.chm::/ui_custom_controls.html">Custom
Controls</a>.\n\n
\par Description:
This provides a simple separator item. Methods are available to get and set the
visibility.\n\n
The value to use in the Class field of the Custom Control Properties dialog is:
<b>CustSeparator</b> */
class ICustSeparator : public ICustomControl {
public:
/*! \remarks Sets the visibility of the control to on or off.
\par Parameters:
<b>BOOL onOff</b>\n\n
TRUE for on; FALSE for off. */
virtual void SetVisibility(BOOL onOff)=0;
/*! \remarks Returns TRUE if the control is visible; otherwise FALSE.
*/
virtual BOOL GetVisibility()=0;
};
/*! \remarks This initializes the pointer to the control.
\par Parameters:
<b>HWND hCtrl</b>\n\n
The window handle of the control. */
CoreExport ICustSeparator *GetICustSeparator( HWND hCtrl );
/*! \remarks This releases the control.
\par Parameters:
<b>ICustSeparator *ics</b>\n\n
Points to the separator to release. */
CoreExport void ReleaseICustSeparator( ICustSeparator *ics );
//----------------------------------------------------------------------------//
// CustToolbar control
#define CUSTTOOLBARWINDOWCLASS _M("CustToolbar")
#ifdef _OSNAP
#define VERTTOOLBARWINDOWCLASS _M("VertToolbar")
#endif
// Sent in a WM_COMMAND when the user right clicks in open space
// on a toolbar.
#define TB_RIGHTCLICK 0x2861
enum ToolItemType {
CTB_PUSHBUTTON,
CTB_CHECKBUTTON,
CTB_MACROBUTTON, // DB 10/27/98
CTB_SEPARATOR,
CTB_STATUS,
CTB_OTHER
#ifdef _OSNAP
, CTB_IMAGE
#endif
};
// toolbar orientation
#define CTB_NONE CUI_NONE
#define CTB_HORIZ CUI_HORIZ
#define CTB_VERT CUI_VERT
#define CTB_FLOAT CUI_FLOAT
/*! \sa <a href="ms-its:3dsmaxsdk.chm::/ui_custom_controls.html">Custom Controls</a>.\n\n
\par Description:
This class describes the properties of an item in a 3ds Max custom toolbar.
\par Data Members:
<b>ToolItemType type;</b>\n\n
See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_tool_item_types.html">List of Tool Item
Types</a>.\n\n
<b>int id</b>\n\n
The ID for the control.\n\n
<b>DWORD helpID</b>\n\n
For plug-in developers this id should be set to 0. Basically, the main 3ds Max
help file contains help tags that are tied to various parts of the 3ds Max UI,
allowing the right help page to come up when UI help is requested. In
particular, if you press the ? button on the toolbar, then press another
toolbar button, you'll get help on that button's functionality. This is because
internally pressing the button yields a help ID that indexes into the help
file. But since the same help ID must be compiled into the help file and into
MAX, and since the main 3ds Max help file can not be rebuilt by developers, they
cannot use this functionality.\n\n
<b>int w</b>\n\n
The width of the button image.\n\n
<b>int h</b>\n\n
The height of the button image.\n\n
<b>int orient;</b>\n\n
The orientation of the item. One of the following values:\n\n
<b>CTB_HORIZ</b>\n\n
<b>CTB_VERT</b>\n\n
<b>CTB_FLOAT</b> */
class ToolItem: public MaxHeapOperators {
public:
ToolItemType type;
int id;
DWORD helpID;
int w, h;
int orient; // which orientations does this item apply to?
/*! \remarks Destructor. */
virtual ~ToolItem() {}
};
//! \brief This class describes the properties of a 3ds Max custom toolbar button.
/*! Each one of these items represents a UI widget on a Toolbar in 3dsmax user interface.
\sa Class ToolItem, Class MAXBmpFileIcon, <a href="ms-its:3dsmaxsdk.chm::/ui_custom_controls.html">Custom Controls</a>. */
class ToolButtonItem : public ToolItem
{
public:
//! \name ImageList Members
/*! The following four data members (<b>iOutEn, iInEn, iOutDis, iInDis</b>) are
indices into the image list. They indicate which images to use for each of the
four possible button states. You may specify a unique image for each one of
these states by passing a different index for each state. Or you may supply a
single image to be used for all the states by specifying the same index four
times. */
//@{
//! Out Enabled
int iOutEn;
//! In Enabled
int iInEn;
//! Out Disabled
int iOutDis;
//! In Disabled
int iInDis;
//@}
//! \name Dimensions
//@{
//! The width of the button image.
int iw;
//! The height of the button image.
int ih;
//@}
//! \name Pointer Members
//@{
//! The label describing the tool button item.
MCHAR *label;
//! A pointer to the icon image associated with the button.
MaxBmpFileIcon* mpIcon;
//! A pointer to the pressed (or in) icon image associated with the button.
MaxBmpFileIcon* mpInIcon;
//@}
//! \name Constructors
//@{
//! \brief Constructor.
/*! \param ToolItemType t - See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_tool_item_types.html">List of Tool Item Types</a>.
\param int iOE - The Out\&Enabled index.
\param int iIE - The In\&Enabled index.
\param int iOD - The Out\&Disabled index.
\param int iID - The In\&Disabled index.
\param int iW - The image width (size of the bitmap in the ImageList).
\param int iH - The image height (size of the bitmap in the ImageList).
\param int wd - The width of the button.
\param int ht - The height of the button.
\param int ID - The ID of the control.
\param DWORD hID=0 - The help ID. For plug-in developers this id should be set to 0.
\param MCHAR *lbl = NULL - The label of the button.
\param int or = CTB_HORIZ|CTB_VERT|CTB_FLOAT - The allowable orientation of the item.
This may be one or more of the following: CTB_HORIZ - Horizontal, CTB_VERT - Vertical
CTB_FLOAT - Floating (not docked) */
ToolButtonItem(ToolItemType t,
int iOE, int iIE, int iOD, int iID,
int iW, int iH, int wd,int ht, int ID, DWORD hID=0, MCHAR *lbl = NULL,
int or = CTB_HORIZ|CTB_VERT|CTB_FLOAT)
{
type = t;
orient = or;
iOutEn = iOE; iInEn = iIE; iOutDis = iOD; iInDis = iID;
iw = iW; ih = iH; w = wd; h = ht; id = ID; helpID = hID;
label = lbl;
mpIcon = mpInIcon = NULL;
}
//! \brief Constructor.
/*! \param ToolItemType t - See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_tool_item_types.html">List of Tool Item Types</a>.
\param MaxBmpFileIcon* pIcon - A pointer to the icon associated with the button.
\param int iW - The image width (size of the bitmap in the ImageList).
\param int iH - The image height (size of the bitmap in the ImageList).
\param int wd - The width of the button.
\param int ht - The height of the button.
\param int ID - The ID of the control.
\param DWORD hID=0 - The help ID. For plug-in developers this id should be set to 0.
\param MCHAR *lbl = NULL - The label of the button.
\param int or = CTB_HORIZ|CTB_VERT|CTB_FLOAT - The orientation of the button item. */
ToolButtonItem(ToolItemType t,
MaxBmpFileIcon* pIcon,
int iW, int iH, int wd,int ht, int ID, DWORD hID=0, MCHAR *lbl = NULL,
int or = CTB_HORIZ|CTB_VERT|CTB_FLOAT)
{
type = t;
orient = or;
mpIcon = pIcon;
mpInIcon = NULL;
iOutEn = iInEn = iOutDis = iInDis = -1;
iw = iW; ih = iH; w = wd; h = ht; id = ID; helpID = hID;
label = lbl;
}
//! \brief Constructor
/*! \param ToolItemType t - See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_tool_item_types.html">List of Tool Item Types</a>.
\param MaxBmpFileIcon* pIcon - A pointer to the icon associated with the button.
\param MaxBmpFileIcon* pInIcon - A pointer to the in icon associated with the button.
\param int iW - The image width (size of the bitmap in the ImageList).
\param int iH - The image height (size of the bitmap in the ImageList).
\param int wd - The width of the button.
\param int ht - The height of the button.
\param int ID - The ID of the control.
\param DWORD hID=0 - The help ID. For plug-in developers this id should be set to 0.
\param MCHAR *lbl = NULL - The label of the button.
\param int or = CTB_HORIZ|CTB_VERT|CTB_FLOAT - The orientation of the button item. */
ToolButtonItem(ToolItemType t,
MaxBmpFileIcon* pIcon,
MaxBmpFileIcon* pInIcon,
int iW, int iH, int wd,int ht, int ID, DWORD hID=0, MCHAR *lbl = NULL,
int or = CTB_HORIZ|CTB_VERT|CTB_FLOAT)
{
type = t;
orient = or;
mpIcon = pIcon;
mpInIcon = pInIcon;
iOutEn = iInEn = iOutDis = iInDis = -1;
iw = iW; ih = iH; w = wd; h = ht; id = ID; helpID = hID;
label = lbl;
}
//@}
};
/*! \sa Class ToolItem,
Class MacroButtonData,
Class ICustButton,
<a href="ms-its:3dsmaxsdk.chm::/ui_custom_controls.html">Custom
Controls</a>.\n\n
\par Description:
This class allows a macro item control to be added to the toolbar.\n\n
\par Data Members:
<b>MacroButtonData md;</b>\n\n
Points to the macro button data for this tool item. */
class ToolMacroItem : public ToolItem {
public:
MacroButtonData md;
/*! \remarks Constructor.
\par Parameters:
<b>int wd</b>\n\n
The width of the item.\n\n
<b>int ht</b>\n\n
The height of the item.\n\n
<b>MacroButtonData *data</b>\n\n
Points to the macro button data.\n\n
<b>int or = CTB_HORIZ|CTB_VERT|CTB_FLOAT</b>\n\n
Specifies the orientation. One or more of the following values:\n\n
<b>CTB_HORIZ</b>\n\n
<b>CTB_VERT</b>\n\n
<b>CTB_FLOAT</b> */
ToolMacroItem(int wd, int ht, MacroButtonData *data, int or = CTB_HORIZ|CTB_VERT|CTB_FLOAT)
{
type = CTB_MACROBUTTON;
md = *data;
orient = or;
w = wd; h = ht; id = 0; helpID = 0;
}
};
/*! \sa Class ToolItem,
<a href="ms-its:3dsmaxsdk.chm::/ui_custom_controls.html">Custom Controls</a>.\n\n
\par Description:
This class provides a toolbar separator object. This is used to space out
buttons in the toolbar.
\par Data Members:
<b>int vis;</b>\n\n
Visibility setting. */
class ToolSeparatorItem : public ToolItem {
public:
int vis;
/*! \remarks
Constructor.
\par Parameters:
<b>int w</b>\n\n
The width of the separator.\n\n
<b>int h=16</b>\n\n
The height of the separator.\n\n
<b>BOOL vis=TRUE</b>\n\n
TRUE for visible; FALSE for not.\n\n
<b>int or=CTB_HORIZ|CTB_VERT|CTB_FLOAT</b>\n\n
The allowable orientations. One or more of the following values:\n\n
<b>CTB_HORIZ</b>\n\n
<b>CTB_VERT</b>\n\n
<b>CTB_FLOAT</b> */
ToolSeparatorItem(int w, int h=16, BOOL vis=TRUE, int or=CTB_HORIZ|CTB_VERT|CTB_FLOAT) {
type = CTB_SEPARATOR;
id = 0;
helpID = 0;
this->w = w;
this->h = h;
h = 0;
this->vis = vis;
orient = or;
}
};
/*! \sa Class ToolItem,
<a href="ms-its:3dsmaxsdk.chm::/ui_custom_controls.html">Custom
Controls</a>.\n\n
\par Description:
This class allows a status control to be added to the toolbar.
\par Data Members:
<b>BOOL fixed;</b>\n\n
TRUE indicates a fixed width. If it is not fixed, then it will auto size itself
horizontally based on the size of the toolbar. For an example of this see the
status bar in the track view. */
class ToolStatusItem : public ToolItem {
public:
BOOL fixed;
/*! \remarks Constructor.
\par Parameters:
<b>int w</b>\n\n
The width of the status box.\n\n
<b>int h</b>\n\n
The height of the status box.\n\n
<b>BOOL f</b>\n\n
The fixed data member - see above.\n\n
<b>int id</b>\n\n
The ID of the control.\n\n
<b>DWORD hID=0</b>\n\n
The help ID of the control. For plug-in developers this id should be set to 0.
*/
ToolStatusItem(int w, int h,BOOL f,int id, DWORD hID=0, int or = CTB_HORIZ|CTB_FLOAT) {
type = CTB_STATUS;
this->w = w;
this->h = h;
this->id = id;
this->helpID = hID;
fixed = f;
orient = or;
}
};
#define CENTER_TOOL_VERTICALLY 0xffffffff
/*! \sa Class ToolItem,
<a href="ms-its:3dsmaxsdk.chm::/ui_custom_controls.html">Custom
Controls</a>.\n\n
\par Description:
This class is used to add any user defined or standard Windows control to a 3ds
Max custom toolbar.
\par Data Members:
<b>int y;</b>\n\n
The vertical justification.\n\n
<b>DWORD style;</b>\n\n
The control window style.\n\n
<b>TCHAR *className;</b>\n\n
The class name of the control. For the 3ds Max custom controls you may use one
of the following #defines:\n\n
<b>SPINNERWINDOWCLASS</b>\n\n
<b>ROLLUPWINDOWCLASS</b>\n\n
<b>CUSTEDITWINDOWCLASS</b>\n\n
<b>CUSTBUTTONWINDOWCLASS</b>\n\n
<b>CUSTSTATUSWINDOWCLASS</b>\n\n
<b>CUSTTOOLBARWINDOWCLASS</b>\n\n
<b>CUSTIMAGEWINDOWCLASS</b>\n\n
<b>COLORSWATCHWINDOWCLASS</b>\n\n
Or it may be a literal string such as:\n\n
<b>"COMBOBOX"</b>\n\n
See the Win32 API help under <b>CreateWindow()</b> for a list of the options
here.\n\n
<b>TCHAR *windowText;</b>\n\n
The window text. This is displayed in controls that have text in them. */
class ToolOtherItem : public ToolItem {
public:
int y;
DWORD_PTR style;
MCHAR *className;
MCHAR *windowText;
/*! \remarks Constructor.
\par Parameters:
<b>MCHAR *cls</b>\n\n
The class name of the control. This may be one of the values listed above under
data members.\n\n
<b>int w</b>\n\n
The width of the control.\n\n
<b>int h</b>\n\n
The height of the control.\n\n
<b>int id</b>\n\n
The ID of the control.\n\n
<b>DWORD_PTR style=WS_CHILD|WS_VISIBLE</b>\n\n
The style of the control window.\n\n
<b>int y=CENTER_TOOL_VERTICALLY</b>\n\n
The vertical justification. This is a y offset from the top of the toolbar in
pixels. The default value simply centers the tool vertically.\n\n
<b>TCHAR *wt=NULL</b>\n\n
The window text.\n\n
<b>DWORD hID=0</b>\n\n
The help ID. For plug-in developers this id should be set to 0. */
ToolOtherItem(MCHAR *cls,int w,int h,int id,DWORD_PTR style=WS_CHILD|WS_VISIBLE,
int y=CENTER_TOOL_VERTICALLY,MCHAR *wt=NULL,DWORD hID=0, int or=CTB_HORIZ|CTB_FLOAT) {
type = CTB_OTHER;
this->y = y;
this->w = w;
this->h = h;
this->id = id;
this->helpID = hID;
this->style = style;
orient = or;
className = cls;
windowText = wt;
}
};
#ifdef _OSNAP //allow image controls on toolbars
/*! \sa Class ToolItem.\n\n
\par Description:
This class allows a developer to use an image in the toolbar. This is used
internally as part of the object snap code. All methods of this class are
implemented by the system. */
class ToolImageItem : public ToolItem {
public:
int y;
int il_index;
/*! \remarks Constructor. The data members are initialized to the values
passed. The type parameter of ToolItem is set to CTB_IMAGE. */
ToolImageItem(int w,int h,int k,int id, int y=CENTER_TOOL_VERTICALLY,DWORD hID=0, int or=CTB_HORIZ|CTB_FLOAT) {
type = CTB_IMAGE;
this->y = y;
this->w = w;
this->h = h;
this->il_index = k;
this->id = id;
this->helpID = hID;
orient = or;
}
};
#endif
/*! \sa <a href="ms-its:3dsmaxsdk.chm::/ui_custom_controls.html">Custom Controls</a>.
Class ToolItem,
Class MacroButtonData,
Class CUIFrameMsgHandler,
Class ICustStatusEdit,
Class ICustStatus,
Class ICustButton.\n\n
\par Description:
This control allows the creation of toolbars containing buttons (push, check,
and fly-offs), status fields, separators (spacers), and other Windows or user
defined controls. Note: The standard size for 3ds Max toolbar button icons is
16x15.\n\n
In 3ds Max 3.0 and later toolbars may have multiple rows, or appear vertically.
They may also have macro buttons (added with the MacroButtonData class) which
may have icons or text.\n
\n \image html "toolbar.gif"
To initialize the pointer to the control call: \n
<code>ICustToolbar *GetICustToolbar(HWND hCtrl);</code> \n
To release the control call: \n
<code>ReleaseICustToolbar(ICustToolbar *ict);</code> \n
The value to use in the Class field of the Custom Control Properties dialog is: CustToolbar \n\n
Note: The TB_RIGHTCLICK message is sent when the user right clicks in open space on a toolbar: \n
Also Note: To add tooltips to the toolbar controls you can do so by capturing the WM_NOTIFY
message in the dialog proc. For complete sample code see <b>/MAXSDK/SAMPLES/HOWTO/CUSTCTRL/CUSTCTRL.CPP</b>.
The specific message is processed as shown below. \n
\code
case WM_NOTIFY:
// This is where we provide the tooltip text for the
// toolbar buttons...
if(((LPNMHDR)lParam)->code == TTN_NEEDTEXT) {
LPTOOLTIPTEXT lpttt;
lpttt = (LPTOOLTIPTEXT)lParam;
switch (lpttt->hdr.idFrom) {
case ID_TB_1:
lpttt->lpszText = _T("Do Nothing Up");
break;
case ID_TB_2:
lpttt->lpszText = _T("Do Nothing Down");
break;
case ID_TB_3:
lpttt->lpszText = _T("Do Nothing Lock");
break;
case IDC_BUTTON1:
if (to->custCtrlButtonC->IsChecked())
lpttt->lpszText = _T("Button Checked");
else
lpttt->lpszText = _T("Button Un-Checked");
break;
};
}
break;
\endcode
*/
class ICustToolbar : public ICustomControl {
public:
/*! \remarks This method establishes the image list used to display
images in the toolbar.
\par Parameters:
<b>HIMAGELIST hImage</b>\n\n
The image list. An image list is a collection of same-sized images,
each of which can be referred to by an index. Image lists are used to
efficiently manage large sets of icons or bitmaps in Windows. All
images in an image list are contained in a single, wide bitmap in
screen device format. An image list may also include a monochrome
bitmap that contains masks used to draw images transparently (icon
style). The Windows API provides image list functions, which enable you
to draw images, create and destroy image lists, add and remove images,
replace images, and merge images. */
virtual void SetImage( HIMAGELIST hImage )=0;
/*! \remarks The developer calls this method once for each item in the
toolbar. The items appear in the toolbar from left to right in the order that
they were added using this method. (Note that this method adds tools to the
custom toolbar and not the 3ds Max toolbar).
\par Parameters:
<b>const ToolItem\& entry</b>\n\n
Describes the item to add to the toolbar.\n\n
<b>int pos=-1</b>\n\n
Controls where the added tool is inserted. The default of -1 indicates the
control will be added at the right end of the toolbar. */
virtual void AddTool( ToolItem& entry, int pos=-1)=0;
/*! \remarks Currently this method is identical to the AddTool() method.
\par Parameters:
<b>ToolItem\& entry</b>\n\n
Describes the item to add to the toolbar.\n\n
<b>int pos=-1</b>\n\n
Controls where the added tool is inserted. The default of -1 indicates
the control will be added at the right end of the toolbar. */
virtual void AddTool2(ToolItem& entry, int pos=-1)=0; // Adds caption buttons to toolbars
/*! \remarks This method is used to delete tools from the toolbar.
\par Parameters:
<b>int start</b>\n\n
Specifies which tool is the first to be deleted.\n\n
<b>int num=-1</b>\n\n
Specifies the number of tools to delete. If this parameter is -1 (the
default) it deletes 'start' through count-1 tools. */
virtual void DeleteTools( int start, int num=-1 )=0; // num = -1 deletes 'start' through count-1 tools
/*! \remarks Passing TRUE to this method draws a border beneath the
toolbar. You can see the appearance of the bottom border in the sample
toolbar shown above. If this is set to FALSE, the border is not drawn.
\par Parameters:
<b>BOOL on</b>\n\n
TRUE to draw the border; FALSE for no border. */
virtual void SetBottomBorder(BOOL on)=0;
/*! \remarks Passing TRUE to this method draws a border above the
toolbar. You can see the appearance of the top border in the sample
toolbar shown above. If this is set to FALSE, the border is not drawn
\par Parameters:
<b>BOOL on</b>\n\n
TRUE to draw the border; FALSE for no border. */
virtual void SetTopBorder(BOOL on)=0;
/*! \remarks Returns the width needed for specified number of rows.
\par Parameters:
<b>int rows</b>\n\n
The number of rows. */
virtual int GetNeededWidth(int rows)=0; // return width needed for specified # of rows
/*! \remarks Sets the number of rows that the toolbar may hold.
\par Parameters:
<b>int rows</b>\n\n
The number of rows to set. */
virtual void SetNumRows(int rows)=0;
/*! \remarks This method is used to return a pointer to one of the
toolbar's buttons. Using this pointer you can call methods on the
button. If you use this method, you must release the control after you
are finished with it.
\par Parameters:
<b>int id</b>\n\n
Specifies the id of the toolbar button.
\return A pointer to one of the toolbar's buttons. If the button is
not found it returns NULL. See Class ICustButton. */
virtual ICustButton *GetICustButton( int id )=0;
/*! \remarks This method is used to return a pointer to one of the
toolbars status controls. Using this pointer you can call methods on
the status control. If you use this method, you must release the
control after you are finished with it.
\par Parameters:
<b>int id</b>\n\n
Specifies the id of the toolbar button.
\return A pointer to one of the toolbars status controls. See
Class ICustStatus. */
virtual ICustStatus *GetICustStatus( int id )=0;
/*! \remarks Returns the handle to the toolbar item whose ID is
passed.
\par Parameters:
<b>int id</b>\n\n
Specifies the id of the toolbar button. */
virtual HWND GetItemHwnd(int id)=0;
/*! \remarks Returns the number of items in the toolbar. */
virtual int GetNumItems()=0;
/*! \remarks Each item in the toolbar has an ID. When items are programatically
added to the toolbar via Class ToolButtonItem an ID is passed to the
ToolButtonItem constructor. This method returns the ID for the
specified item in the toolbar.
\par Parameters:
<b>int index</b>\n\n
Specifies which toolbar item to return the id of. This is an index
between <b>0</b> and <b>GetNumItems()-1</b>.
\return When the button is added using
Class ToolButtonItem this is
the id that is part of that structure. When the user operates a tool
the dialog proc get a <b>WM_COMMAND</b> message and this is also the id
in <b>LOWORD(wParam)</b>. */
virtual int GetItemID(int index)=0;
/*! \remarks Returns the index into the list of toolbar entries of the item whose id
is passed.
\par Parameters:
<b>int id</b>\n\n
The id of the control to find. */
virtual int FindItem(int id)=0;
/*! \remarks Deletes the toolbar item whose id is passed.
\par Parameters:
<b>int id</b>\n\n
The id of the control to delete. */
virtual void DeleteItemByID(int id)=0;
/*! \remarks This method links this toolbar to the CUI frame whose window handle and
message handler are passed.
\par Parameters:
<b>HWND hCUIFrame</b>\n\n
The window handle of the CUI frame to link this toolbar to.\n\n
<b>CUIFrameMsgHandler *msgHandler</b>\n\n
Points to the message handler for the CUI frame. See
Class CUIFrameMsgHandler. */
virtual void LinkToCUIFrame( HWND hCUIFrame, CUIFrameMsgHandler *msgHandler)=0;
/*! \remarks Computes the required size of a floating CUI Frame which is
linked to a toolbar. The values returned will be zero if the frame is not
linked to a toolbar.
\par Parameters:
<b>SIZE *sz</b>\n\n
The computed size is returned here. <b>sz.cx</b> is the width, <b>sz.cy</b> is
the height.\n\n
<b>int rows=1</b>\n\n
The number of rows for the toolbar used in the computation. */
virtual void GetFloatingCUIFrameSize(SIZE *sz, int rows=1)=0;
/*! \remarks This method is used to return a pointer to the custom status edit
control whose id is passedIf you use this method, you must release the
control after you are finished with it. See
Class ICustStatusEdit.
\par Parameters:
<b>int id</b>\n\n
Specifies the id of the toolbar button. */
virtual ICustStatusEdit *GetICustStatusEdit(int id)=0;
/*! \remarks This resets the icons in the toolbar. This tells all the buttons in
this toolbar to delete their icon image cache. If a plug-in has created
a toolbar with any MaxBmpFileIcons on it, it should register a callback
for color changing, and call this method on the toolbar. See
<a href="struct_notify_info.html">Structure NotifyInfo</a> for
registering the color change callback. */
virtual void ResetIconImages() = 0;
};
/*! */
CoreExport ICustToolbar *GetICustToolbar( HWND hCtrl );
/*! Note: The <b>TB_RIGHTCLICK</b> message is sent when the user right clicks
in open space on a toolbar:\n\n
Also Note: To add tooltips to the toolbar controls you can do so by capturing
the <b>WM_NOTIFY</b> message in the dialog proc. For complete sample code see
<b>/MAXSDK/SAMPLES/HOWTO/CUSTCTRL/CUSTCTRL.CPP</b>. The specific message is
processed as shown below.\n\n
\code
case WM_NOTIFY:
// This is where we provide the tooltip text for the
// toolbar buttons...
if(((LPNMHDR)lParam)->code == TTN_NEEDTEXT) {
LPTOOLTIPTEXT lpttt;
lpttt = (LPTOOLTIPTEXT)lParam;
switch (lpttt->hdr.idFrom) {
case ID_TB_1:
lpttt->lpszText = _T("Do Nothing Up");
break;
case ID_TB_2:
lpttt->lpszText = _T("Do Nothing Down");
break;
case ID_TB_3:
lpttt->lpszText = _T("Do Nothing Lock");
break;
case IDC_BUTTON1:
if
(to->custCtrlButtonC->IsChecked())lpttt->lpszText = _T("Button Checked");
else
lpttt->lpszText = _T("Button Un-Checked");
break;
};
}
break;
\endcode */
CoreExport void ReleaseICustToolbar( ICustToolbar *ict );
#ifdef _OSNAP
/*! \sa Class ICustomControl.\n\n
\par Description:
This control allows the creation of <b>vertical</b> toolbars containing buttons
(push, check, and fly-offs), status fields, separators (spacers), and other
Windows or user defined controls. Note: The standard size for 3ds Max toolbar
button icons is 16x15. All methods of this class are implemented by the
system.\n\n
To initialize the pointer to the control call: <br> <b>IVertToolbar
*GetIVertToolbar(HWND hCtrl);</b> To release the control call:<br>
<b>void ReleaseIVertToolbar(IVertToolbar *ict);</b> The value to use in the
Class field of the Custom Control Properties dialog is: <b>VertToolbar</b>
*/
class IVertToolbar : public ICustomControl {
public:
/*! \remarks This method establishes the image list used to display
images in the toolbar.
\par Parameters:
<b>HIMAGELIST hImage</b>\n\n
The image list. An image list is a collection of same-sized images,
each of which can be referred to by an index. Image lists are used to
efficiently manage large sets of icons or bitmaps in Windows. All
images in an image list are contained in a single, wide bitmap in
screen device format. An image list may also include a monochrome
bitmap that contains masks used to draw images transparently (icon
style). The Windows API provides image list functions, which enable you
to draw images, create and destroy image lists, add and remove images,
replace images, and merge images. */
virtual void SetImage( HIMAGELIST hImage )=0;
/*! \remarks The developer calls this method once for each item in the
toolbar. The items appear in the toolbar from left to right in the
order that they were added using this method. (Note that this method
adds tools to the custom toolbar and not the 3ds Max toolbar).
\par Parameters:
<b>const ToolItem\& entry</b>\n\n
Describes the of item to add to the toolbar.\n\n
<b>int pos=-1</b>\n\n
Controls where the added tool is inserted. The default of -1 indicates
the control will be added at the right end of the toolbar. */
virtual void AddTool( const ToolItem& entry, int pos=-1 )=0;
/*! \remarks This method is used to delete tools from the toolbar.
\par Parameters:
<b>int start</b>\n\n
Specifies which tool is the first to be deleted.\n\n
<b>int num=-1</b>\n\n
Specifies the number of tools to delete. If this parameter is -1 (the
default) it deletes 'start' through count-1 tools. */
virtual void DeleteTools( int start, int num=-1 )=0; // num = -1 deletes 'start' through count-1 tools
/*! \remarks Passing TRUE to this method draws a border beneath the
toolbar.
\par Parameters:
<b>BOOL on</b>\n\n
TRUE to draw the border; FALSE for no border. */
virtual void SetBottomBorder(BOOL on)=0;
/*! \remarks Passing TRUE to this method draws a border above the
toolbar.
\par Parameters:
<b>BOOL on</b>\n\n
TRUE to draw the border; FALSE for no border. */
virtual void SetTopBorder(BOOL on)=0;
/*! \remarks This method is used to return a pointer to one of the
toolbar's buttons. Using this pointer you can call methods on the
button. If you use this method, you must release the control after you
are finished with it.
\par Parameters:
<b>int id</b>\n\n
Specifies the id of the toolbar button.
\return A pointer to one of the toolbar's buttons. */
virtual ICustButton *GetICustButton( int id )=0;
/*! \remarks This method is used to return a pointer to one of the
toolbars status controls. Using this pointer you can call methods on
the status control. If you use this method, you must release the
control after you are finished with it.
\par Parameters:
<b>int id</b>\n\n
Specifies the id of the toolbar button.
\return A pointer to one of the toolbars status controls */
virtual ICustStatus *GetICustStatus( int id )=0;
/*! \remarks Returns the handle to the toolbar item whose ID is
passed.
\par Parameters:
<b>int id</b>\n\n
Specifies the id of the toolbar button. */
virtual HWND GetItemHwnd(int id)=0;
virtual void Enable(BOOL onOff=TRUE){};
};
CoreExport IVertToolbar *GetIVertToolbar( HWND hCtrl );
CoreExport void ReleaseIVertToolbar( IVertToolbar *ict );
#endif
//---------------------------------------------------------------------------//
// CustImage
#define CUSTIMAGEWINDOWCLASS _M("CustImage")
/*! \sa Class ICustomControl,
<a href="ms-its:3dsmaxsdk.chm::/ui_custom_controls.html">Custom
Controls</a>.\n\n
\par Description:
The custom image control provides a recessed area in the dialog to display a
bitmap image.\n\n
\image html "custimg.gif"
To initialize the pointer to the control call:\n
<code>ICustImage *GetICustImage(HWND hCtrl);</code> \n
To release the control call: \n
<code>ReleaseICustImage(ICustImage *ici);</code> \n
The value to use in the Class field of the Custom Control Properties dialog is: CustImage
*/
class ICustImage : public ICustomControl {
public:
/*! \remarks This method sets the image to display.
\par Parameters:
<b>HIMAGELIST hImage</b>\n\n
An image list. An image list is a collection of same-sized images, each
of which can be referred to by its index. Image lists are used to
efficiently manage large sets of icons or bitmaps in Windows. All
images in an image list are contained in a single, wide bitmap in
screen device format. An image list may also include a monochrome
bitmap that contains masks used to draw images transparently (icon
style). The Windows API provides image list functions, which enable you
to draw images, create and destroy image lists, add and remove images,
replace images, and merge images.\n\n
<b>int index</b>\n\n
This is the index of the image to display in the image list.\n\n
<b>int w</b>\n\n
The image width.\n\n
<b>int h</b>\n\n
The image height. */
virtual void SetImage( HIMAGELIST hImage,int index, int w, int h )=0;
};
/*! */
CoreExport ICustImage *GetICustImage( HWND hCtrl );
/*! */
CoreExport void ReleaseICustImage( ICustImage *ici );
#ifdef _OSNAP
//---------------------------------------------------------------------------//
// CustImage 2D Version for displaying osnap icons
#define CUSTIMAGEWINDOWCLASS2D _M("CustImage2D")
class ICustImage2D : public ICustomControl {
public:
virtual void SetImage( HIMAGELIST hImage,int index, int w, int h )=0;
};
#endif
//------------------------------------------------------------------------
// Off Screen Buffer
/*! \sa <a href="ms-its:3dsmaxsdk.chm::/ui_custom_controls.html">Custom
Controls</a>.\n\n
\par Description:
This control provides an off screen buffer which the developer may draw into,
then quickly blit onto the actual display for flicker free image updates.\n\n
To initialize the pointer to the control call: */
class IOffScreenBuf: public MaxHeapOperators {
public:
/*! \remarks Returns a handle to the display device context (DC) for
the off screen buffer. The display device context can be used in
subsequent GDI functions to draw in the buffer. */
virtual HDC GetDC()=0;
/*! \remarks This method is used to erase the buffer.
\par Parameters:
<b>Rect *rct=NULL</b>\n\n
Specifies the rectangular region to erase. If NULL the entire buffer is
erased. */
virtual void Erase(Rect *rct=NULL)=0;
/*! \remarks This method blits (transfers the image from) the buffer
to the display.
\par Parameters:
<b>Rect *rct=NULL</b>\n\n
Specifies the rectangular region to blit. If NULL the entire buffer is
blitted. */
virtual void Blit(Rect *rct=NULL)=0;
/*! \remarks This method is used to resize the buffer. */
virtual void Resize()=0;
/*! \remarks This sets the buffer to the specified color.
\par Parameters:
<b>COLORREF color</b>\n\n
The color to set. You may use the RGB macro to set the color. */
virtual void SetBkColor(COLORREF color)=0;
/*! \remarks This methods retrieves the background color of the
buffer.
\return The background color of the buffer. */
virtual COLORREF GetBkColor()=0;
};
/*! */
CoreExport IOffScreenBuf *CreateIOffScreenBuf(HWND hWnd);
/*! */
CoreExport void DestroyIOffScreenBuf(IOffScreenBuf *iBuf);
//------------------------------------------------------------------------
// Color swatch control
// Puts up the ColorPicker when user right clicks on it.
//
// This message is sent as the color is being adjusted in the
// ColorPicker.
// LOWORD(wParam) = ctrlID,
// HIWORD(wParam) = 1 if button UP
// = 0 if mouse drag.
// lParam = pointer to ColorSwatchControl
#define CC_COLOR_CHANGE WM_USER + 603
// LOWORD(wParam) = ctrlID,
// lParam = pointer to ColorSwatchControl
#define CC_COLOR_BUTTONDOWN WM_USER + 606
// LOWORD(wParam) = ctrlID,
// HIWORD(wParam) = FALSE if user cancelled - TRUE otherwise
// lParam = pointer to ColorSwatchControl
#define CC_COLOR_BUTTONUP WM_USER + 607
// This message is sent if the color has been clicked on, before
// bringing up the color picker.
// LOWORD(wParam) = ctrlID,
// HIWORD(wParam) = 0
// lParam = pointer to ColorSwatchControl
#define CC_COLOR_SEL WM_USER + 604
// This message is sent if another color swatch has been dragged and dropped
// on this swatch.
// LOWORD(wParam) = toCtrlID,
// HIWORD(wParam) = 0
// lParam = pointer to ColorSwatchControl
#define CC_COLOR_DROP WM_USER + 605
// This message is sent when the color picker is closed
// LOWORD(wParam) = ctrlID,
// HIWORD(wParam) = 0
// lParam = pointer to ColorSwatchControl
// The following macro has been added
// in 3ds max 4.2. If your plugin utilizes this new
// mechanism, be sure that your clients are aware that they
// must run your plugin with 3ds max version 4.2 or higher.
#define CC_COLOR_CLOSE WM_USER + 608 //RK: 05/14/00, added this
// End of 3ds max 4.2 Extension
#define COLORSWATCHWINDOWCLASS _M("ColorSwatch")
/*! \sa Class ICustomControl,
<a href="ms-its:3dsmaxsdk.chm::/ui_custom_controls.html">Custom Controls</a>,
<a href="ms-its:listsandfunctions.chm::/idx_R_colorref.html">COLORREF</a>.\n\n
\par Description:
The color swatch control puts up the standard 3ds Max modeless color selector
when the control is clicked on. The plug-in may be notified as the user
interactively selects new colors.\n\n
\image html "colorsw.gif"
To initialize the pointer to the control call: <br> <b>*GetIColorSwatch(HWND
hCtrl, COLORREF col, TCHAR *name);</b>\n\n
For example: <b>custCSw = GetIColorSwatch(GetDlgItem(hDlg, IDC_CSWATCH),
RGB(255,255,255), _T("New Wireframe Color"));</b>\n\n
This returns the pointer to the control, sets the initial color selected, and
displays the text string passed in the title bar of the selection dialog.\n\n
To release the control call: <b>ReleaseIColorSwatch(IColowSwatch
*ics);</b>\n\n
The value to use in the Class field of the Custom Control Properties dialog is:
<b>ColorSwatch</b> This message is sent as the color is being adjusted in the
ColorPicker.\n\n
<b>CC_COLOR_CHANGE</b>\n\n
<b>lParam</b> = pointer to ColorSwatchControl\n\n
<b>LOWORD(wParam)</b> contains the ID of the control. This is the named
established in the ID field of the Custom Control Properties dialog.\n\n
<b>HIWORD(wParam)</b> contains 1 if button UP, or 0 if mouse drag.\n\n
This message is sent if the color has been clicked on, before bringing up the
color picker.\n\n
<b>CC_COLOR_SEL</b>\n\n
<b>lParam</b> contains a pointer to the ColorSwatch Control.\n\n
<b>LOWORD(wParam)</b> contains the ID of the control. This is the named
established in the ID field of the Custom Control Properties dialog.\n\n
<b>HIWORD(wParam)</b> contains 0.\n\n
This message is sent if another color swatch has been dragged and dropped on
this swatch.\n\n
<b>CC_COLOR_DROP</b>\n\n
<b>lParam</b> contains a pointer to the ColorSwatch Control.\n\n
<b>LOWORD(wParam)</b> contains the ID of the control. This is the named
established in the ID field of the Custom Control Properties dialog.\n\n
<b>HIWORD(wParam)</b> contains 0.\n\n
This message is sent when the color picker is closed.\n\n
<b>CC_COLOR_CLOSE</b>\n\n
<b>lParam</b> contains a pointer to the ColorSwatch Control.\n\n
<b>LOWORD(wParam)</b> contains the ID of the control. This is the named
established in the ID field of the Custom Control Properties dialog.\n\n
<b>HIWORD(wParam)</b> contains 0.
*/
class IColorSwatch: public ICustomControl {
public:
// sets only the varying color of the color picker if showing
/*! \remarks This method sets the current color value.
\par Parameters:
<b>COLORREF c</b>\n\n
You can pass specific RGB values in using the RGB macro. For example,
to pass in pure blue you would use <b>RGB(0,0,255)</b>.\n\n
<b>int notify=FALSE</b>\n\n
If you pass TRUE for this parameter, the dialog proc for the dialog
will receive the <b>CC_COLOR_CHANGE</b> message each time the color is
changed.
\return This method returns the old color. */
virtual COLORREF SetColor(COLORREF c, int notify=FALSE)=0; // returns old color
COLORREF SetColor(Color c, int notify=FALSE) {return SetColor(c.toRGB(), notify);} // returns old color
virtual AColor SetAColor(AColor c, int notify=FALSE)=0; // returns old color
// sets both the varying color and the "reset"color of the color picker
virtual COLORREF InitColor(COLORREF c, int notify=FALSE)=0; // returns old color
COLORREF InitColor(Color c, int notify=FALSE) {return InitColor(c.toRGB(), notify);} // returns old color
virtual AColor InitAColor(AColor c, int notify=FALSE)=0; // returns old color
virtual void SetUseAlpha(BOOL onOff)=0;
virtual BOOL GetUseAlpha()=0;
/*! \remarks This method may be used to retrieve the color selected by
the user.
\return The <b>COLORREF</b> structure returned may be broken down into
individual RGB values by using the <b>GetRValue(color)</b>,
<b>GetGValue(color)</b>, and <b>GetBValue(color)</b> macros. */
virtual COLORREF GetColor()=0;
virtual AColor GetAColor()=0;
/*! \remarks This method sets if the color shown in the color swatch
is dithered on not.
\par Parameters:
<b>BOOL onOff</b>\n\n
TRUE to force the color to be dithered; otherwise FALSE. */
virtual void ForceDitherMode(BOOL onOff)=0;
/*! \remarks Call this method to have the color selector comes up in a
modal dialog. This forces the user to select OK before the user may
operate the rest of the program. */
virtual void SetModal()=0;
/*! \remarks This method is called to indicate that the color swatch
is in a dialog that has been become active or inactive. A color swatch
that is in an inactive dialog will be drawn as dithered due to the
limited number of color registers available on an 8-bit display.
\par Parameters:
<b>int onOff</b>\n\n
If TRUE the color swatch is in an active dialog. If FALSE the control
is in an inactive dialog. */
virtual void Activate(int onOff)=0;
/*! \remarks If there is already a color picker up for a color swatch,
this method switches it over to edit the color swatch on which
<b>EditThis()</b> was called.
\par Parameters:
<b>BOOL startNew=TRUE</b>\n\n
If there was no color picker up, if this parameter is set to TRUE, then
a color picker is created. If this parameter is set to FALSE, and there
was no color picker up, then nothing happens. */
virtual void EditThis(BOOL startNew=TRUE)=0;
virtual void SetKeyBrackets(BOOL onOff)=0;
};
CoreExport IColorSwatch *GetIColorSwatch( HWND hCtrl, COLORREF col, MCHAR *name);
CoreExport IColorSwatch *GetIColorSwatch( HWND hCtrl, Color col, MCHAR *name);
CoreExport IColorSwatch *GetIColorSwatch( HWND hCtrl, AColor col, MCHAR *name);
CoreExport IColorSwatch *GetIColorSwatch(HWND hCtrl);
CoreExport void ReleaseIColorSwatch( IColorSwatch *ics );
CoreExport void RefreshAllColorSwatches();
// This class is only available in versions 5.1 and later.
#define COLOR_SWATCH_RENAMER_INTERFACE_51 Interface_ID(0x5a684953, 0x1fc043dc)
/*! \n\n
class IColorSwatchRenamer\n\n
\par Description:
This class is an interface for changing the name of a color swatch. Previously
the only way to change the name of a swatch was to reinitialize it with a new
GetIColorSwatch call, and this would not help with swatches that were already
being displayed in a color selector dialog. Using this new interface,
developers can change the name of a swatch and\n\n
simultaneously change the name of a color selector dialog that's associated
with the swatch. An example of its usage can be seen below :-\n\n
It's used in Editable Poly as follows - when the user changes the radio button
that affects whether our swatch is used as a "Select by Color" or a "Select by
Illumination" swatch, the following code is used to update the swatch.\n\n
These first three lines are adequate when the color selector is not being
displayed:\n\n
<b>mpEPoly-\>getParamBlock()-\>GetValue (ep_vert_sel_color, t,
selByColor,</b>\n\n
<b>mpEPoly-\>FOREVER); getParamBlock()-\>GetValue (ep_vert_color_selby,
t,</b>\n\n
<b>mpEPoly-\>byIllum, FOREVER);</b>\n\n
<b>iCol = GetIColorSwatch (GetDlgItem (hWnd, IDC_VERT_SELCOLOR),
selByColor,</b>\n\n
<b> GetString (byIllum ? IDS_SEL_BY_ILLUM : IDS_SEL_BY_COLOR));</b>\n\n
That will update the swatch to the correct name and color. However, if the\n\n
color selector is being displayed, we need to use the new interface to
ensure\n\n
that the name is promptly updated in the UI:\n\n
<b>pInterface = iCol-\>GetInterface
(COLOR_SWATCH_RENAMER_INTERFACE_51);</b>\n\n
<b>if (pInterface) {</b>\n\n
<b> IColorSwatchRenamer *pRenamer = (IColorSwatchRenamer *)
pInterface;</b>\n\n
<b> pRenamer-\>SetName (GetString (byIllum ? IDS_SEL_BY_ILLUM :
IDS_SEL_BY_COLOR));</b>\n\n
<b>}</b>\n\n
Finally, don't forget to release the swatch: ReleaseIColorSwatch (iCol);\n\n
*/
class IColorSwatchRenamer : public BaseInterface {
public:
// The method we needed the interface for:
/*! \remarks Sets the name of the color swatch, and of any associated
color picker dialog. */
virtual void SetName (MCHAR *name) { }
// Interface ID
Interface_ID GetID() {return COLOR_SWATCH_RENAMER_INTERFACE_51;}
};
//---------------------------------------------------------------------------//
// DragAndDrop Window
#define DADWINDOWCLASS _M("DragDropWindow")
typedef LRESULT CALLBACK WindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
/*! \sa Class ICustomControl,
Class DADMgr,
<a href="ms-its:3dsmaxsdk.chm::/ui_custom_controls.html">Custom Controls</a>.\n\n
\par Description:
This is a new type of custom control used to provide drag and drop to and from
things other than Custom Buttons. An example of an item that uses this control
is a sample sphere window in the Material Editor.\n\n
To initialize the pointer to the control call: */
class IDADWindow : public ICustomControl {
public:
// Installing this makes it do drag and drop.
/*! \remarks Set the drag and drop manager for this control.
\par Parameters:
<b>DADMgr *dadMgr</b>\n\n
A pointer to the drag and drop manager for this control. */
virtual void SetDADMgr( DADMgr *dadMgr)=0;
/*! \remarks Returns a pointer to the drag and drop manager for this
control. */
virtual DADMgr *GetDADMgr()=0;
// Install Window proc called to do all the normal things after
// drag/and/drop processing is done.
/*! \remarks This method establishes a window proc that is called to
handle all the normal processing after the drag and drop processing is
done.
\par Parameters:
<b>WindowProc *proc</b>\n\n
The window proc. Note the following typedef:\n\n
<b>typedef LRESULT CALLBACK WindowProc(HWND hwnd, UINT message, WPARAM
wParam, LPARAM lParam);</b>\n\n
<b>#define SLIDERWINDOWCLASS _T("SliderControl")</b>\n\n
<b>// LOWORD(wParam) = ctrlID,</b>\n\n
<b>// HIWORD(wParam) = TRUE if user is dragging the slider
interactively.</b>\n\n
<b>// lParam = pointer to ISliderControl</b>\n\n
<b>#define CC_SLIDER_CHANGE WM_USER + 611</b>\n\n
<b>// LOWORD(wParam) = ctrlID,</b>\n\n
<b>// lParam = pointer to ISliderControl</b>\n\n
<b>#define CC_SLIDER_BUTTONDOWN WM_USER + 612</b>\n\n
<b>// LOWORD(wParam) = ctrlID,</b>\n\n
<b>// HIWORD(wParam) = FALSE if user cancelled - TRUE otherwise</b>\n\n
<b>// lParam = pointer to ISliderControl</b>\n\n
<b>#define CC_SLIDER_BUTTONUP WM_USER + 613</b> */
virtual void SetWindowProc( WindowProc *proc)=0;
};
/*! */
CoreExport IDADWindow *GetIDADWindow( HWND hWnd);
/*! All methods of this class are implemented by the system. */
CoreExport void ReleaseIDADWindow( IDADWindow *idw );
//------------------------------------------------------------------------
// Window thumb tack
//! \brief This function installs a thumb tack in the title bar of a window which forces the window to the top.
/*! The window class for the window should have 4 extra bytes in the window structure for SetWindowLongPtr(). */
CoreExport void InstallThumbTack(HWND hwnd);
CoreExport void RemoveThumbTack(HWND hwnd);
/*! \brief Handy routines for setting up Integer Spinners.
This global function (not part of class ISpinnerControl) is used
for setting up Spinners. It performs the equivalent of GetISpinner(), SetLimits(), SetValue(), and
LinkToEdit().
WARNING: To prevent a Memory Leak, be sure to call ReleaseISpinner on the pointer that this function returns.
\param HWND hwnd - The handle of the dialog box in which the spinner appears.
\param int idSpin - The ID of the spinner.
\param int idEdit - The ID of the edit control.
\param int min - The minimum allowable value.
\param int max - The maximum allowable value.
\param int val - The initial value for the spinner.
\return - A pointer to the spinner control. */
CoreExport ISpinnerControl *SetupIntSpinner(HWND hwnd, int idSpin, int idEdit, int min, int max, int val);
/*! \brief Handy routines for setting up Floating Point and Universe Spinners.
This global function (not part of class ISpinnerControl) is used for setting up
Spinners. Internally it calls the GetISpinner(), SetLimits(), SetValue()
and LinkToEdit() functions.
\param HWND hwnd - The handle of the dialog box in which the spinner appears.
\param int idSpin - The ID of the spinner.
\param int idEdit - The ID of the edit control.
\param float min - The minimum allowable value.
\param float max - The maximum allowable value.
\param float val - The initial value for the spinner.
\param float scale = 0.1f - The initial scale value for the spinner.
\return - A pointer to the spinner control.
\par Sample Code:
Sample code to initialize a spinner / edit control.
\code
ISpinnerControl* spin = GetISpinner(GetDlgItem(hDlg, IDC_SPIN_SPINNER));
spin->SetLimits(0.0f, 100.0f, FALSE);
spin->SetValue(100.0f, FALSE);
spin->LinkToEdit(GetDlgItem(hDlg, IDC_SPIN_EDIT), EDITTYPE_FLOAT);
ReleaseISpinner(spin);
\endcode
The above code could be replaced with the following simplified code:
\code
ISpinnerControl* spin = SetupFloatSpinner(hDlg, IDC_SPIN_SPINNER, IDC_SPIN_EDIT, 0.0f, 100.0f, 100.0f);
ReleaseISpinner(spin);
\endcode */
CoreExport ISpinnerControl *SetupFloatSpinner(HWND hwnd, int idSpin, int idEdit, float min, float max, float val, float scale = 0.1f);
CoreExport ISpinnerControl *SetupUniverseSpinner(HWND hwnd, int idSpin, int idEdit, float min, float max, float val, float scale = 0.1f);
// Controls whether or not spinners send notifications while the user adjusts them with the mouse
/*! \remarks This function controls whether or not spinners send <b>CC_SPINNER_CHANGE</b>
notifications while the user adjusts them with the mouse.
\par Parameters:
<b>BOOL onOff</b>\n\n
TRUE to turn on; FALSE to turn off. */
CoreExport void SetSpinDragNotify(BOOL onOff);
/*! \remarks Returns TRUE if <b>CC_SPINNER_CHANGE</b> notifications are sent by spinners
while the user adjusts them with the mouse; FALSE if they are not sent. */
CoreExport BOOL GetSpinDragNotify();
//---------------------------------------------------------------------------
//
CoreExport void DisableAccelerators();
CoreExport void EnableAccelerators();
CoreExport BOOL AcceleratorsEnabled();
//! \brief Explicitly marks the scene as changed
/*! Some operations/commands are not undoable, but they do change the scene and as a result
the scene should be saved or back-ed up after an autosave time interval elapsed.
Such operations/commands must set the "save-required" and "auto-backup-required"
flags explicitly by calling this method. Plugins should essentially never set the
"auto-backup_required" flag to false.
\param requireSave - If TRUE the scene will be considered changed since it's been
saved last time; otherwise the scene is considered changed if at least one undoable
operation has occurred since it was last saved
\param requireAutoBackupSave - If TRUE the scene will be considered as requiring
to be backed-up; otherwise the scene is considered as requiring a backup if at
least one undoable operation has occurred since it was last back-ed up */
CoreExport void SetSaveRequiredFlag(BOOL requireSave = TRUE, BOOL requireAutoBackupSave = TRUE);
//! \brief Retrieves the internal save required flag
/*! \see void SetSaveRequiredFlag(BOOL requireSave = TRUE, BOOL requireAutoBackupSave = TRUE)
\return The value of the "save-required" flag as last set by the SetSaveRequiredFlag method. */
CoreExport BOOL GetSaveRequiredFlag();
//! \brief This tells if the scene needs to be saved
/*! Whenever an undoable operation is executed (by the user or otherwise), or
SetSaveRequiredFlag is called with TRUE as its first parameter, the scene is
considered different than its most recently saved version.
\return TRUE if the scene needs to be saved; FALSE otherwise. */
CoreExport BOOL IsSaveRequired();
//! \brief This tells if the current scene needs to be backed up.
/*! An autosave is required when (a) something has changed in the scene (a save is
required) and (b) no autosave has been performed since the last scene change.
The second condition (b) guarantees that the scene is backed up only once when
a 3ds Max session is left unattended for a time that spans several autosave
(autobackup) time intervals.
\return TRUE if an autosave should occur; FALSE otherwise. */
CoreExport BOOL IsAutoSaveRequired();
#endif // __CUSTCONT__
| [
"[email protected]"
]
| [
[
[
1,
4433
]
]
]
|
6d81dae79ccafd52e085199a8c680c82eef0c6b9 | 102d8810abb4d1c8aecb454304ec564030bf2f64 | /TP3/Tanque/Tanque/Tanque/XMLParser.h | 7005c22a8b520db26856f1a4b5def457502ab97f | []
| no_license | jfacorro/tp-taller-prog-1-fiuba | 2742d775b917cc6df28188ecc1f671d812017a0a | a1c95914c3be6b1de56d828ea9ff03e982560526 | refs/heads/master | 2016-09-14T04:32:49.047792 | 2008-07-15T20:17:27 | 2008-07-15T20:17:27 | 56,912,077 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 808 | h | #include <stdio.h>
#include <fstream>
#include "ArrayList.h"
#include "Tag.h"
#ifndef XMLParser_h
#define XMLParser_h
enum ParserResult
{
PARSER_OK ,
PARSER_FILE_NOT_FOUND,
PARSER_CLOSING_TAG_MISSING
};
class XMLParser
{
private:
int stringIndex;
int stringLength;
char * stringXml;
Tag * BuildTree(ArrayList * stringsArr, Tag * parentTag, Tag * currentTag);
char * GetNextText();
char * GetNextTag();
public:
char * getSource() { return this->stringXml; };
void setSource(char * sourceLocal) { this->stringXml = sourceLocal; };
XMLParser()
{
this->stringIndex = 0;
this->stringLength = 0;
};
Tag * ParseFile(char * filename);
Tag * Parse(char * stringXml);
static bool ValidateName(char * nameStr);
};
#endif | [
"juan.facorro@6dff32cf-8f48-0410-9a2e-7b8b34aa6dfb"
]
| [
[
[
1,
44
]
]
]
|
badd953642822aadb6648292f3e35464df9ac215 | 629e4fdc23cb90c0144457e994d1cbb7c6ab8a93 | /lib/managers/assetmanager.cpp | b89b3af80c134d2ebb553e7b424d6618779d4e08 | []
| no_license | akin666/ice | 4ed846b83bcdbd341b286cd36d1ef5b8dc3c0bf2 | 7cfd26a246f13675e3057ff226c17d95a958d465 | refs/heads/master | 2022-11-06T23:51:57.273730 | 2011-12-06T22:32:53 | 2011-12-06T22:32:53 | 276,095,011 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 320 | cpp | /*
* assetmanager.cpp
*
* Created on: 19.11.2011
* Author: akin
*/
#include "assetmanager.h"
namespace ice
{
AssetManager::AssetManager()
{
// TODO Auto-generated constructor stub
}
AssetManager::~AssetManager()
{
// TODO Auto-generated destructor stub
}
} /* namespace ice */
| [
"akin@localhost"
]
| [
[
[
1,
24
]
]
]
|
94986ca3f3c859ef1d853848692f369da4aefbc5 | df238aa31eb8c74e2c208188109813272472beec | /BCGInclude/BCGPGanttGrid.h | 20ef3e43f3f5a600ae38a49f37d61fbe88f09887 | []
| no_license | myme5261314/plugin-system | d3166f36972c73f74768faae00ac9b6e0d58d862 | be490acba46c7f0d561adc373acd840201c0570c | refs/heads/master | 2020-03-29T20:00:01.155206 | 2011-06-27T15:23:30 | 2011-06-27T15:23:30 | 39,724,191 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,725 | h | //*******************************************************************************
// COPYRIGHT NOTES
// ---------------
// This is a part of BCGControlBar Library Professional Edition
// Copyright (C) 1998-2008 BCGSoft Ltd.
// All rights reserved.
//
// This source code can be used, distributed or modified
// only under terms and conditions
// of the accompanying license agreement.
//*******************************************************************************
//
// BCGPGanttGrid.h: interface for the CBCGPGanttGrid class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_BCGPGANTTGRID_H__085103BE_34FD_47CC_9F72_363D71F1F974__INCLUDED_)
#define AFX_BCGPGANTTGRID_H__085103BE_34FD_47CC_9F72_363D71F1F974__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "BCGPGridCtrl.h"
class CBCGPGanttControl;
class BCGCBPRODLLEXPORT CBCGPGanttGrid : public CBCGPGridCtrl
{
friend class CBCGPGanttControl;
friend class CBCGPGanttGridRow;
public:
CBCGPGanttGrid();
virtual ~CBCGPGanttGrid();
public:
void SetVerticalSizes (UINT nHeaderHeight, UINT nRowHeight);
void GetVerticalSizes (UINT* pHeaderHeight, UINT* pRowHeight) const;
virtual void AdjustLayout ();
protected:
virtual CBCGPGanttControl* GetGanttControlNotify () const;
virtual void OnItemChanged (CBCGPGridItem* pItem, int nRow, int nColumn);
virtual void SetRowHeight ();
virtual CRect OnGetHeaderRect (CDC* pDC, const CRect& rectDraw);
virtual void OnUpdateVScrollPos (int nVOffset, int nPrevVOffset);
virtual void OnExpandGroup (CBCGPGridRow* pRow, BOOL bExpand);
int GetVScrollPos () const
{
return m_nVertScrollOffset;
}
void SetVScrollPos (int nNewVertOffset)
{
int nOld = m_nVertScrollOffset;
CBCGPGridCtrl::SetScrollPos (SB_VERT, nNewVertOffset, FALSE);
CBCGPGridCtrl::OnVScroll (SB_THUMBPOSITION, nNewVertOffset, NULL);
OnUpdateVScrollPos (nNewVertOffset, nOld);
}
// Overrides
public:
virtual CBCGPGridRow* CreateRow ();
virtual CBCGPGridRow* CreateRow (CString strName);
virtual CBCGPGridRow* CreateRow (int nColumns)
{
return CBCGPGridCtrl::CreateRow (nColumns);
}
// Generated message map functions
protected:
//{{AFX_MSG(CBCGPGanttGrid)
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
DECLARE_DYNCREATE (CBCGPGanttGrid);
protected:
UINT m_nHeaderHeight; // desired header height
};
/////////////////////////////////////////////////////////////////////////////
// CBCGPGridDateTimeItem object
class BCGCBPRODLLEXPORT CBCGPGridPercentItem : public CBCGPGridItem
{
DECLARE_DYNCREATE(CBCGPGridPercentItem)
// Construction
protected:
CBCGPGridPercentItem ();
public:
CBCGPGridPercentItem (double value, DWORD_PTR dwData = 0);
virtual ~CBCGPGridPercentItem();
void SetMaxValue (double dValue);
double GetMaxValue () const
{
return max (0.0, m_dMaxValue);
}
void SetPrecision (int nDigitsAfterFloatingPoint);
int GetPrecision () const
{
return max (0, min (8, m_nPrecision));
}
// Overrides
public:
virtual BOOL OnUpdateValue ();
virtual CString FormatItem ();
protected:
double m_dMaxValue; // Maximal available value. Default is 1.0 (100%).
int m_nPrecision; // From 0 - "x %" (integer part only) to 8 "x.xxxxxxxx %"
};
#endif // !defined(AFX_BCGPGANTTGRID_H__085103BE_34FD_47CC_9F72_363D71F1F974__INCLUDED_)
| [
"myme5261314@ec588229-7da7-b333-41f6-0e1ebc3afda5"
]
| [
[
[
1,
131
]
]
]
|
cbe0a1d96a4ce6ddf293bb36e7fa7b121932f774 | c70941413b8f7bf90173533115c148411c868bad | /core/include/vtxSingleton.h | 27ba058b264a56249cbc87e56e843499c472d92b | []
| no_license | cnsuhao/vektrix | ac6e028dca066aad4f942b8d9eb73665853fbbbe | 9b8c5fa7119ff7f3dc80fb05b7cdba335cf02c1a | refs/heads/master | 2021-06-23T11:28:34.907098 | 2011-03-27T17:39:37 | 2011-03-27T17:39:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,757 | h | /*
-----------------------------------------------------------------------------
This source file is part of "vektrix"
(the rich media and vector graphics rendering library)
For the latest info, see http://www.fuse-software.com/
Copyright (c) 2009-2010 Fuse-Software (tm)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#ifndef __vtxSingleton_H__
#define __vtxSingleton_H__
#include "vtxPrerequisites.h"
namespace vtx
{
//-----------------------------------------------------------------------
/** A template for globally accessible singleton classes */
template <typename T>
class SingletonBase
{
public:
SingletonBase()
{
VTX_DEBUG_ASSERT(!sInstance, "");
sInstance = (T*)this;
}
virtual ~SingletonBase()
{
VTX_DEBUG_ASSERT(sInstance, "");
sInstance = 0;
}
protected:
static T* sInstance;
};
//-----------------------------------------------------------------------
/** A template for globally accessible singleton classes */
template <typename T>
class Singleton : public SingletonBase<T>
{
public:
/** Get the unique instance of this class */
static T* getSingletonPtr()
{
return sInstance;
}
};
//-----------------------------------------------------------------------
/** A template for globally accessible singleton classes */
template <typename T>
class AutoSingleton : public SingletonBase<T>
{
public:
/** Get the unique instance of this class */
static T* getSingletonPtr()
{
if(!sInstance)
sInstance = new T;
return sInstance;
}
};
//-----------------------------------------------------------------------
}
#endif
| [
"stonecold_@9773a11d-1121-4470-82d2-da89bd4a628a",
"fixxxeruk@9773a11d-1121-4470-82d2-da89bd4a628a"
]
| [
[
[
1,
31
],
[
33,
87
]
],
[
[
32,
32
]
]
]
|
1e16dd415c5de24773413bdf392bb6f96247c4ed | 1cc5720e245ca0d8083b0f12806a5c8b13b5cf98 | /v100/ok/10077/p.cpp | bc617d727e693af607017f25d83dd0af1f4cc511 | []
| no_license | Emerson21/uva-problems | 399d82d93b563e3018921eaff12ca545415fd782 | 3079bdd1cd17087cf54b08c60e2d52dbd0118556 | refs/heads/master | 2021-01-18T09:12:23.069387 | 2010-12-15T00:38:34 | 2010-12-15T00:38:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 731 | cpp | #include <iostream>
#include <string>
using namespace std;
int cit;
class Conexao {
public:
int de, para;
int horaSai, horaChega;
};
class Cidade{
public:
string n;
Conexao *c[10000];
};
Cidade cidades[101];
void start() {
int i;
cin >> cit;
for(i=0;i!=cit;i++) {
cin >> cidades[i].n;
cout << cidades[i].n << endl;
}
int trens, con, nH, hA;
string c, ca;
cin >> trens;
while(trens--) {
cin >> con;
i = 0;
while(con--) {
cin >> nH >> c;
if(i++!=0) {
// adiciona a conexao
}
hA = nH;
ca = c;
}
}
cin >> nH;
string s,f;
cin >> s;
cin >> f;
}
int main() {
int t;
cin >> t;
while(t--) start();
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
60
]
]
]
|
40be16af8e13de17d963f9b8fa6c32a2eaa691c9 | 14a00dfaf0619eb57f1f04bb784edd3126e10658 | /Lab1/ObjIO.cpp | 2c3b24626f03216c9c09d71981b927bc38d80cbf | []
| no_license | SHINOTECH/modanimation | 89f842262b1f552f1044d4aafb3d5a2ce4b587bd | 43d0fde55cf75df9d9a28a7681eddeb77460f97c | refs/heads/master | 2021-01-21T09:34:18.032922 | 2010-04-07T12:23:13 | 2010-04-07T12:23:13 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 5,870 | cpp | /*************************************************************************************************
*
* Modeling and animation (TNM079) 2007
* Code base for lab assignments. Copyright:
* Gunnar Johansson ([email protected])
* Ken Museth ([email protected])
* Michael Bang Nielsen ([email protected])
* Ola Nilsson ([email protected])
* Andreas Söderström ([email protected])
*
*************************************************************************************************/
#include "ObjIO.h"
#include <cassert>
#include <sstream>
#include <string>
#include <iostream>
#include <vector>
#include <windows.h>
bool ObjIO::load(Mesh *mesh, std::istream & is){
//std::cerr << "Reading obj file.\nOutputting any skipped line(s) for reference.\n";
bool success = readHeader(is);
if(!success) { return false; }
success = readData(is);
if(!success) { return false; }
loadData.normals.clear();
loadData.hasNormals = false;
// mesh->clear();
// Build mesh
const unsigned int numTris = loadData.tris.size();
for (unsigned int t = 0; t < numTris; t++){
Vector3<unsigned int>& triangle = loadData.tris[t];
Vector3<float>& v0 = loadData.verts[triangle[0]];
Vector3<float>& v1 = loadData.verts[triangle[1]];
Vector3<float>& v2 = loadData.verts[triangle[2]];
mesh->addTriangle(v0,v1,v2);
}
return true;
}
bool ObjIO::readHeader(std::istream & is){
std::string buf;
// just read to the first line starting with a 'v'
while(is.good() && !is.eof() && is.peek() != 'v'){
getline(is, buf);
//std::cerr << "\"" << buf << "\"\n";
}
if (is.good())
return true;
else
return false;
}
bool ObjIO::readData(std::istream & is){
std::string lineBuf;
int c;
int i=0;
while(!is.eof()){
c = is.peek();
switch (c) {
case 'V':
case 'v':{
std::string startBuf;
is >> startBuf; // get the start of the line
getline(is, lineBuf); // get the rest of the line
if(startBuf == "v"){
loadData.verts.push_back(Vector3<float>(lineBuf));
} else if (startBuf == "vn"){
loadData.hasNormals = true;
loadData.normals.push_back(Vector3<float>(lineBuf));
}
}
break;
case 'F':
case 'f':
{
std::stringstream buf;
is.get(*buf.rdbuf(), '\n'); // read a line into buf
is.get(); // read the not extracted \n
buf << "\n"; // and add it to the string stream
std::string tmp;
buf >> tmp; // get the first f or F (+ whitespace)
// count the number of faces, delimited by whitespace
int count = 0;
while (buf >> tmp){
count++;
}
// reset stream
buf.clear();
buf.seekg(0, std::ios::beg);
// Determine wheter we have a triangle or a quad
if (count == 3){
loadData.tris.push_back(readTri(buf));
}
else if (count == 4){
// Assume quad
Vector3<unsigned int> tri1, tri2;
splitQuad(buf, tri1, tri2, loadData);
loadData.tris.push_back(tri1);
loadData.tris.push_back(tri2);
}
else {
std::cerr << "Encountered polygon with " << count << " faces. Bailing out.\n";
return false;
}
}
break;
default:
// otherwise just skip the row
getline(is, lineBuf);
// output it so we see what we miss :)
// std::cerr << "\"" << lineBuf << "\"\n";
break;
}
i++;
}
return true;
}
Vector3<unsigned int> ObjIO::readTri(std::istream &is){
// This is a simplified version of an obj reader that can't read normal and texture indices
std::string buf, v;
is >> buf;
assert(buf == "f" || buf=="F");
getline(is, v); // read indices
return Vector3<unsigned int>(v)-1; // obj file format is 1-based
}
void ObjIO::splitQuad(std::istream &is, Vector3<unsigned int>& tri1, Vector3<unsigned int>& tri2, const LoadData& data)
{
// This is a simplified version of an obj reader that can't read normal and texture indices
std::string buf;
unsigned int indices[4];
is >> buf;
assert(buf == "f" || buf == "F");
// only supports files where normal indices are identical to vert indices
for (int i = 0; i < 4; i++){
is >> indices[i];
}
// Add code to split the quad here (indices[4] contains the 4 vertex indices)
//Edges
Vector3<float> vec1 = data.verts.at(indices[1]) - data.verts.at(indices[0]);
Vector3<float> vec2 = data.verts.at(indices[2]) - data.verts.at(indices[1]);
Vector3<float> vec3 = data.verts.at(indices[3]) - data.verts.at(indices[2]);
Vector3<float> vec4 = data.verts.at(indices[0]) - data.verts.at(indices[3]);
//Cross sections
Vector3<float> vec5 = data.verts.at(indices[3]) - data.verts.at(indices[1]);
Vector3<float> vec6 = data.verts.at(indices[2]) - data.verts.at(indices[0]);
//take norms
float len1 = vec1.norm();
float len2 = vec1.norm();
float len3 = vec1.norm();
float len4 = vec1.norm();
float len5 = vec1.norm();
float len6 = vec1.norm();
float averageA1 = (len1 + len2 + len6)/3.0f;
float averageA2 = (len3 + len4 + len6)/3.0f;
//Ratio should be always >= 1
float ratioA = max(averageA1,averageA2) / min(averageA1,averageA2);
float averageB1 = (len1 + len5 + len4)/3.0f;
float averageB2 = (len2 + len3 + len5)/3.0f;
//Ratio should be always >= 1
float ratioB = max(averageB1,averageB2) / min(averageB1,averageB2);
//ratio closer to 1 is better: to get equal sized are
if(ratioA<ratioB)
{
tri1.set( indices[0], indices[1], indices[2] );
tri2.set( indices[2], indices[3], indices[0] );
}
else
{
tri1.set( indices[0], indices[1], indices[3] );
tri2.set( indices[1], indices[2], indices[3] );
}
}
| [
"jpjorge@da195381-492e-0410-b4d9-ef7979db4686"
]
| [
[
[
1,
193
]
]
]
|
04438967d4cde4d8ff7cc16f554474656b0d3f4f | 5e6ff9e6e8427078135a7b4d3b194bcbf631e9cd | /EngineSource/dpslim/dpslim/Simulation/Source/CMicroSegment.CPP | d0b3394b6561e053659eba0636b551ea8a8ccd7f | []
| no_license | karakots/dpresurrection | 1a6f3fca00edd24455f1c8ae50764142bb4106e7 | 46725077006571cec1511f31d314ccd7f5a5eeef | refs/heads/master | 2016-09-05T09:26:26.091623 | 2010-02-01T11:24:41 | 2010-02-01T11:24:41 | 32,189,181 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,557 | cpp | // CMicroSegment.cpp
//
// Copyright 1998 Salamander Interactive
//
// Multi-agent customer segment population
// -- the secret sauce!
// Created by Ken Karakotsios 5/21/98
#include "CMicroSegment.h"
#include <stdlib.h>
#include <fstream>
#include <math.h>
#include "SocialNetwork.h"
#include "Consumer.h"
#include "ChoiceModel.h"
#include "DBModel.h"
#include "RepurchaseModel.h"
#include "ProductTree.h"
#include "DBProdAttr.h"
#include "PopObject.h"
#include "Product.h"
#include "Attributes.h"
#include "Function.h"
#include "Pantry.h"
#include "Task.h"
#include "Channel.h"
#include "Display.h"
#include "Media.h"
#include "Coupon.h"
#include "MarketUtility.h"
#include "ExternalFactor.h"
// initialization of static class members
int CMicroSegment::iNumSegments = 0;
int CMicroSegment::iDay = 0;
int CMicroSegment::iMonth = 0;
int CMicroSegment::iYear = 0;
CTime CMicroSegment::Current_Time = CTime();
Bucket* CMicroSegment::myBucket = new Bucket();
int pcn_key::NumProducts = 0;
StochasticLib1 CMicroSegment::iRandomLib = StochasticLib1(0);
// static reference to model information stored in database
ModelRecordset* CMicroSegment::iModelInfo = 0;
// ------------------------------------------------------------------------------
// constructor
// ------------------------------------------------------------------------------
CMicroSegment::CMicroSegment()
{
RandomInitialise(1802,9373);
iNumSegments++;
iProdTree = 0;
iSegmentMap = map< pair<int,int>, SegmentDataAcc* >();
choiceModel = new ChoiceModel();
repurchaseModel = new RepurchaseModel();
iPopulation = new PopObject();
myBucket = new Bucket();
iPopulation->iGroupSize = 10000;
iTotalMessages = 0.0;
iPopulation->iPopScaleFactor = 1.0;
iShareAwarenessWithSibs = false;
iRejectSibs = false;
iUseACVDistribution = true;
iNumDays = 0;
iPriceSensitivity = 5.0;
iMessageSensitivity = 5.0;
iBrandLoyalty = 5.0;
iChannelLoyalty = 5.0;
iDiversityPercent = 20.0;
choiceModel->iChoiceModel = kModel_General; //OK
iCatQuantityPurchasedModifier = 0.0;
iCatShoppingTripFrequencyModifier = 0.0;
iCatTaskRateModifier = 0.0;
iMaxDisplayHits = 0;
iAwarenessDecayRatePreUse = 1;
iAwarenessDecayRatePostUse = 0;
iPersuasionDecayRatePreUse = 1;
iPersuasionDecayRatePostUse = 1;
iDisplayUtility = 0.0;
// new general choice model
choiceModel->iChoiceModel = kModel_General;
choiceModel->iGCMf1_PersuasionScore = kGCMf1_Multiplication;
choiceModel->iGCMf2_PersuasionValComp = kGCMf2_Absolute;
choiceModel->iGCMf3_PersuasionContrib = kGCMf3_Addition;
choiceModel->iGCMf4_UtilityScore = kGCMf4_Multiplication;
choiceModel->iGCMf5_CombPartUtilities = kGCMf5_ScaledSumOfProducts;
choiceModel->iGCMf6_PriceContribution = kGCMf6_Addition;
choiceModel->iGCMf7_PriceScore = kGCMf7_Multiplication;
choiceModel->iGCMf8_PriceValueSource = kGCMf8_PricePerUse;
choiceModel->iGCM_referencePrice = 0.0;
choiceModel->iGCMf9_ChoiceProbability = kGCMf9_ScaledLogit;
choiceModel->iGCMf10_InertiaModel = kGCMf10_SameBrand;
choiceModel->iGCMf11_ErrorTerm = kGCMf11_None;
choiceModel->iGCM_ErrorTermUserValue = 0.0;
iHavePrereqs = false;
socialNetworks = 0;
iFunctions = vector< Function* >();
iBinFunctions = vector< int >();
product_id_map = ID_Index_map();
channel_id_map = ID_Index_map();
iChannels = Cn_container();
iProducts = Pn_container();
iSegmentPointers = Seg_container();
iProductsAvailable = Pcn_container();
iProductAttributes = Pan_container();
iAttributePreferences = Can_container();
iAttributes = An_container();
iFunctions.push_back(new StepFunction(10,20,-1000000));
iBinFunctions.push_back(0);
}
Index CMicroSegment::ProdIndex(ID id)
{
return product_id_map[id];
}
Index CMicroSegment::ChanIndex(ID id)
{
return channel_id_map[id];
}
Pcn CMicroSegment::GetPcn(Pcn_iter iter)
{
return Pcn((*iter)->iProductIndex, (*iter)->iChannelIndex);
}
void CMicroSegment::Initialize()
{
reset_products();
reset_attributes();
create_consumer_population();
}
void CMicroSegment::Reset()
{
reset_products();
reset_attributes();
reset_population_and_context();
clean_up();
initial_condition_processing();
}
// ------------------------------------------------------------------------------
//
// ------------------------------------------------------------------------------
void CMicroSegment::create_consumer_population()
{
iPopulation->CreatePopulaionCore(false, choiceModel->iChoiceModel, this,
(int)iProductsAvailable.size(), (int)iProducts.size(), (int)iAttributePreferences.size(), 0.0, 0,
repurchaseModel->type); // OK
reset_population_and_context(); // 4/30/02
}
// ------------------------------------------------------------------------------
//
// ------------------------------------------------------------------------------
void CMicroSegment::reset_population_and_context()
{
iNeedToCalcAttrScores = true;
iCatQuantityPurchasedModifier = 0.0;
iCatShoppingTripFrequencyModifier = 0.0;
iCatTaskRateModifier = 0.0;
iTotalMessages = 0.0;
reset_new_population();
if(this->iModelInfo->using_checkpoint)
{
// Convert a TCHAR string to a LPCSTR
CT2CA pszConvertedAnsiString(this->iModelInfo->checkpoint_file);
// construct a std::string using the LPCSTR input
std::string strStd (pszConvertedAnsiString);
string file = "checkpoints\\";
file += strStd;
file += "\\popdata";
CT2CA pszConvertedAnsiString2(iNameString);
strStd = std::string(pszConvertedAnsiString2);
file += strStd;
if(!this->iPopulation->ReadFromFile(file))
{
//static string errorString("Check Point Data Invalid");
//iCtr->DBSetString(0,0,0, &errorString, kCntr_SimStatus);
//WriteToSessionLog(kWarn_CheckPointInvalid, -1, -1, 0);
}
}
}
// ------------------------------------------------------------------------------
//
// ------------------------------------------------------------------------------
void CMicroSegment::reset_new_population()
{
Consumer* aConsumer;
// set some basic state
iPopulation->ResetPersuasion(); // OK
iPopulation->ResetAwareness();
iPopulation->ResetProductTries();
iPopulation->ResetProdsEverBought();
double avg_size = 0.0;
double num_pcn = 0.0;
Index pn;
Pcn pcn;
ProductTree::List* leafs = ProductTree::theTree->LeafNodes();
for(ProductTree::Iter iter = leafs->begin(); iter != leafs->end(); ++iter)
{
pn = *iter;
for(Cn_iter iter = iChannels.begin(); iter < iChannels.end(); ++iter)
{
pcn = Pcn(pn, (*iter)->iChannelIndex);
avg_size += iProductsAvailable[pcn]->iSize;
num_pcn++;
}
}
avg_size = avg_size / num_pcn;
for (int i=0; i < iPopulation->iConsumerList.size(); i++)
{
aConsumer = iPopulation->iConsumerList[i];
aConsumer->iBoughtThisTick = false;
aConsumer->iRecommend = false;
aConsumer->iProductLastBought = kNoProductBought;
aConsumer->iPreferredChannel = kNoChannel;
aConsumer->iRepurchaseProb = repurchaseModel->Ticks(iDiversityPercent);
//Pantry Model Parameters
if(aConsumer->iTasks[0] != 0)
{
delete aConsumer->iTasks[0];
}
PantryTask* ptask = new PantryTask(1);
double rate = aConsumer->iRepurchaseProb*repurchaseModel->iAverageMaxUnits*avg_size;
ptask->SetRate(0, rate);
aConsumer->iTasks[0] = ptask;
//double consume = -log(RandomUniform())*(1/aConsumer->iShoppingChance)*rate;
double days = 0;
while(!WillDo0to1(aConsumer->iRepurchaseProb))
{
days++;
}
aConsumer->iDaysSinceLastShopping = days;
aConsumer->pantry->SetBin(0,20-RandomUniform()*avg_size);
aConsumer->pantry->SetActivationEnergy(0.0);
aConsumer->iShoppingChance = aConsumer->iRepurchaseProb;
aConsumer->iNBDscale = repurchaseModel->NBDScale();
}
}
// ------------------------------------------------------------------------------
// destructor
// ------------------------------------------------------------------------------
CMicroSegment::~CMicroSegment()
{
iPopulation->DestroyConsumerPopulation();
delete iPopulation;
iNumSegments--;
for (Pn_iter citer = iProducts.begin(); citer != iProducts.end(); citer++)
{
(*citer)->iPrerequisiteNum.clear();
(*citer)->iInCompatibleNum.clear();
}
for(Pcn_iter iter = iProductsAvailable.begin(); iter != iProductsAvailable.end(); ++iter)
{
(*iter)->iMarketUtility.clear();
}
for(Pan_container::iterator iter = iProductAttributes.begin(); iter != iProductAttributes.end(); ++iter)
{
iter->second->clear();
delete iter->second;
}
iProducts.clear();
iProductsAvailable.clear();
iChannels.clear();
iFunctions.clear();
iBinFunctions.clear();
iTasks.clear();
iSegmentNames.clear();
iProductAttributes.clear();
iAttributePreferences.clear();
iAttributes.clear();
iMassMedia.clear();
iCoupons.clear();
iExternalFactor.clear();
product_id_map.clear();
channel_id_map.clear();
iSegmentNames.clear();
iSegmentPointers.clear();
if (socialNetworks != 0)
{
vector<SocialNetwork*>::iterator ptr;
for (ptr = socialNetworks->begin(); ptr != socialNetworks->end(); ++ptr)
{
SocialNetwork* network = *ptr;
delete network;
}
delete socialNetworks;
}
}
// ------------------------------------------------------------------------------
// Pick some consumers to give samples to
// ------------------------------------------------------------------------------
void CMicroSegment::distribute_samples(int numSamplesThisTick, Pcn pcn, double sizeOfSample,
double persuasion)
{
}
void CMicroSegment::process_coupons()
{
for(C_iter iter = iCoupons.begin(); iter != iCoupons.end(); ++iter)
{
Coupon* coupon = iter->second;
//Compute number of redemptions
double redemption = coupon->GetRedemption();
double reach = coupon->GetReach();
double impressions = redemption * reach * iPopulation->iConsumerList.size();
//Redemptions ar front loaded so a scaling factor is used
CTimeSpan current = coupon->GetEndDate() - Current_Time;
double scale_factor = 2.0 * ((double)current.GetDays() / (double) coupon->GetSpan());
double num_impressions = (impressions * scale_factor)/((double) coupon->GetSpan());
double remainder = num_impressions - (int)num_impressions;
if(WillDo0to1(remainder))
{
++num_impressions;
}
redeem_coupons(num_impressions, coupon);
}
}
// ------------------------------------------------------------------------------
// Coupons are currently a hack and need to fixed...this code is gross beware...
// ------------------------------------------------------------------------------
void CMicroSegment::redeem_coupons(int numRedemptionsThisTick, Coupon* coupon)
{
int numRedemptions = 0;
int aRandomPerson;
Consumer* aGuy;
int bound;
int rejectedProduct;
int isBOGO = false;
//iProductsAvailable[prodChanNum].iNumCouponsToBeRedeemed += numRedemptionsThisTick;
bound = (int)iPopulation->iConsumerList.size();
//isBOGO = (iAdSchedule[couponIndex].iAdvertType == kAdvertType_BOGO);
// If product is eliminated by this segment, then throw the coupons away
int oneProd = 0;
Pcn pcn = Pcn(ProdIndex(coupon->GetProduct()), ChanIndex(coupon->GetChannel()));
myBucket->Reset(bound);
//maxTries = 8 * bound; doesn't make a significant difference in APDO scenario
while (!myBucket->Empty() && (numRedemptions < numRedemptionsThisTick))
{
// Pick a consumer at random
aRandomPerson = myBucket->Draw();
aGuy = iPopulation->iConsumerList[aRandomPerson];
//if(!aGuy->AlreadyHasCoupon(couponIndex))
{
rejectedProduct = true;
rejectedProduct = aGuy->ConsumerTriedAndRejectedProduct(pcn.pn);
rejected_by_channel_or_durable(&rejectedProduct, aGuy, coupon, pcn, true);
if (!rejectedProduct)
{
make_coupon_redeemer(aGuy, coupon, coupon->GetPersuasion(), isBOGO, pcn);
numRedemptions++; // we want to have neg people not redeem coupons
}
}
}
}
// ------------------------------------------------------------------------------
// KMK 1/10/05 make sure that any durable/refill constraints are met
// NULL for aGuy will skip channel check
// ------------------------------------------------------------------------------
void CMicroSegment::rejected_by_channel_or_durable(int *rejectedProduct, Consumer* aGuy, Coupon* coupon, Pcn pcn, int checkChannel)
{
if (!(*rejectedProduct))
{
return;
}
if(iProdTree->IsLeaf(pcn.pn))
{
*rejectedProduct = is_rejected_by_channel_or_durable(coupon, aGuy, pcn, checkChannel);
}
else
{
int rejected = false;
ProductTree::LeafNodeList leafs(pcn.pn);
ProductTree::Iter iter;
for(iter = leafs.begin(); iter != leafs.end(); ++iter)
{
Pcn lpcn = Pcn(*iter,pcn.cn);
rejected = is_rejected_by_channel_or_durable(coupon, aGuy, lpcn, checkChannel);
if(!rejected)
{
*rejectedProduct = rejected;
return;
}
}
*rejectedProduct = rejected;
return;
}
}
int CMicroSegment::is_rejected_by_channel_or_durable(Coupon* coupon, Consumer* aGuy, Pcn pcn, int checkChannel)
{
int rejected;
int havePurchasedPrereq;
if (iHavePrereqs && iProducts[pcn.pn]->iHavePrepreqs)
{
havePurchasedPrereq = aGuy->HavePurchasedPrereqProduct(pcn.pn);
}
else
{
havePurchasedPrereq = true;
}
rejected = !havePurchasedPrereq;
if (!rejected && checkChannel != 0)
{
//if the consumer has a preferred channel, and the coupon doesn't match then reject it...
if(aGuy->iPreferredChannel != kNoChannel && coupon->GetChannel() != -1 && pcn.cn != aGuy->iPreferredChannel)
{
return true;
}
}
return rejected;
}
// ------------------------------------------------------------------------------
//
// ------------------------------------------------------------------------------
void CMicroSegment::make_coupon_redeemer(Consumer* aGuy, Coupon* coupon, double couponPersuasion, int isBOGO, Pcn pcn)
{
if(coupon->GetChannel() == -1)
{
aGuy->ChooseAChannel();
pcn.cn = aGuy->iPreferredChannel;
}
iProductsAvailable[pcn]->iNumCouponsToBeRedeemed += 1;
//Perform purchase using 2.3 method to determine num_units bought
//This will ignore external factors for the time being
double avg_units = repurchaseModel->iAverageMaxUnits;
int num_units = (int)avg_units;
if(RandomUniform() < (avg_units - (double)num_units))
{
num_units++;
}
//BOGO QAD
if (isBOGO)
{
num_units *= 2;
}
aGuy->shopping_cart.clear();
for(int i = 0; i < num_units; i++)
{
aGuy->shopping_cart.push_back(pcn);
aGuy->pantry->AddProduct(pcn);
iProductsAvailable[pcn]->iNumCouponPurchases += 1;
}
iProductsAvailable[pcn]->iNotProcessed = true;
iProductsAvailable[pcn]->iUsingPriceType = kPriceTypeUnpromoted;
aGuy->PurchaseProducts(false, false);
aGuy->shopping_cart.clear();
// fill the consumer with awareness (and possibly persuasion) for the product
aGuy->MakeAware(pcn.pn, couponPersuasion); // OK
}
void CMicroSegment::distribute_media()
{
process_mass_media();
process_coupons();
}
void CMicroSegment::process_mass_media()
{
for(MM_iter iter = iMassMedia.begin(); iter != iMassMedia.end(); ++iter)
{
Media* mass_media = iter->second;
//Conver GRPs to number of impressions
//GRPs is given in a penetraion percentage (eg 50% means half of population will receive impression on average)
double GRPs = mass_media->GRPs(Current_Time);
double impressions = (GRPs / 100.0) * iPopulation->iConsumerList.size();
int num_impressions = (int)impressions;
double remainder = impressions - num_impressions;
if(WillDo0to1(remainder))
{
++num_impressions;
}
broadcast_ad(num_impressions, ProdIndex(mass_media->GetProduct()), mass_media->GetPersuasion(), mass_media->GetAwareness());
}
}
// ------------------------------------------------------------------------------
//
// ------------------------------------------------------------------------------
void CMicroSegment::broadcast_ad(int numImpressionsThisTick, Index pn, double persuasion, double awareness)
{
long aRandomPerson;
int bound;
int impressionsDelivered = 0;
// because we only hold integers for the message count, we can't directly handle
// fractional values. So what we do is randomly Add in a message if the strength
// is less than 1. We'll do this in proportion to the strength. SO a strength
// of .25 means that 1 out of 4 times, we'll actually Add the message in.
//integerPart = (int) messageStrength;
//fractPart = messageStrength - ((double)integerPart);
//shortMessageStrength = fractPart * kADStrengthScaleFactor;
bound = (int)iPopulation->iConsumerList.size();
while (impressionsDelivered < numImpressionsThisTick)
{
// pick people at random
aRandomPerson = LocalRand(bound);
Consumer* consumer = iPopulation->iConsumerList[aRandomPerson];
consumer->ProcessAdAwarenessAndPersuasion(awareness, pn, &impressionsDelivered, persuasion);
}
// log impressions delivered KMK 2/13/04
iProducts[pn]->iGRPsThisTick += impressionsDelivered;
}
void CMicroSegment::external_factors()
{
iCatQuantityPurchasedModifier = 0;
for(EF_iter iter = iExternalFactor.begin(); iter != iExternalFactor.end(); ++iter)
{
iCatQuantityPurchasedModifier += iter->second->GetDemand();
}
}
double CMicroSegment::ScaledOddsOfDisplay(Pcn pcn, MarketUtility* market_utility)
{
// need to adjust awareness for distribution:
// If an item has 50% ACV Dist, and 20% ACV Any Display, then 40% (20/50) of the trips
// when an agent enters a store where the item is stocked the agent can encounter the display
// pre use distribution is used here as it is inndependent of whether or not the agent knows where to find the product
// which is what the post use distribution is supposed to be modeling.
double dist = iProductsAvailable[pcn]->iPreUseDistributionPercent;
double scaledOddsOfDisplayEncounter = market_utility->GetDistribution();
if (dist == 0.0 || scaledOddsOfDisplayEncounter == 0.0)
{
return 0.0;
}
if (dist < 1.0)
{
scaledOddsOfDisplayEncounter /= dist;
if (scaledOddsOfDisplayEncounter > 1.0)
{
scaledOddsOfDisplayEncounter = 1.0;
}
}
return scaledOddsOfDisplayEncounter;
}
double CMicroSegment::AttributeScore(ID attr_id, DynamicAttribute* attribute, int post_use)
{
if(post_use)
{
return iAttributePreferences[attr_id]->GetPostUse()*attribute->PostUse();
}
else
{
return iAttributePreferences[attr_id]->GetPreUse()*attribute->PreUse();
}
}
void CMicroSegment::AddDynamicAttribute(ProductAttribute *attribute)
{
double aware_prob = iAttributes[attribute->GetAttribute()]->GetInitialAwareness();
for(Index i = 0; i < iPopulation->iConsumerList.size(); i++)
{
if(WillDo0to1(aware_prob))
{
iPopulation->iConsumerList[i]->dynamic_attributes[ProdIndex(attribute->GetProduct())][attribute->GetAttribute()] = new DynamicAttribute(attribute, 1);
}
else
{
iPopulation->iConsumerList[i]->dynamic_attributes[ProdIndex(attribute->GetProduct())][attribute->GetAttribute()] = new DynamicAttribute(attribute, 0);
}
}
}
void CMicroSegment::WriteAttributes(ofstream& file)
{
int prod_id;
int attr_id;
//Write Product Attributes
for(Pn_iter p_iter = iProducts.begin(); p_iter != iProducts.end(); ++p_iter)
{
for(An_iter a_iter = iAttributes.begin(); a_iter != iAttributes.end(); ++a_iter)
{
prod_id = (*p_iter)->iProductID;
attr_id = a_iter->second->GetAttribute();
if(a_iter->second->GetType() == 0 && iProductAttributes.find(prod_id) != iProductAttributes.end() && iProductAttributes[prod_id]->find(attr_id) != iProductAttributes[prod_id]->end())
{
file << prod_id << " ";
file << attr_id << " ";
file << (double)(*iProductAttributes[prod_id])[attr_id]->GetPreUse() << " ";
file << (double)(*iProductAttributes[prod_id])[attr_id]->GetPostUse() << " ";
}
}
}
file << (int)(-1) << " ";
//Write consumer preferences
for(Can_iter c_iter = iAttributePreferences.begin(); c_iter != iAttributePreferences.end(); ++c_iter)
{
file << (int)c_iter->first << " ";
file << (double)c_iter->second->GetPreUse() << " ";
file << (double)c_iter->second->GetPostUse() << " ";
file << (double)c_iter->second->GetPriceSensitivity() << " ";
}
file << (int)(-1) << " ";
}
void CMicroSegment::ReadAttributes(ifstream& file)
{
int prod_id;
int attr_id;
double pre_use;
double post_use;
double sensitivity;
//Read Product Attributes
file >> prod_id;
while(prod_id != -1)
{
file >> attr_id;
file >> pre_use;
file >> post_use;
//This is going to be a memory leak...
(*iProductAttributes[prod_id])[attr_id] = new ProductAttribute(pre_use, post_use, attr_id, iSegmentID, prod_id, -1, iModelInfo->start_date, iModelInfo->end_date);
file >> prod_id;
}
//Read Consumer Preferences
file >> attr_id;
while(attr_id != -1)
{
file >> pre_use;
file >> post_use;
file >> sensitivity;
//This also may be a memory leak...
iAttributePreferences[attr_id] = new ConsumerPref(pre_use, post_use, sensitivity, attr_id, iSegmentID, -1, -1, iModelInfo->start_date, iModelInfo->end_date);
file >> attr_id;
}
}
| [
"Isaac.Noble@fd82578e-0ebe-11df-96d9-85c6b80b8d9c"
]
| [
[
[
1,
738
]
]
]
|
eba1f09632435dc4644cfdfa478a2099c66e0bf5 | 5095bbe94f3af8dc3b14a331519cfee887f4c07e | /Shared/Components/Data/TAnalysis_form.cpp | 6421faa5b4fdcd2104291a94eae0719228907e60 | []
| no_license | sativa/apsim_development | efc2b584459b43c89e841abf93830db8d523b07a | a90ffef3b4ed8a7d0cce1c169c65364be6e93797 | refs/heads/master | 2020-12-24T06:53:59.364336 | 2008-09-17T05:31:07 | 2008-09-17T05:31:07 | 64,154,433 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,742 | cpp | //---------------------------------------------------------------------------
#include <general\pch.h>
#include <vcl.h>
#pragma hdrstop
#include "TAnalysis_form.h"
#include "TAnalysis.h"
#include <general\vcl_functions.h>
#include <general\stristr.h>
#include <general\string_functions.h>
#include <assert.h>
using namespace std;
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "TAPSTable_form"
#pragma resource "*.dfm"
TAnalysis_form *Analysis_form;
static const char* YIELD_FIELD_NAME = "yield";
//---------------------------------------------------------------------------
__fastcall TAnalysis_form::TAnalysis_form(TComponent* Owner)
: TAPSTable_form(Owner)
{
weAreExpanding = false;
}
// ------------------------------------------------------------------
// Short description:
// FORM Show event handler - setup all scenarios and variables.
// Changes:
// DPH 3/8/2001
// ------------------------------------------------------------------
void __fastcall TAnalysis_form::FormShow(TObject *Sender)
{
if (Analysis_ptr != NULL)
{
showScenarios();
showVariables();
}
}
// ------------------------------------------------------------------
// Short description:
// FORM Close event handler - save all scenarios and variables.
// Changes:
// DPH 3/8/2001
// ------------------------------------------------------------------
void __fastcall TAnalysis_form::FormClose(TObject *Sender,
TCloseAction &Action)
{
if (ModalResult == mrOk && Analysis_ptr != NULL)
{
saveScenarios();
saveVariables();
}
}
// ------------------------------------------------------------------
// Short description:
// Fill the scenarios GUI control with scenario names.
// Changes:
// DPH 3/8/2001
// ------------------------------------------------------------------
void TAnalysis_form::showScenarios(void)
{
ScenarioTree->Items->Clear();
// Fill scenario select control
vector<string> dataBlockNames;
Analysis_ptr->sourceDataset->getAllDataBlockNames(dataBlockNames);
for (vector<string>::iterator i = dataBlockNames.begin();
i != dataBlockNames.end();
i++)
{
vector<string> pivotNames;
Split_string(*i, ";", pivotNames);
// for each pivot name add to tree. Each pivot name is nested down
// one level from the previous.
TTreeNode* node = NULL;
for (vector<string>::iterator p = pivotNames.begin();
p != pivotNames.end();
p++)
{
AnsiString nodeName = (*p).c_str();
TTreeNode* foundNode = findNodeInTree(node, nodeName);
if (foundNode == NULL)
{
if (node == NULL)
node = ScenarioTree->Items->Add(NULL, nodeName);
else
node = ScenarioTree->Items->AddChild(node, nodeName);
if (Analysis_ptr->sourceDataset->isDataBlockVisible(i->c_str()))
node->ImageIndex = 0;
else
node->ImageIndex = -1;
node->Data = (void*) (i - dataBlockNames.begin());
}
else
node = foundNode;
}
}
expandAllNodes(true);
}
// ------------------------------------------------------------------
// Short description:
// Fill the variable GUI control with variables.
// Changes:
// DPH 3/8/2001
// ------------------------------------------------------------------
void TAnalysis_form::showVariables(void)
{
VariableList->Items->Clear();
TStringList* variables = Analysis_ptr->Field_names_to_analyse->PossibleItems;
for (int i = 0; i < variables->Count; i++)
{
AnsiString name = variables->Strings[i];
if (name != "Simulation")
{
TListItem* item = VariableList->Items->Add();
item->Caption = name;
if (Analysis_ptr->Field_names_to_analyse->Items->IndexOf(name) >= 0)
item->Checked = true;
}
}
if (Analysis_ptr->Field_names_to_analyse->Items->Count == 0)
{
bool oneFound = false;
for (int i = 0; i < VariableList->Items->Count && !oneFound; i++)
{
if (stristr(VariableList->Items->Item[i]->Caption.c_str(), YIELD_FIELD_NAME) != NULL)
{
VariableList->Items->Item[i]->Checked = true;
oneFound = true;
}
}
}
}
// ------------------------------------------------------------------
// Short description:
// Save all scenario selections from scenario control back
// to the analysis table.
// Changes:
// DPH 3/8/2001
// ------------------------------------------------------------------
void TAnalysis_form::saveScenarios(void)
{
// If ModalResult == mrOk then loop through all nodes in tree
// mark each data block name as either visible or invisible
// depending on whether the user 'checked' them or not
if (ModalResult == mrOk)
{
vector<string> dataBlockNames;
Analysis_ptr->sourceDataset->getAllDataBlockNames(dataBlockNames);
TTreeNode* node = ScenarioTree->Items->GetFirstNode();
while (node != NULL)
{
if (node->Count == 0)
Analysis_ptr->sourceDataset->markDataBlockVisible(dataBlockNames[(int)node->Data],
(node->ImageIndex == 0));
node = node->GetNext();
}
}
}
// ------------------------------------------------------------------
// Short description:
// Save all variable selections from variable listbox back
// to the analysis table.
// Changes:
// DPH 3/8/2001
// ------------------------------------------------------------------
void TAnalysis_form::saveVariables(void)
{
Analysis_ptr->Field_names_to_analyse->Items->Clear();
// go find checked item.
for (int i = 0; i < VariableList->Items->Count; i++)
{
if (VariableList->Items->Item[i]->Checked)
Analysis_ptr->Field_names_to_analyse->Items->Add(VariableList->Items->Item[i]->Caption);
}
}
// ------------------------------------------------------------------
// Short description:
// Find a child with the specified text given the specified parent.
// Returns NULL if not found.
// Changes:
// DPH 21/1/98
// ------------------------------------------------------------------
TTreeNode* TAnalysis_form::findNodeInTree (TTreeNode* ParentNode, AnsiString& Name)
{
if (ParentNode != NULL)
{
// loop through all children in tree and try and locate child.
TTreeNode* ChildNode = ParentNode->getFirstChild();
while (ChildNode != NULL)
{
if (ChildNode->Text == Name)
return ChildNode;
ChildNode = ParentNode->GetNextChild(ChildNode);
}
}
else
{
// loop through all root nodes in tree and locate our node
TTreeNode* RootNode = ScenarioTree->Items->GetFirstNode();
while (RootNode != NULL)
{
if (RootNode->Text == Name)
return RootNode;
RootNode = RootNode->getNextSibling();
}
}
return NULL;
}
//---------------------------------------------------------------------------
void TAnalysis_form::expandAllNodes(bool expand)
{
if (expand)
ScenarioTree->FullExpand();
else
ScenarioTree->FullCollapse();
/*
The following code was not traversing the tree correctly - DAH
TTreeNode* node = ScenarioTree->Items->GetFirstNode();
while (node != NULL)
{
node->Expanded = expand;
node = node->getNextSibling();
}
*/
}
//---------------------------------------------------------------------------
/*void __fastcall TAnalysis_form::ScenarioTreeChecked(TObject *Sender,
TTreeNTNode *parent)
{
// fix a bug with TreeNT where the last node when checked becomes invisible.
if (parent == ScenarioTree->Items->Item[ScenarioTree->Items->Count-1])
parent->MakeVisible();
// make all children same as parent wrt. checked checkboes.
TTreeNTNode* child = parent->GetFirstChild();
while (child != NULL)
{
child->CheckState = parent->CheckState;
child = child->GetNextSibling();
}
checkOkButton();
}
*///---------------------------------------------------------------------------
void __fastcall TAnalysis_form::VariableListChange(TObject *Sender,
TListItem *Item, TItemChange Change)
{
static bool inVariableListChange = false;
if (!inVariableListChange)
{
inVariableListChange = true;
if (!multipleVariables && Item->Checked)
{
// make sure all other items are unchecked.
for (int i = 0; i < VariableList->Items->Count; i++)
{
TListItem* thisItem = VariableList->Items->Item[i];
if (thisItem->Caption != Item->Caption)
thisItem->Checked = false;
}
}
checkOkButton();
inVariableListChange = false;
}
}
//---------------------------------------------------------------------------
void TAnalysis_form::checkOkButton(void)
{
// make sure at least one scenario is checked.
bool enabled = false;
TTreeNode* node = ScenarioTree->Items->GetFirstNode();
while (node != NULL && !enabled)
{
while (node != NULL && node->Count > 0)
node = node->GetNext();
assert(node != NULL);
enabled = (node->ImageIndex == 0);
node = node->GetNext();
}
// make sure at least one variable is checked.
if (enabled)
{
enabled = false;
for (int i = 0; i < VariableList->Items->Count && !enabled; i++)
enabled = VariableList->Items->Item[i]->Checked;
}
// if all still ok - then allow derived forms to disable it.
enabled = (allowEnableOkButton() && enabled);
OkButton->Enabled = enabled;
}
//---------------------------------------------------------------------------
void __fastcall TAnalysis_form::ScenarioTreeClick(TObject *Sender)
{
if (weAreExpanding == false && ScenarioTree->Selected != NULL)
{
recursiveToggleImageOnNode(ScenarioTree->Selected);
// make all children the same as the selected node.
TTreeNode* node = ScenarioTree->Selected->getFirstChild();
while (node != NULL)
{
node->ImageIndex = ScenarioTree->Selected->ImageIndex;
node->SelectedIndex = node->ImageIndex;
node = node->getNextSibling();
}
ScenarioTree->Refresh();
checkOkButton();
}
weAreExpanding = false;
}
//---------------------------------------------------------------------------
void TAnalysis_form::toggleImageOnNode(TTreeNode* node)
{
if (node->ImageIndex == -1)
{
node->ImageIndex = 0;
node->SelectedIndex = 0;
}
else
{
node->ImageIndex = -1;
node->SelectedIndex = -1;
}
}
//---------------------------------------------------------------------------
void TAnalysis_form::recursiveToggleImageOnNode(TTreeNode* node)
{
toggleImageOnNode(node);
TTreeNode* next = node->getFirstChild();
while (next != NULL)
{
recursiveToggleImageOnNode(next);
next = next->getNextSibling();
}
}
//---------------------------------------------------------------------------
void __fastcall TAnalysis_form::ExpandLabelClick(TObject *Sender)
{
expandAllNodes(true);
}
//---------------------------------------------------------------------------
void __fastcall TAnalysis_form::CollapseLabelClick(TObject *Sender)
{
expandAllNodes(false);
}
//---------------------------------------------------------------------------
void __fastcall TAnalysis_form::ScenarioTreeExpanding(TObject *Sender,
TTreeNode *Node, bool &AllowExpansion)
{
weAreExpanding = true;
}
//---------------------------------------------------------------------------
void __fastcall TAnalysis_form::ScenarioTreeCollapsing(TObject *Sender,
TTreeNode *Node, bool &AllowCollapse)
{
weAreExpanding = true;
}
//---------------------------------------------------------------------------
| [
"devoilp@8bb03f63-af10-0410-889a-a89e84ef1bc8"
]
| [
[
[
1,
390
]
]
]
|
49b82e50322b56df18fd41e216c525e494cb7bd8 | 48ea48679af39ea42a18b0f84523e857d07b8874 | /itkCorrespondences/itkRotateSphericalParameterizationFilter.h | 32ded593d4e5d3a8a5548dc4c19524fcbe8dba97 | []
| no_license | midas-journal/midas-journal-111 | 4fb4a579d62676063a0e0fabe5e14893b4e1710d | 68d084ceff62b3ff745fc0f7b07fdc9212f7e613 | refs/heads/master | 2020-05-09T23:03:13.970993 | 2011-12-12T20:59:01 | 2011-12-12T20:59:01 | 2,967,366 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 3,255 | h | #ifndef _itkRotateSphericalParameterizationFilter_h
#define _itkRotateSphericalParameterizationFilter_h
#include "itkMeshToMeshFilter.h"
#include "itkSphericalParameterizedTriangleMesh.h"
#include "itkAffineTransform.h"
namespace itk
{
/** \class RotateSphericalParameterizationFilter
* \brief This class rotates the parameterization of an
* itk::SphericalParameterizedTriangleMesh.
* A rotation of the parameterization results in rotating all mapped
* points/landmarks around the mesh.
* The function SetTransform() is used to specify the desired rotation
* via an itk::AffineTransform.
*
* \author Tobias Heimann. Division Medical and Biological Informatics,
German Cancer Research Center, Heidelberg, Germany.
*/
template <class TParameterization>
class RotateSphericalParameterizationFilter : public MeshToMeshFilter<TParameterization, TParameterization>
{
public:
/** Standard class typedefs. */
typedef RotateSphericalParameterizationFilter Self;
typedef MeshToMeshFilter
<TParameterization, TParameterization> Superclass;
typedef SmartPointer<Self> Pointer;
typedef SmartPointer<const Self> ConstPointer;
/** Convenient typedefs. */
typedef TParameterization ParameterizationType;
typedef typename ParameterizationType::Pointer ParameterizationPointer;
typedef typename ParameterizationType::SphericalMapType SphericalMapType;
typedef typename ParameterizationType::PointType PointType;
typedef typename ParameterizationType::VectorType VectorType;
typedef typename PointType::CoordRepType CoordRepType;
typedef AffineTransform<CoordRepType, 3> TransformType;
typedef typename TransformType::Pointer TransformPointer;
/** Method for creation through the object factory. */
itkNewMacro(Self);
/** Run-time type information (and related methods). */
itkTypeMacro(RotateSphericalParameterizationFilter, MeshToMeshFilter);
/** Sets the input parameterization. */
void SetInput( ParameterizationType *input )
{
m_NewInputSet = true;
Superclass::SetInput( input );
}
/** Get/Set the used transformation.
* The set transformation has to be a rotation, i.e. no shearing,
* translation or scaling, otherwise the result will not be valid.
*/
itkSetObjectMacro( Transform, TransformType );
itkGetConstObjectMacro( Transform, TransformType );
protected:
RotateSphericalParameterizationFilter();
~RotateSphericalParameterizationFilter();
void PrintSelf( std::ostream& os, Indent indent ) const;
virtual void GenerateData();
/** Copies the cell information from landmarks to output and initializes the required point containers. */
void InitializeOutput( ParameterizationType *input );
private:
bool m_NewInputSet;
TransformPointer m_Transform;
};
}
#ifndef ITK_MANUAL_INSTANTIATION
#include "itkRotateSphericalParameterizationFilter.txx"
#endif
#endif
| [
"[email protected]"
]
| [
[
[
1,
95
]
]
]
|
2a5e87d097155dce215105c7c70f4b889960ba1d | e580637678397200ed79532cd34ef78983e9aacd | /Grapplon/ParticleEmitter.h | e2f8e5ba1ac3d008573725708aad75ffd1915c71 | []
| no_license | TimToxopeus/grapplon2 | 03520bf6b5feb2c6fcb0c5ddb135abe55d3f344b | 60f0564bdeda7d4c6e1b97148b5d060ab84c8bd5 | refs/heads/master | 2021-01-10T21:11:59.438625 | 2008-07-13T06:49:06 | 2008-07-13T06:49:06 | 41,954,527 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,980 | h | #pragma once
#include "ParticleBehaviour.h"
#include "Particle.h"
#include "Vector.h"
#include <string>
#include <vector>
#include <map>
// Emitter type, dictates direction of particles
enum EmitterType
{
NONE, // Random direction away from center
LINE, // Straight line away from center
ARC // A specific angle subset from the circle around the center
};
// Factory base
struct ParticleFactoryEntry
{
CParticle *m_pParticle;
unsigned int m_iChance;
};
class CParticleEmitter
{
private:
// Non-changing information
EmitterType m_eType;
float m_fTypeParameter;
unsigned int m_iMaxParticles;
unsigned int m_iLifespan;
unsigned int m_iSpawnrate;
float m_fRadius;
std::vector<ParticleFactoryEntry> m_vParticleFactory;
std::map<std::string, CParticleBehaviour> m_vBehaviours;
// Changing information
bool m_bActive;
unsigned int m_iCurParticles;
unsigned int m_iAge;
float m_fParticleSpawnTime;
Vector m_vPosition, m_vDirection;
CParticle *m_pFirst;
public:
CParticleEmitter( EmitterType eType, float fTypeParameter, unsigned int iMaxParticles, unsigned int iLifespan, unsigned int iSpawnrate, float fRadius );
~CParticleEmitter();
void AddToFactory( CParticle *pParticle, unsigned int iChance );
void AddBehaviour( std::string szName, CParticleBehaviour pBehaviour );
CParticleBehaviour GetBehaviour( std::string szName );
void SpawnParticle();
void Update( float fTime );
void Render();
void SetPosition( Vector vPosition ) { m_vPosition = vPosition; }
void SetDirection( Vector vDirection ) { m_vDirection = vDirection; }
Vector GetPosition() { return m_vPosition; }
Vector GetDirection() { return m_vDirection; }
bool IsAlive();
void ChangeLifespan( unsigned int iLifespan, bool resetAge = true );
void ToggleSpawn( bool b1 = false, bool b2 = true ) { if ( b1 ) { m_bActive = b2; } else { m_bActive = !m_bActive; } }
bool IsActive() { return m_bActive; }
};
| [
"[email protected]"
]
| [
[
[
1,
71
]
]
]
|
1562cc002120016381c728f4461908b2000627a4 | 485c5413e1a4769516c549ed7f5cd4e835751187 | /Source/ImacDemo/scenes/parrallaxScene.cpp | e9d2a3b61da199d1f81f0dc44d496f1de41d868a | []
| no_license | FranckLetellier/rvstereogram | 44d0a78c47288ec0d9fc88efac5c34088af88d41 | c494b87ee8ebb00cf806214bc547ecbec9ad0ca0 | refs/heads/master | 2021-05-29T12:00:15.042441 | 2010-03-25T13:06:10 | 2010-03-25T13:06:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,261 | cpp | #include "ParallaxScene.h"
#include "plan.h"
#include "FBO.h"
#include "abstractCamera.h"
//Managers
#include "shaderManager.h"
#include "shader.h"
#include "textureManager.h"
#include "texture2D.h"
#include "meshManager.h"
#include "objMesh.h"
#include "Spline.hpp"
ParallaxScene::ParallaxScene(const std::string& sName, AbstractCamera* pCam):AbstractScene(sName,pCam)
{
}
ParallaxScene::~ParallaxScene()
{
delete[] m_fLightPosition;
}
bool ParallaxScene::init()
{
MeshManager & meshManager = MeshManager::getInstance();
ShaderManager & shaderManager = ShaderManager::getInstance();
m_sNextSceneName = "outdoor";
//Spline
cameraSpline = new Spline("../../data/Spline/parallax_pos.xml");
cameraAimSpline = new Spline("../../data/Spline/parallax_aim.xml");
//Load meshs
meshManager.loadMesh("parallaxRoom.obj");
meshManager.loadMesh("cube.obj");
meshManager.loadMesh("geosphere.obj");
//Set the value of the light
m_fLightPosition = new GLfloat[4];
m_fLightPosition[0] = 7.0;
m_fLightPosition[1] = 3.0;
m_fLightPosition[2] = 0.0;
m_fLightPosition[3] = 1.0;
glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0.9f);
glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, 0.0f);
glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.0f);
fAngle = 0.0f;
fAngleObject = 0.0f;
//Texture loading
TextureManager & textureManager = TextureManager::getInstance();
textureManager.getTexture2D("../../data/face_diffuse.jpg");
textureManager.getTexture2D("../../data/face_NM_height.png");
textureManager.getTexture2D("../../data/rocks_diffuse.jpg");
textureManager.getTexture2D("../../data/rocks_NM_height.tga");
textureManager.getTexture2D("../../data/metalfloor2_diffuse.jpg");
textureManager.getTexture2D("../../data/metalfloor2_NM_height.tga");
textureManager.getTexture2D("../../data/wand_boden_diffuse.jpg");
textureManager.getTexture2D("../../data/wand_boden_normals.jpg");
textureManager.getTexture2D("../../data/door_temple_diffuse.jpg");
textureManager.getTexture2D("../../data/door_temple_normal.jpg");
return true;
}
void ParallaxScene::preRender()
{
}
void ParallaxScene::render()
{
MeshManager & meshManager = MeshManager::getInstance();
ShaderManager & shaderManager = ShaderManager::getInstance();
TextureManager & textureManager = TextureManager::getInstance();
//Clean
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
m_pCam->lookAt();
if (m_bDisplaySpline)
displaySpline();
//------------LightParameter
glLightfv(GL_LIGHT0, GL_SPECULAR, m_fWhiteColor);
glLightfv(GL_LIGHT0, GL_AMBIENT, m_fLightYellow);
glMaterialfv(GL_FRONT, GL_SPECULAR,m_fWhiteColor);
glMaterialfv(GL_FRONT, GL_DIFFUSE,m_fLightYellow);
glMaterialfv(GL_FRONT, GL_AMBIENT,m_fDarkGreyColor);
glMaterialf( GL_FRONT, GL_SHININESS, 5.0f);
glPushMatrix();
glRotatef(fAngle,0.0,1.0,0.0);
glLightfv(GL_LIGHT0, GL_POSITION,m_fLightPosition);
glPopMatrix();
glPushMatrix();
glRotatef(fAngle,0.0,1.0,0.0);
glTranslatef(m_fLightPosition[0],m_fLightPosition[1],m_fLightPosition[2]);
glScalef(0.1,0.1,0.1);
glColor3f(1.0,1.0,1.0);
meshManager.getMesh("geosphere.obj")->Draw();
glPopMatrix();
//-----------End light parameter
//-----the walls
shaderManager.getShader("light")->Activate();
shaderManager.getShader("light")->setUniformi("useTexture",1);
shaderManager.getShader("light")->setUniformi("useShadowMap",0);
shaderManager.getShader("light")->setUniformi("usePOM",1);
shaderManager.getShader("light")->setUniformi("useBump",0);
shaderManager.getShader("light")->setUniformf("heightFactor",0.12f);
shaderManager.getShader("light")->setUniformf("fSize",1.0f);
glEnable(GL_CULL_FACE);
glActiveTexture(GL_TEXTURE0);
textureManager.getTexture2D("../../data/face_diffuse.jpg")->activate();
glActiveTexture(GL_TEXTURE1);
textureManager.getTexture2D("../../data/face_NM_height.png")->activate();
glPushMatrix();
meshManager.getMesh("parallaxRoom.obj")->Draw(1);
meshManager.getMesh("parallaxRoom.obj")->Draw(2);
meshManager.getMesh("parallaxRoom.obj")->Draw(3);
meshManager.getMesh("parallaxRoom.obj")->Draw(4);
meshManager.getMesh("parallaxRoom.obj")->Draw(10);
meshManager.getMesh("parallaxRoom.obj")->Draw(11);
glPopMatrix();
glActiveTexture(GL_TEXTURE0);
textureManager.getTexture2D("../../data/rocks_diffuse.jpg")->activate();
glActiveTexture(GL_TEXTURE1);
textureManager.getTexture2D("../../data/rocks_NM_height.tga")->activate();
//Roof
glPushMatrix();
shaderManager.getShader("light")->setUniformf("fSize",3.0f);
shaderManager.getShader("light")->setUniformf("heightFactor",0.09f);
meshManager.getMesh("parallaxRoom.obj")->Draw(5);
glPopMatrix();
//Objects
glActiveTexture(GL_TEXTURE0);
textureManager.getTexture2D("../../data/metalfloor2_diffuse.jpg")->activate();
glActiveTexture(GL_TEXTURE1);
textureManager.getTexture2D("../../data/metalfloor2_NM_height.tga")->activate();
shaderManager.getShader("light")->setUniformf("fSize",1.0f);
shaderManager.getShader("light")->setUniformf("heightFactor",0.120);
glMaterialf( GL_FRONT, GL_SHININESS, 100.0f);
glPushMatrix();
glTranslatef(-2.348,3.7,-1.52);
glRotatef(fAngleObject,1.0,1.0,0.0);
meshManager.getMesh("cube.obj")->Draw();
glPopMatrix();
shaderManager.getShader("light")->setUniformf("fSize",3.0f);
shaderManager.getShader("light")->setUniformf("heightFactor",0.15f);
glActiveTexture(GL_TEXTURE0);
textureManager.getTexture2D("../../data/skin_diffuse.jpg")->activate();
glActiveTexture(GL_TEXTURE1);
textureManager.getTexture2D("../../data/skin_NM_height.png")->activate();
glPushMatrix();
glTranslatef(4.149,3.8,0.0);
glRotatef(-fAngleObject,0.0,1.0,0.0);
glScalef(0.8,0.8,0.8);
meshManager.getMesh("geosphere.obj")->Draw();
glPopMatrix();
glMaterialf( GL_FRONT, GL_SHININESS, 10.0f);
shaderManager.getShader("light")->setUniformi("usePOM",0);
shaderManager.getShader("light")->setUniformi("useBump",1);
shaderManager.getShader("light")->setUniformf("heightFactor",0.04f);
glActiveTexture(GL_TEXTURE0);
textureManager.getTexture2D("../../data/wand_boden_diffuse.jpg")->activate();
glActiveTexture(GL_TEXTURE1);
textureManager.getTexture2D("../../data/wand_boden_normals.jpg")->activate();
glPushMatrix();
//floor
shaderManager.getShader("light")->setUniformf("fSize",10.0f);
meshManager.getMesh("parallaxRoom.obj")->Draw(0);
shaderManager.getShader("light")->setUniformf("fSize",1.0f);
meshManager.getMesh("parallaxRoom.obj")->Draw(6);
meshManager.getMesh("parallaxRoom.obj")->Draw(7);
//Door
meshManager.getMesh("parallaxRoom.obj")->Draw(8);
glActiveTexture(GL_TEXTURE0);
textureManager.getTexture2D("../../data/door_temple_diffuse.jpg")->activate();
glActiveTexture(GL_TEXTURE1);
textureManager.getTexture2D("../../data/door_temple_normal.jpg")->activate();
meshManager.getMesh("parallaxRoom.obj")->Draw(9);
glPopMatrix();
glActiveTexture(GL_TEXTURE0);
textureManager.getTexture2D("../../data/rocks_diffuse.jpg")->desactivate();
glActiveTexture(GL_TEXTURE1);
textureManager.getTexture2D("../../data/rocks_NM_height.tga")->desactivate();
glActiveTexture(GL_TEXTURE0);
shaderManager.getShader("light")->setUniformi("useBump",0);
shaderManager.getShader("light")->Desactivate();
//glDisable(GL_CULL_FACE);
}
void ParallaxScene::update()
{
AbstractScene::update();
fAngle += 0.6;
fAngleObject += 0.3;
}
bool ParallaxScene::isFinished()
{
if (m_pCam->getCurrentControlPoint() == 9)
{
///going back to outdoor
return true;
}
return false;
}
void ParallaxScene::handleKeyUp(unsigned char c, int x, int y)
{
AbstractScene::handleKeyUp(c,x,y);
}
void ParallaxScene::reset()
{
AbstractScene::reset();
glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0.2f);
glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, 0.0f);
glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.4f);
glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 180.0);
fAngle = 0.0f;
fAngleObject = 0.0f;
m_pCam->setSpeed(0.069);
} | [
"[email protected]"
]
| [
[
[
1,
273
]
]
]
|
b083580e1a85d78284a457502d8490d0c869e9b9 | 41efaed82e413e06f31b65633ed12adce4b7abc2 | /projects/lab6/src/MyQuadric.cpp | 18baf6f857b931362c097c616808820b5f3259a1 | []
| no_license | ivandro/AVT---project | e0494f2e505f76494feb0272d1f41f5d8f117ac5 | ef6fe6ebfe4d01e4eef704fb9f6a919c9cddd97f | refs/heads/master | 2016-09-06T03:45:35.997569 | 2011-10-27T15:00:14 | 2011-10-27T15:00:14 | 2,642,435 | 0 | 2 | null | 2016-04-08T14:24:40 | 2011-10-25T09:47:13 | C | UTF-8 | C++ | false | false | 2,634 | cpp | // This file is an example for CGLib.
//
// CGLib 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.
//
// CGLib 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 CGLib; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
// Copyright 2007 Carlos Martinho
#include "MyQuadric.h"
namespace lab6 {
MyQuadric::MyQuadric(std::string id) : cg::Entity(id) {
}
MyQuadric::~MyQuadric() {
}
inline
void MyQuadric::makeQuadric() {
_quadricObj = gluNewQuadric();
gluQuadricCallback(_quadricObj, GLU_ERROR, 0);
gluQuadricDrawStyle(_quadricObj, GLU_FILL);
gluQuadricOrientation(_quadricObj, GLU_OUTSIDE);
gluQuadricNormals(_quadricObj, GLU_SMOOTH);
gluQuadricTexture(_quadricObj, GL_FALSE);
}
inline
void MyQuadric::makeModel() {
_modelDL = glGenLists(1);
assert(_modelDL != 0);
glNewList(_modelDL,GL_COMPILE);
gluSphere(_quadricObj,1.0,25,20);
glEndList();
}
inline
void MyQuadric::makeMaterial() {
GLfloat mat_emission[] = {0.0f,0.0f,0.0f,1.0f};
GLfloat mat_ambient[] = {0.3f,0.3f,0.1f,1.0f};
GLfloat mat_diffuse[] = {0.9f,0.9f,0.1f,1.0f};
GLfloat mat_specular[] = {0.9f,0.9f,0.9f,1.0f};
GLfloat mat_shininess[] = {100.0f};
_materialDL = glGenLists(1);
assert(_materialDL != 0);
glNewList(_materialDL,GL_COMPILE);
glMaterialfv(GL_FRONT,GL_EMISSION,mat_emission);
glMaterialfv(GL_FRONT,GL_AMBIENT,mat_ambient);
glMaterialfv(GL_FRONT,GL_DIFFUSE,mat_diffuse);
glMaterialfv(GL_FRONT,GL_SPECULAR,mat_specular);
glMaterialfv(GL_FRONT,GL_SHININESS,mat_shininess);
glEndList();
}
void MyQuadric::init() {
_physics.setPosition(3.5,1.0,-3.5);
_physics.setAngularVelocity(20.0);
makeQuadric();
makeModel();
makeMaterial();
}
void MyQuadric::update(unsigned long elapsed_millis) {
double elapsed_seconds = elapsed_millis / (double)1000;
_physics.step(elapsed_seconds);
}
void MyQuadric::draw() {
glPushMatrix();
glCallList(_materialDL);
_physics.applyTransforms();
glCullFace(GL_BACK);
glCallList(_modelDL);
glCullFace(GL_FRONT);
glPopMatrix();
}
} | [
"Moreira@Moreira-PC.(none)"
]
| [
[
[
1,
82
]
]
]
|
8a36869eeb9e55f5c1ffc3dfcea40c2d65b79559 | af260b99d9f045ac4202745a3c7a65ac74a5e53c | /tags/engine/src/core/STLHelper.h | 80f61b99bca8863d510f317a19a3e110d9be105b | []
| no_license | BackupTheBerlios/snap-svn | 560813feabcf5d01f25bc960d474f7e218373da0 | a99b5c64384cc229e8628b22f3cf6a63a70ed46f | refs/heads/master | 2021-01-22T09:43:37.862180 | 2008-02-17T15:50:06 | 2008-02-17T15:50:06 | 40,819,397 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,532 | h | #ifndef _SeedSearcher_STLHelper_h
#define _SeedSearcher_STLHelper_h
#include "core/Defs.h"
#include <vector>
//
// choose between wrapper or standard vector
#define USE_VECTOR_WRAPPER BASE_DEBUG
//
// remove elements from vector, while preserving its capacity
template <class _Seq>
static inline void reserveResize (_Seq& sequence, size_t n, size_t res)
{
sequence.reserve (res);
sequence.resize (n);
debug_mustbe (sequence.capacity () >= res);
}
template <class _Seq>
static inline void reserveResize (_Seq& sequence, size_t n)
{
reserveResize (sequence, n, sequence.size ());
}
//
// remove all elements from vector,
// while preserving its capacity
template <class _Seq>
static inline void reserveClear (_Seq& sequence, size_t res)
{
reserveResize (sequence, 0, res);
}
template <class _Seq>
static inline void reserveClear (_Seq& sequence)
{
reserveClear (sequence, sequence.size ());
}
//
// wrapper for std::vector which checks bounds
template <typename T>
class VectorWrapper : public std::vector <T> {
public:
typedef std::vector <T> Super;
typedef typename Super::const_iterator const_iterator;
typedef typename Super::iterator iterator;
VectorWrapper () {}
VectorWrapper (int size) : Super (size) {}
VectorWrapper (int size, T t) : Super (size,t) {}
VectorWrapper (const_iterator b, const_iterator e) : Super (b, e) {}
VectorWrapper (const Super& o) : Super (o) {
}
T& operator [] (unsigned int i) {
debug_mustbe (i>=0 && i<this->Super::size ());
return Super::operator [] (i);
}
const T& operator [] (unsigned int i) const{
debug_mustbe (i>=0 && i<this->Super::size ());
return Super::operator [] (i);
}
};
//
// create a new vector from iterators
template <class Vector, typename const_iterator>
static Vector* createNewVector (int size, const_iterator b, const_iterator e)
{
Vector* v = new Vector (size);
std::copy (b, e, v->begin ());
return v;
}
#if USE_VECTOR_WRAPPER
# define Vec VectorWrapper
#else
# define Vec std::vector
#endif
template <class Container, class TIterator>
class IteratorWrapperBase {
public:
// the type of the values we are iterating over
typedef typename Container::value_type value_type;
//
// underlining iterator
//Container::iterator;
typedef TIterator iterator;
//
// Copy Ctor & operator =
inline IteratorWrapperBase () : _init (false), _current (), _end () {
_current = _end;
}
inline IteratorWrapperBase (iterator begin, iterator end) : _init (true), _current (begin), _end (end) {
}
inline IteratorWrapperBase (const IteratorWrapperBase& i) : _init (true), _current (i._current), _end (i._end) {
}
inline IteratorWrapperBase& operator = (const IteratorWrapperBase& i) {
_init = i._init;
_current = i._current;
_end = i._end;
return *this;
}
//
// step forward a few more steps
void next (int index) {
//
// advance the begin iterator
std::advance(_current, tmin (index, _end - _current));
//for (; (_current!= _end) && (index > 0) ; --index, ++_current);
}
//
// how many iteration steps maximally allowed
void allowNext (int length) {
iterator temp = _current;
std::advance (temp, tmin (length, _end - _current));
// for (; (temp != _end) && (length > 0) ; --length, ++temp);
_end = temp;
};
//
// iteration methods
inline bool hasNext () const {
return _init && (_current != _end);
}
inline void next () {
debug_mustbe (hasNext ());
++_current;
}
inline const value_type& get () const {
debug_mustbe (hasNext ());
return *_current;
}
inline value_type const& operator * () const {
return *_current;
}
inline iterator getImpl () {
return _current;
}
inline const iterator getImpl () const {
return _current;
}
protected:
bool _init;
iterator _current;
iterator _end;
};
template < class Container,
class Iterator = BOOST_DEDUCED_TYPENAME Container::iterator>
class IteratorWrapper :
public IteratorWrapperBase <Container, typename Container::iterator>
{
public:
typedef IteratorWrapperBase <Container, typename Container::iterator> Base;
//
// needed again because gcc is complaining about typenames...
typedef typename Container::iterator iterator;
typedef typename Container::value_type value_type;
inline IteratorWrapper () {
}
inline IteratorWrapper (iterator begin, iterator end)
: Base (begin, end) {
}
inline IteratorWrapper (const IteratorWrapper& i)
: Base (i) {
}
inline value_type* operator -> () const {
//
// weird syntax needed in case 'iterator' is a class/struct and
// not a pointer
return &(*this->_current);
}
};
template <class Container>
class CIteratorWrapper :
public IteratorWrapperBase <Container, typename Container::const_iterator>
{
public:
typedef IteratorWrapperBase <Container, typename Container::const_iterator> Base;
//
// needed again because gcc is complaining about typenames...
typedef typename Container::const_iterator iterator;
typedef typename Container::value_type value_type;
inline CIteratorWrapper () {
}
inline CIteratorWrapper (iterator begin, iterator end)
: Base (begin, end) {
}
inline CIteratorWrapper (const CIteratorWrapper& i)
: Base (i) {
}
inline value_type const* operator -> () const {
//
// weird syntax needed in case 'iterator' is a class/struct and
// not a pointer
return &(*this->_current);
}
};
template <typename T>
class AbstractIterator {
public:
class Rep {
public:
virtual ~Rep () {
}
virtual bool next () = 0;
virtual bool hasNext () const = 0;
virtual T* get () const = 0;
inline T& operator * () const { return *get (); }
inline T* operator -> () const {return get (); }
};
public:
inline AbstractIterator () : _rep (NULL) {
}
inline AbstractIterator (Rep* in) : _hasNext (in->hasNext ()), _rep (in) {
}
~AbstractIterator () {
delete _rep;
}
inline void next () {
mustbe (_rep);
//
// optimization: it is assumed that
_hasNext = _rep->next ();
}
inline bool hasNext () const {
mustbe (_rep);
return _hasNext;
}
inline T* get () const {
mustbe (_rep);
return _rep->get ();
}
inline T& operator * () const { return *get (); }
inline T* operator -> () const {return get (); }
private:
AbstractIterator& operator = (const AbstractIterator&);
AbstractIterator (const AbstractIterator&);
bool _hasNext;
Rep* _rep;
};
template <typename T>
class CAbstractIterator {
public:
class Rep {
public:
virtual ~Rep () {
}
virtual bool next () = 0;
virtual bool hasNext () const = 0;
virtual const T* get () const = 0;
inline const T& operator * () const { return *get (); }
inline const T* operator -> () const {return get (); }
};
public:
inline CAbstractIterator () : _rep (NULL) {
}
inline CAbstractIterator (Rep* in) : _hasNext (in->hasNext ()), _rep (in) {
}
~CAbstractIterator () {
delete _rep;
}
inline void next () {
mustbe (_rep);
//
// optimization: it is assumed that
_hasNext = _rep->next ();
}
inline bool hasNext () const {
mustbe (_rep);
return _hasNext;
}
inline const T* get () const {
mustbe (_rep);
return _rep->get ();
}
inline const T& operator * () const { return *get (); }
inline const T* operator -> () const {return get (); }
private:
CAbstractIterator& operator = (const CAbstractIterator&);
CAbstractIterator (const CAbstractIterator&);
bool _hasNext;
Rep* _rep;
};
template <class Container>
class Map1stBinder {
public:
typedef typename Container::iterator iterator_type;
typedef typename Container::const_iterator const_iterator_type;
typedef const typename Container::key_type value_type;
class Iterator {
public:
Iterator (iterator_type in) : _it (in) {
}
bool operator == (Iterator o) const{
return _it == o._it;
}
bool operator != (Iterator o) const{
return _it != o._it;
}
void operator ++ () {
_it++;
}
Iterator operator ++ (int) {
return Iterator (_it++);
}
value_type& operator * () const{
return _it->first;
}
iterator_type getImpl () {
return _it;
}
const iterator_type getImpl () const {
return _it;
}
protected:
iterator_type _it;
};
class CIterator {
public:
CIterator (const_iterator_type in) : _it (in) {
}
bool operator == (CIterator o) const{
return _it == o._it;
}
bool operator != (CIterator o) const{
return _it != o._it;
}
void operator ++ () {
_it++;
}
CIterator operator ++ (int) {
return CIterator (_it++);
}
value_type& operator * () const{
return _it->first;
}
const_iterator_type getImpl () {
return _it;
}
const const_iterator_type getImpl () const {
return _it;
}
protected:
const_iterator_type _it;
};
typedef Iterator iterator;
typedef CIterator const_iterator;
};
template <class Container>
class Map2ndBinder {
public:
typedef typename Container::iterator iterator_type;
typedef typename Container::const_iterator const_iterator_type;
typedef typename Container::referent_type value_type;
typedef Map2ndBinder <Container> iterator;
Map2ndBinder (iterator_type in) : _it (in) {
}
bool operator == (Map2ndBinder o) const{
return _it == o._it;
}
bool operator != (Map2ndBinder o) const{
return _it != o._it;
}
void operator ++ () {
_it++;
}
Map2ndBinder operator ++ (int) {
return Map2ndBinder (_it++);
}
value_type& operator * () const{
return _it->second;
}
iterator_type getImpl () {
return _it;
}
protected:
iterator_type _it;
};
#endif //_SeedSearcher_STLHelper_h
//
// File : $RCSfile: $
// $Workfile: STLHelper.h $
// Version : $Revision: 26 $
// $Author: Aviad $
// $Date: 3/03/05 21:34 $
// Description :
// The Core library contains contains basic definitions and classes
// which are useful to any highly-portable applications
//
// 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 appliy.
//
| [
"aviadr1@1f8b7f26-7806-0410-ba70-a23862d07478"
]
| [
[
[
1,
442
]
]
]
|
03fe501696513af29f780bf8219cb5bf1c0ade64 | 1585c7e187eec165138edbc5f1b5f01d3343232f | /СПиОС/RegView/RegView/RegView.h | 0e5fdea551ed4734100da940467db2fcd0c44bf8 | []
| no_license | a-27m/vssdb | c8885f479a709dd59adbb888267a03fb3b0c3afb | d86944d4d93fd722e9c27cb134256da16842f279 | refs/heads/master | 2022-08-05T06:50:12.743300 | 2011-06-23T08:35:44 | 2011-06-23T08:35:44 | 82,612,001 | 1 | 0 | null | 2021-03-29T08:05:33 | 2017-02-20T23:07:03 | C# | UTF-8 | C++ | false | false | 670 | h |
// RegView.h : main header file for the RegView application
//
#pragma once
#ifndef __AFXWIN_H__
#error "include 'stdafx.h' before including this file for PCH"
#endif
#include "resource.h" // main symbols
// CRegViewApp:
// See RegView.cpp for the implementation of this class
//
class CRegViewApp : public CWinAppEx
{
public:
CRegViewApp();
// Overrides
public:
virtual BOOL InitInstance();
// Implementation
BOOL m_bHiColorIcons;
virtual void PreLoadState();
virtual void LoadCustomState();
virtual void SaveCustomState();
afx_msg void OnAppAbout();
DECLARE_MESSAGE_MAP()
};
extern CRegViewApp theApp;
| [
"Axell@bf672a44-3a04-1d4a-850b-c2a239875c8c"
]
| [
[
[
1,
38
]
]
]
|
ec7d8615f246d12fa447d57890625b5f4f11315d | 1c9f99b2b2e3835038aba7ec0abc3a228e24a558 | /Projects/elastix/elastix_sources_v4/src/Components/MovingImagePyramids/MovingSmoothingPyramid/elxMovingSmoothingPyramid.h | 8c59a6afec32795f52bfbba296d91d22a113e9c3 | []
| no_license | mijc/Diploma | 95fa1b04801ba9afb6493b24b53383d0fbd00b33 | bae131ed74f1b344b219c0ffe0fffcd90306aeb8 | refs/heads/master | 2021-01-18T13:57:42.223466 | 2011-02-15T14:19:49 | 2011-02-15T14:19:49 | 1,369,569 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,348 | h | /*======================================================================
This file is part of the elastix software.
Copyright (c) University Medical Center Utrecht. All rights reserved.
See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for
details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
======================================================================*/
#ifndef __elxMovingSmoothingPyramid_h
#define __elxMovingSmoothingPyramid_h
#include "itkMultiResolutionGaussianSmoothingPyramidImageFilter.h"
#include "elxIncludes.h"
namespace elastix
{
using namespace itk;
/**
* \class MovingSmoothingPyramid
* \brief A pyramid based on the itkMultiResolutionGaussianSmoothingPyramidImageFilter.
*
* The parameters used in this class are:
* \parameter MovingImagePyramid: Select this pyramid as follows:\n
* <tt>(MovingImagePyramid "MovingSmoothingImagePyramid")</tt>
*
* \ingroup ImagePyramids
*/
template <class TElastix>
class MovingSmoothingPyramid :
public
MultiResolutionGaussianSmoothingPyramidImageFilter<
ITK_TYPENAME MovingImagePyramidBase<TElastix>::InputImageType,
ITK_TYPENAME MovingImagePyramidBase<TElastix>::OutputImageType >,
public
MovingImagePyramidBase<TElastix>
{
public:
/** Standard ITK. */
typedef MovingSmoothingPyramid Self;
typedef MultiResolutionGaussianSmoothingPyramidImageFilter<
typename MovingImagePyramidBase<TElastix>::InputImageType,
typename MovingImagePyramidBase<TElastix>::OutputImageType > Superclass1;
typedef MovingImagePyramidBase<TElastix> Superclass2;
typedef SmartPointer<Self> Pointer;
typedef SmartPointer<const Self> ConstPointer;
/** Method for creation through the object factory. */
itkNewMacro( Self );
/** Run-time type information (and related methods). */
itkTypeMacro( MovingSmoothingPyramid, MultiResolutionGaussianSmoothingPyramidImageFilter );
/** Name of this class.
* Use this name in the parameter file to select this specific pyramid. \n
* example: <tt>(MovingImagePyramid "MovingSmoothingImagePyramid")</tt>\n
*/
elxClassNameMacro( "MovingSmoothingImagePyramid" );
/** Get the ImageDimension. */
itkStaticConstMacro( ImageDimension, unsigned int, Superclass1::ImageDimension );
/** Typedefs inherited from Superclass1. */
typedef typename Superclass1::InputImageType InputImageType;
typedef typename Superclass1::OutputImageType OutputImageType;
typedef typename Superclass1::InputImagePointer InputImagePointer;
typedef typename Superclass1::OutputImagePointer OutputImagePointer;
typedef typename Superclass1::InputImageConstPointer InputImageConstPointer;
/** Typedefs inherited from Elastix. */
typedef typename Superclass2::ElastixType ElastixType;
typedef typename Superclass2::ElastixPointer ElastixPointer;
typedef typename Superclass2::ConfigurationType ConfigurationType;
typedef typename Superclass2::ConfigurationPointer ConfigurationPointer;
typedef typename Superclass2::RegistrationType RegistrationType;
typedef typename Superclass2::RegistrationPointer RegistrationPointer;
typedef typename Superclass2::ITKBaseType ITKBaseType;
protected:
/** The constructor. */
MovingSmoothingPyramid() {}
/** The destructor. */
virtual ~MovingSmoothingPyramid() {}
private:
/** The private constructor. */
MovingSmoothingPyramid( const Self& ); // purposely not implemented
/** The private copy constructor. */
void operator=( const Self& ); // purposely not implemented
}; // end class MovingSmoothingPyramid
} // end namespace elastix
#ifndef ITK_MANUAL_INSTANTIATION
#include "elxMovingSmoothingPyramid.hxx"
#endif
#endif // end #ifndef __elxMovingSmoothingPyramid_h
| [
"[email protected]"
]
| [
[
[
1,
110
]
]
]
|
971e9f104de25e3dfcfaa5e5af836d785c767534 | 507511ecc4d58017e035c9a40139a1b142ea5a2f | /network/Data.cpp | 4b253c2de5edd61b6537b99c72a097174216b02f | []
| no_license | stefansundin/twug | a15a02efc500aec8f271d1c80e2631fd4b2d05d9 | 654a1f6d4540baba742a1002821802057fec1bb8 | refs/heads/master | 2020-05-01T01:39:48.605865 | 2008-05-01T15:21:08 | 2008-05-01T15:21:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 899 | cpp | #include "Data.h"
int Data::m_mem_leaked = 0;
Data::Data()
{
m_type = 0;
m_data = 0;
m_length = 0;
}
Data::Data(int p_type, std::string p_str_data)
{
m_type = p_type;
m_length = p_str_data.size();
m_data = new char[m_length];
memcpy(m_data, p_str_data.c_str(), m_length);
m_mem_leaked += m_length;
printf("m_mem_leaked: (%d)\n", m_mem_leaked);
}
Data::Data(int p_type, const void *p_data, unsigned int p_length)
{
m_type = p_type;
m_length = p_length;
m_data = new char[m_length];
memcpy(m_data, p_data, m_length);
m_mem_leaked += m_length;
printf("m_mem_leaked: (%d)\n", m_mem_leaked);
}
Data::~Data()
{
if(m_data != 0)
{
// delete [] m_data; //why does this line cause a crash?
}
}
const void* Data::getData() const
{
return m_data;
}
int Data::getType() const
{
return m_type;
}
unsigned int Data::getLength() const
{
return m_length;
}
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
1
],
[
4,
17
],
[
21,
29
],
[
33,
55
]
],
[
[
2,
3
],
[
18,
20
],
[
30,
32
]
]
]
|
8c2e42f1e916d1b9dbfe4c7827da26b0c4f66cc2 | ce1b0d027c41f70bc4cfa13cb05f09bd4edaf6a2 | / edge2d --username [email protected]/EdgeGUI/EdgeGUIManager.cpp | 85cc603e264896f56e9da8f46bfced17090ca3f8 | []
| no_license | ratalaika/edge2d | 11189c41b166960d5d7d5dbcf9bfaf833a41c079 | 79470a0fa6e8f5ea255df1696da655145bbf83ff | refs/heads/master | 2021-01-10T04:59:22.495428 | 2010-02-19T13:45:03 | 2010-02-19T13:45:03 | 36,088,756 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,461 | cpp | /**
*
*
*
*/
#include "EdgeGUIManager.h"
#include "EdgeGUIWidget.h"
#include "EdgeEngine.h"
#include "EdgeInputManager.h"
#include <algorithm>
namespace Edge
{
GUIManager::GUIManager()
{
mFocusWidget = 0;
}
GUIManager::~GUIManager()
{
release();
}
bool GUIManager::initiate()
{
return true;
}
void GUIManager::release()
{
}
void GUIManager::addWidget( GUIWidget *widget )
{
mWidgets.push_back( widget );
}
void GUIManager::removeWidget( GUIWidget *widget )
{
WidgetList::iterator it = std::find( mWidgets.begin(), mWidgets.end(), widget );
if( it != mWidgets.end() )
{
mWidgets.erase( it );
}
}
void GUIManager::setFocus( GUIWidget *widget )
{
mFocusWidget = widget;
}
void GUIManager::update( float dt )
{
GUIWidget *widget;
float mx, my, mz;
InputManager *im = EdgeEngine::getSingleton().getInputManager();
for( WidgetList::iterator it = mWidgets.begin(); it != mWidgets.end(); ++ it )
{
/// update the widget
(*it)->update( dt );
/// mouse events
widget = *it;
mx = static_cast<float>( im->getMousePosX() );
my = static_cast<float>( im->getMousePosY() );
mz = static_cast<float>( im->getMousePosZ() );
if( widget != 0 && widget->isEnable() && widget->isVisible() )
{
_processMouse( widget, mx, my, mz );
}
}
}
void GUIManager::render()
{
for( WidgetList::iterator it = mWidgets.begin(); it != mWidgets.end(); ++ it )
{
(*it)->render();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
void GUIManager::_processMouse( GUIWidget *widget, float mx, float my, float mz )
{
static float s_last_mx = mx;
static float s_last_my = my;
static float s_last_mz = mz;
if( s_last_mx != mx || s_last_my != my )
{
widget->mouseMove( fPoint( mx, my ) );
}
if( s_last_mz != mz )
{
widget->mouseWheel( static_cast<int>( mz - s_last_mz ) );
}
InputManager *im = EdgeEngine::getSingleton().getInputManager();
if( im->isKeyDown( Edge::KC_MOUSELEFT ) )
{
widget->mouseLButton( fPoint( mx, my ), true );
}
else
{
widget->mouseLButton( fPoint( mx, my ), false );
}
if( im->isKeyDown( Edge::KC_MOUSERIGHT ) )
{
widget->mouseRButton( fPoint( mx, my ), true );
}
else
{
widget->mouseRButton( fPoint( mx, my ), false );
}
}
} | [
"[email protected]@539dfdeb-0f3d-0410-9ace-d34ff1985647"
]
| [
[
[
1,
120
]
]
]
|
7bcd8bfcd0f681df37935028bf7bb4c183db8fa1 | c5bb639004e0f7f527c0a3e664bec07198064a97 | /ixutils/interface/xmlhelper.h | 1bb9121b91301808e9f50bcb9bc7dfdcfe1cf43c | []
| no_license | avgx/ixdev | 18b7887dc008d39ae73b2801c2addc4560f85315 | 4e8ce8773b3a18c299dec0b4023b242851a6d214 | refs/heads/master | 2016-09-05T09:24:05.726573 | 2007-05-28T17:11:25 | 2007-05-28T17:11:25 | 32,116,317 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 11,381 | h | #ifndef __XML_HELPER__H__
#define __XML_HELPER__H__
#pragma once
#include <vector>
#include <map>
#include <string>
#include <atlbase.h>
#include <atlstr.h>
#include <comutil.h>
#include <msxml2.h>
#pragma comment(lib, "comsuppw.lib")
namespace ixdev
{
namespace xml
{
#define IXDEV_XML_VERSION L"1.2"
class attribute;
class node;
class document;
typedef std::vector<attribute> attributes;
typedef std::map<_bstr_t, attribute> attributesmap;
typedef std::vector<node> nodes;
typedef std::multimap<_bstr_t, node> nodesmap;
class attribute
{
_bstr_t _name;
_bstr_t _value;
public:
attribute()
{
}
//имя
_bstr_t name()const
{
return _name;
}
//значение
_bstr_t value()const
{
return _value;
}
//набор ...
template<typename T>
attribute(BSTR theName, T theValue)
: _name(theName), _value(_variant_t(theValue))
{
}
#pragma warning(disable : 4267)
//как-то плохо преобразуется size_t в вариант
attribute(BSTR theName, size_t theValue)
: _name(theName), _value(_variant_t(theValue))
{
}
#pragma warning(default : 4267)
attribute(BSTR theName, BSTR theValue)
: _name(theName), _value(theValue)
{
}
attribute(BSTR theName, bool theValue)
: _name(theName), _value(_variant_t(int(theValue)))
{
}
attribute(BSTR theName, const std::string& theValue)
: _name(theName), _value(_bstr_t(theValue.c_str()))
{
}
attribute(BSTR theName, const std::wstring& theValue)
: _name(theName), _value(_bstr_t(theValue.c_str()))
{
}
//набор перегруженных функций, для однообразного получения значения
template<typename T>
void value(T& v)const
{
v = _variant_t(_value);
}
void value(bool& v)const
{
v = int(_variant_t(_value))?true:false;
}
void value(std::string& v)const
{
v = _value;
}
void value(std::wstring& v)const
{
v = _value;
}
void value(_bstr_t& v)const
{
v = _value;
}
};
class node
{
CComPtr<IXMLDOMNode> _node;
public:
//конструктор по умолчанию - пустая, не готовая к использованию ветка
node()
{
}
//конструктор для присвоения этому узлу элемента msxml
//(для чтения его свойств и дочерних узлов) (или установки корня дерева)
node(IXMLDOMNode* theNode)
{
_ASSERT(theNode);
if(theNode)
_node = theNode;
}
//конструктор копирования (для использования в контейнерах stl)
node(const node& r)
{
_node = r._node;
}
node& operator=(const node& r)
{
_node = r._node;
return (*this);
}
public:
bool is_valid()const
{
return (NULL != _node);
}
void clear()
{
_node.Release();
}
//создаем новый узел в документе дочерний для этого узла
node create_child(BSTR name)
{
HRESULT hr;
CComPtr<IXMLDOMDocument> pDoc;
hr = _node->get_ownerDocument(&pDoc);
_ASSERT(S_OK==hr);
_ASSERT(pDoc);
if(S_OK!=hr)
{
return node(0);
}
CComPtr<IXMLDOMElement> child;
hr = pDoc->createElement(_bstr_t(name), &child);
hr = _node->appendChild(child, NULL);
_ASSERT(S_OK==hr);
CComQIPtr<IXMLDOMNode> pChildNode(child);
_ASSERT(pChildNode);
return node(pChildNode);
}
//получаем все аттрибуты этого узла
attributes get_attributes()const
{
std::vector<attribute> result;
CComPtr<IXMLDOMNamedNodeMap> attrList;
HRESULT hr = E_FAIL;
hr = _node->get_attributes( &attrList );
_ASSERT(S_OK==hr);
_ASSERT(attrList);
if(NULL == attrList)
{
return result;
}
long size = 0;
hr = attrList->get_length(&size);
_ASSERT(S_OK==hr);
for (long i = 0; i < size; i++)
{
CComPtr<IXMLDOMNode> attr;
hr = attrList->get_item(i, &attr);
_ASSERT(S_OK==hr);
_ASSERT(attr);
if(S_OK!=hr)
continue;
DOMNodeType dt;
hr = attr->get_nodeType(&dt);
_ASSERT(S_OK==hr);
if(S_OK!=hr)
continue;
_ASSERT(NODE_ATTRIBUTE==dt);
if(NODE_ATTRIBUTE!=dt)
continue;
_bstr_t name;
_variant_t val;
hr = attr->get_nodeName(name.GetAddress());
_ASSERT(S_OK==hr);
if(S_OK!=hr)
continue;
hr = attr->get_nodeTypedValue(&val);
_ASSERT(S_OK==hr);
if(S_OK!=hr)
continue;
result.push_back(attribute(name, _bstr_t(val)));
}
return result;
}
attributesmap get_attributes_map()const
{
attributesmap result;
std::vector<attribute> item_list = get_attributes();
for(size_t j = 0; j < item_list.size(); j++)
{
result[item_list[j].name()] = item_list[j];
}
return result;
}
//получаем все дочерние узлы этого узла
nodes get_children()const
{
std::vector<node> result;
HRESULT hr = E_FAIL;
_ASSERT(_node);
if(NULL == _node)
{
return result;
}
CComPtr<IXMLDOMNodeList> childList;
long size;
hr = _node->get_childNodes(&childList);
_ASSERT(S_OK==hr);
_ASSERT(childList);
if(NULL == childList)
{
return result;
}
hr = childList->get_length(&size);
_ASSERT(S_OK==hr);
for (long i = 0; i < size; i++)
{
CComPtr<IXMLDOMNode> child;
hr = childList->get_item(i, &child);
_ASSERT(S_OK==hr);
_ASSERT(child);
if(child)
{
//debug only!!
//_bstr_t nodeName;
//child->get_nodeName(nodeName.GetAddress());
result.push_back( node(child) );
}
child.Release();
}
return result;
}
nodesmap get_children_map()const
{
nodesmap result;
nodes item_list = get_children();
for(size_t j = 0; j < item_list.size(); j++)
{
result.insert( nodesmap::value_type(item_list[j].get_name(), item_list[j]) );
}
return result;
}
//получаем текст узла
_bstr_t get_text()const
{
_bstr_t result;
_ASSERT(_node);
if(!_node)
return result;
_variant_t v;
HRESULT hr = E_FAIL;
hr = _node->get_nodeTypedValue(&v);
_ASSERT(hr);
if(S_OK==hr)
result = _bstr_t(v);
return result;
}
//получаем имя узла (тэг)
_bstr_t get_name()const
{
_bstr_t result;
_ASSERT(_node);
_bstr_t s;
HRESULT hr = E_FAIL;
if(NULL !=_node)
{
hr = _node->get_nodeName(result.GetAddress());
}
_ASSERT(S_OK==hr);
return result;
}
public:
//устанавливаем текст узла
HRESULT set_text(BSTR s)
{
HRESULT hr = E_FAIL;
if(!s)
return E_POINTER;
_ASSERT(_node);
if(!_node)
return hr;
hr = _node->put_text(_bstr_t(s));
return hr;
}
//добавляем аттрибут к этому узлу
HRESULT add_attribute(const attribute& attr)
{
HRESULT hr = E_FAIL;
_ASSERT(_node);
if(!_node)
return hr;
CComQIPtr<IXMLDOMElement> pElement(_node);
_ASSERT(pElement);
if(pElement)
hr = pElement->setAttribute(_bstr_t(attr.name()), _variant_t(attr.value()));
return hr;
}
};
class document
{
CComPtr<IXMLDOMDocument2> _doc;
CComPtr<IXMLDOMNode> _root;
document(const document&);
document& operator=(const document&);
public:
document()
{
::CoInitialize(NULL);
clear();
}
~document()
{
_doc.Release();
_root.Release();
::CoUninitialize();
}
void clear()
{
HRESULT hr = Create();
_ASSERT(S_OK==hr);
}
node get_root()const
{
return node(_root);
}
HRESULT create_root(BSTR name)
{
HRESULT hr = E_FAIL;
hr = Create();
if(FAILED(hr))
{
return hr;
}
hr = AddProcessingInstruction();
_ASSERT(S_OK==hr);
CComPtr<IXMLDOMElement> pRootElement;
hr = _doc->createElement(_bstr_t(name), &pRootElement);
_ASSERT(S_OK==hr);
if(!pRootElement)
return hr;
hr = _doc->putref_documentElement(pRootElement);
_ASSERT(S_OK==hr);
if(!pRootElement)
return hr;
hr = pRootElement->QueryInterface(&_root);
_ASSERT(S_OK==hr);
_ASSERT(_root);
return hr;
}
HRESULT from_string(BSTR s)
{
HRESULT hr = E_FAIL;
hr = Create();
if(FAILED(hr))
return hr;
VARIANT_BOOL res;
hr = _doc->loadXML(_bstr_t(s), &res);
if (SUCCEEDED(hr) && res != VARIANT_FALSE)
{
hr = AddProcessingInstruction();
_ASSERT(S_OK==hr);
hr = SetRootElementFromDoc();
}
return hr;
}
HRESULT to_string(BSTR* s)const
{
_ASSERT(_doc);
HRESULT hr = E_FAIL;
if(_doc)
{
hr = _doc->get_xml(s);
}
return hr;
}
HRESULT from_file(BSTR filename)
{
HRESULT hr = E_FAIL;
hr = Create();
if(FAILED(hr))
return hr;
_variant_t v(filename);
VARIANT_BOOL res;
hr = _doc->load(v, &res);
if (SUCCEEDED(hr) && res != VARIANT_FALSE)
{
hr = SetRootElementFromDoc();
}
return hr;
}
HRESULT to_file(BSTR filename)const
{
_ASSERT(_doc);
HRESULT hr = E_FAIL;
if(_doc)
{
hr = _doc->save(_variant_t(_bstr_t(filename)));
}
return hr;
}
private:
HRESULT Create()
{
HRESULT hr = E_FAIL;
_doc.Release();
_root.Release();
hr = _doc.CoCreateInstance(__uuidof(DOMDocument));
_ASSERT(SUCCEEDED(hr));
_ASSERT(_doc);
return hr;
}
HRESULT SetRootElementFromDoc()
{
HRESULT hr = E_FAIL;
_ASSERT(_doc);
CComPtr<IXMLDOMElement> pRootElement;
hr = _doc->get_documentElement(&pRootElement);
_ASSERT(S_OK==hr);
_ASSERT(pRootElement);
if(pRootElement)
{
hr = pRootElement->QueryInterface(&_root);
_ASSERT(S_OK==hr);
_ASSERT(_root);
}
return hr;
}
HRESULT AddProcessingInstruction()
{
HRESULT hr = E_FAIL;
_bstr_t data;
_bstr_t target;
bool need_insert_new_pi = true;
//создаем новую ProcessingInstruction
CComPtr<IXMLDOMProcessingInstruction> pi;
target = _T("xml");
data = _T(" version='1.0' encoding='UTF-8'");
hr = _doc->createProcessingInstruction(target, data, &pi);
_ASSERT(S_OK==hr);
_ASSERT(pi);
//ищем старую
CComPtr<IXMLDOMNode> instr;
hr = _doc->get_firstChild( &instr );
if(S_OK==hr)
{
_ASSERT(NULL != instr);
DOMNodeType tp;
hr = instr->get_nodeType( &tp );
_ASSERT(S_OK==hr);
if ( tp == NODE_PROCESSING_INSTRUCTION )
{
//Обнаружили остатки ProcessingInstruction
CComQIPtr<IXMLDOMProcessingInstruction> pi_old(instr);
_ASSERT(NULL != pi_old);
if ( NULL != pi_old )
{
CComPtr<IXMLDOMNode> oldInstr;
hr = _doc->replaceChild( pi, pi_old, &oldInstr );
need_insert_new_pi = false;
}
}
}
if(need_insert_new_pi)
{
//надо втыкнуть первой
hr = _doc->appendChild(pi, NULL);
CComPtr<IXMLDOMComment> comment;
_bstr_t comment_text = _bstr_t(L"created with ixdev.xml version='") + _bstr_t(IXDEV_XML_VERSION)+ _bstr_t(L"'");
hr = _doc->createComment(comment_text, &comment);
_ASSERT(S_OK==hr);
if(comment)
{
_doc->appendChild(comment, NULL);
}
}
return hr;
}
};
}//namespace xml
//////////////////////////////////////////////////////////////////////////
}//namespace ixdev
#endif//__XML_HELPER__H__ | [
"AGovorovsky@51359c97-8a31-0410-b0b4-35c1303a86e6"
]
| [
[
[
1,
546
]
]
]
|
289b94e38a1d31f4d681041f97fa7d34f10b8a56 | 3daaefb69e57941b3dee2a616f62121a3939455a | /mgllib/src/2d/MglTexture2.cpp | 22d5e83e876345ff7a5e15e274dc36bab1765f91 | []
| no_license | myun2ext/open-mgl-legacy | 21ccadab8b1569af8fc7e58cf494aaaceee32f1e | 8faf07bad37a742f7174b454700066d53a384eae | refs/heads/master | 2016-09-06T11:41:14.108963 | 2009-12-28T12:06:58 | 2009-12-28T12:06:58 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 596 | cpp | //////////////////////////////////////////////////////////
//
// MglTexture2
// - MglGraphicManager サーフェスクラス
//
//////////////////////////////////////////////////////////
#include "stdafx.h"
#include "MglTexture2.h"
////////////////////////////////////////////////////////////////////
// コンストラクタ
CMglTexture2::CMglTexture2()
{
m_myudg = NULL;
d3d = NULL;
}
// 初期化
void CMglTexture2::Init( CMglGraphicManager* in_myudg )
{
m_myudg = in_myudg;
d3d = m_myudg->GetD3dDevPtr();
}
// 開放
void CMglTexture2::Release()
{
}
| [
"myun2@6d62ff88-fa28-0410-b5a4-834eb811a934"
]
| [
[
[
1,
31
]
]
]
|
ee65f9cc39f0d2d8ac0520a623cbd22357edd069 | d08c381305e3e675c3f8253ce88fafd5111b103c | /8_8_2008/curve_-project/doc/arm_curve_going/arm_curve_5/screen.cpp | fa58e1842448b25fa2ff7b1a0c5f3c395cdc2344 | []
| no_license | happypeter/tinylion | 07ea77febf6dff84089eddd6e1e47cd2ae032eb2 | 2f802f291ff43c568f9ef5eb846719efca03cc80 | refs/heads/master | 2020-06-03T09:14:19.682005 | 2010-10-19T09:12:56 | 2010-10-19T09:12:56 | 914,128 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 13,604 | cpp | #include "screen.h"
#include <qevent.h>
#include <qrect.h>
#include <qsize.h>
#include <qstring.h>
#include <iostream>
using namespace std;
#include <qwmatrix.h>
#include <qfont.h>
#include <qpen.h>
Screen::Screen( QWidget *parent, const char *name, WFlags flags )
: QFrame( parent, name, flags)
//there was ' | WNoAutoErase ) ' here, peter deleted it
{
setLineWidth( FrameWidth );
setFrameStyle( Panel | Sunken );
setBackgroundMode( PaletteBase );
// setSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding );
firstShow = TRUE;
}
void Screen::showEvent( QShowEvent *e )
{
if ( firstShow )
initNumber();
initCordinate( drawPainter );
}
QSize Screen::minimumSize () const
{
return QSize( 20 * SpaceMargin, 20 * SpaceMargin );
}
void Screen::hideEvent( QHideEvent *e )
{
firstShow = FALSE;
}
void Screen::setXTitle( QString str )
{
stringXTitle = str;
}
void Screen::setYTitle( QString str )
{
stringYTitle = str;
}
void Screen::initNumber( )
{
saveBuffer.resize( size() );
saveBuffer.fill( this, 0, 0 );
newBuffer.resize( size() );
newBuffer.fill( this, 0, 0 );
midBuffer.resize( size() );
midBuffer.fill( this, 0, 0 );
drawPainter.begin(&newBuffer);
QRect newWindow = drawPainter.window();
newY = 0;
oldY =0;
sec = 0;
min = 0;
hour = 0;
stringXTitle = QObject::tr( "Time (hh:mm:ss)" );
// Yval.push_back( (double)oldY );
rectCordinate.setRect(
newWindow.topLeft().x()+FrameWidth + 2 * BaseFontHeight + 2 * BaseLineLenght,
newWindow.topLeft().y()+FrameWidth + 2 * SpaceMargin,
newWindow.width() - 2 * ( FrameWidth + BaseFontHeight + BaseLineLenght + SpaceMargin ),
newWindow.height() - 2 * ( FrameWidth + BaseFontHeight + BaseLineLenght + SpaceMargin ) );
if ( 0 != ( rectCordinate.width() % (Step*Step) ) )
{
int x = rectCordinate.width() % ( Step * Step );
rectCordinate.setWidth( rectCordinate.width() - x+1 );
}
if ( 0 != ( rectCordinate.height() % (Step*Step) ) )
{
int y = rectCordinate.height() % (Step*Step); rectCordinate.setHeight( rectCordinate.height() - y+1 );
}
numXTicks = rectCordinate.width() / Step;
numYTicks = rectCordinate.height() / Step;
rectYText.setRect(
newWindow.topLeft().x() + FrameWidth,
newWindow.topLeft().y() + FrameWidth + 2 * SpaceMargin,
BaseFontHeight, rectCordinate.height() );
rectXText.setRect(
rectCordinate.bottomLeft().x(),
newWindow.bottomLeft().y() - FrameWidth - BaseFontHeight,
rectCordinate.width(), BaseFontHeight );
fromSaveRect.setRect(
rectCordinate.topLeft().x() + Step,
rectCordinate.topLeft().y() + 1,
rectCordinate.width() - Step - 1,
rectCordinate.height() + 2 * BaseLineLenght + BaseFontHeight );
toNewRect.setRect(
rectCordinate.topLeft().x() + 1,
rectCordinate.topLeft().y() + 1,
rectCordinate.width() - Step - 1,
rectCordinate.height() + 2 * BaseLineLenght + BaseFontHeight );
drawPainter.drawRect(toNewRect);
}
void Screen::initCordinate( QPainter &pCordinate )
{
if ( firstShow )
{
pCordinate.setPen( Qt::blue );
pCordinate.drawRect( rectCordinate );
int y0 = rectCordinate.bottomLeft().y();
int x0 = rectCordinate.bottomLeft().x();
int yText = 0;
int xText= 0;
for (int j = 0; j <= numYTicks; j ++ )
{
pCordinate.drawLine( x0 - BaseLineLenght, y0, x0, y0 );
if (0 == j % Step )
{
pCordinate.drawLine( x0 - 2 * BaseLineLenght, y0, x0 - BaseLineLenght, y0 );
pCordinate.save();
pCordinate.setPen( QPen( blue, 1, DotLine) );
pCordinate.drawLine( x0 , y0, rectCordinate.bottomRight().x(), y0 );
pCordinate.restore();
pCordinate.setPen( Qt::black );
pCordinate.drawText(
x0 - 2 * BaseLineLenght - BaseFontHeight,
y0 - 2 * BaseFontHeight + 5 * Step,
BaseFontHeight, BaseFontHeight + Step,
AlignCenter , QString::number( yText) );
yText ++;
pCordinate.setPen( Qt::blue );
}
y0 -= Step;
}
/*画y轴的标题*/
pCordinate.save();
QRect tempYText(
rectYText.topLeft().x(), rectYText.topLeft().y(),
rectYText.height(), rectYText.height() );
pCordinate.setViewport( tempYText );
QRect rectYViewport = pCordinate.viewport();
pCordinate.setWindow( -(int)rectYViewport.width()/2, -(int)rectYViewport.height()/2,
rectYViewport.width(), rectYViewport.height() );
QRect rectYWindow = pCordinate.window();
QRect rectDrawText(
rectYWindow.topLeft().x(),
-(int)rectYText.width()/2,
rectYText.height(),
rectYText.width() );
pCordinate.rotate(-90.0);
double dy = ( rectYWindow.width() - rectDrawText.height() ) / 2;
dy = dy > 0 ? dy : ( -dy );
pCordinate.translate( 0, -dy );
pCordinate.drawText(
rectDrawText.topLeft().x(),
rectDrawText.topLeft().y(),
rectDrawText.width(),
rectDrawText.height(),
AlignCenter, stringYTitle );
pCordinate.restore();
pCordinate.setPen( Qt::blue );
y0 = rectCordinate.bottomLeft().y();
for ( int i = 0; i <= numXTicks; i ++ )
{
pCordinate.drawLine( x0 , y0, x0, y0 + BaseLineLenght );
if ( 0 == i % (2*Step) )
{
pCordinate.save();
pCordinate.setPen( QPen( blue, 1, DotLine) );
pCordinate.drawLine( x0 , rectCordinate.bottomLeft().y(),
x0 , rectCordinate.topLeft().y() );
pCordinate.restore();
}
x0 += Step;
}
/*画x轴的标题*/
pCordinate.drawText(
rectXText.topLeft().x(), rectXText.topLeft().y(),
rectXText.width(), rectXText.height(),
AlignCenter, stringXTitle );
}
/*将初始化好的坐标系复制到Screen部件上*/
bitBlt( this, 0, 0, &newBuffer, 0, 0, newBuffer.width(), newBuffer.height() );
}
void Screen::animate( double y )
{
newY = y;
if ( (int) Yval.size() <= (int) width() / 4 )
{
// Yval.append( newY );
} else {
// Yval.erase( Yval.begin() );
// Yval.append( newY );
}
updateCurve( drawPainter);
}
void Screen::updateCurve( QPainter &pDrawCurve)
{
/*
copyBlt ( &saveBuffer, 0, 0,&newBuffer, 0, 0, newBuffer.width(), newBuffer.height() );
copyBlt ( &midBuffer, toNewRect.topLeft().x(), toNewRect.topLeft().y(),
&saveBuffer, fromSaveRect.topLeft().x(), fromSaveRect.topLeft().y(),
fromSaveRect.width(), fromSaveRect.height() );
copyBlt ( &newBuffer, rectCordinate.topLeft().x()+1, rectCordinate.topLeft().y()+1,
&midBuffer, rectCordinate.topLeft().x()+1, rectCordinate.topLeft().y()+1,
rectCordinate.width()-2, fromSaveRect.height() );
*/
// QVector<double>::iterator Yit = Yval.end();
double Ynew, Yold;
int Xnew, Xold;
Ynew = rectCordinate.bottomRight().y();// - *(--Yit) - 1;
Xnew = rectCordinate.bottomRight().x() -1;
Yold = rectCordinate.bottomRight().y();// - *(--Yit) - 1;
Xold = rectCordinate.bottomRight().x() - Step;
pDrawCurve.setPen( Qt::blue );
pDrawCurve.drawLine(
toNewRect.bottomRight().x(), rectCordinate.bottomRight().y(),
rectCordinate.bottomRight().x(), rectCordinate.bottomRight().y() ); pDrawCurve.drawLine(
toNewRect.bottomRight().x(), rectCordinate.bottomRight().y(),
toNewRect.bottomRight().x(), rectCordinate.bottomRight().y() + BaseLineLenght );
/*draw the dotline in the horizontal direction*/
int y0 = rectCordinate.bottomRight().y();
static bool drawDotLine = FALSE;
pDrawCurve.save();
if ( drawDotLine )
{
for (int j =0; j < (numYTicks /5 -1 ); j++)
{
y0 -= 5*Step;
pDrawCurve.setPen( QPen( blue, 1, DotLine) );
pDrawCurve.drawLine( toNewRect.bottomRight().x() , y0,
rectCordinate.bottomRight().x(), y0 );
}
}
pDrawCurve.restore();
drawDotLine = !drawDotLine;
/*draw the calibration values of x-axis*/
static int numX = 0;
if ( 0 == numX % (2*Step) )
{
/*以hh:mm:ss的格式画时间*/
int low = hour % 10;
int high = hour / 10;
QString timeString;
timeString += ( QString( "%1%2:").arg(high).arg(low) );
low = min % 10;
high = min / 10;
timeString += ( QString( "%1%2:").arg(high).arg(low) );
low = sec % 10;
high = sec / 10;
timeString += ( QString( "%1%2").arg(high).arg(low) );
/*draw the long calibration */
pDrawCurve.drawLine(
toNewRect.bottomRight().x(),
rectCordinate.bottomRight().y() + BaseLineLenght,
toNewRect.bottomRight().x(),
rectCordinate.bottomRight().y() + 2 * BaseLineLenght );
/*draw the dotline in the vertical direction*/
pDrawCurve.save();
pDrawCurve.setPen( QPen( blue, 1, DotLine) );
pDrawCurve.drawLine(
toNewRect.bottomRight().x(),
rectCordinate.bottomRight().y(),
toNewRect.topRight().x(),
rectCordinate.topRight().y() );
pDrawCurve.restore();
/*draw the calibration values of x-axis*/
if ( 0 == numX % (4*Step) )
{
pDrawCurve.drawLine(
toNewRect.bottomRight().x(),
rectCordinate.bottomRight().y() + 2*BaseLineLenght,
toNewRect.bottomRight().x(),
rectCordinate.bottomRight().y() + 3 * Step );
pDrawCurve.setPen( Qt::black );
/*画时间的矩形范围*/
QRect rectCValue(
toNewRect.bottomRight().x() - 9 * Step,
toNewRect.bottomRight().y() - BaseFontHeight+2,
10 * Step,
BaseFontHeight);
pDrawCurve.drawText(
rectCValue.topLeft().x(),
rectCValue.topLeft().y(),
rectCValue.width(),
rectCValue.height(),
AlignRight | Qt::AlignHCenter,
timeString );
}
sec += 10;
if ( 60 == sec )
{
sec = 0;
min += 1;
if ( 60 == min )
{
min = 0;
hour += 1;
if ( 60 == hour )
hour = 0;
}
}
}
numX ++;
if ( numX >= 100 )
numX = 0;
pDrawCurve.setPen( Qt::black );
pDrawCurve.drawLine( Xold, (int)Yold, Xnew, (int)Ynew );
bitBlt( this, 0, 0, &newBuffer, 0, 0, newBuffer.width(), newBuffer.height() );
}
| [
"[email protected]"
]
| [
[
[
1,
361
]
]
]
|
d81ec424de5d0f1ff84d80997b9cf8486ce5922c | df238aa31eb8c74e2c208188109813272472beec | /BCGInclude/BCGPPopupDlg.h | c18e03ab1355571e832c33d487445d74f47ac72e | []
| no_license | myme5261314/plugin-system | d3166f36972c73f74768faae00ac9b6e0d58d862 | be490acba46c7f0d561adc373acd840201c0570c | refs/heads/master | 2020-03-29T20:00:01.155206 | 2011-06-27T15:23:30 | 2011-06-27T15:23:30 | 39,724,191 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,340 | h | #if !defined(AFX_BCGPPOPUPDLG_H__9EC5BC9D_ED2B_4255_A14E_E130CF5E49CA__INCLUDED_)
#define AFX_BCGPPOPUPDLG_H__9EC5BC9D_ED2B_4255_A14E_E130CF5E49CA__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
//*******************************************************************************
// COPYRIGHT NOTES
// ---------------
// This is a part of the BCGControlBar Library
// Copyright (C) 1998-2008 BCGSoft Ltd.
// All rights reserved.
//
// This source code can be used, distributed or modified
// only under terms and conditions
// of the accompanying license agreement.
//*******************************************************************************
// BCGPPopupDlg.h : header file
//
#include "BCGCBPro.h"
#ifndef BCGP_EXCLUDE_POPUP_WINDOW
#include "BCGPDialog.h"
#include "BCGPURLLinkButton.h"
/////////////////////////////////////////////////////////////////////////////
// CBCGPPopupWndParams
class BCGCBPRODLLEXPORT CBCGPPopupWndParams
{
public:
CBCGPPopupWndParams()
{
m_hIcon = NULL;
m_nURLCmdID = 0;
}
HICON m_hIcon;
CString m_strText;
CString m_strURL;
UINT m_nURLCmdID;
CBCGPPopupWndParams& operator= (CBCGPPopupWndParams& src)
{
m_hIcon = src.m_hIcon;
m_strText = src.m_strText;
m_strURL = src.m_strURL;
m_nURLCmdID = src.m_nURLCmdID;
return *this;
}
};
/////////////////////////////////////////////////////////////////////////////
// CBCGPPopupDlg window
class CBCGPPopupWindow;
class BCGCBPRODLLEXPORT CBCGPPopupDlg : public CBCGPDialog
{
DECLARE_DYNCREATE (CBCGPPopupDlg)
friend class CBCGPPopupWindow;
// Construction
public:
CBCGPPopupDlg();
BOOL CreateFromParams (CBCGPPopupWndParams& params, CBCGPPopupWindow* pParent);
// Attributes
protected:
CBCGPPopupWindow* m_pParentPopup;
BOOL m_bDefault;
CBCGPPopupWndParams m_Params;
CStatic m_wndIcon;
CStatic m_wndText;
CBCGPURLLinkButton m_btnURL;
CSize m_sizeDlg;
BOOL m_bDontSetFocus;
BOOL m_bMenuIsActive;
// Operations
public:
BOOL HasFocus () const;
CSize GetDlgSize ();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CBCGPPopupDlg)
public:
virtual BOOL PreTranslateMessage(MSG* pMsg);
protected:
virtual BOOL OnCommand(WPARAM wParam, LPARAM lParam);
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CBCGPPopupDlg();
// Generated message map functions
protected:
//{{AFX_MSG(CBCGPPopupDlg)
afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor);
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
afx_msg void OnPaint();
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
virtual BOOL OnInitDialog();
afx_msg void OnSetFocus(CWnd* pOldWnd);
//}}AFX_MSG
afx_msg LRESULT OnPrintClient(WPARAM wp, LPARAM lp);
DECLARE_MESSAGE_MAP()
virtual void OnDraw (CDC* pDC);
CSize GetOptimalTextSize (CString str);
};
#endif // BCGP_EXCLUDE_POPUP_WINDOW
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_BCGPPOPUPDLG_H__9EC5BC9D_ED2B_4255_A14E_E130CF5E49CA__INCLUDED_)
| [
"myme5261314@ec588229-7da7-b333-41f6-0e1ebc3afda5"
]
| [
[
[
1,
130
]
]
]
|
96d396c3d95fa5f549d32dfdfae89bdd4b9de0e4 | eb829319bf85e1b3140d767c4752b2fd7a95567b | /dev/src/Core/Defines.h | aea725e06335e0217674ccd78974524e3d17628f | []
| no_license | remerico/isometrico | bcf8a47393bbff7bb163257c211e307bc1ef91ba | 0da3229cc446b70a4023950455ee23b5e145ba19 | refs/heads/master | 2016-09-05T15:10:31.066219 | 2011-02-18T06:46:03 | 2011-02-18T06:46:03 | 32,114,297 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 382 | h | #ifndef DEFINES_H
#define DEFINES_H
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <stack>
#include <sstream>
#include "Utils/StrUtils.h"
#define SAFE_DELETE(x) if (x != NULL) { delete x; x = NULL; }
typedef std::vector< std::vector< int > > vector2int;
#define Vector std::vector
#define debug std::cout
#endif | [
"[email protected]@140b4ea2-ba7e-df39-444d-31ebc172e76c"
]
| [
[
[
1,
23
]
]
]
|
d280dc784a3b09457c54bd4176363045e38c73cb | b7c505dcef43c0675fd89d428e45f3c2850b124f | /Src/SimulatorQt/Util/qt/Win32/include/QtGui/qworkspace.h | 64ec0a46f1577bc987abc0d5bd080b71ac9156c5 | [
"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 | UTF-8 | C++ | false | false | 4,549 | h | /****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QWORKSPACE_H
#define QWORKSPACE_H
#include <QtGui/qwidget.h>
QT_BEGIN_HEADER
QT_BEGIN_NAMESPACE
QT_MODULE(Gui)
#ifndef QT_NO_WORKSPACE
class QAction;
class QWorkspaceChild;
class QShowEvent;
class QWorkspacePrivate;
class Q_GUI_EXPORT QWorkspace : public QWidget
{
Q_OBJECT
Q_PROPERTY(bool scrollBarsEnabled READ scrollBarsEnabled WRITE setScrollBarsEnabled)
Q_PROPERTY(QBrush background READ background WRITE setBackground)
public:
explicit QWorkspace(QWidget* parent=0);
~QWorkspace();
enum WindowOrder { CreationOrder, StackingOrder };
QWidget* activeWindow() const;
QWidgetList windowList(WindowOrder order = CreationOrder) const;
QWidget * addWindow(QWidget *w, Qt::WindowFlags flags = 0);
QSize sizeHint() const;
bool scrollBarsEnabled() const;
void setScrollBarsEnabled(bool enable);
#ifdef QT3_SUPPORT
QT3_SUPPORT_CONSTRUCTOR QWorkspace(QWidget* parent, const char* name);
QT3_SUPPORT void setPaletteBackgroundColor(const QColor &);
QT3_SUPPORT void setPaletteBackgroundPixmap(const QPixmap &);
#endif
void setBackground(const QBrush &background);
QBrush background() const;
Q_SIGNALS:
void windowActivated(QWidget* w);
public Q_SLOTS:
void setActiveWindow(QWidget *w);
void cascade();
void tile();
void arrangeIcons();
void closeActiveWindow();
void closeAllWindows();
void activateNextWindow();
void activatePreviousWindow();
protected:
bool event(QEvent *e);
void paintEvent(QPaintEvent *e);
void changeEvent(QEvent *);
void childEvent(QChildEvent *);
void resizeEvent(QResizeEvent *);
bool eventFilter(QObject *, QEvent *);
void showEvent(QShowEvent *e);
void hideEvent(QHideEvent *e);
#ifndef QT_NO_WHEELEVENT
void wheelEvent(QWheelEvent *e);
#endif
private:
Q_DECLARE_PRIVATE(QWorkspace)
Q_DISABLE_COPY(QWorkspace)
Q_PRIVATE_SLOT(d_func(), void _q_normalizeActiveWindow())
Q_PRIVATE_SLOT(d_func(), void _q_minimizeActiveWindow())
Q_PRIVATE_SLOT(d_func(), void _q_showOperationMenu())
Q_PRIVATE_SLOT(d_func(), void _q_popupOperationMenu(const QPoint&))
Q_PRIVATE_SLOT(d_func(), void _q_operationMenuActivated(QAction *))
Q_PRIVATE_SLOT(d_func(), void _q_updateActions())
Q_PRIVATE_SLOT(d_func(), void _q_scrollBarChanged())
friend class QWorkspaceChild;
};
#endif // QT_NO_WORKSPACE
QT_END_NAMESPACE
QT_END_HEADER
#endif // QWORKSPACE_H
| [
"alon@rogue.(none)"
]
| [
[
[
1,
137
]
]
]
|
d16a868aa1e4b983cefb14a2a14e60f770c7792f | 8a8873b129313b24341e8fa88a49052e09c3fa51 | /inc/HandleSystemInfo.h | c22655f60f44040a0e1617d1b293bf54482102a8 | []
| 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 | 1,586 | h | /*
============================================================================
Name : HandleSystemInfo.h
Author :
Version :
Copyright : Your copyright notice
Description : CHandleSystemInfo declaration
============================================================================
*/
#ifndef HANDLESYSTEMINFO_H
#define HANDLESYSTEMINFO_H
// INCLUDES
#include <e32std.h>
#include <e32base.h>
#include "HttpObserver.h"
class CMainEngine;
class MHandleEventObserver;
class CHttpManager;
/**
* CHandleSystemInfo
*
*/
class CHandleSystemInfo : public CBase,public MOperationObserver
{
public: // Constructors and destructor
~CHandleSystemInfo();
static CHandleSystemInfo* NewL(MHandleEventObserver& aObserver,CMainEngine& aMainEngine);
static CHandleSystemInfo* NewLC(MHandleEventObserver& aObserver,CMainEngine& aMainEngine);
private:
CHandleSystemInfo(MHandleEventObserver& aObserver,CMainEngine& aMainEngine);
void ConstructL();
public://From MOperationObserver
virtual void OperationEvent(TInt aEventType,const TDesC& aEventData,TInt aType);
public:
void SendRequest();
void CancelSendRequest();
const TDesC& GetInfo();
const TDesC& GetTitle();
const TDesC& GetSystemInfo();
TBool IsNextSystemInfo(){ return iBoolNext;}
private:
MHandleEventObserver& iObserver;
CMainEngine& iMainEngine;
CHttpManager& iHttpManager;
HBufC8* iUrl;
HBufC* iBuf;
HBufC* iSystemInfo;
HBufC* iTitle;
TBool iContentError;
TBool iBoolNext;
};
#endif // HANDLESYSTEMINFO_H
| [
"sungrass.xp@37a08ede-ebbd-11dd-bd7b-b12b6590754f"
]
| [
[
[
1,
70
]
]
]
|
b9369cbc8ad6dd443154c4c31e129203895836de | 7347ab0d3daab6781af407d43ac29243daeae438 | /src/graphics/entity.h | db1c153c9f8b9bb12e9b962cc530e62b929df266 | []
| no_license | suprafun/smalltowns | e096cdfc11e329674a7f76486452f4cd58ddaace | c722da7dd3a1d210d07f22a6c322117b540e63da | refs/heads/master | 2021-01-10T03:09:47.664318 | 2011-06-03T01:22:29 | 2011-06-03T01:22:29 | 50,808,558 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,113 | h | /*********************************************
*
* Author: David Athay
*
* License: New BSD License
*
* Copyright (c) 2008, CT Games
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of CT Games nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*
*
* Date of file creation: 08-09-20
*
* Date file last modified: 08-09-21
*
* $Id$
*
********************************************/
/**
* The entity class, this is used by movable objects
*/
#ifndef ST_ENTITY_HEADER
#define ST_ENTITY_HEADER
namespace ST
{
class Entity : public Node
{
private:
Entity();
public:
Entity(std::string name, Texture *texture);
private:
};
}
#endif
| [
"ko2fan@2ae5cb60-8703-11dd-9899-c7ba65f7c4c7"
]
| [
[
[
1,
63
]
]
]
|
8f09c6ecdaec88c783eb250b063319e29d217e72 | 208475bcab65438eed5d8380f26eacd25eb58f70 | /SockServExe/UdpSock_old.cpp | cc879f42ce52077a2d3f71fc22c2f449e9171f64 | []
| 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 | 16,943 | cpp | #include "StdAfx.h"
#undef MSG_HEAD
#define MSG_HEAD ("SockServ-UdpSock ")
void *G_ThreadUdpSend(void *arg)
{
DWORD v_dwSymb = *((DWORD*)arg);
switch(v_dwSymb)
{
case DEV_DVR:
g_objDvrUdp.P_ThreadSend();
break;
case DEV_UPDATE:
g_objUpdateUdp.P_ThreadSend();
break;
case DEV_QIAN:
g_objQianUdp.P_ThreadSend();
break;
default:
break;
}
pthread_exit(0);
}
void *G_ThreadUdpRecv(void *arg)
{
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
DWORD v_dwSymb = *((DWORD*)arg);
switch(v_dwSymb)
{
case DEV_DVR:
g_objDvrUdp.P_ThreadRecv();
break;
case DEV_UPDATE:
g_objUpdateUdp.P_ThreadRecv();
break;
case DEV_QIAN:
g_objQianUdp.P_ThreadRecv();
break;
default:
break;
}
pthread_exit(0);
}
//////////////////////////////////////////////////////////////////////////
CUdpSocket::CUdpSocket(DWORD v_dwSymb)
{
m_sockUdp = -1;
m_dwSymb = v_dwSymb;
m_pthreadSend = m_pthreadRecv = 0;
// m_bInit = false;
m_bToRelease = false;
m_bToCreate = false;
switch(m_dwSymb)
{
case DEV_DVR:
m_objSendMng.InitCfg(1024*1024, 30000);
break;
case DEV_UPDATE:
m_objSendMng.InitCfg(10*1024, 10000);
break;
case DEV_QIAN:
m_objSendMng.InitCfg(100*1024, 10000);
break;
default:
break;
}
// pthread_mutex_init( &m_mtxSock );
}
CUdpSocket::~CUdpSocket()
{
// pthread_mutex_destroy( &m_mtxSock );
}
int CUdpSocket::Init()
{
if( pthread_create( &m_pthreadSend, NULL, G_ThreadUdpSend, (void*)(&m_dwSymb) )
||
pthread_create( &m_pthreadRecv, NULL, G_ThreadUdpRecv, (void*)(&m_dwSymb) ) )
{
PRTMSG(MSG_ERR, "Create udp send/recv thread failed\n");
perror("");
return ERR_THREAD;
}
return 0;
}
void CUdpSocket::Release()
{
if( -1 != m_sockUdp )
{
shutdown( m_sockUdp, 2 ); // 参数2表示终止读取及传送操作
close( m_sockUdp );
m_sockUdp = -1;
}
}
int CUdpSocket::_CreateSock()
{
int iRet = 0;
BOOL blVal;
int iVal;
LINGER ling;
SOCKADDR_IN localaddr;
unsigned long ulIP = INADDR_ANY;
tag1QIpCfg obj1QIpCfg[2];
if( GetImpCfg( (void*)&obj1QIpCfg, sizeof(obj1QIpCfg), offsetof(tagImportantCfg, m_uni1QComuCfg.m_ary1QIpCfg), sizeof(obj1QIpCfg) ) )
return ERR_READCFGFAILED;
tag1LComuCfg obj1LComuCfg;
if( GetImpCfg( (void*)&obj1LComuCfg, sizeof(obj1LComuCfg), offsetof(tagImportantCfg, m_uni1LComuCfg.m_obj1LComuCfg), sizeof(obj1LComuCfg) ) )
return ERR_READCFGFAILED;
_DetroySock();
switch(m_dwSymb)
{
case DEV_UPDATE: // 流媒体升级中心
m_ulIp = obj1LComuCfg.m_ulLiuIP;
m_usPort = obj1LComuCfg.m_usLiuPort;
break;
case DEV_DVR: // king中心 视频上传
m_ulIp = obj1QIpCfg[0].m_ulVUdpIP;
m_usPort = obj1QIpCfg[0].m_usVUdpPort;
localaddr.sin_addr.s_addr = m_ulIp;
PRTMSG(MSG_NOR, "Video IP: %s, Port: %d\n", inet_ntoa(localaddr.sin_addr), htons(m_usPort));
break;
case DEV_QIAN: // King中心 照相数据上传
m_ulIp = obj1QIpCfg[0].m_ulQianUdpIP;
m_usPort = obj1QIpCfg[0].m_usQianUdpPort;
break;
default:
break;
}
localaddr.sin_family = AF_INET;
switch(m_dwSymb)
{
case DEV_UPDATE:
localaddr.sin_port = htons(LIU_UDP_LOCAL_PORT);
break;
case DEV_DVR:
localaddr.sin_port = htons(DVR_UDP_LOCAL_PROT);
break;
case DEV_QIAN:
localaddr.sin_port = htons(PHO_UDP_LOCAL_PROT);
break;
default:
return ERR_PAR;
}
localaddr.sin_addr.s_addr = ulIP;
// pthread_mutex_lock( &m_mtxSock );
m_sockUdp = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP );
if( -1 == m_sockUdp )
{
iRet = ERR_SOCK;
goto _CREATE_SOCK_END;
}
ling.l_onoff = 1; // 强制关闭且立即释放资源
ling.l_linger = 0;
setsockopt( m_sockUdp, SOL_SOCKET, SO_LINGER, (char*)&ling, sizeof(ling) );
blVal = FALSE; // 禁止带外数据
setsockopt( m_sockUdp, SOL_SOCKET, SO_OOBINLINE, (char*)&blVal, sizeof(blVal) );
iVal = UDP_RECVSIZE;
setsockopt( m_sockUdp, SOL_SOCKET, SO_RCVBUF, (char*)&iVal, sizeof(iVal) );
iVal = UDP_SENDSIZE;
setsockopt( m_sockUdp, SOL_SOCKET, SO_SNDBUF, (char*)&iVal, sizeof(iVal) );
// 设置为非阻塞
int iFlag = fcntl(m_sockUdp, F_GETFL, 0);
fcntl(m_sockUdp, F_SETFL, iFlag | O_NONBLOCK);
// DVR的发送缓冲设大一些 (其实设的是否不要太大,可能会快一点,待)
if( m_dwSymb == DEV_DVR )
{
iVal = 1024*32;
if( setsockopt(m_sockUdp, SOL_SOCKET, SO_SNDBUF, (char*)&iVal, sizeof(iVal)) )
{
PRTMSG(MSG_ERR, "udp setsockopt failed!\n");
perror("");
}
}
if( bind( m_sockUdp, (SOCKADDR*)&localaddr, sizeof(localaddr) ) )
{
iRet = ERR_SOCK;
goto _CREATE_SOCK_END;
}
m_bToRelease = false;
m_bToCreate = false;
// m_bInit = true;
_CREATE_SOCK_END:
// thread_mutex_unlock( &m_mtxSock );
if( 0 == iRet && m_dwSymb == DEV_UPDATE )
{
char szbuf[2];
szbuf[0] = 0x01; // 0x01 表示非中心协议帧
szbuf[1] = 0x02; // 0x02 表示UDP套接字可用
DataPush(szbuf, 2, DEV_SOCK, DEV_UPDATE, LV3);
}
if( iRet )
{
usleep( 1000 * 1000 );
}
return iRet;
}
int CUdpSocket::_DetroySock()
{
// thread_mutex_lock( &m_mtxSock );
// m_bInit = false;
if( -1 != m_sockUdp )
{
shutdown( m_sockUdp, 2 );
close( m_sockUdp );
m_sockUdp = -1;
//PRTMSG( MSG_NOR, "Destroy UDP Socket! (symb = %d)\n", m_dwSymb );
}
m_bToRelease = false;
// thread_mutex_unlock( &m_mtxSock );
usleep(500000);
}
void CUdpSocket::ReqDestroySock()
{
m_bToRelease = true;
}
void CUdpSocket::ReqCreateSock()
{
m_bToCreate = true;
}
// 发送UDP队列中的数据
void CUdpSocket::P_ThreadSend()
{
char szSendBuf[ UDP_SENDSIZE ] = {0};
DWORD dwSendLen = 0;
int iResult;
BYTE bytLvl;
BYTE bytSymb = 0;
DWORD dwPushTm = 0;
struct sockaddr_in adrTo;
int iPack = 0;
int iBytes = 0;
int i = 0;
fd_set wset, eset;
timeval tval;
// byte bytTest = 0;
// DWORD dwLastTestTm = GetTickCount();
// FILE *fp = NULL, *fp2 = NULL;
// char szTempbuf[100] = {0};
// fp = fopen("111.264", "wb+");
// fp2 = fopen("222.264", "wb+");
DWORD dw1, dw2, dw3, dw4;
int iLoop = 0;
DWORD dwSleep = 200000;
bool bNeedRestSndControl = false;
while(!g_bProgExit )
{
static DWORD sta_dwLstSndTm = ::GetTickCount();
static DWORD sta_dwSndTotal = 0;
bool bSend = false;
int iCurSend = 0;
if( DEV_DVR == m_dwSymb )
{
#if NETWORK_TYPE == NETWORK_EVDO
dwSleep = 45000;
#elif NETWORK_TYPE == NETWORK_TD
dwSleep = 100000;
#else
dwSleep = 200000;
#endif
}
else
{
dwSleep = 200000;
}
// thread_mutex_lock( &m_mtxSock );
if( m_sockUdp < 0 )
{
sta_dwLstSndTm = GetTickCount();
sta_dwSndTotal = 0;
bNeedRestSndControl = false;
dwSleep = 500000;
goto _ONE_SENDLOOP_END;
}
if( m_ulIp == 0xffffffff || m_usPort == 0xffff)
{
PRTMSG(MSG_NOR, "Ip or Port incorrect, can not send!\n");
continue;
}
//dw1 = GetTickCount();
FD_ZERO(&wset);
FD_ZERO(&eset);
FD_SET(m_sockUdp, &wset);
FD_SET(m_sockUdp, &eset);
tval.tv_sec = 0;
tval.tv_usec = 0;
iResult = select( m_sockUdp + 1, NULL, &wset, &eset, &tval );
if( iResult > 0 )
{
if( FD_ISSET(m_sockUdp, &eset) )
{
PRTMSG(MSG_NOR, "Udp Socket select write except!\n");
goto _WRITE_SOCK_EXCEPT;
}
}
else if( 0 == iResult )
{
PRTMSG(MSG_NOR, "Udp Socket select write block!\n");
goto _ONE_SENDLOOP_END;
}
else
{
PRTMSG(MSG_NOR, "Udp Socket select write except -2!\n");
goto _WRITE_SOCK_EXCEPT;
}
// // 测试用,发送34协议帧
// if(m_dwSymb == DEV_DVR)
// {
// szSendBuf[0] = 0x34;
// szSendBuf[1] = bytTest;
// if( GetTickCount() - dwLastTestTm > 5000 )
// {
// adrTo.sin_family = AF_INET;
// adrTo.sin_port = m_usPort;
// adrTo.sin_addr.s_addr = m_ulIp;
// iResult = sendto( m_sockUdp, szSendBuf, 2, 0, (struct sockaddr*)&adrTo, sizeof(adrTo) );
//
// dwLastTestTm = GetTickCount();
// bytTest++;
// PRTMSG(MSG_DBG, "send 0x34 Test: %2x, %2x, tickTount = %d\n", szSendBuf[0], szSendBuf[1], GetTickCount());
// }
// }
//dw2 = GetTickCount();
if( bNeedRestSndControl )
{
sta_dwLstSndTm = GetTickCount();
sta_dwSndTotal = 0;
bNeedRestSndControl = false;
//if( DEV_DVR == m_dwSymb ) PRTMSG( MSG_DBG, "6: %d", sta_dwLstSndTm );
}
for(i=0; i<10; i++)
{
iResult = m_objSendMng.PopData( bytLvl, sizeof(szSendBuf), dwSendLen, szSendBuf, dwPushTm, &bytSymb);
if( iResult || !dwSendLen || dwSendLen > sizeof(szSendBuf) )
{
if( iResult != ERR_QUEUE_EMPTY) PRTMSG( MSG_DBG, "UDP Sock send pop data Err! %d, %d\n", iResult, dwSendLen );
goto _ONE_SENDLOOP_END;
}
//dw3 = GetTickCount();
adrTo.sin_family = AF_INET;
adrTo.sin_port = m_usPort;
adrTo.sin_addr.s_addr = m_ulIp;
iResult = sendto( m_sockUdp, szSendBuf, int(dwSendLen), 0, (struct sockaddr*)&adrTo, sizeof(adrTo) );
//dw4 = GetTickCount();
// if( 0 == i )
// {
// PRTMSG( MSG_DBG, "!!!000: %d, %d, %d\n", dw2-dw1, dw3-dw2, dw4-dw3 );
// }
if( iResult > 0 )
{
if( iResult < (int)dwSendLen )
{
PRTMSG(MSG_DBG, "send succ, but send len incorrect, iResult = %d, dwSendLen = %d\n", iResult, dwSendLen);
}
sta_dwSndTotal += iResult;
bSend = true;
if( m_dwSymb == DEV_DVR )
{
static int sta_iLstBytes = 0;
static DWORD sta_dwLstTm = 0;
iPack++;
iBytes += iResult;
if(iPack%20 == 0)
{
DWORD dwCur = GetTickCount();
DWORD dwSndSpd = 0;
if( sta_iLstBytes && sta_dwLstTm )
{
dwSndSpd = int( double(sta_iLstBytes) / (dwCur - sta_dwLstTm) * 1000 );
sta_iLstBytes = 0;
}
sta_dwLstTm = dwCur;
PRTMSG(MSG_DBG, "DVR UDP Send %d packs, %d bytes, Tickcount:%d, Spd:%d\n", iPack, iBytes, dwCur, dwSndSpd );
}
sta_iLstBytes += iResult;
// 保存所发送的数据到文件中
// fwrite((void*)&iResult, 1, 4, fp);
// fwrite(szSendBuf, 1, iResult, fp);
// fflush(fp);
// fwrite(szSendBuf+55, iResult-57, 1, fp2);
// fflush(fp2);
//memset(szTempbuf, 0, sizeof(szTempbuf));
// sprintf(szTempbuf, "win:%2x %2x %2x %2x, pakcet:%d\r\n",
// szSendBuf[20], szSendBuf[21], szSendBuf[22], szSendBuf[23], szSendBuf[28]);
// fwrite(szTempbuf, 1, strlen(szTempbuf), fp);
// fflush(fp);
}
// else if( m_dwSymb == DEV_UPDATE )
// {
// PRTMSG(MSG_DBG, "Liu UDP send:");
// PrintString(szSendBuf, iResult);
// }
else if( m_dwSymb == DEV_QIAN )
{
iPack++;
iBytes += iResult;
PRTMSG(MSG_DBG, "Qian UDP Send %d packs, %d bytes\n", iPack, iBytes);
}
iCurSend += iResult;
if( iCurSend > 6000 )
{
//PRTMSG( MSG_DBG, "7: %d\n", iCurSend );
break;
}
}
else if( iResult < 0 )
{
PRTMSG(MSG_ERR, "Udp Send Fail\n");
perror("");
goto _WRITE_SOCK_EXCEPT;
}
usleep( 5000 );
}
goto _ONE_SENDLOOP_END;
_WRITE_SOCK_EXCEPT:
PRTMSG( MSG_DBG, "%d UDP Send Thread Except!\n", m_dwSymb );
m_bToRelease = true;
dwSleep = 500000;
sta_dwLstSndTm = GetTickCount();
sta_dwSndTotal = 0;
// 发送出错,通知TCP套接字
{
char szdata = 0x01;
DWORD dwPacketNum = 0;
g_objQianTcp.m_objSockStaMng.PushData(LV1, 1, &szdata, dwPacketNum);
}
goto _ONE_SENDLOOP_END2;
_ONE_SENDLOOP_END:
// thread_mutex_unlock( &m_mtxSock );
{
#if NETWORK_TYPE == NETWORK_TD
const DWORD SENDLMT_PERSEC = 15000;
#endif
#if NETWORK_TYPE == NETWORK_EVDO
const DWORD SENDLMT_PERSEC = 20000;
#endif
#if NETWORK_TYPE == NETWORK_WCDMA
const DWORD SENDLMT_PERSEC = 20000;
#endif
#if NETWORK_TYPE == NETWORK_GSM
const DWORD SENDLMT_PERSEC = 3000;
#endif
DWORD dwCur = GetTickCount();
DWORD dwDelt = dwCur - sta_dwLstSndTm;
// if( sta_dwSndTotal > 0 )
// {
// PRTMSG( MSG_DBG, "!!!!%d, %d\n", sta_dwSndTotal, dwDelt );
// }
if( sta_dwSndTotal >= SENDLMT_PERSEC || dwDelt >= 2000 )
{
//PRTMSG( MSG_DBG, "1: \n");
//DWORD dwNeedSleep = DWORD( sta_dwSndTotal * (dwDelt / 1000.0) );
DWORD dwNeedSleep = DWORD( double(sta_dwSndTotal) / SENDLMT_PERSEC * 1000.0 ); // ms
if( dwNeedSleep >= dwDelt )
{
dwSleep = ( dwNeedSleep - dwDelt ) * 1000;
#if NETWORK_TYPE == NETWORK_TD
if( dwSleep < 80000 ) dwSleep = 80000;
#endif
#if NETWORK_TYPE == NETWORK_EVDO
if( dwSleep < 80000 ) dwSleep = 50000;
#endif
#if NETWORK_TYPE == NETWORK_WCDMA
if( dwSleep < 80000 ) dwSleep = 50000;
#endif
#if NETWORK_TYPE == NETWORK_GSM
if( dwSleep < 80000 ) dwSleep = 300000;
#endif
//if( DEV_DVR == m_dwSymb ) PRTMSG( MSG_DBG, "2: %d,%d,%d,%d\n", dwSleep, dwNeedSleep, dwDelt, sta_dwSndTotal );
}
else
{
#if NETWORK_TYPE == NETWORK_TD
dwSleep = 80000;
#endif
#if NETWORK_TYPE == NETWORK_EVDO
dwSleep = 50000;
#endif
#if NETWORK_TYPE == NETWORK_WCDMA
dwSleep = 50000;
#endif
#if NETWORK_TYPE == NETWORK_GSM
dwSleep = 300000;
#endif
//if( DEV_DVR == m_dwSymb ) PRTMSG( MSG_DBG, "3: %d,%d,%d %d,%d\n", dwNeedSleep, dwDelt, sta_dwSndTotal, dwCur, sta_dwLstSndTm );
}
bNeedRestSndControl = true;
}
else if( sta_dwSndTotal > 0 )
{
#if NETWORK_TYPE == NETWORK_TD
dwSleep = 80000;
#endif
#if NETWORK_TYPE == NETWORK_EVDO
dwSleep = 50000;
#endif
#if NETWORK_TYPE == NETWORK_WCDMA
dwSleep = 50000;
#endif
#if NETWORK_TYPE == NETWORK_GSM
dwSleep = 300000;
#endif
bNeedRestSndControl = false;
//PRTMSG( MSG_DBG, "4: %d\n", dwDelt );
//PRTMSG( MSG_DBG, "4:\n" );
}
}
_ONE_SENDLOOP_END2:
//if( DEV_DVR == m_dwSymb && bNeedRestSndControl ) PRTMSG( MSG_DBG, "5:true\n" );
if( dwSleep )
{
iLoop ++;
//if( m_dwSymb == DEV_DVR && dwSleep > 50000 ) PRTMSG( MSG_DBG, "6: %d, %d, %d\n", dwSleep, iLoop, int(bSend) );
usleep( dwSleep );
}
}
}
void CUdpSocket::P_ThreadRecv()
{
int iResult;
char buf[ UDP_RECVSIZE ];
struct sockaddr_in addrFrom;
int iLen = sizeof(addrFrom);
buf[0] = 0x02; // 0x02 表示中心UDP协议帧
fd_set rset, eset;
timeval tvl;
DWORD dwSleep = 50000;
while(!g_bProgExit)
{
usleep( dwSleep );
dwSleep = 50000;
if( m_bToCreate )
{
//PRTMSG( MSG_DBG, "%d UDP Rcv Thread Here -1!\n", m_dwSymb );
if( _CreateSock() )
{
continue;
}
}
else if( m_bToRelease )
{
//PRTMSG( MSG_DBG, "%d UDP Rcv Thread Here -2!\n", m_dwSymb );
_DetroySock();
continue;
}
if( m_sockUdp < 0 )
{
dwSleep = 500000;
continue;
}
FD_ZERO(&rset);
FD_ZERO(&eset);
FD_SET(m_sockUdp, &rset);
FD_SET(m_sockUdp, &eset);
tvl.tv_sec = 1;
tvl.tv_usec = 0;
iResult = select( m_sockUdp + 1, &rset, NULL, &eset, &tvl);
if( iResult > 0 )
{
if( FD_ISSET(m_sockUdp, &eset) )
{
PRTMSG(MSG_NOR, "Udp Socket select read except!\n");
goto _RCV_SOCK_EXCEPT;
}
}
else if( iResult < 0 )
{
PRTMSG(MSG_NOR, "Udp Socket select read except -2!\n");
goto _RCV_SOCK_EXCEPT;
}
else
{
continue;
}
iResult = recvfrom( m_sockUdp, buf+1, sizeof(buf)-1, 0, (struct sockaddr*)&addrFrom, (socklen_t*)&iLen );
if( iResult > 0 )
{
// if( m_dwSymb == DEV_UPDATE )
// {
// PRTMSG(MSG_NOR, "Liu recv: ");
// PrintString(buf+6, 6);
// }
// if( m_dwSymb == DEV_DVR )
// {
// PRTMSG(MSG_NOR, "Dvr Udp recv: ");
// PrintString(buf, iResult+1);
//
// // 测试用
// if( buf[1] == 0x34 )
// {
// PRTMSG(MSG_NOR, "Recv 0x34 Test: %2x, %2x, TickCount = %d\n", buf[1], buf[2], GetTickCount());
// continue;
// }
// }
DataPush(buf, iResult+1, DEV_SOCK, m_dwSymb, LV2);
}
else if( iResult < 0 )
{
PRTMSG(MSG_ERR, "Udp Read Err\n" );
perror("");
// 接收出错,通知TCP套接字
char szdata = 0x01;
DWORD dwPacketNum = 0;
g_objQianTcp.m_objSockStaMng.PushData(LV1, 1, &szdata, dwPacketNum);
goto _RCV_SOCK_EXCEPT;
}
continue;
_RCV_SOCK_EXCEPT:
PRTMSG( MSG_DBG, "%d UDP Rcv Thread Except!\n", m_dwSymb );
m_bToRelease = true;
dwSleep = 500000;
}
}
bool CUdpSocket::SetIPandPort(unsigned long v_ulIp, unsigned short v_usPort)
{
m_ulIp = v_ulIp;
m_usPort = v_usPort;
}
| [
"[email protected]"
]
| [
[
[
1,
748
]
]
]
|
ee6142fb7de8b764fc661ce55877e6fae0c784b9 | ab41c2c63e554350ca5b93e41d7321ca127d8d3a | /glm/gtx/projection.inl | d7fcb7deb78013394fe1483fca246a56ac20a0a1 | []
| 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,219 | inl | ///////////////////////////////////////////////////////////////////////////////////////////////////
// OpenGL Mathematics Copyright (c) 2005 - 2009 G-Truc Creation (www.g-truc.net)
///////////////////////////////////////////////////////////////////////////////////////////////////
// Created : 2005-12-21
// Updated : 2009-03-06
// Licence : This source is under MIT License
// File : glm/gtx/projection.inl
///////////////////////////////////////////////////////////////////////////////////////////////////
namespace glm{
namespace gtx{
namespace projection{
template <typename T>
inline detail::tvec2<T> proj(
detail::tvec2<T> const & x,
detail::tvec2<T> const & Normal)
{
return glm::dot(x, Normal) / glm::dot(Normal, Normal) * Normal;
}
template <typename T>
inline detail::tvec3<T> proj(
detail::tvec3<T> const & x,
detail::tvec3<T> const & Normal)
{
return dot(x, Normal) / glm::dot(Normal, Normal) * Normal;
}
template <typename T>
inline detail::tvec4<T> proj(
detail::tvec4<T> const & x,
detail::tvec4<T> const & Normal)
{
return glm::dot(x, Normal) / glm::dot(Normal, Normal) * Normal;
}
}//namespace projection
}//namespace gtx
}//namespace glm
| [
"[email protected]"
]
| [
[
[
1,
40
]
]
]
|
7af680b8c4d56023ae47f3a5b963a1a327c25f3e | 7f6fe18cf018aafec8fa737dfe363d5d5a283805 | /samples/titoon/paintbox.h | da72b2e5ac3d35b201df910999176a51df898216 | []
| no_license | snori/ntk | 4db91d8a8fc836ca9a0dc2bc41b1ce767010d5ba | 86d1a32c4ad831e791ca29f5e7f9e055334e8fe7 | refs/heads/master | 2020-05-18T05:28:49.149912 | 2009-08-04T16:47:12 | 2009-08-04T16:47:12 | 268,861 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 623 | h | #ifndef __PAINTBOX_H__
#define __PAINTBOX_H__
#include <ntk/interface/view.h>
class Brush;
class BrushStroke;
class PaintBox : public NView {
public:
PaintBox(const NRect& frame, const NString& name);
virtual ~PaintBox();
Brush* brush() const {return m_brush;}
void set_brush(Brush* brush);
BrushStroke* brush_stroke() const {return m_brush_stroke;}
void set_brush_stroke(BrushStroke* brush_stroke);
virtual void message_received(const NMessage& message);
private:
Brush* m_brush;
BrushStroke* m_brush_stroke;
void set_up_controls_();
};// class PaintBox
#endif//EOH | [
"[email protected]"
]
| [
[
[
1,
34
]
]
]
|
4a589f5f65c09f616a7266c687a2bc55576a1947 | bda7b365b5952dc48827a8e8d33d11abd458c5eb | /Customize/CusMemory.cpp | c0eff78bfaf379731a4d137a092c5ee4ff8c6759 | []
| no_license | MrColdbird/gameservice | 3bc4dc3906d16713050612c1890aa8820d90272e | 009d28334bdd8f808914086e8367b1eb9497c56a | refs/heads/master | 2021-01-25T09:59:24.143855 | 2011-01-31T07:12:24 | 2011-01-31T07:12:24 | 35,889,912 | 3 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 2,516 | cpp | #include "stdafx.h"
#undef GS_USE_ENGINE_MEMORY_SCHEME
// ========================================================
// trigger the customized memory management
// ========================================================
//#define GS_USE_ENGINE_MEMORY_SCHEME 1
// ========================================================
// Customize memory allignment here:
// Replace all the codes in micro GS_USE_ENGINE_MEMORY_SCHEME
// in order to use your memory managerment
// ========================================================
#if GS_USE_ENGINE_MEMORY_SCHEME
#include "BASe/MEMory/MEM.h"
#endif
namespace GameService
{
// old implementation:
//#if defined(_XBOX) || defined(_XENON)
//static GS_BOOL G_AllocAttrInit = 0;
//static GS_DWORD G_AllocAttr = -1;
//#endif
//
//GS_BYTE* Alloc(GS_SIZET size)
//{
//#if GS_USE_ENGINE_MEMORY_SCHEME
// return (GS_BYTE*)MEM_p_Alloc(size);
//#else
// // use default malloc
// return new GS_BYTE[size];
//#endif
//}
//
//GS_VOID Free(GS_VOID* ptr)
//{
//#if GS_USE_ENGINE_MEMORY_SCHEME
// MEM_Free((GS_BYTE*)ptr);
//#else
// // use default free
// if (ptr)
// {
// delete [] (GS_BYTE*)ptr;
// }
//
// return;
//#endif
//}
//
//GS_BYTE* Realloc( GS_BYTE* ptr, GS_DWORD size, GS_DWORD oldsize )
//{
//#if GS_USE_ENGINE_MEMORY_SCHEME
// if (0 == size)
// {
// if(ptr)
// {
// Free(ptr);
// }
// return 0;
// }
// else if (0 == ptr)
// {
// return (GS_BYTE*)Alloc(size);
// }
//
// GS_BYTE* newptr = Alloc(size);
// if (oldsize != 0)
// {
// oldsize = oldsize > size ? size : oldsize;
// memmove(newptr, ptr, oldsize);
// }
// Free(ptr);
//
// return newptr;
//#else
// GS_BYTE* ret = NULL;
// if ((ret=(GS_BYTE*)realloc(ptr,size)) == NULL)
// {
// if (size != 0)
// {
// // not enough memory
// // FatalError("[GameService] - Not enough Memory in Realloc !!! \n");
// GS_Assert(0);
// return ptr;
// }
// else
// {
// // old memory released
// // return NULL?
// }
// }
// return ret;
//#endif
//}
//
//GS_VOID Assert(GS_BOOL value)
//{
//#if GS_USE_ENGINE_MEMORY_SCHEME
// ERR_X_Assert(value);
//#else
//#if defined(_XBOX) || defined(_XENON) || defined(_WINDOWS)
// if (!value)
// DebugBreak();
//#elif defined(_PS3)
// assert(value);
//#endif
//#endif
//}
} // namespace GameService
| [
"leavesmaple@383b229b-c81f-2bc2-fa3f-61d2d0c0fe69"
]
| [
[
[
1,
114
]
]
]
|
3ff4b629e49b7976ac6eac10f855b6f57173050b | f241b6224086eaba2de42d674e2f189a66419a63 | /old/cs4280/GroupWork/Game/Game/gui.cpp | 9a9fdbec62899550a53ab68a6d5c392d42d40bdb | []
| no_license | davidwiggy/Joshs-School | 17c78dc953ffdc5db5fc0524248f1638b64a082c | 87937141406847adcff18741882f53f1a5c44007 | refs/heads/master | 2020-04-08T01:25:17.915887 | 2011-09-24T03:51:44 | 2011-09-24T03:51:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,651 | cpp | #include "gui.h"
#include <math.h>
#include "world.h"
CGUI::CGUI()
{
minutesLeft = secondsLeft = enemiesLeft = 0;
font = new CFont("Arial", 16);
crosshair = new CFont("Courier New", 28);
endText = new CFont("Arial", 40);
enemy1 = new CFont("Courier New", 22);
enemy2 = new CFont("Courier New", 22);
enemy3 = new CFont("Courier New", 22);
enemy4 = new CFont("Courier New", 22);
enemy5 = new CFont("Courier New", 22);
enemy6 = new CFont("Courier New", 22);
player1 = new CFont("Courier New", 22);
keyFont = new CFont("Courier New", 20);
frames = 0;
lastTime = 0;
FPS = 0;
showFPS = false;
}
CGUI::~CGUI()
{
font->ClearFont();
crosshair->ClearFont();
endText->ClearFont();
enemy1->ClearFont();
enemy2->ClearFont();
player1->ClearFont();
delete font;
delete crosshair;
delete endText;
delete enemy1;
delete enemy2;
delete enemy3;
delete enemy4;
delete enemy5;
delete enemy6;
delete player1;
}
void CGUI::SetCurrentTime(float timeLeft)
{
// timeLeft is in seconds
minutesLeft = (int)(timeLeft / 60.0); // 60 seconds in 1 minute
secondsLeft = (int)floor(timeLeft) % 60;
millisecondsLeft = static_cast<int>((timeLeft - (float)floor(timeLeft)) * 1000);
if(frames > 30) { // Gets a larger portion, for more accurate results
float secondsPassed = lastTime - timeLeft;
lastTime = timeLeft;
FPS = (float)frames / secondsPassed;
frames = 0;
}
}
void CGUI::SetEnemiesLeft(int eLeft)
{
enemiesLeft = eLeft;
}
void CGUI::DrawWinner()
{
glDisable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
endText->SetPos3D(-0.25f, 0.15f, -0.1f);
endText->SetRGBA(0.3f, 1.0f, 0.3f, 0.8f);
endText->Print("YOU WIN!");
endText->SetPos3D(-0.5f, -0.2f, -0.1f);
endText->SetRGBA(1.0f, 1.0f, 1.0f, 0.8f);
endText->Print("Press the ESC key to exit");
glDisable(GL_BLEND);
glEnable(GL_TEXTURE_2D);
}
void CGUI::DrawLoser()
{
glDisable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
endText->SetPos3D(-0.25f, 0.15f, -0.1f);
endText->SetRGBA(1.0f, 0.3f, 0.3f, 0.8f);
endText->Print("YOU LOSE!");
endText->SetPos3D(-0.5f, -0.2f, -0.1f);
endText->SetRGBA(1.0f, 1.0f, 1.0f, 0.8f);
endText->Print("Press the ESC key to exit");
glDisable(GL_BLEND);
glEnable(GL_TEXTURE_2D);
}
void CGUI::Draw()
{
glDisable(GL_TEXTURE_2D);
font->SetPos3D(2.5f, 2.7f, -5.0f);
font->SetRGB(0.2f, 0.0f, 1.0f);
if (secondsLeft < 10)
{
if (millisecondsLeft < 10)
font->Print("Time: %d:0%d.0%d", minutesLeft, secondsLeft, millisecondsLeft);
else
font->Print("Time: %d:0%d.%d", minutesLeft, secondsLeft, millisecondsLeft);
}
else
{
if (millisecondsLeft < 10)
font->Print("Time: %d:%d.0%d", minutesLeft, secondsLeft, millisecondsLeft);
else
font->Print("Time: %d:%d.%d", minutesLeft, secondsLeft, millisecondsLeft);
}
font->SetPos3D(2.5f, 2.5f, -5.0f);
font->Print("Enemies: %d", enemiesLeft);
frames++; // Update frames for FPS
if(showFPS) {
font->SetPos3D(2.5f, 2.3f, -5.0f);
font->Print("FPS: %.2f", FPS);
}
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
crosshair->SetRGBA(1.0f, 0.1f, 0.1f, 0.7f);
crosshair->SetPos3D(-0.03f, -0.03f, -5.0f);
crosshair->Print("+");
if (TB_MapEnable)
{
//my Routine
player1->SetRGBA(1.0f, 1.0f, 1.0f, 0.8f);
player1->SetPos3D(static_cast<GLfloat>(-1.*((TB_PlayerPosition.x/800.)+2.+0.05)), static_cast<GLfloat>((TB_PlayerPosition.y/800.)+1.-0.06), -5.f);
player1->Print("+");
//
enemy1->SetRGBA(0.14f, 0.89f, 0.04f, 0.8f);
for (int x=0; x<MAX_ENEMIES; x++)
{
if (TB_OgroPtr[x] != NULL)
{
enemy1->SetPos3D(static_cast<GLfloat>(-1.*((TB_OgroPtr[x]->position.x/800.)+2.+0.03)), static_cast<GLfloat>((TB_OgroPtr[x]->position.z/800.)+1.-0.06), -5.f);
enemy1->Print("+");
}
}
//
enemy2->SetRGBA(0.02f, 0.07f, 0.92f, 0.8f);
for (int x=0; x<MAX_ENEMIES; x++)
{
if (TB_SodPtr[x] != NULL)
{
enemy2->SetPos3D(static_cast<GLfloat>(-1.*((TB_SodPtr[x]->position.x/800.)+2.+0.03)), static_cast<GLfloat>((TB_SodPtr[x]->position.z/800.)+1.-0.06), -5.f);
enemy2->Print("+");
}
}
//
enemy3->SetRGBA(0.93f, 0.16f, 0.01f, 0.8f);
for (int x=0; x<MAX_ENEMIES; x++)
{
if (TB_CowPtr[x] != NULL)
{
enemy3->SetPos3D(static_cast<GLfloat>(-1.*((TB_CowPtr[x]->position.x/800.)+2.+0.03)), static_cast<GLfloat>((TB_CowPtr[x]->position.z/800.)+1.-0.06), -5.f);
enemy3->Print("+");
}
}
//
enemy4->SetRGBA(0.93f, 0.89f, 0.0f, 0.8f);
for (int x=0; x<MAX_ENEMIES; x++)
{
if (TB_MechPtr[x] != NULL)
{
enemy4->SetPos3D(static_cast<GLfloat>(-1.*((TB_MechPtr[x]->position.x/800.)+2.+0.03)), static_cast<GLfloat>((TB_MechPtr[x]->position.z/800.)+1.-0.06), -5.f);
enemy4->Print("+");
}
}
//
enemy5->SetRGBA(1.00f, 0.50f, 0.0f, 0.8f);
for (int x=0; x<MAX_ENEMIES; x++)
{
if (TB_DroidPtr[x] != NULL)
{
enemy5->SetPos3D(static_cast<GLfloat>(-1.*((TB_DroidPtr[x]->position.x/800.)+2.+0.03)), static_cast<GLfloat>((TB_DroidPtr[x]->position.z/800.)+1.-0.06), -5.f);
enemy5->Print("+");
}
}
//
enemy6->SetRGBA(1.0f, 0.0f, 1.0f, 0.8f);
for (int x=0; x<MAX_ENEMIES; x++)
{
if (TB_DragonPtr[x] != NULL)
{
enemy5->SetPos3D(static_cast<GLfloat>(-1.*((TB_DragonPtr[x]->position.x/800.)+2.+0.03)), static_cast<GLfloat>((TB_DragonPtr[x]->position.z/800.)+1.-0.06), -5.f);
enemy5->Print("+");
}
}
}
if (TB_KeyEnable)
{
keyFont->SetRGBA(0.14f, 0.89f, 0.04f, 0.8f);
keyFont->SetPos3D(-2.f, 2.75f, -5.f);
keyFont->Print("Num Ogros Left : %d", TB_NumOgros);
//
keyFont->SetRGBA(0.02f, 0.07f, 0.92f, 0.8f);
keyFont->SetPos3D(-2.f, 2.55f, -5.f);
keyFont->Print("Num Sods Left : %d", TB_NumSods);
//
keyFont->SetRGBA(0.93f, 0.16f, 0.01f, 0.8f);
keyFont->SetPos3D(-2.f, 2.35f, -5.f);
keyFont->Print("Num Cows Left : %d", TB_NumCows);
//
keyFont->SetRGBA(0.93f, 0.89f, 0.0f, 0.8f);
keyFont->SetPos3D(-2.f, 2.15f, -5.f);
keyFont->Print("Num Mechs Left : %d", TB_NumMechs);
//
keyFont->SetRGBA(1.00f, 0.50f, 0.0f, 0.8f);
keyFont->SetPos3D(-2.f, 1.95f, -5.f);
keyFont->Print("Num Droids Left: %d", TB_NumDroids);
//
keyFont->SetRGBA(1.00f, 0.0f, 1.0f, 0.8f);
keyFont->SetPos3D(-2.f, 1.75f, -5.f);
keyFont->Print("Num Dragons Left: %d", TB_NumDragons);
}
glDisable(GL_BLEND);
glEnable(GL_TEXTURE_2D);
}
void CGUI::ToggleFPS() {
showFPS = !showFPS;
} | [
"arnie@67c49fff-0526-0410-8e7c-b4c1397322bd"
]
| [
[
[
1,
239
]
]
]
|
468ad7ac8f751d18d5e4b295b2dd0ae543512916 | b6ad4ca18cb717e403aecb8d045df660e9933f56 | /karma2.cpp | e0d303664d4430dbf6468c18f29a90fa81d46691 | []
| no_license | vi-k/vi-k.cpptests | ea6d47cd4c4d7dfe2604d58d1d78e8aa250a290b | 7ca512f61418359cd8c1c6d1fcd49c35321a2685 | refs/heads/master | 2021-01-10T02:01:17.590606 | 2010-06-18T06:58:31 | 2010-06-18T06:58:31 | 44,516,049 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,036 | cpp | /*
Тест скорости преобразования строки (percent_encode)
1) my
2) karma
3) printf
*/
#include <stdlib.h> /* atoi() */
#include <string.h> /* strlen() */
#include <wchar.h> /* wcslen() */
#include <boost/spirit/include/karma.hpp>
namespace karma=boost::spirit::karma;
/* Boost'овское время (и чтоб без подключения библиотек) */
#include <libs/date_time/src/posix_time/posix_time_types.cpp>
#include <libs/date_time/src/gregorian/date_generators.cpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <iostream> /* cout, wcout */
#include <sstream>
using namespace std;
const char *g_escape_symbols;
string g_str_in;
string g_str_out; /* Глобальная, чтоб не было ненужной оптимизации */
string g_str_must;
/* Проверка правильности выполнения */
#define TEST 1
typedef void(*my_proc)(int n);
void process(my_proc proc, const wchar_t *text, int n)
{
using namespace boost::posix_time;
ptime start;
time_duration time;
wcout << text << L" (" << n << L" раз): ";
start = microsec_clock::local_time();
proc(n);
time = microsec_clock::local_time() - start;
cout << to_simple_string(time) << endl;
}
string percent_encode_my(const string &str, const char *escape_symbols)
{
const char hex[17] = "0123456789abcdef";
const char *ptr_in = str.c_str();
/* Строка может содержать нулевой символ, поэтому
пользуемся размером исходной строки */
const char *end_in = ptr_in + str.size();
/* Сразу готовим буфер */
string out(str.size() * 3, ' ');
char *begin_out = (char*)out.c_str();
char *ptr_out = begin_out;
while (ptr_in != end_in)
{
char ch = *ptr_in++;
/* Кодируются все специальные символы, все не ascii-символы (>127),
пробел и заказынне пользователем */
if (ch <= 32 || ch > 127 ||
escape_symbols && strchr(escape_symbols, ch))
{
*ptr_out++ = '%';
*ptr_out++ = hex[ ((unsigned char)ch) >> 4];
*ptr_out++ = hex[ ch & 0xf ];
}
else
*ptr_out++ = ch;
}
out.resize(ptr_out - begin_out);
return out;
}
string percent_encode_karma(const string &str, const char *escape_symbols)
{
const char *ptr_in = str.c_str();
/* Строка может содержать нулевой символ, поэтому
пользуемся размером исходной строки */
const char *end_in = ptr_in + str.size();
/* Сразу готовим буфер */
string out(str.size() * 3, ' ');
char *begin_out = (char*)out.c_str();
char *ptr_out = begin_out;
while (ptr_in != end_in)
{
char ch = *ptr_in++;
/* Кодируются все специальные символы, все не ascii-символы (>127),
пробел и заказынне пользователем */
if (ch <= 32 || ch > 127 ||
escape_symbols && strchr(escape_symbols, ch))
karma::generate(ptr_out,
'%' <<karma::right_align(2,'0')[karma::hex], ch);
else
*ptr_out++ = ch;
}
out.resize(ptr_out - begin_out);
return out;
}
string percent_encode_printf(const string &str, const char *escape_symbols)
{
const char hex[17] = "0123456789abcdef";
const char *ptr_in = str.c_str();
/* Строка может содержать нулевой символ, поэтому
пользуемся размером исходной строки */
const char *end_in = ptr_in + str.size();
/* Сразу готовим буфер */
string out(str.size() * 3, ' ');
char *begin_out = (char*)out.c_str();
char *ptr_out = begin_out;
while (ptr_in != end_in)
{
char ch = *ptr_in++;
/* Кодируются все специальные символы, все не ascii-символы (>127),
пробел и заказынне пользователем */
if (ch <= 32 || ch > 127 ||
escape_symbols && strchr(escape_symbols, ch))
{
ptr_out += sprintf(ptr_out, "%%%02x",
(unsigned int)(unsigned char)ch);
}
else
*ptr_out++ = ch;
}
out.resize(ptr_out - begin_out);
return out;
}
void encode_my(int n)
{
while(n--)
{
g_str_out = percent_encode_my(g_str_in, g_escape_symbols);
#if TEST
if (g_str_out != g_str_must)
{
wcout << L"Ошибка преобразования:\n";
cout << "out: " << g_str_out << endl;
cout << "must: " << g_str_must << endl;
break;
}
#endif
}
}
void encode_karma(int n)
{
while(n--)
{
g_str_out = percent_encode_karma(g_str_in, g_escape_symbols);
#if TEST
if (g_str_out != g_str_must)
{
wcout << L"Ошибка преобразования:\n";
cout << "out: " << g_str_out << endl;
cout << "must: " << g_str_must << endl;
break;
}
#endif
}
}
void encode_printf(int n)
{
while(n--)
{
g_str_out = percent_encode_printf(g_str_in, g_escape_symbols);
#if TEST
if (g_str_out != g_str_must)
{
wcout << L"Ошибка преобразования:\n";
cout << "out: " << g_str_out << endl;
cout << "must: " << g_str_must << endl;
break;
}
#endif
}
}
int main(int argc, char *argv[])
{
wcout.imbue( locale("Russian_Russia.866") );
wcout << L"percent_encode" << endl;
int n = 100000;
if (argc > 1)
{
n = atoi(argv[1]);
}
g_escape_symbols = "%#()";
g_str_in = "Hello +%#()+ Привет";
g_str_must = "Hello%20+%25%23%28%29+%20%cf%f0%e8%e2%e5%f2";
cout << "in: " << g_str_in << endl;
process(encode_my, L"my ", n);
process(encode_karma, L"karma ", n);
process(encode_printf, L"printf ", n);
return 0;
}
| [
"victor dunaev ([email protected])"
]
| [
[
[
1,
233
]
]
]
|
4a61b27e444b5c8f3bf0d769fa657c5f42cc2acd | 6114db1d18909e8d38365a81ab5f0b1221c6d479 | /Sources/AsProfiled/MethodInfo.h | cb346161483f714b41dccad4e48f5b19d15e7d6e | []
| no_license | bitmizone/asprofiled | c6bf81e89037b68d0a7c8a981be3cd9c8a4db7c7 | b54cb47b1d3ee1ce6ad7077960394ddd5578c0ff | refs/heads/master | 2021-01-10T14:14:42.048633 | 2011-06-21T11:38:26 | 2011-06-21T11:38:26 | 48,724,442 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,236 | h | #pragma once
#include <vector>
#include "cor.h"
#include "corprof.h"
#include "common.h"
#include "ParamParser.h"
#include "Param.h"
enum StateOfReadingMethodBlob { BEGINNING, CALLING_CONVENTION_READ, ARGUMENTS_COUNT_READ, RETURN_VALUE_TYPE_READ, ARGUMENTS_TYPES_READ };
const int MaxParametersCount = 1024;
class CMethodInfo
{
public:
CMethodInfo(FunctionID functionIdArg, CComQIPtr<ICorProfilerInfo2> ICorProfilerInfo2, COR_PRF_FUNCTION_ARGUMENT_INFO* functionArguments);
CMethodInfo(IMetaDataImport* metaDataImport, mdMethodDef methodTokenArg);
CMethodInfo();
~CMethodInfo(void);
void Initialize();
void InitializeInternals();
WCHAR* GetMethodName();
CorCallingConvention GetCallingConvention();
ULONG GetArgumentsCount();
mdTypeDef GetTypeToken();
// change to internal getters
PCCOR_SIGNATURE GetMethodSignatureBlob();
IMetaDataImport* GetMetaDataImport();
mdMethodDef GetMethodToken();
CParam* GetReturnValue();
std::vector<CParam*>* GetArguments();
StateOfReadingMethodBlob GetStateOfReadingMethodBlob();
bool ReadArgumentsValues(COR_PRF_FUNCTION_ARGUMENT_INFO *argumentInfo) ;
mdParamDef argumentsTokens[MaxParametersCount];
CParamParser* GetParamParser();
private:
void SetDefaultValues();
void AssignArgumentsNames();
void AssignArgumentsData();
// fields
CComQIPtr<ICorProfilerInfo2> iCorProfilerInfo2;
// Object for operating and extracting metadata
IMetaDataImport* pMetaDataImport;
// Function global identifier
FunctionID functionId;
// Method token
mdMethodDef methodToken;
// Token for type which owns this method
mdTypeDef typeDefToken;
// Binary metadata blob
PCCOR_SIGNATURE methodSignatureBlob;
// Size of method's signature blob
ULONG methodSignatureBlobSize;
WCHAR* methodName;
ULONG methodNameLength; // + 1 for '\0'
// Internal state idicating state of reading metadata blob
StateOfReadingMethodBlob state;
// Method's calling convention
CorCallingConvention callingConvention;
ULONG argumentsCount;
CParam* returnValue;
std::vector<CParam*>* arguments;
CParamParser* paramParser;
// Represents a function's arguments
COR_PRF_FUNCTION_ARGUMENT_INFO* argumentsInfo;
};
| [
"adamsonic@cf2cc628-70ab-11de-90d8-1fdda9445408"
]
| [
[
[
1,
77
]
]
]
|
cdcd3565573d3d58b1c212b898403ccdc7a2ea09 | ab2777854d7040cc4029edcd1eccc6d48ca55b29 | /Algorithm/ATCode/MemoryDlg.cpp | e3167a3db1e9082ab4762e3e7b8ad7c0863f18f1 | []
| no_license | adrix89/araltrans03 | f9c79f8e5e62a23bbbd41f1cdbcaf43b3124719b | 6aa944d1829006a59d0f7e4cf2fef83e3f256481 | refs/heads/master | 2021-01-10T19:56:34.730964 | 2009-12-21T16:21:45 | 2009-12-21T16:21:45 | 38,417,581 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 2,360 | cpp | // MemoryDlg.cpp : implementation file
//
#include "stdafx.h"
#include "ATCode.h"
#include "MemoryDlg.h"
// CMemoryDlg dialog
IMPLEMENT_DYNAMIC(CMemoryDlg, CDialog)
CMemoryDlg::CMemoryDlg(CWnd* pParent /*=NULL*/)
: CDialog(CMemoryDlg::IDD, pParent)
, m_strSelectedArg(_T(""))
, m_bCustom(FALSE)
, m_strCustomMem(_T(""))
, m_strMemName(_T(""))
{
}
CMemoryDlg::~CMemoryDlg()
{
}
void CMemoryDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_LIST1, m_listMemories);
DDX_LBString(pDX, IDC_LIST1, m_strSelectedArg);
DDX_Check(pDX, IDC_CHECK1, m_bCustom);
DDX_Control(pDX, IDC_EDIT1, m_editCustomArg);
DDX_Control(pDX, IDC_STATIC_CUSTOM, m_staticCustom);
DDX_Text(pDX, IDC_EDIT1, m_strCustomMem);
DDX_Text(pDX, IDC_EDIT2, m_strMemName);
}
BEGIN_MESSAGE_MAP(CMemoryDlg, CDialog)
ON_LBN_DBLCLK(IDC_LIST1, &CMemoryDlg::OnLbnDblclkList1)
ON_BN_CLICKED(IDC_CHECK1, &CMemoryDlg::OnBnClickedCheck1)
ON_BN_CLICKED(IDOK, &CMemoryDlg::OnBnClickedOk)
END_MESSAGE_MAP()
// CMemoryDlg message handlers
BOOL CMemoryDlg::OnInitDialog()
{
BOOL bRetVal = CDialog::OnInitDialog();
// 리스트 박스 초기화
m_listMemories.AddString(_T("EAX"));
m_listMemories.AddString(_T("EBX"));
m_listMemories.AddString(_T("ECX"));
m_listMemories.AddString(_T("EDX"));
m_listMemories.AddString(_T("ESI"));
m_listMemories.AddString(_T("EDI"));
m_listMemories.AddString(_T("EBP"));
m_listMemories.AddString(_T("ESP"));
m_listMemories.AddString(_T("[ESP]"));
CString strMem;
for(int i=4; i<=0x200; i+=4)
{
strMem.Format(_T("[ESP+0x%x]"), i);
m_listMemories.AddString(strMem);
}
return bRetVal;
}
void CMemoryDlg::OnLbnDblclkList1()
{
OnBnClickedOk();
}
void CMemoryDlg::OnBnClickedCheck1()
{
UpdateData();
if(m_bCustom)
{
m_listMemories.ShowWindow(SW_HIDE);
m_editCustomArg.ShowWindow(SW_SHOW);
m_staticCustom.ShowWindow(SW_SHOW);
}
else
{
m_listMemories.ShowWindow(SW_SHOW);
m_editCustomArg.ShowWindow(SW_HIDE);
m_staticCustom.ShowWindow(SW_HIDE);
}
}
void CMemoryDlg::OnBnClickedOk()
{
UpdateData();
m_strMemName = m_strMemName.Trim();
if(m_strMemName.IsEmpty())
{
MessageBox(_T("Please enter the context name."), _T("AT Code"), MB_OK);
return;
}
OnOK();
}
| [
"arallab3@883913d8-bf2b-11de-8cd0-f941f5a20a08"
]
| [
[
[
1,
107
]
]
]
|
9c46136d6e7b3be31186f791d96f0749d47167a5 | 282e6353fbdf90100119bc4c2106109db7e18d15 | /serial/serial-hfk.cpp | bd91b84ea261a734816e85676f30a1babb7dbcd0 | []
| no_license | lipshitz/hfk-parallel | 80c891803ca640d3509cfb7ed9d01b8298779eab | 9b43f87f42270d65422623f1ac66e215c6d13250 | refs/heads/master | 2020-06-04T05:28:32.790747 | 2011-09-08T23:11:26 | 2011-09-08T23:11:26 | 32,195,183 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,474 | cpp | #include <time.h>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <list>
#include <string.h>
#include <algorithm>
using std::list;
using std::vector;
using std::cout;
int find_option( int argc, char **argv, const char *option )
{
for( int i = 1; i < argc; i++ )
if( strcmp( argv[i], option ) == 0 )
return i;
return -1;
}
char *read_string( int argc, char **argv, const char *option, char *default_value )
{
int iplace = find_option( argc, argv, option );
if( iplace >= 0 && iplace < argc-1 )
return argv[iplace+1];
return default_value;
}
class Generator {
public:
list<int> out;
list<int> in;
bool alive;
Generator();
~Generator();
};
// Globals
//const int gridsize = 12; // arc-index
//const int gridsize = 12;
int gridsize = 12; // arc-index
int *white;
int *black;
int default_white[12] = {9,5,11,7,8,1,10,4,0,3,2,6};
int default_black[12] = {1,0,4,3,2,6,5,9,8,11,7,10};
//const int gridsize = 12; // arc-index
// Trefoil
//int white[5] = {1, 2, 3, 4, 0};
//int black[5] = {4, 0, 1, 2, 3};
//int white[10] = {8,7,6,5,4,3,2,9,1,0};
//int black[10] = {1,3,9,0,7,5,8,4,6,2};
// Kinoshita-Terasaka KT_{2,1}
//int white[11]={5,10,9,4,8,0,1,6,7,2,3};
//int black[11]={0,6,1,7,10,2,5,9,3,4,8};
//int white[12] = {9,5,11,7,8,1,10,4,0,3,2,6};
//int black[12] = {1,0,4,3,2,6,5,9,8,11,7,10};
// Don't waste time computing factorials. Look them up.
// Fill in the big ones later since g++ doesn't seem to like big constants
long long Factorial[16] = {
1,1,2,6,24,120,720,5040,40320,362880,3628800,39916800,479001600,
0,0,0};
//braid: (xy)^{-5}
//int white[10] = {7,6,5,3,4,1,2,0,9,8};
//int black[10] = {0,9,8,6,7,4,5,3,2,1};
//another braid
//int white[11] = {5,2,3,1,4,6,7,8,9,0};
//int black[11] = {1,9,0,5,2,3,4,6,7,8};
//int white[2] = {0,1};
//int black[2] = {1,0};
// Function Prototypes
void getPerm(long long k, int h []); // Fills h with the k^th permutation (in lexico. order)
void NextPerm(short counter[], int h[]);
bool RectDotFree(int xll, int yll, int xur, int yur, int which);
inline int max( int a, int b ) { return a > b ? a : b; }
inline int min( int a, int b ) { return a < b ? a : b; }
// Decides whether one of the four rectangles on the torus with corners at(xll,yll) and (xur,yur) contains no white or black dots
/*
1 | 2 | 1
---+---+---
3 | 0 | 3
---+---+---
1 | 2 | 1
*/
long long getIndex(int y []); // Returns the number of permutations appearing before y lexicographically
long long getIndexSwap(int y [], int, int);
int WindingNumber(int x, int y); // Return winding number of the knot projection around (x,y)
int MaslovGrading(int y []);
int NumComp(); //Returns the number of components of the link.
bool ValidGrid();
int Find(vector<long long> & V, long long x); // Returns i if V[i]=x or -1 if x isn't V[i] for any i
// Main
int main(int argc, char *argv[]){
char *knotFile = read_string( argc, argv, "-k", NULL );
if( knotFile ) {
FILE *f = fopen(knotFile, "r");
if( !f ) {
printf("Error opening file %s\n", knotFile);
exit(-1);
}
fscanf(f, "%d\n", &gridsize);
white = (int*) malloc( gridsize*sizeof(int) );
black = (int*) malloc( gridsize*sizeof(int) );
for( int i = 0; i < gridsize; i++ )
fscanf(f, "%d ", white+i);
fscanf(f, "\n");
for( int i = 0; i < gridsize; i++ )
fscanf(f, "%d ", black+i);
fclose(f);
} else {
white = default_white;
black = default_black;
}
Factorial[13] = 13*Factorial[12];
Factorial[14] = 14*Factorial[13];
Factorial[15] = 15*Factorial[14];
int amin=0;
int amax=20;
int numcomp = NumComp();
cout<<"Number of components:"<<numcomp<<"\n";
if(!ValidGrid()) {cout << "Invalid grid!!\n"; return 0;} // Check that the grid is valid
time_t starttime = time(NULL); // Used to record how long this takes
// Record winding numbers around grid points for Alexander grading computations
// Also record the Alexander grading shift
// Want this to be non-positive; if it isn't, exchange the white and black dots,
// multiply all winding numbers by -1 and try again.
int WN[gridsize][gridsize];
for(int x=0; x<gridsize; x++) {
for(int y=0; y<gridsize; y++) {
WN[x][y] = WindingNumber(x,y);
}
}
// Record the lowest winding number per row
int lowestWN[gridsize];
for( int x = 0; x < gridsize; x++ ) {
int lowest = 100;
for( int y = 0; y < gridsize; y++ )
lowest = min(WN[x][y],lowest);
lowestWN[x] = lowest;
}
int temp=0;
for(int i=0; i<gridsize; i++) {
temp += WN[i][black[i]];
temp += WN[i][(black[i]+1) % gridsize];
temp += WN[(i+1) % gridsize][black[i]];
temp += WN[(i+1) % gridsize][(black[i]+1) % gridsize];
}
for(int i=0; i<gridsize; i++) {
temp += WN[i][white[i]];
temp += WN[i][(white[i]+1) % gridsize];
temp += WN[(i+1) % gridsize][white[i]];
temp += WN[(i+1) % gridsize][(white[i]+1) % gridsize];
}
const int AShift = (temp - 4 * gridsize + 4)/8;
cout << "Alexander Grading Shift: " << AShift << "\n";
cout << "Matrix of winding numbers and Black/White grid:\n";
for(int y=gridsize-1; y>=0; y--) {
for(int x=0; x<gridsize; x++) {
if(WN[x][y] >= 0) cout << " ";
cout << WN[x][y];
}
cout << " ";
for(int x=0; x<gridsize; x++) {
cout << " ";
if(black[x]==y) cout << "X";
if(white[x]==y) cout << "O";
if(black[x] != y && white[x] != y) cout << " ";
}
cout << "\n";
}
// Record for later use whether every possible rectangle has a black or white dot in it
// This will speed boundary computations.
cout << "Computing which rectangles on the torus have no black or white dots inside.\n";
bool Rectangles[gridsize][gridsize][gridsize][gridsize][4];
for(int xll=0; xll < gridsize; xll++) {
for(int xur=xll+1; xur < gridsize; xur++) {
for(int yll=0; yll < gridsize; yll++) {
for(int yur=yll+1; yur < gridsize; yur++) {
Rectangles[xll][yll][xur][yur][0] = RectDotFree(xll,yll,xur,yur,0);
Rectangles[xll][yll][xur][yur][1] = RectDotFree(xll,yll,xur,yur,1);
Rectangles[xll][yll][xur][yur][2] = RectDotFree(xll,yll,xur,yur,2);
Rectangles[xll][yll][xur][yur][3] = RectDotFree(xll,yll,xur,yur,3);
}
}
}
}
// Iterate through the generators in lexicographic
// order and calculate their boundaries
// Identify each permutation with the integer given by the number of permutations preceding
// it in lexicographic order.
// Populate Graph[count].out with a list of integers corresponding to the permutations that
// are boundaries of the permutation corresponding to count.
// Populate Graph[count].
int NumGenByAGrading[60]; // NumGenByAGrading[i] holds number of generators in A Grading i-30
vector<long long> label; // label[i] will hold the number of perms lexicographically before the i^th generator
for(int i=0; i<60; i++) NumGenByAGrading[i]=0;
cout << "Searching through " << Factorial[gridsize] << " generators to compute Alexander gradings...\n";
time_t agStartTime = time(NULL);
int g[gridsize];
int taken[gridsize];
int istack[gridsize];
for( int i = 0; i < gridsize; i++ )
istack[i] = 0;
for( int i = 0; i < gridsize; i++ )
taken[i] = 0;
int depth = 0; // this is the index of g we are working on
int AGrading = AShift;
while( true ) {
if ( depth == gridsize ) { // we are at the end of the recursion, use the permutation
if (AGrading >= amin && AGrading <= amax) {
label.push_back(getIndex(g));
NumGenByAGrading[AGrading+30]++;
}
depth--;
if( depth < 0 )
break;
taken[g[depth]] = 0;
AGrading += WN[depth][g[depth]];
continue;
}
// If there is no hope of getting a non-negative Alexander Grading from here on, decrease the depth
int maxAGrading = AGrading;
for( int i = depth; i < gridsize; i++ ) {
maxAGrading -= lowestWN[i];
}
if( maxAGrading < amin ) {
depth--;
if( depth < 0 )
break;
taken[g[depth]] = 0;
AGrading += WN[depth][g[depth]];
continue;
}
bool callBack = true;
for( int i = istack[depth]; i < gridsize; i++ ) { // consider using value i for position depth
if( !taken[i] ) {
g[depth] = i;
taken[i] = 1;
// push onto the stack
callBack = false;
istack[depth] = i+1;
if( depth < gridsize-1 )
istack[depth+1] = 0;
AGrading -= WN[depth][g[depth]];
depth++;
break;
}
}
if( callBack ) {
depth--;
if( depth < 0 )
break;
taken[g[depth]] = 0;
AGrading += WN[depth][g[depth]];
}
}
cout << "Time to compute all Alexander gradings " << time(NULL)-agStartTime << "\n";
for(int i=0;i<60;i++) {
if(NumGenByAGrading[i]>0) cout << "Number of generators in Alexander grading " << (i-30) << ": " << NumGenByAGrading[i] << "\n";
}
cout << "Total generators: " << label.size() << "\n";
vector<Generator> Graph( label.size() ); // Will hold boundary data.
cout << "Populating the Graph...\n";
long long edges=0;
int gij [gridsize];
for(int index=0; index < label.size(); index++) {
getPerm(label[index],g);
bool firstrect;
bool secondrect;
for(int i=0; i<gridsize; i++) {
for(int j=i+1; j<gridsize; j++) {
if(g[i]<g[j]) {
firstrect = Rectangles[i][g[i]][j][g[j]][0];
for(int k=i+1; k<j && firstrect; k++) {
if(g[i] < g[k] && g[k] < g[j]) firstrect=0;
}
secondrect = Rectangles[i][g[i]][j][g[j]][1];
for(int k=0; k<i && secondrect; k++) {
if(g[k]<g[i] || g[k] > g[j]) secondrect=0;
}
for(int k=j+1; k<gridsize && secondrect; k++) {
if(g[k]<g[i] || g[k] > g[j]) secondrect=0;
}
}
if(g[j]<g[i]) {
firstrect = Rectangles[i][g[j]][j][g[i]][2];
for(int k=i+1; k<j && firstrect; k++) {
if(g[k]<g[j] || g[k] > g[i]) firstrect=0;
}
secondrect = Rectangles[i][g[j]][j][g[i]][3];
for(int k=0; k<i && secondrect; k++) {
if(g[k]>g[j] && g[k]<g[i]) secondrect=0;
}
for(int k=j+1; k<gridsize && secondrect; k++) {
if(g[k]>g[j] && g[k]<g[i]) secondrect=0;
}
}
if(firstrect != secondrect) { // Exactly one rectangle is a boundary
for(int k=0; k<i; k++) {
gij[k] = g[k];
}
gij[i]=g[j];
for(int k=i+1; k<j; k++) {
gij[k]=g[k];
}
gij[j] = g[i];
for(int k=j+1; k<gridsize; k++) {
gij[k] = g[k];
}
long long Indexgij = getIndex(gij);
int indexgij = Find(label,Indexgij);
if(indexgij==-1) {cout << "Error with Alexander grading: " << Indexgij << "\n"; return 0; }
Graph[index].out.push_back( indexgij );
Graph[indexgij].in.push_back( index );
edges++;
}
}
}
}
cout << "Done computing the graph. Total edges (boundaries): " << edges << ".\n";
//PrintGraph(Graph);
// Kill all the edges in the graph.
// No live generator should ever have a dead generator on its "out" list
cout << "Killing edges in the graph...\n";
for(int i=0; i<Graph.size(); i++) {
if(i % 1000000 == 0 && i > 0) cout << "Finished " << i << " generators.\n";
if( (!Graph[i].alive) || Graph[i].out.size()==0) continue;
int target = Graph[i].out.front(); // We plan to delete the edge from i to target...
// For every m with i in dm, remove i from dm
for(list<int>::iterator j=Graph[i].in.begin(); j!=Graph[i].in.end(); j++) {
if(Graph[*j].alive) Graph[*j].out.remove(i);
}
Graph[i].alive = 0;
// For every m with target in dm adjust dm appropriately
for(list<int>::iterator j= Graph[ target ].in.begin(); j != Graph[ target ].in.end(); j++) {
if( !Graph[*j].alive ) continue;
for(list<int>::iterator k = Graph[i].out.begin(); k != Graph[i].out.end(); k++) {
// Search for *k in the boundary of *j
// If found, remove it; if not, add it to the boundary of *j
list<int>::iterator search = find( Graph[*j].out.begin(), Graph[*j].out.end(), *k);
if( search != Graph[*j].out.end() ) {
Graph[ *j ].out.erase( search );
if( *k != target) Graph[ *k ].in.remove( *j );
}
else {
Graph[*j].out.push_back(*k);
Graph[*k].in.push_back(*j);
}
}
}
// For each a in di, remove i from the in list of a
for(list<int>::iterator j=Graph[i].out.begin(); j != Graph[i].out.end(); j++) Graph[*j].in.remove(i);
Graph[target].alive = 0;
Graph[target].out.clear();
Graph[target].in.clear();
Graph[i].out.clear();
Graph[i].in.clear();
}
int HomologyRanks [60][60]; // HomologyRanks[i][j] will hold rank of homology Maslov grading=i-30 and Alexander grading j-30
for(int a=0; a<60; a++) { for(int m=0; m<60; m++) HomologyRanks[m][a]=0; }
for(int i=0; i< Graph.size(); i++) {
if(Graph[i].alive) {
getPerm(label[i],g);
int AGrading = AShift;
for(int j=0; j<gridsize; j++) AGrading -= WN[j][g[j]];
HomologyRanks[MaslovGrading(g)+30][AGrading+30]++;
}
}
cout << "Ranks of unshifted homology groups in Alexander grading [" << amin << "," << amax << "]:\n";
for(int a=amax+30; a>=amin+30; a--) {
for(int m=20; m<40; m++) {
if(HomologyRanks[m][a] < 10) cout << " ";
if(HomologyRanks[m][a] >= 10 && HomologyRanks[m][a] < 100) cout << " ";
if(HomologyRanks[m][a] >= 100 && HomologyRanks[m][a] < 1000) cout << " ";
cout << HomologyRanks[m][a];
}
cout << "\n";
}
int HFKRanks [60][60]; // HFKRanks[i][j] will hold rank of HFK^ in Maslov grading=i-30 and Alexander grading=j-30
for(int a=0; a<60; a++) { for(int m=0; m<60; m++) HFKRanks[m][a]=0; }
// Reproduce HFK^ from HFK^ \otimes K^{gridsize-1} in non-negative Alexander grading
for(int a=59; a>=0; a--) {
for(int m=59; m>=0; m--) {
if( HomologyRanks[m][a] > 0) {
HFKRanks[m][a] = HomologyRanks[m][a];
for(int i=0; i<=min(gridsize-numcomp,min(a,m)); i++) HomologyRanks[m-i][a-i] -= (HFKRanks[m][a] * Factorial[gridsize-numcomp]) / (Factorial[i] * Factorial[gridsize-numcomp-i]);
}
}
}
// Use symmetry to fill up HFKRanks in negative Alexander gradings
for(int alex=-1; alex>=-9; alex--){
for(int mas=-20; mas < 12; mas++) {
HFKRanks[mas+30][alex+30] = HFKRanks[mas-2*alex+30 ][-alex+30];
}
}
if(amin > 0) cout << "This Poincare polynomial is only valid in Alexander grading >= " << amin << ":\n";
// Print Results
bool first=1;
for(int a=-20; a<19; a++) {
for(int m=-20; m<19; m++) {
int rankam = HFKRanks[m+30][a+30];
if(rankam > 0) {
if(!first) cout << "+";
else first=0;
if(rankam > 1 || (rankam==1 && a==0 && m==0) ) cout << rankam;
if(m==1) cout << "q";
if(m != 0 && m != 1) cout << "q^{" << m << "}";
if(a==1) cout << "t";
if(a != 0 && a != 1) cout << "t^{" << a << "}";
}
}
}
cout << "\n";
time_t endtime = time(NULL);
cout << "Total time elapsed: " << (endtime-starttime) << " seconds.\n";
return 0;
}
// Class Functions
Generator::Generator(){alive=1;};
Generator::~Generator(){};
// Actual Functions
int NumComp(){
int nc = 0;
int c[gridsize];
int d=0;
int k;
for (int i=0; i<gridsize; i++) c[i]=i;
int dblack[gridsize];
int dwhite[gridsize];
for (int i =0; i<gridsize; i++){
dblack[black[i]]=i;
dwhite[white[i]]=i;
}
bool t=0;
while(!t){
d=0;
k=0;
while(c[k]==-1){
d++;
k++;
}
c[d]=-1;
int l = dblack[white[d]];
while(l!=d){
c[l]=-1;
l=dblack[white[l]];
}
nc++;
t=1;
for (int j=0; j<gridsize; j++) t = t&& (c[j] ==-1);
}
return nc;
}
int Find(vector<long long> & V, long long x) {
int above=V.size()-1;
int below=0;
while(above - below > 1) {
if (x >= V[below+(above-below)/2]) below += (above-below)/2;
else above = below+(above-below)/2;
}
if (V[below] == x) return below;
if (V[above] == x) return above;
return -1;
}
int WindingNumber(int x, int y){ // Return winding number around (x,y)
int ret=0;
for(int i=0; i<x; i++) {
if ((black[i] >= y) && (white[i] < y)) ret++;
if ((white[i] >= y) && (black[i] < y)) ret--;
}
return ret;
}
int MaslovGrading(int y []) {
// Use the formula:
// 4M(y) = 4M(white)+4P_y(R_{y, white})+4P_{white}(R_{y, white})-8W(R_{y, white})
// = 4-4*gridsize+4P_y(R_{y, white})+4P_{x_0}(R_{y, white})-8W(R_{y, white})
int P=4-4*gridsize; // Four times the Maslov grading
for(int i=0; i<gridsize; i++) {
// Calculate incidence number R_{y x_0}.S for each of the four
// squares S having (i,white[i]) as a corner and each of the
// four squares having (i,y[i]) as a corner and shift P appropriately
for(int j=0; j<=i; j++) { // Squares whose BL corners are (i,white[i]) and (i,y[i])
if ((white[j] > white[i]) && (y[j] <= white[i])) P-=7; // because of the -8W(R_{y, white}) contribution
if ((y[j] > white[i]) && (white[j] <= white[i])) P+=7;
if ((white[j] > y[i]) && (y[j] <= y[i])) P++;
if ((y[j] > y[i]) && (white[j] <= y[i])) P--;
}
for(int j=0; j<=((i-1)% gridsize); j++) { // Squares whose BR corners are (i,white[i]) and (i,y[i]) (mod gridsize)
if ((white[j] > white[i]) && (y[j] <= white[i])) P++;
if ((y[j] > white[i]) && (white[j] <= white[i])) P--;
if ((white[j] > y[i]) && (y[j] <= y[i])) P++;
if ((y[j] > y[i]) && (white[j] <= y[i])) P--;
}
for(int j=0; j<=((i-1) % gridsize); j++) { // Squares whose TR corners are...
if ((white[j] > ((white[i]-1) % gridsize)) && (y[j] <= ((white[i]-1) % gridsize))) P++;
if ((y[j] > ((white[i]-1) % gridsize) ) && (white[j] <= ((white[i]-1) % gridsize))) P--;
if ((white[j] > ((y[i]-1) % gridsize)) && (y[j] <= ((y[i]-1) % gridsize))) P++;
if ((y[j] > ((y[i]-1) % gridsize) ) && (white[j] <= ((y[i]-1) % gridsize))) P--;
}
for(int j=0; j<=i; j++) { // Squares whose TL corners are...
if ((white[j] > ((white[i]-1) % gridsize)) && (y[j] <= ((white[i]-1) % gridsize))) P++;
if ((y[j] > ((white[i]-1) % gridsize) ) && (white[j] <= ((white[i]-1) % gridsize))) P--;
if ((white[j] > ((y[i]-1) % gridsize)) && (y[j] <= ((y[i]-1) % gridsize))) P++;
if ((y[j] > ((y[i]-1) % gridsize) ) && (white[j] <= ((y[i]-1) % gridsize))) P--;
}
}
return (P/4);
}
bool RectDotFree(int xll, int yll, int xur, int yur, int which) {
bool dotfree = 1;
switch (which) {
case 0:
for(int x=xll; x<xur && dotfree; x++) {
if (white[x] >= yll && white[x] < yur) dotfree = 0;
if (black[x] >= yll && black[x] < yur) dotfree = 0;
}
return dotfree;
case 1:
for(int x=0; x<xll && dotfree; x++) {
if (white[x] < yll || white[x] >= yur) dotfree = 0;
if (black[x] < yll || black[x] >= yur) dotfree = 0;
}
for(int x=xur; x<gridsize && dotfree; x++) {
if (white[x] < yll || white[x] >= yur) dotfree = 0;
if (black[x] < yll || black[x] >= yur) dotfree = 0;
}
return dotfree;
case 2:
for(int x=xll; x<xur && dotfree; x++) {
if (white[x] < yll || white[x] >= yur) dotfree = 0;
if (black[x] < yll || black[x] >= yur) dotfree = 0;
}
return dotfree;
case 3:
for(int x=0; x<xll && dotfree; x++) {
if (white[x] >= yll && white[x] < yur) dotfree = 0;
if (black[x] >= yll && black[x] < yur) dotfree = 0;
}
for(int x=xur; x<gridsize && dotfree; x++) {
if (white[x] >= yll && white[x] < yur) dotfree = 0;
if (black[x] >= yll && black[x] < yur) dotfree = 0;
}
return dotfree;
}
return 0; //Error!
}
bool ValidGrid() {
int numwhite=0;
int numblack=0;
for(int i=0; i<gridsize; i++) {
for(int j=0; j<gridsize; j++) {
if (white[j]==i) numwhite++;
if (black[j]==i) numblack++;
}
if (numwhite != 1 || numblack != 1) {
std::cout << "\nInvalid Grid!\n";
return 0;
}
numwhite=0;
numblack=0;
}
return 1;
}
// Code below added by MC
// Maps a permutation of size n to an integer < n!
// See: Knuth, Volume 2, Section 3.3.2, Algorithm P
long long getIndex( int *P ) {
long long index = 0;
for( int i = gridsize-2; i >= 0; i-- ) {
int r = P[i];
int m = 0;
for( int j = 0; j < i; j++ )
if( P[j] < r )
m++;
index += Factorial[gridsize-1-i]*(r-m);
}
return index;
}
// Inverse mapping, from integers < gridsize! to permutations of size n
// Writes the permutation corresponding to n into the array P.
void getPerm( long long n, int *P ) {
int taken[gridsize];
int offset;
for( int i = 0; i < gridsize; i++ )
taken[i] = 0;
for( int i = 0; i < gridsize; i++ ) {
offset = n / Factorial[gridsize-1-i];
n -= offset*Factorial[gridsize-1-i];
for( int j = 0; j <= offset; j++ )
if( taken[j] )
offset++;
P[i] = offset;
taken[P[i]] = 1;
}
}
long long getIndexSwap( int *P, int I, int J ) {
long long index = 0;
for( int i = gridsize-2; i >= 0; i-- ) {
int r = P[i];
if( i == I )
r = P[J];
if( i == J )
r = P[I];
int m = 0;
for( int j = 0; j < i; j++ ) {
int l = P[j];
if( j == I )
l = P[J];
if( j == J )
l = P[I];
if( l < r )
m++;
}
index += Factorial[gridsize-1-i]*(r-m);
}
return index;
}
| [
"benjamin.lip@c2f0229c-37c9-6e89-a4ff-2bb24d9bb920"
]
| [
[
[
1,
686
]
]
]
|
185ab3740b09825fbe0ea9b3ec21766db7e0a582 | e03ee4538dce040fe16fc7bb48d495735ac324f4 | /Stable/Main/Engine.h | bc8ce36df97bdca71008a451eb65cd8b01196914 | []
| no_license | vdelgadov/itcvideogame | dca6bcb084c5dde25ecf29ab1555dbe8b0a9a441 | 5eac60e901b29bff4d844f34cd52f97f4d1407b5 | refs/heads/master | 2020-05-16T23:43:48.956373 | 2009-12-01T02:09:08 | 2009-12-01T02:09:08 | 42,265,496 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,354 | h | #ifndef SIMPLE_ENGINE_H
#define SIMPLE_ENGINE_H
#define SERVER 0 //0 or 1
//#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <windowsx.h>
#include <d3d9.h>
#include <d3dx9.h>
#include <dinput.h>
#pragma comment (lib, "dinput8.lib")
#pragma comment (lib, "dxguid.lib")
//===============================================================
// Clean up
#define ReleaseCOM(x) { if(x){ x->Release();x = 0; } }
//Dinput
class CEngine {
public:
D3DXMATRIX matProjection;
D3DXMATRIX matView;
HINSTANCE hInstance;
HWND hWnd;
LPDIRECT3D9 d3d;
LPDIRECT3DDEVICE9 d3ddev;
LPDIRECT3DVERTEXBUFFER9 v_buffer;
int iVertexSize;
int iVertexDataSize;
int iWidth;
int iHeight;
int iFVFFlags;
CEngine(HINSTANCE Instance, int width, int height) : iWidth(width), iHeight(height),
v_buffer(NULL), d3d(NULL), d3ddev(NULL),
iVertexSize(0), iFVFFlags(0), iVertexDataSize(0) {
hInstance = Instance;
initWindow();
init3D();
}
~CEngine() {
close3D();
}
void close3D() {
if(v_buffer){v_buffer->Release();}
d3ddev->Release();
d3d->Release();
}
void initWindow() {
WNDCLASSEX wc;
ZeroMemory(&wc, sizeof(WNDCLASSEX));
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.lpszClassName = L"WindowClass";
RegisterClassEx(&wc);
hWnd = CreateWindowEx(NULL, L"WindowClass", L"D3D nine",
WS_OVERLAPPEDWINDOW, 0, 0, iWidth, iHeight,
NULL, NULL, hInstance, NULL);
ShowWindow(hWnd, SW_SHOWDEFAULT);
}
void init3D() {
d3d = Direct3DCreate9(D3D_SDK_VERSION);
D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory(&d3dpp, sizeof(d3dpp));
d3dpp.Windowed = TRUE;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.hDeviceWindow = hWnd;
d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
d3dpp.BackBufferWidth = 0;
d3dpp.BackBufferHeight = 0;
d3dpp.EnableAutoDepthStencil = TRUE;
d3dpp.AutoDepthStencilFormat = D3DFMT_D24S8;
d3dpp.MultiSampleType = D3DMULTISAMPLE_NONE;
d3d->CreateDevice(D3DADAPTER_DEFAULT,
D3DDEVTYPE_HAL,
hWnd,
D3DCREATE_HARDWARE_VERTEXPROCESSING,
&d3dpp,
&d3ddev);
d3ddev->SetRenderState(D3DRS_LIGHTING, TRUE);
d3ddev->SetRenderState(D3DRS_ZENABLE, TRUE);
d3ddev->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
}
void SetTrianglesVBuffer(const void *data, DWORD datasize, DWORD vertexsize, DWORD fvfflags) {
if (v_buffer)
v_buffer->Release();
d3ddev->CreateVertexBuffer(datasize,
0,
fvfflags,
D3DPOOL_MANAGED,
&v_buffer,
NULL);
void* pVoid;
iVertexSize = vertexsize;
iFVFFlags = fvfflags;
iVertexDataSize = datasize;
// load the vertices
v_buffer->Lock(0, 0, &pVoid, 0);
memcpy(pVoid, data, datasize);
v_buffer->Unlock();
}
bool ProcessMessages() {
MSG msg;
while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
if(msg.message == WM_QUIT)
return false;
return true;
}
void SetPerspective(float fovy, float n, float f) {
D3DXMatrixPerspectiveFovLH(&matProjection, fovy,
1.0f,
n,f);
d3ddev->SetTransform(D3DTS_PROJECTION, &matProjection);
}
void Clear() {
d3ddev->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);
}
void Begin() {
d3ddev->BeginScene();
}
void End() {
d3ddev->EndScene();
d3ddev->Present(NULL, NULL, NULL, NULL);
}
void Render() {
d3ddev->SetFVF(iFVFFlags);
d3ddev->SetStreamSource(0, v_buffer, 0, iVertexSize);
d3ddev->DrawPrimitive(D3DPT_TRIANGLELIST, 0, iVertexDataSize/iVertexSize);
}
protected:
static LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch(message)
{
case WM_DESTROY:
{
PostQuitMessage(0);
return 0;
} break;
}
return DefWindowProc (hWnd, message, wParam, lParam);
}
};
#endif
| [
"leamsi.setroc@972b8bf6-92a2-11de-b72a-e7346c8bff7a",
"victor.delgadov@972b8bf6-92a2-11de-b72a-e7346c8bff7a",
"zombienator@972b8bf6-92a2-11de-b72a-e7346c8bff7a"
]
| [
[
[
1,
2
]
],
[
[
3,
22
],
[
27,
32
],
[
35,
79
],
[
81,
87
],
[
89,
89
],
[
112,
191
]
],
[
[
23,
26
],
[
33,
34
],
[
80,
80
],
[
88,
88
],
[
90,
111
]
]
]
|
4794e9fc0a3b20272e3b47260d9caa58df62e80b | f9774f8f3c727a0e03c170089096d0118198145e | /传奇mod/mirserver/SelGate/ServerSockMsg.cpp | 1f8af744e528da3e584d31c36858720bc7b8a089 | []
| no_license | sdfwds4/fjljfatchina | 62a3bcf8085f41d632fdf83ab1fc485abd98c445 | 0503d4aa1907cb9cf47d5d0b5c606df07217c8f6 | refs/heads/master | 2021-01-10T04:10:34.432964 | 2010-03-07T09:43:28 | 2010-03-07T09:43:28 | 48,106,882 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,814 | cpp | #include "stdafx.h"
void SendExToServer(char *pszPacket);
extern SOCKET g_ssock;
extern SOCKET g_csock;
extern HWND g_hStatusBar;
#ifndef _SOCKET_ASYNC_IO
extern HANDLE g_hIOCP;
CWHList<CSessionInfo*> g_xSessionList;
#endif
extern BOOL g_fTerminated;
void UpdateStatusBar(BOOL fGrow)
{
static LONG nNumOfCurrSession = 0;
TCHAR szText[20];
(fGrow ? InterlockedIncrement(&nNumOfCurrSession) : InterlockedDecrement(&nNumOfCurrSession));
wsprintf(szText, _TEXT("%d Sessions"), nNumOfCurrSession);
SendMessage(g_hStatusBar, SB_SETTEXT, MAKEWORD(3, 0), (LPARAM)szText);
}
//UINT WINAPI AcceptThread(LPVOID lpParameter)
DWORD WINAPI AcceptThread(LPVOID lpParameter)
{
int nLen = sizeof(SOCKADDR_IN);
char szMsg[64];
SOCKET Accept;
SOCKADDR_IN Address;
while (TRUE)
{
Accept = accept(g_ssock, (struct sockaddr FAR *)&Address, &nLen);
if (g_fTerminated)
return 0;
CSessionInfo* pNewUserInfo = (CSessionInfo*)GlobalAlloc(GPTR, sizeof(CSessionInfo));
if (pNewUserInfo)
{
pNewUserInfo->sock = Accept;
CreateIoCompletionPort((HANDLE)pNewUserInfo->sock, g_hIOCP, (DWORD)pNewUserInfo, 0);
if (g_xSessionList.AddNewNode(pNewUserInfo))
{
int zero = 0;
setsockopt(pNewUserInfo->sock, SOL_SOCKET, SO_SNDBUF, (char *)&zero, sizeof(zero) );
// ORZ:
pNewUserInfo->Recv();
UpdateStatusBar(TRUE);
//WSAAddressToString(&AcceptAddr, (DWORD)nAcceptAddrLen, NULL, szAcceptDotAddr, (LPDWORD)&nAcceptDotAddrLen);
// Make packet and send to login server.
//wsprintf(szMsg, _TEXT("%%O%d/%d.%d.%d.%d$"), Accept, Address.sin_addr.s_net, Address.sin_addr.s_host,
// Address.sin_addr.s_lh, Address.sin_addr.s_impno);
szMsg[0] = '%';
szMsg[1] = 'O';
char *pszPos = ValToAnsiStr((int)Accept, &szMsg[2]);
*pszPos++ = '/';
pszPos = ValToAnsiStr((int)Address.sin_addr.s_net, pszPos);
*pszPos++ = '.';
pszPos = ValToAnsiStr((int)Address.sin_addr.s_host, pszPos);
*pszPos++ = '.';
pszPos = ValToAnsiStr((int)Address.sin_addr.s_lh, pszPos);
*pszPos++ = '.';
pszPos = ValToAnsiStr((int)Address.sin_addr.s_impno, pszPos);
*pszPos++ = '$';
*pszPos = '\0';
SendExToServer(szMsg);
}
}
}
return 0;
}
//void CloseSession(CSessionInfo* pSessionInfo)
void CloseSession(int s)
{
char szMsg[32];
// Send close msg to login server
//wsprintf(szMsg, _TEXT("%%X%d$"), s);
szMsg[0] = '%';
szMsg[1] = 'X';
char *pszPos = ValToAnsiStr(s, &szMsg[2]);
*pszPos++ = '$';
*pszPos = '\0';
SendExToServer(szMsg);
closesocket(s);
UpdateStatusBar(FALSE);
}
DWORD WINAPI ServerWorkerThread(LPVOID CompletionPortID)
{
DWORD dwBytesTransferred = 0;
CSessionInfo* pSessionInfo = NULL;
_LPTCOMPLETIONPORT lpPerIoData = NULL;
char szPacket[DATA_BUFSIZE + 20]; // 20 is dummy size
char szMsg[32];
char *pszPos;
while (TRUE)
{
if (GetQueuedCompletionStatus((HANDLE)CompletionPortID, &dwBytesTransferred, (LPDWORD)&pSessionInfo,
(LPOVERLAPPED *)&lpPerIoData, INFINITE) == 0)
{
if (g_fTerminated)
return 0;
if (pSessionInfo)
{
szMsg[0] = '%';
szMsg[1] = 'X';
char *pszPos = ValToAnsiStr((int)pSessionInfo->sock, &szMsg[2]);
*pszPos++ = '$';
*pszPos = '\0';
SendExToServer(szMsg);
g_xSessionList.RemoveNodeByData(pSessionInfo);
closesocket(pSessionInfo->sock);
pSessionInfo->sock = INVALID_SOCKET;
UpdateStatusBar(FALSE);
GlobalFree(pSessionInfo);
}
continue;
}
if (g_fTerminated)
return 0;
if (dwBytesTransferred == 0)
{
szMsg[0] = '%';
szMsg[1] = 'X';
char *pszPos = ValToAnsiStr((int)pSessionInfo->sock, &szMsg[2]);
*pszPos++ = '$';
*pszPos = '\0';
SendExToServer(szMsg);
g_xSessionList.RemoveNodeByData(pSessionInfo);
closesocket(pSessionInfo->sock);
pSessionInfo->sock = INVALID_SOCKET;
UpdateStatusBar(FALSE);
GlobalFree(pSessionInfo);
continue;
}
// ORZ:
pSessionInfo->bufLen += dwBytesTransferred;
while ( pSessionInfo->HasCompletionPacket() )
{
szPacket[0] = '%';
szPacket[1] = 'A';
pszPos = ValToAnsiStr( (int) pSessionInfo->sock, &szPacket[2] );
*pszPos++ = '/';
pszPos = pSessionInfo->ExtractPacket( pszPos );
*pszPos++ = '$';
*pszPos = '\0';
SendExToServer( szPacket );
}
// ORZ:
if ( pSessionInfo->Recv() == SOCKET_ERROR && WSAGetLastError() != ERROR_IO_PENDING )
{
InsertLogMsg(_TEXT("WSARecv() failed"));
CloseSession(pSessionInfo->sock);
continue;
}
}
return 0;
}
| [
"fjljfat@4a88d1ba-22b1-11df-8001-4f4b503b426e"
]
| [
[
[
1,
217
]
]
]
|
30c2ed9359039e302b424f5ab14a5d612e560cfa | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/nGENE Proj/TimeDate.cpp | 52040ed8f14ac2a0d34ddee7ddfb5590425d6012 | []
| no_license | svn2github/ngene | b2cddacf7ec035aa681d5b8989feab3383dac012 | 61850134a354816161859fe86c2907c8e73dc113 | refs/heads/master | 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,854 | cpp | /*
---------------------------------------------------------------------------
This source file is part of nGENE Tech.
Copyright (c) 2006- Wojciech Toman
This program is free software.
File: TimeDate.cpp
Version: 0.03
---------------------------------------------------------------------------
*/
#include "PrecompiledHeaders.h"
#include "TimeDate.h"
#include "FuncSplit.h"
namespace nGENE
{
// Initialize static members
TypeInfo TimeDate::Type(L"TimeDate", NULL);
TimeDate::TimeDate():
seconds(0),
minutes(0),
hours(0),
month(1),
year(1),
week_day(1),
month_day(1),
year_day(1)
{
}
//----------------------------------------------------------------------
TimeDate::TimeDate(const tm& _time):
seconds(_time.tm_sec),
minutes(_time.tm_min),
hours(_time.tm_hour),
month(_time.tm_mon + 1),
year(_time.tm_year + 1900),
week_day(_time.tm_wday + 1),
month_day(_time.tm_mday),
year_day(_time.tm_yday + 1)
{
}
//----------------------------------------------------------------------
TimeDate::~TimeDate()
{
}
//----------------------------------------------------------------------
void TimeDate::reset()
{
seconds = 0;
minutes = 0;
hours = 0;
month = 1;
year = 1;
week_day = 1;
month_day = 1;
year_day = 1;
}
//----------------------------------------------------------------------
tm TimeDate::getCurrentTime()
{
time_t rawTime;
time(&rawTime);
tm localTime;
localTime = *localtime(&rawTime);
return localTime;
}
//----------------------------------------------------------------------
TimeDate TimeDate::now()
{
TimeDate time = getCurrentTime();
return time;
}
//----------------------------------------------------------------------
TimeDate TimeDate::today()
{
TimeDate time = now();
time.seconds = time.minutes = time.hours = 0;
return time;
}
//----------------------------------------------------------------------
TimeDate TimeDate::from_now(const TimeDate& _time)
{
TimeDate time = now();
time += _time;
return time;
}
//----------------------------------------------------------------------
TimeDate TimeDate::ago(const TimeDate& _time)
{
TimeDate time = now();
time -= _time;
return time;
}
//----------------------------------------------------------------------
TimeDate TimeDate::since(const TimeDate& _time)
{
TimeDate time = now();
time -= _time;
return time;
}
//----------------------------------------------------------------------
TimeDate& TimeDate::operator+=(const TimeDate &rhs)
{
seconds += rhs.seconds;
if(seconds >= 60)
{
uint full = floor((float)seconds / 60);
minutes += full;
seconds -= full * 60;
}
minutes += rhs.minutes;
if(minutes >= 60)
{
uint full = floor((float)minutes / 60);
hours += full;
minutes -= full * 60;
}
hours += rhs.hours;
if(hours >= 24)
{
uint full = floor((float)hours / 24);
hours -= full * 24;
Maths::clamp_roll <uint>(week_day += full, 1, 7);
month_day += full;
year_day += full;
}
if(month_day > 31)
{
uint full = floor((float)month_day / 31);
month += full;
month_day -= full * 31;
}
month += rhs.month;
uint year_change = 0;
if(month > 12)
{
uint full = floor((float)month / 12);
year_change = full;
month -= full * 12;
}
if(year_day > 365)
{
uint full = floor((float)year_day / 365);
if(full > year_change)
year_change = full;
year_day -= full * 365;
}
year += (rhs.year + year_change);
return (*this);
}
//----------------------------------------------------------------------
TimeDate& TimeDate::operator-=(const TimeDate &rhs)
{
int tseconds = (int)seconds - rhs.seconds;
int tminutes = (int)minutes - rhs.minutes;
int thours = (int)hours - rhs.hours;
int tmonth = (int)month - rhs.month;
int tyear = (int)year - rhs.year;
int tmonth_day = month_day;
int tyear_day = year_day;
if(tseconds < 0)
{
uint full = ceil((float)Maths::abs <int>(tseconds) / 60);
seconds = full * 60 - Maths::abs <int>(tseconds);
tminutes -= full;
}
else
seconds = (uint)tseconds;
if(tminutes < 0)
{
uint full = ceil((float)Maths::abs <int>(tminutes) / 60);
minutes = full * 60 - Maths::abs <int>(tminutes);
thours -= full;
}
else
minutes = (uint)tminutes;
if(thours < 0)
{
uint full = ceil((float)Maths::abs <int>(thours) / 24);
hours = full * 24 - Maths::abs <int>(thours);
int tweek_day = (int)week_day - full;
Maths::clamp_roll <int>(tweek_day, 1, 7);
week_day = tweek_day;
tmonth_day -= full;
tyear_day -= full;
}
else
hours = (uint)thours;
if(tmonth_day < 1)
{
uint full = ceil((float)Maths::abs <int>(tmonth_day) / 31);
month_day = full * 31 - Maths::abs <int>(tmonth_day);
if(!month_day)
{
month_day = 31;
full = 1;
}
tmonth -= full;
}
else
month_day = (uint)tmonth_day;
uint year_change = 0;
if(tmonth < 1)
{
uint full = ceil((float)Maths::abs <int>(tmonth) / 12);
month = full * 12 - Maths::abs <int>(tmonth);
if(!month)
{
month = 12;
full = 1;
}
year_change = full;
}
else
month = (uint)tmonth;
if(tyear_day < 1)
{
uint full = ceil((float)Maths::abs <int>(tyear_day) / 365);
year_day = full * 31 - Maths::abs <int>(tyear_day);
if(!year_day)
{
year_day = 365;
full = 1;
}
if(full > year_change)
year_change = full;
}
else
year_day = (uint)tyear_day;
tyear -= (rhs.year + year_change);
if(tyear < 1)
{
Log::log(LET_WARNING, L"nGENE", __WFILE__, __WFUNCTION__, __LINE__,
L"Invalid date. Year is less than 1");
reset();
}
else
year = (uint)tyear;
return (*this);
}
//----------------------------------------------------------------------
TimeDate::operator string() const
{
ostringstream buffer;
buffer << setw(2) << setfill('0') << hours << ":" <<
setw(2) << setfill('0') << minutes << ":" <<
setw(2) << setfill('0') << seconds << " " <<
setw(2) << setfill('0') << month_day << "-" <<
setw(2) << setfill('0') << month << "-" <<
setw(4) << setfill('0') << year;
return buffer.str();
}
//----------------------------------------------------------------------
TimeDate::operator wstring() const
{
wstringstream buffer;
buffer << setw(2) << setfill(L'0') << hours << ":" <<
setw(2) << setfill(L'0') << minutes << ":" <<
setw(2) << setfill(L'0') << seconds << " " <<
setw(2) << setfill(L'0') << month_day << "-" <<
setw(2) << setfill(L'0') << month << "-" <<
setw(4) << setfill(L'0') << year;
return buffer.str();
}
//----------------------------------------------------------------------
void TimeDate::fromString(const string& _string)
{
vector <string> vecValues;
FuncSplit <string> tokenizer;
tokenizer(_string, vecValues, " ,;");
if(vecValues.size() == 6)
{
vector <string>::iterator iter = vecValues.begin();
hours = atoi((iter++)->c_str());
minutes = atoi((iter++)->c_str());
seconds = atoi((iter++)->c_str());
month_day = atoi((iter++)->c_str());
month = atoi((iter++)->c_str());
year = atoi((iter++)->c_str());
}
}
//----------------------------------------------------------------------
string TimeDate::toString()
{
stringstream buffer;
buffer << hours << " " << minutes << " " <<
seconds << " " << month_day << " " <<
month << " " << year;
return buffer.str();
}
//----------------------------------------------------------------------
} | [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
]
| [
[
[
1,
328
]
]
]
|
18b0dc5e3a4d1c46290c87b0e583aea9655421ca | 39d36b98402c4ad75aadee357295b92b2f0c0d3d | /src/fceu/utils/endian.h | 40b17263dc72e651784d9b712c628d266518768b | []
| no_license | xxsl/fceux-ps3 | 9eda7c1ee49e69f14b695ddda904b1cc3a79d51a | dc0674a4b8e8c52af6969c8d59330c072486107c | refs/heads/master | 2021-01-20T04:26:05.430450 | 2011-01-02T21:22:47 | 2011-01-02T21:22:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,944 | h | #ifndef __FCEU_ENDIAN
#define __FCEU_ENDIAN
#ifdef GEKKO
#ifdef __cplusplus
#include <iosfwd>
#include <stdio.h>
#include "../types.h"
#include "../emufile.h"
class EMUFILE;
inline uint64 double_to_u64(double d) {
union {
uint64 a;
double b;
} fuxor;
fuxor.b = d;
return fuxor.a;
}
inline double u64_to_double(uint64 u) {
union {
uint64 a;
double b;
} fuxor;
fuxor.a = u;
return fuxor.b;
}
inline uint32 float_to_u32(float f) {
union {
uint32 a;
float b;
} fuxor;
fuxor.b = f;
return fuxor.a;
}
inline float u32_to_float(uint32 u) {
union {
uint32 a;
float b;
} fuxor;
fuxor.a = u;
return fuxor.b;
}
int write16le(uint16 b, FILE *fp);
int write32le(uint32 b, FILE *fp);
int write32le(uint32 b, std::ostream* os);
int write64le(uint64 b, std::ostream* os);
int read64le(uint64 *Bufo, std::istream *is);
int read32le(uint32 *Bufo, std::istream *is);
int read32le(uint32 *Bufo, FILE *fp);
int read16le(uint16 *Bufo, std::istream *is);
void FlipByteOrder(uint8 *src, uint32 count);
void FCEU_en32lsb(uint8 *, uint32);
void FCEU_en16lsb(uint8* buf, uint16 val);
uint64 FCEU_de64lsb(uint8 *morp);
uint32 FCEU_de32lsb(uint8 *morp);
uint16 FCEU_de16lsb(uint8 *morp);
//well. just for the sake of consistency
int write8le(uint8 b, EMUFILE *fp);
inline int write8le(uint8* b, EMUFILE *fp) { return write8le(*b,fp); }
int write16le(uint16 b, EMUFILE* os);
int write32le(uint32 b, EMUFILE* os);
int write64le(uint64 b, EMUFILE* os);
inline int write_double_le(double b, EMUFILE*is) { uint64 temp = double_to_u64(b); int ret = write64le(temp,is); return ret; }
int read8le(uint8 *Bufo, EMUFILE*is);
int read16le(uint16 *Bufo, EMUFILE*is);
inline int read16le(int16 *Bufo, EMUFILE*is) { return read16le((uint16*)Bufo,is); }
int read32le(uint32 *Bufo, EMUFILE*is);
inline int read32le(int32 *Bufo, EMUFILE*is) { return read32le((uint32*)Bufo,is); }
int read64le(uint64 *Bufo, EMUFILE*is);
inline int read_double_le(double *Bufo, EMUFILE*is) { uint64 temp; int ret = read64le(&temp,is); *Bufo = u64_to_double(temp); return ret; }
template<typename T>
int readle(T *Bufo, EMUFILE*is)
{
CTASSERT(sizeof(T)==1||sizeof(T)==2||sizeof(T)==4||sizeof(T)==8);
switch(sizeof(T)) {
case 1: return read8le((uint8*)Bufo,is);
case 2: return read16le((uint16*)Bufo,is);
case 4: return read32le((uint32*)Bufo,is);
case 8: return read64le((uint64*)Bufo,is);
default:
return 0;
}
}
template<typename T>
int writele(T *Bufo, EMUFILE*os)
{
CTASSERT(sizeof(T)==1||sizeof(T)==2||sizeof(T)==4||sizeof(T)==8);
switch(sizeof(T)) {
case 1: return write8le((uint8*)Bufo,os);
case 2: return write16le((uint16*)Bufo,os);
case 4: return write32le((uint32*)Bufo,os);
case 8: return write64le((uint64*)Bufo,os);
default:
return 0;
}
}
#endif // __cplusplus
#endif // GEKKO
#endif //__FCEU_ENDIAN
| [
"[email protected]"
]
| [
[
[
1,
115
]
]
]
|
6b17434d26949729e7310142ded8e56818b7ca96 | 1c9f99b2b2e3835038aba7ec0abc3a228e24a558 | /Projects/elastix/elastix_sources_v4/src/Components/Transforms/TranslationTransform/elxTranslationTransform.hxx | 8626f83c60518ba08dc37b6b29f82c636095a205 | []
| no_license | mijc/Diploma | 95fa1b04801ba9afb6493b24b53383d0fbd00b33 | bae131ed74f1b344b219c0ffe0fffcd90306aeb8 | refs/heads/master | 2021-01-18T13:57:42.223466 | 2011-02-15T14:19:49 | 2011-02-15T14:19:49 | 1,369,569 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,694 | hxx | /*======================================================================
This file is part of the elastix software.
Copyright (c) University Medical Center Utrecht. All rights reserved.
See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for
details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
======================================================================*/
#ifndef __elxTranslationTransform_HXX_
#define __elxTranslationTransform_HXX_
#include "elxTranslationTransform.h"
namespace elastix
{
using namespace itk;
/**
* ********************* Constructor ****************************
*/
template <class TElastix>
TranslationTransformElastix<TElastix>
::TranslationTransformElastix()
{
this->m_TranslationTransform =
TranslationTransformType::New();
this->SetCurrentTransform( this->m_TranslationTransform );
} // end Constructor
/*
* ******************* BeforeRegistration ***********************
*/
template <class TElastix>
void TranslationTransformElastix<TElastix>
::BeforeRegistration(void)
{
/** Give initial parameters to this->m_Registration.*/
this->InitializeTransform();
} // end BeforeRegistration
/**
* ************************* InitializeTransform *********************
*/
template <class TElastix>
void TranslationTransformElastix<TElastix>
::InitializeTransform( void )
{
/** Set all parameters to zero (no translation */
this->m_TranslationTransform->SetIdentity();
/** Check if user wants automatic transform initialization; false by default. */
std::string automaticTransformInitializationString("false");
bool automaticTransformInitialization = false;
this->m_Configuration->ReadParameter(
automaticTransformInitializationString,
"AutomaticTransformInitialization", 0);
if ( (automaticTransformInitializationString == "true") &&
(this->Superclass1::GetInitialTransform() == 0) )
{
automaticTransformInitialization = true;
}
/**
* Run the itkTransformInitializer if:
* the user asked for AutomaticTransformInitialization
*/
if ( automaticTransformInitialization )
{
/** Use the TransformInitializer to determine an initial translation */
TransformInitializerPointer transformInitializer =
TransformInitializerType::New();
transformInitializer->SetFixedImage(
this->m_Registration->GetAsITKBaseType()->GetFixedImage() );
transformInitializer->SetMovingImage(
this->m_Registration->GetAsITKBaseType()->GetMovingImage() );
transformInitializer->SetTransform(this->m_TranslationTransform);
/** Select the method of initialization. Default: "GeometricalCenter". */
transformInitializer->GeometryOn();
std::string method = "GeometricalCenter";
this->m_Configuration->ReadParameter( method,
"AutomaticTransformInitializationMethod", 0 );
if ( method == "CenterOfGravity" )
{
transformInitializer->MomentsOn();
}
transformInitializer->InitializeTransform();
}
/** Set the initial parameters in this->m_Registration.*/
this->m_Registration->GetAsITKBaseType()->
SetInitialTransformParameters( this->GetParameters() );
} // end InitializeTransform
} // end namespace elastix
#endif // end #ifndef __elxTranslationTransform_HXX_
| [
"[email protected]"
]
| [
[
[
1,
116
]
]
]
|
71ad23fe853f19b20911ddc40afa7f17eb93b051 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libc/testifioctls/src/tifioctlsserver.cpp | 781ddcd84c2534efbac4a84b781c1bcda780f52d | []
| no_license | SymbianSource/oss.FCL.sftools.ana.compatanamdw | a6a8abf9ef7ad71021d43b7f2b2076b504d4445e | 1169475bbf82ebb763de36686d144336fcf9d93b | refs/heads/master | 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,021 | cpp | /*
* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
/*
* ==============================================================================
* Name : tifioctlsserver.cpp
* Part of : testifioctls
*
* Description : ?Description
*
*/
#include <c32comm.h>
#if defined (__WINS__)
#define PDD_NAME _L("ECDRV")
#else
#define PDD_NAME _L("EUART1")
#define PDD2_NAME _L("EUART2")
#define PDD3_NAME _L("EUART3")
#define PDD4_NAME _L("EUART4")
#endif
#define LDD_NAME _L("ECOMM")
/**
* @file
*
* Pipe test server implementation
*/
#include "tifioctlsserver.h"
#include "tifioctls.h"
_LIT(KServerName, "tifioctls");
CIfioctlsTestServer* CIfioctlsTestServer::NewL()
{
CIfioctlsTestServer *server = new(ELeave) CIfioctlsTestServer();
CleanupStack::PushL(server);
server->ConstructL(KServerName);
CleanupStack::Pop(server);
return server;
}
static void InitCommsL()
{
TInt ret = User::LoadPhysicalDevice(PDD_NAME);
User::LeaveIfError(ret == KErrAlreadyExists?KErrNone:ret);
#ifndef __WINS__
ret = User::LoadPhysicalDevice(PDD2_NAME);
ret = User::LoadPhysicalDevice(PDD3_NAME);
ret = User::LoadPhysicalDevice(PDD4_NAME);
#endif
ret = User::LoadLogicalDevice(LDD_NAME);
User::LeaveIfError(ret == KErrAlreadyExists?KErrNone:ret);
ret = StartC32();
User::LeaveIfError(ret == KErrAlreadyExists?KErrNone:ret);
}
LOCAL_C void MainL()
{
// Leave the hooks in for platform security
#if (defined __DATA_CAGING__)
RProcess().DataCaging(RProcess::EDataCagingOn);
RProcess().SecureApi(RProcess::ESecureApiOn);
#endif
//InitCommsL();
CActiveScheduler* sched=NULL;
sched=new(ELeave) CActiveScheduler;
CActiveScheduler::Install(sched);
CIfioctlsTestServer* server = NULL;
// Create the CTestServer derived server
TRAPD(err, server = CIfioctlsTestServer::NewL());
if(!err)
{
// Sync with the client and enter the active scheduler
RProcess::Rendezvous(KErrNone);
sched->Start();
}
delete server;
delete sched;
}
/**
* Server entry point
* @return Standard Epoc error code on exit
*/
TInt main()
{
__UHEAP_MARK;
CTrapCleanup* cleanup = CTrapCleanup::New();
if(cleanup == NULL)
{
return KErrNoMemory;
}
TRAP_IGNORE(MainL());
delete cleanup;
__UHEAP_MARKEND;
return KErrNone;
}
CTestStep* CIfioctlsTestServer::CreateTestStep(const TDesC& aStepName)
{
CTestStep* testStep = NULL;
// This server creates just one step but create as many as you want
// They are created "just in time" when the worker thread is created
// install steps
if(aStepName == KExampleL)
{
testStep = new CTestIfioctls(aStepName);
}
if(aStepName == KListInterfaces)
{
testStep = new CTestIfioctls(aStepName);
}
if(aStepName == KCreateManyActiveInterfaces)
{
testStep = new CTestIfioctls(aStepName);
}
if(aStepName == KChooseInterface)
{
testStep = new CTestIfioctls(aStepName);
}
if(aStepName == KChooseActiveInterface)
{
testStep = new CTestIfioctls(aStepName);
}
if(aStepName == KTestIfNameIndex)
{
testStep = new CTestIfioctls(aStepName);
}
if(aStepName == KTestIfIndexToName)
{
testStep = new CTestIfioctls(aStepName);
}
if(aStepName == KTestIfNameToIndex)
{
testStep = new CTestIfioctls(aStepName);
}
if(aStepName == KTestSiocGIfIndex)
{
testStep = new CTestIfioctls(aStepName);
}
if(aStepName == KConnectToIpUsingConnection )
{
testStep = new CTestIfioctls(aStepName);
}
if(aStepName == KSendtoIpUsingConnection)
{
testStep = new CTestIfioctls(aStepName);
}
if(aStepName == KConnectToUrlUsingConnection)
{
testStep = new CTestIfioctls(aStepName);
}
if(aStepName == Kioctltest)
{
testStep = new CTestIfioctls(aStepName);
}
if(aStepName == Kreadtest)
{
testStep = new CTestIfioctls(aStepName);
}
if(aStepName == KTestAddDelRoute)
{
testStep = new CTestIfioctls(aStepName);
}
if(aStepName == KTestAddDelRouteNegative1)
{
testStep = new CTestIfioctls(aStepName);
}
if(aStepName == KTestAddDelRouteNegative2)
{
testStep = new CTestIfioctls(aStepName);
}
if(aStepName == KTestMacAddress)
{
testStep = new CTestIfioctls(aStepName);
}
if(aStepName == KTestMacAddressNegative1)
{
testStep = new CTestIfioctls(aStepName);
}
if(aStepName == KTestioctlfile)
{
testStep = new CTestIfioctls(aStepName);
}
if(aStepName == KTestioctl1)
{
testStep = new CTestIfioctls(aStepName);
}
return testStep;
}
| [
"none@none"
]
| [
[
[
1,
216
]
]
]
|
38a6a61f6fe9e95e872a0aea35dbc20855d41d2f | 5ac13fa1746046451f1989b5b8734f40d6445322 | /minimangalore/Nebula2/code/mangalore/msg/animstop.cc | 930e647ac13772129755b6755294af8c558951c9 | []
| 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 | 404 | cc | //------------------------------------------------------------------------------
// msg/animstop.cc
// (C) 2005 Radon Labs GmbH
//------------------------------------------------------------------------------
#include "msg/animstop.h"
namespace Message
{
ImplementRtti(Message::AnimStop, Message::Msg);
ImplementFactory(Message::AnimStop);
ImplementMsgId(AnimStop);
} // namespace Message
| [
"BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c"
]
| [
[
[
1,
12
]
]
]
|
1c473204d8499e41e988d374a9a7174829fd3cb4 | 7b379862f58f587d9327db829ae4c6493b745bb1 | /JuceLibraryCode/modules/juce_audio_basics/midi/juce_MidiKeyboardState.cpp | bccad6c6d3f151108b7e1dd0f16bee43e509bb01 | []
| no_license | owenvallis/Nomestate | 75e844e8ab68933d481640c12019f0d734c62065 | 7fe7c06c2893421a3c77b5180e5f27ab61dd0ffd | refs/heads/master | 2021-01-19T07:35:14.301832 | 2011-12-28T07:42:50 | 2011-12-28T07:42:50 | 2,950,072 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,237 | cpp | /*
==============================================================================
This file is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright 2004-11 by Raw Material Software Ltd.
------------------------------------------------------------------------------
JUCE can be redistributed and/or modified under the terms of the GNU General
Public License (Version 2), as published by the Free Software Foundation.
A copy of the license is included in the JUCE distribution, or can be found
online at www.gnu.org/licenses.
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.rawmaterialsoftware.com/juce for more information.
==============================================================================
*/
BEGIN_JUCE_NAMESPACE
//==============================================================================
MidiKeyboardState::MidiKeyboardState()
{
zerostruct (noteStates);
}
MidiKeyboardState::~MidiKeyboardState()
{
}
//==============================================================================
void MidiKeyboardState::reset()
{
const ScopedLock sl (lock);
zerostruct (noteStates);
eventsToAdd.clear();
}
bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const noexcept
{
jassert (midiChannel >= 0 && midiChannel <= 16);
return isPositiveAndBelow (n, (int) 128)
&& (noteStates[n] & (1 << (midiChannel - 1))) != 0;
}
bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const noexcept
{
return isPositiveAndBelow (n, (int) 128)
&& (noteStates[n] & midiChannelMask) != 0;
}
void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
{
jassert (midiChannel >= 0 && midiChannel <= 16);
jassert (isPositiveAndBelow (midiNoteNumber, (int) 128));
const ScopedLock sl (lock);
if (isPositiveAndBelow (midiNoteNumber, (int) 128))
{
const int timeNow = (int) Time::getMillisecondCounter();
eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
eventsToAdd.clear (0, timeNow - 500);
noteOnInternal (midiChannel, midiNoteNumber, velocity);
}
}
void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
{
if (isPositiveAndBelow (midiNoteNumber, (int) 128))
{
noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
for (int i = listeners.size(); --i >= 0;)
listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
}
}
void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
{
const ScopedLock sl (lock);
if (isNoteOn (midiChannel, midiNoteNumber))
{
const int timeNow = (int) Time::getMillisecondCounter();
eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
eventsToAdd.clear (0, timeNow - 500);
noteOffInternal (midiChannel, midiNoteNumber);
}
}
void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
{
if (isNoteOn (midiChannel, midiNoteNumber))
{
noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
for (int i = listeners.size(); --i >= 0;)
listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
}
}
void MidiKeyboardState::allNotesOff (const int midiChannel)
{
const ScopedLock sl (lock);
if (midiChannel <= 0)
{
for (int i = 1; i <= 16; ++i)
allNotesOff (i);
}
else
{
for (int i = 0; i < 128; ++i)
noteOff (midiChannel, i);
}
}
void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
{
if (message.isNoteOn())
{
noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
}
else if (message.isNoteOff())
{
noteOffInternal (message.getChannel(), message.getNoteNumber());
}
else if (message.isAllNotesOff())
{
for (int i = 0; i < 128; ++i)
noteOffInternal (message.getChannel(), i);
}
}
void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
const int startSample,
const int numSamples,
const bool injectIndirectEvents)
{
MidiBuffer::Iterator i (buffer);
MidiMessage message (0xf4, 0.0);
int time;
const ScopedLock sl (lock);
while (i.getNextEvent (message, time))
processNextMidiEvent (message);
if (injectIndirectEvents)
{
MidiBuffer::Iterator i2 (eventsToAdd);
const int firstEventToAdd = eventsToAdd.getFirstEventTime();
const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
while (i2.getNextEvent (message, time))
{
const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
buffer.addEvent (message, startSample + pos);
}
}
eventsToAdd.clear();
}
//==============================================================================
void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener)
{
const ScopedLock sl (lock);
listeners.addIfNotAlreadyThere (listener);
}
void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener)
{
const ScopedLock sl (lock);
listeners.removeValue (listener);
}
END_JUCE_NAMESPACE
| [
"ow3nskip"
]
| [
[
[
1,
190
]
]
]
|
61b54dcd5f049e6c1ad96f7da899f7667b06d0e8 | 0163f13e71a728020435702ab2530591d919c908 | /2sat/sat.cpp | 0afde8ea8f31cb839fa76780ff0d5882d0dc89ed | []
| no_license | mishun/aptusat | 94a02490457233c503b8b7b2ef0917f03d33e160 | a095ae95d15cb8e5e873fe933af2fefe96ab9a63 | refs/heads/master | 2021-01-15T13:15:21.348013 | 2010-04-19T15:52:05 | 2010-04-19T15:52:05 | 32,115,578 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,639 | cpp | #include <cassert>
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
#include <utility>
#include <iostream>
const int N = 10000;
bool ok = true;
std::vector<int> impl[N];
int permval[N], tempval[N];
int asstime[N];
int current_time = 0;
int n, m;
bool incPropUnit(int x)
{
if(permval[x] != 0)
{
if(permval[x] == 1)
return true;
else
{
ok = false;
return false;
}
}
permval[x] = 1;
permval[x ^ 1] = -1;
for(int i = 0; i < (int)impl[x].size(); i++)
if(!incPropUnit(impl[x] [i]))
return false;
return true;
}
void incTempPropUnit(int x)
{
if(tempval[x] == -1 && asstime[x ^ 1] == current_time)
{
incPropUnit(x);
return;
}
tempval[x] = 1;
tempval[x ^ 1] = -1;
asstime[x] = current_time;
asstime[x ^ 1] = current_time;
for(int i = 0; ok && i < (int)impl[x].size() && permval[x] == 0; i++)
{
int y = impl[x] [i];
if(permval[y] == 0 && !(asstime[y] == current_time && tempval[y] == 1))
incTempPropUnit(y);
}
}
bool incBinSat(int x, int y)
{
impl[x ^ 1].push_back(y);
impl[y ^ 1].push_back(x);
current_time++;
if(x == y)
return incPropUnit(x);
if(permval[x] == 1 || permval[y] == 1)
return ok;
if(permval[x] == -1)
return incPropUnit(y);
if(permval[y] == -1)
return incPropUnit(x);
if(tempval[x] == 1 || tempval[y] == 1)
return ok;
incTempPropUnit(x);
return ok;
}
std::vector< std::pair<int, int> > clauses;
bool check()
{
for(int i = 0; i < (int)clauses.size(); i++)
{
int a = clauses[i].first;
int b = clauses[i].second;
if(!((permval[a] == 1 || (permval[a] == 0 && tempval[a] == 1)) || (permval[b] == 1 || (permval[b] == 0 && tempval[b] == 1))))
return false;
}
return true;
}
int main()
{
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
scanf("%i %i", &n, &m);
for(int i = 0; i < m; i++)
{
int a, b;
scanf("%i %i", &a, &b);
assert(a != 0);
if(b == 0)
b = a;
else
{
int tmp;
scanf("%i", &tmp);
assert(tmp == 0);
}
if(a < 0)
a = 2 * (-a - 1) + 1;
else
a = 2 * (a - 1);
if(b < 0)
b = 2 * (-b - 1) + 1;
else
b = 2 * (b - 1);
clauses.push_back(std::make_pair(a, b));
incBinSat(a, b);
}
if(ok)
{
assert(check());
printf("Yes\n");
for(int i = 0; i < n; i++)
if(permval[2 * i] == 1)
printf("%i ", i + 1);
else if(permval[2 * i] == 0 && tempval[2 * i] == 1)
printf("%i ", i + 1);
printf("0\n");
}
else
{
printf("No\n");
}
return 0;
}
| [
"[email protected]@feb4d0a8-fdf0-11dd-85c2-bb0660c75f22"
]
| [
[
[
1,
163
]
]
]
|
d2a1a9b0abf7b852e2aa25dfe866efa68541784b | 33f59b1ba6b12c2dd3080b24830331c37bba9fe2 | /Depend/Foundation/Mathematics/Wm4Cone3.h | eb254ae6e1300f1e795a222c1efec709fc27a6e2 | []
| no_license | daleaddink/flagship3d | 4835c223fe1b6429c12e325770c14679c42ae3c6 | 6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a | refs/heads/master | 2021-01-15T16:29:12.196094 | 2009-11-01T10:18:11 | 2009-11-01T10:18:11 | 37,734,654 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,476 | h | // Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// The Wild Magic Version 4 Foundation Library source code is supplied
// under the terms of the license agreement
// http://www.geometrictools.com/License/Wm4FoundationLicense.pdf
// and may not be copied or disclosed except in accordance with the terms
// of that agreement.
#ifndef WM4CONE3_H
#define WM4CONE3_H
#include "Wm4FoundationLIB.h"
#include "Wm4Vector3.h"
namespace Wm4
{
template <class Real>
class Cone3
{
public:
// An acute cone is Dot(A,X-V) = |X-V| cos(T) where V is the vertex, A
// is the unit-length direction of the axis of the cone, and T is the
// cone angle with 0 < T < PI/2. The cone interior is defined by the
// inequality Dot(A,X-V) >= |X-V| cos(T). Since cos(T) > 0, we can avoid
// computing square roots. The solid cone is defined by the inequality
// Dot(A,X-V)^2 >= Dot(X-V,X-V) cos(T)^2.
// construction
Cone3 (); // uninitialized
Cone3 (const Vector3<Real>& rkVertex, const Vector3<Real>& rkAxis,
Real fAngle);
Cone3 (const Vector3<Real>& rkVertex, const Vector3<Real>& rkAxis,
Real fCosAngle, Real fSinAngle);
Vector3<Real> Vertex;
Vector3<Real> Axis;
Real CosAngle, SinAngle; // cos(T), sin(T)
};
#include "Wm4Cone3.inl"
typedef Cone3<float> Cone3f;
typedef Cone3<double> Cone3d;
}
#endif
| [
"yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa"
]
| [
[
[
1,
50
]
]
]
|
817fa7e03e9d4d6ba41a1f7d3d40710c58022c29 | 34d807d2bc616a23486af858647301af98b6296e | /ccbot/bnetprotocol.cpp | 5259cef0b8c0d757bb227999eaf173cd09ab112e | [
"LicenseRef-scancode-warranty-disclaimer"
]
| no_license | Mofsy/ccbot | 65cf5bb08c211cdce2001a36db8968844fce2e05 | f171351c99cce4059a82a23399e7c4587f37beb5 | refs/heads/master | 2020-12-28T21:39:19.297873 | 2011-03-01T00:44:46 | 2011-03-01T00:44:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30,976 | cpp | /*
Copyright [2009] [Joško Nikolić]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
HEAVILY MODIFIED PROJECT BASED ON GHOST++: http://forum.codelain.com
GHOST++ CODE IS PORTED FROM THE ORIGINAL GHOST PROJECT: http://ghost.pwner.org/
*/
#include "ccbot.h"
#include "util.h"
#include "bnetprotocol.h"
CBNETProtocol :: CBNETProtocol( )
{
unsigned char ClientToken[] = { 220, 1, 203, 7 };
m_ClientToken = UTIL_CreateByteArray( ClientToken, 4 );
}
CBNETProtocol :: ~CBNETProtocol( )
{
}
///////////////////////
// RECEIVE FUNCTIONS //
///////////////////////
bool CBNETProtocol :: RECEIVE_SID_NULL( BYTEARRAY data )
{
// DEBUG_Print( "RECEIVED SID_NULL" );
// DEBUG_Print( data );
// 2 bytes -> Header
// 2 bytes -> Length
return ValidateLength( data );
}
bool CBNETProtocol :: RECEIVE_SID_ENTERCHAT( BYTEARRAY data )
{
// DEBUG_Print( "RECEIVED SID_ENTERCHAT" );
// DEBUG_Print( data );
// 2 bytes -> Header
// 2 bytes -> Length
// null terminated string -> UniqueName
if( ValidateLength( data ) && data.size( ) >= 5 )
{
m_UniqueName = UTIL_ExtractCString( data, 4 );
return true;
}
return false;
}
CIncomingChatEvent *CBNETProtocol :: RECEIVE_SID_CHATEVENT( BYTEARRAY data )
{
// DEBUG_Print( "RECEIVED SID_CHATEVENT" );
// DEBUG_Print( data );
// 2 bytes -> Header
// 2 bytes -> Length
// 4 bytes -> EventID
// 4 bytes -> User Flags
// 4 bytes -> Ping
// 12 bytes -> ???
// null terminated string -> User
// null terminated string -> Message
if( ValidateLength( data ) && data.size( ) >= 29 )
{
BYTEARRAY EventID = BYTEARRAY( data.begin( ) + 4, data.begin( ) + 8 );
BYTEARRAY UserFlags = BYTEARRAY( data.begin( ) + 8, data.begin( ) + 12 );
BYTEARRAY Ping = BYTEARRAY( data.begin( ) + 12, data.begin( ) + 16 );
BYTEARRAY User = UTIL_ExtractCString( data, 28 );
BYTEARRAY Message = UTIL_ExtractCString( data, User.size( ) + 29 );
switch( UTIL_ByteArrayToUInt32( EventID, false ) )
{
case CBNETProtocol :: EID_SHOWUSER:
case CBNETProtocol :: EID_JOIN:
case CBNETProtocol :: EID_LEAVE:
case CBNETProtocol :: EID_WHISPER:
case CBNETProtocol :: EID_TALK:
case CBNETProtocol :: EID_BROADCAST:
case CBNETProtocol :: EID_CHANNEL:
case CBNETProtocol :: EID_USERFLAGS:
case CBNETProtocol :: EID_WHISPERSENT:
case CBNETProtocol :: EID_CHANNELFULL:
case CBNETProtocol :: EID_CHANNELDOESNOTEXIST:
case CBNETProtocol :: EID_CHANNELRESTRICTED:
case CBNETProtocol :: EID_INFO:
case CBNETProtocol :: EID_ERROR:
case CBNETProtocol :: EID_EMOTE:
return new CIncomingChatEvent( (CBNETProtocol :: IncomingChatEvent)UTIL_ByteArrayToUInt32( EventID, false ),
UTIL_ByteArrayToUInt32( UserFlags, false ),
UTIL_ByteArrayToUInt32( Ping, false ),
string( User.begin( ), User.end( ) ),
string( Message.begin( ), Message.end( ) )
);
}
}
return NULL;
}
bool CBNETProtocol :: RECEIVE_SID_FLOODDETECTED( BYTEARRAY data )
{
// DEBUG_Print( "RECEIVED SID_FLOODDETECTED" );
// DEBUG_Print( data );
// 2 bytes -> Header
// 2 bytes -> Length
if( ValidateLength( data ) && data.size( ) == 4 )
return true;
return false;
}
bool CBNETProtocol :: RECEIVE_SID_CHECKAD( BYTEARRAY data )
{
// DEBUG_Print( "RECEIVED SID_CHECKAD" );
// DEBUG_Print( data );
// 2 bytes -> Header
// 2 bytes -> Length
return ValidateLength( data );
}
BYTEARRAY CBNETProtocol :: RECEIVE_SID_PING( BYTEARRAY data )
{
// DEBUG_Print( "RECEIVED SID_PING" );
// DEBUG_Print( data );
// 2 bytes -> Header
// 2 bytes -> Length
// 4 bytes -> Ping
if( ValidateLength( data ) && data.size( ) >= 8 )
return BYTEARRAY( data.begin( ) + 4, data.begin( ) + 8 );
return BYTEARRAY( );
}
bool CBNETProtocol :: RECEIVE_SID_LOGONRESPONSE( BYTEARRAY data )
{
// DEBUG_Print( "RECEIVED SID_LOGONRESPONSE" );
// DEBUG_Print( data );
// 2 bytes -> Header
// 2 bytes -> Length
// 4 bytes -> Status
if( ValidateLength( data ) && data.size( ) >= 8 )
{
BYTEARRAY Status = BYTEARRAY( data.begin( ) + 4, data.begin( ) + 8 );
if( UTIL_ByteArrayToUInt32( Status, false ) == 1 )
return true;
}
return false;
}
bool CBNETProtocol :: RECEIVE_SID_AUTH_INFO( BYTEARRAY data )
{
// DEBUG_Print( "RECEIVED SID_AUTH_INFO" );
// DEBUG_Print( data );
// 2 bytes -> Header
// 2 bytes -> Length
// 4 bytes -> LogonType
// 4 bytes -> ServerToken
// 4 bytes -> ???
// 8 bytes -> MPQFileTime
// null terminated string -> IX86VerFileName
// null terminated string -> ValueStringFormula
if( ValidateLength( data ) && data.size( ) >= 25 )
{
m_LogonType = BYTEARRAY( data.begin( ) + 4, data.begin( ) + 8 );
m_ServerToken = BYTEARRAY( data.begin( ) + 8, data.begin( ) + 12 );
m_MPQFileTime = BYTEARRAY( data.begin( ) + 16, data.begin( ) + 24 );
m_IX86VerFileName = UTIL_ExtractCString( data, 24 );
m_ValueStringFormula = UTIL_ExtractCString( data, m_IX86VerFileName.size( ) + 25 );
return true;
}
return false;
}
bool CBNETProtocol :: RECEIVE_SID_AUTH_CHECK( BYTEARRAY data )
{
// DEBUG_Print( "RECEIVED SID_AUTH_CHECK" );
// DEBUG_Print( data );
// 2 bytes -> Header
// 2 bytes -> Length
// 4 bytes -> KeyState
// null terminated string -> KeyStateDescription
if( ValidateLength( data ) && data.size( ) >= 9 )
{
m_KeyState = BYTEARRAY( data.begin( ) + 4, data.begin( ) + 8 );
m_KeyStateDescription = UTIL_ExtractCString( data, 8 );
if( UTIL_ByteArrayToUInt32( m_KeyState, false ) == KR_GOOD )
return true;
}
return false;
}
bool CBNETProtocol :: RECEIVE_SID_AUTH_ACCOUNTLOGON( BYTEARRAY data )
{
// DEBUG_Print( "RECEIVED SID_AUTH_ACCOUNTLOGON" );
// DEBUG_Print( data );
// 2 bytes -> Header
// 2 bytes -> Length
// 4 bytes -> Status
// if( Status == 0 )
// 32 bytes -> Salt
// 32 bytes -> ServerPublicKey
if( ValidateLength( data ) && data.size( ) >= 8 )
{
BYTEARRAY status = BYTEARRAY( data.begin( ) + 4, data.begin( ) + 8 );
if( UTIL_ByteArrayToUInt32( status, false ) == 0 && data.size( ) >= 72 )
{
m_Salt = BYTEARRAY( data.begin( ) + 8, data.begin( ) + 40 );
m_ServerPublicKey = BYTEARRAY( data.begin( ) + 40, data.begin( ) + 72 );
return true;
}
}
return false;
}
bool CBNETProtocol :: RECEIVE_SID_AUTH_ACCOUNTLOGONPROOF( BYTEARRAY data )
{
// DEBUG_Print( "RECEIVED SID_AUTH_ACCOUNTLOGONPROOF" );
// DEBUG_Print( data );
// 2 bytes -> Header
// 2 bytes -> Length
// 4 bytes -> Status
if( ValidateLength( data ) && data.size( ) >= 8 )
{
BYTEARRAY Status = BYTEARRAY( data.begin( ) + 4, data.begin( ) + 8 );
if( UTIL_ByteArrayToUInt32( Status, false ) == 0 )
return true;
}
return false;
}
int CBNETProtocol :: RECEIVE_SID_CLANINVITATION( BYTEARRAY data )
{
// DEBUG_Print( "RECEIVED SID_CLANINVITATION" );
// DEBUG_Print( data );
// 2 bytes -> Header
// 2 bytes -> Length
// 4 bytes -> Cookie
// 1 byte -> Result
if( ValidateLength( data ) && data.size( ) == 9 )
{
return data[8];
}
return -1;
}
int CBNETProtocol :: RECEIVE_SID_CLANREMOVEMEMBER( BYTEARRAY data )
{
// DEBUG_Print( "RECEIVED SID_CLANREMOVEMEMBER" );
// DEBUG_Print( data );
// 2 bytes -> Header
// 2 bytes -> Length
// 4 bytes -> Cookie
// 1 byte -> Result
if( ValidateLength( data ) && data.size( ) == 9 )
{
return data[8];
}
return -1;
}
vector<CIncomingClanList *> CBNETProtocol :: RECEIVE_SID_CLANMEMBERLIST( BYTEARRAY data )
{
// DEBUG_Print( "RECEIVED SID_CLANMEMBERLIST" );
// DEBUG_Print( data );
// 2 bytes -> Header
// 2 bytes -> Length
// 4 bytes -> ???
// 1 byte -> Total
// for( 1 .. Total )
// null term string -> Name
// 1 byte -> Rank
// 1 byte -> Status
// null term string -> Location
vector<CIncomingClanList *> ClanList;
if( ValidateLength( data ) && data.size( ) >= 9 )
{
unsigned int i = 9;
unsigned char Total = data[8];
while( Total > 0 )
{
--Total;
if( data.size( ) < i + 1 )
break;
BYTEARRAY Name = UTIL_ExtractCString( data, i );
i += Name.size( ) + 1;
if( data.size( ) < i + 3 )
break;
unsigned char Rank = data[i];
unsigned char Status = data[i + 1];
i += 2;
// in the original VB source the location string is read but discarded, so that's what I do here
BYTEARRAY Location = UTIL_ExtractCString( data, i );
i += Location.size( ) + 1;
ClanList.push_back( new CIncomingClanList( string( Name.begin( ), Name.end( ) ),
Rank,
Status ) );
}
}
return ClanList;
}
CIncomingClanList *CBNETProtocol :: RECEIVE_SID_CLANMEMBERSTATUSCHANGE( BYTEARRAY data )
{
// DEBUG_Print( "RECEIVED SID_CLANMEMBERSTATUSCHANGE" );
// DEBUG_Print( data );
// 2 bytes -> Header
// 2 bytes -> Length
// null terminated string -> Name
// 1 byte -> Rank
// 1 byte -> Status
// null terminated string -> Location
if( ValidateLength( data ) && data.size( ) >= 5 )
{
BYTEARRAY Name = UTIL_ExtractCString( data, 4 );
if( data.size( ) >= Name.size( ) + 7 )
{
unsigned char Rank = data[Name.size( ) + 5];
unsigned char Status = data[Name.size( ) + 6];
// in the original VB source the location string is read but discarded, so that's what I do here
BYTEARRAY Location = UTIL_ExtractCString( data, Name.size( ) + 7 );
return new CIncomingClanList( string( Name.begin( ), Name.end( ) ),
Rank,
Status );
}
}
return NULL;
}
bool CBNETProtocol :: RECEIVE_SID_CLANINVITATIONRESPONSE( BYTEARRAY data )
{
// DEBUG_Print( "RECEIVED SID_CLANINVITATIONRESPONSE" );
// DEBUG_Print( data );
// 2 bytes -> Header
// 2 bytes -> Length
// 4 bytes -> Cookie
// 4 bytes -> Clan Tag (Reversed)
// x bytes (null terminated string) -> Clan Name
// x bytes (null terminated string) -> Inviter Name
if( ValidateLength( data ) && data.size( ) >= 14 )
{
m_ClanTag = BYTEARRAY( data.begin( ) + 8, data.begin( ) + 12 );
m_ClanName = UTIL_ExtractCString( data, 12 );
m_Inviter = BYTEARRAY( data.begin( ) + 12 + m_ClanName.size( ), data.end( ) - 1 );
m_InviterStr = UTIL_ExtractCString( data, m_ClanName.size( ) + 13 );
return true;
}
return false;
}
int CBNETProtocol :: RECEIVE_SID_CLANMAKECHIEFTAIN( BYTEARRAY data )
{
// DEBUG_Print( "RECEIVED SID_CLANMAKECHIEFTAIN" );
// DEBUG_Print( data );
// 2 bytes -> Header
// 2 bytes -> Length
// 4 bytes -> Cookie
// 1 byte -> Status
if( ValidateLength( data ) && data.size( ) == 9 )
{
return data[8];
}
return false;
}
bool CBNETProtocol :: RECEIVE_SID_CLANCREATIONINVITATION( BYTEARRAY data )
{
// DEBUG_Print( "RECEIVED SID_CLANCREATIONINVITATION" );
// DEBUG_Print( data );
// 2 bytes -> Header
// 2 bytes -> Length
// 4 bytes -> Cookie
// 4 bytes -> Clan Tag (Reversed)
// x bytes (null terminated string) -> Clan Name
// x bytes (null terminated string) -> Inviter Name
// 1 byte -> Number of users invited
// x bytes (list of strings) -> List of users invited
if( ValidateLength( data ) && data.size( ) >= 16 )
{
m_ClanCreationTag = BYTEARRAY( data.begin( ) + 8, data.begin( ) + 12 );
m_ClanCreationName = UTIL_ExtractCString( data, 12 );
m_ClanCreator = UTIL_ExtractCString( data, m_ClanCreationName.size( ) + 13 );
return true;
}
return false;
}
////////////////////
// SEND FUNCTIONS //
////////////////////
BYTEARRAY CBNETProtocol :: SEND_PROTOCOL_INITIALIZE_SELECTOR( )
{
BYTEARRAY packet;
packet.push_back( 1 );
// DEBUG_Print( "SENT PROTOCOL_INITIALIZE_SELECTOR" );
// DEBUG_Print( packet );
return packet;
}
BYTEARRAY CBNETProtocol :: SEND_SID_NULL( )
{
BYTEARRAY packet;
packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant
packet.push_back( SID_NULL ); // SID_NULL
packet.push_back( 0 ); // packet length will be assigned later
packet.push_back( 0 ); // packet length will be assigned later
AssignLength( packet );
// DEBUG_Print( "SENT SID_NULL" );
// DEBUG_Print( packet );
return packet;
}
BYTEARRAY CBNETProtocol :: SEND_SID_ENTERCHAT( )
{
BYTEARRAY packet;
packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant
packet.push_back( SID_ENTERCHAT ); // SID_ENTERCHAT
packet.push_back( 0 ); // packet length will be assigned later
packet.push_back( 0 ); // packet length will be assigned later
packet.push_back( 0 ); // Account Name is NULL on Warcraft III/The Frozen Throne
packet.push_back( 0 ); // Stat String is NULL on CDKEY'd products
AssignLength( packet );
// DEBUG_Print( "SENT SID_ENTERCHAT" );
// DEBUG_Print( packet );
return packet;
}
BYTEARRAY CBNETProtocol :: SEND_SID_JOINCHANNEL( string channel )
{
unsigned char NoCreateJoin[] = { 2, 0, 0, 0 };
unsigned char FirstJoin[] = { 1, 0, 0, 0 };
BYTEARRAY packet;
packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant
packet.push_back( SID_JOINCHANNEL ); // SID_JOINCHANNEL
packet.push_back( 0 ); // packet length will be assigned later
packet.push_back( 0 ); // packet length will be assigned later
if( channel.size( ) > 0 )
UTIL_AppendByteArray( packet, NoCreateJoin, 4 ); // flags for no create join
else
UTIL_AppendByteArray( packet, FirstJoin, 4 ); // flags for first join
UTIL_AppendByteArrayFast( packet, channel );
AssignLength( packet );
// DEBUG_Print( "SENT SID_JOINCHANNEL" );
// DEBUG_Print( packet );
return packet;
}
BYTEARRAY CBNETProtocol :: SEND_SID_CHATCOMMAND( string command )
{
BYTEARRAY packet;
packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant
packet.push_back( SID_CHATCOMMAND ); // SID_CHATCOMMAND
packet.push_back( 0 ); // packet length will be assigned later
packet.push_back( 0 ); // packet length will be assigned later
UTIL_AppendByteArrayFast( packet, command ); // Message
AssignLength( packet );
// DEBUG_Print( "SENT SID_CHATCOMMAND" );
// DEBUG_Print( packet );
return packet;
}
BYTEARRAY CBNETProtocol :: SEND_SID_CHECKAD( )
{
unsigned char Zeros[] = { 0, 0, 0, 0 };
BYTEARRAY packet;
packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant
packet.push_back( SID_CHECKAD ); // SID_CHECKAD
packet.push_back( 0 ); // packet length will be assigned later
packet.push_back( 0 ); // packet length will be assigned later
UTIL_AppendByteArray( packet, Zeros, 4 ); // ???
UTIL_AppendByteArray( packet, Zeros, 4 ); // ???
UTIL_AppendByteArray( packet, Zeros, 4 ); // ???
UTIL_AppendByteArray( packet, Zeros, 4 ); // ???
AssignLength( packet );
// DEBUG_Print( "SENT SID_CHECKAD" );
// DEBUG_Print( packet );
return packet;
}
BYTEARRAY CBNETProtocol :: SEND_SID_PING( BYTEARRAY pingValue )
{
BYTEARRAY packet;
if( pingValue.size( ) == 4 )
{
packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant
packet.push_back( SID_PING ); // SID_PING
packet.push_back( 0 ); // packet length will be assigned later
packet.push_back( 0 ); // packet length will be assigned later
UTIL_AppendByteArrayFast( packet, pingValue ); // Ping Value
AssignLength( packet );
}
else
CONSOLE_Print( "[BNETPROTO] invalid parameters passed to SEND_SID_PING" );
// DEBUG_Print( "SENT SID_PING" );
// DEBUG_Print( packet );
return packet;
}
BYTEARRAY CBNETProtocol :: SEND_SID_LOGONRESPONSE( BYTEARRAY clientToken, BYTEARRAY serverToken, BYTEARRAY passwordHash, string accountName )
{
// todotodo: check that the passed BYTEARRAY sizes are correct (don't know what they should be right now so I can't do this today)
BYTEARRAY packet;
packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant
packet.push_back( SID_LOGONRESPONSE ); // SID_LOGONRESPONSE
packet.push_back( 0 ); // packet length will be assigned later
packet.push_back( 0 ); // packet length will be assigned later
UTIL_AppendByteArrayFast( packet, clientToken ); // Client Token
UTIL_AppendByteArrayFast( packet, serverToken ); // Server Token
UTIL_AppendByteArrayFast( packet, passwordHash ); // Password Hash
UTIL_AppendByteArrayFast( packet, accountName ); // Account Name
AssignLength( packet );
// DEBUG_Print( "SENT SID_LOGONRESPONSE" );
// DEBUG_Print( packet );
return packet;
}
BYTEARRAY CBNETProtocol :: SEND_SID_AUTH_INFO( unsigned char ver, bool TFT, string countryAbbrev, string country )
{
unsigned char ProtocolID[] = { 0, 0, 0, 0 };
unsigned char PlatformID[] = { 54, 56, 88, 73 }; // "IX86"
unsigned char ProductID_ROC[] = { 51, 82, 65, 87 }; // "WAR3"
unsigned char ProductID_TFT[] = { 80, 88, 51, 87 }; // "W3XP"
unsigned char Version[] = { ver, 0, 0, 0 };
unsigned char Language[] = { 83, 85, 110, 101 }; // "enUS"
unsigned char LocalIP[] = { 127, 0, 0, 1 };
unsigned char TimeZoneBias[] = { 108, 253, 255, 255 };
unsigned char LocaleID[] = { 9, 12, 0, 0 };
unsigned char LanguageID[] = { 9, 4, 0, 0 }; // 0x0409 English (United States)
BYTEARRAY packet;
packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant
packet.push_back( SID_AUTH_INFO ); // SID_AUTH_INFO
packet.push_back( 0 ); // packet length will be assigned later
packet.push_back( 0 ); // packet length will be assigned later
UTIL_AppendByteArray( packet, ProtocolID, 4 ); // Protocol ID
UTIL_AppendByteArray( packet, PlatformID, 4 ); // Platform ID
if( TFT )
UTIL_AppendByteArray( packet, ProductID_TFT, 4 ); // Product ID (TFT)
else
UTIL_AppendByteArray( packet, ProductID_ROC, 4 ); // Product ID (ROC)
UTIL_AppendByteArray( packet, Version, 4 ); // Version
UTIL_AppendByteArray( packet, Language, 4 ); // Language
UTIL_AppendByteArray( packet, LocalIP, 4 ); // Local IP for NAT compatibility
UTIL_AppendByteArray( packet, TimeZoneBias, 4 ); // Time Zone Bias
UTIL_AppendByteArray( packet, LocaleID, 4 ); // Locale ID
UTIL_AppendByteArray( packet, LanguageID, 4 ); // Language ID
UTIL_AppendByteArrayFast( packet, countryAbbrev ); // Country Abbreviation
UTIL_AppendByteArrayFast( packet, country ); // Country
AssignLength( packet );
// DEBUG_Print( "SENT SID_AUTH_INFO" );
// DEBUG_Print( packet );
return packet;
}
BYTEARRAY CBNETProtocol :: SEND_SID_AUTH_CHECK( BYTEARRAY clientToken, BYTEARRAY exeVersion, BYTEARRAY exeVersionHash, BYTEARRAY keyInfoROC, BYTEARRAY keyInfoTFT, string exeInfo, string keyOwnerName )
{
uint32_t NumKeys = 0;
uint32_t UsingSpawn = 0;
if( keyInfoTFT.empty( ) )
NumKeys = 1;
else
NumKeys = 2;
BYTEARRAY packet;
if( clientToken.size( ) == 4 && exeVersion.size( ) == 4 && exeVersionHash.size( ) == 4 && keyInfoROC.size( ) == 36 && ( keyInfoTFT.empty( ) || keyInfoTFT.size( ) == 36 ) )
{
packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant
packet.push_back( SID_AUTH_CHECK ); // SID_AUTH_CHECK
packet.push_back( 0 ); // packet length will be assigned later
packet.push_back( 0 ); // packet length will be assigned later
UTIL_AppendByteArrayFast( packet, clientToken ); // Client Token
UTIL_AppendByteArrayFast( packet, exeVersion ); // EXE Version
UTIL_AppendByteArrayFast( packet, exeVersionHash ); // EXE Version Hash
UTIL_AppendByteArray( packet, NumKeys, false ); // number of keys in this packet
UTIL_AppendByteArray( packet, UsingSpawn, false ); // boolean Using Spawn (32 bit)
UTIL_AppendByteArrayFast( packet, keyInfoROC ); // ROC Key Info
if( !keyInfoTFT.empty( ) )
UTIL_AppendByteArrayFast( packet, keyInfoTFT ); // TFT Key Info
UTIL_AppendByteArrayFast( packet, exeInfo ); // EXE Info
UTIL_AppendByteArrayFast( packet, keyOwnerName ); // CD Key Owner Name
AssignLength( packet );
}
else
CONSOLE_Print( "[BNETPROTO] invalid parameters passed to SEND_SID_AUTH_CHECK" );
// DEBUG_Print( "SENT SID_AUTH_CHECK" );
// DEBUG_Print( packet );
return packet;
}
BYTEARRAY CBNETProtocol :: SEND_SID_AUTH_ACCOUNTLOGON( BYTEARRAY clientPublicKey, string accountName )
{
BYTEARRAY packet;
if( clientPublicKey.size( ) == 32 )
{
packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant
packet.push_back( SID_AUTH_ACCOUNTLOGON ); // SID_AUTH_ACCOUNTLOGON
packet.push_back( 0 ); // packet length will be assigned later
packet.push_back( 0 ); // packet length will be assigned later
UTIL_AppendByteArrayFast( packet, clientPublicKey ); // Client Key
UTIL_AppendByteArrayFast( packet, accountName ); // Account Name
AssignLength( packet );
}
else
CONSOLE_Print( "[BNETPROTO] invalid parameters passed to SEND_SID_AUTH_ACCOUNTLOGON" );
// DEBUG_Print( "SENT SID_AUTH_ACCOUNTLOGON" );
// DEBUG_Print( packet );
return packet;
}
BYTEARRAY CBNETProtocol :: SEND_SID_AUTH_ACCOUNTLOGONPROOF( BYTEARRAY clientPasswordProof )
{
BYTEARRAY packet;
if( clientPasswordProof.size( ) == 20 )
{
packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant
packet.push_back( SID_AUTH_ACCOUNTLOGONPROOF ); // SID_AUTH_ACCOUNTLOGONPROOF
packet.push_back( 0 ); // packet length will be assigned later
packet.push_back( 0 ); // packet length will be assigned later
UTIL_AppendByteArrayFast( packet, clientPasswordProof ); // Client Password Proof
AssignLength( packet );
}
else
CONSOLE_Print( "[BNETPROTO] invalid parameters passed to SEND_SID_AUTH_ACCOUNTLOGON" );
// DEBUG_Print( "SENT SID_AUTH_ACCOUNTLOGONPROOF" );
// DEBUG_Print( packet );
return packet;
}
BYTEARRAY CBNETProtocol :: SEND_SID_CLANINVITATION( string username )
{
unsigned char Cookie[] = { 0, 1, 0, 0 };
BYTEARRAY packet;
packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant
packet.push_back( SID_CLANINVITATION ); // SID_CLANINVITATION
packet.push_back( 0 ); // packet length will be assigned later
packet.push_back( 0 ); // packet length will be assigned later
UTIL_AppendByteArray( packet, Cookie, 4); // Cookie: 00 01 00 00
UTIL_AppendByteArrayFast( packet, username ); // Target name
AssignLength( packet ); // Assign packet length
// DEBUG_Print( "SENT SID_CLANINVITATION" );
// DEBUG_Print( packet );
return packet;
}
BYTEARRAY CBNETProtocol :: SEND_SID_CLANREMOVEMEMBER( string username )
{
unsigned char Cookie[] = { 0, 0, 0, 0 };
BYTEARRAY packet;
packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant
packet.push_back( SID_CLANREMOVEMEMBER ); // SID_CLANREMOVEMEMBER
packet.push_back( 0 ); // packet length will be assigned later
packet.push_back( 0 ); // packet length will be assigned later
UTIL_AppendByteArray( packet, Cookie, 4); // Cookie: 00 00 00 00
UTIL_AppendByteArrayFast( packet, username ); // Target name
AssignLength( packet ); // Assign packet length
// DEBUG_Print( "SENT SID_CLANREMOVEMEMBER" );
// DEBUG_Print( packet );
return packet;
}
BYTEARRAY CBNETProtocol :: SEND_SID_CLANCHANGERANK( string username, CBNETProtocol :: RankCode rank )
{
unsigned char Cookie[] = { 0, 0, 0, 0 };
BYTEARRAY packet;
packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant
packet.push_back( SID_CLANCHANGERANK ); // SID_CLANCHANGERANK
packet.push_back( 0 ); // packet length will be assigned later
packet.push_back( 0 ); // packet length will be assigned later
UTIL_AppendByteArray( packet, Cookie, 4 ); // Cookie: 00 01 00 00
UTIL_AppendByteArrayFast( packet, username );
packet.push_back( rank );
AssignLength( packet );
// DEBUG_Print( "SENT SID_CLANCHANGERANK" );
// DEBUG_Print( packet );
return packet;
}
BYTEARRAY CBNETProtocol :: SEND_SID_CLANMEMBERLIST( )
{
unsigned char Cookie[] = { 0, 0, 0, 0 };
BYTEARRAY packet;
packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant
packet.push_back( SID_CLANMEMBERLIST ); // SID_CLANMEMBERLIST
packet.push_back( 0 ); // packet length will be assigned later
packet.push_back( 0 ); // packet length will be assigned later
UTIL_AppendByteArray( packet, Cookie, 4 ); // cookie
AssignLength( packet );
// DEBUG_Print( "SENT SID_CLANMEMBERLIST" );
// DEBUG_Print( packet );
return packet;
}
BYTEARRAY CBNETProtocol :: SEND_SID_CLANSETMOTD( string message )
{
unsigned char Cookie[] = { 11, 0, 0, 0 };
BYTEARRAY packet;
packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant
packet.push_back( SID_CLANSETMOTD ); // SID_CLANSETMOTD
packet.push_back( 0 ); // packet length will be assigned later
packet.push_back( 0 ); // packet length will be assigned later
UTIL_AppendByteArray( packet, Cookie, 4 ); // cookie
UTIL_AppendByteArrayFast( packet, message ); // message
AssignLength( packet );
// DEBUG_Print( "SEND SID_CLANMOTD" );
// DEBUG_Print( packet );
return packet;
}
BYTEARRAY CBNETProtocol :: SEND_SID_CLANINVITATIONRESPONSE( BYTEARRAY clantag, BYTEARRAY inviter, bool response )
{
unsigned char Cookie[] = { 0, 11, 0 };
unsigned char Accept[] = { 0, 6 };
unsigned char Decline[] = { 0, 4 };
BYTEARRAY packet;
packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant
packet.push_back( SID_CLANINVITATIONRESPONSE ); // CLANINVITATIONRESPONSE
packet.push_back( 0 ); // packet length will be assigned later
packet.push_back( 0 ); // packet length will be assigned later
UTIL_AppendByteArray( packet, Cookie, 3 ); // cookie
UTIL_AppendByteArrayFast( packet, clantag ); // clan tag
UTIL_AppendByteArrayFast( packet, inviter ); // inviter
if( response )
UTIL_AppendByteArray( packet, Accept, 2 ); // response - 0x06: Accept
else
UTIL_AppendByteArray( packet, Decline, 2 ); // response - 0x04: Decline
AssignLength( packet ); // assign length
// DEBUG_Print( "SEND SID_CLANINVITATIONRESPONSE" );
// DEBUG_Print( packet );
return packet;
}
BYTEARRAY CBNETProtocol :: SEND_SID_CLANMAKECHIEFTAIN( string username )
{
unsigned char Cookie[] = { 1, 0, 0, 0 };
BYTEARRAY packet;
packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant
packet.push_back( SID_CLANMAKECHIEFTAIN ); // CLANINVITATIONRESPONSE
packet.push_back( 0 ); // packet length will be assigned later
packet.push_back( 0 ); // packet length will be assigned later
UTIL_AppendByteArray( packet, Cookie, 4 ); // cookie
UTIL_AppendByteArrayFast( packet, username ); // clan tag
AssignLength( packet ); // assign length
// DEBUG_Print( "SEND SID_CLANMAKECHIEFTAIN" );
// DEBUG_Print( packet );
return packet;
}
BYTEARRAY CBNETProtocol :: SEND_SID_CLANCREATIONINVITATION( BYTEARRAY clantag, BYTEARRAY inviter )
{
unsigned char Cookie[] = { 2, 0, 0, 0 };
unsigned char Accept[] = { 0, 6 };
BYTEARRAY packet;
packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant
packet.push_back( SID_CLANCREATIONINVITATION ); // CLANCREATIONINVITATION
packet.push_back( 0 ); // packet length will be assigned later
packet.push_back( 0 ); // packet length will be assigned later
UTIL_AppendByteArray( packet, Cookie, 4 ); // cookie
UTIL_AppendByteArrayFast( packet, clantag ); // clan tag
UTIL_AppendByteArrayFast( packet, inviter ); // inviter
UTIL_AppendByteArray( packet, Accept, 2 ); // response - 0x06: Accept
AssignLength( packet ); // assign length
// DEBUG_Print( "SEND SID_CLANCREATIONINVITATION" );
// DEBUG_Print( packet );
return packet;
}
/////////////////////
// OTHER FUNCTIONS //
/////////////////////
inline bool CBNETProtocol :: AssignLength( BYTEARRAY &content )
{
// insert the actual length of the content array into bytes 3 and 4 (indices 2 and 3)
BYTEARRAY LengthBytes;
if( content.size( ) >= 4 && content.size( ) <= 65535 )
{
LengthBytes = UTIL_CreateByteArray( (uint16_t)content.size( ), false );
content[2] = LengthBytes[0];
content[3] = LengthBytes[1];
return true;
}
return false;
}
inline bool CBNETProtocol :: ValidateLength( BYTEARRAY &content )
{
// verify that bytes 3 and 4 (indices 2 and 3) of the content array describe the length
uint16_t Length;
BYTEARRAY LengthBytes;
if( content.size( ) >= 4 && content.size( ) <= 65535 )
{
LengthBytes.push_back( content[2] );
LengthBytes.push_back( content[3] );
Length = UTIL_ByteArrayToUInt16( LengthBytes, false );
if( Length == content.size( ) )
return true;
}
return false;
}
//
// CIncomingChatEvent
//
CIncomingChatEvent :: CIncomingChatEvent( CBNETProtocol :: IncomingChatEvent nChatEvent, uint32_t nUserFlags, int nPing, const string &nUser, const string &nMessage ) : m_ChatEvent( nChatEvent ), m_UserFlags( nUserFlags ), m_Ping( nPing ), m_User( nUser ), m_Message( nMessage )
{
}
CIncomingChatEvent :: ~CIncomingChatEvent( )
{
}
//
// CIncomingClanList
//
CIncomingClanList :: CIncomingClanList( const string &nName, unsigned char nRank, unsigned char nStatus ) : m_Name( nName ), m_Rank( nRank ), m_Status( nStatus )
{
}
CIncomingClanList :: ~CIncomingClanList( )
{
}
string CIncomingClanList :: GetRank( )
{
switch( m_Rank )
{
case 0: return "Recruit";
case 1: return "Peon";
case 2: return "Grunt";
case 3: return "Shaman";
case 4: return "Chieftain";
}
return "Rank Unknown";
}
string CIncomingClanList :: GetStatus( )
{
if( m_Status == 0 )
return "Offline";
return "Online";
}
string CIncomingClanList :: GetDescription( )
{
string Description;
Description += GetName( ) + "\n";
Description += GetStatus( ) + "\n";
Description += GetRank( ) + "\n\n";
return Description;
}
| [
"[email protected]"
]
| [
[
[
1,
996
]
]
]
|
f98a430ba388295a2a581e2ddb3632ce9d7a756d | 54dfb0046228832dcdec6dc5a18c5c23ada6f9ee | /MainProgram/PhataTrackContainter.h | 36afc74602e86653a3e5eae9b9916d16ff7e4a7d | []
| no_license | github188/piglets-monitoring | 3f6ec92e576d334762cc805727d358d9799ca053 | 620b6304384534eb71113c26a054c36ce3800ed8 | refs/heads/master | 2021-01-22T12:45:45.159790 | 2011-11-08T15:37:18 | 2011-11-08T15:37:18 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 812 | h | #pragma once
#include "cv.h"
#include "Track.h"
#include <vector>
#include "PhataBlobContainter.h"
using std::vector;
typedef vector<CTrack*> Track_vector;
typedef vector<CTrack*>::iterator Track_vector_it;
typedef vector<CTrack*>::const_iterator Track_vector_constit;
class PhataTrackContainter
{
public:
PhataTrackContainter(void);
virtual ~PhataTrackContainter(void);
public:
bool AddTrack(CTrack *track);
void ClearTracks();
CTrack GetTrack(int indexTrack)const;
CTrack*GetTrack(int indexTrack);
//查找第一个track的m_trackid等于trackID的track,找不到则返回NULL
CTrack *FindTrackByID(int trackID);
int GetContainterSize()const{ return m_Tracks.size();};
Track_vector GetTrackVector(TRACKSTATE state);//返回状态为state的CTrcak
Track_vector m_Tracks;
};
| [
"[email protected]"
]
| [
[
[
1,
26
]
]
]
|
91a2b61ec7796bcdfc181dac5c02e3ba3a1e59a8 | 9b786d478560dfe2b99084f5d9338c0729634700 | /vxWorks/cpp_test_src/inheritance/diamondSol.cpp | 35e0fc9532bd3c9f8bd9f1791628c825ea024d4e | []
| no_license | hejunbok/demoCode | e33809c13f783cceb47d1bd2a57e2f07b31e42b9 | fb7a7a9c87ba61d104dabf291805c99f76ae9aac | refs/heads/master | 2021-01-18T08:33:07.654385 | 2011-04-25T06:27:11 | 2011-04-25T06:27:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,552 | cpp | /* diamondSol.cpp */
/* Copyright 2004 Wind River Systems, Inc. */
/*
modification history
--------------------
01a,3March04,pp written.
*/
/*
DESCRIPTION
Demonstrate the solving of diamond classes arrangement
by making a single copy of the base most class members
In the test application Base1 and Base2 have virtual base class baseMost.
Class Derived has Base1 and Base2 as base classes. BaseMost Class has
function vFunction().VFunction is called through derived class member
function , the call is not ambigious as baseMost is virtual base class
*/
#include <stdio.h>
class BaseMost
{
int i;
public:
void vFunction()
{
printf("\n vFunction of BaseMost, Value of i = %d",i);
}
void SetI(int iArg)
{
i=iArg;
}
};
class Base1 : virtual public BaseMost
{
public:
virtual void vF1()
{
printf("\n vF1 of Base1");
}
};
class Base2:virtual public BaseMost
{
public:
virtual void vF2()
{
printf("\n vF2 of Base2");
}
};
class Derived: public Base1,public Base2
{
public:
virtual void vF1()
{
Base1::SetI(10); //Setting the value of i
Base2::SetI(20); //Results in overwriting the value of i as there is only one copy of i
vFunction(); //No ambiguity in this case due to virtual inheritance
printf("\n vF1 of Derived");
}
virtual void vF2()
{
printf("\n vF2 of Derived");
}
};
int tdfeTestCase33Execute(void)
{
Derived *pDerived;
pDerived=new Derived;
pDerived->vF1();
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
87
]
]
]
|
2c22a20f7528a6eee8f7526cb303a788c5b905c6 | 737638e4d2496de8656a23e093f40ef74eca6ca8 | /facility.h | 06069bbb97178bfaea0c69945cfee4f10a1734dc | []
| no_license | ianperez/x-com-reloaded | edbd06f3d78b833a21b0b0effed5a887d93f071f | e581b56479233943ae8c7c572eca2a51abb36f2d | refs/heads/master | 2021-01-21T23:16:50.031442 | 2010-12-18T05:52:45 | 2010-12-18T05:52:45 | 32,757,272 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 106 | h | #pragma once
#include <sdl.h>
namespace ufo
{
class Facility
{
public:
Facility();
};
} | [
"[email protected]@687bc148-feef-c4d9-3bcb-ab45cd3def04",
"ianrobertperez@687bc148-feef-c4d9-3bcb-ab45cd3def04"
]
| [
[
[
1,
5
],
[
12,
12
]
],
[
[
6,
11
]
]
]
|
b63c6aa4216e29493255b96ca854f0a5340734e0 | 28aa23d9cb8f5f4e8c2239c70ef0f8f6ec6d17bc | /mytesgnikrow --username hotga2801/Project/AdaboostFaceDetection/AdaboostFaceDetection/Label.cpp | a67c126db744f0387fcfd3eb6b8384d0efc8343a | []
| 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 | 344 | cpp | #include "stdafx.h"
#include "Label.h"
CLabel::CLabel(void)
{
//m_LeftEye = POINT(0,0);
//m_RightEye = POINT(0,0);
//m_CenterMouth = POINT(0,0);
}
bool CLabel::IsInsideRect(CRect rect)
{
if(!rect.PtInRect(m_LeftEye) || !rect.PtInRect(m_RightEye) || !rect.PtInRect(m_CenterMouth))
{
return false;
}
return true;
}
| [
"hotga2801@ecd9aaca-b8df-3bf4-dfa7-576663c5f076"
]
| [
[
[
1,
19
]
]
]
|
f92e4f1ec356eaec2e3a831c9daf01303fd4ac45 | 521721c2e095daf757ad62a267b1c0f724561935 | /bsTextureCache.cpp | d215838d363ce2d03178f4ffe02f36d3eef7bb06 | []
| no_license | MichaelSPG/boms | 251922d78f2db85ece495e067bd56a1e9fae14b1 | 23a13010e0aaa79fea3b7cf1b23e2faab02fa5d4 | refs/heads/master | 2021-01-10T16:23:51.722062 | 2011-12-08T00:04:33 | 2011-12-08T00:04:33 | 48,052,727 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,225 | cpp | #include "StdAfx.h"
#include "bsTextureCache.h"
#include "bsFileIoManager.h"
#include "bsAssert.h"
#include "bsTexture2D.h"
#include "bsLog.h"
#include "bsFixedSizeString.h"
#include "bsFileSystem.h"
//Name for the default pink/yellow checker texture.
const char* bsTextureCacheDefaultTextureName = "__internal_default_pink_yellow_checker";
/* Function object passed to file loader when loading textures asynchronously.
Converts the loaded data into a texture.
*/
class bsTextureFileLoadFinishedCallback
{
public:
bsTextureFileLoadFinishedCallback(const std::shared_ptr<bsTexture2D>& texture,
const std::string& textureName, ID3D11Device& device)
: mTexture(texture)
, mTextureName(textureName)
, mDevice(device)
{
}
void operator()(const bsFileLoader& fileLoader)
{
BS_ASSERT(fileLoader.getCurrentLoadState() == bsFileLoader::SUCCEEDED);
const unsigned long dataSize = fileLoader.getLoadedDataSize();
const char* loadedData = fileLoader.getLoadedData();
ID3D11ShaderResourceView* shaderResourceView = nullptr;
const HRESULT hres = D3DX11CreateShaderResourceViewFromMemory(&mDevice, loadedData,
dataSize, nullptr, nullptr, &shaderResourceView, nullptr);
BS_ASSERT2(SUCCEEDED(hres), "Shader resource view creation failed");
mTexture->loadingCompleted(shaderResourceView, SUCCEEDED(hres));
bsLog::logf(bsLog::SEV_INFO, "Loading of texture '%s' finished, success: %u",
fileLoader.getFileName().c_str(),
fileLoader.getCurrentLoadState() == bsFileLoader::SUCCEEDED);
#ifdef BS_DEBUG
if (shaderResourceView != nullptr)
{
bsString256 debugString(mTextureName.c_str());
shaderResourceView->SetPrivateData(WKPDID_D3DDebugObjectName,
debugString.size(), debugString.c_str());
}
#endif
}
private:
std::shared_ptr<bsTexture2D> mTexture;
std::string mTextureName;
ID3D11Device& mDevice;
};
bsTextureCache::bsTextureCache(ID3D11Device& device, const bsFileSystem& fileSystem,
bsFileIoManager& fileIoManager)
: mFileSystem(fileSystem)
, mFileIoManager(fileIoManager)
, mDevice(device)
, mNumLoadedTextures(0)
{
/* 96 bytes of 2x2 checker texture PNG.
Upper left and lower right pixels are yellow, other two are pink.
This is used as a default placeholder texture while loading the actual texture
in the background. The colors can also help with identifying textures which failed
to load (they will always have the default yellow/pink checker texture.
*/
const unsigned char yellowPinkCheckerPng[] =
{
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d,
0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x02,
0x08, 0x02, 0x00, 0x00, 0x00, 0xfd, 0xd4, 0x9a, 0x73, 0x00, 0x00, 0x00,
0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0e, 0xc4, 0x00, 0x00, 0x0e,
0xc4, 0x01, 0x95, 0x2b, 0x0e, 0x1b, 0x00, 0x00, 0x00, 0x12, 0x49, 0x44,
0x41, 0x54, 0x78, 0xda, 0x63, 0xf8, 0xff, 0x89, 0xe1, 0x3f, 0x04, 0xfe,
0xff, 0xc4, 0x00, 0x00, 0x39, 0x1e, 0x07, 0xdf, 0xbd, 0x59, 0x87, 0x88,
0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
};
//Create the default texture.
ID3D11ShaderResourceView* shaderResourceView = nullptr;
const HRESULT hres = D3DX11CreateShaderResourceViewFromMemory(&mDevice,
yellowPinkCheckerPng, sizeof(yellowPinkCheckerPng), nullptr, nullptr,
&shaderResourceView, nullptr);
BS_ASSERT2(SUCCEEDED(hres), "Failed to create default yellow/pink checker texture");
#ifdef BS_DEBUG
bsString32 debugString("Texture cache default texture");
shaderResourceView->SetPrivateData(WKPDID_D3DDebugObjectName,
debugString.size(), debugString.c_str());
#endif
//Insert the default texture into texture cache.
std::shared_ptr<bsTexture2D> defaultTexture(
std::make_shared<bsTexture2D>(shaderResourceView, mDevice, getNewTextureId(),
D3D11_FILTER_MIN_MAG_MIP_POINT));
mTextures.insert(std::move(StringTexturePair(bsTextureCacheDefaultTextureName, defaultTexture)));
}
bsTextureCache::~bsTextureCache()
{
#ifdef BS_DEBUG
//Warn if there are external references to any textures.
for (auto itr = mTextures.begin(), end = mTextures.end(); itr != end; ++itr)
{
if (!itr->second.unique())
{
bsLog::logf(bsLog::SEV_WARNING, "All references to texture '%s' have not"
" been released when bsTextureCache is being destroyed (%u external refs)",
itr->first.c_str(), itr->second.use_count() - 1);
}
}
#endif //ifdef BS_DEBUG
mTextures.clear();
}
std::shared_ptr<bsTexture2D> bsTextureCache::getTexture(const char* fileName)
{
const auto findResult = mTextures.find(fileName);
if (findResult != std::end(mTextures))
{
//Found it in cache.
return findResult->second;
}
//Not found in cache, load it asynchronously.
const std::string fullFilePath(mFileSystem.getPathFromFilename(fileName));
if (fullFilePath.empty())
{
bsLog::logf(bsLog::SEV_ERROR, "Failed to find path for file '%s'", fileName);
BS_ASSERT2(false, "Failed to find texture file");
//Failed to load the requested texture, return default texture to prevent crashing.
return getDefaultTexture();
}
//Create a temporary default placeholder while loading the actual texture in the background.
std::shared_ptr<bsTexture2D> texture(std::move(std::make_shared<bsTexture2D>(
mTextures[bsTextureCacheDefaultTextureName]->getShaderResourceView(), mDevice,
getNewTextureId())));
mTextures.insert(StringTexturePair(fileName, texture));
mFileIoManager.addAsynchronousLoadRequest(fullFilePath,
bsTextureFileLoadFinishedCallback(texture, fileName, mDevice));
return texture;
}
std::shared_ptr<bsTexture2D> bsTextureCache::getTextureBlocking(const char* fileName)
{
const auto findResult = mTextures.find(fileName);
if (findResult != std::end(mTextures))
{
//Found it in cache.
return findResult->second;
}
//Not found in cache, load it synchronously.
const std::string fullFilePath(mFileSystem.getPathFromFilename(fileName));
if (fullFilePath.empty())
{
bsLog::logf(bsLog::SEV_ERROR, "Failed to find path for file '%s'", fileName);
BS_ASSERT2(false, "Failed to find texture file");
//Failed to load the requested texture, return default texture to prevent crashing.
return getDefaultTexture();
}
//Create a temporary default placeholder.
std::shared_ptr<bsTexture2D> texture(std::move(std::make_shared<bsTexture2D>(
mTextures[bsTextureCacheDefaultTextureName]->getShaderResourceView(), mDevice,
getNewTextureId())));
mTextures.insert(StringTexturePair(fileName, texture));
//Do the same as with async loading, but call loadBlocking instead.
bsTextureFileLoadFinishedCallback finishedCallback(texture, fileName, mDevice);
finishedCallback(mFileIoManager.loadBlocking(fullFilePath));
return texture;
}
std::shared_ptr<bsTexture2D> bsTextureCache::getDefaultTexture() const
{
BS_ASSERT2(mTextures.find(bsTextureCacheDefaultTextureName) != std::end(mTextures),
"Failed to find default texture. This should never happen");
return mTextures.find(bsTextureCacheDefaultTextureName)->second;
}
| [
"[email protected]"
]
| [
[
[
1,
212
]
]
]
|
d204943bf4c20428594a1a4a67ea65ce4afe0041 | d5f5a6b9fb6885b72bec1ee733ba73abcc1c21b8 | /MailWidget.h | 9bbf8957bb87c2923db50b3b0f5feca6b66475bd | []
| no_license | congchenutd/mailchecker | 8e99e080e670a8a1a97fab757955a9d8e7250296 | fbfd2dc5b9b03b1e7887e5864cfdd9cd90fbdf50 | refs/heads/master | 2021-01-18T14:05:07.857597 | 2011-03-07T23:54:11 | 2011-03-07T23:54:11 | 32,358,817 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 698 | h | #ifndef MAILWIDGET_H
#define MAILWIDGET_H
#include <QWidget>
#include "ui_MailWidget.h"
#include "Connection.h"
class MailWidget : public QWidget
{
Q_OBJECT
public:
MailWidget(const MailInfo& info, QWidget *parent = 0);
void setMail(const MailInfo& info);
QString getAccountName() const;
int getMailID() const;
private slots:
void onSetRead();
void onDel();
private:
AccountInfo getAccountInfo(const QString& name) const;
void setSubjectBold(bool bold);
signals:
void mailDeleted(QWidget*);
void newMailCountChanged(int);
public:
static int newMailCount;
private:
Ui::MailWidget ui;
MailInfo mailInfo;
};
#endif // MAILWIDGET_H
| [
"congchenutd@11d43eb3-d973-da56-5163-f7c915874638"
]
| [
[
[
1,
38
]
]
]
|
d8016947ce20d743cd08b7c90b9655fef53698eb | b3b0c727bbafdb33619dedb0b61b6419692e03d3 | /Source/CppUnitTest/Test/Main.cpp | f0b3a46b9cf709299c05811387cc4858486f11d9 | []
| no_license | testzzzz/hwccnet | 5b8fb8be799a42ef84d261e74ee6f91ecba96b1d | 4dbb1d1a5d8b4143e8c7e2f1537908cb9bb98113 | refs/heads/master | 2021-01-10T02:59:32.527961 | 2009-11-04T03:39:39 | 2009-11-04T03:39:39 | 45,688,112 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 1,305 | cpp | //////////////////////////////////////////////////////////
///
/// @file Main.cpp
///
/// @brief 利用CppUnit测试ICalculator接口的主函数
///
/// @version 1.0
///
/// @author 甘先志
///
/// @date 2009-07-22
///
//////////////////////////////////////////////////////////
#include <cppunit/BriefTestProgressListener.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/TestRunner.h>
int
main( int argc, char* argv[] )
{
// 建立事件管理器和测试控制器
CPPUNIT_NS::TestResult controller;
// 添加一个监听colllects测试结果
CPPUNIT_NS::TestResultCollector result;
controller.addListener( &result );
// 添加测试运行的监听
CPPUNIT_NS::BriefTestProgressListener progress;
controller.addListener( &progress );
// 为测试注册
CPPUNIT_NS::TestRunner runner;
runner.addTest( CPPUNIT_NS::TestFactoryRegistry::getRegistry().makeTest() );
runner.run( controller );
// 输出测试结果.
CPPUNIT_NS::CompilerOutputter outputter( &result, CPPUNIT_NS::stdCOut() );
outputter.write();
return result.wasSuccessful() ? 0 : 1;
}
| [
"[email protected]"
]
| [
[
[
1,
47
]
]
]
|
d6e3c5c5c34d0a8ab9d2b524836fc28d22dac617 | 273020f62176230357e51a5ca20212ac0f32a01f | /tags/Release_1.10/traydict/dict_window.cpp | 1b83b8f08e5973d1111195a25fb2cd25973558c3 | []
| no_license | BackupTheBerlios/aegisub-svn | 1915f94798fea3f45db86b16acb07fdd059ac8d2 | e26eda1242e9d628adcc3e6c5d57614a4808c9e0 | refs/heads/master | 2016-08-04T11:27:52.584837 | 2007-01-15T01:46:59 | 2007-01-15T01:46:59 | 40,664,462 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,663 | cpp | // Copyright (c) 2006, Rodrigo Braz Monteiro
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of the Aegisub Group nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// -----------------------------------------------------------------------------
//
// AEGISUB
//
// Website: http://aegisub.cellosoft.com
// Contact: mailto:[email protected]
//
///////////
// Headers
#include <wx/wxprec.h>
#include <wx/taskbar.h>
#include "dict_window.h"
#include "systray.h"
#include "dictionary.h"
#include "main.h"
///////////////
// Constructor
DictWindow::DictWindow()
: wxFrame(NULL,-1,_T("TrayDict v0.06 - By Rodrigo Braz Monteiro"),wxDefaultPosition,wxSize(620,500),wxRESIZE_BORDER | wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxSYSTEM_MENU | wxCAPTION | wxCLOSE_BOX | wxCLIP_CHILDREN)
{
// Icons
SetIcon(wxICON(wxicon));
systray = new Systray(this);
// Menu bar
//menu = new wxMenuBar();
//SetMenuBar(menu);
// Status bar
//wxStatusBar *bar = CreateStatusBar(3,0);
//int widths[] = { 85, -1, -1 };
//bar->SetStatusWidths(3,widths);
// Panel
panel = new wxPanel(this);
// Controls
entry = new wxTextCtrl(panel,ENTRY_FIELD,_T(""),wxDefaultPosition,wxDefaultSize,wxTE_PROCESS_ENTER);
results = new wxTextCtrl(panel,-1,_T(""),wxDefaultPosition,wxSize(280,400),wxTE_RICH2 | wxTE_MULTILINE | wxTE_DONTWRAP | wxTE_READONLY);
wxButton *searchButton = new wxButton(panel,BUTTON_SEARCH,_T("Search"),wxDefaultPosition,wxSize(80,-1));
wxSizer *entrySizer = new wxBoxSizer(wxHORIZONTAL);
entrySizer->Add(entry,1,wxEXPAND | wxRIGHT,5);
entrySizer->Add(searchButton,0,wxEXPAND,0);
// Options
checkKanji = new wxCheckBox(panel,CHECK_KANJI,_T("Kanji"));
checkKana = new wxCheckBox(panel,CHECK_KANA,_T("Kana"));
checkRomaji = new wxCheckBox(panel,CHECK_ROMAJI,_T("Romaji"));
checkEnglish = new wxCheckBox(panel,CHECK_ENGLISH,_T("English"));
checkEdict = new wxCheckBox(panel,CHECK_ENGLISH,_T("EDICT"));
checkEnamdict = new wxCheckBox(panel,CHECK_ENGLISH,_T("ENAMDICT"));
checkCompdic = new wxCheckBox(panel,CHECK_ENGLISH,_T("COMPDIC"));
checkJplaces = new wxCheckBox(panel,CHECK_ENGLISH,_T("J_PLACES"));
checkKanji->SetValue(true);
checkKana->SetValue(true);
checkRomaji->SetValue(true);
checkEnglish->SetValue(true);
checkEdict->SetValue(true);
checkEnamdict->SetValue(false);
checkCompdic->SetValue(false);
checkJplaces->SetValue(false);
wxSizer *optionsSizer = new wxBoxSizer(wxHORIZONTAL);
optionsSizer->Add(new wxStaticText(panel,-1,_T("Display:")),0,wxCENTER | wxRIGHT,5);
optionsSizer->Add(checkKanji,0,wxCENTER | wxRIGHT,5);
optionsSizer->Add(checkKana,0,wxCENTER | wxRIGHT,5);
optionsSizer->Add(checkRomaji,0,wxCENTER | wxRIGHT,5);
optionsSizer->Add(checkEnglish,0,wxCENTER | wxRIGHT,20);
optionsSizer->Add(new wxStaticText(panel,-1,_T("Dictionary:")),0,wxCENTER | wxRIGHT,5);
optionsSizer->Add(checkEdict,0,wxCENTER | wxRIGHT,5);
optionsSizer->Add(checkEnamdict,0,wxCENTER | wxRIGHT,5);
optionsSizer->Add(checkCompdic,0,wxCENTER | wxRIGHT,5);
optionsSizer->Add(checkJplaces,0,wxCENTER | wxRIGHT,0);
optionsSizer->AddStretchSpacer(1);
// Main sizer
wxSizer *mainSizer = new wxBoxSizer(wxVERTICAL);
mainSizer->Add(entrySizer,0,wxEXPAND | wxALL,5);
mainSizer->Add(optionsSizer,0,wxEXPAND | wxLEFT | wxRIGHT | wxBOTTOM,5);
mainSizer->Add(results,1,wxEXPAND | wxLEFT | wxRIGHT | wxBOTTOM,5);
panel->SetSizer(mainSizer);
// Create dictionary files
if (false) {
Dictionary::Convert(TrayDict::folderName + _T("edict"),TrayDict::folderName + _T("edict.dic"));
Dictionary::Convert(TrayDict::folderName + _T("enamdict"),TrayDict::folderName + _T("enamdict.dic"));
Dictionary::Convert(TrayDict::folderName + _T("compdic"),TrayDict::folderName + _T("compdic.dic"));
Dictionary::Convert(TrayDict::folderName + _T("j_places"),TrayDict::folderName + _T("j_places.dic"));
}
// Load dictionary files
dict.push_back(new Dictionary(_T("edict"),checkEdict));
dict.push_back(new Dictionary(_T("enamdict"),checkEnamdict));
dict.push_back(new Dictionary(_T("compdic"),checkCompdic));
dict.push_back(new Dictionary(_T("j_places"),checkJplaces));
// Register hotkey
RegisterHotKey(HOTKEY_ID,wxMOD_WIN,'Z');
}
//////////////
// Destructor
DictWindow::~DictWindow() {
if (systray->IsOk()) {
systray->RemoveIcon();
}
delete systray;
for (size_t i=0;i<dict.size();i++) delete dict[i];
dict.clear();
}
/////////////////
// Go to systray
void DictWindow::GoToTray() {
if (systray->IsOk()) {
Hide();
}
}
///////////////
// Event table
BEGIN_EVENT_TABLE(DictWindow,wxFrame)
EVT_ICONIZE(DictWindow::OnIconize)
EVT_BUTTON(BUTTON_SEARCH,DictWindow::OnSearch)
EVT_TEXT_ENTER(ENTRY_FIELD,DictWindow::OnSearch)
EVT_HOTKEY(HOTKEY_ID,DictWindow::OnHotkey)
EVT_CLOSE(DictWindow::OnClose)
END_EVENT_TABLE()
/////////////////
// Iconize event
void DictWindow::OnIconize(wxIconizeEvent &event) {
if (event.Iconized()) {
GoToTray();
}
}
//////////////////
// Hotkey pressed
void DictWindow::OnHotkey(wxKeyEvent &event) {
if (IsShown()) GoToTray();
else systray->BringUp();
}
/////////////////////////
// Search button pressed
void DictWindow::OnSearch(wxCommandEvent &event) {
Search(entry->GetValue());
}
//////////
// Search
void DictWindow::Search(wxString text) {
// Prepare
int bitmask = (checkKanji->GetValue() ? 1 : 0) | (checkKana->GetValue() ? 2 : 0) | (checkRomaji->GetValue() ? 4 : 0) | (checkEnglish->GetValue() ? 8 : 0);
// Clear text
results->Clear();
entry->SetSelection(0,entry->GetValue().Length());
// Search each dictionary
for (size_t i=0;i<dict.size();i++) {
if (dict[i]->check->GetValue() && dict[i]->check->IsEnabled()) {
// Search
ResultSet res;
dict[i]->Search(res,text);
// Sort results by relevancy
res.results.sort();
// Print
res.Print(results,bitmask);
}
}
// Show start
results->ShowPosition(0);
results->SetSelection(0,0);
}
////////////////
// Close window
void DictWindow::OnClose(wxCloseEvent &event) {
if (event.CanVeto()) {
event.Veto();
GoToTray();
}
else Destroy();
}
| [
"archmagezeratul@93549f3f-7f0a-0410-a4b3-e966c9c94f04"
]
| [
[
[
1,
228
]
]
]
|
f44fb68b622a6e38bd7f1b4f7f410dd1d95e6e08 | 14447604061a3ded605cd609b44fec3979d9b1cc | /Cacoon/ConnectionImpl.cpp | 15d4f7734c132041a552b9c43662d1133b60bf9c | []
| no_license | sinsoku/cacoon | 459e441aacf4dc01311a6b5cd7eae2425fbf4c3f | 36e81b689b53505c2d8117ff60ce8e4012d6eae6 | refs/heads/master | 2020-05-30T23:34:08.361671 | 2010-12-03T17:44:20 | 2010-12-03T17:44:20 | 809,470 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 2,616 | cpp | #include "stdafx.h"
#include "HeaderMap.h"
#include "ConnectionImpl.h"
ConnectionImpl::ConnectionImpl( const std::string & host )
: HostName( host )
{
}
Response ConnectionImpl::Request( const std::string & method, const std::string & url, const HeaderMap & header )
{
HeaderMap hm;
hm["Host"] = this->HostName;
hm["Connection"] = "close";
hm.Update( header );
std::ostringstream ossReq( std::ios::binary ); // \r\n を正しく処理するためバイナリとする。
ossReq << method << " " << url << " HTTP/1.1\r\n" << hm.ToString() << "\r\n" << '\0';
this->makeConnection();
this->sendRequest( ossReq.str() );
std::ostringstream ossResult( std::ios::binary );
const int BufferSize = 256;
char buf[BufferSize+1];
// サーバからヘッダ部を受信
while( 1 )
{
int readSize = this->receive( buf, BufferSize );
if( readSize > 0 )
{
buf[readSize] = '\0';
std::string bufStr( buf );
std::string::size_type endOfHeader = bufStr.find( "\r\n\r\n" );
if( endOfHeader == std::string::npos )
{
ossResult.write( buf, readSize );
}
else
{
ossResult.write( buf, readSize );
break;
}
}
else if( readSize == 0 )
{
break;
}
else
{
throw CACOON_EXCEPTION( "recv エラー" );
}
}
std::string respHeaderStr = ossResult.str();
std::string::size_type firstLine = respHeaderStr.find( "\r\n" );
std::string::size_type lastLine = respHeaderStr.find( "\r\n\r\n" );
HeaderMap respHeader( respHeaderStr.substr( firstLine + 2, lastLine - firstLine - 2 ) );
if( respHeader["Transfer-Encoding"] == "chunked" )
{ // サーバから続きを受信 (chunked バージョン)
int chunkSize = 0;
while( 1 )
{
int readSize = this->receive( buf, BufferSize );
if( chunkSize == 0 )
{
if( readSize == 0 )
{
break;
}
buf[readSize-2] = '\0';
chunkSize = strtol( buf, NULL, 16 );
}
else
{
if( readSize > 0 )
{
ossResult.write( buf, readSize );
chunkSize -= readSize;
}
else if( readSize == 0 )
{
break;
}
else
{
throw CACOON_EXCEPTION( "recv エラー" );
}
}
}
}
else
{ // サーバから続きを受信 (普通)
while( 1 )
{
int readSize = this->receive( buf, BufferSize );
if( readSize > 0 )
{
ossResult.write( buf, readSize );
break;
}
else if( readSize == 0 )
{
break;
}
else
{
throw CACOON_EXCEPTION( "recv エラー" );
}
}
}
return Response( ossResult.str() );
} | [
"[email protected]"
]
| [
[
[
1,
115
]
]
]
|
42aa4a36248eaf650bd305c11adb47483fac3bf9 | 3eae8bea68fd2eb7965cca5afca717b86700adb5 | /Engine/Project/Core/GnMesh/Source/GItemListCtrlItem.h | 9ff2dae241d9bbe6e3ffd614e81471c7aec2e0f8 | []
| no_license | mujige77/WebGame | c0a218ee7d23609076859e634e10e29c92bb595b | 73d36f9d8bfbeaa944c851e8a1cfa5408ce1d3dd | refs/heads/master | 2021-01-01T15:51:20.045414 | 2011-10-03T01:02:59 | 2011-10-03T01:02:59 | 455,950 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 856 | h | #ifndef Core_GItemListCtrlItem_h
#define Core_GItemListCtrlItem_h
#include "GStateListCtrlItem.h"
#include "GnINumberLabel.h"
class GItemListCtrlItem : public GStateListCtrlItem
{
GnDeclareRTTI;
private:
bool mCreateLabelPrice;
GnINumberLabel mLabelPrice;
GnINumberLabel mItemCount;
GnInterfacePtr mpsIconMoney;
public:
GItemListCtrlItem(const gchar* pcDefaultImage, const gchar* pcClickImage = "Upgrade/items/30_140 s.png"
, const gchar* pcDisableImage = NULL, eButtonType eDefaultType = TYPE_NORMAL);
virtual ~GItemListCtrlItem(){};
public:
void CreateLabelPrice();
void CreateIconMoney();
void SetPosition(GnVector2& cPos);
public:
inline void SetPrice(guint32 val) {
mLabelPrice.SetNumber( val );
}
inline void SetItemCount(guint32 val) {
mItemCount.SetNumber( val );
}
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
36
]
]
]
|
fd1213b4a9161655c86c6c28cb9bc5353188223e | cafe8c7142484349342968d848525035eb7cf059 | /Common/OS_Kernel.cpp | f41c95467829e0f13cae190db6da4f3c2b8de25f | []
| no_license | plumbum/scmRTOS_LPC21xx_GCC | 8e3f22c12b0eba8e4e823fa9a936bddc4cc26674 | cdc6fbaf1099eed8c320496a42080bf9b7ba24a6 | refs/heads/master | 2021-01-13T12:58:00.365934 | 2010-03-25T01:06:57 | 2010-03-25T01:06:57 | 578,391 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,280 | cpp | //******************************************************************************
//*
//* FULLNAME: Single-Chip Microcontroller Real-Time Operating System
//*
//* NICKNAME: scmRTOS
//*
//* PURPOSE: OS Kernel Source
//*
//* Version: 3.10
//*
//* $Revision: 256 $
//* $Date:: 2010-01-22 #$
//*
//* Copyright (c) 2003-2010, Harry E. Zhurov
//*
//* Permission is hereby granted, free of charge, to any person
//* obtaining a copy of this software and associated documentation
//* files (the "Software"), to deal in the Software without restriction,
//* including without limitation the rights to use, copy, modify, merge,
//* publish, distribute, sublicense, and/or sell copies of the Software,
//* and to permit persons to whom the Software is furnished to do so,
//* subject to the following conditions:
//*
//* The above copyright notice and this permission notice shall be included
//* in all copies or substantial portions of the Software.
//*
//* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
//* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
//* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
//* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
//* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
//* THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//*
//* =================================================================
//* See http://scmrtos.sourceforge.net for documentation, latest
//* information, license and contact details.
//* =================================================================
//*
//******************************************************************************
#include "scmRTOS.h"
using namespace OS;
//------------------------------------------------------------------------------
OS::TKernel OS::Kernel;
//------------------------------------------------------------------------------
#if scmRTOS_CONTEXT_SWITCH_SCHEME == 0
void TKernel::Sched()
{
byte NextPrty = GetHighPriority(ReadyProcessMap);
if(NextPrty != CurProcPriority)
{
TStackItem* Next_SP = ProcessTable[NextPrty]->StackPointer;
TStackItem** Curr_SP_addr = &(ProcessTable[CurProcPriority]->StackPointer);
CurProcPriority = NextPrty;
OS_ContextSwitcher(Curr_SP_addr, Next_SP);
}
}
#else
//------------------------------------------------------------------------------
void TKernel::Sched()
{
byte NextPrty = GetHighPriority(ReadyProcessMap);
if(NextPrty != CurProcPriority)
{
SchedProcPriority = NextPrty;
RaiseContextSwitch();
do
{
EnableContextSwitch();
DUMMY_INSTR();
DisableContextSwitch();
}
while(!IsContextSwitchDone());
}
}
//------------------------------------------------------------------------------
TStackItem* OS_ContextSwitchHook(TStackItem* sp) { return OS::Kernel.ContextSwitchHook(sp); }
//------------------------------------------------------------------------------
#endif // scmRTOS_CONTEXT_SWITCH_SCHEME
//------------------------------------------------------------------------------
void TBaseProcess::Sleep(TTimeout timeout)
{
TCritSect cs;
Kernel.ProcessTable[Kernel.CurProcPriority]->Timeout = timeout;
Kernel.SetProcessUnready(Kernel.CurProcPriority);
Kernel.Scheduler();
}
//------------------------------------------------------------------------------
void OS::WakeUpProcess(TBaseProcess& p)
{
TCritSect cs;
if(p.Timeout)
{
p.Timeout = 0;
Kernel.SetProcessReady(p.Priority);
Kernel.Scheduler();
}
}
//------------------------------------------------------------------------------
void OS::ForceWakeUpProcess(TBaseProcess& p)
{
TCritSect cs;
p.Timeout = 0;
Kernel.SetProcessReady(p.Priority);
Kernel.Scheduler();
}
//------------------------------------------------------------------------------
| [
"[email protected]"
]
| [
[
[
1,
115
]
]
]
|
a7aff190675fc8beab43235eb2dffe8c9d93772d | 5df145c06c45a6181d7402279aabf7ce9376e75e | /src/xbel.h | 14a2a804edec542630267bb8ba664dd47b1f8192 | []
| no_license | plus7/openjohn | 89318163f42347bbac24e8272081d794449ab861 | 1ffdcc1ea3f0af43b9033b68e8eca048a229305f | refs/heads/master | 2021-03-12T22:55:57.315977 | 2009-05-15T11:30:00 | 2009-05-15T11:30:00 | 152,690 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,608 | h | /****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the demonstration applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef XBEL_H
#define XBEL_H
#include <QtCore/QXmlStreamReader>
#include <QtCore/QDateTime>
class BookmarkNode
{
public:
enum Type {
Root,
Folder,
Bookmark,
Separator
};
BookmarkNode(Type type = Root, BookmarkNode *parent = 0);
~BookmarkNode();
bool operator==(const BookmarkNode &other);
Type type() const;
void setType(Type type);
QList<BookmarkNode *> children() const;
BookmarkNode *parent() const;
void add(BookmarkNode *child, int offset = -1);
void remove(BookmarkNode *child);
QString url;
QString title;
QString desc;
bool expanded;
private:
BookmarkNode *m_parent;
Type m_type;
QList<BookmarkNode *> m_children;
};
class XbelReader : public QXmlStreamReader
{
public:
XbelReader();
BookmarkNode *read(const QString &fileName);
BookmarkNode *read(QIODevice *device);
private:
void skipUnknownElement();
void readXBEL(BookmarkNode *parent);
void readTitle(BookmarkNode *parent);
void readDescription(BookmarkNode *parent);
void readSeparator(BookmarkNode *parent);
void readFolder(BookmarkNode *parent);
void readBookmarkNode(BookmarkNode *parent);
};
#include <QtCore/QXmlStreamWriter>
class XbelWriter : public QXmlStreamWriter
{
public:
XbelWriter();
bool write(const QString &fileName, const BookmarkNode *root);
bool write(QIODevice *device, const BookmarkNode *root);
private:
void writeItem(const BookmarkNode *parent);
};
#endif // XBEL_H
| [
"[email protected]"
]
| [
[
[
1,
113
]
]
]
|
b148e2f303352b7d3b6a2bf6ff94882161e3195d | e680f7b7e88bedb2dc43701a5f192288258a4b1c | /src/cloth.cpp | 276c83355316b0ea2bf186882d4ff68ad112dfc2 | []
| no_license | pseudonumos/SpiderHunt | 870e4543d54adb6bda85912f37d20346daacc687 | 88156327a4393c9e5149ea3fb4d565f67a59a411 | refs/heads/master | 2016-08-03T18:43:29.403358 | 2011-03-09T06:21:55 | 2011-03-09T06:21:55 | 1,457,988 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,443 | cpp | #include "cloth.h"
#include "global.h"
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "Shaders.h"
namespace { // some anonymous helpers for file reading
// get a quoted string, unless there's no quote at the start
// in that case we just get whatever is there.
string getQuoted(istream &str) {
string ret;
char temp;
str >> temp;
if (temp != '"') {
str.putback(temp);
str >> ret;
} else {
getline(str, ret, '"');
}
return ret;
}
void getValue(istream &str, int &val) {
int v;
if (str >> v)
val = v;
}
}
Cloth::Cloth(string filename, string vertProg, string fragProg) {
// define external forces
// gravity = 1/MASS * vec3(0, -9.8, 0);
gravity = 1/MASS * vec3(0, 0, -9.8);
wind = vec3(.2, .2, 4.2);
x = -WIDTH/2 * STEP_SIZE;
y = 3;
z = -HEIGHT/2 * STEP_SIZE;
for (int i = 0; i < height; i++ ) {
for (int j = 0; j < width; j++ ) {
nodes[i][j] = new node(vec3(x + j*STEP_SIZE, y, z + i*STEP_SIZE));
}
}
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
// Structural Springs
// set adjacent nodes
if (i != 0) {
nodes[i][j]->adjNodes.push_back(nodes[i-1][j]);
}
if (j != 0) {
nodes[i][j]->adjNodes.push_back(nodes[i][j-1]);
}
if (i != height - 1) {
nodes[i][j]->adjNodes.push_back(nodes[i+1][j]);
}
if (j != width - 1) {
nodes[i][j]->adjNodes.push_back(nodes[i][j+1]);
}
// Shear Springs
// set diagonal nodes
if (i != 0 && j != 0) {
nodes[i][j]->adjNodes.push_back(nodes[i-1][j-1]);
}
if (i != 0 && j != width - 1) {
nodes[i][j]->adjNodes.push_back(nodes[i-1][j+1]);
}
if (i != height - 1 && j != 0) {
nodes[i][j]->adjNodes.push_back(nodes[i+1][j-1]);
}
if (i != height - 1 && j != width - 1) {
nodes[i][j]->adjNodes.push_back(nodes[i+1][j+1]);
}
// Flexion Springs
// set diagonal and adjacent nodes of length 2
if (i < height - 2 && j < width - 2) {
nodes[i][j]->flexNodes.push_back(nodes[i+2][j+2]);
}
if (i < height - 2 && j > 1) {
nodes[i][j]->flexNodes.push_back(nodes[i+2][j-2]);
}
if (j < width - 2 && i > 1) {
nodes[i][j]->flexNodes.push_back(nodes[i-2][j+2]);
}
if (i < height - 2) {
nodes[i][j]->flexNodes.push_back(nodes[i+2][j]);
}
if (j < width - 2) {
nodes[i][j]->flexNodes.push_back(nodes[i][j+2]);
}
if (i > 1 && j > 1) {
nodes[i][j]->flexNodes.push_back(nodes[i-2][j-2]);
}
if (i > 1) {
nodes[i][j]->flexNodes.push_back(nodes[i-2][j]);
}
if (j > 1) {
nodes[i][j]->flexNodes.push_back(nodes[i][j-2]);
}
}
}
// Load the track file
ifstream f(filename.c_str());
if (!f) {
UCBPrint("Sweep", "Couldn't load file " << filename);
return;
}
string line;
while (getline(f,line)) {
stringstream linestream(line);
string op;
linestream >> op;
if (op[0] == '#') // comments are marked by # at the start of a line
continue;
if (op == "p") { // p marks profile points (2d cross section vertices)
} else if (op == "v") { // v marks bspline control points with optional azimuth info
} else if (op == "twist") {
} else if (op == "azimuth") {
} else if (op == "texture") {
string textureFile = getQuoted(linestream);
loadTexture(textureFile, texture);
} else if (op == "bump") {
string bumpFile = getQuoted(linestream);
loadHeightAndNormalMaps(bumpFile, heightMap, normalMap, .2);
}
}
// compile link and validate shader programs
shadersFailed = false;
program = glCreateProgramObjectARB();
if (!setShader(program, vertProg.c_str(), GL_VERTEX_SHADER_ARB))
shadersFailed = true;
if (!setShader(program, fragProg.c_str(), GL_FRAGMENT_SHADER_ARB))
shadersFailed = true;
if (!linkAndValidateShader(program))
shadersFailed = true;
if (shadersFailed) {
cout << "Shaders failed to initialize correctly" << endl;
}
// start with all the nice settings on
shadersOn = true;
bumpMapEnabled = false;
textureMapEnabled = true;
// set up variables for the shaders to use
glUseProgramObjectARB(program);
glUniform1iARB(glGetUniformLocationARB(program, "textureMap"), 0);
glUniform1iARB(glGetUniformLocationARB(program, "heightMap"), 1);
glUniform1iARB(glGetUniformLocationARB(program, "normalMap"), 2);
// glUniform1iARB(glGetUniformLocationARB(program, "alphaMAp"), 3);
// alpha = glGetUniformLocationARB(program, "alphaMapEnabled");
bumpMapEnabledUniform = glGetUniformLocationARB(program, "bumpMapEnabled");
textureMapEnabledUniform = glGetUniformLocationARB(program, "textureMapEnabled");
tangentAttrib = glGetAttribLocationARB(program, "tangent");
bitangentAttrib = glGetAttribLocationARB(program, "bitangent");
}
Cloth::~Cloth() {
}
void Cloth::setWindForce() {
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
nodes[i][j]->windForce = vec3(0, 0, 0);
}
}
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
vec3 force = vec3(0, 0, 0);
vec3 p = nodes[i][j]->pos;
if (i != height - 1 && j != width - 1) {
vec3 v1 = nodes[i+1][j]->pos;
vec3 v2 = nodes[i][j+1]->pos;
vec3 n = (v1 - p) ^ (v2 - p);
double dot = wind * n;
force = n.normalize() * dot;
nodes[i][j]->windForce += force;
nodes[i+1][j]->windForce += force;
nodes[i][j+1]->windForce += force;
nodes[i][j]->normal = n;
}
if (i != 0 && j != 0) {
vec3 v1 = nodes[i][j-1]->pos;
vec3 v2 = nodes[i-1][j]->pos;
vec3 n = (v2 - p) ^ (v1 - p);
double dot = wind * n;
force = n.normalize() * dot;
nodes[i][j]->windForce += force;
nodes[i][j-1]->windForce += force;
nodes[i-1][j]->windForce += force;
nodes[i][j]->normal = n;
}
}
}
}
void Cloth::renderCloth(GLuint depthTextureId) {
if (shadersOn) {
glUseProgramObjectARB(program);
glUniform1iARB(bumpMapEnabledUniform, bumpMapEnabled);
glUniform1iARB(textureMapEnabledUniform, textureMapEnabled);
} else {
glUseProgramObjectARB(0);
}
// load textures
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, heightMap);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, normalMap);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);
glActiveTextureARB(GL_TEXTURE7);
glBindTexture(GL_TEXTURE_2D,depthTextureId);
//glCullFace(GL_BACK);
setWindForce();
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
// TOP LEFT AND BOTTOM LEFT CORNER REMAIN STATIONARY in a FLAG
if (j == 0) {
if (i == 0) {
top = nodes[i][j]->pos;
}
continue;
}
// APPLY GRAVITY
vec3 gravityForce = gravity;
nodes[i][j]->applyForce(gravityForce);
// APPLY WINDFORCE
vec3 windForce = nodes[i][j]->windForce;
// cout << "windForce: " << windForce << endl;
nodes[i][j]->applyForce(windForce);
// APPLY SPRINGFORCE
vec3 springForce = nodes[i][j]->getSpringForce();
nodes[i][j]->applyForce(springForce);
}
}
for (int i = 0; i < height - 1; i++) {
glBegin(GL_QUAD_STRIP);
for (int j = 0; j < width; j++) {
vec3 p = nodes[i][j]->pos;
vec3 pn = nodes[i][j]->normal;
glNormal3d(pn[0], pn[1], pn[2]);
glTexCoord2f(((double) j) / width, ((double)i) / height);
glVertex3f(p[0], p[1], p[2]);
vec3 q = nodes[i+1][j]->pos;
vec3 qn = nodes[i+1][j]->normal;
glNormal3d(qn[0], qn[1], qn[2]);
glTexCoord2f(((double) j) / width, ((double) (i + 1)) / height);
glVertex3f(q[0], q[1], q[2]);
}
glEnd();
}
glPushMatrix();
glTranslatef(top[0], top[1], -1.0 * HEIGHT*STEP_SIZE + top[2]);
GLUquadricObj * quadratic;
quadratic = gluNewQuadric();
gluQuadricDrawStyle(quadratic, GLU_FILL);
gluCylinder(quadratic, .05f, .05f, 3.5f, 32, 32);
glPopMatrix();
} | [
"[email protected]"
]
| [
[
[
1,
290
]
]
]
|
8de5328feb53765f39bf562e8c39f12cfd53938e | 6996a66a1a3434203d0b9a6433902654c41309c8 | /Vector.h | 1d30f0a181c4f8a8857df87e6349617dee81c08a | []
| no_license | dtbinh/CATALST-Robot-Formations-Simulator | 83509eba833f20f56311078049038da866d0b5a5 | f389557358588dcdf60c058c5ac0b55a5d2a7ae5 | refs/heads/master | 2020-05-29T08:45:57.510135 | 2011-06-29T08:54:27 | 2011-06-29T08:54:27 | 69,551,189 | 1 | 0 | null | 2016-09-29T09:12:48 | 2016-09-29T09:12:47 | null | UTF-8 | C++ | false | false | 4,742 | h | //
// Filename: "Vector.h"
//
// Programmer: Ross Mead
// Last modified: 30Nov2009
//
// Description: This class describes a 3-dimensional vector.
//
// preprocessor directives
#ifndef VECTOR_H
#define VECTOR_H
#include <cmath>
#include <iostream>
#include "Color.h"
#include "Utils.h"
using namespace std;
// global constants
static const Color DEFAULT_VECTOR_COLOR = WHITE;
static const GLfloat DEFAULT_VECTOR_TRANSLATE[3] = {0.0f, 0.0f, 0.0f};
static const GLfloat DEFAULT_VECTOR_ROTATE[3] = {0.0f, 0.0f, 0.0f};
static const GLfloat DEFAULT_VECTOR_SCALE[3] = {1.0f, 1.0f, 1.0f};
static const bool DEFAULT_VECTOR_SHOW_LINE = true;
static const bool DEFAULT_VECTOR_SHOW_HEAD = true;
static const GLfloat VECTOR_LINE_WIDTH = 1.0f;
static const GLfloat VECTOR_HEAD_HEIGHT = 0.015f;
static const GLfloat VECTOR_HEAD_WIDTH = 0.5f * VECTOR_HEAD_HEIGHT;
// describes a 3-dimensional vector
class Vector
{
public:
// <public data members>
GLfloat x, y, z;
GLfloat color[3], translate[3], rotate[3], scale[3];
bool showLine, showHead;
// <constructors>
Vector(const GLfloat dx = 0.0f,
const GLfloat dy = 0.0f,
const GLfloat dz = 0.0f,
const Color colorIndex = DEFAULT_VECTOR_COLOR);
Vector(const Vector &v);
// <destructors>
virtual ~Vector();
// <virtual public mutator functions>
virtual bool set(const GLfloat dx = 0.0f,
const GLfloat dy = 0.0f,
const GLfloat dz = 0.0f);
virtual bool set(const Vector &v);
virtual bool setColor(const GLfloat r,
const GLfloat g,
const GLfloat b);
virtual bool setColor(const GLfloat clr[3]);
virtual bool setColor(const Color colorIndex = DEFAULT_VECTOR_COLOR);
virtual void translated(const GLfloat dx,
const GLfloat dy,
const GLfloat dz);
virtual void translated(const Vector &v);
virtual void rotated(GLfloat theta);
virtual void rotateRelative(GLfloat theta);
virtual void scaled(GLfloat s);
// <public mutator functions>
bool setPolar(GLfloat magnitude = 1.0f,
GLfloat theta = 0.0f,
GLfloat dz = 0.0f);
bool setDiff(const Vector &dest, const Vector &source = Vector());
bool setAngle(const GLfloat theta = 0.0f);
bool setMagnitude(const GLfloat mag = 1.0f);
//bool setNorm(const GLfloat mag = 1.0f);
bool setPerp();
bool setAvg(const Vector v[], const GLint n = 1);
bool normalize();
// <virtual public utility functions>
virtual void draw();
// <public utility functions>
GLfloat angle() const;
GLfloat magnitude() const;
//GLfloat norm() const;
Vector perp();
GLfloat perpDot(const Vector &v) const;
// <virtual overloaded operators>
virtual Vector& operator =(const Vector &v);
virtual Vector operator +(const Vector &v);
virtual Vector operator -(const Vector &v);
virtual Vector& operator +=(const Vector &v);
virtual Vector& operator -=(const Vector &v);
virtual Vector& operator *=(const GLfloat scalar);
virtual bool operator ==(const Vector &v);
virtual bool operator !=(const Vector &v);
// <friend functions>
friend ostream& operator << (ostream &out, const Vector &v);
friend Vector operator -(const Vector &v);
friend Vector operator *(const GLfloat scalar, const Vector &v);
friend Vector operator *(const Vector &v, const GLfloat scalar);
friend Vector unit(const Vector &v);
friend Vector crossProduct(const Vector &v1, const Vector &v2);
friend GLfloat dotProduct(const Vector &v1,
const Vector &v2);
friend GLfloat angle(const Vector &v);
friend GLfloat angle(const Vector &v1, const Vector &v2);
protected:
// <virtual protected utility functions>
virtual bool init(const GLfloat dx = 0.0f,
const GLfloat dy = 0.0f,
const GLfloat dz = 0.0f,
const Color colorIndex = DEFAULT_VECTOR_COLOR);
}; // Vector
#endif
| [
"rossmead@larry.(none)"
]
| [
[
[
1,
125
]
]
]
|
c7a57c2a29f73850500a7974e6d334d370ad10b5 | d1d711ee8315f18a4d8a69ca832a398c17d73130 | /Bioinformatica-kernel/KernelString.cpp | 7f69eadbe5d73c40136809fc0c220fc927887572 | []
| no_license | cyper145/chessmaster | 87f5a74c4bc85704db1e151af3a7058427886b07 | 8ad79658132da24e88271d71f8003b317444ba0c | refs/heads/master | 2016-08-11T14:14:07.352514 | 2009-11-17T23:10:19 | 2009-11-17T23:10:19 | 47,511,972 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,392 | cpp | /*
* File: Main.cpp
* Author: Ramon
*
* Created on 16 de noviembre de 2008, 14:47
*/
// Leer un archivo de texto
#include <stdlib.h>
#include "kernelString.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include "kernelString.h"
using namespace std;
/*
*
*/
kernelString::kernelString()
{
}
kernelString::~kernelString()
{
}
double* kernelString::calcularPorGWSK(string charS, string charT, int n, int m, int p, double lambda) {
//Inicializamos las variables a utilizar.
double** DP;
double** DPS;
double* Kern;
//Creamos las matrices de forma dinamica y el vector tambien.
//Creamos matriz DP
DP = (double **) calloc(n + 1, sizeof (double *));
for (int i = 0; i < n + 1; i++)
DP[i] = (double *) calloc(m + 1, sizeof (double));
//Creamos matriz DPS
DPS = (double **) calloc(n, sizeof (double *));
for (int i = 0; i < n; i++)
DPS[i] = (double *) calloc(m, sizeof (double));
//Creamos el vector.
Kern = new double[p];
for (int i = 0; i < p; i++) {
Kern[i] = 0;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (charS[i] == charT[j]) {
DPS[i][j] = lambda*lambda;
}
}
}
for (int l = 1; l < p; l++) {
for (int i = 1; i < n + 1; i++) {
for (int j = 1; j < m + 1; j++) {
if (i != n && j != m){
DP[i][j] = DPS[i - 1][j - 1] + lambda * DP[i - 1][j] + lambda * DP[i][j - 1] - lambda * lambda * DP[i - 1][j - 1];
}
if (charS[i - 1] == charT[j - 1]) {
DPS[i - 1][j - 1] = lambda * lambda * DP[i - 1][j - 1];
Kern[l] = Kern[l] + DPS[i - 1][j - 1];
}
}
}
}
//Liberamos nuestra memoria..
for (int i = 0; i < n + 1; i++) {
free(DP[i]);
}
free(DP);
for (int i = 0; i < n; i++) {
free(DPS[i]);
}
free(DPS);
return Kern;
}
double* kernelString::calcularPorWNG(string charS, string charT, int n, int m, int p, double lambda) {
//Inicializamos las variables a utilizar.
double** DP;
double** DPS;
double* Kern;
//Creamos las matrices de forma dinamica y el vector tambien.
//Creamos matriz DP con n+1 filas y m+1 columnas
DP = (double **) calloc(n + 1, sizeof (double *));
for (int i = 0; i < n + 1; i++)
DP[i] = (double *) calloc(m + 1, sizeof (double));
//Creamos matriz DPS con n filas y m columnas.
DPS = (double **) calloc(n, sizeof (double *));
for (int i = 0; i < n; i++)
DPS[i] = (double *) calloc(m, sizeof (double));
//Creamos el vector.
Kern = new double[p];
for (int i = 0; i < p; i++) {
Kern[i] = 0;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (charS[i] == charT[j]) {
DPS[i][j] = 1;
}
}
}
for (int l = 1; l < p; l++) {
for (int i = 1; i < n + 1; i++) {
for (int j = 1; j < m + 1; j++) {
if (i != n && j != m)
DP[i][j] = DPS[i - 1][j - 1] + 1 * DP[i - 1][j] + 1 * DP[i][j - 1] - 1 * 1 * DP[i - 1][j - 1];
if (charS[i - 1] == charT[j - 1] && (i >= 2) && (j >= 2)) {
DPS[i - 1][j - 1] = DP[i - 1][j - 1] + (lambda - 1)*(DP[i - 2][j - 1] + DP[i - 1][j - 2] + (lambda - 1)*(DP[i - 2][j - 2]));
Kern[l] = Kern[l] + DPS[i - 1][j - 1];
}
}
}
}
//Liberamos nuestra memoria..
for (int i = 0; i < n + 1; i++) {
free(DP[i]);
}
free(DP);
for (int i = 0; i < n; i++) {
free(DPS[i]);
}
free(DPS);
return Kern;
}
/**
*Si encuentra la letra en el alfabeto, retorna el numero i que representa su posicion en el vector,
*sino retorna -1 en caso que no se encuentra.
*/
int kernelString::traerPos(char letra, vector<char> alfabeto)
{
for (int i = 0; i < alfabeto.size(); i++) {
if(alfabeto[i]==letra)
{
return i;
}
}
return -1;
}
double* kernelString::calcularPorCWSK(string charS, string charT, int n, int m, int p, double lambda, vector<double> vecLambda, vector<double> vecMiu, vector<char> alfabeto) {
//Inicializamos las variables a utilizar.
double** DP;
double** DPS;
double* Kern;
int posicionI = 0;
int posicionJ = 0;
//Creamos las matrices de forma dinamica y el vector tambien.
//Creamos matriz DP con n+1 filas y m+1 columnas
DP = (double **) calloc(n + 1, sizeof (double *));
for (int i = 0; i < n + 1; i++)
DP[i] = (double *) calloc(m + 1, sizeof (double));
//Creamos matriz DPS con n filas y m columnas.
DPS = (double **) calloc(n, sizeof (double *));
for (int i = 0; i < n; i++)
DPS[i] = (double *) calloc(m, sizeof (double));
//Creamos el vector.
Kern = new double[p];
for (int i = 0; i < p; i++) {
Kern[i] = 0;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (charS[i] == charT[j]) {
posicionI = kernelString::traerPos(charS[i], alfabeto);
if(posicionI >= 0){
DPS[i][j] = vecMiu[posicionI]*vecMiu[posicionI];
}
}
}
}
for (int l = 1; l < p; l++) {
for (int i = 1; i < n + 1; i++) {
for (int j = 1; j < m + 1; j++) {
if (i != n && j != m){
posicionI = kernelString::traerPos(charS[i - 1], alfabeto);
posicionJ = kernelString::traerPos(charT[j - 1], alfabeto);
if(posicionI >= 0 && posicionJ >= 0){
DP[i][j] = DPS[i - 1][j - 1] + vecLambda[posicionI]* DP[i - 1][j] + vecLambda[posicionJ]*( DP[i][j - 1] - vecLambda[posicionI]* DP[i - 1][j - 1]);
}
}
if (charS[i - 1] == charT[j - 1] && (i >= 2) && (j >= 2)) {
posicionI = kernelString::traerPos(charS[i - 1], alfabeto);
if(posicionI >= 0){
DPS[i - 1][j - 1] = vecMiu[posicionI]*vecMiu[posicionI]*DP[i - 1][j - 1];
Kern[l] = Kern[l] + DPS[i - 1][j - 1];
}
}
}
}
}
//Liberamos nuestra memoria..
for (int i = 0; i < n + 1; i++) {
free(DP[i]);
}
free(DP);
for (int i = 0; i < n; i++) {
free(DPS[i]);
}
free(DPS);
return Kern;
}
double* kernelString::calcularPorSMSK(string charS, string charT, int n, int m, int p, double lambda, vector<vector<double> > A, vector<char> alfabeto) {
//Inicializamos las variables a utilizar.
double** DP=0;
double** DPS=0;
double* Kern=0;
int posicionI = 0;
int posicionJ = 0;
//Creamos las matrices de forma dinamica y el vector tambien.
//Creamos matriz DP con n+1 filas y m+1 columnas
DP = (double **) calloc(n + 1, sizeof (double *));
for (int i = 0; i < n + 1; i++)
DP[i] = (double *) calloc(m + 1, sizeof (double));
//Creamos matriz DPS con n filas y m columnas.
DPS = (double **) calloc(n, sizeof (double *));
for (int i = 0; i < n; i++)
DPS[i] = (double *) calloc(m, sizeof (double));
//Creamos el vector.
Kern = new double[p];
for (int i = 0; i < p; i++) {
Kern[i] = 0;
}
for (int i = 0; i < n; i++) {
posicionI = kernelString::traerPos(charS[i], alfabeto);
for (int j = 0; j < m; j++) {
posicionJ = kernelString::traerPos(charT[j], alfabeto);
if(posicionI >= 0 && posicionJ >= 0){
if (A[posicionI][posicionJ] != 0) {
DPS[i][j] = lambda*lambda*A[posicionI][posicionJ];
}
}
}
}
for (int l = 1; l < p; l++) {
for (int i = 1; i < n + 1; i++) {
posicionI = kernelString::traerPos(charS[i - 1], alfabeto);
for (int j = 1; j < m + 1; j++) {
if (i != n && j != m){
DP[i][j] = DPS[i - 1][j - 1] + lambda* DP[i - 1][j] + lambda*DP[i][j - 1] - lambda*lambda* DP[i - 1][j - 1];
}
posicionJ = kernelString::traerPos(charT[j - 1], alfabeto);
if(posicionI >= 0 && posicionJ >= 0){
if (A[posicionI][posicionJ] != 0) {
DPS[i - 1][j - 1] = lambda*lambda*A[posicionI][posicionJ]*DP[i - 1][j - 1];
Kern[l] = Kern[l] + DPS[i - 1][j - 1];
}
}
}
}
}
//Liberamos nuestra memoria..
for (int i = 0; i < n + 1; i++) {
free(DP[i]);
}
free(DP);
for (int i = 0; i < n; i++) {
free(DPS[i]);
}
free(DPS);
return Kern;
} | [
"aferreiraduarte@4eb812f8-a032-11dd-a874-8d3a81574e67",
"mavalosgodoy@4eb812f8-a032-11dd-a874-8d3a81574e67"
]
| [
[
[
1,
6
],
[
8,
11
],
[
17,
17
],
[
20,
24
],
[
26,
35
],
[
37,
38
],
[
43,
43
],
[
48,
48
],
[
50,
52
],
[
54,
55
],
[
58,
61
],
[
72,
75
],
[
79,
79
],
[
83,
84
],
[
86,
93
],
[
95,
96
],
[
101,
101
],
[
106,
106
],
[
108,
110
],
[
112,
113
],
[
116,
118
],
[
120,
120
],
[
130,
130
],
[
132,
132
],
[
136,
136
],
[
140,
141
],
[
143,
158
],
[
298,
298
]
],
[
[
7,
7
],
[
12,
16
],
[
18,
19
],
[
25,
25
],
[
36,
36
],
[
39,
42
],
[
44,
47
],
[
49,
49
],
[
53,
53
],
[
56,
57
],
[
62,
71
],
[
76,
78
],
[
80,
82
],
[
85,
85
],
[
94,
94
],
[
97,
100
],
[
102,
105
],
[
107,
107
],
[
111,
111
],
[
114,
115
],
[
119,
119
],
[
121,
129
],
[
131,
131
],
[
133,
135
],
[
137,
139
],
[
142,
142
],
[
159,
297
]
]
]
|
2a78f819a8ceed237ad7cefb634f2252ccf31b5b | 36d0ddb69764f39c440089ecebd10d7df14f75f3 | /プログラム/Game/Manager/Object/ObjectFactory.h | 199bdf4f4e3d7eb47e7a1439810c2bff5e46a691 | []
| no_license | weimingtom/tanuki-mo-issyo | 3f57518b4e59f684db642bf064a30fc5cc4715b3 | ab57362f3228354179927f58b14fa76b3d334472 | refs/heads/master | 2021-01-10T01:36:32.162752 | 2009-04-19T10:37:37 | 2009-04-19T10:37:37 | 48,733,344 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 2,434 | h | /*******************************************************************************/
/**
* @file ObjectFactory.h.
*
* @brief オブジェクト生成基底クラスの定義.
*
* @date 2008/11/25.
*
* @version 1.00.
*
* @author Kenji Iwata.
*/
/*******************************************************************************/
#ifndef _OBJECT_FACTORY_H_
#define _OBJECT_FACTORY_H_
/*===== インクルード ==========================================================*/
class ObjectManager;
class IGameDevice;
class Option;
class ObjectBase;
class GameScene;
class GameSceneState;
class Player;
class Block;
class BackGround;
class Result;
class ReadyGo;
/**
* @brief ObjectFactory.
*/
class ObjectFactory
{
public:
/*=========================================================================*/
/**
* @brief コンストラクタ.
*
* @param[in] device ゲームデバイス.
* @param[in] ObjectManager オブジェクトマネージャメディエータ.
* @param[in] option ゲームオプション.
*/
ObjectFactory(IGameDevice& device, ObjectManager& objectManager, Option& option);
/*=========================================================================*/
/**
* @brief デストラクタ.
*/
~ObjectFactory();
/*=========================================================================*/
/**
* @brief オブジェクトの生成.
*
* @param[in] objectID 生成するオブジェクトのID.
* @return 生成したオブジェクトのポインタ.
*/
Player* CreatePlayer(GameSceneState& gameSceneState, float x, float y, int maxHp, int hp, int skillpoint[],
int maxPlayerTime,int playerTime, int characterID, int score, int playerID, int playerLV, int playerAttack,
int playerDefence, int playerType);
Block* CreateBlock(GameSceneState& gameSceneState,Player& player, int blockCID, int blockMID);
BackGround* CreateBackGround(GameSceneState& gameSceneState);
Result* CreateResult(GameSceneState& gameSceneState);
ReadyGo* CreateReadyGo(GameSceneState& gameSceneState);
private:
/** ゲームデバイス */
IGameDevice& m_device;
/** オブジェクトマネージャメディエータ */
ObjectManager& m_objectManager;
/** ゲームオプション */
Option& m_option;
};
#endif
/*===== EOF ===================================================================*/
| [
"rs.drip@aa49b5b2-a402-11dd-98aa-2b35b7097d33"
]
| [
[
[
1,
86
]
]
]
|
c90d4d428274022bc1809ba2eb16b74b98bc1c64 | accd6e4daa3fc1103c86d245c784182e31681ea4 | /HappyHunter/Effect/stdafx.cpp | db0e2034b60a40ccb65c82c271b5587233540b3f | []
| 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 | GB18030 | C++ | false | false | 266 | cpp | // stdafx.cpp : 只包括标准包含文件的源文件
// Effect.pch 将作为预编译头
// stdafx.obj 将包含预编译类型信息
#include "stdafx.h"
// TODO: 在 STDAFX.H 中
// 引用任何所需的附加头文件,而不是在此文件中引用
| [
"[email protected]"
]
| [
[
[
1,
8
]
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.