blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
146
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
7
| license_type
stringclasses 2
values | repo_name
stringlengths 6
79
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 4
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.07k
426M
⌀ | star_events_count
int64 0
27
| fork_events_count
int64 0
12
| gha_license_id
stringclasses 3
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 6
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 20
6.28M
| extension
stringclasses 20
values | content
stringlengths 20
6.28M
| authors
listlengths 1
16
| author_lines
listlengths 1
16
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5c6dd4c4b84aa15c09ee62c15b19d228a2da1d0b | ed2a1c83681d8ed2d08f8a74707536791e5cd057 | /HGooey.DLL/HGooey Files/HGuiExport.cpp | fad2de0889b71c8d8d88d233dc9a5f3e51959e4c | [
"Apache-2.0"
]
| permissive | MartinMReed/XenDLL | e33d5c27187e58fd4401b2dbcaae3ebab8279bc2 | 51a05c3cec7b2142f704f2ea131202a72de843ec | refs/heads/master | 2021-01-10T19:10:40.492482 | 2007-10-31T16:38:00 | 2007-10-31T16:38:00 | 12,150,175 | 13 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 17,116 | cpp | #define HGOOEY_EXPORTS
#include "HGIncDef_Private.h"
#define keyCount 96
char* DIK_KeyText[keyCount] = { "1", "2", "3", "4", "5", "6", "7", "8", "9",
"0", "A", "B", "C", "D", "E", "F", "G", "H", "I",
"J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z", "F1", "F2", "F3", "F4",
"F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
"ESCAPE", "TAB", "MINUS", "EQUALS", "BACK", "ENTER",
"LBRACKET", "RBRACKET", "LCONTROL", "RCONTROL",
"LSHIFT", "RSHIFT", "LALT", "RALT", "SEMICOLON",
"APOSTROPHE", "BACKSLASH", "COMMA", "PERIOD",
"SPACE", "CAPITAL", "NUMLOCK", "SCROLL", "LEFT",
"RIGHT", "UP", "DOWN", "PAUSE", "HOME", "INSERT",
"DELETE", "NUMPAD1", "NUMPAD2", "NUMPAD3", "NUMPAD4",
"NUMPAD5", "NUMPAD6", "NUMPAD7", "NUMPAD8", "NUMPAD9",
"NUMPAD0", "NUMPADENTER", "NUMPADEQUALS", "DECIMAL",
"ADD", "SUBTRACT", "MULTIPLY", "DIVIDE"};
BYTE DIK_Key[keyCount] = { DIK_1, DIK_2, DIK_3, DIK_4, DIK_5, DIK_6, DIK_7, DIK_8,
DIK_9, DIK_0, DIK_A, DIK_B, DIK_C, DIK_D, DIK_E,
DIK_F, DIK_G, DIK_H, DIK_I, DIK_J, DIK_K, DIK_L, DIK_M,
DIK_N, DIK_O, DIK_P, DIK_Q, DIK_R, DIK_S, DIK_T, DIK_U,
DIK_V, DIK_W, DIK_X, DIK_Y, DIK_Z, DIK_F1, DIK_F2,
DIK_F3, DIK_F4, DIK_F5, DIK_F6, DIK_F7, DIK_F8, DIK_F9,
DIK_F10, DIK_F11, DIK_F12, DIK_ESCAPE, DIK_TAB,
DIK_MINUS, DIK_EQUALS, DIK_BACK, DIK_RETURN,
DIK_LBRACKET, DIK_RBRACKET, DIK_LCONTROL,
DIK_RCONTROL, DIK_LSHIFT, DIK_RSHIFT, DIK_LALT,
DIK_RALT, DIK_SEMICOLON, DIK_APOSTROPHE,
DIK_BACKSLASH, DIK_COMMA, DIK_PERIOD, DIK_SPACE,
DIK_CAPITAL, DIK_NUMLOCK, DIK_SCROLL, DIK_LEFT,
DIK_RIGHT, DIK_UP, DIK_DOWN, DIK_PAUSE, DIK_HOME,
DIK_INSERT, DIK_DELETE, DIK_NUMPAD1, DIK_NUMPAD2,
DIK_NUMPAD3, DIK_NUMPAD4, DIK_NUMPAD5, DIK_NUMPAD6,
DIK_NUMPAD7, DIK_NUMPAD8, DIK_NUMPAD9, DIK_NUMPAD0,
DIK_NUMPADENTER, DIK_NUMPADEQUALS, DIK_DECIMAL, DIK_ADD,
DIK_SUBTRACT, DIK_MULTIPLY, DIK_DIVIDE};
char* DIK_Name[keyCount] = { "DIK_1", "DIK_2", "DIK_3", "DIK_4", "DIK_5", "DIK_6", "DIK_7", "DIK_8",
"DIK_9", "DIK_0", "DIK_A", "DIK_B", "DIK_C", "DIK_D", "DIK_E",
"DIK_F", "DIK_G", "DIK_H", "DIK_I", "DIK_J", "DIK_K", "DIK_L", "DIK_M",
"DIK_N", "DIK_O", "DIK_P", "DIK_Q", "DIK_R", "DIK_S", "DIK_T", "DIK_U",
"DIK_V", "DIK_W", "DIK_X", "DIK_Y", "DIK_Z", "DIK_F1", "DIK_F2",
"DIK_F3", "DIK_F4", "DIK_F5", "DIK_F6", "DIK_F7", "DIK_F8", "DIK_F9",
"DIK_F10", "DIK_F11", "DIK_F12", "DIK_ESCAPE", "DIK_TAB",
"DIK_MINUS", "DIK_EQUALS", "DIK_BACK", "DIK_RETURN",
"DIK_LBRACKET", "DIK_RBRACKET", "DIK_LCONTROL",
"DIK_RCONTROL", "DIK_LSHIFT", "DIK_RSHIFT", "DIK_LALT",
"DIK_RALT", "DIK_SEMICOLON", "DIK_APOSTROPHE",
"DIK_BACKSLASH", "DIK_COMMA", "DIK_PERIOD", "DIK_SPACE",
"DIK_CAPITAL", "DIK_NUMLOCK", "DIK_SCROLL", "DIK_LEFT",
"DIK_RIGHT", "DIK_UP", "DIK_DOWN", "DIK_PAUSE", "DIK_HOME",
"DIK_INSERT", "DIK_DELETE", "DIK_NUMPAD1", "DIK_NUMPAD2",
"DIK_NUMPAD3", "DIK_NUMPAD4", "DIK_NUMPAD5", "DIK_NUMPAD6",
"DIK_NUMPAD7", "DIK_NUMPAD8", "DIK_NUMPAD9", "DIK_NUMPAD0",
"DIK_NUMPADENTER", "DIK_NUMPADEQUALS", "DIK_DECIMAL", "DIK_ADD",
"DIK_SUBTRACT", "DIK_MULTIPLY", "DIK_DIVIDE"};
//-------------------------------------------------------
// class HGooey (private)
//-------------------------------------------------------
bool __stdcall _SetMenuOptions(int _position, float _iwidth, float _iheight)
{
return g_HGooey->SetMenuOptions(_position, _iwidth, _iheight);
}
bool __stdcall _ToggleMenu()
{
return g_HGooey->ToggleMenu();
}
bool __stdcall _Initialize(IDirect3DDevice8* device)
{
return g_HGooey->Initialize(device);
}
bool __stdcall _HandleKeyboard(BYTE cKey, char* buffer, bool bDown, bool bRepeat)
{
return g_HGooey->HandleKeyboard(cKey, buffer, bDown, bRepeat);
}
bool __stdcall _HandleMouse(int cState, DIMOUSESTATE2* mouse)
{
return g_HGooey->HandleMouse(cState, mouse);
}
void __stdcall _EnableDraw(bool _enable)
{
g_HGooey->DrawEnabled = _enable;
}
void __stdcall _EndScene(float _cursorX, float _cursorY)
{
g_HGooey->EndScene(_cursorX, _cursorY);
}
void __stdcall _LostDevice(void)
{
g_HGooey->LostDevice();
}
void __stdcall _ResetDevice(void)
{
g_HGooey->ResetDevice();
}
//-------------------------------------------------------
// class HGooey (public)
//-------------------------------------------------------
bool __stdcall _HGVersionCheck(UINT _version)
{
return (HGVersion >= _version) &&
(_version >= 71223) && // xenimus locks the mouse starting version 1.114
(_version >= 70102) // phased out ->move
;
}
IDirect3DDevice8* __stdcall _D3DDevice(void)
{
return g_HGooey->h_pD3DDevice;
}
KeyInfo __stdcall _Key(void)
{
return g_HGooey->xKey;
}
MouseInfo __stdcall _Mouse(void)
{
return g_HGooey->xMouse;
}
float __stdcall _FontWidth(void)
{
return g_HGooey->FontWidth;
}
float __stdcall _FontHeight(void)
{
return g_HGooey->FontHeight;
}
float __stdcall _ScreenWidth(void)
{
return g_HGooey->h_iScreenWidth;
}
float __stdcall _ScreenHeight(void)
{
return g_HGooey->h_iScreenHeight;
}
const char* __stdcall _ReadConfigItem(char* _item, char* _filename)
{
return g_HGooey->ReadConfigItem(_item, _filename);
}
bool __stdcall _WriteConfigItem(char* _item, char* _data, char* _filename)
{
return g_HGooey->WriteConfigItem(_item, _data, _filename);
}
HGNodeList* __stdcall _CreateExtension(IDDTexture* _texture, RECT* _rect)
{
return g_HGooey->CreateExtension(_texture, _rect);
}
bool __stdcall _UnloadExtension(HGNodeList* _ext)
{
return g_HGooey->UnloadExtension(_ext);
}
bool __stdcall _SetExtensionMenuItem(HGNodeList* _ext, IDDTexture* _texture, RECT* _rect)
{
return g_HGooey->SetExtensionMenuItem(_ext, _texture, _rect);
}
bool __stdcall _CheckExtMenuIO(HGNodeList* _ext)
{
return g_HGooey->CheckExtMenuIO(_ext);
}
void __stdcall _SetExtMenuIO(HGNodeList* _ext, bool _io)
{
g_HGooey->SetExtMenuIO(_ext, _io);
}
HGOImage* __stdcall _CreateImage(float _wscale, float _hscale, IDDTexture* _texture, RECT* _rect)
{
return g_HGooey->CreateImage(_wscale, _hscale, _texture, _rect);
}
HGOTextBar* __stdcall _CreateTextBar(char* _text, float _wscale, float _hscale)
{
return g_HGooey->CreateTextBar(_text, _wscale, _hscale);
}
HGOTextOverImage* __stdcall _CreateTextOverImage(char* _text)
{
return g_HGooey->CreateTextOverImage(_text);
}
HGObj* __stdcall _CreateAreaSelection(float _width, float _height)
{
return g_HGooey->CreateAreaSelection(_width, _height);
}
HGOListViewer* __stdcall _CreateListViewer(float _wscale, float _hscale, bool _duplicates, float _tscale)
{
return g_HGooey->CreateListViewer(_wscale, _hscale, _duplicates, _tscale);
}
HGOScrollBar* __stdcall _CreateScrollBar(HGOListViewer* _parent, UINT _orientation, float _width, float _height)
{
return g_HGooey->CreateScrollBar(_parent, _orientation, _width, _height);
}
HGODefaultList* __stdcall _CreateDefaultList(char* _title, float _scale, bool _duplicates)
{
return g_HGooey->CreateDefaultList(_title, _scale, _duplicates);
}
HGOButton* __stdcall _CreateButton(char* _text, float _scale)
{
return g_HGooey->CreateButton(_text, _scale);
}
bool __stdcall _AttachObject1(HGObj* _parent, HGObj* _obj)
{
return g_HGooey->AttachObject(_parent, _obj);
}
bool __stdcall _AttachObject2(HGNodeList* _parent, HGObj* _obj)
{
return g_HGooey->AttachObject(_parent, _obj);
}
IDDTexture* __stdcall _CreateIDDTextureFromFile(float _width, float _height, char* _filename, UINT _color)
{
return g_HGooey->CreateIDDTextureFromFile(_width, _height, _filename, _color);
}
IDDTexture* __stdcall _CreateIDDTexture(float _width, float _height, IDirect3DTexture8* _texture)
{
return g_HGooey->CreateIDDTexture(_width, _height, _texture);
}
void __stdcall _ActivateFull1(HGObj* _obj, bool _active)
{
g_HGooey->ActivateFull(_obj, _active);
}
void __stdcall _ActivateFull2(HGNodeList* _list, bool _active)
{
g_HGooey->ActivateFull(_list, _active);
}
void __stdcall _DrawText(char* _str, float _x, float _y, float _scale, UINT _color, bool _vertical, RECT* _trim)
{
g_HGooey->DrawText(_str, _x, _y, _scale, _color, _vertical, _trim);
}
//-------------------------------------------------------
//
//-------------------------------------------------------
char* __stdcall _restring(const char* _str, int _start, int _size)
{
if (!_str || _start < 0 || _size < 1) return "";
char* cTemp = new char[_size+1];
for (int i = _start; i < _start + _size; i++)
{
if (i < (int)strlen(_str))
cTemp[i - _start] = _str[i];
else
cTemp[i - _start] = NULL;
}
cTemp[_size] = NULL;
return cTemp;
}
//-------------------------------------------------------
//
//-------------------------------------------------------
BYTE __stdcall _convertDIK_Name(const char* _name)
{
if (_name)
{
for (int i = 0; i < keyCount; i++)
if (_stricmp(_name, DIK_Name[i]) == 0) return DIK_Key[i];
}
return 0x00;
}
//-------------------------------------------------------
//
//-------------------------------------------------------
BYTE __stdcall _convertDIK_KeyText(const char* _text)
{
if (_text)
{
for (int i = 0; i < keyCount; i++)
if (_stricmp(_text, DIK_KeyText[i]) == 0) return DIK_Key[i];
}
return 0x00;
}
//-------------------------------------------------------
//
//-------------------------------------------------------
char* __stdcall _convertDIK_Key(BYTE _key)
{
for (int i = 0; i < keyCount; i++)
if (_key == DIK_Key[i]) return DIK_Name[i];
return "";
}
//-------------------------------------------------------
//
//-------------------------------------------------------
float __stdcall _W2X(float _width)
{
return _width * g_HGooey->h_fGuiScaleX;
}
float __stdcall _H2Y(float _height)
{
return _height * g_HGooey->h_fGuiScaleY;
}
float __stdcall _X2W(float _xDifference)
{
return _xDifference / g_HGooey->h_fGuiScaleX;
}
float __stdcall _Y2H(float _yDifference)
{
return _yDifference / g_HGooey->h_fGuiScaleY;
}
//-------------------------------------------------------
// class IDDTexture
//-------------------------------------------------------
float __stdcall IDDTexture_GetWidth(IDDTexture* element)
{
return element->Width;
}
float __stdcall IDDTexture_GetHeight(IDDTexture* element)
{
return element->Height;
}
//-------------------------------------------------------
// class HGObj
//-------------------------------------------------------
bool __stdcall _SetRemoteAction(HGObj* element, ACTIONPROC _remoteaction)
{
return element->SetRemoteAction(_remoteaction);
}
void __stdcall _SetStickyIO(HGObj* element, bool _stickyio)
{
element->SetStickyIO(_stickyio);
}
bool __stdcall _GetStickyIO(HGObj* element)
{
return element->GetStickyIO();
}
void __stdcall _SetIO(HGObj* element, bool _io)
{
element->SetIO(_io);
}
bool __stdcall _GetIO(HGObj* element)
{
return element->GetIO();
}
void __stdcall _SetActive(HGObj* element, bool _active)
{
element->Active = _active;
}
bool __stdcall _GetActive(HGObj* element)
{
return element->Active;
}
void __stdcall _SetCancelClick(HGObj* element, bool _cancelclick)
{
element->SetCancelClick(_cancelclick);
}
bool __stdcall _GetCancelClick(HGObj* element)
{
return element->GetCancelClick();
}
void __stdcall _SetAcceptAction(HGObj* element, bool _acceptaction)
{
element->SetAcceptAction(_acceptaction);
}
bool __stdcall _GetAcceptAction(HGObj* element)
{
return element->GetAcceptAction();
}
void __stdcall _SetMoveable(HGObj* element, UINT _moveable)
{
element->Moveable = _moveable;
}
UINT __stdcall _GetMoveable(HGObj* element)
{
return element->Moveable;
}
float __stdcall _GetX(HGObj* element)
{
return element->X;
}
float __stdcall _GetY(HGObj* element)
{
return element->Y;
}
float __stdcall _GetWidth(HGObj* element)
{
return element->Width;
}
float __stdcall _GetHeight(HGObj* element)
{
return element->Height;
}
void __stdcall _Move(HGObj* element, float _wDifference, float _hDifference)
{
element->Move(_wDifference, _hDifference);
}
//-------------------------------------------------------
// class HGOImage : public HGObj
//-------------------------------------------------------
bool __stdcall _ResetRect(HGOImage* element, int _left, int _top, int _right, int _bottom)
{
return element->ResetRect(_left, _top, _right, _bottom);
}
void __stdcall _SetTexture(HGOImage* element, float _wscale, float _hscale, IDDTexture* _texture, RECT* _rect)
{
element->SetTexture(_wscale, _hscale, _texture, _rect);
}
void __stdcall _ReScale(HGOImage* element, float _wscale, float _hscale)
{
element->ReScale(_wscale, _hscale);
}
float __stdcall _GetWidthScale(HGOImage* element)
{
return element->GetWidthScale();
}
float __stdcall _GetHeightScale(HGOImage* element)
{
return element->GetHeightScale();
}
//-------------------------------------------------------
// class HGOTextOverImage : public HGOImage
//-------------------------------------------------------
void __stdcall _SetText(HGOTextOverImage* element, char* _str)
{
element->SetText(_str);
}
void __stdcall _SetBorderWidth(HGOTextOverImage* element, float _borderwidth)
{
element->SetBorderWidth(_borderwidth);
}
void __stdcall _SetBorderHeight(HGOTextOverImage* element, float _borderheight)
{
element->SetBorderHeight(_borderheight);
}
//-------------------------------------------------------
// class HGOListViewer : public HGOTextOverImage
//-------------------------------------------------------
void __stdcall _SetAutoScroll(HGOListViewer* element, bool _autoscroll)
{
element->AutoScroll = _autoscroll;
}
bool __stdcall _GetAutoScroll(HGOListViewer* element)
{
return element->AutoScroll;
}
bool __stdcall _LoadString(HGOListViewer* element, char* _str)
{
return element->LoadString(_str);
}
bool __stdcall _UnloadString(HGOListViewer* element, char* _str)
{
return element->UnloadString(_str);
}
bool __stdcall _UnloadStringAt(HGOListViewer* element, int _index)
{
return element->UnloadStringAt(_index);
}
char* __stdcall _ContainsString(HGOListViewer* element, char* _str)
{
return element->ContainsString(_str);
}
char* __stdcall _GetSelected(HGOListViewer* element)
{
return element->GetSelected();
}
void __stdcall _UnSelect(HGOListViewer* element)
{
element->UnSelect();
}
bool __stdcall _SetStringAt(HGOListViewer* element, int _index, char* _str)
{
return element->SetStringAt(_index, _str);
}
char* __stdcall _StringAt(HGOListViewer* element, int _index)
{
return element->StringAt(_index);
}
void __stdcall _Empty(HGOListViewer* element)
{
element->Empty();
}
void __stdcall _ReScaleByLines(HGOListViewer* element, float _wscale, int _lines)
{
element->ReScaleByLines(_wscale, _lines);
}
//-------------------------------------------------------
// class HGMenu
//-------------------------------------------------------
bool __stdcall _isOpen()
{
return (g_HGooey->h_oHGMenu)->isOpen();
}
//-------------------------------------------------------
// class HGODefaultList : public HGOImage
//-------------------------------------------------------
HGOListViewer* __stdcall _GetListViewer(HGODefaultList* element)
{
return element->ListViewer;
}
HGOButton* __stdcall _GetButtonOK(HGODefaultList* element)
{
return element->ButtonOK;
}
HGOButton* __stdcall _GetButtonCancel(HGODefaultList* element)
{
return element->ButtonCancel;
}
//-------------------------------------------------------
// class HGOTextBar : public HGOTextOverImage
//-------------------------------------------------------
void __stdcall _SetTextColor(HGOTextBar* element, UINT _textcolor)
{
element->TextColor = _textcolor;
}
UINT __stdcall _GetTextColor(HGOTextBar* element)
{
return element->TextColor;
}
//-------------------------------------------------------
// class HGOButton : public HGOTextBar
//-------------------------------------------------------
void __stdcall _SetIdleColor(HGOButton* element, UINT _idlecolor)
{
element->IdleColor = _idlecolor;
}
UINT __stdcall _GetIdleColor(HGOButton* element)
{
return element->IdleColor;
}
void __stdcall _SetActiveColor(HGOButton* element, UINT _activecolor)
{
element->ActiveColor = _activecolor;
}
UINT __stdcall _GetActiveColor(HGOButton* element)
{
return element->ActiveColor;
}
| [
"[email protected]"
]
| [
[
[
1,
676
]
]
]
|
6a255b9081e8412e472ebefbdb3c77d2e5210487 | 29792c63c345f87474136c8df87beb771f0a20a8 | /server/vehiclepool.h | b1819f5e79cb225a4df4672f3f26e10e0618598a | []
| no_license | uvbs/jvcmp | 244ba6c2ab14ce0a757f3f6044b5982287b01fae | 57225e1c52085216a0a4a9c4e33ed324c1c92d39 | refs/heads/master | 2020-12-29T00:25:39.180996 | 2009-06-24T14:52:39 | 2009-06-24T14:52:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 784 | h | // File Author: kyeman
#pragma once
class CVehiclePool
{
private:
BOOL m_bVehicleSlotState[MAX_VEHICLES];
CVehicle *m_pVehicles[MAX_VEHICLES];
public:
CVehiclePool();
~CVehiclePool();
BOOL New(BYTE byteVehicleID, BYTE byteVehicleType, VECTOR * vecPos, float fRotation, int iColor1, int iColor2);
BOOL Delete(BYTE byteVehicleID);
// Retrieve a vehicle by id
CVehicle* GetAt(BYTE byteVehicleID) {
if(byteVehicleID > MAX_VEHICLES) { return NULL; }
return m_pVehicles[byteVehicleID];
};
// Find out if the slot is inuse.
BOOL GetSlotState(BYTE byteVehicleID) {
if(byteVehicleID > MAX_VEHICLES) { return FALSE; }
return m_bVehicleSlotState[byteVehicleID];
};
BOOL InitialiseFromConfig(char* szFile);
void Process();
};
| [
"jacks.mini.net@43d76e2e-6035-11de-a55d-e76e375ae706"
]
| [
[
[
1,
34
]
]
]
|
5f1e684c92197f47197d53e4e8330384332da085 | 4de35be6f0b79bb7eeae32b540c6b1483b933219 | /aura/bncsutilinterface.cpp | a8553baf7c655828fb6d5bc130e716a13e4b8303 | []
| no_license | NoodleBoy/aura-bot | 67b2cfb44a0c8453f54cbde0526924e416a2a567 | 2a7d84dc56653c7a4a8edc1552a90bc848b5a5a9 | refs/heads/master | 2021-01-17T06:52:05.819609 | 2010-12-30T15:18:41 | 2010-12-30T15:18:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,612 | cpp | /*
Copyright [2010] [Josko Nikolic]
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/
*/
#include "aura.h"
#include "util.h"
#include "bncsutilinterface.h"
#include <bncsutil/bncsutil.h>
//
// CBNCSUtilInterface
//
CBNCSUtilInterface :: CBNCSUtilInterface( const string &userName, const string &userPassword )
{
// m_nls = (void *)nls_init( userName.c_str( ), userPassword.c_str( ) );
m_NLS = new NLS( userName, userPassword );
}
CBNCSUtilInterface :: ~CBNCSUtilInterface( )
{
// nls_free( (nls_t *)m_nls );
delete (NLS *)m_NLS;
}
void CBNCSUtilInterface :: Reset( string &userName, string &userPassword )
{
// nls_free( (nls_t *)m_nls );
// m_nls = (void *)nls_init( userName.c_str( ), userPassword.c_str( ) );
delete (NLS *)m_NLS;
m_NLS = new NLS( userName, userPassword );
}
bool CBNCSUtilInterface :: HELP_SID_AUTH_CHECK( string &war3Path, string &keyROC, string &keyTFT, const string &valueStringFormula, const string &mpqFileName, const BYTEARRAY &clientToken, const BYTEARRAY &serverToken )
{
// set m_EXEVersion, m_EXEVersionHash, m_EXEInfo, m_InfoROC, m_InfoTFT
string FileWar3EXE = war3Path + "war3.exe";
string FileStormDLL = war3Path + "Storm.dll";
if( !UTIL_FileExists( FileStormDLL ) )
FileStormDLL = war3Path + "storm.dll";
string FileGameDLL = war3Path + "game.dll";
bool ExistsWar3EXE = UTIL_FileExists( FileWar3EXE );
bool ExistsStormDLL = UTIL_FileExists( FileStormDLL );
bool ExistsGameDLL = UTIL_FileExists( FileGameDLL );
if( ExistsWar3EXE && ExistsStormDLL && ExistsGameDLL )
{
// todotodo: check getExeInfo return value to ensure 1024 bytes was enough
char buf[1024];
uint32_t EXEVersion;
getExeInfo( FileWar3EXE.c_str( ), (char *)&buf, 1024, (uint32_t *)&EXEVersion, BNCSUTIL_PLATFORM_X86 );
m_EXEInfo = buf;
m_EXEVersion = UTIL_CreateByteArray( EXEVersion, false );
uint32_t EXEVersionHash;
checkRevisionFlat( valueStringFormula.c_str( ), FileWar3EXE.c_str( ), FileStormDLL.c_str( ), FileGameDLL.c_str( ), extractMPQNumber( mpqFileName.c_str( ) ), (unsigned long *)&EXEVersionHash );
m_EXEVersionHash = UTIL_CreateByteArray( EXEVersionHash, false );
m_KeyInfoROC = CreateKeyInfo( keyROC, UTIL_ByteArrayToUInt32( clientToken, false ), UTIL_ByteArrayToUInt32( serverToken, false ) );
m_KeyInfoTFT = CreateKeyInfo( keyTFT, UTIL_ByteArrayToUInt32( clientToken, false ), UTIL_ByteArrayToUInt32( serverToken, false ) );
if( m_KeyInfoROC.size( ) == 36 && m_KeyInfoTFT.size( ) == 36 )
return true;
else
{
if( m_KeyInfoROC.size( ) != 36 )
Print( "[BNCSUI] unable to create ROC key info - invalid ROC key" );
if( m_KeyInfoTFT.size( ) != 36 )
Print( "[BNCSUI] unable to create TFT key info - invalid TFT key" );
}
}
else
{
if( !ExistsWar3EXE )
Print( "[BNCSUI] unable to open [" + FileWar3EXE + "]" );
if( !ExistsStormDLL )
Print( "[BNCSUI] unable to open [" + FileStormDLL + "]" );
if( !ExistsGameDLL )
Print( "[BNCSUI] unable to open [" + FileGameDLL + "]" );
}
return false;
}
bool CBNCSUtilInterface :: HELP_SID_AUTH_ACCOUNTLOGON( )
{
// set m_ClientKey
char buf[32];
// nls_get_A( (nls_t *)m_nls, buf );
( (NLS *)m_NLS )->getPublicKey( buf );
m_ClientKey = UTIL_CreateByteArray( (unsigned char *)buf, 32 );
return true;
}
bool CBNCSUtilInterface :: HELP_SID_AUTH_ACCOUNTLOGONPROOF( const BYTEARRAY &salt, const BYTEARRAY &serverKey )
{
// set m_M1
char buf[20];
// nls_get_M1( (nls_t *)m_nls, buf, string( serverKey.begin( ), serverKey.end( ) ).c_str( ), string( salt.begin( ), salt.end( ) ).c_str( ) );
( (NLS *)m_NLS )->getClientSessionKey( buf, string( salt.begin( ), salt.end( ) ).c_str( ), string( serverKey.begin( ), serverKey.end( ) ).c_str( ) );
m_M1 = UTIL_CreateByteArray( (unsigned char *)buf, 20 );
return true;
}
bool CBNCSUtilInterface :: HELP_PvPGNPasswordHash( string &userPassword )
{
// set m_PvPGNPasswordHash
char buf[20];
hashPassword( userPassword.c_str( ), buf );
m_PvPGNPasswordHash = UTIL_CreateByteArray( (unsigned char *)buf, 20 );
return true;
}
BYTEARRAY CBNCSUtilInterface :: CreateKeyInfo( string &key, uint32_t clientToken, uint32_t serverToken )
{
unsigned char Zeros[] = { 0, 0, 0, 0 };
BYTEARRAY KeyInfo;
CDKeyDecoder Decoder( key.c_str( ), key.size( ) );
if( Decoder.isKeyValid( ) )
{
UTIL_AppendByteArray( KeyInfo, UTIL_CreateByteArray( (uint32_t)key.size( ), false ) );
UTIL_AppendByteArray( KeyInfo, UTIL_CreateByteArray( Decoder.getProduct( ), false ) );
UTIL_AppendByteArray( KeyInfo, UTIL_CreateByteArray( Decoder.getVal1( ), false ) );
UTIL_AppendByteArray( KeyInfo, UTIL_CreateByteArray( Zeros, 4 ) );
size_t Length = Decoder.calculateHash( clientToken, serverToken );
char *buf = new char[Length];
Length = Decoder.getHash( buf );
UTIL_AppendByteArray( KeyInfo, UTIL_CreateByteArray( (unsigned char *)buf, Length ) );
delete [] buf;
}
return KeyInfo;
}
| [
"[email protected]@268e31a9-a219-ec89-1cb4-ecc417c412f6",
"[email protected]"
]
| [
[
[
1,
2
],
[
4,
20
],
[
22,
159
]
],
[
[
3,
3
],
[
21,
21
]
]
]
|
7f0ee7783b6b4b8cfd31fa2592b3d65fd527b8c4 | 203f8465075e098f69912a6bbfa3498c36ce2a60 | /stacks/motion_planning/sbpl/src/planners/ARAStar/araplanner.h | cd9b2c1e51f04d1d97f3ae8a2c42d464f4f1b308 | []
| no_license | robcn/personalrobots-pkg | a4899ff2db9aef00a99274d70cb60644124713c9 | 4dcf3ca1142d3c3cb85f6d42f7afa33c59e2240a | refs/heads/master | 2021-06-20T16:28:29.549716 | 2009-09-04T23:56:10 | 2009-09-04T23:56:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,266 | h | /*
* Copyright (c) 2008, Maxim Likhachev
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the University of Pennsylvania nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __ARAPLANNER_H_
#define __ARAPLANNER_H_
//---configuration----
//control of EPS
#define ARA_DEFAULT_INITIAL_EPS 5.0
#define ARA_DECREASE_EPS 0.2
#define ARA_FINAL_EPS 1.0
//---------------------
#define ARA_INCONS_LIST_ID 0
class CMDP;
class CMDPSTATE;
class CMDPACTION;
class CHeap;
class CList;
//-------------------------------------------------------------
//state structure
typedef class ARASEARCHSTATEDATA : public AbstractSearchState
{
public:
CMDPSTATE* MDPstate; //the MDP state itself
//ARA* relevant data
unsigned int v;
unsigned int g;
short unsigned int iterationclosed;
short unsigned int callnumberaccessed;
short unsigned int numofexpands;
//best predecessor and the action from it, used only in forward searches
CMDPSTATE *bestpredstate;
//the next state if executing best action
CMDPSTATE *bestnextstate;
unsigned int costtobestnextstate;
int h;
public:
ARASEARCHSTATEDATA() {};
~ARASEARCHSTATEDATA() {};
} ARAState;
//statespace
typedef struct ARASEARCHSTATESPACE
{
double eps;
double eps_satisfied;
CHeap* heap;
CList* inconslist;
short unsigned int searchiteration;
short unsigned int callnumber;
CMDPSTATE* searchgoalstate;
CMDPSTATE* searchstartstate;
CMDP searchMDP;
bool bReevaluatefvals;
bool bReinitializeSearchStateSpace;
bool bNewSearchIteration;
} ARASearchStateSpace_t;
//ARA* planner
class ARAPlanner : public SBPLPlanner
{
public:
int replan(double allocated_time_secs, vector<int>* solution_stateIDs_V);
int replan(double allocated_time_sec, vector<int>* solution_stateIDs_V, int* solcost);
int set_goal(int goal_stateID);
int set_start(int start_stateID);
void costs_changed(StateChangeQuery const & stateChange);
void costs_changed();
int force_planning_from_scratch();
int set_search_mode(bool bSearchUntilFirstSolution);
virtual double get_solution_eps() const {return pSearchStateSpace_->eps_satisfied;};
virtual int get_n_expands() const { return searchexpands; }
virtual void set_initialsolution_eps(double initialsolution_eps) {finitial_eps = initialsolution_eps;};
void print_searchpath(FILE* fOut);
//constructors & destructors
ARAPlanner(DiscreteSpaceInformation* environment, bool bforwardsearch);
~ARAPlanner();
private:
//member variables
double finitial_eps;
MDPConfig* MDPCfg_;
bool bforwardsearch; //if true, then search proceeds forward, otherwise backward
bool bsearchuntilfirstsolution; //if true, then search until first solution only (see planner.h for search modes)
ARASearchStateSpace_t* pSearchStateSpace_;
unsigned int searchexpands;
int MaxMemoryCounter;
clock_t TimeStarted;
FILE *fDeb;
//member functions
void Initialize_searchinfo(CMDPSTATE* state, ARASearchStateSpace_t* pSearchStateSpace);
CMDPSTATE* CreateState(int stateID, ARASearchStateSpace_t* pSearchStateSpace);
CMDPSTATE* GetState(int stateID, ARASearchStateSpace_t* pSearchStateSpace);
int ComputeHeuristic(CMDPSTATE* MDPstate, ARASearchStateSpace_t* pSearchStateSpace);
//initialization of a state
void InitializeSearchStateInfo(ARAState* state, ARASearchStateSpace_t* pSearchStateSpace);
//re-initialization of a state
void ReInitializeSearchStateInfo(ARAState* state, ARASearchStateSpace_t* pSearchStateSpace);
void DeleteSearchStateData(ARAState* state);
//used for backward search
void UpdatePreds(ARAState* state, ARASearchStateSpace_t* pSearchStateSpace);
//used for forward search
void UpdateSuccs(ARAState* state, ARASearchStateSpace_t* pSearchStateSpace);
int GetGVal(int StateID, ARASearchStateSpace_t* pSearchStateSpace);
//returns 1 if the solution is found, 0 if the solution does not exist and 2 if it ran out of time
int ImprovePath(ARASearchStateSpace_t* pSearchStateSpace, double MaxNumofSecs);
void BuildNewOPENList(ARASearchStateSpace_t* pSearchStateSpace);
void Reevaluatefvals(ARASearchStateSpace_t* pSearchStateSpace);
//creates (allocates memory) search state space
//does not initialize search statespace
int CreateSearchStateSpace(ARASearchStateSpace_t* pSearchStateSpace);
//deallocates memory used by SearchStateSpace
void DeleteSearchStateSpace(ARASearchStateSpace_t* pSearchStateSpace);
//debugging
void PrintSearchState(ARAState* state, FILE* fOut);
//reset properly search state space
//needs to be done before deleting states
int ResetSearchStateSpace(ARASearchStateSpace_t* pSearchStateSpace);
//initialization before each search
void ReInitializeSearchStateSpace(ARASearchStateSpace_t* pSearchStateSpace);
//very first initialization
int InitializeSearchStateSpace(ARASearchStateSpace_t* pSearchStateSpace);
int SetSearchGoalState(int SearchGoalStateID, ARASearchStateSpace_t* pSearchStateSpace);
int SetSearchStartState(int SearchStartStateID, ARASearchStateSpace_t* pSearchStateSpace);
//reconstruct path functions are only relevant for forward search
int ReconstructPath(ARASearchStateSpace_t* pSearchStateSpace);
void PrintSearchPath(ARASearchStateSpace_t* pSearchStateSpace, FILE* fOut);
int getHeurValue(ARASearchStateSpace_t* pSearchStateSpace, int StateID);
//get path
vector<int> GetSearchPath(ARASearchStateSpace_t* pSearchStateSpace, int& solcost);
bool Search(ARASearchStateSpace_t* pSearchStateSpace, vector<int>& pathIds, int & PathCost, bool bFirstSolution, bool bOptimalSolution, double MaxNumofSecs);
};
#endif
| [
"maximl@f5854215-dd47-0410-b2c4-cdd35faa7885",
"poftwaresatent@f5854215-dd47-0410-b2c4-cdd35faa7885"
]
| [
[
[
1,
112
],
[
114,
119
],
[
121,
231
]
],
[
[
113,
113
],
[
120,
120
]
]
]
|
e097a5a94beb1252083c073fa4f27383c076f1e2 | 0f7af923b9d3a833f70dd5ab6f9927536ac8e31c | / elistestserver/SubsetDataAssister.cpp | b2e2e73ac510dc6b4a3f52f1879df2d65447dd63 | []
| no_license | empiredan/elistestserver | c422079f860f166dd3fcda3ced5240d24efbd954 | cfc665293731de94ff308697f43c179a4a2fc2bb | refs/heads/master | 2016-08-06T07:24:59.046295 | 2010-01-25T16:40:32 | 2010-01-25T16:40:32 | 32,509,805 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,540 | cpp | // SubsetDataAssister.cpp: implementation of the CSubsetDataAssister class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "ELISTestServer.h"
//#include "ELISTestServerDlg.h"
#include "SubsetDataAssister.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
class CELISTestServerDlg;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CSubsetDataAssister::CSubsetDataAssister()
{
assist.shareOfCommonBuffer = NULL;
assist.subsetNumPerReturn = NULL;
assist.totalSizeOfSubsetsPerReturn = NULL;
heads = NULL;
created = FALSE;
}
CSubsetDataAssister::~CSubsetDataAssister()
{
clear();
}
void CSubsetDataAssister::clear()
{
if(assist.shareOfCommonBuffer != NULL) delete []assist.shareOfCommonBuffer;
if(assist.subsetNumPerReturn != NULL) delete []assist.subsetNumPerReturn;
if(assist.totalSizeOfSubsetsPerReturn != NULL) delete []assist.totalSizeOfSubsetsPerReturn;
if(heads != NULL) delete []heads;
created = FALSE;
}
void CSubsetDataAssister::create(UINT actNum)
{
clear();
ASSERT(actNum > 0);
assist.shareOfCommonBuffer = new float[actNum];
assist.subsetNumPerReturn = new UINT[actNum];
assist.totalSizeOfSubsetsPerReturn = new UINT[actNum];
heads = new RtcBLOCK_DATA_HEADER[actNum];
this->actNum = actNum;
created = TRUE;
}
void CSubsetDataAssister::Save(CFile &log) {
char bout[4096];
ULONG i;
sprintf(bout, "logTimerElapse:%d\n", assist.logTimerElapse);
log.Write(bout, strlen(bout));
sprintf(bout, "subsetNumPerReturn[%d~%d]:", 0, actNum-1);
for(i = 0; i < actNum-1; i++) {
sprintf(bout, "%s%d,", bout, assist.subsetNumPerReturn[i]);
}
sprintf(bout, "%s%d\n", bout, assist.subsetNumPerReturn[i]);
log.Write(bout, strlen(bout));
sprintf(bout, "totalSizeOfSubsetsPerReturn[%d~%d]:", 0, actNum-1);
for(i = 0; i < actNum-1; i++) {
sprintf(bout, "%s%d,", bout, assist.totalSizeOfSubsetsPerReturn[i]);
}
sprintf(bout, "%s%d\n", bout, assist.totalSizeOfSubsetsPerReturn[i]);
log.Write(bout, strlen(bout));
sprintf(bout, "shareOfCommonBuffer[%d~%d]:", 0, actNum-1);
for(i = 0; i < actNum-1; i++) {
sprintf(bout, "%s%f,", bout, assist.shareOfCommonBuffer[i]);
}
sprintf(bout, "%s%f\n", bout, assist.shareOfCommonBuffer[i]);
log.Write(bout, strlen(bout));
log.Flush();
}
| [
"zwusheng@3065b396-e208-11de-81d3-db62269da9c1"
]
| [
[
[
1,
92
]
]
]
|
586f337fc2d48714103583c543a76bb256c8f881 | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/nGENE Proj/BWTEncoder.cpp | 9a116b053ff40e7625db1b02a66e60389145e831 | []
| no_license | svn2github/ngene | b2cddacf7ec035aa681d5b8989feab3383dac012 | 61850134a354816161859fe86c2907c8e73dc113 | refs/heads/master | 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,880 | cpp | /*
---------------------------------------------------------------------------
This source file is part of nGENE Tech.
Copyright (c) 2006- Wojciech Toman
This program is free software.
File: BWTEncoder.cpp
Version: 0.02
---------------------------------------------------------------------------
*/
#include "PrecompiledHeaders.h"
#include "BWTEncoder.h"
#include <set>
namespace nGENE
{
BWTEncoder::BoundedCompare::BoundedCompare(char* _buffer, uint _count):
m_pBuffer(_buffer),
m_nCount(_count)
{
}
//----------------------------------------------------------------------
bool BWTEncoder::BoundedCompare::operator()(const char *p1, const char *p2) const
{
unsigned int l1 = (unsigned int)((m_pBuffer - p1) + m_nCount);
unsigned int l2 = (unsigned int)((m_pBuffer - p2) + m_nCount);
int result = memcmp(p1, p2, min(l1, l2));
if(result < 0)
return true;
if(result > 0)
return false;
return l1 > l2;
}
//----------------------------------------------------------------------
//----------------------------------------------------------------------
//----------------------------------------------------------------------
BWTEncoder::BWTEncoder(uint _blockSize):
m_pBuffer(NULL),
m_nCount(0),
m_kBlockSize(_blockSize)
{
}
//----------------------------------------------------------------------
uint BWTEncoder::encode(char* _result, const char* _data, uint _size)
{
if(!_size)
return 0;
const char* pointer = _data;
uint index = 0;
uint size = _size;
uint totalSize = _size;
uint prevSize = 0;
while(pointer < _data + _size)
{
m_nCount = m_kBlockSize < size ? m_kBlockSize : size;
if(m_nCount != prevSize)
{
NGENE_DELETE_ARRAY(m_pBuffer);
m_pBuffer = new char[m_nCount];
prevSize = m_nCount;
}
memcpy(m_pBuffer, pointer, m_nCount);
// Save block size
uint temp = m_nCount + 1;
memcpy(&_result[index], &temp, sizeof(uint));
index += sizeof(uint);
uint i = 0;
std::set <char*, BoundedCompare> p(BoundedCompare(m_pBuffer, m_nCount));
for(i = 0; i < m_nCount; ++i)
p.insert(m_pBuffer + i);
std::set <char*, BoundedCompare>::iterator iter;
dword first = 0;
dword last = 0;
for(i = 0, iter = p.begin(); iter != p.end(); i++, iter++)
{
if(*iter == (m_pBuffer + 1))
first = i;
if(*iter == m_pBuffer)
{
last = i;
_result[index++] = '?';
}
else
_result[index++] = (*iter)[-1];
}
p.erase(p.begin(), p.end());
memcpy(&_result[index], &first, sizeof(dword));
index += sizeof(dword);
memcpy(&_result[index], &last, sizeof(dword));
index += sizeof(dword);
totalSize += 2 * sizeof(dword) + sizeof(uint);
pointer += m_nCount;
size -= m_nCount;
}
NGENE_DELETE_ARRAY(m_pBuffer);
return totalSize;
}
//----------------------------------------------------------------------
void BWTEncoder::encode(ostream& _result, const char* _data, uint _size)
{
if(!_size)
return;
const char* pointer = _data;
uint size = _size;
char prevFill = _result.fill(0);
uint prevSize = 0;
while(pointer < _data + _size)
{
m_nCount = m_kBlockSize < size ? m_kBlockSize : size;
if(m_nCount != prevSize)
{
NGENE_DELETE_ARRAY(m_pBuffer);
m_pBuffer = new char[m_nCount];
prevSize = m_nCount;
}
memcpy(m_pBuffer, pointer, m_nCount);
// Save block size
_result.width(sizeof(uint));
uint temp = m_nCount + 1;
_result.write((char*)&temp, sizeof(uint));
_result.width(sizeof(char));
uint i = 0;
std::set <char*, BoundedCompare> p(BoundedCompare(m_pBuffer, m_nCount));
for(i = 0; i <= m_nCount; ++i)
p.insert(m_pBuffer + i);
std::set <char*, BoundedCompare>::iterator iter;
dword first = 0;
dword last = 0;
for(i = 0, iter = p.begin(); iter != p.end(); i++, iter++)
{
if(*iter == (m_pBuffer + 1))
first = i;
if(*iter == m_pBuffer)
{
last = i;
_result << '?';
}
else
_result << (*iter)[-1];
}
p.erase(p.begin(), p.end());
_result.width(sizeof(dword));
_result.write((char*)&first, sizeof(dword));
_result.width(sizeof(dword));
_result.write((char*)&last, sizeof(dword));
pointer += m_nCount;
size -= m_nCount;
}
NGENE_DELETE_ARRAY(m_pBuffer);
_result.fill(prevFill);
}
//----------------------------------------------------------------------
uint BWTEncoder::decode(char* _result, const char* _data, uint _size)
{
const char* pointer = _data;
uint* T = NULL;
uint begin = 0;
uint num[257];
uint runningTotal[257];
uint prevSize = 0;
while(pointer < _data + _size)
{
memcpy(&m_nCount, pointer, sizeof(uint));
pointer += sizeof(uint);
if(m_nCount != prevSize)
{
NGENE_DELETE_ARRAY(m_pBuffer);
NGENE_DELETE_ARRAY(T);
m_pBuffer = new char[m_nCount];
T = new uint[m_nCount];
prevSize = m_nCount;
}
memcpy(m_pBuffer, pointer, m_nCount);
pointer += m_nCount;
dword first;
dword last;
memcpy(&first, pointer, sizeof(dword));
pointer += sizeof(dword);
memcpy(&last, pointer, sizeof(dword));
pointer += sizeof(dword);
memset(num, 0, sizeof(uint) * 257);
for(uint i = 0; i < m_nCount; ++i)
{
if(i == last)
++num[256];
else
++num[(byte)m_pBuffer[i]];
}
uint sum = 0;
for(uint i = 0; i < 257; ++i)
{
runningTotal[i] = sum;
sum += num[i];
num[i] = 0;
}
memset(T, 0, sizeof(uint) * m_nCount);
for(uint i = 0; i < m_nCount; ++i)
{
uint index = 0;
if(i == last)
index = 256;
else
index = (byte)m_pBuffer[i];
T[num[index] + runningTotal[index]] = i;
num[index]++;
}
uint index = first;
uint j = 0;
for(j = 0; j < m_nCount - 1; ++j)
{
_result[j + begin] = m_pBuffer[index];
index = T[index];
}
begin = j;
}
NGENE_DELETE_ARRAY(m_pBuffer);
NGENE_DELETE_ARRAY(T);
return _size;
}
//----------------------------------------------------------------------
void BWTEncoder::decode(ostream& _result, const char* _data, uint _size)
{
const char* pointer = _data;
uint* T = NULL;
uint num[257];
uint runningTotal[257];
uint prevSize = 0;
while(pointer < _data + _size)
{
memcpy(&m_nCount, pointer, sizeof(uint));
pointer += sizeof(uint);
if(m_nCount != prevSize)
{
NGENE_DELETE_ARRAY(m_pBuffer);
NGENE_DELETE_ARRAY(T);
m_pBuffer = new char[m_nCount];
T = new uint[m_nCount];
prevSize = m_nCount;
}
memcpy(m_pBuffer, pointer, m_nCount);
pointer += m_nCount;
dword first;
dword last;
memcpy(&first, pointer, sizeof(dword));
pointer += sizeof(dword);
memcpy(&last, pointer, sizeof(dword));
pointer += sizeof(dword);
memset(num, 0, sizeof(uint) * 257);
for(uint i = 0; i < m_nCount; ++i)
{
if(i == last)
++num[256];
else
++num[(byte)m_pBuffer[i]];
}
uint sum = 0;
for(uint i = 0; i < 257; ++i)
{
runningTotal[i] = sum;
sum += num[i];
num[i] = 0;
}
memset(T, 0, sizeof(uint) * m_nCount);
for(uint i = 0; i < m_nCount; ++i)
{
uint index = 0;
if(i == last)
index = 256;
else
index = (byte)m_pBuffer[i];
T[num[index] + runningTotal[index]] = i;
num[index]++;
}
uint index = first;
for(uint j = 0; j < m_nCount - 1; ++j)
{
_result << m_pBuffer[index];
index = T[index];
}
}
NGENE_DELETE_ARRAY(m_pBuffer);
NGENE_DELETE_ARRAY(T);
}
//----------------------------------------------------------------------
} | [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
]
| [
[
[
1,
342
]
]
]
|
184f202859dee164f218692363b1332ed4b5bfb7 | 22fb52fc26ab1da21ab837a507524f111df5b694 | /voxelbrain/propagator.h | 28766bb0810302faf8630dbe312bafb7603ceee3 | []
| no_license | yangguang-ecnu/voxelbrain | b343cec00e7b76bc46cc12723f750185fa84e6d2 | 82e1912ff69998077a5d7ecca9b5b1f9d7c1b948 | refs/heads/master | 2021-01-10T01:21:59.902255 | 2009-02-10T05:24:40 | 2009-02-10T05:24:40 | 52,189,505 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,045 | h | #ifndef PROPAGATOR_H_
#define PROPAGATOR_H_
#include "v3sets.h"
#include "nifti.h"
#include "volio.h"
#include "undo.h"
#include <vector>
using namespace std;
inline int dist(int a, int b){
return (a>b)?(a-b):(b-a);
}; //TODO: move to misc
//remove surface vor values [from to]
struct propagator_t {
undo undo_selection;
struct step {
V3i start;
V3i to;
float P;
bool operator<(const step & other) const {
return P > other.P;
}
};
V3i poi; //point of interest;
typedef vector<step> steps_t;
steps_t proposed;
point_list active;
point_list fresh;
// point_list border;
float half_band_size;
float band_center;
float min;
float max;
void set_band(const raw_volume & vol);
void plan(const raw_volume & vol); //fill in proposed steps
float act(const raw_volume & vol); //apply the selected steps; //do not alter anything
float eval(const step &, const raw_volume & vol);
void undo_step();// undo last step
};
#endif /*PROPAGATOR_H_*/
| [
"konstantin.levinski@04f5dad0-e037-0410-8c28-d9c1d3725aa7"
]
| [
[
[
1,
50
]
]
]
|
c6e6b36dc5af8ee42a0a9ccc23e5b8b72a45f57e | 9df2486e5d0489f83cc7dcfb3ccc43374ab2500c | /src/core/math/utilities.cpp | 2a8377d3820d77e6fad52012a904b42bbb0500ea | []
| no_license | renardchien/Eta-Chronicles | 27ad4ffb68385ecaafae4f12b0db67c096f62ad1 | d77d54184ec916baeb1ab7cc00ac44005d4f5624 | refs/heads/master | 2021-01-10T19:28:28.394781 | 2011-09-05T14:40:38 | 2011-09-05T14:40:38 | 1,914,623 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,178 | cpp | /***************************************************************************
* utilities.cpp - General math functions
*
* Copyright (C) 2005 - 2009 Florian Richter
***************************************************************************/
/*
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "../../core/math/utilities.h"
// for rand()
#include <cstdlib>
// for find_if()
#include <algorithm>
// for isdigit()
#include <cctype>
/* non digit class
* returns true if not a number was found
* used by the valid_number function
*/
class nondigit
{
public:
bool operator() ( char c ) const
{
return !isdigit( c );
}
};
namespace SMC
{
/* *** *** *** *** *** *** *** *** Math utility functions *** *** *** *** *** *** *** *** *** */
float Get_Random_Float( float min, float max )
{
return min + (max - min) * static_cast<float>(rand()) / static_cast<float>(RAND_MAX);
}
unsigned int Get_Power_of_2( unsigned int size )
{
unsigned int value = 1;
while( value < size )
{
value <<= 1;
}
return value;
}
bool Is_Valid_Number( std::string num, bool accept_floating_point /* = 1 */ )
{
// accept negative numbers
if( num.find( '-' ) == 0 )
{
num.erase( 0, 1 );
}
// accept numbers with a point if given
if( accept_floating_point )
{
std::string::size_type pos = num.find( '.' );
if( pos != std::string::npos )
{
num.erase( pos, 1 );
}
}
if( std::find_if( num.begin(), num.end(), nondigit() ) == num.end() )
{
return 1;
}
return 0;
}
bool Is_Float_Equal( float a, float b, float tolerance /* = 0.0001f */ )
{
if( fabs(b - a) <= tolerance )
{
return 1;
}
return 0;
}
/* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
} // namespace SMC
| [
"[email protected]"
]
| [
[
[
1,
98
]
]
]
|
98c562b7d9fa0f5aea5c18ded6905acee7208a60 | 4561a0f9a0de6a9b75202e1c05a4bd6ba7adabcf | /sistream.h | 28e1dee0bb8f0bb3915824ac26fe69d1646c6143 | [
"MIT"
]
| permissive | embarkmobile/ustl-symbian | 3a2471a0487ae8d834f44a69debdb4e093215ce0 | 6d108f5683677d1d6b57705ac08cf1a4f5a37204 | refs/heads/master | 2020-04-23T15:37:30.148583 | 2010-12-10T15:35:16 | 2010-12-10T15:35:16 | 898,964 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,768 | h | // This file is part of the ustl library, an STL implementation.
//
// Copyright (C) 2005 by Mike Sharov <[email protected]>
// This file is free software, distributed under the MIT License.
//
// sistream.h
//
#ifndef SISTREAM_H_0CCA102229A49F5D65EE852E62B27CE2
#define SISTREAM_H_0CCA102229A49F5D65EE852E62B27CE2
#include "mistream.h"
#include "ustring.h"
namespace ustl {
/// \class istringstream sistream.h ustl.h
/// \ingroup TextStreams
///
/// \brief A stream that reads textual data from a memory block.
///
class istringstream : public istream {
public:
static const size_type c_MaxDelimiters = 16; ///< Maximum number of word delimiters.
public:
istringstream (void);
istringstream (const void* p, size_type n);
explicit istringstream (const cmemlink& source);
void iread (int8_t& v);
void iread (int32_t& v);
void iread (double& v);
void iread (bool& v);
void iread (wchar_t& v);
void iread (string& v);
#ifdef HAVE_INT64_T
void iread (int64_t& v);
#endif
#if HAVE_LONG_LONG && (!HAVE_INT64_T || SIZE_OF_LONG_LONG > 8)
void iread (long long& v);
#endif
inline string str (void) const { string s; s.link (*this); return (s); }
inline void str (const string& s) { link (s); }
int get (void);
inline void get (char& c) { c = get(); }
void get (char* p, size_type n, char delim = '\n');
void get (string& s, char delim = '\n');
void getline (char* p, size_type n, char delim = '\n');
void getline (string& s, char delim = '\n');
void ignore (size_type n, char delim = '\0');
inline char peek (void) { int8_t v; iread (v); ungetc(); return (v); }
inline void putback (char) { ungetc(); }
inline void unget (void) { ungetc(); }
void set_delimiters (const char* delimiters);
inline void set_base (short base);
inline void set_decimal_separator (char) { }
inline void set_thousand_separator (char) { }
void read (void* buffer, size_type size);
void read (memlink& buf);
inline void read_strz (string& str);
inline void sync (void) { skip (remaining()); }
protected:
char skip_delimiters (void);
private:
inline bool is_delimiter (char c) const;
template <typename T> void read_number (T& v);
private:
char m_Delimiters [c_MaxDelimiters];
uint8_t m_Base;
};
/// Sets the numeric base used to read numbers.
inline void istringstream::set_base (short base)
{
m_Base = base;
}
/// Reads a null-terminated character stream. This is not allowed in this class.
inline void istringstream::read_strz (string&)
{
assert (!"Reading nul characters is not allowed from text streams");
}
/// Reads one type as another.
template <typename RealT, typename CastT>
inline void _cast_read (istringstream& is, RealT& v)
{
CastT cv;
is.iread (cv);
v = RealT (cv);
}
inline istringstream& operator>> (istringstream& is, int8_t& v) { is.iread (v); return (is); }
inline istringstream& operator>> (istringstream& is, int32_t& v){ is.iread (v); return (is); }
inline istringstream& operator>> (istringstream& is, double& v) { is.iread (v); return (is); }
inline istringstream& operator>> (istringstream& is, bool& v) { is.iread (v); return (is); }
inline istringstream& operator>> (istringstream& is, wchar_t& v){ is.iread (v); return (is); }
inline istringstream& operator>> (istringstream& is, string& v) { is.iread (v); return (is); }
#if HAVE_INT64_T
inline istringstream& operator>> (istringstream& is, int64_t& v){ is.iread (v); return (is); }
#endif
#if HAVE_LONG_LONG && (!HAVE_INT64_T || SIZE_OF_LONG_LONG > 8)
inline istringstream& operator>> (istringstream& is, long long& v) { is.iread (v); return (is); }
#endif
#define ISTRSTREAM_CAST_OPERATOR(RealT, CastT) \
inline istringstream& operator>> (istringstream& is, RealT& v) \
{ _cast_read<RealT,CastT>(is, v); return (is); }
ISTRSTREAM_CAST_OPERATOR (uint8_t, int8_t)
ISTRSTREAM_CAST_OPERATOR (int16_t, int32_t)
#ifndef WCHAR_T_IS_TYPEDEF
ISTRSTREAM_CAST_OPERATOR (uint16_t, int32_t)
#endif
ISTRSTREAM_CAST_OPERATOR (uint32_t, int32_t)
ISTRSTREAM_CAST_OPERATOR (float, double)
#if HAVE_THREE_CHAR_TYPES
ISTRSTREAM_CAST_OPERATOR (char, int8_t)
#endif
#if HAVE_INT64_T
ISTRSTREAM_CAST_OPERATOR (uint64_t, int64_t)
#endif
#if SIZE_OF_LONG == SIZE_OF_INT
ISTRSTREAM_CAST_OPERATOR (long, int)
ISTRSTREAM_CAST_OPERATOR (unsigned long,int)
#endif
#if HAVE_LONG_LONG && (!HAVE_INT64_T || SIZE_OF_LONG_LONG > 8)
ISTRSTREAM_CAST_OPERATOR (unsigned long long, long long)
#endif
#undef ISTRSTREAM_CAST_OPERATOR
} // namespace ustl
#endif
| [
"[email protected]"
]
| [
[
[
1,
134
]
]
]
|
61341d8790af99d5cdbbb6300ad6d4bbb3524110 | b2b5c3694476d1631322a340c6ad9e5a9ec43688 | /Baluchon/Pattern.cpp | 0c3ab5b587efd93f11fea458189f994fd5808a12 | []
| no_license | jpmn/rough-albatross | 3c456ea23158e749b029b2112b2f82a7a5d1fb2b | eb2951062f6c954814f064a28ad7c7a4e7cc35b0 | refs/heads/master | 2016-09-05T12:18:01.227974 | 2010-12-19T08:03:25 | 2010-12-19T08:03:25 | 32,195,707 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,012 | cpp | #include "Pattern.h"
#include "cv.h"
#include "highgui.h"
namespace baluchon { namespace core { namespace services { namespace patterndetection {
Pattern::Pattern(char path[])
{
mPath = path;
mWidth = 0;
mHeight = 0;
mPointCount = 0;
init();
}
Pattern::~Pattern(void)
{
}
void Pattern::init()
{
IplImage *initial = cvLoadImage(mPath);
IplImage *img;
mWidth = initial->width;
mHeight = initial->height;
img = cvCreateImage(cvGetSize(initial), initial->depth, 1);
cvCvtColor(initial, img, CV_BGR2GRAY);
cvThreshold(img, img, 100, 255, CV_THRESH_BINARY);
CvMemStorage* g_storage = cvCreateMemStorage(0);
CvSeq *contours, *result, *patCtr;
cvFindContours(img, g_storage, &contours, sizeof(CvContour), CV_RETR_CCOMP,CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0));
int lowX = mWidth;
int lowY = mHeight;
while(contours != NULL)
{
result = cvApproxPoly(contours, sizeof(CvContour), g_storage, CV_POLY_APPROX_DP, cvContourPerimeter(contours)*0.02, 0);
if(cvCheckContourConvexity(result) && fabs(cvContourArea(result, CV_WHOLE_SEQ)) >= (200) && result->total == 4 && contours->v_next != 0 && contours->v_next->h_next == 0) {
for(int i = 0; i < 4; i++)
{
if((*((CvPoint*) cvGetSeqElem(result, i))).x < lowX)
{
lowX = (*((CvPoint*) cvGetSeqElem(result, i))).x;
}
if((*((CvPoint*) cvGetSeqElem(result, i))).y < lowY)
{
lowY = (*((CvPoint*) cvGetSeqElem(result, i))).y;
}
}
mWidth = mWidth - 2*lowX;
mHeight = mHeight - 2*lowY;
patCtr = contours->v_next;
result = cvApproxPoly(patCtr, sizeof(CvContour), g_storage, CV_POLY_APPROX_DP, cvContourPerimeter(patCtr)*0.02, 0);
mPointCount = result->total;
mSrcPoints = new CvPoint2D32f[mPointCount][4];
for(int i = 0; i < mPointCount; i++)
{
mSrcPoints[i][0].x = (float) (*((CvPoint*) cvGetSeqElem(result, i))).x - lowX;
mSrcPoints[i][0].y = (float) (*((CvPoint*) cvGetSeqElem(result, i))).y - lowY;
for(int j = 1; j < 4; j++)
{
mSrcPoints[i][j].x = -1 * mSrcPoints[i][j-1].y + mWidth;
mSrcPoints[i][j].y = mSrcPoints[i][j-1].x;
}
}
}
contours = contours->h_next;
}
cvReleaseMemStorage(&g_storage);
cvReleaseImage(&img);
cvReleaseImage(&initial);
}
int Pattern::getWidth()
{
return mWidth;
}
int Pattern::getPointCount()
{
return mPointCount;
}
int Pattern::getHeight()
{
return mHeight;
}
CvPoint2D32f Pattern::getSourcePointAt(int pos, int orientation)
{
return mSrcPoints[pos][orientation];
}
}}}}; | [
"[email protected]@bd4f47a5-da4e-a94a-6a47-2669d62bc1a5"
]
| [
[
[
1,
108
]
]
]
|
080faebec0f5d2d1457465b0d4b6098afd434372 | 9089f5a53ae6ede61f9da7ddd44fefe47e9e5f07 | /phase_2/driver.cpp | 738990ee84438c499309ce08ddfc70f6a6596d54 | []
| no_license | akamel001/File-System | a5f27deea482da1693d0a83b797e4ba6fa8ff338 | 901d5392a9c3112a3834c7d5071a4eb5f7858bc6 | refs/heads/master | 2021-01-19T12:38:47.928372 | 2011-11-22T00:53:46 | 2011-11-22T00:53:46 | 2,824,363 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 499 | cpp | /*
* Author: Abdelrahman Kamel
* Assignment: CSCI 350 project 2
* Description: A test driver for the simulation disk
*/
#include <iostream>
#include <fstream>
#include "fileSys.h"
using namespace std;
int main()
{
Pdisk disk("disk",64,128);
fileSys fs(disk);
int error = fs.newFile("file1");
error = fs.newFile("file2");
string block;
for(int i=0; i < 128; i++) block += "7";
error = fs.addBlock("file2", block);
fs.fsClose();
}
| [
"[email protected]"
]
| [
[
[
1,
29
]
]
]
|
2357a5006654bbf6d7a1c9f5b18fec860d1b43d3 | 084767fd7ed36a5ecebf3c60cca04e4ef7dbb27d | /Array.h | 1a0f0f0bd738fe2e4217656913fe94873cd8e0f5 | []
| no_license | ricehiroko/alien | 0ea7e06d180f2556cda5f5aa2da8aa88c6ffc166 | 863283b7081b1b7afef59c33843cc1467c320d0a | refs/heads/master | 2021-05-27T16:37:10.619332 | 2011-08-02T17:56:07 | 2011-08-02T17:56:07 | 114,732,151 | 0 | 1 | null | 2017-12-19T07:16:13 | 2017-12-19T07:16:12 | null | WINDOWS-1250 | C++ | false | false | 3,135 | h | !-------------------------------------------------------------------------
! Versión 1.00 Marzo de 2001
!-------------------------------------------------------------------------
! Motivación:
!-------------------------------------------------------------------------
! Estas son unas sencillas clases que me permiten olvidarme de
! como es la sintaxis de Inform para arrays/vectores.
!-------------------------------------------------------------------------
! Uso:
!-------------------------------------------------------------------------
! vector naturales
! private
! elementos 1 2 3 4 5 6 7 8 9 10
! ;
! print naturales.elemento(2);
! naturales.longitud();
! naturales.escribe(2,99); ! en C++ es: naturales.escribe[2] = 99;
!
! array m2por2
! private elementos 1 2
! 3 4,
! dimx 2,
! dimy 2
! ;
!-------------------------------------------------------------------------
System_file;
! Clase base abstracta ----Collection-------------------------------------
class coleccion
private
elementos 0,
with
elemento [;
return 0;
],
longitud [;
return self.#elementos/WORDSIZE;
],
escribe [;
return;
]
;
! Clase ----Vector-------------------------------------------------------
class vector
class coleccion,
with
elemento [i;
if (i<self.longitud()
|| i>=0)
return self.&elementos-->i;
else
return 0;
],
escribe [ i x;
if (i<self.longitud()
&& i>=0)
self.&elementos-->i = x;
]
;
! Clase ----Array---------------------------------------------------------
class array
class coleccion
private
dimx 0,
dimy 0,
with
elemento [x y;
if (x>=0
&& x<self.dev_dimx()
&& y>=0
&& y<self.dev_dimy())
return (self.&elementos-->((x*self.dev_dimy()) + y));
else return 0;
],
escribe [ x y v;
if (x>=0
&& x<self.dev_dimx()
&& y>=0
&& y<self.dev_dimy())
return (self.&elementos-->((x*self.dev_dimy()) + y) = v);
else return 0;
],
dev_dimx [; return self.dimx; ],
dev_dimy [; return self.dimy; ]
;
! Clase ----Coleccion---------------------------------------------------------
class asociativo
class coleccion
private
parelem 0,
with
busca [x i;
for(i=0:i<self.longitud():i++)
if (self.&elementos-->i == x)
break;
if (i==self.longitud())
return -1;
else return i;
],
elemento [x i;
if ((i=self.busca(x))>-1)
return self.&parelem-->i;
else
return -1;
],
escribe [x y i;
if ((i=self.busca(x))>-1)
self.&parelem-->i = y;
],
modifica [x y i;
if ((i=self.busca(x))>-1)
self.&elementos-->i = y;
]
;
| [
"[email protected]"
]
| [
[
[
1,
122
]
]
]
|
33b047224f8804849450bbeec59cde34cde0e70f | 21da454a8f032d6ad63ca9460656c1e04440310e | /src/wcpp/io/wsiDataOutput.h | b6950f35298f33179ec19be29ab7aeab10041d36 | []
| no_license | merezhang/wcpp | d9879ffb103513a6b58560102ec565b9dc5855dd | e22eb48ea2dd9eda5cd437960dd95074774b70b0 | refs/heads/master | 2021-01-10T06:29:42.908096 | 2009-08-31T09:20:31 | 2009-08-31T09:20:31 | 46,339,619 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 220 | h | #ifndef __wsiDataOutput_h__
#define __wsiDataOutput_h__
#include <wcpp.lang/wsiObject.h>
class wsiDataOutput : public wsiObject
{
public:
static const ws_iid sIID;
};
#endif // __wsIDataOutput_h__
| [
"xukun0217@98f29a9a-77f1-11de-91f8-ab615253d9e8"
]
| [
[
[
1,
14
]
]
]
|
55150e9df3e70e56b657b4973407c0084de9689b | 867f5533667cce30d0743d5bea6b0c083c073386 | /jingxian-network/src/jingxian/configure.h | 184e2770040d58efcc19f4adbe9a6d46ecf89f32 | []
| 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 | 4,320 | h |
#ifndef _configure_h_
#define _configure_h_
#include "jingxian/config.h"
#if !defined (JINGXIAN_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* JINGXIAN_LACKS_PRAGMA_ONCE */
// Include files
# include <stack>
# include <list>
# include "jingxian/connection_functionals.h"
# include "jingxian/logging/logging.h"
_jingxian_begin
namespace configure
{
class Context;
typedef _connection_base<bool (Context& context, const tstring& txt)> callback_type;
class IContext
{
public:
virtual ~IContext() {}
virtual void connect(callback_type* connection) = 0;
virtual void disconnect(callback_type* connection) = 0;
virtual void push(callback_type* callback) = 0;
virtual void pop() = 0;
virtual void exit() = 0;
virtual logging::logger& logger() = 0;
};
class Context : public IContext
{
public:
Context(IContext* context)
: pimpl_(context)
{
}
virtual ~Context() {}
virtual void connect(callback_type* connection)
{
pimpl_->connect(connection);
}
template<class desttype>
void connect(desttype* pclass, bool (desttype::*pmemfun)(Context& , const tstring&))
{
_connection<desttype, bool (Context& , const tstring&)>* conn =
new _connection<desttype, bool (Context& , const tstring&)>(pclass, pmemfun);
connect(conn);
}
virtual void disconnect(callback_type* connection)
{
pimpl_->disconnect(connection);
}
virtual void push(callback_type* connection)
{
pimpl_->push(connection);
}
template<class desttype>
void push(desttype* pclass, bool (desttype::*pmemfun)(Context& , const tstring&))
{
_connection<desttype, bool (Context& , const tstring&)>* conn =
new _connection<desttype, bool (Context& , const tstring&)>(pclass, pmemfun);
push(conn);
}
virtual void pop()
{
pimpl_->pop();
}
virtual void exit()
{
pimpl_->exit();
}
virtual logging::logger& logger()
{
return pimpl_->logger();
}
private:
NOCOPY(Context);
IContext* pimpl_;
};
class ContextImpl : public IContext
{
public:
class ConnectionSlot
{
public:
typedef std::list<callback_type *> connections_list;
ConnectionSlot()
{
}
virtual ~ConnectionSlot()
{
for (connections_list::iterator it = m_slots.begin()
; it != m_slots.end(); ++ it)
{
delete (*it);
}
m_slots.clear();
}
virtual void connect(callback_type* connection)
{
m_slots.push_back(connection);
}
virtual void disconnect(callback_type* connection)
{
m_slots.remove(connection);
}
virtual bool call(Context& context, const tstring& txt)
{
connections_list::const_iterator itNext, it = m_slots.begin();
connections_list::const_iterator itEnd = m_slots.end();
while (it != itEnd)
{
itNext = it;
++itNext;
if ((*it)->call(context, txt))
return true;
it = itNext;
}
return false;
}
private:
NOCOPY(ConnectionSlot);
connections_list m_slots;
};
ContextImpl(logging::logger& alogger)
: m_exit(false)
, m_logger(alogger)
{
m_slots.push(new ConnectionSlot());
}
virtual ~ContextImpl() {}
virtual void connect(callback_type* connection)
{
m_slots.top()->connect(connection);
}
virtual void disconnect(callback_type* connection)
{
m_slots.top()->disconnect(connection);
}
virtual void push(callback_type* connection)
{
m_slots.push(new ConnectionSlot());
m_slots.top()->connect(connection);
}
virtual void pop()
{
m_slots.pop();
}
virtual bool call(Context& context, const tstring& txt)
{
return m_slots.top()->call(context, txt);
}
virtual void exit()
{
m_exit = true;
}
virtual bool isExit()
{
return m_exit;
}
virtual logging::logger& logger()
{
return m_logger;
}
private:
NOCOPY(ContextImpl);
std::stack<ConnectionSlot*> m_slots;
bool m_exit;
logging::logger& m_logger;
};
}
_jingxian_end
#endif //_protocolcontext_h_ | [
"runner.mei@0dd8077a-353d-11de-b438-597f59cd7555"
]
| [
[
[
1,
228
]
]
]
|
605b5bbed77ad573ca7510b002e16aaa164c8386 | b2ff7f6bdf1d09f1adc4d95e8bfdb64746a3d6a4 | /src/bmpbufs.cpp | 566c0b72e858562c606e87d94dd36b87dd3b3739 | []
| no_license | thebruno/dabster | 39a315025b9344b8cca344d2904c084516915353 | f85d7ec99a95542461862b8890b2542ec7a6b28d | refs/heads/master | 2020-05-20T08:48:42.053900 | 2007-08-29T14:29:46 | 2007-08-29T14:29:46 | 32,205,762 | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 32,599 | cpp | /*********************************************************************
Sigma Dabster 5
Copyright (C) The Dabster Team 2007.
All rights reserved.
http://www.dabster.prv.pl/
http://code.google.com/p/dabster/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 dated June, 1991.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
bmpbufs
bmpbufs.cpp
*********************************************************************/
#include "bmpbufs.h"
#include "err.h"
namespace bmp {
using namespace bmptypes;
const uint8 BUFFOR::One [8] = {0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01};
const uint8 BUFFOR::ExOne [8] = {0x7F, 0xBF, 0xDF, 0xEF, 0xF7, 0xFB, 0xFD, 0xFE};
//********************class BUFFOR********************//
/*!
* \brief
* Konstruktor klasy BUFFOR.
*
* BUFFOR wykonuje inicjalizacjie (zerowanie) bufora.
*/
BUFFOR::BUFFOR() {
FileSize = 0;
BufSize = BUFFOR_SIZE;
BufBitSize = 8 * BUFFOR_SIZE;
DataCount = 0;
BitDataCount = 0;
ReadSize = BUFFOR_SIZE;
BufBitPosg = 0;
BufBitPosp = 0;
BufBytePosg = 0;
BufBytePosp = 0;
BufState = BUF_BAD;
BufMode = BUF_TRANSFER;
}
/*!
* \brief
* Destruktor ~BUFFOR.
*
* ~BUFFOR zamyka plik.
*/
BUFFOR::~BUFFOR() {
File.close();
}
/*!
* \brief
* OpenFile otwiera plik i ustawia tryb pracy.
*
* \param DabPath
* Rzeczywista sciezka dostepu.
*
* \param DabFileMode
* Tryb otwarcia pliku.
*
* \param DabBufMode
* Tryb pracy bufora.
*
* \throws err()
* Gdy plik nie istnieje.
*
* Otwiera plik, ustawia tryb pracy i oblicza jego wielkosc.
*/
void BUFFOR::OpenFile(std::string DabPath, std::ios_base::open_mode DabFileMode, BUFFOR_MODE DabBufMode) {
// zamknij aktualny plik i zresetuj strumien
if (File) {
File.close();
File.clear();
}
File.rdbuf()->pubsetbuf(0, 0);
File.open(DabPath.c_str(), DabFileMode | std::ios_base::binary);
if (!File) {
BufState = BUF_BAD;
std::vector<string> params(1);
params[0] = DabPath.c_str();
throw err("!BMP0", params);
}
BufMode = DabBufMode;
BufState = BUF_GOOD;
File.seekg(0L,std::ios_base::end);
FileSize = File.tellg();
File.seekg(0L,std::ios_base::beg);
}
/*!
* \brief
* Pobranie jednego bita z bufora.
*
* \returns
* Zwraca 0xFF lub 0x00.
*
* \throws err()
* Rzuca wyjatek, gdy nastepuje proba wykonania niedozwolonej operacji na buforze.
*
* Zwraca wartosc aktualnego bitu w buforze.
*/
uint8 BUFFOR::GetBit() {
switch (BufMode) {
// tryb tylko odczyt
case BUF_READONLY:
// w srodku bufora
if (BufBitPosg + 1 < BitDataCount) {
if (Buf[BufBytePosg] & One[BufBitPosg % 8 ]) {
++BufBitPosg;
if (!(BufBitPosg % 8)) {
++BufBytePosg;
}
return BitSet;
}
else {
++BufBitPosg;
if (!(BufBitPosg % 8)) {
++BufBytePosg;
}
return BitNSet;
}
}
// na ostatniej pozycji danych w buforze
else if (BufBitPosg + 1 == BitDataCount) {
uint8 Result;
if (Buf[BufBytePosg] & One[BufBitPosg % 8 ])
Result = BitSet;
else
Result = BitNSet;
//wczytanie
File.clear();
File.read((char *)Buf, ReadSize);
DataCount = File.gcount();
BitDataCount = 8 * DataCount;
if (!DataCount) {
if (File.eof())
BufState = BUF_EOF;
else {
BufState = BUF_BAD;
return Result;
}
}
BufBytePosg = 0;
BufBitPosg = 0;
return Result;
}
// tu nie powinien buffor nigdy dojsc!
{
std::vector<string> params(1);
throw err("!BMP2", params);
}
// tryb transfer
case BUF_TRANSFER:
// w srodku bufora
if (BufBitPosg + 1 < BitDataCount){
if (Buf[BufBytePosg] & One[BufBitPosg % 8 ]) {
++BufBitPosg;
if (!(BufBitPosg % 8)) {
++BufBytePosg;
}
return BitSet;
}
else {
++BufBitPosg;
if (!(BufBitPosg % 8)) {
++BufBytePosg;
}
return BitNSet;
}
}
// na ostatniej pozycji
else if (BufBitPosg + 1 == BitDataCount) {
uint8 Result;
if (Buf[BufBytePosg] & One[BufBitPosg % 8 ])
Result = BitSet;
else
Result = BitNSet;
BufBytePosg = 0;
BufBitPosg = 0;
DataCount = 0;
BitDataCount = 0;
BufState = BUF_EMPTY;
return Result;
}
else {
// nie moze zabraknac danych w Buforze!!
BufState = BUF_BAD;
std::vector<string> params(1);
throw err("!BMP2", params);
}
default: {
// inny tryb niedozwolony
std::vector<string> params(1);
throw err("!BMP2", params);
}
}
}
/*!
* \brief
* Zapis jednego bita do bufora.
*
* \param DabBit
* Wartosc zapisywanego bita 0xFF lub 0x00.
*
* \throws err()
* Rzuca wyjatek, gdy nastepuje proba wykonania niedozwolonej operacji na buforze.
*
* Zapisuje wartosc bitu przeslanego w prametrze pod aktualna pozycje w buforze.
*/
void BUFFOR::PutBit(uint8 DabBit) {
switch (BufMode) {
case BUF_TRANSFER:
// w srodku bufora
if (BufBitPosp + 1 < BufBitSize) {
Buf[BufBytePosp] = (Buf[BufBytePosp] & ExOne[BufBitPosp % 8]) | (DabBit & One[BufBitPosp % 8]);
++BufBitPosp;
++BitDataCount;
if (!(BufBitPosp % 8)) {
++BufBytePosp;
++DataCount;
}
return;
}
// na ostatniej pozycji
else if(BufBitPosp + 1 == BufBitSize) {
Buf[BufBytePosp] = (Buf[BufBytePosp] & ExOne[BufBitPosp % 8]) | (DabBit & One[BufBitPosp % 8]);
BufBytePosp = 0;
BufBitPosp = 0;
DataCount = BufSize;
BitDataCount = BufBitSize;
BufState = BUF_FULL;
return;
}
else {
BufState = BUF_BAD;
std::vector<string> params(1);
throw err("!BMP2", params);
}
case BUF_WRITEONLY:
// w srodku bufora
if (BufBitPosp + 1 < BufBitSize) {
Buf[BufBytePosp] = (Buf[BufBytePosp] & ExOne[BufBitPosp % 8]) | (DabBit & One[BufBitPosp % 8]);
++BufBitPosp;
++BitDataCount;
if (!(BufBitPosp % 8)) {
++BufBytePosp;
++DataCount;
}
return;
}
// na ostatniej pozycji
else if(BufBitPosp + 1 == BufBitSize) {
Buf[BufBytePosp] = (Buf[BufBytePosp] & ExOne[BufBitPosp % 8]) | (DabBit & One[BufBitPosp % 8]);
// zpisujemy pelny bufor
File.clear();
File.write((char *)Buf,BufSize);
File.flush();
BufBytePosp = 0;
BufBitPosp = 0;
DataCount = 0;
BitDataCount = 0;
return ;
}
else {
BufState = BUF_BAD;
std::vector<string> params(1);
throw err("!BMP2", params);
}
default: {
// nie mozna wysylac w innym trybie na Bufor!!
std::vector<string> params(1);
throw err("!BMP2", params);
}
}
}
/*!
* \brief
* Pobranie jednego bajta z bufora.
*
* \returns
* Zwraca 0xFF lub 0x00.
*
* \throws err()
* Rzuca wyjatek, gdy nastepuje proba wykonania niedozwolonej operacji na buforze.
*
* Zwraca wartosc aktualnego bajtu w buforze.
*/
uint8 BUFFOR::GetByte() {
switch (BufMode) {
case BUF_READONLY:
// w srodku bufora
if (BufBytePosg + 1 < DataCount) {
BufBitPosg += 8;
return Buf[BufBytePosg++];
}
// na ostatniej pozycji danych w buforze
else if (BufBytePosg + 1 == DataCount) {
uint8 Result = Buf[BufBytePosg];
//wczytanie
File.clear();
File.read((char *)Buf,ReadSize);
DataCount = File.gcount();
BitDataCount = 8 * DataCount;
if (!DataCount) {
if (File.eof())
BufState = BUF_EOF;
else {
BufState = BUF_BAD;
return Result;
}
}
BufBytePosg = 0;
BufBitPosg = 0;
return Result;
}
// tu nie powinien buffor nigdy dojsc!
{
std::vector<string> params(1);
throw err("!BMP2", params);
}
case BUF_TRANSFER:
// w srodku bufora
if (BufBytePosg + 1 < DataCount){
BufBitPosg += 8;
return Buf[BufBytePosg++];
}
// na ostatniej pozycji
else if (BufBytePosg + 1 == DataCount) {
uint8 Result = Buf[BufBytePosg];
BufBytePosg = 0;
BufBitPosg = 0;
DataCount = 0;
BitDataCount = 0;
BufState = BUF_EMPTY;
return Result;
}
else {
// nie moze zabraknac danych w Buforze!!
BufState = BUF_BAD;
std::vector<string> params(1);
throw err("!BMP2", params);
}
default: {
// inny tryb niedozwolony
std::vector<string> params(1);
throw err("!BMP2", params);
}
}
}
/*!
* \brief
* Zapis jednego bajtu do bufora.
*
* \param DabByte
* Wartosc zapisywanego bajtu 0xFF lub 0x00.
*
* \throws err()
* Rzuca wyjatek, gdy nastepuje proba wykonania niedozwolonej operacji na buforze.
*
* Zapisuje wartosc bajtu przeslanego w prametrze pod aktualna pozycje w buforze.
*/
void BUFFOR::PutByte(uint8 DabByte) {
switch (BufMode) {
case BUF_TRANSFER:
// w srodku bufora
if (BufBytePosp + 1 < BufSize) {
Buf[BufBytePosp++] = DabByte;
++DataCount;
BitDataCount += 8;
BufBitPosp += 8;
return;
}
// na ostatniej pozycji
else if(BufBytePosp + 1 == BufSize) {
Buf[BufBytePosp] = DabByte;
BufBytePosp = 0;
BufBitPosp = 0;
DataCount = BufSize;
BitDataCount = BufBitSize;
BufState = BUF_FULL;
return;
}
else {
BufState = BUF_BAD;
std::vector<string> params(1);
throw err("!BMP2", params);
}
case BUF_WRITEONLY:
// w srodku bufora
if (BufBytePosp + 1 < BufSize) {
Buf[BufBytePosp++] = DabByte;
++DataCount;
BitDataCount += 8;
BufBitPosp += 8;
}
// na ostatniej pozycji
else if(BufBitPosp + 1 == BufBitSize) {
Buf[BufBytePosp] = DabByte;
// zpisujemy pelny bufor
File.clear();
File.write((char *)Buf,BufSize);
File.flush();
BufBytePosp = 0;
BufBitPosp = 0;
DataCount = 0;
BitDataCount = 0;
return;
}
else {
BufState = BUF_BAD;
std::vector<string> params(1);
throw err("!BMP2", params);
}
default: {
// nie mozna wysylac w innym trybie na Bufor!!
std::vector<string> params(1);
throw err("!BMP2", params);
}
}
}
/*!
* \brief
* Ustawia tryb bufora.
*
* \param DabBufMode
* Okresla nowy stan bufora.
*
* Zmienia stan bufora na ten przyslany w parametrze.
*/
void BUFFOR::SetMode(BUFFOR_MODE DabBufMode) {
BufMode = DabBufMode;
// nie wiadomo w jakim trybie zostaly umieszczone dane wiec trzeba wyzerowac bufor
DataCount = 0;
BitDataCount = 0;
// ustawienie stanu, gdy transfer albo zapis bufor moze przyjac dane
// w przeciwnym razie trzeba najpierw zrobic odczyt
if (BufMode == BUF_TRANSFER || BufMode == BUF_WRITEONLY)
BufState = BUF_GOOD;
else
BufState= BUF_BAD;
}
/*!
* \brief
* Zamkniecie pliku.
*
*/
void BUFFOR::CloseFile() {
BufReset();
File.close();
File.clear();
}
/*!
* \brief
* Zerowanie bufora.
*
* Resetuje bufor i ustawia stan poczatkowy.
*/
void BUFFOR::BufReset() {
File.clear();
FileSize = 0;
DataCount = 0;
BitDataCount = 0;
BufBitPosg = 0;
BufBitPosp = 0;
BufBytePosg = 0;
BufBytePosp = 0;
ReadSize = BUFFOR_SIZE;
BufState = BUF_BAD;
BufMode = BUF_TRANSFER;
}
//**************** "chodzenie po buforze"*******************//
/*!
* \brief
* Ustawienie pozycji w bajtach do odczytu.
*
* \throws err()
* Rzuca wyjatek, gdy nastepuje proba wykonania niedozwolonej operacji na buforze.
*
*/
void BUFFOR::BufByteSeekg(uint32 DabnewPos) {
if (DabnewPos >= 0 && DabnewPos < DataCount) {
BufBytePosg = DabnewPos;
BufBitPosg = DabnewPos * 8;
}
else {
std::vector<string> params(1);
throw err("!BMP2", params);
}
}
/*!
* \brief
* Ustawienie pozycji w bajtach do zapisu.
*
* \throws err()
* Rzuca wyjatek, gdy nastepuje proba wykonania niedozwolonej operacji na buforze.
*
*/
void BUFFOR::BufByteSeekp(uint32 DabnewPos) {
if (DabnewPos >= 0 && DabnewPos < DataCount) {
BufBytePosp = DabnewPos;
BufBitPosp = DabnewPos * 8;
}
else {
std::vector<string> params(1);
throw err("!BMP2", params);
}
}
/*!
* \brief
* Ustawienie pozycji w bitach do odczytu.
*
* \throws err()
* Rzuca wyjatek, gdy nastepuje proba wykonania niedozwolonej operacji na buforze.
*
*/
void BUFFOR::BufBitSeekg(uint32 DabnewPos) {
if (DabnewPos >= 0 && DabnewPos < BitDataCount) {
BufBitPosg = DabnewPos;
BufBytePosg = DabnewPos / 8;
}
else {
std::vector<string> params(1);
throw err("!BMP2", params);
}
}
/*!
* \brief
* Ustawienie pozycji w bitach do zapisu.
*
* \throws err()
* Rzuca wyjatek, gdy nastepuje proba wykonania niedozwolonej operacji na buforze.
*
*/
void BUFFOR::BufBitSeekp(uint32 DabnewPos) {
if (DabnewPos >= 0 && DabnewPos < BitDataCount) {
BufBitPosp = DabnewPos;
BufBytePosp = DabnewPos / 8;
}
else {
std::vector<string> params(1);
throw err("!BMP2", params);
}
}
/*!
* \brief
* Pobranie aktualnej pozycji do odczytu w buforze w bajtach.
*/
const uint32 BUFFOR::BufByteTellg() const {
return BufBytePosg;
}
/*!
* \brief
* Pobranie aktualnej pozycji do zapisu w buforze w bajtach.
*/
const uint32 BUFFOR::BufByteTellp() const {
return BufBytePosp;
}
/*!
* \brief
* Pobranie aktualnej pozycji do odczytu w buforze w bitach.
*/
const uint32 BUFFOR::BufBitTellg() const {
return BufBitPosg;
}
/*!
* \brief
* Pobranie aktualnej pozycji do zapisu w buforze w bitach.
*/
const uint32 BUFFOR::BufBitTellp() const {
return BufBitPosp;
}
/*!
* \brief
* Napelnienie bufora.
*
* \throws err()
* Rzuca wyjatek przy bledach odczytu zapisu.
*
* Odczyt danych z dysku do bufora.
*/
void BUFFOR::Fill() {
switch (BufMode) {
case BUF_READONLY:
File.clear();
File.read((char *)Buf, ReadSize);
DataCount = File.gcount();
BitDataCount = 8 * DataCount ;
if (!DataCount) {
if (File.eof())
BufState = BUF_EOF;
else
BufState = BUF_BAD;
}
BufState = BUF_GOOD;
BufBytePosg = 0;
BufBitPosg = 0;
break;
default: {
std::vector<string> params(1);
throw err("!BMP2", params);
}
}
}
/*!
* \brief
* Oproznienie bufora.
*
* Zapis danych z bufora na dysk.
*
*/
void BUFFOR::Flush() {
switch (BufMode) {
case BUF_WRITEONLY:
File.clear();
File.write((char *)Buf,DataCount);
File.flush();
BufState = BUF_EMPTY;
BufBytePosg = BufBitPosg = 0;
BitDataCount = DataCount = 0;
break;
default: {
std::vector<string> params(1);
throw err("!BMP2", params);
}
}
}
//********************end of class BUFFOR********************//
//********************class BMP_BUFFOR********************//
/*!
* \brief
* Konstruktor klasy BMP_BUFFOR.
*
* BMP_BUFFOR wykonuje inicjalizacjie (zerowanie) bufora.
*/
BMP_BUFFOR::BMP_BUFFOR() {
BmpHeader = 0;
// domyslnie kompresja = 1
Compr = 1;
Seek = uint8 (8 - Compr);
BytePosg = 0;
BytePosp = 0;
BitPosg = 0;
BitPosp = 0;
ModReminder = 0;
ModWidth = 0;
}
/*!
* \brief
* Konstruktor klasy BMP_BUFFOR.
*
* \param DabBmpHeader
* Wskaznik na obiekt BMP_HEADER, przechowujacy informacjie o aktualnej bitmapie.
*
* BMP_BUFFOR wykonuje inicjalizacjie (zerowanie) bufora.
*/
BMP_BUFFOR::BMP_BUFFOR(BMP_HEADER* DabBmpHeader) {
BmpHeader = DabBmpHeader;
Compr = 1;
Seek = uint8 (8 - Compr);
BytePosg = 0;
BytePosp = 0;
BitPosg = 0;
BitPosp = 0;
ReadSize = BUFFOR_SIZE;
ModReminder = 0;
ModWidth = 0;
}
/*!
* \brief
* Pobranie jednego bita z bufora.
*
* \returns
* Zwraca 0xFF lub 0x00.
*
* \throws err()
* Rzuca wyjatek, gdy nastepuje proba wykonania niedozwolonej operacji na buforze.
*
* Zwraca wartosc aktualnego bitu w buforze.
*/
uint8 BMP_BUFFOR::GetBit() {
switch (BufMode) {
case BUF_READONLY: {
// pojawi sie problem gdy ktos ustawi pozycje w bitach na czesc bajtu ktorej nie odczytujemy
// co wtedy, chyba w byte/bit seekach to poprawic
// trzeba zapewnic, ze przy seekowaniu ustawiony będzie tylko bit brany pod uwage podczas kompresji
// i ten bit nie bedzie sie znajdowac w dopelniajacych zerach!!!!!
// w srodku bufora, gdzies przed ostatnim bitem, zatem odczyt uda sie na pewno,
// jesli pobierany bit jest najmlodszym bitem z bajta -
// - nastepuje przesuniecie glowicy o bajt, wtedy sprawdzamy czy nie wystepuja zera dopelniajace
// i czy mozna ewentualnie przesunac
if (BufBitPosg + 1 < BitDataCount) {
uint8 Result;
if (Buf[BufBytePosg] & One[BufBitPosg % 8 ])
Result = BitSet;
else
Result = BitNSet;
++BufBitPosg;
// jesli spelniony to przesuniecie o Seek na pewno sie zmiesci
if (!(BufBitPosg % 8)) {
++BufBytePosg;
BufBitPosg += Seek;
// gdy zwiekszamy pozycje buf w bajtach to trzeba sprawdzic czy nie ma zer dopelniajacych
uint32 ModSeek = (BytePosg + BufBytePosg - BmpHeader->bfOffBits) % ModWidth;
if ((ModSeek + ModReminder) >= ModWidth) {
// czy przesuniecie zmiesci sie w buforze?
if (BufBitPosg + 8 * (ModWidth - ModSeek) < BitDataCount) {
BufBytePosg += ModWidth - ModSeek;
BufBitPosg = 8 * BufBytePosg + Seek;
}
// nie mozna przesucac trzeba wczytac ponownie!
else {
File.clear();
BytePosg += DataCount;
BitPosg = 8 * BytePosg ;
File.seekg(BytePosg);
File.read((char *)Buf, ReadSize);
DataCount = File.gcount();
BitDataCount = 8 * DataCount;
if (!DataCount) {
if (File.eof())
BufState = BUF_EOF;
else
BufState = BUF_BAD;
return Result;
}
// wstepne ustawienie
BufBytePosg = 0;
BufBitPosg = Seek;
// obliczenie czy akurat pierwszy bajte buforu to nie zera dopelniajace
// BufBytePosg == 0
ModSeek = (BytePosg - BmpHeader->bfOffBits) % ModWidth;
// spr czy trzeba przesunac
if ((ModSeek + ModReminder) >= ModWidth) {
// czy przesuniecie zmiesci sie w buforze?
if (BufBitPosg + 8 * (ModWidth - ModSeek) < BitDataCount) {
BufBytePosg += ModWidth - ModSeek;
BufBitPosg = 8 * BufBytePosg + Seek;
}
// nie zmiescilo sie, ale przed chwila wczytywalismy, wiec koniec pliku:
else {
BufState = BUF_EOF;
}
}
}
}
}
return Result;
}
// na ostatniej pozycji, po odczytaniu bitu trzeba wypelnic ponownie bufor
else if (BufBitPosg + 1 == BitDataCount) {
uint8 Result;
if (Buf[BufBytePosg] & One[BufBitPosg % 8 ])
Result = BitSet;
else
Result = BitNSet;
File.clear();
BytePosg += DataCount;
BitPosg = 8 * BytePosg ;
File.seekg(BytePosg);
File.read((char *)Buf,ReadSize);
DataCount = File.gcount();
BitDataCount = 8 * DataCount;
if (!DataCount) {
if (File.eof())
BufState = BUF_EOF;
else
BufState = BUF_BAD;
return Result;
}
// wstepne ustawienie
BufBytePosg = 0;
BufBitPosg = Seek;
// obliczenie czy akurat pierwszy byte buforu to nie zera dopelniajace
uint32 ModSeek = (BytePosg - BmpHeader->bfOffBits) % ModWidth;
if ((ModSeek + ModReminder) >= ModWidth) {
// spr czy mozna przesunac
if (BufBitPosg + 8 * (ModWidth - ModSeek) < BitDataCount) {
BufBytePosg += ModWidth - ModSeek;
BufBitPosg = 8 * BufBytePosg + Seek;
}
// przed chwila wczytywalismy wiec koniec pliku:
else {
BufState = BUF_EOF;
}
}
return Result;
}
std::vector<string> params(1);
throw err("!BMP2", params);
}
default: {
// inny tryb niedozwolony
std::vector<string> params(1);
throw err("!BMP2", params);
}
}
}
/*!
* \brief
* Zapis jednego bita do bufora.
*
* \param DabBit
* Wartosc zapisywanego bita 0xFF lub 0x00.
*
* \throws err()
* Rzuca wyjatek, gdy nastepuje proba wykonania niedozwolonej operacji na buforze.
*
* Zapisuje wartosc bitu przeslanego w prametrze pod aktualna pozycje w buforze.
*/
void BMP_BUFFOR::PutBit(uint8 DabBit) {
switch (BufMode) {
// to bardziej przypomina read tylko ze z zapisujemy przed odczytem
case BUF_READ_WRITE: {
// w srodku bufora
if ((BufBitPosp + 1 < BitDataCount)) {
Buf[BufBytePosp] = (Buf[BufBytePosp] & ExOne[BufBitPosp % 8]) | (DabBit & One[BufBitPosp % 8]);
++BufBitPosp;
// nie zwiekszamy liczebnosci danych, bo dane bitmapy sa juz w buforze!!
if (!(BufBitPosp % 8)) {
++BufBytePosp;
BufBitPosp += Seek;
// gdy zwiekszamy pozycje buf w byteach to trzeba sprawdzic czy nie ma zer dopelniajacych
uint32 ModSeek = (BufBytePosp + BytePosp - BmpHeader->bfOffBits) % ModWidth;
if ((ModSeek + ModReminder) >= ModWidth) {
if (BufBitPosp + 8 * (ModWidth - ModSeek) < BitDataCount) {
BufBytePosp += ModWidth - ModSeek;
BufBitPosp = 8 * BufBytePosp + Seek;
}
// nie mozna przesucac trzeba zapisac i wczytac ponownie
else {
File.clear();
File.seekp(BytePosp, std::ios_base::beg);
File.write((char *)Buf, DataCount);
File.flush();
BytePosp += DataCount;
BitPosp = 8 * BytePosp;
// przygotowanie do odczytu z pozycji w ktora chcemy pisac
File.seekg(BytePosp, std::ios_base::beg);
File.read((char *)Buf, ReadSize);
DataCount = File.gcount();
BitDataCount = 8 * DataCount;
if (!DataCount) {
if (File.eof())
BufState = BUF_EOF;
else
// jakis blad
BufState = BUF_BAD;
std::vector<string> params(1);
throw err("!BMP2", params);
}
// wstepne ustawienie
BufBytePosp = 0;
BufBitPosp = Seek;
// obliczenie czy akurat pierwszy byte buforu to nie zera dopelniajace
// wersja dla BytePosp
ModSeek = (BytePosp - BmpHeader->bfOffBits) % ModWidth;
// przesuniecie, musi sie zmiescic w buforze!!
if ((ModSeek + ModReminder) >= ModWidth) {
// spr czy trzeba przesunac
if (BufBitPosp + 8 * (ModWidth - ModSeek) < BitDataCount) {
BufBytePosp += ModWidth - ModSeek;
BufBitPosp = 8 * BufBytePosp + Seek;
}
// przed chwila wczytywalismy wiec koniec pliku:
else {
BufState = BUF_EOF;
}
}
}
}
}
return ;
}
// na ostatniej pozycji w buforze!
else if (BufBitPosp + 1 == BitDataCount) {
Buf[BufBytePosp] = (Buf[BufBytePosp] & ExOne[BufBitPosp % 8]) | (DabBit & One[BufBitPosp % 8]);
File.clear();
File.seekp(BytePosp, std::ios_base::beg);
File.write((char *)Buf, DataCount);
File.flush();
BytePosp += DataCount;
BitPosp = 8 * BytePosp;
// przygotowanie do odczytu z pozycji w ktora chcemy pisac
File.seekg(BytePosp, std::ios_base::beg);
File.read((char *)Buf,ReadSize);
DataCount = File.gcount();
BitDataCount = 8 * DataCount;
if (!DataCount) {
if (File.eof())
BufState = BUF_EOF;
else
// jakis blad
BufState = BUF_BAD;
}
BufBytePosp = 0;
BufBitPosp = Seek;
// obliczenie czy akurat pierwszy byte buforu to nie zera dopelniajace
// BufBytePosp == 0
uint32 ModSeek = (BytePosp - BmpHeader->bfOffBits) % ModWidth;
// przesuniecie, musi sie zmiescic w buforze!!
if ((ModSeek + ModReminder) >= ModWidth) {
// spr czy trzeba przesunac
if (BufBitPosp + 8 * (ModWidth - ModSeek) + 1 < BitDataCount) {
BufBytePosp += ModWidth - ModSeek;
BufBitPosp = 8 * BufBytePosp + Seek;
}
// przed chwila wczytywalismy wiec koniec pliku:
else {
BufState = BUF_EOF;
}
}
return;
}
// tu nie powinien sie nigdy znalezc!!
std::vector<string> params(1);
throw err("!BMP2", params);
}
default: {
// nie mozna wysylac w innym trybie na Bufor!!
std::vector<string> params(1);
throw err("!BMP2", params);
}
}
}
/*!
* \brief
* Zerowanie bufora.
*
* Resetuje bufor i ustawia stan poczatkowy.
*/
void BMP_BUFFOR::BufReset() {
BUFFOR::BufReset();
BufMode = BUF_READONLY;
BitPosg = 0;
BitPosp = 0;
BytePosg = 0;
BytePosp = 0;
Compr = 1;
Seek = uint8 (8 - Compr);
ModReminder = 0;
ModWidth = 0;
}
/*!
* \brief
* Ustawienie noewej kompresji.
*
* \param Dabcompr
* Nowa kompresja, dozwolone wartosci od 1 do 7.
*
*/
void BMP_BUFFOR::SetCompr(uint8 Dabcompr) {
Compr = Dabcompr;
Seek = uint8 (8 - Compr);
}
/*!
* \brief
* Ustawia wielkosc blokow doczytywanych z dysku.
*
* \param DabNewSize
* Ilosc danych w bajtach doczytywanych z dysku przez bufor .
*
*/
void BUFFOR::SetReadSize(uint32 DabNewSize) {
if (DabNewSize <= BufSize)
ReadSize = DabNewSize;
}
/*!
* \brief
* Ustawienie glowicy odczytujacej na okreslony bit.
*
* \param DabnewPos
* Przedstawia ilosc bitow.
*
* \param DabSeekWay
* Wartosci: BEGINING albo FORWARD.
*
* \throws err()
* Rzuca wyjatek przy bledach odczytu zapisu.
*
* Gdy parametr == BEGINING, ustawiamy pozycje na bit przyslany w parametrze liczac od poczatku pliku. Gdy parametr == FORWARD, ustawiamy przesuwamy pozycje o DabnewPos w przod.
*
*/
void BMP_BUFFOR::BitSeekg(uint64 DabnewPos, SEEKWAY DabSeekWay) {
switch (DabSeekWay) {
case BEGINING: {
// czy dane w buforze? BitDataCount oznacza ilosc wszystkich danych
// nie tylko tych uzytecznych
if (DabnewPos >= BitPosg && DabnewPos < BitDataCount + BitPosg ) {
BufBytePosg = uint32(DabnewPos / 8) - BytePosg;
BufBitPosg = uint32(DabnewPos - BitPosg);
}
else {
BytePosg = uint32 (DabnewPos / 8);
BitPosg = 8 * BytePosg;
BufBitPosg = uint32 (DabnewPos % 8);
BufBytePosg = 0;
Fill();
}
break;
}
case FORWARD: {
if (DabnewPos + BitPosg < BitDataCount) {
BufBitPosg += (uint32) DabnewPos;
BufBytePosg += uint32 (DabnewPos /8);
}
else {
BytePosg += BufBytePosg + (uint32) (DabnewPos / 8);
BitPosg += BufBitPosg + 8 * BytePosg;
BufBitPosg = uint32 (DabnewPos % 8);
BufBytePosg = 0;
Fill();
}
break;
}
default: {
std::vector<string> params(1);
throw err("!BMP2", params);
}
}
}
/*!
* \brief
* Ustawienie glowicy zapisujacej na okreslony bit.
*
* \param DabnewPos
* Przedstawia ilosc bitow.
*
* \param DabSeekWay
* Wartosci: BEGINING albo FORWARD.
*
* \throws err()
* Rzuca wyjatek przy bledach odczytu zapisu.
*
* Gdy parametr == BEGINING, ustawiamy pozycje na bit przyslany w parametrze liczac od poczatku pliku. Gdy parametr == FORWARD, ustawiamy przesuwamy pozycje o DabnewPos w przod.
*
*/
void BMP_BUFFOR::BitSeekp(uint64 DabnewPos, SEEKWAY DabSeekWay) {
switch (DabSeekWay) {
case BEGINING: {
// czy dane w buforze?
if (DabnewPos >= BitPosp && DabnewPos < BitDataCount + BitPosp) {
BufBytePosp = uint32(DabnewPos / 8 - BytePosp);
BufBitPosp = uint32(DabnewPos - BitPosp);
}
else {
// zapisanie bufora
Flush();
BytePosp = uint32(DabnewPos / 8);
File.seekp(BytePosp, std::ios_base::beg);
BitPosp = 8 * BytePosp;
BufBytePosp = 0;
BufBitPosp = uint32(DabnewPos % 8);
// aby pisac do bufora musza byc tam dane bitmapy
Fill();
}
break;
}
case FORWARD: {
if (DabnewPos + BitPosp < BitDataCount) {
BufBitPosp += (uint32) DabnewPos;
BufBytePosp += (uint32) (DabnewPos / 8);
}
else {
BytePosp += BufBytePosp + (uint32) (DabnewPos / 8);
File.seekp(BytePosp, std::ios_base::beg);
BitPosp = 8 * BytePosp;
BufBytePosp = 0;
BufBitPosp = (uint32) (DabnewPos % 8);
Fill();
}
break;
}
default: {
std::vector<string> params(1);
throw err("!BMP2", params);
}
}
}
/*!
* \brief
* Wielkosc pliku w bitmapie.
*
* \param DabSize
* Wielkosc rzeczywistego pliku w BITACH.
*
* \param DabCurPos
* Aktualna pozycja w buforze w BITACH.
*
* \returns
* Zwraca wielkosc przyslanego pliku w bitmapie w bitach.
*
* Konwertuje wielkosc pliku w bitach na wielkosc tego pliku w bitach ALE W BITMAPIE. Bierze pod uwage kompresje oraz ilosc zer wyrownujacych.
*
*/
uint64 BMP_BUFFOR::FileSizeInBmp(uint64 DabSize, uint64 DabCurPos) {
if (!DabSize)
return 0;
// wielkosc przesunieca
// podstawowe przesuniecie - calkowity rozmiar pliku w bitmapie (nie uwzgledniajacy dopelniajacych zer):
uint64 NewSize = (DabSize / Compr) * 8 + DabSize % Compr;
if (DabCurPos % 8 + DabSize % Compr >= 8) {
NewSize += Seek;
NewSize += DabSize % Compr + DabCurPos % 8;
NewSize -= 8;
}
// dodanie zer!!
uint64 ModSeek = 8 * ModReminder * ( NewSize / (24 * BmpHeader->biWidth));
// >= czy samo ?>
if ((DabCurPos - 8 * BmpHeader->bfOffBits) % (8 * ModWidth) + NewSize % (24 * BmpHeader->biWidth) >= 24 * BmpHeader->biWidth ) {
NewSize+= 8 * ModReminder; //ModWidth - NewSize % (24 * BmpHeader->biWidth);
}
return (NewSize + ModSeek);
}
/*!
* \brief
* Pobranie aktualnej pozycji do odczytu w buforze w bajtach.
*/
const uint32 BMP_BUFFOR::ByteTellg() const {
return BytePosg + BufBytePosg;
}
/*!
* \brief
* Pobranie aktualnej pozycji do zapisu w buforze w bajtach.
*/
const uint32 BMP_BUFFOR::ByteTellp() const {
return BytePosp + BufBytePosp;
}
/*!
* \brief
* Pobranie aktualnej pozycji do odczytu w buforze w bitach.
*/
const uint64 BMP_BUFFOR::BitTellg() const {
return BitPosg + BufBitPosg;
}
/*!
* \brief
* Pobranie aktualnej pozycji do zapisu w buforze w bitach.
*/
const uint64 BMP_BUFFOR::BitTellp() const{
return BitPosp + BufBitPosp;
}
/*!
* \brief
* Napelnienie bufora.
*
* \throws err()
* Rzuca wyjatek przy bledach odczytu zapisu.
*
* Odczyt danych z dysku do bufora. Wersja niemodyfikujaca pozycji glowic - np. gdy bedzie skok do jakiejs pozycji to nalezy zaczac czytac od tego ustawionego bita a nie od pierwszego w kompresjiUstawienia glowic zaleza od trybu.
*/
void BMP_BUFFOR::Fill() {
switch (BufMode) {
case BUF_READONLY:
// pierwszy odczyt - z dokladnie tego okreslonego miejsca
File.clear();
File.seekg(BytePosg,std::ios_base::beg);
File.read((char *)Buf, ReadSize);
DataCount = File.gcount();
BitDataCount = 8 * DataCount ;
if (!DataCount) {
if (File.eof())
BufState = BUF_EOF;
else
BufState = BUF_BAD;
// wyjatek?
return;
}
BufState = BUF_GOOD;
break;
// pierwszy odczyt, bez zapisu
case BUF_READ_WRITE:
File.clear();
// czytamy z pozycji gdzie bedziemy zapisuwac
File.seekg(BytePosp, std::ios_base::beg);
File.read((char *)Buf,ReadSize);
DataCount = File.gcount();
BitDataCount = 8 * DataCount ;
if (!DataCount) {
if (File.eof())
BufState = BUF_EOF;
else
BufState = BUF_BAD;
// wyjatek?
return;
}
BufState = BUF_GOOD;
break;
default: {
std::vector<string> params(1);
throw err("!BMP2", params);
}
}
}
/*!
* \brief
* Oproznienie bufora.
*
* \throws err()
* Rzuca wyjatek przy bledach odczytu zapisu.
*
* Zapis danych z bufora na dysk.
*/
void BMP_BUFFOR::Flush() {
switch (BufMode) {
case BUF_READ_WRITE:
File.clear();
File.seekp(BytePosp,std::ios_base::beg);
File.write((char *)Buf,DataCount);
DataCount = 0;
BitDataCount = 0;
File.flush();
BufState = BUF_EMPTY;
break;
default:
std::vector<string> params(1);
throw err("!BMP2", params);
}
}
//********************end of class BMP_BUFFOR********************//
}//********************end of namespace bmp********************//
| [
"konrad.balys@019b6672-ce2e-0410-a4f6-31e0795bab1a"
]
| [
[
[
1,
1265
]
]
]
|
69776ce116f27c009ffb3a6391cfe1c18087d69a | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/Dependencies/Xerces/include/xercesc/dom/deprecated/NodeListImpl.hpp | 344822740df836132a7836f81bf768c0a29864fe | []
| 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,574 | hpp | #ifndef NodeListImpl_HEADER_GUARD_
#define NodeListImpl_HEADER_GUARD_
/*
* Copyright 1999-2002,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: NodeListImpl.hpp 176026 2004-09-08 13:57:07Z peiyongz $
*/
//
// This file is part of the internal implementation of the C++ XML DOM.
// It should NOT be included or used directly by application programs.
//
// Applications should include the file <xercesc/dom/deprecated/DOM.hpp> for the entire
// DOM API, or DOM_*.hpp for individual DOM classes, where the class
// name is substituded for the *.
//
#include <xercesc/util/XercesDefs.hpp>
#include "RefCountedImpl.hpp"
XERCES_CPP_NAMESPACE_BEGIN
class NodeImpl;
class DEPRECATED_DOM_EXPORT NodeListImpl : public RefCountedImpl
{
protected:
NodeListImpl();
public:
virtual ~NodeListImpl();
virtual NodeImpl * item(unsigned int index) = 0;
virtual unsigned int getLength() = 0;
};
XERCES_CPP_NAMESPACE_END
#endif
| [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
]
| [
[
[
1,
54
]
]
]
|
0b49478f7d719ba3f5efabc6a395e9da2857eb8a | 7bfc60c56b4c12957c53657d0549a136b6e6cdb2 | /array.cpp | ebc102296d7c1ba2c629207d1356d407180d53ac | [
"BSL-1.0"
]
| permissive | bolero-MURAKAMI/CEL---ConstExpr-Library | 867ef5656ff531ececaf5747594f8b948d872f34 | 1ad865dd8845c63e473a132870347e913ff91c1c | refs/heads/master | 2021-01-17T22:03:25.021662 | 2011-11-26T12:59:00 | 2011-11-26T12:59:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,207 | cpp | // Copyright (C) 2011 RiSK (sscrisk)
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include<cassert>
#include<sscrisk/cel/array.hpp>
int main()
{
using sscrisk::cel::array;
// fill
{
array<int, 10> a{{64}};
a.fill(42);
assert(a[0] == 42);
assert(a[9] == 42);
}
// swap
{
array<int, 2> a{{0, 1}};
array<int, 2> b{{1, 2}};
std::swap(a, b);
assert(a[0] == 1);
assert(a[1] == 2);
assert(b[0] == 0);
assert(b[1] == 1);
}
// begin
{
{
array<int, 2> a{{0, 1}};
auto test = a.begin();
assert(*test == 0);
}
{
static constexpr array<int, 2> a{{0, 1}};
constexpr auto test = a.begin();
assert(*test == 0);
}
}
// end
{
{
array<int, 2> a{{0, 1}};
auto test = a.end();
assert(test - a.begin() == 2);
}
{
static constexpr array<int, 2> a{{0, 1}};
constexpr auto test = a.end();
assert(test - a.begin() == 2);
}
}
// rbegin
{
{
array<int, 2> a{{0, 1}};
auto test = a.rbegin();
assert(*test == 1);
}
{
array<int, 2> const a{{0, 1}};
auto test = a.rbegin();
assert(*test == 1);
}
}
// rend
{
{
array<int, 2> a{{0, 1}};
auto test = a.rend();
assert(test - a.rbegin() == 2);
}
{
array<int, 2> const a{{0, 1}};
auto test = a.rend();
assert(test - a.rbegin() == 2);
}
}
// cbegin
{
{
array<int, 2> a{{0, 1}};
auto test = a.cbegin();
assert(*test == 0);
}
{
static constexpr array<int, 2> a{{0, 1}};
auto test = a.cbegin();
assert(*test == 0);
}
}
// cend
{
{
array<int, 2> a{{0, 1}};
auto test = a.cend();
assert(test - a.cbegin() == 2);
}
{
static constexpr array<int, 2> a{{0, 1}};
constexpr auto test = a.cend();
assert(test - a.cbegin() == 2);
}
}
// crbegin
{
{
array<int, 2> a{{0, 1}};
auto test = a.crbegin();
assert(*test == 1);
}
{
array<int, 2> const a{{0, 1}};
auto test = a.crbegin();
assert(*test == 1);
}
}
// crend
{
{
array<int, 2> a{{0, 1}};
auto test = a.crend();
assert(test - a.crbegin() == 2);
}
{
array<int, 2> const a{{0, 1}};
auto test = a.crend();
assert(test - a.crbegin() == 2);
}
}
// size
{
constexpr array<int, 0> a{{}};
constexpr auto test1 = a.size();
assert(test1 == 0);
constexpr array<int, 1> b{{}};
constexpr auto test2 = b.size();
assert(test2 == 1);
}
// max_size
{
constexpr array<int, 0> a{{}};
constexpr auto test1 = a.max_size();
assert(test1 == 0);
constexpr array<int, 2> b{{}};
constexpr auto test2 = b.max_size();
assert(test2 == 2);
}
// empty
{
constexpr array<int, 0> a{{}};
constexpr auto test1 = a.empty();
assert(test1 == true);
constexpr array<int, 3> b{{}};
constexpr auto test2 = b.empty();
assert(test2 == false);
}
// operator[]
{
{
array<int, 1> a{{42}};
auto test = a[0];
assert(test == 42);
}
{
constexpr array<int, 2> a{{42, 64}};
constexpr auto test1 = a[0];
assert(test1 == 42);
constexpr auto test2 = a[1];
assert(test2 == 64);
}
}
// at
{
{
array<int, 1> a{{42}};
auto test = a.at(0);
assert(test == 42);
try
{
auto& test = a.at(2);
assert(!&test);
}
catch(std::out_of_range const &)
{}
}
{
array<int, 2> const a{{42, 64}};
auto test1 = a.at(0);
assert(test1 == 42);
auto test2 = a.at(1);
assert(test2 == 64);
try
{
auto& test = a.at(3);
assert(!&test);
}
catch(std::out_of_range)
{}
}
}
// front
{
{
array<int, 2> a{{42, 64}};
auto test = a.front();
assert(test == 42);
}
{
constexpr array<int, 2> a{{42, 64}};
constexpr auto test = a.front();
assert(test == 42);
}
}
// back
{
{
array<int, 2> a{{42, 64}};
auto test = a.back();
assert(test == 64);
}
{
constexpr array<int, 2> a{{42, 64}};
constexpr auto test = a.back();
assert(test == 64);
}
}
// data
{
{
array<int, 2> a{{42, 64}};
auto test = a.data();
assert(*test == 42);
}
{
static constexpr array<int, 2> a{{42, 64}};
constexpr auto test = a.data();
assert(*test == 42);
}
}
// operator==
{
{
array<int, 0> a, b;
bool test = a == b;
assert(test == true);
}
{
array<int, 1> a{{42}}, b{{42}};
bool test = a == b;
assert(test == true);
}
{
array<int, 1> a{{42}}, b{{64}};
bool test = a == b;
assert(test == false);
}
{
static constexpr array<int, 0> a{{}}, b{{}};
constexpr bool test = a == b;
assert(test == true);
}
{
static constexpr array<int, 1> a{{42}}, b{{42}};
constexpr bool test = a == b;
assert(test == true);
}
{
static constexpr array<int, 1> a{{42}}, b{{64}};
constexpr bool test = a == b;
assert(test == false);
}
}
// operator!=
{
{
array<int, 0> a, b;
bool test = a != b;
assert(test == false);
}
{
array<int, 1> a{{42}}, b{{42}};
bool test = a != b;
assert(test == false);
}
{
array<int, 1> a{{42}}, b{{64}};
bool test = a != b;
assert(test == true);
}
{
static constexpr array<int, 0> a{{}}, b{{}};
constexpr bool test = a != b;
assert(test == false);
}
{
static constexpr array<int, 1> a{{42}}, b{{42}};
constexpr bool test = a != b;
assert(test == false);
}
{
static constexpr array<int, 1> a{{42}}, b{{64}};
constexpr bool test = a != b;
assert(test == true);
}
}
// operator<
{
{
array<int, 0> a, b;
bool test = a < b;
assert(test == false);
}
{
array<int, 1> a{{42}}, b{{42}};
bool test = a < b;
assert(test == false);
}
{
array<int, 1> a{{42}}, b{{64}};
bool test = a < b;
assert(test == true);
}
{
array<int, 1> a{{64}}, b{{42}};
bool test = a < b;
assert(test == false);
}
{
static constexpr array<int, 0> a{{}}, b{{}};
constexpr bool test = a < b;
assert(test == false);
}
{
static constexpr array<int, 1> a{{42}}, b{{42}};
constexpr bool test = a < b;
assert(test == false);
}
{
static constexpr array<int, 1> a{{42}}, b{{64}};
constexpr bool test = a < b;
assert(test == true);
}
{
static constexpr array<int, 1> a{{64}}, b{{42}};
constexpr bool test = a < b;
assert(test == false);
}
}
// operator>
{
{
array<int, 0> a, b;
bool test = a > b;
assert(test == false);
}
{
array<int, 1> a{{42}}, b{{42}};
bool test = a > b;
assert(test == false);
}
{
array<int, 1> a{{42}}, b{{64}};
bool test = a > b;
assert(test == false);
}
{
array<int, 1> a{{64}}, b{{42}};
bool test = a > b;
assert(test == true);
}
{
static constexpr array<int, 0> a{{}}, b{{}};
constexpr bool test = a > b;
assert(test == false);
}
{
static constexpr array<int, 1> a{{42}}, b{{42}};
constexpr bool test = a > b;
assert(test == false);
}
{
static constexpr array<int, 1> a{{42}}, b{{64}};
constexpr bool test = a > b;
assert(test == false);
}
{
static constexpr array<int, 1> a{{64}}, b{{42}};
constexpr bool test = a > b;
assert(test == true);
}
}
// operator<=
{
{
array<int, 0> a, b;
bool test = a <= b;
assert(test == true);
}
{
array<int, 1> a{{42}}, b{{42}};
bool test = a <= b;
assert(test == true);
}
{
array<int, 1> a{{42}}, b{{64}};
bool test = a <= b;
assert(test == true);
}
{
array<int, 1> a{{64}}, b{{42}};
bool test = a <= b;
assert(test == false);
}
{
static constexpr array<int, 0> a{{}}, b{{}};
constexpr bool test = a <= b;
assert(test == true);
}
{
static constexpr array<int, 1> a{{42}}, b{{42}};
constexpr bool test = a <= b;
assert(test == true);
}
{
static constexpr array<int, 1> a{{42}}, b{{64}};
constexpr bool test = a <= b;
assert(test == true);
}
{
static constexpr array<int, 1> a{{64}}, b{{42}};
constexpr bool test = a <= b;
assert(test == false);
}
}
// operator>=
{
{
array<int, 0> a, b;
bool test = a >= b;
assert(test == true);
}
{
array<int, 1> a{{42}}, b{{42}};
bool test = a >= b;
assert(test == true);
}
{
array<int, 1> a{{42}}, b{{64}};
bool test = a >= b;
assert(test == false);
}
{
array<int, 1> a{{64}}, b{{42}};
bool test = a >= b;
assert(test == true);
}
{
static constexpr array<int, 0> a{{}}, b{{}};
constexpr bool test = a >= b;
assert(test == true);
}
{
static constexpr array<int, 1> a{{42}}, b{{42}};
constexpr bool test = a >= b;
assert(test == true);
}
{
static constexpr array<int, 1> a{{42}}, b{{64}};
constexpr bool test = a >= b;
assert(test == false);
}
{
static constexpr array<int, 1> a{{64}}, b{{42}};
constexpr bool test = a >= b;
assert(test == true);
}
}
// tuple_size
{
static_assert(std::tuple_size<array<int, 0> >::value == 0, "");
static_assert(std::tuple_size<array<long, 1> >::value == 1, "");
static_assert(std::tuple_size<array<unsigned, 2> >::value == 2, "");
}
// tuple_element
{
static_assert(std::is_same<std::tuple_element<0, array<int, 1>>::type, int>::value, "");
static_assert(std::is_same<std::tuple_element<0, array<long, 1>>::type, long>::value, "");
static_assert(std::is_same<std::tuple_element<0, array<unsigned, 1>>::type, unsigned>::value, "");
}
// get
{
{
array<int, 1> a{{42}};
int& test = std::get<0>(a);
assert(test == 42);
}
{
array<int, 1> a{{42}};
int&& test = std::get<0>(std::move(a));
assert(test == 42);
}
{
static constexpr array<int, 1> a{{42}};
constexpr int const & test = std::get<0>(a);
assert(test == 42);
}
}
}
| [
"[email protected]"
]
| [
[
[
1,
512
]
]
]
|
a9be2fd05fed9ce58de747f0512868a42e6e2532 | d6eba554d0c3db3b2252ad34ffce74669fa49c58 | /Source/Objects/enemyObj.h | 64fbbd81ce0c0d9a89bc2251d9d16d051e241b76 | []
| no_license | nbucciarelli/Polarity-Shift | e7246af9b8c3eb4aa0e6aaa41b17f0914f9d0b10 | 8b9c982f2938d7d1e5bd1eb8de0bdf10505ed017 | refs/heads/master | 2016-09-11T00:24:32.906933 | 2008-09-26T18:01:01 | 2008-09-26T18:01:01 | 3,408,115 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 561 | h | #pragma once
#include "actorObj.h"
enum enemyTypes { ET_SPIDER, ET_TURRET, ET_BOSS, ET_COUNT, ET_SCORE, ET_INV};
class enemyObj : public actorObj
{
protected:
int enemyType, m_nImageID, m_nExpX, m_nExpY;
bool m_bDied;
int m_nHP;
public:
enemyObj(int type = ET_SPIDER);
~enemyObj();
void update(float dt);
void render();
int getEnemyType() const { return enemyType; }
int getHP() {return m_nHP;}
void setEnemyType(int value) { enemyType = value; }
virtual bool checkCollision(baseObj* obj, polyCollision* result = NULL);
}; | [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
4
],
[
6,
9
],
[
13,
16
],
[
19,
19
],
[
21,
24
]
],
[
[
5,
5
],
[
10,
12
],
[
17,
18
],
[
20,
20
]
]
]
|
733b20dedf4e2fb147fd10f973a50f12a21495de | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Targets/MapLib/Shared/src/MapProjection.cpp | 7d12f1b9f8f33d38e28bb8fd996234f36596c867 | [
"BSD-3-Clause"
]
| permissive | ravustaja/Wayfinder-S60-Navigator | ef506c418b8c2e6498ece6dcae67e583fb8a4a95 | 14d1b729b2cea52f726874687e78f17492949585 | refs/heads/master | 2021-01-16T20:53:37.630909 | 2010-06-28T09:51:10 | 2010-06-28T09:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,912 | cpp | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "MapProjection.h"
#include "PixelBox.h"
#define TOP_LAT 912909609
#define BOTTOM_LAT -912909609
using namespace std;
MapProjection::
MapProjection() : TransformMatrix(),
m_screenSize(100,100),
m_dpiCorrectionFactor( 1 )
{
m_angle = 0.0;
MC2Coordinate lower( 664609150, 157263143 );
MC2Coordinate upper( 664689150, 157405144 );
MC2BoundingBox bbox(lower, upper);
setBoundingBox(bbox);
}
MapProjection::
MapProjection(const MC2Coordinate& centerCoord,
int screenX, int screenY, double scale,
double angle) : TransformMatrix(), m_centerCoord(centerCoord),
m_screenSize(screenX, screenY),
m_scale(scale),
m_angle(angle),
m_dpiCorrectionFactor( 1 )
{
}
void
MapProjection::updateBBox()
{
// static const double mc2scaletometer = 6378137.0*2.0*
// 3.14159265358979323846 / 4294967296.0;
// static const float meterstomc2scale = 1.0 / mc2scaletometer;
pair<float,float> widthAndHeight = getWidthAndHeight();
const float width = widthAndHeight.first;
const float height = widthAndHeight.second;
{
const int32 centerLat = getCenter().lat;
const float halfHeight = height * 0.5;
const int32 intHalfHeight = int32( halfHeight );
if ( halfHeight + centerLat > ( MAX_INT32 / 2 ) ) {
m_bbox.setMaxLat( MAX_INT32 / 2 );
} else {
m_bbox.setMaxLat( centerLat + intHalfHeight );
}
if ( centerLat - halfHeight < ( MIN_INT32 / 2 ) ) {
m_bbox.setMinLat( MIN_INT32 / 2 );
} else {
m_bbox.setMinLat( centerLat - intHalfHeight );
}
m_bbox.updateCosLat();
}
{
if ( width >= MAX_UINT32 - 1) {
m_bbox.setMinLon( MIN_INT32 );
m_bbox.setMaxLon( MAX_INT32 );
} else {
int32 intWidth = int32(width * 0.5 );
int32 centerLon = getCenter().lon;
m_bbox.setMinLon( centerLon - intWidth );
m_bbox.setMaxLon( centerLon + intWidth );
}
}
}
void
MapProjection::updateTransformMatrix()
{
// Constant forever
static const float mc2scaletometer = 6378137.0*2.0*
3.14159265358979323846 / 4294967296.0;
static const float meterstomc2scale = 1.0 / mc2scaletometer;
float radAngle = getAngle() / 180 * M_PI;
float maxScale = getCosLat( m_centerCoord.lat) * float(MAX_UINT32-1000) / (
( fabs( m_screenSize.getX() *
meterstomc2scale * cos(radAngle) ) +
fabs( m_screenSize.getY() *
meterstomc2scale * sin(radAngle) ) ) );
m_scale = MIN( (float)m_scale, maxScale );
const double invScale = 1.0/m_scale;
const double mc2scale = mc2scaletometer * invScale;
updateBBox();
TransformMatrix::updateMatrix( m_angle, mc2scale, m_centerCoord,
m_screenSize.getX(),
m_screenSize.getY() );
}
float64
MapProjection::getPixelScaleFromBBoxAndSize( int screenXSize,
int screenYSize,
MC2BoundingBox& bbox )
{
static const double mc2scaletometer = 6378137.0*2.0*
3.14159265358979323846 / 4294967296.0;
// Strech out the bbox to fit the screen size.
// This is copied from GfxUtility. I don't want that dependency
// so I have copied it here. I might want to change it though.
int32 minLat = bbox.getMinLat();
int32 minLon = bbox.getMinLon();
int32 maxLat = bbox.getMaxLat();
int32 maxLon = bbox.getMaxLon();
int width = screenXSize;
int height = screenYSize;
// width and height should have same proportions as
// bbox.width and bbox.height
float64 bboxHeight = bbox.getHeight();
float64 bboxWidth = bbox.getWidth();
if ( bboxHeight == 0.0 ) {
bboxHeight = 1.0;
}
if ( bboxWidth == 0.0 ) {
bboxWidth = 1.0;
}
float64 factor = bboxHeight / bboxWidth * width / height;
if ( factor < 1 ) {
// Compensate for that the display is higher than the bbox
// height = uint16( height * factor );
int32 extraHeight =
int32( rint( ( (bboxHeight / factor ) -
bboxHeight ) / 2 ) );
minLat -= extraHeight;
maxLat += extraHeight;
} else {
// Compensate for that the display is wider than the bbox
// width = uint16( width / factor );
uint32 lonDiff = bbox.getLonDiff();
if ( lonDiff == 0 ) {
lonDiff = 1;
}
int32 extraWidth =
int32( rint( ( (lonDiff * factor ) -
lonDiff ) / 2 ) );
minLon -= extraWidth;
maxLon += extraWidth;
bbox.setMinLon( minLon );
bbox.setMaxLon( maxLon );
}
bbox.setMinLat( MAX( minLat, (int32) BOTTOM_LAT ) );
bbox.setMaxLat( MIN( maxLat, (int32) TOP_LAT ) );
bbox.setMinLon( minLon );
bbox.setMaxLon( maxLon );
float64 scale =
double(bbox.getHeight() * mc2scaletometer) /
screenYSize; // unit meters map / pixel
// Ugglefix.
if ( scale < 0 || scale > 16000.0 ) {
scale = 16000.0;
}
return scale;
}
MC2BoundingBox
MapProjection::setBoundingBox(const MC2BoundingBox& inbbox)
{
MC2BoundingBox bbox(inbbox);
// Set the scale
m_scale = getPixelScaleFromBBoxAndSize( m_screenSize.getX(),
m_screenSize.getY(),
bbox );
// Save the corner
setCenter( bbox.getCenter() );
return bbox;
}
pair<float,float>
MapProjection::getWidthAndHeight() const
{
static const double mc2scaletometer = 6378137.0*2.0*
3.14159265358979323846 / 4294967296.0;
static const float meterstomc2scale = 1.0 / mc2scaletometer;
const float radAngle = ( getAngle() ) / 180.0 * M_PI;
const float scale = getPixelScale() * meterstomc2scale;
const float b = m_screenSize.getX() * scale;
const float h = m_screenSize.getY() * scale;
const float width =
( fabs( b * cos(radAngle) ) +
fabs( h * sin(radAngle) ) ) / m_cosLat;
const float height =
fabs( b * sin(radAngle) ) +
fabs( h * cos(radAngle) );
return pair<float,float>(width,height);
}
void
MapProjection::getDrawingBBoxes( vector<MC2BoundingBox>& outBoxes ) const
{
pair<float,float> widthAndHeight = getWidthAndHeight();
const float height = widthAndHeight.second;
// Height
MC2BoundingBox bbox;
{
const int32 centerLat = getCenter().lat;
const float halfHeight = height * 0.5 ;
const int32 intHalfHeight = int32( halfHeight );
if ( halfHeight + centerLat > ( MAX_INT32 / 2 ) ) {
bbox.setMaxLat( MAX_INT32 / 2 );
} else {
bbox.setMaxLat( centerLat + intHalfHeight );
}
if ( centerLat - halfHeight < ( MIN_INT32 / 2 ) ) {
bbox.setMinLat( MIN_INT32 / 2 );
} else {
bbox.setMinLat( centerLat - intHalfHeight );
}
bbox.updateCosLat();
}
// Widths
{
float width = MIN( widthAndHeight.first, float(MAX_UINT32) );
int32 centerLon = getCenter().lon;
int32 curMinLon = int32(int64(centerLon) - int64(width / 2) );
// Add bounding boxes until there is no width left
while ( width > 0.0 ) {
outBoxes.push_back( bbox );
MC2BoundingBox& curBox = outBoxes.back();
int32 curWidth = int32( MIN( width, float( MAX_INT32 / 4 ) ) );
if ( curWidth == 0 ) {
outBoxes.pop_back();
break;
}
curBox.setMinLon( curMinLon );
curBox.setMaxLon( curMinLon + curWidth );
if ( curBox.getMinLon() > curBox.getMaxLon() ) {
curBox.setMaxLon( MAX_INT32 );
curMinLon = MIN_INT32;
width -= ( curBox.getMaxLon() - curBox.getMinLon() );
} else {
curMinLon += curWidth;
width -= curWidth;
}
}
}
}
double
MapProjection::setPixelScale(double scale)
{
double oldScale = m_scale;
#ifdef ENABLE_MAPPERFORMANCE_DEBUGGING
if ( scale != m_scale ) {
// Truncate the scale so it will be easier to
// reproduce the same scale level.
double rintScale = rint( scale );
if ( rintScale != rint( m_scale ) ) {
m_scale = rintScale;
} else if ( scale < m_scale ) {
m_scale = rintScale - 1;
} else {
m_scale = rintScale + 1;
}
}
#else
m_scale = scale;
#endif
const double minScale = 0.1;
const double maxScale = 16000.0;
if ( m_scale < minScale ) {
m_scale = minScale;
} else if ( m_scale > maxScale ) {
m_scale = maxScale;
}
if ( m_scale != oldScale ) {
updateTransformMatrix();
}
return m_scale;
}
double
MapProjection::getPixelScale() const
{
return m_scale;
}
void
MapProjection::setDPICorrectionFactor( uint32 factor )
{
m_dpiCorrectionFactor = factor;
}
uint32
MapProjection::getDPICorrectionFactor() const
{
return m_dpiCorrectionFactor;
}
double
MapProjection::setDPICorrectedScale( double scale )
{
setPixelScale( scale / double( getDPICorrectionFactor() ) );
return getDPICorrectedScale();
}
double
MapProjection::getDPICorrectedScale() const
{
double scale = getPixelScale() * double( getDPICorrectionFactor() );
if ( scale > 16000.0 ) {
scale = 16000.0;
}
return scale;
}
double
MapProjection::zoom(double factor)
{
setPixelScale( factor * getPixelScale() );
return m_scale;
}
double
MapProjection::zoom(double factor,
const MC2Coordinate& zoomCoord,
const MC2Point& zoomPoint )
{
double newScale = zoom( factor );
setPoint( zoomCoord, zoomPoint );
return newScale;
}
void
MapProjection::setPixelBox( const MC2Point& oneCorner,
const MC2Point& otherCorner )
{
PixelBox pixBox( oneCorner, otherCorner );
MC2BoundingBox bbox;
for( int i = 0; i < 4; ++i ) {
MC2Coordinate tmpCoord;
inverseTranformUsingCosLat( tmpCoord, pixBox.getCorner(i) );
bbox.update( tmpCoord );
}
double oldangle = m_angle;
setAngle(0);
setBoundingBox( bbox );
setAngle( oldangle );
}
void
MapProjection::move(int deltaX,
int deltaY )
{
// Translate the screen coordinates into lat/lon.
MC2Coordinate center;
inverseTranformCosLatSupplied(
center,
deltaX + (m_screenSize.getX() >> 1),
deltaY + (m_screenSize.getY() >> 1),
getCosLat( m_centerCoord.lat ) );
setCenter( center );
}
void
MapProjection::setCenter(const MC2Coordinate& newCenter)
{
m_centerCoord = newCenter;
if ( m_centerCoord.lat > TOP_LAT ) {
m_centerCoord.lat = TOP_LAT;
} else if ( m_centerCoord.lat < BOTTOM_LAT ) {
m_centerCoord.lat = BOTTOM_LAT;
}
updateTransformMatrix();
}
void MapProjection::setPoint( float64 screenPointX,
float64 screenPointY,
float64 centerPointX,
float64 centerPointY,
const MC2Coordinate& newCoord )
{
// Check the first part of
// TransformMatrix::inverseTranformUsingCosLat
// m_Ty is calculated from this using the screen point and coord.
m_Ty = - 1.0/m_Sy * m_C * screenPointX
+ 1.0/m_Sy * m_D * screenPointY
+ 1.0/m_Sy * m_C * m_tx
- 1.0/m_Sy * m_D * m_ty
- newCoord.lat;
// Now the calculated m_Ty is used to get the latitude of the center.
// Also check the first part of inverseTranformUsingCosLat for this.
m_centerCoord.lat =
int32(int64(( - 1.0/m_Sy * m_C * centerPointX
+ 1.0/m_Sy * m_D * centerPointY
+ 1.0/m_Sy * m_C * m_tx
- 1.0/m_Sy * m_D * m_ty
- m_Ty ) ) );
// Now that the center latitude is known, the coslat can be
// calcualted.
m_cosLat = getCosLat( m_centerCoord.lat );
double S_x = m_Sx * m_cosLat;
// This next step is from the second part of that method.
// m_Tx is solved from that equation using the screenpoint and coord.
m_Tx = 1.0 / S_x * m_A * screenPointX
- 1.0 / S_x * m_B * screenPointY
- 1.0 / S_x * m_A * m_tx
+ 1.0 / S_x * m_B * m_ty
- newCoord.lon;
// Now explicitly calculate the center longitude.
// This is done since we want to be able to use setCenter
// to set all the different members etc.
m_centerCoord.lon = int32( int64( + 1.0 / S_x * m_A * centerPointX
- 1.0 / S_x * m_B * centerPointY
- 1.0 / S_x * m_A * m_tx
+ 1.0 / S_x * m_B * m_ty
- m_Tx) );
// Now set the center to that center coordinate. Will update
// all the members.
setCenter( m_centerCoord );
}
void
MapProjection::setPointf(const MC2Coordinate& newCoord,
const MC2Pointf& screenPoint )
{
// Translate the center to a screen coord.
MC2Pointf centerPoint = { 0.0f, 0.0f };
transformPointInternalCosLatf( centerPoint.x,
centerPoint.y,
m_centerCoord );
setPoint( screenPoint.x,
screenPoint.y,
centerPoint.x,
centerPoint.y,
newCoord );
}
void
MapProjection::setPoint(const MC2Coordinate& newCoord,
const MC2Point& screenPoint )
{
// Translate the center to a screen coord.
MC2Point centerPoint(0,0);
transformPointInternalCosLat( centerPoint,
m_centerCoord );
setPoint( screenPoint.getX(),
screenPoint.getY(),
centerPoint.getX(),
centerPoint.getY(),
newCoord );
}
void
MapProjection::setAngle(double angleDeg)
{
m_angle = angleDeg;
updateTransformMatrix();
}
void
MapProjection::setAngle(double angleDeg,
const MC2Point& rotationPoint )
{
// Translate the center to a screen coord.
MC2Point centerPoint(0,0);
transformPointInternalCosLat( centerPoint,
m_centerCoord );
int deltaX = centerPoint.getX() - rotationPoint.getX();
int deltaY = centerPoint.getY() - rotationPoint.getY();
move(-deltaX, -deltaY);
setAngle( angleDeg );
move(deltaX, deltaY);
}
double
MapProjection::getAngle() const
{
return m_angle;
}
void
MapProjection::setPoint(const MC2Coordinate& newCoord,
const MC2Point& screenPoint,
double angleDeg )
{
disableMatrixUpdatedNotification();
setPoint( newCoord, screenPoint );
setAngle( angleDeg, screenPoint );
enableMatrixUpdatedNotification();
}
void
MapProjection::setScreenSize(const MC2Point& size)
{
if ( size != m_screenSize && size != MC2Point(0,0) ) {
m_screenSize = size;
updateTransformMatrix();
}
}
MC2Coordinate
MapProjection::calcLowerLeft() const
{
// Constant forever
static const double mc2scaletometer = 6378137.0*2.0*
3.14159265358979323846 / 4294967296.0;
const double invScale = 1.0/m_scale;
const double mc2scale = mc2scaletometer * invScale;
const int screenWidth = m_screenSize.getX();
const int screenHeight = m_screenSize.getY();
return MC2Coordinate( int32(double(m_centerCoord.lat) -
(1/mc2scale * screenHeight * 0.5)),
int32(double(m_centerCoord.lon) -
(1/mc2scale/getCosLat(m_centerCoord.lat) *
screenWidth * 0.5 ) ) );
}
| [
"[email protected]"
]
| [
[
[
1,
567
]
]
]
|
625bc478f750cee0fb1fe31661779a2ef0f7b745 | 25a408954fdda07b6a27f84f74c9b9b6af1a282c | /ReLips/PlayStateParam.cpp | d728df7fe50cde763bf908e4351eb0f9cf4dab14 | []
| no_license | nkuln/relips | 6a6f9b99d72157d038bc9badff42a644fe094bf5 | f6ec7614710e7b3785469b2e670f3abc854b9e2e | refs/heads/master | 2016-09-11T02:58:48.354657 | 2009-02-17T15:29:02 | 2009-02-17T15:29:02 | 33,202,450 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 166 | cpp | #include "StdAfx.h"
#include "PlayStateParam.h"
PlayStateParam::PlayStateParam(void)
: difficulity(0)
{
}
PlayStateParam::~PlayStateParam(void)
{
}
| [
"m3rlinez@4e9c09b0-ef73-11dd-a70c-37889e090ee0"
]
| [
[
[
1,
13
]
]
]
|
e860ce5fe576d8a6533eeeb38a80786bdf09632a | 191d4160cba9d00fce9041a1cc09f17b4b027df5 | /ZeroLag2/ZeroLag/ProcessManage.h | 8f72cdb0722469141dc71d860d78ab891b6673ae | []
| no_license | zapline/zero-lag | f71d35efd7b2f884566a45b5c1dc6c7eec6577dd | 1651f264c6d2dc64e4bdcb6529fb6280bbbfbcf4 | refs/heads/master | 2021-01-22T16:45:46.430952 | 2011-05-07T13:22:52 | 2011-05-07T13:22:52 | 32,774,187 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 625 | h | #pragma once
#include "tlhelp32.h"
#include "psapi.h"
#pragma comment(lib,"psapi.lib")
#include "Shlwapi.h"
#include "vector"
using namespace std;
typedef struct _ProcessStruct
{
DWORD pid;
char name[MAX_PATH];
}ProcessStruct;
class CProcessManage
{
public:
CProcessManage(void);
public:
~CProcessManage(void);
void Init();
void Init2();
int GetCount();
ProcessStruct GetProcessInfo(int i);
BOOL TerminateProcessById(DWORD dwId);
private:
vector<ProcessStruct> ProcessList;
int Count;
BOOL AdjustPurview();
void PrintProcessNameAndID(DWORD processID, LPSTR pPathName);
};
| [
"Administrator@PC-200201010241"
]
| [
[
[
1,
34
]
]
]
|
939faa6d2356ab595f8004088442c5ea127338b2 | 3cb5812f3d3e3f0d73e5b8d1f67266f3e3c9e4ba | /libs/serialization/src/basic_serializer_map.cpp | 9c3f7c29d176aad87d03df830f5098d1e8eab94f | [
"BSL-1.0"
]
| permissive | elemel/boost-python | f8d4d90fd849635bbb27549bd14fdd8a6f6805ae | bccdebb4c0aea6ad7bb6431dc0a73879e8380fa7 | refs/heads/master | 2016-08-04T07:50:21.616823 | 2010-06-12T12:11:04 | 2010-06-12T12:11:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,409 | cpp | /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// serializer_map.cpp:
// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for updates, documentation, and revision history.
#if (defined _MSC_VER) && (_MSC_VER == 1200)
# pragma warning (disable : 4786) // too long name, harmless warning
#endif
#include <set>
#include <utility>
#define BOOST_ARCHIVE_SOURCE
#include <boost/archive/archive_exception.hpp>
#include <boost/serialization/throw_exception.hpp>
#include <boost/archive/detail/basic_serializer.hpp>
#include <boost/archive/detail/basic_serializer_map.hpp>
namespace boost {
namespace serialization {
class extended_type_info;
}
namespace archive {
namespace detail {
bool
basic_serializer_map::type_info_pointer_compare::operator()(
const basic_serializer * lhs, const basic_serializer * rhs
) const {
return *lhs < *rhs;
}
BOOST_ARCHIVE_DECL(bool)
basic_serializer_map::insert(const basic_serializer * bs){
// attempt to insert serializer into it's map
const std::pair<map_type::iterator, bool> result =
m_map.insert(bs);
// the following is commented out - rather than being just
// deleted as a reminder not to try this.
// At first it seemed like a good idea. It enforced the
// idea that a type be exported from at most one code module
// (DLL or mainline). This would enforce a "one definition rule"
// across code modules. This seems a good idea to me.
// But it seems that it's just too hard for many users to implement.
// Ideally, I would like to make this exception a warning -
// but there isn't anyway to do that.
// if this fails, it's because it's been instantiated
// in multiple modules - DLLS - a recipe for problems.
// So trap this here
// if(!result.second){
// boost::serialization::throw_exception(
// archive_exception(
// archive_exception::multiple_code_instantiation,
// bs->get_debug_info()
// )
// );
// }
return true;
}
BOOST_ARCHIVE_DECL(void)
basic_serializer_map::erase(const basic_serializer * bs){
map_type::iterator it = m_map.begin();
map_type::iterator it_end = m_map.end();
while(it != it_end){
// note item 9 from Effective STL !!! it++
if(*it == bs)
m_map.erase(it++);
else
it++;
}
// note: we can't do this since some of the eti records
// we're pointing to might be expired and the comparison
// won't work. Leave this as a reminder not to "optimize" this.
//it = m_map.find(bs);
//assert(it != m_map.end());
//if(*it == bs)
// m_map.erase(it);
}
BOOST_ARCHIVE_DECL(const basic_serializer *)
basic_serializer_map::find(
const boost::serialization::extended_type_info & eti
) const {
const basic_serializer_arg bs(eti);
map_type::const_iterator it;
it = m_map.find(& bs);
assert(it != m_map.end());
return *it;
}
} // namespace detail
} // namespace archive
} // namespace boost
| [
"[email protected]"
]
| [
[
[
1,
104
]
]
]
|
7afa3e1a81f88e25aa524538770c672a006a67b8 | b4bff7f61d078e3dddeb760e21174a781ed7f985 | /Examples/Tutorial/ParticleSystem/23RadialFieldParticleAffector.cpp | 99d4c2fa0e84deda88fb2e2782e4bfad00778b49 | []
| no_license | Langkamp/OpenSGToolbox | 8283edb6074dffba477c2c4d632e954c3c73f4e3 | 5a4230441e68f001cdf3e08e9f97f9c0f3c71015 | refs/heads/master | 2021-01-16T18:15:50.951223 | 2010-05-19T20:24:52 | 2010-05-19T20:24:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,991 | cpp | // General OpenSG configuration, needed everywhere
#include "OSGConfig.h"
// A little helper to simplify scene management and interaction
#include "OSGSimpleSceneManager.h"
#include "OSGNode.h"
#include "OSGGroup.h"
#include "OSGViewport.h"
#include "OSGWindowUtils.h"
// Input
#include "OSGKeyListener.h"
#include "OSGBlendChunk.h"
#include "OSGPointChunk.h"
#include "OSGChunkMaterial.h"
#include "OSGMaterialChunk.h"
#include "OSGParticleSystem.h"
#include "OSGParticleSystemCore.h"
#include "OSGPointParticleSystemDrawer.h"
#include "OSGRateParticleGenerator.h"
#include "OSGConeDistribution3D.h"
#include "OSGSphereDistribution3D.h"
#include "OSGRadialParticleAffector.h"
#include "OSGGaussianNormalDistribution1D.h"
// Activate the OpenSG namespace
OSG_USING_NAMESPACE
// The SimpleSceneManager to manage simple applications
SimpleSceneManager *mgr;
WindowEventProducerRefPtr TutorialWindow;
// Forward declaration so we can have the interesting stuff upfront
void display(void);
void reshape(Vec2f Size);
Distribution3DRefPtr createPositionDistribution(void);
Distribution1DRefPtr createLifespanDistribution(void);
Distribution3DRefPtr createVelocityDistribution(void);
RadialParticleAffectorRefPtr ExampleRadialAffector;
// Create a class to allow for the use of the Ctrl+q
class TutorialKeyListener : public KeyListener
{
public:
virtual void keyPressed(const KeyEventUnrecPtr e)
{
if(e->getKey() == KeyEvent::KEY_Q && e->getModifiers() & KeyEvent::KEY_MODIFIER_CONTROL)
{
TutorialWindow->closeWindow();
}
if(e->getKey() == KeyEvent::KEY_R)
{
ExampleRadialAffector->setMagnitude(-(ExampleRadialAffector->getMagnitude()));
}
}
virtual void keyReleased(const KeyEventUnrecPtr e)
{
}
virtual void keyTyped(const KeyEventUnrecPtr e)
{
}
};
class TutorialMouseListener : public MouseListener
{
public:
virtual void mouseClicked(const MouseEventUnrecPtr e)
{
}
virtual void mouseEntered(const MouseEventUnrecPtr e)
{
}
virtual void mouseExited(const MouseEventUnrecPtr e)
{
}
virtual void mousePressed(const MouseEventUnrecPtr e)
{
mgr->mouseButtonPress(e->getButton(), e->getLocation().x(), e->getLocation().y());
}
virtual void mouseReleased(const MouseEventUnrecPtr e)
{
mgr->mouseButtonRelease(e->getButton(), e->getLocation().x(), e->getLocation().y());
}
};
class TutorialMouseMotionListener : public MouseMotionListener
{
public:
virtual void mouseMoved(const MouseEventUnrecPtr e)
{
mgr->mouseMove(e->getLocation().x(), e->getLocation().y());
}
virtual void mouseDragged(const MouseEventUnrecPtr e)
{
mgr->mouseMove(e->getLocation().x(), e->getLocation().y());
}
};
int main(int argc, char **argv)
{
// OSG init
osgInit(argc,argv);
// Set up Window
TutorialWindow = createNativeWindow();
TutorialWindow->initWindow();
TutorialWindow->setDisplayCallback(display);
TutorialWindow->setReshapeCallback(reshape);
TutorialKeyListener TheKeyListener;
TutorialWindow->addKeyListener(&TheKeyListener);
TutorialMouseListener TheTutorialMouseListener;
TutorialMouseMotionListener TheTutorialMouseMotionListener;
TutorialWindow->addMouseListener(&TheTutorialMouseListener);
TutorialWindow->addMouseMotionListener(&TheTutorialMouseMotionListener);
// Create the SimpleSceneManager helper
mgr = new SimpleSceneManager;
// Tell the Manager what to manage
mgr->setWindow(TutorialWindow);
//Particle System Material
PointChunkRefPtr PSPointChunk = PointChunk::create();
PSPointChunk->setSize(5.0f);
PSPointChunk->setSmooth(true);
BlendChunkRefPtr PSBlendChunk = BlendChunk::create();
PSBlendChunk->setSrcFactor(GL_SRC_ALPHA);
PSBlendChunk->setDestFactor(GL_ONE_MINUS_SRC_ALPHA);
MaterialChunkRefPtr PSMaterialChunkChunk = MaterialChunk::create();
PSMaterialChunkChunk->setAmbient(Color4f(1.0f,1.0f,1.0f,1.0f));
PSMaterialChunkChunk->setDiffuse(Color4f(0.7f,0.7f,0.7f,1.0f));
PSMaterialChunkChunk->setSpecular(Color4f(0.9f,0.9f,0.9f,1.0f));
PSMaterialChunkChunk->setColorMaterial(GL_NONE);
ChunkMaterialRefPtr PSMaterial = ChunkMaterial::create();
PSMaterial->addChunk(PSPointChunk);
PSMaterial->addChunk(PSMaterialChunkChunk);
PSMaterial->addChunk(PSBlendChunk);
//Particle System
ParticleSystemRefPtr ExampleParticleSystem = OSG::ParticleSystem::create();
ExampleParticleSystem->addParticle(Pnt3f(0,100,0),
Vec3f(0.0,0.0f,1.0f),
Color4f(1.0,1.0,1.0,1.0),
Vec3f(1.0,1.0,1.0),
0.1,
Vec3f(0.0f,0.0f,0.0f), //Velocity
Vec3f(0.0f,0.0f,0.0f)
);
ExampleParticleSystem->addParticle(Pnt3f(0,-100,0),
Vec3f(0.0,0.0f,1.0f),
Color4f(1.0,1.0,1.0,1.0),
Vec3f(1.0,1.0,1.0),
0.1,
Vec3f(0.0f,0.0f,0.0f), //Velocity
Vec3f(0.0f,0.0f,0.0f)
);
ExampleParticleSystem->attachUpdateListener(TutorialWindow);
//Particle System Drawer (Point)
PointParticleSystemDrawerRefPtr ExampleParticleSystemDrawer = OSG::PointParticleSystemDrawer::create();
//Create a Rate Particle Generator
RateParticleGeneratorRefPtr ExampleGenerator = OSG::RateParticleGenerator::create();
//Attach the function objects to the Generator
ExampleGenerator->setPositionDistribution(createPositionDistribution());
ExampleGenerator->setLifespanDistribution(createLifespanDistribution());
ExampleGenerator->setGenerationRate(80.0);
ExampleGenerator->setVelocityDistribution(createVelocityDistribution());
ExampleRadialAffector = OSG::RadialParticleAffector::create();
ExampleRadialAffector->setMagnitude(15.0);
NodeRefPtr RadialBeacon = OSG::Node::create();
ExampleRadialAffector->setBeacon(RadialBeacon); // set to 'emulate' from (0,0,0)
ExampleRadialAffector->setMaxDistance(-1.0); // particles affected regardless of distance
ExampleRadialAffector->setAttenuation(0.0); // strength of uniform field dimishes by dist^attenuation
//Attach the Generator and Affector to the Particle System
ExampleParticleSystem->pushToGenerators(ExampleGenerator);
ExampleParticleSystem->pushToAffectors(ExampleRadialAffector);
ExampleParticleSystem->setMaxParticles(800);
//Particle System Node
ParticleSystemCoreRefPtr ParticleNodeCore = OSG::ParticleSystemCore::create();
ParticleNodeCore->setSystem(ExampleParticleSystem);
ParticleNodeCore->setDrawer(ExampleParticleSystemDrawer);
ParticleNodeCore->setMaterial(PSMaterial);
NodeRefPtr ParticleNode = OSG::Node::create();
ParticleNode->setCore(ParticleNodeCore);
// Make Main Scene Node and add the Torus
NodeRefPtr scene = OSG::Node::create();
scene->setCore(OSG::Group::create());
scene->addChild(ParticleNode);
mgr->setRoot(scene);
// Show the whole Scene
mgr->showAll();
mgr->getCamera()->setFar(1000.0);
std::cout << "Radial Particle Affector Tutorial Controls:\n"
<< "R: Reverse direction of field\n"
<< "Ctrl + Q: Exit Tutorial";
//Open Window
Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
TutorialWindow->openWindow(WinPos,
WinSize,
"23RadialFieldParticleAffector");
//Enter main Loop
TutorialWindow->mainLoop();
osgExit();
return 0;
}
// Callback functions
// Redraw the window
void display(void)
{
mgr->redraw();
}
// React to size changes
void reshape(Vec2f Size)
{
mgr->resize(Size.x(), Size.y());
}
Distribution3DRefPtr createPositionDistribution(void)
{
SphereDistribution3DRefPtr TheSphereDistribution = SphereDistribution3D::create();
TheSphereDistribution->setCenter(Pnt3f(0.0,0.0,0.0));
TheSphereDistribution->setInnerRadius(20.0);
TheSphereDistribution->setOuterRadius(25.0);
TheSphereDistribution->setMinTheta(0.0);
TheSphereDistribution->setMaxTheta(6.283185);
TheSphereDistribution->setMinZ(-1.0);
TheSphereDistribution->setMaxZ(1.0);
TheSphereDistribution->setSurfaceOrVolume(SphereDistribution3D::VOLUME);
return TheSphereDistribution;
}
Distribution1DRefPtr createLifespanDistribution(void)
{
GaussianNormalDistribution1DRefPtr TheLifespanDistribution = GaussianNormalDistribution1D::create();
TheLifespanDistribution->setMean(15.0f);
TheLifespanDistribution->setStandardDeviation(3.0);
return TheLifespanDistribution;
}
Distribution3DRefPtr createVelocityDistribution(void)
{
SphereDistribution3DRefPtr TheSphereDistribution = SphereDistribution3D::create();
TheSphereDistribution->setCenter(Pnt3f(0.0,0.0,0.0));
TheSphereDistribution->setInnerRadius(0.0);
TheSphereDistribution->setOuterRadius(0.1);
TheSphereDistribution->setMinTheta(0.0);
TheSphereDistribution->setMaxTheta(6.283185);
TheSphereDistribution->setMinZ(-1.0);
TheSphereDistribution->setMaxZ(1.0);
TheSphereDistribution->setSurfaceOrVolume(SphereDistribution3D::SURFACE);
return TheSphereDistribution;
}
| [
"[email protected]"
]
| [
[
[
1,
296
]
]
]
|
eb499b16bfcff92574c0c35471f5b3c9e72f2cdb | 1aa804f9ce4765517ead568d7306cab7bae08e8c | /libatom/Tools/Assert.cpp | 8e8a47ca97800b090d0b42410410409fecefae18 | []
| no_license | marcomorain/atom-old | d6657233fbe3336760f5c873c9531c699cb51429 | 9300e17c25e4ed08d17b15d56b59eaa6da21de7c | refs/heads/master | 2021-01-19T02:41:29.281966 | 2008-12-16T14:21:49 | 2008-12-16T14:21:49 | 32,418,516 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 286 | cpp | #if defined NDEBUG
// No asserts...
#else
#include <Tools/Assert.h>
#include <iostream>
void Assert::Fail(const char* file, const unsigned line, const char* message)
{
std::cerr << file << ":" << line << " Assertion failed: " << message << std::endl;
}
#endif //!NDEBUG
| [
"[email protected]"
]
| [
[
[
1,
12
]
]
]
|
6543496e167b4eac665fd596146fbbcc58134865 | ce1b0d027c41f70bc4cfa13cb05f09bd4edaf6a2 | / edge2d --username [email protected]/test/TestResMgr.cpp | b834ac14e99d55511206436edefb87ccdeb9e50b | []
| no_license | ratalaika/edge2d | 11189c41b166960d5d7d5dbcf9bfaf833a41c079 | 79470a0fa6e8f5ea255df1696da655145bbf83ff | refs/heads/master | 2021-01-10T04:59:22.495428 | 2010-02-19T13:45:03 | 2010-02-19T13:45:03 | 36,088,756 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,099 | cpp | /**
* Test Edge Resource Manager
*
* Kevin Lynx
* 2007.10.24
*
*/
#ifdef _DEBUG
#include "vld.h"
#endif
#if EDGE_PLATFORM == EDGE_PLATFORM_WIN32
#include <windows.h>
#endif
#include "Edge.h"
#include "helper/EdgeHelper.h"
using namespace Edge;
#ifdef _DEBUG
#pragma comment( lib, "../lib/EdgeBase_D.lib" )
#pragma comment( lib, "../lib/EdgeHelper_D.lib" )
#else
#pragma comment( lib, "../lib/EdgeBase.lib" )
#pragma comment( lib, "../lib/EdgeHelper.lib" )
#endif
const wstring g_info = L" \
*-- Edge 综合测试\n \
*-- 资源管理器测试\n \
*-- Kevin Lynx\n \
*-- 2007.10.24\n \
";
class MyApp : public Application
{
public:
MyApp()
{
#ifdef EDGE_DEBUG
mConfigFile = "plugin_d.config";
#else
mConfigFile = "plugin.config";
#endif
mCaption = "Edge Resource Manager Test - Kevin Lynx - 2007.10.24";
}
~MyApp() { release(); }
bool init();
void release();
bool update();
void render();
private:
Font *mFont;
Image *mImgBk;
Image *mImgLogo;
Sound *mSndBk;
};
bool MyApp::init()
{
EdgeEngine *engine = EdgeEngine::getSingletonPtr();
ImageFactory *ifac = engine->getImageFactory();
ArchiveManager *am = engine->getArchiveManager();
SoundFactory *sfac = engine->getSoundFactory();
/// load resources
ResourceManager *resMgr = new ResourceManager();
resMgr->initiate( "./resources.xml" );
resMgr->loadAllGroups();
mFont = resMgr->getFont( "font1" );
mImgBk = resMgr->getImage( "back" );
mImgLogo = resMgr->getImage( "logo" );
mSndBk = resMgr->getSound( "back" );
mImgBk->setRect( 0, 0, mWidth, mHeight );
mImgLogo->setHotSpot( mImgLogo->getWidth() / 2.0f, mImgLogo->getHeight() / 2.0f );
mSndBk->play( true );
setConstFPS( 100 );
return true;
}
void MyApp::release()
{
delete ResourceManager::getSingletonPtr();
}
bool MyApp::update()
{
InputManager *im = EdgeEngine::getSingleton().getInputManager();
if( im->isKeyDown( Edge::KC_ESCAPE ) )
{
return false;
}
return true;
}
void MyApp::render()
{
Graphics *graphics = EdgeEngine::getSingleton().getGraphics();
graphics->beginScene();
graphics->clear( ARGB( 255, 128, 128, 128 ) );
mImgBk->render( 0, 0 );
mImgLogo->render( mWidth / 2.0f, mHeight / 2.0f );
mFont->render( 0, 20, g_info );
mFont->render( 0, 0, Font::ETA_DEFAULT, ARGB( 255, 0, 255, 0 ), L"FPS:%d", getFPS() );
graphics->endScene();
}
/////////////////////////////////////////////////////////////////////////////////////
///
/// program entry
///
/////////////////////////////////////////////////////////////////////////////////////
int main( int argc, char **argv )
{
MyApp app;
try
{
if( !app._init() )
{
return 0;
}
/// log the arguments
for( int i = 0; i < argc; ++ i)
{
LogManager::getSingleton().logMessage( LL_INFORMATION, argv[i] );
}
app.run();
}
catch( Exception &e )
{
#if EDGE_PLATFORM == EDGE_PLATFORM_WIN32
MessageBoxA( NULL, e.getFullDescription().c_str(), "ERROR", MB_OK );
#endif
}
return 0;
}
| [
"[email protected]@539dfdeb-0f3d-0410-9ace-d34ff1985647"
]
| [
[
[
1,
154
]
]
]
|
eddd13dfbb6e639e53c4f070d40023725a3653ef | 3da0b0276bc8c3d7d1bcdbabfb0e763a38d3a24c | /zju.finished/2832.cpp | f595ee9e8591447a749f84499e25915204896cab | []
| no_license | usherfu/zoj | 4af6de9798bcb0ffa9dbb7f773b903f630e06617 | 8bb41d209b54292d6f596c5be55babd781610a52 | refs/heads/master | 2021-05-28T11:21:55.965737 | 2009-12-15T07:58:33 | 2009-12-15T07:58:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 710 | cpp | #include<iostream>
#include<string>
#include<set>
using namespace std;
set<string > good, bad;
set<string>::iterator iter;
int num;
int fun(){
int i,j;
string s;
for(i = 0; i< num; i ++){
cin>>s;
iter = bad.find(s);
if(iter == bad.end()){
good.insert(s);
}
cin>>j;
while(j--){
cin>>s;
iter = good.find(s);
if(iter != good.end()){
good.erase(s);
}
bad.insert(s);
}
}
for(iter = good.begin(); iter != good.end(); iter++){
cout<<(*iter)<<endl;
}
good.clear();
bad.clear();
return 0;
}
int main(){
int tstcase = 0;
while(cin>>num){
if(tstcase ++ ){
cout<<endl;
}
fun();
}
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
47
]
]
]
|
7be443248b0e88c71ee2bd79a84af5f85e6c91e9 | 222bc22cb0330b694d2c3b0f4b866d726fd29c72 | /src/nv38box/RaytracerRForce/KernelDebug.h | 3686e8d7db17685ee8eb5fd991193917b58f01c9 | [
"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 | WINDOWS-1252 | C++ | false | false | 1,017 | h | // NV38Box (http://inferno.hildebrand.cz)
// Copyright (c) 2004 Antonin Hildebrand
// licensed under zlib/libpng license (see license.txt)
// released in Shader Triathlon – Summer 2004 ("Contest")
/*! \addtogroup RForce
@{
\ingroup Raytracers
*/
/*! \file KernelDebug.h
\brief Declaration of KernelDebug class.
*/
#ifndef _KERNELDEBUG_H_
#define _KERNELDEBUG_H_
#include "Kernel.h"
//! Enum for Debug kernel modes
enum E_KERNEL_DEBUG_MODE {
KERNEL_DEBUG_MODE_TEST1 = 0,
KERNEL_DEBUG_MODE_WORK1,
KERNEL_DEBUG_MODE_COUNT
};
//! Class managing Debug kernel.
/*!
Debug kernel is dedicated for testing and debug purposes.
<b>Mode KERNEL_DEBUG_MODE_TEST1 and KERNEL_DEBUG_MODE_WORK1</b><br>
Debug programs for early-z test.
*/
class KernelDebug : public Kernel
{
public:
//! KernelBVBuilder constructor.
KernelDebug ();
//! Loads programs from disk and prepares kernel.
virtual bool Prepare();
};
#endif
//! @} //doxygen group
| [
"[email protected]"
]
| [
[
[
1,
46
]
]
]
|
202dbd4964354f1ff489f81064eb7705a5170d56 | 0b70142d223c7c0eed83246efef6d96b36033b2e | /Class_Segmentation/GraphSeg/binaryHeap.h | eb013cdf210d5dd8c8910f3a7693c76f14837871 | []
| no_license | amounir86/phd-workspace | 5aef9f21baff17d9af0e8e6bc8a0f7e654f6583b | 9fec5eef8cf2bcdd02ae9ee241d6e088bf8f80c3 | refs/heads/master | 2021-04-12T04:45:16.077787 | 2011-01-25T12:28:54 | 2011-01-25T12:28:54 | 32,120,729 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,250 | h | //Copyright (c) 2009, Yan Zhang
//All rights reserved.
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions are
//met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the distribution
//Note:
//This script was originally composed by Yan Zhang and modified by Su Dongcai on 2009/11/15
//BinaryHeap.h
#ifndef __ZY_CBinaryHeap_H__
#define __ZY_CBinaryHeap_H__
#define HEAPTEMPLATE template<class ContentType, class WeightType>
#include <iostream>
#include <exception>
using namespace std;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// CBinaryHeap
// BinaryHeap implementation
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
HEAPTEMPLATE
struct HeapNode
{
ContentType content;
WeightType weight;
};
HEAPTEMPLATE
class CBinaryHeap
{
private:
HeapNode<ContentType, WeightType>* m_heap;
int m_heap_idx; // indicates the heap position for next insertion.
int m_heap_size;
public:
CBinaryHeap(int number_of_points);
CBinaryHeap(ContentType* contenArray, WeightType* weightArray, int number_of_points);
~CBinaryHeap();
public:
void Insert(ContentType content, WeightType weight);
bool Extract(HeapNode<ContentType, WeightType>* heap_node);
bool IsEmpty();
void ReplaceData(ContentType content, WeightType weight);
void Reset();
};
HEAPTEMPLATE
CBinaryHeap<ContentType, WeightType>::CBinaryHeap(int number_of_points)
{
m_heap = new HeapNode<ContentType, WeightType>[number_of_points];
m_heap_idx = 0;
m_heap_size = number_of_points;
}
HEAPTEMPLATE
CBinaryHeap<ContentType, WeightType>::CBinaryHeap(ContentType* contenArray, WeightType* weightArray, int number_of_points)
{
m_heap = new HeapNode<ContentType, WeightType>[number_of_points];
m_heap_idx = 0;
m_heap_size = number_of_points;
int i;
for(i=0; i<number_of_points; i++)
{
Insert(contenArray[i], weightArray[i]);
}
}
HEAPTEMPLATE
CBinaryHeap<ContentType, WeightType>::~CBinaryHeap()
{
if(m_heap) delete []m_heap;
}
HEAPTEMPLATE
void CBinaryHeap<ContentType, WeightType>::Insert(ContentType content, WeightType weight)
{
m_heap[m_heap_idx].content = content;
m_heap[m_heap_idx].weight = weight;
int idx = m_heap_idx;
m_heap_idx++;
if( m_heap_idx > m_heap_size ) throw -1;
while(idx != 0)
{
int parent_idx = int((idx-1)/2);
if( m_heap[idx].weight < m_heap[parent_idx].weight )
{
HeapNode<ContentType, WeightType> tmp = m_heap[idx];
m_heap[idx] = m_heap[parent_idx];
m_heap[parent_idx] = tmp;
idx = parent_idx;
}
else break;
}
}
HEAPTEMPLATE
bool CBinaryHeap<ContentType, WeightType>::Extract(HeapNode<ContentType, WeightType>* heap_node)
{
if( this->IsEmpty() ) return false;
heap_node->content = m_heap[0].content;
heap_node->weight = m_heap[0].weight;
m_heap_idx --;
int idx = m_heap_idx;
if( idx > 0) // if still exists node in the heap
{
m_heap[0] = m_heap[idx]; // replace the first node by the last node
idx = 0;
while(1)
{
int child_idx0 = 2*idx + 1;
int child_idx1 = child_idx0 +1;
if( child_idx0 >= m_heap_idx ) break; // no children for idx, i.e. idx has reached a leave, break.
else
{
int child_idx = child_idx0;
if( child_idx1 < m_heap_idx ) // if idx has two children.
if( m_heap[child_idx].weight > m_heap[child_idx1].weight ) // find the child with larger value.
child_idx = child_idx1;
// if idx has smaller value than the child found, swap.
if( m_heap[idx].weight > m_heap[child_idx].weight )
{
HeapNode<ContentType, WeightType> tmp = m_heap[idx];
m_heap[idx] = m_heap[child_idx];
m_heap[child_idx] = tmp;
idx = child_idx;
}
else break; // otherwise idx is in the right place, break;
}
}
}
return true;
}
HEAPTEMPLATE
bool CBinaryHeap<ContentType, WeightType>::IsEmpty()
{
return m_heap_idx == 0;
}
HEAPTEMPLATE
void CBinaryHeap<ContentType, WeightType>::ReplaceData(ContentType content, WeightType weight)
{
Insert(content, weight);
}
HEAPTEMPLATE
void CBinaryHeap<ContentType, WeightType>::Reset()
{
m_heap_idx = 0;
}
#endif // __ZY_CBinaryHeap_H__
| [
"a.mounir86@96b4d95f-8974-693b-bc50-b51d9e964dd0"
]
| [
[
[
1,
171
]
]
]
|
2b9fa5b5ef749fce06be27c74452454ec72cb615 | 921f01654661c3f802fc6397c64cf4b2c4350196 | /Panoply.Library.Native/MediaInfo/MediaInfo.cpp | 9878c337d1ae849fa77a2a2a7d2aca9419a67673 | []
| no_license | anelson/panoply | c4ee97bf76a64b88c106ec19d310912dba9abdd4 | 87eea912d38559f5b453bb81afc8b793b6c70590 | refs/heads/master | 2021-01-22T09:48:34.395564 | 2010-11-07T23:09:02 | 2010-11-07T23:09:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,717 | cpp | #include "stdafx.h"
#include <vcclr.h>
#include ".\MediaInfo.h"
#define MEDIAINFO_LIB_VERSION L"0.7.15" //The version of MediaInfoLib this is compiled against
using namespace Panoply::Library::Native::MediaInfo;
static MediaInfoLib::String ClrStringToStlWstring(String^ clrString) {
if (clrString == nullptr) {
return L"";
}
pin_ptr<const wchar_t> clrStringBuffer = ::PtrToStringChars(clrString);
return MediaInfoLib::String(clrStringBuffer);
}
MediaInfo::MediaInfo() {
_mediaInfo = new MediaInfoLib::MediaInfo();
}
MediaInfo::~MediaInfo() {
Cleanup(true);
}
MediaInfo::!MediaInfo() {
Cleanup(false);
GC::SuppressFinalize(this);
}
String^ MediaInfo::LibraryVersion::get() {
if (!_initialized) {
throw gcnew InvalidOperationException(L"MediaInfo hasn't been initialized yet");
}
return _mediaInfoLibVersion;
}
void MediaInfo::Initialize(String^ appName, String^ appVersion) {
if (!_initialized) {
String^ versionString = String::Format(L"{0};{1};{2}",
MEDIAINFO_LIB_VERSION,
appName,
appVersion);
MediaInfoLib::String mediaInfoVersion = MediaInfoLib::MediaInfo::Option_Static(L"Info_Version",
::ClrStringToStlWstring(versionString));
if (mediaInfoVersion == L"") {
throw gcnew ApplicationException(L"This library is not compatible with the version of mediainfolib being used");
}
_mediaInfoLibVersion = gcnew String(mediaInfoVersion.c_str());
_initialized = true;
}
}
MediaInfo^ MediaInfo::AttachToFile(String^ filePath) {
if (!_initialized) {
throw gcnew InvalidOperationException(L"MediaInfo hasn't been initialized yet");
}
MediaInfo^ mi = gcnew MediaInfo();
try {
mi->Open(filePath);
} catch (...) {
delete mi;
throw;
}
return mi;
}
void MediaInfo::Open(String^ filePath) {
if (!_mediaInfo->Open(::ClrStringToStlWstring(filePath))) {
throw gcnew ApplicationException(
String::Format(L"Unable to open file '{0}'", filePath)
);
}
}
String^ MediaInfo::Inform() {
return gcnew String(
_mediaInfo->Inform().c_str()
);
}
String^ MediaInfo::GetOption(String^ option) {
return gcnew String(_mediaInfo->Option(::ClrStringToStlWstring(option)).c_str());
}
void MediaInfo::SetOption(String^ option, String^ value) {
_mediaInfo->Option(
::ClrStringToStlWstring(option),
::ClrStringToStlWstring(value)
);
}
unsigned int MediaInfo::GetStreamCount(StreamType streamKind) {
return static_cast<unsigned int>(_mediaInfo->Count_Get(static_cast<MediaInfoLib::stream_t>(streamKind)));
}
unsigned int MediaInfo::GetParameterCount(StreamType streamKind, unsigned int streamNumber) {
return static_cast<unsigned int>(_mediaInfo->Count_Get(static_cast<MediaInfoLib::stream_t>(streamKind),
streamNumber));
}
String^ MediaInfo::GetParameterInfo(StreamType streamKind,
unsigned int streamNumber,
unsigned int parameterNumber,
InfoType infoKind) {
return gcnew String(
_mediaInfo->Get(
static_cast<MediaInfoLib::stream_t>(streamKind),
streamNumber,
parameterNumber,
static_cast<MediaInfoLib::info_t>(infoKind)
).c_str()
);
}
String^ MediaInfo::GetParameterInfo(StreamType streamKind,
unsigned int streamNumber,
String^ parameterName,
InfoType infoKind) {
return gcnew String(
_mediaInfo->Get(
static_cast<MediaInfoLib::stream_t>(streamKind),
streamNumber,
::ClrStringToStlWstring(parameterName),
static_cast<MediaInfoLib::info_t>(infoKind)
).c_str()
);
}
void MediaInfo::Cleanup(bool disposing) {
disposing;
if (!_disposed) {
if (_mediaInfo) {
delete _mediaInfo;
_mediaInfo = NULL;
}
_disposed = true;
}
}
| [
"[email protected]"
]
| [
[
[
1,
154
]
]
]
|
e42d74b6f10331748ef62a5a084f888bef07c483 | 7f72fc855742261daf566d90e5280e10ca8033cf | /branches/full-calibration/ground/src/plugins/config/mixercurvewidget.h | ac8e77118b614bdfa7c85527fbf3753aca9db7f6 | []
| 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 | 1,948 | h | /**
******************************************************************************
*
* @file mixercurvewidget.h
* @author Edouard Lafargue Copyright (C) 2010.
* @addtogroup GCSPlugins GCS Plugins
* @{
* @addtogroup ConfigPlugin Configuration Plugin
* @{
* @brief A widget which displays a mixer curve
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef MIXERCURVEWIDGET_H_
#define MIXERCURVEWIDGET_H_
#include <QGraphicsView>
#include <QtSvg/QSvgRenderer>
#include <QtSvg/QGraphicsSvgItem>
#include "mixercurvepoint.h"
#include "mixercurveline.h"
class MixerCurveWidget : public QGraphicsView
{
Q_OBJECT
public:
MixerCurveWidget(QWidget *parent = 0);
~MixerCurveWidget();
void itemMoved(double itemValue); // Callback when a point is moved, to be updated
void initCurve (QList<double> points);
QList<double> getCurve();
signals:
void curveUpdated(QList<double>, double );
private slots:
private:
QGraphicsSvgItem *plot;
QList<Node*> nodeList;
protected:
void showEvent(QShowEvent *event);
void resizeEvent(QResizeEvent *event);
};
#endif /* MIXERCURVEWIDGET_H_ */
| [
"jonathan@ebee16cc-31ac-478f-84a7-5cbb03baadba"
]
| [
[
[
1,
64
]
]
]
|
2a659d6a531305c533ab6f48d42914ca7fb17c65 | 9773c3304eecc308671bcfa16b5390c81ef3b23a | /MDI AIPI V.6.92 2003 ( Correct Save Fired Rules, AM =-1, g_currentLine)/AIPI/PageFileDlg.h | 9faaa7aae2ab98c9bb59679f214eddfab3bed956 | []
| no_license | 15831944/AiPI-1 | 2d09d6e6bd3fa104d0175cf562bb7826e1ac5ec4 | 9350aea6ac4c7870b43d0a9f992a1908a3c1c4a8 | refs/heads/master | 2021-12-02T20:34:03.136125 | 2011-10-27T00:07:54 | 2011-10-27T00:07:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,161 | h | #if !defined(AFX_PAGEFILEDLG_H__5D09BD92_34F4_42A3_BA84_CE84F7EBD7B1__INCLUDED_)
#define AFX_PAGEFILEDLG_H__5D09BD92_34F4_42A3_BA84_CE84F7EBD7B1__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// PageFileDlg.h : header file
//
#include "PageInsertDlg.h"
#include "OXCoolCtrl.h"
#include "OXSeparator.h"
#include ".\GridCtrl\GridCtrl.h"
#include ".\DataFileCSV\CDataFile.h"
#include ".\BasicExcel\BasicExcelVC6.hpp"
//ComboListCtrl
#include ".\ComboListCtrl\ComboListCtrl.h"
#include ".\ComboListCtrl\InPlaceEditCombo.h"
#include "AIPI_DecisionTree/Aipi_DT_ID3.h"
/////////////////////////////////////////////////////////////////////////////
// CPageFileDlg dialog
class CGridCtrl;
class CPageFileDlg : public CDialog
{
// Construction
public:
CPageFileDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(CPageFileDlg)
enum { IDD = IDD_PAGEFILE_DLG };
CStatic m_nRows;
CStatic m_nCols;
COXCoolButton m_chkTables;
COXCoolButton m_chkQuery;
COXCoolButton m_chkData;
COXCoolButton m_chkVTables;
COXSeparator m_stcSeparator02;
COXSeparator m_stcSeparator03;
COXSeparator m_stcSeparator04;
COXSeparator m_stcSeparator05;
COXSeparator m_stcSeparator;
COXCoolButton m_btnOpenFile;
COXCoolButton m_btnConnectDB;
COXCoolButton m_btnExecQuery;
COXCoolButton m_chkVirtualMode;
COXCoolButton m_chkCallback;
//}}AFX_DATA
CGridCtrl *m_pGrid;
CPageInsertDlg *pInsertPage;
//CInductionTabView *pTab;
CComboListCtrl *m_pListCtrl1;
CListCtrl *m_pListCtrl2;
private:
//void SelectGrid();
int LA_isNumeric(CString t);
void StopTimer(CPerfTimer t, CString msg);
LVITEM CPageFileDlg::AddListItem1( int iItem, int iSubItem, LPTSTR szText);
LVITEM CPageFileDlg::AddListItem2( int iItem, int iSubItem, LPTSTR szText, int iImage);
void CPageFileDlg::AddListSubItem1( LVITEM item, int iItem, int iSubItem, LPTSTR szText);
void CPageFileDlg::AddListSubItem2( LVITEM item, int iItem, int iSubItem, LPTSTR szText);
void ChangeInterfacesPage2();
void UnCheckListCtrl1();
public:
static BOOL CALLBACK GridCallback(GV_DISPINFO *pDispInfo, LPARAM lParam);
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CPageFileDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CPageFileDlg)
afx_msg void OnBtnOpenFile();
afx_msg void OnBtnConnectDB();
virtual BOOL OnInitDialog();
afx_msg void OnBtnSaveAs();
afx_msg void OnCheckViewQuery();
afx_msg void OnCheckViewTables();
afx_msg void OnCheckViewData();
afx_msg void OnCheckTableV();
afx_msg void OnBtnExecQuery();
afx_msg void OnChkVirtualMode();
afx_msg void OnChkCallback();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_PAGEFILEDLG_H__5D09BD92_34F4_42A3_BA84_CE84F7EBD7B1__INCLUDED_)
| [
"[email protected]"
]
| [
[
[
1,
115
]
]
]
|
0a7d6a6bf581ede4c5d85bd53cbcc8b786ff8743 | 6fd162d2cade2db745e68f11d7e9722a3855f033 | /Source/Common/DXUT/Core/DXUT.cpp | 2878cf83866b95ffafb78bbd28b18694c58c0b0a | []
| no_license | SenichiFSeiei/oursavsm | 8f418325bc9883bcb245e139dbd0249e72c18d78 | 379e77cab67b3b1423a4c6f480b664f79b03afa9 | refs/heads/master | 2021-01-10T21:00:52.797565 | 2010-04-27T13:18:19 | 2010-04-27T13:18:19 | 41,737,615 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 284,486 | cpp | //--------------------------------------------------------------------------------------
// File: DXUT.cpp
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
#include "DXUT.h"
#define DXUT_MIN_WINDOW_SIZE_X 200
#define DXUT_MIN_WINDOW_SIZE_Y 200
#define DXUT_COUNTER_STAT_LENGTH 2048
#undef min // use __min instead inside this source file
#undef max // use __max instead inside this source file
#ifndef ARRAYSIZE
extern "C++" // templates cannot be declared to have 'C' linkage
template <typename T, size_t N>
char (*RtlpNumberOf( UNALIGNED T (&)[N] ))[N];
#define RTL_NUMBER_OF_V2(A) (sizeof(*RtlpNumberOf(A)))
#define ARRAYSIZE(A) RTL_NUMBER_OF_V2(A)
#endif
//--------------------------------------------------------------------------------------
// Thread safety
//--------------------------------------------------------------------------------------
CRITICAL_SECTION g_cs;
bool g_bThreadSafe = true;
//--------------------------------------------------------------------------------------
// Automatically enters & leaves the CS upon object creation/deletion
//--------------------------------------------------------------------------------------
class DXUTLock
{
public:
inline DXUTLock() { if( g_bThreadSafe ) EnterCriticalSection( &g_cs ); }
inline ~DXUTLock() { if( g_bThreadSafe ) LeaveCriticalSection( &g_cs ); }
};
//--------------------------------------------------------------------------------------
// Helper macros to build member functions that access member variables with thread safety
//--------------------------------------------------------------------------------------
#define SET_ACCESSOR( x, y ) inline void Set##y( x t ) { DXUTLock l; m_state.m_##y = t; };
#define GET_ACCESSOR( x, y ) inline x Get##y() { DXUTLock l; return m_state.m_##y; };
#define GET_SET_ACCESSOR( x, y ) SET_ACCESSOR( x, y ) GET_ACCESSOR( x, y )
#define SETP_ACCESSOR( x, y ) inline void Set##y( x* t ) { DXUTLock l; m_state.m_##y = *t; };
#define GETP_ACCESSOR( x, y ) inline x* Get##y() { DXUTLock l; return &m_state.m_##y; };
#define GETP_SETP_ACCESSOR( x, y ) SETP_ACCESSOR( x, y ) GETP_ACCESSOR( x, y )
//--------------------------------------------------------------------------------------
// Stores timer callback info
//--------------------------------------------------------------------------------------
struct DXUT_TIMER
{
LPDXUTCALLBACKTIMER pCallbackTimer;
void* pCallbackUserContext;
float fTimeoutInSecs;
float fCountdown;
bool bEnabled;
UINT nID;
};
//--------------------------------------------------------------------------------------
// D3D10 Counters
//--------------------------------------------------------------------------------------
struct D3D10_COUNTERS
{
float fGPUIdle;
float fVertexProcessing;
float fGeometryProcessing;
float fPixelProcessing;
float fOtherGPUProcessing;
float fHostAdapterBandwidthUtilization;
float fLocalVidmemBandwidthUtilization;
float fVertexThroughputUtilization;
float fTriangleSetupThroughputUtilization;
float fFillrateThroughputUtilization;
float fVSMemoryLimited;
float fVSComputationLimited;
float fGSMemoryLimited;
float fGSComputationLimited;
float fPSMemoryLimited;
float fPSComputationLimited;
float fPostTransformCacheHitRate;
float fTextureCacheHitRate;
};
//--------------------------------------------------------------------------------------
// Stores DXUT state and data access is done with thread safety (if g_bThreadSafe==true)
//--------------------------------------------------------------------------------------
class DXUTState
{
protected:
struct STATE
{
// D3D9 specific
IDirect3D9* m_D3D9; // the main D3D9 object
IDirect3DDevice9* m_D3D9Device; // the D3D9 rendering device
DXUTDeviceSettings* m_CurrentDeviceSettings; // current device settings
D3DSURFACE_DESC m_BackBufferSurfaceDesc9; // D3D9 back buffer surface description
D3DCAPS9 m_Caps; // D3D caps for current device
// D3D10 specific
bool m_D3D10Available; // if true, then D3D10 is available
IDXGIFactory* m_DXGIFactory; // DXGI Factory object
IDXGIAdapter* m_D3D10Adapter; // The DXGI adapter object for the D3D10 device
IDXGIOutput** m_D3D10OutputArray; // The array of output obj for the D3D10 adapter obj
UINT m_D3D10OutputArraySize; // Number of elements in m_D3D10OutputArray
ID3D10Device* m_D3D10Device; // the D3D10.0 rendering device
ID3D10Device1* m_D3D10Device1; // the D3D10.1 rendering device
IDXGISwapChain* m_D3D10SwapChain; // the D3D10 swapchain
ID3D10Texture2D* m_D3D10DepthStencil; // the D3D10 depth stencil texture (optional)
ID3D10DepthStencilView* m_D3D10DepthStencilView; // the D3D10 depth stencil view (optional)
ID3D10RenderTargetView* m_D3D10RenderTargetView; // the D3D10 render target view
DXGI_SURFACE_DESC m_BackBufferSurfaceDesc10; // D3D10 back buffer surface description
bool m_RenderingOccluded; // Rendering is occluded by another window
bool m_DoNotStoreBufferSize; // Do not store the buffer size on WM_SIZE messages
ID3D10Counter* m_Counter_GPUIdle;
ID3D10Counter* m_Counter_VertexProcessing;
ID3D10Counter* m_Counter_GeometryProcessing;
ID3D10Counter* m_Counter_PixelProcessing;
ID3D10Counter* m_Counter_OtherGPUProcessing;
ID3D10Counter* m_Counter_HostAdapterBandwidthUtilization;
ID3D10Counter* m_Counter_LocalVidmemBandwidthUtilization;
ID3D10Counter* m_Counter_VertexThroughputUtilization;
ID3D10Counter* m_Counter_TriangleSetupThroughputUtilization;
ID3D10Counter* m_Counter_FillrateThrougputUtilization;
ID3D10Counter* m_Counter_VSMemoryLimited;
ID3D10Counter* m_Counter_VSComputationLimited;
ID3D10Counter* m_Counter_GSMemoryLimited;
ID3D10Counter* m_Counter_GSComputationLimited;
ID3D10Counter* m_Counter_PSMemoryLimited;
ID3D10Counter* m_Counter_PSComputationLimited;
ID3D10Counter* m_Counter_PostTransformCacheHitRate;
ID3D10Counter* m_Counter_TextureCacheHitRate;
D3D10_COUNTERS m_CounterData;
// General
HWND m_HWNDFocus; // the main app focus window
HWND m_HWNDDeviceFullScreen; // the main app device window in fullscreen mode
HWND m_HWNDDeviceWindowed; // the main app device window in windowed mode
HMONITOR m_AdapterMonitor; // the monitor of the adapter
HMENU m_Menu; // handle to menu
UINT m_FullScreenBackBufferWidthAtModeChange; // back buffer size of fullscreen mode right before switching to windowed mode. Used to restore to same resolution when toggling back to fullscreen
UINT m_FullScreenBackBufferHeightAtModeChange; // back buffer size of fullscreen mode right before switching to windowed mode. Used to restore to same resolution when toggling back to fullscreen
UINT m_WindowBackBufferWidthAtModeChange; // back buffer size of windowed mode right before switching to fullscreen mode. Used to restore to same resolution when toggling back to windowed mode
UINT m_WindowBackBufferHeightAtModeChange; // back buffer size of windowed mode right before switching to fullscreen mode. Used to restore to same resolution when toggling back to windowed mode
DWORD m_WindowedStyleAtModeChange; // window style
WINDOWPLACEMENT m_WindowedPlacement;// record of windowed HWND position/show state/etc
bool m_TopmostWhileWindowed; // if true, the windowed HWND is topmost
bool m_Minimized; // if true, the HWND is minimized
bool m_Maximized; // if true, the HWND is maximized
bool m_MinimizedWhileFullscreen; // if true, the HWND is minimized due to a focus switch away when fullscreen mode
bool m_IgnoreSizeChange; // if true, DXUT won't reset the device upon HWND size change
double m_Time; // current time in seconds
double m_AbsoluteTime; // absolute time in seconds
float m_ElapsedTime; // time elapsed since last frame
HINSTANCE m_HInstance; // handle to the app instance
double m_LastStatsUpdateTime; // last time the stats were updated
DWORD m_LastStatsUpdateFrames; // frames count since last time the stats were updated
float m_FPS; // frames per second
int m_CurrentFrameNumber; // the current frame number
HHOOK m_KeyboardHook; // handle to keyboard hook
bool m_AllowShortcutKeysWhenFullscreen; // if true, when fullscreen enable shortcut keys (Windows keys, StickyKeys shortcut, ToggleKeys shortcut, FilterKeys shortcut)
bool m_AllowShortcutKeysWhenWindowed; // if true, when windowed enable shortcut keys (Windows keys, StickyKeys shortcut, ToggleKeys shortcut, FilterKeys shortcut)
bool m_AllowShortcutKeys; // if true, then shortcut keys are currently disabled (Windows key, etc)
bool m_CallDefWindowProc; // if true, DXUTStaticWndProc will call DefWindowProc for unhandled messages. Applications rendering to a dialog may need to set this to false.
STICKYKEYS m_StartupStickyKeys; // StickyKey settings upon startup so they can be restored later
TOGGLEKEYS m_StartupToggleKeys; // ToggleKey settings upon startup so they can be restored later
FILTERKEYS m_StartupFilterKeys; // FilterKey settings upon startup so they can be restored later
bool m_AppSupportsD3D9Override; // true if app sets via DXUTSetD3DVersionSupport()
bool m_AppSupportsD3D10Override; // true if app sets via DXUTSetD3DVersionSupport()
bool m_UseD3DVersionOverride; // true if the app ever calls DXUTSetD3DVersionSupport()
bool m_HandleEscape; // if true, then DXUT will handle escape to quit
bool m_HandleAltEnter; // if true, then DXUT will handle alt-enter to toggle fullscreen
bool m_HandlePause; // if true, then DXUT will handle pause to toggle time pausing
bool m_ShowMsgBoxOnError; // if true, then msgboxes are displayed upon errors
bool m_NoStats; // if true, then DXUTGetFrameStats() and DXUTGetDeviceStats() will return blank strings
bool m_ClipCursorWhenFullScreen; // if true, then DXUT will keep the cursor from going outside the window when full screen
bool m_ShowCursorWhenFullScreen; // if true, then DXUT will show a cursor when full screen
bool m_ConstantFrameTime; // if true, then elapsed frame time will always be 0.05f seconds which is good for debugging or automated capture
float m_TimePerFrame; // the constant time per frame in seconds, only valid if m_ConstantFrameTime==true
bool m_WireframeMode; // if true, then D3DRS_FILLMODE==D3DFILL_WIREFRAME else D3DRS_FILLMODE==D3DFILL_SOLID
bool m_AutoChangeAdapter; // if true, then the adapter will automatically change if the window is different monitor
bool m_WindowCreatedWithDefaultPositions; // if true, then CW_USEDEFAULT was used and the window should be moved to the right adapter
int m_ExitCode; // the exit code to be returned to the command line
bool m_DXUTInited; // if true, then DXUTInit() has succeeded
bool m_WindowCreated; // if true, then DXUTCreateWindow() or DXUTSetWindow() has succeeded
bool m_DeviceCreated; // if true, then DXUTCreateDevice() or DXUTSetD3D*Device() has succeeded
bool m_DXUTInitCalled; // if true, then DXUTInit() was called
bool m_WindowCreateCalled; // if true, then DXUTCreateWindow() or DXUTSetWindow() was called
bool m_DeviceCreateCalled; // if true, then DXUTCreateDevice() or DXUTSetD3D*Device() was called
bool m_DeviceObjectsCreated; // if true, then DeviceCreated callback has been called (if non-NULL)
bool m_DeviceObjectsReset; // if true, then DeviceReset callback has been called (if non-NULL)
bool m_InsideDeviceCallback; // if true, then the framework is inside an app device callback
bool m_InsideMainloop; // if true, then the framework is inside the main loop
bool m_Active; // if true, then the app is the active top level window
bool m_TimePaused; // if true, then time is paused
bool m_RenderingPaused; // if true, then rendering is paused
int m_PauseRenderingCount; // pause rendering ref count
int m_PauseTimeCount; // pause time ref count
bool m_DeviceLost; // if true, then the device is lost and needs to be reset
bool m_NotifyOnMouseMove; // if true, include WM_MOUSEMOVE in mousecallback
bool m_Automation; // if true, automation is enabled
bool m_InSizeMove; // if true, app is inside a WM_ENTERSIZEMOVE
UINT m_TimerLastID; // last ID of the DXUT timer
int m_OverrideForceAPI; // if != -1, then override to use this Direct3D API version
int m_OverrideAdapterOrdinal; // if != -1, then override to use this adapter ordinal
bool m_OverrideWindowed; // if true, then force to start windowed
int m_OverrideOutput; // if != -1, then override to use the particular output on the adapter
bool m_OverrideFullScreen; // if true, then force to start full screen
int m_OverrideStartX; // if != -1, then override to this X position of the window
int m_OverrideStartY; // if != -1, then override to this Y position of the window
int m_OverrideWidth; // if != 0, then override to this width
int m_OverrideHeight; // if != 0, then override to this height
bool m_OverrideForceHAL; // if true, then force to HAL device (failing if one doesn't exist)
bool m_OverrideForceREF; // if true, then force to REF device (failing if one doesn't exist)
bool m_OverrideForcePureHWVP; // if true, then force to use pure HWVP (failing if device doesn't support it)
bool m_OverrideForceHWVP; // if true, then force to use HWVP (failing if device doesn't support it)
bool m_OverrideForceSWVP; // if true, then force to use SWVP
bool m_OverrideConstantFrameTime; // if true, then force to constant frame time
float m_OverrideConstantTimePerFrame; // the constant time per frame in seconds if m_OverrideConstantFrameTime==true
int m_OverrideQuitAfterFrame; // if != 0, then it will force the app to quit after that frame
int m_OverrideForceVsync; // if == 0, then it will force the app to use D3DPRESENT_INTERVAL_IMMEDIATE, if == 1 force use of D3DPRESENT_INTERVAL_DEFAULT
bool m_OverrideRelaunchMCE; // if true, then force relaunch of MCE at exit
bool m_AppCalledWasKeyPressed; // true if the app ever calls DXUTWasKeyPressed(). Allows for optimzation
bool m_ReleasingSwapChain; // if true, the app is releasing its swapchain
bool m_IsInGammaCorrectMode; // Tell DXUTRes and DXUTMisc that we are in gamma correct mode
LPDXUTCALLBACKMODIFYDEVICESETTINGS m_ModifyDeviceSettingsFunc; // modify Direct3D device settings callback
LPDXUTCALLBACKDEVICEREMOVED m_DeviceRemovedFunc; // Direct3D device removed callback
LPDXUTCALLBACKFRAMEMOVE m_FrameMoveFunc; // frame move callback
LPDXUTCALLBACKKEYBOARD m_KeyboardFunc; // keyboard callback
LPDXUTCALLBACKMOUSE m_MouseFunc; // mouse callback
LPDXUTCALLBACKMSGPROC m_WindowMsgFunc; // window messages callback
LPDXUTCALLBACKISD3D9DEVICEACCEPTABLE m_IsD3D9DeviceAcceptableFunc; // D3D9 is device acceptable callback
LPDXUTCALLBACKD3D9DEVICECREATED m_D3D9DeviceCreatedFunc; // D3D9 device created callback
LPDXUTCALLBACKD3D9DEVICERESET m_D3D9DeviceResetFunc; // D3D9 device reset callback
LPDXUTCALLBACKD3D9DEVICELOST m_D3D9DeviceLostFunc; // D3D9 device lost callback
LPDXUTCALLBACKD3D9DEVICEDESTROYED m_D3D9DeviceDestroyedFunc; // D3D9 device destroyed callback
LPDXUTCALLBACKD3D9FRAMERENDER m_D3D9FrameRenderFunc; // D3D9 frame render callback
LPDXUTCALLBACKISD3D10DEVICEACCEPTABLE m_IsD3D10DeviceAcceptableFunc; // D3D10 is device acceptable callback
LPDXUTCALLBACKD3D10DEVICECREATED m_D3D10DeviceCreatedFunc; // D3D10 device created callback
LPDXUTCALLBACKD3D10SWAPCHAINRESIZED m_D3D10SwapChainResizedFunc; // D3D10 SwapChain reset callback
LPDXUTCALLBACKD3D10SWAPCHAINRELEASING m_D3D10SwapChainReleasingFunc; // D3D10 SwapChain lost callback
LPDXUTCALLBACKD3D10DEVICEDESTROYED m_D3D10DeviceDestroyedFunc; // D3D10 device destroyed callback
LPDXUTCALLBACKD3D10FRAMERENDER m_D3D10FrameRenderFunc; // D3D10 frame render callback
void* m_ModifyDeviceSettingsFuncUserContext; // user context for modify Direct3D device settings callback
void* m_DeviceRemovedFuncUserContext; // user context for Direct3D device removed callback
void* m_FrameMoveFuncUserContext; // user context for frame move callback
void* m_KeyboardFuncUserContext; // user context for keyboard callback
void* m_MouseFuncUserContext; // user context for mouse callback
void* m_WindowMsgFuncUserContext; // user context for window messages callback
void* m_IsD3D9DeviceAcceptableFuncUserContext; // user context for is D3D9 device acceptable callback
void* m_D3D9DeviceCreatedFuncUserContext; // user context for D3D9 device created callback
void* m_D3D9DeviceResetFuncUserContext; // user context for D3D9 device reset callback
void* m_D3D9DeviceLostFuncUserContext; // user context for D3D9 device lost callback
void* m_D3D9DeviceDestroyedFuncUserContext; // user context for D3D9 device destroyed callback
void* m_D3D9FrameRenderFuncUserContext; // user context for D3D9 frame render callback
void* m_IsD3D10DeviceAcceptableFuncUserContext; // user context for is D3D10 device acceptable callback
void* m_D3D10DeviceCreatedFuncUserContext; // user context for D3D10 device created callback
void* m_D3D10SwapChainResizedFuncUserContext; // user context for D3D10 SwapChain resized callback
void* m_D3D10SwapChainReleasingFuncUserContext; // user context for D3D10 SwapChain releasing callback
void* m_D3D10DeviceDestroyedFuncUserContext; // user context for D3D10 device destroyed callback
void* m_D3D10FrameRenderFuncUserContext; // user context for D3D10 frame render callback
bool m_Keys[256]; // array of key state
bool m_LastKeys[256]; // array of last key state
bool m_MouseButtons[5]; // array of mouse states
CGrowableArray<DXUT_TIMER>* m_TimerList; // list of DXUT_TIMER structs
WCHAR m_StaticFrameStats[256]; // static part of frames stats
WCHAR m_FPSStats[64]; // fps stats
WCHAR m_FrameStats[256]; // frame stats (fps, width, etc)
WCHAR m_DeviceStats[256]; // device stats (description, device type, etc)
WCHAR m_D3D10CounterStats[DXUT_COUNTER_STAT_LENGTH]; // d3d10 pipeline statistics
WCHAR m_WindowTitle[256]; // window title
};
STATE m_state;
public:
DXUTState() { Create(); }
~DXUTState() { Destroy(); }
void Create()
{
g_bThreadSafe = true;
InitializeCriticalSectionAndSpinCount( &g_cs, 1000 );
ZeroMemory( &m_state, sizeof(STATE) );
m_state.m_OverrideStartX = -1;
m_state.m_OverrideStartY = -1;
m_state.m_OverrideForceAPI = -1;
m_state.m_OverrideAdapterOrdinal = -1;
m_state.m_OverrideOutput = -1;
m_state.m_OverrideForceVsync = 0;
m_state.m_AutoChangeAdapter = true;
m_state.m_ShowMsgBoxOnError = true;
m_state.m_AllowShortcutKeysWhenWindowed = true;
m_state.m_Active = true;
m_state.m_CallDefWindowProc = true;
m_state.m_HandleEscape = true;
m_state.m_HandleAltEnter = true;
m_state.m_HandlePause = true;
m_state.m_IsInGammaCorrectMode = false;
m_state.m_CounterData.fGPUIdle = -1.0f;
m_state.m_CounterData.fVertexProcessing = -1.0f;
m_state.m_CounterData.fGeometryProcessing = -1.0f;
m_state.m_CounterData.fPixelProcessing = -1.0f;
m_state.m_CounterData.fOtherGPUProcessing = -1.0f;
m_state.m_CounterData.fHostAdapterBandwidthUtilization = -1.0f;
m_state.m_CounterData.fLocalVidmemBandwidthUtilization = -1.0f;
m_state.m_CounterData.fVertexThroughputUtilization = -1.0f;
m_state.m_CounterData.fTriangleSetupThroughputUtilization = -1.0f;
m_state.m_CounterData.fFillrateThroughputUtilization = -1.0f;
m_state.m_CounterData.fVSMemoryLimited = -1.0f;
m_state.m_CounterData.fVSComputationLimited = -1.0f;
m_state.m_CounterData.fGSMemoryLimited = -1.0f;
m_state.m_CounterData.fGSComputationLimited = -1.0f;
m_state.m_CounterData.fPSMemoryLimited = -1.0f;
m_state.m_CounterData.fPSComputationLimited = -1.0f;
m_state.m_CounterData.fPostTransformCacheHitRate = -1.0f;
m_state.m_CounterData.fTextureCacheHitRate = -1.0f;
}
void Destroy()
{
SAFE_DELETE( m_state.m_TimerList );
DXUTShutdown();
DeleteCriticalSection( &g_cs );
}
// Macros to define access functions for thread safe access into m_state
// D3D9 specific
GET_SET_ACCESSOR( IDirect3D9*, D3D9 );
GET_SET_ACCESSOR( IDirect3DDevice9*, D3D9Device );
GET_SET_ACCESSOR( DXUTDeviceSettings*, CurrentDeviceSettings );
GETP_SETP_ACCESSOR( D3DSURFACE_DESC, BackBufferSurfaceDesc9 );
GETP_SETP_ACCESSOR( D3DCAPS9, Caps );
// D3D10 specific
GET_SET_ACCESSOR( bool, D3D10Available );
GET_SET_ACCESSOR( IDXGIFactory*, DXGIFactory );
GET_SET_ACCESSOR( IDXGIAdapter*, D3D10Adapter );
GET_SET_ACCESSOR( IDXGIOutput**, D3D10OutputArray );
GET_SET_ACCESSOR( UINT, D3D10OutputArraySize );
GET_SET_ACCESSOR( ID3D10Device*, D3D10Device );
GET_SET_ACCESSOR( ID3D10Device1*, D3D10Device1 );
GET_SET_ACCESSOR( IDXGISwapChain*, D3D10SwapChain );
GET_SET_ACCESSOR( ID3D10Texture2D*, D3D10DepthStencil );
GET_SET_ACCESSOR( ID3D10DepthStencilView*, D3D10DepthStencilView );
GET_SET_ACCESSOR( ID3D10RenderTargetView*, D3D10RenderTargetView );
GETP_SETP_ACCESSOR( DXGI_SURFACE_DESC, BackBufferSurfaceDesc10 );
GET_SET_ACCESSOR( bool, RenderingOccluded );
GET_SET_ACCESSOR( bool, DoNotStoreBufferSize );
GET_SET_ACCESSOR( ID3D10Counter*, Counter_GPUIdle );
GET_SET_ACCESSOR( ID3D10Counter*, Counter_VertexProcessing );
GET_SET_ACCESSOR( ID3D10Counter*, Counter_GeometryProcessing );
GET_SET_ACCESSOR( ID3D10Counter*, Counter_PixelProcessing );
GET_SET_ACCESSOR( ID3D10Counter*, Counter_OtherGPUProcessing );
GET_SET_ACCESSOR( ID3D10Counter*, Counter_HostAdapterBandwidthUtilization );
GET_SET_ACCESSOR( ID3D10Counter*, Counter_LocalVidmemBandwidthUtilization );
GET_SET_ACCESSOR( ID3D10Counter*, Counter_VertexThroughputUtilization );
GET_SET_ACCESSOR( ID3D10Counter*, Counter_TriangleSetupThroughputUtilization );
GET_SET_ACCESSOR( ID3D10Counter*, Counter_FillrateThrougputUtilization );
GET_SET_ACCESSOR( ID3D10Counter*, Counter_VSMemoryLimited );
GET_SET_ACCESSOR( ID3D10Counter*, Counter_VSComputationLimited );
GET_SET_ACCESSOR( ID3D10Counter*, Counter_GSMemoryLimited );
GET_SET_ACCESSOR( ID3D10Counter*, Counter_GSComputationLimited );
GET_SET_ACCESSOR( ID3D10Counter*, Counter_PSMemoryLimited );
GET_SET_ACCESSOR( ID3D10Counter*, Counter_PSComputationLimited );
GET_SET_ACCESSOR( ID3D10Counter*, Counter_PostTransformCacheHitRate );
GET_SET_ACCESSOR( ID3D10Counter*, Counter_TextureCacheHitRate );
GETP_SETP_ACCESSOR( D3D10_COUNTERS, CounterData );
GET_SET_ACCESSOR( HWND, HWNDFocus );
GET_SET_ACCESSOR( HWND, HWNDDeviceFullScreen );
GET_SET_ACCESSOR( HWND, HWNDDeviceWindowed );
GET_SET_ACCESSOR( HMONITOR, AdapterMonitor );
GET_SET_ACCESSOR( HMENU, Menu );
GET_SET_ACCESSOR( UINT, FullScreenBackBufferWidthAtModeChange );
GET_SET_ACCESSOR( UINT, FullScreenBackBufferHeightAtModeChange );
GET_SET_ACCESSOR( UINT, WindowBackBufferWidthAtModeChange );
GET_SET_ACCESSOR( UINT, WindowBackBufferHeightAtModeChange );
GETP_SETP_ACCESSOR( WINDOWPLACEMENT, WindowedPlacement );
GET_SET_ACCESSOR( DWORD, WindowedStyleAtModeChange );
GET_SET_ACCESSOR( bool, TopmostWhileWindowed );
GET_SET_ACCESSOR( bool, Minimized );
GET_SET_ACCESSOR( bool, Maximized );
GET_SET_ACCESSOR( bool, MinimizedWhileFullscreen );
GET_SET_ACCESSOR( bool, IgnoreSizeChange );
GET_SET_ACCESSOR( double, Time );
GET_SET_ACCESSOR( double, AbsoluteTime );
GET_SET_ACCESSOR( float, ElapsedTime );
GET_SET_ACCESSOR( HINSTANCE, HInstance );
GET_SET_ACCESSOR( double, LastStatsUpdateTime );
GET_SET_ACCESSOR( DWORD, LastStatsUpdateFrames );
GET_SET_ACCESSOR( float, FPS );
GET_SET_ACCESSOR( int, CurrentFrameNumber );
GET_SET_ACCESSOR( HHOOK, KeyboardHook );
GET_SET_ACCESSOR( bool, AllowShortcutKeysWhenFullscreen );
GET_SET_ACCESSOR( bool, AllowShortcutKeysWhenWindowed );
GET_SET_ACCESSOR( bool, AllowShortcutKeys );
GET_SET_ACCESSOR( bool, CallDefWindowProc );
GET_SET_ACCESSOR( STICKYKEYS, StartupStickyKeys );
GET_SET_ACCESSOR( TOGGLEKEYS, StartupToggleKeys );
GET_SET_ACCESSOR( FILTERKEYS, StartupFilterKeys );
GET_SET_ACCESSOR( bool, AppSupportsD3D9Override );
GET_SET_ACCESSOR( bool, AppSupportsD3D10Override );
GET_SET_ACCESSOR( bool, UseD3DVersionOverride );
GET_SET_ACCESSOR( bool, HandleEscape );
GET_SET_ACCESSOR( bool, HandleAltEnter );
GET_SET_ACCESSOR( bool, HandlePause );
GET_SET_ACCESSOR( bool, ShowMsgBoxOnError );
GET_SET_ACCESSOR( bool, NoStats );
GET_SET_ACCESSOR( bool, ClipCursorWhenFullScreen );
GET_SET_ACCESSOR( bool, ShowCursorWhenFullScreen );
GET_SET_ACCESSOR( bool, ConstantFrameTime );
GET_SET_ACCESSOR( float, TimePerFrame );
GET_SET_ACCESSOR( bool, WireframeMode );
GET_SET_ACCESSOR( bool, AutoChangeAdapter );
GET_SET_ACCESSOR( bool, WindowCreatedWithDefaultPositions );
GET_SET_ACCESSOR( int, ExitCode );
GET_SET_ACCESSOR( bool, DXUTInited );
GET_SET_ACCESSOR( bool, WindowCreated );
GET_SET_ACCESSOR( bool, DeviceCreated );
GET_SET_ACCESSOR( bool, DXUTInitCalled );
GET_SET_ACCESSOR( bool, WindowCreateCalled );
GET_SET_ACCESSOR( bool, DeviceCreateCalled );
GET_SET_ACCESSOR( bool, InsideDeviceCallback );
GET_SET_ACCESSOR( bool, InsideMainloop );
GET_SET_ACCESSOR( bool, DeviceObjectsCreated );
GET_SET_ACCESSOR( bool, DeviceObjectsReset );
GET_SET_ACCESSOR( bool, Active );
GET_SET_ACCESSOR( bool, RenderingPaused );
GET_SET_ACCESSOR( bool, TimePaused );
GET_SET_ACCESSOR( int, PauseRenderingCount );
GET_SET_ACCESSOR( int, PauseTimeCount );
GET_SET_ACCESSOR( bool, DeviceLost );
GET_SET_ACCESSOR( bool, NotifyOnMouseMove );
GET_SET_ACCESSOR( bool, Automation );
GET_SET_ACCESSOR( bool, InSizeMove );
GET_SET_ACCESSOR( UINT, TimerLastID );
GET_SET_ACCESSOR( bool, AppCalledWasKeyPressed );
GET_SET_ACCESSOR( int, OverrideForceAPI );
GET_SET_ACCESSOR( int, OverrideAdapterOrdinal );
GET_SET_ACCESSOR( bool, OverrideWindowed );
GET_SET_ACCESSOR( int, OverrideOutput );
GET_SET_ACCESSOR( bool, OverrideFullScreen );
GET_SET_ACCESSOR( int, OverrideStartX );
GET_SET_ACCESSOR( int, OverrideStartY );
GET_SET_ACCESSOR( int, OverrideWidth );
GET_SET_ACCESSOR( int, OverrideHeight );
GET_SET_ACCESSOR( bool, OverrideForceHAL );
GET_SET_ACCESSOR( bool, OverrideForceREF );
GET_SET_ACCESSOR( bool, OverrideForcePureHWVP );
GET_SET_ACCESSOR( bool, OverrideForceHWVP );
GET_SET_ACCESSOR( bool, OverrideForceSWVP );
GET_SET_ACCESSOR( bool, OverrideConstantFrameTime );
GET_SET_ACCESSOR( float, OverrideConstantTimePerFrame );
GET_SET_ACCESSOR( int, OverrideQuitAfterFrame );
GET_SET_ACCESSOR( int, OverrideForceVsync );
GET_SET_ACCESSOR( bool, OverrideRelaunchMCE );
GET_SET_ACCESSOR( bool, ReleasingSwapChain );
GET_SET_ACCESSOR( bool, IsInGammaCorrectMode );
GET_SET_ACCESSOR( LPDXUTCALLBACKMODIFYDEVICESETTINGS, ModifyDeviceSettingsFunc );
GET_SET_ACCESSOR( LPDXUTCALLBACKDEVICEREMOVED, DeviceRemovedFunc );
GET_SET_ACCESSOR( LPDXUTCALLBACKFRAMEMOVE, FrameMoveFunc );
GET_SET_ACCESSOR( LPDXUTCALLBACKKEYBOARD, KeyboardFunc );
GET_SET_ACCESSOR( LPDXUTCALLBACKMOUSE, MouseFunc );
GET_SET_ACCESSOR( LPDXUTCALLBACKMSGPROC, WindowMsgFunc );
GET_SET_ACCESSOR( LPDXUTCALLBACKISD3D9DEVICEACCEPTABLE, IsD3D9DeviceAcceptableFunc );
GET_SET_ACCESSOR( LPDXUTCALLBACKD3D9DEVICECREATED, D3D9DeviceCreatedFunc );
GET_SET_ACCESSOR( LPDXUTCALLBACKD3D9DEVICERESET, D3D9DeviceResetFunc );
GET_SET_ACCESSOR( LPDXUTCALLBACKD3D9DEVICELOST, D3D9DeviceLostFunc );
GET_SET_ACCESSOR( LPDXUTCALLBACKD3D9DEVICEDESTROYED, D3D9DeviceDestroyedFunc );
GET_SET_ACCESSOR( LPDXUTCALLBACKD3D9FRAMERENDER, D3D9FrameRenderFunc );
GET_SET_ACCESSOR( LPDXUTCALLBACKISD3D10DEVICEACCEPTABLE, IsD3D10DeviceAcceptableFunc );
GET_SET_ACCESSOR( LPDXUTCALLBACKD3D10DEVICECREATED, D3D10DeviceCreatedFunc );
GET_SET_ACCESSOR( LPDXUTCALLBACKD3D10SWAPCHAINRESIZED, D3D10SwapChainResizedFunc );
GET_SET_ACCESSOR( LPDXUTCALLBACKD3D10SWAPCHAINRELEASING, D3D10SwapChainReleasingFunc );
GET_SET_ACCESSOR( LPDXUTCALLBACKD3D10DEVICEDESTROYED, D3D10DeviceDestroyedFunc );
GET_SET_ACCESSOR( LPDXUTCALLBACKD3D10FRAMERENDER, D3D10FrameRenderFunc );
GET_SET_ACCESSOR( void*, ModifyDeviceSettingsFuncUserContext );
GET_SET_ACCESSOR( void*, DeviceRemovedFuncUserContext );
GET_SET_ACCESSOR( void*, FrameMoveFuncUserContext );
GET_SET_ACCESSOR( void*, KeyboardFuncUserContext );
GET_SET_ACCESSOR( void*, MouseFuncUserContext );
GET_SET_ACCESSOR( void*, WindowMsgFuncUserContext );
GET_SET_ACCESSOR( void*, IsD3D9DeviceAcceptableFuncUserContext );
GET_SET_ACCESSOR( void*, D3D9DeviceCreatedFuncUserContext );
GET_SET_ACCESSOR( void*, D3D9DeviceResetFuncUserContext );
GET_SET_ACCESSOR( void*, D3D9DeviceLostFuncUserContext );
GET_SET_ACCESSOR( void*, D3D9DeviceDestroyedFuncUserContext );
GET_SET_ACCESSOR( void*, D3D9FrameRenderFuncUserContext );
GET_SET_ACCESSOR( void*, IsD3D10DeviceAcceptableFuncUserContext );
GET_SET_ACCESSOR( void*, D3D10DeviceCreatedFuncUserContext );
GET_SET_ACCESSOR( void*, D3D10DeviceDestroyedFuncUserContext );
GET_SET_ACCESSOR( void*, D3D10SwapChainResizedFuncUserContext );
GET_SET_ACCESSOR( void*, D3D10SwapChainReleasingFuncUserContext );
GET_SET_ACCESSOR( void*, D3D10FrameRenderFuncUserContext );
GET_SET_ACCESSOR( CGrowableArray<DXUT_TIMER>*, TimerList );
GET_ACCESSOR( bool*, Keys );
GET_ACCESSOR( bool*, LastKeys );
GET_ACCESSOR( bool*, MouseButtons );
GET_ACCESSOR( WCHAR*, StaticFrameStats );
GET_ACCESSOR( WCHAR*, FPSStats );
GET_ACCESSOR( WCHAR*, FrameStats );
GET_ACCESSOR( WCHAR*, DeviceStats );
GET_ACCESSOR( WCHAR*, D3D10CounterStats );
GET_ACCESSOR( WCHAR*, WindowTitle );
};
//--------------------------------------------------------------------------------------
// Global state
//--------------------------------------------------------------------------------------
DXUTState* g_pDXUTState = NULL;
HRESULT WINAPI DXUTCreateState()
{
if( g_pDXUTState == NULL )
{
g_pDXUTState = new DXUTState;
if( NULL == g_pDXUTState )
return E_OUTOFMEMORY;
}
return S_OK;
}
void WINAPI DXUTDestroyState()
{
SAFE_DELETE( g_pDXUTState );
}
class DXUTMemoryHelper
{
public:
DXUTMemoryHelper() { DXUTCreateState(); }
~DXUTMemoryHelper() { DXUTDestroyState(); }
};
DXUTState& GetDXUTState()
{
// This class will auto create the memory when its first accessed and delete it after the program exits WinMain.
// However the application can also call DXUTCreateState() & DXUTDestroyState() independantly if its wants
static DXUTMemoryHelper memory;
return *g_pDXUTState;
}
//--------------------------------------------------------------------------------------
// Internal functions forward declarations
//--------------------------------------------------------------------------------------
void DXUTParseCommandLine( WCHAR* strCommandLine );
bool DXUTIsNextArg( WCHAR*& strCmdLine, WCHAR* strArg );
bool DXUTGetCmdParam( WCHAR*& strCmdLine, WCHAR* strFlag );
void DXUTAllowShortcutKeys( bool bAllowKeys );
void DXUTUpdateStaticFrameStats();
void DXUTUpdateFrameStats();
void DXUTUpdateD3D10PipelineStats();
LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam );
void DXUTHandleTimers();
void DXUTDisplayErrorMessage( HRESULT hr );
int DXUTMapButtonToArrayIndex( BYTE vButton );
HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, IDirect3DDevice9* pd3d9DeviceFromApp, ID3D10Device* pd3d10DeviceFromApp, bool bForceRecreate, bool bClipWindowToSingleAdapter );
bool DXUTCanDeviceBeReset( DXUTDeviceSettings *pOldDeviceSettings, DXUTDeviceSettings *pNewDeviceSettings, IDirect3DDevice9 *pd3d9DeviceFromApp, ID3D10Device *pd3d10DeviceFromApp );
HRESULT DXUTDelayLoadDXGI();
HRESULT DXUTDelayLoadD3D9();
void DXUTUpdateDeviceSettingsWithOverrides( DXUTDeviceSettings* pDeviceSettings );
void DXUTCheckForDXGIFullScreenSwitch();
void DXUTResizeDXGIBuffers( UINT Width, UINT Height, BOOL bFullscreen );
void DXUTCheckForDXGIBufferChange();
void DXUTCheckForWindowSizeChange();
void DXUTCheckForWindowChangingMonitors();
void DXUTCleanup3DEnvironment( bool bReleaseSettings );
HMONITOR DXUTGetMonitorFromAdapter( DXUTDeviceSettings* pDeviceSettings );
HRESULT DXUTGetAdapterOrdinalFromMonitor( HMONITOR hMonitor, UINT* pAdapterOrdinal );
HRESULT DXUTGetOutputOrdinalFromMonitor( HMONITOR hMonitor, UINT* pOutputOrdinal );
HRESULT DXUTHandleDeviceRemoved();
void DXUTUpdateBackBufferDesc();
void DXUTSetupCursor();
HRESULT DXUTCreate3DEnvironment9( IDirect3DDevice9* pd3dDeviceFromApp );
HRESULT DXUTReset3DEnvironment9();
void DXUTRender3DEnvironment9();
void DXUTCleanup3DEnvironment9( bool bReleaseSettings = true );
HRESULT DXUTSetD3D9DeviceCursor( IDirect3DDevice9* pd3dDevice, HCURSOR hCursor, bool bAddWatermark );
void DXUTUpdateD3D9DeviceStats( D3DDEVTYPE DeviceType, DWORD BehaviorFlags, D3DADAPTER_IDENTIFIER9* pAdapterIdentifier );
HRESULT DXUTFindD3D9AdapterFormat( UINT AdapterOrdinal, D3DDEVTYPE DeviceType, D3DFORMAT BackBufferFormat, BOOL Windowed, D3DFORMAT* pAdapterFormat );
HRESULT DXUTSetupD3D10Views( ID3D10Device* pd3dDevice, DXUTDeviceSettings* pDeviceSettings );
HRESULT DXUTCreate3DEnvironment10( ID3D10Device* pd3dDeviceFromApp );
HRESULT DXUTReset3DEnvironment10();
void DXUTRender3DEnvironment10();
void DXUTCleanup3DEnvironment10( bool bReleaseSettings = true );
void DXUTCreateD3D10Counters( ID3D10Device* pd3dDevice );
void DXUTDestroyD3D10Counters();
void DXUTStartPerformanceCounters();
void DXUTStopPerformanceCounters();
void DXUTUpdateD3D10CounterStats();
void DXUTUpdateD3D10DeviceStats( D3D10_DRIVER_TYPE DeviceType, DXGI_ADAPTER_DESC* pAdapterDesc );
//--------------------------------------------------------------------------------------
// Internal helper functions
//--------------------------------------------------------------------------------------
bool DXUTIsD3D9( DXUTDeviceSettings* pDeviceSettings ) { return (pDeviceSettings && pDeviceSettings->ver == DXUT_D3D9_DEVICE ); };
bool DXUTIsCurrentDeviceD3D9() { DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); return DXUTIsD3D9(pDeviceSettings); };
UINT DXUTGetBackBufferWidthFromDS( DXUTDeviceSettings* pNewDeviceSettings ) { return DXUTIsD3D9(pNewDeviceSettings) ? pNewDeviceSettings->d3d9.pp.BackBufferWidth : pNewDeviceSettings->d3d10.sd.BufferDesc.Width; }
UINT DXUTGetBackBufferHeightFromDS( DXUTDeviceSettings* pNewDeviceSettings ) { return DXUTIsD3D9(pNewDeviceSettings) ? pNewDeviceSettings->d3d9.pp.BackBufferHeight : pNewDeviceSettings->d3d10.sd.BufferDesc.Height; }
bool DXUTGetIsWindowedFromDS( DXUTDeviceSettings* pNewDeviceSettings ) { if (!pNewDeviceSettings) return true; return ((DXUTIsD3D9(pNewDeviceSettings) ? pNewDeviceSettings->d3d9.pp.Windowed : pNewDeviceSettings->d3d10.sd.Windowed) == 1); }
//--------------------------------------------------------------------------------------
// External state access functions
//--------------------------------------------------------------------------------------
IDirect3DDevice9* WINAPI DXUTGetD3D9Device() { return GetDXUTState().GetD3D9Device(); }
const D3DSURFACE_DESC* WINAPI DXUTGetD3D9BackBufferSurfaceDesc() { return GetDXUTState().GetBackBufferSurfaceDesc9(); }
const D3DCAPS9* WINAPI DXUTGetD3D9DeviceCaps() { return GetDXUTState().GetCaps(); }
ID3D10Device* WINAPI DXUTGetD3D10Device() { return GetDXUTState().GetD3D10Device(); }
ID3D10Device1* WINAPI DXUTGetD3D10Device1() { return GetDXUTState().GetD3D10Device1(); }
IDXGISwapChain* WINAPI DXUTGetDXGISwapChain() { return GetDXUTState().GetD3D10SwapChain(); }
ID3D10RenderTargetView* WINAPI DXUTGetD3D10RenderTargetView() { return GetDXUTState().GetD3D10RenderTargetView(); }
ID3D10DepthStencilView* WINAPI DXUTGetD3D10DepthStencilView() { return GetDXUTState().GetD3D10DepthStencilView(); }
const DXGI_SURFACE_DESC* WINAPI DXUTGetDXGIBackBufferSurfaceDesc() { return GetDXUTState().GetBackBufferSurfaceDesc10(); }
HINSTANCE WINAPI DXUTGetHINSTANCE() { return GetDXUTState().GetHInstance(); }
HWND WINAPI DXUTGetHWND() { return DXUTIsWindowed() ? GetDXUTState().GetHWNDDeviceWindowed() : GetDXUTState().GetHWNDDeviceFullScreen(); }
HWND WINAPI DXUTGetHWNDFocus() { return GetDXUTState().GetHWNDFocus(); }
HWND WINAPI DXUTGetHWNDDeviceFullScreen() { return GetDXUTState().GetHWNDDeviceFullScreen(); }
HWND WINAPI DXUTGetHWNDDeviceWindowed() { return GetDXUTState().GetHWNDDeviceWindowed(); }
RECT WINAPI DXUTGetWindowClientRect() { RECT rc; GetClientRect( DXUTGetHWND(), &rc ); return rc; }
LONG WINAPI DXUTGetWindowWidth() { RECT rc = DXUTGetWindowClientRect(); return ((LONG)rc.right - rc.left); }
LONG WINAPI DXUTGetWindowHeight() { RECT rc = DXUTGetWindowClientRect(); return ((LONG)rc.bottom - rc.top); }
RECT WINAPI DXUTGetWindowClientRectAtModeChange() { RECT rc = { 0, 0, GetDXUTState().GetWindowBackBufferWidthAtModeChange(), GetDXUTState().GetWindowBackBufferHeightAtModeChange() }; return rc; }
RECT WINAPI DXUTGetFullsceenClientRectAtModeChange() { RECT rc = { 0, 0, GetDXUTState().GetFullScreenBackBufferWidthAtModeChange(), GetDXUTState().GetFullScreenBackBufferHeightAtModeChange() }; return rc; }
double WINAPI DXUTGetTime() { return GetDXUTState().GetTime(); }
float WINAPI DXUTGetElapsedTime() { return GetDXUTState().GetElapsedTime(); }
float WINAPI DXUTGetFPS() { return GetDXUTState().GetFPS(); }
LPCWSTR WINAPI DXUTGetWindowTitle() { return GetDXUTState().GetWindowTitle(); }
LPCWSTR WINAPI DXUTGetDeviceStats() { return GetDXUTState().GetDeviceStats(); }
LPCWSTR WINAPI DXUTGetD3D10CounterStats() { return GetDXUTState().GetD3D10CounterStats(); }
bool WINAPI DXUTIsRenderingPaused() { return GetDXUTState().GetPauseRenderingCount() > 0; }
bool WINAPI DXUTIsTimePaused() { return GetDXUTState().GetPauseTimeCount() > 0; }
bool WINAPI DXUTIsActive() { return GetDXUTState().GetActive(); }
int WINAPI DXUTGetExitCode() { return GetDXUTState().GetExitCode(); }
bool WINAPI DXUTGetShowMsgBoxOnError() { return GetDXUTState().GetShowMsgBoxOnError(); }
bool WINAPI DXUTGetAutomation() { return GetDXUTState().GetAutomation(); }
bool WINAPI DXUTIsWindowed() { return DXUTGetIsWindowedFromDS( GetDXUTState().GetCurrentDeviceSettings() ); }
bool WINAPI DXUTIsInGammaCorrectMode() { return GetDXUTState().GetIsInGammaCorrectMode(); }
IDirect3D9* WINAPI DXUTGetD3D9Object() { DXUTDelayLoadD3D9(); return GetDXUTState().GetD3D9(); }
IDXGIFactory* WINAPI DXUTGetDXGIFactory() { DXUTDelayLoadDXGI(); return GetDXUTState().GetDXGIFactory(); }
bool WINAPI DXUTIsD3D10Available() { DXUTDelayLoadDXGI(); return GetDXUTState().GetD3D10Available(); }
bool WINAPI DXUTIsAppRenderingWithD3D9() { return (GetDXUTState().GetD3D9Device() != NULL); }
bool WINAPI DXUTIsAppRenderingWithD3D10() { return (GetDXUTState().GetD3D10Device() != NULL); }
//--------------------------------------------------------------------------------------
// External callback setup functions
//--------------------------------------------------------------------------------------
// General callbacks
void WINAPI DXUTSetCallbackDeviceChanging( LPDXUTCALLBACKMODIFYDEVICESETTINGS pCallback, void* pUserContext ) { GetDXUTState().SetModifyDeviceSettingsFunc( pCallback ); GetDXUTState().SetModifyDeviceSettingsFuncUserContext( pUserContext ); }
void WINAPI DXUTSetCallbackDeviceRemoved( LPDXUTCALLBACKDEVICEREMOVED pCallback, void* pUserContext ) { GetDXUTState().SetDeviceRemovedFunc( pCallback ); GetDXUTState().SetDeviceRemovedFuncUserContext( pUserContext ); }
void WINAPI DXUTSetCallbackFrameMove( LPDXUTCALLBACKFRAMEMOVE pCallback, void* pUserContext ) { GetDXUTState().SetFrameMoveFunc( pCallback ); GetDXUTState().SetFrameMoveFuncUserContext( pUserContext ); }
void WINAPI DXUTSetCallbackKeyboard( LPDXUTCALLBACKKEYBOARD pCallback, void* pUserContext ) { GetDXUTState().SetKeyboardFunc( pCallback ); GetDXUTState().SetKeyboardFuncUserContext( pUserContext ); }
void WINAPI DXUTSetCallbackMouse( LPDXUTCALLBACKMOUSE pCallback, bool bIncludeMouseMove, void* pUserContext ) { GetDXUTState().SetMouseFunc( pCallback ); GetDXUTState().SetNotifyOnMouseMove( bIncludeMouseMove ); GetDXUTState().SetMouseFuncUserContext( pUserContext ); }
void WINAPI DXUTSetCallbackMsgProc( LPDXUTCALLBACKMSGPROC pCallback, void* pUserContext ) { GetDXUTState().SetWindowMsgFunc( pCallback ); GetDXUTState().SetWindowMsgFuncUserContext( pUserContext ); }
// Direct3D 9 callbacks
void WINAPI DXUTSetCallbackD3D9DeviceAcceptable( LPDXUTCALLBACKISD3D9DEVICEACCEPTABLE pCallback, void* pUserContext ) { GetDXUTState().SetIsD3D9DeviceAcceptableFunc( pCallback ); GetDXUTState().SetIsD3D9DeviceAcceptableFuncUserContext( pUserContext ); }
void WINAPI DXUTSetCallbackD3D9DeviceCreated( LPDXUTCALLBACKD3D9DEVICECREATED pCallback, void* pUserContext ) { GetDXUTState().SetD3D9DeviceCreatedFunc( pCallback ); GetDXUTState().SetD3D9DeviceCreatedFuncUserContext( pUserContext ); }
void WINAPI DXUTSetCallbackD3D9DeviceReset( LPDXUTCALLBACKD3D9DEVICERESET pCallback, void* pUserContext ) { GetDXUTState().SetD3D9DeviceResetFunc( pCallback ); GetDXUTState().SetD3D9DeviceResetFuncUserContext( pUserContext ); }
void WINAPI DXUTSetCallbackD3D9DeviceLost( LPDXUTCALLBACKD3D9DEVICELOST pCallback, void* pUserContext ) { GetDXUTState().SetD3D9DeviceLostFunc( pCallback ); GetDXUTState().SetD3D9DeviceLostFuncUserContext( pUserContext ); }
void WINAPI DXUTSetCallbackD3D9DeviceDestroyed( LPDXUTCALLBACKD3D9DEVICEDESTROYED pCallback, void* pUserContext ) { GetDXUTState().SetD3D9DeviceDestroyedFunc( pCallback ); GetDXUTState().SetD3D9DeviceDestroyedFuncUserContext( pUserContext ); }
void WINAPI DXUTSetCallbackD3D9FrameRender( LPDXUTCALLBACKD3D9FRAMERENDER pCallback, void* pUserContext ) { GetDXUTState().SetD3D9FrameRenderFunc( pCallback ); GetDXUTState().SetD3D9FrameRenderFuncUserContext( pUserContext ); }
void DXUTGetCallbackD3D9DeviceAcceptable( LPDXUTCALLBACKISD3D9DEVICEACCEPTABLE* ppCallback, void** ppUserContext ) { *ppCallback = GetDXUTState().GetIsD3D9DeviceAcceptableFunc(); *ppUserContext = GetDXUTState().GetIsD3D9DeviceAcceptableFuncUserContext(); }
// Direct3D 10 callbacks
void WINAPI DXUTSetCallbackD3D10DeviceAcceptable( LPDXUTCALLBACKISD3D10DEVICEACCEPTABLE pCallback, void* pUserContext ) { GetDXUTState().SetIsD3D10DeviceAcceptableFunc( pCallback ); GetDXUTState().SetIsD3D10DeviceAcceptableFuncUserContext( pUserContext ); }
void WINAPI DXUTSetCallbackD3D10DeviceCreated( LPDXUTCALLBACKD3D10DEVICECREATED pCallback, void* pUserContext ) { GetDXUTState().SetD3D10DeviceCreatedFunc( pCallback ); GetDXUTState().SetD3D10DeviceCreatedFuncUserContext( pUserContext ); }
void WINAPI DXUTSetCallbackD3D10SwapChainResized( LPDXUTCALLBACKD3D10SWAPCHAINRESIZED pCallback, void* pUserContext ) { GetDXUTState().SetD3D10SwapChainResizedFunc( pCallback ); GetDXUTState().SetD3D10SwapChainResizedFuncUserContext( pUserContext ); }
void WINAPI DXUTSetCallbackD3D10FrameRender( LPDXUTCALLBACKD3D10FRAMERENDER pCallback, void* pUserContext ) { GetDXUTState().SetD3D10FrameRenderFunc( pCallback ); GetDXUTState().SetD3D10FrameRenderFuncUserContext( pUserContext ); }
void WINAPI DXUTSetCallbackD3D10SwapChainReleasing( LPDXUTCALLBACKD3D10SWAPCHAINRELEASING pCallback, void* pUserContext ) { GetDXUTState().SetD3D10SwapChainReleasingFunc( pCallback ); GetDXUTState().SetD3D10SwapChainReleasingFuncUserContext( pUserContext ); }
void WINAPI DXUTSetCallbackD3D10DeviceDestroyed( LPDXUTCALLBACKD3D10DEVICEDESTROYED pCallback, void* pUserContext ) { GetDXUTState().SetD3D10DeviceDestroyedFunc( pCallback ); GetDXUTState().SetD3D10DeviceDestroyedFuncUserContext( pUserContext ); }
void DXUTGetCallbackD3D10DeviceAcceptable( LPDXUTCALLBACKISD3D10DEVICEACCEPTABLE* ppCallback, void** ppUserContext ) { *ppCallback = GetDXUTState().GetIsD3D10DeviceAcceptableFunc(); *ppUserContext = GetDXUTState().GetIsD3D10DeviceAcceptableFuncUserContext(); }
//--------------------------------------------------------------------------------------
// Optionally parses the command line and sets if default hotkeys are handled
//
// Possible command line parameters are:
// -forceapi:# forces app to use specified Direct3D API version (fails if the application doesn't support this API or if no device is found)
// -adapter:# forces app to use this adapter # (fails if the adapter doesn't exist)
// -output:# [D3D10 only] forces app to use a particular output on the adapter (fails if the output doesn't exist)
// -windowed forces app to start windowed
// -fullscreen forces app to start full screen
// -forcehal forces app to use HAL (fails if HAL doesn't exist)
// -forceref forces app to use REF (fails if REF doesn't exist)
// -forcepurehwvp [D3D9 only] forces app to use pure HWVP (fails if device doesn't support it)
// -forcehwvp [D3D9 only] forces app to use HWVP (fails if device doesn't support it)
// -forceswvp [D3D9 only] forces app to use SWVP
// -forcevsync:# if # is 0, then vsync is disabled
// -width:# forces app to use # for width. for full screen, it will pick the closest possible supported mode
// -height:# forces app to use # for height. for full screen, it will pick the closest possible supported mode
// -startx:# forces app to use # for the x coord of the window position for windowed mode
// -starty:# forces app to use # for the y coord of the window position for windowed mode
// -constantframetime:# forces app to use constant frame time, where # is the time/frame in seconds
// -quitafterframe:x forces app to quit after # frames
// -noerrormsgboxes prevents the display of message boxes generated by the framework so the application can be run without user interaction
// -nostats prevents the display of the stats
// -relaunchmce re-launches the MCE UI after the app exits
// -automation a hint to other components that automation is active
//--------------------------------------------------------------------------------------
HRESULT WINAPI DXUTInit( bool bParseCommandLine, bool bShowMsgBoxOnError, WCHAR* strExtraCommandLineParams, bool bThreadSafeDXUT )
{
g_bThreadSafe = bThreadSafeDXUT;
GetDXUTState().SetDXUTInitCalled( true );
// Not always needed, but lets the app create GDI dialogs
InitCommonControls();
// Save the current sticky/toggle/filter key settings so DXUT can restore them later
STICKYKEYS sk = {sizeof(STICKYKEYS), 0};
SystemParametersInfo(SPI_GETSTICKYKEYS, sizeof(STICKYKEYS), &sk, 0);
GetDXUTState().SetStartupStickyKeys( sk );
TOGGLEKEYS tk = {sizeof(TOGGLEKEYS), 0};
SystemParametersInfo(SPI_GETTOGGLEKEYS, sizeof(TOGGLEKEYS), &tk, 0);
GetDXUTState().SetStartupToggleKeys( tk );
FILTERKEYS fk = {sizeof(FILTERKEYS), 0};
SystemParametersInfo(SPI_GETFILTERKEYS, sizeof(FILTERKEYS), &fk, 0);
GetDXUTState().SetStartupFilterKeys( fk );
GetDXUTState().SetShowMsgBoxOnError( bShowMsgBoxOnError );
if( bParseCommandLine )
DXUTParseCommandLine( GetCommandLine() );
if( strExtraCommandLineParams )
DXUTParseCommandLine( strExtraCommandLineParams );
// Declare this process to be high DPI aware, and prevent automatic scaling
HINSTANCE hUser32 = LoadLibrary( L"user32.dll" );
if( hUser32 )
{
typedef BOOL (WINAPI * LPSetProcessDPIAware)(void);
LPSetProcessDPIAware pSetProcessDPIAware = (LPSetProcessDPIAware)GetProcAddress( hUser32, "SetProcessDPIAware" );
if( pSetProcessDPIAware )
{
pSetProcessDPIAware();
}
FreeLibrary( hUser32 );
}
// Reset the timer
DXUTGetGlobalTimer()->Reset();
GetDXUTState().SetDXUTInited( true );
return S_OK;
}
//--------------------------------------------------------------------------------------
// Parses the command line for parameters. See DXUTInit() for list
//--------------------------------------------------------------------------------------
void DXUTParseCommandLine( WCHAR* strCommandLine )
{
WCHAR* strCmdLine;
WCHAR strFlag[MAX_PATH];
int nNumArgs;
WCHAR** pstrArgList = CommandLineToArgvW( strCommandLine, &nNumArgs );
for( int iArg=1; iArg<nNumArgs; iArg++ )
{
strCmdLine = pstrArgList[iArg];
// Handle flag args
if( *strCmdLine == L'/' || *strCmdLine == L'-' )
{
strCmdLine++;
if( DXUTIsNextArg( strCmdLine, L"forceapi" ) )
{
if( DXUTGetCmdParam( strCmdLine, strFlag ) )
{
int nAPIVersion = _wtoi(strFlag);
GetDXUTState().SetOverrideForceAPI( nAPIVersion );
continue;
}
}
if( DXUTIsNextArg( strCmdLine, L"adapter" ) )
{
if( DXUTGetCmdParam( strCmdLine, strFlag ) )
{
int nAdapter = _wtoi(strFlag);
GetDXUTState().SetOverrideAdapterOrdinal( nAdapter );
continue;
}
}
if( DXUTIsNextArg( strCmdLine, L"windowed" ) )
{
GetDXUTState().SetOverrideWindowed( true );
continue;
}
if( DXUTIsNextArg( strCmdLine, L"output" ) )
{
if( DXUTGetCmdParam( strCmdLine, strFlag ) )
{
int Output = _wtoi(strFlag);
GetDXUTState().SetOverrideOutput( Output );
continue;
}
}
if( DXUTIsNextArg( strCmdLine, L"fullscreen" ) )
{
GetDXUTState().SetOverrideFullScreen( true );
continue;
}
if( DXUTIsNextArg( strCmdLine, L"forcehal" ) )
{
GetDXUTState().SetOverrideForceHAL( true );
continue;
}
if( DXUTIsNextArg( strCmdLine, L"forceref" ) )
{
GetDXUTState().SetOverrideForceREF( true );
continue;
}
if( DXUTIsNextArg( strCmdLine, L"forcepurehwvp" ) )
{
GetDXUTState().SetOverrideForcePureHWVP( true );
continue;
}
if( DXUTIsNextArg( strCmdLine, L"forcehwvp" ) )
{
GetDXUTState().SetOverrideForceHWVP( true );
continue;
}
if( DXUTIsNextArg( strCmdLine, L"forceswvp" ) )
{
GetDXUTState().SetOverrideForceSWVP( true );
continue;
}
if( DXUTIsNextArg( strCmdLine, L"forcevsync" ) )
{
if( DXUTGetCmdParam( strCmdLine, strFlag ) )
{
int nOn = _wtoi(strFlag);
GetDXUTState().SetOverrideForceVsync( nOn );
continue;
}
}
if( DXUTIsNextArg( strCmdLine, L"width" ) )
{
if( DXUTGetCmdParam( strCmdLine, strFlag ) )
{
int nWidth = _wtoi(strFlag);
GetDXUTState().SetOverrideWidth( nWidth );
continue;
}
}
if( DXUTIsNextArg( strCmdLine, L"height" ) )
{
if( DXUTGetCmdParam( strCmdLine, strFlag ) )
{
int nHeight = _wtoi(strFlag);
GetDXUTState().SetOverrideHeight( nHeight );
continue;
}
}
if( DXUTIsNextArg( strCmdLine, L"startx" ) )
{
if( DXUTGetCmdParam( strCmdLine, strFlag ) )
{
int nX = _wtoi(strFlag);
GetDXUTState().SetOverrideStartX( nX );
continue;
}
}
if( DXUTIsNextArg( strCmdLine, L"starty" ) )
{
if( DXUTGetCmdParam( strCmdLine, strFlag ) )
{
int nY = _wtoi(strFlag);
GetDXUTState().SetOverrideStartY( nY );
continue;
}
}
if( DXUTIsNextArg( strCmdLine, L"constantframetime" ) )
{
float fTimePerFrame;
if( DXUTGetCmdParam( strCmdLine, strFlag ) )
fTimePerFrame = (float)wcstod( strFlag, NULL );
else
fTimePerFrame = 0.0333f;
GetDXUTState().SetOverrideConstantFrameTime( true );
GetDXUTState().SetOverrideConstantTimePerFrame( fTimePerFrame );
DXUTSetConstantFrameTime( true, fTimePerFrame );
continue;
}
if( DXUTIsNextArg( strCmdLine, L"quitafterframe" ) )
{
if( DXUTGetCmdParam( strCmdLine, strFlag ) )
{
int nFrame = _wtoi(strFlag);
GetDXUTState().SetOverrideQuitAfterFrame( nFrame );
continue;
}
}
if( DXUTIsNextArg( strCmdLine, L"noerrormsgboxes" ) )
{
GetDXUTState().SetShowMsgBoxOnError( false );
continue;
}
if( DXUTIsNextArg( strCmdLine, L"nostats" ) )
{
GetDXUTState().SetNoStats( true );
continue;
}
if( DXUTIsNextArg( strCmdLine, L"relaunchmce" ) )
{
GetDXUTState().SetOverrideRelaunchMCE( true );
continue;
}
if( DXUTIsNextArg( strCmdLine, L"automation" ) )
{
GetDXUTState().SetAutomation( true );
continue;
}
}
// Unrecognized flag
StringCchCopy( strFlag, 256, strCmdLine );
WCHAR* strSpace = strFlag;
while (*strSpace && (*strSpace > L' '))
strSpace++;
*strSpace = 0;
DXUTOutputDebugString( L"Unrecognized flag: %s", strFlag );
strCmdLine += wcslen(strFlag);
}
}
//--------------------------------------------------------------------------------------
// Helper function for DXUTParseCommandLine
//--------------------------------------------------------------------------------------
bool DXUTIsNextArg( WCHAR*& strCmdLine, WCHAR* strArg )
{
int nArgLen = (int) wcslen(strArg);
int nCmdLen = (int) wcslen(strCmdLine);
if( nCmdLen >= nArgLen &&
_wcsnicmp( strCmdLine, strArg, nArgLen ) == 0 &&
(strCmdLine[nArgLen] == 0 || strCmdLine[nArgLen] == L':') )
{
strCmdLine += nArgLen;
return true;
}
return false;
}
//--------------------------------------------------------------------------------------
// Helper function for DXUTParseCommandLine. Updates strCmdLine and strFlag
// Example: if strCmdLine=="-width:1024 -forceref"
// then after: strCmdLine==" -forceref" and strFlag=="1024"
//--------------------------------------------------------------------------------------
bool DXUTGetCmdParam( WCHAR*& strCmdLine, WCHAR* strFlag )
{
if( *strCmdLine == L':' )
{
strCmdLine++; // Skip ':'
// Place NULL terminator in strFlag after current token
StringCchCopy( strFlag, 256, strCmdLine );
WCHAR* strSpace = strFlag;
while (*strSpace && (*strSpace > L' '))
strSpace++;
*strSpace = 0;
// Update strCmdLine
strCmdLine += wcslen(strFlag);
return true;
}
else
{
strFlag[0] = 0;
return false;
}
}
//--------------------------------------------------------------------------------------
// Creates a window with the specified window title, icon, menu, and
// starting position. If DXUTInit() has not already been called, it will
// call it with the default parameters. Instead of calling this, you can
// call DXUTSetWindow() to use an existing window.
//--------------------------------------------------------------------------------------
HRESULT WINAPI DXUTCreateWindow( const WCHAR* strWindowTitle, HINSTANCE hInstance,
HICON hIcon, HMENU hMenu, int x, int y )
{
HRESULT hr;
// Not allowed to call this from inside the device callbacks
if( GetDXUTState().GetInsideDeviceCallback() )
return DXUT_ERR_MSGBOX( L"DXUTCreateWindow", E_FAIL );
GetDXUTState().SetWindowCreateCalled( true );
if( !GetDXUTState().GetDXUTInited() )
{
// If DXUTInit() was already called and failed, then fail.
// DXUTInit() must first succeed for this function to succeed
if( GetDXUTState().GetDXUTInitCalled() )
return E_FAIL;
// If DXUTInit() hasn't been called, then automatically call it
// with default params
hr = DXUTInit();
if( FAILED(hr) )
return hr;
}
if( DXUTGetHWNDFocus() == NULL )
{
if( hInstance == NULL )
hInstance = (HINSTANCE)GetModuleHandle(NULL);
GetDXUTState().SetHInstance( hInstance );
WCHAR szExePath[MAX_PATH];
GetModuleFileName( NULL, szExePath, MAX_PATH );
// NV: The original DXUT icon treatment would always downsample a 32x32 icon for display
// on the title bar. Our additional code explicitly extracts a small icon from the image.
// We also switch to WNDCLASSEX and RegisterClassEx below which allow explicit specification
// of a small icon.
HICON hIconSmall = hIcon;
if( hIcon == NULL ) // If the icon is NULL, then use the first one found in the exe
ExtractIconEx( szExePath, 0, &hIcon, &hIconSmall, 1 );
// Register the windows class
WNDCLASSEX wndClass; // NV: changed from WNDCLASS.
wndClass.cbSize = sizeof(WNDCLASSEX); // NV: we use the "Ex" version which adds this member.
wndClass.style = CS_DBLCLKS;
wndClass.lpfnWndProc = DXUTStaticWndProc;
wndClass.cbClsExtra = 0;
wndClass.cbWndExtra = 0;
wndClass.hInstance = hInstance;
wndClass.hIcon = hIcon;
wndClass.hCursor = LoadCursor( NULL, IDC_ARROW );
wndClass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wndClass.lpszMenuName = NULL;
wndClass.lpszClassName = L"Direct3DWindowClass";
wndClass.hIconSm = hIconSmall; // NV: explicitly set a small icon.
if( !RegisterClassEx( &wndClass ) ) // NV: changed to "Ex" version for small icon.
{
DWORD dwError = GetLastError();
if( dwError != ERROR_CLASS_ALREADY_EXISTS )
return DXUT_ERR_MSGBOX( L"RegisterClass", HRESULT_FROM_WIN32(dwError) );
}
// Override the window's initial & size position if there were cmd line args
if( GetDXUTState().GetOverrideStartX() != -1 )
x = GetDXUTState().GetOverrideStartX();
if( GetDXUTState().GetOverrideStartY() != -1 )
y = GetDXUTState().GetOverrideStartY();
GetDXUTState().SetWindowCreatedWithDefaultPositions( false );
if( x == CW_USEDEFAULT && y == CW_USEDEFAULT )
GetDXUTState().SetWindowCreatedWithDefaultPositions( true );
// Find the window's initial size, but it might be changed later
int nDefaultWidth = 640;
int nDefaultHeight = 480;
if( GetDXUTState().GetOverrideWidth() != 0 )
nDefaultWidth = GetDXUTState().GetOverrideWidth();
if( GetDXUTState().GetOverrideHeight() != 0 )
nDefaultHeight = GetDXUTState().GetOverrideHeight();
RECT rc;
SetRect( &rc, 0, 0, nDefaultWidth, nDefaultHeight );
AdjustWindowRect( &rc, WS_OVERLAPPEDWINDOW, ( hMenu != NULL ) ? true : false );
WCHAR* strCachedWindowTitle = GetDXUTState().GetWindowTitle();
StringCchCopy( strCachedWindowTitle, 256, L"S3Graphics DX10 SDK: " );
StringCchCat ( strCachedWindowTitle, 256, strWindowTitle );
// Create the render window
HWND hWnd = CreateWindow( L"Direct3DWindowClass", strCachedWindowTitle, WS_OVERLAPPEDWINDOW,
x, y, (rc.right-rc.left), (rc.bottom-rc.top), 0,
hMenu, hInstance, 0 );
if( hWnd == NULL )
{
DWORD dwError = GetLastError();
return DXUT_ERR_MSGBOX( L"CreateWindow", HRESULT_FROM_WIN32(dwError) );
}
GetDXUTState().SetWindowCreated( true );
GetDXUTState().SetHWNDFocus( hWnd );
GetDXUTState().SetHWNDDeviceFullScreen( hWnd );
GetDXUTState().SetHWNDDeviceWindowed( hWnd );
}
return S_OK;
}
//--------------------------------------------------------------------------------------
// Sets a previously created window for the framework to use. If DXUTInit()
// has not already been called, it will call it with the default parameters.
// Instead of calling this, you can call DXUTCreateWindow() to create a new window.
//--------------------------------------------------------------------------------------
HRESULT WINAPI DXUTSetWindow( HWND hWndFocus, HWND hWndDeviceFullScreen, HWND hWndDeviceWindowed, bool bHandleMessages )
{
HRESULT hr;
// Not allowed to call this from inside the device callbacks
if( GetDXUTState().GetInsideDeviceCallback() )
return DXUT_ERR_MSGBOX( L"DXUTCreateWindow", E_FAIL );
GetDXUTState().SetWindowCreateCalled( true );
// To avoid confusion, we do not allow any HWND to be NULL here. The
// caller must pass in valid HWND for all three parameters. The same
// HWND may be used for more than one parameter.
if( hWndFocus == NULL || hWndDeviceFullScreen == NULL || hWndDeviceWindowed == NULL )
return DXUT_ERR_MSGBOX( L"DXUTSetWindow", E_INVALIDARG );
// If subclassing the window, set the pointer to the local window procedure
if( bHandleMessages )
{
// Switch window procedures
#ifdef _WIN64
LONG_PTR nResult = SetWindowLongPtr( hWndFocus, GWLP_WNDPROC, (LONG_PTR)DXUTStaticWndProc );
#else
LONG_PTR nResult = SetWindowLongPtr( hWndFocus, GWLP_WNDPROC, (LONG)(LONG_PTR)DXUTStaticWndProc );
#endif
DWORD dwError = GetLastError();
if( nResult == 0 )
return DXUT_ERR_MSGBOX( L"SetWindowLongPtr", HRESULT_FROM_WIN32(dwError) );
}
if( !GetDXUTState().GetDXUTInited() )
{
// If DXUTInit() was already called and failed, then fail.
// DXUTInit() must first succeed for this function to succeed
if( GetDXUTState().GetDXUTInitCalled() )
return E_FAIL;
// If DXUTInit() hasn't been called, then automatically call it
// with default params
hr = DXUTInit();
if( FAILED(hr) )
return hr;
}
WCHAR* strCachedWindowTitle = GetDXUTState().GetWindowTitle();
GetWindowText( hWndFocus, strCachedWindowTitle, 255 );
strCachedWindowTitle[255] = 0;
HINSTANCE hInstance = (HINSTANCE) (LONG_PTR) GetWindowLongPtr( hWndFocus, GWLP_HINSTANCE );
GetDXUTState().SetHInstance( hInstance );
GetDXUTState().SetWindowCreatedWithDefaultPositions( false );
GetDXUTState().SetWindowCreated( true );
GetDXUTState().SetHWNDFocus( hWndFocus );
GetDXUTState().SetHWNDDeviceFullScreen( hWndDeviceFullScreen );
GetDXUTState().SetHWNDDeviceWindowed( hWndDeviceWindowed );
return S_OK;
}
//--------------------------------------------------------------------------------------
// Handles window messages
//--------------------------------------------------------------------------------------
LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
// Consolidate the keyboard messages and pass them to the app's keyboard callback
if( uMsg == WM_KEYDOWN ||
uMsg == WM_SYSKEYDOWN ||
uMsg == WM_KEYUP ||
uMsg == WM_SYSKEYUP )
{
bool bKeyDown = (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN);
DWORD dwMask = (1 << 29);
bool bAltDown = ( (lParam & dwMask) != 0 );
bool* bKeys = GetDXUTState().GetKeys();
bKeys[ (BYTE) (wParam & 0xFF) ] = bKeyDown;
LPDXUTCALLBACKKEYBOARD pCallbackKeyboard = GetDXUTState().GetKeyboardFunc();
if( pCallbackKeyboard )
pCallbackKeyboard( (UINT)wParam, bKeyDown, bAltDown, GetDXUTState().GetKeyboardFuncUserContext() );
}
// Consolidate the mouse button messages and pass them to the app's mouse callback
if( uMsg == WM_LBUTTONDOWN ||
uMsg == WM_LBUTTONUP ||
uMsg == WM_LBUTTONDBLCLK ||
uMsg == WM_MBUTTONDOWN ||
uMsg == WM_MBUTTONUP ||
uMsg == WM_MBUTTONDBLCLK ||
uMsg == WM_RBUTTONDOWN ||
uMsg == WM_RBUTTONUP ||
uMsg == WM_RBUTTONDBLCLK ||
uMsg == WM_XBUTTONDOWN ||
uMsg == WM_XBUTTONUP ||
uMsg == WM_XBUTTONDBLCLK ||
uMsg == WM_MOUSEWHEEL ||
(GetDXUTState().GetNotifyOnMouseMove() && uMsg == WM_MOUSEMOVE) )
{
int xPos = (short)LOWORD(lParam);
int yPos = (short)HIWORD(lParam);
if( uMsg == WM_MOUSEWHEEL )
{
// WM_MOUSEWHEEL passes screen mouse coords
// so convert them to client coords
POINT pt;
pt.x = xPos; pt.y = yPos;
ScreenToClient( hWnd, &pt );
xPos = pt.x; yPos = pt.y;
}
int nMouseWheelDelta = 0;
if( uMsg == WM_MOUSEWHEEL )
nMouseWheelDelta = (short) HIWORD(wParam);
int nMouseButtonState = LOWORD(wParam);
bool bLeftButton = ((nMouseButtonState & MK_LBUTTON) != 0);
bool bRightButton = ((nMouseButtonState & MK_RBUTTON) != 0);
bool bMiddleButton = ((nMouseButtonState & MK_MBUTTON) != 0);
bool bSideButton1 = ((nMouseButtonState & MK_XBUTTON1) != 0);
bool bSideButton2 = ((nMouseButtonState & MK_XBUTTON2) != 0);
bool* bMouseButtons = GetDXUTState().GetMouseButtons();
bMouseButtons[0] = bLeftButton;
bMouseButtons[1] = bMiddleButton;
bMouseButtons[2] = bRightButton;
bMouseButtons[3] = bSideButton1;
bMouseButtons[4] = bSideButton2;
LPDXUTCALLBACKMOUSE pCallbackMouse = GetDXUTState().GetMouseFunc();
if( pCallbackMouse )
pCallbackMouse( bLeftButton, bRightButton, bMiddleButton, bSideButton1, bSideButton2, nMouseWheelDelta, xPos, yPos, GetDXUTState().GetMouseFuncUserContext() );
}
// Pass all messages to the app's MsgProc callback, and don't
// process further messages if the apps says not to.
LPDXUTCALLBACKMSGPROC pCallbackMsgProc = GetDXUTState().GetWindowMsgFunc();
if( pCallbackMsgProc )
{
bool bNoFurtherProcessing = false;
LRESULT nResult = pCallbackMsgProc( hWnd, uMsg, wParam, lParam, &bNoFurtherProcessing, GetDXUTState().GetWindowMsgFuncUserContext() );
if( bNoFurtherProcessing )
return nResult;
}
switch( uMsg )
{
case WM_PAINT:
{
// Handle paint messages when the app is paused
if( DXUTIsRenderingPaused() &&
GetDXUTState().GetDeviceObjectsCreated() && GetDXUTState().GetDeviceObjectsReset() )
{
HRESULT hr;
double fTime = DXUTGetTime();
float fElapsedTime = DXUTGetElapsedTime();
if( DXUTIsCurrentDeviceD3D9() )
{
IDirect3DDevice9* pd3dDevice = DXUTGetD3D9Device();
if( pd3dDevice )
{
LPDXUTCALLBACKD3D9FRAMERENDER pCallbackFrameRender = GetDXUTState().GetD3D9FrameRenderFunc();
if( pCallbackFrameRender != NULL )
pCallbackFrameRender( pd3dDevice, fTime, fElapsedTime, GetDXUTState().GetD3D9FrameRenderFuncUserContext() );
hr = pd3dDevice->Present( NULL, NULL, NULL, NULL );
if( D3DERR_DEVICELOST == hr )
{
GetDXUTState().SetDeviceLost( true );
}
else if( D3DERR_DRIVERINTERNALERROR == hr )
{
// When D3DERR_DRIVERINTERNALERROR is returned from Present(),
// the application can do one of the following:
//
// - End, with the pop-up window saying that the application cannot continue
// because of problems in the display adapter and that the user should
// contact the adapter manufacturer.
//
// - Attempt to restart by calling IDirect3DDevice9::Reset, which is essentially the same
// path as recovering from a lost device. If IDirect3DDevice9::Reset fails with
// D3DERR_DRIVERINTERNALERROR, the application should end immediately with the message
// that the user should contact the adapter manufacturer.
//
// The framework attempts the path of resetting the device
//
GetDXUTState().SetDeviceLost( true );
}
}
}
else
{
ID3D10Device* pd3dDevice = DXUTGetD3D10Device();
if( pd3dDevice )
{
LPDXUTCALLBACKD3D10FRAMERENDER pCallbackFrameRender = GetDXUTState().GetD3D10FrameRenderFunc();
if( pCallbackFrameRender != NULL &&
!GetDXUTState().GetRenderingOccluded() )
{
pCallbackFrameRender( pd3dDevice, fTime, fElapsedTime, GetDXUTState().GetD3D10FrameRenderFuncUserContext() );
}
DWORD dwFlags = 0;
if( GetDXUTState().GetRenderingOccluded() )
dwFlags = DXGI_PRESENT_TEST;
else
dwFlags = GetDXUTState().GetCurrentDeviceSettings()->d3d10.PresentFlags;
IDXGISwapChain *pSwapChain = DXUTGetDXGISwapChain();
hr = pSwapChain->Present( 0, GetDXUTState().GetCurrentDeviceSettings()->d3d10.PresentFlags );
if( DXGI_STATUS_OCCLUDED == hr )
{
// There is a window covering our entire rendering area.
// Don't render until we're visible again.
GetDXUTState().SetRenderingOccluded( true );
}
else if( SUCCEEDED(hr) )
{
if( GetDXUTState().GetRenderingOccluded() )
{
// Now that we're no longer occluded
// allow us to render again
GetDXUTState().SetRenderingOccluded( false );
}
}
}
}
}
break;
}
case WM_SIZE:
if( SIZE_MINIMIZED == wParam )
{
DXUTPause( true, true ); // Pause while we're minimized
GetDXUTState().SetMinimized( true );
GetDXUTState().SetMaximized( false );
}
else
{
RECT rcCurrentClient;
GetClientRect( DXUTGetHWND(), &rcCurrentClient );
if( rcCurrentClient.top == 0 && rcCurrentClient.bottom == 0 )
{
// Rapidly clicking the task bar to minimize and restore a window
// can cause a WM_SIZE message with SIZE_RESTORED when
// the window has actually become minimized due to rapid change
// so just ignore this message
}
else if( SIZE_MAXIMIZED == wParam )
{
if( GetDXUTState().GetMinimized() )
DXUTPause( false, false ); // Unpause since we're no longer minimized
GetDXUTState().SetMinimized( false );
GetDXUTState().SetMaximized( true );
DXUTCheckForWindowSizeChange();
DXUTCheckForWindowChangingMonitors();
}
else if( SIZE_RESTORED == wParam )
{
//DXUTCheckForDXGIFullScreenSwitch();
if( GetDXUTState().GetMaximized() )
{
GetDXUTState().SetMaximized( false );
DXUTCheckForWindowSizeChange();
DXUTCheckForWindowChangingMonitors();
}
else if( GetDXUTState().GetMinimized() )
{
DXUTPause( false, false ); // Unpause since we're no longer minimized
GetDXUTState().SetMinimized( false );
DXUTCheckForWindowSizeChange();
DXUTCheckForWindowChangingMonitors();
}
else if( GetDXUTState().GetInSizeMove() )
{
// If we're neither maximized nor minimized, the window size
// is changing by the user dragging the window edges. In this
// case, we don't reset the device yet -- we wait until the
// user stops dragging, and a WM_EXITSIZEMOVE message comes.
}
else
{
// This WM_SIZE come from resizing the window via an API like SetWindowPos() so
// resize and reset the device now.
DXUTCheckForWindowSizeChange();
DXUTCheckForWindowChangingMonitors();
}
}
}
break;
case WM_GETMINMAXINFO:
((MINMAXINFO*)lParam)->ptMinTrackSize.x = DXUT_MIN_WINDOW_SIZE_X;
((MINMAXINFO*)lParam)->ptMinTrackSize.y = DXUT_MIN_WINDOW_SIZE_Y;
break;
case WM_ENTERSIZEMOVE:
// Halt frame movement while the app is sizing or moving
DXUTPause( true, true );
GetDXUTState().SetInSizeMove( true );
break;
case WM_EXITSIZEMOVE:
DXUTPause( false, false );
DXUTCheckForWindowSizeChange();
DXUTCheckForWindowChangingMonitors();
GetDXUTState().SetInSizeMove( false );
break;
case WM_MOUSEMOVE:
if( DXUTIsActive() && !DXUTIsWindowed() )
{
if( DXUTIsCurrentDeviceD3D9() )
{
IDirect3DDevice9* pd3dDevice = DXUTGetD3D9Device();
if( pd3dDevice )
{
POINT ptCursor;
GetCursorPos( &ptCursor );
pd3dDevice->SetCursorPosition( ptCursor.x, ptCursor.y, 0 );
}
}
else
{
// For D3D10, no processing is necessary. D3D10 cursor
// is handled in the traditional Windows manner.
}
}
break;
case WM_SETCURSOR:
if( DXUTIsActive() && !DXUTIsWindowed() )
{
if( DXUTIsCurrentDeviceD3D9() )
{
IDirect3DDevice9* pd3dDevice = DXUTGetD3D9Device();
if( pd3dDevice && GetDXUTState().GetShowCursorWhenFullScreen() )
pd3dDevice->ShowCursor( true );
}
else
{
if( !GetDXUTState().GetShowCursorWhenFullScreen() )
SetCursor( NULL );
}
return true; // prevent Windows from setting cursor to window class cursor
}
break;
case WM_ACTIVATEAPP:
if( wParam == TRUE && !DXUTIsActive() ) // Handle only if previously not active
{
GetDXUTState().SetActive( true );
// Enable controller rumble & input when activating app
DXUTEnableXInput( true );
// The GetMinimizedWhileFullscreen() varible is used instead of !DXUTIsWindowed()
// to handle the rare case toggling to windowed mode while the fullscreen application
// is minimized and thus making the pause count wrong
if( GetDXUTState().GetMinimizedWhileFullscreen() )
{
if( DXUTIsD3D9( GetDXUTState().GetCurrentDeviceSettings() ) )
DXUTPause( false, false ); // Unpause since we're no longer minimized
GetDXUTState().SetMinimizedWhileFullscreen( false );
if( DXUTIsAppRenderingWithD3D10() )
{
DXUTToggleFullScreen();
}
}
// Upon returning to this app, potentially disable shortcut keys
// (Windows key, accessibility shortcuts)
DXUTAllowShortcutKeys( ( DXUTIsWindowed() ) ? GetDXUTState().GetAllowShortcutKeysWhenWindowed() :
GetDXUTState().GetAllowShortcutKeysWhenFullscreen() );
}
else if( wParam == FALSE && DXUTIsActive() ) // Handle only if previously active
{
GetDXUTState().SetActive( false );
// Disable any controller rumble & input when de-activating app
DXUTEnableXInput( false );
if( !DXUTIsWindowed() )
{
// Going from full screen to a minimized state
ClipCursor( NULL ); // don't limit the cursor anymore
if( DXUTIsD3D9( GetDXUTState().GetCurrentDeviceSettings() ) )
DXUTPause( true, true ); // Pause while we're minimized (take care not to pause twice by handling this message twice)
GetDXUTState().SetMinimizedWhileFullscreen( true );
}
// Restore shortcut keys (Windows key, accessibility shortcuts) to original state
//
// This is important to call here if the shortcuts are disabled,
// because if this is not done then the Windows key will continue to
// be disabled while this app is running which is very bad.
// If the app crashes, the Windows key will return to normal.
DXUTAllowShortcutKeys( true );
}
break;
case WM_ENTERMENULOOP:
// Pause the app when menus are displayed
DXUTPause( true, true );
break;
case WM_EXITMENULOOP:
DXUTPause( false, false );
break;
case WM_MENUCHAR:
// A menu is active and the user presses a key that does not correspond to any mnemonic or accelerator key
// So just ignore and don't beep
return MAKELRESULT(0,MNC_CLOSE);
break;
case WM_NCHITTEST:
// Prevent the user from selecting the menu in full screen mode
if( !DXUTIsWindowed() )
return HTCLIENT;
break;
case WM_POWERBROADCAST:
switch( wParam )
{
#ifndef PBT_APMQUERYSUSPEND
#define PBT_APMQUERYSUSPEND 0x0000
#endif
case PBT_APMQUERYSUSPEND:
// At this point, the app should save any data for open
// network connections, files, etc., and prepare to go into
// a suspended mode. The app can use the MsgProc callback
// to handle this if desired.
return true;
#ifndef PBT_APMRESUMESUSPEND
#define PBT_APMRESUMESUSPEND 0x0007
#endif
case PBT_APMRESUMESUSPEND:
// At this point, the app should recover any data, network
// connections, files, etc., and resume running from when
// the app was suspended. The app can use the MsgProc callback
// to handle this if desired.
// QPC may lose consistency when suspending, so reset the timer
// upon resume.
DXUTGetGlobalTimer()->Reset();
GetDXUTState().SetLastStatsUpdateTime( 0 );
return true;
}
break;
case WM_SYSCOMMAND:
// Prevent moving/sizing in full screen mode
switch( (wParam & 0xFFF0) )
{
case SC_MOVE:
case SC_SIZE:
case SC_MAXIMIZE:
case SC_KEYMENU:
if( !DXUTIsWindowed() )
return 0;
break;
}
break;
case WM_SYSKEYDOWN:
{
switch( wParam )
{
case VK_RETURN:
{
if( GetDXUTState().GetHandleAltEnter() && DXUTIsAppRenderingWithD3D9() )
{
// Toggle full screen upon alt-enter
DWORD dwMask = (1 << 29);
if( (lParam & dwMask) != 0 ) // Alt is down also
{
// Toggle the full screen/window mode
DXUTPause( true, true );
DXUTToggleFullScreen();
DXUTPause( false, false );
return 0;
}
}
}
}
break;
}
case WM_KEYDOWN:
{
switch( wParam )
{
case VK_ESCAPE:
{
if( GetDXUTState().GetHandleEscape() )
SendMessage( hWnd, WM_CLOSE, 0, 0 );
break;
}
case VK_PAUSE:
{
if( GetDXUTState().GetHandlePause() )
{
bool bTimePaused = DXUTIsTimePaused();
bTimePaused = !bTimePaused;
if( bTimePaused )
DXUTPause( true, false );
else
DXUTPause( false, false );
}
break;
}
}
break;
}
case WM_CLOSE:
{
HMENU hMenu;
hMenu = GetMenu(hWnd);
if( hMenu != NULL )
DestroyMenu( hMenu );
DestroyWindow( hWnd );
UnregisterClass( L"Direct3DWindowClass", NULL );
GetDXUTState().SetHWNDFocus( NULL );
GetDXUTState().SetHWNDDeviceFullScreen( NULL );
GetDXUTState().SetHWNDDeviceWindowed( NULL );
return 0;
}
case WM_DESTROY:
PostQuitMessage(0);
break;
}
// Don't allow the F10 key to act as a shortcut to the menu bar
// by not passing these messages to the DefWindowProc only when
// there's no menu present
if( !GetDXUTState().GetCallDefWindowProc() || GetDXUTState().GetMenu() == NULL && (uMsg == WM_SYSKEYDOWN || uMsg == WM_SYSKEYUP) && wParam == VK_F10 )
return 0;
else
return DefWindowProc( hWnd, uMsg, wParam, lParam );
}
//--------------------------------------------------------------------------------------
// Handles app's message loop and rendering when idle. If DXUTCreateDevice() or DXUTSetD3D*Device()
// has not already been called, it will call DXUTCreateWindow() with the default parameters.
//--------------------------------------------------------------------------------------
HRESULT WINAPI DXUTMainLoop( HACCEL hAccel )
{
HRESULT hr;
// Not allowed to call this from inside the device callbacks or reenter
if( GetDXUTState().GetInsideDeviceCallback() || GetDXUTState().GetInsideMainloop() )
{
if( (GetDXUTState().GetExitCode() == 0) || (GetDXUTState().GetExitCode() == 10) )
GetDXUTState().SetExitCode(1);
return DXUT_ERR_MSGBOX( L"DXUTMainLoop", E_FAIL );
}
GetDXUTState().SetInsideMainloop( true );
// If DXUTCreateDevice() or DXUTSetD3D*Device() has not already been called,
// then call DXUTCreateDevice() with the default parameters.
if( !GetDXUTState().GetDeviceCreated() )
{
if( GetDXUTState().GetDeviceCreateCalled() )
{
if( (GetDXUTState().GetExitCode() == 0) || (GetDXUTState().GetExitCode() == 10) )
GetDXUTState().SetExitCode(1);
return E_FAIL; // DXUTCreateDevice() must first succeed for this function to succeed
}
hr = DXUTCreateDevice();
if( FAILED(hr) )
{
if( (GetDXUTState().GetExitCode() == 0) || (GetDXUTState().GetExitCode() == 10) )
GetDXUTState().SetExitCode(1);
return hr;
}
}
HWND hWnd = DXUTGetHWND();
// DXUTInit() must have been called and succeeded for this function to proceed
// DXUTCreateWindow() or DXUTSetWindow() must have been called and succeeded for this function to proceed
// DXUTCreateDevice() or DXUTCreateDeviceFromSettings() or DXUTSetD3D*Device() must have been called and succeeded for this function to proceed
if( !GetDXUTState().GetDXUTInited() || !GetDXUTState().GetWindowCreated() || !GetDXUTState().GetDeviceCreated() )
{
if( (GetDXUTState().GetExitCode() == 0) || (GetDXUTState().GetExitCode() == 10) )
GetDXUTState().SetExitCode(1);
return DXUT_ERR_MSGBOX( L"DXUTMainLoop", E_FAIL );
}
// Now we're ready to receive and process Windows messages.
bool bGotMsg;
MSG msg;
msg.message = WM_NULL;
PeekMessage( &msg, NULL, 0U, 0U, PM_NOREMOVE );
while( WM_QUIT != msg.message )
{
// Use PeekMessage() so we can use idle time to render the scene.
bGotMsg = ( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) != 0 );
if( bGotMsg )
{
// Translate and dispatch the message
if( hAccel == NULL || hWnd == NULL ||
0 == TranslateAccelerator( hWnd, hAccel, &msg ) )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
}
else
{
// Render a frame during idle time (no messages are waiting)
DXUTRender3DEnvironment();
}
}
// Cleanup the accelerator table
if( hAccel != NULL )
DestroyAcceleratorTable( hAccel );
GetDXUTState().SetInsideMainloop( false );
return S_OK;
}
//======================================================================================
//======================================================================================
// Direct3D section
//======================================================================================
//======================================================================================
//--------------------------------------------------------------------------------------
// Creates a Direct3D device. If DXUTCreateWindow() or DXUTSetWindow() has not already
// been called, it will call DXUTCreateWindow() with the default parameters.
// Instead of calling this, you can call DXUTSetD3D*Device() or DXUTCreateDeviceFromSettings().
//--------------------------------------------------------------------------------------
HRESULT WINAPI DXUTCreateDevice( bool bWindowed, int nSuggestedWidth, int nSuggestedHeight )
{
HRESULT hr = S_OK;
// Not allowed to call this from inside the device callbacks
if( GetDXUTState().GetInsideDeviceCallback() )
return DXUT_ERR_MSGBOX( L"DXUTCreateWindow", E_FAIL );
GetDXUTState().SetDeviceCreateCalled( true );
// If DXUTCreateWindow() or DXUTSetWindow() has not already been called,
// then call DXUTCreateWindow() with the default parameters.
if( !GetDXUTState().GetWindowCreated() )
{
// If DXUTCreateWindow() or DXUTSetWindow() was already called and failed, then fail.
// DXUTCreateWindow() or DXUTSetWindow() must first succeed for this function to succeed
if( GetDXUTState().GetWindowCreateCalled() )
return E_FAIL;
// If DXUTCreateWindow() or DXUTSetWindow() hasn't been called, then
// automatically call DXUTCreateWindow() with default params
hr = DXUTCreateWindow();
if( FAILED(hr) )
return hr;
}
DXUTMatchOptions matchOptions;
matchOptions.eAPIVersion = DXUTMT_IGNORE_INPUT;
matchOptions.eAdapterOrdinal = DXUTMT_IGNORE_INPUT;
matchOptions.eDeviceType = DXUTMT_IGNORE_INPUT;
matchOptions.eOutput = DXUTMT_IGNORE_INPUT;
matchOptions.eWindowed = DXUTMT_PRESERVE_INPUT;
matchOptions.eAdapterFormat = DXUTMT_IGNORE_INPUT;
matchOptions.eVertexProcessing = DXUTMT_IGNORE_INPUT;
if( bWindowed || (nSuggestedWidth != 0 && nSuggestedHeight != 0) )
matchOptions.eResolution = DXUTMT_CLOSEST_TO_INPUT;
else
matchOptions.eResolution = DXUTMT_IGNORE_INPUT;
matchOptions.eBackBufferFormat = DXUTMT_IGNORE_INPUT;
matchOptions.eBackBufferCount = DXUTMT_IGNORE_INPUT;
matchOptions.eMultiSample = DXUTMT_CLOSEST_TO_INPUT; // NV: default to 16x CSAA.
matchOptions.eSwapEffect = DXUTMT_IGNORE_INPUT;
matchOptions.eDepthFormat = DXUTMT_IGNORE_INPUT;
matchOptions.eStencilFormat = DXUTMT_IGNORE_INPUT;
matchOptions.ePresentFlags = DXUTMT_IGNORE_INPUT;
matchOptions.eRefreshRate = DXUTMT_IGNORE_INPUT;
matchOptions.ePresentInterval = DXUTMT_IGNORE_INPUT;
// Building D3D9 device settings for mathch options. These
// will be converted to D3D10 settings if app can use D3D10
DXUTDeviceSettings deviceSettings;
ZeroMemory( &deviceSettings, sizeof(DXUTDeviceSettings) );
deviceSettings.ver = DXUT_D3D9_DEVICE;
deviceSettings.d3d9.pp.Windowed = bWindowed;
deviceSettings.d3d9.pp.BackBufferWidth = nSuggestedWidth;
deviceSettings.d3d9.pp.BackBufferHeight = nSuggestedHeight;
// NV: default to 16x CSAA:
deviceSettings.d3d9.pp.MultiSampleType = D3DMULTISAMPLE_4_SAMPLES;
deviceSettings.d3d9.pp.MultiSampleQuality = 16;
// Override with settings from the command line
if( GetDXUTState().GetOverrideWidth() != 0 )
{
deviceSettings.d3d9.pp.BackBufferWidth = GetDXUTState().GetOverrideWidth();
matchOptions.eResolution = DXUTMT_PRESERVE_INPUT;
}
if( GetDXUTState().GetOverrideHeight() != 0 )
{
deviceSettings.d3d9.pp.BackBufferHeight = GetDXUTState().GetOverrideHeight();
matchOptions.eResolution = DXUTMT_PRESERVE_INPUT;
}
if( GetDXUTState().GetOverrideAdapterOrdinal() != -1 )
{
deviceSettings.d3d9.AdapterOrdinal = GetDXUTState().GetOverrideAdapterOrdinal();
matchOptions.eDeviceType = DXUTMT_PRESERVE_INPUT;
}
if( GetDXUTState().GetOverrideFullScreen() )
{
deviceSettings.d3d9.pp.Windowed = FALSE;
if( GetDXUTState().GetOverrideWidth() == 0 && GetDXUTState().GetOverrideHeight() == 0 )
matchOptions.eResolution = DXUTMT_IGNORE_INPUT;
}
if( GetDXUTState().GetOverrideWindowed() )
deviceSettings.d3d9.pp.Windowed = TRUE;
if( GetDXUTState().GetOverrideForceHAL() )
{
deviceSettings.d3d9.DeviceType = D3DDEVTYPE_HAL;
matchOptions.eDeviceType = DXUTMT_PRESERVE_INPUT;
}
if( GetDXUTState().GetOverrideForceREF() )
{
deviceSettings.d3d9.DeviceType = D3DDEVTYPE_REF;
matchOptions.eDeviceType = DXUTMT_PRESERVE_INPUT;
}
if( GetDXUTState().GetOverrideForcePureHWVP() )
{
deviceSettings.d3d9.BehaviorFlags = D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE;
matchOptions.eVertexProcessing = DXUTMT_PRESERVE_INPUT;
}
else if( GetDXUTState().GetOverrideForceHWVP() )
{
deviceSettings.d3d9.BehaviorFlags = D3DCREATE_HARDWARE_VERTEXPROCESSING;
matchOptions.eVertexProcessing = DXUTMT_PRESERVE_INPUT;
}
else if( GetDXUTState().GetOverrideForceSWVP() )
{
deviceSettings.d3d9.BehaviorFlags = D3DCREATE_SOFTWARE_VERTEXPROCESSING;
matchOptions.eVertexProcessing = DXUTMT_PRESERVE_INPUT;
}
if( GetDXUTState().GetOverrideForceVsync() == 0 )
{
deviceSettings.d3d9.pp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
matchOptions.ePresentInterval = DXUTMT_PRESERVE_INPUT;
}
else if( GetDXUTState().GetOverrideForceVsync() == 1 )
{
deviceSettings.d3d9.pp.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;
matchOptions.ePresentInterval = DXUTMT_PRESERVE_INPUT;
}
if( GetDXUTState().GetOverrideForceAPI() != -1 )
{
if( GetDXUTState().GetOverrideForceAPI() == 9 )
{
deviceSettings.ver = DXUT_D3D9_DEVICE;
matchOptions.eAPIVersion = DXUTMT_PRESERVE_INPUT;
}
else if( GetDXUTState().GetOverrideForceAPI() == 10 )
{
deviceSettings.ver = DXUT_D3D10_DEVICE;
matchOptions.eAPIVersion = DXUTMT_PRESERVE_INPUT;
// Convert the struct we're making to be D3D10 settings since
// that is what DXUTFindValidDeviceSettings will expect
DXUTD3D10DeviceSettings d3d10In;
ZeroMemory( &d3d10In, sizeof(DXUTD3D10DeviceSettings) );
DXUTConvertDeviceSettings9to10( &deviceSettings.d3d9, &d3d10In );
deviceSettings.d3d10 = d3d10In;
}
}
hr = DXUTFindValidDeviceSettings( &deviceSettings, &deviceSettings, &matchOptions );
if( FAILED(hr) ) // the call will fail if no valid devices were found
{
DXUTDisplayErrorMessage( hr );
return DXUT_ERR( L"DXUTFindValidDeviceSettings", hr );
}
// Change to a Direct3D device created from the new device settings.
// If there is an existing device, then either reset or recreated the scene
hr = DXUTChangeDevice( &deviceSettings, NULL, NULL, false, true );
if( FAILED(hr) )
return hr;
return S_OK;
}
//--------------------------------------------------------------------------------------
// Tells the framework to change to a device created from the passed in device settings
// If DXUTCreateWindow() has not already been called, it will call it with the
// default parameters. Instead of calling this, you can call DXUTCreateDevice()
// or DXUTSetD3D*Device()
//--------------------------------------------------------------------------------------
HRESULT WINAPI DXUTCreateDeviceFromSettings( DXUTDeviceSettings* pDeviceSettings, bool bPreserveInput, bool bClipWindowToSingleAdapter )
{
HRESULT hr;
GetDXUTState().SetDeviceCreateCalled( true );
// If DXUTCreateWindow() or DXUTSetWindow() has not already been called,
// then call DXUTCreateWindow() with the default parameters.
if( !GetDXUTState().GetWindowCreated() )
{
// If DXUTCreateWindow() or DXUTSetWindow() was already called and failed, then fail.
// DXUTCreateWindow() or DXUTSetWindow() must first succeed for this function to succeed
if( GetDXUTState().GetWindowCreateCalled() )
return E_FAIL;
// If DXUTCreateWindow() or DXUTSetWindow() hasn't been called, then
// automatically call DXUTCreateWindow() with default params
hr = DXUTCreateWindow();
if( FAILED(hr) )
return hr;
}
if( !bPreserveInput )
{
// If not preserving the input, then find the closest valid to it
DXUTMatchOptions matchOptions;
matchOptions.eAPIVersion = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eAdapterOrdinal = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eOutput = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eDeviceType = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eWindowed = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eAdapterFormat = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eVertexProcessing = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eResolution = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eBackBufferFormat = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eBackBufferCount = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eMultiSample = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eSwapEffect = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eDepthFormat = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eStencilFormat = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.ePresentFlags = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eRefreshRate = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.ePresentInterval = DXUTMT_CLOSEST_TO_INPUT;
hr = DXUTFindValidDeviceSettings( pDeviceSettings, pDeviceSettings, &matchOptions );
if( FAILED(hr) ) // the call will fail if no valid devices were found
{
DXUTDisplayErrorMessage( hr );
return DXUT_ERR( L"DXUTFindValidD3D9DeviceSettings", hr );
}
}
// Change to a Direct3D device created from the new device settings.
// If there is an existing device, then either reset or recreate the scene
hr = DXUTChangeDevice( pDeviceSettings, NULL, NULL, false, bClipWindowToSingleAdapter );
if( FAILED(hr) )
return hr;
return S_OK;
}
//--------------------------------------------------------------------------------------
// All device changes are sent to this function. It looks at the current
// device (if any) and the new device and determines the best course of action. It
// also remembers and restores the window state if toggling between windowed and fullscreen
// as well as sets the proper window and system state for switching to the new device.
//--------------------------------------------------------------------------------------
HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings,
IDirect3DDevice9* pd3d9DeviceFromApp, ID3D10Device* pd3d10DeviceFromApp,
bool bForceRecreate, bool bClipWindowToSingleAdapter )
{
HRESULT hr;
DXUTDeviceSettings* pOldDeviceSettings = GetDXUTState().GetCurrentDeviceSettings();
if( !pNewDeviceSettings )
return S_FALSE;
if( pNewDeviceSettings->ver == DXUT_D3D9_DEVICE )
hr = DXUTDelayLoadD3D9();
else
hr = DXUTDelayLoadDXGI();
if( FAILED(hr) )
return DXUTERR_NODIRECT3D;
// Make a copy of the pNewDeviceSettings on the heap
DXUTDeviceSettings* pNewDeviceSettingsOnHeap = new DXUTDeviceSettings;
if( pNewDeviceSettingsOnHeap == NULL )
return E_OUTOFMEMORY;
memcpy( pNewDeviceSettingsOnHeap, pNewDeviceSettings, sizeof(DXUTDeviceSettings) );
pNewDeviceSettings = pNewDeviceSettingsOnHeap;
// If the ModifyDeviceSettings callback is non-NULL, then call it to let the app
// change the settings or reject the device change by returning false.
LPDXUTCALLBACKMODIFYDEVICESETTINGS pCallbackModifyDeviceSettings = GetDXUTState().GetModifyDeviceSettingsFunc();
if( pCallbackModifyDeviceSettings && pd3d9DeviceFromApp == NULL && pd3d10DeviceFromApp == NULL )
{
bool bContinue = pCallbackModifyDeviceSettings( pNewDeviceSettings, GetDXUTState().GetModifyDeviceSettingsFuncUserContext() );
if( !bContinue )
{
// The app rejected the device change by returning false, so just use the current device if there is one.
if( pOldDeviceSettings == NULL )
DXUTDisplayErrorMessage( DXUTERR_NOCOMPATIBLEDEVICES );
SAFE_DELETE( pNewDeviceSettings );
return E_ABORT;
}
if( GetDXUTState().GetD3D9() == NULL && GetDXUTState().GetDXGIFactory() == NULL ) // if DXUTShutdown() was called in the modify callback, just return
{
SAFE_DELETE( pNewDeviceSettings );
return S_FALSE;
}
}
GetDXUTState().SetCurrentDeviceSettings( pNewDeviceSettings );
DXUTPause( true, true );
// When a WM_SIZE message is received, it calls DXUTCheckForWindowSizeChange().
// A WM_SIZE message might be sent when adjusting the window, so tell
// DXUTCheckForWindowSizeChange() to ignore size changes temporarily
if( DXUTIsCurrentDeviceD3D9() )
GetDXUTState().SetIgnoreSizeChange( true );
// Only apply the cmd line overrides if this is the first device created
// and DXUTSetD3D*Device() isn't used
if( NULL == pd3d9DeviceFromApp && NULL == pd3d10DeviceFromApp && NULL == pOldDeviceSettings )
{
// Updates the device settings struct based on the cmd line args.
// Warning: if the device doesn't support these new settings then CreateDevice9() will fail.
DXUTUpdateDeviceSettingsWithOverrides( pNewDeviceSettings );
}
// Take note if the backbuffer width & height are 0 now as they will change after pd3dDevice->Reset()
bool bKeepCurrentWindowSize = false;
if( DXUTGetBackBufferWidthFromDS( pNewDeviceSettings ) == 0 && DXUTGetBackBufferHeightFromDS( pNewDeviceSettings ) == 0 )
bKeepCurrentWindowSize = true;
//////////////////////////
// Before reset
/////////////////////////
// If we are using D3D9, adjust window style when switching from windowed to fullscreen and
// vice versa. Note that this is not necessary in D3D10 because DXGI handles this. If both
// DXUT and DXGI handle this, incorrect behavior would result.
if( DXUTIsCurrentDeviceD3D9() )
{
if( DXUTGetIsWindowedFromDS(pNewDeviceSettings) )
{
// Going to windowed mode
if( pOldDeviceSettings && !DXUTGetIsWindowedFromDS( pOldDeviceSettings ) )
{
// Going from fullscreen -> windowed
GetDXUTState().SetFullScreenBackBufferWidthAtModeChange( DXUTGetBackBufferWidthFromDS(pOldDeviceSettings) );
GetDXUTState().SetFullScreenBackBufferHeightAtModeChange( DXUTGetBackBufferHeightFromDS(pOldDeviceSettings) );
// Restore windowed mode style
SetWindowLong( DXUTGetHWNDDeviceWindowed(), GWL_STYLE, GetDXUTState().GetWindowedStyleAtModeChange() );
}
// If different device windows are used for windowed mode and fullscreen mode,
// hide the fullscreen window so that it doesn't obscure the screen.
if( DXUTGetHWNDDeviceFullScreen() != DXUTGetHWNDDeviceWindowed() )
ShowWindow( DXUTGetHWNDDeviceFullScreen(), SW_HIDE );
// If using the same window for windowed and fullscreen mode, reattach menu if one exists
if( DXUTGetHWNDDeviceFullScreen() == DXUTGetHWNDDeviceWindowed() )
{
if( GetDXUTState().GetMenu() != NULL )
SetMenu( DXUTGetHWNDDeviceWindowed(), GetDXUTState().GetMenu() );
}
}
else
{
// Going to fullscreen mode
if( pOldDeviceSettings == NULL || (pOldDeviceSettings && DXUTGetIsWindowedFromDS(pOldDeviceSettings) ) )
{
// Transistioning to full screen mode from a standard window so
// save current window position/size/style now in case the user toggles to windowed mode later
WINDOWPLACEMENT* pwp = GetDXUTState().GetWindowedPlacement();
ZeroMemory( pwp, sizeof(WINDOWPLACEMENT) );
pwp->length = sizeof(WINDOWPLACEMENT);
GetWindowPlacement( DXUTGetHWNDDeviceWindowed(), pwp );
bool bIsTopmost = ( (GetWindowLong(DXUTGetHWNDDeviceWindowed(),GWL_EXSTYLE) & WS_EX_TOPMOST) != 0);
GetDXUTState().SetTopmostWhileWindowed( bIsTopmost );
DWORD dwStyle = GetWindowLong( DXUTGetHWNDDeviceWindowed(), GWL_STYLE );
dwStyle &= ~WS_MAXIMIZE & ~WS_MINIMIZE; // remove minimize/maximize style
GetDXUTState().SetWindowedStyleAtModeChange( dwStyle );
if( pOldDeviceSettings )
{
GetDXUTState().SetWindowBackBufferWidthAtModeChange( DXUTGetBackBufferWidthFromDS(pOldDeviceSettings) );
GetDXUTState().SetWindowBackBufferHeightAtModeChange( DXUTGetBackBufferHeightFromDS(pOldDeviceSettings) );
}
}
// Hide the window to avoid animation of blank windows
ShowWindow( DXUTGetHWNDDeviceFullScreen(), SW_HIDE );
// Set FS window style
SetWindowLong( DXUTGetHWNDDeviceFullScreen(), GWL_STYLE, WS_POPUP|WS_SYSMENU );
// If using the same window for windowed and fullscreen mode, save and remove menu
if( DXUTGetHWNDDeviceFullScreen() == DXUTGetHWNDDeviceWindowed() )
{
HMENU hMenu = GetMenu( DXUTGetHWNDDeviceFullScreen() );
GetDXUTState().SetMenu( hMenu );
SetMenu( DXUTGetHWNDDeviceFullScreen(), NULL );
}
WINDOWPLACEMENT wpFullscreen;
ZeroMemory( &wpFullscreen, sizeof(WINDOWPLACEMENT) );
wpFullscreen.length = sizeof(WINDOWPLACEMENT);
GetWindowPlacement( DXUTGetHWNDDeviceFullScreen(), &wpFullscreen );
if( (wpFullscreen.flags & WPF_RESTORETOMAXIMIZED) != 0 )
{
// Restore the window to normal if the window was maximized then minimized. This causes the
// WPF_RESTORETOMAXIMIZED flag to be set which will cause SW_RESTORE to restore the
// window from minimized to maxmized which isn't what we want
wpFullscreen.flags &= ~WPF_RESTORETOMAXIMIZED;
wpFullscreen.showCmd = SW_RESTORE;
SetWindowPlacement( DXUTGetHWNDDeviceFullScreen(), &wpFullscreen );
}
}
}
else
{
if( DXUTGetIsWindowedFromDS(pNewDeviceSettings) )
{
// Going to windowed mode
if( pOldDeviceSettings && !DXUTGetIsWindowedFromDS( pOldDeviceSettings ) )
{
// Going from fullscreen -> windowed
GetDXUTState().SetFullScreenBackBufferWidthAtModeChange( DXUTGetBackBufferWidthFromDS(pOldDeviceSettings) );
GetDXUTState().SetFullScreenBackBufferHeightAtModeChange( DXUTGetBackBufferHeightFromDS(pOldDeviceSettings) );
}
}
else
{
// Going to fullscreen mode
if( pOldDeviceSettings == NULL || (pOldDeviceSettings && DXUTGetIsWindowedFromDS(pOldDeviceSettings) ) )
{
// Transistioning to full screen mode from a standard window so
if( pOldDeviceSettings )
{
GetDXUTState().SetWindowBackBufferWidthAtModeChange( DXUTGetBackBufferWidthFromDS(pOldDeviceSettings) );
GetDXUTState().SetWindowBackBufferHeightAtModeChange( DXUTGetBackBufferHeightFromDS(pOldDeviceSettings) );
}
}
}
}
// If API version, AdapterOrdinal and DeviceType are the same, we can just do a Reset().
// If they've changed, we need to do a complete device tear down/rebuild.
// Also only allow a reset if pd3dDevice is the same as the current device
if( !bForceRecreate &&
DXUTCanDeviceBeReset( pOldDeviceSettings, pNewDeviceSettings, pd3d9DeviceFromApp, pd3d10DeviceFromApp ) )
{
// Reset the Direct3D device and call the app's device callbacks
if( DXUTIsD3D9( pOldDeviceSettings ) )
hr = DXUTReset3DEnvironment9();
else
hr = DXUTReset3DEnvironment10();
if( FAILED(hr) )
{
if( D3DERR_DEVICELOST == hr )
{
// The device is lost, just mark it as so and continue on with
// capturing the state and resizing the window/etc.
GetDXUTState().SetDeviceLost( true );
}
else if( DXUTERR_RESETTINGDEVICEOBJECTS == hr ||
DXUTERR_MEDIANOTFOUND == hr )
{
// Something bad happened in the app callbacks
SAFE_DELETE( pOldDeviceSettings );
DXUTDisplayErrorMessage( hr );
DXUTShutdown();
return hr;
}
else // DXUTERR_RESETTINGDEVICE
{
// Reset failed and the device wasn't lost and it wasn't the apps fault,
// so recreate the device to try to recover
GetDXUTState().SetCurrentDeviceSettings( pOldDeviceSettings );
if( FAILED( DXUTChangeDevice( pNewDeviceSettings, pd3d9DeviceFromApp, pd3d10DeviceFromApp, true, bClipWindowToSingleAdapter ) ) )
{
// If that fails, then shutdown
DXUTShutdown();
return DXUTERR_CREATINGDEVICE;
}
else
{
DXUTPause( false, false );
return S_OK;
}
}
}
}
else
{
// Cleanup if not first device created
if( pOldDeviceSettings )
DXUTCleanup3DEnvironment( false );
// Create the D3D device and call the app's device callbacks
if( DXUTIsD3D9( pNewDeviceSettings ) )
hr = DXUTCreate3DEnvironment9( pd3d9DeviceFromApp );
else
hr = DXUTCreate3DEnvironment10( pd3d10DeviceFromApp );
if( FAILED(hr) )
{
SAFE_DELETE( pOldDeviceSettings );
DXUTCleanup3DEnvironment( true );
DXUTDisplayErrorMessage( hr );
DXUTPause( false, false );
GetDXUTState().SetIgnoreSizeChange( false );
return hr;
}
}
// Enable/disable StickKeys shortcut, ToggleKeys shortcut, FilterKeys shortcut, and Windows key
// to prevent accidental task switching
DXUTAllowShortcutKeys( ( DXUTGetIsWindowedFromDS(pNewDeviceSettings) ) ? GetDXUTState().GetAllowShortcutKeysWhenWindowed() : GetDXUTState().GetAllowShortcutKeysWhenFullscreen() );
HMONITOR hAdapterMonitor = DXUTGetMonitorFromAdapter( pNewDeviceSettings );
GetDXUTState().SetAdapterMonitor( hAdapterMonitor );
// Update the device stats text
DXUTUpdateStaticFrameStats();
if( pOldDeviceSettings && !DXUTGetIsWindowedFromDS(pOldDeviceSettings) && DXUTGetIsWindowedFromDS(pNewDeviceSettings) )
{
// Going from fullscreen -> windowed
// Restore the show state, and positions/size of the window to what it was
// It is important to adjust the window size
// after resetting the device rather than beforehand to ensure
// that the monitor resolution is correct and does not limit the size of the new window.
WINDOWPLACEMENT* pwp = GetDXUTState().GetWindowedPlacement();
SetWindowPlacement( DXUTGetHWNDDeviceWindowed(), pwp );
// Also restore the z-order of window to previous state
HWND hWndInsertAfter = GetDXUTState().GetTopmostWhileWindowed() ? HWND_TOPMOST : HWND_NOTOPMOST;
SetWindowPos( DXUTGetHWNDDeviceWindowed(), hWndInsertAfter, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOREDRAW|SWP_NOSIZE );
}
// Check to see if the window needs to be resized.
// Handle cases where the window is minimized and maxmimized as well.
bool bNeedToResize = false;
if( DXUTGetIsWindowedFromDS(pNewDeviceSettings) && // only resize if in windowed mode
!bKeepCurrentWindowSize ) // only resize if pp.BackbufferWidth/Height were not 0
{
UINT nClientWidth;
UINT nClientHeight;
if( IsIconic(DXUTGetHWNDDeviceWindowed()) )
{
// Window is currently minimized. To tell if it needs to resize,
// get the client rect of window when its restored the
// hard way using GetWindowPlacement()
WINDOWPLACEMENT wp;
ZeroMemory( &wp, sizeof(WINDOWPLACEMENT) );
wp.length = sizeof(WINDOWPLACEMENT);
GetWindowPlacement( DXUTGetHWNDDeviceWindowed(), &wp );
if( (wp.flags & WPF_RESTORETOMAXIMIZED) != 0 && wp.showCmd == SW_SHOWMINIMIZED )
{
// WPF_RESTORETOMAXIMIZED means that when the window is restored it will
// be maximized. So maximize the window temporarily to get the client rect
// when the window is maximized. GetSystemMetrics( SM_CXMAXIMIZED ) will give this
// information if the window is on the primary but this will work on multimon.
ShowWindow( DXUTGetHWNDDeviceWindowed(), SW_RESTORE );
RECT rcClient;
GetClientRect( DXUTGetHWNDDeviceWindowed(), &rcClient );
nClientWidth = (UINT)(rcClient.right - rcClient.left);
nClientHeight = (UINT)(rcClient.bottom - rcClient.top);
ShowWindow( DXUTGetHWNDDeviceWindowed(), SW_MINIMIZE );
}
else
{
// Use wp.rcNormalPosition to get the client rect, but wp.rcNormalPosition
// includes the window frame so subtract it
RECT rcFrame = {0};
AdjustWindowRect( &rcFrame, GetDXUTState().GetWindowedStyleAtModeChange(), GetDXUTState().GetMenu() != NULL );
LONG nFrameWidth = rcFrame.right - rcFrame.left;
LONG nFrameHeight = rcFrame.bottom - rcFrame.top;
nClientWidth = (UINT)(wp.rcNormalPosition.right - wp.rcNormalPosition.left - nFrameWidth);
nClientHeight = (UINT)(wp.rcNormalPosition.bottom - wp.rcNormalPosition.top - nFrameHeight);
}
}
else
{
// Window is restored or maximized so just get its client rect
RECT rcClient;
GetClientRect( DXUTGetHWNDDeviceWindowed(), &rcClient );
nClientWidth = (UINT)(rcClient.right - rcClient.left);
nClientHeight = (UINT)(rcClient.bottom - rcClient.top);
}
// Now that we know the client rect, compare it against the back buffer size
// to see if the client rect is already the right size
if( nClientWidth != DXUTGetBackBufferWidthFromDS(pNewDeviceSettings) ||
nClientHeight != DXUTGetBackBufferHeightFromDS(pNewDeviceSettings) )
{
bNeedToResize = true;
}
if( bClipWindowToSingleAdapter && !IsIconic(DXUTGetHWNDDeviceWindowed()) )
{
// Get the rect of the monitor attached to the adapter
MONITORINFO miAdapter;
miAdapter.cbSize = sizeof(MONITORINFO);
HMONITOR hAdapterMonitor = DXUTGetMonitorFromAdapter( pNewDeviceSettings );
DXUTGetMonitorInfo( hAdapterMonitor, &miAdapter );
HMONITOR hWindowMonitor = DXUTMonitorFromWindow( DXUTGetHWND(), MONITOR_DEFAULTTOPRIMARY );
// Get the rect of the window
RECT rcWindow;
GetWindowRect( DXUTGetHWNDDeviceWindowed(), &rcWindow );
// Check if the window rect is fully inside the adapter's vitural screen rect
if( (rcWindow.left < miAdapter.rcWork.left ||
rcWindow.right > miAdapter.rcWork.right ||
rcWindow.top < miAdapter.rcWork.top ||
rcWindow.bottom > miAdapter.rcWork.bottom) )
{
if( hWindowMonitor == hAdapterMonitor && IsZoomed(DXUTGetHWNDDeviceWindowed()) )
{
// If the window is maximized and on the same monitor as the adapter, then
// no need to clip to single adapter as the window is already clipped
// even though the rcWindow rect is outside of the miAdapter.rcWork
}
else
{
bNeedToResize = true;
}
}
}
}
// Only resize window if needed
if( bNeedToResize )
{
// Need to resize, so if window is maximized or minimized then restore the window
if( IsIconic(DXUTGetHWNDDeviceWindowed()) )
ShowWindow( DXUTGetHWNDDeviceWindowed(), SW_RESTORE );
if( IsZoomed(DXUTGetHWNDDeviceWindowed()) ) // doing the IsIconic() check first also handles the WPF_RESTORETOMAXIMIZED case
ShowWindow( DXUTGetHWNDDeviceWindowed(), SW_RESTORE );
if( bClipWindowToSingleAdapter )
{
// Get the rect of the monitor attached to the adapter
MONITORINFO miAdapter;
miAdapter.cbSize = sizeof(MONITORINFO);
HMONITOR hAdapterMonitor = DXUTGetMonitorFromAdapter( pNewDeviceSettings );
DXUTGetMonitorInfo( hAdapterMonitor, &miAdapter );
// Get the rect of the monitor attached to the window
MONITORINFO miWindow;
miWindow.cbSize = sizeof(MONITORINFO);
DXUTGetMonitorInfo( DXUTMonitorFromWindow( DXUTGetHWND(), MONITOR_DEFAULTTOPRIMARY ), &miWindow );
// Do something reasonable if the BackBuffer size is greater than the monitor size
int nAdapterMonitorWidth = miAdapter.rcWork.right - miAdapter.rcWork.left;
int nAdapterMonitorHeight = miAdapter.rcWork.bottom - miAdapter.rcWork.top;
int nClientWidth = DXUTGetBackBufferWidthFromDS( pNewDeviceSettings );
int nClientHeight = DXUTGetBackBufferHeightFromDS( pNewDeviceSettings );
// Get the rect of the window
RECT rcWindow;
GetWindowRect( DXUTGetHWNDDeviceWindowed(), &rcWindow );
// Make a window rect with a client rect that is the same size as the backbuffer
RECT rcResizedWindow;
rcResizedWindow.left = 0;
rcResizedWindow.right = nClientWidth;
rcResizedWindow.top = 0;
rcResizedWindow.bottom = nClientHeight;
AdjustWindowRect( &rcResizedWindow, GetWindowLong( DXUTGetHWNDDeviceWindowed(), GWL_STYLE ), GetDXUTState().GetMenu() != NULL );
int nWindowWidth = rcResizedWindow.right - rcResizedWindow.left;
int nWindowHeight = rcResizedWindow.bottom - rcResizedWindow.top;
if( nWindowWidth > nAdapterMonitorWidth )
nWindowWidth = nAdapterMonitorWidth;
if( nWindowHeight > nAdapterMonitorHeight )
nWindowHeight = nAdapterMonitorHeight;
if( rcResizedWindow.left < miAdapter.rcWork.left ||
rcResizedWindow.top < miAdapter.rcWork.top ||
rcResizedWindow.right > miAdapter.rcWork.right ||
rcResizedWindow.bottom > miAdapter.rcWork.bottom )
{
int nWindowOffsetX = (nAdapterMonitorWidth - nWindowWidth) / 2;
int nWindowOffsetY = (nAdapterMonitorHeight - nWindowHeight) / 2;
rcResizedWindow.left = miAdapter.rcWork.left + nWindowOffsetX;
rcResizedWindow.top = miAdapter.rcWork.top + nWindowOffsetY;
rcResizedWindow.right = miAdapter.rcWork.left + nWindowOffsetX + nWindowWidth;
rcResizedWindow.bottom = miAdapter.rcWork.top + nWindowOffsetY + nWindowHeight;
}
// Resize the window. It is important to adjust the window size
// after resetting the device rather than beforehand to ensure
// that the monitor resolution is correct and does not limit the size of the new window.
SetWindowPos( DXUTGetHWNDDeviceWindowed(), 0, rcResizedWindow.left, rcResizedWindow.top, nWindowWidth, nWindowHeight, SWP_NOZORDER );
}
else
{
// Make a window rect with a client rect that is the same size as the backbuffer
RECT rcWindow = {0};
rcWindow.right = (long)( DXUTGetBackBufferWidthFromDS(pNewDeviceSettings) );
rcWindow.bottom = (long)( DXUTGetBackBufferHeightFromDS(pNewDeviceSettings) );
AdjustWindowRect( &rcWindow, GetWindowLong( DXUTGetHWNDDeviceWindowed(), GWL_STYLE ), GetDXUTState().GetMenu() != NULL );
// Resize the window. It is important to adjust the window size
// after resetting the device rather than beforehand to ensure
// that the monitor resolution is correct and does not limit the size of the new window.
int cx = (int)(rcWindow.right - rcWindow.left);
int cy = (int)(rcWindow.bottom - rcWindow.top);
SetWindowPos( DXUTGetHWNDDeviceWindowed(), 0, 0, 0, cx, cy, SWP_NOZORDER|SWP_NOMOVE );
}
// Its possible that the new window size is not what we asked for.
// No window can be sized larger than the desktop, so see if the Windows OS resized the
// window to something smaller to fit on the desktop. Also if WM_GETMINMAXINFO
// will put a limit on the smallest/largest window size.
RECT rcClient;
GetClientRect( DXUTGetHWNDDeviceWindowed(), &rcClient );
UINT nClientWidth = (UINT)(rcClient.right - rcClient.left);
UINT nClientHeight = (UINT)(rcClient.bottom - rcClient.top);
if( nClientWidth != DXUTGetBackBufferWidthFromDS(pNewDeviceSettings) ||
nClientHeight != DXUTGetBackBufferHeightFromDS(pNewDeviceSettings) )
{
// If its different, then resize the backbuffer again. This time create a backbuffer that matches the
// client rect of the current window w/o resizing the window.
DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings();
if( DXUTIsD3D9( &deviceSettings ) ) deviceSettings.d3d9.pp.BackBufferWidth = 0; else deviceSettings.d3d10.sd.BufferDesc.Width = 0;
if( DXUTIsD3D9( &deviceSettings ) ) deviceSettings.d3d9.pp.BackBufferHeight = 0; else deviceSettings.d3d10.sd.BufferDesc.Height = 0;
hr = DXUTChangeDevice( &deviceSettings, NULL, NULL, false, bClipWindowToSingleAdapter );
if( FAILED( hr ) )
{
SAFE_DELETE( pOldDeviceSettings );
DXUTCleanup3DEnvironment( true );
DXUTPause( false, false );
GetDXUTState().SetIgnoreSizeChange( false );
return hr;
}
}
}
// Make the window visible
if( !IsWindowVisible( DXUTGetHWND() ) )
ShowWindow( DXUTGetHWND(), SW_SHOW );
// Ensure that the display doesn't power down when fullscreen but does when windowed
if( !DXUTIsWindowed() )
SetThreadExecutionState( ES_DISPLAY_REQUIRED | ES_CONTINUOUS );
else
SetThreadExecutionState( ES_CONTINUOUS );
SAFE_DELETE( pOldDeviceSettings );
GetDXUTState().SetIgnoreSizeChange( false );
DXUTPause( false, false );
GetDXUTState().SetDeviceCreated( true );
return S_OK;
}
//--------------------------------------------------------------------------------------
// Check if the new device is close enough to the old device to simply reset or
// resize the back buffer
//--------------------------------------------------------------------------------------
bool DXUTCanDeviceBeReset( DXUTDeviceSettings *pOldDeviceSettings, DXUTDeviceSettings *pNewDeviceSettings,
IDirect3DDevice9 *pd3d9DeviceFromApp, ID3D10Device *pd3d10DeviceFromApp )
{
if( pOldDeviceSettings == NULL || pOldDeviceSettings->ver != pNewDeviceSettings->ver )
return false;
if( pNewDeviceSettings->ver == DXUT_D3D9_DEVICE )
{
if( DXUTGetD3D9Device() &&
(pd3d9DeviceFromApp == NULL || pd3d9DeviceFromApp == DXUTGetD3D9Device()) &&
(pOldDeviceSettings->d3d9.AdapterOrdinal == pNewDeviceSettings->d3d9.AdapterOrdinal) &&
(pOldDeviceSettings->d3d9.DeviceType == pNewDeviceSettings->d3d9.DeviceType) &&
(pOldDeviceSettings->d3d9.BehaviorFlags == pNewDeviceSettings->d3d9.BehaviorFlags) )
return true;
return false;
}
else
{
if( DXUTGetD3D10Device() &&
(pd3d10DeviceFromApp == NULL || pd3d10DeviceFromApp == DXUTGetD3D10Device()) &&
(pOldDeviceSettings->d3d10.AdapterOrdinal == pNewDeviceSettings->d3d10.AdapterOrdinal) &&
(pOldDeviceSettings->d3d10.DriverType == pNewDeviceSettings->d3d10.DriverType) &&
(pOldDeviceSettings->d3d10.CreateFlags == pNewDeviceSettings->d3d10.CreateFlags) &&
(pOldDeviceSettings->d3d10.sd.SampleDesc.Count == pNewDeviceSettings->d3d10.sd.SampleDesc.Count ) &&
(pOldDeviceSettings->d3d10.sd.SampleDesc.Quality == pNewDeviceSettings->d3d10.sd.SampleDesc.Quality ) )
return true;
return false;
}
}
//--------------------------------------------------------------------------------------
// Creates a DXGI factory object if one has not already been created
//--------------------------------------------------------------------------------------
HRESULT DXUTDelayLoadDXGI()
{
IDXGIFactory* pDXGIFactory = GetDXUTState().GetDXGIFactory();
if( pDXGIFactory == NULL )
{
DXUT_Dynamic_CreateDXGIFactory( __uuidof( IDXGIFactory ), (LPVOID*)&pDXGIFactory );
GetDXUTState().SetDXGIFactory( pDXGIFactory );
if( pDXGIFactory == NULL )
{
// If still NULL, then DXGI is not availible
GetDXUTState().SetD3D10Available( false );
return DXUTERR_NODIRECT3D;
}
GetDXUTState().SetD3D10Available( true );
}
return S_OK;
}
//--------------------------------------------------------------------------------------
// Creates a Direct3D object if one has not already been created
//--------------------------------------------------------------------------------------
HRESULT DXUTDelayLoadD3D9()
{
IDirect3D9* pD3D = GetDXUTState().GetD3D9();
if( pD3D == NULL )
{
// This may fail if Direct3D 9 isn't installed
// This may also fail if the Direct3D headers are somehow out of sync with the installed Direct3D DLLs
pD3D = DXUT_Dynamic_Direct3DCreate9( D3D_SDK_VERSION );
if( pD3D == NULL )
{
// If still NULL, then D3D9 is not availible
return DXUTERR_NODIRECT3D;
}
GetDXUTState().SetD3D9( pD3D );
}
return S_OK;
}
//--------------------------------------------------------------------------------------
// Updates the device settings struct based on the cmd line args.
//--------------------------------------------------------------------------------------
void DXUTUpdateDeviceSettingsWithOverrides( DXUTDeviceSettings* pDeviceSettings )
{
if( DXUTIsD3D9( pDeviceSettings ) )
{
if( GetDXUTState().GetOverrideAdapterOrdinal() != -1 )
pDeviceSettings->d3d9.AdapterOrdinal = GetDXUTState().GetOverrideAdapterOrdinal();
if( GetDXUTState().GetOverrideFullScreen() )
pDeviceSettings->d3d9.pp.Windowed = false;
if( GetDXUTState().GetOverrideWindowed() )
pDeviceSettings->d3d9.pp.Windowed = true;
if( GetDXUTState().GetOverrideForceREF() )
pDeviceSettings->d3d9.DeviceType = D3DDEVTYPE_REF;
else if( GetDXUTState().GetOverrideForceHAL() )
pDeviceSettings->d3d9.DeviceType = D3DDEVTYPE_HAL;
if( GetDXUTState().GetOverrideWidth() != 0 )
pDeviceSettings->d3d9.pp.BackBufferWidth = GetDXUTState().GetOverrideWidth();
if( GetDXUTState().GetOverrideHeight() != 0 )
pDeviceSettings->d3d9.pp.BackBufferHeight = GetDXUTState().GetOverrideHeight();
if( GetDXUTState().GetOverrideForcePureHWVP() )
{
pDeviceSettings->d3d9.BehaviorFlags &= ~D3DCREATE_SOFTWARE_VERTEXPROCESSING;
pDeviceSettings->d3d9.BehaviorFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING;
pDeviceSettings->d3d9.BehaviorFlags |= D3DCREATE_PUREDEVICE;
}
else if( GetDXUTState().GetOverrideForceHWVP() )
{
pDeviceSettings->d3d9.BehaviorFlags &= ~D3DCREATE_SOFTWARE_VERTEXPROCESSING;
pDeviceSettings->d3d9.BehaviorFlags &= ~D3DCREATE_PUREDEVICE;
pDeviceSettings->d3d9.BehaviorFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING;
}
else if( GetDXUTState().GetOverrideForceSWVP() )
{
pDeviceSettings->d3d9.BehaviorFlags &= ~D3DCREATE_HARDWARE_VERTEXPROCESSING;
pDeviceSettings->d3d9.BehaviorFlags &= ~D3DCREATE_PUREDEVICE;
pDeviceSettings->d3d9.BehaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING;
}
}
else
{
if( GetDXUTState().GetOverrideAdapterOrdinal() != -1 )
pDeviceSettings->d3d10.AdapterOrdinal = GetDXUTState().GetOverrideAdapterOrdinal();
if( GetDXUTState().GetOverrideFullScreen() )
{
pDeviceSettings->d3d10.sd.Windowed = false;
pDeviceSettings->d3d10.sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
}
if( GetDXUTState().GetOverrideWindowed() )
{
pDeviceSettings->d3d10.sd.Windowed = true;
pDeviceSettings->d3d10.sd.Flags = 0;
}
if( GetDXUTState().GetOverrideForceREF() )
pDeviceSettings->d3d10.DriverType = D3D10_DRIVER_TYPE_REFERENCE;
else if( GetDXUTState().GetOverrideForceHAL() )
pDeviceSettings->d3d10.DriverType = D3D10_DRIVER_TYPE_HARDWARE;
if( GetDXUTState().GetOverrideWidth() != 0 )
pDeviceSettings->d3d10.sd.BufferDesc.Width = GetDXUTState().GetOverrideWidth();
if( GetDXUTState().GetOverrideHeight() != 0 )
pDeviceSettings->d3d10.sd.BufferDesc.Height = GetDXUTState().GetOverrideHeight();
}
}
//--------------------------------------------------------------------------------------
// Allows the app to explictly state if it supports D3D9 or D3D10. Typically
// calling this is not needed as DXUT will auto-detect this based on the callbacks set.
//--------------------------------------------------------------------------------------
void WINAPI DXUTSetD3DVersionSupport( bool bAppCanUseD3D9, bool bAppCanUseD3D10 )
{
GetDXUTState().SetUseD3DVersionOverride( true );
GetDXUTState().SetAppSupportsD3D9Override( bAppCanUseD3D9 );
GetDXUTState().SetAppSupportsD3D10Override( bAppCanUseD3D10 );
}
//--------------------------------------------------------------------------------------
// Returns true if app has registered any D3D9 callbacks or
// used the DXUTSetD3DVersionSupport API and passed true for bAppCanUseD3D9
//--------------------------------------------------------------------------------------
bool WINAPI DXUTDoesAppSupportD3D9()
{
if( GetDXUTState().GetUseD3DVersionOverride() )
return GetDXUTState().GetAppSupportsD3D9Override();
else
return GetDXUTState().GetIsD3D9DeviceAcceptableFunc() ||
GetDXUTState().GetD3D9DeviceCreatedFunc() ||
GetDXUTState().GetD3D9DeviceResetFunc() ||
GetDXUTState().GetD3D9DeviceLostFunc() ||
GetDXUTState().GetD3D9DeviceDestroyedFunc() ||
GetDXUTState().GetD3D9FrameRenderFunc();
}
//--------------------------------------------------------------------------------------
// Returns true if app has registered any D3D10 callbacks or
// used the DXUTSetD3DVersionSupport API and passed true for bAppCanUseD3D10
//--------------------------------------------------------------------------------------
bool WINAPI DXUTDoesAppSupportD3D10()
{
if( GetDXUTState().GetUseD3DVersionOverride() )
return GetDXUTState().GetAppSupportsD3D10Override();
else
return GetDXUTState().GetIsD3D10DeviceAcceptableFunc() ||
GetDXUTState().GetD3D10DeviceCreatedFunc() ||
GetDXUTState().GetD3D10SwapChainResizedFunc() ||
GetDXUTState().GetD3D10FrameRenderFunc() ||
GetDXUTState().GetD3D10SwapChainReleasingFunc() ||
GetDXUTState().GetD3D10DeviceDestroyedFunc();
}
//======================================================================================
//======================================================================================
// Direct3D 9 section
//======================================================================================
//======================================================================================
//--------------------------------------------------------------------------------------
// Passes a previously created Direct3D9 device for use by the framework.
// If DXUTCreateWindow() has not already been called, it will call it with the
// default parameters. Instead of calling this, you can call DXUTCreateDevice() or
// DXUTCreateDeviceFromSettings()
//--------------------------------------------------------------------------------------
HRESULT WINAPI DXUTSetD3D9Device( IDirect3DDevice9* pd3dDevice )
{
HRESULT hr;
if( pd3dDevice == NULL )
return DXUT_ERR_MSGBOX( L"DXUTSetD3D9Device", E_INVALIDARG );
// Not allowed to call this from inside the device callbacks
if( GetDXUTState().GetInsideDeviceCallback() )
return DXUT_ERR_MSGBOX( L"DXUTSetD3D9Device", E_FAIL );
GetDXUTState().SetDeviceCreateCalled( true );
// If DXUTCreateWindow() or DXUTSetWindow() has not already been called,
// then call DXUTCreateWindow() with the default parameters.
if( !GetDXUTState().GetWindowCreated() )
{
// If DXUTCreateWindow() or DXUTSetWindow() was already called and failed, then fail.
// DXUTCreateWindow() or DXUTSetWindow() must first succeed for this function to succeed
if( GetDXUTState().GetWindowCreateCalled() )
return E_FAIL;
// If DXUTCreateWindow() or DXUTSetWindow() hasn't been called, then
// automatically call DXUTCreateWindow() with default params
hr = DXUTCreateWindow();
if( FAILED(hr) )
return hr;
}
DXUTDeviceSettings DeviceSettings;
ZeroMemory( &DeviceSettings, sizeof(DXUTDeviceSettings) );
DeviceSettings.ver = DXUT_D3D9_DEVICE;
// Get the present params from the swap chain
IDirect3DSurface9* pBackBuffer = NULL;
hr = pd3dDevice->GetBackBuffer( 0, 0, D3DBACKBUFFER_TYPE_MONO, &pBackBuffer );
if( SUCCEEDED(hr) )
{
IDirect3DSwapChain9* pSwapChain = NULL;
hr = pBackBuffer->GetContainer( IID_IDirect3DSwapChain9, (void**) &pSwapChain );
if( SUCCEEDED(hr) )
{
pSwapChain->GetPresentParameters( &DeviceSettings.d3d9.pp );
SAFE_RELEASE( pSwapChain );
}
SAFE_RELEASE( pBackBuffer );
}
D3DDEVICE_CREATION_PARAMETERS d3dCreationParams;
pd3dDevice->GetCreationParameters( &d3dCreationParams );
// Fill out the rest of the device settings struct
DeviceSettings.d3d9.AdapterOrdinal = d3dCreationParams.AdapterOrdinal;
DeviceSettings.d3d9.DeviceType = d3dCreationParams.DeviceType;
DXUTFindD3D9AdapterFormat( DeviceSettings.d3d9.AdapterOrdinal, DeviceSettings.d3d9.DeviceType,
DeviceSettings.d3d9.pp.BackBufferFormat, DeviceSettings.d3d9.pp.Windowed,
&DeviceSettings.d3d9.AdapterFormat );
DeviceSettings.d3d9.BehaviorFlags = d3dCreationParams.BehaviorFlags;
// Change to the Direct3D device passed in
hr = DXUTChangeDevice( &DeviceSettings, pd3dDevice, NULL, false, false );
if( FAILED(hr) )
return hr;
return S_OK;
}
//--------------------------------------------------------------------------------------
// Creates the 3D environment
//--------------------------------------------------------------------------------------
HRESULT DXUTCreate3DEnvironment9( IDirect3DDevice9* pd3dDeviceFromApp )
{
HRESULT hr = S_OK;
IDirect3DDevice9* pd3dDevice = NULL;
DXUTDeviceSettings* pNewDeviceSettings = GetDXUTState().GetCurrentDeviceSettings();
// Only create a Direct3D device if one hasn't been supplied by the app
if( pd3dDeviceFromApp == NULL )
{
// Try to create the device with the chosen settings
IDirect3D9* pD3D = DXUTGetD3D9Object();
hr = pD3D->CreateDevice( pNewDeviceSettings->d3d9.AdapterOrdinal, pNewDeviceSettings->d3d9.DeviceType,
DXUTGetHWNDFocus(), pNewDeviceSettings->d3d9.BehaviorFlags,
&pNewDeviceSettings->d3d9.pp, &pd3dDevice );
if( hr == D3DERR_DEVICELOST )
{
GetDXUTState().SetDeviceLost( true );
return S_OK;
}
else if( FAILED(hr) )
{
DXUT_ERR( L"CreateDevice", hr );
return DXUTERR_CREATINGDEVICE;
}
}
else
{
pd3dDeviceFromApp->AddRef();
pd3dDevice = pd3dDeviceFromApp;
}
GetDXUTState().SetD3D9Device( pd3dDevice );
// If switching to REF, set the exit code to 10. If switching to HAL and exit code was 10, then set it back to 0.
if( pNewDeviceSettings->d3d9.DeviceType == D3DDEVTYPE_REF && GetDXUTState().GetExitCode() == 0 )
GetDXUTState().SetExitCode(10);
else if( pNewDeviceSettings->d3d9.DeviceType == D3DDEVTYPE_HAL && GetDXUTState().GetExitCode() == 10 )
GetDXUTState().SetExitCode(0);
// Update back buffer desc before calling app's device callbacks
DXUTUpdateBackBufferDesc();
// Setup cursor based on current settings (window/fullscreen mode, show cursor state, clip cursor state)
DXUTSetupCursor();
// Update GetDXUTState()'s copy of D3D caps
D3DCAPS9* pd3dCaps = GetDXUTState().GetCaps();
DXUTGetD3D9Device()->GetDeviceCaps( pd3dCaps );
// Update the device stats text
CD3D9Enumeration* pd3dEnum = DXUTGetD3D9Enumeration();
CD3D9EnumAdapterInfo* pAdapterInfo = pd3dEnum->GetAdapterInfo( pNewDeviceSettings->d3d9.AdapterOrdinal );
DXUTUpdateD3D9DeviceStats( pNewDeviceSettings->d3d9.DeviceType,
pNewDeviceSettings->d3d9.BehaviorFlags,
&pAdapterInfo->AdapterIdentifier );
// Call the app's device created callback if non-NULL
const D3DSURFACE_DESC* pBackBufferSurfaceDesc = DXUTGetD3D9BackBufferSurfaceDesc();
GetDXUTState().SetInsideDeviceCallback( true );
LPDXUTCALLBACKD3D9DEVICECREATED pCallbackDeviceCreated = GetDXUTState().GetD3D9DeviceCreatedFunc();
hr = S_OK;
if( pCallbackDeviceCreated != NULL )
hr = pCallbackDeviceCreated( DXUTGetD3D9Device(), pBackBufferSurfaceDesc, GetDXUTState().GetD3D9DeviceCreatedFuncUserContext() );
GetDXUTState().SetInsideDeviceCallback( false );
if( DXUTGetD3D9Device() == NULL ) // Handle DXUTShutdown from inside callback
return E_FAIL;
if( FAILED(hr) )
{
DXUT_ERR( L"DeviceCreated callback", hr );
return ( hr == DXUTERR_MEDIANOTFOUND ) ? DXUTERR_MEDIANOTFOUND : DXUTERR_CREATINGDEVICEOBJECTS;
}
GetDXUTState().SetDeviceObjectsCreated( true );
// Call the app's device reset callback if non-NULL
GetDXUTState().SetInsideDeviceCallback( true );
LPDXUTCALLBACKD3D9DEVICERESET pCallbackDeviceReset = GetDXUTState().GetD3D9DeviceResetFunc();
hr = S_OK;
if( pCallbackDeviceReset != NULL )
hr = pCallbackDeviceReset( DXUTGetD3D9Device(), pBackBufferSurfaceDesc, GetDXUTState().GetD3D9DeviceResetFuncUserContext() );
GetDXUTState().SetInsideDeviceCallback( false );
if( DXUTGetD3D9Device() == NULL ) // Handle DXUTShutdown from inside callback
return E_FAIL;
if( FAILED(hr) )
{
DXUT_ERR( L"DeviceReset callback", hr );
return ( hr == DXUTERR_MEDIANOTFOUND ) ? DXUTERR_MEDIANOTFOUND : DXUTERR_RESETTINGDEVICEOBJECTS;
}
GetDXUTState().SetDeviceObjectsReset( true );
return S_OK;
}
//--------------------------------------------------------------------------------------
// Resets the 3D environment by:
// - Calls the device lost callback
// - Resets the device
// - Stores the back buffer description
// - Sets up the full screen Direct3D cursor if requested
// - Calls the device reset callback
//--------------------------------------------------------------------------------------
HRESULT DXUTReset3DEnvironment9()
{
HRESULT hr;
IDirect3DDevice9* pd3dDevice = DXUTGetD3D9Device();
assert( pd3dDevice != NULL );
// Call the app's device lost callback
if( GetDXUTState().GetDeviceObjectsReset() == true )
{
GetDXUTState().SetInsideDeviceCallback( true );
LPDXUTCALLBACKD3D9DEVICELOST pCallbackDeviceLost = GetDXUTState().GetD3D9DeviceLostFunc();
if( pCallbackDeviceLost != NULL )
pCallbackDeviceLost( GetDXUTState().GetD3D9DeviceLostFuncUserContext() );
GetDXUTState().SetDeviceObjectsReset( false );
GetDXUTState().SetInsideDeviceCallback( false );
}
// Reset the device
DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings();
hr = pd3dDevice->Reset( &pDeviceSettings->d3d9.pp );
if( FAILED(hr) )
{
if( hr == D3DERR_DEVICELOST )
return D3DERR_DEVICELOST; // Reset could legitimately fail if the device is lost
else
return DXUT_ERR( L"Reset", DXUTERR_RESETTINGDEVICE );
}
// Update back buffer desc before calling app's device callbacks
DXUTUpdateBackBufferDesc();
// Setup cursor based on current settings (window/fullscreen mode, show cursor state, clip cursor state)
DXUTSetupCursor();
// Call the app's OnDeviceReset callback
GetDXUTState().SetInsideDeviceCallback( true );
const D3DSURFACE_DESC* pBackBufferSurfaceDesc = DXUTGetD3D9BackBufferSurfaceDesc();
LPDXUTCALLBACKD3D9DEVICERESET pCallbackDeviceReset = GetDXUTState().GetD3D9DeviceResetFunc();
hr = S_OK;
if( pCallbackDeviceReset != NULL )
hr = pCallbackDeviceReset( pd3dDevice, pBackBufferSurfaceDesc, GetDXUTState().GetD3D9DeviceResetFuncUserContext() );
GetDXUTState().SetInsideDeviceCallback( false );
if( FAILED(hr) )
{
// If callback failed, cleanup
DXUT_ERR( L"DeviceResetCallback", hr );
if( hr != DXUTERR_MEDIANOTFOUND )
hr = DXUTERR_RESETTINGDEVICEOBJECTS;
GetDXUTState().SetInsideDeviceCallback( true );
LPDXUTCALLBACKD3D9DEVICELOST pCallbackDeviceLost = GetDXUTState().GetD3D9DeviceLostFunc();
if( pCallbackDeviceLost != NULL )
pCallbackDeviceLost( GetDXUTState().GetD3D9DeviceLostFuncUserContext() );
GetDXUTState().SetInsideDeviceCallback( false );
return hr;
}
// Success
GetDXUTState().SetDeviceObjectsReset( true );
return S_OK;
}
//--------------------------------------------------------------------------------------
// Render the 3D environment by:
// - Checking if the device is lost and trying to reset it if it is
// - Get the elapsed time since the last frame
// - Calling the app's framemove and render callback
// - Calling Present()
//--------------------------------------------------------------------------------------
void DXUTRender3DEnvironment9()
{
HRESULT hr;
if( GetDXUTState().GetDeviceLost() || DXUTIsRenderingPaused() || !DXUTIsActive() )
{
// Window is minimized or paused so yield CPU time to other processes
Sleep( 50 );
}
// If no device created yet because device was lost (ie. another fullscreen exclusive device exists),
// then wait and try to create every so often.
IDirect3DDevice9* pd3dDevice = DXUTGetD3D9Device();
if( NULL == pd3dDevice )
{
if( GetDXUTState().GetDeviceLost() )
{
DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings();
DXUTChangeDevice( &deviceSettings, NULL, NULL, false, true );
}
return;
}
if( GetDXUTState().GetDeviceLost() && !GetDXUTState().GetRenderingPaused() )
{
// Test the cooperative level to see if it's okay to render.
if( FAILED( hr = pd3dDevice->TestCooperativeLevel() ) )
{
if( D3DERR_DEVICELOST == hr )
{
// The device has been lost but cannot be reset at this time.
// So wait until it can be reset.
return;
}
// If we are windowed, read the desktop format and
// ensure that the Direct3D device is using the same format
// since the user could have changed the desktop bitdepth
if( DXUTIsWindowed() )
{
D3DDISPLAYMODE adapterDesktopDisplayMode;
IDirect3D9* pD3D = DXUTGetD3D9Object();
DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings();
pD3D->GetAdapterDisplayMode( pDeviceSettings->d3d9.AdapterOrdinal, &adapterDesktopDisplayMode );
if( pDeviceSettings->d3d9.AdapterFormat != adapterDesktopDisplayMode.Format )
{
DXUTMatchOptions matchOptions;
matchOptions.eAPIVersion = DXUTMT_PRESERVE_INPUT;
matchOptions.eAdapterOrdinal = DXUTMT_PRESERVE_INPUT;
matchOptions.eDeviceType = DXUTMT_PRESERVE_INPUT;
matchOptions.eWindowed = DXUTMT_PRESERVE_INPUT;
matchOptions.eAdapterFormat = DXUTMT_PRESERVE_INPUT;
matchOptions.eVertexProcessing = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eResolution = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eBackBufferFormat = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eBackBufferCount = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eMultiSample = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eSwapEffect = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eDepthFormat = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eStencilFormat = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.ePresentFlags = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eRefreshRate = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.ePresentInterval = DXUTMT_CLOSEST_TO_INPUT;
DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings();
deviceSettings.d3d9.AdapterFormat = adapterDesktopDisplayMode.Format;
hr = DXUTFindValidDeviceSettings( &deviceSettings, &deviceSettings, &matchOptions );
if( FAILED(hr) ) // the call will fail if no valid devices were found
{
DXUTDisplayErrorMessage( DXUTERR_NOCOMPATIBLEDEVICES );
DXUTShutdown();
}
// Change to a Direct3D device created from the new device settings.
// If there is an existing device, then either reset or recreate the scene
hr = DXUTChangeDevice( &deviceSettings, NULL, NULL, false, false );
if( FAILED(hr) )
{
// If this fails, try to go fullscreen and if this fails also shutdown.
if( FAILED(DXUTToggleFullScreen()) )
DXUTShutdown();
}
return;
}
}
// Try to reset the device
if( FAILED( hr = DXUTReset3DEnvironment9() ) )
{
if( D3DERR_DEVICELOST == hr )
{
// The device was lost again, so continue waiting until it can be reset.
return;
}
else if( DXUTERR_RESETTINGDEVICEOBJECTS == hr ||
DXUTERR_MEDIANOTFOUND == hr )
{
DXUTDisplayErrorMessage( hr );
DXUTShutdown();
return;
}
else
{
// Reset failed, but the device wasn't lost so something bad happened,
// so recreate the device to try to recover
DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings();
if( FAILED( DXUTChangeDevice( pDeviceSettings, NULL, NULL, true, false ) ) )
{
DXUTShutdown();
return;
}
}
}
}
GetDXUTState().SetDeviceLost( false );
}
// Get the app's time, in seconds. Skip rendering if no time elapsed
double fTime, fAbsTime; float fElapsedTime;
DXUTGetGlobalTimer()->GetTimeValues( &fTime, &fAbsTime, &fElapsedTime );
// Store the time for the app
if( GetDXUTState().GetConstantFrameTime() )
{
fElapsedTime = GetDXUTState().GetTimePerFrame();
fTime = DXUTGetTime() + fElapsedTime;
}
GetDXUTState().SetTime( fTime );
GetDXUTState().SetAbsoluteTime( fAbsTime );
GetDXUTState().SetElapsedTime( fElapsedTime );
// Update the FPS stats
DXUTUpdateFrameStats();
DXUTHandleTimers();
// Animate the scene by calling the app's frame move callback
LPDXUTCALLBACKFRAMEMOVE pCallbackFrameMove = GetDXUTState().GetFrameMoveFunc();
if( pCallbackFrameMove != NULL )
{
pCallbackFrameMove( fTime, fElapsedTime, GetDXUTState().GetFrameMoveFuncUserContext() );
pd3dDevice = DXUTGetD3D9Device();
if( NULL == pd3dDevice ) // Handle DXUTShutdown from inside callback
return;
}
if( !GetDXUTState().GetRenderingPaused() )
{
// Render the scene by calling the app's render callback
LPDXUTCALLBACKD3D9FRAMERENDER pCallbackFrameRender = GetDXUTState().GetD3D9FrameRenderFunc();
if( pCallbackFrameRender != NULL )
{
pCallbackFrameRender( pd3dDevice, fTime, fElapsedTime, GetDXUTState().GetD3D9FrameRenderFuncUserContext() );
pd3dDevice = DXUTGetD3D9Device();
if( NULL == pd3dDevice ) // Handle DXUTShutdown from inside callback
return;
}
#if defined(DEBUG) || defined(_DEBUG)
// The back buffer should always match the client rect
// if the Direct3D backbuffer covers the entire window
RECT rcClient;
GetClientRect( DXUTGetHWND(), &rcClient );
if( !IsIconic( DXUTGetHWND() ) )
{
GetClientRect( DXUTGetHWND(), &rcClient );
assert( DXUTGetD3D9BackBufferSurfaceDesc()->Width == (UINT)rcClient.right );
assert( DXUTGetD3D9BackBufferSurfaceDesc()->Height == (UINT)rcClient.bottom );
}
#endif
// Show the frame on the primary surface.
hr = pd3dDevice->Present( NULL, NULL, NULL, NULL );
if( FAILED(hr) )
{
if( D3DERR_DEVICELOST == hr )
{
GetDXUTState().SetDeviceLost( true );
}
else if( D3DERR_DRIVERINTERNALERROR == hr )
{
// When D3DERR_DRIVERINTERNALERROR is returned from Present(),
// the application can do one of the following:
//
// - End, with the pop-up window saying that the application cannot continue
// because of problems in the display adapter and that the user should
// contact the adapter manufacturer.
//
// - Attempt to restart by calling IDirect3DDevice9::Reset, which is essentially the same
// path as recovering from a lost device. If IDirect3DDevice9::Reset fails with
// D3DERR_DRIVERINTERNALERROR, the application should end immediately with the message
// that the user should contact the adapter manufacturer.
//
// The framework attempts the path of resetting the device
//
GetDXUTState().SetDeviceLost( true );
}
}
}
// If the app called DXUTWasKeyPressed() then do the work
// to store the current state of the keys in bLastKeys
if( GetDXUTState().GetAppCalledWasKeyPressed() )
{
bool* bLastKeys = GetDXUTState().GetLastKeys();
bool* bKeys = GetDXUTState().GetKeys();
memcpy( bLastKeys, bKeys, sizeof(bool)*256 );
}
// Update current frame #
int nFrame = GetDXUTState().GetCurrentFrameNumber();
nFrame++;
GetDXUTState().SetCurrentFrameNumber( nFrame );
// Check to see if the app should shutdown due to cmdline
if( GetDXUTState().GetOverrideQuitAfterFrame() != 0 )
{
if( nFrame > GetDXUTState().GetOverrideQuitAfterFrame() )
DXUTShutdown();
}
return;
}
//--------------------------------------------------------------------------------------
// Cleans up the 3D environment by:
// - Calls the device lost callback
// - Calls the device destroyed callback
// - Releases the D3D device
//--------------------------------------------------------------------------------------
void DXUTCleanup3DEnvironment9( bool bReleaseSettings )
{
IDirect3DDevice9* pd3dDevice = DXUTGetD3D9Device();
if( pd3dDevice != NULL )
{
GetDXUTState().SetInsideDeviceCallback( true );
// Call the app's device lost callback
if( GetDXUTState().GetDeviceObjectsReset() == true )
{
LPDXUTCALLBACKD3D9DEVICELOST pCallbackDeviceLost = GetDXUTState().GetD3D9DeviceLostFunc();
if( pCallbackDeviceLost != NULL )
pCallbackDeviceLost( GetDXUTState().GetD3D9DeviceLostFuncUserContext() );
GetDXUTState().SetDeviceObjectsReset( false );
}
// Call the app's device destroyed callback
if( GetDXUTState().GetDeviceObjectsCreated() == true )
{
LPDXUTCALLBACKD3D9DEVICEDESTROYED pCallbackDeviceDestroyed = GetDXUTState().GetD3D9DeviceDestroyedFunc();
if( pCallbackDeviceDestroyed != NULL )
pCallbackDeviceDestroyed( GetDXUTState().GetD3D9DeviceDestroyedFuncUserContext() );
GetDXUTState().SetDeviceObjectsCreated( false );
}
GetDXUTState().SetInsideDeviceCallback( false );
// Release the D3D device and in debug configs, displays a message box if there
// are unrelease objects.
if( pd3dDevice )
{
UINT references = pd3dDevice->Release();
if( references > 0 )
{
DXUTDisplayErrorMessage( DXUTERR_NONZEROREFCOUNT );
DXUT_ERR( L"DXUTCleanup3DEnvironment", DXUTERR_NONZEROREFCOUNT );
}
}
GetDXUTState().SetD3D9Device( NULL );
if( bReleaseSettings )
{
DXUTDeviceSettings* pOldDeviceSettings = GetDXUTState().GetCurrentDeviceSettings();
SAFE_DELETE(pOldDeviceSettings);
GetDXUTState().SetCurrentDeviceSettings( NULL );
}
D3DSURFACE_DESC* pBackBufferSurfaceDesc = GetDXUTState().GetBackBufferSurfaceDesc9();
ZeroMemory( pBackBufferSurfaceDesc, sizeof(D3DSURFACE_DESC) );
D3DCAPS9* pd3dCaps = GetDXUTState().GetCaps();
ZeroMemory( pd3dCaps, sizeof(D3DCAPS9) );
GetDXUTState().SetDeviceCreated( false );
}
}
//--------------------------------------------------------------------------------------
// Gives the D3D device a cursor with image and hotspot from hCursor.
//--------------------------------------------------------------------------------------
HRESULT DXUTSetD3D9DeviceCursor( IDirect3DDevice9* pd3dDevice, HCURSOR hCursor, bool bAddWatermark )
{
HRESULT hr = E_FAIL;
ICONINFO iconinfo;
bool bBWCursor = false;
LPDIRECT3DSURFACE9 pCursorSurface = NULL;
HDC hdcColor = NULL;
HDC hdcMask = NULL;
HDC hdcScreen = NULL;
BITMAP bm;
DWORD dwWidth = 0;
DWORD dwHeightSrc = 0;
DWORD dwHeightDest = 0;
COLORREF crColor;
COLORREF crMask;
UINT x;
UINT y;
BITMAPINFO bmi;
COLORREF* pcrArrayColor = NULL;
COLORREF* pcrArrayMask = NULL;
DWORD* pBitmap;
HGDIOBJ hgdiobjOld;
ZeroMemory( &iconinfo, sizeof(iconinfo) );
if( !GetIconInfo( hCursor, &iconinfo ) )
goto End;
if (0 == GetObject((HGDIOBJ)iconinfo.hbmMask, sizeof(BITMAP), (LPVOID)&bm))
goto End;
dwWidth = bm.bmWidth;
dwHeightSrc = bm.bmHeight;
if( iconinfo.hbmColor == NULL )
{
bBWCursor = TRUE;
dwHeightDest = dwHeightSrc / 2;
}
else
{
bBWCursor = FALSE;
dwHeightDest = dwHeightSrc;
}
// Create a surface for the fullscreen cursor
if( FAILED( hr = pd3dDevice->CreateOffscreenPlainSurface( dwWidth, dwHeightDest,
D3DFMT_A8R8G8B8, D3DPOOL_SCRATCH, &pCursorSurface, NULL ) ) )
{
goto End;
}
pcrArrayMask = new DWORD[dwWidth * dwHeightSrc];
ZeroMemory(&bmi, sizeof(bmi));
bmi.bmiHeader.biSize = sizeof(bmi.bmiHeader);
bmi.bmiHeader.biWidth = dwWidth;
bmi.bmiHeader.biHeight = dwHeightSrc;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = BI_RGB;
hdcScreen = GetDC( NULL );
hdcMask = CreateCompatibleDC( hdcScreen );
if( hdcMask == NULL )
{
hr = E_FAIL;
goto End;
}
hgdiobjOld = SelectObject(hdcMask, iconinfo.hbmMask);
GetDIBits(hdcMask, iconinfo.hbmMask, 0, dwHeightSrc,
pcrArrayMask, &bmi, DIB_RGB_COLORS);
SelectObject(hdcMask, hgdiobjOld);
if (!bBWCursor)
{
pcrArrayColor = new DWORD[dwWidth * dwHeightDest];
hdcColor = CreateCompatibleDC( hdcScreen );
if( hdcColor == NULL )
{
hr = E_FAIL;
goto End;
}
SelectObject(hdcColor, iconinfo.hbmColor);
GetDIBits(hdcColor, iconinfo.hbmColor, 0, dwHeightDest,
pcrArrayColor, &bmi, DIB_RGB_COLORS);
}
// Transfer cursor image into the surface
D3DLOCKED_RECT lr;
pCursorSurface->LockRect( &lr, NULL, 0 );
pBitmap = (DWORD*)lr.pBits;
for( y = 0; y < dwHeightDest; y++ )
{
for( x = 0; x < dwWidth; x++ )
{
if (bBWCursor)
{
crColor = pcrArrayMask[dwWidth*(dwHeightDest-1-y) + x];
crMask = pcrArrayMask[dwWidth*(dwHeightSrc-1-y) + x];
}
else
{
crColor = pcrArrayColor[dwWidth*(dwHeightDest-1-y) + x];
crMask = pcrArrayMask[dwWidth*(dwHeightDest-1-y) + x];
}
if (crMask == 0)
pBitmap[dwWidth*y + x] = 0xff000000 | crColor;
else
pBitmap[dwWidth*y + x] = 0x00000000;
// It may be helpful to make the D3D cursor look slightly
// different from the Windows cursor so you can distinguish
// between the two when developing/testing code. When
// bAddWatermark is TRUE, the following code adds some
// small grey "D3D" characters to the upper-left corner of
// the D3D cursor image.
if( bAddWatermark && x < 12 && y < 5 )
{
// 11.. 11.. 11.. .... CCC0
// 1.1. ..1. 1.1. .... A2A0
// 1.1. .1.. 1.1. .... A4A0
// 1.1. ..1. 1.1. .... A2A0
// 11.. 11.. 11.. .... CCC0
const WORD wMask[5] = { 0xccc0, 0xa2a0, 0xa4a0, 0xa2a0, 0xccc0 };
if( wMask[y] & (1 << (15 - x)) )
{
pBitmap[dwWidth*y + x] |= 0xff808080;
}
}
}
}
pCursorSurface->UnlockRect();
// Set the device cursor
if( FAILED( hr = pd3dDevice->SetCursorProperties( iconinfo.xHotspot,
iconinfo.yHotspot, pCursorSurface ) ) )
{
goto End;
}
hr = S_OK;
End:
if( iconinfo.hbmMask != NULL )
DeleteObject( iconinfo.hbmMask );
if( iconinfo.hbmColor != NULL )
DeleteObject( iconinfo.hbmColor );
if( hdcScreen != NULL )
ReleaseDC( NULL, hdcScreen );
if( hdcColor != NULL )
DeleteDC( hdcColor );
if( hdcMask != NULL )
DeleteDC( hdcMask );
SAFE_DELETE_ARRAY( pcrArrayColor );
SAFE_DELETE_ARRAY( pcrArrayMask );
SAFE_RELEASE( pCursorSurface );
return hr;
}
//--------------------------------------------------------------------------------------
// Internal helper function to return the adapter format from the first device settings
// combo that matches the passed adapter ordinal, device type, backbuffer format, and windowed.
//--------------------------------------------------------------------------------------
HRESULT DXUTFindD3D9AdapterFormat( UINT AdapterOrdinal, D3DDEVTYPE DeviceType, D3DFORMAT BackBufferFormat,
BOOL Windowed, D3DFORMAT* pAdapterFormat )
{
CD3D9Enumeration* pd3dEnum = DXUTGetD3D9Enumeration( false );
CD3D9EnumDeviceInfo* pDeviceInfo = pd3dEnum->GetDeviceInfo( AdapterOrdinal, DeviceType );
if( pDeviceInfo )
{
for( int iDeviceCombo=0; iDeviceCombo<pDeviceInfo->deviceSettingsComboList.GetSize(); iDeviceCombo++ )
{
CD3D9EnumDeviceSettingsCombo* pDeviceSettingsCombo = pDeviceInfo->deviceSettingsComboList.GetAt(iDeviceCombo);
if( pDeviceSettingsCombo->BackBufferFormat == BackBufferFormat &&
pDeviceSettingsCombo->Windowed == Windowed )
{
// Return the adapter format from the first match
*pAdapterFormat = pDeviceSettingsCombo->AdapterFormat;
return S_OK;
}
}
}
*pAdapterFormat = BackBufferFormat;
return E_FAIL;
}
//======================================================================================
//======================================================================================
// Direct3D 10 section
//======================================================================================
//======================================================================================
//--------------------------------------------------------------------------------------
// Passes a previously created Direct3D 10 device for use by the framework.
// If DXUTCreateWindow() has not already been called, it will call it with the
// default parameters. Instead of calling this, you can call DXUTCreateDevice() or
// DXUTCreateDeviceFromSettings()
//--------------------------------------------------------------------------------------
HRESULT WINAPI DXUTSetD3D10Device( ID3D10Device* pd3dDevice, IDXGISwapChain* pSwapChain )
{
HRESULT hr;
if( pd3dDevice == NULL )
return DXUT_ERR_MSGBOX( L"DXUTSetD3D10Device", E_INVALIDARG );
// Not allowed to call this from inside the device callbacks
if( GetDXUTState().GetInsideDeviceCallback() )
return DXUT_ERR_MSGBOX( L"DXUTSetD3D10Device", E_FAIL );
GetDXUTState().SetDeviceCreateCalled( true );
// If DXUTCreateWindow() or DXUTSetWindow() has not already been called,
// then call DXUTCreateWindow() with the default parameters.
if( !GetDXUTState().GetWindowCreated() )
{
// If DXUTCreateWindow() or DXUTSetWindow() was already called and failed, then fail.
// DXUTCreateWindow() or DXUTSetWindow() must first succeed for this function to succeed
if( GetDXUTState().GetWindowCreateCalled() )
return E_FAIL;
// If DXUTCreateWindow() or DXUTSetWindow() hasn't been called, then
// automatically call DXUTCreateWindow() with default params
hr = DXUTCreateWindow();
if( FAILED(hr) )
return hr;
}
DXUTDeviceSettings DeviceSettings;
ZeroMemory( &DeviceSettings, sizeof(DXUTDeviceSettings) );
// Get adapter info
IDXGIDevice *pDXGIDevice = NULL;
if( SUCCEEDED( hr = pd3dDevice->QueryInterface( __uuidof( *pDXGIDevice ), reinterpret_cast< void** >( &pDXGIDevice ) ) ) )
{
IDXGIAdapter *pAdapter = NULL;
hr = pDXGIDevice->GetAdapter( &pAdapter );
if( SUCCEEDED( hr ) )
{
DXGI_ADAPTER_DESC id;
pAdapter->GetDesc( &id );
// Find the ordinal by inspecting the enum list.
DeviceSettings.d3d10.AdapterOrdinal = 0; // Default
CD3D10Enumeration *pd3dEnum = DXUTGetD3D10Enumeration();
CGrowableArray<CD3D10EnumAdapterInfo*> *pAdapterInfoList = pd3dEnum->GetAdapterInfoList();
for( int i = 0; i < pAdapterInfoList->GetSize(); ++i )
{
CD3D10EnumAdapterInfo* pAdapterInfo = pAdapterInfoList->GetAt(i);
if( !wcscmp( pAdapterInfo->AdapterDesc.Description, id.Description ) )
{
DeviceSettings.d3d10.AdapterOrdinal = i;
break;
}
}
SAFE_RELEASE( pAdapter );
}
SAFE_RELEASE( pDXGIDevice );
}
if( FAILED( hr ) )
return hr;
// Get the swap chain description
DXGI_SWAP_CHAIN_DESC sd;
pSwapChain->GetDesc( &sd );
DeviceSettings.ver = DXUT_D3D10_DEVICE;
DeviceSettings.d3d10.sd = sd;
// Fill out the rest of the device settings struct
DeviceSettings.d3d10.CreateFlags = 0;
DeviceSettings.d3d10.DriverType = D3D10_DRIVER_TYPE_HARDWARE;
DeviceSettings.d3d10.Output = 0;
DeviceSettings.d3d10.PresentFlags = 0;
DeviceSettings.d3d10.SyncInterval = 0;
// DeviceSettings.d3d10.AutoCreateDepthStencil = true; // TODO: verify
// Change to the Direct3D device passed in
hr = DXUTChangeDevice( &DeviceSettings, NULL, pd3dDevice, false, false );
if( FAILED(hr) )
return hr;
return S_OK;
}
//--------------------------------------------------------------------------------------
// Sets the viewport, creates a render target view, and depth scencil texture and view.
//--------------------------------------------------------------------------------------
HRESULT DXUTSetupD3D10Views( ID3D10Device* pd3dDevice, DXUTDeviceSettings* pDeviceSettings )
{
HRESULT hr = S_OK;
IDXGISwapChain* pSwapChain = DXUTGetDXGISwapChain();
ID3D10DepthStencilView* pDSV = NULL;
ID3D10RenderTargetView* pRTV = NULL;
// Get the back buffer and desc
ID3D10Texture2D *pBackBuffer;
hr = pSwapChain->GetBuffer( 0, __uuidof(*pBackBuffer), (LPVOID*)&pBackBuffer );
if( FAILED(hr) )
return hr;
D3D10_TEXTURE2D_DESC backBufferSurfaceDesc;
pBackBuffer->GetDesc( &backBufferSurfaceDesc );
// Setup the viewport to match the backbuffer
D3D10_VIEWPORT vp;
vp.Width = backBufferSurfaceDesc.Width;
vp.Height = backBufferSurfaceDesc.Height;
vp.MinDepth = 0;
vp.MaxDepth = 1;
vp.TopLeftX = 0;
vp.TopLeftY = 0;
pd3dDevice->RSSetViewports( 1, &vp );
// Create the render target view
hr = pd3dDevice->CreateRenderTargetView( pBackBuffer, NULL, &pRTV );
SAFE_RELEASE( pBackBuffer );
if( FAILED(hr) )
return hr;
GetDXUTState().SetD3D10RenderTargetView( pRTV );
if( pDeviceSettings->d3d10.AutoCreateDepthStencil )
{
// Create depth stencil texture
ID3D10Texture2D* pDepthStencil = NULL;
D3D10_TEXTURE2D_DESC descDepth;
descDepth.Width = backBufferSurfaceDesc.Width;
descDepth.Height = backBufferSurfaceDesc.Height;
descDepth.MipLevels = 1;
descDepth.ArraySize = 1;
descDepth.Format = pDeviceSettings->d3d10.AutoDepthStencilFormat;
descDepth.SampleDesc.Count = backBufferSurfaceDesc.SampleDesc.Count; // NV fix: the MS version took Count & Quality from the dev settings parameter, but...
descDepth.SampleDesc.Quality = backBufferSurfaceDesc.SampleDesc.Quality; // this sometimes doesn't match the back-buffer format leading to a crash. This must be better.
descDepth.Usage = D3D10_USAGE_DEFAULT;
descDepth.BindFlags = D3D10_BIND_DEPTH_STENCIL;
descDepth.CPUAccessFlags = 0;
descDepth.MiscFlags = 0;
hr = pd3dDevice->CreateTexture2D( &descDepth, NULL, &pDepthStencil );
if( FAILED(hr) )
return hr;
GetDXUTState().SetD3D10DepthStencil( pDepthStencil );
// Create the depth stencil view
D3D10_DEPTH_STENCIL_VIEW_DESC descDSV;
descDSV.Format = descDepth.Format;
if( descDepth.SampleDesc.Count > 1 )
descDSV.ViewDimension = D3D10_DSV_DIMENSION_TEXTURE2DMS;
else
descDSV.ViewDimension = D3D10_DSV_DIMENSION_TEXTURE2D;
descDSV.Texture2D.MipSlice = 0;
hr = pd3dDevice->CreateDepthStencilView( pDepthStencil, &descDSV, &pDSV );
if( FAILED(hr) )
return hr;
GetDXUTState().SetD3D10DepthStencilView( pDSV );
}
// Set the render targets
pDSV = GetDXUTState().GetD3D10DepthStencilView();
pd3dDevice->OMSetRenderTargets( 1, &pRTV, pDSV );
return hr;
}
//--------------------------------------------------------------------------------------
// Creates the 3D environment
//--------------------------------------------------------------------------------------
HRESULT DXUTCreate3DEnvironment10( ID3D10Device* pd3d10DeviceFromApp )
{
HRESULT hr = S_OK;
ID3D10Device* pd3d10Device = NULL;
ID3D10Device1* pd3d10Device1 = NULL;
IDXGISwapChain *pSwapChain = NULL;
DXUTDeviceSettings* pNewDeviceSettings = GetDXUTState().GetCurrentDeviceSettings();
IDXGIFactory* pDXGIFactory = DXUTGetDXGIFactory();
hr = pDXGIFactory->MakeWindowAssociation( NULL, 0 );
// Only create a Direct3D device if one hasn't been supplied by the app
if( pd3d10DeviceFromApp == NULL )
{
// Try to create the device with the chosen settings
IDXGIAdapter* pAdapter = NULL;
hr = S_OK;
if( pNewDeviceSettings->d3d10.DriverType == D3D10_DRIVER_TYPE_HARDWARE )
hr = pDXGIFactory->EnumAdapters( pNewDeviceSettings->d3d10.AdapterOrdinal, &pAdapter );
//add for running with perfHUD
IDXGIAdapter* selectedAdapter = NULL;
D3D10_DRIVER_TYPE driver_type = D3D10_DRIVER_TYPE_HARDWARE;
UINT adapter_index = 0;
while(pDXGIFactory->EnumAdapters(adapter_index, &pAdapter) != DXGI_ERROR_NOT_FOUND)
{
if(pAdapter)
{
DXGI_ADAPTER_DESC adapter_desc;
if(SUCCEEDED(pAdapter->GetDesc(&adapter_desc)))
{
const bool is_perf_hud = (wcscmp(adapter_desc.Description, L"NVIDIA PerfHUD") == 0);
if(is_perf_hud)
{
driver_type = D3D10_DRIVER_TYPE_REFERENCE;
break;
}
else
{
pAdapter->Release();
}
}
else
{
pAdapter->Release();
}
}
++adapter_index;
}
pNewDeviceSettings->d3d10.DriverType = driver_type;
if( driver_type != D3D10_DRIVER_TYPE_REFERENCE )
{
if( pNewDeviceSettings->d3d10.DriverType == D3D10_DRIVER_TYPE_HARDWARE )
hr = pDXGIFactory->EnumAdapters( pNewDeviceSettings->d3d10.AdapterOrdinal, &pAdapter );
}
//----
if( SUCCEEDED(hr) )
{
// Try creating the D3D10.1 device first
hr = DXUT_Dynamic_D3D10CreateDevice1( pAdapter, pNewDeviceSettings->d3d10.DriverType, (HMODULE)0,
pNewDeviceSettings->d3d10.CreateFlags,
D3D10_FEATURE_LEVEL_10_1, D3D10_1_SDK_VERSION, &pd3d10Device1 );
if( SUCCEEDED(hr) )
{
// Get a D3D10.0 device pointer from the D3D10.1 device
hr = pd3d10Device1->QueryInterface( __uuidof( ID3D10Device ), (LPVOID*)&pd3d10Device );
assert( SUCCEEDED(hr) ); // this should never fail
}
else // if( FAILED(hr) )
{
// If D3D10.1 doesn't exist, then fallback to D3D10.0
hr = DXUT_Dynamic_D3D10CreateDevice( pAdapter, pNewDeviceSettings->d3d10.DriverType, (HMODULE)0,
pNewDeviceSettings->d3d10.CreateFlags,
NULL, D3D10_SDK_VERSION, &pd3d10Device );
}
if( SUCCEEDED(hr) )
{
if( pNewDeviceSettings->d3d10.DriverType != D3D10_DRIVER_TYPE_HARDWARE )
{
IDXGIDevice* pDXGIDev = NULL;
hr = pd3d10Device->QueryInterface( __uuidof( IDXGIDevice ), (LPVOID*)&pDXGIDev );
if( SUCCEEDED(hr) && pDXGIDev )
{
pDXGIDev->GetAdapter( &pAdapter );
}
SAFE_RELEASE( pDXGIDev );
}
GetDXUTState().SetD3D10Adapter( pAdapter );
}
}
if( FAILED(hr) )
{
DXUT_ERR( L"D3D10CreateDevice", hr );
return DXUTERR_CREATINGDEVICE;
}
// Enumerate its outputs.
UINT OutputCount, iOutput;
for( OutputCount = 0; ; ++OutputCount )
{
IDXGIOutput* pOutput;
if( FAILED( pAdapter->EnumOutputs( OutputCount, &pOutput ) ) )
break;
SAFE_RELEASE( pOutput );
}
IDXGIOutput** ppOutputArray = new IDXGIOutput*[OutputCount];
if( !ppOutputArray )
return E_OUTOFMEMORY;
for( iOutput = 0; iOutput < OutputCount; ++iOutput )
pAdapter->EnumOutputs( iOutput, ppOutputArray + iOutput );
GetDXUTState().SetD3D10OutputArray( ppOutputArray );
GetDXUTState().SetD3D10OutputArraySize( OutputCount );
// Create the swapchain
hr = pDXGIFactory->CreateSwapChain( pd3d10Device, &pNewDeviceSettings->d3d10.sd, &pSwapChain );
if( FAILED(hr) )
{
DXUT_ERR( L"CreateSwapChain", hr );
return DXUTERR_CREATINGDEVICE;
}
}
else
{
pd3d10DeviceFromApp->AddRef();
pd3d10Device = pd3d10DeviceFromApp;
}
GetDXUTState().SetD3D10Device( pd3d10Device );
GetDXUTState().SetD3D10Device1( pd3d10Device1 );
GetDXUTState().SetD3D10SwapChain( pSwapChain );
// If switching to REF, set the exit code to 10. If switching to HAL and exit code was 10, then set it back to 0.
if( pNewDeviceSettings->d3d10.DriverType == D3D10_DRIVER_TYPE_REFERENCE && GetDXUTState().GetExitCode() == 0 )
GetDXUTState().SetExitCode(10);
else if( pNewDeviceSettings->d3d10.DriverType == D3D10_DRIVER_TYPE_HARDWARE && GetDXUTState().GetExitCode() == 10 )
GetDXUTState().SetExitCode(0);
// Update back buffer desc before calling app's device callbacks
DXUTUpdateBackBufferDesc();
// Setup cursor based on current settings (window/fullscreen mode, show cursor state, clip cursor state)
DXUTSetupCursor();
// Update the device stats text
CD3D10Enumeration* pd3dEnum = DXUTGetD3D10Enumeration();
CD3D10EnumAdapterInfo* pAdapterInfo = pd3dEnum->GetAdapterInfo( pNewDeviceSettings->d3d10.AdapterOrdinal );
DXUTUpdateD3D10DeviceStats( pNewDeviceSettings->d3d10.DriverType, &pAdapterInfo->AdapterDesc );
// Call the app's device created callback if non-NULL
const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc = DXUTGetDXGIBackBufferSurfaceDesc();
GetDXUTState().SetInsideDeviceCallback( true );
LPDXUTCALLBACKD3D10DEVICECREATED pCallbackDeviceCreated = GetDXUTState().GetD3D10DeviceCreatedFunc();
hr = S_OK;
if( pCallbackDeviceCreated != NULL )
hr = pCallbackDeviceCreated( DXUTGetD3D10Device(), pBackBufferSurfaceDesc, GetDXUTState().GetD3D10DeviceCreatedFuncUserContext() );
GetDXUTState().SetInsideDeviceCallback( false );
if( DXUTGetD3D10Device() == NULL ) // Handle DXUTShutdown from inside callback
return E_FAIL;
if( FAILED(hr) )
{
DXUT_ERR( L"DeviceCreated callback", hr );
return ( hr == DXUTERR_MEDIANOTFOUND ) ? DXUTERR_MEDIANOTFOUND : DXUTERR_CREATINGDEVICEOBJECTS;
}
GetDXUTState().SetDeviceObjectsCreated( true );
// Setup the render target view and viewport
hr = DXUTSetupD3D10Views( pd3d10Device, pNewDeviceSettings );
if( FAILED(hr) )
{
DXUT_ERR( L"DXUTSetupD3D10Views", hr );
return DXUTERR_CREATINGDEVICEOBJECTS;
}
// Create performance counters
//DXUTCreateD3D10Counters( pd3d10Device );
// Call the app's swap chain reset callback if non-NULL
GetDXUTState().SetInsideDeviceCallback( true );
LPDXUTCALLBACKD3D10SWAPCHAINRESIZED pCallbackSwapChainResized = GetDXUTState().GetD3D10SwapChainResizedFunc();
hr = S_OK;
if( pCallbackSwapChainResized != NULL )
hr = pCallbackSwapChainResized( DXUTGetD3D10Device(), pSwapChain, pBackBufferSurfaceDesc, GetDXUTState().GetD3D10SwapChainResizedFuncUserContext() );
GetDXUTState().SetInsideDeviceCallback( false );
if( DXUTGetD3D10Device() == NULL ) // Handle DXUTShutdown from inside callback
return E_FAIL;
if( FAILED(hr) )
{
DXUT_ERR( L"DeviceReset callback", hr );
return ( hr == DXUTERR_MEDIANOTFOUND ) ? DXUTERR_MEDIANOTFOUND : DXUTERR_RESETTINGDEVICEOBJECTS;
}
GetDXUTState().SetDeviceObjectsReset( true );
return S_OK;
}
//--------------------------------------------------------------------------------------
// Resets the 3D environment by:
// - Calls the device lost callback
// - Resets the device
// - Stores the back buffer description
// - Sets up the full screen Direct3D cursor if requested
// - Calls the device reset callback
//--------------------------------------------------------------------------------------
HRESULT DXUTReset3DEnvironment10()
{
HRESULT hr;
GetDXUTState().SetDeviceObjectsReset( false );
DXUTPause( true, true );
bool bDeferredDXGIAction = false;
DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings();
IDXGISwapChain* pSwapChain = DXUTGetDXGISwapChain();
DXGI_SWAP_CHAIN_DESC SCDesc;
pSwapChain->GetDesc( &SCDesc );
// Resize backbuffer and target of the swapchain in case they have changed.
// For windowed mode, use the client rect as the desired size. Unlike D3D9,
// we can't use 0 for width or height. Therefore, fill in the values from
// the window size. For fullscreen mode, the width and height should have
// already been filled with the desktop resolution, so don't change it.
if( pDeviceSettings->d3d10.sd.Windowed && SCDesc.Windowed )
{
RECT rcWnd;
GetClientRect( DXUTGetHWND(), &rcWnd );
pDeviceSettings->d3d10.sd.BufferDesc.Width = rcWnd.right - rcWnd.left;
pDeviceSettings->d3d10.sd.BufferDesc.Height = rcWnd.bottom - rcWnd.top;
}
// If the app wants to switch from windowed to fullscreen or vice versa,
// call the swapchain's SetFullscreenState
// mode.
if( SCDesc.Windowed != pDeviceSettings->d3d10.sd.Windowed )
{
// Set the fullscreen state
if( pDeviceSettings->d3d10.sd.Windowed )
{
V_RETURN( pSwapChain->SetFullscreenState( FALSE, NULL ) );
bDeferredDXGIAction = true;
}
else
{
// Set fullscreen state by setting the display mode to fullscreen, then changing the resolution
// to the desired value.
// SetFullscreenState causes a WM_SIZE message to be sent to the window. The WM_SIZE message calls
// DXUTCheckForDXGIBufferChange which normally stores the new height and width in
// pDeviceSettings->d3d10.sd.BufferDesc. SetDoNotStoreBufferSize tells DXUTCheckForDXGIBufferChange
// not to store the height and width so that we have the correct values when calling ResizeTarget.
GetDXUTState().SetDoNotStoreBufferSize(true);
V_RETURN( pSwapChain->SetFullscreenState( TRUE, NULL ) );
GetDXUTState().SetDoNotStoreBufferSize(false);
V_RETURN( pSwapChain->ResizeTarget( &pDeviceSettings->d3d10.sd.BufferDesc ) );
bDeferredDXGIAction = true;
}
}
else
{
if( pDeviceSettings->d3d10.sd.BufferDesc.Width == SCDesc.BufferDesc.Width &&
pDeviceSettings->d3d10.sd.BufferDesc.Height == SCDesc.BufferDesc.Height &&
pDeviceSettings->d3d10.sd.BufferDesc.Format != SCDesc.BufferDesc.Format )
{
DXUTResizeDXGIBuffers( 0,0, !pDeviceSettings->d3d10.sd.Windowed );
bDeferredDXGIAction = true;
}
else if( pDeviceSettings->d3d10.sd.BufferDesc.Width != SCDesc.BufferDesc.Width ||
pDeviceSettings->d3d10.sd.BufferDesc.Height != SCDesc.BufferDesc.Height )
{
V_RETURN( pSwapChain->ResizeTarget( &pDeviceSettings->d3d10.sd.BufferDesc ) );
bDeferredDXGIAction = true;
}
}
// If no deferred DXGI actions are to take place, mark the device as reset.
// If there is a deferred DXGI action, then the device isn't reset until DXGI sends us a
// window message. Only then can we mark the device as reset.
if( !bDeferredDXGIAction )
GetDXUTState().SetDeviceObjectsReset( true );
DXUTPause( false, false );
return S_OK;
}
//--------------------------------------------------------------------------------------
// Render the 3D environment by:
// - Checking if the device is lost and trying to reset it if it is
// - Get the elapsed time since the last frame
// - Calling the app's framemove and render callback
// - Calling Present()
//--------------------------------------------------------------------------------------
void DXUTRender3DEnvironment10()
{
HRESULT hr;
ID3D10Device* pd3dDevice = DXUTGetD3D10Device();
if( NULL == pd3dDevice )
return;
IDXGISwapChain* pSwapChain = DXUTGetDXGISwapChain();
if( NULL == pSwapChain )
return;
if( DXUTIsRenderingPaused() || !DXUTIsActive() || GetDXUTState().GetRenderingOccluded() )
{
// Window is minimized/paused/occluded/or not exclusive so yield CPU time to other processes
Sleep( 50 );
}
// Get the app's time, in seconds. Skip rendering if no time elapsed
double fTime, fAbsTime; float fElapsedTime;
DXUTGetGlobalTimer()->GetTimeValues( &fTime, &fAbsTime, &fElapsedTime );
// Store the time for the app
if( GetDXUTState().GetConstantFrameTime() )
{
fElapsedTime = GetDXUTState().GetTimePerFrame();
fTime = DXUTGetTime() + fElapsedTime;
}
GetDXUTState().SetTime( fTime );
GetDXUTState().SetAbsoluteTime( fAbsTime );
GetDXUTState().SetElapsedTime( fElapsedTime );
// Start Performance Counters
DXUTStartPerformanceCounters();
// Update the FPS stats
DXUTUpdateFrameStats();
DXUTHandleTimers();
// Animate the scene by calling the app's frame move callback
LPDXUTCALLBACKFRAMEMOVE pCallbackFrameMove = GetDXUTState().GetFrameMoveFunc();
if( pCallbackFrameMove != NULL )
{
pCallbackFrameMove( fTime, fElapsedTime, GetDXUTState().GetFrameMoveFuncUserContext() );
pd3dDevice = DXUTGetD3D10Device();
if( NULL == pd3dDevice ) // Handle DXUTShutdown from inside callback
return;
}
if( !GetDXUTState().GetRenderingPaused() )
{
// Render the scene by calling the app's render callback
LPDXUTCALLBACKD3D10FRAMERENDER pCallbackFrameRender = GetDXUTState().GetD3D10FrameRenderFunc();
if( pCallbackFrameRender != NULL && !GetDXUTState().GetRenderingOccluded() )
{
pCallbackFrameRender( pd3dDevice, fTime, fElapsedTime, GetDXUTState().GetD3D10FrameRenderFuncUserContext() );
pd3dDevice = DXUTGetD3D10Device();
if( NULL == pd3dDevice ) // Handle DXUTShutdown from inside callback
return;
}
#if defined(DEBUG) || defined(_DEBUG)
// The back buffer should always match the client rect
// if the Direct3D backbuffer covers the entire window
RECT rcClient;
GetClientRect( DXUTGetHWND(), &rcClient );
if( !IsIconic( DXUTGetHWND() ) )
{
GetClientRect( DXUTGetHWND(), &rcClient );
assert( DXUTGetDXGIBackBufferSurfaceDesc()->Width == (UINT)rcClient.right );
assert( DXUTGetDXGIBackBufferSurfaceDesc()->Height == (UINT)rcClient.bottom );
}
#endif
}
DWORD dwFlags = 0;
if( GetDXUTState().GetRenderingOccluded() )
dwFlags = DXGI_PRESENT_TEST;
else
dwFlags = GetDXUTState().GetCurrentDeviceSettings()->d3d10.PresentFlags;
UINT SyncInterval = GetDXUTState().GetCurrentDeviceSettings()->d3d10.SyncInterval;
// Show the frame on the primary surface.
hr = pSwapChain->Present( SyncInterval, dwFlags );
if( DXGI_STATUS_OCCLUDED == hr )
{
// There is a window covering our entire rendering area.
// Don't render until we're visible again.
GetDXUTState().SetRenderingOccluded( true );
}
else if( DXGI_ERROR_DEVICE_RESET == hr )
{
// If a mode change happened, we must reset the device
if( FAILED( hr = DXUTReset3DEnvironment10() ) )
{
if( DXUTERR_RESETTINGDEVICEOBJECTS == hr ||
DXUTERR_MEDIANOTFOUND == hr )
{
DXUTDisplayErrorMessage( hr );
DXUTShutdown();
return;
}
else
{
// Reset failed, but the device wasn't lost so something bad happened,
// so recreate the device to try to recover
DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings();
if( FAILED( DXUTChangeDevice( pDeviceSettings, NULL, NULL, true, false ) ) )
{
DXUTShutdown();
return;
}
// TODO: Handle display orientation changes in full-screen mode.
}
}
}
else if( DXGI_ERROR_DEVICE_REMOVED == hr )
{
// Use a callback to ask the app if it would like to find a new device.
// If no device removed callback is set, then look for a new device
if( FAILED( DXUTHandleDeviceRemoved() ) )
{
// TODO: use pD3DDevice->GetDeviceRemovedReason()
DXUTDisplayErrorMessage( DXUTERR_DEVICEREMOVED );
DXUTShutdown();
return;
}
}
else if( SUCCEEDED(hr) )
{
if( GetDXUTState().GetRenderingOccluded() )
{
// Now that we're no longer occluded
// allow us to render again
GetDXUTState().SetRenderingOccluded( false );
}
}
// Update current frame #
int nFrame = GetDXUTState().GetCurrentFrameNumber();
nFrame++;
GetDXUTState().SetCurrentFrameNumber( nFrame );
// Stop performance counters
DXUTStopPerformanceCounters();
// Update the D3D10 counter stats
DXUTUpdateD3D10CounterStats();
// Check to see if the app should shutdown due to cmdline
if( GetDXUTState().GetOverrideQuitAfterFrame() != 0 )
{
if( nFrame > GetDXUTState().GetOverrideQuitAfterFrame() )
DXUTShutdown();
}
return;
}
//--------------------------------------------------------------------------------------
// Cleans up the 3D environment by:
// - Calls the device lost callback
// - Calls the device destroyed callback
// - Releases the D3D device
//--------------------------------------------------------------------------------------
void DXUTCleanup3DEnvironment10( bool bReleaseSettings )
{
ID3D10Device* pd3dDevice = DXUTGetD3D10Device();
if( pd3dDevice != NULL )
{
// Call ClearState to avoid tons of messy debug spew telling us that we're deleting bound objects
pd3dDevice->ClearState();
// Call the app's SwapChain lost callback
GetDXUTState().SetInsideDeviceCallback( true );
if( GetDXUTState().GetDeviceObjectsReset() )
{
LPDXUTCALLBACKD3D10SWAPCHAINRELEASING pCallbackSwapChainReleasing = GetDXUTState().GetD3D10SwapChainReleasingFunc();
if( pCallbackSwapChainReleasing != NULL )
pCallbackSwapChainReleasing( GetDXUTState().GetD3D10SwapChainReleasingFuncUserContext() );
GetDXUTState().SetDeviceObjectsReset( false );
}
// Release our old depth stencil texture and view
ID3D10Texture2D* pDS = GetDXUTState().GetD3D10DepthStencil();
SAFE_RELEASE( pDS );
GetDXUTState().SetD3D10DepthStencil( NULL );
ID3D10DepthStencilView* pDSV = GetDXUTState().GetD3D10DepthStencilView();
SAFE_RELEASE( pDSV );
GetDXUTState().SetD3D10DepthStencilView( NULL );
// Cleanup the render target view
ID3D10RenderTargetView* pRTV = GetDXUTState().GetD3D10RenderTargetView();
SAFE_RELEASE( pRTV );
GetDXUTState().SetD3D10RenderTargetView( NULL );
// Call the app's device destroyed callback
if( GetDXUTState().GetDeviceObjectsCreated() )
{
LPDXUTCALLBACKD3D10DEVICEDESTROYED pCallbackDeviceDestroyed = GetDXUTState().GetD3D10DeviceDestroyedFunc();
if( pCallbackDeviceDestroyed != NULL )
pCallbackDeviceDestroyed( GetDXUTState().GetD3D10DeviceDestroyedFuncUserContext() );
GetDXUTState().SetDeviceObjectsCreated( false );
}
GetDXUTState().SetInsideDeviceCallback( false );
// Release the swap chain
GetDXUTState().SetReleasingSwapChain( true );
IDXGISwapChain* pSwapChain = DXUTGetDXGISwapChain();
if( pSwapChain )
{
pSwapChain->SetFullscreenState( FALSE, 0 );
}
SAFE_RELEASE( pSwapChain );
GetDXUTState().SetD3D10SwapChain( NULL );
GetDXUTState().SetReleasingSwapChain( false );
// Release the outputs.
IDXGIOutput **ppOutputArray = GetDXUTState().GetD3D10OutputArray();
UINT OutputCount = GetDXUTState().GetD3D10OutputArraySize();
for( UINT o = 0; o < OutputCount; ++o )
SAFE_RELEASE( ppOutputArray[o] );
delete[] ppOutputArray;
GetDXUTState().SetD3D10OutputArray( NULL );
GetDXUTState().SetD3D10OutputArraySize( 0 );
// Release the D3D adapter.
IDXGIAdapter *pAdapter = GetDXUTState().GetD3D10Adapter();
SAFE_RELEASE( pAdapter );
GetDXUTState().SetD3D10Adapter( NULL );
// Release the counters
DXUTDestroyD3D10Counters();
// Release the D3D10.1 device (if it exists) because it has a extra ref count on it
ID3D10Device1* pd3d10Device1 = GetDXUTState().GetD3D10Device1();
SAFE_RELEASE( pd3d10Device1 );
GetDXUTState().SetD3D10Device1( NULL );
// Release the D3D device and in debug configs, displays a message box if there
// are unrelease objects.
if( pd3dDevice )
{
UINT references = pd3dDevice->Release();
if( references > 0 )
{
DXUTDisplayErrorMessage( DXUTERR_NONZEROREFCOUNT );
DXUT_ERR( L"DXUTCleanup3DEnvironment", DXUTERR_NONZEROREFCOUNT );
}
}
GetDXUTState().SetD3D10Device( NULL );
if( bReleaseSettings )
{
DXUTDeviceSettings* pOldDeviceSettings = GetDXUTState().GetCurrentDeviceSettings();
SAFE_DELETE(pOldDeviceSettings);
GetDXUTState().SetCurrentDeviceSettings( NULL );
}
DXGI_SURFACE_DESC* pBackBufferSurfaceDesc = GetDXUTState().GetBackBufferSurfaceDesc10();
ZeroMemory( pBackBufferSurfaceDesc, sizeof(DXGI_SURFACE_DESC) );
GetDXUTState().SetDeviceCreated( false );
}
}
//--------------------------------------------------------------------------------------
// Setup D3D10 counters for various statistics
//--------------------------------------------------------------------------------------
void DXUTCreateD3D10Counters( ID3D10Device* pd3dDevice )
{
if( GetDXUTState().GetNoStats() )
return;
ID3D10Counter* pCounter = NULL;
D3D10_COUNTER_DESC Desc;
Desc.MiscFlags = 0;
Desc.Counter = D3D10_COUNTER_GPU_IDLE;
HRESULT hr = DXGI_ERROR_UNSUPPORTED;
if( SUCCEEDED( hr = pd3dDevice->CreateCounter( &Desc, &pCounter ) ) )
GetDXUTState().SetCounter_GPUIdle( pCounter );
Desc.Counter = D3D10_COUNTER_VERTEX_PROCESSING;
if( SUCCEEDED( hr = pd3dDevice->CreateCounter( &Desc, &pCounter ) ) )
GetDXUTState().SetCounter_VertexProcessing( pCounter );
Desc.Counter = D3D10_COUNTER_GEOMETRY_PROCESSING;
if( SUCCEEDED( hr = pd3dDevice->CreateCounter( &Desc, &pCounter ) ) )
GetDXUTState().SetCounter_GeometryProcessing( pCounter );
Desc.Counter = D3D10_COUNTER_PIXEL_PROCESSING;
if( SUCCEEDED( hr = pd3dDevice->CreateCounter( &Desc, &pCounter ) ) )
GetDXUTState().SetCounter_PixelProcessing( pCounter );
Desc.Counter = D3D10_COUNTER_OTHER_GPU_PROCESSING;
if( SUCCEEDED( hr = pd3dDevice->CreateCounter( &Desc, &pCounter ) ) )
GetDXUTState().SetCounter_OtherGPUProcessing( pCounter );
Desc.Counter = D3D10_COUNTER_HOST_ADAPTER_BANDWIDTH_UTILIZATION;
if( SUCCEEDED( hr = pd3dDevice->CreateCounter( &Desc, &pCounter ) ) )
GetDXUTState().SetCounter_HostAdapterBandwidthUtilization( pCounter );
Desc.Counter = D3D10_COUNTER_LOCAL_VIDMEM_BANDWIDTH_UTILIZATION;
if( SUCCEEDED( hr = pd3dDevice->CreateCounter( &Desc, &pCounter ) ) )
GetDXUTState().SetCounter_LocalVidmemBandwidthUtilization( pCounter );
Desc.Counter = D3D10_COUNTER_VERTEX_THROUGHPUT_UTILIZATION;
if( SUCCEEDED( hr = pd3dDevice->CreateCounter( &Desc, &pCounter ) ) )
GetDXUTState().SetCounter_VertexThroughputUtilization( pCounter );
Desc.Counter = D3D10_COUNTER_TRIANGLE_SETUP_THROUGHPUT_UTILIZATION;
if( SUCCEEDED( hr = pd3dDevice->CreateCounter( &Desc, &pCounter ) ) )
GetDXUTState().SetCounter_TriangleSetupThroughputUtilization( pCounter );
Desc.Counter = D3D10_COUNTER_FILLRATE_THROUGHPUT_UTILIZATION;
if( SUCCEEDED( hr = pd3dDevice->CreateCounter( &Desc, &pCounter ) ) )
GetDXUTState().SetCounter_FillrateThrougputUtilization( pCounter );
Desc.Counter = D3D10_COUNTER_VS_MEMORY_LIMITED;
if( SUCCEEDED( hr = pd3dDevice->CreateCounter( &Desc, &pCounter ) ) )
GetDXUTState().SetCounter_VSMemoryLimited( pCounter );
Desc.Counter = D3D10_COUNTER_VS_COMPUTATION_LIMITED;
if( SUCCEEDED( hr = pd3dDevice->CreateCounter( &Desc, &pCounter ) ) )
GetDXUTState().SetCounter_VSComputationLimited( pCounter );
Desc.Counter = D3D10_COUNTER_GS_MEMORY_LIMITED;
if( SUCCEEDED( hr = pd3dDevice->CreateCounter( &Desc, &pCounter ) ) )
GetDXUTState().SetCounter_GSMemoryLimited( pCounter );
Desc.Counter = D3D10_COUNTER_GS_COMPUTATION_LIMITED;
if( SUCCEEDED( hr = pd3dDevice->CreateCounter( &Desc, &pCounter ) ) )
GetDXUTState().SetCounter_GSComputationLimited( pCounter );
Desc.Counter = D3D10_COUNTER_PS_MEMORY_LIMITED;
if( SUCCEEDED( hr = pd3dDevice->CreateCounter( &Desc, &pCounter ) ) )
GetDXUTState().SetCounter_PSMemoryLimited( pCounter );
Desc.Counter = D3D10_COUNTER_PS_COMPUTATION_LIMITED;
if( SUCCEEDED( hr = pd3dDevice->CreateCounter( &Desc, &pCounter ) ) )
GetDXUTState().SetCounter_PSComputationLimited( pCounter );
Desc.Counter = D3D10_COUNTER_POST_TRANSFORM_CACHE_HIT_RATE;
if( SUCCEEDED( hr = pd3dDevice->CreateCounter( &Desc, &pCounter ) ) )
GetDXUTState().SetCounter_PostTransformCacheHitRate( pCounter );
Desc.Counter = D3D10_COUNTER_TEXTURE_CACHE_HIT_RATE;
if( SUCCEEDED( hr = pd3dDevice->CreateCounter( &Desc, &pCounter ) ) )
GetDXUTState().SetCounter_TextureCacheHitRate( pCounter );
}
//--------------------------------------------------------------------------------------
void DXUTDestroyD3D10Counters()
{
ID3D10Counter* pCounter = GetDXUTState().GetCounter_GPUIdle();
SAFE_RELEASE( pCounter );
GetDXUTState().SetCounter_GPUIdle( NULL );
pCounter = GetDXUTState().GetCounter_VertexProcessing();
SAFE_RELEASE( pCounter );
GetDXUTState().SetCounter_VertexProcessing( NULL );
pCounter = GetDXUTState().GetCounter_GeometryProcessing();
SAFE_RELEASE( pCounter );
GetDXUTState().SetCounter_GeometryProcessing( NULL );
pCounter = GetDXUTState().GetCounter_PixelProcessing();
SAFE_RELEASE( pCounter );
GetDXUTState().SetCounter_PixelProcessing( NULL );
pCounter = GetDXUTState().GetCounter_OtherGPUProcessing();
SAFE_RELEASE( pCounter );
GetDXUTState().SetCounter_OtherGPUProcessing( NULL );
pCounter = GetDXUTState().GetCounter_HostAdapterBandwidthUtilization();
SAFE_RELEASE( pCounter );
GetDXUTState().SetCounter_HostAdapterBandwidthUtilization( NULL );
pCounter = GetDXUTState().GetCounter_LocalVidmemBandwidthUtilization();
SAFE_RELEASE( pCounter );
GetDXUTState().SetCounter_LocalVidmemBandwidthUtilization( NULL );
pCounter = GetDXUTState().GetCounter_VertexThroughputUtilization();
SAFE_RELEASE( pCounter );
GetDXUTState().SetCounter_VertexThroughputUtilization( NULL );
pCounter = GetDXUTState().GetCounter_TriangleSetupThroughputUtilization();
SAFE_RELEASE( pCounter );
GetDXUTState().SetCounter_TriangleSetupThroughputUtilization( NULL );
pCounter = GetDXUTState().GetCounter_FillrateThrougputUtilization();
SAFE_RELEASE( pCounter );
GetDXUTState().SetCounter_FillrateThrougputUtilization( NULL );
pCounter = GetDXUTState().GetCounter_VSMemoryLimited();
SAFE_RELEASE( pCounter );
GetDXUTState().SetCounter_VSMemoryLimited( NULL );
pCounter = GetDXUTState().GetCounter_VSComputationLimited();
SAFE_RELEASE( pCounter );
GetDXUTState().SetCounter_VSComputationLimited( NULL );
pCounter = GetDXUTState().GetCounter_GSMemoryLimited();
SAFE_RELEASE( pCounter );
GetDXUTState().SetCounter_GSMemoryLimited( NULL );
pCounter = GetDXUTState().GetCounter_GSComputationLimited();
SAFE_RELEASE( pCounter );
GetDXUTState().SetCounter_GSComputationLimited( NULL );
pCounter = GetDXUTState().GetCounter_PSMemoryLimited();
SAFE_RELEASE( pCounter );
GetDXUTState().SetCounter_PSMemoryLimited( NULL );
pCounter = GetDXUTState().GetCounter_PSComputationLimited();
SAFE_RELEASE( pCounter );
GetDXUTState().SetCounter_PSComputationLimited( NULL );
pCounter = GetDXUTState().GetCounter_PostTransformCacheHitRate();
SAFE_RELEASE( pCounter );
GetDXUTState().SetCounter_PostTransformCacheHitRate( NULL );
pCounter = GetDXUTState().GetCounter_TextureCacheHitRate();
SAFE_RELEASE( pCounter );
GetDXUTState().SetCounter_TextureCacheHitRate( NULL );
}
//--------------------------------------------------------------------------------------
void DXUTStartPerformanceCounters()
{
if( GetDXUTState().GetNoStats() )
return;
ID3D10Counter* pCounter = GetDXUTState().GetCounter_GPUIdle();
if( pCounter )
pCounter->Begin();
pCounter = GetDXUTState().GetCounter_VertexProcessing();
if( pCounter )
pCounter->Begin();
pCounter = GetDXUTState().GetCounter_GeometryProcessing();
if( pCounter )
pCounter->Begin();
pCounter = GetDXUTState().GetCounter_PixelProcessing();
if( pCounter )
pCounter->Begin();
pCounter = GetDXUTState().GetCounter_OtherGPUProcessing();
if( pCounter )
pCounter->Begin();
pCounter = GetDXUTState().GetCounter_HostAdapterBandwidthUtilization();
if( pCounter )
pCounter->Begin();
pCounter = GetDXUTState().GetCounter_LocalVidmemBandwidthUtilization();
if( pCounter )
pCounter->Begin();
pCounter = GetDXUTState().GetCounter_VertexThroughputUtilization();
if( pCounter )
pCounter->Begin();
pCounter = GetDXUTState().GetCounter_TriangleSetupThroughputUtilization();
if( pCounter )
pCounter->Begin();
pCounter = GetDXUTState().GetCounter_FillrateThrougputUtilization();
if( pCounter )
pCounter->Begin();
pCounter = GetDXUTState().GetCounter_VSMemoryLimited();
if( pCounter )
pCounter->Begin();
pCounter = GetDXUTState().GetCounter_VSComputationLimited();
if( pCounter )
pCounter->Begin();
pCounter = GetDXUTState().GetCounter_GSMemoryLimited();
if( pCounter )
pCounter->Begin();
pCounter = GetDXUTState().GetCounter_GSComputationLimited();
if( pCounter )
pCounter->Begin();
pCounter = GetDXUTState().GetCounter_PSMemoryLimited();
if( pCounter )
pCounter->Begin();
pCounter = GetDXUTState().GetCounter_PSComputationLimited();
if( pCounter )
pCounter->Begin();
pCounter = GetDXUTState().GetCounter_PostTransformCacheHitRate();
if( pCounter )
pCounter->Begin();
pCounter = GetDXUTState().GetCounter_TextureCacheHitRate();
if( pCounter )
pCounter->Begin();
}
//--------------------------------------------------------------------------------------
void DXUTStopPerformanceCounters()
{
if( GetDXUTState().GetNoStats() )
return;
ID3D10Counter* pCounter = GetDXUTState().GetCounter_GPUIdle();
if( pCounter )
pCounter->End();
pCounter = GetDXUTState().GetCounter_VertexProcessing();
if( pCounter )
pCounter->End();
pCounter = GetDXUTState().GetCounter_GeometryProcessing();
if( pCounter )
pCounter->End();
pCounter = GetDXUTState().GetCounter_PixelProcessing();
if( pCounter )
pCounter->End();
pCounter = GetDXUTState().GetCounter_OtherGPUProcessing();
if( pCounter )
pCounter->End();
pCounter = GetDXUTState().GetCounter_HostAdapterBandwidthUtilization();
if( pCounter )
pCounter->End();
pCounter = GetDXUTState().GetCounter_LocalVidmemBandwidthUtilization();
if( pCounter )
pCounter->End();
pCounter = GetDXUTState().GetCounter_VertexThroughputUtilization();
if( pCounter )
pCounter->End();
pCounter = GetDXUTState().GetCounter_TriangleSetupThroughputUtilization();
if( pCounter )
pCounter->End();
pCounter = GetDXUTState().GetCounter_FillrateThrougputUtilization();
if( pCounter )
pCounter->End();
pCounter = GetDXUTState().GetCounter_VSMemoryLimited();
if( pCounter )
pCounter->End();
pCounter = GetDXUTState().GetCounter_VSComputationLimited();
if( pCounter )
pCounter->End();
pCounter = GetDXUTState().GetCounter_GSMemoryLimited();
if( pCounter )
pCounter->End();
pCounter = GetDXUTState().GetCounter_GSComputationLimited();
if( pCounter )
pCounter->End();
pCounter = GetDXUTState().GetCounter_PSMemoryLimited();
if( pCounter )
pCounter->End();
pCounter = GetDXUTState().GetCounter_PSComputationLimited();
if( pCounter )
pCounter->End();
pCounter = GetDXUTState().GetCounter_PostTransformCacheHitRate();
if( pCounter )
pCounter->End();
pCounter = GetDXUTState().GetCounter_TextureCacheHitRate();
if( pCounter )
pCounter->End();
}
//--------------------------------------------------------------------------------------
void DXUTUpdateD3D10CounterStats()
{
if( GetDXUTState().GetNoStats() )
return;
D3D10_COUNTERS* pCounterData = GetDXUTState().GetCounterData();
float fData;
ID3D10Counter* pCounter = GetDXUTState().GetCounter_GPUIdle();
if( pCounter )
if( SUCCEEDED( pCounter->GetData( &fData, sizeof(float), D3D10_ASYNC_GETDATA_DONOTFLUSH ) ) )
pCounterData->fGPUIdle = fData;
pCounter = GetDXUTState().GetCounter_VertexProcessing();
if( pCounter )
if( SUCCEEDED( pCounter->GetData( &fData, sizeof(float), D3D10_ASYNC_GETDATA_DONOTFLUSH ) ) )
pCounterData->fVertexProcessing = fData;
pCounter = GetDXUTState().GetCounter_GeometryProcessing();
if( pCounter )
if( SUCCEEDED( pCounter->GetData( &fData, sizeof(float), D3D10_ASYNC_GETDATA_DONOTFLUSH ) ) )
pCounterData->fGeometryProcessing = fData;
pCounter = GetDXUTState().GetCounter_PixelProcessing();
if( pCounter )
if( SUCCEEDED( pCounter->GetData( &fData, sizeof(float), D3D10_ASYNC_GETDATA_DONOTFLUSH ) ) )
pCounterData->fPixelProcessing = fData;
pCounter = GetDXUTState().GetCounter_OtherGPUProcessing();
if( pCounter )
if( SUCCEEDED( pCounter->GetData( &fData, sizeof(float), D3D10_ASYNC_GETDATA_DONOTFLUSH ) ) )
pCounterData->fOtherGPUProcessing = fData;
pCounter = GetDXUTState().GetCounter_HostAdapterBandwidthUtilization();
if( pCounter )
if( SUCCEEDED( pCounter->GetData( &fData, sizeof(float), D3D10_ASYNC_GETDATA_DONOTFLUSH ) ) )
pCounterData->fHostAdapterBandwidthUtilization = fData;
pCounter = GetDXUTState().GetCounter_LocalVidmemBandwidthUtilization();
if( pCounter )
if( SUCCEEDED( pCounter->GetData( &fData, sizeof(float), D3D10_ASYNC_GETDATA_DONOTFLUSH ) ) )
pCounterData->fLocalVidmemBandwidthUtilization = fData;
pCounter = GetDXUTState().GetCounter_VertexThroughputUtilization();
if( pCounter )
if( SUCCEEDED( pCounter->GetData( &fData, sizeof(float), D3D10_ASYNC_GETDATA_DONOTFLUSH ) ) )
pCounterData->fVertexThroughputUtilization = fData;
pCounter = GetDXUTState().GetCounter_TriangleSetupThroughputUtilization();
if( pCounter )
if( SUCCEEDED( pCounter->GetData( &fData, sizeof(float), D3D10_ASYNC_GETDATA_DONOTFLUSH ) ) )
pCounterData->fTriangleSetupThroughputUtilization = fData;
pCounter = GetDXUTState().GetCounter_FillrateThrougputUtilization();
if( pCounter )
if( SUCCEEDED( pCounter->GetData( &fData, sizeof(float), D3D10_ASYNC_GETDATA_DONOTFLUSH ) ) )
pCounterData->fFillrateThroughputUtilization = fData;
pCounter = GetDXUTState().GetCounter_VSMemoryLimited();
if( pCounter )
if( SUCCEEDED( pCounter->GetData( &fData, sizeof(float), D3D10_ASYNC_GETDATA_DONOTFLUSH ) ) )
pCounterData->fVSMemoryLimited = fData;
pCounter = GetDXUTState().GetCounter_VSComputationLimited();
if( pCounter )
if( SUCCEEDED( pCounter->GetData( &fData, sizeof(float), D3D10_ASYNC_GETDATA_DONOTFLUSH ) ) )
pCounterData->fVSComputationLimited = fData;
pCounter = GetDXUTState().GetCounter_GSMemoryLimited();
if( pCounter )
if( SUCCEEDED( pCounter->GetData( &fData, sizeof(float), D3D10_ASYNC_GETDATA_DONOTFLUSH ) ) )
pCounterData->fGSMemoryLimited = fData;
pCounter = GetDXUTState().GetCounter_GSComputationLimited();
if( pCounter )
if( SUCCEEDED( pCounter->GetData( &fData, sizeof(float), D3D10_ASYNC_GETDATA_DONOTFLUSH ) ) )
pCounterData->fGSComputationLimited = fData;
pCounter = GetDXUTState().GetCounter_PSMemoryLimited();
if( pCounter )
if( SUCCEEDED( pCounter->GetData( &fData, sizeof(float), D3D10_ASYNC_GETDATA_DONOTFLUSH ) ) )
pCounterData->fPSMemoryLimited = fData;
pCounter = GetDXUTState().GetCounter_PSComputationLimited();
if( pCounter )
if( SUCCEEDED( pCounter->GetData( &fData, sizeof(float), D3D10_ASYNC_GETDATA_DONOTFLUSH ) ) )
pCounterData->fPSComputationLimited = fData;
pCounter = GetDXUTState().GetCounter_PostTransformCacheHitRate();
if( pCounter )
if( SUCCEEDED( pCounter->GetData( &fData, sizeof(float), D3D10_ASYNC_GETDATA_DONOTFLUSH ) ) )
pCounterData->fPostTransformCacheHitRate = fData;
pCounter = GetDXUTState().GetCounter_TextureCacheHitRate();
if( pCounter )
if( SUCCEEDED( pCounter->GetData( &fData, sizeof(float), D3D10_ASYNC_GETDATA_DONOTFLUSH ) ) )
pCounterData->fTextureCacheHitRate = fData;
// plop everything into a string
WCHAR* strStats = GetDXUTState().GetD3D10CounterStats();
static WCHAR szFormat[] = L"GPUIdle: %f\n"\
L"VertexProcessing: %f\n"\
L"GeometryProcessing: %f\n"\
L"PixelProcessing: %f\n"\
L"OtherGPUProcessing: %f\n"\
L"HostAdapterBandwidthUtilization: %f\n"\
L"LocalVidmemBandwidthUtilization: %f\n"\
L"VertexThroughputUtilization: %f\n"\
L"TriangleSetupThroughputUtilization: %f\n"\
L"FillrateThroughputUtilization: %f\n"\
L"VSMemoryLimited: %f\n"\
L"VSComputationLimited: %f\n"\
L"GSMemoryLimited: %f\n"\
L"GSComputationLimited: %f\n"\
L"PSMemoryLimited: %f\n"\
L"PSComputationLimited: %f\n"\
L"PostTransformCacheHitRate: %f\n"\
L"TextureCacheHitRate: %f\n";
StringCchPrintf( strStats, DXUT_COUNTER_STAT_LENGTH, szFormat,
pCounterData->fGPUIdle,
pCounterData->fVertexProcessing,
pCounterData->fGeometryProcessing,
pCounterData->fPixelProcessing,
pCounterData->fOtherGPUProcessing,
pCounterData->fHostAdapterBandwidthUtilization,
pCounterData->fLocalVidmemBandwidthUtilization,
pCounterData->fVertexThroughputUtilization,
pCounterData->fTriangleSetupThroughputUtilization,
pCounterData->fFillrateThroughputUtilization,
pCounterData->fVSMemoryLimited,
pCounterData->fVSComputationLimited,
pCounterData->fGSMemoryLimited,
pCounterData->fGSComputationLimited,
pCounterData->fPSMemoryLimited,
pCounterData->fPSComputationLimited,
pCounterData->fPostTransformCacheHitRate,
pCounterData->fTextureCacheHitRate );
}
//--------------------------------------------------------------------------------------
// Low level keyboard hook to disable Windows key to prevent accidental task switching.
//--------------------------------------------------------------------------------------
LRESULT CALLBACK DXUTLowLevelKeyboardProc( int nCode, WPARAM wParam, LPARAM lParam )
{
if (nCode < 0 || nCode != HC_ACTION) // do not process message
return CallNextHookEx( GetDXUTState().GetKeyboardHook(), nCode, wParam, lParam);
bool bEatKeystroke = false;
KBDLLHOOKSTRUCT* p = (KBDLLHOOKSTRUCT*)lParam;
switch (wParam)
{
case WM_KEYDOWN:
case WM_KEYUP:
{
bEatKeystroke = ( !GetDXUTState().GetAllowShortcutKeys() &&
(p->vkCode == VK_LWIN || p->vkCode == VK_RWIN) );
break;
}
}
if( bEatKeystroke )
return 1;
else
return CallNextHookEx( GetDXUTState().GetKeyboardHook(), nCode, wParam, lParam );
}
//--------------------------------------------------------------------------------------
// Controls how DXUT behaves when fullscreen and windowed mode with regard to
// shortcut keys (Windows keys, StickyKeys shortcut, ToggleKeys shortcut, FilterKeys shortcut)
//--------------------------------------------------------------------------------------
void WINAPI DXUTSetShortcutKeySettings( bool bAllowWhenFullscreen, bool bAllowWhenWindowed )
{
GetDXUTState().SetAllowShortcutKeysWhenWindowed( bAllowWhenWindowed );
GetDXUTState().SetAllowShortcutKeysWhenFullscreen( bAllowWhenFullscreen );
// DXUTInit() records initial accessibility states so don't change them until then
if( GetDXUTState().GetDXUTInited() )
{
if( DXUTIsWindowed() )
DXUTAllowShortcutKeys( GetDXUTState().GetAllowShortcutKeysWhenWindowed() );
else
DXUTAllowShortcutKeys( GetDXUTState().GetAllowShortcutKeysWhenFullscreen() );
}
}
//--------------------------------------------------------------------------------------
// Enables/disables Windows keys, and disables or restores the StickyKeys/ToggleKeys/FilterKeys
// shortcut to help prevent accidental task switching
//--------------------------------------------------------------------------------------
void DXUTAllowShortcutKeys( bool bAllowKeys )
{
GetDXUTState().SetAllowShortcutKeys( bAllowKeys );
if( bAllowKeys )
{
// Restore StickyKeys/etc to original state and enable Windows key
STICKYKEYS sk = GetDXUTState().GetStartupStickyKeys();
TOGGLEKEYS tk = GetDXUTState().GetStartupToggleKeys();
FILTERKEYS fk = GetDXUTState().GetStartupFilterKeys();
SystemParametersInfo(SPI_SETSTICKYKEYS, sizeof(STICKYKEYS), &sk, 0);
SystemParametersInfo(SPI_SETTOGGLEKEYS, sizeof(TOGGLEKEYS), &tk, 0);
SystemParametersInfo(SPI_SETFILTERKEYS, sizeof(FILTERKEYS), &fk, 0);
// Remove the keyboard hoook when it isn't needed to prevent any slow down of other apps
if( GetDXUTState().GetKeyboardHook() )
{
UnhookWindowsHookEx( GetDXUTState().GetKeyboardHook() );
GetDXUTState().SetKeyboardHook( NULL );
}
}
else
{
// Set low level keyboard hook if haven't already
if( GetDXUTState().GetKeyboardHook() == NULL )
{
// Set the low-level hook procedure. Only works on Windows 2000 and above
OSVERSIONINFO OSVersionInfo;
OSVersionInfo.dwOSVersionInfoSize = sizeof(OSVersionInfo);
GetVersionEx(&OSVersionInfo);
if( OSVersionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT && OSVersionInfo.dwMajorVersion > 4 )
{
HHOOK hKeyboardHook = SetWindowsHookEx( WH_KEYBOARD_LL, DXUTLowLevelKeyboardProc, GetModuleHandle(NULL), 0 );
GetDXUTState().SetKeyboardHook( hKeyboardHook );
}
}
// Disable StickyKeys/etc shortcuts but if the accessibility feature is on,
// then leave the settings alone as its probably being usefully used
STICKYKEYS skOff = GetDXUTState().GetStartupStickyKeys();
if( (skOff.dwFlags & SKF_STICKYKEYSON) == 0 )
{
// Disable the hotkey and the confirmation
skOff.dwFlags &= ~SKF_HOTKEYACTIVE;
skOff.dwFlags &= ~SKF_CONFIRMHOTKEY;
SystemParametersInfo(SPI_SETSTICKYKEYS, sizeof(STICKYKEYS), &skOff, 0);
}
TOGGLEKEYS tkOff = GetDXUTState().GetStartupToggleKeys();
if( (tkOff.dwFlags & TKF_TOGGLEKEYSON) == 0 )
{
// Disable the hotkey and the confirmation
tkOff.dwFlags &= ~TKF_HOTKEYACTIVE;
tkOff.dwFlags &= ~TKF_CONFIRMHOTKEY;
SystemParametersInfo(SPI_SETTOGGLEKEYS, sizeof(TOGGLEKEYS), &tkOff, 0);
}
FILTERKEYS fkOff = GetDXUTState().GetStartupFilterKeys();
if( (fkOff.dwFlags & FKF_FILTERKEYSON) == 0 )
{
// Disable the hotkey and the confirmation
fkOff.dwFlags &= ~FKF_HOTKEYACTIVE;
fkOff.dwFlags &= ~FKF_CONFIRMHOTKEY;
SystemParametersInfo(SPI_SETFILTERKEYS, sizeof(FILTERKEYS), &fkOff, 0);
}
}
}
//--------------------------------------------------------------------------------------
// Pauses time or rendering. Keeps a ref count so pausing can be layered
//--------------------------------------------------------------------------------------
void WINAPI DXUTPause( bool bPauseTime, bool bPauseRendering )
{
int nPauseTimeCount = GetDXUTState().GetPauseTimeCount();
if( bPauseTime ) nPauseTimeCount++; else nPauseTimeCount--;
if( nPauseTimeCount < 0 ) nPauseTimeCount = 0;
GetDXUTState().SetPauseTimeCount( nPauseTimeCount );
int nPauseRenderingCount = GetDXUTState().GetPauseRenderingCount();
if( bPauseRendering ) nPauseRenderingCount++; else nPauseRenderingCount--;
if( nPauseRenderingCount < 0 ) nPauseRenderingCount = 0;
GetDXUTState().SetPauseRenderingCount( nPauseRenderingCount );
if( nPauseTimeCount > 0 )
{
// Stop the scene from animating
DXUTGetGlobalTimer()->Stop();
}
else
{
// Restart the timer
DXUTGetGlobalTimer()->Start();
}
GetDXUTState().SetRenderingPaused( nPauseRenderingCount > 0 );
GetDXUTState().SetTimePaused( nPauseTimeCount > 0 );
}
//--------------------------------------------------------------------------------------
// Starts a user defined timer callback
//--------------------------------------------------------------------------------------
HRESULT WINAPI DXUTSetTimer( LPDXUTCALLBACKTIMER pCallbackTimer, float fTimeoutInSecs, UINT* pnIDEvent, void* pCallbackUserContext )
{
if( pCallbackTimer == NULL )
return DXUT_ERR_MSGBOX( L"DXUTSetTimer", E_INVALIDARG );
HRESULT hr;
DXUT_TIMER DXUTTimer;
DXUTTimer.pCallbackTimer = pCallbackTimer;
DXUTTimer.pCallbackUserContext = pCallbackUserContext;
DXUTTimer.fTimeoutInSecs = fTimeoutInSecs;
DXUTTimer.fCountdown = fTimeoutInSecs;
DXUTTimer.bEnabled = true;
DXUTTimer.nID = GetDXUTState().GetTimerLastID() + 1;
GetDXUTState().SetTimerLastID( DXUTTimer.nID );
CGrowableArray<DXUT_TIMER>* pTimerList = GetDXUTState().GetTimerList();
if( pTimerList == NULL )
{
pTimerList = new CGrowableArray<DXUT_TIMER>;
if( pTimerList == NULL )
return E_OUTOFMEMORY;
GetDXUTState().SetTimerList( pTimerList );
}
if( FAILED( hr = pTimerList->Add( DXUTTimer ) ) )
return hr;
if( pnIDEvent )
*pnIDEvent = DXUTTimer.nID;
return S_OK;
}
//--------------------------------------------------------------------------------------
// Stops a user defined timer callback
//--------------------------------------------------------------------------------------
HRESULT WINAPI DXUTKillTimer( UINT nIDEvent )
{
CGrowableArray<DXUT_TIMER>* pTimerList = GetDXUTState().GetTimerList();
if( pTimerList == NULL )
return S_FALSE;
bool bFound = false;
for( int i=0; i<pTimerList->GetSize(); i++ )
{
DXUT_TIMER DXUTTimer = pTimerList->GetAt(i);
if( DXUTTimer.nID == nIDEvent )
{
DXUTTimer.bEnabled = false;
pTimerList->SetAt(i, DXUTTimer);
bFound = true;
break;
}
}
if( !bFound )
return DXUT_ERR_MSGBOX( L"DXUTKillTimer", E_INVALIDARG );
return S_OK;
}
//--------------------------------------------------------------------------------------
// Internal helper function to handle calling the user defined timer callbacks
//--------------------------------------------------------------------------------------
void DXUTHandleTimers()
{
float fElapsedTime = DXUTGetElapsedTime();
CGrowableArray<DXUT_TIMER>* pTimerList = GetDXUTState().GetTimerList();
if( pTimerList == NULL )
return;
// Walk through the list of timer callbacks
for( int i=0; i<pTimerList->GetSize(); i++ )
{
DXUT_TIMER DXUTTimer = pTimerList->GetAt(i);
if( DXUTTimer.bEnabled )
{
DXUTTimer.fCountdown -= fElapsedTime;
// Call the callback if count down expired
if( DXUTTimer.fCountdown < 0 )
{
DXUTTimer.pCallbackTimer( DXUTTimer.nID, DXUTTimer.pCallbackUserContext );
// The callback my have changed the timer.
DXUTTimer = pTimerList->GetAt(i);
DXUTTimer.fCountdown = DXUTTimer.fTimeoutInSecs;
}
pTimerList->SetAt(i, DXUTTimer);
}
}
}
//--------------------------------------------------------------------------------------
// Display an custom error msg box
//--------------------------------------------------------------------------------------
void DXUTDisplayErrorMessage( HRESULT hr )
{
WCHAR strBuffer[512];
int nExitCode;
bool bFound = true;
switch( hr )
{
case DXUTERR_NODIRECT3D:
{
nExitCode = 2;
if( DXUTDoesAppSupportD3D10() && !DXUTDoesAppSupportD3D9() )
StringCchCopy( strBuffer, ARRAYSIZE(strBuffer), L"Could not initialize Direct3D 10. This application requires a Direct3D 10 class\ndevice (hardware or reference rasterizer) running on Windows Vista (or later)." );
else
StringCchCopy( strBuffer, ARRAYSIZE(strBuffer), L"Could not initialize Direct3D 9. Check that the latest version of DirectX is correctly installed on your system. Also make sure that this program was compiled with header files that match the installed DirectX DLLs." );
break;
}
case DXUTERR_NOCOMPATIBLEDEVICES:
nExitCode = 3;
if( GetSystemMetrics(0x1000) != 0 ) // SM_REMOTESESSION
StringCchCopy( strBuffer, ARRAYSIZE(strBuffer), L"Direct3D does not work over a remote session." );
else
StringCchCopy( strBuffer, ARRAYSIZE(strBuffer), L"Could not find any compatible Direct3D devices." );
break;
case DXUTERR_MEDIANOTFOUND: nExitCode = 4; StringCchCopy( strBuffer, ARRAYSIZE(strBuffer), L"Could not find required media." ); break;
case DXUTERR_NONZEROREFCOUNT: nExitCode = 5; StringCchCopy( strBuffer, ARRAYSIZE(strBuffer), L"The Direct3D device has a non-zero reference count, meaning some objects were not released." ); break;
case DXUTERR_CREATINGDEVICE: nExitCode = 6; StringCchCopy( strBuffer, ARRAYSIZE(strBuffer), L"Failed creating the Direct3D device." ); break;
case DXUTERR_RESETTINGDEVICE: nExitCode = 7; StringCchCopy( strBuffer, ARRAYSIZE(strBuffer), L"Failed resetting the Direct3D device." ); break;
case DXUTERR_CREATINGDEVICEOBJECTS: nExitCode = 8; StringCchCopy( strBuffer, ARRAYSIZE(strBuffer), L"An error occurred in the device create callback function." ); break;
case DXUTERR_RESETTINGDEVICEOBJECTS: nExitCode = 9; StringCchCopy( strBuffer, ARRAYSIZE(strBuffer), L"An error occurred in the device reset callback function." ); break;
// nExitCode 10 means the app exited using a REF device
case DXUTERR_DEVICEREMOVED: nExitCode = 11; StringCchCopy( strBuffer, ARRAYSIZE(strBuffer), L"The Direct3D device was removed." ); break;
default: bFound = false; nExitCode = 1; break; // nExitCode 1 means the API was incorrectly called
}
GetDXUTState().SetExitCode(nExitCode);
bool bShowMsgBoxOnError = GetDXUTState().GetShowMsgBoxOnError();
if( bFound && bShowMsgBoxOnError )
{
if( DXUTGetWindowTitle()[0] == 0 )
MessageBox( DXUTGetHWND(), strBuffer, L"DXUT Application", MB_ICONERROR|MB_OK );
else
MessageBox( DXUTGetHWND(), strBuffer, DXUTGetWindowTitle(), MB_ICONERROR|MB_OK );
}
}
//--------------------------------------------------------------------------------------
// Internal function to map MK_* to an array index
//--------------------------------------------------------------------------------------
int DXUTMapButtonToArrayIndex( BYTE vButton )
{
switch( vButton )
{
case MK_LBUTTON: return 0;
case VK_MBUTTON:
case MK_MBUTTON: return 1;
case MK_RBUTTON: return 2;
case VK_XBUTTON1:
case MK_XBUTTON1: return 3;
case VK_XBUTTON2:
case MK_XBUTTON2: return 4;
}
return 0;
}
//--------------------------------------------------------------------------------------
// Toggle between full screen and windowed
//--------------------------------------------------------------------------------------
HRESULT WINAPI DXUTToggleFullScreen()
{
HRESULT hr;
// Get the current device settings and flip the windowed state then
// find the closest valid device settings with this change
DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings();
DXUTDeviceSettings orginalDeviceSettings = DXUTGetDeviceSettings();
// Togggle windowed/fullscreen bit
if( DXUTIsD3D9( &deviceSettings ) )
deviceSettings.d3d9.pp.Windowed = !deviceSettings.d3d9.pp.Windowed;
else
deviceSettings.d3d10.sd.Windowed = !deviceSettings.d3d10.sd.Windowed;
DXUTMatchOptions matchOptions;
matchOptions.eAPIVersion = DXUTMT_PRESERVE_INPUT;
matchOptions.eAdapterOrdinal = DXUTMT_PRESERVE_INPUT;
matchOptions.eDeviceType = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eWindowed = DXUTMT_PRESERVE_INPUT;
matchOptions.eAdapterFormat = DXUTMT_IGNORE_INPUT;
matchOptions.eVertexProcessing = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eBackBufferFormat = DXUTMT_IGNORE_INPUT;
matchOptions.eBackBufferCount = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eMultiSample = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eSwapEffect = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eDepthFormat = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eStencilFormat = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.ePresentFlags = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eRefreshRate = DXUTMT_IGNORE_INPUT;
matchOptions.ePresentInterval = DXUTMT_CLOSEST_TO_INPUT;
// Go back to previous state
BOOL bIsWindowed = DXUTGetIsWindowedFromDS( &deviceSettings );
UINT nWidth = ( bIsWindowed ) ? GetDXUTState().GetWindowBackBufferWidthAtModeChange() : GetDXUTState().GetFullScreenBackBufferWidthAtModeChange();
UINT nHeight = ( bIsWindowed ) ? GetDXUTState().GetWindowBackBufferHeightAtModeChange() : GetDXUTState().GetFullScreenBackBufferHeightAtModeChange();
if( nWidth > 0 && nHeight > 0 )
{
matchOptions.eResolution = DXUTMT_CLOSEST_TO_INPUT;
if( DXUTIsD3D9( &deviceSettings ) )
{
deviceSettings.d3d9.pp.BackBufferWidth = nWidth;
deviceSettings.d3d9.pp.BackBufferHeight = nHeight;
}
else
{
deviceSettings.d3d10.sd.BufferDesc.Width = nWidth;
deviceSettings.d3d10.sd.BufferDesc.Height = nHeight;
}
}
else
{
// No previous data, so just switch to defaults
matchOptions.eResolution = DXUTMT_IGNORE_INPUT;
}
hr = DXUTFindValidDeviceSettings( &deviceSettings, &deviceSettings, &matchOptions );
if( SUCCEEDED(hr) )
{
// Create a Direct3D device using the new device settings.
// If there is an existing device, then it will either reset or recreate the scene.
hr = DXUTChangeDevice( &deviceSettings, NULL, NULL, false, false );
// If hr == E_ABORT, this means the app rejected the device settings in the ModifySettingsCallback so nothing changed
if( FAILED(hr) && (hr != E_ABORT) )
{
// Failed creating device, try to switch back.
HRESULT hr2 = DXUTChangeDevice( &orginalDeviceSettings, NULL, NULL, false, false );
if( FAILED(hr2) )
{
// If this failed, then shutdown
DXUTShutdown();
}
}
}
return hr;
}
//--------------------------------------------------------------------------------------
// Toggle between HAL and REF
//--------------------------------------------------------------------------------------
HRESULT WINAPI DXUTToggleREF()
{
HRESULT hr;
DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings();
DXUTDeviceSettings orginalDeviceSettings = DXUTGetDeviceSettings();
// Toggle between REF & HAL
if( DXUTIsCurrentDeviceD3D9() )
{
if( deviceSettings.d3d9.DeviceType == D3DDEVTYPE_HAL )
deviceSettings.d3d9.DeviceType = D3DDEVTYPE_REF;
else if( deviceSettings.d3d9.DeviceType == D3DDEVTYPE_REF )
deviceSettings.d3d9.DeviceType = D3DDEVTYPE_HAL;
}
else
{
ID3D10SwitchToRef* pD3D10STR = NULL;
hr = DXUTGetD3D10Device()->QueryInterface( __uuidof( *pD3D10STR ), (LPVOID*)&pD3D10STR );
if( SUCCEEDED( hr ) )
{
pD3D10STR->SetUseRef( pD3D10STR->GetUseRef() ? FALSE : TRUE );
SAFE_RELEASE( pD3D10STR );
return S_OK;
}
if( deviceSettings.d3d10.DriverType == D3D10_DRIVER_TYPE_HARDWARE )
deviceSettings.d3d10.DriverType = D3D10_DRIVER_TYPE_REFERENCE;
else if( deviceSettings.d3d10.DriverType == D3D10_DRIVER_TYPE_REFERENCE )
deviceSettings.d3d10.DriverType = D3D10_DRIVER_TYPE_HARDWARE;
}
DXUTMatchOptions matchOptions;
matchOptions.eAPIVersion = DXUTMT_PRESERVE_INPUT;
matchOptions.eAdapterOrdinal = DXUTMT_PRESERVE_INPUT;
matchOptions.eDeviceType = DXUTMT_PRESERVE_INPUT;
matchOptions.eWindowed = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eAdapterFormat = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eVertexProcessing = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eResolution = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eBackBufferFormat = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eBackBufferCount = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eMultiSample = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eSwapEffect = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eDepthFormat = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eStencilFormat = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.ePresentFlags = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eRefreshRate = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.ePresentInterval = DXUTMT_CLOSEST_TO_INPUT;
hr = DXUTFindValidDeviceSettings( &deviceSettings, &deviceSettings, &matchOptions );
if( SUCCEEDED(hr) )
{
// Create a Direct3D device using the new device settings.
// If there is an existing device, then it will either reset or recreate the scene.
hr = DXUTChangeDevice( &deviceSettings, NULL, NULL, false, false );
// If hr == E_ABORT, this means the app rejected the device settings in the ModifySettingsCallback so nothing changed
if( FAILED( hr ) && (hr != E_ABORT) )
{
// Failed creating device, try to switch back.
HRESULT hr2 = DXUTChangeDevice( &orginalDeviceSettings, NULL, NULL, false, false );
if( FAILED(hr2) )
{
// If this failed, then shutdown
DXUTShutdown();
}
}
}
return hr;
}
//--------------------------------------------------------------------------------------
// Checks to see if DXGI has switched us out of fullscreen or windowed mode
//--------------------------------------------------------------------------------------
void DXUTCheckForDXGIFullScreenSwitch()
{
DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings();
if( !DXUTIsD3D9(pDeviceSettings) )
{
IDXGISwapChain* pSwapChain = DXUTGetDXGISwapChain();
DXGI_SWAP_CHAIN_DESC SCDesc;
pSwapChain->GetDesc( &SCDesc );
BOOL bIsWindowed = (BOOL)DXUTIsWindowed();
if( bIsWindowed != SCDesc.Windowed )
{
pDeviceSettings->d3d10.sd.Windowed = SCDesc.Windowed;
DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings();
if( bIsWindowed )
{
GetDXUTState().SetWindowBackBufferWidthAtModeChange( deviceSettings.d3d10.sd.BufferDesc.Width );
GetDXUTState().SetWindowBackBufferHeightAtModeChange( deviceSettings.d3d10.sd.BufferDesc.Height );
}
else
{
GetDXUTState().SetFullScreenBackBufferWidthAtModeChange( deviceSettings.d3d10.sd.BufferDesc.Width );
GetDXUTState().SetFullScreenBackBufferHeightAtModeChange( deviceSettings.d3d10.sd.BufferDesc.Height );
}
}
}
}
void DXUTResizeDXGIBuffers( UINT Width, UINT Height, BOOL bFullScreen )
{
HRESULT hr = S_OK;
ID3D10Device* pd3dDevice = DXUTGetD3D10Device();
RECT rcCurrentClient;
GetClientRect( DXUTGetHWND(), &rcCurrentClient );
DXUTDeviceSettings* pDevSettings = GetDXUTState().GetCurrentDeviceSettings();
IDXGISwapChain* pSwapChain = DXUTGetDXGISwapChain();
// Determine if we're fullscreen
pDevSettings->d3d10.sd.Windowed = !bFullScreen;
// Call releasing
GetDXUTState().SetInsideDeviceCallback( true );
LPDXUTCALLBACKD3D10SWAPCHAINRELEASING pCallbackSwapChainReleasing = GetDXUTState().GetD3D10SwapChainReleasingFunc();
if( pCallbackSwapChainReleasing != NULL )
pCallbackSwapChainReleasing( GetDXUTState().GetD3D10SwapChainResizedFuncUserContext() );
GetDXUTState().SetInsideDeviceCallback( false );
// Release our old depth stencil texture and view
ID3D10Texture2D* pDS = GetDXUTState().GetD3D10DepthStencil();
SAFE_RELEASE( pDS );
GetDXUTState().SetD3D10DepthStencil( NULL );
ID3D10DepthStencilView* pDSV = GetDXUTState().GetD3D10DepthStencilView();
SAFE_RELEASE( pDSV );
GetDXUTState().SetD3D10DepthStencilView( NULL );
// Release our old render target view
ID3D10RenderTargetView* pRTV = GetDXUTState().GetD3D10RenderTargetView();
SAFE_RELEASE( pRTV );
GetDXUTState().SetD3D10RenderTargetView( NULL );
// Alternate between 0 and DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH when resizing buffers.
// When in windowed mode, we want 0 since this allows the app to change to the desktop
// resolution from windowed mode during alt+enter. However, in fullscreen mode, we want
// the ability to change display modes from the Device Settings dialog. Therefore, we
// want to set the DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH flag.
UINT Flags = 0;
if( bFullScreen )
Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
// ResizeBuffers
V( pSwapChain->ResizeBuffers( pDevSettings->d3d10.sd.BufferCount,
Width,
Height,
pDevSettings->d3d10.sd.BufferDesc.Format,
Flags ) );
if( !GetDXUTState().GetDoNotStoreBufferSize() )
{
pDevSettings->d3d10.sd.BufferDesc.Width = (UINT)rcCurrentClient.right;
pDevSettings->d3d10.sd.BufferDesc.Height = (UINT)rcCurrentClient.bottom;
}
// Save off backbuffer desc
DXUTUpdateBackBufferDesc();
// Update the device stats text
DXUTUpdateStaticFrameStats();
// Setup the render target view and viewport
hr = DXUTSetupD3D10Views( pd3dDevice, pDevSettings );
if( FAILED(hr) )
{
DXUT_ERR( L"DXUTSetupD3D10Views", hr );
return;
}
// Setup cursor based on current settings (window/fullscreen mode, show cursor state, clip cursor state)
DXUTSetupCursor();
// Call the app's SwapChain reset callback
GetDXUTState().SetInsideDeviceCallback( true );
const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc = DXUTGetDXGIBackBufferSurfaceDesc();
LPDXUTCALLBACKD3D10SWAPCHAINRESIZED pCallbackSwapChainResized = GetDXUTState().GetD3D10SwapChainResizedFunc();
hr = S_OK;
if( pCallbackSwapChainResized != NULL )
hr = pCallbackSwapChainResized( pd3dDevice, pSwapChain, pBackBufferSurfaceDesc, GetDXUTState().GetD3D10SwapChainResizedFuncUserContext() );
GetDXUTState().SetInsideDeviceCallback( false );
if( FAILED(hr) )
{
// If callback failed, cleanup
DXUT_ERR( L"DeviceResetCallback", hr );
if( hr != DXUTERR_MEDIANOTFOUND )
hr = DXUTERR_RESETTINGDEVICEOBJECTS;
GetDXUTState().SetInsideDeviceCallback( true );
LPDXUTCALLBACKD3D10SWAPCHAINRELEASING pCallbackSwapChainReleasing = GetDXUTState().GetD3D10SwapChainReleasingFunc();
if( pCallbackSwapChainReleasing != NULL )
pCallbackSwapChainReleasing( GetDXUTState().GetD3D10SwapChainResizedFuncUserContext() );
GetDXUTState().SetInsideDeviceCallback( false );
DXUTPause( false, false );
PostQuitMessage( 0 );
}
else
{
GetDXUTState().SetDeviceObjectsReset( true );
DXUTPause( false, false );
}
}
//--------------------------------------------------------------------------------------
// Checks if DXGI buffers need to change
//--------------------------------------------------------------------------------------
void DXUTCheckForDXGIBufferChange( )
{
if( !GetDXUTState().GetReleasingSwapChain() )
{
IDXGISwapChain* pSwapChain = DXUTGetDXGISwapChain();
// Determine if we're fullscreen
BOOL bFullScreen;
pSwapChain->GetFullscreenState( &bFullScreen, NULL );
DXUTResizeDXGIBuffers( 0, 0, bFullScreen );
ShowWindow( DXUTGetHWND(), SW_SHOW );
}
}
//--------------------------------------------------------------------------------------
// Checks if the window client rect has changed and if it has, then reset the device
//--------------------------------------------------------------------------------------
void DXUTCheckForWindowSizeChange()
{
// Skip the check for various reasons
if( GetDXUTState().GetIgnoreSizeChange() || !GetDXUTState().GetDeviceCreated() || ( DXUTIsCurrentDeviceD3D9() && !DXUTIsWindowed()) )
return;
DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings();
if( DXUTIsD3D9( &deviceSettings ) )
{
RECT rcCurrentClient;
GetClientRect( DXUTGetHWND(), &rcCurrentClient );
if( (UINT)rcCurrentClient.right != DXUTGetBackBufferWidthFromDS( &deviceSettings ) ||
(UINT)rcCurrentClient.bottom != DXUTGetBackBufferHeightFromDS( &deviceSettings ) )
{
// A new window size will require a new backbuffer size size
// Tell DXUTChangeDevice and D3D to size according to the HWND's client rect
if( DXUTIsD3D9( &deviceSettings ) ) deviceSettings.d3d9.pp.BackBufferWidth = 0; else deviceSettings.d3d10.sd.BufferDesc.Width = 0;
if( DXUTIsD3D9( &deviceSettings ) ) deviceSettings.d3d9.pp.BackBufferHeight = 0; else deviceSettings.d3d10.sd.BufferDesc.Height = 0;
DXUTChangeDevice( &deviceSettings, NULL, NULL, false, false );
}
}
else
{
DXUTCheckForDXGIBufferChange( );
}
}
//--------------------------------------------------------------------------------------
// Checks to see if the HWND changed monitors, and if it did it creates a device
// from the monitor's adapter and recreates the scene.
//--------------------------------------------------------------------------------------
void DXUTCheckForWindowChangingMonitors()
{
// Skip this check for various reasons
if( !GetDXUTState().GetAutoChangeAdapter() || GetDXUTState().GetIgnoreSizeChange() || !GetDXUTState().GetDeviceCreated() || !DXUTIsWindowed() )
return;
HRESULT hr;
HMONITOR hWindowMonitor = DXUTMonitorFromWindow( DXUTGetHWND(), MONITOR_DEFAULTTOPRIMARY );
HMONITOR hAdapterMonitor = GetDXUTState().GetAdapterMonitor();
if( hWindowMonitor != hAdapterMonitor )
{
UINT newOrdinal;
if( SUCCEEDED( DXUTGetAdapterOrdinalFromMonitor( hWindowMonitor, &newOrdinal ) ) )
{
// Find the closest valid device settings with the new ordinal
DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings();
if( DXUTIsD3D9( &deviceSettings ) )
{
deviceSettings.d3d9.AdapterOrdinal = newOrdinal;
}
else
{
deviceSettings.d3d10.AdapterOrdinal = newOrdinal;
UINT newOutput;
if( SUCCEEDED( DXUTGetOutputOrdinalFromMonitor( hWindowMonitor, &newOutput ) ) )
deviceSettings.d3d10.Output = newOutput;
}
DXUTMatchOptions matchOptions;
matchOptions.eAPIVersion = DXUTMT_PRESERVE_INPUT;
matchOptions.eAdapterOrdinal = DXUTMT_PRESERVE_INPUT;
matchOptions.eDeviceType = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eWindowed = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eAdapterFormat = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eVertexProcessing = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eResolution = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eBackBufferFormat = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eBackBufferCount = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eMultiSample = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eSwapEffect = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eDepthFormat = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eStencilFormat = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.ePresentFlags = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eRefreshRate = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.ePresentInterval = DXUTMT_CLOSEST_TO_INPUT;
hr = DXUTFindValidDeviceSettings( &deviceSettings, &deviceSettings, &matchOptions );
if( SUCCEEDED(hr) )
{
// Create a Direct3D device using the new device settings.
// If there is an existing device, then it will either reset or recreate the scene.
hr = DXUTChangeDevice( &deviceSettings, NULL, NULL, false, false );
// If hr == E_ABORT, this means the app rejected the device settings in the ModifySettingsCallback
if( hr == E_ABORT )
{
// so nothing changed and keep from attempting to switch adapters next time
GetDXUTState().SetAutoChangeAdapter( false );
}
else if( FAILED(hr) )
{
DXUTShutdown();
DXUTPause( false, false );
return;
}
}
}
}
}
//--------------------------------------------------------------------------------------
// Renders the scene using either D3D9 or D3D10
//--------------------------------------------------------------------------------------
void WINAPI DXUTRender3DEnvironment()
{
if( DXUTIsCurrentDeviceD3D9() )
DXUTRender3DEnvironment9();
else
DXUTRender3DEnvironment10();
}
//--------------------------------------------------------------------------------------
// Cleans up both the D3D9 and D3D10 3D environment (but only one should be active at a time)
//--------------------------------------------------------------------------------------
void DXUTCleanup3DEnvironment( bool bReleaseSettings )
{
if( DXUTGetD3D9Device() )
DXUTCleanup3DEnvironment9( bReleaseSettings );
if( DXUTGetD3D10Device() )
DXUTCleanup3DEnvironment10( bReleaseSettings );
}
//--------------------------------------------------------------------------------------
// Returns the HMONITOR attached to an adapter/output
//--------------------------------------------------------------------------------------
HMONITOR DXUTGetMonitorFromAdapter( DXUTDeviceSettings* pDeviceSettings )
{
if( pDeviceSettings->ver == DXUT_D3D9_DEVICE )
{
IDirect3D9* pD3D = DXUTGetD3D9Object();
return pD3D->GetAdapterMonitor( pDeviceSettings->d3d9.AdapterOrdinal );
}
else
{
CD3D10Enumeration* pD3DEnum = DXUTGetD3D10Enumeration();
CD3D10EnumOutputInfo* pOutputInfo = pD3DEnum->GetOutputInfo( pDeviceSettings->d3d10.AdapterOrdinal, pDeviceSettings->d3d10.Output );
if( !pOutputInfo )
return 0;
return DXUTMonitorFromRect( &pOutputInfo->Desc.DesktopCoordinates, MONITOR_DEFAULTTONEAREST );
}
}
//--------------------------------------------------------------------------------------
// Look for an adapter ordinal that is tied to a HMONITOR
//--------------------------------------------------------------------------------------
HRESULT DXUTGetAdapterOrdinalFromMonitor( HMONITOR hMonitor, UINT* pAdapterOrdinal )
{
*pAdapterOrdinal = 0;
if( DXUTIsCurrentDeviceD3D9() )
{
CD3D9Enumeration* pd3dEnum = DXUTGetD3D9Enumeration();
IDirect3D9* pD3D = DXUTGetD3D9Object();
CGrowableArray<CD3D9EnumAdapterInfo*>* pAdapterList = pd3dEnum->GetAdapterInfoList();
for( int iAdapter=0; iAdapter<pAdapterList->GetSize(); iAdapter++ )
{
CD3D9EnumAdapterInfo* pAdapterInfo = pAdapterList->GetAt(iAdapter);
HMONITOR hAdapterMonitor = pD3D->GetAdapterMonitor( pAdapterInfo->AdapterOrdinal );
if( hAdapterMonitor == hMonitor )
{
*pAdapterOrdinal = pAdapterInfo->AdapterOrdinal;
return S_OK;
}
}
}
else
{
// Get the monitor handle information
MONITORINFOEX mi;
mi.cbSize = sizeof(MONITORINFOEX);
DXUTGetMonitorInfo( hMonitor, &mi );
// Search for this monitor in our enumeration hierarchy.
CD3D10Enumeration* pd3dEnum = DXUTGetD3D10Enumeration();
CGrowableArray<CD3D10EnumAdapterInfo*>* pAdapterList = pd3dEnum->GetAdapterInfoList();
for( int iAdapter=0; iAdapter<pAdapterList->GetSize(); ++iAdapter )
{
CD3D10EnumAdapterInfo* pAdapterInfo = pAdapterList->GetAt( iAdapter );
for( int o = 0; o < pAdapterInfo->outputInfoList.GetSize(); ++o )
{
CD3D10EnumOutputInfo* pOutputInfo = pAdapterInfo->outputInfoList.GetAt( o );
// Convert output device name from MBCS to Unicode
if( wcsncmp( pOutputInfo->Desc.DeviceName, mi.szDevice, sizeof(mi.szDevice) / sizeof(mi.szDevice[0]) ) == 0 )
{
*pAdapterOrdinal = pAdapterInfo->AdapterOrdinal;
return S_OK;
}
}
}
}
return E_FAIL;
}
//--------------------------------------------------------------------------------------
// Look for a monitor ordinal that is tied to a HMONITOR (D3D10-only)
//--------------------------------------------------------------------------------------
HRESULT DXUTGetOutputOrdinalFromMonitor( HMONITOR hMonitor, UINT* pOutputOrdinal )
{
// Get the monitor handle information
MONITORINFOEX mi;
mi.cbSize = sizeof(MONITORINFOEX);
DXUTGetMonitorInfo( hMonitor, &mi );
// Search for this monitor in our enumeration hierarchy.
CD3D10Enumeration* pd3dEnum = DXUTGetD3D10Enumeration();
CGrowableArray<CD3D10EnumAdapterInfo*>* pAdapterList = pd3dEnum->GetAdapterInfoList();
for( int iAdapter=0; iAdapter<pAdapterList->GetSize(); ++iAdapter )
{
CD3D10EnumAdapterInfo* pAdapterInfo = pAdapterList->GetAt( iAdapter );
for( int o = 0; o < pAdapterInfo->outputInfoList.GetSize(); ++o )
{
CD3D10EnumOutputInfo* pOutputInfo = pAdapterInfo->outputInfoList.GetAt( o );
DXGI_OUTPUT_DESC Desc;
pOutputInfo->m_pOutput->GetDesc( &Desc );
if( hMonitor == Desc.Monitor )
{
*pOutputOrdinal = pOutputInfo->Output;
return S_OK;
}
}
}
return E_FAIL;
}
//--------------------------------------------------------------------------------------
// This method is called when D3DERR_DEVICEREMOVED is returned from an API. DXUT
// calls the application's DeviceRemoved callback to inform it of the event. The
// application returns true if it wants DXUT to look for a closest device to run on.
// If no device is found, or the app returns false, DXUT shuts down.
//--------------------------------------------------------------------------------------
HRESULT DXUTHandleDeviceRemoved()
{
HRESULT hr = S_OK;
// Device has been removed. Call the application's callback if set. If no callback
// has been set, then just look for a new device
bool bLookForNewDevice = true;
LPDXUTCALLBACKDEVICEREMOVED pDeviceRemovedFunc = GetDXUTState().GetDeviceRemovedFunc();
if( pDeviceRemovedFunc )
bLookForNewDevice = pDeviceRemovedFunc( GetDXUTState().GetDeviceRemovedFuncUserContext() );
if( bLookForNewDevice )
{
DXUTDeviceSettings *pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings();
DXUTMatchOptions matchOptions;
matchOptions.eAPIVersion = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eAdapterOrdinal = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eDeviceType = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eWindowed = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eAdapterFormat = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eVertexProcessing = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eResolution = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eBackBufferFormat = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eBackBufferCount = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eMultiSample = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eSwapEffect = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eDepthFormat = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eStencilFormat = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.ePresentFlags = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.eRefreshRate = DXUTMT_CLOSEST_TO_INPUT;
matchOptions.ePresentInterval = DXUTMT_CLOSEST_TO_INPUT;
hr = DXUTFindValidDeviceSettings( pDeviceSettings, pDeviceSettings, &matchOptions );
if( SUCCEEDED( hr ) )
{
// Change to a Direct3D device created from the new device settings
// that is compatible with the removed device.
hr = DXUTChangeDevice( pDeviceSettings, NULL, NULL, true, false );
if( SUCCEEDED( hr ) )
return S_OK;
}
}
// The app does not wish to continue or continuing is not possible.
return DXUTERR_DEVICEREMOVED;
}
//--------------------------------------------------------------------------------------
// Stores back buffer surface desc in GetDXUTState().GetBackBufferSurfaceDesc10()
//--------------------------------------------------------------------------------------
void DXUTUpdateBackBufferDesc()
{
if( DXUTIsCurrentDeviceD3D9() )
{
HRESULT hr;
IDirect3DSurface9* pBackBuffer;
hr = GetDXUTState().GetD3D9Device()->GetBackBuffer( 0, 0, D3DBACKBUFFER_TYPE_MONO, &pBackBuffer );
D3DSURFACE_DESC* pBBufferSurfaceDesc = GetDXUTState().GetBackBufferSurfaceDesc9();
ZeroMemory( pBBufferSurfaceDesc, sizeof(D3DSURFACE_DESC) );
if( SUCCEEDED(hr) )
{
pBackBuffer->GetDesc( pBBufferSurfaceDesc );
SAFE_RELEASE( pBackBuffer );
}
}
else
{
HRESULT hr;
ID3D10Texture2D* pBackBuffer;
hr = GetDXUTState().GetD3D10SwapChain()->GetBuffer( 0, __uuidof(*pBackBuffer), (LPVOID*)&pBackBuffer );
DXGI_SURFACE_DESC* pBBufferSurfaceDesc = GetDXUTState().GetBackBufferSurfaceDesc10();
ZeroMemory( pBBufferSurfaceDesc, sizeof(DXGI_SURFACE_DESC) );
if( SUCCEEDED(hr) )
{
D3D10_TEXTURE2D_DESC TexDesc;
pBackBuffer->GetDesc( &TexDesc );
pBBufferSurfaceDesc->Width = (UINT) TexDesc.Width;
pBBufferSurfaceDesc->Height = (UINT) TexDesc.Height;
pBBufferSurfaceDesc->Format = TexDesc.Format;
pBBufferSurfaceDesc->SampleDesc = TexDesc.SampleDesc;
SAFE_RELEASE( pBackBuffer );
}
}
}
//--------------------------------------------------------------------------------------
// Setup cursor based on current settings (window/fullscreen mode, show cursor state, clip cursor state)
//--------------------------------------------------------------------------------------
void DXUTSetupCursor()
{
if( DXUTIsCurrentDeviceD3D9() )
{
// Show the cursor again if returning to fullscreen
IDirect3DDevice9* pd3dDevice = DXUTGetD3D9Device();
if( !DXUTIsWindowed() && pd3dDevice )
{
if( GetDXUTState().GetShowCursorWhenFullScreen() )
{
SetCursor( NULL ); // Turn off Windows cursor in full screen mode
HCURSOR hCursor = (HCURSOR)(ULONG_PTR)GetClassLongPtr( DXUTGetHWNDDeviceFullScreen(), GCLP_HCURSOR );
DXUTSetD3D9DeviceCursor( pd3dDevice, hCursor, false );
DXUTGetD3D9Device()->ShowCursor( true );
}
else
{
SetCursor( NULL ); // Turn off Windows cursor in full screen mode
DXUTGetD3D9Device()->ShowCursor( false );
}
}
// Clip cursor if requested
if( !DXUTIsWindowed() && GetDXUTState().GetClipCursorWhenFullScreen() )
{
// Confine cursor to full screen window
RECT rcWindow;
GetWindowRect( DXUTGetHWNDDeviceFullScreen(), &rcWindow );
ClipCursor( &rcWindow );
}
else
{
ClipCursor( NULL );
}
}
else
{
// Clip cursor if requested
if( !DXUTIsWindowed() && GetDXUTState().GetClipCursorWhenFullScreen() )
{
// Confine cursor to full screen window
RECT rcWindow;
GetWindowRect( DXUTGetHWNDDeviceFullScreen(), &rcWindow );
ClipCursor( &rcWindow );
}
else
{
ClipCursor( NULL );
}
}
}
//--------------------------------------------------------------------------------------
// Updates the static part of the frame stats so it doesn't have be generated every frame
//--------------------------------------------------------------------------------------
void DXUTUpdateStaticFrameStats()
{
if( GetDXUTState().GetNoStats() )
return;
DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings();
if( NULL == pDeviceSettings )
return;
if( DXUTIsD3D9( pDeviceSettings ) )
{
CD3D9Enumeration* pd3dEnum = DXUTGetD3D9Enumeration();
if( NULL == pd3dEnum )
return;
CD3D9EnumDeviceSettingsCombo* pDeviceSettingsCombo = pd3dEnum->GetDeviceSettingsCombo( pDeviceSettings->d3d9.AdapterOrdinal, pDeviceSettings->d3d9.DeviceType, pDeviceSettings->d3d9.AdapterFormat, pDeviceSettings->d3d9.pp.BackBufferFormat, pDeviceSettings->d3d9.pp.Windowed );
if( NULL == pDeviceSettingsCombo )
return;
WCHAR strFmt[100];
D3DPRESENT_PARAMETERS* pPP = &pDeviceSettings->d3d9.pp;
if( pDeviceSettingsCombo->AdapterFormat == pDeviceSettingsCombo->BackBufferFormat )
{
StringCchCopy( strFmt, 100, DXUTD3DFormatToString( pDeviceSettingsCombo->AdapterFormat, false ) );
}
else
{
StringCchPrintf( strFmt, 100, L"backbuf %s, adapter %s",
DXUTD3DFormatToString( pDeviceSettingsCombo->BackBufferFormat, false ),
DXUTD3DFormatToString( pDeviceSettingsCombo->AdapterFormat, false ) );
}
WCHAR strDepthFmt[100];
if( pPP->EnableAutoDepthStencil )
{
StringCchPrintf( strDepthFmt, 100, L" (%s)", DXUTD3DFormatToString( pPP->AutoDepthStencilFormat, false ) );
}
else
{
// No depth buffer
strDepthFmt[0] = 0;
}
WCHAR strMultiSample[100];
switch( pPP->MultiSampleType )
{
case D3DMULTISAMPLE_NONMASKABLE: StringCchCopy( strMultiSample, 100, L" (Nonmaskable Multisample)" ); break;
case D3DMULTISAMPLE_NONE: StringCchCopy( strMultiSample, 100, L"" ); break;
default: StringCchPrintf( strMultiSample, 100, L" (%dx Multisample)", pPP->MultiSampleType ); break;
}
WCHAR* pstrStaticFrameStats = GetDXUTState().GetStaticFrameStats();
StringCchPrintf( pstrStaticFrameStats, 256, L"D3D9 %%sVsync %s (%dx%d), %s%s%s",
( pPP->PresentationInterval == D3DPRESENT_INTERVAL_IMMEDIATE ) ? L"off" : L"on",
pPP->BackBufferWidth, pPP->BackBufferHeight,
strFmt, strDepthFmt, strMultiSample );
}
else
{
// D3D10
CD3D10Enumeration* pd3dEnum = DXUTGetD3D10Enumeration();
if( NULL == pd3dEnum )
return;
CD3D10EnumDeviceSettingsCombo* pDeviceSettingsCombo = pd3dEnum->GetDeviceSettingsCombo( pDeviceSettings->d3d10.AdapterOrdinal, pDeviceSettings->d3d10.DriverType, pDeviceSettings->d3d10.Output, pDeviceSettings->d3d10.sd.BufferDesc.Format, pDeviceSettings->d3d10.sd.Windowed );
if( NULL == pDeviceSettingsCombo )
return;
WCHAR strFmt[100];
StringCchCopy( strFmt, 100, DXUTDXGIFormatToString( pDeviceSettingsCombo->BackBufferFormat, false ) );
WCHAR strMultiSample[100];
StringCchPrintf( strMultiSample, 100, L" (MS%u, Q%u)", pDeviceSettings->d3d10.sd.SampleDesc.Count, pDeviceSettings->d3d10.sd.SampleDesc.Quality );
WCHAR* pstrStaticFrameStats = GetDXUTState().GetStaticFrameStats();
StringCchPrintf( pstrStaticFrameStats, 256, L"D3D10 %%sVsync %s (%dx%d), %s%s",
( pDeviceSettings->d3d10.SyncInterval == 0 ) ? L"off" : L"on",
pDeviceSettings->d3d10.sd.BufferDesc.Width, pDeviceSettings->d3d10.sd.BufferDesc.Height,
strFmt, strMultiSample );
}
}
//--------------------------------------------------------------------------------------
// Updates the frames/sec stat once per second
//--------------------------------------------------------------------------------------
void DXUTUpdateFrameStats()
{
if( GetDXUTState().GetNoStats() )
return;
// Keep track of the frame count
double fLastTime = GetDXUTState().GetLastStatsUpdateTime();
DWORD dwFrames = GetDXUTState().GetLastStatsUpdateFrames();
double fAbsTime = GetDXUTState().GetAbsoluteTime();
dwFrames++;
GetDXUTState().SetLastStatsUpdateFrames( dwFrames );
// Update the scene stats once per second
if( fAbsTime - fLastTime > 1.0f )
{
float fFPS = (float) (dwFrames / (fAbsTime - fLastTime));
GetDXUTState().SetFPS( fFPS );
GetDXUTState().SetLastStatsUpdateTime( fAbsTime );
GetDXUTState().SetLastStatsUpdateFrames( 0 );
WCHAR* pstrFPS = GetDXUTState().GetFPSStats();
StringCchPrintf( pstrFPS, 64, L"%0.2f fps ", fFPS );
}
}
//--------------------------------------------------------------------------------------
// Returns a string describing the current device. If bShowFPS is true, then
// the string contains the frames/sec. If "-nostats" was used in
// the command line, the string will be blank
//--------------------------------------------------------------------------------------
LPCWSTR WINAPI DXUTGetFrameStats( bool bShowFPS )
{
WCHAR* pstrFrameStats = GetDXUTState().GetFrameStats();
WCHAR* pstrFPS = ( bShowFPS ) ? GetDXUTState().GetFPSStats() : L"";
StringCchPrintf( pstrFrameStats, 256, GetDXUTState().GetStaticFrameStats(), pstrFPS );
return pstrFrameStats;
}
//--------------------------------------------------------------------------------------
// Updates the string which describes the device
//--------------------------------------------------------------------------------------
void DXUTUpdateD3D9DeviceStats( D3DDEVTYPE DeviceType, DWORD BehaviorFlags, D3DADAPTER_IDENTIFIER9* pAdapterIdentifier )
{
if( GetDXUTState().GetNoStats() )
return;
// Store device description
WCHAR* pstrDeviceStats = GetDXUTState().GetDeviceStats();
if( DeviceType == D3DDEVTYPE_REF )
StringCchCopy( pstrDeviceStats, 256, L"REF" );
else if( DeviceType == D3DDEVTYPE_HAL )
StringCchCopy( pstrDeviceStats, 256, L"HAL" );
else if( DeviceType == D3DDEVTYPE_SW )
StringCchCopy( pstrDeviceStats, 256, L"SW" );
if( BehaviorFlags & D3DCREATE_HARDWARE_VERTEXPROCESSING &&
BehaviorFlags & D3DCREATE_PUREDEVICE )
{
if( DeviceType == D3DDEVTYPE_HAL )
StringCchCat( pstrDeviceStats, 256, L" (pure hw vp)" );
else
StringCchCat( pstrDeviceStats, 256, L" (simulated pure hw vp)" );
}
else if( BehaviorFlags & D3DCREATE_HARDWARE_VERTEXPROCESSING )
{
if( DeviceType == D3DDEVTYPE_HAL )
StringCchCat( pstrDeviceStats, 256, L" (hw vp)" );
else
StringCchCat( pstrDeviceStats, 256, L" (simulated hw vp)" );
}
else if( BehaviorFlags & D3DCREATE_MIXED_VERTEXPROCESSING )
{
if( DeviceType == D3DDEVTYPE_HAL )
StringCchCat( pstrDeviceStats, 256, L" (mixed vp)" );
else
StringCchCat( pstrDeviceStats, 256, L" (simulated mixed vp)" );
}
else if( BehaviorFlags & D3DCREATE_SOFTWARE_VERTEXPROCESSING )
{
StringCchCat( pstrDeviceStats, 256, L" (sw vp)" );
}
if( DeviceType == D3DDEVTYPE_HAL )
{
// Be sure not to overflow m_strDeviceStats when appending the adapter
// description, since it can be long.
StringCchCat( pstrDeviceStats, 256, L": " );
// Try to get a unique description from the CD3D9EnumDeviceSettingsCombo
DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings();
if( !pDeviceSettings )
return;
CD3D9Enumeration* pd3dEnum = DXUTGetD3D9Enumeration();
CD3D9EnumDeviceSettingsCombo* pDeviceSettingsCombo = pd3dEnum->GetDeviceSettingsCombo( pDeviceSettings->d3d9.AdapterOrdinal, pDeviceSettings->d3d9.DeviceType, pDeviceSettings->d3d9.AdapterFormat, pDeviceSettings->d3d9.pp.BackBufferFormat, pDeviceSettings->d3d9.pp.Windowed );
if( pDeviceSettingsCombo )
{
StringCchCat( pstrDeviceStats, 256, pDeviceSettingsCombo->pAdapterInfo->szUniqueDescription );
}
else
{
const int cchDesc = sizeof(pAdapterIdentifier->Description);
WCHAR szDescription[cchDesc];
MultiByteToWideChar( CP_ACP, 0, pAdapterIdentifier->Description, -1, szDescription, cchDesc );
szDescription[cchDesc-1] = 0;
StringCchCat( pstrDeviceStats, 256, szDescription );
}
}
}
//--------------------------------------------------------------------------------------
// Updates the string which describes the device
//--------------------------------------------------------------------------------------
void DXUTUpdateD3D10DeviceStats( D3D10_DRIVER_TYPE DeviceType, DXGI_ADAPTER_DESC* pAdapterDesc )
{
if( GetDXUTState().GetNoStats() )
return;
// Store device description
WCHAR* pstrDeviceStats = GetDXUTState().GetDeviceStats();
if( DeviceType == D3D10_DRIVER_TYPE_REFERENCE )
StringCchCopy( pstrDeviceStats, 256, L"REFERENCE" );
else if( DeviceType == D3D10_DRIVER_TYPE_HARDWARE )
StringCchCopy( pstrDeviceStats, 256, L"HARDWARE" );
else if( DeviceType == D3D10_DRIVER_TYPE_SOFTWARE )
StringCchCopy( pstrDeviceStats, 256, L"SOFTWARE" );
if( DeviceType == D3D10_DRIVER_TYPE_HARDWARE )
{
// Be sure not to overflow m_strDeviceStats when appending the adapter
// description, since it can be long.
StringCchCat( pstrDeviceStats, 256, L": " );
// Try to get a unique description from the CD3D10EnumDeviceSettingsCombo
DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings();
if( !pDeviceSettings )
return;
CD3D10Enumeration* pd3dEnum = DXUTGetD3D10Enumeration();
CD3D10EnumDeviceSettingsCombo* pDeviceSettingsCombo = pd3dEnum->GetDeviceSettingsCombo( pDeviceSettings->d3d10.AdapterOrdinal, pDeviceSettings->d3d10.DriverType, pDeviceSettings->d3d10.Output, pDeviceSettings->d3d10.sd.BufferDesc.Format, pDeviceSettings->d3d10.sd.Windowed );
if( pDeviceSettingsCombo )
StringCchCat( pstrDeviceStats, 256, pDeviceSettingsCombo->pAdapterInfo->szUniqueDescription );
else
StringCchCat( pstrDeviceStats, 256, pAdapterDesc->Description );
}
}
//--------------------------------------------------------------------------------------
// Misc functions
//--------------------------------------------------------------------------------------
DXUTDeviceSettings WINAPI DXUTGetDeviceSettings()
{
// Return a copy of device settings of the current device. If no device exists yet, then
// return a blank device settings struct
DXUTDeviceSettings* pDS = GetDXUTState().GetCurrentDeviceSettings();
if( pDS )
{
return *pDS;
}
else
{
DXUTDeviceSettings ds;
ZeroMemory( &ds, sizeof(DXUTDeviceSettings) );
return ds;
}
}
D3DPRESENT_PARAMETERS WINAPI DXUTGetD3D9PresentParameters()
{
// Return a copy of the present params of the current device. If no device exists yet, then
// return blank present params
DXUTDeviceSettings* pDS = GetDXUTState().GetCurrentDeviceSettings();
if( pDS )
{
return pDS->d3d9.pp;
}
else
{
D3DPRESENT_PARAMETERS pp;
ZeroMemory( &pp, sizeof(D3DPRESENT_PARAMETERS) );
return pp;
}
}
bool WINAPI DXUTIsVsyncEnabled()
{
DXUTDeviceSettings* pDS = GetDXUTState().GetCurrentDeviceSettings();
if( pDS )
{
if( DXUTIsD3D9( pDS ) )
return ( pDS->d3d9.pp.PresentationInterval == D3DPRESENT_INTERVAL_IMMEDIATE );
else
return ( pDS->d3d10.SyncInterval == 0 );
}
else
{
return true;
}
};
HRESULT WINAPI DXUTGetD3D9DeviceCaps( DXUTDeviceSettings* pDeviceSettings, D3DCAPS9* pCaps )
{
IDirect3D9* pD3D = DXUTGetD3D9Object();
return pD3D->GetDeviceCaps( pDeviceSettings->d3d9.AdapterOrdinal, pDeviceSettings->d3d9.DeviceType, pCaps );
}
bool WINAPI DXUTIsKeyDown( BYTE vKey )
{
bool* bKeys = GetDXUTState().GetKeys();
if( vKey >= 0xA0 && vKey <= 0xA5 ) // VK_LSHIFT, VK_RSHIFT, VK_LCONTROL, VK_RCONTROL, VK_LMENU, VK_RMENU
return GetAsyncKeyState( vKey ) != 0; // these keys only are tracked via GetAsyncKeyState()
else if( vKey >= 0x01 && vKey <= 0x06 && vKey != 0x03 ) // mouse buttons (VK_*BUTTON)
return DXUTIsMouseButtonDown(vKey);
else
return bKeys[vKey];
}
bool WINAPI DXUTWasKeyPressed( BYTE vKey )
{
bool* bLastKeys = GetDXUTState().GetLastKeys();
bool* bKeys = GetDXUTState().GetKeys();
GetDXUTState().SetAppCalledWasKeyPressed( true );
return ( !bLastKeys[vKey] && bKeys[vKey] );
}
bool WINAPI DXUTIsMouseButtonDown( BYTE vButton )
{
bool* bMouseButtons = GetDXUTState().GetMouseButtons();
int nIndex = DXUTMapButtonToArrayIndex(vButton);
return bMouseButtons[nIndex];
}
void WINAPI DXUTSetMultimonSettings( bool bAutoChangeAdapter )
{
GetDXUTState().SetAutoChangeAdapter( bAutoChangeAdapter );
}
void WINAPI DXUTSetHotkeyHandling( bool bAltEnterToToggleFullscreen, bool bEscapeToQuit, bool bPauseToToggleTimePause )
{
GetDXUTState().SetHandleEscape( bEscapeToQuit );
GetDXUTState().SetHandleAltEnter( bAltEnterToToggleFullscreen );
GetDXUTState().SetHandlePause( bPauseToToggleTimePause );
}
void WINAPI DXUTSetCursorSettings( bool bShowCursorWhenFullScreen, bool bClipCursorWhenFullScreen )
{
GetDXUTState().SetClipCursorWhenFullScreen(bClipCursorWhenFullScreen);
GetDXUTState().SetShowCursorWhenFullScreen(bShowCursorWhenFullScreen);
DXUTSetupCursor();
}
void WINAPI DXUTSetWindowSettings( bool bCallDefWindowProc )
{
GetDXUTState().SetCallDefWindowProc( bCallDefWindowProc );
}
void WINAPI DXUTSetConstantFrameTime( bool bEnabled, float fTimePerFrame )
{
if( GetDXUTState().GetOverrideConstantFrameTime() )
{
bEnabled = GetDXUTState().GetOverrideConstantFrameTime();
fTimePerFrame = GetDXUTState().GetOverrideConstantTimePerFrame();
}
GetDXUTState().SetConstantFrameTime(bEnabled);
GetDXUTState().SetTimePerFrame(fTimePerFrame);
}
//--------------------------------------------------------------------------------------
// Resets the state associated with DXUT
//--------------------------------------------------------------------------------------
void WINAPI DXUTResetFrameworkState()
{
GetDXUTState().Destroy();
GetDXUTState().Create();
}
//--------------------------------------------------------------------------------------
// Closes down the window. When the window closes, it will cleanup everything
//--------------------------------------------------------------------------------------
void WINAPI DXUTShutdown( int nExitCode )
{
HWND hWnd = DXUTGetHWND();
if( hWnd != NULL )
SendMessage( hWnd, WM_CLOSE, 0, 0 );
GetDXUTState().SetExitCode(nExitCode);
DXUTCleanup3DEnvironment( true );
// Restore shortcut keys (Windows key, accessibility shortcuts) to original state
// This is important to call here if the shortcuts are disabled,
// because accessibility setting changes are permanent.
// This means that if this is not done then the accessibility settings
// might not be the same as when the app was started.
// If the app crashes without restoring the settings, this is also true so it
// would be wise to backup/restore the settings from a file so they can be
// restored when the crashed app is run again.
DXUTAllowShortcutKeys( true );
// Shutdown D3D9
IDirect3D9* pD3D = GetDXUTState().GetD3D9();
SAFE_RELEASE( pD3D );
GetDXUTState().SetD3D9( NULL );
// Shutdown D3D10
IDXGIFactory* pDXGIFactory = GetDXUTState().GetDXGIFactory();
SAFE_RELEASE( pDXGIFactory );
GetDXUTState().SetDXGIFactory( NULL );
if( GetDXUTState().GetOverrideRelaunchMCE() )
DXUTReLaunchMediaCenter();
}
//--------------------------------------------------------------------------------------
// Tells DXUT whether to operate in gamma correct mode
//--------------------------------------------------------------------------------------
void WINAPI DXUTSetIsInGammaCorrectMode( bool bGammaCorrect )
{
GetDXUTState().SetIsInGammaCorrectMode( bGammaCorrect );
}
| [
"[email protected]"
]
| [
[
[
1,
6190
]
]
]
|
af273a520017891927e5f3c8ea903ef1592be368 | 854ee643a4e4d0b7a202fce237ee76b6930315ec | /arcemu_svn/src/sun/src/InstanceScripts/Raid_SerpentshrineCavern.cpp | 68b4cebcfce03c3fbfc2ea987c93947a1cd47773 | []
| no_license | miklasiak/projekt | df37fa82cf2d4a91c2073f41609bec8b2f23cf66 | 064402da950555bf88609e98b7256d4dc0af248a | refs/heads/master | 2021-01-01T19:29:49.778109 | 2008-11-10T17:14:14 | 2008-11-10T17:14:14 | 34,016,391 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 92,332 | cpp | /*
* Moon++ Scripts for Ascent MMORPG Server
* Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2007-2008 Moon++ Team <http://www.moonplusplus.info/>
* Copyright (C) 2008 Sun++ Team <http://www.sunplusplus.info/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "StdAfx.h"
#include "Setup.h"
#include "Base.h"
/************************************************************************/
/* Raid_SerpentshrineCavern.cpp Script */
/************************************************************************/
#ifdef WIN32
#pragma warning(disable:4146) //warning C4146: unary minus operator applied to unsigned type, result still unsigned
#endif
#define SP_SCALDING_WATER 37284 //This "dot" is supposed to tick whenever you get in the water, it doesnt tick anymore after u kill lurker.
//------------------------------------
// -= Hydross the Unstable =-
//------------------------------------
#define CN_HYDROSS_THE_UNSTABLE 21216
#define CN_TAINTED_SPAWN_OF_HYDROSS 22036
#define CN_PURE_SPAWN_OF_HYDROSS 22035
#define WATER_TOMB 38235
#define VILE_SLUDGE 38246
#define MARK_OF_HYDROSS1 38215
#define MARK_OF_HYDROSS2 38216
#define MARK_OF_HYDROSS3 38217
#define MARK_OF_HYDROSS4 38218
#define MARK_OF_HYDROSS5 38231
#define MARK_OF_HYDROSS6 40584
#define MARK_OF_CORRUPTION1 38219
#define MARK_OF_CORRUPTION2 38220
#define MARK_OF_CORRUPTION3 38221
#define MARK_OF_CORRUPTION4 38222
#define MARK_OF_CORRUPTION5 38230
#define MARK_OF_CORRUPTION6 40583
#define HYDROSS_ENRAGE 13048
#define PURIFY_ELEMENTAL 36461
class HydrossTheUnstableAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(HydrossTheUnstableAI);
SP_AI_Spell spells[2];
bool m_spellcheck[2];
HydrossTheUnstableAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
nrspells = 2;
spells[0].info = dbcSpell.LookupEntry(WATER_TOMB);
spells[0].targettype = TARGET_RANDOM_SINGLE;
spells[0].instant = true;
spells[0].cooldown = 7;
spells[0].attackstoptimer = 1000;
m_spellcheck[0] = false;
spells[1].info = dbcSpell.LookupEntry(VILE_SLUDGE);
spells[1].targettype = TARGET_RANDOM_SINGLE;
spells[1].instant = true;
spells[1].cooldown = 15;
spells[1].attackstoptimer = 1000;
m_spellcheck[1] = false;
//frost attack type
_unit->GetProto()->AttackType = 4;
//frost immunity
_unit->SchoolImmunityList[SCHOOL_FROST] = 1;
}
void ResetCastTime()
{
for (int i = 0; i < nrspells; i++)
spells[i].casttime = spells[i].cooldown;
}
void OnCombatStart(Unit* mTarget)
{
ResetCastTime();
MarkCount = 0;
form = false;
MarkTimer = 10;
minspell = 0;
maxspell = 0;
Enraged = false;
EnrageTimer = 600;
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "I cannot allow you to interfere!");
_unit->PlaySoundToSet(11289);
RegisterAIUpdateEvent(1000);
}
void OnCombatStop(Unit *mTarget)
{
_unit->SetUInt32Value(UNIT_FIELD_DISPLAYID, 20162);
_unit->SchoolImmunityList[SCHOOL_FROST] = 1;
_unit->SchoolImmunityList[SCHOOL_NATURE] = 0;
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
}
void OnTargetDied(Unit* mTarget)
{
if(_unit->GetHealthPct() > 0)
{
if(!form)
{
switch(rand()%2)
{
case 0:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "They have forced me to this...");
_unit->PlaySoundToSet(11291);
break;
case 1:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "I have no choice.");
_unit->PlaySoundToSet(11292);
break;
}
}
else
{
switch(rand()%2)
{
case 0:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "I will purge you from this place.");
_unit->PlaySoundToSet(11298);
break;
case 1:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "You are no better than they!");
_unit->PlaySoundToSet(11299);
break;
}
}
}
}
void OnDied(Unit * mKiller)
{
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "You are the disease, not I.");
_unit->PlaySoundToSet(11300);
RemoveAIUpdateEvent();
}
void AIUpdate()
{
if(!form) //water form
{
//Mark of Hydross
if(MarkCount < 6)
{
MarkTimer--;
if(!MarkTimer)
{
uint32 spellid = 0;
switch(MarkCount)
{
case 0:
_unit->CastSpell(_unit, dbcSpell.LookupEntry(MARK_OF_HYDROSS1), true);
break;
case 1:
_unit->CastSpell(_unit, dbcSpell.LookupEntry(MARK_OF_HYDROSS2), true);
break;
case 2:
_unit->CastSpell(_unit, dbcSpell.LookupEntry(MARK_OF_HYDROSS3), true);
break;
case 3:
_unit->CastSpell(_unit, dbcSpell.LookupEntry(MARK_OF_HYDROSS4), true);
break;
case 4:
_unit->CastSpell(_unit, dbcSpell.LookupEntry(MARK_OF_HYDROSS5), true);
break;
case 5:
_unit->CastSpell(_unit, dbcSpell.LookupEntry(MARK_OF_HYDROSS6), true);
break;
}
MarkCount++;
MarkTimer = 20;
}
}
//Switch check
float distx = _unit->GetSpawnX() - _unit->GetPositionX();
float disty = _unit->GetSpawnY() - _unit->GetPositionY();
float dist = sqrt( (distx*distx) + (disty*disty) );
if(dist > 25)
{
//switch to poison form
MarkTimer = 10;
MarkCount = 0;
minspell = 1;
maxspell = 1;
form = true;
_unit->SetUInt32Value(UNIT_FIELD_DISPLAYID, 5498);
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Aaghh, the poison...");
_unit->PlaySoundToSet(11297);
_unit->GetProto()->AttackType = 3;
_unit->SchoolImmunityList[SCHOOL_FROST] = 0;
_unit->SchoolImmunityList[SCHOOL_NATURE] = 1;
//Summon 4 elementals
Creature * summon;
float posx = _unit->GetPositionX();
float posy = _unit->GetPositionY();
float posz = _unit->GetPositionZ();
float orientation = _unit->GetOrientation();
summon = _unit->GetMapMgr()->GetInterface()->SpawnCreature(CN_TAINTED_SPAWN_OF_HYDROSS,
posx+6.93f, posy-11.25f, posz, orientation,
false, false, 0, 0);
if(summon) summon->SchoolImmunityList[SCHOOL_NATURE] = 1;
summon = _unit->GetMapMgr()->GetInterface()->SpawnCreature(CN_TAINTED_SPAWN_OF_HYDROSS,
posx-6.93f, posy+11.25f, posz, orientation,
false, false, 0, 0);
if(summon) summon->SchoolImmunityList[SCHOOL_NATURE] = 1;
summon = _unit->GetMapMgr()->GetInterface()->SpawnCreature(CN_TAINTED_SPAWN_OF_HYDROSS,
posx-12.57f, posy-4.72f, posz, orientation,
false, false, 0, 0);
if(summon) summon->SchoolImmunityList[SCHOOL_NATURE] = 1;
summon = _unit->GetMapMgr()->GetInterface()->SpawnCreature(CN_TAINTED_SPAWN_OF_HYDROSS,
posx+12.57f, posy+4.72f, posz, orientation,
false, false, 0, 0);
if(summon) summon->SchoolImmunityList[SCHOOL_NATURE] = 1;
}
}
else //poison form
{
//Mark of Corruption
if(MarkCount < 6)
{
MarkTimer--;
if(!MarkTimer)
{
uint32 spellid = 0;
switch(MarkCount)
{
case 0:
_unit->CastSpell(_unit, dbcSpell.LookupEntry(MARK_OF_CORRUPTION1), true);
break;
case 1:
_unit->CastSpell(_unit, dbcSpell.LookupEntry(MARK_OF_CORRUPTION2), true);
break;
case 2:
_unit->CastSpell(_unit, dbcSpell.LookupEntry(MARK_OF_CORRUPTION3), true);
break;
case 3:
_unit->CastSpell(_unit, dbcSpell.LookupEntry(MARK_OF_CORRUPTION4), true);
break;
case 4:
_unit->CastSpell(_unit, dbcSpell.LookupEntry(MARK_OF_CORRUPTION5), true);
break;
case 5:
_unit->CastSpell(_unit, dbcSpell.LookupEntry(MARK_OF_CORRUPTION6), true);
break;
}
MarkCount++;
MarkTimer = 20;
}
}
//Switch check
float distx = _unit->GetSpawnX() - _unit->GetPositionX();
float disty = _unit->GetSpawnY() - _unit->GetPositionY();
float dist = sqrt( (distx*distx) + (disty*disty) );
if(dist < 25)
{
//switch to water form
MarkTimer = 10;
MarkCount = 0;
minspell = 0;
maxspell = 0;
form = false;
_unit->SetUInt32Value(UNIT_FIELD_DISPLAYID, 20162);
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Better, much better.");
_unit->PlaySoundToSet(11290);
_unit->GetProto()->AttackType = 4;
_unit->SchoolImmunityList[SCHOOL_FROST] = 1;
_unit->SchoolImmunityList[SCHOOL_NATURE] = 0;
//Summon 4 elementals
Creature * summon;
float posx = _unit->GetPositionX();
float posy = _unit->GetPositionY();
float posz = _unit->GetPositionZ();
float orientation = _unit->GetOrientation();
summon = _unit->GetMapMgr()->GetInterface()->SpawnCreature(CN_PURE_SPAWN_OF_HYDROSS,
posx+6.93f, posy-11.25f, posz, orientation,
false, false, 0, 0);
if(summon) summon->SchoolImmunityList[SCHOOL_FROST] = 1;
summon = _unit->GetMapMgr()->GetInterface()->SpawnCreature(CN_PURE_SPAWN_OF_HYDROSS,
posx-6.93f, posy+11.25f, posz, orientation,
false, false, 0, 0);
if(summon) summon->SchoolImmunityList[SCHOOL_FROST] = 1;
summon = _unit->GetMapMgr()->GetInterface()->SpawnCreature(CN_PURE_SPAWN_OF_HYDROSS,
posx-12.57f, posy-4.72f, posz, orientation,
false, false, 0, 0);
if(summon) summon->SchoolImmunityList[SCHOOL_FROST] = 1;
summon = _unit->GetMapMgr()->GetInterface()->SpawnCreature(CN_PURE_SPAWN_OF_HYDROSS,
posx+12.57f, posy+4.72f, posz, orientation,
false, false, 0, 0);
if(summon) summon->SchoolImmunityList[SCHOOL_FROST] = 1;
}
}
//Enrage
if(!Enraged)
{
EnrageTimer--;
if(!EnrageTimer)
{
_unit->CastSpell(_unit, dbcSpell.LookupEntry(HYDROSS_ENRAGE), true);
Enraged = true;
}
}
float val = (float)RandomFloat(100.0f);
SpellCast(val);
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i = minspell; i <= maxspell; i++)
{
if(m_spellcheck[i])
{
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant); break;
case TARGET_ATTACKING:
_unit->CastSpell(target, spells[i].info, spells[i].instant);
break;
case TARGET_DESTINATION:
_unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break;
case TARGET_RANDOM_SINGLE:
case TARGET_RANDOM_DESTINATION:
CastSpellOnRandomTarget(i, 0, 0); break;
}
spells[i].casttime = spells[i].cooldown;
m_spellcheck[i] = false;
return;
}
if(spells[i].casttime > 0)
spells[i].casttime--;
if(!spells[i].casttime)
{
_unit->setAttackTimer(spells[i].attackstoptimer, false);
m_spellcheck[i] = true;
}
comulativeperc += spells[i].perctrigger;
}
}
}
void CastSpellOnRandomTarget(uint32 i, float mindist2cast, float maxdist2cast)
{
if (!maxdist2cast) maxdist2cast = 100.0f;
Unit* RandomTarget = NULL;
std::vector<Unit*> TargetTable; /* From M4ksiu - Big THX to Capt who helped me with std stuff to make it simple and fully working <3 */
/* If anyone wants to use this function, then leave this note! */
for(set<Object*>::iterator itr = _unit->GetInRangeSetBegin(); itr != _unit->GetInRangeSetEnd(); ++itr)
{
if (isHostile(_unit, (*itr)) && ((*itr)->GetTypeId()== TYPEID_UNIT || (*itr)->GetTypeId() == TYPEID_PLAYER))
{
RandomTarget = (Unit*)(*itr);
if (RandomTarget->isAlive() && _unit->GetDistance2dSq(RandomTarget) >= mindist2cast*mindist2cast && _unit->GetDistance2dSq(RandomTarget) <= maxdist2cast*maxdist2cast)
TargetTable.push_back(RandomTarget);
}
}
if (!TargetTable.size())
return;
Unit * RTarget = *(TargetTable.begin()+rand()%TargetTable.size());
if (!RTarget)
return;
switch (spells[i].targettype)
{
case TARGET_RANDOM_SINGLE:
_unit->CastSpell(RTarget, spells[i].info, spells[i].instant); break;
case TARGET_RANDOM_DESTINATION:
_unit->CastSpellAoF(RTarget->GetPositionX(), RTarget->GetPositionY(), RTarget->GetPositionZ(), spells[i].info, spells[i].instant); break;
}
TargetTable.clear();
}
private:
int nrspells;
int minspell;
int maxspell;
bool form; //false = water | true = poison
SpellDesc *spell_water_tomb;
uint32 MarkTimer;
uint32 MarkCount;
bool Enraged;
uint32 EnrageTimer;
};
//------------------------------------
// -= The Lurker Below=-
//------------------------------------
#define CN_THE_LURKER_BELOW 21217
#define CN_CN_COILFANG_AMBUSHER 21865
#define CN_CN_COILFANG_GUARDIAN 21873
#define WHIRL 37363
#define GEYSER 37478
#define SPOUT 37433
#define SUBMERGE 37433 // Didn't find the spell id
//#define WATER_BOLT 37138
class LurkerAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(LurkerAI);
SP_AI_Spell spells[4];
bool m_spellcheck[4];
LurkerAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
// -- Number of spells to add --
nrspells = 4;
// --- Initialization ---
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
// ----------------------
// Create basic info for spells here, and play with it later , fill always the info, targettype and if is instant or not!
spells[0].info = dbcSpell.LookupEntry(WHIRL);
spells[0].targettype = TARGET_ATTACKING;
spells[0].instant = true;
spells[0].cooldown = 30;
spells[0].perctrigger = 10.0f;
spells[0].attackstoptimer = 1000; // 1sec
m_spellcheck[0] = true;
spells[1].info = dbcSpell.LookupEntry(GEYSER);
spells[1].targettype = TARGET_VARIOUS;
spells[1].instant = true;
spells[1].cooldown = 10;
spells[1].perctrigger = 10.0f;
spells[1].attackstoptimer = 2000; // 2sec
spells[2].info = dbcSpell.LookupEntry(SPOUT);
spells[2].targettype = TARGET_ATTACKING;
spells[2].instant = false;
spells[2].cooldown = 60;
spells[2].perctrigger = 5.0f;
spells[2].attackstoptimer = 2000; // 2sec
spells[3].info = dbcSpell.LookupEntry(SUBMERGE);
spells[3].targettype = TARGET_SELF;
spells[3].instant = true;
spells[3].cooldown = 120;
spells[3].perctrigger = 10.0f;
spells[3].attackstoptimer = 2000; // 2sec
}
void OnCombatStart(Unit* mTarget)
{
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
}
void OnCombatStop(Unit *mTarget)
{
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
}
void OnDied(Unit * mKiller)
{
RemoveAIUpdateEvent();
}
void OnTargetDied(Unit* mTarget)
{
}
void AIUpdate()
{
float val = (float)RandomFloat(100.0f);
SpellCast(val);
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i=0;i<nrspells;i++)
{
if(!spells[i].perctrigger) continue;
if(m_spellcheck[i])
{
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant); break;
case TARGET_ATTACKING:
_unit->CastSpell(target, spells[i].info, spells[i].instant);
break;
case TARGET_DESTINATION:
_unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break;
}
m_spellcheck[i] = false;
return;
}
if(val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger))
{
_unit->setAttackTimer(spells[i].attackstoptimer, false);
m_spellcheck[i] = true;
}
comulativeperc += spells[i].perctrigger;
}
}
}
protected:
int nrspells;
};
//------------------------------------
// -= Leotheras the Blind =-
//------------------------------------
/* ToDo:
- Some phase timers
- Insidious whispers
*/
#define CN_LEOTHERAS_THE_BLIND 21215
#define CN_INNER_DEMON 21857
#define CN_GREYHEART_SPELLBINDER 21806
#define CN_SHADOW_OF_LEOTHERAS 21875
#define MIND_BLAST 37531
#define WHIRLWINDLEO 40653
#define INSIDIOUS_WHISPER 37676
#define CHAOS_BLAST_ANIMATION 37674
#define CHAOS_BLAST_EFFECT 37675
#define LEO_ENRAGE 41447 //13048
#define LEO_BANISH 37546
uint32 LeotherasEventGreyheartToKill[1000000];
class LeotherasAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(LeotherasAI);
SP_AI_Spell spells[1];
bool m_spellcheck[1];
LeotherasAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
//Insidious Whisper (inner demons)
//"We all have our demons..."
////Debuff that summons an Inner Demon from up to five raid members. Each Inner Demon can be attacked only by the person it spawned from. If you do not kill your Inner Demon before Leotheras gets back into humanoid form you will become Mind Controlled for 10 minutes and can't get out of it unless killed. Inner Demons take increased damage from arcane, nature, and holy spells.
spells[0].info = dbcSpell.LookupEntry(INSIDIOUS_WHISPER);
spells[0].targettype = TARGET_VARIOUS;
spells[0].instant = true;
spells[0].perctrigger = 2.0f;
spells[0].attackstoptimer = 2000;
m_spellcheck[0] = false;
info_chaos_blast = dbcSpell.LookupEntry(CHAOS_BLAST_ANIMATION);
info_whirlwind = dbcSpell.LookupEntry(WHIRLWINDLEO);
_unit->SetUInt64Value(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_ATTACKABLE_9);
_unit->GetAIInterface()->SetAllowedToEnterCombat(false);
LeotherasEventGreyheartToKill[_unit->GetInstanceID()] = 0;
//check if greyheart spellbinders are alive after map initialization
TimedEvent * te = TimedEvent::Allocate(this, new CallbackP0<LeotherasAI>(this, &LeotherasAI::FirstCheck), 1, 500, 1);
sWorld.event_AddEvent(te);
}
void FirstCheck()
{
//count greyheart spellbinders
Creature *creature = NULL;
for(set<Object*>::iterator itr = _unit->GetInRangeSetBegin(); itr != _unit->GetInRangeSetEnd(); ++itr)
{
if((*itr)->GetTypeId() == TYPEID_UNIT)
{
creature = static_cast<Creature*>((*itr));
if(creature->GetCreatureInfo() && creature->GetCreatureInfo()->Id == CN_GREYHEART_SPELLBINDER && creature->isAlive())
LeotherasEventGreyheartToKill[_unit->GetInstanceID()]++;
}
}
//no greyheart spellbinder found, release him
if(!LeotherasEventGreyheartToKill[_unit->GetInstanceID()])
{
//remove banish & blocks
_unit->RemoveAllAuras();
_unit->SetUInt32Value(UNIT_FIELD_FLAGS, 0);
_unit->GetAIInterface()->SetAllowedToEnterCombat(true);
_unit->GetAIInterface()->m_canMove = true;
_unit->SetStandState(STANDSTATE_STAND);
}
}
void OnCombatStart(Unit* mTarget)
{
if(LeotherasEventGreyheartToKill[_unit->GetInstanceID()] != 0)
return;
Phase = 0; //nightelf form
SwitchTimer = 40+rand()%5; //wowwiki says 45, bosskillers says 40
WhirlwindTimer = 15;
mInWhirlwind = false;
FinalPhaseSubphase = 0;
FinalPhaseTimer = 0;
IsMorphing = false;
Enraged = false;
EnrageTimer = 599; //10 minutes
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Finally my banishment ends!");
_unit->PlaySoundToSet(11312);
RegisterAIUpdateEvent(1000);
}
void OnCombatStop(Unit *mTarget)
{
//despawn shadow of leotheras
Creature *shadow = NULL;
shadow = _unit->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(_unit->GetPositionX(), _unit->GetPositionY(), _unit->GetPositionZ(), CN_SHADOW_OF_LEOTHERAS);
if(shadow)
{
shadow->Despawn(0, 0);
}
SwitchToHumanForm();
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
}
void OnTargetDied(Unit* mTarget)
{
if (_unit->GetHealthPct() > 0)
{
if(Phase) //blood elf form
{
switch (rand()%3)
{
case 0:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Kill! KILL!");
_unit->PlaySoundToSet(11314);
break;
case 1:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "That's right! Yes!");
_unit->PlaySoundToSet(11315);
break;
case 2:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Who's the master now?");
_unit->PlaySoundToSet(11316);
break;
}
}
else //demon form
{
switch (rand()%3)
{
case 0:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "I have no equal.");
_unit->PlaySoundToSet(11306);
break;
case 1:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Perish, mortal.");
_unit->PlaySoundToSet(11307);
break;
case 2:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Yes, YES! Ahahah!");
_unit->PlaySoundToSet(11308);
break;
}
}
}
}
void OnDied(Unit * mKiller)
{
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "You cannot kill me! Fools, I'll be back! I'll... aarghh...");
_unit->PlaySoundToSet(11317);
RemoveAIUpdateEvent();
}
void SwitchToHumanForm()
{
_unit->SetUInt32Value(UNIT_FIELD_DISPLAYID, 20514);
_unit->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_DISPLAY, _unit->GetProto()->Item1SlotDisplay);
_unit->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_DISPLAY_01, _unit->GetProto()->Item2SlotDisplay);
_unit->SetUInt32Value(UNIT_VIRTUAL_ITEM_INFO, _unit->GetProto()->Item1Info1);
_unit->SetUInt32Value(UNIT_VIRTUAL_ITEM_INFO_01, _unit->GetProto()->Item1Info2);
_unit->SetUInt32Value(UNIT_VIRTUAL_ITEM_INFO_02, _unit->GetProto()->Item2Info1);
_unit->SetUInt32Value(UNIT_VIRTUAL_ITEM_INFO_03, _unit->GetProto()->Item2Info2);
}
void SwitchToDemonForm()
{
_unit->SetUInt32Value(UNIT_FIELD_DISPLAYID, 20125);
_unit->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_DISPLAY, 0);
_unit->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_DISPLAY_01, 0);
_unit->SetUInt32Value(UNIT_VIRTUAL_ITEM_INFO, 0);
_unit->SetUInt32Value(UNIT_VIRTUAL_ITEM_INFO_01, 0);
_unit->SetUInt32Value(UNIT_VIRTUAL_ITEM_INFO_02, 0);
_unit->SetUInt32Value(UNIT_VIRTUAL_ITEM_INFO_03, 0);
}
void AIUpdate()
{
if(Phase == 0 || Phase == 3) //nightelf phase
{
if(!IsMorphing)
{
//whirlwind
WhirlwindTimer--;
if(!WhirlwindTimer)
{
if(!mInWhirlwind)
{
_unit->CastSpell(_unit, info_whirlwind, true);
_unit->setAttackTimer(15000, false);
_unit->GetAIInterface()->ClearHateList(); //reset aggro
WhirlwindTimer = 15;
mInWhirlwind = true;
}
else
{
_unit->GetAIInterface()->ClearHateList(); //reset aggro
WhirlwindTimer = 15;
mInWhirlwind = false;
}
}
float val = (float)RandomFloat(100.0f);
SpellCast(val);
}
if(Phase == 0)
{
//switch to demon form
SwitchTimer--;
if(!SwitchTimer)
{
//switch to AGENT_SPELL
_unit->GetAIInterface()->setCurrentAgent(AGENT_SPELL);
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Be gone trifling elf. I'm in control now");
_unit->PlaySoundToSet(11304);
SwitchToDemonForm();
Phase = 1;
SwitchTimer = 60; //60 seconds
}
//15% Leotheras/Demon split
//wait until he returns nightelf (blizzlike)
if(_unit->GetHealthPct() <= 15 && !mInWhirlwind)
Phase = 3;
}
else
{
Creature *shadow = NULL;
switch(FinalPhaseSubphase)
{
case 0:
IsMorphing = true;
_unit->setAttackTimer(15000, false);
_unit->SetStandState(STANDSTATE_KNEEL);
_unit->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_ATTACKABLE_9);
_unit->GetAIInterface()->SetAllowedToEnterCombat(false);
_unit->GetAIInterface()->m_canMove = false;
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "No... no! What have you done? I am the master! Do you hear me? I am... aaggh! Can't... contain him.");
_unit->PlaySoundToSet(11313);
FinalPhaseTimer = 10;
FinalPhaseSubphase++;
break;
case 1:
FinalPhaseTimer--;
if(!FinalPhaseTimer)
{
_unit->SetStandState(STANDSTATE_STAND);
shadow = _unit->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(_unit->GetPositionX(), _unit->GetPositionY(), _unit->GetPositionZ(),CN_SHADOW_OF_LEOTHERAS);
if (shadow == NULL)
shadow = _unit->GetMapMgr()->GetInterface()->SpawnCreature(CN_SHADOW_OF_LEOTHERAS, _unit->GetPositionX(), _unit->GetPositionY(), _unit->GetPositionZ(), _unit->GetOrientation(), true, false, 0, 0);
FinalPhaseTimer = 5;
FinalPhaseSubphase++;
}
break;
case 2:
FinalPhaseTimer--;
if(!FinalPhaseTimer)
{
_unit->SetUInt32Value(UNIT_FIELD_FLAGS, 0);
_unit->GetAIInterface()->SetAllowedToEnterCombat(true);
_unit->GetAIInterface()->m_canMove = true;
IsMorphing = false;
FinalPhaseSubphase++;
}
break;
default:
break;
}
}
//Enrage
if(!Enraged)
{
EnrageTimer--;
if(!EnrageTimer)
{
_unit->CastSpell(_unit, dbcSpell.LookupEntry(LEO_ENRAGE), true);
Enraged = true;
}
}
}
else if(Phase == 1) //demon form
{
//Chaos Blast
if(_unit->GetAIInterface()->GetNextTarget())
{
if(_unit->GetCurrentSpell() == NULL)
{
if(rand()%2)
{
_unit->CastSpell(_unit->GetAIInterface()->GetNextTarget(), info_chaos_blast, false);
}
}
//move if needed
if(_unit->GetAIInterface()->GetNextTarget()->GetDistance2dSq(_unit) >= 400) //20 yards
{
_unit->GetAIInterface()->m_moveRun = true;
_unit->GetAIInterface()->_CalcDestinationAndMove(_unit->GetAIInterface()->GetNextTarget(), 5.0f);
}
}
//switch
SwitchTimer--;
if(!SwitchTimer)
{
_unit->GetAIInterface()->setCurrentAgent(AGENT_MELEE);
SwitchToHumanForm();
Phase = 0;
WhirlwindTimer = 10+rand()%5;
SwitchTimer = 40+rand()%5; //wowwiki says 45, bosskillers says 40
_unit->GetAIInterface()->ClearHateList(); //reset aggro
}
}
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i = 0; i < 1; i++)
{
if(!spells[i].perctrigger) continue;
if(m_spellcheck[i])
{
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant); break;
case TARGET_ATTACKING:
_unit->CastSpell(target, spells[i].info, spells[i].instant); break;
case TARGET_DESTINATION:
_unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break;
}
if (spells[i].speech != "")
{
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, spells[i].speech.c_str());
_unit->PlaySoundToSet(spells[i].soundid);
}
m_spellcheck[i] = false;
return;
}
if(val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger))
{
_unit->setAttackTimer(spells[i].attackstoptimer, false);
m_spellcheck[i] = true;
}
comulativeperc += spells[i].perctrigger;
}
}
}
protected:
int nrspells;
uint32 SwitchTimer;
uint32 WhirlwindTimer;
uint32 EnrageTimer;
bool Enraged;
bool mInWhirlwind;
bool IsMorphing;
uint32 Phase;
SpellEntry *info_whirlwind;
SpellEntry *info_chaos_blast;
uint32 FinalPhaseSubphase;
uint32 FinalPhaseTimer;
};
class GreyheartSpellbinderAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(GreyheartSpellbinderAI);
SP_AI_Spell spells[1];
bool m_spellcheck[1];
GreyheartSpellbinderAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
nrspells = 1;
spells[0].info = dbcSpell.LookupEntry(MIND_BLAST);
spells[0].targettype = TARGET_RANDOM_SINGLE;
spells[0].instant = true;
spells[0].perctrigger = 50.0f;
spells[0].attackstoptimer = 2000;
m_spellcheck[0] = false;
Unit* Leotheras = NULL;
Leotheras = _unit->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(376.543f, -438.631f, 29.7083f, CN_LEOTHERAS_THE_BLIND);
if(Leotheras)
{
_unit->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, Leotheras->GetGUID());
_unit->SetUInt32Value(UNIT_CHANNEL_SPELL, 30166);//wrong
}
}
void OnCombatStart(Unit* mTarget)
{
_unit->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
_unit->SetUInt32Value(UNIT_CHANNEL_SPELL, 0);
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
}
void OnCombatStop(Unit *mTarget)
{
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
}
void AIUpdate()
{
float val = (float)RandomFloat(100.0f);
SpellCast(val);
}
void OnDied(Unit * mKiller)
{
LeotherasEventGreyheartToKill[_unit->GetInstanceID()]--;
//start the event
if(LeotherasEventGreyheartToKill[_unit->GetInstanceID()] == 0)
{
Unit* Leotheras = NULL;
Leotheras = _unit->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(376.543f, -438.631f, 29.7083f, CN_LEOTHERAS_THE_BLIND);
if(Leotheras)
{
//remove banish & blocks
Leotheras->RemoveAllAuras();
Leotheras->SetUInt32Value(UNIT_FIELD_FLAGS, 0);
Leotheras->GetAIInterface()->SetAllowedToEnterCombat(true);
Leotheras->GetAIInterface()->m_canMove = true;
Leotheras->SetStandState(STANDSTATE_STAND);
//attack nearest player
Player *NearestPlayer;
float NearestDist = 0;
for(set<Player*>::iterator itr = _unit->GetInRangePlayerSetBegin(); itr != _unit->GetInRangePlayerSetEnd(); ++itr)
{
if(isHostile(_unit, (*itr)) && ((*itr)->GetDistance2dSq(_unit) < NearestDist || !NearestDist))
{
NearestDist = (*itr)->GetDistance2dSq(_unit);
NearestPlayer = (*itr);
}
}
if(NearestPlayer)
Leotheras->GetAIInterface()->AttackReaction(NearestPlayer, 1, 0);
}
}
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i=0;i<nrspells;i++)
{
if(!spells[i].perctrigger) continue;
if(m_spellcheck[i])
{
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant); break;
case TARGET_ATTACKING:
_unit->CastSpell(target, spells[i].info, spells[i].instant); break;
case TARGET_DESTINATION:
_unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break;
case TARGET_RANDOM_SINGLE:
case TARGET_RANDOM_DESTINATION:
CastSpellOnRandomTarget(i, 0, 0); break;
}
m_spellcheck[i] = false;
return;
}
if(val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger))
{
_unit->setAttackTimer(spells[i].attackstoptimer, false);
m_spellcheck[i] = true;
}
comulativeperc += spells[i].perctrigger;
}
}
}
void CastSpellOnRandomTarget(uint32 i, float mindist2cast, float maxdist2cast)
{
if (!maxdist2cast) maxdist2cast = 100.0f;
Unit* RandomTarget = NULL;
std::vector<Unit*> TargetTable; /* From M4ksiu - Big THX to Capt who helped me with std stuff to make it simple and fully working <3 */
/* If anyone wants to use this function, then leave this note! */
for(set<Object*>::iterator itr = _unit->GetInRangeSetBegin(); itr != _unit->GetInRangeSetEnd(); ++itr)
{
if (isHostile(_unit, (*itr)) && ((*itr)->GetTypeId()== TYPEID_UNIT || (*itr)->GetTypeId() == TYPEID_PLAYER) && isAttackable(_unit, (*itr)))
{
RandomTarget = (Unit*)(*itr);
if (RandomTarget->isAlive() && _unit->GetDistance2dSq(RandomTarget) >= mindist2cast*mindist2cast && _unit->GetDistance2dSq(RandomTarget) <= maxdist2cast*maxdist2cast)
TargetTable.push_back(RandomTarget);
}
}
if (!TargetTable.size())
return;
Unit * RTarget = *(TargetTable.begin()+rand()%TargetTable.size());
if (!RTarget)
return;
switch (spells[i].targettype)
{
case TARGET_RANDOM_SINGLE:
_unit->CastSpell(RTarget, spells[i].info, spells[i].instant); break;
case TARGET_RANDOM_DESTINATION:
_unit->CastSpellAoF(RTarget->GetPositionX(), RTarget->GetPositionY(), RTarget->GetPositionZ(), spells[i].info, spells[i].instant); break;
}
TargetTable.clear();
}
private:
int nrspells;
};
class ShadowofLeotherasAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(ShadowofLeotherasAI);
ShadowofLeotherasAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
info_chaos_blast = dbcSpell.LookupEntry(CHAOS_BLAST_ANIMATION);
_unit->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_ATTACKABLE_9);
_unit->GetAIInterface()->SetAllowedToEnterCombat(false);
TimedEvent * te = TimedEvent::Allocate(this, new CallbackP0<ShadowofLeotherasAI>(this, &ShadowofLeotherasAI::Free), 1, 7500, 1);
sWorld.event_AddEvent(te);
}
void Free()
{
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "At last I am liberated. It has been too long since I have tasted true freedom!");
_unit->PlaySoundToSet(11309);
_unit->SetUInt32Value(UNIT_FIELD_FLAGS, 0);
_unit->GetAIInterface()->SetAllowedToEnterCombat(true);
_unit->GetAIInterface()->m_canMove = true;
}
void OnCombatStart(Unit* mTarget)
{
_unit->GetAIInterface()->setCurrentAgent(AGENT_SPELL);
RegisterAIUpdateEvent(1000);
}
void OnCombatStop(Unit* mTarget)
{
RemoveAIUpdateEvent();
}
void AIUpdate()
{
//Chaos Blast
if(_unit->GetAIInterface()->GetNextTarget())
{
if(_unit->GetCurrentSpell() == NULL)
{
if(rand()%2)
{
_unit->CastSpell(_unit->GetAIInterface()->GetNextTarget(), info_chaos_blast, false);
}
}
//move if needed
if(_unit->GetAIInterface()->GetNextTarget()->GetDistance2dSq(_unit) >= 400) //20 yards
{
_unit->GetAIInterface()->m_moveRun = true;
_unit->GetAIInterface()->_CalcDestinationAndMove(_unit->GetAIInterface()->GetNextTarget(), 5.0f);
}
}
}
protected:
SpellEntry* info_chaos_blast;
};
//Chaos blast dummy effect
bool ChaosBlast(uint32 i, Spell * pSpell)
{
/*Unit *target = NULL;
if(GUID_HIPART(pSpell->m_targets.m_unitTarget) == HIGHGUID_UNIT)
target = pSpell->u_caster->GetMapMgr()->GetCreature(pSpell->m_targets.m_unitTarget);
else if (GUID_HIPART(pSpell->m_targets.m_unitTarget) == HIGHGUID_PLAYER)
target = objmgr.GetPlayer(pSpell->m_targets.m_unitTarget);*/
// M4ksiu - not sure if it's correct way to resolve Ascent -> AspireCore changes
if ( pSpell == NULL || pSpell->u_caster == NULL )
return true;
pSpell->u_caster->CastSpell( pSpell->m_targets.m_unitTarget, dbcSpell.LookupEntry( CHAOS_BLAST_EFFECT ), true );
return true;
}
//------------------------------------
// -= Fathom-Lord Karathress =-
//------------------------------------
#define CN_FATHOM_LORD_KARATHRESS 21214
#define CN_FATHOM_GUARD_SHARKKIS 21966
#define CN_FATHOM_GUARD_TIDALVESS 21965
#define CN_FATHOM_LURKER 22119
#define CN_FATHOM_SPOREBAT 22120
#define CN_FATHOM_GUARD_CARIBDIS 21964
#define CN_SEER_OLUM 22820
#define CATACLYSMIC_BOLT 38441
#define BLESSING_OF_THE_TIDES 38449
#define KARATHRESS_ENRAGE 39249
class KarathressAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(KarathressAI);
KarathressAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
info_cataclysmic_bolt = dbcSpell.LookupEntry(CATACLYSMIC_BOLT);
AdvisorsLeft = 0;
//check if advisors are alive after map initialization
TimedEvent * te = TimedEvent::Allocate(this, new CallbackP0<KarathressAI>(this, &KarathressAI::CheckAdvisors), 1, 500, 1);
sWorld.event_AddEvent(te);
}
void CheckAdvisors()
{
Unit *advisor = NULL;
//Sharkkis
advisor = _unit->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(_unit->GetPositionX(), _unit->GetPositionY(), _unit->GetPositionZ(), CN_FATHOM_GUARD_SHARKKIS);
if(advisor && advisor->isAlive()) AdvisorsLeft++;
//Tidalvess
advisor = _unit->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(_unit->GetPositionX(), _unit->GetPositionY(), _unit->GetPositionZ(), CN_FATHOM_GUARD_TIDALVESS);
if(advisor && advisor->isAlive()) AdvisorsLeft++;
//Caribdis
advisor = _unit->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(_unit->GetPositionX(), _unit->GetPositionY(), _unit->GetPositionZ(), CN_FATHOM_GUARD_CARIBDIS);
if(advisor && advisor->isAlive()) AdvisorsLeft++;
}
void OnCombatStart(Unit* mTarget)
{
CataclysmicBoltTimer = 60;
EnrageTimer = 600;
Enraged = false;
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Guards, attention! We have visitors ...");
_unit->PlaySoundToSet(11277);
RegisterAIUpdateEvent(1000);
}
void OnCombatStop(Unit *mTarget)
{
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
}
void OnDied(Unit * mKiller)
{
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Her ... excellency ... awaits!");
_unit->PlaySoundToSet(11285);
RemoveAIUpdateEvent();
//spawn seer olum and despawn him in 3 minutes
Creature *olum = NULL;
olum = _unit->GetMapMgr()->GetInterface()->SpawnCreature(CN_SEER_OLUM, 451.099f, -544.984f, -7.36327f, 0.174533f, true, false, 0, 0);
if(olum)
olum->Despawn(180000, 0);
}
void OnTargetDied(Unit* mTarget)
{
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "I am rid of you.");
_unit->PlaySoundToSet(11284);
}
void AIUpdate()
{
//Cataclysmic Bolt
CataclysmicBoltTimer--;
if(!CataclysmicBoltTimer)
{
//deal half of target life
Unit *target = _unit->GetAIInterface()->GetNextTarget();
if(target && target->GetUInt32Value(UNIT_FIELD_MAXHEALTH) > 0)
{
info_cataclysmic_bolt->EffectBasePoints[0] = target->GetUInt32Value(UNIT_FIELD_MAXHEALTH)/2;
_unit->CastSpell(target, info_cataclysmic_bolt, true);
}
CataclysmicBoltTimer = 60;
}
//Blessing of the Tides
if(_unit->GetHealthPct() <= 70 && AdvisorsLeft > 0)
{
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Your overconfidence will be your undoing! Guards, lend me your strength!");
_unit->PlaySoundToSet(11278);
_unit->CastSpell(_unit, dbcSpell.LookupEntry(BLESSING_OF_THE_TIDES), true);
AdvisorsLeft = 0;
}
//Enrage
if(!Enraged)
{
EnrageTimer--;
if(!EnrageTimer)
{
_unit->CastSpell(_unit, dbcSpell.LookupEntry(KARATHRESS_ENRAGE), true);
Enraged = true;
}
}
}
uint32 AdvisorsLeft;
private:
SpellEntry *info_cataclysmic_bolt;
uint32 CataclysmicBoltTimer;
uint32 EnrageTimer;
bool Enraged;
};
//Fathom-Guard Sharkkis (Hunter)
#define MULTI_SHOT 29576
#define LEECHING_THROW 29436
#define THE_BEAST_WITHIN 38373
class FathomGuardSharkissAI : public MoonScriptCreatureAI
{
public:
ADD_CREATURE_FACTORY_FUNCTION(FathomGuardSharkissAI);
FathomGuardSharkissAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature)
{
AddSpell(MULTI_SHOT, Target_Current, 10.0f, 0, 0);
AddSpell(LEECHING_THROW, Target_Current, 10.0f, 0, 0);
AddSpell(THE_BEAST_WITHIN, Target_Current, 10.0f, 0, 40);
}
void OnCombatStart(Unit* pTarget)
{
CurrentPet = NULL;
SummonPetTimer = 5;
MoonScriptCreatureAI::OnCombatStart(pTarget);
}
void OnDied(Unit* pKiller)
{
Creature* FLK = _unit->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(_unit->GetPositionX(), _unit->GetPositionY(), _unit->GetPositionZ(), CN_FATHOM_LORD_KARATHRESS);
if(FLK)
{
FLK->CastSpell(FLK, dbcSpell.LookupEntry(38455), true); //Power of Sharkkis
FLK->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "I am more powerful than ever!");
FLK->PlaySoundToSet(11280);
if(static_cast<KarathressAI*>(FLK->GetScript())->AdvisorsLeft > 0)
static_cast<KarathressAI*>(FLK->GetScript())->AdvisorsLeft--;
}
MoonScriptCreatureAI::OnDied(pKiller);
}
void AIUpdate()
{
//Summon Pet
if(!CurrentPet || !CurrentPet->isAlive())
{
SummonPetTimer--;
if(!SummonPetTimer)
{
switch(rand()%2)
{
case 0:
CurrentPet = _unit->GetMapMgr()->GetInterface()->SpawnCreature(CN_FATHOM_LURKER, _unit->GetPositionX(), _unit->GetPositionY(), _unit->GetPositionZ(), 0, true, false, 0, 0);
break;
case 1:
CurrentPet = _unit->GetMapMgr()->GetInterface()->SpawnCreature(CN_FATHOM_SPOREBAT, _unit->GetPositionX(), _unit->GetPositionY(), _unit->GetPositionZ(), 0, true, false, 0, 0);
break;
}
SummonPetTimer = 5;
}
}
MoonScriptCreatureAI::AIUpdate();
}
private:
uint32 SummonPetTimer;
Creature *CurrentPet;
};
//Fathom-Guard Tidalvess (Shaman)
#define SPITFIRE_TOTEM 38236
#define POISON_CLEANSING_TOTEM 38306
#define EARTHBIND_TOTEM 38304
#define FROST_SHOCK 38234
#define WINDFURY 38229
class FathomGuardTidalvessAI : public MoonScriptCreatureAI
{
public:
ADD_CREATURE_FACTORY_FUNCTION(FathomGuardTidalvessAI);
FathomGuardTidalvessAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature)
{
//totems
AddSpell(SPITFIRE_TOTEM, Target_Self, 10.0f, 0, 0);
AddSpell(POISON_CLEANSING_TOTEM, Target_Self, 10.0f, 0, 0);
AddSpell(EARTHBIND_TOTEM, Target_Self, 10.0f, 0, 0);
AddSpell(FROST_SHOCK, Target_Current, 10.0f, 0, 0);
AddSpell(WINDFURY, Target_Current, 10.0f, 0, 0);
}
void OnDied(Unit * pKiller)
{
Creature* FLK = _unit->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(_unit->GetPositionX(), _unit->GetPositionY(), _unit->GetPositionZ(), CN_FATHOM_LORD_KARATHRESS);
if(FLK)
{
FLK->CastSpell(FLK, dbcSpell.LookupEntry(38452), true); //Power of Tidalvess
FLK->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Go on, kill them! I'll be the better for it!");
FLK->PlaySoundToSet(11279);
if(static_cast<KarathressAI*>(FLK->GetScript())->AdvisorsLeft > 0)
static_cast<KarathressAI*>(FLK->GetScript())->AdvisorsLeft--;
}
MoonScriptCreatureAI::OnDied(pKiller);
}
};
//Fathom-Guard Caribdis (Priest)
#define HEAL 33144
#define TIDAL_SURGE 38358
#define SUMMON_CYCLONE 38337
class FathomGuardCaribdisAI : public MoonScriptCreatureAI
{
public:
ADD_CREATURE_FACTORY_FUNCTION(FathomGuardCaribdisAI);
FathomGuardCaribdisAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature)
{
AddSpell(TIDAL_SURGE, Target_Self, 20.0f, 0, 10);
AddSpell(SUMMON_CYCLONE, Target_Self, 2.0f, 0, 0);
}
void OnCombatStart(Unit*pTarget)
{
HealingWaveTimer = 15;
MoonScriptCreatureAI::OnCombatStart(pTarget);
}
void AIUpdate()
{
/*HealingWaveTimer--;
if(!HealingWaveTimer)
{
vector<Unit*> TargetTable;
for(set<Object*>::iterator itr = _unit->GetInRangeSetBegin(); itr != _unit->GetInRangeSetEnd(); ++itr)
{
if((*itr)->GetTypeId() == TYPEID_UNIT && isFriendly(_unit, (*itr)))
TargetTable.push_back((Unit*)(*itr));
}
HealingWaveTimer = 15;
}*/
MoonScriptCreatureAI::AIUpdate();
}
void OnDied(Unit * pKiller)
{
Creature* FLK = _unit->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(_unit->GetPositionX(), _unit->GetPositionY(), _unit->GetPositionZ(), CN_FATHOM_LORD_KARATHRESS);
if(FLK)
{
FLK->CastSpell(FLK, dbcSpell.LookupEntry(38451), true); //Power of Caribdis
FLK->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "More knowledge, more power!");
FLK->PlaySoundToSet(11281);
if(static_cast<KarathressAI*>(FLK->GetScript())->AdvisorsLeft > 0)
static_cast<KarathressAI*>(FLK->GetScript())->AdvisorsLeft--;
}
MoonScriptCreatureAI::OnDied(pKiller);
}
private:
uint32 HealingWaveTimer;
};
//------------------------------------
// -= Morogrim Tidewalker =-
//------------------------------------
#define CN_MOROGRIM_TIDEWALKER 21213
#define CN_TIDEWALKER_LURKER 21920 //Murlocks that he spawns after earthquake
#define TIDAL_WAVE 37730
#define WATERY_GRAVE 38049
#define EARTHQUAKE 37764
#define SUMMON_WATER_GLOBULE 37854
class MorogrimAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(MorogrimAI);
SP_AI_Spell spells[4];
MorogrimAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
spells[0].info = dbcSpell.LookupEntry(TIDAL_WAVE);
spells[0].instant = true;
spells[1].info = dbcSpell.LookupEntry(EARTHQUAKE);
spells[1].instant = true;
spells[1].cooldown = 40;
spells[2].info = dbcSpell.LookupEntry(WATERY_GRAVE);
spells[2].instant = true;
spells[2].cooldown = 30;
spells[3].info = dbcSpell.LookupEntry(SUMMON_WATER_GLOBULE);
spells[3].instant = true;
spells[3].cooldown = 30;
}
void OnCombatStart(Unit* mTarget)
{
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Flood of the deep, take you!");
_unit->PlaySoundToSet(11321);
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
uint32 t = (uint32)time(NULL);
for (int i = 1; i < 4; i++)
spells[i].casttime = t + spells[i].cooldown;
}
void OnCombatStop(Unit *mTarget)
{
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
}
void OnDied(Unit * mKiller)
{
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Great... currents of... Ageon.");
_unit->PlaySoundToSet(11329);
RemoveAIUpdateEvent();
}
void OnTargetDied(Unit* mTarget)
{
if (_unit->GetHealthPct() > 0)
{
int RandomSpeach = rand()%3;
switch (RandomSpeach)
{
case 0:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Only the strong survive.");
_unit->PlaySoundToSet(11328);
break;
case 1:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Struggling only makes it worse.");
_unit->PlaySoundToSet(11327);
break;
case 2:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "It is done!");
_unit->PlaySoundToSet(11326);
break;
}
}
}
void AIUpdate()
{
if (_unit->GetAIInterface()->GetNextTarget() != NULL && _unit->GetCurrentSpell() == NULL)
{
Unit *target = NULL;
uint32 t = (uint32)time(NULL);
target = _unit->GetAIInterface()->GetNextTarget();
if (t > spells[2].casttime)
{
_unit->SendChatMessageAlternateEntry(CN_MOROGRIM_TIDEWALKER, CHAT_MSG_MONSTER_EMOTE, LANG_UNIVERSAL, " sends his enemies to their watery graves!");
_unit->CastSpell(target, spells[2].info, spells[2].instant);
spells[2].casttime = t + spells[2].cooldown;
return;
}
if (t > spells[1].casttime)
{
_unit->SendChatMessageAlternateEntry(17165, CHAT_MSG_MONSTER_EMOTE, LANG_UNIVERSAL, "The violent earthquake has alerted nearby Murlocs!");
int RandomSpeach = rand()%2;
switch (RandomSpeach)
{
case 0:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Destroy them my subjects!");
_unit->PlaySoundToSet(11323);
break;
case 1:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "By the Tides, kill them at once!");
_unit->PlaySoundToSet(11322);
break;
}
_unit->CastSpell(_unit, spells[1].info, spells[1].instant);
for (int i = 0; i < 6; i++)
_unit->GetMapMgr()->GetInterface()->SpawnCreature(CN_TIDEWALKER_LURKER, 370.82f, -723.93f, -13.9f, 0, true, false, 0, 0);
for (int i = 0; i < 6; i++)
_unit->GetMapMgr()->GetInterface()->SpawnCreature(CN_TIDEWALKER_LURKER, 527.90f, -721.88f, -7.14f, 0, true, false, 0, 0);
spells[1].casttime = t + spells[1].cooldown;
return;
}
if (_unit->GetHealthPct() < 25)
{
if (t > spells[3].casttime)
{
_unit->SendChatMessageAlternateEntry(CN_MOROGRIM_TIDEWALKER, CHAT_MSG_MONSTER_EMOTE, LANG_UNIVERSAL, " summons Watery Globules!");
int RandomSpeach = rand()%2;
switch (RandomSpeach)
{
case 0:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Soon it will be finished.");
_unit->PlaySoundToSet(11325);
break;
case 1:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "There is nowhere to hide!");
_unit->PlaySoundToSet(11324);
break;
}
_unit->CastSpell(target, spells[3].info, spells[3].instant);
spells[3].casttime = t + spells[3].cooldown;
return;
}
}
else if (_unit->GetHealthPct() >= 25)
{
spells[3].casttime = t + spells[3].cooldown;
}
float random = RandomFloat(100.0f);
if (random < 10.0f)
{
_unit->CastSpell(target, spells[0].info, spells[0].instant);
}
}
}
};
//CN_TIDEWALKER_LURKER
class TidewalkerLurkerAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(TidewalkerLurkerAI);
TidewalkerLurkerAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
Unit *target = FindTargetForSpell();
if (target)
{
_unit->GetAIInterface()->AttackReaction(target, 1, 0);
}
}
void OnCombatStop(Unit *mTarget)
{
_unit->SafeDelete();
}
void OnDied(Unit * mKiller)
{
_unit->SafeDelete();
}
Unit* FindTargetForSpell()
{
Unit* target = NULL;
float distance = 150.0f;
Unit *pUnit;
float dist;
for (std::set<Object*>::iterator itr = _unit->GetInRangeOppFactsSetBegin(); itr != _unit->GetInRangeOppFactsSetEnd(); itr++)
{
if((*itr)->GetTypeId() != TYPEID_UNIT && (*itr)->GetTypeId() != TYPEID_PLAYER)
continue;
pUnit = static_cast<Unit*>((*itr));
if(pUnit->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FEIGN_DEATH))
continue;
if(pUnit->m_invisible)
continue;
if(!pUnit->isAlive() || _unit == pUnit)
continue;
dist = _unit->GetDistance2dSq(pUnit);
if(dist > distance*distance)
continue;
target = pUnit;
break;
}
return target;
}
};
//------------------------------------
// -= Lady Vashj =-
//------------------------------------
/* ToDo:
- Toxic Sporebats
- Coilfang Strider spawn points
- Some vashj spells and cooldowns are wrong
- Right Shield generators coords
*/
#define CN_LADY_VASHJ 21212
#define CN_ENCHANTED_ELEMENTAL 21958
#define CN_COILFANG_STRIDER 22056
#define CN_TAINTED_ELEMENTAL 22009
#define CN_COILFANG_ELITE 22055
#define CN_TOXIC_SPORE_BAT 22140
#define CN_SHIELD_GENERATOR_CHANNEL 19870
#define SHOOT 37770
#define ENTANGLE 38316
#define SPAWN_ELEMENTAL 37053
#define MULTI_SHOT 29576
#define STATIC_CHARGE 38280
#define FORKED_LIGHTNING 40088
#define VASHJ_SHIELD 38112
#define POISON_SPIT 40078
#define TOXIC_SPORES 38575
#define SHOCK_BLAST 38509
#define WALK 0
#define RUN 256
#define FLY 768
static Coords ElementalSpawnPoints[] =
{
{8.3f, -835.3f, 21.9f, 5},
{53.4f, -835.3f, 21.9f, 4.5f},
{96.0f, -861.9f, 21.8f, 4},
{96.0f, -986.4f, 21.4f, 2.5f},
{54.4f, -1010.6f, 22.0f, 1.8f},
{9.8f, -1012.0f, 21.7f, 1.4f},
{-35.0f, -987.6f, 21.5f, 0.8f},
{-58.9f, -901.6f, 21.5f, 6.0f}
};
static Coords ElementalSpawnPoints2[] =
{
{16.305f, -867.82f, 41.09f, 0},
{43.853f, -868.338f, 41.097f, 0},
{71.55f, -885.12f, 40.87f, 0},
{70.96f, -962.56f, 41.09f, 0},
{45.227f, -977.987f, 41.09f, 0},
{17.35f, -979.27f, 41.01f, 0},
{-9.89f, -963.63f, 41.09f, 0},
{-25.37f, -910.266f, 41.09f, 0}
};
static Coords CoilfangEliteSpawnPoints[] =
{
{14.837f, -949.106f, 41.53f, 0},
{14.857f, -897.68f, 41.536f, 0},
{29.79f, -923.35f, 42.9f, 0},
{44.269f, -948.832f, 41.54f, 0}
};
static float ShieldGeneratorCoords[4][3] =
{
{49.256f, -902.354f, 42.9769f},
{9.78695f, -902.882f, 42.9f},
{10.4122f, -944.613f, 42.8262f},
{49.687f, -944.406f, 42.7324f}
};
static Coords fly[] =
{
{ 29.769f, -866.190f, 43, 0 },
{ 1.135f, -874.345f, 43, 0 },
{ -19.719f, -894.950f, 43, 0 },
{ -27.4222f, -923.572f, 43, 0 },
{ -19.739f, -951.907f, 43, 0 },
{ 1.059f, -973.314f, 43, 0 },
{ 30.071f, -980.424f, 43, 0 },
{ 58.665f, -973.410f, 43, 0 },
{ 79.353f, -952.011f, 43, 0 },
{ 87.552f, -923.175f, 43, 0 },
{ 79.068f, -894.570f, 43, 0 },
{ 58.503f, -873.295f, 43, 0 }
};
class EnchantedElementalAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(EnchantedElementalAI);
EnchantedElementalAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
_unit->GetAIInterface()->SetAllowedToEnterCombat(false);
Unit *Vashj = NULL;
Vashj = _unit->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(29.798161f, -923.358276f, 42.900517f, CN_LADY_VASHJ);
if(Vashj)
{
_unit->GetAIInterface()->SetAIState(STATE_SCRIPTMOVE);
_unit->GetAIInterface()->setMoveType(MOVEMENTTYPE_WANTEDWP);
_unit->GetAIInterface()->setWaypointToMove(1);
}
}
void OnReachWP(uint32 iWaypointId, bool bForwards)
{
switch(iWaypointId)
{
case 1:
_unit->GetAIInterface()->setMoveType(MOVEMENTTYPE_WANTEDWP);
_unit->GetAIInterface()->setWaypointToMove(2);
break;
case 2:
Unit *Vashj = NULL;
Vashj = _unit->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(29.798161f, -923.358276f, 42.900517f, CN_LADY_VASHJ);
if(Vashj)
{
//Increase Lady Vashj attack by 5%
Vashj->ModFloatValue(UNIT_FIELD_MINDAMAGE, (Vashj->GetFloatValue(UNIT_FIELD_MINDAMAGE)/100)*5);
Vashj->ModFloatValue(UNIT_FIELD_MAXDAMAGE, (Vashj->GetFloatValue(UNIT_FIELD_MAXDAMAGE)/100)*5);
}
//despawn
_unit->Despawn(0, 0);
break;
}
}
};
class VashjAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(VashjAI);
SP_AI_Spell spells[4];
bool m_spellcheck[4];
VashjAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
nrspells = 3;
spells[0].info = dbcSpell.LookupEntry(SHOCK_BLAST);
spells[0].targettype = TARGET_ATTACKING;
spells[0].instant = true;
spells[0].cooldown = 5;
spells[0].perctrigger = 5.0f;
spells[0].attackstoptimer = 2000;
m_spellcheck[0] = false;
spells[1].info = dbcSpell.LookupEntry(STATIC_CHARGE);
spells[1].targettype = TARGET_RANDOM_SINGLE;
spells[1].instant = true;
spells[1].cooldown = 5;
spells[1].perctrigger = 10.0f;
spells[1].attackstoptimer = 1000;
m_spellcheck[1] = false;
spells[2].info = dbcSpell.LookupEntry(ENTANGLE);
spells[2].targettype = TARGET_RANDOM_DESTINATION;
spells[2].instant = true;
spells[2].cooldown = 15;
spells[2].perctrigger = 10.0f;
spells[2].attackstoptimer = 1000;
m_spellcheck[2] = false;
spells[3].info = dbcSpell.LookupEntry(FORKED_LIGHTNING);
spells[3].targettype = TARGET_RANDOM_SINGLE;
spells[3].perctrigger = 0.0f;
spells[3].instant = false;
info_multishot = dbcSpell.LookupEntry(MULTI_SHOT);
info_shot = dbcSpell.LookupEntry(SHOOT);
WayPoint * wp = _unit->CreateWaypointStruct();
wp->id = 1;
wp->x = 29.798161f;
wp->y = -923.358276f;
wp->z = 42.900517f;
wp->o = 0.0f;
wp->waittime = 0;
wp->flags = RUN;
wp->forwardemoteoneshot = 0;
wp->forwardemoteid = 0;
wp->backwardemoteoneshot = 0;
wp->backwardemoteid = 0;
wp->forwardskinid = 0;
wp->backwardskinid = 0;
_unit->GetAIInterface()->addWayPoint(wp);
_unit->GetAIInterface()->setMoveType(MOVEMENTTYPE_DONTMOVEWP);
_unit->SetUInt64Value(UNIT_FIELD_FLAGS, 0);
}
void ResetCastTime()
{
for(int i = 0; i < nrspells; i++)
spells[i].casttime = spells[i].cooldown;
}
void OnCombatStart(Unit* mTarget)
{
ResetCastTime();
Phase = 1;
EnchantedElementalTimer = 10;
CoilfangStriderTimer = 60;
CoilfangEliteTimer = 40;
TaintedElementalTimer = 50;
SporebatTimer = 0;
ForkedLightningTimer = 5;
switch(rand()%4)
{
case 0:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "I'll split you from stem to stern!");
_unit->PlaySoundToSet(11532);
break;
case 1:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Victory to Lord Illidan!");
_unit->PlaySoundToSet(11533);
break;
case 2:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "I spit on you, surface filth!");
_unit->PlaySoundToSet(11534);
break;
case 3:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Death to the outsiders!");
_unit->PlaySoundToSet(11535);
break;
}
RegisterAIUpdateEvent(1000);
}
void OnCombatStop(Unit *mTarget)
{
//despawn enchanted elemental, tainted elemental, coilfang elite, coilfang strider
Creature *creature = NULL;
for(set<Object*>::iterator itr = _unit->GetInRangeSetBegin(); itr != _unit->GetInRangeSetEnd(); ++itr)
{
if((*itr)->GetTypeId() == TYPEID_UNIT)
{
creature = static_cast<Creature*>((*itr));
if(creature && creature->GetCreatureInfo() &&
(creature->GetCreatureInfo()->Id == CN_ENCHANTED_ELEMENTAL ||
creature->GetCreatureInfo()->Id == CN_TAINTED_ELEMENTAL ||
creature->GetCreatureInfo()->Id == CN_COILFANG_STRIDER ||
creature->GetCreatureInfo()->Id == CN_COILFANG_ELITE ||
creature->GetCreatureInfo()->Id == CN_SHIELD_GENERATOR_CHANNEL)
&& creature->isAlive())
creature->Despawn(500, 0);
}
}
_unit->SetUInt64Value(UNIT_FIELD_FLAGS, 0);
_unit->RemoveAura(VASHJ_SHIELD);
_unit->GetAIInterface()->SetAllowedToEnterCombat(true);
_unit->GetAIInterface()->m_canMove = true;
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
}
void OnDied(Unit * mKiller)
{
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Lord Illidan, I... I am... sorry.");
_unit->PlaySoundToSet(11544);
RemoveAIUpdateEvent();
}
void OnTargetDied(Unit* mTarget)
{
switch(rand()%2)
{
case 0:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Your time ends now!");
_unit->PlaySoundToSet(11541);
break;
case 1:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "You have failed!");
_unit->PlaySoundToSet(11542);
break;
}
}
void AIUpdate()
{
switch(Phase)
{
case 1:
case 3:
PhaseOneAndThree();
break;
case 2:
PhaseTwo();
break;
}
}
void PhaseOneAndThree()
{
if(Phase == 3)
{
//WRONG
//sporebats are spawned faster and faster
/*SporebatTimer++;
if(SporebatTimer > 10)
{
Creature *cre = _unit->GetMapMgr()->GetInterface()->SpawnCreature(CN_TOXIC_SPORE_BAT, 29.769f, -866.190f, 43, 0, false, false, 0, 0);
cre->GetAIInterface()->setOutOfCombatRange(1);
SporebatTimer = 0;
}*/
}
else
{
if(_unit->GetHealthPct() <= 70)
{
_unit->RemoveAllAuras();
_unit->GetAIInterface()->SetAllowedToEnterCombat(false);
_unit->GetAIInterface()->StopMovement(0);
_unit->GetAIInterface()->SetAIState(STATE_SCRIPTMOVE);
_unit->GetAIInterface()->setMoveType(MOVEMENTTYPE_WANTEDWP);
_unit->GetAIInterface()->setWaypointToMove(1);
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "The time is now! Leave none standing!");
_unit->PlaySoundToSet(11539);
_unit->SetUInt64Value(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_ATTACKABLE_9);
_unit->CastSpell(_unit, dbcSpell.LookupEntry(VASHJ_SHIELD), true);
_unit->GetAIInterface()->setOutOfCombatRange(3000);
Phase = 2;
}
}
//if nobody is in range, shot or multishot
bool InRange = false;
for(set<Object*>::iterator itr = _unit->GetInRangeSetBegin(); itr != _unit->GetInRangeSetEnd(); ++itr)
{
if(isHostile(_unit, (*itr)) && _unit->GetDistance2dSq((*itr)) < 100) //10 yards
{
InRange = true;
break;
}
}
if(!InRange)
{
Shoot(_unit->GetAIInterface()->GetNextTarget());
}
float val = (float)RandomFloat(100.0f);
SpellCast(val);
}
void PhaseTwo()
{
//WORKAROUND
_unit->setAttackTimer(2000, false);
//Forked Lightning
ForkedLightningTimer--;
if(!ForkedLightningTimer)
{
CastSpellOnRandomTarget(3, 0, 0);
ForkedLightningTimer = 2+rand()%6;
}
//spawn creatures
EnchantedElementalTimer--;
if(!EnchantedElementalTimer)
{
uint32 pos = rand()%8;
Creature *elemental = NULL;
elemental = _unit->GetMapMgr()->GetInterface()->SpawnCreature(CN_ENCHANTED_ELEMENTAL, ElementalSpawnPoints[pos].mX, ElementalSpawnPoints[pos].mY, ElementalSpawnPoints[pos].mZ, ElementalSpawnPoints[pos].mO, false, false, 0, 0);
if(elemental)
{
WayPoint * wp = _unit->CreateWaypointStruct();
wp->id = 1;
wp->x = ElementalSpawnPoints2[pos].mX;
wp->y = ElementalSpawnPoints2[pos].mY;
wp->z = ElementalSpawnPoints2[pos].mZ;
wp->o = ElementalSpawnPoints2[pos].mO;
wp->waittime = 0;
wp->flags = WALK;
wp->forwardemoteoneshot = 0;
wp->forwardemoteid = 0;
wp->backwardemoteoneshot = 0;
wp->backwardemoteid = 0;
wp->forwardskinid = 0;
wp->backwardskinid = 0;
elemental->GetAIInterface()->addWayPoint(wp);
wp = _unit->CreateWaypointStruct();
wp->id = 2;
wp->x = 29.798161f;
wp->y = -923.358276f;
wp->z = 42.900517f;
wp->o = 0.0f;
wp->o = 0;
wp->waittime = 0;
wp->flags = WALK;
wp->forwardemoteoneshot = 0;
wp->forwardemoteid = 0;
wp->backwardemoteoneshot = 0;
wp->backwardemoteid = 0;
wp->forwardskinid = 0;
wp->backwardskinid = 0;
elemental->GetAIInterface()->addWayPoint(wp);
}
EnchantedElementalTimer = 10+rand()%5;
}
CoilfangStriderTimer--;
if(!CoilfangStriderTimer)
{
Creature *summoned = NULL;
summoned = _unit->GetMapMgr()->GetInterface()->SpawnCreature(CN_COILFANG_STRIDER, -29.761278f, -980.252930f, 41.097122f, 0.0f, false, false, 0, 0);
if(summoned)
{
//attack nearest target
Unit *nearest = NULL;
float nearestdist = 0;
for(set<Object*>::iterator itr = summoned->GetInRangeSetBegin(); itr != summoned->GetInRangeSetEnd(); ++itr)
{
if(((*itr)->GetTypeId() == TYPEID_PLAYER || (*itr)->GetTypeId() == TYPEID_UNIT) && isHostile(summoned, (*itr)) && (summoned->GetDistance2dSq((*itr)) < nearestdist || !nearestdist) )
{
nearestdist = summoned->GetDistance2dSq((*itr));
nearest = static_cast<Unit*>((*itr));
}
}
if(nearest)
summoned->GetAIInterface()->AttackReaction(nearest, 1, 0);
}
CoilfangStriderTimer = 60;
}
CoilfangEliteTimer--;
if(!CoilfangEliteTimer)
{
uint32 pos = rand()%4;
Creature *summoned = NULL;
summoned = _unit->GetMapMgr()->GetInterface()->SpawnCreature(CN_COILFANG_ELITE, CoilfangEliteSpawnPoints[pos].mX, CoilfangEliteSpawnPoints[pos].mY, CoilfangEliteSpawnPoints[pos].mZ, CoilfangEliteSpawnPoints[pos].mO, false, false, 0, 0);
if(summoned)
{
//attack nearest target
Unit *nearest = NULL;
float nearestdist = 0;
for(set<Object*>::iterator itr = summoned->GetInRangeSetBegin(); itr != summoned->GetInRangeSetEnd(); ++itr)
{
if(((*itr)->GetTypeId() == TYPEID_PLAYER || (*itr)->GetTypeId() == TYPEID_UNIT) && isHostile(summoned, (*itr)) && (summoned->GetDistance2dSq((*itr)) < nearestdist || !nearestdist) )
{
nearestdist = summoned->GetDistance2dSq((*itr));
nearest = static_cast<Unit*>((*itr));
}
}
if(nearest)
summoned->GetAIInterface()->AttackReaction(nearest, 1, 0);
}
CoilfangEliteTimer = 45;
}
TaintedElementalTimer--;
if(!TaintedElementalTimer)
{
uint32 pos = rand()%8;
_unit->GetMapMgr()->GetInterface()->SpawnCreature(CN_TAINTED_ELEMENTAL, ElementalSpawnPoints[pos].mX, ElementalSpawnPoints[pos].mY, ElementalSpawnPoints[pos].mZ, ElementalSpawnPoints[pos].mO, false, false, 0, 0);
TaintedElementalTimer = 120;
}
if(_unit->GetHealthPct() <= 50)
{
//despawn enchanted elementals
Creature *creature = NULL;
for(set<Object*>::iterator itr = _unit->GetInRangeSetBegin(); itr != _unit->GetInRangeSetEnd(); ++itr)
{
if((*itr)->GetTypeId() == TYPEID_UNIT)
{
creature = static_cast<Creature*>((*itr));
if(creature->GetCreatureInfo() && creature->GetCreatureInfo()->Id == CN_ENCHANTED_ELEMENTAL && creature->isAlive())
creature->Despawn(0, 0);
}
}
_unit->SetUInt64Value(UNIT_FIELD_FLAGS, 0);
_unit->RemoveAura(VASHJ_SHIELD);
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "You may want to take cover.");
_unit->PlaySoundToSet(11540);
_unit->GetAIInterface()->m_canMove = true;
Phase = 3;
}
}
void Shoot(Unit *target)
{
switch(rand()%2)
{
case 0:
//shoot
_unit->CastSpell(target, info_shot, true);
break;
case 1:
//multishot
_unit->CastSpell(target, info_multishot, true);
break;
}
switch(rand()%6)
{
case 0:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Straight to the heart!");
_unit->PlaySoundToSet(11536);
break;
case 1:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Seek your mark!");
_unit->PlaySoundToSet(11537);
break;
}
}
void OnReachWP(uint32 iWaypointId, bool bForwards)
{
switch(iWaypointId)
{
case 1:
_unit->GetAIInterface()->SetAIState(STATE_SCRIPTIDLE);
_unit->GetAIInterface()->m_canMove = false;
//setup shield
Creature *channel = NULL;
for(uint8 i = 0; i < 4; i++)
{
channel = _unit->GetMapMgr()->GetInterface()->SpawnCreature(CN_SHIELD_GENERATOR_CHANNEL, ShieldGeneratorCoords[i][0], ShieldGeneratorCoords[i][1], ShieldGeneratorCoords[i][2], 0, false, false, 0, 0);
if(channel)
{
channel->SetUInt64Value(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
channel->GetAIInterface()->m_canMove = false;
channel->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, _unit->GetGUID());
channel->SetUInt32Value(UNIT_CHANNEL_SPELL, VASHJ_SHIELD);
}
}
break;
}
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i=0;i<nrspells;i++)
{
if(!spells[i].perctrigger) continue;
if(m_spellcheck[i])
{
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant); break;
case TARGET_ATTACKING:
_unit->CastSpell(target, spells[i].info, spells[i].instant);
break;
case TARGET_DESTINATION:
_unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break;
case TARGET_RANDOM_SINGLE:
case TARGET_RANDOM_DESTINATION:
CastSpellOnRandomTarget(i, 0, 0); break;
}
spells[i].casttime = spells[i].cooldown;
m_spellcheck[i] = false;
return;
}
if(spells[i].casttime > 0)
spells[i].casttime--;
if(val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger) && !spells[i].casttime)
{
_unit->setAttackTimer(spells[i].attackstoptimer, false);
m_spellcheck[i] = true;
}
comulativeperc += spells[i].perctrigger;
}
}
}
void CastSpellOnRandomTarget(uint32 i, float mindist2cast, float maxdist2cast)
{
if (!maxdist2cast) maxdist2cast = 100.0f;
Unit* RandomTarget = NULL;
std::vector<Unit*> TargetTable; /* From M4ksiu - Big THX to Capt who helped me with std stuff to make it simple and fully working <3 */
/* If anyone wants to use this function, then leave this note! */
for(set<Object*>::iterator itr = _unit->GetInRangeSetBegin(); itr != _unit->GetInRangeSetEnd(); ++itr)
{
if (isHostile(_unit, (*itr)) && ((*itr)->GetTypeId()== TYPEID_UNIT || (*itr)->GetTypeId() == TYPEID_PLAYER))
{
RandomTarget = (Unit*)(*itr);
if (RandomTarget->isAlive() && _unit->GetDistance2dSq(RandomTarget) >= mindist2cast*mindist2cast && _unit->GetDistance2dSq(RandomTarget) <= maxdist2cast*maxdist2cast)
TargetTable.push_back(RandomTarget);
}
}
if (!TargetTable.size())
return;
Unit * RTarget = *(TargetTable.begin()+rand()%TargetTable.size());
if (!RTarget)
return;
switch (spells[i].targettype)
{
case TARGET_RANDOM_SINGLE:
_unit->CastSpell(RTarget, spells[i].info, spells[i].instant); break;
case TARGET_RANDOM_DESTINATION:
_unit->CastSpellAoF(RTarget->GetPositionX(), RTarget->GetPositionY(), RTarget->GetPositionZ(), spells[i].info, spells[i].instant); break;
}
TargetTable.clear();
}
uint32 TaintedElementalTimer;
uint32 Phase;
protected:
int nrspells;
uint32 EnchantedElementalTimer;
uint32 CoilfangStriderTimer;
uint32 CoilfangEliteTimer;
uint32 SporebatTimer;
uint32 ForkedLightningTimer;
SpellEntry *info_multishot;
SpellEntry *info_shot;
};
class TaintedElementalAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(TaintedElementalAI);
TaintedElementalAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
spell_poison_spit = new AI_Spell();
spell_poison_spit->agent = AGENT_SPELL;
spell_poison_spit->procChance = 0;
spell_poison_spit->spell = dbcSpell.LookupEntry(POISON_SPIT);
spell_poison_spit->spellType = STYPE_DAMAGE;
spell_poison_spit->spelltargetType = TTYPE_SINGLETARGET;
spell_poison_spit->cooldown = 2000;
spell_poison_spit->cooldowntime = 0;
spell_poison_spit->procCount = 0;
spell_poison_spit->procCounter = 0;
spell_poison_spit->minrange = 0;
spell_poison_spit->maxrange = 30;
_unit->GetAIInterface()->m_canMove = false;
}
void OnCombatStart(Unit *mTarget)
{
_unit->GetAIInterface()->setCurrentAgent(AGENT_SPELL);
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
}
void OnCombatStop(Unit *mTarget)
{
RemoveAIUpdateEvent();
}
void OnDied(Unit * mKiller)
{
Creature *Vashj = NULL;
Vashj = _unit->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(_unit->GetPositionX(), _unit->GetPositionY(), _unit->GetPositionZ(), CN_LADY_VASHJ);
if(Vashj)
{
if(static_cast<VashjAI*>(Vashj->GetScript())->TaintedElementalTimer > 50)
static_cast<VashjAI*>(Vashj->GetScript())->TaintedElementalTimer = 50;
}
}
void AIUpdate()
{
//TODO: Despawn after 15 secs
if(_unit->GetCurrentSpell() == NULL)
_unit->GetAIInterface()->SetNextSpell(spell_poison_spit);
}
private:
AI_Spell *spell_poison_spit;
};
class TaintedCoreGO : public GameObjectAIScript
{
public:
TaintedCoreGO(GameObject *pGameObject) : GameObjectAIScript(pGameObject)
{
}
void OnActivate(Player *pPlayer)
{
Creature *Vashj = NULL;
Vashj = pPlayer->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(29.798161f, -923.358276f, 42.900517f, CN_LADY_VASHJ);
if( Vashj != NULL && static_cast<VashjAI*>(Vashj->GetScript())->Phase == 2 )
{
Vashj->ModUnsigned32Value(UNIT_FIELD_HEALTH, -((Vashj->GetUInt32Value(UNIT_FIELD_MAXHEALTH)/100)*5) );
Creature *channel = NULL;
channel = pPlayer->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(pPlayer->GetPositionX(), pPlayer->GetPositionY(), pPlayer->GetPositionZ(), CN_SHIELD_GENERATOR_CHANNEL);
if(channel != NULL && channel->IsInWorld() )
channel->Despawn(0, 0);
}
}
void Destroy()
{
delete this;
}
static GameObjectAIScript *Create(GameObject *pGameObject) { return new TaintedCoreGO(pGameObject); }
};
class ToxicSporeBatAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(ToxicSporeBatAI);
SP_AI_Spell spells[1];
bool m_spellcheck[1];
ToxicSporeBatAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
/************************ Waypoint Place ************************/
m_entry = pCreature->GetEntry();
_unit->GetAIInterface()->addWayPoint(CreateWaypoint(1, 0, FLY));
_unit->GetAIInterface()->addWayPoint(CreateWaypoint(2, 0, FLY));
_unit->GetAIInterface()->addWayPoint(CreateWaypoint(3, 0, FLY));
_unit->GetAIInterface()->addWayPoint(CreateWaypoint(4, 0, FLY));
_unit->GetAIInterface()->addWayPoint(CreateWaypoint(5, 0, FLY));
_unit->GetAIInterface()->addWayPoint(CreateWaypoint(6, 0, FLY));
_unit->GetAIInterface()->addWayPoint(CreateWaypoint(7, 0, FLY));
_unit->GetAIInterface()->addWayPoint(CreateWaypoint(8, 0, FLY));
_unit->GetAIInterface()->addWayPoint(CreateWaypoint(9, 0, FLY));
_unit->GetAIInterface()->addWayPoint(CreateWaypoint(10, 0, FLY));
_unit->GetAIInterface()->addWayPoint(CreateWaypoint(11, 0, FLY));
_unit->GetAIInterface()->addWayPoint(CreateWaypoint(12, 0, FLY));
/************************** Spells ****************************/
nrspells = 1;
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
spells[0].info = dbcSpell.LookupEntry(TOXIC_SPORES);
spells[0].targettype = TARGET_VARIOUS;
spells[0].instant = true;
spells[0].cooldown = -1;
spells[0].perctrigger = 0.0f;
spells[0].attackstoptimer = 1000;
/******************* Additional Settings *******************/
Phase = 0;
FlameQuills = false;
Meteor = false;
PositionChange=rand()%8+15;
PhoenixSummon=rand()%6+17;
_unit->GetAIInterface()->m_moveFly = true;
_unit->GetAIInterface()->StopMovement(0);
_unit->GetAIInterface()->SetAIState(STATE_SCRIPTMOVE);
_unit->GetAIInterface()->setMoveType(MOVEMENTTYPE_WANTEDWP);
_unit->GetAIInterface()->setWaypointToMove(1);
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
}
void OnCombatStart(Unit* mTarget)
{
//_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Phase 1 Test!");
_unit->PlaySoundToSet(11243);
_unit->GetAIInterface()->SetAIState(STATE_SCRIPTIDLE);
_unit->GetAIInterface()->setMoveType(MOVEMENTTYPE_DONTMOVEWP);
CastTime();
Phase = 1;
FlameQuills = false;
Meteor = false;
PositionChange=rand()%8+15; // 30-45sec /*** if attack time 1000 (%15+31) ***/
PhoenixSummon=rand()%6+17; // 34-44sec /*** if attack time 1000 (%11+34) ***/
FlyWay=rand()%2;
switch (FlyWay)
{
case 0: // Clock like
_unit->GetAIInterface()->setMoveType(MOVEMENTTYPE_WANTEDWP);
_unit->GetAIInterface()->setWaypointToMove(6);
break;
case 1: // hmm... other?
_unit->GetAIInterface()->setMoveType(MOVEMENTTYPE_WANTEDWP);
_unit->GetAIInterface()->setWaypointToMove(9);
break;
}
//RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME)); // Taken from here to add more abilities to code
}
void CastTime()
{
for(int i=0;i<nrspells;i++)
spells[i].casttime = spells[i].cooldown;
}
void OnCombatStop(Unit *mTarget)
{
Phase = 0;
FlameQuills = false;
Meteor = false;
PhoenixSummon=rand()%6+17;
PositionChange=rand()%8+15;
CastTime();
_unit->GetAIInterface()->StopMovement(0);
_unit->GetAIInterface()->SetAIState(STATE_SCRIPTMOVE);
_unit->GetAIInterface()->setMoveType(MOVEMENTTYPE_WANTEDWP);
_unit->GetAIInterface()->setWaypointToMove(1);
//_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
//_unit->GetAIInterface()->SetAIState(STATE_IDLE);
//RemoveAIUpdateEvent();
}
void OnDied(Unit * mKiller)
{
Phase = 0;
FlameQuills = false;
Meteor = false;
PositionChange=rand()%8+15;
PhoenixSummon=rand()%6+17;
CastTime();
//RemoveAIUpdateEvent();
}
void AIUpdate()
{
if (FlameQuills == true)
{
QuillsCount++;
if (QuillsCount == 9)
{
FlameQuills = false;
switch (FlyWay)
{
case 0: // Clock like
_unit->GetAIInterface()->setMoveType(MOVEMENTTYPE_WANTEDWP);
_unit->GetAIInterface()->setWaypointToMove(6);
break;
case 1: // hmm... other?
_unit->GetAIInterface()->setMoveType(MOVEMENTTYPE_WANTEDWP);
_unit->GetAIInterface()->setWaypointToMove(9);
break;
}
}
_unit->CastSpell(_unit, spells[1].info, spells[1].instant);
}
if (Meteor == true)
{
}
else
{
switch (Phase)
{
case 0: return;
case 1:
{
PhaseOne();
}break;
case 2:
{
PhaseTwo();
}break;
default:
{
Phase = 0;
};
};
}
//float val = (float)RandomFloat(100.0f);
//SpellCast(val);
}
void PhaseOne()
{
PositionChange--;
PhoenixSummon--;
if (_unit->GetHealthPct() == 0)
{
Phase = 2;
_unit->CastSpell(_unit, spells[6].info, spells[6].instant);
}
if (!PhoenixSummon--)
{
_unit->CastSpell(_unit, spells[2].info, spells[2].instant);
PhoenixSummon=rand()%6+17;
}
if (!PositionChange)
{
_unit->GetAIInterface()->setMoveType(MOVEMENTTYPE_WANTEDWP);
_unit->GetAIInterface()->setWaypointToMove(NextWP);
PositionChange=rand()%8+17; // added 4 sec fit time + time needed to move to next pos.
}
else
{
uint32 val = RandomUInt(100);
if (val > 0 && val < 5) // Flame Quills wp here!
{
_unit->GetAIInterface()->setMoveType(MOVEMENTTYPE_WANTEDWP);
_unit->GetAIInterface()->setWaypointToMove(10);
}
}
}
void PhaseTwo()
{
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i=0;i<nrspells;i++)
{
spells[i].casttime--;
if (m_spellcheck[i])
{
spells[i].casttime = spells[i].cooldown;
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant); break;
case TARGET_ATTACKING:
_unit->CastSpell(target, spells[i].info, spells[i].instant); break;
case TARGET_DESTINATION:
_unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break;
}
if (spells[i].speech != "")
{
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, spells[i].speech.c_str());
_unit->PlaySoundToSet(spells[i].soundid);
}
m_spellcheck[i] = false;
return;
}
if ((val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger)) || !spells[i].casttime)
{
_unit->setAttackTimer(spells[i].attackstoptimer, false);
m_spellcheck[i] = true;
}
comulativeperc += spells[i].perctrigger;
}
}
}
void OnReachWP(uint32 iWaypointId, bool bForwards)
{
if (Phase == 1)
{
_unit->GetAIInterface()->setMoveType(MOVEMENTTYPE_WANTEDWP);
_unit->GetAIInterface()->setWaypointToMove(6);
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Phase 1 Test!");
_unit->PlaySoundToSet(11243);
}
switch(iWaypointId)
{
case 1: // First fly point
_unit->GetAIInterface()->setMoveType(MOVEMENTTYPE_WANTEDWP);
_unit->GetAIInterface()->setWaypointToMove(2);
break;
case 2:
_unit->GetAIInterface()->setMoveType(MOVEMENTTYPE_WANTEDWP);
_unit->GetAIInterface()->setWaypointToMove(3);
break;
case 3:
_unit->GetAIInterface()->setMoveType(MOVEMENTTYPE_WANTEDWP);
_unit->GetAIInterface()->setWaypointToMove(4);
break;
case 4:
_unit->GetAIInterface()->setMoveType(MOVEMENTTYPE_WANTEDWP);
_unit->GetAIInterface()->setWaypointToMove(5);
break;
case 5:
_unit->GetAIInterface()->setMoveType(MOVEMENTTYPE_WANTEDWP);
_unit->GetAIInterface()->setWaypointToMove(1); // Last fly point (flyback to point 1 - reset)
break;
case 6:
{
_unit->GetAIInterface()->SetAIState(STATE_SCRIPTIDLE);
_unit->GetAIInterface()->setMoveType(MOVEMENTTYPE_DONTMOVEWP);
_unit->GetAIInterface()->m_canMove = false;
switch (FlyWay)
{
case 0:
NextWP = 7;
break;
case 1:
NextWP = 9;
break;
}
}
break;
case 7:
{
_unit->GetAIInterface()->SetAIState(STATE_SCRIPTIDLE);
_unit->GetAIInterface()->setMoveType(MOVEMENTTYPE_DONTMOVEWP);
_unit->GetAIInterface()->m_canMove = false;
switch (FlyWay)
{
case 0:
NextWP = 8;
break;
case 1:
NextWP = 6;
break;
}
}
break;
case 8:
{
_unit->GetAIInterface()->m_canMove = false;
_unit->GetAIInterface()->SetAIState(STATE_SCRIPTIDLE);
_unit->GetAIInterface()->setMoveType(MOVEMENTTYPE_DONTMOVEWP);
switch (FlyWay)
{
case 0:
NextWP = 9;
break;
case 1:
NextWP = 7;
break;
}
}
break;
case 9:
{
_unit->GetAIInterface()->m_canMove = false;
_unit->GetAIInterface()->SetAIState(STATE_SCRIPTIDLE);
_unit->GetAIInterface()->setMoveType(MOVEMENTTYPE_DONTMOVEWP);
switch (FlyWay)
{
case 0:
NextWP = 6;
break;
case 1:
NextWP = 8;
break;
}
}
break;
case 10:
{
_unit->GetAIInterface()->SetAIState(STATE_SCRIPTIDLE);
_unit->GetAIInterface()->setMoveType(MOVEMENTTYPE_DONTMOVEWP);
if (Phase == 1)
{
FlameQuills = true;
QuillsCount = 0;
}
if (Phase == 2)
{
Meteor = true;
}
}
break;
}
}
inline WayPoint* CreateWaypoint(int id, uint32 waittime, uint32 flags)
{
WayPoint * wp = _unit->CreateWaypointStruct();
wp->id = id;
wp->x = fly[id].mX;
wp->y = fly[id].mY;
wp->z = fly[id].mZ;
wp->o = fly[id].mO;
wp->waittime = waittime;
wp->flags = flags;
wp->forwardemoteoneshot = 0;
wp->forwardemoteid = 0;
wp->backwardemoteoneshot = 0;
wp->backwardemoteid = 0;
wp->forwardskinid = 0;
wp->backwardskinid = 0;
return wp;
}
protected:
bool FlameQuills;
uint32 QuillsCount;
bool Meteor;
int PositionChange;
int PhoenixSummon;
uint32 NextWP;
uint32 m_entry;
uint32 FlyWay;
uint32 Phase;
int nrspells;
};
//------------------------------------
// -= Trash Mobs =-
//------------------------------------
//Coilfang Ambusher
#define CN_COILFANG_AMBUSHER 21865
#define CA_MULTI_SHOT 27021
class CoilfangAmbusherAI : public MoonScriptCreatureAI
{
public:
ADD_CREATURE_FACTORY_FUNCTION(CoilfangAmbusherAI);
CoilfangAmbusherAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature)
{
AddSpell(CA_MULTI_SHOT, Target_Self, 10.0f, 0, 0);
}
};
//Coilfang Fathom-Witch
#define CN_COILFANG_FATHOM_WITCH 21299
#define SHADOW_BOLT 27209
#define WHIRLWIND_KNOCKBACK 34109
class CoilfangFathomWitchAI : public MoonScriptCreatureAI
{
public:
ADD_CREATURE_FACTORY_FUNCTION(CoilfangFathomWitchAI);
CoilfangFathomWitchAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature)
{
AddSpell(SHADOW_BOLT, Target_Current, 2.0f, 0, 0);
AddSpell(WHIRLWIND_KNOCKBACK, Target_Self, 2.0f, 0, 0);
}
};
//Coilfang Guardian
#define CN_COILFANG_GUARDIAN 21873
#define CLEAVE 38260
class CoilfangGuardianAI : public MoonScriptCreatureAI
{
public:
ADD_CREATURE_FACTORY_FUNCTION(CoilfangGuardianAI);
CoilfangGuardianAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature)
{
AddSpell(CLEAVE, Target_Destination, 3.0f, 0, 0);
}
};
//Coilfang Priestess
#define CN_COILFANG_PRIESTESS 21220
#define HOLY_NOVA 38589
#define SMITE 25364
#define SPIRIT_OF_REDEMPTION 35618
class CoilfangPriestessAI : public MoonScriptCreatureAI
{
public:
ADD_CREATURE_FACTORY_FUNCTION(CoilfangPriestessAI);
CoilfangPriestessAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature)
{
AddSpell(HOLY_NOVA, Target_Self, 2.0f, 0, 0);
AddSpell(SMITE, Target_Current, 1.0f, 2, 0);
AddSpell(SPIRIT_OF_REDEMPTION, Target_Self, 2.0f, 0, 0);
}
};
//Underbog Colossus
#define CN_UNDERBOG_COLOSSUS 21251
#define ACID_GEYSER 37959
#define ATROPIC_BLOW 39015
#define SPORE_QUAKE 38976
#define TOXIC_POOL 38718
#define FRENZY 37605
#define RAMPANT_INFECTION 39042
#define PARASITE 39044
class UnderbogColossusAI : public MoonScriptCreatureAI
{
public:
ADD_CREATURE_FACTORY_FUNCTION(UnderbogColossusAI);
UnderbogColossusAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature)
{
//these mobs pick from a random set of abilities
switch(rand()%3)
{
case 0:
AddSpell(RAMPANT_INFECTION, Target_Self, 5.0f, 0, 0);
AddSpell(SPORE_QUAKE, Target_Self, 2.0f, 0, 0);
break;
case 1:
AddSpell(ACID_GEYSER, Target_Destination, 10.0f, 0, 0);
AddSpell(PARASITE, Target_Current, 2.0f, 0, 0);
break;
case 2:
AddSpell(FRENZY, Target_Self, 10.0f, 0, 0);
break;
}
}
void OnDied(Unit* pKiller)
{
//There will also be a choice of abilities he might use as he dies:
switch(rand()%3)
{
case 0:
//cast toxic pool
_unit->CastSpell(_unit, dbcSpell.LookupEntry(TOXIC_POOL), true);
break;
case 1:
//spawn two colossus lurkers
_unit->GetMapMgr()->GetInterface()->SpawnCreature(22347, _unit->GetPositionX(), _unit->GetPositionY(), _unit->GetPositionZ(), 0, true, false, 0, 0);
_unit->GetMapMgr()->GetInterface()->SpawnCreature(22347, _unit->GetPositionX(), _unit->GetPositionY(), _unit->GetPositionZ(), 0, true, false, 0, 0);
break;
default:
//Nothing!
break;
//Many small adds, TODO
//Refreshing mist, TODO
}
MoonScriptCreatureAI::OnDied(pKiller);
}
};
//Tidewalker Warrior
#define CN_TIDEWALKER_WARRIOR 21225
#define TW_CLEAVE 38260
#define TW_BLOODTHIRST 30335 //INSTANT
#define TW_FRENZY 37605
class TidewalkerWarriorAI : public MoonScriptCreatureAI
{
public:
ADD_CREATURE_FACTORY_FUNCTION(TidewalkerWarriorAI);
TidewalkerWarriorAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature)
{
AddSpell(TW_CLEAVE, Target_Destination, 1.0f, 0, 0);
AddSpell(TW_BLOODTHIRST, Target_Current, 1.0f, -1, 0); //-1 means instant
AddSpell(TW_FRENZY, Target_Self, 2.0f, 0, 0);
}
};
//Coilfang Serpentguard
#define CN_COILFANG_SERPENTGUARD 21298
#define CSERP_CLEAVE 38260
#define CSERP_REFLECTION 36096
#define CSERP_DEVOTION 38603
class CoilfangSerpentguardAI : public MoonScriptCreatureAI
{
public:
ADD_CREATURE_FACTORY_FUNCTION(CoilfangSerpentguardAI);
CoilfangSerpentguardAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature)
{
AddSpell(CSERP_CLEAVE, Target_Destination, 1.0f, 0, 0);
AddSpell(CSERP_REFLECTION, Target_Self, 0.5f, 0, 0);
AddSpell(CSERP_DEVOTION, Target_Self, 1.0f, 0, 0);
}
};
//Coilfang Shatterer
#define CN_COILFANG_SHATTERER 21301
#define CSHATT_ARMOR 38591
class CoilfangShattererAI : public MoonScriptCreatureAI
{
public:
ADD_CREATURE_FACTORY_FUNCTION(CoilfangShattererAI);
CoilfangShattererAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature)
{
AddSpell(CSHATT_ARMOR, Target_Current, 2.0f, 0, 0);
}
};
//Coilfang Strider
#define CN_COILFANG_STRIDER 22056
#define CSTRID_SCREAM 10890
class CoilfangStriderAI : public MoonScriptCreatureAI
{
public:
ADD_CREATURE_FACTORY_FUNCTION(CoilfangStriderAI);
CoilfangStriderAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature)
{
AddSpell(CSTRID_SCREAM, Target_Current, 2.0f, 0, 0);
}
};
void SetupSerpentshrineCavern(ScriptMgr * mgr)
{
mgr->register_creature_script(CN_HYDROSS_THE_UNSTABLE, &HydrossTheUnstableAI::Create);
mgr->register_creature_script(CN_THE_LURKER_BELOW, &LurkerAI::Create);
//Leotheras the Blind event
mgr->register_creature_script(CN_LEOTHERAS_THE_BLIND, &LeotherasAI::Create);
mgr->register_creature_script(CN_GREYHEART_SPELLBINDER, &GreyheartSpellbinderAI::Create);
mgr->register_creature_script(CN_SHADOW_OF_LEOTHERAS, &ShadowofLeotherasAI::Create);
mgr->register_dummy_spell(CHAOS_BLAST_ANIMATION, &ChaosBlast);
//Morogrim Tidewalker event
mgr->register_creature_script(CN_MOROGRIM_TIDEWALKER, &MorogrimAI::Create);
mgr->register_creature_script(CN_TIDEWALKER_LURKER, &TidewalkerLurkerAI::Create);
//Fathom-Lord Karathress event
mgr->register_creature_script(CN_FATHOM_LORD_KARATHRESS, &KarathressAI::Create);
mgr->register_creature_script(CN_FATHOM_GUARD_CARIBDIS, &FathomGuardCaribdisAI::Create);
mgr->register_creature_script(CN_FATHOM_GUARD_TIDALVESS, &FathomGuardTidalvessAI::Create);
mgr->register_creature_script(CN_FATHOM_GUARD_SHARKKIS, &FathomGuardSharkissAI::Create);
//Lady Vashj event
mgr->register_creature_script(CN_LADY_VASHJ, &VashjAI::Create);
//mgr->register_creature_script(CN_TOXIC_SPORE_BAT, &ToxicSporeBatAI::Create);
mgr->register_creature_script(CN_COILFANG_STRIDER, &CoilfangStriderAI::Create);
mgr->register_creature_script(CN_ENCHANTED_ELEMENTAL, &EnchantedElementalAI::Create);
mgr->register_creature_script(CN_TAINTED_ELEMENTAL, &TaintedElementalAI::Create);
// Shield Generator
mgr->register_gameobject_script(185051, &TaintedCoreGO::Create);
//Trash mobs
mgr->register_creature_script(CN_COILFANG_AMBUSHER, &CoilfangAmbusherAI::Create);
mgr->register_creature_script(CN_COILFANG_FATHOM_WITCH, &CoilfangFathomWitchAI::Create);
mgr->register_creature_script(CN_COILFANG_GUARDIAN, &CoilfangGuardianAI::Create);
mgr->register_creature_script(CN_COILFANG_PRIESTESS, &CoilfangPriestessAI::Create);
mgr->register_creature_script(CN_UNDERBOG_COLOSSUS, &UnderbogColossusAI::Create);
mgr->register_creature_script(CN_TIDEWALKER_WARRIOR, &TidewalkerWarriorAI::Create);
mgr->register_creature_script(CN_COILFANG_SERPENTGUARD, &CoilfangSerpentguardAI::Create);
mgr->register_creature_script(CN_COILFANG_SHATTERER, &CoilfangShattererAI::Create);
}
| [
"[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef",
"[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef"
]
| [
[
[
1,
4
],
[
6,
86
],
[
88,
228
],
[
230,
312
],
[
314,
648
],
[
650,
757
],
[
764,
768
],
[
775,
849
],
[
855,
1219
],
[
1223,
1223
],
[
1225,
1733
],
[
1735,
2005
],
[
2012,
2236
],
[
2238,
2456
],
[
2458,
2459
],
[
2461,
2461
],
[
2463,
2463
],
[
2475,
2477
],
[
2484,
3121
],
[
3125,
3135
]
],
[
[
5,
5
],
[
87,
87
],
[
229,
229
],
[
313,
313
],
[
649,
649
],
[
758,
763
],
[
769,
774
],
[
850,
854
],
[
1220,
1222
],
[
1224,
1224
],
[
1734,
1734
],
[
2006,
2011
],
[
2237,
2237
],
[
2457,
2457
],
[
2460,
2460
],
[
2462,
2462
],
[
2464,
2474
],
[
2478,
2483
],
[
3122,
3124
]
]
]
|
0f46d512e2b9299da81b83541e666d0535b249bf | 58ef4939342d5253f6fcb372c56513055d589eb8 | /MP3EncodeDLL/src/MP3EncodeDLLDllMain.cpp | 7bf9311e6f3cbe2aad5638b169907f1df22de282 | []
| no_license | flaithbheartaigh/lemonplayer | 2d77869e4cf787acb0aef51341dc784b3cf626ba | ea22bc8679d4431460f714cd3476a32927c7080e | refs/heads/master | 2021-01-10T11:29:49.953139 | 2011-04-25T03:15:18 | 2011-04-25T03:15:18 | 50,263,327 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 865 | cpp | /*
============================================================================
Name : MP3EncodeDLLDll.cpp
Author : zengcity
Copyright : Your copyright notice
Description : MP3EncodeDLLDll.cpp - main DLL source
============================================================================
*/
// Include Files
#include <e32std.h> // GLDEF_C
#include "MP3EncodeDLL.pan" // panic codes
// Global Functions
GLDEF_C void Panic(TMP3EncodeDLLPanic aPanic)
// Panics the thread with given panic code
{
User::Panic(_L("MP3EncodeDLL"), aPanic);
}
// Exported Functions
#ifndef EKA2 // for EKA1 only
EXPORT_C TInt E32Dll(TDllReason /*aReason*/)
// Called when the DLL is loaded and unloaded. Note: have to define
// epoccalldllentrypoints in MMP file to get this called in THUMB.
{
return KErrNone;
}
#endif
| [
"zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494"
]
| [
[
[
1,
34
]
]
]
|
c48377a04a945aa8cb209e54150c18210abcdd04 | 9ad9345e116ead00be7b3bd147a0f43144a2e402 | /SEEDMinerGUIApplication/SEEDMinerGUIMFC/SEEDMinerGUIApplication/shockwaveflash.h | 3cd18ee35763ad6575c61c9e7605e5571d642730 | []
| 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 | 4,875 | h | #if !defined(AFX_SHOCKWAVEFLASH_H__25C8E7FC_0F3B_4493_8694_3116C2D46669__INCLUDED_)
#define AFX_SHOCKWAVEFLASH_H__25C8E7FC_0F3B_4493_8694_3116C2D46669__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// Machine generated IDispatch wrapper class(es) created by Microsoft Visual C++
// NOTE: Do not modify the contents of this file. If this class is regenerated by
// Microsoft Visual C++, your modifications will be overwritten.
/////////////////////////////////////////////////////////////////////////////
// CShockwaveFlash wrapper class
class CShockwaveFlash : public CWnd
{
protected:
DECLARE_DYNCREATE(CShockwaveFlash)
public:
CLSID const& GetClsid()
{
static CLSID const clsid
= { 0xd27cdb6e, 0xae6d, 0x11cf, { 0x96, 0xb8, 0x44, 0x45, 0x53, 0x54, 0x0, 0x0 } };
return clsid;
}
virtual BOOL Create(LPCTSTR lpszClassName,
LPCTSTR lpszWindowName, DWORD dwStyle,
const RECT& rect,
CWnd* pParentWnd, UINT nID,
CCreateContext* pContext = NULL)
{ return CreateControl(GetClsid(), lpszWindowName, dwStyle, rect, pParentWnd, nID); }
BOOL Create(LPCTSTR lpszWindowName, DWORD dwStyle,
const RECT& rect, CWnd* pParentWnd, UINT nID,
CFile* pPersist = NULL, BOOL bStorage = FALSE,
BSTR bstrLicKey = NULL)
{ return CreateControl(GetClsid(), lpszWindowName, dwStyle, rect, pParentWnd, nID,
pPersist, bStorage, bstrLicKey); }
// Attributes
public:
// Operations
public:
long GetReadyState();
long GetTotalFrames();
BOOL GetPlaying();
void SetPlaying(BOOL bNewValue);
long GetQuality();
void SetQuality(long nNewValue);
long GetScaleMode();
void SetScaleMode(long nNewValue);
long GetAlignMode();
void SetAlignMode(long nNewValue);
long GetBackgroundColor();
void SetBackgroundColor(long nNewValue);
BOOL GetLoop();
void SetLoop(BOOL bNewValue);
CString GetMovie();
void SetMovie(LPCTSTR lpszNewValue);
long GetFrameNum();
void SetFrameNum(long nNewValue);
void SetZoomRect(long left, long top, long right, long bottom);
void Zoom(long factor);
void Pan(long x, long y, long mode);
void Play();
void Stop();
void Back();
void Forward();
void Rewind();
void StopPlay();
void GotoFrame(long FrameNum);
long CurrentFrame();
BOOL IsPlaying();
long PercentLoaded();
BOOL FrameLoaded(long FrameNum);
long FlashVersion();
CString GetWMode();
void SetWMode(LPCTSTR lpszNewValue);
CString GetSAlign();
void SetSAlign(LPCTSTR lpszNewValue);
BOOL GetMenu();
void SetMenu(BOOL bNewValue);
CString GetBase();
void SetBase(LPCTSTR lpszNewValue);
CString GetScale();
void SetScale(LPCTSTR lpszNewValue);
BOOL GetDeviceFont();
void SetDeviceFont(BOOL bNewValue);
BOOL GetEmbedMovie();
void SetEmbedMovie(BOOL bNewValue);
CString GetBGColor();
void SetBGColor(LPCTSTR lpszNewValue);
CString GetQuality2();
void SetQuality2(LPCTSTR lpszNewValue);
void LoadMovie(long layer, LPCTSTR url);
void TGotoFrame(LPCTSTR target, long FrameNum);
void TGotoLabel(LPCTSTR target, LPCTSTR label);
long TCurrentFrame(LPCTSTR target);
CString TCurrentLabel(LPCTSTR target);
void TPlay(LPCTSTR target);
void TStopPlay(LPCTSTR target);
void SetVariable(LPCTSTR name, LPCTSTR value);
CString GetVariable(LPCTSTR name);
void TSetProperty(LPCTSTR target, long property, LPCTSTR value);
CString TGetProperty(LPCTSTR target, long property);
void TCallFrame(LPCTSTR target, long FrameNum);
void TCallLabel(LPCTSTR target, LPCTSTR label);
void TSetPropertyNum(LPCTSTR target, long property, double value);
double TGetPropertyNum(LPCTSTR target, long property);
double TGetPropertyAsNumber(LPCTSTR target, long property);
CString GetSWRemote();
void SetSWRemote(LPCTSTR lpszNewValue);
CString GetFlashVars();
void SetFlashVars(LPCTSTR lpszNewValue);
CString GetAllowScriptAccess();
void SetAllowScriptAccess(LPCTSTR lpszNewValue);
CString GetMovieData();
void SetMovieData(LPCTSTR lpszNewValue);
LPUNKNOWN GetInlineData();
void SetInlineData(LPUNKNOWN newValue);
BOOL GetSeamlessTabbing();
void SetSeamlessTabbing(BOOL bNewValue);
void EnforceLocalSecurity();
BOOL GetProfile();
void SetProfile(BOOL bNewValue);
CString GetProfileAddress();
void SetProfileAddress(LPCTSTR lpszNewValue);
long GetProfilePort();
void SetProfilePort(long nNewValue);
CString CallFunction(LPCTSTR request);
void SetReturnValue(LPCTSTR returnValue);
void DisableLocalSecurity();
CString GetAllowNetworking();
void SetAllowNetworking(LPCTSTR lpszNewValue);
CString GetAllowFullScreen();
void SetAllowFullScreen(LPCTSTR lpszNewValue);
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_SHOCKWAVEFLASH_H__25C8E7FC_0F3B_4493_8694_3116C2D46669__INCLUDED_)
| [
"buddhi.1986@c7f6ba40-6498-11de-987a-95e5a5a5d5f1"
]
| [
[
[
1,
143
]
]
]
|
ff52bd7739eea3e64e4a524a84ef59b607c0c02b | 7985054c887810f37345f6508f1a7d4fdc65b81b | /Development/Core/GameSocket.cpp | e8c19f1b26875942557b8681f0ab18afa11182bf | []
| no_license | ghostuser846/venicelight | 95e625a8e9cb8dd3d357318c931ee9247420c28d | cdc5dfac8fbaa82d3d5eeb7d21a64c3e206b7ee2 | refs/heads/master | 2021-01-01T06:44:51.163612 | 2009-06-01T02:09:27 | 2009-06-01T02:09:27 | 37,787,439 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,542 | cpp | /*
* Copyright (C) 2005-2008 SREmu <http://www.sremu.org/>
*
* 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 "GameSocket.h"
#include "ObjectMgr.h"
void GameSocket::ProcessData(unsigned char* data, int size)
{
Reader.SetBuffer(data);
int offset = 0;
while(offset < size)
{
unsigned short psize = Reader.ReadWord() + 6;
unsigned short opcode = Reader.ReadWord();
Reader.Skip(2);
switch(opcode) {
case GAME_CLIENT_KEEP_ALIVE:
case GAME_CLIENT_ACCEPT_HANDSHAKE:
break;
case GAME_CLIENT_INFO:
SendServerInfo();
break;
case GAME_CLIENT_PATCH_REQUEST:
SendPatchInfo();
break;
case GAME_CLIENT_AUTH:
OnAuth();
break;
case GAME_CLIENT_CHARACTER:
OnCharacter();
break;
case GAME_CLIENT_INGAME_REQUEST:
OnIngameRequest();
break;
case GAME_CLIENT_MOVEMENT:
OnMovement();
break;
case GAME_CLIENT_CLOSE:
OnGameQuit();
break;
case GAME_CLIENT_CHAT:
OnChat();
break;
case GAME_CLIENT_ITEM_MOVE:
OnItem();
break;
case GAME_CLIENT_TARGET:
OnTarget();
break;
case GAME_CLIENT_INGAME_NOTIFY:
OnIngameNotify();
break;
case GAME_CLIENT_GM:
OnGM();
break;
default:
printf("Unknown opcode: %.4x\n", opcode);
}
Reader.Reset();
Reader.Skip(psize);
offset += psize;
}
Reader.Reset();
}
void GameSocket::ReceiveThread(LPVOID s)
{
GameSocket Client(*((SOCKET*)s));
Client.Init();
Client.Receive();
}
void GameSocket::UpdateCharacter()
{
/* This should update everything from the Player struct. */
db.Query("update characters set xsect=%d, ysect=%d, xpos=%d, ypos=%d, zpos=%d where id=%d",
Player.Position.XSector,
Player.Position.YSector,
int(Player.Position.X),
int(Player.Position.Y),
int(Player.Position.Z),
Player.General.CharacterID)
.execute();
// Update items
Player.Items.UpdateItems(Player.General.CharacterID);
}
GameSocket::~GameSocket()
{
if(Player.Flags.Ingame)
{
DespawnMe(); // Tell other players that we're gone.
UpdateCharacter(); // Save changes to DB
Objects.Players.erase(Player.General.UniqueID); // Delete our map.
}
}
void GameSocket::OnGameQuit()
{
unsigned char type = Reader.ReadByte(); /* Exit or Restart */
const unsigned char countdown = 5;
Writer.Create(GAME_SERVER_COUNTDOWN);
Writer.WriteByte (1);
Writer.WriteByte (countdown);
Writer.WriteByte (type);
Writer.Finalize();
Send(Writer.Buffer, Writer.Size());
/* We will want to interrupt this cooldown on movement or quit cancel. */
Sleep(countdown * 1000);
Writer.Create(GAME_SERVER_QUIT_GAME);
Writer.Finalize();
Send(Writer.Buffer, Writer.Size());
Close(); /* Just making sure :) */
} | [
"dayanfernandez@c3741f72-2d1a-11de-9401-6341fb89ae7c"
]
| [
[
[
1,
152
]
]
]
|
ff75f04a0fd79ec7d94be1537ea36d3c0154a925 | b8fbe9079ce8996e739b476d226e73d4ec8e255c | /src/engine/rb_core/jmethodattr.h | 40f6a6f7ac879f1d13f9d562c5d7cf665ef81a69 | []
| no_license | dtbinh/rush | 4294f84de1b6e6cc286aaa1dd48cf12b12a467d0 | ad75072777438c564ccaa29af43e2a9fd2c51266 | refs/heads/master | 2021-01-15T17:14:48.417847 | 2011-06-16T17:41:20 | 2011-06-16T17:41:20 | 41,476,633 | 1 | 0 | null | 2015-08-27T09:03:44 | 2015-08-27T09:03:44 | null | UTF-8 | C++ | false | false | 1,130 | h | //****************************************************************************/
// File: JMethodAttr.h
//****************************************************************************/
#ifndef __JMETHODATTR_H__
#define __JMETHODATTR_H__
//****************************************************************************/
// Class: JMethodAttr
//****************************************************************************/
template <class BaseT>
class JMethodAttr : public JClassAttr
{
typedef void (BaseT::*FnProcess)();
FnProcess m_fnProcess;
public:
JMethodAttr( const char* name, FnProcess call ) : m_fnProcess( call )
{
SetName( name );
m_Type = "method";
}
virtual bool Call( void* pThis, int tag = -1 )
{
if (!m_fnProcess) return false;
(reinterpret_cast<BaseT*>( pThis )->*m_fnProcess)();
return true;
}
virtual bool Get( const void* pThis, JString& str, int tag = -1 ) const
{
return cast<JString, int>( str, tag );
}
}; // class JMethodAttr
#endif // __JMETHODATTR_H__
| [
"[email protected]"
]
| [
[
[
1,
38
]
]
]
|
0583577c79a3d0a08302ac96c87607fc486e9df3 | d425cf21f2066a0cce2d6e804bf3efbf6dd00c00 | /Laptop/IMP Attribute Selection.cpp | 012d354e10a63627c54eaca881b8fa00cb7e62ae | []
| no_license | infernuslord/ja2 | d5ac783931044e9b9311fc61629eb671f376d064 | 91f88d470e48e60ebfdb584c23cc9814f620ccee | refs/heads/master | 2021-01-02T23:07:58.941216 | 2011-10-18T09:22:53 | 2011-10-18T09:22:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 60,679 | cpp | #ifdef PRECOMPILEDHEADERS
#include "Laptop All.h"
#include "IMP Skill Trait.h"
#include "GameSettings.h"
#else
#include "CharProfile.h"
#include "IMP Attribute Selection.h"
#include "IMP MainPage.h"
#include "IMP HomePage.h"
#include "IMPVideoObjects.h"
#include "Utilities.h"
#include "WCheck.h"
#include "input.h"
#include "Isometric Utils.h"
#include "IMP Skill Trait.h"
#include "Debug.h"
#include "WordWrap.h"
#include "Render Dirty.h"
#include "Encrypted File.h"
#include "cursors.h"
#include "laptop.h"
#include "IMP Text System.h"
#include "IMP Compile Character.h"
#include "text.h"
#include "GameSettings.h"
// Added these 3 - SANDRO
#include "IMP Disability Trait.h"
#include "IMP Color Choosing.h"
#include "IMP Minor Trait.h"
#endif
#define STARTING_LEVEL_BOX_POS_X ( 51 )
#define STARTING_LEVEL_BOX_POS_Y ( 296 )
// width of the slider bar region
#define BAR_WIDTH 423 - 197
// width of the slider bar itself
#define SLIDER_BAR_WIDTH 38
// the sizeof one skill unit on the sliding bar in pixels
#define BASE_SKILL_PIXEL_UNIT_SIZE ( ( 423 - 230 ) )
//#define MAX_ATTIBUTEPOINT 90
//#define START_ATTRIBEPOINT 55
//#define MIN_ATTIBUTEPOINT 35
//#define MAX_ZERO_BONUS 15
enum{
HEALTH_ATTRIBUTE,
DEXTERITY_ATTRIBUTE,
AGILITY_ATTRIBUTE,
STRENGTH_ATTRIBUTE,
WISDOM_ATTRIBUTE,
LEADERSHIP_ATTRIBUTE,
MARKSMANSHIP_SKILL,
EXPLOSIVE_SKILL,
MEDICAL_SKILL,
MECHANICAL_SKILL,
};
enum
{
SLIDER_ERROR,
SLIDER_OK,
SLIDER_OUT_OF_RANGE,
};
// Snap: these globals will be properly initialized in SetAttributes
INT32 iStartingLevel = 1; // Added by SANDRO
INT32 iLevelCostMultiplier; // Added by SANDRO
// the skills as they stand
INT32 iCurrentStrength = 0;
INT32 iCurrentAgility = 0;
INT32 iCurrentDexterity = 0;
INT32 iCurrentHealth = 0;
INT32 iCurrentLeaderShip = 0;
INT32 iCurrentWisdom = 0;
INT32 iCurrentMarkmanship = 0;
INT32 iCurrentMechanical = 0;
INT32 iCurrentMedical = 0;
INT32 iCurrentExplosives = 0;
INT32 iStrengthMinimum = gGameExternalOptions.iMinAttribute;
INT32 iAgilityMinimum = gGameExternalOptions.iMinAttribute;
INT32 iDexterityMinimum = gGameExternalOptions.iMinAttribute;
INT32 iHealthMinimum = gGameExternalOptions.iMinAttribute;
INT32 iLeaderShipMinimum = gGameExternalOptions.iMinAttribute;
INT32 iWisdomMinimum = gGameExternalOptions.iMinAttribute;
INT32 iMarkmanshipMinimum = gGameExternalOptions.iMinAttribute;
INT32 iMechanicalMinimum = gGameExternalOptions.iMinAttribute;
INT32 iMedicalMinimum = gGameExternalOptions.iMinAttribute;
INT32 iExplosivesMinimum = gGameExternalOptions.iMinAttribute;
// which stat is message about stat at zero about
INT32 iCurrentStatAtZero = 0;
// total number of bonus points
// Kaiden: Externalized this value for option-ation
INT32 iCurrentBonusPoints = 0;
//INT32 iCurrentBonusPoints = 40;
// diplsay the 0 skill point warning..if skill set to 0, warn character
BOOLEAN fSkillAtZeroWarning = FALSE;
// is the sliding of the sliding bar active right now?
BOOLEAN fSlideIsActive = TRUE;
// first time in game
BOOLEAN fFirstIMPAttribTime = TRUE;
// review mode
BOOLEAN fReviewStats = FALSE;
// buttons
UINT32 giIMPAttributeSelectionButton[ 1 ];
UINT32 giIMPAttributeSelectionButtonImage[ 1 ];
// STARTING LEVEL BUTTONS ADDED - SANDRO
UINT32 giIMPStartingLevelButton[ 2 ];
UINT32 giIMPStartingLevelButtonImage[ 2 ];
// slider buttons
UINT32 giIMPAttributeSelectionSliderButton[ 20 ];
UINT32 giIMPAttributeSelectionSliderButtonImage[ 20 ];
// mouse regions
MOUSE_REGION pSliderRegions[ 10 ];
MOUSE_REGION pSliderBarRegions[ 10 ];
//The currently "anchored scroll bar"
MOUSE_REGION *gpCurrentScrollBox = NULL;
INT32 giCurrentlySelectedStat = -1;
// has any of the sliding bars moved?...for re-rendering puposes
BOOLEAN fHasAnySlidingBarMoved = FALSE;
INT32 uiBarToReRender = -1;
// are we actually coming back to edit, or are we restarting?
BOOLEAN fReturnStatus = FALSE;
UINT32 guiIST_GreyGoldBoxLvl;
// function definition
void ProcessAttributes( void );
void DestroyIMPAttributeSelectionButtons( void );
void CreateIMPAttributeSelectionButtons( void );
UINT8 IncrementStat( INT32 iStatToIncrement );
UINT8 DecrementStat( INT32 iStatToDecrement );
BOOLEAN DoWeHaveThisManyBonusPoints( INT32 iBonusPoints );
void CreateAttributeSliderButtons( void );
void DestroyAttributeSliderButtons( void );
void CreateSlideRegionMouseRegions( void );
void DestroySlideRegionMouseRegions( void );
INT32 GetCurrentAttributeValue( INT32 iAttribute );
void CreateSliderBarMouseRegions( void );
void DestroySlideBarMouseRegions( void );
void SetAttributes( void );
void DrawBonusPointsRemaining( void );
void SetGeneratedCharacterAttributes( void );
INT32 DetermineNewValue( INT32 iNewX );
INT32 DetermineNewPosition( INT32 iAttribute );
// callbacks
void BtnIMPAttributeFinishCallback(GUI_BUTTON *btn,INT32 reason);
void BtnIMPAttributeSliderLeftCallback(GUI_BUTTON *btn,INT32 reason);
void BtnIMPAttributeSliderRightCallback(GUI_BUTTON *btn,INT32 reason);
void SliderRegionButtonCallback(MOUSE_REGION * pRegion, INT32 iReason );
void SliderBarRegionButtonCallback( MOUSE_REGION * pRegion, INT32 iReason );
void StatAtZeroBoxCallBack( UINT8 bExitValue );
// added starting level choosing
void CreateIMPStartingLevelSelectionButtons( void );
void BtnIMPLevelSelectionLeftCallback( GUI_BUTTON *btn,INT32 reason );
void BtnIMPLevelSelectionRightCallback( GUI_BUTTON *btn,INT32 reason );
INT32 iBonusPointsNeededForLevelUp();
INT32 iBonusPointsRecievedForLevelDown();
void EnterIMPAttributeSelection( void )
{
// set attributes and skills
if( ( fReturnStatus == FALSE ) && ( fFirstIMPAttribTime == TRUE ) )
{
// re starting
SetAttributes( );
iStartingLevel = 1; // ADDED - SADNRO
gpCurrentScrollBox = NULL;
giCurrentlySelectedStat = -1;
// does character have PROBLEMS!!?!?!
/*
if( DoesCharacterHaveAnAttitude() )
{
iCurrentBonusPoints+= 10;
}
if( DoesCharacterHaveAPersoanlity( ) )
{
iCurrentBonusPoints += 10;
}
*/
}
fReturnStatus = TRUE;
fFirstIMPAttribTime = FALSE;
// create done button
CreateIMPAttributeSelectionButtons( );
// create clider buttons
CreateAttributeSliderButtons( );
// the mouse regions
CreateSlideRegionMouseRegions( );
//CreateSliderBarMouseRegions( );
// create starting level choice button
CreateIMPStartingLevelSelectionButtons( );
// render background
RenderIMPAttributeSelection( );
return;
}
void RenderIMPAlteredAttribute( void )
{
}
void RenderIMPAttributeSelection( void )
{
// the background
RenderProfileBackGround( );
// attribute frame
RenderAttributeFrame( 51, 87 );
// render attribute boxes
RenderAttributeBoxes( );
RenderAttrib1IndentFrame(51, 30 );
if( fReviewStats != TRUE )
{
RenderAttrib2IndentFrame(350, 42 );
}
// reset rerender flag
fHasAnySlidingBarMoved = FALSE;
// print text for screen
PrintImpText( );
// texts around
// don't blit bonus if reviewing
if( fReviewStats != TRUE )
{
// Bonus points remaining
DisplayWrappedString( LAPTOP_SCREEN_UL_X + 355, LAPTOP_SCREEN_WEB_UL_Y + 51, ( 640 ), 2, FONT12ARIAL, FONT_WHITE, sgAttributeSelectionText[2],FONT_BLACK,FALSE,0);
// this show us the exact maximum attribute based on ini option
CHAR16 sMaxPntsString[200];
INT32 iMaxPointsToShow = gGameExternalOptions.iMaxAttribute;
if (iMaxPointsToShow > 100 )
iMaxPointsToShow = 100;
swprintf(sMaxPntsString, L"%s %d%s", sgAttributeSelectionText[0], iMaxPointsToShow, L".");
// Explanatory text
DisplayWrappedString( LAPTOP_SCREEN_UL_X + 59, LAPTOP_SCREEN_WEB_UL_Y + 36, ( 240 ), 2, FONT10ARIAL, 142, sMaxPntsString,FONT_BLACK,FALSE,0);
InvalidateRegion( LAPTOP_SCREEN_UL_X + 65, LAPTOP_SCREEN_WEB_UL_Y + 51, LAPTOP_SCREEN_UL_X + 85, LAPTOP_SCREEN_WEB_UL_Y + 71 );
}
else
{
//LoadAndDisplayIMPText( LAPTOP_SCREEN_UL_X + 60, LAPTOP_SCREEN_WEB_UL_Y + 44, ( 200 ), sgAttributeSelectionTextReview, FONT10ARIAL, 142, TRUE, 0);
DisplayWrappedString( LAPTOP_SCREEN_UL_X + 60, LAPTOP_SCREEN_WEB_UL_Y + 44, ( 240 ), 2, FONT10ARIAL, 142, sgAttributeSelectionText[1],FONT_BLACK,FALSE,0);
}
// amt of bonus pts
DrawBonusPointsRemaining( );
//***********************************************************************************************
// STARTING LEVEL BOX
///////////////////////////
// Bonus frame for starting level
RenderAttribStartingLevelFrame( STARTING_LEVEL_BOX_POS_X, STARTING_LEVEL_BOX_POS_Y );
// text
DrawTextToScreen( sgAttributeSelectionText[3], LAPTOP_SCREEN_UL_X + STARTING_LEVEL_BOX_POS_X + 9, LAPTOP_SCREEN_WEB_UL_Y + STARTING_LEVEL_BOX_POS_Y + 4, ( 100 ), FONT12ARIAL, FONT_WHITE, FONT_BLACK, FALSE, RIGHT_JUSTIFIED );
CHAR16 sStartLevelString[64];
swprintf(sStartLevelString, L"%d", iStartingLevel );
// print string
DrawTextToScreen( sStartLevelString, STARTING_LEVEL_BOX_POS_X + LAPTOP_SCREEN_UL_X + 99, STARTING_LEVEL_BOX_POS_Y + LAPTOP_SCREEN_WEB_UL_Y + 6, ( 100 ), FONT14ARIAL, 142, FONT_BLACK, FALSE, CENTER_JUSTIFIED );
InvalidateRegion( STARTING_LEVEL_BOX_POS_X + LAPTOP_SCREEN_UL_X + 94, STARTING_LEVEL_BOX_POS_Y + LAPTOP_SCREEN_WEB_UL_Y + 8, STARTING_LEVEL_BOX_POS_X + LAPTOP_SCREEN_UL_X + 130, STARTING_LEVEL_BOX_POS_Y + LAPTOP_SCREEN_WEB_UL_Y + 42 );
//****************************************
return;
}
void ExitIMPAttributeSelection( void )
{
// get rid of slider buttons
DestroyAttributeSliderButtons( );
// the mouse regions
DestroySlideRegionMouseRegions( );
//DestroySlideBarMouseRegions( );
// get rid of done buttons
DestroyIMPAttributeSelectionButtons( );
fReturnStatus = FALSE;
return;
}
void HandleIMPAttributeSelection( void )
{
// review mode, do not allow changes
if( fReviewStats )
{
return;
}
// set the currently selectd slider bar
if( gfLeftButtonState && gpCurrentScrollBox != NULL )
{
//if theuser is holding down the mouse cursor to left of the start of the slider bars
if( gusMouseXPos < ( SKILL_SLIDE_START_X + LAPTOP_SCREEN_UL_X ) )
{
DecrementStat( giCurrentlySelectedStat );
}
//else if the user is holding down the mouse button to the right of the scroll bars
else if( gusMouseXPos > ( LAPTOP_SCREEN_UL_X + SKILL_SLIDE_START_X + BAR_WIDTH ) )
{
IncrementStat( giCurrentlySelectedStat );
}
else
{
INT32 iCurrentAttributeValue;
INT32 sNewX = gusMouseXPos;
INT32 iNewValue;
INT32 iCounter;
// get old stat value
iCurrentAttributeValue = GetCurrentAttributeValue( giCurrentlySelectedStat );
iNewValue = DetermineNewValue( sNewX );
// chenged, move mouse region if change large enough
if( iCurrentAttributeValue != iNewValue )
{
// update screen
fHasAnySlidingBarMoved = TRUE;
}
// change is enough
if ( iNewValue - iCurrentAttributeValue > 0)
{
// positive, increment stat
iCounter = iNewValue - iCurrentAttributeValue;
for( iCounter; iCounter > 0; iCounter--)
{
IncrementStat( giCurrentlySelectedStat );
}
}
else
{
// negative, decrement stat
iCounter = iCurrentAttributeValue - iNewValue;
for( iCounter; iCounter > 0; iCounter--)
{
DecrementStat( giCurrentlySelectedStat );
}
}
}
RenderIMPAttributeSelection( );
}
else
{
gpCurrentScrollBox = NULL;
giCurrentlySelectedStat = -1;
}
// prcoess current state of attributes
ProcessAttributes( );
// has any bar moved?
if( fHasAnySlidingBarMoved )
{
// render
if( uiBarToReRender == -1 )
{
RenderIMPAttributeSelection( );
}
else
{
RenderAttributeFrameForIndex( 51, 87, uiBarToReRender );
/*
// print text for screen
PrintImpText( );
// amt of bonus pts
DrawBonusPointsRemaining( );
RenderAttributeFrame( 51, 87 );
// render attribute boxes
RenderAttributeBoxes( );
PrintImpText( );
InvalidateRegion( LAPTOP_SCREEN_UL_X + 51, LAPTOP_SCREEN_WEB_UL_Y + 87, LAPTOP_SCREEN_UL_X + 51 + 400, LAPTOP_SCREEN_WEB_UL_Y + 87 + 220 );
*/
uiBarToReRender = -1;
MarkButtonsDirty();
}
fHasAnySlidingBarMoved = FALSE;
}
if ( fSkillAtZeroWarning == TRUE )
{
DoLapTopMessageBox( MSG_BOX_IMP_STYLE, pSkillAtZeroWarning[ 0 ], LAPTOP_SCREEN, MSG_BOX_FLAG_YESNO, StatAtZeroBoxCallBack);
fSkillAtZeroWarning = FALSE;
}
return;
}
void ProcessAttributes( void )
{
//Kaiden: Ignore the values in the below comment, this is now controlled by
// Values externalized in the Ja2_Options.ini file.
// this function goes through and confirms thet state of attributes, ie not allowing attributes to
// drop below 35 or skills to go below 0...and if skill is 34 set to 0
// check any attribute below 35
INT32 iMinAttribute = gGameExternalOptions.iMinAttribute;
INT32 iMaxAttribute = gGameExternalOptions.iMaxAttribute;
// strength
if( iCurrentStrength <= iStrengthMinimum )
{
iCurrentStrength = iStrengthMinimum;
// disable button too
}
// dex
if( iCurrentDexterity <= iDexterityMinimum )
{
iCurrentDexterity = iDexterityMinimum;
// disable button too
}
// agility
if( iCurrentAgility <= iAgilityMinimum )
{
iCurrentAgility = iAgilityMinimum;
// disable button too
}
// wisdom
if( iCurrentWisdom <= iWisdomMinimum )
{
iCurrentWisdom = iWisdomMinimum;
// disable button too
}
// Kaiden: Leadership should be zero-able
// LeaderShip
//if( iCurrentLeaderShip <= MIN_ATTIBUTEPOINT )
//{
//iCurrentLeaderShip = MIN_ATTIBUTEPOINT;
// disable button too
//}
// health
if( iCurrentHealth <= iHealthMinimum )
{
iCurrentHealth = iHealthMinimum;
// disable button too
}
// now check for above MAX_ATTIBUTEPOINT
// strength
if( iCurrentStrength >= iMaxAttribute )
{
iCurrentStrength = iMaxAttribute;
// disable button too
}
// dex
if( iCurrentDexterity >= iMaxAttribute )
{
iCurrentDexterity = iMaxAttribute;
// disable button too
}
// agility
if( iCurrentAgility >= iMaxAttribute )
{
iCurrentAgility = iMaxAttribute;
// disable button too
}
// wisdom
if( iCurrentWisdom >= iMaxAttribute )
{
iCurrentWisdom = iMaxAttribute;
// disable button too
}
// LeaderShip
if( iCurrentLeaderShip >= iMaxAttribute )
{
iCurrentLeaderShip = iMaxAttribute;
// disable button too
}
// health
if( iCurrentHealth >= iMaxAttribute )
{
iCurrentHealth = iMaxAttribute;
// disable button too
}
return;
}
UINT8 IncrementStat( INT32 iStatToIncrement )
{
// this function is responsable for incrementing a stat
INT32 iMinAttribute = gGameExternalOptions.iMinAttribute;
INT32 iMaxAttribute = gGameExternalOptions.iMaxAttribute;
INT32 iMaxZeroBonus = gGameExternalOptions.iMaxZeroBonus;
// review mode, do not allow changes
if( fReviewStats )
{
return( SLIDER_ERROR );
}
// make sure we have enough bonus points
if( iCurrentBonusPoints < 1 )
{
// nope...GO GET SOME BONUS POINTS, IDIOT!
return( SLIDER_ERROR );
}
// check to make sure stat isn't maxed out already
switch( iStatToIncrement )
{
case( STRENGTH_ATTRIBUTE ):
if( iCurrentStrength > iMaxAttribute -1 )
{
// too high, leave
return( SLIDER_OUT_OF_RANGE );
}
else
{
iCurrentStrength++;
iCurrentBonusPoints--;
}
break;
case( DEXTERITY_ATTRIBUTE ):
if( iCurrentDexterity > iMaxAttribute -1 )
{
// too high, leave
return( SLIDER_OUT_OF_RANGE );
}
else
{
iCurrentDexterity++;
iCurrentBonusPoints--;
}
break;
case( AGILITY_ATTRIBUTE ):
if( iCurrentAgility > iMaxAttribute -1 )
{
// too high, leave
return( SLIDER_OUT_OF_RANGE );
}
else
{
iCurrentAgility++;
iCurrentBonusPoints--;
}
break;
case( WISDOM_ATTRIBUTE ):
if( iCurrentWisdom > iMaxAttribute -1 )
{
// too high, leave
return( SLIDER_OUT_OF_RANGE );
}
else
{
iCurrentWisdom++;
iCurrentBonusPoints--;
}
break;
case( HEALTH_ATTRIBUTE ):
if( iCurrentHealth > iMaxAttribute -1 )
{
// too high, leave
return( SLIDER_OUT_OF_RANGE );
}
else
{
iCurrentHealth++;
iCurrentBonusPoints--;
}
break;
case( LEADERSHIP_ATTRIBUTE ):
if( iCurrentLeaderShip > iMaxAttribute -1 )
{
// too high, leave
return( SLIDER_OUT_OF_RANGE );
}
else
{
if( iCurrentLeaderShip == 0)
{
if( DoWeHaveThisManyBonusPoints( iMaxZeroBonus ) == TRUE )
{
iCurrentLeaderShip+=iLeaderShipMinimum;
iCurrentBonusPoints-=iMaxZeroBonus;
fSkillAtZeroWarning = FALSE;
}
else
{
return( SLIDER_OK );
}
}
else
{
iCurrentLeaderShip++;
iCurrentBonusPoints--;
}
}
break;
case( MARKSMANSHIP_SKILL ):
if( iCurrentMarkmanship > iMaxAttribute -1 )
{
// too high, leave
return( SLIDER_OUT_OF_RANGE );
}
else
{
if( iCurrentMarkmanship == 0)
{
if( DoWeHaveThisManyBonusPoints( iMaxZeroBonus ) == TRUE )
{
iCurrentMarkmanship+=iMarkmanshipMinimum;
iCurrentBonusPoints-=iMaxZeroBonus;
fSkillAtZeroWarning = FALSE;
}
else
{
return( SLIDER_OK );
}
}
else
{
iCurrentMarkmanship++;
iCurrentBonusPoints--;
}
}
break;
case( MECHANICAL_SKILL ):
if( iCurrentMechanical > iMaxAttribute -1 )
{
// too high, leave
return( SLIDER_OUT_OF_RANGE );
}
else
{
if( iCurrentMechanical == 0)
{
if( DoWeHaveThisManyBonusPoints( iMaxZeroBonus ) == TRUE )
{
iCurrentMechanical+=iMechanicalMinimum;
iCurrentBonusPoints-=iMaxZeroBonus;
fSkillAtZeroWarning = FALSE;
}
else
{
return( SLIDER_OK );
}
}
else
{
iCurrentMechanical++;
iCurrentBonusPoints--;
}
}
break;
case( MEDICAL_SKILL ):
if( iCurrentMedical > iMaxAttribute -1 )
{
// too high, leave
return( SLIDER_OUT_OF_RANGE );
}
else
{
if( iCurrentMedical == 0)
{
if( DoWeHaveThisManyBonusPoints( iMaxZeroBonus ) == TRUE )
{
iCurrentMedical+=iMedicalMinimum;
iCurrentBonusPoints-=iMaxZeroBonus;
fSkillAtZeroWarning = FALSE;
}
else
{
return( SLIDER_OK );
}
}
else
{
iCurrentMedical++;
iCurrentBonusPoints--;
}
}
break;
case( EXPLOSIVE_SKILL ):
if( iCurrentExplosives > iMaxAttribute -1 )
{
// too high, leave
return( SLIDER_OUT_OF_RANGE );
}
else
{
if( iCurrentExplosives == 0)
{
if( DoWeHaveThisManyBonusPoints( iMaxZeroBonus ) == TRUE )
{
iCurrentExplosives+=iExplosivesMinimum;
iCurrentBonusPoints-=iMaxZeroBonus;
fSkillAtZeroWarning = FALSE;
}
else
{
return( SLIDER_OK );
}
}
else
{
iCurrentExplosives++;
iCurrentBonusPoints--;
}
}
break;
}
return( SLIDER_OK );
}
UINT8 DecrementStat( INT32 iStatToDecrement )
{
INT32 iMinAttribute = gGameExternalOptions.iMinAttribute;
INT32 iMaxZeroBonus = gGameExternalOptions.iMaxZeroBonus;
// review mode, do not allow changes
if( fReviewStats )
{
return( SLIDER_ERROR );
}
// decrement a stat
// check to make sure stat isn't maxed out already
switch( iStatToDecrement )
{
case( STRENGTH_ATTRIBUTE ):
if( iCurrentStrength > iStrengthMinimum )
{
// ok to decrement
iCurrentStrength--;
iCurrentBonusPoints++;
}
else
{
return( SLIDER_OUT_OF_RANGE );
}
break;
case( DEXTERITY_ATTRIBUTE ):
if( iCurrentDexterity > iDexterityMinimum )
{
// ok to decrement
iCurrentDexterity--;
iCurrentBonusPoints++;
}
else
{
return( SLIDER_OUT_OF_RANGE );
}
break;
case( AGILITY_ATTRIBUTE ):
if( iCurrentAgility > iAgilityMinimum )
{
// ok to decrement
iCurrentAgility--;
iCurrentBonusPoints++;
}
else
{
return( SLIDER_OUT_OF_RANGE );
}
break;
case( WISDOM_ATTRIBUTE ):
if( iCurrentWisdom > iWisdomMinimum )
{
// ok to decrement
iCurrentWisdom--;
iCurrentBonusPoints++;
}
else
{
return( SLIDER_OUT_OF_RANGE );
}
break;
case( LEADERSHIP_ATTRIBUTE ):
if( iCurrentLeaderShip > iLeaderShipMinimum )
{
// ok to decrement
iCurrentLeaderShip--;
iCurrentBonusPoints++;
}
//Kaiden: Leadership couldn't be set to zero fixed below:
else if( iCurrentLeaderShip == iLeaderShipMinimum)
{
if (LeadershipRequiredDueToMajorSkills() == 0 && LeaderShipRequiredAdjustmentForMinorTraits( 0 ) == 0 )
{
// ok to decrement
iCurrentLeaderShip-=iLeaderShipMinimum;
iCurrentBonusPoints+=iMaxZeroBonus;
fSkillAtZeroWarning = TRUE;
}
}
break;
case( HEALTH_ATTRIBUTE ):
if( iCurrentHealth > iHealthMinimum )
{
// ok to decrement
iCurrentHealth--;
iCurrentBonusPoints++;
}
else
{
return( SLIDER_OUT_OF_RANGE );
}
break;
case( MARKSMANSHIP_SKILL ):
if( iCurrentMarkmanship > iMarkmanshipMinimum )
{
// ok to decrement
iCurrentMarkmanship--;
iCurrentBonusPoints++;
}
else if( iCurrentMarkmanship == iMarkmanshipMinimum)
{
if (MarksmanshipRequiredDueToMajorSkills() == 0 && MarksmanshipRequiredAdjustmentForMinorTraits( 0 ) == 0 )
{
// ok to decrement
iCurrentMarkmanship-=iMarkmanshipMinimum;
iCurrentBonusPoints+=iMaxZeroBonus;
fSkillAtZeroWarning = TRUE;
}
}
break;
case( MEDICAL_SKILL ):
if( iCurrentMedical > iMedicalMinimum )
{
// ok to decrement
iCurrentMedical--;
iCurrentBonusPoints++;
}
else if( iCurrentMedical == iMedicalMinimum)
{
if (MedicalRequiredDueToMajorSkills() == 0 && MedicalRequiredAdjustmentForMinorTraits( 0 ) == 0 )
{
// ok to decrement
iCurrentMedical-=iMedicalMinimum;
iCurrentBonusPoints+=iMaxZeroBonus;
fSkillAtZeroWarning = TRUE;
}
}
break;
case( MECHANICAL_SKILL ):
if( iCurrentMechanical > iMechanicalMinimum )
{
// ok to decrement
iCurrentMechanical--;
iCurrentBonusPoints++;
}
else if( iCurrentMechanical == iMechanicalMinimum)
{
if (MechanicalRequiredDueToMajorSkills() == 0 && MechanicalRequiredAdjustmentForMinorTraits( 0 ) == 0 )
{
// ok to decrement
iCurrentMechanical-=iMechanicalMinimum;
iCurrentBonusPoints+=iMaxZeroBonus;
fSkillAtZeroWarning = TRUE;
}
}
break;
case( EXPLOSIVE_SKILL ):
if( iCurrentExplosives > iExplosivesMinimum )
{
// ok to decrement
iCurrentExplosives--;
iCurrentBonusPoints++;
}
else if( iCurrentExplosives == iExplosivesMinimum)
{
if (ExplosivesRequiredDueToMajorSkills() == 0 && ExplosivesRequiredAdjustmentForMinorTraits( 0 ) == 0 )
{
// ok to decrement
iCurrentExplosives-=iExplosivesMinimum;
iCurrentBonusPoints+=iMaxZeroBonus;
fSkillAtZeroWarning = TRUE;
}
}
break;
}
if( fSkillAtZeroWarning == TRUE )
{
// current stat at zero
iCurrentStatAtZero = iStatToDecrement;
}
return( SLIDER_OK );
}
BOOLEAN DoWeHaveThisManyBonusPoints( INT32 iBonusPoints )
{
// returns if player has at least this many bonus points
if( iCurrentBonusPoints >= iBonusPoints )
{
// yep, return true
return ( TRUE );
}
else
{
// nope, return false
return ( FALSE );
}
}
void CreateIMPAttributeSelectionButtons( void )
{
// the finished button
giIMPAttributeSelectionButtonImage[0]= LoadButtonImage( "LAPTOP\\button_5.sti" ,-1,0,-1,1,-1 );
/* giIMPAttributeSelectionButton[0] = QuickCreateButton( giIMPAttributeSelectionButtonImage[0], LAPTOP_SCREEN_UL_X + ( 136 ), LAPTOP_SCREEN_WEB_UL_Y + ( 314 ),
BUTTON_TOGGLE, MSYS_PRIORITY_HIGHEST - 1,
BtnGenericMouseMoveButtonCallback, (GUI_CALLBACK)BtnIMPAttributeFinishCallback );
*/
giIMPAttributeSelectionButton[0] = CreateIconAndTextButton( giIMPAttributeSelectionButtonImage[0], pImpButtonText[ 11 ], FONT12ARIAL,
FONT_WHITE, DEFAULT_SHADOW,
FONT_WHITE, DEFAULT_SHADOW,
TEXT_CJUSTIFIED,
LAPTOP_SCREEN_UL_X + ( 350 ), LAPTOP_SCREEN_WEB_UL_Y + ( 340 ), BUTTON_TOGGLE, MSYS_PRIORITY_HIGH,
BtnGenericMouseMoveButtonCallback, (GUI_CALLBACK)BtnIMPAttributeFinishCallback);
SetButtonCursor(giIMPAttributeSelectionButton[0], CURSOR_WWW);
return;
}
void DestroyIMPAttributeSelectionButtons( void )
{
// this function will destroy the buttons needed for the IMP attrib enter page
// the begin button
RemoveButton(giIMPAttributeSelectionButton[ 0 ] );
UnloadButtonImage(giIMPAttributeSelectionButtonImage[ 0 ] );
// Destroy also starting level buttons
RemoveButton(giIMPStartingLevelButton[ 0 ] );
RemoveButton(giIMPStartingLevelButton[ 1 ] );
UnloadButtonImage(giIMPStartingLevelButtonImage[ 0 ] );
UnloadButtonImage(giIMPStartingLevelButtonImage[ 1 ] );
return;
}
void BtnIMPAttributeFinishCallback(GUI_BUTTON *btn,INT32 reason)
{
// btn callback for IMP attrbite begin button
if (!(btn->uiFlags & BUTTON_ENABLED))
return;
if(reason & MSYS_CALLBACK_REASON_LBUTTON_DWN )
{
btn->uiFlags|=(BUTTON_CLICKED_ON);
}
else if(reason & MSYS_CALLBACK_REASON_LBUTTON_UP )
{
if (btn->uiFlags & BUTTON_CLICKED_ON)
{
btn->uiFlags&=~(BUTTON_CLICKED_ON);
//iCurrentImpPage = IMP_MAIN_PAGE;
// SANDRO WAS HERE - THE FINISH PAGE AFTER ATTRIBUTES IS WORTHLESS AND HAVE BEEN CUT OUT
//if ( fReviewStats == TRUE )
//{
iCurrentImpPage = IMP_FINISH;
//}
//else
//{
iCurrentProfileMode = IMP__FINISH; // All done
//}
// SET ATTRIBUTES NOW
SetGeneratedCharacterAttributes( );
//fButtonPendingFlag = TRUE;
}
}
}
void CreateIMPStartingLevelSelectionButtons( void )
{
giIMPStartingLevelButtonImage[ 0 ]= LoadButtonImage( "LAPTOP\\AttributeArrows.sti" ,-1,0,-1,1,-1 );
giIMPStartingLevelButtonImage[ 1 ]= LoadButtonImage( "LAPTOP\\AttributeArrows.sti" ,-1,3,-1,4,-1 );
// left button - decrement level
giIMPStartingLevelButton[ 0 ] = QuickCreateButton( giIMPStartingLevelButtonImage[ 0 ], STARTING_LEVEL_BOX_POS_X + LAPTOP_SCREEN_UL_X + 112, STARTING_LEVEL_BOX_POS_Y + LAPTOP_SCREEN_WEB_UL_Y + 3,
BUTTON_TOGGLE, MSYS_PRIORITY_HIGHEST - 1,
BtnGenericMouseMoveButtonCallback, (GUI_CALLBACK)BtnIMPLevelSelectionLeftCallback );
// right button - increment level
giIMPStartingLevelButton[ 1 ] = QuickCreateButton( giIMPStartingLevelButtonImage[ 1 ], STARTING_LEVEL_BOX_POS_X + LAPTOP_SCREEN_UL_X + 166, STARTING_LEVEL_BOX_POS_Y + LAPTOP_SCREEN_WEB_UL_Y + 3,
BUTTON_TOGGLE, MSYS_PRIORITY_HIGHEST - 1,
BtnGenericMouseMoveButtonCallback, (GUI_CALLBACK)BtnIMPLevelSelectionRightCallback );
SetButtonCursor(giIMPStartingLevelButton[0], CURSOR_WWW);
SetButtonCursor(giIMPStartingLevelButton[1 ], CURSOR_WWW);
// set user data
MSYS_SetBtnUserData(giIMPStartingLevelButton[0],0, 0 / 2 );
MSYS_SetBtnUserData(giIMPStartingLevelButton[1],0, 1 / 2 );
//Get rid of playing the button sound, it will be handled here
//ButtonList[ giIMPStartingLevelButton[0] ]->ubSoundSchemeID = 0;
//ButtonList[ giIMPStartingLevelButton[1] ]->ubSoundSchemeID = 0;
MarkButtonsDirty( );
}
void BtnIMPLevelSelectionLeftCallback( GUI_BUTTON *btn,INT32 reason )
{
// btn callback for IMP personality quiz answer button
if (!(btn->uiFlags & BUTTON_ENABLED))
return;
if( reason & MSYS_CALLBACK_REASON_LBUTTON_REPEAT )
{
if ( (iStartingLevel > 1) && !fReviewStats )
{
PlayButtonSound( giIMPStartingLevelButton[0], BUTTON_SOUND_CLICKED_ON );
iCurrentBonusPoints += iBonusPointsRecievedForLevelDown();
iStartingLevel--;
fHasAnySlidingBarMoved = TRUE;
}
else
{
PlayButtonSound( giIMPStartingLevelButton[0], BUTTON_SOUND_DISABLED_CLICK );
}
}
else if( reason & MSYS_CALLBACK_REASON_LBUTTON_DWN )
{
btn->uiFlags|=(BUTTON_CLICKED_ON);
if ( (iStartingLevel > 1) && !fReviewStats )
{
PlayButtonSound( giIMPStartingLevelButton[0], BUTTON_SOUND_CLICKED_ON );
iCurrentBonusPoints += iBonusPointsRecievedForLevelDown();
iStartingLevel--;
fHasAnySlidingBarMoved = TRUE;
}
else
{
PlayButtonSound( giIMPStartingLevelButton[0], BUTTON_SOUND_DISABLED_CLICK );
}
}
else if( reason & MSYS_CALLBACK_REASON_LBUTTON_UP )
{
if (btn->uiFlags & BUTTON_CLICKED_ON)
{
btn->uiFlags&=~(BUTTON_CLICKED_ON);
}
}
}
void BtnIMPLevelSelectionRightCallback( GUI_BUTTON *btn,INT32 reason )
{
// btn callback for IMP personality quiz answer button
if (!(btn->uiFlags & BUTTON_ENABLED))
return;
if( reason & MSYS_CALLBACK_REASON_LBUTTON_REPEAT )
{
if ((iBonusPointsNeededForLevelUp() <= iCurrentBonusPoints) && ( iStartingLevel < 10 ) && !fReviewStats )
{
PlayButtonSound( giIMPStartingLevelButton[1], BUTTON_SOUND_CLICKED_ON );
iCurrentBonusPoints -= iBonusPointsNeededForLevelUp();
iStartingLevel++;
fHasAnySlidingBarMoved = TRUE;
}
else
{
PlayButtonSound( giIMPStartingLevelButton[1], BUTTON_SOUND_DISABLED_CLICK );
}
}
else if( reason & MSYS_CALLBACK_REASON_LBUTTON_DWN )
{
btn->uiFlags|=(BUTTON_CLICKED_ON);
if ((iBonusPointsNeededForLevelUp() <= iCurrentBonusPoints) && ( iStartingLevel < 10 ) && !fReviewStats )
{
PlayButtonSound( giIMPStartingLevelButton[1], BUTTON_SOUND_CLICKED_ON );
iCurrentBonusPoints -= iBonusPointsNeededForLevelUp();
iStartingLevel++;
fHasAnySlidingBarMoved = TRUE;
}
else
{
PlayButtonSound( giIMPStartingLevelButton[1], BUTTON_SOUND_DISABLED_CLICK );
}
}
else if( reason & MSYS_CALLBACK_REASON_LBUTTON_UP )
{
if (btn->uiFlags & BUTTON_CLICKED_ON)
{
btn->uiFlags&=~(BUTTON_CLICKED_ON);
}
}
}
INT32 iBonusPointsNeededForLevelUp()
{
INT32 iBonusPointsNeeded = 0;
if (iStartingLevel > 0 && iStartingLevel < 10)
{
iBonusPointsNeeded = (iStartingLevel + 1) * iLevelCostMultiplier;
}
return( iBonusPointsNeeded );
}
INT32 iBonusPointsRecievedForLevelDown()
{
INT32 iBonusPointsRecieved;
if (iStartingLevel > 1 && iStartingLevel <= 10)
{
iBonusPointsRecieved = iStartingLevel * iLevelCostMultiplier;
}
return( iBonusPointsRecieved );
}
void RenderAttributeBoxes( void )
{
INT32 iMinAttribute = gGameExternalOptions.iMinAttribute;
// this function will render the boxes in the sliding attribute bar, based on position
INT32 iCnt=STRENGTH_ATTRIBUTE;
INT16 sX = 0;
INT16 sY = 0;
CHAR16 sString[4];
// set last char to null
sString[2] = 0;
// font stuff
SetFont(FONT10ARIAL);
SetFontShadow(NO_SHADOW);
SetFontForeground(FONT_WHITE);
SetFontBackground(FONT_BLACK);
// run through and render each slider bar
for( iCnt = HEALTH_ATTRIBUTE; iCnt <= MECHANICAL_SKILL; iCnt++)
{
// position is ( width * ( stat - 35 ) ) /50]
// unless 0, then it is 0 - for skills
// get y position
sY = SKILL_SLIDE_START_Y + SKILL_SLIDE_HEIGHT * ( ( INT16 )iCnt ) ;
switch( iCnt )
{
case (STRENGTH_ATTRIBUTE):
// blt in strength slider
sX = DetermineNewPosition( iCurrentStrength - iMinAttribute );
RenderSliderBar( sX, sY );
// set sliderbar mouse region
MSYS_MoveMouseRegionTo( &pSliderBarRegions[ iCnt ], ( INT16 )(sX + LAPTOP_SCREEN_UL_X ), ( INT16 )( sY + LAPTOP_SCREEN_WEB_UL_Y ) );
// the text
swprintf( sString, L"%d", iCurrentStrength );
sX += LAPTOP_SCREEN_UL_X;
sY += LAPTOP_SCREEN_WEB_UL_Y;
mprintf(sX + 13, sY + 3, sString);
break;
case (DEXTERITY_ATTRIBUTE):
// blt in strength slider
sX = DetermineNewPosition( iCurrentDexterity - iMinAttribute );
RenderSliderBar( sX, sY );
// set sliderbar mouse region
MSYS_MoveMouseRegionTo( &pSliderBarRegions[ iCnt ], ( INT16 )(sX + LAPTOP_SCREEN_UL_X ), ( INT16 )( sY + LAPTOP_SCREEN_WEB_UL_Y ) );
// the text
swprintf( sString, L"%d", iCurrentDexterity );
sX += LAPTOP_SCREEN_UL_X;
sY += LAPTOP_SCREEN_WEB_UL_Y;
mprintf(sX + 13, sY + 3, sString);
break;
case (AGILITY_ATTRIBUTE):
// blt in strength slider
sX = DetermineNewPosition( iCurrentAgility - iMinAttribute );
RenderSliderBar( sX, sY );
// set sliderbar mouse region
MSYS_MoveMouseRegionTo( &pSliderBarRegions[ iCnt ], ( INT16 )(sX + LAPTOP_SCREEN_UL_X ), ( INT16 )( sY + LAPTOP_SCREEN_WEB_UL_Y ) );
// the text
swprintf( sString, L"%d", iCurrentAgility );
sX += LAPTOP_SCREEN_UL_X;
sY += LAPTOP_SCREEN_WEB_UL_Y;
mprintf(sX + 13, sY + 3, sString);
break;
case (WISDOM_ATTRIBUTE):
// blt in strength slider
sX = DetermineNewPosition( iCurrentWisdom - iMinAttribute );
RenderSliderBar( sX, sY );
// set sliderbar mouse region
MSYS_MoveMouseRegionTo( &pSliderBarRegions[ iCnt ], ( INT16 )(sX + LAPTOP_SCREEN_UL_X ), ( INT16 )( sY + LAPTOP_SCREEN_WEB_UL_Y ) );
// the text
swprintf( sString, L"%d", iCurrentWisdom );
sX += LAPTOP_SCREEN_UL_X;
sY += LAPTOP_SCREEN_WEB_UL_Y;
mprintf(sX + 13, sY + 3, sString);
break;
case (LEADERSHIP_ATTRIBUTE):
// blt in strength slider
sX = DetermineNewPosition( iCurrentLeaderShip - iMinAttribute );
RenderSliderBar( sX, sY );
// set sliderbar mouse region
MSYS_MoveMouseRegionTo( &pSliderBarRegions[ iCnt ], ( INT16 )(sX + LAPTOP_SCREEN_UL_X ), ( INT16 )( sY + LAPTOP_SCREEN_WEB_UL_Y ) );
// the text
swprintf( sString, L"%d", iCurrentLeaderShip );
sX += LAPTOP_SCREEN_UL_X;
sY += LAPTOP_SCREEN_WEB_UL_Y;
mprintf(sX + 13 , sY + 3, sString);
break;
case (HEALTH_ATTRIBUTE):
// blt in health slider
sX = DetermineNewPosition( iCurrentHealth - iMinAttribute );
RenderSliderBar( sX, sY );
// set sliderbar mouse region
MSYS_MoveMouseRegionTo( &pSliderBarRegions[ iCnt ], ( INT16 )(sX + LAPTOP_SCREEN_UL_X ), ( INT16 )( sY + LAPTOP_SCREEN_WEB_UL_Y ) );
// the text
swprintf( sString, L"%d", iCurrentHealth );
sY += LAPTOP_SCREEN_WEB_UL_Y;
sX += LAPTOP_SCREEN_UL_X;
mprintf(sX + 13, sY + 3, sString);
break;
case (MARKSMANSHIP_SKILL):
// blt in marksmanship slider
sX = DetermineNewPosition( iCurrentMarkmanship - iMinAttribute );
RenderSliderBar( sX, sY );
// set sliderbar mouse region
MSYS_MoveMouseRegionTo( &pSliderBarRegions[ iCnt ], ( INT16 )(sX + LAPTOP_SCREEN_UL_X ), ( INT16 )( sY + LAPTOP_SCREEN_WEB_UL_Y ) );
// the text
swprintf( sString, L"%d", iCurrentMarkmanship );
sY += LAPTOP_SCREEN_WEB_UL_Y;
sX += LAPTOP_SCREEN_UL_X;
mprintf(sX + 13, sY + 3, sString);
break;
case (MEDICAL_SKILL):
// blt in medical slider
sX = DetermineNewPosition( iCurrentMedical - iMinAttribute );
RenderSliderBar( sX, sY );
// set sliderbar mouse region
MSYS_MoveMouseRegionTo( &pSliderBarRegions[ iCnt ], ( INT16 )(sX + LAPTOP_SCREEN_UL_X ), ( INT16 )( sY + LAPTOP_SCREEN_WEB_UL_Y ) );
// the text
swprintf( sString, L"%d", iCurrentMedical );
sY += LAPTOP_SCREEN_WEB_UL_Y;
sX += LAPTOP_SCREEN_UL_X;
mprintf(sX + 13, sY + 3, sString);
break;
case (MECHANICAL_SKILL):
// blt in mech slider
sX = DetermineNewPosition( iCurrentMechanical - iMinAttribute );
RenderSliderBar( sX, sY );
// set sliderbar mouse region
MSYS_MoveMouseRegionTo( &pSliderBarRegions[ iCnt ], ( INT16 )(sX + LAPTOP_SCREEN_UL_X ), ( INT16 )( sY + LAPTOP_SCREEN_WEB_UL_Y ) );
// the text
swprintf( sString, L"%d", iCurrentMechanical );
sY += LAPTOP_SCREEN_WEB_UL_Y;
sX += LAPTOP_SCREEN_UL_X;
mprintf(sX + 13, sY + 3, sString);
break;
case (EXPLOSIVE_SKILL):
// blt in explosive slider
sX = DetermineNewPosition( iCurrentExplosives - iMinAttribute );
RenderSliderBar( sX, sY );
// set sliderbar mouse region
MSYS_MoveMouseRegionTo( &pSliderBarRegions[ iCnt ], ( INT16 )(sX + LAPTOP_SCREEN_UL_X ), ( INT16 )( sY + LAPTOP_SCREEN_WEB_UL_Y ) );
// the text
swprintf( sString, L"%d", iCurrentExplosives );
sY += LAPTOP_SCREEN_WEB_UL_Y;
sX += LAPTOP_SCREEN_UL_X;
mprintf(sX + 13, sY + 3, sString);
break;
}
}
// reset shadow
SetFontShadow(DEFAULT_SHADOW);
return;
}
void CreateAttributeSliderButtons( void )
{
// this function will create the buttons for the attribute slider
// the finished button
INT32 iCounter =0;
giIMPAttributeSelectionSliderButtonImage[ 0 ]= LoadButtonImage( "LAPTOP\\AttributeArrows.sti" ,-1,0,-1,1,-1 );
giIMPAttributeSelectionSliderButtonImage[ 1 ]= LoadButtonImage( "LAPTOP\\AttributeArrows.sti" ,-1,3,-1,4,-1 );
for(iCounter = 0; iCounter < 20; iCounter+=2 )
{
// left button - decrement stat
giIMPAttributeSelectionSliderButton[ iCounter ] = QuickCreateButton( giIMPAttributeSelectionSliderButtonImage[ 0 ], LAPTOP_SCREEN_UL_X + ( 163 ), ( INT16 ) ( LAPTOP_SCREEN_WEB_UL_Y + ( 99 + iCounter / 2 * 20 ) ),
BUTTON_TOGGLE, MSYS_PRIORITY_HIGHEST - 1,
BtnGenericMouseMoveButtonCallback, (GUI_CALLBACK)BtnIMPAttributeSliderLeftCallback );
// right button - increment stat
giIMPAttributeSelectionSliderButton[ iCounter + 1 ] = QuickCreateButton( giIMPAttributeSelectionSliderButtonImage[ 1 ], LAPTOP_SCREEN_UL_X + ( 420 ), ( INT16 ) ( LAPTOP_SCREEN_WEB_UL_Y + ( 99 + iCounter / 2 * 20 ) ),
BUTTON_TOGGLE, MSYS_PRIORITY_HIGHEST - 1,
BtnGenericMouseMoveButtonCallback, (GUI_CALLBACK)BtnIMPAttributeSliderRightCallback );
SetButtonCursor(giIMPAttributeSelectionSliderButton[iCounter], CURSOR_WWW);
SetButtonCursor(giIMPAttributeSelectionSliderButton[iCounter + 1 ], CURSOR_WWW);
// set user data
MSYS_SetBtnUserData(giIMPAttributeSelectionSliderButton[iCounter],0, iCounter / 2 );
MSYS_SetBtnUserData(giIMPAttributeSelectionSliderButton[iCounter + 1],0, iCounter / 2 );
}
MarkButtonsDirty( );
}
void DestroyAttributeSliderButtons( void )
{
// this function will destroy the buttons used for attribute manipulation
INT32 iCounter =0;
// get rid of image
UnloadButtonImage(giIMPAttributeSelectionSliderButtonImage[ 0 ] );
UnloadButtonImage(giIMPAttributeSelectionSliderButtonImage[ 1 ] );
for(iCounter = 0; iCounter < 20; iCounter++ )
{
// get rid of button
RemoveButton(giIMPAttributeSelectionSliderButton[ iCounter ] );
}
return;
}
void BtnIMPAttributeSliderLeftCallback(GUI_BUTTON *btn,INT32 reason)
{
INT32 iValue = -1;
// btn callback for IMP personality quiz answer button
if (!(btn->uiFlags & BUTTON_ENABLED))
return;
iValue = (INT32)MSYS_GetBtnUserData( btn, 0 );
if( reason & MSYS_CALLBACK_REASON_LBUTTON_REPEAT )
{
DecrementStat( iValue );
// stat has changed, rerender
fHasAnySlidingBarMoved = TRUE;
uiBarToReRender = iValue;
}
else if( reason & MSYS_CALLBACK_REASON_LBUTTON_DWN )
{
DecrementStat( iValue );
fHasAnySlidingBarMoved = TRUE;
btn->uiFlags|=(BUTTON_CLICKED_ON);
uiBarToReRender = iValue;
}
else if( reason & MSYS_CALLBACK_REASON_LBUTTON_UP )
{
if (btn->uiFlags & BUTTON_CLICKED_ON)
{
btn->uiFlags&=~(BUTTON_CLICKED_ON);
}
}
}
void BtnIMPAttributeSliderRightCallback(GUI_BUTTON *btn,INT32 reason)
{
INT32 iValue = -1;
// btn callback for IMP personality quiz answer button
if (!(btn->uiFlags & BUTTON_ENABLED))
return;
iValue = (INT32)MSYS_GetBtnUserData( btn, 0 );
if( reason & MSYS_CALLBACK_REASON_LBUTTON_REPEAT )
{
IncrementStat( iValue );
// stat has changed, rerender
fHasAnySlidingBarMoved = TRUE;
uiBarToReRender = iValue;
}
else if( reason & MSYS_CALLBACK_REASON_LBUTTON_DWN )
{
IncrementStat( iValue );
fHasAnySlidingBarMoved = TRUE;
uiBarToReRender = iValue;
btn->uiFlags|=(BUTTON_CLICKED_ON);
}
else if( reason & MSYS_CALLBACK_REASON_LBUTTON_UP )
{
if (btn->uiFlags & BUTTON_CLICKED_ON)
{
btn->uiFlags&=~(BUTTON_CLICKED_ON);
}
}
}
void CreateSlideRegionMouseRegions( void )
{
// this function will create that mouse regions on the sliding area, that, if the player clicks on, the bar will automatically jump to
INT32 iCounter = 0;
for( iCounter = 0; iCounter < 10; iCounter++ )
{
// define the region
MSYS_DefineRegion( &pSliderRegions[ iCounter ], ( INT16 ) ( SKILL_SLIDE_START_X + LAPTOP_SCREEN_UL_X), ( INT16 ) ( LAPTOP_SCREEN_WEB_UL_Y + SKILL_SLIDE_START_Y + iCounter * SKILL_SLIDE_HEIGHT ) , ( INT16 ) ( LAPTOP_SCREEN_UL_X + SKILL_SLIDE_START_X + BAR_WIDTH ), ( INT16 ) ( LAPTOP_SCREEN_WEB_UL_Y + SKILL_SLIDE_START_Y + iCounter * SKILL_SLIDE_HEIGHT + 15 ),
MSYS_PRIORITY_HIGH + 2, CURSOR_WWW, MSYS_NO_CALLBACK, SliderRegionButtonCallback);
// define user data
MSYS_SetRegionUserData(&pSliderRegions[iCounter],0,iCounter);
// now add it
MSYS_AddRegion(&pSliderRegions[ iCounter ]);
}
return;
}
void CreateSliderBarMouseRegions( void )
{
INT32 iMinAttribute = gGameExternalOptions.iMinAttribute;
// this function will create that mouse regions on the sliding bars, that, if the player clicks on, the bar will automatically jump to
INT32 iCounter = 0;
INT16 sX = 0;
// set the starting X
// SANDRO - some changes in attribute points distribution method
//sX = DetermineNewPosition( gGameExternalOptions.iStartAttribute - iMinAttribute );
sX = DetermineNewPosition( 0 );
for( iCounter = 0; iCounter < 10; iCounter++ )
{
// define the region
MSYS_DefineRegion( &pSliderBarRegions[ iCounter ], ( INT16 ) ( sX ), ( INT16 ) ( LAPTOP_SCREEN_WEB_UL_Y + SKILL_SLIDE_START_Y + iCounter * SKILL_SLIDE_HEIGHT ) , ( INT16 ) (sX + SLIDER_BAR_WIDTH ), ( INT16 ) ( LAPTOP_SCREEN_WEB_UL_Y + SKILL_SLIDE_START_Y + iCounter * SKILL_SLIDE_HEIGHT + 15 ),
MSYS_PRIORITY_HIGH + 2, CURSOR_WWW, MSYS_NO_CALLBACK, SliderBarRegionButtonCallback);
// define user data
MSYS_SetRegionUserData(&pSliderBarRegions[iCounter],0,iCounter);
// now add it
MSYS_AddRegion(&pSliderBarRegions[ iCounter ]);
}
return;
}
void DestroySlideRegionMouseRegions( void )
{
// this function will destroy the regions user for the slider ' jumping'
INT32 iCounter=0;
// delete the regions
for( iCounter=0; iCounter < 10; iCounter++ )
{
MSYS_RemoveRegion( &pSliderRegions[ iCounter ] );
}
return;
}
void DestroySlideBarMouseRegions( void )
{
// this function will destroy the regions user for the slider ' jumping'
INT32 iCounter=0;
// delete the regions
for( iCounter=0; iCounter < 10; iCounter++ )
{
MSYS_RemoveRegion( &pSliderBarRegions[ iCounter ] );
}
return;
}
void SliderRegionButtonCallback( MOUSE_REGION * pRegion, INT32 iReason )
{
INT32 iMinAttribute = gGameExternalOptions.iMinAttribute;
INT32 iMaxAttribute = gGameExternalOptions.iMaxAttribute;
INT32 iCurrentAttributeValue = 0;
INT32 iNewAttributeValue = 0;
INT32 iAttributeDelta = 0;
INT32 iCounter =0;
INT16 sX =0;
INT16 sY = 0;
static INT16 sOldX = -1;
static INT16 sOldY = -1;
static INT32 iAttribute = -1;
INT32 iNewValue = 0;
INT16 sNewX = -1;
//if we already have an anchored slider bar
if( gpCurrentScrollBox != pRegion && gpCurrentScrollBox != NULL )
return;
if (iReason & MSYS_CALLBACK_REASON_INIT)
{
return;
}
if (iReason & MSYS_CALLBACK_REASON_LBUTTON_REPEAT)
{
if( fSlideIsActive == FALSE)
{
// not active leave
return;
}
// check to see if we have moved
if( MSYS_GetRegionUserData(pRegion, 0) != iAttribute )
{
// different regions
iAttribute = MSYS_GetRegionUserData(pRegion, 0);
sOldX = -1;
sOldY = -1;
return;
}
uiBarToReRender = iAttribute;
giCurrentlySelectedStat = iAttribute;
gpCurrentScrollBox = pRegion;
// get new attribute value x
sNewX = pRegion->MouseXPos;
// sOldX has been reset, set to sNewX
if( sOldX == -1)
{
sOldX = sNewX;
return;
}
// check against old x
if( sNewX != sOldX )
{
// get old stat value
iCurrentAttributeValue = GetCurrentAttributeValue( iAttribute );
iNewValue = DetermineNewValue( sNewX );
// chenged, move mouse region if change large enough
if( iCurrentAttributeValue != iNewValue )
{
// update screen
fHasAnySlidingBarMoved = TRUE;
}
// change is enough
if ( iNewValue - iCurrentAttributeValue > 0)
{
// positive, increment stat
iCounter = iNewValue - iCurrentAttributeValue;
for( iCounter; iCounter > 0; iCounter--)
{
IncrementStat( iAttribute );
}
}
else
{
// negative, decrement stat
iCounter = iCurrentAttributeValue - iNewValue;
for( iCounter; iCounter > 0; iCounter--)
{
DecrementStat( iAttribute );
}
}
sOldX = sNewX;
}
}
else if(iReason & MSYS_CALLBACK_REASON_LBUTTON_UP)
{
if( fSlideIsActive )
{
// reset slide is active flag
fSlideIsActive = FALSE;
return;
}
// get mouse XY
sX = pRegion->MouseXPos;
sY = pRegion->MouseYPos;
// which region are we in?
// get attribute
iAttribute = MSYS_GetRegionUserData(pRegion, 0);
uiBarToReRender = iAttribute;
// get value of attribute
iCurrentAttributeValue = GetCurrentAttributeValue( iAttribute );
// set the new attribute value based on position of mouse click
iNewAttributeValue = DetermineNewValue( sX );
// too high, reset to MAX_ATTIBUTEPOINT
if( iNewAttributeValue > iMaxAttribute )
{
iNewAttributeValue = iMaxAttribute;
}
// get the delta
iAttributeDelta = iCurrentAttributeValue - iNewAttributeValue;
// set Counter
iCounter = iAttributeDelta;
// check if increment or decrement
if( iAttributeDelta > 0)
{
// decrement
for( iCounter = 0; iCounter < iAttributeDelta; iCounter++ )
{
DecrementStat( iAttribute );
}
}
else
{
// increment attribute
for( iCounter = iAttributeDelta; iCounter < 0; iCounter++ )
{
if( iCurrentAttributeValue == 0)
{
iCounter = 0;
}
IncrementStat( iAttribute );
}
}
// update screen
fHasAnySlidingBarMoved = TRUE;
}
else if ( iReason & MSYS_CALLBACK_REASON_RBUTTON_UP )
{
}
else if( iReason & MSYS_CALLBACK_REASON_LBUTTON_DWN )
{
// get mouse positions
sX = pRegion->MouseXPos;
sY = pRegion->MouseYPos;
// get attribute
iAttribute = MSYS_GetRegionUserData(pRegion, 0);
uiBarToReRender = iAttribute;
// get value of attribute
iCurrentAttributeValue = GetCurrentAttributeValue( iAttribute );
// get the boxes bounding x
sNewX = DetermineNewPosition( iCurrentAttributeValue - iMinAttribute );
sNewX += LAPTOP_SCREEN_UL_X;
// the sNewX is below 0, reset to zero
if( sNewX < 0 )
{
sNewX = 0;
}
if( ( sX > sNewX )&&( sX < sNewX + SLIDER_BAR_WIDTH) )
{
// we are within the slide bar, set fact we want to drag and draw
fSlideIsActive = TRUE;
}
else
{
// otherwise want to jump to position
fSlideIsActive =FALSE;
}
}
}
void SliderBarRegionButtonCallback( MOUSE_REGION * pRegion, INT32 iReason )
{
if( iReason & MSYS_CALLBACK_REASON_LBUTTON_DWN )
{
fSlideIsActive = TRUE;
SliderRegionButtonCallback( &pSliderRegions[ MSYS_GetRegionUserData(pRegion, 0) ], MSYS_CALLBACK_REASON_LBUTTON_REPEAT);
}
if( iReason & MSYS_CALLBACK_REASON_LBUTTON_UP )
{
fSlideIsActive = FALSE;
}
}
INT32 GetCurrentAttributeValue( INT32 iAttribute )
{
// this function will get the value of the attribute that was passed to this fucntion via iAttribute
INT32 iValue =0;
switch( iAttribute )
{
case ( STRENGTH_ATTRIBUTE ):
iValue = iCurrentStrength;
break;
case ( DEXTERITY_ATTRIBUTE ):
iValue = iCurrentDexterity;
break;
case ( AGILITY_ATTRIBUTE ):
iValue = iCurrentAgility;
break;
case ( HEALTH_ATTRIBUTE ):
iValue = iCurrentHealth;
break;
case ( WISDOM_ATTRIBUTE ):
iValue = iCurrentWisdom;
break;
case ( LEADERSHIP_ATTRIBUTE ):
iValue = iCurrentLeaderShip;
break;
case ( MARKSMANSHIP_SKILL ):
iValue = iCurrentMarkmanship;
break;
case ( MEDICAL_SKILL ):
iValue = iCurrentMedical;
break;
case ( MECHANICAL_SKILL ):
iValue = iCurrentMechanical;
break;
case ( EXPLOSIVE_SKILL ):
iValue = iCurrentExplosives;
break;
}
return iValue;
}
void SetAttributes( void )
{
INT32 iExtraPoints = 0;
// added externilized multiplier for starting level - SADNRO
iLevelCostMultiplier = gGameExternalOptions.iIMPStartingLevelCostMultiplier;
/////////////////////////////////////////////////////////////////////////////////////////////////
// SANDRO - determine minimum attribute values due to chosen traits
// For new trait system only though
if ( gGameOptions.fNewTraitSystem )
{
// reset bonus pts
iCurrentBonusPoints = gGameExternalOptions.iImpAttributePoints;
//Determine if the player has any extra points
iExtraPoints += iPlayersAttributePointsBonusForDisabilitySelected();
iExtraPoints += DoesPlayerHaveExtraAttibutePointsToDistributeBasedOnSkillSelection();
if( iExtraPoints > 0 )
iCurrentBonusPoints += iExtraPoints;
// Get Strength minimum
iStrengthMinimum = StrengthRequiredDueToMajorSkills();
if ( iStrengthMinimum < gGameExternalOptions.iMinAttribute )
iStrengthMinimum = gGameExternalOptions.iMinAttribute;
iStrengthMinimum += StrengthRequiredAdjustmentForMinorTraits( iStrengthMinimum );
// hehehe, make the alternative weapon holding anim requiring a big strength
if ( bBadAssSelected() && iStrengthMinimum < 80 )
iStrengthMinimum = 80;
if ( iStrengthMinimum > gGameExternalOptions.iMaxAttribute )
iStrengthMinimum = gGameExternalOptions.iMaxAttribute;
iCurrentStrength = iStrengthMinimum;
iCurrentBonusPoints -= iStrengthMinimum;
// Get Agility minimum
iAgilityMinimum = AgilityRequiredDueToMajorSkills();
if ( iAgilityMinimum < gGameExternalOptions.iMinAttribute )
iAgilityMinimum = gGameExternalOptions.iMinAttribute;
iAgilityMinimum += AgilityRequiredAdjustmentForMinorTraits( iAgilityMinimum );
if ( iAgilityMinimum > gGameExternalOptions.iMaxAttribute )
iAgilityMinimum = gGameExternalOptions.iMaxAttribute;
iCurrentAgility = iAgilityMinimum;
iCurrentBonusPoints -= iAgilityMinimum;
// Get Dexterity minimum
iDexterityMinimum = DexterityRequiredDueToMajorSkills();
if ( iDexterityMinimum < gGameExternalOptions.iMinAttribute )
iDexterityMinimum = gGameExternalOptions.iMinAttribute;
iDexterityMinimum += DexterityRequiredAdjustmentForMinorTraits( iDexterityMinimum );
if ( iDexterityMinimum > gGameExternalOptions.iMaxAttribute )
iDexterityMinimum = gGameExternalOptions.iMaxAttribute;
iCurrentDexterity = iDexterityMinimum;
iCurrentBonusPoints -= iDexterityMinimum;
// Get Health minimum
iHealthMinimum = HealthRequiredDueToMajorSkills();
if ( iHealthMinimum <= 0 )
iHealthMinimum = gGameExternalOptions.iMinAttribute;
iHealthMinimum += HealthRequiredAdjustmentForMinorTraits( iHealthMinimum );
if ( iHealthMinimum > gGameExternalOptions.iMaxAttribute )
iHealthMinimum = gGameExternalOptions.iMaxAttribute;
iCurrentHealth = iHealthMinimum;
iCurrentBonusPoints -= iHealthMinimum;
// Get Leadership minimum
iLeaderShipMinimum = LeadershipRequiredDueToMajorSkills();
if ( iLeaderShipMinimum < gGameExternalOptions.iMinAttribute )
iLeaderShipMinimum = gGameExternalOptions.iMinAttribute;
iLeaderShipMinimum += LeaderShipRequiredAdjustmentForMinorTraits( iLeaderShipMinimum );
if ( iLeaderShipMinimum > gGameExternalOptions.iMaxAttribute )
iLeaderShipMinimum = gGameExternalOptions.iMaxAttribute;
iCurrentLeaderShip = iLeaderShipMinimum;
iCurrentBonusPoints -= (iLeaderShipMinimum - gGameExternalOptions.iMinAttribute + gGameExternalOptions.iMaxZeroBonus);
// Get Wisdom minimum
iWisdomMinimum = WisdomRequiredDueToMajorSkills();
if ( iWisdomMinimum < gGameExternalOptions.iMinAttribute )
iWisdomMinimum = gGameExternalOptions.iMinAttribute;
iWisdomMinimum += WisdomRequiredAdjustmentForMinorTraits( iWisdomMinimum );
if ( iWisdomMinimum > gGameExternalOptions.iMaxAttribute )
iWisdomMinimum = gGameExternalOptions.iMaxAttribute;
iCurrentWisdom = iWisdomMinimum;
iCurrentBonusPoints -= iWisdomMinimum;
// Get Marksmanship minimum
iMarkmanshipMinimum = MarksmanshipRequiredDueToMajorSkills();
if ( iMarkmanshipMinimum < gGameExternalOptions.iMinAttribute )
iMarkmanshipMinimum = gGameExternalOptions.iMinAttribute;
iMarkmanshipMinimum += MarksmanshipRequiredAdjustmentForMinorTraits( iMarkmanshipMinimum );
if ( iMarkmanshipMinimum > gGameExternalOptions.iMaxAttribute )
iMarkmanshipMinimum = gGameExternalOptions.iMaxAttribute;
iCurrentMarkmanship = iMarkmanshipMinimum;
iCurrentBonusPoints -= (iMarkmanshipMinimum - gGameExternalOptions.iMinAttribute + gGameExternalOptions.iMaxZeroBonus);
// Get Mechanical minimum
iMechanicalMinimum = MechanicalRequiredDueToMajorSkills();
if ( iMechanicalMinimum < gGameExternalOptions.iMinAttribute )
iMechanicalMinimum = gGameExternalOptions.iMinAttribute;
iMechanicalMinimum += MechanicalRequiredAdjustmentForMinorTraits( iMechanicalMinimum );
if ( iMechanicalMinimum > gGameExternalOptions.iMaxAttribute )
iMechanicalMinimum = gGameExternalOptions.iMaxAttribute;
iCurrentMechanical = iMechanicalMinimum;
iCurrentBonusPoints -= (iMechanicalMinimum - gGameExternalOptions.iMinAttribute + gGameExternalOptions.iMaxZeroBonus);
// Get Medical minimum
iMedicalMinimum = MedicalRequiredDueToMajorSkills();
if ( iMedicalMinimum < gGameExternalOptions.iMinAttribute )
iMedicalMinimum = gGameExternalOptions.iMinAttribute;
iMedicalMinimum += MedicalRequiredAdjustmentForMinorTraits( iMedicalMinimum );
if ( iMedicalMinimum > gGameExternalOptions.iMaxAttribute )
iMedicalMinimum = gGameExternalOptions.iMaxAttribute;
iCurrentMedical = iMedicalMinimum;
iCurrentBonusPoints -= (iMedicalMinimum - gGameExternalOptions.iMinAttribute + gGameExternalOptions.iMaxZeroBonus);
// Get Explosives minimum
iExplosivesMinimum = ExplosivesRequiredDueToMajorSkills();
if ( iExplosivesMinimum < gGameExternalOptions.iMinAttribute )
iExplosivesMinimum = gGameExternalOptions.iMinAttribute;
iExplosivesMinimum += ExplosivesRequiredAdjustmentForMinorTraits( iExplosivesMinimum );
if ( iExplosivesMinimum > gGameExternalOptions.iMaxAttribute )
iExplosivesMinimum = gGameExternalOptions.iMaxAttribute;
iCurrentExplosives = iExplosivesMinimum;
iCurrentBonusPoints -= (iExplosivesMinimum - gGameExternalOptions.iMinAttribute + gGameExternalOptions.iMaxZeroBonus);
// if we exceeded points available, just give us zero points, but keep the attribute minimums untouched
if ( iCurrentBonusPoints < 0 )
iCurrentBonusPoints = 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
else // ORIGINAL
{
// default
iStrengthMinimum = gGameExternalOptions.iMinAttribute;
iAgilityMinimum = gGameExternalOptions.iMinAttribute;
iDexterityMinimum = gGameExternalOptions.iMinAttribute;
iHealthMinimum = gGameExternalOptions.iMinAttribute;
iLeaderShipMinimum = gGameExternalOptions.iMinAttribute;
iWisdomMinimum = gGameExternalOptions.iMinAttribute;
iMarkmanshipMinimum = gGameExternalOptions.iMinAttribute;
iMechanicalMinimum = gGameExternalOptions.iMinAttribute;
iMedicalMinimum = gGameExternalOptions.iMinAttribute;
iExplosivesMinimum = gGameExternalOptions.iMinAttribute;
iCurrentBonusPoints = gGameExternalOptions.iImpAttributePoints;
//Determine if the player has any extra points
iExtraPoints += iPlayersAttributePointsBonusForDisabilitySelected();
iExtraPoints += DoesPlayerHaveExtraAttibutePointsToDistributeBasedOnSkillSelection();
if( iExtraPoints > 0 )
iCurrentBonusPoints += iExtraPoints;
iCurrentStrength = gGameExternalOptions.iMinAttribute;
iCurrentDexterity = gGameExternalOptions.iMinAttribute;
iCurrentHealth = gGameExternalOptions.iMinAttribute;
iCurrentLeaderShip = gGameExternalOptions.iMinAttribute;
iCurrentWisdom = gGameExternalOptions.iMinAttribute;
iCurrentAgility = gGameExternalOptions.iMinAttribute;
iCurrentMarkmanship = gGameExternalOptions.iMinAttribute;
iCurrentMechanical = gGameExternalOptions.iMinAttribute;
iCurrentMedical = gGameExternalOptions.iMinAttribute;
iCurrentExplosives = gGameExternalOptions.iMinAttribute;
iCurrentBonusPoints -= ((5 * gGameExternalOptions.iMinAttribute) + (5 * gGameExternalOptions.iMaxZeroBonus));
}
////////////////////////////////////////////////////
ResetIncrementCharacterAttributes( );
return;
}
void DrawBonusPointsRemaining( void )
{
// draws the amount of points remaining player has
CHAR16 sString[64];
// just reviewing, don't blit stats
if( fReviewStats == TRUE )
{
return;
}
// parse amountof bns pts remaining
swprintf(sString, L"%d", iCurrentBonusPoints);
// set font color
SetFontForeground( FONT_WHITE );
SetFontBackground( FONT_BLACK );
SetFont( FONT12ARIAL );
// print string
mprintf( LAPTOP_SCREEN_UL_X + 425 ,LAPTOP_SCREEN_WEB_UL_Y + 51, sString );
InvalidateRegion( LAPTOP_SCREEN_UL_X + 425, LAPTOP_SCREEN_WEB_UL_Y + 51, LAPTOP_SCREEN_UL_X + 475, LAPTOP_SCREEN_WEB_UL_Y + 71 );
return;
}
void SetGeneratedCharacterAttributes( void )
{
// copies over the attributes of the player generated character
iStrength = iCurrentStrength ;
iDexterity = iCurrentDexterity;
iHealth = iCurrentHealth;
iLeadership = iCurrentLeaderShip;
iWisdom = iCurrentWisdom;
iAgility = iCurrentAgility;
// skills
iMarksmanship = iCurrentMarkmanship;
iMechanical = iCurrentMechanical;
iMedical = iCurrentMedical;
iExplosives = iCurrentExplosives;
return;
}
void StatAtZeroBoxCallBack( UINT8 bExitValue )
{
// yes, so start over, else stay here and do nothing for now
if( bExitValue == MSG_BOX_RETURN_YES )
{
MarkButtonsDirty();
}
else if( bExitValue == MSG_BOX_RETURN_NO )
{
IncrementStat( iCurrentStatAtZero );
fHasAnySlidingBarMoved = TRUE;
MarkButtonsDirty();
}
return;
}
INT32 DetermineNewValue( INT32 iNewX )
{
INT32 iMinAttribute = gGameExternalOptions.iMinAttribute;
INT32 iMaxAttribute = gGameExternalOptions.iMaxAttribute;
INT32 iNewValue=0;
INT32 iStartLoc = SKILL_SLIDE_START_X + LAPTOP_SCREEN_UL_X;
INT32 iPositionX = iNewX - iStartLoc;
FLOAT fPercentOfBar=0.0f;
fPercentOfBar = iPositionX / ( FLOAT)( BAR_WIDTH - SLIDER_BAR_WIDTH );
iNewValue = (INT32)( fPercentOfBar * ( iMaxAttribute - (FLOAT)iMinAttribute ) );
iNewValue += iMinAttribute;
// too high, reset to MAX_ATTIBUTEPOINT
if( iNewValue > iMaxAttribute )
{
iNewValue = iMaxAttribute;
}
return( iNewValue );
}
INT32 DetermineNewPosition( INT32 iAttribute )
{
INT32 iMinAttribute = gGameExternalOptions.iMinAttribute;
INT32 iMaxAttribute = gGameExternalOptions.iMaxAttribute;
INT32 iNewLoc=0;
INT32 iStartLoc = SKILL_SLIDE_START_X;
FLOAT fBasePixelScaleWidth = ( ( BAR_WIDTH - SLIDER_BAR_WIDTH ) / (FLOAT)( iMaxAttribute - iMinAttribute ) );
iNewLoc = (INT32)(iAttribute * fBasePixelScaleWidth);
if( iNewLoc < 0 )
{
iNewLoc = 0;
}
iNewLoc += iStartLoc;
return( iNewLoc );
}
INT8 StartingLevelChosen()
{
if ( (iStartingLevel > 0) && (iStartingLevel <= 10) )
return(iStartingLevel);
else
return(1);
} | [
"jazz_ja@b41f55df-6250-4c49-8e33-4aa727ad62a1"
]
| [
[
[
1,
2241
]
]
]
|
79af8fb9369ac96e874e32c04e606ee1c9806c55 | 7acbb1c1941bd6edae0a4217eb5d3513929324c0 | /GLibrary-CPP/sources/GSwap.hpp | d4812f94b90cc487b7b8c5092f03c8f5cf5633f7 | []
| no_license | hungconcon/geofreylibrary | a5bfc96e0602298b5a7b53d4afe7395a993498f1 | 3abf3e1c31a245a79fa26b4bcf2e6e86fa258e4d | refs/heads/master | 2021-01-10T10:11:51.535513 | 2009-11-30T15:29:34 | 2009-11-30T15:29:34 | 46,771,895 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 186 | hpp |
#ifndef __GWAP_HPP__
# define __GWAP_HPP__
#include "GExport.h"
template<typename T>
void GEXPORTED GSwap(T &t1, T &t2)
{
T tmp(t1);
t1 = t2;
t2 = tmp;
}
#endif
| [
"mvoirgard@34e8d5ee-a372-11de-889f-a79cef5dd62c"
]
| [
[
[
1,
16
]
]
]
|
ca4a4c28447f376fd5d2abc682c7f82da73db0f3 | daa67e21cc615348ba166d31eb25ced40fba9dc7 | /GameCode/Vector.h | ba6bfb50faaf819af8d75be2d47531858b8f21bf | []
| no_license | gearsin/geartesttroject | 443d48b7211f706ab2c5104204bad7228458c3f2 | f86f255f5e9d1d34a00a4095f601a8235e39aa5a | refs/heads/master | 2020-05-19T14:27:35.821340 | 2008-09-02T19:51:16 | 2008-09-02T19:51:16 | 32,342,555 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,256 | h | //------------------------------------------------------------------------------------------------------------------
#ifndef VECTOR_H
#define VECTOR_H
//------------------------------------------------------------------------------------------------------------------
#include "UnitTest.h"
//------------------------------------------------------------------------------------------------------------------
class cVector : public cUnitTest
{
public:
float m_X;
float m_Y;
float m_Z;
static cVector ZERO;
public:
//constructor
cVector();
cVector( float pX, float pY, float pZ );
cVector( cVector & pVec );
//Arithmetic operator overolad
inline cVector operator +( const cVector & pVec );
inline cVector operator -( const cVector & pVec );
inline cVector operator -( const cVector & pVec ) const;
inline cVector& operator +=( const cVector & pVec );
inline cVector& operator -=( const cVector & pVec );
////dot product
//cVector operator *( const cVector & pVec );
//cVector& operator *=( const cVector & pVec );
inline cVector operator *( const float pScale );
inline cVector operator *=( const float pScale );
inline cVector operator /( const float pVal );
inline cVector operator /=( const float pVal );
//conditional opeartor overload
inline bool operator ==( const cVector & pVec );
inline bool operator !=( const cVector & pVec );
inline bool operator <( const cVector & pVec );
inline bool operator <=( const cVector & pVec );
inline bool operator >( const cVector & pVec );
inline bool operator >=( const cVector & pVec );
//sign operator
inline cVector operator -( ) const;
//assignement operator
inline cVector& operator = ( const cVector & pVec );
//Lenght
inline float Length();
inline float SqrLength();
//Vector multiplication
float Dot( const cVector & pVec );
cVector Cross( const cVector & pVec );
//normalize
inline cVector& Normalize();
cVector RotateByMatrix( const float pMat[16] ) const;
//TestFunction
virtual void UnitTestFunction();
};
//------------------------------------------------------------------------------------------------------------------
inline cVector cVector::operator +( const cVector & pVec )
{
return cVector( m_X + pVec.m_X, m_Y + pVec.m_Y, m_Z + pVec.m_Z );
}
//------------------------------------------------------------------------------------------------------------------
inline cVector& cVector::operator +=( const cVector & pVec )
{
m_X += pVec.m_X;
m_Y += pVec.m_Y;
m_Z += pVec.m_Z;
return *this;
}
//------------------------------------------------------------------------------------------------------------------
inline cVector cVector::operator -( const cVector & pVec ) const
{
return cVector( m_X - pVec.m_X, m_Y - pVec.m_Y, m_Z - pVec.m_Z );
}
//------------------------------------------------------------------------------------------------------------------
inline cVector cVector::operator -( const cVector & pVec )
{
return cVector( m_X - pVec.m_X, m_Y - pVec.m_Y, m_Z - pVec.m_Z );
}
//------------------------------------------------------------------------------------------------------------------
inline cVector& cVector::operator -=( const cVector & pVec )
{
m_X -= pVec.m_X;
m_Y -= pVec.m_Y;
m_Z -= pVec.m_Z;
return *this;
}
//------------------------------------------------------------------------------------------------------------------
inline cVector& cVector::operator =( const cVector & pVec )
{
m_X = pVec.m_X;
m_Y = pVec.m_Y;
m_Z = pVec.m_Z;
return *this;
}
//------------------------------------------------------------------------------------------------------------------
inline cVector cVector::operator -() const
{
return ( cVector ( -m_X, -m_Y, -m_Z ) );
}
//------------------------------------------------------------------------------------------------------------------
inline float cVector::Length()
{
return sqrtf( m_X * m_X + m_Y * m_Y + m_Z * m_Z );
}
//------------------------------------------------------------------------------------------------------------------
inline float cVector::SqrLength()
{
return ( m_X * m_X + m_Y * m_Y + m_Z * m_Z );
}
//------------------------------------------------------------------------------------------------------------------
inline cVector cVector::operator *=( const float pScale )
{
m_X *= pScale;
m_Y *= pScale;
m_Z *= pScale;
return *this;
}
//------------------------------------------------------------------------------------------------------------------
inline cVector cVector::operator *( const float pScale )
{
//*this *= pScale;
return cVector( m_X * pScale, m_Y * pScale, m_Z * pScale );
}
//------------------------------------------------------------------------------------------------------------------
inline cVector cVector::operator /=( const float pVal )
{
float scale = 1.0f / pVal;
*this *= scale;
return *this;
}
//------------------------------------------------------------------------------------------------------------------
inline cVector cVector::operator /( const float pVal )
{
float scale = 1.0f / pVal;
return cVector( m_X * scale, m_Y * scale, m_Z * scale );
}
//------------------------------------------------------------------------------------------------------------------
inline bool cVector::operator == ( const cVector & pVec )
{
return ( m_X == pVec.m_X && m_Y == pVec.m_Y && m_Z == pVec.m_Z );
}
//------------------------------------------------------------------------------------------------------------------
inline bool cVector::operator != ( const cVector & pVec )
{
return ( m_X != pVec.m_X && m_Y != pVec.m_Y && m_Z != pVec.m_Z );
}
//------------------------------------------------------------------------------------------------------------------
inline bool cVector::operator < ( const cVector & pVec )
{
return ( m_X < pVec.m_X && m_Y < pVec.m_Y && m_Z < pVec.m_Z );
}
//------------------------------------------------------------------------------------------------------------------
inline bool cVector::operator <= ( const cVector & pVec )
{
return ( m_X <= pVec.m_X && m_Y <= pVec.m_Y && m_Z <= pVec.m_Z );
}
//------------------------------------------------------------------------------------------------------------------
inline bool cVector::operator > ( const cVector & pVec )
{
return ( m_X > pVec.m_X && m_Y > pVec.m_Y && m_Z > pVec.m_Z );
}
//------------------------------------------------------------------------------------------------------------------
inline bool cVector::operator >= ( const cVector & pVec )
{
return ( m_X >= pVec.m_X && m_Y >= pVec.m_Y && m_Z >= pVec.m_Z );
}
//------------------------------------------------------------------------------------------------------------------
inline cVector& cVector::Normalize()
{
float length = Length();
assert( length > 0 );
*this *= ( 1.0f / length );
return *this;
}
//------------------------------------------------------------------------------------------------------------------
#endif
| [
"sunil.ssingh@592c7993-d951-0410-8115-35849596357c"
]
| [
[
[
1,
235
]
]
]
|
38de9d8dbf754578bc2fcb4656163b03c8c14675 | 2a3952c00a7835e6cb61b9cb371ce4fb6e78dc83 | /BasicOgreFramework/PhysxSDK/Samples/SampleCommonCode/src/GLFontRenderer.h | 964b1e01382637ae91cc023f17ac229ef9c21ce9 | []
| 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 | UTF-8 | C++ | false | false | 842 | h | /*----------------------------------------------------------------------------*\
|
| AGEIA PhysX Technology
|
| www.ageia.com
|
\*----------------------------------------------------------------------------*/
#ifndef __GL_FONT_RENDERER__
#define __GL_FONT_RENDERER__
class GLFontRenderer{
private:
static bool m_isInit;
static unsigned int m_textureObject;
static int m_screenWidth;
static int m_screenHeight;
static float m_color[4];
public:
static bool init();
static void print(float x, float y, float fontSize, const char* pString, bool forceMonoSpace=false, int monoSpaceWidth=11, bool doOrthoProj=true);
static void setScreenResolution(int screenWidth, int screenHeight);
static void setColor(float r, float g, float b, float a);
};
#endif // __GL_FONT_RENDERER__
| [
"erucarno@789472dc-e1c3-11de-81d3-db62269da9c1"
]
| [
[
[
1,
31
]
]
]
|
9f6ee7516ce1236906f45e81ee38674a31a75ab2 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/mpl/test/size_t.cpp | 941d253aeca83dea3840fc6de672c0877638be73 | [
"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 | 880 | cpp |
// 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/boost/boost/libs/mpl/test/size_t.cpp,v $
// $Date: 2005/12/08 03:17:47 $
// $Revision: 1.3 $
// Necessary to overcome a strange name lookup bug in GCC 3.3 and 4.0 for Mac OS X
#if defined(__APPLE_CC__) && defined(__GNUC__) && (__GNUC__ <= 4)
# include <cassert>
#endif
#include <boost/mpl/size_t.hpp>
#include <boost/mpl/identity.hpp>
#include <boost/preprocessor/repetition/repeat_from_to.hpp>
#include "integral_wrapper_test.hpp"
MPL_TEST_CASE()
{
# define WRAPPER(T, i) mpl::size_t<i>
BOOST_PP_REPEAT_FROM_TO(1, 11, INTEGRAL_WRAPPER_TEST, std::size_t)
}
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
29
]
]
]
|
14f407d973e7d015e0dde29cfc9a043eefe18b2b | 17083b919f058848c3eb038eae37effd1a5b0759 | /SimpleGL/sgl/Utility/Referenced.h | 85856efede5b28a5f0590e5a9f58f655da998064 | []
| no_license | BackupTheBerlios/sgl | e1ce68dfc2daa011bdcf018ddce744698cc7bc5f | 2ab6e770dfaf5268c1afa41a77c04ad7774a70ed | refs/heads/master | 2021-01-21T12:39:59.048415 | 2011-10-28T16:14:29 | 2011-10-28T16:14:29 | 39,894,148 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,088 | h | #ifndef SIMPLE_GL_REFERENCED_H
#define SIMPLE_GL_REFERENCED_H
#include "DLLInterface.h"
#include <algorithm>
#include <cassert>
namespace sgl {
struct ref_counter;
/** Interface for reference counted objects which allows only
* weak_ptr and scoped_ptr.
*/
class WeakReferenced :
public DLLInterface
{
public:
/** Ger ref counter for weak_ptr */
virtual ref_counter* SGL_DLLCALL get_ref_counter() const = 0;
virtual ~WeakReferenced() {}
};
/** Interface for reference counted objects */
class Referenced :
public WeakReferenced
{
public:
virtual ~Referenced() {}
};
/** Counter for ref and weak references */
struct SGL_DLLEXPORT ref_counter
{
inline ref_counter( WeakReferenced* _ptr,
int _refCount = 0,
int _weakCount = 0 ) :
ptr(_ptr),
refCount(_refCount),
weakCount(_weakCount) {}
inline void add_ref() {
++refCount;
}
inline void remove_ref()
{
if ( --refCount == 0 )
{
ptr->Destroy();
ptr = 0;
if (weakCount == 0) {
Destroy();
}
}
}
inline int ref_count() {
return refCount;
}
inline void add_weak() {
++weakCount;
}
inline void remove_weak()
{
if ( --weakCount == 0 && !ptr ) {
Destroy();
}
}
inline int weak_count() {
return weakCount;
}
template<typename T>
inline T* get() {
return static_cast<T*>(ptr);
}
/* Destroys ref_counter inside DLL */
void SGL_DLLCALL Destroy();
public:
WeakReferenced* ptr;
int refCount;
int weakCount;
};
/* Implemenation of the reference counting objects */
template<typename Interface>
class ReferencedImpl :
public DLLImpl<Interface>
{
public:
typedef DLLImpl<Interface> base_type;
typedef ReferencedImpl<Interface> this_type;
private:
// noncopyable
ReferencedImpl(const this_type& /*impl*/);
ReferencedImpl& operator = (const this_type& /*rhs*/);
public:
ReferencedImpl() :
refCounter(0)
{}
template<typename T0>
ReferencedImpl(T0 _0) :
DLLImpl<Interface>(_0),
refCounter(0)
{}
template<typename T0, typename T1>
ReferencedImpl(T0 _0, T1 _1) :
DLLImpl<Interface>(_0, _1),
refCounter(0)
{}
template<typename T0, typename T1, typename T2>
ReferencedImpl(T0 _0, T1 _1, T2 _3) :
DLLImpl<Interface>(_0, _1, _3),
refCounter(0)
{}
ref_counter* SGL_DLLCALL get_ref_counter() const
{
if (!refCounter) {
refCounter = new ref_counter( const_cast<this_type*>(this) );
}
return refCounter;
}
virtual ~ReferencedImpl() {}
private:
mutable ref_counter* refCounter;
};
// Forward
template<typename T>
class weak_ptr;
/** Smart pointer for sgl classes */
template<typename T>
class scoped_ptr
{
template<typename Y> friend class scoped_ptr;
template<typename Y> friend class weak_ptr;
public:
typedef T value_type;
typedef scoped_ptr<T> this_type;
private:
// noncopyable
scoped_ptr(const this_type&);
scoped_ptr& operator = (const this_type&);
public:
inline scoped_ptr() :
ptr(0)
{}
inline explicit scoped_ptr(T* _ptr) :
ptr(_ptr)
{}
inline ~scoped_ptr()
{
if (ptr)
{
ref_counter* refCounter = ptr->get_ref_counter();
ptr->Destroy();
refCounter->ptr = 0;
if (refCounter->weakCount == 0) {
refCounter->Destroy();
}
}
}
// Compare objects
template<class Y>
inline bool operator == (const scoped_ptr<Y>& rhs) const { return ptr == rhs.ptr; }
template<class Y>
inline bool operator == (Y* rhs) const { return ptr == rhs; }
template<class Y>
inline bool operator != (const scoped_ptr<Y>& rhs) const { return ptr != rhs.ptr ; }
template<class Y>
inline bool operator != (Y* rhs) const { return ptr != rhs; }
// Set pointer to 0. Copy and swap idiom
inline void reset() {
this_type().swap(*this);
}
// Set new pointer to ref_ptr. Copy and swap idiom
inline void reset(T* ptr) {
this_type(ptr).swap(*this);
}
// Swap ref_ptr's
inline void swap(this_type& sPtr) throw() {
std::swap(ptr, sPtr.ptr);
}
// Get object
inline T* operator -> () const { return ptr; }
inline T& operator *() const { return *ptr; }
inline T* get() const { return ptr; }
// implicit cast to the pointer type
inline operator T* () { return ptr; }
inline operator const T* () const { return ptr; }
private:
T* ptr;
};
/** Smart pointer with reference counting for sgl classes */
template<typename T>
class ref_ptr
{
template<typename Y> friend class ref_ptr;
template<typename Y> friend class weak_ptr;
public:
typedef T value_type;
typedef ref_ptr<T> this_type;
public:
inline ref_ptr() :
ptr(0)
{}
inline ref_ptr(const ref_ptr<T>& rPtr) :
ptr(rPtr.ptr)
{
if (ptr) {
ptr->get_ref_counter()->add_ref();
}
}
template<typename Y>
inline ref_ptr(const ref_ptr<Y>& rPtr) :
ptr(rPtr.ptr)
{
if (ptr) {
ptr->get_ref_counter()->add_ref();
}
}
inline explicit ref_ptr(T* _ptr) :
ptr(_ptr)
{
// make sure T can be casted to Referenced
if (ptr)
{
if ( ref_counter* ref = static_cast<const Referenced*>(ptr)->get_ref_counter() ) {
ref->add_ref();
}
}
}
inline ~ref_ptr()
{
if (ptr) {
ptr->get_ref_counter()->remove_ref();
}
}
// Compare objects
template<class Y>
inline bool operator == (const ref_ptr<Y>& rhs) const { return ptr == rhs.ptr; }
template<class Y>
inline bool operator == (Y* rhs) const { return ptr == rhs; }
template<class Y>
inline bool operator != (const ref_ptr<Y>& rhs) const { return ptr != rhs.ptr; }
template<class Y>
inline bool operator != (Y* rhs) const { return ptr != rhs; }
// Copy ref_ptr. Copy and swap idiom
inline ref_ptr<T>& operator = (const ref_ptr<T>& rPtr)
{
if (ptr != rPtr.ptr) {
this_type(rPtr).swap(*this);
}
return *this;
}
// Set pointer to 0. Copy and swap idiom
inline void reset() {
this_type().swap(*this);
}
// Set new pointer to ref_ptr. Copy and swap idiom
inline void reset(T* _ptr) {
this_type(_ptr).swap(*this);
}
// Swap ref_ptr's
inline void swap(this_type& rPtr) throw() {
std::swap(ptr, rPtr.ptr);
}
// Get object
inline T* operator -> () const { return ptr; }
inline T& operator *() const { return *ptr; }
inline T* get() const { return ptr; }
// implicit cast to the pointer type
inline operator T* () { return ptr; }
inline operator const T* () const { return ptr; }
private:
T* ptr;
};
/** Smart pointer with intrusive weak reference counting for sgl classes */
template<typename T>
class weak_ptr
{
public:
typedef T value_type;
typedef weak_ptr<T> this_type;
public:
inline weak_ptr() :
refCounter(0)
{}
inline weak_ptr(const weak_ptr<T>& rPtr) :
refCounter(rPtr.refCounter)
{
if (refCounter) {
refCounter->add_weak();
}
}
template<class Y>
inline weak_ptr(const weak_ptr<Y>& rPtr) :
refCounter( rPtr.refCounter.cast() )
{
if (refCounter) {
refCounter->add_weak();
}
}
inline explicit weak_ptr(Referenced* ptr) :
refCounter(0)
{
if (ptr)
{
refCounter = ptr->get_ref_counter();
refCounter->add_weak();
}
}
inline explicit weak_ptr(WeakReferenced* ptr) :
refCounter(0)
{
if (ptr)
{
refCounter = ptr->get_ref_counter();
refCounter->add_weak();
}
}
inline ~weak_ptr()
{
refCounter->remove_weak();
}
// Compare objects
template<class Y>
inline bool operator == (const weak_ptr<Y>& rhs) const { return refCounter == rhs.refCounter; }
template<class Y>
inline bool operator == (Y* rhs) const { return refCounter && refCounter->ptr == rhs; }
template<class Y>
inline bool operator != (const weak_ptr<Y>& rhs) const { return refCounter != rhs.refCounter; }
template<class Y>
inline bool operator != (Y* rhs) const { return !refCounter || refCounter->ptr != rhs; }
// Copy weak_ptr. Copy and swap idiom
inline weak_ptr<T>& operator = (const weak_ptr<T>& rPtr)
{
if (refCounter != rPtr.refCounter) {
this_type(rPtr).swap(*this);
}
return *this;
}
// Set pointer to 0. Copy and swap idiom
inline void reset() {
this_type().swap(*this);
}
// Set new pointer to weak_ptr. Copy and swap idiom
inline void reset(T* _ptr)
{
if (refCounter->ptr != _ptr) {
this_type(_ptr).swap(*this);
}
}
// Swap weak_ptr's
inline void swap(this_type& rPtr) throw()
{
std::swap< ref_counter* >(refCounter, rPtr.refCounter);
}
// Get object
inline ref_ptr<T> lock () const
{
if ( refCounter && refCounter->get<T>() ) {
return ref_ptr<T>( refCounter->get<T>() );
}
return ref_ptr<T>();
}
// implicit cast to bool type
inline operator bool() const { return refCounter != 0; }
private:
ref_counter* refCounter;
};
/** static_cast for ref_ptr */
template<typename T, typename Y>
ref_ptr<T> ref_static_cast(const ref_ptr<Y>& ptr)
{
return ref_ptr<T>( static_cast<T*>( ptr.get() ) );
}
/** const_cast for ref_ptr */
template<typename T, typename Y>
ref_ptr<T> ref_const_cast(const ref_ptr<Y>& ptr)
{
return ref_ptr<T>( const_cast<T*>( ptr.get() ) );
}
/** dynamic_cast for ref_ptr */
template<typename T, typename Y>
ref_ptr<T> ref_dynamic_cast(const ref_ptr<Y>& ptr)
{
return ref_ptr<T>( dynamic_cast<T*>( ptr.get() ) );
}
/** static_cast for weak_ptr */
template<typename T, typename Y>
weak_ptr<T> weak_static_cast(const weak_ptr<Y> rPtr)
{
return weak_ptr<T>( static_cast<T*>( rPtr.get() ) );
}
/** const_cast for weak_ptr */
template<typename T, typename Y>
weak_ptr<T> weak_const_cast(const weak_ptr<Y> rPtr)
{
return weak_ptr<T>( const_cast<T*>( rPtr.get() ) );
}
/** dynamic_cast for weak_ptr */
template<typename T, typename Y>
weak_ptr<T> weak_dynamic_cast(const weak_ptr<Y> rPtr)
{
return weak_ptr<T>( dynamic_cast<T*>( rPtr.get() ) );
}
} // namespace sgl
// for boost::intrusive_ptr
namespace boost {
inline void intrusive_ptr_add_ref(sgl::Referenced* ptr)
{
ptr->get_ref_counter()->add_ref();
}
inline void intrusive_ptr_release(sgl::Referenced* ptr)
{
ptr->get_ref_counter()->remove_ref();
}
// to allow boost mem_fn & bind from ref_ptr
template<typename T>
T* get_pointer(const sgl::ref_ptr<T>& ptr)
{
return ptr.get();
}
// to allow boost mem_fn & bind from ref_ptr
template<typename T>
T* get_pointer(const sgl::weak_ptr<T>& ptr)
{
return ptr.get();
}
} // namespace boost
#endif // SIMPLE_GL_REFERENCED_H
| [
"devnull@localhost"
]
| [
[
[
1,
513
]
]
]
|
dd069935417cbe9ee94b72beb48c5fcbed04f553 | 01c236af2890d74ca5b7c25cec5e7b1686283c48 | /Src/Trick.h | e27301c185504cb1a8bee3e51612545a39979f78 | [
"MIT"
]
| permissive | muffinista/palm-pitch | 80c5900d4f623204d3b837172eefa09c4efbe5e3 | aa09c857b1ccc14672b3eb038a419bd13abc0925 | refs/heads/master | 2021-01-19T05:43:04.740676 | 2010-07-08T14:42:18 | 2010-07-08T14:42:18 | 763,958 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,197 | h | #ifndef TRICK_H
#define TRICK_H
#include "PlayersCard.h"
class Player;
class Trick {
public:
Trick();
~Trick();
//
// load/save routines
//
void Read(CStream& rStream);
void Write(CStream& rStream);
//
// cleanup routines
//
void CleanUp();
void PostHandCleanUp();
//
// routines for AI, display, etc.
//
Boolean FirstTrickP();
Player *Winner();
Card::suit_t getLead();
Card::suit_t getTrump();
Boolean hasJack();
Boolean hasTen();
Card *currentLow();
Card *currentHigh();
Card *highestCardNotPlayed(Card::suit_t f);
Card *highestCardPlayed(Card::suit_t f);
Card *lowestCardPlayed();
Boolean noTrumpLeft(Player *p);
//
// logic routines
//
Card *RecordPlayedCard(Player *, Card *);
Boolean CalculateGamePoints(Int16 *tmp_high, Int16 *tmp_low, Int16 *tmp_jack, Int16 *tmp_game,
Card::face_t *tmp_high_c, Card::face_t *tmp_low_c,
Boolean *won_smudge );
void ApplyGamePoints();
/* public member fields */
CArray<PlayersCard *> *book;
PlayersCard *current_winner;
PlayersCard *lead;
CArray<Card*> team_winnings[3];
CArray<Card*> played_cards[4];
#define played_clubs played_cards[0]
#define played_diamonds played_cards[1]
#define played_hearts played_cards[2]
#define played_spades played_cards[3]
Boolean no_trump_first_trick;
Boolean first_trick;
Boolean won_bid;
Int16 cards_left;
Int16 trump_played;
private:
Boolean isCardPlayed(Card::suit_t s, Card::face_t f);
void NewScore(Int16 *score0, Int16 *score1, Int16 *score2,
Boolean won_bid,
Int16 tmp_high, Int16 tmp_low, Int16 tmp_jack, Int16 tmp_game,
Card::face_t tmp_high_c, Card::face_t tmp_low_c,
Boolean smudge );
/* pointers to high and low card */
Card::face_t high_c;
Card::face_t low_c;
/* pointer to players of high and low cards and jack */
Int16 high_p;
Int16 low_p;
Int16 jack_p;
Int16 game_p;
Int16 old_score0;
Int16 old_score1;
Int16 old_score2;
Int16 score0;
Int16 score1;
Int16 score2;
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
109
]
]
]
|
f9e2699c1ebe19ff199d1a084e88bd64e4e4e741 | fbe2cbeb947664ba278ba30ce713810676a2c412 | /iptv_root/iptv_kernel/include/iptv_kernel/ChannelInfo.h | dfc42340d3fc1e6935a791416c9f66d24ed4420e | []
| no_license | abhipr1/multitv | 0b3b863bfb61b83c30053b15688b070d4149ca0b | 6a93bf9122ddbcc1971dead3ab3be8faea5e53d8 | refs/heads/master | 2020-12-24T15:13:44.511555 | 2009-06-04T17:11:02 | 2009-06-04T17:11:02 | 41,107,043 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 841 | h | #ifndef _CHANNELINFO_H_
#define _CHANNELINFO_H_
#include "VBLib/VBLib.h"
#include "iptv_kernel/UserInfo.h"
class ChannelInfo
{
private:
br::com::sbVB::VBLib::VBString m_name;
br::com::sbVB::VBLib::VBString m_description;
int m_userCount;
public:
ChannelInfo( br::com::sbVB::VBLib::VBString channelName = "",
br::com::sbVB::VBLib::VBString channelDescription = "",
int userCount = 0);
ChannelInfo(const ChannelInfo &info);
virtual ~ChannelInfo();
br::com::sbVB::VBLib::VBString GetChannelName() const;
br::com::sbVB::VBLib::VBString GetChannelDescription() const;
int GetUserCount() const;
void SetChannelName(br::com::sbVB::VBLib::VBString channelName);
void SetChannelDescription(br::com::sbVB::VBLib::VBString channelDescription);
void SetUserCount(int userCount);
};
#endif
| [
"heineck@c016ff2c-3db2-11de-a81c-fde7d73ceb89"
]
| [
[
[
1,
32
]
]
]
|
49ea9cd4c9a0948bb7204f85b1728a8b7b034244 | 6b99c157ea698e70fca17073c680638f8e516d08 | /ComConnection.h | 6ead72e5dcd452d968b95026a336e727d518337f | []
| no_license | melagabri/sendelf | 3aef89b2e3e7d0424e738fbe87701672d6026fbf | beb17f02ceef3f71cf9e13cae545abe77c282764 | refs/heads/master | 2021-01-10T06:30:37.130626 | 2009-10-10T16:39:39 | 2009-10-10T16:39:39 | 54,057,363 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 590 | h | #pragma once
#include "connection.h"
typedef ULONG (__stdcall *Func_FT_Open) (int deviceNumber, HANDLE *handle);
typedef ULONG (__stdcall *Func_FT_GetComPortNumber) (HANDLE handle, LPLONG portnumber);
typedef ULONG (__stdcall *Func_FT_Close) (HANDLE handle);
class CComConnection :
public CConnection
{
public:
CComConnection(void);
~CComConnection(void);
void Connect();
void Send(const char *buffer, int length);
void Disconnect();
private:
HANDLE gecko;
Func_FT_Open FT_Open;
Func_FT_GetComPortNumber FT_GetComPortNumber;
Func_FT_Close FT_Close;
};
| [
"[email protected]"
]
| [
[
[
1,
24
]
]
]
|
293d33dd28d95f624f89139b02f9c0ca2327eccd | f794fd0abaed1011ede69129e36ce436347693fd | /CBoxPrimitive.h | 8931226bc422ab3dd02d3e08abbf1f90a5c3fc47 | []
| no_license | konradrodzik/raytracer-cpu-gpu | d7a048a45f94457d7dde5f1eb3b34ecc83867ffb | 0ac756a43998b4c0a3d6c923745922ba03cf7b6c | refs/heads/master | 2016-09-15T21:00:23.107984 | 2011-01-24T01:04:41 | 2011-01-24T01:04:41 | 32,467,714 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,560 | h | ////////////////////////////////////
// Konrad Rodrigo Rodzik (c) 2010 //
////////////////////////////////////
#ifndef __H_CBoxPrimitive_H__
#define __H_CBoxPrimitive_H__
class CBoxPrimitive : public CBasePrimitive
{
public:
// Default constructor
CBoxPrimitive();
// Initialize constructor
CBoxPrimitive(CAABBox& box);
// Get type of primitive
E_PRIMITIVE_TYPE getType();
// Intersect function
int intersect(CRay& ray, float& distance);
// Get primitive normal at given position
CVector3 getNormal(const CVector3& pos);
__device__ float3 getNormal(float3 pos)
{
return make_float3(0, 0, 0);
}
// Set position
void setPosition(CVector3& pos);
// Set size
void setSize(CVector3& size);
// Set rotation angle in Y axis
void setAngleY(float angle);
// Get rotation angle in Y axis
float getAngleY();
// Get sinus from angle Y
float getSinusY();
// Get cosinus from angle Y
float getCosinusY();
__device__ CAABBox& getBox() { return m_box; }
__device__ float getSinusAngle() { return m_sinAngleY; }
__device__ float getCosinusAngle() { return m_cosAngleY; }
__device__ float3 getColor(float3 pos)
{
//CColor tmpCol = m_material.getColor();
//return make_float3(tmpCol.m_x, tmpCol.m_y, tmpCol.m_z);
return m_material.getColorEx();
}
private:
CAABBox m_box; // Axis aligned bounding box
float m_angleY; // Rotate angle in Y axis
float m_cosAngleY; // Cosinus from rotation angle Y
float m_sinAngleY; // Sinus from rotation angle Y
};
#endif | [
"konrad.rodzik@8e044db2-5a41-7fc7-fe2a-5b7de51f5869"
]
| [
[
[
1,
66
]
]
]
|
633ff10427e46a4b9c8195cd3e6361ecdb24ff95 | 2a47a0a9749be9adae403d99f6392f9d412fca53 | /OS simulation/store point/FinalFiles/Job.h | d49db0d6cfe46329d1903c2167ccfcf5ed7c3ec1 | []
| no_license | waseemilahi/waseem | 153bed6788475a88d234d75a323049a9d8ec47fe | 0bb2bddcc8758477f0ad5db85bfc927db2ae07af | refs/heads/master | 2020-03-30T14:59:17.066002 | 2008-11-22T01:21:04 | 2008-11-22T01:21:04 | 32,640,847 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,713 | h | # ifndef JOB_H
# define JOB_H
# include <stdio.h>
//Declaration of the class Job.
class Job{
public:
//The constructors
Job();
Job(long jobnum,long prty,long size,long maxtime,long currenttime);
// The accessors and mutators.
long getjobsize();
void setjobsize(long size);
long getjobnumber();
void setjobnumber(long jbnumber);
long getpriority();
void setpriority(long prty);
long getlocation();
void setlocation(long location);
long getmaxcputime();
void setmaxcputime(long cputime);
long getiopending();
void setiopending(long iopending);
long gettimearrived();
void settimearrived(long currenttime);
long getcputimeused();
void setcputimeused();
long gettimejobstopped();
void settimejobstopped(long currenttime);
long gettimejobran();
void settimejobran(long currenttime);
long gettimeslice();
void settimeslice();
unsigned getincorebit();
void setincorebit(unsigned incore);
unsigned getlatchedbit();
void setlatchedbit(unsigned latch);
unsigned getblockedbit();
void setblockedbit(unsigned blocked);
unsigned getterminatebit();
void setterminatebit(unsigned term);
unsigned getreadybit();
void setreadybit(unsigned ry);
unsigned getwaitingbit();
void setwaitingbit(unsigned waiting);
unsigned getintransitbit();
void setintransitbit(unsigned moving);
void incrementiopending();
void decrementiopending();
void setmemoryavailablebit(unsigned mab);
unsigned getmemoryavailablebit();
private:
// The fields.
long size;
long jobnumber;
long priority;
long location_in_memory;
long max_cpu_time;
long io_pending;
long time_arrived; //First time in the system.
long cpu_time_used;
long time_slice;
long time_job_ran;
long time_job_stopped;
struct flags{
unsigned incore: 1;
unsigned memoryavailable: 1;
unsigned latched: 1;
unsigned blocked: 1;
unsigned term: 1;
unsigned ready: 1;
unsigned wait_io: 1;
unsigned intransit: 1;
}flagbits;
};//end of class declaration.
/*Methods definitions.
--------------------*/
/*The constructors*/
Job::Job(){
Job(-1,0,0,0,0);
}
Job::Job(long jn,long prty,long size,long maxtime,long currenttime){
setjobsize(size);
setjobnumber(jn);
setpriority(prty);
setmaxcputime(maxtime);
settimearrived(currenttime);
this->cpu_time_used=0;
}
/*The accessors.
--------------*/
long Job::getjobsize(){ return this->size; }
long Job::getjobnumber(){ return this->jobnumber; }
long Job::getpriority(){ return this->priority; }
long Job::getlocation(){ return this->location_in_memory; }
long Job::getmaxcputime(){ return this->max_cpu_time; }
long Job::gettimearrived(){ return this->time_arrived; }
long Job::getiopending(){ return this->io_pending; }
long Job::gettimejobran(){ return this->time_job_ran; }
long Job::gettimejobstopped(){ return this->time_job_stopped; }
long Job::getcputimeused(){ return this->cpu_time_used; }
long Job::gettimeslice(){ return this->time_slice; }
unsigned Job::getincorebit(){ return this->flagbits.incore; }
unsigned Job::getlatchedbit(){ return this->flagbits.latched; }
unsigned Job::getblockedbit(){ return this->flagbits.blocked; }
unsigned Job::getterminatebit(){ return this->flagbits.term; }
unsigned Job::getreadybit(){ return this->flagbits.ready; }
unsigned Job::getwaitingbit(){ return this->flagbits.wait_io; }
unsigned Job::getintransitbit(){ return this->flagbits.intransit; }
unsigned Job::getmemoryavailablebit(){ return this->flagbits.memoryavailable; }
/*The mutators.
-------------*/
void Job::setjobnumber(long jbnumber){
this->jobnumber=jbnumber;
return ;
}
void Job::setjobsize(long jbsize){
this->size=jbsize;
return ;
}
void Job::setpriority(long prty){
this->priority=prty;
return ;
}
void Job::setlocation(long location){
this->location_in_memory=location;
return ;
}
void Job::setmaxcputime(long maxcpu){
this->max_cpu_time=maxcpu;
return ;
}
void Job::setiopending(long iop){
this->io_pending=iop;
return ;
}
void Job::settimearrived(long currenttime){
this->time_arrived=currenttime;
return ;
}
void Job::settimejobstopped(long currenttime){
this->time_job_stopped=currenttime;
return ;
}
void Job::settimejobran(long currenttime){
this->time_job_ran=currenttime;
return ;
}
void Job::setcputimeused(){
this->cpu_time_used=this->cpu_time_used+(this->time_job_stopped-time_job_ran);
return ;
}
void Job::settimeslice(){
this->time_slice=(this->max_cpu_time)-(this->cpu_time_used);;
return ;
}
void Job::setincorebit(unsigned icb){
this->flagbits.incore=icb;
return ;
}
void Job::setlatchedbit(unsigned lb){
this->flagbits.latched=lb;
return ;
}
void Job::setblockedbit(unsigned bb){
this->flagbits.blocked=bb;
return ;
}
void Job::setterminatebit(unsigned tb){
this->flagbits.term=tb;
return ;
}
void Job::setreadybit(unsigned rdy){
this->flagbits.ready=rdy;
return ;
}
void Job::setmemoryavailablebit(unsigned mab){
this->flagbits.memoryavailable=mab;
return ;
}
void Job::setwaitingbit(unsigned wiob){
this->flagbits.wait_io=wiob;
return ;
}
void Job::setintransitbit(unsigned intb){
this->flagbits.intransit=intb;
return ;
}
void Job::incrementiopending(){this->io_pending++;}
void Job::decrementiopending(){this->io_pending--;}
# endif | [
"waseemilahi@b30cb682-9650-11dd-b20a-03c46e462ecf"
]
| [
[
[
1,
294
]
]
]
|
784391036cf0c068ddd4887a9da79e2fabc577e5 | 2b80036db6f86012afcc7bc55431355fc3234058 | /src/contrib/apedecoder/APESourceSupplier.h | e21374c29df55f1212ad190cc1b42b71e83bb728 | [
"BSD-3-Clause"
]
| permissive | leezhongshan/musikcube | d1e09cf263854bb16acbde707cb6c18b09a0189f | e7ca6a5515a5f5e8e499bbdd158e5cb406fda948 | refs/heads/master | 2021-01-15T11:45:29.512171 | 2011-02-25T14:09:21 | 2011-02-25T14:09:21 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 2,164 | h | //////////////////////////////////////////////////////////////////////////////
// Copyright © 2007, Björn Olievier
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of the author nor the names of other contributors may
// be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////
#pragma once
#include <core/audio/IAudioSource.h>
using namespace musik::core::audio;
class APESourceSupplier : public IAudioSourceSupplier
{
public: APESourceSupplier();
public: ~APESourceSupplier();
public: IAudioSource* CreateAudioSource();
public: void Destroy();
public: bool CanHandle(const utfchar* source) const;
};
| [
"onnerby@6a861d04-ae47-0410-a6da-2d49beace72e"
]
| [
[
[
1,
48
]
]
]
|
2e700d8da7ab2f3e09c536782f1595cd9a5d6e49 | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/zombie/nscene/src/nscene/ntransformswitchanimator_main.cc | e599cc760fd3f801bea7f88e8b5b2ae4f8f2f094 | []
| no_license | ugozapad/TheZombieEngine | 832492930df28c28cd349673f79f3609b1fe7190 | 8e8c3e6225c2ed93e07287356def9fbdeacf3d6a | refs/heads/master | 2020-04-30T11:35:36.258363 | 2011-02-24T14:18:43 | 2011-02-24T14:18:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,489 | cc | #include "precompiled/pchnscene.h"
//------------------------------------------------------------------------------
// ntransformswitchanimator_main.cc
// (C) 2006 Conjurer Services, S.A.
//------------------------------------------------------------------------------
#include "nscene/ntransformswitchanimator.h"
#include "nscene/ntransformnode.h"
#include "zombieentity/ncdictionary.h"
nNebulaScriptClass(nTransformSwitchAnimator, "nanimator");
//------------------------------------------------------------------------------
/**
*/
nTransformSwitchAnimator::nTransformSwitchAnimator()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
nTransformSwitchAnimator::~nTransformSwitchAnimator()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
nAnimator::Type
nTransformSwitchAnimator::GetAnimatorType() const
{
return Transform;
}
//------------------------------------------------------------------------------
/**
*/
void
nTransformSwitchAnimator::ResetKeys()
{
this->positionArray.Reset();
this->rotationArray.Reset();
}
//------------------------------------------------------------------------------
/**
*/
void
nTransformSwitchAnimator::AddPosition(const vector3& pos)
{
this->positionArray.Append(pos);
}
//------------------------------------------------------------------------------
/**
*/
void
nTransformSwitchAnimator::AddEuler(const vector3& rot)
{
this->rotationArray.Append(rot);
}
//------------------------------------------------------------------------------
/**
*/
void
nTransformSwitchAnimator::Animate(nSceneNode* sceneNode, nEntityObject* entityObject)
{
n_assert(sceneNode);
n_assert(entityObject);
// FIXME: dirty cast, make sure that it is a nTransformNode
nTransformNode* targetNode = (nTransformNode*) sceneNode;
ncDictionary* varContext = entityObject->GetComponent<ncDictionary>();
nVariable* var = varContext->GetVariable(this->channelVarHandle);
if (var)
{
int index = var->GetInt();
if (!this->positionArray.Empty() && index < this->positionArray.Size())
{
targetNode->SetPosition(this->positionArray.At(index));
}
if (!this->rotationArray.Empty())
{
targetNode->SetEuler(this->rotationArray.At(index));
}
}
}
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
]
| [
[
[
1,
92
]
]
]
|
29be606fa8603640157f3e9837256ed70551ed88 | 1d6dcdeddc2066f451338361dc25196157b8b45c | /tp1/Visualizacion/Grilla.cpp | 62844ca986c3c8a4d09ab6bca7822431373f1a9b | []
| no_license | nicohen/ssgg2009 | 1c105811837f82aaa3dd1f55987acaf8f62f16bb | 467e4f475ef04d59740fa162ac10ee51f1f95f83 | refs/heads/master | 2020-12-24T08:16:36.476182 | 2009-08-15T00:43:57 | 2009-08-15T00:43:57 | 34,405,608 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,291 | cpp | #include "Grilla.h"
#include "../Geometria/Segmento.h"
Grilla::Grilla(int filas, int columnas, float dx, float dy, Coordenadas* posicion)
{
this->origen = posicion;
this->filas = filas;
this->columnas = columnas;
this->unidadX = floor(dx);
this->unidadY = floor(dy);
int corrX = unidadX/2;
int corrY = unidadY/2;
bool cuadrada;
Coordenadas* coordenadas;
Coordenadas* centro;
Rectangulo* rectangulo;
(dx == dy) ? cuadrada = true : cuadrada = false;
for (int i = 0; i < filas ; i++){
for (int j = 0; j < columnas ; j++){
coordenadas = new Coordenadas(i,j);
centro = new Coordenadas((posicion->getX() + i*unidadX + corrX), (posicion->getY() - j*unidadY - corrY));
cuadrada ? rectangulo = new Cuadrado(dx,centro) : rectangulo = new Rectangulo(dx,dy,centro);
this->mapa.insert(pair<Coordenadas*,Rectangulo*>(coordenadas,rectangulo));
}
}
}
Grilla::~Grilla()
{
delete this->origen;
map<Coordenadas*,Rectangulo*>::iterator it=this->mapa.begin() ;
while(it != this->mapa.end()){
delete (it->first);
delete (it->second);
it++;
}
this->mapa.clear();
}
void Grilla::dibujar(){
this->dibujarEjeX();
this->dibujarEjeY();
map<Coordenadas*,Rectangulo*>::iterator it=this->mapa.begin();
while(it != this->mapa.end()){
((Rectangulo*)it->second)->dibujarPunteado();
it++;
}
//Dibujo las guias de los puntos en el eje X
int init = this->origen->getX() + this->unidadX/2;
Segmento* segmento;
for(int i=0;i<this->columnas;i++) {
segmento = new Segmento(new Coordenadas(init,525),new Coordenadas(init,515));
segmento->dibujar();
delete segmento;
init+=this->unidadX;
}
//Dibujo los numeros de los puntos en el eje X
init = this->origen->getX() + this->unidadX/2 - 5;
Numero* numero;
for(int j=0;j<this->columnas;j++) {
numero = new Numero(new Coordenadas(init,535),j);
numero->dibujar();
delete numero;
init+= this->unidadX;
}
//Dibujo las guias de los puntos en el eje Y
init = this->origen->getY() - this->unidadY/2;
for(int i=0;i<this->filas;i++) {
segmento = new Segmento(new Coordenadas(this->origen->getX() - 5,init),new Coordenadas(this->origen->getX() + 5,init));
segmento->dibujar();
delete segmento;
init-=this->unidadY;
}
//Dibujo los numeros de los puntos en el eje X
init = this->origen->getY() - this->unidadY/2 + 2;
for(int j=0;j<this->columnas;j++) {
numero = new Numero(new Coordenadas(),j);
glPushMatrix();
glTranslatef(this->origen->getX()-25,init,0);
glRotatef(-90,0,0,1);
numero->dibujar();
glPopMatrix();
delete numero;
init-= this->unidadX;
}
}
void Grilla::dibujarEjeY(){
Coordenadas* desde = new Coordenadas(this->origen->getX(),0);
Coordenadas* hasta = new Coordenadas(this->origen->getX(),this->origen->getY());
Segmento* segmento = new Segmento(desde,hasta);
segmento->dibujar();
delete segmento;
}
void Grilla::dibujarEjeX(){
Coordenadas* desde = new Coordenadas(this->origen->getX(),this->origen->getY());
Coordenadas* hasta = new Coordenadas((ANCHO-1),this->origen->getY());
Segmento* segmento = new Segmento(desde,hasta);
segmento->dibujar();
delete segmento;
}
Rectangulo* Grilla::obtenerCelda(int x, int y){
Rectangulo* rectangulo = NULL;
map<Coordenadas*,Rectangulo*>::iterator it=this->mapa.begin();
while ((it != this->mapa.end()) && (!rectangulo)){
Coordenadas* clave = (Coordenadas*)it->first;
if ((x == clave->getX()) && (y == clave->getY()))
rectangulo = (Rectangulo*)it->second;
it++;
}
return rectangulo;
}
Rectangulo* Grilla::obtenerCelda(Coordenadas posicion){
return this->obtenerCelda(posicion.getX(), posicion.getY());
}
Coordenadas Grilla::obtenerPosicion(Rectangulo celda){
Coordenadas posicion(-1,-1);
Rectangulo rectangulo;
map<Coordenadas*,Rectangulo*>::iterator it=this->mapa.begin();
while ((it != this->mapa.end()) && (posicion.getX() ==-1)){
rectangulo = ((Rectangulo)*it->second);
if (rectangulo.getCentro() == celda.getCentro())
posicion = (Coordenadas)*it->first;
it++;
}
return posicion;
}
Coordenadas Grilla::posicionEnGrilla(int x, int y){
Coordenadas posicion(-1,-1);
Rectangulo* rectangulo = NULL;
map<Coordenadas*,Rectangulo*>::iterator it=this->mapa.begin();
while ((it != this->mapa.end()) && (posicion.getX() == -1)){
rectangulo = (Rectangulo*)it->second;
if (rectangulo->contiene(x,y))
posicion = (Coordenadas)*it->first;
it++;
}
return posicion;
}
int Grilla::posicionVirtual (const int x){
return ((x - this->origen->getX())/this->unidadX);
}
Coordenadas* Grilla::getExtremoNE(){
return (new Coordenadas(this->origen->getX() + this->columnas*this->unidadX,
this->origen->getY() - this->filas*this->unidadY));
}
Coordenadas* Grilla::getExtremoSE(){
return (new Coordenadas(this->origen->getX() + this->columnas*this->unidadX,
this->origen->getY()));
}
float Grilla::distanciaOrigen(Coordenadas punto){
return this->origen->distancia(punto);
}
void Grilla::regenerar(bool dobleColor){
int x,y;
map<Coordenadas*,Rectangulo*>::iterator it=this->mapa.begin();
while (it != this->mapa.end()){
if (dobleColor){
x = ((Coordenadas*)it->first)->getX();
y = ((Coordenadas*)it->first)->getY();
if (x >= y){
if (x == y)
((Rectangulo*)it->second)->setRellenoParcial();
((Rectangulo*)it->second)->setColorRelleno(new Color(0.8,0.8,0.8));
}
else
((Rectangulo*)it->second)->setColorRelleno(new Color(1,1,1));
}
else
((Rectangulo*)it->second)->setColorRelleno(new Color(1,1,1));
it++;
}
}
bool Grilla::enRango(int x, int y){
return ( (x >= this->origen->getX()) && (y <= this->origen->getY())
&& (x < (this->origen->getX() + this->columnas*this->unidadX))
&& (y > (this->origen->getY() - this->filas*this->unidadY)));
}
| [
"rodvar@6da81292-15a5-11de-a4db-e31d5fa7c4f0",
"nicohen@6da81292-15a5-11de-a4db-e31d5fa7c4f0"
]
| [
[
[
1,
1
],
[
4,
45
],
[
47,
48
],
[
50,
51
],
[
53,
54
],
[
56,
57
],
[
60,
61
],
[
63,
64
],
[
66,
67
],
[
70,
195
]
],
[
[
2,
3
],
[
46,
46
],
[
49,
49
],
[
52,
52
],
[
55,
55
],
[
58,
59
],
[
62,
62
],
[
65,
65
],
[
68,
69
]
]
]
|
74ae9589bbe9ed756bb120eca2c22b013da07b11 | 6fd162d2cade2db745e68f11d7e9722a3855f033 | /Source/BetterVSM_2009_08_31_SAVSM_64BitFloatSAT/SoftShadowMap.cpp | dd5390edbf2168a544915c85b9f5d609eb7a4843 | []
| no_license | SenichiFSeiei/oursavsm | 8f418325bc9883bcb245e139dbd0249e72c18d78 | 379e77cab67b3b1423a4c6f480b664f79b03afa9 | refs/heads/master | 2021-01-10T21:00:52.797565 | 2010-04-27T13:18:19 | 2010-04-27T13:18:19 | 41,737,615 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,846 | cpp | #define _USE_MATH_DEFINES
#include <dxut.h>
#include <dxutgui.h>
#include <dxutsettingsdlg.h>
#include <sdkmisc.h>
#include "SoftShadowMap.h"
#include "CommonDef.h"
#include <S3UTmesh.h>
#include <S3UTcamera.h>
#ifdef USE_INT_SAT
#ifdef DUAL_EVSM
#define SAT_FORMAT DXGI_FORMAT_R32G32B32A32_UINT
#else
#define SAT_FORMAT DXGI_FORMAT_R32G32_UINT
#endif
#else
#ifdef DISTRIBUTE_PRECISION
#define SAT_FORMAT DXGI_FORMAT_R32G32B32A32_FLOAT
#else
#define SAT_FORMAT DXGI_FORMAT_R32G32_FLOAT
#endif
#endif
SSMap::SSMap()
{
ZeroMemory(this, sizeof(*this));
m_nDepthRes = DEPTH_RES;
nMips = (int)(log((double)m_nDepthRes) / M_LN2);
m_pShadowMapEffect = NULL;
m_bBuildHSM = true;
m_bBuildMSSM = false;
m_bBuildSAT = true;
m_bBuildVSM = false;
m_pDRenderTechnique = NULL;
m_bShaderChanged = false;
}
void SSMap::set_parameters( bool par_bBuildHSM, bool par_bBuildMSSM, bool par_bBuildSAT, bool par_bBuildVSM )
{
m_bBuildHSM = par_bBuildHSM;
m_bBuildMSSM = par_bBuildMSSM;
m_bBuildSAT = par_bBuildSAT;
m_bBuildVSM = par_bBuildVSM;
}
void SSMap::CreateShader(ID3D10Device* pDev10)
{
HRESULT hr;
WCHAR str[MAX_PATH];
ID3D10Blob *pErrors;
SAFE_RELEASE( m_pShadowMapEffect );
V(DXUTFindDXSDKMediaFileCch(str, MAX_PATH, L"softshadowmap.fx"));
if (D3DX10CreateEffectFromFile(str, NULL, NULL, "fx_4_0", D3D10_SHADER_DEBUG|D3D10_SHADER_SKIP_OPTIMIZATION, 0, pDev10, NULL, NULL, &m_pShadowMapEffect, &pErrors, &hr) != S_OK)
{
MessageBoxA(NULL, (char *)pErrors->GetBufferPointer(), "Compilation error", MB_OK);
exit(0);
}
}
void SSMap::OnD3D10CreateDevice(ID3D10Device* pDev10, const DXGI_SURFACE_DESC *pBackBufferSurfaceDesc, void* pUserContext)
{
CreateShader( pDev10 );
}
void SSMap::OnWindowResize()
{
SAFE_RELEASE(m_pOldRenderState);
}
void SSMap::PrepareBuildingNBuffer( ID3D10Device *par_pDev10 )
{
HRESULT hr;
m_pNBufferRTViews = new ID3D10RenderTargetView *[nMips];
m_pNBufferSRViews = new ID3D10ShaderResourceView *[nMips];
D3D10_TEXTURE2D_DESC NBDesc =
{
m_nDepthRes, //UINT Width;
m_nDepthRes, //UINT Height;
1,//UINT MipLevels;
nMips,//UINT ArraySize;
DXGI_FORMAT_R32G32_FLOAT,//DXGI_FORMAT Format;
{1, 0}, //DXGI_SAMPLE_DESC SampleDesc;
D3D10_USAGE_DEFAULT, //D3D10_USAGE Usage;
D3D10_BIND_SHADER_RESOURCE | D3D10_BIND_RENDER_TARGET,//UINT BindFlags;
0,//UINT CPUAccessFlags;
0,//UINT MiscFlags;
};
V(par_pDev10->CreateTexture2D(&NBDesc, NULL, &m_pNBuffers));
D3D10_SHADER_RESOURCE_VIEW_DESC NBsrViewDesc;
NBsrViewDesc.Format = DXGI_FORMAT_R32G32_FLOAT;
NBsrViewDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2DARRAY;
NBsrViewDesc.Texture2DArray.ArraySize = nMips;
NBsrViewDesc.Texture2DArray.MostDetailedMip = 0;
NBsrViewDesc.Texture2DArray.MipLevels = 1;
NBsrViewDesc.Texture2DArray.FirstArraySlice = 0;
V(par_pDev10->CreateShaderResourceView(m_pNBuffers, &NBsrViewDesc, &m_pNBufferSRView));
D3D10_RENDER_TARGET_VIEW_DESC NBrtViewDesc;
NBrtViewDesc.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2DARRAY;
NBrtViewDesc.Texture2DArray.MipSlice = 0;
NBrtViewDesc.Format = DXGI_FORMAT_R32G32_FLOAT;
NBrtViewDesc.Texture2DArray.ArraySize = 1;
NBsrViewDesc.Texture2DArray.ArraySize = 1;
for (int im = 0; im < nMips; ++im)
{
NBrtViewDesc.Texture2DArray.FirstArraySlice = im;
V(par_pDev10->CreateRenderTargetView(m_pNBuffers, &NBrtViewDesc, &m_pNBufferRTViews[im]));
NBsrViewDesc.Texture2DArray.FirstArraySlice = im;
V(par_pDev10->CreateShaderResourceView(m_pNBuffers, &NBsrViewDesc, &m_pNBufferSRViews[im]));
}
}
void SSMap::PrepareBuildingHSM( ID3D10Device *par_pDev10 )
{
HRESULT hr;
m_pDepthMip2SRViews = new ID3D10ShaderResourceView *[nMips];
m_pDepthMip2RTViews = new ID3D10RenderTargetView *[nMips];
// create render targets
D3D10_TEXTURE2D_DESC rtDesc =
{
m_nDepthRes, //UINT Width;
m_nDepthRes, //UINT Height;
nMips,//UINT MipLevels;
1,//UINT ArraySize;
DXGI_FORMAT_R32G32_FLOAT,//DXGI_FORMAT Format;
{1, 0}, //DXGI_SAMPLE_DESC SampleDesc;
D3D10_USAGE_DEFAULT, //D3D10_USAGE Usage;
D3D10_BIND_SHADER_RESOURCE | D3D10_BIND_RENDER_TARGET,//UINT BindFlags;
0,//UINT CPUAccessFlags;
0,//UINT MiscFlags;
};
V(par_pDev10->CreateTexture2D(&rtDesc, NULL, &m_pDepthMip2));
rtDesc.Width = (rtDesc.Width * 3) / 2;
rtDesc.MipLevels = 1;
V(par_pDev10->CreateTexture2D(&rtDesc, NULL, &m_pBigDepth2));
D3D10_SHADER_RESOURCE_VIEW_DESC srViewDesc;
srViewDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D;
srViewDesc.Texture2D.MostDetailedMip = 0;
srViewDesc.Texture2D.MipLevels = nMips;
srViewDesc.Format = DXGI_FORMAT_R32G32_FLOAT;
V(par_pDev10->CreateShaderResourceView(m_pDepthMip2, &srViewDesc, &m_pDepthMip2SRView));
srViewDesc.Texture2D.MipLevels = 1;
D3D10_RENDER_TARGET_VIEW_DESC rtViewDesc;
rtViewDesc.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2D;
for (int im = 0; im < nMips; ++im)
{
srViewDesc.Texture2D.MostDetailedMip = im;
srViewDesc.Format = DXGI_FORMAT_R32G32_FLOAT;
V(par_pDev10->CreateShaderResourceView(m_pDepthMip2, &srViewDesc, &m_pDepthMip2SRViews[im]));
rtViewDesc.Texture2D.MipSlice = im;
rtViewDesc.Format = DXGI_FORMAT_R32G32_FLOAT;
V(par_pDev10->CreateRenderTargetView(m_pDepthMip2, &rtViewDesc, &m_pDepthMip2RTViews[im]));
}
rtViewDesc.Texture2D.MipSlice = 0;
V(par_pDev10->CreateRenderTargetView(m_pBigDepth2, &rtViewDesc, &m_pBigDepth2RTView));
srViewDesc.Texture2D.MostDetailedMip = 0;
V(par_pDev10->CreateShaderResourceView(m_pBigDepth2, &srViewDesc, &m_pBigDepth2SRView));
}
void SSMap::PrepareBuildingSAT( ID3D10Device *par_pDev10 )
{
HRESULT hr;
D3D10_TEXTURE2D_DESC SATDesc =
{
m_cSatRes, //UINT Width;
m_cSatRes, //UINT Height;
1,//UINT MipLevels;
1,//UINT ArraySize;
SAT_FORMAT,//DXGI_FORMAT Format;
{1, 0}, //DXGI_SAMPLE_DESC SampleDesc;
D3D10_USAGE_DEFAULT, //D3D10_USAGE Usage;
D3D10_BIND_SHADER_RESOURCE | D3D10_BIND_RENDER_TARGET,//UINT BindFlags;
0,//UINT CPUAccessFlags;
0,//UINT MiscFlags;
};
for( int i = 0; i < NUM_SAT_TMP_TEX; ++i )
{
V(par_pDev10->CreateTexture2D(&SATDesc, NULL, &m_pSatTexes[i]));
}
D3D10_SHADER_RESOURCE_VIEW_DESC SATsrViewDesc;
SATsrViewDesc.Format = SAT_FORMAT;
SATsrViewDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D;
SATsrViewDesc.Texture2D.MostDetailedMip = 0;
SATsrViewDesc.Texture2D.MipLevels = 1;
for( int i = 0; i < NUM_SAT_TMP_TEX; ++i )
{
V(par_pDev10->CreateShaderResourceView(m_pSatTexes[i], &SATsrViewDesc, &m_pSatSRViews[i]));
}
D3D10_RENDER_TARGET_VIEW_DESC SATrtViewDesc;
SATrtViewDesc.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2D;
SATrtViewDesc.Texture2D.MipSlice = 0;
SATrtViewDesc.Format = SAT_FORMAT;
for( int i = 0; i < NUM_SAT_TMP_TEX; ++i )
{
V(par_pDev10->CreateRenderTargetView(m_pSatTexes[i], &SATrtViewDesc, &m_pSatRTViews[i]));
}
}
void SSMap::PrepareBuildingVSM( ID3D10Device *par_pDev10 )
{
HRESULT hr;
m_pVSMMip2SRViews = new ID3D10ShaderResourceView *[nMips];
m_pVSMMip2RTViews = new ID3D10RenderTargetView *[nMips];
// create render targets
D3D10_TEXTURE2D_DESC rtDesc =
{
m_nDepthRes, //UINT Width;
m_nDepthRes, //UINT Height;
nMips,//UINT MipLevels;
1,//UINT ArraySize;
DXGI_FORMAT_R32G32B32A32_FLOAT,//DXGI_FORMAT Format;
{1, 0}, //DXGI_SAMPLE_DESC SampleDesc;
D3D10_USAGE_DEFAULT, //D3D10_USAGE Usage;
D3D10_BIND_SHADER_RESOURCE | D3D10_BIND_RENDER_TARGET,//UINT BindFlags;
0,//UINT CPUAccessFlags;
0,//UINT MiscFlags;
};
V(par_pDev10->CreateTexture2D(&rtDesc, NULL, &m_pVSMMip2));
D3D10_SHADER_RESOURCE_VIEW_DESC srViewDesc;
srViewDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D;
srViewDesc.Texture2D.MostDetailedMip = 0;
srViewDesc.Texture2D.MipLevels = nMips;
srViewDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
V(par_pDev10->CreateShaderResourceView(m_pVSMMip2, &srViewDesc, &m_pVSMMip2SRView));
srViewDesc.Texture2D.MipLevels = 1;
D3D10_RENDER_TARGET_VIEW_DESC rtViewDesc;
rtViewDesc.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2D;
for (int im = 0; im < nMips; ++im)
{
srViewDesc.Texture2D.MostDetailedMip = im;
srViewDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
V(par_pDev10->CreateShaderResourceView(m_pVSMMip2, &srViewDesc, &m_pVSMMip2SRViews[im]));
rtViewDesc.Texture2D.MipSlice = im;
rtViewDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
V(par_pDev10->CreateRenderTargetView(m_pVSMMip2, &rtViewDesc, &m_pVSMMip2RTViews[im]));
}
}
void SSMap::BuildNBuffer( ID3D10Device *par_pDev10 )
{
HRESULT hr;
ID3D10EffectTechnique *pDReworkTechnique2 = m_pShadowMapEffect->GetTechniqueByName("ReworkDepth2");
D3D10_VIEWPORT vp;
vp.Height = m_nDepthRes;
vp.Width = m_nDepthRes;
vp.MinDepth = 0;
vp.MaxDepth = 1;
vp.TopLeftX = 0;
vp.TopLeftY = 0;
V(m_pShadowMapEffect->GetVariableByName("DepthTex0")->AsShaderResource()->SetResource(m_pDepthSRView[0]));
par_pDev10->RSSetViewports(1, &vp);
par_pDev10->OMSetRenderTargets(1, &m_pNBufferRTViews[0], NULL);
V(pDReworkTechnique2->GetPassByName("ConvertDepthWithAdj")->Apply(0));
for (int im = 0; ; )
{
par_pDev10->Draw(3, 0);
if (++im == nMips)
{ break; }
V(m_pShadowMapEffect->GetVariableByName("nBufferLevel")->AsScalar()->SetInt(im-1)) ;
V(m_pShadowMapEffect->GetVariableByName("DepthNBuffer")->AsShaderResource()->SetResource(m_pNBufferSRViews[im - 1]));
par_pDev10->OMSetRenderTargets(1, &m_pNBufferRTViews[im], NULL);
V(pDReworkTechnique2->GetPassByName("CreateNBuffer")->Apply(0));
}
}
void SSMap::BuildSAT( ID3D10Device *par_pDev10 )
{
HRESULT hr;
D3D10_VIEWPORT vp;
vp.Height = m_cSatRes;
vp.Width = m_cSatRes;
vp.MinDepth = 0;
vp.MaxDepth = 1;
vp.TopLeftX = 0;
vp.TopLeftY = 0;
par_pDev10->RSSetViewports(1, &vp);
ID3D10EffectTechnique *pSATTechnique2 = m_pShadowMapEffect->GetTechniqueByName("RenderSAT");
int src_tex_idx = 0;
int dst_tex_idx = 1;
V(m_pShadowMapEffect->GetVariableByName("DepthTex0")->AsShaderResource()->SetResource(m_pDepthSRView[0]));
par_pDev10->OMSetRenderTargets(1, &m_pSatRTViews[src_tex_idx], NULL);
float ClearColor[4] = { 1, 1, 0, 0 };
#ifndef DEBUG_SAT
V(pSATTechnique2->GetPassByName("ConvertDepth")->Apply(0));
par_pDev10->Draw(3, 0);
#endif
//first src is not SatSRViews, but the original depth map
V(m_pShadowMapEffect->GetVariableByName("nSampleNum")->AsScalar()->SetInt(m_cSampleBatch));
int log2_sample_batch = static_cast<int>(log(static_cast<double>(m_cSampleBatch))/log(static_cast<double>(2)));
int num_passes = 0;
unsigned int current_res = m_cSatRes;
while( current_res > 0 )
{
++num_passes;
current_res >>= log2_sample_batch;
}
int sample_interval = 1;
int left_bound = 0;
for (int pass_idx = 0; pass_idx < num_passes; ++pass_idx)//not iterating passes in a single technique, but those passes doing recursively double
{
V(m_pShadowMapEffect->GetVariableByName("SatSrcTex")->AsShaderResource()->SetResource(m_pSatSRViews[src_tex_idx]));
par_pDev10->OMSetRenderTargets(1, &m_pSatRTViews[dst_tex_idx], NULL);
V(m_pShadowMapEffect->GetVariableByName("nSatSampleInterval")->AsScalar()->SetFloat( sample_interval )) ;
V(pSATTechnique2->GetPassByName("HorizontalPass")->Apply(0));
D3D10_RECT Region = {left_bound, 0, m_cSatRes, m_cSatRes};
par_pDev10->RSSetScissorRects(1, &Region);
par_pDev10->Draw(3, 0);
++src_tex_idx;
++dst_tex_idx;
src_tex_idx %= NUM_SAT_TMP_TEX;
dst_tex_idx %= NUM_SAT_TMP_TEX;
sample_interval *= m_cSampleBatch;
left_bound = sample_interval / m_cSampleBatch;
}
sample_interval = 1;
int bottom_bound = 0;
for (int pass_idx = 0; pass_idx < num_passes; ++pass_idx)//not iterating passes in a single technique, but those passes doing recursively double
{
V(m_pShadowMapEffect->GetVariableByName("SatSrcTex")->AsShaderResource()->SetResource(m_pSatSRViews[src_tex_idx]));
par_pDev10->OMSetRenderTargets(1, &m_pSatRTViews[dst_tex_idx], NULL);
V(m_pShadowMapEffect->GetVariableByName("nSatSampleInterval")->AsScalar()->SetFloat( sample_interval )) ;
V(pSATTechnique2->GetPassByName("VerticalPass")->Apply(0));
D3D10_RECT Region = {0, bottom_bound, m_cSatRes, m_cSatRes};
par_pDev10->RSSetScissorRects(1, &Region);
par_pDev10->Draw(3, 0);
++src_tex_idx;
++dst_tex_idx;
src_tex_idx %= NUM_SAT_TMP_TEX;
dst_tex_idx %= NUM_SAT_TMP_TEX;
sample_interval *= m_cSampleBatch;
bottom_bound = sample_interval / m_cSampleBatch;
}
}
void SSMap::BuildHSM( ID3D10Device *par_pDev10 )
{
HRESULT hr;
ID3D10EffectTechnique *pDReworkTechnique2 = m_pShadowMapEffect->GetTechniqueByName("ReworkDepth2");
D3D10_VIEWPORT vp;
vp.Height = m_nDepthRes;
vp.Width = m_nDepthRes;
vp.MinDepth = 0;
vp.MaxDepth = 1;
vp.TopLeftX = 0;
vp.TopLeftY = 0;
D3D10_RECT Region = {0, 0, m_nDepthRes, m_nDepthRes};
par_pDev10->RSSetScissorRects(1, &Region);
// create mipmap pyramid
V(m_pShadowMapEffect->GetVariableByName("DepthTex0")->AsShaderResource()->SetResource(m_pDepthSRView[0]));
par_pDev10->OMSetRenderTargets(1, &m_pDepthMip2RTViews[0], NULL);
ID3D10Buffer *pNullVBuf[] = { NULL };
unsigned pStrides[] = { 0 };
unsigned pOffsets[] = { 0 };
par_pDev10->IASetVertexBuffers(0, 1, pNullVBuf, pStrides, pOffsets);
par_pDev10->IASetInputLayout(NULL);
V(pDReworkTechnique2->GetPassByName("ConvertDepth")->Apply(0));
for (int im = 0; ; )
{
par_pDev10->Draw(3, 0);
if (++im == nMips)
{ break; }
vp.Width = (vp.Height /= 2);
par_pDev10->RSSetViewports(1, &vp);
V(m_pShadowMapEffect->GetVariableByName("DepthMip2")->AsShaderResource()->SetResource(m_pDepthMip2SRViews[im - 1]));
par_pDev10->OMSetRenderTargets(1, &m_pDepthMip2RTViews[im], NULL);
V(pDReworkTechnique2->GetPassByName("CreateMip")->Apply(0));
}
//Not sure if this will affect codes below
//Magic, without this, shadow map could not be drawn correctly
ID3D10RenderTargetView *pNullRTView = NULL;
par_pDev10->OMSetRenderTargets(1, &pNullRTView, NULL);
/*
V(m_pShadowMapEffect->GetVariableByName("DepthMip2")->AsShaderResource()->SetResource(m_pDepthMip2SRView));
V(pDReworkTechnique2->GetPassByName("ConvertToBig")->Apply(0));
vp.Height = m_nDepthRes;
vp.Width = (m_nDepthRes * 3) / 2;
vp.MinDepth = 0;
vp.MaxDepth = 1;
vp.TopLeftX = 0;
vp.TopLeftY = 0;
par_pDev10->RSSetViewports(1, &vp);
par_pDev10->OMSetRenderTargets(1, &m_pBigDepth2RTView, NULL);
float ClearColor[4] = { 1, 1, 1, 1 };
par_pDev10->ClearRenderTargetView(m_pBigDepth2RTView,ClearColor);
par_pDev10->Draw(3, 0);
*/
}
void SSMap::BuildVSM( ID3D10Device *par_pDev10 )
{
HRESULT hr;
ID3D10EffectTechnique *pDReworkTechnique2 = m_pShadowMapEffect->GetTechniqueByName("ReworkVSM2");
D3D10_VIEWPORT vp;
vp.Height = m_nDepthRes;
vp.Width = m_nDepthRes;
vp.MinDepth = 0;
vp.MaxDepth = 1;
vp.TopLeftX = 0;
vp.TopLeftY = 0;
D3D10_RECT Region = {0, 0, m_nDepthRes, m_nDepthRes};
par_pDev10->RSSetScissorRects(1, &Region);
// create mipmap pyramid
V(m_pShadowMapEffect->GetVariableByName("DepthTex0")->AsShaderResource()->SetResource(m_pDepthSRView[0]));
par_pDev10->OMSetRenderTargets(1, &m_pVSMMip2RTViews[0], NULL);
ID3D10Buffer *pNullVBuf[] = { NULL };
unsigned pStrides[] = { 0 };
unsigned pOffsets[] = { 0 };
par_pDev10->IASetVertexBuffers(0, 1, pNullVBuf, pStrides, pOffsets);
par_pDev10->IASetInputLayout(NULL);
V(pDReworkTechnique2->GetPassByName("ConvertDepth")->Apply(0));
for (int im = 0; ; )
{
par_pDev10->Draw(3, 0);
if (++im == nMips)
{ break; }
vp.Width = (vp.Height /= 2);
par_pDev10->RSSetViewports(1, &vp);
V(m_pShadowMapEffect->GetVariableByName("VSMMip2")->AsShaderResource()->SetResource(m_pVSMMip2SRViews[im - 1]));
par_pDev10->OMSetRenderTargets(1, &m_pVSMMip2RTViews[im], NULL);
V(pDReworkTechnique2->GetPassByName("CreateMip")->Apply(0));
}
//Not sure if this will affect codes below
//Magic, without this, shadow map could not be drawn correctly
ID3D10RenderTargetView *pNullRTView = NULL;
par_pDev10->OMSetRenderTargets(1, &pNullRTView, NULL);
}
void SSMap::Render(ID3D10Device *pDev10, S3UTMesh *pMesh, S3UTCamera &g_LCameraRef,float fTime,float fElapsedTime,bool dump_sm)
{
if( m_bShaderChanged )
{
CreateShader(pDev10);
m_bShaderChanged = false;
}
HRESULT hr;
mLightProj = *g_LCameraRef.GetProjMatrix();
D3DXMATRIX mTranslate,mLightView;
D3DXMatrixInverse(&mTranslate, NULL, g_LCameraRef.GetWorldMatrix());
D3DXMatrixMultiply(&mLightView, &mTranslate, g_LCameraRef.GetViewMatrix());
D3DXMatrixMultiply(&mLightViewProj, &mLightView, &mLightProj);
V(m_pShadowMapEffect->GetVariableByName("mViewProj")->AsMatrix()->SetMatrix((float *)&mLightViewProj));
V(m_pShadowMapEffect->GetVariableByName("mLightView")->AsMatrix()->SetMatrix((float *)&mLightView));
#ifdef USE_LINEAR_Z
D3DXMATRIX mClip2Tex, mTmp;
mClip2Tex = D3DXMATRIX( 0.5, 0, 0, 0,
0, -0.5, 0, 0,
0, 0, 1, 0,
0.5, 0.5, 0, 1 );
D3DXMATRIX mLightViewProjClip2Tex, mLightProjClip2TexInv;
D3DXMatrixMultiply(&mTmp, &mLightProj, &mClip2Tex);
D3DXMatrixInverse(&mLightProjClip2TexInv, NULL, &mTmp);
V(m_pShadowMapEffect->GetVariableByName("mLightProjClip2TexInv")->AsMatrix()->SetMatrix((float *)&mLightProjClip2TexInv));
V(m_pShadowMapEffect->GetVariableByName("Zf")->AsScalar()->SetFloat(g_LCameraRef.GetFarClip()));
V(m_pShadowMapEffect->GetVariableByName("Zn")->AsScalar()->SetFloat(g_LCameraRef.GetNearClip()));
#endif
m_pDRenderTechnique = m_pShadowMapEffect->GetTechniqueByName("RenderDepth");
if (m_pDepthTex[0] == NULL)
{
// create render targets
D3D10_TEXTURE2D_DESC rtDesc =
{
m_nDepthRes, //UINT Width;
m_nDepthRes, //UINT Height;
1,//UINT MipLevels;
1,//UINT ArraySize;
DXGI_FORMAT_R32_TYPELESS,//DXGI_FORMAT Format;
{1, 0}, //DXGI_SAMPLE_DESC SampleDesc;
D3D10_USAGE_DEFAULT, //D3D10_USAGE Usage;
D3D10_BIND_SHADER_RESOURCE | D3D10_BIND_DEPTH_STENCIL,//UINT BindFlags;
0,//UINT CPUAccessFlags;
0,//UINT MiscFlags;
};
V(pDev10->CreateTexture2D(&rtDesc, NULL, &m_pDepthTex[0]));
D3D10_DEPTH_STENCIL_VIEW_DESC dsViewDesc;
D3D10_SHADER_RESOURCE_VIEW_DESC srViewDesc;
dsViewDesc.Format = DXGI_FORMAT_D32_FLOAT;
srViewDesc.Format = DXGI_FORMAT_R32_FLOAT;
dsViewDesc.ViewDimension = D3D10_DSV_DIMENSION_TEXTURE2D;
srViewDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D;
dsViewDesc.Texture2D.MipSlice = 0;
srViewDesc.Texture2D.MostDetailedMip = 0;
srViewDesc.Texture2D.MipLevels = 1;
V(pDev10->CreateDepthStencilView(m_pDepthTex[0], &dsViewDesc, &m_pDepthDSView[0]));
V(pDev10->CreateShaderResourceView(m_pDepthTex[0], &srViewDesc, &m_pDepthSRView[0]));
static const D3D10_INPUT_ELEMENT_DESC depth_layout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
};
D3D10_PASS_DESC PassDesc;
V(m_pDRenderTechnique->GetPassByIndex(0)->GetDesc(&PassDesc));
V(pDev10->CreateInputLayout(depth_layout, 1, PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &m_pDepthLayout));
SAFE_RELEASE(m_pRasterState);
D3D10_RASTERIZER_DESC RasterState;
RasterState.FillMode = D3D10_FILL_SOLID;
RasterState.CullMode = SHADOWMAP_CULL;
RasterState.FrontCounterClockwise = true;
RasterState.DepthBias = true;
//RasterState.DepthBias = false;
RasterState.DepthBiasClamp = 1000.0;
//RasterState.DepthBiasClamp = 0;
RasterState.SlopeScaledDepthBias = 5;
RasterState.DepthClipEnable = true;
RasterState.ScissorEnable = true;
RasterState.MultisampleEnable = false;
RasterState.AntialiasedLineEnable = false;
V(pDev10->CreateRasterizerState(&RasterState, &m_pRasterState));
SAFE_RELEASE(m_pDSState);
D3D10_DEPTH_STENCIL_DESC DSState;
ZeroMemory(&DSState, sizeof(DSState));
DSState.DepthEnable = true;
DSState.DepthWriteMask = D3D10_DEPTH_WRITE_MASK_ALL;
DSState.DepthFunc = D3D10_COMPARISON_LESS_EQUAL;
V(pDev10->CreateDepthStencilState(&DSState, &m_pDSState));
if( m_bBuildHSM )
{
PrepareBuildingHSM( pDev10 );
}
if( m_bBuildVSM )
{
PrepareBuildingVSM( pDev10 );
}
if( m_bBuildSAT )
{
PrepareBuildingSAT( pDev10 );
}
if( m_bBuildMSSM )
{
PrepareBuildingNBuffer( pDev10 );
}
}
if (m_pOldRenderState == NULL)
{
D3D10_STATE_BLOCK_MASK SBMask;
ZeroMemory(&SBMask, sizeof(SBMask));
SBMask.RSViewports = true;
SBMask.OMRenderTargets = true;
SBMask.RSRasterizerState = true;
V(D3D10CreateStateBlock(pDev10, &SBMask, &m_pOldRenderState));
}
V(m_pOldRenderState->Capture());
D3D10_VIEWPORT vp;
vp.Height = m_nDepthRes;
vp.Width = m_nDepthRes;
vp.MinDepth = 0;
vp.MaxDepth = 1;
vp.TopLeftX = 0;
vp.TopLeftY = 0;
pDev10->RSSetViewports(1, &vp);
// render depth
D3D10_RECT Region = {0, 0, m_nDepthRes, m_nDepthRes};
pDev10->RSSetScissorRects(1, &Region);
pDev10->RSSetState(m_pRasterState);
pDev10->OMSetDepthStencilState(m_pDSState, 0);
ID3D10RenderTargetView *pNullRTView = NULL;
pDev10->OMSetRenderTargets(1, &pNullRTView, m_pDepthDSView[0]);
pDev10->IASetInputLayout(m_pDepthLayout);
pDev10->ClearDepthStencilView(m_pDepthDSView[0], D3D10_CLEAR_DEPTH, 1.0, 0);
pMesh->Render( MAX_BONE_MATRICES,
(FLOAT)SCALE,
m_pShadowMapEffect,
m_pShadowMapEffect->GetTechniqueByName(SUIT_TECH_NAME),
m_pShadowMapEffect->GetTechniqueByName(BODY_TECH_NAME),
m_pDRenderTechnique,
m_pDRenderTechnique,
&mLightViewProj,
pDev10,
fTime,fElapsedTime,NULL,false );
if( m_bBuildHSM )
{
BuildHSM( pDev10 );
}
if( m_bBuildVSM )
{
BuildVSM( pDev10 );
}
if( m_bBuildMSSM )
{
BuildNBuffer( pDev10 );
}
if( m_bBuildSAT )
{
BuildSAT( pDev10 );
}
pDev10->OMSetRenderTargets(1, &pNullRTView, NULL);
static bool bSaved = true;
static int iidx = 0;
//if (0)
#ifdef B_DO_DUMP
{
bSaved = true;
ID3D10Texture2D *pTexture = NULL;
D3D10_TEXTURE2D_DESC textureDesc;
m_pSatTexes[0]->GetDesc(&textureDesc);
textureDesc.Format = SAT_FORMAT;
textureDesc.CPUAccessFlags = D3D10_CPU_ACCESS_READ;
textureDesc.Usage = D3D10_USAGE_STAGING;
textureDesc.BindFlags = 0;
V(pDev10->CreateTexture2D(&textureDesc, NULL, &pTexture));
pDev10->CopyResource(pTexture, m_pSatTexes[6%SSMap::NUM_SAT_TMP_TEX]);
//if( 0 == iidx )
D3DX10SaveTextureToFile(pTexture, D3DX10_IFF_DDS, L"e:\\SatVSM.dds");
/*else if( 1 == iidx )
D3DX10SaveTextureToFile(pTexture, D3DX10_IFF_DDS, L"c:\\fff1.dds");
else if( 2 == iidx )
D3DX10SaveTextureToFile(pTexture, D3DX10_IFF_DDS, L"c:\\fff2.dds");
else if( 3 == iidx )
D3DX10SaveTextureToFile(pTexture, D3DX10_IFF_DDS, L"c:\\fff3.dds");
iidx ++;
iidx = iidx%NUM_LIGHT;*/
}
#endif
//if(0)
#ifdef B_DO_DUMP
{
ID3D10Texture2D *pTexture = NULL;
D3D10_TEXTURE2D_DESC textureDesc;
m_pDepthMip2->GetDesc(&textureDesc);
textureDesc.CPUAccessFlags = D3D10_CPU_ACCESS_READ;
textureDesc.Usage = D3D10_USAGE_STAGING;
textureDesc.BindFlags = 0;
V(pDev10->CreateTexture2D(&textureDesc, NULL, &pTexture));
pDev10->CopyResource(pTexture,m_pDepthMip2);
D3DX10SaveTextureToFile(pTexture, D3DX10_IFF_DDS, L"e:\\DepthMip2.dds");
}
#endif
V(m_pOldRenderState->Apply());
}
void SSMap::OnDestroy()
{
SAFE_RELEASE(m_pDepthTex[0]);
SAFE_RELEASE(m_pDepthSRView[0]);
SAFE_RELEASE(m_pDepthDSView[0]);
for( int i = 0; i < NUM_SAT_TMP_TEX; ++i )
{
SAFE_RELEASE(m_pSatTexes[i]);
SAFE_RELEASE(m_pSatSRViews[i]);
SAFE_RELEASE(m_pSatRTViews[i]);
}
SAFE_RELEASE(m_pDepthMip2);
SAFE_RELEASE(m_pDepthMip2SRView);
SAFE_RELEASE(m_pVSMMip2);
SAFE_RELEASE(m_pVSMMip2SRView);
SAFE_RELEASE(m_pNBuffers);
SAFE_RELEASE(m_pNBufferSRView);
if (m_pDepthMip2RTViews)
{
for (int im = 0; im < nMips; ++im)
{
SAFE_RELEASE(m_pDepthMip2RTViews[im]);
SAFE_RELEASE(m_pDepthMip2SRViews[im]);
}
}
if (m_pVSMMip2RTViews)
{
for (int im = 0; im < nMips; ++im)
{
SAFE_RELEASE(m_pVSMMip2RTViews[im]);
SAFE_RELEASE(m_pVSMMip2SRViews[im]);
}
}
if (m_pNBufferRTViews)
{
for (int im = 0; im < nMips; ++im)
{
SAFE_RELEASE(m_pNBufferRTViews[im]);
SAFE_RELEASE(m_pNBufferSRViews[im]);
}
}
SAFE_DELETE_ARRAY(m_pDepthMip2RTViews);
SAFE_DELETE_ARRAY(m_pDepthMip2SRViews);
SAFE_DELETE_ARRAY(m_pVSMMip2RTViews);
SAFE_DELETE_ARRAY(m_pVSMMip2SRViews);
SAFE_DELETE_ARRAY(m_pNBufferRTViews);
SAFE_DELETE_ARRAY(m_pNBufferSRViews);
SAFE_RELEASE(m_pOldRenderState); ///< we save rendering state here
SAFE_RELEASE(m_pDepthLayout); ///< layout with only POSITION semantic in it
SAFE_RELEASE(m_pRasterState); ///< render state we use to render shadow map
SAFE_RELEASE(m_pDSState); ///< render state we use to render shadow map
SAFE_RELEASE(m_pBigDepth2);
SAFE_RELEASE(m_pBigDepth2SRView);
SAFE_RELEASE(m_pBigDepth2RTView);
SAFE_RELEASE(m_pShadowMapEffect);
ZeroMemory(this, sizeof(*this));
}
| [
"[email protected]",
"flycooler@9eb8245e-93ee-11de-8d68-838d6ba51ce1"
]
| [
[
[
1,
728
],
[
731,
731
],
[
734,
734
],
[
737,
749
]
],
[
[
729,
730
],
[
732,
733
],
[
735,
736
]
]
]
|
f84753b2ffb137c139f7331056e5473a6aebed5e | 8b68ff41fd39c9cf20d27922bb9f8b9d2a1c68e9 | /TWL/include/util/numutil.h | 97e57ce524a9a56e2a2745b3c54056cff5119dae | []
| no_license | dandycheung/dandy-twl | 2ec6d500273b3cb7dd6ab9e5a3412740d73219ae | 991220b02f31e4ec82760ece9cd974103c7f9213 | refs/heads/master | 2020-12-24T15:06:06.260650 | 2009-05-20T14:46:07 | 2009-05-20T14:46:07 | 32,625,192 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,105 | h | #ifndef __NUMUTIL_H__
#define __NUMUTIL_H__
class NumUtil
{
public:
static
LPCTSTR StringChar(TCHAR ch, LPCTSTR psz, INT nLength, BOOL bCaseSensitive)
{
if(!psz)
return NULL;
if(!bCaseSensitive)
ch = (TCHAR)CharUpper((LPTSTR)ch);
LPCTSTR p = psz;
TCHAR ch2;
while(*p)
{
ch2 = *p;
if(!bCaseSensitive)
ch2 = (TCHAR)CharUpper((LPTSTR)ch2);
if(ch == ch2)
return p;
p++;
if(p - psz > nLength)
break;
}
return NULL;
}
static
BOOL StringToDWORD(LPCTSTR pszIn, DWORD& rdwOut)
{
if(!pszIn || !*pszIn)
return FALSE;
LPCTSTR pszNumbers = _T("0123456789ABCDEF");
UINT nBase = 10;
if(*pszIn == _T('0'))
{
if((pszIn[1] == _T('x')) || (pszIn[1] == _T('X')))
{
nBase = 16;
pszIn += 2;
}
else
{
nBase = 8;
pszIn++;
}
}
LPCTSTR pszDigit = pszIn;
pszDigit += lstrlen(pszDigit);
rdwOut = 0;
LPCTSTR pszNumber;
DWORD dwAdd;
DWORD nMul = 1;
while(pszDigit > pszIn)
{
pszDigit--;
pszNumber = StringChar(*pszDigit, pszNumbers, nBase, FALSE);
if(!pszNumber)
return FALSE; // wrong char in input string
dwAdd = (pszNumber - pszNumbers) * nMul;
if(rdwOut + dwAdd < rdwOut)
return FALSE; // overflow
rdwOut += dwAdd;
if(pszDigit > pszIn)
{
if(nMul * nBase < nMul)
return FALSE; // overflow
nMul *= nBase;
}
}
return TRUE;
}
};
class CIntergerParser
{
public:
static LONG StringToLong(LPCTSTR pszString)
{
// skip whitespace
while(*pszString == TEXT(' ') || *pszString == TEXT('\t'))
pszString++;
TCHAR chChar = *pszString++; // current char
TCHAR chSign = chChar; // save sign indication, if '-',
// then negative, otherwise positive
// skip sign
if(chChar == TEXT('-') || chChar == TEXT('+'))
chChar = *pszString++;
LONG lTotal = 0; // current total
while(chChar >= TEXT('0') && chChar <= TEXT('9'))
{
lTotal = 10 * lTotal + (chChar - TEXT('0')); // accumulate digit
chChar = *pszString++; // get next char
}
return (chSign == TEXT('-')) ? -lTotal : lTotal; // return result, negated if necessary
}
static BOOL GetIntegerByIndex(LPCTSTR pszString, int iIndex, PDWORD pdwValue, LPCTSTR pszDelimiters = TEXT(",;"))
{
if(pszString == NULL || pdwValue == NULL)
return FALSE;
if(iIndex < 0)
return FALSE;
BOOL bRet = FALSE;
LPCTSTR pBegin = pszString;
LPCTSTR pTracker = pszString;
LPCTSTR pEnd = NULL;
int iDelimiter = 0;
for(; ; pTracker++)
{
BOOL bIsDelimiter = FALSE;
for(int i=0; i<lstrlen(pszDelimiters); i++)
{
if(*pTracker == pszDelimiters[i])
{
bIsDelimiter = TRUE;
break;
}
}
if(bIsDelimiter)
{
iDelimiter++;
if(iDelimiter == iIndex)
pBegin = pTracker + 1;
else if(iDelimiter == (iIndex + 1))
pEnd = pTracker;
}
else if(*pTracker == TEXT('\0'))
{
if(iDelimiter == iIndex)
pEnd = pTracker;
else
break;
}
if(pEnd != NULL)
{
bRet = TRUE;
break;
}
}
if(bRet)
{
DWORD dwSize = (PBYTE)pEnd - (PBYTE)pBegin;
if(dwSize == 0)
bRet = FALSE;
else
{
int iCount = dwSize / sizeof(TCHAR) + 1;
LPTSTR pDigit = new TCHAR[iCount];
#ifdef WIN32
lstrcpyn(pDigit, pBegin, iCount);
#else // WIN32
_tcsncpy(pDigit, pBegin, iCount);
#endif // WIN32
*pdwValue = StringToLong(pDigit);
delete pDigit;
}
}
return bRet;
}
public:
CIntergerParser(LPCTSTR pszSource)
: _pszSource(NULL), _iIndex(0)
{
_pszSource = pszSource;
}
BOOL Get(PDWORD pdwValue)
{
return GetIntegerByIndex(_pszSource, _iIndex++, pdwValue);
}
void Reset()
{
_iIndex = 0;
}
CIntergerParser& operator= (LPCTSTR pszSource)
{
Reset();
_pszSource = pszSource;
return *this;
}
protected:
LPCTSTR _pszSource;
int _iIndex;
};
#endif // __NUMUTIL_H__
| [
"dandycheung@9b253700-4547-11de-82b9-170f4fd74ac7"
]
| [
[
[
1,
227
]
]
]
|
3504f336cfcfa9f835c3f1101cfbbcfc40560d35 | 5095bbe94f3af8dc3b14a331519cfee887f4c07e | /Shared/FortranComponentInterface/FortranWrapper.h | e6c34131cd104f444523e8adab1b85f81123a985 | []
| no_license | sativa/apsim_development | efc2b584459b43c89e841abf93830db8d523b07a | a90ffef3b4ed8a7d0cce1c169c65364be6e93797 | refs/heads/master | 2020-12-24T06:53:59.364336 | 2008-09-17T05:31:07 | 2008-09-17T05:31:07 | 64,154,433 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,035 | h | #ifndef FortranWrapperH
#define FortranWrapperH
#include <vector>
#include <string>
#include <general/platform.h>
// Declarations from the FORTRAN side.
struct Instance
{
const char* id;
unsigned int idSize;
const char* g;
unsigned int gSize;
const char* p;
unsigned int pSize;
const char* c;
unsigned int cSize;
unsigned int dummy1;
unsigned int dummy2;
unsigned int dummy3;
unsigned int dummy4;
unsigned int dummy5;
unsigned int dummy6;
unsigned int dummy7;
unsigned int dummy8;
unsigned int dummy9;
unsigned int dummy10;
};
class ScienceAPI;
class CMPComponentInterface;
class EXPORT FortranWrapper
{
//---------------------------------------------------------------------------
// Wrapper class for fortran routines.
// Keeps pointers to fortran entry points: Main(), do_init1() etc..
// and calls them when reqd.
//---------------------------------------------------------------------------
public:
FortranWrapper(ScienceAPI*, CMPComponentInterface* componentInterface, void *);
~FortranWrapper(void);
int subscribe(const std::string &name, void *address);
void subscribedEventHandler(void *address);
static FortranWrapper* currentInstance;
ScienceAPI* scienceAPI;
CMPComponentInterface* componentInterface;
private:
void * dllHandle; // The fortran dll we are wrapping
Instance *instance; // Pointer into fortran dll (same for all instantiations via getProcAddress())
Instance myInstance; // Saved copy of one instance as retrieved from alloc_dealloc()
void swapInstanceIn(void);
void onInit1(void);
};
void ToFortran(const std::string& cValue,
char* forValue, unsigned forValueLength);
void ToFortran(const std::vector<std::string>& cValue,
char* forValue, unsigned forValueLength, int arraySize, int& numValues);
#endif
| [
"hol353@8bb03f63-af10-0410-889a-a89e84ef1bc8",
"devoilp@8bb03f63-af10-0410-889a-a89e84ef1bc8"
]
| [
[
[
1,
44
],
[
47,
48
],
[
50,
51
],
[
54,
57
],
[
59,
67
]
],
[
[
45,
46
],
[
49,
49
],
[
52,
53
],
[
58,
58
]
]
]
|
d2e5b73050401517555ce67309b68c484e02f2a0 | fb534078556a0266e8e5b69e14bf0bda1a56d4bb | /Block.cpp | 8e1ca5cd4a291fd2a764da0a7611f230dc0ce47f | []
| no_license | jimhester/stonesense | 9f6262aa4f4381aa6037e5061f6a3379a643d5f9 | 428244aab8208effedbc3a60eadf152dfbb8b4cf | refs/heads/master | 2020-06-03T22:46:25.866990 | 2010-02-10T22:47:19 | 2010-02-10T22:47:19 | 537,355 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 9,965 | cpp | #include "Block.h"
#include "common.h"
#include "GUI.h"
#include "SpriteMaps.h"
#include "GameBuildings.h"
#include "Creatures.h"
#include "WorldSegment.h"
#include "BlockFactory.h"
#include "dfhack/library/DFTypes.h"
Block::Block(WorldSegment* ownerSegment)
{
//clear out own memory
memset(this, 0, sizeof(Block));
this->ownerSegment = ownerSegment;
building.info.type = BUILDINGTYPE_NA;
building.index = -1;
this->material.type = INVALID_INDEX;
this->material.index = INVALID_INDEX;
}
Block::~Block(void){
if( creature )
delete(creature);
}
void* Block::operator new (size_t size){
return blockFactory.allocateBlock( );
}
void Block::operator delete (void *p){
blockFactory.deleteBlock( (Block*)p );
}
inline BITMAP* imageSheet(t_SpriteWithOffset sprite, BITMAP* defaultBmp)
{
if (sprite.fileIndex == -1)
{
return defaultBmp;
}
else
{
return getImgFile(sprite.fileIndex);
}
}
void Block::Draw(BITMAP* target){
int sheetOffsetX, sheetOffsetY;
t_SpriteWithOffset sprite;
/*if(config.hide_outer_blocks){
if(x == ownerSegment->x || x == ownerSegment->x + ownerSegment->sizex - 1) return;
if(y == ownerSegment->y || y == ownerSegment->y + ownerSegment->sizey - 1) return;
}*/
int32_t drawx = x;
int32_t drawy = y;
int32_t drawz = z; //- ownerSegment->sizez + 1;
correctBlockForSegmetOffset( drawx, drawy, drawz);
correctBlockForRotation( drawx, drawy, drawz);
pointToScreen((int*)&drawx, (int*)&drawy, drawz);
drawx -= TILEWIDTH>>1;
int tileBorderColor = makecol(85,85,85);
//Draw Floor
if(floorType > 0 || wallType > 0 || ramp.type > 0 || stairType > 0){
//If tile has no floor, look for a Filler Floor from it's wall
if (floorType > 0)
{
sprite = GetFloorSpriteMap(floorType, this->material);
}
else if (wallType > 0)
{
sprite = GetFloorSpriteMap(wallType, this->material);
}
else if (ramp.type > 0)
{
sprite = GetFloorSpriteMap(ramp.type, this->material);
}
else if (stairType > 0)
{
sprite = GetFloorSpriteMap(stairType, this->material);
}
if(sprite.sheetIndex != INVALID_INDEX)
{
//if floor is muddy, override regular floor
if( occ.bits.mud && water.index == 0)
{
sprite.sheetIndex = SPRITEFLOOR_WATERFLOOR;
sprite.fileIndex = INVALID_INDEX;
}
//if floor is snowed down, override regular floor
if( occ.bits.snow )
{
sprite.sheetIndex = SPRITEFLOOR_SNOW;
sprite.fileIndex = INVALID_INDEX;
}
if (sprite.sheetIndex == UNCONFIGURED_INDEX)
{
sprite.sheetIndex = SPRITEOBJECT_FLOOR_NA;
sprite.fileIndex = INVALID_INDEX;
}
sheetOffsetX = TILEWIDTH * (sprite.sheetIndex % SHEET_OBJECTSWIDE);
sheetOffsetY = (TILEHEIGHT + FLOORHEIGHT) * (sprite.sheetIndex / SHEET_OBJECTSWIDE);
masked_blit(imageSheet(sprite,IMGObjectSheet), target, sheetOffsetX,sheetOffsetY, drawx,drawy, TILEWIDTH,TILEHEIGHT + FLOORHEIGHT);
}
//Northern frame
if(this->depthBorderNorth)
line(target, drawx + (TILEWIDTH>>1), drawy, drawx+TILEWIDTH-1, drawy+(TILEHEIGHT>>1)-1, tileBorderColor);
//Western frame
if(this->depthBorderWest)
line(target, drawx, drawy+(TILEHEIGHT>>1)-1, drawx+(TILEWIDTH>>1)-1, drawy, tileBorderColor);
}
//Draw Ramp
if(ramp.type > 0){
sprite = GetBlockSpriteMap(ramp.type, material);
if (sprite.sheetIndex == UNCONFIGURED_INDEX)
{
sprite.sheetIndex = 0;
sprite.fileIndex = INVALID_INDEX;
}
if (sprite.sheetIndex != INVALID_INDEX)
{
sheetOffsetX = SPRITEWIDTH * ramp.index;
sheetOffsetY = ((TILEHEIGHT + FLOORHEIGHT + SPRITEHEIGHT) * sprite.sheetIndex)+(TILEHEIGHT + FLOORHEIGHT);
masked_blit(imageSheet(sprite,IMGRampSheet), target, sheetOffsetX,sheetOffsetY, drawx,drawy - (WALLHEIGHT), SPRITEWIDTH, SPRITEHEIGHT);
}}
//vegetation
if(tree.index > 0 || tree.type > 0){
sprite = GetSpriteVegetation( (TileClass) getVegetationType( this->floorType ), tree.index );
DrawSpriteFromSheet( sprite.sheetIndex, target, imageSheet(sprite,IMGObjectSheet), drawx, drawy );
}
//shadow
if (shadow > 0)
{
DrawSpriteFromSheet( BASE_SHADOW_TILE + shadow - 1, target, IMGObjectSheet, drawx, (ramp.type > 0)?(drawy - (WALLHEIGHT/2)):drawy );
}
//Building
bool skipBuilding =
(building.info.type == BUILDINGTYPE_STOCKPILE && !config.show_stockpiles) ||
(building.info.type == BUILDINGTYPE_ZONE && !config.show_zones);
if(building.info.type != BUILDINGTYPE_NA && !skipBuilding){
int spriteNum = SPRITEOBJECT_NA; //getBuildingSprite(this->building, mirroredBuilding);
for(uint32_t i=0; i < building.sprites.size(); i++){
sprite = building.sprites[i];
if (!(sprite.animFrames & (1 << currentAnimationFrame)))
continue;
DrawSpriteFromSheet(sprite.sheetIndex , target, imageSheet(sprite,IMGObjectSheet),
drawx + building.sprites[i].x,
drawy + building.sprites[i].y);
}
}
//Draw Stairs
if(stairType > 0){
//down part
//skipping at the moment?
//int spriteNum = GetFloorSpriteMap(stairType,material);
//DrawSpriteFromSheet( spriteNum, target, IMGObjectSheet, drawx, drawy );
//up part
bool mirrored = false;
if(findWallCloseTo(ownerSegment, this) == eSimpleW)
mirrored = true;
sprite = GetBlockSpriteMap(stairType, material);
if(sprite.sheetIndex != INVALID_INDEX && sprite.sheetIndex != UNCONFIGURED_INDEX)
{
if (mirrored)
sprite.sheetIndex += 1;
DrawSpriteFromSheet( sprite.sheetIndex, target, imageSheet(sprite,IMGObjectSheet), drawx, drawy );
}
}
//Draw Walls
if(wallType > 0){
//draw wall
sprite = GetBlockSpriteMap(wallType, material);
if (sprite.sheetIndex == UNCONFIGURED_INDEX)
{
sprite.sheetIndex = SPRITEOBJECT_WALL_NA;
sprite.fileIndex = INVALID_INDEX;
}
if (sprite.sheetIndex == INVALID_INDEX)
{
//skip
}
else if( config.truncate_walls && this->z == ownerSegment->z + ownerSegment->sizez -2){
int sheetx = sprite.sheetIndex % SHEET_OBJECTSWIDE;
int sheety = sprite.sheetIndex / SHEET_OBJECTSWIDE;
//draw a tiny bit of wall
masked_blit(imageSheet(sprite,IMGObjectSheet), target,
sheetx * SPRITEWIDTH, sheety * SPRITEHEIGHT+WALL_CUTOFF_HEIGHT,
drawx, drawy - (WALLHEIGHT)+WALL_CUTOFF_HEIGHT, SPRITEWIDTH, SPRITEHEIGHT-WALL_CUTOFF_HEIGHT);
//draw cut-off floor thing
masked_blit(IMGObjectSheet, target,
TILEWIDTH * SPRITEFLOOR_CUTOFF, 0,
drawx, drawy-(SPRITEHEIGHT-WALL_CUTOFF_HEIGHT)/2, SPRITEWIDTH, SPRITEWIDTH);
}
else {
DrawSpriteFromSheet(sprite.sheetIndex, target, imageSheet(sprite,IMGObjectSheet), drawx, drawy );
drawy -= (WALLHEIGHT);
//Northern border
if(this->depthBorderNorth)
line(target, drawx + (TILEWIDTH>>1), drawy, drawx+TILEWIDTH-1, drawy+(TILEHEIGHT>>1)-1, tileBorderColor);
//Western border
if(this->depthBorderWest)
line(target, drawx, drawy+(TILEHEIGHT>>1)-1, drawx+(TILEWIDTH>>1)-1, drawy, tileBorderColor);
drawy += (WALLHEIGHT);
}
}
//water
if(water.index > 0){
int spriteNum = 0;
int waterlevel = water.index;
//if(waterlevel == 7) waterlevel--;
if(water.type == 0)
spriteNum = SPRITEOBJECT_WATERLEVEL1 + waterlevel - 1;
if(water.type == 1)
spriteNum = SPRITEOBJECT_WATERLEVEL1_LAVA + waterlevel - 1;
DrawSpriteFromSheet( spriteNum, target, IMGObjectSheet, drawx, drawy );
}
// creature
// ensure there is *some* creature according to the map data
// (no guarantee it is the right one)
if(creature != null && (occ.bits.unit || occ.bits.unit_grounded)){
DrawCreature( target, drawx, drawy, creature);
}
}
void Block::DrawRamptops(BITMAP* target){
if (ramp.type > 0)
{
int sheetOffsetX, sheetOffsetY;
/*if(config.hide_outer_blocks){
if(x == ownerSegment->x || x == ownerSegment->x + ownerSegment->sizex - 1) return;
if(y == ownerSegment->y || y == ownerSegment->y + ownerSegment->sizey - 1) return;
}*/
int32_t drawx = x;
int32_t drawy = y;
int32_t drawz = z+1; //- ownerSegment->sizez + 1;
correctBlockForSegmetOffset( drawx, drawy, drawz);
correctBlockForRotation( drawx, drawy, drawz);
pointToScreen((int*)&drawx, (int*)&drawy, drawz);
drawx -= TILEWIDTH>>1;
t_SpriteWithOffset sprite = GetBlockSpriteMap(ramp.type,material);
if (sprite.sheetIndex == UNCONFIGURED_INDEX)
{
sprite.sheetIndex = 0;
sprite.fileIndex = INVALID_INDEX;
}
if (sprite.sheetIndex != INVALID_INDEX)
{
sheetOffsetX = SPRITEWIDTH * ramp.index;
sheetOffsetY = (TILEHEIGHT + FLOORHEIGHT + SPRITEHEIGHT) * sprite.sheetIndex;
masked_blit( imageSheet(sprite,IMGRampSheet), target, sheetOffsetX,sheetOffsetY, drawx,drawy, SPRITEWIDTH, TILEHEIGHT + FLOORHEIGHT);
}}
}
bool hasWall(Block* b){
if(!b) return false;
return b->wallType > 0;
}
bool hasBuildingOfID(Block* b, int ID){
if(!b) return false;
return b->building.info.type == ID;
}
bool hasBuildingIdentity(Block* b, uint32_t index, int buildingOcc){
if(!b) return false;
if (!(b->building.index == index)) return false;
return b->occ.bits.building == buildingOcc;
}
bool hasBuildingOfIndex(Block* b, uint32_t index){
if(!b) return false;
return b->building.index == index;
}
bool wallShouldNotHaveBorders( int in ){
switch( in ){
case 65: //stone fortification
case 436: //minstone fortification
case 326: //lavastone fortification
case 327: //featstone fortification
case 494: //constructed fortification
return true;
break;
};
return false;
}
| [
"jonask84@4d48de78-bd66-11de-9616-7b1d4728551e",
"Japa.Mala.Illo@4d48de78-bd66-11de-9616-7b1d4728551e",
"4b524953@4d48de78-bd66-11de-9616-7b1d4728551e",
"[email protected]@4d48de78-bd66-11de-9616-7b1d4728551e"
]
| [
[
[
1,
12
],
[
14,
24
],
[
26,
26
],
[
29,
44
],
[
56,
58
],
[
61,
62
],
[
64,
70
],
[
72,
76
],
[
79,
79
],
[
123,
134
],
[
143,
143
],
[
148,
149
],
[
151,
151
],
[
154,
155
],
[
162,
162
],
[
164,
165
],
[
167,
170
],
[
177,
183
],
[
185,
187
],
[
190,
195
],
[
203,
207
],
[
209,
209
],
[
222,
222
],
[
224,
226
],
[
228,
231
],
[
233,
241
],
[
243,
260
],
[
265,
268
],
[
286,
286
],
[
303,
313
],
[
325,
335
]
],
[
[
13,
13
],
[
161,
161
],
[
163,
163
],
[
166,
166
],
[
176,
176
],
[
242,
242
],
[
272,
272
],
[
336,
336
]
],
[
[
25,
25
],
[
27,
28
],
[
45,
55
],
[
59,
60
],
[
63,
63
],
[
71,
71
],
[
77,
78
],
[
80,
101
],
[
103,
104
],
[
110,
110
],
[
118,
118
],
[
122,
122
],
[
135,
142
],
[
144,
147
],
[
150,
150
],
[
152,
153
],
[
156,
160
],
[
171,
175
],
[
184,
184
],
[
188,
189
],
[
196,
202
],
[
208,
208
],
[
210,
221
],
[
223,
223
],
[
227,
227
],
[
232,
232
],
[
261,
264
],
[
269,
271
],
[
273,
285
],
[
287,
302
],
[
314,
324
]
],
[
[
102,
102
],
[
105,
109
],
[
111,
117
],
[
119,
121
]
]
]
|
c33259b236ad87a1d8a074046f522539e5681dd7 | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Common/Com/ScdSlv/ScdElectrics.cpp | fbc12356f33492702bd69e92d62e54713e054440 | []
| no_license | abcweizhuo/Test3 | 0f3379e528a543c0d43aad09489b2444a2e0f86d | 128a4edcf9a93d36a45e5585b70dee75e4502db4 | refs/heads/master | 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,366 | cpp | // ScdElectrics.cpp : Implementation of CScdElectrics
#include "stdafx.h"
#include "ScdElectrics.h"
#include ".\scdelectrics.h"
// CScdElectrics
STDMETHODIMP CScdElectrics::InterfaceSupportsErrorInfo(REFIID riid)
{
static const IID* arr[] =
{
&IID_IScdElectrics
};
for (int i=0; i < sizeof(arr) / sizeof(arr[0]); i++)
{
if (InlineIsEqualGUID(*arr[i],riid))
return S_OK;
}
return S_FALSE;
}
STDMETHODIMP CScdElectrics::SetObjectInfo(DWORD newVal)
{
dllSCD_COMENTRY(eScdNodeCodes)
{
CHECK_SFE_OK;
m_pNode=(FlwNode*)newVal;
m_lTopoCount=gs_pSfeSrvr->FE_GetTopologyCount();
}
SCD_COMEXIT
}
STDMETHODIMP CScdElectrics::get_TermStrips(eScdElecTypes Types, eScdDirections Direction, IScdTermStrips** pVal)
{
dllSCD_COMENTRYGET(eScdNodeCodes, pVal)
{
CHECK_TOPO_OK;
IScdTermStrips * p;
::CoCreateInstance(CLSID_ScdTermStrips, NULL, CLSCTX_ALL, IID_IScdTermStrips, (void**)&p);
p->SetObjectInfo((DWORD)m_pNode, Types, Direction);
*pVal=p; // User must release
return S_OK;
}
SCD_COMEXIT
}
STDMETHODIMP CScdElectrics::get_Wires(eScdElecTypes Types, IScdWires** pVal)
{
dllSCD_COMENTRYGET(eScdNodeCodes, pVal)
{
CHECK_TOPO_OK;
IScdWires * p;
::CoCreateInstance(CLSID_ScdWires, NULL, CLSCTX_ALL, IID_IScdWires, (void**)&p);
p->SetObjectInfo((DWORD)m_pNode, 0, Types);
*pVal=p; // User must release
return S_OK;
}
SCD_COMEXIT
}
STDMETHODIMP CScdElectrics::get_Terminals(eScdElecTypes Types, IScdTerminals** pVal)
{
dllSCD_COMENTRYGET(eScdNodeCodes, pVal)
{
CHECK_TOPO_OK;
IScdTerminals * p;
::CoCreateInstance(CLSID_ScdTerminals, NULL, CLSCTX_ALL, IID_IScdTerminals, (void**)&p);
p->SetObjectInfo((DWORD)m_pNode, 0, Types);
*pVal=p; // User must release
return S_OK;
}
SCD_COMEXIT
}
STDMETHODIMP CScdElectrics::get_Components(eScdElecTypes Types, IScdComponents** pVal)
{
dllSCD_COMENTRYGET(eScdNodeCodes, pVal)
{
CHECK_TOPO_OK;
IScdComponents * p;
::CoCreateInstance(CLSID_ScdComponents, NULL, CLSCTX_ALL, IID_IScdComponents, (void**)&p);
p->SetObjectInfo((DWORD)m_pNode, Types);
*pVal=p; // User must release
return S_OK;
}
SCD_COMEXIT
}
| [
"[email protected]"
]
| [
[
[
1,
94
]
]
]
|
8dbe9655cff7d7f33987ab6fae8ae21f282972b0 | 989aa92c9dab9a90373c8f28aa996c7714a758eb | /HydraIRC/DCCTransfer.cpp | 736d01ad0bdc3f575cf3480a4ea006df22431b22 | []
| no_license | john-peterson/hydrairc | 5139ce002e2537d4bd8fbdcebfec6853168f23bc | f04b7f4abf0de0d2536aef93bd32bea5c4764445 | refs/heads/master | 2021-01-16T20:14:03.793977 | 2010-04-03T02:10:39 | 2010-04-03T02:10:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 37,507 | cpp | /*
HydraIRC
Copyright (C) 2002-2006 Dominic Clifton aka Hydra
HydraIRC limited-use source license
1) You can:
1.1) Use the source to create improvements and bug-fixes to send to the
author to be incorporated in the main program.
1.2) Use it for review/educational purposes.
2) You can NOT:
2.1) Use the source to create derivative works. (That is, you can't release
your own version of HydraIRC with your changes in it)
2.2) Compile your own version and sell it.
2.3) Distribute unmodified, modified source or compiled versions of HydraIRC
without first obtaining permission from the author. (I want one place
for people to come to get HydraIRC from)
2.4) Use any of the code or other part of HydraIRC in anything other than
HydraIRC.
3) All code submitted to the project:
3.1) Must not be covered by any license that conflicts with this license
(e.g. GPL code)
3.2) Will become the property of the author.
*/
/////////////////////////////////////////////////////////////////////////////
/* WARNING: Attention must be paid to the m_pServer variable
* you must check the server instance is still valid by checking that:
* g_ServerList.Find(m_pServer) >= 0
* This is important for reconnects.
*/
#include "StdAfx.h"
#include "HydraIRC.h"
void ExtractFileName (const char *path, char *dest)
{
const char *src;
src = path + strlen(path) - 1;
while (src != path && *(src-1) != '/'
&& *(src-1) != '\\' )
{
src--;
}
while (*src)
{
*dest++ = *src++;
}
*dest = 0;
}
CDCCTransfer::CDCCTransfer(IRCServer *pServer, char *OtherNick, char *FileName, unsigned long Address, int Port, unsigned long Size, int Flags)
{
if (!pServer || !FileName)
return; // TODO: hmm, need an exception..
m_hFile = INVALID_HANDLE_VALUE;
m_Status = DCCT_STATUS_UNKNOWN;
// TODO: when DCC Xfers are stable, the pref, code and error messages for m_Verbose can be removed.
m_Verbose = BOOLPREF(PREF_bDCCVerboseTransfers);
m_StatusDirty = TRUE;
m_pServer = pServer;
m_ReadyToSend = TRUE; // TODO: check for removal of this code.
m_FastSend = BOOLPREF(PREF_bDCCFastSends);
m_NetworkID = pServer->m_pDetails->m_NetworkID;
m_OtherNick = strdup(OtherNick);
m_Address = Address;
m_Port = Port;
m_Size = Size;
m_Type = Flags;
m_LocalFileName = NULL;
m_Retries = 0;
// set the packet size, making sure it's not bigger than either of the buffer sizes.
m_PacketSize = min(INTPREF(PREF_nDCCSendBufferSize),sizeof(m_SocketBuf));
m_PacketSize = min(m_PacketSize,sizeof(m_FileBuf));
m_pTransferSocket = NULL;
m_pServerSocket = NULL;
strncpy(m_IPAddressString,g_DefaultStrings[DEFSTR_Unknown],sizeof(m_IPAddressString));
if (m_Type == DCC_RECEIVE)
{
// Set the remote file name
char *FileNameCopy = strdup(FileName);
if (!FileNameCopy)
return; // TODO: hmm, need an exception..
char *FileNamePtr = FileNameCopy;
// skip leading quote
while (*FileNamePtr == '\"' || *FileNamePtr == '\'')
FileNamePtr++;
// trip trailing quote
int len = strlen(FileNamePtr);
while (len-- >= 0 && (FileNamePtr[len] == '\"' || FileNamePtr[len] == '\''))
FileNamePtr[len] = 0;
m_FileName = strdup(FileNamePtr); // allocate a buffer the same size as FileNameCopy (as it'll only get smaller..)
if (!m_FileName)
return; // TODO: hmm, need an exception..
// strip any leading paths.
ExtractFileName(FileNamePtr,m_FileName);
// replace any invalid characters with an _
ReplaceInvalidFilenameCharacters(m_FileName,'_');
free(FileNameCopy);
char *Path;
if (m_OtherNick && BOOLPREF(PREF_bCreateFoldersForDCCTransfers))
Path = HydraIRC_BuildString(MAX_PATH,"%s\\%s",PATHPREF(PREF_pDCCDownloadsFolder),m_OtherNick);
else
Path = strdup(PATHPREF(PREF_pDCCDownloadsFolder));
if (!Path)
return; // TODO: hmm, need an exception..
ReplaceString(&Path,"<HOMEDIR>",g_HomeDir);
// create the path that the file is to be placed in.
if (CreatePath(Path))
sys_Printf(BIC_INFO,"Download path \"%s\" is OK\n",Path);
else
sys_Printf(BIC_ERROR,"Download path \"%s\" could not be created/accessed\n",Path);
// Build the local file name
m_LocalFileName = HydraIRC_BuildString(MAX_PATH,"%s\\%s",Path,m_FileName);
free(Path);
if (!m_LocalFileName)
return; // TODO: hmm, need an exception..
// TODO: remove bad ascii characters from m_LocalFileName here!
// -> 0.3.135 - thought this is already done..
//+ <gliptic> Check if we should auto accept or set in pending mode
if (BOOLPREF(PREF_bDCCAutoAccept))
{
NotificationEvent_t *pLastNE = g_pNotificationManager->NotificationEvent(NE_DCCFILERECEIVE,m_NetworkID,m_OtherNick);
if (pLastNE && pLastNE->m_Flags & NE_FLAG_LOGINEVENTLOG)
{
// add to event log
g_pEventLogManager->BuildMessage(g_DefaultStrings[DEFSTR_DCC_Receive],m_OtherNick,m_FileName);
g_pEventLogManager->AddItem(ELIT_DCC, ELID_DCC_Receive,m_OtherNick, NULL, m_pServer, NULL);
}
//Auto accept
Go(DCCT_STATUS_CONNECTING);
}
else
{
NotificationEvent_t *pLastNE = g_pNotificationManager->NotificationEvent(NE_DCCFILERECEIVE,m_NetworkID,m_OtherNick);
if (pLastNE && pLastNE->m_Flags & NE_FLAG_LOGINEVENTLOG)
{
// add to event log
g_pEventLogManager->BuildMessage(g_DefaultStrings[DEFSTR_DCC_ReceivePending],m_OtherNick,m_FileName);
g_pEventLogManager->AddItem(ELIT_DCC, ELID_DCC_Receive,m_OtherNick, NULL, m_pServer, NULL);
}
//Set transfer in pending state
Go(DCCT_STATUS_PENDING);
}
// </gliptic>
}
else // m_Type == DCC_SEND
{
// Build the remote file name (reverse of Receiving)
m_FileName = strdup(GetFilePart(FileName));
if (!m_FileName)
return; // TODO: hmm, need an exception..
// Set the local file name (reverse of Receiving)
m_LocalFileName = strdup(FileName);
if (!m_LocalFileName)
return; // TODO: hmm, need an exception..
// Replace bad/dis-allowed characters in the remote filename (like spaces) with dots ('.')
for (int i = strlen(m_FileName)-1; i != 0; i--)
{
if (strchr(" &#$:",m_FileName[i]) > 0)
m_FileName[i] = '.';
}
NotificationEvent_t *pLastNE = g_pNotificationManager->NotificationEvent(NE_DCCFILESEND,m_NetworkID,m_OtherNick);
if (pLastNE && pLastNE->m_Flags & NE_FLAG_LOGINEVENTLOG)
{
// add to event log
g_pEventLogManager->BuildMessage(g_DefaultStrings[DEFSTR_DCC_Send],m_FileName,m_OtherNick);
g_pEventLogManager->AddItem(ELIT_DCC, ELID_DCC_Send,m_OtherNick, NULL, m_pServer, NULL);
}
Go(DCCT_STATUS_CONNECTING);
}
}
CDCCTransfer::~CDCCTransfer( void )
{
if (IsActive())
{
Disconnect(g_DefaultStrings[DEFSTR_Cancelled]);
}
g_pTransfersManager->RemoveTransfer(this);
if (m_OtherNick) free (m_OtherNick);
if (m_FileName) free (m_FileName);
if (m_LocalFileName) free(m_LocalFileName);
if (m_pTransferSocket)
delete m_pTransferSocket;
if (m_pServerSocket)
delete m_pServerSocket;
if (m_hFile != INVALID_HANDLE_VALUE)
{
CloseHandle(m_hFile);
}
}
void CDCCTransfer::Go( int NewStatus )
{
// new status should be either DCCT_STATUS_CONNECTING or DCCT_STATUS_PENDING
m_Status = NewStatus;
if (m_Status == DCCT_STATUS_CONNECTING)
{
strcpy(m_StatusStr,"Connecting...");
}
else
{
strcpy(m_StatusStr,"Pending...");
}
m_hFile = INVALID_HANDLE_VALUE;
m_FilePosition = 0;
m_Sent = 0;
m_CanRetry = FALSE;
m_Received = 0;
m_CheckTicks = 0;
m_ResumeOffset = 0;
m_Position = 0;
m_RemotePosition = 0;
time(&m_Time);
time(&m_ResumeTime);
if (m_Retries == 0)
g_pTransfersManager->AddTransfer(this);
BOOL Duplicate = g_pTransfersManager->IsDuplicate(this);
if (Duplicate)
{
Disconnect("Duplicate transfer, ignored!");
return;
}
if (m_Status == DCCT_STATUS_CONNECTING)
{
// connect!
Connect();
}
}
void CDCCTransfer::Retry( void )
{
if (!m_CanRetry)
return;
m_Retries++;
Go(DCCT_STATUS_CONNECTING);
}
void CDCCTransfer::UpdateStatus( void )
{
m_StatusDirty = TRUE;
g_pTransfersManager->UpdateStatus(this);
}
//+ <gliptic> Accept DCC transfer method
void CDCCTransfer::Accept( void )
{
if(m_Status == DCCT_STATUS_PENDING)
{
strcpy(m_StatusStr, "Connecting...");
m_Status = DCCT_STATUS_CONNECTING;
Connect();
}
}
// </gliptic>
/** Connect (or reconnect)
*
* to reconnect:
* receives: fill in m_Address and m_Port then call this.
* sends: not implemented yet
*/
void CDCCTransfer::Connect( void )
{
DWORD dwPtr;
if (m_Status != DCCT_STATUS_CONNECTING && m_Status != DCCT_STATUS_RESUMING)
Disconnect("Reconnecting");
m_CheckTicks = 0; // reset our timeout counter.
// Receiving ?
if (m_Type == DCC_RECEIVE)
{
if (m_Status != DCCT_STATUS_RESUMING)
{
// check for existing file, and resume if possible
m_hFile = CreateFile(m_LocalFileName,
GENERIC_WRITE,
0, // no sharing
NULL, // no security
OPEN_EXISTING, // existing file only
FILE_ATTRIBUTE_NORMAL, // normal file
NULL); // no template
if (m_hFile != INVALID_HANDLE_VALUE)
{
// file exists, can can be resumed.
// move to the end
dwPtr = SetFilePointer (m_hFile, 0L, NULL, FILE_END);
if (dwPtr == INVALID_SET_FILE_POINTER) // Test for failure
{
Disconnect("Resume Error: File Seek Error");
return;
}
// get the current position.
dwPtr = SetFilePointer(m_hFile, 0, NULL, FILE_CURRENT);
if (dwPtr != INVALID_SET_FILE_POINTER) // Test for failure
{
m_ResumeOffset = dwPtr;
}
else
{
m_ResumeOffset = 0; // reset it.
Disconnect("Resume Error: File Position Error");
return;
}
// resume offset already the same as file size?
if (m_ResumeOffset == m_Size)
{
// Commented out, because if you queue something up, and the xdcc bot
// sends you the file HydraIRC will not accept the x-fer, thus
// making the bot wait for you to accept it.
// Commenting this out just causes the x-fer to complete immediately.
// but without stalling the bot/other user
//Disconnect("Resume Error: File Already Complete!");
//return;
sys_Printf(BIC_WARNING,"Continuing resume, even though file is already complete!\n");
}
if (m_ResumeOffset > m_Size)
{
// TODO: rename local file and download again? make a pref?
Disconnect("Resume Error: A larger file already exists");
return;
}
#ifdef DEBUG
if (m_ResumeOffset == 0)
{
sys_Printf(BIC_WARNING,"Resuming at position 0!\n");
}
#endif
// if we have a server, and the server instance is still valid...
if (m_pServer && (g_ServerList.Find(m_pServer) >= 0))
{
m_Status = DCCT_STATUS_RESUMING;
m_pServer->CMD_CTCPRequest(m_OtherNick,"DCC RESUME %s %d %lu",
m_FileName,
m_Port,
m_ResumeOffset);
/*
m_pServer->Send("PRIVMSG %s :\001DCC RESUME %s %d %lu\001\r\n",
m_OtherNick,
m_FileName,
m_Port,
m_ResumeOffset);
*/
strcpy(m_StatusStr,"Attempting Resume");
UpdateStatus();
return;
}
else
{
Disconnect("Resume Error: Can't send resume request!");
return;
}
// we never get here.
} // End: File Created, resume attempted.
// if we get here, the file doesn't exist, so accept normally.
}
if (m_Status == DCCT_STATUS_RESUMING)
{
if (m_hFile == INVALID_HANDLE_VALUE)
{
Disconnect("Resume error: File already closed");
return;
}
// move to the resume position, if we're not already there (we should be!)
// get the current position.
dwPtr = SetFilePointer(m_hFile, 0, NULL, FILE_CURRENT);
if (dwPtr != m_ResumeOffset)
{
dwPtr = SetFilePointer (m_hFile, m_ResumeOffset, NULL, FILE_BEGIN);
if (dwPtr == INVALID_SET_FILE_POINTER) // Test for failure
{
Disconnect("Resume error: File seek error");
return;
}
}
// set up the rest of the variables that are used when a file is resumed.
m_Position = m_ResumeOffset;
time(&m_ResumeTime);
}
g_pTransfersManager->m_pTransfersView->ResetStats(this);
unsigned char *AddressDigits;
AddressDigits = (unsigned char *)&m_Address;
_snprintf(m_IPAddressString,sizeof(m_IPAddressString),"%d.%d.%d.%d:%d",AddressDigits[3],AddressDigits[2],AddressDigits[1],AddressDigits[0],(unsigned short)m_Port);
sys_Printf(BIC_INFO,"DCC Connecting to %s\n",m_IPAddressString);
m_pTransferSocket = new Socket(g_pMainWnd->m_hWnd,WM_TRANSFEREVENT);
if (m_pTransferSocket && m_pTransferSocket->Connect(htonl(m_Address),m_Port) == SOCK_ERR_NONE)
{
m_Status = DCCT_STATUS_NEGOTIATE;
_snprintf(m_StatusStr,sizeof(m_StatusStr), "Negotiating Link (%s)", m_IPAddressString);
}
else
{
_snprintf(m_StatusStr,sizeof(m_StatusStr), g_DefaultStrings[DEFSTR_ConnectFailed], m_IPAddressString);
Disconnect(NULL);
}
}
else // m_Type == DCC_SEND
{
if (m_ResumeOffset != 0)
{
// do we still have the server ?
if (g_ServerList.Find(m_pServer) == -1)
{
// No.
Disconnect("Disconnected from server!");
return;
}
else
{
// tell the remote user to accept the file!
m_pServer->CMD_CTCPRequest(m_OtherNick,"DCC ACCEPT %s %d %lu",
"file.ext",
m_Port,
m_ResumeOffset);
/*
m_pServer->Send("PRIVMSG %s :\001DCC ACCEPT %s %d %lu\001\r\n",
m_OtherNick,
"file.ext",
m_Port,
m_ResumeOffset);
*/
sprintf(m_StatusStr,"Accepted resume request");
}
}
else
{
// get the size of the file.
m_hFile = CreateFile(m_LocalFileName,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING, // existing file only
FILE_ATTRIBUTE_NORMAL,
NULL);
if (m_hFile != INVALID_HANDLE_VALUE)
{
m_Size = GetFileSize (m_hFile, NULL);
CloseHandle(m_hFile);
m_hFile = INVALID_HANDLE_VALUE;
if (m_Size == INVALID_FILE_SIZE)
{
Disconnect("Error getting file size (Invalid Size)");
return;
}
}
else
{
Disconnect("Error getting file size (Invalid Handle)");
return;
}
m_pServerSocket = new Socket(g_pMainWnd->m_hWnd,WM_TRANSFEREVENT);
if (!m_pServerSocket)
{
Disconnect("Could not create server socket");
return;
}
// find an available port to listen on...
m_Port = INTPREF(PREF_nDCCSendFirstPort);
CDCCTransfer *pOther;
while ( TRUE )
{
pOther = g_pTransfersManager->FindTransferByPort(m_Port,this);
if ((pOther == NULL) && // no current transfer using this port
(m_pServerSocket->Listen(m_Port) == SOCK_ERR_NONE)) // and the socket is not in use by something else..
break; // found a port, continue!
else
{
if (m_Port < INTPREF(PREF_nDCCSendLastPort) && m_Port < 65535)
m_Port++;
else
{
Disconnect("No free ports!");
return;
}
}
}
sys_Printf(BIC_INFO,"DCC: File %s (%d KB) available on port %d\n",m_LocalFileName,m_Size / 1024,m_Port);
// do we still have the server ?
if (g_ServerList.Find(m_pServer) == -1)
{
// No.
Disconnect("Disconnected from server!");
return;
}
else
{
// tell the remote user to accept the file!
m_pServer->CMD_CTCPRequest(m_OtherNick, "DCC SEND %s %ll %d %lu",
m_FileName,
htonl(GetInternetIP()),
m_Port,
m_Size);
/*
m_pServer->Send("PRIVMSG %s :\001DCC SEND %s %lu %d %lu\001\r\n",
m_OtherNick,
m_FileName,
htonl(GetInternetIP()),
m_Port,
m_Size);
*/
m_Status = DCCT_STATUS_NEGOTIATE;
sprintf(m_StatusStr,"Listening on port %d",m_Port);
// sit back and wait...
}
}
}
UpdateStatus();
}
void CDCCTransfer::Resume( long Offset)
{
if (!(m_Status == DCCT_STATUS_NEGOTIATE || m_Status == DCCT_STATUS_RESUMING))
return;
if (m_Type == DCC_SEND)
{
m_ResumeOffset = Offset;
m_Position = m_ResumeOffset;
m_Status = DCCT_STATUS_RESUMING;
Connect();
}
else // DCC_RECEIVE
{
// TODO: notify user of Offset mismatch, or adjust accordingly?
if (m_ResumeOffset == Offset)
{
Connect();
}
}
}
void CDCCTransfer::Disconnect( char *Reason )
{
NotificationEvent_t *pLastNE = NULL;
// disconnect socket
if (m_pTransferSocket)
{
m_pTransferSocket->CloseSocket();
delete m_pTransferSocket;
m_pTransferSocket = NULL;
}
if (m_pServerSocket)
{
m_pServerSocket->CloseSocket();
delete m_pServerSocket;
m_pServerSocket = NULL;
}
// close file
if (m_hFile != INVALID_HANDLE_VALUE)
{
CloseHandle(m_hFile);
m_hFile = INVALID_HANDLE_VALUE;
}
// update the status, remembering that the socket closes after we complete
if (m_Status != DCCT_STATUS_COMPLETE)
{
if (m_Type == DCC_RECEIVE)
{
pLastNE = g_pNotificationManager->NotificationEvent(NE_DCCFILERECEIVEFAILED,m_NetworkID,m_OtherNick);
switch (m_Status)
{
// we can't always retry a receive.
case DCCT_STATUS_NEGOTIATE:
case DCCT_STATUS_RESUMING:
m_CanRetry = TRUE;
break;
}
}
else
{
pLastNE = g_pNotificationManager->NotificationEvent(NE_DCCFILESENDFAILED,m_NetworkID,m_OtherNick);
m_CanRetry = TRUE; // we can always retry a send!
}
m_Status = DCCT_STATUS_ERROR;
if (Reason)
{
strcpy(m_StatusStr,Reason);
}
}
else
{
// file completed!
if (m_Type == DCC_RECEIVE)
pLastNE = g_pNotificationManager->NotificationEvent(NE_DCCFILERECEIVECOMPLETE,m_NetworkID,m_OtherNick);
else
pLastNE = g_pNotificationManager->NotificationEvent(NE_DCCFILESENDCOMPLETE,m_NetworkID,m_OtherNick);
}
UpdateStatus();
char message[4096];
// you gotta love ternary operators for stuff like this:
_snprintf(message,sizeof(message),"ctcp/dcc %s %s %s of %s %s%s (%s %ldKB of %ldKB)",
m_Type == DCC_RECEIVE ? "Receive" : "Send",
m_Type == DCC_RECEIVE ? "from" : "to",
m_OtherNick,
m_FileName,
m_Status == DCCT_STATUS_COMPLETE ? "Completed" : "Failed: ",
m_Status == DCCT_STATUS_COMPLETE ? "" : m_StatusStr,
m_Type == DCC_RECEIVE ? "Received" : "Sent",
(m_Position / 1024),
(m_Size / 1024));
// if we have a server, and the server instance is still valid...
BOOL ServerStillValid = m_pServer && (g_ServerList.Find(m_pServer) >= 0);
// display message in server window
char percentescapedbuf[512*2 + 1];
EscapePercentCharacters(percentescapedbuf,message,sizeof(percentescapedbuf));
if (ServerStillValid)
{
m_pServer->Printf(BIC_CTCP,percentescapedbuf); // TODO: BIC_QUERYTEXT ? BIC_TRANSFERINFO ???
}
if (pLastNE && pLastNE->m_Flags & NE_FLAG_LOGINEVENTLOG)
{
// add to event log
g_pEventLogManager->AddItem(ELIT_DCC,
m_Status == DCCT_STATUS_COMPLETE ?
(m_Type == DCC_RECEIVE ? ELID_DCC_ReceiveComplete : ELID_DCC_SendComplete)
:
(m_Type == DCC_RECEIVE ? ELID_DCC_ReceiveFailed : ELID_DCC_SendFailed),
m_OtherNick, message,
ServerStillValid ? m_pServer : NULL, NULL);
}
// and also display to the active window, if the server isn't
// the active window (or null). (to avoid printing it twice to the
// same window)
IRCServer *pActiveServer;
if (g_pMainWnd)
{
pActiveServer = FindIRCServer(g_pMainWnd->MDIGetActive(),FALSE);
if ((pActiveServer != m_pServer) || (m_pServer == NULL) || (pActiveServer == NULL))
HydraIRC_ActiveWindowPrintf(BIC_CTCP,percentescapedbuf); // TODO: BIC_QUERYTEXT ? BIC_TRANSFERINFO ???
}
// TODO: try and requeue/resend if failed?
}
/* Check the transfer's not timed out.
*
* this get's called once a second, unless the main app is really busy
* in which case it might be longer.
*/
void CDCCTransfer::Check( void )
{
// only check for timeouts if we're connected...
if (m_Status == DCCT_STATUS_CONNECTED)
{
m_CheckTicks++;
if (m_CheckTicks > INTPREF(PREF_nDCCTransferTimeout))
{
Disconnect("Timeout!");
}
else
{
// Prevent Stalls.
ReadTransferSocket();
WriteTransferSocket();
}
}
// ... or if we're resuming...
if (m_Status == DCCT_STATUS_RESUMING)
{
m_CheckTicks++;
// waiting for response from remote host, after we tried a resume.
if (m_CheckTicks > INTPREF(PREF_nDCCResumeTimeout))
{
Disconnect("Resume Failed");
}
}
// ... or if we're waiting for a remote user...
if (m_Status == DCCT_STATUS_NEGOTIATE)
{
m_CheckTicks++;
// waiting for response from remote host, after we tried a resume.
if (m_CheckTicks > INTPREF(PREF_nDCCNegotiateTimeout))
{
Disconnect("Negotiate Failed");
}
}
}
void CDCCTransfer::OnConnect( void )
{
DWORD dwPtr;
m_Status = DCCT_STATUS_CONNECTED;
unsigned char *AddressDigits = (unsigned char *)&m_pTransferSocket->GetAddress()->sin_addr;
_snprintf(m_IPAddressString,sizeof(m_IPAddressString),"%d.%d.%d.%d:%d",AddressDigits[0],AddressDigits[1],AddressDigits[2],AddressDigits[3],(unsigned short)m_Port);
sys_Printf(BIC_INFO,"DCC Connected to %s\n",m_IPAddressString);
strcpy(m_StatusStr,"Connected");
UpdateStatus();
if (m_Type == DCC_RECEIVE)
{
// file will be at the correct position to start resuming from
// if a resume is required and m_hFile will not be invalid.
// otherwise, create the file
if (m_hFile == INVALID_HANDLE_VALUE)
{
m_hFile = CreateFile(m_LocalFileName,
GENERIC_WRITE,
FILE_SHARE_READ,
NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (m_hFile == INVALID_HANDLE_VALUE)
{
Disconnect("Can't create file!");
// todo: meaningful error messages - see ms-help://MS.VSCC.2003/MS.MSDNQTR.2004OCT.1033/debug/base/retrieving_the_last_error_code.htm
return;
}
}
else
{
g_pEventLogManager->BuildMessage(g_DefaultStrings[DEFSTR_DCC_ReceiveResumed],m_FileName,m_OtherNick,m_ResumeOffset);
g_pEventLogManager->AddItem(ELIT_DCC, ELID_DCC_Receive,m_OtherNick, NULL, m_pServer, NULL);
}
}
else // m_Type == DCC_SEND
{
g_pEventLogManager->BuildMessage(g_DefaultStrings[DEFSTR_DCC_SendAccepted],m_FileName,m_OtherNick);
g_pEventLogManager->AddItem(ELIT_DCC, ELID_DCC_Send,m_OtherNick, NULL, m_pServer, NULL);
m_hFile = CreateFile(m_LocalFileName,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING, // existing file only
FILE_ATTRIBUTE_NORMAL,
NULL);
if (m_hFile == INVALID_HANDLE_VALUE)
{
Disconnect("Can't open local file!");
return;
}
if (m_ResumeOffset != 0)
{
// move to the resume position
dwPtr = SetFilePointer (m_hFile, m_ResumeOffset, NULL, FILE_BEGIN);
if (dwPtr == INVALID_SET_FILE_POINTER || dwPtr != m_ResumeOffset) // Test for failure
{
Disconnect("Resume error: File seek error");
return;
}
m_Position = m_ResumeOffset;
m_FilePosition = m_ResumeOffset;
time(&m_ResumeTime);
g_pTransfersManager->m_pTransfersView->ResetStats(this);
g_pEventLogManager->BuildMessage(g_DefaultStrings[DEFSTR_DCC_SendResumed],m_FileName,m_OtherNick,m_ResumeOffset);
g_pEventLogManager->AddItem(ELIT_DCC, ELID_DCC_Send,m_OtherNick, NULL, m_pServer, NULL);
}
}
}
void CDCCTransfer::OnDCCServerSocketEvent(int Event, int Error)
{
// Todo: display more info about which transfer had a problem
if (Error != 0)
sys_Printf(BIC_WARNING,"Transfer Socket Error: (%d : %s)\n", Error, m_pServerSocket->GetWSASelectErrorString(Error));
switch(Event)
{
case FD_ACCEPT:
m_pTransferSocket = new Socket(g_pMainWnd->m_hWnd,WM_TRANSFEREVENT);
if (m_pTransferSocket)
{
if (m_pTransferSocket->Accept(m_pServerSocket,FD_CLOSE | FD_READ | FD_CONNECT | FD_WRITE))
{
m_pServerSocket->CloseSocket(); // we don't want any more connections
strcpy(m_StatusStr,"Socket connection accepted");
UpdateStatus();
}
else
{
Disconnect("Couldn't accept socket");
return;
}
}
else
{
Disconnect("Couldn't create socket");
return;
}
break;
case FD_CLOSE: // TODO: check this code...
#ifdef DEBUG
sys_Printf(BIC_INFO,"Server socket close notification, m_Status = %d\n",m_Status);
#endif
if (m_pServerSocket->GetSocket() != INVALID_SOCKET)
m_pServerSocket->CloseSocket();
break;
#ifdef DEBUG
default:
sys_Printf(BIC_INFO,"unprocessed: OnDCCServerSocketEvent(%d,%d), m_Status = %d\n",Event, Error, m_Status);
#endif
}
}
void CDCCTransfer::OnDCCTransferSocketEvent(int Event, int Error)
{
// Todo: display more info about which transfer had a problem
if (Error != 0)
sys_Printf(BIC_WARNING,"Transfer Socket Error: (%d : %s)\n", Error, m_pTransferSocket->GetWSASelectErrorString(Error));
switch(Event)
{
case FD_ACCEPT:
//#ifdef DEBUG
if (m_Verbose)
sys_Printf(BIC_INFO,"FD_ACCEPT Notification, m_Position = %d\n",m_Position);
//#endif
// follow through..
case FD_CONNECT:
if (m_pTransferSocket->GetSocket() == INVALID_SOCKET || Error != 0)
{
_snprintf(m_StatusStr,sizeof(m_StatusStr), g_DefaultStrings[DEFSTR_ConnectFailed], m_IPAddressString);
Disconnect(NULL);
}
else
{
OnConnect();
}
break;
case FD_CLOSE:
_snprintf(m_StatusStr,sizeof(m_StatusStr), g_DefaultStrings[DEFSTR_ConnectionClosed], m_IPAddressString);
Disconnect(NULL);
break;
case FD_WRITE:
{
//#ifdef DEBUG
if (m_Verbose)
sys_Printf(BIC_INFO, "FD_WRITE Notification, m_Position = %d, m_RemotePosition = %d\n",m_Position,m_RemotePosition);
//#endif
if (m_Type == DCC_SEND)
{
// this is the fist FD_WRITE we've received...
if (m_Status != DCCT_STATUS_CONNECTED)
OnConnect();
WriteTransferSocket();
}
}
break;
case FD_READ:
{
//#ifdef DEBUG
if (m_Verbose)
sys_Printf(BIC_INFO, "FD_READ Notification, m_Position = %d, m_RemotePosition = %d\n",m_Position,m_RemotePosition);
//#endif
ReadTransferSocket();
}
break;
#ifdef DEBUG
default:
sys_Printf(BIC_INFO,"unprocessed: OnDCCTransferSocketEvent(%d,%d), m_Status = %d\n",Event, Error, m_Status);
#endif
}
}
void CDCCTransfer::ReadTransferSocket( void )
{
int BytesRead;
DWORD BytesWritten;
unsigned long cbLen;
unsigned long Bytes;
// Set this now, something's changed.
// Note: we do this *without* calling UpdateStatus() because
// we don't want to call UpdateStatus() each time we receive
// a bit of data.
m_StatusDirty = TRUE;
if (m_Type == DCC_RECEIVE)
{
cbLen = m_pTransferSocket->GetWaiting();
cbLen = min(sizeof(m_SocketBuf),cbLen);
BytesRead = m_pTransferSocket->Receive(m_SocketBuf,cbLen,0);
// we don't do any null terminating, it's a data stream...
if (BytesRead == SOCKET_ERROR)
{
int Error = WSAGetLastError();
if (m_Verbose)
sys_Printf(BIC_WARNING,"Socket error while receiving: (%d : %s)\n", Error, m_pTransferSocket->GetWSASelectErrorString(Error));
return;
}
else
{
if (BytesRead > 0)
{
// we got some data!
m_CheckTicks = 0; // reset our timeout counter.
// write to the file and check for error.
LockFile(m_hFile, m_Position, 0, BytesRead, 0);
WriteFile(m_hFile, m_SocketBuf, BytesRead, &BytesWritten, NULL);
UnlockFile(m_hFile, m_Position, 0, BytesRead, 0);
if (BytesRead != BytesWritten)
{
sys_Printf(BIC_ERROR,"File write error (Bytes Written: %d != Bytes to Write: %d)\n", BytesWritten, BytesRead);
Disconnect("File write error");
}
else
{
m_Received += BytesRead;
m_Position += BytesRead;
Bytes = htonl(m_Position);
BytesWritten = m_pTransferSocket->SendRaw((char *)&Bytes, sizeof(Bytes), 0);
if (BytesWritten == SOCKET_ERROR)
{
int Error = WSAGetLastError();
if (m_Verbose)
sys_Printf(BIC_WARNING,"Socket error while sending (1): (%d : %s)\n", Error, m_pTransferSocket->GetWSASelectErrorString(Error));
// carry on regardless of error.
}
else
{
m_Sent += BytesWritten;
}
if (m_Position == m_Size)
{
CloseHandle(m_hFile);
m_hFile = INVALID_HANDLE_VALUE;
m_Status = DCCT_STATUS_COMPLETE;
strcpy(m_StatusStr,"Complete");
UpdateStatus();
// Note: socket is disconnected by remote host.
// so we'll receive a FD_CLOSE in a moment...
}
}
}
}
}
else // m_Type == DCC_SEND
{
int LoopCount = 0; // make sure we exit this loop every so often
// as the dcc transfers run in the same thread as the rest of the app
//do
//{
cbLen = m_pTransferSocket->GetWaiting();
cbLen = min(sizeof(m_SocketBuf),cbLen);
if (cbLen < sizeof(DWORD))
{
//if (m_Verbose)
// sys_Printf(BIC_SOCKET,"Bytes waiting = %d (< %d) (\n",cbLen, sizeof(DWORD));
//g_pMainWnd->PostMessage(WM_PROCESSDCCS,0,0);
return;
}
else
{
if (m_Verbose)
sys_Printf(BIC_SOCKET,"Bytes Waiting: %d\n", cbLen);
}
BytesRead = m_pTransferSocket->Receive(m_SocketBuf,sizeof(DWORD),0);
// we don't do any null terminating, it's a data stream...
if (BytesRead == SOCKET_ERROR)
{
int Error = WSAGetLastError();
if (m_Verbose)
sys_Printf(BIC_SOCKET,"Socket error while receiving: (%d : %s)\n", Error, m_pTransferSocket->GetWSASelectErrorString(Error));
return;
}
else
{
m_Received += BytesRead;
if (BytesRead == 0)
{
if (m_Verbose)
sys_Printf(BIC_WARNING,"0 byte socket read with %d bytes waiting\n",cbLen);
}
else
{
// we got some data!
m_CheckTicks = 0; // reset our timeout counter.
// check file position.
m_RemotePosition = htonl(*((DWORD*)m_SocketBuf));
if (m_RemotePosition == m_Size)
{
m_Status = DCCT_STATUS_COMPLETE;
strcpy(m_StatusStr,"Complete");
//UpdateStatus();
Disconnect(NULL);
return;
}
else
{
if (m_RemotePosition != m_Position)
{
//if (m_Verbose)
// sys_Printf(BIC_WARNING,"m_RemotePosition (%d) != m_Position (%d)\n",m_RemotePosition,m_Position);
}
else
{
//if (m_Verbose)
// sys_Printf(BIC_INFO,"m_RemotePosition (%d) == m_Position (%d)\n",m_RemotePosition,m_Position);
m_ReadyToSend = TRUE;
}
WriteTransferSocket();
}
}
}
/*
if (cbLen > sizeof(DWORD))
{
if (m_Verbose)
sys_Printf(BIC_INFO,"Large DCC Receive Buffer!, parsing again! (%d)\n",cbLen);
}
*/
//} while (cbLen > sizeof(DWORD) && LoopCount++ < 1000); // deal with max 1000 * m_PacketSize bytes per call.
//} while (0);
//g_pMainWnd->PostMessage(WM_PROCESSDCCS,0,0);
} // END: m_Type == DCC_SEND
}
BOOL CDCCTransfer::ProcessFastDCCSend( void )
{
if (m_Type == DCC_RECEIVE)
return FALSE;
if (m_Status != DCCT_STATUS_CONNECTED)
return FALSE;
ReadTransferSocket();
WriteTransferSocket();
return TRUE;
}
void CDCCTransfer::WriteTransferSocket( void )
{
if (m_Type == DCC_RECEIVE) // we only do sending in here.
return;
if (m_Verbose)
sys_Printf(BIC_INFO,"SendNextBlock: m_RemotePosition = %d, m_Position = %d, m_Sent = %d\n",m_RemotePosition,m_Position,m_Sent);
if (m_hFile == INVALID_HANDLE_VALUE)
{
if (m_Verbose)
sys_Printf(BIC_WARNING,"SendNextBlock: file is not open\n");
return;
}
if (!m_ReadyToSend)
{
if (m_Verbose)
sys_Printf(BIC_WARNING,"SendNextBlock: NOT ready to send\n");
return;
}
// TODO: Move this bit of code to Socket::IsReadyToWrite()
fd_set socketlist;
socketlist.fd_count = 1;
socketlist.fd_array[0] = m_pTransferSocket->GetSocket();
timeval socketwaittime = {0};
int result = select(NULL,NULL,&socketlist,NULL,&socketwaittime);
// TODO: end of bit to move
if (result != 1)
{
if (m_Verbose)
sys_Printf(BIC_WARNING,"SendNextBlock: Write socket not ready!\n");
// TODO: FIXME!
//g_pMainWnd->PostMessage(WM_PROCESSDCCS,0,0);
return;
}
// Read From File
DWORD BytesRead;
if (m_Position == m_FilePosition && m_Position != m_Size) // we need to read more data from the file
{
// don't try and read past the end of the file (as we already told the other
// host how big the file is).
DWORD BytesToRead = min(m_PacketSize, m_Size - m_FilePosition);
if (ReadFile(m_hFile, m_FileBuf, BytesToRead, &BytesRead, NULL))
{
m_FilePosition += BytesRead;
}
else
{
Disconnect("File read error");
return;
}
}
// Write To Socket
int BytesWritten, BytesToSend = m_FilePosition - m_Position;
//if (m_Verbose)
// sys_Printf(BIC_INFO,"SendNextBlock: BytesToSend == %d\n",BytesToSend);
if (BytesToSend == 0)
{
return;
}
BytesWritten = m_pTransferSocket->SendRaw(m_FileBuf,BytesToSend,0);
if (BytesWritten == SOCKET_ERROR)
{
int Error = WSAGetLastError();
sys_Printf(BIC_SOCKET,"Socket error while sending (2): (%d : %s)\n", Error, m_pTransferSocket->GetWSASelectErrorString(Error));
return;
}
if (BytesToSend != BytesWritten)
{
char *MessageStr = "Read/Send size mismatch while sending";
Disconnect(MessageStr);
sys_Printf(BIC_ERROR,"%s %s to %s: %d != %d\n",MessageStr, m_FileName, m_OtherNick, BytesRead, BytesWritten);
return;
}
m_Sent += BytesWritten;
m_Position += BytesWritten;
// now wait for the remote end to tell us how much data they've received.
if (!m_FastSend)
m_ReadyToSend = FALSE;
}
BOOL CDCCTransfer::IsActive( void )
{
return ((BOOL)(m_Status != DCCT_STATUS_ERROR &&
m_Status != DCCT_STATUS_COMPLETE));
}
| [
"hydra@b2473a34-e2c4-0310-847b-bd686bddb4b0"
]
| [
[
[
1,
1249
]
]
]
|
d5aedc97430e44a2349da6895dd17e2b9294c4c4 | a03552b9437e0e9d7786d11ee18a5326b912efd9 | /PDF2Text/SettingsDlg.h | 08cc536164f78d74a3b63798bcd7be2ac68f72d0 | []
| no_license | datadiode/pdf2textpilot | 179f7fbf3224860363578780207e852ef5593e23 | d4d2f19c15e4f0ba1207f64092e6d14c3fc5b038 | refs/heads/master | 2023-03-06T14:30:59.245793 | 2009-05-26T06:31:02 | 2009-05-26T06:31:02 | 338,306,494 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,886 | h | #pragma once
class CSettingsDlg : public CDialogImpl<CSettingsDlg>,
public CWinDataExchange<CSettingsDlg>
{
public:
bool IsAuthor, IsSubject, IsTitle, IsKeywords;
bool Author, Subject, Title, Keywords;
CButton btnOk, btnCancel;
public:
enum { IDD = IDD_SETTINGSDLG };
BEGIN_MSG_MAP(CAdvSettingsDlg)
MSG_WM_INITDIALOG(OnInitDialog)
COMMAND_HANDLER_EX(IDCANCEL, BN_CLICKED, OnCancel)
COMMAND_HANDLER(IDC_checkAuthor, BN_CLICKED, OnBnClickedcheckAuthor)
COMMAND_HANDLER(IDC_checkSubject, BN_CLICKED, OnBnClickedcheckSubject)
COMMAND_HANDLER(IDC_checkTitle, BN_CLICKED, OnBnClickedcheckTitle)
COMMAND_HANDLER(IDC_checkKeywords, BN_CLICKED, OnBnClickedcheckKeywords)
COMMAND_HANDLER(IDC_btnCancel, BN_CLICKED, OnBnClickedbtnCancel)
COMMAND_HANDLER(IDC_btnOk, BN_CLICKED, OnBnClickedbtnOk)
END_MSG_MAP()
BEGIN_DDX_MAP(CAdvSettingsDlg)
DDX_CONTROL_HANDLE(IDC_btnOk, btnOk)
DDX_CONTROL_HANDLE(IDC_btnCancel, btnCancel)
DDX_CHECK(IDC_checkAuthor, Author)
DDX_CHECK(IDC_checkSubject, Subject)
DDX_CHECK(IDC_checkTitle, Title)
DDX_CHECK(IDC_checkKeywords, Keywords)
END_DDX_MAP()
public:
// Notification handlers
LRESULT OnInitDialog(HWND hwndFocus, LPARAM lParam);
LRESULT OnCancel(WORD wNotifyCode, WORD wID, HWND hWndCtl);
LRESULT OnBnClickedcheckAuthor(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled);
LRESULT OnBnClickedcheckSubject(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled);
LRESULT OnBnClickedcheckTitle(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled);
LRESULT OnBnClickedcheckKeywords(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled);
LRESULT OnBnClickedbtnCancel(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled);
LRESULT OnBnClickedbtnOk(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled);
};
| [
"twopilots@6815dd50-5389-4add-8d21-7a52ba5a1ba7"
]
| [
[
[
1,
45
]
]
]
|
b72ffeb9d9879dba1e3de24a90737c7ee0d52f15 | 95e051bc96bd3f765ce1cec4868535b667be81b6 | /ExplodedVolume/UserInterface/GeneratedFiles/Debug/moc_VisualizationWidget.cpp | ea24ac9bb281b0b388ae926cd49934159d878f26 | []
| 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 | 2,270 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'VisualizationWidget.h'
**
** Created: Thu 28. Jan 23:55:55 2010
** by: The Qt Meta Object Compiler version 62 (Qt 4.6.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../VisualizationWidget.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'VisualizationWidget.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 62
#error "This file was generated using the moc from 4.6.1. 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_VisualizationWidget[] = {
// content:
4, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
static const char qt_meta_stringdata_VisualizationWidget[] = {
"VisualizationWidget\0"
};
const QMetaObject VisualizationWidget::staticMetaObject = {
{ &QGLWidget::staticMetaObject, qt_meta_stringdata_VisualizationWidget,
qt_meta_data_VisualizationWidget, 0 }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &VisualizationWidget::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *VisualizationWidget::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *VisualizationWidget::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_VisualizationWidget))
return static_cast<void*>(const_cast< VisualizationWidget*>(this));
return QGLWidget::qt_metacast(_clname);
}
int VisualizationWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QGLWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_END_MOC_NAMESPACE
| [
"fabiom@2fa1dc7e-98ce-11de-bff5-93fd3790126f"
]
| [
[
[
1,
69
]
]
]
|
5cb319872c997c6a75ee1d620721af6c5446dd14 | b04f65deafef481d6e0f22c26085735a3c275d3a | /mod/applications/mod_cari_ccp_server/CModule_SysInfo.h | d8500bbce3334be0f7eac8f19ba0826a863b4e53 | []
| no_license | gujun/sscore | d28d374f09d40aa426282538416ae16023d8a7a6 | 295d613473a554e4de9f8c203fae961f587555ac | refs/heads/master | 2021-01-02T22:57:21.404133 | 2011-06-21T06:19:57 | 2011-06-21T06:19:57 | 1,927,509 | 2 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,729 | h | #ifndef CMODULE_SYSINFO_H
#define CMODULE_SYSINFO_H
#include "CBaseModule.h"
#if defined(_WIN32) || defined(WIN32)
#pragma comment(lib,"Ws2_32.lib")
//定义驱动空间的结构体
typedef struct
{
char m_FileSystem[256];
char m_DriverType[16];
int m_TotalSize;
int m_UsedSize;
int m_FreeSize;
char m_Usage[10];
}DriverStruct;
#define MAX_OF_HARD_DISKS 24
//static char HardDiskLetters[MAX_OF_HARD_DISKS][4]={
// "c:\\", "d:\\", "e:\\", "f:\\", "g:\\", "h:\\",
// "i:\\", "j:\\", "k:\\", "l:\\", "m:\\", "n:\\",
// "o:\\", "p:\\", "q:\\", "r:\\", "s:\\", "t:\\",
// "u:\\", "v:\\", "w:\\", "x:\\", "y:\\", "z:\\"
//};
#endif
//////////////////////////////////////////////////////////////////////////
/*设备系统的运行状况,包括CPU信息,内存使用情况,磁盘空间等信息
*/
class CModule_SysInfo :public CBaseModule
{
public:
CModule_SysInfo();
~CModule_SysInfo();
public://method
void init();
int receiveReqMsg(inner_CmdReq_Frame*& reqFrame, inner_ResultResponse_Frame*& inner_RespFrame);//接收命令
int sendRespMsg(common_ResultResponse_Frame*& reqFrame); //发送结果
int cmdPro(const inner_CmdReq_Frame*& reqFrame); //命令处理
protected:
//method
private:
//信息的查询,或"轮询"
int querySysInfo(inner_CmdReq_Frame*& reqFrame, inner_ResultResponse_Frame*& inner_RespFrame);
int queryCPUInfo(inner_CmdReq_Frame*& reqFrame, inner_ResultResponse_Frame*& inner_RespFrame);
int queryMemoryInfo(inner_CmdReq_Frame*& reqFrame, inner_ResultResponse_Frame*& inner_RespFrame);
int queryDiskInfo(inner_CmdReq_Frame*& reqFrame, inner_ResultResponse_Frame*& inner_RespFrame);
int queryUptimeInfo(inner_CmdReq_Frame*& reqFrame, inner_ResultResponse_Frame*& inner_RespFrame);
int queryCPURate(inner_CmdReq_Frame*& reqFrame, inner_ResultResponse_Frame*& inner_RespFrame);
};
/************************************************************************/
/* */
/************************************************************************/
//其他,主要涉及到更新比较快的动态信息,可以采用"上报"方式进行
string extractValidStr(string strSource);
void getUpTime(string &strRunTime,string &strUserNum,string &strLoadedAver);
void getCPURate(string &strColName,/*string &strColValue*/char *chColVal);
//下面的方法主要是在windows环境下使用
#if defined(_WIN32) || defined(WIN32)
void QueryOS(string &strOSKneral, string &strOSVersion);
void QCpu();
void QueryRAM(int &allRam,int &availRam,int &usedRam);
void QueryDriveSpace(vector<DriverStruct> &driverVec);
#endif
#endif
| [
"pub@cariteledell.(none)"
]
| [
[
[
1,
76
]
]
]
|
8e7667efbffbb938799abf871e8561bf3bec4239 | 208475bcab65438eed5d8380f26eacd25eb58f70 | /QianExe/yx_Help.cpp | 04774a3a17630d7a85215d8d61003d814aed940b | []
| no_license | awzhang/MyWork | 83b3f0b9df5ff37330c0e976310d75593f806ec4 | 075ad5d0726c793a0c08f9158080a144e0bb5ea5 | refs/heads/master | 2021-01-18T07:57:03.219372 | 2011-07-05T02:41:55 | 2011-07-05T02:46:30 | 15,523,223 | 1 | 2 | null | null | null | null | GB18030 | C++ | false | false | 5,524 | cpp | #include "yx_QianStdAfx.h"
#undef MSG_HEAD
#define MSG_HEAD ("QianExe-Help ")
void G_TmAutoDialHelpTel(void *arg, int ien)
{
g_objHelp.P_TmAutoDialHelpTel();
}
//////////////////////////////////////////////////////////////////////////
CHelp::CHelp()
{
}
CHelp::~CHelp()
{
}
// 求助应答: 应答类型(1)+ 求助类型(1)+ 日期(3)+ 时间(3)
int CHelp::Deal0301( char* v_szData, DWORD v_dwDataLen )
{
if( v_dwDataLen < 8 ) return ERR_PAR;
char buf[ 32 ] = { 0 };
buf[ 0 ] = BYTE( 0x01 );
buf[ 1 ] = BYTE( 0x83 );
memcpy( buf + 2, v_szData, 8 );
// 日期时间可能要转换
if( 0x7f == BYTE(buf[4]) ) buf[4] = 0;
if( 0x7f == BYTE(buf[7]) ) buf[7] = 0;
if( 0x7f == BYTE(buf[8]) ) buf[8] = 0;
if( 0x7f == BYTE(buf[9]) ) buf[9] = 0;
DataPush(buf, 10, DEV_QIAN, DEV_DIAODU, LV2);
return 0;
}
int CHelp::Deal0e01( char* v_szSrcHandtel, char* v_szData, DWORD v_dwDataLen )
{
tag2QServCodeCfg objServCodeCfg, objServCodeCfgBkp;
int iRet = 0;
char buf[ SOCK_MAXSIZE ];
int iBufLen = 0;
BYTE bytResType = 0;
// 数据参数检查
if( 15 != v_dwDataLen )
{
iRet = ERR_PAR;
goto DEAL0E01_FAILED;
}
// 读取->修改
iRet = GetSecCfg( &objServCodeCfg, sizeof(objServCodeCfg), offsetof(tagSecondCfg, m_uni2QServCodeCfg.m_obj2QServCodeCfg), sizeof(objServCodeCfg) );
if( iRet ) goto DEAL0E01_FAILED;
objServCodeCfgBkp = objServCodeCfg; // 先备份
memcpy( objServCodeCfg.m_szHelpTel, v_szData, sizeof(objServCodeCfg.m_szHelpTel) );
// 写回和发送应答
bytResType = 0x01;
iRet = g_objSms.MakeSmsFrame( (char*)&bytResType, 1, 0x0e, 0x41, buf, sizeof(buf), iBufLen);
if( !iRet )
{
iRet = SetSecCfg(&objServCodeCfg, offsetof(tagSecondCfg, m_uni2QServCodeCfg.m_obj2QServCodeCfg), sizeof(objServCodeCfg) );
if( iRet )
goto DEAL0E01_FAILED;
iRet = g_objSock.SOCKSNDSMSDATA( buf, iBufLen, LV12, 0 );
if( iRet ) // 若发送失败
{
SetSecCfg( &objServCodeCfgBkp, offsetof(tagSecondCfg, m_uni2QServCodeCfg.m_obj2QServCodeCfg), sizeof(objServCodeCfgBkp) ); // 恢复原设置
goto DEAL0E01_FAILED;
}
}
else goto DEAL0E01_FAILED;
return 0;
DEAL0E01_FAILED:
bytResType = 0x7f;
int iRet2 = g_objSms.MakeSmsFrame( (char*)&bytResType, 1, 0x0e, 0x41, buf, sizeof(buf), iBufLen);
if( !iRet2 ) g_objSock.SOCKSNDSMSDATA( buf, iBufLen, LV12, 0 );
return iRet;
}
int CHelp::Deal100b( char* v_szSrcHandtel, char* v_szData, DWORD v_dwDataLen, bool v_bFromSM )
{
tag2QServCodeCfg objServCodeCfg, objServCodeCfgBkp;
int iRet = 0;
char buf[ SOCK_MAXSIZE ];
int iBufLen = 0;
BYTE bytResType = 0;
// 数据参数检查
if( 15 != v_dwDataLen )
{
iRet = ERR_PAR;
goto DEAL100b_FAILED;
}
// 读取->修改
iRet = GetSecCfg( &objServCodeCfg, sizeof(objServCodeCfg), offsetof(tagSecondCfg, m_uni2QServCodeCfg.m_obj2QServCodeCfg), sizeof(objServCodeCfg) );
if( iRet ) goto DEAL100b_FAILED;
objServCodeCfgBkp = objServCodeCfg; // 先备份
memcpy( objServCodeCfg.m_szHelpTel, v_szData, sizeof(objServCodeCfg.m_szHelpTel) );
// 写回和发送应答
bytResType = 0x01;
iRet = g_objSms.MakeSmsFrame( (char*)&bytResType, 1, 0x10, 0x4b, buf, sizeof(buf), iBufLen);
if( !iRet )
{
iRet = SetSecCfg(&objServCodeCfg, offsetof(tagSecondCfg, m_uni2QServCodeCfg.m_obj2QServCodeCfg), sizeof(objServCodeCfg) );
if( iRet ) goto DEAL100b_FAILED;
iRet = g_objSock.SOCKSNDSMSDATA( buf, iBufLen, LV12, v_bFromSM ? DATASYMB_USESMS : 0, v_bFromSM ? v_szSrcHandtel : NULL ); // 发送
if( iRet ) // 若发送失败
{
SetSecCfg( &objServCodeCfgBkp, offsetof(tagSecondCfg, m_uni2QServCodeCfg.m_obj2QServCodeCfg), sizeof(objServCodeCfgBkp) ); // 恢复原设置
goto DEAL100b_FAILED;
}
}
else goto DEAL100b_FAILED;
return 0;
DEAL100b_FAILED:
bytResType = 0x7f;
int iRet2 = g_objSms.MakeSmsFrame( (char*)&bytResType, 1, 0x10, 0x4b, buf, sizeof(buf), iBufLen);
if( !iRet2 ) g_objSock.SOCKSNDSMSDATA( buf, iBufLen, LV12, v_bFromSM ? DATASYMB_USESMS : 0, v_bFromSM ? v_szSrcHandtel : NULL );
return iRet;
}
int CHelp::DealComu80( char* v_szData, DWORD v_dwDataLen )
{
int iRet = 0;
int iBufLen = 0;
WORD wPhotoType = 0;
char buf[SOCK_MAXSIZE];
tag0341 req;
tagQianGps objQianGps;
tag2QGprsCfg objGprsCfg;
GetSecCfg( &objGprsCfg, sizeof(objGprsCfg), offsetof(tagSecondCfg, m_uni2QGprsCfg.m_obj2QGprsCfg), sizeof(objGprsCfg) );
if( v_dwDataLen < 1 )
{
iRet = ERR_PAR;
goto DEALCOMU80_END;
}
iRet = g_objMonAlert.GetCurQianGps( objQianGps, true );
if( iRet ) goto DEALCOMU80_END;
req.m_bytHelpType = v_szData[ 0 ];
memcpy( &req.m_objQianGps, &objQianGps, sizeof(req.m_objQianGps) );
iRet = g_objSms.MakeSmsFrame( (char*)&req, sizeof(req), 0x03, 0x41, buf, sizeof(buf), iBufLen );
if( iRet ) goto DEALCOMU80_END;
iRet = g_objSock.SOCKSNDSMSDATA( buf, iBufLen, LV13,
(objGprsCfg.m_bytChannelBkType_1 & 0x04) ? DATASYMB_SMSBACKUP : 0 );
DEALCOMU80_END:
BYTE bytResType = 0;
if( !iRet ) bytResType = 1;
else bytResType = 2;
buf[0] = 0x01;
buf[1] = char(0x81);
buf[2] = bytResType;
DataPush(buf, 3, DEV_QIAN, DEV_DIAODU, LV2);
#if QIANTYPE_USE == QIANTYPE_KJ2 || QIANTYPE_USE == QIANTYPE_JG2 || QIANTYPE_USE == QIANTYPE_V7
_SetTimer(&g_objTimerMng, AUTODIALHELPTEL_TIMER, 3000, G_TmAutoDialHelpTel );
#endif
return iRet;
}
void CHelp::P_TmAutoDialHelpTel()
{
}
| [
"[email protected]"
]
| [
[
[
1,
194
]
]
]
|
587a6162e26cc62d64d2bacc0b456d69a2cc84e7 | 5e61787e7adba6ed1c2b5e40d38098ebdf9bdee8 | /sans/models/c_models/CMultiShellModel.cpp | 82ee4802d58bedc3cd3feae60c8d0bf774df91da | []
| no_license | mcvine/sansmodels | 4dcba43d18c930488b0e69e8afb04139e89e7b21 | 618928810ee7ae58ec35bbb839eba2a0117c4611 | refs/heads/master | 2021-01-22T13:12:22.721492 | 2011-09-30T14:01:06 | 2011-09-30T14:01:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,445 | cpp | /**
This software was developed by the University of Tennessee as part of the
Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
project funded by the US National Science Foundation.
If you use DANSE applications to do scientific research that leads to
publication, we ask that you acknowledge the use of the software with the
following sentence:
"This work benefited from DANSE software developed under NSF award DMR-0520547."
copyright 2008, University of Tennessee
*/
/** CMultiShellModel
*
* C extension
*
* WARNING: THIS FILE WAS GENERATED BY WRAPPERGENERATOR.PY
* DO NOT MODIFY THIS FILE, MODIFY multishell.h
* AND RE-RUN THE GENERATOR SCRIPT
*
*/
#define NO_IMPORT_ARRAY
#define PY_ARRAY_UNIQUE_SYMBOL PyArray_API_sans
extern "C" {
#include <Python.h>
#include <arrayobject.h>
#include "structmember.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include "multishell.h"
}
#include "models.hh"
#include "dispersion_visitor.hh"
/// Error object for raised exceptions
static PyObject * CMultiShellModelError = NULL;
// Class definition
typedef struct {
PyObject_HEAD
/// Parameters
PyObject * params;
/// Dispersion parameters
PyObject * dispersion;
/// Underlying model object
MultiShellModel * model;
/// Log for unit testing
PyObject * log;
} CMultiShellModel;
static void
CMultiShellModel_dealloc(CMultiShellModel* self)
{
Py_DECREF(self->params);
Py_DECREF(self->dispersion);
Py_DECREF(self->log);
delete self->model;
self->ob_type->tp_free((PyObject*)self);
}
static PyObject *
CMultiShellModel_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
CMultiShellModel *self;
self = (CMultiShellModel *)type->tp_alloc(type, 0);
return (PyObject *)self;
}
static int
CMultiShellModel_init(CMultiShellModel *self, PyObject *args, PyObject *kwds)
{
if (self != NULL) {
// Create parameters
self->params = PyDict_New();
self->dispersion = PyDict_New();
self->model = new MultiShellModel();
// Initialize parameter dictionary
PyDict_SetItemString(self->params,"core_sld",Py_BuildValue("d",0.000006400000));
PyDict_SetItemString(self->params,"core_radius",Py_BuildValue("d",60.000000000000));
PyDict_SetItemString(self->params,"n_pairs",Py_BuildValue("d",2.000000000000));
PyDict_SetItemString(self->params,"w_thickness",Py_BuildValue("d",10.000000000000));
PyDict_SetItemString(self->params,"s_thickness",Py_BuildValue("d",10.000000000000));
PyDict_SetItemString(self->params,"scale",Py_BuildValue("d",1.000000000000));
PyDict_SetItemString(self->params,"background",Py_BuildValue("d",0.000000000000));
PyDict_SetItemString(self->params,"shell_sld",Py_BuildValue("d",0.000000400000));
// Initialize dispersion / averaging parameter dict
DispersionVisitor* visitor = new DispersionVisitor();
PyObject * disp_dict;
disp_dict = PyDict_New();
self->model->core_radius.dispersion->accept_as_source(visitor, self->model->core_radius.dispersion, disp_dict);
PyDict_SetItemString(self->dispersion, "core_radius", disp_dict);
disp_dict = PyDict_New();
self->model->s_thickness.dispersion->accept_as_source(visitor, self->model->s_thickness.dispersion, disp_dict);
PyDict_SetItemString(self->dispersion, "s_thickness", disp_dict);
disp_dict = PyDict_New();
self->model->w_thickness.dispersion->accept_as_source(visitor, self->model->w_thickness.dispersion, disp_dict);
PyDict_SetItemString(self->dispersion, "w_thickness", disp_dict);
// Create empty log
self->log = PyDict_New();
}
return 0;
}
static PyMemberDef CMultiShellModel_members[] = {
{"params", T_OBJECT, offsetof(CMultiShellModel, params), 0,
"Parameters"},
{"dispersion", T_OBJECT, offsetof(CMultiShellModel, dispersion), 0,
"Dispersion parameters"},
{"log", T_OBJECT, offsetof(CMultiShellModel, log), 0,
"Log"},
{NULL} /* Sentinel */
};
/** Read double from PyObject
@param p PyObject
@return double
*/
double CMultiShellModel_readDouble(PyObject *p) {
if (PyFloat_Check(p)==1) {
return (double)(((PyFloatObject *)(p))->ob_fval);
} else if (PyInt_Check(p)==1) {
return (double)(((PyIntObject *)(p))->ob_ival);
} else if (PyLong_Check(p)==1) {
return (double)PyLong_AsLong(p);
} else {
return 0.0;
}
}
/**
* Function to call to evaluate model
* @param args: input numpy array q[]
* @return: numpy array object
*/
static PyObject *evaluateOneDim(MultiShellModel* model, PyArrayObject *q){
PyArrayObject *result;
// Check validity of array q , q must be of dimension 1, an array of double
if (q->nd != 1 || q->descr->type_num != PyArray_DOUBLE)
{
//const char * message= "Invalid array: q->nd=%d,type_num=%d\n",q->nd,q->descr->type_num;
//PyErr_SetString(PyExc_ValueError , message);
return NULL;
}
result = (PyArrayObject *)PyArray_FromDims(q->nd, (int *)(q->dimensions),
PyArray_DOUBLE);
if (result == NULL) {
const char * message= "Could not create result ";
PyErr_SetString(PyExc_RuntimeError , message);
return NULL;
}
for (int i = 0; i < q->dimensions[0]; i++){
double q_value = *(double *)(q->data + i*q->strides[0]);
double *result_value = (double *)(result->data + i*result->strides[0]);
*result_value =(*model)(q_value);
}
return PyArray_Return(result);
}
/**
* Function to call to evaluate model
* @param args: input numpy array [x[],y[]]
* @return: numpy array object
*/
static PyObject * evaluateTwoDimXY( MultiShellModel* model,
PyArrayObject *x, PyArrayObject *y)
{
PyArrayObject *result;
int i,j, x_len, y_len, dims[1];
//check validity of input vectors
if (x->nd != 1 || x->descr->type_num != PyArray_DOUBLE
|| y->nd != 1 || y->descr->type_num != PyArray_DOUBLE
|| y->dimensions[0] != x->dimensions[0]){
const char * message= "evaluateTwoDimXY expect 2 numpy arrays";
PyErr_SetString(PyExc_ValueError , message);
return NULL;
}
if (PyArray_Check(x) && PyArray_Check(y)) {
x_len = dims[0]= x->dimensions[0];
y_len = dims[0]= y->dimensions[0];
// Make a new double matrix of same dims
result=(PyArrayObject *) PyArray_FromDims(1,dims,NPY_DOUBLE);
if (result == NULL){
const char * message= "Could not create result ";
PyErr_SetString(PyExc_RuntimeError , message);
return NULL;
}
/* Do the calculation. */
for ( i=0; i< x_len; i++) {
double x_value = *(double *)(x->data + i*x->strides[0]);
double y_value = *(double *)(y->data + i*y->strides[0]);
double *result_value = (double *)(result->data +
i*result->strides[0]);
*result_value = (*model)(x_value, y_value);
}
return PyArray_Return(result);
}else{
PyErr_SetString(CMultiShellModelError,
"CMultiShellModel.evaluateTwoDimXY couldn't run.");
return NULL;
}
}
/**
* evalDistribution function evaluate a model function with input vector
* @param args: input q as vector or [qx, qy] where qx, qy are vectors
*
*/
static PyObject * evalDistribution(CMultiShellModel *self, PyObject *args){
PyObject *qx, *qy;
PyArrayObject * pars;
int npars ,mpars;
// Get parameters
// Reader parameter dictionary
self->model->core_sld = PyFloat_AsDouble( PyDict_GetItemString(self->params, "core_sld") );
self->model->core_radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "core_radius") );
self->model->n_pairs = PyFloat_AsDouble( PyDict_GetItemString(self->params, "n_pairs") );
self->model->w_thickness = PyFloat_AsDouble( PyDict_GetItemString(self->params, "w_thickness") );
self->model->s_thickness = PyFloat_AsDouble( PyDict_GetItemString(self->params, "s_thickness") );
self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") );
self->model->background = PyFloat_AsDouble( PyDict_GetItemString(self->params, "background") );
self->model->shell_sld = PyFloat_AsDouble( PyDict_GetItemString(self->params, "shell_sld") );
// Read in dispersion parameters
PyObject* disp_dict;
DispersionVisitor* visitor = new DispersionVisitor();
disp_dict = PyDict_GetItemString(self->dispersion, "core_radius");
self->model->core_radius.dispersion->accept_as_destination(visitor, self->model->core_radius.dispersion, disp_dict);
disp_dict = PyDict_GetItemString(self->dispersion, "s_thickness");
self->model->s_thickness.dispersion->accept_as_destination(visitor, self->model->s_thickness.dispersion, disp_dict);
disp_dict = PyDict_GetItemString(self->dispersion, "w_thickness");
self->model->w_thickness.dispersion->accept_as_destination(visitor, self->model->w_thickness.dispersion, disp_dict);
// Get input and determine whether we have to supply a 1D or 2D return value.
if ( !PyArg_ParseTuple(args,"O",&pars) ) {
PyErr_SetString(CMultiShellModelError,
"CMultiShellModel.evalDistribution expects a q value.");
return NULL;
}
// Check params
if(PyArray_Check(pars)==1) {
// Length of list should 1 or 2
npars = pars->nd;
if(npars==1) {
// input is a numpy array
if (PyArray_Check(pars)) {
return evaluateOneDim(self->model, (PyArrayObject*)pars);
}
}else{
PyErr_SetString(CMultiShellModelError,
"CMultiShellModel.evalDistribution expect numpy array of one dimension.");
return NULL;
}
}else if( PyList_Check(pars)==1) {
// Length of list should be 2 for I(qx,qy)
mpars = PyList_GET_SIZE(pars);
if(mpars!=2) {
PyErr_SetString(CMultiShellModelError,
"CMultiShellModel.evalDistribution expects a list of dimension 2.");
return NULL;
}
qx = PyList_GET_ITEM(pars,0);
qy = PyList_GET_ITEM(pars,1);
if (PyArray_Check(qx) && PyArray_Check(qy)) {
return evaluateTwoDimXY(self->model, (PyArrayObject*)qx,
(PyArrayObject*)qy);
}else{
PyErr_SetString(CMultiShellModelError,
"CMultiShellModel.evalDistribution expect 2 numpy arrays in list.");
return NULL;
}
}
PyErr_SetString(CMultiShellModelError,
"CMultiShellModel.evalDistribution couln't be run.");
return NULL;
}
/**
* Function to call to evaluate model
* @param args: input q or [q,phi]
* @return: function value
*/
static PyObject * run(CMultiShellModel *self, PyObject *args) {
double q_value, phi_value;
PyObject* pars;
int npars;
// Get parameters
// Reader parameter dictionary
self->model->core_sld = PyFloat_AsDouble( PyDict_GetItemString(self->params, "core_sld") );
self->model->core_radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "core_radius") );
self->model->n_pairs = PyFloat_AsDouble( PyDict_GetItemString(self->params, "n_pairs") );
self->model->w_thickness = PyFloat_AsDouble( PyDict_GetItemString(self->params, "w_thickness") );
self->model->s_thickness = PyFloat_AsDouble( PyDict_GetItemString(self->params, "s_thickness") );
self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") );
self->model->background = PyFloat_AsDouble( PyDict_GetItemString(self->params, "background") );
self->model->shell_sld = PyFloat_AsDouble( PyDict_GetItemString(self->params, "shell_sld") );
// Read in dispersion parameters
PyObject* disp_dict;
DispersionVisitor* visitor = new DispersionVisitor();
disp_dict = PyDict_GetItemString(self->dispersion, "core_radius");
self->model->core_radius.dispersion->accept_as_destination(visitor, self->model->core_radius.dispersion, disp_dict);
disp_dict = PyDict_GetItemString(self->dispersion, "s_thickness");
self->model->s_thickness.dispersion->accept_as_destination(visitor, self->model->s_thickness.dispersion, disp_dict);
disp_dict = PyDict_GetItemString(self->dispersion, "w_thickness");
self->model->w_thickness.dispersion->accept_as_destination(visitor, self->model->w_thickness.dispersion, disp_dict);
// Get input and determine whether we have to supply a 1D or 2D return value.
if ( !PyArg_ParseTuple(args,"O",&pars) ) {
PyErr_SetString(CMultiShellModelError,
"CMultiShellModel.run expects a q value.");
return NULL;
}
// Check params
if( PyList_Check(pars)==1) {
// Length of list should be 2 for I(q,phi)
npars = PyList_GET_SIZE(pars);
if(npars!=2) {
PyErr_SetString(CMultiShellModelError,
"CMultiShellModel.run expects a double or a list of dimension 2.");
return NULL;
}
// We have a vector q, get the q and phi values at which
// to evaluate I(q,phi)
q_value = CMultiShellModel_readDouble(PyList_GET_ITEM(pars,0));
phi_value = CMultiShellModel_readDouble(PyList_GET_ITEM(pars,1));
// Skip zero
if (q_value==0) {
return Py_BuildValue("d",0.0);
}
return Py_BuildValue("d",(*(self->model)).evaluate_rphi(q_value,phi_value));
} else {
// We have a scalar q, we will evaluate I(q)
q_value = CMultiShellModel_readDouble(pars);
return Py_BuildValue("d",(*(self->model))(q_value));
}
}
/**
* Function to call to calculate_ER
* @return: effective radius value
*/
static PyObject * calculate_ER(CMultiShellModel *self) {
PyObject* pars;
int npars;
// Get parameters
// Reader parameter dictionary
self->model->core_sld = PyFloat_AsDouble( PyDict_GetItemString(self->params, "core_sld") );
self->model->core_radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "core_radius") );
self->model->n_pairs = PyFloat_AsDouble( PyDict_GetItemString(self->params, "n_pairs") );
self->model->w_thickness = PyFloat_AsDouble( PyDict_GetItemString(self->params, "w_thickness") );
self->model->s_thickness = PyFloat_AsDouble( PyDict_GetItemString(self->params, "s_thickness") );
self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") );
self->model->background = PyFloat_AsDouble( PyDict_GetItemString(self->params, "background") );
self->model->shell_sld = PyFloat_AsDouble( PyDict_GetItemString(self->params, "shell_sld") );
// Read in dispersion parameters
PyObject* disp_dict;
DispersionVisitor* visitor = new DispersionVisitor();
disp_dict = PyDict_GetItemString(self->dispersion, "core_radius");
self->model->core_radius.dispersion->accept_as_destination(visitor, self->model->core_radius.dispersion, disp_dict);
disp_dict = PyDict_GetItemString(self->dispersion, "s_thickness");
self->model->s_thickness.dispersion->accept_as_destination(visitor, self->model->s_thickness.dispersion, disp_dict);
disp_dict = PyDict_GetItemString(self->dispersion, "w_thickness");
self->model->w_thickness.dispersion->accept_as_destination(visitor, self->model->w_thickness.dispersion, disp_dict);
return Py_BuildValue("d",(*(self->model)).calculate_ER());
}
/**
* Function to call to evaluate model in cartesian coordinates
* @param args: input q or [qx, qy]]
* @return: function value
*/
static PyObject * runXY(CMultiShellModel *self, PyObject *args) {
double qx_value, qy_value;
PyObject* pars;
int npars;
// Get parameters
// Reader parameter dictionary
self->model->core_sld = PyFloat_AsDouble( PyDict_GetItemString(self->params, "core_sld") );
self->model->core_radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "core_radius") );
self->model->n_pairs = PyFloat_AsDouble( PyDict_GetItemString(self->params, "n_pairs") );
self->model->w_thickness = PyFloat_AsDouble( PyDict_GetItemString(self->params, "w_thickness") );
self->model->s_thickness = PyFloat_AsDouble( PyDict_GetItemString(self->params, "s_thickness") );
self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") );
self->model->background = PyFloat_AsDouble( PyDict_GetItemString(self->params, "background") );
self->model->shell_sld = PyFloat_AsDouble( PyDict_GetItemString(self->params, "shell_sld") );
// Read in dispersion parameters
PyObject* disp_dict;
DispersionVisitor* visitor = new DispersionVisitor();
disp_dict = PyDict_GetItemString(self->dispersion, "core_radius");
self->model->core_radius.dispersion->accept_as_destination(visitor, self->model->core_radius.dispersion, disp_dict);
disp_dict = PyDict_GetItemString(self->dispersion, "s_thickness");
self->model->s_thickness.dispersion->accept_as_destination(visitor, self->model->s_thickness.dispersion, disp_dict);
disp_dict = PyDict_GetItemString(self->dispersion, "w_thickness");
self->model->w_thickness.dispersion->accept_as_destination(visitor, self->model->w_thickness.dispersion, disp_dict);
// Get input and determine whether we have to supply a 1D or 2D return value.
if ( !PyArg_ParseTuple(args,"O",&pars) ) {
PyErr_SetString(CMultiShellModelError,
"CMultiShellModel.run expects a q value.");
return NULL;
}
// Check params
if( PyList_Check(pars)==1) {
// Length of list should be 2 for I(qx, qy))
npars = PyList_GET_SIZE(pars);
if(npars!=2) {
PyErr_SetString(CMultiShellModelError,
"CMultiShellModel.run expects a double or a list of dimension 2.");
return NULL;
}
// We have a vector q, get the qx and qy values at which
// to evaluate I(qx,qy)
qx_value = CMultiShellModel_readDouble(PyList_GET_ITEM(pars,0));
qy_value = CMultiShellModel_readDouble(PyList_GET_ITEM(pars,1));
return Py_BuildValue("d",(*(self->model))(qx_value,qy_value));
} else {
// We have a scalar q, we will evaluate I(q)
qx_value = CMultiShellModel_readDouble(pars);
return Py_BuildValue("d",(*(self->model))(qx_value));
}
}
static PyObject * reset(CMultiShellModel *self, PyObject *args) {
return Py_BuildValue("d",0.0);
}
static PyObject * set_dispersion(CMultiShellModel *self, PyObject *args) {
PyObject * disp;
const char * par_name;
if ( !PyArg_ParseTuple(args,"sO", &par_name, &disp) ) {
PyErr_SetString(CMultiShellModelError,
"CMultiShellModel.set_dispersion expects a DispersionModel object.");
return NULL;
}
void *temp = PyCObject_AsVoidPtr(disp);
DispersionModel * dispersion = static_cast<DispersionModel *>(temp);
// Ugliness necessary to go from python to C
// TODO: refactor this
if (!strcmp(par_name, "core_radius")) {
self->model->core_radius.dispersion = dispersion;
} else if (!strcmp(par_name, "s_thickness")) {
self->model->s_thickness.dispersion = dispersion;
} else if (!strcmp(par_name, "w_thickness")) {
self->model->w_thickness.dispersion = dispersion;
} else {
PyErr_SetString(CMultiShellModelError,
"CMultiShellModel.set_dispersion expects a valid parameter name.");
return NULL;
}
DispersionVisitor* visitor = new DispersionVisitor();
PyObject * disp_dict = PyDict_New();
dispersion->accept_as_source(visitor, dispersion, disp_dict);
PyDict_SetItemString(self->dispersion, par_name, disp_dict);
return Py_BuildValue("i",1);
}
static PyMethodDef CMultiShellModel_methods[] = {
{"run", (PyCFunction)run , METH_VARARGS,
"Evaluate the model at a given Q or Q, phi"},
{"runXY", (PyCFunction)runXY , METH_VARARGS,
"Evaluate the model at a given Q or Qx, Qy"},
{"calculate_ER", (PyCFunction)calculate_ER , METH_VARARGS,
"Evaluate the model at a given Q or Q, phi"},
{"evalDistribution", (PyCFunction)evalDistribution , METH_VARARGS,
"Evaluate the model at a given Q or Qx, Qy vector "},
{"reset", (PyCFunction)reset , METH_VARARGS,
"Reset pair correlation"},
{"set_dispersion", (PyCFunction)set_dispersion , METH_VARARGS,
"Set the dispersion model for a given parameter"},
{NULL}
};
static PyTypeObject CMultiShellModelType = {
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"CMultiShellModel", /*tp_name*/
sizeof(CMultiShellModel), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)CMultiShellModel_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
"CMultiShellModel objects", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
CMultiShellModel_methods, /* tp_methods */
CMultiShellModel_members, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)CMultiShellModel_init, /* tp_init */
0, /* tp_alloc */
CMultiShellModel_new, /* tp_new */
};
//static PyMethodDef module_methods[] = {
// {NULL}
//};
/**
* Function used to add the model class to a module
* @param module: module to add the class to
*/
void addCMultiShellModel(PyObject *module) {
PyObject *d;
if (PyType_Ready(&CMultiShellModelType) < 0)
return;
Py_INCREF(&CMultiShellModelType);
PyModule_AddObject(module, "CMultiShellModel", (PyObject *)&CMultiShellModelType);
d = PyModule_GetDict(module);
CMultiShellModelError = PyErr_NewException("CMultiShellModel.error", NULL, NULL);
PyDict_SetItemString(d, "CMultiShellModelError", CMultiShellModelError);
}
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
23
],
[
26,
28
],
[
30,
91
],
[
100,
105
],
[
112,
148
],
[
179,
179
],
[
200,
200
],
[
202,
202
],
[
301,
304
],
[
306,
332
],
[
337,
373
],
[
403,
403
],
[
408,
433
],
[
438,
494
],
[
499,
517
],
[
523,
572
],
[
576,
594
]
],
[
[
24,
25
],
[
29,
29
],
[
92,
99
],
[
106,
111
],
[
149,
178
],
[
180,
199
],
[
201,
201
],
[
203,
300
],
[
305,
305
],
[
333,
336
],
[
374,
402
],
[
404,
407
],
[
434,
437
],
[
495,
498
],
[
518,
522
],
[
573,
575
]
]
]
|
9a5a8cc58e22c76e4eb2fa279afe04b9363c60ed | 6ad58793dd1f859c10d18356c731b54f935c5e9e | /stdafx.cpp | cc82840b5a5af19534bdc3db276c0d1229d9ec2d | []
| no_license | ntchris/kittybookportable | 83f2cf2fbc2cd1243b585f85fb6bc5dd285aa227 | 933a5b096524c24390c32c654ce8624ee35d3835 | refs/heads/master | 2021-01-10T05:49:32.035999 | 2009-06-12T08:50:21 | 2009-06-12T08:50:21 | 45,051,534 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 293 | cpp | // stdafx.cpp : source file that includes just the standard includes
// cntest.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
| [
"ntchris0623@05aa5984-5704-11de-9010-b74abb91d602"
]
| [
[
[
1,
8
]
]
]
|
4a17a5cea0ebfa25e8be3f40c71f17c52b07644a | 0813282678cb6bb52cd0001a760cfbc24663cfca | /Hashtable.h | 11d83ae573fd389be1ea4cb49cc0a11bd5a66da0 | []
| no_license | mannyzhou5/scbuildorder | e3850a86baaa33d1c549c7b89ddab7738b79b3c0 | 2396293ee483e40495590782b652320db8adf530 | refs/heads/master | 2020-04-29T01:01:04.504099 | 2011-04-12T10:00:54 | 2011-04-12T10:00:54 | 33,047,073 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,925 | h | #pragma once
template <typename Key, typename KeyRef, typename Val, typename ValRef, typename Compare = Equal<KeyRef>>
class CHashtable;
#include "MemoryPool.h"
#include "LinkedList.h"
template <typename T>
unsigned long HashKey(T key)
{
return (unsigned long)key;
}
template <typename T>
struct Equal
{
public:
bool operator()(T a, T b) const
{
return a == b;
}
};
size_t GetNextPrimeSize(size_t nDesiredSize);
template <typename Key, typename KeyRef, typename Val, typename ValRef>
class CHashtableNode : public CMemPoolNode<CHashtableNode<Key, KeyRef, Val, ValRef>, 100000, 1.0>
{
protected:
CHashtableNode *m_pNextNode;
public:
Key m_key;
Val m_val;
CHashtableNode(KeyRef key, ValRef val, CHashtableNode *pNextNode = NULL) : m_key(key), m_val(val), m_pNextNode(pNextNode) {}
~CHashtableNode() {}
CHashtableNode *GetNext() { return m_pNextNode; }
const CHashtableNode *GetNext() const { return m_pNextNode; }
void SetNext(CHashtableNode *pNode) { m_pNextNode = pNode; }
void operator=(const CHashtableNode<Key, KeyRef, Val, ValRef> &node) { m_key = node.m_key; m_val = node.m_val; }
operator KeyRef() { return m_key; }
};
template <typename Key, typename KeyRef, typename Val, typename ValRef, typename Compare>
class CHashtable : public CMemPoolNode<CHashtable<Key, KeyRef, Val, ValRef, Compare>, 10>
{
private:
typedef CHashtableNode<Key, KeyRef, Val, ValRef> Node;
Compare m_comp;
float m_fGrowThreshold;
float m_fGrowFactor;
size_t m_nSize;
size_t m_nCount;
Node **m_arrHashtable;
Node *FindKey(size_t nIndex, KeyRef key) const
{
Node *pNode = m_arrHashtable[nIndex];
for(; pNode != NULL && !m_comp(*pNode, key); pNode = pNode->GetNext());
return pNode;
}
public:
CHashtable(size_t nInitialSize = 1009, const Compare &comp = Compare(), float fGrowThreshold = CHRONOBOOST_GAIN, float fGrowFactor = 2.0);
~CHashtable();
void SetAt(KeyRef key, ValRef val);
bool ContainsKey(KeyRef key) const;
bool Lookup(KeyRef key, Val &val) const;
const Node *GetIndex(size_t nIndex) const
{
if(nIndex >= m_nSize)
return NULL;
else
return m_arrHashtable[nIndex];
}
void Grow();
void Reallocate(size_t nSize);
size_t Size() const { return m_nSize; }
void GetStatistics(size_t &nSize, size_t &nCount, size_t &nUsed, size_t &nMaxCollision) const;
size_t CalculateMemoryUsage() const { return m_nSize * sizeof(Node *); }
};
template <typename Key, typename KeyRef, typename Val, typename ValRef, typename Compare>
CHashtable<Key, KeyRef, Val, ValRef, Compare>::CHashtable(size_t nInitialSize /* = 1009 */, const Compare &comp /* = Compare() */, float fGrowThreshold /* = 0.5 */, float fGrowFactor /* = 2.0 */)
: m_nSize(0)
, m_nCount(0)
, m_comp(comp)
, m_fGrowThreshold(fGrowThreshold)
, m_fGrowFactor(fGrowFactor)
, m_arrHashtable(NULL)
{
Reallocate(nInitialSize);
}
template <typename Key, typename KeyRef, typename Val, typename ValRef, typename Compare>
CHashtable<Key, KeyRef, Val, ValRef, Compare>::~CHashtable()
{
for(size_t i=0; i < m_nSize; i++)
{
while(m_arrHashtable[i] != NULL)
{
Node *pNode = m_arrHashtable[i];
m_arrHashtable[i] = pNode->GetNext();
delete pNode;
}
}
delete[] m_arrHashtable;
}
template <typename Key, typename KeyRef, typename Val, typename ValRef, typename Compare>
void CHashtable<Key, KeyRef, Val, ValRef, Compare>::Reallocate(size_t nSize)
{
Node **arrHashtable = new Node *[nSize];
for(size_t i=0; i < nSize; i++)
arrHashtable[i] = NULL;
for(size_t i=0; i < m_nSize; i++)
{
while(m_arrHashtable[i] != NULL)
{
Node *pNode = m_arrHashtable[i];
m_arrHashtable[i] = pNode->GetNext();
size_t nIndex = HashKey<Key>(pNode->m_key) % nSize;
pNode->SetNext(arrHashtable[nIndex]);
arrHashtable[nIndex] = pNode;
}
}
delete[] m_arrHashtable;
m_arrHashtable = arrHashtable;;
m_nSize = nSize;
}
template <typename Key, typename KeyRef, typename Val, typename ValRef, typename Compare>
void CHashtable<Key, KeyRef, Val, ValRef, Compare>::Grow()
{
Reallocate(GetNextPrimeSize((size_t)(m_fGrowFactor * m_nSize)));
}
template <typename Key, typename KeyRef, typename Val, typename ValRef, typename Compare>
void CHashtable<Key, KeyRef, Val, ValRef, Compare>::SetAt(KeyRef key, ValRef val)
{
size_t nIndex = HashKey<KeyRef>(key) % m_nSize;
Node *pNode = FindKey(nIndex, key);
if(pNode)
pNode->m_val = val;
else
{
if((float)m_nCount / (float)m_nSize > m_fGrowThreshold)
Grow();
m_nCount++;
m_arrHashtable[nIndex] = new Node(key, val, m_arrHashtable[nIndex]);
}
}
template <typename Key, typename KeyRef, typename Val, typename ValRef, typename Compare>
bool CHashtable<Key, KeyRef, Val, ValRef, Compare>::ContainsKey(KeyRef key) const
{
size_t nIndex = HashKey<KeyRef>(key) % m_nSize;
return (NULL != FindKey(nIndex, key));
}
template <typename Key, typename KeyRef, typename Val, typename ValRef, typename Compare>
bool CHashtable<Key, KeyRef, Val, ValRef, Compare>::Lookup(KeyRef key, Val &val) const
{
size_t nIndex = HashKey<KeyRef>(key) % m_nSize;
Node *pNode = FindKey(nIndex, key);
if(!pNode)
return false;
else
{
val = pNode->m_val;
return true;
}
}
template <typename Key, typename KeyRef, typename Val, typename ValRef, typename Compare>
void CHashtable<Key, KeyRef, Val, ValRef, Compare>::GetStatistics(size_t &nSize, size_t &nCount, size_t &nUsed, size_t &nMaxCollision) const
{
nCount = m_nCount;
nSize = m_nSize;
nUsed = 0;
nMaxCollision = 0;
for(size_t i=0; i < m_nSize; i++)
{
if(m_arrHashtable[i])
{
size_t nMax = 0;
Node *pNode = m_arrHashtable[i];
while(pNode->GetNext())
{
nMax++;
pNode = pNode->GetNext();
}
if(nMax > nMaxCollision)
nMaxCollision = nMax;
nUsed++;
}
}
}
| [
"[email protected]@a0245358-5b9e-171e-63e1-2316ddff5996"
]
| [
[
[
1,
214
]
]
]
|
eac78850d4e8fcd90d5de503607459e4951a1924 | 0429e2b2a1a09254b5182e15835da188f7d44a3d | /tags/v05/tests/customerManagement/tcustomerManagement.h | e6457f161c6d021cda461f87a819a8e66c93302b | []
| no_license | TheolZacharopoulos/tl2hotel | 0b5af731aa022b04fc7b894b4fad6ce0b1121744 | 87ff9c75250d702c49d62f43e494cf549ea700b7 | refs/heads/master | 2020-03-30T05:41:55.498410 | 2011-04-25T22:24:44 | 2011-04-25T22:24:44 | 42,362,513 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,207 | h | /** @file tcustomerManagement.h
* @brief CustomerManagement Unit Test Header
* @author Efstathios Xatzikiriakidis
*
* This is the unit test for the "CustomerManagement" class.
*/
#if !defined (T_CUSTOMER_MANAGEMENT_H)
#define T_CUSTOMER_MANAGEMENT_H
#include <QtTest>
#include "customerManagement.h"
/** @class TCustomerManagement
* @brief CustomerManagement Test Class
* @author Efstathios Xatzikiriakidis
*
* This is the test class for the "CustomerManagement" class.
*/
class TCustomerManagement : public QObject
{
Q_OBJECT
private slots:
/** Fetch All Customers Test Method
* @brief This method tries to test the "fetchAllCustomers" method of "CustomerManagement" class.
* @author Efstathios Xatzikiriakidis
*/
void testFetchAllCustomers ();
/** Search Customer By Value Test Method
* @brief This method tries to test the "searchCustomerByValue" method of "CustomerManagement" class.
* @author Efstathios Xatzikiriakidis
*/
void testSearchCustomerByValue ();
/** New Customer Test Method
* @brief This method tests the "newCustomer" method of the "CustomerManagement" class.
* @author Efstathios Xatzikiriakidis
*/
void testNewCustomer ();
/** Edit Customer Test Method
* @brief This method tests the "editCustomer" method of the "CustomerManagement" class.
* @author Efstathios Xatzikiriakidis
*/
void testEditCustomer ();
/** Delete Customer Test Method
* @brief This method tests the "deleteCustomer" method of the "CustomerManagement" class.
* @author Efstathios Xatzikiriakidis
*/
void testDeleteCustomer ();
/** Fetch Customer Test Method
* @brief This method tests the "fetchCustomer" method of the "CustomerManagement" class.
* @author Efstathios Xatzikiriakidis
*/
void testFetchCustomer ();
/** Customer Check In Data Test Method
* @brief This method tests the "checkInData" method of the "CustomerManagement" class.
* @author Efstathios Xatzikiriakidis
*/
void testCheckInData ();
};
#endif // T_CUSTOMER_MANAGEMENT_H | [
"delis89@fb7cbe1a-da42-76e9-2caa-fedf319af631"
]
| [
[
[
1,
69
]
]
]
|
5cf159981c1f7d9f90cd47e52e05cd78a38754ca | ad85dfd8765f528fd5815d94acde96e28e210a43 | /trunk/src/FpsCounter.cpp | 167f6765cafe488743dd7da9291973b8ae6eb2d9 | []
| no_license | BackupTheBerlios/openlayer-svn | c53dcdd84b74fd4687c919642e6ccef3dd4bba79 | 3086e76972e6674c9b40282bb7028acb031d0593 | refs/heads/master | 2021-01-01T19:25:13.382956 | 2007-07-18T17:09:55 | 2007-07-18T17:09:55 | 40,823,139 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,373 | cpp | #include "FpsCounter.hpp"
#include "Includes.hpp"
using namespace ol;
// CONSTANTS //
static const int MS_PER_TICK = 1;
static const int FRAMES_PER_CHECK = 30;
// STATIC CLASS VARIABLES //
float FpsCounter::defaultFps = 60.0;
volatile int FpsCounter::timer = 0;
int FpsCounter::frameCount = 0;
float FpsCounter::fps = 0.0;
float FpsCounter::deltaTime = 0.0;
bool FpsCounter::paused = false;
int FpsCounter::pausedTimer = 0;
int FpsCounter::framesPerCheck = 30;
int FpsCounter::normalFPC = 50;
int FpsCounter::quickFPC = 10;
bool FpsCounter::useAdvanced = true;
float FpsCounter::actionLimit = 0.3;
// GENERAL FUNCTIONS //
void FpsCounter::
SetNumOfAveragedFrames( int averagedFrames ) {
if( averagedFrames == AUTO ) {
useAdvanced = true;
framesPerCheck = 30;
}
else {
useAdvanced = false;
framesPerCheck = averagedFrames;
}
}
void FpsCounter::
Start( float defaultFps ) {
FpsCounter::defaultFps = defaultFps;
timer = 0;
frameCount = 0;
frameCount = 0;
framesPerCheck = normalFPC;
paused = false;
install_int( FpsCounter::Tick, MS_PER_TICK );
}
float FpsCounter::
NewFrameStarted() {
if( !paused && ++FpsCounter::frameCount > framesPerCheck && FpsCounter::timer > 0 ) {
float lastFps = fps;
fps = 1000.0 * float(FpsCounter::frameCount)/float(FpsCounter::timer * MS_PER_TICK);
if( useAdvanced ) {
float ratio = fps/lastFps;
if( 1.0 - ratio > actionLimit || 1.0 - 1.0/ratio > actionLimit ) {
framesPerCheck /= 2;
if( framesPerCheck < quickFPC )
framesPerCheck = quickFPC;
}
else {
framesPerCheck *= 2;
if( framesPerCheck > normalFPC )
framesPerCheck = normalFPC;
}
}
frameCount = 0;
timer = 0;
deltaTime = defaultFps/fps;
}
return deltaTime;
}
void FpsCounter::
Tick() {
timer++;
}
float FpsCounter::
GetDeltaTime() {
return deltaTime;
}
float FpsCounter::
GetFps() {
return fps;
}
void FpsCounter::
Pause() {
paused = true;
pausedTimer = timer;
}
void FpsCounter::
Resume() {
paused = false;
timer = pausedTimer;
}
| [
"bradeeoh@9f4572f3-6e0d-0410-ba3b-903ab02ac46b"
]
| [
[
[
1,
131
]
]
]
|
d1f29f9052c01ddb4447042cd982bff6a813394f | fd4f996b64c1994c5e6d8c8ff78a2549255aacb7 | / nicolinorochetaller --username adrianachelotti/trunk/tp3_beta/eTejo/Servidor.cpp | 4d66dedbe9f490b777df51f3c993427e1a3d9406 | []
| no_license | adrianachelotti/nicolinorochetaller | 026f32476e41cdc5ac5c621c483d70af7b397fb0 | d3215dfdfa70b6226b3616c78121f36606135a5f | refs/heads/master | 2021-01-10T19:45:15.378823 | 2009-08-05T14:54:42 | 2009-08-05T14:54:42 | 32,193,619 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 137 | cpp | #include "Servidor.h"
Servidor::Servidor()
{
}
Servidor::~Servidor()
{
}
void Servidor::updatePosiciones()
{
}
| [
"[email protected]@0b808588-0f27-11de-aab3-ff745001d230"
]
| [
[
[
1,
18
]
]
]
|
6ad4a9ca2bafeaed5dd2465b7bb39e1e2aa32f97 | adb2ebb4b7f74f62228c7dd9ca1441ee95297243 | /UI/FeedbackForm.h | 2f04bb8227da5f88d080d47fac3becd201db91eb | []
| no_license | BackupTheBerlios/blazefilesearch-svn | 5984480677ad0a7ae64c082e16dde4e7b2394c2c | b910de6af6f1ae8e018f06a484a8b6d9c4c2f280 | refs/heads/master | 2021-01-22T17:53:29.216195 | 2005-03-05T05:17:38 | 2005-03-05T05:17:38 | 40,608,509 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,412 | h | #pragma once
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
namespace UI
{
/// <summary>
/// Summary for FeedbackForm
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
/// </summary>
public __gc class FeedbackForm : public System::Windows::Forms::Form
{
public:
FeedbackForm(void)
{
InitializeComponent();
}
protected:
void Dispose(Boolean disposing)
{
if (disposing && components)
{
components->Dispose();
}
__super::Dispose(disposing);
}
private: System::Windows::Forms::Label * lblReasons;
private: System::Windows::Forms::TextBox * txtName;
private: System::Windows::Forms::Label * lblName;
private: System::Windows::Forms::TextBox * txtSubject;
private: System::Windows::Forms::Label * lblSubject;
private: System::Windows::Forms::Label * lblMessage;
private: System::Windows::Forms::TextBox * txtMessage;
private: System::Windows::Forms::Button * cmdSubmit;
private: System::Windows::Forms::Button * cmdCancel;
private:
/// <summary>
/// Required designer variable.
/// </summary>
System::ComponentModel::Container* components;
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
void InitializeComponent(void)
{
this->lblReasons = new System::Windows::Forms::Label();
this->lblName = new System::Windows::Forms::Label();
this->txtName = new System::Windows::Forms::TextBox();
this->txtSubject = new System::Windows::Forms::TextBox();
this->lblSubject = new System::Windows::Forms::Label();
this->lblMessage = new System::Windows::Forms::Label();
this->txtMessage = new System::Windows::Forms::TextBox();
this->cmdCancel = new System::Windows::Forms::Button();
this->cmdSubmit = new System::Windows::Forms::Button();
this->SuspendLayout();
//
// lblReasons
//
this->lblReasons->BackColor = System::Drawing::SystemColors::Control;
this->lblReasons->FlatStyle = System::Windows::Forms::FlatStyle::System;
this->lblReasons->Location = System::Drawing::Point(8, 8);
this->lblReasons->Name = S"lblReasons";
this->lblReasons->Size = System::Drawing::Size(272, 56);
this->lblReasons->TabIndex = 0;
this->lblReasons->Text = S"Why don\'t you send us feedback about what you think about Blaze\?\nAny suggestions\?"
S" Bug reports\? Fill out this form to tell us about what you think!";
//
// lblName
//
this->lblName->AutoSize = true;
this->lblName->BackColor = System::Drawing::SystemColors::Control;
this->lblName->FlatStyle = System::Windows::Forms::FlatStyle::System;
this->lblName->Location = System::Drawing::Point(8, 72);
this->lblName->Name = S"lblName";
this->lblName->Size = System::Drawing::Size(88, 16);
this->lblName->TabIndex = 1;
this->lblName->Text = S"Name (optional):";
//
// txtName
//
this->txtName->BorderStyle = System::Windows::Forms::BorderStyle::FixedSingle;
this->txtName->Location = System::Drawing::Point(96, 72);
this->txtName->MaxLength = 20;
this->txtName->Name = S"txtName";
this->txtName->Size = System::Drawing::Size(168, 20);
this->txtName->TabIndex = 2;
this->txtName->Text = S"";
//
// txtSubject
//
this->txtSubject->BorderStyle = System::Windows::Forms::BorderStyle::FixedSingle;
this->txtSubject->Location = System::Drawing::Point(96, 104);
this->txtSubject->MaxLength = 20;
this->txtSubject->Name = S"txtSubject";
this->txtSubject->Size = System::Drawing::Size(168, 20);
this->txtSubject->TabIndex = 5;
this->txtSubject->Text = S"";
//
// lblSubject
//
this->lblSubject->AutoSize = true;
this->lblSubject->FlatStyle = System::Windows::Forms::FlatStyle::System;
this->lblSubject->Location = System::Drawing::Point(48, 104);
this->lblSubject->Name = S"lblSubject";
this->lblSubject->Size = System::Drawing::Size(45, 16);
this->lblSubject->TabIndex = 6;
this->lblSubject->Text = S"Subject:";
//
// lblMessage
//
this->lblMessage->AutoSize = true;
this->lblMessage->FlatStyle = System::Windows::Forms::FlatStyle::System;
this->lblMessage->Location = System::Drawing::Point(40, 136);
this->lblMessage->Name = S"lblMessage";
this->lblMessage->Size = System::Drawing::Size(53, 16);
this->lblMessage->TabIndex = 7;
this->lblMessage->Text = S"Message:";
//
// txtMessage
//
this->txtMessage->BorderStyle = System::Windows::Forms::BorderStyle::FixedSingle;
this->txtMessage->Location = System::Drawing::Point(96, 136);
this->txtMessage->MaxLength = 20;
this->txtMessage->Multiline = true;
this->txtMessage->Name = S"txtMessage";
this->txtMessage->Size = System::Drawing::Size(168, 152);
this->txtMessage->TabIndex = 8;
this->txtMessage->Text = S"";
//
// cmdCancel
//
this->cmdCancel->DialogResult = System::Windows::Forms::DialogResult::Cancel;
this->cmdCancel->FlatStyle = System::Windows::Forms::FlatStyle::System;
this->cmdCancel->Location = System::Drawing::Point(16, 296);
this->cmdCancel->Name = S"cmdCancel";
this->cmdCancel->Size = System::Drawing::Size(96, 23);
this->cmdCancel->TabIndex = 9;
this->cmdCancel->Text = S"Cancel";
this->cmdCancel->Click += new System::EventHandler(this, cmdCancel_Click);
//
// cmdSubmit
//
this->cmdSubmit->FlatStyle = System::Windows::Forms::FlatStyle::System;
this->cmdSubmit->Location = System::Drawing::Point(160, 296);
this->cmdSubmit->Name = S"cmdSubmit";
this->cmdSubmit->Size = System::Drawing::Size(96, 23);
this->cmdSubmit->TabIndex = 10;
this->cmdSubmit->Text = S"Submit";
this->cmdSubmit->Click += new System::EventHandler(this, cmdSubmit_Click);
//
// FeedbackForm
//
this->AutoScaleBaseSize = System::Drawing::Size(5, 13);
this->BackColor = System::Drawing::SystemColors::Control;
this->CancelButton = this->cmdCancel;
this->ClientSize = System::Drawing::Size(277, 327);
this->Controls->Add(this->cmdSubmit);
this->Controls->Add(this->cmdCancel);
this->Controls->Add(this->txtMessage);
this->Controls->Add(this->lblMessage);
this->Controls->Add(this->lblSubject);
this->Controls->Add(this->txtSubject);
this->Controls->Add(this->txtName);
this->Controls->Add(this->lblName);
this->Controls->Add(this->lblReasons);
this->FormBorderStyle = System::Windows::Forms::FormBorderStyle::FixedSingle;
this->MaximizeBox = false;
this->MaximumSize = System::Drawing::Size(283, 359);
this->MinimizeBox = false;
this->MinimumSize = System::Drawing::Size(283, 359);
this->Name = S"FeedbackForm";
this->ShowInTaskbar = false;
this->Text = S"Send Feedback";
this->ResumeLayout(false);
}
private: System::Void cmdClear_Click(System::Object * sender, System::EventArgs * e)
{
this->txtName->Text = String::Empty;
this->txtSubject->Text = String::Empty;
this->txtMessage->Text = String::Empty;
}
private: System::Void cmdSubmit_Click(System::Object * sender, System::EventArgs * e)
{
//MessageBox::Show("Don't do this yet!"); return System::Void;
// TODO: get some guy for the messages
// Compose the message
String *s = String::Concat(String::Concat(S"Name: ", this->txtName->Text,
S"\nSubject: ", this->txtSubject->Text), S"\nMessage: ", this->txtMessage->Text);
// Copy message to clipboard
Clipboard::SetDataObject(s);
// Tell them to email it to whoever
MessageBox::Show(this, S"Your message has been copied to the clipboard. Please email it to us at [email protected]. Thanks!",
"Blaze Feedback", MessageBoxButtons::OK, MessageBoxIcon::Information);
// Close the feedback form
this->Close();
}
private: System::Void cmdCancel_Click(System::Object * sender, System::EventArgs * e)
{
this->Close();
}
};
}
| [
"hyperfusion@8d202536-25f0-0310-b7fd-af1e855a3320"
]
| [
[
[
1,
229
]
]
]
|
f7352b9bed6116ff1aa51cbb64388cd848c98cc0 | 335783c9e5837a1b626073d1288b492f9f6b057f | /source/fbxcmd/daolib/Model/MMH/SPLA.h | 9cfd1799bcf490039c73f764f3f061fcbf60143f | [
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause"
]
| permissive | code-google-com/fbx4eclipse | 110766ee9760029d5017536847e9f3dc09e6ebd2 | cc494db4261d7d636f8c4d0313db3953b781e295 | refs/heads/master | 2016-09-08T01:55:57.195874 | 2009-12-03T20:35:48 | 2009-12-03T20:35:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,748 | h |
/**********************************************************************
*<
FILE: SPLA.h
DESCRIPTION: MMH File Format
HISTORY:
*> Copyright (c) 2009, All Rights Reserved.
**********************************************************************/
#pragma once
#include "MMH/MMHCommon.h"
#include "GFF/GFFField.h"
#include "GFF/GFFList.h"
#include "GFF/GFFStruct.h"
namespace DAO {
using namespace GFF;
namespace MMH {
///////////////////////////////////////////////////////////////////
class SPLA
{
protected:
GFFStructRef impl;
static ShortString type;
public:
SPLA(GFFStructRef owner);
static const ShortString& Type() { return type; }
const ShortString& get_type() const { return type; }
float get_nodeEmitterSplatparamsWidth() const;
void set_nodeEmitterSplatparamsWidth(float value);
float get_nodeEmitterSplatparamsHeight() const;
void set_nodeEmitterSplatparamsHeight(float value);
unsigned long get_nodeEmitterSplatparamsNumsamplesWidth() const;
void set_nodeEmitterSplatparamsNumsamplesWidth(unsigned long value);
unsigned long get_nodeEmitterSplatparamsNumsamplesHeight() const;
void set_nodeEmitterSplatparamsNumsamplesHeight(unsigned long value);
float get_nodeEmitterSplatparamsOrientationRange() const;
void set_nodeEmitterSplatparamsOrientationRange(float value);
float get_nodeEmitterSplatparamsLife() const;
void set_nodeEmitterSplatparamsLife(float value);
unsigned char get_nodeEmitterSplatparamsFlipbookType() const;
void set_nodeEmitterSplatparamsFlipbookType(unsigned char value);
float get_nodeEmitterSplatparamsFlipbookFramesPerSecond() const;
void set_nodeEmitterSplatparamsFlipbookFramesPerSecond(float value);
unsigned char get_nodeEmitterSplatparamsFlipbookRows() const;
void set_nodeEmitterSplatparamsFlipbookRows(unsigned char value);
unsigned char get_nodeEmitterSplatparamsFlipbookColumns() const;
void set_nodeEmitterSplatparamsFlipbookColumns(unsigned char value);
unsigned char get_nodeEmitterSplatparamsFlipbookRandomStartFrame() const;
void set_nodeEmitterSplatparamsFlipbookRandomStartFrame(unsigned char value);
Text get_nodeEmitterSplatparamsMaterialname() const;
void set_nodeEmitterSplatparamsMaterialname(const Text& value);
unsigned char get_nodeEmitterSplatparamsHoldLastFrame() const;
void set_nodeEmitterSplatparamsHoldLastFrame(unsigned char value);
Color4 get_nodeEmitterSplatparamsAgemapColorMultiplier() const;
void set_nodeEmitterSplatparamsAgemapColorMultiplier(Color4 value);
GFFListRef get_children() const;
};
typedef ValuePtr<SPLA> SPLAPtr;
typedef ValueRef<SPLA> SPLARef;
} //namespace MMH
} //namespace DAO
| [
"tazpn314@ccf8930c-dfc1-11de-9043-17b7bd24f792"
]
| [
[
[
1,
89
]
]
]
|
6d6272bc17cb00b1ce287081e4bfea6e7254fa81 | 909e422494d7c012c2bc89c79eabdceb53c721a5 | /icpcLibrary/BiGraphMatch_withWeight.cpp | bbba354497bd6d848cc7c261b25182f8cb22053e | []
| no_license | aviramagen/menglin-icpc-code-library | f14cc303a3fd05992a1a40b9bcd7a0b09657f21c | c8375f39ed13312f705fb42c20ce83f5194bd297 | refs/heads/master | 2021-01-10T14:00:32.605726 | 2011-12-03T11:39:50 | 2011-12-03T11:39:50 | 54,555,734 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,796 | cpp | /*
二分图最大权匹配
PKU2195
*/
#include <iostream>
#include <algorithm>
#include <memory.h>
#include <stdio.h>
using namespace std;
#define N 200
#define MAX 0
int dis[N][N];//存储边权,边权等于MAX表示不通
int homematch[N], personmatch[N]; //左边person集合,右边home集合
bool personset[N], homeset[N];
int person[N], home[N];
int homex[N], homey[N];
int personx[N], persony[N];
inline bool canmatch ( int p, int h )
{
return dis[p][h] == person[p] + home[h];
}
int max ( int a, int b )
{
return a > b ? a : b;
}
int min ( int a, int b )
{
return a < b ? a : b;
}
bool findtree ( int p, int n )
{
personset[p] = true;
int h;
for ( h = 0; h < n; h++ )
{
if ( canmatch ( p, h ) && !homeset[h] )
{
homeset[h] = true;
if ( homematch[h] == -1 || findtree ( homematch[h], n ) )
{
homematch[h] = p;
personmatch[p] = h;
return true;
}
}
}
return false;
}
void relabel ( int n )
{
int p, h, mind = 100000000;
for ( p = 0; p < n; p++ )
{
if ( personset[p] )
{
for ( h = 0; h < n; h++ )
{
if ( !homeset[h] )
{
mind = min ( mind, home[h] + person[p] - dis[p][h] );
}
}
}
}
for ( p = 0; p < n; p++ )
{
if ( personset[p] )
{
person[p] -= mind;
}
}
for ( h = 0; h < n; h++ )
{
if ( homeset[h] )
home[h] += mind;
}
}
bool maxmatch ( int n )
{
memset ( homematch, 0xff, sizeof ( int ) *n );
memset ( personmatch, 0xff, sizeof ( int ) *n );
int p;
for ( p = 0; p < n; p++ )
{
memset ( personset, false, sizeof ( bool ) *n );
memset ( homeset, false, sizeof ( bool ) *n );
while ( !findtree ( p, n ) )
{
relabel ( n );
memset ( personset, false, sizeof ( bool ) *n );
memset ( homeset, false, sizeof ( bool ) *n );
}
}
return true;
}
int mincost ( int n )
{
int p, h, maxd;
for ( p = 0; p < n; p++ )
{
maxd = 0;
for ( h = 0; h < n; h++ )
{
maxd = max ( maxd, dis[p][h] );
}
person[p] = maxd;
home[p] = 0;
}
maxmatch ( n ); //最大权匹配
maxd = 0;
for ( p = 0; p < n; p++ )
{
maxd += ( MAX - dis[p][personmatch[p]] );
}
return maxd;
}
int read ( int r, int c )
{
int pn = 0, hn = 0;
int i, j;
char line[N];
for ( i = 0; i < r; i++ )
{
scanf ( "%s", line );
for ( j = 0; j < c; j++ )
{
if ( line[j] == 'H' )
{
homex[hn] = j;
homey[hn] = i;
hn++;
}
else if ( line[j] == 'm' )
{
personx[pn] = j;
persony[pn] = i;
pn++;
}
}
}
for ( i = 0; i < pn; i++ )
{
for ( j = 0; j < hn; j++ )
{
dis[i][j] = abs ( personx[i] - homex[j] ) + abs ( persony[i] - homey[j] );
dis[i][j] = MAX - dis[i][j];
}
}
return pn;
}
int main()
{
int r, c, n;
while ( scanf ( "%d %d", &r, &c ) != EOF && r > 0 && c > 0 )
{
n = read ( r, c );
printf ( "%d\n", mincost ( n ) );
}
return 0;
}
| [
"bluebird498@localhost"
]
| [
[
[
1,
235
]
]
]
|
4728a46f951948d0d6a5c39c5b1f692e9f74fe16 | c6b554900e16dbcca17bbf960755db9e60a5d717 | /google-any-textfile-indexer/Conf.cpp | 2e8cdd987d7bb0bc3d813f53d36abc1ba9a47f9c | [
"Apache-2.0"
]
| permissive | raunaqkapoor/google-calculator | 361a6388384a1bb31a302cca2380b5da1e448018 | 313321b0bf030f47c477bd8e8cdf34cdabcc9bb2 | refs/heads/master | 2020-05-16T15:08:31.781092 | 2007-10-04T18:37:01 | 2007-10-04T18:37:01 | 38,547,897 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,102 | cpp | /*
Copyright (C) 2007 Google Inc.
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.
*/
#include <vector>
#include <string>
#include <fstream>
#include <algorithm>
#include "conf.h"
using namespace std;
// LoadSettings - Parses through the given filename for commands and stores them inside of the
// Settings vector. Returns true if the file was found and loaded, or false if
// there was an error accessing it.
bool Conf::LoadSettings(const string &Filename) {
ifstream ConfFile(Filename.c_str());
if (!ConfFile) { return false; }
vector<string> Arguments;
string CurCommandName = "";
string CurArg = "";
size_t QuoteStartIndex = 0;
size_t QuoteEndIndex = 0;
Settings.clear();
char RawDataBuffer[256];
string DataBuffer;
while (!ConfFile.eof()) {
ConfFile.getline(RawDataBuffer, 256);
DataBuffer = RawDataBuffer;
if ((DataBuffer.substr(0, 1) != "#") && (DataBuffer.substr(0, 1) != "")) {
CurCommandName = DataBuffer.substr(0, DataBuffer.find(" "));
Arguments.clear();
QuoteStartIndex = DataBuffer.find("\"", 0);
QuoteEndIndex = DataBuffer.find("\"", QuoteStartIndex + 1);
while ((QuoteStartIndex != DataBuffer.npos) && (QuoteEndIndex != DataBuffer.npos)) {
CurArg = DataBuffer.substr(QuoteStartIndex + 1, QuoteEndIndex - QuoteStartIndex - 1);
Arguments.push_back(CurArg);
QuoteStartIndex = DataBuffer.find("\"", QuoteEndIndex + 1);
QuoteEndIndex = DataBuffer.find("\"", QuoteStartIndex + 1);
}
Settings[CurCommandName].push_back(Arguments);
}
}
ConfFile.close();
return true;
}
// GetCommandArgs - Returns a string vector of all the aruments of the specified command and number.
// The CommandName is the command name that was used in the .conf file. The
// CommandNumber is the command's number when the same command is used multiple
// times. For example, if the AddRealm command is used twice in the .conf file,
// CommandNumber being 0 would return the value of the first time the AddRealm
// command was called, and CommandNumber being 1 would return the value of the
// second time the AddRealm command was called. CommandNumber's index starts at 0.
vector<string> Conf::GetCommandArgs(const string &CommandName, const size_t CommandNumber) {
vector <vector <string> > Setting = Settings[CommandName];
if (Setting.size() >= CommandNumber + 1) {
return Setting[CommandNumber];
}
return vector <string>();
}
// GetCommandString - Returns a string of one argument of any command in the .conf file. See the
// description of GetCommandArgs for a description of the CommandNumber arg.
// ArgumentNumber is the argument number of the command. It starts indexing at 0.
// If the specified command/command number/argument wasn't found, the function
// return the DefaultValue. CommandNumber, ArgumentNumber and DefaultValue are all
// optional.
string Conf::GetString(const string &CommandName, const size_t CommandNumber, const size_t ArgumentNumber, const string &DefaultValue) {
vector <vector <string> > Setting = Settings[CommandName];
if ((Setting.size() >= CommandNumber + 1) && (Setting[CommandNumber].size() >= ArgumentNumber + 1)) {
return Setting[CommandNumber][ArgumentNumber];
}
return DefaultValue;
}
string Conf::GetString(const string &CommandName, const string &DefaultValue) {
return GetString(CommandName, 0, 0, DefaultValue);
}
// GetCommandInt - Returns an integer of one argument of any command in the .conf file. See
// description of GetCommandString for an explanation of parameters.
int Conf::GetInt(const string &CommandName, const size_t CommandNumber, const size_t ArgumentNumber, const int DefaultValue) {
string CommandString = "";
CommandString = GetString(CommandName, CommandNumber, ArgumentNumber, "");
if (CommandString == "") {
return DefaultValue;
}
return atoi(CommandString.c_str());
}
int Conf::GetInt(const string &CommandName, const int DefaultValue) {
return GetInt(CommandName, 0, 0, DefaultValue);
}
// GetCommandBool - Returns a bool of one argument of any command in the .conf file. See
// description of GetCOmmandString for an explanation of parameters.
bool Conf::GetBool(const string &CommandName, const size_t CommandNumber, const size_t ArgumentNumber, const bool DefaultValue) {
string CommandString = "";
string SendDefaultValue = "";
if (DefaultValue == true) { SendDefaultValue = "true"; } else { SendDefaultValue = "false"; }
CommandString = GetString(CommandName, CommandNumber, ArgumentNumber, SendDefaultValue);
if ((CommandString == "true") || (CommandString == "1") || (CommandString == "yes")) {
return true;
} else if ((CommandString == "false") || (CommandString == "0") || (CommandString == "no")) {
return false;
}
return DefaultValue;
}
bool Conf::GetBool(const string &CommandName, const bool DefaultValue) {
return GetBool(CommandName, 0, 0, DefaultValue);
}
// GetCommandCount - Returns the amount of times a certain command was used in the .conf file.
// For example, if you call AddRealm twice from the .conf, this function will
// return the number 2. Index starts at 1.
size_t Conf::GetCommandCount(const string &CommandName) {
return Settings[CommandName].size();
} | [
"open.source.gd@9364f158-6e32-0410-9a2b-c31eb177bc70"
]
| [
[
[
1,
151
]
]
]
|
f98d486d745c249fb66e395e272d3dfc1423d2f6 | fb135677f176035a63927d5e307986d27205a6ab | /bitwise-engine/Graphics/Vertex.h | 671ca29cf4752ac8cc6263995416fd34e313772e | []
| no_license | jaylindquist/bitwise-engine | eb7c6991a18db22430a8c38c45cfb5c3de3ed936 | c8be0cb946fff4523b6a42dbe014f6a204afdedb | refs/heads/master | 2016-09-06T06:45:51.390789 | 2008-11-19T23:24:52 | 2008-11-19T23:24:52 | 35,298,714 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 404 | h | #pragma once
#include <BitwiseEngine/Math/Real.h>
#include <BitwiseEngine/Graphics/Real.h>
namespace BitwiseEngine {
namespace Graphics {
class Vertex
{
public:
Color ambient;
Color diffuse;
Color specular;
Color emmissive;
Color color;
Math::Real shininess;
Math::Real alpha;
Math::Vector4 textureCoords;
Math::Vector4 normal;
Math::Vector4 location;
};
};
}; | [
"yasunobu13@194bc0c5-1251-0410-adcc-b97d8ca696f6"
]
| [
[
[
1,
28
]
]
]
|
377c040f9630787f759b0f5aa3df4e02df92b34d | 9324000ac1cb567bd4862547cbdccf0923446095 | /foliage/leaf_sound/sound.hpp | b1ddbac4f707584231e6725785cff67cee420070 | []
| no_license | mguillemot/kamaku.foliage | cf63d49e1e5ddd7c30b75acfc1841028d109cba4 | 18c225346916e240bc19bf5570a8c414bbb4153b | refs/heads/master | 2016-08-03T20:09:17.929309 | 2007-09-04T18:15:17 | 2007-09-04T18:15:17 | 2,226,835 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 468 | hpp | #ifndef _FOLIAGE__SOUND
#define _FOLIAGE__SOUND
#include <string>
#include "../basic_types.hpp"
namespace Foliage
{
class Sound
{
public:
Sound(const std::string filename);
~Sound();
Sint32 getSamplesNb() const;
Sint32 getCurrentSampleNb() const;
Uint32 getNextSample();
void rewind();
bool ended() const;
private:
Sint32 _samplesNb;
Uint32 *_samples;
Sint32 _curSample;
};
}
#endif //_FOLIAGE__SOUND
| [
"erhune@1bdb3d1c-df69-384c-996e-f7b9c3edbfcf",
"Erhune@1bdb3d1c-df69-384c-996e-f7b9c3edbfcf"
]
| [
[
[
1,
16
],
[
18,
30
]
],
[
[
17,
17
]
]
]
|
7622165b2c4345aa509ad2b7bf70eaf52e796124 | be3d7c318d79cd33d306aba58a1159147cac91fd | /modules/wgd_models/src/mesh.cpp | 301c45691e9aa0c886087fa2dc867ed157d6c036 | []
| no_license | knicos/Cadence | 827149b53bb3e92fe532b0ad4234b7d0de11ca43 | 7e1e1cf1bae664f77afce63407b61c7b2b0a4fff | refs/heads/master | 2020-05-29T13:19:07.595099 | 2011-10-31T13:05:48 | 2011-10-31T13:05:48 | 1,238,039 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,985 | cpp | #include <wgd/mesh.h>
#include <wgd/material.h>
#include <wgd/vector.h>
#include <wgd/extensions.h>
using namespace wgd;
using namespace cadence;
using namespace cadence::doste;
Mesh::Mesh()
: Object(), m_weightsPerVertex(0), m_skin(NULL), m_drawable(0) {
set("type",type());
}
Mesh::Mesh(const OID &id)
: Object(id), m_weightsPerVertex(0), m_skin(NULL), m_drawable(0) {
set("type",type());
}
Mesh::~Mesh(){
if(m_skin) delete [] m_skin;
if(m_drawable) m_drawable->destroy();
}
void Mesh::setup() {
m_drawable = new Drawable<meshVertex>;
m_drawable->mode = GL_TRIANGLES;
m_drawable->clearData = false;
m_drawable->discard = false;
}
void Mesh::vertices(int nVertices, meshVertex* vx) {
if(!m_drawable) setup();
m_drawable->deleteData();
m_drawable->data = vx;
m_drawable->size = nVertices;
}
void Mesh::skin(int wpv, MeshSkin *skin){
if(m_skin) delete [] m_skin;
m_weightsPerVertex = wpv;
m_skin = skin;
}
void Mesh::create(int n){
//setup blank mesh array
if(!m_drawable || m_drawable->size != n){
meshVertex *vx = new meshVertex[n];
memset(vx, 0, n * sizeof(meshVertex));
vertices(n, vx);
} else {
memset(m_drawable->data, 0, n * sizeof(meshVertex));
}
}
void Mesh::calcTangents(){
for(unsigned int i=0; i<m_drawable->size; i+=3){
meshVertex *vx = m_drawable->data;
vector3d tangent = calcTangent(vx[i], vx[i+1], vx[i+2]);
for(int j=0; j<3; j++){
vx[i+j].custom.var.x = tangent.x;
vx[i+j].custom.var.y = tangent.y;
vx[i+j].custom.var.z = tangent.z;
}
}
}
vector3d Mesh::calcTangent(const meshVertex &vA, const meshVertex &vB, const meshVertex &vC){
vector3d vAB = vector3d(vB.position.x, vB.position.y, vB.position.z) - vector3d(vA.position.x, vA.position.y, vA.position.z);
vector3d vAC = vector3d(vC.position.x, vC.position.y, vC.position.z) - vector3d(vA.position.x, vA.position.y, vA.position.z);
vector3d nA = vector3d(vA.normal.x, vA.normal.y, vA.normal.z);
// Components of vectors to neighboring vertices that are orthogonal to the
// vertex normal
vector3d vProjAB = vAB - nA * ( vector3d::dotProduct( nA, vAB ));
vector3d vProjAC = vAC - nA * ( vector3d::dotProduct( nA, vAC ));
// tu texture coordinate differences
float duAB = vB.texcoords[0].u - vA.texcoords[0].u;
float duAC = vC.texcoords[0].u - vA.texcoords[0].u;
// tv texture coordinate differences
float dvAB = vB.texcoords[0].v - vA.texcoords[0].v;
float dvAC = vC.texcoords[0].v - vA.texcoords[0].v;
if( (dvAC * duAB) > (dvAB * duAC) ){
dvAC = -dvAC;
dvAB = -dvAB;
}
vector3d vTangent = (vProjAC * dvAB) - (vProjAB * dvAC);
//vTangent.normalise();
return vTangent.normalise();
}
void Mesh::calcNormals(){
for(unsigned int i=0; i<m_drawable->size; i+=3){
meshVertex *vx = m_drawable->data;
//points
vector3d p1 = vector3d(vx[i ].position.x, vx[i ].position.y, vx[i ].position.z);
vector3d p2 = vector3d(vx[i+1].position.x, vx[i+1].position.y, vx[i+1].position.z);
vector3d p3 = vector3d(vx[i+2].position.x, vx[i+2].position.y, vx[i+2].position.z);
//vectors
vector3d a = p2 - p1;
vector3d b = p3 - p1;
//normal
vector3d normal = vector3d::crossProduct(a, b);
normal = normal.normalise();
//save in the three points
for(int j=0; j<3; j++){
vx[i+j].normal.x = normal.x;
vx[i+j].normal.y = normal.y;
vx[i+j].normal.z = normal.z;
}
}
}
| [
"[email protected]"
]
| [
[
[
1,
123
]
]
]
|
88ae4750cd6c4b89d7767126bcec1831a63ecaf4 | b14d5833a79518a40d302e5eb40ed5da193cf1b2 | /cpp/extern/xercesc++/2.6.0/src/xercesc/validators/schema/XMLSchemaDescriptionImpl.hpp | fe7206e16e6ab620ec93934161a2974516387467 | [
"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 | 5,797 | hpp | /*
* 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.
*/
/*
* $Log: XMLSchemaDescriptionImpl.hpp,v $
* Revision 1.4 2004/09/08 13:56:57 peiyongz
* Apache License Version 2.0
*
* Revision 1.3 2003/10/14 15:22:28 peiyongz
* Implementation of Serialization/Deserialization
*
* Revision 1.2 2003/07/31 17:14:27 peiyongz
* Grammar embed grammar description
*
* Revision 1.1 2003/06/20 18:40:29 peiyongz
* Stateless Grammar Pool :: Part I
*
* $Id: XMLSchemaDescriptionImpl.hpp,v 1.4 2004/09/08 13:56:57 peiyongz Exp $
*
*/
#if !defined(XMLSchemaDescriptionImplIMPL_HPP)
#define XMLSchemaDescriptionImplIMPL_HPP
#include <xercesc/framework/XMLSchemaDescription.hpp>
#include <xercesc/util/RefVectorOf.hpp>
XERCES_CPP_NAMESPACE_BEGIN
class XMLAttDefs;
class XMLPARSER_EXPORT XMLSchemaDescriptionImpl : public XMLSchemaDescription
{
public :
// -----------------------------------------------------------------------
/** @name constructor and destructor */
// -----------------------------------------------------------------------
//@{
XMLSchemaDescriptionImpl(
const XMLCh* const targetNamespace
, MemoryManager* const memMgr
);
~XMLSchemaDescriptionImpl();
//@}
// -----------------------------------------------------------------------
/** @name Implementation of GrammarDescription Interface */
// -----------------------------------------------------------------------
//@{
/**
* getGrammarKey
*
*/
virtual const XMLCh* getGrammarKey() const;
//@}
// -----------------------------------------------------------------------
/** @name Implementation of SchemaDescription Interface */
// -----------------------------------------------------------------------
//@{
/**
* getContextType
*
*/
virtual ContextType getContextType() const;
/**
* getTargetNamespace
*
*/
virtual const XMLCh* getTargetNamespace() const;
/**
* getLocationHints
*
*/
virtual RefArrayVectorOf<XMLCh>* getLocationHints() const;
/**
* getTriggeringComponent
*
*/
virtual const QName* getTriggeringComponent() const;
/**
* getenclosingElementName
*
*/
virtual const QName* getEnclosingElementName() const;
/**
* getAttributes
*
*/
virtual const XMLAttDef* getAttributes() const;
/**
* setContextType
*
*/
virtual void setContextType(ContextType);
/**
* setTargetNamespace
*
*/
virtual void setTargetNamespace(const XMLCh* const);
/**
* setLocationHints
*
*/
virtual void setLocationHints(const XMLCh* const);
/**
* setTriggeringComponent
*
*/
virtual void setTriggeringComponent(QName* const);
/**
* getenclosingElementName
*
*/
virtual void setEnclosingElementName(QName* const);
/**
* setAttributes
*
*/
virtual void setAttributes(XMLAttDef* const);
//@}
/***
* Support for Serialization/De-serialization
***/
DECL_XSERIALIZABLE(XMLSchemaDescriptionImpl)
XMLSchemaDescriptionImpl(MemoryManager* const memMgr = XMLPlatformUtils::fgMemoryManager);
private :
// -----------------------------------------------------------------------
/** name Unimplemented copy constructor and operator= */
// -----------------------------------------------------------------------
//@{
XMLSchemaDescriptionImpl(const XMLSchemaDescriptionImpl& );
XMLSchemaDescriptionImpl& operator=(const XMLSchemaDescriptionImpl& );
//@}
// -----------------------------------------------------------------------
// Private data members
//
// All data member in this implementation are owned to out survive
// parser. Except for fNamespace which is replicated upon set, the
// rest shall be created by the embedded memoryManager.
//
// fContextType
//
// fNamespace owned
//
// fLocationHints owned
//
// fTriggeringComponent owned
//
// fEnclosingElementName owned
//
// fAttributes referenced
//
// -----------------------------------------------------------------------
XMLSchemaDescription::ContextType fContextType;
const XMLCh* fNamespace;
RefArrayVectorOf<XMLCh>* fLocationHints;
const QName* fTriggeringComponent;
const QName* fEnclosingElementName;
const XMLAttDef* fAttributes;
};
XERCES_CPP_NAMESPACE_END
#endif
| [
"[email protected]"
]
| [
[
[
1,
198
]
]
]
|
6bc6ab74de18717c3dc66ad75820d85e049da269 | 8ce47e73afa904a145a1104fa8eaa71e3a237907 | /Robot/controller/Tokenizer.h | 3b472be9b41fcc8a77058f02c23cc07bfef7061c | []
| no_license | nobody/magiclegoblimps | bc4f1459773773599ec397bdd1a43b1c341ff929 | d66fe634cc6727937a066118f25847fa7d71b8f6 | refs/heads/master | 2021-01-23T15:42:15.729310 | 2010-05-05T03:15:00 | 2010-05-05T03:15:00 | 39,790,220 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 614 | h | #ifndef TOKENIZER_H
#define TOKENIZER_H
#include <string>
#include <vector>
using namespace std;
static void tokenize(const string& str, vector<string>& tokens,
const string& delimiters = " ")
{
string::size_type lastPos = str.find_first_not_of(delimiters, 0);
string::size_type pos = str.find_first_of(delimiters, lastPos);
while (string::npos != pos || string::npos != lastPos)
{
tokens.push_back(str.substr(lastPos, pos - lastPos));
lastPos = str.find_first_not_of(delimiters, pos);
pos = str.find_first_of(delimiters, lastPos);
}
}
#endif | [
"eXceLynX@445d4ad4-0937-11df-b996-818f58f34e26"
]
| [
[
[
1,
23
]
]
]
|
c4199a887b6499ed127ec568b66803f5af4afa36 | 4f89f1c71575c7a5871b2a00de68ebd61f443dac | /src/algorithms/model_estimation/models/5point/poly3.cpp | 607da49d5225f2eac07ec0d2144ed202f293f63a | []
| no_license | inayatkh/uniclop | 1386494231276c63eb6cdbe83296cdfd0692a47c | 487a5aa50987f9406b3efb6cdc656d76f15957cb | refs/heads/master | 2021-01-10T09:43:09.416338 | 2009-09-03T16:26:15 | 2009-09-03T16:26:15 | 50,645,836 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,531 | cpp | /*
* Copyright (c) 2008 Noah Snavely (snavely (at) cs.washington.edu)
* and the University of Washington
*
* 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.
*
*/
/* 3-variable polynomial functions */
#include <stdio.h>
#include <math.h>
#include "poly3.hpp"
namespace 5point {
poly3_t poly3_new(double x, double y, double z, double unit) {
poly3_t p;
int i;
for (i = 0; i < NUM_POLY3_COEFFS; i++)
p.v[i] = 0.0;
p.v[POLY3_X] = x;
p.v[POLY3_Y] = y;
p.v[POLY3_Z] = z;
p.v[POLY3_UNIT] = unit;
return p;
}
poly3_t poly3_add(poly3_t a, poly3_t b) {
int i;
poly3_t r;
for (i = 0; i < NUM_POLY3_COEFFS; i++)
r.v[i] = a.v[i] + b.v[i];
return r;
}
poly3_t poly3_add3(poly3_t a, poly3_t b, poly3_t c) {
int i;
poly3_t r;
for (i = 0; i < NUM_POLY3_COEFFS; i++)
r.v[i] = a.v[i] + b.v[i] + c.v[i];
return r;
}
poly3_t poly3_sub(poly3_t a, poly3_t b) {
int i;
poly3_t r;
for (i = 0; i < NUM_POLY3_COEFFS; i++)
r.v[i] = a.v[i] - b.v[i];
return r;
}
int poly3_degree(poly3_t a) {
if (a.v[POLY3_X3] != 0.0 || a.v[POLY3_Y3] != 0.0 || a.v[POLY3_Z3] != 0.0 ||
a.v[POLY3_X2Y] != 0.0 || a.v[POLY3_X2Z] != 0.0 || a.v[POLY3_XY2] != 0.0 ||
a.v[POLY3_XZ2] != 0.0 || a.v[POLY3_Y2Z] != 0.0 || a.v[POLY3_YZ2] != 0.0 ||
a.v[POLY3_XYZ] != 0.0)
return 3;
if (a.v[POLY3_X2] != 0.0 || a.v[POLY3_Y2] != 0.0 || a.v[POLY3_Z2] != 0.0 ||
a.v[POLY3_XY] != 0.0 || a.v[POLY3_XZ] != 0.0 || a.v[POLY3_YZ] != 0.0)
return 2;
if (a.v[POLY3_X] != 0.0 || a.v[POLY3_Y] != 0.0 || a.v[POLY3_Z] != 0.0)
return 1;
return 0;
}
int poly3_mult_check(poly3_t a, poly3_t b) {
int deg_a = poly3_degree(a);
int deg_b = poly3_degree(b);
if (deg_a + deg_b <= 3)
return 1;
else
return 0;
}
poly3_t poly3_mult(poly3_t a, poly3_t b) {
poly3_t r;
#if 0
if (!poly3_mult_check(a, b)) {
printf("[poly3_mult] Polynomials cannot be multiplied!\n");
return poly3_new(0.0, 0.0, 0.0, 0.0);
}
#endif
r.v[POLY3_UNIT] = a.v[POLY3_UNIT] * b.v[POLY3_UNIT];
r.v[POLY3_X] = a.v[POLY3_X] * b.v[POLY3_UNIT] + a.v[POLY3_UNIT] * b.v[POLY3_X];
r.v[POLY3_Y] = a.v[POLY3_Y] * b.v[POLY3_UNIT] + a.v[POLY3_UNIT] * b.v[POLY3_Y];
r.v[POLY3_Z] = a.v[POLY3_Z] * b.v[POLY3_UNIT] + a.v[POLY3_UNIT] * b.v[POLY3_Z];
r.v[POLY3_XY] = a.v[POLY3_XY] * b.v[POLY3_UNIT] + a.v[POLY3_UNIT] * b.v[POLY3_XY] + a.v[POLY3_X] * b.v[POLY3_Y] + a.v[POLY3_Y] * b.v[POLY3_X];
r.v[POLY3_XZ] = a.v[POLY3_XZ] * b.v[POLY3_UNIT] + a.v[POLY3_UNIT] * b.v[POLY3_XZ] + a.v[POLY3_X] * b.v[POLY3_Z] + a.v[POLY3_Z] * b.v[POLY3_X];
r.v[POLY3_YZ] = a.v[POLY3_YZ] * b.v[POLY3_UNIT] + a.v[POLY3_UNIT] * b.v[POLY3_YZ] + a.v[POLY3_Y] * b.v[POLY3_Z] + a.v[POLY3_Z] * b.v[POLY3_Y];
r.v[POLY3_X2] = a.v[POLY3_X2] * b.v[POLY3_UNIT] + a.v[POLY3_UNIT] * b.v[POLY3_X2] + a.v[POLY3_X] * b.v[POLY3_X];
r.v[POLY3_Y2] = a.v[POLY3_Y2] * b.v[POLY3_UNIT] + a.v[POLY3_UNIT] * b.v[POLY3_Y2] + a.v[POLY3_Y] * b.v[POLY3_Y];
r.v[POLY3_Z2] = a.v[POLY3_Z2] * b.v[POLY3_UNIT] + a.v[POLY3_UNIT] * b.v[POLY3_Z2] + a.v[POLY3_Z] * b.v[POLY3_Z];
r.v[POLY3_X2Y] = a.v[POLY3_X2Y] * b.v[POLY3_UNIT] + a.v[POLY3_UNIT] * b.v[POLY3_X2Y] +
a.v[POLY3_X2] * b.v[POLY3_Y] + a.v[POLY3_Y] * b.v[POLY3_X2] +
a.v[POLY3_XY] * b.v[POLY3_X] + a.v[POLY3_X] * b.v[POLY3_XY];
r.v[POLY3_X2Z] = a.v[POLY3_X2Z] * b.v[POLY3_UNIT] + a.v[POLY3_UNIT] * b.v[POLY3_X2Z] +
a.v[POLY3_X2] * b.v[POLY3_Z] + a.v[POLY3_Z] * b.v[POLY3_X2] +
a.v[POLY3_XZ] * b.v[POLY3_X] + a.v[POLY3_X] * b.v[POLY3_XZ];
r.v[POLY3_XY2] = a.v[POLY3_XY2] * b.v[POLY3_UNIT] + a.v[POLY3_UNIT] * b.v[POLY3_XY2] +
a.v[POLY3_X] * b.v[POLY3_Y2] + a.v[POLY3_Y2] * b.v[POLY3_X] +
a.v[POLY3_XY] * b.v[POLY3_Y] + a.v[POLY3_Y] * b.v[POLY3_XY];
r.v[POLY3_Y2Z] = a.v[POLY3_Y2Z] * b.v[POLY3_UNIT] + a.v[POLY3_UNIT] * b.v[POLY3_Y2Z] +
a.v[POLY3_Y2] * b.v[POLY3_Z] + a.v[POLY3_Z] * b.v[POLY3_Y2] +
a.v[POLY3_YZ] * b.v[POLY3_Y] + a.v[POLY3_Y] * b.v[POLY3_YZ];
r.v[POLY3_XZ2] = a.v[POLY3_XZ2] * b.v[POLY3_UNIT] + a.v[POLY3_UNIT] * b.v[POLY3_XZ2] +
a.v[POLY3_X] * b.v[POLY3_Z2] + a.v[POLY3_Z2] * b.v[POLY3_X] +
a.v[POLY3_XZ] * b.v[POLY3_Z] + a.v[POLY3_Z] * b.v[POLY3_XZ];
r.v[POLY3_YZ2] = a.v[POLY3_YZ2] * b.v[POLY3_UNIT] + a.v[POLY3_UNIT] * b.v[POLY3_YZ2] +
a.v[POLY3_Y] * b.v[POLY3_Z2] + a.v[POLY3_Z2] * b.v[POLY3_Y] +
a.v[POLY3_YZ] * b.v[POLY3_Z] + a.v[POLY3_Z] * b.v[POLY3_YZ];
r.v[POLY3_XYZ] = a.v[POLY3_XYZ] * b.v[POLY3_UNIT] + a.v[POLY3_UNIT] * b.v[POLY3_XYZ] +
a.v[POLY3_XY] * b.v[POLY3_Z] + a.v[POLY3_Z] * b.v[POLY3_XY] +
a.v[POLY3_XZ] * b.v[POLY3_Y] + a.v[POLY3_Y] * b.v[POLY3_XZ] +
a.v[POLY3_YZ] * b.v[POLY3_X] + a.v[POLY3_X] * b.v[POLY3_YZ];
r.v[POLY3_X3] = a.v[POLY3_X3] * b.v[POLY3_UNIT] + a.v[POLY3_UNIT] * b.v[POLY3_X3] +
a.v[POLY3_X2] * b.v[POLY3_X] + a.v[POLY3_X] * b.v[POLY3_X2];
r.v[POLY3_Y3] = a.v[POLY3_Y3] * b.v[POLY3_UNIT] + a.v[POLY3_UNIT] * b.v[POLY3_Y3] +
a.v[POLY3_Y2] * b.v[POLY3_Y] + a.v[POLY3_Y] * b.v[POLY3_Y2];
r.v[POLY3_Z3] = a.v[POLY3_Z3] * b.v[POLY3_UNIT] + a.v[POLY3_UNIT] * b.v[POLY3_Z3] +
a.v[POLY3_Z2] * b.v[POLY3_Z] + a.v[POLY3_Z] * b.v[POLY3_Z2];
return r;
}
poly3_t poly3_mult11(poly3_t a, poly3_t b) {
poly3_t r;
int i;
for (i = 0; i < NUM_POLY3_COEFFS; i++)
r.v[i] = 0.0;
r.v[POLY3_UNIT] = a.v[POLY3_UNIT] * b.v[POLY3_UNIT];
r.v[POLY3_X] = a.v[POLY3_X] * b.v[POLY3_UNIT] + a.v[POLY3_UNIT] * b.v[POLY3_X];
r.v[POLY3_Y] = a.v[POLY3_Y] * b.v[POLY3_UNIT] + a.v[POLY3_UNIT] * b.v[POLY3_Y];
r.v[POLY3_Z] = a.v[POLY3_Z] * b.v[POLY3_UNIT] + a.v[POLY3_UNIT] * b.v[POLY3_Z];
r.v[POLY3_XY] = a.v[POLY3_X] * b.v[POLY3_Y] + a.v[POLY3_Y] * b.v[POLY3_X];
r.v[POLY3_XZ] = a.v[POLY3_X] * b.v[POLY3_Z] + a.v[POLY3_Z] * b.v[POLY3_X];
r.v[POLY3_YZ] = a.v[POLY3_Y] * b.v[POLY3_Z] + a.v[POLY3_Z] * b.v[POLY3_Y];
r.v[POLY3_X2] = a.v[POLY3_X] * b.v[POLY3_X];
r.v[POLY3_Y2] = a.v[POLY3_Y] * b.v[POLY3_Y];
r.v[POLY3_Z2] = a.v[POLY3_Z] * b.v[POLY3_Z];
return r;
}
poly3_t poly3_mult21(poly3_t a, poly3_t b) {
poly3_t r;
r.v[POLY3_UNIT] = a.v[POLY3_UNIT] * b.v[POLY3_UNIT];
r.v[POLY3_X] = a.v[POLY3_X] * b.v[POLY3_UNIT] + a.v[POLY3_UNIT] * b.v[POLY3_X];
r.v[POLY3_Y] = a.v[POLY3_Y] * b.v[POLY3_UNIT] + a.v[POLY3_UNIT] * b.v[POLY3_Y];
r.v[POLY3_Z] = a.v[POLY3_Z] * b.v[POLY3_UNIT] + a.v[POLY3_UNIT] * b.v[POLY3_Z];
r.v[POLY3_XY] = a.v[POLY3_XY] * b.v[POLY3_UNIT] + a.v[POLY3_X] * b.v[POLY3_Y] + a.v[POLY3_Y] * b.v[POLY3_X];
r.v[POLY3_XZ] = a.v[POLY3_XZ] * b.v[POLY3_UNIT] + a.v[POLY3_X] * b.v[POLY3_Z] + a.v[POLY3_Z] * b.v[POLY3_X];
r.v[POLY3_YZ] = a.v[POLY3_YZ] * b.v[POLY3_UNIT] + a.v[POLY3_Y] * b.v[POLY3_Z] + a.v[POLY3_Z] * b.v[POLY3_Y];
r.v[POLY3_X2] = a.v[POLY3_X2] * b.v[POLY3_UNIT] + a.v[POLY3_X] * b.v[POLY3_X];
r.v[POLY3_Y2] = a.v[POLY3_Y2] * b.v[POLY3_UNIT] + a.v[POLY3_Y] * b.v[POLY3_Y];
r.v[POLY3_Z2] = a.v[POLY3_Z2] * b.v[POLY3_UNIT] + a.v[POLY3_Z] * b.v[POLY3_Z];
r.v[POLY3_X2Y] =
a.v[POLY3_X2] * b.v[POLY3_Y] +
a.v[POLY3_XY] * b.v[POLY3_X];
r.v[POLY3_X2Z] =
a.v[POLY3_X2] * b.v[POLY3_Z] +
a.v[POLY3_XZ] * b.v[POLY3_X];
r.v[POLY3_XY2] =
a.v[POLY3_Y2] * b.v[POLY3_X] +
a.v[POLY3_XY] * b.v[POLY3_Y];
r.v[POLY3_Y2Z] =
a.v[POLY3_Y2] * b.v[POLY3_Z] +
a.v[POLY3_YZ] * b.v[POLY3_Y];
r.v[POLY3_XZ2] =
a.v[POLY3_Z2] * b.v[POLY3_X] +
a.v[POLY3_XZ] * b.v[POLY3_Z];
r.v[POLY3_YZ2] =
a.v[POLY3_Z2] * b.v[POLY3_Y] +
a.v[POLY3_YZ] * b.v[POLY3_Z];
r.v[POLY3_XYZ] =
a.v[POLY3_XY] * b.v[POLY3_Z] +
a.v[POLY3_XZ] * b.v[POLY3_Y] +
a.v[POLY3_YZ] * b.v[POLY3_X];
r.v[POLY3_X3] = a.v[POLY3_X2] * b.v[POLY3_X];
r.v[POLY3_Y3] = a.v[POLY3_Y2] * b.v[POLY3_Y];
r.v[POLY3_Z3] = a.v[POLY3_Z2] * b.v[POLY3_Z];
return r;
}
poly3_t poly3_scale(poly3_t a, double scale) {
poly3_t r;
int i;
for (i = 0; i < NUM_POLY3_COEFFS; i++)
r.v[i] = scale * a.v[i];
return r;
}
double poly3_eval(poly3_t a, double x, double y, double z) {
double r = a.v[POLY3_UNIT];
r += a.v[POLY3_X] * x;
r += a.v[POLY3_Y] * y;
r += a.v[POLY3_Z] * z;
r += a.v[POLY3_XY] * x * y;
r += a.v[POLY3_XZ] * x * z;
r += a.v[POLY3_YZ] * y * z;
r += a.v[POLY3_X2] * x * x;
r += a.v[POLY3_Y2] * y * y;
r += a.v[POLY3_Z2] * z * z;
r += a.v[POLY3_X2Y] * x * x * y;
r += a.v[POLY3_X2Z] * x * x * z;
r += a.v[POLY3_XY2] * x * y * y;
r += a.v[POLY3_Y2Z] * y * y * z;
r += a.v[POLY3_XZ2] * x * z * z;
r += a.v[POLY3_YZ2] * y * z * z;
r += a.v[POLY3_XYZ] * x * y * z;
r += a.v[POLY3_X3] * x * x * x;
r += a.v[POLY3_Y3] * y * y * y;
r += a.v[POLY3_Z3] * z * z * z;
return r;
}
double poly3_get(poly3_t a, poly3_coeff_t idx) {
return a.v[idx];
}
}
| [
"rodrigo.benenson@gmailcom"
]
| [
[
[
1,
284
]
]
]
|
06a058505f612f0e8bb42719251fe4dacadf1d11 | cfb0fafddd1df76e22b1b4212ba9102693f100fa | /Kernel/USBRemover/DeviceManager.cpp | 6b8b91aec4ec253e619245c9c9002d85b3d47d6b | []
| no_license | ExaByt3s/usbremover | ef8fecc6030d23f178c2cd50dbc5557e06c42322 | 13a6b6802a2f968d6cf923fd1821b03999292d5e | refs/heads/master | 2020-04-11T14:48:34.107832 | 2011-04-09T07:51:39 | 2011-04-09T07:51:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,277 | cpp | /*
DeviceManager.cpp
Started: 25.05.2010
Author: Asha'man
Email: [email protected]
License: LGPL v3 <?>
Device manager base class implementation
*/
#include "DeviceManager.h"
//Internal constant for formatting drive name
const LPTSTR DRIVE_PATTERN = _T("\\\\.\\PhysicalDrive%d");
//Critical section for correct device refreshing
CRITICAL_SECTION csRefreshState;
/*
Purpose:
Constructor
Parameters:
None
*/
DeviceManager::DeviceManager()
{
InitializeCriticalSection(&csRefreshState);
this->listeners = new DelegateSet();
//creating volume manager
this->volmgr = new ::VolumeManager();
//refreshing device state
this->Refresh();
}
/*
Purpose:
Deletes and re-gets the information about devices
Parameters:
None
Return value:
None
*/
void DeviceManager::Refresh()
{
// allocating containers
this->volumes = new VolumeList();
this->drives = new DriveList();
this->sticks = new USBDeviceList();
try
{
DeviceDataSet volumeDataSet; //mappings for volumes
DeviceDataSet driveDataSet; //mappings for drives
/*
Fixed 11.08.2010 by Asha'man
It is OBLIGATORY to DESTROY created device information sets!!!
Use SetupDiDestroyDeviceInfoList(handle)
*/
//pausing volume manager to avoid refreshing
this->volmgr->Pause();
//getting device info set handle for volumes
this->hVolumeInformationSet =
::GetDeviceInformationSet(GUID_DEVINTERFACE_VOLUME, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
//getting cache for volume data set
volumeDataSet = ::GetDeviceInformationCache(GUID_DEVINTERFACE_VOLUME,
this->hVolumeInformationSet);
this->GetVolumes(volumeDataSet);
//attaching device manager to volume manager listeners
this->volmgr->AttachListener(this);
//resuming volume manager
this->volmgr->Resume();
//getting device info set handle for drives
this->hDriveInformationSet =
::GetDeviceInformationSet(GUID_DEVINTERFACE_DISK, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
//Getting cache for drive data set
driveDataSet = ::GetDeviceInformationCache(GUID_DEVINTERFACE_DISK,
this->hDriveInformationSet);
this->GetDrives(driveDataSet);
//Linking volumes and drives
this->LinkVD();
//getting info set for devices
this->hDeviceInformationSet =
::GetDeviceInformationSet(GUID_DEVINTERFACE_USB_DEVICE, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
//final step - linking altogether
this->GetDevices();
//notifying about changes
this->FireEvent();
}
catch (...)
{
throw;
}
}
/*
Purpose:
Destructor
*/
DeviceManager::~DeviceManager()
{
//deleting critical section
DeleteCriticalSection(&csRefreshState);
//calls Clean method
this->Clean();
//deleting volume manager
//ONLY AFTER CLEANING!!!
DELOBJ(this->volmgr);
DELOBJ(this->listeners);
#ifdef DEBUG
_ASSERT(this->volmgr == NULL);
#endif
}
/*
Purpose:
Cleans all the references in the class and prepares it for refreshing
Parameters:
None
Return value:
None
*/
void DeviceManager::Clean()
{
/*
Fixed 12.08.2010 - clean disk number set!!!!
+ detach volumes from volume manager
*/
this->disknums.clear();
//detaching listeners
if (this->volumes != NULL)
{
for (VolumeList::iterator i = this->volumes->begin();
i != this->volumes->end(); ++i)
{
this->volmgr->DetachListener(*i);
}
}
// closing and destroying device information sets
if (this->hVolumeInformationSet != INVALID_HANDLE_VALUE)
SetupDiDestroyDeviceInfoList(this->hVolumeInformationSet);
if (this->hDriveInformationSet != INVALID_HANDLE_VALUE)
SetupDiDestroyDeviceInfoList(this->hDriveInformationSet);
if (this->hDeviceInformationSet != INVALID_HANDLE_VALUE)
SetupDiDestroyDeviceInfoList(this->hDeviceInformationSet);
//deleting devices and container
if (this->sticks != NULL)
{
for (USBDeviceList::iterator i = this->sticks->begin();
i != this->sticks->end(); ++i)
{
DELOBJ(*i);
#ifdef DEBUG
_ASSERT(*i == NULL);
#endif
}
DELOBJ(this->sticks);
#ifdef DEBUG
_ASSERT(this->sticks == NULL);
#endif
}
//deleting only containers because each
//device destroys its children
DELOBJ(this->drives);
DELOBJ(this->volumes);
#ifdef DEBUG
_ASSERT(this->drives == NULL);
_ASSERT(this->volumes == NULL);
#endif
}
/*
Purpose:
Implements IMessageListener::RefreshState method
Parameters:
None
Return value:
None
*/
void DeviceManager::RefreshState()
{
try
{
//entering critical section
EnterCriticalSection(&csRefreshState);
//refreshing device list
this->Clean();
this->Refresh();
}
catch(...)
{
//leaving critical section in case of exception
LeaveCriticalSection(&csRefreshState);
throw;
}
LeaveCriticalSection(&csRefreshState);
}
/*
Purpose:
Gets all the removable volumes in the system
Parameters:
volumeDataSet - mapping between volumes and drives
Return value:
None
*/
void DeviceManager::GetVolumes(DeviceDataSet volumeDataSet)
{
//cache for the volumes
StringList volumeList;
//buffer for the strings
LPTSTR volumeName = new TCHAR[MAX_PATH+1];
//get the first volume
HANDLE handle = FindFirstVolume(volumeName, MAX_PATH);
if (handle == INVALID_HANDLE_VALUE)
{
DELARRAY(volumeName);
#ifdef DEBUG
_ASSERT(volumeName == NULL);
#endif
throw WinAPIException(GetLastError());
}
else
{
//save it and get all the other volumes
volumeList.push_back(volumeName);
volumeName = new TCHAR[MAX_PATH+1];
while (FindNextVolume(handle, volumeName, MAX_PATH))
{
volumeList.push_back(volumeName);
volumeName = new TCHAR[MAX_PATH+1];
}
FindVolumeClose(handle);
}
DELARRAY(volumeName);
#ifdef DEBUG
_ASSERT(volumeName == NULL);
#endif
// filtering volumes. Set is for disk numbers
for (size_t i = 0; i<volumeList.size(); ++i)
{
// checking if the volume is located on a
// removable drive
if (FilterRemovableVolume(volumeList[i]))
{
Volume *volume = new Volume(volumeList[i], volumeDataSet,
this->hVolumeInformationSet);
this->volumes->push_back(volume);
//attaching volumes to mount manager
this->volmgr->AttachListener(volume);
// saving disk number to the set
// if operation returned false then set
// already contains such a number
disknums.insert(volume->DiskNumber());
}
}
//clearing volume list
CLRSTRLIST(volumeList);
}
/*
Purpose:
Gets all the removable drives in the system
Parameters:
driveDataSet - mapping between volumes and drives
Return value:
None
*/
void DeviceManager::GetDrives(DeviceDataSet driveDataSet)
{
//iterating over set with drive indexes
for (std::set<DWORD>::iterator i = this->disknums.begin();
i != this->disknums.end(); ++i)
{
//formatting drive name
LPTSTR buffer = new TCHAR[MAX_PATH+1];
_stprintf(buffer,DRIVE_PATTERN,*i);
//creating a drive
DiskDrive *drive = new DiskDrive(*i, buffer, driveDataSet,
this->hDriveInformationSet);
//saving it
this->drives->push_back(drive);
DELARRAY(buffer);
#ifdef DEBUG
_ASSERT(buffer == NULL);
#endif
}
}
/*
Purpose:
Gets all the removable devices in the system
Parameters:
None
Return value:
None
*/
void DeviceManager::GetDevices()
{
//buffer for acceleration of operation
std::map<DWORD,USBDevice*> buffer;
//parent handle
DEVINST parentHandle;
//iterating over drives
for (DriveList::iterator i = this->drives->begin();
i != this->drives->end(); ++i)
{
DiskDrive *drive = *i;
//getting parent for each drive
if (CM_Get_Parent(&parentHandle, drive->InstanceHandle(),
ZERO_FLAGS) == CR_SUCCESS)
{
USBDevice *device;
//checking if the parent already exists
//if it is so, we make a link
//otherwise, we create a new device
std::map<DWORD,USBDevice*>::iterator dev =
buffer.find(parentHandle);
if (dev == buffer.end())
{
//creating new USBDevice
device = new USBDevice((HANDLE)parentHandle, this->hDeviceInformationSet);
//adding the child drive
device->AddChild(drive);
//putting to map
buffer.insert(std::map<DWORD,USBDevice*>::value_type(parentHandle,device));
//putting to list
this->sticks->push_back(device);
}
else
{
device = dev->second;
//linking with existing
device->AddChild(drive);
}
}
}
}
/*
Purpose:
Links volumes and drives with each other
Parameters:
None
Return value:
None
*/
void DeviceManager::LinkVD()
{
//external loop for drives
for (DriveList::iterator i = this->drives->begin();
i != this->drives->end(); ++i)
{
DiskDrive *drive = *i;
//internal loop for volumes
for (VolumeList::iterator j = this->volumes->begin();
j != this->volumes->end(); ++j)
{
Volume *volume = *j;
/*
THE KEY POINT OF USBREMOVER 2.0:
DRIVES AND VOLUMES ARE LINKED BY DISK NUMBER
Many thanks to Uwe Sieber and Simon Mourier
*/
if (volume->DiskNumber() == drive->DiskNumber())
{
drive->AddChild(volume);
}
}
}
}
/*
Purpose:
Refreshes the managers state
Parameters:
None
Return value:
None
*/
void DeviceManager::RefreshVolumeState()
{
try
{
//entering critical section
EnterCriticalSection(&csRefreshState);
//firing an event
this->FireEvent();
}
catch(...)
{
//leaving critical section in case of exception
LeaveCriticalSection(&csRefreshState);
throw;
}
LeaveCriticalSection(&csRefreshState);
}
/*
Purpose:
Attaches a listener
Parameters:
None
Return value:
None
*/
void DeviceManager::AttachListener(IMessageListener *listener)
{
this->listeners->insert(listener);
}
/*
Purpose:
Detaches a listener
Parameters:
None
Return value:
None
*/
void DeviceManager::DetachListener(IMessageListener *listener)
{
this->listeners->erase(listener);
}
/*
Purpose:
Fires an event
Parameters:
None
Return value:
None
*/
void DeviceManager::FireEvent()
{
for (DelegateSet::iterator i = this->listeners->begin();
i != this->listeners->end(); ++i)
{
(*i)->RefreshState();
}
} | [
"[email protected]@8417aba2-bd37-11de-8784-f7ad4773dbab"
]
| [
[
[
1,
455
]
]
]
|
2488a28761d014c25d37b1676f60a4169e92d9af | 282e6353fbdf90100119bc4c2106109db7e18d15 | /baldwin-gillam/hfk11.cpp | edcfc50ff659e2fa02032689e61d22115308e612 | []
| no_license | lipshitz/hfk-parallel | 80c891803ca640d3509cfb7ed9d01b8298779eab | 9b43f87f42270d65422623f1ac66e215c6d13250 | refs/heads/master | 2020-06-04T05:28:32.790747 | 2011-09-08T23:11:26 | 2011-09-08T23:11:26 | 32,195,183 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,025 | cpp |
// Computes Heegaard Floer knot homology of the Kinoshita-Terasaka knot KT_{2,1}.
// To calculate for different knots, modify the gridsize and the white and black arrays below
// and change the loops at lines 340 and 464. Won't work for gridsize > 11 unless you have
// about 60GB of RAM, though, with more modification it could be made to work.
#include <time.h>
#include <iostream>
#include <vector>
#include <list>
using std::list;
using std::vector;
using std::cout;
using std::cin;
class Generator {
public:
list<int> out;
list<int> in;
bool alive;
Generator();
~Generator();
};
// Globals
const int gridsize = 11; // arc-index
// Kinoshita-Terasaka KT_{2,1}
int white[11]={5,10,9,4,8,0,1,6,7,2,3};
int black[11]={0,6,1,7,10,2,5,9,3,4,8};
// Conway Mutant C_{2,1}
// int white[11]={10,9,3,4,5,8,6,7,1,2,0};
// int black[11]={6,1,7,0,3,10,9,2,4,8,5};
// 8_19
// int white[10] = {2,5,3,4,8,6,7,9,1,0};
// int black[10] = {0,9,1,2,3,4,5,6,7,8};
// 8_20
// int white[9] = {4,5,6,7,3,2,1,0,8};
// int black[9] = {0,1,4,5,8,6,3,7,2};
// 8_21
// int white [10] = {9,6,1,5,2,3,0,4,7,8};
// int black [10] = {1,2,3,7,4,6,5,8,9,0};
// 9_42
// int white[10] = {3,4,5,8,2,1,0,6,7,9};
// int black[10] = {0,1,3,4,9,5,7,8,2,6};
// 9_43
// int black[10] = {2,5,6,1,7,9,0,8,4,3};
// int white[10] = {7,8,5,4,3,6,2,1,0,9};
// 9_44
// int black [9] = {0,6,5,3,1,2,4,8,7};
// int white [9] = {5,4,8,6,7,0,1,3,2};
// 9_45
// int white[10] = {2,4,9,8,5,0,3,6,7,1};
// int black[10] = {0,1,2,3,9,4,7,8,5,6};
// 9_46
// int white [9] = {2,1,5,7,6,0,8,3,4};
// int black [9] = {0,6,8,2,3,5,4,7,1};
// 9_47
// int white[9]= {8,6,3,2,1,4,5,7,0};
// int black[9] = {2,1,0,7,5,6,8,3,4};
// 9_48
// int white[10]= {5,6,2,1,8,7,0,4,3,9};
// int black[10]= {7,1,0,5,3,9,8,2,6,4};
// 9_49
// int white[9]={3,2,8,1,7,0,6,5,4};
// int black[9]={0,6,3,5,2,4,1,8,7};
// 10_124
// int white [9] = {7,6,5,3,4,2,1,0,8};
// int black [9] = {3,1,8,0,7,6,5,2,4};
// 10_125
// int white[10] = {8,6,4,3,7,9,2,1,0,5};
// int black[10] = {4,3,1,0,5,6,8,7,2,9};
// 10_126
// int white[10] = {8,0,5,2,1,3,4,6,7,9};
// int black[10] = {1,7,9,8,5,0,2,3,4,6};
// 10_127
// int white[10] = {7,3,4,5,9,0,8,1,6,2};
// int black[10] = {0,1,2,3,4,6,5,7,9,8};
// 10_128
//int white[10] = {9,3,2,8,6,5,7,4,1,0};
//int black[10] = {2,1,4,5,3,0,9,8,7,6};
// 10_129
// int white[10] = {9,3,2,6,8,7,0,4,1,5};
// int black[10] = {2,1,4,3,5,9,6,8,7,0};
// 10_130
// int white[10] = {7,6,8,5,3,9,2,4,0,1};
// int black[10] = {3,0,4,7,6,5,8,1,2,9};
// 10_131
// int white[10] = {8,1,3,5,6,4,2,7,9,0};
// int black[10] = {2,4,6,7,9,8,0,1,5,3};
// 10_132
// int white[9] = {7,3,4,0,1,8,2,6,5};
// int black[9] = {4,6,1,2,5,3,7,0,8};
// 10_133
// int white[10] = {0,9,1,3,6,5,4,7,8,2};
// int black[10] = {5,4,8,0,9,1,2,3,6,7};
// 10_134
// int white[10] = {6,5,4,9,3,8,7,2,1,0};
// int black[10] = {1,8,7,6,5,4,0,9,3,2};
// 10_135
// int white[10] = {8,0,6,7,9,3,4,2,1,5};
// int black[10] = {2,4,1,5,6,0,8,7,3,9};
// 10_136
// int white[10] = {8,6,3,9,2,0,1,7,5,4};
// int black[10] = {0,4,6,2,1,5,9,3,7,8};
// 10_137
// int white[10] = {5,7,9,8,3,2,4,0,1,6};
// int black[10] = {2,1,6,9,3,4,8,5,7,0};
// 10_138
// int white[10] = {9,5,8,2,6,3,7,1,4,0};
// int black[10] = {2,1,3,5,0,9,4,6,8,7};
// 10_139
// int white[10] = {9,8,6,5,3,7,4,2,1,0};
// int black[10] = {1,5,3,2,0,9,8,7,6,4};
// 10_140
// int white[10] = {5,6,9,4,1,0,7,8,2,3};
// int black[10] = {0,2,5,8,6,4,9,3,7,1};
// 10_141
// int white[10] = {9,7,4,8,0,2,1,6,3,5};
// int black[10] = {2,1,9,6,3,7,5,4,8,0};
// 10_142
// int white[10] = {6,5,4,8,3,2,7,1,0,9};
// int black[10] = {2,1,7,6,5,0,9,8,4,3};
// 10_143
// int white[10] = {8,9,1,4,3,5,2,6,7,0};
// int black[10] = {2,7,8,0,9,1,4,3,5,6};
// 10_144
// int white[10] = {7,0,1,5,4,8,9,2,6,3};
// int black[10] = {1,2,4,3,6,5,7,8,0,9};
// 10_145
// int white[10] = {6,8,3,2,4,5,7,9,0,1};
// int black[10] = {0,4,6,7,1,8,3,2,5,9};
// 10_146
// int white[10] = {7,6,1,2,9,0,8,3,4,5};
// int black[10] = {2,0,3,8,7,5,4,6,1,9};
// 10_147
// int white[10] = {6,0,4,7,5,2,9,8,3,1};
// int black[10] = {2,5,6,3,8,7,4,1,0,9};
// 10_148
// int white[10] = {8,7,5,6,1,9,2,3,0,4};
// int black[10] = {1,0,8,2,3,5,4,7,6,9};
// 10_149
// int white[10] = {4,8,5,9,2,0,1,6,7,3};
// int black[10] = {2,3,1,4,6,5,7,8,9,0};
// 10_150
// int white[10] = {6,5,2,9,3,8,7,4,1,0};
// int black[10] = {3,8,7,6,1,2,0,9,5,4};
// 10_151
// int white[10] = {4,3,5,7,0,2,9,1,8,6};
// int black[10] = {0,9,1,4,5,8,7,6,3,2};
// 10_152
// int white[10] = {5,6,7,8,0,9,1,2,3,4};
// int black[10] = {0,2,1,5,3,7,8,4,6,9};
// 10_153
// int white[10] = {9,1,2,3,5,0,7,6,8,4};
// int black[10] = {3,5,8,7,9,6,4,2,1,0};
// 10_154
// int white[10] = {8,7,6,5,4,3,2,9,1,0};
// int black[10] = {1,3,9,0,7,5,8,4,6,2};
// 10_155
// int white[10] = {9,7,5,8,1,4,2,0,3,6};
// int black[10] = {5,4,1,2,3,0,9,6,7,8};
// 10_156
// int white[10] = {9,0,6,7,3,5,8,1,4,2};
// int black[10] = {4,7,8,1,9,0,2,3,6,5};
// 10_157
// int white[10] = {9,6,4,8,3,7,5,2,0,1};
// int black[10] = {4,3,0,2,1,9,8,6,5,7};
// 10_158
// int white[10] = {7,2,1,8,9,6,0,5,3,4};
// int black[10] = {1,0,5,3,7,2,4,8,6,9};
// 10_159
// int white[10] = {4,1,3,0,8,2,7,9,6,5};
// int black[10] = {2,8,7,6,4,9,1,5,3,0};
// 10_160
// int white[10] = {6,4,2,0,3,8,9,1,7,5};
// int black[10] = {3,9,8,7,1,6,2,5,4,0};
// 10_161
// int white[10] = {5,6,8,7,1,2,9,3,0,4};
// int black[10] = {0,1,5,2,3,4,6,8,7,9};
// 10_162
// int white[10] = {2,7,1,8,9,3,0,4,6,5};
// int black[10] = {0,3,4,2,7,6,5,8,1,9};
// 10_163
// int white[10] = {5,4,2,0,3,7,9,1,8,6};
// int black[10] = {3,9,7,5,8,1,2,6,4,0};
// 10_164
// int white[10] = {7,8,6,5,4,0,2,9,1,3};
// int black[10] = {0,5,2,9,1,3,7,4,6,8};
// 10_165
// int white[10] = {3,2,7,5,6,4,1,8,0,9};
// int black[10] = {0,6,4,9,3,8,7,2,5,1};
// Function Prototypes
bool RectDotFree(int xll, int yll, int xur, int yur, int which); /* Is the rectangle with lowerleft
corner xll,yll and upper right corner xur,ur (on the torus their are 4 such, indexed by "which" as below)
free of black and white dots:
| |
1 | 2 | 1
| |
----+------+-------
| |
3 | 0 | 3
| |
----+------+-------
| |
1 | 2 | 1
| |
*/
int Index(int y []); // Returns the number of permutations appearing before y lexicographically
int WindingNumber(int x, int y); // Return winding number of the knot projection around (x,y)
int MaslovGrading(int y []);
int Factorial(int n); // Returns n!
bool ValidGrid();
// Main
int main(int argc, char *argv[]){
if(!ValidGrid()) return 0; // Check that the grid is valid
//cout << "This is a valid " << gridsize << " by " << gridsize << " grid diagram.\n";
int numgen = Factorial(gridsize);
time_t starttime = time(NULL); // Used to record how long this takes
// Record winding numbers around grid points for Alexander grading computations
// Also record the Alexander grading shift
int temp=0;
for(int i=0; i<gridsize; i++) {
temp += WindingNumber(i,black[i]);
temp += WindingNumber(i,(black[i]+1) % gridsize);
temp += WindingNumber((i+1) % gridsize, black[i]);
temp += WindingNumber((i+1) % gridsize, (black[i]+1) % gridsize);
}
for(int i=0; i<gridsize; i++) {
temp += WindingNumber(i,white[i]);
temp += WindingNumber(i,(white[i]+1) % gridsize);
temp += WindingNumber((i+1) % gridsize, white[i]);
temp += WindingNumber((i+1) % gridsize, (white[i]+1) % gridsize);
}
const int AShift = (temp - 4 * gridsize + 4)/8;
//cout << "Alexander Grading Shift: " << AShift << "\n";
//cout << "Calculating winding number around all grid points.\n";
int WN[gridsize][gridsize];
for(int x=0; x<gridsize; x++) {
for(int y=0; y<gridsize; y++) {
WN[x][y] = WindingNumber(x,y);
}
}
// Record for later use whether every possible rectangle has a black or white dot in it
// This will speed boundary computations.
//cout << "Computing which rectangles on the torus have no black or white dots inside.\n";
bool Rectangles[gridsize][gridsize][gridsize][gridsize][4];
for(int xll=0; xll < gridsize; xll++) {
for(int xur=xll+1; xur < gridsize; xur++) {
for(int yll=0; yll < gridsize; yll++) {
for(int yur=yll+1; yur < gridsize; yur++) {
Rectangles[xll][yll][xur][yur][0] = RectDotFree(xll,yll,xur,yur,0);
Rectangles[xll][yll][xur][yur][1] = RectDotFree(xll,yll,xur,yur,1);
Rectangles[xll][yll][xur][yur][2] = RectDotFree(xll,yll,xur,yur,2);
Rectangles[xll][yll][xur][yur][3] = RectDotFree(xll,yll,xur,yur,3);
}
}
}
}
// Iterate through the generators in lexicographic
// order and calculate their boundaries
// Identify each permutation with the integer given by the number of permutations preceding
// it in lexicographic order.
// Populate Graph[count].out with a list of integers corresponding to the permutations that
// are boundaries of the permutation corresponding to count.
// Populate Graph[count].
int g[gridsize];
vector<Generator> Graph(numgen); // Will hold the boundary data. This is VERY RAM intensive. Could be improved.
//cout << "Allocating " << ((sizeof(Generator)*numgen)/1028) << "KB of memory for the boundary graph (more will be needed).\n";
//cout << "Iterating through " << numgen << " generators to compute boundaries...\n";
int edges=0;
int count=0; // Loop through generators... change the loop for different gridsize
for(g[0]=0; g[0]<gridsize; g[0]++) {
for(g[1]=0; g[1]<gridsize; g[1]++) { if (g[1]==g[0]) continue;
for(g[2]=0; g[2]<gridsize; g[2]++) { if (g[2]==g[1] || g[2]==g[0]) continue;
for(g[3]=0; g[3]<gridsize; g[3]++) { if (g[3]==g[2] || g[3]==g[1] || g[3]==g[0]) continue;
for(g[4]=0; g[4]<gridsize; g[4]++) { if (g[4]==g[3] || g[4]==g[2] || g[4]==g[1] || g[4]==g[0]) continue;
for(g[5]=0; g[5]<gridsize; g[5]++) { if (g[5]==g[4] || g[5]==g[3] || g[5]==g[2] || g[5]==g[1] || g[5]==g[0]) continue;
for(g[6]=0; g[6]<gridsize; g[6]++) { if (g[6]==g[5] || g[6]==g[4] || g[6]==g[3] || g[6]==g[2] || g[6]==g[1] || g[6]==g[0]) continue;
for(g[7]=0; g[7]<gridsize; g[7]++) { if (g[7]==g[6] || g[7]==g[5] || g[7]==g[4] || g[7]==g[3] || g[7]==g[2] || g[7]==g[1] || g[7]==g[0]) continue;
for(g[8]=0; g[8]<gridsize; g[8]++) { if (g[8]==g[7] || g[8]==g[6] || g[8]==g[5] || g[8]==g[4] || g[8]==g[3] || g[8]==g[2] || g[8]==g[1] || g[8]==g[0]) continue;
for(g[9]=0; g[9]<gridsize; g[9]++) { if (g[9]==g[8] || g[9]==g[7] || g[9]==g[6] || g[9]==g[5] || g[9]==g[4] || g[9]==g[3] || g[9]==g[2] || g[9]==g[1] || g[9]==g[0]) continue;
for(g[10]=0; g[10]<gridsize; g[10]++) { if (g[10]==g[9] || g[10]==g[8] || g[10]==g[7] || g[10]==g[6] || g[10]==g[5] || g[10]==g[4] || g[10]==g[3] || g[10]==g[2] || g[10]==g[1] || g[10]==g[0]) continue;
int AGrading = AShift;
for(int i=0; i<gridsize; i++) AGrading -= WN[i][g[i]];
if (AGrading < 0) { Graph[count].alive=0; count++; continue; }
bool firstrect;
bool secondrect;
for(int i=0; i<gridsize; i++) {
for(int j=i+1; j<gridsize; j++) {
if(g[i]<g[j]) {
firstrect = Rectangles[i][g[i]][j][g[j]][0];
for(int k=i+1; k<j && firstrect; k++) {
if(g[i] < g[k] && g[k] < g[j]) firstrect=0;
}
secondrect = Rectangles[i][g[i]][j][g[j]][1];
for(int k=0; k<i && secondrect; k++) {
if(g[k]<g[i] || g[k] > g[j]) secondrect=0;
}
for(int k=j+1; k<gridsize && secondrect; k++) {
if(g[k]<g[i] || g[k] > g[j]) secondrect=0;
}
}
if(g[j]<g[i]) {
firstrect = Rectangles[i][g[j]][j][g[i]][2];
for(int k=i+1; k<j && firstrect; k++) {
if(g[k]<g[j] || g[k] > g[i]) firstrect=0;
}
secondrect = Rectangles[i][g[j]][j][g[i]][3];
for(int k=0; k<i && secondrect; k++) {
if(g[k]>g[j] && g[k]<g[i]) secondrect=0;
}
for(int k=j+1; k<gridsize && secondrect; k++) {
if(g[k]>g[j] && g[k]<g[i]) secondrect=0;
}
}
if(firstrect != secondrect) { // Exactly one rectangle is a boundary
int gij [gridsize];
for(int k=0; k<i; k++) {
gij[k] = g[k];
}
gij[i]=g[j];
for(int k=i+1; k<j; k++) {
gij[k]=g[k];
}
gij[j] = g[i];
for(int k=j+1; k<gridsize; k++) {
gij[k] = g[k];
}
int indexgij = Index(gij);
Graph[count].out.push_back(indexgij);
Graph[indexgij].in.push_back(Index(g));
edges++;
}
}
}
count++;
// if (count % 500000 == 0) cout << "Finished " << count << " generators.\n";
}}}}}}}}}}}
//cout << "Done computing the graph. Total edges (boundaries): " << edges << ".\n";
// Kill all the edges in the graph.
// No live generator should ever have a dead generator on its "out" list
//cout << "Killing edges in the graph...\n";
for(int i=0; i<numgen; i++) {
//if(i % 500000 == 1 && i > 1) cout << "Finished " << i-1 << " generators.\n";
if( (!Graph[i].alive) || Graph[i].out.size()==0) continue;
int target = Graph[i].out.front(); // We plan to delete the edge from i to target...
//cout << "Plan to delete edge from " << i << " to " << target << "\n";
// For every m with i in dm, remove i from dm
for(list<int>::iterator j=Graph[i].in.begin(); j!=Graph[i].in.end(); j++) {
if(Graph[*j].alive) Graph[*j].out.remove(i);
}
Graph[i].alive = 0;
// For every m with target in dm adjust dm appropriately
for(list<int>::iterator j= Graph[ target ].in.begin(); j != Graph[ target ].in.end(); j++) {
if( !Graph[*j].alive ) continue;
for(list<int>::iterator k = Graph[i].out.begin(); k != Graph[i].out.end(); k++) {
// Search for *k in the boundary of *j
// If found, remove it; if not, add it to the boundary of *j
// cout << "Searching for " << *k << " in out list of " << *j << "\n";
list<int>::iterator search = find( Graph[*j].out.begin(), Graph[*j].out.end(), *k);
if( search != Graph[*j].out.end() ) {
//cout << "Found it. Erasing " << *k << " from out list of " << *j << " and " << *j << " from the in list of " << *k << ".\n";
Graph[ *j ].out.erase( search );
if( *k != target) Graph[ *k ].in.remove( *j );
}
else {
//cout << "Didn't find it... adding " << *k << " to out list of " << *j << " and " << *j << " to the in list of " << *k << ".\n";
Graph[*j].out.push_back(*k);
Graph[*k].in.push_back(*j);
}
}
}
// For each a in di, remove i from the in list of a
for(list<int>::iterator j=Graph[i].out.begin(); j != Graph[i].out.end(); j++) Graph[*j].in.remove(i);
Graph[target].alive = 0;
Graph[target].out.clear();
Graph[target].in.clear();
Graph[i].out.clear();
Graph[i].in.clear();
//PrintGraph( Graph);
}
int HomologyRanks [60][60]; // HomologyRanks[i][j] will hold rank of homology Maslov grading=i-30 and Alexander grading j-30
for(int a=0; a<60; a++) { for(int m=0; m<60; m++) HomologyRanks[a][m]=0; }
count=0; // Loop through generators...
for(g[0]=0; g[0]<gridsize; g[0]++) {
for(g[1]=0; g[1]<gridsize; g[1]++) { if (g[1]==g[0]) continue;
for(g[2]=0; g[2]<gridsize; g[2]++) { if (g[2]==g[1] || g[2]==g[0]) continue;
for(g[3]=0; g[3]<gridsize; g[3]++) { if (g[3]==g[2] || g[3]==g[1] || g[3]==g[0]) continue;
for(g[4]=0; g[4]<gridsize; g[4]++) { if (g[4]==g[3] || g[4]==g[2] || g[4]==g[1] || g[4]==g[0]) continue;
for(g[5]=0; g[5]<gridsize; g[5]++) { if (g[5]==g[4] || g[5]==g[3] || g[5]==g[2] || g[5]==g[1] || g[5]==g[0]) continue;
for(g[6]=0; g[6]<gridsize; g[6]++) { if (g[6]==g[5] || g[6]==g[4] || g[6]==g[3] || g[6]==g[2] || g[6]==g[1] || g[6]==g[0]) continue;
for(g[7]=0; g[7]<gridsize; g[7]++) { if (g[7]==g[6] || g[7]==g[5] || g[7]==g[4] || g[7]==g[3] || g[7]==g[2] || g[7]==g[1] || g[7]==g[0]) continue;
for(g[8]=0; g[8]<gridsize; g[8]++) { if (g[8]==g[7] || g[8]==g[6] || g[8]==g[5] || g[8]==g[4] || g[8]==g[3] || g[8]==g[2] || g[8]==g[1] || g[8]==g[0]) continue;
for(g[9]=0; g[9]<gridsize; g[9]++) { if (g[9]==g[8] || g[9]==g[7] || g[9]==g[6] || g[9]==g[5] || g[9]==g[4] || g[9]==g[3] || g[9]==g[2] || g[9]==g[1] || g[9]==g[0]) continue;
for(g[10]=0; g[10]<gridsize; g[10]++) { if (g[10]==g[9] || g[10]==g[8] || g[10]==g[7] || g[10]==g[6] || g[10]==g[5] || g[10]==g[4] || g[10]==g[3] || g[10]==g[2] || g[10]==g[1] || g[10]==g[0]) continue;
if(Graph[count].alive) { // This way we only compute Maslov for the surviving generators
int AGrading = AShift;
for(int x=0; x<gridsize; x++) AGrading -= WN[x][g[x]];
HomologyRanks[MaslovGrading(g)+30][AGrading-30]++;
}
count++;
}}}}}}}}}}}
int HFKRanks [60][60]; // HFKRanks[i][j] will hold rank of HFK^ in Maslov grading=i-30 and Alexander grading=j-30
for(int a=0; a<60; a++) { for(int m=0; m<60; m++) HFKRanks[a][m]=0; }
// Reproduce HFK^ from HFK^ \otimes K^{gridsize-1} in non-negative Alexander grading
for(int a=59; a>=0; a--) {
for(int m=59; m>=0; m--) {
if( HomologyRanks[m][a] > 0) {
HFKRanks[m][a] = HomologyRanks[m][a];
for(int i=0; i<=gridsize-1; i++) HomologyRanks[m-i][a-i] -= (HFKRanks[m][a] * Factorial(gridsize-1)) / (Factorial(i) * Factorial(gridsize-1-i));
}
}
}
// Use symmetry to fill up HFKRanks in negative Alexander gradings
for(int alex=-1; alex>=-9; alex--){
for(int mas=-20; mas < 12; mas++) {
HFKRanks[mas+30][alex+30] = HFKRanks[mas-2*alex+30 ][-alex+30];
}
}
// Print Results
cout << "Poincare polynomial of HFK^ is:\n";
bool first=1;
for(int a=-20; a<19; a++) {
for(int m=-20; m<19; m++) {
int rankam = HFKRanks[m+30][a+30];
if(rankam > 1 && (!first) && m != 0 && a != 0) cout << " + " << rankam << "q^{" << m << "}t^{" << a << "}";
if(rankam == 1 && (!first) && m != 0 && a != 0) cout << " + q^{" << m << "}t^{" << a << "}";
if(rankam > 1 && (!first) && m == 0 && a != 0) cout << " + " << rankam << "t^{" << a << "}";
if(rankam == 1 && (!first) && m == 0 && a != 0) cout << " + t^{" << a << "}";
if(rankam > 1 && (!first) && m != 0 && a == 0) cout << " + " << rankam << "q^{" << m << "}";
if(rankam == 1 && (!first) && m != 0 && a == 0) cout << " + q^{" << m << "}";
if(rankam > 1 && (!first) && m == 0 && a == 0) cout << " + " << rankam;
if(rankam == 1 && (!first) && m == 0 && a == 0) cout << " + 1";
if(rankam > 1 && (first) && m != 0 && a != 0) {cout << rankam << "q^{" << m << "}t^{" << a << "}"; first=0;}
if(rankam == 1 && (first) && m != 0 && a != 0) {cout << "q^{" << m << "}t^{" << a << "}"; first=0;}
if(rankam > 1 && (first) && m == 0 && a != 0) {cout << rankam << "t^{" << a << "}"; first=0;}
if(rankam == 1 && (first) && m == 0 && a != 0) {cout << "t^{" << a << "}"; first=0;}
if(rankam > 1 && (first) && m != 0 && a == 0) {cout << rankam << "q^{" << m << "}"; first=0;}
if(rankam == 1 && (first) && m != 0 && a == 0) {cout << "q^{" << m << "}"; first=0;}
if(rankam > 1 && (first) && m == 0 && a == 0) {cout << rankam; first=0;}
if(rankam == 1 && (first) && m == 0 && a == 0) {cout << "1"; first=0;}
}
}
cout << "\n";
time_t endtime = time(NULL);
cout << "Total time elapsed: " << (endtime-starttime) << " seconds.\n";
return 0;
}
// Class Functions
Generator::Generator(){alive=1;};
Generator::~Generator(){};
// Actual Functions
int Index(int y []) {
int index=0;
for(int i=0; i<gridsize; i++) {
int shiftati = y[i];
for(int j=0; j<i; j++) {
if(y[i] > y[j]) shiftati--;
}
index += shiftati * Factorial(gridsize-i-1);
}
return index;
}
int WindingNumber(int x, int y){ // Return winding number around (x,y)
int ret=0;
for(int i=0; i<x; i++) {
if ((black[i] >= y) && (white[i] < y)) ret++;
if ((white[i] >= y) && (black[i] < y)) ret--;
}
return ret;
}
int MaslovGrading(int y []) {
// Use the formula:
// 4M(y) = 4M(white)+4P_y(R_{y, white})+4P_{white}(R_{y, white})-8W(R_{y, white})
// = 4-4*gridsize+4P_y(R_{y, white})+4P_{x_0}(R_{y, white})-8W(R_{y, white})
int P=4-4*gridsize; // Four times the Maslov grading
for(int i=0; i<gridsize; i++) {
// Calculate incidence number R_{y x_0}.S for each of the four
// squares S having (i,white[i]) as a corner and each of the
// four squares having (i,y[i]) as a corner and shift P appropriately
for(int j=0; j<=i; j++) { // Squares whose BL corners are (i,white[i]) and (i,y[i])
if ((white[j] > white[i]) && (y[j] <= white[i])) P-=7; // because of the -8W(R_{y, white}) contribution
if ((y[j] > white[i]) && (white[j] <= white[i])) P+=7;
if ((white[j] > y[i]) && (y[j] <= y[i])) P++;
if ((y[j] > y[i]) && (white[j] <= y[i])) P--;
}
for(int j=0; j<=((i-1)% gridsize); j++) { // Squares whose BR corners are (i,white[i]) and (i,y[i]) (mod gridsize)
if ((white[j] > white[i]) && (y[j] <= white[i])) P++;
if ((y[j] > white[i]) && (white[j] <= white[i])) P--;
if ((white[j] > y[i]) && (y[j] <= y[i])) P++;
if ((y[j] > y[i]) && (white[j] <= y[i])) P--;
}
for(int j=0; j<=((i-1) % gridsize); j++) { // Squares whose TR corners are...
if ((white[j] > ((white[i]-1) % gridsize)) && (y[j] <= ((white[i]-1) % gridsize))) P++;
if ((y[j] > ((white[i]-1) % gridsize) ) && (white[j] <= ((white[i]-1) % gridsize))) P--;
if ((white[j] > ((y[i]-1) % gridsize)) && (y[j] <= ((y[i]-1) % gridsize))) P++;
if ((y[j] > ((y[i]-1) % gridsize) ) && (white[j] <= ((y[i]-1) % gridsize))) P--;
}
for(int j=0; j<=i; j++) { // Squares whose TL corners are...
if ((white[j] > ((white[i]-1) % gridsize)) && (y[j] <= ((white[i]-1) % gridsize))) P++;
if ((y[j] > ((white[i]-1) % gridsize) ) && (white[j] <= ((white[i]-1) % gridsize))) P--;
if ((white[j] > ((y[i]-1) % gridsize)) && (y[j] <= ((y[i]-1) % gridsize))) P++;
if ((y[j] > ((y[i]-1) % gridsize) ) && (white[j] <= ((y[i]-1) % gridsize))) P--;
}
}
return (P/4);
}
int Factorial(int n) {
switch(n) {
case 0: return 1;
case 1: return 1;
case 2: return 2;
case 3: return 6;
case 4: return 24;
case 5: return 120;
case 6: return 720;
case 7: return 5040;
case 8: return 40320;
case 9: return 362880;
case 10: return 3628800;
case 11: return 39916800;
default: return (n*Factorial(n-1));
}
}
bool RectDotFree(int xll, int yll, int xur, int yur, int which) {
bool dotfree = 1;
switch (which) {
case 0:
for(int x=xll; x<xur && dotfree; x++) {
if (white[x] >= yll && white[x] < yur) dotfree = 0;
if (black[x] >= yll && black[x] < yur) dotfree = 0;
}
return dotfree;
case 1:
for(int x=0; x<xll && dotfree; x++) {
if (white[x] < yll || white[x] >= yur) dotfree = 0;
if (black[x] < yll || black[x] >= yur) dotfree = 0;
}
for(int x=xur; x<gridsize && dotfree; x++) {
if (white[x] < yll || white[x] >= yur) dotfree = 0;
if (black[x] < yll || black[x] >= yur) dotfree = 0;
}
return dotfree;
case 2:
for(int x=xll; x<xur && dotfree; x++) {
if (white[x] < yll || white[x] >= yur) dotfree = 0;
if (black[x] < yll || black[x] >= yur) dotfree = 0;
}
return dotfree;
case 3:
for(int x=0; x<xll && dotfree; x++) {
if (white[x] >= yll && white[x] < yur) dotfree = 0;
if (black[x] >= yll && black[x] < yur) dotfree = 0;
}
for(int x=xur; x<gridsize && dotfree; x++) {
if (white[x] >= yll && white[x] < yur) dotfree = 0;
if (black[x] >= yll && black[x] < yur) dotfree = 0;
}
return dotfree;
}
return 0; //Error!
}
void PrintGraph(vector<Generator> & G) { // This is diagnostic only
for(int i=0; i<G.size(); i++) {
if(!G[i].alive) continue;
cout << i << " in=";
for(list<int>::iterator j=G[i].in.begin(); j != G[i].in.end(); j++) {
cout << *j << " ";
}
cout << "out=";
for(list<int>::iterator j=G[i].out.begin(); j != G[i].out.end(); j++) {
cout << *j << " ";
}
cout << "\n";
}
}
bool ValidGrid() {
int numwhite=0;
int numblack=0;
for(int i=0; i<gridsize; i++) {
for(int j=0; j<gridsize; j++) {
if (white[j]==i) numwhite++;
if (black[j]==i) numblack++;
}
if (numwhite != 1 || numblack != 1) {
std::cout << "\nInvalid Grid!\n";
return 0;
}
numwhite=0;
numblack=0;
}
return 1;
}
| [
"benjamin.lip@c2f0229c-37c9-6e89-a4ff-2bb24d9bb920"
]
| [
[
[
1,
700
]
]
]
|
f5c4cb6744f0bee5a145fac45cdf9b6cb61b7e66 | 59166d9d1eea9b034ac331d9c5590362ab942a8f | /TextureShaderTile/KeyboardHandler.cpp | cb427d04bc2d2fd3846ee0eb237403a3eb3ba0ed | []
| no_license | seafengl/osgtraining | 5915f7b3a3c78334b9029ee58e6c1cb54de5c220 | fbfb29e5ae8cab6fa13900e417b6cba3a8c559df | refs/heads/master | 2020-04-09T07:32:31.981473 | 2010-09-03T15:10:30 | 2010-09-03T15:10:30 | 40,032,354 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 3,235 | cpp | #include "KeyboardHandler.h"
#include <osgViewer/Viewer>
#include <iostream>
KeyboardHandler::KeyboardHandler() : m_fOffsetX( 0.0f )
, m_fOffsetY( 0.0f )
, m_fScaleX( 0.0f )
, m_fScaleY( 0.0f )
, m_fOffsetScaleX( 0.0f )
, m_fOffsetScaleY( 0.0f )
{
}
KeyboardHandler::~KeyboardHandler()
{
}
bool KeyboardHandler::handle( const osgGA::GUIEventAdapter& ea,
osgGA::GUIActionAdapter& aa )
{
osgViewer::Viewer* viewer =
dynamic_cast<osgViewer::Viewer*>( &aa );
if (!viewer)
return( false );
switch(ea.getEventType())
{
case(osgGA::GUIEventAdapter::KEYDOWN):
{
if ( ea.getKey()=='o' )
{
m_fOffsetX += 1.0;
m_OffsetX->set( m_fOffsetX / 32768.0f );
std::cout << "m_fOffsetX: " << m_fOffsetX << "\n";
}
else
if ( ea.getKey()=='O' )
{
m_fOffsetX -= 1.0;
m_OffsetX->set( m_fOffsetX / 32768.0f );
std::cout << "m_fOffsetX: " << m_fOffsetX << "\n";
}
else
if ( ea.getKey()=='p' )
{
m_fOffsetY += 1.0;
m_OffsetY->set( m_fOffsetY / 8196.0f );
std::cout << "m_fOffsetY: " << m_fOffsetY << "\n";
}
else
if ( ea.getKey()=='P' )
{
m_fOffsetY -= 1.0;
m_OffsetY->set( m_fOffsetY / 8196.0f );
std::cout << "m_fOffsetY: " << m_fOffsetY << "\n";
}
else
if ( ea.getKey()=='x' )
{
m_fScaleX += 1.0;
m_ScaleX->set( 1.0f + m_fScaleX / 8196.0f );
std::cout << "m_fScaleX: " << m_fScaleX << "\n";
}
else
if ( ea.getKey()=='X' )
{
m_fScaleX -= 1.0;
m_ScaleX->set( 1.0f + m_fScaleX / 8196.0f );
std::cout << "m_fScaleX: " << m_fScaleX << "\n";
}
else
if ( ea.getKey()=='c' )
{
m_fScaleY += 1.0;
m_ScaleY->set( 1.0f + m_fScaleY / 8196.0f );
std::cout << "m_fScaleY: " << m_fScaleY << "\n";
}
else
if ( ea.getKey()=='C' )
{
m_fScaleY -= 1.0;
m_ScaleY->set( 1.0f + m_fScaleY / 8196.0f );
std::cout << "m_fScaleY: " << m_fScaleY << "\n";
}
else
if ( ea.getKey()=='v' )
{
m_fOffsetScaleX += 1.0;
m_OffsetScaleX->set( m_fOffsetScaleX / 1024.0f );
std::cout << "m_fOffsetScaleX: " << m_fOffsetScaleX << "\n";
}
else
if ( ea.getKey()=='V' )
{
m_fOffsetScaleX -= 1.0;
m_OffsetScaleX->set( m_fOffsetScaleX / 1024.0f );
std::cout << "m_fOffsetScaleX: " << m_fOffsetScaleX << "\n";
}
else
if ( ea.getKey()=='b' )
{
m_fOffsetScaleY += 1.0;
m_OffsetScaleY->set( m_fOffsetScaleY / 1024.0f );
std::cout << "m_fOffsetScaleY: " << m_fOffsetScaleY << "\n";
}
else
if ( ea.getKey()=='B' )
{
m_fOffsetScaleY -= 1.0;
m_OffsetScaleY->set( m_fOffsetScaleY / 1024.0f );
std::cout << "m_fOffsetScaleY: " << m_fOffsetScaleY << "\n";
}
return false;
}
default:
return false;
}
return false;
} | [
"asmzx79@3290fc28-3049-11de-8daa-cfecb5f7ff5b"
]
| [
[
[
1,
126
]
]
]
|
b33b573e82788143e742611c2350fcc0c31970d4 | 3c4f5bd6d7ac3878c181fb05ab41c1d755ddf343 | /Asci.cpp | 85eee0d4c3718d1ca24da4ec912957dacd08700a | []
| no_license | imcooder/public | 1078df18c1459e67afd1200346dd971ea3b71933 | be947923c6e2fbd9c993a41115ace3e32dad74bf | refs/heads/master | 2021-05-28T08:43:00.027020 | 2010-07-24T07:39:51 | 2010-07-24T07:39:51 | 32,301,120 | 2 | 1 | null | null | null | null | GB18030 | C++ | false | false | 2,199 | cpp | #include "StdAfx.h"
#include "Asci.h"
//是否是数字
BOOL WINAPI Asci_IsDigit( LONG ch)
{
if (ch < 0)
ch += 256;
if( ch > '9' || ch < '0' )
return 0;
return 1;
}
//是否是16进制数学字符(即0-9 A-F a-f )
BOOL WINAPI Asci_IsXDigit( LONG ch)
{
if (ch < 0)
ch += 256;
if( ( ch >= '0' && ch <= '9' )//Digit
|| ( ch >= 'A' && ch <= 'F' )//upper hex digit
|| ( ch >= 'a' && ch <= 'f' ) )//lower hex digit
return 1;
return 0;
}
//是否控制字符
BOOL WINAPI Asci_iscntrl( LONG ch)
{
if (ch < 0)
ch += 256;
//if (ptConstPara->m_abCharaAttribute[ch] & 0x20)
// return 1;
//else
return 0;
}
//是否空格、跳格符(制表符)或换行符
BOOL WINAPI Asci_isspace( LONG ch)
{
if (ch < 0)
ch += 256;
//if (ptConstPara->m_abCharaAttribute[ch] & 0x40)
// return 1;
//else
return 0;
}
//是否是大写字母
BOOL WINAPI Asci_IsUpper( LONG ch)
{
if (ch < 0)
ch += 256;
if ( ch >= 'A' && ch <= 'Z' )
return 1;
return 0;
}
//是否是小写字母
BOOL WINAPI Asci_IsLower( LONG ch)
{
if (ch < 0)
ch += 256;
if ( ch >= 'a' && ch <= 'z' )
return 1;
return 0;
}
//是否是字母
BOOL WINAPI Asci_IsAlpha( LONG ch)
{
if (ch < 0)
ch += 256;
if ( (ch >= 'A' && ch <= 'Z')
|| (ch >= 'a' && ch <= 'z') )
return 1;
return 0;
}
BOOL WINAPI Asci_IsPunctuation( LONG ch )
{
if (ch < 0x7F)
{
if (ch != TEXT('\t') && !Asci_IsAlpha(ch) && !Asci_IsDigit(ch))
{
return 1;
}
}
return 0;
}
WCHAR WINAPI Asci_HalfToFull( WCHAR wCharInput)
{
WCHAR wChar = wCharInput;
switch(wChar)
{
case TEXT(' '):
{
wChar = 0x3000;
}
break;
case TEXT('\t'):
{
wChar = TEXT('\t');
}
break;
default:
{
if (wChar <= 0x7F)
{
wChar = wChar + 0xFEE0;
}
}
break;
}
return wChar;
}
BOOL WINAPI Asci_IsBelongTo( WCHAR wChr, LPCWSTR pszCharSet)
{
if (!pszCharSet)
{
return FALSE;
}
LPWSTR pszPos = wcschr((LPWSTR)pszCharSet, wChr);
if (!pszPos)
{
return FALSE;
}
return TRUE;
}
BOOL WINAPI Asci_IsSpace( LONG ch )
{
return ch == TEXT(' ');
} | [
"jtxuee@716a2f10-c84c-11dd-bf7c-81814f527a11",
"[email protected]@716a2f10-c84c-11dd-bf7c-81814f527a11"
]
| [
[
[
1,
4
],
[
6,
15
],
[
17,
52
],
[
54,
63
],
[
65,
74
],
[
76,
84
]
],
[
[
5,
5
],
[
16,
16
],
[
53,
53
],
[
64,
64
],
[
75,
75
],
[
85,
142
]
]
]
|
9863b32dab99546794f33c718e9996d2cb381808 | d54d8b1bbc9575f3c96853e0c67f17c1ad7ab546 | /hlsdk-2.3-p3/multiplayer/dmc/dlls/nodes.cpp | 98d7a1235541e477d838b7ea0b4b8c4c2aa399fb | []
| no_license | joropito/amxxgroup | 637ee71e250ffd6a7e628f77893caef4c4b1af0a | f948042ee63ebac6ad0332f8a77393322157fa8f | refs/heads/master | 2021-01-10T09:21:31.449489 | 2010-04-11T21:34:27 | 2010-04-11T21:34:27 | 47,087,485 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 106,640 | cpp | /***
*
* Copyright (c) 1996-2002, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* This source code contains proprietary and confidential information of
* Valve LLC and its suppliers. Access to this code is restricted to
* persons who have executed a written SDK license with Valve. Any access,
* use or distribution of this code by or to any unlicensed person is illegal.
*
****/
//=========================================================
// nodes.cpp - AI node tree stuff.
//=========================================================
#include "extdll.h"
#include "util.h"
#include "cbase.h"
#include "monsters.h"
#include "nodes.h"
#include "animation.h"
#include "doors.h"
#ifndef _WIN32
#include <unistd.h>
#define CreateDirectory(p, n) mkdir(p, 0777)
#endif // _WIN32
#define HULL_STEP_SIZE 16// how far the test hull moves on each step
#define NODE_HEIGHT 8 // how high to lift nodes off the ground after we drop them all (make stair/ramp mapping easier)
// to help eliminate node clutter by level designers, this is used to cap how many other nodes
// any given node is allowed to 'see' in the first stage of graph creation "LinkVisibleNodes()".
#define MAX_NODE_INITIAL_LINKS 128
#define MAX_NODES 1024
extern DLL_GLOBAL edict_t *g_pBodyQueueHead;
Vector VecBModelOrigin( entvars_t* pevBModel );
CGraph WorldGraph;
LINK_ENTITY_TO_CLASS( info_node, CNodeEnt );
LINK_ENTITY_TO_CLASS( info_node_air, CNodeEnt );
//=========================================================
// CGraph - InitGraph - prepares the graph for use. Frees any
// memory currently in use by the world graph, NULLs
// all pointers, and zeros the node count.
//=========================================================
void CGraph :: InitGraph( void)
{
// Make the graph unavailable
//
m_fGraphPresent = FALSE;
m_fGraphPointersSet = FALSE;
m_fRoutingComplete = FALSE;
// Free the link pool
//
if ( m_pLinkPool )
{
free ( m_pLinkPool );
m_pLinkPool = NULL;
}
// Free the node info
//
if ( m_pNodes )
{
free ( m_pNodes );
m_pNodes = NULL;
}
if ( m_di )
{
free ( m_di );
m_di = NULL;
}
// Free the routing info.
//
if ( m_pRouteInfo )
{
free ( m_pRouteInfo );
m_pRouteInfo = NULL;
}
if (m_pHashLinks)
{
free(m_pHashLinks);
m_pHashLinks = NULL;
}
// Zero node and link counts
//
m_cNodes = 0;
m_cLinks = 0;
m_nRouteInfo = 0;
m_iLastActiveIdleSearch = 0;
m_iLastCoverSearch = 0;
}
//=========================================================
// CGraph - AllocNodes - temporary function that mallocs a
// reasonable number of nodes so we can build the path which
// will be saved to disk.
//=========================================================
int CGraph :: AllocNodes ( void )
{
// malloc all of the nodes
WorldGraph.m_pNodes = (CNode *)calloc ( sizeof ( CNode ), MAX_NODES );
// could not malloc space for all the nodes!
if ( !WorldGraph.m_pNodes )
{
ALERT ( at_aiconsole, "**ERROR**\nCouldn't malloc %d nodes!\n", WorldGraph.m_cNodes );
return FALSE;
}
return TRUE;
}
//=========================================================
// CGraph - LinkEntForLink - sometimes the ent that blocks
// a path is a usable door, in which case the monster just
// needs to face the door and fire it. In other cases, the
// monster needs to operate a button or lever to get the
// door to open. This function will return a pointer to the
// button if the monster needs to hit a button to open the
// door, or returns a pointer to the door if the monster
// need only use the door.
//
// pNode is the node the monster will be standing on when it
// will need to stop and trigger the ent.
//=========================================================
entvars_t* CGraph :: LinkEntForLink ( CLink *pLink, CNode *pNode )
{
edict_t *pentSearch;
edict_t *pentTrigger;
entvars_t *pevTrigger;
entvars_t *pevLinkEnt;
TraceResult tr;
pevLinkEnt = pLink->m_pLinkEnt;
if ( !pevLinkEnt )
return NULL;
pentSearch = NULL;// start search at the top of the ent list.
if ( FClassnameIs ( pevLinkEnt, "func_door" ) || FClassnameIs ( pevLinkEnt, "func_door_rotating" ) )
{
///!!!UNDONE - check for TOGGLE or STAY open doors here. If a door is in the way, and is
// TOGGLE or STAY OPEN, even monsters that can't open doors can go that way.
if ( ( pevLinkEnt->spawnflags & SF_DOOR_USE_ONLY ) )
{// door is use only, so the door is all the monster has to worry about
return pevLinkEnt;
}
while ( 1 )
{
pentTrigger = FIND_ENTITY_BY_TARGET ( pentSearch, STRING( pevLinkEnt->targetname ) );// find the button or trigger
if ( FNullEnt( pentTrigger ) )
{// no trigger found
// right now this is a problem among auto-open doors, or any door that opens through the use
// of a trigger brush. Trigger brushes have no models, and don't show up in searches. Just allow
// monsters to open these sorts of doors for now.
return pevLinkEnt;
}
pentSearch = pentTrigger;
pevTrigger = VARS( pentTrigger );
if ( FClassnameIs(pevTrigger, "func_button") || FClassnameIs(pevTrigger, "func_rot_button" ) )
{// only buttons are handled right now.
// trace from the node to the trigger, make sure it's one we can see from the node.
// !!!HACKHACK Use bodyqueue here cause there are no ents we really wish to ignore!
UTIL_TraceLine ( pNode->m_vecOrigin, VecBModelOrigin( pevTrigger ), ignore_monsters, g_pBodyQueueHead, &tr );
if ( VARS(tr.pHit) == pevTrigger )
{// good to go!
return VARS( tr.pHit );
}
}
}
}
else
{
ALERT ( at_aiconsole, "Unsupported PathEnt:\n'%s'\n", STRING ( pevLinkEnt->classname ) );
return NULL;
}
}
//=========================================================
// CGraph - HandleLinkEnt - a brush ent is between two
// nodes that would otherwise be able to see each other.
// Given the monster's capability, determine whether
// or not the monster can go this way.
//=========================================================
int CGraph :: HandleLinkEnt ( int iNode, entvars_t *pevLinkEnt, int afCapMask, NODEQUERY queryType )
{
edict_t *pentWorld;
CBaseEntity *pDoor;
TraceResult tr;
if ( !m_fGraphPresent || !m_fGraphPointersSet )
{// protect us in the case that the node graph isn't available
ALERT ( at_aiconsole, "Graph not ready!\n" );
return FALSE;
}
if ( FNullEnt ( pevLinkEnt ) )
{
ALERT ( at_aiconsole, "dead path ent!\n" );
return TRUE;
}
pentWorld = NULL;
// func_door
if ( FClassnameIs( pevLinkEnt, "func_door" ) || FClassnameIs( pevLinkEnt, "func_door_rotating" ) )
{// ent is a door.
pDoor = ( CBaseEntity::Instance( pevLinkEnt ) );
if ( ( pevLinkEnt->spawnflags & SF_DOOR_USE_ONLY ) )
{// door is use only.
if ( ( afCapMask & bits_CAP_OPEN_DOORS ) )
{// let monster right through if he can open doors
return TRUE;
}
else
{
// monster should try for it if the door is open and looks as if it will stay that way
if ( pDoor->GetToggleState()== TS_AT_TOP && ( pevLinkEnt->spawnflags & SF_DOOR_NO_AUTO_RETURN ) )
{
return TRUE;
}
return FALSE;
}
}
else
{// door must be opened with a button or trigger field.
// monster should try for it if the door is open and looks as if it will stay that way
if ( pDoor->GetToggleState() == TS_AT_TOP && ( pevLinkEnt->spawnflags & SF_DOOR_NO_AUTO_RETURN ) )
{
return TRUE;
}
if ( ( afCapMask & bits_CAP_OPEN_DOORS ) )
{
if ( !( pevLinkEnt->spawnflags & SF_DOOR_NOMONSTERS ) || queryType == NODEGRAPH_STATIC )
return TRUE;
}
return FALSE;
}
}
// func_breakable
else if ( FClassnameIs( pevLinkEnt, "func_breakable" ) && queryType == NODEGRAPH_STATIC )
{
return TRUE;
}
else
{
ALERT ( at_aiconsole, "Unhandled Ent in Path %s\n", STRING( pevLinkEnt->classname ) );
return FALSE;
}
return FALSE;
}
#if 0
//=========================================================
// FindNearestLink - finds the connection (line) nearest
// the given point. Returns FALSE if fails, or TRUE if it
// has stuffed the index into the nearest link pool connection
// into the passed int pointer, and a BOOL telling whether or
// not the point is along the line into the passed BOOL pointer.
//=========================================================
int CGraph :: FindNearestLink ( const Vector &vecTestPoint, int *piNearestLink, BOOL *pfAlongLine )
{
int i, j;// loops
int iNearestLink;// index into the link pool, this is the nearest node at any time.
float flMinDist;// the distance of of the nearest case so far
float flDistToLine;// the distance of the current test case
BOOL fCurrentAlongLine;
BOOL fSuccess;
//float flConstant;// line constant
Vector vecSpot1, vecSpot2;
Vector2D vec2Spot1, vec2Spot2, vec2TestPoint;
Vector2D vec2Normal;// line normal
Vector2D vec2Line;
TraceResult tr;
iNearestLink = -1;// prepare for failure
fSuccess = FALSE;
flMinDist = 9999;// anything will be closer than this
// go through all of the nodes, and each node's connections
int cSkip = 0;// how many links proper pairing allowed us to skip
int cChecked = 0;// how many links were checked
for ( i = 0 ; i < m_cNodes ; i++ )
{
vecSpot1 = m_pNodes[ i ].m_vecOrigin;
if ( m_pNodes[ i ].m_cNumLinks <= 0 )
{// this shouldn't happen!
ALERT ( at_aiconsole, "**Node %d has no links\n", i );
continue;
}
for ( j = 0 ; j < m_pNodes[ i ].m_cNumLinks ; j++ )
{
/*
!!!This optimization only works when the node graph consists of properly linked pairs.
if ( INodeLink ( i, j ) <= i )
{
// since we're going through the nodes in order, don't check
// any connections whose second node is lower in the list
// than the node we're currently working with. This eliminates
// redundant checks.
cSkip++;
continue;
}
*/
vecSpot2 = PNodeLink ( i, j )->m_vecOrigin;
// these values need a little attention now and then, or sometimes ramps cause trouble.
if ( fabs ( vecSpot1.z - vecTestPoint.z ) > 48 && fabs ( vecSpot2.z - vecTestPoint.z ) > 48 )
{
// if both endpoints of the line are 32 units or more above or below the monster,
// the monster won't be able to get to them, so we do a bit of trivial rejection here.
// this may change if monsters are allowed to jump down.
//
// !!!LATER: some kind of clever X/Y hashing should be used here, too
continue;
}
// now we have two endpoints for a line segment that we've not already checked.
// since all lines that make it this far are within -/+ 32 units of the test point's
// Z Plane, we can get away with doing the point->line check in 2d.
cChecked++;
vec2Spot1 = vecSpot1.Make2D();
vec2Spot2 = vecSpot2.Make2D();
vec2TestPoint = vecTestPoint.Make2D();
// get the line normal.
vec2Line = ( vec2Spot1 - vec2Spot2 ).Normalize();
vec2Normal.x = -vec2Line.y;
vec2Normal.y = vec2Line.x;
if ( DotProduct ( vec2Line, ( vec2TestPoint - vec2Spot1 ) ) > 0 )
{// point outside of line
flDistToLine = ( vec2TestPoint - vec2Spot1 ).Length();
fCurrentAlongLine = FALSE;
}
else if ( DotProduct ( vec2Line, ( vec2TestPoint - vec2Spot2 ) ) < 0 )
{// point outside of line
flDistToLine = ( vec2TestPoint - vec2Spot2 ).Length();
fCurrentAlongLine = FALSE;
}
else
{// point inside line
flDistToLine = fabs( DotProduct ( vec2TestPoint - vec2Spot2, vec2Normal ) );
fCurrentAlongLine = TRUE;
}
if ( flDistToLine < flMinDist )
{// just found a line nearer than any other so far
UTIL_TraceLine ( vecTestPoint, SourceNode( i, j ).m_vecOrigin, ignore_monsters, g_pBodyQueueHead, &tr );
if ( tr.flFraction != 1.0 )
{// crap. can't see the first node of this link, try to see the other
UTIL_TraceLine ( vecTestPoint, DestNode( i, j ).m_vecOrigin, ignore_monsters, g_pBodyQueueHead, &tr );
if ( tr.flFraction != 1.0 )
{// can't use this link, cause can't see either node!
continue;
}
}
fSuccess = TRUE;// we know there will be something to return.
flMinDist = flDistToLine;
iNearestLink = m_pNodes [ i ].m_iFirstLink + j;
*piNearestLink = m_pNodes[ i ].m_iFirstLink + j;
*pfAlongLine = fCurrentAlongLine;
}
}
}
/*
if ( fSuccess )
{
WRITE_BYTE(MSG_BROADCAST, SVC_TEMPENTITY);
WRITE_BYTE(MSG_BROADCAST, TE_SHOWLINE);
WRITE_COORD(MSG_BROADCAST, m_pNodes[ m_pLinkPool[ iNearestLink ].m_iSrcNode ].m_vecOrigin.x );
WRITE_COORD(MSG_BROADCAST, m_pNodes[ m_pLinkPool[ iNearestLink ].m_iSrcNode ].m_vecOrigin.y );
WRITE_COORD(MSG_BROADCAST, m_pNodes[ m_pLinkPool[ iNearestLink ].m_iSrcNode ].m_vecOrigin.z + NODE_HEIGHT);
WRITE_COORD(MSG_BROADCAST, m_pNodes[ m_pLinkPool[ iNearestLink ].m_iDestNode ].m_vecOrigin.x );
WRITE_COORD(MSG_BROADCAST, m_pNodes[ m_pLinkPool[ iNearestLink ].m_iDestNode ].m_vecOrigin.y );
WRITE_COORD(MSG_BROADCAST, m_pNodes[ m_pLinkPool[ iNearestLink ].m_iDestNode ].m_vecOrigin.z + NODE_HEIGHT);
}
*/
ALERT ( at_aiconsole, "%d Checked\n", cChecked );
return fSuccess;
}
#endif
int CGraph::HullIndex( const CBaseEntity *pEntity )
{
if ( pEntity->pev->movetype == MOVETYPE_FLY)
return NODE_FLY_HULL;
if ( pEntity->pev->mins == Vector( -12, -12, 0 ) )
return NODE_SMALL_HULL;
else if ( pEntity->pev->mins == VEC_HUMAN_HULL_MIN )
return NODE_HUMAN_HULL;
else if ( pEntity->pev->mins == Vector ( -32, -32, 0 ) )
return NODE_LARGE_HULL;
// ALERT ( at_aiconsole, "Unknown Hull Mins!\n" );
return NODE_HUMAN_HULL;
}
int CGraph::NodeType( const CBaseEntity *pEntity )
{
if ( pEntity->pev->movetype == MOVETYPE_FLY)
{
if (pEntity->pev->waterlevel != 0)
{
return bits_NODE_WATER;
}
else
{
return bits_NODE_AIR;
}
}
return bits_NODE_LAND;
}
// Sum up graph weights on the path from iStart to iDest to determine path length
float CGraph::PathLength( int iStart, int iDest, int iHull, int afCapMask )
{
float distance = 0;
int iNext;
int iMaxLoop = m_cNodes;
int iCurrentNode = iStart;
int iCap = CapIndex( afCapMask );
while (iCurrentNode != iDest)
{
if (iMaxLoop-- <= 0)
{
ALERT( at_console, "Route Failure\n" );
return 0;
}
iNext = NextNodeInRoute( iCurrentNode, iDest, iHull, iCap );
if (iCurrentNode == iNext)
{
//ALERT(at_aiconsole, "SVD: Can't get there from here..\n");
return 0;
}
int iLink;
HashSearch(iCurrentNode, iNext, iLink);
if (iLink < 0)
{
ALERT(at_console, "HashLinks is broken from %d to %d.\n", iCurrentNode, iDest);
return 0;
}
CLink &link = Link(iLink);
distance += link.m_flWeight;
iCurrentNode = iNext;
}
return distance;
}
// Parse the routing table at iCurrentNode for the next node on the shortest path to iDest
int CGraph::NextNodeInRoute( int iCurrentNode, int iDest, int iHull, int iCap )
{
int iNext = iCurrentNode;
int nCount = iDest+1;
char *pRoute = m_pRouteInfo + m_pNodes[ iCurrentNode ].m_pNextBestNode[iHull][iCap];
// Until we decode the next best node
//
while (nCount > 0)
{
char ch = *pRoute++;
//ALERT(at_aiconsole, "C(%d)", ch);
if (ch < 0)
{
// Sequence phrase
//
ch = -ch;
if (nCount <= ch)
{
iNext = iDest;
nCount = 0;
//ALERT(at_aiconsole, "SEQ: iNext/iDest=%d\n", iNext);
}
else
{
//ALERT(at_aiconsole, "SEQ: nCount + ch (%d + %d)\n", nCount, ch);
nCount = nCount - ch;
}
}
else
{
//ALERT(at_aiconsole, "C(%d)", *pRoute);
// Repeat phrase
//
if (nCount <= ch+1)
{
iNext = iCurrentNode + *pRoute;
if (iNext >= m_cNodes) iNext -= m_cNodes;
else if (iNext < 0) iNext += m_cNodes;
nCount = 0;
//ALERT(at_aiconsole, "REP: iNext=%d\n", iNext);
}
else
{
//ALERT(at_aiconsole, "REP: nCount - ch+1 (%d - %d+1)\n", nCount, ch);
nCount = nCount - ch - 1;
}
pRoute++;
}
}
return iNext;
}
//=========================================================
// CGraph - FindShortestPath
//
// accepts a capability mask (afCapMask), and will only
// find a path usable by a monster with those capabilities
// returns the number of nodes copied into supplied array
//=========================================================
int CGraph :: FindShortestPath ( int *piPath, int iStart, int iDest, int iHull, int afCapMask)
{
int iVisitNode;
int iCurrentNode;
int iNumPathNodes;
int iHullMask;
if ( !m_fGraphPresent || !m_fGraphPointersSet )
{// protect us in the case that the node graph isn't available or built
ALERT ( at_aiconsole, "Graph not ready!\n" );
return FALSE;
}
if ( iStart < 0 || iStart > m_cNodes )
{// The start node is bad?
ALERT ( at_aiconsole, "Can't build a path, iStart is %d!\n", iStart );
return FALSE;
}
if (iStart == iDest)
{
piPath[0] = iStart;
piPath[1] = iDest;
return 2;
}
// Is routing information present.
//
if (m_fRoutingComplete)
{
int iCap = CapIndex( afCapMask );
iNumPathNodes = 0;
piPath[iNumPathNodes++] = iStart;
iCurrentNode = iStart;
int iNext;
//ALERT(at_aiconsole, "GOAL: %d to %d\n", iStart, iDest);
// Until we arrive at the destination
//
while (iCurrentNode != iDest)
{
iNext = NextNodeInRoute( iCurrentNode, iDest, iHull, iCap );
if (iCurrentNode == iNext)
{
//ALERT(at_aiconsole, "SVD: Can't get there from here..\n");
return 0;
break;
}
if (iNumPathNodes >= MAX_PATH_SIZE)
{
//ALERT(at_aiconsole, "SVD: Don't return the entire path.\n");
break;
}
piPath[iNumPathNodes++] = iNext;
iCurrentNode = iNext;
}
//ALERT( at_aiconsole, "SVD: Path with %d nodes.\n", iNumPathNodes);
}
else
{
CQueuePriority queue;
switch( iHull )
{
case NODE_SMALL_HULL:
iHullMask = bits_LINK_SMALL_HULL;
break;
case NODE_HUMAN_HULL:
iHullMask = bits_LINK_HUMAN_HULL;
break;
case NODE_LARGE_HULL:
iHullMask = bits_LINK_LARGE_HULL;
break;
case NODE_FLY_HULL:
iHullMask = bits_LINK_FLY_HULL;
break;
}
// Mark all the nodes as unvisited.
//
for ( int i = 0; i < m_cNodes; i++)
{
m_pNodes[ i ].m_flClosestSoFar = -1.0;
}
m_pNodes[ iStart ].m_flClosestSoFar = 0.0;
m_pNodes[ iStart ].m_iPreviousNode = iStart;// tag this as the origin node
queue.Insert( iStart, 0.0 );// insert start node
while ( !queue.Empty() )
{
// now pull a node out of the queue
float flCurrentDistance;
iCurrentNode = queue.Remove(flCurrentDistance);
// For straight-line weights, the following Shortcut works. For arbitrary weights,
// it doesn't.
//
if (iCurrentNode == iDest) break;
CNode *pCurrentNode = &m_pNodes[ iCurrentNode ];
for ( i = 0 ; i < pCurrentNode->m_cNumLinks ; i++ )
{// run through all of this node's neighbors
iVisitNode = INodeLink ( iCurrentNode, i );
if ( ( m_pLinkPool[ m_pNodes[ iCurrentNode ].m_iFirstLink + i ].m_afLinkInfo & iHullMask ) != iHullMask )
{// monster is too large to walk this connection
//ALERT ( at_aiconsole, "fat ass %d/%d\n",m_pLinkPool[ m_pNodes[ iCurrentNode ].m_iFirstLink + i ].m_afLinkInfo, iMonsterHull );
continue;
}
// check the connection from the current node to the node we're about to mark visited and push into the queue
if ( m_pLinkPool[ m_pNodes[ iCurrentNode ].m_iFirstLink + i ].m_pLinkEnt != NULL )
{// there's a brush ent in the way! Don't mark this node or put it into the queue unless the monster can negotiate it
if ( !HandleLinkEnt ( iCurrentNode, m_pLinkPool[ m_pNodes[ iCurrentNode ].m_iFirstLink + i ].m_pLinkEnt, afCapMask, NODEGRAPH_STATIC ) )
{// monster should not try to go this way.
continue;
}
}
float flOurDistance = flCurrentDistance + m_pLinkPool[ m_pNodes[ iCurrentNode ].m_iFirstLink + i].m_flWeight;
if ( m_pNodes[ iVisitNode ].m_flClosestSoFar < -0.5
|| flOurDistance < m_pNodes[ iVisitNode ].m_flClosestSoFar - 0.001 )
{
m_pNodes[iVisitNode].m_flClosestSoFar = flOurDistance;
m_pNodes[iVisitNode].m_iPreviousNode = iCurrentNode;
queue.Insert ( iVisitNode, flOurDistance );
}
}
}
if ( m_pNodes[iDest].m_flClosestSoFar < -0.5 )
{// Destination is unreachable, no path found.
return 0;
}
// the queue is not empty
// now we must walk backwards through the m_iPreviousNode field, and count how many connections there are in the path
iCurrentNode = iDest;
iNumPathNodes = 1;// count the dest
while ( iCurrentNode != iStart )
{
iNumPathNodes++;
iCurrentNode = m_pNodes[ iCurrentNode ].m_iPreviousNode;
}
iCurrentNode = iDest;
for ( i = iNumPathNodes - 1 ; i >= 0 ; i-- )
{
piPath[ i ] = iCurrentNode;
iCurrentNode = m_pNodes [ iCurrentNode ].m_iPreviousNode;
}
}
#if 0
if (m_fRoutingComplete)
{
// This will draw the entire path that was generated for the monster.
for ( int i = 0 ; i < iNumPathNodes - 1 ; i++ )
{
MESSAGE_BEGIN( MSG_BROADCAST, SVC_TEMPENTITY );
WRITE_BYTE( TE_SHOWLINE);
WRITE_COORD( m_pNodes[ piPath[ i ] ].m_vecOrigin.x );
WRITE_COORD( m_pNodes[ piPath[ i ] ].m_vecOrigin.y );
WRITE_COORD( m_pNodes[ piPath[ i ] ].m_vecOrigin.z + NODE_HEIGHT );
WRITE_COORD( m_pNodes[ piPath[ i + 1 ] ].m_vecOrigin.x );
WRITE_COORD( m_pNodes[ piPath[ i + 1 ] ].m_vecOrigin.y );
WRITE_COORD( m_pNodes[ piPath[ i + 1 ] ].m_vecOrigin.z + NODE_HEIGHT );
MESSAGE_END();
}
}
#endif
#if 0 // MAZE map
MESSAGE_BEGIN( MSG_BROADCAST, SVC_TEMPENTITY );
WRITE_BYTE( TE_SHOWLINE);
WRITE_COORD( m_pNodes[ 4 ].m_vecOrigin.x );
WRITE_COORD( m_pNodes[ 4 ].m_vecOrigin.y );
WRITE_COORD( m_pNodes[ 4 ].m_vecOrigin.z + NODE_HEIGHT );
WRITE_COORD( m_pNodes[ 9 ].m_vecOrigin.x );
WRITE_COORD( m_pNodes[ 9 ].m_vecOrigin.y );
WRITE_COORD( m_pNodes[ 9 ].m_vecOrigin.z + NODE_HEIGHT );
MESSAGE_END();
#endif
return iNumPathNodes;
}
inline ULONG Hash(void *p, int len)
{
CRC32_t ulCrc;
CRC32_INIT(&ulCrc);
CRC32_PROCESS_BUFFER(&ulCrc, p, len);
return CRC32_FINAL(ulCrc);
}
void inline CalcBounds(int &Lower, int &Upper, int Goal, int Best)
{
int Temp = 2*Goal - Best;
if (Best > Goal)
{
Lower = max(0, Temp);
Upper = Best;
}
else
{
Upper = min(255, Temp);
Lower = Best;
}
}
// Convert from [-8192,8192] to [0, 255]
//
inline int CALC_RANGE(int x, int lower, int upper)
{
return NUM_RANGES*(x-lower)/((upper-lower+1));
}
void inline UpdateRange(int &minValue, int &maxValue, int Goal, int Best)
{
int Lower, Upper;
CalcBounds(Lower, Upper, Goal, Best);
if (Upper < maxValue) maxValue = Upper;
if (minValue < Lower) minValue = Lower;
}
void CGraph :: CheckNode(Vector vecOrigin, int iNode)
{
// Have we already seen this point before?.
//
if (m_di[iNode].m_CheckedEvent == m_CheckedCounter) return;
m_di[iNode].m_CheckedEvent = m_CheckedCounter;
float flDist = ( vecOrigin - m_pNodes[ iNode ].m_vecOriginPeek ).Length();
if ( flDist < m_flShortest )
{
TraceResult tr;
// make sure that vecOrigin can trace to this node!
UTIL_TraceLine ( vecOrigin, m_pNodes[ iNode ].m_vecOriginPeek, ignore_monsters, 0, &tr );
if ( tr.flFraction == 1.0 )
{
m_iNearest = iNode;
m_flShortest = flDist;
UpdateRange(m_minX, m_maxX, CALC_RANGE(vecOrigin.x, m_RegionMin[0], m_RegionMax[0]), m_pNodes[iNode].m_Region[0]);
UpdateRange(m_minY, m_maxY, CALC_RANGE(vecOrigin.y, m_RegionMin[1], m_RegionMax[1]), m_pNodes[iNode].m_Region[1]);
UpdateRange(m_minZ, m_maxZ, CALC_RANGE(vecOrigin.z, m_RegionMin[2], m_RegionMax[2]), m_pNodes[iNode].m_Region[2]);
// From maxCircle, calculate maximum bounds box. All points must be
// simultaneously inside all bounds of the box.
//
m_minBoxX = CALC_RANGE(vecOrigin.x - flDist, m_RegionMin[0], m_RegionMax[0]);
m_maxBoxX = CALC_RANGE(vecOrigin.x + flDist, m_RegionMin[0], m_RegionMax[0]);
m_minBoxY = CALC_RANGE(vecOrigin.y - flDist, m_RegionMin[1], m_RegionMax[1]);
m_maxBoxY = CALC_RANGE(vecOrigin.y + flDist, m_RegionMin[1], m_RegionMax[1]);
m_minBoxZ = CALC_RANGE(vecOrigin.z - flDist, m_RegionMin[2], m_RegionMax[2]);
m_maxBoxZ = CALC_RANGE(vecOrigin.z + flDist, m_RegionMin[2], m_RegionMax[2]);
}
}
}
//=========================================================
// CGraph - FindNearestNode - returns the index of the node nearest
// the given vector -1 is failure (couldn't find a valid
// near node )
//=========================================================
int CGraph :: FindNearestNode ( const Vector &vecOrigin, CBaseEntity *pEntity )
{
return FindNearestNode( vecOrigin, NodeType( pEntity ) );
}
int CGraph :: FindNearestNode ( const Vector &vecOrigin, int afNodeTypes )
{
int i;
TraceResult tr;
if ( !m_fGraphPresent || !m_fGraphPointersSet )
{// protect us in the case that the node graph isn't available
ALERT ( at_aiconsole, "Graph not ready!\n" );
return -1;
}
// Check with the cache
//
ULONG iHash = (CACHE_SIZE-1) & Hash((void *)(const float *)vecOrigin, sizeof(vecOrigin));
if (m_Cache[iHash].v == vecOrigin)
{
//ALERT(at_aiconsole, "Cache Hit.\n");
return m_Cache[iHash].n;
}
else
{
//ALERT(at_aiconsole, "Cache Miss.\n");
}
// Mark all points as unchecked.
//
m_CheckedCounter++;
if (m_CheckedCounter == 0)
{
for (int i = 0; i < m_cNodes; i++)
{
m_di[i].m_CheckedEvent = 0;
}
m_CheckedCounter++;
}
m_iNearest = -1;
m_flShortest = 999999.0; // just a big number.
// If we can find a visible point, then let CalcBounds set the limits, but if
// we have no visible point at all to start with, then don't restrict the limits.
//
#if 1
m_minX = 0; m_maxX = 255;
m_minY = 0; m_maxY = 255;
m_minZ = 0; m_maxZ = 255;
m_minBoxX = 0; m_maxBoxX = 255;
m_minBoxY = 0; m_maxBoxY = 255;
m_minBoxZ = 0; m_maxBoxZ = 255;
#else
m_minBoxX = CALC_RANGE(vecOrigin.x - flDist, m_RegionMin[0], m_RegionMax[0]);
m_maxBoxX = CALC_RANGE(vecOrigin.x + flDist, m_RegionMin[0], m_RegionMax[0]);
m_minBoxY = CALC_RANGE(vecOrigin.y - flDist, m_RegionMin[1], m_RegionMax[1]);
m_maxBoxY = CALC_RANGE(vecOrigin.y + flDist, m_RegionMin[1], m_RegionMax[1]);
m_minBoxZ = CALC_RANGE(vecOrigin.z - flDist, m_RegionMin[2], m_RegionMax[2]);
m_maxBoxZ = CALC_RANGE(vecOrigin.z + flDist, m_RegionMin[2], m_RegionMax[2])
CalcBounds(m_minX, m_maxX, CALC_RANGE(vecOrigin.x, m_RegionMin[0], m_RegionMax[0]), m_pNodes[m_iNearest].m_Region[0]);
CalcBounds(m_minY, m_maxY, CALC_RANGE(vecOrigin.y, m_RegionMin[1], m_RegionMax[1]), m_pNodes[m_iNearest].m_Region[1]);
CalcBounds(m_minZ, m_maxZ, CALC_RANGE(vecOrigin.z, m_RegionMin[2], m_RegionMax[2]), m_pNodes[m_iNearest].m_Region[2]);
#endif
int halfX = (m_minX+m_maxX)/2;
int halfY = (m_minY+m_maxY)/2;
int halfZ = (m_minZ+m_maxZ)/2;
int j;
for (i = halfX; i >= m_minX; i--)
{
for (j = m_RangeStart[0][i]; j <= m_RangeEnd[0][i]; j++)
{
if (!(m_pNodes[m_di[j].m_SortedBy[0]].m_afNodeInfo & afNodeTypes)) continue;
int rgY = m_pNodes[m_di[j].m_SortedBy[0]].m_Region[1];
if (rgY > m_maxBoxY) break;
if (rgY < m_minBoxY) continue;
int rgZ = m_pNodes[m_di[j].m_SortedBy[0]].m_Region[2];
if (rgZ < m_minBoxZ) continue;
if (rgZ > m_maxBoxZ) continue;
CheckNode(vecOrigin, m_di[j].m_SortedBy[0]);
}
}
for (i = max(m_minY,halfY+1); i <= m_maxY; i++)
{
for (j = m_RangeStart[1][i]; j <= m_RangeEnd[1][i]; j++)
{
if (!(m_pNodes[m_di[j].m_SortedBy[1]].m_afNodeInfo & afNodeTypes)) continue;
int rgZ = m_pNodes[m_di[j].m_SortedBy[1]].m_Region[2];
if (rgZ > m_maxBoxZ) break;
if (rgZ < m_minBoxZ) continue;
int rgX = m_pNodes[m_di[j].m_SortedBy[1]].m_Region[0];
if (rgX < m_minBoxX) continue;
if (rgX > m_maxBoxX) continue;
CheckNode(vecOrigin, m_di[j].m_SortedBy[1]);
}
}
for (i = min(m_maxZ,halfZ); i >= m_minZ; i--)
{
for (j = m_RangeStart[2][i]; j <= m_RangeEnd[2][i]; j++)
{
if (!(m_pNodes[m_di[j].m_SortedBy[2]].m_afNodeInfo & afNodeTypes)) continue;
int rgX = m_pNodes[m_di[j].m_SortedBy[2]].m_Region[0];
if (rgX > m_maxBoxX) break;
if (rgX < m_minBoxX) continue;
int rgY = m_pNodes[m_di[j].m_SortedBy[2]].m_Region[1];
if (rgY < m_minBoxY) continue;
if (rgY > m_maxBoxY) continue;
CheckNode(vecOrigin, m_di[j].m_SortedBy[2]);
}
}
for (i = max(m_minX,halfX+1); i <= m_maxX; i++)
{
for (j = m_RangeStart[0][i]; j <= m_RangeEnd[0][i]; j++)
{
if (!(m_pNodes[m_di[j].m_SortedBy[0]].m_afNodeInfo & afNodeTypes)) continue;
int rgY = m_pNodes[m_di[j].m_SortedBy[0]].m_Region[1];
if (rgY > m_maxBoxY) break;
if (rgY < m_minBoxY) continue;
int rgZ = m_pNodes[m_di[j].m_SortedBy[0]].m_Region[2];
if (rgZ < m_minBoxZ) continue;
if (rgZ > m_maxBoxZ) continue;
CheckNode(vecOrigin, m_di[j].m_SortedBy[0]);
}
}
for (i = min(m_maxY,halfY); i >= m_minY; i--)
{
for (j = m_RangeStart[1][i]; j <= m_RangeEnd[1][i]; j++)
{
if (!(m_pNodes[m_di[j].m_SortedBy[1]].m_afNodeInfo & afNodeTypes)) continue;
int rgZ = m_pNodes[m_di[j].m_SortedBy[1]].m_Region[2];
if (rgZ > m_maxBoxZ) break;
if (rgZ < m_minBoxZ) continue;
int rgX = m_pNodes[m_di[j].m_SortedBy[1]].m_Region[0];
if (rgX < m_minBoxX) continue;
if (rgX > m_maxBoxX) continue;
CheckNode(vecOrigin, m_di[j].m_SortedBy[1]);
}
}
for (i = max(m_minZ,halfZ+1); i <= m_maxZ; i++)
{
for (j = m_RangeStart[2][i]; j <= m_RangeEnd[2][i]; j++)
{
if (!(m_pNodes[m_di[j].m_SortedBy[2]].m_afNodeInfo & afNodeTypes)) continue;
int rgX = m_pNodes[m_di[j].m_SortedBy[2]].m_Region[0];
if (rgX > m_maxBoxX) break;
if (rgX < m_minBoxX) continue;
int rgY = m_pNodes[m_di[j].m_SortedBy[2]].m_Region[1];
if (rgY < m_minBoxY) continue;
if (rgY > m_maxBoxY) continue;
CheckNode(vecOrigin, m_di[j].m_SortedBy[2]);
}
}
#if 0
// Verify our answers.
//
int iNearestCheck = -1;
m_flShortest = 8192;// find nodes within this radius
for ( i = 0 ; i < m_cNodes ; i++ )
{
float flDist = ( vecOrigin - m_pNodes[ i ].m_vecOriginPeek ).Length();
if ( flDist < m_flShortest )
{
// make sure that vecOrigin can trace to this node!
UTIL_TraceLine ( vecOrigin, m_pNodes[ i ].m_vecOriginPeek, ignore_monsters, 0, &tr );
if ( tr.flFraction == 1.0 )
{
iNearestCheck = i;
m_flShortest = flDist;
}
}
}
if (iNearestCheck != m_iNearest)
{
ALERT( at_aiconsole, "NOT closest %d(%f,%f,%f) %d(%f,%f,%f).\n",
iNearestCheck,
m_pNodes[iNearestCheck].m_vecOriginPeek.x,
m_pNodes[iNearestCheck].m_vecOriginPeek.y,
m_pNodes[iNearestCheck].m_vecOriginPeek.z,
m_iNearest,
(m_iNearest == -1?0.0:m_pNodes[m_iNearest].m_vecOriginPeek.x),
(m_iNearest == -1?0.0:m_pNodes[m_iNearest].m_vecOriginPeek.y),
(m_iNearest == -1?0.0:m_pNodes[m_iNearest].m_vecOriginPeek.z));
}
if (m_iNearest == -1)
{
ALERT(at_aiconsole, "All that work for nothing.\n");
}
#endif
m_Cache[iHash].v = vecOrigin;
m_Cache[iHash].n = m_iNearest;
return m_iNearest;
}
//=========================================================
// CGraph - ShowNodeConnections - draws a line from the given node
// to all connected nodes
//=========================================================
void CGraph :: ShowNodeConnections ( int iNode )
{
Vector vecSpot;
CNode *pNode;
CNode *pLinkNode;
int i;
if ( !m_fGraphPresent || !m_fGraphPointersSet )
{// protect us in the case that the node graph isn't available or built
ALERT ( at_aiconsole, "Graph not ready!\n" );
return;
}
if ( iNode < 0 )
{
ALERT( at_aiconsole, "Can't show connections for node %d\n", iNode );
return;
}
pNode = &m_pNodes[ iNode ];
UTIL_ParticleEffect( pNode->m_vecOrigin, g_vecZero, 255, 20 );// show node position
if ( pNode->m_cNumLinks <= 0 )
{// no connections!
ALERT ( at_aiconsole, "**No Connections!\n" );
}
for ( i = 0 ; i < pNode->m_cNumLinks ; i++ )
{
pLinkNode = &Node( NodeLink( iNode, i).m_iDestNode );
vecSpot = pLinkNode->m_vecOrigin;
MESSAGE_BEGIN( MSG_BROADCAST, SVC_TEMPENTITY );
WRITE_BYTE( TE_SHOWLINE);
WRITE_COORD( m_pNodes[ iNode ].m_vecOrigin.x );
WRITE_COORD( m_pNodes[ iNode ].m_vecOrigin.y );
WRITE_COORD( m_pNodes[ iNode ].m_vecOrigin.z + NODE_HEIGHT );
WRITE_COORD( vecSpot.x );
WRITE_COORD( vecSpot.y );
WRITE_COORD( vecSpot.z + NODE_HEIGHT );
MESSAGE_END();
}
}
//=========================================================
// CGraph - LinkVisibleNodes - the first, most basic
// function of node graph creation, this connects every
// node to every other node that it can see. Expects a
// pointer to an empty connection pool and a file pointer
// to write progress to. Returns the total number of initial
// links.
//
// If there's a problem with this process, the index
// of the offending node will be written to piBadNode
//=========================================================
int CGraph :: LinkVisibleNodes ( CLink *pLinkPool, FILE *file, int *piBadNode )
{
int i,j,z;
edict_t *pTraceEnt;
int cTotalLinks, cLinksThisNode, cMaxInitialLinks;
TraceResult tr;
// !!!BUGBUG - this function returns 0 if there is a problem in the middle of connecting the graph
// it also returns 0 if none of the nodes in a level can see each other. piBadNode is ALWAYS read
// by BuildNodeGraph() if this function returns a 0, so make sure that it doesn't get some random
// number back.
*piBadNode = 0;
if ( m_cNodes <= 0 )
{
ALERT ( at_aiconsole, "No Nodes!\n" );
return FALSE;
}
// if the file pointer is bad, don't blow up, just don't write the
// file.
if ( !file )
{
ALERT ( at_aiconsole, "**LinkVisibleNodes:\ncan't write to file." );
}
else
{
fprintf ( file, "----------------------------------------------------------------------------\n" );
fprintf ( file, "LinkVisibleNodes - Initial Connections\n" );
fprintf ( file, "----------------------------------------------------------------------------\n" );
}
cTotalLinks = 0;// start with no connections
// to keep track of the maximum number of initial links any node had so far.
// this lets us keep an eye on MAX_NODE_INITIAL_LINKS to ensure that we are
// being generous enough.
cMaxInitialLinks = 0;
for ( i = 0 ; i < m_cNodes ; i++ )
{
cLinksThisNode = 0;// reset this count for each node.
if ( file )
{
fprintf ( file, "Node #%4d:\n\n", i );
}
for ( z = 0 ; z < MAX_NODE_INITIAL_LINKS ; z++ )
{// clear out the important fields in the link pool for this node
pLinkPool [ cTotalLinks + z ].m_iSrcNode = i;// so each link knows which node it originates from
pLinkPool [ cTotalLinks + z ].m_iDestNode = 0;
pLinkPool [ cTotalLinks + z ].m_pLinkEnt = NULL;
}
m_pNodes [ i ].m_iFirstLink = cTotalLinks;
// now build a list of every other node that this node can see
for ( j = 0 ; j < m_cNodes ; j++ )
{
if ( j == i )
{// don't connect to self!
continue;
}
#if 0
if ( (m_pNodes[ i ].m_afNodeInfo & bits_NODE_WATER) != (m_pNodes[ j ].m_afNodeInfo & bits_NODE_WATER) )
{
// don't connect water nodes to air nodes or land nodes. It just wouldn't be prudent at this juncture.
continue;
}
#else
if ( (m_pNodes[ i ].m_afNodeInfo & bits_NODE_GROUP_REALM) != (m_pNodes[ j ].m_afNodeInfo & bits_NODE_GROUP_REALM) )
{
// don't connect air nodes to water nodes to land nodes. It just wouldn't be prudent at this juncture.
continue;
}
#endif
tr.pHit = NULL;// clear every time so we don't get stuck with last trace's hit ent
pTraceEnt = 0;
UTIL_TraceLine ( m_pNodes[ i ].m_vecOrigin,
m_pNodes[ j ].m_vecOrigin,
ignore_monsters,
g_pBodyQueueHead,//!!!HACKHACK no real ent to supply here, using a global we don't care about
&tr );
if ( tr.fStartSolid )
continue;
if ( tr.flFraction != 1.0 )
{// trace hit a brush ent, trace backwards to make sure that this ent is the only thing in the way.
pTraceEnt = tr.pHit;// store the ent that the trace hit, for comparison
UTIL_TraceLine ( m_pNodes[ j ].m_vecOrigin,
m_pNodes[ i ].m_vecOrigin,
ignore_monsters,
g_pBodyQueueHead,//!!!HACKHACK no real ent to supply here, using a global we don't care about
&tr );
// there is a solid_bsp ent in the way of these two nodes, so we must record several things about in order to keep
// track of it in the pathfinding code, as well as through save and restore of the node graph. ANY data that is manipulated
// as part of the process of adding a LINKENT to a connection here must also be done in CGraph::SetGraphPointers, where reloaded
// graphs are prepared for use.
if ( tr.pHit == pTraceEnt && !FClassnameIs( tr.pHit, "worldspawn" ) )
{
// get a pointer
pLinkPool [ cTotalLinks ].m_pLinkEnt = VARS( tr.pHit );
// record the modelname, so that we can save/load node trees
memcpy( pLinkPool [ cTotalLinks ].m_szLinkEntModelname, STRING( VARS(tr.pHit)->model ), 4 );
// set the flag for this ent that indicates that it is attached to the world graph
// if this ent is removed from the world, it must also be removed from the connections
// that it formerly blocked.
if ( !FBitSet( VARS( tr.pHit )->flags, FL_GRAPHED ) )
{
VARS( tr.pHit )->flags += FL_GRAPHED;
}
}
else
{// even if the ent wasn't there, these nodes couldn't be connected. Skip.
continue;
}
}
if ( file )
{
fprintf ( file, "%4d", j );
if ( !FNullEnt( pLinkPool[ cTotalLinks ].m_pLinkEnt ) )
{// record info about the ent in the way, if any.
fprintf ( file, " Entity on connection: %s, name: %s Model: %s", STRING( VARS( pTraceEnt )->classname ), STRING ( VARS( pTraceEnt )->targetname ), STRING ( VARS(tr.pHit)->model ) );
}
fprintf ( file, "\n", j );
}
pLinkPool [ cTotalLinks ].m_iDestNode = j;
cLinksThisNode++;
cTotalLinks++;
// If we hit this, either a level designer is placing too many nodes in the same area, or
// we need to allow for a larger initial link pool.
if ( cLinksThisNode == MAX_NODE_INITIAL_LINKS )
{
ALERT ( at_aiconsole, "**LinkVisibleNodes:\nNode %d has NodeLinks > MAX_NODE_INITIAL_LINKS", i );
fprintf ( file, "** NODE %d HAS NodeLinks > MAX_NODE_INITIAL_LINKS **\n", i );
*piBadNode = i;
return FALSE;
}
else if ( cTotalLinks > MAX_NODE_INITIAL_LINKS * m_cNodes )
{// this is paranoia
ALERT ( at_aiconsole, "**LinkVisibleNodes:\nTotalLinks > MAX_NODE_INITIAL_LINKS * NUMNODES" );
*piBadNode = i;
return FALSE;
}
if ( cLinksThisNode == 0 )
{
fprintf ( file, "**NO INITIAL LINKS**\n" );
}
// record the connection info in the link pool
WorldGraph.m_pNodes [ i ].m_cNumLinks = cLinksThisNode;
// keep track of the most initial links ANY node had, so we can figure out
// if we have a large enough default link pool
if ( cLinksThisNode > cMaxInitialLinks )
{
cMaxInitialLinks = cLinksThisNode;
}
}
if ( file )
{
fprintf ( file, "----------------------------------------------------------------------------\n" );
}
}
fprintf ( file, "\n%4d Total Initial Connections - %4d Maximum connections for a single node.\n", cTotalLinks, cMaxInitialLinks );
fprintf ( file, "----------------------------------------------------------------------------\n\n\n" );
return cTotalLinks;
}
//=========================================================
// CGraph - RejectInlineLinks - expects a pointer to a link
// pool, and a pointer to and already-open file ( if you
// want status reports written to disk ). RETURNS the number
// of connections that were rejected
//=========================================================
int CGraph :: RejectInlineLinks ( CLink *pLinkPool, FILE *file )
{
int i,j,k;
int cRejectedLinks;
BOOL fRestartLoop;// have to restart the J loop if we eliminate a link.
CNode *pSrcNode;
CNode *pCheckNode;// the node we are testing for (one of pSrcNode's connections)
CNode *pTestNode;// the node we are checking against ( also one of pSrcNode's connections)
float flDistToTestNode, flDistToCheckNode;
Vector2D vec2DirToTestNode, vec2DirToCheckNode;
if ( file )
{
fprintf ( file, "----------------------------------------------------------------------------\n" );
fprintf ( file, "InLine Rejection:\n" );
fprintf ( file, "----------------------------------------------------------------------------\n" );
}
cRejectedLinks = 0;
for ( i = 0 ; i < m_cNodes ; i++ )
{
pSrcNode = &m_pNodes[ i ];
if ( file )
{
fprintf ( file, "Node %3d:\n", i );
}
for ( j = 0 ; j < pSrcNode->m_cNumLinks ; j++ )
{
pCheckNode = &m_pNodes[ pLinkPool[ pSrcNode->m_iFirstLink + j ].m_iDestNode ];
vec2DirToCheckNode = ( pCheckNode->m_vecOrigin - pSrcNode->m_vecOrigin ).Make2D();
flDistToCheckNode = vec2DirToCheckNode.Length();
vec2DirToCheckNode = vec2DirToCheckNode.Normalize();
pLinkPool[ pSrcNode->m_iFirstLink + j ].m_flWeight = flDistToCheckNode;
fRestartLoop = FALSE;
for ( k = 0 ; k < pSrcNode->m_cNumLinks && !fRestartLoop ; k++ )
{
if ( k == j )
{// don't check against same node
continue;
}
pTestNode = &m_pNodes [ pLinkPool[ pSrcNode->m_iFirstLink + k ].m_iDestNode ];
vec2DirToTestNode = ( pTestNode->m_vecOrigin - pSrcNode->m_vecOrigin ).Make2D();
flDistToTestNode = vec2DirToTestNode.Length();
vec2DirToTestNode = vec2DirToTestNode.Normalize();
if ( DotProduct ( vec2DirToCheckNode, vec2DirToTestNode ) >= 0.998 )
{
// there's a chance that TestNode intersects the line to CheckNode. If so, we should disconnect the link to CheckNode.
if ( flDistToTestNode < flDistToCheckNode )
{
if ( file )
{
fprintf ( file, "REJECTED NODE %3d through Node %3d, Dot = %8f\n", pLinkPool[ pSrcNode->m_iFirstLink + j ].m_iDestNode, pLinkPool[ pSrcNode->m_iFirstLink + k ].m_iDestNode, DotProduct ( vec2DirToCheckNode, vec2DirToTestNode ) );
}
pLinkPool[ pSrcNode->m_iFirstLink + j ] = pLinkPool[ pSrcNode->m_iFirstLink + ( pSrcNode->m_cNumLinks - 1 ) ];
pSrcNode->m_cNumLinks--;
j--;
cRejectedLinks++;// keeping track of how many links are cut, so that we can return that value.
fRestartLoop = TRUE;
}
}
}
}
if ( file )
{
fprintf ( file, "----------------------------------------------------------------------------\n\n" );
}
}
return cRejectedLinks;
}
//=========================================================
// TestHull is a modelless clip hull that verifies reachable
// nodes by walking from every node to each of it's connections
//=========================================================
class CTestHull : public CBaseMonster
{
public:
void Spawn( entvars_t *pevMasterNode );
virtual int ObjectCaps( void ) { return CBaseMonster :: ObjectCaps() & ~FCAP_ACROSS_TRANSITION; }
void EXPORT CallBuildNodeGraph ( void );
void BuildNodeGraph ( void );
void EXPORT ShowBadNode ( void );
void EXPORT DropDelay ( void );
void EXPORT PathFind ( void );
Vector vecBadNodeOrigin;
};
LINK_ENTITY_TO_CLASS( testhull, CTestHull );
//=========================================================
// CTestHull::Spawn
//=========================================================
void CTestHull :: Spawn( entvars_t *pevMasterNode )
{
SET_MODEL(ENT(pev), "models/player.mdl");
UTIL_SetSize(pev, VEC_HUMAN_HULL_MIN, VEC_HUMAN_HULL_MAX);
pev->solid = SOLID_SLIDEBOX;
pev->movetype = MOVETYPE_STEP;
pev->effects = 0;
pev->health = 50;
pev->yaw_speed = 8;
if ( WorldGraph.m_fGraphPresent )
{// graph loaded from disk, so we don't need the test hull
SetThink ( SUB_Remove );
pev->nextthink = gpGlobals->time;
}
else
{
SetThink ( DropDelay );
pev->nextthink = gpGlobals->time + 1;
}
// Make this invisible
// UNDONE: Shouldn't we just use EF_NODRAW? This doesn't need to go to the client.
pev->rendermode = kRenderTransTexture;
pev->renderamt = 0;
}
//=========================================================
// TestHull::DropDelay - spawns TestHull on top of
// the 0th node and drops it to the ground.
//=========================================================
void CTestHull::DropDelay ( void )
{
UTIL_CenterPrintAll( "Node Graph out of Date. Rebuilding..." );
UTIL_SetOrigin ( VARS(pev), WorldGraph.m_pNodes[ 0 ].m_vecOrigin );
SetThink ( CallBuildNodeGraph );
pev->nextthink = gpGlobals->time + 1;
}
//=========================================================
// nodes start out as ents in the world. As they are spawned,
// the node info is recorded then the ents are discarded.
//=========================================================
void CNodeEnt :: KeyValue( KeyValueData *pkvd )
{
if (FStrEq(pkvd->szKeyName, "hinttype"))
{
m_sHintType = (short)atoi( pkvd->szValue );
pkvd->fHandled = TRUE;
}
if (FStrEq(pkvd->szKeyName, "activity"))
{
m_sHintActivity = (short)atoi( pkvd->szValue );
pkvd->fHandled = TRUE;
}
else
CBaseEntity::KeyValue( pkvd );
}
//=========================================================
//=========================================================
void CNodeEnt :: Spawn( void )
{
pev->movetype = MOVETYPE_NONE;
pev->solid = SOLID_NOT;// always solid_not
if ( WorldGraph.m_fGraphPresent )
{// graph loaded from disk, so discard all these node ents as soon as they spawn
REMOVE_ENTITY( edict() );
return;
}
if ( WorldGraph.m_cNodes == 0 )
{// this is the first node to spawn, spawn the test hull entity that builds and walks the node tree
CTestHull *pHull = GetClassPtr((CTestHull *)NULL);
pHull->Spawn( pev );
}
if ( WorldGraph.m_cNodes >= MAX_NODES )
{
ALERT ( at_aiconsole, "cNodes > MAX_NODES\n" );
return;
}
WorldGraph.m_pNodes[ WorldGraph.m_cNodes ].m_vecOriginPeek =
WorldGraph.m_pNodes[ WorldGraph.m_cNodes ].m_vecOrigin = pev->origin;
WorldGraph.m_pNodes[ WorldGraph.m_cNodes ].m_flHintYaw = pev->angles.y;
WorldGraph.m_pNodes[ WorldGraph.m_cNodes ].m_sHintType = m_sHintType;
WorldGraph.m_pNodes[ WorldGraph.m_cNodes ].m_sHintActivity = m_sHintActivity;
if (FClassnameIs( pev, "info_node_air" ))
WorldGraph.m_pNodes[ WorldGraph.m_cNodes ].m_afNodeInfo = bits_NODE_AIR;
else
WorldGraph.m_pNodes[ WorldGraph.m_cNodes ].m_afNodeInfo = 0;
WorldGraph.m_cNodes++;
REMOVE_ENTITY( edict() );
}
//=========================================================
// CTestHull - ShowBadNode - makes a bad node fizzle. When
// there's a problem with node graph generation, the test
// hull will be placed up the bad node's location and will generate
// particles
//=========================================================
void CTestHull :: ShowBadNode( void )
{
pev->movetype = MOVETYPE_FLY;
pev->angles.y = pev->angles.y + 4;
UTIL_MakeVectors ( pev->angles );
UTIL_ParticleEffect ( pev->origin, g_vecZero, 255, 25 );
UTIL_ParticleEffect ( pev->origin + gpGlobals->v_forward * 64, g_vecZero, 255, 25 );
UTIL_ParticleEffect ( pev->origin - gpGlobals->v_forward * 64, g_vecZero, 255, 25 );
UTIL_ParticleEffect ( pev->origin + gpGlobals->v_right * 64, g_vecZero, 255, 25 );
UTIL_ParticleEffect ( pev->origin - gpGlobals->v_right * 64, g_vecZero, 255, 25 );
pev->nextthink = gpGlobals->time + 0.1;
}
extern BOOL gTouchDisabled;
void CTestHull::CallBuildNodeGraph( void )
{
// TOUCH HACK -- Don't allow this entity to call anyone's "touch" function
gTouchDisabled = TRUE;
BuildNodeGraph();
gTouchDisabled = FALSE;
// Undo TOUCH HACK
}
//=========================================================
// BuildNodeGraph - think function called by the empty walk
// hull that is spawned by the first node to spawn. This
// function links all nodes that can see each other, then
// eliminates all inline links, then uses a monster-sized
// hull that walks between each node and each of its links
// to ensure that a monster can actually fit through the space
//=========================================================
void CTestHull :: BuildNodeGraph( void )
{
TraceResult tr;
FILE *file;
char szNrpFilename [MAX_PATH];// text node report filename
CLink *pTempPool; // temporary link pool
CNode *pSrcNode;// node we're currently working with
CNode *pDestNode;// the other node in comparison operations
BOOL fSkipRemainingHulls;//if smallest hull can't fit, don't check any others
BOOL fPairsValid;// are all links in the graph evenly paired?
int i, j, hull;
int iBadNode;// this is the node that caused graph generation to fail
int cMaxInitialLinks = 0;
int cMaxValidLinks = 0;
int iPoolIndex = 0;
int cPoolLinks;// number of links in the pool.
Vector vecDirToCheckNode;
Vector vecDirToTestNode;
Vector vecStepCheckDir;
Vector vecTraceSpot;
Vector vecSpot;
Vector2D vec2DirToCheckNode;
Vector2D vec2DirToTestNode;
Vector2D vec2StepCheckDir;
Vector2D vec2TraceSpot;
Vector2D vec2Spot;
float flYaw;// use this stuff to walk the hull between nodes
float flDist;
int step;
SetThink ( SUB_Remove );// no matter what happens, the hull gets rid of itself.
pev->nextthink = gpGlobals->time;
// malloc a swollen temporary connection pool that we trim down after we know exactly how many connections there are.
pTempPool = (CLink *)calloc ( sizeof ( CLink ) , ( WorldGraph.m_cNodes * MAX_NODE_INITIAL_LINKS ) );
if ( !pTempPool )
{
ALERT ( at_aiconsole, "**Could not malloc TempPool!\n" );
return;
}
// make sure directories have been made
GET_GAME_DIR( szNrpFilename );
strcat( szNrpFilename, "/maps" );
CreateDirectory( szNrpFilename, NULL );
strcat( szNrpFilename, "/graphs" );
CreateDirectory( szNrpFilename, NULL );
strcat( szNrpFilename, "/" );
strcat( szNrpFilename, STRING( gpGlobals->mapname ) );
strcat( szNrpFilename, ".nrp" );
file = fopen ( szNrpFilename, "w+" );
if ( !file )
{// file error
ALERT ( at_aiconsole, "Couldn't create %s!\n", szNrpFilename );
if ( pTempPool )
{
free ( pTempPool );
}
return;
}
fprintf( file, "Node Graph Report for map: %s.bsp\n", STRING(gpGlobals->mapname) );
fprintf ( file, "%d Total Nodes\n\n", WorldGraph.m_cNodes );
for ( i = 0 ; i < WorldGraph.m_cNodes ; i++ )
{// print all node numbers and their locations to the file.
WorldGraph.m_pNodes[ i ].m_cNumLinks = 0;
WorldGraph.m_pNodes[ i ].m_iFirstLink = 0;
memset(WorldGraph.m_pNodes[ i ].m_pNextBestNode, 0, sizeof(WorldGraph.m_pNodes[ i ].m_pNextBestNode));
fprintf ( file, "Node# %4d\n", i );
fprintf ( file, "Location %4d,%4d,%4d\n",(int)WorldGraph.m_pNodes[ i ].m_vecOrigin.x, (int)WorldGraph.m_pNodes[ i ].m_vecOrigin.y, (int)WorldGraph.m_pNodes[ i ].m_vecOrigin.z );
fprintf ( file, "HintType: %4d\n", WorldGraph.m_pNodes[ i ].m_sHintType );
fprintf ( file, "HintActivity: %4d\n", WorldGraph.m_pNodes[ i ].m_sHintActivity );
fprintf ( file, "HintYaw: %4f\n", WorldGraph.m_pNodes[ i ].m_flHintYaw );
fprintf ( file, "-------------------------------------------------------------------------------\n" );
}
fprintf ( file, "\n\n" );
// Automatically recognize WATER nodes and drop the LAND nodes to the floor.
//
for ( i = 0; i < WorldGraph.m_cNodes; i++)
{
if (WorldGraph.m_pNodes[ i ].m_afNodeInfo & bits_NODE_AIR)
{
// do nothing
}
else if (UTIL_PointContents(WorldGraph.m_pNodes[ i ].m_vecOrigin) == CONTENTS_WATER)
{
WorldGraph.m_pNodes[ i ].m_afNodeInfo |= bits_NODE_WATER;
}
else
{
WorldGraph.m_pNodes[ i ].m_afNodeInfo |= bits_NODE_LAND;
// trace to the ground, then pop up 8 units and place node there to make it
// easier for them to connect (think stairs, chairs, and bumps in the floor).
// After the routing is done, push them back down.
//
TraceResult tr;
UTIL_TraceLine ( WorldGraph.m_pNodes[i].m_vecOrigin,
WorldGraph.m_pNodes[i].m_vecOrigin - Vector ( 0, 0, 384 ),
ignore_monsters,
g_pBodyQueueHead,//!!!HACKHACK no real ent to supply here, using a global we don't care about
&tr );
// This trace is ONLY used if we hit an entity flagged with FL_WORLDBRUSH
TraceResult trEnt;
UTIL_TraceLine ( WorldGraph.m_pNodes[i].m_vecOrigin,
WorldGraph.m_pNodes[i].m_vecOrigin - Vector ( 0, 0, 384 ),
dont_ignore_monsters,
g_pBodyQueueHead,//!!!HACKHACK no real ent to supply here, using a global we don't care about
&trEnt );
// Did we hit something closer than the floor?
if ( trEnt.flFraction < tr.flFraction )
{
// If it was a world brush entity, copy the node location
if ( trEnt.pHit && (trEnt.pHit->v.flags & FL_WORLDBRUSH) )
tr.vecEndPos = trEnt.vecEndPos;
}
WorldGraph.m_pNodes[i].m_vecOriginPeek.z =
WorldGraph.m_pNodes[i].m_vecOrigin.z = tr.vecEndPos.z + NODE_HEIGHT;
}
}
cPoolLinks = WorldGraph.LinkVisibleNodes( pTempPool, file, &iBadNode );
if ( !cPoolLinks )
{
ALERT ( at_aiconsole, "**ConnectVisibleNodes FAILED!\n" );
SetThink ( ShowBadNode );// send the hull off to show the offending node.
//pev->solid = SOLID_NOT;
pev->origin = WorldGraph.m_pNodes[ iBadNode ].m_vecOrigin;
if ( pTempPool )
{
free ( pTempPool );
}
if ( file )
{// close the file
fclose ( file );
}
return;
}
// send the walkhull to all of this node's connections now. We'll do this here since
// so much of it relies on being able to control the test hull.
fprintf ( file, "----------------------------------------------------------------------------\n" );
fprintf ( file, "Walk Rejection:\n");
for ( i = 0 ; i < WorldGraph.m_cNodes ; i++ )
{
pSrcNode = &WorldGraph.m_pNodes[ i ];
fprintf ( file, "-------------------------------------------------------------------------------\n");
fprintf ( file, "Node %4d:\n\n", i );
for ( j = 0 ; j < pSrcNode->m_cNumLinks ; j++ )
{
// assume that all hulls can walk this link, then eliminate the ones that can't.
pTempPool [ pSrcNode->m_iFirstLink + j ].m_afLinkInfo = bits_LINK_SMALL_HULL | bits_LINK_HUMAN_HULL | bits_LINK_LARGE_HULL | bits_LINK_FLY_HULL;
// do a check for each hull size.
// if we can't fit a tiny hull through a connection, no other hulls with fit either, so we
// should just fall out of the loop. Do so by setting the SkipRemainingHulls flag.
fSkipRemainingHulls = FALSE;
for ( hull = 0 ; hull < MAX_NODE_HULLS; hull++ )
{
if (fSkipRemainingHulls && (hull == NODE_HUMAN_HULL || hull == NODE_LARGE_HULL)) // skip the remaining walk hulls
continue;
switch ( hull )
{
case NODE_SMALL_HULL:
UTIL_SetSize(pev, Vector(-12, -12, 0), Vector(12, 12, 24));
break;
case NODE_HUMAN_HULL:
UTIL_SetSize(pev, VEC_HUMAN_HULL_MIN, VEC_HUMAN_HULL_MAX );
break;
case NODE_LARGE_HULL:
UTIL_SetSize(pev, Vector(-32, -32, 0), Vector(32, 32, 64));
break;
case NODE_FLY_HULL:
UTIL_SetSize(pev, Vector(-32, -32, 0), Vector(32, 32, 64));
// UTIL_SetSize(pev, Vector(0, 0, 0), Vector(0, 0, 0));
break;
}
UTIL_SetOrigin ( pev, pSrcNode->m_vecOrigin );// place the hull on the node
if ( !FBitSet ( pev->flags, FL_ONGROUND ) )
{
ALERT ( at_aiconsole, "OFFGROUND!\n" );
}
// now build a yaw that points to the dest node, and get the distance.
if ( j < 0 )
{
ALERT ( at_aiconsole, "**** j = %d ****\n", j );
if ( pTempPool )
{
free ( pTempPool );
}
if ( file )
{// close the file
fclose ( file );
}
return;
}
pDestNode = &WorldGraph.m_pNodes [ pTempPool[ pSrcNode->m_iFirstLink + j ].m_iDestNode ];
vecSpot = pDestNode->m_vecOrigin;
//vecSpot.z = pev->origin.z;
if (hull < NODE_FLY_HULL)
{
int SaveFlags = pev->flags;
int MoveMode = WALKMOVE_WORLDONLY;
if (pSrcNode->m_afNodeInfo & bits_NODE_WATER)
{
pev->flags |= FL_SWIM;
MoveMode = WALKMOVE_NORMAL;
}
flYaw = UTIL_VecToYaw ( pDestNode->m_vecOrigin - pev->origin );
flDist = ( vecSpot - pev->origin ).Length2D();
int fWalkFailed = FALSE;
// in this loop we take tiny steps from the current node to the nodes that it links to, one at a time.
// pev->angles.y = flYaw;
for ( step = 0 ; step < flDist && !fWalkFailed ; step += HULL_STEP_SIZE )
{
float stepSize = HULL_STEP_SIZE;
if ( (step + stepSize) >= (flDist-1) )
stepSize = (flDist - step) - 1;
if ( !WALK_MOVE( ENT(pev), flYaw, stepSize, MoveMode ) )
{// can't take the next step
fWalkFailed = TRUE;
break;
}
}
if (!fWalkFailed && (pev->origin - vecSpot).Length() > 64)
{
// ALERT( at_console, "bogus walk\n");
// we thought we
fWalkFailed = TRUE;
}
if (fWalkFailed)
{
//pTempPool[ pSrcNode->m_iFirstLink + j ] = pTempPool [ pSrcNode->m_iFirstLink + ( pSrcNode->m_cNumLinks - 1 ) ];
// now me must eliminate the hull that couldn't walk this connection
switch ( hull )
{
case NODE_SMALL_HULL: // if this hull can't fit, nothing can, so drop the connection
fprintf ( file, "NODE_SMALL_HULL step %f\n", step );
pTempPool[ pSrcNode->m_iFirstLink + j ].m_afLinkInfo &= ~(bits_LINK_SMALL_HULL | bits_LINK_HUMAN_HULL | bits_LINK_LARGE_HULL);
fSkipRemainingHulls = TRUE;// don't bother checking larger hulls
break;
case NODE_HUMAN_HULL:
fprintf ( file, "NODE_HUMAN_HULL step %f\n", step );
pTempPool[ pSrcNode->m_iFirstLink + j ].m_afLinkInfo &= ~(bits_LINK_HUMAN_HULL | bits_LINK_LARGE_HULL);
fSkipRemainingHulls = TRUE;// don't bother checking larger hulls
break;
case NODE_LARGE_HULL:
fprintf ( file, "NODE_LARGE_HULL step %f\n", step );
pTempPool[ pSrcNode->m_iFirstLink + j ].m_afLinkInfo &= ~bits_LINK_LARGE_HULL;
break;
}
}
pev->flags = SaveFlags;
}
else
{
TraceResult tr;
UTIL_TraceHull( pSrcNode->m_vecOrigin + Vector( 0, 0, 32 ), pDestNode->m_vecOriginPeek + Vector( 0, 0, 32 ), ignore_monsters, large_hull, ENT( pev ), &tr );
if (tr.fStartSolid || tr.flFraction < 1.0)
{
pTempPool[ pSrcNode->m_iFirstLink + j ].m_afLinkInfo &= ~bits_LINK_FLY_HULL;
}
}
}
if (pTempPool[ pSrcNode->m_iFirstLink + j ].m_afLinkInfo == 0)
{
fprintf ( file, "Rejected Node %3d - Unreachable by ", pTempPool [ pSrcNode->m_iFirstLink + j ].m_iDestNode );
pTempPool[ pSrcNode->m_iFirstLink + j ] = pTempPool [ pSrcNode->m_iFirstLink + ( pSrcNode->m_cNumLinks - 1 ) ];
fprintf ( file, "Any Hull\n" );
pSrcNode->m_cNumLinks--;
cPoolLinks--;// we just removed a link, so decrement the total number of links in the pool.
j--;
}
}
}
fprintf ( file, "-------------------------------------------------------------------------------\n\n\n");
cPoolLinks -= WorldGraph.RejectInlineLinks ( pTempPool, file );
// now malloc a pool just large enough to hold the links that are actually used
WorldGraph.m_pLinkPool = (CLink *) calloc ( sizeof ( CLink ), cPoolLinks );
if ( !WorldGraph.m_pLinkPool )
{// couldn't make the link pool!
ALERT ( at_aiconsole, "Couldn't malloc LinkPool!\n" );
if ( pTempPool )
{
free ( pTempPool );
}
if ( file )
{// close the file
fclose ( file );
}
return;
}
WorldGraph.m_cLinks = cPoolLinks;
//copy only the used portions of the TempPool into the graph's link pool
int iFinalPoolIndex = 0;
int iOldFirstLink;
for ( i = 0 ; i < WorldGraph.m_cNodes ; i++ )
{
iOldFirstLink = WorldGraph.m_pNodes[ i ].m_iFirstLink;// store this, because we have to re-assign it before entering the copy loop
WorldGraph.m_pNodes[ i ].m_iFirstLink = iFinalPoolIndex;
for ( j = 0 ; j < WorldGraph.m_pNodes[ i ].m_cNumLinks ; j++ )
{
WorldGraph.m_pLinkPool[ iFinalPoolIndex++ ] = pTempPool[ iOldFirstLink + j ];
}
}
// Node sorting numbers linked nodes close to each other
//
WorldGraph.SortNodes();
// This is used for HashSearch
//
WorldGraph.BuildLinkLookups();
fPairsValid = TRUE; // assume that the connection pairs are all valid to start
fprintf ( file, "\n\n-------------------------------------------------------------------------------\n");
fprintf ( file, "Link Pairings:\n");
// link integrity check. The idea here is that if Node A links to Node B, node B should
// link to node A. If not, we have a situation that prevents us from using a basic
// optimization in the FindNearestLink function.
for ( i = 0 ; i < WorldGraph.m_cNodes ; i++ )
{
for ( j = 0 ; j < WorldGraph.m_pNodes[ i ].m_cNumLinks ; j++ )
{
int iLink;
WorldGraph.HashSearch(WorldGraph.INodeLink(i,j), i, iLink);
if (iLink < 0)
{
fPairsValid = FALSE;// unmatched link pair.
fprintf ( file, "WARNING: Node %3d does not connect back to Node %3d\n", WorldGraph.INodeLink(i, j), i);
}
}
}
// !!!LATER - if all connections are properly paired, when can enable an optimization in the pathfinding code
// (in the find nearest line function)
if ( fPairsValid )
{
fprintf ( file, "\nAll Connections are Paired!\n");
}
fprintf ( file, "-------------------------------------------------------------------------------\n");
fprintf ( file, "\n\n-------------------------------------------------------------------------------\n");
fprintf ( file, "Total Number of Connections in Pool: %d\n", cPoolLinks );
fprintf ( file, "-------------------------------------------------------------------------------\n");
fprintf ( file, "Connection Pool: %d bytes\n", sizeof ( CLink ) * cPoolLinks );
fprintf ( file, "-------------------------------------------------------------------------------\n");
ALERT ( at_aiconsole, "%d Nodes, %d Connections\n", WorldGraph.m_cNodes, cPoolLinks );
// This is used for FindNearestNode
//
WorldGraph.BuildRegionTables();
// Push all of the LAND nodes down to the ground now. Leave the water and air nodes alone.
//
for ( i = 0 ; i < WorldGraph.m_cNodes ; i++ )
{
if ((WorldGraph.m_pNodes[ i ].m_afNodeInfo & bits_NODE_LAND))
{
WorldGraph.m_pNodes[ i ].m_vecOrigin.z -= NODE_HEIGHT;
}
}
if ( pTempPool )
{// free the temp pool
free ( pTempPool );
}
if ( file )
{
fclose ( file );
}
// We now have some graphing capabilities.
//
WorldGraph.m_fGraphPresent = TRUE;//graph is in memory.
WorldGraph.m_fGraphPointersSet = TRUE;// since the graph was generated, the pointers are ready
WorldGraph.m_fRoutingComplete = FALSE; // Optimal routes aren't computed, yet.
// Compute and compress the routing information.
//
WorldGraph.ComputeStaticRoutingTables();
// save the node graph for this level
WorldGraph.FSaveGraph( (char *)STRING( gpGlobals->mapname ) );
ALERT( at_console, "Done.\n");
}
//=========================================================
// returns a hardcoded path.
//=========================================================
void CTestHull :: PathFind ( void )
{
int iPath[ 50 ];
int iPathSize;
int i;
CNode *pNode, *pNextNode;
if ( !WorldGraph.m_fGraphPresent || !WorldGraph.m_fGraphPointersSet )
{// protect us in the case that the node graph isn't available
ALERT ( at_aiconsole, "Graph not ready!\n" );
return;
}
iPathSize = WorldGraph.FindShortestPath ( iPath, 0, 19, 0, 0 ); // UNDONE use hull constant
if ( !iPathSize )
{
ALERT ( at_aiconsole, "No Path!\n" );
return;
}
ALERT ( at_aiconsole, "%d\n", iPathSize );
pNode = &WorldGraph.m_pNodes[ iPath [ 0 ] ];
for ( i = 0 ; i < iPathSize - 1 ; i++ )
{
pNextNode = &WorldGraph.m_pNodes[ iPath [ i + 1 ] ];
MESSAGE_BEGIN( MSG_BROADCAST, SVC_TEMPENTITY );
WRITE_BYTE( TE_SHOWLINE);
WRITE_COORD( pNode->m_vecOrigin.x );
WRITE_COORD( pNode->m_vecOrigin.y );
WRITE_COORD( pNode->m_vecOrigin.z + NODE_HEIGHT );
WRITE_COORD( pNextNode->m_vecOrigin.x);
WRITE_COORD( pNextNode->m_vecOrigin.y);
WRITE_COORD( pNextNode->m_vecOrigin.z + NODE_HEIGHT);
MESSAGE_END();
pNode = pNextNode;
}
}
//=========================================================
// CStack Constructor
//=========================================================
CStack :: CStack( void )
{
m_level = 0;
}
//=========================================================
// pushes a value onto the stack
//=========================================================
void CStack :: Push( int value )
{
if ( m_level >= MAX_STACK_NODES )
{
printf("Error!\n");
return;
}
m_stack[m_level] = value;
m_level++;
}
//=========================================================
// pops a value off of the stack
//=========================================================
int CStack :: Pop( void )
{
if ( m_level <= 0 )
return -1;
m_level--;
return m_stack[ m_level ];
}
//=========================================================
// returns the value on the top of the stack
//=========================================================
int CStack :: Top ( void )
{
return m_stack[ m_level - 1 ];
}
//=========================================================
// copies every element on the stack into an array LIFO
//=========================================================
void CStack :: CopyToArray ( int *piArray )
{
int i;
for ( i = 0 ; i < m_level ; i++ )
{
piArray[ i ] = m_stack[ i ];
}
}
//=========================================================
// CQueue constructor
//=========================================================
CQueue :: CQueue( void )
{
m_cSize = 0;
m_head = 0;
m_tail = -1;
}
//=========================================================
// inserts a value into the queue
//=========================================================
void CQueue :: Insert ( int iValue, float fPriority )
{
if ( Full() )
{
printf ( "Queue is full!\n" );
return;
}
m_tail++;
if ( m_tail == MAX_STACK_NODES )
{//wrap around
m_tail = 0;
}
m_queue[ m_tail ].Id = iValue;
m_queue[ m_tail ].Priority = fPriority;
m_cSize++;
}
//=========================================================
// removes a value from the queue (FIFO)
//=========================================================
int CQueue :: Remove ( float &fPriority )
{
if ( m_head == MAX_STACK_NODES )
{// wrap
m_head = 0;
}
m_cSize--;
fPriority = m_queue[ m_head ].Priority;
return m_queue[ m_head++ ].Id;
}
//=========================================================
// CQueue constructor
//=========================================================
CQueuePriority :: CQueuePriority( void )
{
m_cSize = 0;
}
//=========================================================
// inserts a value into the priority queue
//=========================================================
void CQueuePriority :: Insert( int iValue, float fPriority )
{
if ( Full() )
{
printf ( "Queue is full!\n" );
return;
}
m_heap[ m_cSize ].Priority = fPriority;
m_heap[ m_cSize ].Id = iValue;
m_cSize++;
Heap_SiftUp();
}
//=========================================================
// removes the smallest item from the priority queue
//
//=========================================================
int CQueuePriority :: Remove( float &fPriority )
{
int iReturn = m_heap[ 0 ].Id;
fPriority = m_heap[ 0 ].Priority;
m_cSize--;
m_heap[ 0 ] = m_heap[ m_cSize ];
Heap_SiftDown(0);
return iReturn;
}
#define HEAP_LEFT_CHILD(x) (2*(x)+1)
#define HEAP_RIGHT_CHILD(x) (2*(x)+2)
#define HEAP_PARENT(x) (((x)-1)/2)
void CQueuePriority::Heap_SiftDown(int iSubRoot)
{
int parent = iSubRoot;
int child = HEAP_LEFT_CHILD(parent);
struct tag_HEAP_NODE Ref = m_heap[ parent ];
while (child < m_cSize)
{
int rightchild = HEAP_RIGHT_CHILD(parent);
if (rightchild < m_cSize)
{
if ( m_heap[ rightchild ].Priority < m_heap[ child ].Priority )
{
child = rightchild;
}
}
if ( Ref.Priority <= m_heap[ child ].Priority )
break;
m_heap[ parent ] = m_heap[ child ];
parent = child;
child = HEAP_LEFT_CHILD(parent);
}
m_heap[ parent ] = Ref;
}
void CQueuePriority::Heap_SiftUp(void)
{
int child = m_cSize-1;
while (child)
{
int parent = HEAP_PARENT(child);
if ( m_heap[ parent ].Priority <= m_heap[ child ].Priority )
break;
struct tag_HEAP_NODE Tmp;
Tmp = m_heap[ child ];
m_heap[ child ] = m_heap[ parent ];
m_heap[ parent ] = Tmp;
child = parent;
}
}
//=========================================================
// CGraph - FLoadGraph - attempts to load a node graph from disk.
// if the current level is maps/snar.bsp, maps/graphs/snar.nod
// will be loaded. If file cannot be loaded, the node tree
// will be created and saved to disk.
//=========================================================
int CGraph :: FLoadGraph ( char *szMapName )
{
char szFilename[MAX_PATH];
int iVersion;
int length;
byte *aMemFile;
byte *pMemFile;
// make sure the directories have been made
char szDirName[MAX_PATH];
GET_GAME_DIR( szDirName );
strcat( szDirName, "/maps" );
CreateDirectory( szDirName, NULL );
strcat( szDirName, "/graphs" );
CreateDirectory( szDirName, NULL );
strcpy ( szFilename, "maps/graphs/" );
strcat ( szFilename, szMapName );
strcat( szFilename, ".nod" );
pMemFile = aMemFile = LOAD_FILE_FOR_ME(szFilename, &length);
if ( !aMemFile )
{
return FALSE;
}
else
{
// Read the graph version number
//
length -= sizeof(int);
if (length < 0) goto ShortFile;
memcpy(&iVersion, pMemFile, sizeof(int));
pMemFile += sizeof(int);
if ( iVersion != GRAPH_VERSION )
{
// This file was written by a different build of the dll!
//
ALERT ( at_aiconsole, "**ERROR** Graph version is %d, expected %d\n",iVersion, GRAPH_VERSION );
goto ShortFile;
}
// Read the graph class
//
length -= sizeof(CGraph);
if (length < 0) goto ShortFile;
memcpy(this, pMemFile, sizeof(CGraph));
pMemFile += sizeof(CGraph);
// Set the pointers to zero, just in case we run out of memory.
//
m_pNodes = NULL;
m_pLinkPool = NULL;
m_di = NULL;
m_pRouteInfo = NULL;
m_pHashLinks = NULL;
// Malloc for the nodes
//
m_pNodes = ( CNode * )calloc ( sizeof ( CNode ), m_cNodes );
if ( !m_pNodes )
{
ALERT ( at_aiconsole, "**ERROR**\nCouldn't malloc %d nodes!\n", m_cNodes );
goto NoMemory;
}
// Read in all the nodes
//
length -= sizeof(CNode) * m_cNodes;
if (length < 0) goto ShortFile;
memcpy(m_pNodes, pMemFile, sizeof(CNode)*m_cNodes);
pMemFile += sizeof(CNode) * m_cNodes;
// Malloc for the link pool
//
m_pLinkPool = ( CLink * )calloc ( sizeof ( CLink ), m_cLinks );
if ( !m_pLinkPool )
{
ALERT ( at_aiconsole, "**ERROR**\nCouldn't malloc %d link!\n", m_cLinks );
goto NoMemory;
}
// Read in all the links
//
length -= sizeof(CLink)*m_cLinks;
if (length < 0) goto ShortFile;
memcpy(m_pLinkPool, pMemFile, sizeof(CLink)*m_cLinks);
pMemFile += sizeof(CLink)*m_cLinks;
// Malloc for the sorting info.
//
m_di = (DIST_INFO *)calloc( sizeof(DIST_INFO), m_cNodes );
if ( !m_di )
{
ALERT ( at_aiconsole, "***ERROR**\nCouldn't malloc %d entries sorting nodes!\n", m_cNodes );
goto NoMemory;
}
// Read it in.
//
length -= sizeof(DIST_INFO)*m_cNodes;
if (length < 0) goto ShortFile;
memcpy(m_di, pMemFile, sizeof(DIST_INFO)*m_cNodes);
pMemFile += sizeof(DIST_INFO)*m_cNodes;
// Malloc for the routing info.
//
m_fRoutingComplete = FALSE;
m_pRouteInfo = (char *)calloc( sizeof(char), m_nRouteInfo );
if ( !m_pRouteInfo )
{
ALERT ( at_aiconsole, "***ERROR**\nCounldn't malloc %d route bytes!\n", m_nRouteInfo );
goto NoMemory;
}
m_CheckedCounter = 0;
for (int i = 0; i < m_cNodes; i++)
{
m_di[i].m_CheckedEvent = 0;
}
// Read in the route information.
//
length -= sizeof(char)*m_nRouteInfo;
if (length < 0) goto ShortFile;
memcpy(m_pRouteInfo, pMemFile, sizeof(char)*m_nRouteInfo);
pMemFile += sizeof(char)*m_nRouteInfo;
m_fRoutingComplete = TRUE;;
// malloc for the hash links
//
m_pHashLinks = (short *)calloc(sizeof(short), m_nHashLinks);
if (!m_pHashLinks)
{
ALERT ( at_aiconsole, "***ERROR**\nCounldn't malloc %d hash link bytes!\n", m_nHashLinks );
goto NoMemory;
}
// Read in the hash link information
//
length -= sizeof(short)*m_nHashLinks;
if (length < 0) goto ShortFile;
memcpy(m_pHashLinks, pMemFile, sizeof(short)*m_nHashLinks);
pMemFile += sizeof(short)*m_nHashLinks;
// Set the graph present flag, clear the pointers set flag
//
m_fGraphPresent = TRUE;
m_fGraphPointersSet = FALSE;
FREE_FILE(aMemFile);
if (length != 0)
{
ALERT ( at_aiconsole, "***WARNING***:Node graph was longer than expected by %d bytes.!\n", length);
}
return TRUE;
}
ShortFile:
NoMemory:
FREE_FILE(aMemFile);
return FALSE;
}
//=========================================================
// CGraph - FSaveGraph - It's not rocket science.
// this WILL overwrite existing files.
//=========================================================
int CGraph :: FSaveGraph ( char *szMapName )
{
int iVersion = GRAPH_VERSION;
char szFilename[MAX_PATH];
FILE *file;
if ( !m_fGraphPresent || !m_fGraphPointersSet )
{// protect us in the case that the node graph isn't available or built
ALERT ( at_aiconsole, "Graph not ready!\n" );
return FALSE;
}
// make sure directories have been made
GET_GAME_DIR( szFilename );
strcat( szFilename, "/maps" );
CreateDirectory( szFilename, NULL );
strcat( szFilename, "/graphs" );
CreateDirectory( szFilename, NULL );
strcat( szFilename, "/" );
strcat( szFilename, szMapName );
strcat( szFilename, ".nod" );
file = fopen ( szFilename, "wb" );
ALERT ( at_aiconsole, "Created: %s\n", szFilename );
if ( !file )
{// couldn't create
ALERT ( at_aiconsole, "Couldn't Create: %s\n", szFilename );
return FALSE;
}
else
{
// write the version
fwrite ( &iVersion, sizeof ( int ), 1, file );
// write the CGraph class
fwrite ( this, sizeof ( CGraph ), 1, file );
// write the nodes
fwrite ( m_pNodes, sizeof ( CNode ), m_cNodes, file );
// write the links
fwrite ( m_pLinkPool, sizeof ( CLink ), m_cLinks, file );
fwrite ( m_di, sizeof(DIST_INFO), m_cNodes, file );
// Write the route info.
//
if ( m_pRouteInfo && m_nRouteInfo )
{
fwrite ( m_pRouteInfo, sizeof( char ), m_nRouteInfo, file );
}
if (m_pHashLinks && m_nHashLinks)
{
fwrite(m_pHashLinks, sizeof(short), m_nHashLinks, file);
}
fclose ( file );
return TRUE;
}
}
//=========================================================
// CGraph - FSetGraphPointers - Takes the modelnames of
// all of the brush ents that block connections in the node
// graph and resolves them into pointers to those entities.
// this is done after loading the graph from disk, whereupon
// the pointers are not valid.
//=========================================================
int CGraph :: FSetGraphPointers ( void )
{
int i;
edict_t *pentLinkEnt;
for ( i = 0 ; i < m_cLinks ; i++ )
{// go through all of the links
if ( m_pLinkPool[ i ].m_pLinkEnt != NULL )
{
char name[5];
// when graphs are saved, any valid pointers are will be non-zero, signifying that we should
// reset those pointers upon reloading. Any pointers that were NULL when the graph was saved
// will be NULL when reloaded, and will ignored by this function.
// m_szLinkEntModelname is not necessarily NULL terminated (so we can store it in a more alignment-friendly 4 bytes)
memcpy( name, m_pLinkPool[ i ].m_szLinkEntModelname, 4 );
name[4] = 0;
pentLinkEnt = FIND_ENTITY_BY_STRING( NULL, "model", name );
if ( FNullEnt ( pentLinkEnt ) )
{
// the ent isn't around anymore? Either there is a major problem, or it was removed from the world
// ( like a func_breakable that's been destroyed or something ). Make sure that LinkEnt is null.
ALERT ( at_aiconsole, "**Could not find model %s\n", name );
m_pLinkPool[ i ].m_pLinkEnt = NULL;
}
else
{
m_pLinkPool[ i ].m_pLinkEnt = VARS( pentLinkEnt );
if ( !FBitSet( m_pLinkPool[ i ].m_pLinkEnt->flags, FL_GRAPHED ) )
{
m_pLinkPool[ i ].m_pLinkEnt->flags += FL_GRAPHED;
}
}
}
}
// the pointers are now set.
m_fGraphPointersSet = TRUE;
return TRUE;
}
//=========================================================
// CGraph - CheckNODFile - this function checks the date of
// the BSP file that was just loaded and the date of the a
// ssociated .NOD file. If the NOD file is not present, or
// is older than the BSP file, we rebuild it.
//
// returns FALSE if the .NOD file doesn't qualify and needs
// to be rebuilt.
//
// !!!BUGBUG - the file times we get back are 20 hours ahead!
// since this happens consistantly, we can still correctly
// determine which of the 2 files is newer. This needs fixed,
// though. ( I now suspect that we are getting GMT back from
// these functions and must compensate for local time ) (sjb)
//=========================================================
int CGraph :: CheckNODFile ( char *szMapName )
{
int retValue;
char szBspFilename[MAX_PATH];
char szGraphFilename[MAX_PATH];
strcpy ( szBspFilename, "maps/" );
strcat ( szBspFilename, szMapName );
strcat ( szBspFilename, ".bsp" );
strcpy ( szGraphFilename, "maps/graphs/" );
strcat ( szGraphFilename, szMapName );
strcat ( szGraphFilename, ".nod" );
retValue = TRUE;
int iCompare;
if (COMPARE_FILE_TIME(szBspFilename, szGraphFilename, &iCompare))
{
if ( iCompare > 0 )
{// BSP file is newer.
ALERT ( at_aiconsole, ".NOD File will be updated\n\n" );
retValue = FALSE;
}
}
else
{
retValue = FALSE;
}
return retValue;
}
#define ENTRY_STATE_EMPTY -1
struct tagNodePair
{
short iSrc;
short iDest;
};
void CGraph::HashInsert(int iSrcNode, int iDestNode, int iKey)
{
struct tagNodePair np;
np.iSrc = iSrcNode;
np.iDest = iDestNode;
CRC32_t dwHash;
CRC32_INIT(&dwHash);
CRC32_PROCESS_BUFFER(&dwHash, &np, sizeof(np));
dwHash = CRC32_FINAL(dwHash);
int di = m_HashPrimes[dwHash&15];
int i = (dwHash >> 4) % m_nHashLinks;
while (m_pHashLinks[i] != ENTRY_STATE_EMPTY)
{
i += di;
if (i >= m_nHashLinks) i -= m_nHashLinks;
}
m_pHashLinks[i] = iKey;
}
void CGraph::HashSearch(int iSrcNode, int iDestNode, int &iKey)
{
struct tagNodePair np;
np.iSrc = iSrcNode;
np.iDest = iDestNode;
CRC32_t dwHash;
CRC32_INIT(&dwHash);
CRC32_PROCESS_BUFFER(&dwHash, &np, sizeof(np));
dwHash = CRC32_FINAL(dwHash);
int di = m_HashPrimes[dwHash&15];
int i = (dwHash >> 4) % m_nHashLinks;
while (m_pHashLinks[i] != ENTRY_STATE_EMPTY)
{
CLink &link = Link(m_pHashLinks[i]);
if (iSrcNode == link.m_iSrcNode && iDestNode == link.m_iDestNode)
{
break;
}
else
{
i += di;
if (i >= m_nHashLinks) i -= m_nHashLinks;
}
}
iKey = m_pHashLinks[i];
}
#define NUMBER_OF_PRIMES 177
int Primes[NUMBER_OF_PRIMES] =
{ 1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67,
71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239,
241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337,
347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433,
439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541,
547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641,
643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743,
751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857,
859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971,
977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 0 };
void CGraph::HashChoosePrimes(int TableSize)
{
int LargestPrime = TableSize/2;
if (LargestPrime > Primes[NUMBER_OF_PRIMES-2])
{
LargestPrime = Primes[NUMBER_OF_PRIMES-2];
}
int Spacing = LargestPrime/16;
// Pick a set primes that are evenly spaced from (0 to LargestPrime)
// We divide this interval into 16 equal sized zones. We want to find
// one prime number that best represents that zone.
//
for (int iZone = 1, iPrime = 0; iPrime < 16; iZone += Spacing)
{
// Search for a prime number that is less than the target zone
// number given by iZone.
//
int Lower = Primes[0];
for (int jPrime = 0; Primes[jPrime] != 0; jPrime++)
{
if (jPrime != 0 && TableSize % Primes[jPrime] == 0) continue;
int Upper = Primes[jPrime];
if (Lower <= iZone && iZone <= Upper)
{
// Choose the closest lower prime number.
//
if (iZone - Lower <= Upper - iZone)
{
m_HashPrimes[iPrime++] = Lower;
}
else
{
m_HashPrimes[iPrime++] = Upper;
}
break;
}
Lower = Upper;
}
}
// Alternate negative and positive numbers
//
for (iPrime = 0; iPrime < 16; iPrime += 2)
{
m_HashPrimes[iPrime] = TableSize-m_HashPrimes[iPrime];
}
// Shuffle the set of primes to reduce correlation with bits in
// hash key.
//
for (iPrime = 0; iPrime < 16-1; iPrime++)
{
int Pick = RANDOM_LONG(0, 15-iPrime);
int Temp = m_HashPrimes[Pick];
m_HashPrimes[Pick] = m_HashPrimes[15-iPrime];
m_HashPrimes[15-iPrime] = Temp;
}
}
// Renumber nodes so that nodes that link together are together.
//
#define UNNUMBERED_NODE -1
void CGraph::SortNodes(void)
{
// We are using m_iPreviousNode to be the new node number.
// After assigning new node numbers to everything, we move
// things and patchup the links.
//
int iNodeCnt = 0;
m_pNodes[0].m_iPreviousNode = iNodeCnt++;
for (int i = 1; i < m_cNodes; i++)
{
m_pNodes[i].m_iPreviousNode = UNNUMBERED_NODE;
}
for (i = 0; i < m_cNodes; i++)
{
// Run through all of this node's neighbors
//
for (int j = 0 ; j < m_pNodes[i].m_cNumLinks; j++ )
{
int iDestNode = INodeLink(i, j);
if (m_pNodes[iDestNode].m_iPreviousNode == UNNUMBERED_NODE)
{
m_pNodes[iDestNode].m_iPreviousNode = iNodeCnt++;
}
}
}
// Assign remaining node numbers to unlinked nodes.
//
for (i = 0; i < m_cNodes; i++)
{
if (m_pNodes[i].m_iPreviousNode == UNNUMBERED_NODE)
{
m_pNodes[i].m_iPreviousNode = iNodeCnt++;
}
}
// Alter links to reflect new node numbers.
//
for (i = 0; i < m_cLinks; i++)
{
m_pLinkPool[i].m_iSrcNode = m_pNodes[m_pLinkPool[i].m_iSrcNode].m_iPreviousNode;
m_pLinkPool[i].m_iDestNode = m_pNodes[m_pLinkPool[i].m_iDestNode].m_iPreviousNode;
}
// Rearrange nodes to reflect new node numbering.
//
for (i = 0; i < m_cNodes; i++)
{
while (m_pNodes[i].m_iPreviousNode != i)
{
// Move current node off to where it should be, and bring
// that other node back into the current slot.
//
int iDestNode = m_pNodes[i].m_iPreviousNode;
CNode TempNode = m_pNodes[iDestNode];
m_pNodes[iDestNode] = m_pNodes[i];
m_pNodes[i] = TempNode;
}
}
}
void CGraph::BuildLinkLookups(void)
{
m_nHashLinks = 3*m_cLinks/2 + 3;
HashChoosePrimes(m_nHashLinks);
m_pHashLinks = (short *)calloc(sizeof(short), m_nHashLinks);
if (!m_pHashLinks)
{
ALERT(at_aiconsole, "Couldn't allocated Link Lookup Table.\n");
return;
}
for (int i = 0; i < m_nHashLinks; i++)
{
m_pHashLinks[i] = ENTRY_STATE_EMPTY;
}
for (i = 0; i < m_cLinks; i++)
{
CLink &link = Link(i);
HashInsert(link.m_iSrcNode, link.m_iDestNode, i);
}
#if 0
for (i = 0; i < m_cLinks; i++)
{
CLink &link = Link(i);
int iKey;
HashSearch(link.m_iSrcNode, link.m_iDestNode, iKey);
if (iKey != i)
{
ALERT(at_aiconsole, "HashLinks don't match (%d versus %d)\n", i, iKey);
}
}
#endif
}
void CGraph::BuildRegionTables(void)
{
if (m_di) free(m_di);
// Go ahead and setup for range searching the nodes for FindNearestNodes
//
m_di = (DIST_INFO *)calloc(sizeof(DIST_INFO), m_cNodes);
if (!m_di)
{
ALERT(at_aiconsole, "Couldn't allocated node ordering array.\n");
return;
}
// Calculate regions for all the nodes.
//
//
for (int i = 0; i < 3; i++)
{
m_RegionMin[i] = 999999999.0; // just a big number out there;
m_RegionMax[i] = -999999999.0; // just a big number out there;
}
for (i = 0; i < m_cNodes; i++)
{
if (m_pNodes[i].m_vecOrigin.x < m_RegionMin[0])
m_RegionMin[0] = m_pNodes[i].m_vecOrigin.x;
if (m_pNodes[i].m_vecOrigin.y < m_RegionMin[1])
m_RegionMin[1] = m_pNodes[i].m_vecOrigin.y;
if (m_pNodes[i].m_vecOrigin.z < m_RegionMin[2])
m_RegionMin[2] = m_pNodes[i].m_vecOrigin.z;
if (m_pNodes[i].m_vecOrigin.x > m_RegionMax[0])
m_RegionMax[0] = m_pNodes[i].m_vecOrigin.x;
if (m_pNodes[i].m_vecOrigin.y > m_RegionMax[1])
m_RegionMax[1] = m_pNodes[i].m_vecOrigin.y;
if (m_pNodes[i].m_vecOrigin.z > m_RegionMax[2])
m_RegionMax[2] = m_pNodes[i].m_vecOrigin.z;
}
for (i = 0; i < m_cNodes; i++)
{
m_pNodes[i].m_Region[0] = CALC_RANGE(m_pNodes[i].m_vecOrigin.x, m_RegionMin[0], m_RegionMax[0]);
m_pNodes[i].m_Region[1] = CALC_RANGE(m_pNodes[i].m_vecOrigin.y, m_RegionMin[1], m_RegionMax[1]);
m_pNodes[i].m_Region[2] = CALC_RANGE(m_pNodes[i].m_vecOrigin.z, m_RegionMin[2], m_RegionMax[2]);
}
for (i = 0; i < 3; i++)
{
for (int j = 0; j < NUM_RANGES; j++)
{
m_RangeStart[i][j] = 255;
m_RangeEnd[i][j] = 0;
}
for (j = 0; j < m_cNodes; j++)
{
m_di[j].m_SortedBy[i] = j;
}
for (j = 0; j < m_cNodes - 1; j++)
{
int jNode = m_di[j].m_SortedBy[i];
int jCodeX = m_pNodes[jNode].m_Region[0];
int jCodeY = m_pNodes[jNode].m_Region[1];
int jCodeZ = m_pNodes[jNode].m_Region[2];
int jCode;
switch (i)
{
case 0:
jCode = (jCodeX << 16) + (jCodeY << 8) + jCodeZ;
break;
case 1:
jCode = (jCodeY << 16) + (jCodeZ << 8) + jCodeX;
break;
case 2:
jCode = (jCodeZ << 16) + (jCodeX << 8) + jCodeY;
break;
}
for (int k = j+1; k < m_cNodes; k++)
{
int kNode = m_di[k].m_SortedBy[i];
int kCodeX = m_pNodes[kNode].m_Region[0];
int kCodeY = m_pNodes[kNode].m_Region[1];
int kCodeZ = m_pNodes[kNode].m_Region[2];
int kCode;
switch (i)
{
case 0:
kCode = (kCodeX << 16) + (kCodeY << 8) + kCodeZ;
break;
case 1:
kCode = (kCodeY << 16) + (kCodeZ << 8) + kCodeX;
break;
case 2:
kCode = (kCodeZ << 16) + (kCodeX << 8) + kCodeY;
break;
}
if (kCode < jCode)
{
// Swap j and k entries.
//
int Tmp = m_di[j].m_SortedBy[i];
m_di[j].m_SortedBy[i] = m_di[k].m_SortedBy[i];
m_di[k].m_SortedBy[i] = Tmp;
}
}
}
}
// Generate lookup tables.
//
for (i = 0; i < m_cNodes; i++)
{
int CodeX = m_pNodes[m_di[i].m_SortedBy[0]].m_Region[0];
int CodeY = m_pNodes[m_di[i].m_SortedBy[1]].m_Region[1];
int CodeZ = m_pNodes[m_di[i].m_SortedBy[2]].m_Region[2];
if (i < m_RangeStart[0][CodeX])
{
m_RangeStart[0][CodeX] = i;
}
if (i < m_RangeStart[1][CodeY])
{
m_RangeStart[1][CodeY] = i;
}
if (i < m_RangeStart[2][CodeZ])
{
m_RangeStart[2][CodeZ] = i;
}
if (m_RangeEnd[0][CodeX] < i)
{
m_RangeEnd[0][CodeX] = i;
}
if (m_RangeEnd[1][CodeY] < i)
{
m_RangeEnd[1][CodeY] = i;
}
if (m_RangeEnd[2][CodeZ] < i)
{
m_RangeEnd[2][CodeZ] = i;
}
}
// Initialize the cache.
//
memset(m_Cache, 0, sizeof(m_Cache));
}
void CGraph :: ComputeStaticRoutingTables( void )
{
int nRoutes = m_cNodes*m_cNodes;
#define FROM_TO(x,y) ((x)*m_cNodes+(y))
short *Routes = new short[nRoutes];
int *pMyPath = new int[m_cNodes];
unsigned short *BestNextNodes = new unsigned short[m_cNodes];
char *pRoute = new char[m_cNodes*2];
if (Routes && pMyPath && BestNextNodes && pRoute)
{
int nTotalCompressedSize = 0;
for (int iHull = 0; iHull < MAX_NODE_HULLS; iHull++)
{
for (int iCap = 0; iCap < 2; iCap++)
{
int iCapMask;
switch (iCap)
{
case 0:
iCapMask = 0;
break;
case 1:
iCapMask = bits_CAP_OPEN_DOORS | bits_CAP_AUTO_DOORS | bits_CAP_USE;
break;
}
// Initialize Routing table to uncalculated.
//
for (int iFrom = 0; iFrom < m_cNodes; iFrom++)
{
for (int iTo = 0; iTo < m_cNodes; iTo++)
{
Routes[FROM_TO(iFrom, iTo)] = -1;
}
}
for (iFrom = 0; iFrom < m_cNodes; iFrom++)
{
for (int iTo = m_cNodes-1; iTo >= 0; iTo--)
{
if (Routes[FROM_TO(iFrom, iTo)] != -1) continue;
int cPathSize = FindShortestPath(pMyPath, iFrom, iTo, iHull, iCapMask);
// Use the computed path to update the routing table.
//
if (cPathSize > 1)
{
for (int iNode = 0; iNode < cPathSize-1; iNode++)
{
int iStart = pMyPath[iNode];
int iNext = pMyPath[iNode+1];
for (int iNode1 = iNode+1; iNode1 < cPathSize; iNode1++)
{
int iEnd = pMyPath[iNode1];
Routes[FROM_TO(iStart, iEnd)] = iNext;
}
}
#if 0
// Well, at first glance, this should work, but actually it's safer
// to be told explictly that you can take a series of node in a
// particular direction. Some links don't appear to have links in
// the opposite direction.
//
for (iNode = cPathSize-1; iNode >= 1; iNode--)
{
int iStart = pMyPath[iNode];
int iNext = pMyPath[iNode-1];
for (int iNode1 = iNode-1; iNode1 >= 0; iNode1--)
{
int iEnd = pMyPath[iNode1];
Routes[FROM_TO(iStart, iEnd)] = iNext;
}
}
#endif
}
else
{
Routes[FROM_TO(iFrom, iTo)] = iFrom;
Routes[FROM_TO(iTo, iFrom)] = iTo;
}
}
}
for (iFrom = 0; iFrom < m_cNodes; iFrom++)
{
for (int iTo = 0; iTo < m_cNodes; iTo++)
{
BestNextNodes[iTo] = Routes[FROM_TO(iFrom, iTo)];
}
// Compress this node's routing table.
//
int iLastNode = 9999999; // just really big.
int cSequence = 0;
int cRepeats = 0;
int CompressedSize = 0;
char *p = pRoute;
for (int i = 0; i < m_cNodes; i++)
{
BOOL CanRepeat = ((BestNextNodes[i] == iLastNode) && cRepeats < 127);
BOOL CanSequence = (BestNextNodes[i] == i && cSequence < 128);
if (cRepeats)
{
if (CanRepeat)
{
cRepeats++;
}
else
{
// Emit the repeat phrase.
//
CompressedSize += 2; // (count-1, iLastNode-i)
*p++ = cRepeats - 1;
int a = iLastNode - iFrom;
int b = iLastNode - iFrom + m_cNodes;
int c = iLastNode - iFrom - m_cNodes;
if (-128 <= a && a <= 127)
{
*p++ = a;
}
else if (-128 <= b && b <= 127)
{
*p++ = b;
}
else if (-128 <= c && c <= 127)
{
*p++ = c;
}
else
{
ALERT( at_aiconsole, "Nodes need sorting (%d,%d)!\n", iLastNode, iFrom);
}
cRepeats = 0;
if (CanSequence)
{
// Start a sequence.
//
cSequence++;
}
else
{
// Start another repeat.
//
cRepeats++;
}
}
}
else if (cSequence)
{
if (CanSequence)
{
cSequence++;
}
else
{
// It may be advantageous to combine
// a single-entry sequence phrase with the
// next repeat phrase.
//
if (cSequence == 1 && CanRepeat)
{
// Combine with repeat phrase.
//
cRepeats = 2;
cSequence = 0;
}
else
{
// Emit the sequence phrase.
//
CompressedSize += 1; // (-count)
*p++ = -cSequence;
cSequence = 0;
// Start a repeat sequence.
//
cRepeats++;
}
}
}
else
{
if (CanSequence)
{
// Start a sequence phrase.
//
cSequence++;
}
else
{
// Start a repeat sequence.
//
cRepeats++;
}
}
iLastNode = BestNextNodes[i];
}
if (cRepeats)
{
// Emit the repeat phrase.
//
CompressedSize += 2;
*p++ = cRepeats - 1;
#if 0
iLastNode = iFrom + *pRoute;
if (iLastNode >= m_cNodes) iLastNode -= m_cNodes;
else if (iLastNode < 0) iLastNode += m_cNodes;
#endif
int a = iLastNode - iFrom;
int b = iLastNode - iFrom + m_cNodes;
int c = iLastNode - iFrom - m_cNodes;
if (-128 <= a && a <= 127)
{
*p++ = a;
}
else if (-128 <= b && b <= 127)
{
*p++ = b;
}
else if (-128 <= c && c <= 127)
{
*p++ = c;
}
else
{
ALERT( at_aiconsole, "Nodes need sorting (%d,%d)!\n", iLastNode, iFrom);
}
}
if (cSequence)
{
// Emit the Sequence phrase.
//
CompressedSize += 1;
*p++ = -cSequence;
}
// Go find a place to store this thing and point to it.
//
int nRoute = p - pRoute;
if (m_pRouteInfo)
{
for (int i = 0; i < m_nRouteInfo - nRoute; i++)
{
if (memcmp(m_pRouteInfo + i, pRoute, nRoute) == 0)
{
break;
}
}
if (i < m_nRouteInfo - nRoute)
{
m_pNodes[ iFrom ].m_pNextBestNode[iHull][iCap] = i;
}
else
{
char *Tmp = (char *)calloc(sizeof(char), (m_nRouteInfo + nRoute));
memcpy(Tmp, m_pRouteInfo, m_nRouteInfo);
free(m_pRouteInfo);
m_pRouteInfo = Tmp;
memcpy(m_pRouteInfo + m_nRouteInfo, pRoute, nRoute);
m_pNodes[ iFrom ].m_pNextBestNode[iHull][iCap] = m_nRouteInfo;
m_nRouteInfo += nRoute;
nTotalCompressedSize += CompressedSize;
}
}
else
{
m_nRouteInfo = nRoute;
m_pRouteInfo = (char *)calloc(sizeof(char), nRoute);
memcpy(m_pRouteInfo, pRoute, nRoute);
m_pNodes[ iFrom ].m_pNextBestNode[iHull][iCap] = 0;
nTotalCompressedSize += CompressedSize;
}
}
}
}
ALERT( at_aiconsole, "Size of Routes = %d\n", nTotalCompressedSize);
}
if (Routes) delete Routes;
if (BestNextNodes) delete BestNextNodes;
if (pRoute) delete pRoute;
if (pMyPath) delete pMyPath;
Routes = 0;
BestNextNodes = 0;
pRoute = 0;
pMyPath = 0;
#if 0
TestRoutingTables();
#endif
m_fRoutingComplete = TRUE;
}
// Test those routing tables. Doesn't really work, yet.
//
void CGraph :: TestRoutingTables( void )
{
int *pMyPath = new int[m_cNodes];
int *pMyPath2 = new int[m_cNodes];
if (pMyPath && pMyPath2)
{
for (int iHull = 0; iHull < MAX_NODE_HULLS; iHull++)
{
for (int iCap = 0; iCap < 2; iCap++)
{
int iCapMask;
switch (iCap)
{
case 0:
iCapMask = 0;
break;
case 1:
iCapMask = bits_CAP_OPEN_DOORS | bits_CAP_AUTO_DOORS | bits_CAP_USE;
break;
}
for (int iFrom = 0; iFrom < m_cNodes; iFrom++)
{
for (int iTo = 0; iTo < m_cNodes; iTo++)
{
m_fRoutingComplete = FALSE;
int cPathSize1 = FindShortestPath(pMyPath, iFrom, iTo, iHull, iCapMask);
m_fRoutingComplete = TRUE;
int cPathSize2 = FindShortestPath(pMyPath2, iFrom, iTo, iHull, iCapMask);
// Unless we can look at the entire path, we can verify that it's correct.
//
if (cPathSize2 == MAX_PATH_SIZE) continue;
// Compare distances.
//
#if 1
float flDistance1 = 0.0;
for (int i = 0; i < cPathSize1-1; i++)
{
// Find the link from pMyPath[i] to pMyPath[i+1]
//
if (pMyPath[i] == pMyPath[i+1]) continue;
int iVisitNode;
BOOL bFound = FALSE;
for (int iLink = 0; iLink < m_pNodes[pMyPath[i]].m_cNumLinks; iLink++)
{
iVisitNode = INodeLink ( pMyPath[i], iLink );
if (iVisitNode == pMyPath[i+1])
{
flDistance1 += m_pLinkPool[ m_pNodes[ pMyPath[i] ].m_iFirstLink + iLink].m_flWeight;
bFound = TRUE;
break;
}
}
if (!bFound)
{
ALERT(at_aiconsole, "No link.\n");
}
}
float flDistance2 = 0.0;
for (i = 0; i < cPathSize2-1; i++)
{
// Find the link from pMyPath2[i] to pMyPath2[i+1]
//
if (pMyPath2[i] == pMyPath2[i+1]) continue;
int iVisitNode;
BOOL bFound = FALSE;
for (int iLink = 0; iLink < m_pNodes[pMyPath2[i]].m_cNumLinks; iLink++)
{
iVisitNode = INodeLink ( pMyPath2[i], iLink );
if (iVisitNode == pMyPath2[i+1])
{
flDistance2 += m_pLinkPool[ m_pNodes[ pMyPath2[i] ].m_iFirstLink + iLink].m_flWeight;
bFound = TRUE;
break;
}
}
if (!bFound)
{
ALERT(at_aiconsole, "No link.\n");
}
}
if (fabs(flDistance1 - flDistance2) > 0.10)
{
#else
if (cPathSize1 != cPathSize2 || memcmp(pMyPath, pMyPath2, sizeof(int)*cPathSize1) != 0)
{
#endif
ALERT(at_aiconsole, "Routing is inconsistent!!!\n");
ALERT(at_aiconsole, "(%d to %d |%d/%d)1:", iFrom, iTo, iHull, iCap);
for (int i = 0; i < cPathSize1; i++)
{
ALERT(at_aiconsole, "%d ", pMyPath[i]);
}
ALERT(at_aiconsole, "\n(%d to %d |%d/%d)2:", iFrom, iTo, iHull, iCap);
for (i = 0; i < cPathSize2; i++)
{
ALERT(at_aiconsole, "%d ", pMyPath2[i]);
}
ALERT(at_aiconsole, "\n");
m_fRoutingComplete = FALSE;
cPathSize1 = FindShortestPath(pMyPath, iFrom, iTo, iHull, iCapMask);
m_fRoutingComplete = TRUE;
cPathSize2 = FindShortestPath(pMyPath2, iFrom, iTo, iHull, iCapMask);
goto EnoughSaid;
}
}
}
}
}
}
EnoughSaid:
if (pMyPath) delete pMyPath;
if (pMyPath2) delete pMyPath2;
pMyPath = 0;
pMyPath2 = 0;
}
//=========================================================
// CNodeViewer - Draws a graph of the shorted path from all nodes
// to current location (typically the player). It then draws
// as many connects as it can per frame, trying not to overflow the buffer
//=========================================================
class CNodeViewer : public CBaseEntity
{
public:
void Spawn( void );
int m_iBaseNode;
int m_iDraw;
int m_nVisited;
int m_aFrom[128];
int m_aTo[128];
int m_iHull;
int m_afNodeType;
Vector m_vecColor;
void FindNodeConnections( int iNode );
void AddNode( int iFrom, int iTo );
void EXPORT DrawThink( void );
};
LINK_ENTITY_TO_CLASS( node_viewer, CNodeViewer );
LINK_ENTITY_TO_CLASS( node_viewer_human, CNodeViewer );
LINK_ENTITY_TO_CLASS( node_viewer_fly, CNodeViewer );
LINK_ENTITY_TO_CLASS( node_viewer_large, CNodeViewer );
void CNodeViewer::Spawn( )
{
if ( !WorldGraph.m_fGraphPresent || !WorldGraph.m_fGraphPointersSet )
{// protect us in the case that the node graph isn't available or built
ALERT ( at_console, "Graph not ready!\n" );
UTIL_Remove( this );
return;
}
if (FClassnameIs( pev, "node_viewer_fly"))
{
m_iHull = NODE_FLY_HULL;
m_afNodeType = bits_NODE_AIR;
m_vecColor = Vector( 160, 100, 255 );
}
else if (FClassnameIs( pev, "node_viewer_large"))
{
m_iHull = NODE_LARGE_HULL;
m_afNodeType = bits_NODE_LAND | bits_NODE_WATER;
m_vecColor = Vector( 100, 255, 160 );
}
else
{
m_iHull = NODE_HUMAN_HULL;
m_afNodeType = bits_NODE_LAND | bits_NODE_WATER;
m_vecColor = Vector( 255, 160, 100 );
}
m_iBaseNode = WorldGraph.FindNearestNode ( pev->origin, m_afNodeType );
if ( m_iBaseNode < 0 )
{
ALERT( at_console, "No nearby node\n" );
return;
}
m_nVisited = 0;
ALERT( at_aiconsole, "basenode %d\n", m_iBaseNode );
if (WorldGraph.m_cNodes < 128)
{
for (int i = 0; i < WorldGraph.m_cNodes; i++)
{
AddNode( i, WorldGraph.NextNodeInRoute( i, m_iBaseNode, m_iHull, 0 ));
}
}
else
{
// do a depth traversal
FindNodeConnections( m_iBaseNode );
int start = 0;
int end;
do {
end = m_nVisited;
// ALERT( at_console, "%d :", m_nVisited );
for (end = m_nVisited; start < end; start++)
{
FindNodeConnections( m_aFrom[start] );
FindNodeConnections( m_aTo[start] );
}
} while (end != m_nVisited);
}
ALERT( at_aiconsole, "%d nodes\n", m_nVisited );
m_iDraw = 0;
SetThink( DrawThink );
pev->nextthink = gpGlobals->time;
}
void CNodeViewer :: FindNodeConnections ( int iNode )
{
AddNode( iNode, WorldGraph.NextNodeInRoute( iNode, m_iBaseNode, m_iHull, 0 ));
for ( int i = 0 ; i < WorldGraph.m_pNodes[ iNode ].m_cNumLinks ; i++ )
{
CLink *pToLink = &WorldGraph.NodeLink( iNode, i);
AddNode( pToLink->m_iDestNode, WorldGraph.NextNodeInRoute( pToLink->m_iDestNode, m_iBaseNode, m_iHull, 0 ));
}
}
void CNodeViewer::AddNode( int iFrom, int iTo )
{
if (m_nVisited >= 128)
{
return;
}
else
{
if (iFrom == iTo)
return;
for (int i = 0; i < m_nVisited; i++)
{
if (m_aFrom[i] == iFrom && m_aTo[i] == iTo)
return;
if (m_aFrom[i] == iTo && m_aTo[i] == iFrom)
return;
}
m_aFrom[m_nVisited] = iFrom;
m_aTo[m_nVisited] = iTo;
m_nVisited++;
}
}
void CNodeViewer :: DrawThink( void )
{
pev->nextthink = gpGlobals->time;
for (int i = 0; i < 10; i++)
{
if (m_iDraw == m_nVisited)
{
UTIL_Remove( this );
return;
}
extern short g_sModelIndexLaser;
MESSAGE_BEGIN( MSG_BROADCAST, SVC_TEMPENTITY );
WRITE_BYTE( TE_BEAMPOINTS );
WRITE_COORD( WorldGraph.m_pNodes[ m_aFrom[m_iDraw] ].m_vecOrigin.x );
WRITE_COORD( WorldGraph.m_pNodes[ m_aFrom[m_iDraw] ].m_vecOrigin.y );
WRITE_COORD( WorldGraph.m_pNodes[ m_aFrom[m_iDraw] ].m_vecOrigin.z + NODE_HEIGHT );
WRITE_COORD( WorldGraph.m_pNodes[ m_aTo[m_iDraw] ].m_vecOrigin.x );
WRITE_COORD( WorldGraph.m_pNodes[ m_aTo[m_iDraw] ].m_vecOrigin.y );
WRITE_COORD( WorldGraph.m_pNodes[ m_aTo[m_iDraw] ].m_vecOrigin.z + NODE_HEIGHT );
WRITE_SHORT( g_sModelIndexLaser );
WRITE_BYTE( 0 ); // framerate
WRITE_BYTE( 0 ); // framerate
WRITE_BYTE( 250 ); // life
WRITE_BYTE( 40 ); // width
WRITE_BYTE( 0 ); // noise
WRITE_BYTE( m_vecColor.x ); // r, g, b
WRITE_BYTE( m_vecColor.y ); // r, g, b
WRITE_BYTE( m_vecColor.z ); // r, g, b
WRITE_BYTE( 128 ); // brightness
WRITE_BYTE( 0 ); // speed
MESSAGE_END();
m_iDraw++;
}
}
| [
"joropito@23c7d628-c96c-11de-a380-73d83ba7c083"
]
| [
[
[
1,
3642
]
]
]
|
46ba6ef29f0ed3d26a41f4520d472ee519433d83 | 4d5ee0b6f7be0c3841c050ed1dda88ec128ae7b4 | /src/nvmath/Fitting.cpp | d0a133db44b134186331f09df785d55375d754d8 | []
| no_license | saggita/nvidia-mesh-tools | 9df27d41b65b9742a9d45dc67af5f6835709f0c2 | a9b7fdd808e6719be88520e14bc60d58ea57e0bd | refs/heads/master | 2020-12-24T21:37:11.053752 | 2010-09-03T01:39:02 | 2010-09-03T01:39:02 | 56,893,300 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,219 | cpp | // This code is in the public domain -- [email protected]
#include "Fitting.h"
#include <nvcore/Algorithms.h> // max
#include <nvcore/Containers.h> // swap
#include <float.h> // FLT_MAX
using namespace nv;
// @@ Move to EigenSolver.h
static inline Vector3 firstEigenVector_PowerMethod(const float *__restrict matrix)
{
if (matrix[0] == 0 || matrix[3] == 0 || matrix[5] == 0)
{
return Vector3(zero);
}
const int NUM = 8;
Vector3 v(1, 1, 1);
for (int i = 0; i < NUM; i++)
{
float x = v.x() * matrix[0] + v.y() * matrix[1] + v.z() * matrix[2];
float y = v.x() * matrix[1] + v.y() * matrix[3] + v.z() * matrix[4];
float z = v.x() * matrix[2] + v.y() * matrix[4] + v.z() * matrix[5];
float norm = max(max(x, y), z);
v = Vector3(x, y, z) / norm;
}
return v;
}
Vector3 nv::Fit::computeCentroid(int n, const Vector3 *__restrict points)
{
Vector3 centroid(zero);
for (int i = 0; i < n; i++)
{
centroid += points[i];
}
centroid /= float(n);
return centroid;
}
Vector3 nv::Fit::computeCentroid(int n, const Vector3 *__restrict points, const float *__restrict weights, Vector3::Arg metric)
{
Vector3 centroid(zero);
float total = 0.0f;
for (int i = 0; i < n; i++)
{
total += weights[i];
centroid += weights[i]*points[i];
}
centroid /= total;
return centroid;
}
Vector3 nv::Fit::computeCovariance(int n, const Vector3 *__restrict points, float *__restrict covariance)
{
// compute the centroid
Vector3 centroid = computeCentroid(n, points);
// compute covariance matrix
for (int i = 0; i < 6; i++)
{
covariance[i] = 0.0f;
}
for (int i = 0; i < n; i++)
{
Vector3 v = points[i] - centroid;
covariance[0] += v.x() * v.x();
covariance[1] += v.x() * v.y();
covariance[2] += v.x() * v.z();
covariance[3] += v.y() * v.y();
covariance[4] += v.y() * v.z();
covariance[5] += v.z() * v.z();
}
return centroid;
}
Vector3 nv::Fit::computeCovariance(int n, const Vector3 *__restrict points, const float *__restrict weights, Vector3::Arg metric, float *__restrict covariance)
{
// compute the centroid
Vector3 centroid = computeCentroid(n, points, weights, metric);
// compute covariance matrix
for (int i = 0; i < 6; i++)
{
covariance[i] = 0.0f;
}
for (int i = 0; i < n; i++)
{
Vector3 a = (points[i] - centroid) * metric;
Vector3 b = weights[i]*a;
covariance[0] += a.x()*b.x();
covariance[1] += a.x()*b.y();
covariance[2] += a.x()*b.z();
covariance[3] += a.y()*b.y();
covariance[4] += a.y()*b.z();
covariance[5] += a.z()*b.z();
}
return centroid;
}
Vector3 nv::Fit::computePrincipalComponent(int n, const Vector3 *__restrict points)
{
float matrix[6];
computeCovariance(n, points, matrix);
return firstEigenVector_PowerMethod(matrix);
}
Vector3 nv::Fit::computePrincipalComponent(int n, const Vector3 *__restrict points, const float *__restrict weights, Vector3::Arg metric)
{
float matrix[6];
computeCovariance(n, points, weights, metric, matrix);
return firstEigenVector_PowerMethod(matrix);
}
Plane nv::Fit::bestPlane(int n, const Vector3 *__restrict points)
{
// compute the centroid and covariance
float matrix[6];
Vector3 centroid = computeCovariance(n, points, matrix);
if (matrix[0] == 0 || matrix[3] == 0 || matrix[5] == 0)
{
// If no plane defined, then return a horizontal plane.
return Plane(Vector3(0, 0, 1), centroid);
}
#pragma message(NV_FILE_LINE "TODO: need to write an eigensolver!")
// - Numerical Recipes in C is a good reference. Householder transforms followed by QL decomposition seems to be the best approach.
// - The one from magic-tools is now LGPL. For the 3D case it uses a cubic root solver, which is not very accurate.
// - Charles' Galaxy3 contains an implementation of the tridiagonalization method, but is under BPL.
//EigenSolver3 solver(matrix);
return Plane();
}
int nv::Fit::compute4Means(int n, const Vector3 *__restrict points, const float *__restrict weights, Vector3::Arg metric, Vector3 *__restrict cluster)
{
// Compute principal component.
float matrix[6];
Vector3 centroid = computeCovariance(n, points, weights, metric, matrix);
Vector3 principal = firstEigenVector_PowerMethod(matrix);
// Pick initial solution.
int mini, maxi;
mini = maxi = 0;
float mindps, maxdps;
mindps = maxdps = dot(points[0] - centroid, principal);
for (int i = 1; i < n; ++i)
{
float dps = dot(points[i] - centroid, principal);
if (dps < mindps) {
mindps = dps;
mini = i;
}
else {
maxdps = dps;
maxi = i;
}
}
cluster[0] = centroid + mindps * principal;
cluster[1] = centroid + maxdps * principal;
cluster[2] = (2 * cluster[0] + cluster[1]) / 3;
cluster[3] = (2 * cluster[1] + cluster[0]) / 3;
// Now we have to iteratively refine the clusters.
while (true)
{
Vector3 newCluster[4] = { Vector3(zero), Vector3(zero), Vector3(zero), Vector3(zero) };
float total[4] = {0, 0, 0, 0};
for (int i = 0; i < n; ++i)
{
// Find nearest cluster.
int nearest = 0;
float mindist = FLT_MAX;
for (int j = 0; j < 4; j++)
{
float dist = length_squared((cluster[j] - points[i]) * metric);
if (dist < mindist)
{
mindist = dist;
nearest = j;
}
}
newCluster[nearest] += weights[i] * points[i];
total[nearest] += weights[i];
}
for (int j = 0; j < 4; j++)
{
if (total[j] != 0)
newCluster[j] /= total[j];
}
if (equal(cluster[0], newCluster[0]) && equal(cluster[1], newCluster[1]) &&
equal(cluster[2], newCluster[2]) && equal(cluster[3], newCluster[3]))
{
return (total[0] != 0) + (total[1] != 0) + (total[2] != 0) + (total[3] != 0);
}
cluster[0] = newCluster[0];
cluster[1] = newCluster[1];
cluster[2] = newCluster[2];
cluster[3] = newCluster[3];
// Sort clusters by weight.
for (int i = 0; i < 4; i++)
{
for (int j = i; j > 0 && total[j] > total[j - 1]; j--)
{
swap( total[j], total[j - 1] );
swap( cluster[j], cluster[j - 1] );
}
}
}
}
| [
"castano@0f2971b0-9fc2-11dd-b4aa-53559073bf4c"
]
| [
[
[
1,
247
]
]
]
|
6d2dc44ede8cf7f8ed80af097556730b5e1c5727 | c58f258a699cc866ce889dc81af046cf3bff6530 | /include/qmlib/corelib/dates/boost_date.hpp | 0439dca9028826733e61c044390943fe5cc4a4ea | []
| no_license | KoWunnaKo/qmlib | db03e6227d4fff4ad90b19275cc03e35d6d10d0b | b874501b6f9e537035cabe3a19d61eed7196174c | refs/heads/master | 2021-05-27T21:59:56.698613 | 2010-02-18T08:27:51 | 2010-02-18T08:27:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,105 | hpp | //
//
#ifndef __BOOST_DATE_QM_HPP__
#define __BOOST_DATE_QM_HPP__
//
#include <qmlib/corelib/dates/date.hpp>
#include <qmlib/corelib/dates/juldate.hpp>
QM_NAMESPACE
class gregorian_roman_easter: public boost::gregorian::year_based_generator {
public:
typedef boost::gregorian::date date_type;
gregorian_roman_easter(int days):m_days(days){}
date_type get_date(boost::gregorian::greg_year y) const {
return juldate::ToDate<date_type>(juldate(juldate::RomanEaster(y)+m_days));
}
std::string to_string() const {return "";}
private:
int m_days;
};
class gregorian_orthodox_easter: public boost::gregorian::year_based_generator {
public:
typedef boost::gregorian::date date_type;
//
gregorian_orthodox_easter(int days):m_days(days){}
date_type get_date(boost::gregorian::greg_year y) const {
return juldate::ToDate<date_type>(juldate(juldate::OrthodoxEaster(y)+m_days));
}
std::string to_string() const {return "";}
private:
int m_days;
};
QM_NAMESPACE_END
#endif // __BOOST_DATE_QM_HPP__
| [
"[email protected]"
]
| [
[
[
1,
51
]
]
]
|
1d3ae57b5743325e1ba10b62a3c689e9b1aa33c0 | 0f8559dad8e89d112362f9770a4551149d4e738f | /Wall_Destruction/Havok/Source/Common/Base/Container/String/hkString.inl | 0c58c098d10b4b54e945f74e4483b8a0dc2f5dd6 | []
| 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 | 8,061 | inl | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-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.
*
*/
void HK_CALL hkString::memCpy4( void* dst, const void* src, int numWords)
{
const hkUint32* src32 = reinterpret_cast<const hkUint32*>(src);
hkUint32* dst32 = reinterpret_cast< hkUint32*>(dst);
{
for (int i = 0; i < numWords; i++)
{
*(dst32++) = *(src32++);
}
}
}
void HK_CALL hkString::memCpy16( void* dst, const void* src, int numQuads)
{
#if defined (HK_PLATFORM_PS3_PPU) || defined (HK_PLATFORM_PS3_SPU)
const vector signed int* srcQuad = reinterpret_cast<const vector signed int*>(src);
vector signed int* dstQuad = reinterpret_cast<vector signed int*>(dst);
{
for (int i = numQuads-1; i>=0; i--)
{
*(dstQuad++) = *(srcQuad++);
}
}
#else
HK_ASSERT2( 0xf021d445, (hkUlong(dst) & 0xf) == 0, "Unaligned address" );
HK_ASSERT2( 0xf021d446, (hkUlong(src) & 0xf) == 0, "Unaligned address" );
const hkUint32* src32 = reinterpret_cast<const hkUint32*>(src);
hkUint32* dst32 = reinterpret_cast< hkUint32*>(dst);
{
for (int i = 0; i < numQuads; i++)
{
dst32[0] = src32[0];
dst32[1] = src32[1];
dst32[2] = src32[2];
dst32[3] = src32[3];
dst32+= 4;
src32+= 4;
}
}
#endif
}
void HK_CALL hkString::memCpy16NonEmpty( void* dst, const void* src, int numQuads)
{
#if defined (HK_PLATFORM_PS3_PPU) || defined (HK_PLATFORM_PS3_SPU)
const vector signed int* srcQuad = reinterpret_cast<const vector signed int*>(src);
vector signed int* dstQuad = reinterpret_cast<vector signed int*>(dst);
{
do
{
*(dstQuad++) = *(srcQuad++);
}
while ( --numQuads > 0 );
}
#else
HK_ASSERT2( 0xf022d444, numQuads > 0, "Size 0 not allowed" );
HK_ASSERT2( 0xf022d445, (hkUlong(dst) & 0xf) == 0, "Unaligned address" );
HK_ASSERT2( 0xf022d446, (hkUlong(src) & 0xf) == 0, "Unaligned address" );
const hkUint32* src32 = reinterpret_cast<const hkUint32*>(src);
hkUint32* dst32 = reinterpret_cast< hkUint32*>(dst);
{
do
{
dst32[0] = src32[0];
dst32[1] = src32[1];
dst32[2] = src32[2];
dst32[3] = src32[3];
dst32+= 4;
src32+= 4;
}
while ( --numQuads > 0 );
}
#endif
}
template<int size>
void hkString::memCpy16(void* dst, const void* src)
{
HK_ASSERT( 0xf0dedf34, ((size & 0xf) == 0) && (size <= 128) && (size > 0));
#if defined(HK_PLATFORM_PS3_SPU) || defined(HK_PLATFORM_PS3_PPU)
const vector signed int* srcQuad = reinterpret_cast<const vector signed int*>(src);
vector signed int* dstQuad = reinterpret_cast<vector signed int*>(dst);
vector signed int a,b,c,d;
if ( size > 0) a = srcQuad[0];
if ( size > 16) b = srcQuad[1];
if ( size > 32) c = srcQuad[2];
if ( size > 48) d = srcQuad[3];
if ( size > 0) dstQuad[0] = a;
if ( size > 64) a = srcQuad[4];
if ( size > 16) dstQuad[1] = b;
if ( size > 80) b = srcQuad[5];
if ( size > 32) dstQuad[2] = c;
if ( size > 96) c = srcQuad[6];
if ( size > 48) dstQuad[3] = d;
if ( size > 112) d = srcQuad[7];
if ( size > 64) dstQuad[4] = a;
if ( size > 80) dstQuad[5] = b;
if ( size > 96) dstQuad[6] = c;
if ( size > 112) dstQuad[7] = d;
#else
hkString::memCpy16NonEmpty(dst, src, size/16);
#endif
}
void hkString::memCpy256(void* dst, const void* src)
{
#if defined(HK_PLATFORM_PS3_SPU) || defined(HK_PLATFORM_PS3_PPU)
const vector signed int* HK_RESTRICT srcQuad = (const vector signed int*)src;
vector signed int* HK_RESTRICT dstQuad = (vector signed int*) dst;
vector signed int a = srcQuad[0];
vector signed int b = srcQuad[1];
vector signed int c = srcQuad[2];
vector signed int d = srcQuad[3];
dstQuad[0] = a; a = srcQuad[4];
dstQuad[1] = b; b = srcQuad[5];
dstQuad[2] = c; c = srcQuad[6];
dstQuad[3] = d; d = srcQuad[7];
dstQuad[4] = a; a = srcQuad[8];
dstQuad[5] = b; b = srcQuad[9];
dstQuad[6] = c; c = srcQuad[10];
dstQuad[7] = d; d = srcQuad[11];
dstQuad[8] = a; a = srcQuad[12];
dstQuad[9] = b; b = srcQuad[13];
dstQuad[10] = c; c = srcQuad[14];
dstQuad[11] = d; d = srcQuad[15];
dstQuad[12] = a;
dstQuad[13] = b;
dstQuad[14] = c;
dstQuad[15] = d;
#else
hkString::memCpy16NonEmpty(dst, src, 16);
#endif
}
void hkString::memSet4(void* dst, const int value, int numWords)
{
hkUint32* dst32 = reinterpret_cast< hkUint32*>(dst);
for (int i = numWords-1; i>=0; i--)
{
*dst32 = value;
dst32++;
}
}
void HK_CALL hkString::memClear16(void* dst, int numQuads)
{
#if defined (HK_PLATFORM_PS3_PPU) || defined (HK_PLATFORM_PS3_SPU)
vector signed int zero = (vector signed int){0,0,0,0};
vector signed int* dest = (vector signed int*)dst;
for (int i = numQuads-1; i>=0; i--)
{
*(dest++) = zero;
}
#else
HK_ASSERT2( 0xf021d445, (hkUlong(dst) & 0xf) == 0, "Unaligned address" );
hkUint32* dst32 = reinterpret_cast< hkUint32*>(dst);
{
for (int i = 0; i < numQuads; i++)
{
dst32[0] = 0;
dst32[1] = 0;
dst32[2] = 0;
dst32[3] = 0;
dst32+= 4;
}
}
#endif
}
// For size up to 512 bytes, on PLAYSTATION(R)3, this will compile down to a sequence of store instructions
// For larger copies or other platforms, it reverts to the looped version.
template<int size>
void hkString::memSet16(void* dst, const void* src)
{
HK_ASSERT( 0xf0dedf34, ((size & 0xf) == 0) && (size > 0) );
#if defined(HK_PLATFORM_SPU) || defined(HK_PLATFORM_PS3_PPU)
if (size < 32 * 16)
{
const hkQuadReal srcQuad = *reinterpret_cast<const hkQuadReal*>(src);
hkQuadReal* dstQuad = reinterpret_cast<hkQuadReal*>(dst);
#define HK_SET_ELEM( X ) { if ( size > 16 * (X) ) dstQuad[X] = srcQuad; }
#define HK_SET_ELEM4( X ) { HK_SET_ELEM((X)+0); HK_SET_ELEM((X)+1); HK_SET_ELEM((X)+2); HK_SET_ELEM((X)+3);}
HK_SET_ELEM4(0);
HK_SET_ELEM4(4);
HK_SET_ELEM4(8);
HK_SET_ELEM4(12);
HK_SET_ELEM4(16);
HK_SET_ELEM4(20);
HK_SET_ELEM4(24);
HK_SET_ELEM4(28);
#undef HK_SET_ELEM4
#undef HK_SET_ELEM
}
else
#endif
{
hkString::memSet16(dst, src, size/16);
}
}
void HK_CALL hkString::memSet16(void* dst, const void* value, int numQuads)
{
#if defined (HK_PLATFORM_PS3_PPU) || defined (HK_PLATFORM_PS3_SPU)
const vector signed int* valueQuad = reinterpret_cast<const vector signed int*>(value);
vector signed int* dstQuad = reinterpret_cast<vector signed int*>(dst);
{
for (int i = numQuads-1; i>=0; i--)
{
*(dstQuad++) = *(valueQuad);
}
}
#else
HK_ASSERT2( 0xf021d445, (hkUlong(dst) & 0xf) == 0, "Unaligned address" );
HK_ASSERT2( 0xf021d446, (hkUlong(value) & 0xf) == 0, "Unaligned address" );
const hkUint32* value32 = reinterpret_cast<const hkUint32*>(value);
hkUint32* dst32 = reinterpret_cast< hkUint32*>(dst);
{
for (int i = 0; i < numQuads; i++)
{
dst32[0] = value32[0];
dst32[1] = value32[1];
dst32[2] = value32[2];
dst32[3] = value32[3];
dst32+= 4;
}
}
#endif
}
/*
* 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.
*
*/
| [
"[email protected]"
]
| [
[
[
1,
261
]
]
]
|
33727a83b0a1ccc2afa70f52f7125c774dcd6860 | 880e5a47c23523c8e5ba1602144ea1c48c8c8f9a | /enginesrc/operating_system/systemwindow.cpp | d3382fc42b304df9e934468bdcc8139ff9bbb810 | []
| no_license | kfazi/Engine | 050cb76826d5bb55595ecdce39df8ffb2d5547f8 | 0cedfb3e1a9a80fd49679142be33e17186322290 | refs/heads/master | 2020-05-20T10:02:29.050190 | 2010-02-11T17:45:42 | 2010-02-11T17:45:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,092 | cpp | #include "systemwindow.hpp"
namespace engine
{
CSystemWindow::CSystemWindow(int iX, int iY, unsigned int iWidth, unsigned int iHeight, const CString &cCaption, bool bCaptionBar, bool bCloseButton, bool bMaximalizeButton, bool bMinimalizeButton)
{
}
CSystemWindow::~CSystemWindow()
{
}
bool CSystemWindow::OnClose()
{
if (m_pOnCloseFunctor)
return m_pOnCloseFunctor();
return true;
}
bool CSystemWindow::OnMinimalize()
{
if (m_pOnMinimalizeFunctor)
m_bMinimalized = m_pOnMinimalizeFunctor();
else
m_bMinimalized = true;
return m_bMinimalized;
}
bool CSystemWindow::OnRestore()
{
if (m_pOnRestoreFunctor)
m_bMinimalized = !m_pOnRestoreFunctor();
else
m_bMinimalized = false;
return !m_bMinimalized;
}
void CSystemWindow::Show()
{
m_bVisible = true;
}
void CSystemWindow::Hide()
{
m_bVisible = false;
}
void CSystemWindow::SetVisible(bool bVisible)
{
if (bVisible)
Show();
else
Hide();
}
bool CSystemWindow::GetVisible() const
{
return m_bVisible;
}
bool CSystemWindow::IsMinimalized() const
{
return m_bMinimalized;
}
}
/* EOF */
| [
"[email protected]"
]
| [
[
[
1,
69
]
]
]
|
eb37d41c1f5126e00499412d8b0af7856cb88141 | 6d94a4365af81730ef597dfb22e5c35e51400ade | /Code/Libs/Hash/UnitTests/HashData_unittest.cpp | ad4439a08ffa7bde19eccdd17e03844f801a1244 | []
| no_license | shaun-leach/game-riff | be57a59659d0fcb413dd75f51dae1bda8a9cdc98 | 8f649d06ce763bc828817a417d01f44402c93f7e | refs/heads/master | 2016-09-08T00:30:27.025751 | 2011-07-16T05:31:31 | 2011-07-16T05:31:31 | 32,223,990 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,853 | cpp | /*
GameRiff - Framework for creating various video game services
Hash function unit tests
Copyright (C) 2011, Shaun Leach.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <gtest/gtest.h>
#include "Pch.h"
#define DATA_A ("a")
#define LEN_A (strlen(DATA_A))
#define DATA_B ("b")
#define LEN_B (strlen(DATA_B))
#define DATA_FILE1 ("art/planets/textures/gasGiant1.dds")
#define LEN_FILE1 (strlen(DATA_FILE1))
#define DATA_FILE2 ("art/planets/textures/gasGiant2.dds")
#define LEN_FILE2 (strlen(DATA_FILE2))
#define DATA_1 ("abcd")
#define LEN_1 (strlen(DATA_1))
#define DATA_2 ("abcde")
#define LEN_2 (strlen(DATA_2))
TEST(HashDataTest, TestUniqueness64) {
EXPECT_EQ(HashData64(DATA_A, LEN_A), HashData64(DATA_A, LEN_A));
EXPECT_EQ(HashData64(DATA_FILE1, LEN_FILE1), HashData64(DATA_FILE1, LEN_FILE1));
EXPECT_NE(HashData64(DATA_A, LEN_A), HashData64(DATA_B, LEN_B));
EXPECT_NE(HashData64(DATA_1, LEN_1), HashData64(DATA_2, LEN_2));
EXPECT_NE(HashData64(DATA_FILE1, LEN_FILE1), HashData64(DATA_FILE2, LEN_FILE2));
}
TEST(HashDataTest, TestUniqueness32) {
EXPECT_EQ(HashData32(DATA_A, LEN_A), HashData32(DATA_A, LEN_A));
EXPECT_EQ(HashData32(DATA_FILE1, LEN_FILE1), HashData32(DATA_FILE1, LEN_FILE1));
EXPECT_NE(HashData32(DATA_A, LEN_A), HashData32(DATA_B, LEN_B));
EXPECT_NE(HashData32(DATA_1, LEN_1), HashData32(DATA_2, LEN_2));
EXPECT_NE(HashData32(DATA_FILE1, LEN_FILE1), HashData32(DATA_FILE2, LEN_FILE2));
}
| [
"[email protected]@91311ff6-4d11-5f1f-8822-9f0e3032c885"
]
| [
[
[
1,
66
]
]
]
|
a973ded9040ed405fe43bbe7227c7fd919f6784c | 14a00dfaf0619eb57f1f04bb784edd3126e10658 | /lab6/LoopSubdivisionMesh.h | 7ddf1005730ffb695c27f93ada6b6873371a4ddc | []
| no_license | SHINOTECH/modanimation | 89f842262b1f552f1044d4aafb3d5a2ce4b587bd | 43d0fde55cf75df9d9a28a7681eddeb77460f97c | refs/heads/master | 2021-01-21T09:34:18.032922 | 2010-04-07T12:23:13 | 2010-04-07T12:23:13 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,787 | h | /*************************************************************************************************
*
* Modeling and animation (TNM079) 2007
* Code base for lab assignments. Copyright:
* Gunnar Johansson ([email protected])
* Ken Museth ([email protected])
* Michael Bang Nielsen ([email protected])
* Ola Nilsson ([email protected])
* Andreas Söderström ([email protected])
*
*************************************************************************************************/
#ifndef _LOOP_SUBDIVISION_MESH_
#define _LOOP_SUBDIVISION_MESH_
#include "HalfEdgeMesh.h"
/*! \brief Subdivision mesh that implements the Loop scheme
*/
class LoopSubdivisionMesh : public HalfEdgeMesh
{
public :
LoopSubdivisionMesh(const HalfEdgeMesh & m, unsigned int s) : HalfEdgeMesh(m), mNumSubDivs(s) { }
LoopSubdivisionMesh() : mNumSubDivs(0) { }
virtual ~LoopSubdivisionMesh() { }
//! Subdivides the mesh uniformly one step
virtual bool subdivide();
//! Loops over the edges incident to the vertex and collects all pairs' verts
//! Almost identical to findNeighbourTris
bool findNeighbourVerts(const unsigned int vertexIndex, std::vector<unsigned int>& foundVerts) const;
//! Return weights for interior verts
float beta(unsigned int valence);
//! Uses the HalfEdge::draw
virtual void draw() { HalfEdgeMesh::draw(); }
protected :
//! The number of accumulated subdivisions
unsigned int mNumSubDivs;
//! Computes a new vertex, replacing a vertex in the old mesh
virtual Vector3<float> computeVertex(unsigned int edgeIndex);
//! Computes a new vertex, placed along an edge in the old mesh
virtual Vector3<float> computeEdgeVertex(unsigned int edgeIndex);
};
#endif
| [
"onnepoika@da195381-492e-0410-b4d9-ef7979db4686",
"jpjorge@da195381-492e-0410-b4d9-ef7979db4686"
]
| [
[
[
1,
45
],
[
47,
48
],
[
50,
52
]
],
[
[
46,
46
],
[
49,
49
]
]
]
|
63280f448c50cc3f62644a301228c05e0cfa2153 | 5d3c1be292f6153480f3a372befea4172c683180 | /trunk/Event Heap/c++/Mac OS X/include/idk_io_IOException.h | f9a178d7fd36db3af1752f09a86a709f5760eb24 | [
"Artistic-2.0"
]
| permissive | BackupTheBerlios/istuff-svn | 5f47aa73dd74ecf5c55f83765a5c50daa28fa508 | d0bb9963b899259695553ccd2b01b35be5fb83db | refs/heads/master | 2016-09-06T04:54:24.129060 | 2008-05-02T22:33:26 | 2008-05-02T22:33:26 | 40,820,013 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 683 | h | /* Copyright (c) 2003 The Board of Trustees of The Leland Stanford Junior
* University. All Rights Reserved.
*
* See the file LICENSE.txt for information on redistributing this software.
*/
/* $Id: idk_io_IOException.h,v 1.3 2003/06/02 08:03:40 tomoto Exp $ */
#ifndef _IDK_IO_IOEXCEPTION_H_
#define _IDK_IO_IOEXCEPTION_H_
#include <idk_ut_Types.h>
#include <idk_ut_Exception.h>
/** @file
Definition of idk_io_IOException class.
*/
/**
This is the base class of errors which occurs during I/O operations.
*/
class IDK_DECL idk_io_IOException : public idk_ut_Exception {
IDK_UT_EXCEPTION_DECL(idk_io_IOException, idk_ut_Exception);
};
#endif
| [
"ballagas@2a53cb5c-8ff1-0310-8b75-b3ec22923d26"
]
| [
[
[
1,
26
]
]
]
|
8a000d78f3d7145e959d5bac1ae4bbb2e9f58d6e | 10bac563fc7e174d8f7c79c8777e4eb8460bc49e | /matlab/ipcBee/matlab_bee_inc.h | b6c8ca8ba694d3b23346487b8502add33d30b59d | []
| no_license | chenbk85/alcordev | 41154355a837ebd15db02ecaeaca6726e722892a | bdb9d0928c80315d24299000ca6d8c492808f1d5 | refs/heads/master | 2021-01-10T13:36:29.338077 | 2008-10-22T15:57:50 | 2008-10-22T15:57:50 | 44,953,286 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 668 | h | #ifndef matlab_bee_inc_H_INCLUDED
#define matlab_bee_inc_H_INCLUDED
//--------------------------------------------------------------------++
#include "mex.h"
#include "alcor.extern/matlab/ObjectHandle.h"
#include "alcor/sense/bumblebee_ipc_recv_t.h"
#include "alcor/core/core.h"
#include <iostream>
#include <cstdio>
//--------------------------------------------------------------------++
#pragma comment (lib,"bumblebee_ipc_recv_t.lib")
//--------------------------------------------------------------------++
using std::cout;
using std::endl;
//--------------------------------------------------------------------++
#endif //matlab_cam_inc_H_INCLUDED | [
"andrea.carbone@1c7d64d3-9b28-0410-bae3-039769c3cb81"
]
| [
[
[
1,
16
]
]
]
|
aa652447bfada261a23d51eb7bfa9a52107f6014 | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/exporter/3dsplugin/inc/n3dsexporters/n3dscustomattributes.h | 82cf0ecb6bf298c5c52a9d9b090b26e91735cd55 | []
| no_license | ugozapad/TheZombieEngine | 832492930df28c28cd349673f79f3609b1fe7190 | 8e8c3e6225c2ed93e07287356def9fbdeacf3d6a | refs/heads/master | 2020-04-30T11:35:36.258363 | 2011-02-24T14:18:43 | 2011-02-24T14:18:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 992 | h | /**
@file n3dscustomattributes.h
@author Luis Jose Cabellos Gomez
(C) 2005 Conjurer Services, S.A.
*/
#ifndef N3DSCUSTOMATTRIBUTES_H
#define N3DSCUSTOMATTRIBUTES_H
#include "util/narray.h"
class nString;
class n3dsCustomAttributes
{
public:
/// get the string in the node attributes
static bool GetParamString( INode * const node, const nString &attribute, const nString ¶m, TSTR & value );
/// get the integer in the node attributes
static bool GetParamInt( INode * const node, const nString &attribute, const nString ¶m, int & value );
/// get the array of nodes in the node attributes
static bool GetParamNodes( INode * const node, const nString & attribute, const nString & param, nArray<INode*> & value );
};
#endif//N3DSCUSTOMATTRIBUTES_H
//------------------------------------------------------------------------------
// EOF
//------------------------------------------------------------------------------
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
]
| [
[
[
1,
27
]
]
]
|
36e7c1d6806c65c8cb899a4d186a0ce965317e00 | c3a0cf3d0c023cbdb9a1ab8295aa1231543d83e7 | /sln/src/FbgRenderer.h | 7348330c56853c644af741346de5d4170dc9eb17 | []
| no_license | yakergong/seedcup2008 | 2596cdb5fe404ef8628366cdd2f8003141625264 | e57b92cf576900ba6cb5e0c0f6661bba3e7f75d7 | refs/heads/master | 2016-09-05T11:06:12.717346 | 2008-12-19T13:04:28 | 2008-12-19T13:04:28 | 32,268,668 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,840 | h | #ifndef FBG_RENDERER_H
#define FBG_RENDERER_H
#include <string>
#include "glTGAImage.h"
#include "fbgblock.h"
class FbgGame;
class FbgRenderer
{
public:
static FbgRenderer& Instance();
bool init(bool fs = false, int width = 640, int height = 480, int bpp = 24);
void exit();
void draw();
private:
FbgRenderer();
static FbgRenderer instance_;
// 增加图片
GLTgaImage msb_;
// Textures
GLTgaImage *bg_;
GLTgaImage *ml_;
GLTgaImage *mb_;
GLTgaImage *mt_;
GLTgaImage *nb_;
GLTgaImage *gameover_;
GLTgaImage nr_;
GLTgaImage *blocks_;
GLTgaImage *digits_;
// Display Lists
GLuint cube_;
GLuint cubeWithoutBack_;
GLuint digitsBase_;
GLfloat lineZSpeeds_[4][10];
void loadTextures();
void killTextures();
void buildLists(); // Build OpenGL display lists
void killLists(); // Destroy OpenGL display lists
// 绘制背景,由draw调用
void drawBkgnd(FbgGame *game);
void drawGameID(FbgGame *game);
void drawMulGameInfo(FbgGame *game);
void drawCurBlockFrame(FbgGame *game);
void drawNextBlockFrame(FbgGame *game);
void drawGameInfo(FbgGame *game);
void drawGameplay(FbgGame *game); // Normal rendering during game play
void drawBlock(FbgGame *game, FbgBlock * theBlock);
void drawCurBlock( FbgGame * game );
void drawNextBlock( FbgGame * game );
void drawLineGain(FbgGame *game); // 绘制一行逐渐被消去的过程
void drawGameOver(FbgGame *game); // When the game ends
void drawGameMatrix(FbgGame *game); // Code-saving function for drawing the game matrix
void drawDigits(const std::string & str);
};
#endif | [
"yakergong@c3067968-ca50-11dd-8ca8-e3ff79f713b6"
]
| [
[
[
1,
66
]
]
]
|
62bbec5686cce561f9d89be37255d424252a42b2 | 8d3bc2c1c82dee5806c4503dd0fd32908c78a3a9 | /tools/xsi/src/xsi_nel_export/xsi_nel_kd_tree.cpp | 1b6d739e10fea2f225c3c79357e9562b50ca2a17 | []
| no_license | ryzom/werewolf2 | 2645d169381294788bab9a152c4071061063a152 | a868205216973cf4d1c7d2a96f65f88360177b69 | refs/heads/master | 2020-03-22T20:08:32.123283 | 2010-03-05T21:43:32 | 2010-03-05T21:43:32 | 140,575,749 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,343 | cpp | /* Copyright, 2003 Neverborn Entertainment.
* This file is part of our XSI Plugins.
* The XSI Plugins are free software, you can redistribute them and/or modify
* them 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.
* XSI Plugins are distributed WITHOUT ANY WARRANTY or implied warranty of
* MERCHANTABILITY. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with the XSI Plugins; see the file COPYING. If not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
//
// Includes
//
#include "std_pch.h"
#include "xsi_nel_mesh_lib.h"
#include "xsi_nel_export.h"
#include "xsi_nel_material.h"
#include "xsi_nel_kd_tree.h"
//
// Namespaces
//
using namespace XSI;
using namespace NLMISC;
using namespace NL3D;
//
// Functions
//
CStatus CKDTree::subdivide( uint32 node_index, const _STL::vector<SVertex> &vertices )
{
uint32 node_depth;
CVector center_point = CVector( 0.0f, 0.0f, 0.0f );
CVector distance_from_center = CVector( 0.0f, 0.0f, 0.0f );
static CVector planes_normal[ 3 ] = { CVector( 1.0f, 0.0f, 0.0f ), CVector( 0.0f, 1.0f, 0.0f ), CVector( 0.0f, 0.0f, 1.0f ) };
_STL::vector< SVertex > front_vertices, back_vertices;
// Sub Division
if( vertices.size() == 1 )
{
nodes[ node_index ].is_leaf = true;
nodes[ node_index ].vertex = vertices[ 0 ];
}
else
{
nodes[ node_index ].is_leaf = false;
// Calculate Center Point
for( uint32 i = 0; i < vertices.size(); i++ )
{
center_point += vertices[ i ].position;
}
center_point /= float( vertices.size() );
// Compute Distance From Center For Each Axis
for( uint32 i = 0; i < vertices.size(); i++ )
{
distance_from_center.x += fabsf( vertices[ i ].position.x - center_point.x );
distance_from_center.y += fabsf( vertices[ i ].position.y - center_point.y );
distance_from_center.z += fabsf( vertices[ i ].position.z - center_point.z );
}
node_depth = 0;
// We Choose Node Depth That Has Largest Distance
if( distance_from_center.x > distance_from_center.y )
{
if( distance_from_center.x > distance_from_center.z )
{
node_depth = 0;
}
else
{
node_depth = 2;
}
}
else if( distance_from_center.y > distance_from_center.x )
{
if( distance_from_center.y > distance_from_center.z )
{
node_depth = 1;
}
else
{
node_depth = 2;
}
}
if( distance_from_center.x == 0.0f && node_depth == 0 )
{
if( distance_from_center.y == 0.0f )
{
node_depth = 2;
}
else
{
node_depth = 1;
}
}
if( distance_from_center.y == 0.0f && node_depth == 1 )
{
if( distance_from_center.x == 0.0f )
{
node_depth = 2;
}
else
{
node_depth = 0;
}
}
if( distance_from_center.z == 0.0f && node_depth == 2 )
{
if( distance_from_center.y == 0.0f )
{
node_depth = 0;
}
else
{
node_depth = 1;
}
}
// Duplicate Vertexes
if( distance_from_center.x == 0.0f && distance_from_center.y == 0.0f && distance_from_center.z == 0.0f )
{
return CStatus::Fail;
}
// Setup Splitter Plane
nodes[ node_index ].splitter_plane.make( planes_normal[ node_depth % 3 ], center_point );
// Setup Front & Back Vertices
for( uint32 i = 0; i < vertices.size(); i++ )
{
if( nodes[ node_index ].splitter_plane * vertices[ i ].position > 0.0f )
{
front_vertices.push_back( vertices[ i ] );
}
else
{
back_vertices.push_back( vertices[ i ] );
}
}
// Create Front & Back Node Next Sub Division Populates
uint32 current_node_index = nodes.size();
SKDTreeNode node;
nodes.push_back(node);
nodes.push_back(node);
// Setup Child Nodes
nodes[ node_index ].front_node = current_node_index;
nodes[ node_index ].back_node = current_node_index + 1;
if ( subdivide( current_node_index, front_vertices ) != CStatus::OK )
{
return CStatus::Fail;
};
if ( subdivide( current_node_index + 1, back_vertices ) != CStatus::OK )
{
return CStatus::Fail;
};
}
return CStatus::OK;
}
CStatus CKDTree::build( const _STL::vector<SVertex> &vertices )
{
// Remove Any Previous Tree
nodes.clear();
// Create A Root
SKDTreeNode root_node;
nodes.push_back( root_node );
// Create Branches And Leaves
return subdivide( 0, vertices );
}
bool CKDTree::checkIfVertexExists( const CVector &vertice )
{
// Scan Tree
return checkIfVertexExists( 0, vertice );
}
bool CKDTree::checkIfVertexExists( uint32 node_index, const CVector &vertice )
{
if( nodes[ node_index ].is_leaf )
{
if( nodes[ node_index ].vertex.position == vertice )
{
return true;
}
}
else
{
if( nodes[ node_index ].splitter_plane * vertice > 0.0f )
{
// Check Front Nodes
return checkIfVertexExists( nodes[ node_index ].front_node, vertice );
}
else
{
// Check Back Nodes
return checkIfVertexExists( nodes[ node_index ].back_node, vertice );
}
}
return false;
}
| [
"[email protected]"
]
| [
[
[
1,
235
]
]
]
|
941ee54bf24625c7836153ce6d31ecd58ef330cc | fd792229322e4042f6e88a01144665cebdb1c339 | /src/collisionPackets.h | 183e4aee312b0cc100f909f2ef4cf84c960f2536 | []
| no_license | weimingtom/mmomm | 228d70d9d68834fa2470d2cd0719b9cd60f8dbcd | cab04fcad551f7f68f99fa0b6bb14cec3b962023 | refs/heads/master | 2021-01-10T02:14:31.896834 | 2010-03-15T16:15:43 | 2010-03-15T16:15:43 | 44,764,408 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,123 | h | #ifndef COLLISION_PACKETS_H_
#define COLLISION_PACKETS_H_
// Packets linked with actors and collision.
#include <string>
#include <iostream>
#include <boost/static_assert.hpp>
#include "collision.h"
#include "networkPacket.h"
#include "packetTypes.h"
#include "serial.h"
#include "vector2D.h"
// Gives information about the initial state of an object.
struct CreationUpdate {
ActorID id;
Rect offsetRect;
Vector2D velocity;
uint8_t sprite;
bool isClientPlayer;
std::string name;
};
// Informs the player that an entity is no longer relevant
struct DestructionUpdate {
ActorID id;
};
// Informs the player of an entity's new position and velocity
struct MovementUpdate {
ActorID id;
Vector2D displacement;
Vector2D velocity;
};
inline void serial(BitStream& bs, bool write, CreationUpdate& data)
{
serialFull(bs, write, data.id);
serialDisplacement(bs, write, data.offsetRect);
serialVelocity(bs, write, data.velocity);
serial(bs, write, data.sprite);
serial(bs, write, data.isClientPlayer);
serial(bs, write, data.name);
}
inline void serial(BitStream& bs, bool write, DestructionUpdate& data)
{
serialFull(bs, write, data.id);
}
inline void serial(BitStream& bs, bool write, MovementUpdate& data)
{
serialFull(bs, write, data.id);
serialDisplacement(bs, write, data.displacement);
serialVelocity(bs, write, data.velocity);
}
// Occurs to inform about new entities and destroyed entities.
class CreationPacket: public NetworkPacket {
public:
CreationPacket() { }
// Initialize from a series of movementUpdates
template<typename CreationIterator, typename DestructionIterator>
CreationPacket(const Vector2D& referencePoint,
CreationIterator createBegin, CreationIterator createEnd,
DestructionIterator destructBegin, DestructionIterator destructEnd)
: _referencePoint(referencePoint)
, _creation(createBegin, createEnd)
, _destruction(destructBegin, destructEnd) { }
NetworkParams params() const
{
return NetworkParams(ID_COLLISION_CREATE, HIGH_PRIORITY,
RELIABLE, ORDER_DEFAULT, true);
}
// Respond to object creation on client.
void respondClient() const;
// Invalid on server.
// Serialization function.
void serialize(BitStream& bs, bool write)
{
serialPosition(bs, write, _referencePoint);
serial(bs, write, _creation);
serial(bs, write, _destruction);
}
const Vector2D& referencePoint() const { return _referencePoint; }
typedef std::vector<CreationUpdate> CreationList;
const CreationList& creation() const { return _creation; }
typedef std::vector<DestructionUpdate> DestructionList;
const DestructionList& destruction() const { return _destruction; }
private:
Vector2D _referencePoint;
CreationList _creation;
DestructionList _destruction;
};
// Occurs to inform about entities moving around.
// May be processed before a CreationUpdate or after a DestructionUpdate
class MovementPacket: public NetworkPacket {
public:
MovementPacket() { }
// Initialize from a series of movementUpdates
template<typename MovementIterator>
MovementPacket(const Vector2D& referencePoint,
MovementIterator moveBegin, MovementIterator moveEnd)
: _referencePoint(referencePoint)
, _movement(moveBegin, moveEnd) { }
NetworkParams params() const
{
// Could be just UNRELIABLE, though packet inversion would look odd
return NetworkParams(ID_COLLISION_UPDATE, HIGH_PRIORITY,
UNRELIABLE, SEQUENCE_DEFAULT, true);
}
// Respond to actor movement on client.
void respondClient() const;
// Respond to player movement on server.
void respondServer() const;
// Serialization function.
void serialize(BitStream& bs, bool write)
{
serialPosition(bs, write, _referencePoint);
serial(bs, write, _movement);
}
const Vector2D& referencePoint() const { return _referencePoint; }
typedef std::vector<MovementUpdate> MovementList;
const MovementList& movement() const { return _movement; }
private:
Vector2D _referencePoint;
MovementList _movement;
};
#endif
| [
"[email protected]",
"grandfunkdynasty@191a6260-07ae-11df-8636-19de83dc8dca",
"kingoipo@191a6260-07ae-11df-8636-19de83dc8dca"
]
| [
[
[
1,
5
],
[
8,
20
],
[
23,
41
],
[
45,
61
],
[
63,
71
],
[
73,
77
],
[
79,
80
],
[
82,
82
],
[
84,
85
],
[
87,
92
],
[
94,
109
],
[
111,
117
],
[
119,
124
],
[
126,
127
],
[
129,
130
],
[
132,
137
],
[
139,
150
]
],
[
[
6,
6
],
[
21,
22
],
[
42,
44
],
[
86,
86
]
],
[
[
7,
7
],
[
62,
62
],
[
72,
72
],
[
78,
78
],
[
81,
81
],
[
83,
83
],
[
93,
93
],
[
110,
110
],
[
118,
118
],
[
125,
125
],
[
128,
128
],
[
131,
131
],
[
138,
138
]
]
]
|
2a46b9bf22e8f1c82356efcaa35c5b9842611c44 | b22c254d7670522ec2caa61c998f8741b1da9388 | /common/vector.h | d27ddb36cff98b1fe65e50f6ca07602fbdd9a96c | []
| 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 | WINDOWS-1252 | C++ | false | false | 7,893 | h | /*
------------------------[ Lbanet Source ]-------------------------
Copyright (C) 2009
Author: adaptation from Miguel Gomez's code on gamasutra
Email : [email protected]
-------------------------------[ GNU License ]-------------------------------
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-----------------------------------------------------------------------------
*/
#ifndef __LBA_NET_VECTOR_H__
#define __LBA_NET_VECTOR_H__
#include <math.h>
// A floating point number
//
typedef float SCALAR;
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
//*************************************************************************************************
//* class VECTOR
//*************************************************************************************************
class VECTOR
{
public:
SCALAR x,y,z; //x,y,z coordinates
public:
//! constructor
VECTOR()
: x(0), y(0), z(0)
{}
//! constructor
VECTOR( const SCALAR& a, const SCALAR& b, const SCALAR& c )
: x(a), y(b), z(c)
{}
//index a component
//NOTE: returning a reference allows
//you to assign the indexed element
SCALAR& operator [] ( const long i )
{
return *((&x) + i);
}
const SCALAR& operator [] ( const long i ) const
{
return *((&x) + i);
}
//compare
const bool operator == ( const VECTOR& v ) const
{
return (v.x==x && v.y==y && v.z==z);
}
const bool operator != ( const VECTOR& v ) const
{
return !(v == *this);
}
const bool operator < ( const VECTOR& v ) const
{
if(v.x < x)
return true;
if(v.x == x)
{
if(v.y < y)
return true;
if(v.y == y)
{
if(v.z < z)
return true;
}
}
return false;
}
//negate
const VECTOR operator - () const
{
return VECTOR( -x, -y, -z );
}
//assign
const VECTOR& operator = ( const VECTOR& v )
{
x = v.x;
y = v.y;
z = v.z;
return *this;
}
//increment
const VECTOR& operator += ( const VECTOR& v )
{
x+=v.x;
y+=v.y;
z+=v.z;
return *this;
}
//decrement
const VECTOR& operator -= ( const VECTOR& v )
{
x-=v.x;
y-=v.y;
z-=v.z;
return *this;
}
//self-multiply
const VECTOR& operator *= ( const SCALAR& s )
{
x*=s;
y*=s;
z*=s;
return *this;
}
//self-divide
const VECTOR& operator /= ( const SCALAR& s )
{
const SCALAR r = 1 / s;
x *= r;
y *= r;
z *= r;
return *this;
}
//add
const VECTOR operator + ( const VECTOR& v ) const
{
return VECTOR(x + v.x, y + v.y, z + v.z);
}
//subtract
const VECTOR operator - ( const VECTOR& v ) const
{
return VECTOR(x - v.x, y - v.y, z - v.z);
}
//post-multiply by a scalar
const VECTOR operator * ( const SCALAR& s ) const
{
return VECTOR( x*s, y*s, z*s );
}
//pre-multiply by a scalar
friend inline const VECTOR operator * ( const SCALAR& s, const VECTOR& v )
{
return v * s;
}
//divide
const VECTOR operator / (SCALAR s) const
{
s = 1/s;
return VECTOR( s*x, s*y, s*z );
}
//cross product
const VECTOR cross( const VECTOR& v ) const
{
//Davis, Snider, "Introduction to Vector Analysis", p. 44
return VECTOR( y*v.z - z*v.y, z*v.x - x*v.z, x*v.y - y*v.x );
}
//scalar dot product
const SCALAR dot( const VECTOR& v ) const
{
return x*v.x + y*v.y + z*v.z;
}
//length
const SCALAR length() const
{
return (SCALAR)sqrt( (double)this->dot(*this) );
}
//unit vector
const VECTOR unit() const
{
return (*this) / length();
}
//make this a unit vector
void normalize()
{
(*this) /= length();
}
//equal within an error ‘e’
const bool nearlyEquals( const VECTOR& v, const SCALAR e ) const
{
return (fabs(x-v.x) < e);
}
};
//*************************************************************************************************
//* axis oriented AABB bounding box class
//*************************************************************************************************
class AABB
{
public:
VECTOR P; //position
VECTOR E; //x,y,z extents
public:
//! constructor
AABB()
{}
//! constructor
AABB(const VECTOR& p, const VECTOR& e)
: P(p), E(e)
{}
//returns true if this is overlapping b
const bool overlaps( const AABB& b ) const
{
const VECTOR T = b.P - P;//vector from A to B
return (fabs(T.x) <= (E.x + b.E.x) )
&& (fabs(T.y) <= (E.y + b.E.y))
&& (fabs(T.z) <= (E.z + b.E.z));
}
//min x, y, or z
const SCALAR min(long i) const
{
return (P[i] - E[i]);
}
//max x, y, or z
const SCALAR max(long i) const
{
return (P[i] + E[i]);
}
// bounding box sweep test
const bool AABBSweep( const VECTOR& va, //displacement of A
const AABB& B, //boundingbox of b
const VECTOR& vb, //displacement of B
SCALAR& u0, //normalized time of first collision
SCALAR& u1 //normalized time of second collision
)
{
//the problem is solved in A's frame of reference
VECTOR v = (vb - va);
//relative velocity (in normalized time)
VECTOR u_0(0,0,0);
//first times of overlap along each axis
VECTOR u_1(1,1,1);
//last times of overlap along each axis
//check if they were overlapping
// on the previous frame
if( overlaps(B) )
{
u0 = u1 = 0;
return true;
}
//find the possible first and last times
//of overlap along each axis
for( long i=0 ; i<3 ; i++ )
{
if( max(i)<B.min(i) && v[i]<0 )
{
u_0[i] = (max(i) - B.min(i)) / v[i];
}
else if( B.max(i)<min(i) && v[i]>0 )
{
u_0[i] = (min(i) - B.max(i)) / v[i];
}
if( B.max(i)>min(i) && v[i]<0 )
{
u_1[i] = (min(i) - B.max(i)) / v[i];
}
else if( max(i)>B.min(i) && v[i]>0 )
{
u_1[i] = (max(i) - B.min(i)) / v[i];
}
}
//possible first time of overlap
u0 = MAX( u_0.x, MAX(u_0.y, u_0.z) );
//possible last time of overlap
u1 = MIN( u_1.x, MIN(u_1.y, u_1.z) );
//they could have only collided if
//the first time of overlap occurred
//before the last time of overlap
return (u0 <= u1);
}
};
//*************************************************************************************************
//* 2D square class
//*************************************************************************************************
class Square2D
{
public:
//! constructor
Square2D()
: _minX(0), _minZ(0), _maxX(0), _maxZ(0)
{}
//! constructor
Square2D(float minX, float minZ, float maxX, float maxZ)
: _minX(minX), _minZ(minZ), _maxX(maxX), _maxZ(maxZ)
{}
//! overlap
bool Overlap(const Square2D & B) const
{
if( (_minX >= B._maxX) || (_maxX <= B._minX) )
return false;
if( (_minZ >= B._maxZ) || (_maxZ <= B._minZ) )
return false;
return true;
}
//! overlap
bool Overlap(float ptX, float ptZ) const
{
if( (ptX > _minX) && (ptX < _maxX) )
if( (ptZ > _minZ) && (ptZ < _maxZ) )
return true;
return false;
}
float _minX;
float _minZ;
float _maxX;
float _maxZ;
};
#endif | [
"vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13"
]
| [
[
[
1,
396
]
]
]
|
bf657dbe410062197d3e8bc6c5d795164963a3ea | d1ce8db98d580f0f17f868ed408edf6d92f9208f | /QT/OgreQt/MainWindow.cpp | 88e0782ebdcd3267d1dd7c04a1db9a3c3baefe2e | []
| no_license | babochingu/andrew-phd | eed82e7bbd3e2b5b5403c1493e3d36b112b1b007 | ba94c3961d9dfef041c974e7ed2d9da4eb7d4dd3 | refs/heads/master | 2016-09-06T07:18:39.627522 | 2010-10-04T23:54:06 | 2010-10-04T23:54:06 | 33,762,959 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,858 | cpp | #include "ExampleApplication.h"
class TutorialApplication : public ExampleApplication
{
protected:
public:
TutorialApplication()
{
}
~TutorialApplication()
{
}
protected:
MeshPtr mGrassMesh;
void createGrassMesh()
{
}
void createScene(void)
{
createGrassMesh();
mSceneMgr->setAmbientLight(ColourValue(1, 1, 1));
mCamera->setPosition(150, 50, 150);
mCamera->lookAt(0, 0, 0);
Entity *robot = mSceneMgr->createEntity("robot", "robot.mesh");
mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(robot);
Plane plane;
plane.normal = Vector3::UNIT_Y;
plane.d = 0;
MeshManager::getSingleton().createPlane("floor",
ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, plane,
450,450,10,10,true,1,50,50,Vector3::UNIT_Z);
Entity* pPlaneEnt = mSceneMgr->createEntity("plane", "floor");
pPlaneEnt->setMaterialName("Examples/GrassFloor");
pPlaneEnt->setCastShadows(false);
mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt);
}
};
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
INT WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT)
#else
int main(int argc, char **argv)
#endif
{
// Create application object
TutorialApplication app;
try {
app.go();
} catch(Exception& e) {
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
MessageBoxA(NULL, e.getFullDescription().c_str(), "An exception has occurred!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
#else
fprintf(stderr, "An exception has occurred: %s\n",
e.getFullDescription().c_str());
#endif
}
return 0;
}
| [
"evertech.andrew@2dccfce6-0550-11df-956f-01f849d29158"
]
| [
[
[
1,
69
]
]
]
|
dff34bdadbd1d535c434296d99e030627b0be7f0 | 655ecd56b40ee9f5b4721ee1a7ff64c4b64639a3 | /src/LetterParticle.h | a1a4cdc46f448edd861e31147876c26bedfb5d08 | []
| no_license | fx-lange/ofxSptaUtils | 9a4fdb1445bc17e8592202a96bc5869a868b57d3 | 5c5b28aeed72e96016e6c138dfb73a97980f345d | refs/heads/master | 2020-05-20T00:35:00.488065 | 2011-11-23T15:52:21 | 2011-11-23T15:52:21 | 2,289,582 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,129 | h | #pragma once
#include "Particle.h"
class letterParticle : public Particle{
public:
ofPoint target;
bool bMoveToTarget;
float * maxSpeed;
float * smoothSpeed;
float * softKillStepSize;
float * aperture;
float * maxPointSize;
letterParticle(float _x = 0, float _y = 0, float _xv = 0, float _yv = 0) :
Particle(_x,_y,_xv, _yv) {
bMoveToTarget = false;
bKillSoft = false;
}
void setSettingsPointer( float * maxSpeed, float * smoothSpeed,float * softKillStepSize,float * aperture, float * maxPointSize){
this->maxSpeed = maxSpeed;
this->smoothSpeed = smoothSpeed;
this->softKillStepSize = softKillStepSize;
this->aperture = aperture;
this->maxPointSize = maxPointSize;
}
virtual void updatePosition(float timeStep) {
if(bFree)
return;
Particle::updatePosition(timeStep);
if(bKillSoft){
alpha -= *softKillStepSize;
if(alpha<=0){
bKillSoft = false;
setFree(true);
}
}
if(!bMoveToTarget)
return;
float smooth = *smoothSpeed;
float dx,dy;
dx = (target.x - x)* smooth;
dy = (target.y - y)* smooth;
if(abs(dx)+abs(dy)> *maxSpeed){
float fac = *maxSpeed / (float)(abs(dx)+abs(dy));
dx *= fac;
dy *= fac;
}
x += dx;
y += dy;
}
virtual float getDistanceToTarget(){
return this->distance(target);
}
virtual void draw(float grey = 255) {
if(bFree){
return;
}
ofSetColor(grey,grey,grey,alpha);//TODO include z
ofCircle(x,y,radius);
}
virtual void drawVertex(){
if(bFree){
return;
}
float opacity = 1;
float size = 0;
if (z!=0){
size = z * *aperture + 1.;
size = min(size, *maxPointSize);
float r = size / 2.f;
opacity = 1.f / (PI * r * r);
}
glPointSize(2.f+size);
glBegin(GL_POINTS);
ofSetColor(255,255,255,alpha*opacity);
glVertex2f(x,y);
glEnd();
}
void setTarget(float x,float y){
bMoveToTarget = true;
bNoForce = true;
target.set(x,y);
}
void removeTarget(){
bNoForce = false;
bMoveToTarget = false;
}
virtual void killSoft(){
bKillSoft = true;
}
};
| [
"[email protected]"
]
| [
[
[
1,
110
]
]
]
|
12c93f7d5292f775ff684b39144285936e9b685e | fd4f996b64c1994c5e6d8c8ff78a2549255aacb7 | / nicolinorochetaller --username adrianachelotti/trunk/testing Server_transfierreArchivo/clientedeprueba/Cuadrado.h | e752ee9ba4cc5ae1c2302a0b7113788d1a534571 | []
| no_license | adrianachelotti/nicolinorochetaller | 026f32476e41cdc5ac5c621c483d70af7b397fb0 | d3215dfdfa70b6226b3616c78121f36606135a5f | refs/heads/master | 2021-01-10T19:45:15.378823 | 2009-08-05T14:54:42 | 2009-08-05T14:54:42 | 32,193,619 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,053 | h | // Cuadrado.h: interface for the Cuadrado class.
//
//////////////////////////////////////////////////////////////////////
#if !defined CUADRADO_H
#define CUADRADO_H
#include "Figura.h"
class Cuadrado : public Figura
{
private:
int lado;
Punto posicionVerticeInferiorIzquierdo;
public:
/*Constructor sin parametros */
Cuadrado();
/*Constructor sin parametros */
Cuadrado(string id,int lado, Punto posVerInfIzq);
/*Destrcutor */
virtual ~Cuadrado();
/*Setea la longitud del lado del cuadrado */
void setLado(int lado);
/*Retorna la longitud del lado del cuadrado */
int getLado();
/*Setea la posicion del vertice inferior izquierdo del cuadrado */
void setPosicionVerticeInferiorIzquierdo(Punto vertice);
/*Retorna la posicion del vertice inferior izquierdo del cuadrado*/
Punto getPosicionVerticeInferiorIzquierdo();
/*Metodo encargado de dibujar el cuadrado*/
virtual int dibujar();
/*Metodo encargado de dibujar la figura */
virtual void resolverChoque();
};
#endif
| [
"[email protected]@0b808588-0f27-11de-aab3-ff745001d230"
]
| [
[
[
1,
46
]
]
]
|
fab77f46004fd3a62b4628289993556eb0536555 | f95341dd85222aa39eaa225262234353f38f6f97 | /DesktopX/Plugins/DXTaskbar7/DXTaskbar7/Taskbar7.h | e9eb6805bfc1084581436ceb4ccd56b14f949b08 | []
| no_license | Templier/threeoaks | 367b1a0a45596b8fe3607be747b0d0e475fa1df2 | 5091c0f54bd0a1b160ddca65a5e88286981c8794 | refs/heads/master | 2020-06-03T11:08:23.458450 | 2011-10-31T04:33:20 | 2011-10-31T04:33:20 | 32,111,618 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,056 | h | ///////////////////////////////////////////////////////////////////////////////////////////////
//
// DXTaskbar7 - Extended Taskbar Support for Windows 7
//
// Copyright (c) 2009-2010, Julien Templier
// All rights reserved.
//
///////////////////////////////////////////////////////////////////////////////////////////////
// * $LastChangedRevision$
// * $LastChangedDate$
// * $LastChangedBy$
///////////////////////////////////////////////////////////////////////////////////////////////
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "stdafx.h"
#include <comsvcs.h>
#include "COMError.h"
#include "DXTaskbar7.h"
#include "Taskbar7Errors.h"
#include "resource.h"
// Header Files for Jump List features
#include <objectarray.h>
#include <shobjidl.h>
#include <propkey.h>
#include <propvarutil.h>
#include <shlobj.h>
#define DESTINATION_TASKS L"Tasks"
#define DESTINATION_FREQUENT L"DESTINATION_FREQUENT"
#define DESTINATION_RECENT L"DESTINATION_RECENT"
#include <gdiplus.h>
using namespace Gdiplus;
#include <string>
#include <vector>
#include <map>
using namespace std;
// CAeroColor
class ATL_NO_VTABLE CTaskbar7 :
public CComObjectRootEx<CComSingleThreadModel>,
public CComCoClass<CTaskbar7, &CLSID_Taskbar7>,
public IDispatchImpl<ITaskbar7, &IID_ITaskbar7, &LIBID_DXTaskbar7Lib, /*wMajor =*/ 1, /*wMinor =*/ 0>,
public ISupportErrorInfo
{
public:
CTaskbar7() {}
DECLARE_PROTECT_FINAL_CONSTRUCT()
HRESULT FinalConstruct()
{
GdiplusStartup(&m_gdiplusToken, &m_gdiplusStartupInput, NULL);
m_pTaskbarList = NULL;
m_pCustomDestinationList = NULL;
m_pApplicationDestinations = NULL;
m_hwnd = NULL;
m_objectID = NULL;
m_processID = NULL;
m_parentHwnd = NULL;
m_isTabRegistered = false;
m_isAppIdSet = false;
m_isWindows7 = false;
// Check that we are running on Windows 7
OSVERSIONINFO versionInfo;
versionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&versionInfo);
if (versionInfo.dwMajorVersion == 6 && versionInfo.dwMinorVersion == 1)
m_isWindows7 = true;
return S_OK;
}
void FinalRelease()
{
GdiplusShutdown(m_gdiplusToken);
}
DECLARE_REGISTRY_RESOURCEID(IDR_TASKBAR7)
DECLARE_NOT_AGGREGATABLE(CTaskbar7)
BEGIN_COM_MAP(CTaskbar7)
COM_INTERFACE_ENTRY(ITaskbar7)
COM_INTERFACE_ENTRY(ISupportErrorInfo)
COM_INTERFACE_ENTRY(IDispatch)
END_COM_MAP()
private:
enum Category {
Task = 1,
Custom = 2,
Separator = 3,
Frequent = 4,
Recent = 5
};
struct ThumbButton
{
int id;
wstring image;
wstring tooltip;
int flags;
};
struct Destination
{
Category type;
wstring name;
wstring path;
wstring arguments;
wstring icon;
int iconIndex;
wstring workingFolder;
Destination() {};
Destination(Category type, wstring name, wstring path, wstring arguments, wstring icon, int iconIndex, wstring workingFolder) :
type(type),
name(name),
path(path),
arguments(arguments),
icon(icon),
iconIndex(iconIndex),
workingFolder(workingFolder) {};
~Destination() {};
};
ULONG_PTR m_gdiplusToken;
GdiplusStartupInput m_gdiplusStartupInput;
// The COM instances
ITaskbarList3* m_pTaskbarList;
ICustomDestinationList* m_pCustomDestinationList;
IApplicationDestinations* m_pApplicationDestinations;
// Handle to the DX window
HWND m_hwnd;
DWORD m_objectID;
// Main process window (the one with the taskbar icon)
HWND m_parentHwnd;
DWORD m_processID;
bool m_isWindows7;
bool m_isTabRegistered;
bool m_isAppIdSet;
// The list of thumbbar buttons to add
vector<ThumbButton> m_buttons;
map<wstring, vector<Destination>> destinations;
bool IsWindows7();
void GetMainWindowHandle();
static BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam);
static LRESULT CALLBACK WindowProc(int nCode, WPARAM wParam, LPARAM lParam);
void RegisterTab();
void AddCustomDestination(Category type, wstring name, wstring category, wstring path, wstring arguments, wstring icon, int iconIndex, wstring workingFolder);
HRESULT CreateShellLink(Destination destination, IShellLink **ppShellLink);
HRESULT CreateSeparatorLink(IShellLink **ppShellLink);
HRESULT LoadImageFromFile(wstring path, Bitmap** bitmap);
HRESULT LoadButton(int id, wstring path, wstring tooltip, int flags, THUMBBUTTON* button);
public:
// Used by DXTaskbar
void SetHWND(HWND hwnd) { m_hwnd = hwnd; }
HWND GetHWND() { return m_hwnd; }
HWND GetParentHWND() { return m_parentHwnd; }
void SetObjectID(DWORD id) { m_objectID = id; }
void Init();
void Cleanup();
// Internal use by static methods
void SetMainHwnd(HWND hwnd) { m_parentHwnd = hwnd; }
DWORD GetProcessID() { return m_processID; }
void HookMainWindowMessages();
//////////////////////////////////////////////////////////////////////////
// ISupportErrorInfo
//////////////////////////////////////////////////////////////////////////
STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid);
//////////////////////////////////////////////////////////////////////////
// ITaskbar7
//////////////////////////////////////////////////////////////////////////
STDMETHOD(get_TabHwnd)(LONG* hwnd);
STDMETHOD(SetTabsIcon)(BSTR icon);
STDMETHOD(ConfigureTab)(BSTR name, LONG after);
STDMETHOD(SetTabActive)();
STDMETHOD(RemoveTab)();
// ThumbBar
STDMETHOD(SetupButton)(int id, BSTR image, BSTR tooltip, int flags);
STDMETHOD(UpdateButton)(int id, BSTR image, BSTR tooltip, int flags);
STDMETHOD(AddButtons)();
// Overlay
STDMETHOD(SetOverlayIcon)(BSTR path, BSTR description);
// Progress
STDMETHOD(SetProgressState)(int flag);
STDMETHOD(SetProgressValue)(ULONGLONG ullCompleted, ULONGLONG ullTotal);
// Tasks and destinations
STDMETHOD(RemoveAllDestinations)();
STDMETHOD(DeleteList)(BSTR appID);
STDMETHOD(CommitList)();
STDMETHOD(AbortList)();
STDMETHOD(AddUserTask)(BSTR name, BSTR path, BSTR arguments, BSTR icon, int iconIndex, BSTR workingFolder);
STDMETHOD(AddDestination)(BSTR category, BSTR name, BSTR path, BSTR arguments, BSTR icon, int iconIndex, BSTR workingFolder);
STDMETHOD(AddSeparator)(BSTR category);
STDMETHOD(AppendKnownCategory)(int knownDestCategory);
};
OBJECT_ENTRY_AUTO(__uuidof(Taskbar7), CTaskbar7)
| [
"julien.templier@ab80709b-eb45-0410-bb3a-633ce738720d"
]
| [
[
[
1,
250
]
]
]
|
991578744d77a4ad88971236cb51f6fd19bc032d | 7f980896deef4d39fc88627f98f3cba8fa4c3e37 | /src/rs.h | 8876e4c1919b4e8986c63a5583bd07741d817a39 | [
"MIT"
]
| permissive | mshogin/node-occi | 226ede27d1b355530312cd4841fc6dae4c96c50a | ad0a7b33854e7005ba8af57f7acb92f5c0192155 | refs/heads/master | 2020-04-06T04:41:06.842206 | 2011-08-26T13:41:53 | 2011-08-26T13:41:53 | 2,211,402 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,062 | h | /*!
* Copyright by Shogin Michael
* See contributors list in README
*/
#pragma once
#ifndef H_NODE_OCCI_RS
#define H_NODE_OCCI_RS
#include <v8.h>
#include <node.h>
#include <node_events.h>
#include "occi.h"
using namespace v8;
using namespace oracle::occi;
#define V8STR(str) String::New(str)
class rs : public node::EventEmitter {
public:
ResultSet *_rs;
rs();
~rs();
static Persistent<FunctionTemplate> persistent_function_template;
static void Init(Handle<Object> target);
static Handle<Value> Next(const v8::Arguments& args);
static Handle<Value> Get_Int(const v8::Arguments& args);
static Handle<Value> Get_Double(const v8::Arguments& args);
static Handle<Value> Get_Clob(const v8::Arguments& args);
static Handle<Value> Get_String(const v8::Arguments& args);
static Handle<Value> Fetch_All(const v8::Arguments& args);
static Handle<Value> Fetch(const v8::Arguments& args);
protected:
static Handle<Value> New(const Arguments& args);
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
48
]
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.