blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
7
license_type
stringclasses
2 values
repo_name
stringlengths
6
79
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
4 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.07k
426M
star_events_count
int64
0
27
fork_events_count
int64
0
12
gha_license_id
stringclasses
3 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
6 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
20
6.28M
extension
stringclasses
20 values
content
stringlengths
20
6.28M
authors
sequencelengths
1
16
author_lines
sequencelengths
1
16
4452b93a4ae6efba2f30e0a573e5855fa9375d45
70ae839ba975347dc4c97ce6ff3e87056d4baa5e
/Tutorial4/Tutorial4/include/client.h
93b7f5112bc39eec04a258d7117dd5d1b08a94dd
[]
no_license
jbreslin33/networksinbad
63a81d9a240b517b1a631bd2173dcd0bbe8ff7cb
e9f15b83aab010bfc7ae570880c11ec6d52aadf9
refs/heads/master
2020-06-03T15:20:15.140383
2011-03-12T13:41:51
2011-03-12T13:41:51
37,391,302
0
0
null
null
null
null
UTF-8
C++
false
false
3,132
h
#ifndef CLIENT_H #define CLIENT_H #include "BaseApplication.h" #include "common.h" //#include "Tutorial4.h" class SinbadCharacterController; extern bool keys[256]; typedef struct { float x; float y; } VECTOR2D; typedef struct { float w; float x; float y; float z; } QUATERNION; typedef struct { int key; VECTOR2D vel; VECTOR2D origin; VECTOR2D predictedOrigin; QUATERNION rot; QUATERNION predictedRot; //float yaw; int msec; } command_t; typedef struct clientData { command_t frame[64]; // frame history command_t serverFrame; // the latest frame from server command_t command; // current frame's commands int index; VECTOR2D startPos; bool team; char nickname[30]; char password[30]; Ogre::SceneNode *myNode; SinbadCharacterController* character; clientData *next; } clientData; // The main application class interface class CArmyWar : public BaseApplication { private: // Methods // Client.cpp void DrawMap(void); void CheckPredictionError(int a); void CalculateVelocity(command_t *command, float frametime); void PredictMovement(int prevFrame, int curFrame); void MoveObjects(void); void MovePlayer(void); void setKeyDirection(command_t *command, float frametime); void AddClient(int local, int index, char *name); void RemoveClient(int index); void RemoveClients(void); // Network.cpp void ReadPackets(void); void SendCommand(void); void SendRequestNonDeltaFrame(void); void ReadMoveCommand(dreamMessage *mes, clientData *client); void ReadDeltaMoveCommand(dreamMessage *mes, clientData *client); void BuildDeltaMoveCommand(dreamMessage *mes, clientData *theClient); bool processUnbufferedInput(const Ogre::FrameEvent& evt); // Variables // Network variables dreamClient *networkClient; clientData *clientList; // Client list clientData *localClient; // Pointer to the local client in the client list int clients; clientData inputClient; // Handles all keyboard input float frametime; float rendertime; char gamename[32]; bool init; //bool mapdata[100][100]; int gameIndex; SinbadCharacterController* character; public: CArmyWar(); ~CArmyWar(); void createPlayer(int index); virtual void createScene(void); virtual bool frameRenderingQueued(const Ogre::FrameEvent& evt); virtual bool keyPressed( const OIS::KeyEvent &arg ); virtual bool keyReleased( const OIS::KeyEvent &arg ); // Client.cpp void Shutdown(void); void CheckKeys(void); void Frame(void); void RunNetwork(int msec); // Network.cpp void StartConnection(); void Connect(void); void Disconnect(void); void SendStartGame(void); void SetName(char *n) { strcpy(gamename, n); } char *GetName(void) { return gamename; } void SetGameIndex(int index) { gameIndex = index; } int GetGameIndex(void) { return gameIndex; } clientData *GetClientList(void) { return clientList; } clientData *GetClientPointer(int index); CArmyWar *next; }; #endif
[ [ [ 1, 153 ] ] ]
60bfcdb358e4b14a5c43a980f3f42b3f4e321ed5
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/_Multimedia/MP3/OBUFFER5.CPP
c5d2c39f1d3f2412763f176810ae27d8f94345ca
[]
no_license
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
10,055
cpp
/* * @(#) obuffer.cc 1.15, last edit: 6/23/94 13:04:36 * @(#) Copyright (C) 1993, 1994 Tobias Bading ([email protected]) * @(#) Berlin University of Technology * * Idea and first implementation for u-law output with fast downsampling by * Jim Boucher ([email protected]) * * LinuxObuffer class written by * Louis P. Kruger ([email protected]) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* * Changes from version 1.1 to 1.2: * - new LinuxObuffer class, which works with 16 bit soundcards * like Gravis Ultrasound, SoundBlaster 16 or Pro Audio Spectrum 16, * if attached to /dev/dsp * - ShortObuffer renamed to FileObuffer * - If ULAW is defined: * - SparcObuffer feeds mono u-law output to an amd device (u-law format). * The required downsampling to 8 kHz in done in the synthesis filter. * - FileObuffer creates u-law output at 8 kHz instead of 16 bit PCM samples. * - O_NDELAY flag is cleared now after a successful open syscall * on /dev/audio (caused problems under Solaris) * - options -us, -uh and -ul should work now * - FileObuffer can handle incomplete write syscalls now */ /* MCIbuffer class added by Jeff Tsay (last edit: 05/18/96) Writing to Windows multimedia system with such a small buffer won't do, so we increase buffer size, and ignore most of the writes. Also we need to have a queue of 3 wave headers for smooth playback. The last header and the oldest header play while the current one is being filled in. Note that this does not support 8-bit soundcards yet! I don't know what the data format is to that */ /* Changes since last version: changed GMEM_MOVEABLE to GMEM_FIXED which is a bit faster, according to the suggestions of Paul Forgey. clear_buffer() added for seeking. Changes int16 parameter to int32 for minor speed improvement. Last edit: 06/29/96. */ /* More changes: eliminated GlobalLock on the fixed memory, which is unnecessary. Added a function clear_buffer(), which clears the audio data when a seek is made by the user. Also added a function set_stop_flag() which sets a flag when playback is interrupted by the user. Then no attempt is made to unprepare headers after waveReset() is called by the main thread. Last edit: 10/12/96. */ /* Replaced usage of the PCMWAVEFORMAT structure with the more up to date WAVEFORMATEX structure. According to the suggestions of Sergey Kuzmin, replaced GlobalAlloc and GlobalFree with new and delete, which should eliminate memory leaks. Last edit: 12/31/96. */ #define STRICT #define WIN32_LEAN_AND_MEAN #define NOMCX #define NOIME #define NOGDI #define NOUSER #define NOSOUND #define NOCOMM #define NODRIVERS #define OEMRESOURCE #define NONLS #define NOSERVICE #define NOKANJI #define NOMINMAX #define NOLOGERROR #define NOPROFILER #define NOMEMMGR #define NOLFILEIO #define NOOPENFILE #define NORESOURCE #define NOATOM #define NOLANGUAGE #define NOLSTRING #define NODBCS #define NOKEYBOARDINFO #define NOGDICAPMASKS #define NOCOLOR #define NOGDIOBJ #define NODRAWTEXT #define NOTEXTMETRIC #define NOSCALABLEFONT #define NOBITMAP #define NORASTEROPS #define NOMETAFILE #define NOSYSMETRICS #define NOSYSTEMPARAMSINFO #define NOMSG #define NOWINSTYLES #define NOWINOFFSETS #define NOSHOWWINDOW #define NODEFERWINDOWPOS #define NOVIRTUALKEYCODES #define NOKEYSTATES #define NOWH #define NOMENUS #define NOSCROLL #define NOCLIPBOARD #define NOICONS #define NOMB #define NOSYSCOMMANDS #define NOMDI #define NOCTLMGR #define NOWINMESSAGES #define NOHELP #define _WINUSER_ #define __oleidl_h__ #define _OLE2_H_ #include "stdafx.h" #include "obuffer.h" #include "obuffer5.h" // Windows addition #include "header.h" MCIbuffer::MCIbuffer (uint32 number_of_channels, Header *header, HWAVEOUT *phwo0) { int32 i; LPWAVEHDR temp; channels= number_of_channels; data_size= channels * BUFFERSIZE; hdr_size= sizeof(WAVEHDR); lpwavehdr_arr=new LPWAVEHDR[3]; phwo=phwo0; fillup=0; lpwf = (tWAVEFORMATEX *) new WAVEFORMATEX; lpwf->wBitsPerSample=16; // No 8-bit support yet lpwf->wFormatTag=WAVE_FORMAT_PCM; lpwf->nChannels=(WORD) channels; lpwf->nSamplesPerSec=(DWORD) header->frequency (); lpwf->nAvgBytesPerSec=(DWORD) channels * header->frequency() << 1; lpwf->nBlockAlign=(WORD) (channels << 1); lpwf->cbSize = 0; if (waveOutOpen(phwo, WAVE_MAPPER, (const tWAVEFORMATEX *) lpwf, NULL, NULL, WAVE_ALLOWSYNC)) ExitThread(1L); buffer_count=0; for(i=0; i<3; i++) { lpwavehdr_arr[i] = (LPWAVEHDR) new WAVEHDR; temp = lpwavehdr_arr[i]; if(!temp) ExitThread(1L); temp->lpData=(LPSTR) new char[data_size]; if(!temp->lpData) ExitThread(1L); temp->dwBufferLength=data_size; temp->dwBytesRecorded=0L; temp->dwUser=0L; // If played, dwUser = 1 temp->dwLoops=0L; temp->dwFlags=NULL; } for(i=0; i<channels; i++) bufferp[i]=i * channels; user_stop = 0; } void MCIbuffer::append (uint32 channel, int32 value) { // Need to break up the 32-bit integer into 2 8-bit bytes. // (ignore the first two bytes - either 0x0000 or 0xffff) // Note that Intel byte order is backwards!!! LPSTR temp=lpwavehdr_arr[2]->lpData; temp[bufferp[channel]]= (char) (value & 0xff); temp[bufferp[channel]+1] = (char) (value >> 8); bufferp[channel]+= channels << 1; return; } //#pragma argsused void MCIbuffer::write_buffer (int fd) { // Actually write only when buffer is actually full. if ((++buffer_count & BIT_SELECT)==0) { int32 i; buffer_count=0; // Wait for 2 completed headers if (fillup>1) { // Prepare+write newest header while (waveOutPrepareHeader(*phwo, lpwavehdr_arr[2], hdr_size)) Sleep(SLEEPTIME); while(waveOutWrite(*phwo, lpwavehdr_arr[2], hdr_size)) Sleep(SLEEPTIME); // Header has now been sent lpwavehdr_arr[2]->dwUser=1L; wave_swap(); // Unprepare oldest header if (lpwavehdr_arr[2]->dwUser) { while(waveOutUnprepareHeader(*phwo, lpwavehdr_arr[2], hdr_size)==WAVERR_STILLPLAYING) Sleep(SLEEPTIME); } } else { if (++fillup == 2) { // Write the previously calculated 2 headers while (waveOutPrepareHeader(*phwo, lpwavehdr_arr[0], hdr_size)) Sleep(SLEEPTIME); while(waveOutWrite(*phwo, lpwavehdr_arr[0], hdr_size)) Sleep(SLEEPTIME); // Header has now been sent lpwavehdr_arr[0]->dwUser=1L; wave_swap(); while (waveOutPrepareHeader(*phwo, lpwavehdr_arr[0], hdr_size)) Sleep(SLEEPTIME); while(waveOutWrite(*phwo, lpwavehdr_arr[0], hdr_size)) Sleep(SLEEPTIME); // Header has now been sent lpwavehdr_arr[0]->dwUser=1L; } else wave_swap(); } for(i=0; i<channels; i++) bufferp[i]=i * channels; } return; } void MCIbuffer::wave_swap(void) { int32 i; LPWAVEHDR temp=lpwavehdr_arr[2]; for(i=2;i>0; i--) lpwavehdr_arr[i]=lpwavehdr_arr[i-1]; lpwavehdr_arr[0]=temp; return; } void MCIbuffer::clear_buffer(void) // Clear all the data in the buffers { int32 i, j; LPWAVEHDR temp; waveOutReset(*phwo); for(i=0; i<3; i++) { temp = lpwavehdr_arr[i]; if (temp->dwUser) waveOutUnprepareHeader(*phwo, temp, hdr_size); temp->dwUser = 0; for(j=0; j<data_size; j++) temp->lpData[j] = (char) 0; } // Reset buffer pointers for(i=0; i<channels; i++) bufferp[i]=i * channels; // Force the buffers to fillup before playing. fillup = buffer_count = 0; } void MCIbuffer::set_stop_flag(void) // Set the flag to avoid unpreparing non-existent headers { user_stop = 1; return; } MCIbuffer::~MCIbuffer(void) { int32 i, j; if ((fillup==1) && !user_stop) { // Write the last header calculated (at the top of the array). while (waveOutPrepareHeader(*phwo, lpwavehdr_arr[0], hdr_size)) Sleep(SLEEPTIME); while(waveOutWrite(*phwo, lpwavehdr_arr[0], hdr_size)) Sleep(SLEEPTIME); // Header has been written. lpwavehdr_arr[0]->dwUser=1L; } if (buffer_count && !user_stop) { /* Write the last wave header (probably not be written due to buffer size increase.) */ for(i= bufferp[channels-1]; i< data_size; i++) lpwavehdr_arr[2]->lpData[i]= (char) 0; while (waveOutPrepareHeader(*phwo, lpwavehdr_arr[2], hdr_size)) Sleep(SLEEPTIME); while(waveOutWrite(*phwo, lpwavehdr_arr[2], hdr_size)) Sleep(SLEEPTIME); // Header has been written. lpwavehdr_arr[2]->dwUser=1L; wave_swap(); } // Unprepare and free the header memory. for (j=2; j>=0; j--) { if (lpwavehdr_arr[j]->dwUser && !user_stop) while (waveOutUnprepareHeader(*phwo, lpwavehdr_arr[j], hdr_size) ==WAVERR_STILLPLAYING) Sleep(SLEEPTIME); safe_delete_array( lpwavehdr_arr[j]->lpData ); safe_delete( lpwavehdr_arr[j] ); } safe_delete_array( lpwavehdr_arr ); safe_delete( lpwf ); if (!user_stop) // Wave device already closed if user_stop while(waveOutClose(*phwo)) Sleep(SLEEPTIME); return; }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 387 ] ] ]
ba4ff37ff642d2ae1b0598a54fb3ef86c4906197
ad80c85f09a98b1bfc47191c0e99f3d4559b10d4
/code/src/gfx/ngltex_openil.cc
121d28c4a9ae51106c5831e06c8915cea1d3ceb2
[]
no_license
DSPNerd/m-nebula
76a4578f5504f6902e054ddd365b42672024de6d
52a32902773c10cf1c6bc3dabefd2fd1587d83b3
refs/heads/master
2021-12-07T18:23:07.272880
2009-07-07T09:47:09
2009-07-07T09:47:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,951
cc
#define N_IMPLEMENTS nGlTexture //------------------------------------------------------------------------------ /** ngltex_openil.cc Texture load function using OpenIL library functions. (C) A.Weissflog 2001 */ #include "gfx/ngltexture.h" #include "gfx/ns3tcgltexture.h" #include "gfx/nopenilfile.h" #ifdef _UNICODE #undef _UNICODE #endif #include "il/il.h" #include "il/ilu.h" static unsigned int nextPOW2(unsigned int val) { unsigned int i; for (i = 1; i < (1<<30); i <<= 1) if (val <= i) return i; return i; } bool nGlTexture::loadFileIntoTextureDDS(const char* fileName){ nOpenILFile oilFile(this->kernelServer); oilFile.Open(fileName); nS3TCGlTexture texture; if (!texture.Load(oilFile.GetFile())) return false; long width = texture.width; long height = texture.height; long size; long offset = 0; this->SetWidth(width); this->SetHeight(height); this->SetBytesPerPixel(texture.bufsize/(width*height)); glGenTextures(1, &this->tex_id); glBindTexture(GL_TEXTURE_2D, this->tex_id); /* load the mipmaps */ for (long i = 0; i < texture.numMipmaps && (width || height); ++i) { if (width == 0) width = 1; if (height == 0) height = 1; size = ((width + 3) / 4) * ((height + 3) / 4) * texture.blockSize; glCompressedTexImage2DARB(GL_TEXTURE_2D, i, texture.GLformat, width, height, 0, size, texture.pixels + offset); offset += size; width >>= 1; height >>= 1; if (glGetError() != GL_NO_ERROR) { return false; } } #ifdef _DEBUG_DDS n_printf("nGL Texture: DDS: loaded successfully'%s'\n", fileName); #endif return true; } //------------------------------------------------------------------------------ /** Load an image file into an OpenGL texture. Allocate a new OpenGL texture and write its name to this->tex_id. @param fileName filename of the texture file @return true if texture successfully loaded and bound + 05-Nov-2002 Ilya compressed textures support */ bool nGlTexture::loadFileIntoTextureIL(const char* fileName) { n_assert(UINT_MAX == this->tex_id); // load the image ILenum il_type = GetILType(fileName); if (il_type == IL_DDS && (glCompressedTexImage2DARB != 0)) { if (this->loadFileIntoTextureDDS( fileName )) return true; #ifdef _DEBUG else n_printf("failed to load compresssed texture %s loading in usual way\n", fileName); #endif } nOpenILFile oilFile(this->kernelServer); oilFile.Open(fileName); if (oilFile.ReadData() < 0) return false; ILuint imgId; ilGenImages(1, &imgId); ilBindImage(imgId); if (!ilLoadL(il_type, oilFile.GetData(), oilFile.GetSize())) { n_printf("nGlTexture: Failed loading image file '%s' as texture!\n", fileName); n_printf("OpenIL error: '%s'\n", iluErrorString(ilGetError())); ilDeleteImages(1, &imgId); return false; } if (il_type == IL_DDS) { iluFlipImage(); } if (!this->createTextureIL(fileName, imgId)) { ilDeleteImages(1, &imgId); return false; } // gracefully exit on failure ilDeleteImages(1, &imgId); return true; } //------------------------------------------------------------------------------ /** Load an image from memory into a opengl texture using DevIL image loading and mipmap generation functions. @param p - pointer to memory chunk contains texture size - size of those chunk @return true if texture successfully loaded +27-jul-2002 --Ilya Kliot */ bool nGlTexture::loadFromMem(void* p, unsigned long size, long maxw, long maxh) { n_assert(UINT_MAX == this->tex_id); // load the image ILuint imgId; ilGenImages(1, &imgId); ilBindImage(imgId); if (!ilLoadL(IL_BMP, p, size)) { n_printf("nGlTexture: Failed loading image from memory as texture!\n"); n_printf("OpenIL error: '%s'\n", iluErrorString(ilGetError())); ilDeleteImages(1, &imgId); return false; } if (!this->createTextureIL("memory", imgId, maxw, maxh)) { ilDeleteImages(1, &imgId); return false; } // gracefully exit on failure ilDeleteImages(1, &imgId); return true; } //------------------------------------------------------------------------------ /** Create an OpenGL texture using DevIL image manipulation and mipmap generation functions. @param name of the texture imgid id of texture in devil @return true if texture successfully loaded +02-feb-2003 --Ilya Kliot */ bool nGlTexture::createTextureIL(const char* name, int imgId, long maxw, long maxh) { ilBindImage(imgId); // if this is a paletted image, convert it to RGB format if (ilGetInteger(IL_IMAGE_FORMAT) == IL_COLOR_INDEX) { if (!ilConvertImage(IL_RGB, IL_UNSIGNED_BYTE)) { n_printf("nGlTexture: %s ilConvertImage() failed with '%s'\n", name, iluErrorString(ilGetError())); return false; } } int imgWidth = ilGetInteger(IL_IMAGE_WIDTH); int imgHeight = ilGetInteger(IL_IMAGE_HEIGHT); // force texture dimensions to power of 2 int newW = nextPOW2(imgWidth); int newH = nextPOW2(imgHeight); if (maxw > 0 && newW > maxw) newW = maxw; if (maxh > 0 && newH > maxh) newH = maxh; iluImageParameter(ILU_FILTER, ILU_BILINEAR); if ((imgWidth != newW) || (imgHeight != newH)) { if (!iluScale(newW, newH, 1)) { n_printf("nGlTexture: %s iluScale() failed with '%s'\n", name, iluErrorString(ilGetError())); return false; } imgWidth = newW; imgHeight = newH; } // generate mipmaps if necessary if (this->gen_mipmaps) { if (!iluBuildMipmaps()) { n_printf("nGlTexture: %s iluBuildMipmaps() failed with '%s'\n", name, iluErrorString(ilGetError())); return false; } } // bind the images to OpenGL glGenTextures(1, &this->tex_id); glBindTexture(GL_TEXTURE_2D, this->tex_id); // for each mipmap level... ILint numMipmaps = ilGetInteger(IL_NUM_MIPMAPS); GLint components = ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL); GLenum type = (GLenum) ilGetInteger(IL_IMAGE_TYPE); GLenum format = (GLenum) ilGetInteger(IL_IMAGE_FORMAT); this->SetWidth(imgWidth); this->SetHeight(imgHeight); this->SetBytesPerPixel(components); this->SetNumMipLevels(numMipmaps + 1); for (GLint curLevel = 0; curLevel <= numMipmaps; curLevel++) { // need to rebind original image before selecting // mipmap level (is this a design bug in OpenIL?) ilBindImage(imgId); if (!ilActiveMipmap(curLevel)) { n_printf("nGlTexture: %s ilActiveMipmap() failed with '%s'\n", name, iluErrorString(ilGetError())); return false; } glTexImage2D(GL_TEXTURE_2D, // target curLevel, // mipmap level-of-detail components, // components (internal format) ilGetInteger(IL_IMAGE_WIDTH), // width ilGetInteger(IL_IMAGE_HEIGHT), // height 0, // border format, // format (GL_RGB, GL_RGBA...) type, // type (GL_UNSIGNED_unsigned char...) (GLvoid*) ilGetData()); // pointer to image data } ilActiveMipmap(0); return true; }
[ "plushe@411252de-2431-11de-b186-ef1da62b6547" ]
[ [ [ 1, 269 ] ] ]
9569e6c47422370b5f8022405deeb8208c916d6f
3e69b159d352a57a48bc483cb8ca802b49679d65
/tags/release-2006-01-03/eeschema/bus-wire-junction.cpp
acec1f4ad257b5eff319efd9b2c2e08a3b094c92
[]
no_license
BackupTheBerlios/kicad-svn
4b79bc0af39d6e5cb0f07556eb781a83e8a464b9
4c97bbde4b1b12ec5616a57c17298c77a9790398
refs/heads/master
2021-01-01T19:38:40.000652
2006-06-19T20:01:24
2006-06-19T20:01:24
40,799,911
0
0
null
null
null
null
ISO-8859-1
C++
false
false
19,012
cpp
/*********************************************************/ /* Modules de creations de Traits, Wires, Bus, Junctions */ /*********************************************************/ #include "fctsys.h" #include "gr_basic.h" #include "common.h" #include "program.h" #include "libcmp.h" #include "general.h" #include "protos.h" /* Routines Locales */ static void Polyline_in_Ghost(WinEDA_DrawPanel * panel, wxDC * DC, bool erase); static void Segment_in_Ghost(WinEDA_DrawPanel * panel, wxDC * DC, bool erase); static void ExitTrace(WinEDA_DrawFrame * frame, wxDC * DC); static bool IsTerminalPoint(SCH_SCREEN * screen, const wxPoint & pos, int layer ); static bool IsJunctionNeeded (WinEDA_SchematicFrame * frame, wxPoint & pos ); wxPoint s_ConnexionStartPoint; /*************************************************************/ void WinEDA_SchematicFrame::BeginSegment(wxDC * DC, int type) /*************************************************************/ /* Create a new segment ( WIRE, BUS ). */ { EDA_DrawLineStruct * oldsegment, * newsegment; wxPoint pos = GetScreen()->m_Curseur; if ( GetScreen()->m_CurrentItem && (GetScreen()->m_CurrentItem->m_Flags == 0) ) GetScreen()->m_CurrentItem = NULL; if ( GetScreen()->m_CurrentItem ) { switch (GetScreen()->m_CurrentItem->m_StructType ) { case DRAW_SEGMENT_STRUCT_TYPE: case DRAW_POLYLINE_STRUCT_TYPE: break; default: return; } } oldsegment = newsegment = (EDA_DrawLineStruct *) GetScreen()->m_CurrentItem; if (!newsegment) /* first point : Create first wire ou bus */ { s_ConnexionStartPoint = pos; SchematicCleanUp(NULL); switch(type) { default: newsegment = new EDA_DrawLineStruct(pos, LAYER_NOTES); break; case LAYER_WIRE: newsegment = new EDA_DrawLineStruct(pos, LAYER_WIRE); /* A junction will be created later, when w'll know the segment end, and if the junction is really needed */ break; case LAYER_BUS: newsegment = new EDA_DrawLineStruct(pos, LAYER_BUS); break; } newsegment->m_Flags = IS_NEW; GetScreen()->m_CurrentItem = newsegment; GetScreen()->ManageCurseur = Segment_in_Ghost; GetScreen()->ForceCloseManageCurseur = ExitTrace; g_ItemToRepeat = NULL; } else /* Trace en cours: Placement d'un point supplementaire */ { if( (oldsegment->m_Start.x == oldsegment->m_End.x) && (oldsegment->m_Start.y == oldsegment->m_End.y) ) /* Structure inutile */ return; GetScreen()->ManageCurseur(DrawPanel, DC, FALSE); /* Creation du segment suivant ou fin de tracé si point sur pin, jonction ...*/ if ( IsTerminalPoint(GetScreen(), oldsegment->m_End, oldsegment->m_Layer) ) { EndSegment(DC); return; } /* Placement en liste generale */ oldsegment->Pnext = GetScreen()->EEDrawList; g_ItemToRepeat = GetScreen()->EEDrawList = oldsegment; GetScreen()->Trace_Curseur(DrawPanel, DC); // Erase schematic cursor RedrawOneStruct(DrawPanel,DC, oldsegment, GR_DEFAULT_DRAWMODE); GetScreen()->Trace_Curseur(DrawPanel, DC); // Display schematic cursor /* Creation du segment suivant */ newsegment = oldsegment->GenCopy(); newsegment->m_Start = oldsegment->m_End; newsegment->m_End = pos; oldsegment->m_Flags = 0; newsegment->m_Flags = IS_NEW; GetScreen()->m_CurrentItem = newsegment; GetScreen()->ManageCurseur(DrawPanel, DC, FALSE); if ( (oldsegment->m_Start.x == s_ConnexionStartPoint.x) && (oldsegment->m_Start.y == s_ConnexionStartPoint.y)) { /* This is the first segment: Now we know the start segment position. Create a junction if needed. Note: a junction can be needed later, if the new segment is merged (after a cleanup) with an older one (tested when the connection will be finished)*/ if ( IsJunctionNeeded(this, s_ConnexionStartPoint) ) CreateNewJunctionStruct(DC, s_ConnexionStartPoint); } } } /*************************************************************/ /* Routine de fin de trace d'une struct segment (Wire, Bus */ /*************************************************************/ void WinEDA_SchematicFrame::EndSegment(wxDC *DC) { EDA_DrawLineStruct * segment = (EDA_DrawLineStruct *)GetScreen()->m_CurrentItem; wxPoint end_point = segment->m_End; if ( GetScreen()->ManageCurseur == NULL ) return; if ( segment == NULL ) return; if ( (segment->m_Flags & IS_NEW) == 0) return; if( (segment->m_Start.x == segment->m_End.x) && (segment->m_Start.y == segment->m_End.y) ) /* Structure inutile */ { EraseStruct(segment, (SCH_SCREEN*)GetScreen()); segment = NULL; } else { /* Put it in Drawlist */ GetScreen()->ManageCurseur(DrawPanel, DC, FALSE); segment->Pnext = GetScreen()->EEDrawList; g_ItemToRepeat = GetScreen()->EEDrawList = segment; segment->m_Flags = 0; } /* Fin de trace */ GetScreen()->ManageCurseur = NULL; GetScreen()->ForceCloseManageCurseur = NULL; GetScreen()->m_CurrentItem = NULL; SchematicCleanUp(NULL); // Automatic place of a junction on the end point, if needed DrawJunctionStruct * junction1 = NULL, * junction2 = NULL; if ( IsJunctionNeeded(this, end_point) ) { junction1 = CreateNewJunctionStruct(DC, end_point); } /* Automatic place of a junction on the start point if necessary because the Cleanup can suppress intermediate points by merging wire segments*/ if ( IsJunctionNeeded(this, s_ConnexionStartPoint) ) { GetScreen()->m_Curseur = s_ConnexionStartPoint; junction2 = CreateNewJunctionStruct(DC, s_ConnexionStartPoint); } TestDanglingEnds(GetScreen()->EEDrawList, DC); /* Redraw junctions which can be changed by TestDanglingEnds() */ if ( junction1 ) RedrawOneStruct(DrawPanel,DC, junction1, GR_DEFAULT_DRAWMODE); if ( junction2 ) RedrawOneStruct(DrawPanel,DC, junction2, GR_DEFAULT_DRAWMODE); SetFlagModify(GetScreen()); if( segment ) { GetScreen()->Trace_Curseur(DrawPanel, DC); // Erase schematic cursor RedrawOneStruct(DrawPanel,DC, segment, GR_DEFAULT_DRAWMODE); GetScreen()->Trace_Curseur(DrawPanel, DC); // Display schematic cursor } } /****************************************************************************/ static void Segment_in_Ghost(WinEDA_DrawPanel * panel, wxDC * DC, bool erase) /****************************************************************************/ /* Dessin du Segment Fantome lors des deplacements du curseur */ { EDA_DrawLineStruct * segment = (EDA_DrawLineStruct *) panel->m_Parent->GetScreen()->m_CurrentItem; wxPoint endpos; int color; if ( segment == NULL ) return; color = ReturnLayerColor(segment->m_Layer) ^ HIGHT_LIGHT_FLAG; endpos = panel->m_Parent->GetScreen()->m_Curseur; if( g_HVLines ) /* Coerce the line to vertical or horizontal one: */ { if (ABS(endpos.x - segment->m_Start.x) < ABS(endpos.y - segment->m_Start.y)) endpos.x = segment->m_Start.x; else endpos.y = segment->m_Start.y; } if( erase ) // Redraw if segment lengtht != 0 { if ( (segment->m_Start.x != segment->m_End.x) || (segment->m_Start.y != segment->m_End.y) ) RedrawOneStruct(panel,DC, segment, g_XorMode, color); } segment->m_End = endpos; // Redraw if segment lengtht != 0 if ( (segment->m_Start.x != segment->m_End.x) || (segment->m_Start.y != segment->m_End.y) ) RedrawOneStruct(panel,DC, segment, g_XorMode,color); } /*****************************************************************************/ static void Polyline_in_Ghost(WinEDA_DrawPanel * panel, wxDC * DC, bool erase) /*****************************************************************************/ /* Dessin du du Polyline Fantome lors des deplacements du curseur */ { DrawPolylineStruct * NewPoly = (DrawPolylineStruct *)panel->m_Parent->GetScreen()->m_CurrentItem; int color; wxPoint endpos; endpos = panel->m_Parent->GetScreen()->m_Curseur; color = ReturnLayerColor(NewPoly->m_Layer); GRSetDrawMode(DC, g_XorMode); if( g_HVLines ) { /* Coerce the line to vertical or horizontal one: */ if (ABS(endpos.x - NewPoly->m_Points[NewPoly->m_NumOfPoints * 2 - 2]) < ABS(endpos.y - NewPoly->m_Points[NewPoly->m_NumOfPoints * 2 - 1])) endpos.x = NewPoly->m_Points[NewPoly->m_NumOfPoints * 2 - 2]; else endpos.y = NewPoly->m_Points[NewPoly->m_NumOfPoints * 2 - 1]; } NewPoly->m_NumOfPoints++; if( erase ) RedrawOneStruct(panel,DC, NewPoly, g_XorMode, color); NewPoly->m_Points[NewPoly->m_NumOfPoints * 2 - 2] = endpos.x; NewPoly->m_Points[NewPoly->m_NumOfPoints * 2 - 1] = endpos.y; RedrawOneStruct(panel,DC, NewPoly, g_XorMode, color); NewPoly->m_NumOfPoints--; } /**********************************************************/ void WinEDA_SchematicFrame::DeleteCurrentSegment(wxDC * DC) /**********************************************************/ /* Routine effacant le dernier trait trace, ou l'element pointe par la souris */ { g_ItemToRepeat = NULL; if( (GetScreen()->m_CurrentItem == NULL) || ((GetScreen()->m_CurrentItem->m_Flags & IS_NEW) == 0) ) { return; } /* Trace en cours: annulation */ if (GetScreen()->m_CurrentItem->m_StructType == DRAW_POLYLINE_STRUCT_TYPE) { Polyline_in_Ghost(DrawPanel, DC, FALSE); /* Effacement du trace en cours */ } else { Segment_in_Ghost(DrawPanel, DC, FALSE); /* Effacement du trace en cours */ } EraseStruct(GetScreen()->m_CurrentItem, GetScreen()); GetScreen()->ManageCurseur = NULL; GetScreen()->m_CurrentItem = NULL; } /***************************************************************************/ DrawJunctionStruct * WinEDA_SchematicFrame::CreateNewJunctionStruct( wxDC * DC, const wxPoint & pos) /***************************************************************************/ /* Routine to create new connection struct. */ { DrawJunctionStruct *NewConnect; NewConnect = new DrawJunctionStruct(pos); g_ItemToRepeat = NewConnect; GetScreen()->Trace_Curseur(DrawPanel, DC); // Erase schematic cursor RedrawOneStruct(DrawPanel,DC, NewConnect, GR_DEFAULT_DRAWMODE); GetScreen()->Trace_Curseur(DrawPanel, DC); // Display schematic cursor NewConnect->Pnext = GetScreen()->EEDrawList; GetScreen()->EEDrawList = NewConnect; SetFlagModify(GetScreen()); return(NewConnect); } /*************************************************************************/ EDA_BaseStruct *WinEDA_SchematicFrame::CreateNewNoConnectStruct(wxDC * DC) /*************************************************************************/ /*Routine to create new NoConnect struct. ( Symbole de Non Connexion) */ { DrawNoConnectStruct *NewNoConnect; NewNoConnect = new DrawNoConnectStruct(GetScreen()->m_Curseur); g_ItemToRepeat = NewNoConnect; GetScreen()->Trace_Curseur(DrawPanel, DC); // Erase schematic cursor RedrawOneStruct(DrawPanel,DC, NewNoConnect, GR_DEFAULT_DRAWMODE); GetScreen()->Trace_Curseur(DrawPanel, DC); // Display schematic cursor NewNoConnect->Pnext = GetScreen()->EEDrawList; GetScreen()->EEDrawList = NewNoConnect; SetFlagModify(GetScreen()); return(NewNoConnect); } /**********************************************************/ static void ExitTrace(WinEDA_DrawFrame * frame, wxDC * DC) /**********************************************************/ /* Routine de sortie des menus de trace */ { BASE_SCREEN * Screen = frame->GetScreen(); if( Screen->m_CurrentItem) /* trace en cours */ { Screen->ManageCurseur(frame->DrawPanel, DC, FALSE); Screen->ManageCurseur = NULL; Screen->ForceCloseManageCurseur = NULL; EraseStruct(Screen->m_CurrentItem,(SCH_SCREEN*) Screen); Screen->m_CurrentItem = NULL; return; } else g_ItemToRepeat = NULL; // Fin de commande generale } /***************************************************/ void WinEDA_SchematicFrame::RepeatDrawItem(wxDC *DC) /***************************************************/ /* Routine de recopie du dernier element dessine Les elements duplicables sont fils, bus, traits, textes, labels Les labels termines par un nombre seront incrementes */ { int ox = 0, oy = 0; if( g_ItemToRepeat == NULL ) return; switch( g_ItemToRepeat->m_StructType ) { case DRAW_JUNCTION_STRUCT_TYPE: #undef STRUCT #define STRUCT ((DrawJunctionStruct*) g_ItemToRepeat) g_ItemToRepeat = STRUCT->GenCopy(); STRUCT->m_Pos.x += g_RepeatStep.x; ox = STRUCT->m_Pos.x; STRUCT->m_Pos.y += g_RepeatStep.y; oy = STRUCT->m_Pos.y; break; case DRAW_NOCONNECT_STRUCT_TYPE: #undef STRUCT #define STRUCT ((DrawNoConnectStruct*) g_ItemToRepeat) g_ItemToRepeat = STRUCT->GenCopy(); STRUCT->m_Pos.x += g_RepeatStep.x; ox = STRUCT->m_Pos.x; STRUCT->m_Pos.y += g_RepeatStep.y; oy = STRUCT->m_Pos.y; break; case DRAW_TEXT_STRUCT_TYPE: #undef STRUCT #define STRUCT ((DrawTextStruct*) g_ItemToRepeat) g_ItemToRepeat = STRUCT->GenCopy(); STRUCT->m_Pos.x += g_RepeatStep.x; ox = STRUCT->m_Pos.x; STRUCT->m_Pos.y += g_RepeatStep.y; oy = STRUCT->m_Pos.y; /*** Increment du numero de label ***/ IncrementLabelMember(STRUCT->m_Text); break; case DRAW_LABEL_STRUCT_TYPE: #undef STRUCT #define STRUCT ((DrawLabelStruct*) g_ItemToRepeat) g_ItemToRepeat = STRUCT->GenCopy(); STRUCT->m_Pos.x += g_RepeatStep.x; ox = STRUCT->m_Pos.x; STRUCT->m_Pos.y += g_RepeatStep.y; oy = STRUCT->m_Pos.y; /*** Increment du numero de label ***/ IncrementLabelMember(STRUCT->m_Text); break; case DRAW_GLOBAL_LABEL_STRUCT_TYPE: #undef STRUCT #define STRUCT ((DrawGlobalLabelStruct*) g_ItemToRepeat) g_ItemToRepeat = STRUCT->GenCopy(); STRUCT->m_Pos.x += g_RepeatStep.x; ox = STRUCT->m_Pos.x; STRUCT->m_Pos.y += g_RepeatStep.y; oy = STRUCT->m_Pos.y; /*** Increment du numero de label ***/ IncrementLabelMember(STRUCT->m_Text); break; case DRAW_SEGMENT_STRUCT_TYPE: #undef STRUCT #define STRUCT ((EDA_DrawLineStruct*) g_ItemToRepeat) g_ItemToRepeat = STRUCT->GenCopy(); STRUCT->m_Start.x += g_RepeatStep.x; ox = STRUCT->m_Start.x; STRUCT->m_Start.y += g_RepeatStep.y; oy = STRUCT->m_Start.y; STRUCT->m_End.x += g_RepeatStep.x; STRUCT->m_End.y += g_RepeatStep.y; break; case DRAW_BUSENTRY_STRUCT_TYPE: #undef STRUCT #define STRUCT ((DrawBusEntryStruct*) g_ItemToRepeat) g_ItemToRepeat = STRUCT->GenCopy(); STRUCT->m_Pos.x += g_RepeatStep.x; ox = STRUCT->m_Pos.x; STRUCT->m_Pos.y += g_RepeatStep.y; oy = STRUCT->m_Pos.y; break; default: g_ItemToRepeat = NULL; DisplayError(this, wxT("Repeat Type Error"), 10); break; } if ( g_ItemToRepeat ) { g_ItemToRepeat->Pnext = GetScreen()->EEDrawList; GetScreen()->EEDrawList = g_ItemToRepeat; TestDanglingEnds(GetScreen()->EEDrawList, NULL); RedrawOneStruct(DrawPanel,DC, g_ItemToRepeat, GR_DEFAULT_DRAWMODE); // GetScreen()->Curseur.x = ox; GetScreen()->Curseur.x = oy; // GRMouseWarp(DrawPanel, DrawPanel->CursorScreenPosition() ); } } /******************************************/ void IncrementLabelMember(wxString & name) /******************************************/ /* Routine incrementant les labels, c'est a dire pour les textes finissant par un nombre, ajoutant <RepeatDeltaLabel> a ce nombre */ { int ii, nn; long number = 0; ii = name.Len() - 1; nn = 0; if( !isdigit(name.GetChar(ii)) ) return; while( (ii > 0) && isdigit(name.GetChar(ii)) ) { ii--; nn++ ; } ii++; /* digits are starting at ii position */ wxString litt_number = name.Right(nn); if ( litt_number.ToLong(&number) ) { number += g_RepeatDeltaLabel; name.Remove(ii); name << number; } } /***************************************************************************/ static bool IsTerminalPoint(SCH_SCREEN * screen, const wxPoint & pos, int layer) /***************************************************************************/ /* Returne TRUE si pos est un point possible pour terminer automatiquement un segment, c'est a dire pour - type WIRE, si il y a - une jonction - ou une pin - ou une extrémité unique de fil - type BUS, si il y a - ou une extrémité unique de BUS */ { EDA_BaseStruct * item; LibDrawPin * pin; EDA_SchComponentStruct * LibItem = NULL; DrawSheetLabelStruct * pinsheet; wxPoint itempos; switch ( layer ) { case LAYER_BUS: item = PickStruct(pos, screen->EEDrawList, BUSITEM); if ( item ) return TRUE; pinsheet = LocateAnyPinSheet(pos, screen->EEDrawList ); if ( pinsheet && IsBusLabel(pinsheet->m_Text) ) { itempos = pinsheet->m_Pos; if ( (itempos.x == pos.x) && (itempos.y == pos.y) ) return TRUE; } break; case LAYER_NOTES: item = PickStruct(pos, screen->EEDrawList, DRAWITEM); if ( item ) return TRUE; break; case LAYER_WIRE: item = PickStruct(pos, screen->EEDrawList, RACCORDITEM |JUNCTIONITEM); if ( item ) return TRUE; pin = LocateAnyPin( screen->EEDrawList, pos, &LibItem ); if ( pin && LibItem ) { // calcul de la position exacte du point de connexion de la pin, // selon orientation du composant: itempos = LibItem->GetScreenCoord(pin->m_Pos); itempos.x += LibItem->m_Pos.x; itempos.y += LibItem->m_Pos.y; if ( (itempos.x == pos.x) && (itempos.y == pos.y) ) return TRUE; } item = PickStruct(pos, screen->EEDrawList, WIREITEM); if ( item ) return TRUE; item = PickStruct(pos, screen->EEDrawList, LABELITEM); if ( item && (item->m_StructType != DRAW_TEXT_STRUCT_TYPE) && ( ((DrawGlobalLabelStruct*)item)->m_Pos.x == pos.x) && ( ((DrawGlobalLabelStruct*)item)->m_Pos.y == pos.y) ) return TRUE; pinsheet = LocateAnyPinSheet( pos, screen->EEDrawList ); if ( pinsheet && ! IsBusLabel(pinsheet->m_Text) ) { itempos = pinsheet->m_Pos; if ( (itempos.x == pos.x) && (itempos.y == pos.y) ) return TRUE; } break; default: break; } return FALSE; } /****************************************************************/ bool IsJunctionNeeded (WinEDA_SchematicFrame * frame, wxPoint & pos ) /****************************************************************/ /* Return True when a wire is located at pos "pos" if - there is no junction. - The wire has no ends at pos "pos", and therefore it is considered as no connected. - One (or more) wire has one end at pos "pos" or - a pin is on location pos */ { if ( PickStruct(pos,frame->GetScreen()->EEDrawList, JUNCTIONITEM ) ) return FALSE; if ( PickStruct(pos,frame->GetScreen()->EEDrawList, WIREITEM |EXCLUDE_WIRE_BUS_ENDPOINTS ) ) { if ( PickStruct(pos,frame->GetScreen()->EEDrawList, WIREITEM |WIRE_BUS_ENDPOINTS_ONLY ) ) return TRUE; if ( frame->LocatePinEnd(frame->GetScreen()->EEDrawList, pos) ) return TRUE; } return FALSE; }
[ "bokeoa@244deca0-f506-0410-ab94-f4f3571dea26" ]
[ [ [ 1, 588 ] ] ]
169f4cd3ee4caeda3ea91734ae0c0b6ce6f3b64b
47e2bbe6fb7b417d6de09dbaf4ba5ffb593589b0
/examples/fortran_call_c/external/graphics_lib/utilities/CVec3.h
da5c5c48becbeb838d2a2aa18d186634cf359610
[]
no_license
bollig/CMakeUtilities
ca1b11b99dce84f78f1c189505731cad549106f1
f6ea900e2dddea6ca610c097ff2fe54eebd081d4
refs/heads/master
2020-06-04T05:56:28.035642
2011-11-21T09:02:04
2011-11-21T09:02:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,178
h
/* * Written by Dr. G. Erlebacher. */ #ifndef _CVEC3_H_ #define _CVEC3_H_ #include <math.h> #include <complex> #include "Vec3.h" //class ostream; #include <iosfwd> // sizeof(CVec3) = 24 // Complex Vec3 class typedef std::complex<double> CMPLX; class CVec3 { public: inline CVec3() { vec[0] = vec[1] = vec[2] = 0.0; }; inline CVec3(const CVec3& v) { this->vec[0] = v.vec[0]; this->vec[1] = v.vec[1]; this->vec[2] = v.vec[2]; } inline CVec3(int x, int y=0, int z=0) { CVec3((float)x, (float)y, (float)z); } inline CVec3(float x, float y=0.f, float z=0.f) { vec[0] = CMPLX(x,0.); vec[1] = CMPLX(y,0.); vec[2] = CMPLX(z,0.); } inline CVec3(double x, double y=0.f, double z=0.f) { vec[0] = CMPLX(x,0.); vec[1] = CMPLX(y,0.); vec[2] = CMPLX(z,0.); } inline CVec3(CMPLX x, CMPLX y=CMPLX(0.,0.), CMPLX z=CMPLX(0.,0.)) { vec[0] = x; vec[1] = y; vec[2] = z; } /* * allocated in calling routine. */ /// Memory is controlled by CVec3 inline CVec3(float* pt) { vec[0] = CMPLX(pt[0],0.); vec[1] = CMPLX(pt[1],0.); vec[2] = CMPLX(pt[2],0.); } /// Memory is controlled by CVec3 (since CVec3 is float, and argument is CMPLX) inline CVec3(CMPLX* pt) { vec[0] = pt[0]; vec[1] = pt[1]; vec[2] = pt[2]; } inline CVec3(const CMPLX* pt) { vec[0] = pt[0]; vec[1] = pt[1]; vec[2] = pt[2]; } ~CVec3() {}; CVec3(CVec3&); CVec3(Vec3&); /* * memory allocated in class */ CMPLX* getVec(); void getVec(CMPLX* x, CMPLX* y, CMPLX* z); void setValue(float x, float y, float z=0.); void setValue(float x); void setValue(CVec3& v); void setValue(float* val); void normalize(float scale=1.0); double magnitude(); double magnitude() const; CMPLX square() { return (vec[0]*vec[0]+vec[1]*vec[1]+vec[2]*vec[2]); } const CMPLX square() const { return (vec[0]*vec[0]+vec[1]*vec[1]+vec[2]*vec[2]); } void print(const char *msg=0) const; //void print() {print("");} inline CMPLX x() {return vec[0];} inline CMPLX y() {return vec[1];} inline CMPLX z() {return vec[2];} inline CMPLX x() const {return vec[0];} inline CMPLX y() const {return vec[1];} inline CMPLX z() const {return vec[2];} CVec3 conj(const CVec3& a) { return CVec3(std::conj(vec[0]), std::conj(vec[1]), std::conj(vec[2])); } CVec3 cross(const CVec3& a, const CVec3& b) { return (CVec3(a.vec[1]*b.vec[2]-a.vec[2]*b.vec[1], a.vec[2]*b.vec[0]-a.vec[0]*b.vec[2], a.vec[0]*b.vec[1]-a.vec[1]*b.vec[0])); } CVec3 cross(const CVec3& b) { return (CVec3(this->vec[1]*b.vec[2]-this->vec[2]*b.vec[1], this->vec[2]*b.vec[0]-this->vec[0]*b.vec[2], this->vec[0]*b.vec[1]-this->vec[1]*b.vec[0])); } /* * Overload operators, as needed. */ const CVec3 operator+(const CVec3& a) const { return (CVec3(a.vec[0]+vec[0], a.vec[1]+vec[1], a.vec[2]+vec[2])); } CVec3 operator+(CVec3& a) { return (CVec3(a.vec[0]+vec[0], a.vec[1]+vec[1], a.vec[2]+vec[2])); } const CVec3 operator-(const CVec3& a) const { return (CVec3(vec[0]-a.vec[0], vec[1]-a.vec[1], vec[2]-a.vec[2])); } CVec3 operator-(CVec3& a) { return (CVec3(vec[0]-a.vec[0], vec[1]-a.vec[1], vec[2]-a.vec[2])); } #if 0 bool operator<(const CVec3& b) const { return((vec[0] < b.vec[0]) && (vec[1] < b.vec[1]) && (vec[2] < b.vec[2])); } bool operator<=(const CVec3& b) const { return((vec[0] <= b.vec[0]) && (vec[1] <= b.vec[1]) && (vec[2] <= b.vec[2])); } bool operator>(const CVec3& b) const { return((vec[0] > b.vec[0]) && (vec[1] > b.vec[1]) && (vec[2] > b.vec[2])); } bool operator>=(const CVec3& b) const { return((vec[0] >= b.vec[0]) && (vec[1] >= b.vec[1]) && (vec[2] >= b.vec[2])); } #endif friend CVec3 operator*(const CVec3& a, CMPLX f) { return (CVec3(a.vec[0]*f, a.vec[1]*f, a.vec[2]*f)); } friend CVec3 operator*(CMPLX f, const CVec3& a) { return (CVec3(a.vec[0]*f, a.vec[1]*f, a.vec[2]*f)); } // GENERATES WARNING since a temporary is returned, and I might lose it. //const CVec3& operator/(const CVec3& a) const { // SOME COMPILERS MIGHT OPTIMIZE THIS TO AVOID COPIES! const CVec3 operator/(const CVec3& a) const { return (CVec3(vec[0]/a.vec[0], vec[1]/a.vec[1], vec[2]/a.vec[2])); } // NOT ALLOWED TO RETURN NON-CONSTANT BECAUSE A TEMPORARY SHOULD NEVER BE CHANGED! CVec3 operator/(const CVec3& a) { return (CVec3(vec[0]/a.vec[0], vec[1]/a.vec[1], vec[2]/a.vec[2])); } /* * Addition: Brian M. Bouta */ CMPLX operator*(const CVec3& a) const { return (a.vec[0]*vec[0] + a.vec[1]*vec[1] + a.vec[2]*vec[2]); } /* * Addition: Brian M. Bouta * The bivector formed from the outer product of two vectors * is treated as a vector, i.e., vec[0] = e1 ^ e2, * vec[1] = e2 ^ e3, vec[2] = e3 ^ e1. */ CVec3 operator^(const CVec3& b) { return (CVec3(vec[0]*b.vec[1]-vec[1]*b.vec[0], vec[1]*b.vec[2]-vec[2]*b.vec[1], vec[2]*b.vec[0]-vec[0]*b.vec[2])); } /* * Addition: Brian M. Bouta */ CVec3& operator+=(const CVec3& a) { vec[0] += a.vec[0]; vec[1] += a.vec[1]; vec[2] += a.vec[2]; return *this; } CVec3& operator*=(CMPLX f) { vec[0] *= f; vec[1] *= f; vec[2] *= f; return *this; } CVec3& operator=(const CVec3& a) { vec[0] = a.vec[0]; vec[1] = a.vec[1]; vec[2] = a.vec[2]; return *this; } const CMPLX& operator[](const int i) const { return(vec[i]); } CMPLX operator()(int i) { // 1/5/08 return(vec[i]); } CMPLX& operator[](int i) { return(vec[i]); } //friend CVec3 operator-(const CVec3&, const CVec3&); //friend CVec3 operator+(const CVec3&, const CVec3&); friend double cosine(CVec3& a, CVec3& b) { double am = a.magnitude(); double bm = b.magnitude(); if ((fabs(am) < 1.e-7) || (fabs(bm) < 1.e-7)) { return 1.0; } return scalprod(a,b)/(am*bm); } friend double scalprod(CVec3& a, CVec3& b) { double s0 = real(a[0])*real(b[0]) + imag(a[0])*imag(b[0]); double s1 = real(a[1])*real(b[1]) + imag(a[1])*imag(b[1]); double s2 = real(a[2])*real(b[2]) + imag(a[2])*imag(b[2]); return s0+s1+s2; } friend double scalprod(const CVec3& a, const CVec3& b) { double s0 = real(a[0])*real(b[0]) + imag(a[0])*imag(b[0]); double s1 = real(a[1])*real(b[1]) + imag(a[1])*imag(b[1]); double s2 = real(a[2])*real(b[2]) + imag(a[2])*imag(b[2]); return s0+s1+s2; } int isColinear(CVec3& a, CVec3& b) { CMPLX am = a.magnitude(); CMPLX bm = b.magnitude(); if ((abs(am) < 1.e-7) || (abs(bm) < 1.e-7)) { return 0; } if (abs((a*b)/(am*bm)-1.0) < 1.e-5) { return 1; } else { return 0; // not collinear } } int isZero(float tolerance) { //(vec[0]*vec[0]+vec[1]*vec[1]+vec[2]*vec[2]) if (scalprod(*this, *this) < (tolerance*tolerance)) { return 1; } else { return 0; } } //---------------------------------------------------------------------- public: CMPLX vec[3]; }; #endif
[ [ [ 1, 262 ] ] ]
7af4374f45451d5f38b9de807dc95e14fdd49a15
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/wave/test/testwave/testfiles/t_1_020.cpp
326b1b9ed2c2052b218690c9bff0a9f43ee08ce7
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
752
cpp
/*============================================================================= Boost.Wave: A Standard compliant C++ preprocessor library http://www.boost.org/ Copyright (c) 2001-2006 Hartmut Kaiser. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ // Tests the handling of placeholder tokens, which have to be inserted, when // some macro expands into nothing (certainly these have to be ignored // afterwards :-) #define NIL #define A B NIL #define B() anything //R #line 21 "t_1_020.cpp" //R B() A() // not 'anything'!
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 22 ] ] ]
e1f1790612caaf260bf2b02ee36860c2f88422f3
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/util/Compilers/TandemCCDefs.cpp
081510138d61add12084be8b6117fc087a031ade
[ "Apache-2.0" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
1,873
cpp
/* * Copyright 1999-2000,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Log: TandemCCDefs.cpp,v $ * Revision 1.2 2004/09/08 13:56:32 peiyongz * Apache License Version 2.0 * * Revision 1.1.1.1 2002/02/01 22:22:19 peiyongz * sane_include * * Revision 1.3 2000/03/02 19:55:09 roddey * This checkin includes many changes done while waiting for the * 1.1.0 code to be finished. I can't list them all here, but a list is * available elsewhere. * * Revision 1.2 2000/02/06 07:48:18 rahulj * Year 2K copyright swat. * * Revision 1.1.1.1 1999/11/09 01:07:40 twl * Initial checkin * * Revision 1.2 1999/11/08 20:45:25 rahul * Swat for adding in Product name and CVS comment log variable. * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/util/Compilers/TandemCCDefs.hpp> #include <strings.h> int stricmp(const char* const str1, const char* const str2) { return strcasecmp(str1, str2); } int strnicmp(const char* const str1, const char* const str2, const unsigned int count) { if (count == 0) return 0; return strncasecmp( str1, str2, (size_t)count); }
[ [ [ 1, 60 ] ] ]
865fbc0959355c2d8337db0435d146a61d1a97f2
428b5f476e013d4699416629ce5fa155e724849f
/mainwindow.h
69c691dcd3568d6c443350afbf4734927792794d
[]
no_license
vitorboschi/kpws
afab7f2eb97f25c0eb7bcab2404d308edc0e3297
e51dd08e5f8e00149f407c259030855b82ae5f38
refs/heads/master
2021-01-16T19:35:50.269368
2010-02-02T23:59:33
2010-02-02T23:59:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,550
h
/* KDE Personal Web Server - Allow you to easily share files over http Copyright (C) 2010 by Vitor Boschi da Silva ([email protected]) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 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 MAINWINDOW_H #define MAINWINDOW_H #include <KXmlGuiWindow> #include <KTextEdit> #include <KVBox> #include <KListWidget> #include <KComboBox> #include <QTreeView> #include "webserver.h" #include "webcontent_dummy.h" #include "webcontent_virtualfolder.h" #include "webcontent_file.h" class MainWindow : public KXmlGuiWindow { public: MainWindow(QWidget *parent=0); private: KVBox* layout; KComboBox* bindAddress; QTreeView* resourcesView; KListWidget* logList; WebServer daemon; //test content WebContent_VirtualFolder* root; WebContent_Dummy* c1; WebContent_Dummy* c2; WebContent_VirtualFolder* f1; WebContent_Dummy* c3; WebContent_File* fileOk; WebContent_File* fileError; }; #endif
[ [ [ 1, 60 ] ] ]
b84fd706b185eb53ceae8286bc07f63120b1ce1e
205069c97095da8f15e45cede1525f384ba6efd2
/Casino/Code/Server/GameModule/B_Upgrade/GameProject/GameLogic.h
545596205816d82b175bdb7f7aa2276279e9dbcc
[]
no_license
m0o0m/01technology
1a3a5a48a88bec57f6a2d2b5a54a3ce2508de5ea
5e04cbfa79b7e3cf6d07121273b3272f441c2a99
refs/heads/master
2021-01-17T22:12:26.467196
2010-01-05T06:39:11
2010-01-05T06:39:11
null
0
0
null
null
null
null
GB18030
C++
false
false
9,389
h
#ifndef GAME_LOGIC_HEAD_FILE #define GAME_LOGIC_HEAD_FILE #pragma once ////////////////////////////////////////////////////////////////////////// //宏定义 //牌副定义 #define CELL_PACK 54 //单元数目 //属性定义 #define MAX_COUNT 60 //最大数目 #define MAX_TRACKOR 18 //最大连牌 #define COLOR_RIGHT 40 //花色权位 //无效定义 #define CT_ERROR 0 //错误类型 #define VALUE_ERROR 0x00 //数值定义 #define COLOR_ERROR 0xFF //花色定义 //花色定义 #define COLOR_NT 0x40 //花色定义 #define COLOR_HEI_TAO 0x30 //花色定义 #define COLOR_HONG_TAO 0x20 //花色定义 #define COLOR_MEI_HUA 0x10 //花色定义 #define COLOR_FANG_KUAI 0x00 //花色定义 //数值掩码 #define LOGIC_MASK_COLOR 0xF0 //花色掩码 #define LOGIC_MASK_VALUE 0x0F //数值掩码 //扑克类型 #define CT_ERROR 0 //错误类型 #define CT_SINGLE 1 //单牌类型 #define CT_SAME_2 2 //对牌类型 #define CT_SAME_3 3 //三牌类型 #define CT_SAME_4 4 //四牌类型 #define CT_TRACKOR_2 5 //拖拉机型 #define CT_TRACKOR_3 6 //拖拉机型 #define CT_TRACKOR_4 7 //拖拉机型 #define CT_THROW_CARD 8 //甩牌类型 ////////////////////////////////////////////////////////////////////////// //结构定义 //连牌信息 struct tagSameDataInfo { BYTE cbCardCount; //扑克数目 BYTE cbBlockCount; //牌段数目 BYTE cbSameData[MAX_COUNT]; //拖拉机牌 }; //拖拉机信息 struct tagTractorDataInfo { BYTE cbCardCount; //扑克数目 BYTE cbTractorCount; //拖牌个数 BYTE cbTractorMaxIndex; //索引位置 BYTE cbTractorMaxLength; //最大长度 BYTE cbTractorData[MAX_COUNT*3/2]; //拖拉机牌 }; //牌型结构 struct tagAnalyseResult { BYTE cbCardColor; //扑克花色 tagSameDataInfo SameDataInfo[2]; //同牌数据 tagTractorDataInfo TractorDataInfo[2-1]; //拖牌数据 }; //最大牌型结构 struct tagAnalyseMostResult { tagTractorDataInfo TractorDataInfo[5][MAX_COUNT/2]; //拖牌数据 BYTE cbTractorDataInfoCount[5]; //拖牌数目 tagSameDataInfo SameDataInfo[5][MAX_COUNT/2]; //同牌数据 BYTE cbSameDataInfoInfoCount[5]; //同牌数目 BYTE cbSingleCardData[5][MAX_COUNT]; //单牌数据 BYTE cbSingleCardCount[5]; //单牌个数 }; //需求结构 struct tagDemandInfo { BYTE cbMaxTractor[2-1]; //长度需求 BYTE cbSameCardCount[2]; //同牌需求 BYTE cbTractorCardCount[2-1]; //拖牌需求 }; //出牌结果 struct tagOutCardResult { BYTE cbCardCount; //扑克数目 BYTE cbResultCard[MAX_COUNT]; //结果扑克 }; ////////////////////////////////////////////////////////////////////////// //游戏逻辑类 class CGameLogic { //属性变量 protected: BYTE m_cbPackCount; //牌副数目 BYTE m_cbDispatchCount; //派发数目 //逻辑变量 protected: BYTE m_cbMainColor; //主牌花色 BYTE m_cbMainValue; //主牌数值 //辅助变量 protected: BYTE m_cbSortRight[5]; //排序权位 //变量定义 public: static const BYTE m_cbNTValue; //常主数值 static const BYTE m_cbCardData[CELL_PACK]; //扑克数据 //函数定义 public: //构造函数 CGameLogic(); //析构函数 virtual ~CGameLogic(); //状态设置 public: //设置副数 bool SetPackCount(BYTE cbPackCount); //获取副数 BYTE GetPackCount() { return m_cbPackCount; } //派发数目 BYTE GetDispatchCount() { return m_cbDispatchCount; } //信息函数 public: //主牌花色 bool SetMainColor(BYTE cbMainColor); //主牌数值 bool SetMainValue(BYTE cbMainValue); //主牌花色 BYTE GetMainColor() { return m_cbMainColor; } //主牌数值 BYTE GetMainValue() { return m_cbMainValue; } //控制函数 public: //排列扑克 void SortCardList(BYTE cbCardData[], BYTE cbCardCount); //混乱扑克 void RandCardList(BYTE cbCardBuffer[], BYTE cbBufferCount); //删除扑克 bool RemoveCard(const BYTE cbRemoveCard[], BYTE cbRemoveCount, BYTE cbCardData[], BYTE cbCardCount); //额度函数 public: //获取额度 WORD GetCardScore(const BYTE cbCardData[], BYTE cbCardCount); //额度扑克 BYTE GetScoreCard(const BYTE cbCardData[], BYTE cbCardCount, BYTE cbScoreCard[], BYTE cbMaxCount); //功能函数 public: //分析扑克 bool AnalyseCardData(const BYTE cbCardData[], BYTE cbCardCount, tagAnalyseResult & AnalyseResult); //出牌判断 bool SearchOutCard(const BYTE cbHandCardData[], BYTE cbHandCardCount,const BYTE cbTurnCardData[], BYTE cbTurnCardCount, tagOutCardResult & OutCardResult); //出牌判断 bool SearchMostOutCard(const BYTE cbHandCardData[], BYTE cbHandCardCount,const BYTE cbTurnCardData[], BYTE cbTurnCardCount, tagOutCardResult & OutCardResult); //效验出牌 bool EfficacyOutCard(const BYTE cbOutCardData[], BYTE cbOutCardCount, const BYTE cbFirstCardData[], BYTE cbFirstCardCount, const BYTE cbHandCardData[], BYTE cbHandCardCount); //效验甩牌 bool EfficacyThrowCard(const BYTE cbOutCardData[], BYTE cbOutCardCount, WORD wOutCardIndex, const BYTE cbHandCardData[GAME_PLAYER][MAX_COUNT], BYTE cbHandCardCount, tagOutCardResult & OutCardResult); //分牌 bool SplitCardByColor(const BYTE cbCardData[], BYTE cbCardCount,BYTE cbResultCardData[5][MAX_COUNT],BYTE cbResultCardCount[5]); //对比函数 public: //对比扑克 bool CompareCardData(BYTE cbFirstCardData, BYTE cbNextCardData); //对比扑克 bool CompareCardResult(const tagAnalyseResult WinnerResult, const tagAnalyseResult UserResult); //对比扑克 bool CompareCardResult(const tagTractorDataInfo WinnerResult, const tagTractorDataInfo UserResult); //对比扑克 bool CompareCardResult(const tagSameDataInfo WinnerResult, const tagSameDataInfo UserResult); //对比扑克 WORD CompareCardArray(const BYTE cbOutCardData[GAME_PLAYER][MAX_COUNT], BYTE cbCardCount, WORD wFirstIndex); //对比扑克 tagTractorDataInfo GetMostTractorDataInfo(tagTractorDataInfo TractorDataInfo[MAX_COUNT/2], BYTE cbTrackorCount); //对比扑克 tagSameDataInfo GetMostSameDataInfo(tagSameDataInfo SameDataInfo[MAX_COUNT/2], BYTE cbSameDataInfoCount); //对比扑克 BYTE GetMostSingleCard(BYTE cbCardData[], BYTE cbCardCount); //类型函数 public: //获取类型 BYTE GetCardType(const BYTE cbCardData[], BYTE cbCardCount); //获取数值 BYTE GetCardValue(BYTE cbCardData) { return cbCardData&LOGIC_MASK_VALUE; } //获取花色 BYTE GetCardColor(BYTE cbCardData) { return cbCardData&LOGIC_MASK_COLOR; } //逻辑函数 public: //有效判断 bool IsValidCard(BYTE cbCardData); //排序等级 BYTE GetCardSortOrder(BYTE cbCardData); //逻辑数值 BYTE GetCardLogicValue(BYTE cbCardData); //逻辑花色 BYTE GetCardLogicColor(BYTE cbCardData); //牌列花色 BYTE GetCardLogicColor(const BYTE cbCardData[], BYTE cbCardCount); //牌列花色数目 BYTE GetCardColorCount(const BYTE cbCardData[], BYTE cbCardCount,BYTE cbColorData[4]); //获取索引 BYTE GetAnalyseMostResultIndexByCardColor(BYTE cbCardColor); //逻辑辅助 protected: //是否相连 bool IsLineValue(BYTE cbFirstCard, BYTE cbSecondCard); //是否同花 bool IsSameColor(BYTE cbFirstCard, BYTE cbSecondCard); //交集数目 BYTE GetIntersectionCount(const BYTE cbCardData1[], BYTE cbCardCount1, const BYTE cbCardData2[], BYTE cbCardCount2); //判断相同 bool HaveSameCardData(const BYTE cbCardData[], BYTE cbCardCount,BYTE cbSameCardDataIndex); //提取函数 protected: //提取扑克 BYTE DistillCardByColor(const BYTE cbCardData[], BYTE cbCardCount, BYTE cbCardColor, BYTE cbResultCard[]); //提取扑克 BYTE DistillCardByCount(const BYTE cbCardData[], BYTE cbCardCount, BYTE cbSameCount, tagSameDataInfo & SameDataInfo); //提取扑克 BYTE DistillTrackorByCount(const BYTE cbCardData[], BYTE cbCardCount, BYTE cbSameCount, tagTractorDataInfo & TractorDataInfo); //提取扑克 BYTE DistillSpiltTrackorByCount(const BYTE cbCardData[], BYTE cbCardCount, BYTE cbSameCount, tagTractorDataInfo TractorDataInfo[MAX_TRACKOR/2]); //提取扑克 BYTE DistillSpiltSameDataInfoByCount(const BYTE cbCardData[], BYTE cbCardCount, BYTE cbSameCount, tagSameDataInfo SameDataInfo[MAX_TRACKOR/2]); public: //提取扑克 BYTE DistillSingleCard(const BYTE cbCardData[], BYTE cbCardCount, BYTE cbMainColor, BYTE cbMainValue, BYTE cbResultCard[]); //提取扑克 BYTE DistillMostCard(const BYTE cbCardData[], BYTE cbCardCount, tagAnalyseMostResult & AnalyseResult); //内部函数 protected: //更新权位 void UpdateSortRight(); //调整扑克 bool RectifyCardWeave(const BYTE cbCardData[], BYTE cbCardCount, const tagAnalyseResult & TargetResult, tagAnalyseResult & RectifyResult); }; ////////////////////////////////////////////////////////////////////////// #endif
[ [ [ 1, 269 ] ] ]
8bf58e69325a89249512e4e97ecce5f97d0a0e07
e537c879c7f7777d649121eee4b3f1fbff1e07c8
/modules/LogManServer/LogManServer_MessageQueue.cpp
7c1fec81e96b005ee2ac8064c3d0b8cf61150462
[]
no_license
SymbiSoft/logman-for-symbian
1181007a28a6d798496bb7e1107d1bce366becdd
cd0de1cf1afef03df09622e3d1db6c8bddbd324b
refs/heads/master
2021-01-10T15:04:55.032082
2010-05-11T13:26:07
2010-05-11T13:26:07
48,182,126
0
0
null
null
null
null
UTF-8
C++
false
false
1,401
cpp
#include <e32debug.h> #include <badesca.h> #include "LogManServer_MessageQueue.h" #include "LogManServer_Server.h" #include "loggingdefs.h" CLogManMessageQueue::CLogManMessageQueue(CLogManServer* aLogManServer) : CActive(0),iLogManServer(aLogManServer),iMessages(NULL) { } void CLogManMessageQueue::ConstructL() { CActiveScheduler::Add(this); iMessages = new (ELeave) CDesC8ArrayFlat(10); } void CLogManMessageQueue::AppendL( TDesC8& aMessage) { iMessages->AppendL( aMessage ); } void CLogManMessageQueue::Start() { PRINTF( "void CLoggingServerMessageQueue::Start()" ) TRequestStatus* status = &iStatus; User::RequestComplete( status, KErrNone ); SetActive(); } void CLogManMessageQueue::DoCancel() { } void CLogManMessageQueue::RunL() { if (!iLogManServer->IsClosing()) { for ( TInt i = 0; i < iMessages->MdcaCount(); i++) { const TPtrC8& data = iMessages->MdcaPoint(0); TMessageBuffer8 buffer; buffer.Copy( data ); this->iLogManServer->SendMessage( buffer ); // Remove from Queue iMessages->Delete(0); } } } CLogManMessageQueue::~CLogManMessageQueue() { Cancel(); // Clear message array if (iMessages ) { iMessages->Reset(); delete iMessages; } }
[ "jtoivola@localhost", "Jussi Toivola@localhost" ]
[ [ [ 1, 9 ], [ 12, 15 ], [ 17, 21 ], [ 23, 25 ], [ 27, 34 ], [ 36, 38 ], [ 40, 40 ], [ 42, 48 ], [ 50, 56 ], [ 58, 67 ] ], [ [ 10, 11 ], [ 16, 16 ], [ 22, 22 ], [ 26, 26 ], [ 35, 35 ], [ 39, 39 ], [ 41, 41 ], [ 49, 49 ], [ 57, 57 ] ] ]
51878bccea47cf5f29c1f610fbdd849dcebe2a78
14a00dfaf0619eb57f1f04bb784edd3126e10658
/lab6/Cube.cpp
fc3a5b24af07101cc4fdbb7b87370552aceaf7de
[]
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
UTF-8
C++
false
false
1,997
cpp
#include "Cube.h" Cube::Cube() { Vector3<float> lowP(-1.1); Vector3<float> highP(1.1); setBoundingBox(Bbox(lowP, highP)); Matrix4x4<float> matrix; matrix[0][0] = 0.0; matrix[1][1] = 0.0; matrix[2][2] = 0.0; matrix[3][3] = 0.0; matrix[0][3] = 0.0; matrix[1][3] = 0.5; matrix[2][3] = 0.0; // Plane 1 Quadric* q = new Quadric(matrix); q->translate(0.0, 0.5, 0); q->setBoundingBox(Bbox(lowP, highP)); mPlanes.push_back(q); // Plane 2 matrix[0][3] = 0.0; matrix[1][3] = -0.5; matrix[2][3] = 0.0; q = new Quadric(matrix); q->translate(0.0, -0.5, 0); q->setBoundingBox(Bbox(lowP, highP)); mPlanes.push_back(q); // Plane 3 matrix[0][3] = 0.5; matrix[1][3] = 0.0; matrix[2][3] = 0.0; q = new Quadric(matrix); q->translate(0.5, 0.0, 0); q->setBoundingBox(Bbox(lowP, highP)); mPlanes.push_back(q); // Plane 4 matrix[0][3] = -0.5; matrix[1][3] = 0.0; matrix[2][3] = 0.0; q = new Quadric(matrix); q->translate(-0.5, 0, 0); q->setBoundingBox(Bbox(lowP, highP)); mPlanes.push_back(q); // Plane 5 matrix[0][3] = 0.0; matrix[1][3] = 0.0; matrix[2][3] = 0.5; q = new Quadric(matrix); q->translate(0.0, 0.0, 0.5); q->setBoundingBox(Bbox(lowP, highP)); mPlanes.push_back(q); // Plane 6 matrix[0][3] = 0.0; matrix[1][3] = 0.0; matrix[2][3] = -0.5; q = new Quadric(matrix); q->translate(0.0, 0, -0.5); q->setBoundingBox(Bbox(lowP, highP)); mPlanes.push_back(q); } Cube::~Cube() { for (unsigned int i = 0; i < mPlanes.size(); i++){ delete mPlanes[i]; } } float Cube::getValue(float x, float y, float z) const { // union.. Vector4<float> vprim, v = Vector4<float>(x, y, z, 1.f); vprim = mWorld2Obj*v; float value = mPlanes[0]->getValue(vprim[0], vprim[1], vprim[2]); for (unsigned int i = 1; i < mPlanes.size(); i++){ value = std::max(value, mPlanes[i]->getValue(vprim[0], vprim[1], vprim[2])); } return value; }
[ "onnepoika@da195381-492e-0410-b4d9-ef7979db4686" ]
[ [ [ 1, 95 ] ] ]
97f9e828d161f0a0f19882f75ecbfc49be7b961f
99527557aee4f1db979a7627e77bd7d644098411
/rainbow/sdlmain.cpp
fc49da2d7fa31f2969efeb92b17603a63740935b
[]
no_license
GunioRobot/2deffects
7aeb02400090bb7118d23f1fc435ffbdd4417c59
39d8e335102d6a51cab0d47a3a2dc7686d7a7c67
refs/heads/master
2021-01-18T14:10:32.049756
2008-09-15T15:56:50
2008-09-15T15:56:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,266
cpp
/* SDL_main.c, placed in the public domain by Sam Lantinga 4/13/98 The WinMain function -- calls your program's main() function */ #include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #include <windows.h> #include <malloc.h> /* For _alloca() */ /* Include the SDL main definition header */ extern "C" { #include "SDL.h" #include "SDL_main.h" } #ifdef main #ifndef _WIN32_WCE_EMULATION #undef main #endif #endif #define NO_STDIO_REDIRECT /* Do we really not want stdio redirection with Windows CE? */ #ifdef _WIN32_WCE #define NO_STDIO_REDIRECT #endif /* The standard output files */ #define STDOUT_FILE TEXT("stdout.txt") #define STDERR_FILE TEXT("stderr.txt") #if defined(_WIN32_WCE) && _WIN32_WCE < 300 /* seems to be undefined in Win CE although in online help */ #define isspace(a) (((CHAR)a == ' ') || ((CHAR)a == '\t')) /* seems to be undefined in Win CE although in online help */ char *strrchr(char *str, int c) { char *p; /* Skip to the end of the string */ p=str; while (*p) p++; /* Look for the given character */ while ( (p >= str) && (*p != (CHAR)c) ) p--; /* Return NULL if character not found */ if ( p < str ) { p = NULL; } return p; } #endif /* _WIN32_WCE < 300 */ /* Parse a command line buffer into arguments */ static int ParseCommandLine(char *cmdline, char **argv) { char *bufp; int argc; argc = 0; for ( bufp = cmdline; *bufp; ) { /* Skip leading whitespace */ while ( isspace(*bufp) ) { ++bufp; } /* Skip over argument */ if ( *bufp == '"' ) { ++bufp; if ( *bufp ) { if ( argv ) { argv[argc] = bufp; } ++argc; } /* Skip over word */ while ( *bufp && (*bufp != '"') ) { ++bufp; } } else { if ( *bufp ) { if ( argv ) { argv[argc] = bufp; } ++argc; } /* Skip over word */ while ( *bufp && ! isspace(*bufp) ) { ++bufp; } } if ( *bufp ) { if ( argv ) { *bufp = '\0'; } ++bufp; } } if ( argv ) { argv[argc] = NULL; } return(argc); } /* Show an error message */ static void ShowError(const char *title, const char *message) { /* If USE_MESSAGEBOX is defined, you need to link with user32.lib */ #ifdef USE_MESSAGEBOX MessageBox(NULL, message, title, MB_ICONEXCLAMATION|MB_OK); #else fprintf(stderr, "%s: %s\n", title, message); #endif } /* Pop up an out of memory message, returns to Windows */ static BOOL OutOfMemory(void) { ShowError("Fatal Error", "Out of memory - aborting"); return FALSE; } /* Remove the output files if there was no output written */ static void __cdecl cleanup_output(void) { #ifndef NO_STDIO_REDIRECT FILE *file; int empty; #endif /* Flush the output in case anything is queued */ fclose(stdout); fclose(stderr); #ifndef NO_STDIO_REDIRECT /* See if the files have any output in them */ file = fopen(STDOUT_FILE, "rb"); if ( file ) { empty = (fgetc(file) == EOF) ? 1 : 0; fclose(file); if ( empty ) { remove(STDOUT_FILE); } } file = fopen(STDERR_FILE, "rb"); if ( file ) { empty = (fgetc(file) == EOF) ? 1 : 0; fclose(file); if ( empty ) { remove(STDERR_FILE); } } #endif } #if defined(_MSC_VER) && !defined(_WIN32_WCE) /* The VC++ compiler needs main defined */ #define console_main main #endif /* This is where execution begins [console apps] */ int console_main(int argc, char *argv[]) { int n; char *bufp, *appname; /* Get the class name from argv[0] */ appname = argv[0]; if ( (bufp=strrchr(argv[0], '\\')) != NULL ) { appname = bufp+1; } else if ( (bufp=strrchr(argv[0], '/')) != NULL ) { appname = bufp+1; } if ( (bufp=strrchr(appname, '.')) == NULL ) n = strlen(appname); else n = (bufp-appname); bufp = (char *)malloc(n+1); if ( bufp == NULL ) { return OutOfMemory(); } strncpy(bufp, appname, n); bufp[n] = '\0'; appname = bufp; /* Load SDL dynamic link library */ if ( SDL_Init(SDL_INIT_NOPARACHUTE) < 0 ) { ShowError("WinMain() error", SDL_GetError()); free(bufp); return(FALSE); } atexit(cleanup_output); atexit(SDL_Quit); #ifndef DISABLE_VIDEO #if 0 /* Create and register our class * DJM: If we do this here, the user nevers gets a chance to putenv(SDL_WINDOWID). This is already called later by the (DIB|DX5)_CreateWindow function, so it should be safe to comment it out here. if ( SDL_RegisterApp(appname, CS_BYTEALIGNCLIENT, GetModuleHandle(NULL)) < 0 ) { ShowError("WinMain() error", SDL_GetError()); exit(1); }*/ #else /* Sam: We still need to pass in the application handle so that DirectInput will initialize properly when SDL_RegisterApp() is called later in the video initialization. */ SDL_SetModuleHandle(GetModuleHandle(NULL)); #endif /* 0 */ #endif /* !DISABLE_VIDEO */ /* Run the application main() code */ SDL_main(argc, argv); /* Exit cleanly, calling atexit() functions */ exit(0); free(bufp); /* Hush little compiler, don't you cry... */ return(0); } /* This is where execution begins [windowed apps] */ #ifdef _WIN32_WCE int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPWSTR szCmdLine, int sw) #else int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int sw) #endif { HINSTANCE handle; char **argv; int argc; char *cmdline; #ifdef _WIN32_WCE wchar_t *bufp; int nLen; #else char *bufp; #endif #ifndef NO_STDIO_REDIRECT FILE *newfp; #endif /* Start up DDHELP.EXE before opening any files, so DDHELP doesn't keep them open. This is a hack.. hopefully it will be fixed someday. DDHELP.EXE starts up the first time DDRAW.DLL is loaded. */ handle = LoadLibrary(TEXT("DDRAW.DLL")); if ( handle != NULL ) { FreeLibrary(handle); } #ifndef NO_STDIO_REDIRECT /* Redirect standard input and standard output */ newfp = freopen(STDOUT_FILE, "w", stdout); if ( newfp == NULL ) { /* This happens on NT */ #if !defined(stdout) stdout = fopen(STDOUT_FILE, "w"); #else newfp = fopen(STDOUT_FILE, "w"); if ( newfp ) { *stdout = *newfp; } #endif } newfp = freopen(STDERR_FILE, "w", stderr); if ( newfp == NULL ) { /* This happens on NT */ #if !defined(stderr) stderr = fopen(STDERR_FILE, "w"); #else newfp = fopen(STDERR_FILE, "w"); if ( newfp ) { *stderr = *newfp; } #endif } setvbuf(stdout, NULL, _IOLBF, BUFSIZ); /* Line buffered */ setbuf(stderr, NULL); /* No buffering */ #endif /* !NO_STDIO_REDIRECT */ /* Grab the command line (use _alloca() on Windows) */ bufp = GetCommandLine(); cmdline = (char *)malloc(strlen(bufp)+1); if ( cmdline == NULL ) { return OutOfMemory(); } strcpy(cmdline, bufp); /* Parse it into argv and argc */ argc = ParseCommandLine(cmdline, NULL); argv = (char **)malloc((argc+1)*(sizeof *argv)); if ( argv == NULL ) { free(cmdline); return OutOfMemory(); } ParseCommandLine(cmdline, argv); /* Run the main program (after a little SDL initialization) */ free(cmdline); return(console_main(argc, argv)); }
[ [ [ 1, 319 ] ] ]
f20a6f40624d249449dc7b2ced91d86cf63fc217
658a1222b06267650db18923a269d7cf7ae0f100
/PhysicalObject.cpp
b79daaf4e8add81bd63f7d7c340761658ec45b63
[]
no_license
imclab/H.E.A.D
4c3eb84ea8fd12a6b1b6c0598dd910f541aa92e0
02303c25be37d3708a8db66a8f7bb5ee9610c841
refs/heads/master
2021-01-18T10:42:07.368559
2010-09-19T17:43:49
2010-09-19T17:43:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
334
cpp
#include "PhysicalObject.h" PhysicalObject::PhysicalObject(void) { } PhysicalObject::~PhysicalObject(void) { } void PhysicalObject::handleevents(){ } void PhysicalObject::draw(){ } EObjectType PhysicalObject::getType(){ return type; } void PhysicalObject::setPosition(float x , float y){ pX=x; pY=y; }
[ [ [ 1, 24 ] ] ]
ef36e35abc007f8455bcaef26d427513c90aba33
2f72d621e6ec03b9ea243a96e8dd947a952da087
/include/gameItem.h
a4201c09844a3e9489bf3ffd24c9e644f31e37b5
[]
no_license
gspu/lol4fg
752358c3c3431026ed025e8cb8777e4807eed7a0
12a08f3ef1126ce679ea05293fe35525065ab253
refs/heads/master
2023-04-30T05:32:03.826238
2011-07-23T23:35:14
2011-07-23T23:35:14
364,193,504
0
0
null
null
null
null
ISO-8859-1
C++
false
false
2,317
h
#ifndef __praGameItem #define __praGameItem #include "GameObject.h" #include "Ogre.h" #include "OgreNewt.h" #include "StandardApplication.h" class GameItem: public GameObject { public: GameItem(TiXmlElement *XMLNode,Level *lvl, Ogre::Vector3 positionOffset); GameItem(gamedata_item *data, Level *lvl, Ogre::Vector3 pos, Ogre::Quaternion ornt=Ogre::Quaternion::IDENTITY, Ogre::Vector3 _scale = Ogre::Vector3::UNIT_SCALE) { init(data,lvl,pos,ornt,_scale); } GameItem(Ogre::String id, Level *lvl, Ogre::Vector3 pos, Ogre::Quaternion ornt=Ogre::Quaternion::IDENTITY, Ogre::Vector3 _scale = Ogre::Vector3::UNIT_SCALE) { gamedata_item *myData = StandardApplication::getSingletonPtr()->getItemDataPtr(id); if(!myData) { throw etInvalidId; } init(myData,lvl,pos,ornt,_scale); } GameItem(GameItem *src,Level *targetlvl); ~GameItem(); GameObject* clone(Level *targetLvl = NULL) { return new GameItem(this,targetLvl); } Ogre::String getDisplayName() { return ID; } virtual TiXmlElement* getXmlElem(Ogre::Vector3 startPosition = Ogre::Vector3::ZERO,bool savegame=false); //void update(Ogre::Real time); ////sets position //void setPosition(Ogre::Vector3 pos); ////sets orientation //void setOrientation(Ogre::Quaternion ornt); ////retrieves body position //Ogre::Vector3 getPosition(); ////retr. body orient //Ogre::Quaternion getOrientation(); //void setScale(Ogre::Vector3 scale); //void modScale(Ogre::Vector3 scale); //Ogre::Vector3 getScale(); //OgreNewt::Body *getBody(); //Ogre::SceneNode *getSceneNode(); ////pointer to the level this obj is currently in //Level *getLevel(); //ObjType getType(); //Ogre::String getID(); //Ogre::String getUName(); Ogre::String getName(); void onActivate(GameChar *user,bool cursorMode=false); /*inline gamedata_item *getData() { return myData; }*/ protected: void init(gamedata_item *data, Level *lvl, Ogre::Vector3 pos, Ogre::Quaternion ornt=Ogre::Quaternion::IDENTITY, Ogre::Vector3 _scale = Ogre::Vector3::UNIT_SCALE,int SaveGameID = 0); //gamedata_obj_static *myData; //OgreNewt::Body *mBody; //Ogre::SceneNode *mNode; //ObjType type; //<- später evtl als enum //Ogre::String mID; //Ogre::String uName; //Level *mLevel; }; #endif
[ "praecipitator@bd7a9385-7eed-4fd6-88b1-0096df50a1ac" ]
[ [ [ 1, 77 ] ] ]
900a3c1c78866a89fec3129b12883b59f5a5a9bb
6e8b65984ea7b539d1c2ccfda8845c9c89512d12
/Ajedrez/jugadas_definicion.cpp
c30e7a84b578530388cd8dc948f955034fc7dbad
[]
no_license
camilomorat/ajedrez-javeriana
77e1f115801291f807853f06aa6d3a9d12cfb2dd
28c1845f8ee644efc6f538957a78e95a9c94c2c6
refs/heads/master
2021-01-10T13:27:43.985641
2009-06-06T16:46:31
2009-06-06T16:46:31
43,012,371
0
0
null
null
null
null
UTF-8
C++
false
false
1,017
cpp
#ifndef funciones #undef funciones #include <cstdlib> #include <iostream> #include "fichas_movimiento.h" #include "funciones_jugadas.h" char imprimirTablero(char TABLERO[TAM][TAM]) { cout<<endl; for (int i = 0; i < TAM; i++) { for (int j = 0; j < TAM; j++) { cout << TABLERO [i][j]; if (j+1 < TAM) cout << " | "; } cout << endl; if (i+1 < TAM) { for (int cont = 0 ; cont < 34; cont++) { cout << '-'; } } cout << endl; } } int cambio(char numero) { int cambio; if(numero=='A') cambio=7; if(numero=='B') cambio=6; if(numero=='C') cambio=5; if(numero=='D') cambio=4; if(numero=='E') cambio=3; if(numero=='F') cambio=2; if(numero=='G') cambio=1; if(numero=='H') cambio=0; return cambio; } #endif
[ "josedavid91@d3a48c4c-32b5-11de-9cad-a3574e5575ef" ]
[ [ [ 1, 56 ] ] ]
8dc9d68a008ef770a8fa6c6fa021d4f53c1c5480
7f72fc855742261daf566d90e5280e10ca8033cf
/branches/full-calibration/ground/src/plugins/uavobjects/homelocation.cpp
8be3eabe9ca70ce571a92003a277a145fdca96e0
[]
no_license
caichunyang2007/my_OpenPilot_mods
8e91f061dc209a38c9049bf6a1c80dfccb26cce4
0ca472f4da7da7d5f53aa688f632b1f5c6102671
refs/heads/master
2023-06-06T03:17:37.587838
2011-02-28T10:25:56
2011-02-28T10:25:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,396
cpp
/** ****************************************************************************** * * @file homelocation.cpp * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. * @see The GNU Public License (GPL) Version 3 * @addtogroup GCSPlugins GCS Plugins * @{ * @addtogroup UAVObjectsPlugin UAVObjects Plugin * @{ * * @note Object definition file: homelocation.xml. * This is an automatically generated file. * DO NOT modify manually. * * @brief The UAVUObjects GCS plugin *****************************************************************************/ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "homelocation.h" #include "uavobjectfield.h" const QString HomeLocation::NAME = QString("HomeLocation"); /** * Constructor */ HomeLocation::HomeLocation(): UAVDataObject(OBJID, ISSINGLEINST, ISSETTINGS, NAME) { // Create fields QList<UAVObjectField*> fields; QStringList SetElemNames; SetElemNames.append("0"); QStringList SetEnumOptions; SetEnumOptions.append("FALSE"); SetEnumOptions.append("TRUE"); fields.append( new UAVObjectField(QString("Set"), QString(""), UAVObjectField::ENUM, SetElemNames, SetEnumOptions) ); QStringList LatitudeElemNames; LatitudeElemNames.append("0"); fields.append( new UAVObjectField(QString("Latitude"), QString("deg * 10e6"), UAVObjectField::INT32, LatitudeElemNames, QStringList()) ); QStringList LongitudeElemNames; LongitudeElemNames.append("0"); fields.append( new UAVObjectField(QString("Longitude"), QString("deg * 10e6"), UAVObjectField::INT32, LongitudeElemNames, QStringList()) ); QStringList AltitudeElemNames; AltitudeElemNames.append("0"); fields.append( new UAVObjectField(QString("Altitude"), QString("m over geoid"), UAVObjectField::FLOAT32, AltitudeElemNames, QStringList()) ); QStringList ECEFElemNames; ECEFElemNames.append("0"); ECEFElemNames.append("1"); ECEFElemNames.append("2"); fields.append( new UAVObjectField(QString("ECEF"), QString("cm"), UAVObjectField::INT32, ECEFElemNames, QStringList()) ); QStringList RNEElemNames; RNEElemNames.append("0"); RNEElemNames.append("1"); RNEElemNames.append("2"); RNEElemNames.append("3"); RNEElemNames.append("4"); RNEElemNames.append("5"); RNEElemNames.append("6"); RNEElemNames.append("7"); RNEElemNames.append("8"); fields.append( new UAVObjectField(QString("RNE"), QString(""), UAVObjectField::FLOAT32, RNEElemNames, QStringList()) ); QStringList BeElemNames; BeElemNames.append("0"); BeElemNames.append("1"); BeElemNames.append("2"); fields.append( new UAVObjectField(QString("Be"), QString(""), UAVObjectField::FLOAT32, BeElemNames, QStringList()) ); QStringList g_eElemNames; g_eElemNames.append("0"); fields.append( new UAVObjectField(QString("g_e"), QString("m/s^2"), UAVObjectField::FLOAT32, g_eElemNames, QStringList()) ); // Initialize object initializeFields(fields, (quint8*)&data, NUMBYTES); // Set the default field values setDefaultFieldValues(); } /** * Get the default metadata for this object */ UAVObject::Metadata HomeLocation::getDefaultMetadata() { UAVObject::Metadata metadata; metadata.flightAccess = ACCESS_READWRITE; metadata.gcsAccess = ACCESS_READWRITE; metadata.gcsTelemetryAcked = 1; metadata.gcsTelemetryUpdateMode = UAVObject::UPDATEMODE_ONCHANGE; metadata.gcsTelemetryUpdatePeriod = 0; metadata.flightTelemetryAcked = 1; metadata.flightTelemetryUpdateMode = UAVObject::UPDATEMODE_ONCHANGE; metadata.flightTelemetryUpdatePeriod = 0; metadata.loggingUpdateMode = UAVObject::UPDATEMODE_NEVER; metadata.loggingUpdatePeriod = 0; return metadata; } /** * Initialize object fields with the default values. * If a default value is not specified the object fields * will be initialized to zero. */ void HomeLocation::setDefaultFieldValues() { data.Set = 0; data.Latitude = 0; data.Longitude = 0; data.Altitude = 0; data.ECEF[0] = 0; data.ECEF[1] = 0; data.ECEF[2] = 0; data.RNE[0] = 0; data.RNE[1] = 0; data.RNE[2] = 0; data.RNE[3] = 0; data.RNE[4] = 0; data.RNE[5] = 0; data.RNE[6] = 0; data.RNE[7] = 0; data.RNE[8] = 0; data.Be[0] = 0; data.Be[1] = 0; data.Be[2] = 0; data.g_e = 9.81; } /** * Get the object data fields */ HomeLocation::DataFields HomeLocation::getData() { QMutexLocker locker(mutex); return data; } /** * Set the object data fields */ void HomeLocation::setData(const DataFields& data) { QMutexLocker locker(mutex); // Get metadata Metadata mdata = getMetadata(); // Update object if the access mode permits if ( mdata.gcsAccess == ACCESS_READWRITE ) { this->data = data; emit objectUpdatedAuto(this); // trigger object updated event emit objectUpdated(this); } } /** * Create a clone of this object, a new instance ID must be specified. * Do not use this function directly to create new instances, the * UAVObjectManager should be used instead. */ UAVDataObject* HomeLocation::clone(quint32 instID) { HomeLocation* obj = new HomeLocation(); obj->initialize(instID, this->getMetaObject()); return obj; } /** * Static function to retrieve an instance of the object. */ HomeLocation* HomeLocation::GetInstance(UAVObjectManager* objMngr, quint32 instID) { return dynamic_cast<HomeLocation*>(objMngr->getObject(HomeLocation::OBJID, instID)); }
[ "jonathan@ebee16cc-31ac-478f-84a7-5cbb03baadba" ]
[ [ [ 1, 184 ] ] ]
fe9c602f7b47368144bc494d23a12ee4ee9d7018
0720d1d1dafeab58e9da83e8d4b16008ef63222d
/Renderer/vector3d.h
8ca7b29aaf7439e2e4645bfde1f377b1c8c947bb
[]
no_license
theonlynexus/quokka3d
a676f617ad4d7ee655401f37ed8820c4497e12b4
faeaf00f366b964c94e5a1e9ba979be193d82c4d
refs/heads/master
2016-09-05T21:17:04.981500
2007-06-02T16:01:48
2007-06-02T16:01:48
41,408,006
0
1
null
null
null
null
WINDOWS-1252
C++
false
false
5,951
h
// *************************************************************** // math3d version: 1.0 · date: 04/21/2007 // ------------------------------------------------------------- // // ------------------------------------------------------------- // Copyright (C) 2007 - All Rights Reserved // *************************************************************** // // *************************************************************** #ifndef MATH3D_H #define MATH3D_H // Avoid opening the header again for MS VC++ #ifdef _MSC_VER #pragma once #endif #include <iostream> #include <string> #include <vector> #include <cmath> #include <limits> #include <cassert> //=========================================================================== // // Global templates for operator overloads // (See "More Effective C++", Item 22) // //=========================================================================== template<typename T> const T operator+(const T& lhs, const T& rhs) { return T(lhs) += rhs; } template<typename T> const T operator-(const T& lhs, const T& rhs) { return T(lhs) -= rhs; } template<typename T> const T operator/(const T& lhs, float rhs) { assert(rhs > FLT_EPSILON); // check for divide-by-zero return T(lhs) /= rhs; } template<typename T> const T operator*(const T& lhs, float rhs) { return T(lhs) *= rhs; } template<typename T> const T operator*(float lhs, const T& rhs) { return T(rhs) *= lhs; } namespace Quokka3D { //=========================================================================== // // Forward declarations // //=========================================================================== // class Vector3D; class Transform3D; //=========================================================================== // // General purpose global utilities // //=========================================================================== const float PI = 3.141592654f; // Returns true if lhs == rhs within tolerance inline bool float_equals(float lhs, float rhs) { return fabs(lhs - rhs) < FLT_EPSILON ? true : false; } inline float DegToRad(float degree) { return degree * (PI / 180.0f); } inline float RadToDeg(float radian) { return radian * (180.0f / PI); } //=========================================================================== // // Math Classes // //=========================================================================== struct Rectangle { int x, y, width, height; }; class Transformable { public: //virtual Vector3D operator+(const Vector3D&) const = 0; //virtual Vector3D operator-(const Vector3D&) const = 0; //virtual Vector3D operator*(const float) const = 0; //virtual Vector3D operator/(const float) const = 0; // virtual void add(Transform3D xform) = 0; // virtual void subtract(Transform3D xform) = 0; // virtual void addRotation(Transform3D xform) = 0; // virtual void subtractRotation(Transform3D xform) = 0; }; //***************************************************************** // // The Vector3D class represents a 3D vector or vertex consisting // of 3 coordinates. // //***************************************************************** class Vector3D : public Transformable { public: float x; float y; float z; Vector3D(); // Default copy constructor should work (bitwise copy) // Vector3D(const Vector3D& vec) {} Vector3D(float x, float y, float z); // assignment operators Vector3D& operator += (const Vector3D&); Vector3D& operator -= (const Vector3D&); Vector3D& operator *= (float); Vector3D& operator /= (float); // equality operators bool operator == (const Vector3D&) const; bool operator != (const Vector3D&) const; std::string toString() const; // void setTo(float x, float y, float z); float length() const; void normalize(); float dot(const Vector3D&) const; void cross(const Vector3D&, const Vector3D&); void add(Transform3D&); void subtract(Transform3D&); void addRotation(Transform3D&); void subtractRotation(Transform3D&); private: void rotateX(float cosAngle, float sinAngle); void rotateY(float cosAngle, float sinAngle); void rotateZ(float cosAngle, float sinAngle); }; // Vector3D //***************************************************************** // // Inline functions of the Transform3D class // //***************************************************************** inline float Vector3D::length() const { return sqrt(x*x + y*y + z*z); } inline void Vector3D::normalize() { *this /= length(); } inline float Vector3D::dot(const Vector3D& v) const { return x*v.x + y*v.y + z*v.z; } // Sets this vector to the cross product of the two // specified vectors. inline void Vector3D::cross(const Vector3D& u, const Vector3D& v) { float x1 = u.y * v.z - u.z * v.y; float y1 = u.z * v.x - u.x * v.z; float z1 = u.x * v.y - u.y * v.x; this->x = x1; this->y = y1; this->z = z1; } } // Quokka3D // Output operators for Vector3D std::ostream& operator<< ( std::ostream&, Quokka3D::Vector3D& ); std::ostream& operator<< ( std::ostream&, const Quokka3D::Vector3D&); #endif // MATH3D_H
[ "martin.rennix@b6e4cb7b-8d2e-0410-91ea-c19743d4332f" ]
[ [ [ 1, 232 ] ] ]
e07d052651ef15babe613abddcf20a400dd6e9e5
01fadae9f2a6d3f19bc843841a7faa9c40fc4a20
/CG/code_CG/EX04_10.CPP
b77c9e18d388382a1962ae631bb3dfbbbe5a11fc
[]
no_license
passzenith/passzenithproject
9999da29ac8df269c41d280137113e1e2638542d
67dd08f4c3a046889319170a89b45478bfd662d2
refs/heads/master
2020-12-24T14:36:46.389657
2010-09-05T02:34:42
2010-09-05T02:34:42
32,310,266
0
0
null
null
null
null
UTF-8
C++
false
false
2,217
cpp
#include <windows.h> void drawDot (GLint x, GLint y) { glColor3f(0.0,0.0,0.0); glBegin (GL_POINTS); glVertex2i (x, y); glEnd(); } void myInit(void) { glClearColor(1.0,1.0,1.0,0.0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glPointSize(2.0); glLineWidth(2.0); gluOrtho2D(0.0, 640.0, 0.0, 480.0); } void symmetricPixels (int x, int y, int xc, int yc) // Function to plot semmetricPixel { drawDot (xc + x, yc + y); drawDot (xc - x, yc + y); drawDot (xc + x, yc - y); drawDot (xc - x, yc - y); } void Ellipse (int Rx, int Ry, int xc, int yc) // Function to draw ellipse { int RxSq,RySq,twoRxSq,twoRySq,d,dx,dy,x,y; RxSq = Rx*Rx; RySq = Ry*Ry; twoRxSq = 2*RxSq; twoRySq = 2*RySq; d = RySq - Ry*RxSq + RxSq/4; dx = 0; dy = twoRxSq*Ry; x = 0; y = Ry; symmetricPixels(x,y,xc,yc); while (dx < dy) { x++; dx += twoRySq; if (d >= 0) { y--; dy -= twoRxSq; } if (d < 0) d += RySq + dx; else d += RySq + dx - dy; symmetricPixels (x,y,xc,yc); } d = (int)(RySq*(x+0.5)*(x+0.5) + RxSq*(y-1)*(y-1) - RxSq*RySq); while (y > 0) { y--; dy -= twoRxSq; if (d <= 0) { x++; dx += twoRySq; } if (d > 0) d += RxSq - dy; else d += RxSq -dy +dx; symmetricPixels(x,y,xc,yc); } } void myDisplay(void) { glClear(GL_COLOR_BUFFER_BIT); glColor3f(0.0f,0.0f,0.0f); // Set line & point to black glBegin (GL_LINES); // Horizontal line (x axis) glVertex2i (50,240); glVertex2i (590,240); glEnd(); glBegin(GL_LINES); // Vertical line (ellipse y axis) glVertex2i(320,50); glVertex2i(320,430); glEnd(); Ellipse (200,100,320,240); glFlush(); } void main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(640,480); glutInitWindowPosition(50, 50); glutCreateWindow("Ellipse Drawing"); glutDisplayFunc(myDisplay); myInit(); glutMainLoop(); }
[ "passzenith@00fadc5f-a3f2-dbaa-0561-d91942954633" ]
[ [ [ 1, 100 ] ] ]
f7da5c59ee686891f892e453254f5a61cfed9bf8
6630a81baef8700f48314901e2d39141334a10b7
/1.4/Testing/Cxx/swWxGuiTesting/swCRXRCNode.cpp
96e09ddb3c7219c70a6f66db14712e36217818fc
[]
no_license
jralls/wxGuiTesting
a1c0bed0b0f5f541cc600a3821def561386e461e
6b6e59e42cfe5b1ac9bca02fbc996148053c5699
refs/heads/master
2021-01-10T19:50:36.388929
2009-03-24T20:22:11
2009-03-26T18:51:24
623,722
1
0
null
null
null
null
ISO-8859-1
C++
false
false
990
cpp
/////////////////////////////////////////////////////////////////////////////// // Name: swWxGuiTesting/swCRXRCNode.cpp // Author: Reinhold Füreder // Created: 2004 // Copyright: (c) 2005 Reinhold Füreder // Licence: wxWindows licence /////////////////////////////////////////////////////////////////////////////// #ifdef __GNUG__ #pragma implementation "swCRXRCNode.h" #endif #include "swCRXRCNode.h" namespace swTst { CRXRCNode::CRXRCNode (const wxString &name, const wxString &className, CRXRCNode *parentNode) : m_name (name), m_class (className), m_parentNode (parentNode) { // Nothing to do } CRXRCNode::~CRXRCNode () { // Nothing to do } const wxString & CRXRCNode::GetName () const { return m_name; } const wxString & CRXRCNode::GetClass () const { return m_class; } CRXRCNode * CRXRCNode::GetParent () const { return m_parentNode; } } // End namespace swTst
[ "john@64288482-8357-404e-ad65-de92a562ee98" ]
[ [ [ 1, 52 ] ] ]
0fe1914be9e9962f329ab3cfc8eeaa69cdbd9995
1493997bb11718d3c18c6632b6dd010535f742f5
/direct_ui/UIlib/UILabel.h
442c24b454c0a924c8b962e711753c52cc0f9912
[]
no_license
kovrov/scrap
cd0cf2c98a62d5af6e4206a2cab7bb8e4560b168
b0f38d95dd4acd89c832188265dece4d91383bbb
refs/heads/master
2021-01-20T12:21:34.742007
2010-01-12T19:53:23
2010-01-12T19:53:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,097
h
#if !defined(AFX_UILABEL_H__20060218_34CC_2871_036E_0080AD509054__INCLUDED_) #define AFX_UILABEL_H__20060218_34CC_2871_036E_0080AD509054__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 ///////////////////////////////////////////////////////////////////////////////////// // class UILIB_API CLabelPanelUI : public CControlUI { public: CLabelPanelUI(); LPCTSTR GetClass() const; void SetText(LPCTSTR pstrText); void SetWidth(int cxWidth); void SetTextStyle(UINT uStyle); SIZE EstimateSize(SIZE szAvailable); void DoPaint(HDC hDC, const RECT& rcPaint); void SetAttribute(LPCTSTR pstrName, LPCTSTR pstrValue); protected: int m_cxWidth; UINT m_uTextStyle; }; ///////////////////////////////////////////////////////////////////////////////////// // class UILIB_API CGreyTextHeaderUI : public CControlUI { public: LPCTSTR GetClass() const; SIZE EstimateSize(SIZE szAvailable); void DoPaint(HDC hDC, const RECT& rcPaint); }; #endif // !defined(AFX_UILABEL_H__20060218_34CC_2871_036E_0080AD509054__INCLUDED_)
[ [ [ 1, 47 ] ] ]
526ce0d7721d021a90ca758c1544dece0ef72fe0
7b4c786d4258ce4421b1e7bcca9011d4eeb50083
/_统计专用/C++Primer中文版(第4版)/第一次-代码集合-20090414/第八章 标准IO库/20090208_习题8.13_打开文件用于输出.hpp
4c9e70a796c27e284315660f9d11f8e573cc815a
[]
no_license
lzq123218/guoyishi-works
dbfa42a3e2d3bd4a984a5681e4335814657551ef
4e78c8f2e902589c3f06387374024225f52e5a92
refs/heads/master
2021-12-04T11:11:32.639076
2011-05-30T14:12:43
2011-05-30T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
134
hpp
// ofstream& open_file(ofstream &out, const string &file) { out.close(); out.clear(); out.open(file.c_str()); return out; }
[ "baicaibang@70501136-4834-11de-8855-c187e5f49513" ]
[ [ [ 1, 8 ] ] ]
72189dec190e1e3c224446def74e3749ddb89da1
155c4955c117f0a37bb9481cd1456b392d0e9a77
/Tessa/TessaTypes/TessaValue.cpp
caeff3034c46d06a763fb865d4db36d854ab0261
[]
no_license
zwetan/tessa
605720899aa2eb4207632700abe7e2ca157d19e6
940404b580054c47f3ced7cf8995794901cf0aaa
refs/heads/master
2021-01-19T19:54:00.236268
2011-08-31T00:18:24
2011-08-31T00:18:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,166
cpp
#include "TessaTypeHeader.h" namespace TessaTypes { int TessaValue::nextAvailableId = 0; TessaValue::TessaValue() { setType(TypeFactory::getInstance()->anyType()); _id = this->nextAvailableId++; } TessaValue::TessaValue(Type* type) { setType(type); _id = this->nextAvailableId++; } Type* TessaValue::getType() { return _type; } void TessaValue::setType(Type *type) { AvmAssert(type != NULL); _type = type; } bool TessaValue::isInstruction() { return false; } bool TessaValue::isConstantValue() { return false; } bool TessaValue::isInteger(){ return _type->isInteger(); } bool TessaValue::isUnsignedInteger() { return _type->isUnsignedInt(); } bool TessaValue::isBoolean() { return _type->isBoolean(); } bool TessaValue::isNumber() { return _type->isNumber(); } bool TessaValue::isArray() { return this->_type->isArray(); } bool TessaValue::isObject() { return _type->isObject(); } bool TessaValue::isNumeric() { return isInteger() || isNumber() || isUnsignedInteger(); } bool TessaValue::isString() { return _type->isString(); } bool TessaValue::isAny() { return _type->isAnyType(); } bool TessaValue::isPointer() { return _type->isPointer(); } bool TessaValue::isVector() { return _type->isVector(); } bool TessaValue::isScriptObject() { return _type->isScriptObject(); } TessaValue* TessaValue::resolve() { return this; } string TessaValue::toString() { char buffer[32]; VMPI_snprintf(buffer, sizeof(buffer), "Value $%d", getValueId()); return buffer; } string TessaValue::getOperandString() { char buffer[32]; VMPI_snprintf(buffer, sizeof(buffer), this->toString().data()); return buffer; } int TessaValue::getValueId() { return _id; } TessaInstructions::TessaInstruction* TessaValue::toInstruction() { if (this->isInstruction()) { return reinterpret_cast<TessaInstructions::TessaInstruction*>(this); } else { AvmAssertMsg(false, "False cast from TessaValue to tessaInstruction\n\n"); return NULL; } } }
[ [ [ 1, 109 ] ] ]
c720aac13d9977afcd42b98c62af3e23a7cf99f8
39f9ae6bdbda7f3b42cf4a006fb2a469fb44e4cf
/Farol/AssemblyInfo.cpp
4b46aa567e0d2ef8993d1f2dc527747d40b59ecd
[]
no_license
maochy/farol
30b2af11cf951d128797ec79c0d419883b7bbc11
486928695c3658e7646606d14c3bf6b8bc9d8933
refs/heads/master
2021-01-10T01:17:40.086620
2010-03-12T04:10:39
2010-03-12T04:10:39
38,855,832
0
0
null
null
null
null
UTF-8
C++
false
false
1,326
cpp
#include "stdafx.h" using namespace System; using namespace System::Reflection; using namespace System::Runtime::CompilerServices; using namespace System::Runtime::InteropServices; using namespace System::Security::Permissions; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly:AssemblyTitleAttribute("Farol")]; [assembly:AssemblyDescriptionAttribute("")]; [assembly:AssemblyConfigurationAttribute("")]; [assembly:AssemblyCompanyAttribute("")]; [assembly:AssemblyProductAttribute("Farol")]; [assembly:AssemblyCopyrightAttribute("Copyright (c) 2009")]; [assembly:AssemblyTrademarkAttribute("")]; [assembly:AssemblyCultureAttribute("")]; // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the value or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly:AssemblyVersionAttribute("1.0.*")]; [assembly:ComVisible(false)]; [assembly:CLSCompliantAttribute(true)]; [assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)];
[ "renanrv@5a151274-b240-11de-8e13-c326f17d7b4c" ]
[ [ [ 1, 40 ] ] ]
0f5dbbf92b37ddf6fb620691cad05c1f3002eebf
0454def9ffc8db9884871a7bccbd7baa4322343b
/src/plugins/shared2/QURequestUrl.h
66f6ae42e0339a971220c1c04715dafe5918c99b
[]
no_license
escaped/uman
e0187d1d78e2bb07dade7ef6ef041b6ed424a2d3
bedc1c6c4fc464be4669f03abc9bac93e7e442b0
refs/heads/master
2016-09-05T19:26:36.679240
2010-07-26T07:55:31
2010-07-26T07:55:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
751
h
#ifndef QUREQUESTURL_H #define QUREQUESTURL_H #include <QCoreApplication> #include <QUrl> #include <QByteArray> #include <QStringList> class QUSongInterface; class QURequestUrl: public QUrl { Q_DECLARE_TR_FUNCTIONS(QURequestUrl) public: QURequestUrl(const QString &host, const QStringList &properties, QUSongInterface *song); virtual ~QURequestUrl() {} virtual QString request() const = 0; protected: QUSongInterface* song() const { return _song; } QStringList properties() const { return _properties; } QByteArray fixedPercentageEncoding() const; QByteArray fixedPercentageEncoding(QByteArray source) const; private: QUSongInterface *_song; QStringList _properties; }; #endif // QUREQUESTURL_H
[ [ [ 1, 32 ] ] ]
1ceffe7ab53d63d11b04fa63427b42728d22ea2c
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/WORLDSERVER/User.h
e6941952efadedb2c9f4be467c0eb01d06efe936
[]
no_license
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UHC
C++
false
false
46,242
h
#ifndef __USER_H__ #define __USER_H__ #pragma once #include <DPlay.h> #include "MsgHdr.h" #include "Snapshot.h" #include "UserTaskBar.h" #include "Party.h" #ifdef __RT_1025 #include "rtmessenger.h" #else // __RT_1025 #include "messenger.h" #endif // __RT_1025 #include "misc.h" #include "guild.h" #include "eveschool.h" #include "Chatting.h" #include "CooltimeMgr.h" #if __VER >= 11 // __SYS_PLAYER_DATA #include "playerdata.h" #endif // __SYS_PLAYER_DATA #if __VER >= 12 // __SECRET_ROOM #include "SecretRoom.h" #endif // __SECRET_ROOM #if __VER >= 13 // __RAINBOW_RACE #include "RainbowRace.h" #endif // __RAINBOW_RACE #if __VER >= 13 // __HOUSING #include "Housing.h" #endif // __HOUSING #if __VER >= 14 // __PCBANG #include "PCBang.h" class CPCBangInfo; #endif // __PCBANG #if __VER >= 15 // __GUILD_HOUSE #include "GuildHouse.h" #endif // __GUILD_HOUSE #if __VER >= 15 // __CAMPUS #include "CampusHelper.h" #endif // __CAMPUS #define GETID( pCtrl ) ( (pCtrl) ? (pCtrl)->GetId() : NULL_ID ) typedef MemPooler<CUser> CUserPool; #ifdef __AZRIA_1023 #define MAX_INPUT_LEN 100 #endif // __AZRIA_1023 class CShip; class CMail; class CMailBox; ////////////////////////////////////////////////////////////////////////// #define CHECK_TICK_FROM_CLIENT SEC(3) ////////////////////////////////////////////////////////////////////////// #if __VER >= 12 // __LORD class CLordSkill; #endif // __LORD /// 플레이어를 나타내는 클래스 class CUser : public CMover { public: CUser(); CUser( DPID dpidCache, DPID dpidUser ); virtual ~CUser(); ////////////////////////////////////////////////////////////////////////// private: BOOL m_bCheckTransMailBox; int m_nCountFromClient; DWORD m_dwTickFromClient; ////////////////////////////////////////////////////////////////////////// public: DWORD m_dwSerial; /// 캐쉬서버가 발급한 유저의 순차적 번호 BOOL m_bValid; /// db server에서 join packet받고, 맵에 Add된후 TRUE CSnapshot m_Snapshot; /// SNAPSHOTTYPE_류 송신 누적 버퍼( Notify()에서 보내진다. ) map<DWORD, CCtrl*> m_2npc; /// 주변 NPC를 담고 있는 container DWORD m_dwTickSFS; /// SubSMMode, Finite, SavePlyer()용 타이머 DWORD m_dwTickNotify; /// Notify()용 타이머 DWORD m_dwTimeout4Save; /// db 저장용 타이머 DWORD m_dwLeavePenatyTime; /// 종료요청 시각 DWORD m_dwDestroyTime; /// Destory예약 시각 DWORD m_dwAuthKey; /// 인증용 key PLAY_ACCOUNT m_playAccount; /// Account정보 CUserTaskBar m_playTaskBar; /// player의 taskbar class(큇슬롯) OBJID m_idSetTarget; /// 이 유저가 잡고있는 타겟 #ifdef __RT_1025 CRTMessenger m_RTMessenger; #else // __RT_1025 CMessenger m_Messenger; /// 메신져 #endif // __RT_1025 char m_szPartyName[32]; /// 파티 이름 char m_szBankPass[5]; /// 은행 비빌번호 int m_nOverHeal; /// 오버힐 한 어시에게는 이 카운트가 붙는다. CObj *m_pWall[2]; /// 사이킥 월을 생성하면 여기에 저장 BOOL m_bPosting; /// 메일 사용중? u_long m_idChatting; /// 채팅방에 들어갔을 때의 채팅방 id u_long m_idSnoop; /// 나를 감청하는자 id BOOL m_bInstantBank; /// 즉시 사용 뱅크 사용중? CCooltimeMgr m_cooltimeMgr; /// 아이템 쿨타임 관리자 DWORD m_tmEscape; /// 탈출 인터페이스 시작시각 D3DXVECTOR3 m_vReturnPos; /// '귀환 두루마리' - 목표지점 DWORD m_dwReturnWorldID; /// '귀환 두루마리' - 월드 id LPCTSTR m_lpszVillage; /// '귀환 두루마리' - 마을 이름 DWORD m_dwPlayerTime; /// DB저장용 총 플레이 시간 DWORD m_dwSavePlayerTime; /// 마지막 저장 플레이 시간의 총합 #ifndef __JEFF_9_20 DWORD m_dwFlyTime; /// DB저장용 총 비행 시간 DWORD m_dwSaveFlyTime; /// 비행시간 계산용 DWORD m_dwSendFlyTime; /// 비행시간 계산용 #endif // __JEFF_9_20 OBJID m_idTargetCollect; /// 자원몬스터 채집대상 - 채집중에 타겟을 바꿀 수도 있기때문 int m_nCollect; /// 현재 자원 채집량 DWORD m_tmCollect; /// 자원채집 타이머 - 1초에 한번씩 #ifdef __EVENT_1101 #ifdef __EVENT_1101_2 __int64 m_nEventFlag; #else // __EVENT_1101_2 DWORD m_dwEventFlag; // 경과 일 번째 비트 #endif // __EVENT_1101_2 DWORD m_dwEventTime; // 분 단위 계수 DWORD m_dwEventElapsed; // 경과 일 #ifdef __EVENT_1101_2 __int64 GetEventFlagBit( int nBit ); #else // __EVENT_1101_2 int GetEventFlagBit( int nBit ); #endif // __EVENT_1101_2 int SetEventFlagBit( int nBit ); void AddCallTheRoll( void ); #endif // __EVENT_1101 #ifdef __HACK_1130 DWORD m_tmDuelRequest; #endif // __HACK_1130 #ifdef __QUEST_1208 DWORD m_tickScript; #endif // __QUEST_1208 #ifdef __S_SERVER_UNIFY BOOL m_bAllAction; #endif // __S_SERVER_UNIFY #ifdef __EVE_MINIGAME int m_nKawibawiboWin; int m_nKawibawiboState; int m_nBetFiveSystem[6]; #endif // __EVE_MINIGAME #ifdef __EXP_ANGELEXP_LOG int m_nExpLog; int m_nAngelExpLog; #endif // __EXP_ANGELEXP_LOG #ifdef __EVENTLUA_COUPON int m_nCoupon; DWORD m_dwTickCoupon; #endif // __EVENTLUA_COUPON #ifdef __EVENTLUA_KEEPCONNECT DWORD m_dwTickKeepConnect; #endif // __EVENTLUA_KEEPCONNECT #ifdef __PERIN_BUY_BUG DWORD m_dwLastTryBuyItem; DWORD m_dwLastBuyItemTick; #endif // __PERIN_BUY_BUG public: virtual void Process(); void DoSMItemEquip( CItemElem* pItemElem, DWORD dwParts ); void DoSMItemUnEquip( CItemElem* pItemElem, DWORD dwParts ); void CheckFiniteItem(); void LevelUpSetting( void ); void ExpUpSetting( void ); void SetValid( BOOL bValid ) { m_bValid = bValid; } BOOL IsValid(); void SetReturnPos( const D3DXVECTOR3& vPos ); D3DXVECTOR3& GetReturnPos( DWORD* pdwWorldID ); void SetPlayerTime( DWORD dwSaveTime ) { m_dwPlayerTime = timeGetTime(); m_dwSavePlayerTime = dwSaveTime; }; DWORD GetPlayerTime() { return (((timeGetTime() - m_dwPlayerTime) / 1000) + m_dwSavePlayerTime ); }; #ifndef __JEFF_9_20 void SetSaveFlyTime( DWORD dwFlyTime ) { m_dwFlyTime = m_dwSendFlyTime = 0; m_dwSaveFlyTime = dwFlyTime; }; void SetFlyTimeOn() { m_dwFlyTime = timeGetTime(); }; void SetFlyTimeOff() { m_dwSendFlyTime += (timeGetTime() - m_dwFlyTime ) / 1000; m_dwFlyTime = 0; }; DWORD GetFlyTime() { return m_dwSendFlyTime; }; #endif // __JEFF_9_20 void NPCSetAt( OBJID objid, CCtrl* pCtrl ) { m_2npc[objid] = pCtrl; } BOOL NPCRemoveKey( OBJID objid ) { return m_2npc.erase( objid ) > 0; } void RemoveItFromView2( BOOL bRemoveall = FALSE ); #ifdef __MAP_SECURITY void Open( DWORD dwWorldId ); #else // __MAP_SECURITY void Open(); #endif // __MAP_SECURITY // void Notify(); int Notify( void ); // void Flush() { Notify(); m_Snapshot.Flush(); } #ifdef __S_SERVER_UNIFY void SetAllAction(); #endif // __S_SERVER_UNIFY void AddPostMail( CMail* pMail ); void AddRemoveMail( u_long nMail, int nType ); void AddMailBox( CMailBox* pMailBox ); ////////////////////////////////////////////////////////////////////////// void SendCheckMailBoxReq( BOOL bCheckTransMailBox ); void CheckTransMailBox( BOOL bCheckTransMailBox ); BOOL GetCheckTransMailBox(); bool CheckClientReq(); void ResetCheckClientReq(); int GetCountClientReq(); ////////////////////////////////////////////////////////////////////////// void SetPosting( BOOL bPosting ) { m_bPosting = bPosting; } BOOL IsPosting( void ) { return m_bPosting; } BOOL IsUsableState( DWORD dwId ); void OnDoUseItem( DWORD dwData, OBJID objid, int nPart ); void DoUsePackItem( CItemElem* pItemElem, PPACKITEMELEM pPackItemElem ); BOOL DoUseGiftbox( CItemElem* pItemElem, DWORD dwItemId ); void DoUseEveFBOX( CItemElem* pItemElem ); void OnMsgArrival( DWORD dwParam ); void ADDGameJoin(); void AddHdr( OBJID objid, WORD wHdr ); void AddBlock( LPBYTE lpBlock, u_long uBlockSize ); void AddAddObj( CCtrl* pCtrl ); void AddRemoveObj( OBJID objid ) { AddHdr( objid, SNAPSHOTTYPE_DEL_OBJ ); } void AddDiagText( LPCSTR lpszText ); void AddText( LPCSTR lpszText ); void AddReplace( DWORD dwWorldID, D3DXVECTOR3 & vPos ); void AddCreateItem( CItemBase* pItemBase, BYTE* pnId, short* pnNum, BYTE nCount ); void AddMoveItem( BYTE nItemType, BYTE nSrcIndex, BYTE nDestIndex ); void AddTrade( CUser* pTrader, u_long uidPlayer ); void AddComfirmTrade( OBJID objid ); void AddComfirmTradeCancel( OBJID objid ); void AddTradePut( OBJID objid, BYTE i, BYTE nItemType, BYTE nId, short nItemNum = 1 ); void AddTradePutError(); void AddTradePull( OBJID objid, BYTE i ); void AddTradePutGold( OBJID objid, DWORD dwGold ); //raiders.2006.11.28 // void AddTradeClearGold( OBJID objid ); void AddTradeCancel( OBJID objid, u_long uidPlayer, int nMode = 0 ); void AddTradeOk( OBJID objid ) { AddHdr( objid, SNAPSHOTTYPE_TRADEOK ); } void AddTradeConsent() { AddHdr( NULL_ID, SNAPSHOTTYPE_TRADECONSENT ); } void AddTradelastConfirm() { AddHdr( NULL_ID, SNAPSHOTTYPE_TRADELASTCONFIRM ); } void AddTradelastConfirmOk( OBJID objid ) { AddHdr( objid, SNAPSHOTTYPE_TRADELASTCONFIRMOK ); } void AddOpenShopWnd( CMover* pVendor ); #if __VER >= 15 // __PETVIS void AddUpdateItem( CHAR cType, BYTE nId, CHAR cParam, DWORD dwValue, DWORD dwTime ); #else // __PETVIS void AddUpdateItem( CHAR cType, BYTE nId, CHAR cParam, DWORD dwValue ); #endif // __PETVIS #if __VER >= 11 // __SYS_IDENTIFY void AddUpdateItemEx( unsigned char id, char cParam, __int64 iValue ); #endif // __SYS_IDENTIFY #ifdef __JEFF_11 void AddQuePetResurrectionResult( BOOL bResult ); #endif // __JEFF_11 #if __VER >= 11 // __SYS_POCKET void AddPocketAttribute( int nAttribute, int nPocket, int nData ); void AddPocketView( void ); void AddPocketAddItem( int nPocket, CItemElem* pItem ); void AddPocketRemoveItem( int nPocket, int nItem, short nNum ); #endif // __SYS_POCKET void AddSetFxp( int nFxp, int nFlightLv ); void AddSetGrowthLearningPoint( long nRemainGP ); void AddSetStatLevel( CHAR chID, long nValue, long nRemainGP ); void AddDefinedText( int dwText, LPCSTR lpszFormat, ... ); void AddChatText( int dwText, LPCSTR lpszFormat, ... ); void AddDefinedText( int dwText ); void AddDefinedCaption( BOOL bSmall, int dwText, LPCSTR lpszFormat, ... ); void AddGoldText( int nPlus ); void AddExpBoxInfo( OBJID objid, DWORD dwSet, DWORD dwTime, u_long idPlayer ); void AddSetQuest( LPQUEST lpQuest ); void AddSetGuildQuest( int nQuestId, int nState ); void AddRemoveGuildQuest( int nQuestId ); void AddSetChangeJob( int nJob ); void AddReturnSay( int ReturnFlag, const CHAR* lpszPlayer ); void AddGameTimer( double dCurrentTime ); void AddDoEquip( BYTE nId, DWORD dwItemId, BYTE fEquip ); void AddPartyChangeLeader( u_long uidChangeLeader ); void AddCancelQuest( DWORD dwQuestCancelID ); void AddRemoveQuest( DWORD dwQuestCancelID ); void AddRemoveAllQuest(); void AddRemoveCompleteQuest(); void AddGetItemBank( CItemElem* pItemElem ); void AddMoveBankItem( BYTE nSrcIndex, BYTE nDestIndex ); void AddBankIsFull(); void AddRemoveGuildBankItem( u_long idGuild, DWORD dwId, DWORD dwItemNum ); void AddChangeBankPass( int nMode, DWORD dwId, DWORD dwItemId ); void AddBankWindow( int nMode, DWORD dwId, DWORD dwItemId ); void AddconfirmBankPass( int nMode, DWORD dwId, DWORD dwItemId ); void AddTaskBar(); void AddSendErrorParty( DWORD dw, DWORD dwSkill = 0 ); #if __VER >= 11 // __SYS_PLAYER_DATA void AddPartyMember( CParty *pParty, u_long idPlayer, const char* pszLeader, const char* pszMember ); #else // __SYS_PLAYER_DATA void AddPartyMember( CParty *pParty, u_long uPlayerId = 0 ); #endif // __SYS_PLAYER_DATA void AddPartyRequest( CUser * pLeader, CUser * pMember, BOOL bTroup ); void AddPartyRequestCancel( u_long uLeaderid, u_long uMemberid, int nMode = 0 ); void AddPartyExpLevel( int Exp, int Level, int nPoint ); #if __VER < 11 // __SYS_PLAYER_DATA void AddPartyMemberJob( int nMemberIndex, int nJob); void AddPartyMemberLevel( int nMemberIndex, int nLevel); #endif // __SYS_PLAYER_DATA void AddPartyMemberFlightLevel( int nMemberIndex, int nLevel); void AddPartyChangeTroup( const char * szPartyName ); void AddPartyChangeName( const char * szPartyName ); #if __VER >= 12 // __JHMA_VER12_1 //12차 극단유료아이템 void AddSetPartyMode( int nMode, BOOL bOnOff, LONG nPoint , DWORD dwSkillTime ); #else // //12차 극단유료아이템 void AddSetPartyMode( int nMode, BOOL bOnOff, LONG nPoint ); #endif // //12차 극단유료아이템 void AddPartyChangeItemMode( int nItemMode ); void AddPartyChangeExpMode( int nExpMode ); void AddSetPartyMemberParam( u_long idPlayer, BYTE nParam, int nVal ); void AddPartyName(); void AddPartySkillCall( const D3DXVECTOR3 &vLeader ); void AddPartySkillBlitz( OBJID idTarget ); #if __VER < 11 // __SYS_PLAYER_DATA void AddFriendChangeJob( u_long uidPlayer, int nJob ); #endif // __SYS_PLAYER_DATA void AddFriendGameJoin(); void AddFriendReqest( u_long uLeader, LONG nJob, BYTE nSex, const char * szName ); void AddFriendCancel(); void AddFriendError( BYTE nError, const char * szName ); #if __VER < 11 // __SYS_PLAYER_DATA void AddGetFriendName( int nCount, FRIEND* aFriend ); #endif // __SYS_PLAYER_DATA #ifdef __ENVIRONMENT_EFFECT void AddEnvironmentSetting(); #endif // __ENVIRONMENT_EFFECT void AddEnvironment(); void AddPartyChat( const CHAR* lpName, const CHAR* lpString, OBJID objid ); #ifdef __RT_1025 void AddAddFriend( u_long idPlayer, const char* lpszPlayer ); #else // __RT_1025 void AddAddFriend( u_long idPlayer, LONG nJob, DWORD dwSex, const char* lpszPlayer ); #endif // __RT_1025 void AddRemoveFriend( u_long uidSender ); void AddDuelCount( int nCount ); void AddDuelRequest( u_long uidSrc, u_long uidDst ); void AddDuelStart( u_long uidTarget, int bStart = 0 ); void AddDuelNo( OBJID idTarget ); void AddDuelCancel( OBJID idTarget ); // 듀얼중 취소시킴 void AddDuelPartyRequest( u_long uidSrc, u_long uidDst ); void AddDuelPartyStart( LPCTSTR szPartyName, int nMax, OBJID *pMembers, u_long idParty, int bFlag = 0 ); void AddDuelPartyNo( OBJID idTarget ); void AddDuelPartyCancel( CParty *pDuelOther ); // 듀얼중 취소시킴 void AddDuelPartyResult( CParty *pDuelOther, BOOL bWin ); // 듀얼결과 통보. #if __VER >= 11 // __SYS_PLAYER_DATA void AddQueryPlayerData( u_long idPlayer, PlayerData* pPlayerData ); void AddPlayerData( void ); #else // __SYS_PLAYER_DATA void AddQueryPlayerString( u_long idPlayer, LPCSTR lpszPlayer, BYTE nQuery ); void AddQueryPlayerListString( BYTE nQuery ); #endif // __SYS_PLAYER_DATA void AddSetState( LONG nStr, LONG nSta, LONG nDex, LONG nInt, LONG nGP ); void AddSetSkill( DWORD dwSkill, DWORD dwSkillLevel ); void AddQueryGetPos( OBJID objid ); void AddGetPos( OBJID objid, const D3DXVECTOR3 & vPos, float fAngle ); void AddResurrectionMessage(); void AddCorrReq( CMover *pMover ); void AddSetFuel( int nFuel, DWORD tmAccFuel ); void AddTag( short nTagCount, const TAG_ENTRY* tags ); void AddSetSkillState( CMover *pMover, DWORD dwSkill, DWORD dwLevel, DWORD dwTime ); void AddPlaySound( u_long idSound ); void AddMoverFocus( CMover *pMover ); void AddPlayMusic( u_long idMusic ); void AddRegisterPVendorItem( BYTE iIndex, BYTE nType, BYTE nId, short nNum, int nCost ); void AddUnregisterPVendorItem( BYTE iIndex ); void AddPVendorItem( CUser* pUser, BOOL bState ); // locked void AddPVendorClose( OBJID objidVendor ); void AddMotionError(); void AddPutItemBank( BYTE nSlot, CItemElem* pItemElem ); void AddPutGoldBank( BYTE nSlot, DWORD dwGold, DWORD dwGoldBank ); void AddUpdateBankItem( BYTE nSlot, BYTE nId, CHAR cParam, DWORD dwValue ); void AddGuildBankWindow(int nMode); void AddPutItemGuildBank(CItemElem* pItemElem); void AddGetItemGuildBank( CItemElem* pItemElem ); void AddGetGoldGuildBank( DWORD p_Gold, BYTE p_Mode, u_long playerID, BYTE cbCloak ); void AddContribution( CONTRIBUTION_CHANGED_INFO& info ); void AddSetNotice( u_long idGuild, const char* szNotice ); void AddInsertedVote( VOTE_INSERTED_INFO& info ); void AddModifyVote( u_long idVote, BYTE cbOperation, BYTE cbExtra ); void AddSetGuildAuthority( DWORD dwAuthority[] ); void AddSetGuildPenya( DWORD dwType, DWORD dwPenya ); void AddGuildRealPenya( int nGoldGuild, int nType ); #if __VER < 11 // __SYS_PLAYER_DATA void AddChangeGuildJobLevel( u_long uidPlayer, LONG nJob, LONG nLevel ); #endif // __SYS_PLAYER_DATA void AddAllGuilds(); void AddMyGuild(); void AddGuildInvite( u_long idGuild, u_long idMaster ); void AddMyGuildWar(); void SendGuildRank(); void AddSMMode( int nType, DWORD dwTime ); void AddSMModeAll(); void AddResistSMMode( BYTE nAttackResistLeft, BYTE nAttackResistRight, BYTE nDefenceResist ); void AddCommercialElem( DWORD dwItemId, int nResistSMItemId ); void AddFlyffEvent(); #if __VER >= 9 // __EVENTLUA void AddEventLuaDesc( int nState, string strDesc ); #endif // __EVENTLUA void AddQueryGetDestObj( OBJID objid ); void AddGetDestObj( OBJID objid, OBJID objidDest, FLOAT fRange ); BOOL DoCollect( CMover *pTarget ); // 채집시작. int OnActCollecting(); // 채집중 계속 호출. void AddCommonSkill( DWORD dwSkill, DWORD dwLevel ); void AddExpBoxCoolTime( OBJID objid, DWORD dwTime ); void AddPlaySound2( const char* szSound ); void AddRunScriptFunc( const RunScriptFunc & runScriptFunc ); void AddRemoveSkillInfluence( WORD wType, WORD wID ); void AddGCWindow( __int64 dwPrizePenya, DWORD dwRequstPenya, DWORD dwMinRequestPenya ); void AddGCRequestStatus( __int64 nPrizePenya, vector<CGuildCombat::__REQUESTGUILD> vecRequestStatus ); void AddGCSelectPlayerWindow( vector<CGuildCombat::__JOINPLAYER> &vecSelectPlayer, u_long uidDefender, BOOL bWindow, BOOL bRequestWar ); void AddGCJoinWarWindow( int nMap, int nTelTime ); void AddGuildCombatNextTime( DWORD dwTime, DWORD dwState ); void AddGuildCombatEnterTime( DWORD dwTime ); void AddGCWinGuild( void ); void AddGCBestPlayer( void ); void AddGCIsRequest( BOOL bRequest ); void AddGCGetPenyaGuild( int nGetResult, __int64 nGetPenya ); void AddGCGetPenyaPlayer( int nGetResult, __int64 nGetPenya ); void AddGCDiagMessage( const char* str ); void AddGCTele( const char* str ); void AddGCWarPlayerlist( void ); void AddCtrlCoolTimeCancel( void ); void AddGuildCombatState( void ); void AddQuestTextTime( BOOL bFlag, int nState, DWORD dwTime ); void AddGCLog( void ); void AddGCPlayerPoint( void ); void AddFocusObj(OBJID objid); void AddEnterChatting( CUser* pUser ); void AddNewChatting( CChatting* pChatting ); void AddRemoveChatting( u_long uidPlayer ); void AddDeleteChatting( void ); void AddChatting( u_long uidPlayer, char* pszChat ); void AddChttingRoomState( BOOL bState ); void AddGameRate( FLOAT fRate, BYTE nFlag ); void AddGameSetting(); void AddInitSkill(); void AddSetNaviPoint( const NaviPoint & nv, OBJID objid, const char* Name ); void AddEscape( DWORD tmMaxEscape ); void AddSetActionPoint( int nAP ); void AddSetTarget( OBJID idTarget ); void AddSetDuel( CMover* pMover ); #if __VER >= 8 // __S8_PK void AddPKValue(); #else // __VER >= 8 // __S8_PK void UpdatePlayerEnemy( BYTE byType, OBJID objid ); #endif // __VER >= 8 // __S8_PK void ScheduleDestory( DWORD dwDestoryTime ); void AddWantedInfo( const D3DXVECTOR3& vPos, BYTE byOnline, DWORD dwWorldID, LPCTSTR lpszWorld ); void AddReturnScroll(); void AddSnoop( const char* lpString ); void AddSetCheerParam( int nCheerPoint, DWORD dwRest, BOOL bAdd = FALSE ); void AddQueryEquip( CUser* pUser ); void AddSummonFriendUse( CItemElem* pItemElem ); void AddSummonFriendConfirm( OBJID objid, DWORD dwData, const char* szName, const char* szWorldName ); void AddSummonPartyConfirm( OBJID objid, DWORD dwData, const char * szWorldName ); void AddDoUseSkillPoint( SKILL aJobSkill[], int nSkillPoint ); void AddPartyMapInfo( int nIndex, D3DXVECTOR3 vPos ); // __S1005_PARTY_MAP void AddSetExperience( EXPINTEGER nExp1, WORD wLevel, int nSkillPoint, int nSkillLevel, EXPINTEGER nDeathExp = (EXPINTEGER)-1, WORD wDeathLevel = 0xffff ); #ifdef __S_SERVER_UNIFY void AddAllAction( BOOL bCharacter ); #endif // __S_SERVER_UNIFY #ifdef __S1108_BACK_END_SYSTEM void AddMonsterProp(); #endif // __S1108_BACK_END_SYSTEM #if __VER >= 8 //__CSC_VER8_5 // void AddCreateAngel(BOOL isSuccess, char* createAngel); void AddAngelInfo( BOOL bComplete = FALSE ); #endif //__CSC_VER8_5 #ifdef __EVE_MINIGAME void AddKawibawiboResult( int nResult, int nWinCount, DWORD dwItemId = 0, int nItemCount = 0, DWORD dwNextItemId = 0, int nNextItemCount = 0 ); void AddReassembleResult( DWORD dwItemId, int nItemCount ); void AddReassembleOpenWnd( vector<DWORD> vecItemId ); void AddAlphabetOpenWnd( int nQuestionID, int nPublicAlphabet, char chPublicChar, CString strQuestion ); void AddAlphabetResult( int nResult, DWORD dwItemId = 0, int nItemCount = 0 ); void AddFiveSystemOpenWnd( int nBetMinPenya, int nBetMaxPenya, int nMultiple ); void AddFiveSystemResult( int nResult, int nGetPenya = 0, int nBetNum = 0 ); #endif // __EVE_MINIGAME #if __VER >= 9 // __ULTIMATE void AddUltimateMakeItem( BOOL bResult ); void AddUltimateMakeGem( int nResult, int nNum ); void AddUltimateWeapon( BYTE state, int nResult ); #endif // __ULTIMATE #ifdef __TRADESYS void AddExchangeResult( BYTE state, int nResult ); #endif // __TRADESYS #if __VER >= 9 // __PET_0410 void AddPet( CPet* pPet, BYTE nPetLevelup = PF_PET ); void AddPetState( DWORD dwPetId, WORD wLife, WORD wEnergy, DWORD dwExp ); void AddPetSetExp( DWORD dwExp ); void AddPetFoodMill( int nResult, int nCount ); #endif // __PET_0410 #if __VER >= 10 // __LEGEND // 9차 전승시스템 Neuz, World, Trans void AddLegendSkillResult( int nResult ); #endif //__LEGEND // 9차 전승시스템 Neuz, World, Trans #if __VER >= 10 // __REMOVE_ATTRIBUTE void AddRemoveAttribute( BOOL bSuccess ); #endif // __REMOVE_ATTRIBUTE #if __VER >= 11 // __SYS_COLLECTING virtual void ProcessCollecting( void ); virtual void StartCollecting( void ); virtual void StopCollecting( void ); BOOL DoUseItemBattery( void ); #if __VER < 14 // __SMELT_SAFETY BOOL PreRefine( DWORD dwTarget, DWORD dwMaterial ); void RefineCollector( CItemElem* pTarget, CItemElem* pMaterial ); void RefineAccessory( CItemElem* pTarget, CItemElem* pMaterial ); #endif // __SMELT_SAFETY void AddRestartCollecting( DWORD dwItemId ); int m_nCollecting; #endif // __SYS_COLLECTING #ifdef __AZRIA_1023 BOOL HasInput() { return m_szInput[0] != '\0'; } void ResetInput() { m_szInput[0] = '\0'; } void SetInput( char* szInput ) { strncpy( m_szInput, szInput, MAX_INPUT_LEN ); m_szInput[MAX_INPUT_LEN-1] = '\0'; } char* GetInput() { return m_szInput; } int DoUseItemInput( ItemProp* pProp, CItemElem* pItem ); #endif // __AZRIA_1023 #ifdef __PET_1024 int DoUseItemPetNaming(); #endif // __PET_1024 #ifdef __SYS_TICKET private: CItemElem* FindActiveTicket( DWORD dwItemId ); public: void DoUseItemTicket( CItemElem* pItemElem ); #endif // __SYS_TICKET #if __VER >= 11 // __GUILD_COMBAT_1TO1 void AddGC1to1TenderOpenWnd( int nPenya ); void AddGC1to1TenderGuildView( int nPenya, int nRanking, time_t t, vector<CGuildCombat1to1Mng::__GC1TO1TENDER>& vecTenderGuild ); void AddGC1to1MemberLineUpOpenWnd( vector<u_long>& vecMemberId ); void AddGC1to1NowState( int nState, int nTime, int nProgCount = 0 ); void AddGC1to1WarResult( int m_nState, u_long uIdPlayer, int nWinCount0, int nWinCount1 ); #endif // __GUILD_COMBAT_1TO1 #if __VER >= 8 // __CSC_VER8_5 void RemoveAngel( void ); #endif // __CSC_VER8_5 #if __VER >= 11 // __MA_VER11_04 // 길드 창고 로그 기능 world,database,neuz void AddGuildBankLogView( BYTE byListType, short nLogCount, const __GUILDBANKLOG_ENTRY* logs ); #endif //__MA_VER11_04 // 길드 창고 로그 기능 world,database,neuz #if __VER >= 11 // __MA_VER11_05 // 케릭터 봉인 거래 기능 world,database,neuz void AddSealChar( short nLogCount, const __SEALCHAR_ENTRY* seals ); void AddSealCharSet(); #endif // __MA_VER11_05 // 케릭터 봉인 거래 기능 world,database,neuz #if __VER >= 13 // __HONORABLE_TITLE // 달인 void AddHonorListAck(); #endif // __HONORABLE_TITLE // 달인 #ifdef __EVENTLUA_COUPON void AddCoupon( int nCoupon ); #endif // __EVENTLUA_COUPON #if __VER >= 12 // __SECRET_ROOM void AddSecretRoomMngState( int nState, DWORD dwRemainTime ); void AddSecretRoomContInfo( BYTE nContinent, BYTE nType, vector<__SECRETROOM_TENDER> & vecSecreetRoomTender, int nIndex ); void AddSecretRoomTenderOpenWnd( int nTenderPenya ); void AddSecretRoomLineUpOpenWnd( vector<DWORD>& vecLineUpMember ); void AddSecretRoomTenderView( int nTenderPenya, int nRanking, time_t t, vector<__SECRETROOM_TENDER>& vecSRTender ); #endif // __SECRET_ROOM #if __VER >= 12 // __LORD void AddLord( void ); void AddLordSkillTick( CLordSkill* pSkills ); int GetMuteText( void ); void SetElection( u_long idElection ) { m_idElection = idElection; } u_long GetElection( void ) { return m_idElection; } BOOL IsTeleportable( void ); BOOL IsQuerying( void ) { return m_bQuerying; } void SetQuerying( BOOL bQuerying ) { m_bQuerying = bQuerying; } #endif // __LORD #if __VER >= 12 // __MOD_TUTORIAL void AddSetTutorialState( void ); #endif // __MOD_TUTORIAL #if __VER >= 12 // __TAX void AddTaxInfo( void ); void AddTaxSetTaxRateOpenWnd( BYTE nCont ); #endif // __TAX BOOL IsGuildMaster(); void ValidateItem( void ); void AdjustGuildQuest( DWORD dwWorldId ); void AdjustMailboxState( void ); void AddEventLuaDesc( void ); void AdjustPartyQuest( DWORD dwWorldId ); public: #ifndef __VM_0820 #ifndef __MEM_TRACE static CUserPool* m_pPool; void* operator new( size_t nSize ) { return CUser::m_pPool->Alloc(); } void* operator new( size_t nSize, LPCSTR lpszFileName, int nLine ) { return CUser::m_pPool->Alloc(); } void operator delete( void* lpMem ) { CUser::m_pPool->Free( (CUser*)lpMem ); } void operator delete( void* lpMem, LPCSTR lpszFileName, int nLine ) { CUser::m_pPool->Free( (CUser*)lpMem ); } #endif // __MEM_TRACE #endif // __VM_0820 #if __VER >= 13 // __RAINBOW_RACE void AddRainbowRacePrevRankingOpenWnd(); void AddRainbowRaceApplicationOpenWnd(); void AddRainbowRaceState( CRainbowRace* pRainbowRace ); void AddMiniGameState( __MINIGAME_PACKET MiniGamePacket ); void AddMiniGameExtState( __MINIGAME_EXT_PACKET MiniGameExtPacket ); #endif // __RAINBOW_RACE #if __VER >= 13 // __HOUSING void AddHousingAllInfo( CHousing* pHousing ); void AddHousingSetFurnitureList( HOUSINGINFO& housingInfo, BOOL bAdd ); void AddHousingSetupFurniture( HOUSINGINFO* pHousingInfo ); void AddHousingPaperingInfo( DWORD dwItemId, BOOL bSetup ); void AddHousingSetVisitAllow( DWORD dwTargetId, BOOL bAllow ); void AddHousingVisitableList( vector<DWORD> & vecVisitable ); #endif // __HOUSING #if __VER >= 13 // __QUEST_HELPER void AddNPCPos( const D3DXVECTOR3 & vPos ); #endif // __QUEST_HELPER void AddClearTarget(); private: void Init( DPID dpidCache = DPID_UNKNOWN, DPID dpidUser = DPID_UNKNOWN ); #if __VER >= 12 // __LORD u_long m_idElection; BOOL m_bQuerying; #endif // __LORD #ifdef __AZRIA_1023 char m_szInput[MAX_INPUT_LEN]; #endif // __AZRIA_1023 #if __VER >= 13 // __COUPLE_1117 public: void SetProposer( u_long idProposer ) { m_idProposer = idProposer; } u_long GetProposer() { return m_idProposer; } void AddCouple(); void AddProposeResult( u_long idProposer, const char* pszProposer,const char* propose ); void AddCoupleResult( u_long idPartner, const char* pszPartner ); void AddDecoupleResult(); void SandCoupleInfo( CCtrl* pCtrl,BYTE byType, const char* szCouple); #if __VER >= 13 // __COUPLE_1202 void ProcessCouple(); void ActiveCoupleBuff( int nLevel ); void AddAddCoupleExperience( int nExperience ); #endif // __COUPLE_1202 #if __VER >= 14 // __PCBANG void AddPCBangInfo( CPCBangInfo* pPI ); #endif // __PCBANG #ifdef __VTN_TIMELIMIT void AddAccountPlayTime(); #endif // __VTN_TIMELIMIT #if __VER >= 14 // __SMELT_SAFETY void AddSmeltSafety( BYTE nResult ); #endif // __SMELT_SAFETY #ifdef __MAP_SECURITY void AddWorldReadInfo( DWORD dwWorldId, D3DXVECTOR3 vPos ); #endif // __MAP_SECURITY #ifdef __QUIZ void AddQuizEventState( int nType, int nState ); void AddQuizEventMessage( const char* lpszMessage, int nState = 0 ); void AddQuizQuestion( int nType, const char* lpszQuestion, int nCount ); #endif // __QUIZ #if __VER >= 15 // __PETVIS void AddActivateVisPet( OBJID objIdVisPetItem, OBJID objIdVisPetId ); #endif // PETVIS #if __VER >= 15 // __IMPROVE_QUEST_INTERFACE void AddCheckedQuest(); #endif // __IMPROVE_QUEST_INTERFACE #if __VER >= 15 // __GUILD_HOUSE public: void AddGuildHousePakcet( int nPacketType, GH_Fntr_Info & gfi, int nIndex ); void AddGuildHouseAllInfo( CGuildHouseBase* pGuildHouse ); void AddGuildHouseRemvoe(); int GetRestPoint() { return m_nRestPoint; } int SetIncRestPoint( int nRestPoint ) { return SetAddRestPoint( (int)( nRestPoint * static_cast<float>( GetParam( DST_RESTPOINT_RATE, 0 ) / 100.0f ) ) ); } int SetDecRestPoint( int nRestPoint ) { return SetAddRestPoint( -nRestPoint ); } void SetRestPoint( int nRestPoint ) { m_nRestPoint = nRestPoint; } void SetRestPointTick() { m_tRestPointTick = time_null() + REST_POINT_TICK; } EXPINTEGER GetAddExpAfterApplyRestPoint( EXPINTEGER nExp ); private: int SetAddRestPoint( int nRestPoint ); void AddRestPoint(); int m_nRestPoint; int m_nPrevRestPoint; time_t m_tRestPointTick; #endif // __GUILD_HOUSE #if __VER >= 15 // __CAMPUS public: void AddInviteCampusMember( CUser* pRequest ); void AddUpdateCampus( CCampus* pCampus ); void AddRemoveCampus( u_long idCampus ); void AddUpdateCampusPoint( int nCampusPoint ); void ProcessCampus(); void ActiveCampusBuff( int nLevel ); DWORD GetCampusTick() { return m_dwCampusTick; } void SetCampusTick( DWORD dwTick ) { m_dwCampusTick = dwTick; } int GetPointByType( int nType ); // 100122 define.h 에 정의되어 있는 포인트 타입에 따른 유저의 포인트 리턴 private: DWORD m_dwCampusTick; #endif // __CAMPUS #ifdef __GUILD_HOUSE_MIDDLE public: void AddGuildHouseTenderMainWnd( map<OBJID, char*>& mapGHList ); void AddGuildHouseTenderInfoWnd( OBJID objGHId, int nTenderMinPenya, __int64 nTenderPenya, vector<DWORD>& vecGuildId ); void AddGuildHouseTenderResult( OBJID objGHId, BOOL bResult ); #endif // __GUILD_HOUSE_MIDDLE private: u_long m_idProposer; #if __VER >= 13 // __COUPLE_1202 int m_cbProcessCouple; #endif // __COUPLE_1202 #endif // __COUPLE_1117 // mulcom BEGIN100405 각성 보호의 두루마리 public: void SelectAwakeningValue( DWORD dwItemObjID, DWORD dwSerialNumber, BYTE bySelectFlag ); void SendNewRandomOption( unsigned char id, DWORD dwSerialNumber, __int64 n64NewRandomOption ); // mulcom END100405 각성 보호의 두루마리 }; #define SEC_SAVEPLAYER 900 class CDPSrvr; #if __VER >= 12 // __LORD class CLEComponent; class ILordEvent; #endif // __LORD class CUserMng { public: CUserMng(); virtual ~CUserMng(); private: long m_lCount; map<DWORD, CUser*> m_users; private: void RemoveUserFromCacheMsg( CUser *pUser ); public: void DestroyPlayer( CUser* pUser ); LONG GetCount() { return m_lCount; } void RemoveAllUsers(); CUser* AddUser( DPID dpidCache, DPID dpidUser, DPID dpidSocket ); void RemoveUser( DWORD dwSerial ); CUser* GetUser( DPID dpidCache, DPID dpidUser ); CUser* GetUserByPlayerID( u_long idPlayer ); // void Notify(); #ifdef __LAYER_1015 BOOL AddPlayer( CUser* pUser, DWORD dwWorldID, int nLayer ); #else // __LAYER_1015 BOOL AddPlayer( CUser* pUser, DWORD dwWorldID ); #endif // __LAYER_1015 void AddDisguise( CMover* pMover, DWORD dwMoverIdx ); void AddNoDisguise( CMover* pMover ); void AddSetStateLevel( CMover* pMover, CHAR chID, long nValue ); void AddHdr( CCtrl* pCtrl, WORD wHdr ); void AddChat( CCtrl* pCtrl, const TCHAR* szChat ); #if __VER >= 11 // __SYS_COLLECTING void AddStartCollecting( CUser* pUser ); void AddStopCollecting( CUser* pUser ); #endif // __SYS_COLLECTING void AddDlgEmoticon( CCtrl* pCtrl, int nIdx ); void AddDamage( CMover* pMover, OBJID objidAttacker, DWORD dwHit, DWORD dwAtkFlags ); void AddDoEquip( CMover* pMover, int nPart, BYTE nId, const EQUIP_INFO & rEquipInfo, BYTE fEquip ); void AddDoEquip( CMover* pMover, int nPart, CItemElem *pItemElem, BYTE fEquip ); // 간단 파라메터 버전. void AddVendor( CMover* pVendor ); void AddUpdateVendor( CMover* pVendor, CHAR cTab, BYTE nId, short nNum ); void AddSetDestParam( CMover* pMover, int nDstParameter, int nAdjParameterValue, int nChgParameterValue ); void AddResetDestParam( CMover* pMover, int nDstParamter, int nAdjParameterValue ); #ifdef __SPEED_SYNC_0108 // ResetDestParam speed 수정 void AddResetDestParamSync( CMover* pMover, int nDstParameter,int nAdjParameterValue, int nParameterValue ); #endif // __SPEED_SYNC_0108 // ResetDestParam speed 수정 void AddSetPointParam( CMover* pMover, int nDstParameter, int nValue ); void AddSetPos( CCtrl* pCtrl, D3DXVECTOR3 & vPos ); void AddSetPosAngle( CCtrl* pCtrl, const D3DXVECTOR3 &vPos, FLOAT fAngle ); void AddSetLevel( CMover* pMover, WORD wLevel ); void AddSetFlightLevel( CMover* pMover, int nFlightLv ); void AddSetSkillLevel( CMover* pMover, DWORD dwSkill, DWORD dwLevel ); void AddSetScale( CMover* pMover, float fScalePercent ); void AddWorldShout( const TCHAR* szName, const TCHAR* szShout, D3DXVECTOR3 vPos, CWorld* pWorld ); void AddSetSkillState( CMover* pCenter, CMover *pTarget, WORD wType, WORD wID, DWORD dwLevel, DWORD dwTime ); void AddShipActMsg( CMover* pMover, CShip *pShip, DWORD dwMsg, int nParam1, int nParam2 ); void AddMeleeAttack( CMover* pMover, DWORD dwAtkMsg, OBJID objid, int nParam2, int nParam3 ); void AddMeleeAttack2( CMover* pMover, DWORD dwAtkMsg, OBJID objid, int nParam2, int nParam3 ); void AddMagicAttack( CMover* pMover, DWORD dwAtkMsg, OBJID objid, int nParam2, int nParam3, int nMagicPower, int idSfxHit ); void AddRangeAttack( CMover* pMover, DWORD dwAtkMsg, OBJID objid, int nParam2, int nParam3, int idSfxHit ); void AddAttackSP( CMover* pMover, DWORD dwAtkMsg, OBJID objid, int nParam2, int nParam3 ); void AddSetDestAngle( CMover* pMover, float fAngle, BYTE fLeft ); void AddMoverSetDestObj( CMover* pMover, OBJID objid, float fRange = 0.0f, BOOL fTransferToMe = FALSE ); void AddMoverDeath( CMover* pMover, CMover* pAttacker, DWORD dwMsg ); void AddSetMovePattern( CMover* pMover, int nPattern, const D3DXVECTOR3 &vPos, FLOAT fAngle, FLOAT fAngleX ); void AddMoverBehavior2( CMover* pMover, D3DXVECTOR3 & v, D3DXVECTOR3 &vd, float f, float fAngleX, float fAccPower, float fTurnAngle, DWORD dwState, DWORD dwStateFlag, DWORD dwMotion, int nMotionEx, int nLoop, DWORD dwMotionOption, __int64 nTickCount, BOOL fTransferToMe = FALSE ); void AddCreateSfxAllow( CMover *pMover, DWORD dwSfxObjArrow, DWORD dwSfxObjHit, D3DXVECTOR3 vPosDest, int idTarget ); void AddCreateSfxObj( CCtrl* pCtrl, DWORD dwSfxObj, float x = 0, float y = 0, float z = 0, BOOL bFlag = FALSE ); #if __VER >= 11 // __MA_VER11_06 // 확율스킬 효과수정 world,neuz void AddRemoveSfxObj( CCtrl* pCtrl, DWORD dwSfxObj, float x = 0, float y = 0, float z = 0, BOOL bFlag = FALSE ); #endif // __MA_VER11_06 // 확율스킬 효과수정 world,neuz void AddNearSetChangeJob( CMover* pMover, int nJob, LPSKILL lpSkill ); void AddModifyMode( CUser* pUser ); void AddStateMode( CUser* pUser, BYTE nFlag ); #if __VER < 8 // __S8_PK void AddSetSlaughterPoint( CMover* pMover, int nVal, int nNumKill ); #endif // __VER < 8 // __S8_PK void AddSetFame( CMover* pMover, int nFame ); void AddDefinedText( CMover* pMover, int dwText, LPCSTR lpszFormat, ... ); void AddBlock( LPBYTE lpBlock, u_long uBlockSize ); void AddBlock( LPBYTE lpBlock, u_long uBlockSize, CWorld* pWorld ); void AddBlock( CWorld* pWorld, const D3DXVECTOR3 & vPos, int nRange, LPBYTE lpBlock, u_long uBlockSize ); void AddPVendorOpen( CUser* pUser ); void AddPVendorClose( CUser* pUser ); #if __VER >= 11 // __MOD_VENDOR void AddPVendorItemNum( CUser* pUser, BYTE nItem, short nVend, const char* sBuyer ); #else // __MOD_VENDOR void AddPVendorItemNum( CUser* pUser, BYTE nItem, short nVend ); #endif // __MOD_VENDOR void AddSetHair( CUser* pUser, BYTE nHair, BYTE r, BYTE g, BYTE b ); void AddDoCollect( CUser* pUser, OBJID idTarget ); void AddCreateSkillEffect( CMover *pAttacker, OBJID idTarget, DWORD dwSkill, DWORD dwLevel ); void AddSetStun( CMover *pMover, int nMaxTime ); void AddSendActMsg( CMover *pMover, OBJMSG dwMsg, int nParam1 = 0, int nParam2 = 0, int nParam3 = 0 ); void AddPushPower( CMover *pMover, D3DXVECTOR3 vPos, FLOAT fAngle, FLOAT fPushAngle, FLOAT fPower ); void AddRemoveSkillInfluence( CMover *pMover, WORD wType, WORD wID ); void AddDoApplySkill( CCtrl *pCtrl, OBJID idTarget, DWORD dwSkill, DWORD dwLevel ); void AddWorldCreateSfxObj( DWORD dwSfxObj, float x, float y, float z, BOOL bFlag, DWORD dwWorldId ); void AddMoverMoved( CMover* pMover, D3DXVECTOR3 & v, D3DXVECTOR3 &vd, float f, DWORD dwState, DWORD dwStateFlag, DWORD dwMotion, int nMotionEx, int nLoop, DWORD dwMotionOption, __int64 nTickCount ); void AddMoverBehavior( CMover* pMover, D3DXVECTOR3 & v, D3DXVECTOR3 &vd, float f, DWORD dwState, DWORD dwStateFlag, DWORD dwMotion, int nMotionEx, int nLoop, DWORD dwMotionOption, __int64 nTickCount, BOOL fTransferToMe = FALSE ); void AddMoverMoved2( CMover* pMover, D3DXVECTOR3 & v, D3DXVECTOR3 &vd, float f, float fAngleX, float fAccPower, float fTurnAngle, DWORD dwState, DWORD dwStateFlag, DWORD dwMotion, int nMotionEx, int nLoop, DWORD dwMotionOption, __int64 nTickCount, BYTE nFrame = MAX_CORR_SIZE_150 ); void AddUseSkill( CMover* pMover, DWORD dwSkill, DWORD dwLevel, OBJID objid, int nUseType, int nCastingTime ); void AddEventMessage( CCtrl* pCtrl, const TCHAR* szChat, int nFlag, DWORD dwItemId = 0); void AddMotion( CMover* pMover, DWORD dwMsg ); void AddRemoveAllSkillInfluence( CMover* pMover ); void AddMoverAngle( CMover* pMover, D3DXVECTOR3 & v, D3DXVECTOR3 & vd, float f, float fAngleX, float fAccPower, float fTurnAngle, __int64 nTickCount ); void AddMoverCorr( CMover* pMover, D3DXVECTOR3 & v, D3DXVECTOR3 &vd, float f, DWORD dwState, DWORD dwStateFlag, DWORD dwMotion, int nMotionEx, int nLoop, DWORD dwMotionOption, __int64 nTickCount ); void AddMoverCorr2( CMover* pMover, D3DXVECTOR3 & v, D3DXVECTOR3 &vd, float f, float fAngleX, float fAccPower, float fTurnAngle, DWORD dwState, DWORD dwStateFlag, DWORD dwMotion, int nMotionEx, int nLoop, DWORD dwMotionOption, __int64 nTickCount ); void AddCreateGuild( u_long idPlayer, const char* lpszPlayer, u_long idGuild, const char* szGuild ); void AddDestroyGuild( const char* lpszPlayer, u_long idGuild ); void AddSetGuild( CUser* pUser, u_long idGuild ); void AddSetLogo( u_long idGuild, DWORD dwLogo ); void AddGetItemElem( CUser* pUser, CItemElem* pItemElem ); void AddPutItemElem( CUser* pUser, CItemElem* pItemElem ); #if __VER >= 8 // __GUILDCOMBAT_85 void AddPutItemElem( u_long uidGuild, CItemElem* pItemElem ); #endif // __VER >= 8 void AddSetWar( CUser* pUser, u_long idWar ); void ModifyMode( DWORD dwMode ); void AddSchoolReport( PSCHOOL_ENTRY pSchool, short nElapse = 0 ); void AddSexChange( CMover* pMover ); void AddSetLocalEvent( short id, BYTE nState ); void AddGameRate( FLOAT fRate, BYTE nFlag ); void AddChangeFace( u_long uidPlayer, DWORD dwFace ); #if __VER >= 13 void AddShout( CUser* pUserSrc, int nRange, LPBYTE lpBlock, u_long uBlockSize ); #else // __VER >= 13 void AddShout( const D3DXVECTOR3 & vPos, int nRange, LPBYTE lpBlock, u_long uBlockSize ); #endif // __VER >= 13 void AddWorldMsg( const CRect* pRect, LPCTSTR lpszString ); void AddGameSetting(); void AddCommonPlace( CCtrl* pCtrl, BYTE nType ); void OutputStatistics( void ); void AddGuildCombatNextTimeWorld( DWORD dwTime, DWORD dwState ); void AddGuildCombatState( void ); void AddGuildCombatUserState( CMover* pMover ); #ifdef __LAYER_1015 void ReplaceWorld( DWORD dwWorldId, DWORD dwReplaceWorldId, float fReplaceX, float fReplaceZ, int nLayer ); void ReplaceWorldArea( u_long idParty, DWORD dwWorldId, DWORD dwReplaceWorldId, float fReplaceX, float fReplaceZ, float fArea, BOOL bDieFlag, int nLayer ); #else // __LAYER_1015 void ReplaceWorld( DWORD dwWorldId, DWORD dwReplaceWorldId, float fReplaceX, float fReplaceZ ); void ReplaceWorldArea( u_long idParty, DWORD dwWorldId, DWORD dwReplaceWorldId, float fReplaceX, float fReplaceZ, float fArea, BOOL bDieFlag ); #endif // __LAYER_1015 void AddWorldMsg( DWORD dwWorldId, LPCTSTR lpszString ); void AddGCGuildStatus( u_long uidGuild, CUser* pSendUser = NULL ); void AddGCGuildPrecedence( CUser* pSendUser = NULL ); void AddGCPlayerPrecedence( CUser* pSendUser = NULL ); void AddGCWinGuild( void ); void AddGCBestPlayer( void ); void AddGCWarPlayerlist( u_long uidGuild = 0, CUser* pSendUser = NULL ); void AddGuildCombatEnterTime( DWORD dwTime ); void AddGCLogWorld( void ); void AddGCLogRealTimeWorld( CGuildCombat::__GCGETPOINT GCGetPoint ); void AddGCIsRequest( u_long uidGuild, BOOL bRequest ); void AddBlockNoLock( LPBYTE lpBlock, u_long uBlockSize ); void AddBlockNoLock( LPBYTE lpBlock, u_long uBlockSize, CWorld* pWorld ); void AddGuildMsg( u_long idGuild, LPCSTR lpsz ); void AddGuildMsg( CGuild* pGuild, LPCSTR lpsz ); #ifdef __S1108_BACK_END_SYSTEM void AddMonsterProp( ); void AddGMChat( int nSize ); #endif // __S1108_BACK_END_SYSTEM void AddMotionArrive( CMover* pMover, OBJMSG objmsg ); #if __VER >= 8 // __S8_PK void AddPKPink( CMover* pMover, BYTE byPink ); void AddPKPropensity( CMover* pMover ); #endif // __VER >= 8 // __S8_PK #ifdef __IAOBJ0622 void AddSetDestPos( CMover* pMover, CONST D3DXVECTOR3 & vPos, BYTE fForward, OBJID objidIAObj = NULL_ID ); #else // __IAOBJ0622 void AddSetDestPos( CMover* pMover, CONST D3DXVECTOR3 & vPos, BYTE fForward ); #endif // __IAOBJ0622 void AddAddRegion( DWORD dwWorldId, REGIONELEM & re ); #ifdef __EVENT_1101 void CallTheRoll( int nBit ); #endif // __EVENT_1101 #if __VER >= 9 // __PET_0410 #ifdef __PET_1024 void AddPetCall( CMover* pMover, DWORD dwPetId, DWORD dwIndex, BYTE nPetLevel, const char* szPetName ); void AddSetPetName( CUser* pUser, const char* szPetName ); #else // __PET_1024 void AddPetCall( CMover* pMover, DWORD dwPetId, DWORD dwIndex, BYTE nPetLevel ); #endif // __PET_1024 void AddPetRelease( CMover* pMover ); void AddPetLevelup( CMover* pMover, DWORD dwPetId ); void AddPetFeed( CMover* pMover, WORD wEnergy ); #endif // __PET_0410 #if __VER >= 13 // __HONORABLE_TITLE // 달인 void AddHonorTitleChange( CMover* pMover, int nChange ); #endif // __HONORABLE_TITLE // 달인 #if __VER >= 9 //__AI_0509 void AddSetSpeedFactor( CMover* pMover, FLOAT fSpeedFactor ); #endif // __AI_0509 #if __VER >= 9 // __EVENTLUA void AddEventLua( BYTE nId, BOOL bState ); #endif // __EVENTLUA #if __VER >= 12 // __LORD void AddElectionBeginCandidacy( void ); void AddElectionBeginVote( int nRequirement ); void AddElectionEndVote( u_long idPlayer ); void AddElectionAddDeposit( u_long idPlayer, __int64 iDeposit, time_t tCreate ); void AddElectionSetPledge( u_long idPlayer, const char* szPledge ); void AddElectionIncVote( u_long idPlayer, u_long idElector ); void AddLEventCreate( CLEComponent* pComponent ); void AddLEventInitialize( void ); void AddLEventTick( ILordEvent* pEvent ); void AddLordSkillUse( CUser* pUser, u_long idTarget, int nSkill ); void AddQueryPlayerData( u_long idPlayer ); #endif // __LORD #if __VER >= 12 // __TAX void AddTaxInfo( void ); #endif // __TAX #if __VER >= 13 // __HOUSING void AddHousingPaperingInfo( DWORD dwItemId, BOOL bSetup, DWORD dwMasterId ); #endif // __HOUSING #ifdef __VTN_TIMELIMIT void ResetAccountPlayTime(); #endif // __VTN_TIMELIMIT #if __VER >= 15 // __PETVIS void AddChangeMoverSfxId( CMover* pMover ); #endif // __PETVIS #if __VER >= 15 // __GUILD_HOUSE BOOL HasUserSameWorldnLayer( CUser* pUserSrc ); #endif // __GUILD_HOUSE //헙쩟斤口 void SandCoupleInfo( CCtrl* pCtrl,BYTE byType, const char* szCouple); }; #endif // __USER_H__
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278", "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 127 ], [ 131, 432 ], [ 435, 885 ], [ 887, 1044 ] ], [ [ 128, 130 ], [ 433, 434 ], [ 886, 886 ] ] ]
949a939616fe9b365a9fe068cced0c217edce242
3ecc6321b39e2aedb14cb1834693feea24e0896f
/src/model_g3d.cpp
8c1060c603d2a8b96789212f8d4493305e734bc5
[]
no_license
weimingtom/forget3d
8c1d03aa60ffd87910e340816d167c6eb537586c
27894f5cf519ff597853c24c311d67c7ce0aaebb
refs/heads/master
2021-01-10T02:14:36.699870
2011-06-24T06:21:14
2011-06-24T06:21:14
43,621,966
1
1
null
null
null
null
UTF-8
C++
false
false
7,996
cpp
/***************************************************************************** * Copyright (C) 2009 The Forget3D Project by Martin Foo ([email protected]) * ALL RIGHTS RESERVED * * License I * Permission to use, copy, modify, and distribute this software for * any purpose and WITHOUT a fee is granted under following requirements: * - You make no money using this software. * - The authors and/or this software is credited in your software or any * work based on this software. * * Licence II * Permission to use, copy, modify, and distribute this software for * any purpose and WITH a fee is granted under following requirements: * - As soon as you make money using this software, you have to pay a * licence fee. Until this point of time, you can use this software * without a fee. * Please contact Martin Foo ([email protected]) for further details. * - The authors and/or this software is credited in your software or any * work based on this software. * * THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS" * AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE, * INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR * FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHORS * BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT, SPECIAL, INCIDENTAL, * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER, * INCLUDING WITHOUT LIMITATION, LOSS OF PROFIT, LOSS OF USE, SAVINGS OR * REVENUE, OR THE CLAIMS OF THIRD PARTIES, WHETHER OR NOT THE AUTHORS HAVE * BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE * POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE. *****************************************************************************/ #include "model_g3d.h" namespace F3D { /** * ModelG3D class for all games using F3D. * G3D is glest(http://www.glest.org/) 3D model */ ModelG3D::ModelG3D() : m_g3dMeshs(NULL), m_frameIdx(0), m_frameCount(0), m_isPrepared(GL_FALSE) { #ifdef DEBUG printf("ModelG3D constructor...\n"); #endif } ModelG3D::~ModelG3D() { delete [] m_g3dMeshs; #ifdef DEBUG printf("ModelG3D destructor...\n"); #endif } bool ModelG3D::loadModel(const char *filename, GLboolean is_absPath) { FILE *file; file = fopen(Utils::getFileName(filename, is_absPath), "rb"); if (!file) return false; /* initialize model and read header */ fread (&m_header, sizeof (g3d_header_t), 1, file); #ifdef DEBUG printf ("magic:%s\n", m_header.magic); printf ("version:%d\n", m_header.version); printf ("meshCount:%d\n", m_header.meshCount); printf ("type:%d\n", m_header.type); #endif if (!strcmp((char *)m_header.magic, "G3D") || m_header.version != 4) { printf("Invalid G3D model or unsupport version, magic:[%s], version[%d]...\n", m_header.magic, m_header.version); fclose(file); return false; } setMeshCount(m_header.meshCount); m_g3dMeshs = new g3d_mesh_t[m_meshCount]; for (GLushort i = 0; i < m_header.meshCount; i++) { fread(&m_g3dMeshs[i].header, sizeof(g3d_mesh_header_t), 1, file); #ifdef DEBUG printf ("Mesh[%d] name:%s\n", i, m_g3dMeshs[i].header.name); printf ("Mesh[%d] frameCount:%d\n", i, m_g3dMeshs[i].header.frameCount); printf ("Mesh[%d] vertexCount:%d\n", i, m_g3dMeshs[i].header.vertexCount); printf ("Mesh[%d] indexCount:%d\n", i, m_g3dMeshs[i].header.indexCount); printf ("Mesh[%d] textures:%d\n", i, m_g3dMeshs[i].header.textures); #endif //read textures for (GLushort j = 0; j < m_g3dMeshs[i].header.textures; j++) { char texName[G3D_NAME_SIZE]; fread(texName, G3D_NAME_SIZE, 1, file); #ifdef DEBUG printf ("Mesh[%d] textures[%d]:%s\n", i, j, texName); #endif } int frameCount = m_g3dMeshs[i].header.frameCount; int vertexCount = m_g3dMeshs[i].header.vertexCount; int indicesCount = m_g3dMeshs[i].header.indexCount; int v_size = frameCount * vertexCount * sizeof(Vec3f); int u_size = vertexCount * sizeof(Vec2f); int i_size = indicesCount * sizeof(GLuint); //read mesh all frame vertices m_g3dMeshs[i].vertices = new Vec3f[frameCount * vertexCount]; fread(&m_g3dMeshs[i].vertices[0], v_size, 1, file); //read mesh all frame normals m_g3dMeshs[i].normals = new Vec3f[frameCount * vertexCount]; fread(&m_g3dMeshs[i].normals[0], v_size, 1, file); //read all uvs if model have textures if (m_g3dMeshs[i].header.textures > 0) { m_g3dMeshs[i].uvs = new Vec2f[vertexCount]; fread(&m_g3dMeshs[i].uvs[0], u_size, 1, file); } //read mesh all frame indices m_g3dMeshs[i].indices = new GLuint[indicesCount]; fread(&m_g3dMeshs[i].indices[0], i_size, 1, file); setTriangleNums(indicesCount / 3, i); } fclose(file); m_frameCount = m_g3dMeshs[0].header.frameCount; m_frameIdx = 0; //set uvs for (int k = 0; k < m_meshCount; k++) { int indicesCount = m_g3dMeshs[k].header.indexCount; int u_size = indicesCount * sizeof(Vec2f); float *uvs = (float *) malloc(u_size); int u_idx = 0; for (int j = 0; j < indicesCount; j++) { int i_idx = m_g3dMeshs[k].indices[j]; uvs[u_idx++] = m_g3dMeshs[k].uvs[i_idx].s; uvs[u_idx++] = m_g3dMeshs[k].uvs[i_idx].t; } setUvs(uvs, u_size, k); FREEANDNULL(uvs); } return true; } void ModelG3D::prepareFrame() { #ifdef DEBUG static bool isFirst = true; if (isFirst) { printf("Call ModelG3D::prepareFrame()...\n"); isFirst = false; } #endif if (m_frameCount == 1 && m_isPrepared) { #ifdef DEBUG printf("Only one frame, don't need prepare again...\n"); #endif return; } if (!m_isPrepared) m_isPrepared = GL_TRUE; //read all g3d meshs and copy data to model meshs for (int i = 0; i < m_meshCount; i++) { int vertexCount = m_g3dMeshs[i].header.vertexCount; int indicesCount = m_g3dMeshs[i].header.indexCount; int v_size = indicesCount * sizeof(Vec3f); float *vertices = (float *) malloc(v_size); float *normals = (float *) malloc(v_size); int v_idx = 0, n_idx = 0; for (int j = 0; j < indicesCount; j++) { int i_idx = vertexCount * m_frameIdx + m_g3dMeshs[i].indices[j]; vertices[v_idx++] = m_g3dMeshs[i].vertices[i_idx].x; vertices[v_idx++] = m_g3dMeshs[i].vertices[i_idx].y; vertices[v_idx++] = m_g3dMeshs[i].vertices[i_idx].z; normals[n_idx++] = m_g3dMeshs[i].normals[i_idx].x; normals[n_idx++] = m_g3dMeshs[i].normals[i_idx].y; normals[n_idx++] = m_g3dMeshs[i].normals[i_idx].z; } setVertices(vertices, v_size, i); setNormals(normals, v_size, i); FREEANDNULL(vertices); FREEANDNULL(normals); } m_frameIdx++; if (m_frameIdx >= m_frameCount) m_frameIdx = m_isLooped ? 0 : m_frameCount - 1; } }
[ "i25ffz@8907dee8-4f14-11de-b25e-a75f7371a613" ]
[ [ [ 1, 208 ] ] ]
476e384533b2ceb76a26c7a5be8307edfcac87ff
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Physics/Collide/Agent/Deprecated/ConvexList/hkpConvexListUtils.h
8bd679883c4b36974b52e9ef8d8d8ea3f12e09de
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
7,444
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_COLLIDE2_CONVEX_LIST_SHARED_HELPERS_H #define HK_COLLIDE2_CONVEX_LIST_SHARED_HELPERS_H #include <Physics/Collide/Shape/Compound/Collection/hkpShapeCollection.h> #include <Physics/Collide/Shape/Deprecated/ConvexList/hkpConvexListShape.h> // File info: this file is shared by the hkpConvexListAgent & hkConvexListAgent3 // C4701: local variable 'output' may be used without having been initialized # pragma warning(push) # pragma warning(disable: 4701) struct hkpProcessCollisionOutputBackup { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_COLLIDE, hkpProcessCollisionOutputBackup ); hkpProcessCollisionOutputBackup( const hkpProcessCollisionOutput& output ) { m_firstPoint = output.m_firstFreeContactPoint; m_toi = output.m_toi; #if defined(HK_1N_MACHINE_SUPPORTS_WELDING) if ( output.m_potentialContacts ) { m_weldingInformation = *output.m_potentialContacts; } #endif } inline void rollbackOutput( const hkpCdBody& bodyA, const hkpCdBody& bodyB, hkpProcessCollisionOutput& output, hkpContactMgr* mgr ) { if ( output.m_toi.m_time != m_toi.m_time ) { mgr->removeToi( *output.m_constraintOwner.val(), output.m_toi.m_properties ); output.m_toi = m_toi; } output.m_firstFreeContactPoint = m_firstPoint; #if defined(HK_1N_MACHINE_SUPPORTS_WELDING) if ( output.m_potentialContacts ) { *output.m_potentialContacts = m_weldingInformation; } #endif } hkpProcessCdPoint* m_firstPoint; hkpProcessCollisionOutput::PotentialInfo m_weldingInformation; hkpProcessCollisionOutput::ToiInfo m_toi; }; class hkpMapPointsToSubShapeContactMgr : public hkpContactMgr { public: hkpMapPointsToSubShapeContactMgr( hkpContactMgr* mgr ): hkpContactMgr( hkpContactMgr::TYPE_CONVEX_LIST_CONTACT_MGR ) { m_contactMgr = mgr; m_invalidPointHit = false; } hkContactPointId addContactPointImpl( const hkpCdBody& a, const hkpCdBody& b, const hkpProcessCollisionInput& input, hkpProcessCollisionOutput& output, const hkpGskCache* contactCache, hkContactPoint& cp ) { const hkpCdBody* aMod = &a; const hkpCdBody* bMod = &b; hkpCdBody aTemp; hkpCdBody bTemp; if (a.getShape()->getType() == HK_SHAPE_CONVEX_LIST ) { int shapeKey = ( 0xff00 & contactCache->m_vertices[0] ) >> 8; for (int i = 1; i < contactCache->m_dimA; ++i) { int shapeKey2 = ( 0xff00 & contactCache->m_vertices[i] ) >> 8; if ( shapeKey2 != shapeKey ) { m_invalidPointHit = true; return HK_INVALID_CONTACT_POINT; } } hkpShapeBuffer buffer; const hkpShape* childShape = static_cast<const hkpConvexListShape*>(a.getShape())->getChildShape(shapeKey, buffer); new (&aTemp) hkpCdBody(&a); aTemp.setShape( childShape, shapeKey ); aMod = &aTemp; } if (b.getShape()->getType() == HK_SHAPE_CONVEX_LIST ) { int shapeKey = (0xff00 & contactCache->m_vertices[contactCache->m_dimA]) >> 8; for (int i = contactCache->m_dimA + 1; i < contactCache->m_dimA + contactCache->m_dimB; ++i) { int shapeKey2 = (0xff00 & contactCache->m_vertices[i]) >> 8; if ( shapeKey2 != shapeKey ) { m_invalidPointHit = true; return HK_INVALID_CONTACT_POINT; } } hkpShapeBuffer buffer; const hkpShape* childShape = static_cast<const hkpConvexListShape*>(b.getShape())->getChildShape(shapeKey, buffer); new (&bTemp) hkpCdBody(&b); bTemp.setShape( childShape, shapeKey ); bMod = &bTemp; } return m_contactMgr->addContactPoint( *aMod, *bMod, input, output, contactCache, cp ); } hkResult reserveContactPointsImpl( int numPoints ) { return m_contactMgr->reserveContactPoints( numPoints ); } void removeContactPointImpl( hkContactPointId cpId, hkCollisionConstraintOwner& constraintOwner ) { m_contactMgr->removeContactPoint( cpId, constraintOwner ); } void processContactImpl( const hkpCollidable& a, const hkpCollidable& b, const hkpProcessCollisionInput& input, hkpProcessCollisionData& collisionData ) { m_contactMgr->processContact( a, b, input, collisionData ); } void cleanup() { m_contactMgr->cleanup(); } ToiAccept addToiImpl( const hkpCdBody& a, const hkpCdBody& b, const hkpProcessCollisionInput& input, hkpProcessCollisionOutput& output, hkTime toi, hkContactPoint& cp, const hkpGskCache* gskCache, hkReal& projectedVelocity, hkpContactPointProperties& propertiesOut ) { const hkpCdBody* aMod = &a; const hkpCdBody* bMod = &b; hkpCdBody aTemp; hkpCdBody bTemp; if (a.getShape()->getType() == HK_SHAPE_CONVEX_LIST ) { int shapeKey = ( 0xff00 & gskCache->m_vertices[0] ) >> 8; for (int i = 1; i < gskCache->m_dimA; ++i) { int shapeKey2 = ( 0xff00 & gskCache->m_vertices[i] ) >> 8; if ( shapeKey2 != shapeKey ) { m_invalidPointHit = true; return TOI_REJECT; } } hkpShapeBuffer buffer; const hkpShape* childShape = static_cast<const hkpConvexListShape*>(a.getShape())->getChildShape(shapeKey, buffer); new (&aTemp) hkpCdBody(&a); aTemp.setShape( childShape, shapeKey ); aMod = &aTemp; } if (b.getShape()->getType() == HK_SHAPE_CONVEX_LIST ) { int shapeKey = ( 0xff00 & gskCache->m_vertices[gskCache->m_dimA] ) >> 8; for (int i = gskCache->m_dimA + 1; i < gskCache->m_dimA + gskCache->m_dimB; ++i) { int shapeKey2 = ( 0xff00 & gskCache->m_vertices[i] ) >> 8; if ( shapeKey2 != shapeKey ) { m_invalidPointHit = true; return TOI_REJECT; } } hkpShapeBuffer buffer; const hkpShape* childShape = static_cast<const hkpConvexListShape*>(b.getShape())->getChildShape(shapeKey, buffer); new (&bTemp) hkpCdBody(&b); bTemp.setShape( childShape, shapeKey ); bMod = &bTemp; } return m_contactMgr->addToi( *aMod, *bMod, input, output, toi, cp, gskCache, projectedVelocity, propertiesOut ); } void removeToiImpl( class hkCollisionConstraintOwner& constraintOwner, hkpContactPointProperties& properties ) { m_contactMgr->removeToi( constraintOwner, properties ); } public: hkpContactMgr* m_contactMgr; hkBool m_invalidPointHit; }; # pragma warning(pop) #endif // HK_COLLIDE2_CONVEX_LIST_SHARED_HELPERS_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222) * * Confidential Information of Havok. (C) Copyright 1999-2009 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ [ [ 1, 220 ] ] ]
e32abd5b3b41fc2986ae91c31934faf374510c27
c63685bfe2d1ecfdfebcda0eab70642f6fcf4634
/SimpleHDRRendering/main.cpp
376335d1f5c4762649bdc8c414abc55deecdcd31
[]
no_license
Shell64/cgdemos
8afa9272cef51e6d0544d672caa0142154e231fc
d34094d372fea0536a5b3a17a861bb1a1bfac8c4
refs/heads/master
2021-01-22T23:26:19.112999
2011-10-13T12:38:10
2011-10-13T12:38:10
35,008,078
1
0
null
null
null
null
UTF-8
C++
false
false
6,283
cpp
#ifndef OEMRESOURCE #define OEMRESOURCE #endif #include <windows.h> //#include <GdiPlus.h> #include <cstdio> #include <GL/gl.h> #include <map> #include "ShaderObject.h" #include "ProgramGLSL.h" #include "GLTexImage.h" #include "resource.h" #include "Controls.h" #define APP_WINDOW_NAME "Jupiter" #define APP_CLASS_NMAE "Jupiter_Class" //using namespace Gdiplus; HWND g_hToolbar = NULL; int current = 0; HWND g_hMainWnd = NULL; HINSTANCE g_hInstance = NULL; DisplayWidget* g_widget[2]; BOOL InitApplication( HINSTANCE hInstance ); BOOL InitInstance( HINSTANCE hInstance, INT nShowCmd ); LRESULT CALLBACK MainWndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ); void ShutDown( void ); void OnFileOpen( void ); int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd ) { BOOL bSuccess = TRUE; MSG msg = { 0 }; /*GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken = NULL;*/ // only one instance is allowed HANDLE appMutex = CreateMutex( NULL, FALSE, "Jupiter" ); if ( ERROR_ALREADY_EXISTS == GetLastError() ) { bSuccess = FALSE; goto exit_func; } //GdiplusStartup( &gdiplusToken, &gdiplusStartupInput, NULL ); if ( !InitApplication( hInstance ) ) { bSuccess = FALSE; goto exit_func; } if ( !InitInstance( hInstance, nShowCmd ) ) { bSuccess = FALSE; goto exit_func; } g_hInstance = hInstance; while( msg.message != WM_QUIT ) { if ( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } else { if ( NULL != g_widget[current] ) g_widget[current]->Display(); current = ( current + 1 ) % 2; } } exit_func: /*if ( gdiplusToken ) { GdiplusShutdown( gdiplusToken ); }*/ CloseHandle( appMutex ); if ( bSuccess ) { return int( msg.wParam ); } return 0; } BOOL InitApplication( HINSTANCE hInstance ) { BOOL bSuccess = TRUE; WNDCLASS wndClass = { 0 }; wndClass.style = 0; wndClass.lpfnWndProc = MainWndProc; wndClass.cbClsExtra = 0; wndClass.cbWndExtra = 0; wndClass.hInstance = hInstance; wndClass.hIcon = LoadIcon( hInstance, TEXT( "BlackLeaf" ) ); wndClass.hCursor = LoadCursor( NULL, IDC_ARROW ); wndClass.hbrBackground = (HBRUSH)( COLOR_WINDOW ); wndClass.lpszMenuName = TEXT( "MainMenu" ); wndClass.lpszClassName = TEXT( APP_CLASS_NMAE ); if ( !RegisterClass( &wndClass ) ) { MessageBox( NULL, TEXT( "RegisterClass failed!" ), TEXT( APP_CLASS_NMAE ), MB_ICONERROR ); bSuccess = FALSE; } if ( !InitControls( hInstance ) ) { bSuccess = FALSE; } return bSuccess; } BOOL InitInstance( HINSTANCE hInstance, INT nShowCmd ) { g_hMainWnd = CreateWindow( TEXT( APP_CLASS_NMAE ), TEXT( APP_WINDOW_NAME ), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL ); if ( NULL == g_hMainWnd ) { MessageBox( NULL, "CreateWindow failed", TEXT( APP_CLASS_NMAE ), MB_ICONERROR ); return FALSE; } ShowWindow( g_hMainWnd, nShowCmd ); UpdateWindow( g_hMainWnd ); return TRUE; } void UpdateLayout( HWND hMainWnd ) { /*RECT MWndRect; GetClientRect( hMainWnd, &MWndRect ); RECT DWRect; DWRect.left = 200; DWRect.top = 0; DWRect.right = MWndRect.right; DWRect.bottom = MWndRect.bottom; g_pDisplayWidget->SetPosition( DWRect.left, DWRect.top, DWRect.right - DWRect.left, DWRect.bottom - DWRect.top );*/ } LRESULT CALLBACK ProcessCommand( WPARAM wParam ) { switch ( wParam ) { case IDM_FILE_OPEN: OnFileOpen( ); break; case IDM_FILE_SAVE: break; case IDM_FILE_EXIT: ShutDown(); break; case IDM_TOOLS_MOVE: //g_pDisplayWidget->SetState( DWS_MOVE ); break; case IDM_TOOLS_ZOOM: //g_pDisplayWidget->SetState( DWS_ZOOM ); break; case ID_GEODESICMATTING_FORE: break; case ID_GEODESICMATTING_BACK: break; case ID_GEODESICMATTING_DONE: break; default: break; } return 0; } LRESULT CALLBACK MainWndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { static bool init = false; // Handle some specific messages: switch( msg ) { case WM_PAINT: init = true; break; case WM_CREATE: g_widget[0] = new SceneRender( hWnd ); g_widget[1] = new SceneRender( hWnd ); if ( NULL == g_widget[0] || NULL == g_widget[1] ) { ::PostMessage( hWnd, WM_CLOSE, 0, 0 ); } else { g_widget[0]->Initialize(); g_widget[0]->SetPosition( 10, 10, 600, 600 ); g_widget[1]->Initialize(); g_widget[1]->SetPosition( 620, 10, 600, 600 ); } return 0; case WM_KEYDOWN: //g_pDisplayWidget->KeyDownProc( wParam, lParam ); return 0; case WM_KEYUP: //g_pDisplayWidget->KeyUpProc( wParam, lParam ); return 0; case WM_DESTROY: ::PostQuitMessage(0); return 0; case WM_SIZE: UpdateLayout( hWnd ); break; case WM_CLOSE: ShutDown(); return 0; case WM_COMMAND: ProcessCommand( wParam ); return 0; default: break; } // Forward any other messages we didn't handle // above to the default window procedure. return ::DefWindowProc(hWnd, msg, wParam, lParam); } void ShutDown( void ) { /*if ( NULL != g_pDisplayWidget ) { delete g_pDisplayWidget; g_pDisplayWidget = NULL; }*/ DestroyWindow( g_hMainWnd ); g_hMainWnd = NULL; if ( NULL != g_hToolbar ) { DestroyWindow( g_hToolbar ); g_hToolbar = NULL; } } void OnFileOpen( void ) { TCHAR szFile[ MAX_PATH ] = { 0 }; TCHAR szPath[ MAX_PATH ] = { 0 }; OPENFILENAME ofn = { sizeof ( OPENFILENAME ), NULL, NULL, TEXT("JPG files(*.jpg,*jpeg)\0*.jpg;*.jpeg\0Bitmap Files(*.bmp)\0*.bmp\0Png Files(.png)\0*.png\0All files(*.*)\0*.*\0"), NULL, 0, 1, szFile, MAX_PATH, NULL, 0, szPath, TEXT("Open Image File"), OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST|OFN_HIDEREADONLY, 0, 0, TEXT(".jpg"), 0, NULL, NULL }; if ( TRUE != GetOpenFileName( &ofn ) ) { return; } //Image* hdrImg = ImageManager::get()->getImage( szFile ); //code comes here return; }
[ "hpsoar@6e3944b4-cba9-11de-a8df-5d31f88aefc0" ]
[ [ [ 1, 313 ] ] ]
3a9855245ab7a6b585e21d3d00db400412c9fdb8
7c4e18dc769ebc3b87d6f45d82812984b7eb6608
/source/shapepoint.cpp
5b2b261758242689d472a041d3beae94921611a6
[]
no_license
ishahid/smartmap
5bce0ca5690efb5b8e28c561d86321c8c5dcc794
195b1ebb03cd786d38167d622e7a46c7603e9094
refs/heads/master
2020-03-27T05:43:49.428923
2010-07-06T08:24:59
2010-07-06T08:24:59
10,093,280
0
0
null
null
null
null
UTF-8
C++
false
false
830
cpp
#include "shapepoint.h" ShapePoint::ShapePoint( int id, double x, double y ) { _shapeID = id; _type = 1; point.setXY( x, y ); } QString ShapePoint::coordinates() { QString str; str = " <Point X=\"" + QString::number( point.x(), 'f', 6 ) + "\" " + "Y=\"" + QString::number( point.y(), 'f', 6 ) + "\"/>\n"; return str; } inline void ShapePoint::draw( double sf, QPainter& painter ) { /**************************************************************************************** drawEllipse draws an ellipse with center at (x + w/2, y + h/2) and size (w, h). ****************************************************************************************/ painter.drawEllipse( Convert::degreeToPixelX( point.x(), sf ), Convert::degreeToPixelY( point.y(), sf ), 4, 4 ); }
[ "none@none" ]
[ [ [ 1, 26 ] ] ]
496da6fd1888e8832b6e72ced0741c08175bc3d9
09ea547305ed8be9f8aa0dc6a9d74752d660d05d
/smf/smfservermodule/smfserver/pluginmgr/smfpluginmanager.cpp
52eea777796ab9df06c9d3464d708e1725d03891
[]
no_license
SymbianSource/oss.FCL.sf.mw.socialmobilefw
3c49e1d1ae2db8703e7c6b79a4c951216c9c5019
7020b195cf8d1aad30732868c2ed177e5459b8a8
refs/heads/master
2021-01-13T13:17:24.426946
2010-10-12T09:53:52
2010-10-12T09:53:52
72,676,540
0
0
null
null
null
null
UTF-8
C++
false
false
38,364
cpp
/** * Copyright (c) 2010 Sasken Communication Technologies Ltd. * All rights reserved. * This component and the accompanying materials are made available * under the terms of the "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: * Chandradeep Gandhi, Sasken Communication Technologies Ltd - Initial contribution * * Contributors: * Manasij Roy, Nalina Hariharan * * Description: * The Plugin Manager class manages the loading and unloading of plug-ins * */ #include <QDir> #include <QDebug> #include <QLibraryInfo> #include <QFileSystemWatcher> #include <QPluginLoader> #include <QList> #include <smfpluginbase.h> #include <smfpluginutil.h> #include <smfprovider.h> #include <smfcredmgrclient.h> #include "smfpluginmanager.h" #include "smfpluginmanagerutil.h" #include "smftransportmanagerutil.h" // Static data initialisation SmfPluginManager* SmfPluginManager::m_myInstance = NULL; /** * Method to get the instance of SmfPluginManager class * @param aServer The Smf server instance * @return The instance of SmfPluginManager class */ SmfPluginManager* SmfPluginManager::getInstance ( SmfServer *aServer) { if(NULL == m_myInstance) m_myInstance = new SmfPluginManager(aServer); return m_myInstance; } /** * Constructor with default argument * @param aServer The Smf server instance */ SmfPluginManager::SmfPluginManager ( SmfServer *aServer ) { // Save the server instance m_server = aServer; // initialize the file watcher to monitor plugin addition/upgradation/removal initializeFileWatcher ( ); // create a database to store the folder structure of the path "c://resource//qt//plugins" initializeSmfPluginDataBase ( ); // create teh Plugin Manager utility class instance m_util = new SmfPluginManagerUtil(this); // Get handle to the Transport MAnager utility instance m_transMngrUtil = SmfTransportManagerUtil::getInstance(); } /** * Destructor */ SmfPluginManager::~SmfPluginManager ( ) { qDebug()<<"Inside SmfPluginManager::~SmfPluginManager()"; // delete file watcher if(m_fileWatcher) delete m_fileWatcher; if(m_tempStruct) delete m_tempStruct; // delete the plugin information hash if(m_waitingPluginHash.count() > 0) { foreach(SmfWaitingPluginInfoStruc *str, m_waitingPluginHash.values()) delete str; } // delete the SmfPluginManagerUtil class instance if(m_util) delete m_util; // Close the database if(m_pluginDataBase.isOpen()) { m_pluginDataBase.close(); m_pluginDataBase.removeDatabase("SmfPluginsInfoDatabase"); QFile::remove("SmfPluginsInfoDatabase"); } // unload all loaded plugins unload(m_pluginLoaderHash.keys()); // Finally remove the existing singleton instance of plugin manager itself if(m_myInstance) delete m_myInstance; } /** * Method called by Smf server to create a web query. * Plugin Manager calls the appropriate web query creation method * using the aOperation and aInputData parameters. Once the web request * is ready, it calls the appropriate methods exposed by the Transport * Manager to send the network request. * @param aSessionID The session ID provided by Smf Server * @param aPluginID The plugin ID that need to perform this operation * @param aOperation The type of operation to be performed * @param aInputData The data required to create the web query * @return SmfError The result of the operation. It can be :- * SmfPluginNoError (if the request is sent successfully) or * SmfPluginLoadError (if plugin could not be loaded) or * SmfPluginNotAuthorised (if the plugin is not authorised) or * SmfPluginUnknownPluginService (if the requested service is not known or unsupported) or * SmfPluginRequestCreationFailed (if request creation has failed) or * SmfPluginSOPCheckFailed (if plugins request doesnot comply to the Same Origin Policy) or * SmfPluginRequestSendingFailed (if request could not be sent) or * SmfPluginUnknownHttpService (if the plugin requested any unknown http * method other than get, post, put, head or delete) */ SmfError SmfPluginManager::createRequest ( const quint32& aSessionID, const QString& aPluginID, const SmfRequestTypeID& aOperation, QByteArray& aInputData ) { qDebug()<<"Inside SmfPluginManager::createRequest()"; SmfError result = SmfUnknownError; // Load the plugin QObject *plugin = load(aPluginID, result); // Check if plugin is loaded if(plugin && (SmfNoError == result)) { SmfPluginBase* instance = qobject_cast<SmfPluginBase *>(plugin); if(instance) { QList<QUrl> urlList; SmfPluginRequestData reqData; // check if the plugin is authorised (with CSM) if( authorisePlugin(aPluginID, urlList )) { qDebug()<<"Plugin authorised"; // call the utility method to create plugin specific request result = SmfUnknownError; QByteArray notused; m_util->createRequest(plugin, aOperation, aInputData, reqData, result, notused); // If the request is created successfully, call the TM method to send the request if( SmfNoError == result ) { qDebug()<<"Plugin request creation successful"; m_tempStruct = new SmfWaitingPluginInfoStruc(); m_tempStruct->iSessionID = aSessionID; m_tempStruct->iPluginId = aPluginID; m_tempStruct->iInstance = instance; m_tempStruct->iOperation = aOperation; m_tempStruct->iInputData = aInputData; // send the request sendRequest ( reqData, result, urlList ); } else qDebug()<<"Plugin request creation failed!!!, error = "<<result; } else { // plugin not authorised, so unload qDebug()<<"Plugin not authorised!!!"; unload(instance); result = SmfPMPluginNotAuthorised; } } else { // plugin instance cannot be casted, so unload qDebug()<<"Plugin instance cannot be casted to SmfPluginBase*!!!"; unload(instance); result = SmfPMPluginLoadError; } } else { // plugin not loaded qDebug()<<"Plugin not loaded!!!"; } return result; } /** * Method called by Smf server to create a synchronous plugin request. * @param aPluginID The plugin ID that need to perform this operation * @param aOperation The type of operation to be performed * @param aInputData The data required by the plugins * @param aOutputData [out] The output data to be filled by the plugins * @return SmfError The result of the operation. It can be :- * SmfPluginNoError (if the request is success) or * SmfPluginLoadError (if plugin could not be loaded) or * SmfPluginNotAuthorised (if the plugin is not authorised) or * SmfPluginUnknownPluginService (if the requested service is not known or unsupported) */ SmfError SmfPluginManager::createSyncRequest ( const QString& aPluginID, const SmfRequestTypeID& aOperation, QByteArray& aInputData, QByteArray& aOutputData ) { qDebug()<<"Inside SmfPluginManager::createSyncRequest()"; SmfError result = SmfUnknownError; // Load the plugin QObject *plugin = load(aPluginID, result); // Check if plugin is loaded if(plugin && (SmfNoError == result)) { SmfPluginBase* instance = qobject_cast<SmfPluginBase *>(plugin); if(instance) { QList<QUrl> urlList; SmfPluginRequestData reqData; // check if the plugin is authorised (with CSM) if( authorisePlugin(aPluginID, urlList )) { qDebug()<<"Plugin authorised"; // call the utility method to create plugin specific request result = SmfUnknownError; m_util->createRequest(plugin, aOperation, aInputData, reqData, result, aOutputData ); // If the request is created successfully, call the TM method to send the request if( SmfNoError == result ) qDebug()<<"Plugin request creation successful"; else qDebug()<<"Plugin request creation failed!!!, error = "<<result; } else { // plugin not authorised, so unload qDebug()<<"Plugin not authorised!!!"; unload(instance); result = SmfPMPluginNotAuthorised; } } else { // plugin instance cannot be casted, so unload qDebug()<<"Plugin instance cannot be casted to SmfPluginBase*!!!"; unload(instance); result = SmfPMPluginLoadError; } } else { // plugin not loaded qDebug()<<"Plugin not loaded!!!"; } return result; } /** * Method called by Transport Manager when network response is available * @param aTransportResult The result of Transport Operation * @param aReply The QNetworkReply instance that requested * this transaction * @param aResponse The network response data, may be NULL for error */ void SmfPluginManager::responseAvailable ( const SmfTransportResult &aTransportResult, QNetworkReply *aReply, QByteArray *aResponse ) { qDebug()<<"Inside SmfPluginManager::responseAvailable()"; // get the details of the plugin which made this request SmfWaitingPluginInfoStruc* info = NULL; info = m_waitingPluginHash.value(aReply); if(info) { quint32 sessionId = m_waitingPluginHash.value(aReply)->iSessionID; QString pluginId = m_waitingPluginHash.value(aReply)->iPluginId; SmfRequestTypeID operation = m_waitingPluginHash.value(aReply)->iOperation; QByteArray inputData = m_waitingPluginHash.value(aReply)->iInputData; QVariant result; SmfPluginRetType retType = SmfRequestError; SmfResultPage pageResult; // call the utility method to send response to appropriate plugins SmfError retValue = m_util->responseAvailable( info->iInstance, operation, aTransportResult, aResponse, &result, retType, pageResult ); qDebug()<<"m_util->responseAvailable() return = "<<retValue; // remove the plugin from the waiting list delete m_waitingPluginHash.value(aReply); m_waitingPluginHash.remove(aReply); QByteArray arr; QDataStream stream(&arr, QIODevice::ReadWrite); if( SmfNoError == retValue ) { qDebug()<<"Parsing of response is successful"; // serialize the response to suitable class and pass the data to server serializeResult(operation, &result, stream); // Send the response data to the server m_server->resultsAvailable(sessionId, &arr, retValue); } // Send the request again else if( SmfPMPluginSendRequestAgain == retValue ) { qDebug()<<"Send request again"; retValue = createRequest( sessionId, pluginId, operation, inputData ); } // Error else { qDebug()<<"Plugin responseAvailable() failed!!!, error = "<<retValue; // Error in parsing, sent to server stream<<result.toString(); m_server->resultsAvailable(sessionId, &arr, retValue); } } else qDebug()<<"No outstanding requests for this QNetworkReply!!!"; // delete aReply later, when event loop is re-entered aReply->deleteLater(); } /** * Method to cancel the service request * @param aSessionID The session to be cancelled. * If the plugin is not loaded currently, this method just returns true. * @return Returns true if the plugin operation could be cancelled * else returns false. */ bool SmfPluginManager::cancelRequest ( const quint32& aSessionID ) { bool retValue = true; qDebug()<<"Inside SmfPluginManager::cancelRequest()"; // Get the plugin for which cancel is requested foreach(SmfWaitingPluginInfoStruc* iPluginInfo, m_waitingPluginHash.values()) { if( aSessionID == iPluginInfo->iSessionID ) { qDebug()<<"Plugin to be cancelled found in the waiting list"; // Notify Transport Manager m_transMngrUtil->cancelRequest(m_waitingPluginHash.key(iPluginInfo)); } else retValue = true; } return retValue; } /** * Method called to initialize the file watcher watching the file * system for adition/upgradation/removal of plugins */ void SmfPluginManager::initializeFileWatcher ( ) { qDebug()<<"Inside SmfPluginManager::initializeFileWatcher()"; // Create the file watcher for the plugins in /Smf folder of the Qt plugin directory m_fileWatcher = new QFileSystemWatcher(this); // Get the directory having the Qt plugin stubs QDir dir(QLibraryInfo::location(QLibraryInfo::PluginsPath)); // If Smf folder exists if(dir.cd("smf/plugin")) { // Add each service provider folders to the file watcher foreach(QString folder, dir.entryList(QDir::AllDirs)) { dir.cd(folder); m_fileWatcher->addPath(dir.absolutePath()); dir.cdUp(); } } else m_fileWatcher->addPath(dir.absolutePath()); connect(m_fileWatcher, SIGNAL(directoryChanged(const QString&)), this, SLOT (directoryChanged(const QString&))); connect(m_fileWatcher, SIGNAL(fileChanged(const QString&)), this, SLOT (directoryChanged(const QString&))); } /** * Method called to initialize the database holding the plugin * directory sructure information. This is called only once when * the Plugin Manager is instantiated. * This method creates and updates m_pluginIdPathHash member * of this class * @return Returns true the database is successfully created and updated, * else returns false */ bool SmfPluginManager::initializeSmfPluginDataBase ( ) { qDebug()<<"Inside SmfPluginManager::initializeSmfPluginDataBase()"; // Find QSQLite driver and create a connection to database QFile::remove("SmfPluginsInfoDatabase"); m_pluginDataBase = QSqlDatabase::addDatabase("QSQLITE"); m_pluginDataBase.setDatabaseName("SmfPluginsInfoDatabase"); // Open the database bool opened = m_pluginDataBase.open(); if(!opened) { qDebug()<<"Database could not be opened, returning !!!"; return false; } #ifdef DETAILEDDEBUGGING qDebug()<<"Database opened"; #endif // Create a query to create the DB table for Plugin Manager (if it doesn't exists) QSqlQuery query; bool tableCreated = false; tableCreated = query.exec("CREATE TABLE IF NOT EXISTS pluginDetails (" "pluginId TEXT PRIMARY KEY, interfaceName TEXT, serviceProvider TEXT, " "description TEXT, serviceUrl TEXT, authAppId TEXT, authAppName TEXT)"); // Error - table not created, Plugin Manager might not work properly if(!tableCreated) { qDebug()<<"Table not created!!!, error = "<<query.lastError().text(); // Close the database m_pluginDataBase.close(); return false; } #ifdef DETAILEDDEBUGGING qDebug()<<"Table created"; #endif // Get the directory having the Qt plugin stubs QDir dir(QLibraryInfo::location(QLibraryInfo::PluginsPath)); // If Smf folder exists if(dir.cd("smf/plugin")) { #ifdef DETAILEDDEBUGGING qDebug()<<"Smf/plugin folder exists"; #endif // Get each interface folders names foreach(QString intfName, dir.entryList(QDir::AllDirs)) { dir.cd(intfName); #ifdef DETAILEDDEBUGGING qDebug()<<"Interface name : "<<dir.dirName(); #endif // Get each plugin in this folder foreach(QString pluginName, dir.entryList(QDir::Files)) { #ifdef DETAILEDDEBUGGING qDebug()<<"plugins for this Interface : "<<pluginName; #endif // load this plugin QPluginLoader pluginLoader(dir.absoluteFilePath(pluginName)); QObject *instance = pluginLoader.instance(); if (instance) { #ifdef DETAILEDDEBUGGING qDebug()<<"instance found"; #endif SmfPluginBase* plugin = qobject_cast<SmfPluginBase *>(instance); if (plugin) { #ifdef DETAILEDDEBUGGING qDebug()<<"SmfPluginBase found"; #endif plugin->initialize(); // get the plugin id QString id = plugin->getProviderInfo()->pluginId(); // get the interface implemented by the plugin QString intfImplemented = dir.dirName(); intfImplemented.prepend("org.symbian.smf.plugin."); #ifdef DETAILEDDEBUGGING qDebug()<<"intfImplemented = "<<intfImplemented; #endif // get the service provider QString serProv = plugin->getProviderInfo()->serviceName(); //get the description QString desc = plugin->getProviderInfo()->description(); // get the service URL QString servURL = plugin->getProviderInfo()->serviceUrl().toString(); // get the auth application process name QString authAppName = plugin->getProviderInfo()->authenticationAppName(); // get the authentication application id QString str; QStringList list; QString authAppId = plugin->getProviderInfo()->authenticationApp( str, list, QIODevice::ReadWrite); // Update m_pluginIdPathHash m_pluginIdPathHash.insert(id, dir.absoluteFilePath(pluginName)); QSqlQuery rowInsertQuery; // insert into database bool rowInserted = rowInsertQuery.exec(QString("INSERT INTO pluginDetails VALUES (" "'%1', '%2', '%3', '%4', '%5', '%6', '%7')").arg(id).arg(intfImplemented) .arg(serProv).arg(desc).arg(servURL).arg(authAppId).arg(authAppName)); if(rowInserted) qDebug()<<QString("This Plugin's information is added to database : '%1' '%2' '%3' '%4'") .arg(id).arg(intfImplemented).arg(serProv).arg(authAppId); else { qDebug()<<"Data base insert statement returned = "<<rowInserted; if(0 != query.lastError().text().size()) qDebug()<<"plugins data not written to database!!!, error = "<<query.lastError().text(); } } else { qDebug()<<"Plugin could not be converted to SmfpluginBase* - returning!!!"; // Close the database m_pluginDataBase.close(); return false; } pluginLoader.unload(); } else { qDebug()<<"Plugin could not be loaded - returning!!!, error = "<<pluginLoader.errorString(); // Close the database m_pluginDataBase.close(); return false; } } dir.cdUp(); } } else { qDebug()<<"No Smf plugins installed!!!"; return false; } // Close the database m_pluginDataBase.close(); return true; } /** * Method to load a plugin using its Plugin Id. * @param aPluginId The unique ID of the plugin * @param aLoadResult [out] Output paramater indicating the result * of the loading. It can be:- * SmfPluginNoError (if plugin was loaded successfully) or * SmfPluginNotFound (if plugin with the given id could not be found) * SmfPluginNotLoaded (if plugin could not be loaded) or * @return The instance of the loaded plugin if loaded, else NULL */ QObject* SmfPluginManager::load ( const QString &aPluginId, SmfError &aLoadResult) { qDebug()<<"Inside SmfPluginManager::load()"; // Find the plugin Path QString pluginPath = m_pluginIdPathHash.value(aPluginId); if(!pluginPath.isEmpty()) { // create the plugin loader and load the plugin QPluginLoader *pluginLoader = NULL; pluginLoader = new QPluginLoader(pluginPath); if(!pluginLoader) { // Plugin loader could not be created, error qDebug()<<"QPluginLoader allocation failed!!!"; aLoadResult = SmfPMPluginNotLoaded; return NULL; } SmfPluginBase *plugin = qobject_cast<SmfPluginBase *>(pluginLoader->instance()); // If the plugin is loaded if( pluginLoader->isLoaded() && plugin ) { // Initialize the plugin plugin->initialize(); // update the plugin loader and the loaded plugin lists m_pluginLoaderHash.insertMulti(plugin, pluginLoader); aLoadResult = SmfNoError; qDebug()<<"Plugin loaded"; return pluginLoader->instance(); } else { // Plugin could not be loaded, error qDebug()<<"Plugin not loaded!!!, error = "<<pluginLoader->errorString(); aLoadResult = SmfPMPluginNotLoaded; return NULL; } } else { // plugin could not be found in the hash maintained by PM qDebug()<<"Plugin not found!!!"; aLoadResult = SmfPMPluginNotFound; return NULL; } } /** * Method to unload a loaded plugin. Returns true if success, else * returns false. * @param aPlugin The plugin instance to be unloaded * @return Returns true if the mentioned plugin could be unloaded. Returns * false, if the plugin instance is NULL, or if it could not be unloaded. */ bool SmfPluginManager::unload ( SmfPluginBase *aPlugin ) { qDebug()<<"Inside SmfPluginManager::unload()"; bool unloadResult = true; if(aPlugin) { // Get all the loaders for this plugin QList<QPluginLoader*> loaderList = m_pluginLoaderHash.values(aPlugin); if(loaderList.size()) { foreach(QPluginLoader *loader, loaderList) { // for each loader unload the plugin unloadResult = loader->unload(); // delete the instance of the loader delete loader; loader = NULL; } // Remove the plugin and its associated loaders from the Hash m_pluginLoaderHash.remove(aPlugin); return unloadResult; } } else { qDebug()<<"Plugin instance is NULL!!!"; unloadResult = false; } return unloadResult; } /** * Method to unload the list of loaded plugins. Returns true if all unload * are success, else returns false if any one fails. * @param aPluginList The list of instances for all plugins that are * to be unloaded. This method does nothing and returns false if the list is empty. * @return Returns true if all are success, else returns false if any * one fails. Also returns false if the input list is empty. */ bool SmfPluginManager::unload ( const QList<SmfPluginBase *> &aPluginList) { qDebug()<<"Inside SmfPluginManager::unload() - overloaded fn"; bool unloaded = false; if(aPluginList.size()) { //unload all the required plugins foreach(SmfPluginBase *plugin, aPluginList) { // unload individual plugins in the list bool ret = unload(plugin); // indicate error if any one of the plugin failed to unload if(!ret) unloaded = ret; } } return unloaded; } /** * Method that calls the Transport Manager Utility class method to * send the request created by the plugins over the network * @param aReqData The request data created by the plugin * @param aResult [out] The output parameter indicating the result * of this method. This can be :- * SmfPluginNoError (if the request is sent successfully) or * SmfPluginSOPCheckFailed (if plugins request doesnot comply to * the Same Origin Policy) or * SmfPluginRequestSendingFailed (if request could not be sent) or * SmfPluginUnknownHttpService (if the plugin requested any unknown http * method other than get, post, put, head or delete) * @param aUrlList The list of accessible Urls for this plugin */ void SmfPluginManager::sendRequest ( SmfPluginRequestData &aReqData, SmfError &aResult, const QList<QUrl> &aUrlList ) { qDebug()<<"Inside SmfPluginManager::sendRequest()"; QNetworkReply* reply; bool sopCompliant = false; // Check the type of Http operation to be performed switch(aReqData.iHttpOperationType) { // Http HEAD case QNetworkAccessManager::HeadOperation: #ifdef DETAILEDDEBUGGING qDebug()<<"http::head Operation requested"; #endif reply = m_transMngrUtil->head(aReqData.iNetworkRequest, aUrlList, sopCompliant); break; // Http GET case QNetworkAccessManager::GetOperation: #ifdef DETAILEDDEBUGGING qDebug()<<"http::get Operation requested"; #endif reply = m_transMngrUtil->get(aReqData.iNetworkRequest, aUrlList, sopCompliant); break; // Http PUT case QNetworkAccessManager::PutOperation: #ifdef DETAILEDDEBUGGING qDebug()<<"http::put Operation requested"; #endif reply = m_transMngrUtil->put(aReqData.iNetworkRequest, aReqData.iPostData->buffer(), aUrlList, sopCompliant); delete aReqData.iPostData; break; // Http POST case QNetworkAccessManager::PostOperation: #ifdef DETAILEDDEBUGGING qDebug()<<"http::post Operation requested"; #endif reply = m_transMngrUtil->post(aReqData.iNetworkRequest, aReqData.iPostData->buffer(), aUrlList, sopCompliant); delete aReqData.iPostData; break; // Http DELETE case QNetworkAccessManager::DeleteOperation: #ifdef DETAILEDDEBUGGING qDebug()<<"http::delete Operation requested"; #endif reply = m_transMngrUtil->deleteResource(aReqData.iNetworkRequest, aUrlList, sopCompliant); break; default: #ifdef DETAILEDDEBUGGING qDebug()<<"unknown http Operation requested!!!"; #endif aResult = SmfPMPluginUnknownHttpService; return; } if( sopCompliant ) { if( reply ) { // SOP compliant, sending successful qDebug()<<"No error, request sent"; m_waitingPluginHash.insert(reply, m_tempStruct); m_tempStruct = NULL; aResult = SmfNoError; } else { // reply is NULL, sending failed qDebug()<<"QNetworkReply returned NULL - request not sent"; aResult = SmfPMPluginRequestSendingFailed; } } else { // SOP violation qDebug()<<"SOP checking failed"; aResult = SmfPMPluginSOPCheckFailed; } } /** * Method that checks if a plugin is authorised to make a request. * This method communicates with Credential and Settings Manager * through Smf server, giving the registration token and getting * the valid url list if available for this plugin. * @param aPluginId The ID of the plugin * @param aUrlList [out] The list of Urls that the plugin can send * request to (to be filled by CSM). This list will be empty if * aPluginId is not valid or not authorised. * @return Returns true if plugin is authorised, else returns false. * Also returns false if aRegToken is empty. */ bool SmfPluginManager::authorisePlugin( const QString &aPluginId, QList<QUrl> &aUrlList ) { qDebug()<<"Inside SmfPluginManager::authorisePlugin()"; bool authorised = false; SmfCredMgrClient csmClient; aUrlList = csmClient.URLList(aPluginId); if(aUrlList.count()) authorised = true; return authorised; } /** * Method to serialize the result of parsing (which is done by the * plugins) to QByteArray to be sent to Smf server. * @param aOperation The type of operation to be performed * @param aResult The data to be serialized (should not be NULL) * @param aDataStream Stream to be written to */ void SmfPluginManager::serializeResult ( const SmfRequestTypeID &aOperation, QVariant* aResult, QDataStream &aDataStream ) { qDebug()<<"Inside SmfPluginManager::serializeResult()"; // Call the utlity class method to serialize the result m_util->serializeResult(aOperation, aResult, aDataStream); } /** * Method for the directoryChanged signal of QFileSystemWatcher. * This will update the iPluginHash member and also the Plugin * Information List. * @param aPath The path of the directory that has changed */ void SmfPluginManager::directoryChanged ( const QString &aPath ) { qDebug()<<"Inside SmfPluginManager::directoryChanged()"; qDebug()<<"Changed path = "<<aPath; // Create a QDir instance with the given path QDir dir(aPath); QString pluginId; QString oldpluginId; QString interfaceName; QString serviceProv; QString authAppId; QString authAppName; // Get all the files in the directory at a specified path(sorted) QStringList newPlugins = dir.entryList(QDir::Files, QDir::Name); QStringList::const_iterator newListIterator = newPlugins.constBegin(); foreach(QString name, newPlugins) qDebug()<<"New plugin = "<<name; // Get all plugins who were in this path, before this directory was changed QStringList availablePlugins = m_pluginIdPathHash.keys(aPath); availablePlugins.sort(); QStringList::const_iterator oldListIterator = availablePlugins.constBegin(); foreach(QString name, availablePlugins) qDebug()<<"Old plugin = "<<name; // Open the database bool opened = m_pluginDataBase.open(); if(!opened) return; // If plugin is changed if( newPlugins.count() == availablePlugins.count() ) { qDebug()<<"Plugin upgraded..."; // Check for equality while( newListIterator != newPlugins.constEnd() ) { if( *newListIterator == *oldListIterator ) { newListIterator++; oldListIterator++; } else break; } // replace *oldListIterator with *newListIterator QHash<QString, QString>::iterator i = m_pluginIdPathHash.find(*oldListIterator); m_pluginIdPathHash.insert(*newListIterator, i.value()); m_pluginIdPathHash.remove(*oldListIterator); // Also update database with *newListIterator QSqlQuery updateQuery; bool updated = updateQuery.exec(QString("UPDATE pluginDetails SET pluginId = '%1' " "WHERE pluginId = '%2'").arg(*newListIterator).arg(*oldListIterator)); if (!updated) if(0 != updateQuery.lastError().text().size()) qDebug()<<"Database table not updated, error = "<<updateQuery.lastError().text(); // Get the new and old plugin Ids pluginId = *newListIterator; oldpluginId = *oldListIterator; // Load the plugin and get its service provider name SmfError result; SmfPluginBase* instance = qobject_cast<SmfPluginBase *>(load(pluginId, result)); if(instance && (SmfNoError == result)) { instance->initialize(); serviceProv = instance->getProviderInfo()->serviceName(); interfaceName = dir.dirName(); } unload(instance); qDebug()<<QString("Upgraded plugin details are : '%1' '%2' '%3' '%4'").arg(oldpluginId) .arg(pluginId).arg(interfaceName).arg(serviceProv); // Inform server that plugin has been changed #ifdef CSM_INTEGRATED //Remove after Server Integration m_server->pluginChanged(oldPluginId, pluginId, interfaceName, serviceProv); #endif } // If plugin is added else if(newPlugins.count() > availablePlugins.count()) { qDebug()<<"Plugin Added..."; // Check for equality while( oldListIterator != availablePlugins.constEnd() ) { if( *newListIterator == *oldListIterator ) { newListIterator++; oldListIterator++; } else break; } // replace *oldListIterator with *newListIterator m_pluginIdPathHash.insert(*newListIterator, aPath); // Get the plugin Id pluginId = *newListIterator; // Load the plugin and get its service provider name SmfError result; SmfPluginBase* instance = qobject_cast<SmfPluginBase *>(load(pluginId, result)); if(instance && (SmfNoError == result)) { instance->initialize(); serviceProv = instance->getProviderInfo()->serviceName(); interfaceName = dir.dirName(); interfaceName.prepend("org.symbian.smf.plugin."); QString prgm; QStringList list; authAppId = instance->getProviderInfo()->authenticationApp(prgm, list, QIODevice::ReadWrite); authAppName = instance->getProviderInfo()->authenticationAppName(); } unload(instance); // Also add to the database the value newListIterator and aPath QSqlQuery insertRowQuery; bool rowInserted = insertRowQuery.exec(QString("INSERT INTO pluginDetails VALUES " "('%1', '%2', '%3', '%4', '%5')").arg(pluginId).arg(interfaceName).arg(serviceProv).arg(authAppId).arg(authAppName)); // Error if (!rowInserted) qDebug()<<"Database table not inserted, error = "<<insertRowQuery.lastError().text(); qDebug()<<QString("Added plugin detailes are : '%1' '%2' '%3'").arg(pluginId) .arg(interfaceName).arg(serviceProv); // Inform server that plugin has been added #ifdef CSM_INTEGRATED //Remove after Server Integration m_server->pluginAdded(pluginId, interfaceName, serviceProv); #endif } // If plugin is removed else //for newPlugins.count() < availablePlugins.count() { qDebug()<<"Plugin removed..."; // Check for equality while( newListIterator != newPlugins.constEnd() ) { if( *newListIterator == *oldListIterator ) { newListIterator++; oldListIterator++; } else break; } // remove *oldListIterator m_pluginIdPathHash.remove(*oldListIterator); // Also remove oldListIterator from the database QSqlQuery deleteRowQuery; bool rowDeleted = deleteRowQuery.exec(QString("DELETE FROM pluginDetails WHERE pluginId = '%1'") .arg(*oldListIterator)); // Error if (!rowDeleted) qDebug()<<"Database table row not deleted, error = "<<deleteRowQuery.lastError().text(); // Get the plugin Id pluginId = *oldListIterator; // Load the plugin and get its service provider name SmfError result; SmfPluginBase* instance = qobject_cast<SmfPluginBase *>(load(pluginId, result)); if(instance && (SmfNoError == result)) { instance->initialize(); serviceProv = instance->getProviderInfo()->serviceName(); interfaceName = dir.dirName(); } unload(instance); qDebug()<<QString("Added plugin detailes are : '%1' '%2' '%3'").arg(pluginId) .arg(interfaceName).arg(serviceProv); // Inform server that plugin has removed #ifdef CSM_INTEGRATED //Remove after Server Integration m_server->pluginRemoved(pluginId, interfaceName, serviceProv); #endif } // Close the database m_pluginDataBase.close(); } /** * Method to get the list of the SmfProvider for all the plugins that implement * the mentioned Interface * @param aInterface The interface for which list of plugins is required * @param aMap The map of pluginID and its corresponding SmfProvider. The Map * will be empty if no plugins for the given interface could be found. */ void SmfPluginManager::getPlugins(const QString& aInterface, QMap<QString,SmfProvider>& aMap) { qDebug()<<"Inside SmfPluginManager::getPlugins()"; qDebug()<<"Argument, intf name = "<<aInterface; aMap.clear(); if(aInterface.isEmpty()) { qDebug()<<"Interface name is empty!!!"; return; } // Open the database bool opened = m_pluginDataBase.open(); if(!opened) { qDebug()<<"Data base not opened, exiting getplugins()!!!"; return; } #ifdef DETAILEDDEBUGGING qDebug()<<"Data base opened"; #endif // Query the database for all pluginIDs that implement the given interface QSqlQuery query(QString("SELECT pluginId, interfaceName, serviceProvider, description, " "serviceUrl, authAppId, authAppName FROM pluginDetails where interfaceName = '%1'").arg(aInterface)); while(query.next()) { #ifdef DETAILEDDEBUGGING qDebug()<<"Query is success"; #endif SmfProvider prov; // get the pluginId QString pluginId = query.value(0).toString(); qDebug()<<"Found Plugin Id = "<<pluginId; // get the service type / interface name QStringList servicetypes; servicetypes.insert(0, query.value(1).toString()); prov.setSupportedInterfaces(servicetypes); #ifdef DETAILEDDEBUGGING qDebug()<<" Its interface = "<<servicetypes.at(0); #endif // Get the serv provider QString servName = query.value(2).toString(); prov.setServiceName(servName); #ifdef DETAILEDDEBUGGING qDebug()<<" Its serv prov = "<<servName; #endif // Get the description QString desc = query.value(3).toString(); prov.setDescription(desc); #ifdef DETAILEDDEBUGGING qDebug()<<" Its description = "<<desc; #endif // Get the service URL QUrl url(query.value(4).toString()); prov.setServiceUrl(url); #ifdef DETAILEDDEBUGGING qDebug()<<" Its url = "<<url.toString(); #endif // Get the auth app ID QString id(query.value(5).toString()); prov.setAuthenticationAppId(id); #ifdef DETAILEDDEBUGGING qDebug()<<" Its auth app id = "<<id; #endif // Get the auth app name QString name (query.value(6).toString()); prov.setAuthenticationAppName(name); #ifdef DETAILEDDEBUGGING qDebug()<<" Its auth app name = "<<name; #endif aMap.insert(pluginId, prov); } if(0 != query.lastError().text().size()) qDebug()<<"Data base query->next() exited, error = "<<query.lastError().text(); else qDebug()<<"Data base query->next() exited"; qDebug()<<"Count of SmfProvider returned = "<<aMap.count(); // Close the database m_pluginDataBase.close(); } /** * Method to get the pluginID for the mentioned interface and service provider * @param aInterface The interface implemented by the plugin * @param aProv The plugin's service provider * @param aPluginId The required pluginID. This argument will be empty if no plugin * for the given interface and service provider could be found. */ void SmfPluginManager::getPluginId(const QString& aInterface, const SmfProvider& aProv, QString& aPluginId) { qDebug()<<"SmfPluginManager::getPluginId()"; aPluginId.clear(); if(aInterface.isEmpty()) { qDebug()<<"Interface name is empty!!!"; return; } // Open the database bool opened = m_pluginDataBase.open(); if(!opened) { qDebug()<<"Data base not opened, exiting!!!"; return; } #ifdef DETAILEDDEBUGGING qDebug()<<"Data base opened"; #endif // Query the database for a pluginID with given interface name and service provider QSqlQuery query(QString("SELECT pluginId FROM pluginDetails where interfaceName = '%1' AND " "serviceProvider = '%2'").arg(aInterface).arg(aProv.serviceName())); if (query.next()) { #ifdef DETAILEDDEBUGGING qDebug()<<"Query is success"; #endif // get the pluginId aPluginId = query.value(0).toString(); qDebug()<<"returned pluginID = "<<aPluginId; } else { if(0 != query.lastError().text().size()) qDebug()<<"Data base query->next() returned false, error = "<<query.lastError().text(); else qDebug()<<"Data base query->next() returned false"; } // Close the database m_pluginDataBase.close(); }
[ "[email protected]", "none@none" ]
[ [ [ 1, 28 ], [ 30, 160 ], [ 162, 166 ], [ 169, 214 ], [ 293, 372 ], [ 374, 377 ], [ 379, 385 ], [ 387, 462 ], [ 464, 464 ], [ 466, 472 ], [ 474, 483 ], [ 485, 485 ], [ 487, 493 ], [ 495, 495 ], [ 497, 500 ], [ 502, 502 ], [ 504, 507 ], [ 509, 509 ], [ 511, 516 ], [ 518, 518 ], [ 520, 522 ], [ 524, 524 ], [ 527, 533 ], [ 535, 535 ], [ 537, 546 ], [ 550, 561 ], [ 565, 566 ], [ 569, 569 ], [ 572, 573 ], [ 575, 601 ], [ 607, 652 ], [ 654, 779 ], [ 781, 781 ], [ 783, 787 ], [ 789, 789 ], [ 791, 795 ], [ 797, 797 ], [ 799, 804 ], [ 806, 806 ], [ 808, 813 ], [ 815, 815 ], [ 817, 820 ], [ 822, 822 ], [ 824, 859 ], [ 861, 862 ], [ 864, 866 ], [ 868, 871 ], [ 874, 874 ], [ 878, 878 ], [ 880, 919 ], [ 921, 980 ], [ 982, 1024 ], [ 1026, 1031 ], [ 1033, 1039 ], [ 1041, 1092 ], [ 1094, 1140 ], [ 1142, 1142 ], [ 1144, 1146 ], [ 1148, 1150 ], [ 1152, 1152 ], [ 1154, 1164 ], [ 1166, 1166 ], [ 1168, 1171 ], [ 1173, 1173 ], [ 1175, 1178 ], [ 1180, 1180 ], [ 1182, 1185 ], [ 1187, 1187 ], [ 1189, 1189 ], [ 1204, 1244 ], [ 1246, 1246 ], [ 1248, 1254 ], [ 1256, 1256 ], [ 1258, 1273 ] ], [ [ 29, 29 ], [ 161, 161 ], [ 167, 168 ], [ 215, 292 ], [ 373, 373 ], [ 378, 378 ], [ 386, 386 ], [ 463, 463 ], [ 465, 465 ], [ 473, 473 ], [ 484, 484 ], [ 486, 486 ], [ 494, 494 ], [ 496, 496 ], [ 501, 501 ], [ 503, 503 ], [ 508, 508 ], [ 510, 510 ], [ 517, 517 ], [ 519, 519 ], [ 523, 523 ], [ 525, 526 ], [ 534, 534 ], [ 536, 536 ], [ 547, 549 ], [ 562, 564 ], [ 567, 568 ], [ 570, 571 ], [ 574, 574 ], [ 602, 606 ], [ 653, 653 ], [ 780, 780 ], [ 782, 782 ], [ 788, 788 ], [ 790, 790 ], [ 796, 796 ], [ 798, 798 ], [ 805, 805 ], [ 807, 807 ], [ 814, 814 ], [ 816, 816 ], [ 821, 821 ], [ 823, 823 ], [ 860, 860 ], [ 863, 863 ], [ 867, 867 ], [ 872, 873 ], [ 875, 877 ], [ 879, 879 ], [ 920, 920 ], [ 981, 981 ], [ 1025, 1025 ], [ 1032, 1032 ], [ 1040, 1040 ], [ 1093, 1093 ], [ 1141, 1141 ], [ 1143, 1143 ], [ 1147, 1147 ], [ 1151, 1151 ], [ 1153, 1153 ], [ 1165, 1165 ], [ 1167, 1167 ], [ 1172, 1172 ], [ 1174, 1174 ], [ 1179, 1179 ], [ 1181, 1181 ], [ 1186, 1186 ], [ 1188, 1188 ], [ 1190, 1203 ], [ 1245, 1245 ], [ 1247, 1247 ], [ 1255, 1255 ], [ 1257, 1257 ] ] ]
da092c07e662576f6ee545927893505e7e0cefaf
d7320c9c1f155e2499afa066d159bfa6aa94b432
/ghost/socket.h
bc12272c59f764abb80173a7675478dd753be923
[]
no_license
HOST-PYLOS/ghostnordicleague
c44c804cb1b912584db3dc4bb811f29f3761a458
9cb262d8005dda0150b75d34b95961d664b1b100
refs/heads/master
2016-09-05T10:06:54.279724
2011-02-23T08:02:50
2011-02-23T08:02:50
32,241,503
0
1
null
null
null
null
UTF-8
C++
false
false
5,423
h
/* Copyright [2008] [Trevor Hogan] 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. CODE PORTED FROM THE ORIGINAL GHOST PROJECT: http://ghost.pwner.org/ */ #ifndef SOCKET_H #define SOCKET_H #ifdef WIN32 #include <winsock2.h> #include <errno.h> #define EADDRINUSE WSAEADDRINUSE #define EADDRNOTAVAIL WSAEADDRNOTAVAIL #define EAFNOSUPPORT WSAEAFNOSUPPORT #define EALREADY WSAEALREADY #define ECONNABORTED WSAECONNABORTED #define ECONNREFUSED WSAECONNREFUSED #define ECONNRESET WSAECONNRESET #define EDESTADDRREQ WSAEDESTADDRREQ #define EDQUOT WSAEDQUOT #define EHOSTDOWN WSAEHOSTDOWN #define EHOSTUNREACH WSAEHOSTUNREACH #define EINPROGRESS WSAEINPROGRESS #define EISCONN WSAEISCONN #define ELOOP WSAELOOP #define EMSGSIZE WSAEMSGSIZE // #define ENAMETOOLONG WSAENAMETOOLONG #define ENETDOWN WSAENETDOWN #define ENETRESET WSAENETRESET #define ENETUNREACH WSAENETUNREACH #define ENOBUFS WSAENOBUFS #define ENOPROTOOPT WSAENOPROTOOPT #define ENOTCONN WSAENOTCONN // #define ENOTEMPTY WSAENOTEMPTY #define ENOTSOCK WSAENOTSOCK #define EOPNOTSUPP WSAEOPNOTSUPP #define EPFNOSUPPORT WSAEPFNOSUPPORT #define EPROTONOSUPPORT WSAEPROTONOSUPPORT #define EPROTOTYPE WSAEPROTOTYPE #define EREMOTE WSAEREMOTE #define ESHUTDOWN WSAESHUTDOWN #define ESOCKTNOSUPPORT WSAESOCKTNOSUPPORT #define ESTALE WSAESTALE #define ETIMEDOUT WSAETIMEDOUT #define ETOOMANYREFS WSAETOOMANYREFS #define EUSERS WSAEUSERS #define EWOULDBLOCK WSAEWOULDBLOCK #else #include <arpa/inet.h> #include <errno.h> #include <fcntl.h> #include <netdb.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> typedef int SOCKET; #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #define closesocket close extern int GetLastError( ); #endif #ifndef INADDR_NONE #define INADDR_NONE -1 #endif #ifndef MSG_NOSIGNAL #define MSG_NOSIGNAL 0 #endif #ifdef WIN32 #define SHUT_RDWR 2 #endif // // CSocket // class CSocket { protected: SOCKET m_Socket; struct sockaddr_in m_SIN; bool m_HasError; int m_Error; public: CSocket( ); CSocket( SOCKET nSocket, struct sockaddr_in nSIN ); ~CSocket( ); virtual BYTEARRAY GetPort( ); virtual BYTEARRAY GetIP( ); virtual string GetIPString( ); virtual bool HasError( ) { return m_HasError; } virtual int GetError( ) { return m_Error; } virtual string GetErrorString( ); virtual void SetFD( fd_set *fd, fd_set *send_fd, int *nfds ); virtual void Allocate( int type ); virtual void Reset( ); }; // // CTCPSocket // class CTCPSocket : public CSocket { protected: bool m_Connected; private: string m_RecvBuffer; string m_SendBuffer; uint32_t m_LastRecv; uint32_t m_LastSend; public: CTCPSocket( ); CTCPSocket( SOCKET nSocket, struct sockaddr_in nSIN ); virtual ~CTCPSocket( ); virtual void Reset( ); virtual bool GetConnected( ) { return m_Connected; } virtual string *GetBytes( ) { return &m_RecvBuffer; } virtual void PutBytes( string bytes ); virtual void PutBytes( BYTEARRAY bytes ); virtual uint32_t GetLastRecv( ) { return m_LastRecv; } virtual uint32_t GetLastSend( ) { return m_LastSend; } virtual void DoRecv( fd_set *fd ); virtual void DoSend( fd_set *send_fd ); virtual void Disconnect( ); virtual void SetNoDelay( bool noDelay ); }; // // CTCPClient // class CTCPClient : public CTCPSocket { protected: bool m_Connecting; public: CTCPClient( ); virtual ~CTCPClient( ); virtual void Reset( ); virtual void Disconnect( ); virtual bool GetConnecting( ) { return m_Connecting; } virtual void Connect( string localaddress, string address, uint16_t port ); virtual bool CheckConnect( ); }; // // CTCPServer // class CTCPServer : public CTCPSocket { public: CTCPServer( ); virtual ~CTCPServer( ); virtual bool Listen( string address, uint16_t port ); virtual CTCPSocket *Accept( fd_set *fd ); }; // // CUDPSocket // class CUDPSocket : public CSocket { protected: struct in_addr m_BroadcastTarget; public: CUDPSocket( ); virtual ~CUDPSocket( ); virtual bool SendTo( struct sockaddr_in sin, BYTEARRAY message ); virtual bool SendTo( string address, uint16_t port, BYTEARRAY message ); virtual bool Broadcast( uint16_t port, BYTEARRAY message ); virtual void SetBroadcastTarget( string subnet ); virtual void SetDontRoute( bool dontRoute ); }; // // CUDPServer // class CUDPServer : public CUDPSocket { public: CUDPServer( ); virtual ~CUDPServer( ); virtual bool Bind( struct sockaddr_in sin ); virtual bool Bind( string address, uint16_t port ); virtual void RecvFrom( fd_set *fd, struct sockaddr_in *sin, string *message ); }; #endif
[ "fredrik.sigillet@4a4c9648-eef2-11de-9456-cf00f3bddd4e" ]
[ [ [ 1, 227 ] ] ]
06fa9ffac9af6ad1ad5ae627031e8225ed5b98c7
3e94c7f668d9903556ecc3a00faac8d9aca869c9
/MMA Semestralka/glm.cpp
df0a58e02e41c8f061b28fff49abbdcb2e9c282c
[]
no_license
kucerad/rpak-snowman-madness2
5a6ab30bf273ac71dcaccdb4b0c6215f8a7bd600
74409305cc6a4cc1face84e22403a2058dd447ea
refs/heads/master
2016-09-05T19:26:00.750294
2010-12-20T19:53:27
2010-12-20T19:53:27
35,802,289
0
0
null
null
null
null
UTF-8
C++
false
false
76,384
cpp
/* glm.c Nate Robins, 1997, 2000 [email protected], http://www.pobox.com/~nate Wavefront OBJ model file format reader/writer/manipulator. Includes routines for generating smooth normals with preservation of edges, welding redundant vertices & texture coordinate generation (spheremap and planar projections) + more. Improved version of GLM - 08.05.2008 Tudor Carean Added support for textures */ #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "glm.h" #include "TextureLoader.h" static CTextureLoader* _glmTextureLoader = NULL; //#define DebugVisibleSurfaces #define total_textures 5 #define T(x) (model->triangles[(x)]) GLuint glmLoadTexture(char *filename, GLboolean alpha, GLboolean repeat, GLboolean filtering, GLboolean mipmaps, GLfloat *texcoordwidth, GLfloat *texcoordheight); /* _GLMnode: general purpose node */ typedef struct _GLMnode { GLuint index; GLboolean averaged; struct _GLMnode* next; } GLMnode; /* glmMax: returns the maximum of two floats */ static GLfloat glmMax(GLfloat a, GLfloat b) { if (b > a) return b; return a; } /* glmAbs: returns the absolute value of a float */ static GLfloat glmAbs(GLfloat f) { if (f < 0) return -f; return f; } /* glmDot: compute the dot product of two vectors * * u - array of 3 GLfloats (GLfloat u[3]) * v - array of 3 GLfloats (GLfloat v[3]) */ GLfloat glmDot(GLfloat* u, GLfloat* v) { assert(u); assert(v); return u[0]*v[0] + u[1]*v[1] + u[2]*v[2]; } /* glmCross: compute the cross product of two vectors * * u - array of 3 GLfloats (GLfloat u[3]) * v - array of 3 GLfloats (GLfloat v[3]) * n - array of 3 GLfloats (GLfloat n[3]) to return the cross product in */ static GLvoid glmCross(GLfloat* u, GLfloat* v, GLfloat* n) { assert(u); assert(v); assert(n); n[0] = u[1]*v[2] - u[2]*v[1]; n[1] = u[2]*v[0] - u[0]*v[2]; n[2] = u[0]*v[1] - u[1]*v[0]; } /* glmNormalize: normalize a vector * * v - array of 3 GLfloats (GLfloat v[3]) to be normalized */ static GLvoid glmNormalize(GLfloat* v) { GLfloat l; assert(v); l = (GLfloat)sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); v[0] /= l; v[1] /= l; v[2] /= l; } /* glmEqual: compares two vectors and returns GL_TRUE if they are * equal (within a certain threshold) or GL_FALSE if not. An epsilon * that works fairly well is 0.000001. * * u - array of 3 GLfloats (GLfloat u[3]) * v - array of 3 GLfloats (GLfloat v[3]) */ static GLboolean glmEqual(GLfloat* u, GLfloat* v, GLfloat epsilon) { if (glmAbs(u[0] - v[0]) < epsilon && glmAbs(u[1] - v[1]) < epsilon && glmAbs(u[2] - v[2]) < epsilon) { return GL_TRUE; } return GL_FALSE; } /* glmWeldVectors: eliminate (weld) vectors that are within an * epsilon of each other. * * vectors - array of GLfloat[3]'s to be welded * numvectors - number of GLfloat[3]'s in vectors * epsilon - maximum difference between vectors * */ GLfloat* glmWeldVectors(GLfloat* vectors, GLuint* numvectors, GLfloat epsilon) { GLfloat* copies; GLuint copied; GLuint i, j; copies = (GLfloat*)malloc(sizeof(GLfloat) * 3 * (*numvectors + 1)); memcpy(copies, vectors, (sizeof(GLfloat) * 3 * (*numvectors + 1))); copied = 1; for (i = 1; i <= *numvectors; i++) { for (j = 1; j <= copied; j++) { if (glmEqual(&vectors[3 * i], &copies[3 * j], epsilon)) { goto duplicate; } } /* must not be any duplicates -- add to the copies array */ copies[3 * copied + 0] = vectors[3 * i + 0]; copies[3 * copied + 1] = vectors[3 * i + 1]; copies[3 * copied + 2] = vectors[3 * i + 2]; j = copied; /* pass this along for below */ copied++; duplicate: /* set the first component of this vector to point at the correct index into the new copies array */ vectors[3 * i + 0] = (GLfloat)j; } *numvectors = copied-1; return copies; } /* glmFindGroup: Find a group in the model */ GLMgroup* glmFindGroup(GLMmodel* model, char* name) { GLMgroup* group; assert(model); group = model->groups; while(group) { if (!strcmp(name, group->name)) break; group = group->next; } return group; } /* glmAddGroup: Add a group to the model */ GLMgroup* glmAddGroup(GLMmodel* model, char* name) { GLMgroup* group; group = glmFindGroup(model, name); if (!group) { group = (GLMgroup*)malloc(sizeof(GLMgroup)); group->name = strdup(name); group->material = 0; group->numtriangles = 0; group->triangles = NULL; group->next = model->groups; model->groups = group; model->numgroups++; } return group; } /* glmFindMaterial: Find a material in the model */ GLuint glmFindMaterial(GLMmodel* model, char* name) { GLuint i; /* XXX doing a linear search on a string key'd list is pretty lame, but it works and is fast enough for now. */ for (i = 0; i < model->nummaterials; i++) { if (!strcmp(model->materials[i].name, name)) goto found; } /* didn't find the name, so print a warning and return the default material (0). */ printf("glmFindMaterial(): can't find material \"%s\".\n", name); i = 0; found: return i; } /* glmDirName: return the directory given a path * * path - filesystem path * * NOTE: the return value should be free'd. */ static char* glmDirName(char* path) { char* dir; char* s; dir = strdup(path); s = strrchr(dir, '/'); if (s) s[1] = '\0'; else dir[0] = '\0'; return dir; } int glmFindOrAddTexture(GLMmodel* model, char* name) { GLuint i; char *dir, *filename; float width, height; char *numefis = name; while (*numefis==' ') numefis++; for (i = 0; i < model->numtextures; i++) { if (!strcmp(model->textures[i].name, numefis)) return i; } if (strstr(name,":\\")) { filename = (char*)malloc(sizeof(char) * (strlen(name) + 1)); strcpy(filename,name); } else { dir = glmDirName(model->pathname); filename = (char*)malloc(sizeof(char) * (strlen(dir) + strlen(numefis) + 1)); strcpy(filename, dir); //strcpy(filename, numefis); strcat(filename, numefis); free(dir); } int lung = (int)strlen(filename); if (filename[lung-1]<32) filename[lung-1]=0; if (filename[lung-2]<32) filename[lung-2]=0; model->numtextures++; model->textures = (GLMtexture*)realloc(model->textures, sizeof(GLMtexture)*model->numtextures); model->textures[model->numtextures-1].name = strdup(numefis); model->textures[model->numtextures-1].id = glmLoadTexture(filename, GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE, &width, &height); model->textures[model->numtextures-1].width = width; model->textures[model->numtextures-1].height = height; free(filename); return model->numtextures-1; } /* glmReadMTL: read a wavefront material library file * * model - properly initialized GLMmodel structure * name - name of the material library */ /* * Comments begin with a '#' character in column 1. Blank lines may be inserted for clarity. * Otherwise, the file consists of a sequence of newmtl statements, followed by a definition * of various properties for that material. * The quantities that may be defined for a material include: * * Ka r g b * defines the ambient color of the material to be (r,g,b). The default is (0.2,0.2,0.2); * Kd r g b * defines the diffuse color of the material to be (r,g,b). The default is (0.8,0.8,0.8); * Ks r g b * defines the specular color of the material to be (r,g,b). This color shows up in highlights. The default is (1.0,1.0,1.0); * d alpha * defines the transparency of the material to be alpha. The default is 1.0 (not transparent at all) Some formats use Tr instead of d; * Tr alpha * defines the transparency of the material to be alpha. The default is 1.0 (not transparent at all). Some formats use d instead of Tr; * Ns s * defines the shininess of the material to be s. The default is 0.0; * illum n * denotes the illumination model used by the material. illum = 1 indicates a flat material with no specular highlights, so the value of Ks is not used. illum = 2 denotes the presence of specular highlights, and so a specification for Ks is required. * map_Ka filename * names a file containing a texture map, which should just be an ASCII dump of RGB values; */ static GLvoid glmReadMTL(GLMmodel* model, char* name) { FILE* file; char* dir; char* filename; char buf[128]; GLuint nummaterials, i; dir = glmDirName(model->pathname); filename = (char*)malloc(sizeof(char) * (strlen(dir) + strlen(name) + 1)); strcpy(filename, dir); strcat(filename, name); free(dir); file = fopen(filename, "r"); if (!file) { fprintf(stderr, "glmReadMTL() failed: can't open material file \"%s\".\n", filename); exit(1); } free(filename); /* count the number of materials in the file */ nummaterials = 1; while(fscanf(file, "%s", buf) != EOF) { switch(buf[0]) { case '#': /* comment */ /* eat up rest of line */ fgets(buf, sizeof(buf), file); break; case 'n': /* newmtl */ fgets(buf, sizeof(buf), file); nummaterials++; sscanf(buf, "%s %s", buf, buf); break; default: /* eat up rest of line */ fgets(buf, sizeof(buf), file); break; } } rewind(file); model->materials = (GLMmaterial*)malloc(sizeof(GLMmaterial) * nummaterials); model->nummaterials = nummaterials; /* set the default material */ for (i = 0; i < nummaterials; i++) { model->materials[i].name = NULL; model->materials[i].shininess = 65.0; model->materials[i].diffuse[0] = 0.8; model->materials[i].diffuse[1] = 0.8; model->materials[i].diffuse[2] = 0.8; model->materials[i].diffuse[3] = 1.0; model->materials[i].ambient[0] = 0.2; model->materials[i].ambient[1] = 0.2; model->materials[i].ambient[2] = 0.2; model->materials[i].ambient[3] = 1.0; model->materials[i].specular[0] = 0.0; model->materials[i].specular[1] = 0.0; model->materials[i].specular[2] = 0.0; model->materials[i].specular[3] = 1.0; model->materials[i].textureID = -1; model->materials[i].textureName = NULL; } model->materials[0].name = strdup("default"); /* now, read in the data */ nummaterials = 0; while(fscanf(file, "%s", buf) != EOF) { switch(buf[0]) { case '#': /* comment */ /* eat up rest of line */ fgets(buf, sizeof(buf), file); break; case 'n': /* newmtl */ fgets(buf, sizeof(buf), file); sscanf(buf, "%s %s", buf, buf); nummaterials++; model->materials[nummaterials].name = strdup(buf); break; case 'N': if (buf[1]!='s') break; fscanf(file, "%f", &model->materials[nummaterials].shininess); /* wavefront shininess is from [0, 1000], so scale for OpenGL */ model->materials[nummaterials].shininess /= 1000.0; model->materials[nummaterials].shininess *= 128.0; break; case 'K': switch(buf[1]) { case 'd': fscanf(file, "%f %f %f", &model->materials[nummaterials].diffuse[0], &model->materials[nummaterials].diffuse[1], &model->materials[nummaterials].diffuse[2]); break; case 's': fscanf(file, "%f %f %f", &model->materials[nummaterials].specular[0], &model->materials[nummaterials].specular[1], &model->materials[nummaterials].specular[2]); break; case 'a': fscanf(file, "%f %f %f", &model->materials[nummaterials].ambient[0], &model->materials[nummaterials].ambient[1], &model->materials[nummaterials].ambient[2]); break; default: /* eat up rest of line */ fgets(buf, sizeof(buf), file); break; } break; case 'd': // 'd' (or 'Tr') -> dissolve factor, pseudo-transparency fscanf(file, "%f", &model->materials[nummaterials].diffuse[3]); break; case 'T': switch(buf[1]) { case 'r': fscanf(file, "%f", &model->materials[nummaterials].diffuse[3]); break; default: /* eat up rest of line */ fgets(buf, sizeof(buf), file); break; } case 'm': // search for texture filename = (char *)malloc(FILENAME_MAX); fgets(filename, FILENAME_MAX, file); model->materials[nummaterials].textureName = strdup(filename); free(filename); if(strncmp(buf, "map_Kd", 6) == 0) { model->materials[nummaterials].textureID = glmFindOrAddTexture(model, model->materials[nummaterials].textureName); } else { //printf("map %s %s ignored",buf,t_filename); free(model->materials[nummaterials].textureName); //fgets(buf, sizeof(buf), file); } break; default: /* eat up rest of line */ fgets(buf, sizeof(buf), file); break; } } } /* glmWriteMTL: write a wavefront material library file * * model - properly initialized GLMmodel structure * modelpath - pathname of the model being written * mtllibname - name of the material library to be written */ static GLvoid glmWriteMTL(GLMmodel* model, char* modelpath, char* mtllibname) { FILE* file; char* dir; char* filename; GLMmaterial* material; GLuint i; dir = glmDirName(modelpath); filename = (char*)malloc(sizeof(char) * (strlen(dir)+strlen(mtllibname))); strcpy(filename, dir); strcat(filename, mtllibname); free(dir); /* open the file */ file = fopen(filename, "w"); if (!file) { fprintf(stderr, "glmWriteMTL() failed: can't open file \"%s\".\n", filename); exit(1); } free(filename); /* spit out a header */ fprintf(file, "# \n"); fprintf(file, "# Wavefront MTL generated by GLM library\n"); fprintf(file, "# \n"); fprintf(file, "# GLM library\n"); fprintf(file, "# Nate Robins\n"); fprintf(file, "# [email protected]\n"); fprintf(file, "# http://www.pobox.com/~ndr\n"); fprintf(file, "# \n\n"); for (i = 0; i < model->nummaterials; i++) { material = &model->materials[i]; fprintf(file, "newmtl %s\n", material->name); fprintf(file, "Ka %f %f %f\n", material->ambient[0], material->ambient[1], material->ambient[2]); fprintf(file, "Kd %f %f %f\n", material->diffuse[0], material->diffuse[1], material->diffuse[2]); fprintf(file, "Ks %f %f %f\n", material->specular[0],material->specular[1],material->specular[2]); fprintf(file, "Ns %f\n", material->shininess / 128.0 * 1000.0); if (material->diffuse[3] != 1.0) fprintf(file, "d %f\n", material->diffuse[3]); // dissolve factor, pseudo-transparency if (material->textureID != -1) fprintf(file, "map_Kd %s\n", material->textureName); // PRL 20030806: texturemap. fprintf(file, "\n"); } } /* glmFirstPass: first pass at a Wavefront OBJ file that gets all the * statistics of the model (such as #vertices, #normals, etc) * * model - properly initialized GLMmodel structure * file - (fopen'd) file descriptor */ static GLvoid glmFirstPass(GLMmodel* model, FILE* file) { GLuint numvertices; /* number of vertices in model */ GLuint numnormals; /* number of normals in model */ GLuint numtexcoords; /* number of texcoords in model */ GLuint numtriangles; /* number of triangles in model */ GLMgroup* group; /* current group */ unsigned v, n, t; char buf[128]; /* make a default group */ group = glmAddGroup(model, "default"); numvertices = numnormals = numtexcoords = numtriangles = 0; while(fscanf(file, "%s", buf) != EOF) { switch(buf[0]) { case '#': /* comment */ /* eat up rest of line */ fgets(buf, sizeof(buf), file); break; case 'v': /* v, vn, vt */ switch(buf[1]) { case '\0': /* vertex */ /* eat up rest of line */ fgets(buf, sizeof(buf), file); numvertices++; break; case 'n': /* normal */ /* eat up rest of line */ fgets(buf, sizeof(buf), file); numnormals++; break; case 't': /* texcoord */ /* eat up rest of line */ fgets(buf, sizeof(buf), file); numtexcoords++; break; default: printf("glmFirstPass(): Unknown token \"%s\".\n", buf); exit(1); break; } break; case 'm': //mtllib fgets(buf, sizeof(buf), file); sscanf(buf, "%s %s", buf, buf); model->mtllibname = strdup(buf); glmReadMTL(model, buf); break; case 'u': //usemtl /* eat up rest of line */ fgets(buf, sizeof(buf), file); break; case 'g': /* group */ /* eat up rest of line */ fgets(buf, sizeof(buf), file); #if SINGLE_STRING_GROUP_NAMES sscanf(buf, "%s", buf); #else buf[strlen(buf)-1] = '\0'; /* nuke '\n' */ #endif group = glmAddGroup(model, buf); break; case 'f': /* face */ v = n = t = 0; fscanf(file, "%s", buf); /* can be one of %d, %d//%d, %d/%d, %d/%d/%d %d//%d */ if (strstr(buf, "//")) { /* v//n */ sscanf(buf, "%d//%d", &v, &n); fscanf(file, "%d//%d", &v, &n); fscanf(file, "%d//%d", &v, &n); numtriangles++; group->numtriangles++; while(fscanf(file, "%d//%d", &v, &n) > 0) { numtriangles++; group->numtriangles++; } } else if (sscanf(buf, "%d/%d/%d", &v, &t, &n) == 3) { /* v/t/n */ fscanf(file, "%d/%d/%d", &v, &t, &n); fscanf(file, "%d/%d/%d", &v, &t, &n); numtriangles++; group->numtriangles++; while(fscanf(file, "%d/%d/%d", &v, &t, &n) > 0) { numtriangles++; group->numtriangles++; } } else if (sscanf(buf, "%d/%d", &v, &t) == 2) { /* v/t */ fscanf(file, "%d/%d", &v, &t); fscanf(file, "%d/%d", &v, &t); numtriangles++; group->numtriangles++; while(fscanf(file, "%d/%d", &v, &t) > 0) { numtriangles++; group->numtriangles++; } } else { /* v */ fscanf(file, "%d", &v); fscanf(file, "%d", &v); numtriangles++; group->numtriangles++; while(fscanf(file, "%d", &v) > 0) { numtriangles++; group->numtriangles++; } } break; default: /* eat up rest of line */ fgets(buf, sizeof(buf), file); break; } } /* set the stats in the model structure */ model->numvertices = numvertices; model->numnormals = numnormals; model->numtexcoords = numtexcoords; model->numtriangles = numtriangles; /* allocate memory for the triangles in each group */ group = model->groups; while(group) { group->triangles = (GLuint*)malloc(sizeof(GLuint) * group->numtriangles); group->numtriangles = 0; group = group->next; } } /* glmSecondPass: second pass at a Wavefront OBJ file that gets all * the data. * * model - properly initialized GLMmodel structure * file - (fopen'd) file descriptor */ static GLvoid glmSecondPass(GLMmodel* model, FILE* file) { GLuint numvertices; /* number of vertices in model */ GLuint numnormals; /* number of normals in model */ GLuint numtexcoords; /* number of texcoords in model */ GLuint numtriangles; /* number of triangles in model */ GLfloat* vertices; /* array of vertices */ GLfloat* normals; /* array of normals */ GLfloat* texcoords; /* array of texture coordinates */ GLMgroup* group; /* current group pointer */ GLuint material; /* current material */ GLuint v, n, t; char buf[128]; /* set the pointer shortcuts */ vertices = model->vertices; normals = model->normals; texcoords = model->texcoords; group = model->groups; /* on the second pass through the file, read all the data into the allocated arrays */ numvertices = numnormals = numtexcoords = 1; numtriangles = 0; material = 0; while(fscanf(file, "%s", buf) != EOF) { switch(buf[0]) { case '#': /* comment */ /* eat up rest of line */ fgets(buf, sizeof(buf), file); break; case 'v': /* v, vn, vt */ switch(buf[1]) { case '\0': /* vertex */ fscanf(file, "%f %f %f", &vertices[3 * numvertices + 0], &vertices[3 * numvertices + 1], &vertices[3 * numvertices + 2]); numvertices++; break; case 'n': /* normal */ fscanf(file, "%f %f %f", &normals[3 * numnormals + 0], &normals[3 * numnormals + 1], &normals[3 * numnormals + 2]); numnormals++; break; case 't': /* texcoord */ fscanf(file, "%f %f", &texcoords[2 * numtexcoords + 0], &texcoords[2 * numtexcoords + 1]); numtexcoords++; break; } break; case 'u': /* usemtl */ fgets(buf, sizeof(buf), file); sscanf(buf, "%s %s", buf, buf); group->material = material = glmFindMaterial(model, buf); //material = glmFindMaterial(model, buf); break; case 'g': /* group */ /* eat up rest of line */ fgets(buf, sizeof(buf), file); #if SINGLE_STRING_GROUP_NAMES sscanf(buf, "%s", buf); #else buf[strlen(buf)-1] = '\0'; /* nuke '\n' */ #endif group = glmFindGroup(model, buf); group->material = material; break; case 'f': /* face */ v = n = t = 0; T(numtriangles).findex = -1; // ??? T(numtriangles).vecini[0]=-1; T(numtriangles).vecini[1]=-1; T(numtriangles).vecini[2]=-1; fscanf(file, "%s", buf); /* can be one of %d, %d//%d, %d/%d, %d/%d/%d %d//%d */ if (strstr(buf, "//")) { /* v//n */ sscanf(buf, "%d//%d", &v, &n); T(numtriangles).vindices[0] = v; //if (n== 181228) //{ // printf(""); //} T(numtriangles).nindices[0] = n; fscanf(file, "%d//%d", &v, &n); T(numtriangles).vindices[1] = v; T(numtriangles).nindices[1] = n; fscanf(file, "%d//%d", &v, &n); T(numtriangles).vindices[2] = v; T(numtriangles).nindices[2] = n; group->triangles[group->numtriangles++] = numtriangles; numtriangles++; while(fscanf(file, "%d//%d", &v, &n) > 0) { // polygon -> replace by triangle fan T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0]; T(numtriangles).nindices[0] = T(numtriangles-1).nindices[0]; T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2]; T(numtriangles).nindices[1] = T(numtriangles-1).nindices[2]; T(numtriangles).vindices[2] = v; T(numtriangles).nindices[2] = n; group->triangles[group->numtriangles++] = numtriangles; numtriangles++; } } else if (sscanf(buf, "%d/%d/%d", &v, &t, &n) == 3) { /* v/t/n */ T(numtriangles).vindices[0] = v; T(numtriangles).tindices[0] = t; T(numtriangles).nindices[0] = n; fscanf(file, "%d/%d/%d", &v, &t, &n); T(numtriangles).vindices[1] = v; T(numtriangles).tindices[1] = t; T(numtriangles).nindices[1] = n; fscanf(file, "%d/%d/%d", &v, &t, &n); T(numtriangles).vindices[2] = v; T(numtriangles).tindices[2] = t; T(numtriangles).nindices[2] = n; group->triangles[group->numtriangles++] = numtriangles; numtriangles++; while(fscanf(file, "%d/%d/%d", &v, &t, &n) > 0) { //if (n== 181228) T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0]; T(numtriangles).tindices[0] = T(numtriangles-1).tindices[0]; T(numtriangles).nindices[0] = T(numtriangles-1).nindices[0]; T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2]; T(numtriangles).tindices[1] = T(numtriangles-1).tindices[2]; T(numtriangles).nindices[1] = T(numtriangles-1).nindices[2]; T(numtriangles).vindices[2] = v; T(numtriangles).tindices[2] = t; T(numtriangles).nindices[2] = n; group->triangles[group->numtriangles++] = numtriangles; numtriangles++; } } else if (sscanf(buf, "%d/%d", &v, &t) == 2) { /* v/t */ T(numtriangles).vindices[0] = v; T(numtriangles).tindices[0] = t; fscanf(file, "%d/%d", &v, &t); T(numtriangles).vindices[1] = v; T(numtriangles).tindices[1] = t; fscanf(file, "%d/%d", &v, &t); T(numtriangles).vindices[2] = v; T(numtriangles).tindices[2] = t; group->triangles[group->numtriangles++] = numtriangles; numtriangles++; while(fscanf(file, "%d/%d", &v, &t) > 0) { T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0]; T(numtriangles).tindices[0] = T(numtriangles-1).tindices[0]; T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2]; T(numtriangles).tindices[1] = T(numtriangles-1).tindices[2]; T(numtriangles).vindices[2] = v; T(numtriangles).tindices[2] = t; group->triangles[group->numtriangles++] = numtriangles; numtriangles++; } } else { /* v */ //if (n== 181228) sscanf(buf, "%d", &v); T(numtriangles).vindices[0] = v; fscanf(file, "%d", &v); T(numtriangles).vindices[1] = v; fscanf(file, "%d", &v); T(numtriangles).vindices[2] = v; group->triangles[group->numtriangles++] = numtriangles; numtriangles++; while(fscanf(file, "%d", &v) > 0) { T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0]; T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2]; T(numtriangles).vindices[2] = v; group->triangles[group->numtriangles++] = numtriangles; numtriangles++; } } break; default: /* eat up rest of line */ fgets(buf, sizeof(buf), file); break; } } #if 0 /* announce the memory requirements */ printf(" Memory: %d bytes\n", numvertices * 3*sizeof(GLfloat) + numnormals * 3*sizeof(GLfloat) * (numnormals ? 1 : 0) + numtexcoords * 3*sizeof(GLfloat) * (numtexcoords ? 1 : 0) + numtriangles * sizeof(GLMtriangle)); #endif } /* public functions */ /* glmUnitize: "unitize" a model by translating it to the origin and * scaling it to fit in a unit cube around the origin. Returns the * scalefactor used. * * model - properly initialized GLMmodel structure */ GLfloat glmUnitize(GLMmodel* model) { GLuint i; GLfloat maxx, minx, maxy, miny, maxz, minz; GLfloat cx, cy, cz, w, h, d; GLfloat scale; assert(model); assert(model->vertices); /* get the max/mins */ maxx = minx = model->vertices[3 + 0]; maxy = miny = model->vertices[3 + 1]; maxz = minz = model->vertices[3 + 2]; for (i = 1; i <= model->numvertices; i++) { if (maxx < model->vertices[3 * i + 0]) maxx = model->vertices[3 * i + 0]; if (minx > model->vertices[3 * i + 0]) minx = model->vertices[3 * i + 0]; if (maxy < model->vertices[3 * i + 1]) maxy = model->vertices[3 * i + 1]; if (miny > model->vertices[3 * i + 1]) miny = model->vertices[3 * i + 1]; if (maxz < model->vertices[3 * i + 2]) maxz = model->vertices[3 * i + 2]; if (minz > model->vertices[3 * i + 2]) minz = model->vertices[3 * i + 2]; } /* calculate model width, height, and depth */ w = maxx - minx; // w = glmAbs(maxx) + glmAbs(minx); h = maxy - miny; // h = glmAbs(maxy) + glmAbs(miny); d = maxz - minz; // d = glmAbs(maxz) + glmAbs(minz); /* calculate center of the model */ cx = (maxx + minx) / 2.0; cy = (maxy + miny) / 2.0; cz = (maxz + minz) / 2.0; /* calculate unitizing scale factor */ scale = 1.0 / glmMax(glmMax(w, h), d); // scale = 2.0 / glmMax(glmMax(w, h), d); /* translate around center then scale */ for (i = 1; i <= model->numvertices; i++) { model->vertices[3 * i + 0] -= cx; model->vertices[3 * i + 1] -= cy; model->vertices[3 * i + 2] -= cz; model->vertices[3 * i + 0] *= scale; model->vertices[3 * i + 1] *= scale; model->vertices[3 * i + 2] *= scale; } return scale; } /* glmDimensions: Calculates the dimensions (width, height, depth) of * a model. * * model - initialized GLMmodel structure * dimensions - array of 3 GLfloats (GLfloat dimensions[3]) */ GLvoid glmDimensions(GLMmodel* model, GLfloat* dimensions) { GLuint i; GLfloat maxx, minx, maxy, miny, maxz, minz; assert(model); assert(model->vertices); assert(dimensions); /* get the max/mins */ maxx = minx = model->vertices[3 + 0]; maxy = miny = model->vertices[3 + 1]; maxz = minz = model->vertices[3 + 2]; for (i = 1; i <= model->numvertices; i++) { if (maxx < model->vertices[3 * i + 0]) maxx = model->vertices[3 * i + 0]; if (minx > model->vertices[3 * i + 0]) minx = model->vertices[3 * i + 0]; if (maxy < model->vertices[3 * i + 1]) maxy = model->vertices[3 * i + 1]; if (miny > model->vertices[3 * i + 1]) miny = model->vertices[3 * i + 1]; if (maxz < model->vertices[3 * i + 2]) maxz = model->vertices[3 * i + 2]; if (minz > model->vertices[3 * i + 2]) minz = model->vertices[3 * i + 2]; } /* calculate model width, height, and depth */ dimensions[0] = maxx - minx; // dimensions[0] = glmAbs(maxx) + glmAbs(minx); dimensions[1] = maxy - miny; // dimensions[1] = glmAbs(maxy) + glmAbs(miny); dimensions[2] = maxz - minz; // dimensions[2] = glmAbs(maxz) + glmAbs(minz); } /* glmScale: Scales a model by a given amount. * * model - properly initialized GLMmodel structure * scale - scalefactor (0.5 = half as large, 2.0 = twice as large) */ GLvoid glmScale(GLMmodel* model, GLfloat scale) { GLuint i; for (i = 1; i <= model->numvertices; i++) { model->vertices[3 * i + 0] *= scale; model->vertices[3 * i + 1] *= scale; model->vertices[3 * i + 2] *= scale; } } /* glmReverseWinding: Reverse the polygon winding for all polygons in * this model. Default winding is counter-clockwise. Also changes * the direction of the normals. * * model - properly initialized GLMmodel structure */ GLvoid glmReverseWinding(GLMmodel* model) { GLuint i, swap; assert(model); for (i = 0; i < model->numtriangles; i++) { swap = T(i).vindices[0]; T(i).vindices[0] = T(i).vindices[2]; T(i).vindices[2] = swap; if (model->numnormals) { swap = T(i).nindices[0]; T(i).nindices[0] = T(i).nindices[2]; T(i).nindices[2] = swap; } if (model->numtexcoords) { swap = T(i).tindices[0]; T(i).tindices[0] = T(i).tindices[2]; T(i).tindices[2] = swap; } } /* reverse facet normals */ for (i = 1; i <= model->numfacetnorms; i++) { model->facetnorms[3 * i + 0] = -model->facetnorms[3 * i + 0]; model->facetnorms[3 * i + 1] = -model->facetnorms[3 * i + 1]; model->facetnorms[3 * i + 2] = -model->facetnorms[3 * i + 2]; } /* reverse vertex normals */ for (i = 1; i <= model->numnormals; i++) { model->normals[3 * i + 0] = -model->normals[3 * i + 0]; model->normals[3 * i + 1] = -model->normals[3 * i + 1]; model->normals[3 * i + 2] = -model->normals[3 * i + 2]; } } /* glmFacetNormals: Generates facet normals for a model (by taking the * cross product of the two vectors derived from the sides of each * triangle). Assumes a counter-clockwise winding. * * model - initialized GLMmodel structure */ GLvoid glmFacetNormals(GLMmodel* model) { GLuint i; GLfloat u[3]; GLfloat v[3]; assert(model); assert(model->vertices); /* clobber any old facetnormals */ if (model->facetnorms) free(model->facetnorms); /* allocate memory for the new facet normals */ model->numfacetnorms = model->numtriangles; model->facetnorms = (GLfloat*)malloc(sizeof(GLfloat) * 3 * (model->numfacetnorms + 1)); for (i = 0; i < model->numtriangles; i++) { model->triangles[i].findex = i+1; u[0] = model->vertices[3 * T(i).vindices[1] + 0] - model->vertices[3 * T(i).vindices[0] + 0]; u[1] = model->vertices[3 * T(i).vindices[1] + 1] - model->vertices[3 * T(i).vindices[0] + 1]; u[2] = model->vertices[3 * T(i).vindices[1] + 2] - model->vertices[3 * T(i).vindices[0] + 2]; v[0] = model->vertices[3 * T(i).vindices[2] + 0] - model->vertices[3 * T(i).vindices[0] + 0]; v[1] = model->vertices[3 * T(i).vindices[2] + 1] - model->vertices[3 * T(i).vindices[0] + 1]; v[2] = model->vertices[3 * T(i).vindices[2] + 2] - model->vertices[3 * T(i).vindices[0] + 2]; glmCross(u, v, &model->facetnorms[3 * (i+1)]); glmNormalize(&model->facetnorms[3 * (i+1)]); } } /* glmVertexNormals: Generates smooth vertex normals for a model. * First builds a list of all the triangles each vertex is in. Then * loops through each vertex in the the list averaging all the facet * normals of the triangles each vertex is in. Finally, sets the * normal index in the triangle for the vertex to the generated smooth * normal. If the dot product of a facet normal and the facet normal * associated with the first triangle in the list of triangles the * current vertex is in is greater than the cosine of the angle * parameter to the function, that facet normal is not added into the * average normal calculation and the corresponding vertex is given * the facet normal. This tends to preserve hard edges. The angle to * use depends on the model, but 90 degrees is usually a good start. * * model - initialized GLMmodel structure * angle - maximum angle (in degrees) to smooth across */ GLvoid glmVertexNormals(GLMmodel* model, GLfloat angle) { GLMnode* node; GLMnode* tail; GLMnode** members; GLfloat* normals; GLuint numnormals; GLfloat average[3]; GLfloat dot, cos_angle; GLuint i, avg; assert(model); assert(model->facetnorms); /* calculate the cosine of the angle (in degrees) */ cos_angle = cos(angle * M_PI / 180.0); /* nuke any previous normals */ if (model->normals) free(model->normals); /* allocate space for new normals */ model->numnormals = model->numtriangles * 3; /* 3 normals per triangle */ model->normals = (GLfloat*)malloc(sizeof(GLfloat)* 3* (model->numnormals+1)); /* allocate a structure that will hold a linked list of triangle indices for each vertex */ members = (GLMnode**)malloc(sizeof(GLMnode*) * (model->numvertices + 1)); for (i = 1; i <= model->numvertices; i++) members[i] = NULL; /* for every triangle, create a node for each vertex in it */ for (i = 0; i < model->numtriangles; i++) { node = (GLMnode*)malloc(sizeof(GLMnode)); node->index = i; node->next = members[T(i).vindices[0]]; members[T(i).vindices[0]] = node; node = (GLMnode*)malloc(sizeof(GLMnode)); node->index = i; node->next = members[T(i).vindices[1]]; members[T(i).vindices[1]] = node; node = (GLMnode*)malloc(sizeof(GLMnode)); node->index = i; node->next = members[T(i).vindices[2]]; members[T(i).vindices[2]] = node; } /* calculate the average normal for each vertex */ numnormals = 1; for (i = 1; i <= model->numvertices; i++) { /* calculate an average normal for this vertex by averaging the facet normal of every triangle this vertex is in */ node = members[i]; if (!node) fprintf(stderr, "glmVertexNormals(): vertex w/o a triangle\n"); average[0] = 0.0; average[1] = 0.0; average[2] = 0.0; avg = 0; while (node) { /* only average if the dot product of the angle between the two facet normals is greater than the cosine of the threshold angle -- or, said another way, the angle between the two facet normals is less than (or equal to) the threshold angle */ dot = glmDot(&model->facetnorms[3 * T(node->index).findex], &model->facetnorms[3 * T(members[i]->index).findex]); if (dot > cos_angle) { node->averaged = GL_TRUE; average[0] += model->facetnorms[3 * T(node->index).findex + 0]; average[1] += model->facetnorms[3 * T(node->index).findex + 1]; average[2] += model->facetnorms[3 * T(node->index).findex + 2]; avg = 1; /* we averaged at least one normal! */ } else { node->averaged = GL_FALSE; } node = node->next; } if (avg) { /* normalize the averaged normal */ glmNormalize(average); /* add the normal to the vertex normals list */ model->normals[3 * numnormals + 0] = average[0]; model->normals[3 * numnormals + 1] = average[1]; model->normals[3 * numnormals + 2] = average[2]; avg = numnormals; numnormals++; } /* set the normal of this vertex in each triangle it is in */ node = members[i]; while (node) { if (node->averaged) { /* if this node was averaged, use the average normal */ if (T(node->index).vindices[0] == i) T(node->index).nindices[0] = avg; else if (T(node->index).vindices[1] == i) T(node->index).nindices[1] = avg; else if (T(node->index).vindices[2] == i) T(node->index).nindices[2] = avg; } else { /* if this node wasn't averaged, use the facet normal */ model->normals[3 * numnormals + 0] = model->facetnorms[3 * T(node->index).findex + 0]; model->normals[3 * numnormals + 1] = model->facetnorms[3 * T(node->index).findex + 1]; model->normals[3 * numnormals + 2] = model->facetnorms[3 * T(node->index).findex + 2]; if (T(node->index).vindices[0] == i) T(node->index).nindices[0] = numnormals; else if (T(node->index).vindices[1] == i) T(node->index).nindices[1] = numnormals; else if (T(node->index).vindices[2] == i) T(node->index).nindices[2] = numnormals; numnormals++; } node = node->next; } } model->numnormals = numnormals - 1; /* free the member information */ for (i = 1; i <= model->numvertices; i++) { node = members[i]; while (node) { tail = node; node = node->next; free(tail); } } free(members); /* pack the normals array (we previously allocated the maximum number of normals that could possibly be created (numtriangles * 3), so get rid of some of them (usually alot unless none of the facet normals were averaged)) */ normals = model->normals; model->normals = (GLfloat*)malloc(sizeof(GLfloat)* 3* (model->numnormals+1)); for (i = 1; i <= model->numnormals; i++) { model->normals[3 * i + 0] = normals[3 * i + 0]; model->normals[3 * i + 1] = normals[3 * i + 1]; model->normals[3 * i + 2] = normals[3 * i + 2]; } free(normals); } GLvoid glmLinearTexture(GLMmodel* model) { GLMgroup *group; GLfloat dimensions[3]; GLfloat x, y, scalefactor; GLuint i; assert(model); if (model->texcoords) free(model->texcoords); model->numtexcoords = model->numvertices; model->texcoords=(GLfloat*)malloc(sizeof(GLfloat)*2*(model->numtexcoords+1)); glmDimensions(model, dimensions); scalefactor = 2.0 / glmAbs(glmMax(glmMax(dimensions[0], dimensions[1]), dimensions[2])); /* do the calculations */ for(i = 1; i <= model->numvertices; i++) { x = model->vertices[3 * i + 0] * scalefactor; y = model->vertices[3 * i + 2] * scalefactor; model->texcoords[2 * i + 0] = (x + 1.0) / 2.0; model->texcoords[2 * i + 1] = (y + 1.0) / 2.0; } /* go through and put texture coordinate indices in all the triangles */ group = model->groups; while(group) { for(i = 0; i < group->numtriangles; i++) { T(group->triangles[i]).tindices[0] = T(group->triangles[i]).vindices[0]; T(group->triangles[i]).tindices[1] = T(group->triangles[i]).vindices[1]; T(group->triangles[i]).tindices[2] = T(group->triangles[i]).vindices[2]; } group = group->next; } #if 0 printf("glmLinearTexture(): generated %d linear texture coordinates\n", model->numtexcoords); #endif } /* glmSpheremapTexture: Generates texture coordinates according to a * spherical projection of the texture map. Sometimes referred to as * spheremap, or reflection map texture coordinates. It generates * these by using the normal to calculate where that vertex would map * onto a sphere. Since it is impossible to map something flat * perfectly onto something spherical, there is distortion at the * poles. This particular implementation causes the poles along the X * axis to be distorted. * * model - pointer to initialized GLMmodel structure */ GLvoid glmSpheremapTexture(GLMmodel* model) { GLMgroup* group; GLfloat theta, phi, rho, x, y, z, r; GLuint i; assert(model); assert(model->normals); if (model->texcoords) free(model->texcoords); model->numtexcoords = model->numnormals; model->texcoords=(GLfloat*)malloc(sizeof(GLfloat)*2*(model->numtexcoords+1)); for (i = 1; i <= model->numnormals; i++) { z = model->normals[3 * i + 0]; /* re-arrange for pole distortion */ y = model->normals[3 * i + 1]; x = model->normals[3 * i + 2]; r = sqrt((x * x) + (y * y)); rho = sqrt((r * r) + (z * z)); if(r == 0.0) { theta = 0.0; phi = 0.0; } else { if(z == 0.0) phi = 3.14159265 / 2.0; else phi = acos(z / rho); if(y == 0.0) theta = 3.141592365 / 2.0; else theta = asin(y / r) + (3.14159265 / 2.0); } model->texcoords[2 * i + 0] = theta / 3.14159265; model->texcoords[2 * i + 1] = phi / 3.14159265; } /* go through and put texcoord indices in all the triangles */ group = model->groups; while(group) { for (i = 0; i < group->numtriangles; i++) { T(group->triangles[i]).tindices[0] = T(group->triangles[i]).nindices[0]; T(group->triangles[i]).tindices[1] = T(group->triangles[i]).nindices[1]; T(group->triangles[i]).tindices[2] = T(group->triangles[i]).nindices[2]; } group = group->next; } } /* glmDelete: Deletes a GLMmodel structure. * * model - initialized GLMmodel structure */ GLvoid glmDelete(GLMmodel* model) { GLMgroup* group; GLuint i; assert(model); if (model->pathname) free(model->pathname); if (model->mtllibname) free(model->mtllibname); if (model->vertices) free(model->vertices); if (model->normals) free(model->normals); if (model->texcoords) free(model->texcoords); if (model->facetnorms) free(model->facetnorms); if (model->triangles) free(model->triangles); if (model->materials) { for (i = 0; i < model->nummaterials; i++) free(model->materials[i].name); free(model->materials); } if (model->textures) { for (i = 0; i < model->numtextures; i++) { free(model->textures[i].name); glDeleteTextures(1,&model->textures[i].id); } free(model->textures); } while(model->groups) { group = model->groups; model->groups = model->groups->next; free(group->name); free(group->triangles); free(group); } free(model); } /* glmReadOBJ: Reads a model description from a Wavefront .OBJ file. * Returns a pointer to the created object which should be free'd with * glmDelete(). * * filename - name of the file containing the Wavefront .OBJ format data. */ GLMmodel* glmReadOBJ(char* filename) { GLMmodel* model; FILE* file; //if (call) call->loadcallback(0,"Loading Models..."); /* open the file */ file = fopen(filename, "r"); if (!file) { fprintf(stderr, "glmReadOBJ() failed: can't open data file \"%s\".\n", filename); exit(1); } /* allocate a new model */ model = (GLMmodel*)malloc(sizeof(GLMmodel)); model->pathname = strdup(filename); model->mtllibname = NULL; model->numvertices = 0; model->vertices = NULL; model->numnormals = 0; model->normals = NULL; model->numtexcoords = 0; model->texcoords = NULL; model->numfacetnorms = 0; model->facetnorms = NULL; model->numtriangles = 0; model->triangles = NULL; model->nummaterials = 0; model->materials = NULL; model->numtextures = 0; model->textures = NULL; model->numgroups = 0; model->groups = NULL; model->position[0] = 0.0; model->position[1] = 0.0; model->position[2] = 0.0; _glmTextureLoader = new CTextureLoader(); /* make a first pass through the file to get a count of the number of vertices, normals, texcoords & triangles */ glmFirstPass(model, file); /* allocate memory */ model->vertices = (GLfloat*)malloc(sizeof(GLfloat) * 3 * (model->numvertices + 1)); model->triangles = (GLMtriangle*)malloc(sizeof(GLMtriangle) * model->numtriangles); if (model->numnormals) { model->normals = (GLfloat*)malloc(sizeof(GLfloat) * 3 * (model->numnormals + 1)); } if (model->numtexcoords) { model->texcoords = (GLfloat*)malloc(sizeof(GLfloat) * 2 * (model->numtexcoords + 1)); } /* rewind to beginning of file and read in the data this pass */ rewind(file); glmSecondPass(model, file); /* close the file */ fclose(file); delete _glmTextureLoader; _glmTextureLoader = NULL; return model; } /* glmWriteOBJ: Writes a model description in Wavefront .OBJ format to * a file. * * model - initialized GLMmodel structure * filename - name of the file to write the Wavefront .OBJ format data to * mode - a bitwise or of values describing what is written to the file * GLM_NONE - render with only vertices * GLM_FLAT - render with facet normals * GLM_SMOOTH - render with vertex normals * GLM_TEXTURE - render with texture coords * GLM_COLOR - render with colors (color material) * GLM_MATERIAL - render with materials * GLM_COLOR and GLM_MATERIAL should not both be specified. * GLM_FLAT and GLM_SMOOTH should not both be specified. */ GLvoid glmWriteOBJ(GLMmodel* model, char* filename, GLuint mode) { GLuint i; FILE* file; GLMgroup* group; assert(model); /* do a bit of warning */ if (mode & GLM_FLAT && !model->facetnorms) { printf("glmWriteOBJ() warning: flat normal output requested " "with no facet normals defined.\n"); mode &= ~GLM_FLAT; } if (mode & GLM_SMOOTH && !model->normals) { printf("glmWriteOBJ() warning: smooth normal output requested " "with no normals defined.\n"); mode &= ~GLM_SMOOTH; } if (mode & GLM_TEXTURE && !model->texcoords) { printf("glmWriteOBJ() warning: texture coordinate output requested " "with no texture coordinates defined.\n"); mode &= ~GLM_TEXTURE; } if (mode & GLM_FLAT && mode & GLM_SMOOTH) { printf("glmWriteOBJ() warning: flat normal output requested " "and smooth normal output requested (using smooth).\n"); mode &= ~GLM_FLAT; } if (mode & GLM_COLOR && !model->materials) { printf("glmWriteOBJ() warning: color output requested " "with no colors (materials) defined.\n"); mode &= ~GLM_COLOR; } if (mode & GLM_MATERIAL && !model->materials) { printf("glmWriteOBJ() warning: material output requested " "with no materials defined.\n"); mode &= ~GLM_MATERIAL; } if (mode & GLM_COLOR && mode & GLM_MATERIAL) { printf("glmWriteOBJ() warning: color and material output requested " "outputting only materials.\n"); mode &= ~GLM_COLOR; } /* open the file */ file = fopen(filename, "w"); if (!file) { fprintf(stderr, "glmWriteOBJ() failed: can't open file \"%s\" to write.\n", filename); exit(1); } /* spit out a header */ fprintf(file, "# \n"); fprintf(file, "# Wavefront OBJ generated by GLM library\n"); fprintf(file, "# \n"); fprintf(file, "# GLM library\n"); fprintf(file, "# Nate Robins\n"); fprintf(file, "# [email protected]\n"); fprintf(file, "# http://www.pobox.com/~ndr\n"); fprintf(file, "# \n"); if (mode & GLM_MATERIAL && model->mtllibname) { fprintf(file, "\nmtllib %s\n\n", model->mtllibname); glmWriteMTL(model, filename, model->mtllibname); } /* spit out the vertices */ fprintf(file, "\n"); fprintf(file, "# %d vertices\n", model->numvertices); for (i = 1; i <= model->numvertices; i++) { fprintf(file, "v %f %f %f\n", model->vertices[3 * i + 0], model->vertices[3 * i + 1], model->vertices[3 * i + 2]); } /* spit out the smooth/flat normals */ if (mode & GLM_SMOOTH) { fprintf(file, "\n"); fprintf(file, "# %d normals\n", model->numnormals); for (i = 1; i <= model->numnormals; i++) { fprintf(file, "vn %f %f %f\n", model->normals[3 * i + 0], model->normals[3 * i + 1], model->normals[3 * i + 2]); } } else if (mode & GLM_FLAT) { fprintf(file, "\n"); fprintf(file, "# %d normals\n", model->numfacetnorms); for (i = 1; i <= model->numnormals; i++) { fprintf(file, "vn %f %f %f\n", model->facetnorms[3 * i + 0], model->facetnorms[3 * i + 1], model->facetnorms[3 * i + 2]); } } /* spit out the texture coordinates */ if (mode & GLM_TEXTURE) { fprintf(file, "\n"); fprintf(file, "# %d texcoords\n", model->numtexcoords); for (i = 1; i <= model->numtexcoords; i++) { fprintf(file, "vt %f %f\n", model->texcoords[2 * i + 0], model->texcoords[2 * i + 1]); } } fprintf(file, "\n"); fprintf(file, "# %d groups\n", model->numgroups); fprintf(file, "# %d faces (triangles)\n", model->numtriangles); fprintf(file, "\n"); group = model->groups; while(group) { fprintf(file, "g %s\n", group->name); if (mode & GLM_MATERIAL) fprintf(file, "usemtl %s\n", model->materials[group->material].name); for (i = 0; i < group->numtriangles; i++) { if (mode & GLM_SMOOTH && mode & GLM_TEXTURE) { fprintf(file, "f %d/%d/%d %d/%d/%d %d/%d/%d\n", T(group->triangles[i]).vindices[0], T(group->triangles[i]).nindices[0], T(group->triangles[i]).tindices[0], T(group->triangles[i]).vindices[1], T(group->triangles[i]).nindices[1], T(group->triangles[i]).tindices[1], T(group->triangles[i]).vindices[2], T(group->triangles[i]).nindices[2], T(group->triangles[i]).tindices[2]); } else if (mode & GLM_FLAT && mode & GLM_TEXTURE) { fprintf(file, "f %d/%d %d/%d %d/%d\n", T(group->triangles[i]).vindices[0], T(group->triangles[i]).findex, T(group->triangles[i]).vindices[1], T(group->triangles[i]).findex, T(group->triangles[i]).vindices[2], T(group->triangles[i]).findex); } else if (mode & GLM_TEXTURE) { fprintf(file, "f %d/%d %d/%d %d/%d\n", T(group->triangles[i]).vindices[0], T(group->triangles[i]).tindices[0], T(group->triangles[i]).vindices[1], T(group->triangles[i]).tindices[1], T(group->triangles[i]).vindices[2], T(group->triangles[i]).tindices[2]); } else if (mode & GLM_SMOOTH) { fprintf(file, "f %d//%d %d//%d %d//%d\n", T(group->triangles[i]).vindices[0], T(group->triangles[i]).nindices[0], T(group->triangles[i]).vindices[1], T(group->triangles[i]).nindices[1], T(group->triangles[i]).vindices[2], T(group->triangles[i]).nindices[2]); } else if (mode & GLM_FLAT) { fprintf(file, "f %d//%d %d//%d %d//%d\n", T(group->triangles[i]).vindices[0], T(group->triangles[i]).findex, T(group->triangles[i]).vindices[1], T(group->triangles[i]).findex, T(group->triangles[i]).vindices[2], T(group->triangles[i]).findex); } else { fprintf(file, "f %d %d %d\n", T(group->triangles[i]).vindices[0], T(group->triangles[i]).vindices[1], T(group->triangles[i]).vindices[2]); } } fprintf(file, "\n"); group = group->next; } fclose(file); } /* glmDraw: Renders the model to the current OpenGL context using the * mode specified. * * model - initialized GLMmodel structure * mode - a bitwise OR of values describing what is to be rendered. * GLM_NONE - render with only vertices * GLM_FLAT - render with facet normals * GLM_SMOOTH - render with vertex normals * GLM_TEXTURE - render with texture coords * GLM_COLOR - render with colors (color material) * GLM_MATERIAL - render with materials * GLM_COLOR and GLM_MATERIAL should not both be specified. * GLM_FLAT and GLM_SMOOTH should not both be specified. */ GLvoid glmDraw(GLMmodel* model, GLuint mode) { glmDraw(model,mode,0); } GLvoid glmDraw(GLMmodel* model, GLuint mode,char *drawonly) { /* static GLuint i; static GLMgroup* group; static GLMtriangle* triangle; static GLMmaterial* material; */ GLuint i; GLMgroup* group; GLMtriangle* triangle; GLMmaterial* material; GLuint textureID; assert(model); assert(model->vertices); /* do a bit of warning */ if (mode & GLM_FLAT && !model->facetnorms) { printf("glmDraw() warning: flat render mode requested " "with no facet normals defined.\n"); mode &= ~GLM_FLAT; } if (mode & GLM_SMOOTH && !model->normals) { printf("glmDraw() warning: smooth render mode requested " "with no normals defined.\n"); mode &= ~GLM_SMOOTH; } if (mode & GLM_TEXTURE && !model->texcoords) { printf("glmDraw() warning: texture render mode requested " "with no texture coordinates defined.\n"); mode &= ~GLM_TEXTURE; } if (mode & GLM_FLAT && mode & GLM_SMOOTH) { printf("glmDraw() warning: flat render mode requested " "and smooth render mode requested (using smooth).\n"); mode &= ~GLM_FLAT; } if (mode & GLM_COLOR && !model->materials) { printf("glmDraw() warning: color render mode requested " "with no materials defined.\n"); mode &= ~GLM_COLOR; } if (mode & GLM_MATERIAL && !model->materials) { printf("glmDraw() warning: material render mode requested " "with no materials defined.\n"); mode &= ~GLM_MATERIAL; } if (mode & GLM_COLOR && mode & GLM_MATERIAL) { printf("glmDraw() warning: color and material render mode requested " "using only material mode.\n"); mode &= ~GLM_COLOR; } if (mode & GLM_COLOR) glEnable(GL_COLOR_MATERIAL); else if (mode & GLM_MATERIAL) glDisable(GL_COLOR_MATERIAL); if (mode & GLM_TEXTURE) { glEnable(GL_TEXTURE_2D); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); } /* perhaps this loop should be unrolled into material, color, flat, smooth, etc. loops? since most cpu's have good branch prediction schemes (and these branches will always go one way), probably wouldn't gain too much? */ textureID = -1; group = model->groups; while (group) { if (drawonly) if (strcmp(group->name,drawonly)) { group=group->next; continue; } material = &model->materials[group->material]; if (material) textureID = material->textureID; else textureID=-1; if (mode & GLM_MATERIAL) { glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, material->ambient); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, material->diffuse); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, material->specular); glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, material->shininess); } if (mode & GLM_TEXTURE) { if(textureID == -1) glBindTexture(GL_TEXTURE_2D, 0); else glBindTexture(GL_TEXTURE_2D, model->textures[textureID].id); } if (mode & GLM_COLOR) { glColor3fv(material->diffuse); } glBegin(GL_TRIANGLES); for (i = 0; i < group->numtriangles; i++) { triangle = &T(group->triangles[i]); #ifdef DebugVisibleSurfaces if (!triangle->visible) continue; #endif if (mode & GLM_FLAT) glNormal3fv(&model->facetnorms[3 * triangle->findex]); if (mode & GLM_SMOOTH) glNormal3fv(&model->normals[3 * triangle->nindices[0]]); if (mode & GLM_TEXTURE) glTexCoord2fv(&model->texcoords[2 * triangle->tindices[0]]); glVertex3fv(&model->vertices[3 * triangle->vindices[0]]); if (mode & GLM_SMOOTH) glNormal3fv(&model->normals[3 * triangle->nindices[1]]); if (mode & GLM_TEXTURE) { //if (textureID==-1) printf("Warning: GLM_TEXTURE este on dar nu este setata nici o textura in material!"); glTexCoord2fv(&model->texcoords[2 * triangle->tindices[1]]); } glVertex3fv(&model->vertices[3 * triangle->vindices[1]]); if (mode & GLM_SMOOTH) glNormal3fv(&model->normals[3 * triangle->nindices[2]]); if (mode & GLM_TEXTURE) glTexCoord2fv(&model->texcoords[2 * triangle->tindices[2]]); glVertex3fv(&model->vertices[3 * triangle->vindices[2]]); } glEnd(); group = group->next; } } /* glmList: Generates and returns a display list for the model using * the mode specified. * * model - initialized GLMmodel structure * mode - a bitwise OR of values describing what is to be rendered. * GLM_NONE - render with only vertices * GLM_FLAT - render with facet normals * GLM_SMOOTH - render with vertex normals * GLM_TEXTURE - render with texture coords * GLM_COLOR - render with colors (color material) * GLM_MATERIAL - render with materials * GLM_COLOR and GLM_MATERIAL should not both be specified. * GLM_FLAT and GLM_SMOOTH should not both be specified. */ GLuint glmList(GLMmodel* model, GLuint mode) { GLuint list; list = glGenLists(1); glNewList(list, GL_COMPILE); glmDraw(model, mode); glEndList(); return list; } /* glmWeld: eliminate (weld) vectors that are within an epsilon of * each other. * * model - initialized GLMmodel structure * epsilon - maximum difference between vertices * ( 0.00001 is a good start for a unitized model) * */ GLvoid glmWeld(GLMmodel* model, GLfloat epsilon) { GLfloat* vectors; GLfloat* copies; GLuint numvectors; GLuint i; /* vertices */ numvectors = model->numvertices; vectors = model->vertices; copies = glmWeldVectors(vectors, &numvectors, epsilon); #if 0 printf("glmWeld(): %d redundant vertices.\n", model->numvertices - numvectors - 1); #endif for (i = 0; i < model->numtriangles; i++) { T(i).vindices[0] = (GLuint)vectors[3 * T(i).vindices[0] + 0]; T(i).vindices[1] = (GLuint)vectors[3 * T(i).vindices[1] + 0]; T(i).vindices[2] = (GLuint)vectors[3 * T(i).vindices[2] + 0]; } /* free space for old vertices */ free(vectors); /* allocate space for the new vertices */ model->numvertices = numvectors; model->vertices = (GLfloat*)malloc(sizeof(GLfloat) * 3 * (model->numvertices + 1)); /* copy the optimized vertices into the actual vertex list */ for (i = 1; i <= model->numvertices; i++) { model->vertices[3 * i + 0] = copies[3 * i + 0]; model->vertices[3 * i + 1] = copies[3 * i + 1]; model->vertices[3 * i + 2] = copies[3 * i + 2]; } free(copies); } /* glmReadPPM: read a PPM raw (type P6) file. The PPM file has a header * that should look something like: * * P6 * # comment * width height max_value * rgbrgbrgb... * * where "P6" is the magic cookie which identifies the file type and * should be the only characters on the first line followed by a * carriage return. Any line starting with a # mark will be treated * as a comment and discarded. After the magic cookie, three integer * values are expected: width, height of the image and the maximum * value for a pixel (max_value must be < 256 for PPM raw files). The * data section consists of width*height rgb triplets (one byte each) * in binary format (i.e., such as that written with fwrite() or * equivalent). * * The rgb data is returned as an array of unsigned chars (packed * rgb). The malloc()'d memory should be free()'d by the caller. If * an error occurs, an error message is sent to stderr and NULL is * returned. * * filename - name of the .ppm file. * width - will contain the width of the image on return. * height - will contain the height of the image on return. * */ GLubyte* glmReadPPM(char* filename, int* width, int* height) { FILE* fp; int i, w, h, d; unsigned char* image; char head[70]; /* max line <= 70 in PPM (per spec). */ fp = fopen(filename, "rb"); if (!fp) { perror(filename); return NULL; } /* grab first two chars of the file and make sure that it has the correct magic cookie for a raw PPM file. */ fgets(head, 70, fp); if (strncmp(head, "P6", 2)) { fprintf(stderr, "%s: Not a raw PPM file\n", filename); return NULL; } /* grab the three elements in the header (width, height, maxval). */ i = 0; while(i < 3) { fgets(head, 70, fp); if (head[0] == '#') /* skip comments. */ continue; if (i == 0) i += sscanf(head, "%d %d %d", &w, &h, &d); else if (i == 1) i += sscanf(head, "%d %d", &h, &d); else if (i == 2) i += sscanf(head, "%d", &d); } /* grab all the image data in one fell swoop. */ image = (unsigned char*)malloc(sizeof(unsigned char)*w*h*3); fread(image, sizeof(unsigned char), w*h*3, fp); fclose(fp); *width = w; *height = h; return image; } #if 0 /* normals */ if (model->numnormals) { numvectors = model->numnormals; vectors = model->normals; copies = glmOptimizeVectors(vectors, &numvectors); printf("glmOptimize(): %d redundant normals.\n", model->numnormals - numvectors); for (i = 0; i < model->numtriangles; i++) { T(i).nindices[0] = (GLuint)vectors[3 * T(i).nindices[0] + 0]; T(i).nindices[1] = (GLuint)vectors[3 * T(i).nindices[1] + 0]; T(i).nindices[2] = (GLuint)vectors[3 * T(i).nindices[2] + 0]; } /* free space for old normals */ free(vectors); /* allocate space for the new normals */ model->numnormals = numvectors; model->normals = (GLfloat*)malloc(sizeof(GLfloat) * 3 * (model->numnormals + 1)); /* copy the optimized vertices into the actual vertex list */ for (i = 1; i <= model->numnormals; i++) { model->normals[3 * i + 0] = copies[3 * i + 0]; model->normals[3 * i + 1] = copies[3 * i + 1]; model->normals[3 * i + 2] = copies[3 * i + 2]; } free(copies); } /* texcoords */ if (model->numtexcoords) { numvectors = model->numtexcoords; vectors = model->texcoords; copies = glmOptimizeVectors(vectors, &numvectors); printf("glmOptimize(): %d redundant texcoords.\n", model->numtexcoords - numvectors); for (i = 0; i < model->numtriangles; i++) { for (j = 0; j < 3; j++) { T(i).tindices[j] = (GLuint)vectors[3 * T(i).tindices[j] + 0]; } } /* free space for old texcoords */ free(vectors); /* allocate space for the new texcoords */ model->numtexcoords = numvectors; model->texcoords = (GLfloat*)malloc(sizeof(GLfloat) * 2 * (model->numtexcoords + 1)); /* copy the optimized vertices into the actual vertex list */ for (i = 1; i <= model->numtexcoords; i++) { model->texcoords[2 * i + 0] = copies[2 * i + 0]; model->texcoords[2 * i + 1] = copies[2 * i + 1]; } free(copies); } #endif #if 0 /* look for unused vertices */ /* look for unused normals */ /* look for unused texcoords */ for (i = 1; i <= model->numvertices; i++) { for (j = 0; j < model->numtriangles; i++) { if (T(j).vindices[0] == i || T(j).vindices[1] == i || T(j).vindices[1] == i) break; } } #endif GLuint glmLoadTexture(char *filename, GLboolean alpha, GLboolean repeat, GLboolean filtering, GLboolean mipmaps, GLfloat *texcoordwidth, GLfloat *texcoordheight) { GLuint tex; int pixelsize; int filter_min, filter_mag; int xSize2, ySize2; // skip spaces at the beginnig of the filename char *name = filename; while (*name==' ') name++; CImage *image; if(_glmTextureLoader->Load(name, image) != true) { char errorString[256]; sprintf(errorString, "Error reading texture: %s \n", name); CError::FatalError(errorString); } char tmpString[256]; sprintf(tmpString, "Loaded texture: %s", name); CError::Warning(tmpString); switch(image->GetFormat()) { case GL_RGB: pixelsize = 3; break; case GL_RGBA: pixelsize = 4; break; default: printf( "glmLoadTexture(): unknown type 0x%x", image->GetFormat()); pixelsize = 0; break; } if((pixelsize*image->GetWidth()) % 4 == 0) glPixelStorei(GL_UNPACK_ALIGNMENT, 4); else glPixelStorei(GL_UNPACK_ALIGNMENT, 1); xSize2 = image->GetWidth(); ySize2 = image->GetHeight(); glGenTextures(1, &tex); glBindTexture(GL_TEXTURE_2D, tex); if(filtering) { filter_min = (mipmaps) ? GL_LINEAR_MIPMAP_LINEAR : GL_LINEAR; filter_mag = GL_LINEAR; } else { filter_min = (mipmaps) ? GL_NEAREST_MIPMAP_NEAREST : GL_NEAREST; filter_mag = GL_NEAREST; } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filter_min); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filter_mag); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, (repeat) ? GL_REPEAT : GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, (repeat) ? GL_REPEAT : GL_CLAMP); if(mipmaps) gluBuild2DMipmaps(GL_TEXTURE_2D, image->GetComponents(), xSize2, ySize2, image->GetFormat(), GL_UNSIGNED_BYTE, image->GetPixels()); else glTexImage2D(GL_TEXTURE_2D, 0, image->GetComponents(), xSize2, ySize2, 0, image->GetFormat(), GL_UNSIGNED_BYTE, image->GetPixels()); delete image; *texcoordwidth = xSize2; // size of texture coords *texcoordheight = ySize2; return tex; }
[ "roman.polasek@defb9fe8-8568-b3c7-aa61-90d022bbe42a" ]
[ [ [ 1, 2162 ] ] ]
9f9a797ff522c3701095799bb03f6cc16ad678e5
974a20e0f85d6ac74c6d7e16be463565c637d135
/trunk/coreLibrary_200/source/newton/Newton.cpp
78398236c3e1e0ff73e32308f96f8cfd4a023fb6
[]
no_license
Naddiseo/Newton-Dynamics-fork
cb0b8429943b9faca9a83126280aa4f2e6944f7f
91ac59c9687258c3e653f592c32a57b61dc62fb6
refs/heads/master
2021-01-15T13:45:04.651163
2011-11-12T04:02:33
2011-11-12T04:02:33
2,759,246
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
419,925
cpp
/* * Copyright (c) <2003-2011> <Julio Jerez, Newton Game Dynamics> * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. */ #include "NewtonStdAfx.h" #include "Newton.h" #include "NewtonClass.h" #ifdef _WIN32 # ifdef _DEBUG //#define DG_USED_DEBUG_EXCEPTIONS # endif // _DEBUG #endif // _WIN32 #ifdef _DEBUG void TraceFuntionName(const char *name) { //static int trace; //dgTrace(("%d %s\n", trace, name)); dgTrace(("%s\n", name)); } //#define TRACE_FUNTION(name) TraceFuntionName (name) # define TRACE_FUNTION(name) #else # define TRACE_FUNTION(name) #endif // _DEBUG #ifndef _NEWTON_STATIC_LIB # ifdef __MINGW32__ int main(int argc, char* argv[]) { return 0; } # endif // _MINGW32__ BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { return TRUE; } #endif // _NEWTON_STATIC_LIB //#define SAVE_COLLISION #ifdef SAVE_COLLISION void SerializeFile(void* serializeHandle, const void* buffer, size_t size) { fwrite(buffer, size, 1, (FILE*) serializeHandle); } void DeSerializeFile(void* serializeHandle, void* buffer, size_t size) { fread(buffer, size, 1, (FILE*) serializeHandle); } void SaveCollision(const NewtonCollision* collisionPtr) { FILE* file; //save the collision file file = fopen("collisiontest.bin", "wb"); //SerializeFile(file, MAGIC_NUMBER, strlen(MAGIC_NUMBER) + 1); NewtonCollisionSerialize(collisionPtr, SerializeFile, file); fclose(file); } #endif // SAVE_COLLISION /* * *dFloat* globalScale - global scale factor that will scale all internal tolerance. * Remarks: the physics system in theory should be dimensionless, however in practice the engine have to be implemented with * limited precision floating numbers and is also built for real-time simulation, it is inevitable that tolerances have to be used in order to increase performance, and * reduce instabilities. These tolerances make the engine dimension dependent, for example let say a rigid body is considered at rest when * its velocity is less than 0.01 units per second for some frames. For a program using meters as unit this translate to 0.01 meters per second, * however for a program using centimeter this translate to 0.0001 meter per second, since the precession of speed is independent of the unit system, * this means that in the second system the engine has to work much harder to bring the body to rest. A solution for this is to scale all tolerances * to match the unit system. The argument *globalScale* must be a constant to convert the unit system in the game to meters, for example if in your game you are using 39 units is a meter, * the *globaScale* must be 39. The exact conversion factor does not have to be exact, but the closer it is to reality the better performance the application will get. * Applications that are already using meters as the unit system must pass 1.0 as *globalSscale*. */ /*! * Return the exact amount of memory use by the engine and any given time time. * * @return * Total memory use by the engine. * * @remarks * This function is useful for application to determine if the memory * use by the engine is balanced at all time. * * @see * NewtonCreate */ int NewtonGetMemoryUsed() { //Newton* world; //dgMemoryAllocator* allocator; TRACE_FUNTION(__FUNCTION__); //world = (Newton*)newtonWorld; //allocator = world->dgWorld::GetAllocator(); return dgGetMemoryUsed(); } void NewtonSetMemorySystem(NewtonAllocMemory mallocFnt, NewtonFreeMemory mfreeFnt) { dgMemFree _free; dgMemAlloc _malloc; TRACE_FUNTION(__FUNCTION__); if (mallocFnt && mfreeFnt) { _malloc = (dgMemAlloc) mallocFnt; _free = (dgMemFree) mfreeFnt; } else { _malloc = (dgMemAlloc) Newton::DefaultAllocMemory; _free = (dgMemFree) Newton::DefaultFreeMemory; } dgSetGlobalAllocators(_malloc, _free); } // *************************************************************************************************************** // // Name: World interface // // *************************************************************************************************************** /*! * Create an instance of the Newton world. * * @return * A pointer to an instance of the Newton world. * * @remarks * This function must be called before any of the other API functions. * * @see * NewtonDestroy, * NewtonDestroyAllBodies */ NewtonWorld* NewtonCreate() { TRACE_FUNTION(__FUNCTION__); dgMemoryAllocator* const allocator = new dgMemoryAllocator(); dFloat p0[4]; dFloat p1[4]; NewtonWorld* const world = (NewtonWorld*) new (allocator) Newton( dgFloat32(1.0f), allocator); p0[0] = -100.0f; p0[1] = -100.0f; p0[2] = -100.0f; p1[0] = 100.0f; p1[1] = 100.0f; p1[2] = 100.0f; NewtonSetWorldSize(world, p0, p1); return world; } /*! * Destroy an instance of the Newton world. * * @param newtonWorld * Is the pointer to the Newton world. * * @remarks * This function will destroy the entire Newton world. * * @see * NewtonCreate, * NewtonDestroyAllBodies */ void NewtonDestroy(const NewtonWorld* const newtonWorld) { TRACE_FUNTION(__FUNCTION__); Newton* const world = (Newton*) newtonWorld; dgMemoryAllocator* const allocator = world->dgWorld::GetAllocator(); delete world; delete allocator; } // Name: NewtonInvalidateCache // Reset all internal states of the engine. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // // Remarks: When an application wants to reset the state of all the objects in the world to a predefined initial condition, // just setting the initial position and velocity is not sufficient to reproduce equal runs since the engine maintain // there are internal states that in order to take advantage of frame to frame coherence. // In this cases this function will reset all of the internal states. // // Remarks: This function must be call outside of a Newton Update. this function should only be used for special case of synchronization, // using it as part of the simulation loop will severally affect the engine performance. // // See also: NewtonUpdate void NewtonInvalidateCache(const NewtonWorld* const newtonWorld) { TRACE_FUNTION(__FUNCTION__); Newton* const world = (Newton *) newtonWorld; world->FlushCache(); } // Name: NewtonGetGlobalScale // Get the global scale factor. // // Remarks: the physics system in theory should be dimensionless, however in practice the engine have to be implemented with // limited precision floating numbers and is also built for real-time simulation, it is inevitable that tolerances have to be used in order to increase performance, and // reduce instabilities. These tolerances make the engine dimension dependent, for example let say a rigid body is considered at rest when // its velocity is less than 0.01 units per second for some frames. For a program using meters as unit this translate to 0.01 meters per second, // however for a program using centimeter this translate to 0.0001 meter per second, since the precession of speed is independent of the unit system, // this means that in the second system the engine has to work much harder to bring the body to rest. A solution for this is to scale all tolerances // to match the unit system. The argument *globalScale* must be a constant to convert the unit system in the game to meters, for example if in your game you are using 39 units is a meter, // the *globaScale* must be 39. The exact conversion factor does not have to be exact, but the closer it is to reality the better performance the application will get. // Applications that are already using meters as the unit system must pass 1.0 as *globalScale*. // //See also: NewtonCreate //dFloat NewtonGetGlobalScale(const NewtonWorld* const newtonWorld) //{ // Newton* world; // world = (Newton *) newtonWorld; // return world->GetGlobalScale(); // return dgFloat32(1.0f); //} // Name: NewtonSetPlatformArchitecture // Set the current platform hardware architecture. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world // *int* model - model of operation 0 = default, 1 = medium, n = best. // // Return: Nothing // // Remarks: This function allows the application to configure the Newton to take advantage // for specific hardware architecture in the same platform. // // 0: force the hardware lower common denominator for the running platform. // // 1: will try to use common floating point enhancement like special instruction set // on the specific architecture. This mode made lead to result that differ from mode 1 and 2 as the accumulation // round off errors maybe different. // // Remarks: the only hardware mode guarantee to work is mode 0. all other are only // hints to the engine, for example setting mode 1 will take not effect on CPUs without // specially floating point instructions set. // // See also: NewtonGetPlatformArchitecture void NewtonSetPlatformArchitecture(const NewtonWorld* const newtonWorld, int mode) { TRACE_FUNTION(__FUNCTION__); Newton* const world = (Newton *) newtonWorld; world->SetHardwareMode(mode); } // Name: NewtonGetPlatformArchitecture // Get the current platform hardware architecture. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world // *char* *description - pointer to a string to contain a description of the current architecture // // Return: index indicating the current platform architecture. // // Remarks: if *description* is not NULL, then is must be at least 32 characters long. // // Remarks: This function allows the application to configure the Newton to take advantage // for specific hardware architecture in the same platform. // // 0: force the hardware lower common denominator for the running platform. // // 1: will try to use common floating point enhancement like special instruction set // on the specific architecture. This mode made lead to result that differ from mode 1 and 2 as the accumulation // round off errors maybe different. // // Remarks: the only hardware mode guarantee to work is mode 0. all other are only // hints to the engine, for example setting mode 1 will take not effect on CPUs without // specially floating point instructions set. // // See also: NewtonSetPlatformArchitecture int NewtonGetPlatformArchitecture(const NewtonWorld* const newtonWorld, char* description) { TRACE_FUNTION(__FUNCTION__); Newton* const world = (Newton *) newtonWorld; return world->GetHardwareMode(description); } // Name: NewtonWorldCriticalSectionLock // this function block all other threads from executing the same subsequent code simultaneously. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // // Remarks: this function should use to present racing conditions when when a call back ins executed form a mutithreaded loop. // In general most call back are thread safe when they do not write to object outside the scope of the call back. // this means for example that the application can modify values of object pointed by the arguments and or call that function // that are allowed to be call for such callback. // There are cases, however, when the application need to collect data for the client logic, example of such case are collecting // information to display debug information, of collecting data for feedback. // In these situations it is possible the the same critical code could be execute at the same time but several thread causing unpredictable side effect. // so it is necessary to block all of the thread from executing any pieces of critical code. // // Remarks: Not calling function *NewtonWorldCriticalSectionUnlock* will result on the engine going into an infinite loop. // // Remarks: it is important that the critical section wrapped by functions *NewtonWorldCriticalSectionLock* and // *NewtonWorldCriticalSectionUnlock* be keep small if the application is using the multi threaded functionality of the engine // no doing so will lead to serialization of the parallel treads since only one thread can run the a critical section at a time. // // Return: Nothing. // // See also: NewtonWorldCriticalSectionUnlock void NewtonWorldCriticalSectionLock(const NewtonWorld* const newtonWorld) { TRACE_FUNTION(__FUNCTION__); Newton* const world = (Newton *) newtonWorld; world->dgGetUserLock(); } // Name: NewtonWorldCriticalSectionUnlock // this function block all other threads from executing the same subsequent code simultaneously. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // // // Remarks: this function should use to present racing conditions when when a call back ins executed form a mutithreaded loop. // In general most call back are thread safe when they do not write to object outside the scope of the call back. // this means for example that the application can modify values of object pointed by the arguments and or call that function // that are allowed to be call for such callback. // There are cases, however, when the application need to collect data for the client logic, example of such case are collecting // information to display debug information, of collecting data for feedback. // In these situations it is possible the the same critical code could be execute at the same time but several thread causing unpredictable side effect. // so it is necessary to block all of the thread from executing any pieces of critical code. // // Remarks: it is important that the critical section wrapped by functions *NewtonWorldCriticalSectionLock* and // *NewtonWorldCriticalSectionUnlock* be keep small if the application is using the multi threaded functionality of the engine // no doing so will lead to serialization of the parallel treads since only one thread can run the a critical section at a time. // // Return: Nothing. // // See also: NewtonWorldCriticalSectionLock void NewtonWorldCriticalSectionUnlock(const NewtonWorld* const newtonWorld) { TRACE_FUNTION(__FUNCTION__); Newton* const world = (Newton *) newtonWorld; world->dgReleasedUserLock(); } // Name: NewtonSetThreadsCount // Set the maximum number of thread the engine is allowed to use by the application. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world // *int* threads - max number of threaded allowed // // Return: Nothing // // Remarks: The maximum number of threaded is set on initialization to the maximum number of CPU in the system. // // Remarks: The engine will only allow a maximum number of thread equal are lower to the maximum number of cores visible in the system. // if *threads* is set to a value larger that then number of logical CPUs in the system, the *threads* will be clamped to the number of logical CPUs. // // Remarks: the function is only only have effect on the multi core version of the engine. // // See also: NewtonGetThreadNumber, NewtonGetThreadsCount void NewtonSetThreadsCount(const NewtonWorld* const newtonWorld, int threads) { TRACE_FUNTION(__FUNCTION__); Newton* const world = (Newton *) newtonWorld; world->SetThreadsCount(threads); } // Name: NewtonGetThreadsCount // Get the total number of thread running in the engine. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world // // Return: number threads // // Remarks: The maximum number of threaded is set on initialization to the maximum number of CPU in the system. // // Remarks: the function will always return 1 on the none multi core version of the library.. // // See also: NewtonGetThreadNumber, NewtonSetThreadsCount, NewtonSetMultiThreadSolverOnSingleIsland int NewtonGetThreadsCount(const NewtonWorld* const newtonWorld) { TRACE_FUNTION(__FUNCTION__); Newton* const world = (Newton *) newtonWorld; return world->GetThreadsCount(); } // Name: NewtonGetMaxThreadsCount // Get the maximu number of thread abialble. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world // // Return: number threads // // Remarks: The maximum number of threaded is set on initialization to the maximum number of CPU in the system. // // Remarks: the function will always return 1 on the none multi core version of the library.. // // See also: NewtonGetThreadNumber, NewtonSetThreadsCount, NewtonSetMultiThreadSolverOnSingleIsland int NewtonGetMaxThreadsCount(const NewtonWorld* const newtonWorld) { TRACE_FUNTION(__FUNCTION__); Newton* const world = (Newton *) newtonWorld; return world->GetMaxThreadsCount(); } /* // Name: NewtonGetThreadNumber // Get the current thread the Engine is running // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world // // Return: the index to the current workir thread runnin the call back. -1 if the function is called ourxoed of a call back // // Remarks: This function let application to read the current thread running in a callback // // Remarks: the function will always return 1 on the none multi core version of the library.. // // See also: NewtonGetThreadsCount, NewtonSetThreadsCount, NewtonSetMultiThreadSolverOnSingleIsland int NewtonGetThreadNumber(const NewtonWorld* const newtonWorld) { Newton* world; world = (Newton *)newtonWorld; TRACE_FUNTION(__FUNCTION__); return world->GetThreadNumber(); } */ // Name: NewtonSetMultiThreadSolverOnSingleIsland // Enable or disable solver to resolve constraint forces in multi threaded mode when large island configurations. Mode is disabled by default. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world // *int* mode - solver mode 1 enable parallel mode 0 disable parallel mode, default // // Return: Nothing // // Remarks: When running in multi threaded mode it is not always faster to calculate constraint forces in parallel. // there reasons for this are: // 1 - there is a significant software cost for setting threads both in memory and instructions overhead. // 2 - different systems have different cost for running separate threads in a share memory environment // 3 - numerical algorithms have decreased converge rate when implemented in parallel, typical lost of converge can be as high as half // of the of the sequential version, for this reason the parallel version require higher number of interaction to achieve similar convergence. // // Remarks: It is recommended this option is enabled on system with more than two cores, since the performance gain in a dual core system are marginally better. // at the very list the application must test the option to verify the performance gains. // // Remarks: disabling or enabling this option have not impact on the execution of the any of the other subsystems of the engine. // // See also: NewtonGetThreadsCount, NewtonSetThreadsCount void NewtonSetMultiThreadSolverOnSingleIsland( const NewtonWorld* const newtonWorld, int mode) { Newton* world; world = (Newton *) newtonWorld; TRACE_FUNTION(__FUNCTION__); world->EnableThreadOnSingleIsland(mode); } int NewtonGetMultiThreadSolverOnSingleIsland( const NewtonWorld* const newtonWorld) { Newton* world; world = (Newton *) newtonWorld; TRACE_FUNTION(__FUNCTION__); return world->GetThreadOnSingleIsland(); } // Name: NewtonSetSolverModel // Set the solver precision mode. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world // *int* model - model of operation 0 = exact, 1 = adaptive, n = linear. The default is exact. // // Return: Nothing // // Remarks: This function allows the application to configure the Newton solver to work in three different modes. // // 0: Is the exact mode. This is good for application where precision is more important than speed, ex: realistic simulation. // // 1: Is the adaptive mode, the solver is not as exact but the simulation will still maintain a high degree of accuracy. // This mode is good for applications were a good degree of stability is important but not as important as speed. // // n: Linear mode. The solver will not try to reduce the joints relative acceleration errors to below some limit, // instead it will perform up to n passes over the joint configuration each time reducing the acceleration error, // but it will terminate when the number of passes is exhausted regardless of the error magnitude. // In general this is the fastest mode and is is good for applications where speed is the only important factor, ex: video games. // // Remarks: the adaptive friction model combined with the linear model make for the fastest possible configuration // of the Newton solver. This setup is best for games. // If you need the best realistic behavior, we recommend the use of the exact solver and exact friction model which are the defaults. // // See also: NewtonSetFrictionModel, NewtonGetThreadNumber void NewtonSetSolverModel(const NewtonWorld* const newtonWorld, int model) { Newton* world; world = (Newton *) newtonWorld; TRACE_FUNTION(__FUNCTION__); world->SetSolverMode(model); } // Name: NewtonSetFrictionModel // Set coulomb model of friction. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world // *int* model - friction model; 0 = exact coulomb, 1 = adaptive coulomb, The default is exact. // // Return: Nothing. // // Remarks: This function allows the application to chose between and exact or an adaptive coulomb friction model // // 0: Is the exact model. Friction forces are calculated in each frame. // This model is good for applications where precision is more important than speed, ex: realistic simulation. // // 1: Is the adaptive model. Here values from previous frames are used to determine the maximum friction values of the current frame. // This is about 10% faster than the exact model however it may introduce strange friction behaviors. For example a // bouncing object tumbling down a ramp will act as a friction less object because the contacts do not have continuity. // In general each time a new contact is generated the friction value is zero, only if the contact persist a non zero // friction values is used. The second effect is that if a normal force is very strong, and if the contact is suddenly // destroyed, a very strong friction force will be generated at the contact point making the object react in a non-familiar way. // // Remarks: the adaptive friction model combined with the linear model make for the fastest possible configuration // of the Newton solver. This setup is best for games. // If you need the best realistic behavior, we recommend the use of the exact solver and exact friction model which are the defaults. // // See also: NewtonSetSolverModel void NewtonSetFrictionModel(const NewtonWorld* const newtonWorld, int model) { Newton* world; world = (Newton *) newtonWorld; TRACE_FUNTION(__FUNCTION__); world->SetFrictionMode(model); } // Name: NewtonSetPerformanceClock // Set performance Counter callback. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world // *NewtonGetTicksCountCallback* callback - application define callback // // Remarks: The application can use this function to profile Newton. *NewtonGetTicksCountCallback* callback is a // function call back that should return and absolute time since the the application started. // // Return: Nothing. // // See also: NewtonReadPerformanceTicks void NewtonSetPerformanceClock(const NewtonWorld* const newtonWorld, NewtonGetTicksCountCallback callback) { Newton* world; world = (Newton *) newtonWorld; TRACE_FUNTION(__FUNCTION__); world->SetPerfomanceCounter((OnGetPerformanceCountCallback) callback); } // Name: NewtonReadPerformanceTicks // Get the number of ticks used by the engine in one of the major components // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world // *unsigned* performanceEntry - index to one of the engine internal components. // // Remarks: there are 9 hierarchical counters // // NEWTON_PROFILER_WORLD_UPDATE: measure total ticks in each update call // NEWTON_PROFILER_COLLISION_UPDATE: total ticks in each collision and contact calculation // NEWTON_PROFILER_COLLISION_UPDATE_BROAD_PHASE: measure ticks on colliding pairs. // NEWTON_PROFILER_COLLISION_UPDATE_NARROW_PHASE: measure ticks calculating contacts for each colliding pair. // NEWTON_PROFILER_DYNAMICS_UPDATE: measure ticks on solving constraints, contact inter penetration, and integration // NEWTON_PROFILER_DYNAMICS_CONSTRAINT_GRAPH: measure ticks solving contacts and constraint graph interconnectivity. // NEWTON_PROFILER_DYNAMICS_BUILD_MASS_MATRIX: measure ticks solving preparing constraint matrix // NEWTON_PROFILER_DYNAMICS_SOLVE_CONSTRAINT_GRAPH: measure tick solving constraint matrix and calculating reaction forces and integration. // // Remarks: This function will return zero unless the application had previous // set a performance counter callback by calling the function *NewtonSetPerformanceClock* // // Return: Ticks count used by application in lass call to *NewtonUpdate* // // See also: NewtonReadPerformanceTicks, NewtonUpdate unsigned NewtonReadPerformanceTicks(const NewtonWorld* const newtonWorld, unsigned performanceEntry) { Newton* world; world = (Newton *) newtonWorld; TRACE_FUNTION(__FUNCTION__); return world->GetPerfomanceTicks(performanceEntry); } unsigned NewtonReadThreadPerformanceTicks(const NewtonWorld* newtonWorld, unsigned threadIndex) { Newton* const world = (Newton *) newtonWorld; TRACE_FUNTION(__FUNCTION__); return world->GetThreadPerfomanceTicks(threadIndex); } #ifdef DG_USED_DEBUG_EXCEPTIONS dgInt32 ExecptionHandler (void *exceptPtr) { EXCEPTION_RECORD *record; record = ((EXCEPTION_POINTERS *)exceptPtr)->ExceptionRecord; // if (record->ExceptionCode != EXCEPTION_ACCESS_VIOLATION) { // return 0; // } return 1; } #endif // Name: NewtonUpdate // Advance the simulation by an amount of time. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world // *dFloat* timestep - time step in seconds // // Return: Nothing // // Remarks: This function will advance the simulation by the amount of time specified by *timestep*. The Newton Engine does // not perform sub-steps, and does not need tuning parameters. It is the responsibility of the application to // ensure that *timestep* is small enough to guarantee physics stability. // // Return: This function call NewtonCollisionUpdate at the lower level to get the colliding contacts. // // See also: NewtonInvalidateCache, NewtonCollisionUpdate void NewtonUpdate(const NewtonWorld* const newtonWorld, dFloat timestep) { TRACE_FUNTION(__FUNCTION__); Newton* const world = (Newton *) newtonWorld; //timestep = ClampValue (timestep, MIN_TIMESTEP, MAX_TIMESTEP * 2.0f); timestep = ClampValue(dgFloat32(timestep), dgFloat32(MIN_TIMESTEP), dgFloat32(dgFloat32(1.0f / 60.0f))); dgInt32 count = dgInt32( dgCeil(timestep / (world->g_maxTimeStep + dgFloat32(1.0e-10f)))); dgFloat32 time = timestep / count; for (dgInt32 i = 0; i < count; i++) { #ifdef DG_USED_DEBUG_EXCEPTIONS __try { world->UpdatePhysics (time); }__except (ExecptionHandler (_exception_info ())) { _ASSERTE (0); // world->UpdatePhysics (time); } #else world->UpdatePhysics(time); #endif } } // Name: NewtonCollisionUpdate // Update the collision state of all object in eh world. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world // // Return: Nothing // // Remarks: This function will update all of the collision for all body in the physics world. // the function is meant for application that are using the engine as collision system only, // sample of these are legacy application that use collision but no physics, level editor, plug in for modeling packages // and even physics application that some time do not need to execute and dynamics simulation step for what every reason // // Return: when calling this function the application do not need to call NetwonUpdate // // See also: NewtonUpdate, NewtonInvalidateCache void NewtonCollisionUpdate(const NewtonWorld* const newtonWorld) { TRACE_FUNTION(__FUNCTION__); Newton* const world = (Newton *) newtonWorld; #ifdef DG_USED_DEBUG_EXCEPTIONS __try { world->UpdateCollision (); }__except (ExecptionHandler (_exception_info ())) { world->UpdateCollision (); } #else world->UpdateCollision(); #endif } // Name: NewtonSetMinimumFrameRate // Set the minimum frame rate at which the simulation can run. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world // *dFloat* frameRate - minimum frame rate of the simulation in frame per second. This value is clamped between 60fps and 1000fps // // Return: nothing // // Remarks: the default minimum frame rate of the simulation is 60 frame per second. When the simulation falls below the specified minimum frame, Newton will // perform sub steps in order to meet the desired minimum FPS. void NewtonSetMinimumFrameRate(const NewtonWorld* const newtonWorld, dFloat frameRate) { Newton* world; world = (Newton *) newtonWorld; TRACE_FUNTION(__FUNCTION__);_ASSERTE( dgFloat32(1.0f) / dgFloat32 (MAX_TIMESTEP) < dgFloat32(1.0f) / dgFloat32 (MIN_TIMESTEP)); frameRate = ClampValue(frameRate, dgFloat32(1.0f) / dgFloat32(MAX_TIMESTEP), dgFloat32(1.0f) / dgFloat32(MIN_TIMESTEP)); world->g_maxTimeStep = dgFloat32(1.0f) / frameRate; } /* // Name: NewtonGetTimeStep // Return the correct time step for this simulation update. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // // Remark: This application can used this function to get the current simulation time step. // // Return: correct update timestep. dFloat NewtonGetTimeStep(const NewtonWorld* const newtonWorld) { Newton* world; world = (Newton *)newtonWorld; return world->GetTimeStep(); } */ // Name: NewtonDestroyAllBodies // Remove all bodies and joints from the newton world. // // Parameters: // *const NewtonWorld* *newtonWorld - is a pointer to the Newton world // // Return: Nothing // // Remarks: This function will destroy all bodies and all joints in the Newton world, but it will retain group IDs. // Use this function for when you want to clear the world but preserve all the group IDs and material pairs. // // See also: NewtonMaterialDestroyAllGroupID void NewtonDestroyAllBodies(const NewtonWorld* const newtonWorld) { dFloat p0[4]; dFloat p1[4]; Newton* world; p0[0] = -100.0f; p0[1] = -100.0f; p0[2] = -100.0f; p1[0] = 100.0f; p1[1] = 100.0f; p1[2] = 100.0f; TRACE_FUNTION(__FUNCTION__); NewtonSetWorldSize(newtonWorld, p0, p1); world = (Newton *) newtonWorld; // world->RagDollList::DestroyAll(); world->DestroyAllBodies(); } // Name: NewtonSetWorldSize // Set the size of the Newton world. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world // *const dFloat* *minPtr - is the minimum point of the world bounding box // *const dFloat* *maxPtr - is the maximum point of the world bounding box // // Return: Nothing. // // Remarks: The Newton world must have a finite size. The size of the world is set to a box +- 100 units in all three dimensions // at creation time and after a call to the function _NewtonRemoveAllBodies_ // // See also: NewtonSetBodyLeaveWorldEvent void NewtonSetWorldSize(const NewtonWorld* const newtonWorld, const dFloat* const minPtr, const dFloat* const maxPtr) { TRACE_FUNTION(__FUNCTION__); Newton* const world = (Newton *) newtonWorld; dgVector p0(minPtr[0], minPtr[1], minPtr[2], dgFloat32(1.0f)); dgVector p1(maxPtr[0], maxPtr[1], maxPtr[2], dgFloat32(1.0f)); world->SetWorldSize(p0, p1); } // Name: NewtonSetIslandUpdateEvent // Set a function callback to be call on each island update. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world // *NewtonIslandUpdate* slandUpdate - application defined callback // // Return: Nothing. // //Remarks: The application can set a function callback to be called just after the array of all bodies making an island of articulated and colliding bodies are collected for resolution. //This function will be called just before the array is accepted for solution and integration. //The function callback may return one to validate the array or zero to skip the resolution of this array of bodies on this frame only. //This functionality can be used by the application to implement in game physics LOD. For example the application can determine the AABB of the //island and check against the view frustum, if the entire island AABB is invisible then the application can suspend simulation even if they are not in equilibrium. //another functionality is the implementation of visual debuggers, and also the implementation of auto frozen bodies under arbitrary condition set by the logic of the application. // //Remarks: The application should not modify the position, velocity, or it create or destroy any body or joint during this function call. Doing so will result in unpredictable malfunctions. // // See also: NewtonIslandGetBody void NewtonSetIslandUpdateEvent(const NewtonWorld* const newtonWorld, NewtonIslandUpdate islandUpdate) { Newton* world; TRACE_FUNTION(__FUNCTION__); world = (Newton *) newtonWorld; world->SetIslandUpdateCallback((OnIslandUpdate) islandUpdate); } // Name: NewtonSetCollisionDestructor // Set a function callback to be call on each island update. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world // *NewtonIslandUpdate* slandUpdate - application defined callback // // Return: Nothing. void NewtonSetCollisionDestructor(const NewtonWorld* const newtonWorld, NewtonCollisionDestructor callback) { Newton* world; TRACE_FUNTION(__FUNCTION__); world = (Newton *) newtonWorld; world->SetDestroyCollisionCallback((OnDestroyCollision) callback); } // Name: NewtonSetDestroyBodyByExeciveForce // Set a function callback to be call when the force applied at a contact point exceed the max force allowed for that convex shape // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world // *NewtonDestroyBodyByExeciveForce* callback - application defined callback // //Remarks: Only convex Hull shapes can have max brak force parameter. // // Return: Nothing. void NewtonSetDestroyBodyByExeciveForce(const NewtonWorld* const newtonWorld, NewtonDestroyBodyByExeciveForce callback) { Newton* world; TRACE_FUNTION(__FUNCTION__); world = (Newton *) newtonWorld; world->SetBodyDestructionByExeciveForce( (OnBodyDestructionByExeciveForce) callback); } // Name: NewtonSetBodyLeaveWorldEvent // Set the event callback function to be called in the event a body is escaping the limits of the world // during simulation time. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world // *NewtonBodyLeaveWorld* callback - is the pointer to the function callback // // Return: Nothing // // Remarks: When a body moves outside the bounding box that defines the world space the body is automatically disabled // and Newton calls the application defined callback function *NewtonBodyLeaveWorld callback*. // The application should decide how to handle the event, because Newton will make the callback once. // The only options available to the application are: do nothing or destroy the object. // // See also: NewtonSetWorldSize, NewtonBodyGetFirstJoint, NewtonBodyGetNextJoint void NewtonSetBodyLeaveWorldEvent(const NewtonWorld* const newtonWorld, NewtonBodyLeaveWorld callback) { Newton* world; world = (Newton *) newtonWorld; TRACE_FUNTION(__FUNCTION__); world->SetLeavingWorldCallback((OnLeavingWorldAction) callback); } // Name: NewtonWorldGetFirstBody // get th firt body in the body in the world body list. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // // Return: nothing // // Remarks: The application can call this function to iterate thought every body in the world. // // Remarks: The application call this function for debugging purpose // See also: NewtonWorldGetNextBody, NewtonBodyForEachPolygonDo, NewtonWorldForEachBodyInAABBDo, NewtonWorldForEachJointDo NewtonBody* NewtonWorldGetFirstBody(const NewtonWorld* const newtonWorld) { Newton* world; dgBodyMasterList::dgListNode *node; world = (Newton *) newtonWorld; dgBodyMasterList &masterList = *world; TRACE_FUNTION(__FUNCTION__);_ASSERTE( masterList.GetFirst()->GetInfo().GetBody() == world->GetSentinelBody()); node = masterList.GetFirst()->GetNext(); // body = node->GetInfo().GetBody(); // node = node->GetNext(); // callback ((const NewtonBody*) body); // } if (node) { return (NewtonBody*) node->GetInfo().GetBody(); } else { return NULL; } } // Name: NewtonWorldGetFirstBody // get the fixt body in the general body. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // // Return: nothing // // Remarks: The application can call this function to iterate thought every body in the world. // // Remarks: The application call this function for debugging purpose // See also: NewtonWorldGetFirstBody, NewtonBodyForEachPolygonDo, NewtonWorldForEachBodyInAABBDo, NewtonWorldForEachJointDo NewtonBody* NewtonWorldGetNextBody(const NewtonWorld* const newtonWorld, const NewtonBody* const curBody) { dgBody* const body = (dgBody*) curBody; TRACE_FUNTION(__FUNCTION__); dgBodyMasterList::dgListNode* const node = body->GetMasterList()->GetNext(); if (node) { return (NewtonBody*) node->GetInfo().GetBody(); } else { return NULL; } } // Name: NewtonWorldForEachJointDo // Iterate thought every joint in the world calling the function callback. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *NewtonJointIterator* callback - application define callback // *void* callback - application define userdata // // Return: nothing // // Remarks: The application can call this function to iterate thought every joint in the world. // the application should provide the function *NewtonJointIterator callback* to be called by Newton for every joint in the world // // Remarks: this function affect severally the performance of Newton. The application should call this function only for debugging // or for serialization purposes. // // See also: NewtonBodyForEachPolygonDo, NewtonWorldForEachBodyInAABBDo, NewtonWorldGetFirstBody void NewtonWorldForEachJointDo(const NewtonWorld* const newtonWorld, NewtonJointIterator callback, void* const userData) { Newton* world; dgBodyMasterList::dgListNode *node; dgBodyMasterListRow::dgListNode* jointNode; world = (Newton *) newtonWorld; dgBodyMasterList &masterList = *world; TRACE_FUNTION(__FUNCTION__); dgTree<dgConstraint*, dgConstraint*> jointMap(world->dgWorld::GetAllocator()); for (node = masterList.GetFirst()->GetNext(); node; node = node->GetNext()) { dgBodyMasterListRow& row = node->GetInfo(); for (jointNode = row.GetFirst(); jointNode; jointNode = jointNode->GetNext()) { const dgBodyMasterListCell& cell = jointNode->GetInfo(); if (cell.m_joint->GetId() != dgContactConstraintId) { if (!jointMap.Find(cell.m_joint)) { jointMap.Insert(cell.m_joint, cell.m_joint); callback((const NewtonJoint*) cell.m_joint, userData); } } } } } // Name: NewtonWorldForEachBodyInAABBDo // Iterate thought every body in the world that intersect the AABB calling the function callback. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *const dFloat* *p0 - pointer to an array of at least three floats to hold minimum value for the AABB. // *const dFloat* *p1 - pointer to an array of at least three floats to hold maximum value for the AABB. // *NewtonBodyIterator* callback - application define callback // *void* callback - application define userdata // // Return: nothing // // Remarks: The application can call this function to iterate thought every body in the world. // the application should provide the function *NewtonBodyIterator callback* to be called by Newton for every body in the world // // Remarks: For relatively small AABB volumes this function is much more inefficients // that NewtonWorldGetFirstBody, however in case where the AABB contain must of the objects in the scene, // the overhead of scanning the internal Broad face collision plus the AABB test make this function more expensive. // // See also: NewtonBodyForEachPolygonDo, NewtonWorldGetFirstBody void NewtonWorldForEachBodyInAABBDo(const NewtonWorld* const newtonWorld, const dFloat* const p0, const dFloat* const p1, NewtonBodyIterator callback, void* const userData) { Newton* world; world = (Newton *) newtonWorld; dgVector q0(p0[0], p0[1], p0[2], dgFloat32(0.0f)); dgVector q1(p1[0], p1[1], p1[2], dgFloat32(0.0f)); TRACE_FUNTION(__FUNCTION__); world->ForEachBodyInAABB(q0, q1, (OnBodiesInAABB) callback, userData); } // Name: NewtonWorldGetVersion // Return the current library version number. // // Parameters: // // Return: release decimal three digit value x.xx // the first digit: is mayor version number (interface changes among other things) // the second digit: is mayor patch number (new features, and bug fixes) // third digit: is minor bug fixed patch. int NewtonWorldGetVersion() { TRACE_FUNTION(__FUNCTION__); return NEWTON_MAJOR_VERSION * 100 + NEWTON_MINOR_VERSION; } // Name: NewtonWorldFloatSize // Return the current sizeof of float value in bytes. // // Parameters: // // Return: sizeof of float value in bytes int NewtonWorldFloatSize() { TRACE_FUNTION(__FUNCTION__); return sizeof(dFloat); } // Name: NewtonWorldSetUserData // Store a user defined data value with the world. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the newton world. // *void* *userDataPtr - pointer to the user defined user data value. // // Return: Nothing. // // Remarks: The application can store a user defined value with the Newton world. The user data is useful for application developing // object oriented classes based on the Newton API. // // See also: NewtonWorldGetUserData void NewtonWorldSetUserData(const NewtonWorld* const newtonWorld, void* const userData) { Newton* world; world = (Newton *) newtonWorld; world->SetUserData(userData); } // Name: NewtonWorldGetUserData // Retrieve a user previously stored user define value with the world. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // // Return: user data value. // // Remarks: The application can store a user defined value with the Newton world. The user data is useful for application developing // object oriented classes based on the Newton API. // // See also: NewtonWorldSetDestructorCallBack, NewtonWorldGetUserData void* NewtonWorldGetUserData(const NewtonWorld* const newtonWorld) { Newton* world; world = (Newton *) newtonWorld; TRACE_FUNTION(__FUNCTION__); return world->GetUserData(); } // Name: NewtonWorldSetDestructorCallBack // set a function pointer as destructor call back. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *NewtonDestroyWorld* destructor - function poiter callback // // Remarks: The application can store a user defined destrutor call back function to be called at the time the world is to be destruyed // // See also: NewtonWorldGetUserData void NewtonWorldSetDestructorCallBack(const NewtonWorld* const newtonWorld, NewtonDestroyWorld destructor) { Newton* world; world = (Newton *) newtonWorld; TRACE_FUNTION(__FUNCTION__); world->m_destructor = destructor; } // Name: NewtonWorldSetDestructorCallBack // Return the function call back Pointer. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // // Remarks: The application can store a user defined destrutor call back function to be called at the time the world is to be destruyed // // See also: NewtonWorldGetUserData, NewtonWorldSetDestructorCallBack NewtonDestroyWorld NewtonWorldGetDestructorCallBack( const NewtonWorld* const newtonWorld) { Newton* world; world = (Newton *) newtonWorld; TRACE_FUNTION(__FUNCTION__); return world->m_destructor; } // Name: NewtonWorldGetBodyCount // return the total number of rigid bodies in the world. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world // // Return: number of rigid bodies in this world. // int NewtonWorldGetBodyCount(const NewtonWorld* const newtonWorld) { Newton* world; TRACE_FUNTION(__FUNCTION__); world = (Newton *) newtonWorld; // dgBodyMasterList &masterList = *world; // _ASSERTE (masterList.GetFirst()->GetInfo().GetBody() == world->GetSentinelBody()); // return masterList.GetCount() - 1; return world->GetBodiesCount(); } // Name: NewtonWorldGetConstraintCount // return the total number of contsting in th eworld. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world // // remark: this function will retrun the total numbe of joint including conctats // // Return: number of rigid bodies in this world. // int NewtonWorldGetConstraintCount(const NewtonWorld* const newtonWorld) { Newton* world; TRACE_FUNTION(__FUNCTION__); world = (Newton *) newtonWorld; return world->GetConstraintsCount(); } // Name: NewtonWorldRayCast // Shoot a ray from p0 to p1 and call the application callback with each ray intersection. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the world. // *const dFloat* *p0 - pointer to an array of at least three floats containing the beginning of the ray in global space. // *const dFloat* *p1 - pointer to an array of at least three floats containing the end of the ray in global space. // *NewtonWorldRayFilterCallback* filter - user define function to be called for each body hit during the ray scan. // *void* *userData - user data to be passed to the filter callback. // *NewtonWorldRayPrefilterCallback* prefilter - user define function to be called for each body before intersection. // // Return: nothing // // Remarks: The ray cast function will call the application with each body intersecting the line segment. // By writing the callback filter function in different ways the application can implement different flavors of ray casting. // For example an all body ray cast can be easily implemented by having the filter function always returning 1.0, and copying each // rigid body into an array of pointers; a closest hit ray cast can be implemented by saving the body with the smaller intersection // parameter and returning the parameter t; and a report the first body hit can be implemented by having the filter function returning // zero after the first call and saving the pointer to the rigid body. // // Remarks: The most common use for the ray cast function is the closest body hit, In this case it is important, for performance reasons, // that the filter function returns the intersection parameter. If the filter function returns a value of zero the ray cast will terminate // immediately. // // Remarks: if prefilter is not NULL, Newton will call the application right before executing the intersections between the ray and the primitive. // if the function returns zero the Newton will not ray cast the primitive. passing a NULL pointer will ray cast the. // The application can use this implement faster or smarter filters when implementing complex logic, otherwise for normal all ray cast // this parameter could be NULL. // // Remarks: The ray cast function is provided as an utility function, this means that even thought the function is very high performance // by function standards, it can not by batched and therefore it can not be an incremental function. For example the cost of calling 1000 // ray cast is 1000 times the cost of calling one ray cast. This is much different than the collision system where the cost of calculating // collision for 1000 pairs in much, much less that the 1000 times the cost of one pair. Therefore this function must be used with care, // as excessive use of it can degrade performance. // // See also: NewtonWorldConvexCast void NewtonWorldRayCast(const NewtonWorld* const newtonWorld, const dFloat* const p0, const dFloat* const p1, NewtonWorldRayFilterCallback filter, void* const userData, NewtonWorldRayPrefilterCallback prefilter) { TRACE_FUNTION(__FUNCTION__); if (filter) { dgVector pp0(p0[0], p0[1], p0[2], dgFloat32(0.0f)); dgVector pp1(p1[0], p1[1], p1[2], dgFloat32(0.0f)); Newton* const world = (Newton *) newtonWorld; world->RayCast(pp0, pp1, (OnRayCastAction) filter, (OnRayPrecastAction) prefilter, userData); } } // Name: NewtonWorldConvexCast // cast a simple convex shape along the ray that goes for the matrix position to the destination and get the firsts contacts of collision. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the world. // *const dFloat* *matrix - pointer to an array of at least three floats containing the beginning and orienetaion of the shape in global space. // *const dFloat* *target - pointer to an array of at least three floats containing the end of the ray in global space. // *const NewtonCollision* shape - collision shap[e use to cat the ray. // *dFloat* hitParam - pointe to a variable the will contart the time to closet aproah to the collision. // *void* *userData - user data to be passed to the prefilter callback. // *NewtonWorldRayPrefilterCallback* prefilter - user define function to be called for each body before intersection. // *NewtonWorldConvexCastReturnInfo* *info - pointer to an array of contacts at the point of intesections. // *int* maxContactsCount - maximun number of contacts to be conclaculated, the variable sould be initialized to the capaciaty of *info* // *int* threadIndex - thread index from whe thsi function is called, zero if call form outsize a newton update // // Return: the number of contact at the intesection point (a value equal o lower than maxContactsCount. // variable *hitParam* will be set the uintesation parameter an the momen of impact. // // Remarks: passing and value of NULL in *info* an dzero in maxContactsCount will turn thos function into a spcial Ray cast // where the function will only calculate the *hitParam* at the momenet of contacts. tshi si one of the most effiecnet way to use thsio function. // // Remarks: these function is similar to *NewtonWorldRayCast* but instead of casting a point it cast a simple convex shape along a ray for maoprix.m_poit // to target position. the shape is global orientation and position is set to matrix and then is swept along the segment to target and it will stop at the very first intersession contact. // // Remarks: for case where the application need to cast solid short to medium rays, it is better to use this function instead of casting and array of parallel rays segments. // examples of these are: implementation of ray cast cars with cylindrical tires, foot placement of character controllers, kinematic motion of objects, user controlled continue collision, etc. // this function may not be as efficient as sampling ray for long segment, for these cases try using parallel ray cast. // // Remarks: The most common use for the ray cast function is the closest body hit, In this case it is important, for performance reasons, // that the filter function returns the intersection parameter. If the filter function returns a value of zero the ray cast will terminate // immediately. // // Remarks: if prefilter is not NULL, Newton will call the application right before executing the intersections between the ray and the primitive. // if the function returns zero the Newton will not ray cast the primitive. // The application can use this callback to implement faster or smarter filters when implementing complex logic, otherwise for normal all ray cast // this parameter could be NULL. // // See also: NewtonWorldRayCast int NewtonWorldConvexCast(const NewtonWorld* const newtonWorld, const dFloat* const matrix, const dFloat* const target, const NewtonCollision* const shape, dFloat* const hitParam, void* const userData, NewtonWorldRayPrefilterCallback prefilter, NewtonWorldConvexCastReturnInfo* const info, int maxContactsCount, int threadIndex) { TRACE_FUNTION(__FUNCTION__); dgVector destination(target[0], target[1], target[2], dgFloat32(0.0f)); Newton* const world = (Newton *) newtonWorld; return world->ConvexCast((dgCollision*) shape, *((dgMatrix*) matrix), destination, *(dgFloat32*) hitParam, (OnRayPrecastAction) prefilter, userData, (dgConvexCastReturnInfo*) info, maxContactsCount, threadIndex); } // Name: NewtonIslandGetBody // Get the body indexed by bodyIndex form and island. // // Parameters: // *const void* *island - is the pointer to current island // *int* bodyIndex - index to the body in current island // // Return: body at location bodtIndex. // // Remarks: This function can only be called from an island update callback. // //Remarks: The application can set a function callback to be called just after the array of all bodies making an island of connected bodies are collected. //This function will be called just before the array is accepted for solution and integration. //The function callback may return one to validate the array of zero to freeze it. //This functionality can be used by the application to implement in game physics LOD. For example the application can determine the AABB of the //island and check against the view frustum, if the entire island AABB is invisible then the application can suspend simulation even if they are not in equilibrium. //another functionality is the implementation of visual debuggers, and also the implementation of auto frozen bodies under arbitrary condition set by the logic of the application. // //Remarks: The application should not modify any parameter of the origin body when the callback is called, nor it should create or destroy any body or joint. Do so will result in unpredictable malfunction. // // See also: NewtonSetIslandUpdateEvent NewtonBody* NewtonIslandGetBody(const void* const island, int bodyIndex) { dgWorld* world; TRACE_FUNTION(__FUNCTION__); world = *(dgWorld**) island; return (NewtonBody*) world->GetIslandBody(island, bodyIndex); } // Name: NewtonIslandGetBodyAABB // Return the AABB of the body on this island // // Parameters: // *const void* *island - is the pointer to current island // *int* bodyIndex - index to the body in current island // // Remarks: This function can only be called from an island update callback. // //Remarks: The application can set a function callback to be called just after the array of all bodies making an island of connected bodies are collected. //This function will be called just before the array is accepted for solution and integration. //The function callback may return one to validate the array of zero to freeze it. //This functionality can be used by the application to implement in game physics LOD. For example the application can determine the AABB of the //island and check against the view frustum, if the entire island AABB is invisible then the application can suspend simulation even if they are not in equilibrium. //another functionality is the implementation of visual debuggers, and also the implementation of auto frozen bodies under arbitrary condition set by the logic of the application. // //Remarks: The application should not modify any parameter of the origin body when the callback is called, nor it should create or destroy any body or joint. Do so will result in unpredictable malfunction. // // See also: NewtonSetIslandUpdateEvent void NewtonIslandGetBodyAABB(const void* const island, int bodyIndex, dFloat* const p0, dFloat* const p1) { TRACE_FUNTION(__FUNCTION__); dgBody* const body = (dgBody*) NewtonIslandGetBody(island, bodyIndex); if (body) { body->GetAABB((dgVector&) *p0, (dgVector&) *p1); } } // *************************************************************************************************************** // // Name: GroupID interface // // *************************************************************************************************************** // Name: NewtonMaterialGetDefaultGroupID // Get the value of the default MaterialGroupID. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world // // Return: The ID number for the default Group ID. // // Remarks: Group IDs can be interpreted as the nodes of a dense graph. The edges of the graph are the physics materials. // When the Newton world is created, the default Group ID is created by the engine. // When bodies are created the application assigns a group ID to the body. int NewtonMaterialGetDefaultGroupID(const NewtonWorld* const newtonWorld) { Newton* const world = (Newton *) newtonWorld; TRACE_FUNTION(__FUNCTION__); return int(world->GetDefualtBodyGroupID()); } // Name: NewtonMaterialCreateGroupID // Create a new MaterialGroupID. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world // // Return: The ID of a new GroupID. // // Remarks: Group IDs can be interpreted as the nodes of a dense graph. The edges of the graph are the physics materials. // When the Newton world is created, the default Group ID is created by the engine. // When bodies are created the application assigns a group ID to the body. // // Note: The only way to destroy a Group ID after its creation is by destroying all the bodies and calling the function *NewtonMaterialDestroyAllGroupID*. // // See also: NewtonMaterialDestroyAllGroupID int NewtonMaterialCreateGroupID(const NewtonWorld* const newtonWorld) { Newton* const world = (Newton *) newtonWorld; TRACE_FUNTION(__FUNCTION__); return int(world->CreateBodyGroupID()); } // Name: NewtonMaterialDestroyAllGroupID // Remove all groups ID from the Newton world. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world // // Return: Nothing. // // Remarks: This function removes all groups ID from the Newton world. // This function must be called after there are no more rigid bodies in the word. // // See also: NewtonDestroyAllBodies void NewtonMaterialDestroyAllGroupID(const NewtonWorld* const newtonWorld) { Newton* world; // _ASSERTE (0); world = (Newton *) newtonWorld; TRACE_FUNTION(__FUNCTION__); world->RemoveAllGroupID(); } //int NewtonGetActiveBodiesCount() //{ // _ASSERTE (0); // return 0; //} //int NewtonGetActiveConstraintsCount() //{ // _ASSERTE (0); // return 0; //} // *************************************************************************************************************** // // Name: Material setup interface // // *************************************************************************************************************** // Name: NewtonMaterialSetDefaultCollidable // Set the material interaction between two physics materials to be collidable or non-collidable by default. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world // *int* id0 - group id0 // *int* id1 - group id1 // *int* state - state for this material: 1 = collidable; 0 = non collidable // // Return: Nothing. void NewtonMaterialSetDefaultCollidable(const NewtonWorld* const newtonWorld, int id0, int id1, int state) { Newton* const world = (Newton *) newtonWorld; dgContactMaterial* const material = world->GetMaterial(dgUnsigned32(id0), dgUnsigned32(id1)); TRACE_FUNTION(__FUNCTION__); // material->m_collisionEnable = state ? true : false; if (state) { material->m_flags |= dgContactMaterial::m_collisionEnable__; } else { material->m_flags &= ~dgContactMaterial::m_collisionEnable__; } } // Name: NewtonMaterialSetContinuousCollisionMode // Set the material interaction between two physics materials to enable or disable continue collision. // continue collision is on by defaults. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world // *int* id0 - group id0 // *int* id1 - group id1 // *int* state - state for this material: 1 = continue collision on; 0 = continue collision off, default mode is on // // Return: Nothing. // // Remarks: continue collision mode enable allow the engine to predict colliding contact on rigid bodies // Moving at high speed of subject to strong forces. // // Remarks: continue collision mode does not prevent rigid bodies from inter penetration instead it prevent bodies from // passing trough each others by extrapolating contact points when the bodies normal contact calculation determine the bodies are not colliding. // // Remarks: for performance reason the bodies angular velocities is only use on the broad face of the collision, // but not on the contact calculation. // // Remarks: continue collision does not perform back tracking to determine time of contact, instead it extrapolate contact by incrementally // extruding the collision geometries of the two colliding bodies along the linear velocity of the bodies during the time step, // if during the extrusion colliding contact are found, a collision is declared and the normal contact resolution is called. // // Remarks: for continue collision to be active the continue collision mode must on the material pair of the colliding bodies as well as on at least one of the two colliding bodies. // // Remarks: Because there is penalty of about 40% to 80% depending of the shape complexity of the collision geometry, this feature is set // off by default. It is the job of the application to determine what bodies need this feature on. Good guidelines are: very small objects, // and bodies that move a height speed. // // See also: NewtonBodySetContinuousCollisionMode void NewtonMaterialSetContinuousCollisionMode( const NewtonWorld* const newtonWorld, int id0, int id1, int state) { Newton* const world = (Newton *) newtonWorld; dgContactMaterial* const material = world->GetMaterial(dgUnsigned32(id0), dgUnsigned32(id1)); TRACE_FUNTION(__FUNCTION__); //material->m_collisionContinueCollisionEnable = state ? true : false; if (state) { material->m_flags |= dgContactMaterial::m_collisionContinueCollisionEnable__; } else { material->m_flags &= ~dgContactMaterial::m_collisionContinueCollisionEnable__; } } // Name: NewtonMaterialSetSurfaceThickness // Set an imaginary thickness between the collision geometry of two colliding bodies who’s physics // properties are defined by this material pair // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world // *int* id0 - group id0 // *int* id1 - group id1 // *dFloat* thickness - material thickness a value form 0.0 to 0.125; the default surface value is 0.0 // // Return: Nothing. // // Remarks: when two bodies collide the engine resolve contact inter penetration by applying a small restoring // velocity at each contact point. By default this restoring velocity will stop when the two contacts are // at zero inter penetration distance. However by setting a non zero thickness the restoring velocity will // continue separating the contacts until the distance between the two point of the collision geometry is equal // to the surface thickness. // // Remark: Surfaces thickness can improve the behaviors of rolling objects on flat surfaces. // // Remarks: Surface thickness does not alter the performance of contact calculation. void NewtonMaterialSetSurfaceThickness(const NewtonWorld* const newtonWorld, int id0, int id1, dFloat thickness) { TRACE_FUNTION(__FUNCTION__); Newton* const world = (Newton *) newtonWorld; dgContactMaterial* const material = world->GetMaterial(dgUnsigned32(id0), dgUnsigned32(id1)); material->m_penetrationPadding = GetMin(GetMax(thickness, dgFloat32(0.0)), dgFloat32(DG_MAX_COLLISION_PADDING)); } // Name: NewtonMaterialSetDefaultFriction // Set the default coefficients of friction for the material interaction between two physics materials . // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world // *int* id0 - group id0 // *int* id1 - group id1 // *dFloat* staticFriction - static friction coefficients // *dFloat* kineticFriction - dynamic coefficient of friction // // Return: Nothing. // // Remarks: *staticFriction* and *kineticFriction* must be positive values. *kineticFriction* must be lower than *staticFriction*. // It is recommended that *staticFriction* and *kineticFriction* be set to a value lower or equal to 1.0, however because some synthetic materials // can have higher than one coefficient of friction Newton allows for the coefficient of friction to be as high as 2.0. void NewtonMaterialSetDefaultFriction(const NewtonWorld* const newtonWorld, int id0, int id1, dFloat staticFriction, dFloat kineticFriction) { dFloat stat; dFloat kine; Newton* world; TRACE_FUNTION(__FUNCTION__); world = (Newton *) newtonWorld; dgContactMaterial* const material = world->GetMaterial(dgUnsigned32(id0), dgUnsigned32(id1)); staticFriction = dgAbsf(staticFriction); kineticFriction = dgAbsf(kineticFriction); if (material) { if (staticFriction >= dgFloat32(1.e-2f)) { stat = ClampValue(staticFriction, dFloat(0.01f), dFloat(2.0f)); kine = ClampValue(kineticFriction, dFloat(0.01f), dFloat(2.0f)); stat = GetMax(stat, kine); material->m_staticFriction0 = stat; material->m_staticFriction1 = stat; material->m_dynamicFriction0 = kine; material->m_dynamicFriction1 = kine; } else { //material->m_friction0Enable = false; //material->m_friction1Enable = false; material->m_flags &= ~(dgContactMaterial::m_friction0Enable__ | dgContactMaterial::m_friction1Enable__); } } } // Name: NewtonMaterialSetDefaultElasticity // Set the default coefficients of restitution (elasticity) for the material interaction between two physics materials . // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world // *int* id0 - group id0 // *int* id1 - group id1 // *dFloat* elasticCoef - static friction coefficients // // Return: Nothing. // // Remarks: *elasticCoef* must be a positive value. // It is recommended that *elasticCoef* be set to a value lower or equal to 1.0 void NewtonMaterialSetDefaultElasticity(const NewtonWorld* const newtonWorld, int id0, int id1, dFloat elasticCoef) { Newton* world; TRACE_FUNTION(__FUNCTION__); world = (Newton *) newtonWorld; dgContactMaterial* const material = world->GetMaterial(dgUnsigned32(id0), dgUnsigned32(id1)); material->m_restitution = ClampValue(elasticCoef, dFloat(0.01f), dFloat(2.0f)); } // Name: NewtonMaterialSetDefaultSoftness // Set the default softness coefficients for the material interaction between two physics materials . // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world // *int* id0 - group id0 // *int* id1 - group id1 // *dFloat* softnessCoef - softness coefficient // // Return: Nothing. // // Remarks: *softnessCoef* must be a positive value. // It is recommended that *softnessCoef* be set to value lower or equal to 1.0 // A low value for *softnessCoef* will make the material soft. A typical value for *softnessCoef* is 0.15 void NewtonMaterialSetDefaultSoftness(const NewtonWorld* const newtonWorld, int id0, int id1, dFloat softnessCoef) { Newton* world; TRACE_FUNTION(__FUNCTION__); world = (Newton *) newtonWorld; dgContactMaterial* const material = world->GetMaterial(dgUnsigned32(id0), dgUnsigned32(id1)); material->m_softness = ClampValue(softnessCoef, dFloat(0.01f), dFloat(dgFloat32(1.0f))); } // Name: NewtonMaterialSetCollisionCallback // Set userData and the functions event handlers for the material interaction between two physics materials . // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *int* id0 - group id0. // *int* id1 - group id1. // *void* *userData - user data value. // *NewtonOnAABBOverlap* aabbOverlap - address of the event function called when the AABB of tow bodyes overlap. This parameter can be NULL. // *NewtonContactsProcess* processCallback - address of the event function called for every contact resulting from contact calculation. This parameter can be NULL. // // Return: Nothing. // // Remarks: When the AABB extend of the collision geometry of two bodies overlap, Newton collision system retrieves the material // interaction that defines the behavior between the pair of bodies. The material interaction is collected from a database of materials, // indexed by the material gruopID assigned to the bodies. If the material is tagged as non collidable, // then no action is taken and the simulation continues. // If the material is tagged as collidable, and a *aabbOverlap* was set for this material, then the *aabbOverlap* function is called. // If the function *aabbOverlap* returns 0, no further action is taken for this material (this can be use to ignore the interaction under // certain conditions). If the function *aabbOverlap* returns 1, Newton proceeds to calculate the array of contacts for the pair of // colliding bodies. If the function *processCallback* was set, the application receives a callback for every contact found between the // two colliding bodies. Here the application can perform fine grain control over the behavior of the collision system. For example, // rejecting the contact, making the contact frictionless, applying special effects to the surface etc. // After all contacts are processed and if the function *endCallback* was set, Newton calls *endCallback*. // Here the application can collect information gathered during the contact-processing phase and provide some feedback to the player. // A typical use for the material callback is to play sound effects. The application passes the address of structure in the *userData* along with // three event function callbacks. When the function *aabbOverlap* is called by Newton, the application resets a variable say *maximumImpactSpeed*. // Then for every call to the function *processCallback*, the application compares the impact speed for this contact with the value of // *maximumImpactSpeed*, if the value is larger, then the application stores the new value along with the position, and any other quantity desired. // When the application receives the call to *endCallback* the application plays a 3d sound based in the position and strength of the contact. // // See also: NewtonMaterialAsThreadSafe void NewtonMaterialSetCollisionCallback(const NewtonWorld* const newtonWorld, int id0, int id1, void *userData, NewtonOnAABBOverlap aabbOverlap, NewtonContactsProcess processCallback) { Newton* world; world = (Newton *) newtonWorld; TRACE_FUNTION(__FUNCTION__); dgContactMaterial* const material = world->GetMaterial(dgUnsigned32(id0), dgUnsigned32(id1)); material->SetUserData(userData); material->SetCollisionCallback((OnAABBOverlap) aabbOverlap, (OnContactCallback) processCallback); } // Name: NewtonMaterialSetCollisionCallback // Set userData and the functions event handlers for the material interaction between two physics materials . // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *int* id0 - group id0. // *int* id1 - group id1. // *void* *userData - user data value. // *NewtonOnAABBOverlap* aabbOverlap - address of the event function called before contact calculation for collision. This parameter can be NULL. // *NewtonContactsProcess* processCallback - address of the event function called for every contact resulting from contact calculation. This parameter can be NULL. // *NewtonContactEnd* endCallback - address of the event function called after all contacts are processed. This parameter can be NULL. // // Return: Nothing. // // Remarks: When the AABB extend of the collision geometry of two bodies overlap, Newton collision system retrieves the material // interaction that defines the behavior between the pair of bodies. The material interaction is collected from a database of materials, // indexed by the material gruopID assigned to the bodies. If the material is tagged as non collidable, // then no action is taken and the simulation continues. // If the material is tagged as collidable, and a *aabbOverlap* was set for this material, then the *aabbOverlap* function is called. // If the function *aabbOverlap* returns 0, no further action is taken for this material (this can be use to ignore the interaction under // certain conditions). If the function *aabbOverlap* returns 1, Newton proceeds to calculate the array of contacts for the pair of // colliding bodies. If the function *processCallback* was set, the application receives a callback for every contact found between the // two colliding bodies. Here the application can perform fine grain control over the behavior of the collision system. For example, // rejecting the contact, making the contact frictionless, applying special effects to the surface etc. // After all contacts are processed and if the function *endCallback* was set, Newton calls *endCallback*. // Here the application can collect information gathered during the contact-processing phase and provide some feedback to the player. // A typical use for the material callback is to play sound effects. The application passes the address of structure in the *userData* along with // three event function callbacks. When the function *aabbOverlap* is called by Newton, the application resets a variable say *maximumImpactSpeed*. // Then for every call to the function *processCallback*, the application compares the impact speed for this contact with the value of // *maximumImpactSpeed*, if the value is larger, then the application stores the new value along with the position, and any other quantity desired. // When the application receives the call to *endCallback* the application plays a 3d sound based in the position and strength of the contact. void NewtonMaterialSetCompondCollisionCallback( const NewtonWorld* const newtonWorld, int id0, int id1, NewtonOnAABBOverlap aabbOverlap) { Newton* world; TRACE_FUNTION(__FUNCTION__); world = (Newton *) newtonWorld; dgContactMaterial* const material = world->GetMaterial(dgUnsigned32(id0), dgUnsigned32(id1)); material->SetCompoundCollisionCallback((OnAABBOverlap) aabbOverlap); } // Name: NewtonMaterialGetUserData // Get userData associated with this material. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *int* id0 - group id0. // *int* id1 - group id1. // // Return: Nothing. void* NewtonMaterialGetUserData(const NewtonWorld* const newtonWorld, int id0, int id1) { Newton* world; TRACE_FUNTION(__FUNCTION__); world = (Newton *) newtonWorld; dgContactMaterial* const material = world->GetMaterial(dgUnsigned32(id0), dgUnsigned32(id1)); return material->GetUserData(); } // Name: NewtonWorldGetFirstMaterial // Get the first Material pair from the material array. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // // Return: the first material. // // See also: NewtonWorldGetNextMaterial NewtonMaterial* NewtonWorldGetFirstMaterial( const NewtonWorld* const newtonWorld) { Newton* world; TRACE_FUNTION(__FUNCTION__); world = (Newton *) newtonWorld; return (NewtonMaterial*) world->GetFirstMaterial(); } // Name: NewtonWorldGetNextMaterial // Get the next Material pair from the material array. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *const NewtonMaterial* *material - corrent material // // Return: next material in material array or NULL if material is the last material in the list. // // See also: NewtonWorldGetFirstMaterial NewtonMaterial* NewtonWorldGetNextMaterial(const NewtonWorld* const newtonWorld, const NewtonMaterial* const material) { Newton* world; TRACE_FUNTION(__FUNCTION__); world = (Newton *) newtonWorld; return (NewtonMaterial*) world->GetNextMaterial((dgContactMaterial*) material); } // *************************************************************************************************************** // // Name: Contact behavior control interface // // *************************************************************************************************************** /* // Name: NewtonMaterialDisableContact // Disable processing for the contact. // // Parameters: // *const NewtonMaterial* materialHandle - pointer to a material pair // // Return: Nothing. // // Remarks: This function can only be called from a material callback event handler. // // See also: NewtonMaterialSetCollisionCallback void NewtonMaterialDisableContact(const NewtonMaterial* const materialHandle) { material = (dgContactMaterial*) materialHandle; dgContactMaterial* const material->m_collisionEnable = false; } */ // Name: NewtonMaterialGetMaterialPairUserData // Get the userData set by the application when it created this material pair. // // Parameters: // *const NewtonMaterial* materialHandle - pointer to a material pair // // Return: Application user data. // // Remarks: This function can only be called from a material callback event handler. // // See also: NewtonMaterialSetCollisionCallback void* NewtonMaterialGetMaterialPairUserData( const NewtonMaterial* const materialHandle) { TRACE_FUNTION(__FUNCTION__); dgContactMaterial* const material = (dgContactMaterial*) materialHandle; return material->GetUserData(); } // Name: NewtonMaterialGetContactFaceAttribute // Return the face attribute assigned to this face when for a user defined collision or a Newton collision tree. // // Parameters: // *const NewtonMaterial* materialHandle - pointer to a material pair // // Return: face attribute for collision trees. Zero if the contact was generated by two convex collisions. // // Remarks: This function can only be called from a material callback event handler. // // Remarks: this function can be used by the application to retrieve the face id of a polygon for a collision tree. // // See also: NewtonMaterialSetCollisionCallback unsigned NewtonMaterialGetContactFaceAttribute( const NewtonMaterial* const materialHandle) { TRACE_FUNTION(__FUNCTION__); dgContactMaterial* const material = (dgContactMaterial*) materialHandle; return (unsigned) material->m_userId; } /* // Name: NewtonMaterialGetCurrentTimestep // Get the current time step. // // Parameters: // *const NewtonMaterial* materialHandle - pointer to a material pair // // Return: the current time step. // // Remarks: This function can only be called from a material callback event handler. The function can be useful for the implementation of powered contacts. // // See also: NewtonMaterialSetCollisionCallback dFloat NewtonMaterialGetCurrentTimestep(const NewtonMaterial* const materialHandle) { dgContactMaterial* const material = (dgContactMaterial*) materialHandle; // return material->m_currTimestep; _ASSERTE (material->m_body0); return material->m_body0->GetWorld()->GetTimeStep(); } */ // Name: NewtonMaterialGetContactNormalSpeed // Calculate the speed of this contact along the normal vector of the contact. // // Parameters: // *const NewtonMaterial* materialHandle - pointer to a material pair // // Return: Contact speed. A positive value means the contact is repulsive. // // Remarks: This function can only be called from a material callback event handler. // // See also: NewtonMaterialSetCollisionCallback dFloat NewtonMaterialGetContactNormalSpeed( const NewtonMaterial* const materialHandle) { // _ASSERTE (0); TRACE_FUNTION(__FUNCTION__); dgContactMaterial* const material = (dgContactMaterial*) materialHandle; // contact = (dgContact*) contactlHandle; dgBody* const body0 = material->m_body0; dgBody* const body1 = material->m_body1; dgVector p0(material->m_point - body0->GetPosition()); dgVector p1(material->m_point - body1->GetPosition()); dgVector v0(body0->GetVelocity() + body0->GetOmega() * p0); dgVector v1(body1->GetVelocity() + body1->GetOmega() * p1); dgVector dv(v1 - v0); dFloat speed = dv % material->m_normal; return speed; } // Name: NewtonMaterialGetContactTangentSpeed // Calculate the speed of this contact along the tangent vector of the contact. // // Parameters: // *const NewtonMaterial* materialHandle - pointer to a material pair. // *int* index - index to the tangent vector. This value can be 0 for primary tangent direction or 1 for the secondary tangent direction. // // Return: Contact tangent speed. // // Remarks: This function can only be called from a material callback event handler. // // See also: NewtonMaterialSetCollisionCallback dFloat NewtonMaterialGetContactTangentSpeed( const NewtonMaterial* const materialHandle, int index) { // _ASSERTE (0); TRACE_FUNTION(__FUNCTION__); dgContactMaterial* const material = (dgContactMaterial*) materialHandle; // contact = (dgContact*) contactlHandle; dgBody* const body0 = material->m_body0; dgBody* const body1 = material->m_body1; dgVector p0(material->m_point - body0->GetPosition()); dgVector p1(material->m_point - body1->GetPosition()); dgVector v0(body0->GetVelocity() + body0->GetOmega() * p0); dgVector v1(body1->GetVelocity() + body1->GetOmega() * p1); dgVector dv(v1 - v0); dgVector dir; if (index) { dir = material->m_dir1; } else { dir = material->m_dir0; } dFloat speed = dv % dir; return -speed; } // Name: NewtonMaterialGetContactPositionAndNormal // Get the contact position and normal in global space. // // Parameters: // *const NewtonMaterial* materialHandle - pointer to a material pair. // *dFloat* *positPtr - pointer to an array of at least three floats to hold the contact position. // *dFloat* *normalPtr - pointer to an array of at least three floats to hold the contact normal. // // Return: Nothing. // // Remarks: This function can only be called from a material callback event handle. // // See also: NewtonMaterialSetCollisionCallback void NewtonMaterialGetContactPositionAndNormal( const NewtonMaterial* const materialHandle, NewtonBody* const body, dFloat* const positPtr, dFloat* const normalPtr) { TRACE_FUNTION(__FUNCTION__); dgContactMaterial* const material = (dgContactMaterial*) materialHandle; positPtr[0] = material->m_point.m_x; positPtr[1] = material->m_point.m_y; positPtr[2] = material->m_point.m_z; normalPtr[0] = material->m_normal.m_x; normalPtr[1] = material->m_normal.m_y; normalPtr[2] = material->m_normal.m_z; if ((dgBody*) body != material->m_body0) { normalPtr[0] *= dgFloat32(-1.0f); normalPtr[1] *= dgFloat32(-1.0f); normalPtr[2] *= dgFloat32(-1.0f); } } // Name: NewtonMaterialGetContactForce // Get the contact force vector in global space. // // Parameters: // *const NewtonMaterial* materialHandle - pointer to a material pair. // *dFloat* *forcePtr - pointer to an array of at least three floats to hold the force vector in global space. // // Return: Nothing. // // Remarks: The contact force value is only valid when calculating resting contacts. This means if two bodies collide with // non zero relative velocity, the reaction force will be an impulse, which is not a reaction force, this will return zero vector. // this function will only return meaningful values when the colliding bodies are at rest. // // Remarks: This function can only be called from a material callback event handler. // // See also: NewtonMaterialSetCollisionCallback void NewtonMaterialGetContactForce(const NewtonMaterial* const materialHandle, NewtonBody* const body, dFloat* const forcePtr) { TRACE_FUNTION(__FUNCTION__); dgContactMaterial* const material = (dgContactMaterial*) materialHandle; dgVector force( material->m_normal.Scale(material->m_normal_Force) + material->m_dir0.Scale(material->m_dir0_Force) + material->m_dir1.Scale(material->m_dir1_Force)); forcePtr[0] = force.m_x; forcePtr[1] = force.m_y; forcePtr[2] = force.m_z; if ((dgBody*) body != material->m_body0) { forcePtr[0] *= dgFloat32(-1.0f); forcePtr[1] *= dgFloat32(-1.0f); forcePtr[2] *= dgFloat32(-1.0f); } } // Name: NewtonMaterialGetContactTangentDirections // Get the contact tangent vector to the contact point. // // Parameters: // *const NewtonMaterial* materialHandle - pointer to a material pair. // *dFloat* *dir0 - pointer to an array of at least three floats to hold the contact primary tangent vector. // *dFloat* *dir1 - pointer to an array of at least three floats to hold the contact secondary tangent vector. // // Return: Nothing. // // Remarks: This function can only be called from a material callback event handler. // // See also: NewtonMaterialSetCollisionCallback void NewtonMaterialGetContactTangentDirections( const NewtonMaterial* const materialHandle, NewtonBody* const body, dFloat* const dir0, dFloat* const dir1) { TRACE_FUNTION(__FUNCTION__); dgContactMaterial* const material = (dgContactMaterial*) materialHandle; dir0[0] = material->m_dir0.m_x; dir0[1] = material->m_dir0.m_y; dir0[2] = material->m_dir0.m_z; dir1[0] = material->m_dir1.m_x; dir1[1] = material->m_dir1.m_y; dir1[2] = material->m_dir1.m_z; if ((dgBody*) body != material->m_body0) { dir0[0] *= dgFloat32(-1.0f); dir0[1] *= dgFloat32(-1.0f); dir0[2] *= dgFloat32(-1.0f); dir1[0] *= dgFloat32(-1.0f); dir1[1] *= dgFloat32(-1.0f); dir1[2] *= dgFloat32(-1.0f); } } // Name: NewtonMaterialGetBodyCollisionID // Retrieve a user defined value stored with a convex collision primitive. // // Parameters: // *const NewtonMaterial* materialHandle - pointer to a material pair. // *const NewtonBody* *bodyPtr - is the pointer to the body. // // Return: a user defined value. Zero if not id was stored with the collision primitive. // // Remarks: the application can store an id with any collision primitive. This id can be used to identify what type of collision primitive generated a contact. // This function can only be called from a contact callback, // // Remarks: this function can only be called from a contact process callback. If called from contact callback begin this function will crash the application. // // See also: NewtonCollisionSetUserID, NewtonCreateBox, NewtonCreateSphere unsigned NewtonMaterialGetBodyCollisionID(const NewtonMaterial* const material, const NewtonBody* const body) { TRACE_FUNTION(__FUNCTION__); dgBody* const bodyPtr = (dgBody*) body; dgContactMaterial* const materialPtr = (dgContactMaterial*) material; dgCollision* collision = materialPtr->m_collision0; if (bodyPtr == materialPtr->m_body1) { collision = materialPtr->m_collision1; } return collision->SetUserDataID(); } // Name: NewtonMaterialSetContactSoftness // Override the default softness value for the contact. // // Parameters: // *const NewtonMaterial* materialHandle - pointer to a material pair. // *dFloat* softness - softness value, must be positive. // // Return: Nothing. // // Remarks: This function can only be called from a material callback event handler. // // See also: NewtonMaterialSetCollisionCallback, NewtonMaterialSetDefaultSoftness void NewtonMaterialSetContactSoftness( const NewtonMaterial* const materialHandle, dFloat softness) { TRACE_FUNTION(__FUNCTION__); dgContactMaterial* const material = (dgContactMaterial*) materialHandle; material->m_softness = ClampValue(softness, dFloat(0.01f), dFloat(0.7f)); } // Name: NewtonMaterialSetContactElasticity // Override the default elasticity (coefficient of restitution) value for the contact. // // Parameters: // *const NewtonMaterial* materialHandle - pointer to a material pair. // *dFloat* restitution - elasticity value, must be positive. // // Return: Nothing. // // Remarks: This function can only be called from a material callback event handler. // // See also: NewtonMaterialSetCollisionCallback, NewtonMaterialSetDefaultElasticity void NewtonMaterialSetContactElasticity( const NewtonMaterial* const materialHandle, dFloat restitution) { TRACE_FUNTION(__FUNCTION__); dgContactMaterial* const material = (dgContactMaterial*) materialHandle; material->m_restitution = ClampValue(restitution, dFloat(0.01f), dFloat(2.0f)); } // Name: NewtonMaterialSetContactFrictionState // Enable or disable friction calculation for this contact. // // Parameters: // *const NewtonMaterial* materialHandle - pointer to a material pair. // *int* state* - new state. 0 makes the contact frictionless along the index tangent vector. // *int* index - index to the tangent vector. 0 for primary tangent vector or 1 for the secondary tangent vector. // // Return: Nothing. // // Remarks: This function can only be called from a material callback event handler. // // See also: NewtonMaterialSetCollisionCallback void NewtonMaterialSetContactFrictionState( const NewtonMaterial* const materialHandle, int state, int index) { TRACE_FUNTION(__FUNCTION__); dgContactMaterial* const material = (dgContactMaterial*) materialHandle; if (index) { // material->m_friction1Enable = state ? true : false; if (state) { material->m_flags |= dgContactMaterial::m_friction1Enable__; } else { material->m_flags &= ~dgContactMaterial::m_friction1Enable__; } } else { // material->m_friction0Enable = state ? true : false; if (state) { material->m_flags |= dgContactMaterial::m_friction0Enable__; } else { material->m_flags &= ~dgContactMaterial::m_friction0Enable__; } } } // Name: NewtonMaterialSetContactFrictionCoef // Override the default value of the kinetic and static coefficient of friction for this contact. // // Parameters: // *const NewtonMaterial* materialHandle - pointer to a material pair. // *dFloat* staticFrictionCoef - static friction coefficient. Must be positive. // *dFloat* kineticFrictionCoef - static friction coefficient. Must be positive. // *int* index - index to the tangent vector. 0 for primary tangent vector or 1 for the secondary tangent vector. // // Return: Nothing. // // Remarks: This function can only be called from a material callback event handler. // // Remarks: It is recommended that *coef* be set to a value lower or equal to 1.0, however because some synthetic materials // can have hight than one coefficient of friction Newton allows for the coefficient of friction to be as high as 2.0. // // Remarks: the value *staticFrictionCoef* and *kineticFrictionCoef* will be clamped between 0.01f and 2.0. // If the application wants to set a kinetic friction higher than the current static friction it must increase the static friction first. // // See also: NewtonMaterialSetCollisionCallback, NewtonMaterialSetDefaultFriction, NewtonMaterialSetContactStaticFrictionCoef void NewtonMaterialSetContactFrictionCoef( const NewtonMaterial* const materialHandle, dFloat staticFrictionCoef, dFloat kineticFrictionCoef, int index) { TRACE_FUNTION(__FUNCTION__); dgContactMaterial* const material = (dgContactMaterial*) materialHandle; if (staticFrictionCoef < kineticFrictionCoef) { staticFrictionCoef = kineticFrictionCoef; } if (index) { material->m_staticFriction1 = ClampValue(staticFrictionCoef, dFloat(0.01f), dFloat(2.0f)); material->m_dynamicFriction1 = ClampValue(kineticFrictionCoef, dFloat(0.01f), dFloat(2.0f)); } else { material->m_staticFriction0 = ClampValue(staticFrictionCoef, dFloat(0.01f), dFloat(2.0f)); material->m_dynamicFriction0 = ClampValue(kineticFrictionCoef, dFloat(0.01f), dFloat(2.0f)); } } // Name: NewtonMaterialSetContactNormalAcceleration // Force the contact point to have a non-zero acceleration aligned this the contact normal. // // Parameters: // *const NewtonMaterial* materialHandle - pointer to a material pair. // *dFloat* accel - desired contact acceleration, Must be a positive value // // Return: Nothing. // // Remarks: This function can only be called from a material callback event handler. // // Remarks: This function can be used for spacial effects like implementing jump, of explosive contact in a call back. // // See also: NewtonMaterialSetCollisionCallback void NewtonMaterialSetContactNormalAcceleration( const NewtonMaterial* const materialHandle, dFloat accel) { TRACE_FUNTION(__FUNCTION__); dgContactMaterial* const material = (dgContactMaterial*) materialHandle; // if (accel > dFloat (0.0f)) { material->m_normal_Force = accel; // material->m_overrideNormalAccel = true; material->m_flags |= dgContactMaterial::m_overrideNormalAccel__; // } } // Name: NewtonMaterialSetContactTangentAcceleration // Force the contact point to have a non-zero acceleration along the surface plane. // // Parameters: // *const NewtonMaterial* materialHandle - pointer to a material pair. // *dFloat* accel - desired contact acceleration. // *int* index - index to the tangent vector. 0 for primary tangent vector or 1 for the secondary tangent vector. // // Return: Nothing. // // Remarks: This function can only be called from a material callback event handler. // // See also: NewtonMaterialSetCollisionCallback, NewtonMaterialContactRotateTangentDirections void NewtonMaterialSetContactTangentAcceleration( const NewtonMaterial* const materialHandle, dFloat accel, int index) { TRACE_FUNTION(__FUNCTION__); dgContactMaterial* const material = (dgContactMaterial*) materialHandle; if (index) { material->m_dir1_Force = accel; // material->m_override1Accel = true; material->m_flags |= dgContactMaterial::m_override1Accel__; } else { material->m_dir0_Force = accel; // material->m_override0Accel = true; material->m_flags |= dgContactMaterial::m_override0Accel__; } } // Name: NewtonMaterialSetContactNormalDirection // Set the new direction of the for this contact point. // // Parameters: // *const NewtonMaterial* materialHandle - pointer to a material pair. // *const dFloat* *direction - pointer to an array of at least three floats holding the direction vector. // // Return: Nothing. // // Remarks: This function can only be called from a material callback event handler. // This function changes the basis of the contact point to one where the contact normal is aligned to the new direction vector // and the tangent direction are recalculated to be perpendicular to the new contact normal. // // Remarks: In 99.9% of the cases the collision system can calculates a very good contact normal. // however this algorithm that calculate the contact normal use as criteria the normal direction // that will resolve the inter penetration with the least amount on motion. // There are situations however when this solution is not the best. Take for example a rolling // ball over a tessellated floor, when the ball is over a flat polygon, the contact normal is always // perpendicular to the floor and pass by the origin of the sphere, however when the sphere is going // across two adjacent polygons, the contact normal is now perpendicular to the polygons edge and this does // not guarantee they it will pass bay the origin of the sphere, but we know that the best normal is always // the one passing by the origin of the sphere. // // See also: NewtonMaterialSetCollisionCallback, NewtonMaterialContactRotateTangentDirections void NewtonMaterialSetContactNormalDirection( const NewtonMaterial* const materialHandle, const dFloat* const direction) { TRACE_FUNTION(__FUNCTION__); dgContactMaterial* const material = (dgContactMaterial*) materialHandle; dgVector normal(direction[0], direction[1], direction[2], dgFloat32(0.0f)); _ASSERTE( (dgAbsf (normal % material->m_normal) - dgFloat32(1.0f)) <dgFloat32 (0.01f)); if ((normal % material->m_normal) < dgFloat32(0.0f)) { normal = normal.Scale(-dgFloat32(1.0f)); } material->m_normal = normal; dgMatrix matrix(normal); material->m_dir1 = matrix.m_up; material->m_dir0 = matrix.m_right; // NewtonMaterialContactRotateTangentDirections(materialHandle, &material->m_dir0[0]); } // Name: NewtonMaterialContactRotateTangentDirections // Rotate the tangent direction of the contacts until the primary direction is aligned with the alignVector. // // Parameters: // *const NewtonMaterial* materialHandle - pointer to a material pair. // *const dFloat* *alignVector - pointer to an array of at least three floats holding the aligning vector. // // Return: Nothing. // // Remarks: This function can only be called from a material callback event handler. // This function rotates the tangent vectors of the contact point until the primary tangent vector and the align vector // are perpendicular (ex. when the dot product between the primary tangent vector and the alignVector is 1.0). This // function can be used in conjunction with NewtonMaterialSetContactTangentAcceleration in order to // create special effects. For example, conveyor belts, cheap low LOD vehicles, slippery surfaces, etc. // // See also: NewtonMaterialSetCollisionCallback, NewtonMaterialSetContactNormalDirection void NewtonMaterialContactRotateTangentDirections( const NewtonMaterial* const materialHandle, const dFloat* const alignVector) { TRACE_FUNTION(__FUNCTION__); dgContactMaterial* const material = (dgContactMaterial*) materialHandle; const dgVector dir0(alignVector[0], alignVector[1], alignVector[2], dgFloat32(0.0f)); dgVector dir1 = material->m_normal * dir0; dFloat mag2 = dir1 % dir1; if (mag2 > 1.0e-6f) { material->m_dir1 = dir1.Scale(dgRsqrt (mag2)); material->m_dir0 = material->m_dir1 * material->m_normal; } } // ********************************************************************************************** // // Name: Convex collision primitives interface // // ********************************************************************************************** // Name: NewtonCreateNull // Create a transparent collision primitive. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // // Return: Pointer to the collision object. // // Remarks: Some times the application needs to create helper rigid bodies that will never collide with other bodies, // for example the neck of a rag doll, or an internal part of an articulated structure. This can be done by using the material system // but it too much work and it will increase unnecessarily the material count, and therefore the project complexity. The Null collision // is a collision object that satisfy all this conditions without having to change the engine philosophy. // // Remarks: Collision primitives are reference counted objects. The application should call *NewtonReleaseCollision* in order to release references to the objects. // Neglecting to release references to collision primitives is a common cause of memory leaks. // Collision primitives can be reused with more than one body. This will reduce the amount of memory used by the engine, as well // as speed up some calculations. // // See also: NewtonReleaseCollision NewtonCollision* NewtonCreateNull(const NewtonWorld* const newtonWorld) { Newton* world; TRACE_FUNTION(__FUNCTION__); world = (Newton *) newtonWorld; return (NewtonCollision*) world->CreateNull(); } // Name: NewtonCreateBox // Create a box primitive for collision. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *dFloat* dx - box side one x dimension. // *dFloat* dy - box side one y dimension. // *dFloat* dz - box side one z dimension. // *const dFloat* *offsetMatrix - pointer to an array of 16 floats containing the offset matrix of the box relative to the body. If this parameter is NULL, then the primitive is centered at the origin of the body. // // Return: Pointer to the box // // Remarks: Collision primitives are reference counted objects. The application should call *NewtonReleaseCollision* in order to release references to the object. // Neglecting to release references to collision primitives is a common cause of memory leaks. // Collision primitives can be reused with more than one body. This will reduce the amount of memory used be the engine, as well // as speed up some calculations. // // See also: NewtonAddCollisionReference, NewtonReleaseCollision, NewtonCreateConvexHullModifier NewtonCollision* NewtonCreateBox(const NewtonWorld* const newtonWorld, dFloat dx, dFloat dy, dFloat dz, int shapeID, const dFloat* const offsetMatrix) { Newton* world; TRACE_FUNTION(__FUNCTION__); world = (Newton *) newtonWorld; dgMatrix matrix(dgGetIdentityMatrix()); if (offsetMatrix) { matrix = *((dgMatrix*) offsetMatrix); } return (NewtonCollision*) world->CreateBox(dx, dy, dz, shapeID, matrix); } // Name: NewtonCreateSphere // Create a generalized ellipsoid primitive.. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *dFloat* radiusX - sphere radius along x axis. // *dFloat* radiusY - sphere radius along x axis. // *dFloat* radiusZ - sphere radius along x axis. // *const dFloat* *offsetMatrix - pointer to an array of 16 floats containing the offset matrix of the sphere relative to the body. If this parameter is NULL then the sphere is centered at the origin of the body. // // Return: Pointer to the generalized sphere. // // Remarks: Sphere collision are generalized ellipsoids, the application can create many different kind of objects by just playing with dimensions of the radius. // for example to make a sphere set all tree radius to the same value, to make a ellipse of revolution just set two of the tree radius to the same value. // // Remarks: General ellipsoids are very good hull geometries to represent the outer shell of avatars in a game. // // Remarks: Collision primitives are reference counted objects. The application should call *NewtonReleaseCollision* in order to release references to the object. // Neglecting to release references to collision primitives is a common cause of memory leaks. // Collision primitives can be reused with more than one body. This will reduce the amount of memory used be the engine, as well // as speed up some calculations. // // See also: NewtonAddCollisionReference, NewtonReleaseCollision, NewtonCreateConvexHullModifier NewtonCollision* NewtonCreateSphere(const NewtonWorld* const newtonWorld, dFloat radiusX, dFloat radiusY, dFloat radiusZ, int shapeID, const dFloat* const offsetMatrix) { Newton* world; TRACE_FUNTION(__FUNCTION__); world = (Newton *) newtonWorld; dgMatrix matrix(dgGetIdentityMatrix()); if (offsetMatrix) { matrix = *((dgMatrix*) offsetMatrix); } radiusX = dgAbsf(radiusX); radiusY = dgAbsf(radiusY); radiusZ = dgAbsf(radiusZ); if ((dgAbsf(radiusX - radiusY) < 1.0e-5f) && (dgAbsf(radiusX - radiusZ) < 1.0e-5f)) { return (NewtonCollision*) world->CreateSphere(radiusX, shapeID, matrix); } return (NewtonCollision*) world->CreateEllipse(radiusX, radiusY, radiusZ, shapeID, matrix); } // Name: NewtonCreateCone // Create a cone primitive for collision. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *dFloat* radius - cone radius at the base. // *dFloat* height - cone height along the x local axis from base to tip. // *const dFloat* *offsetMatrix - pointer to an array of 16 floats containing the offset matrix of the box relative to the body. If this parameter is NULL, then the primitive is centered at the origin of the body. // // Return: Pointer to the box // // Remarks: Collision primitives are reference counted objects. The application should call *NewtonReleaseCollision* in order to release references to the object. // Neglecting to release references to collision primitives is a common cause of memory leaks. // Collision primitives can be reused with more than one body. This will reduce the amount of memory used be the engine, as well // as speed up some calculations. // // See also: NewtonAddCollisionReference, NewtonReleaseCollision, NewtonCreateConvexHullModifier NewtonCollision* NewtonCreateCone(const NewtonWorld* const newtonWorld, dFloat radius, dFloat height, int shapeID, const dFloat* const offsetMatrix) { Newton* world; TRACE_FUNTION(__FUNCTION__); world = (Newton *) newtonWorld; dgMatrix matrix(dgGetIdentityMatrix()); if (offsetMatrix) { matrix = *((dgMatrix*) offsetMatrix); } return (NewtonCollision*) world->CreateCone(radius, height, shapeID, matrix); } // Name: NewtonCreateCapsule // Create a capsule primitive for collision. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *dFloat* radius - capsule radius at the base. // *dFloat* height - capsule height along the x local axis from tip to tip. // *const dFloat* *offsetMatrix - pointer to an array of 16 floats containing the offset matrix of the box relative to the body. If this parameter is NULL, then the primitive is centered at the origin of the body. // // Return: Pointer to the box // // Remark: the capsule height must equal of larger than the sum of the cap radius. If this is not the case the height will be clamped the 2 * radius. // // Remarks: Collision primitives are reference counted objects. The application should call *NewtonReleaseCollision* in order to release references to the object. // Neglecting to release references to collision primitives is a common cause of memory leaks. // Collision primitives can be reused with more than one body. This will reduce the amount of memory used be the engine, as well // as speed up some calculations. // // See also: NewtonAddCollisionReference, NewtonReleaseCollision, NewtonCreateConvexHullModifier NewtonCollision* NewtonCreateCapsule(const NewtonWorld* const newtonWorld, dFloat radius, dFloat height, int shapeID, const dFloat* const offsetMatrix) { Newton* world; TRACE_FUNTION(__FUNCTION__); world = (Newton *) newtonWorld; dgMatrix matrix(dgGetIdentityMatrix()); if (offsetMatrix) { matrix = *((dgMatrix*) offsetMatrix); } return (NewtonCollision*) world->CreateCapsule(radius, height, shapeID, matrix); } // Name: NewtonCreateCylinder // Create a cylinder primitive for collision. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *dFloat* radius - cylinder radius at the base. // *dFloat* height - cylinder height along the x local axis. // *const dFloat* *offsetMatrix - pointer to an array of 16 floats containing the offset matrix of the box relative to the body. If this parameter is NULL, then the primitive is centered at the origin of the body. // // Return: Pointer to the box // // Remarks: Collision primitives are reference counted objects. The application should call *NewtonReleaseCollision* in order to release references to the object. // Neglecting to release references to collision primitives is a common cause of memory leaks. // Collision primitives can be reused with more than one body. This will reduce the amount of memory used be the engine, as well // as speed up some calculations. // // See also: NewtonAddCollisionReference, NewtonReleaseCollision, NewtonCreateConvexHullModifier NewtonCollision* NewtonCreateCylinder(const NewtonWorld* const newtonWorld, dFloat radius, dFloat height, int shapeID, const dFloat* const offsetMatrix) { Newton* world; TRACE_FUNTION(__FUNCTION__); world = (Newton *) newtonWorld; dgMatrix matrix(dgGetIdentityMatrix()); if (offsetMatrix) { matrix = *((dgMatrix*) offsetMatrix); } return (NewtonCollision*) world->CreateCylinder(radius, height, shapeID, matrix); } NewtonCollision* NewtonCreateChamferCylinder( const NewtonWorld* const newtonWorld, dFloat radius, dFloat height, const dFloat* const offsetMatrix); // Name: NewtonCreateChamferCylinder // Create a ChamferCylinder primitive for collision. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *dFloat* radius - ChamferCylinder radius at the base. // *dFloat* height - ChamferCylinder height along the x local axis. // *const dFloat* *offsetMatrix - pointer to an array of 16 floats containing the offset matrix of the box relative to the body. If this parameter is NULL, then the primitive is centered at the origin of the body. // // Return: Pointer to the box // // Remarks: Collision primitives are reference counted objects. The application should call *NewtonReleaseCollision* in order to release references to the object. // Neglecting to release references to collision primitives is a common cause of memory leaks. // Collision primitives can be reused with more than one body. This will reduce the amount of memory used be the engine, as well // as speed up some calculations. // // See also: NewtonAddCollisionReference, NewtonReleaseCollision, NewtonCreateConvexHullModifier NewtonCollision* NewtonCreateChamferCylinder( const NewtonWorld* const newtonWorld, dFloat radius, dFloat height, int shapeID, const dFloat* const offsetMatrix) { Newton* world; TRACE_FUNTION(__FUNCTION__); world = (Newton *) newtonWorld; dgMatrix matrix(dgGetIdentityMatrix()); if (offsetMatrix) { matrix = *((dgMatrix*) offsetMatrix); } return (NewtonCollision*) world->CreateChamferCylinder(radius, height, shapeID, matrix); } // Name: NewtonCreateConvexHull // Create a ConvexHull primitive from collision from a cloud of points. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *int* count - number of consecutive point to follow must be at least 4. // *const dFloat* *vertexCloud - pointer to and array of point. // *int* strideInBytes - vertex size in bytes, must be at least 12. // *dFloat* tolerance - tolerance value for the hull generation. // *const dFloat* *offsetMatrix - pointer to an array of 16 floats containing the offset matrix of the box relative to the body. If this parameter is NULL, then the primitive is centered at the origin of the body. // // Return: Pointer to the collision mesh, NULL if the function fail to generate convex shape // // Remarks: Convex hulls are the solution to collision primitive that can not be easily represented by an implicit solid. // The implicit solid primitives (spheres, cubes, cylinders, capsules, cones, etc.), have constant time complexity for contact calculation // and are also extremely efficient on memory usage, therefore the application get perfect smooth behavior. // However for cases where the shape is too difficult or a polygonal representation is desired, convex hulls come closest to the to the model shape. // For example it is a mistake to model a 10000 point sphere as a convex hull when the perfect sphere is available, but it is better to represent a // pyramid by a convex hull than with a sphere or a box. // // Remarks: There is not upper limit as to how many vertex the application can pass to make a hull shape, // however for performance and memory usage concern it is the application responsibility to keep the max vertex at the possible minimum. // The minimum number of vertex should be equal or larger than 4 and it is the application responsibility that the points are part of a solid geometry. // Unpredictable results will occur if all points happen to be collinear or coplanar. // // remark: The performance of collision with convex hull proxies is sensitive to the vertex count of the hull. Since a the convex hull // of a visual geometry is already an approximation of the mesh, for visual purpose there is not significant difference between the // appeal of a exact hull and one close to the exact hull but with but with a smaller vertex count. // It just happens that sometime complex meshes lead to generation of convex hulls with lots of small detail that play not // roll of the quality of the simulation but that have a significant impact on the performance because of a large vertex count. // For this reason the application have the option to set a *tolerance* parameter. // *tolerance* is use to post process the final geometry in the following faction, a point on the surface of the hull can // be remove if the distance of all of the surrounding vertex immediately adjacent to the average plane equation formed the // faces adjacent to that point, is smaller than the tolerance. A value of zero in *tolerance* will generate an exact hull and a value langer that zero // will generate a loosely fitting hull and it willbe faster to generate. // // Remarks: Collision primitives are reference counted objects. The application should call *NewtonReleaseCollision* in order to release references to the object. // Neglecting to release references to collision primitives is a common cause of memory leaks. // Collision primitives can be reused with more than one body. This will reduce the amount of memory used be the engine, as well // as speed up some calculations. // // See also: NewtonAddCollisionReference, NewtonReleaseCollision, NewtonCreateConvexHullModifier NewtonCollision* NewtonCreateConvexHull(const NewtonWorld* const newtonWorld, int count, const dFloat* const vertexCloud, int strideInBytes, dgFloat32 tolerance, int shapeID, const dFloat* const offsetMatrix) { Newton* world; TRACE_FUNTION(__FUNCTION__); world = (Newton *) newtonWorld; dgMatrix matrix(dgGetIdentityMatrix()); if (offsetMatrix) { matrix = *((dgMatrix*) offsetMatrix); } tolerance = ClampValue(tolerance, dgFloat32(0.0f), dgFloat32(0.125f)); return (NewtonCollision*) world->CreateConvexHull(count, vertexCloud, strideInBytes, tolerance, shapeID, matrix); } // Name: NewtonCreateConvexHullFromMesh // Create a ConvexHull primitive from a special effect mesh. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *const NewtonMesh* *mesh - special effect mesh // *dFloat* tolerance - tolerance value for the hull generation. // // Return: Pointer to the collision mesh, NULL if the function fail to generate convex shape // // Remark: Because the in general this function is used for runtime special effect like debris and or solid particles // it is recommended that the source mesh complexity is kept small. // // See also: NewtonCreateConvexHull, NewtonMeshCreate NewtonCollision* NewtonCreateConvexHullFromMesh( const NewtonWorld* const newtonWorld, const NewtonMesh* const mesh, dFloat tolerance, int shapeID) { TRACE_FUNTION(__FUNCTION__); dgMeshEffect* const meshEffect = (dgMeshEffect*) mesh; return (NewtonCollision*) meshEffect->CreateConvexCollision(tolerance, shapeID); } // Name: NewtonCreateConvexHullModifier // Create a collision modifier for any convex collision part. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *NewtonCollision* convexHullCollision. // // Return: Pointer to the collision modifier // // Remarks: The matrix should be arranged in row-major order. // a collision modifier can take any type of transformation matrix, as long as the matrix can be invertible by straight // Gaussian elimination process. Typical uses are non-uniform scaling, translation and skewing. // // Remarks: Collision modifier can be used by the application to achieve effects like animating collision geometry at run time, // however care must taken as animation of a collision primitive could result in unwanted penetrations. // // See also: NewtonAddCollisionReference, NewtonReleaseCollision, NewtonConvexHullModifierSetMatrix, NewtonConvexHullModifierGetMatrix NewtonCollision* NewtonCreateConvexHullModifier( const NewtonWorld* const newtonWorld, const NewtonCollision* const convexHullCollision, int shapeID) { Newton* world; dgCollision* collision; TRACE_FUNTION(__FUNCTION__); world = (Newton *) newtonWorld; collision = world->CreateConvexModifier((dgCollision*) convexHullCollision); collision->SetUserDataID(dgUnsigned32(shapeID)); return (NewtonCollision*) collision; } // Name: NewtonConvexHullModifierGetMatrix // Get the transformation matrix of a convex hull modifier collision. // // Parameters: // *const NewtonCollision* *convexHullModifier - pointer to the body. // *dFloat* *matrixPtr - pointer to an array of 16 floats containing the global matrix of the collision modifier. // // Return: Nothing. // // Remarks: The matrix should be arranged in row-major order. // a collision modifier can take any type of transformation matrix, as long as the matrix can be invertible by straight // Gaussian elimination process. Typical uses are non-uniform scaling, translation and skewing. // // Remarks: Collision modifier can be used by the application to achieve effects like animating collision geometry at run time, // however care must taken as animation of a collision primitive could result into unwanted penetrations. // // See also: NewtonCreateConvexHullModifier, NewtonConvexHullModifierSetMatrix void NewtonConvexHullModifierGetMatrix( const NewtonCollision* convexHullModifier, dFloat* matrixPtr) { dgCollision* collision; collision = (dgCollision*) convexHullModifier; TRACE_FUNTION(__FUNCTION__); dgMatrix& matrix = (*((dgMatrix*) matrixPtr)); matrix = collision->ModifierGetMatrix(); } // Name: NewtonConvexHullModifierSetMatrix // Set the transformation matrix of a convex hull modifier collision. // // Parameters: // *const NewtonCollision* *convexHullModifier - pointer to the body. // *const dFloat* *matrixPtr - pointer to an array of 16 floats containing the global matrix of the collision modifier. // // Return: Nothing. // // Remarks: The matrix should be arranged in row-major order. // a collision modifier can take any type of transformation matrix, as long as the matrix can be invertible by straight // Gaussian elimination process. Typical uses are non-uniform scaling, translation and skewing. // // Remarks: Collision modifier can be used by the application to achieve effects like animating collision geometry at run time, // however care must taken as animation of a collision primitive could result into unwanted penetrations. // // See also: NewtonCreateConvexHullModifier, NewtonConvexHullModifierGetMatrix void NewtonConvexHullModifierSetMatrix( const NewtonCollision* convexHullModifier, const dFloat* const matrixPtr) { dgCollision* collision; collision = (dgCollision*) convexHullModifier; TRACE_FUNTION(__FUNCTION__); const dgMatrix& matrix = (*((dgMatrix*) matrixPtr)); collision->ModifierSetMatrix(matrix); } // Name: NewtonCreateCompoundCollision // Create a container to hold an array of convex collision primitives. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *int* count - number of primitives in the array. // *const NewtonCollision* **collisionPrimitiveArray - pointer to an array of convex collision primitives. This array must be filled with convex collision primitives before this function is called. // *int* shapeID // // Return: Pointer to the compound collision. // // Remarks: Compound collision primitives can only be made of convex collision primitives and they can not contain compound collision. Therefore they are treated as convex primitives. // // Remarks: Compound collision primitives are treated as instance collision objects that can not shared by multiples rigid bodies. // // Remarks: Collision primitives are reference counted objects. The application should call *NewtonReleaseCollision* in order to release references to the object. // Neglecting to release references to collision primitives is a common cause of memory leaks. // // See also: NewtonReleaseCollision NewtonCollision* NewtonCreateCompoundCollision( const NewtonWorld* const newtonWorld, int count, NewtonCollision* const collisionPrimitiveArray[], int shapeID) { TRACE_FUNTION(__FUNCTION__); Newton* world = (Newton *) newtonWorld; dgCollision* collision = world->CreateCollisionCompound(count, (dgCollision**) collisionPrimitiveArray); collision->SetUserDataID(dgUnsigned32(shapeID)); return (NewtonCollision*) collision; } // Name: NewtonCreateCompoundCollisionFromMesh // Create a compound collision from a concave mesh by an approximate convex partition // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *const NewtonMesh* *mesh - pointed concave mesh. // *int* maxsubShapesCount, // *int* shapeID // *int* subShapeId // // // Return: Pointer to the compound collision. // // Remarks: The algorithm will separated the the original mesh into a series of sub meshes until either // the worse concave point is smaller than the specified min concavity or the max number convex shapes is reached. // // Remarks: is is recommended that convex approximation are made by person with a graphics toll by physically overlaying collision primitives over the concave mesh. // but for quit test of maybe for simple meshes and algorithm approximations can be used. // // Remarks: is is recommended that for best performance this function is used in an off line toll and serialize the output. // // Remarks: Compound collision primitives are treated as instanced collision objects that cannot be shared by multiples rigid bodies. // // Remarks: Collision primitives are reference counted objects. The application should call *NewtonReleaseCollision* in order to release references to the object. // Neglecting to release references to collision primitives is a common cause of memory leaks. // // See also: NewtonCreateCompoundCollision NEWTON_API NewtonCollision* NewtonCreateCompoundAproximation( const NewtonWorld* const newtonWorld, const dFloat* const points, int pointCount, int pointStride, const int* const triangleIndex, int indexCount, dFloat concavity, int shapeID, int subShapeID) { // TRACE_FUNTION(__FUNCTION__); // Newton* const world = (Newton *)newtonWorld; // dgMeshEffect* effectMesh = (dgMeshEffect*) mesh; // dgCollision* collision = effectMesh->CreateConvexApproximationCollision(world, maxSubShapesCount, shapeID, subShapeID); // return (NewtonCollision*) collision; _ASSERTE(0); return NULL; /* NewtonMesh* convexAproximation = NewtonMeshConvexApproximation (mesh, concavity); dgList<NewtonCollision*> list(world->dgWorld::GetAllocator()); NewtonMesh* nextSegment = NULL; for (NewtonMesh* segment = NewtonMeshCreateFirstSingleSegment (convexAproximation); segment; segment = nextSegment) { nextSegment = NewtonMeshCreateNextSingleSegment (convexAproximation, segment); NewtonCollision* convexHull = NewtonCreateConvexHullFromMesh (newtonWorld, segment, 0.01f, subShapeID); if (convexHull) { list.Append(convexHull); } NewtonMeshDestroy(segment); } int count = 0; dgStack<NewtonCollision*> array(list.GetCount()); for (dgList<NewtonCollision*>::dgListNode* node = list.GetFirst(); node; node = node->GetNext()) { array[count] = node->GetInfo(); count ++; } NewtonCollision* collision = NewtonCreateCompoundCollision(newtonWorld, count, &array[0], shapeID); for (dgInt32 i = 0; i < count; i ++) { NewtonReleaseCollision(newtonWorld, array[i]); } NewtonMeshDestroy(convexAproximation); return collision; */ } NEWTON_API NewtonCollision* NewtonCreateCompoundBreakable( const NewtonWorld* const newtonWorld, int meshCount, const NewtonMesh** const solids, const int* const shapeIDArray, const dFloat* const densities, const int* const internalFaceMaterial, int shapeID, int debriID, dFloat debriSeparationGap) { Newton* world; dgCollision* collision; world = (Newton *) newtonWorld; TRACE_FUNTION(__FUNCTION__); collision = world->CreateCollisionCompoundBreakable(meshCount, (dgMeshEffect**) solids, shapeIDArray, densities, internalFaceMaterial, debriID, debriSeparationGap); collision->SetUserDataID(dgUnsigned32(shapeID)); return (NewtonCollision*) collision; } void NewtonCompoundBreakableResetAnchoredPieces( const NewtonCollision* const compoundBreakable) { dgCollision* collision; TRACE_FUNTION(__FUNCTION__); collision = (dgCollision*) compoundBreakable; if (collision->IsType(dgCollision::dgCollisionCompoundBreakable_RTTI)) { dgCollisionCompoundBreakable* compound; compound = (dgCollisionCompoundBreakable*) collision; compound->ResetAnchor(); } } void NewtonCompoundBreakableSetAnchoredPieces( const NewtonCollision* const compoundBreakable, int fixShapesCount, dFloat* const matrixPallete, NewtonCollision** const fixedShapesArray) { dgCollision* collision; TRACE_FUNTION(__FUNCTION__); collision = (dgCollision*) compoundBreakable; if (collision->IsType(dgCollision::dgCollisionCompoundBreakable_RTTI)) { dgCollisionCompoundBreakable* compound; compound = (dgCollisionCompoundBreakable*) collision; compound->SetAnchoredParts(fixShapesCount, (dgMatrix*) matrixPallete, (const dgCollision**) fixedShapesArray); } } NewtonbreakableComponentMesh* NewtonBreakableGetMainMesh( const NewtonCollision* const compoundBreakable) { dgCollision* collision; NewtonbreakableComponentMesh* mesh; TRACE_FUNTION(__FUNCTION__); collision = (dgCollision*) compoundBreakable; mesh = NULL; if (collision->IsType(dgCollision::dgCollisionCompoundBreakable_RTTI)) { dgCollisionCompoundBreakable* compound; compound = (dgCollisionCompoundBreakable*) collision; mesh = (NewtonbreakableComponentMesh*) compound->GetMainMesh(); } return mesh; } void NewtonBreakableBeginDelete(const NewtonCollision* const compoundBreakable) { dgCollision* collision; NewtonbreakableComponentMesh* mesh; TRACE_FUNTION(__FUNCTION__); collision = (dgCollision*) compoundBreakable; mesh = NULL; if (collision->IsType(dgCollision::dgCollisionCompoundBreakable_RTTI)) { dgCollisionCompoundBreakable* compound; compound = (dgCollisionCompoundBreakable*) collision; compound->DeleteComponentBegin(); } } NewtonBody* NewtonBreakableCreateDebrieBody( const NewtonCollision* const compoundBreakable, const NewtonbreakableComponentMesh* const component) { dgBody* body; dgCollision* collision; NewtonbreakableComponentMesh* mesh; TRACE_FUNTION(__FUNCTION__); collision = (dgCollision*) compoundBreakable; mesh = NULL; body = NULL; if (collision->IsType(dgCollision::dgCollisionCompoundBreakable_RTTI)) { dgCollisionCompoundBreakable* compound; compound = (dgCollisionCompoundBreakable*) collision; body = compound->CreateComponentBody( (dgCollisionCompoundBreakable::dgDebriGraph::dgListNode*) component); } return (NewtonBody*) body; } void NewtonBreakableDeleteComponent( const NewtonCollision* const compoundBreakable, const NewtonbreakableComponentMesh* const component) { dgCollision* collision; NewtonbreakableComponentMesh* mesh; TRACE_FUNTION(__FUNCTION__); collision = (dgCollision*) compoundBreakable; mesh = NULL; if (collision->IsType(dgCollision::dgCollisionCompoundBreakable_RTTI)) { dgCollisionCompoundBreakable* compound; compound = (dgCollisionCompoundBreakable*) collision; compound->DeleteComponent( (dgCollisionCompoundBreakable::dgDebriGraph::dgListNode*) component); } } void NewtonBreakableEndDelete(const NewtonCollision* const compoundBreakable) { dgCollision* collision; NewtonbreakableComponentMesh* mesh; TRACE_FUNTION(__FUNCTION__); collision = (dgCollision*) compoundBreakable; mesh = NULL; if (collision->IsType(dgCollision::dgCollisionCompoundBreakable_RTTI)) { dgCollisionCompoundBreakable* compound; compound = (dgCollisionCompoundBreakable*) collision; compound->DeleteComponentEnd(); } } NewtonbreakableComponentMesh* NewtonBreakableGetFirstComponent( const NewtonCollision* const compoundBreakable) { dgCollision* collision; NewtonbreakableComponentMesh* mesh; TRACE_FUNTION(__FUNCTION__); collision = (dgCollision*) compoundBreakable; mesh = NULL; if (collision->IsType(dgCollision::dgCollisionCompoundBreakable_RTTI)) { dgCollisionCompoundBreakable* compound; compound = (dgCollisionCompoundBreakable*) collision; mesh = (NewtonbreakableComponentMesh*) compound->GetFirstComponentMesh(); } return mesh; } NewtonbreakableComponentMesh* NewtonBreakableGetNextComponent( const NewtonbreakableComponentMesh* const component) { dgCollisionCompoundBreakable::dgDebriGraph::dgListNode* node; TRACE_FUNTION(__FUNCTION__); node = (dgCollisionCompoundBreakable::dgDebriGraph::dgListNode*) component; node = node->GetNext(); return node->GetNext() ? (NewtonbreakableComponentMesh*) node : NULL; } int NewtonCompoundBreakableGetVertexCount( const NewtonCollision* const compoundBreakable) { dgInt32 count; dgCollision* collision; TRACE_FUNTION(__FUNCTION__); collision = (dgCollision*) compoundBreakable; count = 0; if (collision->IsType(dgCollision::dgCollisionCompoundBreakable_RTTI)) { dgCollisionCompoundBreakable* compound; compound = (dgCollisionCompoundBreakable*) collision; count = compound->GetVertecCount(); } return count; } void NewtonCompoundBreakableGetVertexStreams( const NewtonCollision* const compoundBreakable, int vertexStrideInByte, dFloat* const vertex, int normalStrideInByte, dFloat* const normal, int uvStrideInByte, dFloat* const uv) { dgCollision* collision; TRACE_FUNTION(__FUNCTION__); collision = (dgCollision*) compoundBreakable; if (collision->IsType(dgCollision::dgCollisionCompoundBreakable_RTTI)) { dgCollisionCompoundBreakable* compound; compound = (dgCollisionCompoundBreakable*) collision; compound->GetVertexStreams(vertexStrideInByte, vertex, normalStrideInByte, normal, uvStrideInByte, uv); } } void* NewtonBreakableGetFirstSegment( const NewtonbreakableComponentMesh* const breakableComponent) { dgCollisionCompoundBreakable::dgDebriGraph::dgListNode* node; TRACE_FUNTION(__FUNCTION__); node = (dgCollisionCompoundBreakable::dgDebriGraph::dgListNode*) breakableComponent; return node->GetInfo().m_nodeData.m_mesh->GetFirst(); } void* NewtonBreakableGetNextSegment(const void* const segment) { dgCollisionCompoundBreakable::dgMesh::dgListNode* node; TRACE_FUNTION(__FUNCTION__); node = (dgCollisionCompoundBreakable::dgMesh::dgListNode*) segment; return node->GetNext(); } int NewtonBreakableGetComponentsInRadius( const NewtonCollision* const compoundBreakable, const dFloat* position, dFloat radius, NewtonbreakableComponentMesh** const segments, int maxCount) { dgInt32 count; dgCollision* collision; TRACE_FUNTION(__FUNCTION__); count = 0; collision = (dgCollision*) compoundBreakable; if (collision->IsType(dgCollision::dgCollisionCompoundBreakable_RTTI)) { dgCollisionCompoundBreakable* compound; compound = (dgCollisionCompoundBreakable*) collision; dgVector origin(position[0], position[1], position[2], dgFloat32(0.0f)); count = compound->GetSegmentsInRadius(origin, radius, (dgCollisionCompoundBreakable::dgDebriGraph::dgListNode**) segments, maxCount); } return count; } int NewtonBreakableSegmentGetMaterial(const void* const segment) { dgCollisionCompoundBreakable::dgMesh::dgListNode* node; TRACE_FUNTION(__FUNCTION__); node = (dgCollisionCompoundBreakable::dgMesh::dgListNode*) segment; return node->GetInfo().m_material; } int NewtonBreakableSegmentGetIndexCount(const void* const segment) { dgCollisionCompoundBreakable::dgMesh::dgListNode* node; TRACE_FUNTION(__FUNCTION__); node = (dgCollisionCompoundBreakable::dgMesh::dgListNode*) segment; return node->GetInfo().m_faceCount * 3; } int NewtonBreakableSegmentGetIndexStream( const NewtonCollision* const compoundBreakable, const NewtonbreakableComponentMesh* const meshOwner, const void* const segment, int* const index) { int count; dgCollision* collision; TRACE_FUNTION(__FUNCTION__); count = 0; collision = (dgCollision*) compoundBreakable; if (collision->IsType(dgCollision::dgCollisionCompoundBreakable_RTTI)) { dgCollisionCompoundBreakable* compound; compound = (dgCollisionCompoundBreakable*) collision; count = compound->GetSegmentIndexStream( (dgCollisionCompoundBreakable::dgDebriGraph::dgListNode*) meshOwner, (dgCollisionCompoundBreakable::dgMesh::dgListNode*) segment, index); } return count; } int NewtonBreakableSegmentGetIndexStreamShort( const NewtonCollision* const compoundBreakable, const NewtonbreakableComponentMesh* const meshOwner, const void* const segment, short int* const index) { int count; dgCollision* collision; TRACE_FUNTION(__FUNCTION__); count = 0; collision = (dgCollision*) compoundBreakable; if (collision->IsType(dgCollision::dgCollisionCompoundBreakable_RTTI)) { dgCollisionCompoundBreakable* compound; compound = (dgCollisionCompoundBreakable*) collision; count = compound->GetSegmentIndexStreamShort( (dgCollisionCompoundBreakable::dgDebriGraph::dgListNode*) meshOwner, (dgCollisionCompoundBreakable::dgMesh::dgListNode*) segment, index); } return count; } // Name: NewtonCollisionSetAsTriggerVolume // Return the trigger volume flag of this shape. // // Parameters: // *const NewtonCollision* convexCollision - is the pointer to a convex collision primitive. // // Return: 0 if collison shape is solid, non zero is collision shspe is a trigger volume. // // Remarks: this function can be used to place collision triggers in the scene. // Setting this flag is not really a neessesary to place a collision trigger however this option hint the egine that // this particular shape is a trigger volume and no contact calculation is desired. // // See also: NewtonCollisionIsTriggerVolume int NewtonCollisionIsTriggerVolume(const NewtonCollision* const convexCollision) { dgCollision* collision; collision = (dgCollision*) convexCollision; TRACE_FUNTION(__FUNCTION__); return collision->IsTriggerVolume() ? 1 : 0; } // Name: NewtonCollisionSetAsTriggerVolume // Set a flag on a convex collision shape to indicate that no contacts should calculated for this shape. // // Parameters: // *const NewtonCollision* convexCollision - is the pointer to a convex collision primitive. // *unsigned* triggerMode - 1 set diecable contact calculation 0 enable contact calculation. // // Return: nothing // // Remarks: this function can be used to place collision triggers in the scene. // Setting this flag is not really a nessesary to place a collision trigger however this option hint the egine that // this particular shape is a trigger volume and no contact calculation is desired. // // See also: NewtonCollisionIsTriggerVolume void NewtonCollisionSetAsTriggerVolume(const NewtonCollision* convexCollision, int trigger) { dgCollision* collision; collision = (dgCollision*) convexCollision; TRACE_FUNTION(__FUNCTION__); collision->SetAsTriggerVolume(trigger ? true : false); } void NewtonCollisionSetMaxBreakImpactImpulse( const NewtonCollision* const convexHullCollision, dFloat maxImpactImpulse) { dgCollision* collision; collision = (dgCollision*) convexHullCollision; TRACE_FUNTION(__FUNCTION__); collision->SetBreakImpulse(dgFloat32(maxImpactImpulse)); } dFloat NewtonCollisionGetMaxBreakImpactImpulse( const NewtonCollision* const convexHullCollision) { dgCollision* collision; collision = (dgCollision*) convexHullCollision; TRACE_FUNTION(__FUNCTION__); return dgFloat32(collision->GetBreakImpulse()); } // Name: NewtonCollisionSetUserID // Store a user defined value with a convex collision primitive. // // Parameters: // *const NewtonCollision* collision - is the pointer to a collision primitive. // *unsigned* id - value to store with the collision primitive. // // Return: nothing // // Remarks: the application can store an id with any collision primitive. This id can be used to identify what type of collision primitive generated a contact. // // See also: NewtonMaterialGetBodyCollisionID, NewtonCollisionGetUserID, NewtonCreateBox, NewtonCreateSphere void NewtonCollisionSetUserID(const NewtonCollision* const collision, unsigned id) { dgCollision* coll; coll = (dgCollision*) collision; TRACE_FUNTION(__FUNCTION__); coll->SetUserDataID(id); } // Name: NewtonCollisionGetUserID // Return a user define value with a convex collision primitive. // // Parameters: // *const NewtonCollision* collision - is the pointer to a convex collision primitive. // // Return: user id // // Remarks: the application can store an id with any collision primitive. This id can be used to identify what type of collision primitive generated a contact. // // See also: NewtonMaterialGetBodyCollisionID, NewtonMaterialGetBodyCollisionID, NewtonCreateBox, NewtonCreateSphere unsigned NewtonCollisionGetUserID(const NewtonCollision* const collision) { dgCollision* coll; TRACE_FUNTION(__FUNCTION__); coll = (dgCollision*) collision; // //return unsigned (dgUnsigned64 (collision->GetUserData())); // return unsigned (PointerToInt (collision->GetUserData())); return coll->SetUserDataID(); } // Name: NewtonConvexHullGetFaceIndices // Return the number of vertices of face and copy each index into array faceIndices. // // Parameters: // *const NewtonCollision* convexHullCollision - is the pointer to a convex collision hull primitive. // // Return: user face count of face. // // Remarks: this function will return zero on all shapes other than a convex full collision shape. // // Remarks: To get the number of faces of a convex hull shape see function *NewtonCollisionGetInfo* // // See also: NewtonCollisionGetInfo, NewtonCreateConvexHull int NewtonConvexHullGetFaceIndices( const NewtonCollision* const convexHullCollision, int face, int* const faceIndices) { dgCollision* coll; TRACE_FUNTION(__FUNCTION__); coll = (dgCollision*) convexHullCollision; if (coll->IsType(dgCollision::dgCollisionConvexHull_RTTI)) { return ((dgCollisionConvexHull*) coll)->GetFaceIndices(face, faceIndices); } else { return 0; } } // Name: NewtonConvexCollisionCalculateVolume // calculate the total volume defined by a convex collision geometry. // // Parameters: // *const NewtonCollision* *convexCollision - pointer to the collision. // // Return: collision geometry volume. This function will return zero if the body collision geometry is no convex. // // Remarks: The total volume calculated by the function is only an approximation of the ideal volume. This is not an error, it is a fact resulting from the polygonal representation of convex solids. // // Remarks: This function can be used to assist the application in calibrating features like fluid density weigh factor when calibrating buoyancy forces for more realistic result. // // See also: NewtonBodyAddBuoyancyForce dFloat NewtonConvexCollisionCalculateVolume( const NewtonCollision* const convexCollision) { dgCollision *collision; TRACE_FUNTION(__FUNCTION__); collision = (dgCollision *) convexCollision; return collision->GetVolume(); } // Name: NewtonConvexCollisionCalculateInertialMatrix // Calculate the three principal axis and the the values of the inertia matrix of a convex collision objects. // // Parameters: // *const NewtonCollision* convexCollision - is the pointer to a convex collision primitive. // *dFloat* *inertia - pointer to and array of a least 3 floats to hold the values of the principal inertia. // *dFloat* *origin - pointer to and array of a least 3 floats to hold the values of the center of mass for the principal inertia. // // Remarks: This function calculate a general inertial matrix for arbitrary convex collision including compound collisions. // // See also: NewtonBodySetMassMatrix, NewtonBodyGetMassMatrix, NewtonBodySetCentreOfMass, NewtonBodyGetCentreOfMass void NewtonConvexCollisionCalculateInertialMatrix( const NewtonCollision* convexCollision, dFloat* const inertia, dFloat* const origin) { dgCollision *collision; collision = (dgCollision *) convexCollision; dgVector tmpInertia; dgVector tmpOringin; TRACE_FUNTION(__FUNCTION__); collision->CalculateInertia(tmpInertia, tmpOringin); inertia[0] = tmpInertia[0]; inertia[1] = tmpInertia[1]; inertia[2] = tmpInertia[2]; origin[0] = tmpOringin[0]; origin[1] = tmpOringin[1]; origin[2] = tmpOringin[2]; } // ********************************************************************************************** // // Name: Complex collision primitives interface // // ********************************************************************************************** // Name: NewtonCreateUserMeshCollision // Create a complex collision geometry to be controlled by the application. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *const dFloat* *minBox - pointer to an array of at least three floats to hold minimum value for the box relative to the collision. // *const dFloat* *maxBox - pointer to an array of at least three floats to hold maximum value for the box relative to the collision. // *void* *userData - pointer to user data to be used as context for event callback. // *NewtonUserMeshCollisionCollideCallback* collideCallback - pointer to an event function for providing Newton with the polygon inside a given box region. // *NewtonUserMeshCollisionRayHitCallback* rayHitCallBack - pointer to an event function for providing Newton with ray intersection information. // *NewtonUserMeshCollisionDestroyCallback* destroyCallback - pointer to an event function for destroying any data allocated for use by the application. // *NewtonUserMeshCollisionGetCollisionInfo* getInfoCallback - xxxxx // *NewtonUserMeshCollisionGetFacesInAABB* facesInAABBCallback - xxxxxxxxxx // // Return: Pointer to the user collision. // // Remarks: *UserMeshCollision* provides the application with a method of overloading the built-in collision system for background objects. // UserMeshCollision can be used for implementing collisions with height maps, collisions with BSP, and any other collision structure the application // supports and wishes to preserve. // However, *UserMeshCollision* can not take advantage of the efficient and sophisticated algorithms and data structures of the // built-in *TreeCollision*. We suggest you experiment with both methods and use the method best suited to your situation. // // Remarks: When a *UserMeshCollision* is assigned to a body, the mass of the body is ignored in all dynamics calculations. // This make the body behave as a static body. // // Remarks: Collision primitives are reference counted objects. The application should call *NewtonReleaseCollision* in order to release references to the object. // Neglecting to release references to collision primitives is a common cause of memory leaks. // Collision primitives can be reused with more than one body. This will reduce the amount of memory used be the engine, as well // as speed up some calculations. // // See also: NewtonReleaseCollision NewtonCollision* NewtonCreateUserMeshCollision( const NewtonWorld* const newtonWorld, const dFloat* const minBox, const dFloat* const maxBox, void* const userData, NewtonUserMeshCollisionCollideCallback collideCallback, NewtonUserMeshCollisionRayHitCallback rayHitCallBack, NewtonUserMeshCollisionDestroyCallback destroyCallback, NewtonUserMeshCollisionGetCollisionInfo getInfoCallback, NewtonUserMeshCollisionGetFacesInAABB facesInAABBCallback, int shapeID) { Newton* world; dgCollision* collision; TRACE_FUNTION(__FUNCTION__); dgVector p0(minBox[0], minBox[1], minBox[2], dgFloat32(1.0f)); dgVector p1(maxBox[0], maxBox[1], maxBox[2], dgFloat32(1.0f)); world = (Newton *) newtonWorld; dgUserMeshCreation data; data.m_userData = userData; data.m_collideCallback = (OnUserMeshCollideCallback) collideCallback; data.m_rayHitCallBack = (OnUserMeshRayHitCallback) rayHitCallBack; data.m_destroyCallback = (OnUserMeshDestroyCallback) destroyCallback; data.m_getInfo = (UserMeshCollisionInfo) getInfoCallback; data.m_faceInAabb = (UserMeshFacesInAABB) facesInAABBCallback; collision = world->CreateStaticUserMesh(p0, p1, data); collision->SetUserDataID(dgUnsigned32(shapeID)); return (NewtonCollision*) collision; } // Name: NewtonCreateTreeCollision // Create an empty complex collision geometry tree. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // // Return: Pointer to the collision tree. // // Remarks: *TreeCollision* is the preferred method within Newton for collision with polygonal meshes of arbitrary complexity. // The mesh must be made of flat non-intersecting polygons, but they do not explicitly need to be triangles. // *TreeCollision* can be serialized by the application to/from an arbitrary storage device. // // Remarks: When a *TreeCollision* is assigned to a body the mass of the body is ignored in all dynamics calculations. // This makes the body behave as a static body. // // Remarks: Collision primitives are reference counted objects. The application should call *NewtonReleaseCollision* in order to release references to the object. // Neglecting to release references to collision primitives is a common cause of memory leaks. // Collision primitives can be reused with more than one body. This will reduce the amount of memory used by the engine, as well // as speed up some calculations. // // See also: NewtonTreeCollisionBeginBuild, NewtonTreeCollisionAddFace, NewtonTreeCollisionEndBuild, NewtonStaticCollisionSetDebugCallback, NewtonTreeCollisionGetFaceAtribute, NewtonTreeCollisionSetFaceAtribute, NewtonReleaseCollision NewtonCollision* NewtonCreateTreeCollision(const NewtonWorld* const newtonWorld, int shapeID) { Newton* world; dgCollision* collision; world = (Newton *) newtonWorld; TRACE_FUNTION(__FUNCTION__); collision = world->CreateBVH(); collision->SetUserDataID(dgUnsigned32(shapeID)); return (NewtonCollision*) collision; } // Name: NewtonStaticCollisionSetDebugCallback // set a function call back to be call during the face query of a collision tree. // // Parameters: // *const NewtonCollision* *staticCollision - is the pointer to the static collision (a CollisionTree of a HeightFieldCollision) // *NewtonTreeCollisionCallback *userCallback - pointer to an event function to call before Newton evaluates the polygons colliding with a body. This parameter can be NULL. // // Remarks: because debug display display report all the faces of a collision primitive, it could get slow on very large static collision. // this function can be used for debugging purpose to just report only faces intersetion the collision AABB of the collision shape colliding with the polyginal mesh collision. // // Remarks: this function is not recommended to use for production code only for debug purpose. // // See also: NewtonTreeCollisionGetFaceAtribute, NewtonTreeCollisionSetFaceAtribute void NewtonStaticCollisionSetDebugCallback( const NewtonCollision* const staticCollision, NewtonTreeCollisionCallback userCallback) { /* dgCollision* collision; TRACE_FUNTION(__FUNCTION__); collision = (dgCollision*) staticCollision; if (collision->IsType(dgCollision::dgCollisionPolygonalSoup_RTTI)) { dgCollisionPolygonalSoup* collisionTree; collisionTree = (dgCollisionPolygonalSoup*) collision; if (collisionTree->GetCallBack___() == NewtonCollisionTree::GetIntersectingPolygons) { NewtonCollisionTree& tree = *((NewtonCollisionTree*) collisionTree->GetUserData()); tree.SetCollisionCallback (userCallback); } else if (collisionTree->GetCallBack___() == NewtonHeightFieldCollision::GetIntersectingPolygons) { NewtonHeightFieldCollision& heightField = *((NewtonHeightFieldCollision*) collisionTree->GetUserData()); heightField.SetCollisionCallback (userCallback); } } */ dgCollision* collision; // dgCollisionMesh* collision; TRACE_FUNTION(__FUNCTION__); collision = (dgCollision*) staticCollision; if (collision->IsType(dgCollision::dgCollisionMesh_RTTI)) { dgCollisionMesh* mesh; mesh = (dgCollisionMesh*) staticCollision; mesh->SetCollisionCallback((dgCollisionMeshCollisionCallback) userCallback); } else if (collision->IsType(dgCollision::dgCollisionScene_RTTI)) { dgCollisionScene* scene; scene = (dgCollisionScene*) staticCollision; scene->SetCollisionCallback( (dgCollisionMeshCollisionCallback) userCallback); } } // Name: NewtonTreeCollisionSetUserRayCastCallback // set a function call back to be called during the face query of a collision tree. // // Parameters: // *const NewtonCollision* *treeCollision - is the pointer to the collision tree. // *NewtonCollisionTreeRayCastCallback *userCallback - pointer to an event function to call before Newton evaluates the polygons colliding with a body. This parameter can be NULL. // // Remarks: In general a ray cast on a collision tree will stops at the first interceptions with the closest face in the tree // that was hit by the ray. In some cases the application may be interested in the intesation with faces other than the fiorst hit. // In this cases the application can set this alternate callback and the ray scanner will notify the application of each face hit by the ray scan. // // Remarks: since this function faces the ray scanner to visit all of the potential faces intersected by the ray, // setting the function call back make the ray casting on collision tree less efficient than the default behavior. // So it is this functionality is only recommended for cases were the application is using especial effects like transparencies, or other effects // // Remarks: calling this function with *rayHitCallback* = NULL will rest the collision tree to it default raycast mode, which is return with the closest hit. // // Remarks: when *rayHitCallback* is not null then the callback is dalled with the follwing arguments // *const NetwonCollisio* collision - pointer to the collision tree // *dFloat* interseption - inetstion parameters of the ray // *dFloat* *normal - unnormalized face mormal in the space fo eth parent of the collision. // *int* faceId - id of this face in the collision tree. // // See also: NewtonTreeCollisionGetFaceAtribute, NewtonTreeCollisionSetFaceAtribute void NewtonTreeCollisionSetUserRayCastCallback( const NewtonCollision* const treeCollision, NewtonCollisionTreeRayCastCallback rayHitCallback) { TRACE_FUNTION(__FUNCTION__); dgCollisionBVH* const collision = (dgCollisionBVH*) treeCollision; if (collision->IsType(dgCollision::dgCollisionBVH_RTTI)) { collision->SetCollisionRayCastCallback( (dgCollisionBVHUserRayCastCallback) rayHitCallback); } } void NewtonHeightFieldSetUserRayCastCallback( const NewtonCollision* treeCollision, NewtonHeightFieldRayCastCallback rayHitCallback) { TRACE_FUNTION(__FUNCTION__); dgCollisionHeightField* const collision = (dgCollisionHeightField*) treeCollision; if (collision->IsType(dgCollision::dgCollisionHeightField_RTTI)) { collision->SetCollisionRayCastCallback( (dgCollisionHeightFieldRayCastCallback) rayHitCallback); } } // Name: NewtonTreeCollisionBeginBuild // Prepare a *TreeCollision* to begin to accept the polygons that comprise the collision mesh. // // Parameters: // *const NewtonCollision* *treeCollision - is the pointer to the collision tree. // // Return: Nothing. // // See also: NewtonTreeCollisionAddFace, NewtonTreeCollisionEndBuild void NewtonTreeCollisionBeginBuild(const NewtonCollision* treeCollision) { TRACE_FUNTION(__FUNCTION__); dgCollisionBVH* const collision = (dgCollisionBVH*) treeCollision; _ASSERTE(collision->IsType (dgCollision::dgCollisionBVH_RTTI)); collision->BeginBuild(); } // Name: NewtonTreeCollisionAddFace // Add an individual polygon to a *TreeCollision*. // // Parameters: // *const NewtonCollision* *treeCollision - is the pointer to the collision tree. // *int* vertexCount - number of vertex in *vertexPtr* // *const dFloat* *vertexPtr - pointer to an array of vertex. The vertex should consist of at least 3 floats each. // *int* strideInBytes - size of each vertex in bytes. This value should be 12 or larger. // *int* faceAttribute - id that identifies the polygon. The application can use this value to customize the behavior of the collision geometry. // // Return: Nothing. // // Remarks: After the call to *NewtonTreeCollisionBeginBuild* the *TreeCollision* is ready to accept polygons. The application should iterate // through the application's mesh, adding the mesh polygons to the *TreeCollision* one at a time. // The polygons must be flat and non-self intersecting. // // See also: NewtonTreeCollisionAddFace, NewtonTreeCollisionEndBuild void NewtonTreeCollisionAddFace(const NewtonCollision* const treeCollision, int vertexCount, const dFloat* const vertexPtr, int strideInBytes, int faceAttribute) { TRACE_FUNTION(__FUNCTION__); dgCollisionBVH* const collision = (dgCollisionBVH*) treeCollision; _ASSERTE(collision->IsType (dgCollision::dgCollisionBVH_RTTI)); collision->AddFace(vertexCount, vertexPtr, strideInBytes, faceAttribute); } // Name: NewtonTreeCollisionEndBuild // Finalize the construction of the polygonal mesh. // // Parameters: // *const NewtonCollision* *treeCollision - is the pointer to the collision tree. // *int* optimize - flag that indicates to Newton whether it should optimize this mesh. Set to 1 to optimize the mesh, otherwise 0. // // Return: Nothing. // // // Remarks: After the application has finished adding polygons to the *TreeCollision*, it must call this function to finalize the construction of the collision mesh. // If concave polygons are added to the *TreeCollision*, the application must call this function with the parameter *optimize* set to 1. // With the *optimize* parameter set to 1, Newton will optimize the collision mesh by removing non essential edges from adjacent flat polygons. // Newton will not change the topology of the mesh but significantly reduces the number of polygons in the mesh. The reduction factor of the number of polygons in the mesh depends upon the irregularity of the mesh topology. // A reduction factor of 1.5 to 2.0 is common. // Calling this function with the parameter *optimize* set to zero, will leave the mesh geometry unaltered. // // See also: NewtonTreeCollisionAddFace, NewtonTreeCollisionEndBuild void NewtonTreeCollisionEndBuild(const NewtonCollision* const treeCollision, int optimize) { TRACE_FUNTION(__FUNCTION__); dgCollisionBVH* const collision = (dgCollisionBVH*) treeCollision; _ASSERTE(collision->IsType (dgCollision::dgCollisionBVH_RTTI)); collision->EndBuild(optimize); } // Name: NewtonTreeCollisionGetFaceAtribute // Get the user defined collision attributes stored with each face of the collision mesh. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *const int* *faceIndexArray - pointer to the face index list passed to the function *NewtonTreeCollisionCallback userCallback* // // Return: User id of the face. // // Remarks: This function is used to obtain the user data stored in faces of the collision geometry. // The application can use this user data to achieve per polygon material behavior in large static collision meshes. // // See also: NewtonTreeCollisionSetFaceAtribute, NewtonCreateTreeCollision, NewtonCreateTreeCollisionFromSerialization int NewtonTreeCollisionGetFaceAtribute( const NewtonCollision* const treeCollision, const int* const faceIndexArray) { TRACE_FUNTION(__FUNCTION__); dgCollisionBVH* const collision = (dgCollisionBVH*) treeCollision; _ASSERTE(collision->IsType (dgCollision::dgCollisionBVH_RTTI)); return int(collision->GetTagId(faceIndexArray)); } // Name: NewtonTreeCollisionSetFaceAtribute // Change the user defined collision attribute stored with faces of the collision mesh. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *const int* *faceIndexArray - pointer to the face index list passed to the function *NewtonTreeCollisionCallback userCallback* // *int* attribute - value of the user defined attribute to be stored with the face. // // Return: User id of the face. // // Remarks: This function is used to obtain the user data stored in faces of the collision geometry. // The application can use this user data to achieve per polygon material behavior in large static collision meshes. // By changing the value of this user data the application can achieve modifiable surface behavior with the collision geometry. // For example, in a driving game, the surface of a polygon that represents the street can changed from pavement to oily or wet after // some collision event occurs. // // See also: NewtonTreeCollisionGetFaceAtribute, NewtonCreateTreeCollision, NewtonCreateTreeCollisionFromSerialization void NewtonTreeCollisionSetFaceAtribute( const NewtonCollision* const treeCollision, const int* const faceIndexArray, int attribute) { TRACE_FUNTION(__FUNCTION__); dgCollisionBVH* const collision = (dgCollisionBVH*) treeCollision; _ASSERTE(collision->IsType (dgCollision::dgCollisionBVH_RTTI)); collision->SetTagId(faceIndexArray, dgUnsigned32(attribute)); } // Name: NewtonTreeCollisionGetVertexListIndexListInAABB // collect the vertex list index list mesh intersecting the AABB in collision mesh. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *dFloat* *p0 - pointer to an array of at least three floats representing the ray origin in the local space of the geometry. // *dFloat* *p1 - pointer to an array of at least three floats representing the ray end in the local space of the geometry. // *const dFloat* **vertexArray - pointer to a the vertex array of vertex. // *int* *vertexCount - pointer int to return the number of vertex in vertexArray. // *int* *vertexStrideInBytes - pointer to int to return the size of each vertex in vertexArray. // *const int* *indexList - pointer to array on integers containing the triangles intersection the aabb. // *const int* maxIndexCount - maximum number of indices the function will copy to indexList. // *const int* *faceAttribute - pointer to array on integers top contain the face containing the . // // Return: the number of triangles in indexList. // // Remarks: indexList should be a list 3 * maxIndexCount the number of elements. // // Remarks: faceAttributet should be a list maxIndexCount the number of elements. // // Remarks: this function could be used by the application for many purposes. // for example it can be used to draw the collision geometry intersecting a collision primitive instead // of drawing the entire collision tree in debug mode. // Another use for this function is to to efficient draw projective texture shadows. int NewtonTreeCollisionGetVertexListIndexListInAABB( const NewtonCollision* const treeCollision, const dFloat* const p0, const dFloat* const p1, const dFloat** const vertexArray, int* const vertexCount, int* const vertexStrideInBytes, const int* const indexList, int maxIndexCount, const int* const faceAttribute) { dgInt32 count; dgCollision* meshColl; count = 0; TRACE_FUNTION(__FUNCTION__); meshColl = (dgCollision*) treeCollision; if (meshColl->IsType(dgCollision::dgCollisionMesh_RTTI)) { dgCollisionMesh* collision; collision = (dgCollisionMesh*) meshColl; //NewtonCollisionTree& tree = *((NewtonCollisionTree*) collisionTree->GetUserData()); dgVector pmin(p0[0], p0[1], p0[2], dgFloat32(0.0f)); dgVector pmax(p1[0], p1[1], p1[2], dgFloat32(0.0f)); dgCollisionMesh::dgGetVertexListIndexList data; data.m_indexList = (dgInt32 *) indexList; data.m_userDataList = (dgInt32 *) faceAttribute; data.m_maxIndexCount = maxIndexCount; data.m_triangleCount = 0; collision->GetVertexListIndexList(pmin, pmax, data); count = data.m_triangleCount; *vertexArray = data.m_veterxArray; *vertexCount = data.m_vertexCount; *vertexStrideInBytes = data.m_vertexStrideInBytes; } return count; } // Name: NewtonCreateHeightFieldCollision // Create a height field collision geometry. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *int* width - // *int* height - // *int* cellsDiagonals - // *unsigned short* elevationMap - // *char* atributeMap - // *dFloat* horizontalScale - // *dFloat* verticalScale - // // Return: Pointer to the collision. // // Remarks: // Remarks: // Remarks: // // See also: NewtonCreateTreeCollision, NewtonReleaseCollision NewtonCollision* NewtonCreateHeightFieldCollision( const NewtonWorld* const newtonWorld, int width, int height, int cellsDiagonals, const unsigned short* const elevationMap, const char* const atributeMap, dFloat horizontalScale, dFloat verticalScale, int shapeID) { Newton* world; dgCollision* collision; world = (Newton *) newtonWorld; TRACE_FUNTION(__FUNCTION__); collision = world->CreateBVHFieldCollision(width, height, cellsDiagonals, elevationMap, atributeMap, horizontalScale, verticalScale); collision->SetUserDataID(dgUnsigned32(shapeID)); return (NewtonCollision*) collision; } // Name: NewtonCreateSceneCollision // Create a height field collision geometry. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // // Return: Pointer to the collision. // // Remarks: // Remarks: // Remarks: // // See also: NewtonCreateTreeCollision, NewtonReleaseCollision NewtonCollision* NewtonCreateSceneCollision( const NewtonWorld* const newtonWorld, int shapeID) { Newton* world; dgCollision* collision; TRACE_FUNTION(__FUNCTION__); world = (Newton *) newtonWorld; collision = world->CreateScene(); collision->SetUserDataID(dgUnsigned32(shapeID)); return (NewtonCollision*) collision; } NewtonSceneProxy* NewtonSceneCollisionCreateProxy(NewtonCollision* const scene, NewtonCollision* const collision, const dFloat* const matrixPtr) { dgMatrix matrix(*((dgMatrix*) matrixPtr)); matrix.m_front.m_w = dgFloat32(0.0f); matrix.m_up.m_w = dgFloat32(0.0f); matrix.m_right.m_w = dgFloat32(0.0f); matrix.m_posit.m_w = dgFloat32(1.0f); dgCollisionScene* const newtonScene = (dgCollisionScene*) scene; _ASSERTE(newtonScene->IsType(dgCollision::dgCollisionScene_RTTI)); return (NewtonSceneProxy*) newtonScene->AddProxy((dgCollision*) collision, matrix); } void NewtonSceneCollisionDestroyProxy(NewtonCollision* const scene, NewtonSceneProxy* const proxy) { dgCollisionScene* const newtonScene = (dgCollisionScene*) scene; _ASSERTE(newtonScene->IsType(dgCollision::dgCollisionScene_RTTI)); newtonScene->RemoveProxy(proxy); } void NewtonSceneProxySetMatrix(NewtonSceneProxy* const proxy, const dFloat* const matrix) { dgList<dgCollisionScene::dgProxy*>::dgListNode* const node = (dgList< dgCollisionScene::dgProxy*>::dgListNode*) proxy; dgCollisionScene* const newtonScene = node->GetInfo()->m_owner; dgMatrix& offset = *((dgMatrix*) matrix); newtonScene->SetProxyMatrix(node, offset); } void NewtonSceneProxyGetMatrix(NewtonSceneProxy* const proxy, dFloat* const matrix) { dgList<dgCollisionScene::dgProxy*>::dgListNode* const node = (dgList< dgCollisionScene::dgProxy*>::dgListNode*) proxy; dgCollisionScene* const newtonScene = node->GetInfo()->m_owner; dgMatrix& offset = *((dgMatrix*) matrix); offset = newtonScene->GetProxyMatrix(node); } void NewtonSceneSetProxyUserData(NewtonSceneProxy* const proxy, void* userData) { dgList<dgCollisionScene::dgProxy*>::dgListNode* const node = (dgList< dgCollisionScene::dgProxy*>::dgListNode*) proxy; dgCollisionScene* const newtonScene = node->GetInfo()->m_owner; newtonScene->SetProxyUserData(node, userData); } void* NewtonSceneGetProxyUserData(NewtonSceneProxy* const proxy) { dgList<dgCollisionScene::dgProxy*>::dgListNode* const node = (dgList< dgCollisionScene::dgProxy*>::dgListNode*) proxy; dgCollisionScene* const newtonScene = node->GetInfo()->m_owner; return newtonScene->GetProxyUserData(node); } NewtonSceneProxy* NewtonSceneGetFirstProxy(NewtonCollision* const scene) { dgCollisionScene* const newtonScene = (dgCollisionScene*) scene; return (NewtonSceneProxy*) newtonScene->GetFirstProxy(); } NewtonSceneProxy* NewtonSceneGetNextProxy(NewtonCollision* const scene, NewtonSceneProxy* const proxy) { dgList<dgCollisionScene::dgProxy*>::dgListNode* const node = (dgList< dgCollisionScene::dgProxy*>::dgListNode*) proxy; dgCollisionScene* const newtonScene = node->GetInfo()->m_owner; return (NewtonSceneProxy*) newtonScene->GetNextProxy(proxy); } void NewtonSceneCollisionOptimize(NewtonCollision* const scene) { dgCollisionScene* const newtonScene = (dgCollisionScene*) scene; _ASSERTE(newtonScene->IsType(dgCollision::dgCollisionScene_RTTI)); newtonScene->ImproveTotalFitness(); } // ********************************************************************************************** // // Name: Generic collision library functions // // ********************************************************************************************** // Name: NewtonCollisionPointDistance // Calculate the closest point between a point and convex collision primitive. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *dFloat* *point - pointer to and array of a least 3 floats representing the origin. // *const NewtonCollision* *collision - pointer to collision primitive. // *const dFloat* *matrix - pointer to an array of 16 floats containing the offset matrix of collision primitiveA. // *dFloat* *contact - pointer to and array of a least 3 floats to contain the closest point to collisioA. // *dFloat* *normal - pointer to and array of a least 3 floats to contain the separating vector normal. // *int* threadIndex -Thread index form where the call is made from, zeor otherwize // // Return: one if the two bodies are disjoint and the closest point could be found, // zero if the point is inside the convex primitive. // // Remarks: This function can be used as a low-level building block for a stand-alone collision system. // Applications that have already there own physics system, and only want and quick and fast collision solution, // can use Newton advanced collision engine as the low level collision detection part. // To do this the application only needs to initialize Newton, create the collision primitives at application discretion, // and just call this function when the objects are in close proximity. Applications using Newton as a collision system // only, are responsible for implementing their own broad phase collision determination, based on any high level tree structure. // Also the application should implement their own trivial aabb test, before calling this function . // // Remarks: the current implementation of this function do work on collision trees, or user define collision. // // See also: NewtonCollisionCollideContinue, NewtonCollisionClosestPoint, NewtonCollisionCollide, NewtonCollisionRayCast, NewtonCollisionCalculateAABB int NewtonCollisionPointDistance(const NewtonWorld* const newtonWorld, const dFloat* const point, const NewtonCollision* const collision, const dFloat* const matrix, dFloat* const contact, dFloat* const normal, int threadIndex) { Newton* world; world = (Newton *) newtonWorld; TRACE_FUNTION(__FUNCTION__); return world->ClosestPoint(*((dgTriplex*) point), (dgCollision*) collision, *((dgMatrix*) matrix), *((dgTriplex*) contact), *((dgTriplex*) normal), threadIndex); } // Name: NewtonCollisionClosestPoint // Calculate the closest points between two disjoint convex collision primitive. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *const NewtonCollision* *collisionA - pointer to collision primitive A. // *const dFloat* *matrixA - pointer to an array of 16 floats containing the offset matrix of collision primitiveA. // *const NewtonCollision* *collisionB - pointer to collision primitive B. // *const dFloat* *matrixB - pointer to an array of 16 floats containing the offset matrix of collision primitiveB. // *dFloat* *contactA - pointer to and array of a least 3 floats to contain the closest point to collisionA. // *dFloat* *contactB - pointer to and array of a least 3 floats to contain the closest point to collisionB. // *dFloat* *normalAB - pointer to and array of a least 3 floats to contain the separating vector normal. // *int* threadIndex -Thread index form where the call is made from, zeor otherwize // // Return: one if the tow bodies are disjoint and he closest point could be found, // zero if the two collision primitives are intersecting. // // Remarks: This function can be used as a low-level building block for a stand-alone collision system. // Applications that have already there own physics system, and only want and quick and fast collision solution, // can use Newton advanced collision engine as the low level collision detection part. // To do this the application only needs to initialize Newton, create the collision primitives at application discretion, // and just call this function when the objects are in close proximity. Applications using Newton as a collision system // only, are responsible for implementing their own broad phase collision determination, based on any high level tree structure. // Also the application should implement their own trivial aabb test, before calling this function . // // Remarks: the current implementation of this function does not work on collision trees, or user define collision. // // See also: NewtonCollisionCollideContinue, NewtonCollisionPointDistance, NewtonCollisionCollide, NewtonCollisionRayCast, NewtonCollisionCalculateAABB int NewtonCollisionClosestPoint(const NewtonWorld* const newtonWorld, const NewtonCollision* const collisionA, const dFloat* const matrixA, const NewtonCollision* const collisionB, const dFloat* const matrixB, dFloat* const contactA, dFloat* const contactB, dFloat* const normalAB, int threadIndex) { Newton* world; world = (Newton *) newtonWorld; TRACE_FUNTION(__FUNCTION__); return world->ClosestPoint((dgCollision*) collisionA, *((dgMatrix*) matrixA), (dgCollision*) collisionB, *((dgMatrix*) matrixB), *((dgTriplex*) contactA), *((dgTriplex*) contactB), *((dgTriplex*) normalAB), threadIndex); } // Name: NewtonCollisionCollide // Calculate contact points between two collision primitive. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *int* maxSize - size of maximum number of elements in contacts, normals, and penetration. // *const NewtonCollision* *collisionA - pointer to collision primitive A. // *const dFloat* *matrixA - pointer to an array of 16 floats containing the offset matrix of collision primitiveA. // *const NewtonCollision* *collisionB - pointer to collision primitive B. // *const dFloat* *matrixB - pointer to an array of 16 floats containing the offset matrix of collision primitiveB. // *dFloat* *contacts - pointer to and array of a least 3 times maxSize floats to contain the collision contact points. // *dFloat* *normals - pointer to and array of a least 3 times maxSize floats to contain the collision contact normals. // *dFloat* *penetration - pointer to and array of a least maxSize floats to contain the collision penetration at each contact. // *int* threadIndex -Thread index form where the call is made from, zeor otherwize // // Return: the number of contact points. // // Remarks: This function can be used as a low-level building block for a stand-alone collision system. // Applications that have already there own physics system, and only want and quick and fast collision solution, // can use Newton advanced collision engine as the low level collision detection part. // To do this the application only needs to initialize Newton, create the collision primitives at application discretion, // and just call this function when the objects are in close proximity. Applications using Newton as a collision system // only, are responsible for implementing their own broad phase collision determination, based on any high level tree structure. // Also the application should implement their own trivial aabb test, before calling this function . // // See also: NewtonCollisionCollideContinue, NewtonCollisionClosestPoint, NewtonCollisionPointDistance, NewtonCollisionRayCast, NewtonCollisionCalculateAABB int NewtonCollisionCollide(const NewtonWorld* const newtonWorld, int maxSize, const NewtonCollision* const collisionA, const dFloat* const matrixA, const NewtonCollision* const collisionB, const dFloat* const matrixB, dFloat* const contacts, dFloat* const normals, dFloat* const penetration, int threadIndex) { Newton* world; world = (Newton *) newtonWorld; TRACE_FUNTION(__FUNCTION__); return world->Collide((dgCollision*) collisionA, *((dgMatrix*) matrixA), (dgCollision*) collisionB, *((dgMatrix*) matrixB), (dgTriplex*) contacts, (dgTriplex*) normals, penetration, maxSize, threadIndex); } // Name: NewtonCollisionCollideContinue // Calculate time of impact of impact and contact points between two collision primitive. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *int* maxSize - size of maximum number of elements in contacts, normals, and penetration. // *const dFloat* timestep - maximum time interval considered for the continue collision calculation. // *const NewtonCollision* *collisionA - pointer to collision primitive A. // *const dFloat* *matrixA - pointer to an array of 16 floats containing the offset matrix of collision primitiveA. // *const dFloat* *velocA - pointer to and array of a least 3 times maxSize floats containing the linear velocity of collision primitiveA. // *const dFloat* *omegaA - pointer to and array of a least 3 times maxSize floats containing the angular velocity of collision primitiveA. // *const NewtonCollision* *collisionB - pointer to collision primitive B. // *const dFloat* *matrixB - pointer to an array of 16 floats containing the offset matrix of collision primitiveB. // *const dFloat* *velocB - pointer to and array of a least 3 times maxSize floats containing the linear velocity of collision primitiveB. // *const dFloat* *omegaB - pointer to and array of a least 3 times maxSize floats containing the angular velocity of collision primitiveB. // *dFloat* *timeOfImpact - pointer to least 1 float variable to contain the time of the intersection. // *dFloat* *contacts - pointer to and array of a least 3 times maxSize floats to contain the collision contact points. // *dFloat* *normals - pointer to and array of a least 3 times maxSize floats to contain the collision contact normals. // *dFloat* *penetration - pointer to and array of a least maxSize floats to contain the collision penetration at each contact. // *int* threadIndex -Thread index form where the call is made from, zeor otherwize // // Return: the number of contact points. // // Remarks: by passing zero as *maxSize* not contact will be calculated and the function will just determine the time of impact is any. // // Remarks: if the body are inter penetrating the time of impact will be zero. // // Remarks: if the bodies do not collide time of impact will be set to *timestep* // // Remarks: This function can be used as a low-level building block for a stand-alone collision system. // Applications that have already there own physics system, and only want and quick and fast collision solution, // can use Newton advanced collision engine as the low level collision detection part. // To do this the application only needs to initialize Newton, create the collision primitives at application discretion, // and just call this function when the objects are in close proximity. Applications using Newton as a collision system // only, are responsible for implementing their own broad phase collision determination, based on any high level tree structure. // Also the application should implement their own trivial aabb test, before calling this function . // // See also: NewtonCollisionCollide, NewtonCollisionClosestPoint, NewtonCollisionPointDistance, NewtonCollisionRayCast, NewtonCollisionCalculateAABB int NewtonCollisionCollideContinue(const NewtonWorld* const newtonWorld, int maxSize, const dFloat timestep, const NewtonCollision* const collisionA, const dFloat* const matrixA, const dFloat* const velocA, const dFloat* const omegaA, const NewtonCollision* const collisionB, const dFloat* const matrixB, const dFloat* const velocB, const dFloat* const omegaB, dFloat* const timeOfImpact, dFloat* const contacts, dFloat* const normals, dFloat* const penetration, int threadIndex) { Newton* const world = (Newton *) newtonWorld; *timeOfImpact = timestep; TRACE_FUNTION(__FUNCTION__); return world->CollideContinue((dgCollision*) collisionA, *((dgMatrix*) matrixA), *((dgVector*) velocA), *((dgVector*) omegaA), (dgCollision*) collisionB, *((dgMatrix*) matrixB), *((dgVector*) velocB), *((dgVector*) omegaB), *timeOfImpact, (dgTriplex*) contacts, (dgTriplex*) normals, penetration, maxSize, threadIndex); } // Name: NewtonCollisionSupportVertex // Calculate the most extreme point of a convex collision shape along the given direction. // // Parameters: // *const NewtonCollision* *collisionPtr - pointer to the collision object. // *const dFloat* *dir - pointer to an array of at least three floats representing the search direction. // *dFloat* *vertex - pointer to an array of at least three floats to hold the collision most extreme vertex along the search direction. // // Return: nothing. // // Remarks: the search direction must be in the space of the collision shape. // // See also: NewtonCollisionRayCast, NewtonCollisionClosestPoint, NewtonCollisionPointDistance void NewtonCollisionSupportVertex(const NewtonCollision* collisionPtr, const dFloat* const dir, dFloat* const vertex) { dgCollisionConvex* collision; TRACE_FUNTION(__FUNCTION__); collision = (dgCollisionConvex*) collisionPtr; // _ASSERTE (collision->IsType (dgCollision::dgConvexCollision_RTTI)); const dgMatrix& matrix = collision->GetOffsetMatrix(); dgVector searchDir( matrix.UnrotateVector(dgVector(dir[0], dir[1], dir[2], dgFloat32(0.0f)))); searchDir = searchDir.Scale(dgRsqrt (searchDir % searchDir)); dgVector vertexOut( matrix.TransformVector(collision->SupportVertex(searchDir))); vertex[0] = vertexOut[0]; vertex[1] = vertexOut[1]; vertex[2] = vertexOut[2]; } // Name: NewtonCollisionRayCast // Ray cast specific collision object. // // Parameters: // *const NewtonCollision* *collisionPtr - pointer to the collision object. // *const dFloat* *p0 - pointer to an array of at least three floats representing the ray origin in the local space of the geometry. // *const dFloat* *p1 - pointer to an array of at least three floats representing the ray end in the local space of the geometry. // *dFloat* *normal - pointer to an array of at least three floats to hold the normal at the intersection point. // *int* *attribute - pointer to an array of at least one floats to hold the ID of the face hit by the ray. // // Return: the parametric value of the intersection, between 0.0 and 1.0, an value larger than 1.0 if the ray miss. // // Remarks: This function is intended for applications using newton collision system separate from the dynamics system, also for applications // implementing any king of special purpose logic like sensing distance to another object. // // Remarks: the ray most be local to the collisions geometry, for example and application ray casting the collision geometry of // of a rigid body, must first take the points p0, and p1 to the local space of the rigid body by multiplying the points by the // inverse of he rigid body transformation matrix. // // See also: NewtonCollisionClosestPoint, NewtonCollisionSupportVertex, NewtonCollisionPointDistance, NewtonCollisionCollide, NewtonCollisionCalculateAABB dFloat NewtonCollisionRayCast(const NewtonCollision* collisionPtr, const dFloat* const p0, const dFloat* const p1, dFloat* const normal, int* const attribute) { dFloat t; dgCollision* collision; collision = (dgCollision*) collisionPtr; TRACE_FUNTION(__FUNCTION__); const dgMatrix& matrix = collision->GetOffsetMatrix(); dgVector q0( matrix.UntransformVector(dgVector(p0[0], p0[1], p0[2], dgFloat32(0.0f)))); dgVector q1( matrix.UntransformVector(dgVector(p1[0], p1[1], p1[2], dgFloat32(0.0f)))); dgContactPoint contact; t = collision->RayCast(q0, q1, contact, NULL, NULL, NULL); if (t >= dFloat(0.0f) && t <= dFloat(dgFloat32(1.0f))) { attribute[0] = (int) contact.m_userId; dgVector n(matrix.RotateVector(contact.m_normal)); normal[0] = n[0]; normal[1] = n[1]; normal[2] = n[2]; } return t; } // Name: NewtonCollisionCalculateAABB // Calculate an axis-aligned bounding box for this collision, the box is calculated relative to *offsetMatrix*. // // Parameters: // *const NewtonCollision* *collisionPtr - pointer to the collision object. // *const dFloat* *offsetMatrix - pointer to an array of 16 floats containing the offset matrix used as the coordinate system and center of the AABB. // *dFloat* *p0 - pointer to an array of at least three floats to hold minimum value for the AABB. // *dFloat* *p1 - pointer to an array of at least three floats to hold maximum value for the AABB. // // Return: Nothing. // // See also: NewtonCollisionClosestPoint, NewtonCollisionPointDistance, NewtonCollisionCollide, NewtonCollisionRayCast void NewtonCollisionCalculateAABB(const NewtonCollision* collisionPtr, const dFloat* const offsetMatrix, dFloat* const p0, dFloat* const p1) { dgCollision* collision; collision = (dgCollision*) collisionPtr; //const dgMatrix& matrix = *((dgMatrix*) offsetMatrix); dgMatrix matrix(collision->GetOffsetMatrix() * (*((dgMatrix*) offsetMatrix))); dgVector q0; dgVector q1; TRACE_FUNTION(__FUNCTION__); collision->CalcAABB(matrix, q0, q1); p0[0] = q0.m_x; p0[1] = q0.m_y; p0[2] = q0.m_z; p1[0] = q1.m_x; p1[1] = q1.m_y; p1[2] = q1.m_z; } // Name: NewtonCollisionForEachPolygonDo // Iterate thought polygon of the collision geometry of a body calling the function callback. // // Parameters: // *const NewtonBody* *collisionPtr - is the pointer to the collision objects. // *const dFloat32* *matrix - is the pointer to the collision objects. // *NewtonCollisionIterator* callback - application define callback // *void* *userDataPtr - pointer to the user defined user data value. // // Return: nothing // // Remarks: This function used to be a member of the rigid body, but to making it a member of the collision object provides better // low lever display capabilities. The application can still call this function to show the collision of a rigid body by // getting the collision and the transformation matrix from the rigid, and then calling this functions. // // Remarks: This function can be called by the application in order to show the collision geometry. The application should provide a pointer to the function *NewtonCollisionIterator*, // Newton will convert the collision geometry into a polygonal mesh, and will call *callback* for every polygon of the mesh // // Remarks: this function affect severely the performance of Newton. The application should call this function only for debugging purpose // // Remarks: This function will ignore user define collision mesh // See also: NewtonWorldGetFirstBody, NewtonWorldForEachBodyInAABBDo void NewtonCollisionForEachPolygonDo(const NewtonCollision* collisionPtr, const dFloat* const matrixPtr, NewtonCollisionIterator callback, void* const userDataPtr) { TRACE_FUNTION(__FUNCTION__); dgCollision* const collision = (dgCollision *) (collisionPtr); dgMatrix matrix = *((dgMatrix*) matrixPtr); collision->DebugCollision(matrix, (OnDebugCollisionMeshCallback) callback, userDataPtr); } // Name: NewtonCollisionMakeUnique // Convert a collision primitive to a unique instance by removing it for the collision cache. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *const NewtonCollision* *collisionPtr - pointer to the collision object // // Return: Nothing. // // Remarks: // This function will not make preexisting collision object unique instances, so for best result this function should be call immediately after the // creation of the collision object. // // Remarks: // Collision objects are reference counted objects. The application should call *NewtonReleaseCollision* in order to release references to the object. // Neglecting to release references to collision primitives is a common cause of memory leaks. void NewtonCollisionMakeUnique(const NewtonWorld* const newtonWorld, const NewtonCollision* const collisionPtr) { TRACE_FUNTION(__FUNCTION__); Newton* const world = (Newton *) newtonWorld; dgCollision* const collision = (dgCollision*) collisionPtr; world->RemoveFromCache(collision); } // Name: NewtonAddCollisionReference // Increase the reference count of this collision object. // // Parameters: // *const NewtonCollision* *collisionPtr - pointer to the collision object // // Return: the new refCount. // // Remarks: to get the correct reference count of a collision primitive the application can call fution *NewtonCollisionGetInfo* // // Remarks: // Collision objects are reference counted objects. The application should call *NewtonReleaseCollision* in order to release references to the object. // Neglecting to release references to collision primitives is a common cause of memory leaks. // // See also: NewtonReleaseCollision , NewtonCollisionGetInfo, NewtonCollisionSerialize int NewtonAddCollisionReference(const NewtonCollision* collisionPtr) { TRACE_FUNTION(__FUNCTION__); dgCollision* const collision = (dgCollision*) collisionPtr; collision->AddRef(); return collision->GetRefCount(); } // Name: NewtonReleaseCollision // Release a reference from this collision object returning control to Newton. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *const NewtonCollision* *collisionPtr - pointer to the collision object // // Return: Nothing. // // Remarks: to get the correct reference count of a collision primitive the application can call function *NewtonCollisionGetInfo* // // Remarks: // Collision objects are reference counted objects. The application should call *NewtonReleaseCollision* in order to release references to the object. // Neglecting to release references to collision primitives is a common cause of memory leaks. // // See also: NewtonAddCollisionReference, NewtonCollisionGetInfo, NewtonCollisionSerialize void NewtonReleaseCollision(const NewtonWorld* const newtonWorld, const NewtonCollision* const collisionPtr) { TRACE_FUNTION(__FUNCTION__); Newton* const world = (Newton *) newtonWorld; dgCollision* const collision = (dgCollision*) collisionPtr; world->ReleaseCollision(collision); } // Name: NewtonCollisionSerialize // Serialize a * general collision shape. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *const NewtonCollision* *collision - is the pointer to the collision tree shape. // *NewtonSerialize* serializeFunction - pointer to the event function that will do the serialization. // *void* *serializeHandle - user data that will be passed to the *NewtonSerialize* callback. // // Return: Nothing. // // Remarks: Small and medium collision shapes like *TreeCollision* (under 50000 polygons) small convex hulls or compude collision can be constructed at application // startup without significant processing overhead. // // // See also: NewtonCollisionGetInfo void NewtonCollisionSerialize(const NewtonWorld* const newtonWorld, const NewtonCollision* const collision, NewtonSerialize serializeFunction, void* const serializeHandle) { TRACE_FUNTION(__FUNCTION__); Newton* const world = (Newton *) newtonWorld; world->Serialize((dgCollision*) collision, (dgSerialize) serializeFunction, serializeHandle); } // Name: NewtonCreateCollisionFromSerialization // Create a collision shape via a serialization function. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *NewtonTreeCollisionCallback *userCallback - pointer to an event function to call before Newton is begins collecting polygons that are colliding with a body. This parameter can be NULL. // *NewtonSerialize* callback - pointer to the callback function that will handle the serialization. // *void* *userData - user data that will be passed as the argument to *NewtonSerialize* callback. // // Return: Nothing. // // Remarks: this function is useful to to load collision primitive for and archive file. In the case of complex shapes like convex hull and compound collision the // it save a significant amount of construction time. // // Remarks: if this function is called to load a serialized tree collision, the tree collision will be loaded, but the function pointer callback will be set to NULL. // for this operation see function *NewtonCreateTreeCollisionFromSerialization* // // See also: NewtonAddCollisionReference, NewtonReleaseCollision, NewtonCollisionSerialize, NewtonCollisionGetInfo NewtonCollision* NewtonCreateCollisionFromSerialization( const NewtonWorld* const newtonWorld, NewtonDeserialize deserializeFunction, void* const serializeHandle) { TRACE_FUNTION(__FUNCTION__); Newton* const world = (Newton *) newtonWorld; return (NewtonCollision*) world->CreateFromSerialization( (dgDeserialize) deserializeFunction, serializeHandle); } /* // Name: NewtonCreateTreeCollisionFromSerialization // Create a tree collision and load the polygon mesh via a serialization function. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *NewtonTreeCollisionCallback *userCallback - pointer to an event function to call before Newton is begins collecting polygons that are colliding with a body. This parameter can be NULL. // *NewtonSerialize* callback - pointer to the callback function that will handle the serialization. // *void* *userData - user data that will be passed as the argument to *NewtonSerialize* callback. // // Return: Nothing. // // Remarks: if this function is call on a non tree collision, the results are unpredictable. // // Remarks: Small and medium size *TreeCollision* objects (under 50000 polygons) can be constructed at application startup without significant processing overhead. // However, for very large polygons sets (over 50000 polygons) it is recommended that the application use *NewtonCreateTreeCollision* // in an off-line tool. Then the application can call this function to store the *TreeCollision* to a file or // any file packer system the application is using. At run time the application can use the function *NewtonCreateTreeCollisionFromSerialization* // to create and load a pre-made *TreeCollision* // // See also: NewtonAddCollisionReference, NewtonReleaseCollision, NewtonCollisionSerialize, NewtonCollisionGetInfo NewtonCollision* NewtonCreateTreeCollisionFromSerialization(const NewtonWorld* const newtonWorld, NewtonTreeCollisionCallback userCallback, NewtonDeserialize deserializeFunction, void* const serializeHandle) { Newton* world; dgCollision* collision; NewtonCollisionTree *dataBase; world = (Newton *)newtonWorld; dataBase = new NewtonCollisionTree (world, userCallback); dataBase->Deserialize (deserializeFunction, serializeHandle); dgVector p0; dgVector p1; dataBase->GetAABB (p0, p1); world = (Newton *)newtonWorld; collision = world->CreatePolygonSoup (dataBase, NewtonCollisionTree::GetIntersectingPolygons, NewtonCollisionTree::RayHit, NewtonCollisionTree::Destroy, NULL, NULL); collision->SetCollisionBBox(p0, p1); return (NewtonCollision*)collision; } */ // Name: NewtonCollisionGetInfo // Get creation parameters for this collision objects. // // Parameters: // *const NewtonCollision* collision - is the pointer to a convex collision primitive. // *NewtonCollisionInfoRecord* *collisionInfo - pointer to a collision information record. // // Remarks: This function can be used by the application for writing file format and for serialization. // // See also: NewtonCollisionGetInfo, NewtonCollisionSerialize void NewtonCollisionGetInfo(const NewtonCollision* const collision, NewtonCollisionInfoRecord* const collisionInfo) { dgCollision *coll; coll = (dgCollision *) collision; TRACE_FUNTION(__FUNCTION__); _ASSERTE(sizeof (dgCollisionInfo) <= sizeof (NewtonCollisionInfoRecord)); coll->GetCollisionInfo((dgCollisionInfo*) collisionInfo); } // ********************************************************************************************** // // Name: Transform utility functions // // ********************************************************************************************** // Name: NewtonGetEulerAngle // Get the three Euler angles from a 4x4 rotation matrix arranged in row-major order. // // Parameters: // *const dFloat* matrix - pointer to the 4x4 rotation matrix. // *dFloat* angles - pointer to an array of at least three floats to hold the Euler angles. // // Return: Nothing. // // Remarks: The motivation for this function is that many graphics engines still use Euler angles to represent the orientation // of graphics entities. // The angles are expressed in radians and represent: // *angle[0]* - rotation about first matrix row // *angle[1]* - rotation about second matrix row // *angle[2]* - rotation about third matrix row // // See also: NewtonSetEulerAngle void NewtonGetEulerAngle(const dFloat* const matrix, dFloat* const angles) { const dgMatrix& mat = *((dgMatrix*) matrix); TRACE_FUNTION(__FUNCTION__); dgVector eulers(mat.CalcPitchYawRoll()); angles[0] = eulers.m_x; angles[1] = eulers.m_y; angles[2] = eulers.m_z; } // Name: NewtonSetEulerAngle // Build a rotation matrix from the Euler angles in radians. // // Parameters: // *dFloat* matrix - pointer to the 4x4 rotation matrix. // *const dFloat* angles - pointer to an array of at least three floats to hold the Euler angles. // // Return: Nothing. // // Remarks: The motivation for this function is that many graphics engines still use Euler angles to represent the orientation // of graphics entities. // The angles are expressed in radians and represent: // *angle[0]* - rotation about first matrix row // *angle[1]* - rotation about second matrix row // *angle[2]* - rotation about third matrix row // // See also: NewtonGetEulerAngle void NewtonSetEulerAngle(const dFloat* const angles, dFloat* const matrix) { dgInt32 i; dgInt32 j; TRACE_FUNTION(__FUNCTION__); dgMatrix mat( dgPitchMatrix(angles[0]) * dgYawMatrix(angles[1]) * dgRollMatrix(angles[2])); dgMatrix& retMatrix = *((dgMatrix*) matrix); retMatrix[3][3] = dgFloat32(1.0f); for (i = 0; i < 3; i++) { retMatrix[3][i] = 0.0f; for (j = 0; j < 4; j++) { retMatrix[i][j] = mat[i][j]; } } } // Name: NewtonCalculateSpringDamperAcceleration // Calculates the acceleration to satisfy the specified the spring damper system. // // Parameters: // *dFloat* dt - integration time step. // *dFloat* ks - spring stiffness, it must be a positive value. // *dFloat* x - spring position. // *dFloat* kd - desired spring damper, it must be a positive value. // *dFloat* s - spring velocity. // // return: the spring acceleration. // // Remark: the acceleration calculated by this function represent the mass, spring system of the form // a = -ks * x - kd * v. dFloat NewtonCalculateSpringDamperAcceleration(dFloat dt, dFloat ks, dFloat x, dFloat kd, dFloat s) { dFloat accel; // accel = - (ks * x + kd * s); TRACE_FUNTION(__FUNCTION__); //at = [- ks (x2 - x1) - kd * (v2 - v1) - dt * ks * (v2 - v1)] / [1 + dt * kd + dt * dt * ks] dgFloat32 ksd = dt * ks; dgFloat32 num = ks * x + kd * s + ksd * s; dgFloat32 den = dgFloat32(1.0f) + dt * kd + dt * ksd; _ASSERTE(den > 0.0f); accel = -num / den; // dgCheckFloat (accel); return accel; } // ********************************************************************************************** // // Name: Rigid body interface // // ********************************************************************************************** // Name: NewtonCreateBody // Create a rigid body. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *const NewtonCollision* *collisionPtr - pointer to the collision object. // // Return: Pointer to the rigid body. // // Remarks: This function creates a Newton rigid body and assigns a *collisionPtr* as the collision geometry representing the rigid body. // This function increments the reference count of the collision geometry. // All event functions are set to NULL and the material gruopID of the body is set to the default GroupID. // // See also: NewtonDestroyBody NewtonBody* NewtonCreateBody(const NewtonWorld* const newtonWorld, const NewtonCollision* const collisionPtr, const dFloat* const matrixPtr) { TRACE_FUNTION(__FUNCTION__); Newton* const world = (Newton *) newtonWorld; dgCollision* const collision = (dgCollision*) collisionPtr; #ifdef SAVE_COLLISION SaveCollision (collisionPtr); #endif dgMatrix matrix(*((dgMatrix*) matrixPtr)); #ifdef _DEBUG // matrix.m_front = matrix.m_front.Scale (dgRsqrt (matrix.m_front % matrix.m_front)); // matrix.m_right = matrix.m_front * matrix.m_up; // matrix.m_right = matrix.m_right.Scale (dgRsqrt (matrix.m_right % matrix.m_right)); // matrix.m_up = matrix.m_right * matrix.m_front; #endif matrix.m_front.m_w = dgFloat32(0.0f); matrix.m_up.m_w = dgFloat32(0.0f); matrix.m_right.m_w = dgFloat32(0.0f); matrix.m_posit.m_w = dgFloat32(1.0f); return (NewtonBody*) world->CreateBody(collision, matrix); } // Name: NewtonDestroyBody // Destroy a rigid body. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *const NewtonBody* *bodyPtr - pointer to the body to be destroyed. // // Return: Nothing. // // Remarks: If this function is called from inside a simulation step the destruction of the body will be delayed until end of the time step. // This function will decrease the reference count of the collision geometry by one. If the reference count reaches zero, then the collision // geometry will be destroyed. This function will destroy all joints associated with this body. // // See also: NewtonCreateBody void NewtonDestroyBody(const NewtonWorld* const newtonWorld, const NewtonBody* const bodyPtr) { dgBody *body; Newton* world; TRACE_FUNTION(__FUNCTION__); body = (dgBody *) bodyPtr; world = (Newton *) newtonWorld; world->DestroyBody(body); } // Name: NewtonBodySetUserData // Store a user defined data value with the body. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // *void* *userDataPtr - pointer to the user defined user data value. // // Return: Nothing. // // Remarks: The application can store a user defined value with the Body. This value can be the pointer to a structure containing some application data for special effect. // if the application allocate some resource to store the user data, the application can register a joint destructor to get rid of the allocated resource when the body is destroyed // // See also: NewtonBodyGetUserData, NewtonBodySetDestructorCallback void NewtonBodySetUserData(const NewtonBody* const bodyPtr, void* const userDataPtr) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); body->SetUserData(userDataPtr); } // Name: NewtonBodyGetUserData // Retrieve a user defined data value stored with the body. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // // Return: The user defined data. // // Remarks: The application can store a user defined value with a rigid body. This value can be the pointer // to a structure which is the graphical representation of the rigid body. // // See also: NewtonBodySetUserData void* NewtonBodyGetUserData(const NewtonBody* const bodyPtr) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); return body->GetUserData(); } // Name: NewtonBodyGetWorld // Retrieve get the pointer to the world from the body. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // // Return: the world that own this body. // // Remarks: The application can use this function to determine what world own this body. If the application // have to get the world from a joint, it can do so by getting one of the bodies attached to the joint and getting the world from // that body. // NewtonWorld* NewtonBodyGetWorld(const NewtonBody* const bodyPtr) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); return (NewtonWorld*) body->GetWorld(); } // Name: NewtonBodySetTransformCallback // Assign a transformation event function to the body. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // *NewtonSetTransform callback - pointer to a function callback in used to update the transformation matrix of the visual object that represents the rigid body. // // Return: Nothing. // // Remarks: The function *NewtonSetTransform callback* is called by the Newton engine every time a visual object that represents the rigid body has changed. // The application can obtain the pointer user data value that points to the visual object. // The Newton engine does not call the *NewtonSetTransform callback* function for bodies that are inactive or have reached a state of stable equilibrium. // // Remarks: The matrix should be organized in row-major order (this is the way directX and OpenGL stores matrices). // // See also: NewtonBodyGetUserData, NewtonBodyGetUserData void NewtonBodySetTransformCallback(const NewtonBody* const bodyPtr, NewtonSetTransform callback) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); body->SetMatrixUpdateCallback((OnMatrixUpdateCallback) callback); } // Name: NewtonBodyGetTransformCallback // Assign a transformation event function to the body. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // *NewtonSetTransform callback - pointer to a function callback in used to update the transformation matrix of the visual object that represents the rigid body. // // Return: Nothing. // // Remarks: The function *NewtonSetTransform callback* is called by the Newton engine every time a visual object that represents the rigid body has changed. // The application can obtain the pointer user data value that points to the visual object. // The Newton engine does not call the *NewtonSetTransform callback* function for bodies that are inactive or have reached a state of stable equilibrium. // // Remarks: The matrix should be organized in row-major order (this is the way directX and OpenGL stores matrices). // // See also: NewtonBodyGetUserData, NewtonBodyGetUserData NewtonSetTransform NewtonBodyGetTransformCallback( const NewtonBody* const bodyPtr) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); return (NewtonSetTransform) body->GetMatrixUpdateCallback(); } // Name: NewtonBodySetForceAndTorqueCallback // Assign an event function for applying external force and torque to a rigid body. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // *NewtonApplyForceAndTorque callback - pointer to a function callback used to apply force and torque to a rigid body. // // Return: Nothing. // // Remarks: Before the *NewtonApplyForceAndTorque callback* is called for a body, Newton first clears the net force and net torque for the body. // // Remarks: The function *NewtonApplyForceAndTorque callback* is called by the Newton Engine every time an active body is going to be simulated. // The Newton Engine does not call the *NewtonApplyForceAndTorque callback* function for bodies that are inactive or have reached a state of stable equilibrium. // // See also: NewtonBodyGetUserData, NewtonBodyGetUserData, NewtonBodyGetForceAndTorqueCallback void NewtonBodySetForceAndTorqueCallback(const NewtonBody* const bodyPtr, NewtonApplyForceAndTorque callback) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); body->SetExtForceAndTorqueCallback((OnApplyExtForceAndTorque) callback); } // Name: NewtonBodyGetForceAndTorqueCallback // Return the pointer to the current force and torque call back function. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // // Return: pointer to the force call back. // // Remarks: This function can be used to concatenate different force calculation components making more modular the // design of function components dedicated to apply special effect. For example a body may have a basic force a force that // only apply the effect of gravity, but that application can place a region in where there can be a fluid volume, or another gravity field. // we this function the application can read the correct function and save into a local variable, and set a new one. // this new function will firs call the save function pointer and upon return apply the correct effect. // this similar to the concept of virtual methods on objected oriented languages. // // Remarks: The function *NewtonApplyForceAndTorque callback* is called by the Newton Engine every time an active body is going to be simulated. // The Newton Engine does not call the *NewtonApplyForceAndTorque callback* function for bodies that are inactive or have reached a state of stable equilibrium. // // See also: NewtonBodyGetUserData, NewtonBodyGetUserData, NewtonBodySetForceAndTorqueCallback NewtonApplyForceAndTorque NewtonBodyGetForceAndTorqueCallback( const NewtonBody* const bodyPtr) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); return (NewtonApplyForceAndTorque) body->GetExtForceAndTorqueCallback(); } // Name: NewtonBodySetDestructorCallback // Assign an event function to be called when this body is about to be destroyed. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body to be destroyed. // *NewtonBodyDestructor* callback - pointer to a function callback. // // Return: Nothing. // // Remarks: // This function *NewtonBodyDestructor callback* acts like a destruction function in CPP. This function // is called when the body and all data joints associated with the body are about to be destroyed. // The application could use this function to destroy or release any resource associated with this body. // The application should not make reference to this body after this function returns. // // Remarks: // The destruction of a body will destroy all joints associated with the body. // // See also: NewtonBodyGetUserData, NewtonBodyGetUserData void NewtonBodySetDestructorCallback(const NewtonBody* const bodyPtr, NewtonBodyDestructor callback) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); body->SetDestructorCallback((OnBodyDestroy) callback); } // Name: NewtonBodySetMassMatrix // Set the mass matrix of a rigid body. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // *dFloat* mass - mass value. // *dFloat* Ixx - moment of inertia of the first principal axis of inertia of the body. // *dFloat* Iyy - moment of inertia of the first principal axis of inertia of the body. // *dFloat* Izz - moment of inertia of the first principal axis of inertia of the body. // // Return: Nothing. // // Remarks: Newton algorithms have no restriction on the values for the mass, but due to floating point dynamic // range (24 bit precision) it is best if the ratio between the heaviest and the lightest body in the scene is limited to 200. // There are no special utility functions in Newton to calculate the moment of inertia of common primitives. // The application should specify the inertial values, keeping in mind that realistic inertia values are necessary for // realistic physics behavior. // // See also: NewtonConvexCollisionCalculateInertialMatrix, NewtonBodyGetMassMatrix, NewtonBodyGetInvMass void NewtonBodySetMassMatrix(const NewtonBody* const bodyPtr, dFloat mass, dFloat Ixx, dFloat Iyy, dFloat Izz) { dgBody *body; dFloat Ixx1; dFloat Iyy1; dFloat Izz1; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); mass = dgAbsf(mass); Ixx = dgAbsf(Ixx); Iyy = dgAbsf(Iyy); Izz = dgAbsf(Izz); Ixx1 = ClampValue(Ixx, dgFloat32(0.001f) * mass, dgFloat32(100.0f) * mass); Iyy1 = ClampValue(Iyy, dgFloat32(0.001f) * mass, dgFloat32(100.0f) * mass); Izz1 = ClampValue(Izz, dgFloat32(0.001f) * mass, dgFloat32(100.0f) * mass); if (mass < dgFloat32(1.0e-3f)) { mass = DG_INFINITE_MASS * dgFloat32(1.5f); } body->SetMassMatrix(mass, Ixx1, Iyy1, Izz1); body->SetAparentMassMatrix(dgVector(Ixx, Iyy, Izz, mass)); } // Name: NewtonBodyGetMassMatrix // Get the mass matrix of a rigid body. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // *dFloat* *mass - pointer to a variable that will hold the mass value of the body. // *dFloat* *Ixx - pointer to a variable that will hold the moment of inertia of the first principal axis of inertia of the body. // *dFloat* *Iyy - pointer to a variable that will hold the moment of inertia of the first principal axis of inertia of the body. // *dFloat* *Izz - pointer to a variable that will hold the moment of inertia of the first principal axis of inertia of the body. // // Return: Nothing. // // See also: NewtonBodySetMassMatrix, NewtonBodyGetInvMass void NewtonBodyGetMassMatrix(const NewtonBody* const bodyPtr, dFloat* const mass, dFloat* const Ixx, dFloat* const Iyy, dFloat* const Izz) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); // dgVector vector (body->GetMass ()); dgVector vector(body->GetAparentMass()); Ixx[0] = vector.m_x; Iyy[0] = vector.m_y; Izz[0] = vector.m_z; mass[0] = vector.m_w; if (vector.m_w > DG_INFINITE_MASS * 0.5f) { Ixx[0] = 0.0f; Iyy[0] = 0.0f; Izz[0] = 0.0f; mass[0] = 0.0f; } } // Name: NewtonBodyGetInvMass // Get the inverse mass matrix of a rigid body. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // *dFloat* *invMass - pointer to a variable that will hold the mass inverse value of the body. // *dFloat* *invIxx - pointer to a variable that will hold the moment of inertia inverse of the first principal axis of inertia of the body. // *dFloat* *invIyy - pointer to a variable that will hold the moment of inertia inverse of the first principal axis of inertia of the body. // *dFloat* *invIzz - pointer to a variable that will hold the moment of inertia inverse of the first principal axis of inertia of the body. // // Return: Nothing. // // See also: NewtonBodySetMassMatrix, NewtonBodyGetMassMatrix void NewtonBodyGetInvMass(const NewtonBody* const bodyPtr, dFloat* const invMass, dFloat* const invIxx, dFloat* const invIyy, dFloat* const invIzz) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); // dgVector vector (body->GetInvMass ()); // invIxx[0] = vector.m_x; // invIyy[0] = vector.m_y; // invIzz[0] = vector.m_z; // invMass[0] = vector.m_w; dgVector vector1(body->GetAparentMass()); invIxx[0] = dgFloat32(1.0f) / (vector1.m_x + dgFloat32(1.0e-8f)); invIyy[0] = dgFloat32(1.0f) / (vector1.m_y + dgFloat32(1.0e-8f)); invIzz[0] = dgFloat32(1.0f) / (vector1.m_z + dgFloat32(1.0e-8f)); invMass[0] = dgFloat32(1.0f) / (vector1.m_w + dgFloat32(1.0e-8f)); } // Name: NewtonBodySetMatrix // Set the transformation matrix of a rigid body. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // *const dFloat* *matrixPtr - pointer to an array of 16 floats containing the global matrix of the rigid body. // // Return: Nothing. // // Remarks: The matrix should be arranged in row-major order. // If you are using OpenGL matrices (column-major) you will need to transpose you matrices into a local array, before // passing them to Newton. // // Remarks: That application should make sure the transformation matrix has not scale, otherwise unpredictable result will occur. // // See also: NewtonBodyGetMatrix void NewtonBodySetMatrix(const NewtonBody* const bodyPtr, const dFloat* const matrixPtr) { dgBody *body; body = (dgBody *) bodyPtr; dgMatrix matrix(*((dgMatrix*) matrixPtr)); TRACE_FUNTION(__FUNCTION__); #ifdef _DEBUG // matrix.m_front = matrix.m_front.Scale (dgRsqrt (matrix.m_front % matrix.m_front)); // matrix.m_right = matrix.m_front * matrix.m_up; // matrix.m_right = matrix.m_right.Scale (dgRsqrt (matrix.m_right % matrix.m_right)); // matrix.m_up = matrix.m_right * matrix.m_front; #endif matrix.m_front.m_w = dgFloat32(0.0f); matrix.m_up.m_w = dgFloat32(0.0f); matrix.m_right.m_w = dgFloat32(0.0f); matrix.m_posit.m_w = dgFloat32(1.0f); body->SetMatrixIgnoreSleep(matrix); } // Name: NewtonBodySetMatrixRecursive // Apply hierarchical transformation to a body. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // *const dFloat* *matrixPtr - pointer to an array of 16 floats containing the global matrix of the rigid body. // // Return: Nothing. // // Remarks: This function applies the transformation matrix to the *body* and also applies the appropriate transformation matrix to // set of articulated bodies. If the body is in contact with another body the other body is not transformed. // // Remarks: this function should not be used to transform set of articulated bodies that are connected to a static body. // doing so will result in unpredictables results. Think for example moving a chain attached to a ceiling from one place to another, // to do that in real life a person first need to disconnect the chain (destroy the joint), move the chain (apply the transformation to the // entire chain), the reconnect it in the new position (recreate the joint again). // // Remarks: this function will set to zero the linear and angular velocity of all bodies that are part of the set of articulated body array. // // Remarks: The matrix should be arranged in row-major order (this is the way direct x stores matrices). // If you are using OpenGL matrices (column-major) you will need to transpose you matrices into a local array, before // passing them to Newton. // // See also: NewtonBodySetMatrix void NewtonBodySetMatrixRecursive(const NewtonBody* const bodyPtr, const dFloat* const matrixPtr) { dgBody *body; Newton* world; body = (dgBody *) bodyPtr; world = (Newton *) body->GetWorld(); dgMatrix matrix(*((dgMatrix*) matrixPtr)); world->BodySetMatrix(body, matrix); } // Name: NewtonBodyGetMatrix // Get the transformation matrix of a rigid body. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // *const dFloat* *matrixPtr - pointer to an array of 16 floats that will hold the global matrix of the rigid body. // // Return: Nothing. // // Remarks: The matrix should be arranged in row-major order (this is the way direct x stores matrices). // If you are using OpenGL matrices (column-major) you will need to transpose you matrices into a local array, before // passing them to Newton. // // See also: NewtonBodySetMatrix, NewtonBodyGetRotation void NewtonBodyGetMatrix(const NewtonBody* const bodyPtr, dFloat* const matrixPtr) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); dgMatrix& matrix = *((dgMatrix*) matrixPtr); matrix = body->GetMatrix(); } // Name: NewtonBodyGetRotation // Get the rotation part of the transformation matrix of a body, in form of a unit quaternion. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // *const dFloat* *rotPtr - pointer to an array of 4 floats that will hold the global rotation of the rigid body. // // Return: Nothing. // // Remarks: The rotation matrix is written set in the form of a unit quaternion in the format Rot (q0, q1, q1, q3) // // Remarks: The rotation quaternion is the same as what the application would get by using at function to extract a quaternion form a matrix. // however since the rigid body already contained the rotation in it, it is more efficient to just call this function avoiding expensive conversion. // // Remarks: this function could be very useful for the implementation of pseudo frame rate independent simulation. // by running the simulation at a fix rate and using linear interpolation between the last two simulation frames. // to determine the exact fraction of the render step. // // See also: NewtonBodySetMatrix, NewtonBodyGetMatrix void NewtonBodyGetRotation(const NewtonBody* const bodyPtr, dFloat* rotPtr) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); dgQuaternion& rot = *((dgQuaternion*) rotPtr); rot = body->GetRotation(); } // Name: NewtonBodySetForce // Set the net force applied to a rigid body. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // *const dFloat* *vectorPtr - pointer to an array of 3 floats containing the net force to be applied to the body. // // Return: Nothing. // // Remarks: This function is only effective when called from *NewtonApplyForceAndTorque callback* // // See also: NewtonBodyAddForce, NewtonBodyGetForce, NewtonBodyGetForceAcc void NewtonBodySetForce(const NewtonBody* const bodyPtr, const dFloat* vectorPtr) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); dgVector vector(vectorPtr[0], vectorPtr[1], vectorPtr[2], dgFloat32(0.0f)); body->SetForce(vector); } // Name: NewtonBodyAddForce // Add the net force applied to a rigid body. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body to be destroyed. // *const dFloat* *vectorPtr - pointer to an array of 3 floats containing the net force to be applied to the body. // // Return: Nothing. // // Remarks: This function is only effective when called from *NewtonApplyForceAndTorque callback* // // See also: NewtonBodySetForce, NewtonBodyGetForce, NewtonBodyGetForceAcc void NewtonBodyAddForce(const NewtonBody* const bodyPtr, const dFloat* const vectorPtr) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); dgVector vector(vectorPtr[0], vectorPtr[1], vectorPtr[2], dgFloat32(0.0f)); body->AddForce(vector); } // Name: NewtonBodyGetForceAcc // Get the force applied on the last call to apply force and torque callback. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // *const dFloat* *vectorPtr - pointer to an array of 3 floats to hold the net force of the body. // // Remark: this function can be useful to modify force from joint callback // // Return: Nothing. // // See also: NewtonBodyAddForce, NewtonBodyGetForce, NewtonBodyGetForce void NewtonBodyGetForceAcc(const NewtonBody* const bodyPtr, dFloat* const vectorPtr) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); dgVector vector(body->GetForce()); vectorPtr[0] = vector.m_x; vectorPtr[1] = vector.m_y; vectorPtr[2] = vector.m_z; } // Name: NewtonBodyGetForce // Get the net force applied to a rigid body after the last NewtonUpdate. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // *const dFloat* *vectorPtr - pointer to an array of 3 floats to hold the net force of the body. // // Return: Nothing. // // See also: NewtonBodyAddForce, NewtonBodyGetForce, NewtonBodyGetForceAcc void NewtonBodyGetForce(const NewtonBody* const bodyPtr, dFloat* const vectorPtr) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); dgVector vector(body->GetNetForce()); vectorPtr[0] = vector.m_x; vectorPtr[1] = vector.m_y; vectorPtr[2] = vector.m_z; } // Name: NewtonBodyCalculateInverseDynamicsForce // Calculate the next force that net to be applied to the body to archive the desired velocity in the current time step. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // *dFloat* timestep - time step that the force will be applyed. // *const dFloat* *desiredVeloc - pointer to an array of 3 floats containing the desired velocity. // *dFloat* *forceOut - pointer to an array of 3 floats to hold the calculated net force. // // Remark: this function can be useful when creating object for game play. // // remark: this treat the body as a point mass and is uses the solver to calculates the net force that need to be applied to the body // such that is reach the desired velocity in the net time step. // In general the force should be calculated by the expression f = M * (dsiredVeloc - bodyVeloc) / timestep // however due to algorithmic optimization and limitations if such equation is used then the solver will generate a different desired velocity. // // Return: Nothing. // // See also: NewtonBodySetForce, NewtonBodyAddForce, NewtonBodyGetForce, NewtonBodyGetForceAcc void NewtonBodyCalculateInverseDynamicsForce(const NewtonBody* const bodyPtr, dFloat timestep, const dFloat* const desiredVeloc, dFloat* const forceOut) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); dgVector veloc(desiredVeloc[0], desiredVeloc[1], desiredVeloc[2], dgFloat32(0.0f)); dgVector force(body->CalculateInverseDynamicForce(veloc, timestep)); forceOut[0] = force[0]; forceOut[1] = force[1]; forceOut[2] = force[2]; } // Name: NewtonBodySetTorque // Set the net torque applied to a rigid body. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // *const dFloat* *vectorPtr - pointer to an array of 3 floats containing the net torque to be applied to the body. // // Return: Nothing. // // Remarks: This function is only effective when called from *NewtonApplyForceAndTorque callback* // // See also: NewtonBodyAddTorque, NewtonBodyGetTorque, NewtonBodyGetTorqueAcc void NewtonBodySetTorque(const NewtonBody* const bodyPtr, const dFloat* const vectorPtr) { dgBody *body; TRACE_FUNTION(__FUNCTION__); body = (dgBody *) bodyPtr; dgVector vector(vectorPtr[0], vectorPtr[1], vectorPtr[2], dgFloat32(0.0f)); body->SetTorque(vector); } // Name: NewtonBodyAddTorque // Add the net torque applied to a rigid body. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // *const dFloat* *vectorPtr - pointer to an array of 3 floats containing the net torque to be applied to the body. // // Return: Nothing. // // Remarks: This function is only effective when called from *NewtonApplyForceAndTorque callback* // // See also: NewtonBodySetTorque, NewtonBodyGetTorque, NewtonBodyGetTorqueAcc void NewtonBodyAddTorque(const NewtonBody* const bodyPtr, const dFloat* const vectorPtr) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); dgVector vector(vectorPtr[0], vectorPtr[1], vectorPtr[2], dgFloat32(0.0f)); body->AddTorque(vector); } // Name: NewtonBodyGetTorque // Get the net torque applied to a rigid body after the last NewtonUpdate. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // *const dFloat* *vectorPtr - pointer to an array of 3 floats to hold the net torque of the body. // // Return: Nothing. // // See also: NewtonBodyAddTorque, NewtonBodyGetTorque, NewtonBodyGetTorqueAcc void NewtonBodyGetTorque(const NewtonBody* const bodyPtr, dFloat* const vectorPtr) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); dgVector vector(body->GetNetTorque()); vectorPtr[0] = vector.m_x; vectorPtr[1] = vector.m_y; vectorPtr[2] = vector.m_z; } // Name: NewtonBodyGetTorqueAcc // Get the torque applied on the last call to apply force and torque callback. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // *const dFloat* *vectorPtr - pointer to an array of 3 floats to hold the net force of the body. // // Remark: this function can be useful to modify torque form joint callback // // Return: Nothing. // // See also: NewtonBodyAddTorque, NewtonBodyGetTorque, NewtonBodyGetTorque void NewtonBodyGetTorqueAcc(const NewtonBody* const bodyPtr, dFloat* const vectorPtr) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); dgVector vector(body->GetTorque()); vectorPtr[0] = vector.m_x; vectorPtr[1] = vector.m_y; vectorPtr[2] = vector.m_z; } // Name: NewtonBodySetCentreOfMass // Set the relative position of the center of mass of a rigid body. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // *const dFloat* *comPtr - pointer to an array of 3 floats containing the relative offset of the center of mass of the body. // // Return: Nothing. // // Remarks: This function can be used to set the relative offset of the center of mass of a rigid body. // when a rigid body is created the center of mass is set the the point c(0, 0, 0), and normally this is // the best setting for a rigid body. However the are situations in which and object does not have symmetry or // simple some kind of special effect is desired, and this origin need to be changed. // // Remarks: Care must be taken when offsetting the center of mass of a body. // The application must make sure that the external torques resulting from forces applied at at point // relative to the center of mass are calculated appropriately. // this could be done Transform and Torque callback function as the follow pseudo code fragment shows: // // Matrix matrix; // Vector center; // // NewtonGatMetrix(body, matrix) // NewtonGetCentreOfMass(body, center); // // for global space torque. // Vector localForce (fx, fy, fz); // Vector localPosition (x, y, z); // Vector localTroque (crossproduct ((localPosition - center). localForce); // Vector globalTroque (matrix.RotateVector (localTroque)); // // for global space torque. // Vector globalCentre (matrix.TranformVector (center)); // Vector globalPosition (x, y, z); // Vector globalForce (fx, fy, fz); // Vector globalTroque (crossproduct ((globalPosition - globalCentre). globalForce); // // See also: NewtonConvexCollisionCalculateInertialMatrix, NewtonBodyGetCentreOfMass void NewtonBodySetCentreOfMass(const NewtonBody* const bodyPtr, const dFloat* const comPtr) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); dgVector vector(comPtr[0], comPtr[1], comPtr[2], dgFloat32(1.0f)); body->SetCentreOfMass(vector); } // Name: NewtonBodyGetCentreOfMass // Get the relative position of the center of mass of a rigid body. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // *dFloat* *comPtr - pointer to an array of 3 floats to hold the relative offset of the center of mass of the body. // // Return: Nothing. // // Remarks: This function can be used to set the relative offset of the center of mass of a rigid body. // when a rigid body is created the center of mass is set the the point c(0, 0, 0), and normally this is // the best setting for a rigid body. However the are situations in which and object does not have symmetry or // simple some kind of special effect is desired, and this origin need to be changed. // // Remarks: This function can be used in conjunction with *NewtonConvexCollisionCalculateInertialMatrix* // // See also: NewtonConvexCollisionCalculateInertialMatrix, NewtonBodySetCentreOfMass void NewtonBodyGetCentreOfMass(const NewtonBody* const bodyPtr, dFloat* const comPtr) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); dgVector vector(body->GetCentreOfMass()); comPtr[0] = vector.m_x; comPtr[1] = vector.m_y; comPtr[2] = vector.m_z; } // Name: NewtonBodyGetFirstJoint // Return a pointer to the first joint attached to this rigid body. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // // Return: Joint if at least one is attached to the body, NULL if not joint is attached // // Remarks: this function will only return the pointer to user defined joints, older build in constraints will be skipped by this function. // // Remark: this function can be used to implement recursive walk of complex articulated arrangement of rodid bodies. // // See also: NewtonBodyGetNextJoint NewtonJoint* NewtonBodyGetFirstJoint(const NewtonBody* const bodyPtr) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); return (NewtonJoint*) body->GetFirstJoint(); } // Name: NewtonBodyGetNextJoint // Return a pointer to the next joint attached to this body. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // *const NewtonJoint* *joint - pointer to current joint. // // Return: Joint is at least one joint is attached to the body, NULL if not joint is attached // // Remarks: this function will only return the pointer to User defined joint, older build in constraints will be skipped by this function. // // Remark: this function can be used to implement recursive walk of complex articulated arrangement of rodid bodies. // // See also: NewtonBodyGetFirstJoint NewtonJoint* NewtonBodyGetNextJoint(const NewtonBody* const bodyPtr, const NewtonJoint* const jointPtr) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); return (NewtonJoint*) body->GetNextJoint((dgConstraint*) jointPtr); } // Name: NewtonBodyGetFirstContactJoint // Return a pointer to the first contact joint attached to this rigid body. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // // Return: Contact if the body is colliding with anther body, NULL otherwise // // See also: NewtonBodyGetNextContactJoint, NewtonContactJointGetFirstContact, NewtonContactJointGetNextContact, NewtonContactJointRemoveContact NewtonJoint* NewtonBodyGetFirstContactJoint(const NewtonBody* const bodyPtr) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); return (NewtonJoint*) body->GetFirstContact(); } // Name: NewtonBodyGetNextContactJoint // Return a pointer to the next contactjoint attached to this rigid body. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // *const NewtonJoint* *contactJoint - pointer to corrent contact joint. // // Return: Contact if the body is colliding with anther body, NULL otherwise // // See also: NewtonBodyGetFirstContactJoint, NewtonContactJointGetFirstContact, NewtonContactJointGetNextContact, NewtonContactJointRemoveContact NewtonJoint* NewtonBodyGetNextContactJoint(const NewtonBody* const bodyPtr, const NewtonJoint* const contactPtr) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); return (NewtonJoint*) body->GetNextContact((dgConstraint*) contactPtr); } // Name: NewtonContactJointGetContactCount // Return to number of contact int thsi contact joint. // // Parameters: // *const NewtonJoint* *contactJoint - pointer to corrent contact joint. // // Return: numbet of contacts. // // See also: NewtonContactJointGetFirstContact, NewtonContactJointGetNextContact, NewtonContactJointRemoveContact int NewtonContactJointGetContactCount(const NewtonJoint* const contactJoint) { dgContact *joint; joint = (dgContact *) contactJoint; TRACE_FUNTION(__FUNCTION__); if ((joint->GetId() == dgContactConstraintId) && joint->GetCount()) { return joint->GetCount(); } else { return 0; } } // Name: NewtonContactJointGetFirstContact // Return to the next contact from the cantact array of the contact joint. // // Parameters: // *const NewtonJoint* *contactJoint - pointer to corrent contact joint. // // Return: first contact contact array of the joint contact exist, NULL otherwise // // See also: NewtonContactJointGetNextContact, NewtonContactGetMaterial, NewtonContactJointRemoveContact void* NewtonContactJointGetFirstContact(const NewtonJoint* const contactJoint) { dgContact *joint; joint = (dgContact *) contactJoint; TRACE_FUNTION(__FUNCTION__); if ((joint->GetId() == dgContactConstraintId) && joint->GetCount()) { return joint->GetFirst(); } else { return NULL; } } // Name: NewtonContactJointGetNextContact // Return to the first contact fromm the cantact array of the contact joint. // // Parameters: // *const NewtonJoint* *contactJoint - pointer to corrent contact joint. // *void* *contact - pointer to current contact. // // Return: a handle to the next contact contact in the contact array if contact exist, NULL otherwise. // // See also: NewtonContactJointGetFirstContact, NewtonContactGetMaterial, NewtonContactJointRemoveContact void* NewtonContactJointGetNextContact(const NewtonJoint* const contactJoint, void* const contact) { dgContact *joint; joint = (dgContact *) contactJoint; TRACE_FUNTION(__FUNCTION__); if ((joint->GetId() == dgContactConstraintId) && joint->GetCount()) { dgList<dgContactMaterial>::dgListNode* node; node = (dgList<dgContactMaterial>::dgListNode*) contact; return node->GetNext(); } else { return NULL; } } // Name: NewtonContactJointRemoveContact // Return to the next contact from the cantact array of the contact joint. // // Parameters: // *const NewtonJoint* *contactJoint - pointer to corrent contact joint. // // Return: first contact contact array of the joint contact exist, NULL otherwise // // See also: NewtonBodyGetFirstContactJoint, NewtonBodyGetNextContactJoint, NewtonContactJointGetFirstContact, NewtonContactJointGetNextContact void NewtonContactJointRemoveContact(const NewtonJoint* const contactJoint, void* const contact) { dgContact *joint; joint = (dgContact *) contactJoint; TRACE_FUNTION(__FUNCTION__); if ((joint->GetId() == dgContactConstraintId) && joint->GetCount()) { dgList<dgContactMaterial>::dgListNode* node; node = (dgList<dgContactMaterial>::dgListNode*) contact; joint->Remove(node); } } // Name: NewtonContactGetMaterial // Return to the next contact from the cantact array of the contact joint. // // Parameters: // *const NewtonJoint* *contactJoint - pointer to corrent contact joint. // // Return: first contact contact array of the joint contact exist, NULL otherwise // // See also: NewtonContactJointGetFirstContact, NewtonContactJointGetNextContact NewtonMaterial* NewtonContactGetMaterial(const void* const contact) { dgList<dgContactMaterial>::dgListNode* node; TRACE_FUNTION(__FUNCTION__); node = (dgList<dgContactMaterial>::dgListNode*) contact; dgContactMaterial& contactMaterial = node->GetInfo(); return (NewtonMaterial*) &contactMaterial; } // Name: NewtonBodyAddBuoyancyForce // Add buoyancy force and torque for bodies immersed in a fluid. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // *dFloat* fluidDensity - fluid density. // *dFloat* fluidLinearViscosity - fluid linear viscosity (resistance to linear translation). // *dFloat* fluidAngularViscosity - fluid angular viscosity (resistance to rotation). // *const dFloat* *gravityVector - pointer to an array of floats containing the gravity vector. // *NewtonGetBuoyancyPlane* *buoyancyPlane - pointer to an array of at least 4 floats containing the plane equation of the surface of the fluid. This parameter can be NULL // // Return: Nothing. // // Remarks: This function is only effective when called from *NewtonApplyForceAndTorque callback* // // Remarks: This function adds buoyancy force and torque to a body when it is immersed in a fluid. // The force is calculated according to Archimedes’ Buoyancy Principle. When the parameter *buoyancyPlane* is set to NULL, the body is considered // to completely immersed in the fluid. This can be used to simulate boats and lighter than air vehicles etc.. // // Remarks: If *buoyancyPlane* return 0 buoyancy calculation for this collision primitive is ignored, this could be used to filter buoyancy calculation // of compound collision geometry with different IDs. // // See also: NewtonConvexCollisionCalculateVolume void NewtonBodyAddBuoyancyForce(const NewtonBody* const bodyPtr, dFloat fluidDensity, dFloat fluidLinearViscosity, dFloat fluidAngularViscosity, const dFloat* const gravityVector, NewtonGetBuoyancyPlane buoyancyPlane, void* const context) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); dgVector gravity(gravityVector[0], gravityVector[1], gravityVector[2], dgFloat32(0.0f)); body->AddBuoyancyForce(fluidDensity, fluidLinearViscosity, fluidAngularViscosity, gravity, (GetBuoyancyPlane) buoyancyPlane, context); } // Name: NewtonBodySetCollision // Assign a collision primitive to the body. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // *const collisionPtr* *collisionPtr - pointer to the new collision geometry. // // Return: Nothing. // // Remarks: This function replaces a collision geometry of a body with the new collision geometry. // This function increments the reference count of the collision geometry and decrements the reference count // of the old collision geometry. If the reference count of the old collision geometry reaches zero, the old collision geometry is destroyed. // This function can be used to swap the collision geometry of bodies at runtime. // // See also: NewtonCreateBody, NewtonBodyGetCollision void NewtonBodySetCollision(const NewtonBody* const bodyPtr, const NewtonCollision* const collisionPtr) { dgBody *body; dgCollision* collision; TRACE_FUNTION(__FUNCTION__); body = (dgBody *) bodyPtr; collision = (dgCollision*) collisionPtr; body->AttachCollision(collision); } /* // Name: NewtonBodySetGyroscopicForcesMode // Enable or disable Coriolis and gyroscopic force calculation for this body. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // *int* mode - force mode zero indicate not gyroscopic force calculation. // // Return: Nothing. // // Remarks: Gyroscopic forces internal forces generated as a result of an asymmetric tensor. They are a pure mathematical consequence that the physics have to comply in order to agree with the math. As Gyroscopic forces are not real forces but the result of net unbalance of the changing inertia tensor or a rigid body when its angular velocity is measured on a reference frame different than the body’s own. // Gyroscopic forces are extremely non linear by nature, therefore a first order implicit integrator will have a extremely hard time at dealing with this kind of forces, however because the fact that they are not real forces they do not make much difference in the outcome of the integration. // Fortunately due to the fact that the magnitude of gyroscopic forces is proportional to the unbalance of the inertia tensor, it is possible to disregard the effect of this forces by assuming their inertial tensor is symmetric for the purpose of this calculation. For most cases an ordinary person is not capable to distinguish the motion of a body subject to gyroscopic forces and one that is not, especially when the motion is constrained. // Because of this fact gyroscopic force are turned off by default in Newton, however there are cases when the desire effect is precisely to simulate these forces like a spinning top, or the design of a space navigational system, etc. The most important feature of gyroscopic forces is that they make the rigid body to process. void NewtonBodySetGyroscopicForcesMode(const NewtonBody* const bodyPtr, int mode) { dgBody *body; body = (dgBody *)bodyPtr; body->SetGyroscopicTorqueMode (mode ? true : false); } // Name: NewtonBodyGetGyroscopicForcesMode // get a values indicating if Coriolis and gyroscopic force calculation for this body are enable. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // // Return: force mode 1 means Gyro copy force are on. // // Remarks: Gyroscopic forces are internal forces generated as a result of an asymmetric tensor. They are a pure mathematical consequence that the physics have to comply in order to agree with the math. As Gyroscopic forces are not real forces but the result of net unbalance of the changing inertia tensor or a rigid body when its angular velocity is measured on a reference frame different than the body’s own. // Gyroscopic forces are extremely non linear by nature, therefore a first order implicit integrator will have a extremely hard time at dealing with this kind of forces, however because the fact that they are not real forces they do not make much difference in the outcome of the integration. // Fortunately due to the fact that the magnitude of gyroscopic forces is proportional to the unbalance of the inertia tensor, it is possible to disregard the effect of this forces by assuming their inertial tensor is symmetric for the purpose of this calculation. For most cases an ordinary person is not capable to distinguish the motion of a body subject to gyroscopic forces and one that is not, especially when the motion is constrained. // Because of this fact gyroscopic force are turned off by default in Newton, however there are cases when the desire effect is precisely to simulate these forces like a spinning top, or the design of a space navigational system, etc. The most important feature of gyroscopic forces is that they make the rigid body to process. int NewtonBodyGetGyroscopicForcesMode(const NewtonBody* const bodyPtr) { dgBody *body; body = (dgBody *)bodyPtr; return body->GetGyroscopicTorqueMode () ? 1 : 0; } */ // Name: NewtonBodyGetCollision // Get the collision primitive of a body. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // // Return: Pointer to body collision geometry. // // Remarks: This function does not increment the reference count of the collision geometry. // // See also: NewtonCreateBody, NewtonBodySetCollision NewtonCollision* NewtonBodyGetCollision(const NewtonBody* const bodyPtr) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); return (NewtonCollision*) body->GetCollision(); } // Name: NewtonBodySetMaterialGroupID // Assign a material group id to the body. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // *int* id - id of a previously created material group. // // Return: Nothing. // // Remarks: When the application creates a body, the default material group, *defaultGroupId*, is applied by default. // // See also: NewtonBodyGetMaterialGroupID, NewtonMaterialCreateGroupID, NewtonMaterialGetDefaultGroupID void NewtonBodySetMaterialGroupID(const NewtonBody* const bodyPtr, int id) { dgBody* const body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); body->SetGroupID(dgUnsigned32(id)); } // Name: NewtonBodyGetMaterialGroupID // Get the material group id of the body. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // *int* id - id of a previously created material group. // // Return: Nothing. // // See also: NewtonBodySetMaterialGroupID int NewtonBodyGetMaterialGroupID(const NewtonBody* const bodyPtr) { dgBody* const body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); return int(body->GetGroupID()); } // Name: NewtonBodySetContinuousCollisionMode // Set the continuous collision state mode for this rigid body. // continue collision flag is off by default in when bodies are created. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // *int* state - collision state. 1 indicates this body may tunnel through other objects while moving at high speed. 0 ignore high speed collision checks. // // Return: Nothing. // // Remarks: continue collision mode enable allow the engine to predict colliding contact on rigid bodies // Moving at high speed of subject to strong forces. // // Remarks: continue collision mode does not prevent rigid bodies from inter penetration instead it prevent bodies from // passing trough each others by extrapolating contact points when the bodies normal contact calculation determine the bodies are not colliding. // // Remarks: for performance reason the bodies angular velocities is only use on the broad face of the collision, // but not on the contact calculation. // // Remarks: continue collision does not perform back tracking to determine time of contact, instead it extrapolate contact by incrementally // extruding the collision geometries of the two colliding bodies along the linear velocity of the bodies during the time step, // if during the extrusion colliding contact are found, a collision is declared and the normal contact resolution is called. // // Remarks: for continue collision to be active the continue collision mode must on the material pair of the colliding bodies as well as on at least one of the two colliding bodies. // // Remarks: Because there is penalty of about 40% to 80% depending of the shape complexity of the collision geometry, this feature is set // off by default. It is the job of the application to determine what bodies need this feature on. Good guidelines are: very small objects, // and bodies that move a height speed. // // See also: NewtonBodyGetContinuousCollisionMode, NewtonBodySetContinuousCollisionMode void NewtonBodySetContinuousCollisionMode(const NewtonBody* const bodyPtr, unsigned state) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); body->SetContinuesCollisionMode(state ? true : false); } // Name: NewtonBodyGetContinuousCollisionMode // Get the continuous collision state mode for this rigid body. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // // Return: Nothing. // // Remarks: //Remark: Because there is there is penalty of about 3 to 5 depending of the shape complexity of the collision geometry, this feature is set //off by default. It is the job of the application to determine what bodies need this feature on. Good guidelines are: very small objects, //and bodies that move a height speed. // //Remark: this feature is currently disabled: // // See also: NewtonBodySetContinuousCollisionMode, NewtonBodySetContinuousCollisionMode int NewtonBodyGetContinuousCollisionMode(const NewtonBody* const bodyPtr) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); return body->GetContinuesCollisionMode() ? 1 : false; } // Name: NewtonBodySetJointRecursiveCollision // Set the collision state flag of this body when the body is connected to another body by a hierarchy of joints. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // *int* state - collision state. 1 indicates this body will collide with any linked body. 0 disable collision with body connected to this one by joints. // // Return: Nothing. // // Remarks: sometimes when making complicated arrangements of linked bodies it is possible the collision geometry of these bodies is in the way of the // joints work space. This could be a problem for the normal operation of the joints. When this situation happens the application can determine which bodies // are the problem and disable collision for those bodies while they are linked by joints. For the collision to be disable for a pair of body, // both bodies must have the collision disabled. If the joints connecting the bodies are destroyed these bodies become collidable automatically. // This feature can also be achieved by making special material for the whole configuration of jointed bodies, however it is a lot easier just to set collision disable // for jointed bodies. // // See also: NewtonBodySetMaterialGroupID void NewtonBodySetJointRecursiveCollision(const NewtonBody* const bodyPtr, unsigned state) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); body->SetCollisionWithLinkedBodies(state ? true : false); } // Name: NewtonBodyGetJointRecursiveCollision // Get the collision state flag when the body is joint. // // Parameters: // *const NewtonBody* *bodyPtr - pointer to the body. // // Return: return the collision state flag for this body. // // See also: NewtonBodySetMaterialGroupID int NewtonBodyGetJointRecursiveCollision(const NewtonBody* const bodyPtr) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); return body->GetCollisionWithLinkedBodies() ? 1 : 0; } // Name: NewtonBodyGetFreezeState // get the freeze state of this body // // Parameters: // *const NewtonBody* *bodyPtr - is the pointer to the body to be frozen // // Return: 1 id the bode is frozen, 0 if bode is unfrozen. // // Remarks: When a body is created it is automatically placed in the active simulation list. As an optimization // for large scenes, you may use this function to put background bodies in an inactive equilibrium state. // // Remarks: This function tells Newton that this body does not currently need to be simulated. // However, if the body is part of a larger configuration it may be affected indirectly by the reaction forces // of objects that it is connected to. // // See also: NewtonBodySetAutoSleep, NewtonBodyGetAutoSleep int NewtonBodyGetFreezeState(const NewtonBody* const bodyPtr) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); return body->GetFreeze() ? 1 : 0; } // Name: NewtonBodySetFreezeState // This function tells Newton to simulate or suspend simulation of this body and all other bodies in contact with it // // Parameters: // *const NewtonBody* *bodyPtr - is the pointer to the body to be activated // *int* state - 1 teels newton to freeze the bode and allconceted bodiesm, 0 to unfreze it // // Return: Nothing // // Remarks: This function to no activate the body, is just lock or unlock the body for physics simulation. // // See also: NewtonBodyGetFreezeState, NewtonBodySetAutoSleep, NewtonBodyGetAutoSleep void NewtonBodySetFreezeState(const NewtonBody* const bodyPtr, int state) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); body->SetFreeze(state ? true : false); } // Name: NewtonBodySetAutoSleep // Set the auto-activation mode for this body. // // Parameters: // *const NewtonBody* *bodyPtr - is the pointer to the body. // *int* state - active mode: 1 = auto-activation on (controlled by Newton). 0 = auto-activation off and body is active all the time. // // Return: Nothing. // // Remarks: Bodies are created with auto-activation on by default. // // Remarks: Auto activation enabled is the default state for the majority of bodies in a large scene. // However, for player control, ai control or some other special circumstance, the application may want to control // the activation/deactivation of the body. // In that case, the application may call NewtonBodySetAutoSleep (body, 0) followed by // NewtonBodySetFreezeState(body), this will make the body active forever. // // See also: NewtonBodyGetFreezeState, NewtonBodySetFreezeState, NewtonBodyGetAutoSleep, NewtonBodySetFreezeTreshold void NewtonBodySetAutoSleep(const NewtonBody* const bodyPtr, int state) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); // body->SetAutoSleep (state ? false : true); body->SetAutoSleep(state ? true : false); } // Name: NewtonBodyGetAutoSleep // Get the auto-activation state of the body. // // Parameters: // *const NewtonBody* *bodyPtr - is the pointer to the body. // // Return: Auto activation state: 1 = auto-activation on. 0 = auto-activation off. // // See also: NewtonBodySetAutoSleep, NewtonBodyGetSleepState int NewtonBodyGetAutoSleep(const NewtonBody* const bodyPtr) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); return body->GetAutoSleep() ? 1 : 0; } // Name: NewtonBodyGetSleepState // Return the sleep mode of a rigid body. // // Parameters: // *const NewtonBody* *bodyPtr - is the pointer to the body. // // Return: Sleep state: 1 = active. 0 = sleeping. // // See also: NewtonBodySetAutoSleep int NewtonBodyGetSleepState(const NewtonBody* const bodyPtr) { dgBody *body; body = (dgBody *) bodyPtr; return body->GetSleepState() ? 1 : 0; } /* // Name: NewtonBodySetFreezeTreshold // Set the minimum values for velocity of a body that will be considered at rest. // // Parameters: // *const NewtonBody* *bodyPtr - is the pointer to the body. // *dFloat* freezeSpeedMag2 - magnitude squared of the velocity threshold. // *dFloat* freezeOmegaMag2 - magnitude squared of angular velocity threshold. // *int* framesCount - number of frames the body velocity and angular will not exceed freezeSpeedMag and freezeOmegaMag. // // Remarks: Ideally, a body should be deactivated when it reaches a state of stable equilibrium. However, because of floating point // inaccuracy, discrete time step simulation and other factors it is virtually impossible for a body to reach that state // in a real-time simulation. Therefore, in the Newton World, a body is considered to be in stable equilibrium when its // velocity and angular velocity fall below some threshold for a consecutive number of frames. // // Remarks: The default and minimum values for the thresholds is 0.01 for speed and 10 for frames count. // These values are tuned for single objects colliding under the influence of gravity. It is possible that for complex configuration // of bodies like multiples pendulums, rag dolls, etc. these values may need to be increased. This is because joints have the property that they // add a small amount of energy to the system in order to reduce the separation error. This may cause the bodies reach a state of unstable // equilibrium. That is, when a body oscillates between two different positions because the energy added to the body is equal to the energy // dissipated by the integrator. This is a situation that is hard to predict, and the best solution is to tweak these values for specific cases. // // See also: NewtonBodySetAutoSleep, NewtonBodyGetFreezeTreshold void NewtonBodySetFreezeTreshold(const NewtonBody* const bodyPtr, dFloat freezeSpeedMag2, dFloat freezeOmegaMag2, int framesCount) { // dFloat alpha; // dFloat accel; dgBody *body; body = (dgBody *)bodyPtr; // framesCount = GetMin (framesCount * 2, 30); // alpha = 60.0f * dgSqrt (freezeOmegaMag2) / framesCount; // accel = 60.0f * dgSqrt (freezeSpeedMag2) / framesCount; // body->SetFreezeTreshhold (accel * accel, alpha * alpha, freezeSpeedMag2, freezeOmegaMag2); // dFloat scale; // slace = dgFloat32(1.0f) / (framesCount body->SetFreezeTreshhold (freezeSpeedMag2, freezeOmegaMag2, freezeSpeedMag2 * dgFloat32(0.1f), freezeOmegaMag2 * dgFloat32(0.1f)); } // Name: NewtonBodyGetFreezeTreshold // Get the minimum values for velocity of a body the will be considered at rest. // // Parameters: // *const NewtonBody* *bodyPtr - is the pointer to the body. // *dFloat* freezeSpeedMag2 - point the to a dFloat to hold the velocity threshold // *dFloat* freezeOmegaMag2 - point the to a dFloat to hold the angular velocity threshold // // See also: NewtonBodySetFreezeTreshold void NewtonBodyGetFreezeTreshold(const NewtonBody* const bodyPtr, dFloat* freezeSpeedMag2, dFloat* freezeOmegaMag2) { dgBody *body; dFloat alpha; dFloat accel; body = (dgBody *)bodyPtr; body->GetFreezeTreshhold (accel, alpha, *freezeSpeedMag2, *freezeOmegaMag2); freezeSpeedMag2[0] *= 10.0f; freezeOmegaMag2[0] *= 10.0f; } */ // Name: NewtonBodyGetAABB // Get the world axis aligned bounding box (AABB) of the body. // // Parameters: // *const NewtonBody* *bodyPtr - is the pointer to the body. // *dFloat* *p0 - pointer to an array of at least three floats to hold minimum value for the AABB. // *dFloat* *p1 - pointer to an array of at least three floats to hold maximum value for the AABB. // void NewtonBodyGetAABB(const NewtonBody* const bodyPtr, dFloat* const p0, dFloat* const p1) { dgBody *body; dgVector vector0; dgVector vector1; TRACE_FUNTION(__FUNCTION__); body = (dgBody *) bodyPtr; body->GetAABB(vector0, vector1); p0[0] = vector0.m_x; p0[1] = vector0.m_y; p0[2] = vector0.m_z; p1[0] = vector1.m_x; p1[1] = vector1.m_y; p1[2] = vector1.m_z; } // Name: NewtonBodySetVelocity // Set the global linear velocity of the body. // // Parameters: // *const NewtonBody* *bodyPtr - is the pointer to the body. // *const dFloat* *velocity - pointer to an array of at least three floats containing the velocity vector. // // See also: NewtonBodyGetVelocity void NewtonBodySetVelocity(const NewtonBody* const bodyPtr, const dFloat* const velocity) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); dgVector vector(velocity[0], velocity[1], velocity[2], dgFloat32(0.0f)); body->SetVelocity(vector); } // Name: NewtonBodyGetVelocity // Get the global linear velocity of the body. // // Parameters: // *const NewtonBody* *bodyPtr - is the pointer to the body. // *const dFloat* *velocity - pointer to an array of at least three floats to hold the velocity vector. // // See also: NewtonBodySetVelocity void NewtonBodyGetVelocity(const NewtonBody* const bodyPtr, dFloat* const velocity) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); // dgVector& vector = *((dgVector*) velocity); // vector = body->GetVelocity(); dgVector vector(body->GetVelocity()); velocity[0] = vector.m_x; velocity[1] = vector.m_y; velocity[2] = vector.m_z; } // Name: NewtonBodySetOmega // Set the global angular velocity of the body. // // Parameters: // *const NewtonBody* *bodyPtr - is the pointer to the body. // *const dFloat* *omega - pointer to an array of at least three floats containing the angular velocity vector. // // See also: NewtonBodyGetOmega void NewtonBodySetOmega(const NewtonBody* const bodyPtr, const dFloat* const omega) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); dgVector vector(omega[0], omega[1], omega[2], dgFloat32(0.0f)); body->SetOmega(vector); } // Name: NewtonBodyGetOmega // Get the global angular velocity of the body. // // Parameters: // *const NewtonBody* *bodyPtr - is the pointer to the body // *dFloat* *omega - pointer to an array of at least three floats to hold the angular velocity vector. // // See also: NewtonBodySetOmega void NewtonBodyGetOmega(const NewtonBody* const bodyPtr, dFloat* const omega) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); // dgVector& vector = *((dgVector*) omega); // vector = body->GetOmega(); dgVector vector(body->GetOmega()); omega[0] = vector.m_x; omega[1] = vector.m_y; omega[2] = vector.m_z; } // Name: NewtonBodySetLinearDamping // Apply the linear viscous damping coefficient to the body. // // Parameters: // *const NewtonBody* *bodyPtr - is the pointer to the body. // *dFloat* linearDamp - linear damping coefficient. // // Remarks: the default value of *linearDamp* is clamped to a value between 0.0 and 1.0; the default value is 0.1, // There is a non zero implicit attenuation value of 0.0001 assume by the integrator. // // Remarks: The dampening viscous friction force is added to the external force applied to the body every frame before going to the solver-integrator. // This force is proportional to the square of the magnitude of the velocity to the body in the opposite direction of the velocity of the body. // An application can set *linearDamp* to zero when the application takes control of the external forces and torque applied to the body, should the application // desire to have absolute control of the forces over that body. However, it is recommended that the *linearDamp* coefficient is set to a non-zero // value for the majority of background bodies. This saves the application from having to control these forces and also prevents the integrator from // adding very large velocities to a body. // // See also: NewtonBodyGetLinearDamping void NewtonBodySetLinearDamping(const NewtonBody* const bodyPtr, dFloat linearDamp) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); body->SetLinearDamping(linearDamp); } // Name: NewtonBodyGetLinearDamping // Get the linear viscous damping of the body. // // Parameters: // *const NewtonBody* *bodyPtr - is the pointer to the body. // // Return: The linear damping coefficient. // // See also: NewtonBodySetLinearDamping dFloat NewtonBodyGetLinearDamping(const NewtonBody* const bodyPtr) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); return body->GetLinearDamping(); } // Name: NewtonBodySetAngularDamping // Apply the angular viscous damping coefficient to the body. // // Parameters: // *const NewtonBody* *bodyPtr - is the pointer to the body. // *dFloat* *angularDamp - pointer to an array of at least three floats containing the angular damping coefficients for the principal axis of the body. // // Remarks: the default value of *angularDamp* is clamped to a value between 0.0 and 1.0; the default value is 0.1, // There is a non zero implicit attenuation value of 0.0001 assumed by the integrator. // // Remarks: The dampening viscous friction torque is added to the external torque applied to the body every frame before going to the solver-integrator. // This torque is proportional to the square of the magnitude of the angular velocity to the body in the opposite direction of the angular velocity of the body. // An application can set *angularDamp* to zero when the to take control of the external forces and torque applied to the body, should the application // desire to have absolute control of the forces over that body. However, it is recommended that the *linearDamp* coefficient be set to a non-zero // value for the majority of background bodies. This saves the application from needing to control these forces and also prevents the integrator from // adding very large velocities to a body. // // See also: NewtonBodyGetAngularDamping void NewtonBodySetAngularDamping(const NewtonBody* const bodyPtr, const dFloat* angularDamp) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); dgVector vector(angularDamp[0], angularDamp[1], angularDamp[2], dgFloat32(0.0f)); body->SetAngularDamping(vector); } // Name: NewtonBodyGetAngularDamping // Get the linear viscous damping of the body. // // Parameters: // *const NewtonBody* *bodyPtr - is the pointer to the body. // *dFloat* *angularDamp - pointer to an array of at least three floats to hold the angular damping coefficient for the principal axis of the body. // // See also: NewtonBodySetAngularDamping void NewtonBodyGetAngularDamping(const NewtonBody* const bodyPtr, dFloat* angularDamp) { dgBody *body; body = (dgBody *) bodyPtr; TRACE_FUNTION(__FUNCTION__); // dgVector& vector = *((dgVector*) angularDamp); // vector = body->GetAngularDamping(); dgVector vector(body->GetAngularDamping()); angularDamp[0] = vector.m_x; angularDamp[1] = vector.m_y; angularDamp[2] = vector.m_z; } /* // Name: NewtonBodyForEachPolygonDo // Iterate thought polygon of the collision geometry of a body calling the function callback. // // Parameters: // *const NewtonBody* *bodyPtr - is the pointer to the body. // *NewtonCollisionIterator* callback - application define callback // // Return: nothing // // Remarks: This function can be called by the application in order to show the collision geometry. The application should provide a pointer to the function *NewtonCollisionIterator*, // Newton will convert the collision geometry into a polygonal mesh, and will call *callback* for every polygon of the mesh // // Remarks: this function affect severely the performance of Newton. The application should call this function only for debugging purpose // // Remarks: This function will ignore user define collision mesh // See also: NewtonWorldGetFirstBody, NewtonWorldForEachBodyInAABBDo, NewtonCollisionForEachPolygonDo void NewtonBodyForEachPolygonDo(const NewtonBody* const bodyPtr, NewtonCollisionIterator callback) { dgBody *body; void *saveCallBack; dgCollision *collision; dgCollisionPolygonalSoup *treeCollision; body = (dgBody *) bodyPtr; collision = body->GetCollision(); if (collision->IsType (dgCollision::dgCollisionPolygonalSoup_RTTI)) { treeCollision = (dgCollisionPolygonalSoup*) collision; saveCallBack = treeCollision->GetCallBack(); if (saveCallBack == NewtonCollisionTree::GetIntersectingPolygons) { treeCollision->SetCallBack ((void*)NewtonCollisionTree::IteratePolygonMesh); collision->DebugCollision (*body, (DebugCollisionMeshCallback) callback); treeCollision->SetCallBack (saveCallBack); } } else { collision->DebugCollision (*body, (DebugCollisionMeshCallback) callback); } } */ // Name: NewtonBodyAddImpulse // Add an impulse to a specific point on a body. // // Parameters: // *const NewtonWorld* *newtonWorld - pointer to the Newton world. // *const NewtonBody* *bodyPtr - is the pointer to the body. // *const dFloat* pointDeltaVeloc - pointer to an array of at least three floats containing the desired change in velocity to point pointPosit. // *const dFloat* pointPosit - pointer to an array of at least three floats containing the center of the impulse in global space. // // Return: Nothing. // // Remarks: This function will activate the body. // // Remarks: *pointPosit* and *pointDeltaVeloc* must be specified in global space. // // Remarks: *pointDeltaVeloc* represent a change in velocity. For example, a value of *pointDeltaVeloc* of (1, 0, 0) changes the velocity // of *bodyPtr* in such a way that the velocity of point *pointDeltaVeloc* will increase by (1, 0, 0) // // Remarks: Because *pointDeltaVeloc* represents a change in velocity, this function must be used with care. Repeated calls // to this function will result in an increase of the velocity of the body and may cause to integrator to lose stability. void NewtonBodyAddImpulse(const NewtonBody* const bodyPtr, const dFloat* const pointDeltaVeloc, const dFloat* const pointPosit) { dgBody *body; dgWorld *world; TRACE_FUNTION(__FUNCTION__); body = (dgBody *) bodyPtr; world = body->GetWorld(); dgVector p(pointPosit); dgVector v(pointDeltaVeloc); world->AddBodyImpulse(body, v, p); } // Name: NewtonBodyAddImpulse // Add an train of impulses to a specific point on a body. // // Parameters: // *const NewtonWorld* *newtonWorld - pointer to the Newton world. // *const NewtonBody* *bodyPtr - is the pointer to the body. // int impulseCount - number of impulses and distances in the array distance // int strideInByte - sized in bytes of vector impulse and // *const dFloat* impulseArray - pointer to an array containing the desired impulse to apply ate psoition pointarray. // *const dFloat* pointArray - pointer to an array of at least three floats containing the center of the impulse in global space. // // Return: Nothing. // // Remarks: This function will activate the body. // // Remarks: *pointPosit* and *pointDeltaVeloc* must be specified in global space. // // // Remarks: this function apply at general impulse to a body a oppose to a desired change on velocity // this mean that the body mass, and Inertia will determine the gain on velocity. void NewtonBodyApplyImpulseArray(const NewtonBody* const bodyPtr, int impuleCount, int strideInByte, const dFloat* const impulseArray, const dFloat* const pointArray) { dgBody *body; dgWorld *world; TRACE_FUNTION(__FUNCTION__); body = (dgBody *) bodyPtr; world = body->GetWorld(); world->ApplyImpulseArray(body, impuleCount, strideInByte, impulseArray, pointArray); } // *************************************************************************************************************** // // Name: Ball and Socket joint interface // // *************************************************************************************************************** // Name: NewtonConstraintCreateBall // Create a ball an socket joint. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *const NewtonCollision* *pivotPoint - is origin of ball and socket in global space. // *const NewtonBody* *childBody - is the pointer to the attached rigid body, this body can not be NULL or it can not have an infinity (zero) mass. // *const NewtonBody* *parentBody - is the pointer to the parent rigid body, this body can be NULL or any kind of rigid body. // // Return: Pointer to the ball and socket joint. // // Remarks: This function creates a ball and socket and add it to the world. By default joint disables collision with the linked bodies. NewtonJoint* NewtonConstraintCreateBall(const NewtonWorld* const newtonWorld, const dFloat* pivotPoint, const NewtonBody* const childBody, const NewtonBody* const parentBody) { dgBody *body0; dgBody *body1; Newton* world; TRACE_FUNTION(__FUNCTION__); world = (Newton *) newtonWorld; body0 = (dgBody *) childBody; body1 = (dgBody *) parentBody; dgVector pivot(pivotPoint[0], pivotPoint[1], pivotPoint[2], dgFloat32(0.0f)); return (NewtonJoint*) world->CreateBallConstraint(pivot, body0, body1); } // Name: NewtonBallSetConeLimits // Set the ball and socket cone and twist limits. // // Parameters: // *const NewtonJoint* *ball - is the pointer to a ball and socket joint. // *const NewtonCollision* *pin - pointer to a unit vector defining the cone axis in global space. // *const dFloat* maxConeAngle - max angle in radians the attached body is allow to swing relative to the pin axis, a value of zero will disable this limits. // *const dFloat* maxTwistAngle - max angle in radians the attached body is allow to twist relative to the pin axis, a value of zero will disable this limits. // // Remarks: limits are disabled at creation time. A value of zero for *maxConeAngle* disable the cone limit, a value of zero for *maxTwistAngle* disable the twist limit // all non-zero value for *maxConeAngle* are clamped between 5 degree and 175 degrees // // See also: NewtonConstraintCreateBall void NewtonBallSetConeLimits(const NewtonJoint* const ball, const dFloat* pin, dFloat maxConeAngle, dFloat maxTwistAngle) { dgBallConstraint* joint; TRACE_FUNTION(__FUNCTION__); joint = (dgBallConstraint*) ball; dgVector coneAxis(pin[0], pin[1], pin[2], dgFloat32(0.0f)); if ((coneAxis % coneAxis) < 1.0e-3f) { coneAxis.m_x = dgFloat32(1.0f); } dgVector tmp(dgFloat32(1.0f), dgFloat32(0.0f), dgFloat32(0.0f), dgFloat32(0.0f)); if (dgAbsf(tmp % coneAxis) > dgFloat32(0.999f)) { tmp = dgVector(dgFloat32(0.0f), dgFloat32(1.0f), dgFloat32(0.0f), dgFloat32(0.0f)); if (dgAbsf(tmp % coneAxis) > dgFloat32(0.999f)) { tmp = dgVector(dgFloat32(0.0f), dgFloat32(0.0f), dgFloat32(1.0f), dgFloat32(0.0f)); _ASSERTE(dgAbsf (tmp % coneAxis) < dgFloat32 (0.999f)); } } dgVector lateral(tmp * coneAxis); lateral = lateral.Scale(dgRsqrt (lateral % lateral)); coneAxis = coneAxis.Scale(dgRsqrt (coneAxis % coneAxis)); maxConeAngle = dgAbsf(maxConeAngle); maxTwistAngle = dgAbsf(maxTwistAngle); joint->SetConeLimitState((maxConeAngle > dgDEG2RAD) ? true : false); joint->SetTwistLimitState((maxTwistAngle > dgDEG2RAD) ? true : false); joint->SetLatealLimitState(false); joint->SetLimits(coneAxis, -maxConeAngle, maxConeAngle, maxTwistAngle, lateral, 0.0f, 0.0f); } // Name: NewtonBallSetUserCallback // Set an update call back to be called when either of the two bodies linked by the joint is active. // // Parameters: // *const NewtonJoint* *ball - pointer to the joint. // *NewtonBallCallBack* callback - pointer to the joint function call back. // // Return: nothing. // // Remarks: if the application wants to have some feedback from the joint simulation, the application can register a function // update callback to be called every time any of the bodies linked by this joint is active. This is useful to provide special // effects like particles, sound or even to simulate breakable moving parts. // // See also: NewtonJointSetUserData void NewtonBallSetUserCallback(const NewtonJoint* const ball, NewtonBallCallBack callback) { dgBallConstraint* contraint; TRACE_FUNTION(__FUNCTION__); contraint = (dgBallConstraint*) ball; contraint->SetJointParameterCallBack((dgBallJointFriction) callback); } // Name: NewtonBallGetJointAngle // Get the relative joint angle between the two bodies. // // Parameters: // *const NewtonJoint* *ball - pointer to the joint. // *dFloat* *angle - pointer to an array of a least three floats to hold the joint relative Euler angles. // // Return: nothing. // // Remarks: this function can be used during a function update call back to provide the application with some special effect. // for example the application can play a bell sound when the joint angle passes some max value. // // See also: NewtonBallSetUserCallback void NewtonBallGetJointAngle(const NewtonJoint* const ball, dFloat* angle) { dgBallConstraint* contraint; contraint = (dgBallConstraint*) ball; dgVector angleVector(contraint->GetJointAngle()); TRACE_FUNTION(__FUNCTION__); angle[0] = angleVector.m_x; angle[1] = angleVector.m_y; angle[2] = angleVector.m_z; } // Name: NewtonBallGetJointOmega // Get the relative joint angular velocity between the two bodies. // // Parameters: // *const NewtonJoint* *ball - pointer to the joint. // *dFloat* *omega - pointer to an array of a least three floats to hold the joint relative angular velocity. // // Return: nothing. // // Remarks: this function can be used during a function update call back to provide the application with some special effect. // for example the application can play the creaky noise of a hanging lamp. // // See also: NewtonBallSetUserCallback void NewtonBallGetJointOmega(const NewtonJoint* const ball, dFloat* omega) { dgBallConstraint* contraint; TRACE_FUNTION(__FUNCTION__); contraint = (dgBallConstraint*) ball; dgVector omegaVector(contraint->GetJointOmega()); omega[0] = omegaVector.m_x; omega[1] = omegaVector.m_y; omega[2] = omegaVector.m_z; } // Name: NewtonBallGetJointForce // Get the total force asserted over the joint pivot point, to maintain the constraint. // // Parameters: // *const NewtonJoint* *ball - pointer to the joint. // *dFloat* *force - pointer to an array of a least three floats to hold the force value of the joint. // // Return: nothing. // // Remarks: this function can be used during a function update call back to provide the application with some special effect. // for example the application can destroy the joint if the force exceeds some predefined value. // // See also: NewtonBallSetUserCallback void NewtonBallGetJointForce(const NewtonJoint* const ball, dFloat* const force) { dgBallConstraint* contraint; TRACE_FUNTION(__FUNCTION__); contraint = (dgBallConstraint*) ball; dgVector forceVector(contraint->GetJointForce()); force[0] = forceVector.m_x; force[1] = forceVector.m_y; force[2] = forceVector.m_z; } // *************************************************************************************************************** // // Name: Hinge joint interface // // *************************************************************************************************************** // Name: NewtonConstraintCreateHinge // Create a hinge joint. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *const dFloat* *pivotPoint - is origin of the hinge in global space. // *const dFloat* *pinDir - is the line of action of the hinge in global space. // *const NewtonBody* *childBody - is the pointer to the attached rigid body, this body can not be NULL or it can not have an infinity (zero) mass. // *const NewtonBody* *parentBody - is the pointer to the parent rigid body, this body can be NULL or any kind of rigid body. // // Return: Pointer to the hinge joint. // // Remarks: This function creates a hinge and add it to the world. By default joint disables collision with the linked bodies. NewtonJoint* NewtonConstraintCreateHinge(const NewtonWorld* const newtonWorld, const dFloat* pivotPoint, const dFloat* pinDir, const NewtonBody* const childBody, const NewtonBody* const parentBody) { dgBody *body0; dgBody *body1; Newton* world; TRACE_FUNTION(__FUNCTION__); world = (Newton *) newtonWorld; body0 = (dgBody *) childBody; body1 = (dgBody *) parentBody; dgVector pivot(pivotPoint[0], pivotPoint[1], pivotPoint[2], dgFloat32(0.0f)); dgVector pin(pinDir[0], pinDir[1], pinDir[2], dgFloat32(0.0f)); return (NewtonJoint*) world->CreateHingeConstraint(pivot, pin, body0, body1); } // Name: NewtonHingeSetUserCallback // Set an update call back to be called when either of the two body linked by the joint is active. // // Parameters: // *const NewtonJoint* *Hinge - pointer to the joint. // *NewtonHingeCallBack* callback - pointer to the joint function call back. // // Return: nothing. // // Remarks: if the application wants to have some feedback from the joint simulation, the application can register a function // update callback to be call every time any of the bodies linked by this joint is active. This is useful to provide special // effects like particles, sound or even to simulate breakable moving parts. // // See also: NewtonJointGetUserData, NewtonJointSetUserData void NewtonHingeSetUserCallback(const NewtonJoint* const hinge, NewtonHingeCallBack callback) { dgHingeConstraint* contraint; TRACE_FUNTION(__FUNCTION__); contraint = (dgHingeConstraint*) hinge; contraint->SetJointParameterCallBack((dgHingeJointAcceleration) callback); } // Name: NewtonHingeGetJointAngle // Get the relative joint angle between the two bodies. // // Parameters: // *const NewtonJoint* *Hinge - pointer to the joint. // // Return: the joint angle relative to the hinge pin. // // Remarks: this function can be used during a function update call back to provide the application with some special effect. // for example the application can play a bell sound when the joint angle passes some max value. // // See also: NewtonHingeSetUserCallback dFloat NewtonHingeGetJointAngle(const NewtonJoint* const hinge) { dgHingeConstraint* contraint; TRACE_FUNTION(__FUNCTION__); contraint = (dgHingeConstraint*) hinge; return contraint->GetJointAngle(); } // Name: NewtonHingeGetJointOmega // Get the relative joint angular velocity between the two bodies. // // Parameters: // *const NewtonJoint* *Hinge - pointer to the joint. // // Return: the joint angular velocity relative to the pin axis. // // Remarks: this function can be used during a function update call back to provide the application with some special effect. // for example the application can play the creaky noise of a hanging lamp. // // See also: NewtonHingeSetUserCallback dFloat NewtonHingeGetJointOmega(const NewtonJoint* const hinge) { dgHingeConstraint* contraint; TRACE_FUNTION(__FUNCTION__); contraint = (dgHingeConstraint*) hinge; return contraint->GetJointOmega(); } // Name: NewtonHingeGetJointForce // Calculate the angular acceleration needed to stop the hinge at the desired angle. // // Parameters: // *const NewtonJoint* *Hinge - pointer to the joint. // *NewtonHingeSliderUpdateDesc* *desc - is the pointer to and the Hinge or slide structure. // *dFloat* angle - is the desired hinge stop angle // // Return: the relative angular acceleration needed to stop the hinge. // // Remarks: this function can only be called from a *NewtonHingeCallBack* and it can be used by the application to implement hinge limits. // // See also: NewtonHingeSetUserCallback dFloat NewtonHingeCalculateStopAlpha(const NewtonJoint* const hinge, const NewtonHingeSliderUpdateDesc* const desc, dFloat angle) { dgHingeConstraint* contraint; TRACE_FUNTION(__FUNCTION__); contraint = (dgHingeConstraint*) hinge; return contraint->CalculateStopAlpha(angle, (dgJointCallBackParam*) desc); } // Name: NewtonHingeGetJointForce // Get the total force asserted over the joint pivot point, to maintain the constraint. // // Parameters: // *const NewtonJoint* *Hinge - pointer to the joint. // *dFloat* *force - pointer to an array of a least three floats to hold the force value of the joint. // // Return: nothing. // // Remarks: this function can be used during a function update call back to provide the application with some special effect. // for example the application can destroy the joint if the force exceeds some predefined value. // // See also: NewtonHingeSetUserCallback void NewtonHingeGetJointForce(const NewtonJoint* const hinge, dFloat* const force) { dgHingeConstraint* contraint; TRACE_FUNTION(__FUNCTION__); contraint = (dgHingeConstraint*) hinge; dgVector forceVector(contraint->GetJointForce()); force[0] = forceVector.m_x; force[1] = forceVector.m_y; force[2] = forceVector.m_z; } // *************************************************************************************************************** // // Name: Slider joint interface // // *************************************************************************************************************** // Name: NewtonConstraintCreateSlider // Create a slider joint. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *const dFloat* *pivotPoint - is origin of the slider in global space. // *const dFloat* *pinDir - is the line of action of the slider in global space. // *const NewtonBody* *childBody - is the pointer to the attached rigid body, this body can not be NULL or it can not have an infinity (zero) mass. // *const NewtonBody* *parentBody - is the pointer to the parent rigid body, this body can be NULL or any kind of rigid body. // // Return: Pointer to the slider joint. // // Remarks: This function creates a slider and add it to the world. By default joint disables collision with the linked bodies. NewtonJoint* NewtonConstraintCreateSlider(const NewtonWorld* const newtonWorld, const dFloat* pivotPoint, const dFloat* pinDir, const NewtonBody* const childBody, const NewtonBody* const parentBody) { dgBody *body0; dgBody *body1; Newton* world; TRACE_FUNTION(__FUNCTION__); world = (Newton *) newtonWorld; body0 = (dgBody *) childBody; body1 = (dgBody *) parentBody; dgVector pin(pinDir[0], pinDir[1], pinDir[2], dgFloat32(0.0f)); dgVector pivot(pivotPoint[0], pivotPoint[1], pivotPoint[2], dgFloat32(0.0f)); return (NewtonJoint*) world->CreateSlidingConstraint(pivot, pin, body0, body1); } // Name: NewtonSliderSetUserCallback // Set an update call back to be called when either of the two body linked by the joint is active. // // Parameters: // *const NewtonJoint* *Slider - pointer to the joint. // *NewtonSliderCallBack* callback - pointer to the joint function call back. // // Return: nothing. // // Remarks: if the application wants to have some feedback from the joint simulation, the application can register a function // update callback to be call every time any of the bodies linked by this joint is active. This is useful to provide special // effects like particles, sound or even to simulate breakable moving parts. // // See also: NewtonJointGetUserData, NewtonJointSetUserData void NewtonSliderSetUserCallback(const NewtonJoint* const slider, NewtonSliderCallBack callback) { dgSlidingConstraint* contraint; TRACE_FUNTION(__FUNCTION__); contraint = (dgSlidingConstraint*) slider; contraint->SetJointParameterCallBack((dgSlidingJointAcceleration) callback); } // Name: NewtonSliderGetJointPosit // Get the relative joint angle between the two bodies. // // Parameters: // *const NewtonJoint* *Slider - pointer to the joint. // // Return: the joint angle relative to the hinge pin. // // Remarks: this function can be used during a function update call back to provide the application with some special effect. // for example the application can play a bell sound when the joint angle passes some max value. // // See also: NewtonSliderSetUserCallback dFloat NewtonSliderGetJointPosit(const NewtonJoint* Slider) { dgSlidingConstraint* contraint; TRACE_FUNTION(__FUNCTION__); contraint = (dgSlidingConstraint*) Slider; return contraint->GetJointPosit(); } // Name: NewtonSliderGetJointVeloc // Get the relative joint angular velocity between the two bodies. // // Parameters: // *const NewtonJoint* *Slider - pointer to the joint. // // Return: the joint angular velocity relative to the pin axis. // // Remarks: this function can be used during a function update call back to provide the application with some special effect. // for example the application can play the creaky noise of a hanging lamp. // // See also: NewtonSliderSetUserCallback dFloat NewtonSliderGetJointVeloc(const NewtonJoint* Slider) { dgSlidingConstraint* contraint; TRACE_FUNTION(__FUNCTION__); contraint = (dgSlidingConstraint*) Slider; return contraint->GetJointVeloc(); } // Name: NewtonSliderGetJointForce // Calculate the angular acceleration needed to stop the slider at the desired angle. // // Parameters: // *const NewtonJoint* *slider - pointer to the joint. // *NewtonSliderSliderUpdateDesc* *desc - is the pointer to the Slider or slide structure. // *dFloat* distance - desired stop distance relative to the pivot point // // Return: the relative linear acceleration needed to stop the slider. // // Remarks: this function can only be called from a *NewtonSliderCallBack* and it can be used by the application to implement slider limits. // // See also: NewtonSliderSetUserCallback dFloat NewtonSliderCalculateStopAccel(const NewtonJoint* const slider, const NewtonHingeSliderUpdateDesc* const desc, dFloat distance) { dgSlidingConstraint* contraint; TRACE_FUNTION(__FUNCTION__); contraint = (dgSlidingConstraint*) slider; return contraint->CalculateStopAccel(distance, (dgJointCallBackParam*) desc); } // Name: NewtonSliderGetJointForce // Get the total force asserted over the joint pivot point, to maintain the constraint. // // Parameters: // *const NewtonJoint* *Slider - pointer to the joint. // *dFloat* *force - pointer to an array of a least three floats to hold the force value of the joint. // // Return: nothing. // // Remarks: this function can be used during a function update call back to provide the application with some special effect. // for example the application can destroy the joint if the force exceeds some predefined value. // // See also: NewtonSliderSetUserCallback void NewtonSliderGetJointForce(const NewtonJoint* const slider, dFloat* const force) { dgSlidingConstraint* contraint; TRACE_FUNTION(__FUNCTION__); contraint = (dgSlidingConstraint*) slider; dgVector forceVector(contraint->GetJointForce()); force[0] = forceVector.m_x; force[1] = forceVector.m_y; force[2] = forceVector.m_z; } // *************************************************************************************************************** // // Name: Corkscrew joint interface // // *************************************************************************************************************** // Name: NewtonConstraintCreateCorkscrew // Create a corkscrew joint. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *const dFloat* *pivotPoint - is origin of the corkscrew in global space. // *const dFloat* *pinDir - is the line of action of the corkscrew in global space. // *const NewtonBody* *childBody - is the pointer to the attached rigid body, this body can not be NULL or it can not have an infinity (zero) mass. // *const NewtonBody* *parentBody - is the pointer to the parent rigid body, this body can be NULL or any kind of rigid body. // // Return: Pointer to the corkscrew joint. // // Remarks: This function creates a corkscrew and add it to the world. By default joint disables collision with the linked bodies. NewtonJoint* NewtonConstraintCreateCorkscrew( const NewtonWorld* const newtonWorld, const dFloat* pivotPoint, const dFloat* pinDir, const NewtonBody* const childBody, const NewtonBody* const parentBody) { dgBody *body0; dgBody *body1; Newton* world; TRACE_FUNTION(__FUNCTION__); world = (Newton *) newtonWorld; body0 = (dgBody *) childBody; body1 = (dgBody *) parentBody; dgVector pin(pinDir[0], pinDir[1], pinDir[2], dgFloat32(0.0f)); dgVector pivot(pivotPoint[0], pivotPoint[1], pivotPoint[2], dgFloat32(0.0f)); return (NewtonJoint*) world->CreateCorkscrewConstraint(pivot, pin, body0, body1); } // Name: NewtonCorkscrewSetUserCallback // Set an update call back to be called when either of the two body linked by the joint is active. // // Parameters: // *const NewtonJoint* *Corkscrew - pointer to the joint. // *NewtonCorkscrewCallBack* callback - pointer to the joint function call back. // // Return: nothing. // // Remarks: if the application wants to have some feedback from the joint simulation, the application can register a function // update callback to be call every time any of the bodies linked by this joint is active. This is useful to provide special // effects like particles, sound or even to simulate breakable moving parts. // // Remarks: the function *NewtonCorkscrewCallBack callback* should return a bit field code. // if the application does not want to set the joint acceleration the return code is zero // if the application only wants to change the joint linear acceleration the return code is 1 // if the application only wants to change the joint angular acceleration the return code is 2 // if the application only wants to change the joint angular and linear acceleration the return code is 3 // // See also: NewtonJointGetUserData, NewtonJointSetUserData void NewtonCorkscrewSetUserCallback(const NewtonJoint* const corkscrew, NewtonCorkscrewCallBack callback) { dgCorkscrewConstraint* contraint; TRACE_FUNTION(__FUNCTION__); contraint = (dgCorkscrewConstraint*) corkscrew; contraint->SetJointParameterCallBack((dgCorkscrewJointAcceleration) callback); } // Name: NewtonCorkscrewGetJointPosit // Get the relative joint angle between the two bodies. // // Parameters: // *const NewtonJoint* *Corkscrew - pointer to the joint. // // Return: the joint angle relative to the hinge pin. // // Remarks: this function can be used during a function update call back to provide the application with some special effect. // for example the application can play a bell sound when the joint angle passes some max value. // // See also: NewtonCorkscrewSetUserCallback dFloat NewtonCorkscrewGetJointPosit(const NewtonJoint* const corkscrew) { dgCorkscrewConstraint* contraint; TRACE_FUNTION(__FUNCTION__); contraint = (dgCorkscrewConstraint*) corkscrew; return contraint->GetJointPosit(); } // Name: NewtonCorkscrewGetJointVeloc // Get the relative joint angular velocity between the two bodies. // // Parameters: // *const NewtonJoint* *Corkscrew - pointer to the joint. // // Return: the joint angular velocity relative to the pin axis. // // Remarks: this function can be used during a function update call back to provide the application with some special effect. // for example the application can play the creaky noise of a hanging lamp. // // See also: NewtonCorkscrewSetUserCallback dFloat NewtonCorkscrewGetJointVeloc(const NewtonJoint* const corkscrew) { dgCorkscrewConstraint* contraint; TRACE_FUNTION(__FUNCTION__); contraint = (dgCorkscrewConstraint*) corkscrew; return contraint->GetJointVeloc(); } // Name: NewtonCorkscrewGetJointAngle // Get the relative joint angle between the two bodies. // // Parameters: // *const NewtonJoint* *Corkscrew - pointer to the joint. // // Return: the joint angle relative to the corkscrew pin. // // Remarks: this function can be used during a function update call back to provide the application with some special effect. // for example the application can play a bell sound when the joint angle passes some max value. // // See also: NewtonCorkscrewSetUserCallback dFloat NewtonCorkscrewGetJointAngle(const NewtonJoint* const corkscrew) { dgCorkscrewConstraint* contraint; TRACE_FUNTION(__FUNCTION__); contraint = (dgCorkscrewConstraint*) corkscrew; return contraint->GetJointAngle(); } // Name: NewtonCorkscrewGetJointOmega // Get the relative joint angular velocity between the two bodies. // // Parameters: // *const NewtonJoint* *Corkscrew - pointer to the joint. // // Return: the joint angular velocity relative to the pin axis. // // Remarks: this function can be used during a function update call back to provide the application with some special effect. // for example the application can play the creaky noise of a hanging lamp. // // See also: NewtonCorkscrewSetUserCallback dFloat NewtonCorkscrewGetJointOmega(const NewtonJoint* const corkscrew) { dgCorkscrewConstraint* contraint; TRACE_FUNTION(__FUNCTION__); contraint = (dgCorkscrewConstraint*) corkscrew; return contraint->GetJointOmega(); } // Name: NewtonCorkscrewCalculateStopAlpha // Calculate the angular acceleration needed to stop the corkscrew at the desired angle. // // Parameters: // *const NewtonJoint* *Corkscrew - pointer to the joint. // *NewtonCorkscrewSliderUpdateDesc* *desc - is the pointer to the Corkscrew or slide structure. // *dFloat* angle - is the desired corkscrew stop angle // // Return: the relative angular acceleration needed to stop the corkscrew. // // Remarks: this function can only be called from a *NewtonCorkscrewCallBack* and it can be used by the application to implement corkscrew limits. // // See also: NewtonCorkscrewSetUserCallback dFloat NewtonCorkscrewCalculateStopAlpha(const NewtonJoint* const corkscrew, const NewtonHingeSliderUpdateDesc* const desc, dFloat angle) { dgCorkscrewConstraint* contraint; TRACE_FUNTION(__FUNCTION__); contraint = (dgCorkscrewConstraint*) corkscrew; return contraint->CalculateStopAlpha(angle, (dgJointCallBackParam*) desc); } // Name: NewtonCorkscrewGetJointForce // Calculate the angular acceleration needed to stop the corkscrew at the desired angle. // // Parameters: // *const NewtonJoint* *corkscrew - pointer to the joint. // *NewtonCorkscrewCorkscrewUpdateDesc* *desc - is the pointer to the Corkscrew or slide structure. // *dFloat* distance - desired stop distance relative to the pivot point // // Return: the relative linear acceleration needed to stop the corkscrew. // // Remarks: this function can only be called from a *NewtonCorkscrewCallBack* and it can be used by the application to implement corkscrew limits. // // See also: NewtonCorkscrewSetUserCallback dFloat NewtonCorkscrewCalculateStopAccel(const NewtonJoint* const corkscrew, const NewtonHingeSliderUpdateDesc* const desc, dFloat distance) { dgCorkscrewConstraint* contraint; contraint = (dgCorkscrewConstraint*) corkscrew; return contraint->CalculateStopAccel(distance, (dgJointCallBackParam*) desc); } // Name: NewtonCorkscrewGetJointForce // Get the total force asserted over the joint pivot point, to maintain the constraint. // // Parameters: // *const NewtonJoint* *Corkscrew - pointer to the joint. // *dFloat* *force - pointer to an array of a least three floats to hold the force value of the joint. // // Return: nothing. // // Remarks: this function can be used during a function update call back to provide the application with some special effect. // for example the application can destroy the joint if the force exceeds some predefined value. // // See also: NewtonCorkscrewSetUserCallback void NewtonCorkscrewGetJointForce(const NewtonJoint* const corkscrew, dFloat* const force) { dgCorkscrewConstraint* contraint; TRACE_FUNTION(__FUNCTION__); contraint = (dgCorkscrewConstraint*) corkscrew; dgVector forceVector(contraint->GetJointForce()); force[0] = forceVector.m_x; force[1] = forceVector.m_y; force[2] = forceVector.m_z; } // *************************************************************************************************************** // // Name: Universal joint interface // // *************************************************************************************************************** // Name: NewtonConstraintCreateUniversal // Create a universal joint. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *const dFloat* *pivotPoint - is origin of the universal joint in global space. // *const dFloat* *pinDir0 - first axis of rotation fixed on childBody body and perpendicular to pinDir1. // *const dFloat* *pinDir1 - second axis of rotation fixed on parentBody body and perpendicular to pinDir0. // *const NewtonBody* *childBody - is the pointer to the attached rigid body, this body can not be NULL or it can not have an infinity (zero) mass. // *const NewtonBody* *parentBody - is the pointer to the parent rigid body, this body can be NULL or any kind of rigid body. // // Return: Pointer to the universal joint. // // Remarks: This function creates a universal joint and add it to the world. By default joint disables collision with the linked bodies. // // Remark: a universal joint is a constraint that restricts twp rigid bodies to be connected to a point fixed on both bodies, // while and allowing one body to spin around a fix axis in is own frame, and the other body to spin around another axis fixes on // it own frame. Both axis must be mutually perpendicular. NewtonJoint* NewtonConstraintCreateUniversal( const NewtonWorld* const newtonWorld, const dFloat* pivotPoint, const dFloat* pinDir0, const dFloat* pinDir1, const NewtonBody* const childBody, const NewtonBody* const parentBody) { dgBody *body0; dgBody *body1; Newton* world; TRACE_FUNTION(__FUNCTION__); world = (Newton *) newtonWorld; body0 = (dgBody *) childBody; body1 = (dgBody *) parentBody; dgVector pin0(pinDir0[0], pinDir0[1], pinDir0[2], dgFloat32(0.0f)); dgVector pin1(pinDir1[0], pinDir1[1], pinDir1[2], dgFloat32(0.0f)); dgVector pivot(pivotPoint[0], pivotPoint[1], pivotPoint[2], dgFloat32(0.0f)); return (NewtonJoint*) world->CreateUniversalConstraint(pivot, pin0, pin1, body0, body1); } // Name: NewtonUniversalSetUserCallback // Set an update call back to be called when either of the two body linked by the joint is active. // // Parameters: // *const NewtonJoint* *Universal - pointer to the joint. // *NewtonUniversalCallBack* callback - pointer to the joint function call back. // // Return: nothing. // // Remarks: if the application wants to have some feedback from the joint simulation, the application can register a function // update callback to be called every time any of the bodies linked by this joint is active. This is useful to provide special // effects like particles, sound or even to simulate breakable moving parts. // // Remarks: the function *NewtonUniversalCallBack callback* should return a bit field code. // if the application does not want to set the joint acceleration the return code is zero // if the application only wants to change the joint linear acceleration the return code is 1 // if the application only wants to change the joint angular acceleration the return code is 2 // if the application only wants to change the joint angular and linear acceleration the return code is 3 // // See also: NewtonJointGetUserData, NewtonJointSetUserData void NewtonUniversalSetUserCallback(const NewtonJoint* const universal, NewtonUniversalCallBack callback) { dgUniversalConstraint* contraint; TRACE_FUNTION(__FUNCTION__); contraint = (dgUniversalConstraint*) universal; contraint->SetJointParameterCallBack((dgUniversalJointAcceleration) callback); } // Name: NewtonUniversalGetJointAngle0 // Get the relative joint angle between the two bodies. // // Parameters: // *const NewtonJoint* *Universal - pointer to the joint. // // Return: the joint angle relative to the universal pin0. // // Remarks: this function can be used during a function update call back to provide the application with some special effect. // for example the application can play a bell sound when the joint angle passes some max value. // // See also: NewtonUniversalSetUserCallback dFloat NewtonUniversalGetJointAngle0(const NewtonJoint* const universal) { dgUniversalConstraint* contraint; TRACE_FUNTION(__FUNCTION__); contraint = (dgUniversalConstraint*) universal; return contraint->GetJointAngle0(); } // Name: NewtonUniversalGetJointAngle1 // Get the relative joint angle between the two bodies. // // Parameters: // *const NewtonJoint* *Universal - pointer to the joint. // // Return: the joint angle relative to the universal pin1. // // Remarks: this function can be used during a function update call back to provide the application with some special effect. // for example the application can play a bell sound when the joint angle passes some max value. // // See also: NewtonUniversalSetUserCallback dFloat NewtonUniversalGetJointAngle1(const NewtonJoint* const universal) { dgUniversalConstraint* contraint; TRACE_FUNTION(__FUNCTION__); contraint = (dgUniversalConstraint*) universal; return contraint->GetJointAngle1(); } // Name: NewtonUniversalGetJointOmega0 // Get the relative joint angular velocity between the two bodies. // // Parameters: // *const NewtonJoint* *Universal - pointer to the joint. // // Return: the joint angular velocity relative to the pin0 axis. // // Remarks: this function can be used during a function update call back to provide the application with some special effect. // for example the application can play the creaky noise of a hanging lamp. // // See also: NewtonUniversalSetUserCallback dFloat NewtonUniversalGetJointOmega0(const NewtonJoint* const universal) { dgUniversalConstraint* contraint; TRACE_FUNTION(__FUNCTION__); contraint = (dgUniversalConstraint*) universal; return contraint->GetJointOmega0(); } // Name: NewtonUniversalGetJointOmega1 // Get the relative joint angular velocity between the two bodies. // // Parameters: // *const NewtonJoint* *Universal - pointer to the joint. // // Return: the joint angular velocity relative to the pin1 axis. // // Remarks: this function can be used during a function update call back to provide the application with some special effect. // for example the application can play the creaky noise of a hanging lamp. // // See also: NewtonUniversalSetUserCallback dFloat NewtonUniversalGetJointOmega1(const NewtonJoint* const universal) { dgUniversalConstraint* contraint; TRACE_FUNTION(__FUNCTION__); contraint = (dgUniversalConstraint*) universal; return contraint->GetJointOmega1(); } // Name: NewtonUniversalCalculateStopAlpha0 // Calculate the angular acceleration needed to stop the universal at the desired angle. // // Parameters: // *const NewtonJoint* *Universal - pointer to the joint. // *NewtonUniversalSliderUpdateDesc* *desc - is the pointer to the Universal or slide structure. // *dFloat* angle - is the desired universal stop angle rotation around pin0 // // Return: the relative angular acceleration needed to stop the universal. // // Remarks: this function can only be called from a *NewtonUniversalCallBack* and it can be used by the application to implement universal limits. // // See also: NewtonUniversalSetUserCallback dFloat NewtonUniversalCalculateStopAlpha0(const NewtonJoint* const universal, const NewtonHingeSliderUpdateDesc* const desc, dFloat angle) { dgUniversalConstraint* contraint; TRACE_FUNTION(__FUNCTION__); contraint = (dgUniversalConstraint*) universal; return contraint->CalculateStopAlpha0(angle, (dgJointCallBackParam*) desc); } // Name: NewtonUniversalCalculateStopAlpha1 // Calculate the angular acceleration needed to stop the universal at the desired angle. // // Parameters: // *const NewtonJoint* *Universal - pointer to the joint. // *NewtonUniversalSliderUpdateDesc* *desc - is the pointer to and the Universal or slide structure. // *dFloat* angle - is the desired universal stop angle rotation around pin1 // // Return: the relative angular acceleration needed to stop the universal. // // Remarks: this function can only be called from a *NewtonUniversalCallBack* and it can be used by the application to implement universal limits. // // See also: NewtonUniversalSetUserCallback dFloat NewtonUniversalCalculateStopAlpha1(const NewtonJoint* const universal, const NewtonHingeSliderUpdateDesc* const desc, dFloat angle) { dgUniversalConstraint* contraint; TRACE_FUNTION(__FUNCTION__); contraint = (dgUniversalConstraint*) universal; return contraint->CalculateStopAlpha1(angle, (dgJointCallBackParam*) desc); } // Name: NewtonUniversalGetJointForce // Get the total force asserted over the joint pivot point, to maintain the constraint. // // Parameters: // *const NewtonJoint* *Universal - pointer to the joint. // *dFloat* *force - pointer to an array of a least three floats to hold the force value of the joint. // // Return: nothing. // // Remarks: this function can be used during a function update call back to provide the application with some special effect. // for example the application can destroy the joint if the force exceeds some predefined value. // // See also: NewtonUniversalSetUserCallback void NewtonUniversalGetJointForce(const NewtonJoint* const universal, dFloat* const force) { dgUniversalConstraint* contraint; TRACE_FUNTION(__FUNCTION__); contraint = (dgUniversalConstraint*) universal; dgVector forceVector(contraint->GetJointForce()); force[0] = forceVector.m_x; force[1] = forceVector.m_y; force[2] = forceVector.m_z; } // *************************************************************************************************************** // // Name: UpVector joint Interface // // *************************************************************************************************************** // Name: NewtonConstraintCreateUpVector // Create a UpVector joint. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *const dFloat* *pinDir - is the aligning vector. // *const NewtonBody* *body - is the pointer to the attached rigid body, this body can not be NULL or it can not have an infinity (zero) mass. // // Return: Pointer to the up vector joint. // // Remarks: This function creates an up vector joint. An up vector joint is a constraint that allows a body to translate freely in 3d space, // but it only allows the body to rotate around the pin direction vector. This could be use by the application to control a character // with physics and collision. // // Remark: Since the UpVector joint is a unary constraint, there is not need to have user callback or user data assigned to it. // The application can simple hold to the joint handle and update the pin on the force callback function of the rigid body owning the joint. NewtonJoint* NewtonConstraintCreateUpVector( const NewtonWorld* const newtonWorld, const dFloat* pinDir, const NewtonBody* const body) { dgBody *body0; Newton* world; TRACE_FUNTION(__FUNCTION__); world = (Newton *) newtonWorld; body0 = (dgBody *) body; dgVector pin(pinDir[0], pinDir[1], pinDir[2], dgFloat32(0.0f)); return (NewtonJoint*) world->CreateUpVectorConstraint(pin, body0); } // Name: NewtonUpVectorGetPin // Get the up vector pin of this joint in global space. // // Parameters: // *const NewtonJoint* *upVector - pointer to the joint. // *dFloat* *pin - pointer to an array of a least three floats to hold the up vector direction in global space. // // Return: nothing. // // Remarks: the application ca call this function to read the up vector, this is useful to animate the up vector. // if the application is going to animated the up vector, it must do so by applying only small rotation, // too large rotation can cause vibration of the joint. // // See also: NewtonUpVectorSetUserCallback, NewtonUpVectorSetPin void NewtonUpVectorGetPin(const NewtonJoint* const upVector, dFloat *pin) { dgUpVectorConstraint* contraint; TRACE_FUNTION(__FUNCTION__); contraint = (dgUpVectorConstraint*) upVector; dgVector pinVector(contraint->GetPinDir()); pin[0] = pinVector.m_x; pin[1] = pinVector.m_y; pin[2] = pinVector.m_z; } // Name: NewtonUpVectorSetPin // Set the up vector pin of this joint in global space. // // Parameters: // *const NewtonJoint* *upVector - pointer to the joint. // *dFloat* *pin - pointer to an array of a least three floats containing the up vector direction in global space. // // Return: nothing. // // Remarks: the application ca call this function to change the joint up vector, this is useful to animate the up vector. // if the application is going to animated the up vector, it must do so by applying only small rotation, // too large rotation can cause vibration of the joint. // // See also: NewtonUpVectorSetUserCallback, NewtonUpVectorGetPin void NewtonUpVectorSetPin(const NewtonJoint* const upVector, const dFloat *pin) { dgUpVectorConstraint* contraint; TRACE_FUNTION(__FUNCTION__); contraint = (dgUpVectorConstraint*) upVector; dgVector pinVector(pin[0], pin[1], pin[2], dgFloat32(0.0f)); contraint->SetPinDir(pinVector); } // *************************************************************************************************************** // // Name: User defined joint interface // // *************************************************************************************************************** // Name: NewtonConstraintCreateUserJoint // Create a user define bilateral joint. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *in*t maxDOF - is the maximum number of degree of freedom controlled by this joint. // *NewtonUserBilateralCallBack* submitConstraints - pointer to the joint constraint definition function call back. // *NewtonUserBilateralGetInfoCallBack* getInfo - pointer to callback for collecting joint information. // *const NewtonBody* *childBody - is the pointer to the attached rigid body, this body can not be NULL or it can not have an infinity (zero) mass. // *const NewtonBody* *parentBody - is the pointer to the parent rigid body, this body can be NULL or any kind of rigid body. // // Remark: Bilateral joint are constraints that can have up to 6 degree of freedoms, 3 linear and 3 angular. // By restricting the motion along any number of these degree of freedom a very large number of useful joint between // two rigid bodies can be accomplished. Some of the degree of freedoms restriction makes no sense, and also some // combinations are so rare that only make sense to a very specific application, the Newton engine implements the more // commons combinations like, hinges, ball and socket, etc. However if and application is in the situation that any of // the provided joints can achieve the desired effect, then the application can design it own joint. // // Remark: User defined joint is a very advance feature that should be look at, only for very especial situations. // The designer must be a person with a very good understanding of constrained dynamics, and it may be the case // that many trial have to be made before a good result can be accomplished. // // Remark: function *submitConstraints* is called before the solver state to get the jacobian derivatives and the righ hand acceleration // for the definition of the constraint. // // Remark: maxDOF is and upper bound as to how many degrees of freedoms the joint can control, usually this value // can be 6 for bilateral joints, but it can be higher for special joints like vehicles where by the used of friction clamping // the number of rows can be higher. // In general the application should determine maxDof correctly, passing an unnecessary excessive value will lead to performance decreased. // // See also: NewtonUserJointSetFeedbackCollectorCallback NewtonJoint* NewtonConstraintCreateUserJoint( const NewtonWorld* const newtonWorld, int maxDOF, NewtonUserBilateralCallBack submitConstraints, NewtonUserBilateralGetInfoCallBack getInfo, const NewtonBody* const childBody, const NewtonBody* const parentBody) { dgBody *body0; dgBody *body1; Newton* world; TRACE_FUNTION(__FUNCTION__); world = (Newton *) newtonWorld; body0 = (dgBody *) childBody; body1 = (dgBody *) parentBody; return (NewtonJoint*) new (world->dgWorld::GetAllocator()) NewtonUserJoint( world, maxDOF, submitConstraints, getInfo, body0, body1); } // Name: NewtonUserJointAddLinearRow // Add a linear restricted degree of freedom. // // Parameters: // *const NewtonJoint* *joint - pointer to the joint. // *const dFloat* *pivot0 - pointer of a vector in global space fixed on body zero. // *const dFloat* *pivot1 - pointer of a vector in global space fixed on body one. // *const dFloat* *pin - pointer of a unit vector in global space along which the relative position, velocity and acceleration between the bodies will be driven to zero. // // Remark: A linear constraint row calculates the Jacobian derivatives and relative acceleration required to enforce the constraint condition at // the attachment point and the pin direction considered fixed to both bodies. // // Remark: The acceleration is calculated such that the relative linear motion between the two points is zero, the application can // afterward override this value to create motors. // // Remark: after this function is call and internal DOF index will point to the current row entry in the constraint matrix. // // Remark: This function call only be called from inside a *NewtonUserBilateralCallBack* callback. // // See also: NewtonUserJointAddAngularRow, void NewtonUserJointAddLinearRow(const NewtonJoint* const joint, const dFloat* const pivot0, const dFloat* const pivot1, const dFloat* const dir) { NewtonUserJoint* userJoint; userJoint = (NewtonUserJoint*) joint; TRACE_FUNTION(__FUNCTION__); dgVector direction(dir[0], dir[1], dir[2], dgFloat32(0.0f)); direction = direction.Scale(dgRsqrt (direction % direction)); _ASSERTE( dgAbsf (direction % direction - dgFloat32 (1.0f)) < dgFloat32 (1.0e-2f)); dgVector pivotPoint0(pivot0[0], pivot0[1], pivot0[2], dgFloat32(0.0f)); dgVector pivotPoint1(pivot1[0], pivot1[1], pivot1[2], dgFloat32(0.0f)); userJoint->AddLinearRowJacobian(pivotPoint0, pivotPoint1, direction); } // Name: NewtonUserJointAddAngularRow // Add an angular restricted degree of freedom. // // Parameters: // *const NewtonJoint* *joint - pointer to the joint. // *dFloat* relativeAngleError - relative angle error between both bodies around pin axis. // *const dFloat* *pin - pointer of a unit vector in global space along which the relative position, velocity and acceleration between the bodies will be driven to zero. // // Remark: An angular constraint row calculates the Jacobian derivatives and relative acceleration required to enforce the constraint condition at // pin direction considered fixed to both bodies. // // Remark: The acceleration is calculated such that the relative angular motion between the two points is zero, The application can // afterward override this value to create motors. // // Remark: After this function is called and internal DOF index will point to the current row entry in the constraint matrix. // // Remark: This function call only be called from inside a *NewtonUserBilateralCallBack* callback. // // Remark: This function is of not practical to enforce hard constraints, but it is very useful for making angular motors. // // See also: NewtonUserJointAddLinearRow, NewtonUserJointAddIndependentAngularRow void NewtonUserJointAddAngularRow(const NewtonJoint* const joint, dFloat relativeAngleError, const dFloat* const pin) { NewtonUserJoint* userJoint; TRACE_FUNTION(__FUNCTION__); userJoint = (NewtonUserJoint*) joint; dgVector direction(pin[0], pin[1], pin[2], dgFloat32(0.0f)); direction = direction.Scale(dgRsqrt (direction % direction)); _ASSERTE( dgAbsf (direction % direction - dgFloat32 (1.0f)) < dgFloat32 (1.0e-3f)); userJoint->AddAngularRowJacobian(direction, relativeAngleError); } // Name: NewtonUserJointAddGeneralRow // set the general linear and angular Jacobian for the desired degree of freedom // // Parameters: // *const NewtonJoint* *joint - pointer to the joint. // *const dFloat* *jacobian0 - pointer of a set of six values defining the linear and angular Jacobian for body0. // *const dFloat* *jacobian1 - pointer of a set of six values defining the linear and angular Jacobian for body1. // // Remark: In general this function must be used for very special effects and in combination with other joints. // it is expected that the user have a knowledge of Constrained dynamics to make a good used of this function. // Must typical application of this function are the creation of synchronization or control joints like gears, pulleys, // worm gear and some other mechanical control. // // Remark: this function set the relative acceleration for this degree of freedom to zero. It is the // application responsibility to set the relative acceleration after a call to this function // // See also: NewtonUserJointAddLinearRow, NewtonUserJointAddAngularRow void NewtonUserJointAddGeneralRow(const NewtonJoint* const joint, const dFloat* const jacobian0, const dFloat* const jacobian1) { NewtonUserJoint* userJoint; TRACE_FUNTION(__FUNCTION__); userJoint = (NewtonUserJoint*) joint; userJoint->AddGeneralRowJacobian(jacobian0, jacobian1); } // Name: NewtonUserJointSetRowMaximumFriction // Set the maximum friction value the solver is allow to apply to the joint row. // // Parameters: // *const NewtonJoint* *joint - pointer to the joint. // *dFloat* friction - maximum friction value for this row. It must be a positive value between 0.0 and INFINITY. // // Remark: This function will override the default friction values set after a call to NewtonUserJointAddLinearRow or NewtonUserJointAddAngularRow. // friction value is context sensitive, if for linear constraint friction is a Max friction force, for angular constraint friction is a // max friction is a Max friction torque. // // See also: NewtonUserJointSetRowMinimumFriction, NewtonUserJointAddLinearRow, NewtonUserJointAddAngularRow void NewtonUserJointSetRowMaximumFriction(const NewtonJoint* const joint, dFloat friction) { NewtonUserJoint* userJoint; userJoint = (NewtonUserJoint*) joint; TRACE_FUNTION(__FUNCTION__); userJoint->SetHighFriction(friction); } // Name: NewtonUserJointSetRowMinimumFriction // Set the minimum friction value the solver is allow to apply to the joint row. // // Parameters: // *const NewtonJoint* *joint - pointer to the joint. // *dFloat* friction - friction value for this row. It must be a negative value between 0.0 and -INFINITY. // // Remark: This function will override the default friction values set after a call to NewtonUserJointAddLinearRow or NewtonUserJointAddAngularRow. // friction value is context sensitive, if for linear constraint friction is a Min friction force, for angular constraint friction is a // friction is a Min friction torque. // // See also: NewtonUserJointSetRowMaximumFriction, NewtonUserJointAddLinearRow, NewtonUserJointAddAngularRow void NewtonUserJointSetRowMinimumFriction(const NewtonJoint* const joint, dFloat friction) { NewtonUserJoint* userJoint; userJoint = (NewtonUserJoint*) joint; userJoint->SetLowerFriction(friction); } // Name: NewtonUserJointSetRowAcceleration // Set the value for the desired acceleration for the current constraint row. // // Parameters: // *const NewtonJoint* *joint - pointer to the joint. // *dFloat* acceleration - desired acceleration value for this row. // // Remark: This function will override the default acceleration values set after a call to NewtonUserJointAddLinearRow or NewtonUserJointAddAngularRow. // friction value is context sensitive, if for linear constraint acceleration is a linear acceleration, for angular constraint acceleration is an // angular acceleration. // // See also: NewtonUserJointAddLinearRow, NewtonUserJointAddAngularRow void NewtonUserJointSetRowAcceleration(const NewtonJoint* const joint, dFloat acceleration) { NewtonUserJoint* userJoint; userJoint = (NewtonUserJoint*) joint; TRACE_FUNTION(__FUNCTION__); userJoint->SetAcceleration(acceleration); } // Name: NewtonUserJointSetRowSpringDamperAcceleration // Calculates the row acceleration to satisfy the specified the spring damper system. // // Parameters: // *const NewtonJoint* *joint - pointer to the joint. // *dFloat* springK - desired spring stiffness, it must be a positive value. // *dFloat* springD - desired spring damper, it must be a positive value. // // Remark: This function will override the default acceleration values set after a call to NewtonUserJointAddLinearRow or NewtonUserJointAddAngularRow. // friction value is context sensitive, if for linear constraint acceleration is a linear acceleration, for angular constraint acceleration is an // angular acceleration. // // Remark: the acceleration calculated by this function represent the mass, spring system of the form // a = -ks * x - kd * v. // // Remark: for this function to take place the joint stiffness must be set to a values lower than 1.0 // // See also: NewtonUserJointSetRowAcceleration, NewtonUserJointSetRowStiffness void NewtonUserJointSetRowSpringDamperAcceleration( const NewtonJoint* const joint, dFloat springK, dFloat springD) { NewtonUserJoint* userJoint; userJoint = (NewtonUserJoint*) joint; TRACE_FUNTION(__FUNCTION__); userJoint->SetSpringDamperAcceleration(springK, springD); } // Name: NewtonUserJointSetRowStiffness // Set the maximum percentage of the constraint force that will be applied to the constraint row. // // Parameters: // *const NewtonJoint* *joint - pointer to the joint. // *dFloat* stiffness - row stiffness, it must be a values between 0.0 and 1.0, the default is 0.9. // // Remark: This function will override the default stiffness value set after a call to NewtonUserJointAddLinearRow or NewtonUserJointAddAngularRow. // the row stiffness is the percentage of the constraint force that will be applied to the rigid bodies. Ideally the value should be // 1.0 (100% stiff) but dues to numerical integration error this could be the joint a little unstable, and lower values are preferred. // // See also: NewtonUserJointAddLinearRow, NewtonUserJointAddAngularRow, NewtonUserJointSetRowSpringDamperAcceleration void NewtonUserJointSetRowStiffness(const NewtonJoint* const joint, dFloat stiffness) { NewtonUserJoint* userJoint; userJoint = (NewtonUserJoint*) joint; TRACE_FUNTION(__FUNCTION__); userJoint->SetRowStiffness(stiffness); } // Name: NewtonUserJointGetRowForce // Return the magnitude previews force or torque value calculated by the solver for this constraint row. // // Parameters: // *const NewtonJoint* *joint - pointer to the joint. // *int* row - index to the constraint row. // // Remark: This function can be call for any of the previews row for this particular joint, The application must keep track of the meaning of the row. // // Remark: This function can be used to produce special effects like breakable or malleable joints, fro example a hinge can turn into ball and socket // after the force in some of the row exceed certain high value. dFloat NewtonUserJointGetRowForce(const NewtonJoint* const joint, int row) { NewtonUserJoint* userJoint; userJoint = (NewtonUserJoint*) joint; TRACE_FUNTION(__FUNCTION__); return userJoint->GetRowForce(row); } // Name: NewtonUserJointSetFeedbackCollectorCallback // Set a constrain callback to collect the force calculated by the solver to enforce this constraint // // Parameters: // *const NewtonJoint* *joint - pointer to the joint. // *NewtonUserBilateralCallBack* getFeedback - pointer to the joint constraint definition function call back. // // See also: NewtonUserJointGetRowForce void NewtonUserJointSetFeedbackCollectorCallback(const NewtonJoint* const joint, NewtonUserBilateralCallBack getFeedback) { NewtonUserJoint* userJoint; userJoint = (NewtonUserJoint*) joint; TRACE_FUNTION(__FUNCTION__); return userJoint->SetUpdateFeedbackFunction(getFeedback); } // *************************************************************************************************************** // // Name: Joint common function s // // *************************************************************************************************************** // Name: NewtonJointSetUserData // Store a user defined data value with the joint. // // Parameters: // *const NewtonJoint* *joint - pointer to the joint. // *void* *userDataPtr - pointer to the user defined user data value. // // Return: Nothing. // // Remarks: The application can store a user defined value with the Joint. This value can be the pointer to a structure containing some application data for special effect. // if the application allocate some resource to store the user data, the application can register a joint destructor to get rid of the allocated resource when the Joint is destroyed // // See also: NewtonConstraintCreateJoint, NewtonJointSetDestructor void NewtonJointSetUserData(const NewtonJoint* const joint, void* const userData) { dgConstraint* contraint; contraint = (dgConstraint*) joint; TRACE_FUNTION(__FUNCTION__); contraint->SetUserData(userData); } // Name: NewtonJointGetUserData // Retrieve a user defined data value stored with the joint. // // Parameters: // *const NewtonJoint* *joint - pointer to the joint. // // Return: The user defined data. // // Remarks: The application can store a user defined value with a joint. This value can be the pointer // to a structure to store some game play data for special effect. // // See also: NewtonJointSetUserData void* NewtonJointGetUserData(const NewtonJoint* const joint) { dgConstraint* contraint; contraint = (dgConstraint*) joint; TRACE_FUNTION(__FUNCTION__); return contraint->GetUserData(); } /* // Name: NewtonJointGetBody0 // Retrieve the first rigid body controlled by this joint. // // Parameters: // *const NewtonJoint* *joint - pointer to the joint. // // Return: pointer the first body // // See also: NewtonJointGetBody1 NewtonBody* NewtonJointGetBody0(const NewtonJoint* const joint) { dgBody* body; dgWorld* world; dgConstraint* contraint; contraint = (dgConstraint*) joint; body = contraint->GetBody0(); world = body->GetWorld(); if (body == world->GetSentinelBody()) { body = NULL; } return (NewtonBody*) body; } // Name: NewtonJointGetBody1 // Retrieve the second rigid body controlled by this joint. // // Parameters: // *const NewtonJoint* *joint - pointer to the joint. // // Return: pointer the second body. // // See also: NewtonJointGetBody0 NewtonBody* NewtonJointGetBody1(const NewtonJoint* const joint) { dgBody* body; dgWorld* world; dgConstraint* contraint; contraint = (dgConstraint*) joint; body = contraint->GetBody1(); world = body->GetWorld(); if (body == world->GetSentinelBody()) { body = NULL; } return (NewtonBody*) body; } */ // Name: NewtonJointGetInfo // Get creation parameters for this joint. // // Parameters: // *const NewtonJoint* joint - is the pointer to a convex collision primitive. // *NewtonJointRecord* *jointInfo - pointer to a collision information record. // // Remarks: This function can be used by the application for writing file format and for serialization. // // See also: void NewtonJointGetInfo(const NewtonJoint* const joint, NewtonJointRecord* const jointInfo) { dgConstraint* contraint; contraint = (dgConstraint*) joint; TRACE_FUNTION(__FUNCTION__); contraint->GetInfo((dgConstraintInfo*) jointInfo); } // Name: NewtonJointGetBody0 // Get the first body connected by this joint. // // Parameters: // *const NewtonJoint* joint - is the pointer to a convex collision primitive. // // // See also: NewtonBody* NewtonJointGetBody0(const NewtonJoint* const joint) { dgConstraint* contraint; contraint = (dgConstraint*) joint; TRACE_FUNTION(__FUNCTION__); return (NewtonBody*) contraint->GetBody0(); } // Name: NewtonJointGetBody1 // Get the secund body connected by this joint. // // Parameters: // *const NewtonJoint* joint - is the pointer to a convex collision primitive. // // See also: NewtonBody* NewtonJointGetBody1(const NewtonJoint* const joint) { dgBody* body; dgWorld* world; dgConstraint* contraint; contraint = (dgConstraint*) joint; TRACE_FUNTION(__FUNCTION__); body = contraint->GetBody1(); world = body->GetWorld(); return (world->GetSentinelBody() != body) ? (NewtonBody*) body : NULL; } // Name: NewtonJointSetCollisionState // Enable or disable collision between the two bodies linked by this joint. The default state is collision disable when the joint is created. // // Parameters: // *const NewtonJoint* *joint - pointer to the joint. // *int* state - collision state, zero mean disable collision, non zero enable collision between linked bodies. // // Return: nothing. // // Remarks: usually when two bodies are linked by a joint, the application wants collision between this two bodies to be disabled. // This is the default behavior of joints when they are created, however when this behavior is not desired the application can change // it by setting collision on. If the application decides to enable collision between jointed bodies, the application should make sure the // collision geometry do not collide in the work space of the joint. // // Remarks: if the joint is destroyed the collision state of the two bodies linked by this joint is determined by the material pair assigned to each body. // // See also: NewtonJointGetCollisionState, NewtonBodySetJointRecursiveCollision void NewtonJointSetCollisionState(const NewtonJoint* const joint, int state) { dgConstraint* contraint; contraint = (dgConstraint*) joint; TRACE_FUNTION(__FUNCTION__); return contraint->SetCollidable(state ? true : false); } // Name: NewtonJointGetCollisionState // Get the collision state of the two bodies linked by the joint. // // Parameters: // *const NewtonJoint* *joint - pointer to the joint. // // Return: the collision state. // // Remarks: usually when two bodies are linked by a joint, the application wants collision between this two bodies to be disabled. // This is the default behavior of joints when they are created, however when this behavior is not desired the application can change // it by setting collision on. If the application decides to enable collision between jointed bodies, the application should make sure the // collision geometry do not collide in the work space of the joint. // // See also: NewtonJointSetCollisionState int NewtonJointGetCollisionState(const NewtonJoint* const joint) { dgConstraint* contraint; contraint = (dgConstraint*) joint; TRACE_FUNTION(__FUNCTION__); return contraint->IsCollidable() ? 1 : 0; } // Name: NewtonJointSetStiffness // Set the strength coefficient to be applied to the joint reaction forces. // // Parameters: // *const NewtonJoint* *joint - pointer to the joint. // *dFloat* stiffness - stiffness coefficient, a value between 0, and 1.0, the default value for most joint is 0.9 // // Return: nothing. // // Remarks: Constraint keep bodies together by calculating the exact force necessary to cancel the relative acceleration between one or // more common points fixed in the two bodies. The problem is that when the bodies drift apart due to numerical integration inaccuracies, // the reaction force work to pull eliminated the error but at the expense of adding extra energy to the system, does violating the rule // that constraint forces must be work less. This is a inevitable situation and the only think we can do is to minimize the effect of the // extra energy by dampening the force by some amount. In essence the stiffness coefficient tell Newton calculate the precise reaction force // by only apply a fraction of it to the joint point. And value of 1.0 will apply the exact force, and a value of zero will apply only // 10 percent. // // Remark: The stiffness is set to a all around value that work well for most situation, however the application can play with these // parameter to make finals adjustment. A high value will make the joint stronger but more prompt to vibration of instability; a low // value will make the joint more stable but weaker. // // See also: NewtonJointGetStiffness void NewtonJointSetStiffness(const NewtonJoint* const joint, dFloat stiffness) { dgConstraint* contraint; contraint = (dgConstraint*) joint; TRACE_FUNTION(__FUNCTION__); contraint->SetStiffness(stiffness); } // Name: NewtonJointGetStiffness // Get the strength coefficient bing applied to the joint reaction forces. // // Parameters: // *const NewtonJoint* *joint - pointer to the joint. // *dFloat* stiffness - stiffness coefficient, a value between 0, and 1.0, the default value for most joint is 0.9 // // Return: stiffness coefficient. // // Remarks: Constraint keep bodies together by calculating the exact force necessary to cancel the relative acceleration between one or // more common points fixed in the two bodies. The problem is that when the bodies drift apart due to numerical integration inaccuracies, // the reaction force work to pull eliminated the error but at the expense of adding extra energy to the system, does violating the rule // that constraint forces must be work less. This is a inevitable situation and the only think we can do is to minimize the effect of the // extra energy by dampening the force by some amount. In essence the stiffness coefficient tell Newton calculate the precise reaction force // by only apply a fraction of it to the joint point. And value of 1.0 will apply the exact force, and a value of zero will apply only // 10 percent. // // Remark: The stiffness is set to a all around value that work well for most situation, however the application can play with these // parameter to make finals adjustment. A high value will make the joint stronger but more prompt to vibration of instability; a low // value will make the joint more stable but weaker. // // See also: NewtonJointSetStiffness dFloat NewtonJointGetStiffness(const NewtonJoint* const joint) { dgConstraint* contraint; contraint = (dgConstraint*) joint; TRACE_FUNTION(__FUNCTION__); return contraint->GetStiffness(); } // Name: NewtonJointSetDestructor // Register a destructor callback to be called when the joint is about to be destroyed. // // Parameters: // *const NewtonJoint* *joint - pointer to the joint. // *NewtonJointCallBack* destructor - pointer to the joint destructor callback. // // Return: nothing. // // Remarks: If application stores any resource with the joint, or the application wants to be notified when the // joint is about to be destroyed. The application can register a destructor call back with the joint. // // See also: NewtonJointSetUserData void NewtonJointSetDestructor(const NewtonJoint* const joint, NewtonConstraintDestructor destructor) { dgConstraint* contraint; contraint = (dgConstraint*) joint; TRACE_FUNTION(__FUNCTION__); contraint->SetDestructorCallback((OnConstraintDestroy) destructor); } // Name: NewtonDestroyJoint // destroy a joint. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the body. // *const NewtonJoint* *joint - pointer to joint to be destroyed // // Return: nothing // // Remarks: The application can call this function when it wants to destroy a joint. This function can be used by the application to simulate // breakable joints // // See also: NewtonConstraintCreateJoint, NewtonConstraintCreateHinge, NewtonConstraintCreateSlider void NewtonDestroyJoint(const NewtonWorld* const newtonWorld, const NewtonJoint* const joint) { Newton* world; world = (Newton *) newtonWorld; TRACE_FUNTION(__FUNCTION__); world->DestroyJoint((dgConstraint*) joint); } // *************************************************************************************************************** // // Name: Special effect mesh interface // // *************************************************************************************************************** NewtonMesh* NewtonMeshCreate(const NewtonWorld* const newtonWorld) { TRACE_FUNTION(__FUNCTION__); Newton* world = (Newton *) newtonWorld; dgMeshEffect* mesh = new (world->dgWorld::GetAllocator()) dgMeshEffect( world->dgWorld::GetAllocator(), true); return (NewtonMesh*) mesh; } NewtonMesh* NewtonMeshCreateFromMesh(const NewtonMesh* const mesh) { TRACE_FUNTION(__FUNCTION__); dgMeshEffect* srcMesh = (dgMeshEffect*) mesh; dgMeshEffect* clone = new (srcMesh->GetAllocator()) dgMeshEffect(*srcMesh); return (NewtonMesh*) clone; } NewtonMesh* NewtonMeshCreateFromCollision( const NewtonCollision* const collision) { TRACE_FUNTION(__FUNCTION__); dgCollision* const shape = (dgCollision*) collision; dgMeshEffect* const mesh = new (shape->GetAllocator()) dgMeshEffect(shape); return (NewtonMesh*) mesh; } NewtonMesh* NewtonMeshConvexHull(const NewtonWorld* const newtonWorld, int count, const dFloat* const vertexCloud, int strideInBytes, dFloat tolerance) { TRACE_FUNTION(__FUNCTION__); Newton* const world = (Newton *) newtonWorld; dgStack<dgBigVector> pool(count); dgInt32 stride = strideInBytes / sizeof(dgFloat32); for (dgInt32 i = 0; i < count; i++) { pool[i].m_x = vertexCloud[i * stride + 0]; pool[i].m_y = vertexCloud[i * stride + 1]; pool[i].m_z = vertexCloud[i * stride + 2]; pool[i].m_w = dgFloat64(0.0); } dgMeshEffect* const mesh = new (world->dgWorld::GetAllocator()) dgMeshEffect( world->dgWorld::GetAllocator(), &pool[0].m_x, count, sizeof(dgBigVector), tolerance); return (NewtonMesh*) mesh; } /* NewtonMesh* NewtonMeshCreatePlane (const NewtonWorld* const newtonWorld, const dFloat* const locationMatrix, dFloat witdth, dFloat breadth, int material, const dFloat* const textureMatrix0, const dFloat* const textureMatrix1) { TRACE_FUNTION(__FUNCTION__); Newton* world = (Newton *) newtonWorld; dgMeshEffect* mesh = new (world->dgWorld::GetAllocator()) dgMeshEffect (world->dgWorld::GetAllocator(), *(dgMatrix*)locationMatrix, witdth, breadth, material, *(dgMatrix*)textureMatrix0, *(dgMatrix*)textureMatrix1); return (NewtonMesh*) mesh; } */ void NewtonMeshDestroy(const NewtonMesh* const mesh) { dgMeshEffect* const meshEffect = (dgMeshEffect*) mesh; TRACE_FUNTION(__FUNCTION__); delete meshEffect; } void NewtonMeshCalculateOOBB(const NewtonMesh* const mesh, dFloat* const matrix, dFloat* const x, dFloat* const y, dFloat* const z) { dgMeshEffect* const meshEffect = (dgMeshEffect*) mesh; TRACE_FUNTION(__FUNCTION__); dgBigVector size; dgMatrix alignMatrix(meshEffect->CalculateOOBB(size)); *((dgMatrix *) matrix) = alignMatrix; *x = dgFloat32(size.m_x); *y = dgFloat32(size.m_y); *z = dgFloat32(size.m_z); } void NewtonMeshCalculateVertexNormals(const NewtonMesh* const mesh, dFloat angleInRadians) { dgMeshEffect* const meshEffect = (dgMeshEffect*) mesh; TRACE_FUNTION(__FUNCTION__); meshEffect->CalculateNormals(angleInRadians); } void NewtonMeshApplySphericalMapping(const NewtonMesh* const mesh, int material) { dgMeshEffect* const meshEffect = (dgMeshEffect*) mesh; TRACE_FUNTION(__FUNCTION__); meshEffect->SphericalMapping(material); } void NewtonMeshApplyBoxMapping(const NewtonMesh* const mesh, int front, int side, int top) { dgMeshEffect* const meshEffect = (dgMeshEffect*) mesh; TRACE_FUNTION(__FUNCTION__); meshEffect->BoxMapping(front, side, top); } void NewtonMeshApplyCylindricalMapping(const NewtonMesh* const mesh, int cylinderMaterial, int capMaterial) { dgMeshEffect* const meshEffect = (dgMeshEffect*) mesh; TRACE_FUNTION(__FUNCTION__); meshEffect->CylindricalMapping(cylinderMaterial, capMaterial); } void NewtonMeshTriangulate(const NewtonMesh* const mesh) { TRACE_FUNTION(__FUNCTION__); ((dgMeshEffect*) mesh)->Triangulate(); } void NewtonMeshPolygonize(const NewtonMesh* const mesh) { TRACE_FUNTION(__FUNCTION__); ((dgMeshEffect*) mesh)->ConvertToPolygons(); } int NewtonMeshIsOpenMesh(const NewtonMesh* const mesh) { TRACE_FUNTION(__FUNCTION__); return ((dgMeshEffect*) mesh)->HasOpenEdges() ? 1 : 0; } void NewtonMeshFixTJoints(const NewtonMesh* const mesh) { TRACE_FUNTION(__FUNCTION__); return ((dgMeshEffect*) mesh)->RepairTJoints(false); } void NewtonMeshClip(const NewtonMesh* const mesh, const NewtonMesh* const clipper, const dFloat* const clipperMatrix, NewtonMesh** const topMesh, NewtonMesh** const bottomMesh) { TRACE_FUNTION(__FUNCTION__); *topMesh = NULL; *bottomMesh = NULL; dgMatrix& matrix = *((dgMatrix*) clipperMatrix); ((dgMeshEffect*) mesh)->ClipMesh(matrix, (dgMeshEffect*) clipper, (dgMeshEffect**) topMesh, (dgMeshEffect**) bottomMesh); } void NewtonMeshPlaneClip(const NewtonMesh* const mesh, dFloat* const planeMatrix, const dFloat* const planeTextureMatrix, int planeMaterial, NewtonMesh** const topMesh, NewtonMesh** const bottomMesh) { TRACE_FUNTION(__FUNCTION__); *topMesh = NULL; *bottomMesh = NULL; dgMatrix& matrix = *((dgMatrix*) planeMatrix); dgMatrix& texMatrix = *((dgMatrix*) planeTextureMatrix); ((dgMeshEffect*) mesh)->PlaneClipMesh(matrix, texMatrix, planeMaterial, (dgMeshEffect**) topMesh, (dgMeshEffect**) bottomMesh); } NewtonMesh* NewtonMeshApproximateConvexDecomposition( const NewtonMesh* const mesh) { TRACE_FUNTION(__FUNCTION__); return (NewtonMesh*) ((dgMeshEffect*) mesh)->CreateConvexApproximation(10); } NewtonMesh* NewtonMeshTetrahedralization(const NewtonMesh* const mesh, int internalMaterial, const dFloat* const textureMatrix) { TRACE_FUNTION(__FUNCTION__); dgMatrix& tetMatrix = *((dgMatrix*) textureMatrix); return (NewtonMesh*) ((dgMeshEffect*) mesh)->CreateDelanayTretrahedralization( internalMaterial, tetMatrix); } NewtonMesh* NewtonMeshVoronoiDecomposition(const NewtonMesh* const mesh, int pointCount, int pointStrideInBytes, const dFloat* const pointCloud, int internalMaterial, const dFloat* const textureMatrix) { TRACE_FUNTION(__FUNCTION__); dgMatrix& tetMatrix = *((dgMatrix*) textureMatrix); return (NewtonMesh*) ((dgMeshEffect*) mesh)->CreateVoronoiPartition( pointCount, pointStrideInBytes, pointCloud, internalMaterial, tetMatrix); } NewtonMesh* NewtonMeshUnion(const NewtonMesh* const mesh, const NewtonMesh* const clipper, const dFloat* const clipperMatrix) { TRACE_FUNTION(__FUNCTION__); dgMatrix& matrix = *((dgMatrix*) clipperMatrix); return (NewtonMesh*) ((dgMeshEffect*) mesh)->Union(matrix, (dgMeshEffect*) clipper); } NewtonMesh* NewtonMeshDifference(const NewtonMesh* const mesh, const NewtonMesh* const clipper, const dFloat* const clipperMatrix) { TRACE_FUNTION(__FUNCTION__); dgMatrix& matrix = *((dgMatrix*) clipperMatrix); return (NewtonMesh*) ((dgMeshEffect*) mesh)->Difference(matrix, (dgMeshEffect*) clipper); } NewtonMesh* NewtonMeshIntersection(const NewtonMesh* const mesh, const NewtonMesh* const clipper, const dFloat* const clipperMatrix) { TRACE_FUNTION(__FUNCTION__); dgMatrix& matrix = *((dgMatrix*) clipperMatrix); return (NewtonMesh*) ((dgMeshEffect*) mesh)->Intersection(matrix, (dgMeshEffect*) clipper); } void NewtonRemoveUnusedVertices(const NewtonMesh* const mesh, int* const vertexRemapTable) { TRACE_FUNTION(__FUNCTION__); ((dgMeshEffect*) mesh)->RemoveUnusedVertices(vertexRemapTable); } void NewtonMeshBeginFace(const NewtonMesh* const mesh) { dgMeshEffect* const meshEffect = (dgMeshEffect*) mesh; TRACE_FUNTION(__FUNCTION__); meshEffect->BeginPolygon(); } void NewtonMeshAddFace(const NewtonMesh* const mesh, int vertexCount, const dFloat* const vertex, int strideInBytes, int materialIndex) { dgMeshEffect* const meshEffect = (dgMeshEffect*) mesh; TRACE_FUNTION(__FUNCTION__); meshEffect->AddPolygon(vertexCount, vertex, strideInBytes, materialIndex); } void NewtonMeshEndFace(const NewtonMesh* const mesh) { dgMeshEffect* const meshEffect = (dgMeshEffect*) mesh; TRACE_FUNTION(__FUNCTION__); meshEffect->EndPolygon(dgFloat64(1.0e-8f)); } void NewtonMeshBuildFromVertexListIndexList(const NewtonMesh* const mesh, int faceCount, const int* const faceIndexCount, const int* const faceMaterialIndex, const dFloat* const vertex, int vertexStrideInBytes, const int* const vertexIndex, const dFloat* const normal, int normalStrideInBytes, const int* const normalIndex, const dFloat* const uv0, int uv0StrideInBytes, const int* const uv0Index, const dFloat* const uv1, int uv1StrideInBytes, const int* const uv1Index) { dgMeshEffect* const meshEffect = (dgMeshEffect*) mesh; TRACE_FUNTION(__FUNCTION__); meshEffect->BuildFromVertexListIndexList(faceCount, faceIndexCount, faceMaterialIndex, vertex, vertexStrideInBytes, vertexIndex, normal, normalStrideInBytes, normalIndex, uv0, uv0StrideInBytes, uv0Index, uv1, uv1StrideInBytes, uv1Index); } int NewtonMeshGetVertexCount(const NewtonMesh* const mesh) { dgMeshEffect* const meshEffect = (dgMeshEffect*) mesh; TRACE_FUNTION(__FUNCTION__); // return meshEffect->GetPropertiesCount(); return meshEffect->GetVertexCount(); } int NewtonMeshGetVertexStrideInByte(const NewtonMesh* const mesh) { dgMeshEffect* const meshEffect = (dgMeshEffect*) mesh; TRACE_FUNTION(__FUNCTION__); return meshEffect->GetVertexStrideInByte(); } dFloat64* NewtonMeshGetVertexArray(const NewtonMesh* const mesh) { dgMeshEffect* const meshEffect = (dgMeshEffect*) mesh; TRACE_FUNTION(__FUNCTION__); return meshEffect->GetVertexPool(); } int NewtonMeshGetPointCount(const NewtonMesh* const mesh) { dgMeshEffect* const meshEffect = (dgMeshEffect*) mesh; TRACE_FUNTION(__FUNCTION__); return meshEffect->GetPropertiesCount(); } int NewtonMeshGetPointStrideInByte(const NewtonMesh* const mesh) { dgMeshEffect* const meshEffect = (dgMeshEffect*) mesh; TRACE_FUNTION(__FUNCTION__); return meshEffect->GetPropertiesStrideInByte(); } dFloat64* NewtonMeshGetPointArray(const NewtonMesh* const mesh) { dgMeshEffect* const meshEffect = (dgMeshEffect*) mesh; TRACE_FUNTION(__FUNCTION__); return meshEffect->GetAttributePool(); } dFloat64* NewtonMeshGetNormalArray(const NewtonMesh* const mesh) { dgMeshEffect* const meshEffect = (dgMeshEffect*) mesh; TRACE_FUNTION(__FUNCTION__); return meshEffect->GetNormalPool(); } dFloat64* NewtonMeshGetUV0Array(const NewtonMesh* const mesh) { dgMeshEffect* const meshEffect = (dgMeshEffect*) mesh; TRACE_FUNTION(__FUNCTION__); return meshEffect->GetUV0Pool(); } dFloat64* NewtonMeshGetUV1Array(const NewtonMesh* const mesh) { dgMeshEffect* const meshEffect = (dgMeshEffect*) mesh; TRACE_FUNTION(__FUNCTION__); return meshEffect->GetUV1Pool(); } void NewtonMeshGetVertexStreams(const NewtonMesh* const mesh, dgInt32 vetexStrideInByte, dFloat* const vertex, dgInt32 normalStrideInByte, dFloat* const normal, dgInt32 uvStrideInByte0, dFloat* const uv0, dgInt32 uvStrideInByte1, dFloat* const uv1) { dgMeshEffect* const meshEffect = (dgMeshEffect*) mesh; TRACE_FUNTION(__FUNCTION__); meshEffect->GetVertexStreams(vetexStrideInByte, (dgFloat32*) vertex, normalStrideInByte, (dgFloat32*) normal, uvStrideInByte0, (dgFloat32*) uv0, uvStrideInByte1, (dgFloat32*) uv1); } void NewtonMeshGetIndirectVertexStreams(const NewtonMesh* const mesh, int vetexStrideInByte, dFloat* const vertex, int* const vertexIndices, int* const vertexCount, int normalStrideInByte, dFloat* const normal, int* const normalIndices, int* const normalCount, int uvStrideInByte0, dFloat* const uv0, int* const uvIndices0, int* const uvCount0, int uvStrideInByte1, dFloat* const uv1, int* const uvIndices1, int* const uvCount1) { _ASSERTE(0); /* dgMeshEffect* const meshEffect = (dgMeshEffect*) mesh; TRACE_FUNTION(__FUNCTION__); meshEffect->GetIndirectVertexStreams (vetexStrideInByte, (dgFloat32*) vertex, (dgInt32*) vertexIndices, (dgInt32*) vertexCount, normalStrideInByte, (dgFloat32*) normal, (dgInt32*) normalIndices, (dgInt32*) normalCount, uvStrideInByte0, (dgFloat32*) uv0, (dgInt32*) uvIndices0, (dgInt32*) uvCount0, uvStrideInByte1, (dgFloat32*) uv1, (dgInt32*) uvIndices1, (dgInt32*) uvCount1); */ } void* NewtonMeshBeginHandle(const NewtonMesh* const mesh) { dgMeshEffect* const meshEffect = (dgMeshEffect*) mesh; TRACE_FUNTION(__FUNCTION__); return meshEffect->MaterialGeometryBegin(); } void NewtonMeshEndHandle(const NewtonMesh* const mesh, void* const handle) { dgMeshEffect* const meshEffect = (dgMeshEffect*) mesh; TRACE_FUNTION(__FUNCTION__); meshEffect->MaterialGeomteryEnd((dgMeshEffect::dgIndexArray*) handle); } int NewtonMeshFirstMaterial(const NewtonMesh* const mesh, void* const handle) { dgMeshEffect* const meshEffect = (dgMeshEffect*) mesh; TRACE_FUNTION(__FUNCTION__); return meshEffect->GetFirstMaterial((dgMeshEffect::dgIndexArray*) handle); } int NewtonMeshNextMaterial(const NewtonMesh* const mesh, void* const handle, int materialId) { dgMeshEffect* const meshEffect = (dgMeshEffect*) mesh; TRACE_FUNTION(__FUNCTION__); return meshEffect->GetNextMaterial((dgMeshEffect::dgIndexArray*) handle, materialId); } int NewtonMeshMaterialGetMaterial(const NewtonMesh* const mesh, void* const handle, int materialId) { dgMeshEffect* const meshEffect = (dgMeshEffect*) mesh; TRACE_FUNTION(__FUNCTION__); return meshEffect->GetMaterialID((dgMeshEffect::dgIndexArray*) handle, materialId); } int NewtonMeshMaterialGetIndexCount(const NewtonMesh* const mesh, void* const handle, int materialId) { dgMeshEffect* const meshEffect = (dgMeshEffect*) mesh; TRACE_FUNTION(__FUNCTION__); return meshEffect->GetMaterialIndexCount((dgMeshEffect::dgIndexArray*) handle, materialId); } void NewtonMeshMaterialGetIndexStream(const NewtonMesh* const mesh, void* const handle, int materialId, int* const index) { dgMeshEffect* const meshEffect = (dgMeshEffect*) mesh; TRACE_FUNTION(__FUNCTION__); meshEffect->GetMaterialGetIndexStream((dgMeshEffect::dgIndexArray*) handle, materialId, index); } void NewtonMeshMaterialGetIndexStreamShort(const NewtonMesh* const mesh, void* const handle, int materialId, short int* const index) { dgMeshEffect* const meshEffect = (dgMeshEffect*) mesh; TRACE_FUNTION(__FUNCTION__); meshEffect->GetMaterialGetIndexStreamShort( (dgMeshEffect::dgIndexArray*) handle, materialId, index); } NewtonMesh* NewtonMeshCreateFirstSingleSegment(const NewtonMesh* const mesh) { TRACE_FUNTION(__FUNCTION__); dgMeshEffect* const effectMesh = (dgMeshEffect*) mesh; dgPolyhedra segment(effectMesh->GetAllocator()); effectMesh->BeginConectedSurface(); if (effectMesh->GetConectedSurface(segment)) { dgMeshEffect* const solid = new (effectMesh->GetAllocator()) dgMeshEffect( segment, *((dgMeshEffect*) mesh)); return (NewtonMesh*) solid; } else { return NULL; } } NewtonMesh* NewtonMeshCreateNextSingleSegment(const NewtonMesh* const mesh, const NewtonMesh* const segment) { TRACE_FUNTION(__FUNCTION__); dgMeshEffect* const effectMesh = (dgMeshEffect*) mesh; dgPolyhedra nextSegment(effectMesh->GetAllocator()); _ASSERTE(segment); dgInt32 moreSegments = effectMesh->GetConectedSurface(nextSegment); dgMeshEffect* solid; if (moreSegments) { solid = new (effectMesh->GetAllocator()) dgMeshEffect(nextSegment, *effectMesh); } else { solid = NULL; effectMesh->EndConectedSurface(); } return (NewtonMesh*) solid; } NewtonMesh* NewtonMeshCreateFirstLayer(const NewtonMesh* const mesh) { TRACE_FUNTION(__FUNCTION__); dgMeshEffect* const effectMesh = (dgMeshEffect*) mesh; return (NewtonMesh*) effectMesh->GetFirstLayer(); } NewtonMesh* NewtonMeshCreateNextLayer(const NewtonMesh* const mesh, const NewtonMesh* const segment) { TRACE_FUNTION(__FUNCTION__); dgMeshEffect* const effectMesh = (dgMeshEffect*) mesh; return (NewtonMesh*) effectMesh->GetNextLayer((dgMeshEffect*) segment); } int NewtonMeshGetTotalFaceCount(const NewtonMesh* const mesh) { TRACE_FUNTION(__FUNCTION__); return ((dgMeshEffect*) mesh)->GetTotalFaceCount(); } int NewtonMeshGetTotalIndexCount(const NewtonMesh* const mesh) { TRACE_FUNTION(__FUNCTION__); return ((dgMeshEffect*) mesh)->GetTotalIndexCount(); } void NewtonMeshGetFaces(const NewtonMesh* const mesh, int* const faceIndexCount, int* const faceMaterial, void** const faceIndices) { ((dgMeshEffect*) mesh)->GetFaces(faceIndexCount, faceMaterial, faceIndices); } void* NewtonMeshGetFirstVertex(const NewtonMesh* const mesh) { TRACE_FUNTION(__FUNCTION__); return ((dgMeshEffect*) mesh)->GetFirstVertex(); } void* NewtonMeshGetNextVertex(const NewtonMesh* const mesh, const void* const vertex) { TRACE_FUNTION(__FUNCTION__); return ((dgMeshEffect*) mesh)->GetNextVertex(vertex); } int NewtonMeshGetVertexIndex(const NewtonMesh* const mesh, const void* const vertex) { TRACE_FUNTION(__FUNCTION__); return ((dgMeshEffect*) mesh)->GetVertexIndex(vertex); } void* NewtonMeshGetFirstPoint(const NewtonMesh* const mesh) { TRACE_FUNTION(__FUNCTION__); return ((dgMeshEffect*) mesh)->GetFirstPoint(); } void* NewtonMeshGetNextPoint(const NewtonMesh* const mesh, const void* const point) { TRACE_FUNTION(__FUNCTION__); return ((dgMeshEffect*) mesh)->GetNextPoint(point); } int NewtonMeshGetPointIndex(const NewtonMesh* const mesh, const void* const point) { TRACE_FUNTION(__FUNCTION__); return ((dgMeshEffect*) mesh)->GetPointIndex(point); } int NewtonMeshGetVertexIndexFromPoint(const NewtonMesh* const mesh, const void* const point) { TRACE_FUNTION(__FUNCTION__); return ((dgMeshEffect*) mesh)->GetVertexIndexFromPoint(point); } void* NewtonMeshGetFirstEdge(const NewtonMesh* const mesh) { TRACE_FUNTION(__FUNCTION__); return ((dgMeshEffect*) mesh)->GetFirstEdge(); } void* NewtonMeshGetNextEdge(const NewtonMesh* const mesh, const void* const edge) { TRACE_FUNTION(__FUNCTION__); return ((dgMeshEffect*) mesh)->GetNextEdge(edge); } void NewtonMeshGetEdgeIndices(const NewtonMesh* const mesh, const void* const edge, int* const v0, int* const v1) { TRACE_FUNTION(__FUNCTION__); return ((dgMeshEffect*) mesh)->GetEdgeIndex(edge, *v0, *v1); } //void NewtonMeshGetEdgePointIndices (const NewtonMesh* const mesh, const void* const edge, int* const v0, int* const v1) //{ // return ((dgMeshEffect*)mesh)->GetEdgeAttributeIndex (edge, *v0, *v1); //} void* NewtonMeshGetFirstFace(const NewtonMesh* const mesh) { TRACE_FUNTION(__FUNCTION__); return ((dgMeshEffect*) mesh)->GetFirstFace(); } void* NewtonMeshGetNextFace(const NewtonMesh* const mesh, const void* const face) { TRACE_FUNTION(__FUNCTION__); return ((dgMeshEffect*) mesh)->GetNextFace(face); } int NewtonMeshIsFaceOpen(const NewtonMesh* const mesh, const void* const face) { TRACE_FUNTION(__FUNCTION__); return ((dgMeshEffect*) mesh)->IsFaceOpen(face); } int NewtonMeshGetFaceIndexCount(const NewtonMesh* const mesh, const void* const face) { TRACE_FUNTION(__FUNCTION__); return ((dgMeshEffect*) mesh)->GetFaceIndexCount(face); } int NewtonMeshGetFaceMaterial(const NewtonMesh* const mesh, const void* const face) { TRACE_FUNTION(__FUNCTION__); return ((dgMeshEffect*) mesh)->GetFaceMaterial(face); } void NewtonMeshGetFaceIndices(const NewtonMesh* const mesh, const void* const face, int* const indices) { TRACE_FUNTION(__FUNCTION__); ((dgMeshEffect*) mesh)->GetFaceIndex(face, indices); } void NewtonMeshGetFacePointIndices(const NewtonMesh* const mesh, const void* const face, int* const indices) { TRACE_FUNTION(__FUNCTION__); ((dgMeshEffect*) mesh)->GetFaceAttributeIndex(face, indices); } #if 0 // *************************************************************************************************************** // // Name: Rag doll joint container Interface // // *************************************************************************************************************** // Name: NewtonCreateRagDoll // Create an empty rag doll container. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // // Return: handle to an empty rag doll container. // // Remarks: A rag doll container is the encapsulation of a group of ball and socket joints, under a common object. It provides common functional // shared by all joints in the tree like structure. The rag doll object job is to simplify some of the common task that the programmer encounters // when it tries to make a rag doll model by connecting joints. // It also has some limitations, for example the hierarchy of joints is made of Ball and socket joints, it only support tree like structures of // joints, the joints can not by detached from the array once they are added to the rag doll. // Rag doll joints are good to make articulated creatures, like humans, monsters, horses, etc. // They are good to simulate effects like death of a character in a game. // // See also: NewtonDestroyRagDoll NewtonRagDoll* NewtonCreateRagDoll(const NewtonWorld* newtonWorld) { Newton* world; world = (Newton *)newtonWorld; TRACE_FUNTION(__FUNCTION__); return (NewtonRagDoll*) world->RagDollList::Create(world); } // Name: NewtonDestroyRagDoll // Destroy a rag doll containers and all it components. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *const NewtonRagDoll* *ragDoll - handle to a rag doll container. // // Return: nothing // // See also: NewtonCreateRagDoll void NewtonDestroyRagDoll(const NewtonWorld* newtonWorld, const NewtonRagDoll* ragDoll) { Newton* world; world = (Newton *)newtonWorld; TRACE_FUNTION(__FUNCTION__); world->RagDollList::Destroy ((RagdollHeader*) ragDoll); } // Name: NewtonRagDollBegin // Prepare a rag doll object to accept bones and making the skeleton. // // Parameters: // *const NewtonRagDoll* *ragDoll - handle to a rag doll container. // // Return: nothing // // Remarks: This function will clean up the rag doll container of any previously // added bone. After the constructions process of the rag doll is completed the application should call // *NewtonRagDollEnd*, not doing so will result in unpredictable results. // // See also: NewtonRagDollEnd, NewtonRagDollAddBone, SetExtForceAndTorqueCallback, SetTransformCallback void NewtonRagDollBegin(const NewtonRagDoll* ragDoll) { RagdollHeader* ragDollHeader; ragDollHeader = (RagdollHeader*) ragDoll; TRACE_FUNTION(__FUNCTION__); ragDollHeader->Begin(); } // Name: NewtonRagDollEnd // Finalized the rag doll construction process. // // Parameters: // *const NewtonRagDoll* *ragDoll - handle to a rag doll container. // // Return: nothing // // Remarks: This function should be called after the constructions process of the rag doll in completed. // calling this function without first calling *NewtonRagDollBegin* will produce unpredictable results. // // See also: NewtonRagDollBegin void NewtonRagDollEnd(const NewtonRagDoll* ragDoll) { RagdollHeader* ragDollHeader; ragDollHeader = (RagdollHeader*) ragDoll; TRACE_FUNTION(__FUNCTION__); ragDollHeader->End(); } // Name: NewtonRagDollAddBone // Add a bone to a rag doll objects. // // Parameters: // *const NewtonRagDoll* *ragDoll - handle to a rag doll container. // *const NewtonRagDollBone* *parent - handle to the bone parent for this bone. If this is the root bone the *parent* should be NULL. // *void* *userData - user data value. The application can use this parameter to store the pointer on index into the graphical part representing this bone. // *dFloat* mass - mass of this body part. // *const dFloat* *matrix - pointer to a 4x4 transformation matrix in the local space of the bone. The matrix should be expressed relative to the parent bone. // *const NewtonCollision* *boneCollision - bone collision geometry. // *const dFloat* size - pointer to an array of three dFloat specifying the size of this body part. The first component of the array is interpreted as the length of the bone. // // Return: the handle to a Rag doll bone // // Remarks: The user data value of a rag doll rigid body is set to the *NewtonRagDollBone*, Unpredictable result will happens if the application set the // user data of a rag doll node rigid body. // // Remarks: this function can only be called from inside of a NewtonRagDollBegin/NewtonRagDollEnd pair. // // See also: NewtonRagDollBegin NewtonRagDollBone* NewtonRagDollAddBone(const NewtonRagDoll* ragDoll, const NewtonRagDollBone* parent, void *userData, dFloat mass, const dFloat* matrix, const NewtonCollision* boneCollision, const dFloat* size) { dgCollision *collision; RagdollHeader* ragDollHeader; TRACE_FUNTION(__FUNCTION__); ragDollHeader = (RagdollHeader*) ragDoll; dgMatrix boneMatrix (*(dgMatrix*) matrix); dgVector boneSize (size[0], size[1], size[2], dgFloat32 (0.0f)); collision = (dgCollision *)boneCollision; return (NewtonRagDollBone*) ragDollHeader->AddBone ((RagdollBone*) parent, userData, mass, boneMatrix, collision, boneSize); } // Name: NewtonRagDollBoneGetUserData // Retrieve a user defined data value stored with the rag doll bone. // // Parameters: // *const NewtonRagDollBone* *bone - pointer to the bone. // // Return: The user defined data. // // Remarks: The application can store a user defined value with a rigid body. This value can be the pointer // to a structure which is the graphical representation of the bone. // // See also: NewtonRagDollAddBone void* NewtonRagDollBoneGetUserData(const NewtonRagDollBone* bone) { RagdollBone* dollBone; TRACE_FUNTION(__FUNCTION__); dollBone = (RagdollBone*) bone; return dollBone->GetUserData(); } // Name: NewtonRagDollSetTransformCallback // Assign a transformation event function to a rag doll object. // // Parameters: // *const NewtonRagDoll* *ragDoll - handle to a rag doll container. // *NewtonSetRagDollTransform callback - pointer to a function callback is used to update the transformation matrix of the visual object that represents the rag doll. // // Return: Nothing. // // Remarks: The function *NewtonSetRagDollTransform callback* is called by the Newton engine every time a visual object that represent a bone of a rag doll has changed. // The application can obtain the pointer user data value that points to the visual object. // The Newton engine does not call the *NewtonSetRagDollTransform callback* function for bones that are inactive or have reached a state of stable equilibrium. // // Remarks: The user data value of a rag doll rigid body is set to the *NewtonRagDollBone*, Unpredictable result will happens if the application set the // user data of a rag doll node rigid body. // The application can get the pointer to the application graphical data by retrieving the user data stored with the *NewtonRagDollBone*. // // Remarks: The matrix should be organized in row-major order (this is the way directX stores matrices). // If you are using OpenGL matrices (column-major) you will need to transpose the matrices into a local array, before // you pass them to Newton. // // Remarks: this function can only be called from inside of a NewtonRagDollBegin/NewtonRagDollEnd pair. // // See also: NewtonRagDollBegin, NewtonRagDollAddBone void NewtonRagDollSetTransformCallback(const NewtonRagDoll* ragDoll, NewtonSetRagDollTransform callback) { RagdollHeader* ragDollHeader; TRACE_FUNTION(__FUNCTION__); ragDollHeader = (RagdollHeader*) ragDoll; ragDollHeader->SetTransformCallback (callback); } // Name: NewtonRagDollSetForceAndTorqueCallback // Assign an event function for applying external force and torque to a Rag doll. // // Parameters: // *const NewtonRagDoll* *ragDoll - handle to a rag doll container. // *NewtonApplyForceAndTorque callback - pointer to a function callback used to apply force and torque to a rigid body bone. // // Return: Nothing. // // Remarks: this function can be seen as a utility function that will call *NewtonBodySetForceAndTorqueCallback* for every bone of a rag doll object. // // Remarks: The user data value of a rag doll rigid body is set to the *NewtonRagDollBone*, unpredictable result will happens if the application set the // user data of a rag doll node rigid body. // The application can get the pointer to the application graphical data by retrieving the user data stored with the *NewtonRagDollBone*. // // Remarks: Before the *NewtonApplyForceAndTorque callback* is called for a body, Newton first clears the net force and net torque for the body. // // Remarks: The function *NewtonApplyForceAndTorque callback* is called by the Newton Engine every time an active body is going to be simulated. // The Newton Engine does not call the *NewtonApplyForceAndTorque callback* function for bodies that are inactive or have reached a state of stable equilibrium. // // See also: NewtonRagDollBegin, NewtonRagDollAddBone void NewtonRagDollSetForceAndTorqueCallback(const NewtonRagDoll* ragDoll, NewtonApplyForceAndTorque callback) { RagdollHeader* ragDollHeader; TRACE_FUNTION(__FUNCTION__); ragDollHeader = (RagdollHeader*) ragDoll; ragDollHeader->SetExtForceAndTorqueCallback ((OnApplyExtForceAndTorque) callback); } // Name: NewtonRagDollBoneSetID // Set an id for this particular bone. // // Parameters: // *const NewtonRagDollBone* *bone - handle to the bone. // *int* id - identifier for this bone. // // Return: Nothing. // // Remarks: during the construction, the application has the option to set an identifier for each bone. It is good idea to make this identifier unique for the rag doll. // // See also: NewtonRagDollAddBone, NewtonRagDollFindBone void NewtonRagDollBoneSetID (const NewtonRagDollBone* bone, int id) { RagdollBone* dollBone; TRACE_FUNTION(__FUNCTION__); dollBone = (RagdollBone*) bone; dollBone->SetNameID (id); } // Name: NewtonRagDollFindBone // Find the first bone with this id in this rag doll. // // Parameters: // *const NewtonRagDoll* *ragDoll - handle to a rag doll container. // *int* id - identifier for this bone. // // Return: the handle to the bone with this identifier. NULL if no bone in the rag doll has this id // // Remarks: during the construction, the application has the option to set an identifier for each bone. It is good idea to make this identifier unique for the rag doll. // the application can use this id to find particular bones in the rag doll body. This is useful for authoring tolls. // // See also: NewtonRagDollBoneSetID NewtonRagDollBone* NewtonRagDollFindBone(const NewtonRagDoll* ragDoll, int id) { RagdollHeader* ragDollHeader; TRACE_FUNTION(__FUNCTION__); ragDollHeader = (RagdollHeader*) ragDoll; return (NewtonRagDollBone*) ragDollHeader->FindBone (id); } // Name: NewtonRagDollBoneGetBody // Retrieve the rigid body assigned to this bone. // // Parameters: // *const NewtonRagDollBone* *bone - handle to the bone. // // Return: The rigid body assigned to this bone // // Remarks: this function can be used to customized some of the properties of the rigid body assigned to the bone. // the application should not override the pointer to *TransformCallback* or *ApplyForceAndTorque* of a rigid body assigned // to a Rag doll bone. It should call the functions *NewtonRagDollSetTransformCallback* and *NewtonRagDollSetForceAndTorqueCallback* instead. // // See also: NewtonRagDollAddBone, NewtonRagDollSetTransformCallback, NewtonRagDollSetForceAndTorqueCallback NewtonBody* NewtonRagDollBoneGetBody(const NewtonRagDollBone* bone) { RagdollBone* dollBone; TRACE_FUNTION(__FUNCTION__); dollBone = (RagdollBone*) bone; return (NewtonBody*) dollBone->m_body; } // Name: NewtonRagDollBoneSetLimits // Set the stop limits for this bone. // // Parameters: // *const NewtonRagDollBone* *bone - handle to this particular bone. If this parameter is the root bone, then the limits do not have any effect. // *const dFloat* *coneDir - pointer to an array of tree dFloat specifying the direction in global space of the cone limits for this bone. // *dFloat* minConeAngle - minimum value of the cone of the cone limit. // *dFloat* maxConeAngle - maximum value of the cone of the cone limit. // *dFloat* maxTwistAngle - maximum and minimum that this bone is allow to spin around the coneDir. // *const dFloat* *lateralConeDir - this parameter is ignored in this release. // *dFloat* negativeBilateralConeAngle - this parameter is ignored in this release. // *dFloat* negativeBilateralConeAngle - this parameter is ignored in this release. // // // Remarks: This function set a cone fixed on the frame of the parent of this bone and defining the work space of the bone. // // See also: NewtonRagDollBegin void NewtonRagDollBoneSetLimits(const NewtonRagDollBone* bone, const dFloat* coneDir, dFloat minConeAngle, dFloat maxConeAngle, dFloat maxTwistAngle, const dFloat* lateralConeDir, dFloat negativeBilateralConeAngle, dFloat positiveBilateralConeAngle) { RagdollBone* dollBone; TRACE_FUNTION(__FUNCTION__); dollBone = (RagdollBone*) bone; dgVector coneAxis (coneDir[0], coneDir[1], coneDir[2], dgFloat32 (0.0f)); // dgVector lateralAxis (lateralConeDir[0], lateralConeDir[1], lateralConeDir[2]); dgVector lateralAxis (dgFloat32(1.0f), dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f)); dollBone->SetJointLimits (coneDir, minConeAngle, maxConeAngle, maxTwistAngle, lateralAxis, negativeBilateralConeAngle, positiveBilateralConeAngle); } // Name: NewtonRagDollBoneGetLocalMatrix // Get the transformation matrix for this bone in the local space of the bone. // // Parameters: // *const NewtonRagDollBone* *bone - handle to this particular bone. If this parameter is the root bone, then the limits do not have any effect. // *dFloat* *matrix - pointer to a 4x4 transformation matrix to receive the transformation matrix for this bone. // // Remarks: the application can call this function from a NewtonSetRagDollTransform to get the transformation matrix for the graphical representation of the bone in local space. // // See also: NewtonRagDollSetTransformCallback void NewtonRagDollBoneGetLocalMatrix(const NewtonRagDollBone* bone, dFloat* matrixPtr) { RagdollBone* dollBone; TRACE_FUNTION(__FUNCTION__); dgMatrix& matrix (*((dgMatrix*) matrixPtr)); dollBone = (RagdollBone*) bone; matrix = dollBone->GetBoneLocalMatrix (); } // Name: NewtonRagDollBoneGetGlobalMatrix // Get the transformation matrix for this bone in the global space of the bone. // // Parameters: // *const NewtonRagDollBone* *bone - handle to this particular bone. If this parameter is the root bone, then the limits do not have any effect. // *dFloat* *matrix - pointer to a 4x4 transformation matrix to receive the transformation matrix for this bone. // // Remarks: the application can call this function from a NewtonSetRagDollTransform to get the transformation matrix for the graphical representation of the bone in global space. // // See also: NewtonRagDollSetTransformCallback void NewtonRagDollBoneGetGlobalMatrix(const NewtonRagDollBone* bone, dFloat* matrixPtr) { RagdollBone* dollBone; TRACE_FUNTION(__FUNCTION__); dgMatrix& matrix (*((dgMatrix*) matrixPtr)); dollBone = (RagdollBone*) bone; matrix = dollBone->GetBoneMatrix (); } //void NewtonRagDollSetFriction (const NewtonRagDoll* ragDoll, dFloat friction) //{ //RagdollHeader* ragDollHeader; //ragDollHeader = (RagdollHeader*) ragDoll; //ragDollHeader->SetFriction(friction); //} // *************************************************************************************************************** // // Name: Vehicle constraint interface // // *************************************************************************************************************** // Name: NewtonConstraintCreateVehicle // Create and empty vehicle joint. // // Parameters: // *const NewtonWorld* *newtonWorld - is the pointer to the Newton world. // *const dFloat* *upDir - is the unit vector defined by the tires pivot points, usually the opposite direction to the gravity vector. // *const NewtonBody* *body - is the pointer to the attached rigid body, this body can not be NULL or it can not have an infinity (zero) mass. // // Return: Pointer to the vehicle joint. // // Remarks: This joint provides basics functionality for simulating real-time simplistic vehicle dynamics. The joint is not meant to be and // accurate and realistic representation of a real vehicle, that is out of the scope of a real-time physics engine. The vehicle is made out // of a main rigid body visible to the application and attached to it a set of tires not visible to the application directly as rigid bodies. // The tires are connected to the body via rigid wheel joints providing the ability for the tire to spin, have suspension, and turn. The // internal vehicle mechanics like transmission, power transfer shaft, suspension mechanism, doors etc. It only models the vehicle body // mounted on a set of wheels, with suspension and the ability to roll. NewtonJoint* NewtonConstraintCreateVehicle(const NewtonWorld* newtonWorld, const dFloat* upDir, const NewtonBody* body) { Newton* world; dgBody *carBody; TRACE_FUNTION(__FUNCTION__); carBody = (dgBody *)body; world = (Newton *)newtonWorld; dgVector pin (upDir[0], upDir[1], upDir[2], dgFloat32 (0.0f)); return (NewtonJoint*) world->CreateVehicleContraint(pin, carBody); } // Name: NewtonVehicleSetTireCallback // Store a function callback pointer for vehicle update. // // Parameters: // *const NewtonJoint* *vehicle - pointer to the vehicle joint. // *NewtonVehicleTireUpdate* update - pointer to the callback function. // // Return: nothing // // Remarks: The only way to control a vehicle is by implementing the vehicle update callback. // The application should iterate through each tire applying tire dynamics to each one. // // See also: NewtonVehicleGetFirstTireID, NewtonVehicleGetNextTireID void NewtonVehicleSetTireCallback(const NewtonJoint* vehicle, NewtonVehicleTireUpdate update) { dgVehicleConstraint* joint; TRACE_FUNTION(__FUNCTION__); joint = (dgVehicleConstraint*)vehicle; joint->SetTireCallback ((OnVehicleUpdate) update); } // Name: NewtonVehicleAddTire // Add a new tire to the vehicle container. // // Parameters: // *const NewtonJoint* *vehicle - pointer to the vehicle joint. // *const dFloat* *localMatrix - pointer to an array of 16 floats containing the offset of the tire relative to the vehicle body. // *const dFloat* pin - pointer to an array of 3 floats containing the rotation axis of the tire, in the space of the tire. // *dFloat* mass - tire mass, must be much smaller than the vehicle body. ratio of 50:1 to 100:1 are the recommended values. // *dFloat* width - width of the tire, must be smaller than the tire radius. // *dFloat* radius - tire radius. // *dFloat* suspesionShock - parametrized damping constant for a spring, mass, damper system. A value of one corresponds to a critically damped system. // *dFloat* suspesionSpring - parametrized spring constant for a spring, mass, damper system. A value of one corresponds to a critically damped system. // *dFloat* suspesionLength - distance from the tire set position to the upper stop on the vehicle body frame. The total suspension length is twice that. // *void* *userData - pointer to a user define data value. Usually used to store the pointer to the graphical representation of the tire. // *int* collisionID - the collision ID use by the application to identify the tire contacts in a contact callback function. // // Return: the tire ID. // // Remarks: After the application creates the vehicle joint, it must add the tires. // Tires are added one at a time at the graphics set position and with the appropriate. // the application should calculate the correct tire parameters, like tire mass, position, width height, // spring and damper constants. // // See also: NewtonVehicleRemoveTire void* NewtonVehicleAddTire(const NewtonJoint* vehicle, const dFloat* localMatrix, const dFloat* pin, dFloat mass, dFloat width, dFloat radius, dFloat suspesionShock, dFloat suspesionSpring, dFloat suspesionLength, void* userData, int collisionID) { dgVehicleConstraint* joint; TRACE_FUNTION(__FUNCTION__); joint = (dgVehicleConstraint*)vehicle; dgMatrix& matrix (*((dgMatrix*) localMatrix)); dgVector tirePin (pin[0], pin[1], pin[2], dgFloat32 (0.0f)); //return joint->AddTire (matrix, pin, mass, width, radius, suspesionShock, suspesionSpring, suspesionLength, (void*)(dgUnsigned64(collisionID)), userData); return joint->AddTire (matrix, pin, mass, width, radius, suspesionShock, suspesionSpring, suspesionLength, IntToPointer(collisionID), userData); } // Name: NewtonVehicleReset // Reset all tires velocities to zero. // // Parameters: // *const NewtonJoint* *vehicle - pointer to the vehicle joint. // // Return: nothing. // // This function is useful for reposition the vehicle. void NewtonVehicleReset(const NewtonJoint* vehicle) { dgVehicleConstraint* joint; joint = (dgVehicleConstraint*)vehicle; TRACE_FUNTION(__FUNCTION__); return joint->Reset(); } // Name: NewtonVehicleRemoveTire // Detach and destroy a tire from the vehicle. // // Parameters: // *const NewtonJoint* *vehicle - pointer to the vehicle joint. // *void* *tireId - tire index to be destroyed. // // Return: nothing. void NewtonVehicleRemoveTire(const NewtonJoint* vehicle, void* tireId) { dgVehicleConstraint* joint; TRACE_FUNTION(__FUNCTION__); joint = (dgVehicleConstraint*)vehicle; joint->RemoveTire (tireId); } // Name: NewtonVehicleGetFirstTireID // Get the index of the first tire of the vehicle tire set. // // Parameters: // *const NewtonJoint* *vehicle - pointer to the vehicle joint. // // Return: tire index. // // Remarks: This function is usually used from inside the vehicle update callback. It is used to iterate through the tire set applying the tire dynamics. // // See also: NewtonVehicleGetNextTireID void* NewtonVehicleGetFirstTireID(const NewtonJoint* vehicle) { dgVehicleConstraint* joint; joint = (dgVehicleConstraint*)vehicle; return joint->GetFirstTireIndex(); } // Name: NewtonVehicleGetNextTireID // Get the index of the next tire on the tire set. // // Parameters: // *const NewtonJoint* *vehicle - pointer to the vehicle joint. // *void* *tireId - index to current tire. // // Return: Next tire index, or zero if index *tireId* was pointing to the last tire in the set. // // Remarks: This function is usually used from inside a tire update callback. It is used to iterate through the tire set applying the tire dynamics. // // See also: NewtonVehicleGetFirstTireID void* NewtonVehicleGetNextTireID(const NewtonJoint* vehicle, void* tireId) { dgVehicleConstraint* joint; TRACE_FUNTION(__FUNCTION__); joint = (dgVehicleConstraint*)vehicle; return joint->GetNextTireIndex(tireId); } // Name: NewtonVehicleGetTireUserData // Retrieve the pointer to the tire user data. // // Parameters: // *const NewtonJoint* *vehicle - pointer to the vehicle joint. // *void* *tireId - index to current tire. // // Return: tire user data. // // Remarks: This function is usually used from the vehicle update callback or from transformation callback of the vehicle body, // It can used do set the transformation matrix of the tire graphical representation. void* NewtonVehicleGetTireUserData (const NewtonJoint* vehicle, void* tireId) { dgVehicleConstraint* joint; TRACE_FUNTION(__FUNCTION__); joint = (dgVehicleConstraint*)vehicle; return joint->GetTireUserData (tireId); } // Name: NewtonVehicleGetTireMatrix // Retrieve the transformation matrix of the tire in global space. // // Parameters: // *const NewtonJoint* *vehicle - pointer to the vehicle joint. // *void* *tireId - index to current tire. // *dFloat* matrix - pointer to an array of 16 floats containing the global matrix of the tire. // // Return: nothing // // Remarks: This function is usually used from the tire update callback or from transformation callback of the vehicle body, // It can be used to set the transformation of the tire graphical representation. void NewtonVehicleGetTireMatrix(const NewtonJoint* vehicle, void* tireId, dFloat* matrix) { dgVehicleConstraint* joint; joint = (dgVehicleConstraint*)vehicle; TRACE_FUNTION(__FUNCTION__); dgMatrix& retMatrix = *((dgMatrix*) matrix); joint->GetTireMatrix (tireId, retMatrix); } // Name: NewtonVehicleGetTireSteerAngle // Get the tire steering angle. // // Parameters: // *const NewtonJoint* *vehicle - pointer to the vehicle joint. // *void* *tireId - index to current tire. // // Return: steering angle. // // Remarks: The vehicle joint provides a rich set of interface functions to the application. Which function to use // is only determined by the level of fidelity the application wants to achieve. In not case the use of one method is better than // other, and it may be that some tweaking and trial is necessary before the desired vehicle behavior is achieved. // // Remarks: The parameters applied to a tire are reset to default values each time the update function is called. // So the application should set the desired value in each simulation frame. // // Remarks: This function can only be called from the vehicle update call back. It can be used by the application to generate the custom vehicle dynamics. dFloat NewtonVehicleGetTireSteerAngle(const NewtonJoint* vehicle, void* tireId) { dgVehicleConstraint* joint; joint = (dgVehicleConstraint*)vehicle; TRACE_FUNTION(__FUNCTION__); return joint->GetSteerAngle(tireId); } // Name: NewtonVehicleSetTireSteerAngle // Set the tire steering angle. // // Parameters: // *const NewtonJoint* *vehicle - pointer to the vehicle joint. // *void* *tireId - index to current tire. // *dFloat* angle - new steering angle. // // Return: nothing. // // Remarks: The vehicle joint provides a rich set of interface functions to the application. Which function to use // is only determined by the level of fidelity the application wants to achieve. In not case the use of one method is better than // other, and it may be that some tweaking and trial is necessary before the desired vehicle behavior is achieved. // // Remarks: The parameters applied to a tire are reset to default values each time the update function is called. // So the application should set the desired value in each simulation frame. // // Remarks: This function can only be called from the vehicle update call back. It can be used by the application to generate the custom vehicle dynamics. void NewtonVehicleSetTireSteerAngle(const NewtonJoint* vehicle, void* tireId, dFloat angle) { dgVehicleConstraint* joint; joint = (dgVehicleConstraint*)vehicle; TRACE_FUNTION(__FUNCTION__); return joint->SetSteerAngle(tireId, angle); } // Name: NewtonVehicleSetTireTorque // Set the tire torque. // // Parameters: // *const NewtonJoint* *vehicle - pointer to the vehicle joint. // *void* *tireId - index to current tire. // *dFloat* torque - new torque value. // // Return: nothing. // // Remarks: This function is useful to simulate normal vehicles with wheels that propel by applying torque to a the tire axis // in order to move. // // Remarks: The vehicle joint provides a rich set of interface functions to the application. Which function to use // is only determined by the level of fidelity the application wants to achieve. In not case the use of one method is better than // other, and it may be that some tweaking and trial is necessary before the desired vehicle behavior is achieved. // // Remarks: The parameters applied to a tire are reset to default values each time the update function is called. // So the application should set the desired value in each simulation frame. // // Remarks: This function can only be called from the vehicle update call back. It can be used by the application to generate the custom vehicle dynamics. void NewtonVehicleSetTireTorque(const NewtonJoint* vehicle, void* tireId, dFloat torque) { dgVehicleConstraint* joint; joint = (dgVehicleConstraint*)vehicle; TRACE_FUNTION(__FUNCTION__); return joint->SetTireTorque(tireId, torque); } // Name: NewtonVehicleGetTireOmega // Retrieve the tire angular velocity. // // Parameters: // *const NewtonJoint* *vehicle - pointer to the vehicle joint. // *void* *tireId - index to current tire. // // Return: angular velocity. // // Remarks: The vehicle joint provides a rich set of interface functions to the application. Which function to use // is only determined by the level of fidelity the application wants to achieve. In not case the use of one method is better than // other, and it may be that some tweaking and trial is necessary before the desired vehicle behavior is achieved. // // Remarks: The parameters applied to a tire are reset to default values each time the update function is called. // So the application should set the desired value in each simulation frame. // // Remarks: This function can only be called from the vehicle update call back. It can be used by the application to generate the custom vehicle dynamics. dFloat NewtonVehicleGetTireOmega(const NewtonJoint* vehicle, void* tireId) { dgVehicleConstraint* joint; joint = (dgVehicleConstraint*)vehicle; TRACE_FUNTION(__FUNCTION__); return joint->GetTireOmega(tireId); } // Name: NewtonVehicleGetTireNormalLoad // Return the part of the vehicle weight supported by this tire. // // Parameters: // *const NewtonJoint* *vehicle - pointer to the vehicle joint. // *void* *tireId - index to current tire. // // Return: magnitude of the vehicle weight supported by this tire. // // Remarks: The vehicle joint provides a rich set of interface functions to the application. Which function to use // is only determined by the level of fidelity the application wants to achieve. In not case the use of one method is better than // other, and it may be that some tweaking and trial is necessary before the desired vehicle behavior is achieved. // // Remarks: The parameters applied to a tire are reset to default values each time the update function is called. // So the application should set the desired value in each simulation frame. // // Remarks: This function can only be called from the vehicle update call back. It can be used by the application to generate the custom vehicle dynamics. dFloat NewtonVehicleGetTireNormalLoad(const NewtonJoint* vehicle, void* tireId) { dgVehicleConstraint* joint; joint = (dgVehicleConstraint*)vehicle; TRACE_FUNTION(__FUNCTION__); return joint->GetTireNormalLoad(tireId); } // Name: NewtonVehicleTireSetBrakeAcceleration // Apply the acceleration and max friction torque to a tire axis. // // Parameters: // *const NewtonJoint* *vehicle - pointer to the vehicle joint. // *void* *tireId - index to current tire. // *dFloat* acceleration - desire tire acceleration. // *dFloat* maxFrictionTorque - maximum friction torque the tire brake, or tire motor can withstand. // // Return: noting. // // Remarks: This is a multipurpose function. The more common use is to apply hand or soft brakes to a vehicle. // To apply brakes the application may use the function *NewtonVehicleTireSetBrakeAcceleration* to determine the exact acceleration // needed to stop the tire from continue to spin in one frame. To simulated the variable brakes strength the application can use // a nominal maximum friction torque (just like in real life any device will withstand a max value) and modulate this value with an analog // control. For hand brakes the application set the control to the maximum and for soft brakes it can just modulate the variable friction. // Another use for this function is to simulate rolling friction, For this effect the application apply the acceleration to stop // but with a friction value set to a minimum non zero fixed value. Note that brakes and tire torque are not mutually exclusive, // the application can apply then simultaneously. As a matter of fact doing so is quite a satisfying test showing how the vehicles rocks // forth and back due to the engine torque, while the tire prevent it from moving. Another use for this function is the simulation of // track based vehicles. For this the application apply an arbitrary fix acceleration to // the tires on each side of the vehicle. A function as simple as *A = Ad minus Ks x Omega* can do the trick, where Ad is the desire acceleration // controlled by the application joystick, Ks is some viscous velocity damping, and omega is the current tire angular velocity reported by the // function *NewtonVehicleGetTireOmega*. // To make the vehicle take turns the application can elaborate the equation like *A = Ad + At minus Ks x Omega* where At is the differential // acceleration supplied by the steering control, for the tires on the right side At is positive while for tires of the left side At is negative. // // Remarks: The vehicle joint provides a rich set of interface functions to the application. Which function to use // is only determined by the level of fidelity the application wants to achieve. In not case the use of one method is better than // other, and it may be that some tweaking and trial is necessary before the desired vehicle behavior is achieved. // // Remarks: The parameters applied to a tire are reset to default values each time the update function is called. // So the application should set the desired value in each simulation frame. // // Remarks: This function can only be called from the vehicle update call back. It can be used by the application to generate the custom vehicle dynamics. // // See also: NewtonVehicleTireCalculateMaxBrakeAcceleration, NewtonVehicleGetTireOmega void NewtonVehicleTireSetBrakeAcceleration(const NewtonJoint* vehicle, void* tireId, dFloat acceleration, dFloat maxFrictionTorque) { dgVehicleConstraint* joint; joint = (dgVehicleConstraint*)vehicle; TRACE_FUNTION(__FUNCTION__); return joint->TireSetBrakeAcceleration(tireId, acceleration, maxFrictionTorque); } // Name: NewtonVehicleTireCalculateMaxBrakeAcceleration // Calculate the exact acceleration needed to be applied to a tire axis in order to bring it to full stop in one time step. // // Parameters: // *const NewtonJoint* *vehicle - pointer to the vehicle joint. // *void* *tireId - index to current tire. // // Return: exact acceleration for full stop of the tire. // // Remarks: The vehicle joint provides a rich set of interface functions to the application. Which function to use // is only determined by the level of fidelity the application want to achieve. In not case the use of one method is better than // other, and it may be that some tweaking and trial is necessary before the desired vehicle behavior is achieved. // // Remarks: The parameters applied to a tire are reset to default values each time the update function is called. // So the application should set the desired value in each simulation frame. // // Remarks: This function can only be called from the vehicle update call back. It can be used by the application to generate the custom vehicle dynamics. // // See also: NewtonVehicleTireSetBrakeAcceleration dFloat NewtonVehicleTireCalculateMaxBrakeAcceleration(const NewtonJoint* vehicle, void* tireId) { dgVehicleConstraint* joint; joint = (dgVehicleConstraint*)vehicle; TRACE_FUNTION(__FUNCTION__); return joint->TireCalculateMaxBrakeAcceleration(tireId); } // Name: NewtonVehicleGetTireLateralSpeed // Return the tire speed along the tire pin axis. // // Parameters: // *const NewtonJoint* *vehicle - pointer to the vehicle joint. // *void* *tireId - index to current tire. // // Return: tire lateral speed. // // Remarks: The vehicle joint provides a rich set of interface functions to the application. Which function to use // is only determined by the level of fidelity the application want to achieve. In not case the use of one method is better than // other, and it may be that some tweaking and trial is necessary before the desired vehicle behavior is achieved. // // Remarks: The parameters applied to a tire are reset to default values each time the update function is called. // So the application should set the desired value in each simulation frame. // // Remarks: This function can only be called from the vehicle update call back. It can be used by the application to generate the custom vehicle dynamics. dFloat NewtonVehicleGetTireLateralSpeed(const NewtonJoint* vehicle, void* tireId) { dgVehicleConstraint* joint; joint = (dgVehicleConstraint*)vehicle; TRACE_FUNTION(__FUNCTION__); return joint->GetTireLateralSpeed(tireId); } // Name: NewtonVehicleGetTireLongitudinalSpeed // Return the tire speed along tire center line. // // Parameters: // *const NewtonJoint* *vehicle - pointer to the vehicle joint. // *void* *tireId - index to current tire. // // Return: tire longitudinal speed. // // Remarks: The vehicle joint provides a rich set of interface functions to the application. Which function to use // is only determined by the level of fidelity the application want to achieve. In not case the use of one method is better than // other, and it may be that some tweaking and trial is necessary before the desired vehicle behavior is achieved. // // Remarks: The parameters applied to a tire are reset to default values each time the update function is called. // So the application should set the desired value in each simulation frame. // // Remarks: This function can only be called from the vehicle update call back. It can be used by the application to generate the custom vehicle dynamics. dFloat NewtonVehicleGetTireLongitudinalSpeed(const NewtonJoint* vehicle, void* tireId) { dgVehicleConstraint* joint; joint = (dgVehicleConstraint*)vehicle; TRACE_FUNTION(__FUNCTION__); return joint->GetTireLongitudinalSpeed(tireId); } // Name: NewtonVehicleSetTireMaxSideSleepSpeed // Set the maximum side slip velocity for the tire to be considered to lose grip. // // Parameters: // *const NewtonJoint* *vehicle - pointer to the vehicle joint. // *void* *tireId - index to current tire. // *dFloat* speed - maximum side speed before the vehicle is considered to loose side grip. // // Return: nothing. // // Remarks: Tire operation involve a mix of elastic distortion and sliding friction. To have and idea how to code a convincing // approximation of a real tire we must run some experiment and make some reflection upon the result. First we will run a static // test: keeping a tire at equilibrium applying a constant load and without rolling, we will apply a lateral force perpendicular // to the tire plane and applied at the tire center. If we run this experiment we will find that the tire will deflect in response // to the lateral force. If we increase the magnitude of the lateral force, the magnitude of the deflection is proportional to the // magnitude of the lateral force, until the tire begins to slide. This show that when a tire is not moving it behaves like a spring // (elastic distortion). If we repeat this experiment but this time increasing the tire load, but still not moving the tire, we will // see that the max deflection is proportional to the magnitude of the tire load. This indicates the tire behavior is proportional // to two variables, the lateral force and the tire load. (Fortunately the side force in practice is a linear function of the tire // load so this keeps the model simple) Now we will run the first experiment but this time we will rotate the tire with a constant // angular velocity (think of those tune up machines at check up stations.) With the tire rolling at constant angular velocity if we // apply a lateral force we will see that as the tire deflect, the part of the tire in contact with the floor keeps rolling and another // part take its place, but this part also start to deflect, allowing the tire to move sideways with a velocity proportional to the // tire rolling angular velocity. Notice that the tire does this without sliding as the part of it in contact with the floor never // loses grip. Now if we increase the lateral force we will find that the lateral speed of the tire will also increase. This suggests // that the side speed of the tire is proportional to the lateral force and also proportional to the rolling angular velocity. This // is the tire elastic properties give then some kind of damping property when they are rolling. There is not known macroscopic // mathematical model that can explain this behavior. The best we can do is to write the values of the experiment and use then to // interpolate and extrapolate intermediate values. One thing we know is that the tires operates within some limits, and we can use // those parameters to treat then as a constraint optimization problem, which is the Newton approach. When the tire is rolling and // side slipping is not that the tire lost grip, nor that the tire is generating some force. It is rather that the tire have the // capacity to absorb some of the lateral force by sliding and convert it to side velocity, this means that for the tire to // loose grip a stronger force is necessary. In another word at rest a tire will lose grip under a much lower lateral force than // if the tire was rolling. In Newton this behavior is treaded as a constrain optimization problem by asking the application how // much side slip velocity is the tire allow to have before it is considered to lose grip, and how much of the lateral forces // generated by the rigid body dynamics will be adsorbed by the tire at a given speed. It is the application responsibility to // set these parameters as close to the real tire as it chooses. This approach allows for a very wide range of behaviors form arcade, // to toy cars to very realistic. // // Remarks: The vehicle joint provides a rich set of interface functions to the application. Which function to use // is only determined by the level of fidelity the application want to achieve. In not case the use of one method is better than // other, and it may be that some tweaking and trial is necessary before the desired vehicle behavior is achieved. // // Remarks: The parameters applied to a tire are reset to default values each time the update function is called. // So the application should set the desired value in each simulation frame. // // Remarks: This function can only be called from the vehicle update call back. It can be used by the application to generate the custom vehicle dynamics. // // See also: NewtonVehicleSetTireSideSleepCoeficient void NewtonVehicleSetTireMaxSideSleepSpeed(const NewtonJoint* vehicle, void* tireId, dFloat speed) { dgVehicleConstraint* joint; joint = (dgVehicleConstraint*)vehicle; TRACE_FUNTION(__FUNCTION__); return joint->SetTireMaxSideSleepSpeed(tireId, speed); } // Name: NewtonVehicleSetTireSideSleepCoeficient // Set the coefficient that tell the engine how much of the lateral force can be absorbed by the tire. // // Parameters: // *const NewtonJoint* *vehicle - pointer to the vehicle joint. // *void* *tireId - index to current tire. // *dFloat* coefficient - side slip coefficient. // // Return: nothing. // // Remarks: See description of side slip on function *NewtonVehicleSetTireMaxSideSleepSpeed* // // Remarks: The vehicle joint provides a rich set of interface functions to the application. Which function to use // is only determined by the level of fidelity the application want to achieve. In not case the use of one method is better than // other, and it may be that some tweaking and trial is necessary before the desired vehicle behavior is achieved. // // Remarks: The parameters applied to a tire are reset to default values each time the update function is called. // So the application should set the desired value in each simulation frame. // // Remarks: This function can only be called from the vehicle update call back. It can be used by the application to generate the custom vehicle dynamics. // // See also: NewtonVehicleSetTireMaxSideSleepSpeed void NewtonVehicleSetTireSideSleepCoeficient(const NewtonJoint* vehicle, void* tireId, dFloat coeficient) { dgVehicleConstraint* joint; joint = (dgVehicleConstraint*)vehicle; TRACE_FUNTION(__FUNCTION__); return joint->SetTireSideSleepCoeficient(tireId, coeficient); } // Name: NewtonVehicleSetTireMaxLongitudinalSlideSpeed // Set the maximum side slide velocity for the tire to be considered to lose traction. // // Parameters: // *const NewtonJoint* *vehicle - pointer to the vehicle joint. // *void* *tireId - index to current tire. // *dFloat* speed - maximum side speed before the vehicle is considered to loose side traction. // // Return: nothing. // // Remarks: The explanation of longitudinal slide is similar to the side slip, however it is not so critical to achieve realistic behavior. // See description of side slip on function *NewtonVehicleSetTireMaxSideSleepSpeed* // // Remarks: The vehicle joint provides a rich set of interface functions to the application. Which function to use // is only determined by the level of fidelity the application want to achieve. In not case the use of one method is better than // other, and it may be that some tweaking and trial is necessary before the desired vehicle behavior is achieved. // // Remarks: The parameters applied to a tire are reset to default values each time the update function is called. // So the application should set the desired value in each simulation frame. // // Remarks: This function can only be called from the vehicle update call back. It can be used by the application to generate the custom vehicle dynamics. // // See also: NewtonVehicleSetTireLongitudinalSlideCoeficient void NewtonVehicleSetTireMaxLongitudinalSlideSpeed(const NewtonJoint* vehicle, void* tireId, dFloat speed) { dgVehicleConstraint* joint; joint = (dgVehicleConstraint*)vehicle; TRACE_FUNTION(__FUNCTION__); return joint->SetTireMaxLongitudinalSlideSpeed(tireId, speed); } // Name: NewtonVehicleSetTireLongitudinalSlideCoeficient // Set the coefficient that tell the engine how much of the longitudinal force can be absorbed by the tire. // // Parameters: // *const NewtonJoint* *vehicle - pointer to the vehicle joint. // *void* *tireId - index to current tire. // *dFloat* coefficient - longitudinal slide coefficient. // // Return: nothing. // // Remarks: The explanation of longitudinal slide is similar to the side slip, however it is not so critical to achieve realistic behavior. // See description of side slip on function *NewtonVehicleSetTireMaxSideSleepSpeed* // // Remarks: The vehicle joint provides a rich set of interface functions to the application. Which function to use // is only determined by the level of fidelity the application want to achieve. In not case the use of one method is better than // other, and it may be that some tweaking and trial is necessary before the desired vehicle behavior is achieved. // // Remarks: The parameters applied to a tire are reset to default values each time the update function is called. // So the application should set the desired value in each simulation frame. // // Remarks: This function can only be called from the vehicle update call back. It can be used by the application to generate the custom vehicle dynamics. // // See also: NewtonVehicleSetTireMaxLongitudinalSlideSpeed void NewtonVehicleSetTireLongitudinalSlideCoeficient(const NewtonJoint* vehicle, void* tireId, dFloat coeficient) { dgVehicleConstraint* joint; joint = (dgVehicleConstraint*)vehicle; TRACE_FUNTION(__FUNCTION__); return joint->SetTireLongitudinalSlideCoeficient(tireId, coeficient); } // Name: NewtonVehicleTireIsAirBorne // Return a boolean value that tells the application if this tire is touching the ground. // // Parameters: // *const NewtonJoint* *vehicle - pointer to the vehicle joint. // *void* *tireId - index to current tire. // // Return: airborne state 1 on the air, 0 on the ground. // // Remarks: The vehicle joint provides a rich set of interface functions to the application. Which function to use // is only determined by the level of fidelity the application want to achieve. In not case the use of one method is better than // other, and it may be that some tweaking and trial is necessary before the desired vehicle behavior is achieved. // // Remarks: The parameters applied to a tire are reset to default values each time the update function is called. // So the application should set the desired value in each simulation frame. // // Remarks: This function can only be called from the vehicle update call back. It can be used by the application to generate the custom vehicle dynamics. int NewtonVehicleTireIsAirBorne(const NewtonJoint* vehicle, void* tireId) { dgVehicleConstraint* joint; joint = (dgVehicleConstraint*)vehicle; TRACE_FUNTION(__FUNCTION__); return joint->IsTireAirBorned(tireId) ? 1 : 0; } // Name: NewtonVehicleTireLostSideGrip // Return a boolean value that tell the application if this tire lost side grip.. // // Parameters: // *const NewtonJoint* *vehicle - pointer to the vehicle joint. // *void* *tireId - index to current tire. // // Return: Grip state. // // Remarks: The vehicle joint provides a rich set of interface functions to the application. Which function to use // is only determined by the level of fidelity the application want to achieve. In not case the use of one method is better than // other, and it may be that some tweaking and trial is necessary before the desired vehicle behavior is achieved. // // Remarks: The parameters applied to a tire are reset to default values each time the update function is called. // So the application should set the desired value in each simulation frame. // // Remarks: This function can only be called from the vehicle update call back. It can be used by the application to generate the custom vehicle dynamics. int NewtonVehicleTireLostSideGrip(const NewtonJoint* vehicle, void* tireId) { dgVehicleConstraint* joint; joint = (dgVehicleConstraint*)vehicle; TRACE_FUNTION(__FUNCTION__); return joint->TireLostSideGrip(tireId) ? 1 : 0; } // Name: NewtonVehicleTireLostTraction // Return a boolean value that tell the application if this tire lost longitudinal traction. // // Parameters: // *const NewtonJoint* *vehicle - pointer to the vehicle joint. // *void* *tireId - index to current tire. // // Return: traction state. // // Remarks: The vehicle joint provides a rich set of interface functions to the application. Which function to use // is only determined by the level of fidelity the application want to achieve. In not case the use of one method is better than // other, and it may be that some tweaking and trial is necessary before the desired vehicle behavior is achieved. // // Remarks: The parameters applied to a tire are reset to default values each time the update function is called. // So the application should set the desired value in each simulation frame. // // Remarks: This function can only be called from the vehicle update call back. It can be used by the application to generate the custom vehicle dynamics. int NewtonVehicleTireLostTraction(const NewtonJoint* vehicle, void* tireId) { dgVehicleConstraint* joint; joint = (dgVehicleConstraint*)vehicle; TRACE_FUNTION(__FUNCTION__); return joint->TireLostTraction(tireId) ? 1 : 0; } #endif
[ "[email protected]@b7a2f1d6-d59d-a8fe-1e9e-8d4888b32692" ]
[ [ [ 1, 9959 ] ] ]
abef8d96ec498fdcde110f56c3f6d91a716a33b3
7159990d73f161a819b815d63b8d413576031122
/Origional/Zombie.cpp
192008d8efd0bf373332546db8e96f6f26705e6a
[]
no_license
MBCook/Zombie-City-GLUT
2d93dc51fcf2c7f9f7d58c014d1492ce8944ef3b
a9999ad6de5d95897ca151840a63f56713a883e2
refs/heads/master
2016-09-05T16:55:54.862373
2005-03-29T23:32:53
2005-03-29T23:32:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
29,697
cpp
#include <windows.h> // Header File For Windows #include <scrnsave.h> // Header File for Screensaving #include <math.h> // Header File for Math #include <stdio.h> // Header FIle for Input/Output #include <stdarg.h> #include <gl\gl.h> // Header File For The OpenGL32 Library #include <gl\glu.h> // Header File For The GLu32 Library #include <gl\glaux.h> // Header File For The Glaux Library #include <fstream.h> HDC hDC=NULL; // Private GDI Device Context HGLRC hRC=NULL; // Permanent Rendering Context HWND hWnd=NULL; // Holds Our Window Handle HINSTANCE hInstance; // Holds The Instance Of The Application bool keys[256]; // Array Used For The Keyboard Routine bool keypressed[256]; // Array Used For The Keyboard Routine bool active=true; // Window Active Flag Set To TRUE By Default bool fullscreen=true; // Fullscreen Flag Set To Fullscreen Mode By Default bool end=false; bool mouseclick; GLfloat lightposition[]={ 1.0f, 1.0f, 1.0f, 1.0f}; GLfloat LightDiffuse[]= { 1.0f, 1.0f, 1.0f, 1.0f}; float i_tick; float framelength; float GAMESPEED = 0.09f; float i_frame; float i_tick_2; float i_frame_rate; int leveltime; GLfloat camerapos[2] = {125.0f, 125.0f}; int centersquare[2] = {0,0}; int population = 2000; //Amount of total beings int zombies = 1; //Amount of Zombies bool hud; //Is the HUD online? struct being{ int state; //0=human, 1=panic, 2=zombie int xPos, yPos; //Coordinates int dir; //Facing int active; //How long it's gonna be running GLfloat move; //how far it is towards the next square GLfloat flash; //Flash of light when they convert to Zombie-hood bool moving; }being[4000]; int city[250][250]; //the City Plan int tracker[250][250]; //Who's where? int list[3]; GLvoid BuildLists() { list[0]=glGenLists(3); glNewList(list[0], GL_COMPILE); glBegin(GL_QUADS); //Ground glColor3f( 0.5f, 0.5f, 0.5f); glNormal3f( 0.0f, 0.0f, 1.0f); glVertex3f(-0.5f,-0.5f, 0.0f); glVertex3f( 0.5f,-0.5f, 0.0f); glVertex3f( 0.5f, 0.5f, 0.0f); glVertex3f(-0.5f, 0.5f, 0.0f); glEnd(); glEndList(); list[1] = list[0] + 1; glNewList(list[1], GL_COMPILE); glBegin(GL_QUADS); //Wall glColor3f( 0.7f, 0.7f, 0.7f); glNormal3f( 0.0f, 0.0f, 1.0f); glVertex3f(-0.5f,-0.5f, 2.0f); glVertex3f( 0.5f,-0.5f, 2.0f); glVertex3f( 0.5f, 0.5f, 2.0f); glVertex3f(-0.5f, 0.5f, 2.0f); glNormal3f(-1.0f, 0.0f, 0.0f); glVertex3f(-0.5f,-0.5f, 2.0f); glVertex3f(-0.5f, 0.5f, 2.0f); glVertex3f(-0.5f, 0.5f, 0.0f); glVertex3f(-0.5f,-0.5f, 0.0f); glNormal3f( 0.0f,-1.0f, 0.0f); glVertex3f(-0.5f,-0.5f, 2.0f); glVertex3f( 0.5f,-0.5f, 2.0f); glVertex3f( 0.5f,-0.5f, 0.0f); glVertex3f(-0.5f,-0.5f, 0.0f); glNormal3f( 1.0f, 0.0f, 0.0f); glVertex3f( 0.5f,-0.5f, 2.0f); glVertex3f( 0.5f, 0.5f, 2.0f); glVertex3f( 0.5f, 0.5f, 0.0f); glVertex3f( 0.5f,-0.5f, 0.0f); glNormal3f( 0.0f, 1.0f, 0.0f); glVertex3f(-0.5f, 0.5f, 2.0f); glVertex3f( 0.5f, 0.5f, 2.0f); glVertex3f( 0.5f, 0.5f, 0.0f); glVertex3f(-0.5f, 0.5f, 0.0f); glEnd(); glEndList(); list[2] = list[1] + 1; glNewList(list[2], GL_COMPILE); glBegin(GL_TRIANGLES); //Being glNormal3f( 0.577f, 0.577f, 0.577f); glVertex3f( 0.0f, 0.0f, 1.2f); glVertex3f( 0.3f, 0.0f, 0.9f); glVertex3f( 0.0f, 0.3f, 0.9f); glNormal3f(-0.577f, 0.577f, 0.577f); glVertex3f( 0.0f, 0.0f, 1.2f); glVertex3f(-0.3f, 0.0f, 0.9f); glVertex3f( 0.0f, 0.3f, 0.9f); glNormal3f( 0.577f, 0.577f,-0.577f); glVertex3f( 0.0f, 0.0f, 0.6f); glVertex3f( 0.3f, 0.0f, 0.9f); glVertex3f( 0.0f, 0.3f, 0.9f); glNormal3f(-0.577f, 0.577f,-0.577f); glVertex3f( 0.0f, 0.0f, 0.6f); glVertex3f(-0.3f, 0.0f, 0.9f); glVertex3f( 0.0f, 0.3f, 0.9f); glNormal3f( 0.0f,-1.0f, 0.0f); glVertex3f( 0.0f, 0.0f, 1.2f); glVertex3f( 0.3f, 0.0f, 0.9f); glVertex3f( 0.0f, 0.0f, 0.6f); glNormal3f( 0.0f,-1.0f, 0.0f); glVertex3f( 0.0f, 0.0f, 1.2f); glVertex3f(-0.3f, 0.0f, 0.9f); glVertex3f( 0.0f, 0.0f, 0.6f); glNormal3f( 0.667f, 0.667f, 0.333f); glVertex3f( 0.0f, 0.0f, 0.9f); glVertex3f( 0.3f, 0.0f, 0.3f); glVertex3f( 0.0f, 0.3f, 0.3f); glNormal3f( 0.667f,-0.667f, 0.333f); glVertex3f( 0.0f, 0.0f, 0.9f); glVertex3f( 0.3f, 0.0f, 0.3f); glVertex3f( 0.0f,-0.3f, 0.3f); glNormal3f(-0.667f, 0.667f, 0.333f); glVertex3f( 0.0f, 0.0f, 0.9f); glVertex3f(-0.3f, 0.0f, 0.3f); glVertex3f( 0.0f, 0.3f, 0.3f); glNormal3f(-0.667f,-0.667f, 0.333f); glVertex3f( 0.0f, 0.0f, 0.9f); glVertex3f(-0.3f, 0.0f, 0.3f); glVertex3f( 0.0f,-0.3f, 0.3f); glEnd(); glEndList(); } LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); // Declaration For WndProc GLvoid ReSizeGLScene(GLsizei width, GLsizei height) // Resize And Initialize The GL Window { if (height==0) // Prevent A Divide By Zero By { height=1; // Making Height Equal One } glViewport(0,0,width,height); // Reset The Current Viewport glMatrixMode(GL_PROJECTION); // Select The Projection Matrix glLoadIdentity(); // Reset The Projection Matrix // Calculate The Aspect Ratio Of The Window gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.05f,100.0f); glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix glLoadIdentity(); // Reset The Modelview Matrix } void Populate_City(int pop) { int x,y; for(int i = 0; i < pop; ++i) { do { x = rand() % 249 + 1; y = rand() % 249 + 1; } while (city[x][y] == 1); being[i].dir = rand() % 4; being[i].move = 0.0f; being[i].state = 0; being[i].xPos = x; being[i].yPos = y; being[i].active = rand() % 10; being[i].moving = false; tracker[being[i].xPos][being[i].yPos] = 0; } x = rand() % pop; being[x].state = 2; being[x].move = 0.8f; tracker[being[i].xPos][being[i].yPos] = 2; camerapos[0] = GLfloat(being[x].xPos); camerapos[1] = GLfloat(being[x].yPos); zombies = 1; } void Build_City() { for(int i = 0; i < 250; ++i) { for(int d = 0; d < 250; ++d) { city[i][d] = 0; tracker[i][d] = -1; } } int x,y,x_length, y_length; for(i = 0; i < 100; ++i) { x = rand() % 250; y = rand() % 250; x_length = rand() % 60 + 10; y_length = rand() % 60 + 10; for(int d = 0; d < x_length; ++d) { for(int e = 0; e < y_length; ++e) { if(d < 250 && e < 250) { if(d == 0 || e == 0 || d == x_length - 1 || e == y_length - 1) { city[d+x][e+y] = 0; } else { city[d+x][e+y] = 1; } } } } } for(i = 0; i < 30; ++i) { x = rand() % 250; y = rand() % 250; x_length = rand() % 20 + 20; y_length = rand() % 20 + 20; for(int d = 0; d < x_length; ++d) { for(int e = 0; e < y_length; ++e) { if(d < 250 && e < 250) { city[d+x][e+y] = 0; } } } } Populate_City(population); }; int InitGL(GLvoid) // All Setup For OpenGL Goes Here { srand(GetTickCount()); glShadeModel(GL_SMOOTH); // Enable Smooth Shading glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Black Background glClearDepth(1.0f); // Depth Buffer Setup glDepthFunc(GL_LESS); // The Type Of Depth Testing To Do glEnable(GL_DEPTH_TEST); // Enables Depth Testing glLightfv(GL_LIGHT1, GL_DIFFUSE, LightDiffuse); glLightfv(GL_LIGHT1, GL_POSITION, lightposition); glEnable(GL_LIGHT1); glEnable(GL_LIGHTING); glShadeModel(GL_SMOOTH); // Enables Smooth Color Shading glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculations glEnable(GL_COLOR_MATERIAL); BuildLists(); Build_City(); return TRUE; // Initialization Went OK } int look(int x, int y, int dir, int dist) { int mod[5] = {0,1,0,-1,0}; for(int i=0; i<dist; i++) { y += mod[dir+1]; x += mod[dir]; if (x>249 || x<1 || y>249 || y<1) { return 3; } else { if (city[x][y] == 1) return 3; } if(tracker[x][y] != -1) { return tracker[x][y]; } } return -1; } int Count_Zombies() { int z = 0; for(int i = 0; i < population; ++i) { if(being[i].state == 2) ++z; } return z; } void Move_Beings() { int mod[5] = {0,1,0,-1,0}; for(int i = 0; i < population; ++i) { switch(being[i].state) { case 0: being[i].move += 0.05f * framelength; break; case 1: being[i].move += 0.1f * framelength; break; case 2: being[i].move += 0.01f * framelength; } if(being[i].move > 1.0f) { //AI Time! being[i].move = 0.0f; if(being[i].moving) { being[i].xPos += mod[being[i].dir]; being[i].yPos += mod[being[i].dir+1]; } tracker[being[i].xPos][being[i].yPos] = -1; being[i].moving = false; int r = rand() % 10; int target[2] = {look(being[i].xPos, being[i].yPos, being[i].dir, 1), look(being[i].xPos, being[i].yPos, being[i].dir, 10)}; switch(being[i].state) { case 0: if(being[i].active == 0 && r < 5) { being[i].dir = rand() % 4; being[i].active = 10; if(look(being[i].xPos, being[i].yPos, being[i].dir, 1) != -1) being[i].moving = false; } being[i].moving = true; if(look(being[i].xPos, being[i].yPos, being[i].dir, 1) != -1) { being[i].dir = rand() % 4; being[i].moving = false; } if(being[i].active > 0) --being[i].active; if(target[1] == 2 || target[1] == 1) { being[i].state = 1; being[i].active = 10; } break; case 1: if(being[i].active == 0 && r < 5) { being[i].dir = rand() % 4; being[i].active = 10; if(look(being[i].xPos, being[i].yPos, being[i].dir, 1) != -1) { being[i].moving = false; if(look(being[i].xPos, being[i].yPos, being[i].dir, 1) == 2) { being[i].state = 2; zombies = Count_Zombies(); being[i].flash = 1.0f; } } } being[i].moving = true; if(look(being[i].xPos, being[i].yPos, being[i].dir, 1) != -1) { being[i].dir = rand() % 4; being[i].moving = false; if(target[0] == 2) { being[i].state = 2; zombies = Count_Zombies(); being[i].flash = 1.0f; } } if(being[i].active > 0) --being[i].active; if(target[1] == 2) { being[i].dir += 2; if(being[i].dir > 3) { being[i].dir -= 4; if(look(being[i].xPos, being[i].yPos, being[i].dir, 1) != -1) { being[i].dir = rand() % 4; being[i].moving = false; if(look(being[i].xPos, being[i].yPos, being[i].dir, 1) == 2) { being[i].state = 2; zombies = Count_Zombies(); being[i].flash = 1.0f; } } } } break; case 2: if(target[1] == 0 || target[1] == 1) being[i].active = 10; if(being[i].active == 0) { being[i].dir = rand() % 4; if(look(being[i].xPos, being[i].yPos, being[i].dir, 1) != -1) being[i].moving = false; } being[i].moving = true; if(look(being[i].xPos, being[i].yPos, being[i].dir, 1) != -1) { if(target[0] == 1 || target[0] == 0) { for(int d = 0; d < population; ++d) { if(being[d].xPos == being[i].xPos + mod[being[i].dir] && being[d].yPos == being[i].yPos + mod[being[i].dir+1]) { being[d].state = 2; zombies = Count_Zombies(); being[d].moving = false; being[i].flash = 1.0f; break; } } } being[i].dir = rand() % 4; being[i].moving = false; } if(being[i].active > 0) --being[i].active; break; } if(look(being[i].xPos, being[i].yPos, being[i].dir, 1) == 0 || look(being[i].xPos, being[i].yPos, being[i].dir, 1) == 1 || look(being[i].xPos, being[i].yPos, being[i].dir, 1) == 2 || look(being[i].xPos, being[i].yPos, being[i].dir, 1) == 3) being[i].moving = false; if(being[i].moving) { tracker[being[i].xPos + mod[being[i].dir]][being[i].yPos + mod[being[i].dir+1]] = being[i].state; } else { tracker[being[i].xPos][being[i].yPos] = being[i].state; } if(being[i].yPos == 0 || being[i].xPos == 0) { int x,y; do { x = rand() % 249 + 1; y = rand() % 249 + 1; } while(city[x][y] != 0 || tracker[x][y] != -1 || (x > centersquare[0] - 25 && x < centersquare[0] + 25 && y > centersquare[1] - 25 && y < centersquare[1] + 25)); being[i].xPos = x; being[i].yPos = y; } } } } int DrawGLScene(GLvoid) // Here's Where We Do All The Drawing { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer Move_Beings(); for(int i = centersquare[0] - 25; i < centersquare[0] + 25; ++i) { for(int d = centersquare[1] - 25; d < centersquare[1] + 25; ++d) { if(i > 0 && i < 250 && d > 0 && d < 250) { glLoadIdentity(); glTranslatef(0.0f, 0.0f, -25.0f); glRotatef(-30.0f, 1.0f, 0.0f, 0.0f); glRotatef( 45.0f, 0.0f, 0.0f, 1.0f); glTranslatef(-camerapos[0],-camerapos[1], 0.0f); glTranslatef(GLfloat(i), GLfloat(d), 0.0f); glColor3f(0.5f, 0.5f, 0.5f); glCallList(list[city[i][d]]); } } } for(i = 0; i < population; ++i) { if(being[i].xPos > centersquare[0] - 25 && being[i].xPos < centersquare[0] + 25 && being[i].yPos > centersquare[1] - 25 && being[i].yPos < centersquare[1] + 25) { glLoadIdentity(); glTranslatef(0.0f, 0.0f, -25.0f); glRotatef(-30.0f, 1.0f, 0.0f, 0.0f); glRotatef( 45.0f, 0.0f, 0.0f, 1.0f); glTranslatef(-camerapos[0],-camerapos[1], 0.0f); glTranslatef(GLfloat(being[i].xPos), being[i].yPos, 0.0f); switch(being[i].state) { case 0: glColor3f(0.6f, 0.0f, 0.0f); break; case 1: glColor3f(1.0f, 0.3f, 0.3f); break; case 2: glColor3f(being[i].flash, 1.0f, being[i].flash); being[i].flash -= 0.03 * framelength; break; } glRotatef(-90.0f * being[i].dir, 0.0f, 0.0f, 1.0f); if(being[i].moving == true) { glTranslatef(0.0f, being[i].move, 0.0f); } glCallList(list[2]); } } if(hud) { GLfloat a,b; a = GLfloat(population - zombies) / GLfloat(population); //Red Bar Length b = GLfloat(zombies) / GLfloat(population); //Green Bar Length glLoadIdentity(); glTranslatef(-2.7f, 2.0f,-5.0f); glBegin(GL_QUADS); glNormal3f(0.0f, 0.0f, 1.0f); glColor3f(1.0f, 0.0f, 0.0f); glVertex3f(0.0f, 0.03f, 0.0f); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f( a, 0.0f, 0.0f); glVertex3f( a, 0.03f, 0.0f); glColor3f(0.0f, 1.0f, 0.0f); glVertex3f(0.0f,-0.03f, 0.0f); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f( b, 0.0f, 0.0f); glVertex3f( b,-0.03f, 0.0f); glEnd(); } return true; } GLvoid KillGLWindow(GLvoid) // Properly Kill The Window { if (fullscreen) // Are We In Fullscreen Mode? { ChangeDisplaySettings(NULL,0); // If So Switch Back To The Desktop ShowCursor(TRUE); // Show Mouse Pointer } if (hRC) // Do We Have A Rendering Context? { if (!wglMakeCurrent(NULL,NULL)) // Are We Able To Release The DC And RC Contexts? { MessageBox(NULL,"Release Of DC And RC Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION); } if (!wglDeleteContext(hRC)) // Are We Able To Delete The RC? { MessageBox(NULL,"Release Rendering Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION); } hRC=NULL; // Set RC To NULL } if (hDC && !ReleaseDC(hWnd,hDC)) // Are We Able To Release The DC { MessageBox(NULL,"Release Device Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION); hDC=NULL; // Set DC To NULL } if (hWnd && !DestroyWindow(hWnd)) // Are We Able To Destroy The Window? { MessageBox(NULL,"Could Not Release hWnd.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION); hWnd=NULL; // Set hWnd To NULL } if (!UnregisterClass("OpenGL",hInstance)) // Are We Able To Unregister Class { MessageBox(NULL,"Could Not Unregister Class.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION); hInstance=NULL; // Set hInstance To NULL } } /* This Code Creates Our OpenGL Window. Parameters Are: * * title - Title To Appear At The Top Of The Window * * width - Width Of The GL Window Or Fullscreen Mode * * height - Height Of The GL Window Or Fullscreen Mode * * bits - Number Of Bits To Use For Color (8/16/24/32) * * fullscreenflag - Use Fullscreen Mode (TRUE) Or Windowed Mode (FALSE) */ BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag) { GLuint PixelFormat; // Holds The Results After Searching For A Match WNDCLASS wc; // Windows Class Structure DWORD dwExStyle; // Window Extended Style DWORD dwStyle; // Window Style RECT WindowRect; // Grabs Rectangle Upper Left / Lower Right Values WindowRect.left=(long)0; // Set Left Value To 0 WindowRect.right=(long)width; // Set Right Value To Requested Width WindowRect.top=(long)0; // Set Top Value To 0 WindowRect.bottom=(long)height; // Set Bottom Value To Requested Height fullscreen=fullscreenflag; // Set The Global Fullscreen Flag hInstance = GetModuleHandle(NULL); // Grab An Instance For Our Window wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Redraw On Size, And Own DC For Window. wc.lpfnWndProc = (WNDPROC) WndProc; // WndProc Handles Messages wc.cbClsExtra = 0; // No Extra Window Data wc.cbWndExtra = 0; // No Extra Window Data wc.hInstance = hInstance; // Set The Instance wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); // Load The Default Icon wc.hCursor = LoadCursor(NULL, IDC_ARROW); // Load The Arrow Pointer wc.hbrBackground = NULL; // No Background Required For GL wc.lpszMenuName = NULL; // We Don't Want A Menu wc.lpszClassName = "OpenGL"; // Set The Class Name if (!RegisterClass(&wc)) // Attempt To Register The Window Class { MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (fullscreen) // Attempt Fullscreen Mode? { DEVMODE dmScreenSettings; // Device Mode memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared dmScreenSettings.dmSize=sizeof(dmScreenSettings); // Size Of The Devmode Structure dmScreenSettings.dmPelsWidth = width; // Selected Screen Width dmScreenSettings.dmPelsHeight = height; // Selected Screen Height dmScreenSettings.dmBitsPerPel = bits; // Selected Bits Per Pixel dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT; // Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar. if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL) { // If The Mode Fails, Offer Two Options. Quit Or Use Windowed Mode. if (MessageBox(NULL,"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?","NeHe GL",MB_YESNO|MB_ICONEXCLAMATION)==IDYES) { fullscreen=FALSE; // Windowed Mode Selected. Fullscreen = FALSE } else { // Pop Up A Message Box Letting User Know The Program Is Closing. MessageBox(NULL,"Program Will Now Close.","ERROR",MB_OK|MB_ICONSTOP); return FALSE; // Return FALSE } } } if (fullscreen) // Are We Still In Fullscreen Mode? { dwExStyle=WS_EX_APPWINDOW; // Window Extended Style dwStyle=WS_POPUP; // Windows Style } else { dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Window Extended Style dwStyle=WS_OVERLAPPEDWINDOW; // Windows Style } ShowCursor(!fullscreen); // Hide/Show Mouse Pointer AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle); // Adjust Window To True Requested Size // Create The Window if (!(hWnd=CreateWindowEx( dwExStyle, // Extended Style For The Window "OpenGL", // Class Name title, // Window Title dwStyle | // Defined Window Style WS_CLIPSIBLINGS | // Required Window Style WS_CLIPCHILDREN, // Required Window Style 0, 0, // Window Position WindowRect.right-WindowRect.left, // Calculate Window Width WindowRect.bottom-WindowRect.top, // Calculate Window Height NULL, // No Parent Window NULL, // No Menu hInstance, // Instance NULL))) // Dont Pass Anything To WM_CREATE { KillGLWindow(); // Reset The Display MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } static PIXELFORMATDESCRIPTOR pfd= // pfd Tells Windows How We Want Things To Be { sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor 1, // Version Number PFD_DRAW_TO_WINDOW | // Format Must Support Window PFD_SUPPORT_OPENGL | // Format Must Support OpenGL PFD_DOUBLEBUFFER, // Must Support Double Buffering PFD_TYPE_RGBA, // Request An RGBA Format bits, // Select Our Color Depth 0, 0, 0, 0, 0, 0, // Color Bits Ignored 0, // No Alpha Buffer 0, // Shift Bit Ignored 0, // No Accumulation Buffer 0, 0, 0, 0, // Accumulation Bits Ignored 16, // 16Bit Z-Buffer (Depth Buffer) 0, // No Stencil Buffer 0, // No Auxiliary Buffer PFD_MAIN_PLANE, // Main Drawing Layer 0, // Reserved 0, 0, 0 // Layer Masks Ignored }; if (!(hDC=GetDC(hWnd))) // Did We Get A Device Context? { KillGLWindow(); // Reset The Display MessageBox(NULL,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd))) // Did Windows Find A Matching Pixel Format? { KillGLWindow(); // Reset The Display MessageBox(NULL,"Can't Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if(!SetPixelFormat(hDC,PixelFormat,&pfd)) // Are We Able To Set The Pixel Format? { KillGLWindow(); // Reset The Display MessageBox(NULL,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (!(hRC=wglCreateContext(hDC))) // Are We Able To Get A Rendering Context? { KillGLWindow(); // Reset The Display MessageBox(NULL,"Can't Create A GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if(!wglMakeCurrent(hDC,hRC)) // Try To Activate The Rendering Context { KillGLWindow(); // Reset The Display MessageBox(NULL,"Can't Activate The GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } ShowWindow(hWnd,SW_SHOW); // Show The Window SetForegroundWindow(hWnd); // Slightly Higher Priority SetFocus(hWnd); // Sets Keyboard Focus To The Window ReSizeGLScene(width, height); // Set Up Our Perspective GL Screen if (!InitGL()) // Initialize Our Newly Created GL Window { KillGLWindow(); // Reset The Display MessageBox(NULL,"Initialization Failed.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } return TRUE; // Success } LRESULT CALLBACK WndProc( HWND hWnd, // Handle For This Window UINT uMsg, // Message For This Window WPARAM wParam, // Additional Message Information LPARAM lParam) // Additional Message Information { switch (uMsg) // Check For Windows Messages { case WM_ACTIVATE: // Watch For Window Activate Message { if (!HIWORD(wParam)) // Check Minimization State { active=TRUE; // Program Is Active } else { active=FALSE; // Program Is No Longer Active } return 0; // Return To The Message Loop } case WM_SYSCOMMAND: // Intercept System Commands { switch (wParam) // Check System Calls { case SC_SCREENSAVE: // Screensaver Trying To Start? case SC_MONITORPOWER: // Monitor Trying To Enter Powersave? return 0; // Prevent From Happening } break; // Exit } case WM_CLOSE: // Did We Receive A Close Message? { PostQuitMessage(0); // Send A Quit Message return 0; // Jump Back } case WM_KEYDOWN: // Is A Key Being Held Down? { keys[wParam] = true; // If So, Mark It As TRUE return 0; // Jump Back } case WM_KEYUP: // Has A Key Been Released? { keys[wParam] = false; // If So, Mark It As FALSE keypressed[wParam] = false; return 0; // Jump Back } case WM_LBUTTONDOWN: { mouseclick = true; return 0; } case WM_LBUTTONUP: { mouseclick = false; return 0; } case WM_MOUSEMOVE: { return 0; } case WM_SIZE: // Resize The OpenGL Window { ReSizeGLScene(LOWORD(lParam),HIWORD(lParam)); // LoWord=Width, HiWord=Height return 0; // Jump Back } } // Pass All Unhandled Messages To DefWindowProc return DefWindowProc(hWnd,uMsg,wParam,lParam); } update() { if(keys[VK_LEFT]) { camerapos[0] -= 0.0707f * 4 * framelength; camerapos[1] += 0.0707f * 4 * framelength; } if(keys[VK_RIGHT]) { camerapos[0] += 0.0707f * 4 * framelength; camerapos[1] -= 0.0707f * 4 * framelength; } if(keys[VK_UP]) { camerapos[0] += 0.0707f * 4 * framelength; camerapos[1] += 0.0707f * 4 * framelength; } if(keys[VK_DOWN]) { camerapos[0] -= 0.0707f * 4 * framelength; camerapos[1] -= 0.0707f * 4 * framelength; } centersquare[0] = int(camerapos[0]); centersquare[1] = int(camerapos[1]); if(keys['Z']) { keys['Z'] = false; Build_City(); } if(keys['S']) { keys['S'] = false; GAMESPEED += 0.01f; if(GAMESPEED > 0.3) GAMESPEED = 0.02f; } if(keys[VK_SUBTRACT]) { keys[VK_SUBTRACT] = false; population -= 100; if(population < 100) population = 100; Build_City(); } if(keys[VK_ADD]) { keys[VK_ADD] = false; population += 100; if(population > 4000) population = 4000; Build_City(); } if(keys[VK_TAB]) { keys[VK_TAB] = false; hud = !hud; } }; int WINAPI WinMain( HINSTANCE hInstance, // Instance HINSTANCE hPrevInstance, // Previous Instance LPSTR lpCmdLine, // Command Line Parameters int nCmdShow) // Window Show State { MSG msg; // Windows Message Structure BOOL done=FALSE; // Bool Variable To Exit Loop // Ask The User Which Screen Mode They Prefer fullscreen=true; // Fullscreen Mode if (MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO) { fullscreen=false; } // Create Our OpenGL Window if (!CreateGLWindow("Zombie City!",640,480,16,fullscreen)) { return 0; // Quit If Window Was Not Created } for(int i=0; i<256; ++i) { keys[i] = 0; } i_tick = float(GetTickCount()); //Set i_tick to the new tick count - so the difference does not exponentially increase while(!done) // Loop That Runs While done=FALSE { if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) // Is There A Message Waiting? { if (msg.message==WM_QUIT) // Have We Received A Quit Message? { done=TRUE; // If So done=TRUE } else // If Not, Deal With Window Messages { TranslateMessage(&msg); // Translate The Message DispatchMessage(&msg); // Dispatch The Message } } else // If There Are No Messages { do { } while (( GetTickCount() - i_tick ) < 10 ); framelength = (GetTickCount() - i_tick) * GAMESPEED; //When the frame starts, find out how many 'ticks' have occurred since the last frame if(framelength > 10.0f) framelength = 10.0f; leveltime += int(GetTickCount() - i_tick); i_tick = float(GetTickCount()); //Set i_tick to the new tick count - so the difference does not exponentially increase i_frame+=1; if ((i_tick_2 + 1000) < GetTickCount()) { i_frame_rate = i_frame; i_frame=0; i_tick_2 = float(GetTickCount()); }; update(); // Draw The Scene. Watch For ESC Key And Quit Messages From DrawGLScene() if ((active && !DrawGLScene()) || keys[VK_ESCAPE]) // Active? Was There A Quit Received? { done=TRUE; // ESC or DrawGLScene Signalled A Quit } else // Not Time To Quit, Update Screen { SwapBuffers(hDC); // Swap Buffers (Double Buffering) } if (keys[VK_F1]) // Is F1 Being Pressed? { keys[VK_F1]=FALSE; // If So Make Key FALSE KillGLWindow(); // Kill Our Current Window fullscreen=!fullscreen; // Toggle Fullscreen / Windowed Mode // Recreate Our OpenGL Window if (!CreateGLWindow("Zombie City",640,480,16,fullscreen)) { return 0; // Quit If Window Was Not Created } } } if(end) done=true; } // Shutdown KillGLWindow(); // Kill The Window return (msg.wParam); // Exit The Program }
[ [ [ 1, 915 ] ] ]
7ee4d05b7e870e584c4eafd7101c30b67df0b7c1
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/addons/pa/ParticleUniverse/src/ParticleUniverseDynamicAttribute.cpp
22142f7aae15d2721a0b16a7e92f811141511da6
[]
no_license
dbabox/aomi
dbfb46c1c9417a8078ec9a516cc9c90fe3773b78
4cffc8e59368e82aed997fe0f4dcbd7df626d1d0
refs/heads/master
2021-01-13T14:05:10.813348
2011-06-07T09:36:41
2011-06-07T09:36:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,875
cpp
/* ----------------------------------------------------------------------------------------------- This source file is part of the Particle Universe product. Copyright (c) 2010 Henry van Merode Usage of this program is licensed under the terms of the Particle Universe Commercial License. You can find a copy of the Commercial License in the Particle Universe package. ----------------------------------------------------------------------------------------------- */ #include "ParticleUniversePCH.h" #ifndef PARTICLE_UNIVERSE_EXPORTS #define PARTICLE_UNIVERSE_EXPORTS #endif namespace ParticleUniverse { //----------------------------------------------------------------------- DynamicAttribute::DynamicAttribute (void) : IElement() { } //----------------------------------------------------------------------- DynamicAttribute::~DynamicAttribute (void) { } //----------------------------------------------------------------------- DynamicAttribute::DynamicAttributeType DynamicAttribute::getType (void) const { return mType; } //----------------------------------------------------------------------- void DynamicAttribute::setType (DynamicAttribute::DynamicAttributeType type) { mType = type; } //----------------------------------------------------------------------- DynamicAttributeFixed::DynamicAttributeFixed (void) : mValue(0) { mType = DynamicAttribute::DAT_FIXED; } //----------------------------------------------------------------------- DynamicAttributeFixed::DynamicAttributeFixed (const DynamicAttributeFixed& dynamicAttributeFixed) { mType = DynamicAttribute::DAT_FIXED; mValue = dynamicAttributeFixed.mValue; } //----------------------------------------------------------------------- DynamicAttributeFixed::~DynamicAttributeFixed (void) { } //----------------------------------------------------------------------- void DynamicAttributeFixed::setValue (Ogre::Real value) { mValue = value; } //----------------------------------------------------------------------- Ogre::Real DynamicAttributeFixed::getValue (Ogre::Real x) { return mValue; } //----------------------------------------------------------------------- void DynamicAttributeFixed::copyAttributesTo(DynamicAttribute* dynamicAttribute) { if (!dynamicAttribute || dynamicAttribute->getType() != DynamicAttribute::DAT_FIXED) return; DynamicAttributeFixed* dynAttr = static_cast<DynamicAttributeFixed*>(dynamicAttribute); dynAttr->mValue = mValue; } //----------------------------------------------------------------------- DynamicAttributeRandom::DynamicAttributeRandom (void) : mMin(0), mMax(0) { mType = DynamicAttribute::DAT_RANDOM; } //----------------------------------------------------------------------- DynamicAttributeRandom::DynamicAttributeRandom (const DynamicAttributeRandom& dynamicAttributeRandom) { mType = DynamicAttribute::DAT_RANDOM; mMin = dynamicAttributeRandom.mMin; mMax = dynamicAttributeRandom.mMax; } //----------------------------------------------------------------------- DynamicAttributeRandom::~DynamicAttributeRandom (void) { } //----------------------------------------------------------------------- Ogre::Real DynamicAttributeRandom::getMin (void) const { return mMin; } //----------------------------------------------------------------------- void DynamicAttributeRandom::setMin (Ogre::Real min) { mMin = min; } //----------------------------------------------------------------------- Ogre::Real DynamicAttributeRandom::getMax (void) const { return mMax; } //----------------------------------------------------------------------- void DynamicAttributeRandom::setMax (Ogre::Real max) { mMax = max; } //----------------------------------------------------------------------- void DynamicAttributeRandom::setMinMax (Ogre::Real min, Ogre::Real max) { mMin = min; mMax = max; } //----------------------------------------------------------------------- Ogre::Real DynamicAttributeRandom::getValue (Ogre::Real x) { return Ogre::Math::RangeRandom(mMin, mMax); } //----------------------------------------------------------------------- void DynamicAttributeRandom::copyAttributesTo(DynamicAttribute* dynamicAttribute) { if (!dynamicAttribute || dynamicAttribute->getType() != DynamicAttribute::DAT_RANDOM) return; DynamicAttributeRandom* dynAttr = static_cast<DynamicAttributeRandom*>(dynamicAttribute); dynAttr->mMin = mMin; dynAttr->mMax = mMax; } //----------------------------------------------------------------------- DynamicAttributeCurved::DynamicAttributeCurved (void) : mInterpolationType(IT_LINEAR), mRange(0) { mType = DynamicAttribute::DAT_CURVED; } //----------------------------------------------------------------------- DynamicAttributeCurved::DynamicAttributeCurved (InterpolationType interpolationType) : mInterpolationType(interpolationType), mRange(0) { mType = DynamicAttribute::DAT_CURVED; } //----------------------------------------------------------------------- DynamicAttributeCurved::DynamicAttributeCurved (const DynamicAttributeCurved& dynamicAttributeCurved) { mType = DynamicAttribute::DAT_CURVED; mInterpolationType = dynamicAttributeCurved.mInterpolationType; mSpline = dynamicAttributeCurved.mSpline; mRange = dynamicAttributeCurved.mRange; // Copy controlpoints DynamicAttributeCurved::ControlPointList::const_iterator it; // Need const_iterator here! for (it = dynamicAttributeCurved.mControlPoints.begin(); it != dynamicAttributeCurved.mControlPoints.end(); ++it) { Ogre::Vector2 controlPoint = *it; mControlPoints.push_back (controlPoint); } processControlPoints(); } //----------------------------------------------------------------------- DynamicAttributeCurved::~DynamicAttributeCurved (void) { } //----------------------------------------------------------------------- void DynamicAttributeCurved::setInterpolationType (InterpolationType interpolationType) { if (interpolationType != mInterpolationType) { // If switched to another InterpolationType, the already existing ControlPoints will be removed. removeAllControlPoints(); mInterpolationType = interpolationType; } } //----------------------------------------------------------------------- InterpolationType DynamicAttributeCurved::getInterpolationType (void) const { return mInterpolationType; } //----------------------------------------------------------------------- Ogre::Real DynamicAttributeCurved::getValue (Ogre::Real x) { switch (mInterpolationType) { case IT_LINEAR: { // Search the interval in which 'x' resides and apply linear interpolation if (mControlPoints.empty()) return 0; ControlPointList::iterator it1 = _findNearestControlPointIterator(x); ControlPointList::iterator it2 = it1 + 1; if (it2 != mControlPoints.end()) { // Calculate fraction: y = y1 + ((y2 - y1) * (x - x1)/(x2 - x1)) return (*it1).y + (((*it2).y - (*it1).y) * (x - (*it1).x)/((*it2).x - (*it1).x)); } else { return (*it1).y; } } break; case IT_SPLINE: { // Fit using spline if (mSpline.getNumPoints() < 1) return 0; Ogre::Real fraction = x / mRange; return (mSpline.interpolate(fraction < 1.0f ? fraction : 1.0f)).y; } break; } return 0; } //----------------------------------------------------------------------- void DynamicAttributeCurved::addControlPoint (Ogre::Real x, Ogre::Real y) { mControlPoints.push_back(Ogre::Vector2(x, y)); } //----------------------------------------------------------------------- const DynamicAttributeCurved::ControlPointList& DynamicAttributeCurved::getControlPoints (void) const { return mControlPoints; } //----------------------------------------------------------------------- void DynamicAttributeCurved::processControlPoints(void) { if (mControlPoints.empty()) return; std::sort(mControlPoints.begin(), mControlPoints.end(), ControlPointSorter()); mRange = (*_getLastValidIterator()).x - (*_getFirstValidIterator()).x; if (mInterpolationType == IT_SPLINE) { // Add all sorted control points to the spline DynamicAttributeCurved::ControlPointList::iterator it; mSpline.clear(); for (it = mControlPoints.begin(); it != mControlPoints.end(); ++it) mSpline.addPoint(Ogre::Vector3((*it).x, (*it).y, 0)); } } //----------------------------------------------------------------------- size_t DynamicAttributeCurved::getNumControlPoints(void) const { return mControlPoints.size(); } //----------------------------------------------------------------------- void DynamicAttributeCurved::removeAllControlPoints(void) { mControlPoints.clear(); } //----------------------------------------------------------------------- DynamicAttributeCurved::ControlPointList::iterator DynamicAttributeCurved::_findNearestControlPointIterator(Ogre::Real x) { // Assume that the ControlPointList is not empty ControlPointList::iterator it; for (it = mControlPoints.begin(); it != mControlPoints.end(); ++it) { if (x < (*it).x) { if (it == mControlPoints.begin()) return it; else return --it; } } // If not found return the last valid iterator return --it; } //----------------------------------------------------------------------- DynamicAttributeCurved::ControlPointList::iterator DynamicAttributeCurved::_getFirstValidIterator(void) { return mControlPoints.begin(); } //----------------------------------------------------------------------- DynamicAttributeCurved::ControlPointList::iterator DynamicAttributeCurved::_getLastValidIterator(void) { return mControlPoints.end() - 1; } //----------------------------------------------------------------------- void DynamicAttributeCurved::copyAttributesTo(DynamicAttribute* dynamicAttribute) { if (!dynamicAttribute || dynamicAttribute->getType() != DynamicAttribute::DAT_CURVED) return; DynamicAttributeCurved* dynAttr = static_cast<DynamicAttributeCurved*>(dynamicAttribute); dynAttr->mInterpolationType = mInterpolationType; dynAttr->mSpline = mSpline; dynAttr->mRange = mRange; // Copy controlpoints DynamicAttributeCurved::ControlPointList::const_iterator it; // Need const_iterator here! for (it = mControlPoints.begin(); it != mControlPoints.end(); ++it) { Ogre::Vector2 controlPoint = *it; dynAttr->mControlPoints.push_back(controlPoint); } dynAttr->processControlPoints(); } //----------------------------------------------------------------------- DynamicAttributeOscillate::DynamicAttributeOscillate (void) : mOscillationType(DynamicAttributeOscillate::OSCT_SINE), mFrequency(1.0f), mPhase(0.0f), mBase(0.0f), mAmplitude(1.0f) { mType = DynamicAttribute::DAT_OSCILLATE; } //----------------------------------------------------------------------- DynamicAttributeOscillate::DynamicAttributeOscillate (const DynamicAttributeOscillate& dynamicAttributeOscillate) { mType = DynamicAttribute::DAT_OSCILLATE; } //----------------------------------------------------------------------- DynamicAttributeOscillate::~DynamicAttributeOscillate (void) { } //----------------------------------------------------------------------- DynamicAttributeOscillate::OscillationType DynamicAttributeOscillate::getOscillationType (void) const { return mOscillationType; } //----------------------------------------------------------------------- void DynamicAttributeOscillate::setOscillationType (DynamicAttributeOscillate::OscillationType oscillationType) { mOscillationType = oscillationType; } //----------------------------------------------------------------------- Ogre::Real DynamicAttributeOscillate::getFrequency (void) const { return mFrequency; } //----------------------------------------------------------------------- void DynamicAttributeOscillate::setFrequency (Ogre::Real frequency) { mFrequency = frequency; } //----------------------------------------------------------------------- Ogre::Real DynamicAttributeOscillate::getPhase (void) const { return mPhase; } //----------------------------------------------------------------------- void DynamicAttributeOscillate::setPhase (Ogre::Real phase) { mPhase = phase; } //----------------------------------------------------------------------- Ogre::Real DynamicAttributeOscillate::getBase (void) const { return mBase; } //----------------------------------------------------------------------- void DynamicAttributeOscillate::setBase (Ogre::Real base) { mBase = base; } //----------------------------------------------------------------------- Ogre::Real DynamicAttributeOscillate::getAmplitude (void) const { return mAmplitude; } //----------------------------------------------------------------------- void DynamicAttributeOscillate::setAmplitude (Ogre::Real amplitude) { mAmplitude = amplitude; } //----------------------------------------------------------------------- Ogre::Real DynamicAttributeOscillate::getValue (Ogre::Real x) { switch (mOscillationType) { case OSCT_SINE: { return mBase + mAmplitude * Ogre::Math::Sin(mPhase + mFrequency * x * Ogre::Math::TWO_PI); } break; case OSCT_SQUARE: { return mBase + mAmplitude * Ogre::Math::Sign(Ogre::Math::Sin(mPhase + mFrequency * x * Ogre::Math::TWO_PI)); } break; } return 0; } //----------------------------------------------------------------------- void DynamicAttributeOscillate::copyAttributesTo(DynamicAttribute* dynamicAttribute) { if (!dynamicAttribute || dynamicAttribute->getType() != DynamicAttribute::DAT_OSCILLATE) return; DynamicAttributeOscillate* dynAttr = static_cast<DynamicAttributeOscillate*>(dynamicAttribute); dynAttr->mOscillationType = mOscillationType; dynAttr->mFrequency = mFrequency; dynAttr->mPhase = mPhase; dynAttr->mBase = mBase; dynAttr->mAmplitude = mAmplitude; } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- Ogre::Real DynamicAttributeHelper::calculate(DynamicAttribute* dyn, Ogre::Real x, Ogre::Real defaultValue) { if (dyn) { return dyn->getValue(x); } return defaultValue; } }
[ [ [ 1, 425 ] ] ]
373d3f5e859e3c0e7f28400b7498bf750c973ca4
aca65a1eb785ebe6d6e0e862f3b49931923da90b
/DTI Visualization/DicomImageSet.cpp
34dde5c95e3861a78720121351bfcbfc72924e45
[]
no_license
vcpudding/DTI-Visualization-Hypergraph
d5126a0123707a2b1399a73751aa9bec88c1e25c
23da494ba4291450cdece4bda421853ec2beedfc
refs/heads/master
2020-06-05T09:47:30.924373
2011-12-29T13:13:44
2011-12-29T13:13:44
3,026,931
0
0
null
null
null
null
UTF-8
C++
false
false
17,111
cpp
#include "DicomImageSet.h" int DicomImageSet::parseFolder(QString folderName) { QStringList fileList = getAllFiles(folderName); HRESULT hr = CoInitialize(NULL); if (!SUCCEEDED(hr)) { return NULL; } hr = S_OK; IXMLDOMDocument *pXMLDom = NULL; IXMLDOMElement *pRoot = NULL; BSTR bstrXML = NULL; VARIANT varFileName; VariantInit(&varFileName); QProgressDialog progress (QString("Parsing all files in %1").arg(folderName), QString("Cancel"), 0, fileList.count()); CHK_HR(CreateAndInitDOM(&pXMLDom)); // Create a processing instruction element. CHK_HR(CreateAndAddPINode(pXMLDom, L"xml", L"version='1.0'")); // Create the root element. CHK_HR(CreateElement(pXMLDom, L"root", &pRoot)); // Create an attribute for the <root> element, with name "created" and value "using dom". CHK_HR(CreateAndAddAttributeNode(pXMLDom, L"path", folderName.toStdWString().c_str(), pRoot)); // Add NEWLINE for identation before </root>. CHK_HR(CreateAndAddTextNode(pXMLDom, L"\n", pRoot)); // add <root> to document CHK_HR(AppendChildToParent(pRoot, pXMLDom)); progress.show(); for (int i=0; i<fileList.count(); ++i) { insertFileItem(pXMLDom, pRoot, folderName, fileList[i]); progress.setValue(i); } CHK_HR(VariantFromString(QDir(folderName).filePath(DATASET_FILE_NAME).toStdWString().c_str(), varFileName)); CHK_HR(pXMLDom->save(varFileName)); CleanUp: SAFE_RELEASE(pRoot); SysFreeString(bstrXML); VariantClear(&varFileName); CoUninitialize(); if (FAILED(hr)) { SAFE_RELEASE(pXMLDom); return 0; } return 1; } QStringList DicomImageSet::getAllFiles(const QString &folderName) { QDir folder (folderName); QFileInfoList fileInfoList = folder.entryInfoList(); QStringList fileList; for (int i=0; i<fileInfoList.count(); ++i) { QString fName = fileInfoList[i].fileName(); if (!fileInfoList[i].isDir()) { fileList.append(fileInfoList[i].absoluteFilePath()); } else if (fileInfoList[i].fileName().compare (".") && fileInfoList[i].fileName().compare ("..")) { fileList = fileList + getAllFiles(fileInfoList[i].absoluteFilePath()); } } return fileList; } int DicomImageSet::insertFileItem(IXMLDOMDocument *pDom, IXMLDOMNode * pRoot, const QString &folderName, const QString &fileName) { DicomImage * dicomImage = new DicomImage (); if (!dicomImage->readHeader((QDir(folderName).absoluteFilePath(fileName)).toStdString().c_str())) { //fail to resolve header information return 0; } int nElement; char * patientsName = dicomImage->getCharTag(DicomImage::TAG_PATIENTS_NAME, nElement); char * patientsId = dicomImage->getCharTag(DicomImage::TAG_PATIENT_ID, nElement); char * protocolName = dicomImage->getCharTag(DicomImage::TAG_PROTOCOL_NAME, nElement); double * pInstanceNumber = dicomImage->getNumericTag(DicomImage::TAG_INSTANCE_NUMBER, nElement); double * pAcquisitionNumber = dicomImage->getNumericTag(DicomImage::TAG_ACQUISITION_NUMBER, nElement); double * pAcquisitionDate = dicomImage->getNumericTag(DicomImage::TAG_ACQUISITION_DATE, nElement); int instanceNumber = pInstanceNumber?(int)pInstanceNumber[0]:-1; int acquisitionNumber = pAcquisitionNumber?(int)pAcquisitionNumber[0]:-1; int acquisitionDate = pAcquisitionDate?(int)pAcquisitionDate[0]:0; IXMLDOMNode * pParent = findParentNode(pDom, pRoot, patientsName, patientsId, acquisitionDate, protocolName, acquisitionNumber); if (!pParent) { return 0; } HRESULT hr = S_OK; IXMLDOMElement *pNode = NULL; CHK_HR(CreateElement(pDom, L"File", &pNode)); CHK_HR(CreateAndAddAttributeNode(pDom, L"path", fileName.toStdWString().c_str(), pNode)); CHK_HR(CreateAndAddAttributeNode(pDom, L"instance_number", QString::number(instanceNumber).toStdWString().c_str(), pNode)); IXMLDOMNode * pSibling = NULL; CHK_HR(pParent->get_firstChild(&pSibling)); int sibInstanceNumber = -1; VARIANT varInstanceNumber; DOMNodeType nodeType; while (pSibling && instanceNumber >= sibInstanceNumber) { CHK_HR(pSibling->get_nodeType(&nodeType)); if(nodeType == NODE_ELEMENT) { CHK_HR(GetAttributeFromNode(pSibling, L"instance_number", &varInstanceNumber)); sibInstanceNumber = QString::fromWCharArray(_bstr_t(varInstanceNumber)).toInt(); if (instanceNumber < sibInstanceNumber) { break; } } IXMLDOMNode * tmpNode = NULL; CHK_HR(pSibling->get_nextSibling(&tmpNode)); SAFE_RELEASE(pSibling); pSibling = tmpNode; } if (pSibling) { IXMLDOMNode * tmpNode = NULL; CHK_HR(pSibling->get_previousSibling(&tmpNode)); SAFE_RELEASE(pSibling); pSibling = tmpNode; } CHK_HR(CreateAndAddTextNodeBefore(pDom, L"\n", pParent, pSibling)); CHK_HR(InsertChildToParent(pNode, pSibling, pParent)); CleanUp: SAFE_RELEASE(pNode); return 1; } IXMLDOMNode * DicomImageSet::findParentNode(IXMLDOMDocument *pXMLDom, IXMLDOMNode * pRoot, const char * patientsName, const char * patientsId, int acquisitionDate, const char * protocol, int acquisitionNumber) { if (!pXMLDom) { return NULL; } HRESULT hr = S_OK; IXMLDOMElement *pPatient = NULL, *pDate = NULL, *pProtocol = NULL, *pCollection = NULL; BSTR bstrQuery = NULL; QString strQuery; bool nodeExist = false; //look for the patient node strQuery = QString("root/Patient[@patients_name = '%1' and @patient_id = '%2']").arg(patientsName).arg(patientsId); bstrQuery = SysAllocString(strQuery.toStdWString().c_str()); CHK_ALLOC(bstrQuery); CHK_HR(pXMLDom->selectSingleNode(bstrQuery, (IXMLDOMNode**)&pPatient)); SysFreeString(bstrQuery); nodeExist = pPatient; if (!nodeExist) { //create the patient node CHK_HR(CreateElement(pXMLDom, L"Patient", &pPatient)); CHK_HR(CreateAndAddAttributeNode(pXMLDom, L"patients_name", QString(patientsName).toStdWString().c_str(), pPatient)); CHK_HR(CreateAndAddAttributeNode(pXMLDom, L"patient_id", QString(patientsId).toStdWString().c_str(), pPatient)); CHK_HR(CreateAndAddTextNode(pXMLDom, L"\n", pRoot)); CHK_HR(AppendChildToParent(pPatient, pRoot)); } if (nodeExist) { //look for the date node strQuery = QString("Date[@acquisition_date = '%1']").arg(acquisitionDate); bstrQuery = SysAllocString(strQuery.toStdWString().c_str()); CHK_ALLOC(bstrQuery); CHK_HR(pPatient->selectSingleNode(bstrQuery, (IXMLDOMNode**)&pDate)); SysFreeString(bstrQuery); nodeExist = pDate; } if (!nodeExist) { CHK_HR(CreateElement(pXMLDom, L"Date", &pDate)); CHK_HR(CreateAndAddAttributeNode(pXMLDom, L"acquisition_date", QString::number(acquisitionDate).toStdWString().c_str(), pDate)); CHK_HR(CreateAndAddTextNode(pXMLDom, L"\n", pPatient)); CHK_HR(AppendChildToParent(pDate, pPatient)); } if (nodeExist) { //look for the protocol node strQuery = QString("Protocol[@protocol_name = '%1']").arg(protocol); bstrQuery = SysAllocString(strQuery.toStdWString().c_str()); CHK_ALLOC(bstrQuery); CHK_HR(pDate->selectSingleNode(bstrQuery, (IXMLDOMNode**)&pProtocol)); SysFreeString(bstrQuery); nodeExist = pProtocol; } if (!nodeExist) { CHK_HR(CreateElement(pXMLDom, L"Protocol", &pProtocol)); CHK_HR(CreateAndAddAttributeNode(pXMLDom, L"protocol_name", QString(protocol).toStdWString().c_str(), pProtocol)); CHK_HR(CreateAndAddTextNode(pXMLDom, L"\n", pDate)); CHK_HR(AppendChildToParent(pProtocol, pDate)); } if (nodeExist) { //look for the collection node strQuery = QString("Collection[@acquisition_number = '%1']").arg(acquisitionNumber); bstrQuery = SysAllocString(strQuery.toStdWString().c_str()); CHK_ALLOC(bstrQuery); CHK_HR(pProtocol->selectSingleNode(bstrQuery, (IXMLDOMNode**)&pCollection)); SysFreeString(bstrQuery); nodeExist = pCollection; } if (!nodeExist) { CHK_HR(CreateElement(pXMLDom, L"Collection", &pCollection)); CHK_HR(CreateAndAddAttributeNode(pXMLDom, L"acquisition_number", QString::number(acquisitionNumber).toStdWString().c_str(), pCollection)); CHK_HR(CreateAndAddTextNode(pXMLDom, L"\n", pProtocol)); CHK_HR(AppendChildToParent(pCollection, pProtocol)); } CleanUp: SAFE_RELEASE(pPatient); SAFE_RELEASE(pDate); SAFE_RELEASE(pProtocol); if(SUCCEEDED(hr)) { return pCollection; } SAFE_RELEASE(pCollection); return NULL; } int DicomImageSet::readDatasetFile(const QString &datasetFileName, QTreeWidget *treeWidget) { HRESULT hr = S_OK; IXMLDOMDocument *pXMLDom = NULL; IXMLDOMNodeList *pPatients = NULL; IXMLDOMNode *pPatient = NULL; DOMNodeType nodeType; VARIANT_BOOL varStatus; VARIANT varFileName; VARIANT varValue; BSTR bstrQuery; VariantInit(&varFileName); VariantInit(&varValue); QString queryPatient, queryDate, queryProtocol, queryCollection; CHK_HR(CreateAndInitDOM(&pXMLDom)); CHK_HR(VariantFromString(datasetFileName.toStdWString().c_str(), varFileName)); CHK_HR(pXMLDom->load(varFileName, &varStatus)); if (varStatus != VARIANT_TRUE) { CHK_HR(ReportParseError(pXMLDom, "Failed to load DOM from stocks.xml.")); } treeWidget->clear(); treeWidget->setColumnCount(1); CHK_HR(pXMLDom->getElementsByTagName(L"Patient", &pPatients)); if (pPatients) { long nPatients; CHK_HR(pPatients->get_length(&nPatients)); for (long i=0; i<nPatients; ++i) { CHK_HR(pPatients->get_item(i, &pPatient)); CHK_HR(GetAttributeFromNode(pPatient, L"patients_name", &varValue)); queryPatient = QString::fromWCharArray(_bstr_t(varValue)); QTreeWidgetItem * patientItem = new QTreeWidgetItem(treeWidget, QStringList(queryPatient)); patientItem->setExpanded(true); IXMLDOMNodeList * pDates = NULL; CHK_HR(pPatient->get_childNodes(&pDates)); long nDates; CHK_HR(pDates->get_length(&nDates)); for (long j=0; j<nDates; ++j) { IXMLDOMNode * pDate = NULL; CHK_HR(pDates->get_item(j, &pDate)); CHK_HR(pDate->get_nodeType(&nodeType)); if(nodeType!=NODE_ELEMENT) { continue; } CHK_HR(GetAttributeFromNode(pDate, L"acquisition_date", &varValue)); queryDate = QString::fromWCharArray(_bstr_t(varValue)); int intDate = queryDate.toInt(); QDate date = (QDate::fromString("1900-01-01", "yyyy-MM-dd")).addDays(intDate-693962); QTreeWidgetItem * dateItem = new QTreeWidgetItem(patientItem, QStringList(date.toString("yyyy-MM-dd"))); dateItem->setExpanded(true); IXMLDOMNodeList * pProtocols = NULL; CHK_HR(pDate->get_childNodes(&pProtocols)); long nProtocols; CHK_HR(pProtocols->get_length(&nProtocols)); for (long j=0; j<nProtocols; ++j) { IXMLDOMNode * pProtocol = NULL; CHK_HR(pProtocols->get_item(j, &pProtocol)); CHK_HR(pProtocol->get_nodeType(&nodeType)); if(nodeType!=NODE_ELEMENT) { continue; } CHK_HR(GetAttributeFromNode(pProtocol, L"protocol_name", &varValue)); queryProtocol = QString::fromWCharArray(_bstr_t(varValue)); QTreeWidgetItem * protocolItem = new QTreeWidgetItem(dateItem, QStringList(queryProtocol)); protocolItem->setExpanded(true); IXMLDOMNodeList * pCollections = NULL; CHK_HR(pProtocol->get_childNodes(&pCollections)); long nCollections; CHK_HR(pCollections->get_length(&nCollections)); for (long j=0; j<nCollections; ++j) { IXMLDOMNode * pCollection = NULL; CHK_HR(pCollections->get_item(j, &pCollection)); CHK_HR(pCollection->get_nodeType(&nodeType)); if(nodeType!=NODE_ELEMENT) { continue; } CHK_HR(GetAttributeFromNode(pCollection, L"acquisition_number", &varValue)); queryCollection = QString::fromWCharArray(_bstr_t(varValue)); QTreeWidgetItem * collectionItem = new QTreeWidgetItem(protocolItem); QString queryStr = QString("root/Patient[@patients_name = '%1']/Date[@acquisition_date = '%2']/Protocol[@protocol_name = '%3']/Collection[@acquisition_number = '%4']") .arg(queryPatient).arg(queryDate).arg(queryProtocol).arg(queryCollection); IXMLDOMElement * pDtiNode = NULL; bstrQuery = SysAllocString(QString(queryStr+"/DTI").toStdWString().c_str()); CHK_ALLOC(bstrQuery); CHK_HR(pXMLDom->selectSingleNode(bstrQuery, (IXMLDOMNode**)&pDtiNode)); SysFreeString(bstrQuery); if (pDtiNode) { collectionItem->setText(0,queryCollection+"*"); } else { collectionItem->setText(0, queryCollection); } collectionItem->setData(0, Qt::UserRole, queryStr); collectionItem->setExpanded(true); protocolItem->addChild(collectionItem); SAFE_RELEASE(pCollection); } dateItem->addChild(protocolItem); SAFE_RELEASE(pProtocol); } patientItem->addChild(dateItem); SAFE_RELEASE(pDate); } treeWidget->insertTopLevelItem(i, patientItem); SAFE_RELEASE(pPatient); } } CleanUp: SAFE_RELEASE(pXMLDom); SAFE_RELEASE(pPatients); SAFE_RELEASE(pPatient); VariantClear(&varFileName); return SUCCEEDED(hr); } QStringList DicomImageSet::getOrderedDcmFiles(const QString &datasetFileName, const QString & queryString) { HRESULT hr = S_OK; IXMLDOMDocument *pXMLDom = NULL; IXMLDOMNodeList *pFileNodes = NULL; VARIANT_BOOL varStatus; VARIANT varFileName; BSTR bstrQuery; QStringList fileList; CHK_HR(CreateAndInitDOM(&pXMLDom)); CHK_HR(VariantFromString(datasetFileName.toStdWString().c_str(), varFileName)); CHK_HR(pXMLDom->load(varFileName, &varStatus)); if (varStatus != VARIANT_TRUE) { CHK_HR(ReportParseError(pXMLDom, "Failed to load DOM from stocks.xml.")); } bstrQuery = SysAllocString(queryString.toStdWString().c_str()); CHK_ALLOC(bstrQuery); CHK_HR(pXMLDom->selectNodes(bstrQuery, &pFileNodes)); if (pFileNodes) { long nFiles; CHK_HR(pFileNodes->get_length(&nFiles)); for (long i=0; i<nFiles; ++i) { VARIANT varValue; IXMLDOMNode * pFile = NULL; CHK_HR(pFileNodes->get_item(i, &pFile)); CHK_HR(GetAttributeFromNode(pFile, L"path", &varValue)); fileList <<QString::fromWCharArray(_bstr_t(varValue)); SAFE_RELEASE(pFile); } } CleanUp: SAFE_RELEASE(pXMLDom); SAFE_RELEASE(pFileNodes); return fileList; } int DicomImageSet::insertDTIFileItem(const QString &datasetFolderName, const QString &queryString, const QString &dtiFileName) { HRESULT hr = CoInitialize(NULL); if (!SUCCEEDED(hr)) { return 0; } QString datasetFileName = datasetFolderName+DATASET_FILE_NAME; IXMLDOMDocument *pXMLDom = NULL; IXMLDOMElement *pNode = NULL, *pParent = NULL; BSTR bstrQuery = NULL; VARIANT varFileName; VARIANT_BOOL varStatus; QString queryDTIFile; CHK_HR(CreateAndInitDOM(&pXMLDom)); CHK_HR(VariantFromString(datasetFileName.toStdWString().c_str(), varFileName)); CHK_HR(pXMLDom->load(varFileName, &varStatus)); /*queryDTIFile = queryString+QString("/DTI[@file_name = '%1']").arg(dtiFileName); bstrQuery = SysAllocString(queryString.toStdWString().c_str()); CHK_ALLOC(bstrQuery); CHK_HR(pXMLDom->selectSingleNode(bstrQuery, (IXMLDOMNode**)&pNode)); SysFreeString(bstrQuery); if (pNode) { return 1; }*/ bstrQuery = SysAllocString(queryString.toStdWString().c_str()); CHK_ALLOC(bstrQuery); CHK_HR(pXMLDom->selectSingleNode(bstrQuery, (IXMLDOMNode**)&pParent)); SysFreeString(bstrQuery); if (pParent) { CHK_HR(CreateElement(pXMLDom, L"DTI", &pNode)); CHK_HR(CreateAndAddAttributeNode(pXMLDom, L"file_name", dtiFileName.toStdWString().c_str(), pNode)); CHK_HR(CreateAndAddTextNode(pXMLDom, L"\n", pParent)); CHK_HR(AppendChildToParent(pNode, pParent)); CHK_HR(pXMLDom->save(varFileName)); return 1; } CleanUp: SAFE_RELEASE(pXMLDom); SAFE_RELEASE(pNode); return 0; } QString DicomImageSet::getDTIFileName(const QString &datasetFolderName, const QString &queryString) { QString datasetFileName = datasetFolderName+DATASET_FILE_NAME; HRESULT hr = S_OK; IXMLDOMDocument *pXMLDom = NULL; IXMLDOMNode *pFileNode = NULL; VARIANT_BOOL varStatus; VARIANT varFileName; BSTR bstrQuery; QStringList fileList; CHK_HR(CreateAndInitDOM(&pXMLDom)); CHK_HR(VariantFromString(datasetFileName.toStdWString().c_str(), varFileName)); CHK_HR(pXMLDom->load(varFileName, &varStatus)); if (varStatus != VARIANT_TRUE) { CHK_HR(ReportParseError(pXMLDom, "Failed to load DOM from stocks.xml.")); } bstrQuery = SysAllocString(QString(queryString+"/DTI").toStdWString().c_str()); CHK_ALLOC(bstrQuery); CHK_HR(pXMLDom->selectSingleNode(bstrQuery, &pFileNode)); if (pFileNode) { VARIANT varValue; CHK_HR(GetAttributeFromNode(pFileNode, L"file_name", &varValue)); return QString::fromWCharArray(_bstr_t(varValue)); } CleanUp: SAFE_RELEASE(pXMLDom); SAFE_RELEASE(pFileNode); return QString(); }
[ [ [ 1, 516 ] ] ]
020f4167cf65f692473bdb1220f4583fd9ccabfc
1d209ba17bfd1cb74caf736b5f0d05fa93723d65
/IMController.h
ad4a8b0276aac4df8e145a36afdbe2a3d7e01386
[]
no_license
Konnekt/SzuKacz
e6c3a44ab262499f23ad330b1915066741c83c46
45b0b73ab77564b9d59c40456889a9f719ab8edd
refs/heads/master
2021-01-18T13:46:52.654452
2008-03-03T21:43:11
2008-03-03T21:43:11
3,440,116
1
0
null
null
null
null
UTF-8
C++
false
false
13,826
h
/** * IMessage Controller class * * Licensed under The GNU Lesser General Public License * Redistributions of files must retain the above copyright notice. * * @filesource * @copyright Copyright (c) 2005-2006 Sijawusz Pur Rahnama * @link svn://konnekt.info/kaway2/ kAway2 plugin SVN Repo * @version $Revision: 98 $ * @modifiedby $LastChangedBy: sija $ * @lastmodified $Date: 2006-12-08 18:27:59 +0100 (Pt, 08 gru 2006) $ * @license http://creativecommons.org/licenses/LGPL/2.1/ */ #pragma once #ifndef __IMESSAGECTRL_H__ #define __IMESSAGECTRL_H__ #include <boost/signal.hpp> #include <boost/function.hpp> #include <boost/bind.hpp> using namespace Stamina; using namespace boost; namespace Konnekt { typedef void tIMCallback; template<typename TC, typename TR> TR (TC::* resolve_cast0(TR (TC::* pFunc)(void)))(void) { return pFunc; } template<typename TP, typename TC, typename TR> TR (TC::* resolve_cast1(TR (TC::* pFunc)(TP)))(TP) { return pFunc; } class IMController : public SharedObject<iSharedObject>, public signals::trackable { public: /* Class version */ STAMINA_OBJECT_CLASS_VERSION(IMController, iSharedObject, Version(0,2,1,0)); public: typedef function<tIMCallback(IMController*)> fOnIMessage; typedef signal<tIMCallback(IMController*)> sigOnIMessage; public: typedef std::map<String, signals::connection> tConnections; struct sObserver { tConnections connections; sigOnIMessage signal; }; struct sSubclassedAction { static const int notFound = -1; bool autoForward; int prevOwner; int parent; int id; sSubclassedAction(): id(0), parent(0), prevOwner(notFound), autoForward(false) { } sSubclassedAction(int _id, int _parent, bool _autoForward = false): id(_id), parent(_parent), prevOwner(notFound), autoForward(_autoForward) { } sSubclassedAction(int _id, int _parent, bool _autoForward, int _prevOwner): id(_id), parent(_parent), prevOwner(_prevOwner), autoForward(_autoForward) { } }; typedef std::deque<sSubclassedAction> tSubclassedActions; typedef std::map<int, sObserver*> tObservers; typedef std::map<int, int> tStaticValues; public: inline IMController(): returnCodeSet(false), returnCode(0) { // setting/unsetting Ctrl global pointer registerObserver(IM_PLUG_INIT, bind(resolve_cast0(&IMController::_plugInit), this)); registerObserver(IM_PLUG_DEINIT, bind(resolve_cast0(&IMController::_plugDeInit), this)); // actions subclassing registerObserver(IM_UI_PREPARE, bind(resolve_cast0(&IMController::_subclass), this)); // default values for common messages, may be overriden setStaticValue(IM_PLUG_NETNAME, 0); setStaticValue(IM_PLUG_PRIORITY, 0); setStaticValue(IM_PLUG_SDKVERSION, KONNEKT_SDK_V); setStaticValue(IM_PLUG_VERSION, 0); setStaticValue(IM_PLUG_CORE_V, (int) "W98"); setStaticValue(IM_PLUG_UI_V, 0); } inline virtual ~IMController() { for (tObservers::iterator it = observers.begin(); it != observers.end(); it++) { delete it->second; } for (tObservers::iterator it = actionObservers.begin(); it != actionObservers.end(); it++) { delete it->second; } } public: /* * Process incoming IMessage * @see registerObserver */ inline int process(sIMessage_base* msgBase) { sIMessage_2params* msg = static_cast<sIMessage_2params*>(msgBase); // clear residues clear(); // set im setIM(msg); // looking for static values if (staticValues.find(msg->id) != staticValues.end()) { setReturnCode(staticValues[msg->id]); } // notify global observers notifyObservers(msg); // ui action message if (isAction()) { // notify action observers notifyActionObservers(msg); // auto-forward action if (isForwardable()) { forwardAction(); } } // log IMessage if (isReturnCodeSet()) { IMLOG("[IMController<%i>::process()]: id = %i, returnCode = %i", this, msg->id, getReturnCode()); } else { // set error if no result if (Ctrl) { Ctrl->setError(IMERROR_NORESULT); } IMLOG("[IMController<%i>::process()]: id = %i", this, msg->id); } return getReturnCode(); } /* * Attach observer to specific IMessage * @param id IMessage id * @param f function which should be fired on @a id IMessage * @param priority callback priority (group) * @param pos callback position in group (signals::at_back, signals::at_front) * @param name callback name * @param overwrite overrides callback with the same @a name if any exists * @return logical true if observer was attached */ inline bool registerObserver(tIMid id, fOnIMessage f, int priority = 0, signals::connect_position pos = signals::at_back, const StringRef& name = "", bool overwrite = true) { return _registerObserver(id, f, priority, pos, name, overwrite, observers); } inline bool registerActionObserver(const sSubclassedAction& an, fOnIMessage f, int priority = 0, signals::connect_position pos = signals::at_back, const StringRef& name = "", bool overwrite = true) { if (_registerObserver(an.id, f, priority, pos, name, overwrite, actionObservers)) { subclassAction(an); return true; } return false; } inline bool registerActionObserver(int id, fOnIMessage f, int priority = 0, signals::connect_position pos = signals::at_back, const StringRef& name = "", bool overwrite = true) { return _registerObserver(id, f, priority, pos, name, overwrite, actionObservers); } inline void notifyObservers(sIMessage_2params* msg) { return _notifyObservers(im->id, observers); } inline void notifyActionObservers(sIMessage_2params* msg) { return _notifyObservers(getAN()->act.id, actionObservers); } /* Subclassing */ inline bool isSublassed(int id, int parent) { for (tSubclassedActions::iterator it = subclassedActions.begin(); it != subclassedActions.end(); it++) { if (it->id == id && it->parent == parent) return true; } return false; } inline bool isSublassed() { if (!isAction()) return false; return isSublassed(getAN()->act.id, getAN()->act.parent); } inline bool isForwardable(int id, int parent) { if (isSublassed(id, parent)) { return _getSubclassedAction(id, parent).autoForward; } return false; } inline bool isForwardable() { if (!isAction()) return false; return isForwardable(getAN()->act.id, getAN()->act.parent); } inline int getPrevOwner(int id, int parent) { if (isSublassed(id, parent)) { return _getSubclassedAction(id, parent).prevOwner; } return sSubclassedAction::notFound; } inline int getPrevOwner() { if (!isAction()) return sSubclassedAction::notFound; return getPrevOwner(getAN()->act.id, getAN()->act.parent); } inline void setForwardable(int id, int parent, bool set) { if (isSublassed(id, parent)) { _getSubclassedAction(id, parent).autoForward = set; } } inline void setForwardable(bool set) { if (!isAction()) return; return setForwardable(getAN()->act.id, getAN()->act.parent, set); } inline void subclassAction(const sSubclassedAction& an) { if (!isSublassed(an.id, an.parent)) { subclassedActions.push_back(an); } } inline void subclassAction(int id, int parent, bool autoForward = false) { return subclassAction(sSubclassedAction(id, parent, autoForward)); } inline IMController* forwardAction(bool _setReturnCode = true) { if (isAction() && isSublassed()) { int retValue = Ctrl->IMessageDirect(IM_UIACTION, getPrevOwner(), (int) getAN()); if (_setReturnCode) setReturnCode(retValue); } return this; } // Cleanin' variables inline void clear() { returnCodeSet = false; returnCode = NULL; im = NULL; } inline int getReturnCode() { return returnCode; } inline void setReturnCode(int code) { returnCodeSet = true; returnCode = code; } /* * Set string as return value * @warning { this method uses internal buffer which can be overridden by * commonly used functions like @c GETSTR in all flavors. } */ inline void setReturnValue(const StringRef& value) { // creating temp buffer char* buff = (char*) Ctrl->GetTempBuffer(value.size() + 1); // cleaning memory memset(buff, 0, value.size() + 1); // copying data memcpy(buff, value.a_str(), value.size()); // setting return code to pointer to internal, temp buffer setReturnCode((int) buff); } inline void setSuccess() { return setReturnCode(1); } inline void setFailure() { return setReturnCode(-1); } inline bool isReturnCodeSet() { return returnCodeSet; } inline sIMessage_2params* getIM() { return im; } inline IMController* setIM(sIMessage_2params* im) { this->im = im; return this; } inline bool isAction() { return getIM()->id == IM_UIACTION; } inline sUIActionNotify_2params* getAN() { if (!isAction()) return NULL; return static_cast<sUIActionNotify_2params*>((sUIActionNotify_base*) getIM()->p1); } inline void setStaticValue(int id, int value) { staticValues[id] = value; } inline bool isObserved(int id) { return _isObserved(id, observers); } inline bool isActionObserved(int id) { return _isObserved(id, actionObservers); } protected: /* Actions subclassing */ inline sSubclassedAction& _getSubclassedAction(int id, int parent) { for (tSubclassedActions::iterator it = subclassedActions.begin(); it != subclassedActions.end(); it++) { if (id == it->id && parent == it->parent) return *it; } return sSubclassedAction(); } /* Observers related methods */ inline bool _isObserved(int id, tObservers& list) { if (list.find(id) != list.end()) { return !list[id]->signal.empty(); } return false; } /* inline void _dbgObservers() { for (tObservers::iterator it = observers.begin(); it != observers.end(); it++) { for (tConnections::iterator it2 = it->second->connections.begin(); it2 != it->second->connections.end(); it2++) { IMLOG("Observer[%i].connection: %s", it->first, it2->first.c_str()); } } for (tObservers::iterator it = actionObservers.begin(); it != actionObservers.end(); it++) { for (tConnections::iterator it2 = it->second->connections.begin(); it2 != it->second->connections.end(); it2++) { IMLOG("ActionObserver[%i].connection: %s", it->first, it2->first.c_str()); } } } */ inline void _notifyObservers(int id, tObservers& list) { if (!_isObserved(id, list)) { return; } list[id]->signal(this); } inline bool _registerObserver(int id, fOnIMessage f, int priority, signals::connect_position pos, StringRef name, bool overwrite, tObservers& list) { if (f.empty()) { return false; } if (list.find(id) == list.end()) { list[id] = new sObserver; } if (!name.length()) { name = "unnamed." + inttostr(list[id]->connections.size()); } if (list[id]->connections.find(name) != list[id]->connections.end()) { if (overwrite) { list[id]->connections[name].disconnect(); } else { return false; } } return (list[id]->connections[name] = list[id]->signal.connect(priority, f, pos)).connected(); } /* Callbacks */ inline tIMCallback _plugInit() { Plug_Init(getIM()->p1, getIM()->p2); return setSuccess(); } inline tIMCallback _plugDeInit() { Plug_Deinit(getIM()->p1, getIM()->p2); return setSuccess(); } inline tIMCallback _subclass() { for (tSubclassedActions::iterator it = subclassedActions.begin(); it != subclassedActions.end(); it++) { sUIActionInfo nfo(it->parent, it->id); nfo.mask = UIAIM_ALL; nfo.txt = new char[100]; nfo.txtSize = 99; UIActionGet(nfo); if (!(it->prevOwner = Ctrl->ICMessage(IMI_ACTION_GETOWNER, (int)&nfo.act))) { it->prevOwner = Ctrl->ICMessage(IMC_PLUG_ID, 0); } IMLOG("[IMController<%i>::subclass()]: name = %s, id = %i, parent = %i, prevOwner = %i", this, nfo.txt, it->id, it->parent, it->prevOwner); Ctrl->ICMessage(IMI_ACTION_REMOVE, (int)&nfo.act); Ctrl->ICMessage(IMI_ACTION, (int)&nfo); delete [] nfo.txt; } } protected: tSubclassedActions subclassedActions; tStaticValues staticValues; tObservers actionObservers; tObservers observers; sIMessage_2params* im; bool returnCodeSet; int returnCode; }; } #endif // __IMESSAGECTRL_H__
[ [ [ 1, 9 ], [ 11, 11 ], [ 13, 43 ], [ 45, 116 ], [ 120, 127 ], [ 129, 184 ], [ 186, 188 ], [ 190, 200 ], [ 202, 212 ], [ 214, 216 ], [ 229, 235 ], [ 237, 250 ], [ 252, 313 ], [ 323, 371 ], [ 373, 438 ] ], [ [ 10, 10 ], [ 12, 12 ], [ 44, 44 ], [ 117, 119 ], [ 128, 128 ], [ 185, 185 ], [ 189, 189 ], [ 201, 201 ], [ 213, 213 ], [ 217, 228 ], [ 236, 236 ], [ 251, 251 ], [ 314, 322 ], [ 372, 372 ] ] ]
1f7f3ef3379dd83b1215d1747088065d0cbc54a9
30d6818e6f7d4ad459d751226b8e91ab07990ce4
/OSGControl/trunk/OSGControl/OSG/MFC_OSG.cpp
e33bdec3086c353d1af815a86fab4bb0746e1ab0
[]
no_license
TenYearsADream/osgkeyframer
cd7052e56d28e459ad6b28fea77a76f4df5d5fe7
f6b8a47827f9869a1d3b99c311ca29c455fead0f
refs/heads/master
2020-05-15T14:59:38.475978
2011-04-20T15:18:38
2011-04-20T15:18:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,393
cpp
// MFC_OSG.cpp : implementation of the cOSG class // #include "stdafx.h" #include "MFC_OSG.h" #include "osgEarthUtil\Viewpoint" LPARAM FLOAT_TO_LPARAM(double d) { // Convert double to float - this allows caller to pass double as parameter // without being concerned about warning messages. We explicitly cast here // to avoid those messages. const float f = (float)d; // This function relies on the fact that in Win32 a float is the same size // as LPARAM. If this assert fails (i.e. Win64) then a different method of // packing a float into an LPARAM will be needed. ASSERT(sizeof(float)==sizeof(LPARAM)); // Return the float binary data directly as an LPARAM return *((LPARAM *)&f); } float LPARAM_TO_FLOAT(LPARAM l) { // This function relies on the fact that in Win32 a float is the same size // as LPARAM. If this assert fails (i.e. Win64) then a different method of // packing a float into an LPARAM will be needed. ASSERT(sizeof(float)==sizeof(LPARAM)); // Return the LPARAM binary data directly as a float return *((float *)&l); } cOSG::cOSG(HWND placeholder,HWND parent) : m_hWnd(placeholder), m_hParentWnd(parent), m_simTime(DBL_MAX), m_apm_isPaused(false), m_apm_loaded(false) { } cOSG::~cOSG() { mViewer->setDone(true); Sleep(1000); mViewer->setSceneData(0); mRoot = 0; mModel = 0; mViewer->stopThreading(); delete mViewer; } void cOSG::EnqueueRequest(osgRequest* req) { m_RequestQueue.push(req); } void cOSG::EnqueueRequest(byte type, LPARAM lParam) { osgRequest* req = new osgRequest(); req->lParam = lParam; req->type = type; EnqueueRequest(req); } void cOSG::InitOSG() { // Init different parts of OSG InitManipulators(); InitCameraConfig(); //InitSceneGraph(); //mViewer->getViewerBase()->setRunMaxFrameRate(30); //mViewer->getViewerBase()->setThreadingModel(osgViewer::ViewerBase::ThreadingModel::CullThreadPerCameraDrawThreadPerContext); //mViewer->getViewerBase()->setRunFrameScheme(osgViewer::ViewerBase::FrameScheme::ON_DEMAND); } void cOSG::InitManipulators(void) { m_earthManip = new osgEarth::Util::EarthManipulator(); } void cOSG::InitSceneGraph(std::string modelName) { mViewer->setSceneData(0); // Init the main Root Node/Group mRoot = new osg::Group; // Load the Model from the model name mModel = osgDB::readNodeFile(modelName); // Optimize the model osgUtil::Optimizer optimizer; optimizer.optimize(mModel.get()); optimizer.reset(); // Add the model to the scene mRoot->addChild(mModel.get()); // Set the Scene Data mViewer->setSceneData(mRoot.get()); // Realize the Viewer mViewer->realize(); } void cOSG::InitCameraConfig(void) { // Local Variable to hold window size data RECT rect; // Create the viewer for this window mViewer = new osgViewer::Viewer(); // Add a Stats Handler to the viewer mViewer->addEventHandler(new osgViewer::StatsHandler); // add the screen capture handler mViewer->addEventHandler(new osgViewer::ScreenCaptureHandler); // Get the current window size ::GetWindowRect(m_hWnd, &rect); // Init the GraphicsContext Traits osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits; // Init the Windata Variable that holds the handle for the Window to display OSG in. osg::ref_ptr<osg::Referenced> windata = new osgViewer::GraphicsWindowWin32::WindowData(m_hWnd); // Setup the traits parameters traits->x = 0; traits->y = 0; traits->width = rect.right - rect.left; traits->height = rect.bottom - rect.top; traits->windowDecoration = false; traits->doubleBuffer = true; traits->sharedContext = 0; traits->setInheritedWindowPixelFormat = true; traits->inheritedWindowData = windata; // Create the Graphics Context osg::GraphicsContext* gc = osg::GraphicsContext::createGraphicsContext(traits.get()); // Init a new Camera (Master for this View) osg::ref_ptr<osg::Camera> camera = new osg::Camera; // Assign Graphics Context to the Camera camera->setGraphicsContext(gc); // Set the viewport for the Camera camera->setViewport(new osg::Viewport(traits->x, traits->y, traits->width, traits->height)); // Add the Camera to the Viewer mViewer->addSlave(camera.get()); // Add the Camera Manipulator to the Viewer mViewer->setCameraManipulator(m_earthManip); // Correct aspect ratio double fovy,aspectRatio,z1,z2; mViewer->getCamera()->getProjectionMatrixAsPerspective(fovy,aspectRatio,z1,z2); aspectRatio=double(traits->width)/double(traits->height); mViewer->getCamera()->setProjectionMatrixAsPerspective(fovy,aspectRatio,z1,z2); } void cOSG::PreFrameUpdate() { // Do any preframe updates in this routine //check if there are any requests waiting in the queue osgRequest* req; while(!m_RequestQueue.empty()) { if(m_RequestQueue.try_pop(req)) HandleMsg(req); } } void cOSG::HandleMsg(osgRequest* &req) { switch(req->type) { case REQ_SETCAMMATRIX: { osg::Matrixd* m = (osg::Matrixd*) req->lParam; mViewer->getCameraManipulator()->setByMatrix(*m); delete m; break; } case REQ_SETCAMVIEWPOINT: { if(!m_apm_loaded){ osgEarth::Util::Viewpoint* vp = (osgEarth::Util::Viewpoint*) req->lParam; m_earthManip->setViewpoint(*vp); delete vp; } break; } case REQ_STARTANIMATION: { osg::ref_ptr<osg::AnimationPath> ap = (osg::AnimationPath*)req->lParam; ap->unref(); m_apm = new COSGAnimationPathManipulator(ap); m_apm->getAnimationPath()->setLoopMode(osg::AnimationPath::LoopMode::NO_LOOPING); mViewer->setCameraManipulator(m_apm); mViewer->setReferenceTime(); m_apm_loaded = true; //Alert Control that an Animation has begun PostMessage(m_hParentWnd,UM_OSGNOTIFY,RPLY_ANIMATIONSTARTED,0); break; } case REQ_RESETANIMATION: { mViewer->setReferenceTime(); break; } case REQ_TOGGLEANIMATION: { mViewer->getEventQueue()->keyPress('p'); break; } case REQ_STOPANIMATION: { //swap manipulators mViewer->setCameraManipulator(m_earthManip,false); m_apm = 0; m_apm_loaded = false; //Alert Control that an Animation has ended PostMessage(m_hParentWnd,UM_OSGNOTIFY,RPLY_ANIMATIONCOMPLETED,0); break; } case REQ_LOADEARTHFILE: { PostMessage(m_hParentWnd,UM_OSGNOTIFY,RPLY_LOADINGEARTH,STAGE_LOADING); m_modelName = *(std::string*)req->lParam; InitSceneGraph(m_modelName); delete (std::string*)req->lParam; PostMessage(m_hParentWnd,UM_OSGNOTIFY,RPLY_LOADINGEARTH,STAGE_COMPLETED); } } delete req; req = 0; } void cOSG::PostFrameUpdate() { double reftime = mViewer->getFrameStamp()->getReferenceTime(); //Do any postframe updates in this routine if(m_apm_loaded && !m_apm->animationIsPaused()) { if( m_apm->animationCompleted( reftime )) { //post last animationtime reply PostMessage(m_hParentWnd,UM_OSGNOTIFY,RPLY_ANIMATIONTIME,FLOAT_TO_LPARAM(m_apm->getAnimationTime(reftime))); //swap manipulators mViewer->setCameraManipulator(m_earthManip,false); m_apm = 0; m_apm_loaded = false; //Alert Control that an Animation has ended PostMessage(m_hParentWnd,UM_OSGNOTIFY,RPLY_ANIMATIONCOMPLETED,0); } else { PostMessage(m_hParentWnd,UM_OSGNOTIFY,RPLY_ANIMATIONTIME,FLOAT_TO_LPARAM(m_apm->getAnimationTime(reftime))); } } //if we need to turn off the animation } void cOSG::Render(void* ptr) { cOSG* osg = (cOSG*)ptr; osgViewer::Viewer* viewer = osg->getViewer(); // You have two options for the main viewer loop // viewer->run() or // while(!viewer->done()) { viewer->frame(); } //viewer->run(); while(!viewer->done()) { osg->PreFrameUpdate(); viewer->frame(); osg->PostFrameUpdate(); Sleep(10); // Use this command if you need to allow other processes to have cpu time } // For some reason this has to be here to avoid issue: // if you have multiple OSG windows up // and you exit one then all stop rendering // AfxMessageBox(_T("Exit Rendering Thread")); viewer->releaseGLObjects(); osg::FrameStamp now = *viewer->getFrameStamp(); viewer->getDatabasePager()->updateSceneGraph(now); _endthread(); }
[ "[email protected]@c71c211c-a3f6-341e-745a-b305fdfe3b14" ]
[ [ [ 1, 305 ] ] ]
9cb4f059ed372a0a4f3041cea31f267f1da36885
a4bb94cfe9c0bee937a6ec584e10f6fe126372ff
/Drivers/Video/Console/Console.cpp
61c3ebf8a02b2cd6a3ad948192fecf6816fce2aa
[]
no_license
MatiasNAmendola/magneto
564d0bdb3534d4b7118e74cc8b50601afaad10a0
33bc34a49a34923908883775f94eb266be5af0f9
refs/heads/master
2020-04-05T23:36:22.535156
2009-07-04T09:14:01
2009-07-04T09:14:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
48,172
cpp
/* * Module Name: Console * File: Silver\Console\Console.cpp * */ #include "Drivers\Video\Console\Console.h" #if !defined ( __CONSOLE_CPP_ ) #define __CONSOLE_CPP_ char Console::is_console; unsigned int Console::last_result; unsigned char * Console::vid_mem; unsigned int Console::curr_x, Console::curr_y, Console::c_maxx, Console::c_maxy, Console::textattrib, Console::fgcolor, Console::bgcolor; const char * CONSOLE_ID = "CONSOLE"; Console console; unsigned char _40x25_text[] = { /* MISC */ 0x67, /* SEQ */ 0x03, 0x08, 0x03, 0x00, 0x02, /* CRTC */ 0x2D, 0x27, 0x28, 0x90, 0x2B, 0xA0, 0xBF, 0x1F, 0x00, 0x4F, 0x0D, 0x0E, 0x00, 0x00, 0x00, 0xA0, 0x9C, 0x8E, 0x8F, 0x14, 0x1F, 0x96, 0xB9, 0xA3, 0xFF, /* GC */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0E, 0x00, 0xFF, /* AC */ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x14, 0x07, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x0C, 0x00, 0x0F, 0x08, 0x00, }; unsigned char _40x50_text[] = { /* MISC */ 0x67, /* SEQ */ 0x03, 0x08, 0x03, 0x00, 0x02, /* CRTC */ 0x2D, 0x27, 0x28, 0x90, 0x2B, 0xA0, 0xBF, 0x1F, 0x00, 0x47, 0x06, 0x07, 0x00, 0x00, 0x04, 0x60, 0x9C, 0x8E, 0x8F, 0x14, 0x1F, 0x96, 0xB9, 0xA3, 0xFF, /* GC */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0E, 0x00, 0xFF, /* AC */ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x14, 0x07, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x0C, 0x00, 0x0F, 0x08, 0x00, }; unsigned char _80x25_text[] = { /* MISC */ 0x67, /* SEQ */ 0x03, 0x00, 0x03, 0x00, 0x02, /* CRTC */ 0x5F, 0x4F, 0x50, 0x82, 0x55, 0x81, 0xBF, 0x1F, 0x00, 0x4F, 0x0D, 0x0E, 0x00, 0x00, 0x00, 0x50, 0x9C, 0x0E, 0x8F, 0x28, 0x1F, 0x96, 0xB9, 0xA3, 0xFF, /* GC */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0E, 0x00, 0xFF, /* AC */ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x14, 0x07, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x0C, 0x00, 0x0F, 0x08, 0x00 }; unsigned char _80x50_text[] = { /* MISC */ 0x67, /* SEQ */ 0x03, 0x00, 0x03, 0x00, 0x02, /* CRTC */ 0x5F, 0x4F, 0x50, 0x82, 0x55, 0x81, 0xBF, 0x1F, 0x00, 0x47, 0x06, 0x07, 0x00, 0x00, 0x01, 0x40, 0x9C, 0x8E, 0x8F, 0x28, 0x1F, 0x96, 0xB9, 0xA3, 0xFF, /* GC */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0E, 0x00, 0xFF, /* AC */ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x14, 0x07, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x0C, 0x00, 0x0F, 0x08, 0x00, }; unsigned char _90x30_text[] = { /* MISC */ 0xE7, /* SEQ */ 0x03, 0x01, 0x03, 0x00, 0x02, /* CRTC */ 0x6B, 0x59, 0x5A, 0x82, 0x60, 0x8D, 0x0B, 0x3E, 0x00, 0x4F, 0x0D, 0x0E, 0x00, 0x00, 0x00, 0x00, 0xEA, 0x0C, 0xDF, 0x2D, 0x10, 0xE8, 0x05, 0xA3, 0xFF, /* GC */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0E, 0x00, 0xFF, /* AC */ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x14, 0x07, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x0C, 0x00, 0x0F, 0x08, 0x00, }; unsigned char _90x60_text[] = { /* MISC */ 0xE7, /* SEQ */ 0x03, 0x01, 0x03, 0x00, 0x02, /* CRTC */ 0x6B, 0x59, 0x5A, 0x82, 0x60, 0x8D, 0x0B, 0x3E, 0x00, 0x47, 0x06, 0x07, 0x00, 0x00, 0x00, 0x00, 0xEA, 0x0C, 0xDF, 0x2D, 0x08, 0xE8, 0x05, 0xA3, 0xFF, /* GC */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0E, 0x00, 0xFF, /* AC */ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x14, 0x07, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x0C, 0x00, 0x0F, 0x08, 0x00, }; unsigned char g_8x8_font[2048] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0x81, 0xA5, 0x81, 0xBD, 0x99, 0x81, 0x7E, 0x7E, 0xFF, 0xDB, 0xFF, 0xC3, 0xE7, 0xFF, 0x7E, 0x6C, 0xFE, 0xFE, 0xFE, 0x7C, 0x38, 0x10, 0x00, 0x10, 0x38, 0x7C, 0xFE, 0x7C, 0x38, 0x10, 0x00, 0x38, 0x7C, 0x38, 0xFE, 0xFE, 0x92, 0x10, 0x7C, 0x00, 0x10, 0x38, 0x7C, 0xFE, 0x7C, 0x38, 0x7C, 0x00, 0x00, 0x18, 0x3C, 0x3C, 0x18, 0x00, 0x00, 0xFF, 0xFF, 0xE7, 0xC3, 0xC3, 0xE7, 0xFF, 0xFF, 0x00, 0x3C, 0x66, 0x42, 0x42, 0x66, 0x3C, 0x00, 0xFF, 0xC3, 0x99, 0xBD, 0xBD, 0x99, 0xC3, 0xFF, 0x0F, 0x07, 0x0F, 0x7D, 0xCC, 0xCC, 0xCC, 0x78, 0x3C, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x7E, 0x18, 0x3F, 0x33, 0x3F, 0x30, 0x30, 0x70, 0xF0, 0xE0, 0x7F, 0x63, 0x7F, 0x63, 0x63, 0x67, 0xE6, 0xC0, 0x99, 0x5A, 0x3C, 0xE7, 0xE7, 0x3C, 0x5A, 0x99, 0x80, 0xE0, 0xF8, 0xFE, 0xF8, 0xE0, 0x80, 0x00, 0x02, 0x0E, 0x3E, 0xFE, 0x3E, 0x0E, 0x02, 0x00, 0x18, 0x3C, 0x7E, 0x18, 0x18, 0x7E, 0x3C, 0x18, 0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x66, 0x00, 0x7F, 0xDB, 0xDB, 0x7B, 0x1B, 0x1B, 0x1B, 0x00, 0x3E, 0x63, 0x38, 0x6C, 0x6C, 0x38, 0x86, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x7E, 0x7E, 0x7E, 0x00, 0x18, 0x3C, 0x7E, 0x18, 0x7E, 0x3C, 0x18, 0xFF, 0x18, 0x3C, 0x7E, 0x18, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x18, 0x7E, 0x3C, 0x18, 0x00, 0x00, 0x18, 0x0C, 0xFE, 0x0C, 0x18, 0x00, 0x00, 0x00, 0x30, 0x60, 0xFE, 0x60, 0x30, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xC0, 0xC0, 0xFE, 0x00, 0x00, 0x00, 0x24, 0x66, 0xFF, 0x66, 0x24, 0x00, 0x00, 0x00, 0x18, 0x3C, 0x7E, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x7E, 0x3C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3C, 0x3C, 0x18, 0x18, 0x00, 0x18, 0x00, 0x6C, 0x6C, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6C, 0x6C, 0xFE, 0x6C, 0xFE, 0x6C, 0x6C, 0x00, 0x18, 0x7E, 0xC0, 0x7C, 0x06, 0xFC, 0x18, 0x00, 0x00, 0xC6, 0xCC, 0x18, 0x30, 0x66, 0xC6, 0x00, 0x38, 0x6C, 0x38, 0x76, 0xDC, 0xCC, 0x76, 0x00, 0x30, 0x30, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x30, 0x60, 0x60, 0x60, 0x30, 0x18, 0x00, 0x60, 0x30, 0x18, 0x18, 0x18, 0x30, 0x60, 0x00, 0x00, 0x66, 0x3C, 0xFF, 0x3C, 0x66, 0x00, 0x00, 0x00, 0x18, 0x18, 0x7E, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x30, 0x00, 0x00, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x06, 0x0C, 0x18, 0x30, 0x60, 0xC0, 0x80, 0x00, 0x7C, 0xCE, 0xDE, 0xF6, 0xE6, 0xC6, 0x7C, 0x00, 0x30, 0x70, 0x30, 0x30, 0x30, 0x30, 0xFC, 0x00, 0x78, 0xCC, 0x0C, 0x38, 0x60, 0xCC, 0xFC, 0x00, 0x78, 0xCC, 0x0C, 0x38, 0x0C, 0xCC, 0x78, 0x00, 0x1C, 0x3C, 0x6C, 0xCC, 0xFE, 0x0C, 0x1E, 0x00, 0xFC, 0xC0, 0xF8, 0x0C, 0x0C, 0xCC, 0x78, 0x00, 0x38, 0x60, 0xC0, 0xF8, 0xCC, 0xCC, 0x78, 0x00, 0xFC, 0xCC, 0x0C, 0x18, 0x30, 0x30, 0x30, 0x00, 0x78, 0xCC, 0xCC, 0x78, 0xCC, 0xCC, 0x78, 0x00, 0x78, 0xCC, 0xCC, 0x7C, 0x0C, 0x18, 0x70, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x18, 0x18, 0x30, 0x18, 0x30, 0x60, 0xC0, 0x60, 0x30, 0x18, 0x00, 0x00, 0x00, 0x7E, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x60, 0x30, 0x18, 0x0C, 0x18, 0x30, 0x60, 0x00, 0x3C, 0x66, 0x0C, 0x18, 0x18, 0x00, 0x18, 0x00, 0x7C, 0xC6, 0xDE, 0xDE, 0xDC, 0xC0, 0x7C, 0x00, 0x30, 0x78, 0xCC, 0xCC, 0xFC, 0xCC, 0xCC, 0x00, 0xFC, 0x66, 0x66, 0x7C, 0x66, 0x66, 0xFC, 0x00, 0x3C, 0x66, 0xC0, 0xC0, 0xC0, 0x66, 0x3C, 0x00, 0xF8, 0x6C, 0x66, 0x66, 0x66, 0x6C, 0xF8, 0x00, 0xFE, 0x62, 0x68, 0x78, 0x68, 0x62, 0xFE, 0x00, 0xFE, 0x62, 0x68, 0x78, 0x68, 0x60, 0xF0, 0x00, 0x3C, 0x66, 0xC0, 0xC0, 0xCE, 0x66, 0x3A, 0x00, 0xCC, 0xCC, 0xCC, 0xFC, 0xCC, 0xCC, 0xCC, 0x00, 0x78, 0x30, 0x30, 0x30, 0x30, 0x30, 0x78, 0x00, 0x1E, 0x0C, 0x0C, 0x0C, 0xCC, 0xCC, 0x78, 0x00, 0xE6, 0x66, 0x6C, 0x78, 0x6C, 0x66, 0xE6, 0x00, 0xF0, 0x60, 0x60, 0x60, 0x62, 0x66, 0xFE, 0x00, 0xC6, 0xEE, 0xFE, 0xFE, 0xD6, 0xC6, 0xC6, 0x00, 0xC6, 0xE6, 0xF6, 0xDE, 0xCE, 0xC6, 0xC6, 0x00, 0x38, 0x6C, 0xC6, 0xC6, 0xC6, 0x6C, 0x38, 0x00, 0xFC, 0x66, 0x66, 0x7C, 0x60, 0x60, 0xF0, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xD6, 0x7C, 0x0E, 0x00, 0xFC, 0x66, 0x66, 0x7C, 0x6C, 0x66, 0xE6, 0x00, 0x7C, 0xC6, 0xE0, 0x78, 0x0E, 0xC6, 0x7C, 0x00, 0xFC, 0xB4, 0x30, 0x30, 0x30, 0x30, 0x78, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xFC, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x78, 0x30, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xD6, 0xFE, 0x6C, 0x00, 0xC6, 0xC6, 0x6C, 0x38, 0x6C, 0xC6, 0xC6, 0x00, 0xCC, 0xCC, 0xCC, 0x78, 0x30, 0x30, 0x78, 0x00, 0xFE, 0xC6, 0x8C, 0x18, 0x32, 0x66, 0xFE, 0x00, 0x78, 0x60, 0x60, 0x60, 0x60, 0x60, 0x78, 0x00, 0xC0, 0x60, 0x30, 0x18, 0x0C, 0x06, 0x02, 0x00, 0x78, 0x18, 0x18, 0x18, 0x18, 0x18, 0x78, 0x00, 0x10, 0x38, 0x6C, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x30, 0x30, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0x76, 0x00, 0xE0, 0x60, 0x60, 0x7C, 0x66, 0x66, 0xDC, 0x00, 0x00, 0x00, 0x78, 0xCC, 0xC0, 0xCC, 0x78, 0x00, 0x1C, 0x0C, 0x0C, 0x7C, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x78, 0xCC, 0xFC, 0xC0, 0x78, 0x00, 0x38, 0x6C, 0x64, 0xF0, 0x60, 0x60, 0xF0, 0x00, 0x00, 0x00, 0x76, 0xCC, 0xCC, 0x7C, 0x0C, 0xF8, 0xE0, 0x60, 0x6C, 0x76, 0x66, 0x66, 0xE6, 0x00, 0x30, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00, 0x0C, 0x00, 0x1C, 0x0C, 0x0C, 0xCC, 0xCC, 0x78, 0xE0, 0x60, 0x66, 0x6C, 0x78, 0x6C, 0xE6, 0x00, 0x70, 0x30, 0x30, 0x30, 0x30, 0x30, 0x78, 0x00, 0x00, 0x00, 0xCC, 0xFE, 0xFE, 0xD6, 0xD6, 0x00, 0x00, 0x00, 0xB8, 0xCC, 0xCC, 0xCC, 0xCC, 0x00, 0x00, 0x00, 0x78, 0xCC, 0xCC, 0xCC, 0x78, 0x00, 0x00, 0x00, 0xDC, 0x66, 0x66, 0x7C, 0x60, 0xF0, 0x00, 0x00, 0x76, 0xCC, 0xCC, 0x7C, 0x0C, 0x1E, 0x00, 0x00, 0xDC, 0x76, 0x62, 0x60, 0xF0, 0x00, 0x00, 0x00, 0x7C, 0xC0, 0x70, 0x1C, 0xF8, 0x00, 0x10, 0x30, 0xFC, 0x30, 0x30, 0x34, 0x18, 0x00, 0x00, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0xCC, 0xCC, 0xCC, 0x78, 0x30, 0x00, 0x00, 0x00, 0xC6, 0xC6, 0xD6, 0xFE, 0x6C, 0x00, 0x00, 0x00, 0xC6, 0x6C, 0x38, 0x6C, 0xC6, 0x00, 0x00, 0x00, 0xCC, 0xCC, 0xCC, 0x7C, 0x0C, 0xF8, 0x00, 0x00, 0xFC, 0x98, 0x30, 0x64, 0xFC, 0x00, 0x1C, 0x30, 0x30, 0xE0, 0x30, 0x30, 0x1C, 0x00, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x00, 0xE0, 0x30, 0x30, 0x1C, 0x30, 0x30, 0xE0, 0x00, 0x76, 0xDC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x6C, 0xC6, 0xC6, 0xFE, 0x00, 0x7C, 0xC6, 0xC0, 0xC6, 0x7C, 0x0C, 0x06, 0x7C, 0x00, 0xCC, 0x00, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x1C, 0x00, 0x78, 0xCC, 0xFC, 0xC0, 0x78, 0x00, 0x7E, 0x81, 0x3C, 0x06, 0x3E, 0x66, 0x3B, 0x00, 0xCC, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0x76, 0x00, 0xE0, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0x76, 0x00, 0x30, 0x30, 0x78, 0x0C, 0x7C, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC0, 0x78, 0x0C, 0x38, 0x7E, 0x81, 0x3C, 0x66, 0x7E, 0x60, 0x3C, 0x00, 0xCC, 0x00, 0x78, 0xCC, 0xFC, 0xC0, 0x78, 0x00, 0xE0, 0x00, 0x78, 0xCC, 0xFC, 0xC0, 0x78, 0x00, 0xCC, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00, 0x7C, 0x82, 0x38, 0x18, 0x18, 0x18, 0x3C, 0x00, 0xE0, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00, 0xC6, 0x10, 0x7C, 0xC6, 0xFE, 0xC6, 0xC6, 0x00, 0x30, 0x30, 0x00, 0x78, 0xCC, 0xFC, 0xCC, 0x00, 0x1C, 0x00, 0xFC, 0x60, 0x78, 0x60, 0xFC, 0x00, 0x00, 0x00, 0x7F, 0x0C, 0x7F, 0xCC, 0x7F, 0x00, 0x3E, 0x6C, 0xCC, 0xFE, 0xCC, 0xCC, 0xCE, 0x00, 0x78, 0x84, 0x00, 0x78, 0xCC, 0xCC, 0x78, 0x00, 0x00, 0xCC, 0x00, 0x78, 0xCC, 0xCC, 0x78, 0x00, 0x00, 0xE0, 0x00, 0x78, 0xCC, 0xCC, 0x78, 0x00, 0x78, 0x84, 0x00, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0xE0, 0x00, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0xCC, 0x00, 0xCC, 0xCC, 0x7C, 0x0C, 0xF8, 0xC3, 0x18, 0x3C, 0x66, 0x66, 0x3C, 0x18, 0x00, 0xCC, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0x78, 0x00, 0x18, 0x18, 0x7E, 0xC0, 0xC0, 0x7E, 0x18, 0x18, 0x38, 0x6C, 0x64, 0xF0, 0x60, 0xE6, 0xFC, 0x00, 0xCC, 0xCC, 0x78, 0x30, 0xFC, 0x30, 0xFC, 0x30, 0xF8, 0xCC, 0xCC, 0xFA, 0xC6, 0xCF, 0xC6, 0xC3, 0x0E, 0x1B, 0x18, 0x3C, 0x18, 0x18, 0xD8, 0x70, 0x1C, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0x76, 0x00, 0x38, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00, 0x00, 0x1C, 0x00, 0x78, 0xCC, 0xCC, 0x78, 0x00, 0x00, 0x1C, 0x00, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0xF8, 0x00, 0xB8, 0xCC, 0xCC, 0xCC, 0x00, 0xFC, 0x00, 0xCC, 0xEC, 0xFC, 0xDC, 0xCC, 0x00, 0x3C, 0x6C, 0x6C, 0x3E, 0x00, 0x7E, 0x00, 0x00, 0x38, 0x6C, 0x6C, 0x38, 0x00, 0x7C, 0x00, 0x00, 0x18, 0x00, 0x18, 0x18, 0x30, 0x66, 0x3C, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0x0C, 0x0C, 0x00, 0x00, 0xC6, 0xCC, 0xD8, 0x36, 0x6B, 0xC2, 0x84, 0x0F, 0xC3, 0xC6, 0xCC, 0xDB, 0x37, 0x6D, 0xCF, 0x03, 0x18, 0x00, 0x18, 0x18, 0x3C, 0x3C, 0x18, 0x00, 0x00, 0x33, 0x66, 0xCC, 0x66, 0x33, 0x00, 0x00, 0x00, 0xCC, 0x66, 0x33, 0x66, 0xCC, 0x00, 0x00, 0x22, 0x88, 0x22, 0x88, 0x22, 0x88, 0x22, 0x88, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0xDB, 0xF6, 0xDB, 0x6F, 0xDB, 0x7E, 0xD7, 0xED, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xF8, 0x18, 0x18, 0x18, 0x18, 0x18, 0xF8, 0x18, 0xF8, 0x18, 0x18, 0x18, 0x36, 0x36, 0x36, 0x36, 0xF6, 0x36, 0x36, 0x36, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x36, 0x36, 0x36, 0x00, 0x00, 0xF8, 0x18, 0xF8, 0x18, 0x18, 0x18, 0x36, 0x36, 0xF6, 0x06, 0xF6, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x00, 0x00, 0xFE, 0x06, 0xF6, 0x36, 0x36, 0x36, 0x36, 0x36, 0xF6, 0x06, 0xFE, 0x00, 0x00, 0x00, 0x36, 0x36, 0x36, 0x36, 0xFE, 0x00, 0x00, 0x00, 0x18, 0x18, 0xF8, 0x18, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1F, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1F, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0xFF, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1F, 0x18, 0x1F, 0x18, 0x18, 0x18, 0x36, 0x36, 0x36, 0x36, 0x37, 0x36, 0x36, 0x36, 0x36, 0x36, 0x37, 0x30, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0x30, 0x37, 0x36, 0x36, 0x36, 0x36, 0x36, 0xF7, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xF7, 0x36, 0x36, 0x36, 0x36, 0x36, 0x37, 0x30, 0x37, 0x36, 0x36, 0x36, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x36, 0x36, 0xF7, 0x00, 0xF7, 0x36, 0x36, 0x36, 0x18, 0x18, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x36, 0x36, 0x36, 0x36, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x3F, 0x00, 0x00, 0x00, 0x18, 0x18, 0x1F, 0x18, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0x18, 0x1F, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x3F, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xFF, 0x36, 0x36, 0x36, 0x18, 0x18, 0xFF, 0x18, 0xFF, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0x18, 0x18, 0x18, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xDC, 0xC8, 0xDC, 0x76, 0x00, 0x00, 0x78, 0xCC, 0xF8, 0xCC, 0xF8, 0xC0, 0xC0, 0x00, 0xFC, 0xCC, 0xC0, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0xFE, 0x6C, 0x6C, 0x6C, 0x6C, 0x00, 0xFC, 0xCC, 0x60, 0x30, 0x60, 0xCC, 0xFC, 0x00, 0x00, 0x00, 0x7E, 0xD8, 0xD8, 0xD8, 0x70, 0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x7C, 0x60, 0xC0, 0x00, 0x76, 0xDC, 0x18, 0x18, 0x18, 0x18, 0x00, 0xFC, 0x30, 0x78, 0xCC, 0xCC, 0x78, 0x30, 0xFC, 0x38, 0x6C, 0xC6, 0xFE, 0xC6, 0x6C, 0x38, 0x00, 0x38, 0x6C, 0xC6, 0xC6, 0x6C, 0x6C, 0xEE, 0x00, 0x1C, 0x30, 0x18, 0x7C, 0xCC, 0xCC, 0x78, 0x00, 0x00, 0x00, 0x7E, 0xDB, 0xDB, 0x7E, 0x00, 0x00, 0x06, 0x0C, 0x7E, 0xDB, 0xDB, 0x7E, 0x60, 0xC0, 0x38, 0x60, 0xC0, 0xF8, 0xC0, 0x60, 0x38, 0x00, 0x78, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x00, 0x00, 0x7E, 0x00, 0x7E, 0x00, 0x7E, 0x00, 0x00, 0x18, 0x18, 0x7E, 0x18, 0x18, 0x00, 0x7E, 0x00, 0x60, 0x30, 0x18, 0x30, 0x60, 0x00, 0xFC, 0x00, 0x18, 0x30, 0x60, 0x30, 0x18, 0x00, 0xFC, 0x00, 0x0E, 0x1B, 0x1B, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xD8, 0xD8, 0x70, 0x18, 0x18, 0x00, 0x7E, 0x00, 0x18, 0x18, 0x00, 0x00, 0x76, 0xDC, 0x00, 0x76, 0xDC, 0x00, 0x00, 0x38, 0x6C, 0x6C, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x0F, 0x0C, 0x0C, 0x0C, 0xEC, 0x6C, 0x3C, 0x1C, 0x58, 0x6C, 0x6C, 0x6C, 0x6C, 0x00, 0x00, 0x00, 0x70, 0x98, 0x30, 0x60, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x3C, 0x3C, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; unsigned char g_8x16_font[4096] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0x81, 0xA5, 0x81, 0x81, 0xBD, 0x99, 0x81, 0x81, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0xFF, 0xDB, 0xFF, 0xFF, 0xC3, 0xE7, 0xFF, 0xFF, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6C, 0xFE, 0xFE, 0xFE, 0xFE, 0x7C, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x7C, 0xFE, 0x7C, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3C, 0x3C, 0xE7, 0xE7, 0xE7, 0x99, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3C, 0x7E, 0xFF, 0xFF, 0x7E, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3C, 0x3C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE7, 0xC3, 0xC3, 0xE7, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x66, 0x42, 0x42, 0x66, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC3, 0x99, 0xBD, 0xBD, 0x99, 0xC3, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x1E, 0x0E, 0x1A, 0x32, 0x78, 0xCC, 0xCC, 0xCC, 0xCC, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x66, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x7E, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0x33, 0x3F, 0x30, 0x30, 0x30, 0x30, 0x70, 0xF0, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x63, 0x7F, 0x63, 0x63, 0x63, 0x63, 0x67, 0xE7, 0xE6, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0xDB, 0x3C, 0xE7, 0x3C, 0xDB, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0xF0, 0xF8, 0xFE, 0xF8, 0xF0, 0xE0, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x06, 0x0E, 0x1E, 0x3E, 0xFE, 0x3E, 0x1E, 0x0E, 0x06, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3C, 0x7E, 0x18, 0x18, 0x18, 0x18, 0x7E, 0x3C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x66, 0x66, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0xDB, 0xDB, 0xDB, 0x7B, 0x1B, 0x1B, 0x1B, 0x1B, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0x60, 0x38, 0x6C, 0xC6, 0xC6, 0x6C, 0x38, 0x0C, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFE, 0xFE, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3C, 0x7E, 0x18, 0x18, 0x18, 0x18, 0x7E, 0x3C, 0x18, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3C, 0x7E, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x7E, 0x3C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x0C, 0xFE, 0x0C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x60, 0xFE, 0x60, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xC0, 0xC0, 0xC0, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x28, 0x6C, 0xFE, 0x6C, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x38, 0x7C, 0x7C, 0xFE, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFE, 0x7C, 0x7C, 0x38, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3C, 0x3C, 0x3C, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x66, 0x66, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6C, 0x6C, 0xFE, 0x6C, 0x6C, 0x6C, 0xFE, 0x6C, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x7C, 0xC6, 0xC2, 0xC0, 0x7C, 0x06, 0x86, 0xC6, 0x7C, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC2, 0xC6, 0x0C, 0x18, 0x30, 0x60, 0xC6, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x6C, 0x6C, 0x38, 0x76, 0xDC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x30, 0x30, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x18, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x18, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x18, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x18, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x3C, 0xFF, 0x3C, 0x66, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x7E, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x06, 0x0C, 0x18, 0x30, 0x60, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xCE, 0xD6, 0xD6, 0xE6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x38, 0x78, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0x06, 0x0C, 0x18, 0x30, 0x60, 0xC0, 0xC6, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0x06, 0x06, 0x3C, 0x06, 0x06, 0x06, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x1C, 0x3C, 0x6C, 0xCC, 0xFE, 0x0C, 0x0C, 0x0C, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xC0, 0xC0, 0xC0, 0xFC, 0x0E, 0x06, 0x06, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x60, 0xC0, 0xC0, 0xFC, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xC6, 0x06, 0x06, 0x0C, 0x18, 0x30, 0x30, 0x30, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0x7E, 0x06, 0x06, 0x06, 0x0C, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x18, 0x18, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x0C, 0x18, 0x30, 0x60, 0x30, 0x18, 0x0C, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x00, 0x00, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x30, 0x18, 0x0C, 0x06, 0x0C, 0x18, 0x30, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC6, 0x0C, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xDE, 0xDE, 0xDE, 0xDC, 0xC0, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x6C, 0xC6, 0xC6, 0xFE, 0xC6, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0x66, 0x66, 0x66, 0x7C, 0x66, 0x66, 0x66, 0x66, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x66, 0xC2, 0xC0, 0xC0, 0xC0, 0xC0, 0xC2, 0x66, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x6C, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x6C, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x66, 0x62, 0x68, 0x78, 0x68, 0x60, 0x62, 0x66, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x66, 0x62, 0x68, 0x78, 0x68, 0x60, 0x60, 0x60, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x66, 0xC2, 0xC0, 0xC0, 0xDE, 0xC6, 0xC6, 0x66, 0x3A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xFE, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0xCC, 0xCC, 0xCC, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE6, 0x66, 0x6C, 0x6C, 0x78, 0x78, 0x6C, 0x66, 0x66, 0xE6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x62, 0x66, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xEE, 0xFE, 0xFE, 0xD6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xE6, 0xF6, 0xFE, 0xDE, 0xCE, 0xC6, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x6C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x6C, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0x66, 0x66, 0x66, 0x7C, 0x60, 0x60, 0x60, 0x60, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xD6, 0xDE, 0x7C, 0x0C, 0x0E, 0x00, 0x00, 0x00, 0x00, 0xFC, 0x66, 0x66, 0x66, 0x7C, 0x6C, 0x66, 0x66, 0x66, 0xE6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC6, 0x60, 0x38, 0x0C, 0x06, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0x7E, 0x5A, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x6C, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xD6, 0xD6, 0xFE, 0x6C, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xC6, 0x6C, 0x6C, 0x38, 0x38, 0x6C, 0x6C, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xC6, 0x86, 0x0C, 0x18, 0x30, 0x60, 0xC2, 0xC6, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0x70, 0x38, 0x1C, 0x0E, 0x06, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x6C, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x30, 0x30, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0x60, 0x60, 0x78, 0x6C, 0x66, 0x66, 0x66, 0x66, 0xDC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC0, 0xC0, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1C, 0x0C, 0x0C, 0x3C, 0x6C, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xFE, 0xC0, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x6C, 0x64, 0x60, 0xF0, 0x60, 0x60, 0x60, 0x60, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x7C, 0x0C, 0xCC, 0x78, 0x00, 0x00, 0x00, 0xE0, 0x60, 0x60, 0x6C, 0x76, 0x66, 0x66, 0x66, 0x66, 0xE6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x06, 0x00, 0x0E, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x66, 0x66, 0x3C, 0x00, 0x00, 0x00, 0xE0, 0x60, 0x60, 0x66, 0x6C, 0x78, 0x78, 0x6C, 0x66, 0xE6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xEC, 0xFE, 0xD6, 0xD6, 0xD6, 0xD6, 0xD6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xDC, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xDC, 0x66, 0x66, 0x66, 0x66, 0x66, 0x7C, 0x60, 0x60, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x7C, 0x0C, 0x0C, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xDC, 0x76, 0x62, 0x60, 0x60, 0x60, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0x60, 0x38, 0x0C, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x30, 0x30, 0xFC, 0x30, 0x30, 0x30, 0x30, 0x36, 0x1C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xC6, 0xC6, 0xD6, 0xD6, 0xFE, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0x6C, 0x38, 0x38, 0x38, 0x6C, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7E, 0x06, 0x0C, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xCC, 0x18, 0x30, 0x60, 0xC6, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E, 0x18, 0x18, 0x18, 0x70, 0x18, 0x18, 0x18, 0x18, 0x0E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, 0x18, 0x18, 0x18, 0x0E, 0x18, 0x18, 0x18, 0x18, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xDC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x6C, 0xC6, 0xC6, 0xC6, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x66, 0xC2, 0xC0, 0xC0, 0xC0, 0xC2, 0x66, 0x3C, 0x0C, 0x06, 0x7C, 0x00, 0x00, 0x00, 0x00, 0xCC, 0xCC, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x18, 0x30, 0x00, 0x7C, 0xC6, 0xFE, 0xC0, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x6C, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xCC, 0xCC, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x30, 0x18, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x6C, 0x38, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x66, 0x60, 0x60, 0x66, 0x3C, 0x0C, 0x06, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x6C, 0x00, 0x7C, 0xC6, 0xFE, 0xC0, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xC6, 0x00, 0x7C, 0xC6, 0xFE, 0xC0, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x30, 0x18, 0x00, 0x7C, 0xC6, 0xFE, 0xC0, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x66, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3C, 0x66, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x30, 0x18, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xC6, 0x10, 0x38, 0x6C, 0xC6, 0xC6, 0xFE, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x38, 0x6C, 0x38, 0x00, 0x38, 0x6C, 0xC6, 0xC6, 0xFE, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x18, 0x30, 0x60, 0x00, 0xFE, 0x66, 0x60, 0x7C, 0x60, 0x60, 0x66, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xCC, 0x76, 0x36, 0x7E, 0xD8, 0xD8, 0x6E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x6C, 0xCC, 0xCC, 0xFE, 0xCC, 0xCC, 0xCC, 0xCC, 0xCE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x6C, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xC6, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x30, 0x18, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x78, 0xCC, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x30, 0x18, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xC6, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7E, 0x06, 0x0C, 0x78, 0x00, 0x00, 0xC6, 0xC6, 0x00, 0x38, 0x6C, 0xC6, 0xC6, 0xC6, 0xC6, 0x6C, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xC6, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x3C, 0x66, 0x60, 0x60, 0x60, 0x66, 0x3C, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x6C, 0x64, 0x60, 0xF0, 0x60, 0x60, 0x60, 0x60, 0xE6, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x66, 0x3C, 0x18, 0x7E, 0x18, 0x7E, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xCC, 0xCC, 0xF8, 0xC4, 0xCC, 0xDE, 0xCC, 0xCC, 0xCC, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E, 0x1B, 0x18, 0x18, 0x18, 0x7E, 0x18, 0x18, 0x18, 0x18, 0x18, 0xD8, 0x70, 0x00, 0x00, 0x00, 0x18, 0x30, 0x60, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x18, 0x30, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x30, 0x60, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x30, 0x60, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xDC, 0x00, 0xDC, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x00, 0x00, 0x00, 0x76, 0xDC, 0x00, 0xC6, 0xE6, 0xF6, 0xFE, 0xDE, 0xCE, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x6C, 0x6C, 0x3E, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x6C, 0x6C, 0x38, 0x00, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x30, 0x00, 0x30, 0x30, 0x60, 0xC0, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xC0, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x06, 0x06, 0x06, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xC0, 0xC2, 0xC6, 0xCC, 0x18, 0x30, 0x60, 0xCE, 0x93, 0x06, 0x0C, 0x1F, 0x00, 0x00, 0x00, 0xC0, 0xC0, 0xC2, 0xC6, 0xCC, 0x18, 0x30, 0x66, 0xCE, 0x9A, 0x3F, 0x06, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x3C, 0x3C, 0x3C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x33, 0x66, 0xCC, 0x66, 0x33, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xCC, 0x66, 0x33, 0x66, 0xCC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0xDD, 0x77, 0xDD, 0x77, 0xDD, 0x77, 0xDD, 0x77, 0xDD, 0x77, 0xDD, 0x77, 0xDD, 0x77, 0xDD, 0x77, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xF8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xF8, 0x18, 0xF8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xF6, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x18, 0xF8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x36, 0x36, 0x36, 0x36, 0x36, 0xF6, 0x06, 0xF6, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x06, 0xF6, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xF6, 0x06, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0xF8, 0x18, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1F, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xFF, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1F, 0x18, 0x1F, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x37, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x37, 0x30, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0x30, 0x37, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xF7, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xF7, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x37, 0x30, 0x37, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x36, 0x36, 0x36, 0x36, 0xF7, 0x00, 0xF7, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x18, 0x18, 0x18, 0x18, 0x18, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1F, 0x18, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0x18, 0x1F, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xFF, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x18, 0x18, 0x18, 0x18, 0x18, 0xFF, 0x18, 0xFF, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xDC, 0xD8, 0xD8, 0xD8, 0xDC, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xC6, 0xFC, 0xC6, 0xC6, 0xFC, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xC6, 0xC6, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xFE, 0x6C, 0x6C, 0x6C, 0x6C, 0x6C, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xC6, 0x60, 0x30, 0x18, 0x30, 0x60, 0xC6, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0xD8, 0xD8, 0xD8, 0xD8, 0xD8, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x7C, 0x60, 0x60, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xDC, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0x18, 0x3C, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x6C, 0xC6, 0xC6, 0xFE, 0xC6, 0xC6, 0x6C, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x6C, 0xC6, 0xC6, 0xC6, 0x6C, 0x6C, 0x6C, 0x6C, 0xEE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1E, 0x30, 0x18, 0x0C, 0x3E, 0x66, 0x66, 0x66, 0x66, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0xDB, 0xDB, 0xDB, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x06, 0x7E, 0xCF, 0xDB, 0xF3, 0x7E, 0x60, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1C, 0x30, 0x60, 0x60, 0x7C, 0x60, 0x60, 0x60, 0x30, 0x1C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x00, 0x00, 0xFE, 0x00, 0x00, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x7E, 0x18, 0x18, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x18, 0x0C, 0x06, 0x0C, 0x18, 0x30, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x18, 0x30, 0x60, 0x30, 0x18, 0x0C, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E, 0x1B, 0x1B, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xD8, 0xD8, 0xD8, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x7E, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xDC, 0x00, 0x76, 0xDC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x6C, 0x6C, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0xEC, 0x6C, 0x6C, 0x3C, 0x1C, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD8, 0x6C, 0x6C, 0x6C, 0x6C, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, 0x98, 0x30, 0x60, 0xC8, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0x7C, 0x7C, 0x7C, 0x7C, 0x7C, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; Console::Console() { is_console = 0; if(detect_card_type()==COLOR_CARD) vid_mem = (unsigned char*) 0xB8000; else if(detect_card_type()==MONO_CARD) vid_mem = (unsigned char*) 0xB0000; curr_x = curr_y = 0; c_maxx = 79; c_maxy = 24; last_result = 0; textattrib = WHITE; bgcolor = BLACK; fgcolor = WHITE; set_res(TEXT_90x30); clrscr(); } Console::~Console() { ; } int Console::detect_card_type() { /* check for monochrome or color VGA emulation */ if((inportb(VGA_MISC_READ) & 0x01) == 1) return COLOR_CARD; else return MONO_CARD; } void Console::update_cursor() { unsigned int position = (curr_y * (c_maxx + 1) + curr_x); outportb(0x3D4, 0x0F); outportb(0x3D5, (unsigned char)(position&0xFF)); outportb(0x3D4, 0x0E); outportb(0x3D5, (unsigned char)((position>>8)&0xFF)); } void Console::scroll_line_up(void) { memcpy(vid_mem, vid_mem + (c_maxx+1)*2, (c_maxy*(c_maxx+1)*2)); memsetb(vid_mem + (c_maxx+1) * (c_maxy)*2, NULL, (c_maxx+1)*2); } void Console::write_regs(unsigned char *regs) { unsigned i; /* write MISCELLANEOUS reg */ outportb(VGA_MISC_WRITE, *regs); regs++; outportb(VGA_INSTAT_READ, 0x00); /* write SEQUENCER regs */ for(i = 0; i < VGA_NUM_SEQ_REGS; i++) { outportb(VGA_SEQ_INDEX, i); outportb(VGA_SEQ_DATA, *regs); regs++; } /* unlock CRTC registers */ outportb(VGA_CRTC_INDEX, 0x03); outportb(VGA_CRTC_DATA, inportb(VGA_CRTC_DATA) | 0x80); outportb(VGA_CRTC_INDEX, 0x11); outportb(VGA_CRTC_DATA, inportb(VGA_CRTC_DATA) & ~0x80); /* make sure they remain unlocked */ regs[0x03] |= 0x80; regs[0x11] &= ~0x80; /* write CRTC regs */ for(i = 0; i < VGA_NUM_CRTC_REGS; i++) { outportb(VGA_CRTC_INDEX, i); outportb(VGA_CRTC_DATA, *regs); regs++; } /* write GRAPHICS CONTROLLER regs */ for(i = 0; i < VGA_NUM_GC_REGS; i++) { outportb(VGA_GC_INDEX, i); outportb(VGA_GC_DATA, *regs); regs++; } /* write ATTRIBUTE CONTROLLER regs */ for(i = 0; i < VGA_NUM_AC_REGS; i++) { (void)inportb(VGA_INSTAT_READ); outportb(VGA_AC_INDEX, i); outportb(VGA_AC_WRITE, *regs); regs++; } /* lock 16-color palette and unblank display */ (void)inportb(VGA_INSTAT_READ); outportb(VGA_AC_INDEX, 0x20); } int Console::init() { if(is_console == 1) { last_result = CONSOLE_ALREADY_INITIALIZED; return KMSG_FALIURE; } else { is_console = 1; cout<<"\nConsole:"; cout<<"\n\tColor Emulation Detected"; cout<<"\n\tVGA+ "; cout<<c_maxx + 1<<" x "<<c_maxy + 1; cout<<"\n\tUsing WHITE on BLACK"; return KMSG_SUCCESS; } return last_result; } int Console::set_res(unsigned int mode) { switch(mode) { case TEXT_40x25: write_regs(_40x25_text); c_maxx = 39; c_maxy = 24; break; case TEXT_40x50: write_regs(_40x50_text); c_maxx = 39; c_maxy = 49; break; case TEXT_80x25: write_regs(_80x25_text); c_maxx = 79; c_maxy = 24; break; case TEXT_80x50: write_regs(_80x50_text); c_maxx = 79; c_maxy = 49; break; case TEXT_90x30: write_regs(_90x30_text); c_maxx = 89; c_maxy = 29; break; case TEXT_90x60: write_regs(_90x60_text); c_maxx = 89; c_maxy = 59; break; default: last_result = MODE_NOT_SUPPORTED; break; }; clrscr(); return last_result; } void Console::settextbackground(int col) { if(col>7); else if(col<0); else bgcolor=col; textattrib=(bgcolor*16)+fgcolor; } void Console::settextcolor(int col) { if(col > 15); else if(col < 0); else fgcolor = col; textattrib = (bgcolor*16) + fgcolor; } void Console::settextattrib(int col) { textattrib = col; } int Console::gettextcolor() { return fgcolor; } int Console::gettextbgcolor() { return bgcolor; } int Console::gettextattrib() { return textattrib; } int Console::wherex(void) { return curr_x + 1; } int Console::wherey(void) { return curr_y + 1; } int Console::getmaxx() { return c_maxx + 1; } int Console::getmaxy() { return c_maxy + 1; } void Console::gotoxy(unsigned int x, unsigned int y) { if((y < 1)&&(x < 1)); else if((y>c_maxy)&&(x>c_maxx)); else { curr_x = x - 1; curr_y = y - 1; update_cursor(); } } void Console::clrscr() { unsigned int i; for (i=0; i != (c_maxx * c_maxy); i=i+1) putch(' '); curr_x = 0; curr_y = 0; update_cursor(); } void Console::putch(const unsigned char ch) { int i; switch(ch) { case BUFFER_UNDERFLOW: break; case BUFFER_OVERFLOW: break; case '\r': case '\n': curr_x = 0; curr_y = curr_y + 1; if(curr_y > c_maxy) { curr_x = 0; curr_y = c_maxy; scroll_line_up(); } break; case '\t': for(i=0; i!=TAB; i=i+1) { putch(' '); } break; case '\b': curr_x = curr_x - 1; //Bug at pos 0,0 if(curr_x < 0) { curr_x = c_maxx; curr_y = curr_y - 1; } if(curr_y < 0) { curr_x = 0; curr_y = 0; } vid_mem[(((curr_y * (c_maxx + 1)) + curr_x) * 2)] = ' '; vid_mem[(((curr_y * (c_maxx + 1)) + curr_x) * 2) + 1] = textattrib; break; default: if(ch >= ' ') { vid_mem[(((curr_y * (c_maxx + 1)) + curr_x) * 2)] = ch; vid_mem[(((curr_y * (c_maxx + 1)) + curr_x) * 2) + 1] = textattrib; curr_x = curr_x + 1; if(curr_x > c_maxx) { putch('\n'); } } break; } update_cursor(); } int Console::writeln(const char *buf) { while(*buf != '\0') { putch(*buf); buf++; } } void Console::writeint(const unsigned int num) { unsigned _num = num; char _tnum[6]; int _i=0; while(_num!=0) { _tnum[_i]=itoa(_num%10); _num=_num/10; _i=_i+1; } _tnum[_i]='\0'; for(_i=0;_tnum[_i]!='\0';_i=_i+1); for(_i=_i-1;_i>=0;_i=_i-1) { putch(_tnum[_i]); } } void Console::writeint(const int num) { int _num = num; if(_num < 0) { _num = _num * -1; putch('-'); } char _tnum[10]; int _i=0; while(_num!=0) { _tnum[_i]=itoa(_num%10); _num=_num/10; _i=_i+1; } _tnum[_i]='\0'; for(_i=0;_tnum[_i]!='\0';_i=_i+1); for(_i=_i-1;_i>=0;_i=_i-1) { putch(_tnum[_i]); } } #endif
[ [ [ 1, 985 ] ] ]
5f4ad3b86f5c87c82dff7dfa474d1a44c8c1182a
188058ec6dbe8b1a74bf584ecfa7843be560d2e5
/GodDK/util/concurrent/atomic/AtomicLong.cpp
23dec3dd54b742986350aab20913a471d4fc001f
[]
no_license
mason105/red5cpp
636e82c660942e2b39c4bfebc63175c8539f7df0
fcf1152cb0a31560af397f24a46b8402e854536e
refs/heads/master
2021-01-10T07:21:31.412996
2007-08-23T06:29:17
2007-08-23T06:29:17
36,223,621
0
0
null
null
null
null
UTF-8
C++
false
false
387
cpp
#include ".\atomiclong.h" namespace goddk { namespace util { namespace concurrent { namespace Atomic{ AtomicLong::AtomicLong() { value = 0; valueOffset = value; } AtomicLong::AtomicLong(jlong initialValue) { value = initialValue; valueOffset = value; } AtomicLong::~AtomicLong(void) { } } } } }
[ "soaris@46205fef-a337-0410-8429-7db05d171fc8" ]
[ [ [ 1, 24 ] ] ]
c5a07767de264595e109a95c0e02cf506ffeaec2
f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0
/Depend/MyGUI/Tools/SkinEditor/PropertyInt2Control.cpp
6b3785bf47875cec2af06bf51aa06d1db7fa625f
[]
no_license
lxinhcn/starworld
79ed06ca49d4064307ae73156574932d6185dbab
86eb0fb8bd268994454b0cfe6419ffef3fc0fc80
refs/heads/master
2021-01-10T07:43:51.858394
2010-09-15T02:38:48
2010-09-15T02:38:48
47,859,019
2
1
null
null
null
null
UTF-8
C++
false
false
2,091
cpp
/*! @file @author Albert Semenov @date 08/2010 */ #include "precompiled.h" #include "PropertyInt2Control.h" #include "Localise.h" namespace tools { PropertyInt2Control::PropertyInt2Control(MyGUI::Widget* _parent) : wraps::BaseLayout("PropertyEditControl.layout", _parent), mEdit(nullptr) { assignWidget(mEdit, "Edit"); mEdit->eventEditTextChange += MyGUI::newDelegate(this, &PropertyInt2Control::notifyEditTextChange); } PropertyInt2Control::~PropertyInt2Control() { mEdit->eventEditTextChange -= MyGUI::newDelegate(this, &PropertyInt2Control::notifyEditTextChange); } void PropertyInt2Control::updateProperty() { Property* proper = getProperty(); if (proper != nullptr) { mEdit->setEnabled(!proper->getReadOnly()); mEdit->setCaption(proper->getValue()); bool validate = isValidate(); setColour(validate); } else { mEdit->setCaption(""); mEdit->setEnabled(false); } } void PropertyInt2Control::notifyEditTextChange(MyGUI::Edit* _sender) { Property* proper = getProperty(); if (proper != nullptr) { bool validate = isValidate(); if (validate) proper->setValue(getClearValue(), getTypeName()); setColour(validate); } } bool PropertyInt2Control::isValidate() { MyGUI::UString value = mEdit->getOnlyText(); int value1 = 0; int value2 = 0; if (!MyGUI::utility::parseComplex(value, value1, value2)) return false; return true; } MyGUI::UString PropertyInt2Control::getClearValue() { MyGUI::UString value = mEdit->getOnlyText(); int value1 = 0; int value2 = 0; if (MyGUI::utility::parseComplex(value, value1, value2)) return MyGUI::utility::toString(value1, " ", value2); return ""; } void PropertyInt2Control::setColour(bool _validate) { MyGUI::UString value = mEdit->getOnlyText(); if (!_validate) value = replaceTags("ColourError") + value; size_t index = mEdit->getTextCursor(); mEdit->setCaption(value); mEdit->setTextCursor(index); } } // namespace tools
[ "albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c" ]
[ [ [ 1, 93 ] ] ]
8adca379c8e22570a6160b01f02ffc7f4672dd81
c94aa08b9f0574e67a04f6f4213665e35219ab8d
/DSound/ExceptionHandler.cpp
2d466e7aa7366b89273549c7a99841af0223e6d1
[]
no_license
xzlinux/dsbridge
47f2e2c80abc5313b756c22aa9ae0bd9624ac207
bc7cb0413a554b07b9d2894b9ea9734a03835ce3
refs/heads/master
2021-12-10T04:47:47.540806
2009-07-31T16:16:34
2009-07-31T16:16:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,240
cpp
/* Copyright 2009 Jesper Svennevid Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ExceptionHandler.h" #include <stdio.h> namespace dsbridge { ExceptionHandler::ExceptionHandler() { } ExceptionHandler::~ExceptionHandler() { } LONG WINAPI ExceptionHandler::filter(const char* name, struct _EXCEPTION_POINTERS* info) { // uncomment to catch exception in debugger //return EXCEPTION_CONTINUE_SEARCH; char buf[256]; ExceptionHandler handler; if (handler.createDump(GetCurrentThreadId(), name, info)) { sprintf_s(buf, sizeof(buf), "Exception in DSBridge (%s)\n\nDetails have been written to dsound.mdmp,\nlook in installation directory.", name); } else { sprintf_s(buf, sizeof(buf), "Exception in DSBridge (%s)\n\nCould not generate minidump, exception information is not available.", name); } MessageBox(0, buf, "DSBridge Exception Handler", MB_ICONEXCLAMATION|MB_OK); return EXCEPTION_EXECUTE_HANDLER; } bool ExceptionHandler::createDump(DWORD thread, const char* name, struct _EXCEPTION_POINTERS* info) { bool success = false; HANDLE dumpFile = INVALID_HANDLE_VALUE; do { if (!initialize()) { break; } dumpFile = CreateFile("dsound.mdmp", GENERIC_WRITE, 0, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); if (dumpFile == INVALID_HANDLE_VALUE) { break; } MINIDUMP_EXCEPTION_INFORMATION miniInfo; miniInfo.ThreadId = thread; miniInfo.ExceptionPointers = info; miniInfo.ClientPointers = TRUE; if (!MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), dumpFile, MiniDumpNormal, &miniInfo, 0, 0)) { break; } success = true; } while (0); if (dumpFile != INVALID_HANDLE_VALUE) { CloseHandle(dumpFile); } return success; } bool ExceptionHandler::initialize() { m_module = LoadLibrary("dbghelp.dll"); if (!m_module) { return false; } MiniDumpWriteDump = reinterpret_cast<MINIDUMPWRITEDUMP>(GetProcAddress(m_module, "MiniDumpWriteDump")); return !!MiniDumpWriteDump; } }
[ [ [ 1, 118 ] ] ]
e44615917eb6bd5cf4f91fddcf203cb6fce11423
f177993b13e97f9fecfc0e751602153824dfef7e
/ImProSln/MyLib/CameraDS.cpp
9452ca16aa15464d2bbed1cffa5478f53911151b
[]
no_license
svn2github/imtophooksln
7bd7412947d6368ce394810f479ebab1557ef356
bacd7f29002135806d0f5047ae47cbad4c03f90e
refs/heads/master
2020-05-20T04:00:56.564124
2010-09-24T09:10:51
2010-09-24T09:10:51
11,787,598
1
0
null
null
null
null
GB18030
C++
false
false
10,181
cpp
#include "CameraDS.h" CCameraDS::CCameraDS() { m_pRenderFilter = NULL; m_pMediaEvent = NULL; m_pSampleGrabberFilter = NULL; m_pDeviceFilter = NULL; m_pCameraOutput = NULL; m_pRenderInputPin = NULL; m_pSampleGrabber = NULL; m_pGrabberInput = NULL; m_pGrabberOutput = NULL; } CCameraDS::~CCameraDS() { CloseCamera(); } void CCameraDS::CloseCamera() { UnInitDS(); m_pDeviceFilter = NULL; m_pSampleGrabberFilter = NULL; m_pCameraOutput = NULL; m_pRenderFilter = NULL; m_pRenderInputPin = NULL; m_pSampleGrabber = NULL; m_pGrabberInput = NULL; m_pGrabberOutput = NULL; } bool CCameraDS::OpenCamera(int nCamID, bool bDisplayProperties, int nWidth, int nHeight) { HRESULT hr = S_OK; // Create the Filter Graph Manager. hr = CreateGraph((IGraphBuilder**)&m_pGraph); hr = CreateFilters(nCamID, bDisplayProperties, nWidth, nHeight); hr = ConnectGraph(); hr = ConfigFilters(); return true; } HRESULT CCameraDS::ConfigFilters() { m_pSampleGrabber->SetBufferSamples(TRUE); return S_OK; } HRESULT CCameraDS::ConnectGraph() { HRESULT hr; hr = m_pGraph->Connect(m_pCameraOutput, m_pGrabberInput); if (FAILED(hr)) return hr; hr = m_pGraph->Connect(m_pGrabberOutput, m_pRenderInputPin); return hr; } HRESULT CCameraDS::CreateFilters(int nCamID, bool bDisplayProperties, int nWidth, int nHeight) { HRESULT hr; hr = CoCreateInstance(CLSID_VideoRenderer, NULL, CLSCTX_INPROC_SERVER, IID_IBaseFilter, (LPVOID*) &m_pRenderFilter); hr = CoCreateInstance(CLSID_SampleGrabber, NULL, CLSCTX_INPROC_SERVER, IID_IBaseFilter, (LPVOID *)&m_pSampleGrabberFilter); hr = m_pGraph->AddFilter(m_pRenderFilter, L"Video Renderer"); hr = m_pSampleGrabberFilter->QueryInterface(IID_ISampleGrabber, (void**)&m_pSampleGrabber); m_pGraph->AddFilter(m_pSampleGrabberFilter, L"Sample Grabber"); // Bind Device Filter. We know the device because the id was passed in BindFilter(nCamID, &m_pDeviceFilter); m_pGraph->AddFilter(m_pDeviceFilter, L"Camera"); CComPtr<IEnumPins> pEnum; m_pDeviceFilter->EnumPins(&pEnum); hr = pEnum->Reset(); hr = pEnum->Next(1, &m_pCameraOutput, NULL); pEnum = NULL; m_pSampleGrabberFilter->EnumPins(&pEnum); pEnum->Reset(); hr = pEnum->Next(1, &m_pGrabberInput, NULL); pEnum = NULL; m_pSampleGrabberFilter->EnumPins(&pEnum); pEnum->Reset(); pEnum->Skip(1); hr = pEnum->Next(1, &m_pGrabberOutput, NULL); pEnum = NULL; m_pRenderFilter->EnumPins(&pEnum); pEnum->Reset(); hr = pEnum->Next(1, &m_pRenderInputPin, NULL); //SetCrossBar(); if (bDisplayProperties) { CComPtr<ISpecifyPropertyPages> pPages; HRESULT hr = m_pCameraOutput->QueryInterface(IID_ISpecifyPropertyPages, (void**)&pPages); if (SUCCEEDED(hr)) { PIN_INFO PinInfo; m_pCameraOutput->QueryPinInfo(&PinInfo); CAUUID caGUID; pPages->GetPages(&caGUID); OleCreatePropertyFrame(NULL, 0, 0, L"Property Sheet", 1, (IUnknown **)&(m_pCameraOutput.p), caGUID.cElems, caGUID.pElems, 0, 0, NULL); CoTaskMemFree(caGUID.pElems); PinInfo.pFilter->Release(); } pPages = NULL; } else { ////////////////////////////////////////////////////////////////////////////// // 加入由 lWidth和lHeight设置的摄像头的宽和高 的功能,默认320*240 // by flymanbox @2009-01-24 ////////////////////////////////////////////////////////////////////////////// int _Width = nWidth, _Height = nHeight; IAMStreamConfig* iconfig; iconfig = NULL; hr = m_pCameraOutput->QueryInterface(IID_IAMStreamConfig, (void**)&iconfig); AM_MEDIA_TYPE* pmt; if(iconfig->GetFormat(&pmt) !=S_OK) { //printf("GetFormat Failed ! \n"); return false; } VIDEOINFOHEADER* phead; if ( pmt->formattype == FORMAT_VideoInfo) { phead=( VIDEOINFOHEADER*)pmt->pbFormat; phead->bmiHeader.biWidth = _Width; phead->bmiHeader.biHeight = _Height; if(( hr=iconfig->SetFormat(pmt)) != S_OK ) { return false; } } iconfig->Release(); iconfig=NULL; MYFREEMEDIATYPE(*pmt); } return S_OK; } bool CCameraDS::BindFilter(int nCamID, IBaseFilter **pFilter) { if (nCamID < 0) return false; // enumerate all video capture devices CComPtr<ICreateDevEnum> pCreateDevEnum; HRESULT hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, IID_ICreateDevEnum, (void**)&pCreateDevEnum); if (hr != NOERROR) { return false; } CComPtr<IEnumMoniker> pEm; hr = pCreateDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, &pEm, 0); if (hr != NOERROR) { return false; } pEm->Reset(); ULONG cFetched; IMoniker *pM; int index = 0; while(hr = pEm->Next(1, &pM, &cFetched), hr==S_OK, index <= nCamID) { IPropertyBag *pBag; hr = pM->BindToStorage(0, 0, IID_IPropertyBag, (void **)&pBag); if(SUCCEEDED(hr)) { VARIANT var; var.vt = VT_BSTR; hr = pBag->Read(L"FriendlyName", &var, NULL); if (hr == NOERROR) { if (index == nCamID) { pM->BindToObject(0, 0, IID_IBaseFilter, (void**)pFilter); } SysFreeString(var.bstrVal); } pBag->Release(); } pM->Release(); index++; } pCreateDevEnum = NULL; return true; } void CCameraDS::SetCrossBar() { int i; IAMCrossbar *pXBar1 = NULL; ICaptureGraphBuilder2 *pBuilder = NULL; HRESULT hr = CoCreateInstance(CLSID_CaptureGraphBuilder2, NULL, CLSCTX_INPROC_SERVER, IID_ICaptureGraphBuilder2, (void **)&pBuilder); if (SUCCEEDED(hr)) { hr = pBuilder->SetFiltergraph(m_pGraph); } hr = pBuilder->FindInterface(&LOOK_UPSTREAM_ONLY, NULL, m_pDeviceFilter,IID_IAMCrossbar, (void**)&pXBar1); if (SUCCEEDED(hr)) { long OutputPinCount; long InputPinCount; long PinIndexRelated; long PhysicalType; long inPort = 0; long outPort = 0; pXBar1->get_PinCounts(&OutputPinCount,&InputPinCount); for( i =0;i<InputPinCount;i++) { pXBar1->get_CrossbarPinInfo(TRUE,i,&PinIndexRelated,&PhysicalType); if(PhysConn_Video_Composite==PhysicalType) { inPort = i; break; } } for( i =0;i<OutputPinCount;i++) { pXBar1->get_CrossbarPinInfo(FALSE,i,&PinIndexRelated,&PhysicalType); if(PhysConn_Video_VideoDecoder==PhysicalType) { outPort = i; break; } } if(S_OK==pXBar1->CanRoute(outPort,inPort)) { pXBar1->Route(outPort,inPort); } pXBar1->Release(); } pBuilder->Release(); } int CCameraDS::CameraCount() { int count = 0; CoInitialize(NULL); // enumerate all video capture devices CComPtr<ICreateDevEnum> pCreateDevEnum; HRESULT hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, IID_ICreateDevEnum, (void**)&pCreateDevEnum); CComPtr<IEnumMoniker> pEm; hr = pCreateDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, &pEm, 0); if (hr != NOERROR) { return count; } pEm->Reset(); ULONG cFetched; IMoniker *pM; while(hr = pEm->Next(1, &pM, &cFetched), hr==S_OK) { count++; } pCreateDevEnum = NULL; pEm = NULL; return count; } int CCameraDS::CameraName(int nCamID, WCHAR* sName, int nBufferSize) { int count = 0; CoInitialize(NULL); // enumerate all video capture devices CComPtr<ICreateDevEnum> pCreateDevEnum; HRESULT hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, IID_ICreateDevEnum, (void**)&pCreateDevEnum); CComPtr<IEnumMoniker> pEm; hr = pCreateDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, &pEm, 0); if (hr != NOERROR) return 0; pEm->Reset(); ULONG cFetched; IMoniker *pM; while(hr = pEm->Next(1, &pM, &cFetched), hr==S_OK) { if (count != nCamID) { pM->Release(); count++; continue; } IPropertyBag *pBag=0; hr = pM->BindToStorage(0, 0, IID_IPropertyBag, (void **)&pBag); if(SUCCEEDED(hr)) { VARIANT var; var.vt = VT_BSTR; hr = pBag->Read(L"FriendlyName", &var, NULL); //还有其他属性,像描述信息等等... if(hr == NOERROR) { wcscpy_s(sName, nBufferSize, (WCHAR*)var.bstrVal); SysFreeString(var.bstrVal); } pBag->Release(); } pM->Release(); break; } pCreateDevEnum = NULL; pEm = NULL; return 1; } HRESULT CCameraDS::ShowCamProp() { return ShowFilterProp(m_pDeviceFilter); } HRESULT CCameraDS::ShowCamPinProp() { return ShowFilterProp(m_pCameraOutput); } HRESULT CCameraDS::QueryFrame(IplImage*& pFrame) { HRESULT hr = S_OK; long evCode; long size = 0; OAFilterState state; m_pMediaControl->GetState(INFINITE, &state); if (state != State_Running && state != State_Paused) return E_FAIL; AM_MEDIA_TYPE mt; ZeroMemory(&mt, sizeof(AM_MEDIA_TYPE)); hr = m_pSampleGrabber->GetConnectedMediaType(&mt); if(FAILED(hr)) return E_FAIL; VIDEOINFOHEADER *videoHeader; videoHeader = reinterpret_cast<VIDEOINFOHEADER*>(mt.pbFormat); int nWidth = videoHeader->bmiHeader.biWidth; int nHeight = videoHeader->bmiHeader.biHeight; long bufferSize = mt.lSampleSize; int nChannel = videoHeader->bmiHeader.biBitCount / 8; //if the buffer size changed if (pFrame == NULL) { if (IsEqualGUID(mt.subtype, MEDIASUBTYPE_RGB32)) { pFrame = cvCreateImage(cvSize(nWidth, nHeight), IPL_DEPTH_8U, 4); } else if(IsEqualGUID(mt.subtype, MEDIASUBTYPE_RGB24)) { pFrame = cvCreateImage(cvSize(nWidth, nHeight), IPL_DEPTH_8U, 3); } else { MYFREEMEDIATYPE(mt); return E_FAIL; } } if (pFrame->width != nWidth || pFrame->height != nHeight || pFrame->nChannels != nChannel) { MYFREEMEDIATYPE(mt); return S_FALSE; } hr = m_pSampleGrabber->GetCurrentBuffer(&bufferSize, (long*)pFrame->imageData); cvFlip(pFrame); MYFREEMEDIATYPE(mt); return S_OK; }
[ "ndhumuscle@fa729b96-8d43-11de-b54f-137c5e29c83a", "claire3kao@fa729b96-8d43-11de-b54f-137c5e29c83a" ]
[ [ [ 1, 169 ], [ 171, 334 ], [ 336, 337 ], [ 340, 340 ], [ 357, 425 ] ], [ [ 170, 170 ], [ 335, 335 ], [ 338, 339 ], [ 341, 356 ] ] ]
caa2faca1e5c7d5125f82946c6a2baf0732a8fb7
e47722025231d67c684f8072265cdb832487b4f3
/cpp/client/message_area.cpp
f2b2811fc0ce2e7bf618e1dfe53150b521681292
[]
no_license
Gamer2k4/basinrogue
0950c049b9e7a9dd543c892b8b0d4f30b460faf7
0fac183e94ddb8d7b6a5b3333f137b11a2b72b58
refs/heads/master
2021-01-19T07:54:05.228849
2007-02-25T13:35:25
2007-02-25T13:35:25
40,727,740
0
0
null
null
null
null
UTF-8
C++
false
false
5,501
cpp
// // C++ Implementation: message_area // // Description: // // // Author: Cavalaria Christophe <[email protected]>, (C) 2007 // // Copyright: See COPYING file that comes with this distribution // // #include <iostream> #pragma warning(disable:4786) #include "message_area.h" MessageArea::MessageArea ( SDL_Surface* dest_surface, int sizex, int sizey, int originx, int originy ) : Widget( dest_surface, sizex, sizey, originx, originy ) { dest.x = originx; dest.y = originy; dest.w = sizex; dest.h = sizey; font = TTF_OpenFont ( "client/data/Vera.ttf", 12 ); if ( !font ) { std::cerr << "Error creating TTF_Font: " << TTF_GetError() << "\n"; exit ( 1 ); } font_height = TTF_FontLineSkip ( font ); message_color.r = 255; message_color.g = 255; message_color.b = 0; message_color.unused = 0; input_received = true; blocked = 0; current_message = -1; } MessageArea::~MessageArea() { // delete font; this gets me a compile-time warning - not sure why? // because the font type is an internal hidden type from SDL, and one // does not call delete on internal types. // That is what TTF_CloseFont is meant for anyway :) TTF_CloseFont ( font ); } void MessageArea::InputReceived() { input_received = true; // ready for more input with no 'more' prompt } int MessageArea::GetBlocked() const { return blocked; } void MessageArea::SetUnblocked() { blocked = blocked - 1; input_received = false; current_message = current_message + 1; } void MessageArea::AddMessage ( const std::string& message ) { if ( message.length() == 0 ) { return; } if ( input_received ) { input_received = false; current_message = current_message + 1; } else { blocked = blocked + 1; } messages.push_back ( message ); } void MessageArea::Draw() { SDL_FillRect ( dest_surface, &dest, 0 ); if (current_message < 0) return; std::vector < std::string > wrapped_text = WrapText ( messages[current_message] + ( blocked ? " --more--" : "" ), font, dest.w ); SDL_Rect this_line_dest; this_line_dest.x = originx; this_line_dest.y = originy; // from SDL manual : Only the position is used in the dstrect (the width and height are ignored). // this_line_dest.w = sizex; // this_line_dest.h = font_height; for ( int i=0 ; i < wrapped_text.size() ; i++ ) { DrawText ( wrapped_text[i], dest_surface, font, message_color, this_line_dest ); this_line_dest.y += font_height; } SDL_UpdateRect ( dest_surface, dest.x, dest.y, dest.w, dest.h ); } /* SOME CODE CRIBBED OFF THE WEB FOLLOWS. NEEDS A TIDY UP This is C looking code used for standard C strings. Fortunately, C++ strings are far more powerful and useful so the end result will look better :) */ /* There was a small bug that caused that function to return a space in the front of each line So I wrote a new one :) */ void Tokenize ( const std::string& str, std::vector<std::string>& tokens, const std::string& delimiters = " " ) { std::string::size_type lastPos = 0; std::string::size_type pos = str.find_first_of ( delimiters, lastPos ); while ( std::string::npos != pos || std::string::npos != lastPos ) { tokens.push_back ( str.substr ( lastPos, pos - lastPos ) ); if ( pos == std::string::npos ) return; lastPos = pos + 1; pos = str.find_first_of ( delimiters, lastPos ); } } void WrapSingleLine ( const std::string& line, std::vector<std::string>& result, TTF_Font* textFont, int maxWidth ) { int w; if ( TTF_SizeUTF8 ( textFont, line.c_str(), &w, 0 ) ) return; // Silently ignoring errors ? if ( w <= maxWidth ) { result.push_back ( line ); return; } std::string right_part = line; std::string::size_type pos = right_part.size(); while ( pos > 0 ) { pos = right_part.find_last_of ( ' ', pos ); if ( pos == std::string::npos ) { // Word wrap failed, bailing out result.push_back ( right_part ); return; } pos = right_part.find_last_not_of ( ' ', pos ); if ( pos == std::string::npos ) { // Word wrap failed, bailing out result.push_back ( right_part ); return; } std::string left_part = right_part.substr ( 0, pos+1 ); if ( TTF_SizeUTF8 ( textFont, left_part.c_str(), &w, 0 ) ) return; // Silently ignoring errors ? if ( w <= maxWidth ) { result.push_back ( left_part ); right_part = right_part.substr ( pos+2, std::string::npos ); pos = std::string::npos; } } } std::vector<std::string> WrapText ( const std::string& message, TTF_Font* textFont, int maxWidth ) { std::vector<std::string> result; std::vector<std::string> line_list; Tokenize ( message, line_list, "\n" ); for ( int ii = 0; ii < line_list.size(); ++ii ) WrapSingleLine ( line_list[ii], result, textFont, maxWidth ); return result; } void DrawText ( std::string& line, SDL_Surface* surface, TTF_Font* textFont, SDL_Color textColor, SDL_Rect& drawingPos ) { SDL_Surface* textSurface = TTF_RenderUTF8_Blended ( textFont, line.c_str(), textColor ); // RenderBlended because some fonts will slightly overlap when drawn one above the // other. Things like the letter 'g' for example extends slightly on the line bellow // when using BitstreamVeraMono if ( !textSurface ) return; SDL_BlitSurface ( textSurface, 0, surface, &drawingPos ); SDL_FreeSurface ( textSurface ); return; }
[ "antoine.from.rgrd@712ddccb-0227-0410-9f85-29faccf8bd71", "christophe.cavalaria@712ddccb-0227-0410-9f85-29faccf8bd71" ]
[ [ [ 1, 18 ], [ 20, 25 ], [ 27, 31 ], [ 33, 38 ], [ 40, 46 ], [ 51, 54 ], [ 56, 65 ], [ 67, 69 ], [ 71, 75 ], [ 77, 77 ], [ 79, 87 ], [ 89, 90 ], [ 94, 96 ], [ 100, 101 ], [ 104, 107 ], [ 109, 109 ], [ 117, 117 ], [ 121, 121 ], [ 133, 134 ], [ 136, 136 ], [ 173, 174 ], [ 176, 177 ], [ 184, 186 ], [ 189, 189 ], [ 197, 197 ] ], [ [ 19, 19 ], [ 26, 26 ], [ 32, 32 ], [ 39, 39 ], [ 47, 50 ], [ 55, 55 ], [ 66, 66 ], [ 70, 70 ], [ 76, 76 ], [ 78, 78 ], [ 88, 88 ], [ 91, 93 ], [ 97, 99 ], [ 102, 103 ], [ 108, 108 ], [ 110, 116 ], [ 118, 120 ], [ 122, 132 ], [ 135, 135 ], [ 137, 172 ], [ 175, 175 ], [ 178, 183 ], [ 187, 188 ], [ 190, 196 ], [ 198, 201 ] ] ]
28766eea75e59a65589db65dc48576ac02c4458f
138a353006eb1376668037fcdfbafc05450aa413
/source/ogre/OgreNewt/boost/mpl/aux_/iter_fold_impl.hpp
75a0d8f7ffb097483b1849de0deb7aba1969eabd
[]
no_license
sonicma7/choreopower
107ed0a5f2eb5fa9e47378702469b77554e44746
1480a8f9512531665695b46dcfdde3f689888053
refs/heads/master
2020-05-16T20:53:11.590126
2009-11-18T03:10:12
2009-11-18T03:10:12
32,246,184
0
0
null
null
null
null
UTF-8
C++
false
false
1,404
hpp
#ifndef BOOST_MPL_AUX_ITER_FOLD_IMPL_HPP_INCLUDED #define BOOST_MPL_AUX_ITER_FOLD_IMPL_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2000-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Source: /cvsroot/ogre/ogreaddons/ogrenewt/OgreNewt_Main/inc/boost/mpl/aux_/iter_fold_impl.hpp,v $ // $Date: 2006/04/17 23:47:07 $ // $Revision: 1.1 $ #if !defined(BOOST_MPL_PREPROCESSING_MODE) # include <boost/mpl/next_prior.hpp> # include <boost/mpl/apply.hpp> # include <boost/mpl/aux_/config/ctps.hpp> # if defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) # include <boost/mpl/if.hpp> # include <boost/type_traits/is_same.hpp> # endif #endif #include <boost/mpl/aux_/config/use_preprocessed.hpp> #if !defined(BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS) \ && !defined(BOOST_MPL_PREPROCESSING_MODE) # define BOOST_MPL_PREPROCESSED_HEADER iter_fold_impl.hpp # include <boost/mpl/aux_/include_preprocessed.hpp> #else # define AUX778076_FOLD_IMPL_OP(iter) iter # define AUX778076_FOLD_IMPL_NAME_PREFIX iter_fold # include <boost/mpl/aux_/fold_impl_body.hpp> #endif // BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS #endif // BOOST_MPL_AUX_ITER_FOLD_IMPL_HPP_INCLUDED
[ "Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e" ]
[ [ [ 1, 42 ] ] ]
5762d03bd3455bf1a5ee9647034ac82b17e0bdb8
3eae1d8c99d08bca129aceb7c2269bd70e106ff0
/trunk/Codes/CLR/Tools/TFConvert/stdafx.h
f59fd908381cabc1cce8055aec6411fb2c08a5e0
[]
no_license
yuaom/miniclr
9bfd263e96b0d418f6f6ba08cfe4c7e2a8854082
4d41d3d5fb0feb572f28cf71e0ba02acb9b95dc1
refs/heads/master
2023-06-07T09:10:33.703929
2010-12-27T14:41:18
2010-12-27T14:41:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,141
h
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma once #define _WIN32_WINNT 0x0501 #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers #include <stdio.h> #include <tchar.h> #include <windows.h> #include <process.h> #include <vector> #include <list> #include <cor.h> #include <corhdr.h> #include <corhlpr.h> #include <AssemblyParser.h> #include <AssemblyReparser.h> #include <WatchAssemblyBuilder.h> #include <TinyCLR_Runtime.h> #include <TinyCLR_Checks.h> #include <TinyCLR_Diagnostics.h> #include <TinyCLR_Graphics.h> #include <TinyCLR_Hardware.h> #include <TinyCLR_Debugging.h> #include <TinyCLR_ParseOptions.h> #include <HAL_Windows.h>
[ [ [ 1, 38 ] ] ]
458062f1258d72f837534c751d45abfa5b89380e
c74b0c37ac8e2d3d1a3c0ffaa2b608bc4deff1c6
/Toolkit/Converters/3DAssetConverter/dll/src/conv.cpp
187ce9129df4b3930b47551339ba74715769f88f
[]
no_license
crsib/freya-3d
c33beeb787e572f2faf9528c6f3a1fa3875749c5
ff1f54b09f7bc0e253053a474f3fe5635dbedde6
refs/heads/master
2022-05-21T19:42:30.694778
2011-03-11T13:49:00
2011-03-11T13:49:00
259,894,429
1
0
null
null
null
null
UTF-8
C++
false
false
11,866
cpp
/* 3DAC source */ #include "freya-3dac/common.h" #include "freya-3dac/conv.h" namespace dac { // // Mesh // //Mesh::Mesh(aiMesh* mesh) //: _mesh(mesh) //{ // hasAnim // ??? //} btVector3 convAssimp2Bullet(const aiVector3D& v) { return btVector3(v.x, v.y, v.z); } scenegraph::AABB Mesh::getAABB() const { aiVector3D m, M; if (_mesh->mNumVertices != 0) { m = M = _mesh->mVertices[0]; for (unsigned int i = 1; i < _mesh->mNumVertices; ++i) { const aiVector3D& v = _mesh->mVertices[i]; if (v.x < m.x) m.x = v.x; if (v.y < m.y) m.y = v.y; if (v.z < m.z) m.z = v.z; if (v.x > M.x) M.x = v.x; if (v.y > M.y) M.y = v.y; if (v.z > M.z) M.z = v.z; } } return scenegraph::AABB::FromMM(convAssimp2Bullet(m), convAssimp2Bullet(M)); } // // GDataExporter // GDataExporter::GDataExporter(const std::vector<Mesh>& meshes, const String& filename) : mMeshes(meshes), mFilename(filename), mState(S_EXPORTING) { } // WARNING! Don't call it for unpacked structures, that have to be packed :). Captain. template <typename T> void binWrite(const T& write, std::ostream& stream) { stream.write((const char*)&write, sizeof(write)); } void binWrite(const void* write, unsigned int sz, std::ostream& stream) { stream.write((const char*)&write, sz); } void binWriteV3(const aiVector3D& v, std::ostream& stream) { binWrite<float>(v.x, stream); binWrite<float>(v.y, stream); binWrite<float>(v.z, stream); } // Not a miss. Print V3 as V2. void binWriteV2(const aiVector3D& v, std::ostream& stream) { binWrite<float>(v.x, stream); binWrite<float>(v.y, stream); } void binWriteV2(const aiVector2D& v, std::ostream& stream) { binWrite<float>(v.x, stream); binWrite<float>(v.y, stream); } class VertexDecl { public: VertexDecl(); void add(rvf::USAGE usage, rvf::TYPE type); bool has(rvf::USAGE usage) const; static int getSize(rvf::TYPE type); void writeElements(std::ostream& stream) const; unsigned int getVertexSize() const { return mVertexSize; } protected: std::vector<FreyaVertexElement> mElements; unsigned int mVertexSize; }; VertexDecl::VertexDecl() : mVertexSize(0) { mElements.push_back(FreyaVertexElement((unsigned)-1,rvf::UNUSED,rvf::DWORD,0)); } void VertexDecl::writeElements(std::ostream& stream) const { for (size_t i = 0; i < mElements.size(); ++i) { binWrite<uint32>(mElements[i].streamID, stream); binWrite<uint32>(mElements[i].usage, stream); binWrite<uint32>(mElements[i].type, stream); binWrite<uint32>(mElements[i].offset, stream); } } int VertexDecl::getSize(rvf::TYPE type) { switch (type) // Because life without hardcoding isn't real life :D { // ...But FIXME. What about x64? case rvf::FLOAT1: return 4; case rvf::FLOAT2: return 4 * 2; case rvf::FLOAT3: return 4 * 3; case rvf::FLOAT4: return 4 * 4; case rvf::DWORD: return 4; case rvf::UBYTE4: return 4 * 1; case rvf::SHORT2: return 2 * 2; case rvf::SHORT4: return 4 * 2; default: DAC_ERROR("Unknown vertex format type `" << type << "`!"); return 0; } } void VertexDecl::add(rvf::USAGE usage, rvf::TYPE type) { mElements.insert(mElements.end() - 1, FreyaVertexElement(0, usage, type, mVertexSize)); mVertexSize += getSize(type); } bool VertexDecl::has(rvf::USAGE usage) const { for (size_t i = 0; i < mElements.size(); ++i) if (mElements[i].usage == usage) return true; return false; } rvf::USAGE texIndex2Type(unsigned int index) { switch (index) { case 0: return rvf::TEXT_COORD0; case 1: return rvf::TEXT_COORD1; case 2: return rvf::TEXT_COORD2; case 3: return rvf::TEXT_COORD3; default: DAC_ERROR(index << " - such big texture index isn't supported by Assimp!"); return rvf::TEXT_COORD0; } } struct ExportMeshInfo { VertexDecl vdecl; uint16 index_count; uint16 buffer_offset; uint32 vertex_elem_offset; }; int GDataExporter::operator()() { mState = S_EXPORTING; std::ofstream out(mFilename.c_str(), std::ios_base::binary); std::vector<ExportMeshInfo> infos; infos.resize(mMeshes.size()); uint16 index_buffer_offset = 0; uint32 vertex_elem_offset = 0; uint16 number_of_indices = 0; uint32 size_of_vertex_data = 0; // // Calculate offsets, counts... // for (size_t i = 0; i < mMeshes.size(); ++i) { ExportMeshInfo& info = infos[i]; aiMesh* mesh = mMeshes[i]._mesh; info.index_count = mesh->mNumFaces * 3; info.buffer_offset = index_buffer_offset; info.vertex_elem_offset = vertex_elem_offset; index_buffer_offset += info.index_count; vertex_elem_offset += mesh->mNumVertices; number_of_indices += info.index_count; info.vdecl.add(rvf::POSITION, rvf::FLOAT3); info.vdecl.add(rvf::NORMAL, rvf::FLOAT3); unsigned int texIndex = 0; // NB! Assimp imports not more than 4 different texture coords // TODO: Warn if can for (; mesh->HasTextureCoords(texIndex); ++texIndex) info.vdecl.add(texIndex2Type(texIndex), rvf::FLOAT2); // TODO: Third dim. size_of_vertex_data += mesh->mNumVertices * info.vdecl.getVertexSize(); } // // Write batch headers // // Via http://freya3d.org/wiki/WorldDataFormats/GeometricData (20.02.2010) //(16-bit unsigned int) num_batches binWrite<uint16>(infos.size(), out); for (size_t i = 0; i < infos.size(); ++i) { ExportMeshInfo& info = infos[i]; // 32-bit unsigned integer assembly_type binWrite<uint32>(renderer::Primitive::TRIANGLES, out); // 16-bit unsigned integer index_count binWrite<uint16>(info.index_count, out); // 16-bit unsigned integer buffer_offset binWrite<uint16>(info.buffer_offset, out); renderer::VertexElement vertexElement; // Write vertices declaration info.vdecl.writeElements(out); } // // Write indices // // 16-bit unsigned int number_of_indicies binWrite<uint16>(number_of_indices, out); for (size_t i = 0; i < infos.size(); ++i) { ExportMeshInfo& info = infos[i]; aiMesh* mesh = mMeshes[i]._mesh; for(unsigned int face = 0; face < mesh->mNumFaces; ++face) { for (unsigned int ind = 0; ind < mesh->mFaces[face].mNumIndices; ++ind) binWrite<uint16>(info.vertex_elem_offset + mesh->mFaces[face].mIndices[ind], out); } } // // Write vertices // // 32-bit unsigned integer size_of_vertex_data binWrite<uint32>(size_of_vertex_data, out); for (size_t i = 0; i < infos.size(); ++i) { ExportMeshInfo& info = infos[i]; aiMesh* mesh = mMeshes[i]._mesh; // Raw vertex data for (unsigned int v = 0; v < mesh->mNumVertices; ++v) { // Found way to do it even more slowly if (info.vdecl.has(rvf::POSITION)) binWriteV3(mesh->mVertices[v], out); if (info.vdecl.has(rvf::NORMAL)) binWriteV3(mesh->mNormals[v], out); // Textures for (unsigned int t = 0; info.vdecl.has(texIndex2Type(t)); ++t) binWriteV2(mesh->mTextureCoords[t][v], out); } } out.close(); mState = S_READY; return Task::DONE; } // // Asset // // // AssetLoader // AssetLoader::AssetLoader(const String& filepath) : mFilepath(filepath), mState(S_LOADING) { } String getFileExt(const String& filename) { String ext; int sz = (int)filename.size(); int i = sz - 1; for (; i >= 0; --i) if (filename[i] == '.') break; if (i == -1) return ""; for (++i; i < sz; ++i) ext += filename[i]; return ext; } void printNode(const aiNode* node, int offset) { for (int i = 0; i < offset; ++i) std::cout << " "; std::cout << node->mName.data << std::endl; for (unsigned int i = 0; i < node->mNumChildren; ++i) printNode(node->mChildren[i], offset + 1); } bool hasAnimation(const aiScene* scene, unsigned int meshId) { for (size_t animIter = 0; animIter < scene->mNumAnimations; ++animIter) { const aiAnimation* anim = scene->mAnimations[animIter]; for (size_t nodeIter = 0; nodeIter < anim->mNumChannels; ++nodeIter) { aiNodeAnim* animNode = anim->mChannels[nodeIter]; aiNode* sceneNode = scene->mRootNode->FindNode(animNode->mNodeName); if (sceneNode) { for (size_t meshIter = 0; meshIter < sceneNode->mNumMeshes; ++meshIter) { if (sceneNode->mMeshes[meshIter] == meshId) return true; } } } } return false; } int AssetLoader::operator() () { mState = S_LOADING; size_t fileSize; void* fileData = core::EngineCore::getFilesystem()->read(mFilepath, &fileSize); DAC_ASSERT3(fileData != nullptr, "Can't open file `" << mFilepath << "`!", mState = S_FAILED; return Task::DONE); const aiScene* scene = mImporter.ReadFileFromMemory(fileData, fileSize, aiProcessPreset_TargetRealtime_Fast, getFileExt(mFilepath).c_str()); // FIXME. How do I know that it was from GENERIC_POOL? core::memory::Free(fileData, core::memory::GENERIC_POOL); DAC_ASSERT3(scene, "Load failed! Assimp desc: " << mImporter.GetErrorString() << "", mState = S_FAILED; return Task::DONE) AssetPtr asset(new Asset()); asset->_scene = scene; asset->meshes.reserve(scene->mNumMeshes); for (unsigned int i = 0; i < scene->mNumMeshes; ++i) { Mesh mesh; mesh._mesh = scene->mMeshes[i]; mesh.hasAnim = hasAnimation(scene, i); asset->meshes.push_back(mesh); } mAsset = asset; // Assign only when it's done mState = S_READY; return Task::DONE; } } // namespace dac
[ "aptakhin@localhost" ]
[ [ [ 1, 415 ] ] ]
eacec01ae791e4ea5f0c1d604c367589c304fd89
b63cad17af550bc7150431b7b0d639a46a129d82
/msgCourier.cpp
c5910bcdf4be1159c946dd8b49a97304af43060c
[]
no_license
cjus/msgCourier
90463028b5e6222dd5c804215fa43bc518c4a539
075ff724316fd28c21d842726b694806d82bf53b
refs/heads/master
2021-01-10T19:41:02.306930
2010-09-05T18:47:24
2010-09-05T18:47:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,181
cpp
/* msgCourier.cpp Copyright (C) 2005 Carlos Justiniano [email protected], [email protected], [email protected] msgCourier.cpp 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. msgCourier.cpp was developed by Carlos Justiniano for use on the msgCourier project and the ChessBrain Project and is now 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 msgCourier.cpp; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /** @file msgCourier.cpp @brief Built in handler for MsgCourier messages @author Carlos Justiniano @attention Copyright (C) 2005 Carlos Justiniano, GNU GPL Licence (see source file header) Built in handler for MsgCourier messages */ #include "core.h" #include "exception.h" #include "log.h" #include "msgCourier.h" #include <string> #include <boost/tokenizer.hpp> #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/find.hpp> #include "routingtag.h" #include "xmlliteparser.h" using namespace std; using namespace boost; #define COMMAND_NAME "MC" char *cMsgCourier::GetCommandName() { return COMMAND_NAME; } void cMsgCourier::OnStartup(cIMsgQueue *pMsgQueue, cISysInfo *pSysInfo, cILogger *pLogger) { //cRoutingTag rt; //rt.SetTag("6afb4db2-3a37-41ce-9496-22f98a7d6dca"); m_pMsgQueue = pMsgQueue; m_pSysInfo = pSysInfo; } void cMsgCourier::OnShutdown() { } int cMsgCourier::OnProcess(cIMsg *pMessage) { MARK_TRAVEL(pMessage); string::size_type i; string command; try { command = pMessage->GetCommand(); ////////////////////////////// // TEST IF ROUTABLE MESSAGE // ////////////////////////////// cIMsg *pRoutedMsg = 0; if (((cMsg*)pMessage)->GetRemoteHandler() != 0) { LOG("Routing %s to remote handler", command.c_str()); int RemoteSocketHandle = (((cMsg*)pMessage)->GetRemoteHandler())->m_pNode->m_TCPSocketHandle; cIMsg *pReply = m_pMsgQueue->CreateMessage(); ((cMsg*)pMessage)->DeepCopy((cMsg*)pReply); ((cMsg*)pReply)->SetTCPSocketHandle(RemoteSocketHandle); //stringstream ss (stringstream::in | stringstream::out); //ss << RemoteSocketHandle; //((cMsg*)pReply)->SetSID(ss.str().c_str()); ((cMsg*)pReply)->SetConnectionType(cIMsg::MSG_CT_OB_TCP); pReply->DispatchMsg(); pMessage->MarkProcessed(); return HRC_COMMAND_HANDLER_OK; } ////////////////////////// // TEST IF POST COMMAND // ////////////////////////// i = command.find("POST"); if (i != string::npos) { HandleXoolleMessage(pMessage); pMessage->MarkProcessed(); return HRC_COMMAND_HANDLER_OK; } //////////////////////////////// // TEST IF FORWARDING MESSAGE // //////////////////////////////// i = command.find(".FORWARD"); if (i != string::npos) { string s = pMessage->GetTo(); int socketfd = cCore::GetInstance()->GetPeerRoutingMap()->GetSocket(s.c_str()); cIMsg *pForward = m_pMsgQueue->CreateMessage(); ((cMsg*)pMessage)->DeepCopy((cMsg*)pForward); ((cMsg*)pForward)->SetFrom(pMessage->GetFrom()); ((cMsg*)pForward)->SetTCPSocketHandle(socketfd); ((cMsg*)pForward)->SetConnectionType(cIMsg::MSG_CT_OB_TCP); ((cMsg*)pForward)->SetFormat(cIMsg::MSG_FORMAT_REQ); pForward->DispatchMsg(); pMessage->MarkProcessed(); return HRC_COMMAND_HANDLER_OK; } ///////////////////////////// // TEST FOR REPLY MESSAGES // ///////////////////////////// i = command.find("MCP/"); if (i != string::npos) { int socketfd = cCore::GetInstance()->GetPeerRoutingMap()->GetSocket(pMessage->GetFrom()); cIMsg *pReply = m_pMsgQueue->CreateMessage(); ((cMsg*)pMessage)->DeepCopy((cMsg*)pReply); ((cMsg*)pReply)->SetTCPSocketHandle(socketfd); ((cMsg*)pReply)->SetConnectionType(cIMsg::MSG_CT_OB_TCP); ((cMsg*)pReply)->SetFormat(cIMsg::MSG_FORMAT_RES); pReply->DispatchMsg(); pMessage->MarkProcessed(); return HRC_COMMAND_HANDLER_OK; } //////////////////// // TEST FOR ERROR // //////////////////// i = command.find(".ERROR"); if (i != string::npos) { cIMsg *pReply = m_pMsgQueue->CreateMessageReply(pMessage); pReply->SetResponseCode(500); ((cMsg*)pReply)->SetKeepAlive(false); pReply->DispatchMsg(); pMessage->MarkProcessed(); return HRC_COMMAND_HANDLER_OK; } /////////////////// // TEST FOR PING // /////////////////// i = command.find(".PING"); if (i != string::npos) { //LOG("Recieved PING from %s", pMessage->GetSourceIP()); cIMsg *pReply = m_pMsgQueue->CreateMessageReply(pMessage); SET_TOUCH_CODE(pReply, 8); pReply->DispatchMsg(); } /////////////////////// // TEST FOR PRESENCE // /////////////////////// i = command.find(".PRESENCE"); if (i != string::npos) { /* cIMsg *pReply = m_pMsgQueue->CreateMessageReply(pMessage); pReply->SetResponseCode(200); pReply->DispatchMsg(); */ cIMsg::MSG_REPLY_ACTION reply = pMessage->GetReplyAction(); string::size_type j; j = command.find(".BROADCAST"); if (j != string::npos) { bool bRegistered = false; string sInterface1 = cCore::GetInstance()->GetServerPrimaryAddr(); string sInterface2 = cCore::GetInstance()->GetServerSecondaryAddr(); string sFrom = pMessage->GetFrom(); bool bRemote = true; if (sFrom.find(sInterface1) != string::npos) bRemote = false; else if (sFrom.find(sInterface2) != string::npos) bRemote = false; if (bRemote == true) { string::size_type idx = sFrom.find("@"); string sMachineName = sFrom.substr(0, idx); string sMacAddress = pMessage->GetHeaderFieldValue("HWAddr"); string sServices = pMessage->GetHeaderFieldValue("Services"); cPresence *pPresence = cCore::GetInstance()->GetPresence(); string sNodeKey = pPresence->UpdateNode(pMessage->GetSourceIP(), sMachineName.c_str(), sMacAddress.c_str(), sServices.c_str()); // ,ePresenceStatus status = PS_ACTIVE); cService *pService = cCore::GetInstance()->GetService(); typedef tokenizer<char_separator<char> > tokenizer; char_separator<char> sep(" "); tokenizer tokens(sServices, sep); tokenizer::iterator tok_iter; for (tok_iter = tokens.begin(); tok_iter != tokens.end(); ++tok_iter) { if ((*tok_iter) != string("MC")) { bRegistered = pService->RegisterRemoteService(sNodeKey.c_str(), (*tok_iter).c_str(),0,0,0, true, true, pMessage->GetTCPSocketHandle()); if (bRegistered == false) { pService->UnregisterRemoteService(sNodeKey.c_str(), (*tok_iter).c_str()); bRegistered = pService->RegisterRemoteService(sNodeKey.c_str(), (*tok_iter).c_str(),0,0,0, true, true, pMessage->GetTCPSocketHandle()); if (bRegistered == false) { cIMsg *pReply = m_pMsgQueue->CreateMessageReply(pMessage); pReply->SetResponseCode(500); pReply->DispatchMsg(); } break; } } } } if (bRegistered == true) { cIMsg *pReply = m_pMsgQueue->CreateMessageReply(pMessage); pReply->SetResponseCode(200); pReply->DispatchMsg(); } } } //////////////////////////////// // TEST FOR PEER LIST REQUEST // //////////////////////////////// i = command.find(".PEER.LIST"); if (i != string::npos) { string sList; cIMsg *pReply = m_pMsgQueue->CreateMessageReply(pMessage); cService *pService = cCore::GetInstance()->GetService(); cServiceEntry *pEntry = pService->QueryServiceFirst(pMessage->GetSubject()); do { if (pEntry != 0 && pEntry->m_pNode->m_status == PS_ACTIVE) { sList.append(pEntry->m_pNode->m_IPAddress.c_str()); sList.append(":3400\n"); } } while (pEntry = pService->QueryServiceNext()); if (sList.length() >= 0) { pReply->SetContentType("text/s-expression"); pReply->SetContentLength(sList.length()); pReply->SetContentPayload(sList.c_str(), sList.length()); } MARK_TRAVEL(pReply); pReply->SetResponseCode(200); pReply->DispatchMsg(); } pMessage->MarkProcessed(); } catch (exception const &e) { LOGALL(e.what()); } return HRC_COMMAND_HANDLER_OK; } const char *cMsgCourier::OnProcessInternal(const char *pMessage) { cPresence *pPresence = cCore::GetInstance()->GetPresence(); return pPresence->GetPresenceData(); } void cMsgCourier::HandleXoolleMessage(cIMsg* pMessage) { string sPayload; sPayload = "<?xml version=\"1.0\"?>"; sPayload += "<msgcourier application=\"xoolle\" >"; //<sessionID id=\"6afb4db2-3a37-41ce-9496-22f98a7d6dca\" /></msgcourier>"; const char *pContent = pMessage->GetContentPayload(); const char *pszMessage = strstr(pContent, "<?xml"); if (pszMessage != NULL) { char *pData = NULL; cXMLLiteElement *pElm; cXMLLiteParser xml; xml.Parse(pszMessage); xml.MoveHead(); do { /* pElm = xml.GetElement(); pData = const_cast<char*>(pElm->GetElementValue()); if (pData == NULL) LOG("|%s|", pElm->GetElementName()); else LOG("|%s|[%s]", pElm->GetElementName(), pData); if (pElm->hasAttributes()) { pElm->MoveHead(); do { cXMLLiteAttributePair *pAttr = pElm->GetAttributePair(); pData = const_cast<char*>(pAttr->GetAttribValue()); LOG(" attrib: |%s|[%s]", pAttr->GetAttribName(), pData); } while (pElm->MoveNext() == HRC_XMLLITELIST_OK); } if (pElm->hasCDATA()) { LOG(" CDATA: %s", pElm->GetElementCDATA()); } */ pElm = xml.GetElement(); pData = const_cast<char*>(pElm->GetElementName()); if (strstr(pData, "getSession") != NULL) { string msg; msg += "<sessionID id=\""; msg += pMessage->GetMsgID(); msg += "\" />"; sPayload += msg; LOG("Received: getSession command. Sending: %s", msg.c_str()); } else if (strstr(pData, "userActivity") != NULL) { if (pElm->hasAttributes()) { pElm->MoveHead(); cXMLLiteAttributePair *pAttr = pElm->GetAttributePair(); LOG("Received: userActivity command: [%s]", pAttr->GetAttribValue()); } } else if (strstr(pData, "retrieveForm") != NULL) { if (pElm->hasAttributes()) { string sFormData; string id; pElm->MoveHead(); cXMLLiteAttributePair *pAttr = pElm->GetAttributePair(); id = pAttr->GetAttribValue(); if (strstr(id.c_str(), "2CF17DF3-0ED9-4fd9-9CC9-178823798959") != NULL) { sFormData = "<q>1) Are you thinking about updating more than one area of your home?\n" "<rb>Yes, start with one area at a time. Don't worry you will have a chance to design other areas of your home your next time thru Xoolle.\n" "<rb>No, okay continue on and have fun...\n" "<hp>For a qualified quote regional responses are required due to regional pricing therefore, your zip code must be supplied in order to gain a competent quote."; } else if (strstr(id.c_str(), "0E460765-9E71-49ce-9C44-5B76632499E4") != NULL) { sFormData = "<q>2) What are you envisioning for your home?\n" "<rb>Cosmetic Remodel (Cosmetically updating your home without Structural changes).\n" "<rb>Major Remodel (Cosmetically updating your home including Structural changes).\n" "<rb>Addition (Adding square footage to your home).\n" "<rb>New Construction (New structure on your property).\n" "<v>Please respond with a year represented in 4 digits.\n" "<hp>There are underling concerns related to construction that might impact your quote. For example, a 1972 home, and prior, might contain asbestos in the plaster, acoustic ceiling material, ducting, stucco and etc. installed at your home."; } else if (strstr(id.c_str(), "8E1D84AA-6DC5-414d-9D60-0AF9851E9CF5") != NULL) { sFormData = "<q>3) What type of home is yours? choose all that apply.\n" "<rb>Detached single family?\n" "<rb>Attached condo/townhome?\n" "<cb>Single level?\n" "<cb>Multi level?\n" "<v>Please respond\n" "<hp>The type of home your contemplating an alteration on requires some basic information that aid in the quote process."; } else if (strstr(id.c_str(), "7C257A08-6F4E-4099-B2DC-22F90AB8A2D6") != NULL) { sFormData = "<q>As requested lets go through the XoolleCalc again, simply choose a room or area of your home that needs work.\n" "<rb >Bathrooms? \n" "<rb>Kitchen? \n" "<rb>Living Family area?\n" "<rb>Dining area? \n" "<rb>Master Suite?\n" "<rb>Bedrooms? \n" "<rb>Game/Bonus room? \n" "<rb>Laundry/Mudroom area?\n" "<rb>Attic/Basement?\n" "<rb>Garage area\n" "<rb>Exterior?\n" "<rb>Addition\n" "<v>Please respond."; } else if (strstr(id.c_str(), "80A318FE-3B2F-4eed-9157-4214F8834BE6") != NULL) { sFormData = "<q>5) This form will be modified?"; } string msg; msg += "<formData><![CDATA["; msg += sFormData.c_str(); msg += "]]></formData>"; sPayload += msg; LOG("Received: retrieveForm command: [%s]. Sending: [%s]", pAttr->GetAttribValue(), msg.c_str()); } } //retrieveForm } while (xml.MoveNext() == HRC_XMLLITELIST_OK); sPayload += "</msgcourier>"; cIMsg *pReply = m_pMsgQueue->CreateMessage(); ((cMsg*)pMessage)->DeepCopy((cMsg*)pReply); ((cMsg*)pReply)->SetTCPSocketHandle(pMessage->GetTCPSocketHandle()); ((cMsg*)pReply)->SetConnectionType(cIMsg::MSG_CT_OB_TCP); ((cMsg*)pReply)->SetContentType("text/xml"); ((cMsg*)pReply)->SetContentPayload(sPayload.c_str(), sPayload.length()); ((cMsg*)pReply)->SetFormat(cIMsg::MSG_FORMAT_RES); ((cMsg*)pReply)->SetKeepAlive(false); pReply->DispatchMsg(); } }
[ [ [ 1, 448 ] ] ]
e9673d80a871943e1b92ff9f502a15efee041f2d
ed41104173ed37bcec9d4c4d6d7537d0c329fdd3
/MC Tetris/Main.cpp
4cc87e4d7c4f94923f14f6c584d242a330b2d55a
[ "CC-BY-3.0" ]
permissive
abajwa/Tetris
13959449022dcac9cfbe7b9bf39247360749b074
1b3cb26c066445b961a2dbe3fa90acf10cfa6cd8
refs/heads/master
2021-01-01T17:27:08.436031
2011-12-07T06:08:45
2011-12-07T06:08:45
2,699,305
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
3,930
cpp
/***************************************************************************************** /* Desc: Tetris tutorial /* /* gametuto.com - Javier López López (javilop.com) /* /***************************************************************************************** /* /* Creative Commons - Attribution 3.0 Unported /* You are free: /* to Share — to copy, distribute and transmit the work /* to Remix — to adapt the work /* /* Under the following conditions: /* Attribution. You must attribute the work in the manner specified by the author or licensor /* (but not in any way that suggests that they endorse you or your use of the work). /* /*****************************************************************************************/ #include <iostream> #include <fstream> #include "Game.h" #ifndef LINUX #include <windows.h> #endif using namespace std; /* ================== Main ================== */ #ifndef LINUX int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) // Linux users should quit this line #else int main() #endif // int main () // Linux users should use this line instead the previous one { clock_t start; start = clock(); int linesWon = 0; ofstream output("testBLEE.txt"); // ----- Vars ----- // Class for drawing staff, it uses SDL for the rendering. Change the methods of this class // in order to use a different renderer IO mIO; int mScreenHeight = mIO.GetScreenHeight(); // Pieces Pieces mPieces; // Board Board mBoard = Board (&mPieces, mScreenHeight); // Game Game mGame (&mBoard, &mPieces, &mIO, mScreenHeight); // Get the actual clock milliseconds (SDL) unsigned long mTime1 = SDL_GetTicks() + 630; // ----- Main Loop ----- while (!mIO.IsKeyDown (SDLK_ESCAPE)) { // ----- Draw ----- mIO.ClearScreen (); // Clear screen mGame.DrawScene (); // Draw staff mIO.UpdateScreen (); // Put the graphic context in the screen // ----- Input ----- int mKey = mIO.Pollkey(); switch (mKey) { case (SDLK_RIGHT): { if (mBoard.IsPossibleMovement (mGame.mPosX + 1, mGame.mPosY, mGame.mPiece, mGame.mRotation)) mGame.mPosX++; break; } case (SDLK_LEFT): { if (mBoard.IsPossibleMovement (mGame.mPosX - 1, mGame.mPosY, mGame.mPiece, mGame.mRotation)) mGame.mPosX--; break; } case (SDLK_DOWN): { if (mBoard.IsPossibleMovement (mGame.mPosX, mGame.mPosY + 1, mGame.mPiece, mGame.mRotation)) mGame.mPosY++; break; } case (SDLK_x): { // Check collision from up to down while (mBoard.IsPossibleMovement(mGame.mPosX, mGame.mPosY, mGame.mPiece, mGame.mRotation)) { mGame.mPosY++; } mBoard.StorePiece (mGame.mPosX, mGame.mPosY - 1, mGame.mPiece, mGame.mRotation); linesWon += mBoard.DeletePossibleLines (); if (mBoard.IsGameOver()) { output << linesWon << endl; output <<(clock() - start)/ (double)CLOCKS_PER_SEC << endl; mIO.Getkey(); exit(0); } mGame.CreateNewPiece(); break; } case (SDLK_z): { if (mBoard.IsPossibleMovement (mGame.mPosX, mGame.mPosY, mGame.mPiece, (mGame.mRotation + 1) % 4)) mGame.mRotation = (mGame.mRotation + 1) % 4; break; } } // ----- Vertical movement ----- unsigned long mTime2 = SDL_GetTicks() ;//+ 630; if ((mTime2 - mTime1) > WAIT_TIME) { if (mBoard.IsPossibleMovement (mGame.mPosX, mGame.mPosY + 1, mGame.mPiece, mGame.mRotation)) { mGame.mPosY++; } else { mBoard.StorePiece (mGame.mPosX, mGame.mPosY, mGame.mPiece, mGame.mRotation); mBoard.DeletePossibleLines (); if (mBoard.IsGameOver()) { mIO.Getkey(); exit(0); } mGame.CreateNewPiece(); } mTime1 = SDL_GetTicks(); } } return 0; }
[ [ [ 1, 162 ] ] ]
11227416bd06291c1b4496cf0c3f28d7ad398ad8
a7990bf2f56d927ae884db0e727c17394bda39c4
/image-approx/MaxIntensityDifMinAgainstMax.h
a5f92553abf1e6d49d961157eaccbbdec25a9f1c
[]
no_license
XPaladin/image-approx
600862d8d76264e25f96ae10f3a9f5639a678b17
b0fbddef0e58ae1ba2b5e31f7eb87e2a48509dfb
refs/heads/master
2016-09-01T17:49:01.705563
2009-06-15T06:01:46
2009-06-15T06:01:46
33,272,564
0
0
null
null
null
null
UTF-8
C++
false
false
648
h
#ifndef MAXINTENSITYDIFMINAGAINSTMAX_H_ #define MAXINTENSITYDIFMINAGAINSTMAX_H_ #include "MaxDifIntensityCriterio.h" #include "PriorityQueue.h" class MaxIntensityDifMinAgainstMax : public MaxDifIntensityCriterio { protected: float excludingPercent; MaxIntensityDifMinAgainstMax(){} unsigned char diferencia(const Rectangle::Rectangle rec)const; public: MaxIntensityDifMinAgainstMax(Image *image, int max_dif, float excluding_percent):MaxDifIntensityCriterio(image,max_dif){ excludingPercent=excluding_percent; } virtual ~MaxIntensityDifMinAgainstMax(){} }; #endif /*MAXINTENSITYDIFMINAGAINSTMAX_H_*/
[ "pala.sepu@17da7754-4e6e-11de-84bb-6bba061bd1d3" ]
[ [ [ 1, 25 ] ] ]
3a4b4f3cc400558cb0ab47d45209855ac667db94
138a353006eb1376668037fcdfbafc05450aa413
/source/ogre/OgreNewt/boost/mpl/aux_/arity.hpp
8da6cee664c37fc86aae47cd947ae84e00c1c8f2
[]
no_license
sonicma7/choreopower
107ed0a5f2eb5fa9e47378702469b77554e44746
1480a8f9512531665695b46dcfdde3f689888053
refs/heads/master
2020-05-16T20:53:11.590126
2009-11-18T03:10:12
2009-11-18T03:10:12
32,246,184
0
0
null
null
null
null
UTF-8
C++
false
false
1,247
hpp
#ifndef BOOST_MPL_AUX_ARITY_HPP_INCLUDED #define BOOST_MPL_AUX_ARITY_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2001-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Source: /cvsroot/ogre/ogreaddons/ogrenewt/OgreNewt_Main/inc/boost/mpl/aux_/arity.hpp,v $ // $Date: 2006/04/17 23:47:07 $ // $Revision: 1.1 $ #include <boost/mpl/aux_/config/dtp.hpp> #if defined(BOOST_MPL_CFG_BROKEN_DEFAULT_PARAMETERS_IN_NESTED_TEMPLATES) # include <boost/mpl/aux_/nttp_decl.hpp> # include <boost/mpl/aux_/config/static_constant.hpp> namespace boost { namespace mpl { namespace aux { // agurt, 15/mar/02: it's possible to implement the template so that it will // "just work" and do not require any specialization, but not on the compilers // that require the arity workaround in the first place template< typename F, BOOST_MPL_AUX_NTTP_DECL(int, N) > struct arity { BOOST_STATIC_CONSTANT(int, value = N); }; }}} #endif // BOOST_MPL_CFG_BROKEN_DEFAULT_PARAMETERS_IN_NESTED_TEMPLATES #endif // BOOST_MPL_AUX_ARITY_HPP_INCLUDED
[ "Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e" ]
[ [ [ 1, 39 ] ] ]
d51b50a62e84d739eb3611f515584464bf6389d4
53b3f50f75b5f38ceb1aff83ca71f559186a8782
/Source/Main.cpp
87b281790855555f10345f84368664c92c095b70
[]
no_license
sonic59/JuceS1Text
f8fa6ad546e7229b1aac3acc080d7f2fafefea6b
9f69675a74f134fc5e7e6fc7d4d87e0a5acac4bd
refs/heads/master
2020-04-21T03:36:34.429482
2011-11-22T15:53:53
2011-11-22T15:53:53
2,828,197
0
0
null
null
null
null
UTF-8
C++
false
false
1,913
cpp
/* ============================================================================== This file was auto-generated by the Introjucer! It contains the basic startup code for a Juce application. ============================================================================== */ #include "../JuceLibraryCode/JuceHeader.h" #include "MainWindow.h" //============================================================================== class JuceS1TextApplication : public JUCEApplication { public: //============================================================================== JuceS1TextApplication() { } ~JuceS1TextApplication() { } //============================================================================== void initialise (const String& commandLine) { // Do your application's initialisation code here.. mainWindow = new MainAppWindow(); } void shutdown() { // Do your application's shutdown code here.. mainWindow = 0; } //============================================================================== void systemRequestedQuit() { quit(); } //============================================================================== const String getApplicationName() { return "JuceS1Text"; } const String getApplicationVersion() { return ProjectInfo::versionString; } bool moreThanOneInstanceAllowed() { return true; } void anotherInstanceStarted (const String& commandLine) { } private: ScopedPointer <MainAppWindow> mainWindow; }; //============================================================================== // This macro generates the main() routine that starts the app. START_JUCE_APPLICATION(JuceS1TextApplication)
[ [ [ 1, 74 ] ] ]
b6d26046737734e787b7d8bc8b688840d7d24dc8
555ce7f1e44349316e240485dca6f7cd4496ea9c
/DirectShowFilters/DVBSubtitle2/Source/PesDecoder/PacketSync.cpp
250caaa55bec6c309994d79428174ff7b88b9381
[]
no_license
Yura80/MediaPortal-1
c71ce5abf68c70852d261bed300302718ae2e0f3
5aae402f5aa19c9c3091c6d4442b457916a89053
refs/heads/master
2021-04-15T09:01:37.267793
2011-11-25T20:02:53
2011-11-25T20:11:02
2,851,405
2
0
null
null
null
null
UTF-8
C++
false
false
2,539
cpp
/* * Copyright (C) 2006-2009 Team MediaPortal * http://www.team-mediaportal.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 * */ #pragma warning(disable : 4995) #include <windows.h> #include "PacketSync.h" // For more details for memory leak detection see the alloctracing.h header #include "..\..\..\alloctracing.h" CPacketSync::CPacketSync(void) { m_tempBufferPos=-1; } CPacketSync::~CPacketSync(void) { } extern void LogDebug( const char *fmt, ... ); // [188] [188] [188] [100] [88] // 0..187 188..375 376..563 564..663 0..87 // datalen=664 void CPacketSync::OnRawData(byte* pData, int nDataLen) { //LogDebug("On raw data"); int syncOffset=0; if (m_tempBufferPos > 0 ) { syncOffset = TS_PACKET_LEN - m_tempBufferPos; memcpy(&m_tempBuffer[m_tempBufferPos], pData, syncOffset); if (m_tempBuffer[0] == TS_PACKET_SYNC) { OnTsPacket(m_tempBuffer); } m_tempBufferPos = 0; } while (syncOffset < nDataLen) { if (syncOffset + TS_PACKET_LEN > nDataLen) break; if (pData[syncOffset] != TS_PACKET_SYNC) { //check if this is a corrupted packet... int nextPkt=syncOffset + TS_PACKET_LEN; if (nextPkt < nDataLen) { if (pData[nextPkt]==TS_PACKET_SYNC) { syncOffset=nextPkt; } else { syncOffset++; continue; } } else { syncOffset++; continue; } } OnTsPacket( &pData[syncOffset] ); syncOffset += TS_PACKET_LEN; } if (syncOffset < nDataLen) { m_tempBufferPos= nDataLen - syncOffset; memcpy( m_tempBuffer, &pData[syncOffset], m_tempBufferPos ); } } void CPacketSync::OnTsPacket(byte* tsPacket) { }
[ [ [ 1, 35 ], [ 37, 94 ] ], [ [ 36, 36 ] ] ]
83e2ecb714627bde5316a2438d634d7bf103c8a3
b2fa537cef03244de283e231932f22ee41aec051
/src/agg/agg_color_rgba.h
6d6e38643357f7f6204b6c0416202017031d8aab
[]
no_license
rebolsource/r3-hostkit
2e0037119cde8a161e2f7994fd3842cc3891e9d5
f331c6a46947e6e5afedc90f3d375bcd3f7ad8a1
refs/heads/master
2021-01-10T18:34:50.420402
2010-09-09T18:38:59
2010-09-10T11:59:58
813,301
0
0
null
null
null
null
UTF-8
C++
false
false
21,235
h
//---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.3 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // // Adaptation for high precision colors has been sponsored by // Liberty Technology Systems, Inc., visit http://lib-sys.com // // Liberty Technology Systems, Inc. is the provider of // PostScript and PDF technology for software developers. // //---------------------------------------------------------------------------- // Contact: [email protected] // [email protected] // http://www.antigrain.com //---------------------------------------------------------------------------- #ifndef AGG_COLOR_RGBA_INCLUDED #define AGG_COLOR_RGBA_INCLUDED #include <math.h> #include "agg_basics.h" namespace agg { // Supported byte orders for RGB and RGBA pixel formats //======================================================================= struct order_rgb { enum rgb_e { R=0, G=1, B=2, rgb_tag }; }; //----order_rgb struct order_bgr { enum bgr_e { B=0, G=1, R=2, rgb_tag }; }; //----order_bgr struct order_rgba { enum rgba_e { R=0, G=1, B=2, A=3, rgba_tag }; }; //----order_rgba struct order_argb { enum argb_e { A=0, R=1, G=2, B=3, rgba_tag }; }; //----order_argb struct order_abgr { enum abgr_e { A=0, B=1, G=2, R=3, rgba_tag }; }; //----order_abgr struct order_bgra { enum bgra_e { B=0, G=1, R=2, A=3, rgba_tag }; }; //----order_bgra //====================================================================rgba struct rgba { typedef double value_type; double r; double g; double b; double a; //-------------------------------------------------------------------- rgba() {} //-------------------------------------------------------------------- rgba(double r_, double g_, double b_, double a_=1.0) : r(r_), g(g_), b(b_), a(a_) {} //-------------------------------------------------------------------- rgba(const rgba& c, double a_) : r(c.r), g(c.g), b(c.b), a(a_) {} //-------------------------------------------------------------------- void clear() { r = g = b = a = 0; } //-------------------------------------------------------------------- const rgba& transparent() { a = 0.0; return *this; } //-------------------------------------------------------------------- const rgba& opacity(double a_) { if(a_ < 0.0) a_ = 0.0; if(a_ > 1.0) a_ = 1.0; a = a_; return *this; } //-------------------------------------------------------------------- double opacity() const { return a; } //-------------------------------------------------------------------- const rgba& premultiply() { r *= a; g *= a; b *= a; return *this; } //-------------------------------------------------------------------- const rgba& premultiply(double a_) { if(a <= 0.0 || a_ <= 0.0) { r = g = b = a = 0.0; return *this; } a_ /= a; r *= a_; g *= a_; b *= a_; a = a_; return *this; } //-------------------------------------------------------------------- const rgba& demultiply() { if(a == 0) { r = g = b = 0; return *this; } double a_ = 1.0 / a; r *= a_; g *= a_; b *= a_; return *this; } //-------------------------------------------------------------------- rgba gradient(rgba c, double k) const { rgba ret; ret.r = r + (c.r - r) * k; ret.g = g + (c.g - g) * k; ret.b = b + (c.b - b) * k; ret.a = a + (c.a - a) * k; return ret; } //-------------------------------------------------------------------- static rgba no_color() { return rgba(0,0,0,1.0); } //-------------------------------------------------------------------- static rgba from_wavelength(double wl, double gamma = 1.0); //-------------------------------------------------------------------- explicit rgba(double wavelen, double gamma=1.0) { *this = from_wavelength(wavelen, gamma); } }; //----------------------------------------------------------------rgba_pre inline rgba rgba_pre(double r, double g, double b, double a=1.0) { return rgba(r, g, b, a).premultiply(); } inline rgba rgba_pre(const rgba& c) { return rgba(c).premultiply(); } inline rgba rgba_pre(const rgba& c, double a) { return rgba(c, a).premultiply(); } //------------------------------------------------------------------------ inline rgba rgba::from_wavelength(double wl, double gamma) { rgba t(0.0, 0.0, 0.0); if(wl >= 380.0 && wl <= 440.0) { t.r = -1.0 * (wl - 440.0) / (440.0 - 380.0); t.b = 1.0; } else if(wl >= 440.0 && wl <= 490.0) { t.g = (wl - 440.0) / (490.0 - 440.0); t.b = 1.0; } else if(wl >= 490.0 && wl <= 510.0) { t.g = 1.0; t.b = -1.0 * (wl - 510.0) / (510.0 - 490.0); } else if(wl >= 510.0 && wl <= 580.0) { t.r = (wl - 510.0) / (580.0 - 510.0); t.g = 1.0; } else if(wl >= 580.0 && wl <= 645.0) { t.r = 1.0; t.g = -1.0 * (wl - 645.0) / (645.0 - 580.0); } else if(wl >= 645.0 && wl <= 780.0) { t.r = 1.0; } double s = 1.0; if(wl > 700.0) s = 0.3 + 0.7 * (780.0 - wl) / (780.0 - 700.0); else if(wl < 420.0) s = 0.3 + 0.7 * (wl - 380.0) / (420.0 - 380.0); t.r = pow(t.r * s, gamma); t.g = pow(t.g * s, gamma); t.b = pow(t.b * s, gamma); return t; } //===================================================================rgba8 struct rgba8 { typedef int8u value_type; typedef int32u calc_type; typedef int32 long_type; enum base_scale_e { base_shift = 8, base_size = 1 << base_shift, base_mask = base_size - 1 }; typedef rgba8 self_type; value_type r; value_type g; value_type b; value_type a; //-------------------------------------------------------------------- rgba8() {} //-------------------------------------------------------------------- rgba8(unsigned r_, unsigned g_, unsigned b_, unsigned a_=0) : r(value_type(r_)), g(value_type(g_)), b(value_type(b_)), a(value_type(a_)) {} //-------------------------------------------------------------------- rgba8(const rgba& c, double a_) : r(value_type(c.r * double(base_mask) + 0.5)), g(value_type(c.g * double(base_mask) + 0.5)), b(value_type(c.b * double(base_mask) + 0.5)), a(value_type(a_ * double(base_mask) + 0.5)) {} //-------------------------------------------------------------------- rgba8(const self_type& c, unsigned a_) : r(c.r), g(c.g), b(c.b), a(value_type(a_)) {} //-------------------------------------------------------------------- rgba8(const rgba& c) : r(value_type(c.r * double(base_mask) + 0.5)), g(value_type(c.g * double(base_mask) + 0.5)), b(value_type(c.b * double(base_mask) + 0.5)), a(value_type(c.a * double(base_mask) + 0.5)) {} //-------------------------------------------------------------------- void clear() { r = g = b = a = 0; } //-------------------------------------------------------------------- const self_type& transparent() { a = 255; return *this; } //-------------------------------------------------------------------- const self_type& opacity(double a_) { if(a_ < 0.0) a_ = 0.0; if(a_ > 1.0) a_ = 1.0; a = value_type(a_ * double(base_mask) + 0.5); return *this; } //-------------------------------------------------------------------- double opacity() const { return double(a) / double(base_mask); } //-------------------------------------------------------------------- const self_type& premultiply() { if(a == base_mask) return *this; if(a == 0) { r = g = b = 0; return *this; } r = value_type((calc_type(r) * a) >> base_shift); g = value_type((calc_type(g) * a) >> base_shift); b = value_type((calc_type(b) * a) >> base_shift); return *this; } //-------------------------------------------------------------------- const self_type& premultiply(unsigned a_) { if(a == base_mask && a_ >= base_mask) return *this; if(a == 0 || a_ == 0) { r = g = b = a = 0; return *this; } calc_type r_ = (calc_type(r) * a_) / a; calc_type g_ = (calc_type(g) * a_) / a; calc_type b_ = (calc_type(b) * a_) / a; r = value_type((r_ > a_) ? a_ : r_); g = value_type((g_ > a_) ? a_ : g_); b = value_type((b_ > a_) ? a_ : b_); a = value_type(a_); return *this; } //-------------------------------------------------------------------- const self_type& demultiply() { if(a == base_mask) return *this; if(a == 0) { r = g = b = 0; return *this; } calc_type r_ = (calc_type(r) * base_mask) / a; calc_type g_ = (calc_type(g) * base_mask) / a; calc_type b_ = (calc_type(b) * base_mask) / a; r = value_type((r_ > base_mask) ? base_mask : r_); g = value_type((g_ > base_mask) ? base_mask : g_); b = value_type((b_ > base_mask) ? base_mask : b_); return *this; } //-------------------------------------------------------------------- self_type gradient(const self_type& c, double k) const { self_type ret; calc_type ik = calc_type(k * base_size); ret.r = value_type(calc_type(r) + (((calc_type(c.r) - r) * ik) >> base_shift)); ret.g = value_type(calc_type(g) + (((calc_type(c.g) - g) * ik) >> base_shift)); ret.b = value_type(calc_type(b) + (((calc_type(c.b) - b) * ik) >> base_shift)); ret.a = value_type(calc_type(a) + (((calc_type(c.a) - a) * ik) >> base_shift)); return ret; } //-------------------------------------------------------------------- static self_type no_color() { return self_type(0,0,0,255); } //-------------------------------------------------------------------- static self_type from_wavelength(double wl, double gamma = 1.0) { return self_type(rgba::from_wavelength(wl, gamma)); } }; //-------------------------------------------------------------rgba8_pre inline rgba8 rgba8_pre(unsigned r, unsigned g, unsigned b, unsigned a = rgba8::base_mask) { return rgba8(r,g,b,a).premultiply(); } inline rgba8 rgba8_pre(const rgba8& c) { return rgba8(c).premultiply(); } inline rgba8 rgba8_pre(const rgba8& c, unsigned a) { return rgba8(c,a).premultiply(); } inline rgba8 rgba8_pre(const rgba& c) { return rgba8(c).premultiply(); } inline rgba8 rgba8_pre(const rgba& c, double a) { return rgba8(c,a).premultiply(); } //-----------------------------------------------------------rgb8_packed inline rgba8 rgb8_packed(unsigned v) { return rgba8((v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF); } //-----------------------------------------------------------bgr8_packed inline rgba8 bgr8_packed(unsigned v) { return rgba8(v & 0xFF, (v >> 8) & 0xFF, (v >> 16) & 0xFF); } //----------------------------------------------------------argb8_packed inline rgba8 argb8_packed(unsigned v) { return rgba8((v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF, v >> 24); } //=================================================================rgba16 struct rgba16 { typedef int16u value_type; typedef int32u calc_type; typedef int64 long_type; enum base_scale_e { base_shift = 16, base_size = 1 << base_shift, base_mask = base_size - 1 }; typedef rgba16 self_type; value_type r; value_type g; value_type b; value_type a; //-------------------------------------------------------------------- rgba16() {} //-------------------------------------------------------------------- rgba16(unsigned r_, unsigned g_, unsigned b_, unsigned a_=base_mask) : r(value_type(r_)), g(value_type(g_)), b(value_type(b_)), a(value_type(a_)) {} //-------------------------------------------------------------------- rgba16(const self_type& c, unsigned a_) : r(c.r), g(c.g), b(c.b), a(value_type(a_)) {} //-------------------------------------------------------------------- rgba16(const rgba& c) : r(value_type(c.r * double(base_mask) + 0.5)), g(value_type(c.g * double(base_mask) + 0.5)), b(value_type(c.b * double(base_mask) + 0.5)), a(value_type(c.a * double(base_mask) + 0.5)) {} //-------------------------------------------------------------------- rgba16(const rgba& c, double a_) : r(value_type(c.r * double(base_mask) + 0.5)), g(value_type(c.g * double(base_mask) + 0.5)), b(value_type(c.b * double(base_mask) + 0.5)), a(value_type(a_ * double(base_mask) + 0.5)) {} //-------------------------------------------------------------------- rgba16(const rgba8& c) : r(value_type((value_type(c.r) << 8) | c.r)), g(value_type((value_type(c.g) << 8) | c.g)), b(value_type((value_type(c.b) << 8) | c.b)), a(value_type((value_type(c.a) << 8) | c.a)) {} //-------------------------------------------------------------------- rgba16(const rgba8& c, unsigned a_) : r(value_type((value_type(c.r) << 8) | c.r)), g(value_type((value_type(c.g) << 8) | c.g)), b(value_type((value_type(c.b) << 8) | c.b)), a(value_type(( a_ << 8) | c.a)) {} //-------------------------------------------------------------------- void clear() { r = g = b = a = 0; } //-------------------------------------------------------------------- const self_type& transparent() { a = 0; return *this; } //-------------------------------------------------------------------- const self_type& opacity(double a_) { if(a_ < 0.0) a_ = 0.0; if(a_ > 1.0) a_ = 1.0; a = value_type(a_ * double(base_mask) + 0.5); return *this; } //-------------------------------------------------------------------- double opacity() const { return double(a) / double(base_mask); } //-------------------------------------------------------------------- const self_type& premultiply() { if(a == base_mask) return *this; if(a == 0) { r = g = b = 0; return *this; } r = value_type((calc_type(r) * a) >> base_shift); g = value_type((calc_type(g) * a) >> base_shift); b = value_type((calc_type(b) * a) >> base_shift); return *this; } //-------------------------------------------------------------------- const self_type& premultiply(unsigned a_) { if(a == base_mask && a_ >= base_mask) return *this; if(a == 0 || a_ == 0) { r = g = b = a = 0; return *this; } calc_type r_ = (calc_type(r) * a_) / a; calc_type g_ = (calc_type(g) * a_) / a; calc_type b_ = (calc_type(b) * a_) / a; r = value_type((r_ > a_) ? a_ : r_); g = value_type((g_ > a_) ? a_ : g_); b = value_type((b_ > a_) ? a_ : b_); a = value_type(a_); return *this; } //-------------------------------------------------------------------- const self_type& demultiply() { if(a == base_mask) return *this; if(a == 0) { r = g = b = 0; return *this; } calc_type r_ = (calc_type(r) * base_mask) / a; calc_type g_ = (calc_type(g) * base_mask) / a; calc_type b_ = (calc_type(b) * base_mask) / a; r = value_type((r_ > base_mask) ? base_mask : r_); g = value_type((g_ > base_mask) ? base_mask : g_); b = value_type((b_ > base_mask) ? base_mask : b_); return *this; } //-------------------------------------------------------------------- self_type gradient(const self_type& c, double k) const { self_type ret; calc_type ik = calc_type(k * base_size); ret.r = value_type(calc_type(r) + (((calc_type(c.r) - r) * ik) >> base_shift)); ret.g = value_type(calc_type(g) + (((calc_type(c.g) - g) * ik) >> base_shift)); ret.b = value_type(calc_type(b) + (((calc_type(c.b) - b) * ik) >> base_shift)); ret.a = value_type(calc_type(a) + (((calc_type(c.a) - a) * ik) >> base_shift)); return ret; } //-------------------------------------------------------------------- static self_type no_color() { return self_type(0,0,0,0); } //-------------------------------------------------------------------- static self_type from_wavelength(double wl, double gamma = 1.0) { return self_type(rgba::from_wavelength(wl, gamma)); } }; //--------------------------------------------------------------rgba16_pre inline rgba16 rgba16_pre(unsigned r, unsigned g, unsigned b, unsigned a = rgba16::base_mask) { return rgba16(r,g,b,a).premultiply(); } inline rgba16 rgba16_pre(const rgba16& c, unsigned a) { return rgba16(c,a).premultiply(); } inline rgba16 rgba16_pre(const rgba& c) { return rgba16(c).premultiply(); } inline rgba16 rgba16_pre(const rgba& c, double a) { return rgba16(c,a).premultiply(); } inline rgba16 rgba16_pre(const rgba8& c) { return rgba16(c).premultiply(); } inline rgba16 rgba16_pre(const rgba8& c, unsigned a) { return rgba16(c,a).premultiply(); } } #endif
[ [ [ 1, 618 ] ] ]
276a4b52b51b7a6b89edcea0daa3587a7ba09813
95e051bc96bd3f765ce1cec4868535b667be81b6
/ExplodedView_old/src/ColorVisitor.h
e4ac323b1ef89108bcaa885c7ffe2512fef26a72
[]
no_license
fabio-miranda/exploded
6aacdb5ca1250b676990572ef028fcbc0af93b1a
12ca185b161b78d0b903c86fb5a08cee3ed87362
refs/heads/master
2021-05-29T09:06:03.007813
2010-02-26T04:40:32
2010-02-26T04:40:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,039
h
#include <osg/NodeVisitor> #include <osg/Node> #include <osg/Material> class ColorVisitor : public osg::NodeVisitor { public: ColorVisitor (const osg::Vec4& pColor): osg::NodeVisitor(TRAVERSE_ALL_CHILDREN), mColor(pColor) { } virtual void apply(osg::Geode& geode) { osg::StateSet* ss = geode.getOrCreateStateSet(); unsigned pNumDrawables = geode.getNumDrawables(); for(unsigned i = 0; i < pNumDrawables; ++i) { osg::Drawable* draw = geode.getDrawable(i); //osg::Material* mat = new osg::Material(); osg::Material* mat = dynamic_cast<osg::Material*>(draw->getOrCreateStateSet()->getAttribute(osg::StateAttribute::MATERIAL)); if(mat) { mat->setDiffuse(osg::Material::FRONT_AND_BACK, mColor); mat->setEmission(osg::Material::FRONT_AND_BACK, mColor); } //draw->getOrCreateStateSet()->setAttributeAndModes(osg::StateAttribute::MATERIAL, mat); } } private: osg::Vec4 mColor; };
[ "fabiom@2fa1dc7e-98ce-11de-bff5-93fd3790126f" ]
[ [ [ 1, 39 ] ] ]
3b3a45d3ef7f589f71c677c58c7d02bf95715d1d
975d45994f670a7f284b0dc88d3a0ebe44458a82
/servidor/Testes/Comunicação/Comunicação/Comunicação/stdafx.cpp
8b24b26133cac06bb5386f3ad919b8fbae311b43
[]
no_license
phabh/warbugs
2b616be17a54fbf46c78b576f17e702f6ddda1e6
bf1def2f8b7d4267fb7af42df104e9cdbe0378f8
refs/heads/master
2020-12-25T08:51:02.308060
2010-11-15T00:37:38
2010-11-15T00:37:38
60,636,297
0
0
null
null
null
null
ISO-8859-1
C++
false
false
300
cpp
// stdafx.cpp : source file that includes just the standard includes // Comunicação.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ [ [ 1, 8 ] ] ]
dbc16c7431b297a79cd020f542cee585fe344c3a
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/libs/STLPort-4.0/stlport/stl/debug/_hashtable.h
8eded624fb24f7f40181bc188dab199a3c7960a9
[ "LicenseRef-scancode-stlport-4.5" ]
permissive
rickyharis39/nolf2
ba0b56e2abb076e60d97fc7a2a8ee7be4394266c
0da0603dc961e73ac734ff365bfbfb8abb9b9b04
refs/heads/master
2021-01-01T17:21:00.678517
2011-07-23T12:11:19
2011-07-23T12:11:19
38,495,312
1
0
null
null
null
null
UTF-8
C++
false
false
8,112
h
/* * * Copyright (c) 1994 * Hewlett-Packard Company * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Copyright (c) 1997 * Moscow Center for SPARC Technology * * Copyright (c) 1999 * Boris Fomitchev * * This material is provided "as is", with absolutely no warranty expressed * or implied. Any use is at your own risk. * * Permission to use or copy this software for any purpose is hereby granted * without fee, provided the above notices are retained on all copies. * Permission to modify the code and to distribute modified code is granted, * provided the above notices are retained, and a notice that the code was * modified is included with the above copyright notice. * */ /* NOTE: This is an internal header file, included by other STL headers. * You should not attempt to use it directly. */ #ifndef __SGI_STL_INTERNAL_DBG_HASHTABLE_H #define __SGI_STL_INTERNAL_DBG_HASHTABLE_H // Hashtable class, used to implement the hashed associative containers // hash_set, hash_map, hash_multiset, and hash_multimap. # include <stl/debug/_iterator.h> # undef hashtable # undef _DBG_hashtable # define _DBG_hashtable hashtable # define __STL_DBG_HT_SUPER \ __WORKAROUND_DBG_RENAME(hashtable) <_Val, _Key, _HF, _ExK, _EqK, _All> __STL_BEGIN_NAMESPACE # ifdef __STL_DEBUG_USE_DISTINCT_VALUE_TYPE_HELPERS template <class _Val, class _Key, class _HF, class _ExK, class _EqK, class _All> inline _Val* __VALUE_TYPE(const _DBG_iter_base< __STL_DBG_HT_SUPER >&) { return (_Val*)0; } template <class _Val, class _Key, class _HF, class _ExK, class _EqK, class _All> inline forward_iterator_tag __ITERATOR_CATEGORY(const _DBG_iter_base< __STL_DBG_HT_SUPER >&) { return forward_iterator_tag(); } # endif template <class _Val, class _Key, class _HF, class _ExK, class _EqK, class _All> class _DBG_hashtable : public __STL_DBG_HT_SUPER { typedef _DBG_hashtable<_Val, _Key, _HF, _ExK, _EqK, _All> _Self; typedef __STL_DBG_HT_SUPER _Base; public: typedef _Key key_type; typedef _HF hasher; typedef _EqK key_equal; __IMPORT_CONTAINER_TYPEDEFS(_Base) public: typedef _DBG_iter<_Base, _Nonconst_traits<value_type> > iterator; typedef _DBG_iter<_Base, _Const_traits<value_type> > const_iterator; typedef typename _Base::iterator _Base_iterator; typedef typename _Base::const_iterator _Base_const_iterator; public: _DBG_hashtable(size_type __n, const _HF& __hf, const _EqK& __eql, const _ExK& __ext, const allocator_type& __a = allocator_type()): __STL_DBG_HT_SUPER(__n, __hf, __eql, __ext, __a), _M_iter_list((_Base*)this) {} _DBG_hashtable(size_type __n, const _HF& __hf, const _EqK& __eql, const allocator_type& __a = allocator_type()): __STL_DBG_HT_SUPER(__n, __hf, __eql, __a), _M_iter_list((_Base*)this) {} _DBG_hashtable(const _Self& __ht): __STL_DBG_HT_SUPER(__ht), _M_iter_list((_Base*)this) {} _Self& operator= (const _Self& __ht) { _M_iter_list._Invalidate_all(); _Base::operator=(__ht); return *this; } void swap(_Self& __ht) { _Swap_owners(__ht); _Base::swap(__ht); } iterator begin() { return iterator(&_M_iter_list, _Base::begin()); } iterator end() { return iterator(&_M_iter_list, _Base::end()); } const_iterator begin() const { return const_iterator(&_M_iter_list, _Base::begin()); } const_iterator end() const { return const_iterator(&_M_iter_list, _Base::end()); } pair<iterator, bool> insert_unique(const value_type& __obj) { pair < _Base_iterator, bool> __res = _Base::insert_unique(__obj); return pair<iterator, bool> ( iterator(&_M_iter_list, __res.first), __res.second); } iterator insert_equal(const value_type& __obj) { return iterator(&_M_iter_list, _Base::insert_equal(__obj)); } pair<iterator, bool> insert_unique_noresize(const value_type& __obj) { pair < _Base_iterator, bool> __res = _Base::insert_unique_noresize(__obj); return pair<iterator, bool> ( iterator(&_M_iter_list, __res.first), __res.second); } iterator insert_equal_noresize(const value_type& __obj) { return iterator(&_M_iter_list, _Base::insert_equal_noresize(__obj)); } #ifdef __STL_MEMBER_TEMPLATES template <class _InputIterator> void insert_unique(_InputIterator __f, _InputIterator __l) { _Base::insert_unique(__f, __l); } template <class _InputIterator> void insert_equal(_InputIterator __f, _InputIterator __l){ _Base::insert_equal(__f, __l); } #else /* __STL_MEMBER_TEMPLATES */ void insert_unique(const value_type* __f, const value_type* __l) { _Base::insert_unique(__f, __l); } void insert_equal(const value_type* __f, const value_type* __l) { _Base::insert_equal(__f, __l); } void insert_unique(const_iterator __f, const_iterator __l) { _Base::insert_unique(__f._M_iterator, __l._M_iterator); } void insert_equal(const_iterator __f, const_iterator __l) { _Base::insert_equal(__f._M_iterator, __l._M_iterator); } #endif /*__STL_MEMBER_TEMPLATES */ iterator find(const key_type& __key) { return iterator(&_M_iter_list, _Base::find(__key)); } const_iterator find(const key_type& __key) const { return const_iterator(&_M_iter_list, _Base::find(__key)); } pair<iterator, iterator> equal_range(const key_type& __key) { pair < _Base_iterator, _Base_iterator > __res = _Base::equal_range(__key); return pair<iterator,iterator> (iterator(&_M_iter_list,__res.first), iterator(&_M_iter_list,__res.second)); } pair<const_iterator, const_iterator> equal_range(const key_type& __key) const { pair < _Base_iterator, _Base_iterator > __res = _Base::equal_range(__key); return pair<const_iterator,const_iterator> (const_iterator(&_M_iter_list,__res.first), const_iterator(&_M_iter_list,__res.second)); } size_type erase(const key_type& __key) { return _Base::erase(__key); } void erase(const const_iterator& __it) { __STL_VERBOSE_ASSERT(__it._Owner()==&_M_iter_list, _StlMsg_NOT_OWNER) _Base::erase(__it._M_iterator); } void erase(const_iterator __first, const_iterator __last) { __STL_DEBUG_CHECK(__check_if_owner(&_M_iter_list, __first)&& __check_if_owner(&_M_iter_list, __last)) _Base::erase(__first._M_iterator, __last._M_iterator); } void resize(size_type __num_elements_hint) { _Base::resize(__num_elements_hint); } void clear() { _M_iter_list._Invalidate_all(); _Base::clear(); } private: __owned_list _M_iter_list; }; #ifdef __STL_EXTRA_OPERATORS_FOR_DEBUG template <class _Val, class _Key, class _HF, class _ExK, class _EqK, class _All> inline bool operator==(const _DBG_hashtable<_Val,_Key,_HF,_ExK,_EqK,_All>& __ht1, const _DBG_hashtable<_Val,_Key,_HF,_ExK,_EqK,_All>& __ht2) { return hashtable<_Val,_Key,_HF,_ExK,_EqK,_All>::_M_equal( __ht1, __ht2 ); } #ifdef __STL_USE_SEPARATE_RELOPS_NAMESPACE template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All> inline bool operator!=(const _DBG_hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>& __ht1, const _DBG_hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>& __ht2) { return !(__ht1 == __ht2); } #endif /* __STL_USE_SEPARATE_RELOPS_NAMESPACE */ #endif /* __STL_EXTRA_OPERATORS_FOR_DEBUG */ #ifdef __STL_FUNCTION_TMPL_PARTIAL_ORDER template <class _Val, class _Key, class _HF, class _ExK, class _EqK, class _All> inline void swap( _DBG_hashtable<_Val, _Key, _HF, _ExK, _EqK, _All>& __ht1, _DBG_hashtable<_Val, _Key, _HF, _ExK, _EqK, _All>& __ht2) { __ht1.swap(__ht2); } #endif __STL_END_NAMESPACE # undef hashtable #endif /* __SGI_STL_INTERNAL_HASHTABLE_H */ // Local Variables: // mode:C++ // End:
[ [ [ 1, 256 ] ] ]
0ac1c24f54c7b09c28a9d45f629e7269011da06c
30898d899aa49d5801dab4f0df19fca18a2d4d02
/yltk/yltkToken.cxx
c5b3964e4a49734a503a098bdb5114708c27cdb8
[]
no_license
jackyko1991/vtkpythonext
c278987c7c61f7e610eec277ca3c9e42df097fa5
6d20ce2071581064616064a36243646a96e4c75e
refs/heads/master
2021-01-10T19:32:45.869634
2011-03-20T03:15:55
2011-03-20T03:15:55
40,592,349
2
1
null
null
null
null
UTF-8
C++
false
false
1,382
cxx
#include "yltkToken.h" #include "yltkSimpleFastMutexLock.h" #include <iostream> namespace yltk { /** The counter for providing pseudo-unique identifiers for tokens */ Token::IdentifierType Token::m_IdentifierCounter = 1; /** Used for mutex locking */ static ::yltk::SimpleFastMutexLock TokenMutex; /** Constructor */ Token::Token() { /** Start mutual exclusion section. This prevent race conditions when * multiple threads are creating Tokens simultaneously */ TokenMutex.Lock(); /** When the IdentifierCounter rolls over (reaches it maximum value and * restars from zero) the Uniqueness of identifiers can no longer be * guaranted. */ this->m_Identifier = m_IdentifierCounter++; TokenMutex.Unlock(); } /** Destructor */ Token::~Token() { } /** Print Self function */ void Token::PrintSelf( std::ostream& os, yltk::Indent indent ) const { os << indent << "RTTI typeinfo: " << typeid( *this ).name() << std::endl; os << indent << "Identifier: " << this->m_Identifier << std::endl; } void Token::Print(std::ostream& os, yltk::Indent indent) const { os << indent << "Token" << " (" << this << ")\n"; this->PrintSelf(os, indent.GetNextIndent()); } std::ostream& operator<<(std::ostream& os, const Token& o) { o.Print(os, 0); return os; } } // end namespace igstk
[ "summit.chocice@6ba1a03e-a7e1-11de-9ca8-173d21a9ba08" ]
[ [ [ 1, 55 ] ] ]
78695ea90f1b4aa032d684f990189ee2ea036e04
7a4dfb986f5bd5fbee2186fcf37a0a0a74ef6033
/SubtitleGrabber/HTTPRequest.h
3b12b6f8d47b5a93a736324139abcb2270584548
[]
no_license
zsjoska/subtitle-grabber
cad96727e73d6d3ec58eb3ad5eb1dfbac0c646bd
8de1a741b2b7fdd2e7899738839516e729d23430
refs/heads/master
2016-09-06T19:14:26.133224
2007-05-30T09:20:55
2007-05-30T09:20:55
32,320,106
0
0
null
null
null
null
UTF-8
C++
false
false
509
h
#pragma once #include "httpcontent.h" class CHTTPRequest : public CHTTPContent { public: CHTTPRequest(void); ~CHTTPRequest(void); void SetRequestURL( CString strURL); void SetMethod(CString strMethod); void SetHTTPVersion(CString strHttp); inline CString GetServer(){ return m_strServer; } LPCSTR PrepareRequest(int & iSendCount); BOOL CanPersist(); private: CString m_strMethod; CString m_strUri; CString m_strServer; CString m_strHTTPVer; void FormatCommand(); };
[ "zsjoska@a99920ad-ab31-0410-9f62-6da89933afc0" ]
[ [ [ 1, 25 ] ] ]
a1ba27d2d160477cb392e999d5fcabf4b3928289
9ad9345e116ead00be7b3bd147a0f43144a2e402
/Extraction/SMDataExtraction/SMDataExtraction/PureStringAttInfo.h
665f88581991d08cc0535440638eb009ce9a75a5
[]
no_license
asankaf/scalable-data-mining-framework
e46999670a2317ee8d7814a4bd21f62d8f9f5c8f
811fddd97f52a203fdacd14c5753c3923d3a6498
refs/heads/master
2020-04-02T08:14:39.589079
2010-07-18T16:44:56
2010-07-18T16:44:56
33,870,353
0
0
null
null
null
null
UTF-8
C++
false
false
524
h
#pragma once #include "PureAttInfo.h" #include <cstring> #include <string> #include <vector> using namespace std; class PureStringAttInfo : public PureAttInfo { public: PureStringAttInfo(void); ~PureStringAttInfo(void); __declspec(dllexport) string* ValueList(); __declspec(dllexport) void setValueList(string* values,int noRows); __declspec(dllexport) vector<string> uniqueValueList(); void setUniqueValueList(int noRows); private: string* _valueList; vector<string> _uniqueValList; };
[ "jaadds@c7f6ba40-6498-11de-987a-95e5a5a5d5f1" ]
[ [ [ 1, 24 ] ] ]
dcbf96fc088d0572963a9b6610a5ed15bad51fd6
2a3952c00a7835e6cb61b9cb371ce4fb6e78dc83
/BasicOgreFramework/PhysxSDK/Graphics/include/Object.h
7f5d414973b253abb980e9c53a9c5bb08a88d879
[]
no_license
mgq812/simengines-g2-code
5908d397ef2186e1988b1d14fa8b73f4674f96ea
699cb29145742c1768857945dc59ef283810d511
refs/heads/master
2016-09-01T22:57:54.845817
2010-01-11T19:26:51
2010-01-11T19:26:51
32,267,377
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
4,368
h
#ifndef _SG_OBJECT_H__ #define _SG_OBJECT_H__ /*----------------------------------------------------------------------------*\ | | Ageia PhysX Technology | | www.ageia.com | \*----------------------------------------------------------------------------*/ #include <3DMath.h> namespace SceneGraph { class Model; class Primitive; class Object /*-------------------------------*\ | Anything that is displayed in the scene. | Has location (but may be special for) | background, may have special status like camera. | May or may not (camera) have "looks" == a model. Objects are either owned by the scene (top level) or by their parents. This is strictly a forest, not a dag, i.e. objects always have max a single parent. \*-------------------------------*/ { public: Object(Model * m = 0, Object * parent = 0); ~Object(); virtual void render(); void renderAsCamera(); void renderAsLight(int lightNo); //manipulation: void setScale(flo s); void setPosition(flo x,flo y, flo z); void setPosition(Vec3 * Position); //define later as needed void setOrientation(Quat * Quat); void setOrientation(Vec3 * YawPitchRoll); void setVisibility(bool bVisible); void lookAt(Vec3 * Target, Vec3 * Up); //useful for cameras void updateMatrix(); //call this if Pos or orient changed manually. //tree structure: Object *createChild(Model * clopModel); //if all 3 nodes are filled, expands tree with a NULL node and creates a new leaf. void addChild(Object *child); //ditto. bool deleteChild(Object * clopObj); //removes passed obj from subtrees if its there. (returns true on success.) bool removeChild(Object * clopObj); //removes passed object, removing also it's whole subtree, without deleting anything. void getBoundingBox(Vec3 & dims); //ask for bounding box. Only works when containing a Model! Returns box edge lengths, not radii. Model * collapseSubtreeToNewModel(Model * m = 0, bool keepMaterials = true, bool meshesInParentsSpace = false, clMatrix4x4 * _ = 0); //create a new model3 that will have a single mesh with all the submeshes of this object, with vertices in the space of this object. //if keep materials is false, all the submeshes also get merged. //if a model with a mesh is passed, stuff gets merged in there, otherwise a new one is created. //xforms encountered in the subtree will be executed on the meshes in the subtree. //meshesInParentsSpace determines if the transform of this is execute or not. //Note: the returned model is not made into the model of the current node. void deleteSubtree(); //deletes all child objects of this node. Other referenced objects are not deleted. void removeSubtree(); //same as deleteSubtree, but doesn't deallocate nodes in subtree. void executeTransform(); //transforms all meshes in subtree to the space of our parent, and sets our transform to identity. Model * model; //a model (may be NULL for cameras) not owned. Primitive * primitive; //a graphics primitive. Owned. float scale; Vec3 position; Quat qOrientation; clMatrix4x4 orientation; clMatrix4x4 model2World; //does not contain scaling bool bNullXform; //indicates that above xforms and model are to be ignored -- this obj is only a storage node for //child nodes. Object * leftObj, *middleObj,*rightObj; //descendants ternary tree //objs. Owned. Object * parentObj; //parent of this node in ternary tree, may be null. //Only needed for rendering obj as camera, //would be nice if we could eliminate it. bool bHideModel; //set to true to not render model. Does not hide entire subtree. bool bHideSubtree; //hides all children bool bWireFrame; //forces wireframe view. bool bTwoSided; //no culling }; }; #endif //__OBJECT_H__ //AGCOPYRIGHTBEGIN /////////////////////////////////////////////////////////////////////////// // Copyright © 2005 AGEIA Technologies. // All rights reserved. www.ageia.com /////////////////////////////////////////////////////////////////////////// //AGCOPYRIGHTEND
[ "erucarno@789472dc-e1c3-11de-81d3-db62269da9c1" ]
[ [ [ 1, 99 ] ] ]
5f9966f53ca4605512e6ef1a774bfa84ef0cfb41
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Physics/Dynamics/World/Listener/hkpIslandActivationListener.h
eb0350dd6998682e8cbce33e0f7d7128e3e6ddb8
[]
no_license
blockspacer/transporter-game
23496e1651b3c19f6727712a5652f8e49c45c076
083ae2ee48fcab2c7d8a68670a71be4d09954428
refs/heads/master
2021-05-31T04:06:07.101459
2009-02-19T20:59:59
2009-02-19T20:59:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,181
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_DYNAMICS2_ISLAND_ACTIVATION_LISTENER_H #define HK_DYNAMICS2_ISLAND_ACTIVATION_LISTENER_H class hkpSimulationIsland; /// Derive from this class, and add to hkpWorld using hkpWorld::addIslandActivationListener() /// You will then receive callbacks when simulation islands are activated and deactivated class hkpIslandActivationListener { public: virtual ~hkpIslandActivationListener() {} /// Called when an island is activated. /// NOTE: Activation and Deactivation callbacks are not symmetrical, /// and neither is called upon island creation and destruction. virtual void islandActivatedCallback( hkpSimulationIsland* island ) = 0; /// Called when an island is deactivated. /// NOTE: Activation and Deactivation callbacks are not symmetrical, /// and neither is called upon island creation and destruction. virtual void islandDeactivatedCallback( hkpSimulationIsland* island ) = 0; }; #endif // HK_DYNAMICS2_WORLD_ACTIVATION_LISTENER_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529) * * Confidential Information of Havok. (C) Copyright 1999-2008 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at * www.havok.com/tryhavok * */
[ "uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4" ]
[ [ [ 1, 51 ] ] ]
44ede6977d3e0a66009baab8642e99c94f70b368
eae59c3051213d3154057daf93890e5829f895c6
/Labms_v1/Labms_v1/GeneratedFiles/Debug/moc_AboutDlg.cpp
8be27cb97317ae0410e9bee42202fc7b726cdf0d
[]
no_license
firemariovn/tortoiseforlabms
1fa2e7e712dd22db92c46a4b55d77576caf93ebc
bfcb0e5acedbf5318ac0b4890bdb46892cac70d9
refs/heads/master
2021-01-25T12:07:33.838491
2010-08-25T10:14:07
2010-08-25T10:14:07
39,875,746
0
0
null
null
null
null
UTF-8
C++
false
false
2,374
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'AboutDlg.h' ** ** Created: Wed Aug 25 17:55:47 2010 ** by: The Qt Meta Object Compiler version 62 (Qt 4.6.3) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../AboutDlg.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'AboutDlg.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 62 #error "This file was generated using the moc from 4.6.3. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_AboutDlg[] = { // content: 4, // revision 0, // classname 0, 0, // classinfo 1, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: signature, parameters, type, tag, flags 10, 9, 9, 9, 0x0a, 0 // eod }; static const char qt_meta_stringdata_AboutDlg[] = { "AboutDlg\0\0clickedOKBtn()\0" }; const QMetaObject AboutDlg::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_AboutDlg, qt_meta_data_AboutDlg, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &AboutDlg::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *AboutDlg::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *AboutDlg::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_AboutDlg)) return static_cast<void*>(const_cast< AboutDlg*>(this)); return QDialog::qt_metacast(_clname); } int AboutDlg::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDialog::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: clickedOKBtn(); break; default: ; } _id -= 1; } return _id; } QT_END_MOC_NAMESPACE
[ "PL080516@8578381e-9b32-7834-3d0b-259b2497d42e" ]
[ [ [ 1, 79 ] ] ]
88885454476ef15a2e2b7c2c03fdbed8893eddd0
971b000b9e6c4bf91d28f3723923a678520f5bcf
/demo_write_mng/movieplayer.h
baa83f9ebe0afb3d014de1524af032a762d76948
[]
no_license
google-code-export/fop-miniscribus
14ce53d21893ce1821386a94d42485ee0465121f
966a9ca7097268c18e690aa0ea4b24b308475af9
refs/heads/master
2020-12-24T17:08:51.551987
2011-09-02T07:55:05
2011-09-02T07:55:05
32,133,292
2
0
null
null
null
null
UTF-8
C++
false
false
3,321
h
/**************************************************************************** ** ** Copyright (C) 2005-2008 Trolltech ASA. All rights reserved. ** ** This file is part of the example classes of the Qt Toolkit. ** ** This file may be used under the terms of the GNU General Public ** License versions 2.0 or 3.0 as published by the Free Software ** Foundation and appearing in the files LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Alternatively you may (at ** your option) use any later version of the GNU General Public ** License if such license has been publicly approved by Trolltech ASA ** (or its successors, if any) and the KDE Free Qt Foundation. In ** addition, as a special exception, Trolltech gives you certain ** additional rights. These rights are described in the Trolltech GPL ** Exception version 1.2, which can be found at ** http://www.trolltech.com/products/qt/gplexception/ and in the file ** GPL_EXCEPTION.txt in this package. ** ** Please review the following information to ensure GNU General ** Public Licensing requirements will be met: ** http://trolltech.com/products/qt/licenses/licensing/opensource/. If ** you are unsure which license is appropriate for your use, please ** review the following information: ** http://trolltech.com/products/qt/licenses/licensing/licensingoverview ** or contact the sales department at [email protected]. ** ** In addition, as a special exception, Trolltech, as the sole ** copyright holder for Qt Designer, grants users of the Qt/Eclipse ** Integration plug-in the right for the Qt/Eclipse Integration to ** link to functionality provided by Qt Designer and its related ** libraries. ** ** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, ** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE. Trolltech reserves all rights not expressly ** granted herein. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ****************************************************************************/ #ifndef MOVIEPLAYER_H #define MOVIEPLAYER_H #include <QWidget> QT_BEGIN_NAMESPACE class QCheckBox; class QGridLayout; class QHBoxLayout; class QLabel; class QMovie; class QSlider; class QSpinBox; class QToolButton; class QVBoxLayout; QT_END_NAMESPACE class MoviePlayer : public QWidget { Q_OBJECT public: MoviePlayer(QWidget *parent = 0); void openFile(const QString &fileName); public slots: void open(); private slots: void goToFrame(int frame); void fitToWindow(); void updateButtons(); void updateFrameSlider(); private: void createControls(); void createButtons(); QString currentMovieDirectory; QLabel *movieLabel; QMovie *movie; QToolButton *openButton; QToolButton *playButton; QToolButton *pauseButton; QToolButton *stopButton; QToolButton *quitButton; QCheckBox *fitCheckBox; QSlider *frameSlider; QSpinBox *speedSpinBox; QLabel *frameLabel; QLabel *speedLabel; QGridLayout *controlsLayout; QHBoxLayout *buttonsLayout; QVBoxLayout *mainLayout; }; #endif
[ "ppkciz@9af58faf-7e3e-0410-b956-55d145112073" ]
[ [ [ 1, 101 ] ] ]
db78e0e71e06a88200be45e2241b9c1f85a25fee
2dbbca065b62a24f47aeb7ec5cd7a4fd82083dd4
/OUAN/OUAN/Src/Loader/XMLGameObject.h
da236fdcb0846c80885cdff3d9d3a8a9288e3a2d
[]
no_license
juanjmostazo/once-upon-a-night
9651dc4dcebef80f0475e2e61865193ad61edaaa
f8d5d3a62952c45093a94c8b073cbb70f8146a53
refs/heads/master
2020-05-28T05:45:17.386664
2010-10-06T12:49:50
2010-10-06T12:49:50
38,101,059
1
1
null
null
null
null
UTF-8
C++
false
false
687
h
#ifndef XMLGAMEOBJECTH_H #define XMLGAMEOBJECTH_H #include "../OUAN.h" namespace OUAN { class XMLGameObject { public: XMLGameObject(); virtual ~XMLGameObject(); std::string name; std::string dreamsName; std::string nightmaresName; std::string gameObjectType; TiXmlElement *XMLNodeDreams; TiXmlElement *XMLNodeNightmares; TiXmlElement *XMLNodeCustomProperties; //Returns gameObject->XMLDreamsNode if object exist both in dreams and nightmares, //gameObject->XMLNightmaresNode if only exists on nightmares and gameObject->XMLDreamsNode if only exists in dreams TiXmlElement * getMainXMLNode(); }; } #endif // XMLGAMEOBJECTH_H
[ "wyern1@1610d384-d83c-11de-a027-019ae363d039" ]
[ [ [ 1, 28 ] ] ]
e61ff50cc262062482dec670c2b62676fcbe915b
49db059c239549a8691fda362adf0654c5749fb1
/2010/sitnikov/task7/src/dialog.cpp
1ac8aebb2f9be657c7e5ad31d64ed936b05b96b3
[]
no_license
bondarevts/amse-qt
1a063f27c45a80897bb4751ae5c10f5d9d80de1b
2b9b76c7a5576bc1079fc037adcf039fed4dc848
refs/heads/master
2020-05-07T21:19:48.773724
2010-12-07T07:53:51
2010-12-07T07:53:51
35,804,478
0
0
null
null
null
null
UTF-8
C++
false
false
2,161
cpp
#include <QLabel> #include <QVBoxLayout> #include <QHBoxLayout> #include <QMessageBox> #include <QTimerEvent> #include "dialog.h" #include <iostream> Dialog::Dialog(QWidget *parent) : QDialog(parent), timer1_(0), timer2_(0), count1_(0), count2_(0), exst1_(false), exst2_(false) { btnSet_ = new QPushButton("set", this); btnStop_ = new QPushButton("stop", this); trmTicker1_ = new QLCDNumber(this); trmTicker2_ = new QLCDNumber(this); cbTimer_ = new QComboBox(this); txtValue_ = new QLineEdit(this); setLayout(new QVBoxLayout()); QVBoxLayout *lay0 = new QVBoxLayout(); QHBoxLayout *lay = new QHBoxLayout(); lay->addWidget(new QLabel("Timer 1: ", this)); lay->addWidget(trmTicker1_); lay0->addItem(lay); lay = new QHBoxLayout(); lay->addWidget(new QLabel("Timer 2: ", this)); lay->addWidget(trmTicker2_); lay0->addItem(lay); layout()->addItem(lay0); cbTimer_->addItem("Timer 1"); cbTimer_->addItem("Timer 2"); layout()->addWidget(cbTimer_); QHBoxLayout *lay1 = new QHBoxLayout(); lay1->addWidget(txtValue_); lay1->addWidget(btnSet_); layout()->addItem(lay1); layout()->addWidget(btnStop_); connect(btnSet_, SIGNAL(clicked()), this, SLOT(set_click())); connect(btnStop_, SIGNAL(clicked()), this, SLOT(stop_click())); setWindowTitle("why?"); } void Dialog::timerEvent(QTimerEvent *e) { if(e->timerId() == timer1_) { trmTicker1_->display(++count1_); } else if(e->timerId() == timer2_) { trmTicker2_->display(++count2_); } } void Dialog::set_click() { //std::cout << "set" << std::endl; bool ok = true; int value = txtValue_->text().toInt(&ok); if(!ok) { QMessageBox::critical(this, "why?", "Invalid input"); return; } if(cbTimer_->currentIndex() == 0) { if(exst1_) killTimer(timer1_); timer1_ = startTimer(value); exst1_ = true; } else { if(exst2_) killTimer(timer2_); timer2_ = startTimer(value); exst2_ = true; } } void Dialog::stop_click() { if(cbTimer_->currentIndex() == 0 && exst1_) { killTimer(timer1_); exst1_ = false; } else if(exst2_) { killTimer(timer2_); exst2_ = false; } }
[ "shuffle.c@1a14799f-55e9-4979-7f51-533a2053511e" ]
[ [ [ 1, 92 ] ] ]
2f42fe7c7dc3539b7903e547bf4cce820c671b74
2ff4099407bd04ffc49489f22bd62996ad0d0edd
/Project/Code/src/Main.cpp
b62814f807fa56fbae8386999c0f05ffa5bbc285
[]
no_license
willemfrishert/imagebasedrendering
13687840a8e5b37a38cc91c3c5b8135f9c1881f2
1cb9ed13b820b791a0aa2c80564dc33fefdc47a2
refs/heads/master
2016-09-10T15:23:42.506289
2007-06-04T11:52:13
2007-06-04T11:52:13
32,184,690
0
1
null
null
null
null
UTF-8
C++
false
false
2,962
cpp
#include "CubeMap.h" #include "Vector3.h" #include "Matrix4.h" #include "Quaternion.h" #include "VirtualTrackball.h" #include "Renderer.h" #include "UIHandler.h" #include "GPUParallelReductor.h" #include <math.h> //CONSTANTS const int KWindowPositionX = 50; const int KWindowPositionY = 50; const int KWindowWidth = 512; const int KWindowHeight = 512; void initContext(int argc, char **argv) { glutInit( &argc, argv ); //Init Window glutInitDisplayMode( GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA); glutInitWindowPosition( KWindowPositionX, KWindowPositionY ); glutInitWindowSize( KWindowWidth, KWindowHeight ); //800,600); glutCreateWindow(Renderer::WINDOW_TITLE.c_str()); //Set some Glut functions glutKeyboardFunc( ProcessNormalKeysWithUi ); glutSpecialFunc( ProcessCursorKeysWithUi ); glutMouseFunc( ProcessMouseEventWithUi ); glutMotionFunc( ProcessMouseMotionEventWithUi ); ////////////////////////////////////////////////////////////////////////// // GLEW INIT ////////////////////////////////////////////////////////////////////////// printf("Initializing Glew...\n"); #ifdef _WIN32 GLenum err = glewInit(); if (GLEW_OK != err) { /* Problem: glewInit failed, something is seriously wrong. */ fprintf(stderr, "Error: %s\n", glewGetErrorString(err)); } fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION)); #endif if(GLEW_VERSION_2_0) { fprintf(stderr, "OpenGL 2.0 support OK.\n"); } else { fprintf(stderr, "OpenGL 2.0 not supported!!!.\n"); } glutDisplayFunc( RenderSceneWithRenderer ); //glutIdleFunc( RenderSceneWithRenderer ); glutReshapeFunc( ResizeSceneWithRenderer ); glutTimerFunc(10, RenderSceneWithRendererTimerFunc, 10); } void testGPU() { const int side = 512; //float f[side*side]; float* f = new float[side*side]; for (int i = 0; i < side*side; i++) { f[i] = 1; //f[i] = (i % 2) + 1; //f[i] = i % 2 ? 0.25f : 0.5f; } //f[side] = 1056; //f[side] = 0.75f; //f[side*2] = 0.6f; //f[side*2+side/2] = 0.3333f; //f[side*side - side/2] = 0.8f; GPUParallelReductor proc(f, side, side, "./shader/logSumFP.frag"); GLfloat result[4]; proc.processData(result); delete f; } /** * Main method. * This method is called first an it will do the following: * -# Creates the renderer and ui objects * -# Initializes Glut * -# Calls renderer->CreateMesh to create a CMesh * -# Starts the glutMainLoop() * @param argc amount of arguments for glutInit(). * @param argv arguments for glutInit(). * @return 0 */ int main(int argc, char **argv) { //Initialize GL using GLUT functions initContext(argc, argv); //testGPU(); //Init renderer Renderer* renderer = new Renderer(); UIHandler* ui = new UIHandler( NULL ); ui->AddMouseListener( renderer ); ui->AddKeyListener( renderer ); renderer->setUIHandler( ui ); renderer->CreateScene(); //glutFullScreen(); //START GL loop glutMainLoop(); delete ui; delete renderer; return 0; }
[ "jpjorge@15324175-3028-0410-9899-2d1205849c9d", "wfrishert@15324175-3028-0410-9899-2d1205849c9d" ]
[ [ [ 1, 73 ], [ 79, 117 ], [ 119, 129 ] ], [ [ 74, 78 ], [ 118, 118 ] ] ]
695c29278d9e4d0f28963bcb2d3eb4466e4697ff
10dae5a20816dba197ecf76d6200fd1a9763ef97
/src/service.h
11b1936f34b03aeeafeebd5db73e767bedeb1b3e
[]
no_license
peterdfields/quantiNEMO_Taylor2010
fd43aba9b1fcf504132494ff63d08a9b45b3f683
611b46bf89836c4327fe64abd7b4008815152c9f
refs/heads/master
2020-02-26T17:33:24.396350
2011-02-08T23:08:34
2011-02-08T23:08:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,783
h
/** @file service.h * * Copyright (C) 2006 Frederic Guillaume <[email protected]> * Copyright (C) 2008 Samuel Neuenschwander <[email protected]> * * quantiNEMO: * quantiNEMO is an individual-based, genetically explicit stochastic * simulation program. It was developed to investigate the effects of * selection, mutation, recombination, and drift on quantitative traits * with varying architectures in structured populations connected by * migration and located in a heterogeneous habitat. * * quantiNEMO is built on the evolutionary and population genetics * programming framework NEMO (Guillaume and Rougemont, 2006, Bioinformatics). * * * Licensing: * This file is part of quantiNEMO. * * quantiNEMO 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. * * quantiNEMO 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 quantiNEMO. If not, see <http://www.gnu.org/licenses/>. */ #ifndef serviceH #define serviceH #include <list> #include "handler.h" #include "output.h" using namespace std; class SimComponent; /**Interface for the simulation services (files and stats). * Implements the observer pattern. Notify the observers (Handler) to update their state. * Contains the observer list. Provides interface to attach the observers to the service. **/ class Service { private: /**The list of observers. */ list<Handler*> _observers; public: Service( ) { } virtual ~Service( ) { } /**Inits internals. */ virtual bool init ( ) = 0; /**Notifies all observers to update their state. */ virtual void notify ( ) { #ifdef _DEBUG message(" %i ... ",_observers.size()); #endif list< Handler* >::iterator HIT = _observers.begin(); while(HIT != _observers.end()) { (*HIT)->update(); HIT++; } } virtual list<Handler*>* get_observers( ){return &_observers;} /**Interface to used by a simulation component to load its obervers onto a service provider.*/ virtual void load ( SimComponent* sc ) = 0; /**Adds an observer to the list. */ virtual void attach ( Handler* h ) { _observers.push_back(h); } /**Clears the observers list. */ virtual void reset ( ) { _observers.clear(); } }; #endif //SERVICE_H
[ [ [ 1, 99 ] ] ]
8a2352104d7033af7ef1c71d781de238dc51ac19
8bbbcc2bd210d5608613c5c591a4c0025ac1f06b
/nes/mapper/119.cpp
a381b612137967304c5cd950cc2051249b8acd1d
[]
no_license
PSP-Archive/NesterJ-takka
140786083b1676aaf91d608882e5f3aaa4d2c53d
41c90388a777c63c731beb185e924820ffd05f93
refs/heads/master
2023-04-16T11:36:56.127438
2008-12-07T01:39:17
2008-12-07T01:39:17
357,617,280
1
0
null
null
null
null
UTF-8
C++
false
false
6,548
cpp
///////////////////////////////////////////////////////////////////// // Mapper 119 void NES_mapper119_Init() { g_NESmapper.Reset = NES_mapper119_Reset; g_NESmapper.MemoryWrite = NES_mapper119_MemoryWrite; g_NESmapper.HSync = NES_mapper119_HSync; } void NES_mapper119_Reset() { // clear registers FIRST!!! int i; for(i = 0; i < 8; i++) g_NESmapper.Mapper119.regs[i] = 0x00; // set CPU bank pointers g_NESmapper.Mapper119.prg0 = 0; g_NESmapper.Mapper119.prg1 = 1; NES_mapper119_MMC3_set_CPU_banks(); // set VROM banks g_NESmapper.Mapper119.chr01 = 0; g_NESmapper.Mapper119.chr23 = 2; g_NESmapper.Mapper119.chr4 = 4; g_NESmapper.Mapper119.chr5 = 5; g_NESmapper.Mapper119.chr6 = 6; g_NESmapper.Mapper119.chr7 = 7; NES_mapper119_MMC3_set_PPU_banks(); g_NESmapper.Mapper119.irq_enabled = 0; g_NESmapper.Mapper119.irq_counter = 0; g_NESmapper.Mapper119.irq_latch = 0; g_PPU.vram_write_protect = 0; } void NES_mapper119_MemoryWrite(uint32 addr, uint8 data) { switch(addr & 0xE001) { case 0x8000: { g_NESmapper.Mapper119.regs[0] = data; NES_mapper119_MMC3_set_PPU_banks(); NES_mapper119_MMC3_set_CPU_banks(); } break; case 0x8001: { uint32 bank_num; g_NESmapper.Mapper119.regs[1] = data; bank_num = g_NESmapper.Mapper119.regs[1]; switch(g_NESmapper.Mapper119.regs[0] & 0x07) { case 0x00: { if(g_NESmapper.num_1k_VROM_banks) { bank_num &= 0xfe; g_NESmapper.Mapper119.chr01 = bank_num; NES_mapper119_MMC3_set_PPU_banks(); } } break; case 0x01: { if(g_NESmapper.num_1k_VROM_banks) { bank_num &= 0xfe; g_NESmapper.Mapper119.chr23 = bank_num; NES_mapper119_MMC3_set_PPU_banks(); } } break; case 0x02: { if(g_NESmapper.num_1k_VROM_banks) { g_NESmapper.Mapper119.chr4 = bank_num; NES_mapper119_MMC3_set_PPU_banks(); } } break; case 0x03: { if(g_NESmapper.num_1k_VROM_banks) { g_NESmapper.Mapper119.chr5 = bank_num; NES_mapper119_MMC3_set_PPU_banks(); } } break; case 0x04: { if(g_NESmapper.num_1k_VROM_banks) { g_NESmapper.Mapper119.chr6 = bank_num; NES_mapper119_MMC3_set_PPU_banks(); } } break; case 0x05: { if(g_NESmapper.num_1k_VROM_banks) { g_NESmapper.Mapper119.chr7 = bank_num; NES_mapper119_MMC3_set_PPU_banks(); } } break; case 0x06: { g_NESmapper.Mapper119.prg0 = bank_num; NES_mapper119_MMC3_set_CPU_banks(); } break; case 0x07: { g_NESmapper.Mapper119.prg1 = bank_num; NES_mapper119_MMC3_set_CPU_banks(); } break; } } break; case 0xA000: { g_NESmapper.Mapper119.regs[2] = data; if(NES_ROM_get_mirroring() != NES_PPU_MIRROR_FOUR_SCREEN) { if(data & 0x01) { g_NESmapper.set_mirroring2(NES_PPU_MIRROR_HORIZ); } else { g_NESmapper.set_mirroring2(NES_PPU_MIRROR_VERT); } } } break; case 0xA001: { g_NESmapper.Mapper119.regs[3] = data; } break; case 0xC000: g_NESmapper.Mapper119.regs[4] = data; g_NESmapper.Mapper119.irq_counter = g_NESmapper.Mapper119.regs[4]; break; case 0xC001: g_NESmapper.Mapper119.regs[5] = data; g_NESmapper.Mapper119.irq_latch = g_NESmapper.Mapper119.regs[5]; break; case 0xE000: g_NESmapper.Mapper119.regs[6] = data; g_NESmapper.Mapper119.irq_enabled = 0; break; case 0xE001: g_NESmapper.Mapper119.regs[7] = data; g_NESmapper.Mapper119.irq_enabled = 1; break; } } void NES_mapper119_HSync(uint32 scanline) { if(g_NESmapper.Mapper119.irq_enabled) { if((scanline >= 0) && (scanline <= 239)) { if(NES_PPU_spr_enabled() || NES_PPU_bg_enabled()) { if(!(g_NESmapper.Mapper119.irq_counter--)) { g_NESmapper.Mapper119.irq_counter = g_NESmapper.Mapper119.irq_latch; NES6502_DoIRQ(); } } } } } void NES_mapper119_MMC3_set_CPU_banks() { if(g_NESmapper.Mapper119.regs[0] & 0x40) { g_NESmapper.set_CPU_banks4(g_NESmapper.num_8k_ROM_banks-2,g_NESmapper.Mapper119.prg1,g_NESmapper.Mapper119.prg0,g_NESmapper.num_8k_ROM_banks-1); } else { g_NESmapper.set_CPU_banks4(g_NESmapper.Mapper119.prg0,g_NESmapper.Mapper119.prg1,g_NESmapper.num_8k_ROM_banks-2,g_NESmapper.num_8k_ROM_banks-1); } } void NES_mapper119_MMC3_set_PPU_banks() { uint8 chr_bank[8]; if(g_NESmapper.Mapper119.regs[0] & 0x80) { chr_bank[0] = g_NESmapper.Mapper119.chr4; chr_bank[1] = g_NESmapper.Mapper119.chr5; chr_bank[2] = g_NESmapper.Mapper119.chr6; chr_bank[3] = g_NESmapper.Mapper119.chr7; chr_bank[4] = g_NESmapper.Mapper119.chr01+0; chr_bank[5] = g_NESmapper.Mapper119.chr01+1; chr_bank[6] = g_NESmapper.Mapper119.chr23+0; chr_bank[7] = g_NESmapper.Mapper119.chr23+1; } else { chr_bank[0] = g_NESmapper.Mapper119.chr01+0; chr_bank[1] = g_NESmapper.Mapper119.chr01+1; chr_bank[2] = g_NESmapper.Mapper119.chr23+0; chr_bank[3] = g_NESmapper.Mapper119.chr23+1; chr_bank[4] = g_NESmapper.Mapper119.chr4; chr_bank[5] = g_NESmapper.Mapper119.chr5; chr_bank[6] = g_NESmapper.Mapper119.chr6; chr_bank[7] = g_NESmapper.Mapper119.chr7; } if(chr_bank[0] & 0x40) g_NESmapper.set_VRAM_bank(0, chr_bank[0] & 0x07); else g_NESmapper.set_PPU_bank0(chr_bank[0]); if(chr_bank[1] & 0x40) g_NESmapper.set_VRAM_bank(1, chr_bank[1] & 0x07); else g_NESmapper.set_PPU_bank1(chr_bank[1]); if(chr_bank[2] & 0x40) g_NESmapper.set_VRAM_bank(2, chr_bank[2] & 0x07); else g_NESmapper.set_PPU_bank2(chr_bank[2]); if(chr_bank[3] & 0x40) g_NESmapper.set_VRAM_bank(3, chr_bank[3] & 0x07); else g_NESmapper.set_PPU_bank3(chr_bank[3]); if(chr_bank[4] & 0x40) g_NESmapper.set_VRAM_bank(4, chr_bank[4] & 0x07); else g_NESmapper.set_PPU_bank4(chr_bank[4]); if(chr_bank[5] & 0x40) g_NESmapper.set_VRAM_bank(5, chr_bank[5] & 0x07); else g_NESmapper.set_PPU_bank5(chr_bank[5]); if(chr_bank[6] & 0x40) g_NESmapper.set_VRAM_bank(6, chr_bank[6] & 0x07); else g_NESmapper.set_PPU_bank6(chr_bank[6]); if(chr_bank[7] & 0x40) g_NESmapper.set_VRAM_bank(7, chr_bank[7] & 0x07); else g_NESmapper.set_PPU_bank7(chr_bank[7]); } /////////////////////////////////////////////////////////////////////
[ "takka@e750ed6d-7236-0410-a570-cc313d6b6496" ]
[ [ [ 1, 282 ] ] ]
8fd21ae87fac39f1418ef91b949fd1fc23cb27a1
6bdb3508ed5a220c0d11193df174d8c215eb1fce
/Codes/Halak/UIFlowPanel.h
8dc4b867829f25aa16822b81e6e3b388d00facd1
[]
no_license
halak/halak-plusplus
d09ba78640c36c42c30343fb10572c37197cfa46
fea02a5ae52c09ff9da1a491059082a34191cd64
refs/heads/master
2020-07-14T09:57:49.519431
2011-07-09T14:48:07
2011-07-09T14:48:07
66,716,624
0
0
null
null
null
null
UTF-8
C++
false
false
1,618
h
#pragma once #ifndef __HALAK_UIFLOWPANEL_H__ #define __HALAK_UIFLOWPANEL_H__ # include <Halak/FWD.h> # include <Halak/UIWindow.h> # include <Halak/UIFrame.h> # include <Halak/UIPickingContext.h> # include <Halak/UIDrawingContext.h> namespace Halak { class UIFlowPanel : public UIWindow { public: enum Direction { LeftToRight = 0x01, RightToLeft = 0x02, TopDown = 0x04, BottomUp = 0x08, }; public: UIFlowPanel(); virtual ~UIFlowPanel(); inline Direction GetDirection() const; void SetDirection(Direction value); protected: class ArrangedFrame : public UIFrame { public: Vector2 Offset; Vector2 Size; bool IsNewLine; public: ArrangedFrame(); ArrangedFrame(Vector2 offset, Vector2 size, bool isNewLine); virtual ~ArrangedFrame(); virtual bool Setup(const RectangleF& bounds, const RectangleF& referenceBounds); virtual RectangleF ComputeBounds(UIVisualVisitor& visitor, Vector2 desiredSize); }; private: Direction direction; }; } # include <Halak/UIFlowPanel.inl> #endif
[ [ [ 1, 55 ] ] ]
3ea406d17a8440e63c4149e52c67f30fb8de1c53
279b68f31b11224c18bfe7a0c8b8086f84c6afba
/playground/shelta/obsolete/0.0.1-DEV-01/dbconnection.cpp
7c30d4e71c5379133c30fcd81843a7f67b5a4de3
[]
no_license
bogus/findik
83b7b44b36b42db68c2b536361541ee6175bb791
2258b3b3cc58711375fe05221588d5a068da5ea8
refs/heads/master
2020-12-24T13:36:19.550337
2009-08-16T21:46:57
2009-08-16T21:46:57
32,120,100
0
0
null
null
null
null
UTF-8
C++
false
false
844
cpp
#include "dbconnection.hpp" #ifndef FINDIK_DBCONNECTION_CPP #define FINDIK_DBCONNECTION_CPP namespace findik { template <class T> dbconnection<T>::dbconnection(T * connection) : lock_(false), connection_(connection) { } template <class T> dbconnection<T>::~dbconnection(void) { delete connection_; } template <class T> void dbconnection<T>::lock() { lock_ = true; } template <class T> void dbconnection<T>::unlock() { lock_ = false; } template <class T> bool dbconnection<T>::is_locked() { return _lock; } template <class T> T * dbconnection<T>::connection() { return connection_; } template <class T> bool dbconnection<T>::try_lock() { if (lock_ == true) return false; else { lock_ = true; return true; } } } #endif
[ "shelta@d40773b4-ada0-11de-b0a2-13e92fe56a31" ]
[ [ [ 1, 59 ] ] ]
35ad630fb59473c0ed16e3bf478159ff06940fae
986d745d6a1653d73a497c1adbdc26d9bef48dba
/oldnewthing/262_cache2.cpp
ac1c3a747121284f4c95cd78e54d077c0f12f758
[]
no_license
AnarNFT/books-code
879f75327c1dad47a13f9c5d71a96d69d3cc7d3c
66750c2446477ac55da49ade229c21dd46dffa99
refs/heads/master
2021-01-20T23:40:30.826848
2011-01-17T11:14:34
2011-01-17T11:14:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,321
cpp
#include <windows.h> #include <vector> #include <iostream> class BufferCache { public: BufferCache() : m_pCache(NULL) { } ~BufferCache() { LocalFree(m_pCache); } void *GetBuffer(SIZE_T cb); void ReturnBuffer(void *p); private: void *m_pCache; }; void *BufferCache::GetBuffer(SIZE_T cb) { // Satisfy from cache if possible if (m_pCache && LocalSize(m_pCache) >= cb) { void *p = m_pCache; m_pCache = NULL; return p; } return LocalAlloc(LMEM_FIXED, cb); } // Flawed design - see discussion void BufferCache::ReturnBuffer(void *p) { SIZE_T cb = LocalSize(p); if (cb > LocalSize(m_pCache)) { // Returned buffer is bigger than the cache: // Keep the returned buffer LocalFree(m_pCache); m_pCache = p; } else { // Returned buffer is smaller than the cache: // Keep the cache LocalFree(p); } } // Since this is just a quick test, we're going to be sloppy using namespace std; // sloppy int __cdecl main(int argc, char **argv) { BufferCache b; // seeding the random number generator is not important here // in fact, the distribution isn't important either vector<void *> v; // keeps track of allocated memory SIZE_T cbAlloc = 0, cbNeeded = 0; // memory statistics for (int count = 0; ; count++) { // randomly allocate and free if (v.size() == 0 || (rand() & 1)) { // allocate SIZE_T cb = 100; while (cb < 1024 * 1024 && !(rand() % 4)) { cb *= 2; // exponential decay distribution up to 1MB } void* p = b.GetBuffer(cb); if (p) { *(SIZE_T*)p = cb; // remember requested size of this block cbAlloc += LocalSize(p); // update total memory allocated cbNeeded += cb; // update total memory requested v.push_back(p); // append to vector } } else { // free int victim = rand() % v.size(); // choose one at random cbAlloc -= LocalSize(v[victim]); // update total memory allocated cbNeeded -= *(SIZE_T*)v[victim]; // update total memory requested b.ReturnBuffer(v[victim]); // free it v[victim] = v.back(); v.pop_back(); } if (count % 100 == 0) { cout << count << ": " << v.size() << " buffers, " << cbNeeded << "/" << cbAlloc << "=" << cbNeeded * 100.0 / cbAlloc << "% used" << endl; } } }
[ [ [ 1, 85 ] ] ]
da1d25d323b4668e0d6bd9f31fa244c40abf1f34
5d36f6102c8cadcf1a124b366ae189d6a2609c59
/src/r3000a_new.cpp
9a84c24c542ecc5735c94728547c71eb1200cb72
[]
no_license
Devil084/psx4all
336f2861246367c8d397ef5acfc0b7972085c21b
04c02bf8840007792d23d15ca42a572035a1d703
refs/heads/master
2020-02-26T15:18:04.554046
2010-08-11T13:49:24
2010-08-11T13:49:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,734
cpp
/* Pcsx - Pc Psx Emulator * Copyright (C) 1999-2003 Pcsx Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "common.h" void psxBiosException(); void psxBiosInit(); void psxBiosShutdown(); R3000Acpu *psxCpu; #ifndef GP2X_MAPREGS u32 reg_code; u32 reg_pc; #endif int psxInit() { psxCpu = &psxInt; #ifdef DYNAREC if (!Config.Cpu) psxCpu = &psxRec; #endif Log=0; if (psxMemInit() == -1) return -1; return psxCpu->Init(); } void psxReset() { psxCpu->Reset(); psxMemReset(); memset(psxRegs, 0, sizeof(psxRegisters)); psxRegs->pc = 0xbfc00000; // Start in bootstrap psxRegs->CP0.r[12] = 0x10900000; // COP0 enabled | BEV = 1 | TS = 1 psxRegs->CP0.r[15] = 0x00000002; // PRevID = Revision ID, same as R3000A psxHwReset(); psxBiosInit(); if (!Config.HLE) psxExecuteBios(); #ifdef EMU_LOG // EMU_LOG("*BIOS END*\n"); #endif Log=0; } void psxShutdown() { psxMemShutdown(); psxBiosShutdown(); psxCpu->Shutdown(); } u32 psxException(u32 code, u32 bd) { // Set the Cause psxRegs->CP0.n.Cause = code; // Set the EPC & PC if (bd) { #ifdef PSXCPU_LOG PSXCPU_LOG("bd set!!!\n"); #endif SysPrintf("bd set!!!\n"); psxRegs->CP0.n.Cause|= 0x80000000; psxRegs->CP0.n.EPC = (psxRegs->pc - 4); } else { psxRegs->CP0.n.EPC = (psxRegs->pc); } if (psxRegs->CP0.n.Status & 0x400000) psxRegs->pc = 0xbfc00180; else psxRegs->pc = 0x80000080; // Set the Status psxRegs->CP0.n.Status = (psxRegs->CP0.n.Status &~0x3f) | ((psxRegs->CP0.n.Status & 0xf) << 2); if ( !Config.HLE && (((PSXMu32(psxRegs->CP0.n.EPC) >> 24) & 0xfe) == 0x4a)) { // "hokuto no ken" / "Crash Bandicot 2" ... fix PSXMu32ref(psxRegs->CP0.n.EPC)&= SWAPu32(~0x02000000); } if (Config.HLE) psxBiosException(); return psxRegs->pc; } //#define ENABLE_INTERRUPT_LOG_SUPPORT bool activeINTLog = false; #ifdef ENABLE_INTERRUPT_LOG_SUPPORT extern bool activeINTLog; #define DO_INT_LOG(expr) do { if(activeINTLog) SysPrintf expr; } while(false) #else // #define DO_INT_LOG(expr) do { /*if(activeINTLog)*/ SysPrintf expr; } while(false) #define DO_INT_LOG(expr) do {} while(false) #endif INLINE void psxTestHWInts() { if (psxHu32(0x1070) & psxHu32(0x1074)) { if ((psxRegs->CP0.n.Status & 0x401) == 0x401) { #ifdef PSXCPU_LOG // PSXCPU_LOG("Interrupt: %x %x\n", psxHu32(0x1070), psxHu32(0x1074)); #endif // SysPrintf("Interrupt (%x): %x %x\n", psxRegs.cycle, psxHu32(0x1070), psxHu32(0x1074)); psxException(0x400, 0); } } } void psxExecuteBios() { while (psxRegs->pc != 0x80030000) psxCpu->ExecuteBlock(); } #define spu_reg0 (psxHu16(0x1daa)) #define t0_count (psxHu16(0x1100)) #define t0_mode (psxHu32(0x1104)) #define t0_target (psxHu16(0x1108)) #define t1_count (psxHu16(0x1110)) #define t1_mode (psxHu32(0x1114)) #define t1_target (psxHu16(0x1118)) #define t2_count (psxHu16(0x1120)) #define t2_mode (psxHu32(0x1124)) #define t2_target (psxHu16(0x1128)) #define int_reg (psxHu16(0x1070)) #define int_mask (psxHu16(0x1074)) #define dma_pcr (psxHu32(0x10f0)) #define dma_icr (psxHu32(0x10f4)) #define UPPER 0xFFFF #define PER cycles void update_hw(u32 cycles) { int tmp; psxCounters.base_count+=PER; if (psxCounters.base_count>=RCNT_VSYNC) { psxCounters.base_count=0; GPU_vSinc(); #if !defined(IPHONE) && !defined( __SYMBIAN32__ ) SPU_async(Config.PsxType); #endif psxHu32ref(0x1070)|= SWAPu32(1); psxRegs->interrupt|= 0x80000000; } tmp = t0_count + ((t0_mode & 0x100)?PER:PER/8); if (tmp>=psxCounters.t0_limit && t0_count<psxCounters.t0_limit) { tmp = 0; // printf("t0 == limit\n"); if (t0_mode & 0x50) { psxHu32ref(0x1070)|= SWAPu32(0x10); psxRegs->interrupt|= 0x80000000; } } t0_count=tmp; if ((t1_mode & 0x100)==0) { tmp = t1_count + PER; if (tmp>=psxCounters.t1_limit && t1_count<psxCounters.t1_limit) { tmp = 0; // printf("t1 == limit\n"); if (t1_mode & 0x50) { psxHu32ref(0x1070)|= SWAPu32(0x20); psxRegs->interrupt|= 0x80000000; } } t1_count=tmp; } else { if ((psxCounters.dec1_count-=PER) <= 0) { if (++t1_count == psxCounters.t1_limit) { t1_count = 0; // printf("t1 == limit\n"); if (t1_mode & 0x50) { psxHu32ref(0x1070)|= SWAPu32(0x20); psxRegs->interrupt|= 0x80000000; } } psxCounters.dec1_count = RCNT_HSYNC; } } if ((t2_mode & 1) == 0) { tmp = t2_count + ((t2_mode & 0x200)?PER/8:PER); if (tmp>=psxCounters.t2_limit && t2_count<psxCounters.t2_limit) { tmp = 0; // printf("t2 == limit\n"); if (t2_mode & 0x50) { psxHu32ref(0x1070)|= SWAPu32(0x40); psxRegs->interrupt|= 0x80000000; } } t2_count=tmp; } //if(psxRegs->interrupt) { /* Make sure interrupts always when mcd is active */ if( mcdst != 0 ) { psxRegs->interrupt&=~0x80; sioInterrupt(); } // cdr if (psxRegs->interrupt & 0x04) { if ((psxRegs->cycle - psxRegs->intCycle[2]) >= psxRegs->intCycle[2+1]) { psxRegs->interrupt&=~0x04; cdrInterrupt(); DO_INT_LOG((" CDRInt\n")); } } // cdr read if (psxRegs->interrupt & 0x040000) { if ((psxRegs->cycle - psxRegs->intCycle[2+16]) >= psxRegs->intCycle[2+16+1]) { psxRegs->interrupt&=~0x040000; cdrReadInterrupt(); DO_INT_LOG((" CDRReadInt\n")); } } // sio if ((psxRegs->interrupt & 0x80) && (!Config.Sio)) { if ((psxRegs->cycle - psxRegs->intCycle[7]) >= psxRegs->intCycle[7+1]) { psxRegs->interrupt&=~0x80; sioInterrupt(); DO_INT_LOG((" SIOInt\n")); } } // gpu dma ??? if (psxRegs->interrupt & 0x01000000) { if ((psxRegs->cycle - psxRegs->intCycle[3+24]) >= psxRegs->intCycle[3+24+1]) { psxRegs->interrupt&=~0x01000000; gpuDMAInterrupt(); DO_INT_LOG((" GPUInt\n")); } } // mdec out dma if (psxRegs->interrupt & 0x02000000) { if ((psxRegs->cycle - psxRegs->intCycle[5+24]) >= psxRegs->intCycle[5+24+1]) { psxRegs->interrupt&=~0x02000000; mdec1DMAInterrupt(); DO_INT_LOG((" MDEC1Int\n")); } } // HWINTS if (psxRegs->interrupt & 0x80000000) { psxRegs->interrupt&=~0x80000000; psxTestHWInts(); DO_INT_LOG((" HWInt -> %d\n",psxRegs->cycle)); } } #ifdef IPHONE if( !__emulation_run ) { char buffer[260]; char filename[260]; time_t curtime; struct tm *loctime; curtime = time (NULL); loctime = localtime (&curtime); strftime (buffer, 260, "%y%m%d-%I%M%p", loctime); sprintf(filename, "%s-%s.svs", iphonefile, buffer); GPU_freeze(2, NULL); SaveState(filename); app_SetSvsFile(filename); psx4all_prof_show(); psxShutdown(); CloseComponents(); gp2x_deinit(); pthread_exit(NULL); } #endif }
[ "jars@jars-desktop.(none)", "[email protected]" ]
[ [ [ 1, 172 ], [ 174, 340 ] ], [ [ 173, 173 ] ] ]
56eb5b78966c7e5e44226395dd87973b4836fd13
d5706b5871d9650b30043ab45cfd7f02878d18e6
/src/b2cinder/BoundaryElement.cpp
9c29ff743380d884d0caf5cade5987da8d1321ed
[]
no_license
onedayitwillmake/CinderBox2dOSC
bb8db212ecb644cd51798cc672789e51ba13b071
e76d4b1d522f08df73f7bc0d9c76434326f05f4c
refs/heads/master
2020-06-04T06:33:04.897125
2011-06-10T14:32:05
2011-06-10T14:32:05
1,782,762
0
0
null
null
null
null
UTF-8
C++
false
false
1,797
cpp
/* * BoundaryElement.cpp * Joint2D * * Created by David Wicks on 6/10/10. * Copyright 2010 David Wicks. All rights reserved. * */ #include "BoundaryElement.h" namespace cinder { namespace box2d { BoundaryElement::BoundaryElement() { } BoundaryElement::BoundaryElement( Rectf screenBounds, float thickness ) { set( screenBounds, thickness ); } void BoundaryElement::set( Rectf screenBounds, float thickness ) { mScreenBounds = screenBounds; mBoundThickness = thickness; if( mScreenBounds.calcArea() != 0 ) { // half width and half height float w = Conversions::toPhysics( mScreenBounds.getWidth()/2.0f ); float h = Conversions::toPhysics( mScreenBounds.getHeight()/2.0f ); // center x, y Vec2f upperLeft = mScreenBounds.getUpperLeft(); float x = Conversions::toPhysics( upperLeft.x ) + w; float y = Conversions::toPhysics( upperLeft.y ) + h; w += mBoundThickness; h += mBoundThickness; mBodyDef.position.Set( x, y ); mBodyDef.type = b2_staticBody; // Left leftShape.SetAsBox( mBoundThickness, h, b2Vec2( -w, 0 ), 0 ); mFixtureDef.shape = &leftShape; mFixtureDefs.push_back(mFixtureDef); // Right rightShape.SetAsBox( mBoundThickness, h, b2Vec2( w, 0 ), 0 ); mFixtureDef.shape = &rightShape; mFixtureDefs.push_back(mFixtureDef); // Top topShape.SetAsBox( w, mBoundThickness, b2Vec2( 0, -h ), 0 ); mFixtureDef.shape = &topShape; mFixtureDefs.push_back(mFixtureDef); // Bottom floorShape.SetAsBox( w, mBoundThickness, b2Vec2( 0, h ), 0 ); mFixtureDef.shape = &floorShape; mFixtureDefs.push_back(mFixtureDef); } } void BoundaryElement::draw() { } } }
[ [ [ 1, 76 ] ] ]
69c2755e90283f8258b39a384f7f6e9edac6abf3
463c3b62132d215e245a097a921859ecb498f723
/lib/dlib/matrix/matrix_expressions.h
f5fcea65ce5d1020b5418d5bf49569b1e8e6104d
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
athulan/cppagent
58f078cee55b68c08297acdf04a5424c2308cfdc
9027ec4e32647e10c38276e12bcfed526a7e27dd
refs/heads/master
2021-01-18T23:34:34.691846
2009-05-05T00:19:54
2009-05-05T00:19:54
197,038
4
1
null
null
null
null
UTF-8
C++
false
false
55,451
h
// Copyright (C) 2006 Davis E. King ([email protected]) // License: Boost Software License See LICENSE.txt for the full license. #ifndef DLIB_MATRIx_EXPRESSIONS_H_ #define DLIB_MATRIx_EXPRESSIONS_H_ #include "matrix_fwd.h" #ifdef _MSC_VER // This #pragma directive is also located in the algs.h file but for whatever // reason visual studio 9 just ignores it when it is only there. // this is to disable the "'this' : used in base member initializer list" // warning you get from some of the GUI objects since all the objects // require that their parent class be passed into their constructor. // In this case though it is totally safe so it is ok to disable this warning. #pragma warning(disable : 4355) #endif namespace dlib { // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- // Helper templates for making operators used by expression objects // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- /* templates for finding the max of two matrix expressions' dimensions */ template <typename EXP1, typename EXP2 = void, typename EXP3 = void, typename EXP4 = void> struct max_nr; template <typename EXP1> struct max_nr<EXP1,void,void,void> { const static long val = EXP1::NR; }; template <typename EXP1, typename EXP2> struct max_nr<EXP1,EXP2,void,void> { const static long val = (EXP1::NR > EXP2::NR) ? (EXP1::NR) : (EXP2::NR); }; template <typename EXP1, typename EXP2, typename EXP3> struct max_nr<EXP1,EXP2,EXP3,void> { private: const static long max12 = (EXP1::NR > EXP2::NR) ? (EXP1::NR) : (EXP2::NR); public: const static long val = (max12 > EXP3::NR) ? (max12) : (EXP3::NR); }; template <typename EXP1, typename EXP2, typename EXP3, typename EXP4> struct max_nr { private: const static long max12 = (EXP1::NR > EXP2::NR) ? (EXP1::NR) : (EXP2::NR); const static long max34 = (EXP3::NR > EXP4::NR) ? (EXP3::NR) : (EXP4::NR); public: const static long val = (max12 > max34) ? (max12) : (max34); }; template <typename EXP1, typename EXP2 = void, typename EXP3 = void, typename EXP4 = void> struct max_nc; template <typename EXP1> struct max_nc<EXP1,void,void,void> { const static long val = EXP1::NC; }; template <typename EXP1, typename EXP2> struct max_nc<EXP1,EXP2,void,void> { const static long val = (EXP1::NC > EXP2::NC) ? (EXP1::NC) : (EXP2::NC); }; template <typename EXP1, typename EXP2, typename EXP3> struct max_nc<EXP1,EXP2,EXP3,void> { private: const static long max12 = (EXP1::NC > EXP2::NC) ? (EXP1::NC) : (EXP2::NC); public: const static long val = (max12 > EXP3::NC) ? (max12) : (EXP3::NC); }; template <typename EXP1, typename EXP2, typename EXP3, typename EXP4> struct max_nc { private: const static long max12 = (EXP1::NC > EXP2::NC) ? (EXP1::NC) : (EXP2::NC); const static long max34 = (EXP3::NC > EXP4::NC) ? (EXP3::NC) : (EXP4::NC); public: const static long val = (max12 > max34) ? (max12) : (max34); }; // ---------------------------------------------------------------------------------------- struct has_destructive_aliasing { template <typename M, typename U, long iNR, long iNC, typename MM, typename L > static bool destructively_aliases ( const M& m, const matrix<U,iNR,iNC,MM,L>& item ) { return m.aliases(item); } template <typename M1, typename M2, typename U, long iNR, long iNC, typename MM, typename L > static bool destructively_aliases ( const M1& m1, const M2& m2, const matrix<U,iNR,iNC,MM,L>& item ) { return m1.aliases(item) || m2.aliases(item) ; } template <typename M1, typename M2, typename M3, typename U, long iNR, long iNC, typename MM, typename L > static bool destructively_aliases ( const M1& m1, const M2& m2, const M3& m3, const matrix<U,iNR,iNC,MM,L>& item ) { return m1.aliases(item) || m2.aliases(item) || m3.aliases(item); } template <typename M1, typename M2, typename M3, typename M4, typename U, long iNR, long iNC, typename MM, typename L > static bool destructively_aliases ( const M1& m1, const M2& m2, const M3& m3, const M4& m4, const matrix<U,iNR,iNC,MM,L>& item ) { return m1.aliases(item) || m2.aliases(item) || m3.aliases(item) || m4.aliases(item); } }; // ---------------------------------------------------------------------------------------- struct has_nondestructive_aliasing { template <typename M, typename U, long iNR, long iNC, typename MM, typename L > static bool destructively_aliases ( const M& m, const matrix<U,iNR,iNC,MM,L>& item ) { return m.destructively_aliases(item); } template <typename M1, typename M2, typename U, long iNR, long iNC, typename MM, typename L > static bool destructively_aliases ( const M1& m1, const M2& m2, const matrix<U,iNR,iNC, MM, L>& item ) { return m1.destructively_aliases(item) || m2.destructively_aliases(item) ; } template <typename M1, typename M2, typename M3, typename U, long iNR, long iNC, typename MM, typename L > static bool destructively_aliases ( const M1& m1, const M2& m2, const M3& m3, const matrix<U,iNR,iNC, MM, L>& item ) { return m1.destructively_aliases(item) || m2.destructively_aliases(item) || m3.destructively_aliases(item) ; } template <typename M1, typename M2, typename M3, typename M4, typename U, long iNR, long iNC, typename MM, typename L > static bool destructively_aliases ( const M1& m1, const M2& m2, const M3& m3, const M4& m4, const matrix<U,iNR,iNC, MM, L>& item ) { return m1.destructively_aliases(item) || m2.destructively_aliases(item) || m3.destructively_aliases(item) || m4.destructively_aliases(item) ; } }; // ---------------------------------------------------------------------------------------- template <typename EXP1, typename EXP2 = void, typename EXP3 = void, typename EXP4 = void> struct preserves_dimensions { const static long NR = max_nr<EXP1,EXP2,EXP3,EXP4>::val; const static long NC = max_nc<EXP1,EXP2,EXP3,EXP4>::val; typedef typename EXP1::mem_manager_type mem_manager_type; template <typename M> static long nr (const M& m) { return m.nr(); } template <typename M> static long nc (const M& m) { return m.nc(); } template <typename M1, typename M2> static long nr (const M1& m1, const M2& ) { return m1.nr(); } template <typename M1, typename M2> static long nc (const M1& m1, const M2& ) { return m1.nc(); } template <typename M1, typename M2, typename M3> static long nr (const M1& m1, const M2&, const M3& ) { return m1.nr(); } template <typename M1, typename M2, typename M3> static long nc (const M1& m1, const M2&, const M3& ) { return m1.nc(); } template <typename M1, typename M2, typename M3, typename M4> static long nr (const M1& m1, const M2&, const M3&, const M4& ) { return m1.nr(); } template <typename M1, typename M2, typename M3, typename M4> static long nc (const M1& m1, const M2&, const M3&, const M4& ) { return m1.nc(); } }; // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- // General matrix expressions that take operator structs // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- template < typename M, typename OP_ > class matrix_unary_exp; template < typename M, typename OP_ > struct matrix_traits<matrix_unary_exp<M,OP_> > { typedef typename OP_::template op<M> OP; typedef typename OP::type type; typedef typename OP::mem_manager_type mem_manager_type; typedef typename M::layout_type layout_type; const static long NR = OP::NR; const static long NC = OP::NC; const static long cost = OP::cost; }; template < typename M, typename OP_ > class matrix_unary_exp : public matrix_exp<matrix_unary_exp<M,OP_> > { /*! REQUIREMENTS ON M - must be an object that inherits from matrix_exp !*/ typedef typename OP_::template op<M> OP; public: typedef typename matrix_traits<matrix_unary_exp>::type type; typedef typename matrix_traits<matrix_unary_exp>::mem_manager_type mem_manager_type; typedef typename matrix_traits<matrix_unary_exp>::layout_type layout_type; const static long NR = matrix_traits<matrix_unary_exp>::NR; const static long NC = matrix_traits<matrix_unary_exp>::NC; const static long cost = matrix_traits<matrix_unary_exp>::cost; matrix_unary_exp ( const matrix_unary_exp& item ) : matrix_exp<matrix_unary_exp>(*this), m(item.m) {} // This constructor exists simply for the purpose of causing a compile time error if // someone tries to create an instance of this object with the wrong kind of objects. template <typename T1> matrix_unary_exp (T1); matrix_unary_exp ( const M& m_ ) : matrix_exp<matrix_unary_exp>(*this), m(m_) {} const typename OP::type operator() ( long r, long c ) const { return OP::apply(m,r,c); } const typename OP::type operator() ( long i ) const { return matrix_exp<matrix_unary_exp>::operator()(i); } template <typename U, long iNR, long iNC, typename MM, typename L > bool aliases ( const matrix<U,iNR,iNC,MM,L>& item ) const { return m.aliases(item); } template <typename U, long iNR, long iNC, typename MM, typename L > bool destructively_aliases ( const matrix<U,iNR,iNC,MM,L>& item ) const { return OP::destructively_aliases(m,item); } long nr ( ) const { return OP::nr(m); } long nc ( ) const { return OP::nc(m); } const M& m; }; // ---------------------------------------------------------------------------------------- template < typename M, typename S, typename OP_ > class matrix_scalar_binary_exp; template < typename M, typename S, typename OP_ > struct matrix_traits<matrix_scalar_binary_exp<M,S,OP_> > { typedef typename OP_::template op<M> OP; typedef typename OP::type type; typedef typename OP::mem_manager_type mem_manager_type; const static long NR = OP::NR; const static long NC = OP::NC; const static long cost = OP::cost; typedef typename M::layout_type layout_type; }; template < typename M, typename S, typename OP_ > class matrix_scalar_binary_exp : public matrix_exp<matrix_scalar_binary_exp<M,S,OP_> > { /*! REQUIREMENTS ON M - must be an object that inherits from matrix_exp !*/ typedef typename OP_::template op<M> OP; public: typedef typename matrix_traits<matrix_scalar_binary_exp>::type type; typedef typename matrix_traits<matrix_scalar_binary_exp>::mem_manager_type mem_manager_type; const static long NR = matrix_traits<matrix_scalar_binary_exp>::NR; const static long NC = matrix_traits<matrix_scalar_binary_exp>::NC; const static long cost = matrix_traits<matrix_scalar_binary_exp>::cost; typedef typename matrix_traits<matrix_scalar_binary_exp>::layout_type layout_type; matrix_scalar_binary_exp ( const matrix_scalar_binary_exp& item ) : matrix_exp<matrix_scalar_binary_exp>(*this), m(item.m), s(item.s) {} // This constructor exists simply for the purpose of causing a compile time error if // someone tries to create an instance of this object with the wrong kind of objects. template <typename T1> matrix_scalar_binary_exp (T1,const S&); matrix_scalar_binary_exp ( const M& m_, const S& s_ ) : matrix_exp<matrix_scalar_binary_exp>(*this), m(m_), s(s_) { COMPILE_TIME_ASSERT(is_matrix<S>::value == false); } const typename OP::type operator() ( long r, long c ) const { return OP::apply(m,s,r,c); } const typename OP::type operator() ( long i ) const { return matrix_exp<matrix_scalar_binary_exp>::operator()(i); } template <typename U, long iNR, long iNC, typename MM, typename L > bool aliases ( const matrix<U,iNR,iNC,MM,L>& item ) const { return m.aliases(item); } template <typename U, long iNR, long iNC , typename MM, typename L> bool destructively_aliases ( const matrix<U,iNR,iNC,MM,L>& item ) const { return OP::destructively_aliases(m,item); } long nr ( ) const { return OP::nr(m); } long nc ( ) const { return OP::nc(m); } const M& m; const S s; }; // ---------------------------------------------------------------------------------------- template < typename M, typename S, typename OP_ > class matrix_scalar_ternary_exp; template < typename M, typename S, typename OP_ > struct matrix_traits<matrix_scalar_ternary_exp<M,S,OP_> > { typedef typename OP_::template op<M> OP; typedef typename OP::type type; typedef typename OP::mem_manager_type mem_manager_type; const static long NR = OP::NR; const static long NC = OP::NC; const static long cost = OP::cost; typedef typename M::layout_type layout_type; }; template < typename M, typename S, typename OP_ > class matrix_scalar_ternary_exp : public matrix_exp<matrix_scalar_ternary_exp<M,S,OP_> > { /*! REQUIREMENTS ON M - must be an object that inherits from matrix_exp !*/ typedef typename OP_::template op<M> OP; public: typedef typename matrix_traits<matrix_scalar_ternary_exp>::type type; typedef typename matrix_traits<matrix_scalar_ternary_exp>::mem_manager_type mem_manager_type; const static long NR = matrix_traits<matrix_scalar_ternary_exp>::NR; const static long NC = matrix_traits<matrix_scalar_ternary_exp>::NC; const static long cost = matrix_traits<matrix_scalar_ternary_exp>::cost; typedef typename matrix_traits<matrix_scalar_ternary_exp>::layout_type layout_type; matrix_scalar_ternary_exp ( const matrix_scalar_ternary_exp& item ) : matrix_exp<matrix_scalar_ternary_exp>(*this), m(item.m), s1(item.s1), s2(item.s2) { } // This constructor exists simply for the purpose of causing a compile time error if // someone tries to create an instance of this object with the wrong kind of objects. template <typename T1> matrix_scalar_ternary_exp (T1, const S&, const S&); matrix_scalar_ternary_exp ( const M& m_, const S& s1_, const S& s2_ ) : matrix_exp<matrix_scalar_ternary_exp>(*this), m(m_), s1(s1_), s2(s2_) { COMPILE_TIME_ASSERT(is_matrix<S>::value == false); } const typename OP::type operator() ( long r, long c ) const { return OP::apply(m,s1,s2,r,c); } const typename OP::type operator() ( long i ) const { return matrix_exp<matrix_scalar_ternary_exp>::operator()(i); } template <typename U, long iNR, long iNC, typename MM, typename L> bool aliases ( const matrix<U,iNR,iNC,MM,L>& item ) const { return m.aliases(item); } template <typename U, long iNR, long iNC , typename MM, typename L> bool destructively_aliases ( const matrix<U,iNR,iNC,MM,L>& item ) const { return OP::destructively_aliases(m,item); } long nr ( ) const { return OP::nr(m,s1,s2); } long nc ( ) const { return OP::nc(m,s1,s2); } const M& m; const S s1; const S s2; }; // ---------------------------------------------------------------------------------------- template < typename M1, typename M2, typename OP_ > class matrix_binary_exp; template < typename M1, typename M2, typename OP_ > struct matrix_traits<matrix_binary_exp<M1,M2,OP_> > { typedef typename OP_::template op<M1,M2> OP; typedef typename OP::type type; typedef typename OP::mem_manager_type mem_manager_type; const static long NR = OP::NR; const static long NC = OP::NC; const static long cost = OP::cost; typedef typename M1::layout_type layout_type; }; template < typename M1, typename M2, typename OP_ > class matrix_binary_exp : public matrix_exp<matrix_binary_exp<M1,M2,OP_> > { /*! REQUIREMENTS ON M1 AND M2 - must be objects that inherit from matrix_exp !*/ typedef typename OP_::template op<M1,M2> OP; public: typedef typename matrix_traits<matrix_binary_exp>::type type; typedef typename matrix_traits<matrix_binary_exp>::mem_manager_type mem_manager_type; const static long NR = matrix_traits<matrix_binary_exp>::NR; const static long NC = matrix_traits<matrix_binary_exp>::NC; const static long cost = matrix_traits<matrix_binary_exp>::cost; typedef typename matrix_traits<matrix_binary_exp>::layout_type layout_type; matrix_binary_exp ( const matrix_binary_exp& item ) : matrix_exp<matrix_binary_exp>(*this), m1(item.m1), m2(item.m2) {} // This constructor exists simply for the purpose of causing a compile time error if // someone tries to create an instance of this object with the wrong kind of objects. template <typename T1, typename T2> matrix_binary_exp (T1,T2); matrix_binary_exp ( const M1& m1_, const M2& m2_ ) : matrix_exp<matrix_binary_exp>(*this), m1(m1_), m2(m2_) {} const typename OP::type operator() ( long r, long c ) const { return OP::apply(m1,m2,r,c); } const typename OP::type operator() ( long i ) const { return matrix_exp<matrix_binary_exp>::operator()(i); } template <typename U, long iNR, long iNC, typename MM, typename L > bool aliases ( const matrix<U,iNR,iNC,MM,L>& item ) const { return m1.aliases(item) || m2.aliases(item); } template <typename U, long iNR, long iNC, typename MM, typename L > bool destructively_aliases ( const matrix<U,iNR,iNC,MM,L>& item ) const { return OP::destructively_aliases(m1,m2,item); } long nr ( ) const { return OP::nr(m1,m2); } long nc ( ) const { return OP::nc(m1,m2); } private: const M1& m1; const M2& m2; }; // ---------------------------------------------------------------------------------------- template < typename M1, typename M2, typename M3, typename OP_ > class matrix_ternary_exp; template < typename M1, typename M2, typename M3, typename OP_ > struct matrix_traits<matrix_ternary_exp<M1,M2,M3,OP_> > { typedef typename OP_::template op<M1,M2,M3> OP; typedef typename OP::type type; typedef typename OP::mem_manager_type mem_manager_type; const static long NR = OP::NR; const static long NC = OP::NC; const static long cost = OP::cost; typedef typename M1::layout_type layout_type; }; template < typename M1, typename M2, typename M3, typename OP_ > class matrix_ternary_exp : public matrix_exp<matrix_ternary_exp<M1,M2,M3,OP_> > { /*! REQUIREMENTS ON M1, M2 AND M3 - must be objects that inherit from matrix_exp !*/ typedef typename OP_::template op<M1,M2,M3> OP; public: typedef typename matrix_traits<matrix_ternary_exp>::type type; typedef typename matrix_traits<matrix_ternary_exp>::mem_manager_type mem_manager_type; const static long NR = matrix_traits<matrix_ternary_exp>::NR; const static long NC = matrix_traits<matrix_ternary_exp>::NC; const static long cost = matrix_traits<matrix_ternary_exp>::cost; typedef typename matrix_traits<matrix_ternary_exp>::layout_type layout_type; matrix_ternary_exp ( const matrix_ternary_exp& item ) : matrix_exp<matrix_ternary_exp>(*this), m1(item.m1), m2(item.m2), m3(item.m3) {} // This constructor exists simply for the purpose of causing a compile time error if // someone tries to create an instance of this object with the wrong kind of objects. template <typename T1, typename T2, typename T3> matrix_ternary_exp ( T1, T2, T3 ); matrix_ternary_exp ( const M1& m1_, const M2& m2_, const M3& m3_ ) : matrix_exp<matrix_ternary_exp>(*this), m1(m1_), m2(m2_), m3(m3_) {} const typename OP::type operator() ( long r, long c ) const { return OP::apply(m1,m2,m3,r,c); } const typename OP::type operator() ( long i ) const { return matrix_exp<matrix_ternary_exp>::operator()(i); } template <typename U, long iNR, long iNC, typename MM, typename L > bool aliases ( const matrix<U,iNR,iNC,MM,L>& item ) const { return m1.aliases(item) || m2.aliases(item) || m3.aliases(item); } template <typename U, long iNR, long iNC, typename MM, typename L > bool destructively_aliases ( const matrix<U,iNR,iNC,MM,L>& item ) const { return OP::destructively_aliases(m1,m2,m3,item); } long nr ( ) const { return OP::nr(m1,m2,m3); } long nc ( ) const { return OP::nc(m1,m2,m3); } private: const M1& m1; const M2& m2; const M3& m3; }; // ---------------------------------------------------------------------------------------- template < typename M1, typename M2, typename M3, typename M4, typename OP_ > class matrix_fourary_exp; template < typename M1, typename M2, typename M3, typename M4, typename OP_ > struct matrix_traits<matrix_fourary_exp<M1,M2,M3,M4,OP_> > { typedef typename OP_::template op<M1,M2,M3,M4> OP; typedef typename OP::type type; typedef typename OP::mem_manager_type mem_manager_type; const static long NR = OP::NR; const static long NC = OP::NC; const static long cost = OP::cost; typedef typename M1::layout_type layout_type; }; template < typename M1, typename M2, typename M3, typename M4, typename OP_ > class matrix_fourary_exp : public matrix_exp<matrix_fourary_exp<M1,M2,M3,M4,OP_> > { /*! REQUIREMENTS ON M1, M2, M3 AND M4 - must be objects that inherit from matrix_exp !*/ typedef typename OP_::template op<M1,M2,M3,M4> OP; public: typedef typename matrix_traits<matrix_fourary_exp>::type type; typedef typename matrix_traits<matrix_fourary_exp>::mem_manager_type mem_manager_type; const static long NR = matrix_traits<matrix_fourary_exp>::NR; const static long NC = matrix_traits<matrix_fourary_exp>::NC; const static long cost = matrix_traits<matrix_fourary_exp>::cost; typedef typename matrix_traits<matrix_fourary_exp>::layout_type layout_type; matrix_fourary_exp ( const matrix_fourary_exp& item ) : matrix_exp<matrix_fourary_exp>(*this), m1(item.m1), m2(item.m2), m3(item.m3), m4(item.m4) {} // This constructor exists simply for the purpose of causing a compile time error if // someone tries to create an instance of this object with the wrong kind of objects. template <typename T1, typename T2, typename T3, typename T4> matrix_fourary_exp (T1,T2,T3,T4); matrix_fourary_exp ( const M1& m1_, const M2& m2_, const M3& m3_, const M4& m4_ ) : matrix_exp<matrix_fourary_exp>(*this), m1(m1_), m2(m2_), m3(m3_), m4(m4_) {} const typename OP::type operator() ( long r, long c ) const { return OP::apply(m1,m2,m3,m4,r,c); } const typename OP::type operator() ( long i ) const { return matrix_exp<matrix_fourary_exp>::operator()(i); } template <typename U, long iNR, long iNC, typename MM, typename L > bool aliases ( const matrix<U,iNR,iNC,MM,L>& item ) const { return m1.aliases(item) || m2.aliases(item) || m3.aliases(item) || m4.aliases(item); } template <typename U, long iNR, long iNC, typename MM, typename L > bool destructively_aliases ( const matrix<U,iNR,iNC,MM,L>& item ) const { return OP::destructively_aliases(m1,m2,m3,m4,item); } long nr ( ) const { return OP::nr(m1,m2,m3,m4); } long nc ( ) const { return OP::nc(m1,m2,m3,m4); } private: const M1& m1; const M2& m2; const M3& m3; const M4& m4; }; // ---------------------------------------------------------------------------------------- template < typename S, typename OP > class dynamic_matrix_scalar_unary_exp; template < typename S, typename OP > struct matrix_traits<dynamic_matrix_scalar_unary_exp<S,OP> > { typedef typename OP::type type; typedef typename OP::mem_manager_type mem_manager_type; const static long NR = OP::NR; const static long NC = OP::NC; const static long cost = OP::cost; typedef row_major_layout layout_type; }; template < typename S, typename OP > class dynamic_matrix_scalar_unary_exp : public matrix_exp<dynamic_matrix_scalar_unary_exp<S,OP> > { /*! REQUIREMENTS ON S should be some scalar type !*/ public: typedef typename matrix_traits<dynamic_matrix_scalar_unary_exp>::type type; typedef typename matrix_traits<dynamic_matrix_scalar_unary_exp>::mem_manager_type mem_manager_type; const static long NR = matrix_traits<dynamic_matrix_scalar_unary_exp>::NR; const static long NC = matrix_traits<dynamic_matrix_scalar_unary_exp>::NC; const static long cost = matrix_traits<dynamic_matrix_scalar_unary_exp>::cost; typedef typename matrix_traits<dynamic_matrix_scalar_unary_exp>::layout_type layout_type; dynamic_matrix_scalar_unary_exp ( const dynamic_matrix_scalar_unary_exp& item ) : matrix_exp<dynamic_matrix_scalar_unary_exp>(*this), nr_(item.nr_), nc_(item.nc_), s(item.s) {} dynamic_matrix_scalar_unary_exp ( long nr__, long nc__, const S& s_ ) : matrix_exp<dynamic_matrix_scalar_unary_exp>(*this), nr_(nr__), nc_(nc__), s(s_) { COMPILE_TIME_ASSERT(is_matrix<S>::value == false); } const typename OP::type operator() ( long r, long c ) const { return OP::apply(s,r,c); } const typename OP::type operator() ( long i ) const { return matrix_exp<dynamic_matrix_scalar_unary_exp>::operator()(i); } template <typename U, long iNR, long iNC, typename MM, typename L > bool aliases ( const matrix<U,iNR,iNC,MM,L>& item ) const { return false; } template <typename U, long iNR, long iNC , typename MM, typename L> bool destructively_aliases ( const matrix<U,iNR,iNC,MM,L>& item ) const { return false; } long nr ( ) const { return nr_; } long nc ( ) const { return nc_; } private: const long nr_; const long nc_; const S s; }; // ---------------------------------------------------------------------------------------- template <typename S, typename OP> class matrix_scalar_unary_exp; template <typename S, typename OP> struct matrix_traits<matrix_scalar_unary_exp<S,OP> > { typedef typename OP::type type; typedef typename OP::mem_manager_type mem_manager_type; const static long NR = OP::NR; const static long NC = OP::NC; const static long cost = OP::cost; typedef row_major_layout layout_type; }; template < typename S, typename OP > class matrix_scalar_unary_exp : public matrix_exp<matrix_scalar_unary_exp<S,OP> > { /*! REQUIREMENTS ON S should be some scalar type !*/ public: typedef typename matrix_traits<matrix_scalar_unary_exp>::type type; typedef typename matrix_traits<matrix_scalar_unary_exp>::mem_manager_type mem_manager_type; const static long NR = matrix_traits<matrix_scalar_unary_exp>::NR; const static long NC = matrix_traits<matrix_scalar_unary_exp>::NC; const static long cost = matrix_traits<matrix_scalar_unary_exp>::cost; typedef typename matrix_traits<matrix_scalar_unary_exp>::layout_type layout_type; matrix_scalar_unary_exp ( const matrix_scalar_unary_exp& item ) : matrix_exp<matrix_scalar_unary_exp>(*this), s(item.s) {} matrix_scalar_unary_exp ( const S& s_ ) : matrix_exp<matrix_scalar_unary_exp>(*this), s(s_) { COMPILE_TIME_ASSERT(is_matrix<S>::value == false); } const typename OP::type operator() ( long r, long c ) const { return OP::apply(s,r,c); } const typename OP::type operator() ( long i ) const { return matrix_exp<matrix_scalar_unary_exp>::operator()(i); } template <typename U, long iNR, long iNC, typename MM, typename L > bool aliases ( const matrix<U,iNR,iNC,MM,L>& item ) const { return false; } template <typename U, long iNR, long iNC, typename MM, typename L > bool destructively_aliases ( const matrix<U,iNR,iNC,MM,L>& item ) const { return false; } long nr ( ) const { return NR; } long nc ( ) const { return NC; } private: const S s; }; // ---------------------------------------------------------------------------------------- template <typename OP> class matrix_zeroary_exp; template <typename OP> struct matrix_traits<matrix_zeroary_exp<OP> > { typedef typename OP::type type; typedef typename OP::mem_manager_type mem_manager_type; const static long NR = OP::NR; const static long NC = OP::NC; const static long cost = OP::cost; typedef row_major_layout layout_type; }; template < typename OP > class matrix_zeroary_exp : public matrix_exp<matrix_zeroary_exp<OP> > { public: typedef typename matrix_traits<matrix_zeroary_exp>::type type; typedef typename matrix_traits<matrix_zeroary_exp>::mem_manager_type mem_manager_type; const static long NR = matrix_traits<matrix_zeroary_exp>::NR; const static long NC = matrix_traits<matrix_zeroary_exp>::NC; const static long cost = matrix_traits<matrix_zeroary_exp>::cost; typedef typename matrix_traits<matrix_zeroary_exp>::layout_type layout_type; matrix_zeroary_exp ( const matrix_zeroary_exp& item ) : matrix_exp<matrix_zeroary_exp>(*this) {} matrix_zeroary_exp ( ) : matrix_exp<matrix_zeroary_exp>(*this) {} const typename OP::type operator() ( long r, long c ) const { return OP::apply(r,c); } const typename OP::type operator() ( long i ) const { return matrix_exp<matrix_zeroary_exp>::operator()(i); } template <typename U, long iNR, long iNC , typename MM, typename L> bool aliases ( const matrix<U,iNR,iNC,MM,L>& item ) const { return false; } template <typename U, long iNR, long iNC, typename MM, typename L > bool destructively_aliases ( const matrix<U,iNR,iNC,MM,L>& item ) const { return false; } long nr ( ) const { return NR; } long nc ( ) const { return NC; } }; // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- // Specialized matrix expressions // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- template < typename M, typename EXPr, typename EXPc > class matrix_sub_range_exp; template < typename M, typename EXPr, typename EXPc > struct matrix_traits<matrix_sub_range_exp<M,EXPr,EXPc> > { typedef typename M::type type; typedef typename M::mem_manager_type mem_manager_type; typedef typename M::layout_type layout_type; const static long NR = EXPr::NR*EXPr::NC; const static long NC = EXPc::NR*EXPr::NC; const static long cost = EXPr::cost+EXPc::cost+M::cost; }; template < typename M, typename EXPr, typename EXPc > class matrix_sub_range_exp : public matrix_exp<matrix_sub_range_exp<M,EXPr,EXPc> > { /*! REQUIREMENTS ON M, EXPr and EXPc - must be objects that inherit from matrix_exp !*/ public: typedef typename matrix_traits<matrix_sub_range_exp>::type type; typedef typename matrix_traits<matrix_sub_range_exp>::mem_manager_type mem_manager_type; const static long NR = matrix_traits<matrix_sub_range_exp>::NR; const static long NC = matrix_traits<matrix_sub_range_exp>::NC; const static long cost = matrix_traits<matrix_sub_range_exp>::cost; typedef typename matrix_traits<matrix_sub_range_exp>::layout_type layout_type; matrix_sub_range_exp ( const matrix_sub_range_exp& item ) : matrix_exp<matrix_sub_range_exp>(*this), m(item.m), rows(item.rows), cols(item.cols) { } // This constructor exists simply for the purpose of causing a compile time error if // someone tries to create an instance of this object with the wrong kind of objects. template <typename T1, typename T2, typename T3> matrix_sub_range_exp (T1,T2,T3); matrix_sub_range_exp ( const M& m_, const EXPr& rows_, const EXPc& cols_ ) : matrix_exp<matrix_sub_range_exp>(*this), m(m_), rows(rows_), cols(cols_) { } const typename M::type operator() ( long r, long c ) const { return m(rows(r),cols(c)); } const typename M::type operator() ( long i ) const { return matrix_exp<matrix_sub_range_exp>::operator()(i); } template <typename U, long iNR, long iNC, typename MM, typename L > bool aliases ( const matrix<U,iNR,iNC,MM,L>& item ) const { return m.aliases(item) || rows.aliases(item) || cols.aliases(item); } template <typename U, long iNR, long iNC , typename MM, typename L> bool destructively_aliases ( const matrix<U,iNR,iNC,MM,L>& item ) const { return m.aliases(item) || rows.aliases(item) || cols.aliases(item); } long nr ( ) const { return rows.size(); } long nc ( ) const { return cols.size(); } private: const M& m; const EXPr& rows; const EXPc& cols; }; // ---------------------------------------------------------------------------------------- template <typename M> class matrix_std_vector_exp; template <typename M> struct matrix_traits<matrix_std_vector_exp<M> > { typedef typename M::value_type type; typedef typename memory_manager<char>::kernel_1a mem_manager_type; const static long NR = 0; const static long NC = 1; const static long cost = 1; typedef row_major_layout layout_type; }; template < typename M > class matrix_std_vector_exp : public matrix_exp<matrix_std_vector_exp<M> > { /*! REQUIREMENTS ON M - must be a std::vector object (or an object with a compatible interface). !*/ public: typedef typename matrix_traits<matrix_std_vector_exp>::type type; typedef typename matrix_traits<matrix_std_vector_exp>::mem_manager_type mem_manager_type; const static long NR = matrix_traits<matrix_std_vector_exp>::NR; const static long NC = matrix_traits<matrix_std_vector_exp>::NC; const static long cost = matrix_traits<matrix_std_vector_exp>::cost; typedef typename matrix_traits<matrix_std_vector_exp>::layout_type layout_type; matrix_std_vector_exp ( const matrix_std_vector_exp& item ) : matrix_exp<matrix_std_vector_exp>(*this), m(item.m) { } // This constructor exists simply for the purpose of causing a compile time error if // someone tries to create an instance of this object with the wrong kind of objects. template <typename T1> matrix_std_vector_exp (T1); matrix_std_vector_exp ( const M& m_ ) : matrix_exp<matrix_std_vector_exp>(*this), m(m_) { } const typename M::value_type operator() ( long r, long ) const { return m[r]; } const typename M::value_type operator() ( long i ) const { return m[i]; } template <typename U, long iNR, long iNC, typename MM, typename L> bool aliases ( const matrix<U,iNR,iNC,MM,L>& item ) const { return false; } template <typename U, long iNR, long iNC , typename MM, typename L> bool destructively_aliases ( const matrix<U,iNR,iNC,MM,L>& item ) const { return false; } long nr ( ) const { return m.size(); } long nc ( ) const { return 1; } private: const M& m; }; // ---------------------------------------------------------------------------------------- template <typename M> class matrix_array_exp; template <typename M> struct matrix_traits<matrix_array_exp<M> > { typedef typename M::type type; typedef typename M::mem_manager_type mem_manager_type; typedef row_major_layout layout_type; const static long NR = 0; const static long NC = 1; const static long cost = 1; }; template < typename M > class matrix_array_exp : public matrix_exp<matrix_array_exp<M> > { /*! REQUIREMENTS ON M - must be a dlib::array object (or an object with a compatible interface). !*/ public: typedef typename matrix_traits<matrix_array_exp>::type type; typedef typename matrix_traits<matrix_array_exp>::mem_manager_type mem_manager_type; const static long NR = matrix_traits<matrix_array_exp>::NR; const static long NC = matrix_traits<matrix_array_exp>::NC; const static long cost = matrix_traits<matrix_array_exp>::cost; typedef typename matrix_traits<matrix_array_exp>::layout_type layout_type; matrix_array_exp ( const matrix_array_exp& item ) : matrix_exp<matrix_array_exp>(*this), m(item.m) { } // This constructor exists simply for the purpose of causing a compile time error if // someone tries to create an instance of this object with the wrong kind of objects. template <typename T1> matrix_array_exp (T1); matrix_array_exp ( const M& m_ ) : matrix_exp<matrix_array_exp>(*this), m(m_) { } const typename M::type operator() ( long r, long ) const { return m[r]; } const typename M::type operator() ( long i ) const { return m[i]; } template <typename U, long iNR, long iNC, typename MM, typename L> bool aliases ( const matrix<U,iNR,iNC,MM,L>& item ) const { return false; } template <typename U, long iNR, long iNC , typename MM, typename L> bool destructively_aliases ( const matrix<U,iNR,iNC,MM,L>& item ) const { return false; } long nr ( ) const { return m.size(); } long nc ( ) const { return 1; } private: const M& m; }; // ---------------------------------------------------------------------------------------- template <typename M> class matrix_array2d_exp; template <typename M> struct matrix_traits<matrix_array2d_exp<M> > { typedef typename M::type type; typedef typename M::mem_manager_type mem_manager_type; typedef row_major_layout layout_type; const static long NR = 0; const static long NC = 0; const static long cost = 1; }; template < typename M > class matrix_array2d_exp : public matrix_exp<matrix_array2d_exp<M> > { /*! REQUIREMENTS ON M - must be a dlib::array2d object (or an object with a compatible interface). !*/ public: typedef typename matrix_traits<matrix_array2d_exp>::type type; typedef typename matrix_traits<matrix_array2d_exp>::mem_manager_type mem_manager_type; const static long NR = matrix_traits<matrix_array2d_exp>::NR; const static long NC = matrix_traits<matrix_array2d_exp>::NC; const static long cost = matrix_traits<matrix_array2d_exp>::cost; typedef typename matrix_traits<matrix_array2d_exp>::layout_type layout_type; matrix_array2d_exp ( const matrix_array2d_exp& item ) : matrix_exp<matrix_array2d_exp>(*this), m(item.m) { } // This constructor exists simply for the purpose of causing a compile time error if // someone tries to create an instance of this object with the wrong kind of objects. template <typename T1> matrix_array2d_exp (T1); matrix_array2d_exp ( const M& m_ ) : matrix_exp<matrix_array2d_exp>(*this), m(m_) { } const typename M::type operator() ( long r, long c ) const { return m[r][c]; } const typename M::type operator() ( long i ) const { return matrix_exp<matrix_array2d_exp>::operator()(i); } template <typename U, long iNR, long iNC, typename MM, typename L> bool aliases ( const matrix<U,iNR,iNC,MM,L>& item ) const { return false; } template <typename U, long iNR, long iNC , typename MM, typename L> bool destructively_aliases ( const matrix<U,iNR,iNC,MM,L>& item ) const { return false; } long nr ( ) const { return m.nr(); } long nc ( ) const { return m.nc(); } private: const M& m; }; // ---------------------------------------------------------------------------------------- template <typename M> class matrix_sub_exp; template <typename M> struct matrix_traits<matrix_sub_exp<M> > { typedef typename M::type type; typedef typename M::mem_manager_type mem_manager_type; typedef typename M::layout_type layout_type; const static long NR = 0; const static long NC = 0; const static long cost = M::cost+1; }; template < typename M > class matrix_sub_exp : public matrix_exp<matrix_sub_exp<M> > { /*! REQUIREMENTS ON M - must be an object that inherits from matrix_exp !*/ public: typedef typename matrix_traits<matrix_sub_exp>::type type; typedef typename matrix_traits<matrix_sub_exp>::mem_manager_type mem_manager_type; const static long NR = matrix_traits<matrix_sub_exp>::NR; const static long NC = matrix_traits<matrix_sub_exp>::NC; const static long cost = matrix_traits<matrix_sub_exp>::cost; typedef typename matrix_traits<matrix_sub_exp>::layout_type layout_type; matrix_sub_exp ( const matrix_sub_exp& item ) : matrix_exp<matrix_sub_exp>(*this), m(item.m), r_(item.r_), c_(item.c_), nr_(item.nr_), nc_(item.nc_) { } // This constructor exists simply for the purpose of causing a compile time error if // someone tries to create an instance of this object with the wrong kind of objects. template <typename T1> matrix_sub_exp (T1, long, long, long, long); matrix_sub_exp ( const M& m_, const long& r__, const long& c__, const long& nr__, const long& nc__ ) : matrix_exp<matrix_sub_exp>(*this), m(m_), r_(r__), c_(c__), nr_(nr__), nc_(nc__) { } const typename M::type operator() ( long r, long c ) const { return m(r+r_,c+c_); } const typename M::type operator() ( long i ) const { return matrix_exp<matrix_sub_exp>::operator()(i); } template <typename U, long iNR, long iNC, typename MM, typename L > bool aliases ( const matrix<U,iNR,iNC,MM,L>& item ) const { return m.aliases(item); } template <typename U, long iNR, long iNC , typename MM, typename L> bool destructively_aliases ( const matrix<U,iNR,iNC,MM,L>& item ) const { return m.aliases(item); } long nr ( ) const { return nr_; } long nc ( ) const { return nc_; } const M& m; const long r_, c_, nr_, nc_; }; // ---------------------------------------------------------------------------------------- class matrix_range_exp; template <> struct matrix_traits<matrix_range_exp> { typedef long type; typedef memory_manager<char>::kernel_1a mem_manager_type; typedef row_major_layout layout_type; const static long NR = 0; const static long NC = 1; const static long cost = 1; }; class matrix_range_exp : public matrix_exp<matrix_range_exp> { public: typedef matrix_traits<matrix_range_exp>::type type; typedef matrix_traits<matrix_range_exp>::mem_manager_type mem_manager_type; const static long NR = matrix_traits<matrix_range_exp>::NR; const static long NC = matrix_traits<matrix_range_exp>::NC; const static long cost = matrix_traits<matrix_range_exp>::cost; typedef matrix_traits<matrix_range_exp>::layout_type layout_type; matrix_range_exp ( const matrix_range_exp& item ) : matrix_exp<matrix_range_exp>(*this), nr_(item.nr_), start(item.start), inc(item.inc) {} matrix_range_exp ( long start_, long end_ ) : matrix_exp<matrix_range_exp>(*this) { start = start_; if (start_ <= end_) inc = 1; else inc = -1; nr_ = std::abs(end_ - start_) + 1; } matrix_range_exp ( long start_, long inc_, long end_ ) : matrix_exp<matrix_range_exp>(*this) { start = start_; nr_ = std::abs(end_ - start_)/inc_ + 1; if (start_ <= end_) inc = inc_; else inc = -inc_; } long operator() ( long r, long c ) const { return start + r*inc; } long operator() ( long r ) const { return start + r*inc; } template <typename U, long iNR, long iNC , typename MM, typename L> bool aliases ( const matrix<U,iNR,iNC,MM,L>& item ) const { return false; } template <typename U, long iNR, long iNC, typename MM, typename L > bool destructively_aliases ( const matrix<U,iNR,iNC,MM,L>& item ) const { return false; } long nr ( ) const { return nr_; } long nc ( ) const { return NC; } long nr_; long start; long inc; }; // ---------------------------------------------------------------------------------------- template <long start, long inc_, long end> class matrix_range_static_exp; template <long start, long inc_, long end> struct matrix_traits<matrix_range_static_exp<start,inc_,end> > { typedef long type; typedef memory_manager<char>::kernel_1a mem_manager_type; const static long NR = tabs<(end - start)>::value/inc_ + 1; const static long NC = 1; const static long cost = 1; typedef row_major_layout layout_type; }; template <long start, long inc_, long end> class matrix_range_static_exp : public matrix_exp<matrix_range_static_exp<start,inc_,end> > { public: typedef typename matrix_traits<matrix_range_static_exp>::type type; typedef typename matrix_traits<matrix_range_static_exp>::mem_manager_type mem_manager_type; const static long NR = matrix_traits<matrix_range_static_exp>::NR; const static long NC = matrix_traits<matrix_range_static_exp>::NC; const static long cost = matrix_traits<matrix_range_static_exp>::cost; typedef typename matrix_traits<matrix_range_static_exp>::layout_type layout_type; const static long inc = (start <= end)?inc_:-inc_; matrix_range_static_exp ( const matrix_range_static_exp& item ) : matrix_exp<matrix_range_static_exp>(*this) {} matrix_range_static_exp ( ) : matrix_exp<matrix_range_static_exp>(*this) {} long operator() ( long r, long c ) const { return start + r*inc; } long operator() ( long r ) const { return start + r*inc; } template <typename U, long iNR, long iNC , typename MM, typename L> bool aliases ( const matrix<U,iNR,iNC,MM,L>& item ) const { return false; } template <typename U, long iNR, long iNC, typename MM, typename L > bool destructively_aliases ( const matrix<U,iNR,iNC,MM,L>& item ) const { return false; } long nr ( ) const { return NR; } long nc ( ) const { return NC; } }; // ---------------------------------------------------------------------------------------- } #endif // DLIB_MATRIx_UTILITIES_
[ "jimmy@DGJ3X3B1.(none)" ]
[ [ [ 1, 1601 ] ] ]
7f6ca61d3444928a6b9c329d7fcade22bdd5c97c
d425cf21f2066a0cce2d6e804bf3efbf6dd00c00
/TacticalAI/DecideAction.cpp
7c3451f56a21cb4730a31c69763ca168af2a8347
[]
no_license
infernuslord/ja2
d5ac783931044e9b9311fc61629eb671f376d064
91f88d470e48e60ebfdb584c23cc9814f620ccee
refs/heads/master
2021-01-02T23:07:58.941216
2011-10-18T09:22:53
2011-10-18T09:22:53
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
214,488
cpp
#ifdef PRECOMPILEDHEADERS #include "AI All.h" #else #include "ai.h" #include "AIInternals.h" #include "Isometric utils.h" #include "Points.h" #include "overhead.h" #include "opplist.h" #include "items.h" #include "Weapons.h" #include "NPC.h" #include "Soldier Functions.h" #include "worldman.h" #include "Scheduling.h" #include "Message.h" #include "Structure Wrap.h" #include "Keys.h" #include "pathai.h" #include "Render Fun.h" #include "Boxing.h" // #include "Air Raid.h" #include "Soldier Profile.h" #include "soldier profile type.h" #include "Soldier macros.h" #include "los.h" #include "Buildings.h" #include "strategicmap.h" #include "Quests.h" #include "Map Screen Interface Map.h" #include "soldier ani.h" #include "rotting corpses.h" #include "GameSettings.h" #include "Dialogue Control.h" #endif #include "connect.h" #include "Text.h" ////////////////////////////////////////////////////////////////////////////// // SANDRO - In this file, all APBPConstants[AP_CROUCH] and APBPConstants[AP_PRONE] were changed to GetAPsCrouch() and GetAPsProne() // On the bottom here, there are these functions made ////////////////////////////////////////////////////////////////////// extern BOOLEAN gfHiddenInterrupt; extern BOOLEAN gfUseAlternateQueenPosition; // global status time counters to determine what takes the most time #ifdef AI_TIMING_TESTS UINT32 guiGreenTimeTotal = 0, guiYellowTimeTotal = 0, guiRedTimeTotal = 0, guiBlackTimeTotal = 0; UINT32 guiGreenCounter = 0, guiYellowCounter = 0, guiRedCounter = 0, guiBlackCounter = 0; UINT32 guiRedSeekTimeTotal = 0, guiRedHelpTimeTotal = 0, guiRedHideTimeTotal = 0; UINT32 guiRedSeekCounter = 0, guiRedHelpCounter = 0; guiRedHideCounter = 0; #endif #define CENTER_OF_RING 11237 #define MAX_FLANKS_RED 15 #define MAX_FLANKS_YELLOW 25 #define MIN_FLANK_DIST_YELLOW 10 * STRAIGHT_RATIO #define MAX_FLANK_DIST_YELLOW 50 * STRAIGHT_RATIO #define MIN_FLANK_DIST_RED 10 * STRAIGHT_RATIO #define MAX_FLANK_DIST_RED 40 * STRAIGHT_RATIO void DoneScheduleAction( SOLDIERTYPE * pSoldier ) { pSoldier->aiData.fAIFlags &= (~AI_CHECK_SCHEDULE); pSoldier->bAIScheduleProgress = 0; PostNextSchedule( pSoldier ); } INT8 DecideActionSchedule( SOLDIERTYPE * pSoldier ) { SCHEDULENODE * pSchedule; INT32 iScheduleIndex; UINT8 ubScheduleAction; INT32 usGridNo1, usGridNo2; INT16 sX, sY; INT8 bDirection; STRUCTURE * pStructure; BOOLEAN fDoUseDoor; DOOR_STATUS * pDoorStatus; pSchedule = GetSchedule( pSoldier->ubScheduleID ); if (!pSchedule) { return( AI_ACTION_NONE ); } if (pSchedule->usFlags & SCHEDULE_FLAGS_ACTIVE1) { iScheduleIndex = 0; } else if (pSchedule->usFlags & SCHEDULE_FLAGS_ACTIVE2) { iScheduleIndex = 1; } else if (pSchedule->usFlags & SCHEDULE_FLAGS_ACTIVE3) { iScheduleIndex = 2; } else if (pSchedule->usFlags & SCHEDULE_FLAGS_ACTIVE4) { iScheduleIndex = 3; } else { // error! return( AI_ACTION_NONE ); } ubScheduleAction = pSchedule->ubAction[ iScheduleIndex ]; usGridNo1 = pSchedule->usData1[ iScheduleIndex ]; usGridNo2 = pSchedule->usData2[ iScheduleIndex ]; // assume soldier is awake unless the action is a sleep pSoldier->aiData.fAIFlags &= ~(AI_ASLEEP); switch( ubScheduleAction ) { case SCHEDULE_ACTION_LOCKDOOR: //Uses first gridno for locking door, then second to move to after door is locked. //It is possible that the second gridno will border the edge of the map, meaning that //the individual will walk off of the map. //If this is a "merchant", make sure that nobody occupies the building/room. switch( pSoldier->bAIScheduleProgress ) { case 0: // move to gridno specified if (pSoldier->sGridNo == usGridNo1) { pSoldier->bAIScheduleProgress++; // fall through } else { pSoldier->aiData.usActionData = usGridNo1; pSoldier->sAbsoluteFinalDestination = pSoldier->aiData.usActionData; return( AI_ACTION_SCHEDULE_MOVE ); } // fall through case 1: // start the door open: find the door... usGridNo1 = FindDoorAtGridNoOrAdjacent( usGridNo1 ); if (TileIsOutOfBounds(usGridNo1)) { // do nothing right now! return( AI_ACTION_NONE ); } pDoorStatus = GetDoorStatus( usGridNo1 ); if (pDoorStatus && pDoorStatus->ubFlags & DOOR_BUSY) { // do nothing right now! return( AI_ACTION_NONE ); } pStructure = FindStructure( usGridNo1, STRUCTURE_ANYDOOR ); if (pStructure == NULL) { fDoUseDoor = FALSE; } else { // action-specific tests to not handle the door fDoUseDoor = TRUE; if (pStructure->fFlags & STRUCTURE_OPEN) { // not only do we have to lock the door but // close it too! pSoldier->aiData.fAIFlags |= AI_LOCK_DOOR_INCLUDES_CLOSE; } else { DOOR * pDoor; pDoor = FindDoorInfoAtGridNo( usGridNo1 ); if (pDoor) { if (pDoor->fLocked) { // door already locked! fDoUseDoor = FALSE; } else { pDoor->fLocked = TRUE; } } else { ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_BETAVERSION, L"Schedule involved locked door at %d but there's no lock there!", usGridNo1 ); fDoUseDoor = FALSE; } } } if (fDoUseDoor) { pSoldier->aiData.usActionData = usGridNo1; return( AI_ACTION_LOCK_DOOR ); } // the door is already in the desired state, or it doesn't exist! pSoldier->bAIScheduleProgress++; // fall through case 2: if (pSoldier->sGridNo == usGridNo2 || TileIsOutOfBounds(pSoldier->sGridNo)) { // NOWHERE indicates we were supposed to go off map and have done so DoneScheduleAction( pSoldier ); if (!TileIsOutOfBounds(pSoldier->sGridNo)) { pSoldier->aiData.sPatrolGrid[0] = pSoldier->sGridNo; } } else { if ( GridNoOnEdgeOfMap( usGridNo2, &bDirection ) ) { // told to go to edge of map, so go off at that point! pSoldier->ubQuoteActionID = GetTraversalQuoteActionID( bDirection ); } pSoldier->aiData.usActionData = usGridNo2; pSoldier->sAbsoluteFinalDestination = pSoldier->aiData.usActionData; return( AI_ACTION_SCHEDULE_MOVE ); } break; } break; case SCHEDULE_ACTION_UNLOCKDOOR: case SCHEDULE_ACTION_OPENDOOR: case SCHEDULE_ACTION_CLOSEDOOR: //Uses first gridno for opening/closing/unlocking door, then second to move to after door is opened. //It is possible that the second gridno will border the edge of the map, meaning that //the individual will walk off of the map. switch( pSoldier->bAIScheduleProgress ) { case 0: // move to gridno specified if (pSoldier->sGridNo == usGridNo1) { pSoldier->bAIScheduleProgress++; // fall through } else { pSoldier->aiData.usActionData = usGridNo1; pSoldier->sAbsoluteFinalDestination = pSoldier->aiData.usActionData; return( AI_ACTION_SCHEDULE_MOVE ); } // fall through case 1: // start the door open: find the door... usGridNo1 = FindDoorAtGridNoOrAdjacent( usGridNo1 ); if (TileIsOutOfBounds(usGridNo1)) { // do nothing right now! return( AI_ACTION_NONE ); } pDoorStatus = GetDoorStatus( usGridNo1 ); if (pDoorStatus && pDoorStatus->ubFlags & DOOR_BUSY) { // do nothing right now! return( AI_ACTION_NONE ); } pStructure = FindStructure( usGridNo1, STRUCTURE_ANYDOOR ); if (pStructure == NULL) { fDoUseDoor = FALSE; } else { fDoUseDoor = TRUE; // action-specific tests to not handle the door switch( ubScheduleAction ) { case SCHEDULE_ACTION_UNLOCKDOOR: if (pStructure->fFlags & STRUCTURE_OPEN) { // door is already open! fDoUseDoor = FALSE; } else { // set the door to unlocked DOOR * pDoor; pDoor = FindDoorInfoAtGridNo( usGridNo1 ); if (pDoor) { if (pDoor->fLocked) { pDoor->fLocked = FALSE; } else { // door already unlocked! fDoUseDoor = FALSE; } } else { // WTF? Warning time! ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_BETAVERSION, L"Schedule involved locked door at %d but there's no lock there!", usGridNo1 ); fDoUseDoor = FALSE; } } break; case SCHEDULE_ACTION_OPENDOOR: if (pStructure->fFlags & STRUCTURE_OPEN) { // door is already open! fDoUseDoor = FALSE; } break; case SCHEDULE_ACTION_CLOSEDOOR: if ( !(pStructure->fFlags & STRUCTURE_OPEN) ) { // door is already closed! fDoUseDoor = FALSE; } break; default: break; } } if (fDoUseDoor) { pSoldier->aiData.usActionData = usGridNo1; if (ubScheduleAction == SCHEDULE_ACTION_UNLOCKDOOR) { return( AI_ACTION_UNLOCK_DOOR ); } else { return( AI_ACTION_OPEN_OR_CLOSE_DOOR ); } } // the door is already in the desired state, or it doesn't exist! pSoldier->bAIScheduleProgress++; // fall through case 2: if (pSoldier->sGridNo == usGridNo2 || TileIsOutOfBounds(pSoldier->sGridNo)) { // NOWHERE indicates we were supposed to go off map and have done so DoneScheduleAction( pSoldier ); if (!TileIsOutOfBounds(pSoldier->sGridNo)) { pSoldier->aiData.sPatrolGrid[0] = pSoldier->sGridNo; } } else { if ( GridNoOnEdgeOfMap( usGridNo2, &bDirection ) ) { // told to go to edge of map, so go off at that point! pSoldier->ubQuoteActionID = GetTraversalQuoteActionID( bDirection ); } pSoldier->aiData.usActionData = usGridNo2; pSoldier->sAbsoluteFinalDestination = pSoldier->aiData.usActionData; return( AI_ACTION_SCHEDULE_MOVE ); } break; } break; case SCHEDULE_ACTION_GRIDNO: // Only uses the first gridno if ( pSoldier->sGridNo == usGridNo1 ) { // done! DoneScheduleAction( pSoldier ); if (!TileIsOutOfBounds(pSoldier->sGridNo)) { pSoldier->aiData.sPatrolGrid[0] = pSoldier->sGridNo; } } else { // move! pSoldier->aiData.usActionData = usGridNo1; pSoldier->sAbsoluteFinalDestination = pSoldier->aiData.usActionData; return( AI_ACTION_SCHEDULE_MOVE ); } break; case SCHEDULE_ACTION_LEAVESECTOR: //Doesn't use any gridno data switch( pSoldier->bAIScheduleProgress ) { case 0: // start the action pSoldier->aiData.usActionData = FindNearestEdgePoint( pSoldier->sGridNo ); if (TileIsOutOfBounds(pSoldier->aiData.usActionData)) { #ifdef JA2BETAVERSION ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_BETAVERSION, L"Civilian could not find path to map edge!" ); #endif DoneScheduleAction( pSoldier ); return( AI_ACTION_NONE ); } if ( pSoldier->sGridNo == pSoldier->aiData.usActionData ) { // time to go off the map pSoldier->bAIScheduleProgress++; } else { // move! pSoldier->sAbsoluteFinalDestination = pSoldier->aiData.usActionData; return( AI_ACTION_SCHEDULE_MOVE ); } // fall through case 1: // near edge pSoldier->aiData.usActionData = FindNearbyPointOnEdgeOfMap( pSoldier, &bDirection ); if (TileIsOutOfBounds(pSoldier->aiData.usActionData)) { // what the heck?? // ABORT! DoneScheduleAction( pSoldier ); } else { pSoldier->ubQuoteActionID = GetTraversalQuoteActionID( bDirection ); pSoldier->bAIScheduleProgress++; pSoldier->sAbsoluteFinalDestination = pSoldier->aiData.usActionData; return( AI_ACTION_SCHEDULE_MOVE ); } break; case 2: // should now be done! DoneScheduleAction( pSoldier ); break; default: break; } break; case SCHEDULE_ACTION_ENTERSECTOR: if ( pSoldier->ubProfile != NO_PROFILE && gMercProfiles[ pSoldier->ubProfile ].ubMiscFlags & PROFILE_MISC_FLAG2_DONT_ADD_TO_SECTOR ) { // ignore. DoneScheduleAction( pSoldier ); break; } switch( pSoldier->bAIScheduleProgress ) { case 0: sX = CenterX( pSoldier->sOffWorldGridNo ); sY = CenterY( pSoldier->sOffWorldGridNo ); pSoldier->EVENT_SetSoldierPosition( sX, sY ); pSoldier->bInSector = TRUE; MoveSoldierFromAwayToMercSlot( pSoldier ); pSoldier->aiData.usActionData = usGridNo1; pSoldier->bAIScheduleProgress++; pSoldier->sAbsoluteFinalDestination = pSoldier->aiData.usActionData; return( AI_ACTION_SCHEDULE_MOVE ); case 1: if (pSoldier->sGridNo == usGridNo1) { DoneScheduleAction( pSoldier ); if (!TileIsOutOfBounds(pSoldier->sGridNo)) { pSoldier->aiData.sPatrolGrid[0] = pSoldier->sGridNo; } } else { pSoldier->aiData.usActionData = usGridNo1; pSoldier->sAbsoluteFinalDestination = pSoldier->aiData.usActionData; return( AI_ACTION_SCHEDULE_MOVE ); } break; } break; case SCHEDULE_ACTION_WAKE: // Go to this position if (pSoldier->sGridNo == pSoldier->sInitialGridNo) { // th-th-th-that's it! DoneScheduleAction( pSoldier ); pSoldier->aiData.sPatrolGrid[0] = pSoldier->sGridNo; } else { pSoldier->aiData.usActionData = pSoldier->sInitialGridNo; pSoldier->sAbsoluteFinalDestination = pSoldier->aiData.usActionData; return( AI_ACTION_SCHEDULE_MOVE ); } break; case SCHEDULE_ACTION_SLEEP: // Go to this position if (pSoldier->sGridNo == usGridNo1) { // Sleep pSoldier->aiData.fAIFlags |= AI_ASLEEP; DoneScheduleAction( pSoldier ); if (!TileIsOutOfBounds(pSoldier->sGridNo)) { pSoldier->aiData.sPatrolGrid[0] = pSoldier->sGridNo; } } else { pSoldier->aiData.usActionData = usGridNo1; pSoldier->sAbsoluteFinalDestination = pSoldier->aiData.usActionData; return( AI_ACTION_SCHEDULE_MOVE ); } break; } return( AI_ACTION_NONE ); } INT8 DecideActionBoxerEnteringRing(SOLDIERTYPE *pSoldier) { UINT8 ubRoom; INT32 sDesiredMercLoc; UINT8 ubDesiredMercDir; #ifdef DEBUGDECISIONS STR16 tempstr; #endif // boxer, should move into ring! if ( InARoom( pSoldier->sGridNo, &ubRoom )) { if (ubRoom == BOXING_RING) { // look towards nearest player sDesiredMercLoc = ClosestPC( pSoldier, NULL ); if (!TileIsOutOfBounds(sDesiredMercLoc)) { // see if we are facing this person ubDesiredMercDir = atan8(CenterX(pSoldier->sGridNo),CenterY(pSoldier->sGridNo),CenterX(sDesiredMercLoc),CenterY(sDesiredMercLoc)); // if not already facing in that direction, if ( pSoldier->ubDirection != ubDesiredMercDir && pSoldier->InternalIsValidStance( ubDesiredMercDir, gAnimControl[ pSoldier->usAnimState ].ubEndHeight ) ) { pSoldier->aiData.usActionData = ubDesiredMercDir; #ifdef DEBUGDECISIONS sprintf(tempstr,"%s - TURNS TOWARDS CLOSEST PC to face direction %d",pSoldier->name,pSoldier->aiData.usActionData); AIPopMessage(tempstr); #endif return( AI_ACTION_CHANGE_FACING ); } } return( AI_ACTION_ABSOLUTELY_NONE ); } else { // move to starting spot pSoldier->aiData.usActionData = FindClosestBoxingRingSpot( pSoldier, TRUE ); return( AI_ACTION_GET_CLOSER ); } } return( AI_ACTION_ABSOLUTELY_NONE ); } INT8 DecideActionNamedNPC( SOLDIERTYPE * pSoldier ) { INT32 sDesiredMercLoc; UINT8 ubDesiredMercDir; UINT8 ubDesiredMerc; INT32 sDesiredMercDist; #ifdef DEBUGDECISIONS STR16 tempstr; #endif // if a quote record has been set and we're not doing movement, then // it means we have to wait until someone is nearby and then see // to do... // is this person close enough to trigger event? if (pSoldier->ubQuoteRecord && pSoldier->ubQuoteActionID == QUOTE_ACTION_ID_TURNTOWARDSPLAYER ) { sDesiredMercLoc = ClosestPC( pSoldier, &sDesiredMercDist ); if (!TileIsOutOfBounds(sDesiredMercLoc)) { if ( sDesiredMercDist <= NPC_TALK_RADIUS * 2) { pSoldier->ubQuoteRecord = 0; // see if this triggers a conversation/NPC record PCsNearNPC( pSoldier->ubProfile ); // clear "handle every frame" flag pSoldier->aiData.fAIFlags &= (~AI_HANDLE_EVERY_FRAME); return( AI_ACTION_ABSOLUTELY_NONE ); } // see if we are facing this person ubDesiredMercDir = atan8(CenterX(pSoldier->sGridNo),CenterY(pSoldier->sGridNo),CenterX(sDesiredMercLoc),CenterY(sDesiredMercLoc)); // if not already facing in that direction, if (pSoldier->ubDirection != ubDesiredMercDir && pSoldier->InternalIsValidStance( ubDesiredMercDir, gAnimControl[ pSoldier->usAnimState ].ubEndHeight ) ) { pSoldier->aiData.usActionData = ubDesiredMercDir; #ifdef DEBUGDECISIONS sprintf(tempstr,"%s - TURNS TOWARDS CLOSEST PC to face direction %d",pSoldier->name,pSoldier->aiData.usActionData); AIPopMessage(tempstr); #endif return( AI_ACTION_CHANGE_FACING ); } } // do nothing; we're looking at the PC or the NPC is far away return( AI_ACTION_ABSOLUTELY_NONE ); } else { /////////////// // CHECK TO SEE IF WE WANT TO GO UP TO PERSON AND SAY SOMETHING /////////////// pSoldier->aiData.usActionData = NPCConsiderInitiatingConv( pSoldier, &ubDesiredMerc ); if (!TileIsOutOfBounds(pSoldier->aiData.usActionData)) { return( AI_ACTION_APPROACH_MERC ); } } switch( pSoldier->ubProfile ) { case JIM: case JACK: case OLAF: case RAY: case OLGA: case TYRONE: sDesiredMercLoc = ClosestPC( pSoldier, &sDesiredMercDist ); if (!TileIsOutOfBounds(sDesiredMercLoc)) { if ( sDesiredMercDist <= NPC_TALK_RADIUS * 2 ) { AddToShouldBecomeHostileOrSayQuoteList( pSoldier->ubID ); // now wait a bit! pSoldier->aiData.usActionData = 5000; return( AI_ACTION_WAIT ); } else { pSoldier->aiData.usActionData = GoAsFarAsPossibleTowards( pSoldier, sDesiredMercLoc, AI_ACTION_APPROACH_MERC ); if (!TileIsOutOfBounds(pSoldier->aiData.usActionData)) { return( AI_ACTION_APPROACH_MERC ); } } } break; default: break; } return( AI_ACTION_NONE ); } INT8 DecideActionGreen(SOLDIERTYPE *pSoldier) { DOUBLE iChance, iSneaky = 10; INT8 bInWater,bInGas; #ifdef DEBUGDECISIONS STR16 tempstr; #endif DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("DecideActionGreen, orders = %d",pSoldier->aiData.bOrders)); BOOLEAN fCivilian = (PTR_CIVILIAN && (pSoldier->ubCivilianGroup == NON_CIV_GROUP || pSoldier->aiData.bNeutral || (pSoldier->ubBodyType >= FATCIV && pSoldier->ubBodyType <= CRIPPLECIV) ) ); BOOLEAN fCivilianOrMilitia = PTR_CIV_OR_MILITIA; gubNPCPathCount = 0; if ( gTacticalStatus.bBoxingState != NOT_BOXING ) { if (pSoldier->flags.uiStatusFlags & SOLDIER_BOXER) { if ( gTacticalStatus.bBoxingState == PRE_BOXING ) { return( DecideActionBoxerEnteringRing( pSoldier ) ); } else { UINT8 ubRoom; UINT8 ubLoop; // boxer... but since in status green, it's time to leave the ring! if ( InARoom( pSoldier->sGridNo, &ubRoom )) { if (ubRoom == BOXING_RING) { for ( ubLoop = 0; ubLoop < NUM_BOXERS; ubLoop++ ) { if (pSoldier->ubID == gubBoxerID[ ubLoop ]) { // we should go back where we started pSoldier->aiData.usActionData = gsBoxerGridNo[ ubLoop ]; return( AI_ACTION_GET_CLOSER ); } } pSoldier->aiData.usActionData = FindClosestBoxingRingSpot( pSoldier, FALSE ); return( AI_ACTION_GET_CLOSER ); } else { // done! // WANNE: This should fix the bug if any merc are still under PC control. This could happen after boxing in SAN MONA. SOLDIERTYPE *pTeamSoldier; for (INT8 bLoop=gTacticalStatus.Team[gbPlayerNum].bFirstID; bLoop <= gTacticalStatus.Team[gbPlayerNum].bLastID; bLoop++) { pTeamSoldier=MercPtrs[bLoop]; if (pTeamSoldier->flags.uiStatusFlags & SOLDIER_PCUNDERAICONTROL) pTeamSoldier->flags.uiStatusFlags &= (~SOLDIER_PCUNDERAICONTROL); if (pTeamSoldier->flags.uiStatusFlags & SOLDIER_BOXER) pTeamSoldier->flags.uiStatusFlags &= (~SOLDIER_BOXER); } if (pSoldier->bTeam == gbPlayerNum || CountPeopleInBoxingRing() == 0) { TriggerEndOfBoxingRecord( pSoldier ); } } } return( AI_ACTION_ABSOLUTELY_NONE ); } } //else if ( (gTacticalStatus.bBoxingState == PRE_BOXING || gTacticalStatus.bBoxingState == BOXING) && ( PythSpacesAway( pSoldier->sGridNo, CENTER_OF_RING ) <= MaxDistanceVisible() ) ) else if ( PythSpacesAway( pSoldier->sGridNo, CENTER_OF_RING ) <= MaxNormalDistanceVisible() ) { UINT8 ubRingDir; // face ring! ubRingDir = atan8(CenterX(pSoldier->sGridNo),CenterY(pSoldier->sGridNo),CenterX(CENTER_OF_RING),CenterY(CENTER_OF_RING)); if ( gfTurnBasedAI || GetAPsToLook( pSoldier ) <= pSoldier->bActionPoints ) { if ( pSoldier->ubDirection != ubRingDir ) { pSoldier->aiData.usActionData = ubRingDir; return( AI_ACTION_CHANGE_FACING ); } } return( AI_ACTION_NONE ); } } if ( TANK( pSoldier ) ) { return( AI_ACTION_NONE ); } bInWater = Water( pSoldier->sGridNo ); // check if standing in tear gas without a gas mask on, or in smoke bInGas = InGasOrSmoke( pSoldier, pSoldier->sGridNo ); // if real-time, and not in the way, do nothing 90% of the time (for GUARDS!) // unless in water (could've started there), then we better swim to shore! if (fCivilian) { // special stuff for civs if (pSoldier->flags.uiStatusFlags & SOLDIER_COWERING) { // everything's peaceful again, stop cowering!! pSoldier->aiData.usActionData = ANIM_STAND; return( AI_ACTION_STOP_COWERING ); } if (!gfTurnBasedAI) { // ****************** // REAL TIME NPC CODE // ****************** if (pSoldier->aiData.fAIFlags & AI_CHECK_SCHEDULE) { pSoldier->aiData.bAction = DecideActionSchedule( pSoldier ); if (pSoldier->aiData.bAction != AI_ACTION_NONE) { return( pSoldier->aiData.bAction ); } } if (pSoldier->ubProfile != NO_PROFILE) { pSoldier->aiData.bAction = DecideActionNamedNPC( pSoldier ); if ( pSoldier->aiData.bAction != AI_ACTION_NONE ) { return( pSoldier->aiData.bAction ); } // can we act again? not for a minute since we were last spoken to/triggered a record if ( pSoldier->uiTimeSinceLastSpoke && (GetJA2Clock() < pSoldier->uiTimeSinceLastSpoke + 60000) ) { return( AI_ACTION_NONE ); } // turn off counter so we don't check it again pSoldier->uiTimeSinceLastSpoke = 0; } } // if not in the way, do nothing most of the time // unless in water (could've started there), then we better swim to shore! if (!(bInWater) && PreRandom( 5 ) ) { // don't do nuttin! return( AI_ACTION_NONE ); } } //ddd{ if(gGameExternalOptions.bNewTacticalAIBehavior && !( (gTacticalStatus.uiFlags & TURNBASED) && (gTacticalStatus.uiFlags & INCOMBAT) ) && pSoldier->bTeam == ENEMY_TEAM) { INT32 cnt; ROTTING_CORPSE * pCorpse; for ( cnt = 0; cnt < giNumRottingCorpse; cnt++ ) { pCorpse = &(gRottingCorpse[ cnt ] ); if ( pCorpse->fActivated && pCorpse->def.ubAIWarningValue > 0 ) if ( PythSpacesAway( pSoldier->sGridNo, pCorpse->def.sGridNo ) <= 5 )//приделать сравнение переменно дальности видения (smaxvid ?) { //проверить, находится ли труп в поле зрения драника.мента? //CHRISL: Shouldn't we be using the corpse's bLevel? Otherwise a soldier inside a building can see a corpse on the roof of that building //if ( SoldierTo3DLocationLineOfSightTest( pSoldier, pCorpse->def.sGridNo, pSoldier->pathing.bLevel, 3, TRUE, CALC_FROM_WANTED_DIR ) ) if ( SoldierTo3DLocationLineOfSightTest( pSoldier, pCorpse->def.sGridNo, pCorpse->def.bLevel, 3, TRUE, CALC_FROM_WANTED_DIR ) ) { ScreenMsg( MSG_FONT_YELLOW, MSG_INTERFACE, New113Message[MSG113_ENEMY_FOUND_DEAD_BODY]); //pCorpse->def.ubAIWarningValue=0; gRottingCorpse[ cnt ].def.ubAIWarningValue=0; return( AI_ACTION_RED_ALERT ); } } } } //ddd} //////////////////////////////////////////////////////////////////////////// // POINT PATROL: move towards next point unless getting a bit winded //////////////////////////////////////////////////////////////////////////// // this takes priority over water/gas checks, so that point patrol WILL work // from island to island, and through gas covered areas, too if ((pSoldier->aiData.bOrders == POINTPATROL) && (pSoldier->bBreath >= 75)) { if (PointPatrolAI(pSoldier)) { if (!gfTurnBasedAI) { // wait after this... pSoldier->aiData.bNextAction = AI_ACTION_WAIT; pSoldier->aiData.usNextActionData = RealtimeDelay( pSoldier ); } return(AI_ACTION_POINT_PATROL); } else { // Reset path count to avoid dedlok gubNPCPathCount = 0; } } if ((pSoldier->aiData.bOrders == RNDPTPATROL) && (pSoldier->bBreath >=75)) { if (RandomPointPatrolAI(pSoldier)) { if (!gfTurnBasedAI) { // wait after this... pSoldier->aiData.bNextAction = AI_ACTION_WAIT; pSoldier->aiData.usNextActionData = RealtimeDelay( pSoldier ); } return(AI_ACTION_POINT_PATROL); } else { // Reset path count to avoid dedlok gubNPCPathCount = 0; } } //////////////////////////////////////////////////////////////////////////// // WHEN LEFT IN WATER OR GAS, GO TO NEAREST REACHABLE SPOT OF UNGASSED LAND //////////////////////////////////////////////////////////////////////////// DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("DecideActionGreen: get out of water and gas")); if (bInWater || bInGas) { pSoldier->aiData.usActionData = FindNearestUngassedLand(pSoldier); if (!TileIsOutOfBounds(pSoldier->aiData.usActionData)) { #ifdef DEBUGDECISIONS sprintf(tempstr,"%s - SEEKING NEAREST UNGASSED LAND at grid %d",pSoldier->name,pSoldier->aiData.usActionData); AIPopMessage(tempstr); #endif return(AI_ACTION_LEAVE_WATER_GAS); } } //////////////////////////////////////////////////////////////////////// // REST IF RUNNING OUT OF BREATH //////////////////////////////////////////////////////////////////////// DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("DecideActionGreen: rest if running out of breath")); // if our breath is running a bit low, and we're not in the way or in water if ((pSoldier->bBreath < 75) && !bInWater) { // take a breather for gods sake! // for realtime, AI will use a standard wait set outside of here pSoldier->aiData.usActionData = NOWHERE; return(AI_ACTION_NONE); } //////////////////////////////////////////////////////////////////////////// // CLIMB A BUILDING //////////////////////////////////////////////////////////////////////////// if (!fCivilian && pSoldier->aiData.bLastAction != AI_ACTION_CLIMB_ROOF && !is_networked) { iChance = 10 + pSoldier->aiData.bBypassToGreen; // set base chance and maximum seeking distance according to orders switch (pSoldier->aiData.bOrders) { case STATIONARY: iChance *= 0; break; case ONGUARD: iChance += 10; break; case ONCALL: break; case CLOSEPATROL: iChance += -20; break; case RNDPTPATROL: case POINTPATROL: iChance = -30; break; case FARPATROL: iChance += -40; break; case SEEKENEMY: iChance += -30; break; case SNIPER: iChance += 70; break; } // modify for attitude switch (pSoldier->aiData.bAttitude) { case DEFENSIVE: iChance *= 1.5; break; case BRAVESOLO: iChance /= 2; break; case BRAVEAID: iChance /= 2; break; case CUNNINGSOLO: iChance *= 1; break; case CUNNINGAID: iChance /= 1; break; case AGGRESSIVE: iChance /= 3; break; case ATTACKSLAYONLY: break; } //hide those suicidal militia on the roofs for better defensive positions // 0verhaul: If they are allowed at all to move if ( pSoldier->bTeam == MILITIA_TEAM && iChance != 0) iChance += 20; // reduce chance for any injury, less likely to hop up if hurt iChance -= (pSoldier->stats.bLifeMax - pSoldier->stats.bLife); // reduce chance if breath is down //iChance -= (100 - pSoldier->bBreath); // don't care // This is the chance that we want to be on the roof. If already there, invert the chance to see if we want back // down if (pSoldier->pathing.bLevel > 0) { iChance = 100 - iChance; } if ((INT16) PreRandom(100) < iChance) { BOOLEAN fUp = FALSE; if ( pSoldier->pathing.bLevel == 0 ) { fUp = TRUE; } else if (pSoldier->pathing.bLevel > 0 ) { fUp = FALSE; } if ( CanClimbFromHere ( pSoldier, fUp ) ) { DebugMsg ( TOPIC_JA2AI , DBG_LEVEL_3 , String("Soldier %d is climbing roof",pSoldier->ubID) ); return( AI_ACTION_CLIMB_ROOF ); } else { pSoldier->aiData.usActionData = FindClosestClimbPoint(pSoldier, fUp ); // Added the check here because sniper militia who are locked inside of a building without keys // will still have a >100% chance to want to climb, which means an infinite loop. In fact, any // time a move is desired, there probably also will be a need to check for a path. if ( !TileIsOutOfBounds(pSoldier->aiData.usActionData) && LegalNPCDestination(pSoldier,pSoldier->aiData.usActionData,ENSURE_PATH,WATEROK, 0 )) { return( AI_ACTION_MOVE_TO_CLIMB ); } } } } //////////////////////////////////////////////////////////////////////////// // RANDOM PATROL: determine % chance to start a new patrol route //////////////////////////////////////////////////////////////////////////// if (!gubNPCPathCount) // try to limit pathing in Green AI { iChance = 25 + pSoldier->aiData.bBypassToGreen; // set base chance according to orders switch (pSoldier->aiData.bOrders) { case STATIONARY: iChance += -20; break; case ONGUARD: iChance += -15; break; case ONCALL: break; case CLOSEPATROL: iChance += +15; break; case RNDPTPATROL: case POINTPATROL: iChance = 0; break; /* if ( !gfTurnBasedAI ) { // realtime deadlock... increase chance! iChance = 110;// more than 100 in case person is defensive } else if ( pSoldier->bInitialActionPoints < pSoldier->bActionPoints ) // could be less because of carried-over points { // CJC: allow pt patrol guys to do a random move in case // of a deadlock provided they haven't done anything yet this turn iChance= 0; } break; */ case FARPATROL: iChance += +25; break; case SEEKENEMY: iChance += -10; break; case SNIPER: iChance += -10; break; } // modify chance of patrol (and whether it's a sneaky one) by attitude switch (pSoldier->aiData.bAttitude) { case DEFENSIVE: iChance += -10; break; case BRAVESOLO: iChance += 5; break; case BRAVEAID: break; case CUNNINGSOLO: iChance += 5; iSneaky += 10; break; case CUNNINGAID: iSneaky += 5; break; case AGGRESSIVE: iChance += 10; iSneaky += -5; break; case ATTACKSLAYONLY: iChance += 10; iSneaky += -5; break; } // reduce chance for any injury, less likely to wander around when hurt iChance -= (pSoldier->stats.bLifeMax - pSoldier->stats.bLife); // reduce chance if breath is down, less likely to wander around when tired iChance -= (100 - pSoldier->bBreath); // if we're in water with land miles (> 25 tiles) away, // OR if we roll under the chance calculated if (bInWater || ((INT16) PreRandom(100) < iChance)) { pSoldier->aiData.usActionData = RandDestWithinRange(pSoldier); if (!TileIsOutOfBounds(pSoldier->aiData.usActionData)) { pSoldier->aiData.usActionData = GoAsFarAsPossibleTowards( pSoldier, pSoldier->aiData.usActionData, AI_ACTION_RANDOM_PATROL ); } if (!TileIsOutOfBounds(pSoldier->aiData.usActionData)) { #ifdef DEBUGDECISIONS sprintf(tempstr,"%s - RANDOM PATROL to grid %d",pSoldier->name,pSoldier->aiData.usActionData); AIPopMessage(tempstr); #endif if (!gfTurnBasedAI) { // wait after this... pSoldier->aiData.bNextAction = AI_ACTION_WAIT; pSoldier->aiData.usNextActionData = RealtimeDelay( pSoldier ); } return(AI_ACTION_RANDOM_PATROL); } } } if (!gubNPCPathCount) // try to limit pathing in Green AI { //////////////////////////////////////////////////////////////////////////// // SEEK FRIEND: determine %chance for man to pay a friendly visit //////////////////////////////////////////////////////////////////////////// iChance = 25 + pSoldier->aiData.bBypassToGreen; // set base chance and maximum seeking distance according to orders switch (pSoldier->aiData.bOrders) { case STATIONARY: iChance += -20; break; case ONGUARD: iChance += -15; break; case ONCALL: break; case CLOSEPATROL: iChance += +10; break; case RNDPTPATROL: case POINTPATROL: iChance = -10; break; case FARPATROL: iChance += +20; break; case SEEKENEMY: iChance += -10; break; case SNIPER: iChance += -10; break; } // modify for attitude switch (pSoldier->aiData.bAttitude) { case DEFENSIVE: break; case BRAVESOLO: iChance /= 2; break; // loners case BRAVEAID: iChance += 10; break; // friendly case CUNNINGSOLO: iChance /= 2; break; // loners case CUNNINGAID: iChance += 10; break; // friendly case AGGRESSIVE: break; case ATTACKSLAYONLY: break; } // reduce chance for any injury, less likely to wander around when hurt iChance -= (pSoldier->stats.bLifeMax - pSoldier->stats.bLife); // reduce chance if breath is down iChance -= (100 - pSoldier->bBreath); // very likely to wait when exhausted if ((INT16) PreRandom(100) < iChance) { if (RandomFriendWithin(pSoldier)) { if ( pSoldier->aiData.usActionData == GoAsFarAsPossibleTowards( pSoldier, pSoldier->aiData.usActionData, AI_ACTION_SEEK_FRIEND ) ) { #ifdef DEBUGDECISIONS sprintf(tempstr,"%s - SEEK FRIEND at grid %d",pSoldier->name,pSoldier->aiData.usActionData); AIPopMessage(tempstr); #endif if (fCivilianOrMilitia && !gfTurnBasedAI) { // pause at the end of the walk! pSoldier->aiData.bNextAction = AI_ACTION_WAIT; pSoldier->aiData.usNextActionData = (UINT16) REALTIME_CIV_AI_DELAY; } return(AI_ACTION_SEEK_FRIEND); } } } } //////////////////////////////////////////////////////////////////////////// // SNIPERS LIKE TO CROUCH (on roofs) //////////////////////////////////////////////////////////////////////////// DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("DecideActionGreen: Snipers like to crouch, sniper = %d",pSoldier->sniper)); // if not in water and not already crouched, try to crouch down first if (pSoldier->aiData.bOrders == SNIPER && !PTR_CROUCHED && IsValidStance( pSoldier, ANIM_CROUCH ) && pSoldier->pathing.bLevel == 1 ) { if (!gfTurnBasedAI || (GetAPsToChangeStance( pSoldier, ANIM_CROUCH ) <= pSoldier->bActionPoints)) { DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("DecideActionGreen: Sniper is crouching")); pSoldier->aiData.usActionData = ANIM_CROUCH; pSoldier->sniper = 0; return(AI_ACTION_CHANGE_STANCE); } } //////////////////////////////////////////////////////////////////////////// // SNIPER - RAISE WEAPON TO SCAN AREA //////////////////////////////////////////////////////////////////////////// DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("DecideActionGreen: Snipers like to raise weapons, sniper = %d",pSoldier->sniper)); if ( pSoldier->aiData.bOrders == SNIPER && pSoldier->sniper == 0 && ( pSoldier->pathing.bLevel == 1 || Random(100) < 40 ) ) { if ( !(WeaponReady(pSoldier)) ) // SANDRO - only call this if we are not in readied position yet { if (!gfTurnBasedAI || GetAPsToReadyWeapon( pSoldier, READY_RIFLE_CROUCH ) <= pSoldier->bActionPoints) { DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("DecideActionGreen: Sniper is raising weapon, soldier = %d, sniper = %d",pSoldier->ubID,pSoldier->sniper)); pSoldier->sniper = 1; DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("DecideActionGreen: Sniper = %d",pSoldier->sniper)); return(AI_ACTION_RAISE_GUN); } } } //else if ( pSoldier->sniper == 1 ) //{ // DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("DecideActionGreen: Sniper is lowering weapon, sniper = %d",pSoldier->sniper)); // pSoldier->sniper = 0; // DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("DecideActionGreen: Sniper = %d",pSoldier->sniper)); // return(AI_ACTION_LOWER_GUN); //} //////////////////////////////////////////////////////////////////////////// // SANDRO - occasionally, allow regular soldiers to scan around too if ( (UsingNewCTHSystem() == false && IsScoped(&pSoldier->inv[HANDPOS])) || (UsingNewCTHSystem() == true && NCTHIsScoped(&pSoldier->inv[HANDPOS])) ) { if (!(WeaponReady(pSoldier))) { if (!gfTurnBasedAI || GetAPsToReadyWeapon( pSoldier, pSoldier->usAnimState ) <= pSoldier->bActionPoints) { iChance = 25; if ( pSoldier->ubSoldierClass == SOLDIER_CLASS_ELITE_MILITIA || pSoldier->ubSoldierClass == SOLDIER_CLASS_ELITE ) iChance += 15; else if ( pSoldier->ubSoldierClass == SOLDIER_CLASS_GREEN_MILITIA || pSoldier->ubSoldierClass == SOLDIER_CLASS_ADMINISTRATOR ) iChance -= 15; if ( Random(100) < iChance ) { DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("DecideActionGreen: Soldier deciding to raise weapon with scope")); return(AI_ACTION_RAISE_GUN); } } } else // if the weapon is ready already, maybe unready it { if ( Random(100) < 40 ) { DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("DecideActionGreen: Soldier deciding to lower weapon")); return(AI_ACTION_LOWER_GUN); } } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// // LOOK AROUND: determine %chance for man to turn in place //////////////////////////////////////////////////////////////////////////// DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("DecideActionGreen: Soldier deciding to turn")); if (!gfTurnBasedAI || GetAPsToLook( pSoldier ) <= pSoldier->bActionPoints) { // avoid 2 consecutive random turns in a row if (pSoldier->aiData.bLastAction != AI_ACTION_CHANGE_FACING) { iChance = 25 + pSoldier->aiData.bBypassToGreen; // set base chance according to orders if (pSoldier->aiData.bOrders == STATIONARY || pSoldier->aiData.bOrders == SNIPER) iChance += 25; if (pSoldier->aiData.bOrders == ONGUARD) iChance += 20; if (pSoldier->aiData.bAttitude == DEFENSIVE) iChance += 25; if ( pSoldier->aiData.bOrders == SNIPER && pSoldier->pathing.bLevel == 1) iChance += 35; if ( WeaponReady(pSoldier) ) // SANDRO - if readied weapon, make him more likelz to turn around iChance += 30; if ((INT16)PreRandom(100) < iChance) { // roll random directions (stored in actionData) until different from current do { // if man has a LEGAL dominant facing, and isn't facing it, he will turn // back towards that facing 50% of the time here (normally just enemies) if ((pSoldier->aiData.bDominantDir >= 0) && (pSoldier->aiData.bDominantDir <= 8) && (pSoldier->ubDirection != pSoldier->aiData.bDominantDir) && PreRandom(2) && pSoldier->aiData.bOrders != SNIPER ) { pSoldier->aiData.usActionData = pSoldier->aiData.bDominantDir; } else { INT32 iNoiseValue; BOOLEAN fClimb; BOOLEAN fReachable; INT32 sNoiseGridNo = MostImportantNoiseHeard(pSoldier,&iNoiseValue, &fClimb, &fReachable); UINT8 ubNoiseDir; if (TileIsOutOfBounds(sNoiseGridNo) || (ubNoiseDir = atan8(CenterX(pSoldier->sGridNo),CenterY(pSoldier->sGridNo),CenterX(sNoiseGridNo),CenterY(sNoiseGridNo)) ) == pSoldier->ubDirection ) { pSoldier->aiData.usActionData = PreRandom(8); } else { pSoldier->aiData.usActionData = ubNoiseDir; } } } while (pSoldier->aiData.usActionData == pSoldier->ubDirection); #ifdef DEBUGDECISIONS sprintf(tempstr,"%s - TURNS to face direction %d",pSoldier->name,pSoldier->aiData.usActionData); AIPopMessage(tempstr); #endif DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("DecideActionGreen: Trying to turn - checking stance validity, sniper = %d",pSoldier->sniper)); if ( pSoldier->InternalIsValidStance( (INT8) pSoldier->aiData.usActionData, gAnimControl[ pSoldier->usAnimState ].ubEndHeight ) ) { if ( !gfTurnBasedAI ) { // wait after this... pSoldier->aiData.bNextAction = AI_ACTION_WAIT; pSoldier->aiData.usNextActionData = RealtimeDelay( pSoldier ); } DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("DecideActionGreen: Soldier is turning")); return(AI_ACTION_CHANGE_FACING); } } } } //////////////////////////////////////////////////////////////////////////// // NONE: //////////////////////////////////////////////////////////////////////////// // by default, if everything else fails, just stands in place without turning // for realtime, regular AI guys will use a standard wait set outside of here pSoldier->aiData.usActionData = NOWHERE; return(AI_ACTION_NONE); } INT8 DecideActionYellow(SOLDIERTYPE *pSoldier) { INT32 iDummy; UINT8 ubNoiseDir; INT32 sNoiseGridNo; INT32 iNoiseValue; INT32 iChance, iSneaky; INT32 sClosestFriend; BOOLEAN fCivilian = (PTR_CIVILIAN && (pSoldier->ubCivilianGroup == NON_CIV_GROUP || pSoldier->aiData.bNeutral || (pSoldier->ubBodyType >= FATCIV && pSoldier->ubBodyType <= CRIPPLECIV) ) ); BOOLEAN fClimb; BOOLEAN fReachable; #ifdef DEBUGDECISIONS STR16 tempstr; #endif if (fCivilian) { if (pSoldier->flags.uiStatusFlags & SOLDIER_COWERING) { // everything's peaceful again, stop cowering!! pSoldier->aiData.usActionData = ANIM_STAND; return( AI_ACTION_STOP_COWERING ); } if (!gfTurnBasedAI) { // ****************** // REAL TIME NPC CODE // ****************** if (pSoldier->ubProfile != NO_PROFILE) { pSoldier->aiData.bAction = DecideActionNamedNPC( pSoldier ); if ( pSoldier->aiData.bAction != AI_ACTION_NONE ) { return( pSoldier->aiData.bAction ); } } } } // determine the most important noise heard, and its relative value sNoiseGridNo = MostImportantNoiseHeard(pSoldier,&iNoiseValue, &fClimb, &fReachable); //NumMessage("iNoiseValue = ",iNoiseValue); if (TileIsOutOfBounds(sNoiseGridNo)) { // then we have no business being under YELLOW status any more! #ifdef RECORDNET fprintf(NetDebugFile,"\nDecideActionYellow: ERROR - No important noise known by guynum %d\n\n",pSoldier->ubID); #endif #ifdef BETAVERSION NumMessage("DecideActionYellow: ERROR - No important noise known by guynum ",pSoldier->ubID); #endif return(AI_ACTION_NONE); } //////////////////////////////////////////////////////////////////////////// // LOOK AROUND TOWARD NOISE: determine %chance for man to turn towards noise //////////////////////////////////////////////////////////////////////////// // determine direction from this soldier in which the noise lies ubNoiseDir = atan8(CenterX(pSoldier->sGridNo),CenterY(pSoldier->sGridNo),CenterX(sNoiseGridNo),CenterY(sNoiseGridNo)); // if soldier is not already facing in that direction, // and the noise source is close enough that it could possibly be seen if ( !gfTurnBasedAI || GetAPsToLook( pSoldier ) <= pSoldier->bActionPoints ) { if ((pSoldier->ubDirection != ubNoiseDir) && PythSpacesAway(pSoldier->sGridNo,sNoiseGridNo) <= pSoldier->GetMaxDistanceVisible(sNoiseGridNo) ) { // set base chance according to orders if ((pSoldier->aiData.bOrders == STATIONARY) || (pSoldier->aiData.bOrders == ONGUARD) ) iChance = 50; else // all other orders iChance = 25; if (pSoldier->aiData.bAttitude == DEFENSIVE) iChance += 15; if ((INT16)PreRandom(100) < iChance && pSoldier->InternalIsValidStance( ubNoiseDir, gAnimControl[ pSoldier->usAnimState ].ubEndHeight ) ) { pSoldier->aiData.usActionData = ubNoiseDir; #ifdef DEBUGDECISIONS sprintf(tempstr,"%s - TURNS TOWARDS NOISE to face direction %d",pSoldier->name,pSoldier->aiData.usActionData); AIPopMessage(tempstr); #endif if ( pSoldier->aiData.bOrders == SNIPER ) { if (!gfTurnBasedAI || GetAPsToReadyWeapon( pSoldier, READY_RIFLE_CROUCH ) <= pSoldier->bActionPoints) { pSoldier->aiData.bNextAction = AI_ACTION_RAISE_GUN; } } //////////////////////////////////////////////////////////////////////////// // SANDRO - allow regular soldiers to raise scoped weapons to see rather away too if ( (UsingNewCTHSystem() == false && IsScoped(&pSoldier->inv[HANDPOS])) || (UsingNewCTHSystem() == true && NCTHIsScoped(&pSoldier->inv[HANDPOS])) ) { if (!(WeaponReady(pSoldier))) { if (!gfTurnBasedAI || GetAPsToReadyWeapon( pSoldier, pSoldier->usAnimState ) <= pSoldier->bActionPoints) { if ( Random(100) < 35 ) { pSoldier->aiData.bNextAction = AI_ACTION_RAISE_GUN; } } } } //////////////////////////////////////////////////////////////////////////// return(AI_ACTION_CHANGE_FACING); } } } //////////////////////////////////////////////////////////////////////////// // RADIO YELLOW ALERT: determine %chance to call others and report noise //////////////////////////////////////////////////////////////////////////// // if we have the action points remaining to RADIO // (we never want NPCs to choose to radio if they would have to wait a turn) if ( !fCivilian && (pSoldier->bActionPoints >= APBPConstants[AP_RADIO]) && (gTacticalStatus.Team[pSoldier->bTeam].bMenInSector > 1) ) { // base chance depends on how much new info we have to radio to the others iChance = 5 * WhatIKnowThatPublicDont(pSoldier,FALSE); // use 5 * for YELLOW alert // if I actually know something they don't and I ain't swimming (deep water) if (iChance && !DeepWater( pSoldier->sGridNo )) { // CJC: this addition allows for varying difficulty levels for soldier types iChance += gbDiff[ DIFF_RADIO_RED_ALERT ][ SoldierDifficultyLevel( pSoldier ) ] / 2; // Alex: this addition replaces the sectorValue/2 in original JA //iChance += gsDiff[DIFF_RADIO_RED_ALERT][GameOption[ENEMYDIFFICULTY]] / 2; // modify base chance according to orders switch (pSoldier->aiData.bOrders) { case STATIONARY: iChance += 20; break; case ONGUARD: iChance += 15; break; case ONCALL: iChance += 10; break; case CLOSEPATROL: break; case RNDPTPATROL: case POINTPATROL: break; case FARPATROL: iChance += -10; break; case SEEKENEMY: iChance += -20; break; case SNIPER: iChance += -10; break; //Madd: sniper contacts are supposed to be automatically reported } // modify base chance according to attitude switch (pSoldier->aiData.bAttitude) { case DEFENSIVE: iChance += 20; break; case BRAVESOLO: iChance += -10; break; case BRAVEAID: break; case CUNNINGSOLO:iChance += -5; break; case CUNNINGAID: break; case AGGRESSIVE: iChance += -20; break; case ATTACKSLAYONLY: iChance = 0; break; } #ifdef DEBUGDECISIONS AINumMessage("Chance to radio yellow alert = ",iChance); #endif if ((INT16)PreRandom(100) < iChance) { #ifdef DEBUGDECISIONS AINameMessage(pSoldier,"decides to radio a YELLOW alert!",1000); #endif return(AI_ACTION_YELLOW_ALERT); } } } if ( TANK( pSoldier ) ) { return( AI_ACTION_NONE ); } //////////////////////////////////////////////////////////////////////// // REST IF RUNNING OUT OF BREATH //////////////////////////////////////////////////////////////////////// // if our breath is running a bit low, and we're not in water if ((pSoldier->bBreath < 25) && !pSoldier->MercInWater()) { // take a breather for gods sake! pSoldier->aiData.usActionData = NOWHERE; return(AI_ACTION_NONE); } //continue flanking INT32 tempGridNo; if (TileIsOutOfBounds(sNoiseGridNo)) tempGridNo = pSoldier->lastFlankSpot; else tempGridNo = sNoiseGridNo; if ( pSoldier->numFlanks > 0 && pSoldier->numFlanks < MAX_FLANKS_YELLOW ) { INT16 currDir = GetDirectionFromGridNo ( tempGridNo, pSoldier ); INT16 origDir = pSoldier->origDir; pSoldier->numFlanks += 1; if ( pSoldier->flags.lastFlankLeft ) { if ( origDir > currDir ) origDir -= 8; if ( (currDir - origDir) >= 4 ) { pSoldier->numFlanks = MAX_FLANKS_YELLOW; } else { pSoldier->aiData.usActionData = FindFlankingSpot (pSoldier, tempGridNo , AI_ACTION_FLANK_LEFT); if (!TileIsOutOfBounds(pSoldier->aiData.usActionData) ) //&& (currDir - origDir) < 2 ) return AI_ACTION_FLANK_LEFT ; else pSoldier->numFlanks = MAX_FLANKS_YELLOW; } } else { if ( origDir < currDir ) origDir += 8; if ( (origDir - currDir) >= 4 ) { pSoldier->numFlanks = MAX_FLANKS_YELLOW; } else { pSoldier->aiData.usActionData = FindFlankingSpot (pSoldier, tempGridNo , AI_ACTION_FLANK_RIGHT); if (!TileIsOutOfBounds(pSoldier->aiData.usActionData))//&& (origDir - currDir) < 2 ) return AI_ACTION_FLANK_RIGHT ; else pSoldier->numFlanks = MAX_FLANKS_YELLOW; } } } if ( pSoldier->numFlanks == MAX_FLANKS_YELLOW ) { pSoldier->numFlanks += 1; pSoldier->aiData.usActionData = GoAsFarAsPossibleTowards(pSoldier,tempGridNo,AI_ACTION_SEEK_NOISE); return AI_ACTION_SEEK_NOISE ; } // Hmmm, I don't think this check is doing what is intended. But then I see no comment about what is intended. // However, civilians with no profile (and likely no weapons) do not need to be seeking out noises. Most don't // even have the body type for it (can't climb or jump). //if ( !( pSoldier->bTeam == CIV_TEAM && pSoldier->ubProfile != NO_PROFILE && pSoldier->ubProfile != ELDIN ) ) //if ( pSoldier->bTeam != CIV_TEAM || ( !pSoldier->aiData.bNeutral && pSoldier->ubProfile != ELDIN ) ) // ADB: Eldin is the only neutral civilian who should be seeking out noises. As the museum curator, he can be // available to talk to. As the night watchman, he needs to look for thieves. bool onCivTeam = (pSoldier->bTeam == CIV_TEAM); bool isNamedCiv = (pSoldier->ubProfile != NO_PROFILE); bool isEldin = (pSoldier->ubProfile == ELDIN);//logically flipped from the original, isNotEldin == false is confusing // For purpose of seeking noise, cowardly civs are neutral, even if attacked by your thugs bool isNeutral = pSoldier->aiData.bNeutral || pSoldier->flags.uiStatusFlags & SOLDIER_COWERING; if ( (onCivTeam == false) || //true #1 (onCivTeam == true && isNamedCiv == true && isNeutral == false) || //true #2 (onCivTeam == true && isEldin == true)//true #3 ) { // IF WE ARE MILITIA/CIV IN REALTIME, CLOSE TO NOISE, AND CAN SEE THE SPOT WHERE THE NOISE CAME FROM, FORGET IT if ( fReachable && !fClimb && !gfTurnBasedAI && (pSoldier->bTeam == MILITIA_TEAM || pSoldier->bTeam == CIV_TEAM )&& PythSpacesAway( pSoldier->sGridNo, sNoiseGridNo ) < 5 ) { if ( SoldierTo3DLocationLineOfSightTest( pSoldier, sNoiseGridNo, pSoldier->pathing.bLevel, 0, TRUE, 6 ) ) { // set reachable to false so we don't investigate fReachable = FALSE; // forget about noise pSoldier->aiData.sNoiseGridno = NOWHERE; pSoldier->aiData.ubNoiseVolume = 0; } } //////////////////////////////////////////////////////////////////////////// // SEEK NOISE //////////////////////////////////////////////////////////////////////////// if ( fReachable ) { // remember that noise value is negative, and closer to 0 => more important! iChance = 95 + (iNoiseValue / 3); iSneaky = 30; // increase // set base chance according to orders switch (pSoldier->aiData.bOrders) { case STATIONARY: iChance += -20; break; case ONGUARD: iChance += -15; break; case ONCALL: break; case CLOSEPATROL: iChance += -10; break; case RNDPTPATROL: case POINTPATROL: break; case FARPATROL: iChance += 10; break; case SEEKENEMY: iChance += 25; break; case SNIPER: iChance += -10; break; } // modify chance of patrol (and whether it's a sneaky one) by attitude switch (pSoldier->aiData.bAttitude) { case DEFENSIVE: iChance += -10; iSneaky += 15; break; case BRAVESOLO: iChance += 10; break; case BRAVEAID: iChance += 5; break; case CUNNINGSOLO: iChance += 5; iSneaky += 30; break; case CUNNINGAID: iSneaky += 30; break; case AGGRESSIVE: iChance += 20; iSneaky += -10; break; case ATTACKSLAYONLY: iChance += 20; iSneaky += -10; break; } // reduce chance if breath is down, less likely to wander around when tired iChance -= (100 - pSoldier->bBreath); //Madd: make militia less likely to go running headlong into trouble if ( pSoldier->bTeam == MILITIA_TEAM ) iChance -= 30; if ((INT16) PreRandom(100) < iChance ) { pSoldier->aiData.usActionData = GoAsFarAsPossibleTowards(pSoldier,sNoiseGridNo,AI_ACTION_SEEK_NOISE); if (!TileIsOutOfBounds(pSoldier->aiData.usActionData)) { #ifdef DEBUGDECISIONS sprintf(tempstr,"%s - INVESTIGATING NOISE at grid %d, moving to %d", pSoldier->name,sNoiseGridNo,pSoldier->aiData.usActionData); AIPopMessage(tempstr); #endif if ( fClimb )//&& pSoldier->aiData.usActionData == sNoiseGridNo) { // need to climb AND have enough APs to get there this turn BOOLEAN fUp = TRUE; if (pSoldier->pathing.bLevel > 0 ) fUp = FALSE; if (!fUp) DebugMsg ( TOPIC_JA2AI , DBG_LEVEL_3 , String("Soldier %d, is climbing down",pSoldier->ubID) ); // 0verhaul: the Closest Noise call returns the location of a climb. So 1) it's not necessary to // ask if we can climb from here. And 2) It's not necessary to look for the climb point. We already // have it. // if ( CanClimbFromHere ( pSoldier, fUp ) ) if ( pSoldier->sGridNo == sNoiseGridNo) { if (IsActionAffordable(pSoldier) && pSoldier->bActionPoints >= ( APBPConstants[AP_CLIMBROOF] + MinAPsToAttack( pSoldier, sNoiseGridNo, ADDTURNCOST))) { return( AI_ACTION_CLIMB_ROOF ); } } else { // pSoldier->aiData.usActionData = FindClosestClimbPoint(pSoldier, pSoldier->sGridNo , sNoiseGridNo , fUp ); pSoldier->aiData.usActionData = sNoiseGridNo; //if (!TileIsOutOfBounds(pSoldier->aiData.usActionData)) { return( AI_ACTION_MOVE_TO_CLIMB ); } } } if ( ( pSoldier->aiData.bAttitude == CUNNINGAID || pSoldier->aiData.bAttitude == CUNNINGSOLO || pSoldier->aiData.bAttitude == BRAVESOLO ) ) { INT8 action = AI_ACTION_SEEK_NOISE; INT16 dist = PythSpacesAway ( pSoldier->sGridNo, sNoiseGridNo ); if ( dist > MIN_FLANK_DIST_YELLOW && dist < MAX_FLANK_DIST_YELLOW ) { INT16 rdm = Random(6); switch (rdm) { case 1: case 2: case 3: if ( pSoldier->aiData.bLastAction != AI_ACTION_FLANK_LEFT && pSoldier->aiData.bLastAction != AI_ACTION_FLANK_RIGHT ) action = AI_ACTION_FLANK_LEFT ; break; default: if ( pSoldier->aiData.bLastAction != AI_ACTION_FLANK_LEFT && pSoldier->aiData.bLastAction != AI_ACTION_FLANK_RIGHT ) action = AI_ACTION_FLANK_RIGHT ; break; } } else return AI_ACTION_SEEK_NOISE ; pSoldier->aiData.usActionData = FindFlankingSpot (pSoldier, sNoiseGridNo, action ); if (TileIsOutOfBounds(pSoldier->aiData.usActionData) || pSoldier->numFlanks >= MAX_FLANKS_YELLOW ) { pSoldier->aiData.usActionData = GoAsFarAsPossibleTowards(pSoldier,sNoiseGridNo,AI_ACTION_SEEK_NOISE); //pSoldier->numFlanks = 0; return(AI_ACTION_SEEK_NOISE); } else { if ( action == AI_ACTION_FLANK_LEFT ) pSoldier->flags.lastFlankLeft = TRUE; else pSoldier->flags.lastFlankLeft = FALSE; if ( pSoldier->lastFlankSpot != sNoiseGridNo) pSoldier->numFlanks = 0; pSoldier->origDir = GetDirectionFromGridNo ( sNoiseGridNo, pSoldier); pSoldier->lastFlankSpot = sNoiseGridNo; pSoldier->numFlanks++; return(action); } } else { return(AI_ACTION_SEEK_NOISE); } } } } //////////////////////////////////////////////////////////////////////////// // SEEK FRIEND WHO LAST RADIOED IN TO REPORT NOISE //////////////////////////////////////////////////////////////////////////// sClosestFriend = ClosestReachableFriendInTrouble(pSoldier, &fClimb); // if there is a friend alive & reachable who last radioed in if (!TileIsOutOfBounds(sClosestFriend)) { // there a chance enemy soldier choose to go "help" his friend iChance = 50 - SpacesAway(pSoldier->sGridNo,sClosestFriend); iSneaky = 10; // set base chance according to orders switch (pSoldier->aiData.bOrders) { case STATIONARY: iChance += -20; break; case ONGUARD: iChance += -15; break; case ONCALL: iChance += 20; break; case CLOSEPATROL: iChance += -10; break; case RNDPTPATROL: case POINTPATROL: iChance += -10; break; case FARPATROL: break; case SEEKENEMY: iChance += 10; break; case SNIPER: iChance += -10; break; } // modify chance of patrol (and whether it's a sneaky one) by attitude switch (pSoldier->aiData.bAttitude) { case DEFENSIVE: iChance += -10; iSneaky += 15; break; case BRAVESOLO: break; case BRAVEAID: iChance += 20; iSneaky += -10; break; case CUNNINGSOLO: iSneaky += 30; break; case CUNNINGAID: iChance += 20; iSneaky += 20; break; case AGGRESSIVE: iChance += -20; iSneaky += -20; break; case ATTACKSLAYONLY: iChance += -20; iSneaky += -20; break; } // reduce chance if breath is down, less likely to wander around when tired iChance -= (100 - pSoldier->bBreath); if ((INT16)PreRandom(100) < iChance) { pSoldier->aiData.usActionData = GoAsFarAsPossibleTowards(pSoldier,sClosestFriend,AI_ACTION_SEEK_FRIEND); if (!TileIsOutOfBounds(pSoldier->aiData.usActionData)) { #ifdef DEBUGDECISIONS sprintf(tempstr,"%s - SEEKING FRIEND at %d, MOVING to %d", pSoldier->name,sClosestFriend,pSoldier->aiData.usActionData); AIPopMessage(tempstr); #endif if ( fClimb )//&& pSoldier->aiData.usActionData == sClosestFriend) { // need to climb AND have enough APs to get there this turn BOOLEAN fUp = TRUE; if (pSoldier->pathing.bLevel > 0 ) fUp = FALSE; if (!fUp) DebugMsg ( TOPIC_JA2AI , DBG_LEVEL_3 , String("Soldier %d is climbing down",pSoldier->ubID) ); // 0verhaul: Closest Friend call also returns the climb point if climbing is necessary. So don't // climb the wrong building and don't search again //if ( CanClimbFromHere ( pSoldier, fUp ) ) if (pSoldier->sGridNo == sClosestFriend) { if (IsActionAffordable(pSoldier) ) { return( AI_ACTION_CLIMB_ROOF ); } } else { //pSoldier->aiData.usActionData = FindClosestClimbPoint(pSoldier, pSoldier->sGridNo , sClosestFriend , fUp ); pSoldier->aiData.usActionData = sClosestFriend; //if (!TileIsOutOfBounds(pSoldier->aiData.usActionData)) { return( AI_ACTION_MOVE_TO_CLIMB ); } } } //if (fClimb && pSoldier->aiData.usActionData == sClosestFriend) //{ //// need to climb AND have enough APs to get there this turn //return( AI_ACTION_CLIMB_ROOF ); //} return(AI_ACTION_SEEK_FRIEND); } } } //////////////////////////////////////////////////////////////////////////// // TAKE BEST NEARBY COVER FROM THE NOISE GENERATING GRIDNO //////////////////////////////////////////////////////////////////////////// if (!SkipCoverCheck ) // && gfTurnBasedAI) // only do in turnbased { // remember that noise value is negative, and closer to 0 => more important! iChance = 25; iSneaky = 30; // set base chance according to orders switch (pSoldier->aiData.bOrders) { case STATIONARY: iChance += 20; break; case ONGUARD: iChance += 15; break; case ONCALL: break; case CLOSEPATROL: iChance += 10; break; case RNDPTPATROL: case POINTPATROL: break; case FARPATROL: iChance += -5; break; case SEEKENEMY: iChance += -20; break; case SNIPER: iChance += 20; break; } // modify chance (and whether it's sneaky) by attitude switch (pSoldier->aiData.bAttitude) { case DEFENSIVE: iChance += 10; iSneaky += 15; break; case BRAVESOLO: iChance += -15; iSneaky += -20; break; case BRAVEAID: iChance += -20; iSneaky += -20; break; case CUNNINGSOLO: iChance += 20; iSneaky += 30; break; case CUNNINGAID: iChance += 15; iSneaky += 30; break; case AGGRESSIVE: iChance += -10; iSneaky += -10; break; case ATTACKSLAYONLY: iChance += -10; iSneaky += -10; break; } //Madd: make militia more likely to take cover if ( pSoldier->bTeam == MILITIA_TEAM ) iChance += 20; // reduce chance if breath is down, less likely to wander around when tired iChance -= (100 - pSoldier->bBreath); if ((INT16)PreRandom(100) < iChance) { pSoldier->aiData.bAIMorale = CalcMorale( pSoldier ); pSoldier->aiData.usActionData = FindBestNearbyCover(pSoldier,pSoldier->aiData.bAIMorale,&iDummy); if (!TileIsOutOfBounds(pSoldier->aiData.usActionData)) { #ifdef DEBUGDECISIONS sprintf(tempstr,"%s - TAKING COVER at grid %d",pSoldier->name,pSoldier->aiData.usActionData); AIPopMessage(tempstr); #endif return(AI_ACTION_TAKE_COVER); } } } } //////////////////////////////////////////////////////////////////////////// // SWITCH TO GREEN: determine if soldier acts as if nothing at all was wrong //////////////////////////////////////////////////////////////////////////// if ((INT16)PreRandom(100) < 50 ) { #ifdef RECORDNET fprintf(NetDebugFile,"\tDecideActionYellow: guynum %d ignores noise, switching to GREEN AI...\n",pSoldier->ubID); #endif #ifdef DEBUGDECISIONS AINameMessage(pSoldier,"ignores noise completely and BYPASSES to GREEN!",1000); #endif // Skip YELLOW until new situation, 15% extra chance to do GREEN actions pSoldier->aiData.bBypassToGreen = 15; return(DecideActionGreen(pSoldier)); } //////////////////////////////////////////////////////////////////////////// // CROUCH IF NOT CROUCHING ALREADY //////////////////////////////////////////////////////////////////////////// // if not in water and not already crouched, try to crouch down first if (!fCivilian && !PTR_CROUCHED && IsValidStance( pSoldier, ANIM_CROUCH ) ) { #ifdef DEBUGDECISIONS sprintf(tempstr,"%s CROUCHES (STATUS YELLOW)",pSoldier->name); AIPopMessage(tempstr); #endif if (!gfTurnBasedAI || GetAPsToChangeStance( pSoldier, ANIM_CROUCH ) <= pSoldier->bActionPoints) { //////////////////////////////////////////////////////////////////////////// // SANDRO - raise weapon maybe if (!(WeaponReady(pSoldier)) && pSoldier->ubDirection == ubNoiseDir) // if we are facing the direction of where the noise came from { if (!gfTurnBasedAI || (GetAPsToReadyWeapon( pSoldier, ANIM_CROUCH ) + GetAPsToChangeStance( pSoldier, ANIM_CROUCH )) <= pSoldier->bActionPoints) { iChance = 20; if ( (UsingNewCTHSystem() == false && IsScoped(&pSoldier->inv[HANDPOS])) || (UsingNewCTHSystem() == true && NCTHIsScoped(&pSoldier->inv[HANDPOS])) ) { iChance += 30; } if ( Random(100) < (UINT32)iChance ) { pSoldier->aiData.bNextAction = AI_ACTION_RAISE_GUN; } } } //////////////////////////////////////////////////////////////////////////// pSoldier->aiData.usActionData = ANIM_CROUCH; return(AI_ACTION_CHANGE_STANCE); } } else if (!fCivilian) { //////////////////////////////////////////////////////////////////////////// // SANDRO - raise weapon maybe if (!(WeaponReady(pSoldier)) && pSoldier->ubDirection == ubNoiseDir) // if we are facing the direction of where the noise came from { if (!gfTurnBasedAI || GetAPsToReadyWeapon( pSoldier, pSoldier->usAnimState ) <= pSoldier->bActionPoints) { iChance = 20; if ( (UsingNewCTHSystem() == false && IsScoped(&pSoldier->inv[HANDPOS])) || (UsingNewCTHSystem() == true && NCTHIsScoped(&pSoldier->inv[HANDPOS])) ) { iChance += 30; } if ( Random(100) < (UINT32)iChance ) { return( AI_ACTION_RAISE_GUN ); } } } //////////////////////////////////////////////////////////////////////////// } //////////////////////////////////////////////////////////////////////////// // DO NOTHING: Not enough points left to move, so save them for next turn //////////////////////////////////////////////////////////////////////////// #ifdef DEBUGDECISIONS AINameMessage(pSoldier,"- DOES NOTHING (YELLOW)",1000); #endif // by default, if everything else fails, just stands in place without turning pSoldier->aiData.usActionData = NOWHERE; return(AI_ACTION_NONE); } INT8 DecideActionRed(SOLDIERTYPE *pSoldier, UINT8 ubUnconsciousOK) { INT8 bActionReturned; INT32 iDummy; INT32 iChance,sClosestOpponent,sClosestFriend; INT32 sClosestDisturbance, sDistVisible, sCheckGridNo; UINT8 ubCanMove,ubOpponentDir; INT8 bInWater, bInDeepWater, bInGas; INT8 bSeekPts = 0, bHelpPts = 0, bHidePts = 0, bWatchPts = 0; INT8 bHighestWatchLoc; ATTACKTYPE BestThrow, BestShot; #ifdef AI_TIMING_TEST UINT32 uiStartTime, uiEndTime; #endif #ifdef DEBUGDECISIONS STR16 tempstr; #endif BOOLEAN fClimb; BOOLEAN fCivilian = (PTR_CIVILIAN && (pSoldier->ubCivilianGroup == NON_CIV_GROUP || (pSoldier->aiData.bNeutral && gTacticalStatus.fCivGroupHostile[pSoldier->ubCivilianGroup] == CIV_GROUP_NEUTRAL) || (pSoldier->ubBodyType >= FATCIV && pSoldier->ubBodyType <= CRIPPLECIV) ) ); // WANNE: Headrock informed me that I should remove that because it needs a lot of CPU! // HEADROCK HAM B2.7: Calculate the overall tactical situation //INT16 ubOverallTacticalSituation = AssessTacticalSituation(pSoldier->bSide); DebugMsg (TOPIC_JA2,DBG_LEVEL_3,String("DecideActionRed: soldier orders = %d",pSoldier->aiData.bOrders)); // if we have absolutely no action points, we can't do a thing under RED! if (!pSoldier->bActionPoints) { pSoldier->aiData.usActionData = NOWHERE; return(AI_ACTION_NONE); } // can this guy move to any of the neighbouring squares ? (sets TRUE/FALSE) ubCanMove = (pSoldier->bActionPoints >= MinPtsToMove(pSoldier)); // if we're an alerted enemy, and there are panic bombs or a trigger around if ( (!PTR_CIVILIAN || pSoldier->ubProfile == WARDEN) && ( ( gTacticalStatus.Team[pSoldier->bTeam].bAwareOfOpposition || (pSoldier->ubID == gTacticalStatus.ubTheChosenOne) || (pSoldier->ubProfile == WARDEN) ) && (gTacticalStatus.fPanicFlags & (PANIC_BOMBS_HERE | PANIC_TRIGGERS_HERE ) ) ) ) { if ( pSoldier->ubProfile == WARDEN && gTacticalStatus.ubTheChosenOne == NOBODY ) { PossiblyMakeThisEnemyChosenOne( pSoldier ); } // do some special panic AI decision making bActionReturned = PanicAI(pSoldier,ubCanMove); // if we decided on an action while in there, we're done if (bActionReturned != -1) return(bActionReturned); } if ( pSoldier->ubProfile != NO_PROFILE ) { if ( (pSoldier->ubProfile == QUEEN || pSoldier->ubProfile == JOE) && ubCanMove ) { if ( gWorldSectorX == 3 && gWorldSectorY == MAP_ROW_P && gbWorldSectorZ == 0 && !gfUseAlternateQueenPosition ) { bActionReturned = HeadForTheStairCase( pSoldier ); if ( bActionReturned != AI_ACTION_NONE ) { return( bActionReturned ); } } } } // determine if we happen to be in water (in which case we're in BIG trouble!) bInWater = Water( pSoldier->sGridNo ); bInDeepWater = Water( pSoldier->sGridNo ); // check if standing in tear gas without a gas mask on bInGas = InGasOrSmoke( pSoldier, pSoldier->sGridNo ); //////////////////////////////////////////////////////////////////////////// // WHEN LEFT IN GAS, WEAR GAS MASK IF AVAILABLE AND NOT WORN //////////////////////////////////////////////////////////////////////////// if ( !bInGas && (gWorldSectorX == TIXA_SECTOR_X && gWorldSectorY == TIXA_SECTOR_Y) ) { // only chance if we happen to be caught with our gas mask off if ( PreRandom( 10 ) == 0 && WearGasMaskIfAvailable( pSoldier ) ) { // reevaluate bInGas = InGasOrSmoke( pSoldier, pSoldier->sGridNo ); } } if(WearGasMaskIfAvailable(pSoldier))//dnl ch40 200909 bInGas = InGasOrSmoke(pSoldier, pSoldier->sGridNo); //////////////////////////////////////////////////////////////////////////// // WHEN IN GAS, GO TO NEAREST REACHABLE SPOT OF UNGASSED LAND //////////////////////////////////////////////////////////////////////////// if (bInGas && ubCanMove) { pSoldier->aiData.usActionData = FindNearestUngassedLand(pSoldier); if (!TileIsOutOfBounds(pSoldier->aiData.usActionData)) { #ifdef DEBUGDECISIONS sprintf(tempstr,"%s - SEEKING NEAREST UNGASSED LAND at grid %d",pSoldier->name,pSoldier->aiData.usActionData); AIPopMessage(tempstr); #endif return(AI_ACTION_LEAVE_WATER_GAS); } } if ( fCivilian && !( pSoldier->ubBodyType == COW || pSoldier->ubBodyType == CRIPPLECIV ) && gTacticalStatus.bBoxingState == NOT_BOXING) { if ( FindAIUsableObjClass( pSoldier, IC_WEAPON ) == ITEM_NOT_FOUND ) { // cower in fear!! if ( pSoldier->flags.uiStatusFlags & SOLDIER_COWERING ) { if ( gfTurnBasedAI || gTacticalStatus.fEnemyInSector ) // battle! { // in battle! if ( pSoldier->aiData.bLastAction == AI_ACTION_COWER ) { // do nothing pSoldier->aiData.usActionData = NOWHERE; return( AI_ACTION_NONE ); } else { // set up next action to run away pSoldier->aiData.usNextActionData = FindSpotMaxDistFromOpponents( pSoldier ); if (!TileIsOutOfBounds(pSoldier->aiData.usNextActionData)) { pSoldier->aiData.bNextAction = AI_ACTION_RUN_AWAY; pSoldier->aiData.usActionData = ANIM_STAND; return( AI_ACTION_STOP_COWERING ); } else { return( AI_ACTION_NONE ); } } } else { if ( pSoldier->aiData.bNewSituation == NOT_NEW_SITUATION ) { // stop cowering, not in battle, timer expired // we have to turn off whatever is necessary to stop status red... pSoldier->aiData.bAlertStatus = STATUS_GREEN; return( AI_ACTION_STOP_COWERING ); } else { return( AI_ACTION_NONE ); } } } else { if ( gfTurnBasedAI || gTacticalStatus.fEnemyInSector ) { // battle - cower!!! pSoldier->aiData.usActionData = ANIM_CROUCH; return( AI_ACTION_COWER ); } else // not in battle, cower for a certain length of time { pSoldier->aiData.bNextAction = AI_ACTION_WAIT; pSoldier->aiData.usNextActionData = (UINT16) REALTIME_CIV_AI_DELAY; pSoldier->aiData.usActionData = ANIM_CROUCH; return( AI_ACTION_COWER ); } } } } if ( fCivilian && !( pSoldier->ubBodyType == COW || pSoldier->ubBodyType == CRIPPLECIV ) ) { if ( FindAIUsableObjClass( pSoldier, IC_WEAPON ) == ITEM_NOT_FOUND ) { // cower in fear!! if ( pSoldier->flags.uiStatusFlags & SOLDIER_COWERING ) { if ( gfTurnBasedAI || gTacticalStatus.fEnemyInSector ) // battle! { // in battle! if ( pSoldier->aiData.bLastAction == AI_ACTION_COWER ) { // do nothing pSoldier->aiData.usActionData = NOWHERE; return( AI_ACTION_NONE ); } else { // set up next action to run away pSoldier->aiData.usNextActionData = FindSpotMaxDistFromOpponents( pSoldier ); if (!TileIsOutOfBounds(pSoldier->aiData.usNextActionData)) { pSoldier->aiData.bNextAction = AI_ACTION_RUN_AWAY; pSoldier->aiData.usActionData = ANIM_STAND; return( AI_ACTION_STOP_COWERING ); } else { return( AI_ACTION_NONE ); } } } else { if ( pSoldier->aiData.bNewSituation == NOT_NEW_SITUATION ) { // stop cowering, not in battle, timer expired // we have to turn off whatever is necessary to stop status red... pSoldier->aiData.bAlertStatus = STATUS_GREEN; return( AI_ACTION_STOP_COWERING ); } else { return( AI_ACTION_NONE ); } } } else { if ( gfTurnBasedAI || gTacticalStatus.fEnemyInSector ) { // battle - cower!!! pSoldier->aiData.usActionData = ANIM_CROUCH; return( AI_ACTION_COWER ); } else // not in battle, cower for a certain length of time { pSoldier->aiData.bNextAction = AI_ACTION_WAIT; pSoldier->aiData.usNextActionData = (UINT16) REALTIME_CIV_AI_DELAY; pSoldier->aiData.usActionData = ANIM_CROUCH; return( AI_ACTION_COWER ); } } } } //////////////////////////////////////////////////////////////////////// // IF POSSIBLE, FIRE LONG RANGE WEAPONS AT TARGETS REPORTED BY RADIO //////////////////////////////////////////////////////////////////////// //if(!is_networked)//hayden //{ // can't do this in realtime, because the player could be shooting a gun or whatever at the same time! if (gfTurnBasedAI && !fCivilian && !bInWater && !bInGas && !(pSoldier->flags.uiStatusFlags & SOLDIER_BOXER) && (CanNPCAttack(pSoldier) == TRUE)) { BestThrow.ubPossible = FALSE; // by default, assume Throwing isn't possible CheckIfTossPossible(pSoldier,&BestThrow); if (BestThrow.ubPossible) { // if firing mortar make sure we have room //if ( Item[pSoldier->inv[ BestThrow.bWeaponIn ].usItem].mortar ) //comm by ddd if (Item[pSoldier->inv[ BestThrow.bWeaponIn ].usItem].mortar || Item[pSoldier->inv[ BestThrow.bWeaponIn ].usItem].grenadelauncher || Item[pSoldier->inv[ BestThrow.bWeaponIn ].usItem].flare ) { ubOpponentDir = GetDirectionFromGridNo( BestThrow.sTarget, pSoldier ); // Get new gridno! sCheckGridNo = NewGridNo( pSoldier->sGridNo, DirectionInc( ubOpponentDir ) ); if ( OKFallDirection( pSoldier, sCheckGridNo, pSoldier->pathing.bLevel, ubOpponentDir, pSoldier->usAnimState ) ) { // then do it! The functions have already made sure that we have a // pair of worthy opponents, etc., so we're not just wasting our time // if necessary, swap the usItem from holster into the hand position DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionred: if necessary, swap the usItem from holster into the hand position"); if (BestThrow.bWeaponIn != HANDPOS) RearrangePocket(pSoldier,HANDPOS,BestThrow.bWeaponIn,FOREVER); pSoldier->aiData.usActionData = BestThrow.sTarget; //POSSIBLE STRUCTURE CHANGE PROBLEM, NOT CURRENTLY CHANGED. GOTTHARD 7/14/08 pSoldier->aiData.bAimTime = BestThrow.ubAimTime; return(AI_ACTION_TOSS_PROJECTILE); } else { // can't fire! BestThrow.ubPossible = FALSE; // try behind us, see if there's room to move back sCheckGridNo = NewGridNo( pSoldier->sGridNo, DirectionInc( gOppositeDirection[ ubOpponentDir ] ) ); if ( OKFallDirection( pSoldier, sCheckGridNo, pSoldier->pathing.bLevel, gOppositeDirection[ ubOpponentDir ], pSoldier->usAnimState ) ) { pSoldier->aiData.usActionData = sCheckGridNo; return( AI_ACTION_GET_CLOSER ); } } } } else // toss/throw/launch not possible { // WDS - Fix problem when there is no "best thrown" weapon (i.e., BestThrow.bWeaponIn == NO_SLOT) // if this dude has a longe-range weapon on him (longer than normal // sight range), and there's at least one other team-mate around, and // spotters haven't already been called for, then DO SO! if ( (BestThrow.bWeaponIn != NO_SLOT) && (CalcMaxTossRange( pSoldier, pSoldier->inv[BestThrow.bWeaponIn].usItem, TRUE ) > MaxNormalDistanceVisible() ) && (gTacticalStatus.Team[pSoldier->bTeam].bMenInSector > 1) && (gTacticalStatus.ubSpottersCalledForBy == NOBODY)) { // then call for spotters! Uses up the rest of his turn (whatever // that may be), but from now on, BLACK AI NPC may radio sightings! gTacticalStatus.ubSpottersCalledForBy = pSoldier->ubID; // HEADROCK HAM 3.1: This may be causing problems with HAM's lowered AP limit. From now on, we'll check // whether the soldier has more than 0 APs to begin with. if (pSoldier->bActionPoints > 0) pSoldier->bActionPoints = 0; #ifdef DEBUGDECISIONS AINameMessage(pSoldier,"calls for spotters!",1000); #endif pSoldier->aiData.usActionData = NOWHERE; return(AI_ACTION_NONE); } } //}//hayden // SNIPER! CheckIfShotPossible(pSoldier,&BestShot,FALSE); DebugMsg (TOPIC_JA2,DBG_LEVEL_3,String("decideactionred: is sniper shot possible? = %d, CTH = %d",BestShot.ubPossible,BestShot.ubChanceToReallyHit)); if (BestShot.ubPossible && BestShot.ubChanceToReallyHit > 50 ) { // then do it! The functions have already made sure that we have a // pair of worthy opponents, etc., so we're not just wasting our time // if necessary, swap the usItem from holster into the hand position DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionred: sniper shot possible!"); if (BestShot.bWeaponIn != HANDPOS) RearrangePocket(pSoldier,HANDPOS,BestShot.bWeaponIn,FOREVER); pSoldier->aiData.usActionData = BestShot.sTarget; //POSSIBLE STRUCTURE CHANGE PROBLEM. GOTTHARD 7/14/08 pSoldier->aiData.bAimTime = BestShot.ubAimTime; ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_INTERFACE, New113Message[ MSG113_SNIPER ] ); return(AI_ACTION_FIRE_GUN ); } else // snipe not possible { // if this dude has a longe-range weapon on him (longer than normal // sight range), and there's at least one other team-mate around, and // spotters haven't already been called for, then DO SO! DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionred: sniper shot not possible"); DebugMsg (TOPIC_JA2,DBG_LEVEL_3,String("decideactionred: weapon in slot #%d",BestShot.bWeaponIn)); // WDS - Fix problem when there is no "best shot" weapon (i.e., BestShot.bWeaponIn == NO_SLOT) if (BestShot.bWeaponIn != NO_SLOT) { OBJECTTYPE * gun = &pSoldier->inv[BestShot.bWeaponIn]; DebugMsg (TOPIC_JA2,DBG_LEVEL_3,String("decideactionred: men in sector %d, ubspotters called by %d, nobody %d",gTacticalStatus.Team[pSoldier->bTeam].bMenInSector,gTacticalStatus.ubSpottersCalledForBy,NOBODY )); //if ( ( ( IsScoped(gun) && GunRange(gun) > pSoldier->GetMaxDistanceVisible(BestShot.sTarget, BestShot.bTargetLevel) ) || pSoldier->aiData.bOrders == SNIPER ) && if ( ( ( IsScoped(gun) && GunRange(gun, pSoldier) > MaxNormalDistanceVisible() ) || pSoldier->aiData.bOrders == SNIPER ) && // SANDRO - added argument (gTacticalStatus.Team[pSoldier->bTeam].bMenInSector > 1) && (gTacticalStatus.ubSpottersCalledForBy == NOBODY)) { // then call for spotters! Uses up the rest of his turn (whatever // that may be), but from now on, BLACK AI NPC may radio sightings! gTacticalStatus.ubSpottersCalledForBy = pSoldier->ubID; // HEADROCK HAM 3.1: This may be causing problems with HAM's lowered AP limit. From now on, we'll check // whether the soldier has more than 0 APs to begin with. if (pSoldier->bActionPoints > 0) pSoldier->bActionPoints = 0; DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionred: calling for sniper spotters"); pSoldier->aiData.usActionData = NOWHERE; return(AI_ACTION_NONE); } } } //SUPPRESSION FIRE CheckIfShotPossible(pSoldier,&BestShot,TRUE); //must have a small chance to hit and the opponent must be on the ground (can't suppress guys on the roof) // HEADROCK HAM BETA2.4: Adjusted this for a random chance to suppress regardless of chance. This augments // current revamp of suppression fire. BOOLEAN fEnableAIAutofire = FALSE; // CHRISL: Changed from a simple flag to two externalized values for more modder control over AI suppression if ( BestShot.bWeaponIn != -1 && (GetMagSize(&pSoldier->inv[BestShot.bWeaponIn]) >= gGameExternalOptions.ubAISuppressionMinimumMagSize && pSoldier->inv[BestShot.bWeaponIn][0]->data.gun.ubGunShotsLeft >= gGameExternalOptions.ubAISuppressionMinimumAmmo) && ( ( BestShot.ubPossible && BestShot.ubChanceToReallyHit < 50 ) || (BestShot.ubPossible && BestShot.ubChanceToReallyHit < (INT16)PreRandom(100)) && Menptr[BestShot.ubOpponent].pathing.bLevel == 0 && pSoldier->aiData.bOrders != SNIPER )) fEnableAIAutofire = TRUE; if (fEnableAIAutofire) { // then do it! // if necessary, swap the usItem from holster into the hand position DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionred: suppression fire possible!"); if (BestShot.bWeaponIn != HANDPOS) RearrangePocket(pSoldier,HANDPOS,BestShot.bWeaponIn,FOREVER); pSoldier->aiData.usActionData = BestShot.sTarget; //pSoldier->aiData.bAimTime = BestShot.ubAimTime; INT16 ubBurstAPs = 0; FLOAT dTotalRecoil = 0; pSoldier->bDoAutofire = 0; if(UsingNewCTHSystem() == true){ do { INT8 bRecoilX = 0; INT8 bRecoilY = 0; pSoldier->bDoAutofire++; dTotalRecoil += AICalcRecoilForShot( pSoldier, &(pSoldier->inv[BestShot.bWeaponIn]), pSoldier->bDoAutofire ); ubBurstAPs = CalcAPsToAutofire( pSoldier->CalcActionPoints(), &(pSoldier->inv[BestShot.bWeaponIn]), pSoldier->bDoAutofire ); } while( pSoldier->bActionPoints >= BestShot.ubAPCost + ubBurstAPs && pSoldier->inv[ pSoldier->ubAttackingHand ][0]->data.gun.ubGunShotsLeft >= pSoldier->bDoAutofire && dTotalRecoil <= 10.0f ); } else { do { pSoldier->bDoAutofire++; ubBurstAPs = CalcAPsToAutofire( pSoldier->CalcActionPoints(), &(pSoldier->inv[BestShot.bWeaponIn]), pSoldier->bDoAutofire ); } while( pSoldier->bActionPoints >= BestShot.ubAPCost + ubBurstAPs && pSoldier->inv[ pSoldier->ubAttackingHand ][0]->data.gun.ubGunShotsLeft >= pSoldier->bDoAutofire && GetAutoPenalty(&pSoldier->inv[ pSoldier->ubAttackingHand ], gAnimControl[ pSoldier->usAnimState ].ubEndHeight == ANIM_PRONE)*pSoldier->bDoAutofire <= 80 ); } pSoldier->bDoAutofire--; // Make sure we decided to fire at least one shot! ubBurstAPs = CalcAPsToAutofire( pSoldier->CalcActionPoints(), &(pSoldier->inv[BestShot.bWeaponIn]), pSoldier->bDoAutofire ); // minimum 10 bullets // Hmmm, automatic suppression? Howcome we don't get this? if (pSoldier->bDoAutofire >= 10 && pSoldier->bActionPoints >= BestShot.ubAPCost + ubBurstAPs ) { pSoldier->aiData.bAimTime = 0; pSoldier->bDoBurst = 1; ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_INTERFACE, New113Message[ MSG113_SUPPRESSIONFIRE ] ); // HEADROCK HAM 4: This is the stupidest thing ever. // Menptr[BestShot.ubOpponent].ubSuppressionPoints += pSoldier->bDoAutofire; Menptr[BestShot.ubOpponent].ubSuppressorID = pSoldier->ubID; return( AI_ACTION_FIRE_GUN ); } else { pSoldier->aiData.bAimTime = 0; pSoldier->bDoBurst = 0; pSoldier->bDoAutofire = 0; // not enough aps - do somthing else } } // suppression not possible, do something else } /* // CALL IN AIR STRIKE & RADIO RED ALERT if ( !fCivilian && pSoldier->bTeam != MILITIA_TEAM && gGameOptions.fAirStrikes && airstrikeavailable && (pSoldier->bActionPoints >= APBPConstants[AP_RADIO]) && !WillAirRaidBeStopped(pSoldier->sSectorX,pSoldier->sSectorY)) { DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionred: checking to call in an air strike"); iChance = Random(50); // if I ain't swimming (deep water) if ( !bInDeepWater ) { // modify base chance according to orders switch (pSoldier->aiData.bOrders) { case STATIONARY: iChance += 20; break; case ONGUARD: iChance += 15; break; case ONCALL: iChance += 10; break; case CLOSEPATROL: break; case RNDPTPATROL: case POINTPATROL: iChance += -5; break; case FARPATROL: iChance += -10; break; case SEEKENEMY: iChance += -20; break; } // modify base chance according to attitude switch (pSoldier->aiData.bAttitude) { case DEFENSIVE: iChance += 20; break; case BRAVESOLO: iChance += -10; break; case BRAVEAID: break; case CUNNINGSOLO: iChance += -5; break; case CUNNINGAID: break; case AGGRESSIVE: iChance += -20; break; case ATTACKSLAYONLY: iChance = 0; } // modify base chance according to morale switch (pSoldier->aiData.bAIMorale) { case MORALE_HOPELESS: iChance *= 3; break; case MORALE_WORRIED: iChance *= 2; break; case MORALE_NORMAL: break; case MORALE_CONFIDENT: iChance /= 2; break; case MORALE_FEARLESS: iChance /= 3; break; } if ((INT16) Random(100) < iChance) { DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionred: decided to call in an air strike!"); SayQuoteFromAnyBodyInSector( QUOTE_WEARY_SLASH_SUSPUCIOUS ); EnemyCallInAirStrike ( pSoldier->sSectorX, pSoldier->sSectorY ); airstrikeavailable = FALSE; return(AI_ACTION_RED_ALERT); } } } */ //////////////////////////////////////////////////////////////////////////// // WHEN IN THE LIGHT, GET OUT OF THERE! //////////////////////////////////////////////////////////////////////////// if ( ubCanMove && InLightAtNight( pSoldier->sGridNo, pSoldier->pathing.bLevel ) && pSoldier->aiData.bOrders != STATIONARY ) { //ddd чтобы убегали, когда подсветят фальшвейером ночью if(gGameExternalOptions.bNewTacticalAIBehavior) pSoldier->aiData.bAction = AI_ACTION_LEAVE_WATER_GAS; //ddd pSoldier->aiData.usActionData = FindNearbyDarkerSpot( pSoldier ); if (!TileIsOutOfBounds(pSoldier->aiData.usActionData)) { // move as if leaving water or gas return( AI_ACTION_LEAVE_WATER_GAS ); } } DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionred: crouch and rest if running out of breath"); //////////////////////////////////////////////////////////////////////// // CROUCH & REST IF RUNNING OUT OF BREATH //////////////////////////////////////////////////////////////////////// // if our breath is running a bit low, and we're not in water or under fire if ((pSoldier->bBreath < 25) && !bInWater && !pSoldier->aiData.bUnderFire) { // if not already crouched, try to crouch down first if (!fCivilian && !PTR_CROUCHED && IsValidStance( pSoldier, ANIM_CROUCH ) && gAnimControl[ pSoldier->usAnimState ].ubHeight != ANIM_PRONE) { #ifdef DEBUGDECISIONS sprintf(tempstr,"%s CROUCHES, NEEDING REST (STATUS RED), breath = %d",pSoldier->name,pSoldier->bBreath); AIPopMessage(tempstr); #endif if (!gfTurnBasedAI || GetAPsToChangeStance( pSoldier, ANIM_CROUCH ) <= pSoldier->bActionPoints) { pSoldier->aiData.usActionData = ANIM_CROUCH; return(AI_ACTION_CHANGE_STANCE); } } #ifdef DEBUGDECISIONS sprintf(tempstr,"%s RESTS (STATUS RED), breath = %d",pSoldier->name,pSoldier->bBreath); AIPopMessage(tempstr); #endif pSoldier->aiData.usActionData = NOWHERE; return(AI_ACTION_NONE); } DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionred: calculate morale"); // calculate our morale pSoldier->aiData.bAIMorale = CalcMorale(pSoldier); // WDS DEBUG - this will make all enemies run away (to test retreating into occupied sector bugs) // pSoldier->aiData.bAIMorale = MORALE_HOPELESS; // if a guy is feeling REALLY discouraged, he may continue to run like hell if ((pSoldier->aiData.bAIMorale == MORALE_HOPELESS) && ubCanMove) { DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionred: run away"); //////////////////////////////////////////////////////////////////////// // RUN AWAY TO SPOT FARTHEST FROM KNOWN THREATS (ONLY IF MORALE HOPELESS) //////////////////////////////////////////////////////////////////////// // look for best place to RUN AWAY to (farthest from the closest threat) pSoldier->aiData.usActionData = FindSpotMaxDistFromOpponents(pSoldier); if (!TileIsOutOfBounds(pSoldier->aiData.usActionData)) { #ifdef DEBUGDECISIONS sprintf(tempstr,"%s RUNNING AWAY to grid %d",pSoldier->name,pSoldier->aiData.usActionData); AIPopMessage(tempstr); #endif return(AI_ACTION_RUN_AWAY); } } DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionred: radio red alert?"); //////////////////////////////////////////////////////////////////////////// // RADIO RED ALERT: determine %chance to call others and report contact //////////////////////////////////////////////////////////////////////////// // if we're a computer merc, and we have the action points remaining to RADIO // (we never want NPCs to choose to radio if they would have to wait a turn) if ( !fCivilian && (pSoldier->bActionPoints >= APBPConstants[AP_RADIO]) && (gTacticalStatus.Team[pSoldier->bTeam].bMenInSector > 1) ) { DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionred: checking to radio red alert"); // if there hasn't been an initial RED ALERT yet in this sector if ( !(gTacticalStatus.Team[pSoldier->bTeam].bAwareOfOpposition) || NeedToRadioAboutPanicTrigger() ) // since I'm at STATUS RED, I obviously know we're being invaded! iChance = gbDiff[DIFF_RADIO_RED_ALERT][ SoldierDifficultyLevel( pSoldier ) ]; else // subsequent radioing (only to update enemy positions, request help) // base chance depends on how much new info we have to radio to the others iChance = 10 * WhatIKnowThatPublicDont(pSoldier,FALSE); // use 10 * for RED alert // if I actually know something they don't and I ain't swimming (deep water) if (iChance && !bInDeepWater) { // modify base chance according to orders switch (pSoldier->aiData.bOrders) { case STATIONARY: iChance += 20; break; case ONGUARD: iChance += 15; break; case ONCALL: iChance += 10; break; case CLOSEPATROL: break; case RNDPTPATROL: case POINTPATROL: iChance += -5; break; case FARPATROL: iChance += -10; break; case SEEKENEMY: iChance += -20; break; case SNIPER: iChance += -10; break; // Sniper contacts should be reported automatically } // modify base chance according to attitude switch (pSoldier->aiData.bAttitude) { case DEFENSIVE: iChance += 20; break; case BRAVESOLO: iChance += -10; break; case BRAVEAID: break; case CUNNINGSOLO: iChance += -5; break; case CUNNINGAID: break; case AGGRESSIVE: iChance += -20; break; case ATTACKSLAYONLY: iChance = 0; } if ( (gTacticalStatus.fPanicFlags & PANIC_TRIGGERS_HERE) && !gTacticalStatus.Team[pSoldier->bTeam].bAwareOfOpposition) { // ignore morale (which could be really high } else { // modify base chance according to morale switch (pSoldier->aiData.bAIMorale) { case MORALE_HOPELESS: iChance *= 3; break; case MORALE_WORRIED: iChance *= 2; break; case MORALE_NORMAL: break; case MORALE_CONFIDENT: iChance /= 2; break; case MORALE_FEARLESS: iChance /= 3; break; } } #ifdef DEBUGDECISIONS AINumMessage("Chance to radio RED alert = ",iChance); #endif if ((INT16) PreRandom(100) < iChance) { #ifdef DEBUGDECISIONS AINameMessage(pSoldier,"decides to radio a RED alert!",1000); #endif DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionred: decided to radio red alert"); return(AI_ACTION_RED_ALERT); } } } if ( !TANK( pSoldier ) ) { DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionred: main red ai"); //////////////////////////////////////////////////////////////////////////// // MAIN RED AI: Decide soldier's preference between SEEKING,HELPING & HIDING //////////////////////////////////////////////////////////////////////////// // get the location of the closest reachable opponent sClosestDisturbance = ClosestReachableDisturbance(pSoldier,ubUnconsciousOK, &fClimb); DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionred: check to continue flanking"); // continue flanking INT32 tempGridNo; if (TileIsOutOfBounds(sClosestDisturbance)) tempGridNo = pSoldier->lastFlankSpot; else tempGridNo = sClosestDisturbance; if ( pSoldier->numFlanks > 0 && pSoldier->numFlanks < MAX_FLANKS_RED && gAnimControl[ pSoldier->usAnimState ].ubHeight != ANIM_PRONE ) { DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionred: continue flanking"); INT16 currDir = GetDirectionFromGridNo ( tempGridNo, pSoldier ); INT16 origDir = pSoldier->origDir; pSoldier->numFlanks += 1; if ( pSoldier->flags.lastFlankLeft ) { if ( origDir > currDir ) origDir -= 8; if ( (currDir - origDir) >= 4 ) { pSoldier->numFlanks = MAX_FLANKS_RED; } else { pSoldier->aiData.usActionData = FindFlankingSpot (pSoldier, tempGridNo , AI_ACTION_FLANK_LEFT); if (!TileIsOutOfBounds(pSoldier->aiData.usActionData) ) //&& (currDir - origDir) < 2 ) return AI_ACTION_FLANK_LEFT ; else pSoldier->numFlanks = MAX_FLANKS_RED; } } else { if ( origDir < currDir ) origDir += 8; if ( (origDir - currDir) >= 4 ) { pSoldier->numFlanks = MAX_FLANKS_RED; } else { pSoldier->aiData.usActionData = FindFlankingSpot (pSoldier, tempGridNo , AI_ACTION_FLANK_RIGHT); if (!TileIsOutOfBounds(pSoldier->aiData.usActionData) )//&& (origDir - currDir) < 2 ) return AI_ACTION_FLANK_RIGHT ; else pSoldier->numFlanks = MAX_FLANKS_RED; } } } if ( pSoldier->numFlanks == MAX_FLANKS_RED ) { pSoldier->numFlanks += 1; DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionred: stop flanking"); if (PythSpacesAway ( pSoldier->sGridNo, tempGridNo ) > MIN_FLANK_DIST_RED * 2 ) { pSoldier->aiData.usActionData = InternalGoAsFarAsPossibleTowards(pSoldier,tempGridNo,GetAPsProne( pSoldier, TRUE),AI_ACTION_SEEK_OPPONENT,0); if ( LocationToLocationLineOfSightTest( pSoldier->aiData.usActionData, pSoldier->pathing.bLevel, tempGridNo, pSoldier->pathing.bLevel, TRUE) ) { // reserve APs for a possible crouch plus a shot pSoldier->aiData.usActionData = InternalGoAsFarAsPossibleTowards(pSoldier, tempGridNo, (INT8) (MinAPsToAttack( pSoldier, tempGridNo, ADDTURNCOST) + GetAPsCrouch( pSoldier, TRUE)), AI_ACTION_SEEK_OPPONENT, FLAG_CAUTIOUS ); if (!TileIsOutOfBounds(pSoldier->aiData.usActionData)) { pSoldier->aiData.fAIFlags |= AI_CAUTIOUS; pSoldier->aiData.bNextAction = AI_ACTION_END_TURN; return(AI_ACTION_SEEK_OPPONENT); } } else { return(AI_ACTION_SEEK_OPPONENT); } } else { pSoldier->aiData.usActionData = FindBestNearbyCover(pSoldier,pSoldier->aiData.bAIMorale,&iDummy); return AI_ACTION_TAKE_COVER ; } } // if we can move at least 1 square's worth // and have more APs than we want to reserve DebugMsg (TOPIC_JA2,DBG_LEVEL_3,String("decideactionred: can we move? = %d, APs = %d",ubCanMove,pSoldier->bActionPoints)); if (ubCanMove && pSoldier->bActionPoints > APBPConstants[MAX_AP_CARRIED]) { if (fCivilian) { // only interested in hiding out... bSeekPts = -99; bHelpPts = -99; bHidePts = +1; } else { DebugMsg (TOPIC_JA2,DBG_LEVEL_3,String("decideactionred: checking hide/seek/help/watch points... orders = %d, attitude = %d",pSoldier->aiData.bOrders,pSoldier->aiData.bAttitude)); // calculate initial points for watch based on highest watch loc bWatchPts = GetHighestWatchedLocPoints( pSoldier->ubID ); if ( bWatchPts <= 0 ) { // no watching bWatchPts = -99; } // modify RED movement tendencies according to morale switch (pSoldier->aiData.bAIMorale) { case MORALE_HOPELESS: bSeekPts = -99; bHelpPts = -99; bHidePts = +2; bWatchPts = -99; break; case MORALE_WORRIED: bSeekPts += -2; bHelpPts += 0; bHidePts += +2; bWatchPts += 1; break; case MORALE_NORMAL: bSeekPts += 0; bHelpPts += 0; bHidePts += 0; bWatchPts += 0; break; case MORALE_CONFIDENT: bSeekPts += +1; bHelpPts += 0; bHidePts += -1; bWatchPts += 0; break; case MORALE_FEARLESS: bSeekPts += +1; bHelpPts += 0; bHidePts = -1; bWatchPts += 0; break; } // modify tendencies according to orders switch (pSoldier->aiData.bOrders) { case STATIONARY: bSeekPts += -1; bHelpPts += -1; bHidePts += +1; bWatchPts += +1; break; case ONGUARD: bSeekPts += -1; bHelpPts += 0; bHidePts += +1; bWatchPts += +1; break; case CLOSEPATROL: bSeekPts += 0; bHelpPts += 0; bHidePts += 0; bWatchPts += 0; break; case RNDPTPATROL: bSeekPts += 0; bHelpPts += 0; bHidePts += 0; bWatchPts += 0; break; case POINTPATROL: bSeekPts += 0; bHelpPts += 0; bHidePts += 0; bWatchPts += 0; break; case FARPATROL: bSeekPts += 0; bHelpPts += 0; bHidePts += 0; bWatchPts += 0; break; case ONCALL: bSeekPts += 0; bHelpPts += +1; bHidePts += -1; bWatchPts += 0; break; case SEEKENEMY: bSeekPts += +1; bHelpPts += 0; bHidePts += -1; bWatchPts += -1; break; case SNIPER: bSeekPts += -1; bHelpPts += 0; bHidePts += +1; bWatchPts += +1; break; } // modify tendencies according to attitude switch (pSoldier->aiData.bAttitude) { case DEFENSIVE: bSeekPts += -1; bHelpPts += 0; bHidePts += +2; bWatchPts += +1; break; case BRAVESOLO: bSeekPts += +1; bHelpPts += -1; bHidePts += -1; bWatchPts += -1; break; case BRAVEAID: bSeekPts += +1; bHelpPts += +1; bHidePts += -1; bWatchPts += -1; break; case CUNNINGSOLO: bSeekPts += 1; bHelpPts += -1; bHidePts += +1; bWatchPts += 0; break; case CUNNINGAID: bSeekPts += 1; bHelpPts += +1; bHidePts += +1; bWatchPts += 0; break; case AGGRESSIVE: bSeekPts += +1; bHelpPts += 0; bHidePts += -1; bWatchPts += 0; break; case ATTACKSLAYONLY:bSeekPts += +1; bHelpPts += 0; bHidePts += -1; bWatchPts += 0; break; } //Madd: make militia less likely to go running headlong into trouble if ( pSoldier->bTeam == MILITIA_TEAM ) { bSeekPts += -1; bHelpPts += 0; bHidePts += +1; bWatchPts += +0; } } if (!gfTurnBasedAI) { // don't search for cover bHidePts = -99; } DebugMsg (TOPIC_JA2,DBG_LEVEL_3,String("decideactionred: hide = %d, seek = %d, watch = %d, help = %d",bHidePts,bSeekPts,bWatchPts,bHelpPts)); // while one of the three main RED REACTIONS remains viable while ((bSeekPts > -90) || (bHelpPts > -90) || (bHidePts > -90) ) { DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionred: checking to seek"); // if SEEKING is possible and at least as desirable as helping or hiding if ( ((bSeekPts > -90) && (bSeekPts >= bHelpPts) && (bSeekPts >= bHidePts) && (bSeekPts >= bWatchPts )) ) { #ifdef AI_TIMING_TESTS uiStartTime = GetJA2Clock(); #endif #ifdef AI_TIMING_TESTS uiEndTime = GetJA2Clock(); guiRedSeekTimeTotal += (uiEndTime - uiStartTime); guiRedSeekCounter++; #endif // if there is an opponent reachable if (!TileIsOutOfBounds(sClosestDisturbance) && gAnimControl[ pSoldier->usAnimState ].ubHeight != ANIM_PRONE ) { DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionred: seek opponent"); ////////////////////////////////////////////////////////////////////// // SEEK CLOSEST DISTURBANCE: GO DIRECTLY TOWARDS CLOSEST KNOWN OPPONENT ////////////////////////////////////////////////////////////////////// // try to move towards him pSoldier->aiData.usActionData = InternalGoAsFarAsPossibleTowards(pSoldier,sClosestDisturbance,GetAPsCrouch( pSoldier, TRUE),AI_ACTION_SEEK_OPPONENT,0); if (!TileIsOutOfBounds(pSoldier->aiData.usActionData)) { // Check for a trap if ( !ArmySeesOpponents() ) { if ( GetNearestRottingCorpseAIWarning( pSoldier->aiData.usActionData ) > 0 ) { // abort! abort! pSoldier->aiData.usActionData = NOWHERE; } } } // if it's possible if (!TileIsOutOfBounds(pSoldier->aiData.usActionData)) { #ifdef DEBUGDECISIONS // do it! sprintf(tempstr,"%s - SEEKING OPPONENT at grid %d, MOVING to %d", pSoldier->name,sClosestDisturbance,pSoldier->aiData.usActionData); AIPopMessage(tempstr); #endif if (fClimb)//&& pSoldier->aiData.usActionData == sClosestDisturbance) { // need to climb AND have enough APs to get there this turn BOOLEAN fUp = TRUE; if (pSoldier->pathing.bLevel > 0 ) fUp = FALSE; if (!fUp) DebugMsg ( TOPIC_JA2AI , DBG_LEVEL_3 , String("Soldier %d is climbing down",pSoldier->ubID) ); // As mentioned in the next part, the sClosestDisturbance IS the climb point desired. So the // check here should be "Am I aready there?" If so, THEN possibly climb. This previous check // would have a soldier climbing any building, even if it was not the desired building. So // WRONG WRONG WRONG //if ( CanClimbFromHere ( pSoldier, fUp ) ) if (pSoldier->sGridNo == sClosestDisturbance) { if (IsActionAffordable(pSoldier) && pSoldier->bActionPoints >= ( APBPConstants[AP_CLIMBROOF] + MinAPsToAttack( pSoldier, sClosestDisturbance, ADDTURNCOST))) { return( AI_ACTION_CLIMB_ROOF ); } } else { // Do not overwrite the usActionData here. If there's no nearby climb point, the action data // would become NOWHERE, and then the SEEK_ENEMY fallback would also fail. // In fact, sClosestDisturbance has ALREADY calculated the closest climb point when climbing is // necessary. The returned grid # in sClosestDisturbance is that climb point. So if climb is // set, then use sClosestDisturbance as is. //INT16 usClimbPoint = FindClosestClimbPoint(pSoldier, pSoldier->sGridNo , sClosestDisturbance , fUp ); INT32 usClimbPoint = sClosestDisturbance; if (!TileIsOutOfBounds(usClimbPoint)) { pSoldier->aiData.usActionData = usClimbPoint; return( AI_ACTION_MOVE_TO_CLIMB ); } } } //if ( fClimb && pSoldier->aiData.usActionData == sClosestDisturbance) //{ // return( AI_ACTION_CLIMB_ROOF ); //} if ( ( pSoldier->aiData.bAttitude == CUNNINGAID || pSoldier->aiData.bAttitude == CUNNINGSOLO || pSoldier->aiData.bAttitude == BRAVESOLO ) && gAnimControl[ pSoldier->usAnimState ].ubHeight != ANIM_PRONE ) { INT8 action = AI_ACTION_SEEK_OPPONENT; INT16 dist = PythSpacesAway ( pSoldier->sGridNo, sClosestDisturbance ); if ( dist > MIN_FLANK_DIST_RED && dist < MAX_FLANK_DIST_RED ) { INT16 rdm = Random(6); switch (rdm) { case 1: case 2: case 3: if ( pSoldier->aiData.bLastAction != AI_ACTION_FLANK_LEFT && pSoldier->aiData.bLastAction != AI_ACTION_FLANK_RIGHT ) action = AI_ACTION_FLANK_LEFT ; break; default: if ( pSoldier->aiData.bLastAction != AI_ACTION_FLANK_LEFT && pSoldier->aiData.bLastAction != AI_ACTION_FLANK_RIGHT ) action = AI_ACTION_FLANK_RIGHT ; break; } if (action == AI_ACTION_SEEK_OPPONENT) { return action; } } else return AI_ACTION_SEEK_OPPONENT ; pSoldier->aiData.usActionData = FindFlankingSpot (pSoldier, sClosestDisturbance, action ); if (TileIsOutOfBounds(pSoldier->aiData.usActionData) || pSoldier->numFlanks >= MAX_FLANKS_RED ) { pSoldier->aiData.usActionData = InternalGoAsFarAsPossibleTowards(pSoldier,sClosestDisturbance,GetAPsCrouch( pSoldier, TRUE), AI_ACTION_SEEK_OPPONENT,0); //pSoldier->numFlanks = 0; if ( PythSpacesAway( pSoldier->aiData.usActionData, sClosestDisturbance ) < 5 || LocationToLocationLineOfSightTest( pSoldier->aiData.usActionData, pSoldier->pathing.bLevel, sClosestDisturbance, pSoldier->pathing.bLevel, TRUE ) ) { // reserve APs for a possible crouch plus a shot pSoldier->aiData.usActionData = InternalGoAsFarAsPossibleTowards(pSoldier, sClosestDisturbance, (INT8) (MinAPsToAttack( pSoldier, sClosestDisturbance, ADDTURNCOST) + GetAPsCrouch( pSoldier, TRUE)), AI_ACTION_SEEK_OPPONENT, FLAG_CAUTIOUS ); if (!TileIsOutOfBounds(pSoldier->aiData.usActionData)) { pSoldier->aiData.fAIFlags |= AI_CAUTIOUS; pSoldier->aiData.bNextAction = AI_ACTION_END_TURN; return(AI_ACTION_SEEK_OPPONENT); } } else { return(AI_ACTION_SEEK_OPPONENT); } } else { if ( action == AI_ACTION_FLANK_LEFT ) pSoldier->flags.lastFlankLeft = TRUE; else pSoldier->flags.lastFlankLeft = FALSE; if ( pSoldier->lastFlankSpot != sClosestDisturbance) pSoldier->numFlanks=0; pSoldier->origDir = GetDirectionFromGridNo ( sClosestDisturbance, pSoldier); pSoldier->lastFlankSpot = sClosestDisturbance; pSoldier->numFlanks++; return(action); } } else { // let's be a bit cautious about going right up to a location without enough APs to shoot if ( PythSpacesAway( pSoldier->aiData.usActionData, sClosestDisturbance ) < 5 || LocationToLocationLineOfSightTest( pSoldier->aiData.usActionData, pSoldier->pathing.bLevel, sClosestDisturbance, pSoldier->pathing.bLevel, TRUE ) ) { // reserve APs for a possible crouch plus a shot pSoldier->aiData.usActionData = InternalGoAsFarAsPossibleTowards(pSoldier, sClosestDisturbance, (INT8) (MinAPsToAttack( pSoldier, sClosestDisturbance, ADDTURNCOST) + GetAPsCrouch( pSoldier, TRUE)), AI_ACTION_SEEK_OPPONENT, FLAG_CAUTIOUS ); if (!TileIsOutOfBounds(pSoldier->aiData.usActionData)) { pSoldier->aiData.fAIFlags |= AI_CAUTIOUS; pSoldier->aiData.bNextAction = AI_ACTION_END_TURN; return(AI_ACTION_SEEK_OPPONENT); } } else { return(AI_ACTION_SEEK_OPPONENT); } break; } } } // mark SEEKING as impossible for next time through while loop #ifdef DEBUGDECISIONS AINameMessage(pSoldier,"couldn't SEEK...",1000); #endif bSeekPts = -99; DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionred: couldn't seek"); } DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionred: checking to watch"); // if WATCHING is possible and at least as desirable as anything else if ((bWatchPts > -90) && (bWatchPts >= bSeekPts) && (bWatchPts >= bHelpPts) && (bWatchPts >= bHidePts )) { // take a look at our highest watch point... if it's still visible, turn to face it and then wait bHighestWatchLoc = GetHighestVisibleWatchedLoc( pSoldier->ubID ); //sDistVisible = DistanceVisible( pSoldier, DIRECTION_IRRELEVANT, DIRECTION_IRRELEVANT, gsWatchedLoc[ pSoldier->ubID ][ bHighestWatchLoc ] ); if ( bHighestWatchLoc != -1 ) { // see if we need turn to face that location ubOpponentDir = atan8( CenterX(pSoldier->sGridNo),CenterY(pSoldier->sGridNo),CenterX( gsWatchedLoc[ pSoldier->ubID ][ bHighestWatchLoc ] ),CenterY( gsWatchedLoc[ pSoldier->ubID ][ bHighestWatchLoc ] ) ); // if soldier is not already facing in that direction, // and the opponent is close enough that he could possibly be seen if ( pSoldier->ubDirection != ubOpponentDir && pSoldier->InternalIsValidStance( ubOpponentDir, gAnimControl[ pSoldier->usAnimState ].ubEndHeight ) ) { // turn pSoldier->aiData.usActionData = ubOpponentDir; pSoldier->aiData.bNextAction = AI_ACTION_END_TURN; return(AI_ACTION_CHANGE_FACING); } else { // consider at least crouching if ( gAnimControl[ pSoldier->usAnimState ].ubEndHeight == ANIM_STAND && pSoldier->InternalIsValidStance( ubOpponentDir, ANIM_CROUCH ) ) { pSoldier->aiData.usActionData = ANIM_CROUCH; pSoldier->aiData.bNextAction = AI_ACTION_END_TURN; return(AI_ACTION_CHANGE_STANCE); } else if ( gAnimControl[ pSoldier->usAnimState ].ubHeight != ANIM_PRONE ) { // maybe go prone if ( PreRandom( 2 ) == 0 && pSoldier->InternalIsValidStance( ubOpponentDir, ANIM_PRONE ) ) { pSoldier->aiData.usActionData = ANIM_PRONE; pSoldier->aiData.bNextAction = AI_ACTION_END_TURN; return( AI_ACTION_CHANGE_STANCE ); } // end turn return( AI_ACTION_END_TURN ); } } } bWatchPts = -99; DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionred: couldn't watch"); } DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionred: checking to help"); // if HELPING is possible and at least as desirable as seeking or hiding if ((bHelpPts > -90) && (bHelpPts >= bSeekPts) && (bHelpPts >= bHidePts) && (bHelpPts >= bWatchPts )) { #ifdef AI_TIMING_TESTS uiStartTime = GetJA2Clock(); #endif sClosestFriend = ClosestReachableFriendInTrouble(pSoldier, &fClimb ); #ifdef AI_TIMING_TESTS uiEndTime = GetJA2Clock(); guiRedHelpTimeTotal += (uiEndTime - uiStartTime); guiRedHelpCounter++; #endif if (!TileIsOutOfBounds(sClosestFriend)) { ////////////////////////////////////////////////////////////////////// // GO DIRECTLY TOWARDS CLOSEST FRIEND UNDER FIRE OR WHO LAST RADIOED ////////////////////////////////////////////////////////////////////// pSoldier->aiData.usActionData = InternalGoAsFarAsPossibleTowards(pSoldier,sClosestFriend,GetAPsCrouch( pSoldier, TRUE), AI_ACTION_SEEK_OPPONENT,0); if (!TileIsOutOfBounds(pSoldier->aiData.usActionData)) { #ifdef DEBUGDECISIONS sprintf(tempstr,"%s - SEEKING FRIEND at %d, MOVING to %d", pSoldier->name,sClosestFriend,pSoldier->aiData.usActionData); AIPopMessage(tempstr); #endif if ( fClimb )//&& pSoldier->aiData.usActionData == sClosestFriend) { // need to climb AND have enough APs to get there this turn BOOLEAN fUp = TRUE; if (pSoldier->pathing.bLevel > 0 ) fUp = FALSE; if (!fUp) DebugMsg ( TOPIC_JA2AI , DBG_LEVEL_3 , String("Soldier %d is climbing down",pSoldier->ubID) ); // 0verhaul: Yet another chance to climb the wrong building and otherwise waste CPU power. // We already know the climb point we want, which may not be here even if climbing is possible. //if ( CanClimbFromHere ( pSoldier, fUp ) ) if (pSoldier->sGridNo == sClosestFriend) { if (IsActionAffordable(pSoldier) && pSoldier->bActionPoints >= ( APBPConstants[AP_CLIMBROOF] + MinAPsToAttack( pSoldier, sClosestFriend, ADDTURNCOST))) { return( AI_ACTION_CLIMB_ROOF ); } } else { pSoldier->aiData.usActionData = sClosestFriend; //INT32 sClimbPoint = FindClosestClimbPoint(pSoldier, pSoldier->sGridNo , sClosestFriend , fUp ); //if (!TileIsOutOfBounds(sClimbPoint)) { //pSoldier->aiData.usActionData = sClimbPoint; return( AI_ACTION_MOVE_TO_CLIMB ); } } } //if (fClimb && pSoldier->aiData.usActionData == sClosestFriend) //{ // return( AI_ACTION_CLIMB_ROOF ); //} return(AI_ACTION_SEEK_FRIEND); } } // mark SEEKING as impossible for next time through while loop #ifdef DEBUGDECISIONS AINameMessage(pSoldier,"couldn't HELP...",1000); #endif DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionred: couldn't help"); bHelpPts = -99; } DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionred: checking to hide"); // if HIDING is possible and at least as desirable as seeking or helping if ((bHidePts > -90) && (bHidePts >= bSeekPts) && (bHidePts >= bHelpPts) && (bHidePts >= bWatchPts )) { sClosestOpponent = ClosestKnownOpponent( pSoldier, NULL, NULL ); // if an opponent is known (not necessarily reachable or conscious) if (!SkipCoverCheck && !TileIsOutOfBounds(sClosestOpponent)) { ////////////////////////////////////////////////////////////////////// // TAKE BEST NEARBY COVER FROM ALL KNOWN OPPONENTS ////////////////////////////////////////////////////////////////////// #ifdef AI_TIMING_TESTS uiStartTime = GetJA2Clock(); #endif pSoldier->aiData.usActionData = FindBestNearbyCover(pSoldier,pSoldier->aiData.bAIMorale,&iDummy); #ifdef AI_TIMING_TESTS uiEndTime = GetJA2Clock(); guiRedHideTimeTotal += (uiEndTime - uiStartTime); guiRedHideCounter++; #endif // let's be a bit cautious about going right up to a location without enough APs to shoot if (!TileIsOutOfBounds(pSoldier->aiData.usActionData)) { sClosestDisturbance = ClosestReachableDisturbance(pSoldier, ubUnconsciousOK, &fClimb); if (!TileIsOutOfBounds(sClosestDisturbance) && ( SpacesAway( pSoldier->aiData.usActionData, sClosestDisturbance ) < 5 || SpacesAway( pSoldier->aiData.usActionData, sClosestDisturbance ) + 5 < SpacesAway( pSoldier->sGridNo, sClosestDisturbance ) ) ) { // either moving significantly closer or into very close range // ensure will we have enough APs for a possible crouch plus a shot if ( InternalGoAsFarAsPossibleTowards( pSoldier, pSoldier->aiData.usActionData, (INT8) (MinAPsToAttack( pSoldier, sClosestOpponent, ADDTURNCOST) + GetAPsCrouch( pSoldier, TRUE)), AI_ACTION_TAKE_COVER, 0 ) == pSoldier->aiData.usActionData ) { return(AI_ACTION_TAKE_COVER); } } else { return(AI_ACTION_TAKE_COVER); } } } // mark HIDING as impossible for next time through while loop #ifdef DEBUGDECISIONS AINameMessage(pSoldier,"couldn't HIDE...",1000); #endif bHidePts = -99; DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionred: couldn't hide"); } } } DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionred: nothing to do!"); //////////////////////////////////////////////////////////////////////////// // NOTHING USEFUL POSSIBLE! IF NPC IS CURRENTLY UNDER FIRE, TRY TO RUN AWAY //////////////////////////////////////////////////////////////////////////// // if we're currently under fire (presumably, attacker is hidden) if (pSoldier->aiData.bUnderFire || fCivilian) { // only try to run if we've actually been hit recently & noticably so // otherwise, presumably our current cover is pretty good & sufficient // HEADROCK HAM B2.6: New value here helps us change the ratio of running away due to shock. This // is terribly important if Suppression Shock is enabled. UINT16 bShock = 0; if (gGameExternalOptions.usSuppressionShockEffect > 0 ) { // If bShock value is greater than (2*ExpLevel + MoraleModifier)*1.5, the target will flee. bShock = pSoldier->aiData.bShock; if (bShock <= ((float)CalcSuppressionTolerance(pSoldier)*(float)1.5)) bShock = 0; } else { bShock = pSoldier->aiData.bShock; } if (bShock > 0 || fCivilian) { // look for best place to RUN AWAY to (farthest from the closest threat) pSoldier->aiData.usActionData = FindSpotMaxDistFromOpponents(pSoldier); if (!TileIsOutOfBounds(pSoldier->aiData.usActionData)) { #ifdef DEBUGDECISIONS sprintf(tempstr,"%s RUNNING AWAY to grid %d",pSoldier->name,pSoldier->aiData.usActionData); AIPopMessage(tempstr); #endif DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionred: run away!"); return(AI_ACTION_RUN_AWAY); } } //////////////////////////////////////////////////////////////////////////// // UNDER FIRE, DON'T WANNA/CAN'T RUN AWAY, SO CROUCH //////////////////////////////////////////////////////////////////////////// DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionred: crouch or go prone"); // if not in water and not already crouched if (!fCivilian ) { if ( gAnimControl[ pSoldier->usAnimState ].ubHeight == ANIM_STAND && IsValidStance( pSoldier, ANIM_CROUCH ) ) { if (!gfTurnBasedAI || GetAPsToChangeStance( pSoldier, ANIM_CROUCH ) <= pSoldier->bActionPoints) { #ifdef DEBUGDECISIONS sprintf(tempstr,"%s CROUCHES (STATUS RED)",pSoldier->name); AIPopMessage(tempstr); #endif pSoldier->aiData.usActionData = ANIM_CROUCH; return(AI_ACTION_CHANGE_STANCE); } } else if ( gAnimControl[ pSoldier->usAnimState ].ubHeight != ANIM_PRONE ) { // maybe go prone if ( PreRandom( 2 ) == 0 && IsValidStance( pSoldier, ANIM_PRONE ) ) { pSoldier->aiData.usActionData = ANIM_PRONE; return( AI_ACTION_CHANGE_STANCE ); } } } } } DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionred: look around towards opponent"); //////////////////////////////////////////////////////////////////////////// // LOOK AROUND TOWARD CLOSEST KNOWN OPPONENT, IF KNOWN //////////////////////////////////////////////////////////////////////////// if (!gfTurnBasedAI || GetAPsToLook( pSoldier ) <= pSoldier->bActionPoints) { // determine the location of the known closest opponent // (don't care if he's conscious, don't care if he's reachable at all) sClosestOpponent = ClosestKnownOpponent(pSoldier, NULL, NULL); if (!TileIsOutOfBounds(sClosestOpponent)) { // determine direction from this soldier to the closest opponent ubOpponentDir = atan8(CenterX(pSoldier->sGridNo),CenterY(pSoldier->sGridNo),CenterX(sClosestOpponent),CenterY(sClosestOpponent)); // if soldier is not already facing in that direction, // and the opponent is close enough that he could possibly be seen // note, have to change this to use the level returned from ClosestKnownOpponent sDistVisible = pSoldier->GetMaxDistanceVisible(sClosestOpponent, 0, CALC_FROM_ALL_DIRS ); if ((pSoldier->ubDirection != ubOpponentDir) && (PythSpacesAway(pSoldier->sGridNo,sClosestOpponent) <= sDistVisible)) { // set base chance according to orders if ((pSoldier->aiData.bOrders == STATIONARY) || (pSoldier->aiData.bOrders == ONGUARD)) iChance = 50; else // all other orders iChance = 25; if (pSoldier->aiData.bAttitude == DEFENSIVE) iChance += 25; if ( TANK( pSoldier ) ) { iChance += 50; } if ((INT16)PreRandom(100) < iChance && pSoldier->InternalIsValidStance( ubOpponentDir, gAnimControl[ pSoldier->usAnimState ].ubEndHeight ) ) { pSoldier->aiData.usActionData = ubOpponentDir; #ifdef DEBUGDECISIONS sprintf(tempstr,"%s - TURNS TOWARDS CLOSEST ENEMY to face direction %d",pSoldier->name,pSoldier->aiData.usActionData); AIPopMessage(tempstr); #endif if ( pSoldier->aiData.bOrders == SNIPER && !(WeaponReady(pSoldier)) ) { if (!gfTurnBasedAI || GetAPsToReadyWeapon( pSoldier, READY_RIFLE_CROUCH ) <= pSoldier->bActionPoints) { pSoldier->aiData.bNextAction = AI_ACTION_RAISE_GUN; } } //////////////////////////////////////////////////////////////////////////// // SANDRO - allow regular soldiers to raise scoped weapons to see rather away too else if ( (UsingNewCTHSystem() == false && IsScoped(&pSoldier->inv[HANDPOS])) || (UsingNewCTHSystem() == true && NCTHIsScoped(&pSoldier->inv[HANDPOS])) ) { if (!(WeaponReady(pSoldier))) { if (!gfTurnBasedAI || GetAPsToReadyWeapon( pSoldier, READY_RIFLE_CROUCH ) <= pSoldier->bActionPoints) { if ( Random(100) < 35 ) { pSoldier->aiData.bNextAction = AI_ACTION_RAISE_GUN; } } } } //////////////////////////////////////////////////////////////////////////// return(AI_ACTION_CHANGE_FACING); } } //////////////////////////////////////////////////////////////////////////// // SANDRO - allow regular soldiers to raise scoped weapons to see rather away too else if ( pSoldier->ubDirection == ubOpponentDir && !(WeaponReady(pSoldier))) { if (!gfTurnBasedAI || GetAPsToReadyWeapon( pSoldier, pSoldier->usAnimState ) <= pSoldier->bActionPoints) { if ( pSoldier->aiData.bOrders == SNIPER ) { return AI_ACTION_RAISE_GUN; } else if ( (UsingNewCTHSystem() == false && IsScoped(&pSoldier->inv[HANDPOS])) || (UsingNewCTHSystem() == true && NCTHIsScoped(&pSoldier->inv[HANDPOS])) ) { if ( Random(100) < 40 ) { return AI_ACTION_RAISE_GUN; } } else { if ( Random(100) < 20 ) { return AI_ACTION_RAISE_GUN; } } } } //////////////////////////////////////////////////////////////////////////// } } if ( TANK( pSoldier ) ) { // try turning in a random direction as we still can't see anyone. if (!gfTurnBasedAI || GetAPsToLook( pSoldier ) <= pSoldier->bActionPoints) { sClosestDisturbance = MostImportantNoiseHeard( pSoldier, NULL, NULL, NULL ); if (!TileIsOutOfBounds(sClosestDisturbance)) { ubOpponentDir = atan8( CenterX( pSoldier->sGridNo ), CenterY( pSoldier->sGridNo ), CenterX( sClosestDisturbance ), CenterY( sClosestDisturbance ) ); if ( pSoldier->ubDirection == ubOpponentDir ) { ubOpponentDir = (UINT8) PreRandom( NUM_WORLD_DIRECTIONS ); } } else { ubOpponentDir = (UINT8) PreRandom( NUM_WORLD_DIRECTIONS ); } if ( (pSoldier->ubDirection != ubOpponentDir) ) { if ( (pSoldier->bActionPoints == pSoldier->bInitialActionPoints || (INT16)PreRandom(100) < 60) && pSoldier->InternalIsValidStance( ubOpponentDir, gAnimControl[ pSoldier->usAnimState ].ubEndHeight ) ) { pSoldier->aiData.usActionData = ubOpponentDir; #ifdef DEBUGDECISIONS sprintf(tempstr,"%s - TURNS TOWARDS CLOSEST ENEMY to face direction %d",pSoldier->name,pSoldier->aiData.usActionData); AIPopMessage(tempstr); #endif // limit turning a bit... if the last thing we did was also a turn, add a 60% chance of this being our last turn if ( pSoldier->aiData.bLastAction == AI_ACTION_CHANGE_FACING && PreRandom( 100 ) < 60 ) { if ( gfTurnBasedAI ) { pSoldier->aiData.bNextAction = AI_ACTION_END_TURN; } else { pSoldier->aiData.bNextAction = AI_ACTION_WAIT; pSoldier->aiData.usNextActionData = (UINT16) REALTIME_AI_DELAY; } } return(AI_ACTION_CHANGE_FACING); } } } // that's it for tanks return( AI_ACTION_NONE ); } //////////////////////////////////////////////////////////////////////////// // LEAVE THE SECTOR //////////////////////////////////////////////////////////////////////////// // NOT IMPLEMENTED //////////////////////////////////////////////////////////////////////////// // PICKUP A NEARBY ITEM THAT'S USEFUL //////////////////////////////////////////////////////////////////////////// if ( ubCanMove && !pSoldier->aiData.bNeutral && (gfTurnBasedAI || pSoldier->bTeam == ENEMY_TEAM ) ) { pSoldier->aiData.bAction = SearchForItems( pSoldier, SEARCH_GENERAL_ITEMS, pSoldier->inv[HANDPOS].usItem ); if (pSoldier->aiData.bAction != AI_ACTION_NONE) { return( pSoldier->aiData.bAction ); } } //////////////////////////////////////////////////////////////////////////// // SEEK CLOSEST FRIENDLY MEDIC //////////////////////////////////////////////////////////////////////////// // NOT IMPLEMENTED //////////////////////////////////////////////////////////////////////////// // GIVE FIRST AID TO A NEARBY INJURED/DYING FRIEND //////////////////////////////////////////////////////////////////////////// // - must be BRAVEAID or CUNNINGAID (medic) ? // NOT IMPLEMENTED /* JULY 29, 1996 - Decided that this was a bad idea, after watching a civilian start a random patrol while 2 steps away from a hidden armed opponent...*/ //////////////////////////////////////////////////////////////////////////// // SWITCH TO GREEN: soldier does ordinary regular patrol, seeks friends //////////////////////////////////////////////////////////////////////////// // if not in combat or under fire, and we COULD have moved, just chose not to if ( (pSoldier->aiData.bAlertStatus != STATUS_BLACK) && !pSoldier->aiData.bUnderFire && ubCanMove && (!gfTurnBasedAI || pSoldier->bActionPoints >= pSoldier->bInitialActionPoints) && ( TileIsOutOfBounds(ClosestReachableDisturbance(pSoldier, TRUE, &fClimb))) ) { // addition: if soldier is bleeding then reduce bleeding and do nothing if ( pSoldier->bBleeding > MIN_BLEEDING_THRESHOLD ) { // reduce bleeding by 1 point per AP (in RT, APs will get recalculated so it's okay) pSoldier->bBleeding = __max( 0, pSoldier->bBleeding - (pSoldier->bActionPoints/2) ); return( AI_ACTION_NONE ); // will end-turn/wait depending on whether we're in TB or realtime } #ifdef RECORDNET fprintf(NetDebugFile,"\tDecideActionRed: guynum %d switching to GREEN AI...\n",pSoldier->ubID); #endif #ifdef DEBUGDECISIONS AINameMessage(pSoldier,"- chose to SKIP all RED actions, BYPASSES to GREEN!",1000); #endif // Skip RED until new situation/next turn, 30% extra chance to do GREEN actions pSoldier->aiData.bBypassToGreen = 30; return(DecideActionGreen(pSoldier)); } //////////////////////////////////////////////////////////////////////////// // CROUCH IF NOT CROUCHING ALREADY //////////////////////////////////////////////////////////////////////////// // if not in water and not already crouched, try to crouch down first if (!fCivilian && !bInWater && (gAnimControl[ pSoldier->usAnimState ].ubHeight == ANIM_STAND) && IsValidStance( pSoldier, ANIM_CROUCH ) ) { sClosestOpponent = ClosestKnownOpponent(pSoldier, NULL, NULL); //if ( ( !TileIsOutOfBounds(sClosestOpponent) && PythSpacesAway( pSoldier->sGridNo, sClosestOpponent ) < (MaxNormalDistanceVisible() * 3) / 2 ) || PreRandom( 4 ) == 0 ) if ( (!TileIsOutOfBounds(sClosestOpponent) && PythSpacesAway( pSoldier->sGridNo, sClosestOpponent ) < (pSoldier->GetMaxDistanceVisible(sClosestOpponent) * 3) / 2 ) || PreRandom( 4 ) == 0 ) { if (!gfTurnBasedAI || GetAPsToChangeStance( pSoldier, ANIM_CROUCH ) <= pSoldier->bActionPoints) { #ifdef DEBUGDECISIONS sprintf(tempstr,"%s CROUCHES (STATUS RED)",pSoldier->name ); AIPopMessage(tempstr); #endif //////////////////////////////////////////////////////////////////////////// // SANDRO - allow regular soldiers to raise scoped weapons to see rather away too if (!gfTurnBasedAI || (GetAPsToReadyWeapon( pSoldier, READY_RIFLE_CROUCH ) + GetAPsToChangeStance( pSoldier, ANIM_CROUCH )) <= pSoldier->bActionPoints) { // determine direction from this soldier to the closest opponent ubOpponentDir = atan8(CenterX(pSoldier->sGridNo),CenterY(pSoldier->sGridNo),CenterX(sClosestOpponent),CenterY(sClosestOpponent)); if (!(WeaponReady(pSoldier)) && pSoldier->ubDirection == ubOpponentDir ) { iChance = 25; if ( (UsingNewCTHSystem() == false && IsScoped(&pSoldier->inv[HANDPOS])) || (UsingNewCTHSystem() == true && NCTHIsScoped(&pSoldier->inv[HANDPOS])) ) { iChance += 25; } if ( Random(100) < (UINT32)iChance ) { pSoldier->aiData.bNextAction = AI_ACTION_RAISE_GUN; } } } //////////////////////////////////////////////////////////////////////////// pSoldier->aiData.usActionData = ANIM_CROUCH; return(AI_ACTION_CHANGE_STANCE); } } } //////////////////////////////////////////////////////////////////////////// // IF UNDER FIRE, FACE THE MOST IMPORTANT NOISE WE KNOW AND GO PRONE //////////////////////////////////////////////////////////////////////////// if ( !fCivilian && pSoldier->aiData.bUnderFire && pSoldier->bActionPoints >= (pSoldier->bInitialActionPoints - GetAPsToLook( pSoldier ) ) && IsValidStance( pSoldier, ANIM_PRONE ) ) { sClosestDisturbance = MostImportantNoiseHeard( pSoldier, NULL, NULL, NULL ); if (!TileIsOutOfBounds(sClosestDisturbance)) { ubOpponentDir = atan8( CenterX( pSoldier->sGridNo ), CenterY( pSoldier->sGridNo ), CenterX( sClosestDisturbance ), CenterY( sClosestDisturbance ) ); if ( pSoldier->ubDirection != ubOpponentDir ) { if ( !gfTurnBasedAI || GetAPsToLook( pSoldier ) <= pSoldier->bActionPoints ) { pSoldier->aiData.usActionData = ubOpponentDir; return( AI_ACTION_CHANGE_FACING ); } } else if ( (!gfTurnBasedAI || GetAPsToChangeStance( pSoldier, ANIM_PRONE ) <= pSoldier->bActionPoints ) && pSoldier->InternalIsValidStance( ubOpponentDir, ANIM_PRONE ) ) { // go prone, end turn pSoldier->aiData.bNextAction = AI_ACTION_END_TURN; pSoldier->aiData.usActionData = ANIM_PRONE; return( AI_ACTION_CHANGE_STANCE ); } } } //////////////////////////////////////////////////////////////////////////// // If sniper and nothing else to do then raise gun, and if that doesn't find somebody then goto yellow //////////////////////////////////////////////////////////////////////////// if ( pSoldier->aiData.bOrders == SNIPER ) { if ( pSoldier->sniper == 0 ) { DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("DecideActionRed: sniper raising gun...")); if (!gfTurnBasedAI || GetAPsToReadyWeapon( pSoldier, READY_RIFLE_CROUCH ) <= pSoldier->bActionPoints) { if (!(WeaponReady(pSoldier))) { pSoldier->sniper = 1; return AI_ACTION_RAISE_GUN; } } } else { pSoldier->sniper = 0; return(DecideActionYellow(pSoldier)); } } else if (!fCivilian) { //////////////////////////////////////////////////////////////////////////// // SANDRO - raise weapon maybe if (!(WeaponReady(pSoldier))) // if we are facing the direction of where the noise came from { if (!gfTurnBasedAI || GetAPsToReadyWeapon( pSoldier, pSoldier->usAnimState ) <= pSoldier->bActionPoints) { if ( (UsingNewCTHSystem() == false && IsScoped(&pSoldier->inv[HANDPOS])) || (UsingNewCTHSystem() == true && NCTHIsScoped(&pSoldier->inv[HANDPOS])) ) { if ( Random(100) < 35 ) { return( AI_ACTION_RAISE_GUN ); } } } } //////////////////////////////////////////////////////////////////////////// } //////////////////////////////////////////////////////////////////////////// // DO NOTHING: Not enough points left to move, so save them for next turn //////////////////////////////////////////////////////////////////////////// DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("DecideActionRed: do nothing at all...")); #ifdef DEBUGDECISIONS AINameMessage(pSoldier,"- DOES NOTHING (RED)",1000); #endif pSoldier->aiData.usActionData = NOWHERE; return(AI_ACTION_NONE); } INT8 DecideActionBlack(SOLDIERTYPE *pSoldier) { INT32 iCoverPercentBetter, iOffense, iDefense, iChance; INT32 sClosestOpponent,sBestCover = NOWHERE; INT32 sClosestDisturbance; INT16 ubMinAPCost; UINT8 ubCanMove; INT8 bInWater,bInDeepWater,bInGas; INT8 bDirection; UINT8 ubBestAttackAction = AI_ACTION_NONE; INT8 bCanAttack,bActionReturned; INT8 bWeaponIn; BOOLEAN fTryPunching = FALSE; #ifdef DEBUGDECISIONS STR16 tempstr; #endif DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("DecideActionBlack: soldier = %d, orders = %d, attitude = %d",pSoldier->ubID,pSoldier->aiData.bOrders,pSoldier->aiData.bAttitude)); ATTACKTYPE BestShot = {},BestThrow = {},BestStab = {},BestAttack = {}; BOOLEAN fCivilian = (PTR_CIVILIAN && (pSoldier->ubCivilianGroup == NON_CIV_GROUP || pSoldier->aiData.bNeutral || (pSoldier->ubBodyType >= FATCIV && pSoldier->ubBodyType <= CRIPPLECIV) ) ); UINT8 ubBestStance = 1, ubStanceCost; BOOLEAN fChangeStanceFirst; // before firing BOOLEAN fClimb; INT16 ubBurstAPs; UINT8 ubOpponentDir; INT32 sCheckGridNo; BOOLEAN fAllowCoverCheck = FALSE; DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"DecideActionBlack"); // once we hit status black, reset flanking status //pSoldier->numFlanks = 0; // if we have absolutely no action points, we can't do a thing under BLACK! if (!pSoldier->bActionPoints) { pSoldier->aiData.usActionData = NOWHERE; return(AI_ACTION_NONE); } // can this guy move to any of the neighbouring squares ? (sets TRUE/FALSE) ubCanMove = (pSoldier->bActionPoints >= MinPtsToMove(pSoldier)); if ( (pSoldier->bTeam == ENEMY_TEAM || pSoldier->ubProfile == WARDEN) && (gTacticalStatus.fPanicFlags & PANIC_TRIGGERS_HERE) && (gTacticalStatus.ubTheChosenOne == NOBODY) ) { INT8 bPanicTrigger; bPanicTrigger = ClosestPanicTrigger( pSoldier ); // if it's an alarm trigger and team is alerted, ignore it if ( !(gTacticalStatus.bPanicTriggerIsAlarm[ bPanicTrigger ] && gTacticalStatus.Team[pSoldier->bTeam].bAwareOfOpposition) && PythSpacesAway( pSoldier->sGridNo, gTacticalStatus.sPanicTriggerGridNo[ bPanicTrigger ] ) < 10) { PossiblyMakeThisEnemyChosenOne( pSoldier ); } } // if this soldier is the "Chosen One" (enemies only) if (pSoldier->ubID == gTacticalStatus.ubTheChosenOne) { // do some special panic AI decision making bActionReturned = PanicAI(pSoldier,ubCanMove); // if we decided on an action while in there, we're done if (bActionReturned != -1) return(bActionReturned); } if ( pSoldier->ubProfile != NO_PROFILE ) { // if they see enemies, the Queen will keep going to the staircase, but Joe will fight if ( (pSoldier->ubProfile == QUEEN) && ubCanMove ) { if ( gWorldSectorX == 3 && gWorldSectorY == MAP_ROW_P && gbWorldSectorZ == 0 && !gfUseAlternateQueenPosition ) { bActionReturned = HeadForTheStairCase( pSoldier ); if ( bActionReturned != AI_ACTION_NONE ) { return( bActionReturned ); } } } } if ( pSoldier->flags.uiStatusFlags & SOLDIER_BOXER ) { if ( gTacticalStatus.bBoxingState == PRE_BOXING ) { return( DecideActionBoxerEnteringRing( pSoldier ) ); } else if ( gTacticalStatus.bBoxingState == BOXING ) { bInWater = FALSE; bInDeepWater = FALSE; bInGas = FALSE; // calculate our morale pSoldier->aiData.bAIMorale = CalcMorale(pSoldier); // and continue on... } else //???? { return( AI_ACTION_NONE ); } } else { // determine if we happen to be in water (in which case we're in BIG trouble!) bInWater = Water( pSoldier->sGridNo ); bInDeepWater = WaterTooDeepForAttacks( pSoldier->sGridNo ); // check if standing in tear gas without a gas mask on bInGas = InGasOrSmoke( pSoldier, pSoldier->sGridNo ); // calculate our morale pSoldier->aiData.bAIMorale = CalcMorale(pSoldier); //////////////////////////////////////////////////////////////////////////// // WHEN LEFT IN GAS, WEAR GAS MASK IF AVAILABLE AND NOT WORN //////////////////////////////////////////////////////////////////////////// if ( !bInGas && (gWorldSectorX == TIXA_SECTOR_X && gWorldSectorY == TIXA_SECTOR_Y) ) { // only chance if we happen to be caught with our gas mask off if ( PreRandom( 10 ) == 0 && WearGasMaskIfAvailable( pSoldier ) ) { bInGas = FALSE; } } if(WearGasMaskIfAvailable(pSoldier))//dnl ch40 200909 bInGas = InGasOrSmoke(pSoldier, pSoldier->sGridNo); //////////////////////////////////////////////////////////////////////////// // IF GASSED, OR REALLY TIRED (ON THE VERGE OF COLLAPSING), TRY TO RUN AWAY //////////////////////////////////////////////////////////////////////////// // if we're desperately short on breath (it's OK if we're in water, though!) if (bInGas || (pSoldier->bBreath < 5)) { // if soldier has enough APs left to move at least 1 square's worth if (ubCanMove) { // look for best place to RUN AWAY to (farthest from the closest threat) pSoldier->aiData.usActionData = FindSpotMaxDistFromOpponents(pSoldier); if (!TileIsOutOfBounds(pSoldier->aiData.usActionData)) { #ifdef DEBUGDECISIONS sprintf(tempstr,"%s - GASSED or LOW ON BREATH (%d), RUNNING AWAY to grid %d",pSoldier->name,pSoldier->bBreath,pSoldier->aiData.usActionData); AIPopMessage(tempstr); #endif return(AI_ACTION_RUN_AWAY); } } // REALLY tired, can't get away, force soldier's morale to hopeless state if ( gGameOptions.ubDifficultyLevel == DIF_LEVEL_INSANE ) { pSoldier->bBreath = pSoldier->bBreathMax; //Madd: backed into a corner, so go crazy like a wild animal... pSoldier->aiData.bAIMorale = MORALE_FEARLESS; } else pSoldier->aiData.bAIMorale = MORALE_HOPELESS; } } //////////////////////////////////////////////////////////////////////////// // STUCK IN WATER OR GAS, NO COVER, GO TO NEAREST SPOT OF UNGASSED LAND //////////////////////////////////////////////////////////////////////////// // if soldier in water/gas has enough APs left to move at least 1 square if ( ( bInDeepWater || bInGas ) && ubCanMove) { pSoldier->aiData.usActionData = FindNearestUngassedLand(pSoldier); if (!TileIsOutOfBounds(pSoldier->aiData.usActionData)) { #ifdef DEBUGDECISIONS sprintf(tempstr,"%s - SEEKING NEAREST UNGASSED LAND at grid %d",pSoldier->name,pSoldier->aiData.usActionData); AIPopMessage(tempstr); #endif return(AI_ACTION_LEAVE_WATER_GAS); } // couldn't find ANY land within 25 tiles(!), this should never happen... // look for best place to RUN AWAY to (farthest from the closest threat) pSoldier->aiData.usActionData = FindSpotMaxDistFromOpponents(pSoldier); if (!TileIsOutOfBounds(pSoldier->aiData.usActionData)) { #ifdef DEBUGDECISIONS sprintf(tempstr,"%s - NO LAND NEAR, RUNNING AWAY to grid %d",pSoldier->name,pSoldier->aiData.usActionData); AIPopMessage(tempstr); #endif return(AI_ACTION_RUN_AWAY); } // GIVE UP ON LIFE! MERCS MUST HAVE JUST CORNERED A HELPLESS ENEMY IN A // GAS FILLED ROOM (OR IN WATER MORE THAN 25 TILES FROM NEAREST LAND...) if ( bInGas && gGameOptions.ubDifficultyLevel == DIF_LEVEL_INSANE ) { pSoldier->bBreath = pSoldier->bBreathMax; pSoldier->aiData.bAIMorale = MORALE_FEARLESS; // Can't move, can't get away, go nuts instead... } else pSoldier->aiData.bAIMorale = MORALE_HOPELESS; } // offer surrender? if ( pSoldier->bTeam == ENEMY_TEAM && pSoldier->bVisible == TRUE && !( gTacticalStatus.fEnemyFlags & ENEMY_OFFERED_SURRENDER ) && pSoldier->stats.bLife >= pSoldier->stats.bLifeMax / 2 ) { if ( gTacticalStatus.Team[ MILITIA_TEAM ].bMenInSector == 0 && NumPCsInSector() < 4 && gTacticalStatus.Team[ ENEMY_TEAM ].bMenInSector >= NumPCsInSector() * 3 ) { //if( GetWorldDay() > STARTDAY_ALLOW_PLAYER_CAPTURE_FOR_RESCUE && !( gStrategicStatus.uiFlags & STRATEGIC_PLAYER_CAPTURED_FOR_RESCUE ) ) { if ( gubQuest[ QUEST_HELD_IN_ALMA ] == QUESTNOTSTARTED || ( gubQuest[ QUEST_HELD_IN_ALMA ] == QUESTDONE && gubQuest[ QUEST_INTERROGATION ] == QUESTNOTSTARTED ) ) { gTacticalStatus.fEnemyFlags |= ENEMY_OFFERED_SURRENDER; return( AI_ACTION_OFFER_SURRENDER ); } } } } //////////////////////////////////////////////////////////////////////////// // SOLDIER CAN ATTACK IF NOT IN WATER/GAS AND NOT DOING SOMETHING TOO FUNKY //////////////////////////////////////////////////////////////////////////// // NPCs in water/tear gas without masks are not permitted to shoot/stab/throw if ((pSoldier->bActionPoints < 2) || bInDeepWater || bInGas || pSoldier->aiData.bRTPCombat == RTP_COMBAT_REFRAIN) { bCanAttack = FALSE; } else if (pSoldier->flags.uiStatusFlags & SOLDIER_BOXER) { bCanAttack = TRUE; fTryPunching = TRUE; } else { do { bCanAttack = CanNPCAttack(pSoldier); if (bCanAttack != TRUE) { if (fCivilian) { if ( ( bCanAttack == NOSHOOT_NOWEAPON) && !(pSoldier->flags.uiStatusFlags & SOLDIER_BOXER) && pSoldier->ubBodyType != COW && pSoldier->ubBodyType != CRIPPLECIV ) { // cower in fear!! if ( pSoldier->flags.uiStatusFlags & SOLDIER_COWERING ) { if ( pSoldier->aiData.bLastAction == AI_ACTION_COWER ) { // do nothing pSoldier->aiData.usActionData = NOWHERE; return( AI_ACTION_NONE ); } else { // set up next action to run away pSoldier->aiData.usNextActionData = FindSpotMaxDistFromOpponents( pSoldier ); if (!TileIsOutOfBounds(pSoldier->aiData.usNextActionData)) { pSoldier->aiData.bNextAction = AI_ACTION_RUN_AWAY; pSoldier->aiData.usActionData = ANIM_STAND; return( AI_ACTION_STOP_COWERING ); } else { return( AI_ACTION_NONE ); } } } else { // cower!!! pSoldier->aiData.usActionData = ANIM_CROUCH; return( AI_ACTION_COWER ); } } } else if (bCanAttack == NOSHOOT_NOAMMO && ubCanMove && !pSoldier->aiData.bNeutral) { int handPOS; //CHRISL: We need to know which weapon has no ammo in case the soldier is holding a weapoin in SECONDHANDPOS if(pSoldier->inv[SECONDHANDPOS].exists() == true && pSoldier->inv[SECONDHANDPOS][0]->data.gun.ubGunShotsLeft == 0) handPOS = SECONDHANDPOS; else handPOS = HANDPOS; // try to find more ammo pSoldier->aiData.bAction = SearchForItems( pSoldier, SEARCH_AMMO, pSoldier->inv[handPOS].usItem ); if (pSoldier->aiData.bAction == AI_ACTION_NONE) { // the current weapon appears is useless right now! // (since we got a return code of noammo, we know the hand usItem // is our gun) pSoldier->inv[handPOS].fFlags |= OBJECT_AI_UNUSABLE; // move the gun into another pocket... if (!AutoPlaceObject( pSoldier, &(pSoldier->inv[handPOS]), FALSE ) ) { // If there's no room in his pockets for the useless gun, just throw it away return AI_ACTION_DROP_ITEM; } } else { return( pSoldier->aiData.bAction ); } } else { bCanAttack = FALSE; } } } while( bCanAttack != TRUE && bCanAttack != FALSE ); #ifdef RETREAT_TESTING bCanAttack = FALSE; #endif if (!bCanAttack) { if (pSoldier->aiData.bAIMorale > MORALE_WORRIED) { pSoldier->aiData.bAIMorale = MORALE_WORRIED; } if (!fCivilian) { // can always attack with HTH as a last resort bCanAttack = TRUE; fTryPunching = TRUE; } } } // if we don't have a gun, look around for a weapon! if (FindAIUsableObjClass( pSoldier, IC_GUN ) == ITEM_NOT_FOUND && ubCanMove && !pSoldier->aiData.bNeutral) { // look around for a gun... pSoldier->aiData.bAction = SearchForItems( pSoldier, SEARCH_WEAPONS, pSoldier->inv[HANDPOS].usItem ); if (pSoldier->aiData.bAction != AI_ACTION_NONE ) { return( pSoldier->aiData.bAction ); } } BestShot.ubPossible = FALSE; // by default, assume Shooting isn't possible BestThrow.ubPossible = FALSE; // by default, assume Throwing isn't possible BestStab.ubPossible = FALSE; // by default, assume Stabbing isn't possible BestAttack.ubChanceToReallyHit = 0; // if we are able attack if (bCanAttack) { pSoldier->bAimShotLocation = AIM_SHOT_RANDOM; ////////////////////////////////////////////////////////////////////////// // FIRE A GUN AT AN OPPONENT ////////////////////////////////////////////////////////////////////////// DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"FIRE A GUN AT AN OPPONENT"); bWeaponIn = FindAIUsableObjClass( pSoldier, IC_GUN ); if (bWeaponIn != NO_SLOT) { BestShot.bWeaponIn = bWeaponIn; // if it's in another pocket, swap it into his hand temporarily if (bWeaponIn != HANDPOS) { DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionblack: swap gun into hand"); RearrangePocket(pSoldier,HANDPOS,bWeaponIn,TEMPORARILY); } // now it better be a gun, or the guy can't shoot (but has other attack(s)) if (Item[pSoldier->inv[HANDPOS].usItem].usItemClass == IC_GUN && pSoldier->inv[HANDPOS][0]->data.gun.bGunStatus >= USABLE) { // get the minimum cost to attack the same target with this gun ubMinAPCost = MinAPsToAttack(pSoldier,pSoldier->sLastTarget,ADDTURNCOST); // if we have enough action points to shoot with this gun if (pSoldier->bActionPoints >= ubMinAPCost) { // look around for a worthy target (which sets BestShot.ubPossible) BOOLEAN shootUnseen = FALSE; ///ddd //if (gGameOptions.ubDifficultyLevel > DIF_LEVEL_MEDIUM ) //comm by ddd if (gGameOptions.ubDifficultyLevel > DIF_LEVEL_MEDIUM || gGameExternalOptions.bNewTacticalAIBehavior) shootUnseen = TRUE; CalcBestShot(pSoldier,&BestShot,shootUnseen); if (pSoldier->bTeam == gbPlayerNum && pSoldier->aiData.bRTPCombat == RTP_COMBAT_CONSERVE) { if (BestShot.ubChanceToReallyHit < 30) { // skip firing, our chance isn't good enough BestShot.ubPossible = FALSE; } } if (BestShot.ubPossible) { // if the selected opponent is not a threat (unconscious & !serviced) // (usually, this means all the guys we see are unconscious, but, on // rare occasions, we may not be able to shoot a healthy guy, too) if ((Menptr[BestShot.ubOpponent].stats.bLife < OKLIFE) && !Menptr[BestShot.ubOpponent].bService) { // if our attitude is NOT aggressive if ( pSoldier->aiData.bAttitude != AGGRESSIVE || BestShot.ubChanceToReallyHit < 60 ) { // get the location of the closest CONSCIOUS reachable opponent sClosestDisturbance = ClosestReachableDisturbance(pSoldier,FALSE, &fClimb); // if we found one if (!TileIsOutOfBounds(sClosestDisturbance)) { // don't bother checking GRENADES/KNIVES, he can't have conscious targets #ifdef RECORDNET fprintf(NetDebugFile,"\tDecideActionBlack: all visible opponents unconscious, switching to RED AI...\n"); #endif // then make decision as if at alert status RED, but make sure // we don't try to SEEK OPPONENT the unconscious guy! return(DecideActionRed(pSoldier,FALSE)); } // else kill the guy, he could be the last opponent alive in this sector } // else aggressive guys will ALWAYS finish off unconscious opponents } // now we KNOW FOR SURE that we will do something (shoot, at least) NPCDoesAct(pSoldier); DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"NPC decided to shoot (or something)"); } } // if it was in his holster, swap it back into his holster for now if (bWeaponIn != HANDPOS) { DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionblack: swap gun into holster"); RearrangePocket(pSoldier,HANDPOS,bWeaponIn,TEMPORARILY); } } } ////////////////////////////////////////////////////////////////////////// // THROW A TOSSABLE ITEM AT OPPONENT(S) // - HTH: THIS NOW INCLUDES FIRING THE GRENADE LAUNCHAR AND MORTAR! ////////////////////////////////////////////////////////////////////////// // this looks for throwables, and sets BestThrow.ubPossible if it can be done //if ( !gfHiddenInterrupt ) // { //if(!is_networked) //disable for mp ai //{ CheckIfTossPossible(pSoldier,&BestThrow); if (BestThrow.ubPossible) { DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"good throw possible"); if ( Item[pSoldier->inv[ BestThrow.bWeaponIn ].usItem].mortar ) { ubOpponentDir = (UINT8)GetDirectionFromGridNo( BestThrow.sTarget, pSoldier ); // Get new gridno! sCheckGridNo = NewGridNo( pSoldier->sGridNo, (UINT16)DirectionInc( ubOpponentDir ) ); if ( !OKFallDirection( pSoldier, sCheckGridNo, pSoldier->pathing.bLevel, ubOpponentDir, pSoldier->usAnimState ) ) { // can't fire! BestThrow.ubPossible = FALSE; // try behind us, see if there's room to move back sCheckGridNo = NewGridNo( pSoldier->sGridNo, (UINT16)DirectionInc( gOppositeDirection[ ubOpponentDir ] ) ); if ( OKFallDirection( pSoldier, sCheckGridNo, pSoldier->pathing.bLevel, gOppositeDirection[ ubOpponentDir ], pSoldier->usAnimState ) ) { pSoldier->aiData.usActionData = sCheckGridNo; return( AI_ACTION_GET_CLOSER ); } } } if ( BestThrow.ubPossible ) { // now we KNOW FOR SURE that we will do something (throw, at least) NPCDoesAct(pSoldier); } } //} //} ////////////////////////////////////////////////////////////////////////// // GO STAB AN OPPONENT WITH A KNIFE ////////////////////////////////////////////////////////////////////////// DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"GO STAB AN OPPONENT WITH A KNIFE"); // if soldier has a knife in his hand bWeaponIn = FindAIUsableObjClass( pSoldier, (IC_BLADE | IC_THROWING_KNIFE) ); // if the soldier does have a usable knife somewhere // 0verhaul: And is not a tank! if (bWeaponIn != NO_SLOT && !TANK( pSoldier)) { DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"try to stab"); BestStab.bWeaponIn = bWeaponIn; // if it's in his holster, swap it into his hand temporarily if (bWeaponIn != HANDPOS) { DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionblack: about to rearrange pocket before stab check"); RearrangePocket(pSoldier,HANDPOS,bWeaponIn,TEMPORARILY); } // get the minimum cost to attack with this knife ubMinAPCost = MinAPsToAttack(pSoldier,pSoldier->sLastTarget,DONTADDTURNCOST); // if we can afford the minimum AP cost to stab with/throw this knife weapon if (pSoldier->bActionPoints >= ubMinAPCost) { // NB throwing knife in hand now if ( Item[ pSoldier->inv[HANDPOS].usItem ].usItemClass & IC_THROWING_KNIFE ) { // throwing knife code works like shooting // look around for a worthy target (which sets BestStab.ubPossible) CalcBestShot(pSoldier,&BestStab,FALSE); if (BestStab.ubPossible) { // if the selected opponent is not a threat (unconscious & !serviced) // (usually, this means all the guys we see are unconscious, but, on // rare occasions, we may not be able to shoot a healthy guy, too) if ((Menptr[BestStab.ubOpponent].stats.bLife < OKLIFE) && !Menptr[BestStab.ubOpponent].bService) { // don't throw a knife at him. BestStab.ubPossible = FALSE; } // now we KNOW FOR SURE that we will do something (shoot, at least) NPCDoesAct(pSoldier); DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"NPC decided to shoot (2)"); } } else { //sprintf((CHAR *)tempstr,"%s - ubMinAPCost = %d",pSoldier->name,ubMinAPCost); //PopMessage(tempstr); // then look around for a worthy target (which sets BestStab.ubPossible) CalcBestStab(pSoldier,&BestStab, TRUE); if (BestStab.ubPossible) { // now we KNOW FOR SURE that we will do something (stab, at least) NPCDoesAct(pSoldier); DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"NPC decided to stab"); } } } // if it was in his holster, swap it back into his holster for now if (bWeaponIn != HANDPOS) { DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"about to rearrange pocket after stab check"); RearrangePocket(pSoldier,HANDPOS,bWeaponIn,TEMPORARILY); } } ///////////////////////////////////////////////////////////////////////////////////////////////////// // SANDRO - even if we don't have any blade, calculate how much damage we could do unarmed else if ( !TANK( pSoldier) ) { bWeaponIn = FindAIUsableObjClass( pSoldier, IC_PUNCH ); if (bWeaponIn == NO_SLOT) // if no punch-type weapon found, just calculate it with empty hands { bWeaponIn = FindEmptySlotWithin( pSoldier, HANDPOS, NUM_INV_SLOTS ); } if (bWeaponIn != NO_SLOT) { DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"try to punch"); BestStab.bWeaponIn = bWeaponIn; // if it's in his holster, swap it into his hand temporarily if (bWeaponIn != HANDPOS) { DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionblack: about to rearrange pocket before punch check"); RearrangePocket(pSoldier,HANDPOS,bWeaponIn,TEMPORARILY); } // get the minimum cost to attack with punch ubMinAPCost = MinAPsToAttack(pSoldier,pSoldier->sLastTarget,DONTADDTURNCOST); // if we can afford the minimum AP cost to punch if (pSoldier->bActionPoints >= ubMinAPCost) { // then look around for a worthy target (which sets BestStab.ubPossible) CalcBestStab(pSoldier,&BestStab, FALSE); if (BestStab.ubPossible) { // if we have not enough APs to deal at least two or three punches, // reduce the attack value as one punch ain't much if( gGameOptions.fNewTraitSystem ) { // if we are not specialized, reduce the attack attractiveness generaly if ( !HAS_SKILL_TRAIT( pSoldier, MARTIAL_ARTS_NT ) ) { BestStab.iAttackValue /= 4; // if too far and not having APs for at least 3 hits no way to attack if (((CalcTotalAPsToAttack( pSoldier,BestStab.sTarget,ADDTURNCOST, 0 ) + (2 * (ApsToPunch( pSoldier )))) > pSoldier->bActionPoints) && !(PythSpacesAway(pSoldier->sGridNo, BestStab.sTarget) <= 1) ) { BestStab.ubPossible = 0; BestStab.iAttackValue = 0; } } else { if (PythSpacesAway(pSoldier->sGridNo, BestStab.sTarget) <= 1) { BestStab.iAttackValue = (BestStab.iAttackValue * 2); } // if too far and not having APs for at least 2 hits else if (((CalcTotalAPsToAttack( pSoldier,BestStab.sTarget,ADDTURNCOST, 0 ) + ApsToPunch( pSoldier )) > pSoldier->bActionPoints) && !(PythSpacesAway(pSoldier->sGridNo, BestStab.sTarget) <= 1)) { BestStab.iAttackValue /= 3; } } } else { if ( !HAS_SKILL_TRAIT( pSoldier, MARTIALARTS_OT ) && !HAS_SKILL_TRAIT( pSoldier, HANDTOHAND_OT ) ) { // if we are not specialized, reduce the attack attractiveness generaly BestStab.iAttackValue /= 4; // if too far and not having APs for at least 3 hits if (((CalcTotalAPsToAttack( pSoldier,BestStab.sTarget,ADDTURNCOST, 0 ) + (2 * (ApsToPunch( pSoldier )))) > pSoldier->bActionPoints) && !(PythSpacesAway(pSoldier->sGridNo, BestStab.sTarget <= 1)) ) { BestStab.ubPossible = 0; BestStab.iAttackValue = 0; } } else { BestStab.iAttackValue = ((BestStab.iAttackValue * 3)/2); if (PythSpacesAway(pSoldier->sGridNo, BestStab.sTarget) <= 1) { BestStab.iAttackValue = ((BestStab.iAttackValue * 3)/2); } // if too far and not having APs for at least 2 hits else if (((CalcTotalAPsToAttack( pSoldier,BestStab.sTarget,ADDTURNCOST, 0 ) + ApsToPunch( pSoldier )) > pSoldier->bActionPoints) && !(PythSpacesAway(pSoldier->sGridNo, BestStab.sTarget <= 1)) ) { BestStab.iAttackValue /= 3; } } } // now we KNOW FOR SURE that we will do something (stab, at least) NPCDoesAct(pSoldier); DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"NPC decided to punch"); } } // if it was in his holster, swap it back into his holster for now if (bWeaponIn != HANDPOS) { DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"about to rearrange pocket after punch check"); RearrangePocket(pSoldier,HANDPOS,bWeaponIn,TEMPORARILY); } } } ///////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // CHOOSE THE BEST TYPE OF ATTACK OUT OF THOSE FOUND TO BE POSSIBLE ////////////////////////////////////////////////////////////////////////// DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"CHOOSE THE BEST TYPE OF ATTACK OUT OF THOSE FOUND TO BE POSSIBLE"); if (BestShot.ubPossible) { BestAttack.iAttackValue = BestShot.iAttackValue; ubBestAttackAction = AI_ACTION_FIRE_GUN; DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"best action = fire gun"); } else { BestAttack.iAttackValue = 0; } if (BestStab.ubPossible && ((BestStab.iAttackValue > BestAttack.iAttackValue) || (ubBestAttackAction == AI_ACTION_NONE))) { BestAttack.iAttackValue = BestStab.iAttackValue; if ( Item[ pSoldier->inv[BestStab.bWeaponIn].usItem ].usItemClass & IC_THROWING_KNIFE ) { ubBestAttackAction = AI_ACTION_THROW_KNIFE; DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"best action = throw knife"); } else if ( Item[ pSoldier->inv[BestStab.bWeaponIn].usItem ].usItemClass & IC_BLADE ) // SANDRO - check specifically for blade attack { ubBestAttackAction = AI_ACTION_KNIFE_MOVE; DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"best action = move to stab"); } //////////////////////////////////////////////////////////////////////////////////// // SANDRO - added a chance to try to steal merc's gun from hands else { if (AIDetermineStealingWeaponAttempt( pSoldier, MercPtrs[BestStab.ubOpponent] ) == TRUE) { ubBestAttackAction = AI_ACTION_STEAL_MOVE; DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"best action = move to steal weapon"); } else { ubBestAttackAction = AI_ACTION_KNIFE_MOVE; DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"best action = move to punch"); } } //////////////////////////////////////////////////////////////////////////////////// } if (BestThrow.ubPossible && ((BestThrow.iAttackValue > BestAttack.iAttackValue) || (ubBestAttackAction == AI_ACTION_NONE))) { ubBestAttackAction = AI_ACTION_TOSS_PROJECTILE; DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"best action = throw something"); } if ( ( ubBestAttackAction == AI_ACTION_NONE ) && fTryPunching ) { // nothing (else) to attack with so let's try hand-to-hand bWeaponIn = FindObj( pSoldier, NOTHING, HANDPOS, NUM_INV_SLOTS ); if (bWeaponIn != NO_SLOT) { BestStab.bWeaponIn = bWeaponIn; // if it's in his holster, swap it into his hand temporarily if (bWeaponIn != HANDPOS) { DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionblack: swap knife into hand"); RearrangePocket(pSoldier,HANDPOS,bWeaponIn,TEMPORARILY); } // get the minimum cost to attack by HTH ubMinAPCost = MinAPsToAttack(pSoldier,pSoldier->sLastTarget,DONTADDTURNCOST); // if we can afford the minimum AP cost to use HTH combat if (pSoldier->bActionPoints >= ubMinAPCost) { // then look around for a worthy target (which sets BestStab.ubPossible) CalcBestStab(pSoldier,&BestStab, FALSE); if (BestStab.ubPossible) { // now we KNOW FOR SURE that we will do something (stab, at least) NPCDoesAct(pSoldier); ubBestAttackAction = AI_ACTION_KNIFE_MOVE; DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"NPC decided to move to stab"); } } // if it was in his holster, swap it back into his holster for now if (bWeaponIn != HANDPOS) { DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionblack: about to put knife away"); RearrangePocket(pSoldier,HANDPOS,bWeaponIn,TEMPORARILY); } } } // copy the information on the best action selected into BestAttack struct DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"copy the information on the best action selected into BestAttack struct"); switch (ubBestAttackAction) { case AI_ACTION_FIRE_GUN: memcpy(&BestAttack,&BestShot,sizeof(BestAttack)); DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"DecideActionBlack: best attack = firing a gun"); break; case AI_ACTION_TOSS_PROJECTILE: memcpy(&BestAttack,&BestThrow,sizeof(BestAttack)); DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"DecideActionBlack: best attack = tossing a grenade"); break; case AI_ACTION_THROW_KNIFE: case AI_ACTION_KNIFE_MOVE: DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"DecideActionBlack: best attack = stab with a knife"); memcpy(&BestAttack,&BestStab,sizeof(BestAttack)); break; case AI_ACTION_STEAL_MOVE: // added by SANDRO DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"DecideActionBlack: best attack = try to steal weapon"); memcpy(&BestAttack,&BestStab,sizeof(BestAttack)); break; default: // set to empty DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"DecideActionBlack: best attack = no good attack"); memset( &BestAttack, 0, sizeof( BestAttack ) ); break; } } // NB a desire of 4 or more is only achievable by brave/aggressive guys with high morale UINT16 usRange = GetModifiedGunRange(pSoldier->inv[ BestAttack.bWeaponIn ].usItem); if ( (pSoldier->bActionPoints == pSoldier->bInitialActionPoints) && (ubBestAttackAction == AI_ACTION_FIRE_GUN) && (pSoldier->aiData.bShock == 0) && (pSoldier->stats.bLife >= pSoldier->stats.bLifeMax / 2) && (BestAttack.ubChanceToReallyHit < 30) && (PythSpacesAway( pSoldier->sGridNo, BestAttack.sTarget ) > usRange / CELL_X_SIZE ) && (RangeChangeDesire( pSoldier ) >= 4) ) { // okay, really got to wonder about this... could taking cover be an option? if (ubCanMove && pSoldier->aiData.bOrders != STATIONARY && !gfHiddenInterrupt && !(pSoldier->flags.uiStatusFlags & SOLDIER_BOXER) ) { // make militia a bit more cautious // 3 (UINT16) CONVERSIONS HERE TO AVOID ERRORS. GOTTHARD 7/15/08 if ( ( (pSoldier->bTeam == MILITIA_TEAM) && ((INT16)(PreRandom( 20 )) > BestAttack.ubChanceToReallyHit) ) || ( (pSoldier->bTeam != MILITIA_TEAM) && ((INT16)(PreRandom( 40 )) > BestAttack.ubChanceToReallyHit) ) ) { //ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_TESTVERSION, L"AI %d allowing cover check, chance to hit is only %d, at range %d", BestAttack.ubChanceToReallyHit, PythSpacesAway( pSoldier->sGridNo, BestAttack.sTarget ) ); // maybe taking cover would be better! fAllowCoverCheck = TRUE; if ( (INT16)(PreRandom( 10 )) > BestAttack.ubChanceToReallyHit ) { DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"DecideActionBlack: can't hit so screw the attack"); // screw the attack! ubBestAttackAction = AI_ACTION_NONE; } } } } DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"LOOK FOR SOME KIND OF COVER BETTER THAN WHAT WE HAVE NOW"); //////////////////////////////////////////////////////////////////////////// // LOOK FOR SOME KIND OF COVER BETTER THAN WHAT WE HAVE NOW //////////////////////////////////////////////////////////////////////////// // if soldier has enough APs left to move at least 1 square's worth, // and either he can't attack any more, or his attack did wound someone iCoverPercentBetter = 0; if ( (ubCanMove && !SkipCoverCheck && !gfHiddenInterrupt && ((ubBestAttackAction == AI_ACTION_NONE) || pSoldier->aiData.bLastAttackHit) && (pSoldier->bTeam != gbPlayerNum || pSoldier->aiData.fAIFlags & AI_RTP_OPTION_CAN_SEEK_COVER) && !(pSoldier->flags.uiStatusFlags & SOLDIER_BOXER) ) || fAllowCoverCheck ) { sBestCover = FindBestNearbyCover(pSoldier,pSoldier->aiData.bAIMorale,&iCoverPercentBetter); } #ifdef RETREAT_TESTING sBestCover = NOWHERE; #endif DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"DecideActionBlack: DECIDE BETWEEN ATTACKING AND DEFENDING (TAKING COVER)"); ////////////////////////////////////////////////////////////////////////// // IF NECESSARY, DECIDE BETWEEN ATTACKING AND DEFENDING (TAKING COVER) ////////////////////////////////////////////////////////////////////////// // if both are possible if ((ubBestAttackAction != AI_ACTION_NONE) && ( !TileIsOutOfBounds(sBestCover))) { // gotta compare their merits and select the more desirable option iOffense = BestAttack.ubChanceToReallyHit; iDefense = iCoverPercentBetter; // based on how we feel about the situation, decide whether to attack first switch (pSoldier->aiData.bAIMorale) { case MORALE_FEARLESS: iOffense += iOffense / 2; // increase 50% break; case MORALE_CONFIDENT: iOffense += iOffense / 4; // increase 25% break; case MORALE_NORMAL: break; case MORALE_WORRIED: iDefense += iDefense / 4; // increase 25% break; case MORALE_HOPELESS: iDefense += iDefense / 2; // increase 50% break; } // smart guys more likely to try to stay alive, dolts more likely to shoot! if (pSoldier->stats.bWisdom >= 50) //Madd: reduced the wisdom required to want to live... iDefense += 10; else if (pSoldier->stats.bWisdom < 30) iDefense -= 10; // some orders are more offensive, others more defensive if (pSoldier->aiData.bOrders == SEEKENEMY) iOffense += 10; else if ((pSoldier->aiData.bOrders == STATIONARY) || (pSoldier->aiData.bOrders == ONGUARD) || pSoldier->aiData.bOrders == SNIPER ) iDefense += 10; switch (pSoldier->aiData.bAttitude) { case DEFENSIVE: iDefense += 30; break; case BRAVESOLO: iDefense -= 0; break; case BRAVEAID: iDefense -= 0; break; case CUNNINGSOLO: iDefense += 20; break; case CUNNINGAID: iDefense += 20; break; case AGGRESSIVE: iOffense += 10; break; case ATTACKSLAYONLY:iOffense += 30; break; } #ifdef DEBUGDECISIONS STR tempstr=""; sprintf( tempstr, "%s - CHOICE: iOffense = %d, iDefense = %d\n", pSoldier->name,iOffense,iDefense); DebugAI( tempstr ); #endif DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"DecideActionBlack: if his defensive instincts win out, forget all about the attack"); // if his defensive instincts win out, forget all about the attack if (iDefense > iOffense) ubBestAttackAction = AI_ACTION_NONE; } DebugMsg (TOPIC_JA2,DBG_LEVEL_3,String("DecideActionBlack: is attack still desirable? ubBestAttackAction = %d",ubBestAttackAction)); // if attack is still desirable (meaning it's also preferred to taking cover) if (ubBestAttackAction != AI_ACTION_NONE) { DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"DecideActionBlack: attack is still desirable (meaning it's also preferred to taking cover)"); // if we wanted to be REALLY mean, we could look at chance to hit and decide whether // to shoot at the head... fChangeStanceFirst = FALSE; // default settings //POSSIBLE STRUCTURE CHANGE PROBLEM, NOT CURRENTLY CHANGED. GOTTHARD 7/14/08 pSoldier->aiData.bAimTime = BestAttack.ubAimTime; pSoldier->bDoBurst = 0; // HEADROCK HAM 3.6: bAimTime represents how MANY aiming levels are used, not how much APs they cost necessarily. INT16 sActualAimTime = CalcAPCostForAiming( pSoldier, BestAttack.sTarget, (INT8)pSoldier->aiData.bAimTime ); if (ubBestAttackAction == AI_ACTION_FIRE_GUN) { // Do we need to change stance? NB We'll have to ready our gun again if ( !TANK( pSoldier ) && ( pSoldier->bActionPoints >= BestAttack.ubAPCost + GetAPsCrouch( pSoldier, TRUE) + MinAPsToAttack( pSoldier, BestAttack.sTarget, ADDTURNCOST, 1 ) ) ) { // since the AI considers shooting chance from standing primarily, if we are not // standing we should always consider a stance change if ( gAnimControl[ pSoldier->usAnimState ].ubEndHeight != ANIM_STAND ) { iChance = 100; } else { iChance = 50; switch (pSoldier->aiData.bAttitude) { case DEFENSIVE: iChance += 20; break; case BRAVESOLO: iChance -= 10; break; case BRAVEAID: iChance -= 10; break; case CUNNINGSOLO: iChance += 10; break; case CUNNINGAID: iChance += 10; break; case AGGRESSIVE: iChance -= 20; break; case ATTACKSLAYONLY: iChance -= 30; break; } } if ( (INT32)PreRandom( 100 ) < iChance || GetRangeInCellCoordsFromGridNoDiff( pSoldier->sGridNo, BestAttack.sTarget ) <= MIN_PRONE_RANGE ) { // first get the direction, as we will need to pass that in to ShootingStanceChange bDirection = atan8(CenterX(pSoldier->sGridNo),CenterY(pSoldier->sGridNo),CenterX(BestAttack.sTarget),CenterY(BestAttack.sTarget)); ubBestStance = ShootingStanceChange( pSoldier, &BestAttack, bDirection ); if (ubBestStance != 0) { // change stance first! if ( pSoldier->ubDirection != bDirection && pSoldier->InternalIsValidStance( bDirection, gAnimControl[ pSoldier->usAnimState ].ubEndHeight ) ) { // we're not facing towards him, so turn first! pSoldier->aiData.usActionData = bDirection; #ifdef DEBUGDECISIONS sprintf(tempstr,"%s - TURNS to face CLOSEST OPPONENT in direction %d",pSoldier->name,pSoldier->aiData.usActionData); AIPopMessage(tempstr); #endif return(AI_ACTION_CHANGE_FACING); } // pSoldier->aiData.usActionData = ubBestStance; // attack after we change stance // we don't just return here because we want to check whether to // burst first fChangeStanceFirst = TRUE; // account for increased AP cost and having to re-ready weapon ubStanceCost = (UINT8) GetAPsToChangeStance( pSoldier, ubBestStance ); BestAttack.ubAPCost = MinAPsToAttack( pSoldier, BestAttack.sTarget, ADDTURNCOST, 1) + ubStanceCost; // Clip the aim time if necessary // HEADROCK HAM 3.6: Use Actual Aiming Costs, without assuming that each aim level = 1 AP. if ( BestAttack.ubAPCost + sActualAimTime > pSoldier->bActionPoints ) { // AP cost would balance (plus X, minus X) but aim time is reduced // HEADROCK HAM 3.6: Use actual Aiming Costs. BestAttack.ubAimTime = CalcAimingLevelsAvailableWithAP( pSoldier, BestAttack.sTarget, (pSoldier->bActionPoints - BestAttack.ubAPCost - ubStanceCost) ); if (BestAttack.ubAimTime < 0 ) { // This is actually a logic error situation. The ChangeStance section is supposed // to not make a shot impossible after changing stance. BestAttack.ubPossible = 0; } } } } } ////////////////////////////////////////////////////////////////////////// // IF ENOUGH APs TO BURST, RANDOM CHANCE OF DOING SO ////////////////////////////////////////////////////////////////////////// if (IsGunBurstCapable( &pSoldier->inv[BestAttack.bWeaponIn], FALSE, pSoldier ) && !(Menptr[BestShot.ubOpponent].stats.bLife < OKLIFE) && // don't burst at downed targets pSoldier->inv[BestAttack.bWeaponIn][0]->data.gun.ubGunShotsLeft > 1 && (pSoldier->bTeam != gbPlayerNum || pSoldier->aiData.bRTPCombat == RTP_COMBAT_AGGRESSIVE) ) { DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"DecideActionBlack: ENOUGH APs TO BURST, RANDOM CHANCE OF DOING SO"); ubBurstAPs = CalcAPsToBurst( pSoldier->CalcActionPoints(), &(pSoldier->inv[BestAttack.bWeaponIn]) ); // HEADROCK HAM 3.6: Use Actual Aiming Time. if (pSoldier->bActionPoints >= BestAttack.ubAPCost + sActualAimTime + ubBurstAPs ) { // Base chance of bursting is 25% if best shot was +0 aim, down to 8% at +4 if ( TANK( pSoldier ) ) { iChance = 100; } else { iChance = (25 / max((BestAttack.ubAimTime + 1),1)); switch (pSoldier->aiData.bAttitude) { case DEFENSIVE: iChance += -5; break; case BRAVESOLO: iChance += 5; break; case BRAVEAID: iChance += 5; break; case CUNNINGSOLO: iChance += 0; break; case CUNNINGAID: iChance += 0; break; case AGGRESSIVE: iChance += 10; break; case ATTACKSLAYONLY:iChance += 30; break; } // CHRISL: Changed from a simple flag to two externalized values for more modder control over AI suppression if ( GetMagSize(&pSoldier->inv[BestAttack.bWeaponIn], 0) >= gGameExternalOptions.ubAISuppressionMinimumMagSize && pSoldier->inv[BestAttack.bWeaponIn][0]->data.gun.ubGunShotsLeft >= gGameExternalOptions.ubAISuppressionMinimumAmmo ) iChance += 20; // increase chance based on proximity and difficulty of enemy if ( PythSpacesAway( pSoldier->sGridNo, BestAttack.sTarget ) < 15 ) { DebugMsg(TOPIC_JA2AI,DBG_LEVEL_3,String("DecideActionBlack: check chance to burst")); iChance += ( 15 - PythSpacesAway( pSoldier->sGridNo, BestAttack.sTarget ) ) * ( 1 + SoldierDifficultyLevel( pSoldier ) ); if ( pSoldier->aiData.bAttitude == ATTACKSLAYONLY ) { // increase it more! iChance += 5 * ( 15 - PythSpacesAway( pSoldier->sGridNo, BestAttack.sTarget ) ); } } // HEADROCK HAM 3.6: due to the "else", this part of the formula is NEVER hit. Removing. //else if (PythSpacesAway( pSoldier->sGridNo, BestAttack.sTarget ) < 10 && gGameOptions.ubDifficultyLevel > DIF_LEVEL_EASY ) if (PythSpacesAway( pSoldier->sGridNo, BestAttack.sTarget ) < 10 && gGameOptions.ubDifficultyLevel > DIF_LEVEL_EASY ) { iChance += 100; } } if ( (INT32) PreRandom( 100 ) < iChance) { BestAttack.ubAimTime = BURSTING; BestAttack.ubAPCost = BestAttack.ubAPCost + ubBurstAPs; // check for spread burst possibilities if (pSoldier->aiData.bAttitude != ATTACKSLAYONLY) { CalcSpreadBurst( pSoldier, BestAttack.sTarget, BestAttack.bTargetLevel ); } } } } if (IsGunAutofireCapable( &pSoldier->inv[BestAttack.bWeaponIn] ) && !(Menptr[BestShot.ubOpponent].stats.bLife < OKLIFE) && // don't burst at downed targets (( pSoldier->inv[BestAttack.bWeaponIn][0]->data.gun.ubGunShotsLeft > 1 && !pSoldier->bDoBurst ) || Weapon[pSoldier->inv[BestAttack.bWeaponIn].usItem].NoSemiAuto) ) { DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"DecideActionBlack: ENOUGH APs TO AUTOFIRE, RANDOM CHANCE OF DOING SO"); FLOAT dTotalRecoil = 0.0f; pSoldier->bDoAutofire = 0; if(UsingNewCTHSystem() == true){ do { INT8 bRecoilX = 0; INT8 bRecoilY = 0; pSoldier->bDoAutofire++; dTotalRecoil += AICalcRecoilForShot( pSoldier, &(pSoldier->inv[BestShot.bWeaponIn]), pSoldier->bDoAutofire ); ubBurstAPs = CalcAPsToAutofire( pSoldier->CalcActionPoints(), &(pSoldier->inv[BestShot.bWeaponIn]), pSoldier->bDoAutofire ); } while( pSoldier->bActionPoints >= BestShot.ubAPCost + ubBurstAPs + sActualAimTime && pSoldier->inv[ pSoldier->ubAttackingHand ][0]->data.gun.ubGunShotsLeft >= pSoldier->bDoAutofire && dTotalRecoil <= 10.0f ); } else { do { pSoldier->bDoAutofire++; ubBurstAPs = CalcAPsToAutofire( pSoldier->CalcActionPoints(), &(pSoldier->inv[BestAttack.bWeaponIn]), pSoldier->bDoAutofire ); } while( pSoldier->bActionPoints >= BestAttack.ubAPCost + ubBurstAPs && pSoldier->inv[ pSoldier->ubAttackingHand ][0]->data.gun.ubGunShotsLeft >= pSoldier->bDoAutofire && GetAutoPenalty(&pSoldier->inv[ BestAttack.bWeaponIn ], gAnimControl[ pSoldier->usAnimState ].ubEndHeight == ANIM_PRONE)*pSoldier->bDoAutofire <= 80); } pSoldier->bDoAutofire--; if (pSoldier->bDoAutofire > 0) { ubBurstAPs = CalcAPsToAutofire( pSoldier->CalcActionPoints(), &(pSoldier->inv[BestAttack.bWeaponIn]), pSoldier->bDoAutofire ); if (pSoldier->bActionPoints >= BestAttack.ubAPCost + ubBurstAPs ) { // Base chance of bursting is 25% if best shot was +0 aim, down to 8% at +4 if ( TANK( pSoldier ) ) { iChance = 100; } else { iChance = (100 / max((BestAttack.ubAimTime + 1),1)); switch (pSoldier->aiData.bAttitude) { case DEFENSIVE: iChance += -5; break; case BRAVESOLO: iChance += 5; break; case BRAVEAID: iChance += 5; break; case CUNNINGSOLO: iChance += 0; break; case CUNNINGAID: iChance += 0; break; case AGGRESSIVE: iChance += 10; break; case ATTACKSLAYONLY:iChance += 30; break; } // CHRISL: Changed from a simple flag to two externalized values for more modder control over AI suppression if ( GetMagSize(&pSoldier->inv[BestAttack.bWeaponIn], 0) >= gGameExternalOptions.ubAISuppressionMinimumMagSize && pSoldier->inv[BestAttack.bWeaponIn][0]->data.gun.ubGunShotsLeft >= gGameExternalOptions.ubAISuppressionMinimumAmmo ) iChance += 30; if ( bInGas ) iChance += 50; //Madd: extra chance of going nuts and autofiring if stuck in gas // increase chance based on proximity and difficulty of enemy if ( PythSpacesAway( pSoldier->sGridNo, BestAttack.sTarget ) < 15 ) { DebugMsg(TOPIC_JA2AI,DBG_LEVEL_3,String("DecideActionBlack: check chance to autofire")); iChance += ( 15 - PythSpacesAway( pSoldier->sGridNo, BestAttack.sTarget ) ) * ( 1 + SoldierDifficultyLevel( pSoldier ) ); if ( pSoldier->aiData.bAttitude == ATTACKSLAYONLY ) { // increase it more! iChance += 5 * ( 15 - PythSpacesAway( pSoldier->sGridNo, BestAttack.sTarget ) ); } } // HEADROCK HAM 3.6: Forcing enemies to autofire at close range if possible, similar to forced burst (see above) if (PythSpacesAway( pSoldier->sGridNo, BestAttack.sTarget ) < 10 && gGameOptions.ubDifficultyLevel > DIF_LEVEL_EASY ) { iChance += 100; } } if ((INT32) PreRandom( 100 ) < iChance || Weapon[pSoldier->inv[BestAttack.bWeaponIn].usItem].NoSemiAuto) { pSoldier->aiData.bAimTime = BestAttack.ubAimTime ; pSoldier->bDoBurst = 1; BestAttack.ubAPCost = BestAttack.ubAPCost + CalcAPsToAutofire( pSoldier->CalcActionPoints(), &(pSoldier->inv[BestAttack.bWeaponIn]), pSoldier->bDoAutofire ) + sActualAimTime; } else { pSoldier->bDoAutofire = 0; pSoldier->bDoBurst = 0; } } } } if (!pSoldier->bDoBurst) { pSoldier->aiData.bAimTime = BestAttack.ubAimTime; pSoldier->bDoBurst = 0; pSoldier->bDoAutofire = 0; } // IF WAY OUT OF EFFECTIVE RANGE TRY TO ADVANCE RESERVING ENOUGH AP FOR A SHOT IF NOT ACTED YET if ((pSoldier->bActionPoints > BestAttack.ubAPCost) && (pSoldier->aiData.bShock == 0) && (pSoldier->stats.bLife >= pSoldier->stats.bLifeMax / 2) && (BestAttack.ubChanceToReallyHit < 8) && (PythSpacesAway( pSoldier->sGridNo, BestAttack.sTarget ) > usRange / CELL_X_SIZE ) && (RangeChangeDesire( pSoldier ) >= 3) ) // Cunning and above { sClosestOpponent = Menptr[BestShot.ubOpponent].sGridNo; if (!TileIsOutOfBounds(sClosestOpponent)) { // temporarily make merc get closer reserving enough for expected cost of shot USHORT tgrd = pSoldier->aiData.sPatrolGrid[0]; INT8 oldOrders = pSoldier->aiData.bOrders; pSoldier->aiData.sPatrolGrid[0] = pSoldier->sGridNo; pSoldier->aiData.bOrders = CLOSEPATROL; pSoldier->aiData.usActionData = InternalGoAsFarAsPossibleTowards( pSoldier, sClosestOpponent, BestAttack.ubAPCost, AI_ACTION_GET_CLOSER, 0 ); pSoldier->aiData.sPatrolGrid[0] = tgrd; pSoldier->aiData.bOrders = oldOrders; if (!TileIsOutOfBounds(pSoldier->aiData.usActionData)) { pSoldier->aiData.usActionData = pSoldier->sGridNo ; pSoldier->pathing.sFinalDestination = pSoldier->aiData.usActionData; pSoldier->aiData.bNextAction = AI_ACTION_FIRE_GUN; pSoldier->aiData.usNextActionData = BestAttack.sTarget; pSoldier->aiData.bNextTargetLevel = BestAttack.bTargetLevel; return( AI_ACTION_GET_CLOSER ); } } } ////////////////////////////////////////////////////////////////////////// // IF NOT CROUCHED & WILL STILL HAVE ENOUGH APs TO DO THIS SAME BEST // ATTACK AFTER A STANCE CHANGE, CONSIDER CHANGING STANCE ////////////////////////////////////////////////////////////////////////// // HEADROCK HAM 4: No longer necessary to do here. The conditions above already handle this, specifically // WITHOUT messing with the BestAttack.ubAimTime variable, since that can apply now even when bursting // or autofiring!! /* if (BestAttack.ubAimTime == BURSTING) { pSoldier->aiData.bAimTime = 0; pSoldier->bDoBurst = 1; pSoldier->bDoAutofire = 0; } else if(BestAttack.ubAimTime >= AUTOFIRING) { pSoldier->aiData.bAimTime = 0; pSoldier->bDoBurst = 1; pSoldier->bDoAutofire = BestAttack.ubAimTime-AUTOFIRING; BestAttack.ubAimTime = AUTOFIRING; }*/ /* else // defaults already set { pSoldier->aiData.bAimTime = BestAttack.ubAimTime; pSoldier->bDoBurst = 0; } */ } else if (ubBestAttackAction == AI_ACTION_THROW_KNIFE) { if (BestAttack.bWeaponIn != HANDPOS && gAnimControl[ pSoldier->usAnimState ].ubEndHeight == ANIM_STAND ) { // we had better make sure we lower our gun first! pSoldier->aiData.bAction = AI_ACTION_LOWER_GUN; pSoldier->aiData.usActionData = 0; // queue up attack for after we lower weapon if any pSoldier->aiData.bNextAction = AI_ACTION_THROW_KNIFE; pSoldier->aiData.usNextActionData = BestAttack.sTarget; pSoldier->aiData.bNextTargetLevel = BestAttack.bTargetLevel; } } // SANDRO - chance to make aimed punch/stab for martial arts/melee else if (ubBestAttackAction == AI_ACTION_KNIFE_MOVE && gGameOptions.fNewTraitSystem) { pSoldier->aiData.bAimTime = 0; if (Item[pSoldier->inv[BestAttack.bWeaponIn].usItem].usItemClass == IC_PUNCH) { if (HAS_SKILL_TRAIT( pSoldier, MARTIAL_ARTS_NT)) { if( PreRandom( (gGameExternalOptions.fEnhancedCloseCombatSystem ? 2 : 0) + 2 * NUM_SKILL_TRAITS( pSoldier, MARTIAL_ARTS_NT) ) > 2 ) { pSoldier->aiData.bAimTime = (gGameExternalOptions.fEnhancedCloseCombatSystem ? gSkillTraitValues.ubModifierForAPsAddedOnAimedPunches : 6); } } } else { if (HAS_SKILL_TRAIT( pSoldier, MELEE_NT)) { if( PreRandom( gGameExternalOptions.fEnhancedCloseCombatSystem ? 3 : 1 ) > 0 ) { pSoldier->aiData.bAimTime = (gGameExternalOptions.fEnhancedCloseCombatSystem ? gSkillTraitValues.ubModifierForAPsAddedOnAimedBladedAttackes : 6); } } } } ////////////////////////////////////////////////////////////////////////// // OTHERWISE, JUST GO AHEAD & ATTACK! ////////////////////////////////////////////////////////////////////////// DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"OTHERWISE, JUST GO AHEAD & ATTACK!"); // swap weapon to hand if necessary if (BestAttack.bWeaponIn != HANDPOS) { DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"decideactionblack: swap weapon into hand"); RearrangePocket(pSoldier,HANDPOS,BestAttack.bWeaponIn,FOREVER); } if (fChangeStanceFirst) { // currently only for guns... pSoldier->aiData.bNextAction = AI_ACTION_FIRE_GUN; pSoldier->aiData.usNextActionData = BestAttack.sTarget; pSoldier->aiData.bNextTargetLevel = BestAttack.bTargetLevel; pSoldier->aiData.usActionData = ubBestStance; return( AI_ACTION_CHANGE_STANCE ); } else { pSoldier->aiData.usActionData = BestAttack.sTarget; pSoldier->bTargetLevel = BestAttack.bTargetLevel; #ifdef DEBUGDECISIONS STR tempstr=""; sprintf( tempstr, "%d(%s) %s %d(%s) at gridno %d (%d APs aim)\n", pSoldier->ubID,pSoldier->name, (ubBestAttackAction == AI_ACTION_FIRE_GUN)?"SHOOTS":((ubBestAttackAction == AI_ACTION_TOSS_PROJECTILE)?"TOSSES AT":"STABS"), BestAttack.ubOpponent,pSoldier->name , BestAttack.sTarget,BestAttack.ubAimTime ); DebugAI( tempstr); #endif //DebugMsg(TOPIC_JA2, DBG_LEVEL_3, String("DecideActionBlack: Check for GL Bursts, is launcher capable? = %d, rtpcombat? = %d, bestattackaction = %d",IsGunBurstCapable( pSoldier, BestAttack.bWeaponIn, FALSE ),pSoldier->aiData.bRTPCombat,ubBestAttackAction )); //should be a bug DebugMsg(TOPIC_JA2, DBG_LEVEL_3, String("DecideActionBlack: Check for GL Bursts, is launcher capable? = %d, rtpcombat? = %d, bestattackaction = %d",IsGunBurstCapable( &pSoldier->inv[BestAttack.bWeaponIn], FALSE, pSoldier ),pSoldier->aiData.bRTPCombat,ubBestAttackAction )); if (ubBestAttackAction == AI_ACTION_TOSS_PROJECTILE && (Item[pSoldier->inv[BestAttack.bWeaponIn].usItem].usItemClass == IC_LAUNCHER && IsGunBurstCapable( &pSoldier->inv[BestAttack.bWeaponIn], FALSE, pSoldier )) && (pSoldier->bTeam != gbPlayerNum || pSoldier->aiData.bRTPCombat == RTP_COMBAT_AGGRESSIVE) ) { DebugMsg(TOPIC_JA2, DBG_LEVEL_3, "DecideActionBlack: Doing burst calc"); ubBurstAPs = CalcAPsToBurst( pSoldier->CalcActionPoints(), &(pSoldier->inv[BestAttack.bWeaponIn]) ); if ( (pSoldier->bActionPoints - BestAttack.ubAPCost) >= ubBurstAPs ) { // Base chance of bursting is 25% if best shot was +0 aim, down to 8% at +4 if ( TANK( pSoldier ) ) { iChance = 100; } else { iChance = 50; switch (pSoldier->aiData.bAttitude) { case DEFENSIVE: iChance += -5; break; case BRAVESOLO: iChance += 5; break; case BRAVEAID: iChance += 5; break; case CUNNINGSOLO: iChance += 0; break; case CUNNINGAID: iChance += 0; break; case AGGRESSIVE: iChance += 10; break; case ATTACKSLAYONLY:iChance += 30; break; } // increase chance based on proximity and difficulty of enemy DebugMsg(TOPIC_JA2AI,DBG_LEVEL_3,String("DecideActionBlack: check chance to gl burst")); iChance += ( 15 - PythSpacesAway( pSoldier->sGridNo, BestAttack.sTarget ) ) * ( 1 + SoldierDifficultyLevel( pSoldier ) ); } if ( (INT32) PreRandom( 100 ) < iChance) { DebugMsg(TOPIC_JA2, DBG_LEVEL_3, "DecideActionBlack: Doing GL burst"); BestAttack.ubAimTime = BURSTING; BestAttack.ubAPCost = BestAttack.ubAPCost + CalcAPsToBurst( pSoldier->CalcActionPoints(), &(pSoldier->inv[HANDPOS]) ); // check for spread burst possibilities if (pSoldier->aiData.bAttitude != ATTACKSLAYONLY) { CalcSpreadBurst( pSoldier, BestAttack.sTarget, BestAttack.bTargetLevel ); } pSoldier->bDoBurst = 1; } } } return(ubBestAttackAction); } } // end of tank AI if ( TANK( pSoldier ) ) { return( AI_ACTION_NONE ); } // try to make boxer close if possible if (pSoldier->flags.uiStatusFlags & SOLDIER_BOXER ) { if ( ubCanMove ) { sClosestOpponent = ClosestSeenOpponent(pSoldier, NULL, NULL); if (!TileIsOutOfBounds(sClosestOpponent)) { // temporarily make boxer have orders of CLOSEPATROL rather than STATIONARY // And make him patrol the ring, not his usual place // so he has a good roaming range USHORT tgrd = pSoldier->aiData.sPatrolGrid[0]; pSoldier->aiData.sPatrolGrid[0] = pSoldier->sGridNo; pSoldier->aiData.bOrders = CLOSEPATROL; pSoldier->aiData.usActionData = GoAsFarAsPossibleTowards( pSoldier, sClosestOpponent, AI_ACTION_GET_CLOSER ); pSoldier->aiData.sPatrolGrid[0] = tgrd; pSoldier->aiData.bOrders = STATIONARY; if (!TileIsOutOfBounds(pSoldier->aiData.usActionData)) { // truncate path to 1 step pSoldier->aiData.usActionData = pSoldier->sGridNo + DirectionInc( (UINT8) pSoldier->pathing.usPathingData[0] ); pSoldier->pathing.sFinalDestination = pSoldier->aiData.usActionData; pSoldier->aiData.bNextAction = AI_ACTION_END_TURN; return( AI_ACTION_GET_CLOSER ); } } } // otherwise do nothing return( AI_ACTION_NONE ); } //////////////////////////////////////////////////////////////////////////// // IF A LOCATION WITH BETTER COVER IS AVAILABLE & REACHABLE, GO FOR IT! //////////////////////////////////////////////////////////////////////////// if (!TileIsOutOfBounds(sBestCover)) { #ifdef DEBUGDECISIONS STR tempstr=""; sprintf ( tempstr,"%s - TAKING COVER at gridno %d (%d%% better)\n", pSoldier->name,sBestCover,iCoverPercentBetter); DebugAI( tempstr ) ; #endif //ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_TESTVERSION, L"AI %d taking cover, morale %d, from %d to %d", pSoldier->ubID, pSoldier->aiData.bAIMorale, pSoldier->sGridNo, sBestCover ); pSoldier->aiData.usActionData = sBestCover; return(AI_ACTION_TAKE_COVER); } //////////////////////////////////////////////////////////////////////////// // IF THINGS ARE REALLY HOPELESS, OR UNARMED, TRY TO RUN AWAY //////////////////////////////////////////////////////////////////////////// // if soldier has enough APs left to move at least 1 square's worth if ( ubCanMove && (pSoldier->bTeam != gbPlayerNum || pSoldier->aiData.fAIFlags & AI_RTP_OPTION_CAN_RETREAT) ) { if ((pSoldier->aiData.bAIMorale == MORALE_HOPELESS) || !bCanAttack) { // look for best place to RUN AWAY to (farthest from the closest threat) //pSoldier->aiData.usActionData = RunAway( pSoldier ); pSoldier->aiData.usActionData = FindSpotMaxDistFromOpponents(pSoldier); if (!TileIsOutOfBounds(pSoldier->aiData.usActionData)) { #ifdef DEBUGDECISIONS sprintf(tempstr,"%s - RUNNING AWAY to grid %d",pSoldier->name,pSoldier->aiData.usActionData); AIPopMessage(tempstr); #endif return(AI_ACTION_RUN_AWAY); } } } //////////////////////////////////////////////////////////////////////////// // IF SPOTTERS HAVE BEEN CALLED FOR, AND WE HAVE SOME NEW SIGHTINGS, RADIO! //////////////////////////////////////////////////////////////////////////// // if we're a computer merc, and we have the action points remaining to RADIO // (we never want NPCs to choose to radio if they would have to wait a turn) // and we're not swimming in deep water, and somebody has called for spotters // and we see the location of at least 2 opponents if ((gTacticalStatus.ubSpottersCalledForBy != NOBODY) && (pSoldier->bActionPoints >= APBPConstants[AP_RADIO]) && (pSoldier->aiData.bOppCnt > 1) && !fCivilian && (gTacticalStatus.Team[pSoldier->bTeam].bMenInSector > 1) && !bInDeepWater) { // base chance depends on how much new info we have to radio to the others iChance = 25 * WhatIKnowThatPublicDont(pSoldier,TRUE); // just count them // if I actually know something they don't if (iChance) { #ifdef DEBUGDECISIONS AINumMessage("Chance to radio for SPOTTING = ",iChance); #endif if ((INT16)PreRandom(100) < iChance) { #ifdef DEBUGDECISIONS AINameMessage(pSoldier,"decides to radio a RED for SPOTTING!",1000); #endif return(AI_ACTION_RED_ALERT); } } } //////////////////////////////////////////////////////////////////////////// // CROUCH IF NOT CROUCHING ALREADY //////////////////////////////////////////////////////////////////////////// // if not in water and not already crouched, try to crouch down first if (!gfTurnBasedAI || GetAPsToChangeStance( pSoldier, ANIM_CROUCH ) <= pSoldier->bActionPoints) { if ( !fCivilian && !gfHiddenInterrupt && IsValidStance( pSoldier, ANIM_CROUCH ) && ubBestAttackAction != AI_ACTION_KNIFE_MOVE && ubBestAttackAction != AI_ACTION_KNIFE_STAB && ubBestAttackAction != AI_ACTION_STEAL_MOVE) // SANDRO - if knife attack don't crouch { // determine the location of the known closest opponent // (don't care if he's conscious, don't care if he's reachable at all) sClosestOpponent = ClosestSeenOpponent(pSoldier, NULL, NULL); // SANDRO - don't crouch if in close combat distance (we got penalties that way) if (PythSpacesAway(pSoldier->sGridNo, sClosestOpponent) > 1 ) { pSoldier->aiData.usActionData = StanceChange( pSoldier, BestAttack.ubAPCost ); if (pSoldier->aiData.usActionData != 0) { if (pSoldier->aiData.usActionData == ANIM_PRONE) { // we might want to turn before lying down! if ( (!gfTurnBasedAI || GetAPsToLook( pSoldier ) <= pSoldier->bActionPoints - GetAPsToChangeStance( pSoldier, (INT8) pSoldier->aiData.usActionData )) && (((pSoldier->aiData.bAIMorale > MORALE_HOPELESS) || ubCanMove) && !AimingGun(pSoldier)) ) { // if we have a closest seen opponent if (!TileIsOutOfBounds(sClosestOpponent)) { bDirection = atan8(CenterX(pSoldier->sGridNo),CenterY(pSoldier->sGridNo),CenterX(sClosestOpponent),CenterY(sClosestOpponent)); // if we're not facing towards him if (pSoldier->ubDirection != bDirection) { if ( pSoldier->InternalIsValidStance( bDirection, (INT8) pSoldier->aiData.usActionData) ) { // change direction, THEN change stance! pSoldier->aiData.bNextAction = AI_ACTION_CHANGE_STANCE; pSoldier->aiData.usNextActionData = pSoldier->aiData.usActionData; pSoldier->aiData.usActionData = bDirection; #ifdef DEBUGDECISIONS sprintf(tempstr,"%s - TURNS to face CLOSEST OPPONENT in direction %d",pSoldier->name,pSoldier->aiData.usActionData); AIPopMessage(tempstr); #endif return(AI_ACTION_CHANGE_FACING); } else if ( (pSoldier->aiData.usActionData == ANIM_PRONE) && (pSoldier->InternalIsValidStance( bDirection, ANIM_CROUCH) ) ) { // we shouldn't go prone, since we can't turn to shoot pSoldier->aiData.usActionData = ANIM_CROUCH; pSoldier->aiData.bNextAction = AI_ACTION_END_TURN; return( AI_ACTION_CHANGE_STANCE ); } } // else we are facing in the right direction } // else we don't know any enemies } // we don't want to turn } pSoldier->aiData.bNextAction = AI_ACTION_END_TURN; return( AI_ACTION_CHANGE_STANCE ); } } } } //////////////////////////////////////////////////////////////////////////// // TURN TO FACE CLOSEST KNOWN OPPONENT (IF NOT FACING THERE ALREADY) //////////////////////////////////////////////////////////////////////////// if (!gfTurnBasedAI || GetAPsToLook( pSoldier ) <= pSoldier->bActionPoints) { // hopeless guys shouldn't waste their time this way, UNLESS they CAN move // but chose not to to get this far (which probably means they're cornered) // ALSO, don't bother turning if we're already aiming a gun if ( !gfHiddenInterrupt && ((pSoldier->aiData.bAIMorale > MORALE_HOPELESS) || ubCanMove) && !AimingGun(pSoldier)) { // determine the location of the known closest opponent // (don't care if he's conscious, don't care if he's reachable at all) sClosestOpponent = ClosestSeenOpponent(pSoldier, NULL, NULL); // if we have a closest reachable opponent if (!TileIsOutOfBounds(sClosestOpponent)) { bDirection = atan8(CenterX(pSoldier->sGridNo),CenterY(pSoldier->sGridNo),CenterX(sClosestOpponent),CenterY(sClosestOpponent)); // if we're not facing towards him if ( pSoldier->ubDirection != bDirection && pSoldier->InternalIsValidStance( bDirection, gAnimControl[ pSoldier->usAnimState ].ubEndHeight ) ) { pSoldier->aiData.usActionData = bDirection; #ifdef DEBUGDECISIONS sprintf(tempstr,"%s - TURNS to face CLOSEST OPPONENT in direction %d",pSoldier->name,pSoldier->aiData.usActionData); AIPopMessage(tempstr); #endif return(AI_ACTION_CHANGE_FACING); } } } } // if a militia has absofreaking nothing else to do, maybe they should radio in a report! //////////////////////////////////////////////////////////////////////////// // RADIO RED ALERT: determine %chance to call others and report contact //////////////////////////////////////////////////////////////////////////// if ( pSoldier->bTeam == MILITIA_TEAM && (pSoldier->bActionPoints >= APBPConstants[AP_RADIO]) && (gTacticalStatus.Team[pSoldier->bTeam].bMenInSector > 1) ) { // if there hasn't been an initial RED ALERT yet in this sector if ( !(gTacticalStatus.Team[pSoldier->bTeam].bAwareOfOpposition) || NeedToRadioAboutPanicTrigger() ) { // since I'm at STATUS RED, I obviously know we're being invaded! DebugMsg(TOPIC_JA2AI,DBG_LEVEL_3,String("DecideActionBlack: check chance to radio contact")); iChance = gbDiff[DIFF_RADIO_RED_ALERT][ SoldierDifficultyLevel( pSoldier ) ]; } else // subsequent radioing (only to update enemy positions, request help) // base chance depends on how much new info we have to radio to the others iChance = 10 * WhatIKnowThatPublicDont(pSoldier,FALSE); // use 10 * for RED alert // if I actually know something they don't and I ain't swimming (deep water) if (iChance && !bInDeepWater) { // modify base chance according to orders switch (pSoldier->aiData.bOrders) { case STATIONARY: iChance += 20; break; case ONGUARD: iChance += 15; break; case ONCALL: iChance += 10; break; case CLOSEPATROL: break; case RNDPTPATROL: case POINTPATROL: iChance += -5; break; case FARPATROL: iChance += -10; break; case SEEKENEMY: iChance += -20; break; case SNIPER: iChance += -10; break; } // modify base chance according to attitude switch (pSoldier->aiData.bAttitude) { case DEFENSIVE: iChance += 20; break; case BRAVESOLO: iChance += -10; break; case BRAVEAID: break; case CUNNINGSOLO: iChance += -5; break; case CUNNINGAID: break; case AGGRESSIVE: iChance += -20; break; case ATTACKSLAYONLY: iChance = 0; } if (gTacticalStatus.Team[pSoldier->bTeam].bAwareOfOpposition) { // ignore morale (which could be really high) } else { // modify base chance according to morale switch (pSoldier->aiData.bAIMorale) { case MORALE_HOPELESS: iChance *= 3; break; case MORALE_WORRIED: iChance *= 2; break; case MORALE_NORMAL: break; case MORALE_CONFIDENT: iChance /= 2; break; case MORALE_FEARLESS: iChance /= 3; break; } } // reduce chance because we're in combat iChance /= 2; #ifdef DEBUGDECISIONS AINumMessage("Chance to radio RED alert = ",iChance); #endif if ((INT16) PreRandom(100) < iChance) { #ifdef DEBUGDECISIONS AINameMessage(pSoldier,"decides to radio a RED alert!",1000); #endif return(AI_ACTION_RED_ALERT); } } } //////////////////////////////////////////////////////////////////////////// // LEAVE THE SECTOR //////////////////////////////////////////////////////////////////////////// // NOT IMPLEMENTED //////////////////////////////////////////////////////////////////////////// // DO NOTHING: Not enough points left to move, so save them for next turn //////////////////////////////////////////////////////////////////////////// #ifdef DEBUGDECISIONS AINameMessage(pSoldier,"- DOES NOTHING (BLACK)",1000); #endif // by default, if everything else fails, just stand in place and wait pSoldier->aiData.usActionData = NOWHERE; return(AI_ACTION_NONE); } INT8 DecideAction(SOLDIERTYPE *pSoldier) { DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"DecideAction"); INT8 bAction=AI_ACTION_NONE; #ifdef DEBUGDECISIONS STR16 tempstr; #endif #ifdef AI_TIMING_TESTS UINT32 uiStartTime, uiEndTime; #endif if ( pSoldier->bTeam != MILITIA_TEAM ) { if ( !sniperwarning && pSoldier->aiData.bOrders == SNIPER ) { ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_INTERFACE, New113Message[MSG113_WATHCHOUTFORSNIPERS] ); sniperwarning = TRUE; } if (!biggunwarning && FindRocketLauncherOrCannon(pSoldier) != NO_SLOT ) { biggunwarning = TRUE; //TODO: don't say this again after reloading a savegame SayQuoteFromAnyBodyInSector( QUOTE_WEARY_SLASH_SUSPUCIOUS ); } } // turn off cautious flag pSoldier->aiData.fAIFlags &= (~AI_CAUTIOUS); //reset flank count //NumMessage("DecideAction - Guy#",pSoldier->ubID); // if the NPC is being "ESCORTED" (seen civilians only for now) if (pSoldier->aiData.bUnderEscort) { #ifdef DEBUGDECISIONS AIPopMessage("AlertStatus = ESCORT"); #endif //bAction = DecideActionEscort(pSoldier); } else // "normal" NPC AI { // if status over-ride is set, bypass RED/YELLOW and go directly to GREEN! if ((pSoldier->aiData.bBypassToGreen) && (pSoldier->aiData.bAlertStatus < STATUS_BLACK)) { bAction = DecideActionGreen(pSoldier); if ( !gfTurnBasedAI ) { // reset bypass now pSoldier->aiData.bBypassToGreen = 0; } } else { switch (pSoldier->aiData.bAlertStatus) { case STATUS_GREEN: #ifdef DEBUGDECISIONS AIPopMessage("AlertStatus = GREEN"); #endif #ifdef AI_TIMING_TESTS uiStartTime = GetJA2Clock(); #endif bAction = DecideActionGreen(pSoldier); #ifdef AI_TIMING_TESTS uiEndTime = GetJA2Clock(); guiGreenTimeTotal += (uiEndTime - uiStartTime); guiGreenCounter++; #endif break; case STATUS_YELLOW: #ifdef DEBUGDECISIONS AIPopMessage("AlertStatus = YELLOW"); #endif #ifdef AI_TIMING_TESTS uiStartTime = GetJA2Clock(); #endif bAction = DecideActionYellow(pSoldier); #ifdef AI_TIMING_TESTS uiEndTime = GetJA2Clock(); guiYellowTimeTotal += (uiEndTime - uiStartTime); guiYellowCounter++; #endif break; case STATUS_RED: #ifdef DEBUGDECISIONS AIPopMessage("AlertStatus = RED"); #endif #ifdef AI_TIMING_TESTS uiStartTime = GetJA2Clock(); #endif bAction = DecideActionRed(pSoldier,TRUE); #ifdef AI_TIMING_TESTS uiEndTime = GetJA2Clock(); guiRedTimeTotal += (uiEndTime - uiStartTime); guiRedCounter++; #endif break; case STATUS_BLACK: #ifdef DEBUGDECISIONS AIPopMessage("AlertStatus = BLACK"); #endif #ifdef AI_TIMING_TESTS uiStartTime = GetJA2Clock(); #endif bAction = DecideActionBlack(pSoldier); DebugMsg (TOPIC_JA2,DBG_LEVEL_3,String("DecideActionBlack=%d",bAction)); #ifdef AI_TIMING_TESTS uiEndTime = GetJA2Clock(); guiBlackTimeTotal += (uiEndTime - uiStartTime); guiBlackCounter++; #endif break; } } } #ifdef DEBUGDECISIONS sprintf( tempstr,"DecideAction: selected action %d, actionData %d\n\n",bAction,pSoldier->aiData.usActionData); DebugAI( tempstr ); #endif DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"DecideAction done"); return(bAction); } INT8 DecideActionEscort(SOLDIERTYPE *pSoldier) { #ifdef DEBUGDECISIONS STR16 tempstr; #endif // if he has a place to go, and isn't already there... go! if (!TileIsOutOfBounds(pSoldier->aiData.usActionData) && (pSoldier->sGridNo != pSoldier->aiData.usActionData)) { #ifdef DEBUGDECISIONS sprintf(tempstr,"%s - ESCORTED NPC GOING to grid %d",pSoldier->name,pSoldier->aiData.usActionData); AIPopMessage(tempstr); #endif return(AI_ACTION_ESCORTED_MOVE); } else return(AI_ACTION_NONE); } void DecideAlertStatus( SOLDIERTYPE *pSoldier ) { #ifdef DEBUGDECISIONS STR16 tempstr; #endif INT8 bOldStatus; INT32 iDummy; BOOLEAN fClimbDummy,fReachableDummy; // THE FOUR (4) POSSIBLE ALERT STATUSES ARE: // GREEN - No one seen, no suspicious noise heard, go about regular duties // YELLOW - Suspicious noise was heard personally or radioed in by buddy // RED - Either saw opponents in person, or definite contact had been radioed // BLACK - Currently has one or more opponents in sight // save the man's previous status if (pSoldier->flags.uiStatusFlags & SOLDIER_MONSTER) { CreatureDecideAlertStatus( pSoldier ); return; } bOldStatus = pSoldier->aiData.bAlertStatus; // determine the current alert status for this category of man //if (!(pSoldier->flags.uiStatusFlags & SOLDIER_PC)) { if (pSoldier->aiData.bOppCnt > 0) // opponent(s) in sight { pSoldier->aiData.bAlertStatus = STATUS_BLACK; CheckForChangingOrders( pSoldier ); } else // no opponents are in sight { switch (bOldStatus) { case STATUS_BLACK: // then drop back to RED status pSoldier->aiData.bAlertStatus = STATUS_RED; break; case STATUS_RED: // RED can never go back down below RED, only up to BLACK break; case STATUS_YELLOW: // if all enemies have been RED alerted, or we're under fire if (!PTR_CIVILIAN && (gTacticalStatus.Team[pSoldier->bTeam].bAwareOfOpposition || pSoldier->aiData.bUnderFire)) { pSoldier->aiData.bAlertStatus = STATUS_RED; } else { // if we are NOT aware of any uninvestigated noises right now // and we are not currently in the middle of an action // (could still be on his way heading to investigate a noise!) if (( TileIsOutOfBounds(MostImportantNoiseHeard(pSoldier,&iDummy,&fClimbDummy,&fReachableDummy))) && !pSoldier->aiData.bActionInProgress) { // then drop back to GREEN status pSoldier->aiData.bAlertStatus = STATUS_GREEN; CheckForChangingOrders( pSoldier ); } } break; case STATUS_GREEN: // if all enemies have been RED alerted, or we're under fire if (!PTR_CIVILIAN && (gTacticalStatus.Team[pSoldier->bTeam].bAwareOfOpposition || pSoldier->aiData.bUnderFire)) { pSoldier->aiData.bAlertStatus = STATUS_RED; } else { // if we ARE aware of any uninvestigated noises right now if (!TileIsOutOfBounds(MostImportantNoiseHeard(pSoldier,&iDummy,&fClimbDummy,&fReachableDummy))) { // then move up to YELLOW status pSoldier->aiData.bAlertStatus = STATUS_YELLOW; } } break; } // otherwise, RED stays RED, YELLOW stays YELLOW, GREEN stays GREEN } } #if 0 else { if (pSoldier->bOppCnt > 0) { pSoldier->aiData.bAlertStatus = STATUS_BLACK; // opponent(s) in sight } else { pSoldier->aiData.bAlertStatus = STATUS_RED; // enemy sector /* // wow, JA1 stuff... // good guys all have a built-in, magic, "enemy detecting radar"... if (Status.enemies) pSoldier->aiData.bAlertStatus = STATUS_RED; // enemy sector else { pSoldier->aiData.bAlertStatus = STATUS_GREEN; // secured sector // if he just dropped back from alert status, and it's a GUARD if ((oldStatus >= STATUS_RED) && (pSoldier->manCategory == MAN_GUARD)) { if (TileIsOutOfBounds(pSoldier->whereIWas)) // not assigned to any trees // FUTURE ENHANCEMENT: Look for unguarded trees with tappers pSoldier->orders = ONCALL; else // assigned to trees // FUTURE ENHANCEMENT: If his tree is now tapperless, go ONCALL pSoldier->orders = CLOSEPATROL; // go back to his tree area // turn off any existing bypass to Green and its "hyper-activity" pSoldier->bypassToGreen = FALSE; // turn off the "inTheWay" flag, may have been set during TurnBased pSoldier->inTheWay = FALSE; // make the guard put his gun away if he has it drawn HandleNoMoreTarget(pSoldier); } } */ } } #endif if ( gTacticalStatus.bBoxingState == NOT_BOXING ) { // if the man's alert status has changed in any way if (pSoldier->aiData.bAlertStatus != bOldStatus) { // HERE ARE TRYING TO AVOID NPCs SHUFFLING BACK & FORTH BETWEEN RED & BLACK // if either status is < RED (ie. anything but RED->BLACK && BLACK->RED) if ((bOldStatus < STATUS_RED) || (pSoldier->aiData.bAlertStatus < STATUS_RED)) { // force a NEW action decision on next pass through HandleManAI() SetNewSituation( pSoldier ); } // if this guy JUST discovered that there were opponents here for sure... if ((bOldStatus < STATUS_RED) && (pSoldier->aiData.bAlertStatus >= STATUS_RED)) { CheckForChangingOrders(pSoldier); } #ifdef DEBUGDECISIONS // don't report status changes for human-controlled mercs sprintf(tempstr,"%s's Alert Status changed from %d to %d", pSoldier->name,bOldStatus,pSoldier->aiData.bAlertStatus); AIPopMessage(tempstr); #endif } else // status didn't change { // only do this stuff in TB // if a guy on status GREEN or YELLOW is running low on breath if (((pSoldier->aiData.bAlertStatus == STATUS_GREEN) && (pSoldier->bBreath < 75)) || ((pSoldier->aiData.bAlertStatus == STATUS_YELLOW) && (pSoldier->bBreath < 50))) { // as long as he's not in water (standing on a bridge is OK) if (!pSoldier->MercInWater()) { // force a NEW decision so that he can get some rest SetNewSituation( pSoldier ); // current action will be canceled. if noise is no longer important if ((pSoldier->aiData.bAlertStatus == STATUS_YELLOW) && ( TileIsOutOfBounds(MostImportantNoiseHeard(pSoldier,&iDummy,&fClimbDummy,&fReachableDummy)))) { // then drop back to GREEN status pSoldier->aiData.bAlertStatus = STATUS_GREEN; CheckForChangingOrders( pSoldier ); } } } } } else if (gTacticalStatus.bBoxingState == DISQUALIFIED || gTacticalStatus.bBoxingState == WON_ROUND || gTacticalStatus.bBoxingState == LOST_ROUND) { pSoldier->aiData.bAlertStatus = STATUS_GREEN; } }
[ "jazz_ja@b41f55df-6250-4c49-8e33-4aa727ad62a1" ]
[ [ [ 1, 5886 ] ] ]
84b18430973553d0ecf89b92a78e4b2523e75941
fe122f81ca7d6dff899945987f69305ada995cd7
/NET/NDK/NDK.cpp
7a2604aac529a1243bfdc63cae54a72ae6896085
[]
no_license
myeverytime/chtdependstoreroom
ddb9f4f98a6a403521aaf403d0b5f2dc5213f346
64a4d1e2d32abffaab0376f6377e10448b3c5bc3
refs/heads/master
2021-01-10T06:53:35.455736
2010-06-23T10:21:44
2010-06-23T10:21:44
50,168,936
0
0
null
null
null
null
UTF-8
C++
false
false
1,512
cpp
// NDK.cpp : Defines the initialization routines for the DLL. // #include "stdafx.h" #include <afxdllx.h> #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif static AFX_EXTENSION_MODULE NDKDLL = { NULL, NULL }; extern "C" int APIENTRY DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) { // Remove this if you use lpReserved UNREFERENCED_PARAMETER(lpReserved); if (dwReason == DLL_PROCESS_ATTACH) { TRACE0("NDK.DLL Initializing!\n"); // Extension DLL one-time initialization if (!AfxInitExtensionModule(NDKDLL, hInstance)) return 0; // Insert this DLL into the resource chain // NOTE: If this Extension DLL is being implicitly linked to by // an MFC Regular DLL (such as an ActiveX Control) // instead of an MFC application, then you will want to // remove this line from DllMain and put it in a separate // function exported from this Extension DLL. The Regular DLL // that uses this Extension DLL should then explicitly call that // function to initialize this Extension DLL. Otherwise, // the CDynLinkLibrary object will not be attached to the // Regular DLL's resource chain, and serious problems will // result. new CDynLinkLibrary(NDKDLL); } else if (dwReason == DLL_PROCESS_DETACH) { TRACE0("NDK.DLL Terminating!\n"); // Terminate the library before destructors are called AfxTermExtensionModule(NDKDLL); } return 1; // ok }
[ "robustwell@bd7e636a-136b-06c9-ecb0-b59307166256" ]
[ [ [ 1, 51 ] ] ]
f045816270ad2cf2d46297dc0c6441f907739364
a6364718e205f8a83f180f5f06703e8964d6eafe
/foo_lyricsgrabber2/foo_lyricsgrabber2/tag_writer.h
c485f50df79bdb4f282cfd8cf7a66bcda9442c45
[ "MIT" ]
permissive
LWain83/lyricsgrabber2
b40f56303b7de120a8f12292e194faac661a79e3
b71765433d6ac0c1d1b85b6b1d82de705c6d5718
refs/heads/master
2016-08-12T18:53:51.990628
2010-08-28T07:13:29
2010-08-28T07:13:29
52,316,826
0
0
null
null
null
null
UTF-8
C++
false
false
864
h
#pragma once #include "ui_tagger.h" class main_thread_callback_tag_writer : public main_thread_callback { public: main_thread_callback_tag_writer(const pfc::string_base & p_name, metadb_handle_list_cref p_handles, const pfc::string_list_impl & p_values) : m_tagger_dlg(new CTaggerDialog(p_name, p_handles, p_values)) { } void callback_run(); private: CTaggerDialog * m_tagger_dlg; }; class tag_writter : public file_info_filter { public: tag_writter(metadb_handle_list_cref p_handles, const pfc::string_list_impl & p_values, const pfc::list_base_const_t<const metadb_handle *> & p_skipped); bool apply_filter(metadb_handle_ptr p_location,t_filestats p_stats,file_info & p_info); private: metadb_handle_list m_handles; pfc::list_t<const char *> m_values; pfc::string_list_impl m_data; pfc::string8 m_fieldname; };
[ "qudeid@d0561270-fede-e5e2-f771-9cccb1c17e5b" ]
[ [ [ 1, 31 ] ] ]
327028910de3ffae4b0aaeacf2c0aacf49be63b9
c1a2953285f2a6ac7d903059b7ea6480a7e2228e
/deitel/appI/figI_03.cpp
19b620249f03cdfebae5572cb1eded74aa8753e2
[]
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
2,059
cpp
// Fig. I.03: figI_03.cpp // Create and manipulate Account objects. #include <iostream> using std::cin; using std::cout; using std::endl; // include definition of class Account from Account.h #include "Account.h" // function main begins program execution int main() { Account account1( 50 ); // create Account object // display initial balance of each object cout << "account1 balance: $" << account1.getBalance() << endl; int withdrawalAmount; // stores withdrawal amount read from user cout << "\nEnter withdrawal amount for account1: "; // prompt cin >> withdrawalAmount; // obtain user input cout << "\nattempting to subtract " << withdrawalAmount << " from account1 balance\n\n"; account1.debit( withdrawalAmount ); // try to subtract from account1 // display balances cout << "account1 balance: $" << account1.getBalance() << endl; return 0; // indicate 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. * **************************************************************************/
[ [ [ 1, 46 ] ] ]
6a3d5c33ed13f43325587320e081a902384c3e60
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Dependencies/Xerces/include/xercesc/util/UTFDataFormatException.hpp
136434075eedcf28e2456a9f3965ffec3e524169
[]
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
1,024
hpp
/* * Copyright 1999-2000,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: UTFDataFormatException.hpp 176026 2004-09-08 13:57:07Z peiyongz $ */ #if !defined(UTFDATAFORMATEXCEPTION_HPP) #define UTFDATAFORMATEXCEPTION_HPP #include <xercesc/util/XercesDefs.hpp> #include <xercesc/util/XMLException.hpp> XERCES_CPP_NAMESPACE_BEGIN MakeXMLException(UTFDataFormatException, XMLUTIL_EXPORT) XERCES_CPP_NAMESPACE_END #endif
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 34 ] ] ]
5fd324502a928682cdf6d6f67e2b91f86cb4f5bc
e842915fe71c1974def6b2025853faefded5ff6f
/src/oopframework/Texture.cpp
7b50199bf1044f195d422c10bf6c3f1ebe082d24
[]
no_license
leMax/CG-Assignments
83d18d49420f0d8acfa7ee328d5608e2efd29135
e6d1014b09ae2f0463d99cf1d3067e26d240ce5e
refs/heads/master
2021-01-10T20:26:17.262707
2010-11-02T13:57:01
2010-11-02T13:57:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
936
cpp
#include <Texture.h> Texture::Texture() : texID(0), texType(GL_TEXTURE_2D), minFilter(GL_NEAREST), magFilter(GL_NEAREST), mipMaps(false), name(""), refCnt(0), isPrivate(true) { } void Texture::bind() { if( !glIsEnabled( GL_TEXTURE_2D ) ) glEnable( GL_TEXTURE_2D ); glBindTexture( GL_TEXTURE_2D, texID ); } void Texture::unbind() { if( glIsEnabled( GL_TEXTURE_2D ) ) glDisable( GL_TEXTURE_2D ); glBindTexture( GL_TEXTURE_2D, NULL ); } unsigned Texture::getWidth() const { return width; } unsigned Texture::getHeight() const { return height; } bool Texture::operator ==( Texture const& rhs ) { if( texID == rhs.texID && texType == rhs.texType && minFilter == rhs.minFilter && magFilter == rhs.magFilter && mipMaps == rhs.mipMaps && name == rhs.name && isPrivate == rhs.isPrivate ) return true; else return false; } Texture::~Texture() { }
[ [ [ 1, 53 ] ] ]
a9c1e93046f82a2bbd41b5527637ddca37de6f0d
867f5533667cce30d0743d5bea6b0c083c073386
/jingxian-downloader/wxCURL/include/wxCURL/davtool.h
08ec0bb11d6ed571e3af7b658385785f9efdeb29
[]
no_license
mei-rune/jingxian-project
32804e0fa82f3f9a38f79e9a99c4645b9256e889
47bc7a2cb51fa0d85279f46207f6d7bea57f9e19
refs/heads/master
2022-08-12T18:43:37.139637
2009-12-11T09:30:04
2009-12-11T09:30:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,365
h
/* * davtool.h * wxCURL * * Created by Casey O'Donnell on Thu Jul 15 2004. * Copyright (c) 2004 Casey O'Donnell. All rights reserved. * * Licence: wxWidgets Licence */ // wxCurlDAVTool.h // ////////////////////////////////////////////////////////////////////// #ifndef _WXCURLDAVTOOL_H__INCLUDED_ #define _WXCURLDAVTOOL_H__INCLUDED_ #if defined(__GNUG__) && !defined(__APPLE__) #pragma interface "wxcurl/davtool.h" #endif #include "wxcurl/dav.h" class wxCurlDAVTool; class WXDLLIMPEXP_CURL wxCurlDAVFs { friend class wxCurlDAVTool; public: wxCurlDAVFs(); wxCurlDAVFs(const wxString& szHREF , const wxString& szStatus , const wxString& szCreationDate , const wxString& szLastModified , const long& iContentLength , const wxString& szContentType ); ~wxCurlDAVFs(); bool IsDirectory() const { return m_szContentType == _T("httpd/unix-directory"); } bool IsOK() const { return m_szStatus.Right(6) == _T("200 OK"); } wxString GetHREF() const { return m_szHREF; } wxString GetStatus() const { return m_szStatus; } wxDateTime GetCreationDate() const { return m_dtCreationDate; } wxDateTime GetLastModified() const { return m_dtLastModified; } long GetContentLength() const { return m_iContentLength; } wxString GetContentType() const { return m_szContentType; } wxString GetType() const { return m_szContentType.BeforeFirst('/'); } wxString GetSubType() const { return m_szContentType.AfterLast('/'); } protected: wxString m_szHREF; wxString m_szStatus; wxDateTime m_dtCreationDate; wxDateTime m_dtLastModified; long m_iContentLength; wxString m_szContentType; }; WX_DECLARE_OBJARRAY(wxCurlDAVFs, wxArrayDAVFs); // davtool.h: interface for the wxCurlDAVTool class. // ////////////////////////////////////////////////////////////////////// class WXDLLIMPEXP_CURL wxCurlDAVTool : public wxCurlDAV { public: wxCurlDAVTool(const wxString& szURL = wxEmptyString, const wxString& szUserName = wxEmptyString, const wxString& szPassword = wxEmptyString, wxEvtHandler* pEvtHandler = NULL, const bool& bSendUpdateEvents = false, const bool& bSendBeginEndEvents = false); virtual ~wxCurlDAVTool(); // More Complex Action Methods - These All Make Calls To: curl_easy_perform() // These routines have more 'intelligence' than simple WebDAV calls. bool GetDAVFs(wxArrayDAVFs& fs, const wxString& szRemoteLoc = wxEmptyString); bool Exists(const wxString& szRemoteLoc = wxEmptyString); bool IsDirectory(const wxString& szRemoteLoc = wxEmptyString); bool HasDirectory(const wxString& szRemoteLoc = wxEmptyString) { return IsDirectory(szRemoteLoc); } bool IsOk(const wxString& szRemoteLoc = wxEmptyString); wxDateTime GetLastModified(const wxString& szRemoteLoc = wxEmptyString); wxDateTime GetCreationDate(const wxString& szRemoteLoc = wxEmptyString); long GetContentLength(const wxString& szRemoteLoc = wxEmptyString); wxString GetContentType(const wxString& szRemoteLoc = wxEmptyString); protected: // XML Helper Methods bool ParseResponseXml(wxCurlDAVFs& fsItem, wxXmlNode* pNode); bool ParsePropstatXml(wxCurlDAVFs& fsItem, wxXmlNode* pNode); bool ParsePropsXml(wxCurlDAVFs& fsItem, wxXmlNode* pNode); private: }; #endif // _WXCURLDAVTOOL_H__INCLUDED_
[ "runner.mei@0dd8077a-353d-11de-b438-597f59cd7555" ]
[ [ [ 1, 104 ] ] ]
b2b90518aba6d3d04e7b46f7d3dc330e01f950f1
bc4919e48aa47e9f8866dcfc368a14e8bbabbfe2
/Open GL Basic Engine/source/glutFramework/glutFramework/basicObject.h
6d8173285c6cc7a1727eb5de7451e44744cfc7f3
[]
no_license
CorwinJV/rvbgame
0f2723ed3a4c1a368fc3bac69052091d2d87de77
a4fc13ed95bd3e5a03e3c6ecff633fe37718314b
refs/heads/master
2021-01-01T06:49:33.445550
2009-11-03T23:14:39
2009-11-03T23:14:39
32,131,378
0
0
null
null
null
null
UTF-8
C++
false
false
456
h
#ifndef BASICOBJECT_H #define BASICOBJECT_H enum direction { ne, se, sw, nw; } class basicObject { private: double strength; double health; int movementSpeed; int jumpDistance; int climbHeight; direction facing; int xpos, ypos; public: basicObject(); ~basicObject(); bool moveForward(); bool turnLeft(); bool turnRight(); bool crouch(); bool jump(); bool punch(); bool activate(); bool wait(); } #endif
[ "corwin.j@5457d560-9b84-11de-b17c-2fd642447241" ]
[ [ [ 1, 33 ] ] ]
ce5706cacf25e8ffb24c85e304c1d41ca7872248
8342f87cc7e048aa812910975c68babc6fb6c5d8
/client/Game2/Control/ConsoleActions.cpp
c2c9a27603a90b07b578a4b4ef45f7b263d1234e
[]
no_license
espes/hoverrace
1955c00961af4bb4f5c846f20e65ec9312719c08
7d5fd39ba688e2c537f35f7c723dedced983a98c
refs/heads/master
2021-01-23T13:23:03.710443
2010-12-19T22:26:12
2010-12-19T22:26:12
2,005,364
0
1
null
null
null
null
UTF-8
C++
false
false
3,611
cpp
// ConsoleActions.cpp // A collection of classes implementing the ConsoleAction template class // (just has to implement operator() and a constructor). These are all // actions to be performed when the user presses a control key. // // Copyright (c) 2010, Ryan Curtin // // Licensed under GrokkSoft HoverRace SourceCode License v1.0(the "License"); // you may not use this file except in compliance with the License. // // A copy of the license should have been attached to the package from which // you have taken this file. If you can not find the license you can not use // this file. // // // The author makes no representations about the suitability of // this software for any purpose. It is provided "as is" "AS IS", // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. // // See the License for the specific language governing permissions // and limitations under the License. // #include "StdAfx.h" #include "../../engine/Exception.h" #include "ConsoleActions.h" using namespace HoverRace::Client::Control; using namespace HoverRace::Client::HoverScript; //// Console actions ConsoleAction::ConsoleAction(std::string name, int listOrder, HighConsole* hc) : ControlAction(name, listOrder), hc(hc) { } void ConsoleAction::SetHighConsole(HighConsole* hc) { this->hc = hc; } ConsoleKeyAction::ConsoleKeyAction(std::string name, int listOrder, HighConsole* hc, OIS::KeyCode kc) : ConsoleAction(name, listOrder, hc), kc(kc) { } void ConsoleKeyAction::operator()(int eventValue) { #ifdef _WIN32 if(eventValue > 0) { HKL layout = GetKeyboardLayout(0); unsigned char state[256]; // Generally, in this case we would use GetKeyboardState(); however, // this causes bizarre issues because that method plays with the input // event stack and we end up with the shift key held down one character // too long. So this, while potentially slower, is actually accurate. // Plus users don't type too incredibly quickly. // TODO(ryan): #ifdef blocks for platform independence; depend on OIS unless on Windows for(int i = 0; i < 256; i++) state[i] = static_cast<unsigned char>(GetKeyState(i)); int vk = MapVirtualKeyEx(kc, 1, layout); int out; int ret = ToAsciiEx(vk, kc, state, (LPWORD) &out, 0, layout); if(ret == 1) hc->OnChar((char) out); } #else throw UnimplementedExn("ConsoleKeyAction::operator()(int)"); #endif } void ConsoleToggleAction::operator()(int eventValue) { if(eventValue > 0 && hc != NULL) { if(hc->IsVisible()) { // Delete old console action maps, re-add player action maps. controller->ClearActionMap(); for(size_t i = 0; i < oldMaps.size(); i++) controller->AddActionMap(oldMaps.at(i)); } else { // Save our old maps oldMaps = controller->GetActiveMaps(); controller->ClearActionMap(); controller->AddActionMap("console-keys"); controller->AddActionMap(_("Console")); } hc->ToggleVisible(); } } void ConsoleScrollAction::operator()(int eventValue) { if(eventValue > 0 && hc != NULL) { if(hc->IsVisible()) hc->Scroll(scrollStep); } } void ConsoleScrollTopAction::operator()(int eventValue) { if(eventValue > 0 && hc != NULL) { if(hc->IsVisible()) hc->ScrollTop(); } } void ConsoleScrollBottomAction::operator()(int eventValue) { if(eventValue > 0 && hc != NULL) { if(hc->IsVisible()) hc->ScrollBottom(); } } void ConsoleHelpAction::operator()(int eventValue) { if(eventValue > 0 && hc != NULL) { if(hc->IsVisible()) hc->ToggleHelp(); } }
[ "ryan@7d5085ce-8879-48fc-b0cc-67565f2357fd", "zoogie@7d5085ce-8879-48fc-b0cc-67565f2357fd" ]
[ [ [ 1, 26 ], [ 29, 46 ], [ 48, 57 ], [ 59, 64 ], [ 68, 75 ], [ 77, 118 ] ], [ [ 27, 28 ], [ 47, 47 ], [ 58, 58 ], [ 65, 67 ], [ 76, 76 ], [ 119, 119 ] ] ]
2eb9fd743b45c62cf94c9a7206b87a6ab481cd74
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/addons/pa/ParticleUniverse/include/ParticleRenderers/ParticleUniverseEntityRendererFactory.h
1913b2715df227ca1d279ef85da3aaa2313864ab
[]
no_license
dbabox/aomi
dbfb46c1c9417a8078ec9a516cc9c90fe3773b78
4cffc8e59368e82aed997fe0f4dcbd7df626d1d0
refs/heads/master
2021-01-13T14:05:10.813348
2011-06-07T09:36:41
2011-06-07T09:36:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,085
h
/* ----------------------------------------------------------------------------------------------- This source file is part of the Particle Universe product. Copyright (c) 2010 Henry van Merode Usage of this program is licensed under the terms of the Particle Universe Commercial License. You can find a copy of the Commercial License in the Particle Universe package. ----------------------------------------------------------------------------------------------- */ #ifndef __PU_ENTITY_RENDERER_FACTORY_H__ #define __PU_ENTITY_RENDERER_FACTORY_H__ #include "ParticleUniversePrerequisites.h" #include "ParticleUniverseRendererFactory.h" #include "ParticleUniverseEntityRenderer.h" #include "ParticleUniverseEntityRendererTokens.h" namespace ParticleUniverse { /** Factory class responsible for creating a EntityRenderer. */ class _ParticleUniverseExport EntityRendererFactory : public ParticleRendererFactory { public: EntityRendererFactory(void) {}; virtual ~EntityRendererFactory(void) {}; /** See ParticleRendererFactory */ Ogre::String getRendererType(void) const { return "Entity"; } /** See ParticleRendererFactory */ ParticleRenderer* createRenderer(void) { return _createRenderer<EntityRenderer>(); } /** See ScriptReader */ virtual bool translateChildProperty(Ogre::ScriptCompiler* compiler, const Ogre::AbstractNodePtr &node) { return mEntityRendererTranslator.translateChildProperty(compiler, node); }; /** See ScriptReader */ virtual bool translateChildObject(Ogre::ScriptCompiler* compiler, const Ogre::AbstractNodePtr &node) { return mEntityRendererTranslator.translateChildObject(compiler, node); }; /* */ virtual void write(ParticleScriptSerializer* serializer, const IElement* element) { // Delegate mEntityRendererWriter.write(serializer, element); } protected: EntityRendererWriter mEntityRendererWriter; EntityRendererTranslator mEntityRendererTranslator; }; } #endif
[ [ [ 1, 68 ] ] ]
2bbd70cc5d0ba605640b347eb04c92032c970afd
011359e589f99ae5fe8271962d447165e9ff7768
/src/burner/win32/progress.cpp
52627737b59788ca8e8866af2cb68e9d9c340e26
[]
no_license
PS3emulators/fba-next-slim
4c753375fd68863c53830bb367c61737393f9777
d082dea48c378bddd5e2a686fe8c19beb06db8e1
refs/heads/master
2021-01-17T23:05:29.479865
2011-12-01T18:16:02
2011-12-01T18:16:02
2,899,840
1
0
null
null
null
null
UTF-8
C++
false
false
5,776
cpp
#include "burner.h" static HWND hProgressDlg = NULL; static HANDLE hProgressThread = NULL; static DWORD dwProgressThreadID = 0; int nProgressPosBurn, nProgressPosBurner; int nProgressMin, nProgressMax; static HANDLE hEvent = NULL; // ---------------------------------------------------------------------------- // Callbacks for burn library static int __cdecl ProgressSetRangeBurn(double dProgressRange) { if (hProgressThread == NULL || hProgressDlg == NULL) { return 1; } nProgressMin = -(int)((double)nProgressMax * dProgressRange); SendDlgItemMessage(hProgressDlg, IDC_WAIT_PROG, PBM_SETRANGE32, nProgressMin, nProgressMax); return 0; } static int __cdecl ProgressUpdateBurn(double dProgress, const TCHAR* pszText, bool bAbs) { if (hProgressThread == NULL || hProgressDlg == NULL) { return 1; } if (pszText) { SendDlgItemMessage(hProgressDlg, IDC_WAIT_LABEL_B2, WM_SETTEXT, 0, (LPARAM)pszText); SetWindowText(hScrnWnd, pszText); } if (bAbs) { nProgressPosBurn = (int)((double)(-nProgressMin) * dProgress); if (nProgressPosBurn > -nProgressMin) { nProgressPosBurn = -nProgressMin; } SendDlgItemMessage(hProgressDlg, IDC_WAIT_PROG, PBM_SETPOS, (WPARAM)(nProgressMin + nProgressPosBurn + nProgressPosBurner), 0); } else { if (dProgress) { nProgressPosBurn += (int)((double)(-nProgressMin) * dProgress); if (nProgressPosBurn > -nProgressMin) { nProgressPosBurn = -nProgressMin; } SendDlgItemMessage(hProgressDlg, IDC_WAIT_PROG, PBM_SETPOS, (WPARAM)(nProgressMin + nProgressPosBurn + nProgressPosBurner), 0); } } return 0; } // ---------------------------------------------------------------------------- // Callback for burner int ProgressUpdateBurner(double dProgress, const TCHAR* pszText, bool bAbs) { if (hProgressThread == NULL || hProgressDlg == NULL) { return 1; } if (pszText) { SendDlgItemMessage(hProgressDlg, IDC_WAIT_LABEL_B2, WM_SETTEXT, 0, (LPARAM)pszText); SetWindowText(hScrnWnd, pszText); } if (bAbs) { nProgressPosBurner = (int)((double)nProgressMax * dProgress); if (nProgressPosBurner > nProgressMax) { nProgressPosBurner = nProgressMax; } SendDlgItemMessage(hProgressDlg, IDC_WAIT_PROG, PBM_SETPOS, (WPARAM)(nProgressMin + nProgressPosBurn + nProgressPosBurner), 0); } else { if (dProgress) { if (nProgressPosBurner > nProgressMax) { nProgressPosBurner = nProgressMax; } nProgressPosBurner += (int)((double)nProgressMax * dProgress); SendDlgItemMessage(hProgressDlg, IDC_WAIT_PROG, PBM_SETPOS, (WPARAM)(nProgressMin + nProgressPosBurn + nProgressPosBurner), 0); } } return 0; } // ---------------------------------------------------------------------------- // Code that runs in a seperate thread static INT_PTR CALLBACK ProgressProc(HWND hDlg, UINT Msg, WPARAM /*wParam*/, LPARAM /*lParam*/) { if (Msg == WM_INITDIALOG) { TCHAR szText[MAX_PATH] = _T(""); hProgressDlg = hDlg; // ==> load custom resource, added by regret HBITMAP hBitmap = (HBITMAP)LoadImage(hAppInst, _T("res\\misc.bmp"), IMAGE_BITMAP, 80, 60, LR_LOADFROMFILE); if (!hBitmap) { hBitmap = LoadBitmap(hAppInst, MAKEINTRESOURCE(BMP_MISC)); } SendDlgItemMessage(hDlg, IDC_MISC, STM_SETIMAGE, IMAGE_BITMAP, (LPARAM)hBitmap); // <== load custom resource SendDlgItemMessage(hDlg, IDC_WAIT_PROG, PBM_SETRANGE32, nProgressMin, nProgressMax); _stprintf(szText, FBALoadStringEx(IDS_PROGRESS_LOADING), BurnDrvGetText(DRV_NAME)); SendDlgItemMessage(hDlg, IDC_WAIT_LABEL_B1, WM_SETTEXT, 0, (LPARAM)szText); ShowWindow(GetDlgItem(hDlg, IDC_WAIT_LABEL_B1), TRUE); ShowWindow(GetDlgItem(hDlg, IDC_WAIT_LABEL_B2), TRUE); wndInMid(hDlg, hScrnWnd); SetForegroundWindow(hDlg); SetWindowPos(hDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); return TRUE; } return FALSE; } static DWORD WINAPI DoProgress(LPVOID) { MSG msg; BOOL bRet; // Raise the thread priority for this thread SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST); nProgressMin = 0; nProgressMax = 1 << 30; nProgressPosBurn = 0; nProgressPosBurner = 0; BurnExtProgressRangeCallback = ProgressSetRangeBurn; BurnExtProgressUpdateCallback = ProgressUpdateBurn; FBACreateDialog(IDD_WAIT, NULL, (DLGPROC)ProgressProc); if (hEvent) { SetEvent(hEvent); } while (1) { bRet = GetMessage(&msg, NULL, 0, 0); if (bRet != 0 && bRet != -1) { // See if we need to end the thread if (msg.message == (WM_APP + 0)) { break; } TranslateMessage(&msg); DispatchMessage(&msg); } } DestroyWindow(hProgressDlg); return 0; } // ---------------------------------------------------------------------------- int ProgressCreate() { if (hProgressDlg || hProgressThread) { return 1; } hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); hProgressThread = CreateThread(NULL, 0, DoProgress, NULL, THREAD_TERMINATE, &dwProgressThreadID); WaitForSingleObject(hEvent, 15000); CloseHandle(hEvent); hEvent = NULL; return 0; } int ProgressDestroy() { if (!hProgressThread) { return 0; } // Signal the prgress thread to end PostThreadMessage(dwProgressThreadID, WM_APP + 0, 0, 0); // Wait for the thread to finish if (WaitForSingleObject(hProgressThread, 15000) != WAIT_OBJECT_0) { // If the thread doesn't finish within 15 seconds, forcibly kill it TerminateThread(hProgressThread, 1); } BurnExtProgressRangeCallback = NULL; BurnExtProgressUpdateCallback = NULL; hProgressDlg = NULL; CloseHandle(hProgressThread); hProgressThread = NULL; dwProgressThreadID = 0; return 0; }
[ [ [ 1, 214 ] ] ]
0efe0544a42be7a8a2eb1a1e55775a9147e64a68
222bc22cb0330b694d2c3b0f4b866d726fd29c72
/src/brookbox/wm2/WmlTerrainVertex.h
ebd79de57fa774fdcd77dadf0d77f3bebcbd13b5
[ "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference" ]
permissive
darwin/inferno
02acd3d05ca4c092aa4006b028a843ac04b551b1
e87017763abae0cfe09d47987f5f6ac37c4f073d
refs/heads/master
2021-03-12T22:15:47.889580
2009-04-17T13:29:39
2009-04-17T13:29:39
178,477
2
0
null
null
null
null
UTF-8
C++
false
false
867
h
// Magic Software, Inc. // http://www.magic-software.com // http://www.wild-magic.com // Copyright (c) 2003. All Rights Reserved // // The Wild Magic Library (WML) source code is supplied under the terms of // the license agreement http://www.magic-software.com/License/WildMagic.pdf // and may not be copied or disclosed except in accordance with the terms of // that agreement. #ifndef WMLTERRAINVERTEX_H #define WMLTERRAINVERTEX_H #include "WmlSystem.h" namespace Wml { class WML_ITEM TerrainVertex { public: TerrainVertex (); void SetDependent (int i, TerrainVertex* pkDependent); TerrainVertex* GetDependent (int i); bool GetEnabled () const; void Enable (); void Disable (); protected: TerrainVertex* m_akDependent[2]; bool m_bEnabled; }; #include "WmlTerrainVertex.inl" } #endif
[ [ [ 1, 39 ] ] ]
1ffa54120adb72dd6712c1e4c0292a1b894a9ccb
38926bfe477f933a307f51376dd3c356e7893ffc
/Source/GameDLL/Menus/GameNetworkProfile.h
b740df8f8e5bd4782d666fe49eb89dc0724adec1
[]
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
UTF-8
C++
false
false
6,144
h
/************************************************************************* Crytek Source File. Copyright (C), Crytek Studios, 2001-2007. ------------------------------------------------------------------------- $Id$ $DateTime$ Description: Game-side part of Palyer's network profile ------------------------------------------------------------------------- History: - 03/2007: Created by Stas Spivakov *************************************************************************/ #ifndef __GAMENETWORKPROFILE_H__ #define __GAMENETWORKPROFILE_H__ #pragma once #include "INetworkService.h" class CMPHub; enum EChatUserType { eCUT_buddy, eCUT_general, eCUT_ignore }; struct SChatUser { int m_id; string m_nick; EUserStatus m_status; string m_location; bool m_foreign; }; enum EUserInfoSource { eUIS_backend, eUIS_chat }; struct SUserStats { SUserStats():m_played(0),m_accuracy(0),m_killsPerMinute(0),m_kills(0),m_deaths(0) {} int m_played; string m_gameMode; string m_map; string m_weapon; string m_vehicle; string m_suitMode; float m_accuracy; float m_killsPerMinute; int m_kills; int m_deaths; }; struct SUserInfo { SUserInfo(): m_basic(true),m_foreignName(false) { } string m_nick; string m_country; SUserStats m_stats; // flag for displaying bool m_foreignName; // bool m_basic;//if false - means we have full info EUserInfoSource m_source;//source... - info will be re-read from backend in some cases if this is eUIS_chat CTimeValue m_expires;//non-basic information expires at this point }; struct SStoredUserInfo { int m_kills; int m_deaths; int m_hits; int m_shots; int m_played; int m_mode; int m_map; int m_weapon; int m_vehicle; int m_suitmode; void Serialize(struct IStoredSerialize* ser); }; struct INProfileUI { virtual void AddBuddy(SChatUser s)=0; virtual void UpdateBuddy(SChatUser s)=0; virtual void RemoveBuddy(int id)=0; virtual void AddIgnore(SChatUser s)=0; virtual void RemoveIgnore(int id)=0; virtual void ProfileInfo(int id, SUserInfo ui)=0; virtual void SearchResult(int id, const char* nick)=0; virtual void OnMessage(int id, const char* message)=0; virtual void SearchCompleted()=0; virtual void ShowError(const char* descr)=0; virtual void OnAuthRequest(int id, const char* nick, const char* message)=0; virtual void AddFavoriteServer(uint ip, ushort port)=0; virtual void AddRecentServer(uint ip, ushort port)=0; }; struct SStoredServer { SStoredServer(uint i = 0, ushort p = 0):ip(i),port(p){} int ip; int port; bool operator==(const SStoredServer& svr) { return ip == svr.ip && port == svr.port; } void Serialize(struct IStoredSerialize* ser); }; static const char* AUTO_INVITE_TEXT = "Crysis auto generated invitation"; class CGameNetworkProfile { private: typedef std::map<int,SUserInfo> TUserInfoMap; template<class T> class TStoredArray; struct SBuddies; struct SChat; struct SChatText; struct SStoredServerLists; struct SUserInfoReader; struct SStorageQuery { SStorageQuery(CGameNetworkProfile* p):m_parent(p) { m_parent->m_queries.push_back(this); } virtual ~SStorageQuery() { if(m_parent) { stl::find_and_erase(m_parent->m_queries,this); m_parent->OnEndQuery(); } } CGameNetworkProfile *m_parent; }; typedef std::map<int, SChatText> TChatTextMap; public: CGameNetworkProfile(CMPHub* hub); ~CGameNetworkProfile(); void Login(const char* login, const char* password); void LoginProfile(const char* email, const char* password, const char* profile); void Register(const char* login, const char* email, const char* pass, const char* country, SRegisterDayOfBirth dob); void Logoff(); void AcceptBuddy(int id, bool accept); void RequestBuddy(const char* nick, const char* reason); void RequestBuddy(int id, const char* reason); void RemoveBuddy(const char* nick); void AddIgnore(const char* nick); void StopIgnore(const char* nick); void QueryUserInfo(const char* nick); void QueryUserInfo(int id); void SendBuddyMessage(int id, const char* message); void SearchUsers(const char* nick); bool CanInvite(const char* nick); bool CanIgnore(const char* nick); bool IsIgnored(const char* nick); bool CanInvite(int id); bool CanIgnore(int id); bool GetUserInfo(int id, SUserInfo& info); bool GetUserInfo(const char* nick, SUserInfo& info, int &id); void SetPlayingStatus(uint ip, ushort port, ushort publicport, const char* game_type); void SetChattingStatus(); void OnUserStats(int id, const SUserStats& stats, EUserInfoSource src, const char* country =""); void OnUserNick(int profile, const char* user); void InitUI(INProfileUI* a); void DestroyUI(); void AddFavoriteServer(uint ip, ushort port); void RemoveFavoriteServer(uint ip, ushort port); void AddRecentServer(uint ip, ushort port); bool IsLoggedIn()const; bool IsLoggingIn()const; const char* GetLogin()const; const char* GetPassword()const; const char* GetCountry()const; const int GetProfileId()const; void RetrievePassword(const char *email); bool IsDead()const; const SUserStats& GetMyStats()const; bool GetFavoriteServers(std::vector<SStoredServer>& svr); private: void OnLoggedIn(int id, const char* nick); void OnEndQuery(); void CleanUpQueries(); private: CMPHub* m_hub; INetworkProfile* m_profile; string m_login; string m_password; string m_country; int m_profileId; bool m_loggingIn; SUserStats m_stats; std::auto_ptr<SBuddies> m_buddies; std::auto_ptr<SStoredServerLists> m_stroredServers; std::auto_ptr<SUserInfoReader> m_infoReader; std::vector<SStorageQuery*> m_queries; }; #endif //__GAMENETWORKPROFILE_H__
[ "[email protected]", "kkirst@c5e09591-5635-0410-80e3-0b71df3ecc31" ]
[ [ [ 1, 36 ], [ 44, 44 ], [ 62, 63 ], [ 94, 106 ], [ 108, 114 ], [ 123, 124 ], [ 127, 131 ], [ 135, 138 ], [ 142, 142 ], [ 144, 149 ], [ 151, 151 ], [ 154, 163 ], [ 166, 173 ], [ 177, 179 ], [ 181, 182 ], [ 185, 187 ], [ 192, 199 ], [ 212, 213 ], [ 215, 220 ], [ 223, 223 ], [ 226, 228 ], [ 230, 233 ] ], [ [ 37, 43 ], [ 45, 61 ], [ 64, 93 ], [ 107, 107 ], [ 115, 122 ], [ 125, 126 ], [ 132, 134 ], [ 139, 141 ], [ 143, 143 ], [ 150, 150 ], [ 152, 153 ], [ 164, 165 ], [ 174, 176 ], [ 180, 180 ], [ 183, 184 ], [ 188, 191 ], [ 200, 211 ], [ 214, 214 ], [ 221, 222 ], [ 224, 225 ], [ 229, 229 ] ] ]
930946246c072fe69ace2d09d8ed9d5bcabbb32a
266f56e33501ad66eeb47275857433e0bec84243
/master/ramwatch.cpp
b4dd7862bac847d5c2f23dc6458170219700e74b
[]
no_license
mauzus/dega-s
fc245abeaddcf1a26f4fc52feb17edf507ac349b
e1f43c7f40561da600d9bc92c200d912f28e5438
refs/heads/master
2020-06-08T12:16:41.220929
2011-11-10T08:50:24
2011-11-10T08:50:24
32,238,913
0
0
null
null
null
null
UTF-8
C++
false
false
35,717
cpp
//#include "../PsxCommon.h" //#ifdef WIN32 //#include "Win32.h" //#endif #include "app.h" #include "resource.h" #include "ramsearch.h" #include "ramwatch.h" #include <string> using std::min; using std::max; /* #include <commctrl.h> #pragma comment(lib, "comctl32.lib") #include <shellapi.h> #pragma comment(lib, "shell32.lib") #include <commdlg.h> #pragma comment(lib, "comdlg32.lib") */ static HMENU ramwatchmenu; static HMENU rwrecentmenu; /*static*/ HACCEL RamWatchAccels = NULL; char rw_recent_files[MAX_RECENT_WATCHES][1024]; //char Watch_Dir[1024]=""; bool RWfileChanged = false; //Keeps track of whether the current watch file has been changed, if so, ramwatch will prompt to save changes bool AutoRWLoad = false; //Keeps track of whether Auto-load is checked bool RWSaveWindowPos = false; //Keeps track of whether Save Window position is checked char currentWatch[1024]; int ramw_x, ramw_y; //Used to store ramwatch dialog window positions AddressWatcher rswatches[MAX_WATCH_COUNT]; int WatchCount=0; char applicationPath[2048]; struct InitRamWatch { InitRamWatch() { GetModuleFileName(NULL, applicationPath, 2048); } } initRamWatch; HWND RamWatchHWnd; #define gamefilename EmuRomName #define hWnd hFrameWnd #define hInst hAppInst static char Str_Tmp [1024]; void init_list_box(HWND Box, const char* Strs[], int numColumns, int *columnWidths); //initializes the ram search and/or ram watch listbox #define MESSAGEBOXPARENT (RamWatchHWnd ? RamWatchHWnd : hWnd) bool QuickSaveWatches(); bool ResetWatches(); void RefreshWatchListSelectedCountControlStatus(HWND hDlg); unsigned int GetCurrentValue(AddressWatcher& watch) { return ReadValueAtHardwareAddress(watch.Address, watch.Size == 'd' ? 4 : watch.Size == 'w' ? 2 : 1); } bool IsSameWatch(const AddressWatcher& l, const AddressWatcher& r) { if (r.Size == 'S') return false; return ((l.Address == r.Address) && (l.Size == r.Size) && (l.Type == r.Type)/* && (l.WrongEndian == r.WrongEndian)*/); } bool VerifyWatchNotAlreadyAdded(const AddressWatcher& watch) { for (int j = 0; j < WatchCount; j++) { if (IsSameWatch(rswatches[j], watch)) { if(RamWatchHWnd) SetForegroundWindow(RamWatchHWnd); return false; } } return true; } bool InsertWatch(const AddressWatcher& Watch, const char *Comment) { if(!VerifyWatchNotAlreadyAdded(Watch)) return false; if(WatchCount >= MAX_WATCH_COUNT) return false; int i = WatchCount++; AddressWatcher& NewWatch = rswatches[i]; NewWatch = Watch; //if (NewWatch.comment) free(NewWatch.comment); NewWatch.comment = (char *) malloc(strlen(Comment)+2); NewWatch.CurValue = GetCurrentValue(NewWatch); strcpy(NewWatch.comment, Comment); ListView_SetItemCount(GetDlgItem(RamWatchHWnd,IDC_WATCHLIST),WatchCount); RWfileChanged=true; return true; } LRESULT CALLBACK PromptWatchNameProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) //Gets the description of a watched address { RECT r; RECT r2; int dx1, dy1, dx2, dy2; switch(uMsg) { case WM_INITDIALOG: //Clear_Sound_Buffer(); GetWindowRect(hWnd, &r); dx1 = (r.right - r.left) / 2; dy1 = (r.bottom - r.top) / 2; GetWindowRect(hDlg, &r2); dx2 = (r2.right - r2.left) / 2; dy2 = (r2.bottom - r2.top) / 2; //SetWindowPos(hDlg, NULL, max(0, r.left + (dx1 - dx2)), max(0, r.top + (dy1 - dy2)), NULL, NULL, SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW); SetWindowPos(hDlg, NULL, r.left, r.top, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW); strcpy(Str_Tmp,"Enter a name for this RAM address."); SendDlgItemMessage(hDlg,IDC_PROMPT_TEXT,WM_SETTEXT,0,(LPARAM)Str_Tmp); strcpy(Str_Tmp,""); SendDlgItemMessage(hDlg,IDC_PROMPT_TEXT2,WM_SETTEXT,0,(LPARAM)Str_Tmp); return true; break; case WM_COMMAND: switch(LOWORD(wParam)) { case IDOK: { GetDlgItemText(hDlg,IDC_PROMPT_EDIT,Str_Tmp,80); InsertWatch(rswatches[WatchCount],Str_Tmp); EndDialog(hDlg, true); return true; break; } case IDCANCEL: EndDialog(hDlg, false); return false; break; } break; case WM_CLOSE: EndDialog(hDlg, false); return false; break; } return false; } bool InsertWatch(const AddressWatcher& Watch, HWND parent) { if(!VerifyWatchNotAlreadyAdded(Watch)) return false; if(!parent) parent = RamWatchHWnd; if(!parent) parent = hWnd; int prevWatchCount = WatchCount; rswatches[WatchCount] = Watch; rswatches[WatchCount].CurValue = GetCurrentValue(rswatches[WatchCount]); DialogBox(hInst, MAKEINTRESOURCE(IDD_PROMPT), parent, (DLGPROC) PromptWatchNameProc); return WatchCount > prevWatchCount; } void Update_RAM_Watch() { BOOL watchChanged[MAX_WATCH_COUNT] = {0}; if(WatchCount) { // update cached values and detect changes to displayed listview items for(int i = 0; i < WatchCount; i++) { unsigned int prevCurValue = rswatches[i].CurValue; unsigned int newCurValue = GetCurrentValue(rswatches[i]); if(prevCurValue != newCurValue) { rswatches[i].CurValue = newCurValue; watchChanged[i] = TRUE; } } } // refresh any visible parts of the listview box that changed HWND lv = GetDlgItem(RamWatchHWnd,IDC_WATCHLIST); int top = ListView_GetTopIndex(lv); int bottom = top + ListView_GetCountPerPage(lv) + 1; // +1 is so we will update a partially-displayed last item if(top < 0) top = 0; if(bottom > WatchCount) bottom = WatchCount; int start = -1; for(int i = top; i <= bottom; i++) { if(start == -1) { if(i != bottom && watchChanged[i]) { start = i; //somethingChanged = true; } } else { if(i == bottom || !watchChanged[i]) { ListView_RedrawItems(lv, start, i-1); start = -1; } } } } bool AskSave() { //This function asks to save changes if the watch file contents have changed //returns false only if a save was attempted but failed or was cancelled if (RWfileChanged) { int answer = MessageBox(MESSAGEBOXPARENT, "Save Changes?", "Ram Watch", MB_YESNOCANCEL); if(answer == IDYES) if(!QuickSaveWatches()) return false; return (answer != IDCANCEL); } return true; } void WriteRecentRWFiles() { char str[2048]; for (int i = 0; i < MAX_RECENT_WATCHES; i++) { sprintf(str, "recentWatch%d", i+1); //regSetStringValue(str, &rw_recent_files[i][0]); TODO } } void UpdateRW_RMenu(HMENU menu, unsigned int mitem, unsigned int baseid) { MENUITEMINFO moo; int x; moo.cbSize = sizeof(moo); moo.fMask = MIIM_SUBMENU | MIIM_STATE; GetMenuItemInfo(GetSubMenu(ramwatchmenu, 0), mitem, FALSE, &moo); moo.hSubMenu = menu; moo.fState = strlen(rw_recent_files[0]) ? MFS_ENABLED : MFS_GRAYED; SetMenuItemInfo(GetSubMenu(ramwatchmenu, 0), mitem, FALSE, &moo); // Remove all recent files submenus for(x = 0; x < MAX_RECENT_WATCHES; x++) { RemoveMenu(menu, baseid + x, MF_BYCOMMAND); } // Recreate the menus for(x = MAX_RECENT_WATCHES - 1; x >= 0; x--) { char tmp[128 + 5]; // Skip empty strings if(!strlen(rw_recent_files[x])) { continue; } moo.cbSize = sizeof(moo); moo.fMask = MIIM_DATA | MIIM_ID | MIIM_TYPE; // Fill in the menu text. if(strlen(rw_recent_files[x]) < 128) { sprintf(tmp, "&%d. %s", ( x + 1 ) % 10, rw_recent_files[x]); } else { sprintf(tmp, "&%d. %s", ( x + 1 ) % 10, rw_recent_files[x] + strlen( rw_recent_files[x] ) - 127); } // Insert the menu item moo.cch = strlen(tmp); moo.fType = 0; moo.wID = baseid + x; moo.dwTypeData = tmp; InsertMenuItem(menu, 0, 1, &moo); } // I don't think one function shall do so many things in a row // WriteRecentRWFiles(); // write recent menu to ini } void UpdateRWRecentArray(const char* addString, unsigned int arrayLen, HMENU menu, unsigned int menuItem, unsigned int baseId) { const size_t len = 1024; // Avoid magic numbers // Try to find out if the filename is already in the recent files list. for(unsigned int x = 0; x < arrayLen; x++) { if(strlen(rw_recent_files[x])) { if(!strncmp(rw_recent_files[x], addString, 1024)) // Item is already in list. { // If the filename is in the file list don't add it again. // Move it up in the list instead. int y; char tmp[len]; // Save pointer. strncpy(tmp, rw_recent_files[x], len); for(y = x; y; y--) { // Move items down. strncpy(rw_recent_files[y],rw_recent_files[y - 1], len); } // Put item on top. strncpy(rw_recent_files[0],tmp, len); // Update the recent files menu UpdateRW_RMenu(menu, menuItem, baseId); return; } } } // The filename wasn't found in the list. That means we need to add it. // Move the other items down. for(unsigned int x = arrayLen - 1; x; x--) { strncpy(rw_recent_files[x],rw_recent_files[x - 1], len); } // Add the new item. strncpy(rw_recent_files[0], addString, len); // Update the recent files menu UpdateRW_RMenu(menu, menuItem, baseId); } void RWAddRecentFile(const char *filename) { UpdateRWRecentArray(filename, MAX_RECENT_WATCHES, rwrecentmenu, RAMMENU_FILE_RECENT, RW_MENU_FIRST_RECENT_FILE); } void OpenRWRecentFile(int memwRFileNumber) { if(!ResetWatches()) return; int rnum = memwRFileNumber; if ((unsigned int)rnum >= MAX_RECENT_WATCHES) return; //just in case char* x; while(true) { x = rw_recent_files[rnum]; if (!*x) return; //If no recent files exist just return. Useful for Load last file on startup (or if something goes screwy) if (rnum) //Change order of recent files if not most recent { RWAddRecentFile(x); rnum = 0; } else { break; } } strcpy(currentWatch,x); strcpy(Str_Tmp,currentWatch); //loadwatches here FILE *WatchFile = fopen(Str_Tmp,"rb"); if (!WatchFile) { int answer = MessageBox(MESSAGEBOXPARENT,"Error opening file.","ERROR",MB_OKCANCEL); if (answer == IDOK) { rw_recent_files[rnum][0] = '\0'; //Clear file from list if (rnum) //Update the ramwatch list RWAddRecentFile(rw_recent_files[0]); else RWAddRecentFile(rw_recent_files[1]); } return; } const char DELIM = '\t'; AddressWatcher Temp; char mode; fgets(Str_Tmp,1024,WatchFile); sscanf(Str_Tmp,"%c%*s",&mode); //if ((mode == '1' && !(SegaCD_Started)) || (mode == '2' && !(_32X_Started))) //{ // char Device[8]; // strcpy(Device,(mode > '1')?"32X":"SegaCD"); // sprintf(Str_Tmp,"Warning: %s not started. \nWatches for %s addresses will be ignored.",Device,Device); // MessageBox(MESSAGEBOXPARENT,Str_Tmp,"Possible Device Mismatch",MB_OK); //} int WatchAdd; fgets(Str_Tmp,1024,WatchFile); sscanf(Str_Tmp,"%d%*s",&WatchAdd); WatchAdd+=WatchCount; for (int i = WatchCount; i < WatchAdd; i++) { while (i < 0) i++; do { fgets(Str_Tmp,1024,WatchFile); } while (Str_Tmp[0] == '\n'); sscanf(Str_Tmp,"%*05X%*c%04X%*c%c%*c%c%*c%d",&(Temp.Address),&(Temp.Size),&(Temp.Type),(int*)&(Temp.WrongEndian)); Temp.WrongEndian = 0; char *Comment = strrchr(Str_Tmp,DELIM) + 1; *strrchr(Comment,'\n') = '\0'; InsertWatch(Temp,Comment); } fclose(WatchFile); if (RamWatchHWnd) { ListView_SetItemCount(GetDlgItem(RamWatchHWnd,IDC_WATCHLIST),WatchCount); RefreshWatchListSelectedCountControlStatus(RamWatchHWnd); } RWfileChanged=false; return; } static int Change_File_L(char *Dest, char *Dir, const char *Titre, const char *Filter, const char *Ext, HWND hwnd) { OPENFILENAME ofn; SetCurrentDirectory(applicationPath); if (!strcmp(Dest, "")) { strcpy(Dest, "default."); strcat(Dest, Ext); } memset(&ofn, 0, sizeof(OPENFILENAME)); ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = hwnd; ofn.hInstance = hInst; ofn.lpstrFile = Dest; ofn.nMaxFile = 2047; ofn.lpstrFilter = Filter; ofn.nFilterIndex = 1; ofn.lpstrInitialDir = Dir; ofn.lpstrTitle = Titre; ofn.lpstrDefExt = Ext; ofn.Flags = OFN_FILEMUSTEXIST | OFN_HIDEREADONLY; if (GetOpenFileName(&ofn)) return 1; return 0; } static int Change_File_S(char *Dest, char *Dir, const char *Titre, const char *Filter, const char *Ext, HWND hwnd) { OPENFILENAME ofn; SetCurrentDirectory(applicationPath); if (!strcmp(Dest, "")) { strcpy(Dest, "default."); strcat(Dest, Ext); } memset(&ofn, 0, sizeof(OPENFILENAME)); ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = hwnd; ofn.hInstance = hInst; ofn.lpstrFile = Dest; ofn.nMaxFile = 2047; ofn.lpstrFilter = Filter; ofn.nFilterIndex = 1; ofn.lpstrInitialDir = Dir; ofn.lpstrTitle = Titre; ofn.lpstrDefExt = Ext; ofn.Flags = OFN_PATHMUSTEXIST | OFN_HIDEREADONLY; if (GetSaveFileName(&ofn)) return 1; return 0; } bool Save_Watches() { const char* slash = max(strrchr(gamefilename, '|'), max(strrchr(gamefilename, '\\'), strrchr(gamefilename, '/'))); strcpy(Str_Tmp,slash ? slash+1 : gamefilename); char* dot = strrchr(Str_Tmp, '.'); if(dot) *dot = 0; strcat(Str_Tmp,".wch"); if(Change_File_S(Str_Tmp, applicationPath, "Save Watches", "Watchlist\0*.wch\0All Files\0*.*\0\0", "wch", RamWatchHWnd)) { FILE *WatchFile = fopen(Str_Tmp,"r+b"); if (!WatchFile) WatchFile = fopen(Str_Tmp,"w+b"); fputc('\n',WatchFile); strcpy(currentWatch,Str_Tmp); RWAddRecentFile(currentWatch); sprintf(Str_Tmp,"%d\n",WatchCount); fputs(Str_Tmp,WatchFile); const char DELIM = '\t'; for (int i = 0; i < WatchCount; i++) { sprintf(Str_Tmp,"%05X%c%04X%c%c%c%c%c%d%c%s\n",i,DELIM,rswatches[i].Address,DELIM,rswatches[i].Size,DELIM,rswatches[i].Type,DELIM,rswatches[i].WrongEndian,DELIM,rswatches[i].comment); fputs(Str_Tmp,WatchFile); } fclose(WatchFile); RWfileChanged=false; //TODO: Add to recent list function call here return true; } return false; } bool QuickSaveWatches() { if (RWfileChanged==false) return true; //If file has not changed, no need to save changes if (currentWatch[0] == '\0') //If there is no currently loaded file, run to Save as and then return { return Save_Watches(); } strcpy(Str_Tmp,currentWatch); FILE *WatchFile = fopen(Str_Tmp,"r+b"); if (!WatchFile) WatchFile = fopen(Str_Tmp,"w+b"); fputc('\n',WatchFile); sprintf(Str_Tmp,"%d\n",WatchCount); fputs(Str_Tmp,WatchFile); const char DELIM = '\t'; for (int i = 0; i < WatchCount; i++) { sprintf(Str_Tmp,"%05X%c%04X%c%c%c%c%c%d%c%s\n",i,DELIM,rswatches[i].Address,DELIM,rswatches[i].Size,DELIM,rswatches[i].Type,DELIM,rswatches[i].WrongEndian,DELIM,rswatches[i].comment); fputs(Str_Tmp,WatchFile); } fclose(WatchFile); RWfileChanged=false; return true; } bool Load_Watches(bool clear, const char* filename) { const char DELIM = '\t'; FILE* WatchFile = fopen(filename,"rb"); if (!WatchFile) { MessageBox(MESSAGEBOXPARENT,"Error opening file.","ERROR",MB_OK); return false; } if(clear) { if(!ResetWatches()) { fclose(WatchFile); return false; } } strcpy(currentWatch,filename); RWAddRecentFile(currentWatch); AddressWatcher Temp; char mode; fgets(Str_Tmp,1024,WatchFile); sscanf(Str_Tmp,"%c%*s",&mode); int WatchAdd; fgets(Str_Tmp,1024,WatchFile); sscanf(Str_Tmp,"%d%*s",&WatchAdd); WatchAdd+=WatchCount; for (int i = WatchCount; i < WatchAdd; i++) { while (i < 0) i++; do { fgets(Str_Tmp,1024,WatchFile); } while (Str_Tmp[0] == '\n'); sscanf(Str_Tmp,"%*05X%*c%04X%*c%c%*c%c%*c%d",&(Temp.Address),&(Temp.Size),&(Temp.Type),(int*)&(Temp.WrongEndian)); Temp.WrongEndian = 0; char *Comment = strrchr(Str_Tmp,DELIM) + 1; *strrchr(Comment,'\n') = '\0'; InsertWatch(Temp,Comment); } fclose(WatchFile); if (RamWatchHWnd) ListView_SetItemCount(GetDlgItem(RamWatchHWnd,IDC_WATCHLIST),WatchCount); RWfileChanged=false; return true; } bool Load_Watches(bool clear) { const char* slash = max(strrchr(gamefilename, '|'), max(strrchr(gamefilename, '\\'), strrchr(gamefilename, '/'))); strcpy(Str_Tmp,slash ? slash+1 : gamefilename); char* dot = strrchr(Str_Tmp, '.'); if(dot) *dot = 0; strcat(Str_Tmp,".wch"); if(Change_File_L(Str_Tmp, applicationPath, "Load Watches", "Watchlist\0*.wch\0All Files\0*.*\0\0", "wch", RamWatchHWnd)) { return Load_Watches(clear, Str_Tmp); } return false; } bool ResetWatches() { if(!AskSave()) return false; for (;WatchCount>=0;WatchCount--) { free(rswatches[WatchCount].comment); rswatches[WatchCount].comment = NULL; } WatchCount++; if (RamWatchHWnd) { ListView_SetItemCount(GetDlgItem(RamWatchHWnd,IDC_WATCHLIST),WatchCount); RefreshWatchListSelectedCountControlStatus(RamWatchHWnd); } RWfileChanged = false; currentWatch[0] = '\0'; return true; } void RemoveWatch(int watchIndex) { free(rswatches[watchIndex].comment); rswatches[watchIndex].comment = NULL; for (int i = watchIndex; i <= WatchCount; i++) rswatches[i] = rswatches[i+1]; WatchCount--; } void RefreshWatchListSelectedItemControlStatus(HWND hDlg) { static int prevSelIndex=-1; int selIndex = ListView_GetSelectionMark(GetDlgItem(hDlg,IDC_RAMLIST)); if(selIndex != prevSelIndex) { if(selIndex == -1 || prevSelIndex == -1) { EnableWindow(GetDlgItem(hDlg, IDC_C_ADDCHEAT), (selIndex != -1) ? TRUE : FALSE); } prevSelIndex = selIndex; } } LRESULT CALLBACK EditWatchProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) //Gets info for a RAM Watch, and then inserts it into the Watch List { RECT r; RECT r2; int dx1, dy1, dx2, dy2; static int index; static char s,t = s = 0; switch(uMsg) { case WM_INITDIALOG: //Clear_Sound_Buffer(); GetWindowRect(hWnd, &r); dx1 = (r.right - r.left) / 2; dy1 = (r.bottom - r.top) / 2; GetWindowRect(hDlg, &r2); dx2 = (r2.right - r2.left) / 2; dy2 = (r2.bottom - r2.top) / 2; //SetWindowPos(hDlg, NULL, max(0, r.left + (dx1 - dx2)), max(0, r.top + (dy1 - dy2)), NULL, NULL, SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW); SetWindowPos(hDlg, NULL, r.left, r.top, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW); index = (int)lParam; sprintf(Str_Tmp,"%04X",rswatches[index].Address); SetDlgItemText(hDlg,IDC_EDIT_COMPAREADDRESS,Str_Tmp); if (rswatches[index].comment != NULL) SetDlgItemText(hDlg,IDC_PROMPT_EDIT,rswatches[index].comment); s = rswatches[index].Size; t = rswatches[index].Type; switch (s) { case 'b': SendDlgItemMessage(hDlg, IDC_1_BYTE, BM_SETCHECK, BST_CHECKED, 0); break; case 'w': SendDlgItemMessage(hDlg, IDC_2_BYTES, BM_SETCHECK, BST_CHECKED, 0); break; case 'd': SendDlgItemMessage(hDlg, IDC_4_BYTES, BM_SETCHECK, BST_CHECKED, 0); break; default: s = 0; break; } switch (t) { case 's': SendDlgItemMessage(hDlg, IDC_SIGNED, BM_SETCHECK, BST_CHECKED, 0); break; case 'u': SendDlgItemMessage(hDlg, IDC_UNSIGNED, BM_SETCHECK, BST_CHECKED, 0); break; case 'h': SendDlgItemMessage(hDlg, IDC_HEX, BM_SETCHECK, BST_CHECKED, 0); break; default: t = 0; break; } return true; break; case WM_COMMAND: switch(LOWORD(wParam)) { case IDC_SIGNED: t='s'; return true; case IDC_UNSIGNED: t='u'; return true; case IDC_HEX: t='h'; return true; case IDC_1_BYTE: s = 'b'; return true; case IDC_2_BYTES: s = 'w'; return true; case IDC_4_BYTES: s = 'd'; return true; case IDOK: { if (s && t) { AddressWatcher Temp; Temp.Size = s; Temp.Type = t; Temp.WrongEndian = false; //replace this when I get little endian working properly GetDlgItemText(hDlg,IDC_EDIT_COMPAREADDRESS,Str_Tmp,1024); char *addrstr = Str_Tmp; if (strlen(Str_Tmp) > 8) addrstr = &(Str_Tmp[strlen(Str_Tmp) - 9]); for(int i = 0; addrstr[i]; i++) {if(toupper(addrstr[i]) == 'O') addrstr[i] = '0';} sscanf(addrstr,"%04X",&(Temp.Address)); if((Temp.Address & ~0xFFFF) == ~0xFFFF) Temp.Address &= 0xFFFF; if(IsHardwareAddressValid(Temp.Address)) { GetDlgItemText(hDlg,IDC_PROMPT_EDIT,Str_Tmp,80); if (index < WatchCount) RemoveWatch(index); InsertWatch(Temp,Str_Tmp); if(RamWatchHWnd) { ListView_SetItemCount(GetDlgItem(RamWatchHWnd,IDC_WATCHLIST),WatchCount); } EndDialog(hDlg, true); } else { MessageBox(hDlg,"Invalid Address","ERROR",MB_OK); } } else { strcpy(Str_Tmp,"Error:"); if (!s) strcat(Str_Tmp," Size must be specified."); if (!t) strcat(Str_Tmp," Type must be specified."); MessageBox(hDlg,Str_Tmp,"ERROR",MB_OK); } RWfileChanged=true; return true; break; } case IDCANCEL: EndDialog(hDlg, false); return false; break; } break; case WM_CLOSE: EndDialog(hDlg, false); return false; break; } return false; } void RamWatchEnableCommand(HWND hDlg, HMENU hMenu, UINT uIDEnableItem, bool enable) { EnableWindow(GetDlgItem(hDlg, uIDEnableItem), (enable?TRUE:FALSE)); if (hMenu != NULL) { if (uIDEnableItem == ID_WATCHES_UPDOWN) { EnableMenuItem(hMenu, IDC_C_WATCH_UP, MF_BYCOMMAND | (enable?MF_ENABLED:MF_GRAYED)); EnableMenuItem(hMenu, IDC_C_WATCH_DOWN, MF_BYCOMMAND | (enable?MF_ENABLED:MF_GRAYED)); } else EnableMenuItem(hMenu, uIDEnableItem, MF_BYCOMMAND | (enable?MF_ENABLED:MF_GRAYED)); } } void RefreshWatchListSelectedCountControlStatus(HWND hDlg) { static int prevSelCount=-1; int selCount = ListView_GetSelectedCount(GetDlgItem(hDlg,IDC_WATCHLIST)); if(selCount != prevSelCount) { if(selCount < 2 || prevSelCount < 2) { RamWatchEnableCommand(hDlg, ramwatchmenu, IDC_C_WATCH_EDIT, selCount == 1); RamWatchEnableCommand(hDlg, ramwatchmenu, IDC_C_WATCH_REMOVE, selCount >= 1); RamWatchEnableCommand(hDlg, ramwatchmenu, IDC_C_WATCH_DUPLICATE, selCount == 1); RamWatchEnableCommand(hDlg, ramwatchmenu, IDC_C_ADDCHEAT, selCount == 1); RamWatchEnableCommand(hDlg, ramwatchmenu, ID_WATCHES_UPDOWN, selCount == 1); } prevSelCount = selCount; } } LRESULT CALLBACK RamWatchProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { RECT r; RECT r2; int dx1, dy1, dx2, dy2; static int watchIndex=0; switch(uMsg) { case WM_MOVE: { RECT wrect; GetWindowRect(hDlg,&wrect); ramw_x = wrect.left; ramw_y = wrect.top; //regSetDwordValue(RAMWX, ramw_x); TODO //regSetDwordValue(RAMWY, ramw_y); TODO } break; case WM_INITDIALOG: { GetWindowRect(hWnd, &r); //Ramwatch window dx1 = (r.right - r.left) / 2; dy1 = (r.bottom - r.top) / 2; GetWindowRect(hDlg, &r2); // TASer window dx2 = (r2.right - r2.left) / 2; dy2 = (r2.bottom - r2.top) / 2; // push it away from the main window if we can const int width = (r.right-r.left); const int height = (r.bottom - r.top); const int width2 = (r2.right-r2.left); if(r.left+width2 + width < GetSystemMetrics(SM_CXSCREEN)) { r.right += width; r.left += width; } else if((int)r.left - (int)width2 > 0) { r.right -= width2; r.left -= width2; } //----------------------------------------------------------------------------------- //If user has Save Window Pos selected, override default positioning if (RWSaveWindowPos) { //If ramwindow is for some reason completely off screen, use default instead if (ramw_x > (-width*2) || ramw_x < (width*2 + GetSystemMetrics(SM_CYSCREEN)) ) r.left = ramw_x; //This also ignores cases of windows -32000 error codes //If ramwindow is for some reason completely off screen, use default instead if (ramw_y > (0-height*2) ||ramw_y < (height*2 + GetSystemMetrics(SM_CYSCREEN)) ) r.top = ramw_y; //This also ignores cases of windows -32000 error codes } //------------------------------------------------------------------------------------- SetWindowPos(hDlg, NULL, r.left, r.top, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW); ramwatchmenu=GetMenu(hDlg); rwrecentmenu=CreateMenu(); UpdateRW_RMenu(rwrecentmenu, RAMMENU_FILE_RECENT, RW_MENU_FIRST_RECENT_FILE); const char* names[3] = {"Address","Value","Notes"}; int widths[3] = {62,64,64+51+53}; init_list_box(GetDlgItem(hDlg,IDC_WATCHLIST),names,3,widths); if (!ResultCount) reset_address_info(); else signal_new_frame(); ListView_SetItemCount(GetDlgItem(hDlg,IDC_WATCHLIST),WatchCount); if (!noMisalign) SendDlgItemMessage(hDlg, IDC_MISALIGN, BM_SETCHECK, BST_CHECKED, 0); //if (littleEndian) SendDlgItemMessage(hDlg, IDC_ENDIAN, BM_SETCHECK, BST_CHECKED, 0); RamWatchAccels = LoadAccelerators(hInst, MAKEINTRESOURCE(IDR_RWACCELERATOR)); // due to some bug in windows, the arrow button width from the resource gets ignored, so we have to set it here SetWindowPos(GetDlgItem(hDlg,ID_WATCHES_UPDOWN), 0,0,0, 30,60, SWP_NOMOVE); Update_RAM_Watch(); DragAcceptFiles(hDlg, TRUE); RefreshWatchListSelectedCountControlStatus(hDlg); return false; } break; case WM_INITMENU: CheckMenuItem(ramwatchmenu, RAMMENU_FILE_AUTOLOAD, AutoRWLoad ? MF_CHECKED : MF_UNCHECKED); CheckMenuItem(ramwatchmenu, RAMMENU_FILE_SAVEWINDOW, RWSaveWindowPos ? MF_CHECKED : MF_UNCHECKED); break; case WM_MENUSELECT: case WM_ENTERSIZEMOVE: //Clear_Sound_Buffer(); break; case WM_NOTIFY: { switch(wParam) { case ID_WATCHES_UPDOWN: { switch(((LPNMUPDOWN)lParam)->hdr.code) { case UDN_DELTAPOS: { int delta = ((LPNMUPDOWN)lParam)->iDelta; SendMessage(hDlg, WM_COMMAND, delta<0 ? IDC_C_WATCH_UP : IDC_C_WATCH_DOWN,0); } break; } } break; default: { LPNMHDR lP = (LPNMHDR) lParam; switch (lP->code) { case LVN_ITEMCHANGED: // selection changed event { NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)lP; if(pNMListView->uNewState & LVIS_FOCUSED || (pNMListView->uNewState ^ pNMListView->uOldState) & LVIS_SELECTED) { // disable buttons that we don't have the right number of selected items for RefreshWatchListSelectedCountControlStatus(hDlg); } } break; case LVN_GETDISPINFO: { LV_DISPINFO *Item = (LV_DISPINFO *)lParam; Item->item.mask = LVIF_TEXT; Item->item.state = 0; Item->item.iImage = 0; const unsigned int iNum = Item->item.iItem; static char num[11]; switch (Item->item.iSubItem) { case 0: sprintf(num,"%04X",rswatches[iNum].Address); Item->item.pszText = num; return true; case 1: { int i = rswatches[iNum].CurValue; int t = rswatches[iNum].Type; int size = rswatches[iNum].Size; const char* formatString = ((t=='s') ? "%d" : (t=='u') ? "%u" : (size=='d' ? "%08X" : size=='w' ? "%04X" : "%02X")); switch (size) { case 'b': default: sprintf(num, formatString, t=='s' ? (char)(i&0xff) : (unsigned char)(i&0xff)); break; case 'w': sprintf(num, formatString, t=='s' ? (short)(i&0xffff) : (unsigned short)(i&0xffff)); break; case 'd': sprintf(num, formatString, t=='s' ? (long)(i&0xffffffff) : (unsigned long)(i&0xffffffff)); break; } Item->item.pszText = num; } return true; case 2: Item->item.pszText = rswatches[iNum].comment ? rswatches[iNum].comment : (CHAR*)""; return true; default: return false; } } case LVN_ODFINDITEM: { // disable search by keyboard typing, // because it interferes with some of the accelerators // and it isn't very useful here anyway SetWindowLong(hDlg, DWL_MSGRESULT, ListView_GetSelectionMark(GetDlgItem(hDlg,IDC_WATCHLIST))); return 1; } } } } } break; case WM_COMMAND: switch(LOWORD(wParam)) { case RAMMENU_FILE_SAVE: QuickSaveWatches(); break; case RAMMENU_FILE_SAVEAS: //case IDC_C_SAVE: return Save_Watches(); case RAMMENU_FILE_OPEN: return Load_Watches(true); case RAMMENU_FILE_APPEND: //case IDC_C_LOAD: return Load_Watches(false); case RAMMENU_FILE_NEW: //case IDC_C_RESET: ResetWatches(); return true; case IDC_C_WATCH_REMOVE: { HWND watchListControl = GetDlgItem(hDlg, IDC_WATCHLIST); watchIndex = ListView_GetNextItem(watchListControl, -1, LVNI_ALL | LVNI_SELECTED); while (watchIndex >= 0) { RemoveWatch(watchIndex); ListView_DeleteItem(watchListControl, watchIndex); watchIndex = ListView_GetNextItem(watchListControl, -1, LVNI_ALL | LVNI_SELECTED); } RWfileChanged=true; SetFocus(GetDlgItem(hDlg,IDC_WATCHLIST)); return true; } case IDC_C_WATCH_EDIT: watchIndex = ListView_GetSelectionMark(GetDlgItem(hDlg,IDC_WATCHLIST)); if(watchIndex != -1) { DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_EDITWATCH), hDlg, (DLGPROC) EditWatchProc,(LPARAM) watchIndex); SetFocus(GetDlgItem(hDlg,IDC_WATCHLIST)); } return true; case IDC_C_WATCH: rswatches[WatchCount].Address = rswatches[WatchCount].WrongEndian = 0; rswatches[WatchCount].Size = 'b'; rswatches[WatchCount].Type = 's'; DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_EDITWATCH), hDlg, (DLGPROC) EditWatchProc,(LPARAM) WatchCount); SetFocus(GetDlgItem(hDlg,IDC_WATCHLIST)); return true; case IDC_C_WATCH_DUPLICATE: watchIndex = ListView_GetSelectionMark(GetDlgItem(hDlg,IDC_WATCHLIST)); if(watchIndex != -1) { rswatches[WatchCount].Address = rswatches[watchIndex].Address; rswatches[WatchCount].WrongEndian = rswatches[watchIndex].WrongEndian; rswatches[WatchCount].Size = rswatches[watchIndex].Size; rswatches[WatchCount].Type = rswatches[watchIndex].Type; DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_EDITWATCH), hDlg, (DLGPROC) EditWatchProc,(LPARAM) WatchCount); SetFocus(GetDlgItem(hDlg,IDC_WATCHLIST)); } return true; case IDC_C_WATCH_SEPARATE: AddressWatcher separator; separator.Address = 0xc000; separator.WrongEndian = false; separator.Size = 'S'; separator.Type = 'S'; InsertWatch(separator, "----------------------------"); SetFocus(GetDlgItem(hDlg,IDC_WATCHLIST)); return true; case IDC_C_WATCH_UP: { watchIndex = ListView_GetSelectionMark(GetDlgItem(hDlg,IDC_WATCHLIST)); if (watchIndex == 0 || watchIndex == -1) return true; void *tmp = malloc(sizeof(AddressWatcher)); memcpy(tmp,&(rswatches[watchIndex]),sizeof(AddressWatcher)); memcpy(&(rswatches[watchIndex]),&(rswatches[watchIndex - 1]),sizeof(AddressWatcher)); memcpy(&(rswatches[watchIndex - 1]),tmp,sizeof(AddressWatcher)); free(tmp); ListView_SetItemState(GetDlgItem(hDlg,IDC_WATCHLIST),watchIndex,0,LVIS_FOCUSED|LVIS_SELECTED); ListView_SetSelectionMark(GetDlgItem(hDlg,IDC_WATCHLIST),watchIndex-1); ListView_SetItemState(GetDlgItem(hDlg,IDC_WATCHLIST),watchIndex-1,LVIS_FOCUSED|LVIS_SELECTED,LVIS_FOCUSED|LVIS_SELECTED); ListView_SetItemCount(GetDlgItem(hDlg,IDC_WATCHLIST),WatchCount); RWfileChanged=true; return true; } case IDC_C_WATCH_DOWN: { watchIndex = ListView_GetSelectionMark(GetDlgItem(hDlg,IDC_WATCHLIST)); if (watchIndex >= WatchCount - 1 || watchIndex == -1) return true; void *tmp = malloc(sizeof(AddressWatcher)); memcpy(tmp,&(rswatches[watchIndex]),sizeof(AddressWatcher)); memcpy(&(rswatches[watchIndex]),&(rswatches[watchIndex + 1]),sizeof(AddressWatcher)); memcpy(&(rswatches[watchIndex + 1]),tmp,sizeof(AddressWatcher)); free(tmp); ListView_SetItemState(GetDlgItem(hDlg,IDC_WATCHLIST),watchIndex,0,LVIS_FOCUSED|LVIS_SELECTED); ListView_SetSelectionMark(GetDlgItem(hDlg,IDC_WATCHLIST),watchIndex+1); ListView_SetItemState(GetDlgItem(hDlg,IDC_WATCHLIST),watchIndex+1,LVIS_FOCUSED|LVIS_SELECTED,LVIS_FOCUSED|LVIS_SELECTED); ListView_SetItemCount(GetDlgItem(hDlg,IDC_WATCHLIST),WatchCount); RWfileChanged=true; return true; } case ID_WATCHES_UPDOWN: { int delta = ((LPNMUPDOWN)lParam)->iDelta; SendMessage(hDlg, WM_COMMAND, delta<0 ? IDC_C_WATCH_UP : IDC_C_WATCH_DOWN,0); break; } case RAMMENU_FILE_AUTOLOAD: { AutoRWLoad ^= 1; CheckMenuItem(ramwatchmenu, RAMMENU_FILE_AUTOLOAD, AutoRWLoad ? MF_CHECKED : MF_UNCHECKED); break; } case RAMMENU_FILE_SAVEWINDOW: { RWSaveWindowPos ^=1; CheckMenuItem(ramwatchmenu, RAMMENU_FILE_SAVEWINDOW, RWSaveWindowPos ? MF_CHECKED : MF_UNCHECKED); break; } case IDC_C_ADDCHEAT: { watchIndex = ListView_GetSelectionMark(GetDlgItem(hDlg,IDC_WATCHLIST)); if(watchIndex >= 0) { // unsigned int address = rswatches[watchIndex].Address; int sizeType = -1; if(rswatches[watchIndex].Size == 'b') sizeType = 0; else if(rswatches[watchIndex].Size == 'w') sizeType = 1; else if(rswatches[watchIndex].Size == 'd') sizeType = 2; int numberType = -1; if(rswatches[watchIndex].Type == 's') numberType = 0; else if(rswatches[watchIndex].Type == 'u') numberType = 1; else if(rswatches[watchIndex].Type == 'h') numberType = 2; // TODO: open add-cheat dialog } } break; case IDOK: case IDCANCEL: RamWatchHWnd = NULL; DragAcceptFiles(hDlg, FALSE); EndDialog(hDlg, true); return true; default: if (LOWORD(wParam) >= RW_MENU_FIRST_RECENT_FILE && LOWORD(wParam) < RW_MENU_FIRST_RECENT_FILE+MAX_RECENT_WATCHES && LOWORD(wParam) <= RW_MENU_LAST_RECENT_FILE) OpenRWRecentFile(LOWORD(wParam) - RW_MENU_FIRST_RECENT_FILE); } break; #if 0 // this message is never received case WM_KEYDOWN: // handle accelerator keys { SetFocus(GetDlgItem(hDlg,IDC_WATCHLIST)); MSG msg; msg.hwnd = hDlg; msg.message = uMsg; msg.wParam = wParam; msg.lParam = lParam; if(RamWatchAccels && TranslateAccelerator(hDlg, RamWatchAccels, &msg)) return true; } break; #endif // case WM_CLOSE: // RamWatchHWnd = NULL; // DragAcceptFiles(hDlg, FALSE); // DestroyWindow(hDlg); // return false; case WM_DESTROY: // this is the correct place RamWatchHWnd = NULL; DragAcceptFiles(hDlg, FALSE); WriteRecentRWFiles(); // write recent menu to ini break; case WM_DROPFILES: { HDROP hDrop = (HDROP)wParam; DragQueryFile(hDrop, 0, Str_Tmp, 1024); DragFinish(hDrop); return Load_Watches(true, Str_Tmp); } break; } return false; }
[ "[email protected]@d79fac8d-805f-112a-794e-f5414a3d572c" ]
[ [ [ 1, 1234 ] ] ]
7734e933e1d53b4df824c9485dea02fc78fe6368
0033659a033b4afac9b93c0ac80b8918a5ff9779
/game/server/hl2/hl2_player.cpp
0418912d710f678c8d6b94b9e83dcda5e07f28fc
[]
no_license
jonnyboy0719/situation-outbreak-two
d03151dc7a12a97094fffadacf4a8f7ee6ec7729
50037e27e738ff78115faea84e235f865c61a68f
refs/heads/master
2021-01-10T09:59:39.214171
2011-01-11T01:15:33
2011-01-11T01:15:33
53,858,955
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
114,976
cpp
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: Player for HL2. // //=============================================================================// #include "cbase.h" #include "hl2_player.h" #include "globalstate.h" #include "game.h" #include "gamerules.h" #include "trains.h" #include "basehlcombatweapon_shared.h" #include "vcollide_parse.h" #include "in_buttons.h" #include "ai_interactions.h" #include "ai_squad.h" #include "igamemovement.h" #include "ai_hull.h" #include "hl2_shareddefs.h" #include "info_camera_link.h" #include "point_camera.h" #include "engine/IEngineSound.h" #include "ndebugoverlay.h" #include "iservervehicle.h" #include "IVehicle.h" #include "globals.h" #include "collisionutils.h" #include "coordsize.h" #include "effect_color_tables.h" #include "vphysics/player_controller.h" #include "player_pickup.h" #include "weapon_physcannon.h" #include "script_intro.h" #include "effect_dispatch_data.h" #include "te_effect_dispatch.h" #include "ai_basenpc.h" #include "AI_Criteria.h" #include "npc_barnacle.h" #include "entitylist.h" #include "env_zoom.h" #include "hl2_gamerules.h" #include "prop_combine_ball.h" #include "datacache/imdlcache.h" #include "eventqueue.h" #include "GameStats.h" #include "filters.h" #include "tier0/icommandline.h" #ifdef HL2_EPISODIC #include "npc_alyx_episodic.h" #endif ///// // SO2 - James // Do not allow players to fire weapons while sprinting // Base each player's speed on their health #include "so_player.h" ///// // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" extern ConVar weapon_showproficiency; extern ConVar autoaim_max_dist; // Do not touch with without seeing me, please! (sjb) // For consistency's sake, enemy gunfire is traced against a scaled down // version of the player's hull, not the hitboxes for the player's model // because the player isn't aware of his model, and can't do anything about // preventing headshots and other such things. Also, game difficulty will // not change if the model changes. This is the value by which to scale // the X/Y of the player's hull to get the volume to trace bullets against. #define PLAYER_HULL_REDUCTION 0.70 // This switches between the single primary weapon, and multiple weapons with buckets approach (jdw) #define HL2_SINGLE_PRIMARY_WEAPON_MODE 0 #define TIME_IGNORE_FALL_DAMAGE 10.0 extern int gEvilImpulse101; ConVar sv_autojump( "sv_autojump", "0" ); ConVar hl2_walkspeed( "hl2_walkspeed", "150" ); ConVar hl2_normspeed( "hl2_normspeed", "190" ); ConVar hl2_sprintspeed( "hl2_sprintspeed", "320" ); ConVar hl2_darkness_flashlight_factor ( "hl2_darkness_flashlight_factor", "1" ); #ifdef HL2MP ///// // SO2 - James // Base each player's speed on their health /*#define HL2_WALK_SPEED 150 #define HL2_NORM_SPEED 190 #define HL2_SPRINT_SPEED 320*/ #define HL2_WALK_SPEED SO_WALK_SPEED #define HL2_NORM_SPEED SO_NORM_SPEED #define HL2_SPRINT_SPEED SO_SPRINT_SPEED ///// #else #define HL2_WALK_SPEED hl2_walkspeed.GetFloat() #define HL2_NORM_SPEED hl2_normspeed.GetFloat() #define HL2_SPRINT_SPEED hl2_sprintspeed.GetFloat() #endif ConVar player_showpredictedposition( "player_showpredictedposition", "0" ); ConVar player_showpredictedposition_timestep( "player_showpredictedposition_timestep", "1.0" ); ConVar player_squad_transient_commands( "player_squad_transient_commands", "1", FCVAR_REPLICATED ); ConVar player_squad_double_tap_time( "player_squad_double_tap_time", "0.25" ); ConVar sv_infinite_aux_power( "sv_infinite_aux_power", "0", FCVAR_CHEAT ); ConVar autoaim_unlock_target( "autoaim_unlock_target", "0.8666" ); ConVar sv_stickysprint("sv_stickysprint", "0", FCVAR_ARCHIVE | FCVAR_ARCHIVE_XBOX); #define FLASH_DRAIN_TIME 1.1111 // 100 units / 90 secs #define FLASH_CHARGE_TIME 50.0f // 100 units / 2 secs //============================================================================================== // CAPPED PLAYER PHYSICS DAMAGE TABLE //============================================================================================== static impactentry_t cappedPlayerLinearTable[] = { { 150*150, 5 }, { 250*250, 10 }, { 450*450, 20 }, { 550*550, 30 }, //{ 700*700, 100 }, //{ 1000*1000, 500 }, }; static impactentry_t cappedPlayerAngularTable[] = { { 100*100, 10 }, { 150*150, 20 }, { 200*200, 30 }, //{ 300*300, 500 }, }; static impactdamagetable_t gCappedPlayerImpactDamageTable = { cappedPlayerLinearTable, cappedPlayerAngularTable, ARRAYSIZE(cappedPlayerLinearTable), ARRAYSIZE(cappedPlayerAngularTable), 24*24.0f, // minimum linear speed 360*360.0f, // minimum angular speed 2.0f, // can't take damage from anything under 2kg 5.0f, // anything less than 5kg is "small" 5.0f, // never take more than 5 pts of damage from anything under 5kg 36*36.0f, // <5kg objects must go faster than 36 in/s to do damage 0.0f, // large mass in kg (no large mass effects) 1.0f, // large mass scale 2.0f, // large mass falling scale 320.0f, // min velocity for player speed to cause damage }; // Flashlight utility bool g_bCacheLegacyFlashlightStatus = true; bool g_bUseLegacyFlashlight; bool Flashlight_UseLegacyVersion( void ) { // If this is the first run through, cache off what the answer should be (cannot change during a session) if ( g_bCacheLegacyFlashlightStatus ) { char modDir[MAX_PATH]; if ( UTIL_GetModDir( modDir, sizeof(modDir) ) == false ) return false; g_bUseLegacyFlashlight = ( !Q_strcmp( modDir, "hl2" ) || !Q_strcmp( modDir, "episodic" ) ); g_bCacheLegacyFlashlightStatus = false; } // Return the results return g_bUseLegacyFlashlight; } //----------------------------------------------------------------------------- // Purpose: Used to relay outputs/inputs from the player to the world and viceversa //----------------------------------------------------------------------------- class CLogicPlayerProxy : public CLogicalEntity { DECLARE_CLASS( CLogicPlayerProxy, CLogicalEntity ); private: DECLARE_DATADESC(); public: COutputEvent m_OnFlashlightOn; COutputEvent m_OnFlashlightOff; COutputEvent m_PlayerHasAmmo; COutputEvent m_PlayerHasNoAmmo; COutputEvent m_PlayerDied; COutputEvent m_PlayerMissedAR2AltFire; // Player fired a combine ball which did not dissolve any enemies. COutputInt m_RequestedPlayerHealth; void InputRequestPlayerHealth( inputdata_t &inputdata ); void InputSetFlashlightSlowDrain( inputdata_t &inputdata ); void InputSetFlashlightNormalDrain( inputdata_t &inputdata ); void InputSetPlayerHealth( inputdata_t &inputdata ); void InputRequestAmmoState( inputdata_t &inputdata ); void InputLowerWeapon( inputdata_t &inputdata ); void InputEnableCappedPhysicsDamage( inputdata_t &inputdata ); void InputDisableCappedPhysicsDamage( inputdata_t &inputdata ); void InputSetLocatorTargetEntity( inputdata_t &inputdata ); void Activate ( void ); bool PassesDamageFilter( const CTakeDamageInfo &info ); EHANDLE m_hPlayer; }; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void CC_ToggleZoom( void ) { CBasePlayer* pPlayer = UTIL_GetCommandClient(); if( pPlayer ) { CHL2_Player *pHL2Player = dynamic_cast<CHL2_Player*>(pPlayer); if( pHL2Player && pHL2Player->IsSuitEquipped() ) { pHL2Player->ToggleZoom(); } } } static ConCommand toggle_zoom("toggle_zoom", CC_ToggleZoom, "Toggles zoom display" ); // ConVar cl_forwardspeed( "cl_forwardspeed", "400", FCVAR_CHEAT ); // Links us to the client's version ConVar xc_crouch_range( "xc_crouch_range", "0.85", FCVAR_ARCHIVE, "Percentarge [1..0] of joystick range to allow ducking within" ); // Only 1/2 of the range is used ConVar xc_use_crouch_limiter( "xc_use_crouch_limiter", "0", FCVAR_ARCHIVE, "Use the crouch limiting logic on the controller" ); //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void CC_ToggleDuck( void ) { CBasePlayer* pPlayer = UTIL_GetCommandClient(); if ( pPlayer == NULL ) return; // Cannot be frozen if ( pPlayer->GetFlags() & FL_FROZEN ) return; static bool bChecked = false; static ConVar *pCVcl_forwardspeed = NULL; if ( !bChecked ) { bChecked = true; pCVcl_forwardspeed = ( ConVar * )cvar->FindVar( "cl_forwardspeed" ); } // If we're not ducked, do extra checking if ( xc_use_crouch_limiter.GetBool() ) { if ( pPlayer->GetToggledDuckState() == false ) { float flForwardSpeed = 400.0f; if ( pCVcl_forwardspeed ) { flForwardSpeed = pCVcl_forwardspeed->GetFloat(); } flForwardSpeed = max( 1.0f, flForwardSpeed ); // Make sure we're not in the blindspot on the crouch detection float flStickDistPerc = ( pPlayer->GetStickDist() / flForwardSpeed ); // Speed is the magnitude if ( flStickDistPerc > xc_crouch_range.GetFloat() ) return; } } // Toggle the duck pPlayer->ToggleDuck(); } static ConCommand toggle_duck("toggle_duck", CC_ToggleDuck, "Toggles duck" ); #ifndef HL2MP #ifndef PORTAL LINK_ENTITY_TO_CLASS( player, CHL2_Player ); #endif #endif PRECACHE_REGISTER(player); CBaseEntity *FindEntityForward( CBasePlayer *pMe, bool fHull ); BEGIN_SIMPLE_DATADESC( LadderMove_t ) DEFINE_FIELD( m_bForceLadderMove, FIELD_BOOLEAN ), DEFINE_FIELD( m_bForceMount, FIELD_BOOLEAN ), DEFINE_FIELD( m_flStartTime, FIELD_TIME ), DEFINE_FIELD( m_flArrivalTime, FIELD_TIME ), DEFINE_FIELD( m_vecGoalPosition, FIELD_POSITION_VECTOR ), DEFINE_FIELD( m_vecStartPosition, FIELD_POSITION_VECTOR ), DEFINE_FIELD( m_hForceLadder, FIELD_EHANDLE ), DEFINE_FIELD( m_hReservedSpot, FIELD_EHANDLE ), END_DATADESC() // Global Savedata for HL2 player BEGIN_DATADESC( CHL2_Player ) DEFINE_FIELD( m_nControlClass, FIELD_INTEGER ), DEFINE_EMBEDDED( m_HL2Local ), DEFINE_FIELD( m_bSprintEnabled, FIELD_BOOLEAN ), DEFINE_FIELD( m_flTimeAllSuitDevicesOff, FIELD_TIME ), DEFINE_FIELD( m_fIsSprinting, FIELD_BOOLEAN ), DEFINE_FIELD( m_fIsWalking, FIELD_BOOLEAN ), /* // These are initialized every time the player calls Activate() DEFINE_FIELD( m_bIsAutoSprinting, FIELD_BOOLEAN ), DEFINE_FIELD( m_fAutoSprintMinTime, FIELD_TIME ), */ // Field is used within a single tick, no need to save restore // DEFINE_FIELD( m_bPlayUseDenySound, FIELD_BOOLEAN ), // m_pPlayerAISquad reacquired on load DEFINE_AUTO_ARRAY( m_vecMissPositions, FIELD_POSITION_VECTOR ), DEFINE_FIELD( m_nNumMissPositions, FIELD_INTEGER ), // m_pPlayerAISquad DEFINE_EMBEDDED( m_CommanderUpdateTimer ), // m_RealTimeLastSquadCommand DEFINE_FIELD( m_QueuedCommand, FIELD_INTEGER ), DEFINE_FIELD( m_flTimeIgnoreFallDamage, FIELD_TIME ), DEFINE_FIELD( m_bIgnoreFallDamageResetAfterImpact, FIELD_BOOLEAN ), // Suit power fields DEFINE_FIELD( m_flSuitPowerLoad, FIELD_FLOAT ), DEFINE_FIELD( m_flIdleTime, FIELD_TIME ), DEFINE_FIELD( m_flMoveTime, FIELD_TIME ), DEFINE_FIELD( m_flLastDamageTime, FIELD_TIME ), DEFINE_FIELD( m_flTargetFindTime, FIELD_TIME ), DEFINE_FIELD( m_flAdmireGlovesAnimTime, FIELD_TIME ), DEFINE_FIELD( m_flNextFlashlightCheckTime, FIELD_TIME ), DEFINE_FIELD( m_flFlashlightPowerDrainScale, FIELD_FLOAT ), DEFINE_FIELD( m_bFlashlightDisabled, FIELD_BOOLEAN ), DEFINE_FIELD( m_bUseCappedPhysicsDamageTable, FIELD_BOOLEAN ), DEFINE_FIELD( m_hLockedAutoAimEntity, FIELD_EHANDLE ), DEFINE_EMBEDDED( m_LowerWeaponTimer ), DEFINE_EMBEDDED( m_AutoaimTimer ), DEFINE_INPUTFUNC( FIELD_FLOAT, "IgnoreFallDamage", InputIgnoreFallDamage ), DEFINE_INPUTFUNC( FIELD_FLOAT, "IgnoreFallDamageWithoutReset", InputIgnoreFallDamageWithoutReset ), DEFINE_INPUTFUNC( FIELD_VOID, "OnSquadMemberKilled", OnSquadMemberKilled ), DEFINE_INPUTFUNC( FIELD_VOID, "DisableFlashlight", InputDisableFlashlight ), DEFINE_INPUTFUNC( FIELD_VOID, "EnableFlashlight", InputEnableFlashlight ), DEFINE_INPUTFUNC( FIELD_VOID, "ForceDropPhysObjects", InputForceDropPhysObjects ), DEFINE_SOUNDPATCH( m_sndLeeches ), DEFINE_SOUNDPATCH( m_sndWaterSplashes ), DEFINE_FIELD( m_flArmorReductionTime, FIELD_TIME ), DEFINE_FIELD( m_iArmorReductionFrom, FIELD_INTEGER ), DEFINE_FIELD( m_flTimeUseSuspended, FIELD_TIME ), DEFINE_FIELD( m_hLocatorTargetEntity, FIELD_EHANDLE ), DEFINE_FIELD( m_flTimeNextLadderHint, FIELD_TIME ), //DEFINE_FIELD( m_hPlayerProxy, FIELD_EHANDLE ), //Shut up class check! END_DATADESC() CHL2_Player::CHL2_Player() { m_nNumMissPositions = 0; m_pPlayerAISquad = 0; m_bSprintEnabled = true; m_flArmorReductionTime = 0.0f; m_iArmorReductionFrom = 0; } // // SUIT POWER DEVICES // ///// // SO2 - James // Change how quickly suit power (stamina) recharges //#define SUITPOWER_CHARGE_RATE 12.5 // 100 units in 8 seconds #define SUITPOWER_CHARGE_RATE 6.25 // 100 units in 16 seconds ///// #ifdef HL2MP CSuitPowerDevice SuitDeviceSprint( bits_SUIT_DEVICE_SPRINT, 25.0f ); // 100 units in 4 seconds #else CSuitPowerDevice SuitDeviceSprint( bits_SUIT_DEVICE_SPRINT, 12.5f ); // 100 units in 8 seconds #endif #ifdef HL2_EPISODIC CSuitPowerDevice SuitDeviceFlashlight( bits_SUIT_DEVICE_FLASHLIGHT, 1.111 ); // 100 units in 90 second #else CSuitPowerDevice SuitDeviceFlashlight( bits_SUIT_DEVICE_FLASHLIGHT, 2.222 ); // 100 units in 45 second #endif CSuitPowerDevice SuitDeviceBreather( bits_SUIT_DEVICE_BREATHER, 6.7f ); // 100 units in 15 seconds (plus three padded seconds) IMPLEMENT_SERVERCLASS_ST(CHL2_Player, DT_HL2_Player) SendPropDataTable(SENDINFO_DT(m_HL2Local), &REFERENCE_SEND_TABLE(DT_HL2Local), SendProxy_SendLocalDataTable), SendPropBool( SENDINFO(m_fIsSprinting) ), END_SEND_TABLE() void CHL2_Player::Precache( void ) { BaseClass::Precache(); PrecacheScriptSound( "HL2Player.SprintNoPower" ); PrecacheScriptSound( "HL2Player.SprintStart" ); PrecacheScriptSound( "HL2Player.UseDeny" ); PrecacheScriptSound( "HL2Player.FlashLightOn" ); PrecacheScriptSound( "HL2Player.FlashLightOff" ); PrecacheScriptSound( "HL2Player.PickupWeapon" ); PrecacheScriptSound( "HL2Player.TrainUse" ); PrecacheScriptSound( "HL2Player.Use" ); PrecacheScriptSound( "HL2Player.BurnPain" ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHL2_Player::CheckSuitZoom( void ) { //#ifndef _XBOX //Adrian - No zooming without a suit! if ( IsSuitEquipped() ) { if ( m_afButtonReleased & IN_ZOOM ) { StopZooming(); } else if ( m_afButtonPressed & IN_ZOOM ) { StartZooming(); } } //#endif//_XBOX } void CHL2_Player::EquipSuit( bool bPlayEffects ) { MDLCACHE_CRITICAL_SECTION(); BaseClass::EquipSuit(); m_HL2Local.m_bDisplayReticle = true; if ( bPlayEffects == true ) { StartAdmireGlovesAnimation(); } } void CHL2_Player::RemoveSuit( void ) { BaseClass::RemoveSuit(); m_HL2Local.m_bDisplayReticle = false; } void CHL2_Player::HandleSpeedChanges( void ) { int buttonsChanged = m_afButtonPressed | m_afButtonReleased; bool bCanSprint = CanSprint(); bool bIsSprinting = IsSprinting(); bool bWantSprint = ( bCanSprint && IsSuitEquipped() && (m_nButtons & IN_SPEED) ); if ( bIsSprinting != bWantSprint && (buttonsChanged & IN_SPEED) ) { // If someone wants to sprint, make sure they've pressed the button to do so. We want to prevent the // case where a player can hold down the sprint key and burn tiny bursts of sprint as the suit recharges // We want a full debounce of the key to resume sprinting after the suit is completely drained if ( bWantSprint ) { if ( sv_stickysprint.GetBool() ) { StartAutoSprint(); } else { StartSprinting(); } } else { if ( !sv_stickysprint.GetBool() ) { StopSprinting(); } // Reset key, so it will be activated post whatever is suppressing it. m_nButtons &= ~IN_SPEED; } } bool bIsWalking = IsWalking(); // have suit, pressing button, not sprinting or ducking bool bWantWalking; if( IsSuitEquipped() ) { bWantWalking = (m_nButtons & IN_WALK) && !IsSprinting() && !(m_nButtons & IN_DUCK); } else { bWantWalking = true; } if( bIsWalking != bWantWalking ) { if ( bWantWalking ) { StartWalking(); } else { StopWalking(); } } } //----------------------------------------------------------------------------- // This happens when we powerdown from the mega physcannon to the regular one //----------------------------------------------------------------------------- void CHL2_Player::HandleArmorReduction( void ) { if ( m_flArmorReductionTime < gpGlobals->curtime ) return; if ( ArmorValue() <= 0 ) return; float flPercent = 1.0f - (( m_flArmorReductionTime - gpGlobals->curtime ) / ARMOR_DECAY_TIME ); int iArmor = Lerp( flPercent, m_iArmorReductionFrom, 0 ); SetArmorValue( iArmor ); } //----------------------------------------------------------------------------- // Purpose: Allow pre-frame adjustments on the player //----------------------------------------------------------------------------- void CHL2_Player::PreThink(void) { if ( player_showpredictedposition.GetBool() ) { Vector predPos; UTIL_PredictedPosition( this, player_showpredictedposition_timestep.GetFloat(), &predPos ); NDebugOverlay::Box( predPos, NAI_Hull::Mins( GetHullType() ), NAI_Hull::Maxs( GetHullType() ), 0, 255, 0, 0, 0.01f ); NDebugOverlay::Line( GetAbsOrigin(), predPos, 0, 255, 0, 0, 0.01f ); } #ifdef HL2_EPISODIC if( m_hLocatorTargetEntity != NULL ) { // Keep track of the entity here, the client will pick up the rest of the work m_HL2Local.m_vecLocatorOrigin = m_hLocatorTargetEntity->WorldSpaceCenter(); } else { m_HL2Local.m_vecLocatorOrigin = vec3_invalid; // This tells the client we have no locator target. } #endif//HL2_EPISODIC // Riding a vehicle? if ( IsInAVehicle() ) { VPROF( "CHL2_Player::PreThink-Vehicle" ); // make sure we update the client, check for timed damage and update suit even if we are in a vehicle UpdateClientData(); CheckTimeBasedDamage(); // Allow the suit to recharge when in the vehicle. SuitPower_Update(); CheckSuitUpdate(); CheckSuitZoom(); WaterMove(); return; } // This is an experiment of mine- autojumping! // only affects you if sv_autojump is nonzero. if( (GetFlags() & FL_ONGROUND) && sv_autojump.GetFloat() != 0 ) { VPROF( "CHL2_Player::PreThink-Autojump" ); // check autojump Vector vecCheckDir; vecCheckDir = GetAbsVelocity(); float flVelocity = VectorNormalize( vecCheckDir ); if( flVelocity > 200 ) { // Going fast enough to autojump vecCheckDir = WorldSpaceCenter() + vecCheckDir * 34 - Vector( 0, 0, 16 ); trace_t tr; UTIL_TraceHull( WorldSpaceCenter() - Vector( 0, 0, 16 ), vecCheckDir, NAI_Hull::Mins(HULL_TINY_CENTERED),NAI_Hull::Maxs(HULL_TINY_CENTERED), MASK_PLAYERSOLID, this, COLLISION_GROUP_PLAYER, &tr ); //NDebugOverlay::Line( tr.startpos, tr.endpos, 0,255,0, true, 10 ); if( tr.fraction == 1.0 && !tr.startsolid ) { // Now trace down! UTIL_TraceLine( vecCheckDir, vecCheckDir - Vector( 0, 0, 64 ), MASK_PLAYERSOLID, this, COLLISION_GROUP_NONE, &tr ); //NDebugOverlay::Line( tr.startpos, tr.endpos, 0,255,0, true, 10 ); if( tr.fraction == 1.0 && !tr.startsolid ) { // !!!HACKHACK // I KNOW, I KNOW, this is definitely not the right way to do this, // but I'm prototyping! (sjb) Vector vecNewVelocity = GetAbsVelocity(); vecNewVelocity.z += 250; SetAbsVelocity( vecNewVelocity ); } } } } VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-Speed" ); HandleSpeedChanges(); #ifdef HL2_EPISODIC HandleArmorReduction(); #endif if( sv_stickysprint.GetBool() && m_bIsAutoSprinting ) { // If we're ducked and not in the air if( IsDucked() && GetGroundEntity() != NULL ) { StopSprinting(); } // Stop sprinting if the player lets off the stick for a moment. else if( GetStickDist() == 0.0f ) { if( gpGlobals->curtime > m_fAutoSprintMinTime ) { StopSprinting(); } } else { // Stop sprinting one half second after the player stops inputting with the move stick. m_fAutoSprintMinTime = gpGlobals->curtime + 0.5f; } } else if ( IsSprinting() ) { // Disable sprint while ducked unless we're in the air (jumping) if ( IsDucked() && ( GetGroundEntity() != NULL ) ) { StopSprinting(); } } VPROF_SCOPE_END(); if ( g_fGameOver || IsPlayerLockedInPlace() ) return; // finale VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-ItemPreFrame" ); ItemPreFrame( ); VPROF_SCOPE_END(); VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-WaterMove" ); WaterMove(); VPROF_SCOPE_END(); if ( g_pGameRules && g_pGameRules->FAllowFlashlight() ) m_Local.m_iHideHUD &= ~HIDEHUD_FLASHLIGHT; else m_Local.m_iHideHUD |= HIDEHUD_FLASHLIGHT; VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-CommanderUpdate" ); CommanderUpdate(); VPROF_SCOPE_END(); // Operate suit accessories and manage power consumption/charge VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-SuitPower_Update" ); SuitPower_Update(); VPROF_SCOPE_END(); // checks if new client data (for HUD and view control) needs to be sent to the client VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-UpdateClientData" ); UpdateClientData(); VPROF_SCOPE_END(); VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-CheckTimeBasedDamage" ); CheckTimeBasedDamage(); VPROF_SCOPE_END(); VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-CheckSuitUpdate" ); CheckSuitUpdate(); VPROF_SCOPE_END(); VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-CheckSuitZoom" ); CheckSuitZoom(); VPROF_SCOPE_END(); if (m_lifeState >= LIFE_DYING) { PlayerDeathThink(); return; } #ifdef HL2_EPISODIC CheckFlashlight(); #endif // HL2_EPISODIC // So the correct flags get sent to client asap. // if ( m_afPhysicsFlags & PFLAG_DIROVERRIDE ) AddFlag( FL_ONTRAIN ); else RemoveFlag( FL_ONTRAIN ); // Train speed control if ( m_afPhysicsFlags & PFLAG_DIROVERRIDE ) { CBaseEntity *pTrain = GetGroundEntity(); float vel; if ( pTrain ) { if ( !(pTrain->ObjectCaps() & FCAP_DIRECTIONAL_USE) ) pTrain = NULL; } if ( !pTrain ) { if ( GetActiveWeapon() && (GetActiveWeapon()->ObjectCaps() & FCAP_DIRECTIONAL_USE) ) { m_iTrain = TRAIN_ACTIVE | TRAIN_NEW; if ( m_nButtons & IN_FORWARD ) { m_iTrain |= TRAIN_FAST; } else if ( m_nButtons & IN_BACK ) { m_iTrain |= TRAIN_BACK; } else { m_iTrain |= TRAIN_NEUTRAL; } return; } else { trace_t trainTrace; // Maybe this is on the other side of a level transition UTIL_TraceLine( GetAbsOrigin(), GetAbsOrigin() + Vector(0,0,-38), MASK_PLAYERSOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, &trainTrace ); if ( trainTrace.fraction != 1.0 && trainTrace.m_pEnt ) pTrain = trainTrace.m_pEnt; if ( !pTrain || !(pTrain->ObjectCaps() & FCAP_DIRECTIONAL_USE) || !pTrain->OnControls(this) ) { // Warning( "In train mode with no train!\n" ); m_afPhysicsFlags &= ~PFLAG_DIROVERRIDE; m_iTrain = TRAIN_NEW|TRAIN_OFF; return; } } } else if ( !( GetFlags() & FL_ONGROUND ) || pTrain->HasSpawnFlags( SF_TRACKTRAIN_NOCONTROL ) || (m_nButtons & (IN_MOVELEFT|IN_MOVERIGHT) ) ) { // Turn off the train if you jump, strafe, or the train controls go dead m_afPhysicsFlags &= ~PFLAG_DIROVERRIDE; m_iTrain = TRAIN_NEW|TRAIN_OFF; return; } SetAbsVelocity( vec3_origin ); vel = 0; if ( m_afButtonPressed & IN_FORWARD ) { vel = 1; pTrain->Use( this, this, USE_SET, (float)vel ); } else if ( m_afButtonPressed & IN_BACK ) { vel = -1; pTrain->Use( this, this, USE_SET, (float)vel ); } if (vel) { m_iTrain = TrainSpeed(pTrain->m_flSpeed, ((CFuncTrackTrain*)pTrain)->GetMaxSpeed()); m_iTrain |= TRAIN_ACTIVE|TRAIN_NEW; } } else if (m_iTrain & TRAIN_ACTIVE) { m_iTrain = TRAIN_NEW; // turn off train } // // If we're not on the ground, we're falling. Update our falling velocity. // if ( !( GetFlags() & FL_ONGROUND ) ) { m_Local.m_flFallVelocity = -GetAbsVelocity().z; } if ( m_afPhysicsFlags & PFLAG_ONBARNACLE ) { bool bOnBarnacle = false; CNPC_Barnacle *pBarnacle = NULL; do { // FIXME: Not a good or fast solution, but maybe it will catch the bug! pBarnacle = (CNPC_Barnacle*)gEntList.FindEntityByClassname( pBarnacle, "npc_barnacle" ); if ( pBarnacle ) { if ( pBarnacle->GetEnemy() == this ) { bOnBarnacle = true; } } } while ( pBarnacle ); if ( !bOnBarnacle ) { Warning( "Attached to barnacle?\n" ); Assert( 0 ); m_afPhysicsFlags &= ~PFLAG_ONBARNACLE; } else { SetAbsVelocity( vec3_origin ); } } // StudioFrameAdvance( );//!!!HACKHACK!!! Can't be hit by traceline when not animating? // Update weapon's ready status UpdateWeaponPosture(); ///// // SO2 - James // Disable suit zooming functionality /*// Disallow shooting while zooming if ( IsX360() ) { if ( IsZooming() ) { if( GetActiveWeapon() && !GetActiveWeapon()->IsWeaponZoomed() ) { // If not zoomed because of the weapon itself, do not attack. m_nButtons &= ~(IN_ATTACK|IN_ATTACK2); } } } else { if ( m_nButtons & IN_ZOOM ) { //FIXME: Held weapons like the grenade get sad when this happens #ifdef HL2_EPISODIC // Episodic allows players to zoom while using a func_tank CBaseCombatWeapon* pWep = GetActiveWeapon(); if ( !m_hUseEntity || ( pWep && pWep->IsWeaponVisible() ) ) #endif m_nButtons &= ~(IN_ATTACK|IN_ATTACK2); } }*/ ///// } void CHL2_Player::PostThink( void ) { BaseClass::PostThink(); if ( !g_fGameOver && !IsPlayerLockedInPlace() && IsAlive() ) { HandleAdmireGlovesAnimation(); } } void CHL2_Player::StartAdmireGlovesAnimation( void ) { MDLCACHE_CRITICAL_SECTION(); CBaseViewModel *vm = GetViewModel( 0 ); if ( vm && !GetActiveWeapon() ) { vm->SetWeaponModel( "models/weapons/v_hands.mdl", NULL ); ShowViewModel( true ); int idealSequence = vm->SelectWeightedSequence( ACT_VM_IDLE ); if ( idealSequence >= 0 ) { vm->SendViewModelMatchingSequence( idealSequence ); m_flAdmireGlovesAnimTime = gpGlobals->curtime + vm->SequenceDuration( idealSequence ); } } } void CHL2_Player::HandleAdmireGlovesAnimation( void ) { CBaseViewModel *pVM = GetViewModel(); if ( pVM && pVM->GetOwningWeapon() == NULL ) { if ( m_flAdmireGlovesAnimTime != 0.0 ) { if ( m_flAdmireGlovesAnimTime > gpGlobals->curtime ) { pVM->m_flPlaybackRate = 1.0f; pVM->StudioFrameAdvance( ); } else if ( m_flAdmireGlovesAnimTime < gpGlobals->curtime ) { m_flAdmireGlovesAnimTime = 0.0f; pVM->SetWeaponModel( NULL, NULL ); } } } else m_flAdmireGlovesAnimTime = 0.0f; } #define HL2PLAYER_RELOADGAME_ATTACK_DELAY 1.0f void CHL2_Player::Activate( void ) { BaseClass::Activate(); InitSprinting(); #ifdef HL2_EPISODIC // Delay attacks by 1 second after loading a game. if ( GetActiveWeapon() ) { float flRemaining = GetActiveWeapon()->m_flNextPrimaryAttack - gpGlobals->curtime; if ( flRemaining < HL2PLAYER_RELOADGAME_ATTACK_DELAY ) { GetActiveWeapon()->m_flNextPrimaryAttack = gpGlobals->curtime + HL2PLAYER_RELOADGAME_ATTACK_DELAY; } flRemaining = GetActiveWeapon()->m_flNextSecondaryAttack - gpGlobals->curtime; if ( flRemaining < HL2PLAYER_RELOADGAME_ATTACK_DELAY ) { GetActiveWeapon()->m_flNextSecondaryAttack = gpGlobals->curtime + HL2PLAYER_RELOADGAME_ATTACK_DELAY; } } #endif GetPlayerProxy(); } //------------------------------------------------------------------------------ // Purpose : // Input : // Output : //------------------------------------------------------------------------------ Class_T CHL2_Player::Classify ( void ) { // If player controlling another entity? If so, return this class if (m_nControlClass != CLASS_NONE) { return m_nControlClass; } else { if(IsInAVehicle()) { IServerVehicle *pVehicle = GetVehicle(); return pVehicle->ClassifyPassenger( this, CLASS_PLAYER ); } else { return CLASS_PLAYER; } } } //----------------------------------------------------------------------------- // Purpose: This is a generic function (to be implemented by sub-classes) to // handle specific interactions between different types of characters // (For example the barnacle grabbing an NPC) // Input : Constant for the type of interaction // Output : true - if sub-class has a response for the interaction // false - if sub-class has no response //----------------------------------------------------------------------------- bool CHL2_Player::HandleInteraction(int interactionType, void *data, CBaseCombatCharacter* sourceEnt) { if ( interactionType == g_interactionBarnacleVictimDangle ) return false; if (interactionType == g_interactionBarnacleVictimReleased) { m_afPhysicsFlags &= ~PFLAG_ONBARNACLE; SetMoveType( MOVETYPE_WALK ); return true; } else if (interactionType == g_interactionBarnacleVictimGrab) { #ifdef HL2_EPISODIC CNPC_Alyx *pAlyx = CNPC_Alyx::GetAlyx(); if ( pAlyx ) { // Make Alyx totally hate this barnacle so that she saves the player. int priority; priority = pAlyx->IRelationPriority(sourceEnt); pAlyx->AddEntityRelationship( sourceEnt, D_HT, priority + 5 ); } #endif//HL2_EPISODIC m_afPhysicsFlags |= PFLAG_ONBARNACLE; ClearUseEntity(); return true; } return false; } void CHL2_Player::PlayerRunCommand(CUserCmd *ucmd, IMoveHelper *moveHelper) { // Handle FL_FROZEN. if ( m_afPhysicsFlags & PFLAG_ONBARNACLE ) { ucmd->forwardmove = 0; ucmd->sidemove = 0; ucmd->upmove = 0; ucmd->buttons &= ~IN_USE; } // Can't use stuff while dead if ( IsDead() ) { ucmd->buttons &= ~IN_USE; } //Update our movement information if ( ( ucmd->forwardmove != 0 ) || ( ucmd->sidemove != 0 ) || ( ucmd->upmove != 0 ) ) { m_flIdleTime -= TICK_INTERVAL * 2.0f; if ( m_flIdleTime < 0.0f ) { m_flIdleTime = 0.0f; } m_flMoveTime += TICK_INTERVAL; if ( m_flMoveTime > 4.0f ) { m_flMoveTime = 4.0f; } } else { m_flIdleTime += TICK_INTERVAL; if ( m_flIdleTime > 4.0f ) { m_flIdleTime = 4.0f; } m_flMoveTime -= TICK_INTERVAL * 2.0f; if ( m_flMoveTime < 0.0f ) { m_flMoveTime = 0.0f; } } //Msg("Player time: [ACTIVE: %f]\t[IDLE: %f]\n", m_flMoveTime, m_flIdleTime ); BaseClass::PlayerRunCommand( ucmd, moveHelper ); } //----------------------------------------------------------------------------- // Purpose: Sets HL2 specific defaults. //----------------------------------------------------------------------------- void CHL2_Player::Spawn(void) { #ifndef HL2MP #ifndef PORTAL SetModel( "models/player.mdl" ); #endif #endif BaseClass::Spawn(); // // Our player movement speed is set once here. This will override the cl_xxxx // cvars unless they are set to be lower than this. // //m_flMaxspeed = 320; if ( !IsSuitEquipped() ) StartWalking(); SuitPower_SetCharge( 100 ); m_Local.m_iHideHUD |= HIDEHUD_CHAT; m_pPlayerAISquad = g_AI_SquadManager.FindCreateSquad(AllocPooledString(PLAYER_SQUADNAME)); InitSprinting(); // Setup our flashlight values #ifdef HL2_EPISODIC m_HL2Local.m_flFlashBattery = 100.0f; #endif GetPlayerProxy(); SetFlashlightPowerDrainScale( 1.0f ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::UpdateLocatorPosition( const Vector &vecPosition ) { #ifdef HL2_EPISODIC m_HL2Local.m_vecLocatorOrigin = vecPosition; #endif//HL2_EPISODIC } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::InitSprinting( void ) { StopSprinting(); } //----------------------------------------------------------------------------- // Purpose: Returns whether or not we are allowed to sprint now. //----------------------------------------------------------------------------- bool CHL2_Player::CanSprint() { return ( m_bSprintEnabled && // Only if sprint is enabled !IsWalking() && // Not if we're walking !( m_Local.m_bDucked && !m_Local.m_bDucking ) && // Nor if we're ducking (GetWaterLevel() != 3) && // Certainly not underwater (GlobalEntity_GetState("suit_no_sprint") != GLOBAL_ON) ); // Out of the question without the sprint module } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::StartAutoSprint() { if( IsSprinting() ) { StopSprinting(); } else { StartSprinting(); m_bIsAutoSprinting = true; m_fAutoSprintMinTime = gpGlobals->curtime + 1.5f; } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::StartSprinting( void ) { if( m_HL2Local.m_flSuitPower < 10 ) { // Don't sprint unless there's a reasonable // amount of suit power. // debounce the button for sound playing if ( m_afButtonPressed & IN_SPEED ) { CPASAttenuationFilter filter( this ); filter.UsePredictionRules(); EmitSound( filter, entindex(), "HL2Player.SprintNoPower" ); } return; } if( !SuitPower_AddDevice( SuitDeviceSprint ) ) return; CPASAttenuationFilter filter( this ); filter.UsePredictionRules(); EmitSound( filter, entindex(), "HL2Player.SprintStart" ); ///// // SO2 - James // Do not allow players to fire weapons while sprinting CSO_Player *pSOPlayer = ToSOPlayer( this ); if ( pSOPlayer ) { pSOPlayer->SetHolsteredWeapon( pSOPlayer->GetActiveWeapon() ); CBaseCombatWeapon *pHolsteredWeapon = pSOPlayer->GetHolsteredWeapon(); if ( pHolsteredWeapon ) pHolsteredWeapon->Holster(); } ///// SetMaxSpeed( HL2_SPRINT_SPEED ); m_fIsSprinting = true; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::StopSprinting( void ) { if ( m_HL2Local.m_bitsActiveDevices & SuitDeviceSprint.GetDeviceID() ) { SuitPower_RemoveDevice( SuitDeviceSprint ); } ///// // SO2 - James // Do not allow players to fire weapons while sprinting CSO_Player *pSOPlayer = ToSOPlayer( this ); if ( pSOPlayer ) { CBaseCombatWeapon *pHolsteredWeapon = pSOPlayer->GetHolsteredWeapon(); if ( pHolsteredWeapon ) { pHolsteredWeapon->Deploy(); pSOPlayer->SetHolsteredWeapon( NULL ); // weapon is no longer holstered; reset variable } } ///// if( IsSuitEquipped() ) { SetMaxSpeed( HL2_NORM_SPEED ); } else { SetMaxSpeed( HL2_WALK_SPEED ); } m_fIsSprinting = false; if ( sv_stickysprint.GetBool() ) { m_bIsAutoSprinting = false; m_fAutoSprintMinTime = 0.0f; } } //----------------------------------------------------------------------------- // Purpose: Called to disable and enable sprint due to temporary circumstances: // - Carrying a heavy object with the physcannon //----------------------------------------------------------------------------- void CHL2_Player::EnableSprint( bool bEnable ) { if ( !bEnable && IsSprinting() ) { StopSprinting(); } m_bSprintEnabled = bEnable; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::StartWalking( void ) { SetMaxSpeed( HL2_WALK_SPEED ); m_fIsWalking = true; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::StopWalking( void ) { SetMaxSpeed( HL2_NORM_SPEED ); m_fIsWalking = false; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CHL2_Player::CanZoom( CBaseEntity *pRequester ) { if ( IsZooming() ) return false; //Check our weapon return true; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::ToggleZoom(void) { if( IsZooming() ) { StopZooming(); } else { StartZooming(); } } //----------------------------------------------------------------------------- // Purpose: +zoom suit zoom //----------------------------------------------------------------------------- void CHL2_Player::StartZooming( void ) { ///// // SO2 - James // Disable suit zooming functionality /*int iFOV = 25; if ( SetFOV( this, iFOV, 0.4f ) ) { m_HL2Local.m_bZooming = true; }*/ ///// } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHL2_Player::StopZooming( void ) { ///// // SO2 - James // Disable suit zooming functionality /*int iFOV = GetZoomOwnerDesiredFOV( m_hZoomOwner ); if ( SetFOV( this, iFOV, 0.2f ) ) { m_HL2Local.m_bZooming = false; }*/ ///// } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CHL2_Player::IsZooming( void ) { if ( m_hZoomOwner != NULL ) return true; return false; } class CPhysicsPlayerCallback : public IPhysicsPlayerControllerEvent { public: int ShouldMoveTo( IPhysicsObject *pObject, const Vector &position ) { CHL2_Player *pPlayer = (CHL2_Player *)pObject->GetGameData(); if ( pPlayer ) { if ( pPlayer->TouchedPhysics() ) { return 0; } } return 1; } }; static CPhysicsPlayerCallback playerCallback; //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHL2_Player::InitVCollision( const Vector &vecAbsOrigin, const Vector &vecAbsVelocity ) { BaseClass::InitVCollision( vecAbsOrigin, vecAbsVelocity ); // Setup the HL2 specific callback. IPhysicsPlayerController *pPlayerController = GetPhysicsController(); if ( pPlayerController ) { pPlayerController->SetEventHandler( &playerCallback ); } } CHL2_Player::~CHL2_Player( void ) { } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CHL2_Player::CommanderFindGoal( commandgoal_t *pGoal ) { CAI_BaseNPC *pAllyNpc; trace_t tr; Vector vecTarget; Vector forward; EyeVectors( &forward ); //--------------------------------- // MASK_SHOT on purpose! So that you don't hit the invisible hulls of the NPCs. CTraceFilterSkipTwoEntities filter( this, PhysCannonGetHeldEntity( GetActiveWeapon() ), COLLISION_GROUP_INTERACTIVE_DEBRIS ); UTIL_TraceLine( EyePosition(), EyePosition() + forward * MAX_COORD_RANGE, MASK_SHOT, &filter, &tr ); if( !tr.DidHitWorld() ) { CUtlVector<CAI_BaseNPC *> Allies; AISquadIter_t iter; for ( pAllyNpc = m_pPlayerAISquad->GetFirstMember(&iter); pAllyNpc; pAllyNpc = m_pPlayerAISquad->GetNextMember(&iter) ) { if ( pAllyNpc->IsCommandable() ) Allies.AddToTail( pAllyNpc ); } for( int i = 0 ; i < Allies.Count() ; i++ ) { if( Allies[ i ]->IsValidCommandTarget( tr.m_pEnt ) ) { pGoal->m_pGoalEntity = tr.m_pEnt; return true; } } } if( tr.fraction == 1.0 || (tr.surface.flags & SURF_SKY) ) { // Move commands invalid against skybox. pGoal->m_vecGoalLocation = tr.endpos; return false; } if ( tr.m_pEnt->IsNPC() && ((CAI_BaseNPC *)(tr.m_pEnt))->IsCommandable() ) { pGoal->m_vecGoalLocation = tr.m_pEnt->GetAbsOrigin(); } else { vecTarget = tr.endpos; Vector mins( -16, -16, 0 ); Vector maxs( 16, 16, 0 ); // Back up from whatever we hit so that there's enough space at the // target location for a bounding box. // Now trace down. //UTIL_TraceLine( vecTarget, vecTarget - Vector( 0, 0, 8192 ), MASK_SOLID, this, COLLISION_GROUP_NONE, &tr ); UTIL_TraceHull( vecTarget + tr.plane.normal * 24, vecTarget - Vector( 0, 0, 8192 ), mins, maxs, MASK_SOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, &tr ); if ( !tr.startsolid ) pGoal->m_vecGoalLocation = tr.endpos; else pGoal->m_vecGoalLocation = vecTarget; } pAllyNpc = GetSquadCommandRepresentative(); if ( !pAllyNpc ) return false; vecTarget = pGoal->m_vecGoalLocation; if ( !pAllyNpc->FindNearestValidGoalPos( vecTarget, &pGoal->m_vecGoalLocation ) ) return false; return ( ( vecTarget - pGoal->m_vecGoalLocation ).LengthSqr() < Square( 15*12 ) ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- CAI_BaseNPC *CHL2_Player::GetSquadCommandRepresentative() { if ( m_pPlayerAISquad != NULL ) { CAI_BaseNPC *pAllyNpc = m_pPlayerAISquad->GetFirstMember(); if ( pAllyNpc ) { return pAllyNpc->GetSquadCommandRepresentative(); } } return NULL; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- int CHL2_Player::GetNumSquadCommandables() { AISquadIter_t iter; int c = 0; for ( CAI_BaseNPC *pAllyNpc = m_pPlayerAISquad->GetFirstMember(&iter); pAllyNpc; pAllyNpc = m_pPlayerAISquad->GetNextMember(&iter) ) { if ( pAllyNpc->IsCommandable() ) c++; } return c; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- int CHL2_Player::GetNumSquadCommandableMedics() { AISquadIter_t iter; int c = 0; for ( CAI_BaseNPC *pAllyNpc = m_pPlayerAISquad->GetFirstMember(&iter); pAllyNpc; pAllyNpc = m_pPlayerAISquad->GetNextMember(&iter) ) { if ( pAllyNpc->IsCommandable() && pAllyNpc->IsMedic() ) c++; } return c; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::CommanderUpdate() { CAI_BaseNPC *pCommandRepresentative = GetSquadCommandRepresentative(); bool bFollowMode = false; if ( pCommandRepresentative ) { bFollowMode = ( pCommandRepresentative->GetCommandGoal() == vec3_invalid ); // set the variables for network transmission (to show on the hud) m_HL2Local.m_iSquadMemberCount = GetNumSquadCommandables(); m_HL2Local.m_iSquadMedicCount = GetNumSquadCommandableMedics(); m_HL2Local.m_fSquadInFollowMode = bFollowMode; // debugging code for displaying extra squad indicators /* char *pszMoving = ""; AISquadIter_t iter; for ( CAI_BaseNPC *pAllyNpc = m_pPlayerAISquad->GetFirstMember(&iter); pAllyNpc; pAllyNpc = m_pPlayerAISquad->GetNextMember(&iter) ) { if ( pAllyNpc->IsCommandMoving() ) { pszMoving = "<-"; break; } } NDebugOverlay::ScreenText( 0.932, 0.919, CFmtStr( "%d|%c%s", GetNumSquadCommandables(), ( bFollowMode ) ? 'F' : 'S', pszMoving ), 255, 128, 0, 128, 0 ); */ } else { m_HL2Local.m_iSquadMemberCount = 0; m_HL2Local.m_iSquadMedicCount = 0; m_HL2Local.m_fSquadInFollowMode = true; } if ( m_QueuedCommand != CC_NONE && ( m_QueuedCommand == CC_FOLLOW || gpGlobals->realtime - m_RealTimeLastSquadCommand >= player_squad_double_tap_time.GetFloat() ) ) { CommanderExecute( m_QueuedCommand ); m_QueuedCommand = CC_NONE; } else if ( !bFollowMode && pCommandRepresentative && m_CommanderUpdateTimer.Expired() && player_squad_transient_commands.GetBool() ) { m_CommanderUpdateTimer.Set(2.5); if ( pCommandRepresentative->ShouldAutoSummon() ) CommanderExecute( CC_FOLLOW ); } } //----------------------------------------------------------------------------- // Purpose: // // bHandled - indicates whether to continue delivering this order to // all allies. Allows us to stop delivering certain types of orders once we find // a suitable candidate. (like picking up a single weapon. We don't wish for // all allies to respond and try to pick up one weapon). //----------------------------------------------------------------------------- bool CHL2_Player::CommanderExecuteOne( CAI_BaseNPC *pNpc, const commandgoal_t &goal, CAI_BaseNPC **Allies, int numAllies ) { if ( goal.m_pGoalEntity ) { return pNpc->TargetOrder( goal.m_pGoalEntity, Allies, numAllies ); } else if ( pNpc->IsInPlayerSquad() ) { pNpc->MoveOrder( goal.m_vecGoalLocation, Allies, numAllies ); } return true; } //--------------------------------------------------------- //--------------------------------------------------------- void CHL2_Player::CommanderExecute( CommanderCommand_t command ) { CAI_BaseNPC *pPlayerSquadLeader = GetSquadCommandRepresentative(); if ( !pPlayerSquadLeader ) { EmitSound( "HL2Player.UseDeny" ); return; } int i; CUtlVector<CAI_BaseNPC *> Allies; commandgoal_t goal; if ( command == CC_TOGGLE ) { if ( pPlayerSquadLeader->GetCommandGoal() != vec3_invalid ) command = CC_FOLLOW; else command = CC_SEND; } else { if ( command == CC_FOLLOW && pPlayerSquadLeader->GetCommandGoal() == vec3_invalid ) return; } if ( command == CC_FOLLOW ) { goal.m_pGoalEntity = this; goal.m_vecGoalLocation = vec3_invalid; } else { goal.m_pGoalEntity = NULL; goal.m_vecGoalLocation = vec3_invalid; // Find a goal for ourselves. if( !CommanderFindGoal( &goal ) ) { EmitSound( "HL2Player.UseDeny" ); return; // just keep following } } #ifdef _DEBUG if( goal.m_pGoalEntity == NULL && goal.m_vecGoalLocation == vec3_invalid ) { DevMsg( 1, "**ERROR: Someone sent an invalid goal to CommanderExecute!\n" ); } #endif // _DEBUG AISquadIter_t iter; for ( CAI_BaseNPC *pAllyNpc = m_pPlayerAISquad->GetFirstMember(&iter); pAllyNpc; pAllyNpc = m_pPlayerAISquad->GetNextMember(&iter) ) { if ( pAllyNpc->IsCommandable() ) Allies.AddToTail( pAllyNpc ); } //--------------------------------- // If the trace hits an NPC, send all ally NPCs a "target" order. Always // goes to targeted one first #ifdef DEBUG int nAIs = g_AI_Manager.NumAIs(); #endif CAI_BaseNPC * pTargetNpc = (goal.m_pGoalEntity) ? goal.m_pGoalEntity->MyNPCPointer() : NULL; bool bHandled = false; if( pTargetNpc ) { bHandled = !CommanderExecuteOne( pTargetNpc, goal, Allies.Base(), Allies.Count() ); } for ( i = 0; !bHandled && i < Allies.Count(); i++ ) { if ( Allies[i] != pTargetNpc && Allies[i]->IsPlayerAlly() ) { bHandled = !CommanderExecuteOne( Allies[i], goal, Allies.Base(), Allies.Count() ); } Assert( nAIs == g_AI_Manager.NumAIs() ); // not coded to support mutating set of NPCs } } //----------------------------------------------------------------------------- // Enter/exit commander mode, manage ally selection. //----------------------------------------------------------------------------- void CHL2_Player::CommanderMode() { float commandInterval = gpGlobals->realtime - m_RealTimeLastSquadCommand; m_RealTimeLastSquadCommand = gpGlobals->realtime; if ( commandInterval < player_squad_double_tap_time.GetFloat() ) { m_QueuedCommand = CC_FOLLOW; } else { m_QueuedCommand = (player_squad_transient_commands.GetBool()) ? CC_SEND : CC_TOGGLE; } } //----------------------------------------------------------------------------- // Purpose: // Input : iImpulse - //----------------------------------------------------------------------------- void CHL2_Player::CheatImpulseCommands( int iImpulse ) { switch( iImpulse ) { case 50: { CommanderMode(); break; } case 51: { // Cheat to create a dynamic resupply item Vector vecForward; AngleVectors( EyeAngles(), &vecForward ); CBaseEntity *pItem = (CBaseEntity *)CreateEntityByName( "item_dynamic_resupply" ); if ( pItem ) { Vector vecOrigin = GetAbsOrigin() + vecForward * 256 + Vector(0,0,64); QAngle vecAngles( 0, GetAbsAngles().y - 90, 0 ); pItem->SetAbsOrigin( vecOrigin ); pItem->SetAbsAngles( vecAngles ); pItem->KeyValue( "targetname", "resupply" ); pItem->Spawn(); pItem->Activate(); } break; } case 52: { // Rangefinder trace_t tr; UTIL_TraceLine( EyePosition(), EyePosition() + EyeDirection3D() * MAX_COORD_RANGE, MASK_SHOT, this, COLLISION_GROUP_NONE, &tr ); if( tr.fraction != 1.0 ) { float flDist = (tr.startpos - tr.endpos).Length(); float flDist2D = (tr.startpos - tr.endpos).Length2D(); DevMsg( 1,"\nStartPos: %.4f %.4f %.4f --- EndPos: %.4f %.4f %.4f\n", tr.startpos.x,tr.startpos.y,tr.startpos.z,tr.endpos.x,tr.endpos.y,tr.endpos.z ); DevMsg( 1,"3D Distance: %.4f units (%.2f feet) --- 2D Distance: %.4f units (%.2f feet)\n", flDist, flDist / 12.0, flDist2D, flDist2D / 12.0 ); } break; } default: BaseClass::CheatImpulseCommands( iImpulse ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHL2_Player::SetupVisibility( CBaseEntity *pViewEntity, unsigned char *pvs, int pvssize ) { BaseClass::SetupVisibility( pViewEntity, pvs, pvssize ); int area = pViewEntity ? pViewEntity->NetworkProp()->AreaNum() : NetworkProp()->AreaNum(); PointCameraSetupVisibility( this, area, pvs, pvssize ); // If the intro script is playing, we want to get it's visibility points if ( g_hIntroScript ) { Vector vecOrigin; CBaseEntity *pCamera; if ( g_hIntroScript->GetIncludedPVSOrigin( &vecOrigin, &pCamera ) ) { // If it's a point camera, turn it on CPointCamera *pPointCamera = dynamic_cast< CPointCamera* >(pCamera); if ( pPointCamera ) { pPointCamera->SetActive( true ); } engine->AddOriginToPVS( vecOrigin ); } } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::SuitPower_Update( void ) { if( SuitPower_ShouldRecharge() ) { SuitPower_Charge( SUITPOWER_CHARGE_RATE * gpGlobals->frametime ); } else if( m_HL2Local.m_bitsActiveDevices ) { float flPowerLoad = m_flSuitPowerLoad; //Since stickysprint quickly shuts off sprint if it isn't being used, this isn't an issue. if ( !sv_stickysprint.GetBool() ) { if( SuitPower_IsDeviceActive(SuitDeviceSprint) ) { if( !fabs(GetAbsVelocity().x) && !fabs(GetAbsVelocity().y) ) { // If player's not moving, don't drain sprint juice. flPowerLoad -= SuitDeviceSprint.GetDeviceDrainRate(); } } } if( SuitPower_IsDeviceActive(SuitDeviceFlashlight) ) { float factor; factor = 1.0f / m_flFlashlightPowerDrainScale; flPowerLoad -= ( SuitDeviceFlashlight.GetDeviceDrainRate() * (1.0f - factor) ); } if( !SuitPower_Drain( flPowerLoad * gpGlobals->frametime ) ) { // TURN OFF ALL DEVICES!! if( IsSprinting() ) { StopSprinting(); } if ( Flashlight_UseLegacyVersion() ) { if( FlashlightIsOn() ) { #ifndef HL2MP FlashlightTurnOff(); #endif } } } if ( Flashlight_UseLegacyVersion() ) { // turn off flashlight a little bit after it hits below one aux power notch (5%) if( m_HL2Local.m_flSuitPower < 4.8f && FlashlightIsOn() ) { #ifndef HL2MP FlashlightTurnOff(); #endif } } } } //----------------------------------------------------------------------------- // Charge battery fully, turn off all devices. //----------------------------------------------------------------------------- void CHL2_Player::SuitPower_Initialize( void ) { m_HL2Local.m_bitsActiveDevices = 0x00000000; m_HL2Local.m_flSuitPower = 100.0; m_flSuitPowerLoad = 0.0; } //----------------------------------------------------------------------------- // Purpose: Interface to drain power from the suit's power supply. // Input: Amount of charge to remove (expressed as percentage of full charge) // Output: Returns TRUE if successful, FALSE if not enough power available. //----------------------------------------------------------------------------- bool CHL2_Player::SuitPower_Drain( float flPower ) { // Suitpower cheat on? if ( sv_infinite_aux_power.GetBool() ) return true; m_HL2Local.m_flSuitPower -= flPower; if( m_HL2Local.m_flSuitPower < 0.0 ) { // Power is depleted! // Clamp and fail m_HL2Local.m_flSuitPower = 0.0; return false; } return true; } //----------------------------------------------------------------------------- // Purpose: Interface to add power to the suit's power supply // Input: Amount of charge to add //----------------------------------------------------------------------------- void CHL2_Player::SuitPower_Charge( float flPower ) { m_HL2Local.m_flSuitPower += flPower; if( m_HL2Local.m_flSuitPower > 100.0 ) { // Full charge, clamp. m_HL2Local.m_flSuitPower = 100.0; } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CHL2_Player::SuitPower_IsDeviceActive( const CSuitPowerDevice &device ) { return (m_HL2Local.m_bitsActiveDevices & device.GetDeviceID()) != 0; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CHL2_Player::SuitPower_AddDevice( const CSuitPowerDevice &device ) { // Make sure this device is NOT active!! if( m_HL2Local.m_bitsActiveDevices & device.GetDeviceID() ) return false; if( !IsSuitEquipped() ) return false; m_HL2Local.m_bitsActiveDevices |= device.GetDeviceID(); m_flSuitPowerLoad += device.GetDeviceDrainRate(); return true; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CHL2_Player::SuitPower_RemoveDevice( const CSuitPowerDevice &device ) { // Make sure this device is active!! if( ! (m_HL2Local.m_bitsActiveDevices & device.GetDeviceID()) ) return false; if( !IsSuitEquipped() ) return false; // Take a little bit of suit power when you disable a device. If the device is shutting off // because the battery is drained, no harm done, the battery charge cannot go below 0. // This code in combination with the delay before the suit can start recharging are a defense // against exploits where the player could rapidly tap sprint and never run out of power. SuitPower_Drain( device.GetDeviceDrainRate() * 0.1f ); m_HL2Local.m_bitsActiveDevices &= ~device.GetDeviceID(); m_flSuitPowerLoad -= device.GetDeviceDrainRate(); if( m_HL2Local.m_bitsActiveDevices == 0x00000000 ) { // With this device turned off, we can set this timer which tells us when the // suit power system entered a no-load state. m_flTimeAllSuitDevicesOff = gpGlobals->curtime; } return true; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- #define SUITPOWER_BEGIN_RECHARGE_DELAY 0.5f bool CHL2_Player::SuitPower_ShouldRecharge( void ) { // Make sure all devices are off. if( m_HL2Local.m_bitsActiveDevices != 0x00000000 ) return false; // Is the system fully charged? if( m_HL2Local.m_flSuitPower >= 100.0f ) return false; // Has the system been in a no-load state for long enough // to begin recharging? if( gpGlobals->curtime < m_flTimeAllSuitDevicesOff + SUITPOWER_BEGIN_RECHARGE_DELAY ) return false; return true; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- ConVar sk_battery( "sk_battery","0" ); bool CHL2_Player::ApplyBattery( float powerMultiplier ) { const float MAX_NORMAL_BATTERY = 100; if ((ArmorValue() < MAX_NORMAL_BATTERY) && IsSuitEquipped()) { int pct; char szcharge[64]; IncrementArmorValue( sk_battery.GetFloat() * powerMultiplier, MAX_NORMAL_BATTERY ); CPASAttenuationFilter filter( this, "ItemBattery.Touch" ); EmitSound( filter, entindex(), "ItemBattery.Touch" ); CSingleUserRecipientFilter user( this ); user.MakeReliable(); UserMessageBegin( user, "ItemPickup" ); WRITE_STRING( "item_battery" ); MessageEnd(); // Suit reports new power level // For some reason this wasn't working in release build -- round it. pct = (int)( (float)(ArmorValue() * 100.0) * (1.0/MAX_NORMAL_BATTERY) + 0.5); pct = (pct / 5); if (pct > 0) pct--; Q_snprintf( szcharge,sizeof(szcharge),"!HEV_%1dP", pct ); //UTIL_EmitSoundSuit(edict(), szcharge); //SetSuitUpdate(szcharge, FALSE, SUIT_NEXT_IN_30SEC); return true; } return false; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- int CHL2_Player::FlashlightIsOn( void ) { return IsEffectActive( EF_DIMLIGHT ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::FlashlightTurnOn( void ) { if( m_bFlashlightDisabled ) return; if ( Flashlight_UseLegacyVersion() ) { if( !SuitPower_AddDevice( SuitDeviceFlashlight ) ) return; } #ifdef HL2_DLL if( !IsSuitEquipped() ) return; #endif AddEffects( EF_DIMLIGHT ); EmitSound( "HL2Player.FlashLightOn" ); variant_t flashlighton; flashlighton.SetFloat( m_HL2Local.m_flSuitPower / 100.0f ); FirePlayerProxyOutput( "OnFlashlightOn", flashlighton, this, this ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::FlashlightTurnOff( void ) { if ( Flashlight_UseLegacyVersion() ) { if( !SuitPower_RemoveDevice( SuitDeviceFlashlight ) ) return; } RemoveEffects( EF_DIMLIGHT ); EmitSound( "HL2Player.FlashLightOff" ); variant_t flashlightoff; flashlightoff.SetFloat( m_HL2Local.m_flSuitPower / 100.0f ); FirePlayerProxyOutput( "OnFlashlightOff", flashlightoff, this, this ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- #define FLASHLIGHT_RANGE Square(600) bool CHL2_Player::IsIlluminatedByFlashlight( CBaseEntity *pEntity, float *flReturnDot ) { if( !FlashlightIsOn() ) return false; if( pEntity->Classify() == CLASS_BARNACLE && pEntity->GetEnemy() == this ) { // As long as my flashlight is on, the barnacle that's pulling me in is considered illuminated. // This is because players often shine their flashlights at Alyx when they are in a barnacle's // grasp, and wonder why Alyx isn't helping. Alyx isn't helping because the light isn't pointed // at the barnacle. This will allow Alyx to see the barnacle no matter which way the light is pointed. return true; } // Within 50 feet? float flDistSqr = GetAbsOrigin().DistToSqr(pEntity->GetAbsOrigin()); if( flDistSqr > FLASHLIGHT_RANGE ) return false; // Within 45 degrees? Vector vecSpot = pEntity->WorldSpaceCenter(); Vector los; // If the eyeposition is too close, move it back. Solves problems // caused by the player being too close the target. if ( flDistSqr < (128 * 128) ) { Vector vecForward; EyeVectors( &vecForward ); Vector vecMovedEyePos = EyePosition() - (vecForward * 128); los = ( vecSpot - vecMovedEyePos ); } else { los = ( vecSpot - EyePosition() ); } VectorNormalize( los ); Vector facingDir = EyeDirection3D( ); float flDot = DotProduct( los, facingDir ); if ( flReturnDot ) { *flReturnDot = flDot; } if ( flDot < 0.92387f ) return false; if( !FVisible(pEntity) ) return false; return true; } //----------------------------------------------------------------------------- // Purpose: Let NPCs know when the flashlight is trained on them //----------------------------------------------------------------------------- void CHL2_Player::CheckFlashlight( void ) { if ( !FlashlightIsOn() ) return; if ( m_flNextFlashlightCheckTime > gpGlobals->curtime ) return; m_flNextFlashlightCheckTime = gpGlobals->curtime + FLASHLIGHT_NPC_CHECK_INTERVAL; // Loop through NPCs looking for illuminated ones for ( int i = 0; i < g_AI_Manager.NumAIs(); i++ ) { CAI_BaseNPC *pNPC = g_AI_Manager.AccessAIs()[i]; float flDot; if ( IsIlluminatedByFlashlight( pNPC, &flDot ) ) { pNPC->PlayerHasIlluminatedNPC( this, flDot ); } } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::SetPlayerUnderwater( bool state ) { if ( state ) { SuitPower_AddDevice( SuitDeviceBreather ); } else { SuitPower_RemoveDevice( SuitDeviceBreather ); } BaseClass::SetPlayerUnderwater( state ); } //----------------------------------------------------------------------------- bool CHL2_Player::PassesDamageFilter( const CTakeDamageInfo &info ) { CBaseEntity *pAttacker = info.GetAttacker(); if( pAttacker && pAttacker->MyNPCPointer() && pAttacker->MyNPCPointer()->IsPlayerAlly() ) { return false; } if( m_hPlayerProxy && !m_hPlayerProxy->PassesDamageFilter( info ) ) { return false; } return BaseClass::PassesDamageFilter( info ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHL2_Player::SetFlashlightEnabled( bool bState ) { m_bFlashlightDisabled = !bState; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::InputDisableFlashlight( inputdata_t &inputdata ) { if( FlashlightIsOn() ) FlashlightTurnOff(); SetFlashlightEnabled( false ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::InputEnableFlashlight( inputdata_t &inputdata ) { SetFlashlightEnabled( true ); } //----------------------------------------------------------------------------- // Purpose: Prevent the player from taking fall damage for [n] seconds, but // reset back to taking fall damage after the first impact (so players will be // hurt if they bounce off what they hit). This is the original behavior. //----------------------------------------------------------------------------- void CHL2_Player::InputIgnoreFallDamage( inputdata_t &inputdata ) { float timeToIgnore = inputdata.value.Float(); if ( timeToIgnore <= 0.0 ) timeToIgnore = TIME_IGNORE_FALL_DAMAGE; m_flTimeIgnoreFallDamage = gpGlobals->curtime + timeToIgnore; m_bIgnoreFallDamageResetAfterImpact = true; } //----------------------------------------------------------------------------- // Purpose: Absolutely prevent the player from taking fall damage for [n] seconds. //----------------------------------------------------------------------------- void CHL2_Player::InputIgnoreFallDamageWithoutReset( inputdata_t &inputdata ) { float timeToIgnore = inputdata.value.Float(); if ( timeToIgnore <= 0.0 ) timeToIgnore = TIME_IGNORE_FALL_DAMAGE; m_flTimeIgnoreFallDamage = gpGlobals->curtime + timeToIgnore; m_bIgnoreFallDamageResetAfterImpact = false; } //----------------------------------------------------------------------------- // Purpose: Notification of a player's npc ally in the players squad being killed //----------------------------------------------------------------------------- void CHL2_Player::OnSquadMemberKilled( inputdata_t &data ) { // send a message to the client, to notify the hud of the loss CSingleUserRecipientFilter user( this ); user.MakeReliable(); UserMessageBegin( user, "SquadMemberDied" ); MessageEnd(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHL2_Player::NotifyFriendsOfDamage( CBaseEntity *pAttackerEntity ) { CAI_BaseNPC *pAttacker = pAttackerEntity->MyNPCPointer(); if ( pAttacker ) { const Vector &origin = GetAbsOrigin(); for ( int i = 0; i < g_AI_Manager.NumAIs(); i++ ) { const float NEAR_Z = 12*12; const float NEAR_XY_SQ = Square( 50*12 ); CAI_BaseNPC *pNpc = g_AI_Manager.AccessAIs()[i]; if ( pNpc->IsPlayerAlly() ) { const Vector &originNpc = pNpc->GetAbsOrigin(); if ( fabsf( originNpc.z - origin.z ) < NEAR_Z ) { if ( (originNpc.AsVector2D() - origin.AsVector2D()).LengthSqr() < NEAR_XY_SQ ) { pNpc->OnFriendDamaged( this, pAttacker ); } } } } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- ConVar test_massive_dmg("test_massive_dmg", "30" ); ConVar test_massive_dmg_clip("test_massive_dmg_clip", "0.5" ); int CHL2_Player::OnTakeDamage( const CTakeDamageInfo &info ) { if ( GlobalEntity_GetState( "gordon_invulnerable" ) == GLOBAL_ON ) return 0; // ignore fall damage if instructed to do so by input if ( ( info.GetDamageType() & DMG_FALL ) && m_flTimeIgnoreFallDamage > gpGlobals->curtime ) { // usually, we will reset the input flag after the first impact. However there is another input that // prevents this behavior. if ( m_bIgnoreFallDamageResetAfterImpact ) { m_flTimeIgnoreFallDamage = 0; } return 0; } if( info.GetDamageType() & DMG_BLAST_SURFACE ) { if( GetWaterLevel() > 2 ) { // Don't take blast damage from anything above the surface. if( info.GetInflictor()->GetWaterLevel() == 0 ) { return 0; } } } if ( info.GetDamage() > 0.0f ) { m_flLastDamageTime = gpGlobals->curtime; if ( info.GetAttacker() ) NotifyFriendsOfDamage( info.GetAttacker() ); } // Modify the amount of damage the player takes, based on skill. CTakeDamageInfo playerDamage = info; // Should we run this damage through the skill level adjustment? bool bAdjustForSkillLevel = true; if( info.GetDamageType() == DMG_GENERIC && info.GetAttacker() == this && info.GetInflictor() == this ) { // Only do a skill level adjustment if the player isn't his own attacker AND inflictor. // This prevents damage from SetHealth() inputs from being adjusted for skill level. bAdjustForSkillLevel = false; } if ( GetVehicleEntity() != NULL && GlobalEntity_GetState("gordon_protect_driver") == GLOBAL_ON ) { if( playerDamage.GetDamage() > test_massive_dmg.GetFloat() && playerDamage.GetInflictor() == GetVehicleEntity() && (playerDamage.GetDamageType() & DMG_CRUSH) ) { playerDamage.ScaleDamage( test_massive_dmg_clip.GetFloat() / playerDamage.GetDamage() ); } } if( bAdjustForSkillLevel ) { playerDamage.AdjustPlayerDamageTakenForSkillLevel(); } gamestats->Event_PlayerDamage( this, info ); return BaseClass::OnTakeDamage( playerDamage ); } //----------------------------------------------------------------------------- // Purpose: // Input : &info - //----------------------------------------------------------------------------- int CHL2_Player::OnTakeDamage_Alive( const CTakeDamageInfo &info ) { // Drown if( info.GetDamageType() & DMG_DROWN ) { if( m_idrowndmg == m_idrownrestored ) { EmitSound( "Player.DrownStart" ); } else { EmitSound( "Player.DrownContinue" ); } } // Burnt if ( info.GetDamageType() & DMG_BURN ) { EmitSound( "HL2Player.BurnPain" ); } if( (info.GetDamageType() & DMG_SLASH) && hl2_episodic.GetBool() ) { if( m_afPhysicsFlags & PFLAG_USING ) { // Stop the player using a rotating button for a short time if hit by a creature's melee attack. // This is for the antlion burrow-corking training in EP1 (sjb). SuspendUse( 0.5f ); } } // Call the base class implementation return BaseClass::OnTakeDamage_Alive( info ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::OnDamagedByExplosion( const CTakeDamageInfo &info ) { if ( info.GetInflictor() && info.GetInflictor()->ClassMatches( "mortarshell" ) ) { // No ear ringing for mortar UTIL_ScreenShake( info.GetInflictor()->GetAbsOrigin(), 4.0, 1.0, 0.5, 1000, SHAKE_START, false ); return; } BaseClass::OnDamagedByExplosion( info ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CHL2_Player::ShouldShootMissTarget( CBaseCombatCharacter *pAttacker ) { if( gpGlobals->curtime > m_flTargetFindTime ) { // Put this off into the future again. m_flTargetFindTime = gpGlobals->curtime + random->RandomFloat( 3, 5 ); return true; } return false; } //----------------------------------------------------------------------------- // Purpose: Notifies Alyx that player has put a combine ball into a socket so she can comment on it. // Input : pCombineBall - ball the was socketed //----------------------------------------------------------------------------- void CHL2_Player::CombineBallSocketed( CPropCombineBall *pCombineBall ) { #ifdef HL2_EPISODIC CNPC_Alyx *pAlyx = CNPC_Alyx::GetAlyx(); if ( pAlyx ) { pAlyx->CombineBallSocketed( pCombineBall->NumBounces() ); } #endif } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::Event_KilledOther( CBaseEntity *pVictim, const CTakeDamageInfo &info ) { BaseClass::Event_KilledOther( pVictim, info ); #ifdef HL2_EPISODIC CAI_BaseNPC **ppAIs = g_AI_Manager.AccessAIs(); for ( int i = 0; i < g_AI_Manager.NumAIs(); i++ ) { if ( ppAIs[i] && ppAIs[i]->IRelationType(this) == D_LI ) { ppAIs[i]->OnPlayerKilledOther( pVictim, info ); } } #endif } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::Event_Killed( const CTakeDamageInfo &info ) { BaseClass::Event_Killed( info ); FirePlayerProxyOutput( "PlayerDied", variant_t(), this, this ); NotifyScriptsOfDeath(); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::NotifyScriptsOfDeath( void ) { CBaseEntity *pEnt = gEntList.FindEntityByClassname( NULL, "scripted_sequence" ); while( pEnt ) { variant_t emptyVariant; pEnt->AcceptInput( "ScriptPlayerDeath", NULL, NULL, emptyVariant, 0 ); pEnt = gEntList.FindEntityByClassname( pEnt, "scripted_sequence" ); } pEnt = gEntList.FindEntityByClassname( NULL, "logic_choreographed_scene" ); while( pEnt ) { variant_t emptyVariant; pEnt->AcceptInput( "ScriptPlayerDeath", NULL, NULL, emptyVariant, 0 ); pEnt = gEntList.FindEntityByClassname( pEnt, "logic_choreographed_scene" ); } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::GetAutoaimVector( autoaim_params_t &params ) { BaseClass::GetAutoaimVector( params ); if ( IsX360() ) { if( IsInAVehicle() ) { if( m_hLockedAutoAimEntity && m_hLockedAutoAimEntity->IsAlive() && ShouldKeepLockedAutoaimTarget(m_hLockedAutoAimEntity) ) { if( params.m_hAutoAimEntity && params.m_hAutoAimEntity != m_hLockedAutoAimEntity ) { // Autoaim has picked a new target. Switch. m_hLockedAutoAimEntity = params.m_hAutoAimEntity; } // Ignore autoaim and just keep aiming at this target. params.m_hAutoAimEntity = m_hLockedAutoAimEntity; Vector vecTarget = m_hLockedAutoAimEntity->BodyTarget( EyePosition(), false ); Vector vecDir = vecTarget - EyePosition(); VectorNormalize( vecDir ); params.m_vecAutoAimDir = vecDir; params.m_vecAutoAimPoint = vecTarget; return; } else { m_hLockedAutoAimEntity = NULL; } } // If the player manually gets his crosshair onto a target, make that target sticky if( params.m_fScale != AUTOAIM_SCALE_DIRECT_ONLY ) { // Only affect this for 'real' queries //if( params.m_hAutoAimEntity && params.m_bOnTargetNatural ) if( params.m_hAutoAimEntity ) { // Turn on sticky. m_HL2Local.m_bStickyAutoAim = true; if( IsInAVehicle() ) { m_hLockedAutoAimEntity = params.m_hAutoAimEntity; } } else if( !params.m_hAutoAimEntity ) { // Turn off sticky only if there's no target at all. m_HL2Local.m_bStickyAutoAim = false; m_hLockedAutoAimEntity = NULL; } } } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CHL2_Player::ShouldKeepLockedAutoaimTarget( EHANDLE hLockedTarget ) { Vector vecLooking; Vector vecToTarget; vecToTarget = hLockedTarget->WorldSpaceCenter() - EyePosition(); float flDist = vecToTarget.Length2D(); VectorNormalize( vecToTarget ); if( flDist > autoaim_max_dist.GetFloat() ) return false; float flDot; vecLooking = EyeDirection3D(); flDot = DotProduct( vecLooking, vecToTarget ); if( flDot < autoaim_unlock_target.GetFloat() ) return false; return true; } //----------------------------------------------------------------------------- // Purpose: // Input : iCount - // iAmmoIndex - // bSuppressSound - // Output : int //----------------------------------------------------------------------------- int CHL2_Player::GiveAmmo( int nCount, int nAmmoIndex, bool bSuppressSound) { // Don't try to give the player invalid ammo indices. if (nAmmoIndex < 0) return 0; bool bCheckAutoSwitch = false; if (!HasAnyAmmoOfType(nAmmoIndex)) { bCheckAutoSwitch = true; } int nAdd = BaseClass::GiveAmmo(nCount, nAmmoIndex, bSuppressSound); if ( nCount > 0 && nAdd == 0 ) { // we've been denied the pickup, display a hud icon to show that CSingleUserRecipientFilter user( this ); user.MakeReliable(); UserMessageBegin( user, "AmmoDenied" ); WRITE_SHORT( nAmmoIndex ); MessageEnd(); } // // If I was dry on ammo for my best weapon and justed picked up ammo for it, // autoswitch to my best weapon now. // if (bCheckAutoSwitch) { CBaseCombatWeapon *pWeapon = g_pGameRules->GetNextBestWeapon(this, GetActiveWeapon()); if ( pWeapon && pWeapon->GetPrimaryAmmoType() == nAmmoIndex ) { SwitchToNextBestWeapon(GetActiveWeapon()); } } return nAdd; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CHL2_Player::Weapon_CanUse( CBaseCombatWeapon *pWeapon ) { #ifndef HL2MP if ( pWeapon->ClassMatches( "weapon_stunstick" ) ) { if ( ApplyBattery( 0.5 ) ) UTIL_Remove( pWeapon ); return false; } #endif return BaseClass::Weapon_CanUse( pWeapon ); } //----------------------------------------------------------------------------- // Purpose: // Input : *pWeapon - //----------------------------------------------------------------------------- void CHL2_Player::Weapon_Equip( CBaseCombatWeapon *pWeapon ) { #if HL2_SINGLE_PRIMARY_WEAPON_MODE if ( pWeapon->GetSlot() == WEAPON_PRIMARY_SLOT ) { Weapon_DropSlot( WEAPON_PRIMARY_SLOT ); } #endif if( GetActiveWeapon() == NULL ) { m_HL2Local.m_bWeaponLowered = false; } BaseClass::Weapon_Equip( pWeapon ); } //----------------------------------------------------------------------------- // Purpose: Player reacts to bumping a weapon. // Input : pWeapon - the weapon that the player bumped into. // Output : Returns true if player picked up the weapon //----------------------------------------------------------------------------- bool CHL2_Player::BumpWeapon( CBaseCombatWeapon *pWeapon ) { #if HL2_SINGLE_PRIMARY_WEAPON_MODE CBaseCombatCharacter *pOwner = pWeapon->GetOwner(); // Can I have this weapon type? if ( pOwner || !Weapon_CanUse( pWeapon ) || !g_pGameRules->CanHavePlayerItem( this, pWeapon ) ) { if ( gEvilImpulse101 ) { UTIL_Remove( pWeapon ); } return false; } // ---------------------------------------- // If I already have it just take the ammo // ---------------------------------------- if (Weapon_OwnsThisType( pWeapon->GetClassname(), pWeapon->GetSubType())) { //Only remove the weapon if we attained ammo from it if ( Weapon_EquipAmmoOnly( pWeapon ) == false ) return false; // Only remove me if I have no ammo left // Can't just check HasAnyAmmo because if I don't use clips, I want to be removed, if ( pWeapon->UsesClipsForAmmo1() && pWeapon->HasPrimaryAmmo() ) return false; UTIL_Remove( pWeapon ); return false; } // ------------------------- // Otherwise take the weapon // ------------------------- else { //Make sure we're not trying to take a new weapon type we already have if ( Weapon_SlotOccupied( pWeapon ) ) { CBaseCombatWeapon *pActiveWeapon = Weapon_GetSlot( WEAPON_PRIMARY_SLOT ); if ( pActiveWeapon != NULL && pActiveWeapon->HasAnyAmmo() == false && Weapon_CanSwitchTo( pWeapon ) ) { Weapon_Equip( pWeapon ); return true; } //Attempt to take ammo if this is the gun we're holding already if ( Weapon_OwnsThisType( pWeapon->GetClassname(), pWeapon->GetSubType() ) ) { Weapon_EquipAmmoOnly( pWeapon ); } return false; } pWeapon->CheckRespawn(); pWeapon->AddSolidFlags( FSOLID_NOT_SOLID ); pWeapon->AddEffects( EF_NODRAW ); Weapon_Equip( pWeapon ); EmitSound( "HL2Player.PickupWeapon" ); return true; } #else return BaseClass::BumpWeapon( pWeapon ); #endif } //----------------------------------------------------------------------------- // Purpose: // Input : *cmd - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CHL2_Player::ClientCommand( const CCommand &args ) { #if HL2_SINGLE_PRIMARY_WEAPON_MODE //Drop primary weapon if ( !Q_stricmp( args[0], "DropPrimary" ) ) { Weapon_DropSlot( WEAPON_PRIMARY_SLOT ); return true; } #endif if ( !Q_stricmp( args[0], "emit" ) ) { CSingleUserRecipientFilter filter( this ); if ( args.ArgC() > 1 ) { EmitSound( filter, entindex(), args[ 1 ] ); } else { EmitSound( filter, entindex(), "Test.Sound" ); } return true; } return BaseClass::ClientCommand( args ); } //----------------------------------------------------------------------------- // Purpose: // Output : void CBasePlayer::PlayerUse //----------------------------------------------------------------------------- void CHL2_Player::PlayerUse ( void ) { // Was use pressed or released? if ( ! ((m_nButtons | m_afButtonPressed | m_afButtonReleased) & IN_USE) ) return; if ( m_afButtonPressed & IN_USE ) { // Currently using a latched entity? if ( ClearUseEntity() ) { return; } else { if ( m_afPhysicsFlags & PFLAG_DIROVERRIDE ) { m_afPhysicsFlags &= ~PFLAG_DIROVERRIDE; m_iTrain = TRAIN_NEW|TRAIN_OFF; return; } else { // Start controlling the train! CBaseEntity *pTrain = GetGroundEntity(); if ( pTrain && !(m_nButtons & IN_JUMP) && (GetFlags() & FL_ONGROUND) && (pTrain->ObjectCaps() & FCAP_DIRECTIONAL_USE) && pTrain->OnControls(this) ) { m_afPhysicsFlags |= PFLAG_DIROVERRIDE; m_iTrain = TrainSpeed(pTrain->m_flSpeed, ((CFuncTrackTrain*)pTrain)->GetMaxSpeed()); m_iTrain |= TRAIN_NEW; EmitSound( "HL2Player.TrainUse" ); return; } } } // Tracker 3926: We can't +USE something if we're climbing a ladder if ( GetMoveType() == MOVETYPE_LADDER ) { return; } } if( m_flTimeUseSuspended > gpGlobals->curtime ) { // Something has temporarily stopped us being able to USE things. // Obviously, this should be used very carefully.(sjb) return; } CBaseEntity *pUseEntity = FindUseEntity(); bool usedSomething = false; // Found an object if ( pUseEntity ) { //!!!UNDONE: traceline here to prevent +USEing buttons through walls int caps = pUseEntity->ObjectCaps(); variant_t emptyVariant; if ( m_afButtonPressed & IN_USE ) { // Robin: Don't play sounds for NPCs, because NPCs will allow respond with speech. if ( !pUseEntity->MyNPCPointer() ) { EmitSound( "HL2Player.Use" ); } } if ( ( (m_nButtons & IN_USE) && (caps & FCAP_CONTINUOUS_USE) ) || ( (m_afButtonPressed & IN_USE) && (caps & (FCAP_IMPULSE_USE|FCAP_ONOFF_USE)) ) ) { if ( caps & FCAP_CONTINUOUS_USE ) m_afPhysicsFlags |= PFLAG_USING; pUseEntity->AcceptInput( "Use", this, this, emptyVariant, USE_TOGGLE ); usedSomething = true; } // UNDONE: Send different USE codes for ON/OFF. Cache last ONOFF_USE object to send 'off' if you turn away else if ( (m_afButtonReleased & IN_USE) && (pUseEntity->ObjectCaps() & FCAP_ONOFF_USE) ) // BUGBUG This is an "off" use { pUseEntity->AcceptInput( "Use", this, this, emptyVariant, USE_TOGGLE ); usedSomething = true; } #if HL2_SINGLE_PRIMARY_WEAPON_MODE //Check for weapon pick-up if ( m_afButtonPressed & IN_USE ) { CBaseCombatWeapon *pWeapon = dynamic_cast<CBaseCombatWeapon *>(pUseEntity); if ( ( pWeapon != NULL ) && ( Weapon_CanSwitchTo( pWeapon ) ) ) { //Try to take ammo or swap the weapon if ( Weapon_OwnsThisType( pWeapon->GetClassname(), pWeapon->GetSubType() ) ) { Weapon_EquipAmmoOnly( pWeapon ); } else { Weapon_DropSlot( pWeapon->GetSlot() ); Weapon_Equip( pWeapon ); } usedSomething = true; } } #endif } else if ( m_afButtonPressed & IN_USE ) { // Signal that we want to play the deny sound, unless the user is +USEing on a ladder! // The sound is emitted in ItemPostFrame, since that occurs after GameMovement::ProcessMove which // lets the ladder code unset this flag. m_bPlayUseDenySound = true; } // Debounce the use key if ( usedSomething && pUseEntity ) { m_Local.m_nOldButtons |= IN_USE; m_afButtonPressed &= ~IN_USE; } } ConVar sv_show_crosshair_target( "sv_show_crosshair_target", "0" ); //----------------------------------------------------------------------------- // Purpose: Updates the posture of the weapon from lowered to ready //----------------------------------------------------------------------------- void CHL2_Player::UpdateWeaponPosture( void ) { CBaseCombatWeapon *pWeapon = dynamic_cast<CBaseCombatWeapon *>(GetActiveWeapon()); if ( pWeapon && m_LowerWeaponTimer.Expired() && pWeapon->CanLower() ) { m_LowerWeaponTimer.Set( .3 ); VPROF( "CHL2_Player::UpdateWeaponPosture-CheckLower" ); Vector vecAim = BaseClass::GetAutoaimVector( AUTOAIM_SCALE_DIRECT_ONLY ); const float CHECK_FRIENDLY_RANGE = 50 * 12; trace_t tr; UTIL_TraceLine( EyePosition(), EyePosition() + vecAim * CHECK_FRIENDLY_RANGE, MASK_SHOT, this, COLLISION_GROUP_NONE, &tr ); CBaseEntity *aimTarget = tr.m_pEnt; //If we're over something if ( aimTarget && !tr.DidHitWorld() ) { if ( !aimTarget->IsNPC() || aimTarget->MyNPCPointer()->GetState() != NPC_STATE_COMBAT ) { Disposition_t dis = IRelationType( aimTarget ); //Debug info for seeing what an object "cons" as if ( sv_show_crosshair_target.GetBool() ) { int text_offset = BaseClass::DrawDebugTextOverlays(); char tempstr[255]; switch ( dis ) { case D_LI: Q_snprintf( tempstr, sizeof(tempstr), "Disposition: Like" ); break; case D_HT: Q_snprintf( tempstr, sizeof(tempstr), "Disposition: Hate" ); break; case D_FR: Q_snprintf( tempstr, sizeof(tempstr), "Disposition: Fear" ); break; case D_NU: Q_snprintf( tempstr, sizeof(tempstr), "Disposition: Neutral" ); break; default: case D_ER: Q_snprintf( tempstr, sizeof(tempstr), "Disposition: !!!ERROR!!!" ); break; } //Draw the text NDebugOverlay::EntityText( aimTarget->entindex(), text_offset, tempstr, 0 ); } //See if we hates it if ( dis == D_LI ) { //We're over a friendly, drop our weapon if ( Weapon_Lower() == false ) { //FIXME: We couldn't lower our weapon! } return; } } } if ( Weapon_Ready() == false ) { //FIXME: We couldn't raise our weapon! } } if( g_pGameRules->GetAutoAimMode() != AUTOAIM_NONE ) { if( !pWeapon ) { // This tells the client to draw no crosshair m_HL2Local.m_bWeaponLowered = true; return; } else { if( !pWeapon->CanLower() && m_HL2Local.m_bWeaponLowered ) m_HL2Local.m_bWeaponLowered = false; } if( !m_AutoaimTimer.Expired() ) return; m_AutoaimTimer.Set( .1 ); VPROF( "hl2_x360_aiming" ); // Call the autoaim code to update the local player data, which allows the client to update. autoaim_params_t params; params.m_vecAutoAimPoint.Init(); params.m_vecAutoAimDir.Init(); params.m_fScale = AUTOAIM_SCALE_DEFAULT; params.m_fMaxDist = autoaim_max_dist.GetFloat(); GetAutoaimVector( params ); m_HL2Local.m_hAutoAimTarget.Set( params.m_hAutoAimEntity ); m_HL2Local.m_vecAutoAimPoint.Set( params.m_vecAutoAimPoint ); m_HL2Local.m_bAutoAimTarget = ( params.m_bAutoAimAssisting || params.m_bOnTargetNatural ); return; } else { // Make sure there's no residual autoaim target if the user changes the xbox_aiming convar on the fly. m_HL2Local.m_hAutoAimTarget.Set(NULL); } } //----------------------------------------------------------------------------- // Purpose: Lowers the weapon posture (for hovering over friendlies) // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CHL2_Player::Weapon_Lower( void ) { VPROF( "CHL2_Player::Weapon_Lower" ); // Already lowered? if ( m_HL2Local.m_bWeaponLowered ) return true; m_HL2Local.m_bWeaponLowered = true; CBaseCombatWeapon *pWeapon = dynamic_cast<CBaseCombatWeapon *>(GetActiveWeapon()); if ( pWeapon == NULL ) return false; return pWeapon->Lower(); } //----------------------------------------------------------------------------- // Purpose: Returns the weapon posture to normal // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CHL2_Player::Weapon_Ready( void ) { VPROF( "CHL2_Player::Weapon_Ready" ); // Already ready? if ( m_HL2Local.m_bWeaponLowered == false ) return true; m_HL2Local.m_bWeaponLowered = false; CBaseCombatWeapon *pWeapon = dynamic_cast<CBaseCombatWeapon *>(GetActiveWeapon()); if ( pWeapon == NULL ) return false; return pWeapon->Ready(); } //----------------------------------------------------------------------------- // Purpose: Returns whether or not we can switch to the given weapon. // Input : pWeapon - //----------------------------------------------------------------------------- bool CHL2_Player::Weapon_CanSwitchTo( CBaseCombatWeapon *pWeapon ) { CBasePlayer *pPlayer = (CBasePlayer *)this; #if !defined( CLIENT_DLL ) IServerVehicle *pVehicle = pPlayer->GetVehicle(); #else IClientVehicle *pVehicle = pPlayer->GetVehicle(); #endif if (pVehicle && !pPlayer->UsingStandardWeaponsInVehicle()) return false; ///// // SO2 - James // Allow players to switch to weapons that do not have any ammo /*if ( !pWeapon->HasAnyAmmo() && !GetAmmoCount( pWeapon->m_iPrimaryAmmoType ) ) return false;*/ ///// if ( !pWeapon->CanDeploy() ) return false; if ( GetActiveWeapon() ) { if ( PhysCannonGetHeldEntity( GetActiveWeapon() ) == pWeapon && Weapon_OwnsThisType( pWeapon->GetClassname(), pWeapon->GetSubType()) ) { return true; } if ( !GetActiveWeapon()->CanHolster() ) return false; } return true; } void CHL2_Player::PickupObject( CBaseEntity *pObject, bool bLimitMassAndSize ) { // can't pick up what you're standing on if ( GetGroundEntity() == pObject ) return; if ( bLimitMassAndSize == true ) { if ( CBasePlayer::CanPickupObject( pObject, 35, 128 ) == false ) return; } // Can't be picked up if NPCs are on me if ( pObject->HasNPCsOnIt() ) return; PlayerPickupObject( this, pObject ); } //----------------------------------------------------------------------------- // Purpose: // Output : CBaseEntity //----------------------------------------------------------------------------- bool CHL2_Player::IsHoldingEntity( CBaseEntity *pEnt ) { return PlayerPickupControllerIsHoldingEntity( m_hUseEntity, pEnt ); } float CHL2_Player::GetHeldObjectMass( IPhysicsObject *pHeldObject ) { float mass = PlayerPickupGetHeldObjectMass( m_hUseEntity, pHeldObject ); if ( mass == 0.0f ) { mass = PhysCannonGetHeldObjectMass( GetActiveWeapon(), pHeldObject ); } return mass; } CBaseEntity *CHL2_Player::GetHeldObject( void ) { return PhysCannonGetHeldEntity( GetActiveWeapon() ); } //----------------------------------------------------------------------------- // Purpose: Force the player to drop any physics objects he's carrying //----------------------------------------------------------------------------- void CHL2_Player::ForceDropOfCarriedPhysObjects( CBaseEntity *pOnlyIfHoldingThis ) { if ( PhysIsInCallback() ) { variant_t value; g_EventQueue.AddEvent( this, "ForceDropPhysObjects", value, 0.01f, pOnlyIfHoldingThis, this ); return; } #ifdef HL2_EPISODIC if ( hl2_episodic.GetBool() ) { CBaseEntity *pHeldEntity = PhysCannonGetHeldEntity( GetActiveWeapon() ); if( pHeldEntity && pHeldEntity->ClassMatches( "grenade_helicopter" ) ) { return; } } #endif // Drop any objects being handheld. ClearUseEntity(); // Then force the physcannon to drop anything it's holding, if it's our active weapon PhysCannonForceDrop( GetActiveWeapon(), NULL ); } void CHL2_Player::InputForceDropPhysObjects( inputdata_t &data ) { ForceDropOfCarriedPhysObjects( data.pActivator ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHL2_Player::UpdateClientData( void ) { if (m_DmgTake || m_DmgSave || m_bitsHUDDamage != m_bitsDamageType) { // Comes from inside me if not set Vector damageOrigin = GetLocalOrigin(); // send "damage" message // causes screen to flash, and pain compass to show direction of damage damageOrigin = m_DmgOrigin; // only send down damage type that have hud art int iShowHudDamage = g_pGameRules->Damage_GetShowOnHud(); int visibleDamageBits = m_bitsDamageType & iShowHudDamage; m_DmgTake = clamp( m_DmgTake, 0, 255 ); m_DmgSave = clamp( m_DmgSave, 0, 255 ); // If we're poisoned, but it wasn't this frame, don't send the indicator // Without this check, any damage that occured to the player while they were // recovering from a poison bite would register as poisonous as well and flash // the whole screen! -- jdw if ( visibleDamageBits & DMG_POISON ) { float flLastPoisonedDelta = gpGlobals->curtime - m_tbdPrev; if ( flLastPoisonedDelta > 0.1f ) { visibleDamageBits &= ~DMG_POISON; } } CSingleUserRecipientFilter user( this ); user.MakeReliable(); UserMessageBegin( user, "Damage" ); WRITE_BYTE( m_DmgSave ); WRITE_BYTE( m_DmgTake ); WRITE_LONG( visibleDamageBits ); WRITE_FLOAT( damageOrigin.x ); //BUG: Should be fixed point (to hud) not floats WRITE_FLOAT( damageOrigin.y ); //BUG: However, the HUD does _not_ implement bitfield messages (yet) WRITE_FLOAT( damageOrigin.z ); //BUG: We use WRITE_VEC3COORD for everything else MessageEnd(); m_DmgTake = 0; m_DmgSave = 0; m_bitsHUDDamage = m_bitsDamageType; // Clear off non-time-based damage indicators int iTimeBasedDamage = g_pGameRules->Damage_GetTimeBased(); m_bitsDamageType &= iTimeBasedDamage; } // Update Flashlight #ifdef HL2_EPISODIC if ( Flashlight_UseLegacyVersion() == false ) { if ( FlashlightIsOn() && sv_infinite_aux_power.GetBool() == false ) { m_HL2Local.m_flFlashBattery -= FLASH_DRAIN_TIME * gpGlobals->frametime; if ( m_HL2Local.m_flFlashBattery < 0.0f ) { FlashlightTurnOff(); m_HL2Local.m_flFlashBattery = 0.0f; } } else { m_HL2Local.m_flFlashBattery += FLASH_CHARGE_TIME * gpGlobals->frametime; if ( m_HL2Local.m_flFlashBattery > 100.0f ) { m_HL2Local.m_flFlashBattery = 100.0f; } } } else { m_HL2Local.m_flFlashBattery = -1.0f; } #endif // HL2_EPISODIC BaseClass::UpdateClientData(); } //--------------------------------------------------------- //--------------------------------------------------------- void CHL2_Player::OnRestore() { BaseClass::OnRestore(); m_pPlayerAISquad = g_AI_SquadManager.FindCreateSquad(AllocPooledString(PLAYER_SQUADNAME)); } //--------------------------------------------------------- //--------------------------------------------------------- Vector CHL2_Player::EyeDirection2D( void ) { Vector vecReturn = EyeDirection3D(); vecReturn.z = 0; vecReturn.AsVector2D().NormalizeInPlace(); return vecReturn; } //--------------------------------------------------------- //--------------------------------------------------------- Vector CHL2_Player::EyeDirection3D( void ) { Vector vecForward; // Return the vehicle angles if we request them if ( GetVehicle() != NULL ) { CacheVehicleView(); EyeVectors( &vecForward ); return vecForward; } AngleVectors( EyeAngles(), &vecForward ); return vecForward; } //--------------------------------------------------------- //--------------------------------------------------------- bool CHL2_Player::Weapon_Switch( CBaseCombatWeapon *pWeapon, int viewmodelindex ) { MDLCACHE_CRITICAL_SECTION(); // Recalculate proficiency! SetCurrentWeaponProficiency( CalcWeaponProficiency( pWeapon ) ); // Come out of suit zoom mode if ( IsZooming() ) { StopZooming(); } return BaseClass::Weapon_Switch( pWeapon, viewmodelindex ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- WeaponProficiency_t CHL2_Player::CalcWeaponProficiency( CBaseCombatWeapon *pWeapon ) { WeaponProficiency_t proficiency; proficiency = WEAPON_PROFICIENCY_PERFECT; if( weapon_showproficiency.GetBool() != 0 ) { Msg("Player switched to %s, proficiency is %s\n", pWeapon->GetClassname(), GetWeaponProficiencyName( proficiency ) ); } return proficiency; } //----------------------------------------------------------------------------- // Purpose: override how single player rays hit the player //----------------------------------------------------------------------------- bool LineCircleIntersection( const Vector2D &center, const float radius, const Vector2D &vLinePt, const Vector2D &vLineDir, float *fIntersection1, float *fIntersection2) { // Line = P + Vt // Sphere = r (assume we've translated to origin) // (P + Vt)^2 = r^2 // VVt^2 + 2PVt + (PP - r^2) // Solve as quadratic: (-b +/- sqrt(b^2 - 4ac)) / 2a // If (b^2 - 4ac) is < 0 there is no solution. // If (b^2 - 4ac) is = 0 there is one solution (a case this function doesn't support). // If (b^2 - 4ac) is > 0 there are two solutions. Vector2D P; float a, b, c, sqr, insideSqr; // Translate circle to origin. P[0] = vLinePt[0] - center[0]; P[1] = vLinePt[1] - center[1]; a = vLineDir.Dot(vLineDir); b = 2.0f * P.Dot(vLineDir); c = P.Dot(P) - (radius * radius); insideSqr = b*b - 4*a*c; if(insideSqr <= 0.000001f) return false; // Ok, two solutions. sqr = (float)FastSqrt(insideSqr); float denom = 1.0 / (2.0f * a); *fIntersection1 = (-b - sqr) * denom; *fIntersection2 = (-b + sqr) * denom; return true; } static void Collision_ClearTrace( const Vector &vecRayStart, const Vector &vecRayDelta, CBaseTrace *pTrace ) { pTrace->startpos = vecRayStart; pTrace->endpos = vecRayStart; pTrace->endpos += vecRayDelta; pTrace->startsolid = false; pTrace->allsolid = false; pTrace->fraction = 1.0f; pTrace->contents = 0; } bool IntersectRayWithAACylinder( const Ray_t &ray, const Vector &center, float radius, float height, CBaseTrace *pTrace ) { Assert( ray.m_IsRay ); Collision_ClearTrace( ray.m_Start, ray.m_Delta, pTrace ); // First intersect the ray with the top + bottom planes float halfHeight = height * 0.5; // Handle parallel case Vector vStart = ray.m_Start - center; Vector vEnd = vStart + ray.m_Delta; float flEnterFrac, flLeaveFrac; if (FloatMakePositive(ray.m_Delta.z) < 1e-8) { if ( (vStart.z < -halfHeight) || (vStart.z > halfHeight) ) { return false; // no hit } flEnterFrac = 0.0f; flLeaveFrac = 1.0f; } else { // Clip the ray to the top and bottom of box flEnterFrac = IntersectRayWithAAPlane( vStart, vEnd, 2, 1, halfHeight); flLeaveFrac = IntersectRayWithAAPlane( vStart, vEnd, 2, 1, -halfHeight); if ( flLeaveFrac < flEnterFrac ) { float temp = flLeaveFrac; flLeaveFrac = flEnterFrac; flEnterFrac = temp; } if ( flLeaveFrac < 0 || flEnterFrac > 1) { return false; } } // Intersect with circle float flCircleEnterFrac, flCircleLeaveFrac; if ( !LineCircleIntersection( vec3_origin.AsVector2D(), radius, vStart.AsVector2D(), ray.m_Delta.AsVector2D(), &flCircleEnterFrac, &flCircleLeaveFrac ) ) { return false; // no hit } Assert( flCircleEnterFrac <= flCircleLeaveFrac ); if ( flCircleLeaveFrac < 0 || flCircleEnterFrac > 1) { return false; } if ( flEnterFrac < flCircleEnterFrac ) flEnterFrac = flCircleEnterFrac; if ( flLeaveFrac > flCircleLeaveFrac ) flLeaveFrac = flCircleLeaveFrac; if ( flLeaveFrac < flEnterFrac ) return false; VectorMA( ray.m_Start, flEnterFrac , ray.m_Delta, pTrace->endpos ); pTrace->fraction = flEnterFrac; pTrace->contents = CONTENTS_SOLID; // Calculate the point on our center line where we're nearest the intersection point Vector collisionCenter; CalcClosestPointOnLineSegment( pTrace->endpos, center + Vector( 0, 0, halfHeight ), center - Vector( 0, 0, halfHeight ), collisionCenter ); // Our normal is the direction from that center point to the intersection point pTrace->plane.normal = pTrace->endpos - collisionCenter; VectorNormalize( pTrace->plane.normal ); return true; } bool CHL2_Player::TestHitboxes( const Ray_t &ray, unsigned int fContentsMask, trace_t& tr ) { if( g_pGameRules->IsMultiplayer() ) { return BaseClass::TestHitboxes( ray, fContentsMask, tr ); } else { Assert( ray.m_IsRay ); Vector mins, maxs; mins = WorldAlignMins(); maxs = WorldAlignMaxs(); if ( IntersectRayWithAACylinder( ray, WorldSpaceCenter(), maxs.x * PLAYER_HULL_REDUCTION, maxs.z - mins.z, &tr ) ) { tr.hitbox = 0; CStudioHdr *pStudioHdr = GetModelPtr( ); if (!pStudioHdr) return false; mstudiohitboxset_t *set = pStudioHdr->pHitboxSet( m_nHitboxSet ); if ( !set || !set->numhitboxes ) return false; mstudiobbox_t *pbox = set->pHitbox( tr.hitbox ); mstudiobone_t *pBone = pStudioHdr->pBone(pbox->bone); tr.surface.name = "**studio**"; tr.surface.flags = SURF_HITBOX; tr.surface.surfaceProps = physprops->GetSurfaceIndex( pBone->pszSurfaceProp() ); } return true; } } //--------------------------------------------------------- // Show the player's scaled down bbox that we use for // bullet impacts. //--------------------------------------------------------- void CHL2_Player::DrawDebugGeometryOverlays(void) { BaseClass::DrawDebugGeometryOverlays(); if (m_debugOverlays & OVERLAY_BBOX_BIT) { Vector mins, maxs; mins = WorldAlignMins(); maxs = WorldAlignMaxs(); mins.x *= PLAYER_HULL_REDUCTION; mins.y *= PLAYER_HULL_REDUCTION; maxs.x *= PLAYER_HULL_REDUCTION; maxs.y *= PLAYER_HULL_REDUCTION; NDebugOverlay::Box( GetAbsOrigin(), mins, maxs, 255, 0, 0, 100, 0 ); } } //----------------------------------------------------------------------------- // Purpose: Helper to remove from ladder //----------------------------------------------------------------------------- void CHL2_Player::ExitLadder() { if ( MOVETYPE_LADDER != GetMoveType() ) return; SetMoveType( MOVETYPE_WALK ); SetMoveCollide( MOVECOLLIDE_DEFAULT ); // Remove from ladder m_HL2Local.m_hLadder.Set( NULL ); } surfacedata_t *CHL2_Player::GetLadderSurface( const Vector &origin ) { extern const char *FuncLadder_GetSurfaceprops(CBaseEntity *pLadderEntity); CBaseEntity *pLadder = m_HL2Local.m_hLadder.Get(); if ( pLadder ) { const char *pSurfaceprops = FuncLadder_GetSurfaceprops(pLadder); // get ladder material from func_ladder return physprops->GetSurfaceData( physprops->GetSurfaceIndex( pSurfaceprops ) ); } return BaseClass::GetLadderSurface(origin); } //----------------------------------------------------------------------------- // Purpose: Queues up a use deny sound, played in ItemPostFrame. //----------------------------------------------------------------------------- void CHL2_Player::PlayUseDenySound() { m_bPlayUseDenySound = true; } void CHL2_Player::ItemPostFrame() { BaseClass::ItemPostFrame(); if ( m_bPlayUseDenySound ) { m_bPlayUseDenySound = false; EmitSound( "HL2Player.UseDeny" ); } } void CHL2_Player::StartWaterDeathSounds( void ) { CPASAttenuationFilter filter( this ); if ( m_sndLeeches == NULL ) { m_sndLeeches = (CSoundEnvelopeController::GetController()).SoundCreate( filter, entindex(), CHAN_STATIC, "coast.leech_bites_loop" , ATTN_NORM ); } if ( m_sndLeeches ) { (CSoundEnvelopeController::GetController()).Play( m_sndLeeches, 1.0f, 100 ); } if ( m_sndWaterSplashes == NULL ) { m_sndWaterSplashes = (CSoundEnvelopeController::GetController()).SoundCreate( filter, entindex(), CHAN_STATIC, "coast.leech_water_churn_loop" , ATTN_NORM ); } if ( m_sndWaterSplashes ) { (CSoundEnvelopeController::GetController()).Play( m_sndWaterSplashes, 1.0f, 100 ); } } void CHL2_Player::StopWaterDeathSounds( void ) { if ( m_sndLeeches ) { (CSoundEnvelopeController::GetController()).SoundFadeOut( m_sndLeeches, 0.5f, true ); m_sndLeeches = NULL; } if ( m_sndWaterSplashes ) { (CSoundEnvelopeController::GetController()).SoundFadeOut( m_sndWaterSplashes, 0.5f, true ); m_sndWaterSplashes = NULL; } } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CHL2_Player::MissedAR2AltFire() { if( GetPlayerProxy() != NULL ) { GetPlayerProxy()->m_PlayerMissedAR2AltFire.FireOutput( this, this ); } } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CHL2_Player::DisplayLadderHudHint() { #if !defined( CLIENT_DLL ) if( gpGlobals->curtime > m_flTimeNextLadderHint ) { m_flTimeNextLadderHint = gpGlobals->curtime + 60.0f; CFmtStr hint; hint.sprintf( "#Valve_Hint_Ladder" ); UTIL_HudHintText( this, hint.Access() ); } #endif//CLIENT_DLL } //----------------------------------------------------------------------------- // Shuts down sounds //----------------------------------------------------------------------------- void CHL2_Player::StopLoopingSounds( void ) { if ( m_sndLeeches != NULL ) { (CSoundEnvelopeController::GetController()).SoundDestroy( m_sndLeeches ); m_sndLeeches = NULL; } if ( m_sndWaterSplashes != NULL ) { (CSoundEnvelopeController::GetController()).SoundDestroy( m_sndWaterSplashes ); m_sndWaterSplashes = NULL; } BaseClass::StopLoopingSounds(); } //----------------------------------------------------------------------------- void CHL2_Player::ModifyOrAppendPlayerCriteria( AI_CriteriaSet& set ) { BaseClass::ModifyOrAppendPlayerCriteria( set ); if ( GlobalEntity_GetIndex( "gordon_precriminal" ) == -1 ) { set.AppendCriteria( "gordon_precriminal", "0" ); } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- const impactdamagetable_t &CHL2_Player::GetPhysicsImpactDamageTable() { if ( m_bUseCappedPhysicsDamageTable ) return gCappedPlayerImpactDamageTable; return BaseClass::GetPhysicsImpactDamageTable(); } //----------------------------------------------------------------------------- // Purpose: Makes a splash when the player transitions between water states //----------------------------------------------------------------------------- void CHL2_Player::Splash( void ) { CEffectData data; data.m_fFlags = 0; data.m_vOrigin = GetAbsOrigin(); data.m_vNormal = Vector(0,0,1); data.m_vAngles = QAngle( 0, 0, 0 ); if ( GetWaterType() & CONTENTS_SLIME ) { data.m_fFlags |= FX_WATER_IN_SLIME; } float flSpeed = GetAbsVelocity().Length(); if ( flSpeed < 300 ) { data.m_flScale = random->RandomFloat( 10, 12 ); DispatchEffect( "waterripple", data ); } else { data.m_flScale = random->RandomFloat( 6, 8 ); DispatchEffect( "watersplash", data ); } } CLogicPlayerProxy *CHL2_Player::GetPlayerProxy( void ) { CLogicPlayerProxy *pProxy = dynamic_cast< CLogicPlayerProxy* > ( m_hPlayerProxy.Get() ); if ( pProxy == NULL ) { pProxy = (CLogicPlayerProxy*)gEntList.FindEntityByClassname(NULL, "logic_playerproxy" ); if ( pProxy == NULL ) return NULL; pProxy->m_hPlayer = this; m_hPlayerProxy = pProxy; } return pProxy; } void CHL2_Player::FirePlayerProxyOutput( const char *pszOutputName, variant_t variant, CBaseEntity *pActivator, CBaseEntity *pCaller ) { if ( GetPlayerProxy() == NULL ) return; GetPlayerProxy()->FireNamedOutput( pszOutputName, variant, pActivator, pCaller ); } LINK_ENTITY_TO_CLASS( logic_playerproxy, CLogicPlayerProxy); BEGIN_DATADESC( CLogicPlayerProxy ) DEFINE_OUTPUT( m_OnFlashlightOn, "OnFlashlightOn" ), DEFINE_OUTPUT( m_OnFlashlightOff, "OnFlashlightOff" ), DEFINE_OUTPUT( m_RequestedPlayerHealth, "PlayerHealth" ), DEFINE_OUTPUT( m_PlayerHasAmmo, "PlayerHasAmmo" ), DEFINE_OUTPUT( m_PlayerHasNoAmmo, "PlayerHasNoAmmo" ), DEFINE_OUTPUT( m_PlayerDied, "PlayerDied" ), DEFINE_OUTPUT( m_PlayerMissedAR2AltFire, "PlayerMissedAR2AltFire" ), DEFINE_INPUTFUNC( FIELD_VOID, "RequestPlayerHealth", InputRequestPlayerHealth ), DEFINE_INPUTFUNC( FIELD_VOID, "SetFlashlightSlowDrain", InputSetFlashlightSlowDrain ), DEFINE_INPUTFUNC( FIELD_VOID, "SetFlashlightNormalDrain", InputSetFlashlightNormalDrain ), DEFINE_INPUTFUNC( FIELD_INTEGER, "SetPlayerHealth", InputSetPlayerHealth ), DEFINE_INPUTFUNC( FIELD_VOID, "RequestAmmoState", InputRequestAmmoState ), DEFINE_INPUTFUNC( FIELD_VOID, "LowerWeapon", InputLowerWeapon ), DEFINE_INPUTFUNC( FIELD_VOID, "EnableCappedPhysicsDamage", InputEnableCappedPhysicsDamage ), DEFINE_INPUTFUNC( FIELD_VOID, "DisableCappedPhysicsDamage", InputDisableCappedPhysicsDamage ), DEFINE_INPUTFUNC( FIELD_STRING, "SetLocatorTargetEntity", InputSetLocatorTargetEntity ), DEFINE_FIELD( m_hPlayer, FIELD_EHANDLE ), END_DATADESC() void CLogicPlayerProxy::Activate( void ) { BaseClass::Activate(); if ( m_hPlayer == NULL ) { m_hPlayer = AI_GetSinglePlayer(); } } bool CLogicPlayerProxy::PassesDamageFilter( const CTakeDamageInfo &info ) { if (m_hDamageFilter) { CBaseFilter *pFilter = (CBaseFilter *)(m_hDamageFilter.Get()); return pFilter->PassesDamageFilter(info); } return true; } void CLogicPlayerProxy::InputSetPlayerHealth( inputdata_t &inputdata ) { if ( m_hPlayer == NULL ) return; m_hPlayer->SetHealth( inputdata.value.Int() ); } void CLogicPlayerProxy::InputRequestPlayerHealth( inputdata_t &inputdata ) { if ( m_hPlayer == NULL ) return; m_RequestedPlayerHealth.Set( m_hPlayer->GetHealth(), inputdata.pActivator, inputdata.pCaller ); } void CLogicPlayerProxy::InputSetFlashlightSlowDrain( inputdata_t &inputdata ) { if( m_hPlayer == NULL ) return; CHL2_Player *pPlayer = dynamic_cast<CHL2_Player*>(m_hPlayer.Get()); if( pPlayer ) pPlayer->SetFlashlightPowerDrainScale( hl2_darkness_flashlight_factor.GetFloat() ); } void CLogicPlayerProxy::InputSetFlashlightNormalDrain( inputdata_t &inputdata ) { if( m_hPlayer == NULL ) return; CHL2_Player *pPlayer = dynamic_cast<CHL2_Player*>(m_hPlayer.Get()); if( pPlayer ) pPlayer->SetFlashlightPowerDrainScale( 1.0f ); } void CLogicPlayerProxy::InputRequestAmmoState( inputdata_t &inputdata ) { if( m_hPlayer == NULL ) return; CHL2_Player *pPlayer = dynamic_cast<CHL2_Player*>(m_hPlayer.Get()); for ( int i = 0 ; i < pPlayer->WeaponCount(); ++i ) { CBaseCombatWeapon* pCheck = pPlayer->GetWeapon( i ); if ( pCheck ) { if ( pCheck->HasAnyAmmo() && (pCheck->UsesPrimaryAmmo() || pCheck->UsesSecondaryAmmo())) { m_PlayerHasAmmo.FireOutput( this, this, 0 ); return; } } } m_PlayerHasNoAmmo.FireOutput( this, this, 0 ); } void CLogicPlayerProxy::InputLowerWeapon( inputdata_t &inputdata ) { if( m_hPlayer == NULL ) return; CHL2_Player *pPlayer = dynamic_cast<CHL2_Player*>(m_hPlayer.Get()); pPlayer->Weapon_Lower(); } void CLogicPlayerProxy::InputEnableCappedPhysicsDamage( inputdata_t &inputdata ) { if( m_hPlayer == NULL ) return; CHL2_Player *pPlayer = dynamic_cast<CHL2_Player*>(m_hPlayer.Get()); pPlayer->EnableCappedPhysicsDamage(); } void CLogicPlayerProxy::InputDisableCappedPhysicsDamage( inputdata_t &inputdata ) { if( m_hPlayer == NULL ) return; CHL2_Player *pPlayer = dynamic_cast<CHL2_Player*>(m_hPlayer.Get()); pPlayer->DisableCappedPhysicsDamage(); } void CLogicPlayerProxy::InputSetLocatorTargetEntity( inputdata_t &inputdata ) { if( m_hPlayer == NULL ) return; CBaseEntity *pTarget = NULL; // assume no target string_t iszTarget = MAKE_STRING( inputdata.value.String() ); if( iszTarget != NULL_STRING ) { pTarget = gEntList.FindEntityByName( NULL, iszTarget ); } CHL2_Player *pPlayer = dynamic_cast<CHL2_Player*>(m_hPlayer.Get()); pPlayer->SetLocatorTargetEntity(pTarget); }
[ "MadKowa@ec9d42d2-91e1-33f0-ec5d-f2a905d45d61" ]
[ [ [ 1, 4012 ] ] ]
dc0fdca5f6a3e4ab7e89db445ef57bba4bab701f
df238aa31eb8c74e2c208188109813272472beec
/BCGInclude/MenuHash.h
39fa3b303f29c300a0b36f3b6627911a865060af
[]
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
1,424
h
//******************************************************************************* // 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. //******************************************************************************* // MenuHash.h: interface for the CBCGPMenuHash class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_MENUHASH_H__6DC611B4_D93A_11D1_A64E_00A0C93A70EC__INCLUDED_) #define AFX_MENUHASH_H__6DC611B4_D93A_11D1_A64E_00A0C93A70EC__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 #ifndef __AFXTEMPL_H__ #include "afxtempl.h" #endif class CBCGPToolBar; class CBCGPMenuHash { public: CBCGPMenuHash(); virtual ~CBCGPMenuHash(); BOOL SaveMenuBar (HMENU hMenu, CBCGPToolBar* pBar); BOOL LoadMenuBar (HMENU hMenu, CBCGPToolBar* pBar); BOOL RemoveMenu (HMENU hMenu); void CleanUp (); BOOL IsActive () const { return m_bIsActive; } protected: CMap<HMENU, HMENU&, HANDLE, HANDLE&> m_StoredMenues; BOOL m_bIsActive; }; extern CBCGPMenuHash g_menuHash; #endif // !defined(AFX_MENUHASH_H__6DC611B4_D93A_11D1_A64E_00A0C93A70EC__INCLUDED_)
[ "myme5261314@ec588229-7da7-b333-41f6-0e1ebc3afda5" ]
[ [ [ 1, 54 ] ] ]
a37b60dbc706ca304a302392b4d360cd980ac515
2e613efc5a3b330f440a2d90bb758dafbdf8f6b1
/src/rect.cpp
1e2e8cb79aa9c6fb72964a03eedb82f0bbdf6cb9
[]
no_license
zhaoweisonake/qfplot
4a76d446aebfddce4bf8a51c709a815f35ca76d2
e30d851261f3987a42319ff98def23771adb24bd
refs/heads/master
2021-01-18T12:31:07.049737
2010-05-17T09:29:11
2010-05-17T09:29:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
239
cpp
#include "rect.h" void Rect::expand( const QPoint& point ) { setLeft ( qMin(point.x(), left() ) ); setRight ( qMax(point.x(), right() ) ); setTop ( qMax(point.y(), top() ) ); setBottom( qMin(point.y(), bottom()) ); };
[ "akhokhlov@localhost" ]
[ [ [ 1, 9 ] ] ]
482ce62470b7853a708e2e8deddc94028224baed
fd518ed0226c6a044d5e168ab50a0e4a37f8efa9
/iAuthor/Author/BoardDlg.h
7bd1891dca8c96eded39b4bfc71f7686810254d5
[]
no_license
shilinxu/iprojects
e2e2394df9882afaacfb9852332f83cbef6a8c93
79bc8e45596577948c45cf2afcff331bc71ab026
refs/heads/master
2020-05-17T19:15:43.197685
2010-04-02T15:58:11
2010-04-02T15:58:11
41,959,151
0
0
null
null
null
null
UTF-8
C++
false
false
1,801
h
#if !defined(AFX_BOARDDLG_H__B5F27942_9798_4462_9F60_2484EE9DF209__INCLUDED_) #define AFX_BOARDDLG_H__B5F27942_9798_4462_9F60_2484EE9DF209__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // BoardDlg.h : header file // ///////////////////////////////////////////////////////////////////////////// // CBoardDlg dialog class CBoardDlg : public CDialog { // Construction public: void SetCursor(HCURSOR hCursor); void SetBoardImage(CString strPath); void SetBoardImageByDesktop(); void SetBoardStyle(int nBoardStyle); CBoardDlg(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CBoardDlg) enum { IDD = IDD_BOARDDLG }; // NOTE: the ClassWizard will add data members here //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CBoardDlg) public: virtual BOOL PreTranslateMessage(MSG* pMsg); protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CBoardDlg) virtual BOOL OnInitDialog(); afx_msg void OnPaint(); afx_msg BOOL OnEraseBkgnd(CDC* pDC); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnLButtonUp(UINT nFlags, CPoint point); afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message); //}}AFX_MSG DECLARE_MESSAGE_MAP() private: Bitmap* m_pBGBitmap; CString m_strImagePath; HCURSOR m_hCursor; }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_BOARDDLG_H__B5F27942_9798_4462_9F60_2484EE9DF209__INCLUDED_)
[ [ [ 1, 63 ] ] ]
05ad09f06bb448f63bc625d2321b4f3187c016ff
d54d8b1bbc9575f3c96853e0c67f17c1ad7ab546
/hlsdk-2.3-p3/singleplayer/game_shared/vgui_scrollbar2.cpp
0a60f661aa932576300fece1bfc39c77535eb284
[]
no_license
joropito/amxxgroup
637ee71e250ffd6a7e628f77893caef4c4b1af0a
f948042ee63ebac6ad0332f8a77393322157fa8f
refs/heads/master
2021-01-10T09:21:31.449489
2010-04-11T21:34:27
2010-04-11T21:34:27
47,087,485
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
6,560
cpp
//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============ // // Purpose: // // $NoKeywords: $ //============================================================================= #include "VGUI_ScrollBar2.h" #include "VGUI_Slider2.h" #include "vgui_loadtga.h" #include<VGUI_IntChangeSignal.h> #include<VGUI_Button.h> #include<VGUI_ActionSignal.h> #include<VGUI_LineBorder.h> using namespace vgui; namespace { class FooDefaultScrollBarIntChangeSignal : public IntChangeSignal { public: FooDefaultScrollBarIntChangeSignal(ScrollBar2* scrollBar) { _scrollBar=scrollBar; } virtual void intChanged(int value,Panel* panel) { _scrollBar->fireIntChangeSignal(); } protected: ScrollBar2* _scrollBar; }; class FooDefaultButtonSignal : public ActionSignal { public: ScrollBar2* _scrollBar; int _buttonIndex; public: FooDefaultButtonSignal(ScrollBar2* scrollBar,int buttonIndex) { _scrollBar=scrollBar; _buttonIndex=buttonIndex; } public: virtual void actionPerformed(Panel* panel) { _scrollBar->doButtonPressed(_buttonIndex); } }; } //----------------------------------------------------------------------------- // Purpose: Default scrollbar button // Draws in new scoreboard style //----------------------------------------------------------------------------- class ScrollBarButton : public Button { private: LineBorder m_Border; public: ScrollBarButton(const char *filename, int x, int y, int wide, int tall) : m_Border(Color(60, 60, 60, 0)), Button("", x, y, wide, tall) { Image *image = vgui_LoadTGA(filename); if (image) { image->setColor(Color(140, 140, 140, 0)); setImage(image); } setBorder(&m_Border); } virtual void paintBackground() { int wide,tall; getPaintSize(wide,tall); // fill the background drawSetColor(0, 0, 0, 0); drawFilledRect(0, 0, wide, tall); } }; //----------------------------------------------------------------------------- // Purpose: Constructor // Input : x - // y - // wide - // tall - // vertical - //----------------------------------------------------------------------------- ScrollBar2::ScrollBar2(int x,int y,int wide,int tall,bool vertical) : Panel(x,y,wide,tall) { _slider=null; _button[0]=null; _button[1]=null; if(vertical) { setSlider(new Slider2(0,wide-1,wide,(tall-(wide*2))+2,true)); setButton(new ScrollBarButton("gfx/vgui/arrowup.tga",0,0,wide,wide),0); setButton(new ScrollBarButton("gfx/vgui/arrowdown.tga",0,tall-wide,wide,wide),1); } else { // untested code setSlider(new Slider2(tall,0,wide-(tall*2),tall,false)); setButton(new ScrollBarButton("gfx/vgui/320_arrowlt.tga",0,0,tall+1,tall+1),0); setButton(new ScrollBarButton("gfx/vgui/320_arrowrt.tga",wide-tall,0,tall+1,tall+1),1); } setPaintBorderEnabled(true); setPaintBackgroundEnabled(true); setPaintEnabled(true); setButtonPressedScrollValue(15); validate(); } void ScrollBar2::setSize(int wide,int tall) { Panel::setSize(wide,tall); if(_slider==null) { return; } if(_button[0]==null) { return; } if(_button[1]==null) { return; } getPaintSize(wide,tall); if(_slider->isVertical()) { _slider->setBounds(0,wide,wide,tall-(wide*2)); //_slider->setBounds(0,0,wide,tall); _button[0]->setBounds(0,0,wide,wide); _button[1]->setBounds(0,tall-wide,wide,wide); } else { _slider->setBounds(tall,0,wide-(tall*2),tall); //_slider->setBounds(0,0,wide,tall); _button[0]->setBounds(0,0,tall,tall); _button[1]->setBounds((wide-tall),0,tall,tall); } } void ScrollBar2::performLayout() { } void ScrollBar2::setValue(int value) { _slider->setValue(value); } int ScrollBar2::getValue() { return _slider->getValue(); } void ScrollBar2::addIntChangeSignal(IntChangeSignal* s) { _intChangeSignalDar.putElement(s); _slider->addIntChangeSignal(new FooDefaultScrollBarIntChangeSignal(this)); } void ScrollBar2::setRange(int min,int max) { _slider->setRange(min,max); } void ScrollBar2::fireIntChangeSignal() { for(int i=0;i<_intChangeSignalDar.getCount();i++) { _intChangeSignalDar[i]->intChanged(_slider->getValue(),this); } } bool ScrollBar2::isVertical() { return _slider->isVertical(); } bool ScrollBar2::hasFullRange() { return _slider->hasFullRange(); } //LEAK: new and old slider will leak void ScrollBar2::setButton(Button* button,int index) { if(_button[index]!=null) { removeChild(_button[index]); } _button[index]=button; addChild(_button[index]); _button[index]->addActionSignal(new FooDefaultButtonSignal(this,index)); validate(); //_button[index]->setVisible(false); } Button* ScrollBar2::getButton(int index) { return _button[index]; } //LEAK: new and old slider will leak void ScrollBar2::setSlider(Slider2 *slider) { if(_slider!=null) { removeChild(_slider); } _slider=slider; addChild(_slider); _slider->addIntChangeSignal(new FooDefaultScrollBarIntChangeSignal(this)); validate(); } Slider2 *ScrollBar2::getSlider() { return _slider; } void ScrollBar2::doButtonPressed(int buttonIndex) { if(buttonIndex==0) { _slider->setValue(_slider->getValue()-_buttonPressedScrollValue); } else { _slider->setValue(_slider->getValue()+_buttonPressedScrollValue); } } void ScrollBar2::setButtonPressedScrollValue(int value) { _buttonPressedScrollValue=value; } void ScrollBar2::setRangeWindow(int rangeWindow) { _slider->setRangeWindow(rangeWindow); } void ScrollBar2::setRangeWindowEnabled(bool state) { _slider->setRangeWindowEnabled(state); } void ScrollBar2::validate() { if(_slider!=null) { int buttonOffset=0; for(int i=0;i<2;i++) { if(_button[i]!=null) { if(_button[i]->isVisible()) { if(_slider->isVertical()) { buttonOffset+=_button[i]->getTall(); } else { buttonOffset+=_button[i]->getWide(); } } } } _slider->setButtonOffset(buttonOffset); } int wide,tall; getSize(wide,tall); setSize(wide,tall); }
[ "joropito@23c7d628-c96c-11de-a380-73d83ba7c083" ]
[ [ [ 1, 310 ] ] ]
7ad86d95ec2a66e21025c56473ce5d73c977b6e3
b22c254d7670522ec2caa61c998f8741b1da9388
/dependencies/OsgAl/examples/osgal/osgal.cpp
14ec4c200991f42ba338685f0c64fa372b318a9a
[]
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
IBM852
C++
false
false
15,546
cpp
/* -*-c++-*- $Id: osgal.cpp */ /** * OsgAL - OpenSceneGraph Audio Library * Copyright (C) 2004 VRlab, Umeň University * This application is a copy of the osganimation demonstration, with added sound support to * demonstrate the osgAL toolkit. * * 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. */ #include <osgAL/SoundNode> #include <osgAL/SoundRoot> #include <osgAL/SoundManager> #include <osgAL/SoundState> #include <openalpp/FileStream> #include <osg/DeleteHandler> #include <osg/Notify> #include <osg/MatrixTransform> #include <osg/PositionAttitudeTransform> #include <osg/Geometry> #include <osg/Geode> #include <osgUtil/Optimizer> #include <osgDB/Registry> #include <osgDB/ReadFile> #include <osgViewer/ViewerEventHandlers> #include <osgViewer/Viewer> #include "osgAL/Version" using namespace osgAL; osg::ref_ptr<osgAL::SoundNode> createSound(const std::string& file); class KeyboardHandler: public osgGA::GUIEventHandler { public: KeyboardHandler(osgAL::SoundState *state): m_sound_state(state) {} bool handle(const osgGA::GUIEventAdapter &ea, osgGA::GUIActionAdapter &) { if (ea.getEventType() == osgGA::GUIEventAdapter::KEYDOWN) { if (ea.getKey() == 32) { // Now push the soundstate to the queue so it will be played. // Set any of the parameters that will be activated when it // is head of the queue when the sound manager processes the soundstates later on. // Get the current position of the listener float x,y,z; osgAL::SoundManager::instance()->getListener()->getPosition(x,y,z); // Place this sound state at the position of the listener m_sound_state->setPosition(osg::Vec3(x,y,z)); m_sound_state->setPlay(true); // It will play! m_sound_state->setPitch(1); // Now push the event to the sound manager so it can play it whenever this // event reaches the top of the queue. A higher priority will move it to the top // faster! int priority = 10; osgAL::SoundManager::instance()->pushSoundEvent(m_sound_state.get(), priority); return true; } else if (ea.getKey() == 'm') { // Toggle looping ambient music // Try to find a soundstate named "music" SoundState *musicSoundState = osgAL::SoundManager::instance()->findSoundState("music"); if (!musicSoundState) { // If not found, create a new one musicSoundState = new SoundState("music"); // ALlocate a hw source so we can loop it musicSoundState->allocateSource( 10 ); // Create a new filestream that streams samples from a ogg-file. openalpp::FileStream *musicStream = new openalpp::FileStream("44100_2chan.ogg"); // Associate the stream with the sound state musicSoundState->setStream( musicStream ); // Make it an ambient (heard everywhere) sound musicSoundState->setAmbient( true ); // Loop the sound forever musicSoundState->setLooping( true ); // Start playing the music! //musicSoundState->setPlay( true ); // Add the soundstate to the sound manager so we can find it later on. SoundManager::instance()->addSoundState( musicSoundState ); } musicSoundState->setPlay( !musicSoundState->isPlaying() ); return true; } } return false; } private: osg::ref_ptr<osgAL::SoundState> m_sound_state; }; osg::AnimationPath* createAnimationPath(const osg::Vec3& center,float radius,double looptime) { // set up the animation path osg::AnimationPath* animationPath = new osg::AnimationPath; animationPath->setLoopMode(osg::AnimationPath::LOOP); int numSamples = 40; float yaw = 0.0f; float yaw_delta = 2.0f*osg::PI/((float)numSamples-1.0f); float roll = osg::inDegrees(30.0f); double time=0.0f; double time_delta = looptime/(double)numSamples; for(int i=0;i<numSamples;++i) { osg::Vec3 position(center+osg::Vec3(sinf(yaw)*radius,cosf(yaw)*radius,0.0f)); osg::Quat rotation(osg::Quat(roll,osg::Vec3(0.0,1.0,0.0))*osg::Quat(-(yaw+osg::inDegrees(90.0f)),osg::Vec3(0.0,0.0,1.0))); animationPath->insert(time,osg::AnimationPath::ControlPoint(position,rotation)); yaw += yaw_delta; time += time_delta; } return animationPath; } osg::Node* createBase(const osg::Vec3& center,float radius) { int numTilesX = 10; int numTilesY = 10; float width = 2*radius; float height = 2*radius; osg::Vec3 v000(center - osg::Vec3(width*0.5f,height*0.5f,0.0f)); osg::Vec3 dx(osg::Vec3(width/((float)numTilesX),0.0,0.0f)); osg::Vec3 dy(osg::Vec3(0.0f,height/((float)numTilesY),0.0f)); // fill in vertices for grid, note numTilesX+1 * numTilesY+1... osg::Vec3Array* coords = new osg::Vec3Array; int iy; for(iy=0;iy<=numTilesY;++iy) { for(int ix=0;ix<=numTilesX;++ix) { coords->push_back(v000+dx*(float)ix+dy*(float)iy); } } //Just two colours - black and white. osg::Vec4Array* colors = new osg::Vec4Array; colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f)); // white colors->push_back(osg::Vec4(0.0f,0.0f,0.0f,1.0f)); // black int numColors=colors->size(); int numIndicesPerRow=numTilesX+1; osg::UByteArray* coordIndices = new osg::UByteArray; // assumes we are using less than 256 points... osg::UByteArray* colorIndices = new osg::UByteArray; for(iy=0;iy<numTilesY;++iy) { for(int ix=0;ix<numTilesX;++ix) { // four vertices per quad. coordIndices->push_back(ix +(iy+1)*numIndicesPerRow); coordIndices->push_back(ix +iy*numIndicesPerRow); coordIndices->push_back((ix+1)+iy*numIndicesPerRow); coordIndices->push_back((ix+1)+(iy+1)*numIndicesPerRow); // one color per quad colorIndices->push_back((ix+iy)%numColors); } } // set up a single normal osg::Vec3Array* normals = new osg::Vec3Array; normals->push_back(osg::Vec3(0.0f,0.0f,1.0f)); osg::Geometry* geom = new osg::Geometry; geom->setVertexArray(coords); geom->setVertexIndices(coordIndices); geom->setColorArray(colors); geom->setColorIndices(colorIndices); geom->setColorBinding(osg::Geometry::BIND_PER_PRIMITIVE); geom->setNormalArray(normals); geom->setNormalBinding(osg::Geometry::BIND_OVERALL); geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,coordIndices->size())); osg::Geode* geode = new osg::Geode; geode->addDrawable(geom); return geode; } osg::Node* createMovingModel(const osg::Vec3& center, float radius) { float animationLength = 10.0f; osg::AnimationPath* animationPath = createAnimationPath(center,radius,animationLength); osg::Group* model = new osg::Group; osg::Node* glider = osgDB::readNodeFile("glider.osg"); if (glider) { const osg::BoundingSphere& bs = glider->getBound(); osg::BoundingSphere::value_type size = radius/bs.radius()*0.3f; osg::MatrixTransform* positioned = new osg::MatrixTransform; positioned->setDataVariance(osg::Object::STATIC); positioned->setMatrix(osg::Matrix::translate(-bs.center())* osg::Matrix::scale(size,size,size)* osg::Matrix::rotate(osg::inDegrees(-90.0f),0.0f,0.0f,1.0f)); positioned->addChild(glider); // Create a sound node osg::ref_ptr<osgAL::SoundNode> sound_node = createSound("bee.wav"); // Add the sound node positioned->addChild(sound_node.get()); osg::PositionAttitudeTransform* xform = new osg::PositionAttitudeTransform; xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0,1.0)); xform->addChild(positioned); model->addChild(xform); } osg::Node* cessna = osgDB::readNodeFile("cessna.osg"); if (cessna) { const osg::BoundingSphere& bs = cessna->getBound(); osg::BoundingSphere::value_type size = radius/bs.radius()*0.3f; osg::MatrixTransform* positioned = new osg::MatrixTransform; positioned->setDataVariance(osg::Object::STATIC); positioned->setMatrix(osg::Matrix::translate(-bs.center())* osg::Matrix::scale(size,size,size)* osg::Matrix::rotate(osg::inDegrees(180.0f),0.0f,0.0f,1.0f)); positioned->addChild(cessna); osg::MatrixTransform* xform = new osg::MatrixTransform; xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0f,2.0)); xform->addChild(positioned); model->addChild(xform); } return model; } osg::ref_ptr<osgAL::SoundNode> createSound(const std::string& file) { // Create a sample, load a .wav file. openalpp::Sample *sample = new openalpp::Sample(file.c_str()); // Create a named sound state. osg::ref_ptr<osgAL::SoundState> sound_state = new osgAL::SoundState("glider"); // Let the soundstate use the sample we just created sound_state->setSample(sample); // Set its gain (volume) to 0.9 sound_state->setGain(0.9f); // Set its pitch to 1 (normal speed) sound_state->setPitch(1); // Make it play sound_state->setPlay(true); // The sound should loop over and over again sound_state->setLooping(true); // Allocate a hardware soundsource to this soundstate (priority 10) // sound_state->allocateSource(10, false); // At 40 the gain will be half of full! sound_state->setReferenceDistance(70); sound_state->setRolloffFactor(4); sound_state->apply(); // Add the soundstate to the sound manager, so we can find it later on if we want to osgAL::SoundManager::instance()->addSoundState(sound_state.get()); // Create a sound node and attach the soundstate to it. osg::ref_ptr<osgAL::SoundNode> sound = new osgAL::SoundNode; sound->setSoundState(sound_state.get()); return sound; } osg::Node* createModel() { osg::Vec3 center(0.0f,0.0f,0.0f); float radius = 100.0f; osg::Group* root = new osg::Group; root->addChild(createMovingModel(center,radius*0.8f)); root->addChild(createBase(center-osg::Vec3(0.0f,0.0f,radius*0.5),radius)); return root; } int main( int argc, char **argv ) { osg::notify(osg::WARN) << "\n\n" << osgAL::getLibraryName() << " demo" << std::endl; osg::notify(osg::WARN) << "Version: " << osgAL::getVersion() << "\n\n" << std::endl; osg::notify(osg::WARN) << "\nPress space to play a sound once...\n" << std::endl; try { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // set up the usage document, in case we need to print out how to use this program. arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" demonstrates the use of the OsgAL toolkit for spatial sound."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ..."); arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information"); // initialize the viewer. osgViewer::Viewer viewer(arguments); // add the window size toggle handler viewer.addEventHandler(new osgViewer::WindowSizeHandler); // add the stats handler viewer.addEventHandler(new osgViewer::StatsHandler); // add the help handler viewer.addEventHandler(new osgViewer::HelpHandler(arguments.getApplicationUsage())); // get details on keyboard and mouse bindings used by the viewer. viewer.getUsage(*arguments.getApplicationUsage()); // if user request help write it out to cout. if (arguments.read("-h") || arguments.read("--help")) { arguments.getApplicationUsage()->write(std::cout); return 1; } // any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); arguments.getApplicationUsage()->addKeyboardMouseBinding("RETURN", "Play a sound"); // report any errors if they have occured when parsing the program aguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } osgAL::SoundManager::instance()->init(16); osgAL::SoundManager::instance()->getEnvironment()->setDistanceModel(openalpp::InverseDistance); osgAL::SoundManager::instance()->getEnvironment()->setDopplerFactor(1); // load the nodes from the commandline arguments. osg::Node* model = createModel(); if (!model) { return 1; } // tilt the scene so the default eye position is looking down on the model. osg::MatrixTransform* rootnode = new osg::MatrixTransform; rootnode->setMatrix(osg::Matrix::rotate(osg::inDegrees(30.0f),1.0f,0.0f,0.0f)); rootnode->addChild(model); // Create a sample, load a .wav file. openalpp::Sample *sample = new openalpp::Sample("high-e.wav"); osg::ref_ptr<osgAL::SoundState> sound_state = new osgAL::SoundState("glider"); sound_state->setSample(sample); sound_state->setGain(0.7f); sound_state->setReferenceDistance(10); sound_state->setPlay(false); sound_state->setLooping(false); // Add the soundstate to the sound manager, so we can find it later on if we want to osgAL::SoundManager::instance()->addSoundState(sound_state.get()); viewer.getEventHandlers().push_front(new KeyboardHandler(sound_state.get())); // Create ONE (only one, otherwise the transformation of the listener and update for SoundManager will be // called several times, which is not catastrophic, but unnecessary) // SoundRoot that will make sure the listener is updated and // to keep the internal state of the SoundManager updated // This could also be done manually, this is just a handy way of doing it. osg::ref_ptr<osgAL::SoundRoot> sound_root = new osgAL::SoundRoot; // The position in the scenegraph of this node is not important. // Just as long as the cull traversal should be called after any changes to the SoundManager are made. rootnode->addChild(sound_root.get()); // run optimization over the scene graph after the soundnodes are added // otherwise in this case the transformation added earlier would dissapear. osgUtil::Optimizer optimzer; optimzer.optimize(rootnode); // set the scene to render viewer.setSceneData(rootnode); // create the windows and run the threads. viewer.realize(); osgViewer::Viewer::Windows windows; viewer.getWindows(windows); windows[0]->setWindowRectangle( 10, 10, 1024, 768 ); windows[0]->setWindowDecoration( true ); viewer.run(); } catch (std::exception& e) { osg::notify(osg::WARN) << "Caught: " << e.what() << std::endl; } // Very important to call before end of main! if (osg::Referenced::getDeleteHandler()) { osg::Referenced::getDeleteHandler()->setNumFramesToRetainObjects(0); osg::Referenced::getDeleteHandler()->flushAll(); } osgAL::SoundManager::instance()->shutdown(); return 0; }
[ "vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13" ]
[ [ [ 1, 476 ] ] ]
9f3f26b56145bfa1c95856bca10dbcfd1eb6cc75
32d720136c6138829e0fa0c9d2aed580f3b86e60
/MyTabCtrl.h
1f43173b74454aee2cadaad2fb8f9d826fe6c0cc
[]
no_license
ElTopo/ddnct
ce9b13bd19b7d15c23c23739107a8c08a3f8cd6f
94f027b9c6c4937be30ca686d8fc47d740837edb
refs/heads/master
2016-09-05T20:27:39.377828
2010-04-03T00:18:54
2010-04-03T00:18:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
620
h
#pragma once // CMyTabCtrl class CMyTabCtrl : public CTabCtrl { DECLARE_DYNAMIC(CMyTabCtrl) public: CMyTabCtrl(); virtual ~CMyTabCtrl(); //Array to hold the list of dialog boxes/tab pages for CTabCtrl int m_nPageCount; int m_DialogID[2]; //CDialog Array Variable to hold the dialogs CDialog *m_Dialog[2]; //Function to Create the dialog boxes during startup void InitDialogs(); //Function to activate the tab dialog boxes void ActivateTabDialogs(); protected: DECLARE_MESSAGE_MAP() public: afx_msg void OnTcnSelchangeTab(NMHDR *pNMHDR, LRESULT *pResult); };
[ [ [ 1, 33 ] ] ]
dee8bdde1d43cbd1d7a84664ee31adca46c77ccf
69b7796d276703936b8ae0fe82cb931d704ed432
/infrastructure/src/ThreadSpecificData.cpp
42d8d4da9b72bbf58eec5a6ed8cb4be7505433d2
[]
no_license
owensgroup/dcgn
6038bfa1815baea6e89c97c957c6f3a4e6e7545d
d5cadbeacb4223775e8ccc87dbae346724bee214
refs/heads/master
2021-05-29T14:45:48.439038
2011-03-21T22:55:41
2011-03-21T22:55:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
509
cpp
#include <dcgn/ThreadSpecificData.h> namespace dcgn { ThreadSpecificData::ThreadSpecificData() { pthread_key_create(&key, 0); } ThreadSpecificData::~ThreadSpecificData() { pthread_key_delete(key); } void * ThreadSpecificData::getValue() { return pthread_getspecific(key); } void ThreadSpecificData::setValue(void * const p) { pthread_setspecific(key, p); } pthread_key_t & ThreadSpecificData::getNativeResource() { return key; } }
[ "[email protected]@0566f383-6757-26d6-4a9c-121651c89c67" ]
[ [ [ 1, 26 ] ] ]
588e43edcf9c4455161159ab6024e8bc97a37db0
27687dfacdfa03f7a1f509e36e848fa1767f47b3
/XLoader/cryptopp_wrapper.h
ec879e2e00e745ac452d8aab675d0f40368b9d2f
[]
no_license
Gbps/gmod
7f11a79e439c2c63233ad9dcc2e3c32e6c8ceb95
125f7c94e5732abc4dac441181bc3bad51c7aa23
refs/heads/master
2022-06-20T18:36:45.742134
2011-08-04T03:08:58
2011-08-04T03:08:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,640
h
#ifndef SPACECRYPTOWRAPPER_H #define SPACECRYPTOWRAPPER_H /*Some Wrappers For Crypto++*/ /*============================================================================================================ SPACE CRYPTO A Simple Crypto++ Wrapper ============================================================================================================== by Space Soft (Stefano Guerrini) Release Date: 26/06/10 This library, helps you to develop your applications, in a very easy way, with Crypto++. It permits a developer with a minimal understanding of C++ to rapid use a crypting library! The SpaceCrypto is divided in Two Class: The Crypt one and the Hash one. The first one, allow you to perform rapid encrypt\decrypt operations with the most common Methods (AES, Twofish, DES,...) using the c++ string (std::string). CRYPTO CLASS USAGE: After declaring an istance of the Crypto Class, you must set the plain Text, the Key, and optionally the IV. The function parameters are self explainatory. Remember that you must specify the incoming string format type (HEX or normal), or it will automatically turn into normal input. You can also specify the output type. (setInputMode & set OutputMode) When you're ready to encrypt (or decrypt) your string, you need to call Encrypt() (or decrypt()) method, this will return you the processed string. Error Handling: getStatus() function, will return a boolean value, rapresenting the current status of obj (true = error; false=no errors) getErrorMsg() function, will return a string, indicating the current error msg You can only perform one encrypt\decrypt function at time. To perform another crypt operation with the same Crypto object, you need to call reset() function (For security reason too..) This is a security reason too, but it has another explaination... When you call for the first time the Encrypt function (or decrypt one), the obj proceed to encrypt all data. So if you call the Encrypt Function again (to retrieve another time the coded string), he doesn't call again crypto++ crypting function, but will return the already encoded string. SECURITY ADVISE: For this reason, we Strongly reccomend you to call reset() function, immediatly after the conversion, if you don't need to call other functions again, because the plain string and the plain key, will remain in RAM, until you delete the object! HASH CLASS USAGE: The hash function, work similar to the crypto class, with some exception. - Remember that hashes functions are one-way crypt..so you can't retrieve the string back... - Hash Class offers the addStr function that allow you to add some text to the plain string */ #include "modes.h" #include "hex.h" #include "filters.h" #include "aes.h" #include "sha.h" #include "blowfish.h" #include "twofish.h" #include "des.h" #include "serpent.h" #include "base64.h" #include "osrng.h" #include "md5.h" //Function to convert unsigned char to string of length 2 void Char2Hex(const unsigned char ch, char* szHex) { unsigned char byte[2]; byte[0] = ch/16; byte[1] = ch%16; for(int i=0; i<2; i++) { if(byte[i] >= 0 && byte[i] <= 9) szHex[i] = '0' + byte[i]; else szHex[i] = 'A' + byte[i] - 10; } szHex[2] = 0; } //Function to convert string of length 2 to unsigned char void Hex2Char(const char* szHex, unsigned char& rch) { rch = 0; for(int i=0; i<2; i++) { if(*(szHex + i) >='0' && *(szHex + i) <= '9') rch = (rch << 4) + (*(szHex + i) - '0'); else if(*(szHex + i) >='A' && *(szHex + i) <= 'F') rch = (rch << 4) + (*(szHex + i) - 'A' + 10); else break; } } //Function to convert string of unsigned chars to string of chars void CharStr2HexStr(const unsigned char* pucCharStr, char* pszHexStr, int iSize) { int i; char szHex[3]; pszHexStr[0] = 0; for(i=0; i<iSize; i++) { Char2Hex(pucCharStr[i], szHex); strcat(pszHexStr, szHex); } } //Function to convert string of chars to string of unsigned chars void HexStr2CharStr(const char* pszHexStr, unsigned char* pucCharStr, int iSize) { int i; unsigned char ch; for(i=0; i<iSize; i++) { Hex2Char(pszHexStr+2*i, ch); pucCharStr[i] = ch; } } namespace SpaceCrypto { enum OUT_TYPE //OUT&IN TYPE (HEX OR NORMAL ONE) { HEX = 0, NORMAL = 1, }; template <typename T> class Crypt { public: Crypt() //Default Constructor { reset(); //Start with resetting our data variables } /*Encrypt Function*/ std::string Encrypt() { if(_error == true) return errormsg; if(_key.size() == 0 || _plain.size() == 0) { _error = true; //errormsg = "You need to set key and\or plain text"; } if(enc == false) //We haven't already crypted our string..so we need to encrypt it! { if(in_mode==HEX) //Before normalizing data we need to convert HEX strings into Normal one... { char* normstr; normstr = new char [_plain.size()+1]; HexStr2CharStr(_plain.c_str(),(unsigned char*)normstr,_plain.size()); _plain = normstr; delete [] normstr; } this->initializeIV(); //Initializing IV to a padding string (Only '0' chars) try{ _enc.SetKeyWithIV((byte*)_key.c_str(),_key.length(),(byte*)_iv.c_str(),_iv.length()); //Set KEY & IV CryptoPP::StringSource( _plain, true,new CryptoPP::StreamTransformationFilter( _enc, new CryptoPP::StringSink( _encrypted ))); //Crypting and converting to string... if(out_mode == HEX) //If user request to convert string to HEX... { char * hexstr; //Output String hexstr = new char[_encrypted.size()*2+1]; CharStr2HexStr((unsigned char*)_encrypted.c_str(),hexstr,_encrypted.size()); //Converting string... _encrypted = hexstr; //Prepariamo il nostro oggetto di ritorno delete[]hexstr; } } catch (CryptoPP::Exception& e) { //std::string errText = "Bad encrypt"; errormsg = e.GetWhat(); _error = true; return errormsg; } } enc=true; //Successful! return _encrypted; } std::string Decrypt() { if(_error == true) return errormsg; if(_key.size() == 0 || _encrypted.size() == 0) { _error = true; //errormsg = "You need to set key and\or plain text"; return errormsg; } if(dec == false && enc == false) //Process only if we've got an 'empty' SpaceCrypto OBJ { if(in_mode==HEX) { char* normstr; normstr = new char [_encrypted.size()+1]; HexStr2CharStr(_encrypted.c_str(),(unsigned char*)normstr,_encrypted.size()); _encrypted = normstr; delete [] normstr; } this->initializeIV(); try{ _dec.SetKeyWithIV((byte*)_key.c_str(),_key.length(),(byte*)_iv.c_str()); CryptoPP::StringSource( _encrypted, true,new CryptoPP::StreamTransformationFilter( _dec, new CryptoPP::StringSink( _plain ))); if(out_mode == HEX) { char * hexstr; //Dichiariamo la stringa di output esadecimale hexstr = new char[_encrypted.size()*2+5]; //Allochiamo lo spazio del doppio (data la grandezza esadecimale), prendendo qualche carattere in piu per sicurezza CharStr2HexStr((unsigned char*)_plain.c_str(),hexstr,_plain.size()); //Convertiamo da Stringa a stringa esadecimale _plain = hexstr; //Prepariamo il nostro oggetto di ritorno delete[]hexstr; } } catch (CryptoPP::Exception& e) { //std::string errText = "Bad Decrypt"; errormsg = e.GetWhat(); _error = true; return errormsg; } } return _plain; } void setKey(std::string key) { if(key.size() == 0 || key.size()%T::KEYLENGTH_MULTIPLE != 0) //Non valid Key Length... { _error = true; //errormsg="No valid Key Length"; } if(_error == false) //No error existing... _key = key; } void setIV(std::string iv) { if(iv.size() == 0 || iv.size()%T::IV_LENGTH != 0 )//Non valid IV Lenght { _error = true; //errormsg="No valid IV Length"; } if(_error == false) { ivsetted=true; _iv = iv; } } void setPlainString(std::string plainstring) { if(plainstring.size() == 0 ) //Empty string?? { _error = true; //errormsg= "No valid Plain String Length"; } if(_error == false) _plain = plainstring; } void setEncString(std::string encryptedstring) { if(encryptedstring.size() == 0 ) { _error = true; //errormsg= "No valid Encrypted String Length"; } if(_error == false) _encrypted = encryptedstring; } inline void setOutputMode(OUT_TYPE type){out_mode = type;} inline void setInputMode(OUT_TYPE type){in_mode = type;} void reset() { out_mode=HEX; in_mode=NORMAL; enc=false; dec=false; _error = false; ivsetted=false; errormsg = ""; _encrypted=""; _key=""; _plain=""; _iv=""; } inline bool getStatus(){ return _error;} inline std::string getErrorMsg(){return errormsg;} private: void initializeIV() { if(ivsetted == false) { for(int i=0;i<T::BLOCKSIZE;i++) //Default IV _iv.push_back('0'); } } std::string _key; std::string _plain; std::string _encrypted; std::string _iv; std::string errormsg; typename CryptoPP::CBC_Mode<T>::Encryption _enc; typename CryptoPP::CBC_Mode<T>::Decryption _dec; bool _error; bool dec; bool enc; bool ivsetted; OUT_TYPE out_mode; OUT_TYPE in_mode; }; typedef Crypt<CryptoPP::AES> CryptAES; //!Typedef for the AES Encryption\Decryption typedef Crypt<CryptoPP::Blowfish> CryptBlowFish; //!Typedef for BlowFish Encryption\Decryption typedef Crypt<CryptoPP::Twofish> CryptTwoFish; //!Typedef for BlowFish Encryption\Decryption typedef Crypt<CryptoPP::DES> CryptDES; //!Typedef for DE Encryption\Decryption typedef Crypt<CryptoPP::DES_EDE3> CryptTripleDES; //!Typedef for 3-DES Encryption\Decryption typedef Crypt<CryptoPP::Serpent> CryptSerpent; //!Typedef for SerpentEncryption\Decryption template <typename T> class Hash { public: Hash() { reset(); } void reset() { processed = false; _error = false; _plain.empty(); _plain = ""; _encrypted.empty(); hashobj.Restart(); out_mode = HEX; in_mode = NORMAL; } std::string Encrypt() { if(processed == true) return _encrypted; if(_plain.size() == 0) { _error = true; //errormsg = "You need to set plain text"; return errormsg; } if(in_mode==HEX) //Before normalizing data we need to convert HEX strings into Normal one... { char* normstr; normstr = new char [_plain.size()+1]; HexStr2CharStr(_plain.c_str(),(unsigned char*)normstr,_plain.size()); _plain = normstr; delete [] normstr; } if(_error == false) { try { byte digest[ T::DIGESTSIZE ]; hashobj.Final(digest); if(out_mode == HEX) { char * hexout = new char[sizeof(digest)*2+1]; CharStr2HexStr((unsigned char*)digest,hexout,sizeof(digest)); _encrypted = hexout; delete[]hexout; } else { _encrypted = (char*)digest; } if(_encrypted != "") { processed=true; return _encrypted; } } catch (CryptoPP::Exception& e) { //std::string errText = "Bad Hash encrypt"; errormsg = e.GetWhat(); _error = true; return errText; } } _error = true; return ""; } inline void setOutputMode(OUT_TYPE type){out_mode = type;} inline void setInputMode(OUT_TYPE type){in_mode = type;} void setPlain(std::string plain) { if(plain.size() == 0) { _error = true; //errormsg = "No plain text specified"; } if(_plain = plain && _error != true) _error = false; else //errormsg = "Error during plain text assign"; } void addStr(std::string string) { if(_error != true) if(string.size() != 0) { _plain += string; hashobj.Update((byte*)string.c_str(),string.size()); } else _error = false; } inline bool getStatus(){ return _error;} inline std::string getErrorMsg(){return errormsg;} private: std::string _plain; std::string _encrypted; std::string errormsg; bool _error; bool processed; OUT_TYPE out_mode; OUT_TYPE in_mode; T hashobj; }; typedef Hash<CryptoPP::SHA1> HashSHA1; typedef Hash<CryptoPP::MD5> HashMD5; } #endif
[ "cowmonkey111@ea4bc6c7-d654-2506-312e-aa9fc04bc719" ]
[ [ [ 1, 446 ] ] ]
1a597863f74aa33411a21e97db5230875db23c5d
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/framework/XMLAttDef.cpp
533a48828a27e1f929042899622394b44ba848ac
[ "Apache-2.0" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
6,781
cpp
/* * Copyright 1999-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * $Id: XMLAttDef.cpp,v 1.9 2004/09/08 13:55:58 peiyongz Exp $ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/framework/XMLAttDef.hpp> #include <xercesc/util/ArrayIndexOutOfBoundsException.hpp> #include <xercesc/util/XMLUni.hpp> #include <xercesc/util/OutOfMemoryException.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // Local const data // // gAttTypeStrings // A list of strings which are used to map attribute type numbers to // attribute type names. // // gDefAttTypesStrings // A list of strings which are used to map default attribute type // numbers to default attribute type names. // --------------------------------------------------------------------------- const XMLCh* const gAttTypeStrings[XMLAttDef::AttTypes_Count] = { XMLUni::fgCDATAString , XMLUni::fgIDString , XMLUni::fgIDRefString , XMLUni::fgIDRefsString , XMLUni::fgEntityString , XMLUni::fgEntitiesString , XMLUni::fgNmTokenString , XMLUni::fgNmTokensString , XMLUni::fgNotationString , XMLUni::fgEnumerationString , XMLUni::fgCDATAString , XMLUni::fgCDATAString , XMLUni::fgCDATAString , XMLUni::fgCDATAString }; const XMLCh* const gDefAttTypeStrings[XMLAttDef::DefAttTypes_Count] = { XMLUni::fgDefaultString , XMLUni::fgFixedString , XMLUni::fgRequiredString , XMLUni::fgImpliedString , XMLUni::fgImpliedString , XMLUni::fgImpliedString , XMLUni::fgImpliedString , XMLUni::fgImpliedString , XMLUni::fgImpliedString }; // --------------------------------------------------------------------------- // XMLAttDef: Public, static data members // --------------------------------------------------------------------------- const unsigned int XMLAttDef::fgInvalidAttrId = 0xFFFFFFFE; // --------------------------------------------------------------------------- // XMLAttDef: Public, static methods // --------------------------------------------------------------------------- const XMLCh* XMLAttDef::getAttTypeString(const XMLAttDef::AttTypes attrType , MemoryManager* const manager) { // Check for an invalid attribute type and return a null if ((attrType < AttTypes_Min) || (attrType > AttTypes_Max)) ThrowXMLwithMemMgr(ArrayIndexOutOfBoundsException, XMLExcepts::AttDef_BadAttType, manager); return gAttTypeStrings[attrType]; } const XMLCh* XMLAttDef::getDefAttTypeString(const XMLAttDef::DefAttTypes attrType , MemoryManager* const manager) { // Check for an invalid attribute type and return a null if ((attrType < DefAttTypes_Min) || (attrType > DefAttTypes_Max)) ThrowXMLwithMemMgr(ArrayIndexOutOfBoundsException, XMLExcepts::AttDef_BadDefAttType, manager); return gDefAttTypeStrings[attrType]; } // --------------------------------------------------------------------------- // XMLAttDef: Destructor // --------------------------------------------------------------------------- XMLAttDef::~XMLAttDef() { cleanUp(); } // --------------------------------------------------------------------------- // XMLAttDef: Hidden constructors // --------------------------------------------------------------------------- XMLAttDef::XMLAttDef( const XMLAttDef::AttTypes type , const XMLAttDef::DefAttTypes defType , MemoryManager* const manager) : fDefaultType(defType) , fType(type) , fCreateReason(XMLAttDef::NoReason) , fProvided(false) , fExternalAttribute(false) , fId(XMLAttDef::fgInvalidAttrId) , fValue(0) , fEnumeration(0) , fMemoryManager(manager) { } XMLAttDef::XMLAttDef( const XMLCh* const attrValue , const XMLAttDef::AttTypes type , const XMLAttDef::DefAttTypes defType , const XMLCh* const enumValues , MemoryManager* const manager) : fDefaultType(defType) , fType(type) , fCreateReason(XMLAttDef::NoReason) , fProvided(false) , fExternalAttribute(false) , fId(XMLAttDef::fgInvalidAttrId) , fValue(0) , fEnumeration(0) , fMemoryManager(manager) { try { fValue = XMLString::replicate(attrValue, fMemoryManager); fEnumeration = XMLString::replicate(enumValues, fMemoryManager); } catch(const OutOfMemoryException&) { throw; } catch(...) { cleanUp(); } } // --------------------------------------------------------------------------- // XMLAttDef: Private helper methods // --------------------------------------------------------------------------- void XMLAttDef::cleanUp() { if (fEnumeration) fMemoryManager->deallocate(fEnumeration); if (fValue) fMemoryManager->deallocate(fValue); } /*** * Support for Serialization/De-serialization ***/ IMPL_XSERIALIZABLE_NOCREATE(XMLAttDef) void XMLAttDef::serialize(XSerializeEngine& serEng) { if (serEng.isStoring()) { serEng<<(int)fDefaultType; serEng<<(int)fType; serEng<<(int)fCreateReason; serEng<<fProvided; serEng<<fExternalAttribute; serEng<<fId; serEng.writeString(fValue); serEng.writeString(fEnumeration); } else { int i; serEng>>i; fDefaultType = (DefAttTypes) i; serEng>>i; fType = (AttTypes)i; serEng>>i; fCreateReason = (CreateReasons)i; serEng>>fProvided; serEng>>fExternalAttribute; serEng>>fId; serEng.readString(fValue); serEng.readString(fEnumeration); } } XERCES_CPP_NAMESPACE_END
[ [ [ 1, 220 ] ] ]
920d06e91b44513bfa469742a4e885ad8f67f522
99d3989754840d95b316a36759097646916a15ea
/trunk/2011_09_07_to_baoxin_gpd/ferrylibs/src/ferry/cv_geometry/RANSAC_FMC.cpp
c1700f8900170b19566bad0edc157a91860afacf
[]
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
27
cpp
#include ".\ransac_fmc.h"
[ "ferryzhou@b6adba56-547e-11de-b413-c5e99dc0a8e2" ]
[ [ [ 1, 1 ] ] ]