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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
15032092ea9fff764b043014f24f8ffcf7dba516 | 1493997bb11718d3c18c6632b6dd010535f742f5 | /direct_ui/UIlib/UIEdit.h | f7576ba9bae3e9cc2b509adcb6aa894be731afba | []
| no_license | kovrov/scrap | cd0cf2c98a62d5af6e4206a2cab7bb8e4560b168 | b0f38d95dd4acd89c832188265dece4d91383bbb | refs/heads/master | 2021-01-20T12:21:34.742007 | 2010-01-12T19:53:23 | 2010-01-12T19:53:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,785 | h | #if !defined(AFX_UIEDIT_H__20060218_14AE_7A41_09A2_0080AD509054__INCLUDED_)
#define AFX_UIEDIT_H__20060218_14AE_7A41_09A2_0080AD509054__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
/////////////////////////////////////////////////////////////////////////////////////
//
class CSingleLineEditWnd;
class UILIB_API CSingleLineEditUI : public CControlUI
{
friend CSingleLineEditWnd;
public:
CSingleLineEditUI();
LPCTSTR GetClass() const;
UINT GetControlFlags() const;
void SetText(LPCTSTR pstrText);
void SetEditStyle(UINT uStyle);
void SetReadOnly(bool bReadOnly);
bool IsReadOnly() const;
void Event(TEventUI& event);
SIZE EstimateSize(SIZE szAvailable);
void DoPaint(HDC hDC, const RECT& rcPaint);
protected:
CSingleLineEditWnd* m_pWindow;
bool m_bReadOnly;
UINT m_uEditStyle;
};
/////////////////////////////////////////////////////////////////////////////////////
//
class CMultiLineEditWnd;
class UILIB_API CMultiLineEditUI : public CControlUI
{
friend CMultiLineEditWnd;
public:
CMultiLineEditUI();
~CMultiLineEditUI();
LPCTSTR GetClass() const;
UINT GetControlFlags() const;
void Init();
CStdString GetText() const;
void SetText(LPCTSTR pstrText);
void SetEnabled(bool bEnabled);
void SetVisible(bool bVisible);
void SetReadOnly(bool bReadOnly);
void SetFocus(bool bReadOnly);
bool IsReadOnly() const;
void Event(TEventUI& event);
SIZE EstimateSize(SIZE szAvailable);
void SetPos(RECT rc);
void SetPos(int left, int top, int right, int bottom);
void DoPaint(HDC hDC, const RECT& rcPaint);
protected:
CMultiLineEditWnd* m_pWindow;
};
#endif // !defined(AFX_UIEDIT_H__20060218_14AE_7A41_09A2_0080AD509054__INCLUDED_)
| [
"[email protected]"
]
| [
[
[
1,
83
]
]
]
|
f7caf07453c142b46070ef0a7844d17947e6f2bc | de98f880e307627d5ce93dcad1397bd4813751dd | /3libs/ut/include/OXHyperFrameWnd.h | 5478151eaed7a63149ab4e33c1bd1dac6e9ad249 | []
| no_license | weimingtom/sls | 7d44391bc0c6ae66f83ddcb6381db9ae97ee0dd8 | d0d1de9c05ecf8bb6e4eda8a260c7a2f711615dd | refs/heads/master | 2021-01-10T22:20:55.638757 | 2011-03-19T06:23:49 | 2011-03-19T06:23:49 | 44,464,621 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 487 | h | #pragma once
#include "oxdllext.h"
// COXHyperFrameWnd frame
class OX_CLASS_DECL COXHyperFrameWnd : public CFrameWnd
{
DECLARE_DYNCREATE(COXHyperFrameWnd)
protected:
COXHyperFrameWnd(); // protected constructor used by dynamic creation
virtual ~COXHyperFrameWnd();
protected:
// Generated message map functions
//{{AFX_MSG(CConfig)
afx_msg void OnActivate(UINT nState, CWnd* pWndOther, BOOL bMinimized);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
| [
"[email protected]"
]
| [
[
[
1,
22
]
]
]
|
a9fd0f9c87cf57337afc654d894e816208d43f20 | 7b4c786d4258ce4421b1e7bcca9011d4eeb50083 | /_统计专用/C++Primer中文版(第4版)/第一次-代码集合-20090414/第十二章 类/20090216_习题12.34_定义一个'友元'非成员函数.cpp | c4599f6398d90feef2308ec801dcc782baede8e9 | []
| no_license | lzq123218/guoyishi-works | dbfa42a3e2d3bd4a984a5681e4335814657551ef | 4e78c8f2e902589c3f06387374024225f52e5a92 | refs/heads/master | 2021-12-04T11:11:32.639076 | 2011-05-30T14:12:43 | 2011-05-30T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 812 | cpp | #include <iostream>
#include <string>
#include <fstream>
using namespace std;
class Sales_item {
public:
friend Sales_item add(const Sales_item&, const Sales_item&);
bool same_isbn(const Sales_item &rhs) const
{
return isbn == rhs.isbn;
}
Sales_item(const std::string &book = " "):
isbn(book), units_sold(0), revenue(0.0) {}
Sales_item(std::istream &is)
{
cin >> isbn >> units_sold >> revenue;
}
private:
std::string isbn;
unsigned units_sold;
double revenue;
};
Sales_item add(const Sales_item &obj1, const Sales_item &obj2)
{
if (!obj1.same_isbn(obj2))
return obj1;
Sales_item temp;
temp.isbn = obj1.isbn;
temp.units_sold = obj1.units_sold + obj2.units_sold;
temp.revenue = obj1.revenue + obj2.revenue;
return temp;
}
int main()
{
return 0;
} | [
"baicaibang@70501136-4834-11de-8855-c187e5f49513"
]
| [
[
[
1,
40
]
]
]
|
5b78f524daf55462d58adad2b17d4dfeef8d4e60 | 44a6253596a3b1b81e56560b22b8ed4a0dc3b9bc | /Block.h | 4636835f19dab1a056275e0ef220cb4f90ea662c | []
| no_license | Nuos/terraingpu | 9a2329aea3761c61c816759889a46a3ea82be7ea | 1ee3214d6e9e2190556bec2a90a52beec25f7df7 | refs/heads/master | 2020-12-11T07:19:38.181573 | 2009-04-11T17:45:16 | 2009-04-11T17:45:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,427 | h | #pragma once
//#define USE_BOOST 1
#include "DXUT.h"
#ifdef USE_BOOST
#include <boost/unordered_map.hpp>
#define hash_t boost::hash
#define unordered_map_t boost::unordered_map
#else
#include <unordered_map>
#define hash_t std::tr1::hash
#define unordered_map_t std::tr1::unordered_map
#endif
#include <functional>
#include <queue>
struct BLOCK_ID {
BLOCK_ID(void) : x(0), y(0), z(0) {}
BLOCK_ID(int x, int y, int z) : x(x), y(y), z(z) {}
int x, y, z;
};
size_t hash_t<BLOCK_ID>::operator ()(const BLOCK_ID &id) const {
return ((static_cast<size_t>(id.y) & 0x0FF) << 24) |
((static_cast<size_t>(id.x) & 0xFFF) << 12) |
((static_cast<size_t>(id.z) & 0xFFF) << 0);
}
bool std::equal_to<BLOCK_ID>::operator ()(const BLOCK_ID &left, const BLOCK_ID &right) const {
return left.x == right.x && left.y == right.y && left.z == right.z;
}
class Block {
public:
void Activate(void);
void Deactivate(void);
void Draw(ID3D10Device *device, ID3D10EffectTechnique *technique);
bool empty(void) const { return primitive_count_ == 0 || index_count_ == 0; }
const BLOCK_ID &id(void) const { return id_; }
bool active(void) const { return active_; }
bool used(void) const { return used_; }
void set_used(bool used) { used_ = used; }
UINT primitive_count(void) const { return index_count_ / 3; }
static HRESULT OnCreateDevice(ID3D10Device *device);
static HRESULT OnLoadEffect(ID3D10Device *device, ID3D10Effect *effect);
static void OnDestroyDevice(void);
static void OnFrameMove(float elapsed_time, const D3DXVECTOR3 &camera_pos);
static Block *GetBlockByID(const BLOCK_ID &id);
static UINT queue_size(void) { return activation_queue_.size(); }
static UINT vertex_buffers_total_size(void) { return vertex_buffers_total_size_; }
static UINT index_buffers_total_size(void) { return index_buffers_total_size_; }
static void ResetStats(void) { draw_calls_ = primitives_drawn_ = 0; }
static UINT draw_calls(void) { return draw_calls_; }
static UINT primitives_drawn(void) { return primitives_drawn_; }
// Constants
static const UINT kVoxelDim;
static const UINT kVoxelDimMinusOne;
static const float kInvVoxelDim;
static const float kInvVoxelDimMinusOne;
static const UINT kMargin;
static const UINT kVoxelDimWithMargins;
static const UINT kVoxelDimWithMarginsMinusOne;
static const float kInvVoxelDimWithMargins;
static const float kInvVoxelDimWithMarginsMinusOne;
static const float kBlockSize;
private:
Block(const D3DXVECTOR3 &position);
Block(const BLOCK_ID &id);
~Block(void);
HRESULT ActivateReal(ID3D10Device *device);
void DeactivateReal(void);
void UpdateDistanceToCamera(void);
// Generation steps
HRESULT RenderDensityVolume(ID3D10Device *device);
HRESULT GenerateTriangles(ID3D10Device *device);
// Helper methods for stream-out-query
static void InitQuery(ID3D10Device *device);
static UINT64 GetQueryResult(void);
D3DXVECTOR3 position_;
BLOCK_ID id_;
INT primitive_count_;
INT index_count_;
bool active_; // Are all buffers (vertex+index) created and filled with data?
bool waiting_for_activation_;
bool used_; // Is this block referenced by the octree?
float activation_time_;
float distance_to_camera_; // ... at the time when Activate() was called
// Statistics...
static DWORD vertex_buffers_total_size_;
static DWORD index_buffers_total_size_;
static UINT draw_calls_;
static UINT primitives_drawn_;
// Rendering resources
ID3D10Buffer *vertex_buffer_;
ID3D10Buffer *index_buffer_;
static D3DXVECTOR3 camera_pos_;
static ID3D10EffectScalarVariable *activation_time_ev_;
static ID3D10InputLayout *input_layout_;
// Generation resources
static ID3D10Effect *effect_;
static ID3D10Buffer *screen_aligned_quad_vb_;
static ID3D10InputLayout *screen_aligned_quad_il_;
static ID3D10Texture3D *density_volume_tex_;
static ID3D10RenderTargetView *density_volume_rtv_;
static ID3D10ShaderResourceView *density_volume_srv_;
static ID3D10EffectShaderResourceVariable *density_volume_ev_;
static ID3D10Texture3D *indices_volume_tex_;
static ID3D10RenderTargetView *indices_volume_rtv_;
static ID3D10ShaderResourceView *indices_volume_srv_;
static ID3D10EffectShaderResourceVariable *indices_volume_ev_;
static ID3D10Buffer *triangle_list_vb_;
static ID3D10InputLayout *triangle_list_il_;
static ID3D10Buffer *cells_vb_;
static ID3D10InputLayout *cells_il_;
static ID3D10Buffer *edges_vb_;
static ID3D10InputLayout *edges_il_;
static ID3D10Buffer *voxel_slice_vb_;
static ID3D10InputLayout *voxel_slice_il_;
static ID3D10EffectVectorVariable *offset_ev_;
static ID3D10Query *query_;
// Block cache
typedef unordered_map_t<BLOCK_ID, Block *> BLOCK_CACHE;
static BLOCK_CACHE cache_;
// Activation queue
struct CameraDistGreater : public std::binary_function<Block *, Block *, bool> {
bool operator()(const Block *left, const Block *right) const {
return left->distance_to_camera_ > right->distance_to_camera_;
}
};
typedef std::priority_queue<Block *, std::vector<Block *>, CameraDistGreater > BLOCK_PQUEUE;
typedef std::queue<Block *> BLOCK_QUEUE;
static BLOCK_PQUEUE activation_queue_;
static BLOCK_QUEUE deactivation_queue_;
};
| [
"[email protected]",
"[email protected]",
"[email protected]"
]
| [
[
[
1,
2
],
[
4,
4
],
[
11,
11
],
[
17,
25
],
[
27,
47
],
[
49,
57
],
[
63,
82
],
[
84,
102
],
[
109,
139
],
[
141,
154
]
],
[
[
3,
3
],
[
5,
10
],
[
12,
16
],
[
26,
26
],
[
140,
140
]
],
[
[
48,
48
],
[
58,
62
],
[
83,
83
],
[
103,
108
]
]
]
|
bd619ece1f31ba36aacb6ab2fd1e2452400dd597 | 3d7d8969d540b99a1e53e00c8690e32e4d155749 | /AppInc/Gesture.h | eb5d82d8ce2d422e9277ea6950ad74306fd31d57 | []
| no_license | SymbianSource/oss.FCL.sf.incubator.photobrowser | 50c4ea7142102068f33fc62e36baab9d14f348f9 | 818b5857895d2153c4cdd653eb0e10ba6477316f | refs/heads/master | 2021-01-11T02:45:51.269916 | 2010-10-15T01:18:29 | 2010-10-15T01:18:29 | 70,931,013 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,090 | h | /*
* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors: Juha Kauppinen, Mika Hokkanen
*
* Description: Photo Browser
*
*/
#ifndef GESTURE_H
#define GESTURE_H
// INCLUDES
#include <e32std.h>
#include <e32base.h>
#include <w32std.h>
#undef CURSOR_SIMULATION
const TInt KDefaultThresholdOfTapPixels = 25;
const TInt KDefaultThresholdOfCursorPixels = 0; // Any movement is cursor movement
const TInt KDefaultStationaryTime = 100000; // 100ms
const TInt KDefaultLongTapTime = 400000; // 300ms = 200ms + stationary (100ms)
const TInt KDefaultMonitoringTime = 200000; // 200ms
const TInt KDefaultSafetyTime = 200000; // 200ms
const TInt KDefaultValidityTimeOfFlick = 300000; // recent 300ms drag to be checked
enum {
EGestureNone = 0x0000,
EGestureStationary = 0x0001, // Send on moved event when user hasn't moved finger
EGestureDrag = 0x0002,
EGestureTap = 0x0004,
EGestureLongTapping = 0x0008,
EGestureLongTap = 0x0010,
EGestureCursor = 0x0100,
// sub-type for cursor simuation
EGestureUp = 0x1000,
EGestureDown = 0x2000,
EGestureLeft = 0x4000,
EGestureRight = 0x8000,
// 1st gesture type is stored in high 16 bits
EGestureDragged = EGestureDrag << 16,
EGestureTapped = EGestureTap << 16,
EGestureLongTapped = EGestureLongTap << 16
};
// Gestures can be combination
typedef TUint32 TGestureType;
#define IS_GESTURE_NONE(t) ((t) == (EGestureNone))
#define IS_GESTURE_DRAG(t) ((t) & (EGestureDrag))
#define IS_GESTURE_STATIONARY(t) ((t) & (EGestureStationary))
#define IS_GESTURE_CURSORSIMULATION(t) ((t) & ((EGestureUp | EGestureDown | EGestureLeft | EGestureRight)))
#define IS_GESTURE_TAP(t) ((t) & (EGestureTap))
#define IS_GESTURE_TAPPED(t) ((t) & (EGestureTapped))
#define IS_GESTURE_LONGTAPPING(t) ((t) & (EGestureLongTapping))
#define IS_GESTURE_LONGTAP(t) ((t) & (EGestureLongTap))
#define IS_GESTURE_DRAGGED(t) ((t) & (EGestureDragged))
#define IS_GESTURE_SINGLETAP(t) (IS_GESTURE_TAP(t) && !IS_GESTURE_TAPPED(t))
#define IS_GESTURE_DOUBLETAP(t) (IS_GESTURE_TAP(t) && IS_GESTURE_TAPPED(t))
#define IS_GESTURE_TAPnDRAG(t) (IS_GESTURE_CURSORSIMULATION(t) && IS_GESTURE_TAPPED(t))
enum {
EGestureModeNone = 0x00,
EGestureModeCursorEmulation = 0x01, // gives cursor movements when beyond threshold
EGestureModeSingleCursorEmulation = 0x02, // gives singles cursor movement on each touch
EGestureModeDrag = 0x04, //
EGestureModeTap = 0x08,
EGestureModeTapAndDrag = 0x10,
EGestureModeDrawCircle = 0x20
};
// CLASS DECLARATION
class MGestureCallBack
{
public:
/**
* Callback method. Get's called when touch gesture started (when user touches).
* @param aPos Point where touch happens
* @param aType Gesture type bit flag (move_right/left/up/down or tap)
*/
// Called when user touches screen
virtual void HandleGestureBeganL(const TPoint& aPos ) = 0;
// Called when user is dragging
// Drag event comes with movement delta from previous event (EGestureDrag)
// Drag event comes with touched position (EGestureUp/Down/Left/Right)
// when it exceeds defined threshold
virtual void HandleGestureMovedL(const TPoint& aPos,
const TGestureType aType) = 0;
// Called when user releases screen
// Movement within defined last moment is given in aPos. (pixels/250ms by default)
virtual void HandleGestureEndedL(const TPoint& aPos,
const TGestureType aType) = 0;
};
/**
* CGesture
*
*/
class CGesture : public CTimer
{
public:
// Constructors and destructor
/**
* Destructor.
*/
~CGesture();
/**
* Two-phased constructor.
*/
static CGesture* NewL(MGestureCallBack* aOwner);
/**
* Two-phased constructor.
*/
static CGesture* NewLC(MGestureCallBack* aOwner);
private:
/**
* Constructor for performing 1st stage construction
*/
CGesture(MGestureCallBack* aOwner);
/**
* EPOC default constructor for performing 2nd stage construction
*/
void ConstructL();
public: // New functions
IMPORT_C void PointerEventL(const TPointerEvent& aEvent);
IMPORT_C void SetThresholdOfTap(const TInt aPixels);
IMPORT_C void SetThresholdOfCursor(const TInt aPixels);
IMPORT_C void SetStationaryTime(const TInt aMicroseconds);
IMPORT_C void SetLongTapTime(const TInt aMicroSeconds);
IMPORT_C void SetMonitoringTime(const TInt aMicroseconds);
IMPORT_C void SetSafetyTime(const TInt aMicroseconds);
private:
enum TGestureState
{
EWaiting, // Waiting for first touch
EBegan, // Touch down. Gesture started (or second gesture)
EStationary, // Gesture is stationary
ETravelling, // Dragging beyond threshold
EMonitoring, // Monitoring second gesture
EEnded // Touch operation ended. Wait to avoid mis touch
};
/**
* Just check if the movement exceeds thoreshold
*/
TBool IsMovementWithinThreshold(const TPoint aDelta, const TInt aThreshold);
/**
* Map touch movement to 8-directions if volume of movement exceeds threshold
* Also check if movement is faster than threshold
*/
TGestureType CheckMovement(const TPoint aPointPrevious, const TPoint aPointCurrent, const TBool aSkipThresholdCheck=EFalse);
/**
* Maps touch movements in last defines time, aValidityTime, to 8-directions
* Movements are recorded in iDragPoints and iDragTicks (RArray of TPoint and TInt)
*/
TGestureType CheckFlick(const TInt aValidityTime, TPoint& aVector);
/**
* Active object callback. Used for timer
*/
void RunL();
private: // Data
/**
* Current state of Gesture
*/
TGestureState iState;
/**
* Pointer to owner
*/
MGestureCallBack* iOwner;
/**
* Pointer event received from owner.
*/
TPointerEvent iPointerEvent;
/**
* Point records
*/
TPoint iPointBegan; // point where user touched down
TPoint iPointFirstBegan; // point where user touched down in 1st gesture
TPoint iPointLastCursor; // point where last cursor simulation event occured
TPoint iPointPreviousEvent; // last point where avkon informed on drag
/**
* Remembers gesture in 1st gesture
*/
TGestureType iFirstGesture;
/**
* Thresholds in Pixels
*/
TInt iThresholdOfTap; // movement stays within this pixels
TInt iThresholdOfCursor; // cursor simulation occurs when exceeding threshold
/**
* Thresholds in Micro seconds
*/
TInt iStationaryTime; // UP should occur within the time for Tap
TInt iLongTapTime; // for long tap
TInt iMonitoringTime; // for 2nd gesture. Notify gesture end if expires
TInt iSafetyTime; // Ignores gesture after Ended to avoid mis-touch
/**
* Drag points and the tick time for flick
*/
RArray<TPoint> iDragPoints;
RArray<TInt> iDragTicks;
};
#endif // GESTURE_H
| [
"none@none"
]
| [
[
[
1,
238
]
]
]
|
90ab1c6285b471dd7f2d7f7b66af08bd9fd9c4a3 | f25e9e8fd224f81cefd6d900f6ce64ce77abb0ae | /Exercises/Old Solutions/OpenGL5/OpenGL5/controller.h | 44dcbae8fd03efa0483d57925e00cc0995b3ee6f | []
| no_license | giacomof/gameengines2010itu | 8407be66d1aff07866d3574a03804f2f5bcdfab1 | bc664529a429394fe5743d5a76a3d3bf5395546b | refs/heads/master | 2016-09-06T05:02:13.209432 | 2010-12-12T22:18:19 | 2010-12-12T22:18:19 | 35,165,366 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 940 | h | #pragma once
#ifndef controller__H__
#define controller__H__
#include <SDL.h>
#include "entitySpectator.h"
#include "assetManager.h"
class Controller // Singleton
{
public:
static Controller _instance;
static SDL_mutex *mutex_controller;
static entitySpectator *playerObject;
static bool quit;
Controller() { & getInstance(); }
~Controller() {};
Controller(const Controller & getInstance());
Controller & operator=(Controller & getInstance());
static Controller & getInstance();
static void setPlayerObject(entitySpectator * player);
static void moveForward(bool shouldMove);
static void moveBackward(bool shouldMove);
static void strafeLeft(bool shouldMove);
static void strafeRight(bool shouldMove);
static void lookDeltaX(float deltaLook);
static void lookDeltaY(float deltaLook);
static void changeCameraMode(bool following);
static unsigned int count;
};
#endif | [
"[email protected]@1a5f623d-5e27-cfcb-749e-01bf3eb0ad9d",
"[email protected]@1a5f623d-5e27-cfcb-749e-01bf3eb0ad9d"
]
| [
[
[
1,
2
],
[
6,
17
],
[
21,
21
],
[
23,
24
],
[
26,
35
]
],
[
[
3,
5
],
[
18,
20
],
[
22,
22
],
[
25,
25
],
[
36,
38
]
]
]
|
70e17a8333be4a18194e7eb9876bb51ac02d3c46 | da2575b50a44f20ef52d6f271e73ff15dd54682f | /3rdparty/encode/CyoDecode.h | b2faf2524d70862f74fb568821c2afb137c1133b | []
| no_license | lqianlong/lincodelib | 0ef622bc988d6cf981a0aaf9da42b82fbd0b14cf | 27e71716f3279c02a90c213470b4c52cd8e86b60 | refs/heads/master | 2020-08-29T17:02:45.005037 | 2010-05-03T20:17:20 | 2010-05-03T20:17:20 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,042 | h |
//////////////////////////////////////////////////////////////////////
//
// CyoDecode.h
//
// Developed by Graham Bull for Cyotec Systems Limited.
// http://www.cyotec.com
//
// Copyright (c) 2004 by Cyotec Systems Limited. All Rights Reserved.
//
// This source code may be used, modified, compiled, duplicated, and/or
// distributed without restriction provided this copyright notice remains intact.
// Cyotec Systems Limited and/or its employees cannot be held responsible for any
// direct or indirect damage or loss of any kind that may result from using this
// code, and provides no warranty, guarantee, or support.
//
// Associated Files
// - CyoDecode.cpp
// - CyoEncode.h
// - CyoEncode.cpp
//
// History
// - September 22, 2004 - Created
//
// $Id: CyoDecode.h,v 1.2 2007/12/24 09:37:25 guoqiang Exp $
//
//////////////////////////////////////////////////////////////////////
#ifndef __CYODECODE_H
#define __CYODECODE_H
namespace CyoDecode
{
// Base16 Decoding
unsigned Base16DecodeGetLength( unsigned size );
unsigned Base16Decode( void* dest, const void* src, unsigned size );
// Base32 Decoding
unsigned Base32DecodeGetLength( unsigned size );
unsigned Base32Decode( void* dest, const void* src, unsigned size );
// Base64 Decoding
unsigned Base64DecodeGetLength( unsigned size );
unsigned Base64Decode( void* dest, const void* src, unsigned size );
}
#endif //__CYODECODE_H
//////////////////////////////////////////////////////////////////////
// $Log: CyoDecode.h,v $
// Revision 1.2 2007/12/24 09:37:25 guoqiang
// *** empty log message ***
//
// Revision 1.1.2.1 2007/11/16 01:21:30 guoqiang
// *** empty log message ***
//
// Revision 1.2 2005/04/07 08:04:52 xushiwei
// kfc改为使用CyoDecode、CyoEncode实现base64编码。
//
// Revision 1.1 2005/04/07 06:56:45 xushiwei
// base16、base32、base64编码的encode/decode算法。
// Developed by Graham Bull for Cyotec Systems Limited.(原稿)
//
| [
"linzhenqun@785468e8-de65-11dd-a893-8d7ce9fbef62"
]
| [
[
[
1,
63
]
]
]
|
c0c7c600b5e1fc3b1030db5ee769388c9a8ec05b | b505ef7eb1a6c58ebcb73267eaa1bad60efb1cb2 | /source/graphics/font.h | 2b39dd4c07b016df50863b8a214b665dc4fe4c53 | []
| no_license | roxygen/maid2 | 230319e05d6d6e2f345eda4c4d9d430fae574422 | 455b6b57c4e08f3678948827d074385dbc6c3f58 | refs/heads/master | 2021-01-23T17:19:44.876818 | 2010-07-02T02:43:45 | 2010-07-02T02:43:45 | 38,671,921 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,153 | h | #ifndef maid2_graphics_font_h
#define maid2_graphics_font_h
#include"../config/define.h"
#include"../auxiliary/globalpointer.h"
#include"core/ifontdevice.h"
#include"surface.h"
#include"graphicscore.h"
#include<map>
namespace Maid
{
class IFontRasterizeFilter
{
public:
virtual ~IFontRasterizeFilter(){};
//! フォントデータにフィルタ処理を施す
/*!
この中は自由にやっていいので
内部で pData を交換してしまってもOK
@param pData [io] フィルタ処理するサーフェス
@return 関数の成功で0
失敗で0以外
*/
virtual int Convert( SPSURFACEINSTANCE& pData )=0;
};
typedef boost::shared_ptr<IFontRasterizeFilter> SPFONTRASTERIZEFILTER;
typedef std::vector<SPFONTRASTERIZEFILTER> FONTRASTERIZEFILTERLIST;
class Font
:public GlobalPointer<GraphicsCore>
{
public:
enum
{
FILTER_NONE=~0,
};
Font();
bool IsCreated() const;
void Create( const SIZE2DI& size, bool IsAntiAlias );
void Create( const SIZE2DI& size, bool IsAntiAlias, const COLOR_R32G32B32A32F& Color );
void Create( const SIZE2DI& size, bool IsAntiAlias, const COLOR_R32G32B32A32F& Color, unt FilterNo );
void Create( const String& Name, const SIZE2DI& size, bool IsAntiAlias, const COLOR_R32G32B32A32F& Color, unt FilterNo );
void Destroy();
const String& GetName() const;
const SIZE2DI& GetSize() const;
bool IsAntiAlias()const;
const COLOR_R32G32B32A32F& GetColor() const;
unt GetFilterNo() const;
void Rasterize( unt32 code, SurfaceInstance& Dst )const;
SIZE2DI CalcTextSize( const String& text ) const;
static void SetFilter( unt No, const FONTRASTERIZEFILTERLIST& Filter );
private:
typedef std::map<unt,FONTRASTERIZEFILTERLIST> FILTERMAP;
static FILTERMAP s_FilterMap;
Graphics::SPFONT m_pFont;
String m_FontName;
SIZE2DI m_FontSize;
bool m_IsAntiAlias;
COLOR_R32G32B32A32F m_Color;
unt m_Filter;
};
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
79
]
]
]
|
892f3f1e6710db36164780ac2f194a016a008949 | a48646eddd0eec81c4be179511493cbaf22965b9 | /project/mysip/src/timer/timer_type.inc | 1737e00510cd13fedad6071c4a515476bb40f2fe | []
| no_license | lengue/tsip | 0449f791a5cbe9e9fdaa1b4d7f1d1e28eff2f0ec | da8606bd7d865d4b4a389ec1594248a4044bc890 | refs/heads/master | 2021-01-10T08:40:32.925501 | 2010-06-05T12:44:10 | 2010-06-05T12:44:10 | 53,989,315 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 204 | inc | typedef struct tagTIMER_S
{
UCHAR ucIsUsed;
ULONG ulModuleID;
ULONG ulName;
TIMER_TYPE_E eType;
ULONG ulLen;
ULONG ulPara;
HANDLE hTimer;
ULONG ulNext;
}TIMER_S; | [
"[email protected]"
]
| [
[
[
1,
11
]
]
]
|
99091445b670ea5d9cf5f53394121539353161f3 | 6dac9369d44799e368d866638433fbd17873dcf7 | /src/branches/06112002/Include/Input/InputMouse.h | 764f890a60ae81d3939767f9b5578c4ac857a6d1 | []
| no_license | christhomas/fusionengine | 286b33f2c6a7df785398ffbe7eea1c367e512b8d | 95422685027bb19986ba64c612049faa5899690e | refs/heads/master | 2020-04-05T22:52:07.491706 | 2006-10-24T11:21:28 | 2006-10-24T11:21:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,230 | h | #ifndef _INPUTMOUSE_H_
#define _INPUTMOUSE_H_
#include <Input/IInputDevice.h>
#include <Maths/Vector.h>
/** @ingroup Input_Group
* @brief Derived IInputDevice class for all Mouse Devices
*/
class InputMouse: public IInputDevice{
protected:
/** @var Entity *m_cursor
* @brief The cursor this device uses
*/
Entity *m_cursor;
/** @var int m_x
* @brief The x position of the cursor
*/
int m_x;
/** @var int m_y
* @brief The y position of the cursor
*/
int m_y;
/** @var bool *m_buttonstate
* @brief An array of boolean values denoting whether a button/key on the device is pressed or released
*/
bool *m_buttonstate;
/** @var Rect *m_AxisArea
* @brief The area the device can move the cursor within
*/
Rect *m_AxisArea;
/** @var Maths::Vector m_hotspot
* @brief The hotspot of the cursor (to use when pointing at entities)
*/
Maths::Vector m_hotspot;
virtual void ConfinePositionToArea (void);
virtual void AddEvent (InputEvent *e);
virtual void SendEvents (void);
/** Checks the devices axis for it's X/Y value
*
* @param axis The axis to check, X=1/Y=2
*/
virtual long CheckAxis (int axis) = 0;
public:
InputMouse (int DeviceID);
virtual ~InputMouse ();
virtual bool Update (void);
virtual bool ReadDevice (void);
virtual void SetHotspot (int x, int y);
// Activate/DeActivate a device
virtual bool GetActive (void);
virtual void SetActive (bool Active);
// Setting/Positioning cursor
virtual void SetCursor (Entity *cursor);
virtual void SetCursorPosition (int x, int y);
virtual void GetCursorPosition (int &x, int &y);
virtual void SetAxisArea (class Rect *r);
virtual void SetAxisArea ( int sx, int sy,int ex, int ey);
// Listener System
virtual void AddListener (InputEvent **listener);
virtual void RemoveListener (InputEvent **listener);
virtual int GetDeviceID (void);
virtual int GetDeviceType (void);
virtual void SetDeviceMode (int mode);
// Event System
virtual void FlushEventQueue (void);
};
#endif // #ifndef _INPUTMOUSE_H_
| [
"chris_a_thomas@1bf15c89-c11e-0410-aefd-b6ca7aeaabe7"
]
| [
[
[
1,
82
]
]
]
|
5dbd7aa5d1564a71403dbdffd280305b6bf77b1f | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/zombie/nspecialfx/src/nspecialfx/nfxtracer_main.cc | 5f85f4101df39fa8cdde71f465adda3f45a3671e | []
| 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 | 774 | cc | #include "precompiled/pchnspecialfx.h"
//------------------------------------------------------------------------------
// nfxtracer_main.cc
// (C) 2006 Conjurer Services, S.A.
//------------------------------------------------------------------------------
#include "nspecialfx/nfxtracer.h"
nNebulaScriptClass(nFXTracer, "nfxobject");
//------------------------------------------------------------------------------
/**
*/
nFXTracer::nFXTracer()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
nFXTracer::~nFXTracer()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
NSCRIPT_INITCMDS_BEGIN(nFXTracer)
NSCRIPT_INITCMDS_END()
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
]
| [
[
[
1,
30
]
]
]
|
da5d9e0fa0ee4e9f1df88e68676e9c05f14de2f6 | cfad0abe8d02cc052bf22997ba2670573563abff | /xkeymacs/keyboardlayout.h | 65ddcd094b3d4bc588c03ad603d01652e452b582 | []
| no_license | kikairoya/xkeymacs | 0b4a2812f044276d9d6eb6589e4f474ae9ec4142 | 420cc0649c990e43fb5f9579321c28df78bdc1f7 | refs/heads/master | 2021-01-17T21:24:07.576264 | 2011-06-08T04:59:59 | 2011-06-08T04:59:59 | 1,858,433 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,851 | h | #ifndef KEYBOARDLAYOUT_H_INCLUDED
#define KEYBOARDLAYOUT_H_INCLUDED
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "profile.h"
#include "key.h"
struct ScanCode
{
BYTE nScanCode;
BYTE nPrefix; // 0x00, 0xE0 or 0xE1 cf. Keyboard Scan Code Specification -- 16
};
struct ScanCodeMapping
{
ScanCode current;
ScanCode original;
};
struct KeyboardLayout
{
ScanCode scancode;
int nBaseControlID;
int nCurrentControlID;
int nToolTipID;
CKey *pBaseKey;
CKey *pCurrentKey;
};
class CKeyboardLayout: public CDialog
{
private:
static KeyboardLayout m_KeyboardLayouts[112];
static ScanCode m_CurrentScanCodeMap[MAX_HKEY_TYPE][4][256];
static ScanCode m_ScanCodeMap[MAX_HKEY_TYPE][4][256];
CToolTipCtrl m_ToolTip;
int GetControlID(const ScanCode scancode, const BOOL bBase);
BYTE PrefixID2Code(int nPrefixID);
int Prefix2ID(BYTE nPrefix);
DWORD GetScanCodeLength(HKEY_TYPE hkeyType);
BOOL ChangedKeyboardLayout(HKEY_TYPE hkeyType);
protected:
HKEY_TYPE m_HkeyType;
void InitKeyboardLayout();
void CKeyboardLayout::DestroyKeyboardLayout();
BOOL GetScanCodeMap(HKEY_TYPE hkeyType, ScanCode original, ScanCode *current);
int GetBaseControlID(const ScanCode scancode);
int GetCurrentControlID(const ScanCode scancode);
int LostKeyWarning(HKEY_TYPE hkeyType);
void SaveScanCodeMap(HKEY_TYPE hkeyType);
void LoadScanCodeMap(HKEY_TYPE hkeyType);
public:
CToolTipCtrl *ToolTip();
KeyboardLayout *GetKeyboardLayout(int nKey, BOOL bBase = FALSE);
void SetScanCodeMap(HKEY_TYPE hkeyType, ScanCodeMapping mapping);
int GetPointedKey(const CPoint point);
virtual int GetToolTipID(int nToolTipID);
CKeyboardLayout(const HKEY_TYPE hkey_type, UINT nIDTemplate, CWnd* pParentWnd = NULL);
virtual ~CKeyboardLayout();
};
#endif // KEYBOARDLAYOUT_H_INCLUDED
| [
"[email protected]"
]
| [
[
[
1,
65
]
]
]
|
8d16e184b628899542c92fb991fb4dc4a335a425 | 15f5ea95f75eebb643a9fa4d31592b2537a33030 | /src/re167/SceneManager.h | 9cd2cf0025be7ce1cd61544bfb116bcdba96971b | []
| no_license | festus-onboard/graphics | 90aaf323e188b205661889db2c9ac59ed43bfaa7 | fdd195cd758ef95147d2d02160062d2014e50e04 | refs/heads/master | 2021-05-26T14:38:54.088062 | 2009-05-10T16:59:28 | 2009-05-10T16:59:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,533 | h | #ifndef __SceneManager_h__
#define __SceneManager_h__
#include "RE167_global.h"
#include "Camera.h"
#include "Object.h"
#include "RenderContext.h"
#include <list>
#include "Light.h"
#include "FirstPersonCamera.h"
namespace RE167 {
/** This class provides an abstraction of a scene. It manages a camera,
objects in the scene, etc. It is the main interface for applications
to the rendering engine.
*/
class RE167_EXPORT SceneManager
{
public:
SceneManager();
~SceneManager();
/** This method creates a default camera.
*/
Camera *createCamera();
/** This method creates an object and adds it to the list of object
stored in the scene manager.
*/
Object *createObject();
bool canCreateLight();
/**
* This method creates a light and adds it to the list of light objects
* stored in the scene manager
*/
Light *createLight();
/** This method needs to be called in the renderSceneEvent
event handler of the RenderWidget.
@remarks
You should *not* call this anywhere else in your code except in
the renderScene event handler of your RenderWidget. To trigger
rendering, call updateScene of your RenderWidget, which will then
trigger the renderScene event handler to be called.
*/
void renderScene();
private:
Camera *mCamera;
std::list<Object*> mObjectList;
std::list<Light*> mLightList;
static const unsigned int MAX_NUM_LIGHTS = 8;
};
}
#endifß | [
"[email protected]"
]
| [
[
[
1,
62
]
]
]
|
3e2efebeacd5bb2fee4f1ea65cfc48f1ce6d775a | 6a5e7c071f6f62c92f1dcedb8489edda371023fd | /DC/dc.cpp | 4305b73dbbb242dc839945a207a29f9c61f9e55c | []
| no_license | hzhua/oiprogram | 3ba80cf984682a7213f54e6d61cd3e5cbf6492f9 | ca3e2c0e34446db28cb7200a40802647c09a42b3 | refs/heads/master | 2021-03-12T23:00:10.811539 | 2009-05-09T09:43:41 | 2009-05-09T09:43:41 | 125,700 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,130 | cpp | #define maxn 1000001
#include<stdio.h>
int wa[maxn],wb[maxn],wv[maxn],ws[maxn];
int cmp(int *r,int a,int b,int l)
{return r[a]==r[b]&&r[a+l]==r[b+l];}
void print(int *arr,int n)
{
for(int i=0;i<=n;i++)printf("%d ",arr[i]);
printf("\n");
}
void da(int *r,int *sa,int n,int m)
{
int i,j,p,*x=wa,*y=wb,*t;
for(i=0;i<m;i++) ws[i]=0;
for(i=0;i<n;i++) ws[x[i]=r[i]]++;
for(i=1;i<m;i++) ws[i]+=ws[i-1];
for(i=n-1;i>=0;i--) sa[--ws[x[i]]]=i;
for(j=1,p=1;p<n;j*=2,m=p)
{
for(p=0,i=n-j;i<n;i++) y[p++]=i;
print(y,n-1);
for(i=0;i<n;i++) if(sa[i]>=j) y[p++]=sa[i]-j;
print(y,n-1);
for(i=0;i<n;i++) wv[i]=x[y[i]];
for(i=0;i<m;i++) ws[i]=0;
for(i=0;i<n;i++) ws[wv[i]]++;
for(i=1;i<m;i++) ws[i]+=ws[i-1];
for(i=n-1;i>=0;i--) sa[--ws[wv[i]]]=y[i];
print(sa,n-1);
for(t=x,x=y,y=t,p=1,x[sa[0]]=0,i=1;i<n;i++)
x[sa[i]]=cmp(y,sa[i-1],sa[i],j)?p-1:p++;
}
return;
}
int main()
{
int sa[100];
int r[100]={4,6,1,7,3,2};
da(r,sa,6,8);
for(int i=0;i<6;i++)
printf("%d ",sa[i]);
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
43
]
]
]
|
ab7ee4d34d185b7299a701ccdf0cc59f7581da0f | e98d99816ad42028e5988ade802ffdf9846da166 | /Mediotic/mediObjVolumeCreationStrategy.cpp | 784152ada3b4f07b5d41548ef0a79d9954a01697 | []
| no_license | OpenEngineDK/extensions-MediPhysics | 5e9b3a0d178db8e9a42ce7724ee35fdfee70ec64 | 94fdd25f90608ad3db6b3c6a30db1c1e4c490987 | refs/heads/master | 2016-09-14T04:26:29.607457 | 2008-10-14T12:14:53 | 2008-10-14T12:14:53 | 58,073,189 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,709 | cpp | #include "OBJLoader/ObjLoader.h"
#include "mediObjVolumeCreationStrategy.h"
#include "BVH/bvh.h"
#include "BVH/BVHRay.h"
#include "BVH/BVHBoundingSphere.h"
#include "BVH/BVHTriangle.h"
#include "mediVerletODESolver.h"
mediObjVolumeCreationStrategy::mediObjVolumeCreationStrategy(void)
{
}
mediObjVolumeCreationStrategy::~mediObjVolumeCreationStrategy(void)
{
}
mediObjVolumeCreationStrategy::mediObjVolumeCreationStrategy(std::string filename,const Vector3 resolutions)
: resolutions(resolutions)
{
obj = ObjLoader(filename.c_str());
}
void mediObjVolumeCreationStrategy::process(std::vector<mediParticle> & particles )
{
BVH<BVHBoundingSphere> bvh = BVH<BVHBoundingSphere>();
for(unsigned int i=0; i<obj.f.size(); i++)
{
bvh.insert( BVHTriangle(0, obj.v[obj.f[i].v[0]-1], obj.v[obj.f[i].v[1]-1], obj.v[obj.f[i].v[2]-1]));
}
bvh.buildHierarchy();
std::cout << "BVH hierarchy build" << std::endl;
Vector3 minV, maxV;
obj.boundingBox(minV,maxV);
/*for(int x=0; x<resolutions[0]; x++)
for( int y=0; y<resolutions[1]; y++)
for( int z=0; z<resolutions[2]; z++)
{
Vector3 v( (1-(float(x)/resolutions[0]))*minV[0]+(float(x)/resolutions[0])*maxV[0],
(1-(float(y)/resolutions[1]))*minV[1]+(float(y)/resolutions[1])*maxV[1],
(1-(float(z)/resolutions[2]))*minV[2]+(float(z)/resolutions[2])*maxV[2]);
particles.push_back(mediParticle(v));
}*/
for(int x=0; x<resolutions[0]; x++)
for( int y=0; y<resolutions[1]; y++)
{
Vector3 orig( (1-(float(x)/resolutions[0]))*minV[0]+(float(x)/resolutions[0])*maxV[0],
(1-(float(y)/resolutions[1]))*minV[1]+(float(y)/resolutions[1])*maxV[1],
minV[2]);
Vector3 dir = Vector3(0,0,1);
float EPS=0.01;
BVHTriangleHit hit1 = bvh.rayIntersection(BVHRay(orig,dir));
while(hit1.distance!=std::numeric_limits<float>::infinity())
{
particles.push_back(mediParticle(orig+ (dir*hit1.distance)));
BVHTriangleHit hit2 = bvh.rayIntersection(BVHRay(orig+dir*(hit1.distance+EPS),dir));
if (hit2.distance!=std::numeric_limits<float>::infinity())
{
particles.push_back(mediParticle(orig+ dir*(hit1.distance+EPS) + dir*(hit2.distance)));
float d =0;
while( d<hit2.distance)
{
d=d + (maxV[2]-minV[2])/resolutions[2];
particles.push_back(mediParticle(orig + dir*(hit1.distance+EPS+d) ));
}
}
else
{
std::cerr << "Geometry not closed" << std::endl;
//exit(0);
}
orig = orig + dir*(hit1.distance+EPS) + dir*(hit2.distance+EPS); // new orig at end of solid part
hit1 = bvh.rayIntersection(BVHRay(orig,dir));
}
}
}
| [
"[email protected]"
]
| [
[
[
1,
92
]
]
]
|
e52456c0201441a533890613479064a7c73fa6cd | 8bbbcc2bd210d5608613c5c591a4c0025ac1f06b | /nes/mapper/023.cpp | fa09c6004f60ad3b686cf6d139d75045d6704124 | []
| no_license | PSP-Archive/NesterJ-takka | 140786083b1676aaf91d608882e5f3aaa4d2c53d | 41c90388a777c63c731beb185e924820ffd05f93 | refs/heads/master | 2023-04-16T11:36:56.127438 | 2008-12-07T01:39:17 | 2008-12-07T01:39:17 | 357,617,280 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,622 | cpp |
/////////////////////////////////////////////////////////////////////
// Mapper 23
void NES_mapper23_Init()
{
g_NESmapper.Reset = NES_mapper23_Reset;
g_NESmapper.MemoryWrite = NES_mapper23_MemoryWrite;
g_NESmapper.HSync = NES_mapper23_HSync;
}
void NES_mapper23_Reset()
{
g_NESmapper.Mapper23.patch = 0xFFFF;
if(NES_crc32() == 0x93794634) // Akumajou Special - Boku Dracula Kun
{
g_NESmapper.Mapper23.patch = 0xF00C;
}
// set CPU bank pointers
g_NESmapper.set_CPU_banks4(0,1,g_NESmapper.num_8k_ROM_banks-2,g_NESmapper.num_8k_ROM_banks-1);
// set PPU bank pointers
g_NESmapper.set_PPU_banks8(0,1,2,3,4,5,6,7);
g_NESmapper.Mapper23.regs[0] = 0;
g_NESmapper.Mapper23.regs[1] = 1;
g_NESmapper.Mapper23.regs[2] = 2;
g_NESmapper.Mapper23.regs[3] = 3;
g_NESmapper.Mapper23.regs[4] = 4;
g_NESmapper.Mapper23.regs[5] = 5;
g_NESmapper.Mapper23.regs[6] = 6;
g_NESmapper.Mapper23.regs[7] = 7;
g_NESmapper.Mapper23.regs[8] = 0;
g_NESmapper.Mapper23.irq_enabled = 0;
g_NESmapper.Mapper23.irq_counter = 0;
g_NESmapper.Mapper23.irq_latch = 0;
}
void NES_mapper23_MemoryWrite(uint32 addr, uint8 data)
{
// g_NESmapper.Mapper23.regs[0] ... 1K VROM bank at PPU $0000
// g_NESmapper.Mapper23.regs[1] ... 1K VROM bank at PPU $0400
// g_NESmapper.Mapper23.regs[2] ... 1K VROM bank at PPU $0800
// g_NESmapper.Mapper23.regs[3] ... 1K VROM bank at PPU $0C00
// g_NESmapper.Mapper23.regs[4] ... 1K VROM bank at PPU $1000
// g_NESmapper.Mapper23.regs[5] ... 1K VROM bank at PPU $1400
// g_NESmapper.Mapper23.regs[6] ... 1K VROM bank at PPU $1800
// g_NESmapper.Mapper23.regs[7] ... 1K VROM bank at PPU $1C00
// g_NESmapper.Mapper23.regs[8] ... $9008 swap
switch(addr & g_NESmapper.Mapper23.patch)
{
case 0x8000:
case 0x8004:
case 0x8008:
case 0x800C:
{
if(g_NESmapper.Mapper23.regs[8])
{
g_NESmapper.set_CPU_bank6(data);
}
else
{
g_NESmapper.set_CPU_bank4(data);
}
}
break;
case 0x9000:
{
if(data != 0xFF)
{
data &= 0x03;
if(data == 0)
{
g_NESmapper.set_mirroring2(NES_PPU_MIRROR_VERT);
}
else if(data == 1)
{
g_NESmapper.set_mirroring2(NES_PPU_MIRROR_HORIZ);
}
else if(data == 2)
{
g_NESmapper.set_mirroring(0,0,0,0);
}
else
{
g_NESmapper.set_mirroring(1,1,1,1);
}
}
}
break;
case 0x9008:
{
g_NESmapper.Mapper23.regs[8] = data & 0x02;
}
break;
case 0xA000:
case 0xA004:
case 0xA008:
case 0xA00C:
{
g_NESmapper.set_CPU_bank5(data);
}
break;
case 0xB000:
{
g_NESmapper.Mapper23.regs[0] = (g_NESmapper.Mapper23.regs[0] & 0xF0) | (data & 0x0F);
g_NESmapper.set_PPU_bank0(g_NESmapper.Mapper23.regs[0]);
}
break;
case 0xB001:
case 0xB004:
{
g_NESmapper.Mapper23.regs[0] = (g_NESmapper.Mapper23.regs[0] & 0x0F) | ((data & 0x0F) << 4);
g_NESmapper.set_PPU_bank0(g_NESmapper.Mapper23.regs[0]);
}
break;
case 0xB002:
case 0xB008:
{
g_NESmapper.Mapper23.regs[1] = (g_NESmapper.Mapper23.regs[1] & 0xF0) | (data & 0x0F);
g_NESmapper.set_PPU_bank1(g_NESmapper.Mapper23.regs[1]);
}
break;
case 0xB003:
case 0xB00C:
{
g_NESmapper.Mapper23.regs[1] = (g_NESmapper.Mapper23.regs[1] & 0x0F) | ((data & 0x0F) << 4);
g_NESmapper.set_PPU_bank1(g_NESmapper.Mapper23.regs[1]);
}
break;
case 0xC000:
{
g_NESmapper.Mapper23.regs[2] = (g_NESmapper.Mapper23.regs[2] & 0xF0) | (data & 0x0F);
g_NESmapper.set_PPU_bank2(g_NESmapper.Mapper23.regs[2]);
}
break;
case 0xC001:
case 0xC004:
{
g_NESmapper.Mapper23.regs[2] = (g_NESmapper.Mapper23.regs[2] & 0x0F) | ((data & 0x0F) << 4);
g_NESmapper.set_PPU_bank2(g_NESmapper.Mapper23.regs[2]);
}
break;
case 0xC002:
case 0xC008:
{
g_NESmapper.Mapper23.regs[3] = (g_NESmapper.Mapper23.regs[3] & 0xF0) | (data & 0x0F);
g_NESmapper.set_PPU_bank3(g_NESmapper.Mapper23.regs[3]);
}
break;
case 0xC003:
case 0xC00C:
{
g_NESmapper.Mapper23.regs[3] = (g_NESmapper.Mapper23.regs[3] & 0x0F) | ((data & 0x0F) << 4);
g_NESmapper.set_PPU_bank3(g_NESmapper.Mapper23.regs[3]);
}
break;
case 0xD000:
{
g_NESmapper.Mapper23.regs[4] = (g_NESmapper.Mapper23.regs[4] & 0xF0) | (data & 0x0F);
g_NESmapper.set_PPU_bank4(g_NESmapper.Mapper23.regs[4]);
}
break;
case 0xD001:
case 0xD004:
{
g_NESmapper.Mapper23.regs[4] = (g_NESmapper.Mapper23.regs[4] & 0x0F) | ((data & 0x0F) << 4);
g_NESmapper.set_PPU_bank4(g_NESmapper.Mapper23.regs[4]);
}
break;
case 0xD002:
case 0xD008:
{
g_NESmapper.Mapper23.regs[5] = (g_NESmapper.Mapper23.regs[5] & 0xF0) | (data & 0x0F);
g_NESmapper.set_PPU_bank5(g_NESmapper.Mapper23.regs[5]);
}
break;
case 0xD003:
case 0xD00C:
{
g_NESmapper.Mapper23.regs[5] = (g_NESmapper.Mapper23.regs[5] & 0x0F) | ((data & 0x0F) << 4);
g_NESmapper.set_PPU_bank5(g_NESmapper.Mapper23.regs[5]);
}
break;
case 0xE000:
{
g_NESmapper.Mapper23.regs[6] = (g_NESmapper.Mapper23.regs[6] & 0xF0) | (data & 0x0F);
g_NESmapper.set_PPU_bank6(g_NESmapper.Mapper23.regs[6]);
}
break;
case 0xE001:
case 0xE004:
{
g_NESmapper.Mapper23.regs[6] = (g_NESmapper.Mapper23.regs[6] & 0x0F) | ((data & 0x0F) << 4);
g_NESmapper.set_PPU_bank6(g_NESmapper.Mapper23.regs[6]);
}
break;
case 0xE002:
case 0xE008:
{
g_NESmapper.Mapper23.regs[7] = (g_NESmapper.Mapper23.regs[7] & 0xF0) | (data & 0x0F);
g_NESmapper.set_PPU_bank7(g_NESmapper.Mapper23.regs[7]);
}
break;
case 0xE003:
case 0xE00C:
{
g_NESmapper.Mapper23.regs[7] = (g_NESmapper.Mapper23.regs[7] & 0x0F) | ((data & 0x0F) << 4);
g_NESmapper.set_PPU_bank7(g_NESmapper.Mapper23.regs[7]);
}
break;
case 0xF000:
{
g_NESmapper.Mapper23.irq_latch = (g_NESmapper.Mapper23.irq_latch & 0xF0) | (data & 0x0F);
}
break;
case 0xF004:
{
g_NESmapper.Mapper23.irq_latch = (g_NESmapper.Mapper23.irq_latch & 0x0F) | ((data & 0x0F) << 4);
}
break;
case 0xF008:
{
g_NESmapper.Mapper23.irq_enabled = data & 0x03;
if(g_NESmapper.Mapper23.irq_enabled & 0x02)
{
g_NESmapper.Mapper23.irq_counter = g_NESmapper.Mapper23.irq_latch;
}
}
break;
case 0xF00C:
{
g_NESmapper.Mapper23.irq_enabled = (g_NESmapper.Mapper23.irq_enabled & 0x01) * 3;
}
break;
}
}
void NES_mapper23_HSync(uint32 scanline)
{
if(g_NESmapper.Mapper23.irq_enabled & 0x02)
{
if(g_NESmapper.Mapper23.irq_counter == 0xFF)
{
NES6502_DoIRQ();
g_NESmapper.Mapper23.irq_counter = g_NESmapper.Mapper23.irq_latch;
g_NESmapper.Mapper23.irq_enabled = (g_NESmapper.Mapper23.irq_enabled & 0x01) * 3;
}
else
{
g_NESmapper.Mapper23.irq_counter++;
}
}
}
#define MAP23_VROM(ptr) (((ptr)-NES_ROM_get_VROM_banks()) >> 10)
void NES_mapper23_SNSS_fixup()
{
g_NESmapper.Mapper23.regs[0] = MAP23_VROM(g_PPU.PPU_VRAM_banks[0]);
g_NESmapper.Mapper23.regs[1] = MAP23_VROM(g_PPU.PPU_VRAM_banks[1]);
g_NESmapper.Mapper23.regs[2] = MAP23_VROM(g_PPU.PPU_VRAM_banks[2]);
g_NESmapper.Mapper23.regs[3] = MAP23_VROM(g_PPU.PPU_VRAM_banks[3]);
g_NESmapper.Mapper23.regs[4] = MAP23_VROM(g_PPU.PPU_VRAM_banks[4]);
g_NESmapper.Mapper23.regs[5] = MAP23_VROM(g_PPU.PPU_VRAM_banks[5]);
g_NESmapper.Mapper23.regs[6] = MAP23_VROM(g_PPU.PPU_VRAM_banks[6]);
g_NESmapper.Mapper23.regs[7] = MAP23_VROM(g_PPU.PPU_VRAM_banks[7]);
}
/////////////////////////////////////////////////////////////////////
| [
"takka@e750ed6d-7236-0410-a570-cc313d6b6496"
]
| [
[
[
1,
296
]
]
]
|
b93ab2bc6f0c9f351894f3badc23c5bf43c2909c | 2b32433353652d705e5558e7c2d5de8b9fbf8fc3 | /Dm_new_idz/Mlita/GenerationDlg.h | 26edc72b2f7556527a486310791de7d3294c55d0 | []
| no_license | smarthaert/d-edit | 70865143db2946dd29a4ff52cb36e85d18965be3 | 41d069236748c6e77a5a457280846a300d38e080 | refs/heads/master | 2020-04-23T12:21:51.180517 | 2011-01-30T00:37:18 | 2011-01-30T00:37:18 | 35,532,200 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,390 | h | #if !defined(AFX_GENERATIONDLG_H__FE88604E_7D5B_42BA_BD3D_25D2869D1C98__INCLUDED_)
#define AFX_GENERATIONDLG_H__FE88604E_7D5B_42BA_BD3D_25D2869D1C98__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// GenerationDlg.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CGenerationDlg dialog
class CGenerationDlg : public CDialog
{
// Construction
public:
CGenerationDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(CGenerationDlg)
enum { IDD = IDD_GENERATION };
UINT m_Tops;
UINT m_Edges;
BOOL m_Bounds;
BOOL m_Oriented;
BOOL m_Fluidized;
BOOL m_Positive;
BOOL m_HasCycles;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CGenerationDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CGenerationDlg)
// NOTE: the ClassWizard will add member functions here
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
private:
long* m_Graph;
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_GENERATIONDLG_H__FE88604E_7D5B_42BA_BD3D_25D2869D1C98__INCLUDED_)
| [
"[email protected]"
]
| [
[
[
1,
54
]
]
]
|
79e706aad42b9d23d32ff684dfa6b2dc8209a999 | 2e3a8213535db5e3557487aa4bf2ef26fb5385b6 | /calcusdlg.cpp | 2e64096f6a19caebbbac4367f8a5aea4b8a0d6b8 | []
| no_license | silvansky/Calcus | 85aecf653eb18060d84f9d55ebbe547bc6b8ab09 | a8b0597ef711ca50bc680ba18c11d7194a23772e | refs/heads/master | 2021-01-01T17:21:38.065226 | 2011-11-25T11:34:21 | 2011-11-25T11:34:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,518 | cpp | #include "calcusdlg.h"
#include "ui_calcusdlg.h"
#include <QScriptEngine>
#include <QLabel>
#include <QFrame>
#include <QKeyEvent>
#include <QTextDocument>
#include <QScrollBar>
#include "mathwrappers.h"
#include <QDebug>
QScriptValue printToLog(QScriptContext* sc, QScriptEngine* se)
{
QStringList str;
for (int i = 0; i < sc->argumentCount(); i++)
str << sc->argument(i).toString();
CalcusDlg::log->append(str.join(" "));
CalcusDlg::instance->showLog();
QTextCursor c = CalcusDlg::log->textCursor();
c.movePosition(QTextCursor::End);
CalcusDlg::log->setTextCursor(c);
return se->undefinedValue();
}
LogOutput * CalcusDlg::log = NULL;
QDockWidget * CalcusDlg::logDock = NULL;
CalcusDlg * CalcusDlg::instance = NULL;
CalcusDlg::CalcusDlg(QWidget *parent) :
QDialog(parent),
ui(new Ui::CalcusDlg)
{
ui->setupUi(this);
ui->expr->installEventFilter(this);
exprHistoryIndex = -1;
ui->expr->setFocus();
if (!log)
{
log = ui->log;
log->setWindowTitle("Calcus Output");
connect(this, SIGNAL(rejected()), log, SLOT(close()));
QFont monospaceFont("Monospace", 9);
monospaceFont.setStyleHint(QFont::TypeWriter);
log->setFont(monospaceFont);
}
if (!instance)
{
instance = this;
}
if (!logDock)
{
logDock = ui->logDock;
connect(logDock, SIGNAL(visibilityChanged(bool)), SLOT(dockVisibilityChanged(bool)));
}
logDock->hide();
}
CalcusDlg::~CalcusDlg()
{
delete ui;
}
void CalcusDlg::changeEvent(QEvent *e)
{
QDialog::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
bool CalcusDlg::eventFilter(QObject * obj, QEvent * evt)
{
if (obj == ui->expr && evt->type() == QEvent::KeyPress)
{
QKeyEvent * keyEvent = dynamic_cast<QKeyEvent*>(evt);
if (keyEvent)
{
switch(keyEvent->key())
{
case Qt::Key_Up:
if (exprHistoryIndex == -1)
{
// outside history
if (!ui->expr->text().isEmpty())
exprHistory.append(ui->expr->text());
exprHistoryIndex = exprHistory.count() - 1;
if (exprHistoryIndex >= 0)
ui->expr->setText(exprHistory[exprHistoryIndex]);
}
else
{
exprHistoryIndex--;
if (exprHistoryIndex >= 0)
ui->expr->setText(exprHistory[exprHistoryIndex]);
else
exprHistoryIndex = 0;
}
break;
case Qt::Key_Down:
if (exprHistoryIndex != -1)
{
exprHistoryIndex++;
if (exprHistoryIndex < exprHistory.count())
ui->expr->setText(exprHistory[exprHistoryIndex]);
else
exprHistoryIndex = exprHistory.count() - 1;
}
break;
case Qt::Key_Return:
case Qt::Key_Enter:
if (!(keyEvent->modifiers() & Qt::ShiftModifier))
{
ui->calc->click();
return true;
}
break;
}
}
}
return QDialog::eventFilter(obj, evt);
}
void CalcusDlg::closeEvent(QCloseEvent * evt)
{
log->close();
QDialog::closeEvent(evt);
}
void CalcusDlg::addTextToHistory(const QString& text, Qt::Alignment align)
{
QTextCursor c = ui->history->textCursor();
c.movePosition(QTextCursor::End);
ui->history->setTextCursor(c);
QTextBlockFormat format;
format.setAlignment(align);
ui->history->textCursor().insertBlock(format);
ui->history->textCursor().insertHtml(text);
ui->history->setTextCursor(c);
ui->history->ensureCursorVisible();
}
void CalcusDlg::addLineToHistory()
{
QTextCursor c = ui->history->textCursor();
c.movePosition(QTextCursor::End);
ui->history->setTextCursor(c);
QTextBlockFormat format;
format.setAlignment(Qt::AlignLeft);
ui->history->textCursor().insertBlock(format);
ui->history->textCursor().insertHtml("<hr>");
ui->history->setTextCursor(c);
ui->history->ensureCursorVisible();
}
void CalcusDlg::showLog()
{
ui->toggleLog->setChecked(true);
}
void CalcusDlg::on_calc_clicked()
{
static QScriptEngine * engine = 0;
if (!engine)
{
engine = new QScriptEngine;
CalcusMath::registerWrappers(engine);
engine->globalObject().setProperty("print", engine->newFunction(printToLog));
engine->evaluate("function hex(n) { return Number(n).toString(16); }");
engine->evaluate("function bin(n) { return Number(n).toString(2); }");
engine->evaluate("function oct(n) { return Number(n).toString(8); }");
}
QString expr = ui->expr->text();
if (!expr.length())
return;
QScriptValue val = engine->evaluate(expr);
addTextToHistory(Qt::escape(expr), Qt::AlignLeft);
if (engine->hasUncaughtException())
{
addTextToHistory("<font size=+1 color=red><b>" + Qt::escape(val.toString()) + "</b></font>", Qt::AlignLeft);
}
else
{
engine->globalObject().setProperty("result", val);
engine->globalObject().setProperty("res", val);
addTextToHistory("<font size=+2><b>" + Qt::escape(val.toString()) + "</b></font>", Qt::AlignRight);
exprHistory.append(expr);
ui->expr->clear();
exprHistoryIndex = -1;
}
addLineToHistory();
}
void CalcusDlg::exprChanged()
{
if (exprHistoryIndex != -1)
exprHistoryIndex = -1;
}
void CalcusDlg::on_clearLog_clicked()
{
log->clear();
}
void CalcusDlg::on_toggleLog_toggled(bool checked)
{
if (checked)
{
ui->toggleLog->setArrowType(Qt::UpArrow);
ui->logDock->show();
}
else
{
ui->toggleLog->setArrowType(Qt::DownArrow);
ui->logDock->hide();
}
}
void CalcusDlg::dockVisibilityChanged(bool visible)
{
ui->toggleLog->setChecked(visible);
}
| [
"[email protected]"
]
| [
[
[
1,
227
]
]
]
|
295ec35d9b5946692146efbf351b5a1c85da3071 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/graph/detail/adjacency_list.hpp | 5315c95bd2a4e347077854133167cd56da4ba8d6 | [
"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 | 110,215 | hpp | // -*- c++ -*-
//=======================================================================
// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.
// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek
//
// 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)
//=======================================================================
#ifndef BOOST_GRAPH_DETAIL_ADJACENCY_LIST_HPP
#define BOOST_GRAPH_DETAIL_ADJACENCY_LIST_HPP
#include <map> // for vertex_map in copy_impl
#include <boost/config.hpp>
#include <boost/detail/workaround.hpp>
#include <boost/operators.hpp>
#include <boost/property_map.hpp>
#include <boost/pending/integer_range.hpp>
#include <boost/graph/graph_traits.hpp>
#include <memory>
#include <algorithm>
#include <boost/limits.hpp>
#include <boost/iterator/iterator_adaptor.hpp>
#include <boost/pending/ct_if.hpp>
#include <boost/graph/graph_concepts.hpp>
#include <boost/pending/container_traits.hpp>
#include <boost/graph/detail/adj_list_edge_iterator.hpp>
#include <boost/graph/properties.hpp>
#include <boost/pending/property.hpp>
#include <boost/graph/adjacency_iterator.hpp>
#include <boost/static_assert.hpp>
// Symbol truncation problems with MSVC, trying to shorten names.
#define stored_edge se_
#define stored_edge_property sep_
#define stored_edge_iter sei_
/*
Outline for this file:
out_edge_iterator and in_edge_iterator implementation
edge_iterator for undirected graph
stored edge types (these object live in the out-edge/in-edge lists)
directed edges helper class
directed graph helper class
undirected graph helper class
bidirectional graph helper class
bidirectional graph helper class (without edge properties)
bidirectional graph helper class (with edge properties)
adjacency_list helper class
adj_list_impl class
vec_adj_list_impl class
adj_list_gen class
vertex property map
edge property map
Note: it would be nice to merge some of the undirected and
bidirectional code... it is awful similar.
*/
namespace boost {
namespace detail {
template <typename DirectedS>
struct directed_category_traits {
typedef directed_tag directed_category;
};
template <>
struct directed_category_traits<directedS> {
typedef directed_tag directed_category;
};
template <>
struct directed_category_traits<undirectedS> {
typedef undirected_tag directed_category;
};
template <>
struct directed_category_traits<bidirectionalS> {
typedef bidirectional_tag directed_category;
};
template <class Vertex>
struct target_is {
target_is(const Vertex& v) : m_target(v) { }
template <class StoredEdge>
bool operator()(const StoredEdge& e) const {
return e.get_target() == m_target;
}
Vertex m_target;
};
// O(E/V)
template <class EdgeList, class vertex_descriptor>
void erase_from_incidence_list(EdgeList& el, vertex_descriptor v,
allow_parallel_edge_tag)
{
boost::graph_detail::erase_if(el, detail::target_is<vertex_descriptor>(v));
}
// O(log(E/V))
template <class EdgeList, class vertex_descriptor>
void erase_from_incidence_list(EdgeList& el, vertex_descriptor v,
disallow_parallel_edge_tag)
{
typedef typename EdgeList::value_type StoredEdge;
el.erase(StoredEdge(v));
}
//=========================================================================
// Out-Edge and In-Edge Iterator Implementation
template <class BaseIter, class VertexDescriptor, class EdgeDescriptor, class Difference>
struct out_edge_iter
: iterator_adaptor<
out_edge_iter<BaseIter, VertexDescriptor, EdgeDescriptor, Difference>
, BaseIter
, EdgeDescriptor
, use_default
, EdgeDescriptor
, Difference
>
{
typedef iterator_adaptor<
out_edge_iter<BaseIter, VertexDescriptor, EdgeDescriptor, Difference>
, BaseIter
, EdgeDescriptor
, use_default
, EdgeDescriptor
, Difference
> super_t;
inline out_edge_iter() { }
inline out_edge_iter(const BaseIter& i, const VertexDescriptor& src)
: super_t(i), m_src(src) { }
inline EdgeDescriptor
dereference() const
{
return EdgeDescriptor(m_src, (*this->base()).get_target(),
&(*this->base()).get_property());
}
VertexDescriptor m_src;
};
template <class BaseIter, class VertexDescriptor, class EdgeDescriptor, class Difference>
struct in_edge_iter
: iterator_adaptor<
in_edge_iter<BaseIter, VertexDescriptor, EdgeDescriptor, Difference>
, BaseIter
, EdgeDescriptor
, use_default
, EdgeDescriptor
, Difference
>
{
typedef iterator_adaptor<
in_edge_iter<BaseIter, VertexDescriptor, EdgeDescriptor, Difference>
, BaseIter
, EdgeDescriptor
, use_default
, EdgeDescriptor
, Difference
> super_t;
inline in_edge_iter() { }
inline in_edge_iter(const BaseIter& i, const VertexDescriptor& src)
: super_t(i), m_src(src) { }
inline EdgeDescriptor
dereference() const
{
return EdgeDescriptor((*this->base()).get_target(), m_src,
&this->base()->get_property());
}
VertexDescriptor m_src;
};
//=========================================================================
// Undirected Edge Iterator Implementation
template <class EdgeIter, class EdgeDescriptor, class Difference>
struct undirected_edge_iter
: iterator_adaptor<
undirected_edge_iter<EdgeIter, EdgeDescriptor, Difference>
, EdgeIter
, EdgeDescriptor
, use_default
, EdgeDescriptor
, Difference
>
{
typedef iterator_adaptor<
undirected_edge_iter<EdgeIter, EdgeDescriptor, Difference>
, EdgeIter
, EdgeDescriptor
, use_default
, EdgeDescriptor
, Difference
> super_t;
undirected_edge_iter() {}
explicit undirected_edge_iter(EdgeIter i)
: super_t(i) {}
inline EdgeDescriptor
dereference() const {
return EdgeDescriptor(
(*this->base()).m_source
, (*this->base()).m_target
, &this->base()->get_property());
}
};
//=========================================================================
// Edge Storage Types (stored in the out-edge/in-edge lists)
template <class Vertex>
class stored_edge
: public boost::equality_comparable1< stored_edge<Vertex>,
boost::less_than_comparable1< stored_edge<Vertex> > >
{
public:
typedef no_property property_type;
inline stored_edge() { }
inline stored_edge(Vertex target, const no_property& = no_property())
: m_target(target) { }
// Need to write this explicitly so stored_edge_property can
// invoke Base::operator= (at least, for SGI MIPSPro compiler)
inline stored_edge& operator=(const stored_edge& x) {
m_target = x.m_target;
return *this;
}
inline Vertex& get_target() const { return m_target; }
inline const no_property& get_property() const { return s_prop; }
inline bool operator==(const stored_edge& x) const
{ return m_target == x.get_target(); }
inline bool operator<(const stored_edge& x) const
{ return m_target < x.get_target(); }
//protected: need to add hash<> as a friend
static no_property s_prop;
// Sometimes target not used as key in the set, and in that case
// it is ok to change the target.
mutable Vertex m_target;
};
template <class Vertex>
no_property stored_edge<Vertex>::s_prop;
template <class Vertex, class Property>
class stored_edge_property : public stored_edge<Vertex> {
typedef stored_edge_property self;
typedef stored_edge<Vertex> Base;
public:
typedef Property property_type;
inline stored_edge_property() { }
inline stored_edge_property(Vertex target,
const Property& p = Property())
: stored_edge<Vertex>(target), m_property(new Property(p)) { }
stored_edge_property(const self& x)
: Base(x), m_property(const_cast<self&>(x).m_property) { }
self& operator=(const self& x) {
Base::operator=(x);
m_property = const_cast<self&>(x).m_property;
return *this;
}
inline Property& get_property() { return *m_property; }
inline const Property& get_property() const { return *m_property; }
protected:
// Holding the property by-value causes edge-descriptor
// invalidation for add_edge() with EdgeList=vecS. Instead we
// hold a pointer to the property. std::auto_ptr is not
// a perfect fit for the job, but it is darn close.
std::auto_ptr<Property> m_property;
};
template <class Vertex, class Iter, class Property>
class stored_edge_iter
: public stored_edge<Vertex>
{
public:
typedef Property property_type;
inline stored_edge_iter() { }
inline stored_edge_iter(Vertex v)
: stored_edge<Vertex>(v) { }
inline stored_edge_iter(Vertex v, Iter i, void* = 0)
: stored_edge<Vertex>(v), m_iter(i) { }
inline Property& get_property() { return m_iter->get_property(); }
inline const Property& get_property() const {
return m_iter->get_property();
}
inline Iter get_iter() const { return m_iter; }
protected:
Iter m_iter;
};
// For when the EdgeList is a std::vector.
// Want to make the iterator stable, so use an offset
// instead of an iterator into a std::vector
template <class Vertex, class EdgeVec, class Property>
class stored_ra_edge_iter
: public stored_edge<Vertex>
{
typedef typename EdgeVec::iterator Iter;
public:
typedef Property property_type;
inline stored_ra_edge_iter() { }
inline stored_ra_edge_iter(Vertex v, Iter i = Iter(),
EdgeVec* edge_vec = 0)
: stored_edge<Vertex>(v), m_i(i - edge_vec->begin()), m_vec(edge_vec){ }
inline Property& get_property() { return (*m_vec)[m_i].get_property(); }
inline const Property& get_property() const {
return (*m_vec)[m_i].get_property();
}
inline Iter get_iter() const { return m_vec->begin() + m_i; }
protected:
std::size_t m_i;
EdgeVec* m_vec;
};
} // namespace detail
template <class Tag, class Vertex, class Property>
const typename property_value<Property,Tag>::type&
get(Tag property_tag,
const detail::stored_edge_property<Vertex, Property>& e)
{
return get_property_value(e.get_property(), property_tag);
}
template <class Tag, class Vertex, class Iter, class Property>
const typename property_value<Property,Tag>::type&
get(Tag property_tag,
const detail::stored_edge_iter<Vertex, Iter, Property>& e)
{
return get_property_value(e.get_property(), property_tag);
}
template <class Tag, class Vertex, class EdgeVec, class Property>
const typename property_value<Property,Tag>::type&
get(Tag property_tag,
const detail::stored_ra_edge_iter<Vertex, EdgeVec, Property>& e)
{
return get_property_value(e.get_property(), property_tag);
}
//=========================================================================
// Directed Edges Helper Class
namespace detail {
// O(E/V)
template <class edge_descriptor, class EdgeList, class StoredProperty>
inline void
remove_directed_edge_dispatch(edge_descriptor, EdgeList& el,
StoredProperty& p)
{
for (typename EdgeList::iterator i = el.begin();
i != el.end(); ++i)
if (&(*i).get_property() == &p) {
el.erase(i);
return;
}
}
template <class incidence_iterator, class EdgeList, class Predicate>
inline void
remove_directed_edge_if_dispatch(incidence_iterator first,
incidence_iterator last,
EdgeList& el, Predicate pred,
boost::allow_parallel_edge_tag)
{
// remove_if
while (first != last && !pred(*first))
++first;
incidence_iterator i = first;
if (first != last)
for (; i != last; ++i)
if (!pred(*i)) {
*first.base() = *i.base();
++first;
}
el.erase(first.base(), el.end());
}
template <class incidence_iterator, class EdgeList, class Predicate>
inline void
remove_directed_edge_if_dispatch(incidence_iterator first,
incidence_iterator last,
EdgeList& el,
Predicate pred,
boost::disallow_parallel_edge_tag)
{
for (incidence_iterator next = first;
first != last; first = next) {
++next;
if (pred(*first))
el.erase( first.base() );
}
}
template <class PropT, class Graph, class incidence_iterator,
class EdgeList, class Predicate>
inline void
undirected_remove_out_edge_if_dispatch(Graph& g,
incidence_iterator first,
incidence_iterator last,
EdgeList& el, Predicate pred,
boost::allow_parallel_edge_tag)
{
typedef typename Graph::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
// remove_if
while (first != last && !pred(*first))
++first;
incidence_iterator i = first;
bool self_loop_removed = false;
if (first != last)
for (; i != last; ++i) {
if (self_loop_removed) {
/* With self loops, the descriptor will show up
* twice. The first time it will be removed, and now it
* will be skipped.
*/
self_loop_removed = false;
}
else if (!pred(*i)) {
*first.base() = *i.base();
++first;
} else {
if (source(*i, g) == target(*i, g)) self_loop_removed = true;
else {
// Remove the edge from the target
detail::remove_directed_edge_dispatch
(*i,
g.out_edge_list(target(*i, g)),
*(PropT*)(*i).get_property());
}
// Erase the edge property
g.m_edges.erase( (*i.base()).get_iter() );
}
}
el.erase(first.base(), el.end());
}
template <class PropT, class Graph, class incidence_iterator,
class EdgeList, class Predicate>
inline void
undirected_remove_out_edge_if_dispatch(Graph& g,
incidence_iterator first,
incidence_iterator last,
EdgeList& el,
Predicate pred,
boost::disallow_parallel_edge_tag)
{
typedef typename Graph::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
for (incidence_iterator next = first;
first != last; first = next) {
++next;
if (pred(*first)) {
if (source(*first, g) != target(*first, g)) {
// Remove the edge from the target
detail::remove_directed_edge_dispatch
(*first,
g.out_edge_list(target(*first, g)),
*(PropT*)(*first).get_property());
}
// Erase the edge property
g.m_edges.erase( (*first.base()).get_iter() );
// Erase the edge in the source
el.erase( first.base() );
}
}
}
// O(E/V)
template <class edge_descriptor, class EdgeList, class StoredProperty>
inline void
remove_directed_edge_dispatch(edge_descriptor e, EdgeList& el,
no_property&)
{
for (typename EdgeList::iterator i = el.begin();
i != el.end(); ++i)
if ((*i).get_target() == e.m_target) {
el.erase(i);
return;
}
}
} // namespace detail
template <class Config>
struct directed_edges_helper {
// Placement of these overloaded remove_edge() functions
// inside the class avoids a VC++ bug.
// O(E/V)
inline void
remove_edge(typename Config::edge_descriptor e)
{
typedef typename Config::graph_type graph_type;
graph_type& g = static_cast<graph_type&>(*this);
typename Config::OutEdgeList& el = g.out_edge_list(source(e, g));
typedef typename Config::OutEdgeList::value_type::property_type PType;
detail::remove_directed_edge_dispatch(e, el,
*(PType*)e.get_property());
}
// O(1)
inline void
remove_edge(typename Config::out_edge_iterator iter)
{
typedef typename Config::graph_type graph_type;
graph_type& g = static_cast<graph_type&>(*this);
typename Config::edge_descriptor e = *iter;
typename Config::OutEdgeList& el = g.out_edge_list(source(e, g));
el.erase(iter.base());
}
};
// O(1)
template <class Config>
inline std::pair<typename Config::edge_iterator,
typename Config::edge_iterator>
edges(const directed_edges_helper<Config>& g_)
{
typedef typename Config::graph_type graph_type;
typedef typename Config::edge_iterator edge_iterator;
const graph_type& cg = static_cast<const graph_type&>(g_);
graph_type& g = const_cast<graph_type&>(cg);
return std::make_pair( edge_iterator(g.vertex_set().begin(),
g.vertex_set().begin(),
g.vertex_set().end(), g),
edge_iterator(g.vertex_set().begin(),
g.vertex_set().end(),
g.vertex_set().end(), g) );
}
//=========================================================================
// Directed Graph Helper Class
struct adj_list_dir_traversal_tag :
public virtual vertex_list_graph_tag,
public virtual incidence_graph_tag,
public virtual adjacency_graph_tag,
public virtual edge_list_graph_tag { };
template <class Config>
struct directed_graph_helper
: public directed_edges_helper<Config> {
typedef typename Config::edge_descriptor edge_descriptor;
typedef adj_list_dir_traversal_tag traversal_category;
};
// O(E/V)
template <class Config>
inline void
remove_edge(typename Config::vertex_descriptor u,
typename Config::vertex_descriptor v,
directed_graph_helper<Config>& g_)
{
typedef typename Config::graph_type graph_type;
typedef typename Config::edge_parallel_category Cat;
graph_type& g = static_cast<graph_type&>(g_);
detail::erase_from_incidence_list(g.out_edge_list(u), v, Cat());
}
template <class Config, class Predicate>
inline void
remove_out_edge_if(typename Config::vertex_descriptor u, Predicate pred,
directed_graph_helper<Config>& g_)
{
typedef typename Config::graph_type graph_type;
graph_type& g = static_cast<graph_type&>(g_);
typename Config::out_edge_iterator first, last;
tie(first, last) = out_edges(u, g);
typedef typename Config::edge_parallel_category edge_parallel_category;
detail::remove_directed_edge_if_dispatch
(first, last, g.out_edge_list(u), pred, edge_parallel_category());
}
template <class Config, class Predicate>
inline void
remove_edge_if(Predicate pred, directed_graph_helper<Config>& g_)
{
typedef typename Config::graph_type graph_type;
graph_type& g = static_cast<graph_type&>(g_);
typename Config::vertex_iterator vi, vi_end;
for (tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)
remove_out_edge_if(*vi, pred, g);
}
template <class EdgeOrIter, class Config>
inline void
remove_edge(EdgeOrIter e_or_iter, directed_graph_helper<Config>& g_)
{
g_.remove_edge(e_or_iter);
}
// O(V + E) for allow_parallel_edges
// O(V * log(E/V)) for disallow_parallel_edges
template <class Config>
inline void
clear_vertex(typename Config::vertex_descriptor u,
directed_graph_helper<Config>& g_)
{
typedef typename Config::graph_type graph_type;
typedef typename Config::edge_parallel_category Cat;
graph_type& g = static_cast<graph_type&>(g_);
typename Config::vertex_iterator vi, viend;
for (boost::tie(vi, viend) = vertices(g); vi != viend; ++vi)
detail::erase_from_incidence_list(g.out_edge_list(*vi), u, Cat());
g.out_edge_list(u).clear();
// clear() should be a req of Sequence and AssociativeContainer,
// or maybe just Container
}
template <class Config>
inline void
clear_out_edges(typename Config::vertex_descriptor u,
directed_graph_helper<Config>& g_)
{
typedef typename Config::graph_type graph_type;
typedef typename Config::edge_parallel_category Cat;
graph_type& g = static_cast<graph_type&>(g_);
g.out_edge_list(u).clear();
// clear() should be a req of Sequence and AssociativeContainer,
// or maybe just Container
}
// O(V), could do better...
template <class Config>
inline typename Config::edges_size_type
num_edges(const directed_graph_helper<Config>& g_)
{
typedef typename Config::graph_type graph_type;
const graph_type& g = static_cast<const graph_type&>(g_);
typename Config::edges_size_type num_e = 0;
typename Config::vertex_iterator vi, vi_end;
for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)
num_e += out_degree(*vi, g);
return num_e;
}
// O(1) for allow_parallel_edge_tag
// O(log(E/V)) for disallow_parallel_edge_tag
template <class Config>
inline std::pair<typename directed_graph_helper<Config>::edge_descriptor, bool>
add_edge(typename Config::vertex_descriptor u,
typename Config::vertex_descriptor v,
const typename Config::edge_property_type& p,
directed_graph_helper<Config>& g_)
{
typedef typename Config::edge_descriptor edge_descriptor;
typedef typename Config::graph_type graph_type;
typedef typename Config::StoredEdge StoredEdge;
graph_type& g = static_cast<graph_type&>(g_);
typename Config::OutEdgeList::iterator i;
bool inserted;
boost::tie(i, inserted) = boost::graph_detail::push(g.out_edge_list(u),
StoredEdge(v, p));
return std::make_pair(edge_descriptor(u, v, &(*i).get_property()),
inserted);
}
// Did not use default argument here because that
// causes Visual C++ to get confused.
template <class Config>
inline std::pair<typename Config::edge_descriptor, bool>
add_edge(typename Config::vertex_descriptor u,
typename Config::vertex_descriptor v,
directed_graph_helper<Config>& g_)
{
typename Config::edge_property_type p;
return add_edge(u, v, p, g_);
}
//=========================================================================
// Undirected Graph Helper Class
template <class Config>
struct undirected_graph_helper;
struct undir_adj_list_traversal_tag :
public virtual vertex_list_graph_tag,
public virtual incidence_graph_tag,
public virtual adjacency_graph_tag,
public virtual edge_list_graph_tag,
public virtual bidirectional_graph_tag { };
namespace detail {
// using class with specialization for dispatch is a VC++ workaround.
template <class StoredProperty>
struct remove_undirected_edge_dispatch {
// O(E/V)
template <class edge_descriptor, class Config>
static void
apply(edge_descriptor e,
undirected_graph_helper<Config>& g_,
StoredProperty& p)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Config::graph_type graph_type;
graph_type& g = static_cast<graph_type&>(g_);
typename Config::OutEdgeList& out_el = g.out_edge_list(source(e, g));
typename Config::OutEdgeList::iterator out_i = out_el.begin();
for (; out_i != out_el.end(); ++out_i)
if (&(*out_i).get_property() == &p) {
out_el.erase(out_i);
break;
}
typename Config::OutEdgeList& in_el = g.out_edge_list(target(e, g));
typename Config::OutEdgeList::iterator in_i = in_el.begin();
for (; in_i != in_el.end(); ++in_i)
if (&(*in_i).get_property() == &p) {
g.m_edges.erase((*in_i).get_iter());
in_el.erase(in_i);
return;
}
}
};
template <>
struct remove_undirected_edge_dispatch<no_property> {
// O(E/V)
template <class edge_descriptor, class Config>
static void
apply(edge_descriptor e,
undirected_graph_helper<Config>& g_,
no_property&)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Config::graph_type graph_type;
graph_type& g = static_cast<graph_type&>(g_);
no_property* p = (no_property*)e.get_property();
typename Config::OutEdgeList& out_el = g.out_edge_list(source(e, g));
typename Config::OutEdgeList::iterator out_i = out_el.begin();
for (; out_i != out_el.end(); ++out_i)
if (&(*out_i).get_property() == p) {
out_el.erase(out_i);
break;
}
typename Config::OutEdgeList& in_el = g.out_edge_list(target(e, g));
typename Config::OutEdgeList::iterator in_i = in_el.begin();
for (; in_i != in_el.end(); ++in_i)
if (&(*in_i).get_property() == p) {
g.m_edges.erase((*in_i).get_iter());
in_el.erase(in_i);
return;
}
}
};
// O(E/V)
template <class Graph, class EdgeList, class Vertex>
inline void
remove_edge_and_property(Graph& g, EdgeList& el, Vertex v,
boost::allow_parallel_edge_tag cat)
{
typedef typename Graph::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename EdgeList::value_type StoredEdge;
typename EdgeList::iterator i = el.begin(), end = el.end();
for (; i != end; ++i)
if ((*i).get_target() == v)
g.m_edges.erase((*i).get_iter());
detail::erase_from_incidence_list(el, v, cat);
}
// O(log(E/V))
template <class Graph, class EdgeList, class Vertex>
inline void
remove_edge_and_property(Graph& g, EdgeList& el, Vertex v,
boost::disallow_parallel_edge_tag)
{
typedef typename Graph::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename EdgeList::value_type StoredEdge;
typename EdgeList::iterator i = el.find(StoredEdge(v)), end = el.end();
if (i != end) {
g.m_edges.erase((*i).get_iter());
el.erase(i);
}
}
} // namespace detail
template <class Vertex, class EdgeProperty>
struct list_edge // short name due to VC++ truncation and linker problems
: public boost::detail::edge_base<boost::undirected_tag, Vertex>
{
typedef EdgeProperty property_type;
typedef boost::detail::edge_base<boost::undirected_tag, Vertex> Base;
list_edge(Vertex u, Vertex v, const EdgeProperty& p = EdgeProperty())
: Base(u, v), m_property(p) { }
EdgeProperty& get_property() { return m_property; }
const EdgeProperty& get_property() const { return m_property; }
// the following methods should never be used, but are needed
// to make SGI MIPSpro C++ happy
list_edge() { }
bool operator==(const list_edge&) const { return false; }
bool operator<(const list_edge&) const { return false; }
EdgeProperty m_property;
};
template <class Config>
struct undirected_graph_helper {
typedef undir_adj_list_traversal_tag traversal_category;
// Placement of these overloaded remove_edge() functions
// inside the class avoids a VC++ bug.
// O(E/V)
inline void
remove_edge(typename Config::edge_descriptor e)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Config::OutEdgeList::value_type::property_type PType;
detail::remove_undirected_edge_dispatch<PType>::apply
(e, *this, *(PType*)e.get_property());
}
// O(E/V)
inline void
remove_edge(typename Config::out_edge_iterator iter)
{
this->remove_edge(*iter);
}
};
// Had to make these non-members to avoid accidental instantiation
// on SGI MIPSpro C++
template <class C>
inline typename C::InEdgeList&
in_edge_list(undirected_graph_helper<C>&,
typename C::vertex_descriptor v)
{
typename C::stored_vertex* sv = (typename C::stored_vertex*)v;
return sv->m_out_edges;
}
template <class C>
inline const typename C::InEdgeList&
in_edge_list(const undirected_graph_helper<C>&,
typename C::vertex_descriptor v) {
typename C::stored_vertex* sv = (typename C::stored_vertex*)v;
return sv->m_out_edges;
}
// O(E/V)
template <class EdgeOrIter, class Config>
inline void
remove_edge(EdgeOrIter e, undirected_graph_helper<Config>& g_)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
g_.remove_edge(e);
}
// O(E/V) or O(log(E/V))
template <class Config>
void
remove_edge(typename Config::vertex_descriptor u,
typename Config::vertex_descriptor v,
undirected_graph_helper<Config>& g_)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Config::graph_type graph_type;
graph_type& g = static_cast<graph_type&>(g_);
typedef typename Config::edge_parallel_category Cat;
detail::remove_edge_and_property(g, g.out_edge_list(u), v, Cat());
detail::erase_from_incidence_list(g.out_edge_list(v), u, Cat());
}
template <class Config, class Predicate>
void
remove_out_edge_if(typename Config::vertex_descriptor u, Predicate pred,
undirected_graph_helper<Config>& g_)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Config::graph_type graph_type;
typedef typename Config::OutEdgeList::value_type::property_type PropT;
graph_type& g = static_cast<graph_type&>(g_);
typename Config::out_edge_iterator first, last;
tie(first, last) = out_edges(u, g);
typedef typename Config::edge_parallel_category Cat;
detail::undirected_remove_out_edge_if_dispatch<PropT>
(g, first, last, g.out_edge_list(u), pred, Cat());
}
template <class Config, class Predicate>
void
remove_in_edge_if(typename Config::vertex_descriptor u, Predicate pred,
undirected_graph_helper<Config>& g_)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
remove_out_edge_if(u, pred, g_);
}
// O(E/V * E) or O(log(E/V) * E)
template <class Predicate, class Config>
void
remove_edge_if(Predicate pred, undirected_graph_helper<Config>& g_)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Config::graph_type graph_type;
graph_type& g = static_cast<graph_type&>(g_);
typename Config::edge_iterator ei, ei_end, next;
tie(ei, ei_end) = edges(g);
for (next = ei; ei != ei_end; ei = next) {
++next;
if (pred(*ei))
remove_edge(*ei, g);
}
}
// O(1)
template <class Config>
inline std::pair<typename Config::edge_iterator,
typename Config::edge_iterator>
edges(const undirected_graph_helper<Config>& g_)
{
typedef typename Config::graph_type graph_type;
typedef typename Config::edge_iterator edge_iterator;
const graph_type& cg = static_cast<const graph_type&>(g_);
graph_type& g = const_cast<graph_type&>(cg);
return std::make_pair( edge_iterator(g.m_edges.begin()),
edge_iterator(g.m_edges.end()) );
}
// O(1)
template <class Config>
inline typename Config::edges_size_type
num_edges(const undirected_graph_helper<Config>& g_)
{
typedef typename Config::graph_type graph_type;
const graph_type& g = static_cast<const graph_type&>(g_);
return g.m_edges.size();
}
// O(E/V * E/V)
template <class Config>
inline void
clear_vertex(typename Config::vertex_descriptor u,
undirected_graph_helper<Config>& g_)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Config::graph_type graph_type;
typedef typename Config::edge_parallel_category Cat;
graph_type& g = static_cast<graph_type&>(g_);
typename Config::OutEdgeList& el = g.out_edge_list(u);
typename Config::OutEdgeList::iterator
ei = el.begin(), ei_end = el.end();
for (; ei != ei_end; ++ei) {
detail::erase_from_incidence_list
(g.out_edge_list((*ei).get_target()), u, Cat());
g.m_edges.erase((*ei).get_iter());
}
g.out_edge_list(u).clear();
}
// O(1) for allow_parallel_edge_tag
// O(log(E/V)) for disallow_parallel_edge_tag
template <class Config>
inline std::pair<typename Config::edge_descriptor, bool>
add_edge(typename Config::vertex_descriptor u,
typename Config::vertex_descriptor v,
const typename Config::edge_property_type& p,
undirected_graph_helper<Config>& g_)
{
typedef typename Config::StoredEdge StoredEdge;
typedef typename Config::edge_descriptor edge_descriptor;
typedef typename Config::graph_type graph_type;
graph_type& g = static_cast<graph_type&>(g_);
bool inserted;
typename Config::EdgeContainer::value_type e(u, v, p);
typename Config::EdgeContainer::iterator p_iter
= graph_detail::push(g.m_edges, e).first;
typename Config::OutEdgeList::iterator i;
boost::tie(i, inserted) = boost::graph_detail::push(g.out_edge_list(u),
StoredEdge(v, p_iter, &g.m_edges));
if (inserted) {
boost::graph_detail::push(g.out_edge_list(v), StoredEdge(u, p_iter, &g.m_edges));
return std::make_pair(edge_descriptor(u, v, &p_iter->get_property()),
true);
} else {
g.m_edges.erase(p_iter);
return std::make_pair
(edge_descriptor(u, v, &i->get_iter()->get_property()), false);
}
}
template <class Config>
inline std::pair<typename Config::edge_descriptor, bool>
add_edge(typename Config::vertex_descriptor u,
typename Config::vertex_descriptor v,
undirected_graph_helper<Config>& g_)
{
typename Config::edge_property_type p;
return add_edge(u, v, p, g_);
}
// O(1)
template <class Config>
inline typename Config::degree_size_type
degree(typename Config::vertex_descriptor u,
const undirected_graph_helper<Config>& g_)
{
typedef typename Config::graph_type Graph;
const Graph& g = static_cast<const Graph&>(g_);
return out_degree(u, g);
}
template <class Config>
inline std::pair<typename Config::in_edge_iterator,
typename Config::in_edge_iterator>
in_edges(typename Config::vertex_descriptor u,
const undirected_graph_helper<Config>& g_)
{
typedef typename Config::graph_type Graph;
const Graph& cg = static_cast<const Graph&>(g_);
Graph& g = const_cast<Graph&>(cg);
typedef typename Config::in_edge_iterator in_edge_iterator;
return
std::make_pair(in_edge_iterator(g.out_edge_list(u).begin(), u),
in_edge_iterator(g.out_edge_list(u).end(), u));
}
template <class Config>
inline typename Config::degree_size_type
in_degree(typename Config::vertex_descriptor u,
const undirected_graph_helper<Config>& g_)
{ return degree(u, g_); }
//=========================================================================
// Bidirectional Graph Helper Class
struct bidir_adj_list_traversal_tag :
public virtual vertex_list_graph_tag,
public virtual incidence_graph_tag,
public virtual adjacency_graph_tag,
public virtual edge_list_graph_tag,
public virtual bidirectional_graph_tag { };
template <class Config>
struct bidirectional_graph_helper
: public directed_edges_helper<Config> {
typedef bidir_adj_list_traversal_tag traversal_category;
};
// Had to make these non-members to avoid accidental instantiation
// on SGI MIPSpro C++
template <class C>
inline typename C::InEdgeList&
in_edge_list(bidirectional_graph_helper<C>&,
typename C::vertex_descriptor v)
{
typename C::stored_vertex* sv = (typename C::stored_vertex*)v;
return sv->m_in_edges;
}
template <class C>
inline const typename C::InEdgeList&
in_edge_list(const bidirectional_graph_helper<C>&,
typename C::vertex_descriptor v) {
typename C::stored_vertex* sv = (typename C::stored_vertex*)v;
return sv->m_in_edges;
}
template <class Predicate, class Config>
inline void
remove_edge_if(Predicate pred, bidirectional_graph_helper<Config>& g_)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Config::graph_type graph_type;
graph_type& g = static_cast<graph_type&>(g_);
typename Config::edge_iterator ei, ei_end, next;
tie(ei, ei_end) = edges(g);
for (next = ei; ei != ei_end; ei = next) {
++next;
if (pred(*ei))
remove_edge(*ei, g);
}
}
template <class Config>
inline std::pair<typename Config::in_edge_iterator,
typename Config::in_edge_iterator>
in_edges(typename Config::vertex_descriptor u,
const bidirectional_graph_helper<Config>& g_)
{
typedef typename Config::graph_type graph_type;
const graph_type& cg = static_cast<const graph_type&>(g_);
graph_type& g = const_cast<graph_type&>(cg);
typedef typename Config::in_edge_iterator in_edge_iterator;
return
std::make_pair(in_edge_iterator(in_edge_list(g, u).begin(), u),
in_edge_iterator(in_edge_list(g, u).end(), u));
}
// O(1)
template <class Config>
inline std::pair<typename Config::edge_iterator,
typename Config::edge_iterator>
edges(const bidirectional_graph_helper<Config>& g_)
{
typedef typename Config::graph_type graph_type;
typedef typename Config::edge_iterator edge_iterator;
const graph_type& cg = static_cast<const graph_type&>(g_);
graph_type& g = const_cast<graph_type&>(cg);
return std::make_pair( edge_iterator(g.m_edges.begin()),
edge_iterator(g.m_edges.end()) );
}
//=========================================================================
// Bidirectional Graph Helper Class (with edge properties)
template <class Config>
struct bidirectional_graph_helper_with_property
: public bidirectional_graph_helper<Config>
{
typedef typename Config::graph_type graph_type;
typedef typename Config::out_edge_iterator out_edge_iterator;
std::pair<out_edge_iterator, out_edge_iterator>
get_parallel_edge_sublist(typename Config::edge_descriptor e,
const graph_type& g,
void*)
{ return out_edges(source(e, g), g); }
std::pair<out_edge_iterator, out_edge_iterator>
get_parallel_edge_sublist(typename Config::edge_descriptor e,
const graph_type& g,
setS*)
{ return edge_range(source(e, g), target(e, g), g); }
std::pair<out_edge_iterator, out_edge_iterator>
get_parallel_edge_sublist(typename Config::edge_descriptor e,
const graph_type& g,
multisetS*)
{ return edge_range(source(e, g), target(e, g), g); }
#if !defined BOOST_NO_HASH
std::pair<out_edge_iterator, out_edge_iterator>
get_parallel_edge_sublist(typename Config::edge_descriptor e,
const graph_type& g,
hash_setS*)
{ return edge_range(source(e, g), target(e, g), g); }
#endif
// Placement of these overloaded remove_edge() functions
// inside the class avoids a VC++ bug.
// O(E/V) or O(log(E/V))
void
remove_edge(typename Config::edge_descriptor e)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
graph_type& g = static_cast<graph_type&>(*this);
typedef typename Config::edgelist_selector OutEdgeListS;
std::pair<out_edge_iterator, out_edge_iterator> rng =
get_parallel_edge_sublist(e, g, (OutEdgeListS*)(0));
rng.first = std::find(rng.first, rng.second, e);
assert(rng.first != rng.second);
remove_edge(rng.first);
}
inline void
remove_edge(typename Config::out_edge_iterator iter)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Config::graph_type graph_type;
graph_type& g = static_cast<graph_type&>(*this);
typename Config::edge_descriptor e = *iter;
typename Config::OutEdgeList& oel = g.out_edge_list(source(e, g));
typename Config::InEdgeList& iel = in_edge_list(g, target(e, g));
typedef typename Config::OutEdgeList::value_type::property_type PType;
PType& p = *(PType*)e.get_property();
detail::remove_directed_edge_dispatch(*iter, iel, p);
g.m_edges.erase(iter.base()->get_iter());
oel.erase(iter.base());
}
};
// O(E/V) for allow_parallel_edge_tag
// O(log(E/V)) for disallow_parallel_edge_tag
template <class Config>
inline void
remove_edge(typename Config::vertex_descriptor u,
typename Config::vertex_descriptor v,
bidirectional_graph_helper_with_property<Config>& g_)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Config::graph_type graph_type;
graph_type& g = static_cast<graph_type&>(g_);
typedef typename Config::edge_parallel_category Cat;
detail::remove_edge_and_property(g, g.out_edge_list(u), v, Cat());
detail::erase_from_incidence_list(in_edge_list(g, v), u, Cat());
}
// O(E/V) or O(log(E/V))
template <class EdgeOrIter, class Config>
inline void
remove_edge(EdgeOrIter e,
bidirectional_graph_helper_with_property<Config>& g_)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
g_.remove_edge(e);
}
template <class Config, class Predicate>
inline void
remove_out_edge_if(typename Config::vertex_descriptor u, Predicate pred,
bidirectional_graph_helper_with_property<Config>& g_)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Config::graph_type graph_type;
typedef typename Config::OutEdgeList::value_type::property_type PropT;
graph_type& g = static_cast<graph_type&>(g_);
typedef typename Config::EdgeIter EdgeIter;
typedef std::vector<EdgeIter> Garbage;
Garbage garbage;
// First remove the edges from the targets' in-edge lists and
// from the graph's edge set list.
typename Config::out_edge_iterator out_i, out_end;
for (tie(out_i, out_end) = out_edges(u, g); out_i != out_end; ++out_i)
if (pred(*out_i)) {
detail::remove_directed_edge_dispatch
(*out_i, in_edge_list(g, target(*out_i, g)),
*(PropT*)(*out_i).get_property());
// Put in garbage to delete later. Will need the properties
// for the remove_if of the out-edges.
garbage.push_back((*out_i.base()).get_iter());
}
// Now remove the edges from this out-edge list.
typename Config::out_edge_iterator first, last;
tie(first, last) = out_edges(u, g);
typedef typename Config::edge_parallel_category Cat;
detail::remove_directed_edge_if_dispatch
(first, last, g.out_edge_list(u), pred, Cat());
// Now delete the edge properties from the g.m_edges list
for (typename Garbage::iterator i = garbage.begin();
i != garbage.end(); ++i)
g.m_edges.erase(*i);
}
template <class Config, class Predicate>
inline void
remove_in_edge_if(typename Config::vertex_descriptor v, Predicate pred,
bidirectional_graph_helper_with_property<Config>& g_)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Config::graph_type graph_type;
typedef typename Config::OutEdgeList::value_type::property_type PropT;
graph_type& g = static_cast<graph_type&>(g_);
typedef typename Config::EdgeIter EdgeIter;
typedef std::vector<EdgeIter> Garbage;
Garbage garbage;
// First remove the edges from the sources' out-edge lists and
// from the graph's edge set list.
typename Config::in_edge_iterator in_i, in_end;
for (tie(in_i, in_end) = in_edges(v, g); in_i != in_end; ++in_i)
if (pred(*in_i)) {
typename Config::vertex_descriptor u = source(*in_i, g);
detail::remove_directed_edge_dispatch
(*in_i, g.out_edge_list(u), *(PropT*)(*in_i).get_property());
// Put in garbage to delete later. Will need the properties
// for the remove_if of the out-edges.
garbage.push_back((*in_i.base()).get_iter());
}
// Now remove the edges from this in-edge list.
typename Config::in_edge_iterator first, last;
tie(first, last) = in_edges(v, g);
typedef typename Config::edge_parallel_category Cat;
detail::remove_directed_edge_if_dispatch
(first, last, in_edge_list(g, v), pred, Cat());
// Now delete the edge properties from the g.m_edges list
for (typename Garbage::iterator i = garbage.begin();
i != garbage.end(); ++i)
g.m_edges.erase(*i);
}
// O(1)
template <class Config>
inline typename Config::edges_size_type
num_edges(const bidirectional_graph_helper_with_property<Config>& g_)
{
typedef typename Config::graph_type graph_type;
const graph_type& g = static_cast<const graph_type&>(g_);
return g.m_edges.size();
}
// O(E/V * E/V) for allow_parallel_edge_tag
// O(E/V * log(E/V)) for disallow_parallel_edge_tag
template <class Config>
inline void
clear_vertex(typename Config::vertex_descriptor u,
bidirectional_graph_helper_with_property<Config>& g_)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Config::graph_type graph_type;
typedef typename Config::edge_parallel_category Cat;
graph_type& g = static_cast<graph_type&>(g_);
typename Config::OutEdgeList& el = g.out_edge_list(u);
typename Config::OutEdgeList::iterator
ei = el.begin(), ei_end = el.end();
for (; ei != ei_end; ++ei) {
detail::erase_from_incidence_list
(in_edge_list(g, (*ei).get_target()), u, Cat());
g.m_edges.erase((*ei).get_iter());
}
typename Config::InEdgeList& in_el = in_edge_list(g, u);
typename Config::InEdgeList::iterator
in_ei = in_el.begin(), in_ei_end = in_el.end();
for (; in_ei != in_ei_end; ++in_ei) {
detail::erase_from_incidence_list
(g.out_edge_list((*in_ei).get_target()), u, Cat());
g.m_edges.erase((*in_ei).get_iter());
}
g.out_edge_list(u).clear();
in_edge_list(g, u).clear();
}
template <class Config>
inline void
clear_out_edges(typename Config::vertex_descriptor u,
bidirectional_graph_helper_with_property<Config>& g_)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Config::graph_type graph_type;
typedef typename Config::edge_parallel_category Cat;
graph_type& g = static_cast<graph_type&>(g_);
typename Config::OutEdgeList& el = g.out_edge_list(u);
typename Config::OutEdgeList::iterator
ei = el.begin(), ei_end = el.end();
for (; ei != ei_end; ++ei) {
detail::erase_from_incidence_list
(in_edge_list(g, (*ei).get_target()), u, Cat());
g.m_edges.erase((*ei).get_iter());
}
g.out_edge_list(u).clear();
}
template <class Config>
inline void
clear_in_edges(typename Config::vertex_descriptor u,
bidirectional_graph_helper_with_property<Config>& g_)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Config::graph_type graph_type;
typedef typename Config::edge_parallel_category Cat;
graph_type& g = static_cast<graph_type&>(g_);
typename Config::InEdgeList& in_el = in_edge_list(g, u);
typename Config::InEdgeList::iterator
in_ei = in_el.begin(), in_ei_end = in_el.end();
for (; in_ei != in_ei_end; ++in_ei) {
detail::erase_from_incidence_list
(g.out_edge_list((*in_ei).get_target()), u, Cat());
g.m_edges.erase((*in_ei).get_iter());
}
in_edge_list(g, u).clear();
}
// O(1) for allow_parallel_edge_tag
// O(log(E/V)) for disallow_parallel_edge_tag
template <class Config>
inline std::pair<typename Config::edge_descriptor, bool>
add_edge(typename Config::vertex_descriptor u,
typename Config::vertex_descriptor v,
const typename Config::edge_property_type& p,
bidirectional_graph_helper_with_property<Config>& g_)
{
typedef typename Config::graph_type graph_type;
graph_type& g = static_cast<graph_type&>(g_);
typedef typename Config::edge_descriptor edge_descriptor;
typedef typename Config::StoredEdge StoredEdge;
bool inserted;
typename Config::EdgeContainer::value_type e(u, v, p);
typename Config::EdgeContainer::iterator p_iter
= graph_detail::push(g.m_edges, e).first;
typename Config::OutEdgeList::iterator i;
boost::tie(i, inserted) = boost::graph_detail::push(g.out_edge_list(u),
StoredEdge(v, p_iter, &g.m_edges));
if (inserted) {
boost::graph_detail::push(in_edge_list(g, v), StoredEdge(u, p_iter, &g.m_edges));
return std::make_pair(edge_descriptor(u, v, &p_iter->m_property),
true);
} else {
g.m_edges.erase(p_iter);
return std::make_pair(edge_descriptor(u, v,
&i->get_iter()->get_property()),
false);
}
}
template <class Config>
inline std::pair<typename Config::edge_descriptor, bool>
add_edge(typename Config::vertex_descriptor u,
typename Config::vertex_descriptor v,
bidirectional_graph_helper_with_property<Config>& g_)
{
typename Config::edge_property_type p;
return add_edge(u, v, p, g_);
}
// O(1)
template <class Config>
inline typename Config::degree_size_type
degree(typename Config::vertex_descriptor u,
const bidirectional_graph_helper_with_property<Config>& g_)
{
typedef typename Config::graph_type graph_type;
const graph_type& g = static_cast<const graph_type&>(g_);
return in_degree(u, g) + out_degree(u, g);
}
//=========================================================================
// Adjacency List Helper Class
template <class Config, class Base>
struct adj_list_helper : public Base
{
typedef typename Config::graph_type AdjList;
typedef typename Config::vertex_descriptor vertex_descriptor;
typedef typename Config::edge_descriptor edge_descriptor;
typedef typename Config::out_edge_iterator out_edge_iterator;
typedef typename Config::in_edge_iterator in_edge_iterator;
typedef typename Config::adjacency_iterator adjacency_iterator;
typedef typename Config::inv_adjacency_iterator inv_adjacency_iterator;
typedef typename Config::vertex_iterator vertex_iterator;
typedef typename Config::edge_iterator edge_iterator;
typedef typename Config::directed_category directed_category;
typedef typename Config::edge_parallel_category edge_parallel_category;
typedef typename Config::vertices_size_type vertices_size_type;
typedef typename Config::edges_size_type edges_size_type;
typedef typename Config::degree_size_type degree_size_type;
typedef typename Config::StoredEdge StoredEdge;
typedef typename Config::edge_property_type edge_property_type;
typedef typename Config::global_edgelist_selector
global_edgelist_selector;
// protected:
// The edge_dispatch() functions should be static, but
// Borland gets confused about constness.
// O(E/V)
inline std::pair<edge_descriptor,bool>
edge_dispatch(const AdjList& g,
vertex_descriptor u, vertex_descriptor v,
boost::allow_parallel_edge_tag) const
{
bool found;
const typename Config::OutEdgeList& el = g.out_edge_list(u);
typename Config::OutEdgeList::const_iterator
i = std::find_if(el.begin(), el.end(),
detail::target_is<vertex_descriptor>(v));
found = (i != g.out_edge_list(u).end());
if (found)
return std::make_pair(edge_descriptor(u, v, &(*i).get_property()),
true);
else
return std::make_pair(edge_descriptor(u, v, 0), false);
}
// O(log(E/V))
inline std::pair<edge_descriptor,bool>
edge_dispatch(const AdjList& g,
vertex_descriptor u, vertex_descriptor v,
boost::disallow_parallel_edge_tag) const
{
bool found;
/* According to the standard, this should be iterator, not const_iterator,
but the VC++ std::set::find() const returns const_iterator.
And since iterator should be convertible to const_iterator, the
following should work everywhere. -Jeremy */
typename Config::OutEdgeList::const_iterator
i = g.out_edge_list(u).find(StoredEdge(v)),
end = g.out_edge_list(u).end();
found = (i != end);
if (found)
return std::make_pair(edge_descriptor(u, v, &(*i).get_property()),
true);
else
return std::make_pair(edge_descriptor(u, v, 0), false);
}
};
template <class Config, class Base>
inline std::pair<typename Config::adjacency_iterator,
typename Config::adjacency_iterator>
adjacent_vertices(typename Config::vertex_descriptor u,
const adj_list_helper<Config, Base>& g_)
{
typedef typename Config::graph_type AdjList;
const AdjList& cg = static_cast<const AdjList&>(g_);
AdjList& g = const_cast<AdjList&>(cg);
typedef typename Config::adjacency_iterator adjacency_iterator;
typename Config::out_edge_iterator first, last;
boost::tie(first, last) = out_edges(u, g);
return std::make_pair(adjacency_iterator(first, &g),
adjacency_iterator(last, &g));
}
template <class Config, class Base>
inline std::pair<typename Config::inv_adjacency_iterator,
typename Config::inv_adjacency_iterator>
inv_adjacent_vertices(typename Config::vertex_descriptor u,
const adj_list_helper<Config, Base>& g_)
{
typedef typename Config::graph_type AdjList;
const AdjList& cg = static_cast<const AdjList&>(g_);
AdjList& g = const_cast<AdjList&>(cg);
typedef typename Config::inv_adjacency_iterator inv_adjacency_iterator;
typename Config::in_edge_iterator first, last;
boost::tie(first, last) = in_edges(u, g);
return std::make_pair(inv_adjacency_iterator(first, &g),
inv_adjacency_iterator(last, &g));
}
template <class Config, class Base>
inline std::pair<typename Config::out_edge_iterator,
typename Config::out_edge_iterator>
out_edges(typename Config::vertex_descriptor u,
const adj_list_helper<Config, Base>& g_)
{
typedef typename Config::graph_type AdjList;
typedef typename Config::out_edge_iterator out_edge_iterator;
const AdjList& cg = static_cast<const AdjList&>(g_);
AdjList& g = const_cast<AdjList&>(cg);
return
std::make_pair(out_edge_iterator(g.out_edge_list(u).begin(), u),
out_edge_iterator(g.out_edge_list(u).end(), u));
}
template <class Config, class Base>
inline std::pair<typename Config::vertex_iterator,
typename Config::vertex_iterator>
vertices(const adj_list_helper<Config, Base>& g_)
{
typedef typename Config::graph_type AdjList;
const AdjList& cg = static_cast<const AdjList&>(g_);
AdjList& g = const_cast<AdjList&>(cg);
return std::make_pair( g.vertex_set().begin(), g.vertex_set().end() );
}
template <class Config, class Base>
inline typename Config::vertices_size_type
num_vertices(const adj_list_helper<Config, Base>& g_)
{
typedef typename Config::graph_type AdjList;
const AdjList& g = static_cast<const AdjList&>(g_);
return g.vertex_set().size();
}
template <class Config, class Base>
inline typename Config::degree_size_type
out_degree(typename Config::vertex_descriptor u,
const adj_list_helper<Config, Base>& g_)
{
typedef typename Config::graph_type AdjList;
const AdjList& g = static_cast<const AdjList&>(g_);
return g.out_edge_list(u).size();
}
template <class Config, class Base>
inline std::pair<typename Config::edge_descriptor, bool>
edge(typename Config::vertex_descriptor u,
typename Config::vertex_descriptor v,
const adj_list_helper<Config, Base>& g_)
{
typedef typename Config::graph_type Graph;
typedef typename Config::edge_parallel_category Cat;
const Graph& g = static_cast<const Graph&>(g_);
return g_.edge_dispatch(g, u, v, Cat());
}
template <class Config, class Base>
inline std::pair<typename Config::out_edge_iterator,
typename Config::out_edge_iterator>
edge_range(typename Config::vertex_descriptor u,
typename Config::vertex_descriptor v,
const adj_list_helper<Config, Base>& g_)
{
typedef typename Config::graph_type Graph;
typedef typename Config::StoredEdge StoredEdge;
const Graph& cg = static_cast<const Graph&>(g_);
Graph& g = const_cast<Graph&>(cg);
typedef typename Config::out_edge_iterator out_edge_iterator;
typename Config::OutEdgeList& el = g.out_edge_list(u);
typename Config::OutEdgeList::iterator first, last;
typename Config::EdgeContainer fake_edge_container;
tie(first, last) =
std::equal_range(el.begin(), el.end(),
StoredEdge(v, fake_edge_container.end(),
&fake_edge_container));
return std::make_pair(out_edge_iterator(first, u),
out_edge_iterator(last, u));
}
template <class Config>
inline typename Config::degree_size_type
in_degree(typename Config::vertex_descriptor u,
const directed_edges_helper<Config>& g_)
{
typedef typename Config::graph_type Graph;
const Graph& cg = static_cast<const Graph&>(g_);
Graph& g = const_cast<Graph&>(cg);
return in_edge_list(g, u).size();
}
namespace detail {
template <class Config, class Base, class Property>
inline
typename boost::property_map<typename Config::graph_type,
Property>::type
get_dispatch(adj_list_helper<Config,Base>&, Property,
boost::edge_property_tag) {
typedef typename Config::graph_type Graph;
typedef typename boost::property_map<Graph, Property>::type PA;
return PA();
}
template <class Config, class Base, class Property>
inline
typename boost::property_map<typename Config::graph_type,
Property>::const_type
get_dispatch(const adj_list_helper<Config,Base>&, Property,
boost::edge_property_tag) {
typedef typename Config::graph_type Graph;
typedef typename boost::property_map<Graph, Property>::const_type PA;
return PA();
}
template <class Config, class Base, class Property>
inline
typename boost::property_map<typename Config::graph_type,
Property>::type
get_dispatch(adj_list_helper<Config,Base>& g, Property,
boost::vertex_property_tag) {
typedef typename Config::graph_type Graph;
typedef typename boost::property_map<Graph, Property>::type PA;
return PA(&static_cast<Graph&>(g));
}
template <class Config, class Base, class Property>
inline
typename boost::property_map<typename Config::graph_type,
Property>::const_type
get_dispatch(const adj_list_helper<Config, Base>& g, Property,
boost::vertex_property_tag) {
typedef typename Config::graph_type Graph;
typedef typename boost::property_map<Graph, Property>::const_type PA;
const Graph& cg = static_cast<const Graph&>(g);
return PA(&cg);
}
} // namespace detail
// Implementation of the PropertyGraph interface
template <class Config, class Base, class Property>
inline
typename boost::property_map<typename Config::graph_type, Property>::type
get(Property p, adj_list_helper<Config, Base>& g) {
typedef typename property_kind<Property>::type Kind;
return detail::get_dispatch(g, p, Kind());
}
template <class Config, class Base, class Property>
inline
typename boost::property_map<typename Config::graph_type,
Property>::const_type
get(Property p, const adj_list_helper<Config, Base>& g) {
typedef typename property_kind<Property>::type Kind;
return detail::get_dispatch(g, p, Kind());
}
template <class Config, class Base, class Property, class Key>
inline
typename boost::property_traits<
typename boost::property_map<typename Config::graph_type,
Property>::type
>::reference
get(Property p, adj_list_helper<Config, Base>& g, const Key& key) {
return get(get(p, g), key);
}
template <class Config, class Base, class Property, class Key>
inline
typename boost::property_traits<
typename boost::property_map<typename Config::graph_type,
Property>::const_type
>::reference
get(Property p, const adj_list_helper<Config, Base>& g, const Key& key) {
return get(get(p, g), key);
}
template <class Config, class Base, class Property, class Key,class Value>
inline void
put(Property p, adj_list_helper<Config, Base>& g,
const Key& key, const Value& value)
{
typedef typename Config::graph_type Graph;
typedef typename boost::property_map<Graph, Property>::type Map;
Map pmap = get(p, static_cast<Graph&>(g));
put(pmap, key, value);
}
//=========================================================================
// Generalize Adjacency List Implementation
struct adj_list_tag { };
template <class Derived, class Config, class Base>
class adj_list_impl
: public adj_list_helper<Config, Base>
{
typedef typename Config::OutEdgeList OutEdgeList;
typedef typename Config::InEdgeList InEdgeList;
typedef typename Config::StoredVertexList StoredVertexList;
public:
typedef typename Config::stored_vertex stored_vertex;
typedef typename Config::EdgeContainer EdgeContainer;
typedef typename Config::vertex_descriptor vertex_descriptor;
typedef typename Config::edge_descriptor edge_descriptor;
typedef typename Config::vertex_iterator vertex_iterator;
typedef typename Config::edge_iterator edge_iterator;
typedef typename Config::edge_parallel_category edge_parallel_category;
typedef typename Config::vertices_size_type vertices_size_type;
typedef typename Config::edges_size_type edges_size_type;
typedef typename Config::degree_size_type degree_size_type;
typedef typename Config::edge_property_type edge_property_type;
typedef adj_list_tag graph_tag;
static vertex_descriptor null_vertex()
{
return 0;
}
inline adj_list_impl() { }
inline adj_list_impl(const adj_list_impl& x) {
copy_impl(x);
}
inline adj_list_impl& operator=(const adj_list_impl& x) {
this->clear();
copy_impl(x);
return *this;
}
inline void clear() {
for (typename StoredVertexList::iterator i = m_vertices.begin();
i != m_vertices.end(); ++i)
delete (stored_vertex*)*i;
m_vertices.clear();
m_edges.clear();
}
inline adj_list_impl(vertices_size_type num_vertices) {
for (vertices_size_type i = 0; i < num_vertices; ++i)
add_vertex(static_cast<Derived&>(*this));
}
template <class EdgeIterator>
inline adj_list_impl(vertices_size_type num_vertices,
EdgeIterator first, EdgeIterator last)
{
vertex_descriptor* v = new vertex_descriptor[num_vertices];
for (vertices_size_type i = 0; i < num_vertices; ++i)
v[i] = add_vertex(static_cast<Derived&>(*this));
while (first != last) {
add_edge(v[(*first).first], v[(*first).second], *this);
++first;
}
delete [] v;
}
template <class EdgeIterator, class EdgePropertyIterator>
inline adj_list_impl(vertices_size_type num_vertices,
EdgeIterator first, EdgeIterator last,
EdgePropertyIterator ep_iter)
{
vertex_descriptor* v = new vertex_descriptor[num_vertices];
for (vertices_size_type i = 0; i < num_vertices; ++i)
v[i] = add_vertex(static_cast<Derived&>(*this));
while (first != last) {
add_edge(v[(*first).first], v[(*first).second], *ep_iter, *this);
++first;
++ep_iter;
}
delete [] v;
}
~adj_list_impl() {
for (typename StoredVertexList::iterator i = m_vertices.begin();
i != m_vertices.end(); ++i)
delete (stored_vertex*)*i;
}
// protected:
inline OutEdgeList& out_edge_list(vertex_descriptor v) {
stored_vertex* sv = (stored_vertex*)v;
return sv->m_out_edges;
}
inline const OutEdgeList& out_edge_list(vertex_descriptor v) const {
stored_vertex* sv = (stored_vertex*)v;
return sv->m_out_edges;
}
inline StoredVertexList& vertex_set() { return m_vertices; }
inline const StoredVertexList& vertex_set() const { return m_vertices; }
inline void copy_impl(const adj_list_impl& x_)
{
const Derived& x = static_cast<const Derived&>(x_);
// Would be better to have a constant time way to get from
// vertices in x to the corresponding vertices in *this.
std::map<stored_vertex*,stored_vertex*> vertex_map;
// Copy the stored vertex objects by adding each vertex
// and copying its property object.
vertex_iterator vi, vi_end;
for (tie(vi, vi_end) = vertices(x); vi != vi_end; ++vi) {
stored_vertex* v = (stored_vertex*)add_vertex(*this);
v->m_property = ((stored_vertex*)*vi)->m_property;
vertex_map[(stored_vertex*)*vi] = v;
}
// Copy the edges by adding each edge and copying its
// property object.
edge_iterator ei, ei_end;
for (tie(ei, ei_end) = edges(x); ei != ei_end; ++ei) {
edge_descriptor e;
bool inserted;
vertex_descriptor s = source(*ei,x), t = target(*ei,x);
tie(e, inserted) = add_edge(vertex_map[(stored_vertex*)s],
vertex_map[(stored_vertex*)t], *this);
*((edge_property_type*)e.m_eproperty)
= *((edge_property_type*)(*ei).m_eproperty);
}
}
typename Config::EdgeContainer m_edges;
StoredVertexList m_vertices;
};
// O(1)
template <class Derived, class Config, class Base>
inline typename Config::vertex_descriptor
add_vertex(adj_list_impl<Derived, Config, Base>& g_)
{
Derived& g = static_cast<Derived&>(g_);
typedef typename Config::stored_vertex stored_vertex;
stored_vertex* v = new stored_vertex;
typename Config::StoredVertexList::iterator pos;
bool inserted;
boost::tie(pos,inserted) = boost::graph_detail::push(g.m_vertices, v);
v->m_position = pos;
return v;
}
// O(1)
template <class Derived, class Config, class Base>
inline typename Config::vertex_descriptor
add_vertex(const typename Config::vertex_property_type& p,
adj_list_impl<Derived, Config, Base>& g_)
{
Derived& g = static_cast<Derived&>(g_);
typedef typename Config::stored_vertex stored_vertex;
stored_vertex* v = new stored_vertex(p);
typename Config::StoredVertexList::iterator pos;
bool inserted;
boost::tie(pos,inserted) = boost::graph_detail::push(g.m_vertices, v);
v->m_position = pos;
return v;
}
// O(1)
template <class Derived, class Config, class Base>
inline void remove_vertex(typename Config::vertex_descriptor u,
adj_list_impl<Derived, Config, Base>& g_)
{
typedef typename Config::stored_vertex stored_vertex;
Derived& g = static_cast<Derived&>(g_);
stored_vertex* su = (stored_vertex*)u;
g.m_vertices.erase(su->m_position);
delete su;
}
// O(V)
template <class Derived, class Config, class Base>
inline typename Config::vertex_descriptor
vertex(typename Config::vertices_size_type n,
const adj_list_impl<Derived, Config, Base>& g_)
{
const Derived& g = static_cast<const Derived&>(g_);
typename Config::vertex_iterator i = vertices(g).first;
while (n--) ++i; // std::advance(i, n); (not VC++ portable)
return *i;
}
//=========================================================================
// Vector-Backbone Adjacency List Implementation
namespace detail {
template <class Graph, class vertex_descriptor>
inline void
remove_vertex_dispatch(Graph& g, vertex_descriptor u,
boost::directed_tag)
{
typedef typename Graph::edge_parallel_category edge_parallel_category;
g.m_vertices.erase(g.m_vertices.begin() + u);
vertex_descriptor V = num_vertices(g);
if (u != V) {
for (vertex_descriptor v = 0; v < V; ++v)
reindex_edge_list(g.out_edge_list(v), u, edge_parallel_category());
}
}
template <class Graph, class vertex_descriptor>
inline void
remove_vertex_dispatch(Graph& g, vertex_descriptor u,
boost::undirected_tag)
{
typedef typename Graph::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Graph::edge_parallel_category edge_parallel_category;
g.m_vertices.erase(g.m_vertices.begin() + u);
vertex_descriptor V = num_vertices(g);
for (vertex_descriptor v = 0; v < V; ++v)
reindex_edge_list(g.out_edge_list(v), u,
edge_parallel_category());
typedef typename Graph::EdgeContainer Container;
typedef typename Container::iterator Iter;
Iter ei = g.m_edges.begin(), ei_end = g.m_edges.end();
for (; ei != ei_end; ++ei) {
if (ei->m_source > u)
--ei->m_source;
if (ei->m_target > u)
--ei->m_target;
}
}
template <class Graph, class vertex_descriptor>
inline void
remove_vertex_dispatch(Graph& g, vertex_descriptor u,
boost::bidirectional_tag)
{
typedef typename Graph::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Graph::edge_parallel_category edge_parallel_category;
g.m_vertices.erase(g.m_vertices.begin() + u);
vertex_descriptor V = num_vertices(g);
vertex_descriptor v;
if (u != V) {
for (v = 0; v < V; ++v)
reindex_edge_list(g.out_edge_list(v), u,
edge_parallel_category());
for (v = 0; v < V; ++v)
reindex_edge_list(in_edge_list(g, v), u,
edge_parallel_category());
typedef typename Graph::EdgeContainer Container;
typedef typename Container::iterator Iter;
Iter ei = g.m_edges.begin(), ei_end = g.m_edges.end();
for (; ei != ei_end; ++ei) {
if (ei->m_source > u)
--ei->m_source;
if (ei->m_target > u)
--ei->m_target;
}
}
}
template <class EdgeList, class vertex_descriptor>
inline void
reindex_edge_list(EdgeList& el, vertex_descriptor u,
boost::allow_parallel_edge_tag)
{
typename EdgeList::iterator ei = el.begin(), e_end = el.end();
for (; ei != e_end; ++ei)
if ((*ei).get_target() > u)
--(*ei).get_target();
}
template <class EdgeList, class vertex_descriptor>
inline void
reindex_edge_list(EdgeList& el, vertex_descriptor u,
boost::disallow_parallel_edge_tag)
{
typename EdgeList::iterator ei = el.begin(), e_end = el.end();
while (ei != e_end) {
typename EdgeList::value_type ce = *ei;
++ei;
if (ce.get_target() > u) {
el.erase(ce);
--ce.get_target();
el.insert(ce);
}
}
}
} // namespace detail
struct vec_adj_list_tag { };
template <class Graph, class Config, class Base>
class vec_adj_list_impl
: public adj_list_helper<Config, Base>
{
typedef typename Config::OutEdgeList OutEdgeList;
typedef typename Config::InEdgeList InEdgeList;
typedef typename Config::StoredVertexList StoredVertexList;
public:
typedef typename Config::vertex_descriptor vertex_descriptor;
typedef typename Config::edge_descriptor edge_descriptor;
typedef typename Config::out_edge_iterator out_edge_iterator;
typedef typename Config::edge_iterator edge_iterator;
typedef typename Config::directed_category directed_category;
typedef typename Config::vertices_size_type vertices_size_type;
typedef typename Config::edges_size_type edges_size_type;
typedef typename Config::degree_size_type degree_size_type;
typedef typename Config::StoredEdge StoredEdge;
typedef typename Config::stored_vertex stored_vertex;
typedef typename Config::EdgeContainer EdgeContainer;
typedef typename Config::edge_property_type edge_property_type;
typedef vec_adj_list_tag graph_tag;
static vertex_descriptor null_vertex()
{
return (std::numeric_limits<vertex_descriptor>::max)();
}
inline vec_adj_list_impl() { }
inline vec_adj_list_impl(const vec_adj_list_impl& x) {
copy_impl(x);
}
inline vec_adj_list_impl& operator=(const vec_adj_list_impl& x) {
this->clear();
copy_impl(x);
return *this;
}
inline void clear() {
m_vertices.clear();
m_edges.clear();
}
inline vec_adj_list_impl(vertices_size_type _num_vertices)
: m_vertices(_num_vertices) { }
template <class EdgeIterator>
inline vec_adj_list_impl(vertices_size_type num_vertices,
EdgeIterator first, EdgeIterator last)
: m_vertices(num_vertices)
{
while (first != last) {
add_edge((*first).first, (*first).second,
static_cast<Graph&>(*this));
++first;
}
}
template <class EdgeIterator, class EdgePropertyIterator>
inline vec_adj_list_impl(vertices_size_type num_vertices,
EdgeIterator first, EdgeIterator last,
EdgePropertyIterator ep_iter)
: m_vertices(num_vertices)
{
while (first != last) {
add_edge((*first).first, (*first).second, *ep_iter,
static_cast<Graph&>(*this));
++first;
++ep_iter;
}
}
// protected:
inline boost::integer_range<vertex_descriptor> vertex_set() const {
return boost::integer_range<vertex_descriptor>(0, m_vertices.size());
}
inline OutEdgeList& out_edge_list(vertex_descriptor v) {
return m_vertices[v].m_out_edges;
}
inline const OutEdgeList& out_edge_list(vertex_descriptor v) const {
return m_vertices[v].m_out_edges;
}
inline void copy_impl(const vec_adj_list_impl& x_)
{
const Graph& x = static_cast<const Graph&>(x_);
// Copy the stored vertex objects by adding each vertex
// and copying its property object.
for (vertices_size_type i = 0; i < num_vertices(x); ++i) {
vertex_descriptor v = add_vertex(*this);
m_vertices[v].m_property = x.m_vertices[i].m_property;
}
// Copy the edges by adding each edge and copying its
// property object.
edge_iterator ei, ei_end;
for (tie(ei, ei_end) = edges(x); ei != ei_end; ++ei) {
edge_descriptor e;
bool inserted;
tie(e, inserted) = add_edge(source(*ei,x), target(*ei,x) , *this);
*((edge_property_type*)e.m_eproperty)
= *((edge_property_type*)(*ei).m_eproperty);
}
}
typename Config::EdgeContainer m_edges;
StoredVertexList m_vertices;
};
// Had to make these non-members to avoid accidental instantiation
// on SGI MIPSpro C++
template <class G, class C, class B>
inline typename C::InEdgeList&
in_edge_list(vec_adj_list_impl<G,C,B>& g,
typename C::vertex_descriptor v) {
return g.m_vertices[v].m_in_edges;
}
template <class G, class C, class B>
inline const typename C::InEdgeList&
in_edge_list(const vec_adj_list_impl<G,C,B>& g,
typename C::vertex_descriptor v) {
return g.m_vertices[v].m_in_edges;
}
// O(1)
template <class Graph, class Config, class Base>
inline typename Config::vertex_descriptor
add_vertex(vec_adj_list_impl<Graph, Config, Base>& g_) {
Graph& g = static_cast<Graph&>(g_);
g.m_vertices.resize(g.m_vertices.size() + 1);
return g.m_vertices.size() - 1;
}
template <class Graph, class Config, class Base>
inline typename Config::vertex_descriptor
add_vertex(const typename Config::vertex_property_type& p,
vec_adj_list_impl<Graph, Config, Base>& g_) {
Graph& g = static_cast<Graph&>(g_);
typedef typename Config::stored_vertex stored_vertex;
g.m_vertices.push_back(stored_vertex(p));
return g.m_vertices.size() - 1;
}
// Here we override the directed_graph_helper add_edge() function
// so that the number of vertices is automatically changed if
// either u or v is greater than the number of vertices.
template <class Graph, class Config, class Base>
inline std::pair<typename Config::edge_descriptor, bool>
add_edge(typename Config::vertex_descriptor u,
typename Config::vertex_descriptor v,
const typename Config::edge_property_type& p,
vec_adj_list_impl<Graph, Config, Base>& g_)
{
BOOST_USING_STD_MAX();
typename Config::vertex_descriptor x = max BOOST_PREVENT_MACRO_SUBSTITUTION(u, v);
if (x >= num_vertices(g_))
g_.m_vertices.resize(x + 1);
adj_list_helper<Config, Base>& g = g_;
return add_edge(u, v, p, g);
}
template <class Graph, class Config, class Base>
inline std::pair<typename Config::edge_descriptor, bool>
add_edge(typename Config::vertex_descriptor u,
typename Config::vertex_descriptor v,
vec_adj_list_impl<Graph, Config, Base>& g_)
{
typename Config::edge_property_type p;
return add_edge(u, v, p, g_);
}
// O(V + E)
template <class Graph, class Config, class Base>
inline void remove_vertex(typename Config::vertex_descriptor v,
vec_adj_list_impl<Graph, Config, Base>& g_)
{
typedef typename Config::directed_category Cat;
Graph& g = static_cast<Graph&>(g_);
detail::remove_vertex_dispatch(g, v, Cat());
}
// O(1)
template <class Graph, class Config, class Base>
inline typename Config::vertex_descriptor
vertex(typename Config::vertices_size_type n,
const vec_adj_list_impl<Graph, Config, Base>&)
{
return n;
}
namespace detail {
//=========================================================================
// Adjacency List Generator
template <class Graph, class VertexListS, class OutEdgeListS,
class DirectedS, class VertexProperty, class EdgeProperty,
class GraphProperty, class EdgeListS>
struct adj_list_gen
{
typedef typename detail::is_random_access<VertexListS>::type
is_rand_access;
typedef typename has_property<EdgeProperty>::type has_edge_property;
typedef typename DirectedS::is_directed_t DirectedT;
typedef typename DirectedS::is_bidir_t BidirectionalT;
struct config
{
typedef OutEdgeListS edgelist_selector;
typedef EdgeListS global_edgelist_selector;
typedef Graph graph_type;
typedef EdgeProperty edge_property_type;
typedef VertexProperty vertex_property_type;
typedef GraphProperty graph_property_type;
typedef std::size_t vertices_size_type;
typedef adjacency_list_traits<OutEdgeListS, VertexListS, DirectedS>
Traits;
typedef typename Traits::directed_category directed_category;
typedef typename Traits::edge_parallel_category edge_parallel_category;
typedef typename Traits::vertex_descriptor vertex_descriptor;
typedef typename Traits::edge_descriptor edge_descriptor;
typedef void* vertex_ptr;
// need to reorganize this to avoid instantiating stuff
// that doesn't get used -JGS
// VertexList and vertex_iterator
typedef typename container_gen<VertexListS,
vertex_ptr>::type SeqVertexList;
typedef boost::integer_range<std::size_t> RandVertexList;
typedef typename boost::ct_if_t<is_rand_access,
RandVertexList, SeqVertexList>::type VertexList;
typedef typename VertexList::iterator vertex_iterator;
// EdgeContainer and StoredEdge
typedef typename container_gen<EdgeListS,
list_edge<vertex_descriptor, EdgeProperty> >::type EdgeContainer;
typedef typename ct_and<DirectedT,
typename ct_not<BidirectionalT>::type >::type on_edge_storage;
typedef typename boost::ct_if_t<on_edge_storage,
std::size_t, typename EdgeContainer::size_type
>::type edges_size_type;
typedef typename EdgeContainer::iterator EdgeIter;
typedef typename detail::is_random_access<EdgeListS>::type is_edge_ra;
typedef typename boost::ct_if_t<on_edge_storage,
stored_edge_property<vertex_descriptor, EdgeProperty>,
typename boost::ct_if_t<is_edge_ra,
stored_ra_edge_iter<vertex_descriptor, EdgeContainer, EdgeProperty>,
stored_edge_iter<vertex_descriptor, EdgeIter, EdgeProperty>
>::type
>::type StoredEdge;
// Adjacency Types
typedef typename container_gen<OutEdgeListS, StoredEdge>::type
OutEdgeList;
typedef typename OutEdgeList::size_type degree_size_type;
typedef typename OutEdgeList::iterator OutEdgeIter;
typedef boost::detail::iterator_traits<OutEdgeIter> OutEdgeIterTraits;
typedef typename OutEdgeIterTraits::iterator_category OutEdgeIterCat;
typedef typename OutEdgeIterTraits::difference_type OutEdgeIterDiff;
typedef out_edge_iter<
OutEdgeIter, vertex_descriptor, edge_descriptor, OutEdgeIterDiff
> out_edge_iterator;
typedef typename adjacency_iterator_generator<graph_type,
vertex_descriptor, out_edge_iterator>::type adjacency_iterator;
typedef OutEdgeList InEdgeList;
typedef OutEdgeIter InEdgeIter;
typedef OutEdgeIterCat InEdgeIterCat;
typedef OutEdgeIterDiff InEdgeIterDiff;
typedef in_edge_iter<
InEdgeIter, vertex_descriptor, edge_descriptor, InEdgeIterDiff
> in_edge_iterator;
typedef typename inv_adjacency_iterator_generator<graph_type,
vertex_descriptor, in_edge_iterator>::type inv_adjacency_iterator;
// Edge Iterator
typedef boost::detail::iterator_traits<EdgeIter> EdgeIterTraits;
typedef typename EdgeIterTraits::iterator_category EdgeIterCat;
typedef typename EdgeIterTraits::difference_type EdgeIterDiff;
typedef undirected_edge_iter<
EdgeIter
, edge_descriptor
, EdgeIterDiff
> UndirectedEdgeIter; // also used for bidirectional
typedef adj_list_edge_iterator<vertex_iterator, out_edge_iterator,
graph_type> DirectedEdgeIter;
typedef typename boost::ct_if_t<on_edge_storage,
DirectedEdgeIter, UndirectedEdgeIter>::type edge_iterator;
// stored_vertex and StoredVertexList
typedef typename container_gen<VertexListS, vertex_ptr>::type
SeqStoredVertexList;
struct seq_stored_vertex {
seq_stored_vertex() { }
seq_stored_vertex(const VertexProperty& p) : m_property(p) { }
OutEdgeList m_out_edges;
VertexProperty m_property;
typename SeqStoredVertexList::iterator m_position;
};
struct bidir_seq_stored_vertex {
bidir_seq_stored_vertex() { }
bidir_seq_stored_vertex(const VertexProperty& p) : m_property(p) { }
OutEdgeList m_out_edges;
InEdgeList m_in_edges;
VertexProperty m_property;
typename SeqStoredVertexList::iterator m_position;
};
struct rand_stored_vertex {
rand_stored_vertex() { }
rand_stored_vertex(const VertexProperty& p) : m_property(p) { }
OutEdgeList m_out_edges;
VertexProperty m_property;
};
struct bidir_rand_stored_vertex {
bidir_rand_stored_vertex() { }
bidir_rand_stored_vertex(const VertexProperty& p) : m_property(p) { }
OutEdgeList m_out_edges;
InEdgeList m_in_edges;
VertexProperty m_property;
};
typedef typename boost::ct_if_t<is_rand_access,
typename boost::ct_if_t<BidirectionalT,
bidir_rand_stored_vertex, rand_stored_vertex>::type,
typename boost::ct_if_t<BidirectionalT,
bidir_seq_stored_vertex, seq_stored_vertex>::type
>::type StoredVertex;
struct stored_vertex : public StoredVertex {
stored_vertex() { }
stored_vertex(const VertexProperty& p) : StoredVertex(p) { }
};
typedef typename container_gen<VertexListS, stored_vertex>::type
RandStoredVertexList;
typedef typename boost::ct_if_t< is_rand_access,
RandStoredVertexList, SeqStoredVertexList>::type StoredVertexList;
}; // end of config
typedef typename boost::ct_if_t<BidirectionalT,
bidirectional_graph_helper_with_property<config>,
typename boost::ct_if_t<DirectedT,
directed_graph_helper<config>,
undirected_graph_helper<config>
>::type
>::type DirectedHelper;
typedef typename boost::ct_if_t<is_rand_access,
vec_adj_list_impl<Graph, config, DirectedHelper>,
adj_list_impl<Graph, config, DirectedHelper>
>::type type;
};
} // namespace detail
//=========================================================================
// Vertex Property Maps
template <class Graph, class ValueType, class Reference, class Tag>
struct adj_list_vertex_property_map
: public boost::put_get_helper<
Reference,
adj_list_vertex_property_map<Graph, ValueType, Reference, Tag>
>
{
typedef typename Graph::stored_vertex StoredVertex;
typedef ValueType value_type;
typedef Reference reference;
typedef typename Graph::vertex_descriptor key_type;
typedef boost::lvalue_property_map_tag category;
inline adj_list_vertex_property_map() { }
inline adj_list_vertex_property_map(const Graph*) { }
inline Reference operator[](key_type v) const {
StoredVertex* sv = (StoredVertex*)v;
return get_property_value(sv->m_property, Tag());
}
inline Reference operator()(key_type v) const {
return this->operator[](v);
}
};
template <class Graph, class Property, class PropRef>
struct adj_list_vertex_all_properties_map
: public boost::put_get_helper<PropRef,
adj_list_vertex_all_properties_map<Graph, Property, PropRef>
>
{
typedef typename Graph::stored_vertex StoredVertex;
typedef Property value_type;
typedef PropRef reference;
typedef typename Graph::vertex_descriptor key_type;
typedef boost::lvalue_property_map_tag category;
inline adj_list_vertex_all_properties_map() { }
inline adj_list_vertex_all_properties_map(const Graph*) { }
inline PropRef operator[](key_type v) const {
StoredVertex* sv = (StoredVertex*)v;
return sv->m_property;
}
inline PropRef operator()(key_type v) const {
return this->operator[](v);
}
};
template <class Graph, class GraphPtr, class ValueType, class Reference,
class Tag>
struct vec_adj_list_vertex_property_map
: public boost::put_get_helper<
Reference,
vec_adj_list_vertex_property_map<Graph,GraphPtr,ValueType,Reference,
Tag>
>
{
typedef ValueType value_type;
typedef Reference reference;
typedef typename boost::graph_traits<Graph>::vertex_descriptor key_type;
typedef boost::lvalue_property_map_tag category;
vec_adj_list_vertex_property_map() { }
vec_adj_list_vertex_property_map(GraphPtr g) : m_g(g) { }
inline Reference operator[](key_type v) const {
return get_property_value(m_g->m_vertices[v].m_property, Tag());
}
inline Reference operator()(key_type v) const {
return this->operator[](v);
}
GraphPtr m_g;
};
template <class Graph, class GraphPtr, class Property, class PropertyRef>
struct vec_adj_list_vertex_all_properties_map
: public boost::put_get_helper<PropertyRef,
vec_adj_list_vertex_all_properties_map<Graph,GraphPtr,Property,
PropertyRef>
>
{
typedef Property value_type;
typedef PropertyRef reference;
typedef typename boost::graph_traits<Graph>::vertex_descriptor key_type;
typedef boost::lvalue_property_map_tag category;
vec_adj_list_vertex_all_properties_map() { }
vec_adj_list_vertex_all_properties_map(GraphPtr g) : m_g(g) { }
inline PropertyRef operator[](key_type v) const {
return m_g->m_vertices[v].m_property;
}
inline PropertyRef operator()(key_type v) const {
return this->operator[](v);
}
GraphPtr m_g;
};
struct adj_list_any_vertex_pa {
template <class Tag, class Graph, class Property>
struct bind_ {
typedef typename property_value<Property, Tag>::type value_type;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef adj_list_vertex_property_map
<Graph, value_type, reference, Tag> type;
typedef adj_list_vertex_property_map
<Graph, value_type, const_reference, Tag> const_type;
};
};
struct adj_list_all_vertex_pa {
template <class Tag, class Graph, class Property>
struct bind_ {
typedef typename Graph::vertex_descriptor Vertex;
typedef adj_list_vertex_all_properties_map<Graph,Property,
Property&> type;
typedef adj_list_vertex_all_properties_map<Graph,Property,
const Property&> const_type;
};
};
template <class Property, class Vertex>
struct vec_adj_list_vertex_id_map
: public boost::put_get_helper<
Vertex, vec_adj_list_vertex_id_map<Property, Vertex>
>
{
typedef Vertex value_type;
typedef Vertex key_type;
typedef Vertex reference;
typedef boost::readable_property_map_tag category;
inline vec_adj_list_vertex_id_map() { }
template <class Graph>
inline vec_adj_list_vertex_id_map(const Graph&) { }
inline value_type operator[](key_type v) const { return v; }
inline value_type operator()(key_type v) const { return v; }
};
struct vec_adj_list_any_vertex_pa {
template <class Tag, class Graph, class Property>
struct bind_ {
typedef typename property_value<Property, Tag>::type value_type;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef vec_adj_list_vertex_property_map
<Graph, Graph*, value_type, reference, Tag> type;
typedef vec_adj_list_vertex_property_map
<Graph, const Graph*, value_type, const_reference, Tag> const_type;
};
};
struct vec_adj_list_id_vertex_pa {
template <class Tag, class Graph, class Property>
struct bind_ {
typedef typename Graph::vertex_descriptor Vertex;
typedef vec_adj_list_vertex_id_map<Property, Vertex> type;
typedef vec_adj_list_vertex_id_map<Property, Vertex> const_type;
};
};
struct vec_adj_list_all_vertex_pa {
template <class Tag, class Graph, class Property>
struct bind_ {
typedef typename Graph::vertex_descriptor Vertex;
typedef vec_adj_list_vertex_all_properties_map
<Graph, Graph*, Property, Property&> type;
typedef vec_adj_list_vertex_all_properties_map
<Graph, const Graph*, Property, const Property&> const_type;
};
};
namespace detail {
template <class Tag>
struct adj_list_choose_vertex_pa_helper {
typedef adj_list_any_vertex_pa type;
};
template <>
struct adj_list_choose_vertex_pa_helper<vertex_all_t> {
typedef adj_list_all_vertex_pa type;
};
template <class Tag, class Graph, class Property>
struct adj_list_choose_vertex_pa {
typedef typename adj_list_choose_vertex_pa_helper<Tag>::type Helper;
typedef typename Helper::template bind_<Tag,Graph,Property> Bind;
typedef typename Bind::type type;
typedef typename Bind::const_type const_type;
};
template <class Tag>
struct vec_adj_list_choose_vertex_pa_helper {
typedef vec_adj_list_any_vertex_pa type;
};
template <>
struct vec_adj_list_choose_vertex_pa_helper<vertex_index_t> {
typedef vec_adj_list_id_vertex_pa type;
};
template <>
struct vec_adj_list_choose_vertex_pa_helper<vertex_all_t> {
typedef vec_adj_list_all_vertex_pa type;
};
template <class Tag, class Graph, class Property>
struct vec_adj_list_choose_vertex_pa {
typedef typename vec_adj_list_choose_vertex_pa_helper<Tag>::type Helper;
typedef typename Helper::template bind_<Tag,Graph,Property> Bind;
typedef typename Bind::type type;
typedef typename Bind::const_type const_type;
};
} // namespace detail
//=========================================================================
// Edge Property Map
template <class Directed, class Value, class Ref, class Vertex,
class Property, class Tag>
struct adj_list_edge_property_map
: public put_get_helper<
Ref,
adj_list_edge_property_map<Directed, Value, Ref, Vertex, Property,
Tag>
>
{
typedef Value value_type;
typedef Ref reference;
typedef detail::edge_desc_impl<Directed, Vertex> key_type;
typedef boost::lvalue_property_map_tag category;
inline Ref operator[](key_type e) const {
Property& p = *(Property*)e.get_property();
return get_property_value(p, Tag());
}
inline Ref operator()(key_type e) const {
return this->operator[](e);
}
};
template <class Directed, class Property, class PropRef, class PropPtr,
class Vertex>
struct adj_list_edge_all_properties_map
: public put_get_helper<PropRef,
adj_list_edge_all_properties_map<Directed, Property, PropRef,
PropPtr, Vertex>
>
{
typedef Property value_type;
typedef PropRef reference;
typedef detail::edge_desc_impl<Directed, Vertex> key_type;
typedef boost::lvalue_property_map_tag category;
inline PropRef operator[](key_type e) const {
return *(PropPtr)e.get_property();
}
inline PropRef operator()(key_type e) const {
return this->operator[](e);
}
};
// Edge Property Maps
namespace detail {
struct adj_list_any_edge_pmap {
template <class Graph, class Property, class Tag>
struct bind_ {
typedef typename property_value<Property,Tag>::type value_type;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef adj_list_edge_property_map
<typename Graph::directed_category, value_type, reference,
typename Graph::vertex_descriptor,Property,Tag> type;
typedef adj_list_edge_property_map
<typename Graph::directed_category, value_type, const_reference,
typename Graph::vertex_descriptor,const Property, Tag> const_type;
};
};
struct adj_list_all_edge_pmap {
template <class Graph, class Property, class Tag>
struct bind_ {
typedef adj_list_edge_all_properties_map
<typename Graph::directed_category, Property, Property&, Property*,
typename Graph::vertex_descriptor> type;
typedef adj_list_edge_all_properties_map
<typename Graph::directed_category, Property, const Property&,
const Property*, typename Graph::vertex_descriptor> const_type;
};
};
template <class Tag>
struct adj_list_choose_edge_pmap_helper {
typedef adj_list_any_edge_pmap type;
};
template <>
struct adj_list_choose_edge_pmap_helper<edge_all_t> {
typedef adj_list_all_edge_pmap type;
};
template <class Tag, class Graph, class Property>
struct adj_list_choose_edge_pmap {
typedef typename adj_list_choose_edge_pmap_helper<Tag>::type Helper;
typedef typename Helper::template bind_<Graph,Property,Tag> Bind;
typedef typename Bind::type type;
typedef typename Bind::const_type const_type;
};
struct adj_list_edge_property_selector {
template <class Graph, class Property, class Tag>
struct bind_ {
typedef adj_list_choose_edge_pmap<Tag,Graph,Property> Choice;
typedef typename Choice::type type;
typedef typename Choice::const_type const_type;
};
};
} // namespace detail
template <>
struct edge_property_selector<adj_list_tag> {
typedef detail::adj_list_edge_property_selector type;
};
template <>
struct edge_property_selector<vec_adj_list_tag> {
typedef detail::adj_list_edge_property_selector type;
};
// Vertex Property Maps
struct adj_list_vertex_property_selector {
template <class Graph, class Property, class Tag>
struct bind_ {
typedef detail::adj_list_choose_vertex_pa<Tag,Graph,Property> Choice;
typedef typename Choice::type type;
typedef typename Choice::const_type const_type;
};
};
template <>
struct vertex_property_selector<adj_list_tag> {
typedef adj_list_vertex_property_selector type;
};
struct vec_adj_list_vertex_property_selector {
template <class Graph, class Property, class Tag>
struct bind_ {
typedef detail::vec_adj_list_choose_vertex_pa<Tag,Graph,Property> Choice;
typedef typename Choice::type type;
typedef typename Choice::const_type const_type;
};
};
template <>
struct vertex_property_selector<vec_adj_list_tag> {
typedef vec_adj_list_vertex_property_selector type;
};
} // namespace boost
#if !defined(BOOST_NO_HASH) && !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
namespace BOOST_STD_EXTENSION_NAMESPACE {
#if BOOST_WORKAROUND( _STLPORT_VERSION, >= 0x500 )
// STLport 5 already defines a hash<void*> specialization.
#else
template <>
struct hash< void* > // Need this when vertex_descriptor=void*
{
std::size_t
operator()(void* v) const { return (std::size_t)v; }
};
#endif
template <typename V>
struct hash< boost::detail::stored_edge<V> >
{
std::size_t
operator()(const boost::detail::stored_edge<V>& e) const
{
return hash<V>()(e.m_target);
}
};
template <typename V, typename P>
struct hash< boost::detail::stored_edge_property <V,P> >
{
std::size_t
operator()(const boost::detail::stored_edge_property<V,P>& e) const
{
return hash<V>()(e.m_target);
}
};
template <typename V, typename I, typename P>
struct hash< boost::detail::stored_edge_iter<V,I, P> >
{
std::size_t
operator()(const boost::detail::stored_edge_iter<V,I,P>& e) const
{
return hash<V>()(e.m_target);
}
};
}
#endif
#undef stored_edge
#undef stored_edge_property
#undef stored_edge_iter
#endif // BOOST_GRAPH_DETAIL_DETAIL_ADJACENCY_LIST_CCT
/*
Implementation Notes:
Many of the public interface functions in this file would have been
more conveniently implemented as inline friend functions.
However there are a few compiler bugs that make that approach
non-portable.
1. g++ inline friend in namespace bug
2. g++ using clause doesn't work with inline friends
3. VC++ doesn't have Koenig lookup
For these reasons, the functions were all written as non-inline free
functions, and static cast was used to convert from the helper
class to the adjacency_list derived class.
Looking back, it might have been better to write out all functions
in terms of the adjacency_list, and then use a tag to dispatch
to the various helpers instead of using inheritance.
*/
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
2832
]
]
]
|
ad5ea032551aa4369c63abc47e1dc8ad9e3ce7fd | d64ed1f7018aac768ddbd04c5b465c860a6e75fa | /FootprintLib.cpp | f33e1fa782dc5c80594da331aa8faa2551866abc | []
| no_license | roc2/archive-freepcb-codeproject | 68aac46d19ac27f9b726ea7246cfc3a4190a0136 | cbd96cd2dc81a86e1df57b86ce540cf7c120c282 | refs/heads/master | 2020-03-25T00:04:22.712387 | 2009-06-13T04:36:32 | 2009-06-13T04:36:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,308 | cpp | // imlementation of classes to manage footprint libraries
//
#include "stdafx.h"
#include "FootprintLib.h"
#include "DlgLog.h"
#include "DlgAddPart.h"
// index one library file
// file_name is just the file name, not the complete path
//
void CFootLibFolder::IndexLib( CString * file_name, CDlgLog * dlog )
{
// see if file_name already exists in index
int n_libs = m_footlib.GetSize();
CString full_path = m_full_path_to_folder + "\\" + *file_name;
int nlib = n_libs;
for( int ilib=0; ilib<n_libs; ilib++ )
{
if( m_footlib[ilib].m_full_path == full_path )
{
// found it
nlib = ilib;
break;
}
}
if( nlib < n_libs )
{
// file has been indexed previously, we are re-indexing it
// remove all previous entries
for( int i=0; i<GetNumFootprints( nlib ); i++ )
m_lib_map.RemoveKey( *GetFootprintName( nlib, i ) );
}
else
{
// new file to be added to index
m_footlib.SetSize( nlib+1 ); // add one to array
m_footlib[nlib].m_file_name = *file_name;
m_footlib[nlib].m_full_path = full_path;
}
// now index the file
int n_footprints = 0;
CStdioFile file;
int err = file.Open( m_footlib[nlib].m_full_path, CFile::modeRead );
if( !err )
ASSERT(0);
CString instr;
int pos = 0;
int last_ih = 0;
int last_if = -1;
while( file.ReadString( instr ) )
{
if( instr.Left(5) == "name:" )
{
// found a footprint
// if there was a previous footprint, save offset to next one
if( last_if != -1 )
m_footlib[nlib].m_foot[last_if].m_next_offset = file.GetPosition();
CString shape_name = instr.Right( instr.GetLength()-5 );
shape_name.Trim();
if( shape_name.Right(1) == "\"" )
shape_name = shape_name.Left( shape_name.GetLength() -1 );
if( shape_name.Left(1) == "\"" )
shape_name = shape_name.Right( shape_name.GetLength() -1 );
shape_name.Trim();
if( n_footprints >= (m_footlib[nlib].m_foot.GetSize()-1) )
m_footlib[nlib].m_foot.SetSize(n_footprints + 100 );
m_footlib[nlib].m_foot[n_footprints].m_name = shape_name;
m_footlib[nlib].m_foot[n_footprints].m_offset = pos;
unsigned int i;
i = (nlib<<24) + pos;
m_lib_map.SetAt( shape_name, (void*)i );
// save indices to this footprint
last_if = n_footprints;
// next
n_footprints++;
}
pos = file.GetPosition();
}
// set next_offset of last footprint to -1
if( last_if != -1 )
m_footlib[nlib].m_foot[last_if].m_next_offset = -1;
// set array sizes
m_footlib[nlib].m_foot.SetSize( n_footprints );
SetExpanded( nlib, FALSE );
file.Close();
m_footlib[nlib].m_indexed = TRUE;
}
// index all of the library files in a folder
//
void CFootLibFolder::IndexAllLibs( CString * full_path, CDlgLog * dlg_log )
{
Clear();
CDlgAddPart dlg;
m_full_path_to_folder = *full_path;
// start looking for library files
CFileFind finder;
if( CHDIR( m_full_path_to_folder ) != 0 )
{
CString mess;
mess.Format( "Unable to open library folder \"%s\"", m_full_path_to_folder );
AfxMessageBox( mess );
}
else
{
// pop up log window
dlg_log->ShowWindow( SW_SHOW );
dlg_log->UpdateWindow();
dlg_log->BringWindowToTop();
BOOL bWorking = finder.FindFile( "*.fpl" );
while (bWorking)
{
bWorking = finder.FindNextFile();
CString fn = finder.GetFileName();
if( !finder.IsDirectory() )
{
// found a library file, index it
CString log_message;
log_message.Format( "Indexing library: \"%s\"\r\n", fn );
dlg_log->AddLine( log_message );
IndexLib( &fn );
}
}
}
finder.Close();
}
// clear all data
//
void CFootLibFolder::Clear()
{
m_footlib.RemoveAll();
m_lib_map.RemoveAll();
m_full_path_to_folder = "";
}
// returns the number of libraries
//
int CFootLibFolder::GetNumLibs()
{
return m_footlib.GetSize();
}
// returns the full path to the folder
//
CString * CFootLibFolder::GetFullPath()
{
return &m_full_path_to_folder;
}
// get info about a footprint
// enter with:
// name = pointer to CString containing footprint name
// prefer_file_path = pointer to preferred file to search
// ilib = pointer to variable to receive library index (or NULL)
// file_name = pointer to CString to receive lib file name (or NULL)
// offset = pointer to variable to receive position of footprint in lib file (or NULL)
// returns FALSE if fails, TRUE if succeeds with:
// *ilib = index into array of libraries
// *file_name = full path to library file
// *offset = offset into library file
//
BOOL CFootLibFolder::GetFootprintInfo( CString * name, CString * prefer_lib_file,
int * ilib, int * ifootprint, CString * file_name,
int * offset, int * next_offset )
{
void * ptr;
int m_ilib;
int m_if = -1;
int m_offset;
BOOL bExists = FALSE;
int prefer_lib_index = -1;
if( prefer_lib_file )
{
// search for preferred folder
for( int il=0; il<m_footlib.GetSize(); il++ )
{
if( m_footlib[il].m_full_path == *prefer_lib_file )
{
prefer_lib_index = il;
// now search for footprint
for( int in=0; in<m_footlib[il].m_foot.GetSize(); in++ )
{
if( m_footlib[il].m_foot[in].m_name == *name )
{
m_ilib = il;
bExists = TRUE;
}
}
if( bExists )
break;
}
if( bExists )
break;
}
}
if( !bExists )
{
// look for any file path
bExists = m_lib_map.Lookup( *name, ptr );
UINT32 pos = (UINT32)ptr;
m_ilib = pos>>24;
}
if( bExists )
{
CString m_file_name = m_footlib[m_ilib].m_full_path;
// search arrays for file
for( int i=0; i<m_footlib[m_ilib].m_foot.GetSize(); i++ )
{
if( m_footlib[m_ilib].m_foot[i].m_name == *name )
{
m_if = i;
break;
}
}
if( m_if == -1 )
ASSERT(0);
// OK
if( ilib )
*ilib = m_ilib;
if( ifootprint )
*ifootprint = m_if;
if( file_name )
*file_name = m_file_name;
if( offset )
*offset = m_footlib[m_ilib].m_foot[m_if].m_offset;
if( next_offset )
*next_offset = m_footlib[m_ilib].m_foot[m_if].m_next_offset;
return TRUE;
}
else
return FALSE;
}
// search for a file name in library
// returns index to file, or -1 if not found
//
int CFootLibFolder::SearchFileName( CString * fn )
{
for( int i=0; i<m_footlib.GetSize(); i++ )
{
if( m_footlib[i].m_full_path == *fn )
return i;
}
return -1; // if file not found
}
// get library file full path
CString * CFootLibFolder::GetLibraryFullPath( int ilib )
{
return &m_footlib[ilib].m_full_path;
}
// get library file name
CString * CFootLibFolder::GetLibraryFileName( int ilib )
{
return &m_footlib[ilib].m_file_name;
}
// get number of footprints under a heading in library file
int CFootLibFolder::GetNumFootprints( int ilib )
{
return m_footlib[ilib].m_foot.GetSize();
}
// get footprint name
CString * CFootLibFolder::GetFootprintName( int ilib, int ifoot )
{
return &m_footlib[ilib].m_foot[ifoot].m_name;
}
// get footprint offset
int CFootLibFolder::GetFootprintOffset( int ilib, int ifoot )
{
return m_footlib[ilib].m_foot[ifoot].m_offset;
}
//********************* class CFootLibFolderMap *************************
//
// constructor
//
CFootLibFolderMap::CFootLibFolderMap()
{
}
// destructor, also destroys all CFootLibFolders in the map
//
CFootLibFolderMap::~CFootLibFolderMap()
{
POSITION pos;
CString name;
void * ptr;
for( pos = m_folder_map.GetStartPosition(); pos != NULL; )
{
m_folder_map.GetNextAssoc( pos, name, ptr );
CFootLibFolder * folder = (CFootLibFolder*)ptr;
if( folder )
{
folder->Clear();
delete folder;
}
}
}
// add CFootLibFolder to map
// if folder == NULL, the folder will be created on the first call to GetFolder
//
void CFootLibFolderMap::AddFolder( CString * full_path, CFootLibFolder * folder )
{
CString str = full_path->MakeLower();
void * ptr;
if( !m_folder_map.Lookup( str, ptr ) )
m_folder_map.SetAt( str, folder );
}
CFootLibFolder * CFootLibFolderMap::GetFolder( CString * full_path, CDlgLog * log )
{
void * ptr;
CFootLibFolder * folder;
CString str = full_path->MakeLower();
if( !m_folder_map.Lookup( str, ptr ) || ptr == NULL )
{
folder = new CFootLibFolder();
CString mess;
mess.Format( "Indexing library folder \"%s\"\r\n", str );
log->AddLine( mess );
folder->IndexAllLibs( &str, log );
log->AddLine( "\r\n" );
m_folder_map.SetAt( str, folder );
log->AddLine( "\r\n" );
}
else
folder = (CFootLibFolder*)ptr;
return folder;
}
BOOL CFootLibFolderMap::FolderIndexed( CString * full_path )
{
void * ptr;
CString str = full_path->MakeLower();
if( m_folder_map.Lookup( str, ptr ) )
return TRUE;
else
return FALSE;
}
void CFootLibFolderMap::SetDefaultFolder( CString * def_full_path )
{
m_default_folder = *def_full_path;
}
void CFootLibFolderMap::SetLastFolder( CString * last_full_path )
{
m_last_folder = *last_full_path;
}
CString * CFootLibFolderMap::GetDefaultFolder()
{
return( &m_default_folder );
}
CString * CFootLibFolderMap::GetLastFolder()
{
if( m_last_folder != "" )
return( &m_last_folder );
else
return( &m_default_folder );
}
| [
"freepcb@9bfb2a70-7351-0410-8a08-c5b0c01ed314",
"jamesdily@9bfb2a70-7351-0410-8a08-c5b0c01ed314"
]
| [
[
[
1,
100
],
[
102,
375
]
],
[
[
101,
101
]
]
]
|
90918bbff70bdc74c0d35120ff5e6d298187e5b2 | 8fcf3f01e46f8933b356f763c61938ab11061a38 | /Interface/sources/Rendering/PointRender.h | 26b3cd22baca4b89cc92dacafd8ea434b82c0187 | []
| no_license | jonesbusy/parser-effex | 9facab7e0ff865d226460a729f6cb1584e8798da | c8c00e7f9cf360c0f70d86d1929ad5b44c5521be | refs/heads/master | 2021-01-01T16:50:16.254785 | 2011-02-26T22:27:05 | 2011-02-26T22:27:05 | 33,957,768 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 2,193 | h | #ifndef POINT_RENDER_H
#define POINT_RENDER_H
/*!
* \file PointRender.h
* \author Pascal Berberat
* \date 14.05.2010
* \version 1.0
*/
#include <QGraphicsScene>
#include <QPainter>
#include <QStyleOptionGraphicsItem>
#include <QPointF>
#include <QRectF>
#include <QPen>
#include "Rendering/FunctionItem.h"
#include "Expression/IExpression.h"
#include "Data/ItemData.h"
#include "Data/MathTools.h"
/*!
* \class PointRender
*
* \brief La classe PointRender permet de représenter graphiquement un point.
*
* Cette classe dessine une ellipse autour d'un point lié à une fonction.
*/
class PointRender : public FunctionItem
{
private:
/*! Point */
QPointF point;
/*! Coordonnée x */
double x;
/*! Largeur */
double width;
/*! Hauteur */
double height;
public:
/*!
* Constructeur
*
* \param function Fonction
* \param x Coordonnée x
* \param data Données de l'élément graphique
* \param scene Scène graphique
*/
PointRender(IExpression* function, double x, const ItemData& data, QGraphicsScene* scene = NULL);
/*!
* Méthode de calcul, elle sera appelée à chaque fois que la scène est
* modifiée.
*
* \note Méthode héritée de FunctionGraphics.
*
* \param bounds Pointeur sur un rectangle contenant les bornes
* \param accuracy Niveau de détails
*/
void compute(QRectF* bounds, int accuracy);
/*!
* Retourne un rectangle représentant la zone à dessiner.
*
* \note Méthode héritée de QGraphicsItem.
*
* \return Rectangle représentant la zone à dessiner
*/
QRectF boundingRect() const;
/*!
* Dessine le point. Cette méthode est appelée indirectement.
*
* \note Méthode héritée de QGraphicsItem.
*
* \param painter Dispositif de dessin
* \param option Options de style
* \param widget Widget
*/
void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget);
};
#endif // POINT_RENDER_H
| [
"jonesbusy@fa255007-c97c-c9ae-ff28-e9f0558300b6"
]
| [
[
[
1,
93
]
]
]
|
d6c27ea3d449bc0a6d19bc8b3ce38a34633ba880 | a35389bfb109a645e3442038d0ed94a7b82182f5 | /src/CmdOpt.cpp | d499a23e5d9b117d2524c06d9c37a7b637a5c8bb | [
"X11",
"MIT"
]
| permissive | mszubart/Find-FireBalls | 91226c67260635aae069c48bd05da04433eb822b | 6df9e179e763cbbc1fad16e883689224c22f0f3b | refs/heads/master | 2021-01-10T19:59:34.647168 | 2011-11-01T16:05:49 | 2011-11-01T16:05:49 | 2,604,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,236 | cpp | /*
* Find FireBalls
* Copyright (c) 2011 Mateusz Szubart
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "cmdopt.hpp"
CmdOptions::CmdOptions(int ac, char* av[]) {
this->_init_options();
this->_parse_options(ac, av);
}
void CmdOptions::_init_options() {
this->_threads_number = CMDOPT_DEFAULT_THREADS_NUMBER;
this->_pyrScale = CMDOPT_DEFAULT_PYR_SCALE;
this->_levels = CMDOPT_DEFAULT_LEVELS;
this->_winsize = CMDOPT_DEFAULT_WINSIZE;
this->_iterations = CMDOPT_DEFAULT_ITERATIONS;
this->_polyN = CMDOPT_DEFAULT_POLYN;
this->_polySigma = CMDOPT_DEFAULT_POLYSIGMA;
this->_use_farneback_gaussian = CMDOPT_DEFAULT_USE_FBGAUSSIAN;
this->_density = CMDOPT_DEFAULT_DENSITY;
this->_min_vector_len = CMDOPT_DEFAULT_MIN_VECT_LEN;
this->_skipframes = CMDOPT_DEFAULT_SKIPFRAMES;
this->_clip_len = COMOPT_DEFAULT_CLIP_LENGTH;
this->_verbose = CMDOPT_DEFAULT_VERBOSE;
this->_blind_bottom = CMDOPT_DEFAULT_BLIND_BOT;
this->_blind_top = CMDOPT_DEFAULT_BLIND_TOP;
this->_blind_left = CMDOPT_DEFAULT_BLIND_LEFT;
this->_blind_right = CMDOPT_DEFAULT_BLIND_RIGHT;
}
void CmdOptions::_parse_options(int ac, char* av[]) {
try {
po::options_description _desc("Some descriptions were taken from OpenCV documentation (http://opencv.itseez.com/modules/refman.html)\nAllowed options:");
_desc.add_options()
("help,h", "Show this message.\n")
("input-file", po::value<std::string > (), "File with video material.\n")
("skipframes,S", po::value<int>(), "Number of frames to be skipped. Every skipframes-th frame will be processed.\nDefault value = 12\n")
("clip-len,L", po::value<int>(), "Single clip length in seconds.\nDefault value = 11\n")
("density", po::value<int>(), "Density of sampling grid - spacing (in pixels) between the samples.\nDefault value = 16\n")
("min-vect-len", po::value<int>(), "Minimal flow vector length to be assumed as movement.\nDefault value = 6\n")
("blind_top", po::value<int>(), "Blind field, from frame edge to arg.\nDefault value = 0\n")
("blind_left", po::value<int>(), "Blind field, from frame edge to arg.\nDefault value = 0\n")
("blind_right", po::value<int>(), "Blind field, from frame edge to arg.\nDefault value = 0\n")
("blind_bottom", po::value<int>(), "Blind field, from frame edge to arg.\nDefault value = 20\n")
("threads,T", po::value<int>(), "Set number of threads used for video processing.\nBest value is 1 thread per core thread (eg. Intel i7 has 4 cores and 8 threads, best value is 8). Warning: Video material is divided for each thread so you need at least 2x video size free hdd space.\nDefault value = 8\n")
("pyr-scale", po::value<double>(), "Parameter specifying the image scale (<1) to build pyramids for each image. \npyrScale=0.5 means a classical pyramid, where each next layer is twice smaller than the previous one.\nDefault value = 0.5\n")
("levels", po::value<int>(), "Number of pyramid layers including the initial image. \nlevels=1 means that no extra layers are created and only the original images are used.\nDefault value = 3\n")
("winsize", po::value<int>(), "Averaging window size. \nLarger values increase the algorithm robustness to image noise and give more chances for fast motion detection, but yield more blurred motion field.\nDefault value = 15\n")
("iterations", po::value<int>(), "Number of iterations the algorithm does at each pyramid level.\nDefault value = 3\n")
("polyn", po::value<int>(), "Size of the pixel neighborhood used to find polynomial expansion in each pixel. \nLarger values mean that the image will be approximated with smoother surfaces, yielding more robust algorithm and more blurred motion field. \nTypically, polyN =5 or 7.\nDefault value = 5\n")
("poly-sigma", po::value<double>(), "Standard deviation of the Gaussian that is used to smooth derivatives used as a basis for the polynomial expansion. \nFor polyN=5 , you can set polySigma=1.1. For polyN=7, a good value would be polySigma=1.5\nDefault value = 1.2\n")
("use-farneback-gaussian,G", "Use the Gaussian filter instead of a box filter of the same size for optical flow estimation. \nUsually, this option gives z more accurate flow than with a box filter, at the cost of lower speed.\nNormally, winsize for a Gaussian window should be set to a larger value to achieve the same level of robustness.\nDefault value = false\n")
("verbose,V", "Be verbose.\nDefault value = false\n")
;
po::positional_options_description p;
p.add("input-file", -1);
po::variables_map _vm;
po::store(po::command_line_parser(ac, av).options(_desc).positional(p).run(), _vm);
po::notify(_vm);
if (_vm.count("help")) {
std::cout << "Usage: ffb input.avi [options]\n";
std::cout << _desc;
exit(EXIT_SUCCESS);
}
if (_vm.count("input-file")) {
this->_input_file = _vm["input-file"].as<std::string > ();
}
else {
std::cerr << "No input file specified.\nUsage: ffb input.avi [options]\n";
std::cout << _desc;
exit(EXIT_FAILURE);
}
if (_vm.count("threads")) {
this->_threads_number = _vm["threads"].as<int>();
if (this->_threads_number < 1) {
std::cerr << "No threads? Really? Give up, 1 thread is minimum...\n";
exit(EXIT_FAILURE);
}
}
if (_vm.count("pyr-scale")) {
this->_pyrScale = _vm["pyr-scale"].as<double>();
}
if (_vm.count("levels")) {
this->_levels = _vm["levels"].as<int>();
}
if (_vm.count("winsize")) {
this->_winsize = _vm["winsize"].as<int>();
}
if (_vm.count("iterations")) {
this->_iterations = _vm["iterations"].as<int>();
}
if (_vm.count("polyn")) {
this->_polyN = _vm["polyn"].as<int>();
}
if (_vm.count("density")) {
this->_density = _vm["density"].as<int>();
}
if (_vm.count("blind_top")) {
this->_blind_top = _vm["blind_top"].as<int>();
}
if (_vm.count("blind_left")) {
this->_blind_top = _vm["blind_top"].as<int>();
}
if (_vm.count("blind_right")) {
this->_blind_right = _vm["blind_right"].as<int>();
}
if (_vm.count("blind_bottom")) {
this->_blind_bottom = _vm["blind_bottom"].as<int>();
}
if (_vm.count("min-vect-len")) {
this->_min_vector_len = _vm["min-vect-len"].as<int>();
}
if (_vm.count("skipframes")) {
this->_skipframes = _vm["skipframes"].as<int>();
}
if (_vm.count("clip-len")) {
this->_clip_len = _vm["clip-len"].as<int>();
}
if (_vm.count("poly-sigma")) {
this->_polySigma = _vm["poly-sigma"].as<double>();
}
if (_vm.count("use-farneback-gaussian")) {
this->_use_farneback_gaussian = true;
}
if (_vm.count("verbose")) {
this->_verbose = true;
}
}
catch (std::exception& e) {
std::cerr << "Error: " << e.what() << "\n";
exit(EXIT_FAILURE);
}
catch (...) {
std::cerr << "Exception of unknown type!\n";
exit(EXIT_FAILURE);
}
}
std::string CmdOptions::get_input_file() const {
return this->_input_file;
}
int CmdOptions::get_threads_number() const {
return this->_threads_number;
}
double CmdOptions::get_pyrScale() const {
return this->_pyrScale;
}
int CmdOptions::get_levels() const {
return this->_levels;
}
int CmdOptions::get_winsize() const {
return this->_winsize;
}
int CmdOptions::get_iterations() const {
return this->_iterations;
}
int CmdOptions::get_polyN() const {
return this->_polyN;
}
double CmdOptions::get_polySigma() const {
return this->_polySigma;
}
bool CmdOptions::will_use_farneback_gaussian() const {
return this->_use_farneback_gaussian;
}
int CmdOptions::get_density() const {
return this->_density;
}
int CmdOptions::get_min_vector_len() const {
return this->_min_vector_len;
}
int CmdOptions::get_skipframes() const {
return this->_skipframes;
}
int CmdOptions::get_clip_len() const {
return this->_clip_len;
}
bool CmdOptions::get_verbose() const {
return this->_verbose;
}
int CmdOptions::get_blind_bottom() const {
return this->_blind_bottom;
}
int CmdOptions::get_blind_top() const {
return this->_blind_top;
}
int CmdOptions::get_blind_left() const {
return this->_blind_left;
}
int CmdOptions::get_blind_right() const {
return this->_blind_right;
}
| [
"[email protected]"
]
| [
[
[
1,
252
]
]
]
|
350ddacef06185b08142ecb83ca06be3429b4065 | 38763b01d06c87ff1164877f57fc22d0da2927e4 | /src/imageb_player/imgproc/acquisition.h | cacf5a8634e6497d6a44a48f182eb350d7c50a5d | []
| no_license | JPSGoncalves/ImageB | 48b31b83bb1c032394c14e1df5ed90e2a285a521 | 135ccb9847f9e3394f2391417885d753a5b3a930 | refs/heads/master | 2023-03-17T03:57:10.299812 | 2011-07-20T16:59:41 | 2011-07-20T16:59:41 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,920 | h | #ifndef ACQUISITION_H
#define ACQUISITION_H
#include "NumMeth.h"
//! A class to represent acquired Data
/*!
This class stores information about acquired data.
*/
class Acquisition
{
public:
//dados sobre transdutor e parametros da aquisicao de dados
//! steer angle (degrees)
float theta; //angulacao de deflexao em graus
//! number of transducer elements
int elements; //numero de elementos do vetor
//! distance between elements (mm)
double d; //distancia entre os elementos
//! sound velocity (m/s)
int c; //velocidade de propagaçao do ultra-som no meio em m/s
//! oscilloscope delay (us)
double delay; //delay do osciloscopio em us
//! sampling rate (MHz)
double samp_rate; //taxa de amostragem
//! frequency represented in time
double deltat; //deltat
//! delay size in number of points
double delay_size; //valor do delay em pontos
//! Matrix that contains RF signal data points
Matrix rf_matrix;
//! signal average
int avg;
Acquisition()
{
theta = 30; //angulacao de deflexao em graus
elements = 12; //numero de elementos do vetor
d = 1.32e-3; //distancia entre os elementos 1,32 milimetros
c = 1480; //velocidade de propagaçao do ultra-som no meio em m/s
delay = 66.6765e-6; //delay do osciloscopio em us
samp_rate = 20e6; //taxa de amostragem 20MHz
deltat = 1/samp_rate; //representação da frequencia no tempo
delay_size = delay/deltat; //calculo do valor do delay em numero de pontos
avg = 1; //número de amostras para efetuar a média do sinal (promediação)
}
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
62
]
]
]
|
c3ce3caa1cd7669ec76e41d920e1283d3d648fa2 | 51ebb9684ac1a4b65a5426e5c9ee79ebf8eb3db8 | /Windows/CmmHdr/boost_regex.h | 9323f7ef1887d38319a9b18d4a212b0e89d1ac1c | []
| no_license | buf1024/lgcbasic | d4dfe6a6bd19e4e4ac0e5ac2b7a0590e04dd5779 | 11db32c9be46d9ac0740429e09ebf880a7a00299 | refs/heads/master | 2021-01-10T12:55:12.046835 | 2011-09-03T15:45:57 | 2011-09-03T15:45:57 | 49,615,513 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 553 | h | ////////////////////////////////////////////////////////////////////////////////////////
//
//
//
// FileName : boost_regex.h
// Purpose : Regular Expresion Service
// Version : 2011-01-15 (16:46) 1.0 Created
// Author : heidong
// Contact : [email protected]
// Copyright(c): HEIDONG
////////////////////////////////////////////////////////////////////////////////////////
#ifndef _BOOST_REGEX_H_
#define _BOOST_REGEX_H_
#include <boost/regex.hpp>
namespace lgc
{
using namespace boost;
}
#endif
| [
"buf1024@10f8a008-2033-b5f4-5ad9-01b5c2a83ee0"
]
| [
[
[
1,
23
]
]
]
|
2bc60b3a672b69587be8b48d52ad4a9c4a318046 | 2acd91cf2dfe87f4c78fba230de2c2ffc90350ea | / salad-bar-in-space-game/edge/bouncibility/third_party/irrklang/include/ik_ISound.h | b340a4777fc68796ec5aba9f42fafd5a7e8a8f6f | []
| no_license | Joshvanburen/salad-bar-in-space-game | 5f410a06be475edee1ab85950c667e6a6f970763 | b23a35c832258f4fc1a921a45ab4238c734ef1f0 | refs/heads/master | 2016-09-01T18:46:29.672326 | 2008-05-07T18:40:30 | 2008-05-07T18:40:30 | 32,195,299 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,971 | h | // Copyright (C) 2002-2007 Nikolaus Gebhardt
// This file is part of the "irrKlang" library.
// For conditions of distribution and use, see copyright notice in irrKlang.h
#ifndef __I_IRRKLANG_SOUND_H_INCLUDED__
#define __I_IRRKLANG_SOUND_H_INCLUDED__
#include "ik_IVirtualRefCounted.h"
#include "ik_ISoundEffectControl.h"
#include "ik_vec3d.h"
namespace irrklang
{
class ISoundSource;
class ISoundStopEventReceiver;
//! Represents a sound which is currently played.
/** The sound can be stopped, its volume or pan changed, effects added/removed
and similar using this interface.
Creating sounds is done using ISoundEngine::play2D() or ISoundEngine::play3D().
More informations about the source of a sound can be obtained from the ISoundSource
interface. */
class ISound : public IVirtualRefCounted
{
public:
//! returns source of the sound which stores the filename and other informations about that sound
/** \return Returns the sound source poitner of this sound. May return 0 if the sound source
has been removed.*/
virtual ISoundSource* getSoundSource() = 0;
//! returns if the sound is paused
virtual void setIsPaused( bool paused = true) = 0;
//! returns if the sound is paused
virtual bool getIsPaused() = 0;
//! Will stop the sound and free its resources.
/** If you just want to pause the sound, use setIsPaused().
After calling stop(), isFinished() will usually return true. */
virtual void stop() = 0;
//! returns volume of the sound, a value between 0 (mute) and 1 (full volume).
/** (this volume gets multiplied with the master volume of the sound engine
and other parameters like distance to listener when played as 3d sound) */
virtual ik_f32 getVolume() = 0;
//! sets the volume of the sound, a value between 0 (mute) and 1 (full volume).
/** This volume gets multiplied with the master volume of the sound engine
and other parameters like distance to listener when played as 3d sound. */
virtual void setVolume(ik_f32 volume) = 0;
//! sets the pan of the sound. Takes a value between -1 and 1, 0 is center.
virtual void setPan(ik_f32 pan) = 0;
//! returns the pan of the sound. Takes a value between -1 and 1, 0 is center.
virtual ik_f32 getPan() = 0;
//! returns if the sound has been started to play looped
virtual bool isLooped() = 0;
//! changes the loop mode of the sound.
/** If the sound is playing looped and it is changed to not-looped, then it
will stop playing after the loop has finished.
If it is not looped and changed to looped, the sound will start repeating to be
played when it reaches its end.
Invoking this method will not have an effect when the sound already has stopped. */
virtual void setIsLooped(bool looped) = 0;
//! returns if the sound has finished playing.
/** Don't mix this up with isPaused(). isFinished() returns if the sound has been
finished playing. If it has, is maybe already have been removed from the playing list of the
sound engine and calls to any other of the methods of ISound will not have any result.
If you call stop() to a playing sound will result that this function will return true
when invoked. */
virtual bool isFinished() = 0;
//! Sets the minimal distance if this is a 3D sound.
/** Changes the distance at which the 3D sound stops getting louder. This works
like this: As a listener approaches a 3D sound source, the sound gets louder.
Past a certain point, it is not reasonable for the volume to continue to increase.
Either the maximum (zero) has been reached, or the nature of the sound source
imposes a logical limit. This is the minimum distance for the sound source.
Similarly, the maximum distance for a sound source is the distance beyond
which the sound does not get any quieter.
The default minimum distance is 1, the default max distance is a huge number like 1000000000.0f. */
virtual void setMinDistance(ik_f32 min) = 0;
//! Returns the minimal distance if this is a 3D sound.
/** See setMinDistance() for details. */
virtual ik_f32 getMinDistance() = 0;
//! Sets the maximal distance if this is a 3D sound.
/** Changing this value is usually not necessary. Use setMinDistance() instead.
Don't change this value if you don't know what you are doing: This value causes the sound
to stop attenuating after it reaches the max distance. Most people think that this sets the
volume of the sound to 0 after this distance, but this is not true. Only change the
minimal distance (using for example setMinDistance()) to influence this.
The maximum distance for a sound source is the distance beyond which the sound does not get any quieter.
The default minimum distance is 1, the default max distance is a huge number like 1000000000.0f. */
virtual void setMaxDistance(ik_f32 max) = 0;
//! Returns the maximal distance if this is a 3D sound.
/** See setMaxDistance() for details. */
virtual ik_f32 getMaxDistance() = 0;
//! sets the position of the sound in 3d space
virtual void setPosition(vec3df position) = 0;
//! returns the position of the sound in 3d space
virtual vec3df getPosition() = 0;
//! sets the position of the sound in 3d space, needed for Doppler effects.
/** To use doppler effects use ISound::setVelocity to set a sounds velocity,
ISoundEngine::setListenerPosition() to set the listeners velocity and
ISoundEngine::setDopplerEffectParameters() to adjust two parameters influencing
the doppler effects intensity. */
virtual void setVelocity(vec3df vel) = 0;
//! returns the velocity of the sound in 3d space, needed for Doppler effects.
/** To use doppler effects use ISound::setVelocity to set a sounds velocity,
ISoundEngine::setListenerPosition() to set the listeners velocity and
ISoundEngine::setDopplerEffectParameters() to adjust two parameters influencing
the doppler effects intensity. */
virtual vec3df getVelocity() = 0;
//! returns the current play position of the sound in milliseconds.
/** \return Returns -1 if not implemented or possible for this sound for example
because it already has been stopped and freed internally or similar. */
virtual ik_u32 getPlayPosition() = 0;
//! sets the current play position of the sound in milliseconds.
/** \param pos Position in milliseconds. Must be between 0 and the value returned
by getPlayPosition().
\return Returns true successful. False is returned for example if the sound already finished
playing and is stopped or the audio source is not seekable, for example if it
is an internet stream or a a file format not supporting seeking (a .MOD file for example).
A file can be tested if it can bee seeking using ISoundSource::getIsSeekingSupported(). */
virtual bool setPlayPosition(ik_u32 pos) = 0;
//! Sets the playback speed (frequency) of the sound.
/** Plays the sound at a higher or lower speed, increasing or decreasing its
frequency which makes it sound lower or higher.
Note that this feature is not available on all sound output drivers (it is on the
DirectSound drivers at least), and it does not work together with the
'enableSoundEffects' parameter of ISoundEngine::play2D and ISoundEngine::play3D when
using DirectSound.
\param speed Factor of the speed increase or decrease. 2 is twice as fast,
0.5 is only half as fast. The default is 1.0.
\return Returns true if sucessful, false if not. The current sound driver might not
support changing the playBack speed, or the sound was started with the
'enableSoundEffects' parameter. */
virtual bool setPlaybackSpeed(ik_f32 speed = 1.0f) = 0;
//! Returns the playback speed set by setPlaybackSpeed(). Default: 1.0f.
/** See setPlaybackSpeed() for details */
virtual ik_f32 getPlaybackSpeed() = 0;
//! returns the play length of the sound in milliseconds.
/** Returns -1 if not known for this sound for example because its decoder
does not support length reporting or it is a file stream of unknown size.
Note: You can also use ISoundSource::getPlayLength() to get the length of
a sound without actually needing to play it. */
virtual ik_u32 getPlayLength() = 0;
//! Returns the sound effect control interface for this sound.
/** Sound effects such as Chorus, Distorsions, Echo, Reverb and similar can
be controlled using this. The interface pointer is only valid as long as the ISound pointer is valid.
If the ISound pointer gets dropped (IVirtualRefCounted::drop()), the ISoundEffects
may not be used any more.
\return Returns a pointer to the sound effects interface if available. The sound
has to be started via ISoundEngine::play2D() or ISoundEngine::play3D(),
with the flag enableSoundEffects=true, otherwise 0 will be returned. Note that
if the output driver does not support sound effects, 0 will be returned as well.*/
virtual ISoundEffectControl* getSoundEffectControl() = 0;
//! Sets the sound stop event receiver, an interface which gets called if a sound has finished playing.
/** This event is guaranteed to be called when the sound or sound stream is finished,
either because the sound reached its playback end, its sound source was removed,
ISoundEngine::stopAllSounds() has been called or the whole engine was deleted.
There is an example on how to use events in irrklang at @ref events .
\param receiver Interface to a user implementation of the sound receiver. This interface
should be as long valid as the sound exists or another stop event receiver is set.
Set this to null to set no sound stop event receiver.
\param userData: A iser data pointer, can be null. */
virtual void setSoundStopEventReceiver(ISoundStopEventReceiver* reciever, void* userData=0) = 0;
};
} // end namespace irrklang
#endif
| [
"[email protected]@1a2710a4-8244-0410-8b66-391840787a9e"
]
| [
[
[
1,
193
]
]
]
|
98fb28f32731e10a68e9983d567cd840e6bc759d | 63d8291850783397b2149b4f38d0b1919bf87e5c | /PobotKey/Projects/Arduino/Projets complets/PobotEasy/EasyLibraryDevelopment/EasyPince.h | fba3a16ddd6701e2c862be38dbd1f7ed25acd0e0 | []
| no_license | JulienHoltzer/Pobot-Playground | 8d0cb50edc5846d7fe717f467d5a9f07ad7e7979 | a4a9c6af9c8b2fec8e5782be86427620843f38df | refs/heads/master | 2021-05-28T04:54:03.737479 | 2011-11-11T10:32:43 | 2011-11-11T10:32:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,011 | h | /**
* This source code is release under the MIT License.
*
*/
#ifndef _EASY_PINCE_H
#define _EASY_PINCE_H
#include "WProgram.h"
#include "Servo.h"
// Values
#define PINCE_OUVERTE 110
#define PINCE_FERMEE 38
#define BRAS_HAUT 40
#define BRAS_BAS 120
#define pinBras 7
#define pinPince 8
// Class EasyPince
class EasyPince
{
public:
void ouvrePince(void);
void fermePince(void);
boolean isPinceOuverte(void);
boolean isPinceFermee(void);
boolean isPinceBloquee(void);
void levePince(void);
void baissePince(void);
void anglePince(int);
void attachServo(Servo *s1, Servo *s2) {
servoBras = s1;
servoPince = s2;
servoBras->attach(pinBras);
servoPince->attach(pinPince);
}
void disablePince(void)
{
servoBras->detach();
servoPince->detach();
}
void enablePince(void)
{
servoBras->attach(pinBras);
servoPince->attach(pinPince);
}
void testPince();
private:
Servo *servoBras;
Servo *servoPince;
};
#endif
| [
"julien.holtzer@c631b436-7905-11de-aab9-69570e6b7754"
]
| [
[
[
1,
70
]
]
]
|
ee98c42daad80a12bc24facbc8cfbf349626593e | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/os/mm/mmf/T_MdaAudioOutputStream/inc/T_MdaAudioOutputStreamServer.inl | 4da9c829121d022be534e1c54d67349bd7a19370 | []
| no_license | SymbianSource/oss.FCL.sftools.ana.compatanamdw | a6a8abf9ef7ad71021d43b7f2b2076b504d4445e | 1169475bbf82ebb763de36686d144336fcf9d93b | refs/heads/master | 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,414 | inl | /*
* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
#include "T_MMDataMdaAudioOutputStream.h"
_LIT(KT_MdaAudioOutputStream, "CMdaAudioOutputStream");
CT_MdaAudioOutputStreamServer::CT_MdaAudioOutputStreamBlock::CT_MdaAudioOutputStreamBlock()
: CTestBlockController()
{
}
CT_MdaAudioOutputStreamServer::CT_MdaAudioOutputStreamBlock::~CT_MdaAudioOutputStreamBlock()
{
}
CDataWrapper* CT_MdaAudioOutputStreamServer::CT_MdaAudioOutputStreamBlock::CreateDataL(const TDesC& aData)
{
CDataWrapper* wrapper = NULL;
if( KT_MdaAudioOutputStream() == aData )
{
wrapper = CT_MMDataMdaAudioOutputStream::NewL();
}
return wrapper;
}
CT_MdaAudioOutputStreamServer::CT_MdaAudioOutputStreamServer()
{
}
CT_MdaAudioOutputStreamServer::~CT_MdaAudioOutputStreamServer()
{
}
void CT_MdaAudioOutputStreamServer::DeleteActiveSchedulerL()
{
}
CTestBlockController* CT_MdaAudioOutputStreamServer::CreateTestBlock()
{
return new CT_MdaAudioOutputStreamBlock();
}
| [
"none@none"
]
| [
[
[
1,
58
]
]
]
|
6d97fc08a0b4dade75b49b9b9ec8fce9c3b902e7 | 78d40fe09df2496088fd22859876eb6e7be954c0 | /bb.h | 7ff1dd4afa117c10f3d6cf824695fb459ce18897 | []
| no_license | icedman/style7 | f1086f650b43784735542e6fac7df64197d0f00e | 6834d4d1021bd805631379dc4795427eae8d6893 | refs/heads/master | 2021-01-23T04:00:10.384380 | 2010-04-08T10:40:37 | 2010-04-08T10:40:37 | 35,222,984 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 276 | h | #pragma once
#include "style.h"
#include <QMap>
class QSettings;
class BBStyle : public Style
{
public:
bool load(const QString& filename);
protected:
virtual void loadFrame(QString key, int frame, QSettings *settings);
QMap<QString,int> styleMap;
}; | [
"m4rvin2005@12bdf7b2-7090-17ef-321a-d85e0c66d2ab"
]
| [
[
[
1,
18
]
]
]
|
3de26fef5ca57d7c3986b8b51842602e43f16a91 | c6311b5096eeed35f7b8cdb5c228de915075eb71 | /tp3/Tp_3_Mundial2010v1/MainDialog.h | 577d2da3b241f1a5b580e6c9d110bedc991791b4 | []
| no_license | kevinalle/metnum2010 | 5dccdba68bb4d3065c6a696f02836e7119eba657 | 142a5464429e564c13aabd339a7b01800ea9023e | refs/heads/master | 2020-05-28T05:01:34.835358 | 2010-07-23T19:19:27 | 2010-07-23T19:19:27 | 32,120,707 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,261 | h | /** \file
\author Pablo Haramburu
Copyright:
Copyright (C)2010 Pablo Haramburu.
License:
This file is part of mundial2010.
mundial2010 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.
mundial2010 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 mundial2010. If not, see <http://www.gnu.org/licenses/>.
*/
// Generated by DialogBlocks (unregistered), 31/05/2010 13:18:00
#ifndef _MAINDIALOG_H_
#define _MAINDIALOG_H_
/*!
* Includes
*/
#include "AppModel.h"
////@begin includes
////@end includes
/*!
* Forward declarations
*/
////@begin forward declarations
////@end forward declarations
/*!
* Control identifiers
*/
////@begin control identifiers
#define ID_MAINDIALOG 10000
#define ID_ADD_GOALKEEPER_BUTTON 10001
#define ID_GOALKEEPERS_LISTBOX 10002
#define ID_ADD_TESTFILE_BUTTON 10003
#define ID_TESTSFILES_LISTBOX 10004
#define ID_RUN_TESTS_BUTTON 10005
#define SYMBOL_MAINDIALOG_STYLE wxCAPTION|wxRESIZE_BORDER|wxSYSTEM_MENU|wxCLOSE_BOX|wxMINIMIZE_BOX|wxTAB_TRAVERSAL
#define SYMBOL_MAINDIALOG_TITLE wxGetTranslation(wxString(wxT("M")) + (wxChar) 0x00E9 + wxT("todos Num") + (wxChar) 0x00E9 + wxT("ricos 2010c1 - TP3 - Probador"))
#define SYMBOL_MAINDIALOG_IDNAME ID_MAINDIALOG
#define SYMBOL_MAINDIALOG_SIZE wxSize(400, 300)
#define SYMBOL_MAINDIALOG_POSITION wxDefaultPosition
////@end control identifiers
/*!
* MainDialog class declaration
*/
class MainDialog: public wxDialog
{
DECLARE_DYNAMIC_CLASS( MainDialog )
DECLARE_EVENT_TABLE()
public:
/// Constructors
MainDialog();
MainDialog( wxWindow* parent, wxWindowID id = SYMBOL_MAINDIALOG_IDNAME, const wxString& caption = SYMBOL_MAINDIALOG_TITLE, const wxPoint& pos = SYMBOL_MAINDIALOG_POSITION, const wxSize& size = SYMBOL_MAINDIALOG_SIZE, long style = SYMBOL_MAINDIALOG_STYLE );
/// Creation
bool Create( wxWindow* parent, wxWindowID id = SYMBOL_MAINDIALOG_IDNAME, const wxString& caption = SYMBOL_MAINDIALOG_TITLE, const wxPoint& pos = SYMBOL_MAINDIALOG_POSITION, const wxSize& size = SYMBOL_MAINDIALOG_SIZE, long style = SYMBOL_MAINDIALOG_STYLE );
/// Destructor
~MainDialog();
/// Initialises member variables
void Init();
/// Creates the controls and sizers
void CreateControls();
////@begin MainDialog event handler declarations
/// wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_ADD_GOALKEEPER_BUTTON
void OnAddGoalkeeperButtonClick( wxCommandEvent& event );
/// wxEVT_KEY_DOWN event handler for ID_GOALKEEPERS_LISTBOX
void OnGoalkeepersListboxKeyDown( wxKeyEvent& event );
/// wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_ADD_TESTFILE_BUTTON
void OnAddTestfileButtonClick( wxCommandEvent& event );
/// wxEVT_KEY_DOWN event handler for ID_TESTSFILES_LISTBOX
void OnTestsfilesListboxKeyDown( wxKeyEvent& event );
/// wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_RUN_TESTS_BUTTON
void OnRunTestsButtonClick( wxCommandEvent& event );
/// wxEVT_UPDATE_UI event handler for ID_RUN_TESTS_BUTTON
void OnRunTestsButtonUpdate( wxUpdateUIEvent& event );
////@end MainDialog event handler declarations
////@begin MainDialog member function declarations
/// Retrieves bitmap resources
wxBitmap GetBitmapResource( const wxString& name );
/// Retrieves icon resources
wxIcon GetIconResource( const wxString& name );
////@end MainDialog member function declarations
/// Should we show tooltips?
static bool ShowToolTips();
////@begin MainDialog member variables
wxListBox* m_goalkeepers;
wxListBox* m_testfiles;
////@end MainDialog member variables
wxCheckBox * m_showAnimation;
private:
AppModel m_model;
};
#endif
// _MAINDIALOG_H_
| [
"kevinalle@8062f241-9d54-ddaa-24e5-4d4b1e181026"
]
| [
[
[
1,
134
]
]
]
|
76ee7c578356cf53674b85a9574797e7b9713036 | ed9ecdcba4932c1adacac9218c83e19f71695658 | /CJEngine_2010/CJEngine/CJEngine/ResourceManager.h | 7cfbfb596d6a268e99354cffb65ca523537d81fe | []
| no_license | karansapra/futurattack | 59cc71d2cc6564a066a8e2f18e2edfc140f7c4ab | 81e46a33ec58b258161f0dd71757a499263aaa62 | refs/heads/master | 2021-01-10T08:47:01.902600 | 2010-09-20T20:25:04 | 2010-09-20T20:25:04 | 45,804,375 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 569 | h | #pragma once
#include <vector>
#include "./Resource.h"
#include "./Texture.h"
#include "./FX.h"
#include "./Font.h"
typedef std::vector<Resource*> ResourcePtrList;
typedef ResourcePtrList::iterator ResourcePtrListIterator;
class CJEngine;
class ResourceManager
{
friend class CJEngine;
ResourcePtrList resources_;
ResourceManager(void);
~ResourceManager(void);
public:
Texture * AddTexture(const char * name);
FX * AddEffect(const char * vert_sh_file, const char * frag_sh_file);
Font * AddFont(const char * filename, int size);
};
| [
"clems71@52ecbd26-af3e-11de-a2ab-0da4ed5138bb"
]
| [
[
[
1,
25
]
]
]
|
c49f5827ba00f2b35fd04a97f6633d7d2101f734 | e2e49023f5a82922cb9b134e93ae926ed69675a1 | /tools/aoslcpp/source/aosl/event_signal.cpp | 3c5e72435cb5edf5061af13168f24bf026212a21 | []
| no_license | invy/mjklaim-freewindows | c93c867e93f0e2fe1d33f207306c0b9538ac61d6 | 30de8e3dfcde4e81a57e9059dfaf54c98cc1135b | refs/heads/master | 2021-01-10T10:21:51.579762 | 2011-12-12T18:56:43 | 2011-12-12T18:56:43 | 54,794,395 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,142 | cpp | // Copyright (C) 2005-2010 Code Synthesis Tools CC
//
// This program was generated by CodeSynthesis XSD, an XML Schema
// to C++ data binding compiler, in the Proprietary License mode.
// You should have received a proprietary license from Code Synthesis
// Tools CC prior to generating this code. See the license text for
// conditions.
//
// Begin prologue.
//
#define AOSLCPP_SOURCE
//
// End prologue.
#include <xsd/cxx/pre.hxx>
#include "aosl/event_signal.hpp"
#include <xsd/cxx/xml/dom/wildcard-source.hxx>
#include <xsd/cxx/xml/dom/parsing-source.hxx>
#include <xsd/cxx/tree/type-factory-map.hxx>
#include <xsd/cxx/tree/comparison-map.hxx>
namespace _xsd
{
static
const ::xsd::cxx::tree::type_factory_plate< 0, char >
type_factory_plate_init;
static
const ::xsd::cxx::tree::comparison_plate< 0, char >
comparison_plate_init;
}
namespace aosl
{
// Event_signal
//
Event_signal::
Event_signal (const MoveType& move,
const SourceType& source)
: ::aosl::Event_signal_base (move),
source_ (source, ::xml_schema::Flags (), this)
{
}
Event_signal::
Event_signal (const Event_signal& x,
::xml_schema::Flags f,
::xml_schema::Container* c)
: ::aosl::Event_signal_base (x, f, c),
source_ (x.source_, f, this)
{
}
Event_signal::
Event_signal (const ::xercesc::DOMElement& e,
::xml_schema::Flags f,
::xml_schema::Container* c)
: ::aosl::Event_signal_base (e, f | ::xml_schema::Flags::base, c),
source_ (f, this)
{
if ((f & ::xml_schema::Flags::base) == 0)
{
::xsd::cxx::xml::dom::parser< char > p (e, false, true);
this->parse (p, f);
}
}
void Event_signal::
parse (::xsd::cxx::xml::dom::parser< char >& p,
::xml_schema::Flags f)
{
this->::aosl::Event_signal_base::parse (p, f);
p.reset_attributes ();
while (p.more_attributes ())
{
const ::xercesc::DOMAttr& i (p.next_attribute ());
const ::xsd::cxx::xml::qualified_name< char > n (
::xsd::cxx::xml::dom::name< char > (i));
if (n.name () == "source" && n.namespace_ ().empty ())
{
::std::auto_ptr< SourceType > r (
SourceTraits::create (i, f, this));
this->source_.set (r);
continue;
}
}
if (!source_.present ())
{
throw ::xsd::cxx::tree::expected_attribute< char > (
"source",
"");
}
}
Event_signal* Event_signal::
_clone (::xml_schema::Flags f,
::xml_schema::Container* c) const
{
return new class Event_signal (*this, f, c);
}
Event_signal::
~Event_signal ()
{
}
static
const ::xsd::cxx::tree::type_factory_initializer< 0, char, Event_signal >
_xsd_Event_signal_type_factory_init (
"event_signal",
"artofsequence.org/aosl/1.0");
static
const ::xsd::cxx::tree::comparison_initializer< 0, char, Event_signal >
_xsd_Event_signal_comparison_init;
bool
operator== (const Event_signal& x, const Event_signal& y)
{
if (!(static_cast< const ::aosl::Event_signal_base& > (x) ==
static_cast< const ::aosl::Event_signal_base& > (y)))
return false;
if (!(x.source () == y.source ()))
return false;
return true;
}
bool
operator!= (const Event_signal& x, const Event_signal& y)
{
return !(x == y);
}
}
#include <ostream>
#include <xsd/cxx/tree/std-ostream-map.hxx>
namespace _xsd
{
static
const ::xsd::cxx::tree::std_ostream_plate< 0, char >
std_ostream_plate_init;
}
namespace aosl
{
::std::ostream&
operator<< (::std::ostream& o, const Event_signal& i)
{
o << static_cast< const ::aosl::Event_signal_base& > (i);
o << ::std::endl << "source: " << i.source ();
return o;
}
static
const ::xsd::cxx::tree::std_ostream_initializer< 0, char, Event_signal >
_xsd_Event_signal_std_ostream_init;
}
#include <istream>
#include <xsd/cxx/xml/sax/std-input-source.hxx>
#include <xsd/cxx/tree/error-handler.hxx>
namespace aosl
{
}
#include <ostream>
#include <xsd/cxx/tree/error-handler.hxx>
#include <xsd/cxx/xml/dom/serialization-source.hxx>
#include <xsd/cxx/tree/type-serializer-map.hxx>
namespace _xsd
{
static
const ::xsd::cxx::tree::type_serializer_plate< 0, char >
type_serializer_plate_init;
}
namespace aosl
{
void
operator<< (::xercesc::DOMElement& e, const Event_signal& i)
{
e << static_cast< const ::aosl::Event_signal_base& > (i);
// source
//
{
::xercesc::DOMAttr& a (
::xsd::cxx::xml::dom::create_attribute (
"source",
e));
a << i.source ();
}
}
static
const ::xsd::cxx::tree::type_serializer_initializer< 0, char, Event_signal >
_xsd_Event_signal_type_serializer_init (
"event_signal",
"artofsequence.org/aosl/1.0");
}
#include <xsd/cxx/post.hxx>
// Begin epilogue.
//
//
// End epilogue.
| [
"klaim@localhost"
]
| [
[
[
1,
231
]
]
]
|
b54e3d3428cb0f7ad323e53dccce9a75dc799118 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctestaknsound/inc/bctestaknsoundview.h | b16d9fd97f2c7b38cc7c8c377a93e08110aab469 | []
| no_license | SymbianSource/oss.FCL.sftools.ana.compatanamdw | a6a8abf9ef7ad71021d43b7f2b2076b504d4445e | 1169475bbf82ebb763de36686d144336fcf9d93b | refs/heads/master | 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,995 | h | /*
* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: Test BC for Template control API.
*
*/
#ifndef C_CBCTESTAKNSOUNDVIEW_H
#define C_CBCTESTAKNSOUNDVIEW_H
#include <aknview.h>
const TUid KBCTestAknSoundViewId = { 1 };
class CBCTestAknSoundContainer;
class CBCTestUtil;
/**
* Application UI class
*
* @lib bctestutil.lib
*/
class CBCTestAknSoundView : public CAknView
{
public: // Constructors and destructor
/**
* Symbian static 2nd constructor
*/
static CBCTestAknSoundView* NewL();
/**
* dtor
*/
virtual ~CBCTestAknSoundView();
public: // from CAknView
/**
* Return view Id.
*/
TUid Id() const;
/**
* From CAknView, HandleCommandL.
* @param aCommand Command to be handled.
*/
void HandleCommandL( TInt aCommand );
protected: // from CAknView
/**
* When view is activated, do something
*/
void DoActivateL( const TVwsViewId&, TUid, const TDesC8& );
/**
* When view is deactivated, do something
*/
void DoDeactivate();
private: // constructor
/**
* C++ default constructor
*/
CBCTestAknSoundView();
/**
* symbian 2nd ctor
*/
void ConstructL();
private: // data
/**
* pointor to the BC Test framework utility.
* own
*/
CBCTestUtil* iTestUtil;
/**
* pointor to the container.
* own
*/
CBCTestAknSoundContainer* iContainer;
};
#endif // C_CBCTESTAKNSOUNDVIEW_H
| [
"none@none"
]
| [
[
[
1,
102
]
]
]
|
713b43f15373c881759a1565b28036f53174367a | 15732b8e4190ae526dcf99e9ffcee5171ed9bd7e | /INC/node-impl.h | e8e06fe73bddef0a69a5e6035c44fdf77438688b | []
| no_license | clovermwliu/whutnetsim | d95c07f77330af8cefe50a04b19a2d5cca23e0ae | 924f2625898c4f00147e473a05704f7b91dac0c4 | refs/heads/master | 2021-01-10T13:10:00.678815 | 2010-04-14T08:38:01 | 2010-04-14T08:38:01 | 48,568,805 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 18,536 | h | //Copyright (c) 2010, Information Security Institute of Wuhan Universtiy(ISIWhu)
//All rights reserved.
//
//PLEASE READ THIS DOCUMENT CAREFULLY BEFORE UTILIZING THE PROGRAM
//BY UTILIZING THIS PROGRAM, YOU AGREE TO BECOME BOUND BY THE TERMS OF
//THIS LICENSE. IF YOU DO NOT AGREE TO THE TERMS OF THIS LICENSE, DO
//NOT USE THIS PROGRAM OR ANY PORTION THEREOF IN ANY FORM OR MANNER.
//
//This License allows you to:
//1. Make copies and distribute copies of the Program's source code provide that any such copy
// clearly displays any and all appropriate copyright notices and disclaimer of warranty as set
// forth in this License.
//2. Modify the original copy or copies of the Program or any portion thereof ("Modification(s)").
// Modifications may be copied and distributed under the terms and conditions as set forth above.
// Any and all modified files must be affixed with prominent notices that you have changed the
// files and the date that the changes occurred.
//Termination:
// If at anytime you are unable to comply with any portion of this License you must immediately
// cease use of the Program and all distribution activities involving the Program or any portion
// thereof.
//Statement:
// In this program, part of the code is from the GTNetS project, The Georgia Tech Network
// Simulator (GTNetS) is a full-featured network simulation environment that allows researchers in
// computer networks to study the behavior of moderate to large scale networks, under a variety of
// conditions. Our work have great advance due to this project, Thanks to Dr. George F. Riley from
// Georgia Tech Research Corporation. Anyone who wants to study the GTNetS can come to its homepage:
// http://www.ece.gatech.edu/research/labs/MANIACS/GTNetS/
//
//File Information:
//
//
//File Name:
//File Purpose:
//Original Author:
//Author Organization:
//Construct Data:
//Modify Author:
//Author Organization:
//Modify Data:
/************************************************************************/
/* 2010.1.4 关怡萍 */
/***********************************************************************/
#ifndef __nodeimpl_h__
#define __nodeimpl_h__
#include "G_common_defs.h"
#include "macaddr.h"
#include "node.h"
class Link;
class Node;
class Interface;
class Routing;
class Protocol;
class ProtocolGraph;
class PortDemux;
class Linkp2p;
class Queue;
class Application;
////class RoutingAODV;
////class AODVRoutingEntry;
class Image;
////class WirelessLink;
class NodeImpl {
public:
NodeImpl(Node*);
virtual ~NodeImpl();
virtual NodeImpl* Copy() const = 0; //所有的Nodeimpl都能被复制
NodeId_t Id() { return pNode->Id(); }//返回结点Id
//IP地址管理
virtual IPAddr_t GetIPAddr(); // 获取该结点的IP地址
virtual void SetIPAddr(IPAddr_t i);// 设置该结点的IP地址
virtual void IPAddrs(IPMaskVec_t&);// 返回该结点所有接口的IP地址和掩码信息
virtual bool LocalIP(IPAddr_t); // 判断IPAddr_t是否为本结点IP地址,是则返回true
virtual bool IPKnown(); // 判断是否分配了一个非默认的IP地址,是则返回true
virtual bool IsReal() = 0; // 判断是否是real类型结点,是则返回true
//Satellite功能
virtual bool FirstBitRx() const { return false;}
virtual void FirstBitRx(bool) { }
//交换机功能
virtual void IsSwitchNode(bool) = 0;//是否将该结点置为交换机
virtual bool IsSwitchNode() = 0; //判断该结点是否是一个交换机
virtual void PacketRX(Packet* p, Interface* iface) = 0;//若交换机结点收到一个数据包,则该函数被执行
//接口
virtual Interface* AddInterface(Interface*);//添加一个已经设置好的接口
virtual Interface* AddInterface(const L2Proto&, bool bootstrap=false);//添加新的空接口,该接口分配第二层网络协议
virtual Interface* AddInterface(const L2Proto&, //为本地结点新增接口,IP地址、掩码指定,MAC地址默认,并分配第二层网络协议
IPAddr_t, Mask_t,
MACAddr = MACAddr::Allocate(),
bool bootstrap = false);
virtual Interface* AddInterface(const L2Proto&, //为本地结点新增接口,IP地址、掩码、接口类型指定,MAC地址默认,并分配第二层网络协议
const Interface&,
IPAddr_t,
Mask_t,
MACAddr = MACAddr::Allocate(),
bool bootstrap = false);
virtual Count_t InterfaceCount(); //获取与该结点绑定的接口的数目,返回值是接口数目
virtual const IFVec_t& Interfaces(); //获取与本地结点绑定的所有接口的信息
virtual Interface* GetIfByLink(Link*); //根据边查找对应接口
virtual Interface* GetIfByNode(Node*); //根据点查找对应接口
virtual Interface* GetIfByIP(IPAddr_t);//根据本地接口IP地址查找对应接口
virtual void Broadcast(Packet*, Proto_t) = 0;//通过该结点的所有接口广播数据包。
//双向链路:该部分函数功能均为与远程结点建立全双工的链路连接,返回值均为新建链路对应的本地接口
virtual Interface* AddDuplexLink(Node*);//连接远程结点,本地结点新增一条双向链路和一个接口,链路类型为默认
virtual Interface* AddDuplexLink(Node*, const Linkp2p&);//连接远程结点,本地结点新增一条双向链路和一个接口,链路类型指定
virtual Interface* AddDuplexLink(Interface*,Interface*);//新建一个连接两个指定接口的双向链路,链路类型默认
virtual Interface* AddDuplexLink(Interface*,Interface*, const Linkp2p&);//新建一个连接两个指定接口的双向链路,链路类型默认
virtual Interface* AddDuplexLink(Node*,//连接远程结点,本地结点新增一条双向链路和一个接口,链路类型为默认。为本地与远程结点新增的接口分配IP地址和掩码
IPAddr_t,
Mask_t,
IPAddr_t,
Mask_t);
virtual Interface* AddDuplexLink(Node*,//连接远程结点,本地结点新增一条双向链路和一个接口,链路类型为默认。为本地与远程结点新增的接口分配IP地址和掩码
const Linkp2p&,
IPAddr_t,
Mask_t,
IPAddr_t,
Mask_t);
virtual Link* GetLink(Node*); //返回与指定结点联通的链路
//v1.01
//virtual Interface* AddRemoteLink(IPAddr_t, Mask_t);//仅在分布式模拟器中使用,定义一条连通本地结点与其它结点的双向链路,在另一个模拟过程中使用。链路的带宽和延迟默认
//virtual Interface* AddRemoteLink(IPAddr_t, Mask_t, Rate_t, Time_t);//仅在分布式模拟器中使用,定义一条连通本地结点与其它结点的双向链路,在另一个模拟过程中使用。链路的带宽和延迟指定
//单向链路
virtual Interface* AddSimplexLink(Node*);//连接远程结点,本地结点新增一条单向链路和一个接口,链路类型为默认
virtual Interface* AddSimplexLink(Node*, const Linkp2p&);//连接远程结点,本地结点新增一条单向链路和一个接口,链路类型指定
virtual Interface* AddSimplexLink(Node*, //连接远程结点,本地结点新增一条单向链路和一个接口,链路类型指定,本地接口IP地址和掩码指定
const Linkp2p&,
IPAddr_t,
Mask_t);
//队列
virtual Queue* GetQueue() = 0; //获取本地结点的队列,仅对单接口的结点有效
virtual Queue* GetQueue(Node*) = 0; //获取本地结点通往指定目标结点的队列
//应用
virtual Application* AddApplication(const Application& a) = 0;//给本地结点添加指定应用
virtual ApplicationVec_t* GetApplicationVec() = 0; //获取应用
//邻接结点管理:在路由协议中使用
virtual void Neighbors(NodeWeightVec_t &, bool); //获取所有的邻近结点
virtual Count_t NeighborCount(); //获取路由表中邻近结点的数目
virtual void NeighborsByIf(Interface*, IPAddrVec_t&);//获取与本地结点指定接口相连的邻接结点IP地址
//路由
virtual void DefaultRoute(RoutingEntry) = 0;//指定发送数据包的默认路由项
virtual void DefaultRoute(Node*) = 0;//指定发送数据包的默认下一跳结点
virtual void AddRoute( IPAddr_t, Count_t, Interface*, IPAddr_t) = 0;//增加一个路由项,目的IP及其掩码、本地接口、下一跳IP地址确定
virtual RoutingEntry LookupRoute(IPAddr_t) = 0; //根据目的IP地址查找本地路由项,若存在则返回
virtual RoutingEntry LookupRouteNix(Count_t) = 0;//根据邻接结点索引查找本地路由项,若存在则返回
virtual Routing::RType_t RoutingType() = 0;//获取本地结点当前所使用的路由类型
virtual Interface* LocalRoute(IPAddr_t);//判断某IP地址是否是直接与本地结点某interface相连,若是则返回该interface
virtual void InitializeRoutes() = 0;//路由初始化,为路由协议做准备
virtual void ReInitializeRoutes(bool) = 0; //重新初始化路由
virtual Count_t RoutingFibSize() const = 0;//统计本地结点路由的大小
virtual Count_t GetNix(Node*) const;//根据指定结点查找邻接结点的Index,若该结点不是邻接结点,返回MAX_COUNT
virtual RoutingNixVector* GetNixRouting() = 0; // Returns Nix rtg pointer
virtual Routing* GetRouting() = 0;//返回本地结点所使用的路由对象的指针
//AODV路由
//////virtual AODVRoutingEntry *LookupRouteAODV(IPAddr_t ip) =0;
//////virtual void SetRoutingAODV(void *pRouting)= 0;
//////virtual RoutingAODV *GetRoutingAODV() = 0;
//协议族接口
virtual Protocol* LookupProto(Layer_t, Proto_t) = 0;//在本地结点,根据协议层和编号查找对应的协议对象
virtual void InsertProto(Layer_t, Proto_t, Protocol*) = 0;//在本地结点插入一个协议对象,.协议层和编号指定
//多路分配器接口
virtual bool Bind(Proto_t, PortId_t, Protocol*) = 0;//为指定端口绑定指定协议
virtual bool Bind(Proto_t,
PortId_t,
IPAddr_t,
PortId_t,
IPAddr_t,
Protocol*) = 0;//为本地结点指定端口和远程结点指定端口绑定指定协议
virtual PortId_t Bind(Proto_t, Protocol*) = 0;//绑定指定协议,对应本地端口随机
virtual bool Unbind(Proto_t, PortId_t, Protocol*) = 0;//删除本地结点指定接口绑定的指定协议
virtual bool Unbind(Proto_t,
PortId_t,
IPAddr_t,
PortId_t,
IPAddr_t,
Protocol*) = 0;//本地结点指定端口和远程结点指定端口绑定指定协议
virtual Protocol* LookupByPort(Proto_t, PortId_t) = 0;//根据本地端口和协议号查找所绑定的协议
virtual Protocol* LookupByPort(Proto_t,
PortId_t, IPAddr_t,
PortId_t, IPAddr_t) = 0; //查找协议,根据协议号、本地结点端口、IP地址、远程结点端口、IP地址
//数据包跟踪接口
virtual bool TracePDU(Protocol*, PDU*, Packet*, char*) = 0;//将指定PDU内容从指定协议记录到跟踪文件
virtual void SetTrace(Trace::TraceStatus) = 0;//设置本地结点的跟踪状态
//结点坐标(x, y, z)接口
virtual void SetLocation(Meters_t, Meters_t, Meters_t) = 0;//直接在xyz坐标系中设置本地结点的坐标
virtual void SetLocation(const Location&) = 0; //根据location对象设置本地结点在xyz坐标系中的坐标
virtual void SetLocationLongLat(const Location&) = 0;
virtual bool HasLocation() = 0;//检查本地结点是否已分配地址
virtual Meters_t LocationX() = 0;//返回本地结点的x坐标
virtual Meters_t LocationY() = 0;//返回本地结点的y坐标
virtual Meters_t LocationZ() = 0;//返回本地结点的z坐标
virtual Location GetLocation() = 0;//返回本地结点当前位置
virtual Location UpdateLocation() = 0;//更新本地结点的位置
virtual Meters_t Distance(Node*) = 0;//返回本地结点到指定对等结点的距离
virtual Mobility* AddMobility(const Mobility&) = 0;//为本地结点增添一个mobility模型
virtual Mobility* GetMobility() const = 0; //获取本地结点当前的mobility模型
virtual bool IsMobile() = 0; //判断本地结点是否含有mobility模型
virtual bool IsMoving() = 0; //判断本地结点的当前状态是否是正在运行
#ifdef HAVE_QT //v1.01
virtual void UserInformation(void*) = 0;//存储用户仿真过程中任何有用信息
virtual void* UserInformation() = 0;//返回之前指定的用户信息指针,若没有返回空
#endif
////virtual bool WirelessTx() = 0;
////virtual bool WirelessRx() = 0;
////virtual bool WirelessCx() = 0;
////virtual bool WirelessRxMe() = 0;
////virtual bool WirelessRxZz() = 0;
////void UseWormContainment(bool);
////bool UseWormContainment() { return usewormcontainment; }
////virtual void SetWormContainment(WormContainment*) = 0;
////virtual void UseARP(bool) = 0;
////virtual WormContainment* GetWormContainment() = 0;
//QT窗口信息
#ifdef HAVE_QT //v1.01
virtual void Show(bool) = 0; //根据参数确定是否要显示窗口
virtual bool Show() = 0;//返回显示是否要被激活
virtual MyCanvasItem* Display(gui_ctrl*) = 0;//确定点显示的形状、大小等,显示位置为点当前的位置
virtual MyCanvasItem* Display(const MyPoint&, gui_ctrl*) = 0;//确定点显示的形状、大小等,显示位置参数中提供的位置
////virtual void WirelessTxColor(const MyColor&) = 0;
////virtual const MyColor& WirelessTxColor() = 0;
////virtual bool PushWirelessTx(MyCanvasItem*) = 0;
////virtual MyCanvasItem* PopWirelessTx() = 0;
virtual void PixelSize(Count_t) = 0;//设置点在显示时的大小
virtual Count_t PixelSizeX() = 0;//返回点在显示时的宽度
virtual Count_t PixelSizeY() = 0;//返回点在显示时的高度
virtual void Shape(Node::Shape_t) = 0;//设置点在显示时的形状
virtual Node::Shape_t Shape() = 0;//返回点在显示时的形状
virtual CustomShape_t CustomShape();//返回一般图形的回调函数
virtual void CustomShape(CustomShape_t);//设置一般图形的回调函数
virtual bool CustomShapeFile(const char*);//载入一个包含一般图形的文件,若成功返回true,否则返回false
virtual bool CustomShapeImage(const Image&);//载入一个一般图形,若成功返回true,否则返回false
virtual void Color(const MyColor&) = 0;//指定本地结点的颜色
virtual bool HasColor() = 0;//检查本地结点是否已经分配颜色
virtual MyColor& Color() = 0;//返回本地结点的颜色
virtual NodeAnimation* GetNodeAnimation() const = 0;//返回指向所有结点结点动作信息块的指针
#endif
//ICMP相关信息
////virtual bool ICMPEnabled() const;//检查本地结点是否支持ICMP
////virtual void DisableICMP();//设定本地结点不支持ICMP
//管理运行失败信息
virtual void Down();//设定该结点无效,无法产生或转发数据包
virtual void Up();//设定该结点已经恢复,重新有效
virtual bool IsDown();//查看结点是否有效,若无效则返回true,若正常则返回false
//无线传输信息
////virtual void BuildRadioInterfaceList(WirelessLink*) = 0;
////virtual const RadioVec_t& GetRadioInterfaceList() = 0;
////virtual void SetRadioRange(Meters_t ) =0;
////virtual Meters_t GetRadioRange(void ) =0;
//回调函数
virtual void AddCallback(Layer_t, Proto_t,
PacketCallbacks::Type_t,
Interface*,
PacketCallbacks::Function_t) = 0;//给本结点增加一个回调函数。回调允许检测本结点接收或传输的任意协议层的任意数据包
virtual void AddCallbackHead(Layer_t, Proto_t,
PacketCallbacks::Type_t,
Interface*,
PacketCallbacks::Function_t) = 0;//给本地结点田间一个回调函数,该函数回调优先级最高
virtual void DeleteCallback(Layer_t, Proto_t,
PacketCallbacks::Type_t,
Interface*) = 0;//从本地结点删除一个回调函数
virtual bool CallCallbacks(Layer_t, Proto_t,
PacketCallbacks::Type_t, Packet*,
Interface*) = 0;//调用本地结点的回调函数
virtual void setBattery (Joules_t) = 0;//设置本地结点电池容量
virtual Joules_t getBattery (void) = 0;//获取本地结点电池容量
virtual void setComputePower (double) = 0;//设置本地结点CPU功耗
virtual double getComputePower (void) = 0;//获取本地结点CPU功耗
//virtual void setRouteTable (RouteTable*) = 0;//设置本地结点的路由表
//virtual RouteTable* getRouteTable (void) = 0;//返回本地结点的路由表
protected:
Node* pNode;// 指向相应结点接口对象
ApplicationVec_t pappvec; //该节点绑定的应用
bool usewormcontainment;//判断这个结点是否包含蠕虫功能
//real和ghost之间的数据成员
IPAddr_t ipAddr;//本地结点的IP地址
IFVec_t interfaces;//所有的接口
//LineVec_t plinkvec; //本节点所有的边 2010-1-30
Count_t neighborCount;//邻接接口总数
bool down;//判断结点是否无效
};
#endif
| [
"pengelmer@f37e807c-cba8-11de-937e-2741d7931076"
]
| [
[
[
1,
313
]
]
]
|
9a56a01aacc857bb89dfd263201bb0dddbe9fee4 | 222bc22cb0330b694d2c3b0f4b866d726fd29c72 | /src/brookbox/wm2/WmlContMinBox3.h | 75b1f2b9f8a981860378d2b89870c84be6f1d48d | [
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | darwin/inferno | 02acd3d05ca4c092aa4006b028a843ac04b551b1 | e87017763abae0cfe09d47987f5f6ac37c4f073d | refs/heads/master | 2021-03-12T22:15:47.889580 | 2009-04-17T13:29:39 | 2009-04-17T13:29:39 | 178,477 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,057 | h | // Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2003. All Rights Reserved
//
// The Wild Magic Library (WML) source code is supplied under the terms of
// the license agreement http://www.magic-software.com/License/WildMagic.pdf
// and may not be copied or disclosed except in accordance with the terms of
// that agreement.
#ifndef WMLCONTMINBOX3_H
#define WMLCONTMINBOX3_H
// Compute minimum volume oriented box containing the specified points.
#include "WmlBox3.h"
namespace Wml
{
template <class Real>
class WML_ITEM MinBox3
{
public:
MinBox3 (int iQuantity, const Vector3<Real>* akPoint, Box3<Real> &kBox);
private:
static Real Volume (const Real* afAngle, void* pvData);
static void MinimalBoxForAngles (int iQuantity,
const Vector3<Real>* akPoint, Real afAngle[3], Box3<Real>& rkBox);
int m_iQuantity;
const Vector3<Real>* m_akPoint;
};
typedef MinBox3<float> MinBox3f;
typedef MinBox3<double> MinBox3d;
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
42
]
]
]
|
1548a8f3cfaa5d8fca0f90a698c1545a74c7a888 | 71d018f8dbcf49cfb07511de5d58d6ad7df816f7 | /scistudio/trunk/TEXTEDIT.H | d447a4e26fa5e02e6c047aa6c7915317ad156103 | [
"LicenseRef-scancode-warranty-disclaimer"
]
| no_license | qq431169079/SciStudio | 48225261386402530156fc2fc14ff0cad62174e8 | a1fccbdcb423c045078b927e7c275b9d1bcae6b3 | refs/heads/master | 2020-05-29T13:01:50.800903 | 2010-09-14T07:10:07 | 2010-09-14T07:10:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,339 | h | //---------------------------------------------------------------------------
#ifndef texteditH
#define texteditH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include "MenuBar.hpp"
#include <ComCtrls.hpp>
#include <Dialogs.hpp>
#include <ExtCtrls.hpp>
#include <Menus.hpp>
#include <ToolWin.hpp>
//---------------------------------------------------------------------------
class TWndTextEdit : public TForm
{
__published: // IDE-managed Components
TSplitter *Splitter1;
TCoolBar *CoolBar1;
TMenuBar *MenuBar1;
TToolBar *ToolBar1;
TToolButton *tbNew;
TToolButton *tbOpen;
TToolButton *tbSave;
TToolButton *tbWriteScriptHeader;
TToolButton *ToolButton6;
TToolButton *tbViewAsMessageBox;
TToolButton *ToolButton3;
TToolButton *tbCopy;
TToolButton *ToolButton2;
TToolButton *tbAdd;
TToolButton *tbDelete;
TToolButton *tbMoveUp;
TToolButton *tbMoveDown;
TPanel *EditPanel;
TPanel *NamePanel;
TLabel *NameLabel;
TEdit *NameEdit;
TMainMenu *MainMenu1;
TMenuItem *File1;
TMenuItem *New1;
TMenuItem *Open1;
TMenuItem *Save1;
TMenuItem *SaveAs1;
TMenuItem *SaveToGame1;
TMenuItem *N3;
TMenuItem *WriteScriptHeader1;
TMenuItem *N1;
TMenuItem *Exit1;
TMenuItem *Entries1;
TMenuItem *Add1;
TMenuItem *Delete1;
TMenuItem *N2;
TMenuItem *MoveUp1;
TMenuItem *MoveDown1;
TMenuItem *View1;
TMenuItem *AsMessageBox1;
TMenuItem *Edit1;
TMenuItem *Copy1;
TOpenDialog *OpenDialog;
TSaveDialog *SaveDialog;
TPanel *Panel1;
TListView *ListView;
TPanel *Panel2;
TMemo *EditBox;
void __fastcall tbNewClick(TObject *Sender);
void __fastcall tbOpenClick(TObject *Sender);
void __fastcall Save1Click(TObject *Sender);
void __fastcall tbWriteScriptHeaderClick(TObject *Sender);
void __fastcall tbViewAsMessageBoxClick(TObject *Sender);
void __fastcall tbCopyClick(TObject *Sender);
void __fastcall tbAddClick(TObject *Sender);
void __fastcall tbDeleteClick(TObject *Sender);
void __fastcall tbMoveUpClick(TObject *Sender);
void __fastcall tbMoveDownClick(TObject *Sender);
void __fastcall SaveAs1Click(TObject *Sender);
void __fastcall SaveToGame1Click(TObject *Sender);
void __fastcall Exit1Click(TObject *Sender);
void __fastcall FormResize(TObject *Sender);
void __fastcall NameEditChange(TObject *Sender);
void __fastcall EditBoxChange(TObject *Sender);
void __fastcall ListViewDblClick(TObject *Sender);
void __fastcall FormKeyDown(TObject *Sender, WORD &Key,
TShiftState Shift);
void __fastcall ListViewChange(TObject *Sender, TListItem *Item,
TItemChange Change);
private: // User declarations
public: // User declarations
__fastcall TWndTextEdit(TComponent* Owner);
BOOL InitEditor(EDTWND *_edtWnd, U8 *resBuf, S16 resVer);
EDITORTAG edTag;
void LoadText();
void __fastcall LoadTextFile(AnsiString FileName);
BOOL TestString(AnsiString String);
void UpdateItemNumbers();
sciTEXT text;
};
//---------------------------------------------------------------------------
extern PACKAGE TWndTextEdit *WndTextEdit;
//---------------------------------------------------------------------------
#endif
| [
"mageofmarr@d0e240c1-a1d3-4535-ae25-191325aad40e"
]
| [
[
[
1,
106
]
]
]
|
f8cb1f896f0e6231d1cc88664c0d461ef0bdeb24 | b4d726a0321649f907923cc57323942a1e45915b | /CODE/MENUUI/pilotinfo.cpp | b7a9931699fa303c9e40af89a8728dda01783b97 | []
| no_license | chief1983/Imperial-Alliance | f1aa664d91f32c9e244867aaac43fffdf42199dc | 6db0102a8897deac845a8bd2a7aa2e1b25086448 | refs/heads/master | 2016-09-06T02:40:39.069630 | 2010-10-06T22:06:24 | 2010-10-06T22:06:24 | 967,775 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,341 | cpp | #include "globalincs/pstypes.h"
#include "menuui/barracks.h"
#include "playerman/managepilot.h"
#include "ui/ui.h"
#include "graphics/font.h"
#include "io/key.h"
#include "gamesnd/gamesnd.h"
#include "osapi/osapi.h"
#include "popup/popup.h"
#include "menuui/playermenu.h"
#include "gamesequence/gamesequence.h"
#include "gamehelp/contexthelp.h"
#include "graphics/2d.h"
#include "ctype.h"
#include "freespace2/freespace.h"
#include "globalincs/systemvars.h"
#include "bmpman/bmpman.h"
#include "io/mouse.h"
#include "osapi/osregistry.h"
#include "globalincs/alphacolors.h"
#include "debugconsole/dbugfile.h"
#include "Playerman/Player.h"
#include "Ship/Ship.h"
#define PI_NUM_BUTTONS 3
#define PI_UP_BUTTON 0
#define PI_DOWN_BUTTON 1
#define PI_EXIT_BUTTON 2
// stats defines
#define NUM_STAT_LINES (21 + MAX_SHIP_TYPES) // Goober5000
#define STAT_COLUMN1_W 40
#define STAT_COLUMN2_W 10
static int Stat_column1_w[GR_NUM_RESOLUTIONS] =
{
40, // GR_640
40 // GR_1024
};
static int Stat_column2_w[GR_NUM_RESOLUTIONS] =
{
10, // GR_640
10 // GR_1024
};
// constants for coordinate lookup
#define BARRACKS_X_COORD 0
#define BARRACKS_Y_COORD 1
#define BARRACKS_W_COORD 2
#define BARRACKS_H_COORD 3
//title info
static int Pilot_info_title_coords[GR_NUM_RESOLUTIONS][2] = {
{ // GR_640
280, 30
},
{ // GR_1024
100, 100
}
};
// pilot stats field
static int Barracks_stats_coords[GR_NUM_RESOLUTIONS][4] = {
{ // GR_640
170, 61, 200, 366 // 180//578, 366
},
{ // GR_1024
42, 351, 240, 400
}
};
static int Barracks_stats2_coords[GR_NUM_RESOLUTIONS][3] = {
{ // GR_640
386, 212, 81 //376 // X2, , W2
},
{ // GR_1024
286, 351, 81 // X2, , W2
}
};
static char *PilotStats_bitmap_fname[GR_NUM_RESOLUTIONS] = {
"PilotStats",
"2_PilotStats"
};
static char *PilotStats_bitmap_mask_fname[GR_NUM_RESOLUTIONS] = {
"PilotStats-M",
"2_PilotStats-M"
};
static int Num_stat_lines;
static char Stat_labels[NUM_STAT_LINES][STAT_COLUMN1_W];
static char Stats[NUM_STAT_LINES][STAT_COLUMN2_W];
//void pilot_info_init(void);
//void pilot_info_do(void);
static UI_WINDOW Ui_window;
static UI_BUTTON List_region;
static int Background_bitmap = -1;
extern player *Cur_pilot;
static int Stats_scroll_offset;
struct pilot_stats_buttons {
char *filename;
int x, y;
int text_x, text_y; // this is where the text label is
int hotspot;
int repeat;
UI_BUTTON button; // because we have a class inside this struct, we need the constructor below..
pilot_stats_buttons(char *name, int x1, int y1, int x2, int y2, int h, int r = 0) : filename(name), x(x1), y(y1), text_x(x2), text_y(y2), hotspot(h), repeat(r) {}
};
static pilot_stats_buttons Buttons[GR_NUM_RESOLUTIONS][PI_NUM_BUTTONS] = {
{
pilot_stats_buttons("PSB_00", 380, 450, 11, 157, 0),
pilot_stats_buttons("PSB_01", 406, 450, 0, 0, 1),
pilot_stats_buttons("PSB_02", 476, 450, 0, 0, 2),
},
{
pilot_stats_buttons("PSB_00", 8, 122, 11, 157, 0),
pilot_stats_buttons("PSB_01", 323, 130, 0, 0, 1),
pilot_stats_buttons("PSB_02", 350, 130, 0, 0, 2),
}
};
#define STRCPY1(a, b) do { \
Assert(strlen(b) < STAT_COLUMN1_W); \
strcpy(a, b); \
} while (0)
void init_pilot_stats(scoring_struct *stats)
{
int i;
float f;
Num_stat_lines = 0;
STRCPY1(Stat_labels[Num_stat_lines], XSTR( "*All Time Stats", 50));
Stats[Num_stat_lines][0] = 0;
Num_stat_lines++;
Assert(Num_stat_lines < NUM_STAT_LINES);
Stat_labels[Num_stat_lines][0] = 0;
Stats[Num_stat_lines][0] = 0;
Num_stat_lines++;
Assert(Num_stat_lines < NUM_STAT_LINES);
STRCPY1(Stat_labels[Num_stat_lines], XSTR( "Primary weapon shots:", 51));
sprintf(Stats[Num_stat_lines], "%d", stats->p_shots_fired);
Num_stat_lines++;
Assert(Num_stat_lines < NUM_STAT_LINES);
STRCPY1(Stat_labels[Num_stat_lines], XSTR( "Primary weapon hits:", 52));
sprintf(Stats[Num_stat_lines], "%d", stats->p_shots_hit);
Num_stat_lines++;
Assert(Num_stat_lines < NUM_STAT_LINES);
STRCPY1(Stat_labels[Num_stat_lines], XSTR( "Primary friendly hits:", 53));
sprintf(Stats[Num_stat_lines], "%d", stats->p_bonehead_hits);
Num_stat_lines++;
Assert(Num_stat_lines < NUM_STAT_LINES);
STRCPY1(Stat_labels[Num_stat_lines], XSTR( "Primary hit %:", 54));
if (stats->p_shots_fired > 0) {
f = (float) stats->p_shots_hit * 100.0f / (float) stats->p_shots_fired;
} else {
f = 0.0f;
}
sprintf(Stats[Num_stat_lines], XSTR( "%.1f%%", 55), f);
Num_stat_lines++;
Assert(Num_stat_lines < NUM_STAT_LINES);
STRCPY1(Stat_labels[Num_stat_lines], XSTR( "Primary friendly hit %:", 56));
if (stats->p_bonehead_hits > 0) {
f = (float) stats->p_bonehead_hits * 100.0f / (float) stats->p_shots_fired;
} else {
f = 0.0f;
}
sprintf(Stats[Num_stat_lines], XSTR( "%.1f%%", 55), f);
Num_stat_lines++;
Assert(Num_stat_lines < NUM_STAT_LINES);
Stat_labels[Num_stat_lines][0] = 0;
Stats[Num_stat_lines][0] = 0;
Num_stat_lines++;
Assert(Num_stat_lines < NUM_STAT_LINES);
STRCPY1(Stat_labels[Num_stat_lines], XSTR( "Secondary weapon shots:", 57));
sprintf(Stats[Num_stat_lines], "%d", stats->s_shots_fired);
Num_stat_lines++;
Assert(Num_stat_lines < NUM_STAT_LINES);
STRCPY1(Stat_labels[Num_stat_lines], XSTR( "Secondary weapon hits:", 58));
sprintf(Stats[Num_stat_lines], "%d", stats->s_shots_hit);
Num_stat_lines++;
Assert(Num_stat_lines < NUM_STAT_LINES);
STRCPY1(Stat_labels[Num_stat_lines], XSTR( "Secondary friendly hits:", 59));
sprintf(Stats[Num_stat_lines], "%d", stats->s_bonehead_hits);
Num_stat_lines++;
Assert(Num_stat_lines < NUM_STAT_LINES);
STRCPY1(Stat_labels[Num_stat_lines], XSTR( "Secondary hit %:", 60));
if (stats->s_shots_fired > 0) {
f = (float) stats->s_shots_hit * 100.0f / (float) stats->s_shots_fired;
} else {
f = 0.0f;
}
sprintf(Stats[Num_stat_lines], XSTR( "%.1f%%", 55), f);
Num_stat_lines++;
Assert(Num_stat_lines < NUM_STAT_LINES);
STRCPY1(Stat_labels[Num_stat_lines], XSTR( "Secondary friendly hit %:", 61));
if (stats->s_bonehead_hits > 0) {
f = (float) stats->s_bonehead_hits * 100.0f / (float) stats->s_shots_fired;
} else {
f = 0.0f;
}
sprintf(Stats[Num_stat_lines], XSTR( "%.1f%%", 55), f);
Num_stat_lines++;
Assert(Num_stat_lines < NUM_STAT_LINES);
Stat_labels[Num_stat_lines][0] = 0;
Stats[Num_stat_lines][0] = 0;
Num_stat_lines++;
Assert(Num_stat_lines < NUM_STAT_LINES);
STRCPY1(Stat_labels[Num_stat_lines], XSTR( "Total kills:", 62));
sprintf(Stats[Num_stat_lines], "%d", stats->kill_count_ok);
Num_stat_lines++;
Assert(Num_stat_lines < NUM_STAT_LINES);
STRCPY1(Stat_labels[Num_stat_lines], XSTR( "Assists:", 63));
sprintf(Stats[Num_stat_lines], "%d", stats->assists);
Num_stat_lines++;
Assert(Num_stat_lines < NUM_STAT_LINES);
Stat_labels[Num_stat_lines][0] = 0;
Stats[Num_stat_lines][0] = 0;
Num_stat_lines++;
Assert(Num_stat_lines < NUM_STAT_LINES);
Stat_labels[Num_stat_lines][0] = 0;
Stats[Num_stat_lines][0] = 0;
Num_stat_lines++;
STRCPY1(Stat_labels[Num_stat_lines], XSTR( "*Kills by Ship Type", 64));
Stats[Num_stat_lines][0] = 0;
Num_stat_lines++;
Assert(Num_stat_lines < NUM_STAT_LINES);
Stat_labels[Num_stat_lines][0] = 0;
Stats[Num_stat_lines][0] = 0;
Num_stat_lines++;
// Goober5000 - make sure we have room for all ships
Assert(Num_stat_lines + Num_ship_types < NUM_STAT_LINES);
for (i=0; i<Num_ship_types; i++) {
if (stats->kills[i]) {
Assert(Num_stat_lines < NUM_STAT_LINES);
// Goober5000 - in case above Assert isn't triggered (such as in non-debug builds)
if (Num_stat_lines >= NUM_STAT_LINES)
{
break;
}
Assert(strlen(Ship_info[i].name) + 1 < STAT_COLUMN1_W);
sprintf(Stat_labels[Num_stat_lines], NOX("%s:"), Ship_info[i].name);
sprintf(Stats[Num_stat_lines], "%d", stats->kills[i]);
Num_stat_lines++;
}
}
for (i=0; i<Num_stat_lines; i++) {
gr_force_fit_string(Stat_labels[i], Stat_column1_w[gr_screen.res], Barracks_stats_coords[gr_screen.res][BARRACKS_W_COORD]);
gr_force_fit_string(Stats[i], Stat_column2_w[gr_screen.res], Barracks_stats2_coords[gr_screen.res][BARRACKS_W_COORD]);
}
}
void display_pilot_stats()
{
int y = 0;
int z = Stats_scroll_offset;
int font_height = gr_get_font_height();
char *str;
int i, w, h;
while (y + font_height <= Barracks_stats_coords[gr_screen.res][BARRACKS_H_COORD]) {
if (z >= Num_stat_lines) {
break;
}
str = Stat_labels[z];
if (*str == '*') {
gr_set_color_fast(&Color_text_heading);
str++;
gr_get_string_size(&w, &h, str);
i = Barracks_stats_coords[gr_screen.res][BARRACKS_Y_COORD] + y + h / 2 - 1;
gr_line(Barracks_stats_coords[gr_screen.res][BARRACKS_X_COORD], i, Barracks_stats_coords[gr_screen.res][BARRACKS_X_COORD] + Barracks_stats_coords[gr_screen.res][BARRACKS_W_COORD] - w - 2, i,true);
gr_line(Barracks_stats_coords[gr_screen.res][BARRACKS_X_COORD] + Barracks_stats_coords[gr_screen.res][BARRACKS_W_COORD] + 1, i, Barracks_stats2_coords[gr_screen.res][BARRACKS_X_COORD] + Barracks_stats2_coords[gr_screen.res][BARRACKS_W_COORD], i,true);
} else {
gr_set_color_fast(&Color_text_normal);
}
gr_get_string_size(&w, NULL, str);
gr_printf(Barracks_stats_coords[gr_screen.res][BARRACKS_X_COORD] + Barracks_stats_coords[gr_screen.res][BARRACKS_W_COORD] - w, Barracks_stats_coords[gr_screen.res][BARRACKS_Y_COORD] + y, "%s", str);
str = Stats[z];
if (*str) {
gr_printf(Barracks_stats2_coords[gr_screen.res][BARRACKS_X_COORD], Barracks_stats_coords[gr_screen.res][BARRACKS_Y_COORD] + y, "%s", str);
}
y += font_height;
z++;
}
}
void pilot_info_button_pressed(int n)
{
switch (n) {
case PI_EXIT_BUTTON:
gamesnd_play_iface(SND_SWITCH_SCREENS);
gameseq_post_event(GS_EVENT_PREVIOUS_STATE);
break;
}
}
void pilot_info_init(void)
{
// create interface
Ui_window.create(0, 0, gr_screen.max_w, gr_screen.max_h, 0);
Ui_window.set_mask_bmap(PilotStats_bitmap_mask_fname[gr_screen.res]);
// load background bitmap
Background_bitmap = bm_load(PilotStats_bitmap_fname[gr_screen.res]);
if(Background_bitmap < 0){
// we failed to load the bitmap - this is very bad
Int3();
}
for (int i=0; i<PI_NUM_BUTTONS; i++) {
// create the object
Buttons[gr_screen.res][i].button.create(&Ui_window, "", Buttons[gr_screen.res][i].x, Buttons[gr_screen.res][i].y, 60, 30, Buttons[gr_screen.res][i].repeat, 1);
// set the sound to play when highlighted
Buttons[gr_screen.res][i].button.set_highlight_action(common_play_highlight_sound);
// set the ani for the button
Buttons[gr_screen.res][i].button.set_bmaps(Buttons[gr_screen.res][i].filename);
// set the hotspot
Buttons[gr_screen.res][i].button.link_hotspot(Buttons[gr_screen.res][i].hotspot);
}
init_pilot_stats(&Cur_pilot->stats);
}
void pilot_info_do(float frametime)
{
int k = Ui_window.process();
switch (k)
{
case KEY_ESC: // cancel
gameseq_post_event(GS_EVENT_PREVIOUS_STATE);//GS_EVENT_PREVIOUS_STATE
break;
} // end switch
for (int i=0; i<PI_NUM_BUTTONS; i++) {
if (Buttons[gr_screen.res][i].button.pressed()) {
pilot_info_button_pressed(i);
}
}
gr_reset_clip();
GR_MAYBE_CLEAR_RES(Background_bitmap);
if (Background_bitmap >= 0) {
gr_set_bitmap(Background_bitmap);
gr_bitmap(0, 0);
}
Ui_window.draw();
// draw title
char *str = NULL;
int x, y = 16;
int w,h;
x = strlen(Player->callsign);
str = (char *)malloc(x+y+1);
strcpy(str, Player->callsign);
strcat(str, "\'s Combat Record");
gr_get_string_size(&w, &h, str);
gr_set_color_fast(&Color_bright_white);
gr_string((gr_screen.max_w - w)/2, //Pilot_info_title_coords[gr_screen.res][BARRACKS_X_COORD],
Pilot_info_title_coords[gr_screen.res][BARRACKS_Y_COORD],
str);
display_pilot_stats();
gr_flip();
}
void pilot_info_close(void)
{
// destroy window
Ui_window.destroy();
// release background bitmap
if (Background_bitmap >= 0) {
bm_unload(Background_bitmap);
}
// unload the overlay bitmap
//help_overlay_unload(BARRACKS_OVERLAY);
game_flush();
} | [
"[email protected]"
]
| [
[
[
1,
427
]
]
]
|
4a86d145cda053787ed793b6cc237342d1c27e40 | 299a1b0fca9e1de3858a5ebeaf63be6dc3a02b48 | /tags/ic2005demo/nanobots/src/demo/map/GameMap.cpp | 7b13d40607ca6648676cc16602a0777039352104 | []
| no_license | BackupTheBerlios/dingus-svn | 331d7546a6e7a5a3cb38ffb106e57b224efbf5df | 1223efcf4c2079f58860d7fa685fa5ded8f24f32 | refs/heads/master | 2016-09-05T22:15:57.658243 | 2006-09-02T10:10:47 | 2006-09-02T10:10:47 | 40,673,143 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,853 | cpp | #include "stdafx.h"
#include "GameMap.h"
#include "../GameInfo.h"
#include "../ZipReader.h"
#include "../DemoResources.h"
#include "../game/GameColors.h"
#include <dingus/utils/Random.h>
#include <dingus/resource/TextureCreator.h>
#include <boost/crc.hpp>
// --------------------------------------------------------------------------
CGameMap::SPoint::SPoint( ePointType atype, int ax, int ay, int d )
: type(atype), x(ax), y(ay), data(d)
{
switch( type ) {
case PT_AZN:
colorMain = gColors.ptAZN.main.c;
colorTone = gColors.ptAZN.tone.c;
break;
case PT_HOSHIMI:
colorMain = gColors.ptHoshimi.main.c;
colorTone = gColors.ptHoshimi.tone.c;
break;
case PT_INJECTION:
colorMain = gColors.team[data].main.c;
colorTone = gColors.team[data].tone.c;
break;
}
}
// --------------------------------------------------------------------------
class CGameMapTextureCreator : public CFixedTextureCreator {
public:
CGameMapTextureCreator() : CFixedTextureCreator( 256, 256, 0, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED )
{
}
virtual IDirect3DTexture9* createTexture() {
IDirect3DTexture9* tex = CFixedTextureCreator::createTexture();
// create the offscreen surface
HRESULT hr;
const CGameMap& gmap = CGameInfo::getInstance().getGameMap();
CD3DDevice& dx = CD3DDevice::getInstance();
IDirect3DSurface9* srcSurf = 0;
hr = dx.getDevice().CreateOffscreenPlainSurface( gmap.getCellsX(), gmap.getCellsY(), D3DFMT_A8R8G8B8, D3DPOOL_SCRATCH, &srcSurf, NULL );
assert( SUCCEEDED(hr) );
D3DLOCKED_RECT lr;
srcSurf->LockRect( &lr, NULL, D3DLOCK_DISCARD );
const char* linePtr = (const char*)lr.pBits;
for( int y = 0; y < gmap.getCellsY(); ++y ) {
D3DCOLOR* p = (D3DCOLOR*)linePtr;
for( int x = 0; x < gmap.getCellsX(); ++x ) {
const CGameMap::SCell& cell = gmap.getCell(x,y);
switch( cell.type ) {
case CELL_BLOOD1: *p = 0xFF400000; break;
case CELL_BLOOD2: *p = 0xFF300000; break;
case CELL_BLOOD3: *p = 0xFF200000; break;
default: *p = 0x00000000; break;
}
++p;
}
linePtr += lr.Pitch;
}
srcSurf->UnlockRect();
// now, filter this into the texture
IDirect3DSurface9* dstSurf = 0;
hr = tex->GetSurfaceLevel( 0, &dstSurf );
assert( SUCCEEDED(hr) );
hr = D3DXLoadSurfaceFromSurface( dstSurf, NULL, NULL, srcSurf, NULL, NULL, D3DX_FILTER_BOX, 0 );
dstSurf->Release();
srcSurf->Release();
D3DXFilterTexture( tex, NULL, 0, D3DX_FILTER_BOX );
return tex;
}
};
// --------------------------------------------------------------------------
CGameMap::CGameMap()
: mCellsX(0), mCellsY(0), mCells(NULL), mCRC(0)
{
}
CGameMap::~CGameMap()
{
safeDeleteArray( mCells );
}
std::string CGameMap::initialize( const std::string& fileName, const std::string& mapName )
{
mName = mapName;
assert( !mCells );
//
// open zip file
unzFile zipFile = unzOpen( fileName.c_str() );
if( zipFile == NULL )
return "Game map file '" + fileName + "' not found or is corrupt";
//
// read level bitmap
int bmpSize;
char* bmpFile = gReadFileInZip( zipFile, "map.bmp", bmpSize );
if( !bmpFile ) {
unzClose( zipFile );
return "Error in game map file '" + fileName + "' - no cells map";
}
// compute CRC of the bitmap
mCRC = boost::crc<32,0xFFFFFFFF,0,0,false,false>( bmpFile, bmpSize );
HRESULT hr;
D3DXIMAGE_INFO bitmapInfo;
hr = D3DXGetImageInfoFromFileInMemory( bmpFile, bmpSize, &bitmapInfo );
if( FAILED(hr) ) {
unzClose( zipFile );
return "Error in game map file '" + fileName + "' - incorrect cells map format";
}
assert( bitmapInfo.Width > 10 && bitmapInfo.Height > 10 );
assert( bitmapInfo.Width * bitmapInfo.Height <= 256*256 );
if( bitmapInfo.Width < 10 || bitmapInfo.Height < 10 ) {
unzClose( zipFile );
return "Error in game map file '" + fileName + "' - map is too small";
}
if( bitmapInfo.Width * bitmapInfo.Height > 256*256 ) {
unzClose( zipFile );
return "Error in game map file '" + fileName + "' - map is too large";
}
mCellsX = bitmapInfo.Width;
mCellsY = bitmapInfo.Height;
mCells = new SCell[ mCellsX * mCellsY ];
CD3DDevice& dx = CD3DDevice::getInstance();
IDirect3DSurface9* surface = 0;
hr = dx.getDevice().CreateOffscreenPlainSurface( bitmapInfo.Width, bitmapInfo.Height, D3DFMT_A8R8G8B8, D3DPOOL_SCRATCH, &surface, NULL );
assert( SUCCEEDED(hr) );
hr = D3DXLoadSurfaceFromFileInMemory( surface, NULL, NULL, bmpFile, bmpSize, NULL, D3DX_DEFAULT, 0, NULL );
if( FAILED(hr) ) {
unzClose( zipFile );
return "Error in game map file '" + fileName + "' - incorrect cells map format";
}
D3DLOCKED_RECT lr;
surface->LockRect( &lr, NULL, D3DLOCK_READONLY );
const char* linePtr = (const char*)lr.pBits;
for( int y = 0; y < mCellsY; ++y ) {
const D3DCOLOR* p = (const D3DCOLOR*)linePtr;
for( int x = 0; x < mCellsX; ++x ) {
SCell& cell = mCells[y*mCellsX+x];
switch( *p ) {
case 0xFFff0000: cell.type = CELL_BLOOD1; break;
case 0xFF00ff00: cell.type = CELL_BLOOD2; break;
case 0xFF0000ff: cell.type = CELL_BLOOD3; break;
case 0xFFc0c0c0: cell.type = CELL_PERF; break;
default: cell.type = CELL_BONE; break;
}
cell.height = MIN_CELL_HEIGHT;
cell.nearBone = true;
++p;
}
linePtr += lr.Pitch;
}
surface->UnlockRect();
surface->Release();
delete[] bmpFile;
//
// read special points
int ptsSize;
char* ptsFile = gReadFileInZip( zipFile, "entities.txt", ptsSize );
if( !ptsFile ) {
unzClose( zipFile );
return "Error in game map file '" + fileName + "' - no entities info";
}
const char* tokens = "\n\r";
const char* pline = strtok( (char*)gSkipUTFStart( ptsFile, ptsSize ), tokens );
do {
if( !pline )
break;
int etype, eposx, eposy;
int fread = sscanf( pline, "%i:%i:%i", &etype, &eposx, &eposy );
if( fread != 3 )
break;
mPoints.push_back( SPoint(ePointType(etype), eposx, eposy ) );
} while( pline = strtok( NULL, tokens ) );
delete[] ptsFile;
//
// close zip file
unzClose( zipFile );
//
// calc cell heights
calcCellHeights();
//
// register level texture
CSharedTextureBundle::getInstance().registerTexture( RID_TEX_LEVEL, *new CGameMapTextureCreator() );
return ""; // all ok!
}
void CGameMap::calcCellHeights()
{
CRandomFast rnd;
const int NEIGHBOUR_X[8] = { -1, 0, 1, -1, 1, -1, 0, 1 };
const int NEIGHBOUR_Y[8] = { -1, -1, -1, 0, 0, 1, 1, 1 };
int idx = 0;
for( int y = 0; y < mCellsY; ++y ) {
for( int x = 0; x < mCellsX; ++x, ++idx ) {
if( !isBlood( mCells[idx].type ) )
continue;
// see if any of 8-neighbors is a bone
bool nearBone = false;
if( x < 1 || x >= mCellsX-1 || y < 1 || y >= mCellsY-1 )
nearBone = true;
else {
for( int i = 0; i < 8; ++i ) {
int nidx = idx + NEIGHBOUR_Y[i]*mCellsX + NEIGHBOUR_X[i];
if( !isCellBlood(nidx) ) {
nearBone = true;
break;
}
}
}
mCells[idx].nearBone = nearBone;
const int SAMPLING_R = 20;
int emptyR = 0;
for( int r = 1; r < SAMPLING_R; ++r ) {
const int samples = round( 2*D3DX_PI*r * 0.25f );
float dphi = 2*D3DX_PI / samples;
float phi = gRandom.getFloat( dphi );
bool empty = true;
for( int i = 0; i < samples; ++i, phi += dphi ) {
int px = round( x + cosf(phi) * r );
int py = round( y + sinf(phi) * r );
if( px < 0 || py < 0 || px >= mCellsX || py >= mCellsY ) {
empty = false;
break;
}
if( !isCellBlood(py*mCellsX+px) ) {
empty = false;
break;
}
}
if( !empty )
break;
++emptyR;
}
mCells[idx].height += (1-powf(1-(float)emptyR/SAMPLING_R, 2)) * SAMPLING_R * 0.2f;
}
}
}
| [
"nearaz@73827abb-88f4-0310-91e6-a2b8c1a3e93d"
]
| [
[
[
1,
279
]
]
]
|
47889c56d3a96afedff3735e7caf5e4b6226178a | ad8046a7c792e31fab898fa13a7693ff34ef2b83 | /eFilm/CustomeMessageExample/AUTOCLIENT/eFilmAutoClient.cpp | dec04e7c607e56915638df0dadbacf188aa5220d | []
| no_license | alibinjamil/datamedris | df5f205775e78b76f15155c27e316f81beba1660 | 3f4711ef3c43e21870261bfbcab7fbafd369e114 | refs/heads/master | 2016-08-12T06:06:00.915112 | 2010-12-22T08:47:14 | 2010-12-22T08:47:14 | 44,970,197 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,534 | cpp | // eFilmAutoClient.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "eFilmAutoClient.h"
#include "eFilmAutoClientDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CEFilmAutoClientApp
BEGIN_MESSAGE_MAP(CEFilmAutoClientApp, CWinApp)
//{{AFX_MSG_MAP(CEFilmAutoClientApp)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG
ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CEFilmAutoClientApp construction
CEFilmAutoClientApp::CEFilmAutoClientApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
/////////////////////////////////////////////////////////////////////////////
// The one and only CEFilmAutoClientApp object
CEFilmAutoClientApp theApp;
/////////////////////////////////////////////////////////////////////////////
// CEFilmAutoClientApp initialization
BOOL CEFilmAutoClientApp::InitInstance()
{
// Initialize OLE libraries
if (!AfxOleInit())
{
AfxMessageBox(IDP_OLE_INIT_FAILED);
return FALSE;
}
AfxEnableControlContainer();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need.
#ifdef _AFXDLL
Enable3dControls(); // Call this when using MFC in a shared DLL
#else
Enable3dControlsStatic(); // Call this when linking to MFC statically
#endif
// Parse the command line to see if launched as OLE server
if (RunEmbedded() || RunAutomated())
{
// Register all OLE server (factories) as running. This enables the
// OLE libraries to create objects from other applications.
COleTemplateServer::RegisterAll();
}
else
{
// When a server application is launched stand-alone, it is a good idea
// to update the system registry in case it has been damaged.
COleObjectFactory::UpdateRegistryAll();
}
CEFilmAutoClientDlg dlg;
m_pMainWnd = &dlg;
dlg.DoModal();
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
| [
"[email protected]"
]
| [
[
[
1,
87
]
]
]
|
3e6d399978ede1608cbc8b456bac7f08db01dd6a | 3187b0dd0d7a7b83b33c62357efa0092b3943110 | /src/dlib/gui_core/gui_core_kernel_1.h | 38de8fff6966e00eef0b44165aa73ade3f423698 | [
"BSL-1.0"
]
| permissive | exi/gravisim | 8a4dad954f68960d42f1d7da14ff1ca7a20e92f2 | 361e70e40f58c9f5e2c2f574c9e7446751629807 | refs/heads/master | 2021-01-19T17:45:04.106839 | 2010-10-22T09:11:24 | 2010-10-22T09:11:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,502 | h | // Copyright (C) 2005 Davis E. King ([email protected])
// License: Boost Software License See LICENSE.txt for the full license.
#ifndef DLIB_GUI_CORE_KERNEl_1_
#define DLIB_GUI_CORE_KERNEl_1_
#ifdef DLIB_ISO_CPP_ONLY
#error "DLIB_ISO_CPP_ONLY is defined so you can't use this OS dependent code. Turn DLIB_ISO_CPP_ONLY off if you want to use it."
#endif
#ifdef DLIB_NO_GUI_SUPPORT
#error "DLIB_NO_GUI_SUPPORT is defined so you can't use the GUI code. Turn DLIB_NO_GUI_SUPPORT off if you want to use it."
#endif
#include <string>
#include "../windows_magic.h"
#include <windows.h>
#include <winuser.h>
#include <windowsx.h>
#include <commctrl.h>
#include "gui_core_kernel_abstract.h"
#ifdef _MSC_VER
// Disable the following warnings for Visual Studio
//
// These two warnings have to do with converting points to and from the LONG
// type. But both these types are 32 bits in windows so it is fine.
#pragma warning(disable: 4244; disable: 4312)
#endif
#include "../algs.h"
#include "../sync_extension.h"
#include "../binary_search_tree.h"
#include "../threads.h"
#include "../geometry/rectangle.h"
#include "../assert.h"
#include "../queue.h"
#include "../pixel.h"
namespace dlib
{
// ----------------------------------------------------------------------------------------
class base_window;
namespace gui_core_kernel_1_globals
{
LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM);
}
// ----------------------------------------------------------------------------------------
class canvas : public rectangle
{
public:
struct pixel
{
unsigned char blue;
unsigned char green;
unsigned char red;
};
~canvas() { }
inline pixel* operator[] (
unsigned long row
) const
{
DLIB_ASSERT(row < height(),
"\tpixel* canvas::operator[]"
<< "\n\tyou have to give a row that is less than the height()"
<< "\n\tthis: " << this
<< "\n\trow: " << row
<< "\n\theight(): " << height()
);
unsigned char* temp = bits + row_width*row;
return reinterpret_cast<pixel*>(temp);
}
void fill (
unsigned char red_,
unsigned char green_,
unsigned char blue_
) const;
private:
friend LRESULT CALLBACK gui_core_kernel_1_globals::WndProc (HWND, UINT, WPARAM, LPARAM);
canvas (
unsigned char* bits__,
unsigned long padding__,
unsigned long left__,
unsigned long top__,
unsigned long right__,
unsigned long bottom__
) :
rectangle(left__,top__,right__,bottom__),
bits(bits__),
width_(width()),
height_(height()),
row_width(width_*3+padding__)
{}
// restricted functions
canvas(); // normal constructor
canvas(canvas&); // copy constructor
canvas& operator=(canvas&); // assignment operator
unsigned char* const bits;
const unsigned long width_;
const unsigned long height_;
const unsigned long row_width;
};
template <>
struct pixel_traits<canvas::pixel>
{
const static bool rgb = true;
const static bool rgb_alpha = false;
const static bool grayscale = false;
const static bool hsi = false;
const static long num = 3;
static unsigned long max() { return 255;}
const static bool has_alpha = false;
};
// ----------------------------------------------------------------------------------------
void put_on_clipboard (
const std::string& str
);
// ----------------------------------------------------------------------------------------
void get_from_clipboard (
std::string& str
);
// ----------------------------------------------------------------------------------------
class base_window
{
friend LRESULT CALLBACK gui_core_kernel_1_globals::WndProc (HWND, UINT, WPARAM, LPARAM);
HWND hwnd;
DWORD style;
bool has_been_destroyed;
// This is true if the mouse is in this window. false otherwise.
// also note that this variable is only accessed from the event handling thread
// (except for being initialized below in the constructor, but that is inside
// the window_table mutex so it doesn't matter).
bool mouse_in;
// this is a copy of the last inputs we sent to the on_mouse_move() event.
long prevx;
long prevy;
long prev_state;
protected:
const rmutex& wm;
public:
base_window (
bool resizable = true,
bool undecorated = false
);
virtual ~base_window (
);
void close_window (
);
bool is_closed (
) const;
void set_title (
const std::string& title
);
virtual void show (
);
virtual void hide(
);
void set_size (
int width_,
int height_
);
void set_pos (
long x_,
long y_
);
void get_pos (
long& x_,
long& y_
);
void get_size (
unsigned long& width,
unsigned long& height
) const;
void get_display_size (
unsigned long& width,
unsigned long& height
) const;
void invalidate_rectangle (
const rectangle& rect
);
void trigger_user_event (
void* p,
int i
);
void wait_until_closed (
) const;
enum on_close_return_code
{
DO_NOT_CLOSE_WINDOW,
CLOSE_WINDOW
};
enum mouse_state_masks
{
NONE = 0,
LEFT = 1,
RIGHT = 2,
MIDDLE = 4,
SHIFT = 8,
CONTROL = 16
};
enum keyboard_state_masks
{
KBD_MOD_NONE = 0,
KBD_MOD_SHIFT = 1,
KBD_MOD_CONTROL = 2,
KBD_MOD_ALT = 4,
KBD_MOD_META = 8,
KBD_MOD_CAPS_LOCK = 16,
KBD_MOD_NUM_LOCK = 32,
KBD_MOD_SCROLL_LOCK = 64
};
enum non_printable_keyboard_keys
{
KEY_BACKSPACE,
KEY_SHIFT,
KEY_CTRL,
KEY_ALT,
KEY_PAUSE,
KEY_CAPS_LOCK,
KEY_ESC,
KEY_PAGE_UP,
KEY_PAGE_DOWN,
KEY_END,
KEY_HOME,
KEY_LEFT, // This is the left arrow key
KEY_RIGHT, // This is the right arrow key
KEY_UP, // This is the up arrow key
KEY_DOWN, // This is the down arrow key
KEY_INSERT,
KEY_DELETE,
KEY_SCROLL_LOCK,
// Function Keys
KEY_F1,
KEY_F2,
KEY_F3,
KEY_F4,
KEY_F5,
KEY_F6,
KEY_F7,
KEY_F8,
KEY_F9,
KEY_F10,
KEY_F11,
KEY_F12
};
protected:
virtual on_close_return_code on_window_close(
){return CLOSE_WINDOW;}
virtual void on_user_event (
void* p,
int i
){}
virtual void on_window_resized(
){}
virtual void on_window_moved(
){}
virtual void on_mouse_down (
unsigned long btn,
unsigned long state,
long x,
long y,
bool is_double_click
){}
virtual void on_mouse_up (
unsigned long btn,
unsigned long state,
long x,
long y
){}
virtual void on_mouse_move (
unsigned long state,
long x,
long y
){}
virtual void on_mouse_leave (
){}
virtual void on_mouse_enter (
){}
virtual void on_wheel_up (
){}
virtual void on_wheel_down (
){}
virtual void on_focus_gained (
){}
virtual void on_focus_lost (
){}
virtual void on_keydown (
unsigned long key,
bool is_printable,
unsigned long state
){}
private:
virtual void paint (
const canvas& c
) =0;
base_window(base_window&); // copy constructor
base_window& operator=(base_window&); // assignment operator
};
// ----------------------------------------------------------------------------------------
}
#ifdef NO_MAKEFILE
#include "gui_core_kernel_1.cpp"
#endif
#endif // DLIB_GUI_CORE_KERNEl_1_
| [
"[email protected]"
]
| [
[
[
1,
378
]
]
]
|
8faf3685ec084790bf4595896044eff5b70d5dc3 | 26706a661c23f5c2c1f97847ba09f44b7b425cf6 | /TaskManager/XTabCtrl.h | 0908165d08c0a93f6025fb55585533e065c79f9f | []
| no_license | 124327288/nativetaskmanager | 96a54dbe150f855422d7fd813d3631eaac76fadd | e75b3d9d27c902baddbb1bef975c746451b1b8bb | refs/heads/master | 2021-05-29T05:18:26.779900 | 2009-02-10T13:23:28 | 2009-02-10T13:23:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,415 | h | #if !defined(AFX_XTABCTRL_H__A11951B3_2F95_11D3_A896_00A0C9B6FB28__INCLUDED_)
#define AFX_XTABCTRL_H__A11951B3_2F95_11D3_A896_00A0C9B6FB28__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// XTabCtrl.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CXTabCtrl window
#include <afxtempl.h>
class CXTabCtrl : public CTabCtrl
{
// Construction
public:
CXTabCtrl();
// Attributes
public:
// Operations
public:
void AddTab(CWnd* pWnd, LPTSTR lpszCaption, int iImage =0);
void EnableTab(int iIndex, BOOL bEnable = TRUE);
BOOL SelectTab(int iIndex);
void DeleteAllTabs();
void DeleteTab(int iIndex);
void SetTopLeftCorner(CPoint pt);
BOOL IsTabEnabled(int iIndex);
void SetDisabledColor(COLORREF cr);
void SetSelectedColor(COLORREF cr);
void SetNormalColor(COLORREF cr);
void SetMouseOverColor(COLORREF cr);
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CXTabCtrl)
protected:
virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);
virtual void PreSubclassWindow();
//}}AFX_VIRTUAL
// Implementation
public:
BOOL SelectNextTab(BOOL bForward);
BOOL SelectTabByName(LPCTSTR lpszTabCaption);
void ChangeTab(int iIndex, CWnd* pNewTab, LPTSTR lpszCaption, int iImage);
virtual ~CXTabCtrl();
// Generated message map functions
protected:
CArray<BOOL, BOOL> m_arrayStatusTab; //** enabled Y\N
int m_iSelectedTab;
POINT m_ptTabs;
COLORREF m_crSelected;
COLORREF m_crDisabled;
COLORREF m_crNormal;
COLORREF m_crMouseOver;
int m_iIndexMouseOver;
bool m_bMouseOver;
bool m_bColorMouseOver;
bool m_bColorNormal;
bool m_bColorDisabled;
bool m_bColorSelected;
public:
DECLARE_MESSAGE_MAP()
//{{AFX_MSG(CXTabCtrl)
afx_msg void OnSelchange(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnSelchanging(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg void OnTimer(UINT nIDEvent);
afx_msg void OnSize(UINT nType, int cx, int cy);
//}}AFX_MSG
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_XTABCTRL_H__A11951B3_2F95_11D3_A896_00A0C9B6FB28__INCLUDED_)
| [
"[email protected]@97a26042-f463-11dd-a7be-4b3ef3b0700c"
]
| [
[
[
1,
90
]
]
]
|
d3f8148efdb10aa3af69fd738f6928eddfe7b06f | 69aab86a56c78cdfb51ab19b8f6a71274fb69fba | /Code/inc/Engine/Material.h | a9548279c8c83898407bcff30b207a06015c73cd | [
"BSD-3-Clause"
]
| permissive | zc5872061/wonderland | 89882b6062b4a2d467553fc9d6da790f4df59a18 | b6e0153eaa65a53abdee2b97e1289a3252b966f1 | refs/heads/master | 2021-01-25T10:44:13.871783 | 2011-08-11T20:12:36 | 2011-08-11T20:12:36 | 38,088,714 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,703 | h | /*
* Material.h
*
* Created on: 2011-02-13
* Author: Artur
*/
#ifndef MATERIAL_H_
#define MATERIAL_H_
#include <string>
#include <vector>
#include "Program.h"
#include "MathHelper.h"
// Class which is intended to abstract a material i.e. a pair of shaders + their possible variables.
// It is intended to be rather heavy weight and only single instance of each shaders' combination should exist.
// MaterialInstance is the light-weight class which holds specific config variables for materials.
class Material
{
public:
friend class MaterialsManager;
static const int GL_INVALID_LOCATION = -1;
// Note: when changing this enumeration be sure to also check the change value family!
enum MaterialVariables
{
MV_POSITION, // attribute - holds position information, must be filled to have objects properly rendered, requires stride 3 data
MV_NORMAL, // attribute - holds normal informations, requires stride 3 data
MV_UV, // attribute - holds uv information, requires stride 2 data
MV_MODEL_VIEW_PROJECTION, // uniform which holds model-view-projection matrix
MV_MODEL, // uniform which holds model matrix
MV_CAMERA_POS, // uniform with the camera position
MV_LIGHT_DIRECTION, // uniform with the light direction for directional lighting
MV_ENUMERATION_SIZE
};
Program* getProgram() { return m_program; }
// Returns if the specified variable exists in the underlying program
bool isVariableValid(MaterialVariables id) { return m_locations[id].location != GL_INVALID_LOCATION; }
// Disables the attribute arrey specified by the id can be either position, normal or uv
void disableAttribute(MaterialVariables id);
// This method is a bit funny, because it checks if the argument is in range
// and then calls another proper method. This is for convenience.
template <typename DataT>
bool setValue(MaterialVariables id, const DataT& data);
// This one should be used for material-specific variables, i.e. those that are marked in
// the <config> section
template <typename DataT>
bool setValue(const std::string& var, const DataT& data);
void setName(const std::string& name) { m_name = name; }
const std::string& getName() const { return m_name; }
private:
// This POD structure holds information about the size of
// the variable that is associated with this location. This is required
// to make setting up vector variables in program working correctly
struct LocationInfo
{
GLint location;
size_t size;
};
Program* m_program;
LocationInfo m_locations[MV_ENUMERATION_SIZE];
std::string m_name;
// Used to print variables that are set by material by material instances
// but does not exist in the effect file (or at least weren't mapped to GLint)
static std::vector<std::string> s_warningVariables;
// Non typical variables which are specific for one material need
// to be expressed by strings to achieve some flexibility
typedef std::map<std::string, LocationInfo> VariablesMap;
VariablesMap m_variables;
private:
void setAttribute(const LocationInfo& location, const float* data, int stride);
void setUniform(const LocationInfo& location, const Matrix& matrix);
void setUniform(const LocationInfo& location, const Vector& vector);
void setUniform(const LocationInfo& location, const std::string& textureName);
void setUniform(const LocationInfo& location, float value);
template<typename WrongCallT>
void setUniform(const LocationInfo&, const WrongCallT&) {assert(0);} //not implemented, here only for template/compilation error
template<typename WrongCallT>
void setAttribute(const LocationInfo&, const WrongCallT&, int) {assert(0);}
// registers a variable which should exist the program file
// It queries the underlying Program for location and later this variable
// can be referenced and used to set data
// Intended for use by the MaterialsManager
bool addVariable(const std::string& var, size_t size);
// Registers a location from the underlying program which should be
// mapped to one of the predefined engine variables (those found
// in the enumeration above).
// Intended for use by the engine
bool addVariable(const std::string& var, MaterialVariables id, size_t size);
void notInMap(const std::string& var);
void invalidLocation(const std::string& var);
Material(Program* program, const std::string& name);
~Material() {}
Material(const Material&);
Material& operator=(const Material&);
};
template <typename DataT>
bool Material::setValue(MaterialVariables id, const DataT& data)
{
LocationInfo location = m_locations[id];
if(location.location == GL_INVALID_LOCATION) return false;
switch(id)
{
case MV_POSITION:
case MV_NORMAL:
setAttribute(location, data, 3);
break;
case MV_UV:
setAttribute(location, data, 2);
break;
case MV_MODEL_VIEW_PROJECTION:
case MV_MODEL:
case MV_CAMERA_POS:
case MV_LIGHT_DIRECTION:
setUniform(location, data);
break;
default:
Log("Critical error - unknown id used in Material::setValue - %d", id);
assert(0);
}
return true;
}
template <typename DataT>
bool Material::setValue(const std::string& var, const DataT& data)
{
VariablesMap::iterator it = m_variables.find(var);
if(it == m_variables.end())
{
notInMap(var);
return false;
}
if(it->second.location == GL_INVALID_LOCATION)
{
invalidLocation(var);
return false;
}
setUniform(it->second, data);
return true;
}
#endif /* MATERIAL_H_ */
| [
"[email protected]"
]
| [
[
[
1,
159
]
]
]
|
d13f3dc641ab842ba38718709627d1f414f167f1 | 20c74d83255427dd548def97f9a42112c1b9249a | /src/roadfighter/roadfighter-interactive-object-manager.cpp | 859fab0d1d3f551ca4f57a6f5d853af81164c98e | []
| no_license | jonyzp/roadfighter | 70f5c7ff6b633243c4ac73085685595189617650 | d02cbcdcfda1555df836379487953ae6206c0703 | refs/heads/master | 2016-08-10T15:39:09.671015 | 2011-05-05T12:00:34 | 2011-05-05T12:00:34 | 54,320,171 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,536 | cpp | #include "roadfighter-interactive-object-manager.h"
RoadFighterInteractiveObjectManager::RoadFighterInteractiveObjectManager()
:InteractiveObjectManager()
{
carObjects.clear();
otherObjects.clear();
carManager = new CarManager();
obstacleManager = new ObstaclesManager();
stageCompletedPerc = 0;
currentStage = 1;
}
RoadFighterInteractiveObjectManager::~RoadFighterInteractiveObjectManager()
{
}
void RoadFighterInteractiveObjectManager::init()
{
unsigned int i;
carManager->setCurrentStage(getCurrentStage());
carManager->init();
for(i = 0; i < carManager->cars.size(); i++)
{
carObjects.push_back(carManager->cars.at(i));
}
obstacleManager->init();
for(i = 0; i < obstacleManager->obstacles.size(); i++)
{
otherObjects.push_back(obstacleManager->obstacles.at(i));
}
//lprintf("num of object inside rf manager are %d\n",objects.size());
}
void RoadFighterInteractiveObjectManager::spawn()
{
//carManager->spawn();
//obstacleManager->spawn();
}
void RoadFighterInteractiveObjectManager::reinit()
{
carObjects.clear();
otherObjects.clear();
carManager->setCurrentStage(getCurrentStage());
carManager->reinit();
init();
}
void RoadFighterInteractiveObjectManager::display()
{
carManager->display();
obstacleManager->display();
}
void RoadFighterInteractiveObjectManager::update()
{
carManager->update();
obstacleManager->update();
carManager->checkCollision(otherObjects);
carManager->checkCollision(carObjects);
if(carManager->isCanSpawnNewCars())
{
carManager->spawn();
}
if(getCurrentStage() == ROADFIGHTER_STAGE_3 && getCurrentStage() == ROADFIGHTER_STAGE_4)
{
if(getStageCompletedPercentage() % 25 == 0)
{
carManager->spawnBonusCar();
}
}
else
{
if(getStageCompletedPercentage() % 33 == 0)
{
carManager->spawnBonusCar();
}
}
if(getCurrentStage() != ROADFIGHTER_STAGE_1)
{
if(getStageCompletedPercentage() % 25 == 0)
{
carManager->spawnTruckCar();
}
}
}
void RoadFighterInteractiveObjectManager::cleanup()
{
}
void RoadFighterInteractiveObjectManager::setStageCompletedPercentage(int percent)
{
stageCompletedPerc = percent;
}
int RoadFighterInteractiveObjectManager::getStageCompletedPercentage()
{
return stageCompletedPerc;
}
void RoadFighterInteractiveObjectManager::setCurrentStage(int current)
{
currentStage = current;
}
int RoadFighterInteractiveObjectManager::getCurrentStage()
{
return currentStage;
}
| [
"[email protected]"
]
| [
[
[
1,
121
]
]
]
|
e1092287115074606532ee06c4fdef4b5e2baa70 | eb8a27a2cc7307f0bc9596faa4aa4a716676c5c5 | /WinEdition/browser-lcc/jscc/src/v8/v8/src/x64/regexp-macro-assembler-x64.cc | 0ffa5d889e5c40150f8ed96f9e0da9daef2c54c8 | [
"BSD-3-Clause",
"bzip2-1.0.6",
"LicenseRef-scancode-public-domain",
"Artistic-2.0",
"Artistic-1.0"
]
| permissive | baxtree/OKBuzzer | c46c7f271a26be13adcf874d77a7a6762a8dc6be | a16e2baad145f5c65052cdc7c767e78cdfee1181 | refs/heads/master | 2021-01-02T22:17:34.168564 | 2011-06-15T02:29:56 | 2011-06-15T02:29:56 | 1,790,181 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 49,093 | cc | // Copyright 2011 the V8 project authors. 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 Google Inc. 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.
#include "v8.h"
#if defined(V8_TARGET_ARCH_X64)
#include "serialize.h"
#include "unicode.h"
#include "log.h"
#include "regexp-stack.h"
#include "macro-assembler.h"
#include "regexp-macro-assembler.h"
#include "x64/regexp-macro-assembler-x64.h"
namespace v8 {
namespace internal {
#ifndef V8_INTERPRETED_REGEXP
/*
* This assembler uses the following register assignment convention
* - rdx : currently loaded character(s) as ASCII or UC16. Must be loaded using
* LoadCurrentCharacter before using any of the dispatch methods.
* - rdi : current position in input, as negative offset from end of string.
* Please notice that this is the byte offset, not the character
* offset! Is always a 32-bit signed (negative) offset, but must be
* maintained sign-extended to 64 bits, since it is used as index.
* - rsi : end of input (points to byte after last character in input),
* so that rsi+rdi points to the current character.
* - rbp : frame pointer. Used to access arguments, local variables and
* RegExp registers.
* - rsp : points to tip of C stack.
* - rcx : points to tip of backtrack stack. The backtrack stack contains
* only 32-bit values. Most are offsets from some base (e.g., character
* positions from end of string or code location from Code* pointer).
* - r8 : code object pointer. Used to convert between absolute and
* code-object-relative addresses.
*
* The registers rax, rbx, r9 and r11 are free to use for computations.
* If changed to use r12+, they should be saved as callee-save registers.
* The macro assembler special registers r12 and r13 (kSmiConstantRegister,
* kRootRegister) aren't special during execution of RegExp code (they don't
* hold the values assumed when creating JS code), so no Smi or Root related
* macro operations can be used.
*
* Each call to a C++ method should retain these registers.
*
* The stack will have the following content, in some order, indexable from the
* frame pointer (see, e.g., kStackHighEnd):
* - Isolate* isolate (Address of the current isolate)
* - direct_call (if 1, direct call from JavaScript code, if 0 call
* through the runtime system)
* - stack_area_base (High end of the memory area to use as
* backtracking stack)
* - int* capture_array (int[num_saved_registers_], for output).
* - end of input (Address of end of string)
* - start of input (Address of first character in string)
* - start index (character index of start)
* - String* input_string (input string)
* - return address
* - backup of callee save registers (rbx, possibly rsi and rdi).
* - Offset of location before start of input (effectively character
* position -1). Used to initialize capture registers to a non-position.
* - At start of string (if 1, we are starting at the start of the
* string, otherwise 0)
* - register 0 rbp[-n] (Only positions must be stored in the first
* - register 1 rbp[-n-8] num_saved_registers_ registers)
* - ...
*
* The first num_saved_registers_ registers are initialized to point to
* "character -1" in the string (i.e., char_size() bytes before the first
* character of the string). The remaining registers starts out uninitialized.
*
* The first seven values must be provided by the calling code by
* calling the code's entry address cast to a function pointer with the
* following signature:
* int (*match)(String* input_string,
* int start_index,
* Address start,
* Address end,
* int* capture_output_array,
* bool at_start,
* byte* stack_area_base,
* bool direct_call)
*/
#define __ ACCESS_MASM((&masm_))
RegExpMacroAssemblerX64::RegExpMacroAssemblerX64(
Mode mode,
int registers_to_save)
: masm_(Isolate::Current(), NULL, kRegExpCodeSize),
no_root_array_scope_(&masm_),
code_relative_fixup_positions_(4),
mode_(mode),
num_registers_(registers_to_save),
num_saved_registers_(registers_to_save),
entry_label_(),
start_label_(),
success_label_(),
backtrack_label_(),
exit_label_() {
ASSERT_EQ(0, registers_to_save % 2);
__ jmp(&entry_label_); // We'll write the entry code when we know more.
__ bind(&start_label_); // And then continue from here.
}
RegExpMacroAssemblerX64::~RegExpMacroAssemblerX64() {
// Unuse labels in case we throw away the assembler without calling GetCode.
entry_label_.Unuse();
start_label_.Unuse();
success_label_.Unuse();
backtrack_label_.Unuse();
exit_label_.Unuse();
check_preempt_label_.Unuse();
stack_overflow_label_.Unuse();
}
int RegExpMacroAssemblerX64::stack_limit_slack() {
return RegExpStack::kStackLimitSlack;
}
void RegExpMacroAssemblerX64::AdvanceCurrentPosition(int by) {
if (by != 0) {
__ addq(rdi, Immediate(by * char_size()));
}
}
void RegExpMacroAssemblerX64::AdvanceRegister(int reg, int by) {
ASSERT(reg >= 0);
ASSERT(reg < num_registers_);
if (by != 0) {
__ addq(register_location(reg), Immediate(by));
}
}
void RegExpMacroAssemblerX64::Backtrack() {
CheckPreemption();
// Pop Code* offset from backtrack stack, add Code* and jump to location.
Pop(rbx);
__ addq(rbx, code_object_pointer());
__ jmp(rbx);
}
void RegExpMacroAssemblerX64::Bind(Label* label) {
__ bind(label);
}
void RegExpMacroAssemblerX64::CheckCharacter(uint32_t c, Label* on_equal) {
__ cmpl(current_character(), Immediate(c));
BranchOrBacktrack(equal, on_equal);
}
void RegExpMacroAssemblerX64::CheckCharacterGT(uc16 limit, Label* on_greater) {
__ cmpl(current_character(), Immediate(limit));
BranchOrBacktrack(greater, on_greater);
}
void RegExpMacroAssemblerX64::CheckAtStart(Label* on_at_start) {
Label not_at_start;
// Did we start the match at the start of the string at all?
__ cmpb(Operand(rbp, kStartIndex), Immediate(0));
BranchOrBacktrack(not_equal, ¬_at_start);
// If we did, are we still at the start of the input?
__ lea(rax, Operand(rsi, rdi, times_1, 0));
__ cmpq(rax, Operand(rbp, kInputStart));
BranchOrBacktrack(equal, on_at_start);
__ bind(¬_at_start);
}
void RegExpMacroAssemblerX64::CheckNotAtStart(Label* on_not_at_start) {
// Did we start the match at the start of the string at all?
__ cmpb(Operand(rbp, kStartIndex), Immediate(0));
BranchOrBacktrack(not_equal, on_not_at_start);
// If we did, are we still at the start of the input?
__ lea(rax, Operand(rsi, rdi, times_1, 0));
__ cmpq(rax, Operand(rbp, kInputStart));
BranchOrBacktrack(not_equal, on_not_at_start);
}
void RegExpMacroAssemblerX64::CheckCharacterLT(uc16 limit, Label* on_less) {
__ cmpl(current_character(), Immediate(limit));
BranchOrBacktrack(less, on_less);
}
void RegExpMacroAssemblerX64::CheckCharacters(Vector<const uc16> str,
int cp_offset,
Label* on_failure,
bool check_end_of_string) {
#ifdef DEBUG
// If input is ASCII, don't even bother calling here if the string to
// match contains a non-ascii character.
if (mode_ == ASCII) {
ASSERT(String::IsAscii(str.start(), str.length()));
}
#endif
int byte_length = str.length() * char_size();
int byte_offset = cp_offset * char_size();
if (check_end_of_string) {
// Check that there are at least str.length() characters left in the input.
__ cmpl(rdi, Immediate(-(byte_offset + byte_length)));
BranchOrBacktrack(greater, on_failure);
}
if (on_failure == NULL) {
// Instead of inlining a backtrack, (re)use the global backtrack target.
on_failure = &backtrack_label_;
}
// Do one character test first to minimize loading for the case that
// we don't match at all (loading more than one character introduces that
// chance of reading unaligned and reading across cache boundaries).
// If the first character matches, expect a larger chance of matching the
// string, and start loading more characters at a time.
if (mode_ == ASCII) {
__ cmpb(Operand(rsi, rdi, times_1, byte_offset),
Immediate(static_cast<int8_t>(str[0])));
} else {
// Don't use 16-bit immediate. The size changing prefix throws off
// pre-decoding.
__ movzxwl(rax,
Operand(rsi, rdi, times_1, byte_offset));
__ cmpl(rax, Immediate(static_cast<int32_t>(str[0])));
}
BranchOrBacktrack(not_equal, on_failure);
__ lea(rbx, Operand(rsi, rdi, times_1, 0));
for (int i = 1, n = str.length(); i < n; ) {
if (mode_ == ASCII) {
if (i + 8 <= n) {
uint64_t combined_chars =
(static_cast<uint64_t>(str[i + 0]) << 0) ||
(static_cast<uint64_t>(str[i + 1]) << 8) ||
(static_cast<uint64_t>(str[i + 2]) << 16) ||
(static_cast<uint64_t>(str[i + 3]) << 24) ||
(static_cast<uint64_t>(str[i + 4]) << 32) ||
(static_cast<uint64_t>(str[i + 5]) << 40) ||
(static_cast<uint64_t>(str[i + 6]) << 48) ||
(static_cast<uint64_t>(str[i + 7]) << 56);
__ movq(rax, combined_chars, RelocInfo::NONE);
__ cmpq(rax, Operand(rbx, byte_offset + i));
i += 8;
} else if (i + 4 <= n) {
uint32_t combined_chars =
(static_cast<uint32_t>(str[i + 0]) << 0) ||
(static_cast<uint32_t>(str[i + 1]) << 8) ||
(static_cast<uint32_t>(str[i + 2]) << 16) ||
(static_cast<uint32_t>(str[i + 3]) << 24);
__ cmpl(Operand(rbx, byte_offset + i), Immediate(combined_chars));
i += 4;
} else {
__ cmpb(Operand(rbx, byte_offset + i),
Immediate(static_cast<int8_t>(str[i])));
i++;
}
} else {
ASSERT(mode_ == UC16);
if (i + 4 <= n) {
uint64_t combined_chars = *reinterpret_cast<const uint64_t*>(&str[i]);
__ movq(rax, combined_chars, RelocInfo::NONE);
__ cmpq(rax,
Operand(rsi, rdi, times_1, byte_offset + i * sizeof(uc16)));
i += 4;
} else if (i + 2 <= n) {
uint32_t combined_chars = *reinterpret_cast<const uint32_t*>(&str[i]);
__ cmpl(Operand(rsi, rdi, times_1, byte_offset + i * sizeof(uc16)),
Immediate(combined_chars));
i += 2;
} else {
__ movzxwl(rax,
Operand(rsi, rdi, times_1, byte_offset + i * sizeof(uc16)));
__ cmpl(rax, Immediate(str[i]));
i++;
}
}
BranchOrBacktrack(not_equal, on_failure);
}
}
void RegExpMacroAssemblerX64::CheckGreedyLoop(Label* on_equal) {
Label fallthrough;
__ cmpl(rdi, Operand(backtrack_stackpointer(), 0));
__ j(not_equal, &fallthrough);
Drop();
BranchOrBacktrack(no_condition, on_equal);
__ bind(&fallthrough);
}
void RegExpMacroAssemblerX64::CheckNotBackReferenceIgnoreCase(
int start_reg,
Label* on_no_match) {
Label fallthrough;
__ movq(rdx, register_location(start_reg)); // Offset of start of capture
__ movq(rbx, register_location(start_reg + 1)); // Offset of end of capture
__ subq(rbx, rdx); // Length of capture.
// -----------------------
// rdx = Start offset of capture.
// rbx = Length of capture
// If length is negative, this code will fail (it's a symptom of a partial or
// illegal capture where start of capture after end of capture).
// This must not happen (no back-reference can reference a capture that wasn't
// closed before in the reg-exp, and we must not generate code that can cause
// this condition).
// If length is zero, either the capture is empty or it is nonparticipating.
// In either case succeed immediately.
__ j(equal, &fallthrough);
if (mode_ == ASCII) {
Label loop_increment;
if (on_no_match == NULL) {
on_no_match = &backtrack_label_;
}
__ lea(r9, Operand(rsi, rdx, times_1, 0));
__ lea(r11, Operand(rsi, rdi, times_1, 0));
__ addq(rbx, r9); // End of capture
// ---------------------
// r11 - current input character address
// r9 - current capture character address
// rbx - end of capture
Label loop;
__ bind(&loop);
__ movzxbl(rdx, Operand(r9, 0));
__ movzxbl(rax, Operand(r11, 0));
// al - input character
// dl - capture character
__ cmpb(rax, rdx);
__ j(equal, &loop_increment);
// Mismatch, try case-insensitive match (converting letters to lower-case).
// I.e., if or-ing with 0x20 makes values equal and in range 'a'-'z', it's
// a match.
__ or_(rax, Immediate(0x20)); // Convert match character to lower-case.
__ or_(rdx, Immediate(0x20)); // Convert capture character to lower-case.
__ cmpb(rax, rdx);
__ j(not_equal, on_no_match); // Definitely not equal.
__ subb(rax, Immediate('a'));
__ cmpb(rax, Immediate('z' - 'a'));
__ j(above, on_no_match); // Weren't letters anyway.
__ bind(&loop_increment);
// Increment pointers into match and capture strings.
__ addq(r11, Immediate(1));
__ addq(r9, Immediate(1));
// Compare to end of capture, and loop if not done.
__ cmpq(r9, rbx);
__ j(below, &loop);
// Compute new value of character position after the matched part.
__ movq(rdi, r11);
__ subq(rdi, rsi);
} else {
ASSERT(mode_ == UC16);
// Save important/volatile registers before calling C function.
#ifndef _WIN64
// Caller save on Linux and callee save in Windows.
__ push(rsi);
__ push(rdi);
#endif
__ push(backtrack_stackpointer());
static const int num_arguments = 4;
__ PrepareCallCFunction(num_arguments);
// Put arguments into parameter registers. Parameters are
// Address byte_offset1 - Address captured substring's start.
// Address byte_offset2 - Address of current character position.
// size_t byte_length - length of capture in bytes(!)
// Isolate* isolate
#ifdef _WIN64
// Compute and set byte_offset1 (start of capture).
__ lea(rcx, Operand(rsi, rdx, times_1, 0));
// Set byte_offset2.
__ lea(rdx, Operand(rsi, rdi, times_1, 0));
// Set byte_length.
__ movq(r8, rbx);
// Isolate.
__ LoadAddress(r9, ExternalReference::isolate_address());
#else // AMD64 calling convention
// Compute byte_offset2 (current position = rsi+rdi).
__ lea(rax, Operand(rsi, rdi, times_1, 0));
// Compute and set byte_offset1 (start of capture).
__ lea(rdi, Operand(rsi, rdx, times_1, 0));
// Set byte_offset2.
__ movq(rsi, rax);
// Set byte_length.
__ movq(rdx, rbx);
// Isolate.
__ LoadAddress(rcx, ExternalReference::isolate_address());
#endif
ExternalReference compare =
ExternalReference::re_case_insensitive_compare_uc16(masm_.isolate());
__ CallCFunction(compare, num_arguments);
// Restore original values before reacting on result value.
__ Move(code_object_pointer(), masm_.CodeObject());
__ pop(backtrack_stackpointer());
#ifndef _WIN64
__ pop(rdi);
__ pop(rsi);
#endif
// Check if function returned non-zero for success or zero for failure.
__ testq(rax, rax);
BranchOrBacktrack(zero, on_no_match);
// On success, increment position by length of capture.
// Requires that rbx is callee save (true for both Win64 and AMD64 ABIs).
__ addq(rdi, rbx);
}
__ bind(&fallthrough);
}
void RegExpMacroAssemblerX64::CheckNotBackReference(
int start_reg,
Label* on_no_match) {
Label fallthrough;
// Find length of back-referenced capture.
__ movq(rdx, register_location(start_reg));
__ movq(rax, register_location(start_reg + 1));
__ subq(rax, rdx); // Length to check.
// Fail on partial or illegal capture (start of capture after end of capture).
// This must not happen (no back-reference can reference a capture that wasn't
// closed before in the reg-exp).
__ Check(greater_equal, "Invalid capture referenced");
// Succeed on empty capture (including non-participating capture)
__ j(equal, &fallthrough);
// -----------------------
// rdx - Start of capture
// rax - length of capture
// Check that there are sufficient characters left in the input.
__ movl(rbx, rdi);
__ addl(rbx, rax);
BranchOrBacktrack(greater, on_no_match);
// Compute pointers to match string and capture string
__ lea(rbx, Operand(rsi, rdi, times_1, 0)); // Start of match.
__ addq(rdx, rsi); // Start of capture.
__ lea(r9, Operand(rdx, rax, times_1, 0)); // End of capture
// -----------------------
// rbx - current capture character address.
// rbx - current input character address .
// r9 - end of input to match (capture length after rbx).
Label loop;
__ bind(&loop);
if (mode_ == ASCII) {
__ movzxbl(rax, Operand(rdx, 0));
__ cmpb(rax, Operand(rbx, 0));
} else {
ASSERT(mode_ == UC16);
__ movzxwl(rax, Operand(rdx, 0));
__ cmpw(rax, Operand(rbx, 0));
}
BranchOrBacktrack(not_equal, on_no_match);
// Increment pointers into capture and match string.
__ addq(rbx, Immediate(char_size()));
__ addq(rdx, Immediate(char_size()));
// Check if we have reached end of match area.
__ cmpq(rdx, r9);
__ j(below, &loop);
// Success.
// Set current character position to position after match.
__ movq(rdi, rbx);
__ subq(rdi, rsi);
__ bind(&fallthrough);
}
void RegExpMacroAssemblerX64::CheckNotRegistersEqual(int reg1,
int reg2,
Label* on_not_equal) {
__ movq(rax, register_location(reg1));
__ cmpq(rax, register_location(reg2));
BranchOrBacktrack(not_equal, on_not_equal);
}
void RegExpMacroAssemblerX64::CheckNotCharacter(uint32_t c,
Label* on_not_equal) {
__ cmpl(current_character(), Immediate(c));
BranchOrBacktrack(not_equal, on_not_equal);
}
void RegExpMacroAssemblerX64::CheckCharacterAfterAnd(uint32_t c,
uint32_t mask,
Label* on_equal) {
__ movl(rax, current_character());
__ and_(rax, Immediate(mask));
__ cmpl(rax, Immediate(c));
BranchOrBacktrack(equal, on_equal);
}
void RegExpMacroAssemblerX64::CheckNotCharacterAfterAnd(uint32_t c,
uint32_t mask,
Label* on_not_equal) {
__ movl(rax, current_character());
__ and_(rax, Immediate(mask));
__ cmpl(rax, Immediate(c));
BranchOrBacktrack(not_equal, on_not_equal);
}
void RegExpMacroAssemblerX64::CheckNotCharacterAfterMinusAnd(
uc16 c,
uc16 minus,
uc16 mask,
Label* on_not_equal) {
ASSERT(minus < String::kMaxUC16CharCode);
__ lea(rax, Operand(current_character(), -minus));
__ and_(rax, Immediate(mask));
__ cmpl(rax, Immediate(c));
BranchOrBacktrack(not_equal, on_not_equal);
}
bool RegExpMacroAssemblerX64::CheckSpecialCharacterClass(uc16 type,
Label* on_no_match) {
// Range checks (c in min..max) are generally implemented by an unsigned
// (c - min) <= (max - min) check, using the sequence:
// lea(rax, Operand(current_character(), -min)) or sub(rax, Immediate(min))
// cmp(rax, Immediate(max - min))
switch (type) {
case 's':
// Match space-characters
if (mode_ == ASCII) {
// ASCII space characters are '\t'..'\r' and ' '.
Label success;
__ cmpl(current_character(), Immediate(' '));
__ j(equal, &success);
// Check range 0x09..0x0d
__ lea(rax, Operand(current_character(), -'\t'));
__ cmpl(rax, Immediate('\r' - '\t'));
BranchOrBacktrack(above, on_no_match);
__ bind(&success);
return true;
}
return false;
case 'S':
// Match non-space characters.
if (mode_ == ASCII) {
// ASCII space characters are '\t'..'\r' and ' '.
__ cmpl(current_character(), Immediate(' '));
BranchOrBacktrack(equal, on_no_match);
__ lea(rax, Operand(current_character(), -'\t'));
__ cmpl(rax, Immediate('\r' - '\t'));
BranchOrBacktrack(below_equal, on_no_match);
return true;
}
return false;
case 'd':
// Match ASCII digits ('0'..'9')
__ lea(rax, Operand(current_character(), -'0'));
__ cmpl(rax, Immediate('9' - '0'));
BranchOrBacktrack(above, on_no_match);
return true;
case 'D':
// Match non ASCII-digits
__ lea(rax, Operand(current_character(), -'0'));
__ cmpl(rax, Immediate('9' - '0'));
BranchOrBacktrack(below_equal, on_no_match);
return true;
case '.': {
// Match non-newlines (not 0x0a('\n'), 0x0d('\r'), 0x2028 and 0x2029)
__ movl(rax, current_character());
__ xor_(rax, Immediate(0x01));
// See if current character is '\n'^1 or '\r'^1, i.e., 0x0b or 0x0c
__ subl(rax, Immediate(0x0b));
__ cmpl(rax, Immediate(0x0c - 0x0b));
BranchOrBacktrack(below_equal, on_no_match);
if (mode_ == UC16) {
// Compare original value to 0x2028 and 0x2029, using the already
// computed (current_char ^ 0x01 - 0x0b). I.e., check for
// 0x201d (0x2028 - 0x0b) or 0x201e.
__ subl(rax, Immediate(0x2028 - 0x0b));
__ cmpl(rax, Immediate(0x2029 - 0x2028));
BranchOrBacktrack(below_equal, on_no_match);
}
return true;
}
case 'n': {
// Match newlines (0x0a('\n'), 0x0d('\r'), 0x2028 and 0x2029)
__ movl(rax, current_character());
__ xor_(rax, Immediate(0x01));
// See if current character is '\n'^1 or '\r'^1, i.e., 0x0b or 0x0c
__ subl(rax, Immediate(0x0b));
__ cmpl(rax, Immediate(0x0c - 0x0b));
if (mode_ == ASCII) {
BranchOrBacktrack(above, on_no_match);
} else {
Label done;
BranchOrBacktrack(below_equal, &done);
// Compare original value to 0x2028 and 0x2029, using the already
// computed (current_char ^ 0x01 - 0x0b). I.e., check for
// 0x201d (0x2028 - 0x0b) or 0x201e.
__ subl(rax, Immediate(0x2028 - 0x0b));
__ cmpl(rax, Immediate(0x2029 - 0x2028));
BranchOrBacktrack(above, on_no_match);
__ bind(&done);
}
return true;
}
case 'w': {
if (mode_ != ASCII) {
// Table is 128 entries, so all ASCII characters can be tested.
__ cmpl(current_character(), Immediate('z'));
BranchOrBacktrack(above, on_no_match);
}
__ movq(rbx, ExternalReference::re_word_character_map());
ASSERT_EQ(0, word_character_map[0]); // Character '\0' is not a word char.
ExternalReference word_map = ExternalReference::re_word_character_map();
__ testb(Operand(rbx, current_character(), times_1, 0),
current_character());
BranchOrBacktrack(zero, on_no_match);
return true;
}
case 'W': {
Label done;
if (mode_ != ASCII) {
// Table is 128 entries, so all ASCII characters can be tested.
__ cmpl(current_character(), Immediate('z'));
__ j(above, &done);
}
__ movq(rbx, ExternalReference::re_word_character_map());
ASSERT_EQ(0, word_character_map[0]); // Character '\0' is not a word char.
ExternalReference word_map = ExternalReference::re_word_character_map();
__ testb(Operand(rbx, current_character(), times_1, 0),
current_character());
BranchOrBacktrack(not_zero, on_no_match);
if (mode_ != ASCII) {
__ bind(&done);
}
return true;
}
case '*':
// Match any character.
return true;
// No custom implementation (yet): s(UC16), S(UC16).
default:
return false;
}
}
void RegExpMacroAssemblerX64::Fail() {
ASSERT(FAILURE == 0); // Return value for failure is zero.
__ Set(rax, 0);
__ jmp(&exit_label_);
}
Handle<Object> RegExpMacroAssemblerX64::GetCode(Handle<String> source) {
// Finalize code - write the entry point code now we know how many
// registers we need.
// Entry code:
__ bind(&entry_label_);
// Start new stack frame.
__ push(rbp);
__ movq(rbp, rsp);
// Save parameters and callee-save registers. Order here should correspond
// to order of kBackup_ebx etc.
#ifdef _WIN64
// MSVC passes arguments in rcx, rdx, r8, r9, with backing stack slots.
// Store register parameters in pre-allocated stack slots,
__ movq(Operand(rbp, kInputString), rcx);
__ movq(Operand(rbp, kStartIndex), rdx); // Passed as int32 in edx.
__ movq(Operand(rbp, kInputStart), r8);
__ movq(Operand(rbp, kInputEnd), r9);
// Callee-save on Win64.
__ push(rsi);
__ push(rdi);
__ push(rbx);
#else
// GCC passes arguments in rdi, rsi, rdx, rcx, r8, r9 (and then on stack).
// Push register parameters on stack for reference.
ASSERT_EQ(kInputString, -1 * kPointerSize);
ASSERT_EQ(kStartIndex, -2 * kPointerSize);
ASSERT_EQ(kInputStart, -3 * kPointerSize);
ASSERT_EQ(kInputEnd, -4 * kPointerSize);
ASSERT_EQ(kRegisterOutput, -5 * kPointerSize);
ASSERT_EQ(kStackHighEnd, -6 * kPointerSize);
__ push(rdi);
__ push(rsi);
__ push(rdx);
__ push(rcx);
__ push(r8);
__ push(r9);
__ push(rbx); // Callee-save
#endif
__ push(Immediate(0)); // Make room for "at start" constant.
// Check if we have space on the stack for registers.
Label stack_limit_hit;
Label stack_ok;
ExternalReference stack_limit =
ExternalReference::address_of_stack_limit(masm_.isolate());
__ movq(rcx, rsp);
__ movq(kScratchRegister, stack_limit);
__ subq(rcx, Operand(kScratchRegister, 0));
// Handle it if the stack pointer is already below the stack limit.
__ j(below_equal, &stack_limit_hit);
// Check if there is room for the variable number of registers above
// the stack limit.
__ cmpq(rcx, Immediate(num_registers_ * kPointerSize));
__ j(above_equal, &stack_ok);
// Exit with OutOfMemory exception. There is not enough space on the stack
// for our working registers.
__ Set(rax, EXCEPTION);
__ jmp(&exit_label_);
__ bind(&stack_limit_hit);
__ Move(code_object_pointer(), masm_.CodeObject());
CallCheckStackGuardState(); // Preserves no registers beside rbp and rsp.
__ testq(rax, rax);
// If returned value is non-zero, we exit with the returned value as result.
__ j(not_zero, &exit_label_);
__ bind(&stack_ok);
// Allocate space on stack for registers.
__ subq(rsp, Immediate(num_registers_ * kPointerSize));
// Load string length.
__ movq(rsi, Operand(rbp, kInputEnd));
// Load input position.
__ movq(rdi, Operand(rbp, kInputStart));
// Set up rdi to be negative offset from string end.
__ subq(rdi, rsi);
// Set rax to address of char before start of the string
// (effectively string position -1).
__ movq(rbx, Operand(rbp, kStartIndex));
__ neg(rbx);
if (mode_ == UC16) {
__ lea(rax, Operand(rdi, rbx, times_2, -char_size()));
} else {
__ lea(rax, Operand(rdi, rbx, times_1, -char_size()));
}
// Store this value in a local variable, for use when clearing
// position registers.
__ movq(Operand(rbp, kInputStartMinusOne), rax);
if (num_saved_registers_ > 0) {
// Fill saved registers with initial value = start offset - 1
// Fill in stack push order, to avoid accessing across an unwritten
// page (a problem on Windows).
__ Set(rcx, kRegisterZero);
Label init_loop;
__ bind(&init_loop);
__ movq(Operand(rbp, rcx, times_1, 0), rax);
__ subq(rcx, Immediate(kPointerSize));
__ cmpq(rcx,
Immediate(kRegisterZero - num_saved_registers_ * kPointerSize));
__ j(greater, &init_loop);
}
// Ensure that we have written to each stack page, in order. Skipping a page
// on Windows can cause segmentation faults. Assuming page size is 4k.
const int kPageSize = 4096;
const int kRegistersPerPage = kPageSize / kPointerSize;
for (int i = num_saved_registers_ + kRegistersPerPage - 1;
i < num_registers_;
i += kRegistersPerPage) {
__ movq(register_location(i), rax); // One write every page.
}
// Initialize backtrack stack pointer.
__ movq(backtrack_stackpointer(), Operand(rbp, kStackHighEnd));
// Initialize code object pointer.
__ Move(code_object_pointer(), masm_.CodeObject());
// Load previous char as initial value of current-character.
Label at_start;
__ cmpb(Operand(rbp, kStartIndex), Immediate(0));
__ j(equal, &at_start);
LoadCurrentCharacterUnchecked(-1, 1); // Load previous char.
__ jmp(&start_label_);
__ bind(&at_start);
__ Set(current_character(), '\n');
__ jmp(&start_label_);
// Exit code:
if (success_label_.is_linked()) {
// Save captures when successful.
__ bind(&success_label_);
if (num_saved_registers_ > 0) {
// copy captures to output
__ movq(rdx, Operand(rbp, kStartIndex));
__ movq(rbx, Operand(rbp, kRegisterOutput));
__ movq(rcx, Operand(rbp, kInputEnd));
__ subq(rcx, Operand(rbp, kInputStart));
if (mode_ == UC16) {
__ lea(rcx, Operand(rcx, rdx, times_2, 0));
} else {
__ addq(rcx, rdx);
}
for (int i = 0; i < num_saved_registers_; i++) {
__ movq(rax, register_location(i));
__ addq(rax, rcx); // Convert to index from start, not end.
if (mode_ == UC16) {
__ sar(rax, Immediate(1)); // Convert byte index to character index.
}
__ movl(Operand(rbx, i * kIntSize), rax);
}
}
__ Set(rax, SUCCESS);
}
// Exit and return rax
__ bind(&exit_label_);
#ifdef _WIN64
// Restore callee save registers.
__ lea(rsp, Operand(rbp, kLastCalleeSaveRegister));
__ pop(rbx);
__ pop(rdi);
__ pop(rsi);
// Stack now at rbp.
#else
// Restore callee save register.
__ movq(rbx, Operand(rbp, kBackup_rbx));
// Skip rsp to rbp.
__ movq(rsp, rbp);
#endif
// Exit function frame, restore previous one.
__ pop(rbp);
__ ret(0);
// Backtrack code (branch target for conditional backtracks).
if (backtrack_label_.is_linked()) {
__ bind(&backtrack_label_);
Backtrack();
}
Label exit_with_exception;
// Preempt-code
if (check_preempt_label_.is_linked()) {
SafeCallTarget(&check_preempt_label_);
__ push(backtrack_stackpointer());
__ push(rdi);
CallCheckStackGuardState();
__ testq(rax, rax);
// If returning non-zero, we should end execution with the given
// result as return value.
__ j(not_zero, &exit_label_);
// Restore registers.
__ Move(code_object_pointer(), masm_.CodeObject());
__ pop(rdi);
__ pop(backtrack_stackpointer());
// String might have moved: Reload esi from frame.
__ movq(rsi, Operand(rbp, kInputEnd));
SafeReturn();
}
// Backtrack stack overflow code.
if (stack_overflow_label_.is_linked()) {
SafeCallTarget(&stack_overflow_label_);
// Reached if the backtrack-stack limit has been hit.
Label grow_failed;
// Save registers before calling C function
#ifndef _WIN64
// Callee-save in Microsoft 64-bit ABI, but not in AMD64 ABI.
__ push(rsi);
__ push(rdi);
#endif
// Call GrowStack(backtrack_stackpointer())
static const int num_arguments = 3;
__ PrepareCallCFunction(num_arguments);
#ifdef _WIN64
// Microsoft passes parameters in rcx, rdx, r8.
// First argument, backtrack stackpointer, is already in rcx.
__ lea(rdx, Operand(rbp, kStackHighEnd)); // Second argument
__ LoadAddress(r8, ExternalReference::isolate_address());
#else
// AMD64 ABI passes parameters in rdi, rsi, rdx.
__ movq(rdi, backtrack_stackpointer()); // First argument.
__ lea(rsi, Operand(rbp, kStackHighEnd)); // Second argument.
__ LoadAddress(rdx, ExternalReference::isolate_address());
#endif
ExternalReference grow_stack =
ExternalReference::re_grow_stack(masm_.isolate());
__ CallCFunction(grow_stack, num_arguments);
// If return NULL, we have failed to grow the stack, and
// must exit with a stack-overflow exception.
__ testq(rax, rax);
__ j(equal, &exit_with_exception);
// Otherwise use return value as new stack pointer.
__ movq(backtrack_stackpointer(), rax);
// Restore saved registers and continue.
__ Move(code_object_pointer(), masm_.CodeObject());
#ifndef _WIN64
__ pop(rdi);
__ pop(rsi);
#endif
SafeReturn();
}
if (exit_with_exception.is_linked()) {
// If any of the code above needed to exit with an exception.
__ bind(&exit_with_exception);
// Exit with Result EXCEPTION(-1) to signal thrown exception.
__ Set(rax, EXCEPTION);
__ jmp(&exit_label_);
}
FixupCodeRelativePositions();
CodeDesc code_desc;
masm_.GetCode(&code_desc);
Isolate* isolate = ISOLATE;
Handle<Code> code = isolate->factory()->NewCode(
code_desc, Code::ComputeFlags(Code::REGEXP),
masm_.CodeObject());
PROFILE(isolate, RegExpCodeCreateEvent(*code, *source));
return Handle<Object>::cast(code);
}
void RegExpMacroAssemblerX64::GoTo(Label* to) {
BranchOrBacktrack(no_condition, to);
}
void RegExpMacroAssemblerX64::IfRegisterGE(int reg,
int comparand,
Label* if_ge) {
__ cmpq(register_location(reg), Immediate(comparand));
BranchOrBacktrack(greater_equal, if_ge);
}
void RegExpMacroAssemblerX64::IfRegisterLT(int reg,
int comparand,
Label* if_lt) {
__ cmpq(register_location(reg), Immediate(comparand));
BranchOrBacktrack(less, if_lt);
}
void RegExpMacroAssemblerX64::IfRegisterEqPos(int reg,
Label* if_eq) {
__ cmpq(rdi, register_location(reg));
BranchOrBacktrack(equal, if_eq);
}
RegExpMacroAssembler::IrregexpImplementation
RegExpMacroAssemblerX64::Implementation() {
return kX64Implementation;
}
void RegExpMacroAssemblerX64::LoadCurrentCharacter(int cp_offset,
Label* on_end_of_input,
bool check_bounds,
int characters) {
ASSERT(cp_offset >= -1); // ^ and \b can look behind one character.
ASSERT(cp_offset < (1<<30)); // Be sane! (And ensure negation works)
if (check_bounds) {
CheckPosition(cp_offset + characters - 1, on_end_of_input);
}
LoadCurrentCharacterUnchecked(cp_offset, characters);
}
void RegExpMacroAssemblerX64::PopCurrentPosition() {
Pop(rdi);
}
void RegExpMacroAssemblerX64::PopRegister(int register_index) {
Pop(rax);
__ movq(register_location(register_index), rax);
}
void RegExpMacroAssemblerX64::PushBacktrack(Label* label) {
Push(label);
CheckStackLimit();
}
void RegExpMacroAssemblerX64::PushCurrentPosition() {
Push(rdi);
}
void RegExpMacroAssemblerX64::PushRegister(int register_index,
StackCheckFlag check_stack_limit) {
__ movq(rax, register_location(register_index));
Push(rax);
if (check_stack_limit) CheckStackLimit();
}
void RegExpMacroAssemblerX64::ReadCurrentPositionFromRegister(int reg) {
__ movq(rdi, register_location(reg));
}
void RegExpMacroAssemblerX64::ReadStackPointerFromRegister(int reg) {
__ movq(backtrack_stackpointer(), register_location(reg));
__ addq(backtrack_stackpointer(), Operand(rbp, kStackHighEnd));
}
void RegExpMacroAssemblerX64::SetCurrentPositionFromEnd(int by) {
NearLabel after_position;
__ cmpq(rdi, Immediate(-by * char_size()));
__ j(greater_equal, &after_position);
__ movq(rdi, Immediate(-by * char_size()));
// On RegExp code entry (where this operation is used), the character before
// the current position is expected to be already loaded.
// We have advanced the position, so it's safe to read backwards.
LoadCurrentCharacterUnchecked(-1, 1);
__ bind(&after_position);
}
void RegExpMacroAssemblerX64::SetRegister(int register_index, int to) {
ASSERT(register_index >= num_saved_registers_); // Reserved for positions!
__ movq(register_location(register_index), Immediate(to));
}
void RegExpMacroAssemblerX64::Succeed() {
__ jmp(&success_label_);
}
void RegExpMacroAssemblerX64::WriteCurrentPositionToRegister(int reg,
int cp_offset) {
if (cp_offset == 0) {
__ movq(register_location(reg), rdi);
} else {
__ lea(rax, Operand(rdi, cp_offset * char_size()));
__ movq(register_location(reg), rax);
}
}
void RegExpMacroAssemblerX64::ClearRegisters(int reg_from, int reg_to) {
ASSERT(reg_from <= reg_to);
__ movq(rax, Operand(rbp, kInputStartMinusOne));
for (int reg = reg_from; reg <= reg_to; reg++) {
__ movq(register_location(reg), rax);
}
}
void RegExpMacroAssemblerX64::WriteStackPointerToRegister(int reg) {
__ movq(rax, backtrack_stackpointer());
__ subq(rax, Operand(rbp, kStackHighEnd));
__ movq(register_location(reg), rax);
}
// Private methods:
void RegExpMacroAssemblerX64::CallCheckStackGuardState() {
// This function call preserves no register values. Caller should
// store anything volatile in a C call or overwritten by this function.
static const int num_arguments = 3;
__ PrepareCallCFunction(num_arguments);
#ifdef _WIN64
// Second argument: Code* of self. (Do this before overwriting r8).
__ movq(rdx, code_object_pointer());
// Third argument: RegExp code frame pointer.
__ movq(r8, rbp);
// First argument: Next address on the stack (will be address of
// return address).
__ lea(rcx, Operand(rsp, -kPointerSize));
#else
// Third argument: RegExp code frame pointer.
__ movq(rdx, rbp);
// Second argument: Code* of self.
__ movq(rsi, code_object_pointer());
// First argument: Next address on the stack (will be address of
// return address).
__ lea(rdi, Operand(rsp, -kPointerSize));
#endif
ExternalReference stack_check =
ExternalReference::re_check_stack_guard_state(masm_.isolate());
__ CallCFunction(stack_check, num_arguments);
}
// Helper function for reading a value out of a stack frame.
template <typename T>
static T& frame_entry(Address re_frame, int frame_offset) {
return reinterpret_cast<T&>(Memory::int32_at(re_frame + frame_offset));
}
int RegExpMacroAssemblerX64::CheckStackGuardState(Address* return_address,
Code* re_code,
Address re_frame) {
Isolate* isolate = frame_entry<Isolate*>(re_frame, kIsolate);
ASSERT(isolate == Isolate::Current());
if (isolate->stack_guard()->IsStackOverflow()) {
isolate->StackOverflow();
return EXCEPTION;
}
// If not real stack overflow the stack guard was used to interrupt
// execution for another purpose.
// If this is a direct call from JavaScript retry the RegExp forcing the call
// through the runtime system. Currently the direct call cannot handle a GC.
if (frame_entry<int>(re_frame, kDirectCall) == 1) {
return RETRY;
}
// Prepare for possible GC.
HandleScope handles;
Handle<Code> code_handle(re_code);
Handle<String> subject(frame_entry<String*>(re_frame, kInputString));
// Current string.
bool is_ascii = subject->IsAsciiRepresentation();
ASSERT(re_code->instruction_start() <= *return_address);
ASSERT(*return_address <=
re_code->instruction_start() + re_code->instruction_size());
MaybeObject* result = Execution::HandleStackGuardInterrupt();
if (*code_handle != re_code) { // Return address no longer valid
intptr_t delta = *code_handle - re_code;
// Overwrite the return address on the stack.
*return_address += delta;
}
if (result->IsException()) {
return EXCEPTION;
}
// String might have changed.
if (subject->IsAsciiRepresentation() != is_ascii) {
// If we changed between an ASCII and an UC16 string, the specialized
// code cannot be used, and we need to restart regexp matching from
// scratch (including, potentially, compiling a new version of the code).
return RETRY;
}
// Otherwise, the content of the string might have moved. It must still
// be a sequential or external string with the same content.
// Update the start and end pointers in the stack frame to the current
// location (whether it has actually moved or not).
ASSERT(StringShape(*subject).IsSequential() ||
StringShape(*subject).IsExternal());
// The original start address of the characters to match.
const byte* start_address = frame_entry<const byte*>(re_frame, kInputStart);
// Find the current start address of the same character at the current string
// position.
int start_index = frame_entry<int>(re_frame, kStartIndex);
const byte* new_address = StringCharacterPosition(*subject, start_index);
if (start_address != new_address) {
// If there is a difference, update the object pointer and start and end
// addresses in the RegExp stack frame to match the new value.
const byte* end_address = frame_entry<const byte* >(re_frame, kInputEnd);
int byte_length = static_cast<int>(end_address - start_address);
frame_entry<const String*>(re_frame, kInputString) = *subject;
frame_entry<const byte*>(re_frame, kInputStart) = new_address;
frame_entry<const byte*>(re_frame, kInputEnd) = new_address + byte_length;
}
return 0;
}
Operand RegExpMacroAssemblerX64::register_location(int register_index) {
ASSERT(register_index < (1<<30));
if (num_registers_ <= register_index) {
num_registers_ = register_index + 1;
}
return Operand(rbp, kRegisterZero - register_index * kPointerSize);
}
void RegExpMacroAssemblerX64::CheckPosition(int cp_offset,
Label* on_outside_input) {
__ cmpl(rdi, Immediate(-cp_offset * char_size()));
BranchOrBacktrack(greater_equal, on_outside_input);
}
void RegExpMacroAssemblerX64::BranchOrBacktrack(Condition condition,
Label* to) {
if (condition < 0) { // No condition
if (to == NULL) {
Backtrack();
return;
}
__ jmp(to);
return;
}
if (to == NULL) {
__ j(condition, &backtrack_label_);
return;
}
__ j(condition, to);
}
void RegExpMacroAssemblerX64::SafeCall(Label* to) {
__ call(to);
}
void RegExpMacroAssemblerX64::SafeCallTarget(Label* label) {
__ bind(label);
__ subq(Operand(rsp, 0), code_object_pointer());
}
void RegExpMacroAssemblerX64::SafeReturn() {
__ addq(Operand(rsp, 0), code_object_pointer());
__ ret(0);
}
void RegExpMacroAssemblerX64::Push(Register source) {
ASSERT(!source.is(backtrack_stackpointer()));
// Notice: This updates flags, unlike normal Push.
__ subq(backtrack_stackpointer(), Immediate(kIntSize));
__ movl(Operand(backtrack_stackpointer(), 0), source);
}
void RegExpMacroAssemblerX64::Push(Immediate value) {
// Notice: This updates flags, unlike normal Push.
__ subq(backtrack_stackpointer(), Immediate(kIntSize));
__ movl(Operand(backtrack_stackpointer(), 0), value);
}
void RegExpMacroAssemblerX64::FixupCodeRelativePositions() {
for (int i = 0, n = code_relative_fixup_positions_.length(); i < n; i++) {
int position = code_relative_fixup_positions_[i];
// The position succeeds a relative label offset from position.
// Patch the relative offset to be relative to the Code object pointer
// instead.
int patch_position = position - kIntSize;
int offset = masm_.long_at(patch_position);
masm_.long_at_put(patch_position,
offset
+ position
+ Code::kHeaderSize
- kHeapObjectTag);
}
code_relative_fixup_positions_.Clear();
}
void RegExpMacroAssemblerX64::Push(Label* backtrack_target) {
__ subq(backtrack_stackpointer(), Immediate(kIntSize));
__ movl(Operand(backtrack_stackpointer(), 0), backtrack_target);
MarkPositionForCodeRelativeFixup();
}
void RegExpMacroAssemblerX64::Pop(Register target) {
ASSERT(!target.is(backtrack_stackpointer()));
__ movsxlq(target, Operand(backtrack_stackpointer(), 0));
// Notice: This updates flags, unlike normal Pop.
__ addq(backtrack_stackpointer(), Immediate(kIntSize));
}
void RegExpMacroAssemblerX64::Drop() {
__ addq(backtrack_stackpointer(), Immediate(kIntSize));
}
void RegExpMacroAssemblerX64::CheckPreemption() {
// Check for preemption.
Label no_preempt;
ExternalReference stack_limit =
ExternalReference::address_of_stack_limit(masm_.isolate());
__ load_rax(stack_limit);
__ cmpq(rsp, rax);
__ j(above, &no_preempt);
SafeCall(&check_preempt_label_);
__ bind(&no_preempt);
}
void RegExpMacroAssemblerX64::CheckStackLimit() {
Label no_stack_overflow;
ExternalReference stack_limit =
ExternalReference::address_of_regexp_stack_limit(masm_.isolate());
__ load_rax(stack_limit);
__ cmpq(backtrack_stackpointer(), rax);
__ j(above, &no_stack_overflow);
SafeCall(&stack_overflow_label_);
__ bind(&no_stack_overflow);
}
void RegExpMacroAssemblerX64::LoadCurrentCharacterUnchecked(int cp_offset,
int characters) {
if (mode_ == ASCII) {
if (characters == 4) {
__ movl(current_character(), Operand(rsi, rdi, times_1, cp_offset));
} else if (characters == 2) {
__ movzxwl(current_character(), Operand(rsi, rdi, times_1, cp_offset));
} else {
ASSERT(characters == 1);
__ movzxbl(current_character(), Operand(rsi, rdi, times_1, cp_offset));
}
} else {
ASSERT(mode_ == UC16);
if (characters == 2) {
__ movl(current_character(),
Operand(rsi, rdi, times_1, cp_offset * sizeof(uc16)));
} else {
ASSERT(characters == 1);
__ movzxwl(current_character(),
Operand(rsi, rdi, times_1, cp_offset * sizeof(uc16)));
}
}
}
#undef __
#endif // V8_INTERPRETED_REGEXP
}} // namespace v8::internal
#endif // V8_TARGET_ARCH_X64
| [
"[email protected]"
]
| [
[
[
1,
1398
]
]
]
|
4f3a45d908f70a3d2a61196ca979149cc3a156f8 | 97f1be9ac088e1c9d3fd73d76c63fc2c4e28749a | /3dc/win95/CHNKTYPE.CPP | 3a249b6a3570dcd6b391e1ac286de4b2c06ad5ee | [
"LicenseRef-scancode-warranty-disclaimer"
]
| no_license | SR-dude/AvP-Wine | 2875f7fd6b7914d03d7f58e8f0ec4793f971ad23 | 41a9c69a45aacc2c345570ba0e37ec3dc89f4efa | refs/heads/master | 2021-01-23T02:54:33.593334 | 2011-09-17T11:10:07 | 2011-09-17T11:10:07 | 2,375,686 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,423 | cpp | #include "chunk.hpp"
#include <math.h>
#include "chnktype.hpp"
#if engine
#define UseLocalAssert No
#include "ourasert.h"
#define assert(x) GLOBALASSERT(x)
#else
#if cencon
#include "ccassert.h"
#else
#include <assert.h>
#endif
#endif
#ifdef cencon
#define new my_new
#endif
// misc data structures functions
BOOL operator==(const obinfile &o1, const obinfile &o2)
{
return (&o1 == &o2);
}
BOOL operator!=(const obinfile &o1, const obinfile &o2)
{
return (&o1 != &o2);
}
BOOL operator==(const shpinfile &s1, const shpinfile &s2)
{
return (&s1 == &s2);
}
BOOL operator!=(const shpinfile &s1, const shpinfile &s2)
{
return (&s1 != &s2);
}
BOOL operator== (const ChunkUV_List &c1, const ChunkUV_List &c2)
{
return(&c1 == &c2);
}
BOOL operator!= (const ChunkUV_List &c1, const ChunkUV_List &c2)
{
return(&c1 != &c2);
}
BOOL operator== (const ObjectID &o1, const ObjectID &o2)
{
return((o1.id1==o2.id1) && (o1.id2==o2.id2));
}
BOOL operator!= (const ObjectID &o1, const ObjectID &o2)
{
return((o1.id1!=o2.id1) || (o1.id2!=o2.id2));
}
ObjectID Minimum(const ObjectID &o1,const ObjectID &o2)
{
if(o1.id1<o2.id1) return o1;
if(o1.id1>o2.id1) return o2;
if(o1.id2<o2.id2) return o1;
return o2;
}
//////////////////////////////////////////////
#define CHUNK_MAX_UVINDEX ((1<<20)-1)
#define CHUNK_MAX_TEXTUREINDEX ((1<<12)-1)
#define CHUNK_UVINDEX_MASK 0xfffff000
#define CHUNK_TEXTUREINDEX_MASK 0xfff
#define CHUNK_NEWUVINDEX_BITS 0x0000f000
unsigned int ChunkPoly::GetUVIndex()
{
if(colour & CHUNK_NEWUVINDEX_BITS)
{
unsigned int uv_index;
uv_index=(colour & CHUNK_NEWUVINDEX_BITS) << 4;
uv_index|= (colour >> 16);
return uv_index;
}
else
{
//uvindex is just in the top 16 bits
return (colour >> 16);
}
}
unsigned int ChunkPoly::GetTextureIndex()
{
return (colour & CHUNK_TEXTUREINDEX_MASK);
}
void ChunkPoly::SetUVIndex(unsigned int uv_index)
{
assert(uv_index<=CHUNK_MAX_UVINDEX);
//clear the old uvindex
colour &=~CHUNK_UVINDEX_MASK;
if(uv_index<65536)
{
//fit uv index into the top 16 bits if it will fit , to maintain compatibility with
//old chunk loaders
colour |= (uv_index<<16);
}
else
{
//put the bottom 16 bits of the uv_index in the top 16 bits of the colour
colour |= (uv_index & 0xffff) << 16;
//put the next 4 bits of the uv_index in the lower middle 4 bits of the colour
uv_index>>=16;
colour |= (uv_index <<12);
}
}
void ChunkPoly::SetTextureIndex(unsigned int texture_index)
{
assert(texture_index<=CHUNK_MAX_TEXTUREINDEX);
colour &=~ CHUNK_TEXTUREINDEX_MASK;
colour |= texture_index;
}
//////////////////////////////////////////////
ChunkVector operator+(const ChunkVector& a, const ChunkVector& b)
{
ChunkVector v;
v.x=a.x+b.x;
v.y=a.y+b.y;
v.z=a.z+b.z;
return v;
}
ChunkVector operator-(const ChunkVector& a, const ChunkVector& b)
{
ChunkVector v;
v.x=a.x-b.x;
v.y=a.y-b.y;
v.z=a.z-b.z;
return v;
}
ChunkVector& ChunkVector::operator+=(const ChunkVector& a)
{
x += a.x;
y += a.y;
z += a.z;
return *this;
}
ChunkVector& ChunkVector::operator-=(const ChunkVector& a)
{
x -= a.x;
y -= a.y;
z -= a.z;
return *this;
}
#if engine
ChunkVector::operator VECTORCH () const
{
VECTORCH v;
v.vx = x;
v.vy = y;
v.vz = z;
return(v);
}
#endif
ChunkVector::operator ChunkVectorInt () const
{
ChunkVectorInt v;
v.x = (int)x;
v.y = (int)y;
v.z = (int)z;
return(v);
}
ChunkVector::operator ChunkVectorFloat () const
{
ChunkVectorFloat v;
v.x = (float)x;
v.y = (float)y;
v.z = (float)z;
return(v);
}
ChunkVector operator*(const ChunkVector & a, const double s)
{
ChunkVector v;
v.x = a.x * s;
v.y = a.y * s;
v.z = a.z * s;
return(v);
}
ChunkVector operator/(const ChunkVector & a, const double s)
{
ChunkVector v;
v.x = a.x / s;
v.y = a.y / s;
v.z = a.z / s;
return(v);
}
ChunkVector operator*(const ChunkVector& a, const ChunkVector& b)
{
ChunkVector v;
v.x=a.y*b.z - a.z*b.y;
v.y=a.z*b.x - a.x*b.z;
v.z=a.x*b.y - a.y*b.x;
return v;
}
double dot(const ChunkVector& a, const ChunkVector& b)
{
return(a.x*b.x + a.y*b.y + a.z*b.z);
}
double mod(const ChunkVector& a)
{
return(sqrt(dot(a,a)));
}
int ChunkVector::norm()
{
double modulos = mod(*this);
if(modulos == 0)return(0);
x /=modulos;
y /= modulos;
z /= modulos;
return(1);
}
//////////////////////////////////////////////
ChunkVectorInt operator+(const ChunkVectorInt& a, const ChunkVectorInt& b)
{
ChunkVectorInt v;
v.x=a.x+b.x;
v.y=a.y+b.y;
v.z=a.z+b.z;
return v;
}
ChunkVectorInt operator-(const ChunkVectorInt& a, const ChunkVectorInt& b)
{
ChunkVectorInt v;
v.x=a.x-b.x;
v.y=a.y-b.y;
v.z=a.z-b.z;
return v;
}
ChunkVectorInt& ChunkVectorInt::operator+=(const ChunkVectorInt& a)
{
x += a.x;
y += a.y;
z += a.z;
return *this;
}
ChunkVectorInt& ChunkVectorInt::operator-=(const ChunkVectorInt& a)
{
x -= a.x;
y -= a.y;
z -= a.z;
return *this;
}
#if engine
ChunkVectorInt::operator VECTORCH () const
{
VECTORCH v;
v.vx = x;
v.vy = y;
v.vz = z;
return(v);
}
#endif
ChunkVectorInt operator*(const ChunkVectorInt & a, const double s)
{
ChunkVectorInt v;
v.x =(int) (a.x * s);
v.y =(int) (a.y * s);
v.z =(int) (a.z * s);
return(v);
}
ChunkVectorInt operator/(const ChunkVectorInt & a, const double s)
{
ChunkVectorInt v;
v.x =(int) (a.x / s);
v.y =(int) (a.y / s);
v.z =(int) (a.z / s);
return(v);
}
double mod(const ChunkVectorInt& a)
{
return(sqrt((double)a.x*(double)a.x+(double)a.y*(double)a.y+(double)a.z*(double)a.z));
}
int ChunkVectorInt::norm()
{
double modulos = mod(*this) /65536.0;
if(modulos == 0)return(0);
x =(int) (x/modulos);
y =(int) (y/modulos);
z =(int) (z/modulos);
return(1);
}
////////////////////////////////////////////////////////
ChunkVectorFloat operator+(const ChunkVectorFloat& a, const ChunkVectorFloat& b)
{
ChunkVectorFloat v;
v.x=a.x+b.x;
v.y=a.y+b.y;
v.z=a.z+b.z;
return v;
}
ChunkVectorFloat operator-(const ChunkVectorFloat& a, const ChunkVectorFloat& b)
{
ChunkVectorFloat v;
v.x=a.x-b.x;
v.y=a.y-b.y;
v.z=a.z-b.z;
return v;
}
ChunkVectorFloat& ChunkVectorFloat::operator+=(const ChunkVectorFloat& a)
{
x += a.x;
y += a.y;
z += a.z;
return *this;
}
ChunkVectorFloat& ChunkVectorFloat::operator-=(const ChunkVectorFloat& a)
{
x -= a.x;
y -= a.y;
z -= a.z;
return *this;
}
ChunkVectorFloat operator*(const ChunkVectorFloat & a, const double s)
{
ChunkVectorFloat v;
v.x =(float) (a.x * s);
v.y =(float) (a.y * s);
v.z =(float) (a.z * s);
return(v);
}
ChunkVectorFloat operator/(const ChunkVectorFloat & a, const double s)
{
ChunkVectorFloat v;
v.x =(float) (a.x / s);
v.y =(float) (a.y / s);
v.z =(float) (a.z / s);
return(v);
}
#if engine
ChunkVectorFloat::operator VECTORCH () const
{
VECTORCH v;
v.vx =(int) (x*65536);
v.vy =(int) (y*65536);
v.vz =(int) (z*65536);
return(v);
}
#endif
int ChunkVectorFloat::norm()
{
float modulos =(float) mod(*this);
if(modulos == 0)return(0);
x /= modulos;
y /= modulos;
z /= modulos;
return(1);
}
double mod(const ChunkVectorFloat& a)
{
return(sqrt((double)a.x*(double)a.x+(double)a.y*(double)a.y+(double)a.z*(double)a.z));
}
////////////////////////////////////////////////////////
ChunkShape::~ChunkShape()
{
if (v_list) delete [] v_list;
if (v_normal_list) delete [] v_normal_list;
if (p_normal_list) delete [] p_normal_list;
if (poly_list) delete [] poly_list;
if (uv_list) delete [] uv_list;
if (texture_fns)
for (int i = 0; i<num_texfiles; i++)
if (texture_fns[i]) delete texture_fns[i];
#if UseOldChunkLoader
if(float_v_list) delete float_v_list;
#endif
}
ChunkShape::ChunkShape()
{
num_polys = 0;
num_verts = 0;
num_uvs = 0;
num_texfiles = 0;
v_list = 0;
v_normal_list = 0;
p_normal_list = 0;
poly_list = 0;
uv_list = 0;
texture_fns = 0;
radius_about_centre=0;
#if UseOldChunkLoader
float_v_list=0;
#endif
}
ChunkShape::ChunkShape(const ChunkShape &shp)
{
int i;
radius = shp.radius;
max = shp.max;
min = shp.min;
num_polys = shp.num_polys;
num_verts = shp.num_verts;
num_uvs = shp.num_uvs;
num_texfiles = shp.num_texfiles;
if (shp.v_list) {
v_list = new ChunkVectorInt [num_verts];
for (i=0; i<num_verts; i++)
v_list[i] = shp.v_list[i];
}
else v_list = 0;
if (shp.v_normal_list) {
v_normal_list = new ChunkVectorFloat [num_verts];
for (i=0; i<num_verts; i++)
v_normal_list[i] = shp.v_normal_list[i];
}
else v_normal_list = 0;
if (shp.p_normal_list) {
p_normal_list = new ChunkVectorFloat [num_polys];
for (i=0; i<num_polys; i++)
p_normal_list[i] = shp.p_normal_list[i];
}
else p_normal_list = 0;
if (shp.poly_list) {
poly_list = new ChunkPoly [num_polys];
for (i=0; i<num_polys; i++)
poly_list[i] = shp.poly_list[i];
}
else poly_list = 0;
if (shp.uv_list) {
uv_list = new ChunkUV_List [num_uvs];
for (i=0; i<num_uvs; i++)
uv_list[i] = shp.uv_list[i];
}
else uv_list = 0;
if (shp.texture_fns) {
texture_fns = new char * [num_texfiles];
for (i=0; i<num_texfiles; i++) {
texture_fns[i] = new char [strlen (shp.texture_fns[i]) + 1];
strcpy (texture_fns[i], shp.texture_fns[i]);
}
}
else texture_fns = 0;
centre=shp.centre;
radius_about_centre=shp.radius_about_centre;
#if UseOldChunkLoader
float_v_list=0;
#endif
}
ChunkShape& ChunkShape::operator=(const ChunkShape &shp)
{
int i;
if (v_list) delete [] v_list;
if (v_normal_list) delete [] v_normal_list;
if (p_normal_list) delete [] p_normal_list;
if (poly_list) delete [] poly_list;
if (uv_list) delete [] uv_list;
if (texture_fns)
for (int i = 0; i<num_texfiles; i++)
if (texture_fns[i]) delete texture_fns[i];
radius = shp.radius;
max = shp.max;
min = shp.min;
num_polys = shp.num_polys;
num_verts = shp.num_verts;
num_uvs = shp.num_uvs;
num_texfiles = shp.num_texfiles;
if (shp.v_list) {
v_list = new ChunkVectorInt [num_verts];
for (i=0; i<num_verts; i++)
v_list[i] = shp.v_list[i];
}
else v_list = 0;
if (shp.v_normal_list) {
v_normal_list = new ChunkVectorFloat [num_verts];
for (i=0; i<num_verts; i++)
v_normal_list[i] = shp.v_normal_list[i];
}
else v_normal_list = 0;
if (shp.p_normal_list) {
p_normal_list = new ChunkVectorFloat [num_polys];
for (i=0; i<num_polys; i++)
p_normal_list[i] = shp.p_normal_list[i];
}
else p_normal_list = 0;
if (shp.poly_list) {
poly_list = new ChunkPoly [num_polys];
for (i=0; i<num_polys; i++)
poly_list[i] = shp.poly_list[i];
}
else poly_list = 0;
if (shp.uv_list) {
uv_list = new ChunkUV_List [num_uvs];
for (i=0; i<num_uvs; i++)
uv_list[i] = shp.uv_list[i];
}
else uv_list = 0;
if (shp.texture_fns) {
texture_fns = new char * [num_texfiles];
for (i=0; i<num_texfiles; i++) {
texture_fns[i] = new char [strlen (shp.texture_fns[i]) + 1];
strcpy (texture_fns[i], shp.texture_fns[i]);
}
}
else texture_fns = 0;
centre=shp.centre;
radius_about_centre=shp.radius_about_centre;
#if UseOldChunkLoader
if(float_v_list) delete float_v_list;
float_v_list=0;
#endif
return *this;
}
void ChunkShape::rescale (double scale)
{
int i;
if (v_list)
{
for (i=0; i<num_verts; i++)
{
v_list[i].x =(int) (v_list[i].x*scale);
v_list[i].y =(int) (v_list[i].y*scale);
v_list[i].z =(int) (v_list[i].z*scale);
}
}
radius =(float) (radius*scale);
max.x =(int) (max.x*scale);
max.y =(int) (max.y*scale);
max.z =(int) (max.z*scale);
min.x =(int) (min.x*scale);
min.y =(int) (min.y*scale);
min.z =(int) (min.z*scale);
centre=centre*scale;
radius_about_centre=(float) (radius_about_centre*scale);
}
VMod_Arr_Item::VMod_Arr_Item()
{
#if UseOldChunkLoader
o_name = 0;
#endif
}
VMod_Arr_Item::~VMod_Arr_Item()
{
#if UseOldChunkLoader
if (o_name)
delete o_name;
#endif
}
VMod_Arr_Item::VMod_Arr_Item(const VMod_Arr_Item & vma)
{
#if UseOldChunkLoader
if (vma.o_name)
{
o_name = new char [strlen(vma.o_name)+1];
strcpy (o_name, vma.o_name);
}
else
{
o_name = 0;
}
#endif
branch_no = vma.branch_no;
flags = vma.flags;
spare = vma.spare;
object_index=vma.object_index;
}
VMod_Arr_Item& VMod_Arr_Item::operator=(const VMod_Arr_Item & vma)
{
if (&vma == this) return(*this);
#if UseOldChunkLoader
if (o_name)
delete o_name;
if (vma.o_name)
{
o_name = new char [strlen(vma.o_name)+1];
strcpy (o_name, vma.o_name);
}
else
{
o_name = 0;
}
#endif
branch_no = vma.branch_no;
flags = vma.flags;
spare = vma.spare;
object_index=vma.object_index;
return(*this);
}
BOOL operator==(const VMod_Arr_Item & vm1, const VMod_Arr_Item & vm2)
{
return(&vm1 == &vm2);
}
BOOL operator!=(const VMod_Arr_Item & vm1, const VMod_Arr_Item & vm2)
{
return(&vm1 != &vm2);
}
///////////////////////////////////////
Adjacent_Module::Adjacent_Module()
{
flags = 0;
#if UseOldChunkLoader
o_name = 0;
#endif
entry_point.x=0;
entry_point.y=0;
entry_point.z=0;
}
Adjacent_Module::~Adjacent_Module()
{
#if UseOldChunkLoader
if (o_name)
delete o_name;
#endif
}
Adjacent_Module::Adjacent_Module(const Adjacent_Module & am)
{
#if UseOldChunkLoader
if (am.o_name)
{
o_name = new char [strlen(am.o_name)+1];
strcpy (o_name, am.o_name);
}
else
{
o_name = 0;
}
#endif
object_index=am.object_index;
flags = am.flags;
entry_point = am.entry_point;
}
Adjacent_Module& Adjacent_Module::operator=(const Adjacent_Module & am)
{
if (&am == this) return(*this);
#if UseOldChunkLoader
if (o_name)
delete o_name;
if (am.o_name)
{
o_name = new char [strlen(am.o_name)+1];
strcpy (o_name, am.o_name);
}
else
{
o_name = 0;
}
#endif
object_index=am.object_index;
flags = am.flags;
entry_point = am.entry_point;
return(*this);
}
BOOL operator==(const Adjacent_Module & am1, const Adjacent_Module & am2)
{
return(&am1 == &am2);
}
BOOL operator!=(const Adjacent_Module & am1, const Adjacent_Module & am2)
{
return(&am1 != &am2);
}
///////////////////////////////////////
BOOL operator==(poly_change_info const &f1, poly_change_info const &f2)
{
return(&f1 == &f2);
}
BOOL operator!=(poly_change_info const &f1, poly_change_info const &f2)
{
return(&f1 != &f2);
}
//////////////////////////////////////////////
ChunkAnimFrame::~ChunkAnimFrame()
{
if(name) delete [] name;
if(v_list) delete [] v_list;
if(p_normal_list) delete [] p_normal_list;
}
ChunkAnimFrame::ChunkAnimFrame()
{
name=0;
num_polys=0;
num_verts=0;
v_list=0;
p_normal_list=0;
flags=num_interp_frames=pad3=pad4=0;
}
ChunkAnimFrame::ChunkAnimFrame(const ChunkAnimFrame & frm)
{
if(frm.name)
{
name=new char[strlen(frm.name)+1];
strcpy(name,frm.name);
}
else
name=0;
num_polys=frm.num_polys;
num_verts=frm.num_verts;
if(num_polys)
{
p_normal_list=new ChunkVectorFloat[num_polys];
for(int i=0;i<num_polys;i++)
{
p_normal_list[i]=frm.p_normal_list[i];
}
}
else
p_normal_list=0;
if(num_verts)
{
v_list=new ChunkVectorInt[num_verts];
for(int i=0;i<num_verts;i++)
{
v_list[i]=frm.v_list[i];
}
}
else
v_list=0;
flags=frm.flags;
num_interp_frames=frm.num_interp_frames;
pad3=frm.pad3;
pad4=frm.pad4;
}
/*
ChunkAnimFrame::ChunkAnimFrame(ChunkAnimFrame* startframe,ChunkAnimFrame* endframe,int startwt,int endwt,ChunkShape const *cs)
{
name=0;
num_polys=startframe->num_polys;
num_verts=startframe->num_verts;
flags=startframe->flags|animframeflag_interpolated_frame;
num_interp_frames=0;
pad3=0;
pad4=0;
v_list=new ChunkVector[num_verts];
p_normal_list=new ChunkVector[num_polys];
double start_mult=startwt/(double)(startwt+endwt);
double end_mult=endwt/(double)(startwt+endwt);
for(int i=0;i<num_verts;i++)
{
v_list[i].x=startframe->v_list[i].x*start_mult+endframe->v_list[i].x*end_mult;
v_list[i].y=startframe->v_list[i].y*start_mult+endframe->v_list[i].y*end_mult;
v_list[i].z=startframe->v_list[i].z*start_mult+endframe->v_list[i].z*end_mult;
}
for(i=0;i<num_polys;i++)
{
ChunkVector v1=cs->v_list[cs->poly_list[i].vert_ind[1]]-cs->v_list[cs->poly_list[i].vert_ind[0]];
ChunkVector v2=cs->v_list[cs->poly_list[i].vert_ind[2]]-cs->v_list[cs->poly_list[i].vert_ind[0]];
ChunkVector norm;
norm.x=v1.y*v2.z-v1.z*v2.y;
norm.y=v1.z*v2.x-v1.x*v2.z;
norm.z=v1.x*v2.y-v1.y*v2.x;
double length=sqrt(norm.x*norm.x+norm.y*norm.y+norm.z*norm.z);
cs->p_normal_list[i]=norm*(1/length);
}
}
*/
ChunkAnimFrame& ChunkAnimFrame::operator=(const ChunkAnimFrame &frm)
{
if(name) delete [] name;
if(v_list) delete [] v_list;
if(p_normal_list) delete [] p_normal_list;
if(frm.name)
{
name=new char[strlen(frm.name)+1];
strcpy(name,frm.name);
}
else
name=0;
num_polys=frm.num_polys;
num_verts=frm.num_verts;
if(num_polys)
{
p_normal_list=new ChunkVectorFloat[num_polys];
for(int i=0;i<num_polys;i++)
{
p_normal_list[i]=frm.p_normal_list[i];
}
}
else
p_normal_list=0;
if(num_verts)
{
v_list=new ChunkVectorInt[num_verts];
for(int i=0;i<num_verts;i++)
{
v_list[i]=frm.v_list[i];
}
}
else
v_list=0;
flags=frm.flags;
num_interp_frames=frm.num_interp_frames;
pad3=frm.pad3;
pad4=frm.pad4;
return *this;
}
ChunkAnimSequence::~ChunkAnimSequence()
{
if(name) delete [] name;
for(int i=0;i<NumFrames;i++)
{
if(Frames[i])delete Frames[i];
}
if(Frames) delete [] Frames;
if(v_normal_list) delete [] v_normal_list;
}
ChunkAnimSequence::ChunkAnimSequence()
{
SequenceNum=-1;
name=0;
NumFrames=0;
Frames=0;
flags=pad2=pad3=pad4=0;
num_verts=0;
v_normal_list=0;
min.x=min.y=min.z=0;
max.x=max.y=max.z=0;
radius=0;
}
ChunkAnimSequence::ChunkAnimSequence(const ChunkAnimSequence & seq)
{
SequenceNum=seq.SequenceNum;
if(seq.name)
{
name=new char[strlen(seq.name)+1];
strcpy(name,seq.name);
}
else
name=0;
NumFrames=seq.NumFrames;
if(NumFrames)
{
Frames=new ChunkAnimFrame*[NumFrames];
for(int i=0;i<NumFrames;i++)
{
Frames[i]=new ChunkAnimFrame(*seq.Frames[i]);
}
}
else
Frames=0;
flags=seq.flags;
pad2=seq.pad2;
pad3=seq.pad3;
pad4=seq.pad4;
num_verts=seq.num_verts;
if(num_verts)
{
v_normal_list=new ChunkVectorFloat[num_verts];
for(int i=0;i<num_verts;i++)
{
v_normal_list[i]=seq.v_normal_list[i];
}
}
else v_normal_list=0;
min=seq.min;
max=seq.max;
radius=seq.radius;
}
ChunkAnimSequence& ChunkAnimSequence::operator=(const ChunkAnimSequence &seq)
{
if(name) delete [] name;
if(Frames) delete [] Frames;
if(v_normal_list) delete [] v_normal_list;
SequenceNum=seq.SequenceNum;
if(seq.name)
{
name=new char[strlen(seq.name)+1];
strcpy(name,seq.name);
}
else
name=0;
NumFrames=seq.NumFrames;
if(NumFrames)
{
Frames=new ChunkAnimFrame*[NumFrames];
for(int i=0;i<NumFrames;i++)
{
Frames[i]=new ChunkAnimFrame(*seq.Frames[i]);
}
}
else
Frames=0;
flags=seq.flags;
pad2=seq.pad2;
pad3=seq.pad3;
pad4=seq.pad4;
num_verts=seq.num_verts;
if(num_verts)
{
v_normal_list=new ChunkVectorFloat[num_verts];
for(int i=0;i<num_verts;i++)
{
v_normal_list[i]=seq.v_normal_list[i];
}
}
else v_normal_list=0;
min=seq.min;
max=seq.max;
radius=seq.radius;
return *this;
}
void ChunkAnimSequence::UpdateNormalsAndExtents(ChunkShape const * cs,List<int>* poly_not_in_bb)
{
if(!cs) return;
num_verts=cs->num_verts;
if(!v_normal_list)v_normal_list=new ChunkVectorFloat[cs->num_verts];
for(int i=0;i<num_verts;i++)
{
v_normal_list[i].x=0;
v_normal_list[i].y=0;
v_normal_list[i].z=0;
}
for(i=0;i<cs->num_polys;i++)
{
const ChunkPoly* cp=&cs->poly_list[i];
for(int j=0;j<cp->num_verts;j++)
{
int vi=cp->vert_ind[j];
for(int k=0;k<NumFrames;k++)
{
v_normal_list[vi]+=Frames[k]->p_normal_list[i];
}
}
}
for(i=0;i<num_verts;i++)
{
double length=mod(v_normal_list[i]);
if(length)
{
v_normal_list[i]=v_normal_list[i]/length;
}
else
{
v_normal_list[i].x=1;
v_normal_list[i].y=0;
v_normal_list[i].z=0;
}
}
max.x = -2000000000;
max.y = -2000000000;
max.z = -2000000000;
min.x = 2000000000;
min.y = 2000000000;
min.z = 2000000000;
radius = 0;
int* vert_in_bb=0;
if(poly_not_in_bb)
{
vert_in_bb=new int[cs->num_verts];
for(i=0;i<cs->num_verts;i++)
{
vert_in_bb[i]=0;
}
for(i=0;i<cs->num_polys;i++)
{
if(poly_not_in_bb->contains(i))continue;
const ChunkPoly* cp=&cs->poly_list[i];
for(int j=0;j<cp->num_verts;j++)
{
vert_in_bb[cp->vert_ind[j]]=1;
}
}
}
for(i=0;i<NumFrames;i++)
{
ChunkAnimFrame* caf=Frames[i];
for (int j=0; j<caf->num_verts; j++)
{
if(vert_in_bb && !vert_in_bb[j]) continue;
max.x = max(max.x, caf->v_list[j].x);
max.y = max(max.y, caf->v_list[j].y);
max.z = max(max.z, caf->v_list[j].z);
min.x = min(min.x, caf->v_list[j].x);
min.y = min(min.y, caf->v_list[j].y);
min.z = min(min.z, caf->v_list[j].z);
double temp_rad = mod(caf->v_list[j]);
radius = max (radius, (float)temp_rad);
}
}
if(vert_in_bb) delete [] vert_in_bb;
}
void ChunkAnimSequence::DeleteInterpolatedFrames()
{
int NewNumFrames=NumFrames;
for(int i=0;i<NumFrames;i++)
{
if(Frames[i]->flags & animframeflag_interpolated_frame)NewNumFrames--;
}
if(NewNumFrames==NumFrames)return;
int framepos=0;
for(i=0;i<NumFrames;i++)
{
if(Frames[i]->flags & animframeflag_interpolated_frame) continue;
Frames[framepos++]=Frames[i];
}
NumFrames=NewNumFrames;
Frames=(ChunkAnimFrame**)realloc(Frames,sizeof(ChunkAnimFrame*)*NumFrames);
}
void ChunkAnimSequence::GenerateInterpolatedFrames(ChunkShape const *cs)
{
DeleteInterpolatedFrames();
/*
int NewNumFrames=NumFrames;
for(int i=0;i<NumFrames;i++)
{
NewNumFrames+=Frames[i]->num_interp_frames;
}
if(NewNumFrames==NumFrames) return;
ChunkAnimFrame** NewFrames=new ChunkAnimFrame*[NewNumFrames];
int framepos=0;
for( i=0;i<NumFrames;i++ )
{
NewFrames[framepos++]=Frames[i];
if(Frames[i]->num_interp_frames==0)continue;
ChunkAnimFrame* startframe=Frames[i];
ChunkAnimFrame* endframe=Frames[(i+1)%NumFrames];
for(int j=0;j<startframe->num_interp_frames;j++)
{
NewFrames[framepos++]=new ChunkAnimFrame(startframe,endframe,startframe->num_interp_frames-j,j+1,cs);
}
}
delete [] Frames;
Frames=NewFrames;
NumFrames=NewNumFrames;
*/
} | [
"a_jagers@ANTHONYJ.(none)"
]
| [
[
[
1,
1221
]
]
]
|
26a67067e5a7e52cc60d000bb2783908d55a0032 | 0f8559dad8e89d112362f9770a4551149d4e738f | /Wall_Destruction/Havok/Source/Physics/Utilities/Actions/Dashpot/hkpDashpotAction.inl | 6e04cf56a8237f9874be02d9ecf46124118fed69 | []
| 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 | 2,693 | 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.
*
*/
inline void hkpDashpotAction::setInWorldSpace( const hkVector4& pivotA, const hkVector4& pivotB )
{
hkpRigidBody* ra = static_cast<hkpRigidBody*>( m_entityA );
hkpRigidBody* rb = static_cast<hkpRigidBody*>( m_entityB );
HK_ASSERT2(0xf568efca, ra && rb, "Bodies not set in dashpot.");
m_point[0].setTransformedInversePos(ra->getTransform(),pivotA);
m_point[1].setTransformedInversePos(rb->getTransform(),pivotB);
}
inline void hkpDashpotAction::setInBodySpace( const hkVector4& pivotA,const hkVector4& pivotB)
{
m_point[0] = pivotA;
m_point[1]= pivotB;
}
inline hkReal hkpDashpotAction::getStrength() const
{
return m_strength;
}
inline void hkpDashpotAction::setStrength(hkReal s)
{
m_strength = s;
}
inline hkReal hkpDashpotAction::getDamping() const
{
return m_damping;
}
inline void hkpDashpotAction::setDamping(hkReal d)
{
m_damping = d;
}
inline const hkVector4& hkpDashpotAction::getPointA() const
{
return m_point[0];
}
inline const hkVector4& hkpDashpotAction::getPointB() const
{
return m_point[1];
}
inline void hkpDashpotAction::setPointA(const hkVector4& pa)
{
m_point[0] = pa;
}
inline void hkpDashpotAction::setPointB(const hkVector4& pb)
{
m_point[1] = pb;
}
inline void hkpDashpotAction::getPoints(hkVector4& pa, hkVector4& pb)
{
pa = m_point[0];
pb = m_point[1];
}
inline void hkpDashpotAction::setPoints(const hkVector4& pa, const hkVector4& pb)
{
m_point[0] = pa;
m_point[1] = pb;
}
/*
* 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,
91
]
]
]
|
ed1765fd618554dcd2606fa0f47a8fc970b2a8c3 | 974a20e0f85d6ac74c6d7e16be463565c637d135 | /trunk/coreLibrary_300/source/physics/dgCollisionCapsule.h | 46fe771140f3217941abd202ff8c1e64d2fb460b | []
| no_license | Naddiseo/Newton-Dynamics-fork | cb0b8429943b9faca9a83126280aa4f2e6944f7f | 91ac59c9687258c3e653f592c32a57b61dc62fb6 | refs/heads/master | 2021-01-15T13:45:04.651163 | 2011-11-12T04:02:33 | 2011-11-12T04:02:33 | 2,759,246 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,587 | h | /* Copyright (c) <2003-2011> <Julio Jerez, Newton Game Dynamics>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*/
#if !defined(AFX_DGCOLLISIONCAPSULE_H__AS235640FER__INCLUDED_)
#define AFX_DGCOLLISIONCAPSULE_H__AS235640FER__INCLUDED_
#include "dgCollisionConvex.h"
#define DG_CAP_SEGMENTS 4
#define DG_CAPSULE_SEGMENTS 6
class dgCollisionCapsule: public dgCollisionConvex
{
public:
dgCollisionCapsule (dgMemoryAllocator* const allocator, dgUnsigned32 signature, dgFloat32 radius, dgFloat32 height, const dgMatrix& matrix);
dgCollisionCapsule(dgWorld* const world, dgDeserialize deserialization, void* const userData);
virtual ~dgCollisionCapsule();
dgFloat32 GetRadius() const {return m_radius;}
dgFloat32 GetHeight() const {return m_height[0];}
private:
void Init (dgFloat32 radius, dgFloat32 height);
void TesselateTriangle (dgInt32 level, dgFloat32 side, const dgVector& p0, const dgVector& p1, const dgVector& p2, dgInt32& count, dgVector* ouput) const;
virtual dgFloat32 RayCast (const dgVector& localP0, const dgVector& localP1, dgContactPoint& contactOut, OnRayPrecastAction preFilter, const dgBody* const body, void* const userData) const;
virtual dgFloat32 RayCastSimd (const dgVector& localP0, const dgVector& localP1, dgContactPoint& contactOut, OnRayPrecastAction preFilter, const dgBody* const body, void* const userData) const;
virtual dgVector SupportVertex (const dgVector& dir) const;
virtual dgVector SupportVertexSimd (const dgVector& dir) const;
virtual dgInt32 CalculatePlaneIntersection (const dgVector& normal, const dgVector& point, dgVector* const contactsOut) const;
virtual dgInt32 CalculatePlaneIntersectionSimd (const dgVector& normal, const dgVector& point, dgVector* const contactsOut) const;
// virtual void DebugCollision (const dgBody& myBody, DebugCollisionMeshCallback callback) const;
virtual void DebugCollision (const dgMatrix& matrix, OnDebugCollisionMeshCallback callback, void* const userData) const;
virtual dgInt32 CalculateSignature () const;
virtual void SetCollisionBBox (const dgVector& p0, const dgVector& p1);
virtual dgFloat32 CalculateMassProperties (dgVector& inertia, dgVector& crossInertia, dgVector& centerOfMass) const;
virtual void GetCollisionInfo(dgCollisionInfo* info) const;
virtual void Serialize(dgSerialize callback, void* const userData) const;
dgFloat32 m_height[2];
dgFloat32 m_radius;
dgFloat32 m_tethaStep;
dgFloat32 m_tethaStepInv;
dgFloat32 m_delCosTetha;
dgFloat32 m_delSinTetha;
dgVector m_silhuette[4];
dgVector m_vertex[2 * DG_CAP_SEGMENTS * DG_CAPSULE_SEGMENTS];
static dgInt32 m_shapeRefCount;
static dgConvexSimplexEdge m_edgeArray[];
friend class dgWorld;
};
#endif
| [
"[email protected]@b7a2f1d6-d59d-a8fe-1e9e-8d4888b32692"
]
| [
[
[
1,
83
]
]
]
|
69346777c53ce88c871645e713b1e35adba8b5e6 | 3e69b159d352a57a48bc483cb8ca802b49679d65 | /tags/release-2006-01-06/common/drawpanel.cpp | 2983aad30034f24d2f80a69849577267b03a0e0b | []
| no_license | BackupTheBerlios/kicad-svn | 4b79bc0af39d6e5cb0f07556eb781a83e8a464b9 | 4c97bbde4b1b12ec5616a57c17298c77a9790398 | refs/heads/master | 2021-01-01T19:38:40.000652 | 2006-06-19T20:01:24 | 2006-06-19T20:01:24 | 40,799,911 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 23,763 | cpp | /******************************************************************/
/* drawpanel.cpp - fonctions des classes du type WinEDA_DrawPanel */
/******************************************************************/
#ifdef __GNUG__
#pragma implementation
#endif
#include "fctsys.h"
#include "common.h"
#include "macros.h"
#include "id.h"
/* Variables locales */
static wxPoint MouseBoardPos; // position du cureur souris en coord PCB
/* table des evenements captes par un WinEDA_DrawPanel */
BEGIN_EVENT_TABLE(WinEDA_DrawPanel, EDA_DRAW_PANEL)
EVT_LEAVE_WINDOW(WinEDA_DrawPanel::OnMouseLeaving)
EVT_MOUSE_EVENTS(WinEDA_DrawPanel::OnMouseEvent)
EVT_CHAR(WinEDA_DrawPanel::OnKeyEvent)
EVT_CHAR_HOOK(WinEDA_DrawPanel::OnKeyEvent)
EVT_PAINT(WinEDA_DrawPanel::OnPaint)
EVT_SIZE(WinEDA_DrawPanel::OnSize)
EVT_ERASE_BACKGROUND(WinEDA_DrawPanel::OnEraseBackground)
EVT_SCROLLWIN(WinEDA_DrawPanel::OnScroll)
EVT_ACTIVATE(WinEDA_DrawPanel::OnActivate)
EVT_MENU_RANGE( ID_POPUP_ZOOM_START_RANGE, ID_POPUP_ZOOM_END_RANGE,
WinEDA_DrawPanel::Process_Popup_Zoom)
END_EVENT_TABLE()
/***********************************************************/
/* Fonctions de base de WinEDA_DrawPanel: l'ecran de trace */
/***********************************************************/
WinEDA_DrawPanel::WinEDA_DrawPanel(WinEDA_DrawFrame *parent, int id,
const wxPoint& pos, const wxSize& size):
EDA_DRAW_PANEL(parent, id, pos, size,
wxBORDER|wxNO_FULL_REPAINT_ON_RESIZE)
{
m_Parent = parent;
m_Ident = m_Parent->m_Ident;
m_Scroll_unit = 1;
m_ScrollButt_unit = 40;
SetBackgroundColour(wxColour(ColorRefs[g_DrawBgColor].m_Red,
ColorRefs[g_DrawBgColor].m_Green,
ColorRefs[g_DrawBgColor].m_Blue ) );
EnableScrolling(TRUE,TRUE);
m_ClipBox.SetSize(size);
m_ClipBox.SetX(0);
m_ClipBox.SetY(0);
m_CanStartBlock = -1; // Command block can start if >= 0
m_AbortEnable = m_AbortRequest = FALSE;
m_AutoPAN_Enable = TRUE;
m_IgnoreMouseEvents = FALSE;
if ( m_Parent->m_Parent->m_EDA_Config )
m_AutoPAN_Enable = m_Parent->m_Parent->m_EDA_Config->Read(wxT("AutoPAN"), TRUE);
m_AutoPAN_Request = FALSE;
m_Block_Enable = FALSE;
m_PanelDefaultCursor = m_PanelCursor = wxCURSOR_ARROW;
}
/***********************************/
int WinEDA_DrawPanel::GetZoom(void)
/***********************************/
{
return GetScreen()->GetZoom();
}
/***************************************/
void WinEDA_DrawPanel::SetZoom(int zoom)
/***************************************/
{
GetScreen()->SetZoom(zoom);
}
/************************************/
wxSize WinEDA_DrawPanel::GetGrid(void)
/************************************/
{
return GetScreen()->GetGrid();
}
/******************************************************/
void WinEDA_DrawPanel::PrepareGraphicContext(wxDC * DC)
/******************************************************/
{
DC->SetPen(*DrawPen);
DC->SetBrush(*DrawBrush);
GRResetPenAndBrush(DC);
DC->SetBackgroundMode(wxTRANSPARENT);
#ifdef WX_ZOOM
int zoom = GetZoom();
double f_scale = 1.0/(double)zoom;
DC->SetUserScale(f_scale, f_scale);
PrepareDC(*DC);
#endif
SetBoundaryBox();
}
/*********************************************************************/
wxPoint WinEDA_DrawPanel::CalcAbsolutePosition(const wxPoint & rel_pos)
/*********************************************************************/
/* retourne la position absolue en pixels de la position rel_pos,
donnée en position relative scrollée (en pixel)
*/
{
wxPoint pos;
#ifdef WX_ZOOM
CalcUnscrolledPosition( rel_pos.x, rel_pos.y, &pos.x, &pos.y );
#else
int ii, jj;
GetViewStart(&pos.x, &pos.y);
GetScrollPixelsPerUnit(&ii, &jj);
pos.x *= ii; pos.y *= jj;
pos.x += rel_pos.x;
pos.y += rel_pos.y;
#endif
return pos;
}
/**********************************************************************/
wxPoint WinEDA_DrawPanel::CursorRealPosition(const wxPoint & ScreenPos)
/**********************************************************************/
/* Retourne la position en unites utilisateur du pointeur souris
ScreenPos = position pointeur en coord absolue ecran
*/
{
wxPoint curpos;
curpos.x = ScreenPos.x * GetZoom();
curpos.y = ScreenPos.y * GetZoom();
curpos.x += GetScreen()->m_DrawOrg.x;
curpos.y += GetScreen()->m_DrawOrg.y;
return curpos;
}
/********************************************************/
bool WinEDA_DrawPanel::IsPointOnDisplay(wxPoint ref_pos)
/********************************************************/
/* retourne TRUE si le point de coord physique ref_pos
est visible sur l'ecran, c'est a dire:
si ref_pos est sur la partie du schema ou pcb affichee a l'ecran
*/
{
wxPoint pos;
EDA_Rect display_rect;
SetBoundaryBox();
display_rect = m_ClipBox;
// Reduction legere des dimension de l'ecran utile pour eviter cadrage
// en limite d'ecran
#define PIXEL_MARGIN 8
display_rect.Inflate(-PIXEL_MARGIN,-PIXEL_MARGIN);
// Conversion en coord physiques
pos = CalcAbsolutePosition( display_rect.GetPosition() );
pos.x *= GetZoom();
pos.y *= GetZoom();
pos.x += GetScreen()->m_DrawOrg.x;
pos.y += GetScreen()->m_DrawOrg.y;
display_rect.SetX(pos.x); display_rect.SetY(pos.y);
display_rect.SetWidth( display_rect.GetWidth() * GetZoom() );
display_rect.SetHeight( display_rect.GetHeight() * GetZoom() );
return display_rect.Inside(ref_pos);
}
/********************************************************/
wxPoint WinEDA_DrawPanel::CursorScreenPosition(void)
/********************************************************/
/* retourne la position sur l'ecran,en pixels, du curseur
Orgine = coord absolue 0,0;
*/
{
wxPoint curpos = GetScreen()->m_Curseur;
curpos.x -= GetScreen()->m_DrawOrg.x;
curpos.y -= GetScreen()->m_DrawOrg.y;
curpos.x /= GetZoom();
curpos.y /= GetZoom();
return curpos;
}
/*********************************************************/
wxPoint WinEDA_DrawPanel::GetScreenCenterRealPosition(void)
/*********************************************************/
{
wxSize size;
wxPoint realpos;
size = GetClientSize();
size.x /= 2; size.y /= 2;
realpos = CalcAbsolutePosition( wxPoint(size.x, size.y) );
realpos.x *= GetZoom();
realpos.y *= GetZoom();
realpos.x += GetScreen()->m_DrawOrg.x;
realpos.y += GetScreen()->m_DrawOrg.y;
return realpos;
}
/**********************************************/
void WinEDA_DrawPanel::MouseToCursorSchema(void)
/**********************************************/
/* place le curseur souris sur la position du curseur schema
*/
{
wxPoint Mouse = CursorScreenPosition();
MouseTo(Mouse);
}
/****************************************************/
void WinEDA_DrawPanel::MouseTo(const wxPoint & Mouse)
/****************************************************/
/* place le curseur souris sur la position Mouse
*/
{
wxPoint mouse;
#ifdef WX_ZOOM
CalcScrolledPosition(Mouse.x, Mouse.y, &mouse.x, &mouse.y);
#else
mouse = Mouse;
mouse.x -= GetScreen()->m_StartVisu.x;
mouse.y -= GetScreen()->m_StartVisu.y;
#endif
GRMouseWarp(this, mouse);
}
/********************************************************/
void WinEDA_DrawPanel::OnActivate(wxActivateEvent& event)
/********************************************************/
{
m_CanStartBlock = -1; // Commande block can't start
}
/***********************************************************/
void WinEDA_DrawPanel::OnEraseBackground(wxEraseEvent& event)
/***********************************************************/
{
event.Skip();
}
/*********************************************************/
void WinEDA_DrawPanel::OnScroll( wxScrollWinEvent &event )
/*********************************************************/
{
int id = event.GetEventType();
int dir, value = 0;
int x,y;
GetViewStart( &x, &y );
dir = event.GetOrientation(); // wxHORIZONTAL ou wxVERTICAL
if ( id == wxEVT_SCROLLWIN_LINEUP) value = - m_ScrollButt_unit;
else if ( id == wxEVT_SCROLLWIN_LINEDOWN) value = m_ScrollButt_unit;
else if ( id == wxEVT_SCROLLWIN_THUMBTRACK )
{
value = event.GetPosition();
if ( dir == wxHORIZONTAL ) Scroll( value, -1 );
else Scroll( -1, value );
return;
}
else
{
event.Skip();
return;
}
if ( dir == wxHORIZONTAL )
{
Scroll( x + value, -1 );
}
else
{
Scroll( -1, y + value );
}
}
/*************************************************/
void WinEDA_DrawPanel::OnSize(wxSizeEvent & event)
/*************************************************/
{
SetBoundaryBox();
}
/******************************************/
void WinEDA_DrawPanel::SetBoundaryBox(void)
/******************************************/
{
BASE_SCREEN * Screen = GetScreen();;
wxPoint org;
int ii, jj;
Screen->m_SizeVisu = GetClientSize();
GetViewStart(&org.x, &org.y);
GetScrollPixelsPerUnit(&ii, &jj);
org.x *= ii; org.y *= jj;
Screen->m_StartVisu = org;
m_ClipBox.SetOrigin(org);
m_ClipBox.SetSize(GetClientSize());
#ifdef WX_ZOOM
m_ClipBox.m_Pos.x *= GetZoom();
m_ClipBox.m_Pos.y *= GetZoom();
m_ClipBox.m_Size.x *= GetZoom();
m_ClipBox.m_Size.y *= GetZoom();
#else
m_ClipBox.m_Pos.x -= GetScreen()->m_StartVisu.x;
m_ClipBox.m_Pos.y -= GetScreen()->m_StartVisu.y;
#endif
m_ScrollButt_unit = MIN( Screen->m_SizeVisu.x, Screen->m_SizeVisu.y ) / 4;
if ( m_ScrollButt_unit < 2 ) m_ScrollButt_unit = 2;
Screen->m_ScrollbarPos.x = GetScrollPos(wxHORIZONTAL);
Screen->m_ScrollbarPos.y = GetScrollPos(wxVERTICAL);
}
/*********************************************/
void WinEDA_DrawPanel::EraseScreen(wxDC * DC)
/*********************************************/
{
GRSetDrawMode(DC, GR_COPY);
GRSFilledRect(&m_ClipBox, DC, m_ClipBox.GetX(), m_ClipBox.GetY(),
m_ClipBox.GetRight(), m_ClipBox.GetBottom(),
g_DrawBgColor, g_DrawBgColor);
}
/***************************************************/
void WinEDA_DrawPanel::OnPaint(wxPaintEvent & event)
/***************************************************/
{
wxPaintDC paintDC(this);
EDA_Rect tmp;
wxRect PaintClipBox;
wxPoint org;
PrepareGraphicContext(&paintDC);
tmp = m_ClipBox;
org = m_ClipBox.GetOrigin();
wxRegionIterator upd(GetUpdateRegion()); // get the update rect list
while ( upd )
{
PaintClipBox = upd.GetRect();
upd++;
PaintClipBox.x += org.x;
PaintClipBox.y += org.y;
#ifdef WX_ZOOM
m_ClipBox.m_Pos.x = PaintClipBox.x * GetZoom();
m_ClipBox.m_Pos.y = PaintClipBox.y * GetZoom();
m_ClipBox.m_Size.x = PaintClipBox.m_Size.x * GetZoom();
m_ClipBox.m_Size.y = PaintClipBox.m_Size.y * GetZoom();
PaintClipBox = m_ClipBox;
#else
m_ClipBox.SetX(PaintClipBox.GetX());
m_ClipBox.SetY(PaintClipBox.GetY());
m_ClipBox.SetWidth(PaintClipBox.GetWidth());
m_ClipBox.SetHeight(PaintClipBox.GetHeight());
#endif
wxDCClipper * dcclip = new wxDCClipper(paintDC, PaintClipBox);
ReDraw(&paintDC, TRUE);
delete dcclip;
}
m_ClipBox = tmp;
}
/****************************************************/
void WinEDA_DrawPanel::ReDraw(wxDC * DC, bool erasebg)
/****************************************************/
{
BASE_SCREEN * Screen = GetScreen();
if ( Screen == NULL ) return;
if ( (g_DrawBgColor != WHITE) && (g_DrawBgColor != BLACK) ) g_DrawBgColor = BLACK;
if(g_DrawBgColor == WHITE)
{
g_XorMode = GR_NXOR;
g_GhostColor = BLACK;
}
else
{
g_XorMode = GR_XOR;
g_GhostColor = WHITE;
}
#ifdef WX_ZOOM
int zoom = GetZoom();
double f_scale = 1.0/(double)zoom;
DC->SetUserScale(f_scale, f_scale);
#endif
if(erasebg) PrepareGraphicContext(DC);
DC->SetFont(* g_StdFont);
DC->BeginDrawing();
SetBackgroundColour(wxColour(ColorRefs[g_DrawBgColor].m_Red,
ColorRefs[g_DrawBgColor].m_Green,
ColorRefs[g_DrawBgColor].m_Blue ));
GRResetPenAndBrush(DC);
DC->SetBackground(*wxBLACK_BRUSH );
DC->SetBackgroundMode(wxTRANSPARENT);
m_Parent->RedrawActiveWindow(DC, erasebg);
DC->EndDrawing();
}
/***********************************************/
void WinEDA_DrawPanel::DrawBackGround(wxDC * DC)
/***********************************************/
/* Trace les axes X et Y et la grille
La grille n'est affichee que si elle peut etre facilement visible
La grille passe toujours par le centre de l'ecran
*/
{
int Color = BLUE;
BASE_SCREEN * screen = GetScreen();
int ii,jj ,xg , yg , color;
wxSize pas_grille_affichee;
bool drawgrid = FALSE;
int zoom = GetZoom();
wxSize size;
wxPoint org;
double pasx, pasy;
color = screen->m_GridColor;
GRSetDrawMode(DC, GR_COPY);
/* le pas d'affichage doit etre assez grand pour avoir une grille visible */
drawgrid = m_Parent->m_Draw_Grid;
pas_grille_affichee = screen->GetGrid();
ii = pas_grille_affichee.x / zoom;
if (ii < 5 ) { pas_grille_affichee.x *= 2 ; ii *= 2; }
if( ii < 5 ) drawgrid = FALSE; // grille trop petite
ii = pas_grille_affichee.y / zoom;
if (ii < 5 ) { pas_grille_affichee.y *= 2 ; ii *= 2; }
if( ii < 5 ) drawgrid = FALSE; // grille trop petite
GetViewStart(&org.x, &org.y);
GetScrollPixelsPerUnit(&ii, &jj);
org.x *= ii; org.y *= jj;
screen->m_StartVisu = org;
org.x *= zoom; org.y *= zoom;
org.x += screen->m_DrawOrg.x; org.y += screen->m_DrawOrg.y;
size = GetClientSize();
size.x *= zoom; size.y *= zoom;
pasx = screen->m_UserGrid.x * m_Parent->m_InternalUnits;
pasy = screen->m_UserGrid.y * m_Parent->m_InternalUnits;
if ( screen->m_UserGridUnit != INCHES )
{
pasx /= 25.4; pasy /= 25.4;
}
if( drawgrid)
{
m_Parent->PutOnGrid(&org) ;
GRSetColorPen(DC, color );
for ( ii = 0 ; ; ii++ )
{
xg = screen->m_UserGridIsON ? (int)( (ii * pasx) + 0.5)
:ii * pas_grille_affichee.x;
int xpos = org.x + xg;
for ( jj = 0 ; ; jj++ )
{
yg = screen->m_UserGridIsON ? (int)( (jj * pasy) + 0.5)
: jj * pas_grille_affichee.y;
GRPutPixel(&m_ClipBox, DC, xpos, org.y + yg, color);
if ( yg > size.y ) break;
}
if ( xg > size.x ) break;
}
}
/* trace des axes principaux */
if ( m_Parent->m_Draw_Axes )
{
/* Trace de l'axe vertical */
GRDashedLine(&m_ClipBox, DC, 0, -screen->ReturnPageSize().y,
0, screen->ReturnPageSize().y, Color );
/* Trace de l'axe horizontal */
GRDashedLine(&m_ClipBox, DC, -screen->ReturnPageSize().x, 0,
screen->ReturnPageSize().x, 0, Color );
}
/* trace des axes auxiliaires */
if ( m_Parent->m_Draw_Auxiliary_Axe)
{
m_Draw_Auxiliary_Axe(DC, FALSE);
}
}
/********************************************************************/
void WinEDA_DrawPanel::m_Draw_Auxiliary_Axe(wxDC * DC, int drawmode)
/********************************************************************/
{
if ( m_Parent->m_Auxiliary_Axe_Position.x == 0 &&
m_Parent->m_Auxiliary_Axe_Position.y == 0 )
return;
int Color = DARKRED;
BASE_SCREEN * screen = GetScreen();
GRSetDrawMode(DC, drawmode);
/* Trace de l'axe vertical */
GRDashedLine(&m_ClipBox, DC,
m_Parent->m_Auxiliary_Axe_Position.x, -screen->ReturnPageSize().y,
m_Parent->m_Auxiliary_Axe_Position.x, screen->ReturnPageSize().y,
Color );
/* Trace de l'axe horizontal */
GRDashedLine(&m_ClipBox, DC,
-screen->ReturnPageSize().x, m_Parent->m_Auxiliary_Axe_Position.y,
screen->ReturnPageSize().x, m_Parent->m_Auxiliary_Axe_Position.y,
Color );
}
/*******************************************************/
void WinEDA_DrawPanel::OnRightClick(wxMouseEvent& event)
/*******************************************************/
/* Construit et affiche un menu Popup lorsque on actionne le bouton droit
de la souris
*/
{
wxPoint pos;
wxMenu MasterMenu;
pos.x = event.GetX(); pos.y = event.GetY();
m_Parent->OnRightClick(pos, &MasterMenu);
AddMenuZoom(&MasterMenu);
PopupMenu( &MasterMenu, pos);
}
/******************************************************/
void WinEDA_DrawPanel::OnMouseLeaving(wxMouseEvent& event)
/*******************************************************/
// Called when the canvas receives a mouse event leaving frame. //
{
if (GetScreen()->ManageCurseur == NULL ) // Pas de commande encours
m_AutoPAN_Request = FALSE;
if ( ! m_AutoPAN_Enable || ! m_AutoPAN_Request || m_IgnoreMouseEvents)
return;
// Auto pa if mouse is leave working aera:
wxSize size = GetClientSize();
if ( (size.x < event.GetX() ) ||
(size.y < event.GetY() ) ||
( event.GetX() <= 0) || ( event.GetY() <= 0 ) )
m_Parent->OnZoom(ID_POPUP_ZOOM_CENTER);
}
/******************************************************/
void WinEDA_DrawPanel::OnMouseEvent(wxMouseEvent& event)
/*******************************************************/
// Called when the canvas receives a mouse event. //
{
int localrealbutt = 0, localbutt = 0, localkey = 0;
BASE_SCREEN * screen;
static WinEDA_DrawPanel * LastPanel;
if ( event.Leaving() || event.Entering() )
{
m_CanStartBlock = -1;
}
if (GetScreen()->ManageCurseur == NULL ) // Pas de commande en cours
m_AutoPAN_Request = FALSE;
if ( m_IgnoreMouseEvents ) return;
if ( m_Parent->m_FrameIsActive ) SetFocus();
else return;
// Mouse Wheel is a zoom command:
if ( event.m_wheelRotation )
{
// This is a zoom in ou out command
if ( event.GetWheelRotation() > 0 ) localkey = WXK_F1;
else localkey = WXK_F2;
}
if( !event.IsButton() && !event.Moving() &&
!event.Dragging() && ! localkey )
{
return;
}
if( event.RightDown() )
{
OnRightClick(event); return;
}
if( event.LeftIsDown() ) localrealbutt |= GR_M_LEFT_DOWN;
if( event.MiddleIsDown() ) localrealbutt |= GR_M_MIDDLE_DOWN;
if( event.LeftDown()) localbutt = GR_M_LEFT_DOWN;
if( event.ButtonDClick(1)) localbutt = GR_M_LEFT_DOWN|GR_M_DCLICK;
if( event.MiddleDown()) localbutt = GR_M_MIDDLE_DOWN;
if( event.ButtonDClick(2)) {}; // Unused
localrealbutt |= localbutt; /* compensation defaut wxGTK */
MouseBoardPos = CalcAbsolutePosition(wxPoint(event.GetX(), event.GetY()));
wxClientDC DC(this);
int kbstat = 0;
screen = GetScreen();
DC.SetBackground(*wxBLACK_BRUSH );
PrepareGraphicContext(&DC);
g_KeyPressed = localkey;
if( event.ShiftDown() ) kbstat |= GR_KB_SHIFT;
if( event.ControlDown() ) kbstat |= GR_KB_CTRL;
if( event.AltDown() ) kbstat |= GR_KB_ALT;
g_MouseOldButtons = localrealbutt;
// Appel des fonctions liées au Double Click ou au Click
if( localbutt == (int)(GR_M_LEFT_DOWN|GR_M_DCLICK) )
m_Parent->OnLeftDClick(&DC, wxPoint(MouseBoardPos));
else if ( event.LeftDown() )
m_Parent->OnLeftClick(&DC, wxPoint(MouseBoardPos));
if( event.ButtonUp(2) && (screen->BlockLocate.m_State == STATE_NO_BLOCK) )
{ // The middle button has been relached, with no block command:
// We use it for a zoom center command
g_KeyPressed = localkey = WXK_F4;
}
/* Appel de la fonction generale de gestion des mouvements souris
et commandes clavier */
m_Parent->GeneralControle(&DC, MouseBoardPos);
/*******************************/
/* Control of block commands : */
/*******************************/
// Command block can't start if mouse is dragging a new panel
if (LastPanel != this ) m_CanStartBlock = -1;
// A new command block can start after a release buttons
// Avoid a false start block when a dialog bos is demiss,
// or when changing panels in hierachy navigation
if ( !event.LeftIsDown() && !event.MiddleIsDown())
{
m_CanStartBlock = 0;
}
if( m_Block_Enable && !(localbutt & GR_M_DCLICK) )
{
if ( (screen->BlockLocate.m_Command == BLOCK_IDLE) ||
(screen->BlockLocate.m_State == STATE_NO_BLOCK))
{
m_CursorStartPos = screen->m_Curseur;
screen->BlockLocate.SetOrigin(m_CursorStartPos);
}
if ( event.LeftDown() || event.MiddleDown() )
{
m_CursorStartPos = screen->m_Curseur;
if ( screen->BlockLocate.m_State == STATE_BLOCK_MOVE )
{
m_AutoPAN_Request = FALSE;
m_Parent->HandleBlockPlace(&DC);
}
}
else if( (m_CanStartBlock >= 0 ) &&
( event.LeftIsDown() || event.MiddleIsDown() )
&& screen->ManageCurseur == NULL
&& screen->ForceCloseManageCurseur == NULL )
{
if ( screen->BlockLocate.m_State == STATE_NO_BLOCK )
{
int cmd_type = kbstat;
if ( event.MiddleIsDown() ) cmd_type |= MOUSE_MIDDLE;
if ( ! m_Parent->HandleBlockBegin(&DC, cmd_type, m_CursorStartPos) )
{ // error
m_Parent->DisplayToolMsg( wxT("WinEDA_DrawPanel::OnMouseEvent() Block Error") );
}
else
{
m_AutoPAN_Request = TRUE;
SetCursor(m_PanelCursor = wxCURSOR_SIZING);
}
}
}
if( event.ButtonUp(1) || event.ButtonUp(2) )
{ /* Relachement du bouton: fin de delimitation de block.
La commande peut etre terminee (DELETE) ou continuer par le placement
du block ainsi delimite (MOVE, COPY).
Cependant bloc est annule si sa taille est trop petite*/
bool BlockIsSmall =
( ABS(screen->BlockLocate.GetWidth()/GetZoom()) < 3) &&
( ABS(screen->BlockLocate.GetHeight()/GetZoom()) < 3);
if ( (screen->BlockLocate.m_State != STATE_NO_BLOCK) && BlockIsSmall )
{
if( GetScreen()->ForceCloseManageCurseur )
{
GetScreen()->ForceCloseManageCurseur(m_Parent, &DC);
m_AutoPAN_Request = FALSE;
}
SetCursor(m_PanelCursor = m_PanelDefaultCursor);
}
else if ( screen->BlockLocate.m_State == STATE_BLOCK_END )
{
m_AutoPAN_Request = FALSE;
m_Parent->HandleBlockEnd(&DC);
SetCursor(m_PanelCursor = m_PanelDefaultCursor);
if ( screen->BlockLocate.m_State == STATE_BLOCK_MOVE )
{
m_AutoPAN_Request = TRUE;
SetCursor(m_PanelCursor = wxCURSOR_HAND);
}
}
}
}
// Arret de block sur un double click ( qui peut provoquer un move block
// si on déplace la souris dans ce double click
if ( localbutt == (int)(GR_M_LEFT_DOWN|GR_M_DCLICK) )
{
if ( screen->BlockLocate.m_Command != BLOCK_IDLE )
{
if( GetScreen()->ForceCloseManageCurseur )
{
GetScreen()->ForceCloseManageCurseur(m_Parent, &DC);
m_AutoPAN_Request = FALSE;
}
}
}
#if 0
wxString msg_debug;
msg_debug.Printf(" block state %d, cmd %d",
screen->BlockLocate.m_State, screen->BlockLocate.m_Command);
m_Parent->PrintMsg(msg_debug);
#endif
LastPanel = this;
m_Parent->SetToolbars();
}
/****************************************************/
void WinEDA_DrawPanel::OnKeyEvent(wxKeyEvent& event)
/****************************************************/
{
long key, localkey;
bool escape = FALSE;
key = localkey = event.m_keyCode;
switch( localkey )
{
case WXK_CONTROL:
case WXK_CAPITAL:
case WXK_SHIFT:
case WXK_NUMLOCK:
case WXK_LBUTTON:
case WXK_RBUTTON:
case 0x0135: /* Alt key */
return;
case WXK_ESCAPE:
escape = m_AbortRequest = TRUE;
break;
}
if( event.ControlDown() ) localkey |= GR_KB_CTRL;
if( event.AltDown() ) localkey |= GR_KB_ALT;
if( event.ShiftDown() && (key > 256) ) localkey |= GR_KB_SHIFT;
wxClientDC DC(this);
BASE_SCREEN * Screen = GetScreen();
PrepareGraphicContext(&DC);
g_KeyPressed = localkey;
if ( escape )
{
if( Screen->ManageCurseur && Screen->ForceCloseManageCurseur )
{
SetCursor(m_PanelCursor = m_PanelDefaultCursor);
Screen->ForceCloseManageCurseur(m_Parent, &DC);
SetCursor(m_PanelCursor = m_PanelDefaultCursor);
}
else m_Parent->SetToolID(0, m_PanelCursor = m_PanelDefaultCursor = wxCURSOR_ARROW, wxEmptyString);
}
m_Parent->GeneralControle(&DC, MouseBoardPos);
}
| [
"bokeoa@244deca0-f506-0410-ab94-f4f3571dea26"
]
| [
[
[
1,
856
]
]
]
|
82dbe2f10fdde15e0f6a5b79a6cac343f19235ad | 8f816734df7cb71af9c009fa53eeb80a24687e63 | /RenderSystem/src/RenderSystem.cpp | 50bba8d2362d3af6ce19754ac2e36a0aaaface1a | []
| no_license | terepe/rpgskyengine | 46a3a09a1f4d07acf1a04a1bcefff2a9aabebf56 | fbe0ddc86440025d9670fc39fb7ca72afa223953 | refs/heads/master | 2021-01-23T13:18:32.028357 | 2011-06-01T13:35:16 | 2011-06-01T13:35:16 | 35,915,383 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 8,863 | cpp | #include "RenderSystem.h"
static CRenderSystem* g_pRenderSystem = NULL;
void SetRenderSystem(CRenderSystem* pRenderSystem)
{
g_pRenderSystem = pRenderSystem;
}
CRenderSystem& GetRenderSystem()
{
//assert(g_pRenderSystem);
return *g_pRenderSystem;
}
CRenderSystem::CRenderSystem()
{
}
CRenderSystem::~CRenderSystem()
{
}
void CRenderSystem::world2Screen(const Vec3D& vWorldPos, Pos2D& posScreen)
{
Matrix mProj;
Matrix View;
getProjectionMatrix(mProj);
getViewMatrix(View);
Vec4D vOut = mProj*View*Vec4D(vWorldPos,1);
float fW = vOut.w;
CRect<int> rc;
getViewport(rc);
posScreen.x = int(rc.left+(rc.right-rc.left)*(0.5f+vOut.x*0.5f/fW));
posScreen.y = int(rc.top+(rc.bottom-rc.top)*(0.5f-vOut.y*0.5f/fW));
}
#include "Intersect.h"
void CRenderSystem::GetPickRay(Vec3D& vRayPos, Vec3D& vRayDir,int x, int y)
{
Matrix mProj;
getProjectionMatrix(mProj);
CRect<int> rc;
getViewport(rc);
Matrix mView;
getViewMatrix(mView);
::GetPickRay(vRayPos,vRayDir,x,y,mView,mProj,rc.getRECT());
}
CMaterialMgr& CRenderSystem::getMaterialMgr()
{
return m_MaterialMgr;
}
bool CRenderSystem::prepareMaterial(const char* szMaterialName, float fOpacity)
{
return prepareMaterial(getMaterialMgr().getItem(szMaterialName),fOpacity);
}
#include "Timer.h"
bool CRenderSystem::prepareMaterial(/*const */CMaterial& material, float fOpacity) // 由于使用了自动注册纹理的机制,很遗憾的导致不能用“const”
{
CTextureMgr& TM = GetTextureMgr();
for (size_t i=0;i<8;++i)
{
if (material.uTexture[i]==-1)
{
material.uTexture[i] = TM.RegisterTexture(material.getTexture(i));
}
// ----
SetTexture(i, material.uTexture[i]);
// ----
if (material.uTexture[i]==0)
{
break;
}
}
if (material.uShader==-1)
{
material.uShader = GetShaderMgr().registerItem(material.getShader());
}
// ----
SetLightingEnabled(material.bLightingEnabled);
SetCullingMode((CullingMode)material.uCull);
// ----
SetAlphaTestFunc(material.bAlphaTest, (CompareFunction)material.nAlphaTestCompare, material.uAlphaTestValue);
SetBlendFunc(material.bBlend, (SceneBlendOperation)material.nBlendOP, (SceneBlendFactor)material.nBlendSrc, (SceneBlendFactor)material.nBlendDest);
SetDepthBufferFunc(material.bDepthTest,material.bDepthWrite);
// ----
if (0==material.uShader)
{
for (size_t i=0;i<8;++i)
{
CMaterial::TextureOP& texOP = material.textureOP[i];
SetTextureColorOP(i, (TextureBlendOperation)texOP.nColorOP, (TextureBlendSource)texOP.nColorSrc1, (TextureBlendSource)texOP.nColorSrc2);
SetTextureColorOP(i, (TextureBlendOperation)texOP.nAlphaOP, (TextureBlendSource)texOP.nAlphaSrc1, (TextureBlendSource)texOP.nAlphaSrc2);
if (TBOP_DISABLE == texOP.nColorOP)
{
break;
}
}
}
else
{
CShader* pShader = GetShaderMgr().getSharedShader();
if (pShader)
{
// for Terrain
pShader->setVec2D("g_fScaleUV",material.vUVScale);
}
SetShader(material.uShader);
}
return true;
/* if (material.bLightingEnabled)
{
SetMaterial(material.vAmbient,material.vDiffuse);
}
if (0==material.uShader)
{
//SetSamplerAddressUV(0,ADDRESS_WRAP,ADDRESS_WRAP);
if (material.vTexAnim.lengthSquared()>0.0f)
{
Matrix matTex=Matrix::UNIT;
float fTime = (float)GetGlobalTimer().GetTime();
matTex._13=fTime*material.vTexAnim.x;
matTex._23=fTime*material.vTexAnim.y;
setTextureMatrix(0, TTF_COUNT3, matTex);
}
Color32 cFactor = material.cEmissive;
if (material.m_fOpacity<0.0f)
{
fOpacity = (float)(rand()%255)/255.0f;
}
else
{
fOpacity *= material.m_fOpacity;
}
if (material.uDiffuse)
{
SetTexture(0, material.uDiffuse);
cFactor.a=(unsigned char)(cFactor.a*fOpacity);
SetTextureFactor(cFactor);
if (material.bLightingEnabled)
{
SetTextureColorOP(0, TBOP_MODULATE, TBS_TEXTURE, TBS_DIFFUSE);
}
else
{
SetTextureColorOP(0, TBOP_MODULATE, TBS_TEXTURE, TBS_TFACTOR);
}
if(material.bBlend||material.m_fOpacity<1.0f)
{
SetBlendFunc(true, BLENDOP_ADD, SBF_SOURCE_ALPHA, SBF_ONE_MINUS_SOURCE_ALPHA);
}
if (material.m_fOpacity<1.0f)
{
SetTextureAlphaOP(0, TBOP_MODULATE, TBS_TEXTURE, TBS_TFACTOR);
}
else if (material.bAlphaTest||material.bBlend)
{
SetTextureAlphaOP(0, TBOP_SOURCE1, TBS_TEXTURE);
}
else
{
SetTextureAlphaOP(0, TBOP_DISABLE);
}
//////////////////////////////////////////////////////////////////////////
if (material.uSpecular)
{
SetTexture(1, material.uSpecular);
SetTextureColorOP(0, TBOP_MODULATE, TBS_TEXTURE, TBS_DIFFUSE);
setResultARGToTemp(1,true);
SetTextureColorOP(1, TBOP_MODULATE_X2, TBS_TEXTURE, TBS_SPECULAR);
SetTextureColorOP(2, TBOP_ADD, TBS_CURRENT, TBS_TEMP);
SetTexCoordIndex(0,0);
SetTexCoordIndex(1,0);
SetTexCoordIndex(2,0);
}
else if (material.uReflection)
{
SetTextureColorOP(1, TBOP_MODULATE_X2, TBS_CURRENT, TBS_TEXTURE);
SetTexCoordIndex(1,TCI_CAMERASPACE_NORMAL|TCI_CAMERASPACE_POSITION);
SetTexture(1, material.uReflection);
}
else if (material.uLightMap)
{
SetTextureColorOP(1, TBOP_MODULATE, TBS_CURRENT, TBS_TEXTURE);
SetTexCoordIndex(1,1);
SetTexture(1, material.uLightMap);
}
else if (material.uEmissive)
{
SetTextureColorOP(1, TBOP_ADD, TBS_CURRENT, TBS_TEXTURE);
SetTexture(1, material.uEmissive);
}
else if(!material.bBlend&&material.m_fOpacity>=1.0f)
{
SetTextureColorOP(0, TBOP_MODULATE, TBS_TEXTURE, TBS_DIFFUSE);
}
}
else
{
SetTextureFactor(cFactor);
if (material.uSpecular)
{
//SetTexture(0, material.uSpecular);
SetTextureColorOP(0, TBOP_SOURCE1, TBS_SPECULAR);
SetTexCoordIndex(0,0);
}
else if(material.uReflection)
{
cFactor.r=(unsigned char)(cFactor.r*fOpacity);
cFactor.g=(unsigned char)(cFactor.g*fOpacity);
cFactor.b=(unsigned char)(cFactor.b*fOpacity);
SetTextureFactor(cFactor);
if (material.bBlend)
{
SetBlendFunc(true, BLENDOP_ADD, SBF_DEST_COLOUR, SBF_ONE);
}
SetTextureColorOP(0, TBOP_MODULATE, TBS_TEXTURE, TBS_TFACTOR);
SetTextureAlphaOP(0, TBOP_DISABLE);
SetTexCoordIndex(0,TCI_CAMERASPACE_NORMAL|TCI_CAMERASPACE_POSITION);
SetTexture(0, material.uReflection);
}
else if (material.uLightMap)
{
if (material.bBlend)
{
SetBlendFunc(true, BLENDOP_ADD, SBF_DEST_COLOUR, SBF_ZERO);
}
SetTextureColorOP(0, TBOP_MODULATE, TBS_TEXTURE, TBS_TFACTOR);
SetTextureAlphaOP(0, TBOP_DISABLE);
SetTexture(0, material.uLightMap);
}
else if (material.uEmissive)
{
cFactor.r=(unsigned char)(cFactor.r*fOpacity);
cFactor.g=(unsigned char)(cFactor.g*fOpacity);
cFactor.b=(unsigned char)(cFactor.b*fOpacity);
SetTextureFactor(cFactor);
if (material.bBlend)
{
SetBlendFunc(true, BLENDOP_ADD, SBF_ONE, SBF_ONE);
}
SetTextureColorOP(0, TBOP_MODULATE, TBS_TEXTURE, TBS_TFACTOR);
SetTextureAlphaOP(0, TBOP_DISABLE);
SetTexture(0, material.uEmissive);
}
else if (material.uNormal)
{
CShader* pShader = GetShaderMgr().getSharedShader();
if (pShader)
{
static size_t s_uShaderID = GetShaderMgr().registerItem("EngineRes\\fx\\SpaceBump.fx");
pShader->setTexture("g_texNormal",material.uNormal);
SetShader(s_uShaderID);
}
//SetBlendFunc(true, BLENDOP_ADD, SBF_DEST_COLOUR, SBF_ZERO);
//SetTextureColorOP(0, TBOP_MODULATE, TBS_TEXTURE, TBS_TFACTOR);
//SetTextureAlphaOP(0, TBOP_DISABLE);
//SetTexture(0, uLightMap);
}
else
{
SetTextureColorOP(0,TBOP_SOURCE2);
if (material.bBlend)
{
SetTextureAlphaOP(0,TBOP_SOURCE2);
}
else
{
SetTextureAlphaOP(0,TBOP_DISABLE);
}
//return false;
}
}
}
else
{
CShader* pShader = GetShaderMgr().getSharedShader();
if (pShader)
{
pShader->setTexture("g_texDiffuse",material.uDiffuse);
pShader->setTexture("g_texLight",material.uLightMap);
pShader->setTexture("g_texNormal",material.uNormal);
//pShader->setTexture("g_texEnvironment",uEmissive);
//pShader->setTexture("g_texEmissive",uEmissive);
pShader->setTexture("g_texSpecular",material.uSpecular);
// for Terrain
pShader->setVec2D("g_fScaleUV",material.vUVScale);
}
SetShader(material.uShader);
}
return true;*/
}
void CRenderSystem::finishMaterial()
{
SetShader((CShader*)NULL);
SetTextureColorOP(1,TBOP_DISABLE);
SetTextureAlphaOP(1,TBOP_DISABLE);
SetTextureColorOP(2,TBOP_DISABLE);
SetTextureAlphaOP(2,TBOP_DISABLE);
setResultARGToTemp(0,false);
setResultARGToTemp(1,false);
setResultARGToTemp(2,false);
} | [
"rpgsky.com@97dd8ffa-095c-11df-8772-5d79768f539e"
]
| [
[
[
1,
311
]
]
]
|
91e5a846b78bb4da2599fb14e072d912c48858b5 | a2904986c09bd07e8c89359632e849534970c1be | /topcoder/CrossWord.cpp | e3cb5dda3951de1faec332271b2cbda322a61caa | []
| no_license | naturalself/topcoder_srms | 20bf84ac1fd959e9fbbf8b82a93113c858bf6134 | 7b42d11ac2cc1fe5933c5bc5bc97ee61b6ec55e5 | refs/heads/master | 2021-01-22T04:36:40.592620 | 2010-11-29T17:30:40 | 2010-11-29T17:30:40 | 444,669 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,167 | cpp | // BEGIN CUT HERE
// END CUT HERE
#line 5 "CrossWord.cpp"
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <map>
#include <utility>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include <functional>
#include <sstream>
#include <complex>
#include <stack>
#include <queue>
using namespace std;
#define debug(p) cout << #p << "=" << p << endl;
#define forv(i, v) for (int i = 0; i < (int)(v.size()); ++i)
#define fors(i, s) for (int i = 0; i < (int)(s.length()); ++i)
#define all(a) a.begin(), a.end()
#define pb push_back
class CrossWord {
public:
int countWords(vector <string> board, int size) {
}
};
// BEGIN CUT HERE
namespace moj_harness {
int run_test_case(int);
void run_test(int casenum = -1, bool quiet = false) {
if (casenum != -1) {
if (run_test_case(casenum) == -1 && !quiet) {
cerr << "Illegal input! Test case " << casenum << " does not exist." << endl;
}
return;
}
int correct = 0, total = 0;
for (int i=0;; ++i) {
int x = run_test_case(i);
if (x == -1) {
if (i >= 100) break;
continue;
}
correct += x;
++total;
}
if (total == 0) {
cerr << "No test cases run." << endl;
} else if (correct < total) {
cerr << "Some cases FAILED (passed " << correct << " of " << total << ")." << endl;
} else {
cerr << "All " << total << " tests passed!" << endl;
}
}
int verify_case(int casenum, const int &expected, const int &received, clock_t elapsed) {
cerr << "Example " << casenum << "... ";
string verdict;
vector<string> info;
char buf[100];
if (elapsed > CLOCKS_PER_SEC / 200) {
sprintf(buf, "time %.2fs", elapsed * (1.0/CLOCKS_PER_SEC));
info.push_back(buf);
}
if (expected == received) {
verdict = "PASSED";
} else {
verdict = "FAILED";
}
cerr << verdict;
if (!info.empty()) {
cerr << " (";
for (int i=0; i<(int)info.size(); ++i) {
if (i > 0) cerr << ", ";
cerr << info[i];
}
cerr << ")";
}
cerr << endl;
if (verdict == "FAILED") {
cerr << " Expected: " << expected << endl;
cerr << " Received: " << received << endl;
}
return verdict == "PASSED";
}
int run_test_case(int casenum) {
switch (casenum) {
case 0: {
string board[] = {"X....X",
"X.XX.X",
"...X..",
"X.XX.X",
"..X..."};
int size = 3;
int expected__ = 2;
clock_t start__ = clock();
int received__ = CrossWord().countWords(vector <string>(board, board + (sizeof board / sizeof board[0])), size);
return verify_case(casenum, expected__, received__, clock()-start__);
}
case 1: {
string board[] = {"...X...",
".X...X.",
"..X.X..",
"X..X..X",
"..X.X..",
".X...X.",
"...X..."};
int size = 3;
int expected__ = 6;
clock_t start__ = clock();
int received__ = CrossWord().countWords(vector <string>(board, board + (sizeof board / sizeof board[0])), size);
return verify_case(casenum, expected__, received__, clock()-start__);
}
case 2: {
string board[] = {".....X....X....",
".....X....X....",
"..........X....",
"....X....X.....",
"...X....X....XX",
"XXX...X....X...",
".....X....X....",
".......X.......",
"....X....X.....",
"...X....X...XXX",
"XX....X....X...",
".....X....X....",
"....X..........",
"....X....X.....",
"....X....X....."}
;
int size = 5;
int expected__ = 8;
clock_t start__ = clock();
int received__ = CrossWord().countWords(vector <string>(board, board + (sizeof board / sizeof board[0])), size);
return verify_case(casenum, expected__, received__, clock()-start__);
}
case 3: {
string board[] = {"...",
"...",
"..."};
int size = 50;
int expected__ = 0;
clock_t start__ = clock();
int received__ = CrossWord().countWords(vector <string>(board, board + (sizeof board / sizeof board[0])), size);
return verify_case(casenum, expected__, received__, clock()-start__);
}
case 4: {
string board[] = {"....",
"....",
"...."};
int size = 3;
int expected__ = 0;
clock_t start__ = clock();
int received__ = CrossWord().countWords(vector <string>(board, board + (sizeof board / sizeof board[0])), size);
return verify_case(casenum, expected__, received__, clock()-start__);
}
// custom cases
/* case 5: {
string board[] = ;
int size = ;
int expected__ = ;
clock_t start__ = clock();
int received__ = CrossWord().countWords(vector <string>(board, board + (sizeof board / sizeof board[0])), size);
return verify_case(casenum, expected__, received__, clock()-start__);
}*/
/* case 6: {
string board[] = ;
int size = ;
int expected__ = ;
clock_t start__ = clock();
int received__ = CrossWord().countWords(vector <string>(board, board + (sizeof board / sizeof board[0])), size);
return verify_case(casenum, expected__, received__, clock()-start__);
}*/
/* case 7: {
string board[] = ;
int size = ;
int expected__ = ;
clock_t start__ = clock();
int received__ = CrossWord().countWords(vector <string>(board, board + (sizeof board / sizeof board[0])), size);
return verify_case(casenum, expected__, received__, clock()-start__);
}*/
default:
return -1;
}
}
}
int main(int argc, char *argv[]) {
if (argc == 1) {
moj_harness::run_test();
} else {
for (int i=1; i<argc; ++i)
moj_harness::run_test(atoi(argv[i]));
}
}
// END CUT HERE
| [
"shin@CF-7AUJ41TT52JO.(none)"
]
| [
[
[
1,
229
]
]
]
|
43aa928e3799c2850acc361f69e2bf43728f3a33 | 46b3500c9ab98883091eb9d4ca49a6854451d76b | /ghost/gpsprotocol.cpp | e94e50683fdd3c80197d2bbc7936da716a853eae | [
"Apache-2.0"
]
| permissive | kr4uzi/pyghost | 7baa511fa05ddaba57880d2c7483694d5c5816b7 | 35e5bdd838cb21ad57b3c686349251eb277d2e6a | refs/heads/master | 2020-04-25T21:05:20.995556 | 2010-11-21T13:57:49 | 2010-11-21T13:57:49 | 42,011,079 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,127 | cpp | /*
Copyright 2010 Trevor Hogan
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "ghost.h"
#include "util.h"
#include "gpsprotocol.h"
//
// CGPSProtocol
//
CGPSProtocol :: CGPSProtocol( )
{
}
CGPSProtocol :: ~CGPSProtocol( )
{
}
///////////////////////
// RECEIVE FUNCTIONS //
///////////////////////
////////////////////
// SEND FUNCTIONS //
////////////////////
BYTEARRAY CGPSProtocol :: SEND_GPSC_INIT( uint32_t version )
{
BYTEARRAY packet;
packet.push_back( GPS_HEADER_CONSTANT );
packet.push_back( GPS_INIT );
packet.push_back( 0 );
packet.push_back( 0 );
UTIL_AppendByteArray( packet, version, false );
AssignLength( packet );
return packet;
}
BYTEARRAY CGPSProtocol :: SEND_GPSC_RECONNECT( unsigned char PID, uint32_t reconnectKey, uint32_t lastPacket )
{
BYTEARRAY packet;
packet.push_back( GPS_HEADER_CONSTANT );
packet.push_back( GPS_RECONNECT );
packet.push_back( 0 );
packet.push_back( 0 );
packet.push_back( PID );
UTIL_AppendByteArray( packet, reconnectKey, false );
UTIL_AppendByteArray( packet, lastPacket, false );
AssignLength( packet );
return packet;
}
BYTEARRAY CGPSProtocol :: SEND_GPSC_ACK( uint32_t lastPacket )
{
BYTEARRAY packet;
packet.push_back( GPS_HEADER_CONSTANT );
packet.push_back( GPS_ACK );
packet.push_back( 0 );
packet.push_back( 0 );
UTIL_AppendByteArray( packet, lastPacket, false );
AssignLength( packet );
return packet;
}
BYTEARRAY CGPSProtocol :: SEND_GPSS_INIT( uint16_t reconnectPort, unsigned char PID, uint32_t reconnectKey, unsigned char numEmptyActions )
{
BYTEARRAY packet;
packet.push_back( GPS_HEADER_CONSTANT );
packet.push_back( GPS_INIT );
packet.push_back( 0 );
packet.push_back( 0 );
UTIL_AppendByteArray( packet, reconnectPort, false );
packet.push_back( PID );
UTIL_AppendByteArray( packet, reconnectKey, false );
packet.push_back( numEmptyActions );
AssignLength( packet );
return packet;
}
BYTEARRAY CGPSProtocol :: SEND_GPSS_RECONNECT( uint32_t lastPacket )
{
BYTEARRAY packet;
packet.push_back( GPS_HEADER_CONSTANT );
packet.push_back( GPS_RECONNECT );
packet.push_back( 0 );
packet.push_back( 0 );
UTIL_AppendByteArray( packet, lastPacket, false );
AssignLength( packet );
return packet;
}
BYTEARRAY CGPSProtocol :: SEND_GPSS_ACK( uint32_t lastPacket )
{
BYTEARRAY packet;
packet.push_back( GPS_HEADER_CONSTANT );
packet.push_back( GPS_ACK );
packet.push_back( 0 );
packet.push_back( 0 );
UTIL_AppendByteArray( packet, lastPacket, false );
AssignLength( packet );
return packet;
}
BYTEARRAY CGPSProtocol :: SEND_GPSS_REJECT( uint32_t reason )
{
BYTEARRAY packet;
packet.push_back( GPS_HEADER_CONSTANT );
packet.push_back( GPS_REJECT );
packet.push_back( 0 );
packet.push_back( 0 );
UTIL_AppendByteArray( packet, reason, false );
AssignLength( packet );
return packet;
}
/////////////////////
// OTHER FUNCTIONS //
/////////////////////
bool CGPSProtocol :: AssignLength( BYTEARRAY &content )
{
// insert the actual length of the content array into bytes 3 and 4 (indices 2 and 3)
BYTEARRAY LengthBytes;
if( content.size( ) >= 4 && content.size( ) <= 65535 )
{
LengthBytes = UTIL_CreateByteArray( (uint16_t)content.size( ), false );
content[2] = LengthBytes[0];
content[3] = LengthBytes[1];
return true;
}
return false;
}
bool CGPSProtocol :: ValidateLength( BYTEARRAY &content )
{
// verify that bytes 3 and 4 (indices 2 and 3) of the content array describe the length
uint16_t Length;
BYTEARRAY LengthBytes;
if( content.size( ) >= 4 && content.size( ) <= 65535 )
{
LengthBytes.push_back( content[2] );
LengthBytes.push_back( content[3] );
Length = UTIL_ByteArrayToUInt16( LengthBytes, false );
if( Length == content.size( ) )
return true;
}
return false;
}
#include <boost/python.hpp>
void CGPSProtocol :: RegisterPythonClass( )
{
using namespace boost::python;
class_<CGPSProtocol>("GPSProtocol")
.def("SEND_GPSC_INIT", &CGPSProtocol::SEND_GPSC_INIT)
.def("SEND_GPSC_RECONNECT", &CGPSProtocol::SEND_GPSC_RECONNECT)
.def("SEND_GPSC_ACK", &CGPSProtocol::SEND_GPSC_ACK)
.def("SEND_GPSS_INIT", &CGPSProtocol::SEND_GPSS_INIT)
.def("SEND_GPSS_RECONNECT", &CGPSProtocol::SEND_GPSS_RECONNECT)
.def("SEND_GPSS_ACK", &CGPSProtocol::SEND_GPSS_ACK)
.def("SEND_GPSS_REJECT", &CGPSProtocol::SEND_GPSS_REJECT)
.def("assignLength", &CGPSProtocol::AssignLength)
.def("validateLength", &CGPSProtocol::ValidateLength)
;
}
| [
"kr4uzi@88aed30e-2b04-91ce-7a47-0ae997e79d63"
]
| [
[
[
1,
194
]
]
]
|
49989afbd12fbf36e5e23048154ac053b5bbdba7 | 9c2a6fd19d8d1fede218b99749fc48d5123b248a | /3rdParty/Htmlayout/api/htmlayout_queue.h | 9e9584475e5e021229ef079d99ce93a6315de140 | []
| no_license | ans-ashkan/expemerent | 0f6bed7e630301f63e71992e3fbad70a0075082a | 054c33f55408d1274c50a2d6eb4cbc5295c92739 | refs/heads/master | 2021-01-15T22:15:18.929759 | 2008-12-21T00:40:52 | 2008-12-21T00:40:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,852 | h | #ifndef __HTMLAYOUT_QUEUE_H__
#define __HTMLAYOUT_QUEUE_H__
/*
* Terra Informatica Lightweight Embeddable HTMLayout control
* http://terrainformatica.com/htmlayout
*
* Asynchronous GUI Task Queue.
* Use these primitives when you need to run code in GUI thread.
*
* The code and information provided "as-is" without
* warranty of any kind, either expressed or implied.
*
*
* (C) 2003-2006, Andrew Fedoniouk ([email protected])
*/
/*!\file
\brief Asynchronous GUI Task Queue
*/
#include <windows.h>
#include <stdio.h>
#include <assert.h>
#if defined(__cplusplus) && !defined( PLAIN_API_ONLY )
namespace htmlayout
{
class mutex
{
CRITICAL_SECTION cs;
public:
void lock() { EnterCriticalSection(&cs); }
void unlock() { LeaveCriticalSection(&cs); }
mutex() { InitializeCriticalSection(&cs); }
~mutex() { DeleteCriticalSection(&cs); }
};
class critical_section {
mutex& m;
public:
critical_section(mutex& guard) : m(guard) { m.lock(); }
~critical_section() { m.unlock(); }
};
// derive your own tasks from this and implement your own exec()
class gui_task
{
friend class queue;
gui_task* next;
public:
gui_task(): next(0) {}
virtual ~gui_task() {}
virtual void exec() = 0; // override it
};
// this one needs to be created as singleton - one instance per GUI thread(s)
class queue
{
gui_task* head;
gui_task* tail;
mutex guard;
public:
queue():head(0),tail(0) {}
void push( gui_task* new_task )
{
assert(new_task);
{
critical_section cs(guard);
if( tail )
tail->next = new_task;
else
head = new_task;
tail = new_task;
}
PostMessage(NULL, WM_NULL, 0,0);
}
// Place this call after GetMessage()/PeekMessage() in main loop
void execute()
{
gui_task* next;
while(next = pop())
{
next->exec(); // do it
delete next;
}
}
void clear()
{
gui_task* next;
while(next = pop())
delete next;
}
bool is_empty() const
{
return head == 0;
}
private:
gui_task* pop()
{
critical_section cs(guard);
if( !head ) return 0;
gui_task* t = head;
head = head->next;
if( !head ) tail = 0;
return t;
}
};
}
// for one GUI thread per application cases:
extern htmlayout::queue gui_queue;
/*
gui_queue shall be instantiated somewhere in the main file of your application and
gui_queue.execute() call shall be made in message pump loop as:
// Main message loop:
while (GetMessageW(&msg, NULL, 0, 0))
{
// execute asynchronous tasks in GUI thread.
gui_queue.execute(); // <-- here
if (!TranslateAcceleratorW(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
}
*/
/* Example of asynchronous operation wrapper:
struct append_and_update: public gui_task
{
dom::element what;
dom::element where;
append_and_update( const dom::element& to, const dom::element& el ): where(to), what(el) {}
// will be executed in GUI thread
virtual void exec() { where.append(what); where.update(true); }
};
when you need this oparation simply do:
void SomeThreadProc()
{
...
gui_queue.push( new append_and_update( parent, child ) );
}
so next queue::execute() invocation will execute that append_and_update::exec().
*/
#endif // __cplusplus
#endif // __HTMLAYOUT_QUEUE_H__
| [
"userstvo@9d5f44c3-c14b-0410-8269-bdf5c58671da"
]
| [
[
[
1,
171
]
]
]
|
617f1fa29ab46e50434a9717a6b3ab9e9f9efead | ec9b2f87250fa37846440f4fcbc00346d8bf4d0c | /QDialogConvolutionFFT.cpp | ef441b70464b1bbdb12b8f4caaebfac846809a2f | []
| no_license | linan7788626/ESTL-OX | 7056e03e5181a3806608b042bcba42b7acb4dc4a | 73ddeaaa809fdf1604c3b8e580615e94f7665b50 | refs/heads/master | 2021-01-16T00:03:46.287232 | 2011-11-24T13:24:09 | 2011-11-24T13:24:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,197 | cpp | /*
* The information in this file is
* subject to the terms and conditions of the
* GNU Lesser General Public License Version 2.1
* The license text is available from
* http://www.gnu.org/licenses/lgpl.html
*/
#include "QDialogConvolutionFFT.h"
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QCloseEvent>
#include <QtGui/QLayout>
#include <QtGui/QListWidget>
#include <QtGui/QMessageBox>
#include <QtGui/QPushButton>
#include <QtGui/QSpinBox>
#include <QtGui/QSplitter>
#include <QtGui/QTreeWidget>
#include "AoiElement.h"
#include "AoiLayer.h"
#include "AppVerify.h"
#include "DataAccessor.h"
#include "DataAccessorImpl.h"
#include "DataRequest.h"
#include "DockWindow.h"
#include "Executable.h"
#include "GcpList.h"
#include "GcpLayer.h"
//#include "GeoAlgorithms.h"
#include "GraphicLayer.h"
#include "GraphicObject.h"
#include "LatLonLayer.h"
#include "LayerList.h"
//#include "MouseMode.h"
#include "PlugIn.h"
#include "PlugInArg.h"
#include "PlugInArgList.h"
#include "PlugInResource.h"
#include "ProgressTracker.h"
#include "RasterLayer.h"
#include "RasterElement.h"
#include "RasterDataDescriptor.h"
#include "Slot.h"
#include "SpatialDataView.h"
#include "SpatialDataWindow.h"
#include "switchOnEncoding.h"
#include "TypesFile.h"
#include "Undo.h"
#include "UtilityServices.h"
#include "WorkspaceWindow.h"
#include <list>
#include <string>
#include "../ESTL/Convolution.h"
using namespace std;
FFTConvolutionDlg::FFTConvolutionDlg(PlugIn* pPlugIn, ProgressTracker& progressTracker, QWidget* pParent) :
QDialog(pParent), mpDescriptionLabel(NULL), mpPlugIn(pPlugIn), mProgressTracker(progressTracker), pView(NULL) {
setWindowTitle("FFT-based Convolution");
setModal(false);
mpDescriptionLabel = new QLabel(this);
mpDescriptionLabel->setText("Select Data to Convolve and Convolution Kernel");
QFrame* pDescriptionLine = new QFrame(this);
pDescriptionLine->setFrameStyle(QFrame::HLine | QFrame::Sunken);
QFrame* pButtonLine = new QFrame(this);
pButtonLine->setFrameStyle(QFrame::HLine | QFrame::Sunken);
mpOKButton = new QPushButton("&OK", this);
QPushButton* pCancelButton = new QPushButton("&Cancel", this);
pCancelButton->setDefault(true);
QHBoxLayout* pButtonLayout = new QHBoxLayout();
pButtonLayout->setMargin(0);
pButtonLayout->setSpacing(5);
pButtonLayout->addStretch();
pButtonLayout->addWidget(mpOKButton);
pButtonLayout->addWidget(pCancelButton);
QVBoxLayout* pLayout = new QVBoxLayout(this);
pLayout->setMargin(10);
pLayout->setSpacing(10);
pLayout->addWidget(mpDescriptionLabel);
pLayout->addWidget(pDescriptionLine);
pLayout->addWidget(widgetInputSelection = new WidgetInputSelection(this), 10);
pLayout->addWidget(pButtonLine);
pLayout->addLayout(pButtonLayout);
resize(minimumSizeHint()); // required so the dialog shows up the correct size
// connections
VERIFYNR(connect(mpOKButton, SIGNAL(clicked()), this, SLOT(accept())));
VERIFYNR(connect(pCancelButton, SIGNAL(clicked()), this, SLOT(reject())));
}
FFTConvolutionDlg::~FFTConvolutionDlg() { mProgressTracker.report("Convolution transformation complete", 100, NORMAL, true); }
void FFTConvolutionDlg::windowDeleted(Subject& subject, const string& signal, const boost::any& v) { }
void FFTConvolutionDlg::accept() { convolve(); done(QDialog::Accepted); }
void FFTConvolutionDlg::reject() { done(QDialog::Rejected); }
class Image {
private:
public:
SpatialDataView* pView;
RasterElement* pRaster;
const RasterDataDescriptor* pDataDescriptor;
Image(SpatialDataView* iPView) : pView(iPView) {
LayerList* pLayerList = pView->getLayerList(); VERIFYNRV(pLayerList != NULL);
pRaster = dynamic_cast<RasterElement*>(pLayerList->getPrimaryRasterElement()); VERIFYNRV(pRaster != NULL);
pDataDescriptor = dynamic_cast<const RasterDataDescriptor*>(pRaster->getDataDescriptor()); VERIFYNR(pDataDescriptor != NULL);
/* Service<DesktopServices> pDesktop;
VERIFYNRV(pDesktop.get() != NULL);
SpatialDataWindow* pWindow = dynamic_cast<SpatialDataWindow*>(pDesktop->getWindow(pRaster->getName(), SPATIAL_DATA_WINDOW));
VERIFYNRV(pWindow != NULL);
VERIFYNRV(pDesktop->setCurrentWorkspaceWindow(pWindow));*/
}
Image(RasterElement* iPRaster) : pView(NULL), pRaster(iPRaster) {
pDataDescriptor = dynamic_cast<const RasterDataDescriptor*>(pRaster->getDataDescriptor()); VERIFYNR(pDataDescriptor != NULL);
/* SpatialDataWindow* pPrimaryWindow = dynamic_cast<SpatialDataWindow*>(pDesktop->getWindow(pPrimaryRaster->getName(), SPATIAL_DATA_WINDOW));
VERIFYNRV(pPrimaryWindow != NULL);
VERIFYNRV(pDesktop->setCurrentWorkspaceWindow(pPrimaryWindow));*/
}
int getRowCount() { return pDataDescriptor->getRowCount(); }
int getColumnCount() { return pDataDescriptor->getColumnCount(); }
int getBandCount() { return pDataDescriptor->getBands().size(); }
std::string getName() { return pRaster->getName(); }
DataAccessor getAccessor(int band, bool writable = false) {
FactoryResource<DataRequest> pRequest = FactoryResource<DataRequest>();
pRequest->setRows(pDataDescriptor->getActiveRow(0), pDataDescriptor->getActiveRow(getRowCount() - 1));
pRequest->setColumns(pDataDescriptor->getActiveColumn(0), pDataDescriptor->getActiveColumn(getColumnCount() - 1));
pRequest->setBands(pDataDescriptor->getActiveBand(band), pDataDescriptor->getActiveBand(band));
pRequest->setWritable(writable);
return pRaster->getDataAccessor(pRequest.release());
}
};
template <class T> class Opticks2DData : public Data2D<T> {
private:
Image* image;
public:
DataAccessor dataAccessor;
Opticks2DData(Image* iImage, int band, bool writable = false) : image(iImage), dataAccessor(DataAccessor(image->getAccessor(band, writable)))
{ if (!dataAccessor.isValid()) { qDebug("Failed to create data accessor"); /* throw exception */ } }
int getWidth() { return image->getColumnCount(); }
int getHeight() { return image->getRowCount(); }
void toPixel(int x, int y) {
dataAccessor->toPixel(y, x);
if (!dataAccessor.isValid()) { qDebug("DataAccessor invalid after toPixel"); /* throw exception */ }
}
T getPixel(int x, int y) {
toPixel(x, y);
return *((T*) dataAccessor->getColumn());
}
void setPixel(int x, int y, T value) {
toPixel(x, y); //qDebug("((%i, %i, %i))", x, y, (int) value);
*((T*) dataAccessor->getColumn()) = value;//value;//value;
}
};
namespace {
template<typename T> void assignResult(T* pPixel, double value) { *pPixel = static_cast<T>(value); }
}
void FFTConvolutionDlg::convolve() {
Service<ModelServices> pModel; VERIFYNRV(pModel.get() != NULL);
Service<DesktopServices> pDesktop; VERIFYNRV(pDesktop.get() != NULL);
Service<UtilityServices> pUtils; VERIFYNRV(pUtils.get() != NULL);
mProgressTracker.report("Retrieving image to convolve", 1, NORMAL, true);
Image imgToConvolve(widgetInputSelection->getImageToConvolveView());
if (imgToConvolve.pView == NULL) { mProgressTracker.report("Error: Primary data set does not exist. Go back to the Dataset Select Page and select a new Primary Dataset.", 0, ERRORS); return; }
mProgressTracker.report("Retrieving convolution kernel", 2, NORMAL, true);
Image imgConvolutionKernel(widgetInputSelection->getConvolutionKernelView());
if (imgConvolutionKernel.pView == NULL) { mProgressTracker.report("Error: Secondary data set does not exist. Go back to the Dataset Select Page and select a new Secondary Dataset.", 0, ERRORS); return; }
// Convolved Image Result
mProgressTracker.report("Initializing output", 3, NORMAL, true);
EncodingType resultType = imgToConvolve.pDataDescriptor->getDataType();
mProgressTracker.report((string("Result type ") + intToStr(resultType)).c_str(), 4, NORMAL, true);
qDebug("resultType = %i", (int) resultType);
/*if (resultType == INT4SCOMPLEX) { resultType = INT4SBYTES; }
else if (resultType == FLT8COMPLEX) { resultType = FLT8BYTES; }*/
qDebug("resultType = %i", (int) resultType);
// INT1SBYTE = 0, /**< char */
// 00208 INT1UBYTE = 1, /**< unsigned char */
// 00209 INT2SBYTES = 2, /**< short */
// 00210 INT2UBYTES = 3, /**< unsigned short */
// 00211 INT4SCOMPLEX = 4, /**< complex short */
// 00212 INT4SBYTES = 5, /**< int */
// 00213 INT4UBYTES = 6, /**< unsigned int */
// 00214 FLT4BYTES = 7, /**< float */
// 00215 FLT8COMPLEX = 8, /**< complex float */
// 00216 FLT8BYTES = 9 /**< double */
std::string resultName = imgToConvolve.getName() + " conv " + imgConvolutionKernel.getName();
ModelResource<RasterElement> pResult(RasterUtilities::createRasterElement(resultName,
imgToConvolve.getRowCount(), imgToConvolve.getColumnCount(), imgToConvolve.getBandCount(),
resultType, imgToConvolve.pDataDescriptor->getInterleaveFormat(),
imgToConvolve.pDataDescriptor->getProcessingLocation() == IN_MEMORY));
pResult->copyClassification(imgToConvolve.pRaster);
pResult->getMetadata()->merge(imgToConvolve.pDataDescriptor->getMetadata()); //copy original metadata
Image imgResult = Image(pResult.get());
resultRasterElement = imgResult.pRaster;
if (imgResult.pRaster == NULL) { mProgressTracker.report("Unable to create result data set.", 0, ERRORS, true); return; }
if (Service<ApplicationServices>()->isBatch()) { return; }
SpatialDataWindow* pWindow = static_cast<SpatialDataWindow*>(Service<DesktopServices>()->createWindow(resultRasterElement->getName(), SPATIAL_DATA_WINDOW));
pView = (pWindow == NULL) ? NULL : pWindow->getSpatialDataView();
// pView = (pWindow == NULL) ? NULL : pWindow->getSpatialDataView();
if (pView == NULL) {
Service<DesktopServices>()->deleteWindow(pWindow);
mProgressTracker.report("Unable to create view.", 0, ERRORS, true); return;
}
if (!pView->setPrimaryRasterElement(resultRasterElement)) qDebug("Failed to attach raster element");
RasterLayer* pLayer = NULL; { UndoLock lock(pView); pLayer = static_cast<RasterLayer*>(pView->createLayer(RASTER, resultRasterElement)); }
if (pLayer == NULL) {
#pragma message(__FILE__ "(" STRING(__LINE__) ") : warning : This would be cleaner with a WindowResource. If one becomes available, use it instead. (tclarke)")
Service<DesktopServices>()->deleteWindow(pWindow);
mProgressTracker.report("Unable to create layer.", 0, ERRORS, true);
return;
}
// Perform Convolution
mProgressTracker.report("Performing convolution", 5, NORMAL, true);
unsigned int bandCount = imgToConvolve.pDataDescriptor->getBands().size();
// qDebug("bandCount = %i", bandCount);
// qDebug("%i -- %i:%i:%i", (int) imgResult.pDataDescriptor->getDataType(), imgResult.getRowCount(), imgResult.getColumnCount(), imgResult.getBandCount());
typedef unsigned char T;
// ProgressTracker ptBands = ProgressTracker(;
for (unsigned int bandNum = 0; bandNum < bandCount; ++bandNum) {
mProgressTracker.report("Processing band", 5 + (99 - 5)*(bandNum/(double) bandCount), NORMAL, true);
Opticks2DData<T> dataToConvolve(&imgToConvolve, bandNum);
Opticks2DData<T> convolutionKernel(&imgConvolutionKernel, bandNum);
Opticks2DData<T> result(&imgResult, bandNum, true);
Convolution2D_FFT<T> convolution(&dataToConvolve, &convolutionKernel, &result);
convolution.convolve();
}
mProgressTracker.report("Convolution complete", 99, NORMAL, true);
pResult->updateData();
pResult.release();
}
SpatialDataView* FFTConvolutionDlg::displayResult() { return pView; }
| [
"[email protected]"
]
| [
[
[
1,
269
]
]
]
|
86554bbcf728db3fd466d7d0b3e9a8383bf7bade | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/zombie/npythonserver/src/python/npythonobject.cc | 1a4f4edda2ead3686f2e43e6838b8f4fd63f08f4 | []
| 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 | 34,401 | cc | #include "precompiled/pchnpythonserver.h"
#define N_IMPLEMENTS nPythonServer
//-----------------------------------------------------------------------------
// npythonobject.cc -- implements Python/Nebula Objects
// Created by Andy Miller, 2002
// Based upon work by Jason Asbahr
// Updates by Tivonenko Ivan (aka Dark Dragon), 2003
//
// Note that the 'delete' function deletes a Nebula object AND DOESN'T
// delete any python objects that happen to be pointing to it - the reverse
// is true for "deleting" a python object (happens automatically most of
// the time) UNLESS you call the "_SetAutoDel_" function on the python object
// before it is deleted, in which case the Nebula object will be deleted
// along with the Python one..
//
//-----------------------------------------------------------------------------
#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>
#include "python/npythonserver.h"
#include "kernel/nkernelserver.h"
#include "python/npythonobject.h"
#include "kernel/nroot.h"
#include "kernel/ndebug.h" // gives us n_assert, n_error and n_printf
#include "signals/nsignalserver.h"
#ifdef __cplusplus
extern "C" {
#endif
extern PyObject *CreatedObjectsList_;
PyObject* _putOutArgs(nCmd *cmd);
bool _getInArgs(nCmd *cmd, PyObject *args);
PyObject *Npy_ErrorObject;
//-----------------------------------------------------------------------------
/**
@brief Create a new type of nebula object - that works like obj.func(..)
*/
NebulaObject*
NebulaObject_New(nObject * nebulaObj)
{
NebulaObject *self;
PyObject *cObject;
// now lookup if we created this object previously...
if ( 0 != (self = CreatedObjectsList_GetObject(nebulaObj)))
{
return self;
}
// nope, we didn't...
self = PyObject_New(NebulaObject, &Nebula_Type); //new reference
if (NULL == self)
{
return NULL;
}
self->internal_dict = NULL;
self->in_weakreflist = NULL;
self->nebula_object = n_new(nRef<nObject>);
n_assert(self->nebula_object);
//self->nebula_object->initialize(NULL);
self->nebula_object->SetPtr(NULL);
self->nebula_object->set(nebulaObj);
cObject = PyCObject_FromVoidPtr((void *) nebulaObj, NULL);
NebulaObject_SetAttr(self, "__nebobject__", cObject);
Py_XDECREF(cObject);
// and now save this object for later lookup
CreatedObjectsList_AddObject(self, nebulaObj);
return self;
}
//-----------------------------------------------------------------------------
/**
@brief Retrieve a path to the Nebula object from within the Python object.
*/
const char *
NebulaObject_GetPath(NebulaObject * self)
{
n_assert(NULL != self);
if (self->internal_dict != NULL)
{
PyObject * path = PyDict_GetItemString(self->internal_dict,
"__nebobject_path__");
if (path != NULL && PyString_Check(path))
{
return PyString_AS_STRING(path);
}
else
{
n_printf("__nebobject_path__ didn't return a valid path\n");
}
}
else
{
n_printf("internal dictionary is NULL\n");
}
return NULL;
}
//-----------------------------------------------------------------------------
/**
@brief Retrieve a pointer to the Nebula object from within the Python
Object.
*/
nObject *
NebulaObject_GetPointer(NebulaObject * self)
{
n_assert(NULL != self);
if (!self->nebula_object->isvalid())
{
PyErr_SetString(PyExc_Exception, "Invalid pointer no nebula object!\n");
return NULL;
}
n_assert(self->nebula_object->isvalid());
return self->nebula_object->get();
}
//-----------------------------------------------------------------------------
/**
@brief Delete the real Nebula object pointed to by the python object
*/
PyObject *
NebulaObject_Delete(NebulaObject* self, PyObject* /*args*/)
{
PyObject * result = NULL;
n_assert(NULL != self);
nObject * o = NebulaObject_GetPointer(self);
if (o)
{
o->Release();
// delete the object from the dict now !!
PyDict_DelItemString(self->internal_dict, "__nebobject__");
Py_INCREF(Py_None);
result = Py_None;
}
else
{
n_printf("NebulaObject_GetPointer returned NULL\n");
}
return result;
}
//-----------------------------------------------------------------------------
/**
@brief Called when the python object goes out of existance.
*/
void
NebulaObject_Dealloc(NebulaObject *self)
{
n_assert(NULL!=self);
if (self->in_weakreflist != NULL)
{
PyObject_ClearWeakRefs((PyObject *) self);
}
// check for the existance of "deletenebula" in the dictionary
if (self->internal_dict != NULL)
{
PyObject *v = PyDict_GetItemString(self->internal_dict,
"__deletenebula__");
if (v != NULL)
{
NebulaObject_Delete(self, NULL);
}
Py_XDECREF(self->internal_dict);
}
else
{
n_printf("Internal Dictionary is NULL\n");
}
if (self->nebula_object)
{
n_delete(self->nebula_object);
}
PyObject_Del(self);
}
//-----------------------------------------------------------------------------
/**
@brief Call this function to flag the python object to delete the
nebula object as well.
*/
PyObject *
NebulaObject_SetAutoDel(NebulaObject *self, PyObject * /*args*/)
{
PyObject * result = NULL;
n_assert(NULL!=self);
// Set an entry in the dictionary as a flag to delete the Nebula object
// when the python object goes out of scope (gets deleted)
if (self->internal_dict != NULL)
{
PyObject *obj = PyInt_FromLong(1l); // this could be anything
NebulaObject_SetAttr(self, "__deletenebula__", obj);
Py_XDECREF(obj);
Py_INCREF(Py_None);
result = Py_None;
}
else
{
n_printf("Internal Dictionary is NULL\n");
}
return result;
}
//-----------------------------------------------------------------------------
/**
@brief Emit a signal from the emitter object
*/
PyObject *
NebulaObject_Emit(NebulaObject *self, PyObject * args)
{
PyObject * result = NULL;
n_assert(NULL!=self);
char * usageMsg = "Usage: object.emit(signalname,arg1,arg2,...)";
// check args python object is a tuple
if (0 == PyTuple_Check(args))
{
n_message(usageMsg);
return result;
}
// get the emitter object
nObject * o = NebulaObject_GetPointer((NebulaObject*)self);
if (0 == o)
{
PyErr_SetString(PyExc_Exception, "Emitter object not valid");
return result;
}
// get the class of the object
nClass * objClass = o->GetClass();
n_assert(objClass);
// get first item of the tuple (the signal name / fourcc)
PyObject * arg0 = PyTuple_GET_ITEM(args, 0);
n_assert(arg0);
nSignal * signal = 0;
if (PyString_Check(arg0))
{
char * signalName = PyString_AsString(arg0);
signal = objClass->FindSignalByName(signalName);
if (0 == signal && strlen(signalName) == 4)
{
nFourCC fourcc = MAKE_FOURCC(signalName[0], signalName[1], signalName[2], signalName[3]);
signal = objClass->FindSignalById(fourcc);
}
}
if (0 == signal)
{
PyErr_SetString(PyExc_Exception, "Signal name not valid");
return result;
}
// get new nCmd for the signal information
nCmd *cmd = signal->NewCmd();
n_assert(cmd);
// Create a new tuple that has just the arguments needed for the command
PyObject * commandArgs = PyTuple_GetSlice(args, 1, PyTuple_Size(args));
// Pass Cmd object and the remaining tuple arguments to _getInArgs.
// Retrieve input args (skip the 'unknown' and cmd statement)
if (!_getInArgs(cmd, commandArgs))
{
if (o->IsA("nroot"))
{
PyErr_Format(PyExc_Exception,
"Broken input args, object '%s' of class '%s', signal '%s'",
((nRoot *)o)->GetName(),
o->GetClass()->GetName(),
signal->GetName());
}
else
{
PyErr_Format(PyExc_Exception,
"Broken input args, object of class '%s', signal '%s'",
o->GetClass()->GetName(), signal->GetName());
}
result = NULL;
}
else if (o->Dispatch(cmd))
{
// let object handle the command
result = _putOutArgs(cmd);
// either returns a single PyObject of the appropriate
// return type OR a tuple containing results
// a null return is done as a null Tuple..
}
else
{
if (o->IsA("nroot"))
{
PyErr_Format(PyExc_Exception,
"Dispatch error, object '%s' of class '%s', signal '%s'",
((nRoot *)o)->GetName(),
o->GetClass()->GetName(),
signal->GetName());
}
else
{
PyErr_Format(PyExc_Exception,
"Dispatch error, object of class '%s', signal '%s'",
o->GetClass()->GetName(), signal->GetName());
}
result = NULL;
}
// In any case, cleanup the cmd object
signal->RelCmd(cmd);
// Clean up
Py_XDECREF(commandArgs);
return result;
}
//-----------------------------------------------------------------------------
/**
@brief Post a signal/command from the emitter object
*/
PyObject *
NebulaObject_Post(NebulaObject *self, PyObject * args)
{
PyObject * result = NULL;
n_assert(NULL!=self);
char * usageMsg = "Usage: object.post(reltime,cmdSignalName,arg1,arg2,...)";
// check args python object is a tuple
if (0 == PyTuple_Check(args))
{
n_message(usageMsg);
return result;
}
// get the emitter object
nObject * o = NebulaObject_GetPointer((NebulaObject*)self);
if (0 == o)
{
PyErr_SetString(PyExc_Exception, "Object not valid");
return result;
}
// get the class of the object
nClass * objClass = o->GetClass();
n_assert(objClass);
// get fist item of the tuple (the relative time)
nTime relT = 0;
PyObject * arg0 = PyTuple_GET_ITEM(args, 0);
n_assert(arg0);
if (PyFloat_Check(arg0))
{
relT = PyFloat_AsDouble(arg0);
}
else if (PyInt_Check(arg0))
{
relT = (double) PyInt_AsLong(arg0);
}
else
{
PyErr_SetString(PyExc_Exception, "Relative time not valid");
return result;
}
// get second item of the tuple (the signal name / fourcc)
PyObject * arg1 = PyTuple_GET_ITEM(args, 1);
n_assert(arg1);
nCmdProto * cmdsig = 0;
if (PyString_Check(arg1))
{
char * cmdSignalName = PyString_AsString(arg1);
cmdsig = objClass->FindSignalByName(cmdSignalName);
if (0 == cmdsig && strlen(cmdSignalName) == 4)
{
nFourCC fourcc = MAKE_FOURCC(cmdSignalName[0], cmdSignalName[1], cmdSignalName[2], cmdSignalName[3]);
cmdsig = objClass->FindSignalById(fourcc);
}
if (0 == cmdsig)
{
cmdsig = objClass->FindCmdByName(cmdSignalName);
}
}
if (0 == cmdsig)
{
PyErr_SetString(PyExc_Exception, "Signal/Command name not valid");
return result;
}
// get new nCmd for the signal/command
nCmd *cmd = cmdsig->NewCmd();
n_assert(cmd);
// Create a new tuple that has just the arguments needed for the command
PyObject * commandArgs = PyTuple_GetSlice(args, 2, PyTuple_Size(args));
// Pass Cmd object and the remaining tuple arguments to _getInArgs.
// Retrieve input args (skip the 'unknown' and cmd statement)
if (!_getInArgs(cmd, commandArgs))
{
if (o->IsA("nroot"))
{
PyErr_Format(PyExc_Exception,
"Broken input args, object '%s' of class '%s', signal/command '%s'",
((nRoot *)o)->GetName(),
o->GetClass()->GetName(),
cmdsig->GetName());
}
else
{
PyErr_Format(PyExc_Exception,
"Broken input args, object of class '%s', signal/command '%s'",
o->GetClass()->GetName(), cmdsig->GetName());
}
result = NULL;
}
else
{
// let object handle the command
nSignalServer * signalServer = nSignalServer::Instance();
if (0 == signalServer)
{
PyErr_Format(PyExc_Exception,"Signal server not available");
result = NULL;
}
else if (signalServer->PostCmd(relT, o, cmd))
{
Py_INCREF(Py_None);
result = Py_None;
}
else
{
PyErr_Format(PyExc_Exception,"Signal server post failed");
result = NULL;
}
}
if (result == NULL)
{
cmdsig->RelCmd(cmd);
}
// Clean up
Py_XDECREF(commandArgs);
return result;
}
// only one method defined...
PyMethodDef Nebula_methods[] = {
{"_SetAutoDel_", (PyCFunction)NebulaObject_SetAutoDel, METH_VARARGS, NULL},
{"emit", (PyCFunction)NebulaObject_Emit, METH_VARARGS, NULL},
{"post", (PyCFunction)NebulaObject_Post, METH_VARARGS, NULL},
{NULL, NULL, 0, NULL} /* sentinel */
};
//-----------------------------------------------------------------------------
/**
@brief Handle a call to the object.
If functionname =! NULL then we know we are really inside an OPCODE loop
in the interpreter and need to call into Nebula. Makes the object
stateful for one internal interpreter cycle.
*/
PyObject*
NebulaObject_Call(NebulaObject *self,
PyObject *args,
PyObject * /*kw*/)
{
PyObject * result;
n_assert(NULL != self);
// This should have been set previously by getattro call:
if (self->functionname != NULL)
{
int res;
res = NebulaObject_CallPObjectFunction(self,
PyString_AsString(self->functionname),
args, &result);
if (res == 0)
{
Py_XDECREF(self->functionname);
self->functionname = NULL;
return result;
}
else
{
n_printf("CallPObjectFunction failed in Nebula_Call");
}
Py_DECREF(self->functionname);
self->functionname = NULL;
}
else
{
n_error("functionname is NULL (should have been set previously)\n");
}
return NULL;
}
//-----------------------------------------------------------------------------
/**
@brief Trap the function call request (or an attribute call for
that matter).
Set the internal functionname so we know what function is really
wanted and return a pointer to ourselves.
When executing object.function(..) the Python interpreter first
does a GETATTR call (handled by the objects tp_getattro func) on
the object using the 'function' as it's key - in the case of a
function call it expects that the return from the GETATTR is a
callable object which the interpreter then calls on it's next
OPCODE (handled by the tp_call func) - hence we need to store
the function name in the object and pass a pointer back.
*/
PyObject*
NebulaObject_GetAttrO(NebulaObject *self, PyObject *name)
{
// first find the generic attributes and methods of python object
PyObject * result = PyObject_GenericGetAttr( (PyObject*)self, name );
if( result )
{
return result;
}
// clear the error because we'll continue searching in nebula
PyErr_Clear();
n_assert(NULL != self);
n_assert(NULL != name);
self->functionname = name;
Py_INCREF(self); // needed as we are using ourselves for the function call
Py_INCREF(self->functionname); // need to do this one..
return (PyObject *)self;
}
//-----------------------------------------------------------------------------
/**
@brief Call the actual Nebula function.
*/
int
NebulaObject_CallNebulaFunction(nObject* o, char * name,
PyObject * commandArgs,
PyObject **returndata)
{
int result = 0;
if (o)
{
nClass *cl = o->GetClass();
if (!cl)
{
// Unable to acquire current object
// Set appropriate exception
PyErr_SetString(Npy_ErrorObject,
"Unable to get a pointer to the Nebula object - probably Nebula object is deleted");
result = -1;
return result;
}
nCmdProto *cmdProto = (nCmdProto *) cl->FindCmdByName(name);
if (cmdProto)
{
// Invoke the command
nCmd *cmd = cmdProto->NewCmd();
n_assert(cmd);
// Create a new tuple that has just the arguments needed for the command
// Passes Cmd object and the remaining tuple arguments to _getInArgs.
// retrieve input args (skip the 'unknown' and cmd statement)
if (!_getInArgs(cmd, commandArgs))
{
if (o->IsA("nroot"))
{
PyErr_Format(PyExc_Exception,
"Broken input args, object '%s', command '%s'",
((nRoot *) o)->GetName(), name);
}
else
{
PyErr_Format(PyExc_Exception,
"Broken input args, object 0x%x, command '%s'",
o, name);
}
result = -1;
}
else if (o->Dispatch(cmd))
{
// let object handle the command
if (returndata)
{ // the caller wants return data
*returndata = _putOutArgs(cmd); // get the return data
}
result = 0; // set successful return
}
else
{
if (o->IsA("nroot"))
{
PyErr_Format(PyExc_Exception,
"Dispatch error, object '%s', command '%s'",
((nRoot *) o)->GetName(), name);
}
else
{
PyErr_Format(PyExc_Exception,
"Dispatch error, object 0x%x, command '%s'",
o, name);
}
result = -1;
}
// In any case, cleanup the cmd object
cmdProto->RelCmd(cmd);
}
else
{
// Set exception, the object doesn't know about the command!
if (o->IsA("nroot"))
{
PyErr_Format(PyExc_AttributeError,
"Unknown command, object '%s', command '%s'",
((nRoot *) o)->GetName(), name);
}
else
{
PyErr_Format(PyExc_AttributeError,
"Unknown command, object '%s', command '%s'",
o, name);
}
result = -1;
}
}
else
{
// Unable to acquire current object
// Set appropriate exception
PyErr_SetString(Npy_ErrorObject,
"Unable to get a pointer to the Nebula object - probably Nebula object is deleted");
result = -1;
}
return result;
}
//-----------------------------------------------------------------------------
/**
@brief The main function to make a 'function' call on an object - used
by 'Set', etc.
*/
int
NebulaObject_CallPObjectFunction(NebulaObject *self, char *name,
PyObject * args,
PyObject ** returndata)
{
n_assert(NULL != self);
n_assert(NULL != name);
PyObject * commandArgs;
int result = -1;
/* First lets go through and check if the 'function' is really an
attribute or internal method */
// first we look for the attribute in the internal dictionary
if (self->internal_dict != NULL)
{
// If we've already saved this somewhere along the way...
PyObject *v = PyDict_GetItemString(self->internal_dict, name);
if (v != NULL)
{
*returndata = PyTuple_New(1);
Py_INCREF(v); // need to keep access to temp for a while
PyTuple_SetItem(*returndata, 0, v);
Py_DECREF(v);
// need to increment attribute reference as GetItemString just
// borrows the reference
return 0;
}
}
else
{
PyErr_SetString(PyExc_Exception,
("Problem: internal dictionary is NULL"));
n_printf("Internal dictionary is NULL");
return -1; // we should already have a dictionary
}
// not in dictionary so call method as defined in methods listed above...
PyObject *v = Py_FindMethod(Nebula_methods, (PyObject *)self, name);
//returns new reference
if (v != NULL)
{
*returndata = PyObject_CallObject(v, args); //lets call it
Py_DECREF(v);
return 0;
}
PyErr_Clear();
// finally we assume it's a Nebula attribute and continue
// lets lookup the attribute to see if we have already saved a pointer to it
if (NULL == args)
{ // just a function call so create a new empty tuple
commandArgs = PyTuple_New(0);
}
else
{
if (!PyTuple_Check(args))
{
// assume a single argument
commandArgs = PyTuple_New(1);
Py_INCREF(args); // need to keep access to args for a while
PyTuple_SetItem(commandArgs, 0, args); // note a stolen reference to args
}
else
{
// finally args is already a tuple
commandArgs = PyTuple_GetSlice(args, 0, PyTuple_Size(args)); // the entire tuple NR
}
}
// retrieve the stored pointer to the nebula object
nObject *o = NebulaObject_GetPointer(self);
result = NebulaObject_CallNebulaFunction(o, name, commandArgs, returndata);
Py_XDECREF(commandArgs);
return result;
}
//-----------------------------------------------------------------------------
/**
@brief Internal setattribute function to REALLY set the Python attribute
Needed as the "default" setattr calls the nebula object.
*/
int
NebulaObject_SetAttr(NebulaObject *self, char *name, PyObject *v)
{
n_assert(NULL != self);
n_assert(NULL != name);
if (NULL == self->internal_dict)
{
self->internal_dict = PyDict_New();
if (NULL == self->internal_dict)
{
n_error("Couldn't create a dictionary\n");
}
}
if (NULL == v)
{
int rv = PyDict_DelItemString(self->internal_dict, name);
if (rv < 0)
{
PyErr_SetString(PyExc_AttributeError,
"Tried to delete a nonexistent NebulaObject attribute");
}
return rv;
}
else
{
return PyDict_SetItemString(self->internal_dict, name, v);
}
}
static int
NebulaObject_Dict_Length(NebulaObject *mp)
{
n_assert(mp->internal_dict != NULL);
nObject * o = NebulaObject_GetPointer(mp);
if (o && o->IsA("nroot"))
{
nRoot *self = (nRoot *) o;
int num_children = 0;
nRoot *child;
for (child = (nRoot *) self->GetHead(); child; child = (nRoot *) child->GetSucc())
{
num_children++;
}
return num_children;
} else if (!o)
{
n_printf("NebulaObject_GetPointer returned NULL\n");
}
return 0;
}
static PyObject*
NebulaObject_Dict_Subscript(NebulaObject *mp, register PyObject *key)
{
n_assert(mp->internal_dict != NULL);
n_assert(key);
if (!PyString_Check(key))
{
PyErr_Format(PyExc_KeyError, "key must be string type and not %s", key->ob_type->tp_name);
return NULL;
}
char * keystr = PyString_AS_STRING(key);
nObject * o = NebulaObject_GetPointer(mp);
if (o && o->IsA("nroot"))
{
nRoot *self = (nRoot *) o;
if ( 0 != (self = self->Find(keystr)))
{
// TODO maybe check if we created??
return (PyObject *)NebulaObject_New(self);
}
return PyErr_Format(PyExc_KeyError, "key error ('%s' not found)", keystr);
}
else if (!o)
{
n_printf("NebulaObject_GetPointer returned NULL\n");
}
return 0;
}
staticforward PyObject* NebulaObjectIter_New(NebulaObject *nebulaObject);
static PyMappingMethods nebula_as_mapping = {
(inquiry)NebulaObject_Dict_Length, /*mp_length*/
(binaryfunc)NebulaObject_Dict_Subscript, /*mp_subscript*/
(objobjargproc)0, /*mp_ass_subscript*/
};
static char nebula_object_doc[] =
"python wrapper for nebula object\n";
// now to actually define the new python type to represent a Nebula Object
PyTypeObject Nebula_Type = {
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"Nebula", /*tp_name*/
sizeof(NebulaObject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
(destructor)NebulaObject_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*/
&nebula_as_mapping, /*tp_as_mapping*/
0, /*tp_hash*/
(ternaryfunc)NebulaObject_Call, /*tp_call*/
0, /*tp_str*/
(getattrofunc)NebulaObject_GetAttrO, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_WEAKREFS, /*tp_flags*/
nebula_object_doc, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
offsetof(NebulaObject, in_weakreflist), /*tp_weaklistoffset*/
(getiterfunc)NebulaObjectIter_New, /*tp_iter*/
0, /*tp_iternext*/
0, /*tp_methods*/
0, /*tp_members*/
0, /*tp_getset*/
0, /*tp_base*/
0, /*tp_dict*/
0, /*tp_descr_get*/
0, /*tp_descr_set*/
0, /*tp_dictoffset*/
0, /*tp_init*/
0, /*tp_alloc*/
0, /*tp_new*/
0, /*tp_free*/
0, /*tp_is_gc*/
};
/* NebulaObjectIter - iterate over the children of a NebulaObject */
extern PyTypeObject PyNebIter_Type; /* Forward */
typedef struct {
PyObject_HEAD
NebulaObject *ni_nebulaobject;
int currentPosition;
nRoot *currentObject;
} NebulaObjectIter;
static PyObject*
NebulaObjectIter_New(NebulaObject *nebulaObject)
{
NebulaObjectIter *iter = PyObject_NEW(NebulaObjectIter, &PyNebIter_Type);
if (NULL == iter)
{
return NULL;
}
Py_INCREF(nebulaObject);
iter->ni_nebulaobject = nebulaObject;
iter->currentPosition = 0;
iter->currentObject = NULL;
nObject *temp = NebulaObject_GetPointer(nebulaObject);
if (NULL == temp)
{
PyErr_SetString(PyExc_Exception, "pointer to nebula object is null!");
return NULL;
}
if (!temp->IsA("nroot"))
{
return NULL;
}
nRoot * root = static_cast<nRoot*> (temp);
iter->currentObject = root->GetHead();
return (PyObject *)iter;
}
static void
NebulaObjectIter_Dealloc(NebulaObjectIter* iter)
{
Py_DECREF(iter->ni_nebulaobject);
PyObject_DEL(iter);
}
static PyObject*
NebulaObjectIter_Next(NebulaObjectIter* iter, PyObject* /*args*/)
{
if (NULL == iter->currentObject)
{
PyErr_SetObject(PyExc_StopIteration, Py_None);
return NULL;
}
if (iter->currentPosition == 0)
{
iter->currentPosition++;
return (PyObject *)NebulaObject_New(iter->currentObject);
}
iter->currentObject = iter->currentObject->GetSucc();
if (NULL == iter->currentObject)
{
PyErr_SetObject(PyExc_StopIteration, Py_None);
return NULL;
}
iter->currentPosition++;
return (PyObject *)NebulaObject_New(iter->currentObject);
}
static PyObject*
NebulaObjectIter_GetIter(PyObject *it) {
Py_INCREF(it);
return it;
}
static PyMethodDef NebulaObjectIter_Methods[] = {
{"next", (PyCFunction)NebulaObjectIter_Next, METH_VARARGS,
"it.next() -- get the next value, or raise StopIteration"},
{NULL, NULL} /* sentinel */
};
static PyObject*
NebulaObjectIter_IterNext(NebulaObjectIter *iter)
{
if (NULL == iter->currentObject)
{
PyErr_SetObject(PyExc_StopIteration, Py_None);
return NULL;
}
if (iter->currentPosition == 0)
{
iter->currentPosition++;
return (PyObject *)NebulaObject_New(iter->currentObject);
}
iter->currentObject = iter->currentObject->GetSucc();
if (NULL == iter->currentObject)
{
PyErr_SetObject(PyExc_StopIteration, Py_None);
return NULL;
}
iter->currentPosition++;
return (PyObject *)NebulaObject_New(iter->currentObject);
}
// Nebula Iterator type
PyTypeObject PyNebIter_Type = {
PyObject_HEAD_INIT(&PyType_Type)
0, /* ob_size */
"nebula-iterator", /* tp_name */
sizeof(NebulaObjectIter), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
(destructor)NebulaObjectIter_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 */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
(getiterfunc)NebulaObjectIter_GetIter, /* tp_iter */
(iternextfunc)NebulaObjectIter_IterNext, /* tp_iternext */
NebulaObjectIter_Methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
};
#ifdef __cplusplus
}
#endif
//--------------------------------------------------------------------
// EOF
//--------------------------------------------------------------------
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
]
| [
[
[
1,
1049
]
]
]
|
480dc8f3a6632bfd45bcd07dec205bf4c6a3acc5 | 21da454a8f032d6ad63ca9460656c1e04440310e | /src/wcpp/io/wsiPrintStream.h | b7968d121f20c0beb0353812139f8d2f3c9371b2 | []
| 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 | 2,046 | h | #ifndef __wsiPrintStream_h__
#define __wsiPrintStream_h__
#include "wsiOutputStream.h"
class wsiCString;
#define WS_IID_OF_wsiPrintStream \
{ 0x5e26a9c, 0x3786, 0x4872, { 0x87, 0xd6, 0x1f, 0x24, 0xd7, 0x54, 0xc5, 0xcf } }
// {05E26A9C-3786-4872-87D6-1F24D754C5CF}
class wsiPrintStream : public wsiOutputStream
{
public:
static const ws_iid sIID;
public:
WS_METHOD( ws_boolean , CheckError )(void) = 0;
WS_METHOD( ws_result , Close )(void) = 0;
WS_METHOD( ws_result , Flush )(void) = 0;
WS_METHOD( ws_result , Write )(const void * b, ws_int len) = 0;
WS_METHOD( ws_result , Write )(ws_int b) = 0;
WS_METHOD( ws_result , Print )(ws_boolean b) = 0;
WS_METHOD( ws_result , Print )(ws_char c) = 0;
WS_METHOD( ws_result , Print )(const ws_char * const s) = 0;
WS_METHOD( ws_result , Print )(ws_double d) = 0;
WS_METHOD( ws_result , Print )(ws_float f) = 0;
WS_METHOD( ws_result , Print )(ws_int i) = 0;
WS_METHOD( ws_result , Print )(ws_long l) = 0;
WS_METHOD( ws_result , Print )(wsiObject * obj) = 0;
WS_METHOD( ws_result , Print )(wsiString * str) = 0;
WS_METHOD( ws_result , PrintLn )(void) = 0;
WS_METHOD( ws_result , PrintLn )(ws_boolean x) = 0;
WS_METHOD( ws_result , PrintLn )(ws_char x) = 0;
WS_METHOD( ws_result , PrintLn )(const ws_char * const x) = 0;
WS_METHOD( ws_result , PrintLn )(ws_double x) = 0;
WS_METHOD( ws_result , PrintLn )(ws_float x) = 0;
WS_METHOD( ws_result , PrintLn )(ws_int x) = 0;
WS_METHOD( ws_result , PrintLn )(ws_long x) = 0;
WS_METHOD( ws_result , PrintLn )(wsiObject * x) = 0;
WS_METHOD( ws_result , PrintLn )(wsiString * x) = 0;
};
#endif // __wsPrintStream_h__
| [
"xukun0217@98f29a9a-77f1-11de-91f8-ab615253d9e8"
]
| [
[
[
1,
61
]
]
]
|
91afc34a4cef31bc1ce4ee0fd00536fe1f8e6575 | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Targets/MapLib/Symbian/src/SymbianTilemapToolkit.cpp | db795fac8a16aaf76f8e2ad0c60d5599aa2eecf9 | [
"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 | 16,569 | 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 "SymbianTilemapToolkit.h"
#include "TileMapHandler.h"
#include <eikenv.h>
#include <coecntrl.h>
#ifndef SYMBIAN_9
#include <hal.h>
#endif
#include "LogFile.h"
/*
* Constructor
* Parameters :
* aPeriod - time period in milliseconds
* aId - ID given to the timer
* aTk - pointer to the creating TileMapToolkit
*/
static inline CActive::TPriority
prio_convert( TileMapToolkit::priority_t inPrio )
{
switch ( inPrio ) {
case TileMapToolkit::PRIO_IDLE:
return CActive::EPriorityIdle;
case TileMapToolkit::PRIO_LOW:
return CActive::EPriorityLow;
case TileMapToolkit::PRIO_STANDARD:
return CActive::EPriorityStandard;
case TileMapToolkit::PRIO_USERINPUT:
return CActive::EPriorityUserInput;
case TileMapToolkit::PRIO_HIGH:
return CActive::EPriorityHigh;
default:
return CActive::EPriorityStandard;
}
return CActive::EPriorityStandard;
}
class SymbianTileMapPeriodicTimer
: public TileMapPeriodicTimer {
public:
SymbianTileMapPeriodicTimer( TileMapTimerListener* listener,
uint32 periodicID,
TileMapToolkit::priority_t prio )
: TileMapPeriodicTimer( listener, periodicID ) {
m_timer = CPeriodic::NewL( prio_convert( prio ) );
}
~SymbianTileMapPeriodicTimer() {
stop();
delete m_timer;
}
bool active() {
return m_timer->IsActive();
}
void start( uint32 period_millis ) {
uint32 periodMicros = period_millis * 1000;
if ( ! m_timer->IsActive() ) {
m_timer->Start( periodMicros, periodMicros,
TCallBack(SymbCallback,this) );
}
}
void stop() {
if ( m_timer->IsActive() ) {
m_timer->Cancel();
}
}
private:
inline void periodic() {
m_listener->timerExpired( m_timerID );
}
/* key timer callback */
static TInt SymbCallback(TAny* aThisPtr) {
SymbianTileMapPeriodicTimer* thisPtr =
(SymbianTileMapPeriodicTimer*) aThisPtr;
thisPtr->periodic();
return 1;
}
CPeriodic* m_timer;
};
class SymbianTileMapTimer : public CTimer
{
private:
/*
* Contains a pointer to the specified TileMapToolkit
*/
TileMapToolkit* m_Toolkit;
/*
* Id of the timer
*/
uint32 m_Id;
/*
* Gets called when the timer expires.
*/
TileMapTimerListener* m_Listener;
protected:
/*
* Inherited from CTimer.
* Callback for when the timer has expired.
*/
void RunL();
public:
/*
* Constructor
* Parameters :
* aPeriod - time period in milliseconds
* aId - ID given to the timer
* aTk - pointer to the creating TileMapToolkit
*/
SymbianTileMapTimer(uint32 aId,
TileMapTimerListener* aListener,
TileMapToolkit* aTk,
TileMapToolkit::priority_t prio );
/*
* Destructor
*/
virtual ~SymbianTileMapTimer();
/*
* Starts the timer countdown
*/
bool startTimer(uint32 aPeriod);
};
// ilde timer class
class SymbianIdleTimer
{
private:
/*
* The CIdle object which does the actual job
*/
CIdle* m_idleTimer;
typedef std::list<std::pair<uint32, TileMapIdleListener*> > queue_t;
/// Queue of idle objects waiting to run
queue_t m_idleQueue;
/// Current idle id.
uint32 m_curIdleID;
/// True if we are in the callback
int m_inCallBack;
protected:
// callback for the idle timer, this delegates to the listener
static TInt idleTimerCallback(TAny* aThisPtr);
/// Callback called from the real callback
TInt idleCallback();
/// Starts the CIdle
bool Start();
/// Stops the CIdle
void Stop();
public:
/// constructor
SymbianIdleTimer();
/// destructor
~SymbianIdleTimer();
/// Adds the TileMapIdleListener to the end of the queue.
uint32 addIdleListener(TileMapIdleListener* tml);
/// Cancels an idle. Returns true if the id was found.
bool cancelIdle(uint32 id);
};
SymbianTileMapTimer::SymbianTileMapTimer(uint32 aId,
TileMapTimerListener* aListener,
TileMapToolkit* aTk,
TileMapToolkit::priority_t prio) :
CTimer(prio_convert(prio)) {
m_Id = aId;
m_Toolkit = aTk;
m_Listener = aListener;
}
/*
* Destructor
*/
SymbianTileMapTimer::~SymbianTileMapTimer()
{
if ( IsActive() ) {
Cancel();
}
m_Id = NULL;
m_Toolkit = NULL;
m_Listener = NULL;
}
/*
* Starts the timer countdown
*/
bool SymbianTileMapTimer::startTimer(uint32 aPeriod)
{
TRAPD(errCode, ConstructL());
if(errCode != KErrNone) {
return(false);
}
else {
/* add the timer to the active scheduler for processing */
CActiveScheduler::Add(this);
/* multiply by 1000 to get microsecond count */
After(aPeriod * 1000);
}
return(true);
}
/*
* Inherited from CTimer.
* Callback for when the timer has expired.
*/
void SymbianTileMapTimer::RunL() {
m_Listener->timerExpired(m_Id);
((SymbianTileMapToolkit*)m_Toolkit)->timerDone(m_Id);
return;
}
/*******************
* SymbianIdleTimer *
********************/
// constructor
SymbianIdleTimer::SymbianIdleTimer()
{
// This is probably forbidden in Symbian.
m_idleTimer = CIdle::New(CActive::EPriorityIdle);
// Means that it will start at 1.
m_curIdleID = 0;
m_inCallBack = 0;
}
// destructor
SymbianIdleTimer::~SymbianIdleTimer() {
// stop the timer if active
Stop();
delete m_idleTimer;
}
uint32
SymbianIdleTimer::addIdleListener(TileMapIdleListener* listener)
{
++m_curIdleID;
m_idleQueue.push_back( std::make_pair( m_curIdleID, listener ) );
// Start if necessary.
Start();
return m_curIdleID;
}
bool
SymbianIdleTimer::cancelIdle(uint32 id)
{
for( queue_t::iterator it = m_idleQueue.begin();
it != m_idleQueue.end();
++it ) {
if ( it->first == id ) {
// Idle will stop on next request.
m_idleQueue.erase( it );
return true;
}
}
return false;
}
// starts the idle timer
// returns true on success, false on error
bool
SymbianIdleTimer::Start()
{
// If we are in the callback, it will continue automatically
// if the queue is not empty.
if ( ! m_inCallBack ) {
if ( ! m_idleTimer->IsActive() ) {
// timer is allocated, start the callback
m_idleTimer->Start(TCallBack(idleTimerCallback, this));
}
}
// Assume success
return true;
}
// stops the idle timer
void
SymbianIdleTimer::Stop()
{
if( m_idleTimer->IsActive() ) {
m_idleTimer->Cancel();
}
}
// callback for the idle timer, this delegates to the listener
TInt
SymbianIdleTimer::idleCallback()
{
// Check for recursive calls to start
++m_inCallBack;
if ( ! m_idleQueue.empty() ) {
queue_t::value_type curIdle = m_idleQueue.front();
m_idleQueue.pop_front();
// Inform the listener
curIdle.second->runIdleTask( curIdle.first );
}
--m_inCallBack;
// Nothing dangerous in callback now.
return ! m_idleQueue.empty();
}
// Called by Symbian when idle.
TInt
SymbianIdleTimer::idleTimerCallback(TAny* aThisPtr)
{
SymbianIdleTimer* timer = (SymbianIdleTimer*)(aThisPtr);
return timer->idleCallback();
}
/************************
* SymbianTileMapToolkit *
*************************/
/*
* Constructor
*/
SymbianTileMapToolkit::SymbianTileMapToolkit(CCoeControl& parentControl,
const char* extraInfo)
: m_parentContainer(parentControl)
{
m_idleTimer = new SymbianIdleTimer;
if ( extraInfo == NULL ) {
extraInfo = "";
}
/*
* This will have to be changed to the size
* of the map<> so that continous usage of the map doesnt
* cause a overflow! TODO */
m_curTimerID = 100;
// Create id string 8 chars for hex id and a - then some for the extraInfo
m_idString = new char[10+strlen(extraInfo)];
// Get the machine id
TInt machineID = 0;
#ifndef SYMBIAN_9
HAL::Get( HALData::EMachineUid, machineID );
#endif
sprintf(m_idString, "%X-%s", machineID, extraInfo);
}
/*
* Destructor
*/
SymbianTileMapToolkit::~SymbianTileMapToolkit()
{
// clean up the left-over TileMap timers
for(timerMap_t::iterator it = m_timerArray.begin();
it != m_timerArray.end();
++it ) {
/* checks if the timer is non-NULL & active, if it is, cancels it */
if(it->second) {
if( it->second->IsActive() ) {
it->second->Cancel();
}
addForDeletion(it->second);
}
}
m_timerArray.clear();
cleanupOldTimers();
delete [] m_idString;
delete m_idleTimer;
}
TileMapPeriodicTimer*
SymbianTileMapToolkit::createPeriodicTimer( TileMapTimerListener* listener,
priority_t prio )
{
return new SymbianTileMapPeriodicTimer(listener, ++m_curTimerID, prio );
}
inline void
SymbianTileMapToolkit::addForDeletion(SymbianTileMapTimer* timer)
{
m_garbage.push_back(timer);
}
void
SymbianTileMapToolkit::cleanupOldTimers()
{
for ( garbageStorage_t::iterator it = m_garbage.begin();
it != m_garbage.end();
++it ) {
delete *it;
}
m_garbage.clear();
}
/*
* Handles the timer expiration
*/
void SymbianTileMapToolkit::timerDone(uint32 timerID)
{
// Delete timers, but not this one. We know that this
// cannot happen in another timer's context.
cleanupOldTimers();
// Try to find the timer.
timerMap_t::iterator it = m_timerArray.find(timerID);
if( it != m_timerArray.end() ) {
addForDeletion(it->second);
m_timerArray.erase(it);
}
return;
}
/* from TileMapToolkit */
/* currently returns 0xFFFFFFFF on error */
uint32 SymbianTileMapToolkit::requestTimer(TileMapTimerListener* client,
uint32 timeoutMS,
TileMapToolkit::priority_t prio) {
m_curTimerID++;
// We should not delete old timers here, since we don't
// know if requestTimer is called in another timer's context (RunL).
SymbianTileMapTimer* newtimer = new SymbianTileMapTimer(m_curTimerID,
client,
this,
prio );
/* on allocation error, return 0xFFFFFFFF */
if(newtimer == NULL) {
return(0xFFFFFFFF);
}
/* start the timer now */
if(!newtimer->startTimer(timeoutMS))
{
delete newtimer;
return(0xFFFFFFFF);
}
/* add the timer to internal map */
m_timerArray.insert( std::make_pair( m_curTimerID, newtimer ) );
/* increment timer ID */
return m_curTimerID;
}
bool SymbianTileMapToolkit::cancelTimer(TileMapTimerListener* /*client*/,
uint32 timerID)
{
timerMap_t::iterator it = m_timerArray.find(timerID);
if( it != m_timerArray.end() ) {
if( it->second->IsActive() ) {
it->second->Cancel();
}
// We can delete it right away, but we'll wait.
addForDeletion( it->second );
m_timerArray.erase( it );
return(true);
}
return(false);
}
/**
* Requests that client should be notified when
* the system is idle.
*/
uint32 SymbianTileMapToolkit::requestIdle(TileMapIdleListener* client)
{
return m_idleTimer->addIdleListener(client);
}
/**
* Cancels the call to the client with the requested
* idle id.
*/
bool SymbianTileMapToolkit::cancelIdle(TileMapIdleListener* /*client*/,
uint32 id )
{
return m_idleTimer->cancelIdle(id);
}
bool SymbianTileMapToolkit::trustAvailableMemory() const
{
#ifdef SYMBIAN_9
// User::Available seems to cause crashes, and
// HAL::Get(HALData::EMemoryRAMFree, memFree ) is not
// available any more.
return false;
#else
return true;
#endif
}
uint32
SymbianTileMapToolkit::memFree(uint32& biggestBlock)
{
#ifdef SYMBIAN_9
// This method is not working for symbian 9.
biggestBlock = 0;
return 0;
#else
TInt intbiggestBlock;
int available = User::Available(intbiggestBlock);
int memFree=0;
HAL::Get(HALData::EMemoryRAMFree, memFree );
available += memFree;
biggestBlock = intbiggestBlock;
return available;
#endif
}
uint32
SymbianTileMapToolkit::memFree()
{
uint32 biggestBlock;
uint32 res = SymbianTileMapToolkit::memFree(biggestBlock);
return res;
}
uint32
SymbianTileMapToolkit::availableMemory(uint32& biggestBlock) const
{
uint32 res = SymbianTileMapToolkit::memFree(biggestBlock);
return res;
}
const char*
SymbianTileMapToolkit::getIDString() const
{
return m_idString;
}
// Handles assertions from ArchConfigMisc.h
void
handleAssert( const char* cause, const char* file, int line )
{
#ifndef __WINS__
char* newStr = new char[strlen(cause) + strlen(file) + 2 + 1 ];
char* lastSlash = strrchr(file, '/');
if ( lastSlash == NULL ) {
lastSlash = strrchr(file, '\\');
}
if ( lastSlash != NULL ) {
file = lastSlash + 1;
}
sprintf(newStr, "%s", file);
int length = strlen( newStr );
HBufC* buf = HBufC::New( 2*length + 2 );
// Modifyable buffer from inside the HBufC
TPtr charBuf = buf->Des();
for ( int i = 0; i < length + 1; ++i ) {
charBuf.Append( (TChar) newStr[i] );
}
charBuf.PtrZ();
delete [] newStr;
// Show the assertion
User::Panic( *buf, line );
#else
cause = cause; // To remove warnings.
file = file;
line = line;
*((uint8*)(0)) = 0;
#endif
}
// Handles TRACE
void
handleTrace( int line, const char* file, const char* function )
{
FILE* f = fopen("C:\\trace.txt", "a" );
if ( !f ) return;
if ( function ) {
fprintf( f, "%s:%d:%s\n", file, line, function );
} else {
fprintf( f, "%s:%d\n", file, line );
}
fclose( f );
}
| [
"[email protected]"
]
| [
[
[
1,
642
]
]
]
|
54c96d676109270bd7736c0d42f5620f236dd834 | ae9202b0e8b669ea285aa98945cbbc97011e1398 | /src/lsdsoft/welltools/im/immn73/IMMN73CorrectionTable.cpp | 60522ec2fc77c0c455d5149d718ab92d49599c75 | []
| no_license | zukker/zues | c5d5d8032e288a61bf9fad023ea422295e975fa8 | 497f1318284c01c33558c58a6027bcdcb5021cf7 | refs/heads/master | 2021-01-22T13:17:56.747231 | 2011-08-31T06:17:43 | 2011-08-31T06:17:43 | 2,326,349 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 7,771 | cpp | #include <math.h>
#include "IMMN73CorrectionTable.hpp"
#include "Properties.hpp"
#include "TextTemplate.hpp"
extern Properties props;
IMMN73CorrectionTable::IMMN73CorrectionTable() {
setNumber("0");
setDefaults();
}
IMMN73CorrectionTable::IMMN73CorrectionTable(AnsiString num) {
setNumber(num);
setDefaults();
}
IMMN73CorrectionTable::~IMMN73CorrectionTable() {
}
void IMMN73CorrectionTable::setDefaults() {
loaded = false;
}
void IMMN73CorrectionTable::load(void * buf, int size) {
char * input = (char*)buf;
char * line;
// получение данных для БСКТ
line = getLine(input, 3);
computer.bSensor.zeroX = atol(line + 11);
computer.bSensor.zeroY = atol(line + 20);
line = getLine(input, 4);
computer.bSensor.amplitudeX = atol(line + 11);
computer.bSensor.amplitudeY = atol(line + 18);
// данные для магнитометров
line = getLine(input, 6);
computer.mSensor.zeroX = atol(line + 11);
computer.mSensor.zeroY = atol(line + 17);
line = getLine(input, 7);
computer.mSensor.amplitudeX = atol(line + 11);
computer.mSensor.amplitudeY = atol(line + 17);
// установочная погрешность по зениту
line = getLine(input, 8);
zenitOffset = atof(line + 64);
// поправки по зениту
zenitTable.spl.setDimention(11); // жестко заданы 11 значений по азимуту
line = getLine(input, 9); // полученные углы по прибору
for(int i = 0; i < 11; i++) {
zenitTable.spl[i].x = atof(line + i * 8);
}
line = getLine(input, 10); // значение поправки
for(int i = 0; i < 11; i++) {
zenitTable.spl[i].y = atof(line + i * 8);
}
zenitTable.spl.preCalc();
// установочная погрешность по азимуту
line = getLine(input, 11);
azimutOffset = atof(line + 64);
// поправки по азимуту
clearAzimutTable();
for(int table = 0; table < 4; table++) {
line = getLine(input, table * 3 + 12);
AzimutZenitPoint * point = new AzimutZenitPoint;
point->repZenit = atof(line + 26);
point->spl.setDimention(12);
line = getLine(input, table * 3 + 13); // полученные углы по прибору
for(int i = 0; i < 12; i++) {
double value = atof(line + i * 8);
if(i < 2 && value > 300) value -= 360;
point->spl[i].x = value;
}
line = getLine(input, table * 3 + 14); // значение поправки
for(int i = 0; i < 12; i++) {
point->spl[i].y = atof(line + i * 8);
}
azimutTable.zenPoints.addItem(point);
}
}
// 0x0d0a - end of line
char* IMMN73CorrectionTable::getLine(char * buf, int lineNumber) {
int currentLine = 0;
int pos = 0;
char * line = buf;
while(currentLine < lineNumber) {
if(line[pos] == 0x0d) {
if(line[pos + 1] == 0x0a) { // found end of line
line = line + pos + 2; // next line
} else {
line = line + pos + 1;
}
pos = 0;
currentLine ++;
} else if(line[pos] == 0x00) break; // end of buf
else pos++;
}
return line;
}
void IMMN73CorrectionTable::setNumber(AnsiString num) {
number = num;
}
void IMMN73CorrectionTable::load() {
AnsiString file = props.getProperty("immn73.calib");
file = IncludeTrailingBackslash(file);
AnsiString name;
name.sprintf("IM73_%s.CLB", number.c_str());
file += name;
load(file);
}
void IMMN73CorrectionTable::load(AnsiString fileName) {
TFileStream * file = new TFileStream(fileName, fmOpenRead);
int size = file->Size;
char * buf = new char[size + 1];
if(!buf) throw Exception("Not enough memory");
file->Read(buf, size);
buf[size] = 0;
load(buf, size);
delete buf;
delete file;
}
void IMMN73CorrectionTable::compute(int * sensorValues, InklinometerAngles& ang) {
computer.compute(sensorValues, ang);
}
void IMMN73CorrectionTable::correct(InklinometerAngles& angles) {
double value = angles.zenit.getValue();
value += zenitTable.spl.calc(value) + zenitOffset;
angles.zenit = value;
// correct azimut
// find nearest zenit
Angle delta = 360.0;
int index = 0;
unsigned int count = azimutTable.zenPoints.getCount();
if(count == 0) return;
for(unsigned int i = 0; i < azimutTable.zenPoints.getCount(); i++) {
Angle zen = ((AzimutZenitPoint*)azimutTable.zenPoints[i])->repZenit;
if((zen - angles.zenit).abs() < delta) {
index = i;
delta = (zen - angles.zenit).abs();
}
}
value = angles.azimut.getValue();
double corr = ((AzimutZenitPoint*)azimutTable.zenPoints[index])->spl.calc(value);
value += corr + azimutOffset;
angles.azimut = value;
}
void IMMN73CorrectionTable::clearAzimutTable() {
// free allocated space
// TODO this
azimutTable.zenPoints.clear();
}
void IMMN73CorrectionTable::save() {
TextTemplate tpl;
Properties prop1;
TMemoryStream * out = new TMemoryStream;
AnsiString value;
AnsiString name;
AnsiString f, f1;
AnsiString tplroot = props.getProperty("path.templates");
tplroot = IncludeTrailingBackslash(tplroot);
tpl.setProperties(&prop1);
// rotate protocol
name = tplroot;
name += "immn73clb.txt";
tpl.Load(name);
// set some values
prop1.setProperty("tool.number", number);
prop1.setProperty("date.calib", props.getProperty("date.calib"));
prop1.setProperty("bSensor.zeroX", computer.bSensor.zeroX);
prop1.setProperty("bSensor.zeroY", computer.bSensor.zeroY);
prop1.setProperty("bSensor.ampX", computer.bSensor.amplitudeX);
prop1.setProperty("bSensor.ampY", computer.bSensor.amplitudeY);
prop1.setProperty("mSensor.zeroX", computer.mSensor.zeroX);
prop1.setProperty("mSensor.zeroY", computer.mSensor.zeroY);
prop1.setProperty("mSensor.ampX", computer.mSensor.amplitudeX);
prop1.setProperty("mSensor.ampY", computer.mSensor.amplitudeY);
// gen zenit string
f ="";
for(int i = 0; i < zenitTable.spl.getDimension(); i++) {
value.sprintf("%8.2f", zenitTable.spl[i].x);
f += value;
value.sprintf("%8.2f", zenitTable.spl[i].y);
f1 += value;
}
prop1.setProperty("zenit.points", f);
prop1.setProperty("zenit.corr", f1);
// gen azimt strings
for(int i = 0; i < azimutTable.zenPoints.getCount(); i++) {
AzimutZenitPoint* point = (AzimutZenitPoint*)azimutTable.zenPoints[i];
f.sprintf("azenit.%d", i);
value.sprintf("%8.2f", point->repZenit.getValue());
prop1.setProperty(f, value);
f = "";
f1 = "";
for(int j = 0; j < point->spl.getDimension(); j++) {
value.sprintf("%8.2f", point->spl[j].x);
f += value;
value.sprintf("%8.2f", point->spl[j].y);
f1 += value;
}
value.sprintf("azimut.points.%d", i);
prop1.setProperty(value, f);
value.sprintf("azimut.corr.%d", i);
prop1.setProperty(value, f1);
}
// store to file
tpl.doFilter();
tpl.Save(out);
AnsiString file = props.getProperty("immn73.calib");
file = IncludeTrailingBackslash(file);
name.sprintf("IM73_%s_.CLB", number.c_str());
file += name;
out->SaveToFile(file);
delete out;
}
SplineInterpolation* IMMN73CorrectionTable::getZenitSpline() {
return &zenitTable.spl;
}
SplineInterpolation* IMMN73CorrectionTable::getAzimutSpline(unsigned int zenit) {
if(zenit >= azimutTable.zenPoints.getCount()) return 0;
return &((AzimutZenitPoint*)azimutTable.zenPoints[zenit])->spl;
}
double IMMN73CorrectionTable::getZenit(unsigned int zenit) {
if(zenit >= azimutTable.zenPoints.getCount()) return 0;
return ((AzimutZenitPoint*)azimutTable.zenPoints[zenit])->repZenit.getValue();
}
| [
"[email protected]"
]
| [
[
[
1,
242
]
]
]
|
07cd3013ff99491dd186adb0b8b47c0c7fc3100c | c930acc7d855f5082dfc598437dacd7d73718787 | /minimax.h | 58ccd6c3f36724020036d8c959e0e6a6865f73b6 | []
| no_license | giulianoxt/qassault | 9db0c67c2122d41299e4f41e3bc5d985b8a7db7b | ff46426199e5336b64bd8eb70fce66d8e0212f83 | refs/heads/master | 2020-05-19T11:13:13.623501 | 2009-10-06T00:50:02 | 2009-10-06T00:50:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,088 | h | #ifndef MINIMAX_H
#define MINIMAX_H
#include <QCache>
#include "game.h"
#include "globals.h"
struct SearchResult;
class MinimaxAI
{
public:
MinimaxAI(PlayerType, int);
Move searchTree(const GameState&);
Move searchTreeCache(const GameState&);
protected:
bool oneMoveWin(const GameState&,
const QList<Move>&, int&);
double minimax(const GameState&, bool,
int, int&, double, double);
double minimaxCache(const GameState&, bool,
int, int&, double, double);
protected:
bool isMax;
int hitNodes;
int numNodes;
int lookahead;
PlayerType player;
QCache<GameState,SearchResult> cache;
};
enum ResultType { Exact, LowerBound, UpperBound };
struct SearchResult {
int depth;
int movInd;
double eval;
ResultType type;
SearchResult();
SearchResult(int, int, double, ResultType);
GameState st;
double alpha, beta;
};
uint qHash(const GameState&);
#endif // MINIMAX_H
| [
"[email protected]"
]
| [
[
[
1,
54
]
]
]
|
a4c5b8a285cb9a6011c8fe985b8ab9c0597952c6 | 10dae5a20816dba197ecf76d6200fd1a9763ef97 | /src/individual.h | 023b69ecb73ff3234573515518387ccca419cd1f | []
| no_license | peterdfields/quantiNEMO_Taylor2010 | fd43aba9b1fcf504132494ff63d08a9b45b3f683 | 611b46bf89836c4327fe64abd7b4008815152c9f | refs/heads/master | 2020-02-26T17:33:24.396350 | 2011-02-08T23:08:34 | 2011-02-08T23:08:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,426 | h | /** @file individual.h
*
* Copyright (C) 2006 Frederic Guillaume <[email protected]>
* Copyright (C) 2008 Samuel Neuenschwander <[email protected]>
*
* quantiNEMO:
* quantiNEMO is an individual-based, genetically explicit stochastic
* simulation program. It was developed to investigate the effects of
* selection, mutation, recombination, and drift on quantitative traits
* with varying architectures in structured populations connected by
* migration and located in a heterogeneous habitat.
*
* quantiNEMO is built on the evolutionary and population genetics
* programming framework NEMO (Guillaume and Rougemont, 2006, Bioinformatics).
*
*
* Licensing:
* This file is part of quantiNEMO.
*
* quantiNEMO is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* quantiNEMO is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with quantiNEMO. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef individualH
#define individualH
#include <map>
#include <deque>
#include "types.h"
#include "ttrait.h"
/**This class contains traits along with other individual information (sex, pedigree, etc.\ ).
* The Individual class can be view as a trait container. It encapsulates the basic interface to manipulate
* the traits an individual is carrying like initialization, inheritance, mutation and phenotype getter. It also
* stores the basic individual info like its sex, pedigree (home Patch, mother and father id, etc.) and its
* mating and fecundity values. It is not a StorableComponent but declares a similar interface to store and retrieve
* all the previous info to/from a binary file.
* All individuals in a simulation are instantiated by a call to the IndFactory class (through its derived class Metapop)
* which contains the individual and traits prototypes.
*/
class Patch;
class LCE_Breed_fitness;
class Individual {
private:
/**ID tag, unique for one simulation.*/
string _id; // "123_1": individual 123 of patch 1
/**Sex tag.*/
sex_t _sex;
/**Parents pointers.*/
Individual *_mother, *_father;
/** ID tags of the parents */
string _motherID, _fatherID; // "123_1": individual 123 of patch 1
/**Patch tag.*/
Patch *_natalPatch, *_currentPatch;
/**Selfing flag.*/
bool _isSelfed;
/**Assigned fecundity*/
double _fecundity;
/** current fitness of the individual */
double _fitness;
/**Number of times the female mated with [0]: a male from a different Patch or [1]: from the same Patch.*/
unsigned short _matings[2];
/**Number of surviving offspring from the different mating categories (see matings).*/
unsigned short _realizedFecundity[2];
/**Number of traits in the table*/
unsigned int _trait_nb;
public:
typedef int IDX;
/**The traits table.*/
deque<TTrait*> Traits;
Individual ();
~Individual () {clearTraits();}
/**Inits parameters and traits.
@callgraph
**/
Individual* init ();
/**Resets parameters and traits values.
@callgraph
**/
void reset ();
void reset_traits ();
///@name Setters
///@{
void setID (string value) {_id = value;}
void setFather (Individual* f) {_father = f; if(f){_fatherID = f->getID();}}
void setMother (Individual* m) {_mother = m; if(m){_motherID = m->getID();}}
void setFatherID (string f) {_fatherID = f;}
void setMotherID (string m) {_motherID = m;}
void setNatalPatch (Patch* p) {_natalPatch = p;}
void setCurrentPatch (Patch* p) {_currentPatch = p;}
void setSex (sex_t sex) {_sex = sex;}
void setIsSelfed (bool s) {_isSelfed = s;}
void setFitness (double value) {_fitness = value;}
///@}
///@name Getters
///@{
string getID () {return _id;}
unsigned int getID_individual () {return STRING::str2int<unsigned int>(_id.substr(0,_id.find('_')));}
Individual* getFather () {return _father;}
Individual* getMother () {return _mother;}
string getFatherID () {return _fatherID;}
string getMotherID () {return _motherID;}
Patch* getNatalPatch () {return _natalPatch;}
Patch* getCurrentPatch () {return _currentPatch;}
sex_t getSex () {return _sex;}
bool isFemale () {return (_sex == FEM);}
/**@param cat the mating category, 0 = between Patch, 1 = within Patch*/
unsigned short getMatings (unsigned int cat) {return _matings[cat];}
/**@param cat the mating category, 0 = between Patch, 1 = within Patch*/
unsigned short getRealizedFecundity (unsigned int cat) {return _realizedFecundity[cat];}
unsigned int getTotRealizedFecundity() {return _realizedFecundity[0] + _realizedFecundity[1];}
unsigned int getTotMatings ( ) {return _matings[0] + _matings[1];}
bool getIsSelfed ( ) {return _isSelfed;}
double getFitness ( ) {return _fitness;}
///@}
/**Resets the mating and fecundity counters.*/
void reset_counters ( ) {
_matings[0] = _matings[1] = 0;
_realizedFecundity[0] = _realizedFecundity[1] = 0;
}
void switch_sex(age_idx AGE, const int& i);
/**Adds a mating event to the right mating category.
* @param category the mating category, 0 = between Patch, 1 = within Patch
*/
void addMating (unsigned int category) {_matings[category]++;}
/**Increments the fecundity counter following the mating category
* @param category the mating category, 0 = between Patch, 1 = within Patch
*/
void DidHaveABaby (unsigned int category) {
_matings[category]++;
_realizedFecundity[category]++;
}
/**Returns the proportion of succesfull local matings.
* @return _realizedFecundity[1]/_matings[1]
*/
double getFecWithHomePatchMate () {return (_matings[1] != 0 ? (double) _realizedFecundity[1]/_matings[1] : 0.0);}
/**Returns the proportion of successfull remote matings.
*@return _realizedFecundity[0]/_matings[0]
*/
double getFecWithOtherPatchMate () {return (_matings[0] != 0 ? (double) _realizedFecundity[0]/_matings[0] : 0.0);}
///@}
///@name Trait interface
///@{
unsigned int getTraitNumber() { return _trait_nb;}
/**Traits table accessor.
* @return the traits table
*/
deque<TTrait *>& getTraits() {return Traits;}
/**Sets the phenotype/value of a trait to a particular value.
* @param T the trait index
* @param value the value passed to the trait
*/
void* setTrait (IDX i, void* value){
getTrait(i)->set_trait(value);
return value;
}
/**Calls the value setting procedure of a particular trait.
* @param T the trait index
*/
void setTraitValue (IDX T){
getTrait(T)->set_value();
}
void setTraitValue (IDX T, double values){
getTrait(T)->set_value(values);
}
/**Gets the value (phenotype) of a particular trait.
* @param T the trait type
*/
double getTraitValue (IDX T){
return getTrait(T)->get_value();
}
/**Gets the value (genotype) of a particular trait.
* @param T the trait type
*/
double getTraitGenotype (IDX T){
return getTrait(T)->get_genotype();
}
/**Gets the value (phenotype) of a particular trait.
* @param T the trait type
*/
double getTraitPhenotype (IDX T){
return getTrait(T)->get_phenotype();
}
/**Gets the fitness factor of a particular trait (only used for quantitative traits).
* @param T the trait type
*/
double getFitnessFactor (IDX T){
return getTrait(T)->get_fitnessFactor();
}
/**Cpmutes the fitness factor of a particular trait (only used for quantitative traits).
* @param T the trait type
*/
void setFitnessFactor (IDX T){
getTrait(T)->set_fitness_factor();
}
/**Trait accessor.
* @param T the trait index
*/
TTrait* getTrait (IDX T)
{
assert(T >= 0 && T < (int)_trait_nb);
return Traits[T];
}
/**Adds a trait to the table.
* @param theTrait pointer to the trait to add
@param pos the position where the trait should be added
*/
void addTrait (TTrait* theTrait, IDX pos){
if((int)_trait_nb != pos) fatal("Individual::adding a trait to the wrong position (%i) (size %i)!\n",pos,_trait_nb);
Traits.push_back(theTrait);
_trait_nb++;
}
/**Removes a trait from the table.
* @param T the trait index
*/
void removeTrait (IDX T){
delete Traits[T]; Traits.erase(Traits.begin() + T); _trait_nb--;
}
/**Clears the traits container.**/
void clearTraits ( ){
TTraitProto::deleteGeneticMap();
for(unsigned int i = 0; i < _trait_nb; ++i){
delete Traits[i];
}
Traits.clear();
_trait_nb = 0;
}
/**Calls the inheritance procedure of a particular trait.
* @param T the trait index
* @param mother the mother
* @param father the father
*/
void inheritTrait (IDX T, Individual* mother, Individual* father){
getTrait(T)->inherit(mother->getTrait(T), father->getTrait(T));
}
/**Calls the recombination procedure of the traits.
*This function has to be called only once when a new offspring is created.
*/
void recombine (){
TTraitProto::recombine();
}
/**Calls the mutation procedure of a particular trait.
* @param T the trait index
*/
void mutateTrait (IDX T){
getTrait(T)->mutate();
}
/**The creation of a trait includes its inheritance, mutation and value setting.
@param i the index of the trait to create
@param mother the mother
@param father the father
**/
void create (IDX i, Individual* mother, Individual* father){
assert(mother && father);
TTrait* T = Traits[i];
T->inherit(mother->getTrait(i),father->getTrait(i));
T->mutate();
T->set_value();
}
/**Creates an individual's genotypes and phenotypes for first generation.**/
void create (){
for(unsigned int i = 0; i < _trait_nb; i++) {
Traits[i]->ini_sequence(_natalPatch);
Traits[i]->set_value();
}
}
/**Creates an individual, inherit, mutate and set all its traits.
* @param mother the mother
* @param father the father
**/
void create (Individual* mother, Individual* father)
{
assert(mother && father);
recombine(); // make a recombination if the genetic map exists
TTrait *TT;
for(unsigned int i = 0; i < _trait_nb; i++) {
TT = Traits[i];
TT->inherit(mother->getTrait(i), father->getTrait(i));
TT->mutate();
TT->set_value();
}
}
/**Calls the inheritance procedure of all the traits present in the individual.
* @param mother the mother
* @param father the father
**/
void inherit (Individual* mother, Individual* father);
/**Calls the mutation procedure of all the traits present in the individual. */
void mutate (){
for(unsigned int i = 0; i < _trait_nb; i++){
Traits[i]->mutate();
}
}
///@}
/**Write some info to stdout.*/
void show_up();
/**Cloning procedure, clones all the traits present in the individual.*/
Individual* clone ();
///@name Operators
///@{
/**Assignment, make a deep copy of the parameter values and traits.*/
Individual& operator=(const Individual& i);
/**Only checks for traits equivalence. */
bool operator==(const Individual& i);
bool operator!=(const Individual& i);
///@}
};
#endif //INDIVIDUAL_H
| [
"[email protected]"
]
| [
[
[
1,
369
]
]
]
|
3663df83985b21ab6a9d7e1819bd12d5035b0220 | 502efe97b985c69d6378d9c428c715641719ee03 | /src/moaicore/MOAILayer2D.cpp | 6aceb01f6ff3fe58b52309371592ca4dada0e213 | []
| no_license | neojjang/moai-beta | c3933bca2625bca4f4da26341de6b855e41b9beb | 6bc96412d35192246e35bff91df101bd7c7e41e1 | refs/heads/master | 2021-01-16T20:33:59.443558 | 2011-09-19T23:45:06 | 2011-09-19T23:45:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,544 | cpp | // Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved.
// http://getmoai.com
#include "pch.h"
#include <moaicore/MOAIBox2DWorld.h>
#include <moaicore/MOAIDeck.h>
#include <moaicore/MOAICpSpace.h>
#include <moaicore/MOAIDebugLines.h>
#include <moaicore/MOAIFrameBuffer.h>
#include <moaicore/MOAIGfxDevice.h>
#include <moaicore/MOAILayer2D.h>
#include <moaicore/MOAILogMessages.h>
#include <moaicore/MOAIPartitionResultBuffer.h>
#include <moaicore/MOAIPartitionResultMgr.h>
#include <moaicore/MOAIProp2D.h>
#include <moaicore/MOAITexture.h>
#include <moaicore/MOAITransform.h>
//================================================================//
// local
//================================================================//
//----------------------------------------------------------------//
/** @name clear
@text Remove all props from the layer's partition.
@in MOAILayer2D self
@out nil
*/
int MOAILayer2D::_clear ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAILayer2D, "U" )
if ( self->mPartition ) {
self->mPartition->Clear ();
}
return 0;
}
//----------------------------------------------------------------//
/** @name getFitting
@text Computes a camera fitting for a given world rect along with
an optional screen space padding. To do a fitting, computer
the world rect based on whatever you are fitting to, use
this method to get the fitting, then animate the camera
to match.
@in MOAILayer2D self
@in number xMin
@in number yMin
@in number xMax
@in number yMax
@opt number xPad
@opt number yPad
@out number x X center of fitting (use for camera location).
@out number y Y center of fitting (use for camera location).
@out number s Scale of fitting (use for camera scale).
*/
int MOAILayer2D::_getFitting ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAILayer2D, "UNNNN" )
USRect worldRect;
worldRect.mXMin = state.GetValue < float >( 2, 0.0f );
worldRect.mYMin = state.GetValue < float >( 3, 0.0f );
worldRect.mXMax = state.GetValue < float >( 4, 0.0f );
worldRect.mYMax = state.GetValue < float >( 5, 0.0f );
worldRect.Bless ();
float hPad = state.GetValue < float >( 6, 0.0f );
float vPad = state.GetValue < float >( 7, 0.0f );
float x = worldRect.mXMin + (( worldRect.mXMax - worldRect.mXMin ) * 0.5f );
float y = worldRect.mYMin + (( worldRect.mYMax - worldRect.mYMin ) * 0.5f );
lua_pushnumber ( state, x );
lua_pushnumber ( state, y );
float fitting = self->GetFitting ( worldRect, hPad, vPad );
lua_pushnumber ( state, fitting );
return 3;
}
//----------------------------------------------------------------//
/** @name getPartition
@text Returns the partition (if any) currently attached to this layer.
@in MOAILayer2D self
@out MOAIPartition partition
*/
int MOAILayer2D::_getPartition ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAILayer2D, "U" )
if ( self->mPartition ) {
self->mPartition->PushLuaUserdata ( state );
return 1;
}
return 0;
}
//----------------------------------------------------------------//
/** @name insertProp
@text Adds a prop to the layer's partition.
@in MOAILayer2D self
@in MOAIProp prop
@out nil
*/
int MOAILayer2D::_insertProp ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAILayer2D, "UU" )
MOAIProp2D* prop = state.GetLuaObject < MOAIProp2D >( 2 );
if ( !prop ) return 0;
if ( prop == self ) return 0;
self->AffirmPartition ();
self->mPartition->InsertProp ( *prop );
prop->ScheduleUpdate ();
return 0;
}
//----------------------------------------------------------------//
/** @name removeProp
@text Removes a prop from the layer's partition.
@in MOAILayer2D self
@in MOAIProp prop
@out nil
*/
int MOAILayer2D::_removeProp ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAILayer2D, "UU" )
MOAIProp2D* prop = state.GetLuaObject < MOAIProp2D >( 2 );
if ( !prop ) return 0;
if ( prop == self ) return 0;
if ( self->mPartition ) {
self->mPartition->RemoveProp ( *prop );
prop->ScheduleUpdate ();
}
return 0;
}
//----------------------------------------------------------------//
/** @name setBox2DWorld
@text Sets a Box2D world for debug drawing.
@in MOAILayer2D self
@in MOAIBox2DWorld world
@out nil
*/
int MOAILayer2D::_setBox2DWorld ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAILayer2D, "UU" )
#if USE_BOX2D
self->mBox2DWorld = state.GetLuaObject < MOAIBox2DWorld >( 2 );
#endif
return 0;
}
//----------------------------------------------------------------//
/** @name setCamera
@text Sets a camera transform. This is just a regular transform.
Its inverse is used as the view transform. If no camera
transform is set, the layer will render using the
identity transform.
@in MOAILayer2D self
@in MOAITransformBase camera
@out nil
*/
int MOAILayer2D::_setCamera ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAILayer2D, "UU" )
MOAITransformBase* camera = state.GetLuaObject < MOAITransformBase >( 2 );
if ( !camera ) return 0;
self->SetCamera ( camera );
return 0;
}
//----------------------------------------------------------------//
/** @name setCpSpace
@text Sets a Chipmunk space for debug drawing.
@in MOAILayer2D self
@in MOAICpSpace space
@out nil
*/
int MOAILayer2D::_setCpSpace ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAILayer2D, "UU" )
#if USE_CHIPMUNK
self->mCpSpace = state.GetLuaObject < MOAICpSpace >( 2 );
#endif
return 0;
}
//----------------------------------------------------------------//
/** @name setFrameBuffer
@text Attach a frame buffer. Layer will render to frame buffer
instead of the main view.
@in MOAILayer2D self
@in MOAITexture frameBuffer
@out nil
*/
int MOAILayer2D::_setFrameBuffer ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAILayer2D, "UU" )
MOAITexture* frameBuffer = state.GetLuaObject < MOAITexture >( 2 );
if ( !frameBuffer ) return 0;
self->mFrameBuffer = frameBuffer;
return 0;
}
//----------------------------------------------------------------//
/** @name setParallax
@text Sets the parallax scale for this layer. This is simply a
scalar applied to the view transform before rendering.
@in MOAILayer2D self
@in number xParallax
@in number yParallax
@out nil
*/
int MOAILayer2D::_setParallax ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAILayer2D, "UNN" )
self->mParallax.mX = state.GetValue < float >( 2, self->mParallax.mX );
self->mParallax.mY = state.GetValue < float >( 3, self->mParallax.mY );
return 0;
}
//----------------------------------------------------------------//
/** @name setPartition
@text Sets a partition for the layer to use. The layer will automatically
create a partition when the first prop is added if no partition
has been set.
@in MOAILayer2D self
@in MOAIPartition partition
@out nil
*/
int MOAILayer2D::_setPartition ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAILayer2D, "UU" )
MOAIPartition* partition = state.GetLuaObject < MOAIPartition >( 2 );
if ( !partition ) return 0;
self->SetPartition ( partition );
return 0;
}
//----------------------------------------------------------------//
/** @name setViewport
@text Set the layer's viewport.
@in MOAILayer2D self
@in MOAIViewport viewport
@out nil
*/
int MOAILayer2D::_setViewport ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAILayer2D, "UU" )
MOAIViewport* viewport = state.GetLuaObject < MOAIViewport >( 2 );
if ( !viewport ) return 0;
self->SetViewport ( viewport );
return 0;
}
//----------------------------------------------------------------//
/** @name showDebugLines
@text Display debug lines for props in this layer.
@in MOAILayer2D self
@opt bool showDebugLines Default value is 'true'.
@out nil
*/
int MOAILayer2D::_showDebugLines ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAILayer2D, "U" )
self->mShowDebugLines = state.GetValue < bool >( 2, true );
return 0;
}
//----------------------------------------------------------------//
/** @name wndToWorld
@text Transform a point from window space to world space.
@in MOAILayer2D self
@in number x
@in number y
@out number x
@out number y
*/
int MOAILayer2D::_wndToWorld ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAILayer2D, "UNN" )
USVec2D loc;
loc.mX = state.GetValue < float >( 2, 0.0f );
loc.mY = state.GetValue < float >( 3, 0.0f );
USAffine2D wndToWorld;
self->GetWndToWorldMtx ( wndToWorld );
wndToWorld.Transform ( loc );
lua_pushnumber ( state, loc.mX );
lua_pushnumber ( state, loc.mY );
return 2;
}
//----------------------------------------------------------------//
/** @name wndToWorld
@text Transform a point from world space to window space.
@in MOAILayer2D self
@in number x
@in number y
@out number x
@out number y
*/
int MOAILayer2D::_worldToWnd ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAILayer2D, "UNN" )
USVec2D loc;
loc.mX = state.GetValue < float >( 2, 0.0f );
loc.mY = state.GetValue < float >( 3, 0.0f );
USAffine2D worldToWnd;
self->GetWorldToWndMtx ( worldToWnd );
worldToWnd.Transform ( loc );
lua_pushnumber ( state, loc.mX );
lua_pushnumber ( state, loc.mY );
return 2;
}
//================================================================//
// MOAINode
//================================================================//
//----------------------------------------------------------------//
void MOAILayer2D::AffirmPartition () {
if ( !this->mPartition ) {
this->mPartition = new MOAIPartition ();
}
}
//----------------------------------------------------------------//
void MOAILayer2D::Draw () {
if ( !this->mViewport ) return;
MOAIViewport& viewport = *this->mViewport;
MOAIGfxDevice& gfxDevice = MOAIGfxDevice::Get ();
gfxDevice.ResetState ();
gfxDevice.SetFrameBuffer ( this->mFrameBuffer );
USRect viewportRect = viewport;
if ( !this->IsOffscreen ()) {
USMatrix4x4 mtx;
mtx.Init ( this->mLocalToWorldMtx );
mtx.Append (gfxDevice. GetWorldToWndMtx ( 1.0f, 1.0f ));
mtx.Transform ( viewportRect );
}
gfxDevice.SetViewport ( viewportRect );
USAffine2D camera;
this->GetCameraMtx ( camera );
gfxDevice.SetVertexTransform ( MOAIGfxDevice::VTX_VIEW_TRANSFORM, camera );
gfxDevice.SetVertexTransform ( MOAIGfxDevice::VTX_PROJ_TRANSFORM, viewport.GetProjMtx ());
if ( this->mShowDebugLines ) {
#if USE_CHIPMUNK
if ( this->mCpSpace ) {
this->mCpSpace->DrawDebug ();
gfxDevice.Flush ();
}
#endif
#if USE_BOX2D
if ( this->mBox2DWorld ) {
this->mBox2DWorld->DrawDebug ();
gfxDevice.Flush ();
}
#endif
}
gfxDevice.SetVertexTransform ( MOAIGfxDevice::VTX_WORLD_TRANSFORM );
gfxDevice.SetVertexTransform ( MOAIGfxDevice::VTX_VIEW_TRANSFORM, camera );
gfxDevice.SetVertexTransform ( MOAIGfxDevice::VTX_PROJ_TRANSFORM, viewport.GetProjMtx ());
if ( this->mPartition ) {
USQuad viewQuad = gfxDevice.GetViewQuad ();
USRect viewBounds = viewQuad.GetBounds ();
MOAIPartitionResultBuffer& buffer = MOAIPartitionResultMgr::Get ().GetBuffer ();
u32 totalResults = this->mPartition->GatherProps ( buffer, viewBounds, 0, MOAIProp::CAN_DRAW | MOAIProp::CAN_DRAW_DEBUG );
if ( !totalResults ) return;
// TODO: allow configurable sort
buffer.Sort ( MOAIPartitionResultBuffer::SORT_PRIORITY );
// render the sorted list
for ( u32 i = 0; i < totalResults; ++i ) {
MOAIProp* prop = buffer.GetResultUnsafe ( i );
prop->Draw ();
prop->DrawDebug ();
}
}
// render the debug lines
if ( this->mShowDebugLines ) {
MOAIDebugLines::Get ().Draw ();
}
gfxDevice.Flush ();
}
//----------------------------------------------------------------//
void MOAILayer2D::GetCameraMtx ( USAffine2D& camera ) {
if ( this->mCamera ) {
camera = this->mCamera->GetLocalToWorldMtx ();
camera.m [ USAffine2D::C2_R0 ] *= this->mParallax.mX;
camera.m [ USAffine2D::C2_R1 ] *= this->mParallax.mY;
camera.Inverse ();
}
else {
camera.Ident ();
}
}
//----------------------------------------------------------------//
float MOAILayer2D::GetFitting ( USRect& worldRect, float hPad, float vPad ) {
if ( !( this->mCamera && this->mViewport )) return 1.0f;
USRect viewRect = this->mViewport->GetRect ();
float hFit = ( viewRect.Width () - ( hPad * 2 )) / worldRect.Width ();
float vFit = ( viewRect.Height () - ( vPad * 2 )) / worldRect.Height ();
return ( hFit < vFit ) ? hFit : vFit;
}
//----------------------------------------------------------------//
u32 MOAILayer2D::GetLocalFrame ( USRect& frame ) {
if ( this->mViewport ) {
frame = this->mViewport->GetRect ();
return MOAIProp::BOUNDS_OK;
}
return MOAIProp::BOUNDS_EMPTY;
}
//----------------------------------------------------------------//
void MOAILayer2D::GetWndToWorldMtx ( USAffine2D& wndToWorld ) {
if ( this->mViewport ) {
USAffine2D camera;
this->GetCameraMtx ( camera );
wndToWorld = this->mViewport->GetWndToWorldMtx ( camera );
}
else {
wndToWorld.Ident ();
}
}
//----------------------------------------------------------------//
void MOAILayer2D::GetWorldToWndMtx ( USAffine2D& worldToWnd ) {
if ( this->mCamera && this->mViewport ) {
USAffine2D camera;
this->GetCameraMtx ( camera );
worldToWnd = this->mViewport->GetWorldToWndMtx ( camera );
}
else {
worldToWnd.Ident ();
}
}
//----------------------------------------------------------------//
bool MOAILayer2D::IsOffscreen () {
return this->mFrameBuffer ? this->mFrameBuffer->GetFrameBuffer () != 0 : false;
}
//----------------------------------------------------------------//
MOAILayer2D::MOAILayer2D () :
mParallax ( 1.0f, 1.0f ),
mShowDebugLines ( true ) {
RTTI_BEGIN
RTTI_EXTEND ( MOAIProp2D )
RTTI_END
this->SetMask ( MOAIProp::CAN_DRAW | MOAIProp::CAN_DRAW_DEBUG );
}
//----------------------------------------------------------------//
MOAILayer2D::~MOAILayer2D () {
}
//----------------------------------------------------------------//
void MOAILayer2D::RegisterLuaClass ( USLuaState& state ) {
MOAIProp2D::RegisterLuaClass ( state );
}
//----------------------------------------------------------------//
void MOAILayer2D::RegisterLuaFuncs ( USLuaState& state ) {
MOAIProp2D::RegisterLuaFuncs ( state );
luaL_Reg regTable [] = {
{ "clear", _clear },
{ "getFitting", _getFitting },
{ "getPartition", _getPartition },
{ "insertProp", _insertProp },
{ "removeProp", _removeProp },
{ "setBox2DWorld", _setBox2DWorld },
{ "setCamera", _setCamera },
{ "setCpSpace", _setCpSpace },
{ "setFrameBuffer", _setFrameBuffer },
{ "setParallax", _setParallax },
{ "setPartition", _setPartition },
{ "setViewport", _setViewport },
{ "showDebugLines", _showDebugLines },
{ "wndToWorld", _wndToWorld },
{ "worldToWnd", _worldToWnd },
{ NULL, NULL }
};
luaL_register ( state, 0, regTable );
}
//----------------------------------------------------------------//
STLString MOAILayer2D::ToString () {
STLString repr( MOAIProp2D::ToString () );
PRETTY_PRINT ( repr, mCamera )
PRETTY_PRINT ( repr, mViewport )
PRETTY_PRINT ( repr, mPartition )
return repr;
}
| [
"[email protected]",
"[email protected]",
"[email protected]",
"Patrick@agile.(none)"
]
| [
[
[
1,
8
],
[
11,
12
],
[
15,
15
],
[
17,
22
],
[
39,
118
],
[
120,
140
],
[
142,
171
],
[
173,
177
],
[
179,
202
],
[
223,
368
],
[
371,
371
],
[
374,
374
],
[
385,
386
],
[
390,
394
],
[
396,
401
],
[
403,
406
],
[
411,
412
],
[
415,
415
],
[
417,
417
],
[
420,
420
],
[
423,
424
],
[
427,
435
],
[
437,
446
],
[
449,
484
],
[
486,
498
],
[
500,
505
],
[
512,
539
],
[
541,
547
],
[
549,
571
]
],
[
[
9,
9
],
[
16,
16
],
[
203,
203
],
[
212,
222
],
[
548,
548
]
],
[
[
10,
10
],
[
13,
14
],
[
119,
119
],
[
141,
141
],
[
204,
211
],
[
369,
370
],
[
372,
373
],
[
375,
384
],
[
387,
389
],
[
395,
395
],
[
402,
402
],
[
407,
410
],
[
413,
414
],
[
416,
416
],
[
418,
419
],
[
421,
422
],
[
425,
426
],
[
436,
436
],
[
447,
448
],
[
485,
485
],
[
499,
499
],
[
506,
511
]
],
[
[
23,
38
],
[
172,
172
],
[
178,
178
],
[
540,
540
]
]
]
|
0a7fa3b815ecaff5b02b4af3cc0d71915a1e3689 | 105cc69f4207a288be06fd7af7633787c3f3efb5 | /HovercraftUniverse/HovercraftUniverse/RaceState.cpp | 6bed2b074f86ace27c18327c369e884fdefcff32 | []
| no_license | allenjacksonmaxplayio/uhasseltaacgua | 330a6f2751e1d6675d1cf484ea2db0a923c9cdd0 | ad54e9aa3ad841b8fc30682bd281c790a997478d | refs/heads/master | 2020-12-24T21:21:28.075897 | 2010-06-09T18:05:23 | 2010-06-09T18:05:23 | 56,725,792 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,284 | cpp | #include "RaceState.h"
#include "Lobby.h"
#include "Loader.h"
#include "ClientPreparationLoader.h"
#include "RacePlayer.h"
#include "PlayerSettings.h"
#include "RaceStateListener.h"
#include "GameEvent.h"
#include "GameEventParser.h"
#include "StateEvent.h"
#include "InitEvent.h"
#include "NetworkClient.h"
#include "Timing.h"
#include "Track.h"
#include "Entity.h"
#include "EntityManager.h"
#include "DedicatedServer.h"
#include "TrackInfoLoader.h"
#include "Finish.h"
#include "Start.h"
#include "Hovercraft.h"
#include "CheckPoint.h"
#include "CheckpointEvent.h"
#include <math.h>
#include "Havok.h"
#include "EntityMapping.h"
#include <OgreLogManager.h>
namespace HovUni {
RaceState::RaceState(Lobby* lobby, Loader* loader, Ogre::String track) :
NetworkEntity(0), mNumberPlayers(0), mState(0), mServer(true), mLobby(lobby), mLoader(loader), mTrackFilename(track),
mCountdown(-1), mCountdownInterval(5000), mCountdownIntervalLog2(20), mFinishID(-1), mRng(0), mIntroTime(0),
mPlayTime(0), mFinishTime(0) {
mState = new SystemState(this);
if (mLoader) {
mLoader->setRaceState(this);
}
// Read config values
mIntroTime = DedicatedServer::getConfig()->getValue<int> ("Server", "IntroTime", 5000);
mPlayTime = DedicatedServer::getConfig()->getValue<int> ("Server", "PlayTime", 900000);
mFinishTime = DedicatedServer::getConfig()->getValue<int> ("Server", "FinishTime", 30000);
// Add as network entity
networkRegister(NetworkIDManager::getServerSingletonPtr(), getClassName(), true);
mNode->dependsOn(lobby->getNetworkNode());
// Load track info and check players
TrackInfoLoader trackInfoLoader(mTrackFilename);
Track * trackEntity = trackInfoLoader.getTrack();
// Initial position
int initialPosition = 1;
if (trackEntity) {
Ogre::LogManager::getSingletonPtr()->getDefaultLog()->stream() << "Track " << trackEntity->getDisplayName()
<< " must have at least " << trackEntity->getMinimumPlayers() << " players and at most "
<< trackEntity->getMaximumPlayers() << "!";
unsigned int maxPlayers = (mLobby->getMaxPlayers() < trackEntity->getMaximumPlayers() ? mLobby->getMaxPlayers() : trackEntity->getMaximumPlayers());
unsigned int minPlayers = trackEntity->getMinimumPlayers();
// Create race players
const Lobby::playermap::list_type& playersettings = lobby->getPlayers();
for (Lobby::playermap::const_iterator it = playersettings.begin(); it != playersettings.end()
&& mPlayers.getPlayers().size() < maxPlayers; ++it) {
RacePlayer* rplayer = new RacePlayer(this, it->second, initialPosition++);
// Tell the clients to start
StartTrackEvent startEvent;
mLobby->sendEventDirect(startEvent, it->second->getConnID());
rplayer->getNetworkNode()->setOwner(it->first, true);
addPlayer(rplayer);
}
// Bots
int bots = 0;
if (mLobby->hasBots()) {
bots = maxPlayers - mPlayers.getPlayers().size();
} else if (minPlayers > mPlayers.getPlayers().size()) {
// The minimum amount of players is not reached so add bots anyway
bots = minPlayers - mPlayers.getPlayers().size();
}
const std::map<unsigned int, Ogre::String>& hovercrafts = EntityMapping::getInstance().getMap(EntityMapping::HOVERCRAFT);
const std::map<unsigned int, Ogre::String>& characters = EntityMapping::getInstance().getMap(EntityMapping::CHARACTER);
for (int i = 0; i < bots; ++i) {
PlayerSettings* settings = new PlayerSettings(mLobby, "Bot");
RacePlayer* rplayer = new RacePlayer(this, settings, initialPosition++);
addPlayer(rplayer);
// Set random hovercraft and character
unsigned int hov = 0;
unsigned int cha = 0;
randomSettingsForBot(hovercrafts, characters, hov, cha);
settings->setHovercraft(hov);
settings->setCharacter(cha);
}
}
}
RaceState::RaceState(Lobby* lobby, ClientPreparationLoader* loader, ZCom_BitStream* announcementdata, ZCom_ClassID id,
ZCom_Control* control) :
NetworkEntity(0), mNumberPlayers(0), mState(0), mServer(false), mLobby(lobby), mLoader(loader), mTrackFilename(
announcementdata->getString()), mCountdown(-1), mCountdownInterval(5000), mCountdownIntervalLog2(20), mFinishID(-1),
mRng(0), mIntroTime(0), mPlayTime(0), mFinishTime(0) {
mState = new SystemState(this);
if (mLoader) {
mLoader->setRaceState(this);
}
// Add as network entity
networkRegister(id, control);
}
RaceState::~RaceState() {
Ogre::LogManager::getSingleton().getDefaultLog()->stream() << "[RaceState]: Deleting RaceState";
// Delete all the players
for (playermap::iterator it = mPlayers.begin(); it != mPlayers.end();) {
if (it->second->isBot()) {
PlayerSettings* settings = it->second->getSettings();
it = removePlayer(it);
// Only delete settings on server because client will already take care of it
if (mServer) {
delete settings;
}
} else {
it = removePlayer(it);
}
}
// Delete the system state after all the players
delete mState;
mState = 0;
// Delete rng
delete mRng;
mRng = 0;
}
void RaceState::onFinish(Finish * finish, unsigned int playerid) {
if (mFinishID == -1) {
// finish checkpoint
std::vector<Entity*> checkpoints = EntityManager::getServerSingletonPtr()->getEntities(CheckPoint::CATEGORY);
for (unsigned int i = 0; i < checkpoints.size(); ++i) {
CheckPoint * checkpoint = dynamic_cast<CheckPoint *> (checkpoints[i]);
if (checkpoint->getNumber() >= mFinishID) {
mFinishID = checkpoint->getNumber() + 1;
}
}
std::cout << "finish ID is " << mFinishID << std::endl;
}
if (mCheckpointMapping[playerid] == mFinishID) {
// increase next checkpoint
updatePlayerCheckpoint(playerid);
// change state to finishing
if (mState->getState() == RACING) {
mState->newState(FINISHING);
}
// Needs to be after update player checkpoint because else the results can show wrong values
RacePlayer* player = getPlayer(playerid);
player->setFinished();
// finished!
std::cout << playerid << " finished!" << std::endl;
// disable controls for this player
// TODO (or maybe not?)
} else if (mCheckpointMapping[playerid] < mFinishID) {
// not yet finished!
std::cout << playerid << " reaches incorrect finish, skipped checkpoint " << mCheckpointMapping[playerid] << std::endl;
} else {
// already finished
std::cout << playerid << " already finished" << std::endl;
}
}
void RaceState::onCheckPoint(CheckPoint * checkpoint, unsigned int playerid) {
if (mCheckpointMapping[playerid] == checkpoint->getNumber()) {
// correct checkpoint
std::cout << playerid << " reaches correct checkpoint " << checkpoint->getNumber() << std::endl;
// increase next checkpoint
updatePlayerCheckpoint(playerid);
} else {
// incorrect checkpoint
std::cout << playerid << " reaches wrong checkpoint " << checkpoint->getNumber() << " (should be "
<< mCheckpointMapping[playerid] << ")" << std::endl;
}
}
void RaceState::onStart(Start * start, unsigned int playerid) {
if (mCheckpointMapping[playerid] == -1) {
// correct start
std::cout << playerid << " reaches start" << std::endl;
updatePlayerCheckpoint(playerid);
} else {
// already passed start!
std::cout << playerid << " reaches invalid start" << std::endl;
}
}
void RaceState::updatePlayerCheckpoint(unsigned int playerid) {
RacePlayer* player = getPlayer(playerid);
long timestamp = mState->mPlayTimer->elapsed();
player->addCheckpoint(mCheckpointMapping[playerid], timestamp);
calculatePlayerPosition(playerid);
sendEvent(CheckpointEvent(playerid, mCheckpointMapping[playerid], timestamp));
mCheckpointMapping[playerid]++;
}
void RaceState::calculatePlayerPosition(unsigned int playerid) {
unsigned int position = 1;
for (std::map<unsigned int, Ogre::int32>::const_iterator it = mCheckpointMapping.begin(); it != mCheckpointMapping.end(); ++it) {
// If the checkpoint of the other is greater than this one, they already passed this checkpoint
if (it->second > mCheckpointMapping[playerid]) {
++position;
}
}
// Remove the player from the list and insert it at the right position
mPlayerPositions.remove(playerid);
bool playerInserted = false;
unsigned int i = 1;
for (std::list<unsigned int>::iterator it = mPlayerPositions.begin(); it != mPlayerPositions.end(); ++it) {
// Since this player reaches a checkpoint, it can only move forward in position or stay equal
if ((i == position) && (*it != playerid)) {
// Position improved so previous value should be deleted
mPlayerPositions.insert(it, playerid);
playerInserted = true;
break;
}
++i;
}
if (!playerInserted) {
// Add player back to the end of list
mPlayerPositions.push_back(playerid);
}
// Update player positions
i = 1;
for (std::list<unsigned int>::iterator it = mPlayerPositions.begin(); it != mPlayerPositions.end(); ++it) {
getPlayer(*it)->setPosition(i);
++i;
}
}
void RaceState::randomSettingsForBot(const std::map<unsigned int, Ogre::String>& hovercrafts, const std::map<unsigned int,
Ogre::String>& characters, unsigned int& hovercraftKey, unsigned int& characterKey) {
if (!mRng) {
mRng = new boost::mt19937;
}
boost::uniform_int<> unifhov(0, hovercrafts.size() - 1);
boost::uniform_int<> unifcha(0, characters.size() - 1);
boost::variate_generator<boost::mt19937&, boost::uniform_int<> > randhov(*mRng, unifhov);
boost::variate_generator<boost::mt19937&, boost::uniform_int<> > randcha(*mRng, unifcha);
int hov = randhov();
int cha = randcha();
unsigned int i = 0;
for (std::map<unsigned int, Ogre::String>::const_iterator it = hovercrafts.begin(); it != hovercrafts.end(); ++it) {
if (i == hov) {
hovercraftKey = 0;//it->first;
//TODO IK HEB DIT HIER VAST OP 0 GEZET, BOTS KUNNEN NIET ZO GOED OVERWEG MET DE ANDERE HOVERCRAFTS (Dirk)
}
++i;
}
i = 0;
for (std::map<unsigned int, Ogre::String>::const_iterator it = characters.begin(); it != characters.end(); ++it) {
if (i == hov) {
characterKey = it->first;
}
++i;
}
}
std::string RaceState::getClassName() {
return "RaceState";
}
void RaceState::process() {
processEvents(0.0f);
mState->update();
for (playermap::iterator it = mPlayers.begin(); it != mPlayers.end();) {
unsigned int id = it->first;
RacePlayer* player = it->second;
// Check if this settings wasn't deleted in the mean time
if (player->isDeleted()) {
it = removePlayer(it);
} else {
player->processEvents(0.0f);
++it;
}
}
}
RaceState::playermap::iterator RaceState::removePlayer(playermap::iterator i) {
// Remove the ID from the waiting list
mState->eraseFromList(i->first);
// Decrease the number of players
--mNumberPlayers;
return mPlayers.removePlayerByIterator(i);
}
void RaceState::addPlayer(RacePlayer* player, bool ownPlayer) {
mPlayers.addPlayer(player->getSettings()->getID(), player, ownPlayer);
mCheckpointMapping[player->getSettings()->getID()] = 0;
mPlayerPositions.push_back(player->getSettings()->getID());
Ogre::LogManager::getSingleton().getDefaultLog()->stream() << "[RaceState]: Inserting new RacePlayer";
if (ownPlayer) {
Ogre::LogManager::getSingleton().getDefaultLog()->stream() << "[RaceState]: Received own player object";
}
if ((mState->getState() == INITIALIZING)) {
if (mServer) {
++mNumberPlayers;
} else {
onInitialized();
}
}
}
void RaceState::removePlayer(unsigned int id) {
removePlayer(mPlayers.find(id));
}
Listenable<RaceStateListener>::list_type& RaceState::getListeners() {
return mListeners;
}
RaceState::States RaceState::getState() const {
return mState->getState();
}
bool RaceState::isDone() const {
return (mServer ? (mState->getState() == CLEANUP) && mState->mTimer->elapsed() > 3000 : isDeleted());
}
void RaceState::onInitialized() {
if ((mState->getState() == INITIALIZING) && (mPlayers.getPlayers().size() == mNumberPlayers)) {
mState->sendEvent(INITIALIZED);
}
}
void RaceState::onLoaded() {
if (mState->getState() == LOADING) {
// Send event to server indicating that the loading finished
mState->sendEvent(LOADED);
}
}
void RaceState::setAnnouncementData(ZCom_BitStream* stream) {
stream->addString(mTrackFilename.c_str());
}
void RaceState::parseEvents(eZCom_Event type, eZCom_NodeRole remote_role, ZCom_ConnID conn_id, ZCom_BitStream* stream,
float timeSince) {
if (type == eZCom_EventUser) {
GameEventParser p;
GameEvent* gEvent = p.parse(stream);
eZCom_NodeRole role = mNode->getRole();
// Check for an init event if this object is just created
InitEvent* init = dynamic_cast<InitEvent*> (gEvent);
if (init) {
ZCom_BitStream* state = init->getStream();
mNumberPlayers = state->getInt(8);
}
StateEvent* newState = dynamic_cast<StateEvent*> (gEvent);
if (newState) {
if (role == eZCom_RoleOwner || role == eZCom_RoleProxy) {
mState->newState((States) newState->getState());
} else {
mState->newEvent((Events) newState->getState(), mLobby->getPlayerIDfromConnectionID(conn_id));
}
}
CheckpointEvent* checkpoint = dynamic_cast<CheckpointEvent*> (gEvent);
if (checkpoint) {
RacePlayer* player = getPlayer(checkpoint->getUser());
player->addCheckpoint(checkpoint->getCheckpoint(), checkpoint->getTimestamp());
}
delete gEvent;
}
// A new client received this object so send current state
if (type == eZCom_EventInit && mNode->getRole() == eZCom_RoleAuthority) {
ZCom_BitStream* state = new ZCom_BitStream();
state->addInt(mNumberPlayers, 8);
sendEventDirect(InitEvent(state), conn_id);
}
}
void RaceState::setupReplication() {
mNode->addReplicationInt(&mNumberPlayers, 8, false, ZCOM_REPFLAG_MOSTRECENT, ZCOM_REPRULE_AUTH_2_ALL);
mNode->addReplicationInt(&mCountdown, mCountdownIntervalLog2, false, ZCOM_REPFLAG_MOSTRECENT, ZCOM_REPRULE_AUTH_2_ALL, 250,
1000);
}
RaceState::SystemState::SystemState(RaceState* racestate) :
mRaceState(racestate), mCurrentState(INITIALIZING), mStartOfState(false), mTimer(0), mPlayTimer(0) {
if (mRaceState->mServer) {
setWaitingList();
}
}
RaceState::SystemState::~SystemState() {
delete mTimer;
mTimer = 0;
delete mPlayTimer;
mPlayTimer = 0;
}
void RaceState::SystemState::update() {
if (mRaceState->mServer) {
switch (mCurrentState) {
case INTRO:
if (mTimer->elapsed() >= mRaceState->mIntroTime) {
newState(COUNTDOWN);
}
case COUNTDOWN:
if (mTimer->elapsed() >= mRaceState->mCountdownInterval) {
newState(RACING);
Entity::setControlsActive();
} else {
mRaceState->mCountdown = mRaceState->mCountdownInterval - mTimer->elapsed();
}
break;
case RACING:
if (mTimer->elapsed() >= mRaceState->mPlayTime) {
newState(FINISHING);
}
break;
case FINISHING:
if (mTimer->elapsed() >= mRaceState->mFinishTime) {
newState(CLEANUP);
Entity::setControlsInactive();
} else {
mRaceState->mCountdown = mRaceState->mFinishTime - mTimer->elapsed();
//std::cout << "SERVER TIMEOUT: " << mRaceState->mCountdown << std::endl;
}
break;
default:
break;
}
}
}
RaceState::States RaceState::SystemState::getState() const {
return mCurrentState;
}
void RaceState::SystemState::newState(States state) {
Ogre::LogManager::getSingleton().getDefaultLog()->stream() << "[RaceState]: New state is " << state;
mCurrentState = state;
if (mRaceState->mServer) {
// Send the event to the clients
StateEvent newState((unsigned int) state);
mRaceState->sendEvent(newState);
// Do the appropriate action for this state
switch (state) {
case LOADING:
mStartOfState = true;
break;
case INTRO:
mTimer = new Timing();
break;
case COUNTDOWN:
mTimer->restart();
break;
case RACING:
mPlayTimer = new Timing();
mTimer->restart();
break;
case FINISHING:
mTimer->restart();
break;
case CLEANUP:
mTimer->restart();
{
Havok::stop();
std::vector<Entity*> ents = EntityManager::getServerSingletonPtr()->getEntities(EntityManager::ALL);
for (std::vector<Entity*>::iterator i = ents.begin(); i != ents.end(); i++) {
EntityManager::getServerSingletonPtr()->releaseEntity((*i)->getName());
delete (*i);
}
}
break;
default:
break;
}
}
// Client
else {
// Do the appropriate action for this state
switch (state) {
case LOADING:
onLoading();
break;
case CLEANUP: {
//TODO MUST BE DONE ONLY WITH DEDICATED SERVER
/*std::vector<Entity*> ents = EntityManager::getServerSingletonPtr()->getEntities(EntityManager::ALL);
for ( std::vector<Entity*>::iterator i = ents.begin(); i != ents.end(); i++ ){
EntityManager::getServerSingletonPtr()->releaseEntity((*i)->getName());
delete (*i);
}*/
}
break;
default:
break;
}
// Notify the listeners
for (listener_iterator i = mRaceState->listenersBegin(); i != mRaceState->listenersEnd(); ++i) {
(*i)->onStateChange(mCurrentState);
}
}
}
void RaceState::SystemState::newEvent(Events events, unsigned int id) {
Ogre::LogManager::getSingleton().getDefaultLog()->stream() << "[RaceState]: New event " << events << " from " << id;
// Check if the event is correct for the current state
bool correct = false;
if (((mCurrentState == INITIALIZING) && (events == INITIALIZED)) || ((mCurrentState == LOADING) && (events == STATECHANGED))
|| ((mCurrentState == LOADING) && (events == LOADED))) {
correct = true;
}
if (correct) {
eraseFromList(id);
}
}
void RaceState::SystemState::sendEvent(Events events) {
StateEvent newState((unsigned int) events);
ZCom_BitStream* stream = new ZCom_BitStream();
newState.serialize(stream);
ZCom_ConnID id = ((NetworkClient*) mRaceState->mNode->getControl())->getConnectionID();
mRaceState->mNode->sendEventDirect(eZCom_ReliableOrdered, stream, id);
Ogre::LogManager::getSingleton().getDefaultLog()->stream() << "[RaceState]: sent " << events << " event";
}
void RaceState::SystemState::onLoading() {
if (mRaceState->mServer) {
// Load the track on the server
mRaceState->mLoader->load(mRaceState->mTrackFilename);
} else {
sendEvent(STATECHANGED);
// Start waiting for loading the entities
((ClientPreparationLoader*) mRaceState->mLoader)->registerLoader(mRaceState->mTrackFilename);
}
}
void RaceState::SystemState::setWaitingList() {
if (mRaceState->mServer) {
mWaitingList.clear();
for (playermap::const_iterator it = mRaceState->mPlayers.begin(); it != mRaceState->mPlayers.end(); ++it) {
if (!it->second->isBot()) {
mWaitingList.insert(it->first);
}
}
}
}
void RaceState::SystemState::eraseFromList(unsigned int id) {
mWaitingList.erase(id);
if (mWaitingList.empty()) {
switch (mCurrentState) {
case INITIALIZING:
setWaitingList();
newState(LOADING);
break;
case LOADING:
if (mStartOfState) {
mStartOfState = false;
setWaitingList();
onLoading();
} else {
newState(INTRO);
}
break;
default:
break;
}
}
}
std::ostream& operator<<(std::ostream& os, const RaceState::States& state) {
switch (state) {
case RaceState::INITIALIZING:
os << "INITIALIZING";
break;
case RaceState::LOADING:
os << "LOADING";
break;
case RaceState::INTRO:
os << "INTRO";
break;
case RaceState::COUNTDOWN:
os << "COUNTDOWN";
break;
case RaceState::RACING:
os << "RACING";
break;
case RaceState::FINISHING:
os << "FINISHING";
break;
case RaceState::CLEANUP:
os << "CLEANUP";
break;
default:
os << state;
break;
}
return os;
}
std::ostream& operator<<(std::ostream& os, const RaceState::Events& events) {
switch (events) {
case RaceState::INITIALIZED:
os << "INITIALIZED";
break;
case RaceState::LOADED:
os << "LOADED";
break;
case RaceState::STATECHANGED:
os << "STATECHANGED";
break;
default:
os << events;
break;
}
return os;
}
}
| [
"nick.defrangh@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c",
"berghmans.olivier@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c",
"kristof.overdulve@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c",
"tobias.vanbladel@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c",
"pintens.pieterjan@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c",
"dirk.delahaye@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c"
]
| [
[
[
1,
1
],
[
29,
31
],
[
34,
34
],
[
41,
41
],
[
112,
112
],
[
124,
124
],
[
425,
425
],
[
462,
464
]
],
[
[
2,
13
],
[
17,
17
],
[
23,
24
],
[
27,
28
],
[
32,
33
],
[
35,
40
],
[
42,
50
],
[
54,
57
],
[
59,
61
],
[
63,
104
],
[
106,
111
],
[
113,
123
],
[
125,
152
],
[
157,
157
],
[
164,
164
],
[
167,
167
],
[
172,
178
],
[
191,
191
],
[
196,
196
],
[
199,
200
],
[
204,
204
],
[
208,
208
],
[
215,
278
],
[
281,
287
],
[
289,
381
],
[
383,
385
],
[
387,
406
],
[
408,
424
],
[
426,
447
],
[
449,
460
],
[
465,
505
],
[
509,
509
],
[
516,
536
],
[
538,
549
],
[
551,
553
],
[
556,
564
],
[
567,
570
],
[
572,
650
],
[
653,
662
],
[
664,
669
]
],
[
[
14,
14
],
[
18,
18
],
[
51,
51
],
[
53,
53
],
[
58,
58
],
[
62,
62
]
],
[
[
15,
16
],
[
105,
105
],
[
153,
156
],
[
158,
163
],
[
165,
166
],
[
168,
171
],
[
179,
188
],
[
192,
195
],
[
197,
198
],
[
201,
201
],
[
205,
207
],
[
209,
212
],
[
448,
448
],
[
461,
461
]
],
[
[
19,
22
],
[
25,
26
],
[
52,
52
],
[
189,
190
],
[
202,
203
],
[
213,
214
],
[
288,
288
],
[
506,
508
],
[
510,
515
],
[
537,
537
]
],
[
[
279,
280
],
[
382,
382
],
[
386,
386
],
[
407,
407
],
[
550,
550
],
[
554,
555
],
[
565,
566
],
[
571,
571
],
[
651,
652
],
[
663,
663
]
]
]
|
1d2a9b4967bf4f06c310acbc288a1ea67a7af5df | c2153dcfa8bcf5b6d7f187e5a337b904ad9f91ac | /depends/ClanLib/src/Core/XML/dom_processing_instruction.cpp | 7f0b90fd4c054c0dbd78b441ae7285319253bd45 | []
| no_license | ptrefall/smn6200fluidmechanics | 841541a26023f72aa53d214fe4787ed7f5db88e1 | 77e5f919982116a6cdee59f58ca929313dfbb3f7 | refs/heads/master | 2020-08-09T17:03:59.726027 | 2011-01-13T22:39:03 | 2011-01-13T22:39:03 | 32,448,422 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,531 | cpp | /*
** ClanLib SDK
** Copyright (c) 1997-2010 The ClanLib Team
**
** This software is provided 'as-is', without any express or implied
** warranty. In no event will the authors be held liable for any damages
** arising from the use of this software.
**
** Permission is granted to anyone to use this software for any purpose,
** including commercial applications, and to alter it and redistribute it
** freely, subject to the following restrictions:
**
** 1. The origin of this software must not be misrepresented; you must not
** claim that you wrote the original software. If you use this software
** in a product, an acknowledgment in the product documentation would be
** appreciated but is not required.
** 2. Altered source versions must be plainly marked as such, and must not be
** misrepresented as being the original software.
** 3. This notice may not be removed or altered from any source distribution.
**
** Note: Some of the libraries ClanLib may link to may have additional
** requirements or restrictions.
**
** File Author(s):
**
** Magnus Norddahl
*/
#include "precomp.h"
#include "API/Core/XML/dom_processing_instruction.h"
#include "API/Core/XML/dom_document.h"
#include "dom_node_generic.h"
/////////////////////////////////////////////////////////////////////////////
// CL_DomProcessingInstruction construction:
CL_DomProcessingInstruction::CL_DomProcessingInstruction()
{
}
CL_DomProcessingInstruction::CL_DomProcessingInstruction(CL_DomDocument &doc, const CL_DomString &target, const CL_DomString &data)
: CL_DomNode(doc, PROCESSING_INSTRUCTION_NODE)
{
set_node_value(data);
}
CL_DomProcessingInstruction::CL_DomProcessingInstruction(const CL_SharedPtr<CL_DomNode_Generic> &impl) : CL_DomNode(impl)
{
}
CL_DomProcessingInstruction::~CL_DomProcessingInstruction()
{
}
/////////////////////////////////////////////////////////////////////////////
// CL_DomProcessingInstruction attributes:
CL_DomString CL_DomProcessingInstruction::get_target() const
{
return CL_DomString();
}
CL_DomString CL_DomProcessingInstruction::get_data() const
{
return CL_DomString();
}
void CL_DomProcessingInstruction::set_data(const CL_DomString &data)
{
}
/////////////////////////////////////////////////////////////////////////////
// CL_DomProcessingInstruction operations:
/////////////////////////////////////////////////////////////////////////////
// CL_DomProcessingInstruction implementation:
| [
"[email protected]@c628178a-a759-096a-d0f3-7c7507b30227"
]
| [
[
[
1,
76
]
]
]
|
db7ed7c9f8790e82802b9eac30932f7816a5916d | 41371839eaa16ada179d580f7b2c1878600b718e | /SPOJ/seletivas/CONTAGEM.cpp | ac265949707f11a55e4279be73cd1b8bcc618c81 | []
| no_license | marinvhs/SMAS | 5481aecaaea859d123077417c9ee9f90e36cc721 | 2241dc612a653a885cf9c1565d3ca2010a6201b0 | refs/heads/master | 2021-01-22T16:31:03.431389 | 2009-10-01T02:33:01 | 2009-10-01T02:33:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 515 | cpp | #include <cstdio>
long long c;
char word[60];
void run(char s, int k, long long cost){
if(s == 'q')
switch(word[k]){
case 0: c += cost; return;
default: run('q',k+1,(cost<<1)); break;
}
else
switch(word[k]){
case 0: return;
case 'a': run('p',k+1,cost); break;
case 'b':
run('p',k+1,cost);
run('q',k+1,cost);
break;
}
}
int main(void){
for(int i = 1; gets(word); i++){
c = 0;
run('p',0,1);
printf("Palavra %d\n%lld\n\n",i,c);
}
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
28
]
]
]
|
1a3a166d88ee8f67f9fa904a6d53880e6e01d005 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/ptr_container/ptr_array.hpp | b96fa029dbe9448e13981f27948eb1283f64dd8e | [
"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 | 6,870 | hpp | //
// Boost.Pointer Container
//
// Copyright Thorsten Ottosen 2003-2005. 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)
//
// For more information, see http://www.boost.org/libs/ptr_container/
//
#ifndef BOOST_PTR_CONTAINER_PTR_ARRAY_HPP
#define BOOST_PTR_CONTAINER_PTR_ARRAY_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif
#include <boost/array.hpp>
#include <boost/static_assert.hpp>
#include <boost/ptr_container/ptr_sequence_adapter.hpp>
namespace boost
{
namespace ptr_container_detail
{
template
<
class T,
size_t N,
class Allocator = int // dummy
>
class ptr_array_impl : public boost::array<T,N>
{
public:
typedef Allocator allocator_type;
ptr_array_impl( Allocator a = Allocator() )
{
this->assign( 0 );
}
ptr_array_impl( size_t, T*, Allocator a = Allocator() )
{
this->assign( 0 );
}
};
}
template
<
class T,
size_t N,
class CloneAllocator = heap_clone_allocator
>
class ptr_array : public
ptr_sequence_adapter< T,
ptr_container_detail::ptr_array_impl<void*,N>,
CloneAllocator >
{
private:
typedef ptr_sequence_adapter< T,
ptr_container_detail::ptr_array_impl<void*,N>,
CloneAllocator >
base_class;
typedef BOOST_DEDUCED_TYPENAME remove_nullable<T>::type U;
typedef ptr_array<T,N,CloneAllocator>
this_type;
ptr_array( const this_type& );
void operator=( const this_type& );
public:
typedef std::size_t size_type;
typedef U* value_type;
typedef U* pointer;
typedef U& reference;
typedef const U& const_reference;
typedef BOOST_DEDUCED_TYPENAME base_class::auto_type
auto_type;
public: // constructors
ptr_array() : base_class()
{ }
ptr_array( std::auto_ptr<this_type> r )
: base_class( r ) { }
void operator=( std::auto_ptr<this_type> r )
{
base_class::operator=(r);
}
std::auto_ptr<this_type> release()
{
std::auto_ptr<this_type> ptr( new this_type );
this->swap( *ptr );
return ptr;
}
std::auto_ptr<this_type> clone() const
{
std::auto_ptr<this_type> pa( new this_type );
for( size_t i = 0; i != N; ++i )
{
if( ! is_null(i) )
pa->replace( i, CloneAllocator::allocate_clone( (*this)[i] ) );
}
return pa;
}
private: // hide some members
using base_class::insert;
using base_class::erase;
using base_class::push_back;
using base_class::push_front;
using base_class::pop_front;
using base_class::pop_back;
using base_class::transfer;
using base_class::get_allocator;
public: // compile-time interface
template< size_t idx >
auto_type replace( U* r ) // strong
{
BOOST_STATIC_ASSERT( idx < N );
this->enforce_null_policy( r, "Null pointer in 'ptr_array::replace()'" );
auto_type res( static_cast<U*>( this->c_private()[idx] ) ); // nothrow
this->c_private()[idx] = r; // nothrow
return move(res); // nothrow
}
template< size_t idx, class V >
auto_type replace( std::auto_ptr<V> r )
{
return replace<idx>( r.release() );
}
auto_type replace( size_t idx, U* r ) // strong
{
this->enforce_null_policy( r, "Null pointer in 'ptr_array::replace()'" );
auto_type ptr( r );
BOOST_PTR_CONTAINER_THROW_EXCEPTION( idx >= N, bad_index,
"'replace()' aout of bounds" );
auto_type res( static_cast<U*>( this->c_private()[idx] ) ); // nothrow
this->c_private()[idx] = ptr.release(); // nothrow
return move(res); // nothrow
}
template< class V >
auto_type replace( size_t idx, std::auto_ptr<V> r )
{
return replace( idx, r.release() );
}
using base_class::at;
template< size_t idx >
T& at()
{
BOOST_STATIC_ASSERT( idx < N );
return (*this)[idx];
}
template< size_t idx >
const T& at() const
{
BOOST_STATIC_ASSERT( idx < N );
return (*this)[idx];
}
bool is_null( size_t idx ) const
{
return base_class::is_null(idx);
}
template< size_t idx >
bool is_null() const
{
BOOST_STATIC_ASSERT( idx < N );
return this->c_private()[idx] == 0;
}
public: // serialization
template< class Archive >
void save( Archive& ar, const unsigned ) const
{
this->save_helper( ar );
}
template< class Archive >
void load( Archive& ar, const unsigned ) // basic
{
for( size_type i = 0u; i != N; ++i )
{
//
// Remark: pointers are not tracked,
// so we need not call ar.reset_object_address(v, u)
//
T* p;
ar & p;
this->replace( i, p );
}
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
};
//////////////////////////////////////////////////////////////////////////////
// clonability
template< typename T, size_t size, typename CA >
inline ptr_array<T,size,CA>* new_clone( const ptr_array<T,size,CA>& r )
{
return r.clone().release();
}
/////////////////////////////////////////////////////////////////////////
// swap
template< typename T, size_t size, typename CA >
inline void swap( ptr_array<T,size,CA>& l, ptr_array<T,size,CA>& r )
{
l.swap(r);
}
}
#endif
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
239
]
]
]
|
4e14eee501d1799002851065e6fb5a407d483a3a | 3449de09f841146a804930f2a51ccafbc4afa804 | /C++/FluidSystem/src/data10.cpp | 12225fc1c75c2b6f0597b09a21778cc34953cad0 | []
| no_license | davies/daviescode | 0c244f4aebee1eb909ec3de0e4e77db3a5bbacee | bb00ee0cfe5b7d5388485c59211ebc9ba2d6ecbd | refs/heads/master | 2020-06-04T23:32:27.360979 | 2007-08-19T06:31:49 | 2007-08-19T06:31:49 | 32,641,672 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 216 | cpp | #include "stdafx.h"
#include <algorithm>
#include <comdef.h>
#include <comutil.h>
#include "simu.h"
#include "data.h"
#include "excel10.h"
using namespace EXCEL10;
#define EXCEL10
#include "data_cpp.h" | [
"davies.liu@32811f3b-991a-0410-9d68-c977761b5317"
]
| [
[
[
1,
13
]
]
]
|
d778298588b801e2357c87019c728261cf55f7fa | f13f46fbe8535a7573d0f399449c230a35cd2014 | /JelloMan/FileNotFoundException.cpp | 8e7b3e7b2027e46fe087c924bd4e96d577bbe3f5 | []
| no_license | fangsunjian/jello-man | 354f1c86edc2af55045d8d2bcb58d9cf9b26c68a | 148170a4834a77a9e1549ad3bb746cb03470df8f | refs/heads/master | 2020-12-24T16:42:11.511756 | 2011-06-14T10:16:51 | 2011-06-14T10:16:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 272 | cpp | #include "FileNotFoundException.h"
using namespace exceptions;
FileNotFoundException::FileNotFoundException(): m_Message(_T(""))
{
}
FileNotFoundException::FileNotFoundException(const tstring& filename): m_Message(_T("File ") + filename + _T(" not found!"))
{
} | [
"bastian.damman@0fb7bab5-1bf9-c5f3-09d9-7611b49293d6"
]
| [
[
[
1,
10
]
]
]
|
680b7259094e03a42c7437e8e1d7cfc9e84d7ebe | 38926bfe477f933a307f51376dd3c356e7893ffc | /Source/GameDLL/NanoSuit.h | acba622fc12bbd284cbc9d43641b53809f6a639e | []
| no_license | richmondx/dead6 | b0e9dd94a0ebb297c0c6e9c4f24c6482ef4d5161 | 955f76f35d94ed5f991871407f3d3ad83f06a530 | refs/heads/master | 2021-12-05T14:32:01.782047 | 2008-01-01T13:13:39 | 2008-01-01T13:13:39 | null | 0 | 0 | null | null | null | null | ISO-8859-3 | C++ | false | false | 8,112 | h | /*************************************************************************
Crytek Source File.
Copyright (C), Crytek Studios, 2001-2004.
-------------------------------------------------------------------------
$Id$
$DateTime$
Description: Implements the Nanosuit.
-------------------------------------------------------------------------
History:
- 22:11:2005: Created by Filippo De Luca
- 31:01:2006: taken over by Jan Müller
*************************************************************************/
#ifndef __NANOSUIT_H__
#define __NANOSUIT_H__
#if _MSC_VER > 1000
# pragma once
#endif
static const float NANOSUIT_ENERGY = 200.0f;
static const float NANOSUIT_HEALTH_REGEN_INTERVAL = 1.0f;
enum ENanoSlot
{
NANOSLOT_SPEED = 0,
NANOSLOT_STRENGTH,
NANOSLOT_MEDICAL,
NANOSLOT_ARMOR,
//
NANOSLOT_LAST
};
// marcok: if you change this, also change g_USNanoMats and g_AsianNanoMats in nanosuit.cpp
enum ENanoMode
{
NANOMODE_SPEED = 0,
NANOMODE_STRENGTH,
NANOMODE_CLOAK,
NANOMODE_DEFENSE,
NANOMODE_INVULNERABILITY,
NANOMODE_DEFENSE_HIT_REACTION,
//
NANOMODE_LAST
};
enum ENanoCloakMode
{
CLOAKMODE_CHAMELEON = 1,
CLOAKMODE_REFRACTION,
CLOAKMODE_REFRACTION_TEMPERATURE
};
enum ENanoSound
{
NO_SOUND = 0,
SPEED_SOUND,
SPEED_IN_WATER_SOUND,
SPEED_SOUND_STOP,
SPEED_IN_WATER_SOUND_STOP,
STRENGTH_SOUND,
STRENGTH_LIFT_SOUND,
STRENGTH_THROW_SOUND,
STRENGTH_JUMP_SOUND,
STRENGTH_MELEE_SOUND,
MEDICAL_SOUND,
ARMOR_SOUND,
DROP_VS_THROW_SOUND,
ESound_SuitStrengthActivate,
ESound_SuitSpeedActivate,
ESound_SuitArmorActivate,
ESound_SuitCloakActivate,
ESound_SuitCloakFeedback,
ESound_GBootsActivated,
ESound_GBootsDeactivated,
ESound_ZeroGThruster,
ESound_GBootsLanded,
ESound_FreeFall,
ESound_ColdBreath,
ESound_AISuitHumming,
ESound_AISuitCloakFeedback,
ESound_Suit_Last
};
enum ENanoAction
{
eNA_None,
eNA_Jump,
eNA_Forward,
eNA_Backward,
eNA_Sprint,
eNA_Cloak,
eNA_ArmorCharge,
eNA_Crouch,
eNA_Melee,
eNA_Skin,
};
struct SNanoSlot
{
float desiredVal;
float realVal;
SNanoSlot()
{
desiredVal=0.0f;
realVal=0.0f;
};
};
class CNanoSuit;
struct SPlayerStats;
struct SNanoCloak
{
friend class CNanoSuit;
//
SNanoCloak()
{
Reset();
}
void Reset()
{
//default is normal mode
m_mode = CLOAKMODE_REFRACTION;
m_active = false;
m_energyCost = 6.0f; //this stuff is set from BasicActor.lua
m_healthCost = 0.0f;
m_visualDamp = 0.5f;
m_soundDamp = 0.5f;
m_heatDamp = 1.0f;
m_HUDMessage.clear();
}
//
//0 == cloak off, 1/2/3 == cloak mode 1, 2 or 3 (normal,alien tech,temperature camo)
ILINE uint8 GetState() const {return m_mode*m_active;}
ILINE float GetVisualDamp() const {return m_active?m_visualDamp:1.0f;}
ILINE float GetSoundDamp() const {return m_active?m_soundDamp:1.0f;}
ILINE float GetHeatDamp() const {return m_active?m_heatDamp:1.0f;}
ILINE bool IsActive() const { return m_active; }
ILINE void SetType(ENanoCloakMode mode) { m_mode = mode; }
ILINE ENanoCloakMode GetType() const { return m_mode; }
void GetMemoryStatistics(ICrySizer * s)
{
s->Add(m_HUDMessage);
}
private:
void Update(CNanoSuit *pNano);
private:
bool m_active;
//1, 2 or 3 (normal,alien tech,temperature camo)
ENanoCloakMode m_mode;
float m_energyCost;//points per sec
float m_healthCost;//health points per sec
float m_visualDamp;//how much visibility
float m_soundDamp;//how much of the AI sound is emitted
float m_heatDamp;//alien visibility
string m_HUDMessage;
};
class CPlayer;
class CNanoSuit
{
public:
struct INanoSuitListener
{
virtual void ModeChanged(ENanoMode mode) = 0; // nanomode
virtual void EnergyChanged(float energy) = 0; // energy
};
// nanosuit material to apply to player models when the mode changes
struct SNanoMaterial
{
IMaterial* body;
IMaterial* helmet;
IMaterial* arms;
SNanoMaterial() : body(0), helmet(0), arms(0){}
};
static SNanoMaterial* GetNanoMaterial(ENanoMode mode, bool bAsian=false);
static bool AssignNanoMaterialToEntity(IEntity* pEntity, SNanoMaterial* pNanoMaterial);
CNanoSuit();
~CNanoSuit();
void Activate(bool activate, float activationTime = 0.0f);
void ActivateMode(ENanoMode mode, bool active);
void SetModeDefect(ENanoMode mode, bool defect);
bool IsActive() const { return m_active; }
bool IsModeActive(ENanoMode mode) const { return (m_featureMask & (1<<mode))?true:false; }
void Init(CPlayer *owner) { Reset(owner); }
void Reset(CPlayer *owner);
void Update(float frameTime);
void Serialize( TSerialize ser, unsigned aspects );
void GetMemoryStatistics(ICrySizer * s);
bool Tap(ENanoAction nanoAction);
bool AttemptAction(ENanoAction nanoAction);
void ConsumeAction();
ENanoAction PendingAction() const { return m_pendingAction; }
void Death();
void Hit(int damage);
//setting
void SetSuitEnergy(float value, bool playerInitiated = false);
bool SetMode(ENanoMode mode, bool forceUpdate = false);
void SetCloakLevel(ENanoCloakMode mode); // currently 0 - 3
void SetParams(SmartScriptTable &rTable,bool resetFirst);
void SetInvulnerability(bool invulnerable);
void SetInvulnerabilityTimeout(float timeout);
bool IsInvulnerable() const { return m_invulnerable; };
//getting
ENanoMode GetMode() const { return m_currentMode; };
float GetSlotValue(ENanoSlot slot,bool desired=false) const;
bool GetSoundIsPlaying(ENanoSound sound) const;
bool OnComboSpot() { return (m_energy > 0.1f * NANOSUIT_ENERGY && m_energy < 0.3f * NANOSUIT_ENERGY)?true:false; }
void DeactivateSuit(float time);
ILINE float GetSuitEnergy() { return m_energy; }
ILINE float GetEnergyRechargeRate() { return m_energyRechargeRate; }
ILINE float GetHealthRegenRate() { return m_healthRegenRate; }
ILINE const CPlayer* GetOwner() const { return m_pOwner; }
ILINE const SNanoCloak *GetCloak() { return &m_cloak; }
ILINE bool IsNightVisionEnabled() const { return (m_bNightVisionEnabled && m_active); };
ILINE void EnableNightVision(bool enable) { m_bNightVisionEnabled=enable; };
//get sprinting multiplier for ground movement
float GetSprintMultiplier(bool strafing);
void SetCloak(bool on, bool force=false);
//set energy back to max
void ResetEnergy();
//plays an ENanoSound
void PlaySound(ENanoSound sound, float param = 1.0f, bool stopSound = false);
void SelectSuitMaterial();
// listener
void AddListener(INanoSuitListener* pListener);
void RemoveListener(INanoSuitListener* pListener);
private:
void Precache();
void Balance(float energy);
bool SetAllSlots(float armor, float strength, float speed);
int GetButtonFromMode(ENanoMode mode);
void UpdateSprinting(float &recharge, const SPlayerStats &stats, float frametime);
IGameFramework *m_pGameFramework;
CPlayer* m_pOwner;
SNanoMaterial*m_pNanoMaterial;
SNanoCloak m_cloak;
ENanoAction m_lastTap;
ENanoAction m_pendingAction;
// basic variables
float m_energy;
float m_lastEnergy;
float m_energyRechargeRate;
float m_healthAccError;
float m_healthRegenRate;
float m_activationTime;
float m_invulnerabilityTimeout;
bool m_active;
bool m_bWasSprinting;
bool m_bSprintUnderwater;
bool m_bNightVisionEnabled;
bool m_invulnerable;
// timing helpers
float m_now;
float m_lastTimeUsedThruster;
float m_healTime;
float m_startedSprinting;
float m_energyRechargeDelay;
float m_healthRegenDelay;
float m_defenseHitTimer;
//this is used as a mask for nanosuit features
uint16 m_featureMask;
ENanoMode m_currentMode;
SNanoSlot m_slots[NANOSLOT_LAST];
//sound playback
float m_fLastSoundPlayedMedical;
struct SSuitSound
{
tSoundID ID;
bool bLooping;
bool b3D;
int nMassIndex;
int nSpeedIndex;
int nStrengthIndex;
};
SSuitSound m_sounds[ESound_Suit_Last];
std::vector<INanoSuitListener*> m_listeners;
};
#endif //__NANOSUIT_H__
| [
"[email protected]",
"kkirst@c5e09591-5635-0410-80e3-0b71df3ecc31"
]
| [
[
[
1,
41
],
[
44,
73
],
[
75,
80
],
[
83,
85
],
[
100,
103
],
[
110,
127
],
[
129,
195
],
[
199,
212
],
[
218,
218
],
[
220,
221
],
[
223,
226
],
[
231,
241
],
[
243,
244
],
[
247,
252
],
[
255,
263
],
[
265,
270
],
[
274,
281
],
[
283,
287
],
[
289,
294
],
[
298,
307
],
[
319,
323
]
],
[
[
42,
43
],
[
74,
74
],
[
81,
82
],
[
86,
99
],
[
104,
109
],
[
128,
128
],
[
196,
198
],
[
213,
217
],
[
219,
219
],
[
222,
222
],
[
227,
230
],
[
242,
242
],
[
245,
246
],
[
253,
254
],
[
264,
264
],
[
271,
273
],
[
282,
282
],
[
288,
288
],
[
295,
297
],
[
308,
318
]
]
]
|
50a42a155ff15b44f8aa3d57e6da5b93c0eff805 | 011359e589f99ae5fe8271962d447165e9ff7768 | /src/burn/misc/pre90s/d_airbustr.cpp | 9852ecc8d00836ab00f7921d0a96d3c0dd828ef9 | []
| no_license | PS3emulators/fba-next-slim | 4c753375fd68863c53830bb367c61737393f9777 | d082dea48c378bddd5e2a686fe8c19beb06db8e1 | refs/heads/master | 2021-01-17T23:05:29.479865 | 2011-12-01T18:16:02 | 2011-12-01T18:16:02 | 2,899,840 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,685 | cpp | // FB Alpha Air Buster: Trouble Specialty Raid Unit driver module
// Based on MAME driver by Luca Elia
#include "tiles_generic.h"
#include "msm6295.h"
#include "burn_ym2203.h"
static unsigned char *AllMem;
static unsigned char *RamEnd;
static unsigned char *MemEnd;
static unsigned char *AllRam;
static unsigned char *DrvZ80ROM0;
static unsigned char *DrvZ80ROM1;
static unsigned char *DrvZ80ROM2;
static unsigned char *DrvGfxROM0;
static unsigned char *DrvGfxROM1;
static unsigned char *DrvSndROM;
static unsigned char *DrvVidRAM0;
static unsigned char *DrvVidRAM1;
static unsigned char *DrvZ80RAM0;
static unsigned char *DrvZ80RAM1;
static unsigned char *DrvZ80RAM2;
static unsigned char *DrvShareRAM;
static unsigned char *DrvDevRAM;
static unsigned char *DrvPandoraRAM;
static unsigned char *DrvSprRAM;
static unsigned char *DrvPalRAM;
static unsigned int *DrvPalette;
static unsigned char *DrvScrollRegs;
static unsigned char *soundlatch;
static unsigned char *soundlatch2;
static unsigned char *sound_status;
static unsigned char *sound_status2;
static unsigned char *coin_lockout;
static unsigned char *flipscreen;
static int interrupt_vectors[2];
static int watchdog;
static int is_bootleg;
static unsigned char DrvJoy1[8];
static unsigned char DrvJoy2[8];
static unsigned char DrvJoy3[8];
static unsigned char DrvDips[2];
static unsigned char DrvInputs[3];
static unsigned char DrvReset;
static struct BurnInputInfo AirbustrInputList[] = {
{"P1 Coin", BIT_DIGITAL, DrvJoy3 + 2, "p1 coin" },
{"P1 Start", BIT_DIGITAL, DrvJoy3 + 0, "p1 start" },
{"P1 Up", BIT_DIGITAL, DrvJoy1 + 0, "p1 up" },
{"P1 Down", BIT_DIGITAL, DrvJoy1 + 1, "p1 down" },
{"P1 Left", BIT_DIGITAL, DrvJoy1 + 2, "p1 left" },
{"P1 Right", BIT_DIGITAL, DrvJoy1 + 3, "p1 right" },
{"P1 Button 1", BIT_DIGITAL, DrvJoy1 + 4, "p1 fire 1" },
{"P1 Button 2", BIT_DIGITAL, DrvJoy1 + 5, "p1 fire 2" },
{"P2 Coin", BIT_DIGITAL, DrvJoy3 + 3, "p2 coin" },
{"P2 Start", BIT_DIGITAL, DrvJoy3 + 1, "p2 start" },
{"P2 Up", BIT_DIGITAL, DrvJoy2 + 0, "p2 up" },
{"P2 Down", BIT_DIGITAL, DrvJoy2 + 1, "p2 down" },
{"P2 Left", BIT_DIGITAL, DrvJoy2 + 2, "p2 left" },
{"P2 Right", BIT_DIGITAL, DrvJoy2 + 3, "p2 right" },
{"P2 Button 1", BIT_DIGITAL, DrvJoy2 + 4, "p2 fire 1" },
{"P2 Button 2", BIT_DIGITAL, DrvJoy2 + 5, "p2 fire 2" },
{"Reset", BIT_DIGITAL, &DrvReset, "reset" },
{"Service", BIT_DIGITAL, DrvJoy3 + 6, "service" },
{"Dip A", BIT_DIPSWITCH, DrvDips + 0, "dip" },
{"Dip B", BIT_DIPSWITCH, DrvDips + 1, "dip" },
};
STDINPUTINFO(Airbustr)
static struct BurnDIPInfo AirbustrDIPList[]=
{
{0x12, 0xff, 0xff, 0xff, NULL },
{0x13, 0xff, 0xff, 0xff, NULL },
// {0 , 0xfe, 0 , 2, "Flip Screen" },
// {0x12, 0x01, 0x02, 0x02, "Off" },
// {0x12, 0x01, 0x02, 0x00, "On" },
{0 , 0xfe, 0 , 2, "Service Mode" },
{0x12, 0x01, 0x04, 0x04, "Off" },
{0x12, 0x01, 0x04, 0x00, "On" },
{0 , 0xfe, 0 , 2, "Coin Mode" },
{0x12, 0x01, 0x08, 0x08, "Mode 1" },
{0x12, 0x01, 0x08, 0x00, "Mode 2" },
{0 , 0xfe, 0 , 8, "Coin A" },
{0x12, 0x01, 0x30, 0x20, "2 Coins 1 Credits" },
{0x12, 0x01, 0x30, 0x30, "1 Coin 1 Credits" },
{0x12, 0x01, 0x30, 0x10, "1 Coin 2 Credits" },
{0x12, 0x01, 0x30, 0x00, "1 Coin 6 Credits" },
{0x12, 0x01, 0x30, 0x20, "2 Coins 1 Credits" },
{0x12, 0x01, 0x30, 0x30, "1 Coin 1 Credits" },
{0x12, 0x01, 0x30, 0x10, "1 Coin 3 Credits" },
{0x12, 0x01, 0x30, 0x00, "1 Coin 4 Credits" },
{0 , 0xfe, 0 , 8, "Coin B" },
{0x12, 0x01, 0xc0, 0x80, "2 Coins 1 Credits" },
{0x12, 0x01, 0xc0, 0xc0, "1 Coin 1 Credits" },
{0x12, 0x01, 0xc0, 0x40, "1 Coin 2 Credits" },
{0x12, 0x01, 0xc0, 0x00, "1 Coin 6 Credits" },
{0x12, 0x01, 0xc0, 0x80, "2 Coins 1 Credits" },
{0x12, 0x01, 0xc0, 0xc0, "1 Coin 1 Credits" },
{0x12, 0x01, 0xc0, 0x40, "1 Coin 3 Credits" },
{0x12, 0x01, 0xc0, 0x00, "1 Coin 4 Credits" },
{0 , 0xfe, 0 , 4, "Difficulty" },
{0x13, 0x01, 0x03, 0x02, "Easy" },
{0x13, 0x01, 0x03, 0x03, "Normal" },
{0x13, 0x01, 0x03, 0x01, "Difficult" },
{0x13, 0x01, 0x03, 0x00, "Very Difficult" },
{0 , 0xfe, 0 , 2, "Freeze" },
{0x13, 0x01, 0x08, 0x08, "Off" },
{0x13, 0x01, 0x08, 0x00, "On" },
{0 , 0xfe, 0 , 4, "Lives" },
{0x13, 0x01, 0x30, 0x30, "3" },
{0x13, 0x01, 0x30, 0x20, "4" },
{0x13, 0x01, 0x30, 0x10, "5" },
{0x13, 0x01, 0x30, 0x00, "7" },
{0 , 0xfe, 0 , 2, "Demo Sounds" },
{0x13, 0x01, 0x40, 0x00, "Off" },
{0x13, 0x01, 0x40, 0x40, "On" },
};
STDDIPINFO(Airbustr)
static struct BurnDIPInfo AirbustjDIPList[]=
{
{0x12, 0xff, 0xff, 0xff, NULL },
{0x13, 0xff, 0xff, 0xff, NULL },
// {0 , 0xfe, 0 , 2, "Flip Screen" },
// {0x12, 0x01, 0x02, 0x02, "Off" },
// {0x12, 0x01, 0x02, 0x00, "On" },
{0 , 0xfe, 0 , 2, "Service Mode" },
{0x12, 0x01, 0x04, 0x04, "Off" },
{0x12, 0x01, 0x04, 0x00, "On" },
{0 , 0xfe, 0 , 4, "Coin A" },
{0x12, 0x01, 0x30, 0x10, "2 Coins 1 Credits" },
{0x12, 0x01, 0x30, 0x30, "1 Coin 1 Credits" },
{0x12, 0x01, 0x30, 0x00, "2 Coins 3 Credits" },
{0x12, 0x01, 0x30, 0x20, "1 Coin 2 Credits" },
{0 , 0xfe, 0 , 4, "Coin B" },
{0x12, 0x01, 0xc0, 0x40, "2 Coins 1 Credits" },
{0x12, 0x01, 0xc0, 0xc0, "1 Coin 1 Credits" },
{0x12, 0x01, 0xc0, 0x00, "2 Coins 3 Credits" },
{0x12, 0x01, 0xc0, 0x80, "1 Coin 2 Credits" },
{0 , 0xfe, 0 , 4, "Difficulty" },
{0x13, 0x01, 0x03, 0x02, "Easy" },
{0x13, 0x01, 0x03, 0x03, "Normal" },
{0x13, 0x01, 0x03, 0x01, "Difficult" },
{0x13, 0x01, 0x03, 0x00, "Very Difficult" },
{0 , 0xfe, 0 , 2, "Freeze" },
{0x13, 0x01, 0x08, 0x08, "Off" },
{0x13, 0x01, 0x08, 0x00, "On" },
{0 , 0xfe, 0 , 4, "Lives" },
{0x13, 0x01, 0x30, 0x30, "3" },
{0x13, 0x01, 0x30, 0x20, "4" },
{0x13, 0x01, 0x30, 0x10, "5" },
{0x13, 0x01, 0x30, 0x00, "7" },
{0 , 0xfe, 0 , 2, "Demo Sounds" },
{0x13, 0x01, 0x40, 0x00, "Off" },
{0x13, 0x01, 0x40, 0x40, "On" },
};
STDDIPINFO(Airbustj)
//----------------------------------------------------------------------------------------------------
// Kaneko Pandora module -- should be in its own file
static unsigned short *pandora_temp = NULL;
static unsigned char *pandora_ram = NULL;
static unsigned char *pandora_gfx = NULL;
static int pandora_clear;
static int pandora_xoffset;
static int pandora_yoffset;
static int pandora_color_offset;
int pandora_flipscreen;
void pandora_set_clear(int clear)
{
pandora_clear = clear;
}
void pandora_update(unsigned short *dest)
{
for (int i = 0; i < nScreenWidth * nScreenHeight; i++) {
if (pandora_temp[i]) {
dest[i] = pandora_temp[i] & 0x3ff;
}
}
}
void pandora_buffer_sprites()
{
int sx=0, sy=0, x=0, y=0;
if (pandora_clear) memset (pandora_temp, 0, nScreenWidth * nScreenHeight * sizeof(short));
for (int offs = 0; offs < 0x1000; offs += 8)
{
int attr = pandora_ram[offs+7];
int code = pandora_ram[offs+6] + ((attr & 0x3f) << 8);
int dy = pandora_ram[offs+5];
int dx = pandora_ram[offs+4];
int color = pandora_ram[offs+3];
int flipy = attr & 0x40;
int flipx = attr & 0x80;
if (color & 1) dx |= 0x100;
if (color & 2) dy |= 0x100;
if (color & 4)
{
x += dx;
y += dy;
}
else
{
x = dx;
y = dy;
}
if (pandora_flipscreen)
{
sx = 240 - x;
sy = 240 - y;
flipx = !flipx;
flipy = !flipy;
}
else
{
sx = x;
sy = y;
}
sx = (sx + pandora_xoffset) & 0x1ff;
sy = (sy + pandora_yoffset) & 0x1ff;
if (sx & 0x100) sx -= 0x200;
if (sy & 0x100) sy -= 0x200;
if (sx >= nScreenWidth || sx < -15) continue;
if (sy >= nScreenHeight || sy < -15) continue;
if (flipy) {
if (flipx) {
Render16x16Tile_Mask_FlipXY_Clip(pandora_temp, code, sx, sy, color >> 4, 4, 0, pandora_color_offset, pandora_gfx);
} else {
Render16x16Tile_Mask_FlipY_Clip(pandora_temp, code, sx, sy, color >> 4, 4, 0, pandora_color_offset, pandora_gfx);
}
} else {
if (flipx) {
Render16x16Tile_Mask_FlipX_Clip(pandora_temp, code, sx, sy, color >> 4, 4, 0, pandora_color_offset, pandora_gfx);
} else {
Render16x16Tile_Mask_Clip(pandora_temp, code, sx, sy, color >> 4, 4, 0, pandora_color_offset, pandora_gfx);
}
}
}
}
// must be called after GenericTilesInit()
void pandora_init(unsigned char *ram, unsigned char *gfx, int color_offset, int x, int y)
{
pandora_ram = ram;
pandora_xoffset = x;
pandora_yoffset = y;
pandora_gfx = gfx;
pandora_color_offset = color_offset;
if (BurnDrvGetFlags() & BDF_ORIENTATION_VERTICAL) {
BurnDrvGetVisibleSize(&nScreenHeight, &nScreenWidth);
} else {
BurnDrvGetVisibleSize(&nScreenWidth, &nScreenHeight);
}
pandora_temp = (unsigned short*)malloc(nScreenWidth * nScreenHeight * sizeof(short));
pandora_clear = 1;
}
void pandora_exit()
{
free (pandora_temp);
pandora_temp = NULL;
pandora_ram = pandora_gfx = NULL;
}
//---------------------------------------------------------------------------------------------
static inline void DrvRecalcPalette()
{
unsigned char r,g,b;
for (int i = 0; i < 0x600; i+=2) {
int d = DrvPalRAM[i + 1] * 256 + DrvPalRAM[i + 0];
r = (d >> 5) & 0x1f;
g = (d >> 10) & 0x1f;
b = (d >> 0) & 0x1f;
r = (r << 3) | (r >> 2);
g = (g << 3) | (g >> 2);
b = (b << 3) | (b >> 2);
DrvPalette[i / 2] = BurnHighCol(r, g, b, 0);
}
}
static void airbustr_bankswitch(unsigned char *rom, int data)
{
ZetMapArea(0x8000, 0xbfff, 0, rom + 0x4000 * (data & 0x07));
ZetMapArea(0x8000, 0xbfff, 2, rom + 0x4000 * (data & 0x07));
}
void __fastcall airbustr_main_write(unsigned short address, unsigned char data)
{
if ((address & 0xf000) == 0xc000) { // pandora
DrvSprRAM[address & 0xfff] = data;
address = (address & 0x800) | ((address & 0xff) << 3) | ((address & 0x700) >> 8);
DrvPandoraRAM[address] = data;
return;
}
}
unsigned char __fastcall airbustr_main_read(unsigned short address)
{
if ((address & 0xf000) == 0xe000) {
int offset = address & 0xfff;
switch (offset)
{
case 0xfe0:
watchdog = 180;
return 0;
case 0xff2:
case 0xff3:
{
int r = (DrvDevRAM[0xff0] + DrvDevRAM[0xff1] * 256) * (DrvDevRAM[0xff2] + DrvDevRAM[0xff3] * 256);
if (offset & 1) return r >> 8;
return r;
}
case 0xff4:
return rand();
}
return DrvDevRAM[offset];
}
return 0;
}
void __fastcall airbustr_main_out(unsigned short port, unsigned char data)
{
switch (port & 0xff)
{
case 0x00:
airbustr_bankswitch(DrvZ80ROM0, data);
return;
case 0x01:
return; // nop
case 0x02:
{
ZetClose();
ZetOpen(1);
ZetNmi();
ZetClose();
ZetOpen(0);
}
return;
}
}
void __fastcall airbustr_sub_out(unsigned short port, unsigned char data)
{
switch (port & 0xff)
{
case 0x00:
{
airbustr_bankswitch(DrvZ80ROM1, data);
*flipscreen = data & 0x10;
pandora_set_clear(data & 0x20);
}
return;
case 0x02: // soundcommand_w
{
*soundlatch = data;
*sound_status = 1;
ZetClose();
ZetOpen(2);
ZetNmi();
ZetClose();
ZetOpen(1);
}
return;
case 0x04:
case 0x06:
case 0x08:
case 0x0a:
case 0x0c:
DrvScrollRegs[((port & 0x0f) - 0x04) / 2] = data;
return;
case 0x28:
*coin_lockout = ~data & 0x0c;
// coint counter also (0x03)
return;
case 0x38:
return; // nop
}
}
unsigned char __fastcall airbustr_sub_in(unsigned short port)
{
switch (port & 0xff)
{
case 0x02:
*sound_status2 = 0;
return *soundlatch2;
case 0x0e:
return (4 + *sound_status * 2 + (1 - *sound_status2));
case 0x20:
return DrvInputs[0];
case 0x22:
return DrvInputs[1];
case 0x24:
return DrvInputs[2] | *coin_lockout;
}
return 0;
}
void __fastcall airbustr_sound_out(unsigned short port, unsigned char data)
{
switch (port & 0xff)
{
case 0x00:
airbustr_bankswitch(DrvZ80ROM2, data);
return;
case 0x02:
BurnYM2203Write(0, 0, data);
return;
case 0x03:
BurnYM2203Write(0, 1, data);
return;
case 0x04:
MSM6295Command(0, data);
return;
case 0x06:
*soundlatch2 = data;
*sound_status2 = 1;
return;
}
}
unsigned char __fastcall airbustr_sound_in(unsigned short port)
{
switch (port & 0xff)
{
case 0x02:
return BurnYM2203Read(0, 0);
case 0x03:
return BurnYM2203Read(0, 1);
case 0x04:
return MSM6295ReadStatus(0);
case 0x06:
*sound_status = 0;
return *soundlatch;
}
return 0;
}
unsigned char DrvYM2203PortA(unsigned int)
{
return DrvDips[0];
}
unsigned char DrvYM2203PortB(unsigned int)
{
return DrvDips[1];
}
static int DrvSynchroniseStream(int nSoundRate)
{
return (long long)ZetTotalCycles() * nSoundRate / 6000000;
}
static double DrvGetTime()
{
return (double)ZetTotalCycles() / 6000000;
}
static int DrvDoReset(int full_reset)
{
if (full_reset) {
memset (AllRam, 0, RamEnd - AllRam);
}
// unsigned char *rom[3] = { DrvZ80ROM0, DrvZ80ROM1, DrvZ80ROM2 };
for (int i = 0; i < 3; i++) {
ZetOpen(i);
ZetReset();
// if (full_reset) airbustr_bankswitch(rom[i], 2);
ZetClose();
}
MSM6295Reset(0);
BurnYM2203Reset();
interrupt_vectors[0] = 0xff;
interrupt_vectors[1] = 0xfd;
watchdog = 180;
srand(time(NULL));
return 0;
}
static int MemIndex()
{
unsigned char *Next; Next = AllMem;
DrvZ80ROM0 = Next; Next += 0x020000;
DrvZ80ROM1 = Next; Next += 0x020000;
DrvZ80ROM2 = Next; Next += 0x020000;
DrvGfxROM0 = Next; Next += 0x100000;
DrvGfxROM1 = Next; Next += 0x400000;
MSM6295ROM = Next;
DrvSndROM = Next; Next += 0x040000;
DrvPalette = (unsigned int*)Next; Next += 0x0400 * sizeof(int);
AllRam = Next;
DrvVidRAM0 = Next; Next += 0x000800;
DrvVidRAM1 = Next; Next += 0x000800;
DrvZ80RAM0 = Next; Next += 0x001000;
DrvZ80RAM1 = Next; Next += 0x001000;
DrvZ80RAM2 = Next; Next += 0x002000;
DrvShareRAM = Next; Next += 0x001000;
DrvDevRAM = Next; Next += 0x001000;
DrvPandoraRAM = Next; Next += 0x001000;
DrvSprRAM = Next; Next += 0x001000;
DrvPalRAM = Next; Next += 0x001000;
DrvScrollRegs = Next; Next += 0x000006;
soundlatch = Next; Next += 0x000001;
soundlatch2 = Next; Next += 0x000001;
sound_status = Next; Next += 0x000001;
sound_status2 = Next; Next += 0x000001;
coin_lockout = Next; Next += 0x000001;
flipscreen = Next; Next += 0x000001;
RamEnd = Next;
MemEnd = Next;
return 0;
}
static int DrvGfxDecode()
{
static int Plane[4] = { 0, 1, 2, 3 };
static int XOffs[16] = { 0*4, 1*4, 2*4, 3*4, 4*4, 5*4, 6*4, 7*4,
0*4+32*8, 1*4+32*8, 2*4+32*8, 3*4+32*8, 4*4+32*8, 5*4+32*8, 6*4+32*8, 7*4+32*8 };
static int YOffs[16] = { 0*32, 1*32, 2*32, 3*32, 4*32, 5*32, 6*32, 7*32,
0*32+64*8, 1*32+64*8, 2*32+64*8, 3*32+64*8, 4*32+64*8, 5*32+64*8, 6*32+64*8, 7*32+64*8 };
unsigned char *tmp = (unsigned char*)malloc(0x100000);
if (tmp == NULL) {
return 1;
}
for (int i = 0; i < 0x080000; i++) {
tmp[i] = (DrvGfxROM0[i] << 4) | (DrvGfxROM0[i] >> 4);
}
GfxDecode(0x1000, 4, 16, 16, Plane, XOffs, YOffs, 0x400, tmp, DrvGfxROM0);
memcpy (tmp, DrvGfxROM1, 0x100000);
GfxDecode(0x2000, 4, 16, 16, Plane, XOffs, YOffs, 0x400, tmp, DrvGfxROM1);
free (tmp);
return 0;
}
static int DrvInit()
{
is_bootleg = BurnDrvGetFlags() & BDF_BOOTLEG;
AllMem = NULL;
MemIndex();
int nLen = MemEnd - (unsigned char *)0;
if ((AllMem = (unsigned char *)malloc(nLen)) == NULL) return 1;
memset(AllMem, 0, nLen);
MemIndex();
{
if (BurnLoadRom(DrvZ80ROM0 + 0x000000, 0, 1)) return 1;
if (BurnLoadRom(DrvZ80ROM1 + 0x000000, 1, 1)) return 1;
if (BurnLoadRom(DrvZ80ROM2 + 0x000000, 2, 1)) return 1;
if (is_bootleg)
{
if (BurnLoadRom(DrvGfxROM0 + 0x000000, 3, 2)) return 1;
if (BurnLoadRom(DrvGfxROM0 + 0x000001, 4, 2)) return 1;
if (BurnLoadRom(DrvGfxROM0 + 0x040000, 5, 2)) return 1;
if (BurnLoadRom(DrvGfxROM0 + 0x040001, 6, 2)) return 1;
if (BurnLoadRom(DrvGfxROM1 + 0x000000, 7, 1)) return 1;
if (BurnLoadRom(DrvGfxROM1 + 0x020000, 8, 1)) return 1;
if (BurnLoadRom(DrvGfxROM1 + 0x040000, 9, 1)) return 1;
if (BurnLoadRom(DrvGfxROM1 + 0x060000, 10, 1)) return 1;
if (BurnLoadRom(DrvGfxROM1 + 0x080000, 11, 1)) return 1;
if (BurnLoadRom(DrvSndROM + 0x000000, 12, 1)) return 1;
if (BurnLoadRom(DrvSndROM + 0x020000, 13, 1)) return 1;
}
else
{
// mcu...
if (BurnLoadRom(DrvGfxROM0 + 0x000000, 4, 1)) return 1;
if (BurnLoadRom(DrvGfxROM1 + 0x000000, 5, 1)) return 1;
if (BurnLoadRom(DrvGfxROM1 + 0x080000, 6, 1)) return 1;
if (BurnLoadRom(DrvSndROM + 0x000000, 7, 1)) return 1;
}
DrvGfxDecode();
}
ZetInit(3);
ZetOpen(0);
ZetMapArea(0x0000, 0x7fff, 0, DrvZ80ROM0);
ZetMapArea(0x0000, 0x7fff, 2, DrvZ80ROM0);
ZetMapArea(0xc000, 0xcfff, 0, DrvSprRAM);
// ZetMapArea(0xc000, 0xcfff, 1, DrvSprRAM); // handler
ZetMapArea(0xc000, 0xcfff, 2, DrvSprRAM);
ZetMapArea(0xd000, 0xdfff, 0, DrvZ80RAM0);
ZetMapArea(0xd000, 0xdfff, 1, DrvZ80RAM0);
ZetMapArea(0xd000, 0xdfff, 2, DrvZ80RAM0);
if (is_bootleg) ZetMapArea(0xe000, 0xefff, 0, DrvDevRAM);
ZetMapArea(0xe000, 0xefff, 1, DrvDevRAM);
ZetMapArea(0xe000, 0xefff, 2, DrvDevRAM);
ZetMapArea(0xf000, 0xffff, 0, DrvShareRAM);
ZetMapArea(0xf000, 0xffff, 1, DrvShareRAM);
ZetMapArea(0xf000, 0xffff, 2, DrvShareRAM);
ZetSetWriteHandler(airbustr_main_write);
ZetSetReadHandler(airbustr_main_read);
ZetSetOutHandler(airbustr_main_out);
ZetMemEnd();
ZetClose();
ZetOpen(1);
ZetMapArea(0x0000, 0x7fff, 0, DrvZ80ROM1);
ZetMapArea(0x0000, 0x7fff, 2, DrvZ80ROM1);
ZetMapArea(0xc000, 0xc7ff, 0, DrvVidRAM1);
ZetMapArea(0xc000, 0xc7ff, 1, DrvVidRAM1);
ZetMapArea(0xc000, 0xc7ff, 2, DrvVidRAM1);
ZetMapArea(0xc800, 0xcfff, 0, DrvVidRAM0);
ZetMapArea(0xc800, 0xcfff, 1, DrvVidRAM0);
ZetMapArea(0xc800, 0xcfff, 2, DrvVidRAM0);
ZetMapArea(0xd000, 0xdfff, 0, DrvPalRAM);
ZetMapArea(0xd000, 0xdfff, 1, DrvPalRAM);
ZetMapArea(0xd000, 0xdfff, 2, DrvPalRAM);
ZetMapArea(0xe000, 0xefff, 0, DrvZ80RAM1);
ZetMapArea(0xe000, 0xefff, 1, DrvZ80RAM1);
ZetMapArea(0xe000, 0xefff, 2, DrvZ80RAM1);
ZetMapArea(0xf000, 0xffff, 0, DrvShareRAM);
ZetMapArea(0xf000, 0xffff, 1, DrvShareRAM);
ZetMapArea(0xf000, 0xffff, 2, DrvShareRAM);
ZetSetOutHandler(airbustr_sub_out);
ZetSetInHandler(airbustr_sub_in);
ZetMemEnd();
ZetClose();
ZetOpen(2);
ZetMapArea(0x0000, 0x7fff, 0, DrvZ80ROM2);
ZetMapArea(0x0000, 0x7fff, 2, DrvZ80ROM2);
ZetMapArea(0xc000, 0xdfff, 0, DrvZ80RAM2);
ZetMapArea(0xc000, 0xdfff, 1, DrvZ80RAM2);
ZetMapArea(0xc000, 0xdfff, 2, DrvZ80RAM2);
ZetSetOutHandler(airbustr_sound_out);
ZetSetInHandler(airbustr_sound_in);
ZetMemEnd();
ZetClose();
BurnYM2203Init(1, 3000000, NULL, DrvSynchroniseStream, DrvGetTime, 0);
BurnYM2203SetPorts(0, &DrvYM2203PortA, &DrvYM2203PortB, NULL, NULL);
BurnTimerAttachZet(6000000);
MSM6295Init(0, 3000000 / 132, 80, 1);
GenericTilesInit();
pandora_init(DrvPandoraRAM, DrvGfxROM1, 0x200, 0, -16);
DrvDoReset(1);
return 0;
}
static int DrvExit()
{
pandora_exit();
GenericTilesExit();
ZetExit();
MSM6295Exit(0);
BurnYM2203Exit();
free(AllMem);
AllMem = NULL;
return 0;
}
static void draw_layer(unsigned char *ram, int r0, int r1, int r2, int r3, int t)
{
int scrollx = DrvScrollRegs[r0] + ((~DrvScrollRegs[4] << r1) & 0x100);
int scrolly = DrvScrollRegs[r2] + ((~DrvScrollRegs[4] << r3) & 0x100) + 16;
if (*flipscreen) {
scrollx = (scrollx + 0x06a) & 0x1ff;
scrolly = (scrolly + 0x1ff) & 0x1ff;
} else {
scrollx = (scrollx - 0x094) & 0x1ff;
scrolly = (scrolly - 0x100) & 0x1ff;
}
for (int offs = 0; offs < 32 * 32; offs++)
{
int sx = (offs & 0x1f) << 4;
int sy = (offs >> 5) << 4;
sx -= scrollx;
if (sx < -15) sx += 512;
sy -= scrolly;
if (sy < -15) sy += 512;
if (sx >= nScreenWidth) continue;
if (sy >= nScreenHeight) continue;
int attr = ram[offs + 0x400];
int code = ram[offs + 0x000] | ((attr & 0x0f) << 8);
if (t) {
if (*flipscreen) {
Render16x16Tile_Mask_FlipXY_Clip(pTransDraw, code, 240 - sx, 240 - sy, attr >> 4, 4, 0, 0, DrvGfxROM0);
} else {
Render16x16Tile_Mask_Clip(pTransDraw, code, sx, sy, attr >> 4, 4, 0, 0, DrvGfxROM0);
}
} else {
if (*flipscreen) {
Render16x16Tile_FlipXY_Clip(pTransDraw, code, 240 - sx, 240 - sy, attr >> 4, 4, 0x100, DrvGfxROM0);
} else {
Render16x16Tile_Clip(pTransDraw, code, sx, sy, attr >> 4, 4, 0x100, DrvGfxROM0);
}
}
}
}
static int DrvDraw()
{
DrvRecalcPalette();
draw_layer(DrvVidRAM0, 3, 6, 2, 5, 0);
draw_layer(DrvVidRAM1, 1, 8, 0, 7, 0);
pandora_flipscreen = *flipscreen;
pandora_update(pTransDraw);
BurnTransferCopy(DrvPalette);
return 0;
}
static int DrvFrame()
{
if (DrvReset) {
DrvDoReset(1);
}
if (watchdog == 0 && is_bootleg == 0) {
DrvDoReset(0);
}
watchdog--;
ZetNewFrame();
{
memset (DrvInputs, 0xff, 3);
for (int i = 0; i < 8; i++) {
DrvInputs[0] ^= (DrvJoy1[i] & 1) << i;
DrvInputs[1] ^= (DrvJoy2[i] & 1) << i;
DrvInputs[2] ^= (DrvJoy3[i] & 1) << i;
}
}
int nInterleave = 100;
int nSoundBufferPos = 0;
int nCyclesTotal[3] = { 6000000 / 60, 6000000 / 60, 6000000 / 60 };
int nCyclesDone[3] = { 0, 0, 0 };
for (int i = 0; i < nInterleave; i++) {
int nSegment = (nCyclesTotal[0] / nInterleave) * (i + 1);
ZetOpen(0);
nCyclesDone[0] += ZetRun(nSegment - nCyclesDone[0]);
if (i == 49 || i == 99) {
interrupt_vectors[0] ^= 2;
ZetSetVector(interrupt_vectors[0]);
ZetSetIRQLine(0, ZET_IRQSTATUS_AUTO);
}
ZetClose();
ZetOpen(1);
nCyclesDone[1] += ZetRun(nSegment - nCyclesDone[1]);
if (i == 49 || i == 99) {
interrupt_vectors[1] ^= 2;
ZetSetVector(interrupt_vectors[1]);
ZetSetIRQLine(0, ZET_IRQSTATUS_AUTO);
}
ZetClose();
ZetOpen(2);
BurnTimerUpdate(nCyclesDone[1] /*sync with sub cpu*/);
if (i == 99) {
ZetSetIRQLine(0, ZET_IRQSTATUS_AUTO);
}
if (pBurnSoundOut) {
int nSegmentLength = nBurnSoundLen - nSoundBufferPos;
short* pSoundBuf = pBurnSoundOut + (nSoundBufferPos << 1);
BurnYM2203Update(pSoundBuf, nSegmentLength);
MSM6295Render(0, pSoundBuf, nSegmentLength);
nSoundBufferPos += nSegmentLength;
}
ZetClose();
}
ZetOpen(2);
BurnTimerEndFrame(nCyclesTotal[2]);
if (pBurnSoundOut) {
int nSegmentLength = nBurnSoundLen - nSoundBufferPos;
short* pSoundBuf = pBurnSoundOut + (nSoundBufferPos << 1);
if (nSegmentLength) {
BurnYM2203Update(pSoundBuf, nSegmentLength);
MSM6295Render(0, pSoundBuf, nSegmentLength);
}
}
ZetClose();
if (pBurnDraw) {
DrvDraw();
}
pandora_buffer_sprites();
return 0;
}
static int DrvScan(int nAction,int *pnMin)
{
struct BurnArea ba;
if (pnMin) {
*pnMin = 0x029707;
}
if (nAction & ACB_VOLATILE) {
memset(&ba, 0, sizeof(ba));
ba.Data = AllRam;
ba.nLen = RamEnd - AllRam;
ba.szName = "All Ram";
BurnAcb(&ba);
ZetScan(nAction);
BurnYM2203Scan(nAction, pnMin);
MSM6295Scan(0, nAction);
}
return 0;
}
// Air Buster: Trouble Specialty Raid Unit (World)
static struct BurnRomInfo airbustrRomDesc[] = {
{ "pr12.h19", 0x20000, 0x91362eb2, 1 | BRF_PRG | BRF_ESS }, // 0 Z80 #0 Code
{ "pr13.l15", 0x20000, 0x13b2257b, 2 | BRF_PRG | BRF_ESS }, // 1 Z80 #1 Code
{ "pr-21.bin", 0x20000, 0x6e0a5df0, 3 | BRF_PRG | BRF_ESS }, // 2 Z80 #2 Code
{ "i80c51", 0x01000, 0x00000000, 4 | BRF_NODUMP }, // 3 80c51 MCU
{ "pr-000.bin", 0x80000, 0x8ca68f0d, 5 | BRF_GRA }, // 4 Tiles
{ "pr-001.bin", 0x80000, 0x7e6cb377, 6 | BRF_GRA }, // 5 Sprites
{ "pr-02.bin", 0x10000, 0x6bbd5e46, 6 | BRF_GRA }, // 6
{ "pr-200.bin", 0x40000, 0xa4dd3390, 7 | BRF_SND }, // 7 OKI M6295
};
STD_ROM_PICK(airbustr)
STD_ROM_FN(airbustr)
struct BurnDriver BurnDrvAirbustr = {
"airbustr", NULL, NULL, "1990",
"Air Buster: Trouble Specialty Raid Unit (World)\0", NULL, "Kaneko (Namco license)", "Miscellaneous",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING, 2, HARDWARE_MISC_MISC,
NULL, airbustrRomInfo, airbustrRomName, AirbustrInputInfo, AirbustrDIPInfo,
DrvInit, DrvExit, DrvFrame, DrvDraw, DrvScan, NULL,
256, 224, 4, 3
};
// Air Buster: Trouble Specialty Raid Unit (Japan)
static struct BurnRomInfo airbustrjRomDesc[] = {
{ "pr-14j.bin", 0x20000, 0x6b9805bd, 1 | BRF_PRG | BRF_ESS }, // 0 Z80 #0 Code
{ "pr-11j.bin", 0x20000, 0x85464124, 2 | BRF_PRG | BRF_ESS }, // 1 Z80 #1 Code
{ "pr-21.bin", 0x20000, 0x6e0a5df0, 3 | BRF_PRG | BRF_ESS }, // 2 Z80 #2 Code
{ "i80c51", 0x01000, 0x00000000, 4 | BRF_NODUMP }, // 3 80c51 MCU
{ "pr-000.bin", 0x80000, 0x8ca68f0d, 5 | BRF_GRA }, // 4 Tiles
{ "pr-001.bin", 0x80000, 0x7e6cb377, 6 | BRF_GRA }, // 5 Sprites
{ "pr-02.bin", 0x10000, 0x6bbd5e46, 6 | BRF_GRA }, // 6
{ "pr-200.bin", 0x40000, 0xa4dd3390, 7 | BRF_SND }, // 7 OKI M6295
};
STD_ROM_PICK(airbustrj)
STD_ROM_FN(airbustrj)
struct BurnDriver BurnDrvAirbustrj = {
"airbustrj", "airbustr", NULL, "1990",
"Air Buster: Trouble Specialty Raid Unit (Japan)\0", NULL, "Kaneko (Namco license)", "Miscellaneous",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_MISC_MISC,
NULL, airbustrjRomInfo, airbustrjRomName, AirbustrInputInfo, AirbustjDIPInfo,
DrvInit, DrvExit, DrvFrame, DrvDraw, DrvScan, NULL,
256, 224, 4, 3
};
// Air Buster: Trouble Specialty Raid Unit (bootleg)
static struct BurnRomInfo airbustrbRomDesc[] = {
{ "5.bin", 0x20000, 0x9e4216a2, 1 | BRF_PRG | BRF_ESS }, // 0 Z80 #0 Code
{ "1.bin", 0x20000, 0x85464124, 2 | BRF_PRG | BRF_ESS }, // 1 Z80 #1 Code
{ "2.bin", 0x20000, 0x6e0a5df0, 3 | BRF_PRG | BRF_ESS }, // 2 Z80 #2 Code
{ "7.bin", 0x20000, 0x2e3bf0a2, 4 | BRF_GRA }, // 3 Tiles
{ "9.bin", 0x20000, 0x2c23c646, 4 | BRF_GRA }, // 4
{ "6.bin", 0x20000, 0x0d6cd470, 4 | BRF_GRA }, // 5
{ "8.bin", 0x20000, 0xb3372e51, 4 | BRF_GRA }, // 6
{ "13.bin", 0x20000, 0x75dee86d, 5 | BRF_GRA }, // 7 Sprites
{ "12.bin", 0x20000, 0xc98a8333, 5 | BRF_GRA }, // 8
{ "11.bin", 0x20000, 0x4e9baebd, 5 | BRF_GRA }, // 9
{ "10.bin", 0x20000, 0x63dc8cd8, 5 | BRF_GRA }, // 10
{ "14.bin", 0x10000, 0x6bbd5e46, 5 | BRF_GRA }, // 11
{ "4.bin", 0x20000, 0x21d9bfe3, 6 | BRF_SND }, // 12 OKI M6295
{ "3.bin", 0x20000, 0x58cd19e2, 6 | BRF_SND }, // 13
};
STD_ROM_PICK(airbustrb)
STD_ROM_FN(airbustrb)
struct BurnDriver BurnDrvAirbustrb = {
"airbustrb", "airbustr", NULL, "1990",
"Air Buster: Trouble Specialty Raid Unit (bootleg)\0", NULL, "bootleg", "Miscellaneous",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING | BDF_CLONE | BDF_BOOTLEG, 2, HARDWARE_MISC_MISC,
NULL, airbustrbRomInfo, airbustrbRomName, AirbustrInputInfo, AirbustjDIPInfo,
DrvInit, DrvExit, DrvFrame, DrvDraw, DrvScan, NULL,
256, 224, 4, 3
};
| [
"[email protected]"
]
| [
[
[
1,
1054
]
]
]
|
d242cfeb8215c2413daeb5a89e9b84c70b0384b4 | a84b013cd995870071589cefe0ab060ff3105f35 | /webdriver/branches/chrome/chrome/src/cpp/include/v8/src/builtins.h | 3211f312653fa50fca62e237e685d0e222c726f6 | [
"Apache-2.0"
]
| permissive | vdt/selenium | 137bcad58b7184690b8785859d77da0cd9f745a0 | 30e5e122b068aadf31bcd010d00a58afd8075217 | refs/heads/master | 2020-12-27T21:35:06.461381 | 2009-08-18T15:56:32 | 2009-08-18T15:56:32 | 13,650,409 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,198 | h | // Copyright 2006-2008 the V8 project authors. 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 Google Inc. 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 V8_BUILTINS_H_
#define V8_BUILTINS_H_
namespace v8 { namespace internal {
// Define list of builtins implemented in C.
#define BUILTIN_LIST_C(V) \
V(Illegal) \
\
V(EmptyFunction) \
\
V(ArrayCode) \
\
V(ArrayPush) \
V(ArrayPop) \
\
V(HandleApiCall) \
V(HandleApiCallAsFunction)
// Define list of builtins implemented in assembly.
#define BUILTIN_LIST_A(V) \
V(ArgumentsAdaptorTrampoline, BUILTIN, UNINITIALIZED) \
V(JSConstructCall, BUILTIN, UNINITIALIZED) \
V(JSEntryTrampoline, BUILTIN, UNINITIALIZED) \
V(JSConstructEntryTrampoline, BUILTIN, UNINITIALIZED) \
\
V(LoadIC_Miss, BUILTIN, UNINITIALIZED) \
V(KeyedLoadIC_Miss, BUILTIN, UNINITIALIZED) \
V(StoreIC_Miss, BUILTIN, UNINITIALIZED) \
V(KeyedStoreIC_Miss, BUILTIN, UNINITIALIZED) \
\
V(StoreIC_ExtendStorage, BUILTIN, UNINITIALIZED) \
V(KeyedStoreIC_ExtendStorage, BUILTIN, UNINITIALIZED) \
\
V(LoadIC_Initialize, LOAD_IC, UNINITIALIZED) \
V(LoadIC_PreMonomorphic, LOAD_IC, PREMONOMORPHIC) \
V(LoadIC_Normal, LOAD_IC, MONOMORPHIC) \
V(LoadIC_ArrayLength, LOAD_IC, MONOMORPHIC) \
V(LoadIC_StringLength, LOAD_IC, MONOMORPHIC) \
V(LoadIC_FunctionPrototype, LOAD_IC, MONOMORPHIC) \
V(LoadIC_Megamorphic, LOAD_IC, MEGAMORPHIC) \
\
V(KeyedLoadIC_Initialize, KEYED_LOAD_IC, UNINITIALIZED) \
V(KeyedLoadIC_PreMonomorphic, KEYED_LOAD_IC, PREMONOMORPHIC) \
V(KeyedLoadIC_Generic, KEYED_LOAD_IC, MEGAMORPHIC) \
\
V(StoreIC_Initialize, STORE_IC, UNINITIALIZED) \
V(StoreIC_Megamorphic, STORE_IC, MEGAMORPHIC) \
\
V(KeyedStoreIC_Initialize, KEYED_STORE_IC, UNINITIALIZED) \
V(KeyedStoreIC_Generic, KEYED_STORE_IC, MEGAMORPHIC) \
\
/* Uses KeyedLoadIC_Initialize; must be after in list. */ \
V(FunctionCall, BUILTIN, UNINITIALIZED) \
V(FunctionApply, BUILTIN, UNINITIALIZED)
// Define list of builtins used by the debugger implemented in assembly.
#define BUILTIN_LIST_DEBUG_A(V) \
V(Return_DebugBreak, BUILTIN, DEBUG_BREAK) \
V(Return_DebugBreakEntry, BUILTIN, DEBUG_BREAK) \
V(ConstructCall_DebugBreak, BUILTIN, DEBUG_BREAK) \
V(StubNoRegisters_DebugBreak, BUILTIN, DEBUG_BREAK) \
V(LoadIC_DebugBreak, LOAD_IC, DEBUG_BREAK) \
V(KeyedLoadIC_DebugBreak, KEYED_LOAD_IC, DEBUG_BREAK) \
V(StoreIC_DebugBreak, STORE_IC, DEBUG_BREAK) \
V(KeyedStoreIC_DebugBreak, KEYED_STORE_IC, DEBUG_BREAK)
// Define list of builtins implemented in JavaScript.
#define BUILTINS_LIST_JS(V) \
V(EQUALS, 1) \
V(STRICT_EQUALS, 1) \
V(COMPARE, 2) \
V(ADD, 1) \
V(SUB, 1) \
V(MUL, 1) \
V(DIV, 1) \
V(MOD, 1) \
V(INC, 0) \
V(DEC, 0) \
V(BIT_OR, 1) \
V(BIT_AND, 1) \
V(BIT_XOR, 1) \
V(UNARY_MINUS, 0) \
V(BIT_NOT, 0) \
V(SHL, 1) \
V(SAR, 1) \
V(SHR, 1) \
V(DELETE, 1) \
V(IN, 1) \
V(INSTANCE_OF, 1) \
V(GET_KEYS, 0) \
V(FILTER_KEY, 1) \
V(CALL_NON_FUNCTION, 0) \
V(TO_OBJECT, 0) \
V(TO_NUMBER, 0) \
V(TO_STRING, 0) \
V(APPLY_PREPARE, 1) \
V(APPLY_OVERFLOW, 1)
class ObjectVisitor;
class Builtins : public AllStatic {
public:
// Generate all builtin code objects. Should be called once during
// VM initialization.
static void Setup(bool create_heap_objects);
static void TearDown();
// Garbage collection support.
static void IterateBuiltins(ObjectVisitor* v);
// Disassembler support.
static const char* Lookup(byte* pc);
enum Name {
#define DEF_ENUM_C(name) name,
#define DEF_ENUM_A(name, kind, state) name,
BUILTIN_LIST_C(DEF_ENUM_C)
BUILTIN_LIST_A(DEF_ENUM_A)
BUILTIN_LIST_DEBUG_A(DEF_ENUM_A)
#undef DEF_ENUM_C
#undef DEF_ENUM_A
builtin_count
};
enum CFunctionId {
#define DEF_ENUM_C(name) c_##name,
BUILTIN_LIST_C(DEF_ENUM_C)
#undef DEF_ENUM_C
cfunction_count
};
enum JavaScript {
#define DEF_ENUM(name, ignore) name,
BUILTINS_LIST_JS(DEF_ENUM)
#undef DEF_ENUM
id_count
};
static Code* builtin(Name name) {
// Code::cast cannot be used here since we access builtins
// during the marking phase of mark sweep. See IC::Clear.
return reinterpret_cast<Code*>(builtins_[name]);
}
static Address builtin_address(Name name) {
return reinterpret_cast<Address>(&builtins_[name]);
}
static Address c_function_address(CFunctionId id) {
return c_functions_[id];
}
static const char* GetName(JavaScript id) { return javascript_names_[id]; }
static int GetArgumentsCount(JavaScript id) { return javascript_argc_[id]; }
static Handle<Code> GetCode(JavaScript id, bool* resolved);
static int NumberOfJavaScriptBuiltins() { return id_count; }
static Object* builtin_passed_function;
private:
// The external C++ functions called from the code.
static Address c_functions_[cfunction_count];
// Note: These are always Code objects, but to conform with
// IterateBuiltins() above which assumes Object**'s for the callback
// function f, we use an Object* array here.
static Object* builtins_[builtin_count];
static const char* names_[builtin_count];
static const char* javascript_names_[id_count];
static int javascript_argc_[id_count];
static void Generate_Adaptor(MacroAssembler* masm, CFunctionId id);
static void Generate_JSConstructCall(MacroAssembler* masm);
static void Generate_JSEntryTrampoline(MacroAssembler* masm);
static void Generate_JSConstructEntryTrampoline(MacroAssembler* masm);
static void Generate_ArgumentsAdaptorTrampoline(MacroAssembler* masm);
static void Generate_FunctionCall(MacroAssembler* masm);
static void Generate_FunctionApply(MacroAssembler* masm);
};
} } // namespace v8::internal
#endif // V8_BUILTINS_H_
| [
"noel.gordon@07704840-8298-11de-bf8c-fd130f914ac9"
]
| [
[
[
1,
217
]
]
]
|
1be8fe79b85cc819285d159940477930e7e86d45 | d68d288de8b1643d92af2d339f1a3a8dcfc37015 | /Poker.Equity.Test/stdafx.cpp | 4aa648759fb46554e4f57dc02ff3e374dcf79817 | []
| no_license | tonetheman/poker-code | c8574084be9a85edfbc439fe16ace7eca9f64445 | 50e0e43b859aa23dd4d4eb5a802c7fc95c6e77d6 | refs/heads/master | 2016-09-01T22:30:58.854343 | 2009-04-20T12:25:20 | 2009-04-20T12:25:20 | 180,739 | 7 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,304 | cpp | ///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2009 James Devlin
//
// DISCLAIMER OF WARRANTY
//
// This source code is provided "as is" and without warranties as to performance
// or merchantability. The author and/or distributors of this source code may
// have made statements about this source code. Any such statements do not
// constitute warranties and shall not be relied on by the user in deciding
// whether to use this source code.
//
// This source code is provided without any express or implied warranties
// whatsoever. Because of the diversity of conditions and hardware under which
// this source code may be used, no warranty of fitness for a particular purpose
// is offered. The user is advised to test the source code thoroughly before
// relying on it. The user must assume the entire risk of using the source code.
//
///////////////////////////////////////////////////////////////////////////////
// stdafx.cpp : source file that includes just the standard includes
// Poker.Equity.Test.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
| [
"agcc@agcc-ubuntu.(none)"
]
| [
[
[
1,
28
]
]
]
|
29c1b91c85ceaa09068419ce0c3782f33ca2bb72 | 28476e6f67b37670a87bfaed30fbeabaa5f773a2 | /src/test/TypeInjectionTest.cpp | 933ccf66aa39b2f2e67c2bef9a93a8f4016b0c26 | []
| no_license | rdmenezes/autumnframework | d1aeb657cd470b67616dfcf0aacdb173ac1e96e1 | d082d8dc12cc00edae5f132b7f5f6e0b6406fe1d | refs/heads/master | 2021-01-20T13:48:52.187425 | 2008-07-17T18:25:19 | 2008-07-17T18:25:19 | 32,969,073 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,355 | cpp |
#include <cmath>
#include "TypeInjectionTest.h"
#include "IBasicTypesBean.h"
#include "IMultiBase.h"
extern char TestConFile[];
void TypeInjectionTest::setUp()
{
this->bf = Autumn::getBeanFactoryWithXML(TestConFile);
}
void TypeInjectionTest::tearDown()
{
Autumn::deleteBeanFactory(this->bf);
}
void TypeInjectionTest::testBasicType()
{
IBasicTypesBean* b = (IBasicTypesBean*)this->bf->getBean("BasicTypesBean1");
CPPUNIT_ASSERT(b->getChar() == 'c');
CPPUNIT_ASSERT(b->getUChar() == 'u');
CPPUNIT_ASSERT(b->getShort() == 123);
CPPUNIT_ASSERT(b->getUShort() == 65530);
CPPUNIT_ASSERT(b->getInt() == 70000);
CPPUNIT_ASSERT(b->getUInt() == 77777);
CPPUNIT_ASSERT(b->getLong() == 8000000);
CPPUNIT_ASSERT(b->getULong() == 4294967295);
CPPUNIT_ASSERT( fabs(b->getFloat() - 1.234567) < 1e-7);
CPPUNIT_ASSERT( fabs(b->getDouble() - 1.23456789012345) < 1e-15);
CPPUNIT_ASSERT(b->getString().compare("hello, String") == 0 );
CPPUNIT_ASSERT(strcmp(b->getCStr(), "hello, CStr") == 0);
CPPUNIT_ASSERT(strcmp((const char*)b->getUCStr(), "hello, UCStr") == 0);
this->bf->freeBean(b);
b = (IBasicTypesBean*)this->bf->getBean("BasicTypesBean2");
CPPUNIT_ASSERT(b->getChar() == 'c');
CPPUNIT_ASSERT(b->getUChar() == 'u');
CPPUNIT_ASSERT(b->getShort() == 123);
CPPUNIT_ASSERT(b->getUShort() == 65530);
CPPUNIT_ASSERT(b->getInt() == 70000);
CPPUNIT_ASSERT(b->getUInt() == 77777);
CPPUNIT_ASSERT(b->getLong() == 8000000);
CPPUNIT_ASSERT(b->getULong() == 4294967295);
CPPUNIT_ASSERT( fabs(b->getFloat() - 1.234567) < 1e-7);
CPPUNIT_ASSERT( fabs(b->getDouble() - 1.23456789012345) < 1e-15);
CPPUNIT_ASSERT(b->getString().compare("hello, String") == 0 );
CPPUNIT_ASSERT(strcmp(b->getCStr(), "hello, CStr") == 0);
CPPUNIT_ASSERT(strcmp((const char*)b->getUCStr(), "hello, UCStr") == 0);
this->bf->freeBean(b);
}
void TypeInjectionTest::testCombinedType()
{
IBasicTypesBean* b = (IBasicTypesBean*)this->bf->getBean("BasicTypesBean3");
//test pointer type
CPPUNIT_ASSERT(b->getInt() == 70000);
CPPUNIT_ASSERT(strcmp(b->getCStr(), "hello, CStr") == 0);
this->bf->freeBean(b);
}
void TypeInjectionTest::testBeanType()
{
IBasicTypesBean* b = (IBasicTypesBean*)this->bf->getBean("BeanTypeBean1");
CPPUNIT_ASSERT(b->getInt() == 70000);
CPPUNIT_ASSERT(strcmp(b->getCStr(), "hello, CStr for bean4") == 0);
this->bf->freeBean(b);
b = (IBasicTypesBean*)this->bf->getBean("BeanTypeBean2");
CPPUNIT_ASSERT(b->getInt() == 70000);
CPPUNIT_ASSERT(strcmp(b->getCStr(), "hello, CStr") == 0);
this->bf->freeBean(b);
}
void TypeInjectionTest::testSingleton()
{
IBasicTypesBean* b1 = (IBasicTypesBean*)this->bf->getBean("NotSingleton1");
IBasicTypesBean* b2 = (IBasicTypesBean*)this->bf->getBean("NotSingleton1");
b1->setString("I'm changed");
CPPUNIT_ASSERT(b1->getString().compare("I'm changed") == 0);
CPPUNIT_ASSERT(b2->getString().compare("Not Singleton") == 0);
this->bf->freeBean(b1);
this->bf->freeBean(b2);
b1 = (IBasicTypesBean*)this->bf->getBean("SingletonBean1");
b2 = (IBasicTypesBean*)this->bf->getBean("SingletonBean1");
b1->setString("I'm changed");
CPPUNIT_ASSERT(b1->getString().compare("I'm changed") == 0);
CPPUNIT_ASSERT(b2->getString().compare("I'm changed") == 0);
this->bf->freeBean(b1);
this->bf->freeBean(b2);
}
void TypeInjectionTest::testInitDestroyable()
{
IBasicTypesBean* b = (IBasicTypesBean*)this->bf->getBean("InitDestBean1");
IBasicTypesBean* b1 = (IBasicTypesBean*)this->bf->getBean("SingletonBean1");
CPPUNIT_ASSERT(b1->getString().compare("Initialize") == 0);
this->bf->freeBean(b);
CPPUNIT_ASSERT(b1->getString().compare("Destroy") == 0);
}
void TypeInjectionTest::testSelfManage()
{
//can't self managed
//IBasicTypesBean* b = (IBasicTypesBean*)this->bf->getBean("SelfManagedBean1");
//CPPUNIT_ASSERT_NO_THROW(this->bf->freeBean(b));
}
void TypeInjectionTest::testInjectFromLibElse()
{
IBasicTypesBean* b = (IBasicTypesBean*)this->bf->getBean("BeanTypeBean5");
CPPUNIT_ASSERT(b->getInt() == 70021);
CPPUNIT_ASSERT(strcmp(b->getCStr(), "hello, CStr2-1") == 0);
this->bf->freeBean(b);
}
void TypeInjectionTest::testLocalBean()
{
IBasicTypesBean* b = (IBasicTypesBean*)this->bf->getBean("LocalBean1");
CPPUNIT_ASSERT(b->getInt() == 70000);
CPPUNIT_ASSERT(strcmp(b->getCStr(), "hello, Local Bean") == 0);
this->bf->freeBean(b);
}
void TypeInjectionTest::testCustomizedType()
{
IBasicTypesBean* b = (IBasicTypesBean*)this->bf->getBean("MyTypeBean1");
CPPUNIT_ASSERT(b->getInt() == 100);
CPPUNIT_ASSERT(b->getString().compare("Hi, MyData!") == 0);
this->bf->freeBean(b);
}
void TypeInjectionTest::testMultiInherite()
{
IBase1* b1 = (IBase1*)this->bf->getBean("MultiBase", "IBase1");
IBase2* b2 = (IBase2*)this->bf->getBean("MultiBase", "IBase2");
IMulti_Bean* b3 = (IMulti_Bean*)this->bf->getBean("MultiBean1");
IMulti_Bean* b4 = (IMulti_Bean*)this->bf->getBean("MultiBean2");
CPPUNIT_ASSERT(b1->f1() == 1);
CPPUNIT_ASSERT(b2->f2() == 2);
CPPUNIT_ASSERT(b3->getB1() == 1);
CPPUNIT_ASSERT(b3->getB2() == 2);
CPPUNIT_ASSERT(b4->getB1() == 1);
CPPUNIT_ASSERT(b4->getB2() == 2);
this->bf->freeBean(b1);
this->bf->freeBean(b2);
this->bf->freeBean(b3);
this->bf->freeBean(b4);
}
| [
"sharplog@c16174ff-a625-0410-88e5-87db5789ed7d"
]
| [
[
[
1,
163
]
]
]
|
9650e0fd8bd91054913b52296aa076e9dd5b82ad | 0f457762985248f4f6f06e29429955b3fd2c969a | /irrlicht/irrEdit/source/plugins/jz3dplugins/EmptyPluginNode.cpp | 4a1c7e648ae326160ce707ef332dac691d8e4aa2 | []
| no_license | tk8812/ukgtut | f19e14449c7e75a0aca89d194caedb9a6769bb2e | 3146ac405794777e779c2bbb0b735b0acd9a3f1e | refs/heads/master | 2021-01-01T16:55:07.417628 | 2010-11-15T16:02:53 | 2010-11-15T16:02:53 | 37,515,002 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,833 | cpp | #include "EmptyPluginNode.h"
namespace irr
{
namespace scene
{
namespace jz3d
{
const char *CEmptyPluginNode::Name = "CEmptyPluginNode";
CEmptyPluginNode::CEmptyPluginNode(ISceneNode* parent, ISceneManager* mgr, s32 id)
: ISceneNode(parent,mgr,id)
{
#ifdef _DEBUG
setDebugName(CEmptyPluginNode::Name);
#endif
setAutomaticCulling(scene::EAC_OFF);
}
//! pre render event
void CEmptyPluginNode::OnRegisterSceneNode()
{
if (IsVisible)
SceneManager->registerNodeForRendering(this);
ISceneNode::OnRegisterSceneNode();
}
//! render
void CEmptyPluginNode::render()
{
// do nothing
}
//! returns the axis aligned bounding box of this node
const core::aabbox3d<f32>& CEmptyPluginNode::getBoundingBox() const
{
return Box;
}
//! Creates a clone of this scene node and its children.
ISceneNode* CEmptyPluginNode::clone(ISceneNode* newParent, ISceneManager* newManager)
{
if (!newParent) newParent = Parent;
if (!newManager) newManager = SceneManager;
CEmptyPluginNode* nb = new CEmptyPluginNode(newParent,
newManager, ID);
nb->cloneMembers(this, newManager);
nb->Box = Box;
nb->drop();
return nb;
}
void CEmptyPluginNode::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const
{
ISceneNode::serializeAttributes(out, options);
//데이터 쓰기 코드추가
//...
}
//! Reads attributes of the scene node.
void CEmptyPluginNode::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options)
{
//데이터 읽기 코드추가
//...
ISceneNode::deserializeAttributes(in, options);
}
}
}
}
| [
"gbox3d@58f0f68e-7603-11de-abb5-1d1887d8974b"
]
| [
[
[
1,
80
]
]
]
|
34a864e0ee6ccae5e9371684a9778d00a6754205 | 2c5d9e1a28490dce3a19a3fd97a1a478e90f4b9a | /PiraqDriver/piraq.cpp | fccb7442b83f73619461059736aca8067bfa7e3d | []
| no_license | QtWorks/cp2 | 25602bb6ecb9e276e57568b5076b09a551e7eaef | 871344f4f7ee4bb9f05ed35dcfb4ba62b1555dd4 | refs/heads/master | 2021-01-11T04:06:32.283135 | 2009-10-15T16:21:17 | 2009-10-15T16:21:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 35,431 | cpp | /////////////////////////////////////////////////////////////////////////////////////////
// FILE NAME: Piraq.cpp
//
// DESCRIPTION: PIRAQ Class implementation. This class handles the exposed APIs that
// the host application such as LAPXM would use.
//
// PiraqIII Errata
// The option of using a divide by 6 instead of divide by 8 clock for the timers
// does not work because register bits 8 & 9 (Spare0 & Spare1) do not run to the second PLD.
// For this reason the clock (GateClk) to some of the timers (Dealy, TP Width, No of Gates Chan1,
// and No of Gates Chan2) are always set to divide by 8.
//
// The InterPulsePeriod must be a multiple of 8 since the timers use a divide by 8 clock.
//
// The Read & Write timing specified in the DSP code for access to SBRAM, SDRAM, Registers,
// LEDS, PLX chip, Host memory, etc may not be set correctly for a worse case condition.
// Thus this code may not function correctly in every PC.
//
// Data is slightly corrupted when DMAing from SDRAM to PC Host Memory.
// Use a direct copy instead.
//
// Since the PiraqIII board does not support burst reads and writes, a direct copy
// from the PiraqIII board to PC Host Memory is just as fast as DMA.
//
// A DEADLOCK conditions occurs when the DSP is accessing the PC Host Memory via
// the PLX PCI chip while the Host Application is accessing the PiraqIII registers,
// LEDs, Memory, Etc. This is a stated problem in the PLX PCI chip documentation with
// no work around. For this reason, one has to be careful in the code to never allow
// this condition to happen. The deadlock will occur occasionally making it hard to track.
//
// The programmable Altera chip does not contain logic to arbitrate the bus when the DSP
// is trying to access the PLX PCI chip registers such as mailboxes while the Host Application
// is trying to access the PiraqIII registers, LEDS, memory, etc. In this situation,
// addresses and data can be corrupted and the board can lock up. Once again, one must be careful
// to avoid this condition.
//
//
// WRITTEN BY: Coy Chanders - [email protected] - 03-14-02
/////////////////////////////////////////////////////////////////////////////////////////
#include "Piraq.h"
#include "PLX.h"
#include "Control.h"
#include "Hpib.h"
#include "FirFilters.h"
///////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: PIRAQ::PIRAQ()
//
// DESCRIPTION: Constructor
//
// INPUT PARAMETER(s): None
//
// OUTPUT PARAMETER(s): None
//
// RETURN: none
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
PIRAQ::PIRAQ()
{
m_cErrorString[0] = 0;
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: PIRAQ::~PIRAQ()
//
// DESCRIPTION: Destructor - Deletes instances of the other classed that were used
//
// INPUT PARAMETER(s): None
//
// OUTPUT PARAMETER(s): None
//
// RETURN: none
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
PIRAQ::~PIRAQ()
{
delete m_pPLX;
delete m_pControl;
delete m_pHpib;
delete m_pFirFilter;
m_pPiraq_BaseAddress = NULL;
m_pPLX = NULL;
m_pControl = NULL;
m_pHpib = NULL;
m_pFirFilter = NULL;
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: PIRAQ::SetErrorString(char* pErrorString)
//
// DESCRIPTION: Sets the error string
//
// INPUT PARAMETER(s):
// char* pErrorString - Stored error string from last error
//
// OUTPUT PARAMETER(s): None
//
// RETURN: none
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
void PIRAQ::SetErrorString(char* pErrorString)
{
strcpy(m_cErrorString, pErrorString);
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: PIRAQ::GetErrorString(char* pErrorString)
//
// DESCRIPTION: Returns the error string to the host application
//
// INPUT PARAMETER(s): None
//
// OUTPUT PARAMETER(s):
// char* pErrorString - Stored error string from last error
//
// RETURN: none
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
std::string
PIRAQ::GetErrorString()
{
return std::string(m_cErrorString);
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: PIRAQ::Init( unsigned short shVendorID , unsigned short shDeviceID )
//
// DESCRIPTION: Initializes the driver by creating classes to handle the different
// sections of the Piraq board.
//
// PLX Class handles the PLX PCI interface chip
// CONTROL Class handles the Status Registers and the Timers
// HPIB Class handles writing code to the DSP chip
// FIRFILTER Class handles the Fir Filters
//
// m_pPiraq_BaseAddress is the base address of the Piraq Board's registers, timers, etc.
// m_pPLX_BaseAddress is the base address of the PLX chip and it's EPROM
// m_pPCI_Memory is the base address of the CommonBufferMemory used by both the host
// windows application and the Piraq card to pass data back and forth.
// The size of this memory is set in the NT registry and is allocated at boot up.
//
// PIRAQ_MAILBOX2 is written w/m_pCommonBufferAddressOn8MegBounderyUser, base of
// shared memory; this value is also returned by member function GetBuffer(). 11-01-02 mp.
//
// Calculations related to memory allocation were built around the assumption of a single board
// in the system. First pass at multi-board function operational -- return and structure more
// cleanly. 02-18-03 mp.
//
// INPUT PARAMETER(s):
// unsigned short shVendorID - ID used to identify the board
// unsigned short shDeviceID - ID used to identify the board
//
// OUTPUT PARAMETER(s): None
//
// RETURN: error code - 0=OK -1=Error
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY: Milan Pipersky 02-18-03
//
/////////////////////////////////////////////////////////////////////////////////////////
int PIRAQ::Init( unsigned short shVendorID , unsigned short shDeviceID )
{
// Pointers to classes
m_pPLX = NULL;
m_pControl = NULL;
m_pHpib = NULL;
m_pFirFilter = NULL;
static U32 DeviceCount = 0;
// Pointers to memory
m_pPiraq_BaseAddress = NULL;
m_pPLX_BaseAddress = NULL;
m_pPCI_Memory = NULL;
// Create PLX class to gain access to PLX board
m_pPLX = new PLX();
if(m_pPLX == NULL)
{
SetErrorString("Could not instantiate class for PLX board.");
return(-1);
}
// Initialize PLX class
lReturnValue = ((PLX*)m_pPLX)->InitPLX(shVendorID , shDeviceID );
if(lReturnValue != 0)
{
SetErrorString("Could not initialize PLX class.");
return(-1);
}
// Get m_pPiraq_BaseAddress which address the board itself and it's registers
m_pPiraq_BaseAddress = ((PLX*)m_pPLX)->GetPiraqBaseAddress();
if(m_pPiraq_BaseAddress == NULL)
{
SetErrorString("Could not get Piraq base address.");
return(-1);
}
// Get m_pPLX_BaseAddress which address the EPROM
m_pPLX_BaseAddress = ((PLX*)m_pPLX)->GetPLXBaseAddress();
if(m_pPLX_BaseAddress == NULL)
{
SetErrorString("Could not get PLX base address.");
return(-1);
}
// Get m_pPC_BaseAddress which address ??
m_pPC_BaseAddress = ((PLX*)m_pPLX)->GetPCBaseAddress();
if(m_pPC_BaseAddress == NULL)
{
SetErrorString("Could not get PC base address.");
return(-1);
}
// Get m_pPCI_Memory which address the CommonBufferMemory that is shared
// between the Host application and the driver to pass data back and forth
// PCI Memory Structure
//typedef struct _PCI_MEMORY
//{
// U32 UserAddr;
// U32 PhysicalAddr;
// U32 Size;
//} PCI_MEMORY;
m_pPCI_Memory = ((PLX*)m_pPLX)->GetPCIMemoryBaseAddress();
printf("m_pPCI_Memory->UserAddr = 0x%x m_pPCI_Memory->PhysicalAddr = 0x%x m_pPCI_Memory->Size = 0x%x\n", ((PCI_MEMORY*)m_pPCI_Memory)->UserAddr, ((PCI_MEMORY*)m_pPCI_Memory)->PhysicalAddr, ((PCI_MEMORY*)m_pPCI_Memory)->Size);
if(m_pPCI_Memory == NULL)
{
SetErrorString("Could not get PCI Memory base address.");
return(-1);
}
// Check size of CommonBufferMemory to make sure it allocated 8 megabytes
// The size is set in the NT registry
// The PLX PCI chip request allocation of this space at boot up.
// if(((PCI_MEMORY*)m_pPCI_Memory)->Size != 0x1000000) // 16MB total
// if(((PCI_MEMORY*)m_pPCI_Memory)->Size != 0x2000000) // 32MB total: preliminary success
if(((PCI_MEMORY*)m_pPCI_Memory)->Size != 0x3000000) // 48MB total: preliminary success
{
char buf[255];
sprintf(buf,"Set up registry for commonbuffersize! Size is set at %8X",((PCI_MEMORY*)m_pPCI_Memory)->Size);
//SetErrorString("Set HLM\\System\\CurrentControlSet\\Services\\PCI9054\\CommonBufferSize=0x10000000.");
SetErrorString(buf);
return(-1);
}
DeviceCount++; // no error return -- increment device count -- and add 8MB to
// m_pCommonBufferAddressOn8MegBounderyPhysical for each successful instantiation.
// Due to factors of the PLX chip, we had to allocate twice as much memory (16Megabytes)
// and then shift the address to use 8 Megabyes starting at and even 8 Megabyte boundery.
//!!! m_pCommonBufferAddressOn8MegBounderyPhysical = (unsigned long *)((char*)(((PCI_MEMORY*)m_pPCI_Memory)->PhysicalAddr & 0xff800000) + 0x800000);
m_pCommonBufferAddressOn8MegBounderyPhysical
= (unsigned long *)((char*)(((PCI_MEMORY*)m_pPCI_Memory)->PhysicalAddr & 0xff800000)
+ (0x800000*DeviceCount));
unsigned long lDifference
= (unsigned long) m_pCommonBufferAddressOn8MegBounderyPhysical
- (unsigned long) ((PCI_MEMORY*)m_pPCI_Memory)->PhysicalAddr;
m_pCommonBufferAddressOn8MegBounderyUser
= (unsigned long *)((char*)((PCI_MEMORY*)m_pPCI_Memory)->UserAddr + lDifference);
m_lCommonBufferLength = ((PCI_MEMORY*)m_pPCI_Memory)->Size/4/2;
//m_lCommonBufferLength = 0x200000;
// Set the pointer to the PC system memory "CommonBufferMemory" into PLX chip
// This tells the PLX PCI chip to route DSP calls to memory to this address
unsigned long* pPLX_DMPBAM = (unsigned long *)((unsigned char*)m_pPLX_BaseAddress + DMPBAM);
*pPLX_DMPBAM
= (unsigned long)( (*pPLX_DMPBAM & 0x0000FFFF)
| ((unsigned long)m_pCommonBufferAddressOn8MegBounderyPhysical & 0xFFFF0000));
// Set the pointer to "CommonBufferMemory"in PLX chip mailbox 2 for use by DSP program
unsigned long* pPLX_PIRAQ_MAILBOX2
= (unsigned long *)
((unsigned char*)m_pPLX_BaseAddress + PIRAQ_MAILBOX2);
*pPLX_PIRAQ_MAILBOX2
= (unsigned long)
(((unsigned long)m_pCommonBufferAddressOn8MegBounderyPhysical & 0xFFFF0000));
// Set the length in bytes of the "CommonBufferMemory"
unsigned long* pPLX_DMRR = (unsigned long *)((unsigned char*)m_pPLX_BaseAddress + DMRR);
*pPLX_DMRR = 0xff800000;
// Set the address that the DSP will use to write to the "CommonBufferMemory"
// This remaps a constant address for the DSP to a changing address in PC memory
unsigned long* pPLX_DMLBAM
= (unsigned long *)((unsigned char*)m_pPLX_BaseAddress + DMLBAM);
*pPLX_DMLBAM = 0x0;
m_pSemaphores
= (unsigned long *)
((unsigned char*)m_pCommonBufferAddressOn8MegBounderyUser + SEMAPHOREOFFSET);
printf("Device number %d\n", DeviceCount);
printf("PCI memory physical address 0x%08x\n", ((PCI_MEMORY*)m_pPCI_Memory)->PhysicalAddr);
printf("*pPLX_DMPBAM = 0x%x\n", *pPLX_DMPBAM);
printf("m_pCommonBufferAddressOn8MegBounderyPhysical = 0x%08x\n",
m_pCommonBufferAddressOn8MegBounderyPhysical);
printf("lDifference = 0x%x\n", lDifference);
printf("m_pCommonBufferAddressOn8MegBounderyUser = 0x%08x\n",
m_pCommonBufferAddressOn8MegBounderyUser);
printf("m_lCommonBufferLength = 0x%08x\n", m_lCommonBufferLength);
// Create classes
m_pControl = new CONTROL(m_pPiraq_BaseAddress);
m_pHpib = new HPIB(m_pPiraq_BaseAddress);
m_pFirFilter = new FIRFILTER(m_pPiraq_BaseAddress);
// Set up the timer pointer
timer = ((CONTROL *)m_pControl)->GetTimer();
// Set up the FIRCH pointers
FIRCH1_I = GetFilter()->GetFIRCH1_I();
FIRCH1_Q = GetFilter()->GetFIRCH1_Q();
FIRCH2_I = GetFilter()->GetFIRCH2_I();
FIRCH2_Q = GetFilter()->GetFIRCH2_Q();
// Set default PIRAQ Data Mode in MAILBOX5: SEND_COMBINED, execute the dynamic range extension algorithm
unsigned long * pPLX_PIRAQ_MAILBOX5 = (unsigned long *)((unsigned char*)m_pPLX_BaseAddress + PIRAQ_MAILBOX5);
*pPLX_PIRAQ_MAILBOX5 = (unsigned long)SEND_COMBINED;
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: PIRAQ:: GetCommonBufferMemoryPointer()
//
// DESCRIPTION: Returns the virtual address for the common memory used by both
// the PLX PCI chip and the Windows host application. This is how data is passed
// back and forth from the DSP and LAPXM
//
// INPUT PARAMETER(s): None
//
// OUTPUT PARAMETER(s): None
//
// RETURN: m_pPCI_Memory->UserAddr - Virtual address of memory space
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
void PIRAQ::GetCommonBufferMemoryPointer(unsigned long **pCommonMemoryAddress, unsigned long *plLength)
{
// Pass back the address to the common buffer memory.
// This address starts on an even 8 Megabyte boundry.
// To do this, we allocated 16 megabytes of space and chopped out
// the 8 megabytes that started on this boundery
*pCommonMemoryAddress = (unsigned long*)m_pCommonBufferAddressOn8MegBounderyUser;
// Pass back the length to only 8 megabytes in 32 bit words
*plLength = m_lCommonBufferLength;
}
// Used for Testing ***************************
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: PIRAQ::ToggleLED()
//
// DESCRIPTION: Calls on the CONTROL class to toggle the LED
//
// INPUT PARAMETER(s): None
//
// OUTPUT PARAMETER(s): None
//
// RETURN: none
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
void PIRAQ::ToggleLED()
{
((CONTROL*)m_pControl)->ToggleLED();
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: PIRAQ::ReadEPROM(unsigned int * pEPROM)
//
// DESCRIPTION: Returns the values set in the EPROM. Note that some of them have
// been changed in the Init()
//
// INPUT PARAMETER(s): None
//
// OUTPUT PARAMETER(s): None
// unsigned int * pEPROM - Array passed in by host to get the values of the EPROM
//
// RETURN: none
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY: Milan Pipersky 4-19-04 Increase elements transferred from 64 to 128:
// callers must allocate sufficient buffer to accomodate.
//
//
/////////////////////////////////////////////////////////////////////////////////////////
void PIRAQ::ReadEPROM(unsigned int * pEPROM)
{
for(int i=0; i< 128; i++)
{
pEPROM[i] = m_pPLX_BaseAddress[i];
}
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: PIRAQ::PCMemoryTest(unsigned int StartValue)
//
// DESCRIPTION: Writes a pattern to the 8 Megabytes of memory shared by the Piraq and the
// host application. It then reads the pattern back to make sure it was written correctly.
// The host application can then read it back for a second test.
//
// INPUT PARAMETER(s):
// unsigned int StartValue -- test begin data value, incremented for each location.
//
// OUTPUT PARAMETER(s): None
//
// RETURN: error code - 0=OK -1=Error
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY: Milan Pipersky 2-14-03 StartValue set by caller for diagnostic purposes
// and to distinguish cards for shared memory tests.
//
/////////////////////////////////////////////////////////////////////////////////////////
int PIRAQ::PCMemoryTest(unsigned int StartValue)
{
// Write and read back a pattern from the common memory on the PC that is
// used for passing data from the DSP to the Windows application such as Lapxm.
// This memory is allocated on boot up using the following registry entry
// to determine the size. Currently it is set to 8 Megabytes which is 0x7FFFFF
// Get Address to Space
unsigned long * pCommonBufferMemory = m_pCommonBufferAddressOn8MegBounderyUser;
// Get the size in 32bit words
unsigned long lSize = m_lCommonBufferLength;
// Write Pattern
for(unsigned long i = 0; i< lSize; i++) // 256 heights * 4096 points * 2 (I&Q) - 4byte floats
{
// *pCommonBufferMemory = (0x0001 + i);
*pCommonBufferMemory = (StartValue + 4*i);
pCommonBufferMemory = pCommonBufferMemory + 1;
}
// Check Patten
pCommonBufferMemory = m_pCommonBufferAddressOn8MegBounderyUser;
for(unsigned long j = 0; j< lSize; j++)
{
// if(*pCommonBufferMemory != (0x0001 + j))
if(*pCommonBufferMemory != (StartValue + 4*j))
{
// If pattern fails, return error
SetErrorString("Failed PC Memory Test");
return (0);
}
pCommonBufferMemory = pCommonBufferMemory + 1;
}
// If pattern passes, return OK.
// Windows application shoud then test pattern itself
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: PIRAQ::ReturnTimerValues(unsigned int* piCountsPerDelay, unsigned int* piCountsForAllGates,
// unsigned int* piCountsPerGatePulse,unsigned short* piSpare)
//
// DESCRIPTION: Returns to the host the current timer values
//
// INPUT PARAMETER(s): None
//
// OUTPUT PARAMETER(s):
// unsigned int* piCountsPerDelay - Time in clock cycles from start of Sync to start of first sampling gate
// unsigned int* piCountsForAllGates - Time in clock cycles for all sampling gates to happen
// unsigned int* piCountsPerGatePulse - Time in clock cycles from the start of one sampling gate to the start of the next
// unsigned short* piSpare - Value in the upper 16 bits of Status Register 1 that sets the decimation rate
//
// RETURN: none
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
void PIRAQ::ReturnTimerValues(unsigned int* piCountsPerDelay, unsigned int* piCountsForAllGates,
unsigned int* piCountsPerGatePulse,unsigned short* piStatus0,unsigned short* piStatus1)
{
((CONTROL*)m_pControl)->ReturnTimerValues(piCountsPerDelay, piCountsForAllGates, piCountsPerGatePulse,piStatus0,piStatus1);
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: PIRAQ::ReturnFilterValues(unsigned short *pFIR, unsigned int* piCount)
//
// DESCRIPTION: Returns to the host application the current Fir Filter values.
//
// INPUT PARAMETER(s): None
//
// OUTPUT PARAMETER(s):
// unsigned short *pFIR - An array to hold the Fir Filter values
// unsigned int* piCount - The number of values
//
// RETURN: none
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
void PIRAQ::ReturnFilterValues(unsigned short *pFIR, unsigned int* piCount)
{
((FIRFILTER*)m_pFirFilter)->ReturnFilterValues(pFIR, piCount);
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: PIRAQ::ResetPiraq()
//
// DESCRIPTION: Calls on the CONTROL class to put the DSP in a known state
//
// INPUT PARAMETER(s): None
//
// OUTPUT PARAMETER(s): None
//
// RETURN: none
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
void PIRAQ::ResetPiraq()
{
((CONTROL*)m_pControl)->ResetPiraqBoard();
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: PIRAQ::LoadDspCode(char* pFilePathAndName)
//
// DESCRIPTION: Loads COFF type 2 code into the DSP
//
// INPUT PARAMETER(s):
// char* pFilePathAndName - Full path and file name of COFF type 2 code to load into the DSP
//
// OUTPUT PARAMETER(s): None
//
// RETURN: error code - 0=OK -1=Error
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
int PIRAQ::LoadDspCode(char* pFilePathAndName)
{
char cErrorString[256];
lReturnValue = ((HPIB*)m_pHpib)->coffload(pFilePathAndName, cErrorString);
if(lReturnValue != 0)
{
if(lReturnValue == -1)
{
SetErrorString(cErrorString);
return (-1);
}
}
return (0);
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: PIRAQ::StartDsp()
//
// DESCRIPTION: Calls on the HPIB class to start the DSP
//
// INPUT PARAMETER(s): None
//
// OUTPUT PARAMETER(s): None
//
// RETURN: none
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
void PIRAQ::StartDsp()
{
((HPIB*)m_pHpib)->StartDsp();
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: PIRAQ::LoadParameters(float fFrequencyHz, long lTransmitPulseWidthNs,
// long lPreTRNs, long lTimeDelayToFirstGateNs,
// long lGateSpacingNs, long lNumRangeGates,
// long lNumCodeBits, long lNumCoherentIntegrations,
// long lNumPointsInSpectrum,int iFilterType)
//
// DESCRIPTION: Receives the parameters from the host application and used them to
// set up the timers, the filters, and the DSP.
//
// INPUT PARAMETER(s):
// float fFrequencyHz - Piraq Clock Frequency in Hz
// long lTransmitPulseWidthNs - Width of the Transmit pulse in nanoseconds
// long lPreTRNs - Time from start of Sync pulse to start of Transmit pulse in nanoseconds
// long lTimeDelayToFirstGateNs - Time from end of Transmit pulse to start of first sampling gate in nanoseconds
// long lGateSpacingNs - Time from one sampling gate to the next in nanoseconds
// long lNumRangeGates - Number of sampling gates (Nhts)
// long lNumCodeBits - Number of code bits used in coding (NCode)
// long lNumCoherentIntegrations - Number of coherent integrations used (NCI)
// long lNumPointsInSpectrum - Number of FFTS used (Npts)
// int iFilterType - 0=Gausian - 1=Half Bandwidth
// OUTPUT PARAMETER(s): None
//
// RETURN: none
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
void PIRAQ::LoadParameters(float fFrequencyHz, long lTransmitPulseWidthNs,
long lPreTRNs, long lTimeDelayToFirstGateNs,
long lGateSpacingNs, long lNumRangeGates,
long lNumCodeBits, long lNumCoherentIntegrations,
long lNumPointsInSpectrum, long lNumReceivers,
int iTimerDivide, int iFilterType, long lFlip)
{
// Transmit Pulse Width must be at least 300ns
if(lTransmitPulseWidthNs < 300)
{
// Defualt to 300
lTransmitPulseWidthNs = 300;
}
// Convert lTransmitPulseWidthNs & iGateSpacingClockCycles into the correct multiple of the clock
int iGateSpacingClockCycles = (int)( lGateSpacingNs * 1e-9 * fFrequencyHz + .5 );
int iTransmitPulseWidthClockCycles = (int)( lTransmitPulseWidthNs * 1e-9 * fFrequencyHz + .5 );
// Calculate new Pulse Width and GateSpacing
lGateSpacingNs = (long)(iGateSpacingClockCycles * (1e9/fFrequencyHz));
lTransmitPulseWidthNs = (long)(iTransmitPulseWidthClockCycles * (1e9/fFrequencyHz));
if ( lTransmitPulseWidthNs < 1000 /*ns*/)
{
// GateSpacing and TX must be an even number of clock cycles due to the fact that
// the GLEN counter holds only one half of the GateSpacing. Thus GateSpacing is forced
// to be an even multiple of 2.
if(iGateSpacingClockCycles & 0x1)
{
iGateSpacingClockCycles = iGateSpacingClockCycles + (iGateSpacingClockCycles % 2);
}
lGateSpacingNs = (long)(iGateSpacingClockCycles * (1e9/fFrequencyHz));
if(iTransmitPulseWidthClockCycles & 0x1)
{
iTransmitPulseWidthClockCycles = iTransmitPulseWidthClockCycles + (iTransmitPulseWidthClockCycles % 2);
}
lTransmitPulseWidthNs = (long)(iTransmitPulseWidthClockCycles * (1e9/fFrequencyHz));
}
else if ( (lTransmitPulseWidthNs >= 1000 /*ns*/) && (lTransmitPulseWidthNs < 2000 /*ns*/) )
{
// GateSpacing and TX must be an even multiple of 4 clock cycles due to decimation or 2
// and the GLEN counter divides the count in half
if(iGateSpacingClockCycles % 4)
{
iGateSpacingClockCycles = iGateSpacingClockCycles + (iGateSpacingClockCycles % 4);
}
lGateSpacingNs = (long)(iGateSpacingClockCycles * (1e9/fFrequencyHz));
if(iTransmitPulseWidthClockCycles % 4)
{
iTransmitPulseWidthClockCycles = iTransmitPulseWidthClockCycles + (iTransmitPulseWidthClockCycles % 4);
}
lTransmitPulseWidthNs = (long)(iTransmitPulseWidthClockCycles * (1e9/fFrequencyHz));
}
else if ( lTransmitPulseWidthNs >= 2000 /*ns*/ )
{
// GateSpacing and TX must be an even multiple of 4 clock cycles due to decimation or 4
// and the GLEN counter divides the count in half
if(iGateSpacingClockCycles % 8)
{
iGateSpacingClockCycles = iGateSpacingClockCycles + (8 - (iGateSpacingClockCycles % 8));
}
lGateSpacingNs = (long)(iGateSpacingClockCycles * (1e9/fFrequencyHz));
if(iTransmitPulseWidthClockCycles % 8)
{
iTransmitPulseWidthClockCycles = iTransmitPulseWidthClockCycles + (8 - (iTransmitPulseWidthClockCycles % 8));
}
lTransmitPulseWidthNs = (long)(iTransmitPulseWidthClockCycles * (1e9/fFrequencyHz));
}
// Only divide by 8 supported at this time
if(iTimerDivide != 8)
{
iTimerDivide = 8;
}
// Set up the timers
((CONTROL*)m_pControl)->SetUpTimers(fFrequencyHz, lTransmitPulseWidthNs, lPreTRNs,
lTimeDelayToFirstGateNs, lGateSpacingNs, lNumRangeGates,
iTimerDivide, iGateSpacingClockCycles,lNumCodeBits);
// Only Gaussian filter supported at this time
if(iFilterType != 0)
{
iFilterType = 0;
}
// Set up the Fir Filters
if(iFilterType == 1)
{
// Half Band Width Filter
((FIRFILTER*)m_pFirFilter)->FIR_HalfBandWidth(fFrequencyHz, lTransmitPulseWidthNs, lNumCodeBits);
}
else if(iFilterType == 2)
{
// Box Car Filter
((FIRFILTER*)m_pFirFilter)->FIR_BoxCar(fFrequencyHz, lTransmitPulseWidthNs, lNumCodeBits);
}
else
{
// Defualt
// Gaussian Filter
((FIRFILTER*)m_pFirFilter)->Gaussian(fFrequencyHz, lTransmitPulseWidthNs, lNumCodeBits);
}
// Write parameters to the CommonBufferMemory so that the DSP can read them in
// Get Address to Space
volatile int * pParameters;
pParameters = (volatile int *)((char*)m_pCommonBufferAddressOn8MegBounderyUser + PARAMETEROFFSET);
pParameters[NUMCODEBITS] = lNumCodeBits;
pParameters[NUMCOHERENTINTEGRATIONS] = lNumCoherentIntegrations;
pParameters[NUMRANGEGATES] = lNumRangeGates;
pParameters[NUMPOINTSINSPECTRUM] = lNumPointsInSpectrum;
pParameters[NUMRECEIVERS] = lNumReceivers;
pParameters[FLIP] = lFlip;
((CONTROL*)m_pControl)->StartTimers();
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: PIRAQ::LoadFIRParameters(float sp_fFrequencyHz, long sp_lTransmitPulseWidthNs,
// long sp_lNumCodeBits)
//
// DESCRIPTION: Receives the parameters from the host application and used them to
// set up the timers, the filters, and the DSP.
//
// INPUT PARAMETER(s):
// float sp_fFrequencyHz - Piraq Clock Frequency in Hz
// long sp_lTransmitPulseWidthNs - Width of the Transmit pulse in nanoseconds
// long sp_lNumCodeBits - Number of code bits used in coding (NCode)
// OUTPUT PARAMETER(s): None
//
// RETURN: none
//
// WRITTEN BY: Milan Pipersky 11-21-02. Temporary member function until PIRAQ::LoadParameters fully implemented.
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
void PIRAQ::LoadFIRParameters(float sp_fFrequencyHz, long sp_lTransmitPulseWidthNs, long sp_lNumCodeBits)
{
// Defualt
// Gaussian Filter
((FIRFILTER*)m_pFirFilter)->Gaussian(sp_fFrequencyHz, sp_lTransmitPulseWidthNs, sp_lNumCodeBits);
//?que es? pParameters[FLIP] = lFlip;
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: PIRAQ::StopDsp()
//
// DESCRIPTION: Calls on the Control class to perform a Software Reset
//
// INPUT PARAMETER(s): None
//
// OUTPUT PARAMETER(s): None
//
// RETURN: none
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
void PIRAQ::StopDsp()
{
((CONTROL*)m_pControl)->StopDsp();
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: PIRAQ:: SemaSet(int iSemaphore)
//
// DESCRIPTION: Sets the value of the semaphore in local PC memory for the DSP to read.
// Interupts the DSP so that it will read the semaphore and move on.
//
// INPUT PARAMETER(s):
// int iSemaphore - Value of semaphore to set into memory
//
// OUTPUT PARAMETER(s): None
//
// RETURN: long - not used at this time
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
long PIRAQ::SemaSet(int iSemaphore)
{
// Set semaphore value
m_pSemaphores[0] = iSemaphore;
// Interupt DSP so that it will know a semaphore has been set.
((CONTROL*)m_pControl)->InteruptDSP();
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: PIRAQ::SemaWait(int iSemaphore, int iTimeOutInSeconds)
//
// DESCRIPTION: Waits for the DSP to set a semaphore to indicate the code can move on.
//
// INPUT PARAMETER(s):
// int iSemaphore - Value of semaphore we are looking for
// int iTimeOutInSeconds - Time in seconds to wait for semaphore
//
// OUTPUT PARAMETER(s): None
//
// RETURN: long - 0 if semaphore was received in time. -1 if not.
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
long PIRAQ::SemaWait(int iSemaphore, int iTimeOutInMiliSeconds)
{
int iCount = 0;
int iMaxCount = (int)ceil((iTimeOutInMiliSeconds)/(float)10);
// Read first
while((m_pSemaphores[0] != (unsigned int)iSemaphore) && (iCount <iMaxCount) )
{
// If value has not been set yet, wait 1/100th of a second and check again
Sleep(10);
iCount++;
}
// Did we time out
if( iCount >= iMaxCount)
{
return -1;
}
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: PIRAQ::SetPMACAntennaDPRAMAddress(unsigned int * PMACAntennaDPRAMAddress)
//
// DESCRIPTION: Set PMAC Dual-Port RAM base address in PIRAQ Mailbox 4.
//
// INPUT PARAMETER(s):
// unsigned int * PMACAntennaDPRAMAddress
//
// OUTPUT PARAMETER(s): None
//
// RETURN: none.
//
// WRITTEN BY: Milan Pipersky 4-23-04
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
void PIRAQ::SetPMACAntennaDPRAMAddress(unsigned int * PMACAntennaDPRAMAddress)
{
// Compute pointer to PIRAQ mailbox 4; put passed address there
unsigned long * pPLX_PIRAQ_MAILBOX4 = (unsigned long *)((unsigned char*)(GetRegisterBase()) + PIRAQ_MAILBOX4);
*pPLX_PIRAQ_MAILBOX4 = (unsigned long)PMACAntennaDPRAMAddress;
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: PIRAQ::GetPMACAntennaDPRAMAddress(unsigned int * PMACAntennaDPRAMAddress)
//
// DESCRIPTION: Get PMAC Dual-Port RAM base address from PIRAQ Mailbox 4.
//
// INPUT PARAMETER(s): None
//
// OUTPUT PARAMETER(s): None
// unsigned int * PMACAntennaDPRAMAddress
//
// RETURN: none.
//
// WRITTEN BY: Milan Pipersky 4-23-04
//
// LAST MODIFIED BY: Milan Pipersky 3-10-06
//
/////////////////////////////////////////////////////////////////////////////////////////
unsigned int * PIRAQ::GetPMACAntennaDPRAMAddress()
{
// Compute pointer to PIRAQ mailbox 4; get PMAC DPRAM address stored there for PIRAQ use
unsigned long * pPLX_PIRAQ_MAILBOX4 = (unsigned long *)((unsigned char*)(GetRegisterBase()) + PIRAQ_MAILBOX4);
unsigned int * PIRAQ_PMACDPRAM = (unsigned int *)*pPLX_PIRAQ_MAILBOX4;
return(PIRAQ_PMACDPRAM);
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: PIRAQ::SetCP2PIRAQTestAction(unsigned short PIRAQTestAction)
//
// DESCRIPTION: Set PIRAQ channel mode in PIRAQ Mailbox 5.
// 3 modes of data transfer from PIRAQ to host: first 2 are diagnostic
// SEND_CHA // send CHA
// SEND_CHB // send CHB
// SEND_COMBINED // execute dynamic-range extension algorithm; send resulting
// combined data
// // PIRAQ DATA TEST-SINUSOID ADJUSTMENTS: step frequency or amplitude
// INCREMENT_TEST_SINUSIOD_COARSE
// INCREMENT_TEST_SINUSIOD_FINE
// DECREMENT_TEST_SINUSIOD_COARSE
// DECREMENT_TEST_SINUSIOD_FINE
// INCREMENT_TEST_AMPLITUDE_COARSE
// INCREMENT_TEST_AMPLITUDE_FINE
// DECREMENT_TEST_AMPLITUDE_COARSE
// DECREMENT_TEST_AMPLITUDE_FINE
// Definitions are in proto.h also for time being.
//
// INPUT PARAMETER(s):
// unsigned short PIRAQTestAction
//
// OUTPUT PARAMETER(s): None
//
// RETURN: none.
//
// WRITTEN BY: Milan Pipersky 2-23-06
//
// LAST MODIFIED BY: Milan Pipersky 3-10-06
//
/////////////////////////////////////////////////////////////////////////////////////////
void PIRAQ::SetCP2PIRAQTestAction(unsigned short PIRAQTestAction)
{
// Compute pointer to PIRAQ mailbox 5; put PIRAQ test parameter there
unsigned long * pPLX_PIRAQ_MAILBOX5 = (unsigned long *)((unsigned char*)(GetRegisterBase()) + PIRAQ_MAILBOX5);
*pPLX_PIRAQ_MAILBOX5 = (unsigned long)PIRAQTestAction;
}
| [
"martinc@e5e72e4b-7c09-0410-958a-85c34e28b278",
"milan@e5e72e4b-7c09-0410-958a-85c34e28b278"
]
| [
[
[
1,
955
],
[
970,
991
]
],
[
[
956,
969
]
]
]
|
7b8ab879848e70122adb273460c0f27297a6a81e | 080941f107281f93618c30a7aa8bec9e8e2d8587 | /src/conditioners/optimizer_core.cpp | 3a4a1c2021047dead3077bd8ab83d28b9704b841 | [
"MIT"
]
| permissive | scoopr/COLLADA_Refinery | 6d40ee1497b9f33818ec1e71677c3d0a0bf8ced4 | 3a5ad1a81e0359f9025953e38e425bc10b5bf6c5 | refs/heads/master | 2021-01-22T01:55:14.642769 | 2009-03-10T21:31:04 | 2009-03-10T21:31:04 | 194,828 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,036 | cpp | /*
The MIT License
Copyright 2006 Sony Computer Entertainment Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "optimizer.h"
bool Optimizer::init()
{
addBoolOption( "verbose", "verbose", "verbose", true);
addFloatOption( "c", "cache_size", "cache_size", 10);
return true;
}
int Optimizer::execute()
{
float cache_size;
bool verbose = false;
getBoolOption("v", verbose);
getFloatOption("c", cache_size);
int error = 0;
// How many geometry elements are there?
unsigned int geometryElementCount = _dae->getDatabase()->getElementCount(NULL, "geometry", getInput(0).c_str());
// if(verbose) cerr<<"There are "<<geometryElementCount<<" geometry elements in this file\n";
// Iterate over all the geometry elements, each one is optimized individually
for(unsigned int currentGeometry = 0; currentGeometry < geometryElementCount; currentGeometry++)
{
// Get the next geometry element
domGeometry *thisGeometry;
error = _dae->getDatabase()->getElement((daeElement**)&thisGeometry,currentGeometry, NULL, "geometry", getInput(0).c_str());
// Get the geometry element's mesh
domMesh *thisMesh = thisGeometry->getMesh();
if (thisMesh==NULL) continue; // if there is no mesh in geometry, skip to the next one
// Loop over all the triangle elements in this mesh
int trianglesElementCount = (int)(thisMesh->getTriangles_array().getCount());
// if(verbose) cerr<<"There are "<<trianglesElementCount<<" triangle elements in this geometry\n";
for(int currentTriangles = 0; currentTriangles < trianglesElementCount; currentTriangles++)
{
// Get the next triangles out of the mesh
domTriangles *thisTriangles = thisMesh->getTriangles_array().get(currentTriangles);
// Get count of inputs and primitives
// Remember that for triangles a <p> tag can contain multiple triangles
// find the max input offset, 0 start
unsigned int inputCount = (unsigned int)(thisTriangles->getInput_array().getCount());
unsigned int maxinputoffset = 0;
for (unsigned int i=0; i < inputCount; i++)
{
unsigned int thisinputoffset = (unsigned int ) thisTriangles->getInput_array()[i]->getOffset();
if (maxinputoffset < thisinputoffset) maxinputoffset = thisinputoffset;
}
maxinputoffset++; // make it 1 start
unsigned int numberOfPrimitives = (unsigned int )(thisTriangles->getCount());
// Make a new vertex cache
vertexCache beforeCache((int) cache_size);
unsigned int totalVertices = 0;
list<simpleTriangle> inputTriangles;
list<simpleTriangle> outputTriangles;
// Iterate over all the primitives and save them in "inputTriangles"
for(unsigned int currentPrimitive = 0; currentPrimitive < numberOfPrimitives; currentPrimitive++)
{
unsigned int currentTriangleIndex = currentPrimitive * 3 * maxinputoffset;
// Simulate operation of a vertex cache, the file has already been deindexed
// so we only look at the first index of each vertex, all the others will be the same
simpleTriangle aTriangle;
for(unsigned int currentIndex = 0; currentIndex < 3; currentIndex++)
{
domPRef P = thisTriangles->getP();
domListOfUInts Plist = P->getValue();
// unsigned int count = (unsigned int ) Plist.getCount();
unsigned int Pindex = currentTriangleIndex + currentIndex * maxinputoffset;
unsigned int Pvalue = (unsigned int ) Plist[Pindex];
aTriangle.indices[currentIndex] = Pvalue;
beforeCache.addVertex(Pvalue);
// aTriangle.indices[currentIndex] = thisTriangles->getP()->getValue()[currentTriangleIndex + currentIndex*inputCount];
// beforeCache.addVertex(thisTriangles->getP()->getValue()[currentTriangleIndex + currentIndex*inputCount]);
totalVertices++;
}
inputTriangles.push_back(aTriangle);
}
// if(verbose) cerr<<"Triangles "<<currentTriangles<< " had "<<beforeCache.cacheHits<<" cache hits and "<<beforeCache.cacheMisses<<" misses "<<((float)beforeCache.cacheHits/(float)totalVertices)*100.0<<"% hit rate\n";
// This is a simple cache optimizer, it finds the triangle with the lowest cache cost and moves to the
// output triangles array, updating the cache in the process.
vertexCache afterCache((int) cache_size);
// Move the first triangle over to the output array to "seed" the cache
outputTriangles.push_back(*(inputTriangles.begin()));
inputTriangles.pop_front();
afterCache.addTriangle(*(outputTriangles.begin()));
// Repeatedly scan the input array for the lowest cost triangle and move it
// Worst case this is an n-squared loop but there are some short cuts for
// triangles that are totally in-cache.
while(inputTriangles.size() > 0)
{
int lowestCost = 999;
int cost;
list<simpleTriangle>::iterator lowestCostTri;
// Scan the remaining input triangles to find the lowest cost one
for(list<simpleTriangle>::iterator tri = inputTriangles.begin(); tri != inputTriangles.end(); )
{
cost=afterCache.costTriangle(*tri);
if(cost < lowestCost)
{
if(cost == 0)
{
// Triangles with zero cost should be moved to output immediately as they don't change the state of the
// cache or the cost of any unprocessed triangles.
afterCache.addTriangle(*tri);
outputTriangles.push_back(*tri);
tri = inputTriangles.erase(tri);
continue;
}
lowestCostTri = tri;
lowestCost = cost;
}
tri++;
}
// Move the lowest cost triangle over to the output array.
// If there were multiple triangles of cost 1, it might result in better optimization to find
// what vertex appears the most and add those triangles first. This could be done by tracking
// the most frequently missed vertex and adding that vertex to the cache, on the next pass through
// this loop all the triangles containing that vertex would have a cost of 0 and be added all at once.
if(lowestCost != 999)
{
afterCache.addTriangle(*lowestCostTri);
outputTriangles.push_back(*lowestCostTri);
inputTriangles.erase(lowestCostTri);
}
}
// if(verbose) cerr<<"Triangles "<<currentTriangles<< " had "<<afterCache.cacheHits<<" cache hits and "<<afterCache.cacheMisses<<" misses "<<((float)afterCache.cacheHits/(float)totalVertices)*100.0<<"% hit rate\n";
// Rewrite the new order to the output file, this updates it in place
for(unsigned int currentPrimitive = 0; currentPrimitive < numberOfPrimitives; currentPrimitive++)
{
unsigned int currentTriangleIndex = currentPrimitive * 3 * maxinputoffset;
for(unsigned int currentIndex = 0; currentIndex < 3; currentIndex++)
{
unsigned int anIndex = (*(outputTriangles.begin())).indices[currentIndex];
for(unsigned int iCount = 0; iCount < maxinputoffset; iCount++)
{
thisTriangles->getP()->getValue()[currentTriangleIndex + ((currentIndex*maxinputoffset)+iCount)] = anIndex;
}
}
outputTriangles.pop_front();
}
}
}
return 0;
}
Conditioner::Register<OptimizerProxy> opimizerProxy;
| [
"alorino@7d79dae2-2c22-0410-a73c-a02ad39e49d4",
"sceahklaw@7d79dae2-2c22-0410-a73c-a02ad39e49d4",
"hnz@7d79dae2-2c22-0410-a73c-a02ad39e49d4"
]
| [
[
[
1,
1
],
[
23,
98
],
[
100,
178
]
],
[
[
2,
22
]
],
[
[
99,
99
],
[
179,
179
]
]
]
|
7de6296ff5fdd6360e3a133c0950141a476e8c95 | 3d873b9abae5014a271615d94d7c445d0e15b52d | /MsiOpenPackage/MsiOpenPackage/MsiOpenPackage.cpp | a91b8580b3898e7fc19be5c945222020862fa928 | []
| no_license | hacker-chandan/codeproject | c26b6a906cd66714964e31c0b3c5775f72565220 | c65cdd702701e2766feb3114b64455763fa4bbe0 | refs/heads/master | 2021-05-27T11:23:59.870263 | 2010-12-03T15:32:51 | 2010-12-03T15:32:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,988 | cpp | // MsiOpenPackage.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
struct MsiDatabaseSummaryEntry
{
DWORD dwPropertyId; // see http://msdn.microsoft.com/en-us/library/aa372045(VS.85).aspx
VARENUM varPropertyType;
CComVariant varValue;
};
std::wstring FormatMessageFromHRW(HRESULT hr)
{
std::wstring result;
LPWSTR lpMsgBuf = NULL;
DWORD rc = 0;
rc = ::FormatMessageW(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
hr,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
reinterpret_cast<LPWSTR>(& lpMsgBuf),
0,
NULL );
if (rc != 0)
{
result = lpMsgBuf;
}
else
{
std::wstringstream result_s;
result_s << L"0x" << std::hex << hr;
result = result_s.str();
}
return result;
}
int _tmain(int argc, _TCHAR* argv[])
{
::CoInitialize(NULL);
// create an empty MSI
MSIHANDLE hDB = NULL;
wchar_t * lpszFilename = L"C:\\temp\\MsiOpenPackage.msi";
DWORD dwError = 0;
if (0 != (dwError = ::MsiOpenDatabase(lpszFilename, MSIDBOPEN_CREATEDIRECT, & hDB)))
{
std::wcerr << L"Error creating: " << lpszFilename << L": 0x" << std::hex << HRESULT_FROM_WIN32(dwError)
<< L" " << FormatMessageFromHRW(HRESULT_FROM_WIN32(dwError));
return dwError;
}
// set summary information
MsiDatabaseSummaryEntry summary[] =
{
{ PID_TITLE, VT_LPSTR, L"MSI Shim Database" },
{ PID_SUBJECT, VT_LPSTR, L"MSI Shim Database" },
{ PID_AUTHOR, VT_LPSTR, L"dB." },
{ PID_TEMPLATE, VT_LPSTR, ";1033" },
{ PID_REVNUMBER, VT_LPSTR, "{00869AA3-A32E-4398-89B2-5C5DC7328C7C}" },
{ PID_PAGECOUNT, VT_I4, 100 },
{ PID_WORDCOUNT, VT_I4, 100 },
};
MSIHANDLE hSummary;
int size = ARRAYSIZE(summary);
if (0 != (dwError = ::MsiGetSummaryInformation(hDB, NULL, size, & hSummary)))
{
std::wcerr << L"MsiGetSummaryInformation : 0x" << std::hex << HRESULT_FROM_WIN32(dwError)
<< L" " << FormatMessageFromHRW(HRESULT_FROM_WIN32(dwError));
return dwError;
}
for (int i = 0; i < size; i++)
{
switch(summary[i].varValue.vt)
{
case VT_BSTR:
if (0 != (dwError = MsiSummaryInfoSetProperty(hSummary, summary[i].dwPropertyId, summary[i].varPropertyType, 0, NULL, static_cast<LPCWSTR>(summary[i].varValue.bstrVal))))
{
std::wcerr << L"MsiSummaryInfoSetProperty : 0x" << std::hex << HRESULT_FROM_WIN32(dwError)
<< L" " << FormatMessageFromHRW(HRESULT_FROM_WIN32(dwError));
return dwError;
}
break;
case VT_I2:
case VT_I4:
if (0 != (dwError = MsiSummaryInfoSetProperty(hSummary, summary[i].dwPropertyId, summary[i].varPropertyType, summary[i].varValue.iVal, NULL, NULL)))
{
std::wcerr << L"MsiSummaryInfoSetProperty : 0x" << std::hex << HRESULT_FROM_WIN32(dwError)
<< L" " << FormatMessageFromHRW(HRESULT_FROM_WIN32(dwError));
return dwError;
}
break;
}
}
if (0 != (dwError = ::MsiSummaryInfoPersist(hSummary)))
{
std::wcerr << L"MsiSummaryInfoPersist : 0x" << std::hex << HRESULT_FROM_WIN32(dwError)
<< L" " << FormatMessageFromHRW(HRESULT_FROM_WIN32(dwError));
return dwError;
}
if (0 != (dwError = ::MsiDatabaseCommit(hDB)))
{
std::wcerr << L"MsiDatabaseCommit : 0x" << std::hex << HRESULT_FROM_WIN32(dwError)
<< L" " << FormatMessageFromHRW(HRESULT_FROM_WIN32(dwError));
return dwError;
}
::MsiCloseHandle(hSummary);
::MsiCloseHandle(hDB);
// open package
MSIHANDLE hProduct = NULL;
if (0 != (dwError = ::MsiOpenPackage(lpszFilename, & hProduct)))
{
std::wcerr << L"Error opening: " << lpszFilename << L": 0x" << std::hex << HRESULT_FROM_WIN32(dwError)
<< L" " << FormatMessageFromHRW(HRESULT_FROM_WIN32(dwError));
return dwError;
}
::MsiCloseHandle(hProduct);
std::wcout << L"OK";
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
140
]
]
]
|
1543e0bfa1eb94331bec4a5dc3a4f79277f4331b | 2dbbca065b62a24f47aeb7ec5cd7a4fd82083dd4 | /OUAN/OUAN/Src/Graphics/RenderComponent/RenderComponentParticleSystem.h | f93c0b3a4879def8196ee60f9af6b966bf07db29 | []
| no_license | juanjmostazo/once-upon-a-night | 9651dc4dcebef80f0475e2e61865193ad61edaaa | f8d5d3a62952c45093a94c8b073cbb70f8146a53 | refs/heads/master | 2020-05-28T05:45:17.386664 | 2010-10-06T12:49:50 | 2010-10-06T12:49:50 | 38,101,059 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,250 | h | #ifndef RenderComponentParticleSystemH_H
#define RenderComponentParticleSystemH_H
#include "RenderComponent.h"
#include "ParticleUniverseSystemManager.h"
namespace OUAN
{
class RenderComponentParticleSystem: public RenderComponent
{
private:
std::vector<ParticleUniverse::ParticleSystem*> mParticleSystems;
int mPoolPointer;
int mPoolSize;
bool mStarted;
void advancePoolPointer();
public:
RenderComponentParticleSystem(const std::string& type="", int poolSize=1);
~RenderComponentParticleSystem();
std::vector<ParticleUniverse::ParticleSystem*> getParticleSystems() const;
void setParticleSystems(std::vector<ParticleUniverse::ParticleSystem*>);
void setVisible(bool visible);
void start();
void start(Ogre::Vector3 position);
void stop();
void pause();
void resume();
bool hasStarted();
void startAll();
void stopAll();
void pauseAll();
void resumeAll();
};
class TRenderComponentParticleSystemParameters: public TRenderComponentParameters
{
public:
TRenderComponentParticleSystemParameters();
~TRenderComponentParticleSystemParameters();
String templateName;
bool attached;
int poolSize;
Ogre::uint8 queueID;
};
}
#endif | [
"juanj.mostazo@1610d384-d83c-11de-a027-019ae363d039",
"wyern1@1610d384-d83c-11de-a027-019ae363d039"
]
| [
[
[
1,
14
],
[
16,
32
],
[
34,
49
],
[
52,
55
]
],
[
[
15,
15
],
[
33,
33
],
[
50,
51
]
]
]
|
2b294363f87c32558611094c9ab03aa6c845eb50 | 5bd189ea897b10ece778fbf9c7a0891bf76ef371 | /BasicEngine/BasicEngine/Physics/Objects/PhysicsVehicle.cpp | 6fbd560f02f85242c5f63e0027f3d45c8a8e54b9 | []
| no_license | boriel/masterullgrupo | c323bdf91f5e1e62c4c44a739daaedf095029710 | 81b3d81e831eb4d55ede181f875f57c715aa18e3 | refs/heads/master | 2021-01-02T08:19:54.413488 | 2011-12-14T22:42:23 | 2011-12-14T22:42:23 | 32,330,054 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 27,724 | cpp | #include "PhysicsVehicle.h"
#include "..\PhysicsManager.h"
#include "..\..\Graphics\GraphicManager.h"
#include "btBulletDynamicsCommon.h"
#include "..\..\Game\Object\RaceControlManager.h"
//CONSTANTES QUE HAY QUE PASAR A LA CLASE VEHICLE
//
// By default, Bullet Vehicle uses Y as up axis.
// You can override the up axis, for example Z-axis up. Enable this define to see how to:
//#define FORCE_ZAXIS_UP 1
//
#ifdef FORCE_ZAXIS_UP
int rightIndex = 0;
int upIndex = 2;
int forwardIndex = 1;
btVector3 wheelDirectionCS0(0,0,-1);
btVector3 wheelAxleCS(1,0,0);
#else
int giRightIndex = 0;
int giUpIndex = 1;
int giForwardIndex = 2;
btVector3 gvbtWheelDirectionCS0(0, -1, 0);
btVector3 gvbtWheelAxleCS(-1, 0, 0);
#endif
//const int gkiMaxProxies = 32766; //Al parecer no las uso
//const int gkiMaxOverlap = 65535; //Al parecer no las uso
///btRaycastVehicle is the interface for the constraint that implements the raycast vehicle
///notice that for higher-quality slow-moving vehicles, another approach might be better
///implementing explicit hinged-wheel constraints with cylinder collision, rather then raycasts
const float gkfAcelerar = 20.f; //cuando acelera o lo deja presionado
const float gkfDesAcelerar = 5.f; //cuando suelta el acelerador
const float gkfFrenar = 20.f;
btScalar gbtSuspensionRestLength(0.6f);
#define CUBE_HALF_EXTENTS 1
//Yorman begin para borrar, esta puesto por el cubo de pruebas
//#define SCALING 1.
//#define START_POS_X -3
//#define START_POS_Y -1
//#define START_POS_Z 5
//Yorman end
cPhysicsVehicle::cPhysicsVehicle()
//: m_carChassis(0), m_cameraHeight(4.f), m_minCameraDistance(3.f), m_maxCameraDistance(10.f), m_indexVertexArrays(0), m_vertices(0)
{ //Constructor con parámetros por defecto
mpbtVehicle = 0;
mpbtWheelShape = 0;
//m_cameraPosition = btVector3(30,30,30);
mpbtCarChassis = 0;
mbQuitarGiroRueda = false;
mbAcelerando = false;
gbMarchaAtras = false;
//m_cameraHeight = 4.f;
//m_minCameraDistance(3.f)
//m_maxCameraDistance(10.f)
//m_indexVertexArrays(0)
//m_vertices(0)
gfEngineForce = 0.f;
gfBreakingForce = 0.f;
gfMaxEngineForce = 1500.f; //this should be engine/velocity dependent //2000.f
gfMaxBreakingForce = 100.f;
gfMaxBackForce = 1000.f;
gbCocheParado = true; // Controlaremos si el coche está en movimiento o no
gfVehicleSteering = 0.f;
gfSteeringIncrement = 0.02f;
gfSteeringClamp = 0.3f;
gfWheelRadius = 0.5f;
gfWheelWidth = 0.4f;
gfWheelFriction = 1000; //BT_LARGE_FLOAT;
gfSuspensionStiffness = 20.f;
gfSuspensionDamping = 2.3f;
gfSuspensionCompression = 4.4f;
gfRollInfluence = 0.1f;//1.0f;
}
cPhysicsVehicle::~cPhysicsVehicle()
{
//btDiscreteDynamicsWorld* lpDynamicsWorld = cPhysicsManager::Get().GetDynamicsWorld();
btDynamicsWorld* lpDynamicsWorld = cPhysicsManager::Get().GetDynamicsWorld();
lpDynamicsWorld = cPhysicsManager::Get().GetDynamicsWorld();
//cleanup in the reverse order of creation/initialization
//remove the rigidbodies from the dynamics world and delete them
for (int luiIndex = lpDynamicsWorld->getNumCollisionObjects() - 1; luiIndex >= 0 ; luiIndex--)
{
btCollisionObject* lbtObject = lpDynamicsWorld->getCollisionObjectArray()[luiIndex];
btRigidBody* lbtRigidBody = btRigidBody::upcast(lbtObject);
if (lbtRigidBody && lbtRigidBody->getMotionState())
delete lbtRigidBody->getMotionState();
lpDynamicsWorld->removeCollisionObject( lbtObject );
delete lbtObject;
}
//delete collision shapes
for (int luiIndex = 0; luiIndex < mabtCollisionShapes.size(); luiIndex++)
{
btCollisionShape* lbtShape = mabtCollisionShapes[luiIndex];
delete lbtShape;
}
delete mpbtIndexVertexArrays;
delete mpbtVertices;
//delete dynamics world
delete lpDynamicsWorld;
delete mpbtVehicleRayCaster;
delete mpbtVehicle;
delete mpbtWheelShape;
//delete solver
delete mpbtConstraintSolver;
//delete broadphase
delete mpbtOverlappingPairCache;
//delete dispatcher
delete mpbtDispatcher;
delete mpbtCollisionConfiguration;
}
//Inicializamos la física del vehiculo
void cPhysicsVehicle::Init(cVec3 lPosition, cQuaternion lRotacionInicial)
{
btDiscreteDynamicsWorld* lpDynamicsWorld = cPhysicsManager::Get().GetDynamicsWorld();
//btDynamicsWorld* lpDynamicsWorld = cPhysicsManager::Get().GetDynamicsWorld();
//lpDynamicsWorld = cPhysicsManager::Get().GetDynamicsWorld();
#ifdef FORCE_ZAXIS_UP
//m_cameraUp = btVector3(0,0,1);
//m_forwardAxis = 1;
miForwardAxis = 1;
#endif
btCollisionShape* groundShape = new btBoxShape(btVector3(50, 3, 50)); //Figura del suelo
//m_collisionShapes.push_back(groundShape);
//cPhysicsManager::mabtCollisionShapes.push_back(groundShape);
//cPhysicsManager::Get().AddCollisionShape(groundShape);
mabtCollisionShapes.push_back(groundShape);
/*
m_collisionConfiguration = new btDefaultCollisionConfiguration();
m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration);
btVector3 worldMin(-1000,-1000,-1000);
btVector3 worldMax(1000,1000,1000);
m_overlappingPairCache = new btAxisSweep3(worldMin,worldMax);
m_constraintSolver = new btSequentialImpulseConstraintSolver();
lpDynamicsWorld = new btDiscreteDynamicsWorld(m_dispatcher,m_overlappingPairCache,m_constraintSolver,m_collisionConfiguration);
*/
#ifdef FORCE_ZAXIS_UP
//m_dynamicsWorld->setGravity(btVector3(0,0,-10));
lpDynamicsWorld->setGravity(btVector3(0, 0, -10));
#endif
//m_dynamicsWorld->setGravity(btVector3(0,0,0));
btTransform lbtTransform;
lbtTransform.setIdentity();
#ifdef FORCE_ZAXIS_UP
// indexRightAxis = 0;
// indexUpAxis = 2;
// indexForwardAxis = 1;
btCollisionShape* chassisShape = new btBoxShape(btVector3(1.f,2.f, 0.5f));
btCompoundShape* compound = new btCompoundShape();
btTransform localTrans;
localTrans.setIdentity();
//localTrans effectively shifts the center of mass with respect to the chassis
localTrans.setOrigin(btVector3(0,0,1));
#else
btCollisionShape* lbtChassisShape = new btBoxShape( btVector3 (1.f, 0.5f, 2.f) );
//cPhysicsManager::Get().AddCollisionShape(chassisShape);
mabtCollisionShapes.push_back( lbtChassisShape );
btCompoundShape* lbtCompoundShape = new btCompoundShape();
//cPhysicsManager::Get().AddCollisionShape(compound);
mabtCollisionShapes.push_back( lbtCompoundShape );
btTransform lbtLocalTransform;
lbtLocalTransform.setIdentity();
btQuaternion lbtQuaternion = btQuaternion(0, 0, 0, 1);
if (lRotacionInicial.w != 0) //no pusieron ángulo o no rotacion en el xml
lbtQuaternion = CambiarEje(lRotacionInicial); //Lo mismo que hacer la rotacion
lbtTransform = btTransform (lbtQuaternion );
//localTrans effectively shifts the center of mass with respect to the chassis
lbtLocalTransform.setOrigin(btVector3(0,1,0));
#endif
lbtCompoundShape->addChildShape(lbtLocalTransform, lbtChassisShape);
lbtTransform.setOrigin(btVector3(lPosition.x, lPosition.y, lPosition.z));
mpbtCarChassis = LocalCreateRigidBody(800, lbtTransform, lbtCompoundShape); //chassisShape);
//m_carChassis->setDamping(0.2,0.2);
mpbtWheelShape = new btCylinderShapeX(btVector3(gfWheelWidth, gfWheelRadius, gfWheelRadius));
//clientResetScene();
/// create vehicle
{
mpbtVehicleRayCaster = new btDefaultVehicleRaycaster(lpDynamicsWorld);
mpbtVehicle = new btRaycastVehicle(mbtTuning, mpbtCarChassis, mpbtVehicleRayCaster);
///never deactivate the vehicle
mpbtCarChassis->setActivationState(DISABLE_DEACTIVATION);
//btRigidBody* lbtrb = m_vehicle->getRigidBody();
lpDynamicsWorld->addVehicle(mpbtVehicle);
float lfConnectionHeight = 1.2f;
bool lbIsFrontWheel=true;
//choose coordinate system
mpbtVehicle->setCoordinateSystem(giRightIndex, giUpIndex, giForwardIndex);
#ifdef FORCE_ZAXIS_UP
btVector3 connectionPointCS0(CUBE_HALF_EXTENTS-(0.3*wheelWidth),2*CUBE_HALF_EXTENTS-wheelRadius, connectionHeight);
#else
btVector3 connectionPointCS0(CUBE_HALF_EXTENTS-(0.3f * gfWheelWidth), lfConnectionHeight, 2.0f * CUBE_HALF_EXTENTS - gfWheelRadius);
#endif
mpbtVehicle->addWheel (connectionPointCS0, gvbtWheelDirectionCS0, gvbtWheelAxleCS, gbtSuspensionRestLength, gfWheelRadius, mbtTuning, lbIsFrontWheel);
#ifdef FORCE_ZAXIS_UP
connectionPointCS0 = btVector3(-CUBE_HALF_EXTENTS+(0.3*wheelWidth),2*CUBE_HALF_EXTENTS-wheelRadius, connectionHeight);
#else
connectionPointCS0 = btVector3(-CUBE_HALF_EXTENTS+(0.3f * gfWheelWidth), lfConnectionHeight, 2 * CUBE_HALF_EXTENTS - gfWheelRadius);
#endif
mpbtVehicle->addWheel (connectionPointCS0, gvbtWheelDirectionCS0, gvbtWheelAxleCS, gbtSuspensionRestLength, gfWheelRadius, mbtTuning, lbIsFrontWheel);
#ifdef FORCE_ZAXIS_UP
connectionPointCS0 = btVector3(-CUBE_HALF_EXTENTS+(0.3*wheelWidth),-2*CUBE_HALF_EXTENTS+wheelRadius, connectionHeight);
#else
connectionPointCS0 = btVector3(-CUBE_HALF_EXTENTS+(0.3f * gfWheelWidth), lfConnectionHeight, -2 * CUBE_HALF_EXTENTS + gfWheelRadius);
#endif //FORCE_ZAXIS_UP
lbIsFrontWheel = false;
mpbtVehicle->addWheel (connectionPointCS0, gvbtWheelDirectionCS0, gvbtWheelAxleCS, gbtSuspensionRestLength, gfWheelRadius, mbtTuning, lbIsFrontWheel);
#ifdef FORCE_ZAXIS_UP
connectionPointCS0 = btVector3(CUBE_HALF_EXTENTS-(0.3*wheelWidth),-2*CUBE_HALF_EXTENTS+wheelRadius, connectionHeight);
#else
connectionPointCS0 = btVector3(CUBE_HALF_EXTENTS-(0.3f * gfWheelWidth), lfConnectionHeight, -2 * CUBE_HALF_EXTENTS + gfWheelRadius);
#endif
mpbtVehicle->addWheel (connectionPointCS0, gvbtWheelDirectionCS0, gvbtWheelAxleCS, gbtSuspensionRestLength, gfWheelRadius, mbtTuning, lbIsFrontWheel);
for (int liIndex=0; liIndex < mpbtVehicle->getNumWheels(); liIndex++)
{
btWheelInfo& lbtWheelInfo = mpbtVehicle->getWheelInfo(liIndex);
lbtWheelInfo.m_suspensionStiffness = gfSuspensionStiffness;
lbtWheelInfo.m_wheelsDampingRelaxation = gfSuspensionDamping;
lbtWheelInfo.m_wheelsDampingCompression = gfSuspensionCompression;
lbtWheelInfo.m_frictionSlip = gfWheelFriction;
lbtWheelInfo.m_rollInfluence = gfRollInfluence;
}
}
//setCameraDistance(26.f);
// --> Yorman comienzo pruebas
/*
btCollisionShape* colShape = new btBoxShape(btVector3(SCALING * 1, SCALING * 1, SCALING * 1));
//btCollisionShape* colShape = new btSphereShape(btScalar(1.));
//m_collisionShapes.push_back(colShape);
//cPhysicsManager::Get().AddCollisionShape(colShape);
mabtCollisionShapes.push_back(colShape);
btScalar mass(1.f);
//rigidbody is dynamic if and only if mass is non zero, otherwise static
bool isDynamic = (mass != 0.f);
btVector3 localInertia(0,0,0);
if (isDynamic)
colShape->calculateLocalInertia(mass, localInertia);
float start_x = START_POS_X;
float start_y = START_POS_Y;
float start_z = START_POS_Z;
/// Create Dynamic Objects
btTransform startTransform;
startTransform.setIdentity();
startTransform.setOrigin(SCALING * btVector3(btScalar(2.0 + start_x), btScalar(20 + 2.0 + start_y), btScalar(2.0 + start_z)));
//using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, myMotionState, colShape, localInertia);
btRigidBody* body = new btRigidBody(rbInfo);
//m_dynamicsWorld->addRigidBody(body);
lpDynamicsWorld->addRigidBody(body);
*/
// --> Yorman fin pruebas
}
/*
void cPhysicsVehicle::Update(void)
{ //Update
btTransform lbtTransform;
mpbtVehicle->getRigidBody()->getMotionState()->getWorldTransform(lbtTransform);
//mpbtRigidBody->getMotionState()->getWorldTransform(trans);
std::cout << "Vehicle: (" << lbtTransform.getOrigin().getX() << "," << lbtTransform.getOrigin().getY() << "," << lbtTransform.getOrigin().getZ() << ")" << std::endl;
}
*/
//Obtenemos la posicion central del objeto
cVec3 cPhysicsVehicle::GetPosition ()
{
cVec3 lPosition;
btTransform lbtTransform;
//mpbtRigidBody->getMotionState()->getWorldTransform(lbtTransform);
mpbtVehicle->getRigidBody()->getMotionState()->getWorldTransform(lbtTransform);
lPosition.x = lbtTransform.getOrigin().getX();
lPosition.y = lbtTransform.getOrigin().getY();
lPosition.z = lbtTransform.getOrigin().getZ();
return lPosition;
}
//Obtenemos la posicion central del objeto
void cPhysicsVehicle::SetPosition (const cVec3 &lvPosition)//, cQuaternion lRotacion)
{
btTransform lbtTransform;
bool lbIsReload = true; //esto es mejor por parametro, para despues
//mpbtRigidBody->getMotionState()->getWorldTransform(lbtTransform);
mpbtVehicle->getRigidBody()->getMotionState()->getWorldTransform(lbtTransform);
//lbtTransform.getOrigin().setX(lvPosition.x);
//lbtTransform.getOrigin().setY(lvPosition.y);
//lbtTransform.getOrigin().setZ(lvPosition.z);
lbtTransform.setOrigin(btVector3 (lvPosition.x, lvPosition.y, lvPosition.z));
//Claro ya etá cambiada la figura lo unico que no está orientado
//btQuaternion lbtQuaternion = btQuaternion(0, 0, 0, 1);
//if (lRotacion.w != 0) //no pusieron ángulo o no rotacion en el xml
// lbtQuaternion = CambiarEje(lRotacion); //Lo mismo que hacer la rotacion
//lbtTransform = btTransform (lbtQuaternion);
//Poniendo la velocidad a 0
if (lbIsReload)
{
gfEngineForce = 0.f;
gfBreakingForce = 0.f;
mpbtVehicle->getRigidBody()->setAngularVelocity(btVector3 (0, 0, 0));
mpbtVehicle->getRigidBody()->setLinearVelocity(btVector3 (0, 0, 0));
}
mpbtVehicle->getRigidBody()->setWorldTransform(lbtTransform);
}
cQuaternion cPhysicsVehicle::GetQuatRotation()
{
//cVec3 lVecRotation;
cQuaternion lQuatRotation;
btTransform lbtTransform;
//mpbtRigidBody->getMotionState()->getWorldTransform(lbtTransform);
mpbtVehicle->getRigidBody()->getMotionState()->getWorldTransform(lbtTransform);
btQuaternion lbtQuaternion = lbtTransform.getRotation();
lQuatRotation.x = lbtQuaternion.getX();
lQuatRotation.y = lbtQuaternion.getY();
lQuatRotation.z = lbtQuaternion.getZ();
lQuatRotation.w = lbtQuaternion.getW();
return lQuatRotation;
}
void cPhysicsVehicle::SetQuatRotation(const cQuaternion &lRotQuat)
{
btTransform lbtTransform;
btQuaternion lbtRotQuat = btQuaternion(lRotQuat.x, lRotQuat.y, lRotQuat.z, lRotQuat.w);
mpbtVehicle->getRigidBody()->getMotionState()->getWorldTransform(lbtTransform);
lbtTransform.setRotation(lbtRotQuat);
mpbtVehicle->getRigidBody()->setWorldTransform(lbtTransform);
}
cVec3 cPhysicsVehicle::GetAngSpeed()
{
btVector3 btVec3 = mpbtVehicle->getRigidBody()->getAngularVelocity();
return cVec3(btVec3.getX() , btVec3.getY(), btVec3.getZ());
}
cVec3 cPhysicsVehicle::GetLinearSpeed()
{
btVector3 btVec3 = mpbtVehicle->getRigidBody()->getLinearVelocity();
return cVec3(btVec3.getX() , btVec3.getY(), btVec3.getZ());
}
float cPhysicsVehicle::GetSpeed()
{
return mpbtVehicle->getRigidBody()->getLinearVelocity().length();
}
/*
void cPhysicsVehicle::RenderObjectVehicleDebug()
{
cMatrix lWorld;
lWorld.LoadIdentity();
cGraphicManager::Get().SetWorldMatrix(lWorld);
btTransform lbtTransform;
//mpbtRigidBody->getMotionState()->getWorldTransform(lbtTransform);
m_vehicle->getRigidBody()->getMotionState()->getWorldTransform(lbtTransform);
//Pintando los ejes de coordenadas
RenderTransformDebug(lbtTransform, 1.0);
////Detectando todos los Shapes
//for (unsigned int luiIndex = 0; luiIndex < m_collisionShapes.size(); luiIndex++)
//{
// btCollisionShape* lbtCollisionShape = m_collisionShapes[luiIndex];
// const btBoxShape* lbtBoxShape = static_cast<const btBoxShape*>(lbtCollisionShape);
// btVector3 lbtHalfExtents = lbtBoxShape->getHalfExtentsWithMargin();
// btVector3 lbtColor(0.0f, 1.0f, 0.0f); //si se pasa por parametro a lo mejor podemos dibujar cosas de muchos colores
// RenderBoxDebug(- lbtHalfExtents, lbtHalfExtents, lbtTransform, lbtColor);
//}
//btCollisionShape* lbtShape = m_vehicle->getRigidBody()->getCollisionShape();
////Dibujando un cubo, sacado de btCollisionWorld.cpp 1217 (despues de mucho buscar y seguir codigo ...)
////btCollisionShape* lbtShape = mpbtRigidBody->getCollisionShape();
//btCollisionShape* lbtShape = m_vehicle->getRigidBody()->getCollisionShape();
//const btBoxShape* lbtBoxShape = static_cast<const btBoxShape*>(lbtShape);
//btVector3 lbtHalfExtents = lbtBoxShape->getHalfExtentsWithMargin();
//btVector3 lbtColor(1.0f, 0.0f, 0.0f); //si se pasa por parametro a lo mejor podemos dibujar cosas de muchos colores
//RenderBoxDebug(- lbtHalfExtents, lbtHalfExtents, lbtTransform, lbtColor);
}
*/
//Si las ruedas están giradas y no se está tocando ninguna de las teclas de giro
void cPhysicsVehicle::CentrandoRuedas()
{
if (mbQuitarGiroRueda == true)
{
if (gfVehicleSteering > 0.00)
gfVehicleSteering -= gfSteeringIncrement;
if (gfVehicleSteering < 0.00)
gfVehicleSteering += gfSteeringIncrement;
if (gfVehicleSteering < 0.1 && gfVehicleSteering > -0.1){
gfVehicleSteering =0;
mbQuitarGiroRueda = false;
}
}
#ifdef _DEBUG
//printf("gfVehicleSteering = %i\n", gfVehicleSteering);
#endif
ClientMoveAndDisplay();
}
//Si las ruedas están giradas y no se está tocando ninguna de las teclas de giro
void cPhysicsVehicle::DesAcelerar()
{
//if (mbAcelerando == false)
//{
/*if ((gfEngineForce >= 0.00) && (gfEngineForce <= gfMaxEngineForce))
gfEngineForce -= gkfDesAcelerar;*/
//gfBreakingForce += gkfDesAcelerar;
//}
btVector3 lbtVel = mpbtVehicle->getRigidBody()->getAngularVelocity();
float lfVel = lbtVel.getX();
#ifdef _DEBUG
//printf("gfEngineForce = %f ---- gfBreakingForce = %f \n", gfEngineForce, gfBreakingForce);
#endif
ClientMoveAndDisplay();
}
void cPhysicsVehicle::SpecialKeyboardRelease(const unsigned int luiKey)
{
bool lbGirar = false;
switch (luiKey)
{
case eIA_Up: //arriba
gfEngineForce = 0.f;
break;
case eIA_Down: //abajo
gfBreakingForce =gfMaxBreakingForce;
gfEngineForce = 0.f;
break;
case eIA_Left: //izquierda
gfVehicleSteering += gfSteeringIncrement;
if (gfVehicleSteering > gfSteeringClamp)
gfVehicleSteering = gfSteeringClamp;
lbGirar = true;
mbQuitarGiroRueda = true;
break;
case eIA_Right: //derecha
gfVehicleSteering -= gfSteeringIncrement;
if (gfVehicleSteering < -gfSteeringClamp)
gfVehicleSteering = -gfSteeringClamp;
lbGirar = true;
mbQuitarGiroRueda = true;
break;
case eIA_Drift:
ParaDerrapar();
break;
}
}
void cPhysicsVehicle::Derrapar(){
for (int liIndex=0; liIndex < mpbtVehicle->getNumWheels(); liIndex++)
{
btWheelInfo& lbtWheelInfo = mpbtVehicle->getWheelInfo(liIndex);
if(!lbtWheelInfo.m_bIsFrontWheel)
lbtWheelInfo.m_frictionSlip -= 0.5;//gfWheelFriction - gfIntensidadDerrape;
}
//mpbtVehicle->updateFriction();
}
// Dejamos el coche sin derrape
void cPhysicsVehicle::ParaDerrapar(){
for (int liIndex=0; liIndex < mpbtVehicle->getNumWheels(); liIndex++)
{
btWheelInfo& lbtWheelInfo = mpbtVehicle->getWheelInfo(liIndex);
lbtWheelInfo.m_frictionSlip=1;
//m_frictionSlip = gfWheelFriction;
}
//mpbtVehicle->updateFriction();
}
//void VehicleDemo::specialKeyboard(int key, int x, int y)
void cPhysicsVehicle::SpecialKeyboard(const unsigned int luiKey)
{
bool lbGirar = false;
switch (luiKey)
{
case eIA_Up: //arriba
if( gbMarchaAtras ){ // Si estamos con la marcha atrás activada
gfBreakingForce = gfMaxBreakingForce;
gfEngineForce = 0.f;
if(mpbtVehicle->getCurrentSpeedKmHour()<0.1){
gbMarchaAtras=false; // Si el coche está parado activamos la direccion opuesta
#ifdef _DEBUG
//printf("Marcha Atras Desactivada!\n");
#endif
}
}else{
gfEngineForce = gfMaxEngineForce;
gfBreakingForce = 0.f;
}
break;
case eIA_Down: //abajo
if( gbMarchaAtras ){
gfEngineForce = -gfMaxBackForce;
gfBreakingForce = 0.f;
}else{
gfBreakingForce = gfMaxBreakingForce;
gfEngineForce = 0.f;
#ifdef _DEBUG
//printf("Velocidad Coche: %f",mpbtVehicle->getCurrentSpeedKmHour());
#endif
if(mpbtVehicle->getCurrentSpeedKmHour()<0.1)
{
gbMarchaAtras=true; // Si el coche está parado activamos la direccion opuesta
#ifdef _DEBUG
//printf("Marcha Atras Activada!\n");
#endif
}
}
break;
case eIA_Left: //izquierda
gfVehicleSteering += gfSteeringIncrement;
if (gfVehicleSteering > gfSteeringClamp)
gfVehicleSteering = gfSteeringClamp;
lbGirar = true;
mbQuitarGiroRueda = true;
break;
case eIA_Right: //derecha
gfVehicleSteering -= gfSteeringIncrement;
if (gfVehicleSteering < -gfSteeringClamp)
gfVehicleSteering = -gfSteeringClamp;
lbGirar = true;
mbQuitarGiroRueda = true;
break;
case eIA_Drift:
Derrapar();
break;
}
ClientMoveAndDisplay();
#ifdef _DEBUG
//printf("gfVehicleSteering = %i\n", gfVehicleSteering);
//printf("gfEngineForce = %f ---- gfBreakingForce = %f \n", gfEngineForce, gfBreakingForce);
//printf("Friccion Delantera: %f Friccion Trasera: %f Sliding:%f\n",mpbtVehicle->getWheelInfo(1).m_frictionSlip,mpbtVehicle->getWheelInfo(3).m_frictionSlip, mpbtVehicle->getWheelInfo(1).m_skidInfo);
#endif
//printf ("Key = %i\n", luiKey);
// printf("key = %i x=%i y=%i\n",key,x,y);
/*
switch (key)
{
case GLUT_KEY_LEFT :
{
gVehicleSteering += steeringIncrement;
if ( gVehicleSteering > steeringClamp)
gVehicleSteering = steeringClamp;
break;
}
case GLUT_KEY_RIGHT :
{
gVehicleSteering -= steeringIncrement;
if ( gVehicleSteering < -steeringClamp)
gVehicleSteering = -steeringClamp;
break;
}
case GLUT_KEY_UP :
{
gEngineForce = maxEngineForce;
gBreakingForce = 0.f;
break;
}
case GLUT_KEY_DOWN :
{
gBreakingForce = maxBreakingForce;
gEngineForce = 0.f;
break;
}
default:
DemoApplication::specialKeyboard(key,x,y);
break;
}
// glutPostRedisplay();hasta
*/
}
// declaration of callback: Solo ejecutamos el sonido si no es ninguno de ls opuntos de control.
struct btDrawingResult : public btCollisionWorld::ContactResultCallback
{
virtual btScalar addSingleResult(btManifoldPoint& cp, const btCollisionObject* colObj0,int partId0,int index0,const btCollisionObject* colObj1,int partId1,int index1)
{
#ifdef _DEBUG
//std::cout << "contact!" << std::endl;
#endif
bool Choque=true;
for(unsigned int luiIndex=0;luiIndex<cRaceControlManager::Get().GetPuntosControl()->size();luiIndex++)
if(colObj1->getCollisionShape()==cRaceControlManager::Get().GetPuntosControl()->at(luiIndex).Ghost->getCollisionShape())
Choque=false;
if(Choque) cRaceControlManager::Get().SonidosGolpes();
btVector3 ptA = cp.getPositionWorldOnA();
btVector3 ptB = cp.getPositionWorldOnB();
btVector3 norm = cp.m_normalWorldOnB;
return 0;
}
};
void cPhysicsVehicle::ClientMoveAndDisplay()
{
btDiscreteDynamicsWorld* lpDynamicsWorld = cPhysicsManager::Get().GetDynamicsWorld();
btDrawingResult Choque;
lpDynamicsWorld->contactTest(this->mpbtCarChassis,Choque);
{
if(!cRaceControlManager::Get().isRaceRunning()){
gfEngineForce=0;
gfBreakingForce=gfMaxBreakingForce;
gfVehicleSteering=0;
}
int liWheelIndex = 2;
mpbtVehicle->applyEngineForce( gfEngineForce, liWheelIndex );
mpbtVehicle->setBrake( gfBreakingForce, liWheelIndex );
liWheelIndex = 3;
mpbtVehicle->applyEngineForce( gfEngineForce, liWheelIndex );
mpbtVehicle->setBrake( gfBreakingForce, liWheelIndex );
liWheelIndex = 0;
mpbtVehicle->setSteeringValue( gfVehicleSteering, liWheelIndex );
liWheelIndex = 1;
mpbtVehicle->setSteeringValue( gfVehicleSteering, liWheelIndex );
}
float lfDeltaTime = GetDeltaTimeMicroseconds() * 0.000001f;
if (lpDynamicsWorld)
{
//during idle mode, just run 1 simulation step maximum
//int maxSimSubSteps = m_idle ? 1 : 2;
//if (m_idle)
// dt = 1.0/420.f;
lfDeltaTime = 1.0f / 420.f;
int maxSimSubSteps = 1; //temp a mano
int numSimSteps = lpDynamicsWorld->stepSimulation(lfDeltaTime, maxSimSubSteps);
//#define VERBOSE_FEEDBACK
#ifdef VERBOSE_FEEDBACK
if (!numSimSteps)
printf("Interpolated transforms\n");
else
{
if (numSimSteps > maxSimSubSteps)
{
//detect dropping frames
printf("Dropped (%i) simulation steps out of %i\n",numSimSteps - maxSimSubSteps,numSimSteps);
} else
{
printf("Simulated (%i) steps\n",numSimSteps);
}
}
#endif //VERBOSE_FEEDBACK
}
#ifdef USE_QUICKPROF
btProfiler::beginBlock("render");
#endif //USE_QUICKPROF
//renderme();
//optional but useful: debug drawing
//if (lpDynamicsWorld)
// lpDynamicsWorld->debugDrawWorld();
#ifdef USE_QUICKPROF
btProfiler::endBlock("render");
#endif
glFlush();
//glutSwapBuffers();
}
void cPhysicsVehicle::MostrarInfo ()
{
btTransform lbtTransform;
mpbtVehicle->getRigidBody()->getMotionState()->getWorldTransform(lbtTransform);
std::cout << "Vehicle: (" << lbtTransform.getOrigin().getX() << "," << lbtTransform.getOrigin().getY() << "," << lbtTransform.getOrigin().getZ() << ")" << std::endl;
/*
cout << "--------------------" << endl;
cout << "giRightIndex : " << giRightIndex << endl;
cout << "giUpIndex : " << giUpIndex << endl;
cout << "giForwardIndex : " << giForwardIndex << endl;
cout << "gvbtWheelDirectionCS0 : " << gvbtWheelDirectionCS0.getX() << "," << gvbtWheelDirectionCS0.getY() << "," << gvbtWheelDirectionCS0.getZ() << endl;
cout << "gvbtWheelAxleCS : " << gvbtWheelAxleCS.getX() << "," << gvbtWheelAxleCS.getY() << "," << gvbtWheelAxleCS.getZ() << endl;
*/
//cout << "--------------------" << endl;
//cout << "gfEngineForce: " << gfEngineForce << " - gfBreakingForce: " << gfBreakingForce << endl ;
//cout << "gfMaxEngineForce: " << gfMaxEngineForce << " - gfMaxBreakingForce: " << gfMaxBreakingForce << endl ;
//cout << "gfVehicleSteering: " << gfVehicleSteering << " - gfSteeringIncrement: " << gfSteeringIncrement << " - gfSteeringClamp: " << gfSteeringClamp << endl ;
//cout << "gfWheelRadius: " << gfWheelRadius << " - gfWheelWidth: " << gfWheelWidth << " - gfWheelFriction: " << gfWheelFriction << endl ;
//cout << "getLinearVelocity: " << mpbtVehicle->getRigidBody()->getLinearVelocity().getX() << "," << mpbtVehicle->getRigidBody()->getLinearVelocity().getY() << "," << mpbtVehicle->getRigidBody()->getLinearVelocity().getZ() << endl;
//cout << "getTotalForce: " << mpbtVehicle->getRigidBody()->getTotalForce().getX() << "," << mpbtVehicle->getRigidBody()->getTotalForce().getY() << "," << mpbtVehicle->getRigidBody()->getTotalForce().getZ() << endl;
//cout << "getTotalTorque: " << mpbtVehicle->getRigidBody()->getTotalTorque().getX() << "," << mpbtVehicle->getRigidBody()->getTotalTorque().getY() << "," << mpbtVehicle->getRigidBody()->getTotalTorque().getZ() << endl;
} | [
"[email protected]@f2da8aa9-0175-0678-5dcd-d323193514b7",
"[email protected]@f2da8aa9-0175-0678-5dcd-d323193514b7",
"yormanh@f2da8aa9-0175-0678-5dcd-d323193514b7",
"[email protected]@f2da8aa9-0175-0678-5dcd-d323193514b7"
]
| [
[
[
1,
2
],
[
4,
7
],
[
9,
24
],
[
30,
33
],
[
36,
41
],
[
45,
45
],
[
48,
49
],
[
51,
56
],
[
62,
70
],
[
73,
73
],
[
79,
82
],
[
102,
105
],
[
108,
112
],
[
115,
115
],
[
124,
124
],
[
126,
126
],
[
131,
131
],
[
135,
138
],
[
142,
143
],
[
145,
146
],
[
148,
149
],
[
151,
151
],
[
153,
155
],
[
157,
160
],
[
163,
170
],
[
172,
173
],
[
176,
176
],
[
178,
184
],
[
186,
192
],
[
195,
206
],
[
210,
210
],
[
223,
223
],
[
225,
226
],
[
228,
228
],
[
232,
233
],
[
235,
240
],
[
244,
245
],
[
252,
252
],
[
254,
255
],
[
257,
258
],
[
260,
263
],
[
265,
266
],
[
268,
270
],
[
272,
273
],
[
275,
277
],
[
279,
279
],
[
282,
284
],
[
286,
286
],
[
288,
288
],
[
290,
290
],
[
297,
306
],
[
309,
310
],
[
314,
341
],
[
343,
343
],
[
345,
351
],
[
353,
355
],
[
358,
360
],
[
362,
362
],
[
365,
374
],
[
376,
385
],
[
420,
426
],
[
428,
440
],
[
473,
492
],
[
506,
510
],
[
520,
520
],
[
703,
703
],
[
712,
713
],
[
758,
761
],
[
784,
788
],
[
791,
791
],
[
803,
803
],
[
809,
812
],
[
814,
821
],
[
823,
824
],
[
826,
871
],
[
879,
880
],
[
903,
903
]
],
[
[
3,
3
],
[
8,
8
],
[
46,
47
],
[
77,
77
],
[
83,
101
],
[
536,
537
],
[
539,
539
],
[
559,
560
],
[
570,
570
],
[
577,
591
],
[
597,
598
],
[
600,
600
],
[
606,
634
],
[
645,
649
],
[
653,
657
],
[
661,
666
],
[
672,
672
],
[
676,
677
],
[
681,
682
],
[
690,
690
],
[
697,
699
],
[
707,
707
],
[
709,
709
],
[
762,
766
],
[
771,
783
],
[
789,
790
],
[
792,
796
],
[
804,
804
]
],
[
[
25,
29
],
[
34,
35
],
[
42,
44
],
[
50,
50
],
[
57,
61
],
[
71,
72
],
[
74,
76
],
[
78,
78
],
[
106,
107
],
[
113,
114
],
[
116,
123
],
[
125,
125
],
[
127,
130
],
[
132,
134
],
[
139,
141
],
[
144,
144
],
[
147,
147
],
[
150,
150
],
[
152,
152
],
[
156,
156
],
[
161,
162
],
[
171,
171
],
[
174,
175
],
[
177,
177
],
[
185,
185
],
[
193,
194
],
[
207,
209
],
[
211,
222
],
[
224,
224
],
[
227,
227
],
[
229,
231
],
[
234,
234
],
[
241,
243
],
[
246,
251
],
[
253,
253
],
[
256,
256
],
[
259,
259
],
[
264,
264
],
[
267,
267
],
[
271,
271
],
[
274,
274
],
[
278,
278
],
[
280,
281
],
[
285,
285
],
[
287,
287
],
[
289,
289
],
[
291,
296
],
[
307,
308
],
[
311,
313
],
[
342,
342
],
[
344,
344
],
[
352,
352
],
[
356,
357
],
[
361,
361
],
[
363,
364
],
[
375,
375
],
[
386,
386
],
[
388,
419
],
[
427,
427
],
[
472,
472
],
[
493,
505
],
[
511,
519
],
[
521,
535
],
[
538,
538
],
[
540,
558
],
[
561,
569
],
[
571,
576
],
[
592,
596
],
[
599,
599
],
[
601,
605
],
[
635,
644
],
[
650,
652
],
[
658,
660
],
[
667,
671
],
[
673,
675
],
[
678,
680
],
[
683,
689
],
[
691,
696
],
[
700,
702
],
[
704,
706
],
[
708,
708
],
[
710,
711
],
[
714,
757
],
[
767,
770
],
[
797,
802
],
[
805,
808
],
[
813,
813
],
[
822,
822
],
[
825,
825
],
[
872,
878
],
[
881,
902
]
],
[
[
387,
387
],
[
441,
471
]
]
]
|
91d3611cfcd7cfbd7366ab81858422979985a770 | 4df96df7014bf0ffd912ab69142bd3ab8d897a1b | /dev/tests/cpp_interface/include/test_avm_string_methods.h | 0afa0088082221de32a3d9b36909f4e48f5eb363 | []
| no_license | al-sabr/caspin | 25e66369de26e9ac2467109ef20a692e0f508dc7 | fd901f1dbec708864ab12e8ce5ed153e33b6e93f | refs/heads/master | 2021-12-12T04:55:15.474635 | 2011-10-10T18:01:37 | 2011-10-10T18:01:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,427 | h | #include "test_base.h"
class avm_string_test : public test_base
{
//-----------------------------------------------------------------------
const char* name() { return "avm_string_test"; }
//-----------------------------------------------------------------------
void test_global_functions(csp::VmCore* core)
{
core->callGlobalFunction(
core->toScriptPtr("function0"),
core->toScriptPtr("GlobalFunctions"));
avmplus::Atom args[] = { 0, core->toScript("arg0") };
avmplus::Atom result = core->callGlobalFunction(
core->toScriptPtr("function1"),
core->toScriptPtr("GlobalFunctions"),
args);
if(result != nullObjectAtom)
core->console << core->atomToString(result) << "\n";
else
core->console << "null\n";
}
//-----------------------------------------------------------------------
void test_static_class_functions(csp::VmCore* core)
{
core->callStaticFunction(
core->toScriptPtr("Class"),
core->toScriptPtr("static_function0"),
core->toScriptPtr("ClassFunctions"));
avmplus::Atom args[] = { 0, core->toScript("arg0") };
avmplus::Atom result = core->callStaticFunction(
core->toScriptPtr("Class"),
core->toScriptPtr("static_function1"),
core->toScriptPtr("ClassFunctions"),
args);
if(result != nullObjectAtom)
core->console << core->atomToString(result) << "\n";
else
core->console << "null\n";
}
//-----------------------------------------------------------------------
avmplus::ScriptObject* test_class_construction(csp::VmCore* core)
{
avmplus::Atom args[] =
{
0,
core->toScript("arg0"),
core->toScript("arg1")
};
return core->createObject(
core->toScriptPtr("Class"),
core->toScriptPtr("ClassFunctions"),
args);
}
//-----------------------------------------------------------------------
void test_class_member_functions(csp::VmCore* core, avmplus::ScriptObject* obj)
{
csp::VmCore::callFunction(obj, core->toScriptPtr("member_function0"));
avmplus::Atom args[] = { 0, core->toScript("arg0") };
avmplus::Atom result = csp::VmCore::callFunction(
obj,
core->toScriptPtr("member_function1"),
args);
if(result != nullObjectAtom)
core->console << core->atomToString(result) << "\n";
else
core->console << "null\n";
}
//-----------------------------------------------------------------------
};
| [
"[email protected]"
]
| [
[
[
1,
77
]
]
]
|
5082444cb0f6bd54f349dfa701e37aa6cdbc040c | 9773c3304eecc308671bcfa16b5390c81ef3b23a | /MDI AIPI V.6.92 2003 ( Correct Save Fired Rules, AM =-1, g_currentLine)/AIPI/AIPITreeView.cpp | 52bc247afd924e9a66c27105404ded9774959272 | []
| 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 | ISO-8859-1 | C++ | false | false | 23,669 | cpp | // AIPITreeView.cpp : implementation file
//
#include "stdafx.h"
#include "AIPI.h"
#include "AIPITreeDoc.h"
#include "AIPITreeView.h"
#include "FindInFilesDlg.h"
#include "MainFrm.h"
#include "PageFileDlg.h"
#include "InductionTabView.h"
#include ".\DataFileCSV\CDataFile.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CAIPITreeView
IMPLEMENT_DYNCREATE(CAIPITreeView, CView)
CAIPITreeView::CAIPITreeView()
{
}
CAIPITreeView::~CAIPITreeView()
{
}
BEGIN_MESSAGE_MAP(CAIPITreeView, CView)
//{{AFX_MSG_MAP(CAIPITreeView)
ON_WM_CREATE()
ON_WM_SETFOCUS()
ON_WM_SIZE()
ON_COMMAND(ID_VIEW_VERTICALTREE, OnViewVerticalTree)
ON_COMMAND(ID_VIEW_HORIZONTALTREE, OnViewHorizontalTree)
ON_COMMAND(ID_EDIT_CUT, OnEditCut)
ON_COMMAND(ID_EDIT_COPY, OnEditCopy)
ON_COMMAND(ID_EDIT_PASTE, OnEditPaste)
ON_COMMAND(ID_EDIT_FIND, OnEditFind)
ON_WM_DROPFILES()
ON_COMMAND(IDC_EXPAND_ALL_TREE, OnEditExpandAllTree)
ON_COMMAND(ID_COLLAPSE_ALL_ENTIRE_TREE, OnEditCollapseAllEntireTree)
ON_COMMAND(ID_EDIT_ADD_CHILD, OnEditAddChild)
ON_COMMAND(ID_EDIT_ADD_SIBLING, OnEditAddSibling)
ON_COMMAND(ID_EDIT_RENAME, OnEditRename)
ON_COMMAND(ID_EDIT_DELETE_ITEM, OnEditDeleteItem)
ON_COMMAND(ID_EDIT_DELETE_ALL_ITEMS, OnEditDeleteAllItems)
ON_COMMAND(ID_EDIT_SORT_SUBTREE_ALPHABETIC, OnEditSortSubtreeAlphabetic)
ON_COMMAND(ID_EDIT_SORT_SUBTREE_NUMERIC, OnEditSortSubtreeNumeric)
ON_COMMAND(IDC_EDIT_COUNT_SUBTREE, OnEditCountSubtree)
ON_COMMAND(IDC_EDIT_COUNT_ENTIRE_TREE, OnEditCountEntireTree)
ON_COMMAND(ID_EDIT_CALCULATE_LEVEL, OnEditCalculateLevel)
ON_COMMAND(ID_SETTINGS_FONTFACE, OnSettingsFontFace)
ON_COMMAND(ID_SETTINGS_NODECLR, OnSettingsNodeClr)
ON_COMMAND(ID_SETTINGS_LINKTEXTCLR, OnSettingsLinkTextClr)
ON_COMMAND(ID_SETTINGS_NODETEXTCLR, OnSettingsNodeTextClr)
ON_COMMAND(ID_SETTINGS_LEAFTEXTCLR, OnSettingsLeafTextClr)
ON_COMMAND(ID_SETTINGS_LINKCLR, OnSettingsLinkClr)
ON_COMMAND(ID_SETTINGS_LEAFCLR, OnSettingsLeafClr)
ON_COMMAND(ID_BUILD, OnInductionBuildTree)
ON_COMMAND(ID_SETTINGS_SKIN_CLASSIC, OnSettingsSkinClassic)
ON_COMMAND(ID_SETTINGS_SKIN_OFFICEXP, OnSettingsSkinOfficeXP)
ON_WM_DROPFILES()
ON_COMMAND(IDC_EDIT_EXPAND_ALL_TREE, OnEditExpandAllTree)
ON_COMMAND(ID_EDIT_COLLAPSE_ALL_ENTIRE_TREE, OnEditCollapseAllEntireTree)
ON_COMMAND(ID_SETTINGS_SKIN_OFFICE2003, OnSettingsSkinOffice2003)
//}}AFX_MSG_MAP
// Standard printing commands
ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CAIPITreeView drawing
void CAIPITreeView::OnDraw(CDC* pDC)
{
// TODO: add draw code here
/*
//pDC->SetMapMode(MM_LOENGLISH);
CRect rect = CRect(10, -10, 110, -110);
pDC->Rectangle(rect);
*/
CAIPITreeDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
// TODO: add draw code for native data here
if (m_etc.m_bCustomDrawn)
{
//Double Buffering...
CDC dc_backbuffer;
CBitmap bb_image;
//Calculate scoll position and control dimensions
m_etc.UpdateDimensions();
//Create device context for the backbuffer
dc_backbuffer.CreateCompatibleDC(pDC);
//Create the image we are going to draw in
bb_image.CreateCompatibleBitmap(pDC, m_etc.m_Rect.Width(), m_etc.m_Rect.Height());
dc_backbuffer.SelectObject(&bb_image);
//We use the same Font which was configured in the main device context
//dc_backbuffer.SelectObject(GetFont());
dc_backbuffer.SelectObject(&m_etc.m_NodeFont);
dc_backbuffer.SetBkMode(TRANSPARENT);
//General Info
DWORD style = GetStyle();
m_etc.m_bHasButtons = (style & TVS_HASBUTTONS) != 0;
m_etc.m_bHasLines = (style & TVS_HASLINES) != 0;
//Now draw the items...
m_etc.m_XMax = 0;
m_etc.m_YMax = 0;
//dc_backbuffer.FillSolidRect(m_Rect, dc_backbuffer.GetBkColor());
dc_backbuffer.FillSolidRect(m_etc.m_Rect, dc_backbuffer.SetBkColor(RGB(255, 255, 255)));
int xoffset = 0;
for (HTREEITEM root = m_etc.GetRootItem(); root != NULL; root = m_etc.GetNextItem(root, TVGN_NEXT))
xoffset = m_etc.DrawItem(&dc_backbuffer, root, xoffset);
//Copy the backbuffer to the main device context...
pDC->BitBlt( m_etc.m_Rect.left, m_etc.m_Rect.top, m_etc.m_Rect.Width(), m_etc.m_Rect.Height(), &dc_backbuffer, 0, 0, SRCCOPY);
//m_etc.ResetScrollbars();
}
}
/////////////////////////////////////////////////////////////////////////////
// CAIPITreeView diagnostics
#ifdef _DEBUG
void CAIPITreeView::AssertValid() const
{
CView::AssertValid();
}
void CAIPITreeView::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
CAIPITreeDoc* CAIPITreeView::GetDocument() // non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CAIPITreeDoc)));
return (CAIPITreeDoc*)m_pDocument;
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CAIPITreeView message handlers
BOOL CAIPITreeView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return CView::PreCreateWindow(cs);
}
void CAIPITreeView::OnEditCopy()
{
CMDIFrameWnd *pFrame = (CMDIFrameWnd*)AfxGetApp()->m_pMainWnd;
// Get the active MDI child window.
CMDIChildWnd *pChild = (CMDIChildWnd *) pFrame->GetActiveFrame();
// or CMDIChildWnd *pChild = pFrame->MDIGetActive();
// Get the active view attached to the active MDI child window
CAIPITreeView *ptfv= NULL;
ptfv = (CAIPITreeView *)pChild->GetActiveView();
ptfv->m_etc.OnSaveSubtree();
}
void CAIPITreeView::OnEditCut()
{
CMDIFrameWnd *pFrame = (CMDIFrameWnd*)AfxGetApp()->m_pMainWnd;
// Get the active MDI child window.
CMDIChildWnd *pChild = (CMDIChildWnd *) pFrame->GetActiveFrame();
// or CMDIChildWnd *pChild = pFrame->MDIGetActive();
// Get the active view attached to the active MDI child window
CAIPITreeView *ptfv = NULL;
ptfv = (CAIPITreeView *)pChild->GetActiveView();
ptfv->m_etc.CutSubtree();
}
void CAIPITreeView::OnEditPaste()
{
CMDIFrameWnd *pFrame = (CMDIFrameWnd*)AfxGetApp()->m_pMainWnd;
// Get the active MDI child window.
CMDIChildWnd *pChild = (CMDIChildWnd *) pFrame->GetActiveFrame();
// or CMDIChildWnd *pChild = pFrame->MDIGetActive();
// Get the active view attached to the active MDI child window
CAIPITreeView *ptfv = NULL;
ptfv = (CAIPITreeView *)pChild->GetActiveView();
ptfv->m_etc.OnLoadSubtree(ptfv->m_etc.GetSelectedItem());
}
void CAIPITreeView::OnEditFind()
{
CFindInFilesDlg m_Find;
if ( m_Find.DoModal() == IDOK )
{
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
pMainFrame->m_wndOutputTabView.m_TabViewContainer.SetActivePageIndex(2);
if (pMainFrame->m_wndOutputTabView.IsVisible() == FALSE)
//Set visible at first
pMainFrame->ShowControlBar(&pMainFrame->m_wndOutputTabView, TRUE ,TRUE);
CMDIFrameWnd *pFrame = (CMDIFrameWnd*)AfxGetApp()->m_pMainWnd;
// Get the active MDI child window.
CMDIChildWnd *pChild = (CMDIChildWnd *) pFrame->GetActiveFrame();
// or CMDIChildWnd *pChild = pFrame->MDIGetActive();
// Get the active view attached to the active MDI child window
CAIPITreeView *ptfv = NULL;
ptfv = (CAIPITreeView *)pChild->GetActiveView();
ptfv->m_etc.OnFindDlg(m_Find.m_strFind);
g_findText = m_Find.m_strFind;
}
}
void CAIPITreeView::OnDropFiles(HDROP hDropInfo)
{
/*
char path[_MAX_PATH];
CAIPITreeDoc *pted;
pted = GetDocument();
// Called when a file was dropped from Explorer
DragQueryFile(hDropInfo, 0, path, sizeof(path));
pted = (CAIPITreeDoc *)GetActiveDocument();
if (pted->SaveModified())
{
pted->m_strFileName = path;
pted->OpenFile();
}
*/
}
void CAIPITreeView::DrawNodeText(CDC *pDC, HTREEITEM item, CString text, int x, int y, int cx, int cy, COLORREF bkcolor,COLORREF txtcolor)
{
pDC->FillSolidRect(x+m_etc.m_OffsetX, -y-m_etc.m_OffsetY, cx, cy, bkcolor);
pDC->SetTextColor(txtcolor);
pDC->TextOut(x+m_etc.m_OffsetX,-y-m_etc.m_OffsetY,text);
pDC->SelectObject(&m_etc.m_NodeFont);
/*
ItemViewport *nvp = reinterpret_cast<CAIPITreeView> (m_etc.GetViewport(item));
nvp->x = x;
nvp->y = y;
nvp->cx = cx;
nvp->cy = cy;
*/
if (x + cx > m_etc.m_XMax)
m_etc.m_XMax = x + cx;
if (y + cy > m_etc.m_YMax)
m_etc.m_YMax = -(y + cy);
}
void CAIPITreeView::DrawLeafText(CDC *pDC, HTREEITEM item, CString text, int x, int y, int cx, int cy, COLORREF bkcolor,COLORREF txtcolor)
{
pDC->FillSolidRect(x+m_etc.m_OffsetX, -y-m_etc.m_OffsetY, cx, cy, bkcolor);
pDC->SetTextColor(txtcolor);
pDC->TextOut(x+m_etc.m_OffsetX,-y-m_etc.m_OffsetY,text);
pDC->SelectObject(&m_etc.m_LeafFont);
/*
ItemViewport *nvp = GetViewport(item);
nvp->x = x;
nvp->y = y;
nvp->cx = cx;
nvp->cy = cy;
*/
if (x + cx > m_etc.m_XMax)
m_etc.m_XMax = x + cx;
if (y + cy > m_etc.m_YMax)
m_etc.m_YMax = -(y + cy);
}
void CAIPITreeView::DrawLinkText(CDC *pDC, HTREEITEM item, CString text, int x, int y, int cx, int cy, COLORREF bkcolor,COLORREF txtcolor)
{
pDC->FillSolidRect(x+m_etc.m_OffsetX, -y-m_etc.m_OffsetY, cx, cy, bkcolor);
pDC->SetTextColor(txtcolor);
pDC->TextOut(x+m_etc.m_OffsetX,-y-m_etc.m_OffsetY,text);
pDC->SelectObject(&m_etc.m_LinkFont);
/*
ItemViewport *nvp = GetViewport(item);
nvp->x = x;
nvp->y = y;
nvp->cx = cx;
nvp->cy = cy;
*/
if (x + cx > m_etc.m_XMax)
m_etc.m_XMax = x + cx;
if (y + cy > m_etc.m_YMax)
m_etc.m_YMax = -(y + cy);
}
int CAIPITreeView::DrawItem(CDC *pDC, HTREEITEM item, int x, int level)
{
CString name = m_etc.GetItemText(item);
CString link_name = _T("");
CString node_name = _T("");
CSize text_size = 0;
//Separates the nodes text from the link text
for(int i = 0; i<name.GetLength(); i++)
{
if (name[i]== ':')
{
link_name = name.Left(i) ;
node_name = name.Right(name.GetLength() - i -1 );
break;
}
}
//Takes the larger text size
if( node_name != _T("") && link_name != _T(""))
{
if ( node_name.GetLength() > link_name.GetLength())
text_size = pDC->GetTextExtent(node_name);
else
text_size = pDC->GetTextExtent(link_name);
//Center text
int difference = abs(link_name.GetLength() - node_name.GetLength());
int space = (int)(difference/2);
if( link_name.GetLength() >= node_name.GetLength())
{
for(int i = 0; i<= space; i++)
node_name.Insert(i, _T(" "));
}
else
{
for(int i = 0; i<= space; i++)
link_name.Insert(i, _T(" "));
}
}
else
{
node_name = name;
text_size = pDC->GetTextExtent(name);
}
int state = m_etc.GetItemState(item, TVIF_STATE);
bool selected = (state & TVIS_SELECTED) != 0;
if (m_etc.ItemHasChildren(item))
{
int left = x;
int right = 0;
int childcount = 0;
if (state & TVIS_EXPANDED)
for (HTREEITEM childitem = m_etc.GetChildItem(item); childitem != NULL; childitem = m_etc.GetNextItem(childitem, TVGN_NEXT))
{
right = DrawItem(pDC, childitem, x, level + 1);
x = right;
childcount++;
}
right = right - m_etc.m_ItemSpaceX;
int width = right - left;
x = left + width / 2 - text_size.cx / 2;
if (x < left + m_etc.m_ItemSpaceX)
x = left;
int y = -level*m_etc.m_ItemSpaceY;
//Draw the link text a little more higher
if ( link_name.IsEmpty() == 0 )
DrawLinkText(pDC, item, link_name, x, level*m_etc.m_ItemSpaceY + m_etc.m_LinkNodeSpaceY, text_size.cx, text_size.cy, m_etc.m_LinkBkColor, m_etc.m_LinkTextColor);
//Draw the node text
DrawNodeText(pDC, item, node_name, x, -level*m_etc.m_ItemSpaceY, text_size.cx, text_size.cy, m_etc.m_NodeBkColor, m_etc.m_NodeTextColor);
//Draw lines...
if (m_etc.m_bHasLines && (state & TVIS_EXPANDED))
{
int xstart = x + text_size.cx / 2;
int ystart = y - text_size.cy + BUTTON_SIZE;
CGdiObject *oldPen = pDC->SelectObject(&m_etc.m_TreeLinePen);
for (HTREEITEM childitem = m_etc.GetChildItem(item); childitem != NULL; childitem = m_etc.GetNextItem(childitem, TVGN_NEXT))
{
//ItemViewport *current = (CAIPITreeView*)m_etc.GetViewport(childitem);
pDC->MoveTo(xstart+m_etc.m_OffsetX,ystart+m_etc.m_OffsetY);
//pDC->LineTo(current->x +m_etc.m_OffsetX + current->cx / 2 , current->y - m_etc.m_OffsetY);
}
pDC->SelectObject(oldPen);
}
if (m_etc.m_bHasButtons)
{
pDC->Draw3dRect(x+m_etc.m_OffsetX+text_size.cx / 2 - BUTTON_SIZE / 2, y-m_etc.m_OffsetY + text_size.cy, BUTTON_SIZE, BUTTON_SIZE, m_etc.m_clrTopLeft, m_etc.m_clrBottomRight);
pDC->MoveTo(x+m_etc.m_OffsetX+text_size.cx / 2 - BUTTON_SIZE / 2 + 2, y-m_etc.m_OffsetY + text_size.cy + BUTTON_SIZE / 2);
pDC->LineTo(x+m_etc.m_OffsetX+text_size.cx / 2 + BUTTON_SIZE / 2 - 1, y-m_etc.m_OffsetY + text_size.cy + BUTTON_SIZE / 2);
if ((state & TVIS_EXPANDED) == 0)
{
pDC->MoveTo(x+m_etc.m_OffsetX+text_size.cx / 2, y-m_etc.m_OffsetY + text_size.cy + 2);
pDC->LineTo(x+m_etc.m_OffsetX+text_size.cx / 2, y-m_etc.m_OffsetY + text_size.cy + BUTTON_SIZE - 2);
}
}
if (right > x + text_size.cx)
return right + m_etc.m_ItemSpaceX;
else
return x + text_size.cx + m_etc.m_ItemSpaceX;
}
else
{
//Draw the link name from the leaf a little more higher
if ( link_name.IsEmpty() == 0 )
DrawLinkText(pDC, item, link_name, x, level*m_etc.m_ItemSpaceY + m_etc.m_LinkNodeSpaceY, text_size.cx, text_size.cy, m_etc.m_LinkBkColor, m_etc.m_LinkTextColor);
//Draw the node text from the leaf
DrawLeafText(pDC, item, node_name, x, -level*m_etc.m_ItemSpaceY, text_size.cx, text_size.cy, m_etc.m_LeafBkColor, m_etc.m_LeafTextColor);
return x + text_size.cx + m_etc.m_ItemSpaceX;
}
}
void CAIPITreeView::OnInitialUpdate()
{
CView::OnInitialUpdate();
m_etc.SetLimitText(100);
m_etc.InitializeImageList();
m_etc.SetCustomDrawn(FALSE);
//CID3 dt;
//dt.AddSiblingName(_T("Hola pueblo"));
//dt.AddChildName(_T("Hola hijo del pueblo"));
//dt.AddMsgOutputWnd(_T("Mensaje de prueba del arbol de desición ID3"));
/*
m_etc.OnAddSiblingName("Hombres < 456");
m_etc.OnAddChildName("Nodo01");
m_etc.OnAddChildName("Nodo02");
m_etc.OnAddSiblingName("Mujeres");
m_etc.OnAddChildName("Nodo03");
m_etc.OnAddChildName("Nodo04");
m_etc.OnAddSiblingName("Hombres > 456");
m_etc.OnAddChildName("Nodo01");
m_etc.OnAddChildName("Nodo02");
m_etc.OnAddSiblingName("Mujeres");
m_etc.OnAddChildName("Nodo03");
m_etc.OnAddChildName("Nodo04");
*/
// TODO: You may populate your TreeView with items by directly accessing
// its tree control through a call to GetTreeCtrl().
UpdateSkinMenus();
}
void CAIPITreeView::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint)
{
if (m_etc.m_pted == NULL)
m_etc.m_pted = (CAIPITreeDoc *)GetDocument();
switch(lHint)
{
case HINT_NEW:
m_etc.DeleteAllItems();
break;
case HINT_LOAD_DIRECTORY:
m_etc.DeleteAllItems();
m_etc.OnLoadEntireTree(FF_DIRECTORY_TYPE, m_etc.m_pted->m_tt);
break;
case HINT_LOAD_TREE_TYPE:
m_etc.DeleteAllItems();
m_etc.OnLoadEntireTree(FF_TREE_TYPE, m_etc.m_pted->m_tt);
break;
case HINT_LOAD_PROJ_TYPE:
m_etc.DeleteAllItems();
m_etc.OnLoadEntireTree(FF_PROJ_TYPE, m_etc.m_pted->m_tt);
break;
case HINT_LOAD_INDENT_TYPE:
m_etc.DeleteAllItems();
m_etc.OnLoadEntireTree(FF_INDENT_TYPE, m_etc.m_pted->m_tt);
break;
case HINT_LOAD_CSV_TYPE:
m_etc.DeleteAllItems();
m_etc.OnLoadEntireTree(FF_CSV_TYPE, m_etc.m_pted->m_tt);
break;
case HINT_SAVE_TREE_TYPE:
m_etc.OnSaveEntireTree(FF_TREE_TYPE, m_etc.m_pted->m_tt);
break;
case HINT_SAVE_PROJ_TYPE:
m_etc.OnSaveEntireTree(FF_PROJ_TYPE, m_etc.m_pted->m_tt);
break;
case HINT_SAVE_INDENT_TYPE:
m_etc.OnSaveEntireTree(FF_INDENT_TYPE, m_etc.m_pted->m_tt);
break;
case HINT_SAVE_CSV_TYPE:
m_etc.OnSaveEntireTree(FF_CSV_TYPE, m_etc.m_pted->m_tt);
break;
default:
break;
}
}
int CAIPITreeView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CView::OnCreate(lpCreateStruct) == -1)
return -1;
//Create the tree view
CRect r;
DWORD newstyle = TVS_SHOWSELALWAYS | TVS_EDITLABELS | TVS_HASBUTTONS |
TVS_LINESATROOT | TVS_HASLINES;
if (!m_etc.Create(WS_VISIBLE | WS_CHILD | newstyle, r, this, 100))
return -1;
return 0;
}
void CAIPITreeView::OnSetFocus(CWnd* pOldWnd)
{
CView::OnSetFocus(pOldWnd);
m_etc.SetFocus();
}
void CAIPITreeView::OnSize(UINT nType, int cx, int cy)
{
//Let the tree control occupy all the space of the client area
CRect r;
GetClientRect(&r);
m_etc.MoveWindow(r);
//m_etc.MoveWindow(0, 30, cx, cy-40);
}
/////////////////////////////////////////////////////////////////////////////
// CAIPITreeView printing
BOOL CAIPITreeView::OnPreparePrinting(CPrintInfo* pInfo)
{
// default preparation
return DoPreparePrinting(pInfo);
}
void CAIPITreeView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add extra initialization before printing
}
void CAIPITreeView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add cleanup after printing
}
/////////////////////////////////////////////////////////////////////////////
// CAIPITreeView message handlers
void CAIPITreeView::OnViewVerticalTree()
{
m_etc.SetCustomDrawn(TRUE);
m_etc.Invalidate();
}
void CAIPITreeView::OnViewHorizontalTree()
{
m_etc.SetCustomDrawn(FALSE);
m_etc.Invalidate();
CAIPITreeDoc *pDoc = GetDocument();
CString strTitle = (CString) pDoc->GetTitle();
CString strExt = strTitle.Right(3);
//Open different files extensions
if (m_etc.m_pted == NULL)
m_etc.m_pted = (CAIPITreeDoc *)GetDocument();
if(strExt == "tre")
{
m_etc.DeleteAllItems();
m_etc.OnLoadEntireTree(FF_TREE_TYPE, m_etc.m_pted->m_tt);
}
else if(strExt == _T("csv"))
{
m_etc.DeleteAllItems();
m_etc.OnLoadEntireTree(FF_CSV_TYPE, m_etc.m_pted->m_tt);
}
else if(strExt == _T("idt"))
{
m_etc.DeleteAllItems();
m_etc.OnLoadEntireTree(FF_INDENT_TYPE, m_etc.m_pted->m_tt);
}
else
{
MessageBox(_T("Invalid input file " + pDoc->m_strFileNamePath ));
}
}
void CAIPITreeView::OnPrepareDC(CDC* pDC, CPrintInfo* pInfo)
{
//pDC->SetMapMode(MM_LOENGLISH);
pDC->SetMapMode(MM_TEXT);
//CView::OnPrepareDC(pDC, pInfo);
}
void CAIPITreeView::OnPrint(CDC* pDC, CPrintInfo* pInfo)
{
//pDC->SetWindowOrg(pInfo->m_rectDraw.left, -pInfo->m_rectDraw.top);
// Diseño de MM_LOMETRIC con el eje "y" positivo hacia abajo
/*
int nTamX = pDC->GetDeviceCaps(HORZSIZE) * 10; // unidades lógicas
int nTamY = pDC->GetDeviceCaps(VERTSIZE) * 10; // unidades lógicas
int nResX = pDC->GetDeviceCaps(HORZRES); // unidades físicas
int nResY = pDC->GetDeviceCaps(VERTRES); // unidades físicas
pDC->SetMapMode(MM_ANISOTROPIC);
pDC->SetWindowExt(nTamX, nTamY);
pDC->SetViewportExt(nResX, nResY);
/*
// Convertir coordenadas físicas a lógicas
pDC->DPtoLP(pInfo->m_rectDraw);
if ( pInfo->m_nCurPage == 1 ) // si es la página 1
{
// Imprimir el título y una posible historia
PrintTitulo( pDC, pInfo );
// Imprima aquí su historia
return;
}
// Imprimir la cabecera
CString sCabecera = GetDocument()->GetTitle();
PrintCabecera( pDC, pInfo, sCabecera );
// Establecer el origen para el cuerpo de la página
pDC->SetWindowOrg(pInfo->m_rectDraw.left, pInfo->m_rectDraw.top);
*/
CView::OnPrint(pDC, pInfo);
}
void CAIPITreeView::OnEditExpandAllTree()
{
m_etc.OnExpandAllTree();
}
void CAIPITreeView::OnEditCollapseAllEntireTree()
{
m_etc.OnCollapseAllEntireTree();
}
void CAIPITreeView::OnEditAddChild()
{
m_etc.OnAddChild();
}
void CAIPITreeView::OnEditAddSibling()
{
m_etc.OnAddSibling();
}
void CAIPITreeView::OnEditRename()
{
m_etc.OnRename();
}
void CAIPITreeView::OnEditDeleteItem()
{
m_etc.OnDeleteItem();
}
void CAIPITreeView::OnEditDeleteAllItems()
{
m_etc.OnDeleteAllItems();
}
void CAIPITreeView::OnEditSortSubtreeAlphabetic()
{
m_etc.OnSortSubtreeAlphabetic();
}
void CAIPITreeView::OnEditSortSubtreeNumeric()
{
m_etc.OnSortSubtreeNumeric();
}
void CAIPITreeView::OnEditCountSubtree()
{
m_etc.OnCountSubtree();
}
void CAIPITreeView::OnEditCountEntireTree()
{
m_etc.OnCountEntireTree();
}
void CAIPITreeView::OnEditCalculateLevel()
{
m_etc.OnCalculateLevel();
}
void CAIPITreeView::OnSettingsFontFace()
{
m_etc.OnChangeTextFace();
m_etc.Invalidate();
}
void CAIPITreeView::OnSettingsLinkTextClr()
{
m_etc.OnChangeLinkTextColor();
m_etc.Invalidate();
}
void CAIPITreeView::OnSettingsNodeTextClr()
{
m_etc.OnChangeNodeTextColor();
m_etc.Invalidate();
}
void CAIPITreeView::OnSettingsLeafTextClr()
{
m_etc.OnChangeLeafTextColor();
m_etc.Invalidate();
}
void CAIPITreeView::OnSettingsNodeClr()
{
m_etc.OnChangeNodeBkColor();
m_etc.Invalidate();
}
void CAIPITreeView::OnSettingsLinkClr()
{
m_etc.OnChangeLinkBkColor();
m_etc.Invalidate();
}
void CAIPITreeView::OnSettingsLeafClr()
{
m_etc.OnChangeLeafBkColor();
m_etc.Invalidate();
}
void CAIPITreeView::OnInductionBuildTree()
{
/*
m_etc.m_pted = (CAIPITreeDoc *)GetDocument();
m_etc.m_pted->m_strFileNamePath = _T("D:\\Project AIPI VS6\\AIPI\\Examples\\Cicuta.idt");
m_etc.m_pted->OpenFile();
m_etc.m_pted->m_strFileNamePath = _T("D:\\Project AIPI VS6\\AIPI\\Examples\\MFC_Classes.idt");
m_etc.m_pted->OpenFile();
*/
OnEditDeleteAllItems();
m_etc.SetCustomDrawn(FALSE);
BeginWaitCursor(); // display the hourglass cursor
UpdateWindow();
CAipi_DT_ID3 dt;
dt.Build();
EndWaitCursor();
//dlg.OnOpenDatabaseConnection(MS_ACCESS);
/*
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
if ( pMainFrame->m_wndInductionTabView.IsVisible() )
{
pMainFrame->m_wndInductionTabView.OnOpenDatabaseConnection(MS_ACCESS);
}
*/
}
void CAIPITreeView::OnSettingsSkinClassic()
{
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
pMainFrame->OnSettingsSkinClassic();
pMainFrame->CheckMenuSkinType();
}
void CAIPITreeView::OnSettingsSkinOfficeXP()
{
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
pMainFrame->OnSettingsSkinOfficeXP();
pMainFrame->CheckMenuSkinType();
}
void CAIPITreeView::OnSettingsSkinOffice2003()
{
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
pMainFrame->OnSettingsSkinOffice2003();
pMainFrame->CheckMenuSkinType();
}
void CAIPITreeView::UpdateSkinMenus()
{
/*
TCHAR buffer[8];
CString str = _itot( g_iSkinType, buffer, 10 );
AfxMessageBox(_T("CAIPITreeView"));
AfxMessageBox(str);
*/
switch(g_iSkinType)
{
case OXSkinClassic:
OnSettingsSkinClassic();
break;
case OXSkinOfficeXP:
OnSettingsSkinOfficeXP();
break;
case OXSkinOffice2003:
OnSettingsSkinOffice2003();
break;
}
}
| [
"[email protected]"
]
| [
[
[
1,
934
]
]
]
|
e412d608154aa0f2efc47555e9258f8eae56ec46 | 6bdb3508ed5a220c0d11193df174d8c215eb1fce | /Codes/Halak/Entity.cpp | 94b8776dbec5ff9865f39b93b9336d8770cc01c8 | []
| no_license | halak/halak-plusplus | d09ba78640c36c42c30343fb10572c37197cfa46 | fea02a5ae52c09ff9da1a491059082a34191cd64 | refs/heads/master | 2020-07-14T09:57:49.519431 | 2011-07-09T14:48:07 | 2011-07-09T14:48:07 | 66,716,624 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,099 | cpp | #include <Halak/PCH.h>
#include <Halak/Entity.h>
#include <Halak/CloningContext.h>
#include <Halak/ObjectOperators.h>
#include <Halak/SharedObject.h>
#include <algorithm>
namespace Halak
{
struct ComponentPredicate
{
inline bool operator () (const EntityComponent& a, const EntityComponent& b) const
{
return a.GetName() < b.GetName();
}
inline bool operator () (const String& name, const EntityComponent& b) const
{
return name < b.GetName();
}
inline bool operator () (const EntityComponent& a, const String& name) const
{
return a.GetName() < name;
}
};
Entity::Entity()
{
}
Entity::Entity(int numberOfIndexedComponents)
{
indexedComponents.resize(numberOfIndexedComponents);
}
Entity::Entity(const String& type)
: type(type)
{
}
Entity::Entity(const String& type, const String& name)
: type(type),
name(name)
{
}
Entity::Entity(const String& type, const String& name, int numberOfIndexedComponents)
: type(type),
name(name)
{
indexedComponents.resize(numberOfIndexedComponents);
}
Entity::~Entity()
{
DestructAll(indexedComponents);
DestructAll(components);
}
void Entity::Insert(const EntityComponent& item)
{
ComponentCollection::iterator it = FindIterator(item.GetName());
if (it != components.end())
{
if ((*it) != item)
{
EntityComponent removedComponent = (*it);
(*it) = item;
if (removedComponent.GetOperator())
removedComponent.GetOperator()->Destruct(removedComponent.GetObject());
OnComponentRemoved(removedComponent);
}
}
else
{
it = std::lower_bound(components.begin(), components.end(), item, ComponentPredicate());
components.insert(it, item);
}
OnComponentChanged(item);
}
bool Entity::Remove(const String& name)
{
ComponentCollection::iterator it = FindIterator(name);
if (it != components.end())
{
EntityComponent removedComponent = (*it);
components.erase(it);
if (removedComponent.GetOperator())
removedComponent.GetOperator()->Destruct(removedComponent.GetObject());
OnComponentRemoved(removedComponent);
return true;
}
else
return false;
}
void Entity::RemoveAll()
{
ComponentCollection removedComponents;
removedComponents.swap(components);
DestructAll(removedComponents);
if (removedComponents.empty() == false)
OnComponentsRemoved(removedComponents);
}
const EntityComponent* Entity::Find(const String& name) const
{
ComponentCollection::const_iterator it = FindIterator(name);
if (it != components.end())
return &(*it);
else
return nullptr;
}
void Entity::SetComponents(const ComponentCollection& value)
{
ComponentCollection removedComponents;
removedComponents.swap(components);
components = value;
std::sort(components.begin(), components.end(), ComponentPredicate());
if (removedComponents.empty() == false)
OnComponentsRemoved(removedComponents);
}
Entity::ComponentCollection::iterator Entity::FindIterator(const String& name)
{
ComponentCollection::iterator it = std::lower_bound(components.begin(), components.end(), name, ComponentPredicate());
if (it != components.end() && (*it).GetName() == name)
return it;
else
return components.end();
}
Entity::ComponentCollection::const_iterator Entity::FindIterator(const String& name) const
{
ComponentCollection::const_iterator it = std::lower_bound(components.begin(), components.end(), name, ComponentPredicate());
if (it != components.end() && (*it).GetName() == name)
return it;
else
return components.end();
}
void Entity::OnNameChanged(const String& /*old*/)
{
}
void Entity::OnComponentChanged(const EntityComponent& /*item*/)
{
}
void Entity::OnComponentRemoved(const EntityComponent& /*item*/)
{
}
void Entity::OnComponentsRemoved(const ComponentCollection& /*items*/)
{
}
void Entity::DestructAll(ComponentCollection& components)
{
for (ComponentCollection::iterator it = components.begin(); it != components.end(); it++)
{
const EntityComponent& item = (*it);
if (item.GetOperator())
item.GetOperator()->Destruct(item.GetObject());
}
}
} | [
"[email protected]"
]
| [
[
[
1,
181
]
]
]
|
407200d6ba2947192d642a16ebb5a789401c2392 | 974a20e0f85d6ac74c6d7e16be463565c637d135 | /trunk/coreLibrary_200/source/physics/dgCollisionHeightField.cpp | 308f23977cb0df1ad5e850640b4cf9179c652621 | []
| no_license | Naddiseo/Newton-Dynamics-fork | cb0b8429943b9faca9a83126280aa4f2e6944f7f | 91ac59c9687258c3e653f592c32a57b61dc62fb6 | refs/heads/master | 2021-01-15T13:45:04.651163 | 2011-11-12T04:02:33 | 2011-11-12T04:02:33 | 2,759,246 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 39,536 | cpp | /* Copyright (c) <2003-2011> <Julio Jerez, Newton Game Dynamics>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "dgPhysicsStdafx.h"
#include "dgBody.h"
#include "dgWorld.h"
#include "dgCollisionHeightField.h"
#define DG_HIGHTFILD_DATA_ID 0x45AF5E07
dgCollisionHeightField::dgCollisionHeightField(dgWorld* const world,
dgInt32 width, dgInt32 height, dgInt32 contructionMode,
const dgUnsigned16* const elevationMap, const dgInt8* const atributeMap,
dgFloat32 horizontalScale, dgFloat32 vertcalScale) :
dgCollisionMesh(world->GetAllocator(), m_heightField)
{
dgFloat32 y0;
dgFloat32 y1;
m_userRayCastCallback = NULL;
m_rtti |= dgCollisionHeightField_RTTI;
m_width = width;
m_height = height;
m_diagonalMode = contructionMode;
m_verticalScale = vertcalScale;
m_horizontalScale = horizontalScale;
m_elevationMap = (dgUnsigned16 *) dgMallocStack(
m_width * m_height * sizeof(dgUnsigned16));
memcpy(m_elevationMap, elevationMap,
m_width * m_height * sizeof(dgUnsigned16));
m_atributeMap = (dgInt8 *) dgMallocStack(m_width * m_height * sizeof(dgInt8));
memcpy(m_atributeMap, atributeMap, m_width * m_height * sizeof(dgInt8));
y0 = dgFloat32(0.0f);
y1 = dgFloat32(-dgFloat32(1.0e10f));
for (dgInt32 i = 0; i < m_width * m_height; i++)
{
y1 = GetMax(y1, dgFloat32(m_elevationMap[i]));
}
m_minBox = dgVector(dgFloat32(dgFloat32(0.0f)), y0 * m_verticalScale,
dgFloat32(dgFloat32(0.0f)), dgFloat32(dgFloat32(1.0f)));
m_maxBox = dgVector(dgFloat32(m_width - 1) * m_horizontalScale,
y1 * m_verticalScale, dgFloat32(m_height - 1) * m_horizontalScale,
dgFloat32(dgFloat32(1.0f)));
// m_verticalScaleInv = dgFloat32 (1.0f) / m_verticalScale;
m_horizontalScaleInv = dgFloat32(1.0f) / m_horizontalScale;
dgTree<void*, unsigned>::dgTreeNode* nodeData = world->m_perInstanceData.Find(
DG_HIGHTFILD_DATA_ID);
if (!nodeData)
{
m_instanceData = (dgPerIntanceData*) dgMallocStack(
sizeof(dgPerIntanceData));
m_instanceData->m_refCount = 0;
m_instanceData->m_world = world;
for (dgInt32 i = 0; i < DG_MAXIMUN_THREADS; i++)
{
m_instanceData->m_vertex[i] = NULL;
m_instanceData->m_vertexCount[i] = 8 * 8;
AllocateVertex(world, i);
}
nodeData = world->m_perInstanceData.Insert(m_instanceData,
DG_HIGHTFILD_DATA_ID);
}
m_instanceData = (dgPerIntanceData*) nodeData->GetInfo();
m_instanceData->m_refCount++;
SetCollisionBBox(m_minBox, m_maxBox);
}
dgCollisionHeightField::dgCollisionHeightField(dgWorld* const world,
dgDeserialize deserialization, void* const userData) :
dgCollisionMesh(world, deserialization, userData)
{
m_rtti |= dgCollisionHeightField_RTTI;
m_userRayCastCallback = NULL;
deserialization(userData, &m_width, sizeof(dgInt32));
deserialization(userData, &m_height, sizeof(dgInt32));
deserialization(userData, &m_diagonalMode, sizeof(dgInt32));
deserialization(userData, &m_verticalScale, sizeof(dgFloat32));
deserialization(userData, &m_horizontalScale, sizeof(dgFloat32));
deserialization(userData, &m_minBox.m_x, sizeof(dgVector));
deserialization(userData, &m_maxBox.m_x, sizeof(dgVector));
m_elevationMap = (dgUnsigned16 *) dgMallocStack(
m_width * m_height * sizeof(dgUnsigned16));
m_atributeMap = (dgInt8 *) dgMallocStack(m_width * m_height * sizeof(dgInt8));
deserialization(userData, m_elevationMap,
m_width * m_height * sizeof(dgUnsigned16));
deserialization(userData, m_atributeMap, m_width * m_height * sizeof(dgInt8));
// m_verticalScaleInv = dgFloat32 (1.0f) / m_verticalScale;
m_horizontalScaleInv = dgFloat32(1.0f) / m_horizontalScale;
dgTree<void*, unsigned>::dgTreeNode* nodeData = world->m_perInstanceData.Find(
DG_HIGHTFILD_DATA_ID);
if (!nodeData)
{
m_instanceData = (dgPerIntanceData*) dgMallocStack(
sizeof(dgPerIntanceData));
m_instanceData->m_refCount = 0;
m_instanceData->m_world = world;
for (dgInt32 i = 0; i < DG_MAXIMUN_THREADS; i++)
{
m_instanceData->m_vertex[i] = NULL;
m_instanceData->m_vertexCount[i] = 8 * 8;
AllocateVertex(world, i);
}
nodeData = world->m_perInstanceData.Insert(m_instanceData,
DG_HIGHTFILD_DATA_ID);
}
m_instanceData = (dgPerIntanceData*) nodeData->GetInfo();
m_instanceData->m_refCount++;
SetCollisionBBox(m_minBox, m_maxBox);
}
dgCollisionHeightField::~dgCollisionHeightField(void)
{
m_instanceData->m_refCount--;
if (!m_instanceData->m_refCount)
{
dgWorld* world = m_instanceData->m_world;
for (dgInt32 i = 0; i < DG_MAXIMUN_THREADS; i++)
{
dgFreeStack(m_instanceData->m_vertex[i]);
}
dgFreeStack(m_instanceData);
world->m_perInstanceData.Remove(DG_HIGHTFILD_DATA_ID);
}
dgFreeStack(m_elevationMap);
dgFreeStack(m_atributeMap);
}
void dgCollisionHeightField::Serialize(dgSerialize callback,
void* const userData) const
{
// dgVector size (m_size[0].Scale (dgFloat32 (2.0f)));
SerializeLow(callback, userData);
// callback (userData, &size, sizeof (dgVector));
callback(userData, &m_width, sizeof(dgInt32));
callback(userData, &m_height, sizeof(dgInt32));
callback(userData, &m_diagonalMode, sizeof(dgInt32));
callback(userData, &m_verticalScale, sizeof(dgFloat32));
callback(userData, &m_horizontalScale, sizeof(dgFloat32));
callback(userData, &m_minBox.m_x, sizeof(dgVector));
callback(userData, &m_maxBox.m_x, sizeof(dgVector));
callback(userData, m_elevationMap, m_width * m_height * sizeof(dgInt16));
callback(userData, m_atributeMap, m_width * m_height * sizeof(dgInt8));
}
void dgCollisionHeightField::SetCollisionRayCastCallback(
dgCollisionHeightFieldRayCastCallback rayCastCallback)
{
m_userRayCastCallback = rayCastCallback;
}
void dgCollisionHeightField::AllocateVertex(dgWorld* const world,
dgInt32 threadIndex) const
{
dgVector *vertex;
vertex = (dgVector *) dgMallocStack(
2 * m_instanceData->m_vertexCount[threadIndex] * sizeof(dgVector));
if (m_instanceData->m_vertex[threadIndex])
{
memcpy(vertex, m_instanceData->m_vertex[threadIndex],
m_instanceData->m_vertexCount[threadIndex] * sizeof(dgVector));
dgFreeStack(m_instanceData->m_vertex[threadIndex]);
}
m_instanceData->m_vertexCount[threadIndex] *= 2;
m_instanceData->m_vertex[threadIndex] = vertex;
}
void dgCollisionHeightField::GetCollisionInfo(dgCollisionInfo* info) const
{
dgCollision::GetCollisionInfo(info);
info->m_offsetMatrix = GetOffsetMatrix();
info->m_collisionType = m_collsionId;
dgCollisionInfo::dgHeightMapCollisionData& data = info->m_heightFieldCollision;
data.m_width = m_width;
data.m_height = m_height;
data.m_gridsDiagonals = m_diagonalMode;
data.m_verticalScale = m_verticalScale;
data.m_horizonalScale = m_horizontalScale;
data.m_atributes = m_atributeMap;
data.m_elevation = m_elevationMap;
}
void dgCollisionHeightField::CalculateMinExtend2d(const dgVector& p0,
const dgVector& p1, dgVector& boxP0, dgVector& boxP1) const
{
dgFloat32 x0 = GetMin(p0.m_x, p1.m_x) - dgFloat32(1.0e-3f);
dgFloat32 z0 = GetMin(p0.m_z, p1.m_z) - dgFloat32(1.0e-3f);
dgFloat32 x1 = GetMax(p0.m_x, p1.m_x) + dgFloat32(1.0e-3f);
dgFloat32 z1 = GetMax(p0.m_z, p1.m_z) + dgFloat32(1.0e-3f);
x0 = m_horizontalScale * dgFloor(x0 * m_horizontalScaleInv);
z0 = m_horizontalScale * dgFloor(z0 * m_horizontalScaleInv);
x1 = m_horizontalScale * dgFloor(x1 * m_horizontalScaleInv)
+ m_horizontalScale;
z1 = m_horizontalScale * dgFloor(z1 * m_horizontalScaleInv)
+ m_horizontalScale;
boxP0.m_x = GetMax(x0, m_minBox.m_x);
boxP0.m_z = GetMax(z0, m_minBox.m_z);
boxP0.m_y = -dgFloat32(1.0e10f);
boxP0.m_w = dgFloat32(0.0f);
boxP1.m_x = GetMin(x1, m_maxBox.m_x);
boxP1.m_z = GetMin(z1, m_maxBox.m_z);
boxP1.m_y = dgFloat32(1.0e10f);
boxP1.m_w = dgFloat32(0.0f);
}
void dgCollisionHeightField::CalculateMinExtend3d(const dgVector& p0,
const dgVector& p1, dgVector& boxP0, dgVector& boxP1) const
{
_ASSERTE(p0.m_x <= p1.m_x);
_ASSERTE(p0.m_y <= p1.m_y);
_ASSERTE(p0.m_z <= p1.m_z);
dgFloat32 x0 = m_horizontalScale
* dgFloor((p0.m_x - dgFloat32(1.0e-3f)) * m_horizontalScaleInv);
dgFloat32 z0 = m_horizontalScale
* dgFloor((p0.m_z - dgFloat32(1.0e-3f)) * m_horizontalScaleInv);
dgFloat32 x1 = m_horizontalScale
* dgFloor((p1.m_x + dgFloat32(1.0e-3f)) * m_horizontalScaleInv)
+ m_horizontalScale;
dgFloat32 z1 = m_horizontalScale
* dgFloor((p1.m_z + dgFloat32(1.0e-3f)) * m_horizontalScaleInv)
+ m_horizontalScale;
boxP0.m_x = GetMax(x0, m_minBox.m_x);
boxP0.m_z = GetMax(z0, m_minBox.m_z);
boxP0.m_y = p0.m_y - dgFloat32(1.0e-3f);
boxP0.m_w = dgFloat32(0.0f);
boxP1.m_x = GetMin(x1, m_maxBox.m_x);
boxP1.m_z = GetMin(z1, m_maxBox.m_z);
boxP1.m_y = p1.m_y + dgFloat32(1.0e-3f);
boxP1.m_w = dgFloat32(0.0f);
}
dgFloat32 dgCollisionHeightField::RayCastCellSimd(const FastRayTest& ray,
dgInt32 xIndex0, dgInt32 zIndex0, dgVector& normalOut) const
{
dgFloat32 t;
dgInt32 base;
dgInt32 triangle[3];
dgVector points[4];
// get the 3d point at the corner of the cell
if ((xIndex0 < 0) || (zIndex0 < 0) || (xIndex0 >= (m_width - 1))
|| (zIndex0 >= (m_height - 1)))
{
return dgFloat32(1.2f);
}
base = zIndex0 * m_width + xIndex0;
points[0 * 2 + 0] = dgVector((xIndex0 + 0) * m_horizontalScale,
dgFloat32(m_elevationMap[base]) * m_verticalScale,
(zIndex0 + 0) * m_horizontalScale, dgFloat32(0.0f));
points[0 * 2 + 1] = dgVector((xIndex0 + 1) * m_horizontalScale,
dgFloat32(m_elevationMap[base + 1]) * m_verticalScale,
(zIndex0 + 0) * m_horizontalScale, dgFloat32(0.0f));
points[1 * 2 + 1] = dgVector((xIndex0 + 1) * m_horizontalScale,
dgFloat32(m_elevationMap[base + m_width + 1]) * m_verticalScale,
(zIndex0 + 1) * m_horizontalScale, dgFloat32(0.0f));
points[1 * 2 + 0] = dgVector((xIndex0 + 0) * m_horizontalScale,
dgFloat32(m_elevationMap[base + m_width + 0]) * m_verticalScale,
(zIndex0 + 1) * m_horizontalScale, dgFloat32(0.0f));
t = dgFloat32(1.2f);
if (!m_diagonalMode)
{
triangle[0] = 1;
triangle[1] = 2;
triangle[2] = 3;
dgVector e10(points[2] - points[1]);
dgVector e20(points[3] - points[1]);
dgVector normal(e10 * e20);
t = ray.PolygonIntersectSimd(normal, &points[0].m_x, sizeof(dgVector),
triangle, 3);
if (t < dgFloat32(1.0f))
{
normalOut = normal;
return t;
}
triangle[0] = 1;
triangle[1] = 0;
triangle[2] = 2;
dgVector e30(points[0] - points[1]);
normal = e30 * e10;
t = ray.PolygonIntersectSimd(normal, &points[0].m_x, sizeof(dgVector),
triangle, 3);
if (t < dgFloat32(1.0f))
{
normalOut = normal;
return t;
}
}
else
{
triangle[0] = 0;
triangle[1] = 2;
triangle[2] = 3;
dgVector e10(points[2] - points[0]);
dgVector e20(points[3] - points[0]);
dgVector normal(e10 * e20);
t = ray.PolygonIntersectSimd(normal, &points[0].m_x, sizeof(dgVector),
triangle, 3);
if (t < dgFloat32(1.0f))
{
normalOut = normal;
return t;
}
triangle[0] = 0;
triangle[1] = 3;
triangle[2] = 1;
dgVector e30(points[1] - points[0]);
normal = e20 * e30;
t = ray.PolygonIntersectSimd(normal, &points[0].m_x, sizeof(dgVector),
triangle, 3);
if (t < dgFloat32(1.0f))
{
normalOut = normal;
return t;
}
}
return t;
}
dgFloat32 dgCollisionHeightField::RayCastCell(const FastRayTest& ray,
dgInt32 xIndex0, dgInt32 zIndex0, dgVector& normalOut) const
{
dgFloat32 t;
dgInt32 base;
dgInt32 triangle[3];
dgVector points[4];
// get the 3d point at the corner of the cell
if ((xIndex0 < 0) || (zIndex0 < 0) || (xIndex0 >= (m_width - 1))
|| (zIndex0 >= (m_height - 1)))
{
return dgFloat32(1.2f);
}
base = zIndex0 * m_width + xIndex0;
points[0 * 2 + 0] = dgVector((xIndex0 + 0) * m_horizontalScale,
dgFloat32(m_elevationMap[base]) * m_verticalScale,
(zIndex0 + 0) * m_horizontalScale, dgFloat32(0.0f));
points[0 * 2 + 1] = dgVector((xIndex0 + 1) * m_horizontalScale,
dgFloat32(m_elevationMap[base + 1]) * m_verticalScale,
(zIndex0 + 0) * m_horizontalScale, dgFloat32(0.0f));
points[1 * 2 + 1] = dgVector((xIndex0 + 1) * m_horizontalScale,
dgFloat32(m_elevationMap[base + m_width + 1]) * m_verticalScale,
(zIndex0 + 1) * m_horizontalScale, dgFloat32(0.0f));
points[1 * 2 + 0] = dgVector((xIndex0 + 0) * m_horizontalScale,
dgFloat32(m_elevationMap[base + m_width + 0]) * m_verticalScale,
(zIndex0 + 1) * m_horizontalScale, dgFloat32(0.0f));
t = dgFloat32(1.2f);
if (!m_diagonalMode)
{
triangle[0] = 1;
triangle[1] = 2;
triangle[2] = 3;
dgVector e10(points[2] - points[1]);
dgVector e20(points[3] - points[1]);
dgVector normal(e10 * e20);
t = ray.PolygonIntersect(normal, &points[0].m_x, sizeof(dgVector), triangle,
3);
if (t < dgFloat32(1.0f))
{
normalOut = normal;
return t;
}
triangle[0] = 1;
triangle[1] = 0;
triangle[2] = 2;
dgVector e30(points[0] - points[1]);
normal = e30 * e10;
t = ray.PolygonIntersect(normal, &points[0].m_x, sizeof(dgVector), triangle,
3);
if (t < dgFloat32(1.0f))
{
normalOut = normal;
return t;
}
}
else
{
triangle[0] = 0;
triangle[1] = 2;
triangle[2] = 3;
dgVector e10(points[2] - points[0]);
dgVector e20(points[3] - points[0]);
dgVector normal(e10 * e20);
t = ray.PolygonIntersect(normal, &points[0].m_x, sizeof(dgVector), triangle,
3);
if (t < dgFloat32(1.0f))
{
normalOut = normal;
return t;
}
triangle[0] = 0;
triangle[1] = 3;
triangle[2] = 1;
dgVector e30(points[1] - points[0]);
normal = e20 * e30;
t = ray.PolygonIntersect(normal, &points[0].m_x, sizeof(dgVector), triangle,
3);
if (t < dgFloat32(1.0f))
{
normalOut = normal;
return t;
}
}
return t;
}
dgFloat32 dgCollisionHeightField::RayCastSimd(const dgVector& q0,
const dgVector& q1, dgContactPoint& contactOut,
OnRayPrecastAction preFilter, const dgBody* const body,
void* const userData) const
{
dgVector boxP0;
dgVector boxP1;
// set the debug line counter to zero
// debugRayCast = 0;
// calculate the ray bounding box
CalculateMinExtend2d(q0, q1, boxP0, boxP1);
dgVector dq(q1 - q0);
dgVector padding(
dq.Scale(
m_horizontalScale * dgFloat32(10.0f)
/ (dgSqrt (dq % dq) + dgFloat32(1.0e-6f))));
// make sure the line segment crosses the original segment box
dgVector p0(q0 - padding);
dgVector p1(q1 + padding);
// clip the line against the bounding box
if (dgRayBoxClip(p0, p1, boxP0, boxP1))
{
dgVector dp(p1 - p0);
dgVector normalOut(dgFloat32(0.0f), dgFloat32(0.0f), dgFloat32(0.0f),
dgFloat32(0.0f));
dgFloat32 scale = m_horizontalScale;
dgFloat32 invScale = m_horizontalScaleInv;
dgInt32 ix0 = dgFastInt(p0.m_x * invScale);
dgInt32 iz0 = dgFastInt(p0.m_z * invScale);
// implement a 3ddda line algorithm
dgInt32 xInc;
dgFloat32 tx;
dgFloat32 stepX;
if (dp.m_x > dgFloat32(0.0f))
{
xInc = 1;
dgFloat32 val = dgFloat32(1.0f) / dp.m_x;
stepX = scale * val;
tx = (scale * (ix0 + dgFloat32(1.0f)) - p0.m_x) * val;
}
else if (dp.m_x < dgFloat32(0.0f))
{
xInc = -1;
dgFloat32 val = -dgFloat32(1.0f) / dp.m_x;
stepX = scale * val;
tx = -(scale * ix0 - p0.m_x) * val;
}
else
{
xInc = 0;
stepX = dgFloat32(0.0f);
tx = dgFloat32(1.0e10f);
}
dgInt32 zInc;
dgFloat32 stepZ;
dgFloat32 tz;
if (dp.m_z > dgFloat32(0.0f))
{
zInc = 1;
dgFloat32 val = dgFloat32(1.0f) / dp.m_z;
stepZ = scale * val;
tz = (scale * (iz0 + dgFloat32(1.0f)) - p0.m_z) * val;
}
else if (dp.m_z < dgFloat32(0.0f))
{
zInc = -1;
dgFloat32 val = -dgFloat32(1.0f) / dp.m_z;
stepZ = scale * val;
tz = -(scale * iz0 - p0.m_z) * val;
}
else
{
zInc = 0;
stepZ = dgFloat32(0.0f);
tz = dgFloat32(1.0e10f);
}
dgFloat32 txAcc = tx;
dgFloat32 tzAcc = tz;
dgInt32 xIndex0 = ix0;
dgInt32 zIndex0 = iz0;
FastRayTest ray(q0, q1);
// for each cell touched by the line
do
{
dgFloat32 t = RayCastCellSimd(ray, xIndex0, zIndex0, normalOut);
if (t < dgFloat32(1.0f))
{
// bail out at the first intersection and copy the data into the descriptor
contactOut.m_normal = normalOut.Scale(
dgFloat32(1.0f) / dgSqrt (normalOut % normalOut));
contactOut.m_userId = m_atributeMap[zIndex0 * m_width + xIndex0];
if (m_userRayCastCallback)
{
dgVector normal(
body->GetCollisionMatrix().RotateVector(contactOut.m_normal));
m_userRayCastCallback(body, this, t, xIndex0, zIndex0, &normal,
dgInt32(contactOut.m_userId), userData);
}
return t;
}
if (txAcc < tzAcc)
{
xIndex0 += xInc;
tx = txAcc;
txAcc += stepX;
}
else
{
zIndex0 += zInc;
tz = txAcc;
tzAcc += stepZ;
}
} while ((tx <= dgFloat32(1.0f)) || (tz <= dgFloat32(1.0f)));
}
// if no cell was hit, return a large value
return dgFloat32(1.2f);
}
dgFloat32 dgCollisionHeightField::RayCast(const dgVector& q0,
const dgVector& q1, dgContactPoint& contactOut,
OnRayPrecastAction preFilter, const dgBody* const body,
void* const userData) const
{
dgVector boxP0;
dgVector boxP1;
// set the debug line counter to zero
// debugRayCast = 0;
// calculate the ray bounding box
CalculateMinExtend2d(q0, q1, boxP0, boxP1);
// dgVector dq (q1 - q0);
// dgVector padding (dq.Scale (m_horizontalScale * dgFloat32 (10.0f) / (dgSqrt (dq % dq) + dgFloat32 (1.0e-6f))));
// make sure the line segment crosses the original segment box
// dgVector p0 (q0 - padding);
// dgVector p1 (q1 + padding);
dgVector p0(q0);
dgVector p1(q1);
// clip the line against the bounding box
if (dgRayBoxClip(p0, p1, boxP0, boxP1))
{
dgVector dp(p1 - p0);
dgVector normalOut(dgFloat32(0.0f), dgFloat32(0.0f), dgFloat32(0.0f),
dgFloat32(0.0f));
dgFloat32 scale = m_horizontalScale;
dgFloat32 invScale = m_horizontalScaleInv;
dgInt32 ix0 = dgFastInt(p0.m_x * invScale);
dgInt32 iz0 = dgFastInt(p0.m_z * invScale);
// implement a 3ddda line algorithm
dgInt32 xInc;
dgFloat32 tx;
dgFloat32 stepX;
if (dp.m_x > dgFloat32(0.0f))
{
xInc = 1;
dgFloat32 val = dgFloat32(1.0f) / dp.m_x;
stepX = scale * val;
tx = (scale * (ix0 + dgFloat32(1.0f)) - p0.m_x) * val;
}
else if (dp.m_x < dgFloat32(0.0f))
{
xInc = -1;
dgFloat32 val = -dgFloat32(1.0f) / dp.m_x;
stepX = scale * val;
tx = -(scale * ix0 - p0.m_x) * val;
}
else
{
xInc = 0;
stepX = dgFloat32(0.0f);
tx = dgFloat32(1.0e10f);
}
dgInt32 zInc;
dgFloat32 stepZ;
dgFloat32 tz;
if (dp.m_z > dgFloat32(0.0f))
{
zInc = 1;
dgFloat32 val = dgFloat32(1.0f) / dp.m_z;
stepZ = scale * val;
tz = (scale * (iz0 + dgFloat32(1.0f)) - p0.m_z) * val;
}
else if (dp.m_z < dgFloat32(0.0f))
{
zInc = -1;
dgFloat32 val = -dgFloat32(1.0f) / dp.m_z;
stepZ = scale * val;
tz = -(scale * iz0 - p0.m_z) * val;
}
else
{
zInc = 0;
stepZ = dgFloat32(0.0f);
tz = dgFloat32(1.0e10f);
}
dgFloat32 txAcc = tx;
dgFloat32 tzAcc = tz;
dgInt32 xIndex0 = ix0;
dgInt32 zIndex0 = iz0;
FastRayTest ray(q0, q1);
// for each cell touched by the line
do
{
dgFloat32 t = RayCastCell(ray, xIndex0, zIndex0, normalOut);
if (t < dgFloat32(1.0f))
{
// bail out at the first intersection and copy the data into the descriptor
contactOut.m_normal = normalOut.Scale(
dgFloat32(1.0f) / dgSqrt (normalOut % normalOut));
contactOut.m_userId = m_atributeMap[zIndex0 * m_width + xIndex0];
if (m_userRayCastCallback)
{
dgVector normal(
body->GetCollisionMatrix().RotateVector(contactOut.m_normal));
m_userRayCastCallback(body, this, t, xIndex0, zIndex0, &normal,
dgInt32(contactOut.m_userId), userData);
}
return t;
}
if (txAcc < tzAcc)
{
xIndex0 += xInc;
tx = txAcc;
txAcc += stepX;
}
else
{
zIndex0 += zInc;
tz = txAcc;
tzAcc += stepZ;
}
} while ((tx <= dgFloat32(1.0f)) || (tz <= dgFloat32(1.0f)));
}
// if no cell was hit, return a large value
return dgFloat32(1.2f);
}
void dgCollisionHeightField::GetVertexListIndexList(const dgVector& p0,
const dgVector& p1, dgGetVertexListIndexList &data) const
{
_ASSERTE(0);
data.m_vertexCount = 0;
}
struct dgCollisionHeightFieldShowPolyContext
{
dgMatrix m_matrix;
void* m_userData;
OnDebugCollisionMeshCallback m_callback;
};
void dgCollisionHeightField::DebugCollision(const dgMatrix& matrix,
OnDebugCollisionMeshCallback callback, void* const userData) const
{
dgInt32 base;
dgVector points[4];
base = 0;
for (dgInt32 z = 0; z < m_height - 1; z++)
{
points[0 * 2 + 0] = matrix.TransformVector(
dgVector((0 + 0) * m_horizontalScale,
dgFloat32(m_elevationMap[base + 0]) * m_verticalScale,
(z + 0) * m_horizontalScale, dgFloat32(0.0f)));
points[1 * 2 + 0] = matrix.TransformVector(
dgVector((0 + 0) * m_horizontalScale,
dgFloat32(m_elevationMap[base + 0 + m_width + 0]) * m_verticalScale,
(z + 1) * m_horizontalScale, dgFloat32(0.0f)));
for (dgInt32 x = 0; x < m_width - 1; x++)
{
dgTriplex triangle[3];
points[0 * 2 + 1] = matrix.TransformVector(
dgVector((x + 1) * m_horizontalScale,
dgFloat32(m_elevationMap[base + x + 1]) * m_verticalScale,
(z + 0) * m_horizontalScale, dgFloat32(0.0f)));
points[1 * 2 + 1] = matrix.TransformVector(
dgVector(
(x + 1) * m_horizontalScale,
dgFloat32(m_elevationMap[base + x + m_width + 1])
* m_verticalScale, (z + 1) * m_horizontalScale,
dgFloat32(0.0f)));
if (m_diagonalMode)
{
triangle[0].m_x = points[0].m_x;
triangle[0].m_y = points[0].m_y;
triangle[0].m_z = points[0].m_z;
triangle[1].m_x = points[2].m_x;
triangle[1].m_y = points[2].m_y;
triangle[1].m_z = points[2].m_z;
triangle[2].m_x = points[1].m_x;
triangle[2].m_y = points[1].m_y;
triangle[2].m_z = points[1].m_z;
callback(userData, 3, &triangle[0].m_x, m_atributeMap[base]);
triangle[0].m_x = points[1].m_x;
triangle[0].m_y = points[1].m_y;
triangle[0].m_z = points[1].m_z;
triangle[1].m_x = points[2].m_x;
triangle[1].m_y = points[2].m_y;
triangle[1].m_z = points[2].m_z;
triangle[2].m_x = points[3].m_x;
triangle[2].m_y = points[3].m_y;
triangle[2].m_z = points[3].m_z;
callback(userData, 3, &triangle[0].m_x, m_atributeMap[base]);
}
else
{
triangle[0].m_x = points[0].m_x;
triangle[0].m_y = points[0].m_y;
triangle[0].m_z = points[0].m_z;
triangle[1].m_x = points[2].m_x;
triangle[1].m_y = points[2].m_y;
triangle[1].m_z = points[2].m_z;
triangle[2].m_x = points[3].m_x;
triangle[2].m_y = points[3].m_y;
triangle[2].m_z = points[3].m_z;
callback(userData, 3, &triangle[0].m_x, m_atributeMap[base]);
triangle[0].m_x = points[0].m_x;
triangle[0].m_y = points[0].m_y;
triangle[0].m_z = points[0].m_z;
triangle[1].m_x = points[3].m_x;
triangle[1].m_y = points[3].m_y;
triangle[1].m_z = points[3].m_z;
triangle[2].m_x = points[1].m_x;
triangle[2].m_y = points[1].m_y;
triangle[2].m_z = points[1].m_z;
callback(userData, 3, &triangle[0].m_x, m_atributeMap[base]);
}
points[0 * 2 + 0] = points[0 * 2 + 1];
points[1 * 2 + 0] = points[1 * 2 + 1];
}
base += m_width;
}
}
void dgCollisionHeightField::GetLocalAABB(const dgVector& p0,
const dgVector& p1, dgVector& boxP0, dgVector& boxP1) const
{
dgInt32 x0;
dgInt32 x1;
dgInt32 z0;
dgInt32 z1;
dgInt32 base;
dgInt32 minHeight;
dgInt32 maxHeight;
// the user data is the pointer to the collision geometry
CalculateMinExtend3d(p0, p1, boxP0, boxP1);
x0 = dgFastInt(boxP0.m_x * m_horizontalScaleInv);
x1 = dgFastInt(boxP1.m_x * m_horizontalScaleInv);
z0 = dgFastInt(boxP0.m_z * m_horizontalScaleInv);
z1 = dgFastInt(boxP1.m_z * m_horizontalScaleInv);
minHeight = 0x7fffffff;
maxHeight = -0x7fffffff;
base = z0 * m_width;
for (dgInt32 z = z0; z <= z1; z++)
{
for (dgInt32 x = x0; x <= x1; x++)
{
dgInt32 high;
high = m_elevationMap[base + x];
if (high < minHeight)
{
minHeight = high;
}
if (high > maxHeight)
{
maxHeight = high;
}
}
base += m_width;
}
boxP0.m_y = m_verticalScale * minHeight;
boxP1.m_y = m_verticalScale * maxHeight;
}
void dgCollisionHeightField::GetCollidingFacesSimd(
dgPolygonMeshDesc* const data) const
{
GetCollidingFaces(data);
}
void dgCollisionHeightField::GetCollidingFaces(
dgPolygonMeshDesc* const data) const
{
dgInt32 x0;
dgInt32 x1;
dgInt32 z0;
dgInt32 z1;
dgInt32 base;
dgInt32 vertexIndex;
dgVector boxP0;
dgVector boxP1;
dgWorld* world;
// the user data is the pointer to the collision geometry
CalculateMinExtend3d(data->m_boxP0, data->m_boxP1, boxP0, boxP1);
world = data->m_objBody->GetWorld();
x0 = dgFastInt(boxP0.m_x * m_horizontalScaleInv);
x1 = dgFastInt(boxP1.m_x * m_horizontalScaleInv);
z0 = dgFastInt(boxP0.m_z * m_horizontalScaleInv);
z1 = dgFastInt(boxP1.m_z * m_horizontalScaleInv);
dgInt32 minHeight;
dgInt32 maxHeight;
minHeight = 0x7fffffff;
maxHeight = -0x7fffffff;
base = z0 * m_width;
for (dgInt32 z = z0; z <= z1; z++)
{
for (dgInt32 x = x0; x <= x1; x++)
{
dgInt32 high;
high = m_elevationMap[base + x];
if (high < minHeight)
{
minHeight = high;
}
if (high > maxHeight)
{
maxHeight = high;
}
}
base += m_width;
}
if (!(((m_verticalScale * maxHeight) < boxP0.m_y)
|| ((m_verticalScale * minHeight) > boxP1.m_y)))
{
dgInt32 step;
dgInt32 index;
dgInt32 faceCount;
dgInt32 normalBase;
dgInt32 normalIndex;
// scan the vertices's intersected by the box extend
base = (z1 - z0 + 1) * (x1 - x0 + 1) + 2 * (z1 - z0) * (x1 - x0);
while (base > m_instanceData->m_vertexCount[data->m_threadNumber])
{
AllocateVertex(world, data->m_threadNumber);
}
vertexIndex = 0;
base = z0 * m_width;
dgVector* const vertex = m_instanceData->m_vertex[data->m_threadNumber];
for (dgInt32 z = z0; z <= z1; z++)
{
for (dgInt32 x = x0; x <= x1; x++)
{
vertex[vertexIndex] = dgVector(m_horizontalScale * x,
m_verticalScale * dgFloat32(m_elevationMap[base + x]),
m_horizontalScale * z, dgFloat32(0.0f));
vertexIndex++;
_ASSERTE(
vertexIndex <= m_instanceData->m_vertexCount[data->m_threadNumber]);
}
base += m_width;
}
normalBase = vertexIndex;
index = 0;
faceCount = 0;
vertexIndex = 0;
normalIndex = 0;
step = x1 - x0 + 1;
dgInt32* const indices = data->m_globalFaceVertexIndex;
dgInt32* const attributes = data->m_globalUserAttribute;
dgInt32* const faceIndexCount = data->m_globalFaceIndexCount;
dgInt32* const normalIndexCount = data->m_globalFaceNormalIndex;
dgInt32* const faceAdjencentEdgeNormal = data->m_globalAdjencentEdgeNormal;
dgFloat32* const facefaceMaxSize = data->m_globalFaceMaxSize;
dgFloat32 faceSize = GetMax(m_horizontalScale * dgFloat32(2.0f),
dgFloat32(64.0f));
if (!m_diagonalMode)
{
for (dgInt32 z = z0; z < z1; z++)
{
dgInt32 zStep;
zStep = z * m_width;
for (dgInt32 x = x0; x < x1; x++)
{
dgInt32 i0;
dgInt32 i1;
dgInt32 i2;
dgInt32 i3;
i0 = vertexIndex;
i1 = vertexIndex + step;
i2 = vertexIndex + 1;
i3 = vertexIndex + step + 1;
faceIndexCount[faceCount] = 3;
facefaceMaxSize[faceCount] = faceSize;
attributes[faceCount] = m_atributeMap[zStep + x];
indices[index + 0] = i0;
indices[index + 1] = i1;
indices[index + 2] = i2;
index += 3;
faceCount++;
faceIndexCount[faceCount] = 3;
attributes[faceCount] = m_atributeMap[zStep + x];
facefaceMaxSize[faceCount] = faceSize;
indices[index + 0] = i2;
indices[index + 1] = i1;
indices[index + 2] = i3;
index += 3;
faceCount++;
vertexIndex++;
// calculate the the normal
dgVector e0(vertex[i0] - vertex[i2]);
dgVector e1(vertex[i1] - vertex[i2]);
dgVector e2(vertex[i3] - vertex[i2]);
dgVector n0(e0 * e1);
dgVector n1(e1 * e2);
//normalBase
vertex[normalBase] = n0.Scale(dgRsqrt(n0 % n0));
normalIndexCount[normalIndex] = normalBase;
normalIndex++;
normalBase++;
vertex[normalBase] = n1.Scale(dgRsqrt(n1 % n1));
normalIndexCount[normalIndex] = normalBase;
normalIndex++;
normalBase++;
}
vertexIndex++;
}
base = 0;
index = 0;
step = x1 - x0;
for (dgInt32 z = z0; z < z1; z++)
{
dgInt32 z0Flag;
dgInt32 z1Flag;
z0Flag = ((z - z0 - 1) >> 31);
z1Flag = ((z1 - z - 2) >> 31);
for (dgInt32 x = x0; x < x1; x++)
{
dgInt32 xA0;
dgInt32 xA1;
dgInt32 zA0;
dgInt32 zA1;
dgInt32 zxA;
dgInt32 x0Flag;
dgInt32 x1Flag;
dgFloat32 side;
dgFloat32 diagSide;
x0Flag = ((x - x0 - 1) >> 31);
x1Flag = ((x1 - x - 2) >> 31);
const dgVector& point = vertex[indices[base + 1]];
const dgVector& n = vertex[normalIndexCount[index * 2]];
xA0 = ((~x0Flag) & (index * 2 - 1))
| (x0Flag & ((index - x + x0) * 2));
side = n % (vertex[indices[xA0 * 3 + 1]] - point);
faceAdjencentEdgeNormal[base + 0] =
(side < dgFloat32(-1.0e-5f)) ? normalIndexCount[xA0] : -1;
zxA = index * 2 + 1;
diagSide = n % (vertex[indices[xA0 * 3 + 2]] - point);
faceAdjencentEdgeNormal[base + 1] =
(diagSide < dgFloat32(-1.0e-5f)) ? normalIndexCount[zxA] : -1;
zA0 = ((~z0Flag) & ((index - step) * 2 + 1)) | (z0Flag & (index * 2));
side = n % (vertex[indices[zA0 * 3]] - point);
faceAdjencentEdgeNormal[base + 2] =
(side < dgFloat32(-1.0e-5f)) ? normalIndexCount[zA0] : -1;
const dgVector& n1 = vertex[normalIndexCount[index * 2 + 1]];
xA1 = ((~x1Flag) & (index * 2 + 2)) | (x1Flag & (index * 2 + 1));
side = n1 % (vertex[indices[xA1 * 3 + 2]] - point);
faceAdjencentEdgeNormal[base + 5] =
(side < dgFloat32(-1.0e-5f)) ? normalIndexCount[xA1] : -1;
zxA = index * 2;
faceAdjencentEdgeNormal[base + 3] =
(diagSide < dgFloat32(-1.0e-5f)) ? normalIndexCount[zxA] : -1;
;
zA1 = ((~z1Flag) & ((index + step) * 2)) | (z1Flag & (index * 2 + 1));
side = n % (vertex[indices[zA1 * 3 + 1]] - point);
faceAdjencentEdgeNormal[base + 4] =
(side < dgFloat32(-1.0e-5f)) ? normalIndexCount[zA1] : -1;
index++;
base += 6;
}
}
}
else
{
for (dgInt32 z = z0; z < z1; z++)
{
dgInt32 zStep;
zStep = z * m_width;
for (dgInt32 x = x0; x < x1; x++)
{
dgInt32 i0;
dgInt32 i1;
dgInt32 i2;
dgInt32 i3;
i0 = vertexIndex;
i1 = vertexIndex + step + 1;
i2 = vertexIndex + 1;
i3 = vertexIndex + step;
faceIndexCount[faceCount] = 3;
facefaceMaxSize[faceCount] = faceSize;
attributes[faceCount] = m_atributeMap[zStep + x];
indices[index + 0] = i0;
indices[index + 1] = i1;
indices[index + 2] = i2;
index += 3;
faceCount++;
faceIndexCount[faceCount] = 3;
facefaceMaxSize[faceCount] = faceSize;
attributes[faceCount] = m_atributeMap[zStep + x];
indices[index + 0] = i0;
indices[index + 1] = i3;
indices[index + 2] = i1;
index += 3;
faceCount++;
vertexIndex++;
// calculate the the normal
dgVector e0(vertex[i3] - vertex[i0]);
dgVector e1(vertex[i1] - vertex[i0]);
dgVector e2(vertex[i2] - vertex[i0]);
dgVector n0(e0 * e1);
dgVector n1(e1 * e2);
vertex[normalBase] = n0.Scale(dgRsqrt(n0 % n0));
normalIndexCount[normalIndex] = normalBase;
normalIndex++;
normalBase++;
vertex[normalBase] = n1.Scale(dgRsqrt(n1 % n1));
normalIndexCount[normalIndex] = normalBase;
normalIndex++;
normalBase++;
}
vertexIndex++;
}
base = 0;
index = 0;
step = x1 - x0;
for (dgInt32 z = z0; z < z1; z++)
{
dgInt32 z0Flag;
dgInt32 z1Flag;
z0Flag = ((z - z0 - 1) >> 31);
z1Flag = ((z1 - z - 2) >> 31);
for (dgInt32 x = x0; x < x1; x++)
{
dgInt32 xA0;
dgInt32 xA1;
dgInt32 zA0;
dgInt32 zA1;
dgInt32 zxA;
dgInt32 x0Flag;
dgInt32 x1Flag;
dgFloat32 side;
dgFloat32 diagSide;
x1Flag = ((x - x0 - 1) >> 31);
x0Flag = ((x1 - x - 2) >> 31);
const dgVector& point = vertex[indices[base]];
const dgVector& n = vertex[normalIndexCount[index * 2]];
xA0 = ((~x0Flag) & (index * 2 + 3)) | (x0Flag & (index * 2));
side = n % (vertex[indices[xA0 * 3 + 2]] - point);
faceAdjencentEdgeNormal[base + 1] =
(side < dgFloat32(-1.0e-5f)) ? normalIndexCount[xA0] : -1;
zxA = index * 2 + 1;
diagSide = n % (vertex[indices[xA0 * 3 + 1]] - point);
faceAdjencentEdgeNormal[base + 0] =
(diagSide < dgFloat32(-1.0e-5f)) ? normalIndexCount[zxA] : -1;
zA0 = ((~z0Flag) & ((index - step) * 2 + 1)) | (z0Flag & (index * 2));
side = n % (vertex[indices[zA0 * 3]] - point);
faceAdjencentEdgeNormal[base + 2] =
(side < dgFloat32(-1.0e-5f)) ? normalIndexCount[zA0] : -1;
const dgVector& n1 = vertex[normalIndexCount[index * 2 + 1]];
xA1 = ((~x1Flag) & (index * 2 - 2))
| (x1Flag & ((index - x + x0) * 2 + 1));
side = n1 % (vertex[indices[xA1 * 3]] - point);
faceAdjencentEdgeNormal[base + 3] =
(side < dgFloat32(-1.0e-5f)) ? normalIndexCount[xA1] : -1;
zxA = index * 2;
faceAdjencentEdgeNormal[base + 5] =
(diagSide < dgFloat32(-1.0e-5f)) ? normalIndexCount[zxA] : -1;
;
zA1 = ((~z1Flag) & ((index + step) * 2)) | (z1Flag & (index * 2 + 1));
side = n % (vertex[indices[zA1 * 3 + 1]] - point);
faceAdjencentEdgeNormal[base + 4] =
(side < dgFloat32(-1.0e-5f)) ? normalIndexCount[zA1] : -1;
index++;
base += 6;
}
}
}
data->m_faceCount = faceCount;
// initialize the callback data structure
data->m_vertexStrideInBytes = sizeof(dgVector);
data->m_faceVertexIndex = indices;
data->m_faceNormalIndex = normalIndexCount;
data->m_faceMaxSize = facefaceMaxSize;
data->m_faceAdjencentEdgeNormal = faceAdjencentEdgeNormal;
data->m_userAttribute = attributes;
data->m_faceIndexCount = faceIndexCount;
data->m_vertex = &vertex[0].m_x;
if (GetDebugCollisionCallback())
{
dgTriplex triplex[3];
const dgMatrix& matrix = data->m_polySoupBody->GetCollisionMatrix();
for (dgInt32 i = 0; i < faceCount; i++)
{
for (dgInt32 j = 0; j < 3; j++)
{
dgVector p(matrix.TransformVector(vertex[indices[i * 3 + j]]));
triplex[j].m_x = p.m_x;
triplex[j].m_y = p.m_y;
triplex[j].m_z = p.m_z;
}
GetDebugCollisionCallback()(data->m_polySoupBody, data->m_objBody,
attributes[i], 3, &triplex[0].m_x, sizeof(dgTriplex));
}
}
}
}
| [
"[email protected]@b7a2f1d6-d59d-a8fe-1e9e-8d4888b32692"
]
| [
[
[
1,
1273
]
]
]
|
74a33f760dacd9c594f6776e2f3d6fc693022d44 | 0e25e68e96c9883edcc85cbee6d24fdfd49cf8e5 | /source/GameField.cpp | c853ccacb996b3e70defead3966abc1c66d62b93 | []
| no_license | dpembo/tetwiis | ff334a52ce2b41e79790c37fbe6630d26b1eb2b7 | 207692026d767b1a3aa9909ba9c6297cfd78fae0 | refs/heads/master | 2021-08-17T10:36:38.264831 | 2011-08-03T11:25:21 | 2011-08-03T11:25:21 | 32,199,080 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,375 | cpp | /**
*
* Tetwiis
* (C)2009 http://www.pembo.co.uk
*
**/
//------------------------------------------------------------------------------
// Headers
//------------------------------------------------------------------------------
# include "GameField.h"
# include "Debug.h"
# include "Offset.h"
#include <grrlib.h>
//------------------------------------------------------------------------------
// Externals
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Globals
//------------------------------------------------------------------------------
Square* GameField::arrGameField[width+1][height+1];
//int GameField::arrBitGameField[20] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
//_______________________________________________________________________________
/**
* Constructor
*/
GameField::GameField()
{
}
//_______________________________________________________________________________
/**
* destructor
*/
GameField::~GameField()
{
}
void GameField::reset()
{
int x,y;
for(y=height;y>=0;y--)
{
for(x=width; x>=0; x--)
{
arrGameField[x][y]=0;
}
}
}
bool GameField::isEmpty(int x,int y)
{
/*char* debugMessage = strdup(" ");
sprintf(debugMessage, "CALLED ISEMPTY X[%i] Y[%i] W[%i] H[%i]", x,y,width,height);
Debug::log((const char*)debugMessage);*/
if(x<0)return false;
else if(x>width)return false;
else if(y > height)return false;
//else if(y>=0 && (arrBitGameField[y]&(1<<x))!=0)return false;
else if(y>=0 && arrGameField[x][y]!=NULL)return false;
return true;
}
void GameField::stopSquare(Square* square)
{
int x,y;
x = square->getLocation().getX()/getSquareSize();
y = square->getLocation().getY()/getSquareSize();
//char* debugMessage = strdup(" ");
//sprintf(debugMessage, "STOPSQ X[%i] Y[%i]", x,y );
//Debug::log((const char*)debugMessage);
if(x<0)return;
if(x>width)return;
if(y<0)return;
if(y>height) return;
//arrBitGameField[y] = arrBitGameField[y] | (1<<x);
arrGameField[x][y] = square;
}
int GameField::firstPopulatedLine()
{
for(int y=0;y<height;y++)
{
if(!lineEmpty(y))return y;
}
return -1;
}
bool GameField::lineFull(int y)
{
int x;
for(x=0;x<=width;x++)
{
if(arrGameField[x][y]==NULL)return false;
}
return true;
}
bool GameField::lineEmpty(int y)
{
int x;
for(x=0;x<=width;x++)
{
if(arrGameField[x][y]!=NULL)return false;
}
return true;
}
int GameField::checkLines()
{
//char* debugMessage = strdup(" ");
int checkLinesResult=0; //Number of lines completed
int y = height ;
while(y>=0)
{
//sprintf(debugMessage, "checkLines Y[%i]",y);
//Debug::log((const char*)debugMessage);
//Stop when a blank line is reached
if(lineEmpty(y)==true)
{
//Debug::log(strdup("Stopping - found blank line"));
y=0;
}
//if all bits of line are set then increment the counter
//to clear the line and move all above lines down.
if(lineFull(y)==true)
{
//Debug::log(strdup("Found full line"));
checkLinesResult++;
//Move all lines down
int index;
for(index = y;index>=0;index--)
{
//sprintf(debugMessage, "Moving down [%i] to [%i]",index,index-1);
//Debug::log((const char*)debugMessage);
//If current line is not first of gamefield
///copy the line above
if(index>0)
{
//Debug::log(strdup("copying bits"));
//Copy bits from line above
//arrBitGameField[index] = (arrBitGameField[index-1]+0);
//Copy each of the squares
int x;
for(x=0;x<=width;x++)
{
//sprintf(debugMessage, "Copying square x[%i]",x);
//Debug::log((const char*)debugMessage);
//Copy square
arrGameField[x][index] = arrGameField[x][index-1];
//Update location of square
//Debug::log(strdup("Updating location"));
if(arrGameField[x][index]!=NULL)
{
//arrGameField[x][index]->getLocationInst()->setX(arrGameField[x][index]->getLocationInst()->getX());
arrGameField[x][index]->getLocationInst()->setY(arrGameField[x][index]->getLocationInst()->getY()+squareSize);
}
}
}
else
{
//If current line is first line of gamefield
//just clear the line!
//Debug::log(strdup("current line is first line!"));
//arrBitGameField[index]=bitEmpty;
int x;
for(x=0;x<=width;x++)
{
arrGameField[x][index] = NULL;
}
}
}
}
else
{
y--;
}
}
return checkLinesResult;
}
void GameField::redraw()
{
int x,y;
//char* debugMessage = strdup(" ");
//sprintf(debugMessage, "REDRAW W[%i] H[%i]",width,height);
//Debug::log((const char*)debugMessage);
for(y=height;y>=0;y--)
{
//sprintf(debugMessage, "On Y[%i]",y);
//Debug::log((const char*)debugMessage);
/*if(lineEmpty(y)!=true)
{*/
//Debug::log(strdup("not empty!"));
for(x=width; x>=0; x--)
{
if(drawGrid)
{
drawRectangle( (x*getSquareSize())+Offset::getOffsetX(),(y*getSquareSize())+Offset::getOffsetY(),getSquareSize(),getSquareSize(),0x444444FF,0);
}
//sprintf(debugMessage, "y[%i] Not Empty X[%i] sq exists[%i]" ,y,x,arrGameField[x][y]!=NULL);
//Debug::log((const char*)debugMessage);
if(arrGameField[x][y]!= NULL )arrGameField[x][y]->show();
}
/*}
else
{
// Debug::log(strdup("empty!"));
for(x=width; x>=0; x--)
{
drawRectangle(x*squareSize+Offset::getOffsetX(),y*squareSize+Offset::getOffsetY(),10,10,0x999999FF,0);
}
}*/
}
}
//_______________________________________________________________________________
/*
* Draws a rectangle
*/
void GameField::drawRectangle(int x,int y,int width,int height, u32 color, bool fill)
{
int fillint=0;
if(fill)fillint=1;
GRRLIB_Rectangle(x,y,width,height,color,fillint);
}
| [
"[email protected]@d3020fdf-8559-019b-6164-6b32d0407fe0"
]
| [
[
[
1,
270
]
]
]
|
4feb856368de57d302662aea7de08c758266a0b1 | be2e23022d2eadb59a3ac3932180a1d9c9dee9c2 | /GameServer/MapGroupKernel/FriendData.h | d32506df73ea5e516ab30b7027f5673d060b6409 | []
| no_license | cronoszeu/revresyksgpr | 78fa60d375718ef789042c452cca1c77c8fa098e | 5a8f637e78f7d9e3e52acdd7abee63404de27e78 | refs/heads/master | 2020-04-16T17:33:10.793895 | 2010-06-16T12:52:45 | 2010-06-16T12:52:45 | 35,539,807 | 0 | 2 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,015 | h |
#pragma once
#include "GameObj.h"
#include "I_mydb.h"
struct FriendInfoStruct
{
OBJID id;
OBJID idUser;
OBJID idFriend;
NAMESTR szFriendName;
};
class CFriendData : public CGameObj
{
protected:
CFriendData();
virtual ~CFriendData();
public:
bool Create (IRecordset* pRes);
bool Create (OBJID id, IDatabase* pDb);
FriendInfoStruct* GetInfo (void) {return &m_Info;}
bool LoadInfo (IRecord* pRes);
public: // get
OBJID GetID() { return m_Info.id; }
OBJID GetUserID() { return m_Info.idUser; }
OBJID GetFriendID() { return m_Info.idFriend; }
LPCTSTR GetFriendName() { return m_Info.szFriendName; }
public: // add del
OBJID CreateRecord(OBJID idUser, OBJID idFriend, LPCTSTR szFriendName, IDatabase* pDb);
bool DeleteRecord(IDatabase* pDb);
protected:
FriendInfoStruct m_Info;
public:// ±íÄ£°å
static bool Init(IDatabase* pDb);
static void Final();
protected:
// static IRecord* m_pDefaultRecord;
};
| [
"rpgsky.com@cc92e6ba-efcf-11de-bf31-4dec8810c1c1"
]
| [
[
[
1,
49
]
]
]
|
34101c528fc04be0cdbbcae2a4caa88b7d1b2776 | 854ee643a4e4d0b7a202fce237ee76b6930315ec | /arcemu_svn/src/sun/src/InstanceScripts/Instance_Scholomance.cpp | bcc69978d0ee29b593f12174da8f105db74911ea | []
| 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 | 37,279 | cpp | /*
* Moon++ Scripts for Ascent MMORPG Server
* Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2007-2008 Moon++ Team <http://www.moonplusplus.info/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "StdAfx.h"
#include "Setup.h"
/************************************************************************/
/* Instance_Scholomance.cpp Script */
/************************************************************************/
/*****************************/
/* */
/* Boss AIs */
/* */
/*****************************/
// Doctor Theolen KrastinovAI
#define CN_DOCTOR_THEOLEN_KRASTINOV 11261 //+
#define REND 18106
#define KRASTINOVCLEAVE 15584
#define FRENZY 28371
class DoctorTheolenKrastinovAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(DoctorTheolenKrastinovAI);
SP_AI_Spell spells[3];
bool m_spellcheck[3];
DoctorTheolenKrastinovAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
FRENZY_LIMITER = 0;
nrspells = 3;
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
spells[0].info = dbcSpell.LookupEntry(REND);
spells[0].targettype = TARGET_ATTACKING;
spells[0].instant = true;
spells[0].perctrigger = 20.0f;
spells[0].attackstoptimer = 1000;
spells[1].info = dbcSpell.LookupEntry(KRASTINOVCLEAVE);
spells[1].targettype = TARGET_ATTACKING;
spells[1].instant = true;
spells[1].perctrigger = 9.0f;
spells[1].attackstoptimer = 1000;
spells[2].info = dbcSpell.LookupEntry(FRENZY);
spells[2].targettype = TARGET_SELF;
spells[2].instant = true;
spells[2].perctrigger = 0.0f;
spells[2].attackstoptimer = 1000;
}
void OnCombatStart(Unit* mTarget)
{
FRENZY_LIMITER = 0;
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
}
void OnCombatStop(Unit *mTarget)
{
FRENZY_LIMITER = 0;
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
}
void OnDied(Unit * mKiller)
{
FRENZY_LIMITER = 0;
RemoveAIUpdateEvent();
}
void AIUpdate()
{
if(_unit->GetHealthPct() <= 50 && FRENZY_LIMITER == 0)
{
// FRENZY
_unit->CastSpell(_unit, spells[2].info, spells[2].instant);
FRENZY_LIMITER = 1;
}
else
{
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)
{
target = _unit->GetAIInterface()->GetNextTarget();
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant);
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:
uint32 FRENZY_LIMITER;
int nrspells;
};
// Instructor MaliciaAI
#define CN_INSTRUCTOR_MALICIA 10505 //+
#define CALL_OF_GRAVE 17831
#define CORRUPTION 11672
#define FLASH_HEAL 17138 //10917
#define RENEW 10929
#define HEAL 15586 // not sure
class InstructorMaliciaAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(InstructorMaliciaAI);
SP_AI_Spell spells[5];
bool m_spellcheck[5];
InstructorMaliciaAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
nrspells = 5;
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
spells[0].info = dbcSpell.LookupEntry(CALL_OF_GRAVE);
spells[0].targettype = TARGET_DESTINATION; // VARIOUS, DESINATION or ATTACKING?
spells[0].instant = true;
spells[0].perctrigger = 10.0f;
spells[0].attackstoptimer = 1000;
spells[1].info = dbcSpell.LookupEntry(CORRUPTION);
spells[1].targettype = TARGET_ATTACKING;
spells[1].instant = true; // should be false, but doesn't work then
spells[1].perctrigger = 9.0f;
spells[1].attackstoptimer = 1000;
spells[2].info = dbcSpell.LookupEntry(FLASH_HEAL);
spells[2].targettype = TARGET_SELF; // works for caster and his enemy :o
spells[2].instant = true; // should be false, but doesn't work then
spells[2].perctrigger = 5.0f;
spells[2].attackstoptimer = 1000;
spells[3].info = dbcSpell.LookupEntry(RENEW);
spells[3].targettype = TARGET_SELF; // w00t, heals player too ? :|
spells[3].instant = true;
spells[3].perctrigger = 4.0f; // why 0?:|
spells[3].attackstoptimer = 1000;
spells[4].info = dbcSpell.LookupEntry(HEAL);
spells[4].targettype = TARGET_SELF;
spells[4].instant = true; // should be false, but doesn't work then
spells[4].perctrigger = 5.0f;
spells[4].attackstoptimer = 1000;
}
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 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)
{
target = _unit->GetAIInterface()->GetNextTarget();
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant);
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;
};
// The RavenianAI
#define CN_THE_RAVENIAN 10507 //+
#define TRAMPLE 15550
#define RAVENIANCLEAVE 20691
#define SUNDERINCLEAVE 25174
#define KNOCKAWAY 10101
class TheRavenianAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(TheRavenianAI);
SP_AI_Spell spells[4];
bool m_spellcheck[4];
TheRavenianAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
nrspells = 4;
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
spells[0].info = dbcSpell.LookupEntry(TRAMPLE);
spells[0].targettype = TARGET_ATTACKING;
spells[0].instant = true;
spells[0].perctrigger = 8.0f;
spells[0].attackstoptimer = 1000;
spells[1].info = dbcSpell.LookupEntry(RAVENIANCLEAVE);
spells[1].targettype = TARGET_ATTACKING;
spells[1].instant = true;
spells[1].perctrigger = 9.0f;
spells[1].attackstoptimer = 1000;
spells[2].info = dbcSpell.LookupEntry(SUNDERINCLEAVE);
spells[2].targettype = TARGET_ATTACKING;
spells[2].instant = true;
spells[2].perctrigger = 20.0f;
spells[2].attackstoptimer = 1000;
spells[3].info = dbcSpell.LookupEntry(KNOCKAWAY);
spells[3].targettype = TARGET_ATTACKING;
spells[3].instant = true;
spells[3].perctrigger = 11.0f;
spells[3].attackstoptimer = 1000;
}
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 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)
{
target = _unit->GetAIInterface()->GetNextTarget();
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant);
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;
};
// Lady Illucia BarovAI
#define CN_LADY_ILLUCIA_BAROV 10502 //+
#define CURSE_OF_AGONY 18671 //+
#define SHADOW_SHOCK 20603 //+
#define SILENCE 15487 //+
#define ILLUCIA_FEAR 26580 //26661 //+
#define DOMINATE_MIND 20740 //+
class LadyIlluciaBarovAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(LadyIlluciaBarovAI);
SP_AI_Spell spells[5];
bool m_spellcheck[5];
LadyIlluciaBarovAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
nrspells = 5;
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
spells[0].info = dbcSpell.LookupEntry(CURSE_OF_AGONY);
spells[0].targettype = TARGET_VARIOUS;
spells[0].instant = true;
spells[0].perctrigger = 8.0f;
spells[0].attackstoptimer = 1000;
spells[1].info = dbcSpell.LookupEntry(SHADOW_SHOCK);
spells[1].targettype = TARGET_VARIOUS;
spells[1].instant = true;
spells[1].perctrigger = 12.0f;
spells[1].attackstoptimer = 1000;
spells[2].info = dbcSpell.LookupEntry(SILENCE);
spells[2].targettype = TARGET_ATTACKING;
spells[2].instant = true;
spells[2].perctrigger = 8.0f;
spells[2].attackstoptimer = 1000;
spells[3].info = dbcSpell.LookupEntry(ILLUCIA_FEAR);
spells[3].targettype = TARGET_ATTACKING;
spells[3].instant = true;
spells[3].perctrigger = 4.0f;
spells[3].attackstoptimer = 1000;
spells[4].info = dbcSpell.LookupEntry(DOMINATE_MIND);
spells[4].targettype = TARGET_ATTACKING;
spells[4].instant = true;
spells[4].perctrigger = 4.0f;
spells[4].attackstoptimer = 1000;
}
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 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)
{
target = _unit->GetAIInterface()->GetNextTarget();
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant);
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;
};
// Ras ForstwhisperAI
#define CN_RAS_FORSTWHISPER 10508 //+
#define FROSTBOLT 21369 //+
#define ICE_ARMOR 18100 //+
#define FREEZE 18763 //+
#define RAS_FEAR 26070 //+
#define CHILL_NOVA 18099 //+
#define FROSTBOLT_VOLLEY 22643 //8398
class RasForstwhisperAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(RasForstwhisperAI);
SP_AI_Spell spells[6];
bool m_spellcheck[6];
RasForstwhisperAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
nrspells = 6;
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
spells[0].info = dbcSpell.LookupEntry(FROSTBOLT);
spells[0].targettype = TARGET_ATTACKING;
spells[0].instant = false;
spells[0].perctrigger = 14.0f;
spells[0].attackstoptimer = 2000;
spells[1].info = dbcSpell.LookupEntry(ICE_ARMOR);
spells[1].targettype = TARGET_SELF;
spells[1].instant = true;
spells[1].perctrigger = 0.0f;
spells[1].attackstoptimer = 1000;
spells[2].info = dbcSpell.LookupEntry(FREEZE);
spells[2].targettype = TARGET_ATTACKING;
spells[2].instant = false;
spells[2].perctrigger = 11.0f;
spells[2].attackstoptimer = 4000;
spells[3].info = dbcSpell.LookupEntry(RAS_FEAR);
spells[3].targettype = TARGET_ATTACKING;
spells[3].instant = true; // should be false, but doesn't work then
spells[3].perctrigger = 9.0f;
spells[3].attackstoptimer = 2000;
spells[4].info = dbcSpell.LookupEntry(CHILL_NOVA);
spells[4].targettype = TARGET_VARIOUS;
spells[4].instant = true;
spells[4].perctrigger = 8.0f;
spells[4].attackstoptimer = 1000;
spells[5].info = dbcSpell.LookupEntry(FROSTBOLT_VOLLEY);
spells[5].targettype = TARGET_VARIOUS;
spells[5].instant = true; // should be false, but doesn't work then
spells[5].perctrigger = 13.0f;
spells[5].attackstoptimer = 2000;
}
void OnCombatStart(Unit* mTarget)
{
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
_unit->CastSpell(_unit, spells[1].info, spells[1].instant);
}
void OnCombatStop(Unit *mTarget)
{
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
}
void OnDied(Unit * mKiller)
{
RemoveAIUpdateEvent();
}
void AIUpdate()
{
float val = (float)RandomFloat(100.0f);
SpellCast(val);
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i=0;i<nrspells;i++)
{
if(!spells[i].perctrigger) continue;
if(m_spellcheck[i])
{
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
target = _unit->GetAIInterface()->GetNextTarget();
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant);
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;
};
// Jandice BarovAI
#define CN_JANDICE_BAROV 10503 //+
#define CURSE_OF_BLOOD 24673
#define SUMMON_ILLUSION 17773
#define BANISH 39674 // not sure //8994
class JandiceBarovAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(JandiceBarovAI);
SP_AI_Spell spells[3];
bool m_spellcheck[3];
JandiceBarovAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
nrspells = 3;
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
spells[0].info = dbcSpell.LookupEntry(CURSE_OF_BLOOD);
spells[0].targettype = TARGET_DESTINATION;
spells[0].instant = true;
spells[0].perctrigger = 8.0f;
spells[0].attackstoptimer = 1000;
spells[1].info = dbcSpell.LookupEntry(BANISH);
spells[1].targettype = TARGET_ATTACKING;
spells[1].instant = false;
spells[1].perctrigger = 8.0f;
spells[1].attackstoptimer = 1000;
spells[2].info = dbcSpell.LookupEntry(SUMMON_ILLUSION);
spells[2].targettype = TARGET_SELF;
spells[2].instant = true;
spells[2].perctrigger = 5.0f;
spells[2].attackstoptimer = 1000;
}
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 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)
{
target = _unit->GetAIInterface()->GetNextTarget();
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant);
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;
};
// KormokAI
#define CN_KORMOK 14491 //+
#define SHADOW_BOLT_VOLLEY 20741
#define BONE_SHIELD 27688
#define SUMMON_RISEY_LACKEY 17618 // not sure
class KormokAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(KormokAI);
SP_AI_Spell spells[3];
bool m_spellcheck[3];
KormokAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
nrspells = 3;
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
spells[0].info = dbcSpell.LookupEntry(SHADOW_BOLT_VOLLEY);
spells[0].targettype = TARGET_VARIOUS;
spells[0].instant = true;
spells[0].perctrigger = 11.0f;
spells[0].attackstoptimer = 1000;
spells[1].info = dbcSpell.LookupEntry(BONE_SHIELD);
spells[1].targettype = TARGET_SELF;
spells[1].instant = true;
spells[1].perctrigger = 0.0f;
spells[1].attackstoptimer = 1000;
spells[2].info = dbcSpell.LookupEntry(SUMMON_RISEY_LACKEY);
spells[2].targettype = TARGET_SELF;
spells[2].instant = false;
spells[2].perctrigger = 4.0f;
spells[2].attackstoptimer = 1000;
}
void OnCombatStart(Unit* mTarget)
{
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
_unit->CastSpell(_unit, spells[1].info, spells[1].instant);
}
void OnCombatStop(Unit *mTarget)
{
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
}
void OnDied(Unit * mKiller)
{
RemoveAIUpdateEvent();
}
void AIUpdate()
{
float val = (float)RandomFloat(100.0f);
SpellCast(val);
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i=0;i<nrspells;i++)
{
if(!spells[i].perctrigger) continue;
if(m_spellcheck[i])
{
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
target = _unit->GetAIInterface()->GetNextTarget();
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant);
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;
};
// VectusAI
#define CN_VECTUS 10432 //+
#define FIRE_SHIELD 19627
#define BLAST_WAVE 13021
#define FRENZY 28371
class VectusAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(VectusAI);
SP_AI_Spell spells[3];
bool m_spellcheck[3];
VectusAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
FRENZY_LIMITER = 0;
nrspells = 3;
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
spells[0].info = dbcSpell.LookupEntry(BLAST_WAVE);
spells[0].targettype = TARGET_ATTACKING;
spells[0].instant = true;
spells[0].perctrigger = 18.0f;
spells[0].attackstoptimer = 1000;
spells[1].info = dbcSpell.LookupEntry(FIRE_SHIELD);
spells[1].targettype = TARGET_SELF;
spells[1].instant = true;
spells[1].perctrigger = 5.0f;
spells[1].attackstoptimer = 1000;
spells[2].info = dbcSpell.LookupEntry(FRENZY);
spells[2].targettype = TARGET_SELF;
spells[2].instant = true;
spells[2].perctrigger = 0.0f;
spells[2].attackstoptimer = 1000;
}
void OnCombatStart(Unit* mTarget)
{
FRENZY_LIMITER = 0;
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
_unit->CastSpell(_unit, spells[1].info, spells[1].instant);
}
void OnCombatStop(Unit *mTarget)
{
FRENZY_LIMITER = 0;
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
}
void OnDied(Unit * mKiller)
{
FRENZY_LIMITER = 0;
RemoveAIUpdateEvent();
}
void AIUpdate()
{
if(_unit->GetHealthPct() <= 25 && !FRENZY_LIMITER)
{
_unit->CastSpell(_unit, spells[2].info, spells[2].instant);
FRENZY_LIMITER = 1;
}
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)
{
target = _unit->GetAIInterface()->GetNextTarget();
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant);
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:
uint32 FRENZY_LIMITER;
int nrspells;
};
// Lord Alexei BarovAI
#define CN_LORD_ALEXEI_BAROV 10504 //+
#define UNHOLY_AURA 17467
#define IMMOLATE 20294
#define VEIL_OF_SHADOW 17820
class LordAlexeiBarovAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(LordAlexeiBarovAI);
SP_AI_Spell spells[3];
bool m_spellcheck[3];
LordAlexeiBarovAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
nrspells = 3;
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
spells[0].info = dbcSpell.LookupEntry(UNHOLY_AURA);
spells[0].targettype = TARGET_SELF;
spells[0].instant = true;
spells[0].perctrigger = 0.0f;
spells[0].attackstoptimer = 1000;
spells[1].info = dbcSpell.LookupEntry(IMMOLATE);
spells[1].targettype = TARGET_ATTACKING;
spells[1].instant = true;
spells[1].perctrigger = 10.0f;
spells[1].attackstoptimer = 1000;
spells[2].info = dbcSpell.LookupEntry(VEIL_OF_SHADOW);
spells[2].targettype = TARGET_VARIOUS;
spells[2].instant = false;
spells[2].perctrigger = 8.0f;
spells[2].attackstoptimer = 2000;
}
void OnCombatStart(Unit* mTarget)
{
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
_unit->CastSpell(_unit, spells[0].info, spells[0].instant);
}
void OnCombatStop(Unit *mTarget)
{
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
}
void OnDied(Unit * mKiller)
{
RemoveAIUpdateEvent();
}
void AIUpdate()
{
float val = (float)RandomFloat(100.0f);
SpellCast(val);
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i=0;i<nrspells;i++)
{
if(!spells[i].perctrigger) continue;
if(m_spellcheck[i])
{
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
target = _unit->GetAIInterface()->GetNextTarget();
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant);
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;
};
// Lorekeeper PolkeltAI
#define CN_LOREKEEPER_POLKELT 10901 //+
#define VOLATILE_INFECTION 24928 // wrong id // can cause crashes as it is casted on caster too
#define DARK_PLAGUE 18270 // sure it should be here?
#define CORROSIVE_ACID 19463 // Added Corrosive Acid Spit; 16359 or 20667 or 19463 or 19463 // 23313
#define NOXIOUS_CATALYST 18151
class LorekeeperPolkeltAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(LorekeeperPolkeltAI);
SP_AI_Spell spells[4];
bool m_spellcheck[4];
LorekeeperPolkeltAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
nrspells = 4;
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
spells[0].info = dbcSpell.LookupEntry(VOLATILE_INFECTION);
spells[0].targettype = TARGET_ATTACKING; // various affects caster too
spells[0].instant = true;
spells[0].perctrigger = 6.0f;
spells[0].attackstoptimer = 1000;
spells[1].info = dbcSpell.LookupEntry(DARK_PLAGUE);
spells[1].targettype = TARGET_ATTACKING;
spells[1].instant = true;
spells[1].perctrigger = 8.0f;
spells[1].attackstoptimer = 1000;
spells[2].info = dbcSpell.LookupEntry(CORROSIVE_ACID);
spells[2].targettype = TARGET_ATTACKING;
spells[2].instant = true; // should be false, but doesn't work then =/
spells[2].perctrigger = 12.0f;
spells[2].attackstoptimer = 1000;
spells[3].info = dbcSpell.LookupEntry(NOXIOUS_CATALYST);
spells[3].targettype = TARGET_ATTACKING;
spells[3].instant = true;
spells[3].perctrigger = 10.0f;
spells[3].attackstoptimer = 1000;
}
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 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)
{
target = _unit->GetAIInterface()->GetNextTarget();
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant);
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;
};
// Darkmaster GandlingAI
#define CN_DARKMASTER_GANDLING 1853 //+
#define ARCANE_MISSILES 25346
#define CURSE_OF_THE_DARKMASTER 18702
#define SHADOW_SHIELD 22417
class DarkmasterGandlingAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(DarkmasterGandlingAI);
SP_AI_Spell spells[3];
bool m_spellcheck[3];
DarkmasterGandlingAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
nrspells = 3; // 4 ?
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
spells[0].info = dbcSpell.LookupEntry(ARCANE_MISSILES); //VOLATILEINFECTION ???????? :|
spells[0].targettype = TARGET_ATTACKING;
spells[0].instant = true;
spells[0].perctrigger = 12.0f;
spells[0].attackstoptimer = 1000;
spells[1].info = dbcSpell.LookupEntry(CURSE_OF_THE_DARKMASTER);
spells[1].targettype = TARGET_ATTACKING;
spells[1].instant = false;
spells[1].perctrigger = 7.0f;
spells[1].attackstoptimer = 2000;
spells[2].info = dbcSpell.LookupEntry(SHADOW_SHIELD);
spells[2].targettype = TARGET_SELF;
spells[2].instant = true;
spells[2].perctrigger = 0.0f;
spells[2].attackstoptimer = 1000;
}
void OnCombatStart(Unit* mTarget)
{
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
_unit->CastSpell(_unit, spells[2].info, spells[2].instant);
}
void OnCombatStop(Unit *mTarget)
{
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
}
void OnDied(Unit * mKiller)
{
RemoveAIUpdateEvent();
}
void AIUpdate()
{
float val = (float)RandomFloat(100.0f);
SpellCast(val);
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i=0;i<nrspells;i++)
{
if(!spells[i].perctrigger) continue;
if(m_spellcheck[i])
{
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
target = _unit->GetAIInterface()->GetNextTarget();
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant);
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;
};
void SetupScholomance(ScriptMgr * mgr)
{
mgr->register_creature_script(CN_DOCTOR_THEOLEN_KRASTINOV, &DoctorTheolenKrastinovAI::Create);
mgr->register_creature_script(CN_INSTRUCTOR_MALICIA, &InstructorMaliciaAI::Create);
mgr->register_creature_script(CN_THE_RAVENIAN, &TheRavenianAI::Create);
mgr->register_creature_script(CN_LADY_ILLUCIA_BAROV, &LadyIlluciaBarovAI::Create);
mgr->register_creature_script(CN_RAS_FORSTWHISPER, &RasForstwhisperAI::Create);
mgr->register_creature_script(CN_JANDICE_BAROV, &JandiceBarovAI ::Create);
mgr->register_creature_script(CN_KORMOK, &KormokAI::Create);
mgr->register_creature_script(CN_VECTUS, &VectusAI::Create);
mgr->register_creature_script(CN_LORD_ALEXEI_BAROV, &LordAlexeiBarovAI::Create);
mgr->register_creature_script(CN_LOREKEEPER_POLKELT, &LorekeeperPolkeltAI::Create);
mgr->register_creature_script(CN_DARKMASTER_GANDLING, &DarkmasterGandlingAI::Create);
}
// Who should be added ?
// *Kirtonos the Herald
// *Death Knight Darkreaver
// *Lord Blackwood
// *Marduk Blackpool
// *Rattlegore
| [
"[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef"
]
| [
[
[
1,
1324
]
]
]
|
6a58c00eed221ddc8af09def42f0592c9a6ed84c | 854ee643a4e4d0b7a202fce237ee76b6930315ec | /arcemu_svn/src/arcemu-world/AIInterface.cpp | 18c87299021b806a30015822e5bcb91c5c8b3367 | []
| 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 | 129,597 | cpp | /*
* ArcEmu MMORPG Server
* Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2008 <http://www.ArcEmu.org/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "StdAfx.h"
#ifndef UNIX
#include <cmath>
#endif
#ifdef WIN32
#define HACKY_CRASH_FIXES 1 // SEH stuff
#endif
AIInterface::AIInterface()
{
m_waypoints=NULL;
m_canMove = true;
m_destinationX = m_destinationY = m_destinationZ = 0;
m_nextPosX = m_nextPosY = m_nextPosZ = 0;
UnitToFollow = NULL;
FollowDistance = 0.0f;
m_fallowAngle = float(M_PI/2);
m_timeToMove = 0;
m_timeMoved = 0;
m_moveTimer = 0;
m_WayPointsShowing = false;
m_WayPointsShowBackwards = false;
m_currentWaypoint = 0;
m_moveBackward = false;
m_moveType = 0;
m_moveRun = false;
m_moveSprint = false;
m_moveFly = false;
m_creatureState = STOPPED;
m_canCallForHelp = false;
m_hasCalledForHelp = false;
m_fleeTimer = 0;
m_FleeDuration = 0;
m_canFlee = false;
m_hasFleed = false;
m_canRangedAttack = false;
m_FleeHealth = m_CallForHelpHealth = 0.0f;
m_AIState = STATE_IDLE;
m_updateAssist = false;
m_updateTargets = false;
m_updateAssistTimer = 1;
m_updateTargetsTimer = TARGET_UPDATE_INTERVAL_ON_PLAYER;
m_updateTargetsTimer2 = 0;
m_nextSpell = NULL;
m_nextTarget = 0;
totemspell = NULL;
m_Unit = NULL;
m_PetOwner = NULL;
m_aiCurrentAgent = AGENT_NULL;
m_runSpeed = 0.0f;
m_flySpeed = 0.0f;
UnitToFear = NULL;
m_outOfCombatRange = 10000;
tauntedBy = NULL;
isTaunted = false;
soullinkedWith = NULL;
isSoulLinked = false;
m_AllowedToEnterCombat = true;
m_totalMoveTime = 0;
m_lastFollowX = m_lastFollowY = 0;
m_FearTimer = 0;
m_WanderTimer = 0;
m_totemspelltime = 0;
m_totemspelltimer = 0;
m_formationFollowAngle = 0.0f;
m_formationFollowDistance = 0.0f;
m_formationLinkTarget = 0;
m_formationLinkSqlId = 0;
m_currentHighestThreat = 0;
disable_combat = false;
disable_melee = false;
disable_ranged = false;
disable_spell = false;
disable_targeting = false;
next_spell_time = 0;
waiting_for_cooldown = false;
UnitToFollow_backup = NULL;
m_isGuard = false;
m_isNeutralGuard = false;
m_is_in_instance = false;
skip_reset_hp = false;
timed_emotes = NULL;
timed_emote_expire = 0xFFFFFFFF;
m_MovementState = MOVEMENTSTATE_STOP;
m_aiTargets.clear();
m_assistTargets.clear();
m_spells.clear();
#ifdef HACKY_SERVER_CLIENT_POS_SYNC
moved_for_attack = false;
#endif
}
void AIInterface::EventAiInterfaceParamsetFinish()
{
if( timed_emotes && timed_emotes->begin() != timed_emotes->end() )
{
next_timed_emote = timed_emotes->begin();
timed_emote_expire = (*next_timed_emote)->expire_after;
}
}
void AIInterface::Init(Unit *un, AIType at, MovementType mt)
{
ASSERT(at != AITYPE_PET);
m_AIType = at;
m_MovementType = mt;
m_AIState = STATE_IDLE;
m_MovementState = MOVEMENTSTATE_STOP;
m_Unit = un;
m_walkSpeed = m_Unit->m_walkSpeed*0.001f;//move distance per ms time
m_runSpeed = m_Unit->m_runSpeed*0.001f;//move distance per ms time
m_flySpeed = m_Unit->m_flySpeed * 0.001f;
/*if(!m_DefaultMeleeSpell)
{
m_DefaultMeleeSpell = new AI_Spell;
m_DefaultMeleeSpell->entryId = 0;
m_DefaultMeleeSpell->spellType = 0;
m_DefaultMeleeSpell->agent = AGENT_MELEE;
m_DefaultSpell = m_DefaultMeleeSpell;
}*/
m_sourceX = un->GetPositionX();
m_sourceY = un->GetPositionY();
m_sourceZ = un->GetPositionZ();
m_guardTimer = getMSTime();
}
AIInterface::~AIInterface()
{
for(list<AI_Spell*>::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
delete (*itr);
}
void AIInterface::Init(Unit *un, AIType at, MovementType mt, Unit *owner)
{
ASSERT(at == AITYPE_PET || at == AITYPE_TOTEM);
m_AIType = at;
m_MovementType = mt;
m_AIState = STATE_IDLE;
m_MovementState = MOVEMENTSTATE_STOP;
m_Unit = un;
m_PetOwner = owner;
m_walkSpeed = m_Unit->m_walkSpeed*0.001f;//move distance per ms time
m_runSpeed = m_Unit->m_runSpeed*0.001f;//move/ms
m_flySpeed = m_Unit->m_flySpeed*0.001f;
m_sourceX = un->GetPositionX();
m_sourceY = un->GetPositionY();
m_sourceZ = un->GetPositionZ();
}
void AIInterface::HandleEvent(uint32 event, Unit* pUnit, uint32 misc1)
{
if( m_Unit == NULL ) return;
if(m_AIState != STATE_EVADE)
{
switch(event)
{
case EVENT_ENTERCOMBAT:
{
if( pUnit == NULL || pUnit->isDead() || m_Unit->isDead() ) return;
/* send the message */
if( m_Unit->GetTypeId() == TYPEID_UNIT )
{
if( static_cast< Creature* >( m_Unit )->has_combat_text )
objmgr.HandleMonsterSayEvent( static_cast< Creature* >( m_Unit ), MONSTER_SAY_EVENT_ENTER_COMBAT );
CALL_SCRIPT_EVENT(m_Unit, OnCombatStart)(pUnit);
if( static_cast< Creature* >( m_Unit )->m_spawn && ( static_cast< Creature* >( m_Unit )->m_spawn->channel_target_go || static_cast< Creature* >( m_Unit )->m_spawn->channel_target_creature))
{
m_Unit->SetUInt32Value(UNIT_CHANNEL_SPELL, 0);
m_Unit->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
}
}
// Stop the emote - change to fight emote
m_Unit->SetUInt32Value( UNIT_NPC_EMOTESTATE, EMOTE_STATE_READY1H );
m_returnX = m_Unit->GetPositionX();
m_returnY = m_Unit->GetPositionY();
m_returnZ = m_Unit->GetPositionZ();
m_moveRun = true; //run to the target
// dismount if mounted
m_Unit->SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
if(m_AIState != STATE_ATTACKING)
StopMovement(0);
m_AIState = STATE_ATTACKING;
if(pUnit && pUnit->GetInstanceID() == m_Unit->GetInstanceID())
{
m_Unit->SetUInt64Value(UNIT_FIELD_TARGET, pUnit->GetGUID());
}
if(m_Unit->GetMapMgr() && m_Unit->GetMapMgr()->GetMapInfo() && m_Unit->GetMapMgr()->GetMapInfo()->type == INSTANCE_RAID)
{
if(m_Unit->GetTypeId() == TYPEID_UNIT)
{
if(static_cast<Creature*>(m_Unit)->GetCreatureInfo() && static_cast<Creature*>(m_Unit)->GetCreatureInfo()->Rank == 3)
{
m_Unit->GetMapMgr()->AddCombatInProgress(m_Unit->GetGUID());
}
}
}
HandleChainAggro(pUnit);
//give 1 threat to this unit if were not on the threat list
if (m_aiTargets.find(pUnit->GetGUID())==m_aiTargets.end())
{
m_aiTargets.insert(TargetMap::value_type(pUnit->GetGUID(), 1));
}
//Zack : Put mob into combat animation. Take out weapons and start to look serious :P
m_Unit->smsg_AttackStart( pUnit );
}break;
case EVENT_DAMAGEDEALT:
{
if (m_aiTargets.find(pUnit->GetGUID())==m_aiTargets.end())
{
m_aiTargets.insert(TargetMap::value_type(pUnit->GetGUID(), 1));
}
}break;
case EVENT_LEAVECOMBAT:
{
if( pUnit == NULL ) return;
Unit* target = NULL;
if (m_Unit->GetMapMgr() && m_Unit->GetMapMgr()->GetMapInfo())
{
switch (m_Unit->GetMapMgr()->GetMapInfo()->type)
{
case INSTANCE_NULL:
case INSTANCE_PVP:
if (m_outOfCombatRange && _CalcDistanceFromHome() < m_outOfCombatRange)
target = FindTarget();
break;
case INSTANCE_RAID:
case INSTANCE_NONRAID:
case INSTANCE_MULTIMODE:
target = FindTarget();
break;
}
if(target != NULL)
{
AttackReaction(target, 1, 0);
return;
}
}
if( pUnit->IsCreature() )
pUnit->RemoveNegativeAuras();
//cancel spells that we are casting. Should remove bug where creatures cast a spell after they died
// CancelSpellCast();
// restart emote
if(m_Unit->GetTypeId() == TYPEID_UNIT)
{
if( static_cast< Creature* >( m_Unit )->has_combat_text )
objmgr.HandleMonsterSayEvent( static_cast< Creature* >( m_Unit ), MONSTER_SAY_EVENT_ON_COMBAT_STOP );
if( static_cast< Creature* >( m_Unit )->original_emotestate )
m_Unit->SetUInt32Value( UNIT_NPC_EMOTESTATE, static_cast< Creature* >( m_Unit )->original_emotestate );
else
m_Unit->SetUInt32Value( UNIT_NPC_EMOTESTATE, 0 );
if(static_cast<Creature*>(m_Unit)->m_spawn && (static_cast< Creature* >( m_Unit )->m_spawn->channel_target_go || static_cast< Creature* >( m_Unit )->m_spawn->channel_target_creature ) )
{
if(static_cast<Creature*>(m_Unit)->m_spawn->channel_target_go)
sEventMgr.AddEvent( static_cast< Creature* >( m_Unit ), &Creature::ChannelLinkUpGO, static_cast< Creature* >( m_Unit )->m_spawn->channel_target_go, EVENT_CREATURE_CHANNEL_LINKUP, 1000, 5, 0 );
if(static_cast<Creature*>(m_Unit)->m_spawn->channel_target_creature)
sEventMgr.AddEvent( static_cast< Creature* >( m_Unit ), &Creature::ChannelLinkUpCreature, static_cast< Creature* >( m_Unit )->m_spawn->channel_target_creature, EVENT_CREATURE_CHANNEL_LINKUP, 1000, 5, 0 );
}
}
//reset ProcCount
//ResetProcCounts();
m_moveRun = true;
LockAITargets(true);
m_aiTargets.clear();
LockAITargets(false);
m_fleeTimer = 0;
m_hasFleed = false;
m_hasCalledForHelp = false;
m_nextSpell = NULL;
SetNextTarget( (Unit*)NULL );
m_Unit->CombatStatus.Vanished();
if(m_AIType == AITYPE_PET)
{
m_AIState = STATE_FOLLOWING;
UnitToFollow = m_PetOwner;
FollowDistance = 3.0f;
m_lastFollowX = m_lastFollowY = 0;
if( m_Unit->IsPet() )
{
static_cast< Pet* >( m_Unit )->SetPetAction( PET_ACTION_FOLLOW );
if( m_Unit->isAlive() && m_Unit->IsInWorld() )
{
static_cast< Pet* >( m_Unit )->HandleAutoCastEvent( AUTOCAST_EVENT_LEAVE_COMBAT );
}
}
HandleEvent(EVENT_FOLLOWOWNER, 0, 0);
}
else
{
m_AIState = STATE_EVADE;
Unit* SavedFollow = UnitToFollow;
UnitToFollow = NULL;
FollowDistance = 0.0f;
m_lastFollowX = m_lastFollowY = 0;
if(m_Unit->isAlive())
{
if(m_returnX != 0.0f && m_returnY != 0.0f && m_returnZ != 0.0f)
MoveTo(m_returnX,m_returnY,m_returnZ,m_Unit->GetSpawnO());
else
{
MoveTo(m_Unit->GetSpawnX(),m_Unit->GetSpawnY(),m_Unit->GetSpawnZ(),m_Unit->GetSpawnO());
m_returnX=m_Unit->GetSpawnX();
m_returnY=m_Unit->GetSpawnY();
m_returnZ=m_Unit->GetSpawnZ();
}
Creature *aiowner = static_cast<Creature*>(m_Unit);
//clear tagger.
aiowner->Tagged = false;
aiowner->TaggerGuid = 0;
aiowner->SetUInt32Value(UNIT_DYNAMIC_FLAGS,aiowner->GetUInt32Value(UNIT_DYNAMIC_FLAGS) & ~(U_DYN_FLAG_TAGGED_BY_OTHER |U_DYN_FLAG_LOOTABLE));
aiowner->m_lootMethod = -1;
}
CALL_SCRIPT_EVENT(m_Unit, OnCombatStop)(SavedFollow);
}
if(m_Unit->GetMapMgr() && m_Unit->GetMapMgr()->GetMapInfo() && m_Unit->GetMapMgr()->GetMapInfo()->type == INSTANCE_RAID)
{
if(m_Unit->GetTypeId() == TYPEID_UNIT)
{
if(static_cast<Creature*>(m_Unit)->GetCreatureInfo() && static_cast<Creature*>(m_Unit)->GetCreatureInfo()->Rank == 3)
{
m_Unit->GetMapMgr()->RemoveCombatInProgress(m_Unit->GetGUID());
}
}
}
// Remount if mounted
if(m_Unit->GetTypeId() == TYPEID_UNIT)
{
if( static_cast< Creature* >( m_Unit )->GetProto() )
m_Unit->SetUInt32Value( UNIT_FIELD_MOUNTDISPLAYID, static_cast< Creature* >( m_Unit )->GetProto()->MountedDisplayID );
}
//Zack : not sure we need to send this. Did not see it in the dumps since mob died eventually but it seems logical to make this
m_Unit->smsg_AttackStop( pUnit );
}break;
case EVENT_DAMAGETAKEN:
{
if( pUnit == NULL ) return;
if( static_cast< Creature* >( m_Unit )->has_combat_text )
objmgr.HandleMonsterSayEvent( static_cast< Creature* >( m_Unit ), MONSTER_SAY_EVENT_ON_DAMAGE_TAKEN );
HandleChainAggro(pUnit);
CALL_SCRIPT_EVENT(m_Unit, OnDamageTaken)(pUnit, float(misc1));
if(!modThreatByPtr(pUnit, misc1))
{
m_aiTargets.insert(TargetMap::value_type(pUnit->GetGUID(), misc1));
}
m_Unit->CombatStatus.OnDamageDealt(pUnit);
}break;
case EVENT_FOLLOWOWNER:
{
m_AIState = STATE_FOLLOWING;
if(m_Unit->IsPet())
((Pet*)m_Unit)->SetPetAction(PET_ACTION_FOLLOW);
UnitToFollow = m_PetOwner;
m_lastFollowX = m_lastFollowY = 0;
FollowDistance = 4.0f;
LockAITargets(true);
m_aiTargets.clear();
LockAITargets(false);
m_fleeTimer = 0;
m_hasFleed = false;
m_hasCalledForHelp = false;
m_nextSpell = NULL;
SetNextTarget( (Unit*)NULL );
m_moveRun = true;
}break;
case EVENT_FEAR:
{
if( pUnit == NULL ) return;
m_FearTimer = 0;
SetUnitToFear(pUnit);
CALL_SCRIPT_EVENT(m_Unit, OnFear)(pUnit, 0);
m_AIState = STATE_FEAR;
StopMovement(1);
UnitToFollow_backup = UnitToFollow;
UnitToFollow = NULL;
m_lastFollowX = m_lastFollowY = 0;
FollowDistance_backup = FollowDistance;
FollowDistance = 0.0f;
LockAITargets(true);
m_aiTargets.clear(); // we'll get a new target after we are unfeared
LockAITargets(false);
m_fleeTimer = 0;
m_hasFleed = false;
m_hasCalledForHelp = false;
// update speed
m_moveRun = true;
getMoveFlags();
SetNextSpell( NULL );
SetNextTarget( (Unit*)NULL);
}break;
case EVENT_UNFEAR:
{
UnitToFollow = UnitToFollow_backup;
FollowDistance = FollowDistance_backup;
m_AIState = STATE_IDLE; // we need this to prevent permanent fear, wander, and other problems
SetUnitToFear(NULL);
StopMovement(1);
}break;
case EVENT_WANDER:
{
if( pUnit == NULL ) return;
m_WanderTimer = 0;
//CALL_SCRIPT_EVENT(m_Unit, OnWander)(pUnit, 0); FIXME
m_AIState = STATE_WANDER;
StopMovement(1);
UnitToFollow_backup = UnitToFollow;
UnitToFollow = NULL;
m_lastFollowX = m_lastFollowY = 0;
FollowDistance_backup = FollowDistance;
FollowDistance = 0.0f;
LockAITargets(true);
m_aiTargets.clear(); // we'll get a new target after we are unwandered
LockAITargets(false);
m_fleeTimer = 0;
m_hasFleed = false;
m_hasCalledForHelp = false;
// update speed
m_moveRun = true;
getMoveFlags();
SetNextSpell(NULL);
SetNextTarget( (Unit*)NULL );
}break;
case EVENT_UNWANDER:
{
UnitToFollow = UnitToFollow_backup;
FollowDistance = FollowDistance_backup;
m_AIState = STATE_IDLE; // we need this to prevent permanent fear, wander, and other problems
StopMovement(1);
}break;
default:
{
}break;
}
}
//Should be able to do this stuff even when evading
switch(event)
{
case EVENT_UNITDIED:
{
if( pUnit == NULL ) return;
if( static_cast< Creature* >( m_Unit )->has_combat_text )
objmgr.HandleMonsterSayEvent( static_cast< Creature* >( m_Unit ), MONSTER_SAY_EVENT_ON_DIED );
CALL_SCRIPT_EVENT(m_Unit, OnDied)(pUnit);
m_AIState = STATE_IDLE;
StopMovement(0);
LockAITargets(true);
m_aiTargets.clear();
LockAITargets(false);
UnitToFollow = NULL;
m_lastFollowX = m_lastFollowY = 0;
UnitToFear = NULL;
FollowDistance = 0.0f;
m_fleeTimer = 0;
m_hasFleed = false;
m_hasCalledForHelp = false;
m_nextSpell = NULL;
SetNextTarget( (Unit*)NULL );
//reset ProcCount
//ResetProcCounts();
//reset waypoint to 0
m_currentWaypoint = 0;
// There isn't any need to do any attacker checks here, as
// they should all be taken care of in DealDamage
//removed by Zack : why do we need to go to our master if we just died ? On next spawn we will be spawned near him after all
/* if(m_AIType == AITYPE_PET)
{
SetUnitToFollow(m_PetOwner);
SetFollowDistance(3.0f);
HandleEvent(EVENT_FOLLOWOWNER, m_Unit, 0);
}*/
Instance *pInstance = NULL;
if(m_Unit->GetMapMgr())
pInstance = m_Unit->GetMapMgr()->pInstance;
if(m_Unit->GetMapMgr() && m_Unit->GetTypeId() == TYPEID_UNIT && !m_Unit->IsPet() && pInstance && (pInstance->m_mapInfo->type == INSTANCE_RAID || pInstance->m_mapInfo->type == INSTANCE_NONRAID || pInstance->m_mapInfo->type == INSTANCE_MULTIMODE))
{
InstanceBossInfoMap *bossInfoMap = objmgr.m_InstanceBossInfoMap[m_Unit->GetMapMgr()->GetMapId()];
Creature *pCreature = static_cast< Creature* >( m_Unit );
bool found = false;
if(IS_PERSISTENT_INSTANCE(pInstance) && bossInfoMap != NULL && pCreature->GetProto())
{
uint32 npcGuid = pCreature->GetProto()->Id;
InstanceBossInfoMap::const_iterator bossInfo = bossInfoMap->find(npcGuid);
if(bossInfo != bossInfoMap->end())
{
found = true;
m_Unit->GetMapMgr()->pInstance->m_killedNpcs.insert( npcGuid );
m_Unit->GetMapMgr()->pInstance->SaveToDB();
for(InstanceBossTrashList::iterator trash = bossInfo->second->trash.begin(); trash != bossInfo->second->trash.end(); ++trash)
{
Creature *c = m_Unit->GetMapMgr()->GetSqlIdCreature((*trash));
if(c != NULL)
c->m_noRespawn = true;
}
if(!pInstance->m_persistent)
{
pInstance->m_persistent = true;
pInstance->SaveToDB();
for(PlayerStorageMap::iterator itr = m_Unit->GetMapMgr()->m_PlayerStorage.begin(); itr != m_Unit->GetMapMgr()->m_PlayerStorage.end(); ++itr)
{
(*itr).second->SetPersistentInstanceId(pInstance);
}
}
}
}
if (found == false) {
// No instance boss information ... so fallback ...
uint32 npcGuid = pCreature->GetSQL_id();
m_Unit->GetMapMgr()->pInstance->m_killedNpcs.insert( npcGuid );
m_Unit->GetMapMgr()->pInstance->SaveToDB();
}
}
if(m_Unit->GetMapMgr() && m_Unit->GetMapMgr()->GetMapInfo() && m_Unit->GetMapMgr()->GetMapInfo()->type == INSTANCE_RAID)
{
if(m_Unit->GetTypeId() == TYPEID_UNIT)
{
if(static_cast<Creature*>(m_Unit)->GetCreatureInfo() && static_cast<Creature*>(m_Unit)->GetCreatureInfo()->Rank == 3)
{
m_Unit->GetMapMgr()->RemoveCombatInProgress(m_Unit->GetGUID());
}
}
}
//remove negative auras
//if( m_Unit->IsCreature() )
// m_Unit->RemoveNegativeAuras();
}break;
}
}
void AIInterface::Update(uint32 p_time)
{
float tdist;
if(m_AIType == AITYPE_TOTEM)
{
assert(totemspell != 0);
if(p_time >= m_totemspelltimer)
{
Spell *pSpell = SpellPool.PooledNew();
pSpell->Init(m_Unit, totemspell, true, 0);
SpellCastTargets targets(0);
if(!GetNextTarget() ||
(GetNextTarget() &&
(!m_Unit->GetMapMgr()->GetUnit(GetNextTarget()->GetGUID()) ||
!GetNextTarget()->isAlive() ||
!IsInrange(m_Unit,GetNextTarget(),pSpell->GetProto()->base_range_or_radius_sqr) ||
!isAttackable(m_Unit, GetNextTarget(),!(pSpell->GetProto()->c_is_flags & SPELL_FLAG_IS_TARGETINGSTEALTHED))
)
)
)
{
//we set no target and see if we managed to fid a new one
SetNextTarget( (Unit*)NULL );
//something happend to our target, pick another one
pSpell->GenerateTargets(&targets);
if(targets.m_targetMask & TARGET_FLAG_UNIT)
SetNextTarget( targets.m_unitTarget );
}
if(GetNextTarget())
{
SpellCastTargets targets(GetNextTarget()->GetGUID());
pSpell->prepare(&targets);
// need proper cooldown time!
m_totemspelltimer = m_totemspelltime;
}
else SpellPool.PooledDelete( pSpell );
// these will *almost always* be AoE, so no need to find a target here.
// SpellCastTargets targets(m_Unit->GetGUID());
// Spell * pSpell = new Spell(m_Unit, totemspell, true, 0);
// pSpell->prepare(&targets);
// need proper cooldown time!
// m_totemspelltimer = m_totemspelltime;
}
else
{
m_totemspelltimer -= p_time;
}
return;
}
_UpdateTimer(p_time);
_UpdateTargets();
if(m_Unit->isAlive() && m_AIState != STATE_IDLE
&& m_AIState != STATE_FOLLOWING && m_AIState != STATE_FEAR
&& m_AIState != STATE_WANDER && m_AIState != STATE_SCRIPTMOVE)
{
if(m_AIType == AITYPE_PET )
{
if(!m_Unit->bInvincible && m_Unit->IsPet())
{
Pet * pPet = static_cast<Pet*>(m_Unit);
if(pPet->GetPetAction() == PET_ACTION_ATTACK || pPet->GetPetState() != PET_STATE_PASSIVE)
{
_UpdateCombat(p_time);
}
}
//we just use any creature as a pet guardian
else if(!m_Unit->IsPet())
{
_UpdateCombat(p_time);
}
}
else
{
_UpdateCombat(p_time);
}
}
_UpdateMovement(p_time);
if(m_AIState==STATE_EVADE)
{
tdist = m_Unit->GetDistanceSq(m_returnX,m_returnY,m_returnZ);
if(tdist <= 4.0f/*2.0*/)
{
m_AIState = STATE_IDLE;
m_returnX = m_returnY = m_returnZ = 0.0f;
m_moveRun = false;
//remowed by zack : in scripted events if we keep reducing this it will bug the world out !
//On Blizz it will return to previous wp but we can accept the fact that it will move on to next one
/*
if(hasWaypoints())
{
if(m_moveBackward)
{
if(m_currentWaypoint != GetWayPointsCount()-1)
m_currentWaypoint++;
}
else
{
if(m_currentWaypoint != 0)
m_currentWaypoint--;
}
}
*/
// Set health to full if they at there last location before attacking
if(m_AIType != AITYPE_PET&&!skip_reset_hp)
m_Unit->SetUInt32Value(UNIT_FIELD_HEALTH,m_Unit->GetUInt32Value(UNIT_FIELD_MAXHEALTH));
}
else
{
if( m_creatureState == STOPPED )
{
// return to the home
if( m_returnX == 0.0f && m_returnY == 0.0f )
{
m_returnX = m_Unit->GetSpawnX();
m_returnY = m_Unit->GetSpawnY();
m_returnZ = m_Unit->GetSpawnZ();
}
MoveTo(m_returnX, m_returnY, m_returnZ, m_Unit->GetSpawnO());
}
}
}
if(m_fleeTimer)
{
if(m_fleeTimer > p_time)
{
m_fleeTimer -= p_time;
_CalcDestinationAndMove(GetNextTarget(), 5.0f);
}
else
{
m_fleeTimer = 0;
SetNextTarget(FindTargetForSpell(m_nextSpell));
}
}
//Pet Dismiss after a certian ditance away
/*if(m_AIType == AITYPE_PET && m_PetOwner != NULL)
{
float dist = (m_Unit->GetInstanceID() == m_PetOwner->GetInstanceID()) ?
m_Unit->GetDistanceSq(m_PetOwner) : 99999.0f;
if(dist > 8100.0f) //90 yard away we Dismissed
{
DismissPet();
return;
}
}*/
if ( !GetNextTarget() && !m_fleeTimer && m_creatureState == STOPPED && m_AIState == STATE_IDLE && m_Unit->isAlive() )
{
if ( timed_emote_expire <= p_time ) // note that creature might go idle and p_time might get big next time ...We do not skip emotes because of lost time
{
if ( (*next_timed_emote)->type == 1) //standstate
{
m_Unit->SetStandState( (*next_timed_emote)->value );
m_Unit->SetUInt32Value ( UNIT_NPC_EMOTESTATE, 0 );
}
else if ( (*next_timed_emote)->type == 2) //emotestate
{
m_Unit->SetUInt32Value ( UNIT_NPC_EMOTESTATE, (*next_timed_emote)->value );
m_Unit->SetStandState( 0 );
}
else if ( (*next_timed_emote)->type == 3) //oneshot emote
{
m_Unit->SetUInt32Value ( UNIT_NPC_EMOTESTATE, 0 );
m_Unit->SetStandState( 0 );
m_Unit->Emote( (EmoteType)(*next_timed_emote)->value ); // Animation
}
if ( (*next_timed_emote)->msg )
m_Unit->SendChatMessage((*next_timed_emote)->msg_type, (*next_timed_emote)->msg_lang, (*next_timed_emote)->msg);
timed_emote_expire = (*next_timed_emote)->expire_after; //should we keep lost time ? I think not
next_timed_emote++;
if ( next_timed_emote == timed_emotes->end() )
next_timed_emote = timed_emotes->begin();
}
else
timed_emote_expire -= p_time;
}
}
void AIInterface::_UpdateTimer(uint32 p_time)
{
if(m_updateAssistTimer > p_time)
{
m_updateAssistTimer -= p_time;
}else
{
m_updateAssist = true;
m_updateAssistTimer = TARGET_UPDATE_INTERVAL_ON_PLAYER * 2 - m_updateAssistTimer - p_time;
}
if(m_updateTargetsTimer > p_time)
{
m_updateTargetsTimer -= p_time;
}else
{
m_updateTargets = true;
m_updateTargetsTimer = TARGET_UPDATE_INTERVAL_ON_PLAYER * 2 - m_updateTargetsTimer - p_time;
}
}
void AIInterface::_UpdateTargets()
{
if( m_Unit->IsPlayer() || (m_AIType != AITYPE_PET && disable_targeting ))
return;
if( ( ( Creature* )m_Unit )->GetCreatureInfo() && ( ( Creature* )m_Unit )->GetCreatureInfo()->Type == CRITTER )
return;
if( m_Unit->GetMapMgr() == NULL )
return;
AssistTargetSet::iterator i, i2;
TargetMap::iterator itr, it2;
// Find new Assist Targets and remove old ones
if(m_AIState == STATE_FLEEING)
{
FindFriends(100.0f/*10.0*/);
}
else if(m_AIState != STATE_IDLE && m_AIState != STATE_SCRIPTIDLE)
{
FindFriends(100.0f/*10.0f*/);
}
if( m_updateAssist )
{
m_updateAssist = false;
/* deque<Unit*> tokill;
//modified for vs2005 compatibility
for(i = m_assistTargets.begin(); i != m_assistTargets.end(); ++i)
{
if(m_Unit->GetDistanceSq((*i)) > 2500.0f|| !(*i)->isAlive() || !(*i)->CombatStatus.IsInCombat())
{
tokill.push_back(*i);
}
}
for(deque<Unit*>::iterator i2 = tokill.begin(); i2 != tokill.end(); ++i2)
m_assistTargets.erase(*i2);*/
for(i = m_assistTargets.begin(); i != m_assistTargets.end();)
{
i2 = i++;
if((*i2) == NULL || (*i2)->event_GetCurrentInstanceId() != m_Unit->event_GetCurrentInstanceId() ||
!(*i2)->isAlive() || m_Unit->GetDistanceSq((*i2)) >= 2500.0f || !(*i2)->CombatStatus.IsInCombat() )
{
m_assistTargets.erase( i2 );
}
}
}
if( m_updateTargets )
{
m_updateTargets = false;
/*deque<Unit*> tokill;
//modified for vs2005 compatibility
for(itr = m_aiTargets.begin(); itr != m_aiTargets.end();++itr)
{
if(!itr->first->isAlive() || m_Unit->GetDistanceSq(itr->first) >= 6400.0f)
{
tokill.push_back(itr->first);
}
}
for(deque<Unit*>::iterator itr = tokill.begin(); itr != tokill.end(); ++itr)
m_aiTargets.erase((*itr));
tokill.clear();*/
LockAITargets(true);
for(itr = m_aiTargets.begin(); itr != m_aiTargets.end();)
{
it2 = itr++;
Unit *ai_t = m_Unit->GetMapMgr()->GetUnit( it2->first );
if (ai_t == NULL) {
m_aiTargets.erase( it2 );
} else {
bool instance = false;
if (m_Unit->GetMapMgr() && m_Unit->GetMapMgr()->GetMapInfo())
{
switch (m_Unit->GetMapMgr()->GetMapInfo()->type)
{
case INSTANCE_RAID:
case INSTANCE_NONRAID:
case INSTANCE_MULTIMODE:
instance = true;
break;
}
}
if( ai_t->event_GetCurrentInstanceId() != m_Unit->event_GetCurrentInstanceId() || !ai_t->isAlive() || (!instance && m_Unit->GetDistanceSq(ai_t) >= 6400.0f)) {
m_aiTargets.erase( it2 );
}
}
}
LockAITargets(false);
if(m_aiTargets.size() == 0
&& m_AIState != STATE_IDLE && m_AIState != STATE_FOLLOWING
&& m_AIState != STATE_EVADE && m_AIState != STATE_FEAR
&& m_AIState != STATE_WANDER && m_AIState != STATE_SCRIPTIDLE)
{
if (m_Unit->GetMapMgr() && m_Unit->GetMapMgr()->GetMapInfo())
{
Unit* target = NULL;
switch (m_Unit->GetMapMgr()->GetMapInfo()->type)
{
case INSTANCE_RAID:
case INSTANCE_NONRAID:
case INSTANCE_MULTIMODE:
target = FindTarget();
break;
default:
if (m_outOfCombatRange && _CalcDistanceFromHome() < m_outOfCombatRange)
target = FindTarget();
break;
}
if(target != NULL)
AttackReaction(target, 1, 0);
}
}
else if( m_aiTargets.size() == 0 && (m_AIType == AITYPE_PET && (m_Unit->IsPet() && static_cast<Pet*>(m_Unit)->GetPetState() == PET_STATE_AGGRESSIVE) || (!m_Unit->IsPet() && disable_melee == false ) ) )
{
Unit* target = FindTarget();
if( target )
{
AttackReaction(target, 1, 0);
}
}
}
// Find new Targets when we are ooc
if((m_AIState == STATE_IDLE || m_AIState == STATE_SCRIPTIDLE) && m_assistTargets.size() == 0)
{
Unit* target = FindTarget();
if(target)
{
AttackReaction(target, 1, 0);
}
}
}
///====================================================================
/// Desc: Updates Combat Status of m_Unit
///====================================================================
void AIInterface::_UpdateCombat(uint32 p_time)
{
if( m_AIType != AITYPE_PET && disable_combat )
return;
//just make sure we are not hitting self. This was reported as an exploit.Should never ocure anyway
if( GetNextTarget() == m_Unit )
SetNextTarget( GetMostHated() );
uint16 agent = m_aiCurrentAgent;
// If creature is very far from spawn point return to spawnpoint
// If at instance dont return -- this is wrong ... instance creatures always returns to spawnpoint, dunno how do you got this ideia.
// If at instance returns to spawnpoint after empty agrolist
if( m_AIType != AITYPE_PET
&& m_AIState != STATE_EVADE
&& m_AIState != STATE_SCRIPTMOVE
&& !m_is_in_instance
&& (m_outOfCombatRange && m_Unit->GetDistanceSq(m_returnX,m_returnY,m_returnZ) > m_outOfCombatRange) )
{
HandleEvent( EVENT_LEAVECOMBAT, m_Unit, 0 );
}
else if( GetNextTarget() == NULL && m_AIState != STATE_FOLLOWING && m_AIState != STATE_SCRIPTMOVE )
{
// SetNextTarget(FindTargetForSpell(m_nextSpell));
if( m_is_in_instance )
SetNextTarget( FindTarget() );
else SetNextTarget( GetMostHated() );
if( GetNextTarget() == NULL )
{
HandleEvent( EVENT_LEAVECOMBAT, m_Unit, 0 );
}
}
#ifdef HACKY_SERVER_CLIENT_POS_SYNC
if( moved_for_attack && GetNextTarget() && m_creatureState != MOVING )
{
//make sure we reached the exact desired location.
// due to combat updates creature might interrupt moving and start attacking and does not get to destination making us get out of range errors
if( m_destinationX )
{
m_Unit->m_position.x = m_destinationX;
m_Unit->m_position.y = m_destinationY;
}
//send a forced update position to client
StopMovement(0);
//no need to update position until mob moves to nev target
moved_for_attack = false;
}
#endif
/*if (sWorld.Collision) {
float target_land_z=0.0f;
if ( m_Unit->GetMapMgr() != NULL && GetNextTarget() != NULL )
{
if (!m_moveFly)
{
target_land_z = CollideInterface.GetHeight(m_Unit->GetMapId(), GetNextTarget()->GetPositionX(), GetNextTarget()->GetPositionY(), GetNextTarget()->GetPositionZ() + 2.0f);
if ( target_land_z == NO_WMO_HEIGHT )
target_land_z = m_Unit->GetMapMgr()->GetLandHeight(GetNextTarget()->GetPositionX(), GetNextTarget()->GetPositionY());
if (fabs(GetNextTarget()->GetPositionZ() - target_land_z) > _CalcCombatRange(GetNextTarget(), false))
{
if ( GetNextTarget()->GetTypeId() != TYPEID_PLAYER )
{
if ( target_land_z > m_Unit->GetMapMgr()->GetWaterHeight(GetNextTarget()->GetPositionX(), GetNextTarget()->GetPositionY()) )
HandleEvent( EVENT_LEAVECOMBAT, m_Unit, 0); //bugged npcs, probly db fault
}
else if (static_cast<Player*>(GetNextTarget())->GetSession() != NULL)
{
MovementInfo* mi=static_cast<Player*>(GetNextTarget())->GetSession()->GetMovementInfo();
if ( mi != NULL && !(mi->flags & MOVEFLAG_FALLING) && !(mi->flags & MOVEFLAG_SWIMMING) && !(mi->flags & MOVEFLAG_LEVITATE))
HandleEvent( EVENT_LEAVECOMBAT, m_Unit, 0);
}
}
}
}
}*/
if ( GetNextTarget() != NULL && GetNextTarget()->GetTypeId() == TYPEID_UNIT && m_AIState == STATE_EVADE)
HandleEvent( EVENT_LEAVECOMBAT, m_Unit, 0);
#ifdef HACKY_CRASH_FIXES
bool cansee = (GetNextTarget() != NULL) ? CheckCurrentTarget() : NULL;
#else
bool cansee;
if(GetNextTarget() && GetNextTarget()->event_GetCurrentInstanceId() == m_Unit->event_GetCurrentInstanceId())
{
if( m_Unit->GetTypeId() == TYPEID_UNIT )
cansee = static_cast< Creature* >( m_Unit )->CanSee( GetNextTarget() );
else
cansee = static_cast< Player* >( m_Unit )->CanSee( GetNextTarget() );
}
else
{
if( GetNextTarget() )
SetNextTarget( (Unit*)NULL ); // corupt pointer
cansee = false;
}
#endif
if( cansee && GetNextTarget() && GetNextTarget()->isAlive() && m_AIState != STATE_EVADE && !m_Unit->isCasting() )
{
if( agent == AGENT_NULL || ( m_AIType == AITYPE_PET && !m_nextSpell ) ) // allow pets autocast
{
if( !m_nextSpell )
m_nextSpell = this->getSpell();
/*
if(!m_nextSpell && waiting_for_cooldown)
{
// don't start running to the target for melee if we're waiting for a cooldown.
return;
}
*/
if(m_canFlee && !m_hasFleed
&& ((m_Unit->GetUInt32Value(UNIT_FIELD_HEALTH) / m_Unit->GetUInt32Value(UNIT_FIELD_MAXHEALTH)) < m_FleeHealth ))
agent = AGENT_FLEE;
else if(m_canCallForHelp
&& !m_hasCalledForHelp
/*&& (m_CallForHelpHealth > (m_Unit->GetUInt32Value(UNIT_FIELD_HEALTH) / (m_Unit->GetUInt32Value(UNIT_FIELD_MAXHEALTH) > 0 ? m_Unit->GetUInt32Value(UNIT_FIELD_MAXHEALTH) : 1)))*/)
agent = AGENT_CALLFORHELP;
else if(m_nextSpell)
{
if(m_nextSpell->agent != AGENT_NULL)
{
agent = m_nextSpell->agent;
}
else
{
agent = AGENT_MELEE;
}
}
else
{
agent = AGENT_MELEE;
}
}
if(agent == AGENT_RANGED || agent == AGENT_MELEE)
{
if(m_canRangedAttack)
{
agent = AGENT_MELEE;
if(GetNextTarget()->GetTypeId() == TYPEID_PLAYER)
{
float dist = m_Unit->GetDistanceSq(GetNextTarget());
if( static_cast< Player* >( GetNextTarget() )->m_currentMovement == MOVE_ROOT || dist >= 64.0f )
{
agent = AGENT_RANGED;
}
}
else if( GetNextTarget()->m_canMove == false || m_Unit->GetDistanceSq(GetNextTarget()) >= 64.0f )
{
agent = AGENT_RANGED;
}
}
else
{
agent = AGENT_MELEE;
}
}
if(this->disable_melee && agent == AGENT_MELEE)
agent = AGENT_NULL;
if(this->disable_ranged && agent == AGENT_RANGED)
agent = AGENT_NULL;
if(this->disable_spell && agent == AGENT_SPELL)
agent = AGENT_NULL;
switch(agent)
{
case AGENT_MELEE:
{
float combatReach[2]; // Calculate Combat Reach
float distance = m_Unit->CalcDistance(GetNextTarget());
combatReach[0] = GetNextTarget()->GetModelHalfSize();
combatReach[1] = _CalcCombatRange(GetNextTarget(), false);
if( (
// distance >= combatReach[0] && //removed by Zack. You can create an exploit with this that creature will never attack
distance <= combatReach[1] + DISTANCE_TO_SMALL_TO_WALK )
// || gracefull_hit_on_target == GetNextTarget()
) // Target is in Range -> Attack
{
// gracefull_hit_on_target = NULL;
if(UnitToFollow != NULL)
{
UnitToFollow = NULL; //we shouldn't be following any one
m_lastFollowX = m_lastFollowY = 0;
//m_Unit->setAttackTarget(NULL); // remove ourselves from any target that might have been followed
}
FollowDistance = 0.0f;
// m_moveRun = false;
//FIXME: offhand shit
if(m_Unit->isAttackReady(false) && !m_fleeTimer)
{
m_creatureState = ATTACKING;
bool infront = m_Unit->isInFront(GetNextTarget());
if(!infront) // set InFront
{
//prevent mob from rotating while stunned
if(!m_Unit->IsStunned ())
{
setInFront(GetNextTarget());
infront = true;
}
}
if(infront)
{
m_Unit->setAttackTimer(0, false);
#ifdef ENABLE_CREATURE_DAZE
//we require to know if strike was succesfull. If there was no dmg then target cannot be dazed by it
Unit *t_unit = GetNextTarget();
if( !t_unit )
return; //omg lol, in seconds we lost target. This might be possible due to the Eventrelocated
uint32 health_before_strike = t_unit->GetUInt32Value(UNIT_FIELD_HEALTH);
#endif
m_Unit->Strike( GetNextTarget(), ( agent == AGENT_MELEE ? MELEE : RANGED ), NULL, 0, 0, 0, false, false );
#ifdef ENABLE_CREATURE_DAZE
//now if the target is facing his back to us then we could just cast dazed on him :P
//as far as i know dazed is casted by most of the creatures but feel free to remove this code if you think otherwise
if(GetNextTarget() && m_Unit->m_factionDBC &&
!(m_Unit->m_factionDBC->RepListId == -1 && m_Unit->m_faction->FriendlyMask==0 && m_Unit->m_faction->HostileMask==0) /* neutral creature */
&& GetNextTarget()->IsPlayer() && !m_Unit->IsPet() && health_before_strike>GetNextTarget()->GetUInt32Value(UNIT_FIELD_HEALTH)
&& Rand(m_Unit->get_chance_to_daze(GetNextTarget())))
{
float our_facing=m_Unit->calcRadAngle(m_Unit->GetPositionX(),m_Unit->GetPositionY(),GetNextTarget()->GetPositionX(),GetNextTarget()->GetPositionY());
float his_facing=GetNextTarget()->GetOrientation();
if(fabs(our_facing-his_facing)<CREATURE_DAZE_TRIGGER_ANGLE && !GetNextTarget()->HasAura(CREATURE_SPELL_TO_DAZE))
{
SpellEntry *info = dbcSpell.LookupEntry(CREATURE_SPELL_TO_DAZE);
Spell *sp = SpellPool.PooledNew();
sp->Init(m_Unit, info, false, NULL);
SpellCastTargets targets;
targets.m_unitTarget = GetNextTarget()->GetGUID();
sp->prepare(&targets);
}
}
#endif
}
}
}
else // Target out of Range -> Run to it
{
//calculate next move
// float dist = combatReach[1]; //this is theoretically right but annoying formula in game
// float dist = combatReach[1] - m_Unit->GetFloatValue( UNIT_FIELD_COMBATREACH ); //ignore our combat reach, make sure target (player) can reach us first.
//practical tests show that we really should try to jump on target to get good results :S
//simply ignore combat reach and move as close as visually not annoying
float dist;
if( m_Unit->GetModelHalfSize() > GetNextTarget()->GetModelHalfSize() )
dist = m_Unit->GetModelHalfSize();
else
dist = GetNextTarget()->GetModelHalfSize();
//removed by Zack. You can create an exploit with this that creature will never attack
// if (distance<combatReach[0]) //if we are inside one each other
// dist = -(combatReach[1] - distance);
// gracefull_hit_on_target = GetNextTarget(); // this is an exploit where you manage to move the exact speed that mob will reposition itself all the time
m_moveRun = true;
_CalcDestinationAndMove(GetNextTarget(), dist);
}
}break;
case AGENT_RANGED:
{
float combatReach[2]; // Calculate Combat Reach
float distance = m_Unit->CalcDistance(GetNextTarget());
combatReach[0] = 8.0f;
combatReach[1] = 30.0f;
if(distance >= combatReach[0] && distance <= combatReach[1]) // Target is in Range -> Attack
{
if(UnitToFollow != NULL)
{
UnitToFollow = NULL; //we shouldn't be following any one
m_lastFollowX = m_lastFollowY = 0;
//m_Unit->setAttackTarget(NULL); // remove ourselves from any target that might have been followed
}
FollowDistance = 0.0f;
// m_moveRun = false;
//FIXME: offhand shit
if(m_Unit->isAttackReady(false) && !m_fleeTimer)
{
m_creatureState = ATTACKING;
bool infront = m_Unit->isInFront(GetNextTarget());
if(!infront) // set InFront
{
//prevent mob from rotating while stunned
if(!m_Unit->IsStunned ())
{
setInFront(GetNextTarget());
infront = true;
}
}
if(infront)
{
m_Unit->setAttackTimer(0, false);
SpellEntry *info = dbcSpell.LookupEntry(SPELL_RANGED_GENERAL);
if(info)
{
Spell *sp = SpellPool.PooledNew();
sp->Init(m_Unit, info, false, NULL);
SpellCastTargets targets;
targets.m_unitTarget = GetNextTarget()->GetGUID();
sp->prepare(&targets);
//Lets make spell handle this
//m_Unit->Strike( GetNextTarget(), ( agent == AGENT_MELEE ? MELEE : RANGED ), NULL, 0, 0, 0 );
}
}
}
}
else // Target out of Range -> Run to it
{
//calculate next move
float dist;
if(distance < combatReach[0])// Target is too near
dist = 9.0f;
else
dist = 20.0f;
m_moveRun = true;
_CalcDestinationAndMove(GetNextTarget(), dist);
}
}break;
case AGENT_SPELL:
{
if(!m_nextSpell || !GetNextTarget())
return; // this shouldnt happen
SpellCastTime *sd = dbcSpellCastTime.LookupEntry(m_nextSpell->spell->CastingTimeIndex);
float distance = m_Unit->CalcDistance(GetNextTarget());
bool los = true;
if (sWorld.Collision) {
los = CollideInterface.CheckLOS(m_Unit->GetMapId(), m_Unit->GetPositionNC(),GetNextTarget()->GetPositionNC());
}
if(los
&& ( ( distance <= m_nextSpell->maxrange + m_Unit->GetModelHalfSize()
// && distance >= m_nextSpell->minrange
)
|| m_nextSpell->maxrange == 0) ) // Target is in Range -> Attack
{
SpellEntry* spellInfo = m_nextSpell->spell;
/* if in range stop moving so we don't interrupt the spell */
//do not stop for instant spells
if(sd && GetCastTime(sd) != 0)
StopMovement(0);
/* if(m_nextSpell->procCount)
m_nextSpell->procCount--;*/
SpellCastTargets targets = setSpellTargets(spellInfo, GetNextTarget());
uint32 targettype = m_nextSpell->spelltargetType;
switch(targettype)
{
case TTYPE_CASTER:
case TTYPE_SINGLETARGET:
{
CastSpell(m_Unit, spellInfo, targets);
break;
}
case TTYPE_SOURCE:
{
m_Unit->CastSpellAoF(targets.m_srcX,targets.m_srcY,targets.m_srcZ, spellInfo, true);
break;
}
case TTYPE_DESTINATION:
{
m_Unit->CastSpellAoF(targets.m_destX,targets.m_destY,targets.m_destZ, spellInfo, true);
break;
}
default:
sLog.outError("AI Agents: Targettype of AI agent spell %u for creature %u not set", spellInfo->Id, static_cast< Creature* >( m_Unit )->GetCreatureInfo()->Id );
}
// CastSpell(m_Unit, spellInfo, targets);
if(m_nextSpell&&m_nextSpell->cooldown)
m_nextSpell->cooldowntime = getMSTime() + m_nextSpell->cooldown;
next_spell_time = (uint32)UNIXTIME + MOB_SPELLCAST_GLOBAL_COOLDOWN;
//add pet spell after use to pet owner
if( m_Unit->IsPet() )
static_cast< Pet* >( m_Unit )->AddPetSpellToOwner( spellInfo->Id );
m_nextSpell = NULL;
}
else // Target out of Range -> Run to it
{
//calculate next move
m_moveRun = true;
float close_to_enemy = 0.0f;
if( distance > m_nextSpell->maxrange )
close_to_enemy = m_nextSpell->maxrange - DISTANCE_TO_SMALL_TO_WALK ;
else if( distance < m_nextSpell->minrange )
close_to_enemy = m_nextSpell->minrange + DISTANCE_TO_SMALL_TO_WALK ;
if( close_to_enemy < 0 )
close_to_enemy = 0;
_CalcDestinationAndMove(GetNextTarget(), close_to_enemy ); //if we make exact movement we will never position perfectly
/*Destination* dst = _CalcDestination(GetNextTarget(), dist);
MoveTo(dst->x, dst->y, dst->z,0);
delete dst;*/
}
}break;
case AGENT_FLEE:
{
//float dist = 5.0f;
m_moveRun = false;
if(m_fleeTimer == 0)
m_fleeTimer = m_FleeDuration;
/*Destination* dst = _CalcDestination(GetNextTarget(), dist);
MoveTo(dst->x, dst->y, dst->z,0);
delete dst;*/
_CalcDestinationAndMove(GetNextTarget(), 5.0f);
if(!m_hasFleed)
CALL_SCRIPT_EVENT(m_Unit, OnFlee)(GetNextTarget());
m_AIState = STATE_FLEEING;
//removed by Zack : somehow creature starts to attack sefl. Just making sure it is not this one
// m_nextTarget = m_Unit;
// m_Unit->SetUInt64Value(UNIT_FIELD_TARGET, 0);
SetNextTarget( (Unit*)NULL );
WorldPacket data( SMSG_MESSAGECHAT, 100 );
string msg = "%s attempts to run away in fear!";
data << (uint8)CHAT_MSG_CHANNEL;
data << (uint32)LANG_UNIVERSAL;
data << (uint32)( strlen( static_cast< Creature* >( m_Unit )->GetCreatureInfo()->Name ) + 1 );
data << static_cast< Creature* >( m_Unit )->GetCreatureInfo()->Name;
data << (uint64)0;
data << (uint32)(msg.size() + 1);
data << msg;
data << uint8(0);
m_Unit->SendMessageToSet(&data, false);
//m_Unit->SendChatMessage(CHAT_MSG_MONSTER_EMOTE, LANG_UNIVERSAL, msg);
//sChatHandler.FillMessageData(&data, CHAT_MSG_MONSTER_EMOTE, LANG_UNIVERSAL, msg, m_Unit->GetGUID());
m_hasFleed = true;
}break;
case AGENT_CALLFORHELP:
{
FindFriends( 64.0f /*8.0f*/ );
m_hasCalledForHelp = true; // We only want to call for Help once in a Fight.
if( m_Unit->GetTypeId() == TYPEID_UNIT )
objmgr.HandleMonsterSayEvent( static_cast< Creature* >( m_Unit ), MONSTER_SAY_EVENT_CALL_HELP );
CALL_SCRIPT_EVENT( m_Unit, OnCallForHelp )();
}break;
}
}
else if( !GetNextTarget() || GetNextTarget()->GetInstanceID() != m_Unit->GetInstanceID() || !GetNextTarget()->isAlive() || !cansee )
{
SetNextTarget( (Unit*)NULL );
// no more target
//m_Unit->setAttackTarget(NULL);
}
}
void AIInterface::DismissPet()
{
/*
if(m_AIType != AITYPE_PET)
return;
if(!m_PetOwner)
return;
if(m_PetOwner->GetTypeId() != TYPEID_PLAYER)
return;
if(m_Unit->GetUInt32Value(UNIT_CREATED_BY_SPELL) == 0)
static_cast< Player* >( m_PetOwner )->SetFreePetNo(false, (int)m_Unit->GetUInt32Value(UNIT_FIELD_PETNUMBER));
static_cast< Player* >( m_PetOwner )->SetPet(NULL);
static_cast< Player* >( m_PetOwner )->SetPetName("");
//FIXME:Check hunter pet or not
//FIXME:Check enslaved creature
m_PetOwner->SetUInt64Value(UNIT_FIELD_SUMMON, 0);
WorldPacket data;
data.Initialize(SMSG_PET_SPELLS);
data << (uint64)0;
static_cast< Player* >( m_PetOwner )->GetSession()->SendPacket(&data);
sEventMgr.RemoveEvents(((Creature*)m_Unit));
if(m_Unit->IsInWorld())
{
m_Unit->RemoveFromWorld();
}
//setup an event to delete the Creature
sEventMgr.AddEvent(((Creature*)this->m_Unit), &Creature::DeleteMe, EVENT_DELETE_TIMER, 1, 1);*/
}
void AIInterface::AttackReaction(Unit* pUnit, uint32 damage_dealt, uint32 spellId)
{
if( m_AIState == STATE_EVADE || !pUnit || !pUnit->isAlive() || m_Unit->isDead() || m_Unit == pUnit )
return;
if( sWorld.Collision && pUnit->IsPlayer() )
{
float target_land_z=0.0f;
if ( m_Unit->GetMapMgr() != NULL )
{
if (!m_moveFly)
{
target_land_z = CollideInterface.GetHeight(m_Unit->GetMapId(), pUnit->GetPositionX(), pUnit->GetPositionY(), pUnit->GetPositionZ() + 2.0f);
if ( target_land_z == NO_WMO_HEIGHT )
target_land_z = m_Unit->GetMapMgr()->GetLandHeight(pUnit->GetPositionX(), pUnit->GetPositionY());
if (fabs(pUnit->GetPositionZ() - target_land_z) > _CalcCombatRange(pUnit, false) )
{
if ( pUnit->GetTypeId()!=TYPEID_PLAYER && target_land_z > m_Unit->GetMapMgr()->GetWaterHeight(pUnit->GetPositionX(), pUnit->GetPositionY()) )
return;
else if( static_cast<Player*>(pUnit)->GetSession() != NULL )
{
MovementInfo* mi=static_cast<Player*>(pUnit)->GetSession()->GetMovementInfo();
if ( mi != NULL && !(mi->flags & MOVEFLAG_FALLING) && !(mi->flags & MOVEFLAG_SWIMMING) && !(mi->flags & MOVEFLAG_LEVITATE))
return;
}
}
}
}
}
if (pUnit->GetTypeId() == TYPEID_PLAYER && static_cast<Player *>(pUnit)->GetMisdirectionTarget() != 0)
{
Unit *mTarget = m_Unit->GetMapMgr()->GetUnit(static_cast<Player *>(pUnit)->GetMisdirectionTarget());
if (mTarget != NULL && mTarget->isAlive())
pUnit = mTarget;
}
if( (m_AIState == STATE_IDLE || m_AIState == STATE_FOLLOWING) && m_Unit->GetAIInterface()->GetAllowedToEnterCombat())
{
WipeTargetList();
HandleEvent(EVENT_ENTERCOMBAT, pUnit, 0);
}
HandleEvent(EVENT_DAMAGETAKEN, pUnit, _CalcThreat(damage_dealt, spellId ? dbcSpell.LookupEntryForced(spellId) : NULL, pUnit));
}
void AIInterface::HealReaction(Unit* caster, Unit* victim, SpellEntry* sp, uint32 amount)
{
if(!caster || !victim)
return;
bool casterInList = false, victimInList = false;
if(m_aiTargets.find(caster->GetGUID()) != m_aiTargets.end())
casterInList = true;
if(m_aiTargets.find(victim->GetGUID()) != m_aiTargets.end())
victimInList = true;
if(!victimInList && !casterInList) // none of the Casters is in the Creatures Threat list
return;
int32 threat = int32(amount / 2);
if (caster->getClass() == PALADIN)
threat = threat / 2; //Paladins only get 50% threat per heal than other classes
if (sp != NULL)
threat += (threat * caster->GetGeneratedThreatModifyer(sp->School) / 100);
if (threat < 1)
threat = 1;
if(!casterInList && victimInList) // caster is not yet in Combat but victim is
{
// get caster into combat if he's hostile
if(isHostile(m_Unit, caster))
m_aiTargets.insert(TargetMap::value_type(caster->GetGUID(), threat));
}
else if(casterInList && victimInList) // both are in combat already
modThreatByPtr(caster, threat);
else // caster is in Combat already but victim is not
{
modThreatByPtr(caster, threat);
// both are players so they might be in the same group
if( caster->GetTypeId() == TYPEID_PLAYER && victim->GetTypeId() == TYPEID_PLAYER )
{
if( static_cast< Player* >( caster )->GetGroup() == static_cast< Player* >( victim )->GetGroup() )
{
// get victim into combat since they are both
// in the same party
if( isHostile( m_Unit, victim ) )
m_aiTargets.insert( TargetMap::value_type( victim->GetGUID(), 1 ) );
}
}
}
}
void AIInterface::OnDeath(Object* pKiller)
{
if(pKiller->GetTypeId() == TYPEID_PLAYER || pKiller->GetTypeId() == TYPEID_UNIT)
HandleEvent(EVENT_UNITDIED, static_cast<Unit*>(pKiller), 0);
else
HandleEvent(EVENT_UNITDIED, m_Unit, 0);
}
//function is designed to make a quick check on target to decide if we can attack it
bool AIInterface::UnsafeCanOwnerAttackUnit(Unit *pUnit)
{
if( !isHostile(m_Unit,pUnit ) )
return false;
if( !pUnit->isAlive() )
return false;
if( pUnit->bInvincible )
return false;
//do not agro units that are faking death. Should this be based on chance ?
if( pUnit->HasFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_FEIGN_DEATH ) )
return false;
//don't attack owner
if( m_Unit->GetUInt64Value(UNIT_FIELD_CREATEDBY) == pUnit->GetGUID() )
return false;
//don't agro neutrals
if( ( pUnit->IsPlayer() || pUnit->IsPet() )
&& m_Unit->m_factionDBC
&& m_Unit->m_factionDBC->RepListId == -1
&& m_Unit->m_faction->HostileMask == 0
&& m_Unit->m_faction->FriendlyMask == 0
)
return false;
else if( ( m_Unit->IsPlayer() || m_Unit->IsPet() )
&& pUnit->m_factionDBC
&& pUnit->m_factionDBC->RepListId == -1
&& pUnit->m_faction->HostileMask == 0
&& pUnit->m_faction->FriendlyMask == 0
)
return false;
//make sure we do not agro flying stuff
if( abs( pUnit->GetPositionZ() - m_Unit->GetPositionZ() ) > _CalcCombatRange( pUnit, false ) )
return false; //blizz has this set to 250 but uses pathfinding
return true;
}
//this function might be slow but so it should not be spammed
//!!!this function has been reported the biggest bottleneck on emu in 2008 07 04
Unit* AIInterface::FindTarget()
{// find nearest hostile Target to attack
if( !m_AllowedToEnterCombat )
return NULL;
if( m_Unit->GetMapMgr() == NULL )
return NULL;
Unit* target = NULL;
Unit* critterTarget = NULL;
float distance = 999999.0f; // that should do it.. :p
// float crange;
// float z_diff;
std::set<Object*>::iterator itr, itr2;
std::set<Player *>::iterator pitr, pitr2;
// Object *pObj;
Unit *pUnit;
float dist;
bool pvp=true;
if(m_Unit->GetTypeId()==TYPEID_UNIT&&((Creature*)m_Unit)->GetCreatureInfo()&&((Creature*)m_Unit)->GetCreatureInfo()->Civilian)
pvp=false;
//target is immune to all form of attacks, cant attack either.
// not attackable creatures sometimes fight enemies in scripted fights though
if(m_Unit->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NOT_ATTACKABLE_2))
{
return 0;
}
if (m_isNeutralGuard)
{
Player *tmpPlr;
for (std::set<Player*>::iterator itrPlr = m_Unit->GetInRangePlayerSetBegin(); itrPlr != m_Unit->GetInRangePlayerSetEnd(); ++itrPlr)
{
tmpPlr = (*itrPlr);
if (tmpPlr == NULL)
continue;
if (tmpPlr->GetTaxiState())
continue;
if (tmpPlr->bInvincible)
continue;
if (tmpPlr->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FEIGN_DEATH))
continue;
if (tmpPlr->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_ATTACKABLE_9))
continue;
if (tmpPlr->m_invisible)
continue;
if (tmpPlr->CombatStatus.GetPrimaryAttackTarget() == 0)
continue;
else
{
Unit *pPTarget = GetUnit()->GetMapMgr()->GetUnit( tmpPlr->CombatStatus.GetPrimaryAttackTarget() );
if( pPTarget == NULL)
continue;
if (!pPTarget->IsPlayer())
continue;
if (tmpPlr->DuelingWith == static_cast<Player*>(pPTarget))
continue;
}
dist = m_Unit->GetDistanceSq(tmpPlr);
if (dist > 2500.0f)
continue;
if (distance > dist)
{
if (sWorld.Collision) {
if( CollideInterface.CheckLOS( m_Unit->GetMapId(), m_Unit->GetPositionNC(), tmpPlr->GetPositionNC() ) )
{
distance = dist;
target = static_cast<Unit*>(tmpPlr);
}
} else {
distance = dist;
target = static_cast<Unit*>(tmpPlr);
}
}
}
if (target)
{
m_Unit->m_runSpeed = m_Unit->m_base_runSpeed * 2.0f;
AttackReaction(target, 1, 0);
WorldPacket data(SMSG_AI_REACTION, 12);
data << m_Unit->GetGUID() << uint32(2); // Aggro sound
static_cast< Player* >( target )->GetSession()->SendPacket( &data );
return target;
}
distance = 999999.0f; //Reset Distance for normal check
}
//we have a high chance that we will agro a player
//this is slower then oppfaction list BUT it has a lower chance that contains invalid pointers
for( pitr2 = m_Unit->GetInRangePlayerSetBegin(); pitr2 != m_Unit->GetInRangePlayerSetEnd(); )
{
pitr = pitr2;
++pitr2;
pUnit = *pitr;
if( UnsafeCanOwnerAttackUnit( pUnit ) == false )
continue;
//on blizz there is no Z limit check
dist = m_Unit->GetDistance2dSq(pUnit);
if(dist > distance) // we want to find the CLOSEST target
continue;
if(dist <= _CalcAggroRange(pUnit) )
{
if (sWorld.Collision) {
if( CollideInterface.CheckLOS( m_Unit->GetMapId( ), m_Unit->GetPositionNC( ), pUnit->GetPositionNC( ) ) )
{
distance = dist;
target = pUnit;
}
} else {
distance = dist;
target = pUnit;
}
}
}
//a lot less times are check inter faction mob wars :)
if( m_updateTargetsTimer2 < getMSTime() )
{
m_updateTargetsTimer2 = getMSTime() + TARGET_UPDATE_INTERVAL;
m_Unit->AquireInrangeLock(); //make sure to release lock before exit function !
for( itr2 = m_Unit->GetInRangeSetBegin(); itr2 != m_Unit->GetInRangeSetEnd(); )
{
itr = itr2;
++itr2;
if( !(*itr)->IsUnit() )
continue;
pUnit = static_cast< Unit* >( (*itr) );
if( UnsafeCanOwnerAttackUnit( pUnit ) == false )
continue;
//on blizz there is no Z limit check
dist = m_Unit->GetDistance2dSq(pUnit);
if(pUnit->m_faction && pUnit->m_faction->Faction == 28)// only Attack a critter if there is no other Enemy in range
{
if(dist < 225.0f) // was 10
critterTarget = pUnit;
continue;
}
if(dist > distance) // we want to find the CLOSEST target
continue;
if(dist <= _CalcAggroRange(pUnit) )
{
if (sWorld.Collision) {
if( CollideInterface.CheckLOS( m_Unit->GetMapId( ), m_Unit->GetPositionNC( ), pUnit->GetPositionNC( ) ) )
{
distance = dist;
target = pUnit;
}
} else {
distance = dist;
target = pUnit;
}
}
}
m_Unit->ReleaseInrangeLock();
}
if( !target )
{
target = critterTarget;
}
if( target )
{
/* if(m_isGuard)
{
m_Unit->m_runSpeed = m_Unit->m_base_runSpeed * 2.0f;
m_fastMove = true;
}*/
AttackReaction(target, 1, 0);
if(target->IsPlayer())
{
WorldPacket data(SMSG_AI_REACTION, 12);
data << m_Unit->GetGUID() << uint32(2); // Aggro sound
static_cast< Player* >( target )->GetSession()->SendPacket( &data );
}
if(target->GetUInt32Value(UNIT_FIELD_CREATEDBY) != 0)
{
Unit* target2 = m_Unit->GetMapMgr()->GetPlayer(target->GetUInt32Value(UNIT_FIELD_CREATEDBY));
/*if(!target2)
{
target2 = sObjHolder.GetObject<Player>(target->GetUInt32Value(UNIT_FIELD_CREATEDBY));
}*/
if(target2)
{
AttackReaction(target2, 1, 0);
}
}
}
return target;
}
Unit* AIInterface::FindTargetForSpell(AI_Spell *sp)
{
/*if(!m_Unit) return NULL;*/
/*if(!sp)
{
m_Unit->SetUInt64Value(UNIT_FIELD_TARGET, 0);
return NULL;
}*/
TargetMap::iterator itr, itr2;
if(sp)
{
if(sp->spellType == STYPE_HEAL)
{
uint32 cur = m_Unit->GetUInt32Value(UNIT_FIELD_HEALTH) + 1;
uint32 max = m_Unit->GetUInt32Value(UNIT_FIELD_MAXHEALTH) + 1;
float healthPercent = float(cur) / float(max);
if(healthPercent <= sp->floatMisc1) // Heal ourselves cause we got too low HP
{
m_Unit->SetUInt64Value(UNIT_FIELD_TARGET, 0);
return m_Unit;
}
for(AssistTargetSet::iterator i = m_assistTargets.begin(); i != m_assistTargets.end(); i++)
{
if(!(*i)->isAlive())
{
continue;
}
cur = (*i)->GetUInt32Value(UNIT_FIELD_HEALTH);
max = (*i)->GetUInt32Value(UNIT_FIELD_MAXHEALTH);
healthPercent = float(cur) / float(max);
if(healthPercent <= sp->floatMisc1) // Heal ourselves cause we got too low HP
{
m_Unit->SetUInt64Value(UNIT_FIELD_TARGET, (*i)->GetGUID());
return (*i); // heal Assist Target which has low HP
}
}
}
if(sp->spellType == STYPE_BUFF)
{
m_Unit->SetUInt64Value(UNIT_FIELD_TARGET, 0);
return m_Unit;
}
}
return GetMostHated();
}
bool AIInterface::FindFriends(float dist)
{
if( m_Unit->GetMapMgr() == NULL )
return false;
bool result = false;
TargetMap::iterator it;
std::set<Object*>::iterator itr;
Unit *pUnit;
m_Unit->AquireInrangeLock(); //make sure to release lock before exit function !
for( itr = m_Unit->GetInRangeSetBegin(); itr != m_Unit->GetInRangeSetEnd(); itr++ )
{
if(!(*itr) || (*itr)->GetTypeId() != TYPEID_UNIT)
continue;
pUnit = static_cast<Unit*>((*itr));
if(!pUnit->isAlive())
continue;
if(pUnit->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE))
{
continue;
}
if(pUnit->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_ATTACKABLE_9))
{
continue;
}
if( isCombatSupport( m_Unit, pUnit ) )//Not sure
{
if( m_Unit->GetDistanceSq(pUnit) < dist)
{
if( m_assistTargets.count( pUnit ) == 0 )
{
result = true;
m_assistTargets.insert(pUnit);
}
LockAITargets(true);
for(it = m_aiTargets.begin(); it != m_aiTargets.end(); ++it)
{
Unit *ai_t = m_Unit->GetMapMgr()->GetUnit( it->first );
if( ai_t && pUnit->GetAIInterface() )
pUnit->GetAIInterface()->AttackReaction( ai_t, 1, 0 );
}
LockAITargets(false);
}
}
}
m_Unit->ReleaseInrangeLock();
// check if we're a civillan, in which case summon guards on a despawn timer
uint8 civilian = (((Creature*)m_Unit)->GetCreatureInfo()) ? (((Creature*)m_Unit)->GetCreatureInfo()->Civilian) : 0;
uint32 family = (((Creature*)m_Unit)->GetCreatureInfo()) ? (((Creature*)m_Unit)->GetCreatureInfo()->Type) : 0;
if(family == HUMANOID && civilian && getMSTime() > m_guardTimer && !IS_INSTANCE(m_Unit->GetMapId()))
{
m_guardTimer = getMSTime() + 15000;
uint16 AreaId = m_Unit->GetMapMgr()->GetAreaID(m_Unit->GetPositionX(),m_Unit->GetPositionY());
AreaTable * at = dbcArea.LookupEntry(AreaId);
if(!at)
return result;
ZoneGuardEntry * zoneSpawn = ZoneGuardStorage.LookupEntry(at->ZoneId);
if(!zoneSpawn) return result;
uint32 team = 1; // horde default
if(isAlliance(m_Unit))
team = 0;
uint32 guardid = zoneSpawn->AllianceEntry;
if(team == 1) guardid = zoneSpawn->HordeEntry;
if(!guardid) return result;
CreatureInfo * ci = CreatureNameStorage.LookupEntry(guardid);
if(!ci)
return result;
float x = m_Unit->GetPositionX() + (float)( (float)(rand() % 150 + 100) / 1000.0f );
float y = m_Unit->GetPositionY() + (float)( (float)(rand() % 150 + 100) / 1000.0f );
float z;
if (sWorld.Collision) {
z = CollideInterface.GetHeight(m_Unit->GetMapId(), x, y, m_Unit->GetPositionZ() + 2.0f);
if( z == NO_WMO_HEIGHT )
z = m_Unit->GetMapMgr()->GetLandHeight(x, y);
if( fabs( z - m_Unit->GetPositionZ() ) > 10.0f )
z = m_Unit->GetPositionZ();
} else {
z = m_Unit->GetPositionZ();
float adt_z = m_Unit->GetMapMgr()->GetLandHeight(x, y);
if(fabs(z - adt_z) < 3)
z = adt_z;
}
CreatureProto * cp = CreatureProtoStorage.LookupEntry(guardid);
if(!cp) return result;
uint8 spawned = 0;
std::set<Player*>::iterator hostileItr = m_Unit->GetInRangePlayerSetBegin();
for(; hostileItr != m_Unit->GetInRangePlayerSetEnd(); hostileItr++)
{
if(spawned >= 3)
break;
if(!isHostile(*hostileItr, m_Unit))
continue;
if (spawned == 0)
{
uint32 languageid = (team == 0) ? LANG_COMMON : LANG_ORCISH;
m_Unit->SendChatMessage(CHAT_MSG_MONSTER_SAY, languageid, "Guards!");
}
Creature * guard = m_Unit->GetMapMgr()->CreateCreature(guardid);
guard->Load(cp, x, y, z);
guard->SetInstanceID(m_Unit->GetInstanceID());
guard->SetZoneId(m_Unit->GetZoneId());
guard->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP); /* shitty DBs */
guard->m_noRespawn=true;
if(guard->CanAddToWorld())
{
uint32 t = RandomUInt(8)*1000;
if(t==0)
guard->PushToWorld(m_Unit->GetMapMgr());
else
sEventMgr.AddEvent(guard,&Creature::AddToWorld, m_Unit->GetMapMgr(), EVENT_UNK, t, 1, 0);
}
else
{
guard->SafeDelete();
return result;
}
sEventMgr.AddEvent(guard, &Creature::SetGuardWaypoints, EVENT_UNK, 10000, 1,0);
sEventMgr.AddEvent(guard, &Creature::SafeDelete, EVENT_CREATURE_SAFE_DELETE, 60*5*1000, 1,EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT);
spawned++;
}
}
return result;
}
float AIInterface::_CalcAggroRange(Unit* target)
{
//float baseAR = 15.0f; // Base Aggro Range
// -8 -7 -6 -5 -4 -3 -2 -1 0 +1 +2 +3 +4 +5 +6 +7 +8
//float baseAR[17] = {29.0f, 27.5f, 26.0f, 24.5f, 23.0f, 21.5f, 20.0f, 18.5f, 17.0f, 15.5f, 14.0f, 12.5f, 11.0f, 9.5f, 8.0f, 6.5f, 5.0f};
float baseAR[17] = {19.0f, 18.5f, 18.0f, 17.5f, 17.0f, 16.5f, 16.0f, 15.5f, 15.0f, 14.5f, 12.0f, 10.5f, 8.5f, 7.5f, 6.5f, 6.5f, 5.0f};
// Lvl Diff -8 -7 -6 -5 -4 -3 -2 -1 +0 +1 +2 +3 +4 +5 +6 +7 +8
// Arr Pos 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int8 lvlDiff = static_cast<int8>(target->getLevel() - m_Unit->getLevel());
uint8 realLvlDiff = lvlDiff;
if(lvlDiff > 8)
{
lvlDiff = 8;
}
if(lvlDiff < -8)
{
lvlDiff = -8;
}
if(!((Creature*)m_Unit)->CanSee(target))
return 0;
float AggroRange = baseAR[lvlDiff + 8];
if(realLvlDiff > 8)
{
AggroRange += AggroRange * ((lvlDiff - 8) * 5 / 100);
}
// Multiply by elite value
if(m_Unit->IsCreature() && ((Creature*)m_Unit)->GetCreatureInfo() && ((Creature*)m_Unit)->GetCreatureInfo()->Rank > 0)
AggroRange *= (((Creature*)m_Unit)->GetCreatureInfo()->Rank) * 1.50f;
if(AggroRange > 40.0f) // cap at 40.0f
{
AggroRange = 40.0f;
}
/* //printf("aggro range: %f , stealthlvl: %d , detectlvl: %d\n",AggroRange,target->GetStealthLevel(),m_Unit->m_stealthDetectBonus);
if(! ((Creature*)m_Unit)->CanSee(target))
{
AggroRange =0;
// AggroRange *= ( 100.0f - (target->m_stealthLevel - m_Unit->m_stealthDetectBonus)* 20.0f ) / 100.0f;
}
*/
// SPELL_AURA_MOD_DETECT_RANGE
int32 modDetectRange = target->getDetectRangeMod(m_Unit->GetGUID());
AggroRange += modDetectRange;
if(target->IsPlayer())
AggroRange += static_cast< Player* >( target )->DetectedRange;
if(AggroRange < 3.0f)
{
AggroRange = 3.0f;
}
if(AggroRange > 40.0f) // cap at 40.0f
{
AggroRange = 40.0f;
}
return (AggroRange*AggroRange);
}
void AIInterface::_CalcDestinationAndMove(Unit *target, float dist)
{
if(!m_canMove || m_Unit->IsStunned())
{
StopMovement(0); //Just Stop
return;
}
if( target && ( target->GetTypeId() == TYPEID_UNIT || target->GetTypeId() == TYPEID_PLAYER) )
{
#ifdef HACKY_SERVER_CLIENT_POS_SYNC
moved_for_attack = true;
#endif
float ResX = target->GetPositionX();
float ResY = target->GetPositionY();
//avoid eating bandwidth with useless movement packets when target did not move since last position
//this will work since it turned into a common mith that when you pull mob you should not move :D
if( abs(m_last_target_x - ResX) < DISTANCE_TO_SMALL_TO_WALK
&& abs(m_last_target_y - ResY) < DISTANCE_TO_SMALL_TO_WALK && m_creatureState == MOVING)
return;
m_last_target_x = ResX;
m_last_target_y = ResY;
float ResZ = target->GetPositionZ();
float angle = m_Unit->calcAngle(m_Unit->GetPositionX(), m_Unit->GetPositionY(), ResX, ResY) * float(M_PI) / 180.0f;
float x = dist * cosf(angle);
float y = dist * sinf(angle);
if(target->GetTypeId() == TYPEID_PLAYER && static_cast< Player* >( target )->m_isMoving )
{
// cater for moving player vector based on orientation
x -= cosf(target->GetOrientation());
y -= sinf(target->GetOrientation());
}
m_nextPosX = ResX - x;
m_nextPosY = ResY - y;
m_nextPosZ = ResZ;
}
else
{
target = NULL;
m_nextPosX = m_Unit->GetPositionX();
m_nextPosY = m_Unit->GetPositionY();
m_nextPosZ = m_Unit->GetPositionZ();
}
/*
if (sWorld.Collision) {
float target_land_z=0.0f;
if( m_Unit->GetMapMgr() != NULL )
{
if(m_moveFly != true)
{
target_land_z = CollideInterface.GetHeight(m_Unit->GetMapId(), m_nextPosX, m_nextPosY, m_nextPosZ + 2.0f);
if( target_land_z == NO_WMO_HEIGHT )
target_land_z = m_Unit->GetMapMgr()->GetLandHeight(m_nextPosX, m_nextPosY);
}
}
if (m_nextPosZ > m_Unit->GetMapMgr()->GetWaterHeight(m_nextPosX, m_nextPosY) && target_land_z != 0.0f)
m_nextPosZ=target_land_z;
}
*/
float dx = m_nextPosX - m_Unit->GetPositionX();
float dy = m_nextPosY - m_Unit->GetPositionY();
if(dy != 0.0f)
{
float angle = atan2(dx, dy);
m_Unit->SetOrientation(angle);
}
if(m_creatureState != MOVING)
UpdateMove();
}
float AIInterface::_CalcCombatRange(Unit* target, bool ranged)
{
if(!target)
{
return 0;
}
float range = 0.0f;
float rang = 0.0f;
if(ranged)
{
rang = 5.0f;
}
float selfreach = m_Unit->GetFloatValue(UNIT_FIELD_COMBATREACH);
float targetradius;
// targetradius = target->GetFloatValue(UNIT_FIELD_BOUNDINGRADIUS); //this is plain wrong. Represents i have no idea what :)
targetradius = target->GetModelHalfSize();
float selfradius;
// selfradius = m_Unit->GetFloatValue(UNIT_FIELD_BOUNDINGRADIUS); //this is plain wrong. Represents i have no idea what :)
selfradius = m_Unit->GetModelHalfSize();
// float targetscale = target->GetFloatValue(OBJECT_FIELD_SCALE_X);
// float selfscale = m_Unit->GetFloatValue(OBJECT_FIELD_SCALE_X);
// range = ((((targetradius*targetradius)*targetscale) + selfreach) + ((selfradius*selfscale) + rang));
range = targetradius + selfreach + selfradius + rang;
// if(range > 28.29f) range = 28.29f;
return range;
}
float AIInterface::_CalcDistanceFromHome()
{
if (m_AIType == AITYPE_PET)
{
return m_Unit->GetDistanceSq(m_PetOwner);
}
else if(m_Unit->GetTypeId() == TYPEID_UNIT)
{
if(m_returnX !=0.0f && m_returnY != 0.0f)
{
return m_Unit->GetDistanceSq(m_returnX,m_returnY,m_returnZ);
}
}
return 0.0f;
}
/************************************************************************************************************
SendMoveToPacket:
Comments: Some comments on the SMSG_MONSTER_MOVE packet:
the uint8 field:
0: Default known
1: Don't move known
2: there is an extra 3 floats, also known as a vector unknown
3: there is an extra uint64 most likely a guid. unknown
4: there is an extra float that causes the orientation to be set. known
note: when this field is 1.
there is no need to send the next 3 uint32's as they are'nt used by the client
the MoveFlags:
0x00000000 - Walk
0x00000100 - Run
0x00000200 - Fly
some comments on that 0x00000300 - Fly = 0x00000100 | 0x00000200
waypoints:
TODO.... as they somehow seemed to be changed long time ago..
*************************************************************************************************************/
void AIInterface::SendMoveToPacket(float toX, float toY, float toZ, float toO, uint32 time, uint32 MoveFlags)
{
//this should NEVER be called directly !!!!!!
//use MoveTo()
#ifndef USING_BIG_ENDIAN
StackWorldPacket<60> data(SMSG_MONSTER_MOVE);
#else
WorldPacket data(SMSG_MONSTER_MOVE, 60);
#endif
data << m_Unit->GetNewGUID();
data << m_Unit->GetPositionX() << m_Unit->GetPositionY() << m_Unit->GetPositionZ();
data << getMSTime();
// Check if we have an orientation
if(toO != 0.0f)
{
data << uint8(4);
data << toO;
} else {
data << uint8(0);
}
data << MoveFlags;
data << time;
data << uint32(1); // 1 waypoint
data << toX << toY << toZ;
#ifndef ENABLE_COMPRESSED_MOVEMENT_FOR_CREATURES
bool self = m_Unit->GetTypeId() == TYPEID_PLAYER;
m_Unit->SendMessageToSet( &data, self );
#else
if( m_Unit->GetTypeId() == TYPEID_PLAYER )
static_cast<Player*>(m_Unit)->GetSession()->SendPacket(&data);
for(set<Player*>::iterator itr = m_Unit->GetInRangePlayerSetBegin(); itr != m_Unit->GetInRangePlayerSetEnd(); ++itr)
{
if( (*itr)->GetPositionNC().Distance2DSq( m_Unit->GetPosition() ) >= World::m_movementCompressThresholdCreatures )
(*itr)->AppendMovementData( SMSG_MONSTER_MOVE, data.GetSize(), (const uint8*)data.GetBufferPointer() );
else
(*itr)->GetSession()->SendPacket(&data);
}
#endif
}
/*
void AIInterface::SendMoveToSplinesPacket(std::list<Waypoint> wp, bool run)
{
if(!m_canMove)
{
return;
}
WorldPacket data;
uint8 DontMove = 0;
uint32 travelTime = 0;
for(std::list<Waypoint>::iterator i = wp.begin(); i != wp.end(); i++)
{
travelTime += i->time;
}
data.Initialize( SMSG_MONSTER_MOVE );
data << m_Unit->GetNewGUID();
data << m_Unit->GetPositionX() << m_Unit->GetPositionY() << m_Unit->GetPositionZ();
data << getMSTime();
data << uint8(DontMove);
data << uint32(run ? 0x00000100 : 0x00000000);
data << travelTime;
data << (uint32)wp.size();
for(std::list<Waypoint>::iterator i = wp.begin(); i != wp.end(); i++)
{
data << i->x;
data << i->y;
data << i->z;
}
m_Unit->SendMessageToSet( &data, false );
}
*/
bool AIInterface::StopMovement(uint32 time)
{
m_moveTimer = time; //set pause after stopping
m_creatureState = STOPPED;
m_destinationX = m_destinationY = m_destinationZ = 0;
m_nextPosX = m_nextPosY = m_nextPosZ = 0;
m_timeMoved = 0;
m_timeToMove = 0;
WorldPacket data(26);
data.SetOpcode(SMSG_MONSTER_MOVE);
data << m_Unit->GetNewGUID();
data << m_Unit->GetPositionX() << m_Unit->GetPositionY() << m_Unit->GetPositionZ();
data << getMSTime();
data << uint8(1); // "DontMove = 1"
m_Unit->SendMessageToSet( &data, false );
return true;
}
void AIInterface::MoveTo(float x, float y, float z, float o)
{
m_sourceX = m_Unit->GetPositionX();
m_sourceY = m_Unit->GetPositionY();
m_sourceZ = m_Unit->GetPositionZ();
if(!m_canMove || m_Unit->IsStunned())
{
StopMovement(0); //Just Stop
return;
}
m_nextPosX = x;
m_nextPosY = y;
m_nextPosZ = z;
/* //Andy
#ifdef COLLISION
float target_land_z=0.0f;
if( m_Unit->GetMapMgr() != NULL )
{
if(m_moveFly != true)
{
target_land_z = CollideInterface.GetHeight(m_Unit->GetMapId(), m_nextPosX, m_nextPosY, m_nextPosZ + 2.0f);
if( target_land_z == NO_WMO_HEIGHT )
target_land_z = m_Unit->GetMapMgr()->GetLandHeight(m_nextPosX, m_nextPosY);
}
}
if (m_nextPosZ > m_Unit->GetMapMgr()->GetWaterHeight(m_nextPosX, m_nextPosY) && target_land_z != 0.0f)
m_nextPosZ=target_land_z;
#endif*/
if ( m_creatureState != MOVING )
UpdateMove();
}
bool AIInterface::IsFlying()
{
if(m_moveFly)
return true;
/*float z = m_Unit->GetMapMgr()->GetLandHeight(m_Unit->GetPositionX(), m_Unit->GetPositionY());
if(z)
{
if(m_Unit->GetPositionZ() >= (z + 1.0f)) //not on ground? Oo
{
return true;
}
}
return false;*/
if( m_Unit->GetTypeId() == TYPEID_PLAYER )
return static_cast< Player* >( m_Unit )->FlyCheat;
return false;
}
uint32 AIInterface::getMoveFlags()
{
uint32 MoveFlags = 0;
if(m_moveFly == true) //Fly
{
m_flySpeed = m_Unit->m_flySpeed*0.001f;
MoveFlags = 0x300;
}
else if(m_moveSprint == true) //Sprint
{
m_runSpeed = (m_Unit->m_runSpeed+5.0f)*0.001f;
MoveFlags = 0x100;
}
else if(m_moveRun == true) //Run
{
m_runSpeed = m_Unit->m_runSpeed*0.001f;
MoveFlags = 0x100;
}
/* else //Walk
{
m_runSpeed = m_Unit->m_walkSpeed*0.001f;
MoveFlags = 0x000;
}*/
m_walkSpeed = m_Unit->m_walkSpeed*0.001f;//move distance per ms time
return MoveFlags;
}
void AIInterface::UpdateMove()
{
//this should NEVER be called directly !!!!!!
//use MoveTo()
float distance = m_Unit->CalcDistance(m_nextPosX,m_nextPosY,m_nextPosZ);
if(distance < DISTANCE_TO_SMALL_TO_WALK)
return; //we don't want little movements here and there
m_destinationX = m_nextPosX;
m_destinationY = m_nextPosY;
m_destinationZ = m_nextPosZ;
/*if(m_moveFly != true)
{
if(m_Unit->GetMapMgr())
{
float adt_Z = m_Unit->GetMapMgr()->GetLandHeight(m_destinationX, m_destinationY);
if(fabsf(adt_Z - m_destinationZ) < 3.0f)
m_destinationZ = adt_Z;
}
}*/
//this prevents updatemovement working on this function
//m_nextPosX = m_nextPosY = m_nextPosZ = 0;
uint32 moveTime;
/* #ifdef INHERIT_FOLLOWED_UNIT_SPEED vojta - this is pointless and we dont need it anymore
if( UnitToFollow )
{
// moveTime = (uint32) (distance * 1000 / UnitToFollow->m_runSpeed ); //i wonder if runpeed can ever frop to 0
//life sucks, due to calculations the pet will move slower with corect formulas. We add some catch-up speed
moveTime = (uint32) (distance * 1000 / ( UnitToFollow->m_runSpeed * sqrt( distance ) ) ); //i wonder if runpeed can ever frop to 0
}
#endif */
if(m_moveFly)
moveTime = (uint32) (distance / m_flySpeed);
else if(m_moveRun)
moveTime = (uint32) (distance / m_runSpeed);
else moveTime = (uint32) (distance / m_walkSpeed);
m_totalMoveTime = moveTime;
if(m_Unit->GetTypeId() == TYPEID_UNIT)
{
Creature *creature = static_cast<Creature*>(m_Unit);
// check if we're returning to our respawn location. if so, reset back to default
// orientation
if(creature->GetSpawnX() == m_destinationX &&
creature->GetSpawnY() == m_destinationY)
{
float o = creature->GetSpawnO();
creature->SetOrientation(o);
} else {
// Calculate the angle to our next position
float dx = (float)m_destinationX - m_Unit->GetPositionX();
float dy = (float)m_destinationY - m_Unit->GetPositionY();
if(dy != 0.0f)
{
float angle = atan2(dy, dx);
m_Unit->SetOrientation(angle);
}
}
}
if (m_Unit->GetCurrentSpell() == NULL)
SendMoveToPacket(m_destinationX, m_destinationY, m_destinationZ, m_Unit->GetOrientation(), moveTime, getMoveFlags());
m_timeToMove = moveTime;
m_timeMoved = 0;
if(m_moveTimer == 0)
{
m_moveTimer = UNIT_MOVEMENT_INTERPOLATE_INTERVAL; // update every few msecs
}
m_creatureState = MOVING;
}
void AIInterface::SendCurrentMove(Player* plyr/*uint64 guid*/)
{
if(m_destinationX == 0.0f && m_destinationY == 0.0f && m_destinationZ == 0.0f) return; //invalid move
ByteBuffer *splineBuf = new ByteBuffer(20*4);
*splineBuf << uint32(0); // spline flags
*splineBuf << uint32((m_totalMoveTime - m_timeToMove)+m_moveTimer); //Time Passed (start Position) //should be generated/save
*splineBuf << uint32(m_totalMoveTime); //Total Time //should be generated/save
*splineBuf << uint32(0); //Unknown
*splineBuf << uint32(4); //Spline Count // lets try this
*splineBuf << m_sourceX << m_sourceY << m_sourceZ;
*splineBuf << m_Unit->GetPositionX() << m_Unit->GetPositionY() << m_Unit->GetPositionZ();
*splineBuf << m_destinationX << m_destinationY << m_destinationZ;
*splineBuf << m_destinationX << m_destinationY << m_destinationZ;
*splineBuf << m_destinationX << m_destinationY << m_destinationZ;
plyr->AddSplinePacket(m_Unit->GetGUID(), splineBuf);
//This should only be called by Players AddInRangeObject() ONLY
//using guid cuz when i atempted to use pointer the player was deleted when this event was called some times
//Player* plyr = World::GetPlayer(guid);
//if(!plyr) return;
/*if(m_destinationX == 0.0f && m_destinationY == 0.0f && m_destinationZ == 0.0f) return; //invalid move
uint32 moveTime = m_timeToMove-m_timeMoved;
//uint32 moveTime = (m_timeToMove-m_timeMoved)+m_moveTimer;
WorldPacket data(50);
data.SetOpcode( SMSG_MONSTER_MOVE );
data << m_Unit->GetNewGUID();
data << m_Unit->GetPositionX() << m_Unit->GetPositionY() << m_Unit->GetPositionZ();
data << getMSTime();
data << uint8(0);
data << getMoveFlags();
//float distance = m_Unit->CalcDistance(m_destinationX, m_destinationY, m_destinationZ);
//uint32 moveTime = (uint32) (distance / m_runSpeed);
data << moveTime;
data << uint32(1); //Number of Waypoints
data << m_destinationX << m_destinationY << m_destinationZ;
plyr->GetSession()->SendPacket(&data);*/
}
bool AIInterface::setInFront(Unit* target) // not the best way to do it, though
{
//angle the object has to face
float angle = m_Unit->calcAngle(m_Unit->GetPositionX(), m_Unit->GetPositionY(), target->GetPositionX(), target->GetPositionY() );
//Change angle slowly 2000ms to turn 180 deg around
if(angle > 180) angle += 90;
else angle -= 90; //angle < 180
m_Unit->getEasyAngle(angle);
//Convert from degrees to radians (180 deg = PI rad)
float orientation = angle / float(180 / M_PI);
//Update Orentation Server Side
m_Unit->SetPosition(m_Unit->GetPositionX(), m_Unit->GetPositionY(), m_Unit->GetPositionZ(), orientation);
return m_Unit->isInFront(target);
}
bool AIInterface::addWayPoint(WayPoint* wp)
{
if(!m_waypoints)
m_waypoints = new WayPointMap ;
if(!wp)
return false;
if(wp->id <= 0)
return false; //not valid id
if(m_waypoints->size() <= wp->id)
m_waypoints->resize(wp->id+1);
if((*m_waypoints)[wp->id] == NULL)
{
(*m_waypoints)[wp->id] = wp;
return true;
}
return false;
}
void AIInterface::changeWayPointID(uint32 oldwpid, uint32 newwpid)
{
if(!m_waypoints)return;
if(newwpid <= 0)
return; //not valid id
if(newwpid > m_waypoints->size())
return; //not valid id
if(oldwpid > m_waypoints->size())
return;
if(newwpid == oldwpid)
return; //same spot
//already wp with that id ?
WayPoint* originalwp = getWayPoint(newwpid);
if(!originalwp)
return;
WayPoint* oldwp = getWayPoint(oldwpid);
if(!oldwp)
return;
oldwp->id = newwpid;
originalwp->id = oldwpid;
(*m_waypoints)[oldwp->id] = oldwp;
(*m_waypoints)[originalwp->id] = originalwp;
//SaveAll to db
saveWayPoints();
}
void AIInterface::deleteWayPoint(uint32 wpid)
{
if(!m_waypoints)return;
if(wpid <= 0)
return; //not valid id
if(wpid > m_waypoints->size())
return; //not valid id
WayPointMap new_waypoints;
uint32 newpid = 1;
for(WayPointMap::iterator itr = m_waypoints->begin(); itr != m_waypoints->end(); ++itr)
{
if((*itr) == NULL || (*itr)->id == wpid)
{
if((*itr) != NULL)
delete ((*itr));
continue;
}
new_waypoints.push_back(*itr);
}
m_waypoints->clear();
m_waypoints->push_back(NULL); // waypoint 0
for(WayPointMap::iterator itr = new_waypoints.begin(); itr != new_waypoints.end(); ++itr)
{
(*itr)->id = newpid++;
m_waypoints->push_back(*itr);
}
saveWayPoints();
}
bool AIInterface::showWayPoints(Player* pPlayer, bool Backwards)
{
if(!m_waypoints)
return false;
//wpid of 0 == all
WayPointMap::const_iterator itr;
if(m_WayPointsShowing == true)
return false;
m_WayPointsShowing = true;
WayPoint* wp = NULL;
for (itr = m_waypoints->begin(); itr != m_waypoints->end(); itr++)
{
if( (*itr) != NULL )
{
wp = *itr;
//Create
Creature* pWayPoint = new Creature((uint64)HIGHGUID_TYPE_WAYPOINT << 32 | wp->id);
pWayPoint->CreateWayPoint(wp->id,pPlayer->GetMapId(),wp->x,wp->y,wp->z,0);
pWayPoint->SetUInt32Value(OBJECT_FIELD_ENTRY, 300000);
pWayPoint->SetFloatValue(OBJECT_FIELD_SCALE_X, 0.5f);
if(Backwards)
{
uint32 DisplayID = (wp->backwardskinid == 0)? GetUnit()->GetUInt32Value(UNIT_FIELD_NATIVEDISPLAYID) : wp->backwardskinid;
pWayPoint->SetUInt32Value(UNIT_FIELD_DISPLAYID, DisplayID);
pWayPoint->SetUInt32Value(UNIT_NPC_EMOTESTATE, wp->backwardemoteid);
}
else
{
uint32 DisplayID = (wp->forwardskinid == 0)? GetUnit()->GetUInt32Value(UNIT_FIELD_NATIVEDISPLAYID) : wp->forwardskinid;
pWayPoint->SetUInt32Value(UNIT_FIELD_DISPLAYID, DisplayID);
pWayPoint->SetUInt32Value(UNIT_NPC_EMOTESTATE, wp->forwardemoteid);
}
pWayPoint->SetUInt32Value(UNIT_FIELD_LEVEL, wp->id);
pWayPoint->SetUInt32Value(UNIT_NPC_FLAGS, 0);
pWayPoint->SetUInt32Value(UNIT_FIELD_AURA+32, 8326); //invisable & deathworld look
pWayPoint->SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE , pPlayer->GetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE));
pWayPoint->SetUInt32Value(UNIT_FIELD_HEALTH, 1);
pWayPoint->SetUInt32Value(UNIT_FIELD_MAXHEALTH, 1);
pWayPoint->SetUInt32Value(UNIT_FIELD_STAT0, wp->flags);
//Create on client
ByteBuffer buf(2500);
uint32 count = pWayPoint->BuildCreateUpdateBlockForPlayer(&buf, pPlayer);
pPlayer->PushCreationData(&buf, count);
//root the object
WorldPacket data1;
data1.Initialize(SMSG_FORCE_MOVE_ROOT);
data1 << pWayPoint->GetNewGUID();
pPlayer->GetSession()->SendPacket( &data1 );
//Cleanup
delete pWayPoint;
}
}
return true;
}
bool AIInterface::hideWayPoints(Player* pPlayer)
{
if(!m_waypoints)
return false;
//wpid of 0 == all
if(m_WayPointsShowing != true) return false;
m_WayPointsShowing = false;
WayPointMap::const_iterator itr;
// slightly better way to do this
uint64 guid;
for (itr = m_waypoints->begin(); itr != m_waypoints->end(); itr++)
{
if( (*itr) != NULL )
{
// avoid C4293
guid = ((uint64)HIGHGUID_TYPE_WAYPOINT << 32) | (*itr)->id;
WoWGuid wowguid(guid);
pPlayer->PushOutOfRange(wowguid);
}
}
return true;
}
bool AIInterface::saveWayPoints()
{
if(!m_waypoints)return false;
if(!GetUnit()) return false;
if(GetUnit()->GetTypeId() != TYPEID_UNIT) return false;
WorldDatabase.Execute("DELETE FROM creature_waypoints WHERE spawnid = %u", ((Creature*)GetUnit())->GetSQL_id());
WayPointMap::const_iterator itr;
WayPoint* wp = NULL;
std::stringstream ss;
for (itr = m_waypoints->begin(); itr != m_waypoints->end(); itr++)
{
if((*itr) == NULL)
continue;
wp = (*itr);
//Save
ss.str("");
ss << "REPLACE INTO creature_waypoints ";
ss << "(spawnid,waypointid,position_x,position_y,position_z,waittime,flags,forwardemoteoneshot,forwardemoteid,backwardemoteoneshot,backwardemoteid,forwardskinid,backwardskinid) VALUES (";
ss << ((Creature*)GetUnit())->GetSQL_id() << ", ";
ss << wp->id << ", ";
ss << wp->x << ", ";
ss << wp->y << ", ";
ss << wp->z << ", ";
ss << wp->waittime << ", ";
ss << wp->flags << ", ";
ss << wp->forwardemoteoneshot << ", ";
ss << wp->forwardemoteid << ", ";
ss << wp->backwardemoteoneshot << ", ";
ss << wp->backwardemoteid << ", ";
ss << wp->forwardskinid << ", ";
ss << wp->backwardskinid << ")\0";
WorldDatabase.Query( ss.str().c_str() );
}
return true;
}
void AIInterface::deleteWaypoints()
{
if(!m_waypoints)
return;
for(WayPointMap::iterator itr = m_waypoints->begin(); itr != m_waypoints->end(); ++itr)
{
if((*itr) != NULL)
delete (*itr);
}
m_waypoints->clear();
}
WayPoint* AIInterface::getWayPoint(uint32 wpid)
{
if(!m_waypoints)return NULL;
if(wpid >= m_waypoints->size())
return NULL; //not valid id
/*WayPointMap::const_iterator itr = m_waypoints->find( wpid );
if( itr != m_waypoints->end( ) )
return itr->second;*/
return m_waypoints->at(wpid);
}
void AIInterface::_UpdateMovement(uint32 p_time)
{
if(!m_Unit->isAlive())
{
StopMovement(0);
return;
}
//move after finishing our current spell
if ( m_Unit->GetCurrentSpell() != NULL )
return;
uint32 timediff = 0;
if(m_moveTimer > 0)
{
if(p_time >= m_moveTimer)
{
timediff = p_time - m_moveTimer;
m_moveTimer = 0;
}
else
m_moveTimer -= p_time;
}
if(m_timeToMove > 0)
{
m_timeMoved = m_timeToMove <= p_time + m_timeMoved ? m_timeToMove : p_time + m_timeMoved;
}
if(m_creatureState == MOVING)
{
if(!m_moveTimer)
{
if(m_timeMoved == m_timeToMove) //reached destination
{
/* if(m_fastMove)
{
m_Unit->UpdateSpeed();
m_fastMove = false;
}*/
if(m_moveType == MOVEMENTTYPE_WANTEDWP)//We reached wanted wp stop now
m_moveType = MOVEMENTTYPE_DONTMOVEWP;
float wayO = 0.0f;
if((GetWayPointsCount() != 0) && (m_AIState == STATE_IDLE || m_AIState == STATE_SCRIPTMOVE)) //if we attacking don't use wps
{
WayPoint* wp = getWayPoint(getCurrentWaypoint());
if(wp)
{
CALL_SCRIPT_EVENT(m_Unit, OnReachWP)(wp->id, !m_moveBackward);
if(((Creature*)m_Unit)->has_waypoint_text)
objmgr.HandleMonsterSayEvent(((Creature*)m_Unit), MONSTER_SAY_EVENT_RANDOM_WAYPOINT);
//Lets face to correct orientation
wayO = wp->o;
m_moveTimer = wp->waittime; //wait before next move
if(!m_moveBackward)
{
if(wp->forwardemoteoneshot)
{
GetUnit()->Emote(EmoteType(wp->forwardemoteid));
}
else
{
if(GetUnit()->GetUInt32Value(UNIT_NPC_EMOTESTATE) != wp->forwardemoteid)
{
GetUnit()->SetUInt32Value(UNIT_NPC_EMOTESTATE, wp->forwardemoteid);
}
}
}
else
{
if(wp->backwardemoteoneshot)
{
GetUnit()->Emote(EmoteType(wp->backwardemoteid));
}
else
{
if(GetUnit()->GetUInt32Value(UNIT_NPC_EMOTESTATE) != wp->backwardemoteid)
{
GetUnit()->SetUInt32Value(UNIT_NPC_EMOTESTATE, wp->backwardemoteid);
}
}
}
}
else
m_moveTimer = RandomUInt(m_moveRun ? 5000 : 10000); // wait before next move
}
m_creatureState = STOPPED;
m_moveSprint = false;
if(m_MovementType == MOVEMENTTYPE_DONTMOVEWP)
m_Unit->SetPosition(m_destinationX, m_destinationY, m_destinationZ, wayO, true);
else
m_Unit->SetPosition(m_destinationX, m_destinationY, m_destinationZ, m_Unit->GetOrientation(), true);
m_destinationX = m_destinationY = m_destinationZ = 0;
m_timeMoved = 0;
m_timeToMove = 0;
}
else
{
//Move Server Side Update
float q = (float)m_timeMoved / (float)m_timeToMove;
float x = m_Unit->GetPositionX() + (m_destinationX - m_Unit->GetPositionX()) * q;
float y = m_Unit->GetPositionY() + (m_destinationY - m_Unit->GetPositionY()) * q;
float z = m_Unit->GetPositionZ() + (m_destinationZ - m_Unit->GetPositionZ()) * q;
//Andy
if (sWorld.Collision) {
float target_land_z=0.0f;
if( m_Unit->GetMapMgr() != NULL )
{
if(m_moveFly != true)
{
target_land_z = CollideInterface.GetHeight(m_Unit->GetMapId(), x, y, z + 2.0f);
if ( target_land_z == NO_WMO_HEIGHT )
{
target_land_z = m_Unit->GetMapMgr()->GetLandHeight(x, y);
if ( target_land_z == 999999.0f )
target_land_z = z;
}
}
if ( z > m_Unit->GetMapMgr()->GetWaterHeight( m_nextPosX, m_nextPosY ) && target_land_z != 0.0f )
z = target_land_z;
}
}
m_Unit->SetPosition(x, y, z, m_Unit->GetOrientation());
m_timeToMove -= m_timeMoved;
m_timeMoved = 0;
m_moveTimer = (UNIT_MOVEMENT_INTERPOLATE_INTERVAL < m_timeToMove) ? UNIT_MOVEMENT_INTERPOLATE_INTERVAL : m_timeToMove;
}
//**** Movement related stuff that should be done after a move update (Keeps Client and Server Synced) ****//
//**** Process the Pending Move ****//
if(m_nextPosX != 0.0f && m_nextPosY != 0.0f)
{
UpdateMove();
}
}
}
else if(m_creatureState == STOPPED && (m_AIState == STATE_IDLE || m_AIState == STATE_SCRIPTMOVE) && !m_moveTimer && !m_timeToMove && UnitToFollow == NULL) //creature is stopped and out of Combat
{
if(sWorld.getAllowMovement() == false) //is creature movement enabled?
return;
if(m_Unit->GetUInt32Value(UNIT_FIELD_DISPLAYID) == 5233) //if Spirit Healer don't move
return;
// do we have a formation?
if(m_formationLinkSqlId != 0)
{
if(!m_formationLinkTarget)
{
// haven't found our target yet
Creature * c = static_cast<Creature*>(m_Unit);
if(!c->haslinkupevent)
{
// register linkup event
c->haslinkupevent = true;
sEventMgr.AddEvent(c, &Creature::FormationLinkUp, m_formationLinkSqlId,
EVENT_CREATURE_FORMATION_LINKUP, 1000, 0,EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT);
}
}
else
{
// we've got a formation target, set unittofollow to this
UnitToFollow = m_formationLinkTarget;
FollowDistance = m_formationFollowDistance;
m_fallowAngle = m_formationFollowAngle;
}
}
if(UnitToFollow == 0)
{
// no formation, use waypoints
int destpoint = -1;
// If creature has no waypoints just wander aimlessly around spawnpoint
if(GetWayPointsCount()==0) //no waypoints
{
/* if(m_moveRandom)
{
if((rand()%10)==0)
{
float wanderDistance = rand()%4 + 2;
float wanderX = ((wanderDistance*rand()) / RAND_MAX) - wanderDistance / 2;
float wanderY = ((wanderDistance*rand()) / RAND_MAX) - wanderDistance / 2;
float wanderZ = 0; // FIX ME ( i dont know how to get apropriate Z coord, maybe use client height map data)
if(m_Unit->CalcDistance(m_Unit->GetPositionX(), m_Unit->GetPositionY(), m_Unit->GetPositionZ(), ((Creature*)m_Unit)->respawn_cord[0], ((Creature*)m_Unit)->respawn_cord[1], ((Creature*)m_Unit)->respawn_cord[2])>15)
{
//return home
MoveTo(((Creature*)m_Unit)->respawn_cord[0],((Creature*)m_Unit)->respawn_cord[1],((Creature*)m_Unit)->respawn_cord[2],false);
}
else
{
MoveTo(m_Unit->GetPositionX() + wanderX, m_Unit->GetPositionY() + wanderY, m_Unit->GetPositionZ() + wanderZ,false);
}
}
}
*/
return;
}
else //we do have waypoints
{
if(m_moveType == MOVEMENTTYPE_RANDOMWP) //is random move on if so move to a random waypoint
{
if(GetWayPointsCount() > 1)
destpoint = RandomUInt((uint32)GetWayPointsCount());
}
else if (m_moveType == MOVEMENTTYPE_CIRCLEWP) //random move is not on lets follow the path in circles
{
// 1 -> 10 then 1 -> 10
m_currentWaypoint++;
if (m_currentWaypoint > GetWayPointsCount()) m_currentWaypoint = 1; //Happens when you delete last wp seems to continue ticking
destpoint = m_currentWaypoint;
m_moveBackward = false;
}
else if(m_moveType == MOVEMENTTYPE_WANTEDWP)//Move to wanted wp
{
if(m_currentWaypoint)
{
if(GetWayPointsCount() > 0)
{
destpoint = m_currentWaypoint;
}
else
destpoint = -1;
}
}
else if(m_moveType == MOVEMENTTYPE_FORWARDTHANSTOP)// move to end, then stop
{
++m_currentWaypoint;
if(m_currentWaypoint > GetWayPointsCount())
{
//hmm maybe we should stop being path walker since we are waiting here anyway
destpoint = -1;
}
else
destpoint = m_currentWaypoint;
}
else if(m_moveType != MOVEMENTTYPE_QUEST && m_moveType != MOVEMENTTYPE_DONTMOVEWP)//4 Unused
{
// 1 -> 10 then 10 -> 1
if (m_currentWaypoint > GetWayPointsCount()) m_currentWaypoint = 1; //Happens when you delete last wp seems to continue ticking
if (m_currentWaypoint == GetWayPointsCount()) // Are we on the last waypoint? if so walk back
m_moveBackward = true;
if (m_currentWaypoint == 1) // Are we on the first waypoint? if so lets goto the second waypoint
m_moveBackward = false;
if (!m_moveBackward) // going 1..n
destpoint = ++m_currentWaypoint;
else // going n..1
destpoint = --m_currentWaypoint;
}
if(destpoint != -1)
{
WayPoint* wp = getWayPoint(destpoint);
if(wp)
{
if(!m_moveBackward)
{
if((wp->forwardskinid != 0) && (GetUnit()->GetUInt32Value(UNIT_FIELD_DISPLAYID) != wp->forwardskinid))
{
GetUnit()->SetUInt32Value(UNIT_FIELD_DISPLAYID, wp->forwardskinid);
GetUnit()->EventModelChange();
}
}
else
{
if((wp->backwardskinid != 0) && (GetUnit()->GetUInt32Value(UNIT_FIELD_DISPLAYID) != wp->backwardskinid))
{
GetUnit()->SetUInt32Value(UNIT_FIELD_DISPLAYID, wp->backwardskinid);
GetUnit()->EventModelChange();
}
}
m_moveFly = (wp->flags == 768) ? 1 : 0;
m_moveRun = (wp->flags == 256) ? 1 : 0;
MoveTo(wp->x, wp->y, wp->z, 0);
}
}
}
}
}
//Fear Code
if(m_AIState == STATE_FEAR && UnitToFear != NULL && m_creatureState == STOPPED)
{
if(getMSTime() > m_FearTimer) // Wait at point for x ms ;)
{
float Fx;
float Fy;
float Fz;
if( sWorld.DisableFearMovement )
{
if( m_Unit->GetMapId() == 529|| m_Unit->GetMapId() == 566 || m_Unit->GetMapId() == 489 || m_Unit->GetMapId() == 572 || m_Unit->GetMapId() == 562 || m_Unit->GetMapId() == 559 )
{
return;
}
}
// Calculate new angle to target.
float Fo = m_Unit->calcRadAngle(UnitToFear->GetPositionX(), UnitToFear->GetPositionY(), m_Unit->GetPositionX(), m_Unit->GetPositionY());
double fAngleAdd = RandomDouble(((M_PI/2) * 2)) - (M_PI/2);
Fo += (float)fAngleAdd;
float dist = m_Unit->CalcDistance(UnitToFear);
if(dist > 30.0f || (Rand(25) && dist > 10.0f)) // not too far or too close
{
if( m_Unit->GetMapId() == 572 || m_Unit->GetMapId() == 562 || m_Unit->GetMapId() == 559 ) //GET MAP ID
{
Fx = m_Unit->GetPositionX();
Fy = m_Unit->GetPositionY();
}
else
{
Fx = m_Unit->GetPositionX() - (RandomFloat(15.f)+5.0f)*cosf(Fo);
Fy = m_Unit->GetPositionY() - (RandomFloat(15.f)+5.0f)*sinf(Fo);
}
}
else
{
Fx = m_Unit->GetPositionX() + (RandomFloat(20.f)+5.0f)*cosf(Fo);
Fy = m_Unit->GetPositionY() + (RandomFloat(20.f)+5.0f)*sinf(Fo);
}
// Check if this point is in water.
float wl = m_Unit->GetMapMgr()->GetWaterHeight(Fx, Fy);
// uint8 wt = m_Unit->GetMapMgr()->GetWaterType(Fx, Fy);
if (sWorld.Collision) {
Fz = CollideInterface.GetHeight(m_Unit->GetMapId(), Fx, Fy, m_Unit->GetPositionZ() + 2.0f);
if( Fz == NO_WMO_HEIGHT )
Fz = m_Unit->GetMapMgr()->GetLandHeight(Fx, Fy);
else
{
if( CollideInterface.GetFirstPoint(m_Unit->GetMapId(), m_Unit->GetPositionX(), m_Unit->GetPositionY(), m_Unit->GetPositionZ() + 2.0f,
Fx, Fy, Fz + 2.0f, Fx, Fy, Fz, -1.0f) )
{
//Fz = CollideInterface.GetHeight(m_Unit->GetMapId(), Fx, Fy, m_Unit->GetPositionZ() + 2.0f);
}
}
if( fabs( m_Unit->GetPositionZ() - Fz ) > 10.0f ||
( wl != 0.0f && Fz < wl ) ) // in water
{
m_FearTimer=getMSTime() + 500;
}
else if( CollideInterface.CheckLOS(m_Unit->GetMapId(), m_Unit->GetPositionX(), m_Unit->GetPositionY(), m_Unit->GetPositionZ() + 2.0f, Fx, Fy, Fz) )
{
MoveTo(Fx, Fy, Fz, Fo);
m_FearTimer = m_totalMoveTime + getMSTime() + 400;
}
else
{
StopMovement(0);
}
} else {
Fz = m_Unit->GetMapMgr()->GetLandHeight(Fx, Fy);
if(fabs(m_Unit->GetPositionZ()-Fz) > 4 || (Fz != 0.0f && Fz < (wl-2.0f)))
m_FearTimer=getMSTime()+100;
else
{
MoveTo(Fx, Fy, Fz, Fo);
m_FearTimer = m_totalMoveTime + getMSTime() + 200;
}
}
}
}
// Wander AI movement code
if(m_AIState == STATE_WANDER && m_creatureState == STOPPED)
{
if(getMSTime() < m_WanderTimer) // is it time to move again?
return;
// calculate a random distance and angle to move
float wanderD = RandomFloat(2.0f) + 2.0f;
float wanderO = RandomFloat(6.283f);
float wanderX = m_Unit->GetPositionX() + wanderD * cosf(wanderO);
float wanderY = m_Unit->GetPositionY() + wanderD * sinf(wanderO);
if (sWorld.Collision) {
float wanderZ = CollideInterface.GetHeight(m_Unit->GetMapId(), wanderX, wanderY, m_Unit->GetPositionZ() + 2.0f);
float wanderZ2 = wanderZ;
if( wanderZ == NO_WMO_HEIGHT )
wanderZ = m_Unit->GetMapMgr()->GetLandHeight(wanderX, wanderY);
else
{
if( CollideInterface.GetFirstPoint(m_Unit->GetMapId(), m_Unit->GetPositionX(), m_Unit->GetPositionY(), m_Unit->GetPositionZ() + 2.0f,
wanderX, wanderY, wanderZ + 2.0f, wanderX, wanderY, wanderZ, -1.0f) )
{
//wanderZ = CollideInterface.GetHeight(m_Unit->GetMapId(), wanderX, wanderY, m_Unit->GetPositionZ() + 2.0f);
}
else
wanderZ = wanderZ2;
}
if( fabs( m_Unit->GetPositionZ() - wanderZ ) > 10.0f )
{
m_WanderTimer=getMSTime() + 1000;
}
else if(CollideInterface.CheckLOS(m_Unit->GetMapId(), m_Unit->GetPositionX(), m_Unit->GetPositionY(), m_Unit->GetPositionZ() + 2.0f, wanderX, wanderY, wanderZ))
{
m_Unit->SetOrientation(wanderO);
MoveTo(wanderX, wanderY, wanderZ, wanderO);
m_WanderTimer = getMSTime() + m_totalMoveTime + 300; // time till next move (+ pause)
}
else
{
StopMovement(0);
}
} else {
float wanderZ = m_Unit->GetMapMgr()->GetLandHeight(wanderX, wanderY);
// without these next checks we could fall through the "ground" (WMO) and get stuck
// wander won't work correctly in cities until we get some way to fix this and remove these checks
float currentZ = m_Unit->GetPositionZ();
float landZ = m_Unit->GetMapMgr()->GetLandHeight(m_Unit->GetPositionX(), m_Unit->GetPositionY());
if( currentZ > landZ + 1.0f // are we more than 1yd above ground? (possible WMO)
|| wanderZ < currentZ - 5.0f // is our destination land height too low? (possible WMO)
|| wanderZ > currentZ + wanderD) // is our destination too high to climb?
{
m_WanderTimer = getMSTime() + 1000; // wait 1 second before we try again
return;
}
m_Unit->SetOrientation(wanderO);
MoveTo(wanderX, wanderY, wanderZ, wanderO);
m_WanderTimer = getMSTime() + m_totalMoveTime + 300; // time till next move (+ pause)
}
}
//Unit Follow Code
if(UnitToFollow != NULL)
{
#if !defined(WIN32) && !defined(HACKY_CRASH_FIXES)
if( UnitToFollow->event_GetCurrentInstanceId() != m_Unit->event_GetCurrentInstanceId() || !UnitToFollow->IsInWorld() )
UnitToFollow = NULL;
else
{
#else
__try
{
if( UnitToFollow->event_GetCurrentInstanceId() != m_Unit->event_GetCurrentInstanceId() || !UnitToFollow->IsInWorld() )
UnitToFollow = NULL;
else
{
#endif
if(m_AIState == STATE_IDLE || m_AIState == STATE_FOLLOWING)
{
float dist = m_Unit->GetDistanceSq(UnitToFollow);
// re-calculate orientation based on target's movement
if(m_lastFollowX != UnitToFollow->GetPositionX() ||
m_lastFollowY != UnitToFollow->GetPositionY())
{
float dx = UnitToFollow->GetPositionX() - m_Unit->GetPositionX();
float dy = UnitToFollow->GetPositionY() - m_Unit->GetPositionY();
if(dy != 0.0f)
{
float angle = atan2(dx,dy);
m_Unit->SetOrientation(angle);
}
m_lastFollowX = UnitToFollow->GetPositionX();
m_lastFollowY = UnitToFollow->GetPositionY();
}
if (dist > (FollowDistance*FollowDistance)) //if out of range
{
m_AIState = STATE_FOLLOWING;
if(dist > 25.0f) //25 yard away lets run else we will loose the them
m_moveRun = true;
else
m_moveRun = false;
if(m_AIType == AITYPE_PET || UnitToFollow == m_formationLinkTarget) //Unit is Pet/formation
{
if(dist > 900.0f/*30*/)
m_moveSprint = true;
float delta_x = UnitToFollow->GetPositionX();
float delta_y = UnitToFollow->GetPositionY();
float d = 3;
if(m_formationLinkTarget)
d = m_formationFollowDistance;
MoveTo(delta_x+(d*(cosf(m_fallowAngle+UnitToFollow->GetOrientation()))),
delta_y+(d*(sinf(m_fallowAngle+UnitToFollow->GetOrientation()))),
UnitToFollow->GetPositionZ(),UnitToFollow->GetOrientation());
}
else
{
_CalcDestinationAndMove(UnitToFollow, FollowDistance);
}
}
}
}
#if defined(WIN32) && defined(HACKY_CRASH_FIXES)
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
UnitToFollow = NULL;
}
#endif
}
}
void AIInterface::CastSpell(Unit* caster, SpellEntry *spellInfo, SpellCastTargets targets)
{
if( m_AIType != AITYPE_PET && disable_spell )
return;
// Stop movement while casting.
m_AIState = STATE_CASTING;
#ifdef _AI_DEBUG
sLog.outString("AI DEBUG: Unit %u casting spell %s on target "I64FMT, caster->GetEntry(),
sSpellStore.LookupString(spellInfo->Name), targets.m_unitTarget);
#endif
//i wonder if this will lead to a memory leak :S
Spell *nspell = SpellPool.PooledNew();
nspell->Init(caster, spellInfo, false, NULL);
nspell->prepare(&targets);
}
SpellEntry *AIInterface::getSpellEntry(uint32 spellId)
{
SpellEntry *spellInfo = dbcSpell.LookupEntry(spellId );
if(!spellInfo)
{
sLog.outError("WORLD: unknown spell id %i\n", spellId);
return NULL;
}
return spellInfo;
}
SpellCastTargets AIInterface::setSpellTargets(SpellEntry *spellInfo, Unit* target)
{
SpellCastTargets targets;
targets.m_unitTarget = target ? target->GetGUID() : 0;
targets.m_itemTarget = 0;
targets.m_srcX = targets.m_destX = m_Unit->GetPositionX();
targets.m_srcY = targets.m_destY = m_Unit->GetPositionY();
targets.m_srcZ = targets.m_destZ = m_Unit->GetPositionZ();
if(m_nextSpell->spelltargetType == TTYPE_SINGLETARGET)
{
targets.m_targetMask = 2;
targets.m_unitTarget = target->GetGUID();
}
else if(m_nextSpell->spelltargetType == TTYPE_SOURCE)
{
targets.m_targetMask = 32;
// targets.m_srcX = m_Unit->GetPositionX();
// targets.m_srcY = m_Unit->GetPositionY();
// targets.m_srcZ = m_Unit->GetPositionZ();
}
else if(m_nextSpell->spelltargetType == TTYPE_DESTINATION)
{
targets.m_targetMask = 64;
targets.m_destX = target->GetPositionX();
targets.m_destY = target->GetPositionY();
targets.m_destZ = target->GetPositionZ();
}
else if(m_nextSpell->spelltargetType == TTYPE_CASTER)
{
targets.m_targetMask = 2;
targets.m_unitTarget = m_Unit->GetGUID();
}
return targets;
}
AI_Spell *AIInterface::getSpell()
{
if(next_spell_time > (uint32)UNIXTIME)
return NULL;
waiting_for_cooldown = false;
// look at our spells
AI_Spell * sp = NULL;
AI_Spell * def_spell = NULL;
uint32 cool_time=0;
uint32 cool_time2;
uint32 nowtime = getMSTime();
if(m_Unit->IsPet())
{
sp = def_spell = ((Pet*)m_Unit)->HandleAutoCastEvent();
}
else
{
for(list<AI_Spell*>::iterator itr = m_spells.begin(); itr != m_spells.end();)
{
sp = *itr;
++itr;
if(
// sp->cooldowntime && //Zack : no need for this double check here
nowtime < sp->cooldowntime
// && sp->procChance >= 100 //Zack: why was this put here ? It makes mobs spam spells like no tomorrow
)
{
cool_time2=sp->cooldowntime-nowtime;
if(!cool_time || cool_time2<cool_time)
cool_time=cool_time2;
waiting_for_cooldown = true;
continue;
}
if(sp->procCount && sp->procCounter >= sp->procCount)
continue;
if(sp->agent == AGENT_SPELL)
{
if (sp->spellType == STYPE_BUFF)
{
// cast the buff at requested percent only if we don't have it already
if(sp->procChance >= 100 || Rand(sp->procChance))
{
if(!m_Unit->HasBuff(sp->spell->Id))
{
return sp;
}
}
}
else
{
if(def_spell!=0)
continue;
// cast the spell at requested percent.
if(sp->procChance >= 100 || Rand(sp->procChance))
{
//focus/mana requirement
switch(sp->spell->powerType)
{
case POWER_TYPE_MANA:
if(m_Unit->GetUInt32Value(UNIT_FIELD_POWER1) < sp->spell->manaCost)
continue;
break;
case POWER_TYPE_FOCUS:
if(m_Unit->GetUInt32Value(UNIT_FIELD_POWER3) < sp->spell->manaCost)
continue;
break;
}
def_spell = sp;
//we got a selected spell, we can exit loop now
break;
}
else //we failed casting it due to given chance, we activate false cooldown on it to not spam searching this list
{
// sp->cooldowntime = nowtime + sp->cooldown / ( sp->procChance + 1 );
cool_time2 = 2000;
sp->cooldowntime = nowtime + cool_time2;
if( !cool_time || cool_time2 < cool_time )
cool_time = cool_time2;
}
}
}
}
}
if(def_spell)
{
// set cooldown
if(def_spell->procCount)
def_spell->procCounter++;
if(def_spell->cooldown)
def_spell->cooldowntime = nowtime + def_spell->cooldown;
waiting_for_cooldown = false;
return def_spell;
}
// save some loops if waiting for cooldownz
if(cool_time)
{
cool_time2 = cool_time / 1000;
if(cool_time2)
next_spell_time = (uint32)UNIXTIME + cool_time2;
}
else
{
next_spell_time = (uint32)UNIXTIME + MOB_SPELLCAST_REFRESH_COOLDOWN_INTERVAL;
waiting_for_cooldown = false;
}
#ifdef _AI_DEBUG
sLog.outString("AI DEBUG: Returning no spell for unit %u", m_Unit->GetEntry());
#endif
return 0;
}
void AIInterface::addSpellToList(AI_Spell *sp)
{
if(!sp || !sp->spell)
return;
AI_Spell * sp2 = new AI_Spell;
memcpy(sp2, sp, sizeof(AI_Spell));
m_spells.push_back(sp2);
m_Unit->m_SpellList.insert(sp2->spell->Id); // add to list
}
uint32 AIInterface::getThreatByGUID(uint64 guid)
{
if( m_Unit->GetMapMgr() == NULL )
return 0;
Unit *obj = m_Unit->GetMapMgr()->GetUnit(guid);
if(obj)
return getThreatByPtr(obj);
return 0;
}
uint32 AIInterface::getThreatByPtr(Unit* obj)
{
if( !obj || m_Unit->GetMapMgr() == NULL)
return 0;
TargetMap::iterator it = m_aiTargets.find(obj->GetGUID());
if(it != m_aiTargets.end())
{
Unit *tempUnit = m_Unit->GetMapMgr()->GetUnit(it->first);
if (tempUnit)
return it->second + tempUnit->GetThreatModifyer();
else
return it->second;
}
return 0;
}
/*
#if defined(WIN32) && defined(HACKY_CRASH_FIXES)
__declspec(noinline) bool ___CheckTarget(Unit * ptr, Unit * him)
{
__try
{
if( him->GetInstanceID() != ptr->GetInstanceID() || !him->isAlive() || !isAttackable( ptr, him ) )
{
return false;
}
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
return false;
}
return true;
}
#endif
*/
//should return a valid target
Unit *AIInterface::GetMostHated()
{
if( m_Unit->GetMapMgr() == NULL )
return NULL;
Unit *ResultUnit=NULL;
//override mosthated with taunted target. Basic combat checks are made for it.
//What happens if we can't see tauntedby unit ?
ResultUnit = getTauntedBy();
if(ResultUnit)
return ResultUnit;
pair<Unit*, int32> currentTarget;
currentTarget.first = 0;
currentTarget.second = -1;
LockAITargets(true);
TargetMap::iterator it2 = m_aiTargets.begin();
TargetMap::iterator itr;
for(; it2 != m_aiTargets.end();)
{
itr = it2;
++it2;
/* check the target is valid */
/*
#if defined(WIN32) && defined(HACKY_CRASH_FIXES)
if(!___CheckTarget( m_Unit, itr->first ) )
{
if( m_nextTarget == itr->first )
m_nextTarget = NULL;
m_aiTargets.erase(itr);
continue;
}
#else
if(itr->first->event_GetCurrentInstanceId() != m_Unit->event_GetCurrentInstanceId() || !itr->first->isAlive() || !isAttackable(m_Unit, itr->first))
{
m_aiTargets.erase(itr);
continue;
}
#endif
*/
// this is a much slower version then the previous one but it causes a lot of crashes and that is above speed right now.
Unit *ai_t = m_Unit->GetMapMgr()->GetUnit( itr->first );
if( !ai_t || ai_t->GetInstanceID() != m_Unit->GetInstanceID() || !ai_t->isAlive() || !isAttackable( m_Unit, ai_t ) )
{
if( GetNextTarget() == ai_t )
SetNextTarget( (Unit*)NULL );
m_aiTargets.erase(itr);
continue;
}
if((itr->second + ai_t->GetThreatModifyer()) > currentTarget.second)
{
/* new target */
currentTarget.first = ai_t;
currentTarget.second = itr->second + ai_t->GetThreatModifyer();
m_currentHighestThreat = currentTarget.second;
}
/* there are no more checks needed here... the needed checks are done by CheckTarget() */
}
LockAITargets(false);
return currentTarget.first;
}
Unit *AIInterface::GetSecondHated()
{
if( m_Unit->GetMapMgr() == NULL )
return NULL;
Unit *ResultUnit=GetMostHated();
pair<Unit*, int32> currentTarget;
currentTarget.first = 0;
currentTarget.second = -1;
LockAITargets(true);
TargetMap::iterator it2 = m_aiTargets.begin();
TargetMap::iterator itr;
for(; it2 != m_aiTargets.end();)
{
itr = it2;
++it2;
/* check the target is valid */
Unit *ai_t = m_Unit->GetMapMgr()->GetUnit( itr->first );
if(!ai_t || ai_t->GetInstanceID() != m_Unit->GetInstanceID() || !ai_t->isAlive() || !isAttackable(m_Unit, ai_t))
{
m_aiTargets.erase(itr);
continue;
}
if((itr->second + ai_t->GetThreatModifyer()) > currentTarget.second &&
ai_t != ResultUnit)
{
/* new target */
currentTarget.first = ai_t;
currentTarget.second = itr->second + ai_t->GetThreatModifyer();
m_currentHighestThreat = currentTarget.second;
}
}
LockAITargets(false);
return currentTarget.first;
}
bool AIInterface::modThreatByGUID(uint64 guid, int32 mod)
{
if (!m_aiTargets.size())
return false;
if( m_Unit->GetMapMgr() == NULL )
return false;
Unit *obj = m_Unit->GetMapMgr()->GetUnit(guid);
if(obj)
return modThreatByPtr(obj, mod);
return false;
}
bool AIInterface::modThreatByPtr(Unit* obj, int32 mod)
{
if(!obj)
return false;
LockAITargets(true);
int32 tempthreat;
TargetMap::iterator it = m_aiTargets.find(obj->GetGUID());
if(it != m_aiTargets.end())
{
it->second += mod;
if (it->second < 1)
it->second = 1;
tempthreat = it->second + obj->GetThreatModifyer();
if (tempthreat < 1)
tempthreat = 1;
if(tempthreat > m_currentHighestThreat)
{
// new target!
if(!isTaunted)
{
m_currentHighestThreat = tempthreat;
SetNextTarget(obj);
}
}
}
else
{
m_aiTargets.insert( make_pair( obj->GetGUID(), mod ) );
tempthreat = mod + obj->GetThreatModifyer();
if (tempthreat < 1)
tempthreat = 1;
if(tempthreat > m_currentHighestThreat)
{
if(!isTaunted)
{
m_currentHighestThreat = tempthreat;
SetNextTarget(obj);
}
}
}
LockAITargets(false);
if(obj == GetNextTarget())
{
// check for a possible decrease in threat.
if(mod < 0)
{
SetNextTarget(GetMostHated());
//if there is no more new targets then we can walk back home ?
if(!GetNextTarget())
HandleEvent(EVENT_LEAVECOMBAT, m_Unit, 0);
}
}
return true;
}
void AIInterface::RemoveThreatByGUID(uint64 guid)
{
if (!m_aiTargets.size())
return;
if( m_Unit->GetMapMgr() == NULL )
return;
Unit *obj = m_Unit->GetMapMgr()->GetUnit(guid);
if(obj)
RemoveThreatByPtr(obj);
}
void AIInterface::RemoveThreatByPtr(Unit* obj)
{
if(!obj)
return;
LockAITargets(true);
TargetMap::iterator it = m_aiTargets.find(obj->GetGUID());
if(it != m_aiTargets.end())
{
m_aiTargets.erase(it);
//check if we are in combat and need a new target
if(obj==GetNextTarget())
{
SetNextTarget(GetMostHated());
//if there is no more new targets then we can walk back home ?
if(!GetNextTarget())
HandleEvent(EVENT_LEAVECOMBAT, m_Unit, 0);
}
}
LockAITargets(false);
}
void AIInterface::addAssistTargets(Unit* Friend)
{
// stop adding stuff that gives errors on linux!
m_assistTargets.insert(Friend);
}
void AIInterface::WipeHateList()
{
for(TargetMap::iterator itr = m_aiTargets.begin(); itr != m_aiTargets.end(); ++itr)
itr->second = 0;
m_currentHighestThreat = 0;
}
void AIInterface::ClearHateList() //without leaving combat
{
for(TargetMap::iterator itr = m_aiTargets.begin(); itr != m_aiTargets.end(); ++itr)
itr->second = 1;
m_currentHighestThreat = 1;
}
void AIInterface::WipeTargetList()
{
SetNextTarget( (Unit*)NULL );
m_nextSpell = NULL;
m_currentHighestThreat = 0;
LockAITargets( true );
m_aiTargets.clear();
LockAITargets( false );
m_Unit->CombatStatus.Vanished();
}
bool AIInterface::taunt(Unit* caster, bool apply)
{
if(apply)
{
//wowwiki says that we cannot owerride this spell
if(GetIsTaunted())
return false;
if(!caster)
{
isTaunted = false;
return false;
}
//check if we can attack taunter. Maybe it's a hack or a bug if we fail this test
if(isHostile(m_Unit, caster))
{
//check if we have to add him to our agro list
//GetMostHated(); //update our most hated list/ Note that at this point we do not have a taunter yet. If we would have then this funtion will not give real mosthated
int32 oldthreat = getThreatByPtr(caster);
//make sure we rush the target anyway. Since we are not tauted yet, this will also set our target
modThreatByPtr(caster,abs(m_currentHighestThreat-oldthreat)+1); //we need to be the most hated at this moment
// SetNextTarget(caster);
}
isTaunted = true;
tauntedBy = caster;
}
else
{
isTaunted = false;
tauntedBy = NULL;
//taunt is over, we should get a new target based on most hated list
SetNextTarget(GetMostHated());
}
return true;
}
Unit* AIInterface::getTauntedBy()
{
if(GetIsTaunted())
{
return tauntedBy;
}
else
{
return NULL;
}
}
bool AIInterface::GetIsTaunted()
{
if(isTaunted)
{
if(!tauntedBy || !tauntedBy->isAlive())
{
isTaunted = false;
tauntedBy = NULL;
}
}
return isTaunted;
}
void AIInterface::SetSoulLinkedWith(Unit* target)
{
if (!target)
return;
soullinkedWith = target;
isSoulLinked = true;
}
Unit* AIInterface::getSoullinkedWith()
{
if(GetIsTaunted())
{
return soullinkedWith;
}
else
{
return NULL;
}
}
bool AIInterface::GetIsSoulLinked()
{
if(isSoulLinked)
{
if(!soullinkedWith || !soullinkedWith->isAlive())
{
isSoulLinked = false;
soullinkedWith = NULL;
}
}
return isSoulLinked;
}
void AIInterface::CheckTarget(Unit* target)
{
if( target == NULL )
return;
if( target == UnitToFollow ) // fix for crash here
{
UnitToFollow = NULL;
m_lastFollowX = m_lastFollowY = 0;
FollowDistance = 0;
}
if( target == UnitToFollow_backup )
{
UnitToFollow_backup = NULL;
}
AssistTargetSet::iterator itr = m_assistTargets.find(target);
if(itr != m_assistTargets.end())
m_assistTargets.erase(itr);
LockAITargets(true);
TargetMap::iterator it2 = m_aiTargets.find( target->GetGUID() );
if( it2 != m_aiTargets.end() || target == GetNextTarget() )
{
target->CombatStatus.RemoveAttacker( m_Unit, m_Unit->GetGUID() );
m_Unit->CombatStatus.RemoveAttackTarget( target );
if(it2 != m_aiTargets.end())
{
m_aiTargets.erase(it2);
}
if (target == GetNextTarget()) // no need to cast on these.. mem addresses are still the same
{
SetNextTarget( (Unit*)NULL );
m_nextSpell = NULL;
// find the one with the next highest threat
GetMostHated();
}
}
LockAITargets(false);
if( target->GetTypeId() == TYPEID_UNIT )
{
it2 = target->GetAIInterface()->m_aiTargets.find( m_Unit->GetGUID() );
if( it2 != target->GetAIInterface()->m_aiTargets.end() )
{
target->GetAIInterface()->LockAITargets(true);
target->GetAIInterface()->m_aiTargets.erase( it2 );
target->GetAIInterface()->LockAITargets(false);
}
if( target->GetAIInterface()->GetNextTarget() == m_Unit )
{
target->GetAIInterface()->SetNextTarget( (Unit*)NULL );
target->GetAIInterface()->m_nextSpell = NULL;
target->GetAIInterface()->GetMostHated();
}
if( target->GetAIInterface()->UnitToFollow == m_Unit )
target->GetAIInterface()->UnitToFollow = NULL;
}
if(target == UnitToFear)
UnitToFear = NULL;
if(tauntedBy == target)
tauntedBy = NULL;
}
uint32 AIInterface::_CalcThreat(uint32 damage, SpellEntry * sp, Unit* Attacker)
{
if (isSameFaction(m_Unit,Attacker))
return 0;
int32 mod = 0;
if( sp != NULL && sp->ThreatForSpell != 0 )
{
mod = sp->ThreatForSpell;
}
if( sp != NULL && sp->ThreatForSpellCoef != 0.0f )
mod += int32(damage * sp->ThreatForSpellCoef);
else
mod += damage;
if( sp != NULL && sp->SpellGroupType && Attacker)
{
SM_FIValue(Attacker->SM_FThreat,&mod,sp->SpellGroupType);
SM_PIValue(Attacker->SM_PThreat,&mod,sp->SpellGroupType);
}
if (Attacker->getClass() == ROGUE)
mod = int32(mod * 0.71); // Rogues generate 0.71x threat per damage.
// modify threat by Buffs
if (sp != NULL)
mod += (mod * Attacker->GetGeneratedThreatModifyer(sp->School) / 100);
else
mod += (mod * Attacker->GetGeneratedThreatModifyer(0) / 100);
if (mod < 1)
mod = 1;
return mod;
}
void AIInterface::WipeReferences()
{
m_nextSpell = 0;
m_currentHighestThreat = 0;
LockAITargets(true);
m_aiTargets.clear();
LockAITargets(false);
SetNextTarget( (Unit*)NULL );
UnitToFear = 0;
UnitToFollow = 0;
tauntedBy = 0;
m_Unit->AquireInrangeLock(); //make sure to release lock before exit function !
//Clear targettable
for(set<Object*>::iterator itr = m_Unit->GetInRangeSetBegin(); itr != m_Unit->GetInRangeSetEnd(); ++itr)
if( (*itr) && (*itr)->GetTypeId() == TYPEID_UNIT && static_cast<Unit*>(*itr)->GetAIInterface())
static_cast<Unit*>(*itr)->GetAIInterface()->RemoveThreatByPtr( m_Unit );
m_Unit->ReleaseInrangeLock();
}
void AIInterface::ResetProcCounts()
{
for(list<AI_Spell*>::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
if((*itr)->procCount)
(*itr)->procCounter=0;
}
//we only cast once a spell and we will set his health and resistances. Note that this can be made with db too !
void AIInterface::Event_Summon_EE_totem(uint32 summon_duration)
{
//some say it should inherit the level of the caster
Unit *caster = m_Unit->GetMapMgr()->GetUnit( m_Unit->GetUInt64Value( UNIT_FIELD_CREATEDBY ) );
uint32 new_level = 0;
if( caster )
new_level = caster->getLevel( );
//timer should not reach this value thus not cast this spell again
m_totemspelltimer = 0xEFFFFFFF;
//creatures do not support PETs and the spell uses that effect so we force a summon guardian thing
Unit *ourslave=m_Unit->create_guardian(15352,summon_duration,float(-M_PI*2), new_level );
if(ourslave)
{
static_cast<Creature*>(ourslave)->ResistanceModPct[NATURE_DAMAGE]=100;//we should be imune to nature dmg. This can be also set in db
static_cast<Creature*>(ourslave)->m_noRespawn = true;
/*
- Earth Stun (37982)
- taunt
*/
}
}
//we only cast once a spell and we will set his health and resistances. Note that this can be made with db too !
void AIInterface::Event_Summon_FE_totem(uint32 summon_duration)
{
//some say it should inherit the level of the caster
Unit *caster = m_Unit->GetMapMgr()->GetUnit( m_Unit->GetUInt64Value( UNIT_FIELD_CREATEDBY ) );
uint32 new_level = 0;
if( caster )
new_level = caster->getLevel( );
//timer should not reach this value thus not cast this spell again
m_totemspelltimer = 0xEFFFFFFF;
//creatures do not support PETs and the spell uses that effect so we force a summon guardian thing
Unit *ourslave=m_Unit->create_guardian(15438,summon_duration,float(-M_PI*2), new_level);
if(ourslave)
{
//m_Unit->summonPet = ourslave;
static_cast<Creature*>(ourslave)->ResistanceModPct[FIRE_DAMAGE]=100;//we should be imune to fire dmg. This can be also set in db
static_cast<Creature*>(ourslave)->m_noRespawn = true;
/*
- also : select * from dbc_spell where name like "%fire blast%"
- also : select * from dbc_spell where name like "%fire nova"
*/
}
}
/*
void AIInterface::CancelSpellCast()
{
//hmm unit spell casting is not the same as Ai spell casting ? Have to test this
if(m_Unit->isCasting())
m_Unit->m_currentSpell->safe_cancel();
//i can see this crashing already :P.
m_AIState = STATE_IDLE;
}
*/
void AIInterface::EventChangeFaction( Unit *ForceAttackersToHateThisInstead )
{
m_nextSpell = 0;
m_currentHighestThreat = 0;
//we need a new hatred list
LockAITargets(true);
m_aiTargets.clear();
LockAITargets(false);
//we need a new assist list
m_assistTargets.clear();
//Clear targettable
if( ForceAttackersToHateThisInstead == NULL )
{
m_Unit->AquireInrangeLock(); //make sure to release lock before exit function !
for(set<Object*>::iterator itr = m_Unit->GetInRangeSetBegin(); itr != m_Unit->GetInRangeSetEnd(); ++itr)
if( (*itr) && (*itr)->GetTypeId() == TYPEID_UNIT && static_cast<Unit*>(*itr)->GetAIInterface() )
static_cast<Unit*>(*itr)->GetAIInterface()->RemoveThreatByPtr( m_Unit );
m_Unit->ReleaseInrangeLock();
SetNextTarget( (Unit*)NULL );
}
else
{
m_Unit->AquireInrangeLock(); //make sure to release lock before exit function !
for(set<Object*>::iterator itr = m_Unit->GetInRangeSetBegin(); itr != m_Unit->GetInRangeSetEnd(); ++itr)
if( (*itr) && (*itr)->GetTypeId() == TYPEID_UNIT && static_cast<Unit*>(*itr)->GetAIInterface()
&& static_cast<Unit*>(*itr)->GetAIInterface()->getThreatByPtr( m_Unit ) )//this guy will join me in fight since i'm telling him "sorry i was controlled"
{
static_cast<Unit*>(*itr)->GetAIInterface()->modThreatByPtr( ForceAttackersToHateThisInstead, 10 ); //just aping to be bale to hate him in case we got nothing else
static_cast<Unit*>(*itr)->GetAIInterface()->RemoveThreatByPtr( m_Unit );
}
m_Unit->ReleaseInrangeLock();
modThreatByPtr( ForceAttackersToHateThisInstead, 1 );
SetNextTarget( ForceAttackersToHateThisInstead );
}
}
bool isGuard(uint32 id)
{
switch(id)
{
/* stormwind guards */
case 68:
case 1423:
case 1756:
case 15858:
case 15859:
case 16864:
case 20556:
case 18948:
case 18949:
case 1642:
/* ogrimmar guards */
case 3296:
case 15852:
case 15853:
case 15854:
case 18950:
/* undercity guards */
case 5624:
case 18971:
case 16432:
/* exodar */
case 16733:
case 18815:
/* thunder bluff */
case 3084:
/* silvermoon */
case 16221:
case 17029:
case 16222:
/* ironforge */
case 727:
case 5595:
case 12996:
/* darnassus? */
{
return true;
}break;
}
return false;
}
bool isNeutralGuard(uint32 id)
{
switch(id)
{
// Ratchet
case 3502:
// Booty Bay
case 4624:
case 15088:
// Gadgetzan
case 9460:
// Argent Dawn
case 11102:
case 16378:
// Cenarion Hold
case 15184:
// Moonglade
case 11822:
// Everlook
case 11190:
// Cenarion Refuge
case 17855:
// Throne of the elements
case 18099:
case 18101:
case 18102:
// Area 52
case 20484:
case 20485:
// Cosmowrench
case 22494:
// Mudsprocket
case 23636:
// Concert Bruiser
case 23721:
// Shattered Sun
case 26253:
case 24994:
return true;
break;
}
return false;
}
void AIInterface::WipeCurrentTarget()
{
LockAITargets(true);
TargetMap::iterator itr = m_aiTargets.find( GetNextTarget() ? GetNextTarget()->GetGUID() : 0 );
if( itr != m_aiTargets.end() )
m_aiTargets.erase( itr );
LockAITargets(false);
SetNextTarget( (Unit*)NULL );
if( GetNextTarget() == UnitToFollow )
UnitToFollow = NULL;
if( GetNextTarget() == UnitToFollow_backup )
UnitToFollow_backup = NULL;
}
#ifdef HACKY_CRASH_FIXES
bool AIInterface::CheckCurrentTarget()
{
bool cansee = false;
//in case target was removed from map since our last check on him
if( GetNextTarget() == NULL )
{
WipeCurrentTarget();
return false;
}
if( GetNextTarget() && GetNextTarget()->GetInstanceID() == m_Unit->GetInstanceID())
{
if( m_Unit->GetTypeId() == TYPEID_UNIT )
cansee = static_cast< Creature* >( m_Unit )->CanSee( GetNextTarget() );
else
cansee = static_cast< Player* >( m_Unit )->CanSee( GetNextTarget() );
}
else
{
WipeCurrentTarget();
}
return cansee;
}
bool AIInterface::TargetUpdateCheck(Unit * ptr)
{
__try
{
if( ptr->event_GetCurrentInstanceId() != m_Unit->event_GetCurrentInstanceId() ||
!ptr->isAlive() || m_Unit->GetDistanceSq(ptr) >= 6400.0f )
{
return false;
}
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
return false;
}
return true;
}
#endif
Unit* AIInterface::GetNextTarget()
{
if (m_nextTarget && m_Unit && m_Unit->GetMapMgr()) return m_Unit->GetMapMgr()->GetUnit(m_nextTarget);
return NULL;
}
void AIInterface::SetNextTarget (Unit *nextTarget) {
if (nextTarget)
SetNextTarget(nextTarget->GetGUID());
else
SetNextTarget((uint64)NULL);
}
void AIInterface::SetNextTarget (uint64 nextTarget)
{
m_nextTarget = nextTarget;
m_Unit->SetUInt64Value(UNIT_FIELD_TARGET, m_nextTarget);
if(nextTarget)
{
#ifdef ENABLE_GRACEFULL_HIT
have_graceful_hit=false;
#endif
}
}
void AIInterface::HandleChainAggro(Unit *u)
{
if (!m_Unit->IsInWorld() || !m_Unit->isAlive() || m_Unit->m_chain == NULL)
return;
for (std::set<Unit*>::iterator itr=m_Unit->m_chain->m_units.begin(); itr!=m_Unit->m_chain->m_units.end(); ++itr)
{
if (!(*itr)->IsInWorld() || !(*itr)->isAlive() || (m_Unit->m_chain->m_chainrange != 0 && m_Unit->CalcDistance(*itr) > m_Unit->m_chain->m_chainrange))
continue;
if ((*itr)->GetAIInterface()->GetAITargets()->find(u->GetGUID()) == (*itr)->GetAIInterface()->GetAITargets()->end())
{
if((*itr)->GetAIInterface()->getAIState() == STATE_IDLE || (*itr)->GetAIInterface()->getAIState() == STATE_FOLLOWING)
(*itr)->GetAIInterface()->HandleEvent(EVENT_ENTERCOMBAT, u, 0);
else
(*itr)->GetAIInterface()->GetAITargets()->insert(TargetMap::value_type(u->GetGUID(), 1));
}
}
}
| [
"[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef",
"[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef"
]
| [
[
[
1,
1
],
[
5,
22
],
[
25,
26
],
[
28,
33
],
[
35,
65
],
[
68,
69
],
[
71,
77
],
[
79,
108
],
[
132,
192
],
[
194,
199
],
[
201,
215
],
[
219,
235
],
[
237,
239
],
[
241,
245
],
[
268,
268
],
[
271,
271
],
[
286,
286
],
[
292,
301
],
[
308,
321
],
[
325,
328
],
[
330,
337
],
[
339,
339
],
[
342,
342
],
[
344,
347
],
[
349,
356
],
[
358,
358
],
[
361,
362
],
[
367,
378
],
[
380,
382
],
[
384,
392
],
[
395,
395
],
[
398,
403
],
[
405,
405
],
[
407,
409
],
[
411,
422
],
[
424,
424
],
[
426,
429
],
[
431,
450
],
[
452,
452
],
[
454,
461
],
[
464,
491
],
[
493,
493
],
[
495,
503
],
[
505,
526
],
[
528,
529
],
[
531,
535
],
[
537,
537
],
[
539,
547
],
[
549,
565
],
[
567,
567
],
[
570,
570
],
[
576,
576
],
[
580,
580
],
[
583,
583
],
[
616,
618
],
[
625,
636
],
[
639,
640
],
[
647,
651
],
[
653,
655
],
[
657,
657
],
[
659,
659
],
[
661,
664
],
[
666,
735
],
[
737,
760
],
[
762,
781
],
[
814,
823
],
[
825,
832
],
[
834,
840
],
[
842,
843
],
[
847,
904
],
[
907,
909
],
[
913,
913
],
[
931,
932
],
[
935,
940
],
[
942,
942
],
[
945,
945
],
[
956,
956
],
[
960,
991
],
[
994,
998
],
[
1000,
1002
],
[
1005,
1007
],
[
1009,
1010
],
[
1015,
1019
],
[
1068,
1068
],
[
1071,
1072
],
[
1074,
1075
],
[
1077,
1077
],
[
1079,
1081
],
[
1084,
1087
],
[
1089,
1130
],
[
1132,
1132
],
[
1135,
1138
],
[
1140,
1163
],
[
1165,
1165
],
[
1168,
1168
],
[
1174,
1174
],
[
1176,
1188
],
[
1190,
1195
],
[
1197,
1202
],
[
1232,
1237
],
[
1253,
1254
],
[
1256,
1260
],
[
1262,
1280
],
[
1282,
1287
],
[
1289,
1298
],
[
1301,
1301
],
[
1303,
1304
],
[
1306,
1312
],
[
1314,
1317
],
[
1319,
1320
],
[
1322,
1325
],
[
1327,
1328
],
[
1330,
1330
],
[
1332,
1332
],
[
1342,
1343
],
[
1350,
1352
],
[
1354,
1372
],
[
1375,
1379
],
[
1386,
1391
],
[
1403,
1414
],
[
1416,
1417
],
[
1419,
1419
],
[
1421,
1425
],
[
1427,
1431
],
[
1434,
1447
],
[
1449,
1455
],
[
1457,
1457
],
[
1459,
1500
],
[
1502,
1503
],
[
1522,
1522
],
[
1532,
1532
],
[
1536,
1537
],
[
1539,
1547
],
[
1549,
1550
],
[
1552,
1552
],
[
1554,
1554
],
[
1557,
1557
],
[
1560,
1561
],
[
1574,
1577
],
[
1579,
1580
],
[
1583,
1584
],
[
1586,
1593
],
[
1595,
1607
],
[
1653,
1657
],
[
1661,
1663
],
[
1666,
1666
],
[
1670,
1672
],
[
1674,
1676
],
[
1679,
1682
],
[
1684,
1684
],
[
1687,
1687
],
[
1690,
1690
],
[
1692,
1692
],
[
1713,
1713
],
[
1715,
1715
],
[
1717,
1717
],
[
1731,
1731
],
[
1736,
1736
],
[
1740,
1740
],
[
1742,
1742
],
[
1745,
1745
],
[
1752,
1752
],
[
1756,
1756
],
[
1760,
1762
],
[
1764,
1765
],
[
1773,
1773
],
[
1775,
1775
],
[
1796,
1796
],
[
1799,
1799
],
[
1801,
1801
],
[
1805,
1806
],
[
1823,
1823
],
[
1825,
1914
],
[
1919,
1924
],
[
1926,
1943
],
[
1945,
1947
],
[
1955,
1957
],
[
1961,
1961
],
[
1964,
1966
],
[
1968,
1969
],
[
1972,
1996
],
[
1998,
1998
],
[
2007,
2007
],
[
2012,
2026
],
[
2033,
2070
],
[
2072,
2090
],
[
2093,
2129
],
[
2131,
2131
],
[
2135,
2136
],
[
2146,
2170
],
[
2189,
2207
],
[
2209,
2214
],
[
2227,
2388
],
[
2407,
2462
],
[
2465,
2478
],
[
2482,
2483
],
[
2492,
2521
],
[
2525,
2717
],
[
2719,
2724
],
[
2726,
2788
],
[
2790,
2835
],
[
2837,
2841
],
[
2846,
2945
],
[
2950,
2950
],
[
2964,
3104
],
[
3106,
3112
],
[
3114,
3132
],
[
3141,
3148
],
[
3159,
3167
],
[
3170,
3171
],
[
3173,
3181
],
[
3205,
3220
],
[
3223,
3235
],
[
3267,
3361
],
[
3364,
3382
],
[
3388,
3391
],
[
3393,
3396
],
[
3400,
3410
],
[
3412,
3440
],
[
3446,
3464
],
[
3466,
3492
],
[
3503,
3529
],
[
3534,
3542
],
[
3544,
3545
],
[
3549,
3549
],
[
3551,
3554
],
[
3559,
3567
],
[
3571,
3572
],
[
3579,
3582
],
[
3584,
3600
],
[
3602,
3605
],
[
3609,
3620
],
[
3623,
3630
],
[
3632,
3647
],
[
3656,
3656
],
[
3658,
3658
],
[
3660,
3660
],
[
3662,
3663
],
[
3666,
3671
],
[
3674,
3677
],
[
3681,
3686
],
[
3689,
3696
],
[
3699,
3703
],
[
3706,
3707
],
[
3710,
3713
],
[
3716,
3722
],
[
3726,
3734
],
[
3736,
3737
],
[
3742,
3747
],
[
3760,
3762
],
[
3764,
3764
],
[
3769,
3769
],
[
3775,
3777
],
[
3781,
3784
],
[
3786,
3786
],
[
3788,
3793
],
[
3807,
3811
],
[
3816,
3816
],
[
3826,
3826
],
[
3829,
3851
],
[
3853,
3855
],
[
3857,
3857
],
[
3859,
3876
],
[
3878,
3878
],
[
3881,
3882
],
[
3885,
3885
],
[
3888,
3978
],
[
3984,
3992
],
[
3994,
3994
],
[
3996,
4002
],
[
4006,
4006
],
[
4008,
4008
],
[
4011,
4011
],
[
4014,
4014
],
[
4016,
4016
],
[
4018,
4042
],
[
4045,
4045
],
[
4049,
4049
],
[
4052,
4053
],
[
4056,
4056
],
[
4065,
4072
],
[
4074,
4074
],
[
4077,
4079
],
[
4087,
4095
],
[
4142,
4152
],
[
4189,
4234
],
[
4280,
4281
],
[
4284,
4285
],
[
4287,
4287
],
[
4289,
4289
],
[
4291,
4292
],
[
4294,
4301
],
[
4305,
4305
],
[
4308,
4308
],
[
4317,
4342
],
[
4344,
4344
],
[
4348,
4348
],
[
4355,
4355
],
[
4365,
4366
]
],
[
[
2,
4
],
[
23,
24
],
[
27,
27
],
[
34,
34
],
[
66,
67
],
[
70,
70
],
[
78,
78
],
[
109,
131
],
[
193,
193
],
[
200,
200
],
[
216,
218
],
[
236,
236
],
[
240,
240
],
[
246,
267
],
[
269,
270
],
[
272,
285
],
[
287,
291
],
[
302,
307
],
[
322,
324
],
[
329,
329
],
[
338,
338
],
[
340,
341
],
[
343,
343
],
[
348,
348
],
[
357,
357
],
[
359,
360
],
[
363,
366
],
[
379,
379
],
[
383,
383
],
[
393,
394
],
[
396,
397
],
[
404,
404
],
[
406,
406
],
[
410,
410
],
[
423,
423
],
[
425,
425
],
[
430,
430
],
[
451,
451
],
[
453,
453
],
[
462,
463
],
[
492,
492
],
[
494,
494
],
[
504,
504
],
[
527,
527
],
[
530,
530
],
[
536,
536
],
[
538,
538
],
[
548,
548
],
[
566,
566
],
[
568,
569
],
[
571,
575
],
[
577,
579
],
[
581,
582
],
[
584,
615
],
[
619,
624
],
[
637,
638
],
[
641,
646
],
[
652,
652
],
[
656,
656
],
[
658,
658
],
[
660,
660
],
[
665,
665
],
[
736,
736
],
[
761,
761
],
[
782,
813
],
[
824,
824
],
[
833,
833
],
[
841,
841
],
[
844,
846
],
[
905,
906
],
[
910,
912
],
[
914,
930
],
[
933,
934
],
[
941,
941
],
[
943,
944
],
[
946,
955
],
[
957,
959
],
[
992,
993
],
[
999,
999
],
[
1003,
1004
],
[
1008,
1008
],
[
1011,
1014
],
[
1020,
1067
],
[
1069,
1070
],
[
1073,
1073
],
[
1076,
1076
],
[
1078,
1078
],
[
1082,
1083
],
[
1088,
1088
],
[
1131,
1131
],
[
1133,
1134
],
[
1139,
1139
],
[
1164,
1164
],
[
1166,
1167
],
[
1169,
1173
],
[
1175,
1175
],
[
1189,
1189
],
[
1196,
1196
],
[
1203,
1231
],
[
1238,
1252
],
[
1255,
1255
],
[
1261,
1261
],
[
1281,
1281
],
[
1288,
1288
],
[
1299,
1300
],
[
1302,
1302
],
[
1305,
1305
],
[
1313,
1313
],
[
1318,
1318
],
[
1321,
1321
],
[
1326,
1326
],
[
1329,
1329
],
[
1331,
1331
],
[
1333,
1341
],
[
1344,
1349
],
[
1353,
1353
],
[
1373,
1374
],
[
1380,
1385
],
[
1392,
1402
],
[
1415,
1415
],
[
1418,
1418
],
[
1420,
1420
],
[
1426,
1426
],
[
1432,
1433
],
[
1448,
1448
],
[
1456,
1456
],
[
1458,
1458
],
[
1501,
1501
],
[
1504,
1521
],
[
1523,
1531
],
[
1533,
1535
],
[
1538,
1538
],
[
1548,
1548
],
[
1551,
1551
],
[
1553,
1553
],
[
1555,
1556
],
[
1558,
1559
],
[
1562,
1573
],
[
1578,
1578
],
[
1581,
1582
],
[
1585,
1585
],
[
1594,
1594
],
[
1608,
1652
],
[
1658,
1660
],
[
1664,
1665
],
[
1667,
1669
],
[
1673,
1673
],
[
1677,
1678
],
[
1683,
1683
],
[
1685,
1686
],
[
1688,
1689
],
[
1691,
1691
],
[
1693,
1712
],
[
1714,
1714
],
[
1716,
1716
],
[
1718,
1730
],
[
1732,
1735
],
[
1737,
1739
],
[
1741,
1741
],
[
1743,
1744
],
[
1746,
1751
],
[
1753,
1755
],
[
1757,
1759
],
[
1763,
1763
],
[
1766,
1772
],
[
1774,
1774
],
[
1776,
1795
],
[
1797,
1798
],
[
1800,
1800
],
[
1802,
1804
],
[
1807,
1822
],
[
1824,
1824
],
[
1915,
1918
],
[
1925,
1925
],
[
1944,
1944
],
[
1948,
1954
],
[
1958,
1960
],
[
1962,
1963
],
[
1967,
1967
],
[
1970,
1971
],
[
1997,
1997
],
[
1999,
2006
],
[
2008,
2011
],
[
2027,
2032
],
[
2071,
2071
],
[
2091,
2092
],
[
2130,
2130
],
[
2132,
2134
],
[
2137,
2145
],
[
2171,
2188
],
[
2208,
2208
],
[
2215,
2226
],
[
2389,
2406
],
[
2463,
2464
],
[
2479,
2481
],
[
2484,
2491
],
[
2522,
2524
],
[
2718,
2718
],
[
2725,
2725
],
[
2789,
2789
],
[
2836,
2836
],
[
2842,
2845
],
[
2946,
2949
],
[
2951,
2963
],
[
3105,
3105
],
[
3113,
3113
],
[
3133,
3140
],
[
3149,
3158
],
[
3168,
3169
],
[
3172,
3172
],
[
3182,
3204
],
[
3221,
3222
],
[
3236,
3266
],
[
3362,
3363
],
[
3383,
3387
],
[
3392,
3392
],
[
3397,
3399
],
[
3411,
3411
],
[
3441,
3445
],
[
3465,
3465
],
[
3493,
3502
],
[
3530,
3533
],
[
3543,
3543
],
[
3546,
3548
],
[
3550,
3550
],
[
3555,
3558
],
[
3568,
3570
],
[
3573,
3578
],
[
3583,
3583
],
[
3601,
3601
],
[
3606,
3608
],
[
3621,
3622
],
[
3631,
3631
],
[
3648,
3655
],
[
3657,
3657
],
[
3659,
3659
],
[
3661,
3661
],
[
3664,
3665
],
[
3672,
3673
],
[
3678,
3680
],
[
3687,
3688
],
[
3697,
3698
],
[
3704,
3705
],
[
3708,
3709
],
[
3714,
3715
],
[
3723,
3725
],
[
3735,
3735
],
[
3738,
3741
],
[
3748,
3759
],
[
3763,
3763
],
[
3765,
3768
],
[
3770,
3774
],
[
3778,
3780
],
[
3785,
3785
],
[
3787,
3787
],
[
3794,
3806
],
[
3812,
3815
],
[
3817,
3825
],
[
3827,
3828
],
[
3852,
3852
],
[
3856,
3856
],
[
3858,
3858
],
[
3877,
3877
],
[
3879,
3880
],
[
3883,
3884
],
[
3886,
3887
],
[
3979,
3983
],
[
3993,
3993
],
[
3995,
3995
],
[
4003,
4005
],
[
4007,
4007
],
[
4009,
4010
],
[
4012,
4013
],
[
4015,
4015
],
[
4017,
4017
],
[
4043,
4044
],
[
4046,
4048
],
[
4050,
4051
],
[
4054,
4055
],
[
4057,
4064
],
[
4073,
4073
],
[
4075,
4076
],
[
4080,
4086
],
[
4096,
4141
],
[
4153,
4188
],
[
4235,
4279
],
[
4282,
4283
],
[
4286,
4286
],
[
4288,
4288
],
[
4290,
4290
],
[
4293,
4293
],
[
4302,
4304
],
[
4306,
4307
],
[
4309,
4316
],
[
4343,
4343
],
[
4345,
4347
],
[
4349,
4354
],
[
4356,
4364
],
[
4367,
4385
]
]
]
|
9e8fb62406fcd2234c5364770036e5f92dd35ffd | ce262ae496ab3eeebfcbb337da86d34eb689c07b | /SETools/SEManagedFramework/SEManagedUtility.cpp | 383ce2b701e82c8887987c306f4765a5273d8b11 | []
| no_license | pizibing/swingengine | d8d9208c00ec2944817e1aab51287a3c38103bea | e7109d7b3e28c4421c173712eaf872771550669e | refs/heads/master | 2021-01-16T18:29:10.689858 | 2011-06-23T04:27:46 | 2011-06-23T04:27:46 | 33,969,301 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,465 | cpp | // Swing Engine Version 1 Source Code
// Most of techniques in the engine are mainly based on David Eberly's
// Wild Magic 4 open-source code.The author of Swing Engine learned a lot
// from Eberly's experience of architecture and algorithm.
// Several sub-systems are totally new,and others are re-implimented or
// re-organized based on Wild Magic 4's sub-systems.
// Copyright (c) 2007-2010. All Rights Reserved
//
// Eberly's permission:
// Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or (at
// your option) any later version. The license is available for reading at
// the location:
// http://www.gnu.org/copyleft/lgpl.html
#include "SEManagedFrameworkPCH.h"
#include "SEManagedUtility.h"
using namespace Swing;
using namespace Swing::Tools::ManagedFramework;
using namespace System::Runtime::InteropServices;
//---------------------------------------------------------------------------
const char* ManagedUtility::StringToNativeCharBuffer(String^ thString)
{
if( !thString )
{
return 0;
}
// Native heap resource is allocated here.
IntPtr pBuffer = Marshal::StringToHGlobalAnsi(thString);
return (const char*)(void*)pBuffer;
}
//---------------------------------------------------------------------------
void ManagedUtility::FreeNativeCharBuffer(const char* acBuffer)
{
if( !acBuffer )
{
return;
}
// We've done with the native resource allocated by Marshal, free it.
Marshal::FreeHGlobal((IntPtr)(void*)acBuffer);
}
//---------------------------------------------------------------------------
SENode* ManagedUtility::CloneNode(SENode* pSrcNode)
{
if( !pSrcNode )
{
return 0;
}
SENode* pClonedObject = SE_NEW SENode;
pClonedObject->SetName(pSrcNode->GetName());
pClonedObject->Local = pSrcNode->Local;
for( int i = 0; i < pSrcNode->GetControllerCount(); i++ )
{
pClonedObject->AttachController(pSrcNode->GetController(i));
}
for( int i = 0; i < pSrcNode->GetGlobalStateCount(); i++ )
{
pClonedObject->AttachGlobalState(pSrcNode->GetGlobalState(i));
}
for( int i = 0; i < pSrcNode->GetCount(); i++ )
{
SESpatial* pChild = pSrcNode->GetChild(i);
if( pChild )
{
SESpatial* pClonedChild = 0;
const SERTTI& rType = pChild->GetType();
if( rType.IsExactly(SENode::TYPE) )
{
pClonedChild = CloneNode((SENode*)pChild);
}
else if( rType.IsExactly(SETriMesh::TYPE) )
{
pClonedChild = CloneTriMesh((SETriMesh*)pChild);
}
if( pClonedChild )
{
pClonedObject->AttachChild(pClonedChild);
}
}
}
return pClonedObject;
}
//---------------------------------------------------------------------------
SETriMesh* ManagedUtility::CloneTriMesh(SETriMesh* pSrcTriMesh)
{
if( !pSrcTriMesh )
{
return 0;
}
SETriMesh* pClonedObject = SE_NEW SETriMesh(pSrcTriMesh->VBuffer,
pSrcTriMesh->IBuffer);
pClonedObject->SetName(pSrcTriMesh->GetName());
pClonedObject->Local = pSrcTriMesh->Local;
pClonedObject->LightingMode = pSrcTriMesh->LightingMode;
pClonedObject->GenerateNormals();
for( int i = 0; i < pSrcTriMesh->GetControllerCount(); i++ )
{
pClonedObject->AttachController(pSrcTriMesh->GetController(i));
}
for( int i = 0; i < pSrcTriMesh->GetGlobalStateCount(); i++ )
{
pClonedObject->AttachGlobalState(pSrcTriMesh->GetGlobalState(i));
}
for( int i = 0; i < pSrcTriMesh->GetEffectCount(); i++ )
{
SEObjectPtr spCopiedEffect = pSrcTriMesh->GetEffect(i)->Copy();
pClonedObject->AttachEffect((SEEffect*)(SEObject*)spCopiedEffect);
}
return pClonedObject;
}
//---------------------------------------------------------------------------
void ManagedUtility::GenerateNormalsForAll(SENode* pNode)
{
if( !pNode )
{
return;
}
for( int i = 0; i < pNode->GetCount(); i++ )
{
SESpatial* pChild = pNode->GetChild(i);
if( pChild )
{
if( DynamicCast<SENode>(pChild) )
{
GenerateNormalsForAll((SENode*)pChild);
}
else if( DynamicCast<SETriMesh>(pChild) )
{
((SETriMesh*)pChild)->GenerateNormals();
}
}
}
}
//---------------------------------------------------------------------------
void ManagedUtility::DetachAllEffectsForAll(SENode* pNode)
{
if( !pNode )
{
return;
}
pNode->DetachAllEffects();
for( int i = 0; i < pNode->GetCount(); i++ )
{
SESpatial* pChild = pNode->GetChild(i);
if( pChild )
{
if( DynamicCast<SENode>(pChild) )
{
DetachAllEffectsForAll((SENode*)pChild);
}
else
{
pChild->DetachAllEffects();
}
}
}
}
//---------------------------------------------------------------------------
void ManagedUtility::ModulateWithLightingEffectForAll(SENode* pNode)
{
if( !pNode )
{
return;
}
for( int i = 0; i < pNode->GetCount(); i++ )
{
SESpatial* pChild = pNode->GetChild(i);
if( pChild )
{
if( DynamicCast<SENode>(pChild) )
{
ModulateWithLightingEffectForAll((SENode*)pChild);
}
else if( DynamicCast<SETriMesh>(pChild) )
{
if( pChild->GetEffectCount() > 0 )
{
SEShaderEffect* pShaderEffect = DynamicCast<
SEShaderEffect>(pChild->GetEffect(0));
if( pShaderEffect )
{
if( pShaderEffect->GetPassCount() == 0 )
{
throw gcnew Exception("Pass count is zero");
}
SEAlphaState* pAState =
pShaderEffect->GetBlending(0);
pAState->SrcBlend = SEAlphaState::SBF_DST_COLOR;
pAState->DstBlend = SEAlphaState::DBF_ZERO;
}
}
}
}
}
}
//---------------------------------------------------------------------------
void ManagedUtility::MaterialTextureConditioner(SENode* pNode)
{
if( !pNode )
{
return;
}
for( int i = 0; i < pNode->GetCount(); i++ )
{
SESpatial* pChild = pNode->GetChild(i);
if( pChild )
{
if( DynamicCast<SENode>(pChild) )
{
MaterialTextureConditioner((SENode*)pChild);
}
else if( DynamicCast<SETriMesh>(pChild) )
{
SETriMesh* pMesh = (SETriMesh*)pChild;
pMesh->GenerateNormals();
pMesh->LightingMode = SEGeometry::GLM_USER;
std::string tempSubName = pMesh->GetName().substr(0, 4);
if( pMesh->GetEffectCount() > 0 )
{
SESkinMaterialTextureEffect* pEffect =
DynamicCast<SESkinMaterialTextureEffect>(
pMesh->GetEffect(0));
if( pEffect )
{
std::string tempBaseName = pEffect->GetPImageName(
0, 0);
int iBoneCount = pEffect->GetBoneCount();
SENode** apBones = SE_NEW SENode*[iBoneCount];
SETransformation* aOffset =
SE_NEW SETransformation[iBoneCount];
for( int i = 0; i < iBoneCount; i++ )
{
apBones[i] = pEffect->GetBones()[i];
aOffset[i] = pEffect->GetOffsets()[i];
}
SEEffect* pNewEffect = 0;
if( tempSubName == "Part" )
{
pNewEffect = SE_NEW SESkinMaterialTexture2L1Effect(
tempBaseName, "wood_01", iBoneCount, apBones,
aOffset);
}
else
{
pNewEffect = SE_NEW SESkinMaterialTextureL1Effect(
tempBaseName, iBoneCount, apBones, aOffset);
}
pMesh->DetachAllEffects();
pMesh->AttachEffect(pNewEffect);
}
SEMaterialTextureEffect* pEffect2 =
DynamicCast<SEMaterialTextureEffect>(
((SETriMesh*)pChild)->GetEffect(0));
if( pEffect2 )
{
std::string tempBaseName = pEffect2->GetPImageName(0, 0);
SEEffect* pNewEffect = 0;
if( tempSubName == "Part" || tempSubName == "Trun" )
{
pNewEffect = SE_NEW SEMaterialTexture2L1Effect(
tempBaseName, "wood_01");
}
else if( tempSubName == "Wall" )
{
pNewEffect = SE_NEW SETextureTileL1Effect("wall_01");
((SETextureTileL1Effect*)pNewEffect)->TileX = 8.0f;
((SETextureTileL1Effect*)pNewEffect)->TileY = 8.0f;
((SETextureTileL1Effect*)pNewEffect)->AmbientWeight
= 0.65f;
((SETextureTileL1Effect*)pNewEffect)->DiffuseWeight
= 0.2f;
((SETextureTileL1Effect*)pNewEffect)->SpecularWeight
= 0.01f;
}
else
{
pNewEffect = SE_NEW SEMaterialTextureL1Effect(
tempBaseName);
}
pChild->DetachAllEffects();
pChild->AttachEffect(pNewEffect);
}
}
if( tempSubName == "Bone" || tempSubName == "join" )
{
pMesh->DetachAllEffects();
pMesh->Culling = SESpatial::CULL_ALWAYS;
}
else if( tempSubName == "Glas" )
{
SEAlphaState* pAS = SE_NEW SEAlphaState;
pAS->BlendEnabled = true;
pMesh->AttachGlobalState(pAS);
SEZBufferState* pZS = SE_NEW SEZBufferState;
pZS->Writable = false;
pMesh->AttachGlobalState(pZS);
SEMaterialState* pMS =
(SEMaterialState*)pMesh->GetGlobalState(
SEGlobalState::MATERIAL);
if( pMS )
{
pMS->Ambient = SEColorRGB(0.1f, 0.1f, 0.1f);
pMS->Diffuse = SEColorRGB(0.1f, 0.1f, 0.1f);
pMS->Specular = SEColorRGB(1.0f, 1.0f, 1.0f);
pMS->Shininess = 100.0f;
}
}
}
}
}
}
//---------------------------------------------------------------------------
void ManagedUtility::DisableLightingConditioner(SENode* pNode)
{
if( !pNode )
{
return;
}
for( int i = 0; i < pNode->GetCount(); i++ )
{
SESpatial* pChild = pNode->GetChild(i);
if( pChild )
{
if( DynamicCast<SENode>(pChild) )
{
DisableLightingConditioner((SENode*)pChild);
}
else if( DynamicCast<SETriMesh>(pChild) )
{
SETriMesh* pMesh = (SETriMesh*)pChild;
pMesh->LightingMode = SEGeometry::GLM_USER;
}
}
}
}
//---------------------------------------------------------------------------
void ManagedUtility::ImageConditioner(SENode* pNode, SEImage* pImage)
{
if( !pNode || !pImage )
{
return;
}
for( int i = 0; i < pNode->GetCount(); i++ )
{
SESpatial* pChild = pNode->GetChild(i);
if( pChild )
{
if( DynamicCast<SENode>(pChild) )
{
ImageConditioner((SENode*)pChild, pImage);
}
else if( DynamicCast<SETriMesh>(pChild) )
{
SETriMesh* pMesh = (SETriMesh*)pChild;
if( pMesh->GetEffectCount() > 0 )
{
std::string tempSubName = pMesh->GetName().substr(0, 4);
if( tempSubName == "Part" || tempSubName == "Trun" )
{
SEMaterialTexture2L1Effect* pEffect =
DynamicCast<SEMaterialTexture2L1Effect>(
((SETriMesh*)pMesh)->GetEffect(0));
if( pEffect )
{
SEPixelShader* pPS = pEffect->GetPShader(0);
SETexture* pTexture = pPS->GetTexture(1);
if( pTexture )
{
pPS->SetImageName(1, pImage->GetName());
pTexture->SetImage(pImage);
pTexture->Release();
}
}
SESkinMaterialTexture2L1Effect* pEffect2 =
DynamicCast<SESkinMaterialTexture2L1Effect>(
((SETriMesh*)pMesh)->GetEffect(0));
if( pEffect2 )
{
SEPixelShader* pPS = pEffect2->GetPShader(0);
SETexture* pTexture = pPS->GetTexture(1);
if( pTexture )
{
pPS->SetImageName(1, pImage->GetName());
pTexture->SetImage(pImage);
pTexture->Release();
}
}
}
}
}
}
}
}
//---------------------------------------------------------------------------
void ManagedUtility::WallConditioner(SENode* pNode, SETextureTileL1Effect*
pEffect)
{
if( !pNode || !pEffect )
{
return;
}
for( int i = 0; i < pNode->GetCount(); i++ )
{
SESpatial* pChild = pNode->GetChild(i);
if( pChild )
{
if( DynamicCast<SENode>(pChild) )
{
WallConditioner((SENode*)pChild, pEffect);
}
else if( DynamicCast<SETriMesh>(pChild) )
{
SETriMesh* pMesh = (SETriMesh*)pChild;
if( pMesh->GetEffectCount() > 0 )
{
std::string tempSubName = pMesh->GetName().substr(0, 4);
if( tempSubName == "Wall" )
{
pMesh->DetachAllEffects();
pMesh->AttachEffect(pEffect);
}
}
}
}
}
}
//--------------------------------------------------------------------------- | [
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
]
| [
[
[
1,
481
]
]
]
|
a3076fbb2999ac12f832fca74030398fcad67223 | b5ad65ebe6a1148716115e1faab31b5f0de1b493 | /src/ModelEditor/MainFrm.cpp | 8b6fad05ba5a31814202bd328d26a9e42b072d7b | []
| no_license | gasbank/aran | 4360e3536185dcc0b364d8de84b34ae3a5f0855c | 01908cd36612379ade220cc09783bc7366c80961 | refs/heads/master | 2021-05-01T01:16:19.815088 | 2011-03-01T05:21:38 | 2011-03-01T05:21:38 | 1,051,010 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,483 | cpp | // MainFrm.cpp : implementation of the CMainFrame class
//
#include "stdafx.h"
#include "ModelEditor.h"
#include "MainFrm.h"
#include "ModelEditorDoc.h"
#include "ModelEditorView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CMainFrame
IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd)
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
ON_WM_CREATE()
ON_COMMAND(ID_VIEWTEST_ARNVIEW, &CMainFrame::OnViewtestArnview)
ON_COMMAND(ID_VIEWTEST_FIRSTVIEW, &CMainFrame::OnViewtestFirstview)
ON_UPDATE_COMMAND_UI(ID_VIEWTEST_ARNVIEW, &CMainFrame::OnUpdateViewtestArnview)
ON_UPDATE_COMMAND_UI(ID_VIEWTEST_FIRSTVIEW, &CMainFrame::OnUpdateViewtestFirstview)
END_MESSAGE_MAP()
static UINT indicators[] =
{
ID_SEPARATOR, // status line indicator
ID_INDICATOR_CAPS,
ID_INDICATOR_NUM,
ID_INDICATOR_SCRL,
};
// CMainFrame construction/destruction
CMainFrame::CMainFrame()
{
// TODO: add member initialization code here
m_pArnView = NULL;
m_pFirstView = NULL;
}
CMainFrame::~CMainFrame()
{
}
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
return -1;
if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP
| CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
!m_wndToolBar.LoadToolBar(IDR_MAINFRAME))
{
TRACE0("Failed to create toolbar\n");
return -1; // fail to create
}
if (!m_wndStatusBar.Create(this) ||
!m_wndStatusBar.SetIndicators(indicators,
sizeof(indicators)/sizeof(UINT)))
{
TRACE0("Failed to create status bar\n");
return -1; // fail to create
}
// TODO: Delete these three lines if you don't want the toolbar to be dockable
m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
EnableDocking(CBRS_ALIGN_ANY);
DockControlBar(&m_wndToolBar);
return 0;
}
BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
if( !CFrameWnd::PreCreateWindow(cs) )
return FALSE;
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return TRUE;
}
// CMainFrame diagnostics
#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
CFrameWnd::AssertValid();
}
void CMainFrame::Dump(CDumpContext& dc) const
{
CFrameWnd::Dump(dc);
}
#endif //_DEBUG
// CMainFrame message handlers
void CMainFrame::OnViewtestArnview()
{
if (GetActiveView() == m_pArnView)
return;
if (m_pArnView == NULL)
{
CRuntimeClass* pClass;
pClass = RUNTIME_CLASS(CArnView);
CCreateContext context;
context.m_pCurrentDoc = GetActiveDocument();
context.m_pNewViewClass = pClass;
m_pArnView = STATIC_DOWNCAST(CView, CreateView(&context));
m_pArnView->OnInitialUpdate();
}
GetActiveView()->ShowWindow(SW_HIDE);
m_pFirstView = GetActiveView();
SetActiveView(m_pArnView);
m_pArnView->ShowWindow(TRUE);
RecalcLayout();
}
void CMainFrame::OnViewtestFirstview()
{
if (GetActiveView() == m_pFirstView || m_pFirstView == NULL)
return;
GetActiveView()->ShowWindow(SW_HIDE);
SetActiveView(m_pFirstView);
m_pFirstView->ShowWindow(TRUE);
RecalcLayout();
}
void CMainFrame::OnUpdateViewtestArnview(CCmdUI *pCmdUI)
{
// TODO: Add your command update UI handler code here
//pCmdUI->Enable(FALSE);
}
void CMainFrame::OnUpdateViewtestFirstview(CCmdUI *pCmdUI)
{
// TODO: Add your command update UI handler code here
//pCmdUI->Enable(FALSE);
}
| [
"[email protected]"
]
| [
[
[
1,
162
]
]
]
|
4aea15f1104adaa007fa5ad2c55d4205adb8752d | 7f30cb109e574560873a5eb8bb398c027f85eeee | /src/wxSurfaceRenderingGui.cxx | cdf25789a43c5c25d79df8a84a6099ce98b9790a | []
| no_license | svn2github/MITO | e8fd0e0b6eebf26f2382f62660c06726419a9043 | 71d1269d7666151df52d6b5a98765676d992349a | refs/heads/master | 2021-01-10T03:13:55.083371 | 2011-10-14T15:40:14 | 2011-10-14T15:40:14 | 47,415,786 | 1 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 87,991 | cxx | /**
* \file wxSurfaceRenderingGui.cxx
* \brief File per la creazione della finestra 3D contenente il risultato del surface rendering
* \author ICAR-CNR Napoli
*/
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/busyinfo.h>
#include "wxSurfaceRenderingGui.h"
#include "itkVtkData.h"
#include "wxVtkViewer3d.h"
#include <vtkPolyDataMapper.h>
#include "icons/Zoom.xpm"
#include "icons/Dolly.xpm"
#include "icons/Cut3d.xpm"
#include "icons/Rot3d.xpm"
#include "icons/Move.xpm"
#include "icons/Rotate.xpm"
#include "icons/Axial.xpm"
#include "icons/Coronal.xpm"
#include "icons/Sagittal.xpm"
#include "icons/OppositeSagittal.xpm"
// Wii
#include "icons/Wii.xpm"
#include "vtkInteractorStyleWIITrackball.h"
#include <vtkInteractorStyleTrackballCamera.h>
#include "wxCDRatioDialog.h"
#include "wxMotionFactorDialog.h"
// shading
#include <wx/string.h>
#include <wx/stattext.h>
#include <wx/gdicmn.h>
#include <wx/font.h>
#include <wx/colour.h>
#include <wx/settings.h>
#include <wx/checkbox.h>
#include <wx/button.h>
#include <wx/gbsizer.h>
#include <wx/sizer.h>
#include <wx/frame.h>
#include <wx/clrpicker.h>
#include <wx/tglbtn.h>
#include "wxShadingDialog.h"
#include <vtkInteractorStyleTrackballActor.h>
#include "WiiCommandEvents.h"
#include "vtkMitoCustomCamera.h"
BEGIN_EVENT_TABLE(wxSurfaceRenderingGui, wxFrame)
EVT_ACTIVATE(wxSurfaceRenderingGui::onActivate)
EVT_BUTTON(id3d_moveTool,wxSurfaceRenderingGui::onMove)
EVT_BUTTON(id3d_dollyTool,wxSurfaceRenderingGui::onDolly)
EVT_BUTTON(id3d_zoomTool,wxSurfaceRenderingGui::onZoom)
EVT_BUTTON(id3d_rotateTool,wxSurfaceRenderingGui::onRotate)
EVT_BUTTON(id3d_3drotTool,wxSurfaceRenderingGui::onRotateAround)
EVT_BUTTON(id3d_AxialTool,wxSurfaceRenderingGui::onAxialView)
EVT_BUTTON(id3d_CorTool,wxSurfaceRenderingGui::onCoronalView)
EVT_BUTTON(id3d_SagTool,wxSurfaceRenderingGui::onSagittalView)
EVT_BUTTON(id3d_sagoppTool,wxSurfaceRenderingGui::onOppositeSagittalView)
EVT_BUTTON(id3d_shadingChangeButton,wxSurfaceRenderingGui::onChangeShadingParameters)
EVT_TOGGLEBUTTON(id3d_stereo,wxSurfaceRenderingGui::onStereo)
EVT_RADIOBUTTON(id3d_RADIOBUTTONGROUPInputDevice1,wxSurfaceRenderingGui::onChangeInputDevice)
EVT_RADIOBUTTON(id3d_RADIOBUTTONGROUPInputDevice2,wxSurfaceRenderingGui::onChangeInputDevice)
EVT_RADIOBUTTON(id3d_RADIOBUTTONGROUPCursorType1,wxSurfaceRenderingGui::onCursorType)
EVT_RADIOBUTTON(id3d_RADIOBUTTONGROUPCursorType2,wxSurfaceRenderingGui::onCursorType)
EVT_RADIOBUTTON(id3d_perspective,wxSurfaceRenderingGui::onProjectionTypePerspective)
EVT_RADIOBUTTON(id3d_parallel,wxSurfaceRenderingGui::onProjectionTypeParallel)
EVT_RADIOBUTTON(id3d_endoscopy,wxSurfaceRenderingGui::onProjectionTypeEndoscopy)
EVT_MENU(m_3d_3dviewerResetToInitialView,wxSurfaceRenderingGui::onResetView)
EVT_MENU(m_3d_StereoMode,wxSurfaceRenderingGui::onStereo)
EVT_MENU(m_3d_MoveSR,wxSurfaceRenderingGui::onMove)
EVT_MENU(m_3d_DollySR,wxSurfaceRenderingGui::onDolly)
EVT_MENU(m_3d_ZoomSR,wxSurfaceRenderingGui::onZoom)
EVT_MENU(m_3d_RotateSR,wxSurfaceRenderingGui::onRotate)
EVT_MENU(m_3d_RotateAroundSR,wxSurfaceRenderingGui::onRotateAround)
EVT_MENU(m_3d_AxialTool,wxSurfaceRenderingGui::onAxialView)
EVT_MENU(m_3d_CorTool,wxSurfaceRenderingGui::onCoronalView)
EVT_MENU(m_3d_SagTool,wxSurfaceRenderingGui::onSagittalView)
EVT_MENU(m_3d_sagoppTool,wxSurfaceRenderingGui::onOppositeSagittalView)
EVT_MENU(id3d_fileCloseWindow,wxSurfaceRenderingGui::onClose)
EVT_MENU(id3d_HelpAbout,wxSurfaceRenderingGui::onShowAboutDialog)
EVT_MENU(m_3d_3dviewerFullScreen,wxSurfaceRenderingGui::onFullScreen)
EVT_MENU(m_3d_StereoModeAnaglyph,wxSurfaceRenderingGui::onStereoModeAnaglyph)
EVT_MENU(m_3d_StereoModeActivePassive,wxSurfaceRenderingGui::onStereoModeActivePassive)
EVT_MENU(m_3d_StereoModeCheckerboard,wxSurfaceRenderingGui::onStereoModeCheckerboard)
EVT_MENU(m_3d_ModifyObserverDistance,wxSurfaceRenderingGui::onModifyObserverDistance)
EVT_MENU(id3d_WiiTool,wxSurfaceRenderingGui::onWii)
EVT_MENU(id3d_WiiConfigurationTool,wxSurfaceRenderingGui::onWiiConfiguration)
EVT_MENU(id3d_WiiChangeSceneIRInteraction,wxSurfaceRenderingGui::onWiiChangeSceneIRInteraction)
EVT_MENU(id3d_ModifyCDRatioFunction,wxSurfaceRenderingGui::onModifyCDRatioFunction)
EVT_MENU(id3d_ModifyMotionFactor,wxSurfaceRenderingGui::onModifyMotionFactor)
EVT_CHAR_HOOK(wxSurfaceRenderingGui::onChar)
EVT_CLOSE(wxSurfaceRenderingGui::onQuit)
END_EVENT_TABLE()
wxSurfaceRenderingGui::wxSurfaceRenderingGui(const wxString& title, const wxPoint& pos, const wxSize& size)
:wxFrame((wxFrame *)NULL, -1, title, pos, size, wxDEFAULT_FRAME_STYLE | wxMAXIMIZE) {
/*wxIcon icon;
icon.LoadFile("icon.ico",wxBITMAP_TYPE_ICO);
this->SetIcon(icon);*/
SetIcon(wxICON(MITO));
_selectedButton = id3d_3drotTool;
_POD = 600;
// inizializza contour, decimate and smoothing
_contourValue = 0;
_decimateValue = 0.50;
_smoothValue = 20.0;
// inizializza la parallasse
_parallax = 0;
// cursore 3D
_3DCursor = NULL;
_cellLocator = NULL;
_3DCursorIsOnModelSurface = false;
// Assi 3D passanti per il centro dell'oggetto
_3DAxesActor = NULL;
// inizializza lo zoom
_globalZoomFactor = 1;
// shading
_shadingAmbient = 0.10;
_shadingDiffuse = 1.00;
_shadingSpecular = 1.00;
_shadingSpecularPower = 50.0;
_shadingColourAmbient = wxColour(70,70,70);
_shadingColourDiffuse = wxColour(80,80,80);
_shadingColourSpecular = wxColour(200,200,200);
CreateSurfaceToolbar();
Createmenu();
}
void wxSurfaceRenderingGui::Createmenu() {
CreateStatusBar(3);
SetStatusText("Ready", 0);
wxMenu *menuFile = new wxMenu("", wxMENU_TEAROFF);
menuFile->Append(id3d_fileCloseWindow, "Close 3D Viewer\tCtrl-C");
wxMenu *menu3dViewer = new wxMenu("", wxMENU_TEAROFF);
menu3dViewer->Append(m_3d_3dviewerResetToInitialView, "Reset to initial view\tCtrl-R");
menu3dViewer->AppendSeparator();
menu3dViewer->Append(m_3d_CorTool, "Coronal View\tAlt-C");
menu3dViewer->Append(m_3d_SagTool, "Left Sagittal View\tAlt-L");
menu3dViewer->Append(m_3d_sagoppTool, "Right Sagittal View\tAlt-R");
menu3dViewer->Append(m_3d_AxialTool, "Axial View\tAlt-A");
menu3dViewer->AppendSeparator();
menu3dViewer->Append(m_3d_3dviewerFullScreen, "Full Screen\tCtrl-F");
menu3dViewer->AppendSeparator();
_menuStereoMode = new wxMenu;
//_menuStereoMode->Append(m_3d_StereoModeOff,_("Off\tCtrl-O"),_T(""),wxITEM_NORMAL);
_menuStereoMode->AppendCheckItem(m_3d_StereoModeAnaglyph,_("Anaglyph\tCtrl-Y"),_T(""));
(_menuStereoMode->AppendCheckItem(m_3d_StereoModeActivePassive,_("Active/Passive\tCtrl-S"),_T("")))->Check();
_menuStereoMode->AppendCheckItem(m_3d_StereoModeCheckerboard,_("Checkerboard\tCtrl-H"),_T(""));
_menuStereoMode->Append(m_3d_ModifyObserverDistance,_("Modify observer distance\tCtrl-B"),_T(""),wxITEM_NORMAL);
menu3dViewer->Append(m_3d_StereoMode,"Stereo Mode",_menuStereoMode);
wxMenu *menuInteraction = new wxMenu("", wxMENU_TEAROFF);
menuInteraction->Append(m_3d_RotateAroundSR,_("ROTATE 3D\tCtrl-A"),_T(""),wxITEM_NORMAL);
menuInteraction->Append(m_3d_DollySR,_("DOLLY\tCtrl-D"),_T(""),wxITEM_NORMAL);
menuInteraction->Append(m_3d_ZoomSR,_("ZOOM\tCtrl-Z"),_T(""),wxITEM_NORMAL);
menuInteraction->Append(m_3d_RotateSR,_("ROLL\tCtrl-T"),_T(""),wxITEM_NORMAL);
menuInteraction->Append(m_3d_MoveSR,_("PAN\tCtrl-M"),_T(""),wxITEM_NORMAL);
//menuInteraction->Append(m_3d_VOISR,_("VOI\tCtrl-V"),_T(""),wxITEM_NORMAL);
//menuInteraction->Enable(m_3d_VOISR,false);
menuInteraction->AppendSeparator();
menuInteraction->Append(id3d_WiiTool,_("Wiimote Quick Start\tCtrl-1"),_T(""),wxITEM_NORMAL);
menuInteraction->Append(id3d_WiiConfigurationTool,_("Wiimote Options\tCtrl-2"),_T(""),wxITEM_NORMAL);
menuInteraction->Append(id3d_WiiChangeSceneIRInteraction,_("Wiimote interaction technique switch\tCtrl-3"),_T(""),wxITEM_NORMAL);
menuInteraction->Append(id3d_ModifyCDRatioFunction,_("Modify pointing C-D ratio"),_T(""),wxITEM_NORMAL);
menuInteraction->AppendSeparator();
menuInteraction->Append(id3d_ModifyMotionFactor,_("Modify rotation Motion Factor"),_T(""),wxITEM_NORMAL);
wxMenu *menuHelp = new wxMenu("", wxMENU_TEAROFF);
menuHelp->Append(id3d_HelpAbout, "About MITO");
wxMenuBar *menuBar = new wxMenuBar();
menuBar->Append(menuFile, "File");
menuBar->Append(menu3dViewer, "3D Viewer");
menuBar->Append(menuInteraction, "Interaction");
menuBar->Append(menuHelp, "Help");
SetMenuBar(menuBar);
}
void wxSurfaceRenderingGui::CreateSurfaceToolbar() {
int altezzatool=25;
int altezzaradiobox=5;
int currentHorizontalPosition=10;
_surfaceToolbar = CreateToolBar( wxTB_FLAT|wxTB_HORIZONTAL|wxTB_TEXT, id3d_surfaceToolbar3D );
_surfaceToolbar->SetToolSeparation(30);
_surfaceToolbar->SetToolPacking(20);
// aggiunto da Luigi per compatibilità con Vista Aero
_surfaceToolbar->SetBackgroundColour(*wxBLACK);
_surfaceToolbar->SetForegroundColour(*wxWHITE);
wxBitmap zoomTool(this->GetBitmapResource(wxT("icons/Zoom.xpm")));
wxBitmap dollyTool(this->GetBitmapResource(wxT("icons/Dolly.xpm")));
wxBitmap voiTool(this->GetBitmapResource(wxT("icons/Cut3d.xpm")));
wxBitmap rot3dTool(this->GetBitmapResource(wxT("icons/Rot3d.xpm")));
wxBitmap rot3dcamTool(this->GetBitmapResource(wxT("icons/Rot3dcam.xpm")));
wxBitmap moveTool(this->GetBitmapResource(wxT("icons/Move.xpm")));
wxBitmap RotateTool(this->GetBitmapResource(wxT("icons/Rotate.xpm")));
wxBitmap AxialTool(this->GetBitmapResource(wxT("icons/Axial.xpm")));
wxBitmap CorTool(this->GetBitmapResource(wxT("icons/Coronal.xpm")));
wxBitmap SagTool(this->GetBitmapResource(wxT("icons/Sagittal.xpm")));
wxBitmap sagoppTool(this->GetBitmapResource(wxT("icons/OppositeSagittal.xpm")));
wxBitmap WiiTool(this->GetBitmapResource(wxT("icons/Wii.xpm")));
_surfaceToolbar->SetToolBitmapSize(wxSize(28,65));
_surfaceToolbar->Realize();
_surfaceToolbar->SetRows(1);
//Raggruppamento dei radioButton associati al inputDevice
wxPanel* inputDeviceRadioPanel = new wxPanel(_surfaceToolbar, wxID_ANY, wxPoint(currentHorizontalPosition,4));
inputDeviceRadioPanel->SetForegroundColour( *wxWHITE);
wxStaticBox* inputDeviceStaticBox = new wxStaticBox(inputDeviceRadioPanel, wxID_ANY, "Input");
wxStaticBoxSizer* inputDeviceRadioSizer = new wxStaticBoxSizer( inputDeviceStaticBox, wxVERTICAL );
wxBoxSizer* inputDeviceRow1 = new wxBoxSizer(wxHORIZONTAL);
wxRadioButton* inputDeviceB1 = new wxRadioButton(inputDeviceRadioPanel, id3d_RADIOBUTTONGROUPInputDevice1, "");
inputDeviceB1->SetForegroundColour(*wxWHITE);
inputDeviceB1->SetValue(true);
wxStaticText* inputDeviceB1Text = new wxStaticText(inputDeviceRadioPanel,wxID_ANY,"Mouse");
inputDeviceB1Text->SetForegroundColour(*wxWHITE);
inputDeviceRow1->Add( inputDeviceB1 , 0, wxLEFT, 0);
inputDeviceRow1->Add( inputDeviceB1Text , 0, wxLEFT | wxRIGHT, 0);
wxBoxSizer* inputDeviceRow2 = new wxBoxSizer(wxHORIZONTAL);
wxRadioButton* inputDeviceB2 = new wxRadioButton(inputDeviceRadioPanel, id3d_RADIOBUTTONGROUPInputDevice2, "");
wxStaticText* inputDeviceB2Text = new wxStaticText(inputDeviceRadioPanel,wxID_ANY,"Wiimote");
inputDeviceB2Text->SetForegroundColour(*wxWHITE);
inputDeviceRow2->Add( inputDeviceB2 , 0, wxRIGHT, 0);
inputDeviceRow2->Add( inputDeviceB2Text , 0, wxRIGHT, 0);
inputDeviceRadioSizer->Add( inputDeviceRow1 , 0, wxTOP , 6);
inputDeviceRadioSizer->Add( inputDeviceRow2 , 1, wxTOP | wxBOTTOM, 5);
inputDeviceRadioPanel->SetSizerAndFit(inputDeviceRadioSizer);
currentHorizontalPosition=currentHorizontalPosition+inputDeviceRadioPanel->GetSize().GetWidth();
//Contenitore raggruppante i Mouse Functions Buttons
currentHorizontalPosition=currentHorizontalPosition+5;
wxStaticBox* mouseFunctionsButtonsBox = new wxStaticBox(_surfaceToolbar, wxID_ANY, wxString("Mouse Functions"), wxPoint(currentHorizontalPosition,altezzaradiobox-1),wxSize(183,64));
currentHorizontalPosition=currentHorizontalPosition+5;
wxBitmapButton* button3drotTool = new wxBitmapButton(_surfaceToolbar, id3d_3drotTool, rot3dTool, wxPoint(currentHorizontalPosition,altezzatool), wxSize(31,31), wxBU_AUTODRAW|wxBU_EXACTFIT );
button3drotTool->SetToolTip(_("ROTATE 3D"));
_surfaceToolbar->AddControl(button3drotTool);
currentHorizontalPosition=currentHorizontalPosition+button3drotTool->GetSize().GetWidth()-1;
currentHorizontalPosition=currentHorizontalPosition+5;
wxBitmapButton* buttonDolly = new wxBitmapButton(_surfaceToolbar, id3d_dollyTool, dollyTool, wxPoint(currentHorizontalPosition,altezzatool), wxSize(31,31),wxBU_AUTODRAW|wxBU_EXACTFIT );
buttonDolly->SetToolTip(_("DOLLY"));
_surfaceToolbar->AddControl(buttonDolly);
currentHorizontalPosition=currentHorizontalPosition+buttonDolly->GetSize().GetWidth()-1;
currentHorizontalPosition=currentHorizontalPosition+5;
wxBitmapButton* buttonZoom = new wxBitmapButton(_surfaceToolbar, id3d_zoomTool,zoomTool, wxPoint(currentHorizontalPosition,altezzatool), wxSize(31,31),wxBU_AUTODRAW|wxBU_EXACTFIT );
buttonZoom->SetToolTip(_("ZOOM"));
_surfaceToolbar->AddControl(buttonZoom);
currentHorizontalPosition=currentHorizontalPosition+buttonZoom->GetSize().GetWidth()-1;
currentHorizontalPosition=currentHorizontalPosition+5;
wxBitmapButton* buttonRotate = new wxBitmapButton(_surfaceToolbar, id3d_rotateTool,RotateTool, wxPoint(currentHorizontalPosition,altezzatool), wxSize(31,31), wxBU_AUTODRAW|wxBU_EXACTFIT );
buttonRotate->SetToolTip(_("ROLL"));
_surfaceToolbar->AddControl(buttonRotate);
currentHorizontalPosition=currentHorizontalPosition+buttonRotate->GetSize().GetWidth()-1;
currentHorizontalPosition=currentHorizontalPosition+5;
wxBitmapButton* buttonMove = new wxBitmapButton(_surfaceToolbar, id3d_moveTool,moveTool, wxPoint(currentHorizontalPosition,altezzatool), wxSize(31,31), wxBU_AUTODRAW|wxBU_EXACTFIT );
buttonMove->SetToolTip(_("PAN"));
_surfaceToolbar->AddControl(buttonMove);
currentHorizontalPosition=currentHorizontalPosition+buttonMove->GetSize().GetWidth()-1;
//Raggruppamento dei radioButton associati al cursorType
currentHorizontalPosition=currentHorizontalPosition+13;
wxPanel* cursorTypeRadioPanel = new wxPanel(_surfaceToolbar, wxID_ANY, wxPoint(currentHorizontalPosition,4));
cursorTypeRadioPanel->SetForegroundColour( *wxWHITE);
wxStaticBox* cursorTypeStaticBox = new wxStaticBox(cursorTypeRadioPanel, wxID_ANY, "Cursor");
wxStaticBoxSizer* cursorTypeRadioSizer = new wxStaticBoxSizer( cursorTypeStaticBox, wxVERTICAL );
wxBoxSizer* cursorTypeRow1 = new wxBoxSizer(wxHORIZONTAL);
wxRadioButton* cursorTypeB1 = new wxRadioButton(cursorTypeRadioPanel, id3d_RADIOBUTTONGROUPCursorType1, "");
cursorTypeB1->SetForegroundColour(*wxWHITE);
cursorTypeB1->SetValue(true);
wxStaticText* cursorTypeB1Text = new wxStaticText(cursorTypeRadioPanel,wxID_ANY,"2D ");
cursorTypeB1Text->SetForegroundColour(*wxWHITE);
cursorTypeRow1->Add( cursorTypeB1 , 0, wxLEFT, 0);
cursorTypeRow1->Add( cursorTypeB1Text , 0, wxLEFT | wxRIGHT, 3);
wxBoxSizer* cursorTypeRow2 = new wxBoxSizer(wxHORIZONTAL);
wxRadioButton* cursorTypeB2 = new wxRadioButton(cursorTypeRadioPanel, id3d_RADIOBUTTONGROUPCursorType2, "");
wxStaticText* cursorTypeB2Text = new wxStaticText(cursorTypeRadioPanel,wxID_ANY,"3D ");
cursorTypeB2Text->SetForegroundColour(*wxWHITE);
cursorTypeRow2->Add( cursorTypeB2 , 0, wxRIGHT, 3);
cursorTypeRow2->Add( cursorTypeB2Text , 0, wxRIGHT, 5);
cursorTypeRadioSizer->Add( cursorTypeRow1 , 0, wxTOP , 6);
cursorTypeRadioSizer->Add( cursorTypeRow2 , 1, wxTOP | wxBOTTOM, 5);
cursorTypeRadioPanel->SetSizerAndFit(cursorTypeRadioSizer);
currentHorizontalPosition=currentHorizontalPosition+cursorTypeRadioPanel->GetSize().GetWidth();
//Raggruppamento Shading
currentHorizontalPosition=currentHorizontalPosition+5;
wxStaticBox* shadingStaticBox2 = new wxStaticBox(_surfaceToolbar, wxID_ANY, wxString("Surface properties"),wxPoint(currentHorizontalPosition,4),wxSize(205,64));
currentHorizontalPosition=currentHorizontalPosition+10;
wxPanel* shadingPanel = new wxPanel(_surfaceToolbar, wxID_ANY, wxPoint(currentHorizontalPosition,19),wxSize(190,50));
shadingPanel->SetForegroundColour( *wxWHITE);
wxBoxSizer* shadingBoxSizer = new wxBoxSizer(wxVERTICAL);
wxGridBagSizer* shadingGridBagSizer;
shadingGridBagSizer = new wxGridBagSizer( 2, 5 );
shadingGridBagSizer->SetFlexibleDirection( wxBOTH );
shadingGridBagSizer->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_NONE );
shadingGridBagSizer->SetEmptyCellSize( wxSize( -1,-1 ) );
wxString contourValueText = _T(" value: ") + wxString::Format(_T("%6i"), (int)_contourValue);
wxStaticText* contourValueStaticText = new wxStaticText( shadingPanel, id3d_contourValueText, contourValueText, wxDefaultPosition, wxDefaultSize, 0 );
contourValueStaticText->Wrap( -1 );
contourValueStaticText->SetForegroundColour( wxColour( 255, 255, 255 ) );
shadingGridBagSizer->Add( contourValueStaticText, wxGBPosition( 0, 0 ), wxGBSpan( 1, 2 ), wxALIGN_LEFT|wxALL, 0 );
wxButton* shadingChangeButton = new wxButton( shadingPanel, id3d_shadingChangeButton, wxT("change"), wxDefaultPosition, wxDefaultSize, 0 );
shadingChangeButton->SetForegroundColour( wxColour( 0, 0, 0 ) );
shadingGridBagSizer->Add( shadingChangeButton, wxGBPosition( 1, 0 ), wxGBSpan( 2, 2 ), wxALIGN_BOTTOM|wxALIGN_CENTER_HORIZONTAL, 0 );
wxStaticText* shadingAmbient = new wxStaticText( shadingPanel, wxID_ANY, wxT("ambient: "), wxPoint( -1,-1 ), wxDefaultSize, 0 );
shadingAmbient->Wrap( -1 );
shadingAmbient->SetForegroundColour( wxColour( 255, 255, 255 ) );
shadingGridBagSizer->Add( shadingAmbient, wxGBPosition( 0, 2 ), wxGBSpan( 1, 1 ), wxALIGN_RIGHT, 0 );
wxString ambientTxt = wxString::Format(_T("%1.2f"), _shadingAmbient);
wxStaticText* shadingAmbientText = new wxStaticText( shadingPanel, id3d_shadingAmbientText, ambientTxt, wxPoint( -1,-1 ), wxDefaultSize, 0 );
shadingAmbientText->Wrap( -1 );
shadingAmbientText->SetForegroundColour( wxColour( 255, 255, 255 ) );
shadingGridBagSizer->Add( shadingAmbientText, wxGBPosition( 0, 3 ), wxGBSpan( 1, 1 ), wxALIGN_RIGHT, 0 );
wxStaticText* shadingDiffuse = new wxStaticText( shadingPanel, wxID_ANY, wxT("diffuse: "), wxPoint( -1,-1 ), wxDefaultSize, 0 );
shadingDiffuse->Wrap( -1 );
shadingDiffuse->SetForegroundColour( wxColour( 255, 255, 255 ) );
shadingGridBagSizer->Add( shadingDiffuse, wxGBPosition( 1, 2 ), wxGBSpan( 1, 1 ), wxALIGN_RIGHT, 0 );
wxString diffuseTxt = wxString::Format(_T("%1.2f"), _shadingDiffuse);
wxStaticText* shadingDiffuseText = new wxStaticText( shadingPanel, id3d_shadingDiffuseText, diffuseTxt, wxPoint( -1,-1 ), wxDefaultSize, 0 );
shadingDiffuseText->Wrap( -1 );
shadingDiffuseText->SetForegroundColour( wxColour( 255, 255, 255 ) );
shadingGridBagSizer->Add( shadingDiffuseText, wxGBPosition( 1, 3 ), wxGBSpan( 1, 1 ), wxALIGN_RIGHT, 0 );
wxStaticText* shadingSpecular = new wxStaticText( shadingPanel, wxID_ANY, wxT("specular: "), wxPoint( -1,-1 ), wxDefaultSize, 0 );
shadingSpecular->Wrap( -1 );
shadingSpecular->SetForegroundColour( wxColour( 255, 255, 255 ) );
shadingGridBagSizer->Add( shadingSpecular, wxGBPosition( 2, 2 ), wxGBSpan( 1, 1 ), wxALIGN_RIGHT, 0 );
wxString specularTxt = wxString::Format(_T("%1.2f"), _shadingSpecular);
wxString specularPowerTxt = wxString::Format(_T("%2.1f"), _shadingSpecularPower);
wxString specularAllTxt = specularTxt + _T(", ") + specularPowerTxt;
wxStaticText* shadingSpecularText = new wxStaticText( shadingPanel, id3d_shadingSpecularText, specularAllTxt, wxPoint( -1,-1 ), wxDefaultSize, 0 );
shadingSpecularText->Wrap( -1 );
shadingSpecularText->SetForegroundColour( wxColour( 255, 255, 255 ) );
shadingGridBagSizer->Add( shadingSpecularText, wxGBPosition( 2, 3 ), wxGBSpan( 1, 1 ), wxALIGN_RIGHT, 0 );
shadingBoxSizer->Add( shadingGridBagSizer, 0, 0, 0 );
shadingPanel->SetSizerAndFit( shadingBoxSizer );
currentHorizontalPosition=currentHorizontalPosition+shadingPanel->GetSize().GetWidth();
//Contenitore raggruppante Stereo e Parallel/Perspective/Endoscopy
currentHorizontalPosition=currentHorizontalPosition+13;
wxStaticBox* shadingStaticBoxViewMode = new wxStaticBox(_surfaceToolbar, wxID_ANY, wxString("View mode"),wxPoint(currentHorizontalPosition,4),wxSize(145,64));
currentHorizontalPosition=currentHorizontalPosition+8;
wxPanel* viewModePanel = new wxPanel(_surfaceToolbar, wxID_ANY, wxPoint(currentHorizontalPosition,19),wxSize(140,50));
viewModePanel->SetForegroundColour( *wxWHITE);
wxBoxSizer* viewModeBoxSizer = new wxBoxSizer(wxVERTICAL);
wxGridBagSizer* viewModeGridBagSizer;
viewModeGridBagSizer = new wxGridBagSizer( 2, 5 );
viewModeGridBagSizer->SetFlexibleDirection( wxBOTH );
viewModeGridBagSizer->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_NONE );
wxToggleButton* stereoToggleBtn = new wxToggleButton( viewModePanel, id3d_stereo, wxT("Stereo"), wxDefaultPosition, wxSize( 50,-1 ), 0 );
stereoToggleBtn->SetValue( false );
viewModeGridBagSizer->Add( stereoToggleBtn, wxGBPosition( 0, 0 ), wxGBSpan( 3, 1 ), wxALIGN_CENTER_VERTICAL|wxALL, 0 );
wxRadioButton* perspectiveRadioBtn = new wxRadioButton( viewModePanel, id3d_perspective, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
perspectiveRadioBtn->SetValue( true );
viewModeGridBagSizer->Add( perspectiveRadioBtn, wxGBPosition( 0, 1 ), wxGBSpan( 1, 1 ), wxALL, 0 );
wxStaticText* perspectiveStaticText = new wxStaticText( viewModePanel, wxID_ANY, wxT("Perspective"), wxDefaultPosition, wxDefaultSize, 0 );
perspectiveStaticText->Wrap( -1 );
perspectiveStaticText->SetForegroundColour( wxColour( 255, 255, 255 ) );
perspectiveStaticText->SetBackgroundColour( wxColour( 0, 0, 0 ) );
viewModeGridBagSizer->Add( perspectiveStaticText, wxGBPosition( 0, 2 ), wxGBSpan( 1, 1 ), wxALL, 0 );
wxRadioButton* parallelRadioBtn = new wxRadioButton( viewModePanel, id3d_parallel, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
viewModeGridBagSizer->Add( parallelRadioBtn, wxGBPosition( 1, 1 ), wxGBSpan( 1, 1 ), wxALL, 0 );
wxStaticText* parallelStaticText = new wxStaticText( viewModePanel, wxID_ANY, wxT("Parallel"), wxDefaultPosition, wxDefaultSize, 0 );
parallelStaticText->Wrap( -1 );
parallelStaticText->SetForegroundColour( wxColour( 255, 255, 255 ) );
parallelStaticText->SetBackgroundColour( wxColour( 0, 0, 0 ) );
viewModeGridBagSizer->Add( parallelStaticText, wxGBPosition( 1, 2 ), wxGBSpan( 1, 1 ), wxALL, 0 );
wxRadioButton* endoscopyRadioBtn = new wxRadioButton( viewModePanel, id3d_endoscopy, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
viewModeGridBagSizer->Add( endoscopyRadioBtn, wxGBPosition( 2, 1 ), wxGBSpan( 1, 1 ), wxALL, 0 );
wxStaticText* endoscopyStaticText = new wxStaticText( viewModePanel, wxID_ANY, wxT("Endoscopy"), wxDefaultPosition, wxDefaultSize, 0 );
endoscopyStaticText->Wrap( -1 );
endoscopyStaticText->SetForegroundColour( wxColour( 255, 255, 255 ) );
endoscopyStaticText->SetBackgroundColour( wxColour( 0, 0, 0 ) );
viewModeGridBagSizer->Add( endoscopyStaticText, wxGBPosition( 2, 2 ), wxGBSpan( 1, 1 ), wxALL, 0 );
viewModeBoxSizer->Add( viewModeGridBagSizer, 0, 0, 0 );
viewModePanel->SetSizerAndFit( viewModeBoxSizer );
currentHorizontalPosition=currentHorizontalPosition+viewModePanel->GetSize().GetWidth();
//Contenitore raggruppante i View Functions Buttons
currentHorizontalPosition=currentHorizontalPosition+12;
wxStaticBox* viewButtonsBox = new wxStaticBox(_surfaceToolbar, wxID_ANY, wxString("Views"), wxPoint(currentHorizontalPosition,altezzaradiobox-1),wxSize(147,64));
currentHorizontalPosition=currentHorizontalPosition+5;
wxBitmapButton* buttonAxialTool = new wxBitmapButton(_surfaceToolbar, id3d_AxialTool,AxialTool, wxPoint(currentHorizontalPosition,altezzatool), wxSize(31,31), wxBU_AUTODRAW|wxBU_EXACTFIT );
_surfaceToolbar->AddControl(buttonAxialTool);
buttonAxialTool->SetToolTip(_("Move to an axial view"));
currentHorizontalPosition=currentHorizontalPosition+buttonAxialTool->GetSize().GetWidth()-1;
currentHorizontalPosition=currentHorizontalPosition+5;
wxBitmapButton* buttonCorTool = new wxBitmapButton(_surfaceToolbar, id3d_CorTool,CorTool, wxPoint(currentHorizontalPosition,altezzatool), wxSize(31,31), wxBU_AUTODRAW|wxBU_EXACTFIT );
buttonCorTool->SetToolTip(_("Move to a coronal view"));
_surfaceToolbar->AddControl(buttonCorTool);
currentHorizontalPosition=currentHorizontalPosition+buttonCorTool->GetSize().GetWidth()-1;
currentHorizontalPosition=currentHorizontalPosition+5;
wxBitmapButton* buttonSagTool = new wxBitmapButton(_surfaceToolbar, id3d_SagTool,SagTool, wxPoint(currentHorizontalPosition,altezzatool), wxSize(31,31), wxBU_AUTODRAW|wxBU_EXACTFIT );
buttonSagTool->SetToolTip(_("Move to a left sagittal view"));
_surfaceToolbar->AddControl(buttonSagTool);
currentHorizontalPosition=currentHorizontalPosition+buttonSagTool->GetSize().GetWidth()-1;
currentHorizontalPosition=currentHorizontalPosition+5;
wxBitmapButton* buttonSagOppTool = new wxBitmapButton(_surfaceToolbar, id3d_sagoppTool,sagoppTool, wxPoint(currentHorizontalPosition,altezzatool), wxSize(31,31), wxBU_AUTODRAW|wxBU_EXACTFIT );
buttonSagOppTool->SetToolTip(_("Move to a right sagittal view"));
_surfaceToolbar->AddControl(buttonSagOppTool);
currentHorizontalPosition=currentHorizontalPosition+buttonSagOppTool->GetSize().GetWidth()-1;
this->SetToolBar(_surfaceToolbar);
(_surfaceToolbar->FindControl(id3d_3drotTool))->SetBackgroundColour( wxColour(255,255,0) );
}
wxSurfaceRenderingGui::~wxSurfaceRenderingGui() {
destroy3DCursor();
destroy3DAxes();
_mainGui=0;
this->Destroy();
}
wxBitmap wxSurfaceRenderingGui::GetBitmapResource( const wxString& name ){
wxUnusedVar(name);
if (name == _T("icons/Zoom.xpm"))
{
wxBitmap bitmap(zoom_xpm);
return bitmap;
}
if (name == _T("icons/Dolly.xpm"))
{
wxBitmap bitmap(dolly_xpm);
return bitmap;
}
if (name == _T("icons/Cut3d.xpm"))
{
wxBitmap bitmap(cut3d_xpm);
return bitmap;
}
else if (name == _T("icons/Rot3d.xpm"))
{
wxBitmap bitmap( rot3d_xpm);
return bitmap;
}
else if (name == _T("icons/Move.xpm"))
{
wxBitmap bitmap( move_xpm);
return bitmap;
}
else if (name == _T("icons/Rotate.xpm"))
{
wxBitmap bitmap( rotate_xpm);
return bitmap;
}
else if (name == _T("icons/Axial.xpm"))
{
wxBitmap bitmap( axial_xpm);
return bitmap;
}
else if (name == _T("icons/Coronal.xpm"))
{
wxBitmap bitmap( coronal_xpm);
return bitmap;
}
else if (name == _T("icons/Sagittal.xpm"))
{
wxBitmap bitmap( sagittal_xpm);
return bitmap;
}
else if (name == _T("icons/OppositeSagittal.xpm"))
{
wxBitmap bitmap( oppositesagittal_xpm);
return bitmap;
}
else if (name == _T("icons/Wii.xpm"))
{
wxBitmap bitmap( wii_xpm);
return bitmap;
}
return wxNullBitmap;
}
void wxSurfaceRenderingGui::onClose(wxCommandEvent& event) {
Close(TRUE);
}
void wxSurfaceRenderingGui::onQuit(wxCloseEvent& event) {
if ( _mainGui->onViewerQuit(_idViewer)){
event.Skip();
}
}
void wxSurfaceRenderingGui::onChar(wxKeyEvent & event)
{
if ( event.GetKeyCode() == 27 && ((appWxVtkInteractor*)_viewer3d->getWxWindow())->getInteractionType() == wiiSR )
this->onWii(wxCommandEvent());
//else event.Skip();
}
void wxSurfaceRenderingGui::onFullScreen(wxCommandEvent& event) {
appWxVtkInteractor* appWxVtkI = ((appWxVtkInteractor*)_viewer3d->getWxWindow());
if ( appWxVtkI->getInteractionType() != wiiSR )
this->ShowFullScreen(!this->IsFullScreen());
}
void wxSurfaceRenderingGui::onResetView(wxCommandEvent& event) {
wxWindowDisabler disabler;
wxBusyInfo wait("Please wait...");
wxBusyCursor cursor;
// 3d cursor disattivato
((wxRadioButton*)this->FindWindowById(id3d_RADIOBUTTONGROUPCursorType1,_surfaceToolbar))->SetValue(true);
((appWxVtkInteractor*)_viewer3d->getWxWindow())->set3DcursorOff();
this->hide3DCursor();
double* focalPoint = ((itkVtkData*)_mainGui->getDataHandler()->getData(_idData))->getVtkActor()->GetCenter();
_viewer3d->getRenderer()->GetActiveCamera()->SetFocalPoint(focalPoint[0], focalPoint[1], focalPoint[2]);
_viewer3d->getRenderer()->GetActiveCamera()->ComputeViewPlaneNormal();
_viewer3d->getRenderer()->GetActiveCamera()->SetViewUp(0, 1, 0);
_viewer3d->getRenderer()->GetActiveCamera()->OrthogonalizeViewUp();
_viewer3d->getRenderer()->GetActiveCamera()->SetPosition (focalPoint[0], focalPoint[1], focalPoint[2]+_distance);
_viewer3d->getRenderer()->GetActiveCamera()->SetViewUp(0, 1, 0);
(_surfaceToolbar->FindControl(_selectedButton))->SetBackgroundColour(wxNullColour);
(_surfaceToolbar->FindControl(id3d_3drotTool))->SetBackgroundColour( wxColour(255,255,0) );
_selectedButton = id3d_3drotTool;
((appWxVtkInteractor*)_viewer3d->getWxWindow())->setInteractionType(rotateAround3dSR);
// view mode
((wxRadioButton*)this->FindWindowById(id3d_perspective,_surfaceToolbar))->SetValue(true);
_viewer3d->getRenderer()->GetActiveCamera()->ParallelProjectionOff();
// stereo mode
((wxToggleButton*)this->FindWindowById(id3d_stereo,_surfaceToolbar))->SetValue(false);
_viewer3d->getRenderWindow()->SetStereoTypeToCrystalEyes();
_viewer3d->getRenderWindow()->StereoRenderOff();
_parallax = 0;
// inizializza lo zoom
//_zoomValuePerspectiveSR = 100;
//_zoomValueParallelSR = 100;
//_comboBoxZoom->SetValue("100%");
_viewer3d->getRenderer()->GetActiveCamera()->Zoom(1/_globalZoomFactor); // in realtà al momento lo zoom non viene mai usato
_globalZoomFactor = 1;
// shading
_shadingAmbient = 0.10;
_shadingDiffuse = 1.00;
_shadingSpecular = 1.00;
_shadingSpecularPower = 50.0;
_shadingColourAmbient = wxColour(70,70,70);
_shadingColourDiffuse = wxColour(80,80,80);
_shadingColourSpecular = wxColour(200,200,200);
this->updateShading( _shadingAmbient, _shadingDiffuse, _shadingSpecular, _shadingSpecularPower);
this->setInitialDistance();
try {
_viewer3d->updateViewer();
}
catch(...) {
wxMessageBox(_T("Study too large for your hardware! Try with a smaller data set"));
Close(TRUE);
return;
}
}
void wxSurfaceRenderingGui::onAxialView(wxCommandEvent& event) {
// rimuove e poi aggiunge il 3D cursor per evitare slittamenti della camera
if ( _3DCursor != NULL )
_viewer3d->getRenderer()->RemoveActor( _3DCursor );
// necessaria nel caso si sia ruotato il volume e non la camera
( (itkVtkData*)_mainGui->getDataHandler()->getData(_idData) )->getVtkActor()->SetOrientation(_initialOrientation);
( (itkVtkData*)_mainGui->getDataHandler()->getData(_idData) )->getVtkActor()->SetScale(_initialScale);
( (itkVtkData*)_mainGui->getDataHandler()->getData(_idData) )->getVtkActor()->SetPosition(_initialPosition);
float distance = _distance;
if (!((itkVtkData*)_mainGui->getDataHandler()->getData(_idData))->getImageViewPlane().compare("AXIAL")) {
_viewer3d->getRenderer()->GetActiveCamera()->SetFocalPoint (0, 0, 0);
_viewer3d->getRenderer()->GetActiveCamera()->SetPosition (0, 0, -1);
_viewer3d->getRenderer()->GetActiveCamera()->ComputeViewPlaneNormal();
_viewer3d->getRenderer()->GetActiveCamera()->SetViewUp(0, 1, 0);
_viewer3d->getRenderer()->GetActiveCamera()->OrthogonalizeViewUp();
_viewer3d->getRenderer()->ResetCamera();
}
else if (!((itkVtkData*)_mainGui->getDataHandler()->getData(_idData))->getImageViewPlane().compare("CORONAL")) {
_viewer3d->getRenderer()->GetActiveCamera()->SetFocalPoint (0, 0, 0);
_viewer3d->getRenderer()->GetActiveCamera()->SetPosition (0, -1, 0);
_viewer3d->getRenderer()->GetActiveCamera()->ComputeViewPlaneNormal();
_viewer3d->getRenderer()->GetActiveCamera()->SetViewUp(0, 0, 1);
_viewer3d->getRenderer()->GetActiveCamera()->OrthogonalizeViewUp();
_viewer3d->getRenderer()->ResetCamera();
}
else if (!((itkVtkData*)_mainGui->getDataHandler()->getData(_idData))->getImageViewPlane().compare("SAGITTAL")) {
_viewer3d->getRenderer()->GetActiveCamera()->SetFocalPoint (0, 0, 0);
_viewer3d->getRenderer()->GetActiveCamera()->SetPosition (0, -1, 0);
_viewer3d->getRenderer()->GetActiveCamera()->ComputeViewPlaneNormal();
_viewer3d->getRenderer()->GetActiveCamera()->SetViewUp(-1, 0, 0);
_viewer3d->getRenderer()->GetActiveCamera()->OrthogonalizeViewUp();
_viewer3d->getRenderer()->GetActiveCamera()->Dolly(1.5);
_viewer3d->getRenderer()->ResetCamera();
}
// Apply the same zoom
double vn[3], center[3];
_viewer3d->getRenderer()->GetActiveCamera()->GetFocalPoint(center);
_viewer3d->getRenderer()->GetActiveCamera()->GetViewPlaneNormal(vn);
_viewer3d->getRenderer()->GetActiveCamera()->SetPosition(center[0]+distance*vn[0], center[1]+distance*vn[1], center[2]+distance*vn[2]);
_viewer3d->getRenderer()->GetActiveCamera()->Zoom(1/_globalZoomFactor);
_globalZoomFactor=1;
_viewer3d->getRenderer()->ResetCameraClippingRange();
this->updateStereoView(false);
// ripristina il 3D cursor
if ( _3DCursor != NULL )
_viewer3d->getRenderer()->AddActor( _3DCursor );
try {
_viewer3d->updateViewer();
}
catch(...) {
wxMessageBox(_T("Study too large for your hardware! Try with a smaller data set"));
Close(TRUE);
return;
}
}
void wxSurfaceRenderingGui::onCoronalView(wxCommandEvent& event) {
// rimuove e poi aggiunge il 3D cursor per evitare slittamenti della camera
if ( _3DCursor != NULL )
_viewer3d->getRenderer()->RemoveActor( _3DCursor );
// necessaria nel caso si sia ruotato il volume e non la camera
( (itkVtkData*)_mainGui->getDataHandler()->getData(_idData) )->getVtkActor()->SetOrientation(_initialOrientation);
( (itkVtkData*)_mainGui->getDataHandler()->getData(_idData) )->getVtkActor()->SetScale(_initialScale);
( (itkVtkData*)_mainGui->getDataHandler()->getData(_idData) )->getVtkActor()->SetPosition(_initialPosition);
float distance = _distance;
if (!((itkVtkData*)_mainGui->getDataHandler()->getData(_idData))->getImageViewPlane().compare("CORONAL")) {
_viewer3d->getRenderer()->GetActiveCamera()->SetFocalPoint (0, 0, 0);
_viewer3d->getRenderer()->GetActiveCamera()->SetPosition (0, 0, 1);
_viewer3d->getRenderer()->GetActiveCamera()->ComputeViewPlaneNormal();
_viewer3d->getRenderer()->GetActiveCamera()->SetViewUp(0, 1, 0);
_viewer3d->getRenderer()->GetActiveCamera()->OrthogonalizeViewUp();
_viewer3d->getRenderer()->ResetCamera();
}
else if (!((itkVtkData*)_mainGui->getDataHandler()->getData(_idData))->getImageViewPlane().compare("AXIAL")) {
_viewer3d->getRenderer()->GetActiveCamera()->SetFocalPoint (0, 0, 0);
_viewer3d->getRenderer()->GetActiveCamera()->SetPosition (0, 1, 0);
_viewer3d->getRenderer()->GetActiveCamera()->ComputeViewPlaneNormal();
_viewer3d->getRenderer()->GetActiveCamera()->SetViewUp(0, 0, 1);
_viewer3d->getRenderer()->GetActiveCamera()->OrthogonalizeViewUp();
_viewer3d->getRenderer()->ResetCamera();
}
else if (!((itkVtkData*)_mainGui->getDataHandler()->getData(_idData))->getImageViewPlane().compare("SAGITTAL")) {
_viewer3d->getRenderer()->GetActiveCamera()->SetFocalPoint (0, 0, 0);
_viewer3d->getRenderer()->GetActiveCamera()->SetPosition (-1, 0, 0);
_viewer3d->getRenderer()->GetActiveCamera()->ComputeViewPlaneNormal();
_viewer3d->getRenderer()->GetActiveCamera()->SetViewUp(0, 1, 0);
_viewer3d->getRenderer()->GetActiveCamera()->OrthogonalizeViewUp();
_viewer3d->getRenderer()->ResetCamera();
}
// Apply the same zoom
double vn[3], center[3];
_viewer3d->getRenderer()->GetActiveCamera()->GetFocalPoint(center);
_viewer3d->getRenderer()->GetActiveCamera()->GetViewPlaneNormal(vn);
_viewer3d->getRenderer()->GetActiveCamera()->SetPosition(center[0]+distance*vn[0], center[1]+distance*vn[1], center[2]+distance*vn[2]);
_viewer3d->getRenderer()->GetActiveCamera()->Zoom(1/_globalZoomFactor);
_globalZoomFactor=1;
_viewer3d->getRenderer()->ResetCameraClippingRange();
this->updateStereoView(false);
// ripristina il 3D cursor
if ( _3DCursor != NULL )
_viewer3d->getRenderer()->AddActor( _3DCursor );
try {
_viewer3d->updateViewer();
}
catch(...) {
wxMessageBox(_T("Study too large for your hardware! Try with a smaller data set"));
Close(TRUE);
return;
}
}
void wxSurfaceRenderingGui::onSagittalView(wxCommandEvent& event) {
// rimuove e poi aggiunge il 3D cursor per evitare slittamenti della camera
if ( _3DCursor != NULL )
_viewer3d->getRenderer()->RemoveActor( _3DCursor );
// necessaria nel caso si sia ruotato il volume e non la camera
( (itkVtkData*)_mainGui->getDataHandler()->getData(_idData) )->getVtkActor()->SetOrientation(_initialOrientation);
( (itkVtkData*)_mainGui->getDataHandler()->getData(_idData) )->getVtkActor()->SetScale(_initialScale);
( (itkVtkData*)_mainGui->getDataHandler()->getData(_idData) )->getVtkActor()->SetPosition(_initialPosition);
float distance = _distance;
if (!((itkVtkData*)_mainGui->getDataHandler()->getData(_idData))->getImageViewPlane().compare("SAGITTAL")) {
_viewer3d->getRenderer()->GetActiveCamera()->SetFocalPoint (0, 0, 0);
_viewer3d->getRenderer()->GetActiveCamera()->SetPosition (0, 0, 1);
_viewer3d->getRenderer()->GetActiveCamera()->ComputeViewPlaneNormal();
_viewer3d->getRenderer()->GetActiveCamera()->SetViewUp(0, 1, 0);
_viewer3d->getRenderer()->GetActiveCamera()->OrthogonalizeViewUp();
_viewer3d->getRenderer()->GetActiveCamera()->Dolly(1.5);
_viewer3d->getRenderer()->ResetCamera();
}
else if (!((itkVtkData*)_mainGui->getDataHandler()->getData(_idData))->getImageViewPlane().compare("AXIAL")) {
_viewer3d->getRenderer()->GetActiveCamera()->SetFocalPoint (0, 0, 0);
_viewer3d->getRenderer()->GetActiveCamera()->SetPosition (-1, 0, 0);
_viewer3d->getRenderer()->GetActiveCamera()->ComputeViewPlaneNormal();
_viewer3d->getRenderer()->GetActiveCamera()->SetViewUp(0, 0, 1);
_viewer3d->getRenderer()->GetActiveCamera()->OrthogonalizeViewUp();
_viewer3d->getRenderer()->GetActiveCamera()->Dolly(1.5);
_viewer3d->getRenderer()->ResetCamera();
}
else if (!((itkVtkData*)_mainGui->getDataHandler()->getData(_idData))->getImageViewPlane().compare("CORONAL")) {
_viewer3d->getRenderer()->GetActiveCamera()->SetFocalPoint (0, 0, 0);
_viewer3d->getRenderer()->GetActiveCamera()->SetPosition (1, 0, 0);
_viewer3d->getRenderer()->GetActiveCamera()->ComputeViewPlaneNormal();
_viewer3d->getRenderer()->GetActiveCamera()->SetViewUp(0, 1, 0);
_viewer3d->getRenderer()->GetActiveCamera()->OrthogonalizeViewUp();
_viewer3d->getRenderer()->GetActiveCamera()->Dolly(1.5);
_viewer3d->getRenderer()->ResetCamera();
}
// Apply the same zoom
double vn[3], center[3];
_viewer3d->getRenderer()->GetActiveCamera()->GetFocalPoint(center);
_viewer3d->getRenderer()->GetActiveCamera()->GetViewPlaneNormal(vn);
_viewer3d->getRenderer()->GetActiveCamera()->SetPosition(center[0]+distance*vn[0], center[1]+distance*vn[1], center[2]+distance*vn[2]);
_viewer3d->getRenderer()->GetActiveCamera()->Zoom(1/_globalZoomFactor);
_globalZoomFactor=1;
_viewer3d->getRenderer()->ResetCameraClippingRange();
this->updateStereoView(false);
// ripristina il 3D cursor
if ( _3DCursor != NULL )
_viewer3d->getRenderer()->AddActor( _3DCursor );
try {
_viewer3d->updateViewer();
}
catch(...) {
wxMessageBox(_T("Study too large for your hardware! Try with a smaller data set"));
Close(TRUE);
return;
}
}
void wxSurfaceRenderingGui::onOppositeSagittalView(wxCommandEvent& event) {
// rimuove e poi aggiunge il 3D cursor per evitare slittamenti della camera
if ( _3DCursor != NULL )
_viewer3d->getRenderer()->RemoveActor( _3DCursor );
// necessaria nel caso si sia ruotato il volume e non la camera
( (itkVtkData*)_mainGui->getDataHandler()->getData(_idData) )->getVtkActor()->SetOrientation(_initialOrientation);
( (itkVtkData*)_mainGui->getDataHandler()->getData(_idData) )->getVtkActor()->SetScale(_initialScale);
( (itkVtkData*)_mainGui->getDataHandler()->getData(_idData) )->getVtkActor()->SetPosition(_initialPosition);
float distance = _distance;
if (!((itkVtkData*)_mainGui->getDataHandler()->getData(_idData))->getImageViewPlane().compare("SAGITTAL")) {
_viewer3d->getRenderer()->GetActiveCamera()->SetFocalPoint (0, 0, 0);
_viewer3d->getRenderer()->GetActiveCamera()->SetPosition (0, 0, -1);
_viewer3d->getRenderer()->GetActiveCamera()->ComputeViewPlaneNormal();
_viewer3d->getRenderer()->GetActiveCamera()->SetViewUp(0, 1, 0);
_viewer3d->getRenderer()->GetActiveCamera()->OrthogonalizeViewUp();
_viewer3d->getRenderer()->GetActiveCamera()->Dolly(1.5);
_viewer3d->getRenderer()->ResetCamera();
}
else if (!((itkVtkData*)_mainGui->getDataHandler()->getData(_idData))->getImageViewPlane().compare("AXIAL")) {
_viewer3d->getRenderer()->GetActiveCamera()->SetFocalPoint (0, 0, 0);
_viewer3d->getRenderer()->GetActiveCamera()->SetPosition (1, 0, 0);
_viewer3d->getRenderer()->GetActiveCamera()->ComputeViewPlaneNormal();
_viewer3d->getRenderer()->GetActiveCamera()->SetViewUp(0, 0, 1);
_viewer3d->getRenderer()->GetActiveCamera()->OrthogonalizeViewUp();
_viewer3d->getRenderer()->GetActiveCamera()->Dolly(1.5);
_viewer3d->getRenderer()->ResetCamera();
}
else if (!((itkVtkData*)_mainGui->getDataHandler()->getData(_idData))->getImageViewPlane().compare("CORONAL")) {
_viewer3d->getRenderer()->GetActiveCamera()->SetFocalPoint (0, 0, 0);
_viewer3d->getRenderer()->GetActiveCamera()->SetPosition (-1, 0, 0);
_viewer3d->getRenderer()->GetActiveCamera()->ComputeViewPlaneNormal();
_viewer3d->getRenderer()->GetActiveCamera()->SetViewUp(0, 1, 0);
_viewer3d->getRenderer()->GetActiveCamera()->OrthogonalizeViewUp();
_viewer3d->getRenderer()->GetActiveCamera()->Dolly(1.5);
_viewer3d->getRenderer()->ResetCamera();
}
// Apply the same zoom
double vn[3], center[3];
_viewer3d->getRenderer()->GetActiveCamera()->GetFocalPoint(center);
_viewer3d->getRenderer()->GetActiveCamera()->GetViewPlaneNormal(vn);
_viewer3d->getRenderer()->GetActiveCamera()->SetPosition(center[0]+distance*vn[0], center[1]+distance*vn[1], center[2]+distance*vn[2]);
_viewer3d->getRenderer()->GetActiveCamera()->Zoom(1/_globalZoomFactor);
_globalZoomFactor=1;
_viewer3d->getRenderer()->ResetCameraClippingRange();
this->updateStereoView(false);
// ripristina il 3D cursor
if ( _3DCursor != NULL )
_viewer3d->getRenderer()->AddActor( _3DCursor );
try {
_viewer3d->updateViewer();
}
catch(...) {
wxMessageBox(_T("Study too large for your hardware! Try with a smaller data set"));
Close(TRUE);
return;
}
}
void wxSurfaceRenderingGui::onChangeInputDevice(wxCommandEvent& event) {
if(event.GetId() == id3d_RADIOBUTTONGROUPInputDevice2 )
wxSurfaceRenderingGui::onWii(event);
}
void wxSurfaceRenderingGui::onStereo(wxCommandEvent& event)
{
if ( !( (wxToggleButton*)this->FindWindowById(id3d_stereo,_surfaceToolbar) )->GetValue() ) // modalità mono
{
_viewer3d->getRenderWindow()->StereoRenderOff();
try {
_viewer3d->updateViewer();
}
catch(...) {
wxMessageBox(_T("Study too large for your hardware! Try with a smaller data set"));
Close(TRUE);
return;
}
}
else // modalità stereo
{
if ( _menuStereoMode->FindItem(m_3d_StereoModeActivePassive)->IsChecked() )
onStereoModeActivePassive(event);
else if ( _menuStereoMode->FindItem(m_3d_StereoModeAnaglyph)->IsChecked() )
onStereoModeAnaglyph(event);
else
onStereoModeCheckerboard(event);
}
}
void wxSurfaceRenderingGui::onStereoModeAnaglyph(wxCommandEvent& event)
{
// disattiva la visione parallela se attiva
if ( ((wxRadioButton*)this->FindWindowById(id3d_parallel,_surfaceToolbar))->GetValue() )
{
((wxRadioButton*)this->FindWindowById(id3d_perspective,_surfaceToolbar))->SetValue(true);
this->onProjectionTypePerspective(event);
}
_menuStereoMode->FindItem(m_3d_StereoModeAnaglyph)->Check(true);
_menuStereoMode->FindItem(m_3d_StereoModeActivePassive)->Check(false);
_menuStereoMode->FindItem(m_3d_StereoModeCheckerboard)->Check(false);
((wxToggleButton*)this->FindWindowById(id3d_stereo,_surfaceToolbar))->SetValue(true);
_viewer3d->getRenderWindow()->SetStereoTypeToAnaglyph();
this->updateStereoView(true);
}
void wxSurfaceRenderingGui::onStereoModeCheckerboard(wxCommandEvent& event)
{
// disattiva la visione parallela se attiva
if ( ((wxRadioButton*)this->FindWindowById(id3d_parallel,_surfaceToolbar))->GetValue() )
{
((wxRadioButton*)this->FindWindowById(id3d_perspective,_surfaceToolbar))->SetValue(true);
this->onProjectionTypePerspective(event);
}
_menuStereoMode->FindItem(m_3d_StereoModeAnaglyph)->Check(false);
_menuStereoMode->FindItem(m_3d_StereoModeActivePassive)->Check(false);
_menuStereoMode->FindItem(m_3d_StereoModeCheckerboard)->Check(true);
((wxToggleButton*)this->FindWindowById(id3d_stereo,_surfaceToolbar))->SetValue(true);
_viewer3d->getRenderWindow()->SetStereoTypeToCheckerboard();
this->updateStereoView(true);
}
void wxSurfaceRenderingGui::onStereoModeActivePassive(wxCommandEvent& event)
{
// disattiva la visione parallela se attiva
if ( ((wxRadioButton*)this->FindWindowById(id3d_parallel,_surfaceToolbar))->GetValue() )
{
((wxRadioButton*)this->FindWindowById(id3d_perspective,_surfaceToolbar))->SetValue(true);
this->onProjectionTypePerspective(event);
}
_menuStereoMode->FindItem(m_3d_StereoModeAnaglyph)->Check(false);
_menuStereoMode->FindItem(m_3d_StereoModeActivePassive)->Check(true);
_menuStereoMode->FindItem(m_3d_StereoModeCheckerboard)->Check(false);
((wxToggleButton*)this->FindWindowById(id3d_stereo,_surfaceToolbar))->SetValue(true);
_viewer3d->getRenderWindow()->SetStereoTypeToCrystalEyes();
this->updateStereoView(true);
}
void wxSurfaceRenderingGui::onModifyObserverDistance(wxCommandEvent& event) {
const wxChar* PODChar;
do {
char message[60];
strcpy(message,"Set the distance from the screen in cm");
char initialValue[5];
sprintf(initialValue,"%d",_POD);
wxTextEntryDialog *dlg = new wxTextEntryDialog(this, message, "3D Volume Rendering", initialValue);
if (dlg->ShowModal() == wxID_OK) {
PODChar = dlg->GetValue().c_str();
dlg->Destroy();
}
else {
dlg->Destroy();
return;
}
} while(atoi(PODChar) < 10);
_POD = atoi(PODChar);
this->updateStereoView();
try {
_viewer3d->updateViewer();
}
catch(...) {
wxMessageBox(_T("Study too large for your hardware! Try with a smaller data set"));
Close(TRUE);
return;
}
}
void wxSurfaceRenderingGui::onCursorType( wxCommandEvent &event ) {
if(event.GetId() == id3d_RADIOBUTTONGROUPCursorType1) {
((appWxVtkInteractor*)_viewer3d->getWxWindow())->set3DcursorOff();
hide3DCursor();
}
else {
((appWxVtkInteractor*)_viewer3d->getWxWindow())->set3DcursorOn();
show3DCursor();
}
try {
_viewer3d->updateViewer();
}
catch(...) {
wxMessageBox(_T("Study too large for your hardware! Try with a smaller data set"));
Close(TRUE);
return;
}
}
void wxSurfaceRenderingGui::onProjectionTypeParallel(wxCommandEvent& event)
{
// abilita il 3d cursor
((wxRadioButton*)this->FindWindowById(id3d_RADIOBUTTONGROUPCursorType2,_surfaceToolbar))->Enable();
// disattiva lo stereo se presente
if ( ((wxToggleButton*)this->FindWindowById(id3d_stereo,_surfaceToolbar))->GetValue() )
{
((wxToggleButton*)this->FindWindowById(id3d_stereo,_surfaceToolbar))->SetValue(false);
this->onStereo(event);
}
_viewer3d->getRenderer()->GetActiveCamera()->ParallelProjectionOn();
// rimette a posto se c'è stato endoscopy
( (itkVtkData*)_mainGui->getDataHandler()->getData(_idData) )->getVtkActor()->SetOrientation(_initialOrientation);
( (itkVtkData*)_mainGui->getDataHandler()->getData(_idData) )->getVtkActor()->SetScale(_initialScale);
( (itkVtkData*)_mainGui->getDataHandler()->getData(_idData) )->getVtkActor()->SetPosition(_initialPosition);
_viewer3d->getRenderer()->GetActiveCamera()->SetFocalPoint( ( (itkVtkData*)_mainGui->getDataHandler()->getData(_idData) )->getVtkActor()->GetCenter() );
_viewer3d->getRenderer()->ResetCameraClippingRange();
// passo all'interactor style trackball camera
vtkInteractorStyleTrackballCamera *style = vtkInteractorStyleTrackballCamera::New();
((appWxVtkInteractor*)_viewer3d->getWxWindow())->SetInteractorStyle(style);
style->Delete();
try {
_viewer3d->updateViewer();
}
catch(...) {
wxMessageBox(_T("Study too large for your hardware! Try with a smaller data set"));
Close(TRUE);
return;
}
}
void wxSurfaceRenderingGui::onProjectionTypePerspective(wxCommandEvent& event)
{
// abilita il 3d cursor
((wxRadioButton*)this->FindWindowById(id3d_RADIOBUTTONGROUPCursorType2,_surfaceToolbar))->Enable();
_viewer3d->getRenderer()->GetActiveCamera()->ParallelProjectionOff();
// rimette a posto se c'è stato endoscopy
( (itkVtkData*)_mainGui->getDataHandler()->getData(_idData) )->getVtkActor()->SetOrientation(_initialOrientation);
( (itkVtkData*)_mainGui->getDataHandler()->getData(_idData) )->getVtkActor()->SetScale(_initialScale);
( (itkVtkData*)_mainGui->getDataHandler()->getData(_idData) )->getVtkActor()->SetPosition(_initialPosition);
_viewer3d->getRenderer()->GetActiveCamera()->SetFocalPoint( ( (itkVtkData*)_mainGui->getDataHandler()->getData(_idData) )->getVtkActor()->GetCenter() );
_viewer3d->getRenderer()->ResetCameraClippingRange();
// passo all'interactor style trackball camera
vtkInteractorStyleTrackballCamera *style = vtkInteractorStyleTrackballCamera::New();
((appWxVtkInteractor*)_viewer3d->getWxWindow())->SetInteractorStyle(style);
style->Delete();
this->updateStereoView(true);
}
void wxSurfaceRenderingGui::onProjectionTypeEndoscopy(wxCommandEvent& event)
{
// 3d cursor disattivato
((wxRadioButton*)this->FindWindowById(id3d_RADIOBUTTONGROUPCursorType1,_surfaceToolbar))->SetValue(true);
((wxRadioButton*)this->FindWindowById(id3d_RADIOBUTTONGROUPCursorType2,_surfaceToolbar))->Disable();
((appWxVtkInteractor*)_viewer3d->getWxWindow())->set3DcursorOff();
this->hide3DCursor();
_viewer3d->getRenderer()->GetActiveCamera()->ParallelProjectionOff();
// passo all'interactor style trackball actor
vtkInteractorStyleTrackballActor *style = vtkInteractorStyleTrackballActor::New();
((appWxVtkInteractor*)_viewer3d->getWxWindow())->SetInteractorStyle(style);
style->Delete();
this->updateStereoView(true);
}
void wxSurfaceRenderingGui::create3DAxes()
{
if (_3DAxesActor != NULL) return;
_3DAxes = vtkAxes::New();
_3DAxes->SymmetricOn();
vtkPolyDataMapper* axes_mapper = vtkPolyDataMapper::New();
axes_mapper->SetInputConnection(_3DAxes->GetOutputPort());
_3DAxesActor = vtkActor::New();
_3DAxesActor->SetMapper(axes_mapper);
_3DAxesActor->GetProperty()->SetAmbient(0.5);
_3DAxesActor->VisibilityOff();
_viewer3d->getRenderer()->AddActor( _3DAxesActor );
//axes_mapper->Delete();
}
void wxSurfaceRenderingGui::destroy3DAxes() {
if (_3DAxesActor == NULL) return;
_3DAxesActor->Delete();
_3DAxesActor = NULL;
_3DAxes->Delete();
}
void wxSurfaceRenderingGui::show3DAxes() {
if (_3DAxesActor == NULL) return;
//Cerco la max distanza tra i piani dei bounds
double b[6];
((itkVtkData*)_mainGui->getDataHandler()->getData(_idData))->getVtkActor()->GetBounds(b);
double borderPoints[8][3] = { {b[0],b[2],b[4]} ,
{b[0],b[2],b[5]} ,
{b[0],b[3],b[4]} ,
{b[0],b[3],b[5]} ,
{b[1],b[2],b[4]} ,
{b[1],b[2],b[5]} ,
{b[1],b[3],b[4]} ,
{b[1],b[3],b[5]} };
double maxDist = sqrt( pow(abs(borderPoints[0][0]-borderPoints[1][0]),2) +
pow(abs(borderPoints[0][1]-borderPoints[1][1]),2) +
pow(abs(borderPoints[0][2]-borderPoints[1][2]),2) );
double temp = sqrt( pow(abs(borderPoints[0][0]-borderPoints[2][0]),2) +
pow(abs(borderPoints[0][1]-borderPoints[2][1]),2) +
pow(abs(borderPoints[0][2]-borderPoints[2][2]),2) );
if (temp>maxDist) maxDist = temp;
temp = sqrt( pow(abs(borderPoints[0][0]-borderPoints[4][0]),2) +
pow(abs(borderPoints[0][1]-borderPoints[4][1]),2) +
pow(abs(borderPoints[0][2]-borderPoints[4][2]),2) );
if (temp>maxDist) maxDist = temp;
_3DAxes->SetScaleFactor(maxDist);
// LUIGI - così gli assi erano centrati al centro dell'oggetto
//double center[3];
//center[0] = (b[1] + b[0])/2.0;
//center[1] = (b[3] + b[2])/2.0;
//center[2] = (b[5] + b[4])/2.0;
// LUIGI - ora sono centrati sul focalPoint
double focalPosition[3];
_viewer3d->getRenderer()->GetActiveCamera()->GetFocalPoint(focalPosition);
_3DAxes->SetOrigin(focalPosition);
_3DAxesActor->VisibilityOn();
}
void wxSurfaceRenderingGui::hide3DAxes() {
if (_3DAxesActor == NULL) return;
_3DAxesActor->VisibilityOff();
}
void wxSurfaceRenderingGui::create3DCursor()
{
if (_3DCursor != NULL) return;
double bounds[6];
((itkVtkData*)_mainGui->getDataHandler()->getData(_idData))->getVtkActor()->GetBounds(bounds);
double radius = ( bounds[1]-bounds[0] + bounds[3]-bounds[2] + bounds[5]-bounds[4] ) / 300;
vtkSphereSource* _3DCursorSource = vtkSphereSource::New();
_3DCursorSource->SetRadius(radius);
_3DCursorSource->SetPhiResolution(20);
_3DCursorSource->SetThetaResolution(20);
vtkDataSetMapper* _3DCursorMapper = vtkDataSetMapper::New();
_3DCursorMapper->SetInput(_3DCursorSource->GetOutput());
_3DCursorMapper->ImmediateModeRenderingOn();
_3DCursor = vtkActor::New();
_3DCursor->SetMapper( _3DCursorMapper );
_3DCursor->GetProperty()->SetColor(1,1,0);
_viewer3d->getRenderer()->AddActor( _3DCursor );
_3DCursor->VisibilityOff();
_3DCursorSource->Delete();
_3DCursorMapper->Delete();
double focalPosition[3];
_viewer3d->getRenderer()->GetActiveCamera()->GetFocalPoint(focalPosition);
_3DCursor->SetPosition(focalPosition);
// Build a cell locator
_cellLocator = vtkCellLocator::New();
_cellLocator->SetDataSet( ((itkVtkData*)_mainGui->getDataHandler()->getData(_idData))->getVtkActor()->GetMapper()->GetInput() );
_cellLocator->BuildLocator();
}
void wxSurfaceRenderingGui::destroy3DCursor()
{
if (_3DCursor == NULL) return;
_cellLocator->Delete();
_3DCursor->Delete();
_3DCursor = NULL;
_cellLocator = NULL;
}
bool wxSurfaceRenderingGui::intersectingModelSurface(long x, long y, double * point)
{
if (_cellLocator == NULL) return false;
double closest, farthest;
this->getBoundsDepthInfo(closest, farthest);
vtkRenderer* ren = _viewer3d->getRenderer();
appWxVtkInteractor* appWxVtkI = ((appWxVtkInteractor*)_viewer3d->getWxWindow());
// Intersect with line
double p1[4]; double p2[4];
double t, pcoords[3]; int subId;
appWxVtkI->GetInteractorStyle()->ComputeDisplayToWorld( ren, x, y, closest, p1);
appWxVtkI->GetInteractorStyle()->ComputeDisplayToWorld( ren, x, y, farthest, p2);
double distance = sqrt(vtkMath::Distance2BetweenPoints(p1,p2));
_3DCursorIsOnModelSurface = _cellLocator->IntersectWithLine(p1, p2, 1/distance, t, point, pcoords, subId);
return _3DCursorIsOnModelSurface;
}
void wxSurfaceRenderingGui::get3DCursorDisplayPosition(int & x, int & y, bool flipY)
{
if (_3DCursor == NULL) return;
appWxVtkInteractor* appWxVtkI = ((appWxVtkInteractor*)_viewer3d->getWxWindow());
vtkRenderer* ren = _viewer3d->getRenderer();
double worldPosition[3],displayPosition[3];
_3DCursor->GetPosition( worldPosition );
appWxVtkI->GetInteractorStyle()->ComputeWorldToDisplay( ren, worldPosition[0], worldPosition[1],
worldPosition[2], displayPosition);
x = displayPosition[0];
y = displayPosition[1];
if (flipY)
{
int* size = ren->GetRenderWindow()->GetSize();
y = size[1] - y;
}
return;
}
bool wxSurfaceRenderingGui::set3DCursorPosition(long x, long y, bool flipY)
{
if (_3DCursor == NULL) return false;
vtkRenderer* ren = _viewer3d->getRenderer();
appWxVtkInteractor* appWxVtkI = ((appWxVtkInteractor*)_viewer3d->getWxWindow());
if (flipY)
{
int* size = ren->GetRenderWindow()->GetSize();
y = size[1] - y;
}
// Intersect with line
double point[3];
if ( intersectingModelSurface(x,y,point) )
{
_3DCursor->SetPosition(point[0],point[1],point[2]);
_3DCursor->GetProperty()->SetColor(1,1,0);
return true;
}
else
{
double focalDepth, focalPosition[3],newPosition[4];
ren->GetActiveCamera()->GetFocalPoint(focalPosition);
appWxVtkI->GetInteractorStyle()->ComputeWorldToDisplay( ren, focalPosition[0], focalPosition[1],
focalPosition[2], focalPosition);
focalDepth = focalPosition[2];
appWxVtkI->GetInteractorStyle()->ComputeDisplayToWorld( ren, x, y, focalDepth, newPosition);
_3DCursor->SetPosition( newPosition[0], newPosition[1], newPosition[2]);
_3DCursor->GetProperty()->SetColor(1,1,1);
return false;
}
}
bool wxSurfaceRenderingGui::is3DCursorBeyondFocalPlane()
{
double* versor = _viewer3d->getRenderer()->GetActiveCamera()->GetDirectionOfProjection();
double focalPosition[3], cursorPosition[3];
_viewer3d->getRenderer()->GetActiveCamera()->GetFocalPoint(focalPosition);
_3DCursor->GetPosition(cursorPosition);
double cursorProjection, focalProjection;
cursorProjection = versor[0] * cursorPosition[0] + versor[1] * cursorPosition[1] + versor[2] * cursorPosition[2];
focalProjection = versor[0] * focalPosition[0] + versor[1] * focalPosition[1] + versor[2] * focalPosition[2];
return (cursorProjection>focalProjection);
}
void wxSurfaceRenderingGui::show3DCursor()
{
if (_3DCursor == NULL) return;
_3DCursor->VisibilityOn();
}
void wxSurfaceRenderingGui::hide3DCursor()
{
if (_3DCursor == NULL) return;
_3DCursor->VisibilityOff();
}
void wxSurfaceRenderingGui::getBoundsDepthInfo(double & closest, double & farthest)
{
double bounds[6];
((itkVtkData*)_mainGui->getDataHandler()->getData(_idData))->getVtkActor()->GetBounds(bounds);
double temp[3];
closest = 1.0;
farthest = -1.0;
double borderPoints[8][3] = { {bounds[0],bounds[2],bounds[4]} ,
{bounds[0],bounds[2],bounds[5]} ,
{bounds[0],bounds[3],bounds[4]} ,
{bounds[0],bounds[3],bounds[5]} ,
{bounds[1],bounds[2],bounds[4]} ,
{bounds[1],bounds[2],bounds[5]} ,
{bounds[1],bounds[3],bounds[4]} ,
{bounds[1],bounds[3],bounds[5]} };
for (int i = 0; i<8; i++ )
{
((appWxVtkInteractor*)_viewer3d->getWxWindow())->GetInteractorStyle()->ComputeWorldToDisplay( _viewer3d->getRenderer(), borderPoints[i][0], borderPoints[i][1], borderPoints[i][2], temp);
if (temp[2]>1) { // camera nel bounding box
temp[2]=0.999999;
farthest=0.999999;
closest=-0.999999;
}
if ( temp[2] > farthest ) farthest = temp[2];
if ( temp[2] < closest ) closest = temp[2];
}
}
void wxSurfaceRenderingGui::onWiiConfiguration( wxCommandEvent &event )
{
appWxVtkInteractor* appWxVtkI = ( (appWxVtkInteractor*)_viewer3d->getWxWindow() );
wxWiiManager* WiiManager = appWxVtkI->getWiiManager( _viewer3d );
if ( appWxVtkI->getInteractionType() == wiiSR ) //Operazioni da fare in uscita dalla modalità Wii
{
//controllo se posso uscire o meno
if ( (appWxVtkI->idWiiEnabled != AnyWiiEnabled) || (WiiManager->WiiPointing_num) ) return;
else if (appWxVtkI->getInteractionType() == voi3dVRwii) appWxVtkI->InvokeEvent(vtkWiiHomeDown,NULL);
//if (!appWxVtkI->closeWiiAbility()) return;
//_viewer3d->showLeftTopInfo();
appWxVtkI->setInteractionType(rotateAround3dSR);
appWxVtkI->closeWiiManager();
_selectedButton = id3d_rotateTool;
double currentFactor = ((vtkInteractorStyleWIITrackball*)appWxVtkI->GetInteractorStyle())->GetMotionFactor();
vtkInteractorStyleTrackballCamera *style = vtkInteractorStyleTrackballCamera::New();
appWxVtkI->SetInteractorStyle(style);
style->Delete();
((vtkInteractorStyleTrackballCamera*)appWxVtkI->GetInteractorStyle())->SetMotionFactor ( currentFactor );
int x,y;
this->GetSize(&x,&y);
this->WarpPointer(x/2,y/2);
//_viewer3d->getRenderWindow()->ShowCursor();
this->show3DCursor();
// full screen nascondendo l'oggetto
double focalPoint[3];
_viewer3d->getRenderer()->GetActiveCamera()->GetFocalPoint(focalPoint);
_viewer3d->getRenderer()->GetActiveCamera()->SetFocalPoint(focalPoint[0]+10000,focalPoint[1]+10000,focalPoint[2]+10000);
_viewer3d->getRenderWindow()->Render();
wglMakeCurrent(NULL, NULL);
try {
_viewer3d->updateViewer();
}
catch(...) {
wxMessageBox(_T("Study too large for your hardware! Try with a smaller data set"));
Close(TRUE);
return;
}
this->ShowFullScreen(false);
_viewer3d->getRenderer()->GetActiveCamera()->SetFocalPoint(focalPoint);
_viewer3d->getRenderWindow()->Render();
wglMakeCurrent(NULL, NULL);
try {
_viewer3d->updateViewer();
}
catch(...) {
wxMessageBox(_T("Study too large for your hardware! Try with a smaller data set"));
Close(TRUE);
return;
}
((wxRadioButton*)this->FindWindowById(id3d_RADIOBUTTONGROUPInputDevice1,_surfaceToolbar))->SetValue(true);
}
else if ( WiiManager->SetupGui(_viewer3d->getWxWindow()) )
{
// passa alla visione perspective
if ( !( ((wxRadioButton*)this->FindWindowById(id3d_perspective,_surfaceToolbar))->GetValue() ) )
{
((wxRadioButton*)this->FindWindowById(id3d_perspective,_surfaceToolbar))->SetValue(true);
this->onProjectionTypePerspective(event);
}
_selectedButton = id3d_WiiTool;
/*
vtkInteractorStyleWII *style = vtkInteractorStyleWII::New();
appWxVtkI->SetInteractorStyle(style);
style->Delete();
*/
double currentFactor = ((vtkInteractorStyleTrackballCamera*)appWxVtkI->GetInteractorStyle())->GetMotionFactor();
vtkInteractorStyleWIITrackball *style = vtkInteractorStyleWIITrackball::New();
appWxVtkI->SetInteractorStyle(style);
style->setupEventObservers(appWxVtkI);
style->Delete();
((vtkInteractorStyleWIITrackball*)appWxVtkI->GetInteractorStyle())->SetMotionFactor ( currentFactor );
int x,y;
this->GetSize(&x,&y);
this->WarpPointer(x,y);
//_viewer3d->getRenderWindow()->HideCursor();
this->hide3DCursor();
// full screen nascondendo l'oggetto
double focalPoint[3];
_viewer3d->getRenderer()->GetActiveCamera()->GetFocalPoint(focalPoint);
_viewer3d->getRenderer()->GetActiveCamera()->SetFocalPoint(focalPoint[0]+10000,focalPoint[1]+10000,focalPoint[2]+10000);
_viewer3d->getRenderWindow()->Render();
wglMakeCurrent(NULL, NULL);
try {
_viewer3d->updateViewer();
}
catch(...) {
wxMessageBox(_T("Study too large for your hardware! Try with a smaller data set"));
Close(TRUE);
return;
}
this->ShowFullScreen(true);
_viewer3d->getRenderer()->GetActiveCamera()->SetFocalPoint(focalPoint);
_viewer3d->getRenderWindow()->Render();
wglMakeCurrent(NULL, NULL);
//_viewer3d->hideLeftTopInfo();
try {
_viewer3d->updateViewer();
}
catch(...) {
wxMessageBox(_T("Study too large for your hardware! Try with a smaller data set"));
Close(TRUE);
return;
}
double bounds[6];
((itkVtkData*)_mainGui->getDataHandler()->getData(_idData))->getVtkActor()->GetBounds(bounds);
double radius = (bounds[1]-bounds[0]+bounds[3]-bounds[2]+bounds[5]-bounds[4])*0.02/3;
WiiManager->setPointerRadius(radius);
WiiManager->Start();
appWxVtkI->setInteractionType(wiiSR);
appWxVtkI->initInteractionSignals();
appWxVtkI->WiiManagerStarted = true;
((wxRadioButton*)this->FindWindowById(id3d_RADIOBUTTONGROUPInputDevice2,_surfaceToolbar))->SetValue(true);
}
else {
appWxVtkI->closeWiiManager();
((wxRadioButton*)this->FindWindowById(id3d_RADIOBUTTONGROUPInputDevice1,_surfaceToolbar))->SetValue(true);
}
}
void wxSurfaceRenderingGui::onWii( wxCommandEvent &event )
{
appWxVtkInteractor* appWxVtkI = ( (appWxVtkInteractor*)_viewer3d->getWxWindow() );
wxWiiManager* WiiManager = appWxVtkI->getWiiManager( _viewer3d );
if ( appWxVtkI->getInteractionType() == wiiSR ) //Operazioni da fare in uscita dalla modalità Wii
{
//controllo se posso uscire o meno
//if ( (appWxVtkI->idWiiEnabled != AnyWiiEnabled) || (WiiManager->WiiPointing_num) ) return;
//else if (appWxVtkI->getInteractionType() == voi3dVRwii) appWxVtkI->InvokeEvent(vtkWiiHomeDown,NULL);
//if (!appWxVtkI->closeWiiAbility()) return;
//_viewer3d->showLeftTopInfo();
appWxVtkI->setInteractionType(rotateAround3dSR);
appWxVtkI->closeWiiManager();
_selectedButton = id3d_rotateTool;
double currentFactor = ((vtkInteractorStyleWIITrackball*)appWxVtkI->GetInteractorStyle())->GetMotionFactor();
vtkInteractorStyleTrackballCamera *style = vtkInteractorStyleTrackballCamera::New();
appWxVtkI->SetInteractorStyle(style);
style->Delete();
((vtkInteractorStyleTrackballCamera*)appWxVtkI->GetInteractorStyle())->SetMotionFactor ( currentFactor );
int x,y;
this->GetSize(&x,&y);
this->WarpPointer(x/2,y/2);
//_viewer3d->getRenderWindow()->ShowCursor();
this->show3DCursor();
// full screen nascondendo l'oggetto
double focalPoint[3];
_viewer3d->getRenderer()->GetActiveCamera()->GetFocalPoint(focalPoint);
_viewer3d->getRenderer()->GetActiveCamera()->SetFocalPoint(focalPoint[0]+10000,focalPoint[1]+10000,focalPoint[2]+10000);
//_viewer3d->getRenderWindow()->Render();
//wglMakeCurrent(NULL, NULL);
try {
_viewer3d->updateViewer();
}
catch(...) {
wxMessageBox(_T("Study too large for your hardware! Try with a smaller data set"));
Close(TRUE);
return;
}
this->ShowFullScreen(false);
_viewer3d->getRenderer()->GetActiveCamera()->SetFocalPoint(focalPoint);
_viewer3d->getRenderWindow()->Render();
//wglMakeCurrent(NULL, NULL);
try {
_viewer3d->updateViewer();
}
catch(...) {
wxMessageBox(_T("Study too large for your hardware! Try with a smaller data set"));
Close(TRUE);
return;
}
((wxRadioButton*)this->FindWindowById(id3d_RADIOBUTTONGROUPInputDevice1,_surfaceToolbar))->SetValue(true);
}
else if ( WiiManager->QuickSetupGui(_viewer3d->getWxWindow()) )
{
// passa alla visione perspective
if ( !( ((wxRadioButton*)this->FindWindowById(id3d_perspective,_surfaceToolbar))->GetValue() ) )
{
((wxRadioButton*)this->FindWindowById(id3d_perspective,_surfaceToolbar))->SetValue(true);
this->onProjectionTypePerspective(event);
}
_selectedButton = id3d_WiiTool;
/*
vtkInteractorStyleWII *style = vtkInteractorStyleWII::New();
appWxVtkI->SetInteractorStyle(style);
style->Delete();
*/
double currentFactor = ((vtkInteractorStyleTrackballCamera*)appWxVtkI->GetInteractorStyle())->GetMotionFactor();
vtkInteractorStyleWIITrackball *style = vtkInteractorStyleWIITrackball::New();
appWxVtkI->SetInteractorStyle(style);
style->setupEventObservers(appWxVtkI);
style->Delete();
((vtkInteractorStyleWIITrackball*)appWxVtkI->GetInteractorStyle())->SetMotionFactor ( currentFactor );
int x,y;
this->GetSize(&x,&y);
this->WarpPointer(x,y);
//_viewer3d->getRenderWindow()->HideCursor();
this->hide3DCursor();
// full screen nascondendo l'oggetto
double focalPoint[3];
_viewer3d->getRenderer()->GetActiveCamera()->GetFocalPoint(focalPoint);
_viewer3d->getRenderer()->GetActiveCamera()->SetFocalPoint(focalPoint[0]+10000,focalPoint[1]+10000,focalPoint[2]+10000);
//_viewer3d->getRenderWindow()->Render();
//wglMakeCurrent(NULL, NULL);
try {
_viewer3d->updateViewer();
}
catch(...) {
wxMessageBox(_T("Study too large for your hardware! Try with a smaller data set"));
Close(TRUE);
return;
}
this->ShowFullScreen(true);
_viewer3d->getRenderer()->GetActiveCamera()->SetFocalPoint(focalPoint);
_viewer3d->getRenderWindow()->Render();
//wglMakeCurrent(NULL, NULL);
//_viewer3d->hideLeftTopInfo();
try {
_viewer3d->updateViewer();
}
catch(...) {
wxMessageBox(_T("Study too large for your hardware! Try with a smaller data set"));
Close(TRUE);
return;
}
double bounds[6];
((itkVtkData*)_mainGui->getDataHandler()->getData(_idData))->getVtkActor()->GetBounds(bounds);
double radius = (bounds[1]-bounds[0]+bounds[3]-bounds[2]+bounds[5]-bounds[4])*0.02/3;
WiiManager->setPointerRadius(radius);
WiiManager->Start();
appWxVtkI->setInteractionType(wiiSR);
appWxVtkI->initInteractionSignals();
appWxVtkI->WiiManagerStarted = true;
((wxRadioButton*)this->FindWindowById(id3d_RADIOBUTTONGROUPInputDevice2,_surfaceToolbar))->SetValue(true);
}
else {
appWxVtkI->closeWiiManager();
((wxRadioButton*)this->FindWindowById(id3d_RADIOBUTTONGROUPInputDevice1,_surfaceToolbar))->SetValue(true);
}
}
void wxSurfaceRenderingGui::onModifyCDRatioFunction(wxCommandEvent& WXUNUSED(event)) {
appWxVtkInteractor* appWxVtkI = ((appWxVtkInteractor*)_viewer3d->getWxWindow());
wxCDRatioDialog* d = new wxCDRatioDialog(this, -1, appWxVtkI->_minDISP / 1279.0, appWxVtkI->_maxDISP / 1279.0);
if (d->ShowModal() == wxID_OK) {
appWxVtkI->_minDISP = d->getCMin() * 1279;
appWxVtkI->_maxDISP = d->getCMax() * 1279;
}
}
void wxSurfaceRenderingGui::onModifyMotionFactor(wxCommandEvent& WXUNUSED(event)) {
appWxVtkInteractor* appWxVtkI = ((appWxVtkInteractor*)_viewer3d->getWxWindow());
if (appWxVtkI->getInteractionType() == wiiSR) {
double currentFactor = ((vtkInteractorStyleWIITrackball*)appWxVtkI->GetInteractorStyle())->GetMotionFactor();
wxMotionFactorDialog* d = new wxMotionFactorDialog(this, -1, currentFactor);
if (d->ShowModal() == wxID_OK)
((vtkInteractorStyleWIITrackball*)appWxVtkI->GetInteractorStyle())->SetMotionFactor ( d->getMFactor() );
}
else {
double currentFactor = ((vtkInteractorStyleTrackballCamera*)appWxVtkI->GetInteractorStyle())->GetMotionFactor();
wxMotionFactorDialog* d = new wxMotionFactorDialog(this, -1, currentFactor);
if (d->ShowModal() == wxID_OK)
((vtkInteractorStyleTrackballCamera*)appWxVtkI->GetInteractorStyle())->SetMotionFactor ( d->getMFactor() );
}
}
void wxSurfaceRenderingGui::onWiiChangeSceneIRInteraction( wxCommandEvent &event )
{
appWxVtkInteractor* appWVI = (appWxVtkInteractor*)_viewer3d->getWxWindow();
appWVI->_isSceneRotatingIR_1 = !appWVI->_isSceneRotatingIR_1;
}
void wxSurfaceRenderingGui::onDolly(wxCommandEvent& event) {
(_surfaceToolbar->FindControl(_selectedButton))->SetBackgroundColour(wxNullColour);
(_surfaceToolbar->FindControl(id3d_dollyTool))->SetBackgroundColour( wxColour(255,255,0) );
_selectedButton = id3d_dollyTool;
((appWxVtkInteractor*)_viewer3d->getWxWindow())->setInteractionType(dolly3dSR);
try {
_viewer3d->updateViewer();
}
catch(...) {
wxMessageBox(_T("Study too large for your hardware! Try with a smaller data set"));
Close(TRUE);
return;
}
}
void wxSurfaceRenderingGui::onZoom(wxCommandEvent& event) {
(_surfaceToolbar->FindControl(_selectedButton))->SetBackgroundColour(wxNullColour);
(_surfaceToolbar->FindControl(id3d_zoomTool))->SetBackgroundColour( wxColour(255,255,0) );
_selectedButton = id3d_zoomTool;
((appWxVtkInteractor*)_viewer3d->getWxWindow())->setInteractionType(zoom3dSR);
try {
_viewer3d->updateViewer();
}
catch(...) {
wxMessageBox(_T("Study too large for your hardware! Try with a smaller data set"));
Close(TRUE);
return;
}
}
void wxSurfaceRenderingGui::setInitialDistance() {
_distance = _viewer3d->getRenderer()->GetActiveCamera()->GetDistance();
}
void wxSurfaceRenderingGui::setInitialProjectionValues() {
( (itkVtkData*)_mainGui->getDataHandler()->getData(_idData) )->getVtkActor()->GetOrientation( _initialOrientation );
( (itkVtkData*)_mainGui->getDataHandler()->getData(_idData) )->getVtkActor()->GetScale( _initialScale );
( (itkVtkData*)_mainGui->getDataHandler()->getData(_idData) )->getVtkActor()->GetPosition( _initialPosition );
}
void wxSurfaceRenderingGui::updateStereoView(bool doARender)
{
double eyeAngle = 0; // convergence angle
double parallax = 0; // offset between focus distance (FD) and convergence distance (CD) -> parallax = FD - CD
// interocular distance IOD = 63.5 mm
// POD = viewing distance (VD)
// eye angle (convergence angle) is computed as: 2 * tg-1 ( IOD / (2*CD) )
// where CD = POD * distance / _distance
// _distance is the initial distance between the focal point (set at the center of the object) and the camera
double distance = _viewer3d->getRenderer()->GetActiveCamera()->GetDistance();
// distance between the camera and the focal point
double comfortZone = distance/_distance;
// si cerca di contenere la depth bracket nella comfort zone
if ( ((wxRadioButton*)this->FindWindowById(id3d_endoscopy,_surfaceToolbar))->GetValue() ) // endoscopy mode
{
double cameraPosition[3];
_viewer3d->getRenderer()->GetActiveCamera()->GetPosition(cameraPosition);
double closest, farthest;
this->getBoundsDepthInfo(closest, farthest);
vtkRenderer* ren = _viewer3d->getRenderer();
appWxVtkInteractor* appWxVtkI = ((appWxVtkInteractor*)_viewer3d->getWxWindow());
double p1[4], p2[4];
appWxVtkI->GetInteractorStyle()->ComputeDisplayToWorld( ren, ren->GetSize()[0]/2, ren->GetSize()[1]/2, closest, p1);
appWxVtkI->GetInteractorStyle()->ComputeDisplayToWorld( ren, ren->GetSize()[0]/2, ren->GetSize()[1]/2, farthest, p2);
double firstVolumePoint[3], lastVolumePoint[3];
for (int i=0; i<3; i++)
{
firstVolumePoint[i] = p1[i];
lastVolumePoint[i] = p2[i];
}
if ( ((wxToggleButton*)this->FindWindowById(id3d_stereo,_surfaceToolbar))->GetValue() ) // modalità stereo
{
_viewer3d->getRenderWindow()->StereoRenderOn();
// angolo di convergenza sullo schermo
eyeAngle = vtkMath::DegreesFromRadians( 2 * atan( (6.35/2) / _POD ) );
// convergence distance = focal distance - parallax -> settiamo la parallax in modo da avere la convergenza (e quindi la parallasse 0) sullo schermo
parallax = sqrt( vtkMath::Distance2BetweenPoints( cameraPosition, lastVolumePoint ) ); // parallasse solo positiva, tutto dietro lo schermo
}
// focal point sull'estremo del volume
_viewer3d->getRenderer()->GetActiveCamera()->SetFocalPoint ( lastVolumePoint );
}
else // perspective mode
{
if ( ((wxToggleButton*)this->FindWindowById(id3d_stereo,_surfaceToolbar))->GetValue() ) // modalità stereo
{
_viewer3d->getRenderWindow()->StereoRenderOn();
if ( comfortZone>0.5 ) {
eyeAngle = vtkMath::DegreesFromRadians( 2 * atan( (6.35/2) / (_POD * distance/_distance) ) );
parallax = distance - _distance;
}
else {
eyeAngle = vtkMath::DegreesFromRadians( 2 * atan( (6.35/2) / (_POD * 0.5) ) );
parallax = -0.5 * _distance;
}
}
}
// camera perspective update
_viewer3d->getRenderer()->GetActiveCamera()->SetEyeAngle(eyeAngle);
((vtkMitoCustomCamera*)(_viewer3d->getRenderer()->GetActiveCamera()))->SetParallax(parallax/_globalZoomFactor);
if (doARender)
{
try
{
_viewer3d->updateViewer();
}
catch(...)
{
wxMessageBox(_T("Study too large for your hardware! Try with a smaller data set"));
Close(TRUE);
return;
}
}
}
void wxSurfaceRenderingGui::updateZoom(double factor, bool doARender) {
// camera - volume distance
if ( _globalZoomFactor*factor < 1 ) return;
_globalZoomFactor = _globalZoomFactor * factor;
_viewer3d->getRenderer()->GetActiveCamera()->Zoom(factor);
if (doARender) {
try {
_viewer3d->updateViewer();
}
catch(...) {
wxMessageBox(_T("Study too large for your hardware! Try with a smaller data set"));
Close(TRUE);
return;
}
}
}
/*
void wxSurfaceRenderingGui::onZoom(wxCommandEvent& event) {
string value = _comboBoxZoom->GetValue().c_str();
double zoom, tempValue;
if(!value.compare("25%")) zoom = 25;
else if(!value.compare("50%")) zoom = 50;
else if(!value.compare("75%")) zoom = 75;
else if(!value.compare("100%")) zoom = 100;
else if(!value.compare("125%")) zoom = 125;
else if(!value.compare("150%")) zoom = 150;
else if(!value.compare("200%")) zoom = 200;
else if(!value.compare("500%")) zoom = 500;
if (_itemRadioBoxProjectionType->GetSelection()==1) {
tempValue = _zoomValuePerspectiveSR;
_zoomValuePerspectiveSR = zoom;
}
else {
tempValue = _zoomValueParallelSR;
_zoomValueParallelSR = zoom;
}
zoom = zoom/tempValue;
_viewer3d->getRenderer()->GetActiveCamera()->Zoom(zoom);
_viewer3d->updateViewer();
}
*/
void wxSurfaceRenderingGui::onRotate(wxCommandEvent& event) {
(_surfaceToolbar->FindControl(_selectedButton))->SetBackgroundColour(wxNullColour);
(_surfaceToolbar->FindControl(id3d_rotateTool))->SetBackgroundColour( wxColour(255,255,0) );
_selectedButton = id3d_rotateTool;
((appWxVtkInteractor*)_viewer3d->getWxWindow())->setInteractionType(rotate3d);
try {
_viewer3d->updateViewer();
}
catch(...) {
wxMessageBox(_T("Study too large for your hardware! Try with a smaller data set"));
Close(TRUE);
return;
}
}
void wxSurfaceRenderingGui::onMove(wxCommandEvent& event) {
(_surfaceToolbar->FindControl(_selectedButton))->SetBackgroundColour(wxNullColour);
(_surfaceToolbar->FindControl(id3d_moveTool))->SetBackgroundColour( wxColour(255,255,0) );
_selectedButton = id3d_moveTool;
((appWxVtkInteractor*)_viewer3d->getWxWindow())->setInteractionType(move3d);
try {
_viewer3d->updateViewer();
}
catch(...) {
wxMessageBox(_T("Study too large for your hardware! Try with a smaller data set"));
Close(TRUE);
return;
}
}
void wxSurfaceRenderingGui::onRotateAround(wxCommandEvent& event) {
(_surfaceToolbar->FindControl(_selectedButton))->SetBackgroundColour(wxNullColour);
(_surfaceToolbar->FindControl(id3d_3drotTool))->SetBackgroundColour( wxColour(255,255,0) );
_selectedButton = id3d_3drotTool;
((appWxVtkInteractor*)_viewer3d->getWxWindow())->setInteractionType(rotateAround3dSR);
try {
_viewer3d->updateViewer();
}
catch(...) {
wxMessageBox(_T("Study too large for your hardware! Try with a smaller data set"));
Close(TRUE);
return;
}
}
void wxSurfaceRenderingGui::onActivate(wxActivateEvent& event) {
if (_mainGui->onViewerActivate(_idViewer))
event.Skip();
}
wxVtkViewer3d* wxSurfaceRenderingGui::new3dViewer(wxMainGui* mainGui) {
_mainGui = mainGui;
_viewer3d = new wxVtkViewer3d(_mainGui, this, -1);
_viewer3d->setAlgorithm(surfaceRendering);
// inizializza al 100% il valore dello zoom
//_zoomValuePerspectiveSR = 100;
//_zoomValueParallelSR = 100;
// inizializza la distanza iniziale tra camera e volume
_distance = 0;
// inizializza la distanza tra osservatore e schermo
//_POD = 0;
// inizializza i valori di zoom per parallel e perspective mode
//_viewAngle = 0;
//_parallelScale = 0;
return _viewer3d;
}
void wxSurfaceRenderingGui::show(float contourValue, double decimateValue, double smoothValue) {
wxWindowDisabler disabler;
wxBusyInfo wait("Preparing 3D data...");
wxBusyCursor cursor;
_contourValue = contourValue;
_decimateValue = decimateValue;
_smoothValue = smoothValue;
wxString contourValueTxt = _T(" value: ") + wxString::Format(_T("%6i"), (int)_contourValue);
((wxStaticText*)this->FindWindowById(id3d_contourValueText,_surfaceToolbar))->SetLabel(contourValueTxt);
double colourAmbient[3];
colourAmbient[0] = ((double)_shadingColourAmbient.Red())/100;
colourAmbient[1] = ((double)_shadingColourAmbient.Green())/100;
colourAmbient[2] = ((double)_shadingColourAmbient.Blue())/100;
double colourDiffuse[3];
colourDiffuse[0] = ((double)_shadingColourDiffuse.Red())/100;
colourDiffuse[1] = ((double)_shadingColourDiffuse.Green())/100;
colourDiffuse[2] = ((double)_shadingColourDiffuse.Blue())/100;
double colourSpecular[3];
colourSpecular[0] = ((double)_shadingColourSpecular.Red())/100;
colourSpecular[1] = ((double)_shadingColourSpecular.Green())/100;
colourSpecular[2] = ((double)_shadingColourSpecular.Blue())/100;
surfaceRenderingFilter surfaceRendering( _idData, _mainGui->getDataHandler());
((itkVtkData*)_mainGui->getDataHandler()->getData(_idData))->setVtkActor( surfaceRendering.compute(contourValue, decimateValue, smoothValue, _shadingAmbient, _shadingDiffuse, _shadingSpecular, _shadingSpecularPower, colourAmbient, colourDiffuse, colourSpecular) );
_viewer3d->showAppData(_mainGui->getDataHandler()->getData(_idData));
try {
_viewer3d->updateViewer();
}
catch(...) {
wxMessageBox(_T("Study too large for your hardware! Try with a smaller data set"));
Close(TRUE);
return;
}
Show(TRUE);
create3DCursor();
create3DAxes();
((appWxVtkInteractor*)_viewer3d->getWxWindow())->set3dTechnique(SurfaceRendering);
Raise();
}
void wxSurfaceRenderingGui::onShowAboutDialog(wxCommandEvent& WXUNUSED(event)) {
const wxString name = "MITO - Medical imaging toolkit";
const wxString version = "2.0";
const wxString copyright = "(C) 2006-2011 Institute for High Performance Computing and Networking of the National Research Council of Italy (ICAR-CNR), Naples Branch";
const wxString conjunction = "Institute of Biostructure and Bioimaging (IBB-CNR)";
const wxString hyperlink = "<http://ihealthlab.icar.cnr.it/>";
const wxString hyperlink2 = "<http://amico.icar.cnr.it/>";
wxString msg;
msg << name;
msg << _(" Version ") << version << _T('\n');
msg << copyright << _T('\n');
msg << _("in conjunction with ") << conjunction << _T('\n');
msg << hyperlink << _T('\n');
msg << hyperlink2;
wxMessageBox(msg, _T("About ") + name);
}
void wxSurfaceRenderingGui::set3DCursorRGBColor(double R, double G, double B)
{
if (_3DCursor == NULL) return;
_3DCursor->GetProperty()->SetColor(R,G,B);
}
void wxSurfaceRenderingGui::updateShading(double shadingAmbient, double shadingDiffuse, double shadingSpecular, double shadingSpecularPower) {
//((wxCheckBox*)this->FindWindowById(id3d_shadingCheckBox,_surfaceToolbar))->SetValue(true);
//_isShadeActive = true;
double colourAmbient[3];
colourAmbient[0] = ((double)_shadingColourAmbient.Red())/100;
colourAmbient[1] = ((double)_shadingColourAmbient.Green())/100;
colourAmbient[2] = ((double)_shadingColourAmbient.Blue())/100;
double colourDiffuse[3];
colourDiffuse[0] = ((double)_shadingColourDiffuse.Red())/100;
colourDiffuse[1] = ((double)_shadingColourDiffuse.Green())/100;
colourDiffuse[2] = ((double)_shadingColourDiffuse.Blue())/100;
double colourSpecular[3];
colourSpecular[0] = ((double)_shadingColourSpecular.Red())/100;
colourSpecular[1] = ((double)_shadingColourSpecular.Green())/100;
colourSpecular[2] = ((double)_shadingColourSpecular.Blue())/100;
_shadingAmbient = shadingAmbient;
_shadingDiffuse = shadingDiffuse;
_shadingSpecular = shadingSpecular;
_shadingSpecularPower = shadingSpecularPower;
vtkProperty *actorProperty = ( (itkVtkData*)_mainGui->getDataHandler()->getData(_idData) )->getVtkActor()->GetProperty();
actorProperty->SetAmbientColor(colourAmbient[0], colourAmbient[1], colourAmbient[2]);
actorProperty->SetDiffuseColor(colourDiffuse[0], colourDiffuse[1], colourDiffuse[2]);
actorProperty->SetSpecularColor(colourSpecular[0], colourSpecular[1], colourSpecular[2]);
actorProperty->SetAmbient(_shadingAmbient);
actorProperty->SetDiffuse(_shadingDiffuse);
actorProperty->SetSpecular(_shadingSpecular);
actorProperty->SetSpecularPower(_shadingSpecularPower);
wxString ambientTxt = wxString::Format(_T("%1.2f"), _shadingAmbient);
wxString diffuseTxt = wxString::Format(_T("%1.2f"), _shadingDiffuse);
wxString specularTxt = wxString::Format(_T("%1.2f"), _shadingSpecular);
wxString specularPowerTxt = wxString::Format(_T("%2.1f"), _shadingSpecularPower);
wxString specularAllTxt = specularTxt + _T(", ") + specularPowerTxt;
((wxStaticText*)this->FindWindowById(id3d_shadingAmbientText,_surfaceToolbar))->SetLabel(ambientTxt);
((wxStaticText*)this->FindWindowById(id3d_shadingDiffuseText,_surfaceToolbar))->SetLabel(diffuseTxt);
((wxStaticText*)this->FindWindowById(id3d_shadingSpecularText,_surfaceToolbar))->SetLabel(specularAllTxt);
_viewer3d->updateViewer();
}
void wxSurfaceRenderingGui::onChangeShadingParameters( wxCommandEvent &event ) {
// calcola dove posizionare la finestra
int x = 14;
int y = 14;
int* xClient = &x;
int* yClient = &y;
this->ClientToScreen(xClient,yClient);
wxShadingDialog* d = new wxShadingDialog(1, this, -1);
d->SetSize(*xClient,*yClient,-1,-1);
if (d->ShowModal() == wxID_OK) {
}
}
void wxSurfaceRenderingGui::computeSurfaceRendering(float contourValue, double decimateValue, double smoothValue)
{
_contourValue = contourValue;
_decimateValue = decimateValue;
_smoothValue = smoothValue;
wxString contourValueTxt = _T(" value: ") + wxString::Format(_T("%6i"), (int)_contourValue);
((wxStaticText*)this->FindWindowById(id3d_contourValueText,_surfaceToolbar))->SetLabel(contourValueTxt);
double colourAmbient[3];
colourAmbient[0] = ((double)_shadingColourAmbient.Red())/100;
colourAmbient[1] = ((double)_shadingColourAmbient.Green())/100;
colourAmbient[2] = ((double)_shadingColourAmbient.Blue())/100;
double colourDiffuse[3];
colourDiffuse[0] = ((double)_shadingColourDiffuse.Red())/100;
colourDiffuse[1] = ((double)_shadingColourDiffuse.Green())/100;
colourDiffuse[2] = ((double)_shadingColourDiffuse.Blue())/100;
double colourSpecular[3];
colourSpecular[0] = ((double)_shadingColourSpecular.Red())/100;
colourSpecular[1] = ((double)_shadingColourSpecular.Green())/100;
colourSpecular[2] = ((double)_shadingColourSpecular.Blue())/100;
if ( ((itkVtkData*)_mainGui->getDataHandler()->getData(_idData))->getVtkActor() )
_viewer3d->getRenderer()->RemoveActor(((itkVtkData*)_mainGui->getDataHandler()->getData(_idData))->getVtkActor());
surfaceRenderingFilter surfaceRendering( _idData, _mainGui->getDataHandler());
((itkVtkData*)_mainGui->getDataHandler()->getData(_idData))->setVtkActor( surfaceRendering.compute(contourValue, decimateValue, smoothValue, _shadingAmbient, _shadingDiffuse, _shadingSpecular, _shadingSpecularPower, colourAmbient, colourDiffuse, colourSpecular) );
if ( _3DCursor != NULL )
{
_viewer3d->getRenderer()->RemoveActor( _3DCursor );
this->destroy3DCursor();
this->create3DCursor();
if ( ((wxRadioButton*)this->FindWindowById(id3d_RADIOBUTTONGROUPCursorType2,_surfaceToolbar))->GetValue())
{
((appWxVtkInteractor*)_viewer3d->getWxWindow())->set3DcursorOn();
show3DCursor();
}
}
_viewer3d->getRenderer()->AddActor(((itkVtkData*)_mainGui->getDataHandler()->getData(_idData))->getVtkActor());
_viewer3d->updateViewer();
this->SetTitle(_T("MITO: Surface Rendering"));
}
| [
"kg_dexterp37@fde90bc1-0431-4138-8110-3f8199bc04de"
]
| [
[
[
1,
2078
]
]
]
|
821d5048487e40c9095cef2cc06173fde370bb42 | d8f64a24453c6f077426ea58aaa7313aafafc75c | /RenderManager1.cpp | 879fec6433f954ea7c1e89e64923cb08ea96b22d | []
| no_license | dotted/wfto | 5b98591645f3ddd72cad33736da5def09484a339 | 6eebb66384e6eb519401bdd649ae986d94bcaf27 | refs/heads/master | 2021-01-20T06:25:20.468978 | 2010-11-04T21:01:51 | 2010-11-04T21:01:51 | 32,183,921 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,016 | cpp | #include "settings.h"
#include "commons.h"
#include "RenderManager1.h"
#include "Camera.h"
#include "Frustum.h"
#include "Logger.h"
#include "utils.h"
// TODO: fix render speed!
using namespace game_objects;
using namespace game_objects::lighting;
using namespace game_objects::block_objects;
using namespace game_utils;
using namespace utils;
using namespace cml;
using namespace std;
using namespace control;
using namespace rendering;
using namespace geometry;
using namespace shaders;
#define SHADERS__SIMPLE_TEXTURE 0
#define SHADERS__PPL_TEXTURE 1
#define SHADERS__PPL_NMAP 2
#define PPL "PPL"
#define LTQA "LTQA"
#define LTLA "LTLA"
#define LTIA "LTIA"
#define VB "VB"
#define TC "TC"
#define PLT "PLT"
#define BLS "BLS"
#define RS "RS"
namespace game_utils
{
namespace managers
{
GLfloat CRenderManager1::normals[8][3] =
{
{0.0f,0.0f,1.0f}, // front
{0.0f,0.0f,-1.0f}, // back
{-1.0f,0.0f,0.0f}, // left
{1.0f,0.0f,0.0f}, // right
{0.0f,1.0f,0.0f}, // top
{0.0f,1.0f,0.0f}, // bottom
{0.0f,1.0f,0.0f}, // lava
{0.0f,-1.0f,0.0f}, // ceiling
};
CRenderManager1::CRenderManager1(): CRenderManager(), CConsoleListener()
{
shaderManager = NULL;
drawBlockLightSources = false;
usePPL = CV_GAME_MANAGER->getSettingsManager()->getSetting_Int(CV_SETTINGS_USE_PPL)==1;
shaderInUse = SHADERS__PPL_TEXTURE;
}
CRenderManager1::~CRenderManager1()
{
}
GLvoid CRenderManager1::loadShaders()
{
if (!shaderManager->addShader(SHADERS__SIMPLE_TEXTURE,CV_RESOURCES_DIRECTORY+"shaders\\0\\texture0.vert",CV_RESOURCES_DIRECTORY+"shaders\\0\\texture0.frag"))
{
CLogger::addEntry("ERROR: %s\n",shaderManager->getLastError().c_str());
CV_GAME_MANAGER->getConsole()->writeLine("Shader problem! (check logs)");
}
if (!shaderManager->addShader(SHADERS__PPL_TEXTURE,CV_RESOURCES_DIRECTORY+"shaders\\1\\ppl.vert",CV_RESOURCES_DIRECTORY+"shaders\\1\\ppl.frag"))
{
CLogger::addEntry("ERROR:: %s\n",shaderManager->getLastError().c_str());
CV_GAME_MANAGER->getConsole()->writeLine("Shader problem! (check logs)");
}
if (!shaderManager->addShader(SHADERS__PPL_NMAP,CV_RESOURCES_DIRECTORY+"shaders\\3\\nmap.vert",CV_RESOURCES_DIRECTORY+"shaders\\3\\nmap.frag"))
{
CLogger::addEntry("ERROR: %s\n",shaderManager->getLastError().c_str());
CV_GAME_MANAGER->getConsole()->writeLine("Shader problem! (check logs)");
}
}
bool CRenderManager1::init()
{
shaderManager = new CShaderManager();
loadShaders();
glEnable(GL_COLOR_MATERIAL);
static float color[] = { 1.0f, 1.0f, 1.0f, 1.0f };
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color);
//Set global ambient colour
GLfloat globalAmbientColor[] = { 0.2f, 0.2f, 0.2f, 1.0f };
memcpy(&globalAmbientColor[0],&CV_GAME_MANAGER->getSettingsManager()->getSetting_vector3f(CV_SETTINGS_GLOBAL_AMBIENCE),sizeof(GLfloat)*3);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, globalAmbientColor);
// register to console
CV_GAME_MANAGER->getConsole()->registerClass(this,"RENDER MANAGER");
CV_GAME_MANAGER->getConsole()->addParam(PPL,"() Enables/Disables the perpixel lighting.");
CV_GAME_MANAGER->getConsole()->addParam(LTQA,"(TYPE x.x) Sets|Returns the lights (of the specified type) quadratic attenuation.");
CV_GAME_MANAGER->getConsole()->addParam(LTLA,"(TYPE x.x) Sets|Returns the lights (of the specified type) linear attenuation.");
CV_GAME_MANAGER->getConsole()->addParam(LTIA,"(TYPE x.x) Sets|Returns the lights (of the specified type) initial attenuation.");
CV_GAME_MANAGER->getConsole()->addParam(PLT,"() Prints the light types.");
CV_GAME_MANAGER->getConsole()->addParam(VB,"() Returns visible blocks.");
CV_GAME_MANAGER->getConsole()->addParam(BLS,"() Toggle drawing of helper lines showing the light-block relation.");
CV_GAME_MANAGER->getConsole()->addParam(RS,"() Reloads all shaders from source.");
return CRenderManager::init();
}
GLvoid CRenderManager1::setupLights(CBlock *block)
{
CLightingManager *liManager = CV_GAME_MANAGER->getLightingManager();
CBlockLightData *blockLightData = liManager->getBlockLightData(block->getLogicalPosition());
GLint lightsCount = blockLightData->getLightsCount();
CCamera *camera = CV_GAME_MANAGER->getControlManager()->getCamera();
//if (lightsCount>0 && usePPL)
if (usePPL)
{
shaderManager->useShaderProgram(shaderInUse);
shaderManager->getShaderObject(shaderInUse)->setUniform1i("numberOfLights",lightsCount);
// tell shader where (in which texture unit) to find color and normal map
shaderManager->getShaderObject(shaderInUse)->setUniform1i("tex",0);
shaderManager->getShaderObject(shaderInUse)->setUniform1i("nrm",1);
}
else
{
shaderManager->useFFPipeline();
}
if (drawBlockLightSources)
{
for (GLint i=0; i<lightsCount; i++)
{
glColor3f(1.0f,1.0f,1.0f);
vector3f start = block->getRealPosition()+vector3f(CV_BLOCK_WIDTH/2.0f,block->getVertices()[CBlock::BFS_BOTTOM][1],CV_BLOCK_DEPTH/2.0f);
glBegin(GL_LINES);
{
glVertex3fv(&start[0]);
glVertex3fv(&blockLightData->getLightSource(i)->getPosition()[0]);
}
glEnd();
}
}
glDisable(GL_LIGHTING);
for (GLint i=0; i<8; i++)
{
glDisable(GL_LIGHT0+i);
}
if (usePPL)
{
GLfloat pos[4] = {0.0f,0.0f,0.0f,1.0f};
for (GLint i=lightsCount-1; i>=0; i--)
{
CLightSource *lgt = blockLightData->getLightSource(i);
memcpy(pos,&lgt->getPosition()[0],sizeof(GLfloat)*3);
glLightfv(GL_LIGHT0+i, GL_POSITION, pos);
glLightfv(GL_LIGHT0+i, GL_AMBIENT, lgt->getAmbientColor());
glLightfv(GL_LIGHT0+i, GL_DIFFUSE, lgt->getDiffuseColor());
glLightfv(GL_LIGHT0+i, GL_SPECULAR, lgt->getSpecularColor());
glLightf(GL_LIGHT0+i, GL_QUADRATIC_ATTENUATION, lgt->getQuadraticAttenuation());
glLightf(GL_LIGHT0+i, GL_LINEAR_ATTENUATION, lgt->getLinearAttenuation());
glLightf(GL_LIGHT0+i, GL_CONSTANT_ATTENUATION, lgt->getInitialAttenuation());
glEnable(GL_LIGHT0+i);
}
glEnable(GL_LIGHTING);
}
}
bool CRenderManager1::update()
{
// Draw the map and items that fall into view frustum.
glColor3f(1.0f,1.0f,1.0f);
// get camera
CCamera *camera = CV_GAME_MANAGER->getControlManager()->getCamera();
// 1. extract approximate logical location of camera in the level map.
vector2i center = CConversions::realToLogical(camera->getPosition());
GLint centerX = center[0];
GLint centerY = center[1];
bool isFPS = CV_GAME_MANAGER->getControlManager()->isFPS();
if (isFPS)
{
// fog only in FPS mode
glEnable(GL_FOG);
}
// 3. go through all block that fall into this bounding square and check if they fall
// int out view frustum. If not then just exclude them.
CBlock *block;
GLint maxVertInput = 0,
creaturesVisible = 0,
maxTexInput = 0;
tmpVboVertexBufferSize = 0;
tmpVboTexCoordBufferSize = 0;
vector3f vertA,
vertB,
vertC;
GLfloat **verts,
**texCoords;
CLevelManager *lManager = CV_GAME_MANAGER->getLevelManager();
CAnimatedTerrainManager *atManager = CV_GAME_MANAGER->getAnimatedTerrainManager();
CFrustum *frustum = CV_GAME_MANAGER->getControlManager()->getViewFrustum();
bool lavaWater = false;
blockVisible=allVerticesCount=0;
GLfloat delta = CV_GAME_MANAGER->getDeltaTime();
// transform view
camera->transformView();
renderedBlocks.clear();
for (GLint y=0; y<=CV_LEVEL_MAP_SIZE; y++)
{
for (GLint x=0; x<=CV_LEVEL_MAP_SIZE; x++)
{
//if block is far from the camera, cull
if((x-centerX)*(x-centerX)+(y-centerY)*(y-centerY)>300)
continue;
block = lManager->getBlock(x,y);
if (block)
{
//block->getBoundingBox()->draw(); // just for testing
if (frustum->containsBBOX(block->getBoundingBox()))
{
blockVisible++;
block->updateTexture(delta);
lavaWater = (block->isLava() || block->isWater());
if (lavaWater)
{
atManager->updateBlock(block);
}
setupLights(block);
renderedBlocks.push_back(block);
// draw block objects
if (block->getBlockObjects()->size()>0)
{
for (std::vector<CBlockObject*>::iterator rmIter = block->getBlockObjects()->begin(); rmIter != block->getBlockObjects()->end(); rmIter++)
{
CBlockObject *bObj = *rmIter;
bObj->moveTo();
glRotatef(bObj->getRotateY(),0.0f,1.0f,0.0f);
bObj->drawModel(delta);
glRotatef(-bObj->getRotateY(),0.0f,1.0f,0.0f);
bObj->moveBack();
}
}
bool isRoom = block->isRoom();
if (isRoom)
{
std::vector<GLuint> *dls = block->getDisplayLists();
if (dls->size()!=0)
{
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D,textureAtlasColor);
glBegin(GL_QUADS);
{
for (std::vector<GLuint>::iterator dlIter = dls->begin(); dlIter != dls->end(); dlIter++)
{
glCallList(*dlIter);
}
}
glEnd();
glDisable(GL_TEXTURE_2D);
}
}
for (GLint f=CBlock::BFS_FRONT; f<=CBlock::BFS_CEILING; f++)
{
if ((!isFPS && f==CBlock::BFS_CEILING) || (isFPS && f==CBlock::BFS_TOP) || (isRoom && f!=CBlock::BFS_CEILING))
{
continue;
}
verts = block->getVertices();
texCoords = block->getTextureCoordinates();
if (block->isFaceVisible((CBlock::BLOCK_FACE_SELECTOR)f))
{
if (lavaWater && f<=CBlock::BFS_RIGHT)
{
/*
Lava and water have only lowers row of wall sections drawn.
If they are drawn at all.
*/
maxVertInput = CV_FBLR_W_L_FACE_VERT_FLOATS;
maxTexInput = CV_FBLR_W_L_FACE_TEX_FLOATS;
}
else
{
maxVertInput = f>=CBlock::BFS_TOP?CV_TBWLC_FACE_VERT_FLOATS:CV_FBLR_FACE_VERT_FLOATS;
maxTexInput = f>=CBlock::BFS_TOP?CV_TBWLC_FACE_TEX_FLOATS:CV_FBLR_FACE_TEX_FLOATS;
}
memcpy(tmpVboVertexBuffer+tmpVboVertexBufferSize, verts[f], sizeof(GLfloat)*maxVertInput);
for (GLint n=0; n<maxVertInput; n+=3)
{
memcpy(tmpVboNormalBuffer+tmpVboVertexBufferSize+n, normals[f], sizeof(GLfloat)*3);
}
memcpy(tmpVboTexCoordBuffer+tmpVboTexCoordBufferSize, texCoords[f], sizeof(GLfloat)*maxTexInput);
tmpVboVertexBufferSize+=maxVertInput;
tmpVboTexCoordBufferSize+=maxTexInput;
}
}
if (tmpVboVertexBufferSize>0)
{
vbo->setElementsCount(CVBO::IDT_vertex,tmpVboVertexBufferSize/3);
vbo->setElementsCount(CVBO::IDT_normal,tmpVboVertexBufferSize/3);
vbo->setElementsCount(CVBO::IDT_texture0,tmpVboTexCoordBufferSize/2);
vbo->setElementsCount(CVBO::IDT_texture1,tmpVboTexCoordBufferSize/2);
vbo->draw();
allVerticesCount+=tmpVboVertexBufferSize;
tmpVboVertexBufferSize=0;
tmpVboTexCoordBufferSize=0;
}
}
}
}
}
// draw creatures
CCreatureManager *cManager = CV_GAME_MANAGER->getCreatureManager();
GLint cCount = cManager->getCreatureVector()->size();
if (cCount>0)
{
CCreature *creature = NULL;
for (std::vector<CCreature*>::iterator cIter = cManager->getCreatureVector()->begin(); cIter != cManager->getCreatureVector()->end(); cIter++)
{
creature = (*cIter);
if (creature)
{
int x = CConversions::realToLogical(creature->getPosition())[0];
int y = CConversions::realToLogical(creature->getPosition())[1];
if((x-centerX)*(x-centerX)+(y-centerY)*(y-centerY)>300)
continue;
sBoundingBox *cBBOX = creature->getModel()->getBoundingBox();
cBBOX->translate(creature->getPosition());
if (frustum->containsBBOX(cBBOX))
{
creature->draw(delta);
creaturesVisible++;
}
cBBOX->translate(-creature->getPosition());
}
}
}
shaderManager->useFFPipeline();
glDisable(GL_LIGHTING);
// draw transparent block objects
for (std::vector<CBlock*>::iterator vbIter = renderedBlocks.begin(); vbIter != renderedBlocks.end(); vbIter++)
{
block = *vbIter;
if (block->getBlockObjects()->size()>0)
{
for (std::vector<CBlockObject*>::iterator rmIter = block->getBlockObjects()->begin(); rmIter != block->getBlockObjects()->end(); rmIter++)
{
CBlockObject *bObj = *rmIter;
bObj->moveTo();
glRotatef(bObj->getRotateY(),0.0f,1.0f,0.0f);
bObj->drawEffect();
glRotatef(-bObj->getRotateY(),0.0f,1.0f,0.0f);
bObj->moveBack();
}
}
}
glDisable(GL_FOG);
if (!isFPS)
{
handlePickedObjects();
}
handleMineMarker();
CV_GAME_MANAGER->getTextPrinter()->print((GLfloat)0,(GLfloat)(CV_SETTINGS_WINDOW_HEIGHT-15*3),"Visible blocks: %d",blockVisible);
CV_GAME_MANAGER->getTextPrinter()->print((GLfloat)0,(GLfloat)(CV_SETTINGS_WINDOW_HEIGHT-15*2),"Visible creatures: %d",creaturesVisible);
CV_GAME_MANAGER->getTextPrinter()->print((GLfloat)0,(GLfloat)(CV_SETTINGS_WINDOW_HEIGHT-15),"Triangles drawn: %d",(allVerticesCount/4)*2);
// render the lights representations. usefull for debugging
CV_GAME_MANAGER->getLightingManager()->drawLightSources(frustum);
return true;
}
bool CRenderManager1::shutdown()
{
delete shaderManager;
return CRenderManager::shutdown();
}
string CRenderManager1::onAction(string keyword, string params)
{
string checkResult = "";
std::vector<string> tParams;
if (keyword==PPL)
{
usePPL = !usePPL; //(tParams[0]=="0"?false:true);
return "Perpixel lighting "+string(!usePPL?"disabled.":"enabled.");
}
else if (keyword==BLS)
{
drawBlockLightSources = !drawBlockLightSources;
return "Block light sources "+string(!drawBlockLightSources?"disabled.":"enabled.");
}
else if (keyword==LTQA)
{
CLightingManager *liManager = CV_GAME_MANAGER->getLightingManager();
GLint lightType;
string lightName;
if (!CConsoleListener::checkParams(params,2,checkResult,tParams))
{
if (CConsoleListener::checkParams(params,1,checkResult,tParams))
{
lightType = CConversions::strToInt(tParams[0]);
lightName = liManager->lightSourceTypeIndexToName(lightType);
return "Light "+lightName+" quadratic attenuation: "+CConversions::floatToStr(liManager->getLightParam(lightType,ATTENUATION_TYPE_QUADRATIC));
}
else
{
return checkResult;
}
}
lightType = CConversions::strToInt(tParams[0]);
lightName = liManager->lightSourceTypeIndexToName(lightType);
liManager->setLightParam(lightType,ATTENUATION_TYPE_QUADRATIC,CConversions::strToFloat(tParams[1]));
return "Quadratic attenuation for "+lightName+" light types set.";
}
else if (keyword==LTLA)
{
CLightingManager *liManager = CV_GAME_MANAGER->getLightingManager();
GLint lightType;
string lightName;
if (!CConsoleListener::checkParams(params,2,checkResult,tParams))
{
if (CConsoleListener::checkParams(params,1,checkResult,tParams))
{
lightType = CConversions::strToInt(tParams[0]);
lightName = liManager->lightSourceTypeIndexToName(lightType);
return "Light "+lightName+" linear attenuation: "+CConversions::floatToStr(liManager->getLightParam(lightType,ATTENUATION_TYPE_LINEAR));
}
else
{
return checkResult;
}
}
lightType = CConversions::strToInt(tParams[0]);
lightName = liManager->lightSourceTypeIndexToName(lightType);
liManager->setLightParam(lightType,ATTENUATION_TYPE_LINEAR,CConversions::strToFloat(tParams[1]));
return "Quadratic linear for "+lightName+" light types set.";
}
else if (keyword==LTIA)
{
CLightingManager *liManager = CV_GAME_MANAGER->getLightingManager();
GLint lightType;
string lightName;
if (!CConsoleListener::checkParams(params,2,checkResult,tParams))
{
if (CConsoleListener::checkParams(params,1,checkResult,tParams))
{
lightType = CConversions::strToInt(tParams[0]);
lightName = liManager->lightSourceTypeIndexToName(lightType);
return "Light "+lightName+" initial attenuation: "+CConversions::floatToStr(liManager->getLightParam(lightType,ATTENUATION_TYPE_INITIAL));
}
else
{
return checkResult;
}
}
lightType = CConversions::strToInt(tParams[0]);
lightName = liManager->lightSourceTypeIndexToName(lightType);
liManager->setLightParam(lightType,ATTENUATION_TYPE_INITIAL,CConversions::strToFloat(tParams[1]));
return "Quadratic initial for "+lightName+" light types set.";
}
else if (keyword==VB)
{
return "Visible blocks: "+CConversions::intToStr(blockVisible);
}
else if (keyword==TC)
{
return "Drawn triangles: "+CConversions::intToStr((allVerticesCount/4)*2);
}
else if (keyword==PLT)
{
return CV_GAME_MANAGER->getLightingManager()->getLightTypes();
}
else if (keyword==RS)
{
loadShaders();
return "Shaders reloaded!";
}
return "<>";
}
};
}; | [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
]
| [
[
[
1,
12
],
[
14,
96
],
[
102,
125
],
[
128,
173
],
[
175,
186
],
[
190,
202
],
[
208,
214
],
[
216,
225
],
[
227,
240
],
[
244,
244
],
[
246,
246
],
[
253,
254
],
[
256,
270
],
[
309,
310
],
[
312,
315
],
[
319,
326
],
[
329,
331
],
[
334,
335
],
[
337,
337
],
[
339,
339
],
[
345,
346
],
[
348,
357
],
[
359,
368
],
[
398,
400
],
[
433,
553
]
],
[
[
13,
13
],
[
97,
101
],
[
126,
127
],
[
187,
189
],
[
203,
206
],
[
215,
215
],
[
241,
242
],
[
255,
255
],
[
271,
308
],
[
311,
311
],
[
358,
358
],
[
369,
380
],
[
386,
397
],
[
401,
426
],
[
429,
432
]
],
[
[
174,
174
],
[
207,
207
],
[
226,
226
],
[
243,
243
],
[
245,
245
],
[
247,
252
],
[
316,
318
],
[
327,
328
],
[
332,
333
],
[
336,
336
],
[
338,
338
],
[
340,
344
],
[
347,
347
],
[
381,
385
]
],
[
[
427,
428
]
]
]
|
5fc5ff4d95f1c90b5dfb95eed2c5f3e0fc9498a8 | c267e416aba473054330378d18bc3cd172bbad21 | /QQ音乐缓存提取工具/QQ音乐缓存提取工具Dlg.cpp | 0dd29ba2874baff0b5359e1b030d926688204817 | []
| no_license | chenwp/shuax | c3b7dea72708ee539664ac8db1d9885e87fefed7 | b13bea0aae7e252650f4c8f5df1b2a716455ef80 | refs/heads/master | 2021-04-26T16:43:25.168306 | 2011-10-22T15:09:37 | 2011-10-22T15:09:37 | 45,179,472 | 2 | 0 | null | null | null | null | GB18030 | C++ | false | false | 12,368 | cpp | // QQ音乐缓存提取工具Dlg.cpp : implementation file
//
#include <conio.h>
#include "stdafx.h"
#include "QQ音乐缓存提取工具.h"
#include "QQ音乐缓存提取工具Dlg.h"
#include "tea.cpp"
#include "tag.cpp"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
void BrowseDir(CString strDir,CStringList *list,float &size) //此函数用于遍历文件夹下的文件,strDir是一个目录路径
{
CFileFind ff;
CString szDir = strDir,strPath;
if(szDir.Right(1) != "\\") //保证目录是以\结尾的
szDir += "\\";
szDir += "*.*";
BOOL res = ff.FindFile(szDir);
while( res )
{
res = ff.FindNextFile();
strPath = ff.GetFilePath();
if(ff.IsDirectory() && !ff.IsDots())
{
BrowseDir(strPath,list,size); //如果目标是个文件夹,则利用嵌套来遍历
}
else if(!ff.IsDirectory() && !ff.IsDots())
{
if (strstr(strPath,".tdl")!=0)
{
list->AddTail(strPath); //如果目标是个文件,则对它进行处理
size += ff.GetLength();
}
}
}
ff.Close();
}
BOOL mkdirEx(const char* lpPath)
{
CString pathname = lpPath;
if(pathname.Right(1) != "\\")
pathname += "\\" ;
int end = pathname.ReverseFind('\\');
int pt = pathname.Find('\\');
if (pathname[pt-1] == ':')
pt = pathname.Find('\\', pt+1);
CString path;
while(pt != -1 && pt<=end)
{
path = pathname.Left(pt+1);
if(GetFileAttributes(path)==0xFFFFFFFF)
CreateDirectory(path,NULL);
pt = pathname.Find('\\', pt+1);
}
return true;
}
//删除[shan chu]文件[wen jian]到回收站中
//pszPath : 待删除[shan chu]的全路径[lu jing]文件[wen jian]名[wen jian ming]
//bDelete : TRUE 删除[shan chu],不移到回收站,FALSE:移到回收站
//返回 : TRUE 删除[shan chu]成功 FALSE 删除[shan chu]失败
Recycle(LPCTSTR pszPath, BOOL bDelete/*=FALSE*/)
{
SHFILEOPSTRUCT shDelFile;
memset(&shDelFile,0,sizeof(SHFILEOPSTRUCT));
shDelFile.fFlags |= FOF_SILENT; // don't report progress
shDelFile.fFlags |= FOF_NOERRORUI; // don't report errors
shDelFile.fFlags |= FOF_NOCONFIRMATION; // don't confirm delete
// Copy pathname to double-NULL-terminated string.
//
TCHAR buf[_MAX_PATH + 1]; // allow one more character
_tcscpy(buf, pszPath); // copy caller's pathname
buf[_tcslen(buf)+1]=0; // need two NULLs at end
// Set SHFILEOPSTRUCT params for delete operation
shDelFile.wFunc = FO_DELETE; // REQUIRED: delete operation
shDelFile.pFrom = buf; // REQUIRED: which file(s)
shDelFile.pTo = NULL; // MUST be NULL
if (bDelete)
{ // if delete requested..
shDelFile.fFlags &= ~FOF_ALLOWUNDO; // ..don't use Recycle Bin
}
else
{ // otherwise..
shDelFile.fFlags |= FOF_ALLOWUNDO; // ..send to Recycle Bin
}
return SHFileOperation(&shDelFile); // do it!
}
void getpath(char *temppath,char *tips)
{
#define BIF_USENEWUI 0x0050
BROWSEINFO bi;
bi.hwndOwner = NULL;
bi.pidlRoot = NULL;
bi.pszDisplayName = NULL;
bi.lpszTitle = tips;
bi.ulFlags = BIF_RETURNONLYFSDIRS + BIF_USENEWUI;
bi.lpfn = NULL;
bi.lParam = NULL;
bi.iImage = NULL;
if(!SHGetPathFromIDList(SHBrowseForFolder(&bi), temppath))
{
temppath[0]=0;
}
}
/////////////////////////////////////////////////////////////////////////////
// CQQDlg dialog
CQQDlg::CQQDlg(CWnd* pParent /*=NULL*/)
: CDialog(CQQDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CQQDlg)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CQQDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CQQDlg)
// NOTE: the ClassWizard will add DDX and DDV calls here
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CQQDlg, CDialog)
//{{AFX_MSG_MAP(CQQDlg)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_CHECK2, OnCheck2)
ON_BN_CLICKED(IDC_CHECK3, OnCheck3)
ON_BN_CLICKED(IDC_CHECK4, OnCheck4)
ON_BN_CLICKED(IDC_BUTTON1, OnButton1)
ON_BN_CLICKED(IDC_CHECK6, OnCheck6)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CQQDlg message handlers
BOOL CQQDlg::OnInitDialog()
{
CDialog::OnInitDialog();
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
//AllocConsole();
//获得文件大小信息
size1 = size2 = 0;
isrun = false;
isok = false;
list1.RemoveAll();
list2.RemoveAll();
HKEY hkey; unsigned long len=1024;
RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Tencent\\QQMusic", 0, KEY_ALL_ACCESS, &hkey);
if(RegQueryValueEx(hkey, "SaveCachePath", 0, 0,(unsigned char*)&QQPlayer, &len) != ERROR_SUCCESS )
{
char AppDataPath[1024];
LPITEMIDLIST pidl;
SHGetSpecialFolderLocation(NULL,CSIDL_APPDATA,&pidl);
SHGetPathFromIDList(pidl,AppDataPath);
strcat(AppDataPath,"\\Tencent\\QQMusic\\CachePath.ini");
GetPrivateProfileString("Cache","Path",0,QQPlayer,len,AppDataPath);
if(strlen(QQPlayer)<3)
{
MessageBoxW(m_hWnd,L"程序没有找到您电脑上的QQ音乐缓存目录。",L"QQ音乐缓存提取工具",MB_OK + MB_ICONINFORMATION);
ExitProcess(0);
return false;
}
}
if(RegQueryValueEx(hkey, "WhirlCachePath", 0, 0,(unsigned char*)&QZonePlayer, &len) != ERROR_SUCCESS )
{
char AppDataPath[1024];
LPITEMIDLIST pidl;
SHGetSpecialFolderLocation(NULL,CSIDL_APPDATA,&pidl);
SHGetPathFromIDList(pidl,AppDataPath);
strcpy(QZonePlayer,AppDataPath);
strcat(QZonePlayer,"\\Tencent\\QQMusic\\WhirlCache");
}
RegCloseKey(hkey);
GetDlgItem(IDC_EDIT1)->SetWindowText(QQPlayer);
GetDlgItem(IDC_EDIT2)->SetWindowText(QZonePlayer);
BrowseDir(QQPlayer,&list1,size1);
BrowseDir(QZonePlayer,&list2,size2);
((CButton *)GetDlgItem(IDC_CHECK2))->SetCheck(TRUE);
((CButton *)GetDlgItem(IDC_CHECK3))->SetCheck(TRUE);
ChangeCheck();
((CButton *)GetDlgItem(IDC_CHECK1))->SetCheck(TRUE);
((CButton *)GetDlgItem(IDC_CHECK4))->SetCheck(TRUE);
((CButton *)GetDlgItem(IDC_CHECK6))->SetCheck(TRUE);
GetDlgItem(IDC_EDIT3)->SetWindowText("%A - %T");
char DocPath[1024];
LPITEMIDLIST pidl;
SHGetSpecialFolderLocation(NULL,CSIDL_PERSONAL,&pidl);
SHGetPathFromIDList(pidl,DocPath);
strcat(DocPath,"\\QQMusicCollect\\");
GetDlgItem(IDC_EDIT5)->SetWindowText(DocPath);
return TRUE; // return TRUE unless you set the focus to a control
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CQQDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
HCURSOR CQQDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
BOOL CQQDlg::PreTranslateMessage(MSG* pMsg)
{
if( pMsg->message == WM_KEYDOWN)
{
switch(pMsg->wParam)
{
case VK_ESCAPE:
return TRUE;
case VK_RETURN:
return TRUE;
}
}
return CDialog::PreTranslateMessage(pMsg);
}
void CQQDlg::OnCheck2()
{
// TODO: Add your control notification handler code here
ChangeCheck();
}
void CQQDlg::OnCheck3()
{
// TODO: Add your control notification handler code here
ChangeCheck();
}
void CQQDlg::ChangeCheck()
{
char Temp[1024];
float _size1;
float _size2;
int _count1;
int _count2;
if(((CButton *)GetDlgItem(IDC_CHECK2))->GetCheck())
{
_size1=size1;
_count1=list1.GetCount();
}
else
{
_size1=0;
_count1=0;
}
if(((CButton *)GetDlgItem(IDC_CHECK3))->GetCheck())
{
_size2=size2;
_count2=list2.GetCount();
}
else
{
_size2=0;
_count2=0;
}
sprintf(Temp,"缓存文件总大小:%.02fMB,共有缓存文件%d个。",(_size1+_size2)/1024/1024,_count1+_count2);
GetDlgItem(IDC_EDIT4)->SetWindowText(Temp);
((CProgressCtrl*)GetDlgItem(IDC_PROGRESS1))->SetRange(0,_count1+_count2);
}
void CQQDlg::OnCheck6()
{
// TODO: Add your control notification handler code here
if(!((CButton *)GetDlgItem(IDC_CHECK6))->GetCheck())
{
((CButton *)GetDlgItem(IDC_EDIT3))->EnableWindow(false);
}
else
{
((CButton *)GetDlgItem(IDC_EDIT3))->EnableWindow(true);
}
}
void CQQDlg::OnCheck4()
{
// TODO: Add your control notification handler code here
if(!((CButton *)GetDlgItem(IDC_CHECK4))->GetCheck())
{
((CButton *)GetDlgItem(IDC_CHECK5))->SetCheck(false);
((CButton *)GetDlgItem(IDC_CHECK5))->EnableWindow(false);
}
else
{
((CButton *)GetDlgItem(IDC_CHECK5))->EnableWindow(true);
}
}
void CQQDlg::OnButton1()
{
char path[1024];
getpath(path,"请选择保存目录");
if(path[0]!=0) GetDlgItem(IDC_EDIT5)->SetWindowText(path);
}
//
UINT CQQDlg::ThreadProc(LPVOID pParam)
{
CQQDlg * pTaskMain = (CQQDlg *) pParam;
char save[1024];
wchar_t format[128];
GetWindowTextW(::GetDlgItem(pTaskMain->m_hWnd, IDC_EDIT3), format, 128);
pTaskMain->GetDlgItem(IDC_EDIT5)->GetWindowText(save,1024);
if(save[strlen(save)-1]!='\\') strcat(save,"\\");
mkdirEx(save);
CStringList list;
if(((CButton *)pTaskMain->GetDlgItem(IDC_CHECK2))->GetCheck())
{
list.AddTail(&pTaskMain->list1);
}
if(((CButton *)pTaskMain->GetDlgItem(IDC_CHECK3))->GetCheck())
{
list.AddTail(&pTaskMain->list2);
}
int nCount=list.GetCount();
for(int i=0;i<nCount;i++)
{
char *temp;
temp = decrypt(list.GetAt(list.FindIndex(i)),save);
if(((CButton *)pTaskMain->GetDlgItem(IDC_CHECK6))->GetCheck())
{
//改名
GetWmaTag(temp,format,save);
}
((CProgressCtrl*)pTaskMain->GetDlgItem(IDC_PROGRESS1))->SetPos(i+1);
}
//删除文件夹
if(((CButton *)pTaskMain->GetDlgItem(IDC_CHECK4))->GetCheck())
{
if(((CButton *)pTaskMain->GetDlgItem(IDC_CHECK2))->GetCheck()) Recycle(pTaskMain->QQPlayer,((CButton *)pTaskMain->GetDlgItem(IDC_CHECK5))->GetCheck());
if(((CButton *)pTaskMain->GetDlgItem(IDC_CHECK3))->GetCheck()) Recycle(pTaskMain->QZonePlayer,((CButton *)pTaskMain->GetDlgItem(IDC_CHECK5))->GetCheck());
}
//MessageBoxW(pTaskMain->m_hWnd,L"任务全部完成,程序将会退出并且打开提取目录。",L"QQ音乐缓存提取工具",MB_OK + MB_ICONINFORMATION);
if(((CButton *)pTaskMain->GetDlgItem(IDC_CHECK1))->GetCheck()) ::ShellExecute(NULL, "explore", save,NULL,NULL,SW_SHOW);
pTaskMain->isok=true;
pTaskMain->OnOK();
pTaskMain->OnInitDialog();
return 0;
}
void CQQDlg::OnOK()
{
if(!isrun)
{
isrun = true;
static char stop[]="停止";
GetDlgItem(IDOK)->SetWindowText(stop);
pThread = AfxBeginThread(ThreadProc,this,THREAD_PRIORITY_BELOW_NORMAL , 0, 0, NULL);
//
((CButton *)GetDlgItem(IDC_CHECK2))->EnableWindow(false);
((CButton *)GetDlgItem(IDC_CHECK3))->EnableWindow(false);
((CButton *)GetDlgItem(IDC_CHECK4))->EnableWindow(false);
((CButton *)GetDlgItem(IDC_CHECK5))->EnableWindow(false);
((CButton *)GetDlgItem(IDC_CHECK6))->EnableWindow(false);
((CButton *)GetDlgItem(IDC_BUTTON1))->EnableWindow(false);
}
else
{
isrun = false;
static char start[]="开始";
GetDlgItem(IDOK)->SetWindowText(start);
((CButton *)GetDlgItem(IDC_CHECK2))->EnableWindow(true);
((CButton *)GetDlgItem(IDC_CHECK3))->EnableWindow(true);
((CButton *)GetDlgItem(IDC_CHECK4))->EnableWindow(true);
((CButton *)GetDlgItem(IDC_CHECK5))->EnableWindow(true);
((CButton *)GetDlgItem(IDC_CHECK6))->EnableWindow(true);
((CButton *)GetDlgItem(IDC_BUTTON1))->EnableWindow(true);
((CProgressCtrl*)GetDlgItem(IDC_PROGRESS1))->SetPos(0);
if(!isok) TerminateThread(pThread->m_hThread , 0);
}
//CDialog::OnOK();
}
| [
"[email protected]"
]
| [
[
[
1,
435
]
]
]
|
31c8beb76491982ae2e0e6075b8491a3f1677061 | 65eb241d4016d565d18e2aa9d889d13eab68fbf5 | /linucom2.2.0/posix_qextserialport.cpp | 5eae7905ac23ee2fdc748f1dd44fce21777f126d | []
| no_license | openlinux/MyApp | 3c5ac925a58bca1e8bb563d4386ed77de10c0500 | bc86b85b3d315455c1a19e779b10f5dffb4864fe | refs/heads/master | 2021-01-10T20:11:13.555628 | 2011-08-09T02:49:49 | 2011-08-09T02:49:49 | 1,699,362 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 38,642 | cpp |
/*!
\class Posix_QextSerialPort
\version 1.0.0
\author Stefan Sander
\author Michal Policht
A cross-platform serial port class.
This class encapsulates the POSIX portion of QextSerialPort. The user will be notified of errors
and possible portability conflicts at run-time by default - this behavior can be turned off by
defining _TTY_NOWARN_ (to turn off all warnings) or _TTY_NOWARN_PORT_ (to turn off portability
warnings) in the project. Note that _TTY_NOWARN_ will also turn off portability warnings.
*/
#include <stdio.h>
#include "posix_qextserialport.h"
/*!
\fn Posix_QextSerialPort::Posix_QextSerialPort()
Default constructor. Note that the name of the device used by a QextSerialPort constructed with
this constructor will be determined by #defined constants, or lack thereof - the default behavior
is the same as _TTY_LINUX_. Possible naming conventions and their associated constants are:
\verbatim
Constant Used By Naming Convention
---------- ------------- ------------------------
_TTY_WIN_ Windows COM1, COM2
_TTY_IRIX_ SGI/IRIX /dev/ttyf1, /dev/ttyf2
_TTY_HPUX_ HP-UX /dev/tty1p0, /dev/tty2p0
_TTY_SUN_ SunOS/Solaris /dev/ttya, /dev/ttyb
_TTY_DIGITAL_ Digital UNIX /dev/tty01, /dev/tty02
_TTY_FREEBSD_ FreeBSD /dev/ttyd0, /dev/ttyd1
_TTY_LINUX_ Linux /dev/ttyS0, /dev/ttyS1
<none> Linux /dev/ttyS0, /dev/ttyS1
\endverbatim
This constructor assigns the device name to the name of the first port on the specified system.
See the other constructors if you need to open a different port.
*/
Posix_QextSerialPort::Posix_QextSerialPort()
: QextSerialBase()
{
Posix_File=new QFile();
}
/*!
\fn Posix_QextSerialPort::Posix_QextSerialPort(const Posix_QextSerialPort&)
Copy constructor.
*/
Posix_QextSerialPort::Posix_QextSerialPort(const Posix_QextSerialPort& s)
: QextSerialBase(s.port)
{
setOpenMode(s.openMode());
port = s.port;
Settings.BaudRate=s.Settings.BaudRate;
Settings.DataBits=s.Settings.DataBits;
Settings.Parity=s.Settings.Parity;
Settings.StopBits=s.Settings.StopBits;
Settings.FlowControl=s.Settings.FlowControl;
lastErr=s.lastErr;
Posix_File=new QFile();
Posix_File=s.Posix_File;
memcpy(&Posix_Timeout, &s.Posix_Timeout, sizeof(struct timeval));
memcpy(&Posix_Copy_Timeout, &s.Posix_Copy_Timeout, sizeof(struct timeval));
memcpy(&Posix_CommConfig, &s.Posix_CommConfig, sizeof(struct termios));
}
/*!
\fn Posix_QextSerialPort::Posix_QextSerialPort(const QString & name)
Constructs a serial port attached to the port specified by name.
name is the name of the device, which is windowsystem-specific,
e.g."COM1" or "/dev/ttyS0".
*/
Posix_QextSerialPort::Posix_QextSerialPort(const QString & name, QextSerialBase::QueryMode mode)
: QextSerialBase(name)
{
Posix_File=new QFile();
setQueryMode(mode);
init();
}
/*!
\fn Posix_QextSerialPort::Posix_QextSerialPort(const PortSettings& settings)
Constructs a port with default name and specified settings.
*/
Posix_QextSerialPort::Posix_QextSerialPort(const PortSettings& settings, QextSerialBase::QueryMode mode)
: QextSerialBase()
{
setBaudRate(settings.BaudRate);
setDataBits(settings.DataBits);
setParity(settings.Parity);
setStopBits(settings.StopBits);
setFlowControl(settings.FlowControl);
Posix_File=new QFile();
setTimeout(settings.Timeout_Millisec);
setQueryMode(mode);
init();
}
/*!
\fn Posix_QextSerialPort::Posix_QextSerialPort(const QString & name, const PortSettings& settings)
Constructs a port with specified name and settings.
*/
Posix_QextSerialPort::Posix_QextSerialPort(const QString & name, const PortSettings& settings, QextSerialBase::QueryMode mode)
: QextSerialBase(name)
{
setBaudRate(settings.BaudRate);
setDataBits(settings.DataBits);
setParity(settings.Parity);
setStopBits(settings.StopBits);
setFlowControl(settings.FlowControl);
Posix_File=new QFile();
setTimeout(settings.Timeout_Millisec);
setQueryMode(mode);
init();
}
/*!
\fn Posix_QextSerialPort& Posix_QextSerialPort::operator=(const Posix_QextSerialPort& s)
Override the = operator.
*/
Posix_QextSerialPort& Posix_QextSerialPort::operator=(const Posix_QextSerialPort& s)
{
setOpenMode(s.openMode());
port = s.port;
Settings.BaudRate=s.Settings.BaudRate;
Settings.DataBits=s.Settings.DataBits;
Settings.Parity=s.Settings.Parity;
Settings.StopBits=s.Settings.StopBits;
Settings.FlowControl=s.Settings.FlowControl;
lastErr=s.lastErr;
Posix_File=s.Posix_File;
memcpy(&Posix_Timeout, &(s.Posix_Timeout), sizeof(struct timeval));
memcpy(&Posix_Copy_Timeout, &(s.Posix_Copy_Timeout), sizeof(struct timeval));
memcpy(&Posix_CommConfig, &(s.Posix_CommConfig), sizeof(struct termios));
return *this;
}
void Posix_QextSerialPort::init()
{
if (queryMode() == QextSerialBase::EventDriven)
qWarning("POSIX doesn't have event driven mechanism implemented yet");
}
/*!
\fn Posix_QextSerialPort::~Posix_QextSerialPort()
Standard destructor.
*/
Posix_QextSerialPort::~Posix_QextSerialPort()
{
if (isOpen()) {
close();
}
Posix_File->close();
delete Posix_File;
}
/*!
\fn void Posix_QextSerialPort::setBaudRate(BaudRateType baudRate)
Sets the baud rate of the serial port. Note that not all rates are applicable on
all platforms. The following table shows translations of the various baud rate
constants on Windows(including NT/2000) and POSIX platforms. Speeds marked with an *
are speeds that are usable on both Windows and POSIX.
\note
BAUD76800 may not be supported on all POSIX systems. SGI/IRIX systems do not support
BAUD1800.
\verbatim
RATE Windows Speed POSIX Speed
----------- ------------- -----------
BAUD50 110 50
BAUD75 110 75
*BAUD110 110 110
BAUD134 110 134.5
BAUD150 110 150
BAUD200 110 200
*BAUD300 300 300
*BAUD600 600 600
*BAUD1200 1200 1200
BAUD1800 1200 1800
*BAUD2400 2400 2400
*BAUD4800 4800 4800
*BAUD9600 9600 9600
BAUD14400 14400 9600
*BAUD19200 19200 19200
*BAUD38400 38400 38400
BAUD56000 56000 38400
*BAUD57600 57600 57600
BAUD76800 57600 76800
*BAUD115200 115200 115200
BAUD128000 128000 115200
BAUD256000 256000 115200
\endverbatim
*/
void Posix_QextSerialPort::setBaudRate(BaudRateType baudRate)
{
LOCK_MUTEX();
if (Settings.BaudRate!=baudRate) {
switch (baudRate) {
case BAUD14400:
Settings.BaudRate=BAUD9600;
break;
case BAUD56000:
Settings.BaudRate=BAUD38400;
break;
case BAUD76800:
#ifndef B76800
Settings.BaudRate=BAUD57600;
#else
Settings.BaudRate=baudRate;
#endif
break;
case BAUD128000:
case BAUD256000:
Settings.BaudRate=BAUD115200;
break;
default:
Settings.BaudRate=baudRate;
break;
}
}
if (isOpen()) {
switch (baudRate) {
/*50 baud*/
case BAUD50:
TTY_PORTABILITY_WARNING("Posix_QextSerialPort Portability Warning: Windows does not support 50 baud operation.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B50;
#else
cfsetispeed(&Posix_CommConfig, B50);
cfsetospeed(&Posix_CommConfig, B50);
#endif
break;
/*75 baud*/
case BAUD75:
TTY_PORTABILITY_WARNING("Posix_QextSerialPort Portability Warning: Windows does not support 75 baud operation.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B75;
#else
cfsetispeed(&Posix_CommConfig, B75);
cfsetospeed(&Posix_CommConfig, B75);
#endif
break;
/*110 baud*/
case BAUD110:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B110;
#else
cfsetispeed(&Posix_CommConfig, B110);
cfsetospeed(&Posix_CommConfig, B110);
#endif
break;
/*134.5 baud*/
case BAUD134:
TTY_PORTABILITY_WARNING("Posix_QextSerialPort Portability Warning: Windows does not support 134.5 baud operation.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B134;
#else
cfsetispeed(&Posix_CommConfig, B134);
cfsetospeed(&Posix_CommConfig, B134);
#endif
break;
/*150 baud*/
case BAUD150:
TTY_PORTABILITY_WARNING("Posix_QextSerialPort Portability Warning: Windows does not support 150 baud operation.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B150;
#else
cfsetispeed(&Posix_CommConfig, B150);
cfsetospeed(&Posix_CommConfig, B150);
#endif
break;
/*200 baud*/
case BAUD200:
TTY_PORTABILITY_WARNING("Posix_QextSerialPort Portability Warning: Windows does not support 200 baud operation.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B200;
#else
cfsetispeed(&Posix_CommConfig, B200);
cfsetospeed(&Posix_CommConfig, B200);
#endif
break;
/*300 baud*/
case BAUD300:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B300;
#else
cfsetispeed(&Posix_CommConfig, B300);
cfsetospeed(&Posix_CommConfig, B300);
#endif
break;
/*600 baud*/
case BAUD600:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B600;
#else
cfsetispeed(&Posix_CommConfig, B600);
cfsetospeed(&Posix_CommConfig, B600);
#endif
break;
/*1200 baud*/
case BAUD1200:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B1200;
#else
cfsetispeed(&Posix_CommConfig, B1200);
cfsetospeed(&Posix_CommConfig, B1200);
#endif
break;
/*1800 baud*/
case BAUD1800:
TTY_PORTABILITY_WARNING("Posix_QextSerialPort Portability Warning: Windows and IRIX do not support 1800 baud operation.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B1800;
#else
cfsetispeed(&Posix_CommConfig, B1800);
cfsetospeed(&Posix_CommConfig, B1800);
#endif
break;
/*2400 baud*/
case BAUD2400:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B2400;
#else
cfsetispeed(&Posix_CommConfig, B2400);
cfsetospeed(&Posix_CommConfig, B2400);
#endif
break;
/*4800 baud*/
case BAUD4800:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B4800;
#else
cfsetispeed(&Posix_CommConfig, B4800);
cfsetospeed(&Posix_CommConfig, B4800);
#endif
break;
/*9600 baud*/
case BAUD9600:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B9600;
#else
cfsetispeed(&Posix_CommConfig, B9600);
cfsetospeed(&Posix_CommConfig, B9600);
#endif
break;
/*14400 baud*/
case BAUD14400:
TTY_WARNING("Posix_QextSerialPort: POSIX does not support 14400 baud operation. Switching to 9600 baud.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B9600;
#else
cfsetispeed(&Posix_CommConfig, B9600);
cfsetospeed(&Posix_CommConfig, B9600);
#endif
break;
/*19200 baud*/
case BAUD19200:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B19200;
#else
cfsetispeed(&Posix_CommConfig, B19200);
cfsetospeed(&Posix_CommConfig, B19200);
#endif
break;
/*38400 baud*/
case BAUD38400:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B38400;
#else
cfsetispeed(&Posix_CommConfig, B38400);
cfsetospeed(&Posix_CommConfig, B38400);
#endif
break;
/*56000 baud*/
case BAUD56000:
TTY_WARNING("Posix_QextSerialPort: POSIX does not support 56000 baud operation. Switching to 38400 baud.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B38400;
#else
cfsetispeed(&Posix_CommConfig, B38400);
cfsetospeed(&Posix_CommConfig, B38400);
#endif
break;
/*57600 baud*/
case BAUD57600:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B57600;
#else
cfsetispeed(&Posix_CommConfig, B57600);
cfsetospeed(&Posix_CommConfig, B57600);
#endif
break;
/*76800 baud*/
case BAUD76800:
TTY_PORTABILITY_WARNING("Posix_QextSerialPort Portability Warning: Windows and some POSIX systems do not support 76800 baud operation.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
#ifdef B76800
Posix_CommConfig.c_cflag|=B76800;
#else
TTY_WARNING("Posix_QextSerialPort: Posix_QextSerialPort was compiled without 76800 baud support. Switching to 57600 baud.");
Posix_CommConfig.c_cflag|=B57600;
#endif //B76800
#else //CBAUD
#ifdef B76800
cfsetispeed(&Posix_CommConfig, B76800);
cfsetospeed(&Posix_CommConfig, B76800);
#else
TTY_WARNING("Posix_QextSerialPort: Posix_QextSerialPort was compiled without 76800 baud support. Switching to 57600 baud.");
cfsetispeed(&Posix_CommConfig, B57600);
cfsetospeed(&Posix_CommConfig, B57600);
#endif //B76800
#endif //CBAUD
break;
/*115200 baud*/
case BAUD115200:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B115200;
#else
cfsetispeed(&Posix_CommConfig, B115200);
cfsetospeed(&Posix_CommConfig, B115200);
#endif
break;
/*128000 baud*/
case BAUD128000:
TTY_WARNING("Posix_QextSerialPort: POSIX does not support 128000 baud operation. Switching to 115200 baud.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B115200;
#else
cfsetispeed(&Posix_CommConfig, B115200);
cfsetospeed(&Posix_CommConfig, B115200);
#endif
break;
/*256000 baud*/
case BAUD256000:
TTY_WARNING("Posix_QextSerialPort: POSIX does not support 256000 baud operation. Switching to 115200 baud.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B115200;
#else
cfsetispeed(&Posix_CommConfig, B115200);
cfsetospeed(&Posix_CommConfig, B115200);
#endif
break;
}
tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig);
}
UNLOCK_MUTEX();
}
/*!
\fn void Posix_QextSerialPort::setDataBits(DataBitsType dataBits)
Sets the number of data bits used by the serial port. Possible values of dataBits are:
\verbatim
DATA_5 5 data bits
DATA_6 6 data bits
DATA_7 7 data bits
DATA_8 8 data bits
\endverbatim
\note
This function is subject to the following restrictions:
\par
5 data bits cannot be used with 2 stop bits.
\par
8 data bits cannot be used with space parity on POSIX systems.
*/
//设置数据位
void Posix_QextSerialPort::setDataBits(DataBitsType dataBits)
{
LOCK_MUTEX();
if (Settings.DataBits!=dataBits) {
if ((Settings.StopBits==STOP_2 && dataBits==DATA_5) ||
(Settings.StopBits==STOP_1_5 && dataBits!=DATA_5) ||
(Settings.Parity==PAR_SPACE && dataBits==DATA_8)) {
}
else {
Settings.DataBits=dataBits;
}
}
if (isOpen()) {
switch(dataBits) {
/*5 data bits*/
case DATA_5:
if (Settings.StopBits==STOP_2) {
TTY_WARNING("Posix_QextSerialPort: 5 Data bits cannot be used with 2 stop bits.");
}
else {
Settings.DataBits=dataBits;
Posix_CommConfig.c_cflag&=(~CSIZE);
Posix_CommConfig.c_cflag|=CS5;
tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig);
}
break;
/*6 data bits*/
case DATA_6:
if (Settings.StopBits==STOP_1_5) {
TTY_WARNING("Posix_QextSerialPort: 6 Data bits cannot be used with 1.5 stop bits.");
}
else {
Settings.DataBits=dataBits;
Posix_CommConfig.c_cflag&=(~CSIZE);
Posix_CommConfig.c_cflag|=CS6;
tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig);
}
break;
/*7 data bits*/
case DATA_7:
if (Settings.StopBits==STOP_1_5) {
TTY_WARNING("Posix_QextSerialPort: 7 Data bits cannot be used with 1.5 stop bits.");
}
else {
Settings.DataBits=dataBits;
Posix_CommConfig.c_cflag&=(~CSIZE);
Posix_CommConfig.c_cflag|=CS7;
tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig);
}
break;
/*8 data bits*/
case DATA_8:
if (Settings.StopBits==STOP_1_5) {
TTY_WARNING("Posix_QextSerialPort: 8 Data bits cannot be used with 1.5 stop bits.");
}
else {
Settings.DataBits=dataBits;
Posix_CommConfig.c_cflag&=(~CSIZE);
Posix_CommConfig.c_cflag|=CS8;
tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig);
}
break;
}
}
UNLOCK_MUTEX();
}
/*!
\fn void Posix_QextSerialPort::setParity(ParityType parity)
Sets the parity associated with the serial port. The possible values of parity are:
\verbatim
PAR_SPACE Space Parity
PAR_MARK Mark Parity
PAR_NONE No Parity
PAR_EVEN Even Parity
PAR_ODD Odd Parity
\endverbatim
\note
This function is subject to the following limitations:
\par
POSIX systems do not support mark parity.
\par
POSIX systems support space parity only if tricked into doing so, and only with
fewer than 8 data bits. Use space parity very carefully with POSIX systems.
*/
void Posix_QextSerialPort::setParity(ParityType parity)
{
LOCK_MUTEX();
if (Settings.Parity!=parity) {
if (parity==PAR_MARK || (parity==PAR_SPACE && Settings.DataBits==DATA_8)) {
}
else {
Settings.Parity=parity;
}
}
if (isOpen()) {
switch (parity) {
/*space parity*/
case PAR_SPACE:
if (Settings.DataBits==DATA_8) {
TTY_PORTABILITY_WARNING("Posix_QextSerialPort: Space parity is only supported in POSIX with 7 or fewer data bits");
}
else {
/*space parity not directly supported - add an extra data bit to simulate it*/
Posix_CommConfig.c_cflag&=~(PARENB|CSIZE);
switch(Settings.DataBits) {
case DATA_5:
Settings.DataBits=DATA_6;
Posix_CommConfig.c_cflag|=CS6;
break;
case DATA_6:
Settings.DataBits=DATA_7;
Posix_CommConfig.c_cflag|=CS7;
break;
case DATA_7:
Settings.DataBits=DATA_8;
Posix_CommConfig.c_cflag|=CS8;
break;
case DATA_8:
break;
}
tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig);
}
break;
/*mark parity - WINDOWS ONLY*/
case PAR_MARK:
TTY_WARNING("Posix_QextSerialPort: Mark parity is not supported by POSIX.");
break;
/*no parity*/
case PAR_NONE:
Posix_CommConfig.c_cflag&=(~PARENB);
tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig);
break;
/*even parity*/
case PAR_EVEN:
Posix_CommConfig.c_cflag&=(~PARODD);
Posix_CommConfig.c_cflag|=PARENB;
tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig);
break;
/*odd parity*/
case PAR_ODD:
Posix_CommConfig.c_cflag|=(PARENB|PARODD);
tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig);
break;
}
}
UNLOCK_MUTEX();
}
/*!
\fn void Posix_QextSerialPort::setStopBits(StopBitsType stopBits)
Sets the number of stop bits used by the serial port. Possible values of stopBits are:
\verbatim
STOP_1 1 stop bit
STOP_1_5 1.5 stop bits
STOP_2 2 stop bits
\endverbatim
\note
This function is subject to the following restrictions:
\par
2 stop bits cannot be used with 5 data bits.
\par
POSIX does not support 1.5 stop bits.
*/
void Posix_QextSerialPort::setStopBits(StopBitsType stopBits)
{
LOCK_MUTEX();
if (Settings.StopBits!=stopBits) {
if ((Settings.DataBits==DATA_5 && stopBits==STOP_2) || stopBits==STOP_1_5) {}
else {
Settings.StopBits=stopBits;
}
}
if (isOpen()) {
switch (stopBits) {
/*one stop bit*/
case STOP_1:
Settings.StopBits=stopBits;
Posix_CommConfig.c_cflag&=(~CSTOPB);
tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig);
break;
/*1.5 stop bits*/
case STOP_1_5:
TTY_WARNING("Posix_QextSerialPort: 1.5 stop bit operation is not supported by POSIX.");
break;
/*two stop bits*/
case STOP_2:
if (Settings.DataBits==DATA_5) {
TTY_WARNING("Posix_QextSerialPort: 2 stop bits cannot be used with 5 data bits");
}
else {
Settings.StopBits=stopBits;
Posix_CommConfig.c_cflag|=CSTOPB;
tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig);
}
break;
}
}
UNLOCK_MUTEX();
}
/*!
\fn void Posix_QextSerialPort::setFlowControl(FlowType flow)
Sets the flow control used by the port. Possible values of flow are:
\verbatim
FLOW_OFF No flow control
FLOW_HARDWARE Hardware (RTS/CTS) flow control
FLOW_XONXOFF Software (XON/XOFF) flow control
\endverbatim
\note
FLOW_HARDWARE may not be supported on all versions of UNIX. In cases where it is
unsupported, FLOW_HARDWARE is the same as FLOW_OFF.
*/
void Posix_QextSerialPort::setFlowControl(FlowType flow)
{
LOCK_MUTEX();
if (Settings.FlowControl!=flow) {
Settings.FlowControl=flow;
}
if (isOpen()) {
switch(flow) {
/*no flow control*/
case FLOW_OFF:
Posix_CommConfig.c_cflag&=(~CRTSCTS);
Posix_CommConfig.c_iflag&=(~(IXON|IXOFF|IXANY));
tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig);
break;
/*software (XON/XOFF) flow control*/
case FLOW_XONXOFF:
Posix_CommConfig.c_cflag&=(~CRTSCTS);
Posix_CommConfig.c_iflag|=(IXON|IXOFF|IXANY);
tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig);
break;
case FLOW_HARDWARE:
Posix_CommConfig.c_cflag|=CRTSCTS;
Posix_CommConfig.c_iflag&=(~(IXON|IXOFF|IXANY));
tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig);
break;
}
}
UNLOCK_MUTEX();
}
/*!
\fn void Posix_QextSerialPort::setTimeout(ulong sec);
Sets the read and write timeouts for the port to millisec milliseconds.
Note that this is a per-character timeout, i.e. the port will wait this long for each
individual character, not for the whole read operation. This timeout also applies to the
bytesWaiting() function.
\note
POSIX does not support millisecond-level control for I/O timeout values. Any
timeout set using this function will be set to the next lowest tenth of a second for
the purposes of detecting read or write timeouts. For example a timeout of 550 milliseconds
will be seen by the class as a timeout of 500 milliseconds for the purposes of reading and
writing the port. However millisecond-level control is allowed by the select() system call,
so for example a 550-millisecond timeout will be seen as 550 milliseconds on POSIX systems for
the purpose of detecting available bytes in the read buffer.
*/
void Posix_QextSerialPort::setTimeout(long millisec)
{
LOCK_MUTEX();
Settings.Timeout_Millisec = millisec;
Posix_Copy_Timeout.tv_sec = millisec / 1000;
Posix_Copy_Timeout.tv_usec = millisec % 1000;
if (isOpen()) {
tcgetattr(Posix_File->handle(), &Posix_CommConfig);
Posix_CommConfig.c_cc[VTIME] = millisec/100;
tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig);
}
UNLOCK_MUTEX();
}
/*!
\fn bool Posix_QextSerialPort::open(OpenMode mode)
Opens the serial port associated to this class.
This function has no effect if the port associated with the class is already open.
The port is also configured to the current settings, as stored in the Settings structure.
*/
bool Posix_QextSerialPort::open(OpenMode mode)
{
LOCK_MUTEX();
if (mode == QIODevice::NotOpen)
return isOpen();
if (!isOpen()) {
/*open the port*/
Posix_File->setFileName(port);
qDebug("Trying to open File");
if (Posix_File->open(QIODevice::ReadWrite|QIODevice::Unbuffered)) {
qDebug("Opened File succesfully");
/*set open mode*/
QIODevice::open(mode);
/*configure port settings*/
tcgetattr(Posix_File->handle(), &Posix_CommConfig);
/*set up other port settings*/
Posix_CommConfig.c_cflag|=CREAD|CLOCAL;
Posix_CommConfig.c_lflag&=(~(ICANON|ECHO|ECHOE|ECHOK|ECHONL|ISIG));
Posix_CommConfig.c_iflag&=(~(INPCK|IGNPAR|PARMRK|ISTRIP|ICRNL|IXANY));
Posix_CommConfig.c_oflag&=(~OPOST);
Posix_CommConfig.c_cc[VMIN]=0;
Posix_CommConfig.c_cc[VINTR] = _POSIX_VDISABLE;
Posix_CommConfig.c_cc[VQUIT] = _POSIX_VDISABLE;
Posix_CommConfig.c_cc[VSTART] = _POSIX_VDISABLE;
Posix_CommConfig.c_cc[VSTOP] = _POSIX_VDISABLE;
Posix_CommConfig.c_cc[VSUSP] = _POSIX_VDISABLE;
setBaudRate(Settings.BaudRate);
setDataBits(Settings.DataBits);
setParity(Settings.Parity);
setStopBits(Settings.StopBits);
setFlowControl(Settings.FlowControl);
//by hqw
//setTimeout(Settings.Timeout_Sec, Settings.Timeout_Millisec); //这个地方会出现Timeout_Sec未定义错误,修改如下
setTimeout(Settings.Timeout_Millisec);
//end by
tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig);
} else {
qDebug("Could not open File! Error code : %d", Posix_File->error());
}
}
UNLOCK_MUTEX();
return isOpen();
}
/*!
\fn void Posix_QextSerialPort::close()
Closes a serial port. This function has no effect if the serial port associated with the class
is not currently open.
*/
void Posix_QextSerialPort::close()
{
LOCK_MUTEX();
Posix_File->close();
QIODevice::close();
UNLOCK_MUTEX();
}
/*!
\fn void Posix_QextSerialPort::flush()
Flushes all pending I/O to the serial port. This function has no effect if the serial port
associated with the class is not currently open.
*/
//清空串口缓冲区所有输入输出数据,如果串口未被打开则什么都不做
void Posix_QextSerialPort::flush()
{
LOCK_MUTEX();
if (isOpen()) {
Posix_File->flush();
}
UNLOCK_MUTEX();
}
/*!
\fn qint64 Posix_QextSerialPort::size() const
This function will return the number of bytes waiting in the receive queue of the serial port.
It is included primarily to provide a complete QIODevice interface, and will not record errors
in the lastErr member (because it is const). This function is also not thread-safe - in
multithreading situations, use Posix_QextSerialPort::bytesWaiting() instead.
*/
//返回串口缓冲区内字节总数
qint64 Posix_QextSerialPort::size() const
{
int numBytes;
if (ioctl(Posix_File->handle(), FIONREAD, &numBytes)<0) {
numBytes=0;
}
return (qint64)numBytes;
}
/*!
\fn qint64 Posix_QextSerialPort::bytesAvailable()
Returns the number of bytes waiting in the port's receive queue. This function will return 0 if
the port is not currently open, or -1 on error. Error information can be retrieved by calling
Posix_QextSerialPort::getLastError().
*/
//返回串口数据字节总数,如果串口未被打开返回0,如果出错返回-1
qint64 Posix_QextSerialPort::bytesAvailable()
{
LOCK_MUTEX();
if (isOpen()) {
int bytesQueued;
fd_set fileSet;
FD_ZERO(&fileSet);
FD_SET(Posix_File->handle(), &fileSet);
/*on Linux systems the Posix_Timeout structure will be altered by the select() call.
Make sure we use the right timeout values*/
//memcpy(&Posix_Timeout, &Posix_Copy_Timeout, sizeof(struct timeval));
Posix_Timeout = Posix_Copy_Timeout;
int n=select(Posix_File->handle()+1, &fileSet, NULL, &fileSet, &Posix_Timeout);
if (!n) {
lastErr=E_PORT_TIMEOUT;
UNLOCK_MUTEX();
return -1;
}
if (n==-1 || ioctl(Posix_File->handle(), FIONREAD, &bytesQueued)==-1) {
translateError(errno);
UNLOCK_MUTEX();
return -1;
}
lastErr=E_NO_ERROR;
UNLOCK_MUTEX();
return bytesQueued + QIODevice::bytesAvailable();
}
UNLOCK_MUTEX();
return 0;
}
/*!
\fn void Posix_QextSerialPort::ungetChar(char)
This function is included to implement the full QIODevice interface, and currently has no
purpose within this class. This function is meaningless on an unbuffered device and currently
only prints a warning message to that effect.
*/
void Posix_QextSerialPort::ungetChar(char)
{
/*meaningless on unbuffered sequential device - return error and print a warning*/
TTY_WARNING("Posix_QextSerialPort: ungetChar() called on an unbuffered sequential device - operation is meaningless");
}
/*!
\fn void Posix_QextSerialPort::translateError(ulong error)
Translates a system-specific error code to a QextSerialPort error code. Used internally.
*/
void Posix_QextSerialPort::translateError(ulong error)
{
switch (error) {
case EBADF:
case ENOTTY:
lastErr=E_INVALID_FD;
break;
case EINTR:
lastErr=E_CAUGHT_NON_BLOCKED_SIGNAL;
break;
case ENOMEM:
lastErr=E_NO_MEMORY;
break;
}
}
/*!
\fn void Posix_QextSerialPort::setDtr(bool set)
Sets DTR line to the requested state (high by default). This function will have no effect if
the port associated with the class is not currently open.
*/
void Posix_QextSerialPort::setDtr(bool set)
{
LOCK_MUTEX();
if (isOpen()) {
int status;
ioctl(Posix_File->handle(), TIOCMGET, &status);
if (set) {
status|=TIOCM_DTR;
}
else {
status&=~TIOCM_DTR;
}
ioctl(Posix_File->handle(), TIOCMSET, &status);
}
UNLOCK_MUTEX();
}
/*!
\fn void Posix_QextSerialPort::setRts(bool set)
Sets RTS line to the requested state (high by default). This function will have no effect if
the port associated with the class is not currently open.
*/
void Posix_QextSerialPort::setRts(bool set)
{
LOCK_MUTEX();
if (isOpen()) {
int status;
ioctl(Posix_File->handle(), TIOCMGET, &status);
if (set) {
status|=TIOCM_RTS;
}
else {
status&=~TIOCM_RTS;
}
ioctl(Posix_File->handle(), TIOCMSET, &status);
}
UNLOCK_MUTEX();
}
/*!
\fn unsigned long Posix_QextSerialPort::lineStatus()
returns the line status as stored by the port function. This function will retrieve the states
of the following lines: DCD, CTS, DSR, and RI. On POSIX systems, the following additional lines
can be monitored: DTR, RTS, Secondary TXD, and Secondary RXD. The value returned is an unsigned
long with specific bits indicating which lines are high. The following constants should be used
to examine the states of individual lines:
\verbatim
Mask Line
------ ----
LS_CTS CTS
LS_DSR DSR
LS_DCD DCD
LS_RI RI
LS_RTS RTS (POSIX only)
LS_DTR DTR (POSIX only)
LS_ST Secondary TXD (POSIX only)
LS_SR Secondary RXD (POSIX only)
\endverbatim
This function will return 0 if the port associated with the class is not currently open.
*/
unsigned long Posix_QextSerialPort::lineStatus()
{
unsigned long Status=0, Temp=0;
LOCK_MUTEX();
if (isOpen()) {
ioctl(Posix_File->handle(), TIOCMGET, &Temp);
if (Temp&TIOCM_CTS) {
Status|=LS_CTS;
}
if (Temp&TIOCM_DSR) {
Status|=LS_DSR;
}
if (Temp&TIOCM_RI) {
Status|=LS_RI;
}
if (Temp&TIOCM_CD) {
Status|=LS_DCD;
}
if (Temp&TIOCM_DTR) {
Status|=LS_DTR;
}
if (Temp&TIOCM_RTS) {
Status|=LS_RTS;
}
if (Temp&TIOCM_ST) {
Status|=LS_ST;
}
if (Temp&TIOCM_SR) {
Status|=LS_SR;
}
}
UNLOCK_MUTEX();
return Status;
}
/*!
\fn qint64 Posix_QextSerialPort::readData(char * data, qint64 maxSize)
Reads a block of data from the serial port. This function will read at most maxSize bytes from
the serial port and place them in the buffer pointed to by data. Return value is the number of
bytes actually read, or -1 on error.
\warning before calling this function ensure that serial port associated with this class
is currently open (use isOpen() function to check if port is open).
*/
qint64 Posix_QextSerialPort::readData(char * data, qint64 maxSize)
{
LOCK_MUTEX();
int retVal=0;
retVal=Posix_File->read(data, maxSize);
if (retVal==-1)
lastErr=E_READ_FAILED;
UNLOCK_MUTEX();
return retVal;
}
/*!
\fn qint64 Posix_QextSerialPort::writeData(const char * data, qint64 maxSize)
Writes a block of data to the serial port. This function will write maxSize bytes
from the buffer pointed to by data to the serial port. Return value is the number
of bytes actually written, or -1 on error.
\warning before calling this function ensure that serial port associated with this class
is currently open (use isOpen() function to check if port is open).
*/
qint64 Posix_QextSerialPort::writeData(const char * data, qint64 maxSize)
{
LOCK_MUTEX();
int retVal=0;
retVal=Posix_File->write(data, maxSize);
if (retVal==-1)
lastErr=E_WRITE_FAILED;
UNLOCK_MUTEX();
return retVal;
}
| [
"[email protected]"
]
| [
[
[
1,
1135
]
]
]
|
b689fb20e42b5bf408df3750df398cf195cd7879 | af96c6474835be2cc34ef21b0c2a45e950bb9148 | /core/jni/android/graphics/Bitmap.cpp | f2ebefb3a1a780881f8cd74a7b17af1e7b64f608 | [
"Apache-2.0",
"LicenseRef-scancode-unicode"
]
| permissive | zsol/android_frameworks_base | 86abe37fcd4136923cab2d6677e558826f087cf9 | 8d18426076382edaaea68392a0298d2c32cfa52e | refs/heads/donut | 2021-07-04T17:24:05.847586 | 2010-01-13T19:24:55 | 2010-01-13T19:24:55 | 469,422 | 14 | 12 | NOASSERTION | 2020-10-01T18:05:31 | 2010-01-12T21:20:20 | Java | UTF-8 | C++ | false | false | 20,074 | cpp | #include "SkBitmap.h"
#include "SkImageEncoder.h"
#include "SkColorPriv.h"
#include "GraphicsJNI.h"
#include "SkDither.h"
#include "SkUnPreMultiply.h"
#include <utils/Parcel.h>
#include "android_util_Binder.h"
#include "android_nio_utils.h"
#include "CreateJavaOutputStreamAdaptor.h"
#include <jni.h>
#if 0
#define TRACE_BITMAP(code) code
#else
#define TRACE_BITMAP(code)
#endif
///////////////////////////////////////////////////////////////////////////////
// Conversions to/from SkColor, for get/setPixels, and the create method, which
// is basically like setPixels
typedef void (*FromColorProc)(void* dst, const SkColor src[], int width,
int x, int y);
static void FromColor_D32(void* dst, const SkColor src[], int width,
int, int) {
SkPMColor* d = (SkPMColor*)dst;
for (int i = 0; i < width; i++) {
*d++ = SkPreMultiplyColor(*src++);
}
}
static void FromColor_D565(void* dst, const SkColor src[], int width,
int x, int y) {
uint16_t* d = (uint16_t*)dst;
DITHER_565_SCAN(y);
for (int stop = x + width; x < stop; x++) {
SkColor c = *src++;
*d++ = SkDitherRGBTo565(SkColorGetR(c), SkColorGetG(c), SkColorGetB(c),
DITHER_VALUE(x));
}
}
static void FromColor_D4444(void* dst, const SkColor src[], int width,
int x, int y) {
SkPMColor16* d = (SkPMColor16*)dst;
DITHER_4444_SCAN(y);
for (int stop = x + width; x < stop; x++) {
SkPMColor c = SkPreMultiplyColor(*src++);
*d++ = SkDitherARGB32To4444(c, DITHER_VALUE(x));
// *d++ = SkPixel32ToPixel4444(c);
}
}
// can return NULL
static FromColorProc ChooseFromColorProc(SkBitmap::Config config) {
switch (config) {
case SkBitmap::kARGB_8888_Config:
return FromColor_D32;
case SkBitmap::kARGB_4444_Config:
return FromColor_D4444;
case SkBitmap::kRGB_565_Config:
return FromColor_D565;
default:
break;
}
return NULL;
}
bool GraphicsJNI::SetPixels(JNIEnv* env, jintArray srcColors,
int srcOffset, int srcStride,
int x, int y, int width, int height,
const SkBitmap& dstBitmap) {
SkAutoLockPixels alp(dstBitmap);
void* dst = dstBitmap.getPixels();
FromColorProc proc = ChooseFromColorProc(dstBitmap.config());
if (NULL == dst || NULL == proc) {
return false;
}
const jint* array = env->GetIntArrayElements(srcColors, NULL);
const SkColor* src = (const SkColor*)array + srcOffset;
// reset to to actual choice from caller
dst = dstBitmap.getAddr(x, y);
// now copy/convert each scanline
for (int y = 0; y < height; y++) {
proc(dst, src, width, x, y);
src += srcStride;
dst = (char*)dst + dstBitmap.rowBytes();
}
env->ReleaseIntArrayElements(srcColors, const_cast<jint*>(array),
JNI_ABORT);
return true;
}
//////////////////// ToColor procs
typedef void (*ToColorProc)(SkColor dst[], const void* src, int width,
SkColorTable*);
static void ToColor_S32_Alpha(SkColor dst[], const void* src, int width,
SkColorTable*) {
SkASSERT(width > 0);
const SkPMColor* s = (const SkPMColor*)src;
do {
*dst++ = SkUnPreMultiply::PMColorToColor(*s++);
} while (--width != 0);
}
static void ToColor_S32_Opaque(SkColor dst[], const void* src, int width,
SkColorTable*) {
SkASSERT(width > 0);
const SkPMColor* s = (const SkPMColor*)src;
do {
SkPMColor c = *s++;
*dst++ = SkColorSetRGB(SkGetPackedR32(c), SkGetPackedG32(c),
SkGetPackedB32(c));
} while (--width != 0);
}
static void ToColor_S4444_Alpha(SkColor dst[], const void* src, int width,
SkColorTable*) {
SkASSERT(width > 0);
const SkPMColor16* s = (const SkPMColor16*)src;
do {
*dst++ = SkUnPreMultiply::PMColorToColor(SkPixel4444ToPixel32(*s++));
} while (--width != 0);
}
static void ToColor_S4444_Opaque(SkColor dst[], const void* src, int width,
SkColorTable*) {
SkASSERT(width > 0);
const SkPMColor* s = (const SkPMColor*)src;
do {
SkPMColor c = SkPixel4444ToPixel32(*s++);
*dst++ = SkColorSetRGB(SkGetPackedR32(c), SkGetPackedG32(c),
SkGetPackedB32(c));
} while (--width != 0);
}
static void ToColor_S565(SkColor dst[], const void* src, int width,
SkColorTable*) {
SkASSERT(width > 0);
const uint16_t* s = (const uint16_t*)src;
do {
uint16_t c = *s++;
*dst++ = SkColorSetRGB(SkPacked16ToR32(c), SkPacked16ToG32(c),
SkPacked16ToB32(c));
} while (--width != 0);
}
static void ToColor_SI8_Alpha(SkColor dst[], const void* src, int width,
SkColorTable* ctable) {
SkASSERT(width > 0);
const uint8_t* s = (const uint8_t*)src;
const SkPMColor* colors = ctable->lockColors();
do {
*dst++ = SkUnPreMultiply::PMColorToColor(colors[*s++]);
} while (--width != 0);
ctable->unlockColors(false);
}
static void ToColor_SI8_Opaque(SkColor dst[], const void* src, int width,
SkColorTable* ctable) {
SkASSERT(width > 0);
const uint8_t* s = (const uint8_t*)src;
const SkPMColor* colors = ctable->lockColors();
do {
SkPMColor c = colors[*s++];
*dst++ = SkColorSetRGB(SkGetPackedR32(c), SkGetPackedG32(c),
SkGetPackedB32(c));
} while (--width != 0);
ctable->unlockColors(false);
}
// can return NULL
static ToColorProc ChooseToColorProc(const SkBitmap& src) {
switch (src.config()) {
case SkBitmap::kARGB_8888_Config:
return src.isOpaque() ? ToColor_S32_Opaque : ToColor_S32_Alpha;
case SkBitmap::kARGB_4444_Config:
return src.isOpaque() ? ToColor_S4444_Opaque : ToColor_S4444_Alpha;
case SkBitmap::kRGB_565_Config:
return ToColor_S565;
case SkBitmap::kIndex8_Config:
if (src.getColorTable() == NULL) {
return NULL;
}
return src.isOpaque() ? ToColor_SI8_Opaque : ToColor_SI8_Alpha;
default:
break;
}
return NULL;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
static jobject Bitmap_creator(JNIEnv* env, jobject, jintArray jColors,
int offset, int stride, int width, int height,
SkBitmap::Config config, jboolean isMutable) {
if (width <= 0 || height <= 0) {
doThrowIAE(env, "width and height must be > 0");
return NULL;
}
if (NULL != jColors) {
size_t n = env->GetArrayLength(jColors);
if (n < SkAbs32(stride) * (size_t)height) {
doThrowAIOOBE(env);
return NULL;
}
}
SkBitmap bitmap;
bitmap.setConfig(config, width, height);
if (!GraphicsJNI::setJavaPixelRef(env, &bitmap, NULL, true)) {
return NULL;
}
if (jColors != NULL) {
GraphicsJNI::SetPixels(env, jColors, offset, stride,
0, 0, width, height, bitmap);
}
return GraphicsJNI::createBitmap(env, new SkBitmap(bitmap), isMutable,
NULL);
}
static jobject Bitmap_copy(JNIEnv* env, jobject, const SkBitmap* src,
SkBitmap::Config dstConfig, jboolean isMutable) {
SkBitmap result;
JavaPixelAllocator allocator(env, true);
if (!src->copyTo(&result, dstConfig, &allocator)) {
return NULL;
}
return GraphicsJNI::createBitmap(env, new SkBitmap(result), isMutable,
NULL);
}
static void Bitmap_destructor(JNIEnv* env, jobject, SkBitmap* bitmap) {
delete bitmap;
}
static void Bitmap_recycle(JNIEnv* env, jobject, SkBitmap* bitmap) {
bitmap->setPixels(NULL, NULL);
}
// These must match the int values in Bitmap.java
enum JavaEncodeFormat {
kJPEG_JavaEncodeFormat = 0,
kPNG_JavaEncodeFormat = 1
};
static bool Bitmap_compress(JNIEnv* env, jobject clazz, SkBitmap* bitmap,
int format, int quality,
jobject jstream, jbyteArray jstorage) {
SkImageEncoder::Type fm;
switch (format) {
case kJPEG_JavaEncodeFormat:
fm = SkImageEncoder::kJPEG_Type;
break;
case kPNG_JavaEncodeFormat:
fm = SkImageEncoder::kPNG_Type;
break;
default:
return false;
}
bool success = false;
SkWStream* strm = CreateJavaOutputStreamAdaptor(env, jstream, jstorage);
if (NULL != strm) {
SkImageEncoder* encoder = SkImageEncoder::Create(fm);
if (NULL != encoder) {
success = encoder->encodeStream(strm, *bitmap, quality);
delete encoder;
}
delete strm;
}
return success;
}
static void Bitmap_erase(JNIEnv* env, jobject, SkBitmap* bitmap, jint color) {
bitmap->eraseColor(color);
}
static int Bitmap_width(JNIEnv* env, jobject, SkBitmap* bitmap) {
return bitmap->width();
}
static int Bitmap_height(JNIEnv* env, jobject, SkBitmap* bitmap) {
return bitmap->height();
}
static int Bitmap_rowBytes(JNIEnv* env, jobject, SkBitmap* bitmap) {
return bitmap->rowBytes();
}
static int Bitmap_config(JNIEnv* env, jobject, SkBitmap* bitmap) {
return bitmap->config();
}
static jboolean Bitmap_hasAlpha(JNIEnv* env, jobject, SkBitmap* bitmap) {
return !bitmap->isOpaque();
}
static void Bitmap_setHasAlpha(JNIEnv* env, jobject, SkBitmap* bitmap,
jboolean hasAlpha) {
bitmap->setIsOpaque(!hasAlpha);
}
///////////////////////////////////////////////////////////////////////////////
static jobject Bitmap_createFromParcel(JNIEnv* env, jobject, jobject parcel) {
if (parcel == NULL) {
SkDebugf("-------- unparcel parcel is NULL\n");
return NULL;
}
android::Parcel* p = android::parcelForJavaObject(env, parcel);
const bool isMutable = p->readInt32() != 0;
const SkBitmap::Config config = (SkBitmap::Config)p->readInt32();
const int width = p->readInt32();
const int height = p->readInt32();
const int rowBytes = p->readInt32();
const int density = p->readInt32();
if (SkBitmap::kARGB_8888_Config != config &&
SkBitmap::kRGB_565_Config != config &&
SkBitmap::kARGB_4444_Config != config &&
SkBitmap::kIndex8_Config != config &&
SkBitmap::kA8_Config != config) {
SkDebugf("Bitmap_createFromParcel unknown config: %d\n", config);
return NULL;
}
SkBitmap* bitmap = new SkBitmap;
bitmap->setConfig(config, width, height, rowBytes);
SkColorTable* ctable = NULL;
if (config == SkBitmap::kIndex8_Config) {
int count = p->readInt32();
if (count > 0) {
size_t size = count * sizeof(SkPMColor);
const SkPMColor* src = (const SkPMColor*)p->readInplace(size);
ctable = new SkColorTable(src, count);
}
}
if (!GraphicsJNI::setJavaPixelRef(env, bitmap, ctable, true)) {
ctable->safeUnref();
delete bitmap;
return NULL;
}
ctable->safeUnref();
size_t size = bitmap->getSize();
bitmap->lockPixels();
memcpy(bitmap->getPixels(), p->readInplace(size), size);
bitmap->unlockPixels();
return GraphicsJNI::createBitmap(env, bitmap, isMutable, NULL, density);
}
static jboolean Bitmap_writeToParcel(JNIEnv* env, jobject,
const SkBitmap* bitmap,
jboolean isMutable, jint density,
jobject parcel) {
if (parcel == NULL) {
SkDebugf("------- writeToParcel null parcel\n");
return false;
}
android::Parcel* p = android::parcelForJavaObject(env, parcel);
p->writeInt32(isMutable);
p->writeInt32(bitmap->config());
p->writeInt32(bitmap->width());
p->writeInt32(bitmap->height());
p->writeInt32(bitmap->rowBytes());
p->writeInt32(density);
if (bitmap->getConfig() == SkBitmap::kIndex8_Config) {
SkColorTable* ctable = bitmap->getColorTable();
if (ctable != NULL) {
int count = ctable->count();
p->writeInt32(count);
memcpy(p->writeInplace(count * sizeof(SkPMColor)),
ctable->lockColors(), count * sizeof(SkPMColor));
ctable->unlockColors(false);
} else {
p->writeInt32(0); // indicate no ctable
}
}
size_t size = bitmap->getSize();
bitmap->lockPixels();
memcpy(p->writeInplace(size), bitmap->getPixels(), size);
bitmap->unlockPixels();
return true;
}
static jobject Bitmap_extractAlpha(JNIEnv* env, jobject clazz,
const SkBitmap* src, const SkPaint* paint,
jintArray offsetXY) {
SkIPoint offset;
SkBitmap* dst = new SkBitmap;
src->extractAlpha(dst, paint, &offset);
if (offsetXY != 0 && env->GetArrayLength(offsetXY) >= 2) {
int* array = env->GetIntArrayElements(offsetXY, NULL);
array[0] = offset.fX;
array[1] = offset.fY;
env->ReleaseIntArrayElements(offsetXY, array, 0);
}
return GraphicsJNI::createBitmap(env, dst, true, NULL);
}
///////////////////////////////////////////////////////////////////////////////
static int Bitmap_getPixel(JNIEnv* env, jobject, const SkBitmap* bitmap,
int x, int y) {
SkAutoLockPixels alp(*bitmap);
ToColorProc proc = ChooseToColorProc(*bitmap);
if (NULL == proc) {
return 0;
}
const void* src = bitmap->getAddr(x, y);
if (NULL == src) {
return 0;
}
SkColor dst[1];
proc(dst, src, 1, bitmap->getColorTable());
return dst[0];
}
static void Bitmap_getPixels(JNIEnv* env, jobject, const SkBitmap* bitmap,
jintArray pixelArray, int offset, int stride,
int x, int y, int width, int height) {
SkAutoLockPixels alp(*bitmap);
ToColorProc proc = ChooseToColorProc(*bitmap);
if (NULL == proc) {
return;
}
const void* src = bitmap->getAddr(x, y);
if (NULL == src) {
return;
}
SkColorTable* ctable = bitmap->getColorTable();
jint* dst = env->GetIntArrayElements(pixelArray, NULL);
SkColor* d = (SkColor*)dst + offset;
while (--height >= 0) {
proc(d, src, width, ctable);
d += stride;
src = (void*)((const char*)src + bitmap->rowBytes());
}
env->ReleaseIntArrayElements(pixelArray, dst, 0);
}
///////////////////////////////////////////////////////////////////////////////
static void Bitmap_setPixel(JNIEnv* env, jobject, const SkBitmap* bitmap,
int x, int y, SkColor color) {
SkAutoLockPixels alp(*bitmap);
if (NULL == bitmap->getPixels()) {
return;
}
FromColorProc proc = ChooseFromColorProc(bitmap->config());
if (NULL == proc) {
return;
}
proc(bitmap->getAddr(x, y), &color, 1, x, y);
}
static void Bitmap_setPixels(JNIEnv* env, jobject, const SkBitmap* bitmap,
jintArray pixelArray, int offset, int stride,
int x, int y, int width, int height) {
GraphicsJNI::SetPixels(env, pixelArray, offset, stride,
x, y, width, height, *bitmap);
}
static void Bitmap_copyPixelsToBuffer(JNIEnv* env, jobject,
const SkBitmap* bitmap, jobject jbuffer) {
SkAutoLockPixels alp(*bitmap);
const void* src = bitmap->getPixels();
if (NULL != src) {
android::AutoBufferPointer abp(env, jbuffer, JNI_TRUE);
// the java side has already checked that buffer is large enough
memcpy(abp.pointer(), src, bitmap->getSize());
}
}
static void Bitmap_copyPixelsFromBuffer(JNIEnv* env, jobject,
const SkBitmap* bitmap, jobject jbuffer) {
SkAutoLockPixels alp(*bitmap);
void* dst = bitmap->getPixels();
if (NULL != dst) {
android::AutoBufferPointer abp(env, jbuffer, JNI_FALSE);
// the java side has already checked that buffer is large enough
memcpy(dst, abp.pointer(), bitmap->getSize());
}
}
static void Bitmap_prepareToDraw(JNIEnv* env, jobject, SkBitmap* bitmap) {
bitmap->lockPixels();
bitmap->unlockPixels();
}
///////////////////////////////////////////////////////////////////////////////
#include <android_runtime/AndroidRuntime.h>
static JNINativeMethod gBitmapMethods[] = {
{ "nativeCreate", "([IIIIIIZ)Landroid/graphics/Bitmap;",
(void*)Bitmap_creator },
{ "nativeCopy", "(IIZ)Landroid/graphics/Bitmap;",
(void*)Bitmap_copy },
{ "nativeDestructor", "(I)V", (void*)Bitmap_destructor },
{ "nativeRecycle", "(I)V", (void*)Bitmap_recycle },
{ "nativeCompress", "(IIILjava/io/OutputStream;[B)Z",
(void*)Bitmap_compress },
{ "nativeErase", "(II)V", (void*)Bitmap_erase },
{ "nativeWidth", "(I)I", (void*)Bitmap_width },
{ "nativeHeight", "(I)I", (void*)Bitmap_height },
{ "nativeRowBytes", "(I)I", (void*)Bitmap_rowBytes },
{ "nativeConfig", "(I)I", (void*)Bitmap_config },
{ "nativeHasAlpha", "(I)Z", (void*)Bitmap_hasAlpha },
{ "nativeSetHasAlpha", "(IZ)V", (void*)Bitmap_setHasAlpha },
{ "nativeCreateFromParcel",
"(Landroid/os/Parcel;)Landroid/graphics/Bitmap;",
(void*)Bitmap_createFromParcel },
{ "nativeWriteToParcel", "(IZILandroid/os/Parcel;)Z",
(void*)Bitmap_writeToParcel },
{ "nativeExtractAlpha", "(II[I)Landroid/graphics/Bitmap;",
(void*)Bitmap_extractAlpha },
{ "nativeGetPixel", "(III)I", (void*)Bitmap_getPixel },
{ "nativeGetPixels", "(I[IIIIIII)V", (void*)Bitmap_getPixels },
{ "nativeSetPixel", "(IIII)V", (void*)Bitmap_setPixel },
{ "nativeSetPixels", "(I[IIIIIII)V", (void*)Bitmap_setPixels },
{ "nativeCopyPixelsToBuffer", "(ILjava/nio/Buffer;)V",
(void*)Bitmap_copyPixelsToBuffer },
{ "nativeCopyPixelsFromBuffer", "(ILjava/nio/Buffer;)V",
(void*)Bitmap_copyPixelsFromBuffer },
{ "nativePrepareToDraw", "(I)V", (void*)Bitmap_prepareToDraw }
};
#define kClassPathName "android/graphics/Bitmap"
int register_android_graphics_Bitmap(JNIEnv* env);
int register_android_graphics_Bitmap(JNIEnv* env)
{
return android::AndroidRuntime::registerNativeMethods(env, kClassPathName,
gBitmapMethods, SK_ARRAY_COUNT(gBitmapMethods));
}
| [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
]
| [
[
[
1,
7
],
[
9,
30
],
[
32,
39
],
[
41,
51
],
[
53,
82
],
[
84,
86
],
[
88,
89
],
[
91,
98
],
[
100,
214
],
[
216,
224
],
[
226,
226
],
[
228,
234
],
[
236,
242
],
[
244,
247
],
[
249,
319
],
[
325,
331
],
[
333,
333
],
[
335,
339
],
[
342,
363
],
[
366,
376
],
[
379,
382
],
[
385,
390
],
[
392,
396
],
[
398,
423
],
[
425,
431
],
[
433,
449
],
[
451,
459
],
[
461,
508
],
[
510,
521
],
[
523,
529
],
[
535,
553
],
[
555,
557
],
[
559,
568
],
[
571,
581
]
],
[
[
8,
8
],
[
320,
324
],
[
554,
554
]
],
[
[
31,
31
],
[
40,
40
],
[
52,
52
],
[
83,
83
],
[
87,
87
],
[
90,
90
],
[
99,
99
],
[
215,
215
],
[
225,
225
],
[
235,
235
],
[
248,
248
],
[
332,
332
],
[
334,
334
],
[
341,
341
],
[
364,
364
],
[
377,
377
],
[
391,
391
],
[
424,
424
],
[
432,
432
],
[
450,
450
],
[
460,
460
],
[
509,
509
],
[
522,
522
],
[
530,
534
],
[
569,
570
]
],
[
[
227,
227
],
[
243,
243
],
[
365,
365
]
],
[
[
340,
340
],
[
378,
378
],
[
383,
384
],
[
397,
397
],
[
558,
558
]
]
]
|
81ef8733b6921fe01e91a1e65fba51fc53ac46b4 | 57d74ff818cabf449d3ad457bcc54c5d78550352 | /8.0/SpiraTestCompletePlugIn/atlcache.h | 78e09e3a31f2fbd4c5b5062135da4a92148120f9 | []
| no_license | Inflectra/spira-testing-test-complete | f6e28f558b97689331ee2107501eb121341aabdb | 9bcf5d3286dd3bba492bc432511be193becca547 | refs/heads/main | 2023-04-09T07:14:02.796898 | 2010-08-05T17:39:00 | 2010-08-05T17:39:00 | 359,174,921 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 78,035 | h | // This is a part of the Active Template Library.
// Copyright (C) Microsoft Corporation
// All rights reserved.
//
// This source code is only intended as a supplement to the
// Active Template Library Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Active Template Library product.
#ifndef __ATLCACHE_H__
#define __ATLCACHE_H__
#pragma once
#include <atltime.h>
#include <atlutil.h>
#include <atlcoll.h>
#include "atlperf.h"
#include <atlcom.h>
#include <atlstr.h>
#include "atlsrvres.h"
#include <atldbcli.h>
#include "atlspriv.h"
#include <atlutil.h>
#pragma warning (push)
#ifndef _ATL_NO_PRAGMA_WARNINGS
#pragma warning(disable: 4511) // copy constructor could not be generated
#pragma warning(disable: 4512) // assignment operator could not be generated
#endif //!_ATL_NO_PRAGMA_WARNINGS
#pragma warning(disable: 4625) // copy constructor could not be generated because a base class copy constructor is inaccessible
#pragma warning(disable: 4626) // assignment operator could not be generated because a base class assignment operator is inaccessible
#ifndef _CPPUNWIND
#pragma warning(disable: 4702) // unreachable code
#endif
#pragma pack(push,_ATL_PACKING)
namespace ATL {
//forward declarations;
class CStdStatClass;
class CPerfStatClass;
typedef struct __CACHEITEM
{
} *HCACHEITEM;
//Implementation of a cache that stores pointers to void
extern "C" __declspec(selectany) const IID IID_IMemoryCacheClient = {0xb721b49d, 0xbb57, 0x47bc, { 0xac, 0x43, 0xa8, 0xd4, 0xc0, 0x7d, 0x18, 0x3d } };
extern "C" __declspec(selectany) const IID IID_IMemoryCache = { 0x9c6cfb46, 0xfbde, 0x4f8b, { 0xb9, 0x44, 0x2a, 0xa0, 0x5d, 0x96, 0xeb, 0x5c } };
extern "C" __declspec(selectany) const IID IID_IMemoryCacheControl = { 0x7634b28b, 0xd819, 0x409d, { 0xb9, 0x6e, 0xfc, 0x9f, 0x3a, 0xba, 0x32, 0x9f } };
extern "C" __declspec(selectany) const IID IID_IMemoryCacheStats = { 0xd4b6df2d, 0x4bc0, 0x4734, { 0x8a, 0xce, 0xb7, 0x3a, 0xb, 0x97, 0x59, 0x56 } };
__interface ATL_NO_VTABLE __declspec(uuid("b721b49d-bb57-47bc-ac43-a8d4c07d183d"))
IMemoryCacheClient : public IUnknown
{
// IMemoryCacheClient methods
STDMETHOD( Free )(const void *pvData);
};
__interface ATL_NO_VTABLE __declspec(uuid("9c6cfb46-fbde-4f8b-b944-2aa05d96eb5c"))
IMemoryCache : public IUnknown
{
// IMemoryCache Methods
STDMETHOD(Add)(LPCSTR szKey, void *pvData, DWORD dwSize,
FILETIME *pftExpireTime,
HINSTANCE hInstClient, HCACHEITEM *phEntry,
IMemoryCacheClient *pClient);
STDMETHOD(LookupEntry)(LPCSTR szKey, HCACHEITEM * phEntry);
STDMETHOD(GetData)(const HCACHEITEM hEntry, void **ppvData, DWORD *pdwSize) const;
STDMETHOD(ReleaseEntry)(const HCACHEITEM hEntry);
STDMETHOD(RemoveEntry)(const HCACHEITEM hEntry);
STDMETHOD(RemoveEntryByKey)(LPCSTR szKey);
STDMETHOD(Flush)();
};
__interface ATL_NO_VTABLE __declspec(uuid("7634b28b-d819-409d-b96e-fc9f3aba329f"))
IMemoryCacheControl : public IUnknown
{
// IMemoryCacheControl Methods
STDMETHOD(SetMaxAllowedSize)(DWORD dwSize);
STDMETHOD(GetMaxAllowedSize)(DWORD *pdwSize);
STDMETHOD(SetMaxAllowedEntries)(DWORD dwSize);
STDMETHOD(GetMaxAllowedEntries)(DWORD *pdwSize);
STDMETHOD(ResetCache)();
};
__interface ATL_NO_VTABLE __declspec(uuid("d4b6df2d-4bc0-4734-8ace-b73a0b975956"))
IMemoryCacheStats : public IUnknown
{
// IMemoryCacheStats Methods
STDMETHOD(ClearStats)();
STDMETHOD(GetHitCount)(DWORD *pdwSize);
STDMETHOD(GetMissCount)(DWORD *pdwSize);
STDMETHOD(GetCurrentAllocSize)(DWORD *pdwSize);
STDMETHOD(GetMaxAllocSize)(DWORD *pdwSize);
STDMETHOD(GetCurrentEntryCount)(DWORD *pdwSize);
STDMETHOD(GetMaxEntryCount)(DWORD *pdwSize);
};
struct DLL_CACHE_ENTRY
{
HINSTANCE hInstDll;
DWORD dwRefs;
BOOL bAlive;
CHAR szDllName[MAX_PATH];
};
inline bool operator==(const DLL_CACHE_ENTRY& entry1, const DLL_CACHE_ENTRY& entry2)
{
return (entry1.hInstDll == entry2.hInstDll);
}
//
// IDllCache
// An interface that is used to load and unload Dlls.
//
__interface ATL_NO_VTABLE __declspec(uuid("A12478AB-D261-42f9-B525-7589143C1C97"))
IDllCache : public IUnknown
{
// IDllCache methods
virtual HINSTANCE Load(LPCSTR szFileName, void *pPeerInfo);
virtual BOOL Free(HINSTANCE hInstance);
virtual BOOL AddRefModule(HINSTANCE hInstance);
virtual BOOL ReleaseModule(HINSTANCE hInstance);
virtual HRESULT GetEntries(DWORD dwCount, DLL_CACHE_ENTRY *pEntries, DWORD *pdwCopied);
virtual HRESULT Flush();
};
#ifndef ATL_CACHE_KEY_LENGTH
#define ATL_CACHE_KEY_LENGTH 128
#endif
typedef CFixedStringT<CStringA, ATL_CACHE_KEY_LENGTH> CFixedStringKey;
struct CFlusherCacheData
{
CFlusherCacheData *pNext;
CFlusherCacheData *pPrev;
DWORD dwAccessed;
CFlusherCacheData()
{
pNext = NULL;
pPrev = NULL;
dwAccessed = 0;
}
};
// No flusher -- only expired entries will be removed from the cache
// Also gives the skeleton for all of the flushers
class CNoFlusher
{
public:
void Add(CFlusherCacheData * /*pItem*/) { }
void Remove(CFlusherCacheData * /*pItem*/) { }
void Access(CFlusherCacheData * /*pItem*/) { }
CFlusherCacheData * GetStart() const { return NULL; }
CFlusherCacheData * GetNext(CFlusherCacheData * /*pCur*/) const { return NULL; }
void Release(CFlusherCacheData * /*pItem*/){ }
};
// Old flusher -- oldest items are flushed first
class COldFlusher
{
public:
CFlusherCacheData * pHead;
CFlusherCacheData * pTail;
COldFlusher() : pHead(NULL), pTail(NULL)
{
}
// Add it to the tail of the list
void Add(CFlusherCacheData * pItem)
{
ATLENSURE(pItem);
pItem->pNext = NULL;
pItem->pPrev = pTail;
if (pHead)
{
pTail->pNext = pItem;
pTail = pItem;
}
else
{
pHead = pItem;
pTail = pItem;
}
}
void Remove(CFlusherCacheData * pItem)
{
ATLENSURE(pItem);
CFlusherCacheData * pPrev = pItem->pPrev;
CFlusherCacheData * pNext = pItem->pNext;
if (pPrev)
pPrev->pNext = pNext;
else
pHead = pNext;
if (pNext)
pNext->pPrev = pPrev;
else
pTail = pPrev;
}
void Access(CFlusherCacheData * /*pItem*/)
{
}
void Release(CFlusherCacheData * /*pItem*/)
{
}
CFlusherCacheData * GetStart() const
{
return pHead;
}
CFlusherCacheData * GetNext(CFlusherCacheData * pCur) const
{
if (pCur != NULL)
return pCur->pNext;
else
return NULL;
}
};
// Least recently used flusher -- the item that was accessed the longest time ago is flushed
class CLRUFlusher : public COldFlusher
{
public:
// Move it to the tail of the list
void Access(CFlusherCacheData * pItem)
{
ATLASSERT(pItem);
Remove(pItem);
Add(pItem);
}
};
// Least often used flusher
class CLOUFlusher : public COldFlusher
{
public:
// Adds to the tail of the list
void Add(CFlusherCacheData * pItem)
{
ATLENSURE(pItem);
pItem->dwAccessed = 1;
COldFlusher::Add(pItem);
}
void Access(CFlusherCacheData * pItem)
{
ATLENSURE(pItem);
pItem->dwAccessed++;
CFlusherCacheData * pMark = static_cast<CFlusherCacheData *>(pItem->pPrev);
if (!pMark) // The item is already at the head
return;
if (pMark->dwAccessed >= pItem->dwAccessed) // The element before it has
return; // been accessed more times
Remove(pItem);
while (pMark && (pMark->dwAccessed < pItem->dwAccessed))
pMark = static_cast<CFlusherCacheData *>(pMark->pPrev);
// pMark points to the first element that has been accessed more times,
// so add pItem after pMark
if (pMark)
{
CFlusherCacheData *pNext = static_cast<CFlusherCacheData *>(pMark->pNext);
pMark->pNext = pItem;
pItem->pPrev = pMark;
pItem->pNext = pNext;
pNext->pPrev = pItem;
}
else // Ran out of items -- put it on the head
{
pItem->pNext = pHead;
pItem->pPrev = NULL;
if (pHead)
pHead->pPrev = pItem;
else // the list was empty
pTail = pItem;
pHead = pItem;
}
}
// We start at the tail and move forward for this flusher
CFlusherCacheData * GetStart() const
{
return pTail;
}
CFlusherCacheData * GetNext(CFlusherCacheData * pCur) const
{
if (pCur != NULL)
return static_cast<CFlusherCacheData *>(pCur->pPrev);
else
return NULL;
}
};
template <class CFirst, class CSecond>
class COrFlushers
{
CFirst m_First;
CSecond m_Second;
BOOL m_bWhich;
public:
COrFlushers()
{
m_bWhich = FALSE;
}
BOOL Switch()
{
m_bWhich = !m_bWhich;
return m_bWhich;
}
void Add(CFlusherCacheData * pItem)
{
ATLASSERT(pItem);
m_First.Add(pItem);
m_Second.Add(pItem);
}
void Remove(CFlusherCacheData * pItem)
{
ATLASSERT(pItem);
m_First.Remove(pItem);
m_Second.Remove(pItem);
}
void Access(CFlusherCacheData * pItem)
{
ATLASSERT(pItem);
m_First.Access(pItem);
m_Second.Access(pItem);
}
void Release(CFlusherCacheData * pItem)
{
ATLASSERT(pItem);
m_First.Release(pItem);
m_Second.Release(pItem);
}
CFlusherCacheData * GetStart() const
{
if (m_bWhich)
return m_First.GetStart();
else
return m_Second.GetStart();
}
CFlusherCacheData * GetNext(CFlusherCacheData * pCur) const
{
if (m_bWhich)
return m_First.GetNext(pCur);
else
return m_Second.GetNext(pCur);
}
};
struct CCullerCacheData
{
CCullerCacheData()
{
pNext = NULL;
pPrev = NULL;
nLifespan = 0;
}
CCullerCacheData *pNext;
CCullerCacheData *pPrev;
ULONGLONG nLifespan;
CFileTime cftExpireTime;
};
class CNoExpireCuller
{
public:
void Add(CCullerCacheData * /*pItem*/) { }
void Commit(CCullerCacheData * /*pItem*/) { }
void Access(CCullerCacheData * /*pItem*/) { }
void Remove(CCullerCacheData * /*pItem*/) { }
void Start() { }
BOOL IsExpired(CCullerCacheData * /*pItem*/) { return FALSE; }
CCullerCacheData * GetExpired() { return NULL; }
void Release(CCullerCacheData * /*pItem*/){}
};
class CExpireCuller
{
public:
CFileTime m_cftCurrent;
CCullerCacheData *pHead;
CCullerCacheData *pTail;
CExpireCuller()
{
pHead = NULL;
pTail = NULL;
}
// Element is being added -- perform necessary initialization
void Add(CCullerCacheData * pItem)
{
(pItem);
ATLASSERT(pItem);
}
// Expiration data has been set -- add to main list
// Head is the first item to expire
// a FILETIME of 0 indicates that the item should never expire
void Commit(CCullerCacheData * pItem)
{
ATLENSURE(pItem);
if (!pHead)
{
pHead = pItem;
pTail = pItem;
pItem->pNext = NULL;
pItem->pPrev = NULL;
return;
}
if (CFileTime(pItem->cftExpireTime) == 0)
{
pTail->pNext = pItem;
pItem->pPrev = pTail;
pItem->pNext = NULL;
pTail = pItem;
return;
}
CCullerCacheData * pMark = pHead;
while (pMark && (pMark->cftExpireTime < pItem->cftExpireTime))
pMark = pMark->pNext;
if (pMark) // An entry was found that expires after the added entry
{
CCullerCacheData *pPrev = pMark->pPrev;
if (pPrev)
pPrev->pNext = pItem;
else
pHead = pItem;
pItem->pNext = pMark;
pItem->pPrev = pPrev;
pMark->pPrev = pItem;
}
else // Ran out of items -- put it on the tail
{
if (pTail)
pTail->pNext = pItem;
pItem->pPrev = pTail;
pItem->pNext = NULL;
pTail = pItem;
}
}
void Access(CCullerCacheData * /*pItem*/)
{
}
void Release(CCullerCacheData * /*pItem*/)
{
}
void Remove(CCullerCacheData * pItem)
{
ATLENSURE(pItem);
CCullerCacheData *pPrev = pItem->pPrev;
CCullerCacheData *pNext = pItem->pNext;
if (pPrev)
pPrev->pNext = pNext;
else
pHead = pNext;
if (pNext)
pNext->pPrev = pPrev;
else
pTail = pPrev;
}
// About to start culling
void Start()
{
m_cftCurrent = CFileTime::GetCurrentTime();
}
BOOL IsExpired(CCullerCacheData *pItem)
{
if ((pItem->cftExpireTime != 0) &&
m_cftCurrent > pItem->cftExpireTime)
return TRUE;
return FALSE;
}
// Get the next expired entry
CCullerCacheData * GetExpired()
{
if (!pHead)
return NULL;
if (IsExpired(pHead))
return pHead;
return NULL;
}
};
class CLifetimeCuller : public CExpireCuller
{
public:
void Add(CCullerCacheData * pItem)
{
ATLENSURE(pItem);
pItem->nLifespan = 0;
CExpireCuller::Add(pItem);
}
void Commit(CCullerCacheData * pItem)
{
ATLENSURE(pItem);
if (pItem->nLifespan == 0)
pItem->cftExpireTime = 0;
else
pItem->cftExpireTime = CFileTime(CFileTime::GetCurrentTime().GetTime() + pItem->nLifespan);
CExpireCuller::Commit(pItem);
}
void Access(CCullerCacheData * pItem)
{
ATLASSERT(pItem);
CExpireCuller::Remove(pItem);
Commit(pItem);
}
CCullerCacheData * GetExpired()
{
return static_cast<CCullerCacheData *>(CExpireCuller::GetExpired());
}
};
template <__int64 ftLifespan>
class CFixedLifetimeCuller : public CExpireCuller
{
public:
void Commit(CCullerCacheData * pItem)
{
ATLASSERT(pItem);
__int64 nLifeSpan = ftLifespan;
if (nLifeSpan == 0)
pItem->cftExpireTime = 0;
else
pItem->cftExpireTime = CFileTime::GetCurrentTime() + CFileTimeSpan(ftLifespan);
CExpireCuller::Commit(pItem);
}
void Access(CCullerCacheData * pItem)
{
ATLASSERT(pItem);
CExpireCuller::Remove(pItem);
Commit(pItem);
}
CCullerCacheData * GetExpired()
{
return static_cast<CCullerCacheData *>(CExpireCuller::GetExpired());
}
};
template <class CFirst, class CSecond>
class COrCullers
{
CFirst m_First;
CSecond m_Second;
public:
void Add(CCullerCacheData * pItem)
{
m_First.Add(pItem);
m_Second.Add(pItem);
}
void Access(CCullerCacheData * pItem)
{
m_First.Access(pItem);
m_Second.Access(pItem);
}
void Remove(CCullerCacheData * pItem)
{
m_First.Remove(pItem);
m_Second.Remove(pItem);
}
void Start()
{
m_First.Start();
m_Second.Start();
}
void Release(CCullerCacheData *pItem)
{
m_First.Release(pItem);
m_Second.Release(pItem);
}
void Commit(CCullerCacheData * pItem)
{
m_First.Commit(pItem);
m_Second.Commit(pItem);
}
CCullerCacheData * GetExpired()
{
CCullerCacheData *pItem = m_First.GetExpired();
if (!pItem)
pItem = m_Second.GetExpired();
return pItem;
}
BOOL IsExpired(CCullerCacheData * pItem)
{
return (m_First.IsExpired(pItem) || m_Second.IsExpired(pItem));
}
};
//
//CMemoryCacheBase
// Description:
// This class provides the implementation of a generic cache that stores
// elements in memory. CMemoryCacheBase uses the CCacheDataBase generic
// cache element structure to hold items in the cache. The cache is
// implemented using the CAtlMap map class. CMemoryCache uses a wide
// character string as it's Key type to identify entries. Entries must
// have unique key values. If you try to add an entry with a key that
// is exactly the same as an existing key, the existing entry will be
// overwritten.
//
// Template Parameters:
// T: The class that inherits from this class. This class must implement
// void OnDestroyEntry(NodeType *pEntry);
// DataType: Specifies the type of the element to be stored in the memory
// cache such as CString or void*
// NodeInfo: Specifies any additional data that should be stored in each item
// in the cache
// keyType, keyTrait : specifies the key type and traits (see CAtlMap)
// Flusher : the class responsible for determining which data should be flushed
// when the cache is at a configuration limit
// Culler : the class responsible for determining which data should be removed
// from the cache due to expiration
// SyncClass:Specifies the class that will be used for thread synchronization
// when accessing the cache. The class interface for SyncClass must
// be identical to that of CComCriticalSection (see atlbase.h)
// StatClass: Class used to contain statistics about this cache.
template <class T,
class DataType,
class NodeInfo=CCacheDataBase,
class keyType=CFixedStringKey,
class KeyTrait=CStringElementTraits<CFixedStringKey >,
class Flusher=COldFlusher,
class Culler=CExpireCuller,
class SyncClass=CComCriticalSection,
class StatClass=CStdStatClass >
class CMemoryCacheBase
{
protected:
typedef keyType keytype;
struct NodeType : public __CACHEITEM,
public NodeInfo,
public CFlusherCacheData,
public CCullerCacheData
{
NodeType()
{
pos = NULL;
dwSize = 0;
dwRef = 0;
}
DataType Data;
POSITION pos;
DWORD dwSize;
DWORD dwRef;
};
typedef CAtlMap<keyType, NodeType *, KeyTrait> mapType;
SyncClass m_syncObj;
StatClass m_statObj;
Flusher m_flusher;
Culler m_culler;
//memory cache configuration parameters
DWORD m_dwMaxAllocationSize;
DWORD m_dwMaxEntries;
BOOL m_bInitialized;
public:
mapType m_hashTable;
CMemoryCacheBase() :
m_dwMaxAllocationSize(0xFFFFFFFF),
m_dwMaxEntries(0xFFFFFFFF),
m_bInitialized(FALSE)
{
}
//Initializes the cache and the cache synchronization object
//Also the performance monitoring
HRESULT Initialize()
{
if (m_bInitialized)
return HRESULT_FROM_WIN32(ERROR_ALREADY_INITIALIZED);
HRESULT hr;
hr = m_syncObj.Init();
if (hr == S_OK)
hr = m_statObj.Initialize();
m_bInitialized = TRUE;
return hr;
}
//removes all entries whether or not they are initialized.
HRESULT Uninitialize()
{
if (!m_bInitialized)
return S_OK;
//clear out the hash table
HRESULT hr = m_syncObj.Lock();
if (FAILED(hr))
return hr;
RemoveAllEntries();
m_statObj.Uninitialize();
m_syncObj.Unlock();
m_syncObj.Term();
m_bInitialized = FALSE;
return S_OK;
}
//Adds an entry to the cache.
//Also, adds an initial reference on the entry if phEntry is not NULL
HRESULT AddEntry(
const keyType &Key, //key for entry
const DataType &data, //See the DataType template parameter
DWORD dwSize, //Size of memory to be stored in the cache
HCACHEITEM *phEntry = NULL //out pointer that will contain a handle to the new
//cache entry on success.
)
{
_ATLTRY
{
ATLASSUME(m_bInitialized);
CAutoPtr<NodeType> spEntry(new NodeType);
if (!spEntry)
return E_OUTOFMEMORY;
NodeType *pEntry = spEntry;
//fill entry
if (phEntry)
{
*phEntry = static_cast<HCACHEITEM>(pEntry);
pEntry->dwRef++;
}
pEntry->Data = data;
pEntry->dwSize = dwSize;
CComCritSecLock<SyncClass> lock(m_syncObj, false);
HRESULT hr = lock.Lock();
if (FAILED(hr))
{
return hr;
}
POSITION pos = (POSITION)m_hashTable.Lookup(Key);
if (pos != NULL)
{
RemoveAt(pos, FALSE);
m_hashTable.GetValueAt(pos) = pEntry;
}
else
{
pos = m_hashTable.SetAt(Key, pEntry);
}
spEntry.Detach();
pEntry->pos = pos;
m_statObj.AddElement(dwSize);
m_flusher.Add(pEntry);
m_culler.Add(pEntry);
lock.Unlock();
if (!phEntry)
return CommitEntry(static_cast<HCACHEITEM>(pEntry));
return S_OK;
}
_ATLCATCHALL()
{
return E_FAIL;
}
}
// Commits the entry to the cache
HRESULT CommitEntry(const HCACHEITEM hEntry)
{
ATLASSUME(m_bInitialized);
if (!hEntry || hEntry == INVALID_HANDLE_VALUE)
return E_INVALIDARG;
HRESULT hr = m_syncObj.Lock();
if (FAILED(hr))
{
return hr;
}
NodeType *pEntry = static_cast<NodeType *>(hEntry);
m_culler.Commit(pEntry);
m_syncObj.Unlock();
return S_OK;
}
// Looks up an entry and returns a handle to it,
// also updates access count and reference count
HRESULT LookupEntry(const keyType &Key, HCACHEITEM * phEntry)
{
ATLASSUME(m_bInitialized);
HRESULT hr = m_syncObj.Lock();
if (FAILED(hr))
{
return hr;
}
hr = E_FAIL;
POSITION pos = (POSITION)m_hashTable.Lookup(Key);
if (pos != NULL)
{
NodeType * pEntry = m_hashTable.GetValueAt(pos);
m_flusher.Access(pEntry);
m_culler.Access(pEntry);
if (phEntry)
{
pEntry->dwRef++;
*phEntry = static_cast<HCACHEITEM>(pEntry);
}
m_statObj.Hit();
hr = S_OK;
}
else
{
*phEntry = NULL;
m_statObj.Miss();
}
m_syncObj.Unlock();
return hr;
}
// Gets the data based on the handle. Is thread-safe as long as there is a
// reference on the data
HRESULT GetEntryData(const HCACHEITEM hEntry, DataType *pData, DWORD *pdwSize) const
{
ATLASSUME(m_bInitialized);
ATLASSERT(pData != NULL || pdwSize != NULL); // At least one should not be NULL
if (!hEntry || hEntry == INVALID_HANDLE_VALUE)
return E_INVALIDARG;
NodeType * pEntry = static_cast<NodeType *>(hEntry);
if (pData)
*pData = pEntry->Data;
if (pdwSize)
*pdwSize = pEntry->dwSize;
return S_OK;
}
// Unreferences the entry based on the handle
DWORD ReleaseEntry(const HCACHEITEM hEntry)
{
ATLASSUME(m_bInitialized);
if (!hEntry || hEntry == INVALID_HANDLE_VALUE)
return (DWORD)-1;
HRESULT hr = m_syncObj.Lock();
if (FAILED(hr))
return (DWORD)-1;
NodeType * pEntry = static_cast<NodeType *>(hEntry);
m_flusher.Release(pEntry);
m_culler.Release(pEntry);
ATLASSERT(pEntry->dwRef > 0);
DWORD dwRef = --pEntry->dwRef;
if ((pEntry->pos == NULL) && (pEntry->dwRef == 0))
InternalRemoveEntry(pEntry);
m_syncObj.Unlock();
return dwRef;
}
// Increments the entry's reference count
DWORD AddRefEntry(const HCACHEITEM hEntry)
{
ATLASSUME(m_bInitialized);
if (!hEntry || hEntry == INVALID_HANDLE_VALUE)
return (DWORD)-1;
HRESULT hr = m_syncObj.Lock();
if (FAILED(hr))
return (DWORD)-1;
NodeType * pEntry = static_cast<NodeType *>(hEntry);
m_flusher.Access(pEntry);
m_culler.Access(pEntry);
DWORD dwRef = ++pEntry->dwRef;
m_syncObj.Unlock();
return dwRef;
}
// Removes an entry from the cache regardless of whether or
// not it has expired. If there are references, it detaches
// the entry so that future lookups will fail, and when
// the ref count drops to zero, it will be deleted
HRESULT RemoveEntryByKey(const keyType &Key)
{
ATLASSUME(m_bInitialized);
HCACHEITEM hEntry;
HRESULT hr = LookupEntry(Key, &hEntry);
if (hr == S_OK)
hr = RemoveEntry(hEntry);
return hr;
}
// Removes the element from the cache. If there are still
// references, then the entry is detached.
HRESULT RemoveEntry(const HCACHEITEM hEntry)
{
ATLASSUME(m_bInitialized);
if (!hEntry || hEntry == INVALID_HANDLE_VALUE)
return E_INVALIDARG;
_ATLTRY
{
CComCritSecLock<SyncClass> lock(m_syncObj, false);
HRESULT hr = lock.Lock();
if (FAILED(hr))
return hr;
NodeType * pEntry = static_cast<NodeType *>(hEntry);
m_flusher.Release(pEntry);
m_culler.Release(pEntry);
ATLASSERT(pEntry->dwRef > 0);
pEntry->dwRef--;
if (pEntry->pos)
RemoveAt(pEntry->pos, TRUE);
else if ((long)pEntry->dwRef == 0)
InternalRemoveEntry(pEntry);
lock.Unlock();
}
_ATLCATCHALL()
{
return E_OUTOFMEMORY;
}
return S_OK;
}
// CullEntries removes all expired items
HRESULT CullEntries()
{
ATLASSUME(m_bInitialized);
_ATLTRY
{
CComCritSecLock<SyncClass> lock(m_syncObj, false);
HRESULT hr = lock.Lock();
if (FAILED(hr))
return hr;
m_culler.Start();
while (NodeType *pNode = static_cast<NodeType *>(m_culler.GetExpired()))
RemoveAt(pNode->pos, TRUE);
lock.Unlock();
}
_ATLCATCHALL()
{
return E_OUTOFMEMORY;
}
return S_OK;
}
// FlushEntries reduces the cache to meet the configuration requirements
HRESULT FlushEntries()
{
ATLASSUME(m_bInitialized);
HRESULT hr = CullEntries();
if (FAILED(hr))
return hr;
_ATLTRY
{
CComCritSecLock<SyncClass> lock(m_syncObj, false);
hr = lock.Lock();
if (FAILED(hr))
return hr;
NodeType * pNode = static_cast<NodeType *>(m_flusher.GetStart());
while (pNode &&
(((m_statObj.GetCurrentEntryCount() > m_dwMaxEntries)) ||
((m_statObj.GetCurrentAllocSize() > m_dwMaxAllocationSize))))
{
NodeType *pNext = static_cast<NodeType *>(m_flusher.GetNext(pNode));
if (pNode->dwRef == 0)
RemoveAt(pNode->pos, TRUE);
pNode = pNext;
}
lock.Unlock();
}
_ATLCATCHALL()
{
return E_OUTOFMEMORY;
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE SetMaxAllowedSize(DWORD dwSize)
{
m_dwMaxAllocationSize = dwSize;
return S_OK;
}
HRESULT STDMETHODCALLTYPE GetMaxAllowedSize(DWORD *pdwSize)
{
if (!pdwSize)
return E_POINTER;
*pdwSize = m_dwMaxAllocationSize;
return S_OK;
}
HRESULT STDMETHODCALLTYPE SetMaxAllowedEntries(DWORD dwSize)
{
m_dwMaxEntries = dwSize;
return S_OK;
}
HRESULT STDMETHODCALLTYPE GetMaxAllowedEntries(DWORD *pdwSize)
{
if (!pdwSize)
return E_POINTER;
*pdwSize = m_dwMaxEntries;
return S_OK;
}
HRESULT ResetCache()
{
ATLASSUME(m_bInitialized);
HRESULT hr = E_UNEXPECTED;
if (SUCCEEDED(ClearStats()))
hr = RemoveAllEntries();
return hr;
}
HRESULT ClearStats()
{
m_statObj.ResetCounters();
return S_OK;
}
HRESULT RemoveAllEntries()
{
ATLASSUME(m_bInitialized);
HRESULT hr = m_syncObj.Lock();
if (FAILED(hr))
return hr;
m_hashTable.DisableAutoRehash();
POSITION pos = m_hashTable.GetStartPosition();
POSITION oldpos;
while (pos != NULL)
{
oldpos = pos;
m_hashTable.GetNext(pos);
RemoveAt(oldpos, TRUE);
}
m_hashTable.EnableAutoRehash();
m_syncObj.Unlock();
return S_OK;
}
protected:
// Checks to see if the cache can accommodate any new entries within
// its allocation and entry count limits.
bool CanAddEntry(DWORD dwSizeToAdd)
{
return CheckAlloc(dwSizeToAdd) && CheckEntryCount(1);
}
// Checks to see if the cache can accommodate dwSizeToAdd additional
// allocation within its allocation limit.
bool CheckAlloc(DWORD dwSizeToAdd)
{
if (m_dwMaxAllocationSize == 0xFFFFFFFF)
return true; //max allocation size setting hasn't been set
DWORD dwNew = m_statObj.GetCurrentAllocSize() + dwSizeToAdd;
return dwNew < m_dwMaxAllocationSize;
}
// Checks to see if the cache can accommodate dwNumEntriesToAdd
// additional entries within its limits.
bool CheckEntryCount(DWORD dwNumEntriesToAdd)
{
if (m_dwMaxEntries == 0xFFFFFFFF)
return true; //max entry size hasn't been set
DWORD dwNew = m_statObj.GetCurrentEntryCount() + dwNumEntriesToAdd;
return dwNew < m_dwMaxEntries;
}
protected:
// Takes the element at pos in the hash table and removes it from
// the cache. If there are no references, then the entry is
// deleted, otherwise it is deleted by ReleaseEntry when the
// refcount goes to zero.
HRESULT RemoveAt(POSITION pos, BOOL bDelete)
{
HRESULT hr = S_OK;
ATLASSERT(pos != NULL);
NodeType * pEntry = m_hashTable.GetValueAt(pos);
m_flusher.Remove(pEntry);
m_culler.Remove(pEntry);
if (bDelete)
m_hashTable.RemoveAtPos(pos);
if ((long)pEntry->dwRef == 0)
hr = InternalRemoveEntry(pEntry);
else
pEntry->pos = NULL;
return S_OK;
}
// Does the actual destruction of the node. Deletes the
// NodeType struct and calls the inherited class's
// OnDestroyEntry function, where other necessary destruction
// can take place. Also updates the cache statistics.
// Inherited classes should call RemoveAt unless the element's
// refcount is zero and it has been removed from the
// culler and flusher lists.
HRESULT InternalRemoveEntry(NodeType * pEntry)
{
ATLENSURE(pEntry != NULL);
T* pT = static_cast<T*>(this);
ATLASSERT((long)pEntry->dwRef == 0);
pT->OnDestroyEntry(pEntry);
m_statObj.ReleaseElement(pEntry->dwSize);
delete pEntry;
return S_OK;
}
}; // CMemoryCacheBase
class CCacheDataBase
{
};
struct CCacheDataEx : public CCacheDataBase
{
CCacheDataEx()
{
hInstance = NULL;
pClient = NULL;
}
HINSTANCE hInstance;
IMemoryCacheClient * pClient;
};
template <typename DataType,
class StatClass=CStdStatClass,
class FlushClass=COldFlusher,
class keyType=CFixedStringKey, class KeyTrait=CStringElementTraits<CFixedStringKey >,
class SyncClass=CComCriticalSection,
class CullClass=CExpireCuller >
class CMemoryCache:
public CMemoryCacheBase<CMemoryCache<DataType, StatClass, FlushClass, keyType, KeyTrait, SyncClass, CullClass>, DataType, CCacheDataEx,
keyType, KeyTrait, FlushClass, CullClass, SyncClass, StatClass>
{
protected:
CComPtr<IServiceProvider> m_spServiceProv;
CComPtr<IDllCache> m_spDllCache;
typedef CMemoryCacheBase<CMemoryCache<DataType, StatClass, FlushClass, keyType, KeyTrait, SyncClass, CullClass>, DataType, CCacheDataEx,
keyType, KeyTrait, FlushClass, CullClass, SyncClass, StatClass> baseClass;
public:
virtual ~CMemoryCache()
{
}
HRESULT Initialize(IServiceProvider * pProvider)
{
baseClass::Initialize();
m_spServiceProv = pProvider;
if (pProvider)
return m_spServiceProv->QueryService(__uuidof(IDllCache), __uuidof(IDllCache), (void**)&m_spDllCache);
else
return S_OK;
}
HRESULT AddEntry(
const keyType &Key,
const DataType &data,
DWORD dwSize,
FILETIME * pftExpireTime = NULL,
HINSTANCE hInstance = NULL,
IMemoryCacheClient * pClient = NULL,
HCACHEITEM *phEntry = NULL
)
{
_ATLTRY
{
HRESULT hr;
NodeType * pEntry = NULL;
hr = baseClass::AddEntry(Key, data, dwSize, (HCACHEITEM *)&pEntry);
if (hr != S_OK)
return hr;
pEntry->hInstance = hInstance;
pEntry->pClient = pClient;
if (pftExpireTime)
pEntry->cftExpireTime = *pftExpireTime;
if (hInstance && m_spDllCache)
m_spDllCache->AddRefModule(hInstance);
baseClass::CommitEntry(static_cast<HCACHEITEM>(pEntry));
if (phEntry)
*phEntry = static_cast<HCACHEITEM>(pEntry);
else
baseClass::ReleaseEntry(static_cast<HCACHEITEM>(pEntry));
return S_OK;
}
_ATLCATCHALL()
{
return E_FAIL;
}
}
virtual void OnDestroyEntry(const NodeType * pEntry)
{
ATLASSERT(pEntry);
if (!pEntry)
return;
if (pEntry->pClient)
pEntry->pClient->Free((void *)&pEntry->Data);
if (pEntry->hInstance && m_spDllCache)
m_spDllCache->ReleaseModule(pEntry->hInstance);
}
}; // CMemoryCache
// CStdStatData - contains the data that CStdStatClass keeps track of
#define ATL_PERF_CACHE_OBJECT 100
struct CPerfStatObject : public CPerfObject
{
DECLARE_PERF_CATEGORY(CPerfStatObject, ATL_PERF_CACHE_OBJECT, IDS_PERFMON_CACHE, IDS_PERFMON_CACHE_HELP, -1);
BEGIN_COUNTER_MAP(CPerfStatObject)
DEFINE_COUNTER(m_nHitCount, IDS_PERFMON_HITCOUNT, IDS_PERFMON_HITCOUNT_HELP, PERF_COUNTER_RAWCOUNT, -1)
DEFINE_COUNTER(m_nMissCount, IDS_PERFMON_MISSCOUNT, IDS_PERFMON_MISSCOUNT_HELP, PERF_COUNTER_RAWCOUNT, -1)
DEFINE_COUNTER(m_nCurrentAllocations, IDS_PERFMON_CURRENTALLOCATIONS, IDS_PERFMON_CURRENTALLOCATIONS_HELP, PERF_COUNTER_RAWCOUNT, -3)
DEFINE_COUNTER(m_nMaxAllocations, IDS_PERFMON_MAXALLOCATIONS, IDS_PERFMON_MAXALLOCATIONS_HELP, PERF_COUNTER_RAWCOUNT, -3)
DEFINE_COUNTER(m_nCurrentEntries, IDS_PERFMON_CURRENTENTRIES, IDS_PERFMON_CURRENTENTRIES_HELP, PERF_COUNTER_RAWCOUNT, -1)
DEFINE_COUNTER(m_nMaxEntries, IDS_PERFMON_MAXENTRIES, IDS_PERFMON_MAXENTRIES_HELP, PERF_COUNTER_RAWCOUNT, -1)
END_COUNTER_MAP()
long m_nHitCount;
long m_nMissCount;
long m_nCurrentAllocations;
long m_nMaxAllocations;
long m_nCurrentEntries;
long m_nMaxEntries;
};
// CCachePerfMon - the interface to CPerfMon, with associated definitions
class CCachePerfMon : public CPerfMon
{
public:
BEGIN_PERF_MAP(_T("ATL Server:Cache"))
CHAIN_PERF_CATEGORY(CPerfStatObject)
END_PERF_MAP()
};
//
//CStdStatClass
// Description
// This class provides the implementation of a standard cache statistics accounting class
class CStdStatClass
{
protected:
CPerfStatObject* m_pStats;
CPerfStatObject m_stats;
public:
CStdStatClass()
{
m_pStats = &m_stats;
}
// This function is not thread safe by design
HRESULT Initialize(CPerfStatObject* pStats = NULL)
{
if (pStats)
m_pStats = pStats;
else
m_pStats = &m_stats;
ResetCounters();
return S_OK;
}
// This function is not thread safe by design
HRESULT Uninitialize()
{
m_pStats = &m_stats;
return S_OK;
}
void Hit()
{
InterlockedIncrement(&m_pStats->m_nHitCount);
}
void Miss()
{
InterlockedIncrement(&m_pStats->m_nMissCount);
}
void AddElement(DWORD dwBytes)
{
DWORD nCurrentEntries = InterlockedIncrement(&m_pStats->m_nCurrentEntries);
AtlInterlockedUpdateMax(nCurrentEntries, &m_pStats->m_nMaxEntries);
DWORD nCurrentAllocations = dwBytes + AtlInterlockedExchangeAdd(&m_pStats->m_nCurrentAllocations, dwBytes);
AtlInterlockedUpdateMax(nCurrentAllocations, &m_pStats->m_nMaxAllocations);
}
void ReleaseElement(DWORD dwBytes)
{
InterlockedDecrement(&m_pStats->m_nCurrentEntries);
AtlInterlockedExchangeAdd(&m_pStats->m_nCurrentAllocations, -((long)dwBytes));
}
DWORD GetHitCount()
{
return m_pStats->m_nHitCount;
}
DWORD GetMissCount()
{
return m_pStats->m_nMissCount;
}
DWORD GetCurrentAllocSize()
{
return m_pStats->m_nCurrentAllocations;
}
DWORD GetMaxAllocSize()
{
return m_pStats->m_nMaxAllocations;
}
DWORD GetCurrentEntryCount()
{
return m_pStats->m_nCurrentEntries;
}
DWORD GetMaxEntryCount()
{
return m_pStats->m_nMaxEntries;
}
void ResetCounters()
{
m_pStats->m_nHitCount = 0;
m_pStats->m_nMissCount = 0;
m_pStats->m_nCurrentAllocations = 0;
m_pStats->m_nMaxAllocations = 0;
m_pStats->m_nCurrentEntries = 0;
m_pStats->m_nMaxEntries = 0;
}
}; // CStdStatClass
//
// CNoStatClass
// This is a noop stat class
class CNoStatClass
{
public:
HRESULT Initialize(){ return S_OK; }
HRESULT Uninitialize(){ return S_OK; }
void Hit(){ }
void Miss(){ }
void AddElement(DWORD){ }
void ReleaseElement(DWORD){ }
DWORD GetHitCount(){ return 0; }
DWORD GetMissCount(){ return 0; }
DWORD GetCurrentAllocSize(){ return 0; }
DWORD GetMaxAllocSize(){ return 0; }
DWORD GetCurrentEntryCount(){ return 0; }
DWORD GetMaxEntryCount(){ return 0; }
void ResetCounters(){ }
}; // CNoStatClass
//
//CPerfStatClass
// Description
// This class provides the implementation of a cache statistics gathering class
// with PerfMon support
class CPerfStatClass : public CStdStatClass
{
CPerfStatObject * m_pPerfObject;
CCachePerfMon m_PerfMon;
public:
HRESULT Initialize(__in_z_opt LPWSTR szName=NULL)
{
HRESULT hr;
WCHAR szPath[MAX_PATH];
if (!szName)
{
// default name is the name of the module
// we don't care about possible truncation if longer than max_path
// we just need an identifier
HINSTANCE hInst = _AtlBaseModule.GetModuleInstance();
if (::GetModuleFileNameW(hInst, szPath, MAX_PATH) == 0)
{
return E_FAIL;
}
szPath[MAX_PATH-1] = 0;
szName = szPath;
}
m_pPerfObject = NULL;
ATLTRACE(atlTraceCache, 2, _T("Initializing m_PerfMon\n"));
hr = m_PerfMon.Initialize();
if (SUCCEEDED(hr))
{
CPerfLock lock(&m_PerfMon);
if (FAILED(hr = lock.GetStatus()))
{
return hr;
}
hr = m_PerfMon.CreateInstance(ATL_PERF_CACHE_OBJECT, 0, szName, reinterpret_cast<CPerfObject**>(&m_pPerfObject));
if (FAILED(hr))
{
return hr;
}
CStdStatClass::Initialize(m_pPerfObject);
}
else
ATLASSUME(m_pPerfObject == NULL);
return hr;
}
HRESULT Uninitialize()
{
CStdStatClass::Uninitialize();
if (m_pPerfObject != NULL) // Initialized m_pPerfObject successfully above
{
HRESULT hr = m_PerfMon.ReleaseInstance(m_pPerfObject);
if (hr != S_OK)
return hr;
m_PerfMon.UnInitialize();
}
return S_OK;
}
}; // CPerfStatClass
#ifndef ATL_BLOB_CACHE_TIMEOUT
#ifdef _DEBUG
#define ATL_BLOB_CACHE_TIMEOUT 1000
#else
#define ATL_BLOB_CACHE_TIMEOUT 5000
#endif // _DEBUG
#endif // ATL_BLOB_CACHE_TIMEOUT
//
//CBlobCache
// Description:
// Implements a cache that stores pointers to void. Uses the generic CMemoryCacheBase class
// as the implementation.
template <class MonitorClass,
class StatClass=CStdStatClass,
class SyncObj=CComCriticalSection,
class FlushClass=COldFlusher,
class CullClass=CExpireCuller >
class CBlobCache : public CMemoryCache<void*, StatClass, FlushClass, CFixedStringKey,
CStringElementTraits<CFixedStringKey >, SyncObj, CullClass>,
public IMemoryCache,
public IMemoryCacheControl,
public IMemoryCacheStats,
public IWorkerThreadClient
{
typedef CMemoryCache<void*, StatClass, FlushClass, CFixedStringKey,
CStringElementTraits<CFixedStringKey>, SyncObj, CullClass> cacheBase;
MonitorClass m_Monitor;
protected:
HANDLE m_hTimer;
public:
CBlobCache() : m_hTimer(NULL)
{
}
HRESULT Initialize(IServiceProvider *pProv)
{
HRESULT hr = cacheBase::Initialize(pProv);
if (FAILED(hr))
return hr;
hr = m_Monitor.Initialize();
if (FAILED(hr))
return hr;
return m_Monitor.AddTimer(ATL_BLOB_CACHE_TIMEOUT,
static_cast<IWorkerThreadClient*>(this), (DWORD_PTR) this, &m_hTimer);
}
template <class ThreadTraits>
HRESULT Initialize(IServiceProvider *pProv, CWorkerThread<ThreadTraits> *pWorkerThread)
{
ATLASSERT(pWorkerThread);
HRESULT hr = cacheBase::Initialize(pProv);
if (FAILED(hr))
return hr;
hr = m_Monitor.Initialize(pWorkerThread);
if (FAILED(hr))
return hr;
return m_Monitor.AddTimer(ATL_BLOB_CACHE_TIMEOUT,
static_cast<IWorkerThreadClient*>(this), (DWORD_PTR) this, &m_hTimer);
}
HRESULT Execute(DWORD_PTR dwParam, HANDLE /*hObject*/)
{
CBlobCache* pCache = (CBlobCache*)dwParam;
if (pCache)
pCache->Flush();
return S_OK;
}
HRESULT CloseHandle(HANDLE hObject)
{
ATLASSUME(m_hTimer == hObject);
m_hTimer = NULL;
::CloseHandle(hObject);
return S_OK;
}
virtual ~CBlobCache()
{
if (m_hTimer)
{
ATLENSURE(SUCCEEDED(m_Monitor.RemoveHandle(m_hTimer)));
}
}
HRESULT Uninitialize()
{
HRESULT hrMonitor=S_OK;
if (m_hTimer)
{
hrMonitor=m_Monitor.RemoveHandle(m_hTimer);
m_hTimer = NULL;
}
HRESULT hrShut=m_Monitor.Shutdown();
HRESULT hrCache=cacheBase::Uninitialize();
if(FAILED(hrMonitor))
{
return hrMonitor;
}
if(FAILED(hrShut))
{
return hrShut;
}
return hrCache;
}
// IUnknown methods
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppv)
{
HRESULT hr = E_NOINTERFACE;
if (!ppv)
hr = E_POINTER;
else
{
if (InlineIsEqualGUID(riid, __uuidof(IUnknown)) ||
InlineIsEqualGUID(riid, __uuidof(IMemoryCache)))
{
*ppv = (IUnknown *) (IMemoryCache *) this;
AddRef();
hr = S_OK;
}
if (InlineIsEqualGUID(riid, __uuidof(IMemoryCacheStats)))
{
*ppv = (IUnknown *) (IMemoryCacheStats*)this;
AddRef();
hr = S_OK;
}
if (InlineIsEqualGUID(riid, __uuidof(IMemoryCacheControl)))
{
*ppv = (IUnknown *) (IMemoryCacheControl*)this;
AddRef();
hr = S_OK;
}
}
return hr;
}
ULONG STDMETHODCALLTYPE AddRef()
{
return 1;
}
ULONG STDMETHODCALLTYPE Release()
{
return 1;
}
// IMemoryCache Methods
HRESULT STDMETHODCALLTYPE Add(LPCSTR szKey, void *pvData, DWORD dwSize,
FILETIME *pftExpireTime,
HINSTANCE hInstClient,
HCACHEITEM *phEntry,
IMemoryCacheClient *pClient)
{
HRESULT hr = E_FAIL;
//if it's a multithreaded cache monitor we'll let the monitor take care of
//cleaning up the cache so we don't overflow our configuration settings.
//if it's not a threaded cache monitor, we need to make sure we don't
//overflow the configuration settings by adding a new element
if (m_Monitor.GetThreadHandle()==NULL)
{
if (!cacheBase::CanAddEntry(dwSize))
{
//flush the entries and check again to see if we can add
cacheBase::FlushEntries();
if (!cacheBase::CanAddEntry(dwSize))
return E_OUTOFMEMORY;
}
}
_ATLTRY
{
hr = cacheBase::AddEntry(szKey, pvData, dwSize,
pftExpireTime, hInstClient, pClient, phEntry);
return hr;
}
_ATLCATCHALL()
{
return E_FAIL;
}
}
HRESULT STDMETHODCALLTYPE LookupEntry(LPCSTR szKey, HCACHEITEM * phEntry)
{
return cacheBase::LookupEntry(szKey, phEntry);
}
HRESULT STDMETHODCALLTYPE GetData(const HCACHEITEM hKey, void **ppvData, DWORD *pdwSize) const
{
return cacheBase::GetEntryData(hKey, ppvData, pdwSize);
}
HRESULT STDMETHODCALLTYPE ReleaseEntry(const HCACHEITEM hKey)
{
return cacheBase::ReleaseEntry(hKey);
}
HRESULT STDMETHODCALLTYPE RemoveEntry(const HCACHEITEM hKey)
{
return cacheBase::RemoveEntry(hKey);
}
HRESULT STDMETHODCALLTYPE RemoveEntryByKey(LPCSTR szKey)
{
return cacheBase::RemoveEntryByKey(szKey);
}
HRESULT STDMETHODCALLTYPE Flush()
{
return cacheBase::FlushEntries();
}
HRESULT STDMETHODCALLTYPE SetMaxAllowedSize(DWORD dwSize)
{
return cacheBase::SetMaxAllowedSize(dwSize);
}
HRESULT STDMETHODCALLTYPE GetMaxAllowedSize(DWORD *pdwSize)
{
return cacheBase::GetMaxAllowedSize(pdwSize);
}
HRESULT STDMETHODCALLTYPE SetMaxAllowedEntries(DWORD dwSize)
{
return cacheBase::SetMaxAllowedEntries(dwSize);
}
HRESULT STDMETHODCALLTYPE GetMaxAllowedEntries(DWORD *pdwSize)
{
return cacheBase::GetMaxAllowedEntries(pdwSize);
}
HRESULT STDMETHODCALLTYPE ResetCache()
{
return cacheBase::ResetCache();
}
// IMemoryCacheStats methods
HRESULT STDMETHODCALLTYPE ClearStats()
{
m_statObj.ResetCounters();
return S_OK;
}
HRESULT STDMETHODCALLTYPE GetHitCount(DWORD *pdwSize)
{
if (!pdwSize)
return E_POINTER;
*pdwSize = m_statObj.GetHitCount();
return S_OK;
}
HRESULT STDMETHODCALLTYPE GetMissCount(DWORD *pdwSize)
{
if (!pdwSize)
return E_POINTER;
*pdwSize = m_statObj.GetMissCount();
return S_OK;
}
HRESULT STDMETHODCALLTYPE GetMaxAllocSize(DWORD *pdwSize)
{
if (!pdwSize)
return E_POINTER;
*pdwSize = m_statObj.GetMaxAllocSize();
return S_OK;
}
HRESULT STDMETHODCALLTYPE GetCurrentAllocSize(DWORD *pdwSize)
{
if (!pdwSize)
return E_POINTER;
*pdwSize = m_statObj.GetCurrentAllocSize();
return S_OK;
}
HRESULT STDMETHODCALLTYPE GetMaxEntryCount(DWORD *pdwSize)
{
if (!pdwSize)
return E_POINTER;
*pdwSize = m_statObj.GetMaxEntryCount();
return S_OK;
}
HRESULT STDMETHODCALLTYPE GetCurrentEntryCount(DWORD *pdwSize)
{
if (!pdwSize)
return E_POINTER;
*pdwSize = m_statObj.GetCurrentEntryCount();
return S_OK;
}
}; // CBlobCache
//
// CDllCache
// This class manages a cache to handle calls to LoadLibrary
// and FreeLibrary.
// It keeps dlls loaded even after the last call to free library
// a worker thread then calls FreeLibrary on unused dlls
//
#ifndef ATL_DLL_CACHE_TIMEOUT
#ifdef _DEBUG
#define ATL_DLL_CACHE_TIMEOUT 1000 // 1 sec default for debug builds
#else
#define ATL_DLL_CACHE_TIMEOUT 10*60000 // 10 minute default for retail builds
#endif
#endif
class CNoDllCachePeer
{
public:
struct DllInfo
{
};
BOOL Add(HINSTANCE /*hInst*/, DllInfo * /*pInfo*/)
{
return TRUE;
}
void Remove(HINSTANCE /*hInst*/, DllInfo * /*pInfo*/)
{
}
};
// CDllCache
// Implements IDllCache, an interface that is used to load and unload Dlls.
// To use it, construct an instance of a CDllCache and call Initialize.
// The Initialize call has to match with the type of monitor class you
// templatize on. The monitor thread will call IWorkerThreadClient::Execute
// after its timeout expires. Make sure to Uninitialize the object before
// it is destroyed by calling Uninitialize
//
template <class MonitorClass, class Peer=CNoDllCachePeer>
class CDllCache : public IDllCache,
public IWorkerThreadClient
{
protected:
CComCriticalSection m_critSec;
CSimpleArray<DLL_CACHE_ENTRY> m_Dlls;
CSimpleArray<typename Peer::DllInfo> m_DllInfos;
MonitorClass m_Monitor;
HANDLE m_hTimer;
void RemoveDllEntry(DLL_CACHE_ENTRY& entry)
{
::FreeLibrary(entry.hInstDll);
entry.hInstDll = NULL;
m_Dlls.RemoveAt(m_Dlls.GetSize()-1);
}
public:
Peer m_Peer;
CDllCache() :
m_hTimer(NULL)
{
}
HRESULT Initialize(DWORD dwTimeout=ATL_DLL_CACHE_TIMEOUT)
{
HRESULT hr = m_critSec.Init();
if (FAILED(hr))
return hr;
hr = m_Monitor.Initialize();
if (FAILED(hr))
return hr;
return m_Monitor.AddTimer(dwTimeout, this, 0, &m_hTimer);
}
template <class ThreadTraits>
HRESULT Initialize(CWorkerThread<ThreadTraits> *pWorkerThread,
DWORD dwTimeout=ATL_DLL_CACHE_TIMEOUT)
{
HRESULT hr = m_critSec.Init();
if (FAILED(hr))
return hr;
hr = m_Monitor.Initialize(pWorkerThread);
if (FAILED(hr))
return hr;
return m_Monitor.AddTimer(dwTimeout, this, 0, &m_hTimer);
}
HRESULT Uninitialize()
{
HRESULT hr = S_OK;
HRESULT hrLatest = S_OK;
if (m_hTimer)
{
hrLatest=m_Monitor.RemoveHandle(m_hTimer);
if(FAILED(hrLatest) && SUCCEEDED(hr))
{
hr=hrLatest;
}
m_hTimer = NULL;
}
m_Monitor.Shutdown();
// free all the libraries we've cached
int nLen = m_Dlls.GetSize();
for (int i=0; i<nLen; i++)
{
DLL_CACHE_ENTRY& entry = m_Dlls[i];
ATLASSERT(entry.dwRefs == 0);
BOOL bRet = ::FreeLibrary(entry.hInstDll);
if (!bRet)
{
hrLatest = AtlHresultFromLastError();
if(FAILED(hrLatest) && SUCCEEDED(hr))
{
hr=hrLatest;
}
ATLTRACE(atlTraceCache, 0, _T("Free library failed on shutdown of dll cache : hr = 0x%08x)"), hr);
}
}
m_Dlls.RemoveAll();
m_critSec.Term();
return hr;
}
// IUnknown methods
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppv)
{
if (!ppv)
return E_POINTER;
if (InlineIsEqualGUID(riid, __uuidof(IUnknown)) ||
InlineIsEqualGUID(riid, __uuidof(IDllCache)))
{
*ppv = (IUnknown *) this;
AddRef();
return S_OK;
}
return E_NOINTERFACE;
}
ULONG STDMETHODCALLTYPE AddRef()
{
return 1;
}
ULONG STDMETHODCALLTYPE Release()
{
return 1;
}
// IDllCache methods
HINSTANCE Load(LPCSTR szDllName, void *pPeerInfo) throw(...)
{
HRESULT hr = m_critSec.Lock();
if (FAILED(hr))
return NULL;
int nLen = m_Dlls.GetSize();
for (int i=0; i<nLen; i++)
{
DLL_CACHE_ENTRY& entry = m_Dlls[i];
if (!_stricmp(entry.szDllName, szDllName))
{
entry.dwRefs++;
m_critSec.Unlock();
if (pPeerInfo)
{
Peer::DllInfo *pl = (Peer::DllInfo*)pPeerInfo;
*pl = m_DllInfos[i];
}
return entry.hInstDll;
}
}
DLL_CACHE_ENTRY entry;
entry.hInstDll = ::LoadLibraryA(szDllName);
if (!entry.hInstDll)
{
m_critSec.Unlock();
return NULL;
}
if (!SafeStringCopy(entry.szDllName, szDllName))
{
::FreeLibrary(entry.hInstDll);
m_critSec.Unlock();
return NULL;
}
entry.dwRefs = 1;
entry.bAlive = TRUE;
m_Dlls.Add(entry);
Peer::DllInfo *pdllInfo = (Peer::DllInfo*)pPeerInfo;
// m_Peer could throw an exception from user code. We
// pass that exception from here to a higher context (we
// won't deal with user exception here).
if (!m_Peer.Add(entry.hInstDll, pdllInfo))
{
RemoveDllEntry(entry);
}
if ((entry.hInstDll != NULL) && (!m_DllInfos.Add(*pdllInfo)))
{
RemoveDllEntry(entry);
}
m_critSec.Unlock();
return entry.hInstDll;
}
BOOL Free(HINSTANCE hInstDll)
{
HRESULT hr = m_critSec.Lock();
if (FAILED(hr))
return FALSE;
int nLen = m_Dlls.GetSize();
for (int i=0; i<nLen; i++)
{
DLL_CACHE_ENTRY &entry = m_Dlls[i];
if (entry.hInstDll == hInstDll)
{
ATLASSERT(entry.dwRefs > 0);
entry.bAlive = TRUE;
entry.dwRefs--;
m_critSec.Unlock();
return TRUE;
}
}
m_critSec.Unlock();
// the dll wasn't found
// in the cache, so just
// pass along to ::FreeLibrary
return ::FreeLibrary(hInstDll);
}
BOOL AddRefModule(HINSTANCE hInstDll)
{
HRESULT hr = m_critSec.Lock();
if (FAILED(hr))
return FALSE;
int nLen = m_Dlls.GetSize();
for (int i=0; i<nLen; i++)
{
DLL_CACHE_ENTRY &entry = m_Dlls[i];
if (entry.hInstDll == hInstDll)
{
ATLASSERT(entry.dwRefs > 0);
entry.dwRefs++;
m_critSec.Unlock();
return TRUE;
}
}
m_critSec.Unlock();
return FALSE;
}
BOOL ReleaseModule(HINSTANCE hInstDll)
{
HRESULT hr = m_critSec.Lock();
if (FAILED(hr))
return FALSE;
int nLen = m_Dlls.GetSize();
for (int i=0; i<nLen; i++)
{
DLL_CACHE_ENTRY &entry = m_Dlls[i];
if (entry.hInstDll == hInstDll)
{
ATLASSERT(entry.dwRefs > 0);
entry.bAlive = TRUE;
entry.dwRefs--;
m_critSec.Unlock();
return TRUE;
}
}
m_critSec.Unlock();
return FALSE;
}
HRESULT GetEntries(DWORD dwCount, DLL_CACHE_ENTRY *pEntries, DWORD *pdwCopied)
{
if (!pdwCopied)
return E_POINTER;
HRESULT hr = m_critSec.Lock();
if (FAILED(hr))
return hr;
if (dwCount==0 || pEntries==NULL)
{
// just return the required size
*pdwCopied = m_Dlls.GetSize();
m_critSec.Unlock();
return S_OK;
}
if (dwCount > (DWORD) m_Dlls.GetSize())
dwCount = m_Dlls.GetSize();
Checked::memcpy_s(pEntries, dwCount*sizeof(DLL_CACHE_ENTRY), m_Dlls.GetData(), dwCount*sizeof(DLL_CACHE_ENTRY));
*pdwCopied = dwCount;
m_critSec.Unlock();
return S_OK;
}
HRESULT Flush()
{
HRESULT hr = m_critSec.Lock();
if (FAILED(hr))
return hr;
int nLen = m_Dlls.GetSize();
for (int i=0; i<nLen; i++)
{
DLL_CACHE_ENTRY &entry = m_Dlls[i];
if (entry.dwRefs == 0 && !entry.bAlive)
{
_ATLTRY
{
m_Peer.Remove(entry.hInstDll, &m_DllInfos[i]);
}
_ATLCATCHALL()
{
ATLTRACE(atlTraceCache, 2, _T("Exception thrown from user code in CDllCache::Flush\n"));
}
::FreeLibrary(entry.hInstDll);
m_Dlls.RemoveAt(i);
m_DllInfos.RemoveAt(i);
i--;
nLen--;
}
entry.bAlive = FALSE;
}
m_critSec.Unlock();
return S_OK;
}
HRESULT Execute(DWORD_PTR /*dwParam*/, HANDLE /*hObject*/)
{
Flush();
return S_OK;
}
HRESULT CloseHandle(HANDLE hObject)
{
ATLASSUME(m_hTimer == hObject);
m_hTimer = NULL;
::CloseHandle(hObject);
return S_OK;
}
}; // CDllCache
//
//IStencilCache
//IStencilCache is used by a stencil processor to cache pointers to CStencil
//derived objects.
// {8702269B-707D-49cc-AEF8-5FFCB3D6891B}
extern "C" __declspec(selectany) const IID IID_IStencilCache = { 0x8702269b, 0x707d, 0x49cc, { 0xae, 0xf8, 0x5f, 0xfc, 0xb3, 0xd6, 0x89, 0x1b } };
__interface ATL_NO_VTABLE __declspec(uuid("8702269B-707D-49cc-AEF8-5FFCB3D6891B"))
IStencilCache : public IUnknown
{
// IStencilCache methods
STDMETHOD(CacheStencil)(LPCSTR szName, //a name for this cache entry
void *pStencil, //a pointer to a CStencil derived object
DWORD dwSize, //sizeof pStencil
HCACHEITEM *pHandle, //out pointer to a handle to the this cache entry
HINSTANCE hInst, //HINSTANCE of the module putting this entry
//in the cache.
IMemoryCacheClient *pClient //Interface used to free this instance
);
STDMETHOD(LookupStencil)(LPCSTR szName, HCACHEITEM * phStencil);
STDMETHOD(GetStencil)(const HCACHEITEM hStencil, void ** ppStencil) const;
STDMETHOD(AddRefStencil)(const HCACHEITEM hStencil);
STDMETHOD(ReleaseStencil)(const HCACHEITEM hStencil);
};
// {55DEF119-D7A7-4eb7-A876-33365E1C5E1A}
extern "C" __declspec(selectany) const IID IID_IStencilCacheControl = { 0x55def119, 0xd7a7, 0x4eb7, { 0xa8, 0x76, 0x33, 0x36, 0x5e, 0x1c, 0x5e, 0x1a } };
__interface ATL_NO_VTABLE __declspec(uuid("55DEF119-D7A7-4eb7-A876-33365E1C5E1A"))
IStencilCacheControl : public IUnknown
{
//IStencilCacheControl
STDMETHOD(RemoveStencil)(const HCACHEITEM hStencil); // Removes the stencil if there are no references,
// otherwise detaches it
STDMETHOD(RemoveStencilByName)(LPCSTR szStencil); //removes a stencil if there are no
//references to it
STDMETHOD(RemoveAllStencils)(); //removes all stencils that don't have references on them
STDMETHOD(SetDefaultLifespan)(unsigned __int64 dwdwLifespan); //sets the lifespan for all stencils
//in the cache (in 100 nanosecond units (10,000,000=1 second)).
STDMETHOD(GetDefaultLifespan)(unsigned __int64 *pdwdwLifespan);
};
#ifndef ATL_STENCIL_CACHE_TIMEOUT
#ifdef _DEBUG
#define ATL_STENCIL_CACHE_TIMEOUT 1000
#else
#define ATL_STENCIL_CACHE_TIMEOUT 5000
#endif // _DEBUG
#endif // ATL_STENCIL_CACHE_TIMEOUT
#ifndef ATL_STENCIL_LIFESPAN
#ifdef _DEBUG
#define ATL_STENCIL_LIFESPAN CFileTime::Second
#else
#define ATL_STENCIL_LIFESPAN CFileTime::Hour
#endif
#endif
// timeout before we check if the file
// has changed in m.s.
#ifndef ATL_STENCIL_CHECK_TIMEOUT
#define ATL_STENCIL_CHECK_TIMEOUT 1000
#endif
template <class MonitorClass,
class StatClass=CStdStatClass,
class SyncClass=CComCriticalSection,
class FlushClass=COldFlusher,
class CullClass=CLifetimeCuller >
class CStencilCache :
public CMemoryCacheBase<CStencilCache<MonitorClass, StatClass, SyncClass, FlushClass, CullClass>, void *, CCacheDataEx,
CFixedStringKey, CStringElementTraitsI<CFixedStringKey >,
FlushClass, CullClass, SyncClass, StatClass>,
public IStencilCache,
public IStencilCacheControl,
public IWorkerThreadClient,
public IMemoryCacheStats,
public CComObjectRootEx<CComGlobalsThreadModel>
{
protected:
typedef CMemoryCacheBase<CStencilCache<MonitorClass, StatClass, SyncClass, FlushClass, CullClass>, void *, CCacheDataEx,
CFixedStringKey, CStringElementTraitsI<CFixedStringKey >,
FlushClass, CullClass, SyncClass, StatClass> cacheBase;
unsigned __int64 m_dwdwStencilLifespan;
MonitorClass m_Monitor;
HANDLE m_hTimer;
CComPtr<IDllCache> m_spDllCache;
public:
CStencilCache() :
m_dwdwStencilLifespan(ATL_STENCIL_LIFESPAN),
m_hTimer(NULL)
{
}
~CStencilCache()
{
if (m_hTimer)
{
ATLENSURE(SUCCEEDED(m_Monitor.RemoveHandle(m_hTimer)));
}
}
HRESULT Execute(DWORD_PTR dwParam, HANDLE /*hObject*/)
{
CStencilCache* pCache = (CStencilCache*)dwParam;
if (pCache)
pCache->FlushEntries();
return S_OK;
}
HRESULT CloseHandle(HANDLE hObject)
{
ATLASSUME(m_hTimer == hObject);
m_hTimer = NULL;
::CloseHandle(hObject);
return S_OK;
}
HRESULT Initialize(IServiceProvider *pProv, DWORD dwStencilCacheTimeout=ATL_STENCIL_CACHE_TIMEOUT,
__int64 dwdwStencilLifespan=ATL_STENCIL_LIFESPAN)
{
m_dwdwStencilLifespan = dwdwStencilLifespan;
HRESULT hr = cacheBase::Initialize();
if (FAILED(hr))
return hr;
hr = E_FAIL;
if (pProv)
hr = pProv->QueryService(__uuidof(IDllCache), __uuidof(IDllCache), (void**)&m_spDllCache);
if (FAILED(hr))
return hr;
hr = m_Monitor.Initialize();
if (FAILED(hr))
return hr;
return m_Monitor.AddTimer(dwStencilCacheTimeout, this, (DWORD_PTR) this, &m_hTimer);
}
template <class ThreadTraits>
HRESULT Initialize(IServiceProvider *pProv, CWorkerThread<ThreadTraits> *pWorkerThread,
DWORD dwStencilCacheTimeout=ATL_STENCIL_CACHE_TIMEOUT, __int64 dwdwStencilLifespan=ATL_STENCIL_LIFESPAN)
{
m_dwdwStencilLifespan = dwdwStencilLifespan;
HRESULT hr = cacheBase::Initialize();
if (FAILED(hr))
return hr;
hr = E_FAIL;
if (pProv)
hr = pProv->QueryService(__uuidof(IDllCache), __uuidof(IDllCache), (void**)&m_spDllCache);
if (FAILED(hr))
return hr;
hr = m_Monitor.Initialize(pWorkerThread);
if (FAILED(hr))
return hr;
return m_Monitor.AddTimer(dwStencilCacheTimeout, this, (DWORD_PTR) this, &m_hTimer);
}
BEGIN_COM_MAP(CStencilCache)
COM_INTERFACE_ENTRY(IMemoryCacheStats)
COM_INTERFACE_ENTRY(IStencilCache)
COM_INTERFACE_ENTRY(IStencilCacheControl)
END_COM_MAP()
//IStencilCache methods
STDMETHOD(CacheStencil)(LPCSTR szName, void *pStencil, DWORD dwSize, HCACHEITEM *phEntry,
HINSTANCE hInstance, IMemoryCacheClient *pClient)
{
NodeType * pEntry = NULL;
HRESULT hr = m_syncObj.Lock();
if (FAILED(hr))
return hr;
_ATLTRY
{
hr = cacheBase::AddEntry(szName, pStencil, dwSize, (HCACHEITEM *)&pEntry);
}
_ATLCATCHALL()
{
hr = E_FAIL;
}
if (hr != S_OK)
{
m_syncObj.Unlock();
return hr;
}
pEntry->hInstance = hInstance;
pEntry->pClient = pClient;
pEntry->nLifespan = m_dwdwStencilLifespan;
if (hInstance && m_spDllCache)
m_spDllCache->AddRefModule(hInstance);
cacheBase::CommitEntry(static_cast<HCACHEITEM>(pEntry));
if (phEntry)
*phEntry = static_cast<HCACHEITEM>(pEntry);
else
cacheBase::ReleaseEntry(static_cast<HCACHEITEM>(pEntry));
m_syncObj.Unlock();
return hr;
}
STDMETHOD(LookupStencil)(LPCSTR szName, HCACHEITEM * phStencil)
{
return cacheBase::LookupEntry(szName, phStencil);
}
STDMETHOD(GetStencil)(const HCACHEITEM hStencil, void ** pStencil) const
{
return cacheBase::GetEntryData(hStencil, pStencil, NULL);
}
STDMETHOD(AddRefStencil)(const HCACHEITEM hStencil)
{
return cacheBase::AddRefEntry(hStencil);
}
STDMETHOD(ReleaseStencil)(const HCACHEITEM hStencil)
{
return cacheBase::ReleaseEntry(hStencil);
}
//IStencilCacheControl
STDMETHOD(RemoveStencil)(const HCACHEITEM hStencil)
{
return cacheBase::RemoveEntry(hStencil);
}
STDMETHOD(RemoveStencilByName)(LPCSTR szStencil)
{
return cacheBase::RemoveEntryByKey(szStencil);
}
STDMETHOD(RemoveAllStencils)()
{
return cacheBase::RemoveAllEntries();
}
STDMETHOD(SetDefaultLifespan)(unsigned __int64 dwdwLifespan)
{
m_dwdwStencilLifespan = dwdwLifespan;
return S_OK;
}
STDMETHOD(GetDefaultLifespan)(unsigned __int64 *pdwdwLifepsan)
{
HRESULT hr = E_POINTER;
if (pdwdwLifepsan)
{
*pdwdwLifepsan = m_dwdwStencilLifespan;
hr = S_OK;
}
return hr;
}
virtual void OnDestroyEntry(const NodeType * pEntry)
{
ATLASSERT(pEntry);
if (!pEntry)
return;
if (pEntry->pClient)
pEntry->pClient->Free((void *)&pEntry->Data);
if (pEntry->hInstance && m_spDllCache)
m_spDllCache->ReleaseModule(pEntry->hInstance);
}
HRESULT Uninitialize()
{
HRESULT hrMonitor=S_OK;
if (m_hTimer)
{
hrMonitor=m_Monitor.RemoveHandle(m_hTimer);
m_hTimer = NULL;
}
m_Monitor.Shutdown();
HRESULT hrCache=cacheBase::Uninitialize();
if(FAILED(hrMonitor))
{
return hrMonitor;
}
return hrCache;
}
// IMemoryCacheStats methods
HRESULT STDMETHODCALLTYPE ClearStats()
{
m_statObj.ResetCounters();
return S_OK;
}
HRESULT STDMETHODCALLTYPE GetHitCount(DWORD *pdwSize)
{
if (!pdwSize)
return E_POINTER;
*pdwSize = m_statObj.GetHitCount();
return S_OK;
}
HRESULT STDMETHODCALLTYPE GetMissCount(DWORD *pdwSize)
{
if (!pdwSize)
return E_POINTER;
*pdwSize = m_statObj.GetMissCount();
return S_OK;
}
HRESULT STDMETHODCALLTYPE GetMaxAllocSize(DWORD *pdwSize)
{
if (!pdwSize)
return E_POINTER;
*pdwSize = m_statObj.GetMaxAllocSize();
return S_OK;
}
HRESULT STDMETHODCALLTYPE GetCurrentAllocSize(DWORD *pdwSize)
{
if (!pdwSize)
return E_POINTER;
*pdwSize = m_statObj.GetCurrentAllocSize();
return S_OK;
}
HRESULT STDMETHODCALLTYPE GetMaxEntryCount(DWORD *pdwSize)
{
if (!pdwSize)
return E_POINTER;
*pdwSize = m_statObj.GetMaxEntryCount();
return S_OK;
}
HRESULT STDMETHODCALLTYPE GetCurrentEntryCount(DWORD *pdwSize)
{
if (!pdwSize)
return E_POINTER;
*pdwSize = m_statObj.GetCurrentEntryCount();
return S_OK;
}
}; // CStencilCache
// {105A8866-4059-45fe-86AE-FA0EABBFBBB4}
extern "C" __declspec(selectany) const IID IID_IFileCache = { 0x105a8866, 0x4059, 0x45fe, { 0x86, 0xae, 0xfa, 0xe, 0xab, 0xbf, 0xbb, 0xb4 } };
__interface ATL_NO_VTABLE __declspec(uuid("105A8866-4059-45fe-86AE-FA0EABBFBBB4"))
IFileCache : public IUnknown
{
// IFileCache Methods
STDMETHOD(AddFile)(
LPCSTR szFileName,
LPCSTR szTempFileName,
FILETIME *pftExpireTime,
void *pPeerInfo,
HCACHEITEM * phKey);
STDMETHOD(LookupFile)(LPCSTR szFileName, HCACHEITEM * phKey);
STDMETHOD(GetFile)(const HCACHEITEM hKey, LPSTR * pszFileName, void **ppPeerInfo);
STDMETHOD(ReleaseFile)(const HCACHEITEM hKey);
STDMETHOD(RemoveFile)(const HCACHEITEM hKey);
STDMETHOD(RemoveFileByName)(LPCSTR szFileName);
STDMETHOD(Flush)();
};
#ifndef ATL_FILE_CACHE_TIMEOUT
#define ATL_FILE_CACHE_TIMEOUT 1000
#endif
class CNoFileCachePeer
{
public:
struct PeerInfo
{
};
static BOOL Add(PeerInfo* /*pDest*/, PeerInfo * /*pSrc*/)
{
return TRUE;
}
static BOOL Remove(const PeerInfo* /*pFileInfo*/)
{
return TRUE;
}
};
template <class Peer>
struct CCacheDataPeer : public CCacheDataBase
{
typename Peer::PeerInfo PeerData;
};
// A class to keep track of files, with maintenance -- maximum size of cache,
// maximum number of entries, expiration of entries, etc. -- inherits from
// CMemoryCacheBase
template <
class MonitorClass,
class StatClass=CStdStatClass,
class FileCachePeer=CNoFileCachePeer,
class FlushClass=COldFlusher,
class SyncClass=CComCriticalSection,
class CullClass=CExpireCuller >
class CFileCache:
public CMemoryCacheBase<CFileCache<MonitorClass, StatClass, FileCachePeer, FlushClass, SyncClass, CullClass>, LPSTR, CCacheDataPeer<FileCachePeer>,
CFixedStringKey, CStringElementTraits<CFixedStringKey >,
FlushClass, CullClass, SyncClass, StatClass>,
public IWorkerThreadClient,
public IFileCache,
public IMemoryCacheControl,
public IMemoryCacheStats
{
typedef CMemoryCacheBase<CFileCache<MonitorClass, StatClass, FileCachePeer, FlushClass, SyncClass, CullClass>, LPSTR, CCacheDataPeer<FileCachePeer>,
CFixedStringKey, CStringElementTraits<CFixedStringKey >,
FlushClass, CullClass, SyncClass, StatClass> cacheBase;
MonitorClass m_Monitor;
protected:
HANDLE m_hTimer;
public:
CFileCache() : m_hTimer(NULL)
{
}
HRESULT Initialize()
{
HRESULT hr = cacheBase::Initialize();
if (FAILED(hr))
return hr;
hr = m_Monitor.Initialize();
if (FAILED(hr))
return hr;
return m_Monitor.AddTimer(ATL_FILE_CACHE_TIMEOUT,
static_cast<IWorkerThreadClient*>(this), (DWORD_PTR) this, &m_hTimer);
}
template <class ThreadTraits>
HRESULT Initialize(CWorkerThread<ThreadTraits> *pWorkerThread)
{
ATLASSERT(pWorkerThread);
HRESULT hr = cacheBase::Initialize();
if (FAILED(hr))
return hr;
hr = m_Monitor.Initialize(pWorkerThread);
if (FAILED(hr))
return hr;
return m_Monitor.AddTimer(ATL_FILE_CACHE_TIMEOUT,
static_cast<IWorkerThreadClient*>(this), (DWORD_PTR) this, &m_hTimer);
}
// Callback for CWorkerThread
HRESULT Execute(DWORD_PTR dwParam, HANDLE /*hObject*/)
{
CFileCache* pCache = (CFileCache*)dwParam;
if (pCache)
pCache->Flush();
return S_OK;
}
HRESULT CloseHandle(HANDLE hObject)
{
ATLASSUME(m_hTimer == hObject);
m_hTimer = NULL;
::CloseHandle(hObject);
return S_OK;
}
~CFileCache()
{
if (m_hTimer)
{
ATLENSURE(SUCCEEDED(m_Monitor.RemoveHandle(m_hTimer)));
m_hTimer = NULL;
}
}
HRESULT Uninitialize()
{
HRESULT hrMonitor=S_OK;
if (m_hTimer)
{
hrMonitor=m_Monitor.RemoveHandle(m_hTimer);
m_hTimer = NULL;
}
m_Monitor.Shutdown();
HRESULT hrCache=cacheBase::Uninitialize();
if(FAILED(hrMonitor))
{
return hrMonitor;
}
return hrCache;
}
// IUnknown methods
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppv)
{
HRESULT hr = E_NOINTERFACE;
if (!ppv)
hr = E_POINTER;
else
{
if (InlineIsEqualGUID(riid, __uuidof(IUnknown)) ||
InlineIsEqualGUID(riid, __uuidof(IFileCache)))
{
*ppv = (IUnknown *) (IFileCache *) this;
AddRef();
hr = S_OK;
}
if (InlineIsEqualGUID(riid, __uuidof(IMemoryCacheStats)))
{
*ppv = (IMemoryCacheStats*)this;
AddRef();
hr = S_OK;
}
if (InlineIsEqualGUID(riid, __uuidof(IMemoryCacheControl)))
{
*ppv = (IMemoryCacheControl*)this;
AddRef();
hr = S_OK;
}
}
return hr;
}
ULONG STDMETHODCALLTYPE AddRef()
{
return 1;
}
ULONG STDMETHODCALLTYPE Release()
{
return 1;
}
// Adds a file to the cache. A file is created with a
// temporary name, and then Add is called with the temp
// file name and the final file name, along with expiration data,
// etc. A search on the file name will return the name of
// the file on disk (i.e. the temporary file)
HRESULT STDMETHODCALLTYPE AddFile(
LPCSTR szFileName,
LPCSTR szTempFileName,
FILETIME *pftExpireTime,
void* pPeerInfo,
HCACHEITEM * phKey = NULL)
{
WIN32_FILE_ATTRIBUTE_DATA fadData;
BOOL bRet = GetFileAttributesExA(szTempFileName, GetFileExInfoStandard, &fadData);
if (!bRet)
return AtlHresultFromLastError();
__int64 ddwFileSize = (static_cast<__int64>(fadData.nFileSizeHigh) << 32) + fadData.nFileSizeLow;
DWORD dwRecordedFileSize = (DWORD) (ddwFileSize >> 10);
// Round the file size up to 1K if it is < 1K
if (dwRecordedFileSize == 0)
dwRecordedFileSize = 1;
if (m_Monitor.GetThreadHandle()==NULL)
{
if (!cacheBase::CanAddEntry(dwRecordedFileSize))
{
cacheBase::FlushEntries();
if (!cacheBase::CanAddEntry(dwRecordedFileSize))
return E_OUTOFMEMORY;
}
}
NodeType *pEntry = NULL;
HRESULT hr = m_syncObj.Lock();
if (FAILED(hr))
return hr;
hr = E_FAIL;
// Make a private copy of the file name
CHeapPtr<char> szTempFileCopy;
if (szTempFileCopy.Allocate(MAX_PATH))
{
if (strlen(szTempFileName) >= MAX_PATH)
{
m_syncObj.Unlock();
return E_FAIL;
}
Checked::strncpy_s(szTempFileCopy, MAX_PATH, szTempFileName, _TRUNCATE);
_ATLTRY
{
hr = cacheBase::AddEntry(szFileName, szTempFileCopy, dwRecordedFileSize, (HCACHEITEM*)&pEntry);
szTempFileCopy.Detach();
}
_ATLCATCHALL()
{
hr = E_FAIL;
}
}
if (hr != S_OK)
{
m_syncObj.Unlock();
return hr;
}
hr = (TRUE == FileCachePeer::Add(&pEntry->PeerData,
static_cast<FileCachePeer::PeerInfo*>(pPeerInfo)) ? S_OK : E_FAIL);
if (hr == S_OK)
hr = cacheBase::CommitEntry(static_cast<HCACHEITEM>(pEntry));
if (hr != S_OK)
{
cacheBase::RemoveEntry(static_cast<HCACHEITEM>(pEntry));
m_syncObj.Unlock();
return hr;
}
if (pftExpireTime)
pEntry->cftExpireTime = *pftExpireTime;
if (phKey)
*phKey = static_cast<HCACHEITEM>(pEntry);
else
cacheBase::ReleaseEntry(pEntry);
m_syncObj.Unlock();
return hr;
}
// Action to take when the entry is removed from the cache
virtual void OnDestroyEntry(const NodeType * pEntry)
{
ATLASSERT(pEntry);
if (!pEntry)
return;
FileCachePeer::Remove(&pEntry->PeerData);
if (pEntry->Data)
{
DeleteFileA(pEntry->Data);
free(pEntry->Data);
const_cast<NodeType*>(pEntry)->Data = NULL;
}
}
// Looks up a file by name. Must be released after use
HRESULT STDMETHODCALLTYPE LookupFile(LPCSTR szFileName, HCACHEITEM * phKey)
{
return cacheBase::LookupEntry(szFileName, phKey);
}
// Gets the name of the file on disk
HRESULT STDMETHODCALLTYPE GetFile(__in const HCACHEITEM hKey, __deref_out_z_opt LPSTR * pszFileName, __deref_out_opt void **ppPeerInfo)
{
NodeType *pEntry = (NodeType *)hKey;
if (ppPeerInfo)
*ppPeerInfo = &pEntry->PeerData;
return cacheBase::GetEntryData(hKey, pszFileName, NULL);
}
// Releases a file
HRESULT STDMETHODCALLTYPE ReleaseFile(const HCACHEITEM hKey)
{
return cacheBase::ReleaseEntry(hKey);
}
// Releases a file and marks it for deletion
HRESULT STDMETHODCALLTYPE RemoveFile(const HCACHEITEM hKey)
{
return cacheBase::RemoveEntry(hKey);
}
// Removes a file by name -- this calls IMemoryCacheClient->Free
// on the file name, which by default (for CFileCache) deletes the
// file.
HRESULT STDMETHODCALLTYPE RemoveFileByName(LPCSTR szFileName)
{
return cacheBase::RemoveEntryByKey(szFileName);
}
// Flushes the entries in the cache, eliminates expired entries,
// or if the cache exceeds the parameters (alloc size, num entries),
// culls items based on the sweep mode
HRESULT STDMETHODCALLTYPE Flush()
{
return cacheBase::FlushEntries();
}
// IMemoryCacheControl methods
HRESULT STDMETHODCALLTYPE SetMaxAllowedSize(DWORD dwSize)
{
return cacheBase::SetMaxAllowedSize(dwSize);
}
HRESULT STDMETHODCALLTYPE GetMaxAllowedSize(DWORD *pdwSize)
{
return cacheBase::GetMaxAllowedSize(pdwSize);
}
HRESULT STDMETHODCALLTYPE SetMaxAllowedEntries(DWORD dwSize)
{
return cacheBase::SetMaxAllowedEntries(dwSize);
}
HRESULT STDMETHODCALLTYPE GetMaxAllowedEntries(DWORD *pdwSize)
{
return cacheBase::GetMaxAllowedEntries(pdwSize);
}
HRESULT STDMETHODCALLTYPE ResetCache()
{
return cacheBase::ResetCache();
}
// IMemoryCacheStats methods
HRESULT STDMETHODCALLTYPE ClearStats()
{
m_statObj.ResetCounters();
return S_OK;
}
HRESULT STDMETHODCALLTYPE GetHitCount(DWORD *pdwSize)
{
if (!pdwSize)
return E_POINTER;
*pdwSize = m_statObj.GetHitCount();
return S_OK;
}
HRESULT STDMETHODCALLTYPE GetMissCount(DWORD *pdwSize)
{
if (!pdwSize)
return E_POINTER;
*pdwSize = m_statObj.GetMissCount();
return S_OK;
}
HRESULT STDMETHODCALLTYPE GetMaxAllocSize(DWORD *pdwSize)
{
if (!pdwSize)
return E_POINTER;
*pdwSize = m_statObj.GetMaxAllocSize();
return S_OK;
}
HRESULT STDMETHODCALLTYPE GetCurrentAllocSize(DWORD *pdwSize)
{
if (!pdwSize)
return E_POINTER;
*pdwSize = m_statObj.GetCurrentAllocSize();
return S_OK;
}
HRESULT STDMETHODCALLTYPE GetMaxEntryCount(DWORD *pdwSize)
{
if (!pdwSize)
return E_POINTER;
*pdwSize = m_statObj.GetMaxEntryCount();
return S_OK;
}
HRESULT STDMETHODCALLTYPE GetCurrentEntryCount(DWORD *pdwSize)
{
if (!pdwSize)
return E_POINTER;
*pdwSize = m_statObj.GetCurrentEntryCount();
return S_OK;
}
}; // CFileCache
class CDataConnection; // see atldbcli.h
__interface __declspec(uuid("52E7759B-D6CC-4a03-BDF3-80A6BDCA1F94"))
IDataSourceCache : public IUnknown
{
// Method: Add
// Params:
// szConn: Connection string of data source to connect to
// ppDS: Out pointer to the newly added data source
// Comments:
// Attempts to open a connection to the specified data source
// using a CDataSource object. Once the connection is open, the
// CDatasource is cached.
STDMETHOD(Add)(LPCTSTR szID, LPCOLESTR szConn, CDataConnection *pDS);
// Method: Remove
// Params:
// szConn: Specifies the connection string of the connection to close
// Comments:
// Closes the specified connection and removes it's entry from the cache
STDMETHOD(Remove)(LPCTSTR szID);
// Method: Lookup
// Params:
// szConn: Specifies the connection string of the connection to look up
// ppDS: Out pointer to CDataSource object that is connected to the specified
// data source.
STDMETHOD(Lookup)(LPCTSTR szID, CDataConnection *pDS);
// Method: Uninitialize
// Params:
// None
// Comments:
// Closes removes all connections from the cache.
STDMETHOD(Uninitialize)();
};
#ifndef ATL_DS_CONN_STRING_LEN
#define ATL_DS_CONN_STRING_LEN 512
#endif
template <>
class CElementTraits< CDataConnection > :
public CElementTraitsBase< CDataConnection >
{
public:
static ULONG Hash( INARGTYPE t )
{
return( ULONG( ULONG_PTR( &t ) ) );
}
static bool CompareElements( INARGTYPE element1, INARGTYPE element2 )
{
return( element1.m_session.m_spOpenRowset == element2.m_session.m_spOpenRowset);
}
static int CompareElementsOrdered( INARGTYPE /*element1*/, INARGTYPE /*element2*/ )
{
ATLASSERT(FALSE);
return -1;
}
};
typedef CFixedStringT<CString, ATL_DS_CONN_STRING_LEN> atlDataSourceKey;
typedef CAtlMap<atlDataSourceKey, CDataConnection,
CStringElementTraits<atlDataSourceKey>, CElementTraits<CDataConnection> > atlDataSourceCacheMap;
template <class TCritSec=CComFakeCriticalSection>
class CDataSourceCache :
public IDataSourceCache,
public CComObjectRootEx<CComGlobalsThreadModel>
{
public:
BEGIN_COM_MAP(CDataSourceCache)
COM_INTERFACE_ENTRY(IDataSourceCache)
END_COM_MAP()
CDataSourceCache()
{
m_cs.Init();
}
virtual ~CDataSourceCache ()
{
Uninitialize();
}
STDMETHOD(Uninitialize)()
{
HRESULT hr = m_cs.Lock();
if (SUCCEEDED(hr))
{
m_ConnectionMap.RemoveAll();
m_cs.Unlock();
}
return hr;
}
STDMETHOD(Add)(LPCTSTR szID, LPCOLESTR szConn, CDataConnection *pSession)
{
HRESULT hr = E_FAIL;
if (!szID)
return E_INVALIDARG; // must have session name
// Do a lookup to make sure we don't add multiple entries
// with the same name. Adding multiple entries with the same name
// could cause some entries to get orphaned.
hr = m_cs.Lock();
if (FAILED(hr))
{
return hr;
}
const atlDataSourceCacheMap::CPair *pPair =
m_ConnectionMap.Lookup(szID);
if (!pPair)
{
// try to open connection
CDataConnection DS;
hr = DS.Open(szConn);
if (hr == S_OK)
{
_ATLTRY
{
if (m_ConnectionMap.SetAt(szID, DS))
{
if (pSession) // we allow NULL here
*pSession = DS; // copy connection to output.
hr = S_OK;
}
else
hr = E_FAIL; // map add failed
}
_ATLCATCHALL()
{
hr = E_FAIL;
}
}
}
else // lookup succeeded, entry is already in cache
{
// Instead of opening a new connection, just copy
// the one we already have in the cache.
if (pSession)
*pSession = pPair->m_value;
hr = S_OK;
}
m_cs.Unlock();
return hr;
}
STDMETHOD(Remove)(LPCTSTR szID)
{
HRESULT hr = E_INVALIDARG;
if (!szID)
return hr; // must have session name
hr = m_cs.Lock();
if (SUCCEEDED(hr))
{
hr = m_ConnectionMap.RemoveKey(szID) ? S_OK : E_FAIL;
m_cs.Unlock();
}
return hr;
}
STDMETHOD(Lookup)(LPCTSTR szID, CDataConnection *pSession)
{
if (!szID||!pSession)
return E_POINTER;
HRESULT hr = m_cs.Lock();
bool bRet = true;
if (SUCCEEDED(hr))
{
bRet = m_ConnectionMap.Lookup(szID, *pSession);
m_cs.Unlock();
}
return (bRet && (bool)*pSession)? hr : E_FAIL;
}
protected:
atlDataSourceCacheMap m_ConnectionMap;
TCritSec m_cs;
};
// Some helpers for using the datasource cache.
//
// Function: GetDataSource
// Params:
// pProvider: Pointer to IServiceProvider that provides the
// data source cache service
// szID: The name of the connection (can be same as szDS)
// szDS: OLEDB connection string for data source
// ppDS: Out pointer to CDataSource. The CDataSource will be connected
// to the OLEDB provider specified by szDS on successful return.
// RetVal:
// Returns S_OK on success.
static HRESULT ATL_NOINLINE GetDataSource(IServiceProvider *pProvider,
LPCTSTR szID, LPCOLESTR szConn,
CDataConnection *pSession)
{
if (!pProvider || !szID || !szConn)
return E_POINTER;
CComPtr<IDataSourceCache> spDSCache;
HRESULT hr;
hr = pProvider->QueryService(__uuidof(IDataSourceCache), __uuidof(IDataSourceCache), (void**)&spDSCache);
if (hr == S_OK && spDSCache)
{
hr = spDSCache->Add(szID, szConn, pSession);
}
return hr;
}
//
// Function: RemoveDataSource
// Params:
// pProvider: Pointer to IServiceProvider that provides the
// data source cache service
// szID: Name of the datasource connection to remove from the cache
// RetVal:
// none
// Comments:
// Removes the datasource entry from the datasource cache. Since entries are
// copied to the client on calls to lookup and add, removing an entry will not
// release the connections of existing clients.
static HRESULT ATL_NOINLINE RemoveDataSource(IServiceProvider *pProvider, LPCTSTR szID)
{
if (!pProvider || !szID)
return E_POINTER;
CComPtr<IDataSourceCache> spDSCache;
HRESULT hr = pProvider->QueryService(__uuidof(IDataSourceCache), __uuidof(IDataSourceCache), (void**)&spDSCache);
if (spDSCache)
hr = spDSCache->Remove(szID);
return hr;
}
} // namespace ATL
#pragma pack(pop)
#pragma warning (pop)
#endif // __ATLCACHE_H__
| [
"asandman@5d4b435c-4d46-d949-aab2-e601ca53af14"
]
| [
[
[
1,
3246
]
]
]
|
2f66b826316e7a0397d0156cc18ce7bf158c01af | 2ea2445257dd404cdbefa57a95095b37c6e17d23 | /GPU_Warp/trunk/GPU_Warp/FilterWarp.h | 48ac8bf4b9a98760f4f0d68c83498af29a185d2f | []
| no_license | loongfee/gpu-image-warp | 7143e32d30506b3c67e6fee60b3e312191398937 | 56143fbf6337576a0f8a11691ae8c463e5c8ee14 | refs/heads/master | 2020-05-17T19:07:39.813752 | 2009-03-29T08:27:16 | 2009-03-29T08:27:16 | 42,363,349 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 468 | h | #ifndef FILTERWARP_H
#define FILTERWARP_H
namespace GpuImageProcess
{
struct Image;
}
namespace GpuImageProcess
{
class FilterWarp
{
public:
// Call fbo init
void Init();
// Do The Warping
bool Warp(
const Image& inImage, // input image
Image& outImage, // output image
float xRot, float yRot, float zRot, // image rotation
float xTrans, float yTrans, float zTrans); // image translation
};
}
#endif | [
"ralexay@ae3fb228-0cf0-11de-98bb-07cc9828235c"
]
| [
[
[
1,
26
]
]
]
|
8bd75eabf8916c34218bbe2e64590c5946cf98bc | dc4b6ab7b120262779e29d8b2d96109517f35551 | /TextFile.cpp | e2cbbfd89720548b24e515ab7fbce1bc493a1af3 | []
| no_license | cnsuhao/wtlhelper9 | 92daef29b61f95f44a10e3277d8835c2dd620616 | 681df3a014fc71597e9380b0a60bd3cd23e22efe | refs/heads/master | 2021-07-17T19:59:07.143192 | 2009-05-18T14:24:48 | 2009-05-18T14:24:48 | 108,361,858 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,527 | cpp | ////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004 Sergey Solozhentsev
// Author: Sergey Solozhentsev e-mail: [email protected]
// Product: WTL Helper
// File: TextFile.cpp
// Created: 21.01.2005 8:57
//
// Using this software in commercial applications requires an author
// permission. The permission will be granted to everyone excluding the cases
// when someone simply tries to resell the code.
// This file may be redistributed by any means PROVIDING it is not sold for
// profit without the authors written consent, and providing that this notice
// and the authors name is included.
// This file is provided "as is" with no expressed or implied warranty. The
// author accepts no liability if it causes any damage to you or your computer
// whatsoever.
//
////////////////////////////////////////////////////////////////////////////////
#include "StdAfx.h"
#include ".\textfile.h"
CTextFile::CTextFile(void) : m_pBuf(NULL), m_dwSize(0), m_dwPos(0)
{
}
CTextFile::~CTextFile(void)
{
Close();
}
BOOL CTextFile::Open(LPCTSTR lpFileName)
{
Close();
HRESULT hRes = m_File.Create(lpFileName, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN);
if (hRes != S_OK)
return FALSE;
ULONGLONG lSize;
m_File.GetSize(lSize);
m_dwSize = (DWORD)lSize;
if (m_dwSize > 128*1024)
{
if (m_Mapping.MapFile(m_File) != S_OK)
{
return FALSE;
}
m_pBuf = m_Mapping;
}
else
{
m_pBuf = new char[m_dwSize];
if (m_File.Read(m_pBuf, m_dwSize) != S_OK)
return FALSE;
}
return TRUE;
}
BOOL CTextFile::ReadLine(CString& Line)
{
if (m_dwPos >= m_dwSize)
return FALSE;
DWORD dwPos = m_dwPos;
while(dwPos < m_dwSize)
{
if (m_pBuf[dwPos] == '\n')
{
DWORD Len = dwPos - m_dwPos;
if (m_pBuf[dwPos - 1] == '\r' && Len)
Len--;
if (Len)
Line = CString(m_pBuf + m_dwPos, Len);
else
Line.Empty();
m_dwPos = dwPos + 1;
return TRUE;
}
dwPos++;
}
Line = CString(m_pBuf + m_dwPos, dwPos - m_dwPos);
m_dwPos = dwPos;
return TRUE;
}
BOOL CTextFile::Eof()
{
if (m_dwPos >= m_dwSize)
return TRUE;
else
return FALSE;
}
void CTextFile::Close()
{
if (m_pBuf)
{
if (m_dwSize > 128*1024)
{
m_Mapping.Unmap();
}
else
{
if (m_pBuf)
{
delete[] m_pBuf;
m_pBuf = NULL;
}
}
m_File.Close();
}
m_dwSize = 0;
m_dwPos = 0;
} | [
"free2000fly@eea8f18a-16fd-41b0-b60a-c1204a6b73d1"
]
| [
[
[
1,
115
]
]
]
|
4acfd98b52d2078a8d477d2ad43840d4670c2e3f | cd61c8405fae2fa91760ef796a5f7963fa7dbd37 | /Sauron/Vision/Camera.cpp | bb5c4a858baf64714d323544c3909a20e11360cc | []
| no_license | rafaelhdr/tccsauron | b61ec89bc9266601140114a37d024376a0366d38 | 027ecc2ab3579db1214d8a404d7d5fa6b1a64439 | refs/heads/master | 2016-09-05T23:05:57.117805 | 2009-12-14T09:41:58 | 2009-12-14T09:41:58 | 32,693,544 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,335 | cpp | #include "Camera.h"
#include <atlbase.h>
namespace sauron
{
#if _USE_DSHOW
Camera::Camera()
{
m_videoInput.setVerbose( true );
int numDevices = m_videoInput.listDevices();
m_videoInput.setupDevice( 0 );
m_width = m_videoInput.getWidth( 0 );
m_height = m_videoInput.getHeight( 0 );
m_videoInput.setIdealFramerate( 0, 60 );
m_videoInput.showSettingsWindow( 0 );
while ( !m_videoInput.isDeviceSetup( 0 ) );
}
Camera::~Camera()
{
m_videoInput.stopDevice( 0 );
}
bool Camera::getFrame( Image &im )
{
if ( m_videoInput.isFrameNew( 0 ) )
{
if ( im.getWidth() != m_width || im.getHeight() != m_height || im.getFormat() != Pixel::PF_RGB )
im = Image( m_width, m_height, 8, Pixel::PF_RGB );
m_videoInput.getPixels( 0, (byte *)((IplImage*)im)->imageData, false, true );
return true;
}
return false;
}
void Camera::setSize( uint width, uint height )
{
m_videoInput.stopDevice( 0 );
m_videoInput.setupDevice( 0, width, height );
m_width = m_videoInput.getWidth( 0 );
m_height = m_videoInput.getHeight( 0 );
while ( !m_videoInput.isDeviceSetup( 0 ) );
}
uint Camera::getWidth() const
{
return m_width;
}
uint Camera::getHeight() const
{
return m_height;
}
#else // _USE_DSHOW
Camera::Camera()
: m_capture( NULL )
{
m_capture = cvCaptureFromCAM( CV_CAP_ANY );
// Ensures that the camera is initialized before exit the constructor
while ( !cvGrabFrame( m_capture ) );
}
Camera::~Camera(void)
{
cvReleaseCapture( &m_capture );
}
bool Camera::getFrame( Image &im )
{
IplImage *frame = cvQueryFrame( m_capture );
im = frame;
if ( frame )
return true;
return false;
}
void Camera::setSize( uint width, uint height )
{
cvSetCaptureProperty( m_capture, CV_CAP_PROP_FRAME_WIDTH, width );
cvSetCaptureProperty( m_capture, CV_CAP_PROP_FRAME_HEIGHT, height );
}
uint Camera::getWidth() const
{
return (uint)cvGetCaptureProperty( m_capture, CV_CAP_PROP_FRAME_WIDTH );
}
uint Camera::getHeight() const
{
return (uint)cvGetCaptureProperty( m_capture, CV_CAP_PROP_FRAME_HEIGHT );
}
#endif // _USE_DSHOW
} // namespace sauron
| [
"fggodoy@8373e73c-ebb0-11dd-9ba5-89a75009fd5d"
]
| [
[
[
1,
118
]
]
]
|
8485fcb3a81b0945b8383126b6deea61bf94565e | 25f79693b806edb9041e3786fa3cf331d6fd4b97 | /tests/unit/core/LocalBufferTests.cpp | 54def15b3bc8cafd49a95b55aa1942716a9a6ef2 | []
| no_license | ouj/amd-spl | ff3c9faf89d20b5d6267b7f862c277d16aae9eee | 54b38e80088855f5e118f0992558ab88a7dea5b9 | refs/heads/master | 2016-09-06T03:13:23.993426 | 2009-08-29T08:55:02 | 2009-08-29T08:55:02 | 32,124,284 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,130 | cpp | #include "CommonTestDefs.h"
#include "RuntimeTestFixture.h"
#include "util.h"
using namespace amdspl;
using namespace amdspl::core::cal;
typedef RuntimeTestFixture LocalBufferTests;
TEST_F(LocalBufferTests, LocalBufferTypeCastTest)
{
Device* device = _deviceMgr->getDefaultDevice();
if(!device)
return;
Buffer *buf =
RuntimeTestFixture::_bufMgr->createLocalBuffer(device, CAL_FORMAT_FLOAT_4, 1024);
LocalBuffer *localBuf =
dynamic_cast<LocalBuffer*>(buf);
ASSERT_TRUE(localBuf != NULL);
_bufMgr->destroyBuffer(localBuf);
}
TEST_F(LocalBufferTests, LocalBufferGetPropertiesTest)
{
Device* device = _deviceMgr->getDefaultDevice();
if(!device)
return;
Buffer *buf1D =
RuntimeTestFixture::_bufMgr->createLocalBuffer(device, CAL_FORMAT_FLOAT_2, 1024);
if (buf1D)
{
ASSERT_TRUE(buf1D->getResHandle() != 0);
ASSERT_TRUE(buf1D->getFormat() == CAL_FORMAT_FLOAT_2);
ASSERT_TRUE(buf1D->getWidth() == 1024);
ASSERT_TRUE(buf1D->getHeight() == 0);
}
_bufMgr->destroyBuffer(buf1D);
Buffer *buf2D =
RuntimeTestFixture::_bufMgr->createLocalBuffer(device, CAL_FORMAT_INT_1, 1024, 1024);
if (buf2D)
{
ASSERT_TRUE(buf2D->getResHandle() != 0);
ASSERT_TRUE(buf2D->getFormat() == CAL_FORMAT_INT_1);
ASSERT_TRUE(buf2D->getWidth() == 1024);
ASSERT_TRUE(buf2D->getHeight() == 1024);
}
_bufMgr->destroyBuffer(buf2D);
}
TEST_F(LocalBufferTests, LocalBufferReadWriteData1Test)
{
Device* device = _deviceMgr->getDefaultDevice();
if(!device)
return;
Buffer *buf1D =
RuntimeTestFixture::_bufMgr->createLocalBuffer(device, CAL_FORMAT_FLOAT_2, 1024);
if (buf1D)
{
vector<float2> cpuBuf(1024);
util::initializeBuffer(cpuBuf, 1024, 0, 1000, util::RANDOM);
ASSERT_TRUE(buf1D->readData(&cpuBuf[0], static_cast<unsigned long>(cpuBuf.size())));
vector<float2> result;
result.resize(1024);
ASSERT_TRUE(buf1D->writeData(&result[0], static_cast<unsigned long>(result.size())));
ASSERT_EQ(0, util::compareBuffers(cpuBuf, result, static_cast<unsigned long>(cpuBuf.size())));
_bufMgr->destroyBuffer(buf1D);
}
else
FAIL();
}
TEST_F(LocalBufferTests, LocalBufferReadWriteData2Test)
{
Device* device = _deviceMgr->getDefaultDevice();
if(!device)
return;
Buffer *buf =
RuntimeTestFixture::_bufMgr->createLocalBuffer(device, CAL_FORMAT_INT_2, 78, 0);
if (buf)
{
vector<int2> cpuBuf(78);
util::initializeBuffer(cpuBuf, 78, 1, 1000, util::RANDOM);
ASSERT_TRUE(buf->readData(&cpuBuf[0], static_cast<unsigned long>(cpuBuf.size())));
vector<int2> result;
result.resize(78);
ASSERT_TRUE(buf->writeData(&result[0], static_cast<unsigned long>(result.size())));
ASSERT_EQ(0, util::compareBuffers(cpuBuf, result, static_cast<unsigned long>(cpuBuf.size())));
_bufMgr->destroyBuffer(buf);
}
else
FAIL();
}
TEST_F(LocalBufferTests, LocalBufferReadWriteData3Test)
{
unsigned int width = 888;
unsigned int height = 999;
Device* device = _deviceMgr->getDefaultDevice();
if(!device)
return;
Buffer *buf1D =
RuntimeTestFixture::_bufMgr->createLocalBuffer(device, CAL_FORMAT_DOUBLE_2, width, height);
if (buf1D)
{
vector<double2> cpuBuf(width * height);
util::initializeBuffer(cpuBuf, width, height, 1000, util::RANDOM);
ASSERT_TRUE(buf1D->readData(&cpuBuf[0], static_cast<unsigned long>(cpuBuf.size())));
vector<double2> result;
result.resize(width * height);
ASSERT_TRUE(buf1D->writeData(&result[0], static_cast<unsigned long>(result.size())));
ASSERT_EQ(0, util::compareBuffers(cpuBuf, result, static_cast<unsigned long>(cpuBuf.size())));
_bufMgr->destroyBuffer(buf1D);
}
else
FAIL();
}
| [
"jiawei.ou@1960d7c4-c739-11dd-8829-37334faa441c"
]
| [
[
[
1,
136
]
]
]
|
cc07418fd3e929171199310b9fc2db5a4e779a39 | 0b66a94448cb545504692eafa3a32f435cdf92fa | /tags/0.6/cbear.berlios.de/windows/registry/root.hpp | 7efb665a669917c7b81668e9cb1d80432f7bac6e | [
"MIT"
]
| permissive | BackupTheBerlios/cbear-svn | e6629dfa5175776fbc41510e2f46ff4ff4280f08 | 0109296039b505d71dc215a0b256f73b1a60b3af | refs/heads/master | 2021-03-12T22:51:43.491728 | 2007-09-28T01:13:48 | 2007-09-28T01:13:48 | 40,608,034 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,716 | hpp | /*
The MIT License
Copyright (c) 2005 C Bear (http://cbear.berlios.de)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef CBEAR_BERLIOS_DE_WINDOWS_REGISTRY_ROOT_HPP_INCLUDED
#define CBEAR_BERLIOS_DE_WINDOWS_REGISTRY_ROOT_HPP_INCLUDED
#include <cbear.berlios.de/windows/registry/path.hpp>
namespace cbear_berlios_de
{
namespace windows
{
namespace registry
{
template<class Char>
class root: public path_base<Char, root<Char> >
{
public:
typedef Char char_type;
typedef path_base<char_type, root> base_type;
typedef typename base_type::value_list_type value_list_type;
typedef typename base_type::key_list_type key_list_type;
registry::hkey hkey;
root() {}
explicit root(const registry::hkey &hkey): hkey(hkey) {}
typedef typename base_type::create_options_type create_options_type;
void create(const create_options_type &Options)
{
this->base_type::create(this->hkey, Options);
}
void delete_(const sam &Sam)
{
this->base_type::delete_(this->hkey, Sam);
}
};
template<class Char>
class root_list: public std::vector<root<Char> >
{
public:
typedef Char char_type;
typedef root<char_type> root_type;
root_list &operator()(const root_type &R)
{
this->push_back(R);
return *this;
}
typedef typename root_type::create_options_type create_options_type;
void create(const create_options_type &Options)
{
for(range::sub_range<root_list>::type R(*this); !R.empty(); R.begin()++)
{
R.begin()->create(Options);
}
}
void delete_(const sam &Sam)
{
for(range::sub_range<root_list>::type R(*this); !R.empty(); R.begin()++)
{
R.begin()->delete_(Sam);
}
}
};
}
}
}
#endif
| [
"sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838"
]
| [
[
[
1,
98
]
]
]
|
01c4e9f1c1486f48e5eb2241a82aa23c2dd4f0a0 | 1e01b697191a910a872e95ddfce27a91cebc57dd | /GrfAttachOutputToSocket.h | cd709a6a3cd209a6b982d85630e6e0eb09ad9302 | []
| no_license | canercandan/codeworker | 7c9871076af481e98be42bf487a9ec1256040d08 | a68851958b1beef3d40114fd1ceb655f587c49ad | refs/heads/master | 2020-05-31T22:53:56.492569 | 2011-01-29T19:12:59 | 2011-01-29T19:12:59 | 1,306,254 | 7 | 5 | null | null | null | null | IBM852 | C++ | false | false | 1,628 | h | /* "CodeWorker": a scripting language for parsing and generating text.
Copyright (C) 1996-1997, 1999-2010 CÚdric Lemaire
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
To contact the author: [email protected]
*/
#ifndef _GrfAttachOutputToSocket_h_
#define _GrfAttachOutputToSocket_h_
#include "GrfCommand.h"
namespace CodeWorker {
class ExprScriptExpression;
class GrfAttachOutputToSocket : public GrfCommand {
private:
ExprScriptExpression* _pSocket;
public:
GrfAttachOutputToSocket() : _pSocket(NULL) {}
virtual ~GrfAttachOutputToSocket();
virtual const char* getFunctionName() const { return "attachOutputToSocket"; }
inline void setSocket(ExprScriptExpression* pSocket) { _pSocket = pSocket; }
virtual void compileCpp(CppCompilerEnvironment& theCompilerEnvironment) const;
protected:
virtual SEQUENCE_INTERRUPTION_LIST executeInternal(DtaScriptVariable& visibility);
};
}
#endif
| [
"cedric.p.r.lemaire@28b3f5f3-d42e-7560-b87f-5f53cf622bc4"
]
| [
[
[
1,
49
]
]
]
|
1dc07db111bbf8e49e60ae9279986531d3f0dd2d | de98f880e307627d5ce93dcad1397bd4813751dd | /3libs/ut/include/OXLayoutManager.inl | 6817a696eb69d2c1d60bf930cad83e48f190e7a3 | []
| no_license | weimingtom/sls | 7d44391bc0c6ae66f83ddcb6381db9ae97ee0dd8 | d0d1de9c05ecf8bb6e4eda8a260c7a2f711615dd | refs/heads/master | 2021-01-10T22:20:55.638757 | 2011-03-19T06:23:49 | 2011-03-19T06:23:49 | 44,464,621 | 2 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 2,904 | inl | // ==========================================================================
// Class Specification : COXLayoutManager
// ==========================================================================
// Header file : OXLayoutManager.h
//
// Version: 9.3
//
// This software along with its related components, documentation and files ("The Libraries")
// is © 1994-2007 The Code Project (1612916 Ontario Limited) and use of The Libraries is
// governed by a software license agreement ("Agreement"). Copies of the Agreement are
// available at The Code Project (www.codeproject.com), as part of the package you downloaded
// to obtain this file, or directly from our office. For a copy of the license governing
// this software, you may contact us at [email protected], or by calling 416-849-8900.
//
/////////////////////////////////////////////////////////////////////////////
inline int COXLayoutManager::AddChild(CWnd* pChildWnd,
BOOL bSetDefaultConstraints /* = TRUE */)
{
ASSERT(pChildWnd && pChildWnd->GetDlgCtrlID());
return AddChild(pChildWnd->GetDlgCtrlID(), bSetDefaultConstraints);
}
inline BOOL COXLayoutManager::RemoveChild(CWnd* pChildWnd)
{
ASSERT(pChildWnd && pChildWnd->GetDlgCtrlID());
return RemoveChild(pChildWnd->GetDlgCtrlID());
}
inline BOOL COXLayoutManager::SetConstraint(CWnd* pChildWnd, int nSide, int nType,
int nOffset /* = 0 */, CWnd* pBaseWnd /* = NULL */)
{
ASSERT(pChildWnd && pChildWnd->GetDlgCtrlID());
ASSERT(pBaseWnd == NULL || pBaseWnd->GetDlgCtrlID() != 0);
return SetConstraint(pChildWnd->GetDlgCtrlID(), nSide, nType,
nOffset, pBaseWnd == NULL ? 0 : pBaseWnd->GetDlgCtrlID());
}
inline BOOL COXLayoutManager::SetMinMax(CWnd* pChildWnd, CSize sizeMin,
CSize sizeMax /* = CSize(0,0) */)
{
ASSERT(pChildWnd && pChildWnd->GetDlgCtrlID());
return SetMinMax(pChildWnd->GetDlgCtrlID(), sizeMin, sizeMax);
}
inline BOOL COXLayoutManager::RemoveConstraint(CWnd* pChildWnd, int nSide)
{
ASSERT(pChildWnd && pChildWnd->GetDlgCtrlID());
return RemoveConstraint(pChildWnd->GetDlgCtrlID(), nSide);
}
inline int COXLayoutManager::GetFractionBase() const
{
return m_nBase;
}
inline void COXLayoutManager::SetFractionBase(int nBase)
{
if (nBase) m_nBase = nBase;
}
inline void COXLayoutManager::ResetContainerMinMax()
{
m_cxMin = m_cyMin = -1;
m_cxMax = m_cyMax = 32767;
}
inline BOOL COXLayoutManager::TieChild(CWnd* pChildWnd, int nSide, int nType,
CWnd* pBaseWnd/*=NULL*/)
{
ASSERT(pChildWnd && pChildWnd->GetDlgCtrlID());
ASSERT(pBaseWnd==NULL || pBaseWnd->GetDlgCtrlID()!=0);
return TieChild(pChildWnd->GetDlgCtrlID(),nSide, nType,
pBaseWnd==NULL ? 0 : pBaseWnd->GetDlgCtrlID());
}
inline BOOL COXLayoutManager::IsAttached() const
{
return (m_pContainerWnd!=NULL);
}
// end of OXLayoutManager.inl | [
"[email protected]"
]
| [
[
[
1,
82
]
]
]
|
82476d1180d607e0023cada16ff7ee307db30698 | dbc23fb3b25be43c36e2ebf15097a68a636dbd11 | /src/AbstractGraphWriter.cpp | 1ab82006a18d32eb2f86472181c9039cda3b38bc | []
| no_license | lpenguin/QxEditor-Qt | 1907dd4d36390bb21fdff3951d63fb2610d45ece | b322231ef31f3cb2562fee84ddbe870bb5ad3fd2 | refs/heads/master | 2020-04-06T05:49:11.112763 | 2011-10-13T12:18:29 | 2011-10-13T12:18:29 | 1,254,104 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 36 | cpp | #include "AbstractGraphWriter.h"
| [
"[email protected]"
]
| [
[
[
1,
2
]
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.