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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c0da6a9ff54afcc64417ae0641f9cf11c5d45d53 | 2643a033a379ea2041a9fbbf2d8ed7b916ba59b4 | /DLR_Main/Test/DlrComLibrary/ReturnValues.h | 1a1d75410a6aa8731e5c580d8f2ce43887f6197b | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
]
| permissive | mdavid/dlr | 67349a5ae1ee54c41a0163beea55de14d4cb7e08 | 773f9ae89b08c92023e8c1b929e97a938c941fa0 | refs/heads/master | 2021-01-10T20:50:39.162502 | 2010-08-15T19:39:52 | 2010-08-15T19:39:52 | 859,539 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,828 | h | // ReturnValues.h : Declaration of the CReturnValues
#pragma once
#include "resource.h" // main symbols
#include "DlrComLibrary_i.h"
#if defined(_WIN32_WCE) && !defined(_CE_DCOM) && !defined(_CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA)
#error "Single-threaded COM objects are not properly supported on Windows CE platform, such as the Windows Mobile platforms that do not include full DCOM support. Define _CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA to force ATL to support creating single-thread COM object's and allow use of it's single-threaded COM object implementations. The threading model in your rgs file was set to 'Free' as that is the only threading model supported in non DCOM Windows CE platforms."
#endif
// CReturnValues
class ATL_NO_VTABLE CReturnValues :
public CComObjectRootEx<CComSingleThreadModel>,
public CComCoClass<CReturnValues, &CLSID_ReturnValues>,
public IDispatchImpl<IReturnValues, &IID_IReturnValues, &LIBID_DlrComLibraryLib, /*wMajor =*/ 1, /*wMinor =*/ 0>
{
public:
CReturnValues()
{
}
DECLARE_REGISTRY_RESOURCEID(IDR_RETURNVALUES)
BEGIN_COM_MAP(CReturnValues)
COM_INTERFACE_ENTRY(IReturnValues)
COM_INTERFACE_ENTRY(IDispatch)
END_COM_MAP()
DECLARE_PROTECT_FINAL_CONSTRUCT()
HRESULT FinalConstruct()
{
s_cConstructed++;
return S_OK;
}
void FinalRelease()
{
s_cReleased++;
}
public:
STDMETHOD_(void,mNoRetVal)();
STDMETHOD_(int,mIntRetVal)();
STDMETHOD_(int,mTwoRetVals)(int* a);
STDMETHOD(mNullRefException)();
STDMETHOD(mGenericCOMException)();
static BOOL AllDestructed() { return s_cConstructed == s_cReleased; }
private:
static int s_cConstructed;
static int s_cReleased;
};
OBJECT_ENTRY_AUTO(__uuidof(ReturnValues), CReturnValues)
| [
"SND\\Sesh_cp@9b283d60-5439-405e-af05-b73fd8c4d996"
]
| [
[
[
1,
66
]
]
]
|
51518fad2ba93bf9938dc58d07a6dc8fa212cfd9 | 2b80036db6f86012afcc7bc55431355fc3234058 | /src/contrib/oggdecoder/OGGDecoder.h | 8c3a6a8a5bb47c86f527d55e450556562c9e6550 | [
"BSD-3-Clause"
]
| permissive | leezhongshan/musikcube | d1e09cf263854bb16acbde707cb6c18b09a0189f | e7ca6a5515a5f5e8e499bbdd158e5cb406fda948 | refs/heads/master | 2021-01-15T11:45:29.512171 | 2011-02-25T14:09:21 | 2011-02-25T14:09:21 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 2,721 | h | //////////////////////////////////////////////////////////////////////////////
// Copyright © 2007, mC2 team
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of the author nor the names of other contributors may
// be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////
#pragma once
#include <core/audio/IDecoder.h>
#include "vorbis/codec.h"
#include "vorbis/vorbisfile.h"
using namespace musik::core::audio;
class OGGDecoder : public IDecoder
{
public:
OGGDecoder();
~OGGDecoder();
public:
virtual void Destroy();
virtual double SetPosition(double second,double totalLength);
virtual bool GetBuffer(IBuffer *buffer);
virtual bool Open(musik::core::filestreams::IFileStream *fileStream);
public:
// OGG callbacks
static size_t OggRead(void *buffer, size_t nofParts, size_t partSize, void *datasource);
static int OggSeek(void *datasource, ogg_int64_t offset, int whence);
static long OggTell(void *datasource);
static int OggClose(void *datasource);
protected:
musik::core::filestreams::IFileStream *fileStream;
OggVorbis_File oggFile;
ov_callbacks oggCallbacks;
};
| [
"[email protected]@6a861d04-ae47-0410-a6da-2d49beace72e",
"onnerby@6a861d04-ae47-0410-a6da-2d49beace72e"
]
| [
[
[
1,
32
],
[
35,
35
],
[
42,
42
],
[
44,
66
]
],
[
[
33,
34
],
[
36,
41
],
[
43,
43
],
[
67,
67
]
]
]
|
7c6c3acc3931e3b896d82233f4c4db109460befe | b1892b06513186f2d81560e666e84121421f1754 | /foo_sdk/foobar2000/ATLHelpers/inplace_edit.h | 5008763fb86e1d6b21204e75e7f6d44cb6542693 | [
"MIT"
]
| permissive | anders007/foo_input_amr | 469c98d022d50d5020d74de9f24848088bd686ae | b95a758717e0680b97711c03207dead33befca83 | refs/heads/master | 2021-01-18T17:36:27.834218 | 2009-11-19T22:34:49 | 2009-11-19T22:34:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,560 | h | namespace InPlaceEdit {
enum {
KEditAborted = 0,
KEditTab,
KEditShiftTab,
KEditEnter,
KEditLostFocus,
KEditMaskReason = 0xFF,
KEditFlagContentChanged = 0x100,
KFlagReadOnly = 1 << 0,
KFlagMultiLine = 1 << 1,
KFlagAlignCenter = 1 << 2,
KFlagAlignRight = 1 << 3,
};
void Start(HWND p_parentwnd,const RECT & p_rect,bool p_multiline,pfc::rcptr_t<pfc::string_base> p_content,completion_notify_ptr p_notify);
void StartEx(HWND p_parentwnd,const RECT & p_rect,unsigned p_flags,pfc::rcptr_t<pfc::string_base> p_content,completion_notify_ptr p_notify);
void Start_FromListView(HWND p_listview,unsigned p_item,unsigned p_subitem,unsigned p_linecount,pfc::rcptr_t<pfc::string_base> p_content,completion_notify_ptr p_notify);
void Start_FromListViewEx(HWND p_listview,unsigned p_item,unsigned p_subitem,unsigned p_linecount,unsigned p_flags,pfc::rcptr_t<pfc::string_base> p_content,completion_notify_ptr p_notify);
bool TableEditAdvance(unsigned & p_item,unsigned & p_column, unsigned p_item_count,unsigned p_column_count, unsigned p_whathappened);
bool TableEditAdvance_ListView(HWND p_listview,unsigned p_column_base,unsigned & p_item,unsigned & p_column, unsigned p_item_count,unsigned p_column_count, unsigned p_whathappened);
class CTableEditHelper {
public:
void TableEdit_Start(HWND p_listview,unsigned p_item,unsigned p_column,unsigned p_itemcount,unsigned p_columncount,unsigned p_basecolumn,unsigned p_flags = 0) {
if (m_notify.is_valid() || p_columncount == 0 || p_itemcount == 0 || p_item >= p_itemcount || p_column >= p_columncount) return;
m_listview = p_listview;
m_item = p_item;
m_column = p_column;
m_itemcount = p_itemcount;
m_columncount = p_columncount;
m_basecolumn = p_basecolumn;
m_flags = p_flags;
__Start();
}
void TableEdit_Abort(bool p_forwardcontent) {
if (m_notify.is_valid()) {
m_notify->orphan();
m_notify.release();
if (p_forwardcontent && (m_flags & KFlagReadOnly) == 0) {
if (m_content.is_valid()) {
pfc::string8 temp(*m_content);
m_content.release();
TableEdit_SetItemText(m_item,m_column,temp);
}
} else {
m_content.release();
}
SetFocus(NULL);
TableEdit_Finished();
}
}
bool TableEdit_IsActive() const {
return m_notify.is_valid();
}
virtual bool TableEdit_GetItemText(unsigned p_item,unsigned p_column,pfc::string_base & p_out,unsigned & p_linecount) {
listview_helper::get_item_text(m_listview,p_item,p_column + m_basecolumn,p_out);
p_linecount = pfc::is_multiline(p_out) ? 5 : 1;
return true;
}
virtual void TableEdit_SetItemText(unsigned p_item,unsigned p_column,const char * p_text) {
listview_helper::set_item_text(m_listview,p_item,p_column + m_basecolumn,p_text);
}
virtual void TableEdit_Finished() {}
void on_task_completion(unsigned p_taskid,unsigned p_state) {
if (p_taskid == KTaskID) {
m_notify.release();
if (m_content.is_valid()) {
if (p_state & InPlaceEdit::KEditFlagContentChanged) {
TableEdit_SetItemText(m_item,m_column,*m_content);
}
m_content.release();
}
/*if (InPlaceEdit::TableEditAdvance(m_item,m_column,m_itemcount,m_columncount,p_state))*/
if (TableEdit_OnEditCompleted(m_item,m_column,p_state) &&
InPlaceEdit::TableEditAdvance_ListView(m_listview,m_basecolumn,m_item,m_column,m_itemcount,m_columncount,p_state)) {
__Start();
} else {
TableEdit_Finished();
}
}
}
~CTableEditHelper() {
if (m_notify.is_valid()) {
m_notify->orphan();
m_notify.release();
}
}
protected:
HWND TableEdit_GetListView() const {return m_listview;}
//return false to abort
virtual bool TableEdit_OnEditCompleted(unsigned item,unsigned column,unsigned state) {return true;}
private:
void __Start() {
listview_helper::select_single_item(m_listview,m_item);
m_content.new_t();
unsigned linecount = 1;
if (!TableEdit_GetItemText(m_item,m_column,*m_content,linecount)) return;
m_notify = completion_notify_create(this,KTaskID);
InPlaceEdit::Start_FromListViewEx(m_listview,m_item,m_column+m_basecolumn,linecount,m_flags,m_content,m_notify);
}
enum {
KTaskID = 0xc0ffee
};
HWND m_listview;
unsigned m_item,m_column;
unsigned m_itemcount,m_columncount,m_basecolumn;
unsigned m_flags;
pfc::rcptr_t<pfc::string8> m_content;
service_ptr_t<completion_notify_orphanable> m_notify;
};
}
| [
"[email protected]"
]
| [
[
[
1,
128
]
]
]
|
2999cdbb080b1572e57aa8be9cf86c5ce139350b | 7347ab0d3daab6781af407d43ac29243daeae438 | /src/graphics/node.h | 3c53d2acd936b83bfd9050cfc2c540b1fb6a16e0 | []
| no_license | suprafun/smalltowns | e096cdfc11e329674a7f76486452f4cd58ddaace | c722da7dd3a1d210d07f22a6c322117b540e63da | refs/heads/master | 2021-01-10T03:09:47.664318 | 2011-06-03T01:22:29 | 2011-06-03T01:22:29 | 50,808,558 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,408 | h | /*********************************************
*
* Author: David Athay
*
* License: New BSD License
*
* Copyright (c) 2008, CT Games
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of CT Games nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*
*
* Date of file creation: 08-09-20
*
* $Id$
*
********************************************/
/**
* The node class is used by everything that will be displayed on screen
*/
#ifndef ST_NODE_HEADER
#define ST_NODE_HEADER
#include <map>
#include <string>
#include "../utilities/types.h"
namespace ST
{
class Texture;
class Animation;
class Node
{
private:
/**
* Default constructor
* Not to be used
*/
Node();
public:
/**
* Constructor
* @param name The name of the node
* @param texture The name of the texture
*/
Node(std::string name, Texture *texture);
virtual ~Node();
/**
* Get Position
* @return Returns the position of the node
*/
Point& getPosition();
Point getTilePosition();
/**
* Get Width
* @return Returns the width of the node
*/
const int getWidth() const;
/**
* Get Height
* @return Returns the height of the node
*/
const int getHeight() const;
/**
* Get Anchor
* @return Returns the start of the node's image
*/
const int getAnchor() const;
/**
* Set Anchor
* @param anchor The start of the node's image
*/
void setAnchor(int anchor);
/**
* Get Bounds
* @return Returns a rectangle with the position, and size
*/
Rectangle& getBounds();
/**
* Get Visible
* @return Returns if the node is visible
*/
bool getVisible() const;
/**
* Set Visible
* @param visible Sets if the node will be drawn
*/
void setVisible(bool visible);
/**
* Get Blocking
* @return Returns if the node blocks
*/
bool getBlocking() const { return mBlocking; }
/**
* Set Blocking
* @param blocks Sets whether to block
*/
void setBlocking(bool blocks) { mBlocking = blocks; }
/**
* Move Node
* Moves the node to a new position
* @param position The new position for the node to be
*/
virtual void moveNode(Point *position);
/**
* Get GL Texture
* @return Returns the GL Texture for drawing
*/
virtual Texture* getTexture();
/**
* Toggle Name
* Toggles whether the name of the node is shown
*/
void toggleName();
/**
* Show Name
* Returns whether to show the name
*/
bool showName();
/**
* Get Name
* Returns the name of the node
*/
std::string getName() const;
/**
* Logic
* Called every frame
*/
virtual void logic(int ms);
protected:
std::string mName;
Texture *mTexture;
Point mPosition;
Rectangle mBounds;
int mWidth;
int mHeight;
int mAnchor;
bool mVisible;
bool mShowName;
bool mBlocking;
};
class AnimatedNode : public Node
{
public:
AnimatedNode(const std::string &name, Texture *texture);
virtual ~AnimatedNode();
/**
* Get current frame
* Returns the texture of the current frame
*/
Texture* getTexture();
/**
* Set animation
*/
virtual void setAnimation(const std::string &name);
/**
* Turn Node
* Changes the direction the node faces
*/
virtual void turnNode(int direction);
/**
* Logic function
* Called every frame
*/
virtual void logic(int ms);
protected:
Animation *mSetAnimation;
int mUpdateTime;
int mTimeSinceLastUpdate;
int mDirection;
};
}
#endif
| [
"ko2fan@2ae5cb60-8703-11dd-9899-c7ba65f7c4c7"
]
| [
[
[
1,
222
]
]
]
|
42d99a8a6de44540b487a957a4b663eebbf68a9a | d2996420f8c3a6bbeef63a311dd6adc4acc40436 | /src/net/UdpClient.h | b984e66a8a28e6607218928654973f06522d6cd2 | []
| no_license | aruwen/graviator | 4d2e06e475492102fbf5d65754be33af641c0d6c | 9a881db9bb0f0de2e38591478429626ab8030e1d | refs/heads/master | 2021-01-19T00:13:10.843905 | 2011-03-13T13:15:25 | 2011-03-13T13:15:25 | 32,136,578 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,540 | h | //*********************************************************
// Graviator - QPT2a - FH Salzburg
// Stefan Ebner - Malte Langkabel - Christian Winkler
//
// ClientHUDGame
// Manages the ingame HUD
//
//*********************************************************
#ifndef UDP_CLIENT_H
#define UDP_CLIENT_H
#include "UdpSocket.h"
#include "UdpConnection.h"
#include "MulticastSender.h"
#include "..\GraviatorSimpleTypes.h"
#include "..\Timer.h"
#include <queue>
using namespace std;
namespace net
{
class UdpClient
{
public:
UdpClient();
~UdpClient();
bool start( unsigned short port );
bool isRunning();
void connect( const Address &address );
void connectToFirstResponingServer();
bool isConnected();
bool hasConnectFailed();
bool isDisconnected();
void disconnect();
void stop();
unsigned int getId();
bool send( string data );
void update();
string getData();
queue<string> getDataQueue();
private:
UdpSocket mSocket;
MulticastSender mMulticastSender;
UdpConnection mConnection;
bool mIsSearchingForServer;
Timer mSearchingIntervalTimer;
Timer mSearchingTimeoutTimer;
float mSearchingInterval;
float mSearchingTimeout;
bool mIsRunning;
void processReadReady();
};
}
#endif | [
"[email protected]@c8d5bfcc-1391-a108-90e5-e810ef6ef867"
]
| [
[
[
1,
66
]
]
]
|
51c27040eec0463a724256748804972506edc306 | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/Dependencies/Xerces/include/xercesc/util/regx/UnicodeRangeFactory.cpp | c13413e05fb00264b5af6f99d33deb14343ba384 | []
| no_license | svn2github/ngene | b2cddacf7ec035aa681d5b8989feab3383dac012 | 61850134a354816161859fe86c2907c8e73dc113 | refs/heads/master | 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,908 | cpp | /*
* Copyright 2001-2002,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: UnicodeRangeFactory.cpp 191054 2005-06-17 02:56:35Z jberry $
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/regx/UnicodeRangeFactory.hpp>
#include <xercesc/util/regx/TokenFactory.hpp>
#include <xercesc/util/regx/RangeToken.hpp>
#include <xercesc/util/regx/RangeTokenMap.hpp>
#include <xercesc/util/regx/RegxDefs.hpp>
#include <xercesc/util/regx/XMLUniCharacter.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Local data
// ---------------------------------------------------------------------------
const int UNICATEGSIZE = 37;
const unsigned short CHAR_LETTER = 30;
const unsigned short CHAR_MARK = 31;
const unsigned short CHAR_NUMBER = 32;
const unsigned short CHAR_SEPARATOR = 33;
const unsigned short CHAR_OTHER = 34;
const unsigned short CHAR_PUNCTUATION = 35;
const unsigned short CHAR_SYMBOL = 36;
const XMLCh uniCategNames[][UNICATEGSIZE] =
{
{chLatin_C, chLatin_n, chNull},
{chLatin_L, chLatin_u, chNull},
{chLatin_L, chLatin_l, chNull},
{chLatin_L, chLatin_t, chNull},
{chLatin_L, chLatin_m, chNull},
{chLatin_L, chLatin_o, chNull},
{chLatin_M, chLatin_n, chNull},
{chLatin_M, chLatin_e, chNull},
{chLatin_M, chLatin_c, chNull},
{chLatin_N, chLatin_d, chNull},
{chLatin_N, chLatin_l, chNull},
{chLatin_N, chLatin_o, chNull},
{chLatin_Z, chLatin_s, chNull},
{chLatin_Z, chLatin_l, chNull},
{chLatin_Z, chLatin_p, chNull},
{chLatin_C, chLatin_c, chNull},
{chLatin_C, chLatin_f, chNull},
{chLatin_C, chLatin_o, chNull},
{chLatin_C, chLatin_s, chNull},
{chLatin_P, chLatin_d, chNull},
{chLatin_P, chLatin_s, chNull},
{chLatin_P, chLatin_e, chNull},
{chLatin_P, chLatin_c, chNull},
{chLatin_P, chLatin_o, chNull},
{chLatin_S, chLatin_m, chNull},
{chLatin_S, chLatin_c, chNull},
{chLatin_S, chLatin_k, chNull},
{chLatin_S, chLatin_o, chNull},
{chLatin_P, chLatin_i, chNull},
{chLatin_P, chLatin_f, chNull},
{chLatin_L, chNull},
{chLatin_M, chNull},
{chLatin_N, chNull},
{chLatin_Z, chNull},
{chLatin_C, chNull},
{chLatin_P, chNull},
{chLatin_S, chNull},
};
// ---------------------------------------------------------------------------
// UnicodeRangeFactory: Constructors and Destructor
// ---------------------------------------------------------------------------
UnicodeRangeFactory::UnicodeRangeFactory()
{
}
UnicodeRangeFactory::~UnicodeRangeFactory() {
}
// ---------------------------------------------------------------------------
// UnicodeRangeFactory: Range creation methods
// ---------------------------------------------------------------------------
void UnicodeRangeFactory::buildRanges(RangeTokenMap *rangeTokMap) {
if (fRangesCreated)
return;
if (!fKeywordsInitialized) {
initializeKeywordMap(rangeTokMap);
}
TokenFactory* tokFactory = rangeTokMap->getTokenFactory();
RangeToken* ranges[UNICATEGSIZE];
RangeToken* tok;
for (int i=0; i < UNICATEGSIZE; i++) {
ranges[i] = tokFactory->createRange();
}
for (int j=0; j < 0x10000; j++) {
unsigned short charType = XMLUniCharacter::getType(j);
ranges[charType]->addRange(j, j);
charType = getUniCategory(charType);
ranges[charType]->addRange(j, j);
}
ranges[XMLUniCharacter::UNASSIGNED]->addRange(0x10000, Token::UTF16_MAX);
for (int k=0; k < UNICATEGSIZE; k++) {
tok = (RangeToken*) RangeToken::complementRanges(ranges[k], tokFactory);
// build the internal map.
tok->createMap();
rangeTokMap->setRangeToken(uniCategNames[k], ranges[k]);
rangeTokMap->setRangeToken(uniCategNames[k], tok , true);
}
// Create all range
tok = tokFactory->createRange();
tok->addRange(0, Token::UTF16_MAX);
// build the internal map.
tok->createMap();
rangeTokMap->setRangeToken(fgUniAll, tok);
// Create alpha range
tok = tokFactory->createRange();
tok->mergeRanges(ranges[XMLUniCharacter::UPPERCASE_LETTER]);
tok->mergeRanges(ranges[XMLUniCharacter::LOWERCASE_LETTER]);
tok->mergeRanges(ranges[XMLUniCharacter::OTHER_LETTER]);
// build the internal map.
tok->createMap();
rangeTokMap->setRangeToken(fgUniIsAlpha, tok);
// Create alpha-num range
RangeToken* alnumTok = tokFactory->createRange();
alnumTok->mergeRanges(tok);
alnumTok->mergeRanges(ranges[XMLUniCharacter::DECIMAL_DIGIT_NUMBER]);
// build the internal map.
alnumTok->createMap();
rangeTokMap->setRangeToken(fgUniIsAlnum, alnumTok);
// Create word range
tok = tokFactory->createRange();
tok->mergeRanges(alnumTok);
tok->addRange(chUnderscore, chUnderscore);
// build the internal map.
tok->createMap();
rangeTokMap->setRangeToken(fgUniIsWord, tok);
tok = (RangeToken*) RangeToken::complementRanges(tok, tokFactory);
// build the internal map.
tok->createMap();
rangeTokMap->setRangeToken(fgUniIsWord, tok , true);
// Create assigned range
tok = (RangeToken*)RangeToken::complementRanges(
ranges[XMLUniCharacter::UNASSIGNED],
tokFactory,
tokFactory->getMemoryManager());
// build the internal map.
tok->createMap();
rangeTokMap->setRangeToken(fgUniAssigned,tok);
// Create space range
tok = tokFactory->createRange();
tok->mergeRanges(ranges[XMLUniCharacter::SPACE_SEPARATOR]);
tok->mergeRanges(ranges[XMLUniCharacter::LINE_SEPARATOR]);
//tok->mergeRanges(ranges[XMLUniCharacter::PARAGRAPH_SEPARATOR]);
// build the internal map.
tok->createMap();
rangeTokMap->setRangeToken(fgUniIsSpace, tok);
tok = (RangeToken*) RangeToken::complementRanges(tok, tokFactory);
// build the internal map.
tok->createMap();
rangeTokMap->setRangeToken(fgUniIsSpace, tok , true);
// build the internal maps.
for (int l=0; l < UNICATEGSIZE; l++) {
ranges[l]->createMap();
}
fRangesCreated = true;
}
// ---------------------------------------------------------------------------
// UnicodeRangeFactory: Initialization methods
// ---------------------------------------------------------------------------
void UnicodeRangeFactory::initializeKeywordMap(RangeTokenMap *rangeTokMap) {
if (fKeywordsInitialized)
return;
for (int k=0; k < UNICATEGSIZE; k++) {
rangeTokMap->addKeywordMap(uniCategNames[k], fgUnicodeCategory);
}
rangeTokMap->addKeywordMap(fgUniAll, fgUnicodeCategory);
rangeTokMap->addKeywordMap(fgUniIsAlpha, fgUnicodeCategory);
rangeTokMap->addKeywordMap(fgUniIsAlnum, fgUnicodeCategory);
rangeTokMap->addKeywordMap(fgUniIsWord, fgUnicodeCategory);
rangeTokMap->addKeywordMap(fgUniAssigned, fgUnicodeCategory);
rangeTokMap->addKeywordMap(fgUniIsSpace, fgUnicodeCategory);
fKeywordsInitialized = true;
}
// ---------------------------------------------------------------------------
// UnicodeRangeFactory: Helper methods
// ---------------------------------------------------------------------------
unsigned short UnicodeRangeFactory::getUniCategory(const unsigned short type)
{
switch(type) {
case XMLUniCharacter::UPPERCASE_LETTER:
case XMLUniCharacter::LOWERCASE_LETTER:
case XMLUniCharacter::TITLECASE_LETTER:
case XMLUniCharacter::MODIFIER_LETTER:
case XMLUniCharacter::OTHER_LETTER:
return CHAR_LETTER;
case XMLUniCharacter::NON_SPACING_MARK:
case XMLUniCharacter::COMBINING_SPACING_MARK:
case XMLUniCharacter::ENCLOSING_MARK:
return CHAR_MARK;
case XMLUniCharacter::DECIMAL_DIGIT_NUMBER:
case XMLUniCharacter::LETTER_NUMBER:
case XMLUniCharacter::OTHER_NUMBER:
return CHAR_NUMBER;
case XMLUniCharacter::SPACE_SEPARATOR:
case XMLUniCharacter::LINE_SEPARATOR:
case XMLUniCharacter::PARAGRAPH_SEPARATOR:
return CHAR_SEPARATOR;
case XMLUniCharacter::CONTROL:
case XMLUniCharacter::FORMAT:
case XMLUniCharacter::SURROGATE:
case XMLUniCharacter::PRIVATE_USE:
case XMLUniCharacter::UNASSIGNED:
return CHAR_OTHER;
case XMLUniCharacter::CONNECTOR_PUNCTUATION:
case XMLUniCharacter::DASH_PUNCTUATION:
case XMLUniCharacter::START_PUNCTUATION:
case XMLUniCharacter::END_PUNCTUATION:
case XMLUniCharacter::OTHER_PUNCTUATION:
case XMLUniCharacter::INITIAL_PUNCTUATION:
case XMLUniCharacter::FINAL_PUNCTUATION:
return CHAR_PUNCTUATION;
case XMLUniCharacter::MATH_SYMBOL:
case XMLUniCharacter::CURRENCY_SYMBOL:
case XMLUniCharacter::MODIFIER_SYMBOL:
case XMLUniCharacter::OTHER_SYMBOL:
return CHAR_SYMBOL;
}
return 0;
}
XERCES_CPP_NAMESPACE_END
/**
* End of file UnicodeRangeFactory.cpp
*/
| [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
]
| [
[
[
1,
278
]
]
]
|
be5958118b6f5d8a2d07b4822e498119cfeaf7e2 | 975e3cacad2b513dff73ddd5ce3d449ad40c293b | /babel-2014-minett_a/trunk/lib-build-desktop-Qt_4_7_4_for_Desktop_-_MinGW_4_4__Qt_SDK__Debug/ui_mainwindow.h | c0d294961bbb1fca7b51d0c0d43dc3ef8f912385 | []
| no_license | alex-min/babelroxor | 08a2babfbd1cf51dcfcba589d9acc7afcebee6e3 | 53cbdedd7d4b68943fe99d74dbb5443b799cca05 | refs/heads/master | 2021-01-10T14:24:12.257931 | 2011-12-13T10:57:30 | 2011-12-13T10:57:30 | 46,981,346 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,233 | h | /********************************************************************************
** Form generated from reading UI file 'mainwindow.ui'
**
** Created: Wed 9. Nov 19:57:42 2011
** by: Qt User Interface Compiler version 4.7.4
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_MAINWINDOW_H
#define UI_MAINWINDOW_H
#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QHeaderView>
#include <QtGui/QMainWindow>
#include <QtGui/QMenuBar>
#include <QtGui/QStatusBar>
#include <QtGui/QToolBar>
#include <QtGui/QWidget>
QT_BEGIN_NAMESPACE
class Ui_MainWindow
{
public:
QMenuBar *menuBar;
QToolBar *mainToolBar;
QWidget *centralWidget;
QStatusBar *statusBar;
void setupUi(QMainWindow *MainWindow)
{
if (MainWindow->objectName().isEmpty())
MainWindow->setObjectName(QString::fromUtf8("MainWindow"));
MainWindow->resize(400, 300);
menuBar = new QMenuBar(MainWindow);
menuBar->setObjectName(QString::fromUtf8("menuBar"));
MainWindow->setMenuBar(menuBar);
mainToolBar = new QToolBar(MainWindow);
mainToolBar->setObjectName(QString::fromUtf8("mainToolBar"));
MainWindow->addToolBar(mainToolBar);
centralWidget = new QWidget(MainWindow);
centralWidget->setObjectName(QString::fromUtf8("centralWidget"));
MainWindow->setCentralWidget(centralWidget);
statusBar = new QStatusBar(MainWindow);
statusBar->setObjectName(QString::fromUtf8("statusBar"));
MainWindow->setStatusBar(statusBar);
retranslateUi(MainWindow);
QMetaObject::connectSlotsByName(MainWindow);
} // setupUi
void retranslateUi(QMainWindow *MainWindow)
{
MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", 0, QApplication::UnicodeUTF8));
} // retranslateUi
};
namespace Ui {
class MainWindow: public Ui_MainWindow {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_MAINWINDOW_H
| [
"[email protected]"
]
| [
[
[
1,
70
]
]
]
|
f6f2b589b15b01d74c7152cf74ca591057b83a72 | 828b587f277322b12aeb5bb578a926aa108e56b9 | /cpp/Foraging/Foraging/tests.cpp | d53f0eb8d19d12d7aa8e0f932926fa160237d465 | []
| no_license | gmarcotte/marcotte-autobot | 2f20870b28cd9bfba2602d7f9958877d7c3882df | f150a76b91a70af919af7b51e2a2221089c52cd3 | refs/heads/master | 2016-09-06T18:19:37.756914 | 2010-05-05T12:18:02 | 2010-05-05T12:18:02 | 32,219,928 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,569 | cpp | #include <iostream>
#include <utils.hpp>
#include <environment.hpp>
using namespace std;
void testConePlaneIntersect()
{
// Define the cone
double coneOrg[3] = {0.762, -3.219, 6.212};
double coneDir[3] = {-.213, .459, -.71};
double coneAngle = 0.1467;
// Define the plane
double planeOrg[3] = {-1.271, 3.929, .789};
double planeDir1[3] = {1.2, 2.4, -1.9};
double planeDir2[3] = {-3.2, 1.69, 0.828};
double* ellipse = new double[5];
conePlaneIntersection(coneOrg, coneDir, coneAngle, planeOrg, planeDir1, planeDir2, ellipse);
cout << "Ellipse translated by (" << ellipse[0] << ", " << ellipse[1] << ")" << endl;
cout << "Axes are: (" << ellipse[2] << ", " << ellipse[3] << endl;
cout << "Rotation is: " << ellipse[4] << " radians." << endl;
delete [] ellipse;
}
void testDiscreteTarget()
{
double rewards[2] = {0.0, 8.0};
double probs[2] = {0.3, 0.7};
DiscreteTarget* dt = new DiscreteTarget(2, probs, rewards, RED);
int count[2] = {0, 0};
int num_runs = 1000;
for (int i=0; i<num_runs; i++)
{
double r = dt->Payout();
//printf("Payout: %f\n", r);
if (r == 0.0)
count[0]++;
else if (r == 8.0)
count[1]++;
else
printf("Error: Got invalid reward\n");
}
printf("Target Type: %c\n", dt->AsChar());
printf("After %d runs, got %d 0.0 rewards and %d 8.0 rewards\n", num_runs, count[0], count[1]);
delete dt;
}
void testField()
{
double reward = 2.0;
Field* f = new Field(10, 20, 10.0);
int clr;
for (int i=0; i<10; i++)
{
for (int j=0; j<20; j++)
{
clr = f->GetIndex(i, j) % 3;
f->AddTarget(i, j, new ConstantTarget(reward, (COLOR)clr));
}
}
printf(f->AsString());
delete f;
}
void testBasicBinaryField()
{
int N = 50;
double nPct = .1;
double rPct = .6;
double rRwd = 14.0;
double rPrb = 0.2;
double bPct = 0.3;
double bRwd = 8.0;
double bPrb = 0.9;
BasicBinaryField* bbf = new BasicBinaryField(N, nPct, rPct, rRwd, rPrb, bPct, bRwd, bPrb);
//printf(bbf->AsString());
printf("Red: %d, Blue: %d, Gray: %d\n", bbf->NumRed(), bbf->NumBlue(), bbf->NumNeutral());
printf("Expected Payout: %f\n", rPct*rRwd*rPrb + bPct*bRwd*bPrb);
double payout = 0.0;
gsl_rng* rng = gsl_rng_alloc(gsl_rng_default);
int trials = 1000000;
for (int i=0; i<trials; i++)
{
int row = gsl_rng_uniform_int(rng, N);
int col = gsl_rng_uniform_int(rng, N);
payout += bbf->Sample(row, col);
}
double mean = payout / (double)trials;
printf("Actual Mean Payout: %f\n", mean);
gsl_rng_free(rng);
delete bbf;
}
| [
"garrett.marcotte@3fdf3676-2bb9-11df-973c-b9695237dc37"
]
| [
[
[
1,
98
]
]
]
|
2dfbaaf98773b3e039eb4f5607d889600b37c09d | c3a0cf3d0c023cbdb9a1ab8295aa1231543d83e7 | /sln/src/GLTgaImage.h | 3327a402b60fdbb6d5ea7357379d458f00a723f6 | []
| no_license | yakergong/seedcup2008 | 2596cdb5fe404ef8628366cdd2f8003141625264 | e57b92cf576900ba6cb5e0c0f6661bba3e7f75d7 | refs/heads/master | 2016-09-05T11:06:12.717346 | 2008-12-19T13:04:28 | 2008-12-19T13:04:28 | 32,268,668 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,616 | h | /*
* Falling Block Game
* Copyright (C) 1999-2002 Jared Krinke <http://derajdezine.vze.com/>
*
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 or (at your option) any later version
* as published by the Free Software Foundation.
*
* This application 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 distribution; if not, write to:
* Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA02111-1307 USA
*
* Jared Krinke
*
* Deraj DeZine
* http://derajdezine.vze.com/
*/
#ifndef GLTGAIMAGE_H
#define GLTGAIMAGE_H
#include <windows.h>
#include <GL/gl.h>
#include <physfs/physfs.h>
static GLubyte standardTGAHeader[12] = { 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
class GLTgaImage
{
public:
bool loadTGAImage(PHYSFS_file * file);
GLTgaImage *splitImageMap(int mapWidth, int mapHeight, int maxImages = 0);
bool cropImage(int newX, int newY, int newWidth, int newHeight);
void makeClamped();
// Accessors
GLubyte *getImageData()
{
return imageData;
}
GLubyte *getImageData(GLuint seek)
{
return &imageData[seek];
}
GLuint getBitsPerPixel()
{
return bpp;
}
GLuint getBytesPerPixel()
{
return bpp / 8;
}
GLuint getWidth()
{
return width;
}
GLuint getHeight()
{
return height;
}
GLuint getID()
{
return texID;
}
GLuint *getIDPointer()
{
return &texID;
}
void setImageData(GLubyte * newVar)
{
imageData = newVar;
}
void setImageData(GLubyte * newVar, GLuint seek)
{
imageData[seek] = newVar[0];
}
void setBitsPerPixel(GLuint newVar)
{
bpp = newVar;
}
void setBytesPerPixel(GLuint newVar)
{
bpp = newVar * 8;
}
void setWidth(GLuint newVar)
{
width = newVar;
}
void setHeight(GLuint newVar)
{
height = newVar;
}
// Initialization
~GLTgaImage();
private:
GLubyte * imageData;
GLuint bpp;
GLuint width;
GLuint height;
GLuint texID;
};
#endif
| [
"yakergong@c3067968-ca50-11dd-8ca8-e3ff79f713b6"
]
| [
[
[
1,
112
]
]
]
|
02a99e7ccba08ec072cf37521bdf6dbd29933f69 | 1ad310fc8abf44dbcb99add43f6c6b4c97a3767c | /samples_c++/cc/sprite_devl/App.cc | a14b16ecd61b6cf9864721a23994cb84fd5f8de5 | []
| no_license | Jazzinghen/spamOSEK | fed44979b86149809f0fe70355f2117e9cb954f3 | 7223a2fb78401e1d9fa96ecaa2323564c765c970 | refs/heads/master | 2020-06-01T03:55:48.113095 | 2010-05-19T14:37:30 | 2010-05-19T14:37:30 | 580,640 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 4,955 | cc | #include "App.h"
#ifndef _MSC_VER
//the sprite graphics frames
extern const char shiki_intro_spr_start[];
extern const char shiki_walkforward_spr_start[];
extern const char shiki_taunt_spr_start[];
extern const char shiki_breathe_spr_start[];
extern const char nxtOSEK_spr_start[];
extern const char rocks_spr_start[];
extern const char backdrop_spr_start[];
#else
#include <iostream>
#include <fstream>
#include <string>
char *shiki_intro_spr_start;
char *shiki_walkforward_spr_start;
char *shiki_taunt_spr_start;
char *shiki_breathe_spr_start;
char *nxtOSEK_spr_start;
char *rocks_spr_start;
char *backdrop_spr_start;
char *sqr_spr_start;
#pragma warning (disable : 4309)
using namespace std;
#endif
//the set of all of the sprites
const char* shikiDataSet[] =
{
shiki_intro_spr_start,
shiki_walkforward_spr_start,
shiki_taunt_spr_start,
shiki_breathe_spr_start,
};
//the animation indexes and timing
#ifndef _MSC_VER
//anim command come in pairs of 2 (frame number, time in 20msec) or (anim command, parameter)
const char shikiAppearAnim[] = {0,3,1,3,2,3,3,3,4,3,5,3,254,0};
const char shikiWalkAnim[] = {0,3,1,3,2,3,3,3,4,3,5,3,253,1,0,3,1,3,2,3,3,3,4,3,5,3,255,0};
const char shikiTauntAnim[] = {0,3,1,3,2,3,0,3,1,3,2,3,0,3,1,3,2,3,0,3,1,3,2,3,0,3,1,3,2,3,255,0};
const char shikiBreatheAnim[] = {0,3,1,3,2,3,3,3,4,3,5,3,6,3,7,3,8,3,255,0};
#else
const char shikiAppearAnim[] = {0,60,1,60,2,60,3,60,4,60,5,60,254,0};
const char shikiWalkAnim[] = {0,60,1,60,2,60,3,60,4,60,5,60,253,1,0,60,1,60,2,60,3,60,4,60,5,60,255,0};
const char shikiTauntAnim[] = {0,60,1,60,2,60,0,60,1,60,2,60,0,60,1,60,2,60,0,60,1,60,2,60,0,60,1,60,2,60,255,0};
const char shikiBreatheAnim[] = {0,60,1,60,2,60,3,60,4,60,5,60,6,60,7,60,8,60,255,0};
#endif
const char nxtLogoAnim[] = {0, 1, 252,0, 255, 0};
const char rocksAnim[] = {0, 1, 252,0, 255, 0};
//the set of all animations for shiki since we'll be chaining them together
const char* shikiAnimset[] =
{
shikiAppearAnim,
shikiWalkAnim,
shikiTauntAnim,
shikiBreatheAnim
};
#ifdef _MSC_VER
static char* loadAnim(const std::string path)
{
ifstream file (path.c_str(), ios::in|ios::binary|ios::ate);
if (file.is_open())
{
int size = file.tellg();
char *memblock = new char [size];
file.seekg (0, ios::beg);
file.read (memblock, size);
file.close();
return memblock;
}
return NULL;
}
#endif
char spriteRoot[] = "C:\\Users\\Jon\\Documents\\nxtOSEK\\samples\\sprite\\";
App::App()
: mCurrentAnim(0)
#ifndef _MSC_VER
, mShiki(shikiDataSet[0], shikiAnimset[0])
, mNxtOsek(nxtOSEK_spr_start, nxtLogoAnim)
, mRocks(rocks_spr_start, rocksAnim)
, mBackDrop(backdrop_spr_start, (const char*)null)
#endif
{
#ifdef _MSC_VER
shikiDataSet[0] = loadAnim(std::string(spriteRoot) + std::string("shiki_intro.spr"));
shikiDataSet[1] = loadAnim(std::string(spriteRoot) + std::string("shiki_walkforward.spr"));
shikiDataSet[2] = loadAnim(std::string(spriteRoot) + std::string("shiki_taunt.spr"));
shikiDataSet[3] = loadAnim(std::string(spriteRoot) + std::string("shiki_breathe.spr"));
nxtOSEK_spr_start = loadAnim(std::string(spriteRoot) + std::string("nxtOSEK.spr"));
rocks_spr_start = loadAnim(std::string(spriteRoot) + std::string("rocks.spr"));
backdrop_spr_start = loadAnim(std::string(spriteRoot) + std::string("backdrop.spr"));
mBackDrop.changeGfx(backdrop_spr_start, 0);
mShiki.changeGfx(shikiDataSet[0], shikiAnimset[0]);
mNxtOsek.changeGfx(nxtOSEK_spr_start, nxtLogoAnim);
mRocks.changeGfx(rocks_spr_start, rocksAnim);
mSqr.changeGfx(sqr_spr_start, NULL);
#endif
mShiki.setScriptInterface(this);
mShiki.setID(eSprite_Shiki);
mNxtOsek.setID(eSprite_NXTLogo);
mNxtOsek.setScriptInterface(this);
mRocks.setID(eSprite_Rocks);
mRocks.setScriptInterface(this);
}
void App::init()
{
mScreen.newSprite(&mBackDrop);
mScreen.newSprite(&mShiki);
mScreen.newSprite(&mNxtOsek);
mScreen.newSprite(&mRocks);
}
//run animation actions on the sprites as they call new commands
void App::animCommand(Sprite *sprite, int command)
{
switch(sprite->getID())
{
case eSprite_Shiki:
runShikiAnim(sprite, command);
break;
case eSprite_NXTLogo:
runNXTLogo(sprite, command);
break;
case eSprite_Rocks:
runRocks(sprite, command);
break;
}
}
void App::runRocks(Sprite *sprite, int command)
{
if(command == Sprite::eAnimCommand_Move /*&& mTimer.tick()*/)
{
sprite->moveBy(VectorT<S8>(1, 0));
}
}
void App::runShikiAnim(Sprite *sprite, int command)
{
if(++mCurrentAnim == 4)
{
mCurrentAnim = 0;
}
sprite->changeGfx(shikiDataSet[mCurrentAnim], shikiAnimset[mCurrentAnim]);
}
void App::runNXTLogo(Sprite *sprite, int command)
{
if(command == Sprite::eAnimCommand_Move /*&& mTimer.tick()*/)
{
sprite->moveBy(VectorT<S8>(-1, 0));
}
}
void App::update()
{
mScreen.update();
}
| [
"jazzinghen@Jehuty.(none)"
]
| [
[
[
1,
177
]
]
]
|
c256ed9aaf64408ca8599e4440c508bf774fe1f0 | be2e23022d2eadb59a3ac3932180a1d9c9dee9c2 | /AccountServer/T_Index.h | b46393e83c036800f4e8efcfe3c76071b637eaaa | []
| 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 | GB18030 | C++ | false | false | 2,058 | h | // 索引类,用于建立数据表之间的快速查询。加入的KEY不能重复
// 仙剑修,2001.12.18
#pragma once
//#include "Define.h"
//#include "basefunc.h"
#pragma warning(disable:4786)
#include <map>
using namespace std;
//#define MORECHECK //??? 加强检测, 但降低效率。重复添加会出错/
//#define LogSave printf
#define INDEX_PARA class K, class D, D ERR
#define INDEX_PARA2 K, D, ERR
template < INDEX_PARA >
class CIndex
{
public:
CIndex() {}
virtual ~CIndex() { if(m_map.size()) LogSave("WARNING: CIndex destruction in not empty[%d].", m_map.size()); }
public:
bool Add(K key, D data);
bool Del(K key);
bool IsIn(K key);
D operator[](K key);
void ClearAll() { m_map.clear(); }
typedef map<K, D> MAPINDEX;
typename typedef MAPINDEX::iterator iterator;
K Key(iterator iter) { return iter->first; }
D Data(iterator iter) { return iter->second; }
iterator Begin() { return m_map.begin(); }
iterator End() { return m_map.end(); }
DWORD Size() { return m_map.size();}
protected:
MAPINDEX m_map;
};
template < INDEX_PARA >
bool CIndex<INDEX_PARA2>::Add(K key, D data)
{
#ifdef MORECHECK
if(m_map.find(key) ==m_map.end())
#endif
{
m_map[key] = data;
return true;
}
LogSave("ERROR: CIndex::Add() attempt add again. refused.");
return false;
}
template < INDEX_PARA >
bool CIndex<INDEX_PARA2>::Del(K key)
{
#ifdef MORECHECK
if(m_map.find(key) !=m_map.end())
#endif
{
m_map.erase(key);
return true;
}
LogSave("ERROR: CIndex::Del() attempt del again. refused.");
return false;
}
template < INDEX_PARA >
bool CIndex<INDEX_PARA2>::IsIn(K key)
{
if(m_map.find(key) !=m_map.end())
{
return true;
}
return false;
}
template < INDEX_PARA >
D CIndex<INDEX_PARA2>::operator[](K key)
{
MAPINDEX::iterator iter;
if((iter=m_map.find(key)) !=m_map.end())
{
return iter->second;
}
//? 因为有时会用不存在的ID为参数 LogSave("ERROR: CIndex operator[]() not found key.");
return ERR;
} | [
"rpgsky.com@cc92e6ba-efcf-11de-bf31-4dec8810c1c1"
]
| [
[
[
1,
89
]
]
]
|
1fc5741e00bdca29c563e88d671afa72fda53656 | 3276915b349aec4d26b466d48d9c8022a909ec16 | /c++小作品/sony/liquidcreate.h | dadb7f1e184c3bd2fa5205bd9736834d7180b490 | []
| no_license | flyskyosg/3dvc | c10720b1a7abf9cf4fa1a66ef9fc583d23e54b82 | 0279b1a7ae097b9028cc7e4aa2dcb67025f096b9 | refs/heads/master | 2021-01-10T11:39:45.352471 | 2009-07-31T13:13:50 | 2009-07-31T13:13:50 | 48,670,844 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 230 | h | #ifndef LIQUIDCREATE_HEADER
#define LIQUIDCREATE_HEADER
#include<iostream>
#include"createsony.h"
class LiquidCreate :public CreateSony
{
public:
Sony * createinch29();
Sony * createinch43();
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
18
]
]
]
|
6ec32e79d055de956e0bb5fed25ddd08e186b61b | 71381bcdb9299e23b97fa4f28bcc868fa02c4c25 | /model.cc | 833e8107da82a3bc5a62a9a33aa4f028f4130c04 | []
| no_license | jsoffer/distsim | e00a95d9cd88ef60d8ad1092e684b78b7cc17e97 | 16fa0ab22f529ae2510961dec3c80a968eaa5c4b | refs/heads/master | 2021-01-15T22:29:33.928018 | 2009-10-16T04:15:54 | 2009-10-16T04:15:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,688 | cc | // Archivo: model.cc
// implementacion de la clase 'Model'
// R. Marcelin J. (02/08/99)
// esta es una version modificada que extiende la definicion de la clase
// MODELO, para permitir la concatenacion de automatas (29/10/01).
#include "event.h"
#include "model.h"
#include "process.h"
#include <iostream.h>
//@ Model(): constructor
//------------------------------------------------------------------
Model::Model()
{ clock = 0; }
//@ ~Model(): destructor
//------------------------------------------------------------------
Model::~Model()
{ }
//@ init():
//------------------------------------------------------------------
void Model::init()
{ }
//@ init():
//------------------------------------------------------------------
void Model::init(int pid)
{ }
//@ transmit(): transmite evento
//------------------------------------------------------------------
void Model::transmit(Event *e)
{ myProcess->transmit(e); }
//@ transmitAll():
//------------------------------------------------------------------
void Model::transmitAll(Event *e)
{ myProcess->transmitAll(e); }
//@ receive(): recibe evento
//------------------------------------------------------------------
void Model::receive(Event *e)
{ }
| [
"[email protected]"
]
| [
[
[
1,
60
]
]
]
|
96a3f99e27ea88cfd9fb9f66433ca10245b2502c | c2153dcfa8bcf5b6d7f187e5a337b904ad9f91ac | /src/Engine/Core/Cam.h | e4d62a2691c58b4ea75ca5892448cb422fda3bb7 | []
| 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 | 1,742 | h | #pragma once
namespace Engine
{
class Cam
{
public:
Cam(const int &width, const int &height);
~Cam();
const CL_Mat4f &perspective(float fovx, float aspect, float znear, float zfar);
const CL_Mat4f &getViewMatrix() const { return viewMatrix; }
const CL_Mat4f &getProjectionMatrix() const { return projMatrix; }
void moveLeft(float dt);
void moveRight(float dt);
void moveForward(float dt);
void moveBackward(float dt);
void moveUp(float dt);
void moveDown(float dt);
void pitchUp(float dt);
void pitchDown(float dt);
void yawRight(float dt);
void yawLeft(float dt);
void setPos(const CL_Vec3f& pos) { last_pos = this->pos; this->pos = pos; velocity = CL_Vec3f(0.0f, 0.0f, 0.0f); updateMatrix(true); }
const CL_Vec3f &getPos() { return pos; }
const CL_Vec3f &getLastPos() { return last_pos; }
const CL_Vec3f &getDir() { return direction; }
const CL_Vec3f &getFwdDir() { return fowardDirection; }
const CL_Vec3f &getSideDir() { return leftDirection; }
const CL_Vec3f &getUpDir() { return upDirection; }
void setFwdSpeed(float speed) { forwardSpeed = speed; }
void setSideSpeed(float speed) { sidewaysSpeed = speed; }
private:
void move(float dt, const CL_Vec3f& velocity);
void updateMatrix(bool move = false);
CL_Mat4f viewMatrix;
CL_Mat4f projMatrix;
CL_Vec3f pos, last_pos;
float forwardSpeed;
float sidewaysSpeed;
float verticalSpeed;
float pitch;
float pitchRate;
float heading;
float headingRate;
CL_Quaternionf qPitch;
CL_Quaternionf qHeading;
CL_Vec3f direction;
CL_Vec3f fowardDirection;
CL_Vec3f leftDirection;
CL_Vec3f upDirection;
CL_Vec3f velocity;
};
}
| [
"[email protected]@c628178a-a759-096a-d0f3-7c7507b30227"
]
| [
[
[
1,
66
]
]
]
|
0412f4109655413f55257239d103235a49044f98 | 1ba349971c83732af0a88920bcd8d41b76b06a78 | /src/TransGlass.cpp | a0b55d93d4377c59ec546d29ebc2af783917e9f0 | []
| no_license | c-jiang/TransGlass | c7cc0c59eaf73f48a3502d8daf39ed5c8be189fc | 1fb613c160be804e2a42f67aca65663b18403802 | refs/heads/master | 2016-09-06T21:42:37.773223 | 2011-05-30T16:26:09 | 2011-05-30T16:26:09 | 1,652,540 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,543 | cpp |
// TransGlass.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "TransGlass.h"
#include "TransGlassDlg.h"
#include "ProfileHandler.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CTransGlassApp
BEGIN_MESSAGE_MAP(CTransGlassApp, CWinApp)
ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()
// CTransGlassApp construction
CTransGlassApp::CTransGlassApp()
: m_pProfileHandler(NULL)
{
TCHAR tcPath[MAX_PATH];
GetModuleFileName(NULL, tcPath, sizeof(tcPath));
m_szAppPath = tcPath;
CString szIniPath = m_szAppPath.Mid(0, m_szAppPath.GetLength() - 3)
+ TEXT("ini");
m_pProfileHandler = new ProfileHandler(szIniPath);
}
CTransGlassApp::~CTransGlassApp()
{
if (m_pProfileHandler) {
delete m_pProfileHandler;
m_pProfileHandler = NULL;
}
}
// The one and only CTransGlassApp object
CTransGlassApp theApp;
// CTransGlassApp initialization
BOOL CTransGlassApp::InitInstance()
{
// InitCommonControlsEx() is required on Windows XP if an application
// manifest specifies use of ComCtl32.dll version 6 or later to enable
// visual styles. Otherwise, any window creation will fail.
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// Set this to include all the common control classes you want to use
// in your application.
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CreateMutex(NULL, TRUE, APPLICATION_NAME);
if (GetLastError() == ERROR_ALREADY_EXISTS) {
MessageBox(NULL,
TEXT("TransGlass is already running."),
APPLICATION_NAME,
MB_OK | MB_ICONERROR);
return FALSE;
}
CWinApp::InitInstance();
// 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
// Change the registry key under which our settings are stored
CTransGlassDlg dlg;
m_pMainWnd = &dlg;
#if 0
INT_PTR nResponse = dlg.DoModal();
if (nResponse == IDOK) {
} else if (nResponse == IDCANCEL) {
}
#else
dlg.DoModal();
#endif
// 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]",
"[email protected]"
]
| [
[
[
1,
23
],
[
27,
27
],
[
31,
37
],
[
39,
91
]
],
[
[
24,
26
],
[
28,
30
],
[
38,
38
]
]
]
|
cef4f109138fe490c65e5c4ef8f2e56004963187 | b84a38aad619acf34c22ed6e6caa0f7b00ebfa0a | /Code/TootleCore/IPad/IPadTime.h | 423eab9a9d20b3b93c638bfbfd109e86c2e7d6f6 | []
| no_license | SoylentGraham/Tootle | 4ae4e8352f3e778e3743e9167e9b59664d83b9cb | 17002da0936a7af1f9b8d1699d6f3e41bab05137 | refs/heads/master | 2021-01-24T22:44:04.484538 | 2010-11-03T22:53:17 | 2010-11-03T22:53:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 541 | h | /*------------------------------------------------------
Ipod core header
-------------------------------------------------------*/
#pragma once
#include "../TLTime.h"
namespace TLTime
{
namespace Platform
{
SyncBool Init(); // record bootup timestamp
void GetTimeNow(TTimestamp& Timestamp); // get timestamp for right now!
void GetMicroTimeNow(TTimestampMicro& Timestamp); // get timestamp for right now!
void Debug_PrintTimestamp(const TTimestamp& Timestamp,s32 Micro);
}
}
| [
"[email protected]"
]
| [
[
[
1,
22
]
]
]
|
85d5b163f92142cd3ce5c4d02e200f6e478a8b06 | 3a577d02f876776b22e2bf1c0db12a083f49086d | /vba2/gba2/gba/Mode1.cpp | 0845a4c4cdd1c1f16a14584cc7bfdd1878551613 | []
| no_license | xiaoluoyuan/VisualBoyAdvance-2 | d19565617b26e1771f437842dba5f0131d774e73 | cadd2193ba48e1846b45f87ff7c36246cd61b6ee | refs/heads/master | 2021-01-10T01:19:23.884491 | 2010-05-12T09:59:37 | 2010-05-12T09:59:37 | 46,539,728 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,938 | cpp | /* VisualBoyAdvance 2
Copyright (C) 2009-2010 VBA development team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "GBA.h"
#include "GBAGfx.h"
void mode1RenderLine()
{
u16 *palette = (u16 *)paletteRAM;
if(DISPCNT & 0x80) {
for(int x = 0; x < 240; x++) {
lineMix[x] = 0x7fff;
}
gfxLastVCOUNT = VCOUNT;
return;
}
if(layerEnable & 0x0100) {
gfxDrawTextScreen(BG0CNT, BG0HOFS, BG0VOFS, line0);
}
if(layerEnable & 0x0200) {
gfxDrawTextScreen(BG1CNT, BG1HOFS, BG1VOFS, line1);
}
if(layerEnable & 0x0400) {
int changed = gfxBG2Changed;
if(gfxLastVCOUNT > VCOUNT)
changed = 3;
gfxDrawRotScreen(BG2CNT, BG2X_L, BG2X_H, BG2Y_L, BG2Y_H,
BG2PA, BG2PB, BG2PC, BG2PD,
gfxBG2X, gfxBG2Y, changed, line2);
}
gfxDrawSprites(lineOBJ);
u32 backdrop;
backdrop = (READ16LE(&palette[0]) | 0x30000000);
for(int x = 0; x < 240; x++) {
u32 color = backdrop;
u8 top = 0x20;
if(line0[x] < color) {
color = line0[x];
top = 0x01;
}
if((u8)(line1[x]>>24) < (u8)(color >> 24)) {
color = line1[x];
top = 0x02;
}
if((u8)(line2[x]>>24) < (u8)(color >> 24)) {
color = line2[x];
top = 0x04;
}
if((u8)(lineOBJ[x]>>24) < (u8)(color >> 24)) {
color = lineOBJ[x];
top = 0x10;
}
if((top & 0x10) && (color & 0x00010000)) {
// semi-transparent OBJ
u32 back = backdrop;
u8 top2 = 0x20;
if((u8)(line0[x]>>24) < (u8)(back >> 24)) {
back = line0[x];
top2 = 0x01;
}
if((u8)(line1[x]>>24) < (u8)(back >> 24)) {
back = line1[x];
top2 = 0x02;
}
if((u8)(line2[x]>>24) < (u8)(back >> 24)) {
back = line2[x];
top2 = 0x04;
}
if(top2 & (BLDMOD>>8))
color = gfxAlphaBlend(color, back,
coeff[COLEV & 0x1F],
coeff[(COLEV >> 8) & 0x1F]);
else {
switch((BLDMOD >> 6) & 3) {
case 2:
if(BLDMOD & top)
color = gfxIncreaseBrightness(color, coeff[COLY & 0x1F]);
break;
case 3:
if(BLDMOD & top)
color = gfxDecreaseBrightness(color, coeff[COLY & 0x1F]);
break;
}
}
}
lineMix[x] = color;
}
gfxBG2Changed = 0;
gfxLastVCOUNT = VCOUNT;
}
void mode1RenderLineNoWindow()
{
u16 *palette = (u16 *)paletteRAM;
if(DISPCNT & 0x80) {
for(int x = 0; x < 240; x++) {
lineMix[x] = 0x7fff;
}
gfxLastVCOUNT = VCOUNT;
return;
}
if(layerEnable & 0x0100) {
gfxDrawTextScreen(BG0CNT, BG0HOFS, BG0VOFS, line0);
}
if(layerEnable & 0x0200) {
gfxDrawTextScreen(BG1CNT, BG1HOFS, BG1VOFS, line1);
}
if(layerEnable & 0x0400) {
int changed = gfxBG2Changed;
if(gfxLastVCOUNT > VCOUNT)
changed = 3;
gfxDrawRotScreen(BG2CNT, BG2X_L, BG2X_H, BG2Y_L, BG2Y_H,
BG2PA, BG2PB, BG2PC, BG2PD,
gfxBG2X, gfxBG2Y, changed, line2);
}
gfxDrawSprites(lineOBJ);
u32 backdrop;
backdrop = (READ16LE(&palette[0]) | 0x30000000);
for(int x = 0; x < 240; x++) {
u32 color = backdrop;
u8 top = 0x20;
if(line0[x] < color) {
color = line0[x];
top = 0x01;
}
if((u8)(line1[x]>>24) < (u8)(color >> 24)) {
color = line1[x];
top = 0x02;
}
if((u8)(line2[x]>>24) < (u8)(color >> 24)) {
color = line2[x];
top = 0x04;
}
if((u8)(lineOBJ[x]>>24) < (u8)(color >> 24)) {
color = lineOBJ[x];
top = 0x10;
}
if(!(color & 0x00010000)) {
switch((BLDMOD >> 6) & 3) {
case 0:
break;
case 1:
{
if(top & BLDMOD) {
u32 back = backdrop;
u8 top2 = 0x20;
if((u8)(line0[x]>>24) < (u8)(back >> 24)) {
if(top != 0x01) {
back = line0[x];
top2 = 0x01;
}
}
if((u8)(line1[x]>>24) < (u8)(back >> 24)) {
if(top != 0x02) {
back = line1[x];
top2 = 0x02;
}
}
if((u8)(line2[x]>>24) < (u8)(back >> 24)) {
if(top != 0x04) {
back = line2[x];
top2 = 0x04;
}
}
if((u8)(lineOBJ[x]>>24) < (u8)(back >> 24)) {
if(top != 0x10) {
back = lineOBJ[x];
top2 = 0x10;
}
}
if(top2 & (BLDMOD>>8))
color = gfxAlphaBlend(color, back,
coeff[COLEV & 0x1F],
coeff[(COLEV >> 8) & 0x1F]);
}
}
break;
case 2:
if(BLDMOD & top)
color = gfxIncreaseBrightness(color, coeff[COLY & 0x1F]);
break;
case 3:
if(BLDMOD & top)
color = gfxDecreaseBrightness(color, coeff[COLY & 0x1F]);
break;
}
} else {
// semi-transparent OBJ
u32 back = backdrop;
u8 top2 = 0x20;
if((u8)(line0[x]>>24) < (u8)(back >> 24)) {
back = line0[x];
top2 = 0x01;
}
if((u8)(line1[x]>>24) < (u8)(back >> 24)) {
back = line1[x];
top2 = 0x02;
}
if((u8)(line2[x]>>24) < (u8)(back >> 24)) {
back = line2[x];
top2 = 0x04;
}
if(top2 & (BLDMOD>>8))
color = gfxAlphaBlend(color, back,
coeff[COLEV & 0x1F],
coeff[(COLEV >> 8) & 0x1F]);
else {
switch((BLDMOD >> 6) & 3) {
case 2:
if(BLDMOD & top)
color = gfxIncreaseBrightness(color, coeff[COLY & 0x1F]);
break;
case 3:
if(BLDMOD & top)
color = gfxDecreaseBrightness(color, coeff[COLY & 0x1F]);
break;
}
}
}
lineMix[x] = color;
}
gfxBG2Changed = 0;
gfxLastVCOUNT = VCOUNT;
}
void mode1RenderLineAll()
{
u16 *palette = (u16 *)paletteRAM;
if(DISPCNT & 0x80) {
for(int x = 0; x < 240; x++) {
lineMix[x] = 0x7fff;
}
gfxLastVCOUNT = VCOUNT;
return;
}
bool inWindow0 = false;
bool inWindow1 = false;
if(layerEnable & 0x2000) {
u8 v0 = WIN0V >> 8;
u8 v1 = WIN0V & 255;
inWindow0 = ((v0 == v1) && (v0 >= 0xe8));
if(v1 >= v0)
inWindow0 |= (VCOUNT >= v0 && VCOUNT < v1);
else
inWindow0 |= (VCOUNT >= v0 || VCOUNT < v1);
}
if(layerEnable & 0x4000) {
u8 v0 = WIN1V >> 8;
u8 v1 = WIN1V & 255;
inWindow1 = ((v0 == v1) && (v0 >= 0xe8));
if(v1 >= v0)
inWindow1 |= (VCOUNT >= v0 && VCOUNT < v1);
else
inWindow1 |= (VCOUNT >= v0 || VCOUNT < v1);
}
if(layerEnable & 0x0100) {
gfxDrawTextScreen(BG0CNT, BG0HOFS, BG0VOFS, line0);
}
if(layerEnable & 0x0200) {
gfxDrawTextScreen(BG1CNT, BG1HOFS, BG1VOFS, line1);
}
if(layerEnable & 0x0400) {
int changed = gfxBG2Changed;
if(gfxLastVCOUNT > VCOUNT)
changed = 3;
gfxDrawRotScreen(BG2CNT, BG2X_L, BG2X_H, BG2Y_L, BG2Y_H,
BG2PA, BG2PB, BG2PC, BG2PD,
gfxBG2X, gfxBG2Y, changed, line2);
}
gfxDrawSprites(lineOBJ);
gfxDrawOBJWin(lineOBJWin);
u32 backdrop;
backdrop = (READ16LE(&palette[0]) | 0x30000000);
u8 inWin0Mask = WININ & 0xFF;
u8 inWin1Mask = WININ >> 8;
u8 outMask = WINOUT & 0xFF;
for(int x = 0; x < 240; x++) {
u32 color = backdrop;
u8 top = 0x20;
u8 mask = outMask;
if(!(lineOBJWin[x] & 0x80000000)) {
mask = WINOUT >> 8;
}
if(inWindow1) {
if(gfxInWin1[x])
mask = inWin1Mask;
}
if(inWindow0) {
if(gfxInWin0[x]) {
mask = inWin0Mask;
}
}
if(line0[x] < color && (mask & 1)) {
color = line0[x];
top = 0x01;
}
if((u8)(line1[x]>>24) < (u8)(color >> 24) && (mask & 2)) {
color = line1[x];
top = 0x02;
}
if((u8)(line2[x]>>24) < (u8)(color >> 24) && (mask & 4)) {
color = line2[x];
top = 0x04;
}
if((u8)(lineOBJ[x]>>24) < (u8)(color >> 24) && (mask & 16)) {
color = lineOBJ[x];
top = 0x10;
}
if(color & 0x00010000) {
// semi-transparent OBJ
u32 back = backdrop;
u8 top2 = 0x20;
if((mask & 1) && (u8)(line0[x]>>24) < (u8)(back >> 24)) {
back = line0[x];
top2 = 0x01;
}
if((mask & 2) && (u8)(line1[x]>>24) < (u8)(back >> 24)) {
back = line1[x];
top2 = 0x02;
}
if((mask & 4) && (u8)(line2[x]>>24) < (u8)(back >> 24)) {
back = line2[x];
top2 = 0x04;
}
if(top2 & (BLDMOD>>8))
color = gfxAlphaBlend(color, back,
coeff[COLEV & 0x1F],
coeff[(COLEV >> 8) & 0x1F]);
else {
switch((BLDMOD >> 6) & 3) {
case 2:
if(BLDMOD & top)
color = gfxIncreaseBrightness(color, coeff[COLY & 0x1F]);
break;
case 3:
if(BLDMOD & top)
color = gfxDecreaseBrightness(color, coeff[COLY & 0x1F]);
break;
}
}
} else if(mask & 32) {
// special FX on the window
switch((BLDMOD >> 6) & 3) {
case 0:
break;
case 1:
{
if(top & BLDMOD) {
u32 back = backdrop;
u8 top2 = 0x20;
if((mask & 1) && (u8)(line0[x]>>24) < (u8)(back >> 24)) {
if(top != 0x01) {
back = line0[x];
top2 = 0x01;
}
}
if((mask & 2) && (u8)(line1[x]>>24) < (u8)(back >> 24)) {
if(top != 0x02) {
back = line1[x];
top2 = 0x02;
}
}
if((mask & 4) && (u8)(line2[x]>>24) < (u8)(back >> 24)) {
if(top != 0x04) {
back = line2[x];
top2 = 0x04;
}
}
if((mask & 16) && (u8)(lineOBJ[x]>>24) < (u8)(back >> 24)) {
if(top != 0x10) {
back = lineOBJ[x];
top2 = 0x10;
}
}
if(top2 & (BLDMOD>>8))
color = gfxAlphaBlend(color, back,
coeff[COLEV & 0x1F],
coeff[(COLEV >> 8) & 0x1F]);
}
}
break;
case 2:
if(BLDMOD & top)
color = gfxIncreaseBrightness(color, coeff[COLY & 0x1F]);
break;
case 3:
if(BLDMOD & top)
color = gfxDecreaseBrightness(color, coeff[COLY & 0x1F]);
break;
}
}
lineMix[x] = color;
}
gfxBG2Changed = 0;
gfxLastVCOUNT = VCOUNT;
}
| [
"spacy51@5a53c671-dd2d-0410-9261-3f5c817b7aa0"
]
| [
[
[
1,
478
]
]
]
|
36336f3f153e435e85c3dbd431f3ae1ffbeaa42d | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/zombie/nscene/src/nscene/nshadowlightnode_cmds.cc | 5701f86c81321905debff659e1a33ad05330b9a7 | []
| no_license | ugozapad/TheZombieEngine | 832492930df28c28cd349673f79f3609b1fe7190 | 8e8c3e6225c2ed93e07287356def9fbdeacf3d6a | refs/heads/master | 2020-04-30T11:35:36.258363 | 2011-02-24T14:18:43 | 2011-02-24T14:18:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,680 | cc | #include "precompiled/pchrnsscene.h"
//------------------------------------------------------------------------------
// nshadowlightnode_cmds.cc
// (C) 2005 Conjurer Services, S.A.
//------------------------------------------------------------------------------
#include "nscene/nshadowlightnode.h"
#include "kernel/npersistserver.h"
NSCRIPT_INITCMDS_BEGIN( nShadowLightNode )
NSCRIPT_ADDCMD('AABE', void, SetOrthogonal, 4, (float, float, float, float), 0, ());
NSCRIPT_ADDCMD('AABF', void, SetEuler, 1, (const vector3&), 0, ());
NSCRIPT_ADDCMD('AABG', const vector3, GetEuler, 0, (), 0, ());
NSCRIPT_ADDCMD('AABH', void, SetPosition, 1, (const vector3&), 0, ());
NSCRIPT_ADDCMD('AABI', const vector3, GetPosition, 0, (), 0, ());
NSCRIPT_ADDCMD('CSDE', void, SetDeformation, 1, (const vector4&), 0, ());
NSCRIPT_ADDCMD('CGDE', const vector4, GetDeformation, 0, (), 0, ());
NSCRIPT_INITCMDS_END()
//------------------------------------------------------------------------------
/**
*/
bool
nShadowLightNode::SaveCmds(nPersistServer *ps)
{
if (nAbstractShaderNode::SaveCmds(ps))
{
nCmd* cmd;
////---- SetPerspective ----
//cmd = ps->GetCmd(this, 'AABD');
//cmd->In()->SetF(this->GetCamera()->GetAngleOfView());
//cmd->In()->SetF(this->GetCamera()->GetAspectRatio());
//cmd->In()->SetF(this->GetCamera()->GetNearPlane());
//cmd->In()->SetF(this->GetCamera()->GetFarPlane());
//ps->PutCmd(cmd);
//---- SetOrthogonal ----
cmd = ps->GetCmd(this, 'AABE');
cmd->In()->SetF(this->GetCamera().GetWidth());
cmd->In()->SetF(this->GetCamera().GetHeight());
cmd->In()->SetF(this->GetCamera().GetNearPlane());
cmd->In()->SetF(this->GetCamera().GetFarPlane());
ps->PutCmd(cmd);
//---- SetEuler ----
cmd = ps->GetCmd(this, 'AABF');
cmd->In()->SetF(this->euler.x);
cmd->In()->SetF(this->euler.y);
cmd->In()->SetF(this->euler.z);
ps->PutCmd(cmd);
//---- SetPosition ----
cmd = ps->GetCmd(this, 'AABH');
cmd->In()->SetF(this->position.x);
cmd->In()->SetF(this->position.y);
cmd->In()->SetF(this->position.z);
ps->PutCmd(cmd);
//---- SetDeformation ----
cmd = ps->GetCmd(this, 'CSDE');
cmd->In()->SetF(this->deformation.x);
cmd->In()->SetF(this->deformation.y);
cmd->In()->SetF(this->deformation.z);
cmd->In()->SetF(this->deformation.w);
ps->PutCmd(cmd);
return true;
}
return false;
}
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
]
| [
[
[
1,
71
]
]
]
|
b1642698d395931736de3f1e93b1210d26f8850d | 3bfc30f7a07ce0f6eabcd526e39ba1030d84c1f3 | /BlobbyWarriors/Source/BlobbyWarriors/Model/Entity/AbstractWeapon.cpp | 6bfe67f0c6038675d41d4df6f898573d578447e1 | []
| no_license | visusnet/Blobby-Warriors | b0b70a0b4769b60d96424b55ad7c47b256e60061 | adec63056786e4e8dfcb1ed7f7fe8b09ce05399d | refs/heads/master | 2021-01-19T14:09:32.522480 | 2011-11-29T21:53:25 | 2011-11-29T21:53:25 | 2,850,563 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,505 | cpp | #include "AbstractWeapon.h"
AbstractWeapon::AbstractWeapon()
{
this->isActive = false;
this->soundSources[WEAPON_EVENT_FIRE] = 0;
this->soundSources[WEAPON_EVENT_STOP_FIRE] = 0;
this->sounds[WEAPON_EVENT_FIRE] = 0;
this->sounds[WEAPON_EVENT_STOP_FIRE] = 0;
this->soundSingelton[WEAPON_EVENT_FIRE] = true;
this->soundSingelton[WEAPON_EVENT_STOP_FIRE] = true;
}
void AbstractWeapon::fire(b2Vec2 direction, bool constantFire, bool isPlayer)
{
if (hasSoundSource(WEAPON_EVENT_FIRE) && (!this->soundSingelton[WEAPON_EVENT_FIRE] || !isSoundPlaying(WEAPON_EVENT_FIRE))) {
debug("play start fire");
this->sounds[WEAPON_EVENT_FIRE] = SoundManager::getInstance()->getEngine()->play2D(this->soundSources[WEAPON_EVENT_FIRE], true, false, true);
debug("sound is %s", this->sounds[WEAPON_EVENT_FIRE] == 0 ? "null" : "not null");
}
this->onFire(direction, constantFire, isPlayer);
}
void AbstractWeapon::stopFire()
{
if (hasSoundSource(WEAPON_EVENT_FIRE) && isSoundPlaying(WEAPON_EVENT_FIRE)) {
debug("jo");
this->sounds[WEAPON_EVENT_FIRE]->stop();
this->sounds[WEAPON_EVENT_FIRE] = 0;
}
if (hasSoundSource(WEAPON_EVENT_STOP_FIRE)) {
debug("play stop fire");
this->sounds[WEAPON_EVENT_STOP_FIRE] = SoundManager::getInstance()->getEngine()->play2D(this->soundSources[WEAPON_EVENT_STOP_FIRE], true, false, true);
}
this->onStopFire();
}
void AbstractWeapon::onStopFire()
{
}
void AbstractWeapon::draw()
{
if (this->isActive) {
Texturizer::draw(this->getTexture(0), this->getBody(0)->GetPosition().x, this->getBody(0)->GetPosition().y, degree2radian(radian2degree(this->getBody(0)->GetTransform().GetAngle()) + 180), 40, 19);
}
// AbstractEntity::draw();
}
void AbstractWeapon::setActive(bool isActive)
{
this->isActive = isActive;
if (hasSoundSource(WEAPON_EVENT_FIRE) && isSoundPlaying(WEAPON_EVENT_FIRE)) {
this->sounds[WEAPON_EVENT_FIRE]->stop();
this->sounds[WEAPON_EVENT_FIRE] = 0;
}
if (hasSoundSource(WEAPON_EVENT_STOP_FIRE) && isSoundPlaying(WEAPON_EVENT_STOP_FIRE)) {
this->sounds[WEAPON_EVENT_STOP_FIRE]->stop();
this->sounds[WEAPON_EVENT_STOP_FIRE] = 0;
}
}
void AbstractWeapon::setSound(unsigned int event, char *filename, bool singleton)
{
if (event == WEAPON_EVENT_FIRE || event == WEAPON_EVENT_STOP_FIRE) {
this->soundSources[event] = SoundManager::getInstance()->getEngine()->addSoundSourceFromFile(filename, ESM_AUTO_DETECT, true);
this->soundSingelton[event] = singleton;
}
} | [
"[email protected]"
]
| [
[
[
1,
69
]
]
]
|
1c7547768f201cb6827dae49d9700af31c45135b | b5ab57edece8c14a67cc98e745c7d51449defcff | /CD - Sprint 1/Captain's Log - Code/MainGame/Source/GameObjects/CAnimation.h | ebea73651519b305e32bf00f8d99c6beb65b3346 | []
| no_license | tabu34/tht-captainslog | c648c6515424a6fcdb628320bc28fc7e5f23baba | 72d72a45e7ea44bdb8c1ffc5c960a0a3845557a2 | refs/heads/master | 2020-05-30T15:09:24.514919 | 2010-07-30T17:05:11 | 2010-07-30T17:05:11 | 32,187,254 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,119 | h | #ifndef CAnimation_h__
#define CAnimation_h__
#include <Windows.h>
#include <vector>
using namespace std;
class CAnimation
{
public:
struct tFrame
{
RECT rFrame;
POINT ptAnchor;
float fDuration;
};
private:
vector<tFrame> m_vFrames;
int m_nImageID;
unsigned int m_nCurFrame;
float m_fTimeWaited;
float m_fSpeed;
bool m_bIsPlaying;
bool m_bIsLooping;
void Reset();
public:
CAnimation();
~CAnimation();
RECT GetCollisionRect(bool bIsFlipped);
unsigned int CurFrame() const { return m_nCurFrame; }
void CurFrame(unsigned int val) { m_nCurFrame = val; }
void Update(float fElapsedTime);
void Render(int nPosX, int nPosY, bool bIsFlipped = false, float fScale = 1, DWORD dwColor = -1);
void Init(char* szImageID, DWORD dwKeyColor, float fSpeed, bool bIsLooping, int nNumFrames, tFrame* pFrames);
void Shutdown();
bool IsPlaying() const { return m_bIsPlaying; }
void Play()
{
Reset();
m_bIsPlaying = true;
}
void Stop() { m_bIsPlaying = false; }
void Pause() { m_bIsPlaying = true; }
};
#endif // CAnimation_h__ | [
"dpmakin@34577012-8437-c882-6fb8-056151eb068d"
]
| [
[
[
1,
55
]
]
]
|
1f6cc425926202a722492ff28adcc56b41ee00e6 | 021e8c48a44a56571c07dd9830d8bf86d68507cb | /build/vtk/vtkNGramExtraction.h | 8c92cb14db8ce8c5787ae5fa61e9a6325b6f46a3 | [
"BSD-3-Clause"
]
| permissive | Electrofire/QdevelopVset | c67ae1b30b0115d5c2045e3ca82199394081b733 | f88344d0d89beeec46f5dc72c20c0fdd9ef4c0b5 | refs/heads/master | 2021-01-18T10:44:01.451029 | 2011-05-01T23:52:15 | 2011-05-01T23:52:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,686 | h | /*=========================================================================
Program: Visualization Toolkit
Module: vtkNGramExtraction.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
#ifndef __vtkNGramExtraction_h
#define __vtkNGramExtraction_h
#include <vtkTableAlgorithm.h>
// .NAME vtkNGramExtraction - Converts a collection of tokens into a collection of N-grams.
//
// .SECTION Description
// Given a table containing tokens, generates a table containing N-grams.
//
// Inputs:
// Input port 0: (required) A vtkTable containing document, begin, end, and text
// columns.
//
// Outputs:
// Output port 0: A vtkTable containing "document", "begin", "end", "type", and "text"
// columns.
//
// Use SetInputArrayToProcess(0, ...) to specify the "document" array.
// Use SetInputArrayToProcess(1, ...) to specify the "begin" array.
// Use SetInputArrayToProcess(2, ...) to specify the "end" array.
// Use SetInputArrayToProcess(3, ...) to specify the "text" array.
//
// .SECTION Thanks
// Developed by Timothy M. Shead ([email protected]) at Sandia National Laboratories.
class VTK_TEXT_ANALYSIS_EXPORT vtkNGramExtraction :
public vtkTableAlgorithm
{
public:
static vtkNGramExtraction* New();
vtkTypeMacro(vtkNGramExtraction, vtkTableAlgorithm);
void PrintSelf(ostream& os, vtkIndent indent);
// Description:
// Controls the type of N-gram to produce. Default: 1 (unigrams).
vtkSetMacro(N, vtkIdType);
vtkGetMacro(N, vtkIdType);
//BTX
protected:
vtkNGramExtraction();
~vtkNGramExtraction();
virtual int RequestData(
vtkInformation* request,
vtkInformationVector** inputVector,
vtkInformationVector* outputVector);
private:
vtkNGramExtraction(const vtkNGramExtraction &); // Not implemented.
void operator=(const vtkNGramExtraction &); // Not implemented.
vtkIdType N;
//ETX
};
#endif // __vtkNGramExtraction_h
| [
"ganondorf@ganondorf-VirtualBox.(none)"
]
| [
[
[
1,
79
]
]
]
|
62153cd7f61d1c20fd7e3c40d24e05cf0eccbc3b | 073dfce42b384c9438734daa8ee2b575ff100cc9 | /RCF/src/RCF/ThreadLocalCache.cpp | f470d9a5cb7146d51540465811a41b0807344392 | []
| no_license | r0ssar00/iTunesSpeechBridge | a489426bbe30ac9bf9c7ca09a0b1acd624c1d9bf | 71a27a52e66f90ade339b2b8a7572b53577e2aaf | refs/heads/master | 2020-12-24T17:45:17.838301 | 2009-08-24T22:04:48 | 2009-08-24T22:04:48 | 285,393 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,400 | cpp |
//******************************************************************************
// RCF - Remote Call Framework
// Copyright (c) 2005 - 2009, Jarl Lindrud. All rights reserved.
// Consult your license for conditions of use.
// Version: 1.1
// Contact: jarl.lindrud <at> gmail.com
//******************************************************************************
#include <RCF/ThreadLocalCache.hpp>
namespace RCF {
ObjectCache::VectorByteBufferCache & ObjectCache::getCache(VectorByteBufferCache *)
{
return mVectorByteBufferCache;
}
ObjectCache::VectorIntCache & ObjectCache::getCache(VectorIntCache *)
{
return mVectorIntCache;
}
ObjectCache::VectorWsabufCache & ObjectCache::getCache(VectorWsabufCache *)
{
return mVectorWsabufCache;
}
ObjectCache::VectorFilterCache & ObjectCache::getCache(VectorFilterCache *)
{
return mVectorFilterCache;
}
ObjectCache::VectorRcfSessionCallbackCache & ObjectCache::getCache(VectorRcfSessionCallbackCache *)
{
return mVectorRcfSessionCallbackCache;
}
void ObjectCache::clear()
{
mVectorByteBufferCache.clear();
mVectorIntCache.clear();
mVectorWsabufCache.clear();
mVectorFilterCache.clear();
mVectorRcfSessionCallbackCache.clear();
}
} // namespace RCF
| [
"[email protected]"
]
| [
[
[
1,
48
]
]
]
|
b755d997cacaaa86a1718763bc813c8c1c16e6d0 | b7c505dcef43c0675fd89d428e45f3c2850b124f | /Src/SimulatorQt/Util/qt/Win32/include/Qt/qmutex.h | c804e0931f9446fe8e3d876915168927d59e95a6 | [
"BSD-2-Clause"
]
| permissive | pranet/bhuman2009fork | 14e473bd6e5d30af9f1745311d689723bfc5cfdb | 82c1bd4485ae24043aa720a3aa7cb3e605b1a329 | refs/heads/master | 2021-01-15T17:55:37.058289 | 2010-02-28T13:52:56 | 2010-02-28T13:52:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,022 | h | /****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QMUTEX_H
#define QMUTEX_H
#include <QtCore/qglobal.h>
#include <new>
QT_BEGIN_HEADER
QT_BEGIN_NAMESPACE
QT_MODULE(Core)
#ifndef QT_NO_THREAD
class QMutexPrivate;
class Q_CORE_EXPORT QMutex
{
friend class QWaitCondition;
friend class QWaitConditionPrivate;
public:
enum RecursionMode { NonRecursive, Recursive };
explicit QMutex(RecursionMode mode = NonRecursive);
~QMutex();
void lock();
bool tryLock();
bool tryLock(int timeout);
void unlock();
#if defined(QT3_SUPPORT)
inline QT3_SUPPORT bool locked()
{
if (!tryLock())
return true;
unlock();
return false;
}
inline QT3_SUPPORT_CONSTRUCTOR QMutex(bool recursive)
{
new (this) QMutex(recursive ? Recursive : NonRecursive);
}
#endif
private:
Q_DISABLE_COPY(QMutex)
QMutexPrivate *d;
};
class Q_CORE_EXPORT QMutexLocker
{
public:
inline explicit QMutexLocker(QMutex *m)
: mtx(m)
{
Q_ASSERT_X((val & quintptr(1u)) == quintptr(0),
"QMutexLocker", "QMutex pointer is misaligned");
relock();
}
inline ~QMutexLocker() { unlock(); }
inline void unlock()
{
if (mtx) {
if ((val & quintptr(1u)) == quintptr(1u)) {
val &= ~quintptr(1u);
mtx->unlock();
}
}
}
inline void relock()
{
if (mtx) {
if ((val & quintptr(1u)) == quintptr(0u)) {
mtx->lock();
val |= quintptr(1u);
}
}
}
#if defined(Q_CC_MSVC)
#pragma warning( push )
#pragma warning( disable : 4312 ) // ignoring the warning from /Wp64
#endif
inline QMutex *mutex() const
{
return reinterpret_cast<QMutex *>(val & ~quintptr(1u));
}
#if defined(Q_CC_MSVC)
#pragma warning( pop )
#endif
private:
Q_DISABLE_COPY(QMutexLocker)
union {
QMutex *mtx;
quintptr val;
};
};
#else // QT_NO_THREAD
class Q_CORE_EXPORT QMutex
{
public:
enum RecursionMode { NonRecursive, Recursive };
inline explicit QMutex(RecursionMode mode = NonRecursive) { Q_UNUSED(mode); }
inline ~QMutex() {}
static inline void lock() {}
static inline bool tryLock() { return true; }
static inline bool tryLock(int timeout) { Q_UNUSED(timeout); return true; }
static void unlock() {}
#if defined(QT3_SUPPORT)
static inline QT3_SUPPORT bool locked() { return false; }
#endif
private:
Q_DISABLE_COPY(QMutex)
};
class Q_CORE_EXPORT QMutexLocker
{
public:
inline explicit QMutexLocker(QMutex *) {}
inline ~QMutexLocker() {}
static inline void unlock() {}
static void relock() {}
static inline QMutex *mutex() { return 0; }
private:
Q_DISABLE_COPY(QMutexLocker)
};
#endif // QT_NO_THREAD
QT_END_NAMESPACE
QT_END_HEADER
#endif // QMUTEX_H
| [
"alon@rogue.(none)"
]
| [
[
[
1,
193
]
]
]
|
fd1b243b322d8788e1078481f2f7c300999f1d97 | b14d5833a79518a40d302e5eb40ed5da193cf1b2 | /cpp/extern/xercesc++/2.6.0/samples/SAXPrint/SAXPrint.hpp | 5ab5d822ed7933405165229a40b44c38e87427af | [
"Apache-2.0"
]
| permissive | andyburke/bitflood | dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf | fca6c0b635d07da4e6c7fbfa032921c827a981d6 | refs/heads/master | 2016-09-10T02:14:35.564530 | 2011-11-17T09:51:49 | 2011-11-17T09:51:49 | 2,794,411 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,408 | hpp | /*
* Copyright 1999-2000,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Log: SAXPrint.hpp,v $
* Revision 1.7 2004/09/08 13:55:34 peiyongz
* Apache License Version 2.0
*
* Revision 1.6 2003/05/30 09:36:36 gareth
* Use new macros for iostream.h and std:: issues.
*
* Revision 1.5 2003/02/05 18:53:24 tng
* [Bug 11915] Utility for freeing memory.
*
* Revision 1.4 2000/03/02 19:53:49 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.3 2000/02/11 02:47:15 abagchi
* Removed StrX::transcode
*
* Revision 1.2 2000/02/06 07:47:24 rahulj
* Year 2K copyright swat.
*
* Revision 1.1.1.1 1999/11/09 01:09:29 twl
* Initial checkin
*
* Revision 1.6 1999/11/08 20:43:41 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Includes for all the program files to see
// ---------------------------------------------------------------------------
#include <string.h>
#if defined(XERCES_NEW_IOSTREAMS)
#include <iostream>
#else
#include <iostream.h>
#endif
#include <stdlib.h>
#include "SAXPrintHandlers.hpp"
// ---------------------------------------------------------------------------
// This is a simple class that lets us do easy (though not terribly efficient)
// trancoding of XMLCh data to local code page for display.
// ---------------------------------------------------------------------------
class StrX
{
public :
// -----------------------------------------------------------------------
// Constructors and Destructor
// -----------------------------------------------------------------------
StrX(const XMLCh* const toTranscode)
{
// Call the private transcoding method
fLocalForm = XMLString::transcode(toTranscode);
}
~StrX()
{
XMLString::release(&fLocalForm);
}
// -----------------------------------------------------------------------
// Getter methods
// -----------------------------------------------------------------------
const char* localForm() const
{
return fLocalForm;
}
private :
// -----------------------------------------------------------------------
// Private data members
//
// fLocalForm
// This is the local code page form of the string.
// -----------------------------------------------------------------------
char* fLocalForm;
};
inline XERCES_STD_QUALIFIER ostream& operator<<(XERCES_STD_QUALIFIER ostream& target, const StrX& toDump)
{
target << toDump.localForm();
return target;
}
| [
"[email protected]"
]
| [
[
[
1,
103
]
]
]
|
2c5045ec9778a7dc11c20d0ed84460930441c867 | 5527467df8db4e127247ee4a1bb0e81be3b6b914 | /src/EventInterface/EH_Trackball.cpp | 8dd6d2b0a5509f529a6f662a615c4adeb55afff0 | []
| no_license | hywei/PatchEditor | bb9978c294a79d7dd1818a83557962d62273c6ef | a00d3ea685def0b9ad719b8a51ef54f52b0df4b3 | refs/heads/master | 2021-01-19T04:56:20.849381 | 2011-07-06T13:50:19 | 2011-07-06T13:50:19 | 1,481,431 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,245 | cpp | #include "EH_Trackball.h"
#include "../MainWindow/ViewerQT.h"
#include <iostream>
//////////////////////////////////////////////////////////////////////
// EH_Trackball Construction/Destruction
//////////////////////////////////////////////////////////////////////
EH_Trackball::EH_Trackball()
{
this->m_MouseMode = MOUSE_MODE_UNDEFINED;
this->m_KeyMode = KEY_MODE_UNDEFINED;
//
}
EH_Trackball::~EH_Trackball(){}
void EH_Trackball::Init(ViewerQT* _qt_viewer)
{
qt_viewer = _qt_viewer;
}
bool EH_Trackball::OnLButtonDown(unsigned int nFlags, int point_x, int point_y)
{
switch(m_MouseMode){
default:
break;
}
return true;
}
bool EH_Trackball::OnMouseMove(unsigned int nFlags, int point_x, int point_y)
{
// LButton is pressed (dragging)
if((nFlags&Qt::LeftButton) != Qt::LeftButton) return false;
switch(m_MouseMode){
default:
break;
}
return true;
}
bool EH_Trackball::OnMouseWheel(unsigned int nFlags, short zDelta, int point_x, int point_y)
{
return true;
}
bool EH_Trackball::IsMouseNeedHandle(MouseMode mouse_mode)
{
this->m_MouseMode = mouse_mode;
return m_ValidMouseMode.find(mouse_mode) != m_ValidMouseMode.end();
}
| [
"[email protected]"
]
| [
[
[
1,
53
]
]
]
|
57b2343344eb25495afb06dd335593804fc96143 | 1f8c4298e80a2da0f78424152d0db18837bb6254 | /source/Box2D/Dynamics/b2Island.h | ec71173f75f5816bb73eef1fe545ad619fdf9157 | []
| no_license | benbaker76/TriballDS | 68822bd2760f927a9950d8061ee416d07f3d2e4c | 80dabc161227c564940912672f4b643dd401dcd8 | refs/heads/master | 2022-11-28T03:34:09.460898 | 2010-01-10T22:51:34 | 2010-01-10T22:51:34 | 241,390,317 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,053 | h | /*
* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef B2_ISLAND_H
#define B2_ISLAND_H
#include "../Common/b2Math.h"
class b2StackAllocator;
class b2Contact;
class b2Body;
class b2Joint;
struct b2TimeStep;
class b2Island
{
public:
b2Island(int32 bodyCapacity, int32 contactCapacity, int32 jointCapacity, b2StackAllocator* allocator);
~b2Island();
void Clear();
void Solve(const b2TimeStep* step, const b2Vec2& gravity);
void UpdateSleep(Fixed dt);
void Add(b2Body* body)
{
b2Assert(m_bodyCount < m_bodyCapacity);
m_bodies[m_bodyCount++] = body;
}
void Add(b2Contact* contact)
{
b2Assert(m_contactCount < m_contactCapacity);
m_contacts[m_contactCount++] = contact;
}
void Add(b2Joint* joint)
{
b2Assert(m_jointCount < m_jointCapacity);
m_joints[m_jointCount++] = joint;
}
b2StackAllocator* m_allocator;
b2Body** m_bodies;
b2Contact** m_contacts;
b2Joint** m_joints;
int32 m_bodyCount;
int32 m_jointCount;
int32 m_contactCount;
int32 m_bodyCapacity;
int32 m_contactCapacity;
int32 m_jointCapacity;
static int32 m_positionIterationCount;
Fixed m_positionError;
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
78
]
]
]
|
f9bc5988af6a91019ad32243baebfd2ba3513ccc | 3da0b0276bc8c3d7d1bcdbabfb0e763a38d3a24c | /zju.finished/1952.cpp | 13888fe8e4093dcad878846ccafd49d07596938d | []
| no_license | usherfu/zoj | 4af6de9798bcb0ffa9dbb7f773b903f630e06617 | 8bb41d209b54292d6f596c5be55babd781610a52 | refs/heads/master | 2021-05-28T11:21:55.965737 | 2009-12-15T07:58:33 | 2009-12-15T07:58:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,672 | cpp | #include<iostream>
#include<map>
#include<queue>
#include<string>
#include<vector>
using namespace std;
enum {
Size = 204,
};
map<string, int> table;
int N,R;
int start, end;
map<int,int> matrix[Size];
queue<int> que;
int mark[Size];
int fun(){
int cur;
int i;
int t;
int n;
map<int,int>::iterator iter;
memset(mark,0,sizeof(int)*Size);
mark[start] = 100000;
que.push(start);
while(! que.empty()){
cur = que.front();
que.pop();
if(cur== end)
continue;
for(iter=matrix[cur].begin(); iter!= matrix[cur].end(); iter++){
n = iter->first;
t = mark[cur] < iter->second? mark[cur] : iter->second;
if(mark[n] < t) {
mark[n] = t;
que.push(n);
}
}
}
return mark[end];
}
int main(){
int index;
string a,b;
int ton;
int tstcase = 0;
cin>>N>>R;
while(N && R){
table.clear();
index = 0;
while(R -- ){
cin>>a>>b>>ton;
if(table.find(a) == table.end()){
matrix[index].clear();
table[a] = index ++;
}
if(table.find(b) == table.end()){
matrix[index].clear();
table[b] = index ++;
}
int second = table[b];
int first = table[a];
matrix[first][second] = ton;
matrix[second][first] = ton;
}
cin>>a>>b;
if(table.find(a) == table.end()){
matrix[index].clear();
table[a] = index ++;
}
if(table.find(b) == table.end()){
matrix[index].clear();
table[b] = index ++;
}
start = table[a];
end = table[b];
ton = fun();
tstcase ++;
cout<<"Scenario #"<<tstcase<<endl;
cout<<ton<<" tons"<<endl<<endl;
cin>>N>>R;
}
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
90
]
]
]
|
c1dfdac8945b3421f8a7342ec96cb1cb3659097d | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Targets/MapLib/Shared/include/SharedHttpHeader.h | 4f715db559c2fac20d35ae90beadbcb366b724ca | [
"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 | 3,760 | h | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef SHARED_HTTP_HEADER_H
#define SHARED_HTTP_HEADER_H
#include "config.h"
#include <string>
#include <vector>
#include "MC2SimpleString.h"
class SharedHttpHeader {
private:
/* Converts multiple whitespaces to single */
void trimSpaces();
public:
/* Constructor */
SharedHttpHeader();
/* Destructor */
~SharedHttpHeader();
/**
* Resets the header to start state.
*/
void reset();
/**
* Show the SharedHttpHeader the bytes that have been
* read from a socket. The SharedHttpHeader will return
* the number of bytes consumed. If the header is complete
* (i.e. the double CR/LF pair has been received) the
* SharedHttpHeader will consume any more bytes, they are
* part of the body of the message.
* @param bytes Bytes to add to the header.
* @param len Max number of bytes to read into the header.
* @return Number of bytes consumed or -1 if an error occurs.
*/
int addBytes(const unsigned char* bytes, int len);
/**
* Returns true if the header is fully read.
*/
bool complete() const;
/**
* Returns the value of the headerline
* matching the key. (Apart from the first line).
* @param key String to look for among the headers, e.g.
* "Content-Length". Shall not contain the ":".
* @return Value or NULL if not present.
*/
const char* getHeaderValue(const char* key) const;
/**
* Parses the first line containing
* "HTTP/1.X YYY STR" line and returns YYY.
* @return The status code of the first line of http-data.
*/
const int getStatusCode() const;
/* Variables required for state information. */
private:
/* This string holds the header after it is completed */
std::string headerBuffer;
/* IS true, if header is completely done */
bool isComplete;
/// Holds the header values to avoid the previous leak in getHeaderValue
std::vector<char*> m_stringsToFree;
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
86
]
]
]
|
c86dbac9ec920db87028850ba5f461816d2b23f9 | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /SMDK/TransCritical/TTechWOR/TTWORClassifier.cpp | 954ad7994e648dd51c3646189dd35448886b2414 | []
| no_license | abcweizhuo/Test3 | 0f3379e528a543c0d43aad09489b2444a2e0f86d | 128a4edcf9a93d36a45e5585b70dee75e4502db4 | refs/heads/master | 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,768 | cpp | //================== SysCAD - Copyright Kenwalt (Pty) Ltd ===================
// New Precipitation model Transcritical Technologies Pty Ltd Feb 05
// Time-stamp: <2006-07-04 09:54:09 Rod Stephenson Transcritical Pty Ltd>
// Copyright (C) 2005 by Transcritical Technologies Pty Ltd and KWA
//===========================================================================
#include "stdafx.h"
#include "TTWORClassifier.h"
//===========================================================================
// Define the species in the particular precipiation model...
enum ClassifierMethod {CM_Molerus, CM_Lynch, CM_Plitt };
const long idFeed = 0;
const long idOFlow = 1;
const long idUFlow = 2;
static MInOutDefStruct s_IODefs[]=
{
// Desc; Name; Id; Rqd; Max; CnId, FracHgt; Options;
{ "Feed", "Feed1", idFeed , 1, 5, 0, 1.0f, MIO_In |MIO_Material },
{ "Overflow", "Overflow", idOFlow, 1, 1, 0, 1.0f, MIO_Out|MIO_Material },
{ "Underflow", "Underflow", idUFlow, 1, 1, 0, 1.0f, MIO_Out|MIO_Material },
{ NULL },
};
double Drw_CClassifier[] =
{
MDrw_Poly, -5,10, -5,-10, 5,-10, 5,10,
MDrw_End
};
//---------------------------------------------------------------------------
DEFINE_TRANSFER_UNIT(CClassifier, "Classifier", DLL_GroupName)
void CClassifier_UnitDef::GetOptions()
{
SetDefaultTag("PC");
SetDrawing("Tank", Drw_CClassifier);
SetTreeDescription("Worsley:Classifier");
SetDescription("TODO: Worsley Precip Model");
SetModelSolveMode(MSolveMode_Probal);
SetModelGroup(MGroup_Alumina);
SetModelLicense(MLicense_HeatExchange|MLicense_Alumina);
};
//---------------------------------------------------------------------------
void CClassifier::BuildDataFields()
{
static MDDValueLst DDB1[]={
{CM_Molerus, "Molerus" },
{CM_Lynch, "Lynch"},
{CM_Plitt, "Plitt"},
{0}};
static MDDValueLst iPSDDisp[] = {
{0, "Mass", 0},
{1, "Fraction", 0},
{2, "Number", 0},
NULL
};
DD.Text ("");
// #ifdef TTDEBUG
// DD.CheckBox("TTDBG", "", &bTTDebug, MF_PARAMETER);
// #endif
DD.Long("PSD.Display", "", &iPSD, MF_PARAMETER, iPSDDisp);
DD.CheckBox("On", "", &bOnline, MF_PARAMETER|MF_SET_ON_CHANGE);
DD.Long ("ClassMethod", "", &iClassMethod , MF_PARAMETER|MF_SET_ON_CHANGE, DDB1);
DD.Text ("Requirements");
DD.Double("TankVol", "", &dTankVol ,MF_PARAMETER, MC_Vol("m^3"));
DD.Text ("");
DD.Text ("Results Tank");
DD.Double("ExcessBypassUFlow", "", &m_dByPass ,MF_PARAMETER, MC_Frac("%"));
DD.Double("MeasureSharpness", "", &m_dSharp_Index ,MF_PARAMETER, MC_);
DD.CheckBox("CalcCutSize", "", &bCalcCut_Size ,MF_PARAMETER | MF_SET_ON_CHANGE);
DD.Show(bCalcCut_Size);
DD.Double("Viscosity", "", &dViscosity, MF_RESULT, MC_Visc);
DD.Double("ViscCorrection", "", &tTerm, MF_RESULT, MC_);
DD.Show();
DD.Double("CutSize", "", &m_dCut_Size , (bCalcCut_Size ? MF_RESULT : MF_PARAMETER), MC_);
DD.Double("LiquorToUFlow", "", &m_dSlurry_split ,MF_PARAMETER, MC_Frac("%"));
DD.Double("OverPassOFlow", "", &m_dOver_pass ,MF_PARAMETER, MC_Frac("%"));
DD.Double("L_0", "", &m_dL0 ,MF_PARAMETER, MC_);
DD.Double("SolidsSplit", "", &m_dxS ,MF_RESULT, MC_Frac("%"));
DD.Double("Efficiency", "", &m_dEff ,MF_RESULT, MC_);
//std::string s;
DD.Show();
// DD.Long("PSD.Display", "", &iPSD, MF_PARAMETER, iPSDDisp);
DD.Page("Inlet");
const int NumSpecies = gs_MVDefn.Count();
DD.Page("Size In");
for (int i=0; i<=nClasses; i++) {
std::stringstream os;
os << "Size " << std::setw(3) << i << std::setw(12) << L[i] << " " << Lav[i] ;
// s=os.str();
DD.Double(os.str().c_str(), "", dd[3]+i, MF_RESULT|MF_NO_FILING, MC_None);
}
DD.Page("Size OF");
for (int i=0; i<=nClasses; i++) {
std::stringstream os;
os << "Size " << std::setw(3) << i;
DD.Double(os.str().c_str(), "", dd[4]+i, MF_RESULT|MF_NO_FILING, MC_None);
}
DD.Page("Size UF");
for (int i=0; i<=nClasses; i++) {
std::stringstream os;
os << "Size " << std::setw(3) << i;
DD.Double(os.str().c_str(), "", dd[5]+i, MF_RESULT|MF_NO_FILING, MC_None);
}
DD.Page("Split.uf.of");
for (int i=0; i<=nClasses; i++) {
std::stringstream os;
os << "Size " << std::setw(3) << i;
DD.Double(os.str().c_str(), "", dd[6]+i, MF_RESULT|MF_NO_FILING, MC_None);
}
DD.Page("Efficiency");
for (int i=0; i<=nClasses; i++) {
std::stringstream os;
os << "Size " << std::setw(3) << i;
DD.Double(os.str().c_str(), "", dd[7]+i, MF_RESULT|MF_NO_FILING, MC_None);
}
}
//---------------------------------------------------------------------------
bool CClassifier::ValidateDataFields()
{//ensure parameters are within expected ranges
return true;
}
CClassifier::CClassifier(MUnitDefBase *pUnitDef, TaggedObject * pNd) :
MBaseMethod(pUnitDef, pNd)
{ //default values...
// x=new double[4];
// xo = new double[4];
bOnline = 1;
m_dByPass = 0.05;
m_dSharp_Index = 5.0 ;
m_dCut_Size = 100.0;
m_dSlurry_split = .05;
m_dOver_pass = 0.0;
m_dL0 = 0.0;
L[0] = 1.58740105;
for (int i=1; i<=nClasses; i++) L[i] = L[i-1]*1.25992105;
for (int i=0; i<=nClasses; i++) Lav[i] = L[i]*1.12992105;
}
//---------------------------------------------------------------------------
CClassifier::~CClassifier()
{
// delete[] x;
// delete[] xo;
}
//---------------------------------------------------------------------------
void CClassifier::Init()
{
SetIODefinition(s_IODefs);
}
//---------------------------------------------------------------------------
const long OM_Simple = 0;
const long OM_Condensing = 1;
double Viscosity_cp(MStream & s) {
MIBayer & sB=s.IF<MIBayer>(false);
double T = 25.0;
double C = sB.CausticConc(25+273.15);
double A = sB.AluminaConc(25+273.15);
double LVis = -0.11801 + 0.00413*C - 7.8966*1e-5*C*T + 3.712*1e-7*C*T*T
+ 0.0015685*A + 8.679199e-06*A*C - 2.436e-05*A*T;
// + 0.0018944*(S-C) + 0.0070503*TOC + 0.002471*Cl+ 0.018308*SO4;
return pow(10., LVis);
}
void CClassifier::DoClassifier(MStream &OFlow, MStream &UFlow)
{
double pVol_U = 0.0, pVol_O=0.0, mO=0.0, mU=0.0;
double eff, ab, nl[nClasses+1][2];
double xS;
MIPSD & FeedPSD = Feed.IF<MIPSD>(false);
MIPSD & OFPSD = OFlow.IF<MIPSD>(false);
MIPSD & UFPSD = UFlow.IF<MIPSD>(false);
if (bCalcCut_Size) {
double visc = Viscosity_cp(Feed);
dViscosity = visc/1000.;
double grho = 9.81*(2420-Feed.Density(MP_All));
double t = sqrt(visc/grho);
tTerm = t;
}
for (int i=0; i<=nClasses; i++) {
if (m_dL0==0) ab=m_dByPass; else ab=m_dByPass*(1-Lav[i]/m_dL0);
switch (iClassMethod) {
case CM_Molerus:
eff = ab + (1-ab) * (1-m_dOver_pass) /
( 1 + pow(Lav[i]/m_dCut_Size, -m_dSharp_Index) );
break;
case CM_Lynch:
eff = ab + (1-ab) * (1-m_dOver_pass) *
( exp(m_dSharp_Index*Lav[i]/m_dCut_Size) - 1 ) /
( exp(m_dSharp_Index) + exp(m_dSharp_Index*Lav[i]/m_dCut_Size) - 2 );
break;
case CM_Plitt:
eff = ab + (1-ab) * (1-m_dOver_pass) *
( 1 - exp(-0.693147*pow(Lav[i]/m_dCut_Size, m_dSharp_Index)) );
break;
}
nl[i][0]=FeedPSD.getFrac(i)*eff;
nl[i][1]=FeedPSD.getFrac(i)*(1-eff);
mU += nl[i][0];
mO += nl[i][1];
dd[7][i] = eff;
}
if (mO+mU !=0.0)
xS = mU/(mU+mO);
else
xS = 1.0;
m_dxS = xS;
m_dEff = eff;
UFlow.SetF(Feed, MP_Liq, m_dSlurry_split);
UFlow.AddF(Feed, MP_Sol, xS);
OFlow.SetF(Feed, MP_Liq, 1.-m_dSlurry_split);
OFlow.AddF(Feed, MP_Sol, 1.-xS);
for (int i=0; i<=nClasses; i++) {
if (xS<1.0)
OFPSD.putFrac(i, nl[i][1]/(1-xS));
UFPSD.putFrac(i, nl[i][0]/xS);
}
OFPSD.Normalise();
UFPSD.Normalise();
}
void CClassifier::EvalProducts()
{
try {
FlwIOs.AddMixtureIn_Id(Feed, idFeed);
MStream & OFlow = FlwIOs[FlwIOs.First[idOFlow]].Stream; //Reference to the overflow out stream
MStream & UFlow = FlwIOs[FlwIOs.First[idUFlow]].Stream; //Reference to the undrflow out stream
OFlow = Feed;
UFlow = Feed;
OFlow.SetF(Feed, MP_All, .5);
UFlow.SetF(Feed, MP_All, .5);
bool streamOK=((Feed.Mass()>1.0e-3) && (Feed.Mass(MP_Sol)>1.0e-6));
MIBayer & ProdB=OFlow.IF<MIBayer>(false); // Do the checks up front
Log.SetCondition(IsNothing(ProdB), 1, MMsg_Warning, "Bad Feed Stream - Not BATC Bayer Model");
MIPSD & ProdPSD = OFlow.IF<MIPSD>(false);
Log.SetCondition(IsNothing(ProdPSD), 1, MMsg_Warning, "Bad Feed Stream - No PSD Available");
if (IsNothing(ProdB) || IsNothing(ProdPSD)) streamOK = false;
if (bOnline && streamOK) { // Online and have Bayer and SSA properties...
DoClassifier(OFlow, UFlow);
displayPSD(Feed, 3);
displayPSD(OFlow, 4);
displayPSD(UFlow, 5);
} else { // Just tidy up and put some sensible stuff in the results...
Log.Message(MMsg_Warning, "Bad Feed.... Classifier");
}
}
catch (MMdlException &e)
{
Log.Message(MMsg_Error, e.Description);
}
catch (MFPPException &e)
{
e.ClearFPP();
Log.Message(MMsg_Error, e.Description);
}
catch (MSysException &e)
{
Log.Message(MMsg_Error, e.Description);
}
catch (...)
{
Log.Message(MMsg_Error, "Some Unknown Exception occured");
}
}
//--------------------------------------------------------------------------
void CClassifier::ClosureInfo(MClosureInfo & CI)
{//ensure heat balance
if (CI.DoFlows())
{
// CI.AddPowerIn(0, -dThermalLoss);
}
}
void CClassifier::displayPSD(MStream &ms, int scrn)
{
MIPSD & mpsd = ms.IF<MIPSD>(false); /// Does the mud stream have PSD...
int ic = mpsd.getSizeCount();
if (ic>40) ic=40;
double x;
for (int i=0; i<ic; i++) {
switch (iPSD) {
case 0:
x = mpsd.getMass(i);
break;
case 1:
x = mpsd.getFrac(i);
break;
case 2:
x = mpsd.getMass(i);
}
dd[scrn][i]=x;
}
}
| [
"[email protected]"
]
| [
[
[
1,
417
]
]
]
|
14e95b61f8060a31a9f350b942249e68956a2bda | 7a310d01d1a4361fd06b40a74a2afc8ddc23b4d3 | /src/DonutGeckoHistoryBar.h | 5ceca09d852d855dfeb620cfc93d7f6e7dfce90b | []
| no_license | plus7/DonutG | b6fec6111d25b60f9a9ae5798e0ab21bb2fa28f6 | 2d204c36f366d6162eaf02f4b2e1b8bc7b403f6b | refs/heads/master | 2020-06-01T15:30:31.747022 | 2010-08-21T18:51:01 | 2010-08-21T18:51:01 | 767,753 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 4,149 | h | #pragma once
#include "resource.h"
#include "Mtl.h"
#include "MtlCtrls.h"
#include "Donut.h"
#include <nsINavHistoryService.h>
template <class T>
class CPlacesTreeViewCtrlImpl :
public CWindowImpl<T, CTreeViewCtrl>,
public nsINavHistoryResultViewer
{
public:
enum SortingType {
FIRST_VISIT, LAST_VISIT, DATE_AND_SITE, SITE, DATE
};
DECLARE_WND_SUPERCLASS( NULL, CTreeViewCtrl::GetWndClassName() )
CPlacesTreeViewCtrlImpl()
:m_sortingType(DATE)
{
m_historySvc = do_GetService("@mozilla.org/browser/nav-history-service;1");
NS_ADDREF(this);
}
~CPlacesTreeViewCtrlImpl()
{
m_result->SetViewer(NULL);
}
public:
// Message map and handlers
BEGIN_MSG_MAP(CPlacesTreeViewCtrlImpl)
MESSAGE_HANDLER ( WM_CREATE , OnCreate )
END_MSG_MAP()
NS_DECL_ISUPPORTS
NS_DECL_NSINAVHISTORYRESULTVIEWER
LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
DoSearch(_T(""));
bHandled = FALSE;
return 1;
}
void MakeChild(HTREEITEM parent, nsINavHistoryContainerResultNode * parentNode){
PRUint32 cnt;
parentNode->GetChildCount(&cnt);
for(unsigned int i = 0;i<cnt;i++){
nsCOMPtr<nsINavHistoryResultNode> child;
parentNode->GetChild(i, getter_AddRefs(child));
nsEmbedCString title;
child->GetTitle(title);
HTREEITEM item =
InsertItem(NS_ConvertUTF8toUTF16(title).get(), parent, TVI_LAST);
nsCOMPtr<nsINavHistoryContainerResultNode> container = do_QueryInterface(child);
if(container){
container->SetContainerOpen(PR_TRUE);
MakeChild(item, container);
}
}
}
void DoSearch(const CString& str){
nsCOMPtr<nsINavHistoryQuery> query;
nsCOMPtr<nsINavHistoryQueryOptions> options;
m_historySvc->GetNewQuery(getter_AddRefs(query));
m_historySvc->GetNewQueryOptions(getter_AddRefs(options));
options->SetResultType(nsINavHistoryQueryOptions::RESULTS_AS_DATE_SITE_QUERY);//RESULTS_AS_DATE_QUERY);
m_historySvc->ExecuteQuery(query, options, getter_AddRefs(m_result));
m_result->SetViewer(this);
nsCOMPtr<nsINavHistoryContainerResultNode> root;
m_result->GetRoot(getter_AddRefs(root));
root->SetContainerOpen(PR_TRUE);
MakeChild(TVI_ROOT, root);
}
void SetSortingType(int type){
m_sortingType = type;
}
int GetSortingType(){
return m_sortingType;
}
private:
nsCOMPtr<nsINavHistoryService> m_historySvc;
nsCOMPtr<nsINavHistoryResult> m_result;
int m_sortingType;
//CString m_keyword;
};
class CPlacesTreeViewCtrl : public CPlacesTreeViewCtrlImpl<CPlacesTreeViewCtrl> {
public:
DECLARE_WND_SUPERCLASS( _T("PlacesTreeViewCtrl"), GetWndClassName() )
};
#define PLACESTREEVIEW_CTOR() \
template <class T> \
CPlacesTreeViewCtrlImpl<T>
#define PLACESTREEVIEW(rettype) \
template <class T> \
rettype CPlacesTreeViewCtrlImpl<T>
class CDonutGeckoHistoryBar
: public CDialogImpl<CDonutGeckoHistoryBar>
, public CDialogResize<CDonutGeckoHistoryBar>
, public CWinDataExchange<CDonutGeckoHistoryBar>
{
public:
enum { IDD = IDD_GECKOHISTORY_FORM };
private:
// Data members
// Windows
public:
// Ctor
CDonutGeckoHistoryBar();
// Overrides
// Methods
BYTE PreTranslateMessage(MSG *pMsg);
public:
// Message map and handlers
BEGIN_MSG_MAP(CDonutGeckoHistoryBar)
MESSAGE_HANDLER(WM_INITDIALOG , OnInitDialog)
MESSAGE_HANDLER(WM_DESTROY , OnDestroy)
CHAIN_MSG_MAP( CDialogResize<CDonutGeckoHistoryBar> )
END_MSG_MAP()
public:
// Dlg resize map
BEGIN_DLGRESIZE_MAP( CDonutGeckoHistoryBar )
DLGRESIZE_CONTROL( IDC_PLACES_TREEVIEW, DLSZ_SIZE_X | DLSZ_SIZE_Y )
END_DLGRESIZE_MAP()
// DDX map
BEGIN_DDX_MAP( CDonutGeckoHistoryBar )
END_DDX_MAP()
private:
LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL & /*bHandled*/);
LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL & /*bHandled*/);
CPlacesTreeViewCtrl m_treeview;
// Implementation
void _GetData();
void _SetData();
void _GetProfile();
void _WriteProfile();
void _OnItemOpen(int nIndex);
}; | [
"[email protected]"
]
| [
[
[
1,
164
]
]
]
|
40a7c3810a3dbe3b37d1e86d610b11434834dfeb | c10296a1631c01ba470e0e240424dc938208ceb4 | /MediaInfo/ZenLib/Source/ZenLib/ZtringListList.cpp | f18db04115b64a8c3151b028c51a9c5a6c683587 | [
"LicenseRef-scancode-unknown-license-reference",
"Zlib"
]
| permissive | kicker12/scripts | 36b8eb1ba6b5f2fdac8b9fe1e6ff355803fbaeb3 | dfe8613ed64a89120c04782ae388d54174c3b663 | refs/heads/master | 2020-12-29T03:19:36.399190 | 2009-04-05T09:08:24 | 2009-04-05T09:08:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,617 | cpp | // ZenLib::ZtringListList - More methods for std::vector<std::vector<std::(w)string>>
// Copyright (C) 2002-2006 Jerome Martinez, [email protected]
//
// 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 <wx/wxprec.h>
#ifdef __BORLANDC__
#pragma hdrstop
#endif
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <wx/strconv.h>
#include <algorithm>
#include "ZenLib/ZtringListList.h"
using std::vector; //Visual C++ 6 patch
//---------------------------------------------------------------------------
namespace ZenLib
{
//***************************************************************************
// Constructors/Destructor
//***************************************************************************
//---------------------------------------------------------------------------
// Constructors
ZtringListList::ZtringListList()
{
Separator[0]=_T("\r\n");
Separator[1]=_T(";");
Quote=_T("\"");
Max[0]=Error;
Max[1]=Error;
}
ZtringListList::ZtringListList(const ZtringListList &Source)
{
Separator[0]=Source.Separator[0];
Separator[1]=Source.Separator[1];
Quote=Source.Quote;
reserve(Source.size());
for (intu Pos=0; Pos<Source.size(); Pos++)
push_back(Source[Pos]);
}
ZtringListList::ZtringListList(const Ztring &Source)
{
Separator[0]=_T("\r\n");
Separator[1]=_T(";");
Quote=_T("\"");
Max[0]=Error;
Max[1]=Error;
Write(Source.c_str());
}
ZtringListList::ZtringListList(const Char *Source)
{
Separator[0]=_T("\r\n");
Separator[1]=_T(";");
Quote=_T("\"");
Max[0]=Error;
Max[1]=Error;
Write(Source);
}
#ifdef _UNICODE
ZtringListList::ZtringListList (const char* S)
{
Separator[0]=_T("\r\n");
Separator[1]=_T(";");
Quote=_T("\"");
Max[0]=Error;
Max[1]=Error;
Write(wxConvUTF8.cMB2WC(S).data());
}
#endif
//***************************************************************************
// Operators
//***************************************************************************
//---------------------------------------------------------------------------
//Operator ==
bool ZtringListList::operator== (const ZtringListList &Source) const
{
return (Read()==Source.Read());
}
//---------------------------------------------------------------------------
//Operator !=
bool ZtringListList::operator!= (const ZtringListList &Source) const
{
return (!(Read()==Source.Read()));
}
//---------------------------------------------------------------------------
// Operator +=
ZtringListList &ZtringListList::operator+= (const ZtringListList &Source)
{
reserve(size()+Source.size());
for (size_type Pos=0; Pos<Source.size(); Pos++)
{
push_back(Source[Pos]);
operator[](size()-1).Separator_Set(0, Separator[1]);
operator[](size()-1).Quote_Set(Quote);
operator[](size()-1).Max_Set(0, Max[1]);
}
return *this;
}
//---------------------------------------------------------------------------
// Operator =
ZtringListList &ZtringListList::operator= (const ZtringListList &Source)
{
clear();
reserve(Source.size());
for (size_type Pos=0; Pos<Source.size(); Pos++)
{
push_back(Source[Pos]);
operator[](size()-1).Separator_Set(0, Separator[1]);
operator[](size()-1).Quote_Set(Quote);
operator[](size()-1).Max_Set(0, Max[1]);
}
return *this;
}
//---------------------------------------------------------------------------
// Operatorr ()
ZtringList &ZtringListList::operator() (size_type Pos0)
{
//Integrity
if (Pos0>=size())
Write(_T(""), Pos0);
return operator[](Pos0);
}
Ztring &ZtringListList::operator() (size_type Pos0, size_type Pos1)
{
//Integrity
if (Pos0>=size())
Write(_T(""), Pos0);
return operator[](Pos0).operator()(Pos1);
}
Ztring &ZtringListList::operator() (const Ztring &Pos0, size_type Pos0_1, size_type Pos1)
{
size_type Pos=Find(Pos0, Pos0_1, 0, _T("=="), Ztring_CaseSensitive);
if (Pos==Error)
{
Write(Pos0, size(), Pos0_1);
Pos=size()-1;
}
return operator[](Pos).operator()(Pos1);
}
//***************************************************************************
// In/Out
//***************************************************************************
//---------------------------------------------------------------------------
// Read
Ztring ZtringListList::Read () const
{
//Integrity
if (size()==0)
return _T("");
Ztring ToReturn;
size_type Size=size()-1;
for (size_type Pos0=0; Pos0<Size; Pos0++)
ToReturn+=Read(Pos0)+Separator[0];
ToReturn+=Read(Size);
//Delete all useless separators at the end
if(ToReturn.size()>0 && Separator[0].size() && ToReturn(ToReturn.size()-1)==Separator[0][Separator[0].size()-1]) //Optimize speed
while (ToReturn.find(Separator[0].c_str(), ToReturn.size()-Separator[0].size())!=std::string::npos)
ToReturn.resize(ToReturn.size()-Separator[0].size());
return ToReturn;
}
Ztring ZtringListList::Read (size_type Pos0) const
{
//Integrity
if (Pos0>=size())
return _T("");
return operator[](Pos0).Read();
}
Ztring ZtringListList::Read (size_type Pos0, size_type Pos1) const
{
//Integrity
if (Pos0>=size())
return _T("");
return operator[](Pos0).Read(Pos1);
}
Ztring ZtringListList::Read (const Ztring &Pos0, Ztring Default, size_type Pos0_1, size_type Pos1) const //Lecture d'un champs en position 0 avec une option par defaut
{
size_type Pos=Find(Pos0, Pos0_1);
if (Pos==Error)
return Default;
return Read(Pos, Pos1);
}
Ztring ZtringListList::Read1 (size_type Pos1) const
{
Ztring ToReturn;
size_type Size=size()-1;
for (size_type Pos=0; Pos<Size; Pos++)
ToReturn+=operator[](Pos).Read(Pos1)+Separator[0];
ToReturn+=operator[](Size).Read(Pos1);
//Delete all useless separators at the end
if(ToReturn(ToReturn.size()-1)==Separator[0][Separator[0].size()-1]) //Optimize speed
while (ToReturn.find(Separator[0].c_str(), ToReturn.size()-Separator[0].size())!=std::string::npos)
ToReturn.resize(ToReturn.size()-Separator[0].size());
return ToReturn;
}
//---------------------------------------------------------------------------
// Write
void ZtringListList::Write(const Ztring &ToWrite)
{
clear();
if (!&ToWrite || !ToWrite.size())
return;
size_type PosC=0;
bool Fini=false;
Ztring C1;
ZtringList ZL1;
ZL1.Separator_Set(0, Separator[1]);
ZL1.Quote_Set(Quote);
ZL1.Max_Set(0, Max[1]);
do
{
C1=ToWrite.SubString(_T(""), Separator[0], PosC, Ztring_AddLastItem);
ZL1.Write(C1);
push_back(ZL1);
PosC+=C1.size()+Separator[0].size();
if (PosC>=ToWrite.size())
Fini=true;
}
while (!Fini);
}
void ZtringListList::Write(const ZtringList &ToWrite, size_type Pos)
{
//Integrity
if (Pos==Error)
return;
//Writing
if (Pos>=size())
{
//Reservation de ressources
if (!capacity())
reserve(1);
while (Pos>=capacity())
reserve(capacity()*2);
while (Pos>size())
push_back (_T(""));
push_back(ToWrite);
}
else
operator[](Pos)=ToWrite;
}
void ZtringListList::Write(const Ztring &ToWrite, size_type Pos0, size_type Pos1)
{
if (Pos0>=size())
Write(_T(""), Pos0);
operator[](Pos0).Write(ToWrite, Pos1);
}
void ZtringListList::push_back (const ZtringList &ToAdd)
{
vector<ZtringList>::push_back(ToAdd); //Visual C++ 6 patch, should be std::vector
operator[](size()-1).Separator_Set(0, Separator[1]);
operator[](size()-1).Quote_Set(Quote);
operator[](size()-1).Max_Set(0, Max[1]);
}
void ZtringListList::push_back (const Ztring &ToAdd)
{
ZtringList ZL1;
ZL1.Separator_Set(0, Separator[1]);
ZL1.Quote_Set(Quote);
ZL1.Max_Set(0, Max[1]);
ZL1.Write(ToAdd);
push_back(ZL1);
}
//---------------------------------------------------------------------------
// Insert
void ZtringListList::Insert1 (const Ztring &ToInsert, size_type Pos1)
{
for (size_type Pos0=0; Pos0<size(); Pos0++)
operator[](Pos0).Insert(ToInsert, Pos1);
}
//---------------------------------------------------------------------------
// Delete
void ZtringListList::Delete (const Ztring &ToFind, size_type Pos1, const Ztring &Comparator, ztring_t Options)
{
size_type Pos0=0;
while ((Pos0=Find(ToFind, Pos1, Pos0, Comparator, Options))!=Error)
operator [] (Pos0).Delete(Pos1);
}
void ZtringListList::Delete1 (size_type Pos1)
{
for (size_type Pos0=0; Pos0<size(); Pos0++)
operator [] (Pos0).Delete(Pos1);
}
//***************************************************************************
// Edition
//***************************************************************************
//---------------------------------------------------------------------------
// Swap
void ZtringListList::Swap (size_type Pos0_A, size_type Pos0_B)
{
//Integrity
size_type Pos_Max;
if (Pos0_A<Pos0_B)
Pos_Max=Pos0_B;
else
Pos_Max=Pos0_A;
if (Pos_Max>=size())
Write(_T(""), Pos_Max);
operator [] (Pos0_A).swap(operator [] (Pos0_B));
}
void ZtringListList::Swap1 (size_type Pos1_A, size_type Pos1_B)
{
for (size_type Pos0=0; Pos0<size(); Pos0++)
operator () (Pos0, Pos1_A).swap(operator () (Pos0, Pos1_B));
}
//---------------------------------------------------------------------------
// Sort
void ZtringListList::Sort(size_type, ztring_t)
{
std::stable_sort(begin(), end());
return;
}
//---------------------------------------------------------------------------
// Find
Ztring::size_type ZtringListList::Find (const Ztring &ToFind, size_type Pos1, size_type Pos0, const Ztring &Comparator, ztring_t Options) const
{
while ( Pos0<size()
&& ( Pos1>=at(Pos0).size()
|| !at(Pos0).at(Pos1).Compare(ToFind, Comparator, Options)))
Pos0++;
if (Pos0>=size())
return Error;
return Pos0;
}
Ztring ZtringListList::FindValue (const Ztring &ToFind, size_type Pos1Value, size_type Pos1, size_type Pos0Begin, const Ztring &Comparator, ztring_t) const
{
size_type Pos0=Find(ToFind, Pos1, Pos0Begin, Comparator);
if (Pos0==Error)
return _T("");
return Read(Pos0, Pos1Value);
}
ZtringListList ZtringListList::SubSheet (const Ztring &ToFind, size_type Pos1, size_type Pos0, const Ztring &Comparator, ztring_t) const
{
ZtringListList ToReturn;
ToReturn.Separator[0]=Separator[0];
ToReturn.Separator[1]=Separator[1];
ToReturn.Quote=Quote;
Pos0--;
do
{
Pos0=Find(ToFind, Pos1, Pos0+1, Comparator);
ToReturn.push_back(Read(Pos0));
}
while (Pos0!=Error);
return ToReturn;
}
//***************************************************************************
// Configuration
//***************************************************************************
//---------------------------------------------------------------------------
// Separator
void ZtringListList::Separator_Set (size_type Level, const Ztring &NewSeparator)
{
if (Level>1)
return;
Separator[Level]=NewSeparator;
if (Level==1)
for (size_type Pos0=0; Pos0<size(); Pos0++)
operator () (Pos0).Separator_Set(0, Separator[1]);
}
//---------------------------------------------------------------------------
// Quote
void ZtringListList::Quote_Set (const Ztring &NewQuote)
{
Quote=NewQuote;
for (size_type Pos0=0; Pos0<size(); Pos0++)
operator () (Pos0).Quote_Set(Quote);
}
//---------------------------------------------------------------------------
// Max
void ZtringListList::Max_Set (size_type Level, size_type NewMax)
{
if (Level>1 || NewMax==0)
return;
Max[Level]=NewMax;
if (Level==1)
for (size_type Pos0=0; Pos0<size(); Pos0++)
operator () (Pos0).Max_Set(0, Max[1]);
}
} //namespace
| [
"[email protected]"
]
| [
[
[
1,
471
]
]
]
|
6f636ec2efe109e75e95eaf07e2a2ab0cf4ffd1f | 3cd7d37bbc0d8767dcdc0d104c8c445107e38f36 | /acmap.cpp | 717dba25a656bbfe8a1a4f7de42f70bab6bf3310 | []
| no_license | farihi/gpsturbo | 8978fa37d4c164cbdd85091ec3feeb9aa1ff2662 | a56634b63a9022c48f1e529385b6926366da1fda | refs/heads/master | 2021-01-10T12:09:32.768016 | 2010-06-30T23:35:18 | 2010-06-30T23:35:18 | 44,369,116 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,071 | cpp | /*********************************************************************************/
/* GPSTurbo */
/* */
/* Programmed by Kevin Pickell */
/* */
/* http://www.scale18.com/cgi-bin/page/gpsturbo.html */
/* */
/* GPSTurbo is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; version 2. */
/* */
/* GPSTurbo 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. */
/* */
/* http://www.gnu.org/licenses/gpl.txt */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with GPSTurbo; if not, write to the Free Software */
/* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/* */
/*********************************************************************************/
#include "gpsturbo.h"
#include "acmap.h"
#if 0
#define TILEW 3200
#define TILEH 1600
/* the tile format is a grid that is 12 tiles wide by 10 tiles tall */
/* each tile is subdivided into 16 smaller tiles and then each child */
/* tile is again subdivided into 16 pieces */
/* there are only 2 levels of tiles, the rest are drawn using scaling */
enum
{
MAPLEVEL_1,
MAPLEVEL_2
};
typedef struct
{
int maplevel;
int rshift;
}ACLEVEL_DEF;
ACLEVEL_DEF aclevels[MAXACZOOM-MINACZOOM]={
{MAPLEVEL_1,0},
{MAPLEVEL_1,1},
{MAPLEVEL_1,2},
{MAPLEVEL_1,3},
{MAPLEVEL_2,2},
{MAPLEVEL_2,3},
{MAPLEVEL_2,4},
{MAPLEVEL_2,5}};
ACGPXMap::ACGPXMap()
{
int i;
int tw,th;
m_copyright.Sprintf("%c Government of Canada",169);
SetZoomLevels(MINACZOOM,MAXACZOOM);
SetTileSize(TILEW>>3,TILEH>>3);
tw=(12*16)*TILEW>>5;
th=(10*16)*TILEH>>5;
for(i=MINACZOOM;i<MAXACZOOM;++i)
{
SetSize(i,tw,th);
tw<<=1;
th<<=1;
}
}
ACGPXMap::~ACGPXMap()
{
m_image.Purge();
}
int ACGPXMap::RShift(int value,int numbits)
{
if(numbits==0)
return(value);
if(numbits>0)
return(value>>numbits);
return(value<<(-numbits));
}
void ACGPXMap::ToMap(GPXCoord *c,int *sx,int *sy)
{
int z=GetZoom();
sx[0]=(int)((c->GetLon()+144.0f)*RShift(TILEW,12-z)); /* .5 degrees per tile */
sy[0]=(int)((80-c->GetLat())*RShift(TILEH,11-z)); /* .25 degrees per tile */
}
/* convert from screen+scroll values to lon/lat */
void ACGPXMap::FromMap(int sx,int sy,GPXCoord *c)
{
int z=GetZoom();
c->Set(80.0f-((double)sy/RShift(TILEW,12-z)),((double)sx/RShift(TILEW,12-z))-144.0f);
}
/* draw tile at this position */
int ACGPXMap::DrawTile(int tx,int ty)
{
kGUIString hstr;
kGUIString fn;
char xch[]={"mnoplkjiefghdcba"};
int xin[]={13,14,15,16,12,11,10,9,5,6,7,8,4,3,2,1};
int ftx,fty;
int xgroup,ygroup,lgroup,ngroup;
/* convert grid number to a filename */
int z=GetZoom();
ACLEVEL_DEF *acl;
acl=&(aclevels[z-MINACZOOM]);
ftx=tx>>acl->rshift;
fty=ty>>acl->rshift;
if(acl->maplevel==MAPLEVEL_1)
{
xgroup=11-(ftx>>2);
ygroup=9-(fty>>2);
lgroup=((ftx)&3)+(((fty)&3)<<2);
hstr.Sprintf("%02dz%02d%d%c",xgroup,xgroup,ygroup,xch[lgroup]);
}
else
{
xgroup=11-(ftx>>4);
ygroup=9-(fty>>4);
lgroup=((ftx>>2)&3)+(((fty>>2)&3)<<2);
ngroup=(ftx&3)+((fty&3)<<2);
hstr.Sprintf("%02dz%02d%d%c%02d",xgroup,xgroup,ygroup,xch[lgroup],xin[ngroup]);
}
fn.Sprintf(TOPOMAPDIR "t%s.gif",hstr.GetString());
m_image.SetFilename(fn.GetString());
/* if image was not found on harddrive then try downloading it if user is online */
if(m_image.IsValid()==false)
{
if(g_isonline==true)
{
kGUIString gurl;
DataHandle dh;
kGUIDownloadEntry dle;
kGUIString hx;
kGUIString busytitle;
hx.SetString(hstr.GetString());
hx.Replace("z","/");
if(acl->maplevel==MAPLEVEL_1)
gurl.Sprintf("http://toporama.cits.rncan.gc.ca/images/b250k/%s.gif",hx.GetString());
else
gurl.Sprintf("http://toporama.cits.rncan.gc.ca/images/b50k/%s.gif",hx.GetString());
dh.SetFilename(&fn);
dle.DownLoad(&dh,&gurl);
/* since it is now downloaded try again */
m_image.SetFilename(fn.GetString());
}
}
if(m_image.IsValid()==false)
return(TILE_ERROR); /* tile not found! */
switch(acl->rshift)
{
case 0:
m_image.SetScale(1.0f/8.0f,1.0f/8.0f);
m_image.Draw(0,0,0);
break;
case 1:
m_image.SetScale(1.0f/4.0f,1.0f/4.0f);
m_image.Draw(0,-((tx&1)*(TILEW>>3)),-((ty&1)*(TILEH>>3)));
break;
case 2:
m_image.SetScale(1.0f/2.0f,1.0f/2.0f);
m_image.Draw(0,-((tx&3)*(TILEW>>3)),-((ty&3)*(TILEH>>3)));
break;
case 3:
m_image.SetScale(1.0f,1.0f);
m_image.Draw(0,-((tx&7)*(TILEW>>3)),-((ty&7)*(TILEH>>3)));
break;
case 4:
m_image.SetScale(1.0f/0.5f,1.0f/0.5f);
m_image.Draw(0,-((tx&15)*(TILEW>>3)),-((ty&15)*(TILEH>>3)));
break;
case 5:
m_image.SetScale(1.0f/0.25f,1.0f/0.25f);
m_image.Draw(0,-((tx&31)*(TILEW>>3)),-((ty&31)*(TILEH>>3)));
break;
}
return(TILE_OK);
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
205
]
]
]
|
ca75e459135fd561dde85eb581137bbcfe57a9b7 | 3472e587cd1dff88c7a75ae2d5e1b1a353962d78 | /XMonitor/src/ServerModel.h | 1d242a161d2741655a52cfe536bd8bac9e47c542 | []
| no_license | yewberry/yewtic | 9624d05d65e71c78ddfb7bd586845e107b9a1126 | 2468669485b9f049d7498470c33a096e6accc540 | refs/heads/master | 2021-01-01T05:40:57.757112 | 2011-09-14T12:32:15 | 2011-09-14T12:32:15 | 32,363,059 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 590 | h | /*
* ServerModel.h
*
* Created on: 2011-3-14
* Author: Yewberry
*/
#ifndef SERVERMODEL_H_
#define SERVERMODEL_H_
#include "XModel.h"
class ServerModel : public XModel
{
Q_OBJECT
public:
enum { ID = 0, IP = 1, NAME = 2, DESC = 3, USR = 4, PWD = 5, ACTIVE = 6, UI_SCENE_POS = 7, STATUS = 8, STEP_STATUS = 9 };
ServerModel(QObject *parent = 0);
bool isActive(QString id);
bool isWarning(QString id);
QString stepStatus(QString id);
QPointF getUiScenePos(QString id);
void uiScenePos(QString id, QPointF pos);
};
#endif /* SERVERMODEL_H_ */
| [
"[email protected]@5ddc4e96-dffd-11de-b4b3-6d349e4f6f86"
]
| [
[
[
1,
28
]
]
]
|
35116e86b30761c59d4c2ece217521494dfe3d3f | 5ed707de9f3de6044543886ea91bde39879bfae6 | /ASBasketball/Shared/Source/ASBasketballBuildSchedule.h | f1006f8e0f51d9773fcb18242ffcb139105ff637 | []
| no_license | grtvd/asifantasysports | 9e472632bedeec0f2d734aa798b7ff00148e7f19 | 76df32c77c76a76078152c77e582faa097f127a8 | refs/heads/master | 2020-03-19T02:25:23.901618 | 1999-12-31T16:00:00 | 2018-05-31T19:48:19 | 135,627,290 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 935 | h | /* ASBasketballBuildSchedule.h */
/******************************************************************************/
/******************************************************************************/
#ifndef ASBasketballBuildScheduleH
#define ASBasketballBuildScheduleH
#include "ASFantasyBuildSchedule.h"
using namespace asfantasy;
namespace asbasketball
{
/******************************************************************************/
class ASBasketballBuildSchedule : public TBuildSchedule
{
protected:
virtual StaticBuildScheduleGame* getStaticScheduleGameList(int numTeams,
int& numGames);
};
/******************************************************************************/
}; //asbasketball
#endif //ASBasketballBuildScheduleH
/******************************************************************************/
/******************************************************************************/
| [
"[email protected]"
]
| [
[
[
1,
30
]
]
]
|
3266103876fb14a4c965d141a529114093a05397 | c2abb873c8b352d0ec47757031e4a18b9190556e | /src/MyGUIEngine/include/MyGUI_Prerequest.h | 493e31bee17ec62d5c6e5b70452fdd54fce74862 | []
| no_license | twktheainur/vortex-ee | 70b89ec097cd1c74cde2b75f556448965d0d345d | 8b8aef42396cbb4c9ce063dd1ab2f44d95e994c6 | refs/heads/master | 2021-01-10T02:26:21.913972 | 2009-01-30T12:53:21 | 2009-01-30T12:53:21 | 44,046,528 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 4,530 | h | /*!
@file
@author Denis Koronchik
@author Georgiy Evmenov
@author Ну и я чуть чуть =)
@date 09/2007
*/
#ifndef __MYGUI_PREREQUEST_H__
#define __MYGUI_PREREQUEST_H__
#include "MyGUI_Platform.h"
#include <string>
#include <list>
#include <set>
#include <map>
#include <vector>
#include <deque>
#include "MyGUI_Utility.h"
#include "MyGUI_Delegate.h"
namespace MyGUI
{
class Gui;
using MyGUI::delegates::newDelegate;
class WidgetSkinInfo;
class MaskPeekInfo;
class WidgetCreator;
// managers
class InputManager;
class SubWidgetManager;
class LayerManager;
class SkinManager;
class WidgetManager;
class FontManager;
class ControllerManager;
class PointerManager;
class ClipboardManager;
class LayoutManager;
class PluginManager;
class DynLibManager;
class WidgetFactoryInterface;
class DynLib;
namespace factory
{
class WidgetFactory;
class ButtonFactory;
class WindowFactory;
class ListFactory;
class HScrollFactory;
class VScrollFactory;
class EditFactory;
class ComboBoxFactory;
class StaticTextFactory;
class SheetFactory;
class TabFactory;
class ProgressFactory;
class ItemBoxFactory;
class MultiListFactory;
class StaticImageFactory;
class MessageFactory;
class RenderBoxFactory;
class FooBarFactory;
class PopupMenuFactory;
//class MenuBarFactory;
}
class Widget;
class Button;
class Window;
class List;
class HScroll;
class VScroll;
class Edit;
class ComboBox;
class StaticText;
class Sheet;
class Tab;
class Progress;
class ItemBox;
class MultiList;
class StaticImage;
class Message;
class RenderBox;
class FooBar;
class PopupMenu;
class MenuBar;
typedef Widget * WidgetPtr;
typedef Button * ButtonPtr;
typedef Window * WindowPtr;
typedef List * ListPtr;
typedef HScroll * HScrollPtr;
typedef VScroll * VScrollPtr;
typedef Edit * EditPtr;
typedef ComboBox * ComboBoxPtr;
typedef StaticText * StaticTextPtr;
typedef Sheet * SheetPtr;
typedef Tab * TabPtr;
typedef Progress * ProgressPtr;
typedef ItemBox * ItemBoxPtr;
typedef MultiList * MultiListPtr;
typedef StaticImage * StaticImagePtr;
typedef Message * MessagePtr;
typedef RenderBox * RenderBoxPtr;
typedef FooBar * FooBarPtr;
typedef PopupMenu * PopupMenuPtr;
typedef MenuBar * MenuBarPtr;
// Define version
#define MYGUI_VERSION_MAJOR 2
#define MYGUI_VERSION_MINOR 2
#define MYGUI_VERSION_PATCH 0
#define MYGUI_VERSION ((MYGUI_VERSION_MAJOR << 16) | (MYGUI_VERSION_MINOR << 8) | MYGUI_VERSION_PATCH)
// Disable warnings for MSVC compiler
#if MYGUI_COMPILER == MYGUI_COMPILER_MSVC
// Turn off warnings generated by long std templates
// This warns about truncation to 255 characters in debug/browse info
# pragma warning (disable : 4786)
// Turn off warnings generated by long std templates
// This warns about truncation to 255 characters in debug/browse info
# pragma warning (disable : 4503)
// disable: "conversion from 'double' to 'float', possible loss of data
# pragma warning (disable : 4244)
// disable: "truncation from 'double' to 'float'
# pragma warning (disable : 4305)
// disable: "<type> needs to have dll-interface to be used by clients'
// Happens on STL member variables which are not public therefore is ok
# pragma warning (disable : 4251)
// disable: "non dll-interface class used as base for dll-interface class"
// Happens when deriving from Singleton because bug in compiler ignores
// template export
# pragma warning (disable : 4275)
// disable: "C++ Exception Specification ignored"
// This is because MSVC 6 did not implement all the C++ exception
// specifications in the ANSI C++ draft.
# pragma warning( disable : 4290 )
// disable: "no suitable definition provided for explicit template
// instantiation request" Occurs in VC7 for no justifiable reason on all
// #includes of Singleton
# pragma warning( disable: 4661)
// disable: deprecation warnings when using CRT calls in VC8
// These show up on all C runtime lib code in VC8, disable since they clutter
// the warnings with things we may not be able to do anything about (e.g.
// generated code from nvparse etc). I doubt very much that these calls
// will ever be actually removed from VC anyway, it would break too much code.
# pragma warning( disable: 4996)
#endif
} // namespace MyGUI
#endif // __MYGUI_PREREQUEST_H__
| [
"twk.theainur@37e2baaa-b253-11dd-9381-bf584fb1fa83"
]
| [
[
[
1,
172
]
]
]
|
3e4ce362da8be3bef142cf1b7cd7e7e970eead15 | 59ce53af7ad5a1f9b12a69aadbfc7abc4c4bfc02 | /src/SkinResEditor_Old/COutputSetDlg.h | d510205e6b51b7b5a63f276fe1c98806523fc836 | []
| no_license | fingomajom/skinengine | 444a89955046a6f2c7be49012ff501dc465f019e | 6bb26a46a7edac88b613ea9a124abeb8a1694868 | refs/heads/master | 2021-01-10T11:30:51.541442 | 2008-07-30T07:13:11 | 2008-07-30T07:13:11 | 47,892,418 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,697 | h | // aboutdlg.h : interface of the CAboutDlg class
//
/////////////////////////////////////////////////////////////////////////////
#pragma once
#include "resource.h"
#include "SREConfigMgt.h"
class COutputSetDlg : public CDialogImpl<COutputSetDlg>
{
public:
enum { IDD = IDD_OUTPUTSET_DIALOG };
BEGIN_MSG_MAP(COutputSetDlg)
MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
COMMAND_ID_HANDLER(IDOK, OnOKCmd)
COMMAND_ID_HANDLER(IDCANCEL, OnCloseCmd)
COMMAND_HANDLER(IDC_SF_BUTTON1, BN_CLICKED, OnBnClickedSfButton1)
END_MSG_MAP()
// Handler prototypes (uncomment arguments if needed):
// LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
// LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
// LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/)
LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
CenterWindow(GetParent());
SREConfigMgt config;
SkinControlsMgt& ControlsMgt = SkinControlsMgt::Instance();
KSGUI::CString strHF;
config.GetHeaderFileName( ControlsMgt.m_resDocument.GetFileName(),
strHF);
SetDlgItemText(IDC_RF_EDIT, ControlsMgt.m_resDocument.GetFileName());
SetDlgItemText(IDC_HF_EDIT, strHF);
return TRUE;
}
LRESULT OnOKCmd(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
SREConfigMgt config;
SkinControlsMgt& ControlsMgt = SkinControlsMgt::Instance();
KSGUI::CString strHF;
TCHAR pszBuffer[MAX_PATH] = { 0 };
GetDlgItemText(IDC_HF_EDIT, pszBuffer, MAX_PATH);
strHF = pszBuffer;
config.SetHeaderFileName( ControlsMgt.m_resDocument.GetFileName(),
strHF);
EndDialog(wID);
return 0;
}
LRESULT OnCloseCmd(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
EndDialog(wID);
return 0;
}
LRESULT OnBnClickedSfButton1(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
CFileDialog saveDlg(FALSE, _T("h"), _T(""),
OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,// | OFN_ALLOWMULTISELECT,
_T("header file(*.h)\0*.h\0所有文件(*.*)\0*.*\0\0"));
saveDlg.m_ofn.lpstrTitle = (_T("另存为"));
if (saveDlg.DoModal() != IDOK)
return 0;
SetDlgItemText(IDC_HF_EDIT, saveDlg.m_ofn.lpstrFile);
return 0;
}
};
| [
"[email protected]"
]
| [
[
[
1,
87
]
]
]
|
f7497d2eb758e869f2e7f2301d1b6644fb1e1cef | 57574cc7192ea8564bd630dbc2a1f1c4806e4e69 | /Poker/Comun/XmlParserEstado.h | 63130cdfdf47ff09209fcbc26248ba8a55e37729 | []
| no_license | natlehmann/taller-2010-2c-poker | 3c6821faacccd5afa526b36026b2b153a2e471f9 | d07384873b3705d1cd37448a65b04b4105060f19 | refs/heads/master | 2016-09-05T23:43:54.272182 | 2010-11-17T11:48:00 | 2010-11-17T11:48:00 | 32,321,142 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,181 | h | #ifndef _XMLPARSERESTADO_H__
#define _XMLPARSERESTADO_H__
#define _CRT_SECURE_NO_DEPRECATE 1
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include <sstream>
#include <deque>
#include "Elemento.h"
#include "MensajesUtil.h"
#include "PokerException.h"
using namespace std;
class XmlParserEstado
{
private:
deque<string*>* nodosProcesados;
Elemento* elementoActual;
string textoAProcesar;
unsigned int inicioTexto;
int numeroLinea;
protected:
string nombreConfiguracion;
public:
XmlParserEstado(deque<string*>* nodosProcesados);
virtual ~XmlParserEstado(void);
void setElementoActual(Elemento* elemento);
Elemento* getElementoActual();
void setTextoAProcesar(string texto);
string getTextoAProcesar();
virtual void setInicioTexto(unsigned int inicio);
unsigned int getInicioTexto();
void setNumeroLinea(int numero);
int getNumeroLinea();
deque<string*>* getNodosProcesados();
virtual XmlParserEstado* procesarFragmento() = 0;
virtual bool terminado();
string getNombreConfiguracion();
void setNombreConfiguracion(string nombreConfiguracion);
};
#endif
| [
"natlehmann@a9434d28-8610-e991-b0d0-89a272e3a296",
"[email protected]@a9434d28-8610-e991-b0d0-89a272e3a296",
"marianofl85@a9434d28-8610-e991-b0d0-89a272e3a296"
]
| [
[
[
1,
28
],
[
32,
53
],
[
57,
58
]
],
[
[
29,
31
],
[
54,
56
]
],
[
[
59,
59
]
]
]
|
1db5d65b112d84b5381d32e182f6433aac83d369 | ef37d76d24f90ba2d3aa4f9cf94025b2d4255673 | /Code/Build/moc/resampler/moc_ResamplerOptions.cpp | 68571e3e648e494d4b7d577bd4e96ed6dd3c06a8 | []
| no_license | yuguess/GSoC | 799cb55773e5f5ea0925e39d337f35250c937e22 | 21354978f43ea1ebfdfab79f027cdfe04273d264 | refs/heads/master | 2020-05-19T03:53:01.965062 | 2010-08-24T18:20:01 | 2010-08-24T18:20:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,346 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'ResamplerOptions.h'
**
** Created: Sun Jul 11 21:14:37 2010
** by: The Qt Meta Object Compiler version 61 (Qt 4.5.2)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../../Resampler/ResamplerOptions.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'ResamplerOptions.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 61
#error "This file was generated using the moc from 4.5.2. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_ResamplerOptions[] = {
// content:
2, // revision
0, // classname
0, 0, // classinfo
1, 12, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
// slots: signature, parameters, type, tag, flags
27, 18, 17, 17, 0x0a,
0 // eod
};
static const char qt_meta_stringdata_ResamplerOptions[] = {
"ResamplerOptions\0\0newIndex\0"
"currentIndexChanged(int)\0"
};
const QMetaObject ResamplerOptions::staticMetaObject = {
{ &LabeledSectionGroup::staticMetaObject, qt_meta_stringdata_ResamplerOptions,
qt_meta_data_ResamplerOptions, 0 }
};
const QMetaObject *ResamplerOptions::metaObject() const
{
return &staticMetaObject;
}
void *ResamplerOptions::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_ResamplerOptions))
return static_cast<void*>(const_cast< ResamplerOptions*>(this));
return LabeledSectionGroup::qt_metacast(_clname);
}
int ResamplerOptions::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = LabeledSectionGroup::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
case 0: currentIndexChanged((*reinterpret_cast< int(*)>(_a[1]))); break;
default: ;
}
_id -= 1;
}
return _id;
}
QT_END_MOC_NAMESPACE
| [
"[email protected]"
]
| [
[
[
1,
74
]
]
]
|
d1e6aba839db5a7e48d13707201ef56d1eb7890c | 2bdc85da8ec860be41ad14fceecedef1a8efc269 | /TestSwigLib/source/TSInner.cpp | 536740bd8e5bf23590a81e0a729a43e3a38f2277 | []
| no_license | BackupTheBerlios/pythonwrapper-svn | 5c41a03b23690c62693c7b29e81b240ee24f1a7f | 42879461c7302755f3c803cd1314e8da5a202c68 | refs/heads/master | 2016-09-05T09:53:14.554795 | 2005-12-26T07:52:41 | 2005-12-26T07:52:41 | 40,751,088 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 216 | cpp | #include "TSInner.h"
namespace ts
{
Inner::Inner() {}
Inner::~Inner() {}
int Inner::getValue(A *a) const
{
if (a)
return a->getValue();
return 0;
}
}
| [
"cculver@827b5c2f-c6f0-0310-96fe-c05a662c181e"
]
| [
[
[
1,
15
]
]
]
|
e7b13946c1e9dc181f4153af231ba84e318254dd | de98f880e307627d5ce93dcad1397bd4813751dd | /3libs/ut/include/OXGraphics.h | 0e4a279ea523f83043486b7e696b9ace8869ac0e | []
| 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 | 7,208 | h | // ==========================================================================
// Class Specification : COXGraphics
// ==========================================================================
// Header file : OXGraphics.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.
// //////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////
/*
DESCRIPTION
COXGraphics class was designed in order to provide advanced graphics routines
for programmers. We should note from the very beginning that we are not going
to explain the underlying theory that has been used while creating this class.
For those who are interested in depth information about graphics algorithms
we would recommend toread the following book:
"Computer Graphics, principle and practice" by James D. Foley,
Andries van Dam
Steven K. Feiner
John F. Hughes
Addison-Wesley publishing company. ISBN 0-201-84840-6
This class will be constantly updated with new cool graphics routines. At this
point it provides the following functionality:
1) Drawing rounded rectangles. Rectangle is filled with given color.
The color of every point is calculated depending on the location of
light source (vertical and horizontal angles) and surface
characteristics (light intensity, spot size, etc.). This way we
can achieve 3D effect.
In order to draw 3D rounded rectangle you should call the following function:
DrawRoundedButton()
Refer to the documentation on this function which arguments reveal all
settings that influence the ultimate appearance of the drawn rectangle.
The functionality provided by this function is used in the following
Ultimate Toolbox class: COXRoundedButton. Refer to this class as to
the real-life example of using of this function. Also you might want
to take look at the RoundedButton sample that can be found in the
.\Samples\gui\RoundedButton subdirectory of your Ultimate Toolbox
directory.
Dependency:
#include "OXGraphics.h"
Source code files:
"OXGraphics.cpp"
*/
#if !defined(_OXGRAPHICS_H__)
#define _OXGRAPHICS_H__
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
#include "OXDllExt.h"
class OX_CLASS_DECL COXGraphics
{
public:
// --- In :
// --- Out :
// --- Returns:
// --- Effect : Constructs the object
COXGraphics();
// --- In :
// --- Out :
// --- Returns:
// --- Effect : Destructs the object
virtual ~COXGraphics();
protected:
// Functions to draw rounded button
//
// Calculates colors on sphere with light source
DWORD* PrepareSphere(CDC *pDC, // dc where button will be drawn
int nLeft, int nTop, // coordinates of the top/left corner of the button
int nExternalRadius, // roundness of the button
int nInternalRadius, // part of sphere that will be painted using flat sphere color
COLORREF clrLightSource, // color of light source
float Lx, float Ly, float Lz, // normalized vector of the normal to the sphere
float fLightIntensity, // power of the light source
int nPhong, // influence on spot size
float fMirror, // influence on spot intensity
float fDiffuse, // diffuse lighting
float fAmbient, // ambient lighting
COLORREF clrButton, // color for filing the bitmap
COLORREF clrBack // color to fill the space that is not covered by the button
// if CLR_NONE is specified then the background will be covered
// using background of the specified devicce context
);
// Helper function. Draws specified bitmap in the specified position.
// If pPalette is not NULL then it will be populated with palette
// that was used to draw the bitmap (only for 256-color video mode)
void DrawBitmap(CDC *pDC, int nLeft, int nTop, int width, int height,
DWORD *bitmap, CPalette* pPalette);
// Helper function. Builds palette for specified bitmap
BOOL BuildButtonPalette(CDC *pDC, DWORD *bitmap, int width,
int height, CPalette* pPalette);
// Create bitmap for rounded button on the base of the specified sphere bitmap
// that was built using PrepareSphere() function
DWORD* PrepareButton(int nButtonWidth, int nButtonHeight,
DWORD *SphereBitmap, int SphereRadius);
//
///////////////////////////////////////////////////////////////
public:
// --- In : pDC - device context to draw button in
// nLeft - x coordinate of top/left corner of the button
// nTop - y coordinate of top/left corner of the button
// nButtonWidth - button width
// nButtonHeight - button height
// nExternalRadius - radius of flat center and rounded border
// nInternalRadius - radius of flat part
// pPalette - pointer to palette object to be populated with
// entries used to draw the button when 256-color
// video mode is set on
// clrButton - solid color of button without lighting
// clrLightSource - color of light source
// fThetta - vertical angle of the light source
// fPhi - horizontal angle of the light source
// fLightIntensity - influence on diffuse lighting and spot intensity
// nPhong - influence on spot size
// fMirror - influence on spot intensity
// fDiffuse - diffuse lighting
// fAmbient - ambient lighting
// clrBack - color to fill the space that is not covered
// by the button. If CLR_NONE color is specified
// then the background will be covered using
// background of the specified device context
//
// --- Out :
// --- Returns:
// --- Effect : Draws rounded button. The button background color will be
// adjusted in order to accommodate light source, which properties
// can be set using parameters of the function. If current video
// mode is set to display only 256 colors the palette that has
// been used in order to draw the button will be saved in pPalette
// parameter
void DrawRoundedButton(CDC* pDC, int nLeft, int nTop, int nButtonWidth,
int nButtonHeight, int nExternalRadius=8, int nInternalRadius=3,
CPalette* pPalette=NULL,
COLORREF clrButton=::GetSysColor(COLOR_BTNFACE),
COLORREF clrLightSource=::GetSysColor(COLOR_3DHIGHLIGHT),
float fThetta=60, float fPhi=-45,
float fLightIntensity=1.3f, int nPhong=15, float fMirror=0.6f,
float fDiffuse=0.5f, float fAmbient=0.9f,
COLORREF clrBack=CLR_NONE);
};
#endif // !defined(_OXGRAPHICS_H__)
| [
"[email protected]"
]
| [
[
[
1,
187
]
]
]
|
c8363e521a9b2bde2e0e73669b9b68b13615c7f3 | 46653590825ea44df39c88f5e5e761122239b882 | /EseObjects/EseVersion.hpp | 3817449c5525a0aec43d9a8c6d41a8995c2d18b5 | []
| no_license | CADbloke/eselinq | e46e24d41a09ba467cc54a94b5ad803d00e6e2d1 | e19f217a32b23b2fd71149653fe792086c798cb8 | refs/heads/master | 2021-01-13T01:00:48.817112 | 2010-08-26T01:50:39 | 2010-08-26T01:50:39 | 36,408,696 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,116 | hpp | ///////////////////////////////////////////////////////////////////////////////
// Project : EseLinq http://code.google.com/p/eselinq/
// Copyright : (c) 2009 Christopher Smith
// Maintainer : [email protected]
// Module : EseVersion - Retrieves module version information from the ESE DLL
///////////////////////////////////////////////////////////////////////////////
//
//This software is licenced under the terms of the MIT License:
//
//Copyright (c) 2009 Christopher Smith
//
//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.
//
///////////////////////////////////////////////////////////////////////////////
void GetEseVersion(ushort &Major, ushort &Minor, ushort &Build1, ushort &Build2)
{
ulong handle = null;
ulong size = GetFileVersionInfoSize(L"esent.dll", &handle);
if (size > 0)
{
char *buff = new char[size];
try
{
if (GetFileVersionInfo(L"esent.dll", handle, size, buff))
{
VS_FIXEDFILEINFO *fileinfo;
UINT fileinfosize = 0;
if(VerQueryValue(buff, L"\\", (void **)&fileinfo, &fileinfosize) && fileinfosize && fileinfo->dwSignature == 0xfeef04bd)
{
Major = HIWORD(fileinfo->dwFileVersionMS);
Minor = LOWORD(fileinfo->dwFileVersionMS);
Build1 = LOWORD(fileinfo->dwFileVersionLS);
Build2 = HIWORD(fileinfo->dwFileVersionLS);
}
}
}
finally
{
delete buff;
}
}
}
ushort EseVersionMajor = 0, EseVersionMinor = 0, EseVersionBuild1 = 0, EseVersionBuild2 = 0;
bool EseVersionLoaded = false;
void EnsureEseVersionLoaded()
{
if(!EseVersionLoaded)
{
EseVersionLoaded = true;
GetEseVersion(EseVersionMajor, EseVersionMinor, EseVersionBuild1, EseVersionBuild2);
}
}
ushort GetEseVersionMajor()
{
EnsureEseVersionLoaded();
return EseVersionMajor;
}
ushort GetEseVersionMinor()
{
EnsureEseVersionLoaded();
return EseVersionMinor;
}
ushort GetEseVersionBuild1()
{
EnsureEseVersionLoaded();
return EseVersionBuild1;
}
ushort GetEseVersionBuild2()
{
EnsureEseVersionLoaded();
return EseVersionBuild2;
} | [
"[email protected]"
]
| [
[
[
1,
98
]
]
]
|
e5c9863585fb21763d71d09d6e84aeadddd8284d | af2233c4d6a1f94106134a73408fb234b6ae8436 | /RenderUtility/LRUcacheTest.cpp | f5f30b2950f24297870b3ebb5e31c979e5c927e5 | []
| no_license | liwenqiang1990/gpu-streaming-benchmark | 33b01cd5c4964466a4be2de5a3a2f67c2389eb77 | 4339b8cc6d00820e20669488a0406d186d2ffc15 | refs/heads/master | 2020-06-01T11:07:42.246460 | 2011-06-20T21:39:02 | 2011-06-20T21:39:02 | 34,671,006 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,169 | cpp | #include "LRUcachePool.h"
#include <iostream>
#include <list>
using namespace std;
extern "C" void LRUcacheTest()
{
/* //test swapping two node using slice
list<int> ilist;
ilist.push_back(1);
ilist.push_back(2);
ilist.push_back(3);
ilist.push_back(4);
list<int>::iterator i = ilist.begin();
list<int>::iterator j = ilist.end();
j--;
cout<<*i<<" "<<*j<<endl;
list<int>::iterator k = ilist.begin();
for (; k!=ilist.end();k++)
cout<<" "<<*k;
cout<<endl;
ilist.splice(ilist.begin(),ilist,j);
cout<<*i<<" "<<*j<<endl;
k = ilist.begin();
for (; k!=ilist.end();k++)
cout<<" "<<*k;
cout<<endl;
*/
LRUcache<long, float> cache = LRUcache<long, float>(1024*256*sizeof(float), 50);
cache.AllocateGlobalCacheBuffer();
cout<<"cacheCapacity: "<<cache.GetMaxCacheCapacity()<<" Entry"<<endl;
//float *value = new float[1024*256];
long index = 1l;
for(int i=0; i<100; i++)
{
float *value = cache.GetLRUBufferLocation();
memset(value, 0, 256*sizeof(float));
cache.Add(index);
cout<<cache.Find(index)<<endl;;
index++;
cache.outputMap();
if(index>50)
index = 1;
}
}
| [
"[email protected]@46a6917a-aa20-85b6-2959-6e77123ad00a"
]
| [
[
[
1,
48
]
]
]
|
1e198ef1bd7bdc8cfbf769f0f38a75f13daffe30 | ab41c2c63e554350ca5b93e41d7321ca127d8d3a | /glm/GLM_GTX_matrix_query.h | e6266eb506999af664ba8e3f701f223b368af40d | []
| no_license | burner/e3rt | 2dc3bac2b7face3b1606ee1430e7ecfd4523bf2e | 775470cc9b912a8c1199dd1069d7e7d4fc997a52 | refs/heads/master | 2021-01-11T08:08:00.665300 | 2010-04-26T11:42:42 | 2010-04-26T11:42:42 | 337,021 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 808 | h | ///////////////////////////////////////////////////////////////////////////////////////////////////
// OpenGL Mathematics Copyright (c) 2005 - 2008 G-Truc Creation (www.g-truc.net)
///////////////////////////////////////////////////////////////////////////////////////////////////
// Created : 2008-10-22
// Updated : 2008-10-22
// Licence : This source is under MIT License
///////////////////////////////////////////////////////////////////////////////////////////////////
// Dependency:
// - GLM core
///////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef glm_gtx_matrix_query_api
#define glm_gtx_matrix_query_api
#include "gtx/matrix_query.hpp"
namespace glm
{
using GLM_GTX_matrix_query;
}
#endif//glm_gtx_matrix_query_api
| [
"[email protected]"
]
| [
[
[
1,
22
]
]
]
|
8b41d08c726f9c70bf4718349f865a88b5424173 | b14d5833a79518a40d302e5eb40ed5da193cf1b2 | /cpp/extern/xercesc++/2.6.0/src/xercesc/dom/deprecated/AttrNSImpl.cpp | 6008b587d22722364a9a371128c769e8e8544664 | [
"Apache-2.0"
]
| permissive | andyburke/bitflood | dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf | fca6c0b635d07da4e6c7fbfa032921c827a981d6 | refs/heads/master | 2016-09-10T02:14:35.564530 | 2011-11-17T09:51:49 | 2011-11-17T09:51:49 | 2,794,411 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,709 | cpp | /*
* Copyright 1999-2002,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: AttrNSImpl.cpp,v 1.6 2004/09/08 13:55:42 peiyongz Exp $
*/
#include <xercesc/util/XMLUniDefs.hpp>
#include "AttrNSImpl.hpp"
#include "DocumentImpl.hpp"
#include "DOM_DOMException.hpp"
XERCES_CPP_NAMESPACE_BEGIN
AttrNSImpl::AttrNSImpl(DocumentImpl *ownerDoc, const DOMString &nam) :
AttrImpl(ownerDoc, nam)
{
this->namespaceURI=null; //DOM Level 2
this->localName=null; //DOM Level 2
}
//Introduced in DOM Level 2
AttrNSImpl::AttrNSImpl(DocumentImpl *ownerDoc,
const DOMString &fNamespaceURI,
const DOMString &qualifiedName) :
AttrImpl(ownerDoc, qualifiedName)
{
DOMString xmlns = NodeImpl::getXmlnsString();
DOMString xmlnsURI = NodeImpl::getXmlnsURIString();
this->name = qualifiedName.clone();
int index = DocumentImpl::indexofQualifiedName(qualifiedName);
DOMString prefix;
if (index < 0)
throw DOM_DOMException(DOM_DOMException::NAMESPACE_ERR, null);
bool xmlnsAlone = false; //true if attribute name is "xmlns"
if (index == 0) { //qualifiedName contains no ':'
if (this->name.equals(xmlns)) {
if (!fNamespaceURI.equals(xmlnsURI))
throw DOM_DOMException(DOM_DOMException::NAMESPACE_ERR, null);
xmlnsAlone = true;
}
prefix = null;
this -> localName = this -> name;
} else { //0 < index < this->name.length()-1
prefix = this->name.substringData(0, index);
this -> localName =
this->name.substringData(index+1, this->name.length()-index-1);
}
const DOMString& URI = xmlnsAlone ?
xmlnsURI : mapPrefix(prefix, fNamespaceURI, DOM_Node::ATTRIBUTE_NODE);
this -> namespaceURI = URI == null ? DOMString(null) : URI.clone();
};
AttrNSImpl::AttrNSImpl(const AttrNSImpl &other, bool deep) :
AttrImpl(other, deep)
{
this->namespaceURI = other.namespaceURI.clone(); //DOM Level 2
this->localName = other.localName.clone(); //DOM Level 2
};
NodeImpl * AttrNSImpl::cloneNode(bool deep)
{
return new (getOwnerDocument()->getMemoryManager()) AttrNSImpl(*this, deep);
};
DOMString AttrNSImpl::getNamespaceURI()
{
return namespaceURI;
}
DOMString AttrNSImpl::getPrefix()
{
int index = DocumentImpl::indexofQualifiedName(name);
if (index == 0)
return null;
else
return name.substringData(0, index);
}
DOMString AttrNSImpl::getLocalName()
{
return localName;
}
void AttrNSImpl::setPrefix(const DOMString &prefix)
{
DOMString xml = NodeImpl::getXmlString();
DOMString xmlURI = NodeImpl::getXmlURIString();
DOMString xmlns = NodeImpl::getXmlnsString();
DOMString xmlnsURI = NodeImpl::getXmlnsURIString();
if (getOwnerDocument()->getErrorChecking()) {
if (isReadOnly()) {
throw DOM_DOMException(
DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR,
null);
}
if (namespaceURI == null || localName.equals(xmlns)) {
throw DOM_DOMException(DOM_DOMException::NAMESPACE_ERR, null);
}
if (prefix != null && !((DocumentImpl *)this->getOwnerDocument())->isXMLName(prefix)) {
throw DOM_DOMException(DOM_DOMException::INVALID_CHARACTER_ERR,
null);
}
}
if (prefix == null || prefix.length() == 0) {
name = localName;
return;
}
if (getOwnerDocument()->getErrorChecking() &&
(prefix.equals(xml) && !namespaceURI.equals(xmlURI) ||
prefix.equals(xmlns) && !namespaceURI.equals(xmlnsURI))) {
throw DOM_DOMException(DOM_DOMException::NAMESPACE_ERR, null);
}
const XMLCh *p = prefix.rawBuffer();
for (int i = prefix.length(); --i >= 0;)
if (*p++ == chColon) //prefix is malformed
throw DOM_DOMException(DOM_DOMException::NAMESPACE_ERR, null);
name = prefix + chColon + localName; //nodeName is changed too
}
XERCES_CPP_NAMESPACE_END
| [
"[email protected]"
]
| [
[
[
1,
141
]
]
]
|
33570bcbe59daedca935e7f53bb4846c461e2e51 | 2b80036db6f86012afcc7bc55431355fc3234058 | /src/contrib/alsaout/alsaout_plugin.cpp | 67db490b1b1d91c91db728ae57aed1740232547f | [
"BSD-3-Clause"
]
| permissive | leezhongshan/musikcube | d1e09cf263854bb16acbde707cb6c18b09a0189f | e7ca6a5515a5f5e8e499bbdd158e5cb406fda948 | refs/heads/master | 2021-01-15T11:45:29.512171 | 2011-02-25T14:09:21 | 2011-02-25T14:09:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,538 | cpp | //////////////////////////////////////////////////////////////////////////////
//
// License Agreement:
//
// The following are Copyright © 2009, Julian Cromarty
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of the author nor the names of other contributors may
// be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////
#include "pch.h"
#include <core/IPlugin.h>
#include "AlsaOut.h"
class AlsaOutPlugin : public musik::core::IPlugin
{
void Destroy() { delete this; };
const utfchar* Name() { return TEXT("AlsaOut output plugin"); };
const utfchar* Version() { return TEXT("0.1"); };
const utfchar* Author() { return TEXT("Julian Cromarty"); };
};
extern "C" {
musik::core::IPlugin* GetPlugin()
{
return new AlsaOutPlugin();
}
}
/*
extern "C" {
musik::core::audio::IAudioOutputSupplier* CreateAudioOutputSupplier()
{
return new AlsaOutSupplier();
}
}*/
extern "C" {
musik::core::audio::IOutput* GetAudioOutput()
{
return new AlsaOut();
}
}
| [
"Urioxis@6a861d04-ae47-0410-a6da-2d49beace72e",
"urioxis@6a861d04-ae47-0410-a6da-2d49beace72e"
]
| [
[
[
1,
46
],
[
48,
71
]
],
[
[
47,
47
]
]
]
|
18ca8c5e1f2b3ea4719d68ddf6d0a462e67a0aa1 | 3d873b9abae5014a271615d94d7c445d0e15b52d | /UnitTestingCustomActions/Source/CustomActionTest/stdafx.cpp | 74f757b0483f28b64273a5829a36ae8ad4e6cc70 | []
| 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 | 303 | cpp | // stdafx.cpp : source file that includes just the standard includes
// CustomActionTest.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
| [
"[email protected]"
]
| [
[
[
1,
8
]
]
]
|
cb91c2d8abe9b50f4320733378a40e704b252ce4 | 4aadb120c23f44519fbd5254e56fc91c0eb3772c | /Source/src/EduNetApplication/EduNetGames.h | cbf1e392c9bd63578f055db99024f5ba5a4c5d5e | []
| no_license | janfietz/edunetgames | d06cfb021d8f24cdcf3848a59cab694fbfd9c0ba | 04d787b0afca7c99b0f4c0692002b4abb8eea410 | refs/heads/master | 2016-09-10T19:24:04.051842 | 2011-04-17T11:00:09 | 2011-04-17T11:00:09 | 33,568,741 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,059 | h | //-----------------------------------------------------------------------------
//
//
// OpenSteer -- Steering Behaviors for Autonomous Characters
//
// Copyright (c) 2002-2005, Sony Computer Entertainment America
// Original author: Craig Reynolds <[email protected]>
//
// 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.
//
//
//-----------------------------------------------------------------------------
//
//
// GameDemo
//
// This class encapsulates the state of the GameDemo application and
// the services it provides to its plug-ins
//
// 10-04-04 bk: put everything into the OpenSteer namespace
// 11-14-02 cwr: recast App class as GameDemo
// 06-26-02 cwr: App class created
//
//
//-----------------------------------------------------------------------------
#ifndef OPENSTEER_OPENSTEERDEMO_H
#define OPENSTEER_OPENSTEERDEMO_H
#include "EduNetCommon/EduNetCommon.h"
namespace OpenSteer
{
class Color;
class Vec3;
}
namespace EduNet
{
//
//
//class GameDemo
//{
//public:
// // ------------------------------------------------------ component objects
//
// // clock keeps track of both "real time" and "simulation time"
// static Clock& clock;
//
// // ------------------------------------------ addresses of selected objects
//
// // -------------------------------------------- initialize, update and exit
//
// // initialize GameDemo
// // XXX if I switch from "totally static" to "singleton"
// // XXX class structure this becomes the constructor
// static void initialize ( void );
//
// // main update function: step simulation forward and redraw scene
// static void updateSimulationAndRedraw ( void );
//
// // exit GameDemo with a given text message or error code
// static void errorExit ( const char* message );
// static void exit ( int exitCode );
//
// // ------------------------------------------------------- Plugin interface
//
// // select the default Plugin
// static void selectDefaultPlugin ( void );
//
//
// // do a simulation update for the currently selected plug-in
// static void updateSelectedPlugin ( const float currentTime,
// const float elapsedTime );
//
// // redraw graphics for the currently selected plug-in
// static void redrawSelectedPlugin ( const float currentTime,
// const float elapsedTime );
//
//
//
// // ---------------------------------------------------- GameDemo phase
//
// static bool phaseIsDraw ( void )
// {
// return phase == drawPhase;
// }
// static bool phaseIsUpdate ( void )
// {
// return phase == updatePhase;
// }
// static bool phaseIsOverhead ( void )
// {
// return phase == overheadPhase;
// }
//
// static float phaseTimerDraw ( void )
// {
// return phaseTimers[drawPhase];
// }
// static float phaseTimerUpdate ( void )
// {
// return phaseTimers[updatePhase];
// }
// // XXX get around shortcomings in current implementation, see note
// // XXX in updateSimulationAndRedraw
// //static float phaseTimerOverhead(void){return phaseTimers[overheadPhase];}
// static float phaseTimerOverhead ( void )
// {
// return ( clock.getElapsedRealTime() -
// ( phaseTimerDraw() + phaseTimerUpdate() ) );
// }
//
// // ------------------------------------------------------ delayed reset XXX
//
// // XXX to be reconsidered
// static void queueDelayedResetPluginXXX ( void );
// static void doDelayedResetPluginXXX ( void );
//
// // ------------------------------------------------------ vehicle selection
//
// // Find the AbstractVehicle whose screen position is nearest the
// // current the mouse position. Returns NULL if mouse is outside
// // this window or if there are no AbstractVehicles.
// static AbstractVehicle* vehicleNearestToMouse ( void );
//
// // for storing most recent mouse state
// static int mouseX;
// static int mouseY;
// static bool mouseInWindow;
//
// // ------------------------------------------------ graphics and annotation
//
//
// //-----------------------------------------------------------------------------
// // run graphics event loop
// static void runGraphics ( void );
//
// //-----------------------------------------------------------------------------
// // do all initialization related to graphics
// static void initializeGraphics ( int argc, char **argv );
//
// // do all initialization related to graphics
// static void initializeGraphics ( void );
// static void initGluiGraphics( int windowID );
//
// // ----------------------------------------------------------- console text
// // print list of known commands
// static void keyboardMiniHelp ( void );
//
// // ---------------------------------------------------------------- private
// static void initPhaseTimers ( void );
//private:
// static int phase;
// static int phaseStack[];
// static int phaseStackIndex;
// static float phaseTimers[];
// static float phaseTimerBase;
// static const int phaseStackSize;
// static void pushPhase ( const int newPhase );
// static void popPhase ( void );
// static void updatePhaseTimers ( void );
//
// static void setGlutFunctions( void );
// // XXX apparently MS VC6 cannot handle initialized static const members,
// // XXX so they have to be initialized not-inline.
// // static const int drawPhase = 2;
// // static const int updatePhase = 1;
// // static const int overheadPhase = 0;
// static const int drawPhase;
// static const int updatePhase;
// static const int overheadPhase;
//};
//
//
//
////-----------------------------------------------------------------------------
//// accessors for GLUT's window dimensions
//float extern_drawGetWindowHeight ( void );
//float extern_drawGetWindowWidth ( void );
//
} // namespace OpenSteer
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
#endif // OPENSTEER_OPENSTEERDEMO_H
| [
"janfietz@localhost"
]
| [
[
[
1,
210
]
]
]
|
070e41b35a87f703edbb6a4bd40356a0079ae33b | 45c0d7927220c0607531d6a0d7ce49e6399c8785 | /GlobeFactory/src/ui/ui_loader/ui_loader.hh | fc331621997fb406f960dd871102eeb218c3f0aa | []
| no_license | wavs/pfe-2011-scia | 74e0fc04e30764ffd34ee7cee3866a26d1beb7e2 | a4e1843239d9a65ecaa50bafe3c0c66b9c05d86a | refs/heads/master | 2021-01-25T07:08:36.552423 | 2011-01-17T20:23:43 | 2011-01-17T20:23:43 | 39,025,134 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,399 | hh | ////////////////////////////////////////////////////////////////////////////////
// Filename : ui_loader.hh
// Authors : Creteur Clement
// Last edit : 21/05/11 - 19h14
// Comment :
////////////////////////////////////////////////////////////////////////////////
#ifndef UI_LOADER_HH
#define UI_LOADER_HH
#include "../../useful/all.hh"
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
class UIComponent;
class UIParentLoader;
class InterfaceLoader;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
class UILoader
{
friend class UIParentLoader;
friend class InterfaceLoader;
protected:
UILoader(const std::string& parName);
virtual ~UILoader();
virtual UIComponent* LoadComponent(XmlNode* parNode) = 0;
UILoader* GetLoader(const std::string& parName);
bool ExtractBase(XmlNode* parNode, Vector2f& parPos, Vector2f& parSz);
private:
std::string MName;
static std::map<std::string, UILoader*> MLoaders;
};
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
#endif
| [
"creteur.c@8e971d8e-9cf3-0c36-aa0f-a7c54ab41ffc"
]
| [
[
[
1,
44
]
]
]
|
803931b1bf9504c9542a49a08c73ade3d2fee394 | fd4f996b64c1994c5e6d8c8ff78a2549255aacb7 | / nicolinorochetaller --username adrianachelotti/trunk/server_client/clientedeprueba2_1/toSendPackage.h | 2fcd0d6a581595467ad8e79a2c71c8a351e79ef0 | []
| no_license | adrianachelotti/nicolinorochetaller | 026f32476e41cdc5ac5c621c483d70af7b397fb0 | d3215dfdfa70b6226b3616c78121f36606135a5f | refs/heads/master | 2021-01-10T19:45:15.378823 | 2009-08-05T14:54:42 | 2009-08-05T14:54:42 | 32,193,619 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 816 | h | // toSendPackage.h: interface for the toSendPackage class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_TOSENDPACKAGE_H__86950D8F_C79F_4D7F_8A50_CE1B688C2414__INCLUDED_)
#define AFX_TOSENDPACKAGE_H__86950D8F_C79F_4D7F_8A50_CE1B688C2414__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
extern "C"{
#include "transferencia.h"
}
#include <string>
#include <iostream>
using namespace std;
class toSendPackage
{
public:
toSendPackage();
virtual ~toSendPackage();
CONEXION* getConexion();
string getData();
void setConexion(CONEXION* con);
void setData(string data);
private:
CONEXION *con;
string data;
};
#endif // !defined(AFX_TOSENDPACKAGE_H__86950D8F_C79F_4D7F_8A50_CE1B688C2414__INCLUDED_)
| [
"[email protected]@0b808588-0f27-11de-aab3-ff745001d230"
]
| [
[
[
1,
38
]
]
]
|
0507620e1721aa19fe6743371c5e0a4ae3fa8444 | fe7a7f1385a7dd8104e6ccc105f9bb3141c63c68 | /otserv.cpp | daa408573c3ffe4b83e140111c6126963270a35d | []
| no_license | divinity76/ancient-divinity-ots | d29efe620cea3fe8d61ffd66480cf20c8f77af13 | 0c7b5bfd5b9277c97d28de598f781dbb198f473d | refs/heads/master | 2020-05-16T21:01:29.130756 | 2010-10-11T22:58:07 | 2010-10-11T22:58:07 | 29,501,722 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,446 | cpp | //////////////////////////////////////////////////////////////////////
// OpenTibia - an opensource roleplaying game
//////////////////////////////////////////////////////////////////////
// otserv main. The only place where things get instantiated.
//////////////////////////////////////////////////////////////////////
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//////////////////////////////////////////////////////////////////////
#include "otpch.h"
#include "definitions.h"
#include <string>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <fstream>
#include <boost/thread.hpp>
#include <boost/asio.hpp>
#include <stdlib.h>
#include <time.h>
#include "otsystem.h"
#include "server.h"
#include "game.h"
#include "status.h"
#include "monsters.h"
#include "npc.h"
#include "commands.h"
#include "vocation.h"
#include "scriptmanager.h"
#include "configmanager.h"
#include "tools.h"
#include "ban.h"
#ifdef __OTSERV_ALLOCATOR__
#include "allocator.h"
#endif
#ifdef BOOST_NO_EXCEPTIONS
#include <exception>
void boost::throw_exception(std::exception const & e){
std::cout << "Boost exception: " << e.what() << std::endl;
}
#endif
IPList serverIPs;
ConfigManager g_config;
Game g_game;
Commands commands;
Npcs g_npcs;
Monsters g_monsters;
BanManager g_bans;
Vocations g_vocations;
Server* g_server = NULL;
boost::mutex g_loaderLock;
boost::condition_variable g_loaderSignal;
boost::unique_lock<boost::mutex> g_loaderUniqueLock(g_loaderLock);
#if defined __EXCEPTION_TRACER__
#include "exception.h"
#endif
#include "networkmessage.h"
void ErrorMessage(const char* message) {
std::cout << std::endl << std::endl << "Error: " << message << std::endl;
std::string s;
std::cin >> s;
}
void ErrorMessage(std::string m){
ErrorMessage(m.c_str());
}
struct CommandLineOptions{
std::string configfile;
bool truncate_log;
std::string logfile;
std::string errfile;
std::string runfile;
};
CommandLineOptions g_command_opts;
bool parseCommandLine(CommandLineOptions& opts, std::vector<std::string> args);
void mainLoader(const CommandLineOptions& command_opts);
#if !defined(__WINDOWS__)
// Runfile, for running OT as daemon in the background. If the server is shutdown by internal
// means, we need to clear the file to notify the daemon manager of our change in status.
// Note that if the server crashes, this will not happend. :|
void closeRunfile(void)
{
std::ofstream runfile(g_command_opts.runfile.c_str(), std::ios::trunc | std::ios::out);
runfile.close(); // Truncate file
}
#endif
int main(int argc, char *argv[])
{
if(parseCommandLine(g_command_opts, std::vector<std::string>(argv, argv + argc)) == false){
return 0;
}
#if !defined(__WINDOWS__)
if(g_command_opts.runfile != ""){
std::ofstream f(g_command_opts.runfile.c_str(), std::ios::trunc | std::ios::out);
f << getpid();
f.close();
atexit(closeRunfile);
}
#endif
boost::shared_ptr<std::ofstream> logfile;
boost::shared_ptr<std::ofstream> errfile;
if(g_command_opts.logfile != ""){
logfile.reset(new std::ofstream(g_command_opts.logfile.c_str(),
(g_command_opts.truncate_log? std::ios::trunc : std::ios::app) | std::ios::out)
);
if(!logfile->is_open()){
ErrorMessage("Could not open standard log file for writing!");
}
std::cout.rdbuf(logfile->rdbuf());
}
if(g_command_opts.errfile != ""){
errfile.reset(new std::ofstream(g_command_opts.errfile.c_str(),
(g_command_opts.truncate_log? std::ios::trunc : std::ios::app) | std::ios::out)
);
if(!errfile->is_open()){
ErrorMessage("Could not open error log file for writing!");
}
std::cerr.rdbuf(errfile->rdbuf());
}
#if !defined(__WINDOWS__)
// TODO: find something better than this hack. :|
time(&start_time);
#endif
#ifdef __OTSERV_ALLOCATOR_STATS__
boost::thread(boost::bind(&allocatorStatsThread, (void*)NULL));
#endif
#if defined __EXCEPTION_TRACER__
ExceptionHandler mainExceptionHandler;
mainExceptionHandler.InstallHandler();
#endif
std::cout << ":: " OTSERV_NAME " Version " OTSERV_VERSION << std::endl;
std::cout << ":: Compilation date: " __DATE__ " " __TIME__ << std::endl;
std::cout << ":: ==============================================" << std::endl;
std::cout << "::" << std::endl;
#if defined __DEBUG__MOVESYS__ || defined __DEBUG_HOUSES__ || defined __DEBUG_MAILBOX__ \
|| defined __DEBUG_LUASCRIPTS__ || defined __DEBUG_RAID__ || defined __DEBUG_NET__ \
|| defined __DEBUG_SQL__
std::cout << ":: Debugging:";
#ifdef __DEBUG__MOVESYS__
std::cout << " MOVESYS";
#endif
#ifdef __DEBUG_MAILBOX__
std::cout << " MAILBOX";
#endif
#ifdef __DEBUG_HOUSES__
std::cout << " HOUSES";
#endif
#ifdef __DEBUG_LUASCRIPTS__
std::cout << " LUA-SCRIPTS";
#endif
#ifdef __DEBUG_RAID__
std::cout << " RAIDS";
#endif
#ifdef __DEBUG_NET__
std::cout << " NET-ASIO";
#endif
#ifdef __DEBUG_SQL__
std::cout << " SQL";
#endif
std::cout << std::endl;
#endif
#if !defined(WIN32) && !defined(__ROOT_PERMISSION__)
if( getuid() == 0 || geteuid() == 0 ){
std::cout << std::endl << "OTServ executed as root user, please login with a normal user." << std::endl;
return 1;
}
#endif
#if defined __WINDOWS__ || defined WIN32
//nothing yet
#else
// ignore sigpipe...
struct sigaction sigh;
sigh.sa_handler = SIG_IGN;
sigh.sa_flags = 0;
sigemptyset(&sigh.sa_mask);
sigaction(SIGPIPE, &sigh, NULL);
#endif
Dispatcher::getDispatcher().addTask(createTask(boost::bind(mainLoader, g_command_opts)));
g_loaderSignal.wait(g_loaderUniqueLock);
int port = g_config.getNumber(ConfigManager::PORT);
Server server(INADDR_ANY, port);
std::cout << "[done]" << std::endl << ":: OpenTibia Server Running..." << std::endl;
g_server = &server;
server.run();
#if defined __EXCEPTION_TRACER__
mainExceptionHandler.RemoveHandler();
#endif
}
bool parseCommandLine(CommandLineOptions& opts, std::vector<std::string> args)
{
std::vector<std::string>::iterator argi = args.begin();
opts.truncate_log = false;
if(argi != args.end()){
++argi;
}
while(argi != args.end()){
std::string arg = *argi;
if(arg == "-p" || arg == "--port"){
if(++argi == args.end()){
std::cout << "Missing parameter for '" << arg << "'" << std::endl;
return false;
}
g_config.setNumber(ConfigManager::PORT, atoi(argi->c_str()));
}
else if(arg == "-r" || arg == "--runfile"){
if(++argi == args.end()){
std::cout << "Missing parameter for '" << arg << "'" << std::endl;
return false;
}
opts.runfile = *argi;
}
else if(arg == "-i" || arg == "--ip"){
if(++argi == args.end()){
std::cout << "Missing parameter for '" << arg << "'" << std::endl;
return false;
}
g_config.setString(ConfigManager::IP, *argi);
}
else if(arg == "-c" || arg == "--config"){
if(++argi == args.end()){
std::cout << "Missing parameter for '" << arg << "'" << std::endl;
return false;
}
opts.configfile = *argi;
}
else if(arg == "--truncate-log"){
opts.truncate_log = true;
}
else if(arg == "-l" || arg == "--log-file"){
if(++argi == args.end()){
std::cout << "Missing parameter 1 for '" << arg << "'" << std::endl;
return false;
}
opts.logfile = *argi;
if(++argi == args.end()){
std::cout << "Missing parameter 2 for '" << arg << "'" << std::endl;
return false;
}
opts.errfile = *argi;
}
else if(arg == "--help"){
std::cout <<
"Usage: otserv {-i|-p|-c|-r|-l}\n"
"\n"
"\t-i, --ip $1\t\tIP of gameworld server. Should be equal to the \n"
"\t\t\t\tglobal IP.\n"
"\t-p, --port $1\t\tPort for server to listen on.\n"
"\t-c, --config $1\t\tAlternate config file path.\n"
"\t-l, --log-file $1 $2\tAll standard output will be logged to the\n"
"\t\t\t\t$1 file, all errors will be logged to $2.\n"
"\t-r, --run-file $1\t\tSpecifies a runfile. Will contain the pid\n"
"\t\t\t\tof the server process as long as it is running (UNIX).\n"
"\t--truncate-log\t\tReset log file each time the server is \n"
"\t\t\t\tstarted.\n";
return false;
}
else
{
std::cout << "Unrecognized command line argument '" << arg << "'\n"
"Usage: otserv {-i|-p|-c|-r|-l}" << "\n";
return false;
}
++argi;
}
return true;
}
void mainLoader(const CommandLineOptions& command_opts)
{
//dispatcher thread
g_game.setGameState(GAME_STATE_STARTUP);
// random numbers generator
std::cout << ":: Initializing the random numbers... " << std::flush;
srand((unsigned int)OTSYS_TIME());
std::cout << "[done]" << std::endl;
#if defined LUA_CONFIGFILE
const char* configname = LUA_CONFIGFILE;
#elif defined __LUA_NAME_ALTER__
const char* configname = "otserv.lua";
#else
const char* configname = "config.lua";
#endif
if(command_opts.configfile != ""){
configname = command_opts.configfile.c_str();
}
// read global config
std::cout << ":: Loading lua script " << configname << "... " << std::flush;
#if !defined(WIN32) && !defined(__NO_HOMEDIR_CONF__)
std::string configpath;
configpath = getenv("HOME");
configpath += "/.otserv/";
configpath += configname;
if (!g_config.loadFile(configname) && !g_config.loadFile(configpath))
#else
if (!g_config.loadFile(configname))
#endif
{
std::ostringstream os;
#if !defined(WIN32) && !defined(__NO_HOMEDIR_CONF__)
os << "Unable to load " << configname << " or " << configpath;
#else
os << "Unable to load " << configname;
#endif
ErrorMessage(os.str());
exit(-1);
}
std::cout << "[done]" << std::endl;
std::cout << ":: Checking Database Connection... ";
Database* db = Database::instance();
if(db == NULL || !db->isConnected())
{
ErrorMessage("Database Connection Failed!");
exit(-1);
}
std::cout << "[done]" << std::endl;
std::stringstream filename;
//load vocations
filename.str("");
filename << g_config.getString(ConfigManager::DATA_DIRECTORY) << "vocations.xml";
std::cout << ":: Loading " << filename.str() << "... " << std::flush;
if(!g_vocations.loadFromXml(g_config.getString(ConfigManager::DATA_DIRECTORY))){
ErrorMessage("Unable to load vocations!");
exit(-1);
}
std::cout << "[done]" << std::endl;
//load commands
filename.str("");
filename << g_config.getString(ConfigManager::DATA_DIRECTORY) << "commands.xml";
std::cout << ":: Loading " << filename.str() << "... " << std::flush;
if(!commands.loadXml(g_config.getString(ConfigManager::DATA_DIRECTORY))){
std::stringstream errormsg;
errormsg << "Unable to load " << filename.str() << "!";
ErrorMessage(errormsg.str().c_str());
exit(-1);
}
std::cout << "[done]" << std::endl;
// load item data
filename.str("");
filename << g_config.getString(ConfigManager::DATA_DIRECTORY) << "items/items.otb";
std::cout << ":: Loading " << filename.str() << "... " << std::flush;
if(Item::items.loadFromOtb(filename.str())){
std::stringstream errormsg;
errormsg << "Unable to load " << filename.str() << "!";
ErrorMessage(errormsg.str().c_str());
exit(-1);
}
std::cout << "[done]" << std::endl;
filename.str("");
filename << g_config.getString(ConfigManager::DATA_DIRECTORY) << "items/items.xml";
std::cout << ":: Loading " << filename.str() << "... " << std::flush;
if(!Item::items.loadFromXml(g_config.getString(ConfigManager::DATA_DIRECTORY))){
std::stringstream errormsg;
errormsg << "Unable to load " << filename.str() << "!";
ErrorMessage(errormsg.str().c_str());
exit(-1);
}
std::cout << "[done]" << std::endl;
//load scripts
if(ScriptingManager::getInstance()->loadScriptSystems() == false){
exit(-1);
}
// load monster data
filename.str("");
filename << g_config.getString(ConfigManager::DATA_DIRECTORY) << "monsters/monsters.xml";
std::cout << ":: Loading " << filename.str() << "... " << std::flush;
if(!g_monsters.loadFromXml(g_config.getString(ConfigManager::DATA_DIRECTORY))){
std::stringstream errormsg;
errormsg << "Unable to load " << filename.str() << "!";
ErrorMessage(errormsg.str().c_str());
exit(-1);
}
std::cout << "[done]" << std::endl;
#ifdef __XID_EXPERIENCE_STAGES__
//load experience stages
filename.str("");
filename << g_config.getString(ConfigManager::DATA_DIRECTORY) << "stages.xml";
std::cout << ":: Loading stages.xml... ";
if(!g_game.loadExperienceStages()){
std::stringstream errormsg;
errormsg << "Unable to load " << filename.str() << "!";
ErrorMessage(errormsg.str().c_str());
exit(-1);
}
std::cout << "[done]" << std::endl;
#endif
std::cout << ":: Checking Schema version... ";
DBResult* result;
if(!(result = db->storeQuery("SELECT * FROM `schema_info`;"))){
ErrorMessage("Can't get schema version! Does `schema_info` exist?");
exit(-1);
}
int schema_version = result->getDataInt("version");
db->freeResult(result);
if(schema_version != CURRENT_SCHEMA_VERSION){
ErrorMessage("Your database is outdated. Run the dbupdate utility to update it to the latest schema version.");
exit(-1);
}
std::cout << "Version = " << schema_version << " ";
std::cout << "[done]" << std::endl;
std::string worldType = g_config.getString(ConfigManager::WORLD_TYPE);
if(asLowerCaseString(worldType) == "pvp")
g_game.setWorldType(WORLD_TYPE_PVP);
else if(asLowerCaseString(worldType) == "no-pvp")
g_game.setWorldType(WORLD_TYPE_NO_PVP);
else if(asLowerCaseString(worldType) == "pvp-enforced")
g_game.setWorldType(WORLD_TYPE_PVP_ENFORCED);
else{
ErrorMessage("Unknown world type!");
exit(-1);
}
std::cout << ":: Worldtype: " << asUpperCaseString(worldType) << std::endl;
#ifdef __SKULLSYSTEM__
std::cout << ":: Skulls enabled" << std::endl;
#endif
std::string passwordType = g_config.getString(ConfigManager::PASSWORD_TYPE_STR);
if(passwordType.empty() || asLowerCaseString(passwordType) == "plain"){
g_config.setNumber(ConfigManager::PASSWORD_TYPE, PASSWORD_TYPE_PLAIN);
std::cout << ":: Use plain passwords" << std::endl;
}
else if(asLowerCaseString(passwordType) == "md5"){
g_config.setNumber(ConfigManager::PASSWORD_TYPE, PASSWORD_TYPE_MD5);
std::cout << ":: Use MD5 passwords" << std::endl;
}
else if(asLowerCaseString(passwordType) == "sha1"){
g_config.setNumber(ConfigManager::PASSWORD_TYPE, PASSWORD_TYPE_SHA1);
std::cout << ":: Use SHA1 passwords" << std::endl;
}
else{
ErrorMessage("Unknown password type!");
exit(-1);
}
if(!g_game.loadMap(g_config.getString(ConfigManager::MAP_FILE),
g_config.getString(ConfigManager::MAP_KIND))){
exit(-1);
}
g_game.setGameState(GAME_STATE_INIT);
g_game.loadPlayersRecord();
std::pair<uint32_t, uint32_t> IpNetMask;
IpNetMask.first = inet_addr("127.0.0.1");
IpNetMask.second = 0xFFFFFFFF;
serverIPs.push_back(IpNetMask);
char szHostName[128];
if(gethostname(szHostName, 128) == 0){
std::cout << "::" << std::endl << ":: Running on host " << szHostName << std::endl;
hostent *he = gethostbyname(szHostName);
if(he){
std::cout << ":: Local IP address(es): ";
unsigned char** addr = (unsigned char**)he->h_addr_list;
while (addr[0] != NULL){
std::cout << (unsigned int)(addr[0][0]) << "."
<< (unsigned int)(addr[0][1]) << "."
<< (unsigned int)(addr[0][2]) << "."
<< (unsigned int)(addr[0][3]) << " ";
IpNetMask.first = *(uint32_t*)(*addr);
IpNetMask.second = 0x0000FFFF;
serverIPs.push_back(IpNetMask);
addr++;
}
std::cout << std::endl;
}
}
std::cout << ":: Local port: ";
int port = g_config.getNumber(ConfigManager::PORT);
std::cout << port << std::endl;
std::cout << ":: Global IP address: ";
std::string ip = g_config.getString(ConfigManager::IP);
uint32_t resolvedIp = inet_addr(ip.c_str());
if(resolvedIp == INADDR_NONE){
struct hostent* he = gethostbyname(ip.c_str());
if(he != 0){
resolvedIp = *(uint32_t*)he->h_addr;
}
else{
std::string error_msg = "Can't resolve: " + ip;
ErrorMessage(error_msg.c_str());
exit(-1);
}
}
char resolvedIpstr[32];
formatIP(resolvedIp, resolvedIpstr);
std::cout << resolvedIpstr << std::endl << "::" << std::endl;
IpNetMask.first = resolvedIp;
IpNetMask.second = 0;
serverIPs.push_back(IpNetMask);
std::cout << ":: Starting Server... ";
Status* status = Status::instance();
status->setMaxPlayersOnline(g_config.getNumber(ConfigManager::MAX_PLAYERS));
g_game.setGameState(GAME_STATE_NORMAL);
g_loaderSignal.notify_all();
}
| [
"[email protected]@6be3b30e-f956-11de-ba51-6b4196a2b81e"
]
| [
[
[
1,
575
]
]
]
|
d28fdfa6c87915bd42a561ec232dbf04543a73a3 | 0f973718202109e95fc25240d1cec2d952225732 | /Source/Cheese/ProbeControl.cpp | c3f4daf1ab822f85e508182e547c6f5144d7f4e6 | []
| no_license | RadicalZephyr/fast-ai | eeb9a7bb2357680f63f06c5d49361e274772b456 | 4f8b9847f6d59f0ec0fcbbdaef8b2c7291be338f | refs/heads/master | 2021-01-01T19:47:08.047409 | 2011-09-28T01:14:48 | 2011-09-28T01:14:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,949 | cpp | #include "ProbeControl.h"
using namespace BWAPI;
//const int NexusManager::s_mineralDistance = 270;
ProbeControl::ProbeControl(BWAPI::Unit *newProbe, onFindCallbackFunction callback) : m_probe(newProbe),
m_callback(callback),
timeout(0)
{
SIGNAL_ON_FRAME(ProbeControl);
Signal::onUnitDiscover().connect(boost::bind(&ProbeControl::onUnitDiscover, this, _1));
if (m_probe == 0) {
//Broodwar->printf("ERROR: ProbeControl: onStart: null pointer, disconnecting");
SIGNAL_OFF_FRAME(ProbeControl);
return;
}
std::set<TilePosition> & startLocations = Broodwar->getStartLocations();
TilePosition myPlace = Broodwar->self()->getStartLocation();
startLocations.erase(myPlace);
m_scoutLocations = startLocations.begin();
Position nextPlace(*m_scoutLocations);
nextPlace.makeValid();
if(m_probe->getPosition().hasPath(nextPlace)) {
m_probe->move(nextPlace);
}
else {
Broodwar->printf("No path to start location available");
m_callback(m_probe, 0);
SIGNAL_OFF_FRAME(ProbeControl);
Signal::onUnitDiscover().disconnect(boost::bind(&ProbeControl::onUnitDiscover, this, _1));
delete this;
}
}
void ProbeControl::onFrame()
{
if (m_probe->getPosition().getDistance(Position(*m_scoutLocations)) == 0) {
Broodwar->printf("Distance to start location is 0");
Position nextPlace(*(++m_scoutLocations));
nextPlace.makeValid();
timeout = 0;
if(m_probe->getPosition().hasPath(nextPlace)) {
m_probe->move(nextPlace);
}
else {
Broodwar->printf("No path to start location available");
m_callback(m_probe, 0);
SIGNAL_OFF_FRAME(ProbeControl);
Signal::onUnitDiscover().disconnect(boost::bind(&ProbeControl::onUnitDiscover, this, _1));
delete this;
}
}
if (timeout++ > 2000)
{
m_callback(m_probe, 0);
SIGNAL_OFF_FRAME(ProbeControl);
Signal::onUnitDiscover().disconnect(boost::bind(&ProbeControl::onUnitDiscover, this, _1));
delete this;
}
}
void ProbeControl::onUnitDiscover(BWAPI::Unit *unit) {
if (unit->getType().isResourceDepot() && unit->getPlayer() != Broodwar->self() &&
unit->getTilePosition() == m_probe->getTargetPosition()) {
// Broodwar->printf("PC: onUnitDiscover: found a %s at (%d, %d)", unit->getType().getName().c_str(), unit->getPosition().x(), unit->getPosition().y());
m_probe->stop();
m_callback(m_probe, unit);
SIGNAL_OFF_FRAME(ProbeControl);
Signal::onUnitDiscover().disconnect(boost::bind(&ProbeControl::onUnitDiscover, this, _1));
delete this;
}
} | [
"[email protected]",
"[email protected]",
"[email protected]"
]
| [
[
[
1,
5
],
[
9,
9
],
[
12,
12
],
[
18,
18
],
[
20,
20
],
[
22,
22
],
[
24,
24
],
[
40,
43
],
[
46,
46
],
[
50,
50
],
[
71,
71
]
],
[
[
6,
8
],
[
10,
11
],
[
13,
17
],
[
19,
19
],
[
21,
21
],
[
23,
23
],
[
25,
39
],
[
44,
45
],
[
47,
49
],
[
51,
61
],
[
63,
70
],
[
72,
83
]
],
[
[
62,
62
]
]
]
|
126aa67d6a6cda2a38f2e7473c405cf32b300b3f | fad6f9883d4ad2686c196dc532a9ecb9199500ee | /NXP-LPC/CommTest/CommTest/SvrRecvView.h | 98ab92058ad0a110111ec3dc2fc25a85e42cdee6 | []
| no_license | aquarius20th/nxp-lpc | fe83d6a140d361a1737d950ff728c6ea9a16a1dd | 4abfb804daf0ac9c59bd90d879256e7a3c1b2f30 | refs/heads/master | 2021-01-10T13:54:40.237682 | 2009-12-22T14:54:59 | 2009-12-22T14:54:59 | 48,420,260 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 701 | h | #pragma once
// CSvrRecvView 视图
class CSvrRecvView : public CBCGPFormView
{
DECLARE_DYNCREATE(CSvrRecvView)
protected:
CSvrRecvView(); // 动态创建所使用的受保护的构造函数
virtual ~CSvrRecvView();
public:
enum { IDD = IDD_DLG_SVR_RECV };
#ifdef _DEBUG
virtual void AssertValid() const;
#ifndef _WIN32_WCE
virtual void Dump(CDumpContext& dc) const;
#endif
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
DECLARE_MESSAGE_MAP()
public:
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnTimer(UINT_PTR nIDEvent);
};
| [
"lijin.unix@13de9a6c-71d3-11de-b374-81e7cb8b6ca2"
]
| [
[
[
1,
33
]
]
]
|
6201e423ae54218693d95d442d1c38c8bcb57584 | 94c1c7459eb5b2826e81ad2750019939f334afc8 | /source/CSharesDetailList.h | 186a4e594347377f6b6b54585cc446e9c1be8bec | []
| no_license | wgwang/yinhustock | 1c57275b4bca093e344a430eeef59386e7439d15 | 382ed2c324a0a657ddef269ebfcd84634bd03c3a | refs/heads/master | 2021-01-15T17:07:15.833611 | 2010-11-27T07:06:40 | 2010-11-27T07:06:40 | 37,531,026 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,192 | h | #if !defined(AFX_STOCKDETAILLIST_H__7E188421_08E3_11D2_88EE_0080C8E20736__INCLUDED_)
#define AFX_STOCKDETAILLIST_H__7E188421_08E3_11D2_88EE_0080C8E20736__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// CSharesDetailList.h : header file
//
#include "CTaiShanDoc.h"
/////////////////////////////////////////////////////////////////////////////
// CSharesDetailList window
class CSharesDetailList : public CListCtrl
{
public:
CSharesDetailList();
public:
public:
int RedOrGreen[2000];
int num;
bool m_IsF1;
CTaiShanDoc* pDoc;
//{{AFX_VIRTUAL(CSharesDetailList)
//}}AFX_VIRTUAL
public:
virtual ~CSharesDetailList();
virtual void DrawItem( LPDRAWITEMSTRUCT lpDrawItemStruct );
protected:
//{{AFX_MSG(CSharesDetailList)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_STOCKDETAILLIST_H__7E188421_08E3_11D2_88EE_0080C8E20736__INCLUDED_)
| [
"[email protected]"
]
| [
[
[
1,
52
]
]
]
|
f919d700bd1b2b84d4980887062afa9d739b2294 | 9bc85a2a7213db0725beb6ac7bbace0d1f239784 | /include/PsFile.h | c71c7169a2ff9a9a8ae5fce045aa1b08c702833d | []
| no_license | doodoonovitch/fastxml | ac17d6679a0cb6c3044a43160f490a4df9c3441f | f3d55399d09899ce48d5a8b496d8c9ea4117ff86 | refs/heads/master | 2021-01-10T12:16:26.743154 | 2010-07-15T22:31:14 | 2010-07-15T22:31:14 | 44,275,364 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,574 | h | #ifndef PS_FILE_H
#define PS_FILE_H
#include <stdio.h>
/*!
**
** Copyright (c) 2010 by John W. Ratcliff mailto:[email protected]
**
** Skype ID: jratcliff63367
** Yahoo: jratcliff63367
** AOL: jratcliff1961
** email: [email protected]
**
**
** The MIT license:
**
** 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.
*/
namespace physx
{
PX_INLINE errno_t fopen_s( FILE ** _File, const char * _Filename, const char * _Mode)
{
return ::fopen_s( _File, _Filename, _Mode);
};
};
#endif
| [
"jratcliffscarab@8511ecbf-a51f-191b-956b-410d5f6f4539"
]
| [
[
[
1,
48
]
]
]
|
632e3c613190717220fd128ca228142791362fc7 | d7910157c6f2b58f159ec8dc2634e0acfe6d678e | /qtdemo/demoitemanimation.h | 81dabe01f643667a0a83c7c60f44536a39572288 | []
| no_license | TheProjecter/qtdemo-plugin | 7699b19242aacea9c5b2c741e615e6b1e62c6c11 | 4db5ffe7e8607e01686117820ce1fcafb72eb311 | refs/heads/master | 2021-01-19T06:30:22.017229 | 2010-02-05T06:36:25 | 2010-02-05T06:36:25 | 43,904,026 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,424 | h | /****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the demonstration applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef DEMO_ITEM_ANIMATION_H
#define DEMO_ITEM_ANIMATION_H
#include <QtCore>
#include <QtGui>
class DemoItem;
class DemoItemAnimation : public QGraphicsItemAnimation
{
Q_OBJECT
public:
enum INOROUT {ANIM_IN, ANIM_OUT, ANIM_UNSPECIFIED};
DemoItemAnimation(DemoItem *item, INOROUT inOrOut = ANIM_UNSPECIFIED);
virtual ~DemoItemAnimation();
virtual void play(bool fromStart = true, bool force = false);
virtual void playReverse();
virtual void stop(bool reset = true);
virtual void setRepeat(int nr = 0);
void setDuration(int duration);
void setDuration(float duration){ setDuration(int(duration)); };
void setOpacityAt0(qreal opacity);
void setOpacityAt1(qreal opacity);
void setOpacity(qreal step);
void setCurrentTime(int ms);
void setStartPos(const QPointF &pos);
bool notOwnerOfItem();
bool running();
bool runningOrItemLocked();
void lockItem(bool state);
void prepare();
DemoItem *demoItem();
virtual void afterAnimationStep(qreal step); // overridden
QTimeLine *timeline;
qreal opacityAt0;
qreal opacityAt1;
int startDelay;
QPointF startPos;
bool hideOnFinished;
bool moveOnPlay;
bool forcePlay;
bool fromStart;
INOROUT inOrOut;
private slots:
virtual void playWithoutDelay();
};
#endif // DEMO_ITEM_ANIMATION_H
| [
"douyongwang@152bb772-114e-11df-9f54-17e475596acb"
]
| [
[
[
1,
101
]
]
]
|
e5cecc842c1122032f157793182a5329987f1518 | aa56ef00377b2c63a9afb2de1132fc7252ce3dde | /procon/SPSC_RingBufferQueue_PushPopTest.cpp | 18918a9c82e8c2c16a6962b204f1abd2c3a7a0ed | []
| no_license | k06a/procon | 5796fdd9e605b93b3d8ba57362d223182ccd5f12 | 56b35da383a9b4b1f5899e1bc09261315c57f49c | refs/heads/master | 2020-04-06T04:36:12.527471 | 2011-12-28T12:28:50 | 2011-12-28T12:28:50 | 32,887,639 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,680 | cpp | #include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "SPSC_RingBufferQueue_Common.h"
#include "SPSC_RingBufferQueue.h"
//////////////////////////////////////////////////////////////////////////
typedef SPSC_RingBufferQueue<int> IntQueue;
struct Context
{
int N;
IntQueue queue;
Context(int N, int bufferSize)
: N(N), queue(bufferSize)
{
}
};
static void producer(void * param)
{
Context * context = (Context*)param;
for(int i = 0; i < context->N; i++)
context->queue.push(new int(i));
}
static void consumer(void * param)
{
Context * context = (Context*)param;
for(int i = 0; i < context->N; i++)
{
int * val = context->queue.pop();
EXPECT_EQ(i, *val);
delete val;
}
}
//////////////////////////////////////////////////////////////////////////
TEST(SPSC_RingBufferQueue, PushPop_1K_via_100)
{
Context * context = new Context(1000,100);
SPSC_RingBufferQueue_Test(producer,consumer,context);
}
TEST(SPSC_RingBufferQueue, PushPop_1K_via_10)
{
Context * context = new Context(1000,10);
SPSC_RingBufferQueue_Test(producer,consumer,context);
}
TEST(SPSC_RingBufferQueue, PushPop_1K_via_2)
{
Context * context = new Context(1000,2);
SPSC_RingBufferQueue_Test(producer,consumer,context);
}
TEST(SPSC_RingBufferQueue, PushPop_1K_via_1)
{
Context * context = new Context(1000,1);
SPSC_RingBufferQueue_Test(producer,consumer,context);
}
//////////////////////////////////////////////////////////////////////////
TEST(SPSC_RingBufferQueue, PushPop_100K_via_10K)
{
Context * context = new Context(100000,10000);
SPSC_RingBufferQueue_Test(producer,consumer,context);
}
TEST(SPSC_RingBufferQueue, PushPop_100K_via_1K)
{
Context * context = new Context(100000,1000);
SPSC_RingBufferQueue_Test(producer,consumer,context);
}
TEST(SPSC_RingBufferQueue, PushPop_100K_via_100)
{
Context * context = new Context(100000,100);
SPSC_RingBufferQueue_Test(producer,consumer,context);
}
TEST(SPSC_RingBufferQueue, PushPop_100K_via_10)
{
Context * context = new Context(100000,10);
SPSC_RingBufferQueue_Test(producer,consumer,context);
}
TEST(SPSC_RingBufferQueue, PushPop_100K_via_2)
{
Context * context = new Context(100000,2);
SPSC_RingBufferQueue_Test(producer,consumer,context);
}
TEST(SPSC_RingBufferQueue, PushPop_100K_via_1)
{
Context * context = new Context(100000,1);
SPSC_RingBufferQueue_Test(producer,consumer,context);
}
//////////////////////////////////////////////////////////////////////////
| [
"[email protected]"
]
| [
[
[
1,
106
]
]
]
|
0bb73d137bef081a1d6c0b004d2d39484b1cbec7 | b84a38aad619acf34c22ed6e6caa0f7b00ebfa0a | /Code/TootleCore/TTransform.cpp | ff9dbde7c2ffd58298b9d847ba80a239a71c885e | []
| no_license | SoylentGraham/Tootle | 4ae4e8352f3e778e3743e9167e9b59664d83b9cb | 17002da0936a7af1f9b8d1699d6f3e41bab05137 | refs/heads/master | 2021-01-24T22:44:04.484538 | 2010-11-03T22:53:17 | 2010-11-03T22:53:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,658 | cpp | /*
* TTransform.cpp
* TootleCore
*
* Created by Duane Bradbury on 27/10/2009.
* Copyright 2009 Tootle. All rights reserved.
*
*/
#include "TTransform.h"
#include "TBinaryTree.h"
#include "TLDebug.h"
//-----------------------------------------------------------
// import transform data from binary data/message/etc- ChangedBits specifies which parts have changed
//-----------------------------------------------------------
u8 TLMaths::TTransform::ImportData(TBinaryTree& Data)
{
u8 ChangedBits = 0x0;
// import translate
float3 OldTranslate = m_Translate;
Bool ChangedTransform = Data.ImportData( Properties::Translation, m_Translate );
// gr: now support setting of just the Z
ChangedTransform |= Data.ImportData( Properties::ZTranslation, m_Translate.z );
if ( ChangedTransform )
{
TLDebug_CheckFloat( m_Translate );
// only consider value changed if different, or was preivously invalid
if ( !HasTranslate() || m_Translate != OldTranslate )
ChangedBits |= TLMaths_TransformBitTranslate;
}
// import scale
float3 OldScale = m_Scale;
if ( Data.ImportData( Properties::Scale, m_Scale ) )
{
TLDebug_CheckFloat( m_Scale );
// only consider value changed if different, was preivously invalid
if ( !HasScale() || m_Scale != OldScale )
ChangedBits |= TLMaths_TransformBitScale;
}
// import rotation
TQuaternion OldRotation = m_Rotation;
if ( Data.ImportData( Properties::Rotation, m_Rotation ) )
{
TLDebug_CheckFloat( m_Rotation );
// only consider value changed if different, or was preivously invalid
if ( !HasRotation() || m_Rotation != OldRotation )
ChangedBits |= TLMaths_TransformBitRotation;
}
// anything we imported is now considered valid...
m_Valid |= ChangedBits;
return ChangedBits;
}
//-----------------------------------------------------------
// export all our valid data to this binary data- can optionally make it only write certain attributes. Returns attributes written
//-----------------------------------------------------------
u8 TLMaths::TTransform::ExportData(TBinaryTree& Data,u8 TransformBits) const
{
// only write bits that are valid
TransformBits &= m_Valid;
if ( (TransformBits & TLMaths_TransformBitTranslate) != 0x0 )
{
TLDebug_CheckFloat( m_Translate );
Data.ExportData( Properties::Translation, m_Translate );
}
if ( (TransformBits & TLMaths_TransformBitScale) != 0x0 )
{
TLDebug_CheckFloat( m_Scale );
Data.ExportData( Properties::Scale, m_Scale );
}
if ( (TransformBits & TLMaths_TransformBitRotation) != 0x0 )
{
TLDebug_CheckFloat( m_Rotation );
Data.ExportData( Properties::Rotation, m_Rotation );
}
return TransformBits;
}
//-----------------------------------------------------------
// export all our valid data to this binary data- can optionally make it only write certain attributes. Returns attributes written
//-----------------------------------------------------------
u8 TLMaths::TTransform::ReplaceData(TBinaryTree& Data,u8 TransformBits) const
{
// need to remove some parts of the data
u8 RemoveBits = m_Valid & ~TransformBits;
// only write bits that are valid
TransformBits &= m_Valid;
if ( (TransformBits & TLMaths_TransformBitTranslate) != 0x0 )
{
TLDebug_CheckFloat( m_Translate );
Data.ReplaceData( Properties::Translation, m_Translate );
}
else if ( ( RemoveBits & TLMaths_TransformBitTranslate ) != 0x0 )
{
Data.RemoveChild( Properties::Translation );
}
if ( (TransformBits & TLMaths_TransformBitScale) != 0x0 )
{
TLDebug_CheckFloat( m_Scale );
Data.ReplaceData( Properties::Scale, m_Scale );
}
else if ( ( RemoveBits & TLMaths_TransformBitScale ) != 0x0 )
{
Data.RemoveChild( Properties::Scale );
}
if ( (TransformBits & TLMaths_TransformBitRotation) != 0x0 )
{
TLDebug_CheckFloat( m_Rotation );
Data.ReplaceData( Properties::Rotation, m_Rotation );
}
else if ( ( RemoveBits & TLMaths_TransformBitRotation ) != 0x0 )
{
Data.RemoveChild( Properties::Rotation );
}
return TransformBits;
}
//-----------------------------------------------------------
// transform this by Trans.
// THIS is the parent, Trans is the "child" transform
//-----------------------------------------------------------
void TLMaths::TTransform::Transform(const TLMaths::TTransform& Trans)
{
if ( Trans.HasTranslate() )
{
float3 Translate = Trans.m_Translate;
// gr: this is from the render code, we transform the translate of the child by ourselves(the parent)
// so the translate gets rotated, scaled etc... theres a possibility this might be wrong for other things, but Im not sure if it is or not
// it's done BEFORE the merge of the rotation and the matrix of the child
// the order of the other parts doesn't matter as they dont interact, where as this does
Transform( Translate );
SetTranslate( Translate );
TLDebug_CheckFloat( Translate );
}
if ( Trans.HasScale() )
{
if ( HasScale() )
m_Scale *= Trans.m_Scale;
else
SetScale( Trans.m_Scale );
TLDebug_CheckFloat( m_Scale );
}
if ( Trans.HasRotation() )
{
if ( HasRotation() )
{
m_Rotation *= Trans.m_Rotation;
}
else
{
SetRotation( Trans.m_Rotation );
m_Rotation.Normalise();
}
TLDebug_CheckFloat( m_Rotation );
}
}
//-----------------------------------------------------------
// transform this by another transform. returns elements that have changed
// (slightly slower, but if your caller does much LESS work if nothing changed then use this)
//-----------------------------------------------------------
u8 TLMaths::TTransform::Transform_HasChanged(const TLMaths::TTransform& Trans)
{
u8 ChangedBits = 0x0;
if ( Trans.HasTranslate() )
{
if ( Trans.m_Translate.IsNonZero() )
{
float3 Translate = Trans.m_Translate;
// gr: this is from the render code, we transform the translate of the child by ourselves(the parent)
// so the translate gets rotated, scaled etc... theres a possibility this might be wrong for other things, but Im not sure if it is or not
// it's done BEFORE the merge of the rotation and the matrix of the child
// the order of the other parts doesn't matter as they dont interact, where as this does
Transform( Translate );
ChangedBits |= SetTranslateHasChanged( Translate );
TLDebug_CheckFloat( Translate );
}
}
if ( Trans.HasScale() )
{
if ( HasScale() )
m_Scale *= Trans.m_Scale;
else
SetScale( Trans.m_Scale );
// assume scale always changes... can check Trans.m_Scale.LengthSq() == 1 i think to see if its all 1's. Not sure how accurate that is...
ChangedBits |= TLMaths_TransformBitScale;
TLDebug_CheckFloat( m_Scale );
}
if ( Trans.HasRotation() )
{
// gr: needs normalising?
if ( HasRotation() )
m_Rotation *= Trans.m_Rotation;
else
SetRotation( Trans.m_Rotation );
// assume rotation always changes...
ChangedBits |= TLMaths_TransformBitScale;
TLDebug_CheckFloat( m_Rotation );
}
return ChangedBits;
}
//-----------------------------------------------------------
// Modify the transform values by another transform, Translates the translate, scales the scale, rotates the rotation. Doesn't multiply and rotate the translate etc
//-----------------------------------------------------------
void TLMaths::TTransform::AddTransform(const TLMaths::TTransform& Trans)
{
if ( Trans.HasTranslate() )
{
if ( HasTranslate() )
m_Translate += Trans.GetTranslate();
else
SetTranslate( Trans.GetTranslate() );
TLDebug_CheckFloat( m_Translate );
}
if ( Trans.HasScale() )
{
if ( HasScale() )
m_Scale *= Trans.m_Scale;
else
SetScale( Trans.m_Scale );
TLDebug_CheckFloat( m_Scale );
}
if ( Trans.HasRotation() )
{
// gr: needs normalising?
if ( HasRotation() )
m_Rotation *= Trans.m_Rotation;
else
SetRotation( Trans.m_Rotation );
TLDebug_CheckFloat( m_Rotation );
}
}
//-----------------------------------------------------------
// Modify the transform values by another transform, Translates the translate, scales the scale, rotates the rotation. Doesn't multiply and rotate the translate etc. returns elements that have changed (slightly slower, but if your caller does much LESS work if nothing changed then use this)
//-----------------------------------------------------------
u8 TLMaths::TTransform::AddTransform_HasChanged(const TLMaths::TTransform& Trans)
{
u8 ChangedBits = 0x0;
if ( Trans.HasTranslate() )
{
if ( Trans.m_Translate.IsNonZero() )
{
if ( HasTranslate() )
m_Translate += Trans.GetTranslate();
else
SetTranslate( Trans.GetTranslate() );
ChangedBits |= TLMaths_TransformBitTranslate;
TLDebug_CheckFloat( m_Translate );
}
}
if ( Trans.HasScale() )
{
if ( HasScale() )
m_Scale *= Trans.m_Scale;
else
SetScale( Trans.m_Scale );
// assume scale always changes... can check Trans.m_Scale.LengthSq() == 1 i think to see if its all 1's. Not sure how accurate that is...
ChangedBits |= TLMaths_TransformBitScale;
TLDebug_CheckFloat( m_Scale );
}
if ( Trans.HasRotation() )
{
// gr: needs normalising?
if ( HasRotation() )
m_Rotation *= Trans.m_Rotation;
else
SetRotation( Trans.m_Rotation );
// assume rotation always changes...
ChangedBits |= TLMaths_TransformBitScale;
TLDebug_CheckFloat( m_Rotation );
}
return ChangedBits;
}
//-----------------------------------------------------------
// transform vector
//-----------------------------------------------------------
void TLMaths::TTransform::Transform(float3& Vector) const
{
TLDebug_CheckFloat( Vector );
// if we're transforming a vector that is 0,0,0 then scale and rotation will do nothing
if ( Vector.IsNonZero() )
{
if ( HasScale() )
{
Vector *= GetScale();
TLDebug_CheckFloat( Vector );
}
if ( HasRotation() )
{
GetRotation().RotateVector( Vector );
TLDebug_CheckFloat( Vector );
}
}
if ( HasTranslate() )
{
Vector += GetTranslate();
TLDebug_CheckFloat( Vector );
}
}
//-----------------------------------------------------------
// transform vector
//-----------------------------------------------------------
void TLMaths::TTransform::Transform(float2& Vector) const
{
TLDebug_CheckFloat( Vector );
// if we're transforming a vector that is 0,0,0 then scale and rotation will do nothing
if ( Vector.IsNonZero() )
{
if ( HasScale() )
{
Vector *= GetScale();
TLDebug_CheckFloat( Vector );
}
if ( HasRotation() )
{
GetRotation().RotateVector( Vector );
TLDebug_CheckFloat( Vector );
}
}
if ( HasTranslate() )
{
Vector += GetTranslate();
TLDebug_CheckFloat( Vector );
}
}
//-----------------------------------------------------------
// untransform vector
//-----------------------------------------------------------
void TLMaths::TTransform::Untransform(float3& Vector) const
{
TLDebug_CheckFloat( Vector );
if ( HasTranslate() )
{
Vector -= GetTranslate();
TLDebug_CheckFloat( Vector );
}
if ( HasRotation() )
{
GetRotation().UnrotateVector( Vector );
TLDebug_CheckFloat( Vector );
}
if ( HasScale() )
{
Vector /= GetScale();
TLDebug_CheckFloat( Vector );
}
}
//-----------------------------------------------------------
// untransform vector
//-----------------------------------------------------------
void TLMaths::TTransform::Untransform(float2& Vector) const
{
TLDebug_CheckFloat( Vector );
if ( HasTranslate() )
{
Vector -= GetTranslate().xy();
TLDebug_CheckFloat( Vector );
}
if ( HasRotation() )
{
GetRotation().UnrotateVector( Vector );
TLDebug_CheckFloat( Vector );
}
if ( HasScale() )
{
Vector /= GetScale().xy();
TLDebug_CheckFloat( Vector );
}
}
//-----------------------------------------------------------
// make an "untransform" from this transform. (inverts rotation, scale, trans)
//-----------------------------------------------------------
void TLMaths::TTransform::Invert()
{
// negate translate
if ( HasTranslate() )
{
m_Translate.x = -m_Translate.x;
m_Translate.y = -m_Translate.y;
m_Translate.z = -m_Translate.z;
}
// invert rotation
if ( HasRotation() )
{
m_Rotation.Invert();
}
// get reciprocal of scale
if ( HasScale() )
{
m_Scale.x = 1.f/m_Scale.x;
m_Scale.y = 1.f/m_Scale.y;
m_Scale.z = 1.f/m_Scale.z;
}
}
//-----------------------------------------------------------
// assert handler
//-----------------------------------------------------------
void TLMaths::TTransform::Debug_Assert(const char* pString) const
{
TLDebug_Break( pString );
}
//-----------------------------------------------------------
// see if transforms are same
//-----------------------------------------------------------
Bool TLMaths::TTransform::operator==(const TLMaths::TTransform& Transform) const
{
// quick check to see if valid elements are different or not...
// technically we could have scale=1 or transform=0 and they'd have the same EFFECT, but validity is different..
if ( GetHasTransformBits() != Transform.GetHasTransformBits() )
return FALSE;
if ( HasTranslate() && GetTranslate() != Transform.GetTranslate() )
return FALSE;
if ( HasScale() && GetScale() != Transform.GetScale() )
return FALSE;
if ( HasRotation() && GetRotation() != Transform.GetRotation() )
return FALSE;
return TRUE;
}
//-----------------------------------------------------------
// see if transforms are different
//-----------------------------------------------------------
Bool TLMaths::TTransform::operator!=(const TLMaths::TTransform& Transform) const
{
// quick check to see if valid elements are different or not...
// technically we could have scale=1 or transform=0 and they'd have the same EFFECT, but validity is different..
if ( GetHasTransformBits() == Transform.GetHasTransformBits() )
return FALSE;
if ( HasTranslate() && GetTranslate() == Transform.GetTranslate() )
return FALSE;
if ( HasScale() && GetScale() == Transform.GetScale() )
return FALSE;
if ( HasRotation() && GetRotation() == Transform.GetRotation() )
return FALSE;
return TRUE;
}
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
24
],
[
26,
27
],
[
29,
40
],
[
42,
52
],
[
54,
71
],
[
73,
79
],
[
81,
85
],
[
87,
91
],
[
93,
98
],
[
144,
534
]
],
[
[
25,
25
],
[
28,
28
],
[
41,
41
],
[
53,
53
],
[
72,
72
],
[
80,
80
],
[
86,
86
],
[
92,
92
],
[
99,
143
]
]
]
|
0825c2f38f5abef0c41726224fa9ad6c08646b24 | 96fefafdfbb413a56e0a2444fcc1a7056afef757 | /MQ2Map/ISXEQMapCommands.cpp | aed55f9cb78c3898e26123138c6b4e2fe3b86a27 | []
| no_license | kevrgithub/peqtgc-mq2-sod | ffc105aedbfef16060769bb7a6fa6609d775b1fa | d0b7ec010bc64c3f0ac9dc32129a62277b8d42c0 | refs/heads/master | 2021-01-18T18:57:16.627137 | 2011-03-06T13:05:41 | 2011-03-06T13:05:41 | 32,849,784 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 9,939 | cpp | #include "../MQ2Plugin.h"
#include "MQ2Map.h"
VOID MapFilterSetting( DWORD nMapFilter, int arg, int argc, char *argv[])
{
CHAR szBuffer[MAX_STRING] = {0};
CHAR Buff[MAX_STRING]={0};
DWORD dwValue = 0;
PCHAR szFilterMap[] = {
"hide",
"show",
NULL
};
PMAPFILTER pMapFilter=&MapFilterOptions[nMapFilter];
if (!RequirementsMet(nMapFilter))
{
WriteChatf("'%s' requires '%s' option. Please enable this option first.",pMapFilter->szName,MapFilterOptions[pMapFilter->RequiresOption].szName);
return;
}
if (arg>=argc)
{
// NO VALUE
char szBuffer[2048]={0};
if (pMapFilter->bIsToggle)
{
sprintf(szBuffer,"%s: %s",pMapFilter->szName,szFilterMap[pMapFilter->Enabled]);
}
else if (nMapFilter == MAPFILTER_Custom)
{
if (IsOptionEnabled(nMapFilter)==0)
{
sprintf(szBuffer,"%s: Off",pMapFilter->szName);
}
else
{
sprintf(szBuffer,"%s: %s",pMapFilter->szName,FormatSearchSpawn(Buff,&MapFilterCustom));
}
}
else
{
sprintf(szBuffer,"%s: %d",pMapFilter->szName,pMapFilter->Enabled);
}
if (pMapFilter->DefaultColor != -1)
{
CHAR szBuffer2[MAX_STRING] = {0};
DWORD R,G,B;
R= (pMapFilter->Color&0xFF0000)/0x10000;
G= (pMapFilter->Color&0xFF00)/0x100;
B= pMapFilter->Color&0xFF;
WriteChatf("%s (Color: %d %d %d)",szBuffer,R,G,B);
}
else
WriteChatf("%s",szBuffer);
return;
}
if (pMapFilter->bIsToggle)
{
if (!stricmp(szFilterMap[0],argv[arg]))
{
pMapFilter->Enabled = 0;
}
else if (!stricmp(szFilterMap[1],argv[arg]))
{
pMapFilter->Enabled = 1;
}
else
{
pMapFilter->Enabled = 1 - pMapFilter->Enabled;
}
WriteChatf("%s is now set to: %s",pMapFilter->szName,szFilterMap[IsOptionEnabled(nMapFilter)]);
}
else if (nMapFilter == MAPFILTER_Custom)
{
ClearSearchSpawn(&MapFilterCustom);
{
pMapFilter->Enabled = 1;
ParseSearchSpawn(arg+1,argc,argv,MapFilterCustom);
WriteChatf("%s is now set to: %s",pMapFilter->szName,FormatSearchSpawn(Buff,&MapFilterCustom));
}
}
else
{
pMapFilter->Enabled = atoi(argv[arg]);
WriteChatf("%s is now set to: %d",pMapFilter->szName,pMapFilter->Enabled);
}
itoa(pMapFilter->Enabled,szBuffer,10);
pISInterface->SetSettingi("ISXEQMap.xml","Map Filters",pMapFilter->szName,pMapFilter->Enabled);
pISInterface->SaveSettings("ISXEQMap.xml");
}
int CMD_MapFilter(int argc, char *argv[])
{
// Display settings
if (argc<2)
{
WriteChatColor("Map filtering settings:",USERCOLOR_DEFAULT);
WriteChatColor("-----------------------",USERCOLOR_DEFAULT);
for (DWORD i=0;MapFilterOptions[i].szName!=NULL;i++)
if (RequirementsMet(i))
MapFilterSetting(i,argc,argc,argv);
return 0;
}
if (!stricmp(argv[1],"help"))
{
// Display Help
WriteChatColor("Map filtering options:",USERCOLOR_DEFAULT);
for (DWORD i=0;MapFilterOptions[i].szName!=NULL;i++)
{
WriteChatf("%s%s: %s",MapFilterOptions[i].szName,(MapFilterOptions[i].bIsToggle)?"":" #",MapFilterOptions[i].szHelpString);
}
WriteChatColor("'option' color [r g b]: Set display color for 'option' (Omit to reset to default)",USERCOLOR_DEFAULT);
return 0;
}
// Set option
for (DWORD i=0;MapFilterOptions[i].szName!=NULL;i++)
{
if (!stricmp(argv[1],MapFilterOptions[i].szName))
{
if (argc>=3 && !stricmp(argv[2],"color"))
{
if (MapFilterOptions[i].DefaultColor == -1)
{
WriteChatf("Option '%s' does not have a color.",MapFilterOptions[i].szName);
}
else
{
DWORD R,G,B;
if (argc<6)
{
MapFilterOptions[i].Color = MapFilterOptions[i].DefaultColor;
}
else
{
R=atoi(argv[3]);
G=atoi(argv[4]);
B=atoi(argv[5]);
if (R>255) R=255;
if (G>255) G=255;
if (B>255) B=255;
MapFilterOptions[i].Color = R*0x10000 + G*0x100 + B;
}
WriteChatf("Option '%s' color set to: %d %d %d",MapFilterOptions[i].szName,R,G,B);
//itoa(MapFilterOptions[i].Color & 0xFFFFFF,szBuffer,10);
char szBuffer[128];
sprintf(szBuffer,"%s Color",MapFilterOptions[i].szName);
pISInterface->SetSettingi("ISXEQMap.XML","Map Filters",szBuffer,MapFilterOptions[i].Color & 0xFFFFFF);
pISInterface->SaveSettings("ISXEQMap.XML");
MapFilterOptions[i].Color |= 0xFF000000;
}
}
else
{
MapFilterSetting(i,2,argc,argv);
}
if (MapFilterOptions[i].RegenerateOnChange)
{
MapClear();
MapGenerate();
}
return 0;
}
}
WriteChatf("Usage: %s <option>|help",argv[0]);
return 0;
}
int CMD_MapHide(int argc, char *argv[])
{
if (argc<2)
{
WriteChatf("Syntax: %s <spawnfilter>|reset",argv[0]);
return 0;
};
if (!stricmp(argv[1],"reset"))
{
MapClear();
MapGenerate();
WriteChatColor("Map spawns regenerated",USERCOLOR_DEFAULT);
return 0;
}
if (PCHARINFO pCharInfo=GetCharInfo())
{
SEARCHSPAWN ssHide;
ClearSearchSpawn(&ssHide);
ParseSearchSpawn(1,argc,argv,ssHide);
WriteChatf("%d mapped spawns hidden",MapHide(ssHide));
}
return 0;
}
int CMD_MapShow(int argc, char *argv[])
{
if (argc<2)
{
WriteChatf("Syntax: %s <spawnfilter>|reset",argv[0]);
return 0;
};
if (!stricmp(argv[1],"reset"))
{
MapClear();
MapGenerate();
WriteChatf("Map spawns regenerated");
return 0;
}
if (PCHARINFO pCharInfo=GetCharInfo())
{
SEARCHSPAWN ssShow;
ClearSearchSpawn(&ssShow);
ParseSearchSpawn(1,argc,argv,ssShow);
WriteChatf("%d previously hidden spawns shown",MapShow(ssShow));
}
return 0;
}
int CMD_MapHighlight(int argc, char *argv[])
{
if (argc<2)
{
WriteChatf("Syntax: /highlight reset|<spawnfilter>|color <#> <#> <#>");
return 0;
};
if (!stricmp(argv[1],"color"))
{
if (argc<5)
{
WriteChatf("Highlight color: %d %d %d",(HighlightColor&0x00FF0000)>>16,(HighlightColor&0x0000FF00)>>8,(HighlightColor&0x000000FF));
return 0;
}
unsigned char R=atoi(argv[2]);
unsigned char G=atoi(argv[3]);
unsigned char B=atoi(argv[4]);
HighlightColor=0xFF000000 | (R << 16) | (G << 8) | (B);
WriteChatf("Highlight color: %d %d %d",R,G,B);
return 0;
}
else if (!stricmp(argv[1],"reset"))
{
MapHighlight(0);
WriteChatColor("Highlighting reset",USERCOLOR_DEFAULT);
return 0;
}
if (PCHARINFO pCharInfo=GetCharInfo())
{
SEARCHSPAWN ssHighlight;
ClearSearchSpawn(&ssHighlight);
ParseSearchSpawn(1,argc,argv,ssHighlight);
WriteChatf("%d mapped spawns highlighted",MapHighlight(&ssHighlight));
}
return 0;
}
int CMD_MapNames(int argc, char *argv[])
{
if (argc<2)
{
WriteChatf("Normal naming string: %s",MapNameString);
WriteChatf("Target naming string: %s",MapTargetNameString);
return 0;
}
if (!stricmp(argv[1],"target"))
{
if (argc==3 && !stricmp(argv[2],"reset"))
strcpy(MapTargetNameString,"%N");
else
pISInterface->GetArgs(2,argc,argv,MapTargetNameString);
WriteChatf("Target naming string: %s",MapTargetNameString);
pISInterface->SetSetting("ISXEQMap.XML","Naming Schemes","Target",MapTargetNameString);
pISInterface->SaveSettings("ISXEQMap.XML");
MapClear();
MapGenerate();
}
else if (!stricmp(argv[1],"normal"))
{
if (argc==3 && !stricmp(argv[2],"reset"))
strcpy(MapNameString,"%N");
else
pISInterface->GetArgs(2,argc,argv,MapNameString);
WriteChatf("Normal naming string: %s",MapNameString);
pISInterface->SetSetting("ISXEQMap.XML","Naming Schemes","Normal",MapNameString);
pISInterface->SaveSettings("ISXEQMap.XML");
MapClear();
MapGenerate();
}
else
{
WriteChatf("Syntax: %s target|normal <value>|reset",argv[0]);
}
return 0;
}
extern PCHAR DescribeCombo(DWORD Combo);
extern DWORD ParseCombo(PCHAR Combo);
int CMD_MapClick(int argc, char *argv[])
{
if (argc<2)
{
WriteChatf("Syntax: %s list|[key[+key[...]]] clear|<command>");
return 0;
}
if (!stricmp(argv[1],"list"))
{
int Count=0;
for (int i=1 ; i < 16 ; i++)
{
if (MapSpecialClickString[i][0])
{
WriteChatf("%s: %s",DescribeCombo(i),MapSpecialClickString[i]);
Count++;
}
}
WriteChatf("%d special right-click commands",Count);
return 0;
}
DWORD Combo=ParseCombo(argv[1]);
if (!Combo)
{
WriteChatf("Invalid combo '%s'",argv[1]);
return 0;
}
if (argc<3)
{
WriteChatf("%s: %s",DescribeCombo(Combo),MapSpecialClickString[Combo]);
return 0;
}
char szBuffer[2048];
sprintf(szBuffer,"KeyCombo%d",Combo);
if (!stricmp(argv[2],"clear"))
{
MapSpecialClickString[Combo][0]=0;
pISInterface->SetSetting("ISXEQMap.XML","Right Click",szBuffer,MapSpecialClickString[Combo]);
pISInterface->SaveSettings("ISXEQMap.XML");
WriteChatf("%s cleared",DescribeCombo(Combo));
return 0;
}
pISInterface->GetArgs(2,argc,argv,MapSpecialClickString[Combo]);
pISInterface->SetSetting("ISXEQMap.XML","Right Click",szBuffer,MapSpecialClickString[Combo]);
pISInterface->SaveSettings("ISXEQMap.XML");
WriteChatf("%s: %s",DescribeCombo(Combo),MapSpecialClickString[Combo]);
return 0;
}
| [
"[email protected]@39408780-f958-9dab-a28b-4b240efc9052"
]
| [
[
[
1,
352
]
]
]
|
beb782faa8526fd137e38985af2880e8eba37ad4 | 8a8873b129313b24341e8fa88a49052e09c3fa51 | /src/Widgets.cpp | cd9fb1b25891885d417a8f2169d7a634f07b7319 | []
| no_license | flaithbheartaigh/wapbrowser | ba09f7aa981d65df810dba2156a3f153df071dcf | b0d93ce8517916d23104be608548e93740bace4e | refs/heads/master | 2021-01-10T11:29:49.555342 | 2010-03-08T09:36:03 | 2010-03-08T09:36:03 | 50,261,329 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,123 | cpp | /*
============================================================================
Name : Widgets.cpp
Author : 浮生若茶
Version :
Copyright : Your copyright notice
Description : CWidgets implementation
============================================================================
*/
#include "Define.h"
#include "Widgets.h"
#include "WapBrowserappui.h"
/*
//////////////////////////////////////////////////////////////////////////
CWidget
//////////////////////////////////////////////////////////////////////////
*/
CWidget::~CWidget()
{
delete iLink;
delete iBody;
}
TBool CWidget::IsLink()
{
return iLink && iLink->Length() > 0;
}
/*
void CWidget::SetLink(const TDesC& aLink)
{
iLink = aLink.Alloc();
}
const TDesC& CWidget::Link() const
{
//ASSERT(iLink); //TODO:断言不起作用,待查
if(iLink)
{
return *iLink;
}
return KNullDesC;
}
*/
void CWidget::SetLink(const TDesC8& aLink)
{
iLink = aLink.Alloc();
}
void CWidget::SetBody(const TDesC8& aBody)
{
iBody = aBody.Alloc();
}
const TDesC8& CWidget::Link() const
{
//ASSERT(iLink); //TODO:断言不起作用,待查
if(iLink)
{
return *iLink;
}
return KNullDesC8;
}
const TDesC8& CWidget::Body() const
{
//ASSERT(iLink); //TODO:断言不起作用,待查
if(iBody)
{
return *iBody;
}
return KNullDesC8;
}
TBool CWidget::SetActive(TBool aActive)
{
if(iLink)
{
iActive = aActive;
return ETrue;
}
return EFalse;
}
/*
//////////////////////////////////////////////////////////////////////////
CTextWidget
//////////////////////////////////////////////////////////////////////////
*/
//public:
CTextWidget::CTextWidget(const TDesC& aDes)
: CWidget(_L("CTextWidget"))
//: CWidget(EText)
{
ASSERT(aDes.Length());
iText = aDes.Alloc();
ASSERT(iText);
//iSize
width = KDefaultFont->MeasureText(*iText);
}
CTextWidget::~CTextWidget()
{
delete iText;
}
const TDesC& CTextWidget::Text() const
{
// //RDebug::Print(_L("Text"));
if(iText)
{
ASSERT(iText);
// RDebug::Print(*iText);
return *iText;
}
return KNullDesC;
}
//////////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////////
//void CTextWidget::Draw( /*const CWidget&element, */TBool ainRegion, CGraphicsContext &aGc, TPoint &apoint ) const
void CTextWidget::Draw(CGraphicsContext &aGc) const
{
const TDesC& text = /*((CTextWidget&)element).*/Text();
//gc.DrawRect(rect);
if(/*element.*/Link().Length()) //带链接
{
int width = CCoeEnv::Static()->NormalFont()->MeasureText(text);
//aGc.SetPenColor(KRgbBlue);
if(iActive)
{
int textHeight = CCoeEnv::Static()->NormalFont()->HeightInPixels();
TRect rect(point,TSize(width,textHeight));
rect.Move(TPoint(0,-textHeight));
aGc.SetBrushStyle(CGraphicsContext::ESolidBrush);
aGc.SetBrushColor(KRgbBlue);
aGc.SetPenStyle(CGraphicsContext::ENullPen);
aGc.DrawRect(rect);
aGc.SetPenColor(KRgbWhite);
}
else
{
aGc.SetBrushStyle(CGraphicsContext::ENullBrush);
aGc.SetPenStyle(CGraphicsContext::ESolidPen);
aGc.SetPenColor(KRgbBlue);
}
TPoint point1 = point;
TPoint point2 = point1;
point2.iX += width;
aGc.DrawLine(point1,point2);
}
else //不带链接
{
aGc.SetBrushStyle(CGraphicsContext::ENullBrush);
aGc.SetPenStyle(CGraphicsContext::ESolidPen);
aGc.SetPenColor(KRgbBlack);
}
aGc.DrawText(text,point);
}
void CTextWidget::Move(TPoint& aPoint)
{
if(iText)
{
aPoint.iX += KDefaultFont->MeasureText(*iText);
}
//point.iX += width;
}
TSize CTextWidget::Size() const
{
TSize size;
size.iWidth = CCoeEnv::Static()->NormalFont()->MeasureText(Text());
size.iHeight = CCoeEnv::Static()->NormalFont()->HeightInPixels();
return size;
}
/*
//////////////////////////////////////////////////////////////////////////
CPictureWidget
//////////////////////////////////////////////////////////////////////////
*/
#include "WapBrowserappui.h"
#include "WapEngine.h"
#include "ImageEngine.h"
//public:
//CPictureWidget(const TDesC& aDes,const TDesC& aLink)
CPictureWidget::CPictureWidget()
: CWidget(_L("CPictureWidget"))
{
iTextHeight = CCoeEnv::Static()->NormalFont()->HeightInPixels();
}
CPictureWidget::~CPictureWidget()
{
CWapBrowserAppUi::Static()->WapEngineL().ImageEngine().Remove(this);
delete iImageReader;
delete iAlt;
delete iParentLink;
delete iPictureLink;
delete iFileName;
}
void CPictureWidget::SetPictureLink(const TDesC& aParentLink)
{
iParentLink = aParentLink.Alloc();
MakePictureLink();
}
void CPictureWidget::SetPictureName(const TDesC& aName)
{
iFileName = aName.Alloc();
MakePictureLink();
}
void CPictureWidget::SetImage(const TDesC& aName)
{
//if(NULL == iBitmap)
{
ASSERT(NULL == iBitmap);
ASSERT(NULL == iImageReader);
ASSERT(NULL == iImageName);
CImage_Reader* imageReader = new (ELeave)CImage_Reader(*this);
CleanupStack::PushL(imageReader);
iImageName = aName.AllocLC();
imageReader->ConstructL(*iImageName);
CleanupStack::Pop(2);
iImageReader = imageReader;
}
}
void CPictureWidget::SetAlt(const TDesC& aAlt)
{
iAlt = aAlt.Alloc();
//width = KDefaultFont->MeasureText(*iAlt);
iSize.iHeight = KDefaultFont->HeightInPixels();
iSize.iWidth = KDefaultFont->MeasureText(*iAlt);
//SetImage(_L("C:\\coco.jpg"));
}
const TDesC& CPictureWidget::Alt() const
{
// RDebug::Print(_L("Alt"));
if(iAlt)
{
ASSERT(iAlt);
// RDebug::Print(*iAlt);
return *iAlt;
}
return KNullDesC;
}
const TDesC& CPictureWidget::Link() const
{
ASSERT(iPictureLink);
return *iPictureLink;
}
void CPictureWidget::MakePictureLink()
{
if(iParentLink && iFileName && NULL == iPictureLink)
{
int len = iParentLink->Length() + 1 + iFileName->Length();
HBufC* iPictureLink = HBufC::NewL(len);
iPictureLink->Des().Append(*iParentLink);
iPictureLink->Des().Append(_L("/"));
iPictureLink->Des().Append(*iFileName);
}
}
const CFbsBitmap* CPictureWidget::Bitmap() const
{
return iBitmap;
}
//////////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////////
void CPictureWidget::Draw(CGraphicsContext &aGc) const
{
if(iActive)
{
aGc.SetBrushStyle(CGraphicsContext::ENullBrush);
aGc.SetPenStyle(CGraphicsContext::ESolidPen);
aGc.SetPenColor(KRgbBlack);
TRect rect(point,iSize);
rect.Move(TPoint(0,-iTextHeight));
rect.Shrink(-1,-1);
aGc.DrawRect(rect);
}
if(iBitmap)
{
aGc.DrawBitmap(TRect(point - TPoint(0,iTextHeight),iSize),iBitmap,TRect(iSize));
}
else
{
const TDesC& text = /*((CPictureWidget&)element).*/Alt();
int width = CCoeEnv::Static()->NormalFont()->MeasureText(text);
TRect rect(point,TSize(width,iTextHeight));
rect.Move(TPoint(0,-iTextHeight));
aGc.SetPenStyle(CGraphicsContext::ESolidPen);
aGc.SetPenColor(KRgbYellow);
aGc.DrawRect(rect);
aGc.SetPenColor(KRgbBlue);
aGc.DrawText(text,point);
}
}
void CPictureWidget::Move(TPoint& aPoint)
{
aPoint.iX += iSize.iWidth;
}
TSize CPictureWidget::Size() const
{
/*
TSize size;
size.iWidth = CCoeEnv::Static()->NormalFont()->MeasureText(Alt());
//size.iHeight = CCoeEnv::Static()->NormalFont()->HeightInPixels();
size.iHeight = 53;
return size;
*/
return iSize;
}
//////////////////////////////////////////////////////////////////////////
//From MImageReadyCallBack
//////////////////////////////////////////////////////////////////////////
void CPictureWidget::ImageReadyL(const TInt& aError)
{
ASSERT(iImageReader);
if(KErrNone == aError)
{
ASSERT(NULL == iBitmap);
ASSERT(iImageName);
iBitmap = iImageReader->Bitmap();
iSize = iBitmap->SizeInPixels();
UtilityTools::DeleteFile(*iImageName);
delete iImageName;
iImageName = NULL;
CWapBrowserAppUi::Static()->UpdateWindow();
}
}
| [
"sungrass.xp@37a08ede-ebbd-11dd-bd7b-b12b6590754f"
]
| [
[
[
1,
351
]
]
]
|
dfe521dfac6d0e65386e0c2276c674f0c8730c75 | e744c4dacc3b9c4a44a725e2601c678f29826ace | /project/jni/image_plane.h | 39e275918e774fcf2e02282cbca736710e75f668 | []
| no_license | jcayzac/androido3d | 298559ebbe657482afe6b3b616561a1127320388 | 3466ed0ec790d8cbfe24cb5a4e72f1b432726e81 | refs/heads/master | 2016-09-06T06:31:09.984535 | 2010-12-28T01:45:39 | 2010-12-28T01:45:39 | 1,816,466 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,637 | h | /*
* Copyright (C) 2009 The Android Open Source Project
*
* 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.
*/
#ifndef O3D_UTILS_IMAGE_PLANE_H_
#define O3D_UTILS_IMAGE_PLANE_H_
#include <string>
#include "core/cross/types.h"
#include "core/cross/param.h"
namespace o3d {
class Pack;
class ParamSampler;
class Sampler;
class Shape;
class Transform;
class Texture2D;
} // namespace o3d.
namespace o3d_utils {
class ViewInfo;
// An image plane is a Quad with an image mapped to it.
class ImagePlane {
public:
// Creates an ImagePlane. If the requested texture is not already loaded,
// loads it.
static ImagePlane* Create(o3d::Pack* plane_pack,
o3d::Pack* texture_pack,
ViewInfo* view_info,
const std::string& filename,
bool origin_at_center);
// Gets a texture from the pack. If it doesn't exist, loads it.
static o3d::Texture2D* GetTexture(
o3d::Pack* pack, const std::string& filename);
// Gets an image plane shape with associated effect and material. If
// they don't exist in the given pack they will be created.
static o3d::Shape* GetImagePlaneShape(
o3d::Pack* pack, ViewInfo* view_info);
o3d::Transform* transform() const {
return transform_;
}
void SetColorMult(const o3d::Float4& color) {
color_mult_param_->set_value(color);
}
void SetColorMult(const float* color) {
SetColorMult(o3d::Float4(color[0], color[1], color[2], color[3]));
}
o3d::Float4 GetColorMult() const {
return color_mult_param_->value();
}
private:
ImagePlane();
bool Init(
o3d::Texture2D* texture,
o3d::Pack* plane_pack,
ViewInfo* view_info,
const std::string& filename,
bool origin_at_center);
o3d::Sampler* sampler_;
o3d::ParamSampler* sampler_param_;
o3d::ParamFloat4* color_mult_param_;
o3d::Transform* transform_;
o3d::Transform* scale_transform_;
};
} // namespace o3d_utils
#endif // O3D_UTILS_IMAGE_PLANE_H_
| [
"[email protected]"
]
| [
[
[
1,
94
]
]
]
|
4201839bf0dce7dfc5d107789ada16f0bc1031a6 | 69aab86a56c78cdfb51ab19b8f6a71274fb69fba | /Code/inc/BasicState.h | 832e90ac49875b82f2b3c49bde77f11dff922dc4 | [
"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 | 485 | h | /*
* BasicState.h
*
* Created on: 2010-12-21
* Author: artur.m
*/
#ifndef BASICSTATE_H_
#define BASICSTATE_H_
#include "Vector.h"
class Actor;
class BasicState
{
public:
virtual void update(int milis) {}
virtual void touched(const Actor* target, const Vector& touchPoint) {};
virtual void released(const Actor* target, const Vector& touchPoint) {};
virtual void stateEntered() {}
virtual void stateEnded() {}
};
#endif /* BASICSTATE_H_ */
| [
"[email protected]"
]
| [
[
[
1,
25
]
]
]
|
52b00d388d1d7cd60a9d1ad368f9f8f3b7f06665 | 730b67652016844a5a3de08cf1569dd846bf373f | /cube_mapping/cone.cpp | fd033e9675eb31e1a1ca645d6190f439ad83a4f0 | []
| no_license | deepakantony/acad_interactive_cg | 1105fbe78865e37500a33da214fbe71deda96f2d | 08ef7605b27f672beedc524967cb4e384a55f5d6 | refs/heads/master | 2021-01-22T05:10:56.783651 | 2011-06-18T03:15:13 | 2011-06-18T03:15:13 | 1,914,375 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,662 | cpp | #ifdef __APPLE__
#include <OpenGL/gl.h>
#include <OpenGL/glext.h>
#else
#include <GL/glew.h>
#include <GL/glut.h>
#endif
#include <math.h>
#define PI 3.14159265
class Cone {
public:
Cone() {}
Cone(float radius, float height, float numOfQuads) {
this->radius = radius;
this->height = height;
this->numOfQuads = numOfQuads;
this->theta = PI*2/numOfQuads;
}
void drawWithTexture(GLuint texName, int sRepeat, int tRepeat, float texEnvMode) {
float vert0[3] = {0.0, 0.0, 0.0}; vert0[1] = height;
float vert1[3] = {0.0, 0.0, 0.0}; vert1[0] = radius;
float vert2[3] = {0.0, 0.0, 0.0};
float d1[3], d2[3], n[3];
float t1[2], t2[2], t3[2], t4[2];
glActiveTexture(GL_TEXTURE0);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, texEnvMode);
glBindTexture(GL_TEXTURE_2D, texName);
glColor4f(1.0, 1.0, 1.0, 0.5);
GLfloat matEmission[] = {0.3,0.3,0.3,0.0};
GLfloat matDefaultEmission[] = {0.0, 0.0, 0.0, 1.0};
glMaterialfv(GL_FRONT, GL_EMISSION, matEmission);
glBegin(GL_QUADS);
for(int i = 0; i < numOfQuads; i++) {
vert2[0] = radius * cos(theta*(i+1));
vert2[2] = radius * sin(theta*(i+1));
t1[0] = sRepeat*(numOfQuads-i+1)/numOfQuads;
t1[1] = 0;
t2[0] = sRepeat*(numOfQuads-i)/numOfQuads;
t2[1] = 0;
t3[0] = t2[0];
t3[1] = tRepeat;
t4[0] = t1[0];
t4[1] = tRepeat;
for(int j = 0; j < 3; j++) {
d1[j] = vert2[j]-vert0[j];
d2[j] = vert1[j]-vert0[j];
}
// find the normals
this->crossProduct(d1, d2, n);
glTexCoord2fv(t1);
glNormal3fv(n);
glVertex3fv(vert2);
glTexCoord2fv(t2);
glNormal3fv(n);
glVertex3fv(vert1);
glTexCoord2fv(t3);
glNormal3fv(n);
glVertex3fv(vert0);
glTexCoord2fv(t4);
glNormal3fv(n);
glVertex3fv(vert0);
vert1[0] = vert2[0];
vert1[2] = vert2[2];
}
glEnd();
glFlush();
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glActiveTexture(GL_TEXTURE0);
glDisable(GL_TEXTURE_2D);
glDisable(GL_BLEND);
glMaterialfv(GL_FRONT, GL_EMISSION, matDefaultEmission);
}
private:
void normalize(float v[3]) {
GLfloat d = sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]);
v[0] /= d;
v[1] /= d;
v[2] /= d;
}
void crossProduct(float v1[3], float v2[3], float out[3]) {
out[0] = v1[1]*v2[2]-v1[2]*v2[1];
out[1] = v1[2]*v2[0]-v1[0]*v2[2];
out[2] = v1[0]*v2[1]-v1[1]*v2[0];
this->normalize(out);
}
private:
float radius, height, numOfQuads, theta;
};
| [
"[email protected]"
]
| [
[
[
1,
109
]
]
]
|
472301b90768e3532adb715560c3a76a1368505b | 33f59b1ba6b12c2dd3080b24830331c37bba9fe2 | /Depend/Foundation/Intersection/Wm4IntrLine3Torus3.cpp | 6d16d42b67928732761b234ac0501f7a39e42853 | []
| no_license | daleaddink/flagship3d | 4835c223fe1b6429c12e325770c14679c42ae3c6 | 6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a | refs/heads/master | 2021-01-15T16:29:12.196094 | 2009-11-01T10:18:11 | 2009-11-01T10:18:11 | 37,734,654 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,463 | cpp | // Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// The Wild Magic Version 4 Foundation Library source code is supplied
// under the terms of the license agreement
// http://www.geometrictools.com/License/Wm4FoundationLicense.pdf
// and may not be copied or disclosed except in accordance with the terms
// of that agreement.
#include "Wm4FoundationPCH.h"
#include "Wm4IntrLine3Torus3.h"
#include "Wm4PolynomialRoots.h"
namespace Wm4
{
//----------------------------------------------------------------------------
template <class Real>
IntrLine3Torus3<Real>::IntrLine3Torus3 (const Line3<Real>& rkLine,
const Torus3<Real>& rkTorus)
:
m_rkLine(rkLine),
m_rkTorus(rkTorus)
{
}
//----------------------------------------------------------------------------
template <class Real>
const Line3<Real>& IntrLine3Torus3<Real>::GetLine () const
{
return m_rkLine;
}
//----------------------------------------------------------------------------
template <class Real>
const Torus3<Real>& IntrLine3Torus3<Real>::GetTorus () const
{
return m_rkTorus;
}
//----------------------------------------------------------------------------
template <class Real>
bool IntrLine3Torus3<Real>::Find ()
{
// compute coefficients of quartic polynomial
Real fRo2 = m_rkTorus.Ro*m_rkTorus.Ro;
Real fRi2 = m_rkTorus.Ri*m_rkTorus.Ri;
Real fDD = m_rkLine.Direction.Dot(m_rkLine.Direction);
Real fDE = m_rkLine.Origin.Dot(m_rkLine.Direction);
Real fVal = m_rkLine.Origin.Dot(m_rkLine.Origin) - (fRo2 + fRi2);
Polynomial1<Real> kPoly(4);
kPoly[0] = fVal*fVal - ((Real)4.0)*fRo2*(fRi2 -
m_rkLine.Origin.Z()*m_rkLine.Origin.Z());
kPoly[1] = ((Real)4.0)*fDE*fVal +
((Real)8.0)*fRo2*m_rkLine.Direction.Z()*m_rkLine.Origin.Z();
kPoly[2] = ((Real)2.0)*fDD*fVal + ((Real)4.0)*fDE*fDE +
((Real)4.0)*fRo2*m_rkLine.Direction.Z()*m_rkLine.Direction.Z();
kPoly[3] = ((Real)4.0)*fDD*fDE;
kPoly[4] = fDD*fDD;
// solve the quartic
PolynomialRoots<Real> kPR(Math<Real>::ZERO_TOLERANCE);
kPR.FindB(kPoly,6);
m_iQuantity = kPR.GetCount();
const Real* afRoot = kPR.GetRoots();
// get the intersection points
for (int i = 0; i < m_iQuantity; i++)
{
m_akPoint[i] = m_rkLine.Origin + afRoot[i]*m_rkLine.Direction;
}
m_iIntersectionType = ( m_iQuantity > 0 ? IT_POINT : IT_EMPTY );
return m_iIntersectionType != IT_EMPTY;
}
//----------------------------------------------------------------------------
template <class Real>
int IntrLine3Torus3<Real>::GetQuantity () const
{
return m_iQuantity;
}
//----------------------------------------------------------------------------
template <class Real>
const Vector3<Real>& IntrLine3Torus3<Real>::GetPoint (int i) const
{
assert(0 <= i && i < m_iQuantity);
return m_akPoint[i];
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// explicit instantiation
//----------------------------------------------------------------------------
template WM4_FOUNDATION_ITEM
class IntrLine3Torus3<float>;
template WM4_FOUNDATION_ITEM
class IntrLine3Torus3<double>;
//----------------------------------------------------------------------------
}
| [
"yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa"
]
| [
[
[
1,
98
]
]
]
|
4ca9526b446deb9ba0f57ea521ab7ddf7e427678 | d1ce8db98d580f0f17f868ed408edf6d92f9208f | /QT/QtOgre/include/AbstractSettingsWidget.h | bcab0fb9b4f961e0eb683e4c3241d90170caf7f1 | []
| no_license | babochingu/andrew-phd | eed82e7bbd3e2b5b5403c1493e3d36b112b1b007 | ba94c3961d9dfef041c974e7ed2d9da4eb7d4dd3 | refs/heads/master | 2016-09-06T07:18:39.627522 | 2010-10-04T23:54:06 | 2010-10-04T23:54:06 | 33,762,959 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 613 | h | #ifndef QTOGRE_ABSTRACTSETTINGSWIDGET_H_
#define QTOGRE_ABSTRACTSETTINGSWIDGET_H_
#include <QSettings>
#include <QWidget>
namespace QtOgre
{
class AbstractSettingsWidget : public QWidget
{
Q_OBJECT
public:
AbstractSettingsWidget(QWidget *parent = 0);
void setSettings(QSettings* settings);
virtual void disableFirstTimeOnlySettings(void) = 0;
public slots:
void dialogFinished(int result);
virtual void readFromSettings(void) = 0;
virtual void writeToSettings(void) = 0;
protected:
QSettings* mSettings;
};
}
#endif /*QTOGRE_ABSTRACTSETTINGSWIDGET_H_*/ | [
"evertech.andrew@2dccfce6-0550-11df-956f-01f849d29158"
]
| [
[
[
1,
31
]
]
]
|
ee7253929de6d9ac3c0f30eb44fdbb0c1c2a15bc | 95d583eacc45df62b6b6459e2ec79404686cb2b1 | /source/Conjunto.cpp | a6d8a5fd682ff8042725926e1c39977f572ae29f | []
| no_license | sebasrodriguez/teoconj | 81a917c57724a718e6288798f7c58863a1dad523 | aee99839a8ddb293b0ed1402dfe72b80dbfe0af0 | refs/heads/master | 2021-01-01T15:36:42.773692 | 2010-03-13T01:04:12 | 2010-03-13T01:04:12 | 32,334,661 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,873 | cpp | #include "Conjunto.h"
void ConjuntoCreate(Conjunto &c)
{
ArbolIntCreate(c);
}
void ConjuntoAddValue(Conjunto &c, int valor)
{
ArbolIntAdd(c, valor);
}
void ConjuntoShow(Conjunto c)
{
string buffer;
strcrearmax(buffer);
string result;
strcrear(result);
if (ConjuntoCount(c) > 0)
{
ConjuntoOrdenBuffer(c, buffer, result);
result += 2;
}
printf("{");
print(result);
printf("}");
}
void ConjuntoOrdenBuffer(Conjunto c, string &buffer, string &result)
{
if (c != NULL)
{
ConjuntoOrdenBuffer(c->hizq, buffer, result);
straddchar(result, ',');
straddchar(result, BSP);
strcon(result, itoa(c->info, buffer, 10));
ConjuntoOrdenBuffer(c->hder, buffer, result);
}
}
bool ConjuntoPertenece(Conjunto c, int valor)
{
return ArbolIntPertenece(c, valor);
}
int ConjuntoCount(Conjunto c)
{
return ArbolIntCount(c);
}
void ConjuntoRemoveValue(Conjunto &c, int valor)
{
ArbolIntRemove(c, valor);
}
void ConjuntoCopy(Conjunto &c1, Conjunto c2)
{
ConjuntoCreate(c1);
ArbolIntCopy(c1, c2);
}
void ConjuntoOrdenUnion(Conjunto c1, Conjunto &c2)
{
if (c1 != NULL)
{
ConjuntoOrdenUnion(c1->hizq, c2);
if (!ConjuntoPertenece(c2, c1->info))
{
ConjuntoAddValue(c2, c1->info);
}
ConjuntoOrdenUnion(c1->hder, c2);
}
}
void ConjuntoUnion(Conjunto c1, Conjunto c2, Conjunto &uni)
{
ConjuntoCopy(uni, c1);
ConjuntoOrdenUnion(c2, uni);
}
void ConjuntoDifference(Conjunto c1, Conjunto c2, Conjunto &diff)
{
if (c1 != NULL)
{
ConjuntoDifference(c1->hizq, c2, diff);
if (!ConjuntoPertenece(c2, c1->info))
{
ConjuntoAddValue(diff, c1->info);
}
ConjuntoDifference(c1->hder, c2, diff);
}
}
void ConjuntoPostOrdenEquals(Conjunto c1, Conjunto c2, bool &equals)
{
if (c1 != NULL && equals)
{
equals = ConjuntoPertenece(c2, c1->info);
if (equals)
{
ConjuntoPostOrdenEquals(c1->hizq, c2, equals);
if (equals)
{
ConjuntoPostOrdenEquals(c1->hder, c2, equals);
}
}
}
}
bool ConjuntoMember(Conjunto c, int valor){
return ConjuntoPertenece(c, valor);
}
bool ConjuntoEquals(Conjunto c1, Conjunto c2)
{
bool equals = ConjuntoCount(c1) == ConjuntoCount(c2);
if(equals){
ConjuntoPostOrdenEquals(c1, c2, equals);
}
return equals;
}
bool ConjuntoIncluded(Conjunto c1, Conjunto c2){
bool r = false;
if (ConjuntoCount(c1) < ConjuntoCount(c2)){
Conjunto inter; ConjuntoCreate(inter);
ConjuntoIntersection(c1, c2, inter);
if (ConjuntoEquals(c1, inter))
{
r = true;
}
}
return r;
}
void ConjuntoIntersection(Conjunto c1, Conjunto c2, Conjunto &inter)
{
if (c1 != NULL)
{
ConjuntoIntersection(c1->hizq, c2, inter);
ConjuntoIntersection(c1->hder, c2, inter);
if (ConjuntoPertenece(c2, c1->info))
{
ConjuntoAddValue(inter, c1->info);
}
}
}
void ConjuntoOrdenSave(ffile &file, Conjunto c){
if (c != NULL)
{
ConjuntoOrdenSave(file, c->hizq);
fbajarInt(c->info, file);
ConjuntoOrdenSave(file, c->hder);
}
}
void ConjuntoSave(string name, Conjunto c){
ffile file = fopen(name, "wb");
ConjuntoOrdenSave(file, c);
fclose(file);
}
void ConjuntoLoad(string name, Conjunto &c){
ffile file = fopen(name, "rb");
int i;
flevantarInt(i, file);
while(!feof(file)){
ConjuntoAddValue(c, i);
flevantarInt(i, file);
}
fclose(file);
}
| [
"srpabliyo@861ad466-0edf-11df-a223-d798cd56f61e",
"sebasrodriguez@861ad466-0edf-11df-a223-d798cd56f61e"
]
| [
[
[
1,
2
],
[
5,
7
],
[
10,
13
],
[
22,
24
],
[
28,
29
],
[
34,
34
],
[
37,
41
],
[
44,
46
],
[
49,
51
],
[
54,
55
],
[
123,
123
],
[
137,
158
],
[
165,
174
]
],
[
[
3,
4
],
[
8,
9
],
[
14,
21
],
[
25,
27
],
[
30,
33
],
[
35,
36
],
[
42,
43
],
[
47,
48
],
[
52,
53
],
[
56,
122
],
[
124,
136
],
[
159,
164
]
]
]
|
80dba9fa1869448b66b4383eb1e5a9b147a32e99 | ef23e388061a637f82b815d32f7af8cb60c5bb1f | /src/mame/includes/meadows.h | 7a3f6813c692c571aa10c8f8fd81ac50e2d4daa1 | []
| no_license | marcellodash/psmame | 76fd877a210d50d34f23e50d338e65a17deff066 | 09f52313bd3b06311b910ed67a0e7c70c2dd2535 | refs/heads/master | 2021-05-29T23:57:23.333706 | 2011-06-23T20:11:22 | 2011-06-23T20:11:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,150 | h | /*************************************************************************
Meadows S2650 hardware
*************************************************************************/
#include "sound/samples.h"
class meadows_state : public driver_device
{
public:
meadows_state(running_machine &machine, const driver_device_config_base &config)
: driver_device(machine, config) { }
UINT8 *m_videoram;
UINT8 m_dac;
int m_dac_enable;
int m_channel;
int m_freq1;
int m_freq2;
UINT8 m_latched_0c01;
UINT8 m_latched_0c02;
UINT8 m_latched_0c03;
UINT8 m_main_sense_state;
UINT8 m_audio_sense_state;
UINT8 m_0c00;
UINT8 m_0c01;
UINT8 m_0c02;
UINT8 m_0c03;
tilemap_t *m_bg_tilemap;
UINT8 *m_spriteram;
};
/*----------- defined in audio/meadows.c -----------*/
SAMPLES_START( meadows_sh_start );
void meadows_sh_dac_w(running_machine &machine, int data);
void meadows_sh_update(running_machine &machine);
/*----------- defined in video/meadows.c -----------*/
VIDEO_START( meadows );
SCREEN_UPDATE( meadows );
WRITE8_HANDLER( meadows_videoram_w );
WRITE8_HANDLER( meadows_spriteram_w );
| [
"Mike@localhost"
]
| [
[
[
1,
48
]
]
]
|
86dd05a86a77beb1ba795356bcc24dcc8e7e1b05 | c70941413b8f7bf90173533115c148411c868bad | /plugins/AS3Plugin/src/vtxas3Event.cpp | 831d8c1b13d27903574c83ef7583a842e1c25ff2 | []
| no_license | cnsuhao/vektrix | ac6e028dca066aad4f942b8d9eb73665853fbbbe | 9b8c5fa7119ff7f3dc80fb05b7cdba335cf02c1a | refs/heads/master | 2021-06-23T11:28:34.907098 | 2011-03-27T17:39:37 | 2011-03-27T17:39:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,940 | cpp | /*
-----------------------------------------------------------------------------
This source file is part of "vektrix"
(the rich media and vector graphics rendering library)
For the latest info, see http://www.fuse-software.com/
Copyright (c) 2009-2010 Fuse-Software (tm)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "vtxas3Event.h"
#include "vtxLogManager.h"
namespace vtx { namespace as3 {
//-----------------------------------------------------------------------
Event::Event(avmplus::VTable* vtable, avmplus::ScriptObject* prototype)
: avmplus::ScriptObject(vtable, prototype)
{
}
//-----------------------------------------------------------------------
Event::~Event()
{
//VTX_LOG("collecting evt !!! (%d)", RefCount());
}
//-----------------------------------------------------------------------
}}
| [
"stonecold_@9773a11d-1121-4470-82d2-da89bd4a628a"
]
| [
[
[
1,
46
]
]
]
|
4163ee0b6aaaef0fd4af31deac98d6bdfaaa8e85 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/numeric/ublas/doc/samples/matrix_range.cpp | f732f7e41ecc177ce1740c3bef3e19b48f722ab2 | [
"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 | 1,140 | cpp | //
// Copyright (c) 2000-2002
// Joerg Walter, Mathias Koch
//
// Permission to use, copy, modify, distribute and sell this software
// and its documentation for any purpose is hereby granted without fee,
// provided that the above copyright notice appear in all copies and
// that both that copyright notice and this permission notice appear
// in supporting documentation. The authors make no representations
// about the suitability of this software for any purpose.
// It is provided "as is" without express or implied warranty.
//
// The authors gratefully acknowledge the support of
// GeNeSys mbH & Co. KG in producing this work.
//
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/numeric/ublas/io.hpp>
int main () {
using namespace boost::numeric::ublas;
matrix<double> m (3, 3);
matrix_range<matrix<double> > mr (m, range (0, 3), range (0, 3));
for (unsigned i = 0; i < mr.size1 (); ++ i)
for (unsigned j = 0; j < mr.size2 (); ++ j)
mr (i, j) = 3 * i + j;
std::cout << mr << std::endl;
}
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
30
]
]
]
|
fbc277ead85b155a7240da092a8b608cc14fe6a3 | 9c62af23e0a1faea5aaa8dd328ba1d82688823a5 | /rl/tags/v0-1/engine/script/swig/RlDialog.inc | 6f7031b594a6c63e9e93abfaab0c6292c4e97e89 | [
"ClArtistic",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
]
| permissive | jacmoe/dsa-hl-svn | 55b05b6f28b0b8b216eac7b0f9eedf650d116f85 | 97798e1f54df9d5785fb206c7165cd011c611560 | refs/heads/master | 2021-04-22T12:07:43.389214 | 2009-11-27T22:01:03 | 2009-11-27T22:01:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,799 | inc | /* This source file is part of Rastullahs Lockenpracht.
* Copyright (C) 2003-2005 Team Pantheon. http://www.team-pantheon.de
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the Clarified Artistic License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Clarified Artistic License for more details.
*
* You should have received a copy of the Clarified Artistic License
* along with this program; if not you can get it here
* http://www.jpaulmorrison.com/fbp/artistic2.htm.
*/
namespace rl
{
%feature("director") DialogScriptObject;
class DialogScriptObject
{
public:
DialogScriptObject();
virtual ~DialogScriptObject();
virtual int calcOptionValue(const rl::CeGuiString& optionName)=0;
virtual int calcResponseValue(const rl::CeGuiString& responseName)=0;
virtual int calcSelectionValue(const rl::CeGuiString& selectionName)=0;
rl::Creature* getDialogCharacter() const;
rl::Creature* getDialogPartner() const;
};
class DialogCharacter
{
public:
DialogCharacter(const std::string& name);
void setScriptObject(rl::DialogScriptObject* scriptObject);
rl::Creature* getDialogCharacter() const;
void setDialogCharacter(rl::Creature* dialogCharacter);
rl::Creature* getDialogPartner() const;
void setDialogPartner(rl::Creature* dialogPartner);
};
class DialogSubsystem
{
public:
static DialogSubsystem& getSingleton(void);
rl::DialogCharacter* getCurrentBot();
rl::DialogCharacter* loadBot(const rl::CeGuiString& fileName, const rl::CeGuiString& botName = "");
};
}
| [
"blakharaz@4c79e8ff-cfd4-0310-af45-a38c79f83013"
]
| [
[
[
1,
54
]
]
]
|
edd025e8792b85f19f2c4615ff536f67794bd64b | 6ada8deb47e05068cc59c3adbe6c7837669f5227 | /IPhysicsSystem.cpp | 8f17603df4abdc3c66a1be82210bf08b7e0ac1eb | []
| no_license | matthewjack/Pneumatic | be3e776467c47e723dea61a32bf0828cc45195f2 | 0e2e4ab439c6c3e1a1dab04588d645482f77e62e | refs/heads/master | 2016-09-06T18:59:46.148010 | 2010-08-17T12:18:40 | 2010-08-17T12:18:40 | 854,035 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 122 | cpp | #include "IPhysicsSystem.h"
IPhysicsSystem::IPhysicsSystem(void)
{
}
IPhysicsSystem::~IPhysicsSystem(void)
{
}
| [
"[email protected]"
]
| [
[
[
1,
9
]
]
]
|
4f9bf62294d16b7464b304e87172d52a40b60b05 | 0c5fd443401312fafae18ea6a9d17bac9ee61474 | /code/engine/EnumGen/Shared.h | 91426dd661e401f5137f192fda5212b3e1fce24b | []
| no_license | nurF/Brute-Force-Game-Engine | fcfebc997d6ab487508a5706b849e9d7bc66792d | b930472429ec6d6f691230e36076cd2c868d853d | refs/heads/master | 2021-01-18T09:29:44.038036 | 2011-12-02T17:31:59 | 2011-12-02T17:31:59 | 2,877,061 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,906 | h | /* ___ _________ ____ __
/ _ )/ __/ ___/____/ __/___ ___ _/_/___ ___
/ _ / _// (_ //___/ _/ / _ | _ `/ // _ | -_)
/____/_/ \___/ /___//_//_|_, /_//_//_|__/
/___/
This file is part of the Brute-Force Game Engine, BFG-Engine
For the latest info, see http://www.brute-force-games.com
Copyright (c) 2011 Brute-Force Games GbR
The BFG-Engine is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
The BFG-Engine 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 the BFG-Engine. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef BFG_ENUMGEN_SHARED_
#define BFG_ENUMGEN_SHARED_
#include <string>
#include <vector>
#include <iostream> // Shared::Enum::dump()
namespace EnumGen {
//! Shared data by Parse and Generator functions.
namespace Shared
{
//! Equal to a C++ enum.
/** Represents content of either the enumgen XML tag (enum) or
a C++ enum definition.
*/
struct Enum
{
//! Equal to a C++ enumerator-definition.
/** Represents content of either the enumgen tag (value) or
an enumerator-defintion inside an C++ enumerator-list.
Example: enum { FOO = BAR }; // FOO is Text, BAR is Set.
*/
struct ValueT
{
ValueT() : Set(0) {}
std::string Text;
int Set;
};
//! Additional information about the enum itself.
struct MetaT
{
typedef std::vector<std::string> IncludeVector;
MetaT() : DefinitionExists(false) {}
//! If this is true, the enum definition won't get generated.
/** It may be possible that the enum exists already in an other
library, but we need the conversion functions. This should
be true, if this is the case. This is indicated in XML by
the "definition-exists" attribute.
*/
bool DefinitionExists;
//! If this is true, asXXX-functions will be exported.
/** This variable contains the export macro which will be passed
to the compiler in order to produce the interface or the
library itself.
*/
std::string Export;
//! Some enums may require special includes.
/** This will even be considered if DefinitionExists is false.
*/
IncludeVector Required;
//! Of course, this enum may be put into some C++ namespace.
/** Anonymous namespaces are not supported.
*/
std::string Namespace;
};
//! Writes debug output to std::cerr.
void dump() const
{
std::cerr << "Shared::Enum dump for \'"<< mName <<"\'\n";
for (size_t s=0; s<24+mName.size(); ++s) std::cerr << "*";
std::cerr << "\n";
for (size_t i=0; i<mValues.size(); ++i)
{
std::cerr << mValues[i].Text;
if (mValues[i].Set)
std::cerr << " = " << mValues[i].Set;
std::cerr << "\n";
}
std::cerr << "\n";
std::cerr << "Is this enum already defined: "
<< (mMeta.DefinitionExists ? "Yes" : "No") << "\n\n";
std::cerr << "Required includes for this enum:\n";
for (size_t i=0; i<mMeta.Required.size(); ++i)
std::cerr << " -> \"" << mMeta.Required[i] << "\"\n";
if (mMeta.Required.empty())
std::cerr << "<none>\n";
std::cerr << "\n";
}
MetaT mMeta;
std::string mName;
std::vector<ValueT> mValues;
};
typedef std::vector<Enum> EnumVector;
}
} // namespace EnumGen
#endif | [
"[email protected]"
]
| [
[
[
1,
135
]
]
]
|
97b36348d7da4bacd9b761b913d097f9835681d6 | 62874cd4e97b2cfa74f4e507b798f6d5c7022d81 | /src/Properties/FastDelegate.h | 737c5f10b2df289022d092c9c9be15b5363c2a29 | []
| no_license | rjaramih/midi-me | 6a4047e5f390a5ec851cbdc1b7495b7fe80a4158 | 6dd6a1a0111645199871f9951f841e74de0fe438 | refs/heads/master | 2021-03-12T21:31:17.689628 | 2011-07-31T22:42:05 | 2011-07-31T22:42:05 | 36,944,802 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 99,525 | h | // FastDelegate.h
// Efficient delegates in C++ that generate only two lines of asm code!
// Documentation is found at http://www.codeproject.com/cpp/FastDelegate.asp
//
// - Don Clugston, Mar 2004.
// Major contributions were made by Jody Hagins.
// History:
// 24-Apr-04 1.0 * Submitted to CodeProject.
// 28-Apr-04 1.1 * Prevent most unsafe uses of evil static function hack.
// * Improved syntax for horrible_cast (thanks Paul Bludov).
// * Tested on Metrowerks MWCC and Intel ICL (IA32)
// * Compiled, but not run, on Comeau C++ and Intel Itanium ICL.
// 27-Jun-04 1.2 * Now works on Borland C++ Builder 5.5
// * Now works on /clr "managed C++" code on VC7, VC7.1
// * Comeau C++ now compiles without warnings.
// * Prevent the virtual inheritance case from being used on
// VC6 and earlier, which generate incorrect code.
// * Improved warning and error messages. Non-standard hacks
// now have compile-time checks to make them safer.
// * implicit_cast used instead of static_cast in many cases.
// * If calling a const member function, a const class pointer can be used.
// * MakeDelegate() global helper function added to simplify pass-by-value.
// * Added fastdelegate.clear()
// 16-Jul-04 1.2.1* Workaround for gcc bug (const member function pointers in templates)
// 30-Oct-04 1.3 * Support for (non-void) return values.
// * No more workarounds in client code!
// MSVC and Intel now use a clever hack invented by John Dlugosz:
// - The FASTDELEGATEDECLARE workaround is no longer necessary.
// - No more warning messages for VC6
// * Less use of macros. Error messages should be more comprehensible.
// * Added include guards
// * Added FastDelegate::empty() to test if invocation is safe (Thanks Neville Franks).
// * Now tested on VS 2005 Express Beta, PGI C++
// 24-Dec-04 1.4 * Added DelegateMemento, to allow collections of disparate delegates.
// * <,>,<=,>= comparison operators to allow storage in ordered containers.
// * Substantial reduction of code size, especially the 'Closure' class.
// * Standardised all the compiler-specific workarounds.
// * MFP conversion now works for CodePlay (but not yet supported in the full code).
// * Now compiles without warnings on _any_ supported compiler, including BCC 5.5.1
// * New syntax: FastDelegate< int (char *, double) >.
// 14-Feb-05 1.4.1* Now treats =0 as equivalent to .clear(), ==0 as equivalent to .empty(). (Thanks elfric).
// * Now tested on Intel ICL for AMD64, VS2005 Beta for AMD64 and Itanium.
// 30-Mar-05 1.5 * Safebool idiom: "if (dg)" is now equivalent to "if (!dg.empty())"
// * Fully supported by CodePlay VectorC
// * Bugfix for Metrowerks: empty() was buggy because a valid MFP can be 0 on MWCC!
// * More optimal assignment,== and != operators for static function pointers.
#ifndef FASTDELEGATE_H
#define FASTDELEGATE_H
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#ifndef _PSP_
#include <memory.h> // to allow <,> comparisons
#endif
////////////////////////////////////////////////////////////////////////////////
// Configuration options
//
////////////////////////////////////////////////////////////////////////////////
// Uncomment the following #define for optimally-sized delegates.
// In this case, the generated asm code is almost identical to the code you'd get
// if the compiler had native support for delegates.
// It will not work on systems where sizeof(dataptr) < sizeof(codeptr).
// Thus, it will not work for DOS compilers using the medium model.
// It will also probably fail on some DSP systems.
#define FASTDELEGATE_USESTATICFUNCTIONHACK
// Uncomment the next line to allow function declarator syntax.
// It is automatically enabled for those compilers where it is known to work.
//#define FASTDELEGATE_ALLOW_FUNCTION_TYPE_SYNTAX
////////////////////////////////////////////////////////////////////////////////
// Compiler identification for workarounds
//
////////////////////////////////////////////////////////////////////////////////
// Compiler identification. It's not easy to identify Visual C++ because
// many vendors fraudulently define Microsoft's identifiers.
#if defined(_MSC_VER) && !defined(__MWERKS__) && !defined(__VECTOR_C) && !defined(__ICL) && !defined(__BORLANDC__)
#define FASTDLGT_ISMSVC
#if (_MSC_VER <1300) // Many workarounds are required for VC6.
#define FASTDLGT_VC6
#pragma warning(disable:4786) // disable this ridiculous warning
#endif
#endif
// Does the compiler uses Microsoft's member function pointer structure?
// If so, it needs special treatment.
// Metrowerks CodeWarrior, Intel, and CodePlay fraudulently define Microsoft's
// identifier, _MSC_VER. We need to filter Metrowerks out.
#if defined(_MSC_VER) && !defined(__MWERKS__)
#define FASTDLGT_MICROSOFT_MFP
#if !defined(__VECTOR_C)
// CodePlay doesn't have the __single/multi/virtual_inheritance keywords
#define FASTDLGT_HASINHERITANCE_KEYWORDS
#endif
#endif
// Does it allow function declarator syntax? The following compilers are known to work:
#if defined(FASTDLGT_ISMSVC) && (_MSC_VER >=1310) // VC 7.1
#define FASTDELEGATE_ALLOW_FUNCTION_TYPE_SYNTAX
#endif
// Gcc(2.95+), and versions of Digital Mars, Intel and Comeau in common use.
#if defined (__DMC__) || defined(__GNUC__) || defined(__ICL) || defined(__COMO__)
#define FASTDELEGATE_ALLOW_FUNCTION_TYPE_SYNTAX
#endif
// It works on Metrowerks MWCC 3.2.2. From boost.Config it should work on earlier ones too.
#if defined (__MWERKS__)
#define FASTDELEGATE_ALLOW_FUNCTION_TYPE_SYNTAX
#endif
#ifdef __GNUC__ // Workaround GCC bug #8271
// At present, GCC doesn't recognize constness of MFPs in templates
#define FASTDELEGATE_GCC_BUG_8271
#endif
////////////////////////////////////////////////////////////////////////////////
// General tricks used in this code
//
// (a) Error messages are generated by typdefing an array of negative size to
// generate compile-time errors.
// (b) Warning messages on MSVC are generated by declaring unused variables, and
// enabling the "variable XXX is never used" warning.
// (c) Unions are used in a few compiler-specific cases to perform illegal casts.
// (d) For Microsoft and Intel, when adjusting the 'this' pointer, it's cast to
// (char *) first to ensure that the correct number of *bytes* are added.
//
////////////////////////////////////////////////////////////////////////////////
// Helper templates
//
////////////////////////////////////////////////////////////////////////////////
namespace fastdelegate {
namespace detail { // we'll hide the implementation details in a nested namespace.
// implicit_cast< >
// I believe this was originally going to be in the C++ standard but
// was left out by accident. It's even milder than static_cast.
// I use it instead of static_cast<> to emphasize that I'm not doing
// anything nasty.
// Usage is identical to static_cast<>
template <class OutputClass, class InputClass>
inline OutputClass implicit_cast(InputClass input){
return input;
}
// horrible_cast< >
// This is truly evil. It completely subverts C++'s type system, allowing you
// to cast from any class to any other class. Technically, using a union
// to perform the cast is undefined behaviour (even in C). But we can see if
// it is OK by checking that the union is the same size as each of its members.
// horrible_cast<> should only be used for compiler-specific workarounds.
// Usage is identical to reinterpret_cast<>.
// This union is declared outside the horrible_cast because BCC 5.5.1
// can't inline a function with a nested class, and gives a warning.
template <class OutputClass, class InputClass>
union horrible_union{
OutputClass out;
InputClass in;
};
template <class OutputClass, class InputClass>
inline OutputClass horrible_cast(const InputClass input){
horrible_union<OutputClass, InputClass> u;
// Cause a compile-time error if in, out and u are not the same size.
// If the compile fails here, it means the compiler has peculiar
// unions which would prevent the cast from working.
typedef int ERROR_CantUseHorrible_cast[sizeof(InputClass)==sizeof(u)
&& sizeof(InputClass)==sizeof(OutputClass) ? 1 : -1];
u.in = input;
return u.out;
}
////////////////////////////////////////////////////////////////////////////////
// Workarounds
//
////////////////////////////////////////////////////////////////////////////////
// Backwards compatibility: This macro used to be necessary in the virtual inheritance
// case for Intel and Microsoft. Now it just forward-declares the class.
#define FASTDELEGATEDECLARE(CLASSNAME) class CLASSNAME;
// Prevent use of the static function hack with the DOS medium model.
#ifdef __MEDIUM__
#undef FASTDELEGATE_USESTATICFUNCTIONHACK
#endif
// DefaultVoid - a workaround for 'void' templates in VC6.
//
// (1) VC6 and earlier do not allow 'void' as a default template argument.
// (2) They also doesn't allow you to return 'void' from a function.
//
// Workaround for (1): Declare a dummy type 'DefaultVoid' which we use
// when we'd like to use 'void'. We convert it into 'void' and back
// using the templates DefaultVoidToVoid<> and VoidToDefaultVoid<>.
// Workaround for (2): On VC6, the code for calling a void function is
// identical to the code for calling a non-void function in which the
// return value is never used, provided the return value is returned
// in the EAX register, rather than on the stack.
// This is true for most fundamental types such as int, enum, void *.
// Const void * is the safest option since it doesn't participate
// in any automatic conversions. But on a 16-bit compiler it might
// cause extra code to be generated, so we disable it for all compilers
// except for VC6 (and VC5).
#ifdef FASTDLGT_VC6
// VC6 workaround
typedef const void * DefaultVoid;
#else
// On any other compiler, just use a normal void.
typedef void DefaultVoid;
#endif
// Translate from 'DefaultVoid' to 'void'.
// Everything else is unchanged
template <class T>
struct DefaultVoidToVoid { typedef T type; };
template <>
struct DefaultVoidToVoid<DefaultVoid> { typedef void type; };
// Translate from 'void' into 'DefaultVoid'
// Everything else is unchanged
template <class T>
struct VoidToDefaultVoid { typedef T type; };
template <>
struct VoidToDefaultVoid<void> { typedef DefaultVoid type; };
////////////////////////////////////////////////////////////////////////////////
// Fast Delegates, part 1:
//
// Conversion of member function pointer to a standard form
//
////////////////////////////////////////////////////////////////////////////////
// GenericClass is a fake class, ONLY used to provide a type.
// It is vitally important that it is never defined, so that the compiler doesn't
// think it can optimize the invocation. For example, Borland generates simpler
// code if it knows the class only uses single inheritance.
// Compilers using Microsoft's structure need to be treated as a special case.
#ifdef FASTDLGT_MICROSOFT_MFP
#ifdef FASTDLGT_HASINHERITANCE_KEYWORDS
// For Microsoft and Intel, we want to ensure that it's the most efficient type of MFP
// (4 bytes), even when the /vmg option is used. Declaring an empty class
// would give 16 byte pointers in this case....
class __single_inheritance GenericClass;
#endif
// ...but for Codeplay, an empty class *always* gives 4 byte pointers.
// If compiled with the /clr option ("managed C++"), the JIT compiler thinks
// it needs to load GenericClass before it can call any of its functions,
// (compiles OK but crashes at runtime!), so we need to declare an
// empty class to make it happy.
// Codeplay and VC4 can't cope with the unknown_inheritance case either.
class GenericClass {};
#else
class GenericClass;
#endif
// The size of a single inheritance member function pointer.
const int SINGLE_MEMFUNCPTR_SIZE = sizeof(void (GenericClass::*)());
// SimplifyMemFunc< >::Convert()
//
// A template function that converts an arbitrary member function pointer into the
// simplest possible form of member function pointer, using a supplied 'this' pointer.
// According to the standard, this can be done legally with reinterpret_cast<>.
// For (non-standard) compilers which use member function pointers which vary in size
// depending on the class, we need to use knowledge of the internal structure of a
// member function pointer, as used by the compiler. Template specialization is used
// to distinguish between the sizes. Because some compilers don't support partial
// template specialisation, I use full specialisation of a wrapper struct.
// general case -- don't know how to convert it. Force a compile failure
template <int N>
struct SimplifyMemFunc {
template <class X, class XFuncType, class GenericMemFuncType>
inline static GenericClass *Convert(X *pthis, XFuncType function_to_bind,
GenericMemFuncType &bound_func) {
// Unsupported member function type -- force a compile failure.
// (it's illegal to have a array with negative size).
typedef char ERROR_Unsupported_member_function_pointer_on_this_compiler[N-100];
return 0;
}
};
// For compilers where all member func ptrs are the same size, everything goes here.
// For non-standard compilers, only single_inheritance classes go here.
template <>
struct SimplifyMemFunc<SINGLE_MEMFUNCPTR_SIZE> {
template <class X, class XFuncType, class GenericMemFuncType>
inline static GenericClass *Convert(X *pthis, XFuncType function_to_bind,
GenericMemFuncType &bound_func) {
#if defined __DMC__
// Digital Mars doesn't allow you to cast between abitrary PMF's,
// even though the standard says you can. The 32-bit compiler lets you
// static_cast through an int, but the DOS compiler doesn't.
bound_func = horrible_cast<GenericMemFuncType>(function_to_bind);
#else
bound_func = reinterpret_cast<GenericMemFuncType>(function_to_bind);
#endif
return reinterpret_cast<GenericClass *>(pthis);
}
};
////////////////////////////////////////////////////////////////////////////////
// Fast Delegates, part 1b:
//
// Workarounds for Microsoft and Intel
//
////////////////////////////////////////////////////////////////////////////////
// Compilers with member function pointers which violate the standard (MSVC, Intel, Codeplay),
// need to be treated as a special case.
#ifdef FASTDLGT_MICROSOFT_MFP
// We use unions to perform horrible_casts. I would like to use #pragma pack(push, 1)
// at the start of each function for extra safety, but VC6 seems to ICE
// intermittently if you do this inside a template.
// __multiple_inheritance classes go here
// Nasty hack for Microsoft and Intel (IA32 and Itanium)
template<>
struct SimplifyMemFunc< SINGLE_MEMFUNCPTR_SIZE + sizeof(int) > {
template <class X, class XFuncType, class GenericMemFuncType>
inline static GenericClass *Convert(X *pthis, XFuncType function_to_bind,
GenericMemFuncType &bound_func) {
// We need to use a horrible_cast to do this conversion.
// In MSVC, a multiple inheritance member pointer is internally defined as:
union {
XFuncType func;
struct {
GenericMemFuncType funcaddress; // points to the actual member function
int delta; // #BYTES to be added to the 'this' pointer
}s;
} u;
// Check that the horrible_cast will work
typedef int ERROR_CantUsehorrible_cast[sizeof(function_to_bind)==sizeof(u.s)? 1 : -1];
u.func = function_to_bind;
bound_func = u.s.funcaddress;
return reinterpret_cast<GenericClass *>(reinterpret_cast<char *>(pthis) + u.s.delta);
}
};
// virtual inheritance is a real nuisance. It's inefficient and complicated.
// On MSVC and Intel, there isn't enough information in the pointer itself to
// enable conversion to a closure pointer. Earlier versions of this code didn't
// work for all cases, and generated a compile-time error instead.
// But a very clever hack invented by John M. Dlugosz solves this problem.
// My code is somewhat different to his: I have no asm code, and I make no
// assumptions about the calling convention that is used.
// In VC++ and ICL, a virtual_inheritance member pointer
// is internally defined as:
struct MicrosoftVirtualMFP {
void (GenericClass::*codeptr)(); // points to the actual member function
int delta; // #bytes to be added to the 'this' pointer
int vtable_index; // or 0 if no virtual inheritance
};
// The CRUCIAL feature of Microsoft/Intel MFPs which we exploit is that the
// m_codeptr member is *always* called, regardless of the values of the other
// members. (This is *not* true for other compilers, eg GCC, which obtain the
// function address from the vtable if a virtual function is being called).
// Dlugosz's trick is to make the codeptr point to a probe function which
// returns the 'this' pointer that was used.
// Define a generic class that uses virtual inheritance.
// It has a trival member function that returns the value of the 'this' pointer.
struct GenericVirtualClass : virtual public GenericClass
{
typedef GenericVirtualClass * (GenericVirtualClass::*ProbePtrType)();
GenericVirtualClass * GetThis() { return this; }
};
// __virtual_inheritance classes go here
template <>
struct SimplifyMemFunc<SINGLE_MEMFUNCPTR_SIZE + 2*sizeof(int) >
{
template <class X, class XFuncType, class GenericMemFuncType>
inline static GenericClass *Convert(X *pthis, XFuncType function_to_bind,
GenericMemFuncType &bound_func) {
union {
XFuncType func;
GenericClass* (X::*ProbeFunc)();
MicrosoftVirtualMFP s;
} u;
u.func = function_to_bind;
bound_func = reinterpret_cast<GenericMemFuncType>(u.s.codeptr);
union {
GenericVirtualClass::ProbePtrType virtfunc;
MicrosoftVirtualMFP s;
} u2;
// Check that the horrible_cast<>s will work
typedef int ERROR_CantUsehorrible_cast[sizeof(function_to_bind)==sizeof(u.s)
&& sizeof(function_to_bind)==sizeof(u.ProbeFunc)
&& sizeof(u2.virtfunc)==sizeof(u2.s) ? 1 : -1];
// Unfortunately, taking the address of a MF prevents it from being inlined, so
// this next line can't be completely optimised away by the compiler.
u2.virtfunc = &GenericVirtualClass::GetThis;
u.s.codeptr = u2.s.codeptr;
return (pthis->*u.ProbeFunc)();
}
};
#if (_MSC_VER <1300)
// Nasty hack for Microsoft Visual C++ 6.0
// unknown_inheritance classes go here
// There is a compiler bug in MSVC6 which generates incorrect code in this case!!
template <>
struct SimplifyMemFunc<SINGLE_MEMFUNCPTR_SIZE + 3*sizeof(int) >
{
template <class X, class XFuncType, class GenericMemFuncType>
inline static GenericClass *Convert(X *pthis, XFuncType function_to_bind,
GenericMemFuncType &bound_func) {
// There is an apalling but obscure compiler bug in MSVC6 and earlier:
// vtable_index and 'vtordisp' are always set to 0 in the
// unknown_inheritance case!
// This means that an incorrect function could be called!!!
// Compiling with the /vmg option leads to potentially incorrect code.
// This is probably the reason that the IDE has a user interface for specifying
// the /vmg option, but it is disabled - you can only specify /vmg on
// the command line. In VC1.5 and earlier, the compiler would ICE if it ever
// encountered this situation.
// It is OK to use the /vmg option if /vmm or /vms is specified.
// Fortunately, the wrong function is only called in very obscure cases.
// It only occurs when a derived class overrides a virtual function declared
// in a virtual base class, and the member function
// points to the *Derived* version of that function. The problem can be
// completely averted in 100% of cases by using the *Base class* for the
// member fpointer. Ie, if you use the base class as an interface, you'll
// stay out of trouble.
// Occasionally, you might want to point directly to a derived class function
// that isn't an override of a base class. In this case, both vtable_index
// and 'vtordisp' are zero, but a virtual_inheritance pointer will be generated.
// We can generate correct code in this case. To prevent an incorrect call from
// ever being made, on MSVC6 we generate a warning, and call a function to
// make the program crash instantly.
typedef char ERROR_VC6CompilerBug[-100];
return 0;
}
};
#else
// Nasty hack for Microsoft and Intel (IA32 and Itanium)
// unknown_inheritance classes go here
// This is probably the ugliest bit of code I've ever written. Look at the casts!
// There is a compiler bug in MSVC6 which prevents it from using this code.
template <>
struct SimplifyMemFunc<SINGLE_MEMFUNCPTR_SIZE + 3*sizeof(int) >
{
template <class X, class XFuncType, class GenericMemFuncType>
inline static GenericClass *Convert(X *pthis, XFuncType function_to_bind,
GenericMemFuncType &bound_func) {
// The member function pointer is 16 bytes long. We can't use a normal cast, but
// we can use a union to do the conversion.
union {
XFuncType func;
// In VC++ and ICL, an unknown_inheritance member pointer
// is internally defined as:
struct {
GenericMemFuncType m_funcaddress; // points to the actual member function
int delta; // #bytes to be added to the 'this' pointer
int vtordisp; // #bytes to add to 'this' to find the vtable
int vtable_index; // or 0 if no virtual inheritance
} s;
} u;
// Check that the horrible_cast will work
typedef int ERROR_CantUsehorrible_cast[sizeof(XFuncType)==sizeof(u.s)? 1 : -1];
u.func = function_to_bind;
bound_func = u.s.funcaddress;
int virtual_delta = 0;
if (u.s.vtable_index) { // Virtual inheritance is used
// First, get to the vtable.
// It is 'vtordisp' bytes from the start of the class.
const int * vtable = *reinterpret_cast<const int *const*>(
reinterpret_cast<const char *>(pthis) + u.s.vtordisp );
// 'vtable_index' tells us where in the table we should be looking.
virtual_delta = u.s.vtordisp + *reinterpret_cast<const int *>(
reinterpret_cast<const char *>(vtable) + u.s.vtable_index);
}
// The int at 'virtual_delta' gives us the amount to add to 'this'.
// Finally we can add the three components together. Phew!
return reinterpret_cast<GenericClass *>(
reinterpret_cast<char *>(pthis) + u.s.delta + virtual_delta);
};
};
#endif // MSVC 7 and greater
#endif // MS/Intel hacks
} // namespace detail
////////////////////////////////////////////////////////////////////////////////
// Fast Delegates, part 2:
//
// Define the delegate storage, and cope with static functions
//
////////////////////////////////////////////////////////////////////////////////
// DelegateMemento -- an opaque structure which can hold an arbitary delegate.
// It knows nothing about the calling convention or number of arguments used by
// the function pointed to.
// It supplies comparison operators so that it can be stored in STL collections.
// It cannot be set to anything other than null, nor invoked directly:
// it must be converted to a specific delegate.
// Implementation:
// There are two possible implementations: the Safe method and the Evil method.
// DelegateMemento - Safe version
//
// This implementation is standard-compliant, but a bit tricky.
// A static function pointer is stored inside the class.
// Here are the valid values:
// +-- Static pointer --+--pThis --+-- pMemFunc-+-- Meaning------+
// | 0 | 0 | 0 | Empty |
// | !=0 |(dontcare)| Invoker | Static function|
// | 0 | !=0 | !=0* | Method call |
// +--------------------+----------+------------+----------------+
// * For Metrowerks, this can be 0. (first virtual function in a
// single_inheritance class).
// When stored stored inside a specific delegate, the 'dontcare' entries are replaced
// with a reference to the delegate itself. This complicates the = and == operators
// for the delegate class.
// DelegateMemento - Evil version
//
// For compilers where data pointers are at least as big as code pointers, it is
// possible to store the function pointer in the this pointer, using another
// horrible_cast. In this case the DelegateMemento implementation is simple:
// +--pThis --+-- pMemFunc-+-- Meaning---------------------+
// | 0 | 0 | Empty |
// | !=0 | !=0* | Static function or method call|
// +----------+------------+-------------------------------+
// * For Metrowerks, this can be 0. (first virtual function in a
// single_inheritance class).
// Note that the Sun C++ and MSVC documentation explicitly state that they
// support static_cast between void * and function pointers.
class DelegateMemento {
protected:
// the data is protected, not private, because many
// compilers have problems with template friends.
typedef void (detail::GenericClass::*GenericMemFuncType)(); // arbitrary MFP.
detail::GenericClass *m_pthis;
GenericMemFuncType m_pFunction;
#if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
typedef void (*GenericFuncPtr)(); // arbitrary code pointer
GenericFuncPtr m_pStaticFunction;
#endif
public:
#if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
DelegateMemento() : m_pthis(0), m_pFunction(0), m_pStaticFunction(0) {};
void clear() {
m_pthis=0; m_pFunction=0; m_pStaticFunction=0;
}
#else
DelegateMemento() : m_pthis(0), m_pFunction(0) {};
void clear() { m_pthis=0; m_pFunction=0; }
#endif
public:
#if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
inline bool IsEqual (const DelegateMemento &x) const{
// We have to cope with the static function pointers as a special case
if (m_pFunction!=x.m_pFunction) return false;
// the static function ptrs must either both be equal, or both be 0.
if (m_pStaticFunction!=x.m_pStaticFunction) return false;
if (m_pStaticFunction!=0) return m_pthis==x.m_pthis;
else return true;
}
#else // Evil Method
inline bool IsEqual (const DelegateMemento &x) const{
return m_pthis==x.m_pthis && m_pFunction==x.m_pFunction;
}
#endif
// Provide a strict weak ordering for DelegateMementos.
inline bool IsLess(const DelegateMemento &right) const {
// deal with static function pointers first
#if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
if (m_pStaticFunction !=0 || right.m_pStaticFunction!=0)
return m_pStaticFunction < right.m_pStaticFunction;
#endif
if (m_pthis !=right.m_pthis) return m_pthis < right.m_pthis;
// There are no ordering operators for member function pointers,
// but we can fake one by comparing each byte. The resulting ordering is
// arbitrary (and compiler-dependent), but it permits storage in ordered STL containers.
return memcmp(&m_pFunction, &right.m_pFunction, sizeof(m_pFunction)) < 0;
}
// BUGFIX (Mar 2005):
// We can't just compare m_pFunction because on Metrowerks,
// m_pFunction can be zero even if the delegate is not empty!
inline bool operator ! () const // Is it bound to anything?
{ return m_pthis==0 && m_pFunction==0; }
inline bool empty() const // Is it bound to anything?
{ return m_pthis==0 && m_pFunction==0; }
public:
DelegateMemento & operator = (const DelegateMemento &right) {
SetMementoFrom(right);
return *this;
}
inline bool operator <(const DelegateMemento &right) {
return IsLess(right);
}
inline bool operator >(const DelegateMemento &right) {
return right.IsLess(*this);
}
DelegateMemento (const DelegateMemento &right) :
m_pFunction(right.m_pFunction), m_pthis(right.m_pthis)
#if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
, m_pStaticFunction (right.m_pStaticFunction)
#endif
{}
protected:
void SetMementoFrom(const DelegateMemento &right) {
m_pFunction = right.m_pFunction;
m_pthis = right.m_pthis;
#if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
m_pStaticFunction = right.m_pStaticFunction;
#endif
}
};
// ClosurePtr<>
//
// A private wrapper class that adds function signatures to DelegateMemento.
// It's the class that does most of the actual work.
// The signatures are specified by:
// GenericMemFunc: must be a type of GenericClass member function pointer.
// StaticFuncPtr: must be a type of function pointer with the same signature
// as GenericMemFunc.
// UnvoidStaticFuncPtr: is the same as StaticFuncPtr, except on VC6
// where it never returns void (returns DefaultVoid instead).
// An outer class, FastDelegateN<>, handles the invoking and creates the
// necessary typedefs.
// This class does everything else.
namespace detail {
template < class GenericMemFunc, class StaticFuncPtr, class UnvoidStaticFuncPtr>
class ClosurePtr : public DelegateMemento {
public:
// These functions are for setting the delegate to a member function.
// Here's the clever bit: we convert an arbitrary member function into a
// standard form. XMemFunc should be a member function of class X, but I can't
// enforce that here. It needs to be enforced by the wrapper class.
template < class X, class XMemFunc >
inline void bindmemfunc(X *pthis, XMemFunc function_to_bind ) {
m_pthis = SimplifyMemFunc< sizeof(function_to_bind) >
::Convert(pthis, function_to_bind, m_pFunction);
#if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
m_pStaticFunction = 0;
#endif
}
// For const member functions, we only need a const class pointer.
// Since we know that the member function is const, it's safe to
// remove the const qualifier from the 'this' pointer with a const_cast.
// VC6 has problems if we just overload 'bindmemfunc', so we give it a different name.
template < class X, class XMemFunc>
inline void bindconstmemfunc(const X *pthis, XMemFunc function_to_bind) {
m_pthis= SimplifyMemFunc< sizeof(function_to_bind) >
::Convert(const_cast<X*>(pthis), function_to_bind, m_pFunction);
#if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
m_pStaticFunction = 0;
#endif
}
#ifdef FASTDELEGATE_GCC_BUG_8271 // At present, GCC doesn't recognize constness of MFPs in templates
template < class X, class XMemFunc>
inline void bindmemfunc(const X *pthis, XMemFunc function_to_bind) {
bindconstmemfunc(pthis, function_to_bind);
#if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
m_pStaticFunction = 0;
#endif
}
#endif
// These functions are required for invoking the stored function
inline GenericClass *GetClosureThis() const { return m_pthis; }
inline GenericMemFunc GetClosureMemPtr() const { return reinterpret_cast<GenericMemFunc>(m_pFunction); }
// There are a few ways of dealing with static function pointers.
// There's a standard-compliant, but tricky method.
// There's also a straightforward hack, that won't work on DOS compilers using the
// medium memory model. It's so evil that I can't recommend it, but I've
// implemented it anyway because it produces very nice asm code.
#if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
// ClosurePtr<> - Safe version
//
// This implementation is standard-compliant, but a bit tricky.
// I store the function pointer inside the class, and the delegate then
// points to itself. Whenever the delegate is copied, these self-references
// must be transformed, and this complicates the = and == operators.
public:
// The next two functions are for operator ==, =, and the copy constructor.
// We may need to convert the m_pthis pointers, so that
// they remain as self-references.
template< class DerivedClass >
inline void CopyFrom (DerivedClass *pParent, const DelegateMemento &x) {
SetMementoFrom(x);
if (m_pStaticFunction!=0) {
// transform self references...
m_pthis=reinterpret_cast<GenericClass *>(pParent);
}
}
// For static functions, the 'static_function_invoker' class in the parent
// will be called. The parent then needs to call GetStaticFunction() to find out
// the actual function to invoke.
template < class DerivedClass, class ParentInvokerSig >
inline void bindstaticfunc(DerivedClass *pParent, ParentInvokerSig static_function_invoker,
StaticFuncPtr function_to_bind ) {
if (function_to_bind==0) { // cope with assignment to 0
m_pFunction=0;
} else {
bindmemfunc(pParent, static_function_invoker);
}
m_pStaticFunction=reinterpret_cast<GenericFuncPtr>(function_to_bind);
}
inline UnvoidStaticFuncPtr GetStaticFunction() const {
return reinterpret_cast<UnvoidStaticFuncPtr>(m_pStaticFunction);
}
#else
// ClosurePtr<> - Evil version
//
// For compilers where data pointers are at least as big as code pointers, it is
// possible to store the function pointer in the this pointer, using another
// horrible_cast. Invocation isn't any faster, but it saves 4 bytes, and
// speeds up comparison and assignment. If C++ provided direct language support
// for delegates, they would produce asm code that was almost identical to this.
// Note that the Sun C++ and MSVC documentation explicitly state that they
// support static_cast between void * and function pointers.
template< class DerivedClass >
inline void CopyFrom (DerivedClass *pParent, const DelegateMemento &right) {
SetMementoFrom(right);
}
// For static functions, the 'static_function_invoker' class in the parent
// will be called. The parent then needs to call GetStaticFunction() to find out
// the actual function to invoke.
// ******** EVIL, EVIL CODE! *******
template < class DerivedClass, class ParentInvokerSig>
inline void bindstaticfunc(DerivedClass *pParent, ParentInvokerSig static_function_invoker,
StaticFuncPtr function_to_bind) {
if (function_to_bind==0) { // cope with assignment to 0
m_pFunction=0;
} else {
// We'll be ignoring the 'this' pointer, but we need to make sure we pass
// a valid value to bindmemfunc().
bindmemfunc(pParent, static_function_invoker);
}
// WARNING! Evil hack. We store the function in the 'this' pointer!
// Ensure that there's a compilation failure if function pointers
// and data pointers have different sizes.
// If you get this error, you need to #undef FASTDELEGATE_USESTATICFUNCTIONHACK.
typedef int ERROR_CantUseEvilMethod[sizeof(GenericClass *)==sizeof(function_to_bind) ? 1 : -1];
m_pthis = horrible_cast<GenericClass *>(function_to_bind);
// MSVC, SunC++ and DMC accept the following (non-standard) code:
// m_pthis = static_cast<GenericClass *>(static_cast<void *>(function_to_bind));
// BCC32, Comeau and DMC accept this method. MSVC7.1 needs __int64 instead of long
// m_pthis = reinterpret_cast<GenericClass *>(reinterpret_cast<long>(function_to_bind));
}
// ******** EVIL, EVIL CODE! *******
// This function will be called with an invalid 'this' pointer!!
// We're just returning the 'this' pointer, converted into
// a function pointer!
inline UnvoidStaticFuncPtr GetStaticFunction() const {
// Ensure that there's a compilation failure if function pointers
// and data pointers have different sizes.
// If you get this error, you need to #undef FASTDELEGATE_USESTATICFUNCTIONHACK.
typedef int ERROR_CantUseEvilMethod[sizeof(UnvoidStaticFuncPtr)==sizeof(this) ? 1 : -1];
return horrible_cast<UnvoidStaticFuncPtr>(this);
}
#endif // !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
// Does the closure contain this static function?
inline bool IsEqualToStaticFuncPtr(StaticFuncPtr funcptr){
if (funcptr==0) return empty();
// For the Evil method, if it doesn't actually contain a static function, this will return an arbitrary
// value that is not equal to any valid function pointer.
else return funcptr==reinterpret_cast<StaticFuncPtr>(GetStaticFunction());
}
};
} // namespace detail
////////////////////////////////////////////////////////////////////////////////
// Fast Delegates, part 3:
//
// Wrapper classes to ensure type safety
//
////////////////////////////////////////////////////////////////////////////////
// Once we have the member function conversion templates, it's easy to make the
// wrapper classes. So that they will work with as many compilers as possible,
// the classes are of the form
// FastDelegate3<int, char *, double>
// They can cope with any combination of parameters. The max number of parameters
// allowed is 8, but it is trivial to increase this limit.
// Note that we need to treat const member functions seperately.
// All this class does is to enforce type safety, and invoke the delegate with
// the correct list of parameters.
// Because of the weird rule about the class of derived member function pointers,
// you sometimes need to apply a downcast to the 'this' pointer.
// This is the reason for the use of "implicit_cast<X*>(pthis)" in the code below.
// If CDerivedClass is derived from CBaseClass, but doesn't override SimpleVirtualFunction,
// without this trick you'd need to write:
// MyDelegate(static_cast<CBaseClass *>(&d), &CDerivedClass::SimpleVirtualFunction);
// but with the trick you can write
// MyDelegate(&d, &CDerivedClass::SimpleVirtualFunction);
// RetType is the type the compiler uses in compiling the template. For VC6,
// it cannot be void. DesiredRetType is the real type which is returned from
// all of the functions. It can be void.
// Implicit conversion to "bool" is achieved using the safe_bool idiom,
// using member data pointers (MDP). This allows "if (dg)..." syntax
// Because some compilers (eg codeplay) don't have a unique value for a zero
// MDP, an extra padding member is added to the SafeBool struct.
// Some compilers (eg VC6) won't implicitly convert from 0 to an MDP, so
// in that case the static function constructor is not made explicit; this
// allows "if (dg==0) ..." to compile.
//N=0
template<class RetType=detail::DefaultVoid>
class FastDelegate0 {
private:
typedef typename detail::DefaultVoidToVoid<RetType>::type DesiredRetType;
typedef DesiredRetType (*StaticFunctionPtr)();
typedef RetType (*UnvoidStaticFunctionPtr)();
typedef RetType (detail::GenericClass::*GenericMemFn)();
typedef detail::ClosurePtr<GenericMemFn, StaticFunctionPtr, UnvoidStaticFunctionPtr> ClosureType;
ClosureType m_Closure;
public:
// Typedefs to aid generic programming
typedef FastDelegate0 type;
// Construction and comparison functions
FastDelegate0() { clear(); }
FastDelegate0(const FastDelegate0 &x) {
m_Closure.CopyFrom(this, x.m_Closure); }
void operator = (const FastDelegate0 &x) {
m_Closure.CopyFrom(this, x.m_Closure); }
bool operator ==(const FastDelegate0 &x) const {
return m_Closure.IsEqual(x.m_Closure); }
bool operator !=(const FastDelegate0 &x) const {
return !m_Closure.IsEqual(x.m_Closure); }
bool operator <(const FastDelegate0 &x) const {
return m_Closure.IsLess(x.m_Closure); }
bool operator >(const FastDelegate0 &x) const {
return x.m_Closure.IsLess(m_Closure); }
// Binding to non-const member functions
template < class X, class Y >
FastDelegate0(Y *pthis, DesiredRetType (X::* function_to_bind)() ) {
m_Closure.bindmemfunc(detail::implicit_cast<X*>(pthis), function_to_bind); }
template < class X, class Y >
inline void bind(Y *pthis, DesiredRetType (X::* function_to_bind)()) {
m_Closure.bindmemfunc(detail::implicit_cast<X*>(pthis), function_to_bind); }
// Binding to const member functions.
template < class X, class Y >
FastDelegate0(const Y *pthis, DesiredRetType (X::* function_to_bind)() const) {
m_Closure.bindconstmemfunc(detail::implicit_cast<const X*>(pthis), function_to_bind); }
template < class X, class Y >
inline void bind(const Y *pthis, DesiredRetType (X::* function_to_bind)() const) {
m_Closure.bindconstmemfunc(detail::implicit_cast<const X *>(pthis), function_to_bind); }
// Static functions. We convert them into a member function call.
// This constructor also provides implicit conversion
FastDelegate0(DesiredRetType (*function_to_bind)() ) {
bind(function_to_bind); }
// for efficiency, prevent creation of a temporary
void operator = (DesiredRetType (*function_to_bind)() ) {
bind(function_to_bind); }
inline void bind(DesiredRetType (*function_to_bind)()) {
m_Closure.bindstaticfunc(this, &FastDelegate0::InvokeStaticFunction,
function_to_bind); }
// Invoke the delegate
RetType operator() () const {
return (m_Closure.GetClosureThis()->*(m_Closure.GetClosureMemPtr()))(); }
// Implicit conversion to "bool" using the safe_bool idiom
private:
typedef struct SafeBoolStruct {
int a_data_pointer_to_this_is_0_on_buggy_compilers;
StaticFunctionPtr m_nonzero;
} UselessTypedef;
typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type;
public:
operator unspecified_bool_type() const {
return empty()? 0: &SafeBoolStruct::m_nonzero;
}
// necessary to allow ==0 to work despite the safe_bool idiom
inline bool operator==(StaticFunctionPtr funcptr) {
return m_Closure.IsEqualToStaticFuncPtr(funcptr); }
inline bool operator!=(StaticFunctionPtr funcptr) {
return !m_Closure.IsEqualToStaticFuncPtr(funcptr); }
inline bool operator ! () const { // Is it bound to anything?
return !m_Closure; }
inline bool empty() const {
return !m_Closure; }
void clear() { m_Closure.clear();}
// Conversion to and from the DelegateMemento storage class
const DelegateMemento & GetMemento() { return m_Closure; }
void SetMemento(const DelegateMemento &any) { m_Closure.CopyFrom(this, any); }
private: // Invoker for static functions
RetType InvokeStaticFunction() const {
return (*(m_Closure.GetStaticFunction()))(); }
};
//N=1
template<class Param1, class RetType=detail::DefaultVoid>
class FastDelegate1 {
private:
typedef typename detail::DefaultVoidToVoid<RetType>::type DesiredRetType;
typedef DesiredRetType (*StaticFunctionPtr)(Param1 p1);
typedef RetType (*UnvoidStaticFunctionPtr)(Param1 p1);
typedef RetType (detail::GenericClass::*GenericMemFn)(Param1 p1);
typedef detail::ClosurePtr<GenericMemFn, StaticFunctionPtr, UnvoidStaticFunctionPtr> ClosureType;
ClosureType m_Closure;
public:
// Typedefs to aid generic programming
typedef FastDelegate1 type;
// Construction and comparison functions
FastDelegate1() { clear(); }
FastDelegate1(const FastDelegate1 &x) {
m_Closure.CopyFrom(this, x.m_Closure); }
void operator = (const FastDelegate1 &x) {
m_Closure.CopyFrom(this, x.m_Closure); }
bool operator ==(const FastDelegate1 &x) const {
return m_Closure.IsEqual(x.m_Closure); }
bool operator !=(const FastDelegate1 &x) const {
return !m_Closure.IsEqual(x.m_Closure); }
bool operator <(const FastDelegate1 &x) const {
return m_Closure.IsLess(x.m_Closure); }
bool operator >(const FastDelegate1 &x) const {
return x.m_Closure.IsLess(m_Closure); }
// Binding to non-const member functions
template < class X, class Y >
FastDelegate1(Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1) ) {
m_Closure.bindmemfunc(detail::implicit_cast<X*>(pthis), function_to_bind); }
template < class X, class Y >
inline void bind(Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1)) {
m_Closure.bindmemfunc(detail::implicit_cast<X*>(pthis), function_to_bind); }
// Binding to const member functions.
template < class X, class Y >
FastDelegate1(const Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1) const) {
m_Closure.bindconstmemfunc(detail::implicit_cast<const X*>(pthis), function_to_bind); }
template < class X, class Y >
inline void bind(const Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1) const) {
m_Closure.bindconstmemfunc(detail::implicit_cast<const X *>(pthis), function_to_bind); }
// Static functions. We convert them into a member function call.
// This constructor also provides implicit conversion
FastDelegate1(DesiredRetType (*function_to_bind)(Param1 p1) ) {
bind(function_to_bind); }
// for efficiency, prevent creation of a temporary
void operator = (DesiredRetType (*function_to_bind)(Param1 p1) ) {
bind(function_to_bind); }
inline void bind(DesiredRetType (*function_to_bind)(Param1 p1)) {
m_Closure.bindstaticfunc(this, &FastDelegate1::InvokeStaticFunction,
function_to_bind); }
// Invoke the delegate
RetType operator() (Param1 p1) const {
return (m_Closure.GetClosureThis()->*(m_Closure.GetClosureMemPtr()))(p1); }
// Implicit conversion to "bool" using the safe_bool idiom
private:
typedef struct SafeBoolStruct {
int a_data_pointer_to_this_is_0_on_buggy_compilers;
StaticFunctionPtr m_nonzero;
} UselessTypedef;
typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type;
public:
operator unspecified_bool_type() const {
return empty()? 0: &SafeBoolStruct::m_nonzero;
}
// necessary to allow ==0 to work despite the safe_bool idiom
inline bool operator==(StaticFunctionPtr funcptr) {
return m_Closure.IsEqualToStaticFuncPtr(funcptr); }
inline bool operator!=(StaticFunctionPtr funcptr) {
return !m_Closure.IsEqualToStaticFuncPtr(funcptr); }
inline bool operator ! () const { // Is it bound to anything?
return !m_Closure; }
inline bool empty() const {
return !m_Closure; }
void clear() { m_Closure.clear();}
// Conversion to and from the DelegateMemento storage class
const DelegateMemento & GetMemento() { return m_Closure; }
void SetMemento(const DelegateMemento &any) { m_Closure.CopyFrom(this, any); }
private: // Invoker for static functions
RetType InvokeStaticFunction(Param1 p1) const {
return (*(m_Closure.GetStaticFunction()))(p1); }
};
//N=2
template<class Param1, class Param2, class RetType=detail::DefaultVoid>
class FastDelegate2 {
private:
typedef typename detail::DefaultVoidToVoid<RetType>::type DesiredRetType;
typedef DesiredRetType (*StaticFunctionPtr)(Param1 p1, Param2 p2);
typedef RetType (*UnvoidStaticFunctionPtr)(Param1 p1, Param2 p2);
typedef RetType (detail::GenericClass::*GenericMemFn)(Param1 p1, Param2 p2);
typedef detail::ClosurePtr<GenericMemFn, StaticFunctionPtr, UnvoidStaticFunctionPtr> ClosureType;
ClosureType m_Closure;
public:
// Typedefs to aid generic programming
typedef FastDelegate2 type;
// Construction and comparison functions
FastDelegate2() { clear(); }
FastDelegate2(const FastDelegate2 &x) {
m_Closure.CopyFrom(this, x.m_Closure); }
void operator = (const FastDelegate2 &x) {
m_Closure.CopyFrom(this, x.m_Closure); }
bool operator ==(const FastDelegate2 &x) const {
return m_Closure.IsEqual(x.m_Closure); }
bool operator !=(const FastDelegate2 &x) const {
return !m_Closure.IsEqual(x.m_Closure); }
bool operator <(const FastDelegate2 &x) const {
return m_Closure.IsLess(x.m_Closure); }
bool operator >(const FastDelegate2 &x) const {
return x.m_Closure.IsLess(m_Closure); }
// Binding to non-const member functions
template < class X, class Y >
FastDelegate2(Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1, Param2 p2) ) {
m_Closure.bindmemfunc(detail::implicit_cast<X*>(pthis), function_to_bind); }
template < class X, class Y >
inline void bind(Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1, Param2 p2)) {
m_Closure.bindmemfunc(detail::implicit_cast<X*>(pthis), function_to_bind); }
// Binding to const member functions.
template < class X, class Y >
FastDelegate2(const Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1, Param2 p2) const) {
m_Closure.bindconstmemfunc(detail::implicit_cast<const X*>(pthis), function_to_bind); }
template < class X, class Y >
inline void bind(const Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1, Param2 p2) const) {
m_Closure.bindconstmemfunc(detail::implicit_cast<const X *>(pthis), function_to_bind); }
// Static functions. We convert them into a member function call.
// This constructor also provides implicit conversion
FastDelegate2(DesiredRetType (*function_to_bind)(Param1 p1, Param2 p2) ) {
bind(function_to_bind); }
// for efficiency, prevent creation of a temporary
void operator = (DesiredRetType (*function_to_bind)(Param1 p1, Param2 p2) ) {
bind(function_to_bind); }
inline void bind(DesiredRetType (*function_to_bind)(Param1 p1, Param2 p2)) {
m_Closure.bindstaticfunc(this, &FastDelegate2::InvokeStaticFunction,
function_to_bind); }
// Invoke the delegate
RetType operator() (Param1 p1, Param2 p2) const {
return (m_Closure.GetClosureThis()->*(m_Closure.GetClosureMemPtr()))(p1, p2); }
// Implicit conversion to "bool" using the safe_bool idiom
private:
typedef struct SafeBoolStruct {
int a_data_pointer_to_this_is_0_on_buggy_compilers;
StaticFunctionPtr m_nonzero;
} UselessTypedef;
typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type;
public:
operator unspecified_bool_type() const {
return empty()? 0: &SafeBoolStruct::m_nonzero;
}
// necessary to allow ==0 to work despite the safe_bool idiom
inline bool operator==(StaticFunctionPtr funcptr) {
return m_Closure.IsEqualToStaticFuncPtr(funcptr); }
inline bool operator!=(StaticFunctionPtr funcptr) {
return !m_Closure.IsEqualToStaticFuncPtr(funcptr); }
inline bool operator ! () const { // Is it bound to anything?
return !m_Closure; }
inline bool empty() const {
return !m_Closure; }
void clear() { m_Closure.clear();}
// Conversion to and from the DelegateMemento storage class
const DelegateMemento & GetMemento() { return m_Closure; }
void SetMemento(const DelegateMemento &any) { m_Closure.CopyFrom(this, any); }
private: // Invoker for static functions
RetType InvokeStaticFunction(Param1 p1, Param2 p2) const {
return (*(m_Closure.GetStaticFunction()))(p1, p2); }
};
//N=3
template<class Param1, class Param2, class Param3, class RetType=detail::DefaultVoid>
class FastDelegate3 {
private:
typedef typename detail::DefaultVoidToVoid<RetType>::type DesiredRetType;
typedef DesiredRetType (*StaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3);
typedef RetType (*UnvoidStaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3);
typedef RetType (detail::GenericClass::*GenericMemFn)(Param1 p1, Param2 p2, Param3 p3);
typedef detail::ClosurePtr<GenericMemFn, StaticFunctionPtr, UnvoidStaticFunctionPtr> ClosureType;
ClosureType m_Closure;
public:
// Typedefs to aid generic programming
typedef FastDelegate3 type;
// Construction and comparison functions
FastDelegate3() { clear(); }
FastDelegate3(const FastDelegate3 &x) {
m_Closure.CopyFrom(this, x.m_Closure); }
void operator = (const FastDelegate3 &x) {
m_Closure.CopyFrom(this, x.m_Closure); }
bool operator ==(const FastDelegate3 &x) const {
return m_Closure.IsEqual(x.m_Closure); }
bool operator !=(const FastDelegate3 &x) const {
return !m_Closure.IsEqual(x.m_Closure); }
bool operator <(const FastDelegate3 &x) const {
return m_Closure.IsLess(x.m_Closure); }
bool operator >(const FastDelegate3 &x) const {
return x.m_Closure.IsLess(m_Closure); }
// Binding to non-const member functions
template < class X, class Y >
FastDelegate3(Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3) ) {
m_Closure.bindmemfunc(detail::implicit_cast<X*>(pthis), function_to_bind); }
template < class X, class Y >
inline void bind(Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3)) {
m_Closure.bindmemfunc(detail::implicit_cast<X*>(pthis), function_to_bind); }
// Binding to const member functions.
template < class X, class Y >
FastDelegate3(const Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3) const) {
m_Closure.bindconstmemfunc(detail::implicit_cast<const X*>(pthis), function_to_bind); }
template < class X, class Y >
inline void bind(const Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3) const) {
m_Closure.bindconstmemfunc(detail::implicit_cast<const X *>(pthis), function_to_bind); }
// Static functions. We convert them into a member function call.
// This constructor also provides implicit conversion
FastDelegate3(DesiredRetType (*function_to_bind)(Param1 p1, Param2 p2, Param3 p3) ) {
bind(function_to_bind); }
// for efficiency, prevent creation of a temporary
void operator = (DesiredRetType (*function_to_bind)(Param1 p1, Param2 p2, Param3 p3) ) {
bind(function_to_bind); }
inline void bind(DesiredRetType (*function_to_bind)(Param1 p1, Param2 p2, Param3 p3)) {
m_Closure.bindstaticfunc(this, &FastDelegate3::InvokeStaticFunction,
function_to_bind); }
// Invoke the delegate
RetType operator() (Param1 p1, Param2 p2, Param3 p3) const {
return (m_Closure.GetClosureThis()->*(m_Closure.GetClosureMemPtr()))(p1, p2, p3); }
// Implicit conversion to "bool" using the safe_bool idiom
private:
typedef struct SafeBoolStruct {
int a_data_pointer_to_this_is_0_on_buggy_compilers;
StaticFunctionPtr m_nonzero;
} UselessTypedef;
typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type;
public:
operator unspecified_bool_type() const {
return empty()? 0: &SafeBoolStruct::m_nonzero;
}
// necessary to allow ==0 to work despite the safe_bool idiom
inline bool operator==(StaticFunctionPtr funcptr) {
return m_Closure.IsEqualToStaticFuncPtr(funcptr); }
inline bool operator!=(StaticFunctionPtr funcptr) {
return !m_Closure.IsEqualToStaticFuncPtr(funcptr); }
inline bool operator ! () const { // Is it bound to anything?
return !m_Closure; }
inline bool empty() const {
return !m_Closure; }
void clear() { m_Closure.clear();}
// Conversion to and from the DelegateMemento storage class
const DelegateMemento & GetMemento() { return m_Closure; }
void SetMemento(const DelegateMemento &any) { m_Closure.CopyFrom(this, any); }
private: // Invoker for static functions
RetType InvokeStaticFunction(Param1 p1, Param2 p2, Param3 p3) const {
return (*(m_Closure.GetStaticFunction()))(p1, p2, p3); }
};
//N=4
template<class Param1, class Param2, class Param3, class Param4, class RetType=detail::DefaultVoid>
class FastDelegate4 {
private:
typedef typename detail::DefaultVoidToVoid<RetType>::type DesiredRetType;
typedef DesiredRetType (*StaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3, Param4 p4);
typedef RetType (*UnvoidStaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3, Param4 p4);
typedef RetType (detail::GenericClass::*GenericMemFn)(Param1 p1, Param2 p2, Param3 p3, Param4 p4);
typedef detail::ClosurePtr<GenericMemFn, StaticFunctionPtr, UnvoidStaticFunctionPtr> ClosureType;
ClosureType m_Closure;
public:
// Typedefs to aid generic programming
typedef FastDelegate4 type;
// Construction and comparison functions
FastDelegate4() { clear(); }
FastDelegate4(const FastDelegate4 &x) {
m_Closure.CopyFrom(this, x.m_Closure); }
void operator = (const FastDelegate4 &x) {
m_Closure.CopyFrom(this, x.m_Closure); }
bool operator ==(const FastDelegate4 &x) const {
return m_Closure.IsEqual(x.m_Closure); }
bool operator !=(const FastDelegate4 &x) const {
return !m_Closure.IsEqual(x.m_Closure); }
bool operator <(const FastDelegate4 &x) const {
return m_Closure.IsLess(x.m_Closure); }
bool operator >(const FastDelegate4 &x) const {
return x.m_Closure.IsLess(m_Closure); }
// Binding to non-const member functions
template < class X, class Y >
FastDelegate4(Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4) ) {
m_Closure.bindmemfunc(detail::implicit_cast<X*>(pthis), function_to_bind); }
template < class X, class Y >
inline void bind(Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4)) {
m_Closure.bindmemfunc(detail::implicit_cast<X*>(pthis), function_to_bind); }
// Binding to const member functions.
template < class X, class Y >
FastDelegate4(const Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4) const) {
m_Closure.bindconstmemfunc(detail::implicit_cast<const X*>(pthis), function_to_bind); }
template < class X, class Y >
inline void bind(const Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4) const) {
m_Closure.bindconstmemfunc(detail::implicit_cast<const X *>(pthis), function_to_bind); }
// Static functions. We convert them into a member function call.
// This constructor also provides implicit conversion
FastDelegate4(DesiredRetType (*function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4) ) {
bind(function_to_bind); }
// for efficiency, prevent creation of a temporary
void operator = (DesiredRetType (*function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4) ) {
bind(function_to_bind); }
inline void bind(DesiredRetType (*function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4)) {
m_Closure.bindstaticfunc(this, &FastDelegate4::InvokeStaticFunction,
function_to_bind); }
// Invoke the delegate
RetType operator() (Param1 p1, Param2 p2, Param3 p3, Param4 p4) const {
return (m_Closure.GetClosureThis()->*(m_Closure.GetClosureMemPtr()))(p1, p2, p3, p4); }
// Implicit conversion to "bool" using the safe_bool idiom
private:
typedef struct SafeBoolStruct {
int a_data_pointer_to_this_is_0_on_buggy_compilers;
StaticFunctionPtr m_nonzero;
} UselessTypedef;
typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type;
public:
operator unspecified_bool_type() const {
return empty()? 0: &SafeBoolStruct::m_nonzero;
}
// necessary to allow ==0 to work despite the safe_bool idiom
inline bool operator==(StaticFunctionPtr funcptr) {
return m_Closure.IsEqualToStaticFuncPtr(funcptr); }
inline bool operator!=(StaticFunctionPtr funcptr) {
return !m_Closure.IsEqualToStaticFuncPtr(funcptr); }
inline bool operator ! () const { // Is it bound to anything?
return !m_Closure; }
inline bool empty() const {
return !m_Closure; }
void clear() { m_Closure.clear();}
// Conversion to and from the DelegateMemento storage class
const DelegateMemento & GetMemento() { return m_Closure; }
void SetMemento(const DelegateMemento &any) { m_Closure.CopyFrom(this, any); }
private: // Invoker for static functions
RetType InvokeStaticFunction(Param1 p1, Param2 p2, Param3 p3, Param4 p4) const {
return (*(m_Closure.GetStaticFunction()))(p1, p2, p3, p4); }
};
//N=5
template<class Param1, class Param2, class Param3, class Param4, class Param5, class RetType=detail::DefaultVoid>
class FastDelegate5 {
private:
typedef typename detail::DefaultVoidToVoid<RetType>::type DesiredRetType;
typedef DesiredRetType (*StaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5);
typedef RetType (*UnvoidStaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5);
typedef RetType (detail::GenericClass::*GenericMemFn)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5);
typedef detail::ClosurePtr<GenericMemFn, StaticFunctionPtr, UnvoidStaticFunctionPtr> ClosureType;
ClosureType m_Closure;
public:
// Typedefs to aid generic programming
typedef FastDelegate5 type;
// Construction and comparison functions
FastDelegate5() { clear(); }
FastDelegate5(const FastDelegate5 &x) {
m_Closure.CopyFrom(this, x.m_Closure); }
void operator = (const FastDelegate5 &x) {
m_Closure.CopyFrom(this, x.m_Closure); }
bool operator ==(const FastDelegate5 &x) const {
return m_Closure.IsEqual(x.m_Closure); }
bool operator !=(const FastDelegate5 &x) const {
return !m_Closure.IsEqual(x.m_Closure); }
bool operator <(const FastDelegate5 &x) const {
return m_Closure.IsLess(x.m_Closure); }
bool operator >(const FastDelegate5 &x) const {
return x.m_Closure.IsLess(m_Closure); }
// Binding to non-const member functions
template < class X, class Y >
FastDelegate5(Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5) ) {
m_Closure.bindmemfunc(detail::implicit_cast<X*>(pthis), function_to_bind); }
template < class X, class Y >
inline void bind(Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5)) {
m_Closure.bindmemfunc(detail::implicit_cast<X*>(pthis), function_to_bind); }
// Binding to const member functions.
template < class X, class Y >
FastDelegate5(const Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5) const) {
m_Closure.bindconstmemfunc(detail::implicit_cast<const X*>(pthis), function_to_bind); }
template < class X, class Y >
inline void bind(const Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5) const) {
m_Closure.bindconstmemfunc(detail::implicit_cast<const X *>(pthis), function_to_bind); }
// Static functions. We convert them into a member function call.
// This constructor also provides implicit conversion
FastDelegate5(DesiredRetType (*function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5) ) {
bind(function_to_bind); }
// for efficiency, prevent creation of a temporary
void operator = (DesiredRetType (*function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5) ) {
bind(function_to_bind); }
inline void bind(DesiredRetType (*function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5)) {
m_Closure.bindstaticfunc(this, &FastDelegate5::InvokeStaticFunction,
function_to_bind); }
// Invoke the delegate
RetType operator() (Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5) const {
return (m_Closure.GetClosureThis()->*(m_Closure.GetClosureMemPtr()))(p1, p2, p3, p4, p5); }
// Implicit conversion to "bool" using the safe_bool idiom
private:
typedef struct SafeBoolStruct {
int a_data_pointer_to_this_is_0_on_buggy_compilers;
StaticFunctionPtr m_nonzero;
} UselessTypedef;
typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type;
public:
operator unspecified_bool_type() const {
return empty()? 0: &SafeBoolStruct::m_nonzero;
}
// necessary to allow ==0 to work despite the safe_bool idiom
inline bool operator==(StaticFunctionPtr funcptr) {
return m_Closure.IsEqualToStaticFuncPtr(funcptr); }
inline bool operator!=(StaticFunctionPtr funcptr) {
return !m_Closure.IsEqualToStaticFuncPtr(funcptr); }
inline bool operator ! () const { // Is it bound to anything?
return !m_Closure; }
inline bool empty() const {
return !m_Closure; }
void clear() { m_Closure.clear();}
// Conversion to and from the DelegateMemento storage class
const DelegateMemento & GetMemento() { return m_Closure; }
void SetMemento(const DelegateMemento &any) { m_Closure.CopyFrom(this, any); }
private: // Invoker for static functions
RetType InvokeStaticFunction(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5) const {
return (*(m_Closure.GetStaticFunction()))(p1, p2, p3, p4, p5); }
};
//N=6
template<class Param1, class Param2, class Param3, class Param4, class Param5, class Param6, class RetType=detail::DefaultVoid>
class FastDelegate6 {
private:
typedef typename detail::DefaultVoidToVoid<RetType>::type DesiredRetType;
typedef DesiredRetType (*StaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6);
typedef RetType (*UnvoidStaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6);
typedef RetType (detail::GenericClass::*GenericMemFn)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6);
typedef detail::ClosurePtr<GenericMemFn, StaticFunctionPtr, UnvoidStaticFunctionPtr> ClosureType;
ClosureType m_Closure;
public:
// Typedefs to aid generic programming
typedef FastDelegate6 type;
// Construction and comparison functions
FastDelegate6() { clear(); }
FastDelegate6(const FastDelegate6 &x) {
m_Closure.CopyFrom(this, x.m_Closure); }
void operator = (const FastDelegate6 &x) {
m_Closure.CopyFrom(this, x.m_Closure); }
bool operator ==(const FastDelegate6 &x) const {
return m_Closure.IsEqual(x.m_Closure); }
bool operator !=(const FastDelegate6 &x) const {
return !m_Closure.IsEqual(x.m_Closure); }
bool operator <(const FastDelegate6 &x) const {
return m_Closure.IsLess(x.m_Closure); }
bool operator >(const FastDelegate6 &x) const {
return x.m_Closure.IsLess(m_Closure); }
// Binding to non-const member functions
template < class X, class Y >
FastDelegate6(Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6) ) {
m_Closure.bindmemfunc(detail::implicit_cast<X*>(pthis), function_to_bind); }
template < class X, class Y >
inline void bind(Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6)) {
m_Closure.bindmemfunc(detail::implicit_cast<X*>(pthis), function_to_bind); }
// Binding to const member functions.
template < class X, class Y >
FastDelegate6(const Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6) const) {
m_Closure.bindconstmemfunc(detail::implicit_cast<const X*>(pthis), function_to_bind); }
template < class X, class Y >
inline void bind(const Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6) const) {
m_Closure.bindconstmemfunc(detail::implicit_cast<const X *>(pthis), function_to_bind); }
// Static functions. We convert them into a member function call.
// This constructor also provides implicit conversion
FastDelegate6(DesiredRetType (*function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6) ) {
bind(function_to_bind); }
// for efficiency, prevent creation of a temporary
void operator = (DesiredRetType (*function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6) ) {
bind(function_to_bind); }
inline void bind(DesiredRetType (*function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6)) {
m_Closure.bindstaticfunc(this, &FastDelegate6::InvokeStaticFunction,
function_to_bind); }
// Invoke the delegate
RetType operator() (Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6) const {
return (m_Closure.GetClosureThis()->*(m_Closure.GetClosureMemPtr()))(p1, p2, p3, p4, p5, p6); }
// Implicit conversion to "bool" using the safe_bool idiom
private:
typedef struct SafeBoolStruct {
int a_data_pointer_to_this_is_0_on_buggy_compilers;
StaticFunctionPtr m_nonzero;
} UselessTypedef;
typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type;
public:
operator unspecified_bool_type() const {
return empty()? 0: &SafeBoolStruct::m_nonzero;
}
// necessary to allow ==0 to work despite the safe_bool idiom
inline bool operator==(StaticFunctionPtr funcptr) {
return m_Closure.IsEqualToStaticFuncPtr(funcptr); }
inline bool operator!=(StaticFunctionPtr funcptr) {
return !m_Closure.IsEqualToStaticFuncPtr(funcptr); }
inline bool operator ! () const { // Is it bound to anything?
return !m_Closure; }
inline bool empty() const {
return !m_Closure; }
void clear() { m_Closure.clear();}
// Conversion to and from the DelegateMemento storage class
const DelegateMemento & GetMemento() { return m_Closure; }
void SetMemento(const DelegateMemento &any) { m_Closure.CopyFrom(this, any); }
private: // Invoker for static functions
RetType InvokeStaticFunction(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6) const {
return (*(m_Closure.GetStaticFunction()))(p1, p2, p3, p4, p5, p6); }
};
//N=7
template<class Param1, class Param2, class Param3, class Param4, class Param5, class Param6, class Param7, class RetType=detail::DefaultVoid>
class FastDelegate7 {
private:
typedef typename detail::DefaultVoidToVoid<RetType>::type DesiredRetType;
typedef DesiredRetType (*StaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7);
typedef RetType (*UnvoidStaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7);
typedef RetType (detail::GenericClass::*GenericMemFn)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7);
typedef detail::ClosurePtr<GenericMemFn, StaticFunctionPtr, UnvoidStaticFunctionPtr> ClosureType;
ClosureType m_Closure;
public:
// Typedefs to aid generic programming
typedef FastDelegate7 type;
// Construction and comparison functions
FastDelegate7() { clear(); }
FastDelegate7(const FastDelegate7 &x) {
m_Closure.CopyFrom(this, x.m_Closure); }
void operator = (const FastDelegate7 &x) {
m_Closure.CopyFrom(this, x.m_Closure); }
bool operator ==(const FastDelegate7 &x) const {
return m_Closure.IsEqual(x.m_Closure); }
bool operator !=(const FastDelegate7 &x) const {
return !m_Closure.IsEqual(x.m_Closure); }
bool operator <(const FastDelegate7 &x) const {
return m_Closure.IsLess(x.m_Closure); }
bool operator >(const FastDelegate7 &x) const {
return x.m_Closure.IsLess(m_Closure); }
// Binding to non-const member functions
template < class X, class Y >
FastDelegate7(Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7) ) {
m_Closure.bindmemfunc(detail::implicit_cast<X*>(pthis), function_to_bind); }
template < class X, class Y >
inline void bind(Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7)) {
m_Closure.bindmemfunc(detail::implicit_cast<X*>(pthis), function_to_bind); }
// Binding to const member functions.
template < class X, class Y >
FastDelegate7(const Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7) const) {
m_Closure.bindconstmemfunc(detail::implicit_cast<const X*>(pthis), function_to_bind); }
template < class X, class Y >
inline void bind(const Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7) const) {
m_Closure.bindconstmemfunc(detail::implicit_cast<const X *>(pthis), function_to_bind); }
// Static functions. We convert them into a member function call.
// This constructor also provides implicit conversion
FastDelegate7(DesiredRetType (*function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7) ) {
bind(function_to_bind); }
// for efficiency, prevent creation of a temporary
void operator = (DesiredRetType (*function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7) ) {
bind(function_to_bind); }
inline void bind(DesiredRetType (*function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7)) {
m_Closure.bindstaticfunc(this, &FastDelegate7::InvokeStaticFunction,
function_to_bind); }
// Invoke the delegate
RetType operator() (Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7) const {
return (m_Closure.GetClosureThis()->*(m_Closure.GetClosureMemPtr()))(p1, p2, p3, p4, p5, p6, p7); }
// Implicit conversion to "bool" using the safe_bool idiom
private:
typedef struct SafeBoolStruct {
int a_data_pointer_to_this_is_0_on_buggy_compilers;
StaticFunctionPtr m_nonzero;
} UselessTypedef;
typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type;
public:
operator unspecified_bool_type() const {
return empty()? 0: &SafeBoolStruct::m_nonzero;
}
// necessary to allow ==0 to work despite the safe_bool idiom
inline bool operator==(StaticFunctionPtr funcptr) {
return m_Closure.IsEqualToStaticFuncPtr(funcptr); }
inline bool operator!=(StaticFunctionPtr funcptr) {
return !m_Closure.IsEqualToStaticFuncPtr(funcptr); }
inline bool operator ! () const { // Is it bound to anything?
return !m_Closure; }
inline bool empty() const {
return !m_Closure; }
void clear() { m_Closure.clear();}
// Conversion to and from the DelegateMemento storage class
const DelegateMemento & GetMemento() { return m_Closure; }
void SetMemento(const DelegateMemento &any) { m_Closure.CopyFrom(this, any); }
private: // Invoker for static functions
RetType InvokeStaticFunction(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7) const {
return (*(m_Closure.GetStaticFunction()))(p1, p2, p3, p4, p5, p6, p7); }
};
//N=8
template<class Param1, class Param2, class Param3, class Param4, class Param5, class Param6, class Param7, class Param8, class RetType=detail::DefaultVoid>
class FastDelegate8 {
private:
typedef typename detail::DefaultVoidToVoid<RetType>::type DesiredRetType;
typedef DesiredRetType (*StaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8);
typedef RetType (*UnvoidStaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8);
typedef RetType (detail::GenericClass::*GenericMemFn)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8);
typedef detail::ClosurePtr<GenericMemFn, StaticFunctionPtr, UnvoidStaticFunctionPtr> ClosureType;
ClosureType m_Closure;
public:
// Typedefs to aid generic programming
typedef FastDelegate8 type;
// Construction and comparison functions
FastDelegate8() { clear(); }
FastDelegate8(const FastDelegate8 &x) {
m_Closure.CopyFrom(this, x.m_Closure); }
void operator = (const FastDelegate8 &x) {
m_Closure.CopyFrom(this, x.m_Closure); }
bool operator ==(const FastDelegate8 &x) const {
return m_Closure.IsEqual(x.m_Closure); }
bool operator !=(const FastDelegate8 &x) const {
return !m_Closure.IsEqual(x.m_Closure); }
bool operator <(const FastDelegate8 &x) const {
return m_Closure.IsLess(x.m_Closure); }
bool operator >(const FastDelegate8 &x) const {
return x.m_Closure.IsLess(m_Closure); }
// Binding to non-const member functions
template < class X, class Y >
FastDelegate8(Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8) ) {
m_Closure.bindmemfunc(detail::implicit_cast<X*>(pthis), function_to_bind); }
template < class X, class Y >
inline void bind(Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8)) {
m_Closure.bindmemfunc(detail::implicit_cast<X*>(pthis), function_to_bind); }
// Binding to const member functions.
template < class X, class Y >
FastDelegate8(const Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8) const) {
m_Closure.bindconstmemfunc(detail::implicit_cast<const X*>(pthis), function_to_bind); }
template < class X, class Y >
inline void bind(const Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8) const) {
m_Closure.bindconstmemfunc(detail::implicit_cast<const X *>(pthis), function_to_bind); }
// Static functions. We convert them into a member function call.
// This constructor also provides implicit conversion
FastDelegate8(DesiredRetType (*function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8) ) {
bind(function_to_bind); }
// for efficiency, prevent creation of a temporary
void operator = (DesiredRetType (*function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8) ) {
bind(function_to_bind); }
inline void bind(DesiredRetType (*function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8)) {
m_Closure.bindstaticfunc(this, &FastDelegate8::InvokeStaticFunction,
function_to_bind); }
// Invoke the delegate
RetType operator() (Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8) const {
return (m_Closure.GetClosureThis()->*(m_Closure.GetClosureMemPtr()))(p1, p2, p3, p4, p5, p6, p7, p8); }
// Implicit conversion to "bool" using the safe_bool idiom
private:
typedef struct SafeBoolStruct {
int a_data_pointer_to_this_is_0_on_buggy_compilers;
StaticFunctionPtr m_nonzero;
} UselessTypedef;
typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type;
public:
operator unspecified_bool_type() const {
return empty()? 0: &SafeBoolStruct::m_nonzero;
}
// necessary to allow ==0 to work despite the safe_bool idiom
inline bool operator==(StaticFunctionPtr funcptr) {
return m_Closure.IsEqualToStaticFuncPtr(funcptr); }
inline bool operator!=(StaticFunctionPtr funcptr) {
return !m_Closure.IsEqualToStaticFuncPtr(funcptr); }
inline bool operator ! () const { // Is it bound to anything?
return !m_Closure; }
inline bool empty() const {
return !m_Closure; }
void clear() { m_Closure.clear();}
// Conversion to and from the DelegateMemento storage class
const DelegateMemento & GetMemento() { return m_Closure; }
void SetMemento(const DelegateMemento &any) { m_Closure.CopyFrom(this, any); }
private: // Invoker for static functions
RetType InvokeStaticFunction(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8) const {
return (*(m_Closure.GetStaticFunction()))(p1, p2, p3, p4, p5, p6, p7, p8); }
};
////////////////////////////////////////////////////////////////////////////////
// Fast Delegates, part 4:
//
// FastDelegate<> class (Original author: Jody Hagins)
// Allows boost::function style syntax like:
// FastDelegate< double (int, long) >
// instead of:
// FastDelegate2< int, long, double >
//
////////////////////////////////////////////////////////////////////////////////
#ifdef FASTDELEGATE_ALLOW_FUNCTION_TYPE_SYNTAX
// Declare FastDelegate as a class template. It will be specialized
// later for all number of arguments.
template <typename Signature>
class FastDelegate;
//N=0
// Specialization to allow use of
// FastDelegate< R ( ) >
// instead of
// FastDelegate0 < R >
template<typename R>
class FastDelegate< R ( ) >
// Inherit from FastDelegate0 so that it can be treated just like a FastDelegate0
: public FastDelegate0 < R >
{
public:
// Make using the base type a bit easier via typedef.
typedef FastDelegate0 < R > BaseType;
// Allow users access to the specific type of this delegate.
typedef FastDelegate SelfType;
// Mimic the base class constructors.
FastDelegate() : BaseType() { }
template < class X, class Y >
FastDelegate(Y * pthis,
R (X::* function_to_bind)( ))
: BaseType(pthis, function_to_bind) { }
template < class X, class Y >
FastDelegate(const Y *pthis,
R (X::* function_to_bind)( ) const)
: BaseType(pthis, function_to_bind)
{ }
FastDelegate(R (*function_to_bind)( ))
: BaseType(function_to_bind) { }
void operator = (const BaseType &x) {
*static_cast<BaseType*>(this) = x; }
};
//N=1
// Specialization to allow use of
// FastDelegate< R ( Param1 ) >
// instead of
// FastDelegate1 < Param1, R >
template<typename R, class Param1>
class FastDelegate< R ( Param1 ) >
// Inherit from FastDelegate1 so that it can be treated just like a FastDelegate1
: public FastDelegate1 < Param1, R >
{
public:
// Make using the base type a bit easier via typedef.
typedef FastDelegate1 < Param1, R > BaseType;
// Allow users access to the specific type of this delegate.
typedef FastDelegate SelfType;
// Mimic the base class constructors.
FastDelegate() : BaseType() { }
template < class X, class Y >
FastDelegate(Y * pthis,
R (X::* function_to_bind)( Param1 p1 ))
: BaseType(pthis, function_to_bind) { }
template < class X, class Y >
FastDelegate(const Y *pthis,
R (X::* function_to_bind)( Param1 p1 ) const)
: BaseType(pthis, function_to_bind)
{ }
FastDelegate(R (*function_to_bind)( Param1 p1 ))
: BaseType(function_to_bind) { }
void operator = (const BaseType &x) {
*static_cast<BaseType*>(this) = x; }
};
//N=2
// Specialization to allow use of
// FastDelegate< R ( Param1, Param2 ) >
// instead of
// FastDelegate2 < Param1, Param2, R >
template<typename R, class Param1, class Param2>
class FastDelegate< R ( Param1, Param2 ) >
// Inherit from FastDelegate2 so that it can be treated just like a FastDelegate2
: public FastDelegate2 < Param1, Param2, R >
{
public:
// Make using the base type a bit easier via typedef.
typedef FastDelegate2 < Param1, Param2, R > BaseType;
// Allow users access to the specific type of this delegate.
typedef FastDelegate SelfType;
// Mimic the base class constructors.
FastDelegate() : BaseType() { }
template < class X, class Y >
FastDelegate(Y * pthis,
R (X::* function_to_bind)( Param1 p1, Param2 p2 ))
: BaseType(pthis, function_to_bind) { }
template < class X, class Y >
FastDelegate(const Y *pthis,
R (X::* function_to_bind)( Param1 p1, Param2 p2 ) const)
: BaseType(pthis, function_to_bind)
{ }
FastDelegate(R (*function_to_bind)( Param1 p1, Param2 p2 ))
: BaseType(function_to_bind) { }
void operator = (const BaseType &x) {
*static_cast<BaseType*>(this) = x; }
};
//N=3
// Specialization to allow use of
// FastDelegate< R ( Param1, Param2, Param3 ) >
// instead of
// FastDelegate3 < Param1, Param2, Param3, R >
template<typename R, class Param1, class Param2, class Param3>
class FastDelegate< R ( Param1, Param2, Param3 ) >
// Inherit from FastDelegate3 so that it can be treated just like a FastDelegate3
: public FastDelegate3 < Param1, Param2, Param3, R >
{
public:
// Make using the base type a bit easier via typedef.
typedef FastDelegate3 < Param1, Param2, Param3, R > BaseType;
// Allow users access to the specific type of this delegate.
typedef FastDelegate SelfType;
// Mimic the base class constructors.
FastDelegate() : BaseType() { }
template < class X, class Y >
FastDelegate(Y * pthis,
R (X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3 ))
: BaseType(pthis, function_to_bind) { }
template < class X, class Y >
FastDelegate(const Y *pthis,
R (X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3 ) const)
: BaseType(pthis, function_to_bind)
{ }
FastDelegate(R (*function_to_bind)( Param1 p1, Param2 p2, Param3 p3 ))
: BaseType(function_to_bind) { }
void operator = (const BaseType &x) {
*static_cast<BaseType*>(this) = x; }
};
//N=4
// Specialization to allow use of
// FastDelegate< R ( Param1, Param2, Param3, Param4 ) >
// instead of
// FastDelegate4 < Param1, Param2, Param3, Param4, R >
template<typename R, class Param1, class Param2, class Param3, class Param4>
class FastDelegate< R ( Param1, Param2, Param3, Param4 ) >
// Inherit from FastDelegate4 so that it can be treated just like a FastDelegate4
: public FastDelegate4 < Param1, Param2, Param3, Param4, R >
{
public:
// Make using the base type a bit easier via typedef.
typedef FastDelegate4 < Param1, Param2, Param3, Param4, R > BaseType;
// Allow users access to the specific type of this delegate.
typedef FastDelegate SelfType;
// Mimic the base class constructors.
FastDelegate() : BaseType() { }
template < class X, class Y >
FastDelegate(Y * pthis,
R (X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4 ))
: BaseType(pthis, function_to_bind) { }
template < class X, class Y >
FastDelegate(const Y *pthis,
R (X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4 ) const)
: BaseType(pthis, function_to_bind)
{ }
FastDelegate(R (*function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4 ))
: BaseType(function_to_bind) { }
void operator = (const BaseType &x) {
*static_cast<BaseType*>(this) = x; }
};
//N=5
// Specialization to allow use of
// FastDelegate< R ( Param1, Param2, Param3, Param4, Param5 ) >
// instead of
// FastDelegate5 < Param1, Param2, Param3, Param4, Param5, R >
template<typename R, class Param1, class Param2, class Param3, class Param4, class Param5>
class FastDelegate< R ( Param1, Param2, Param3, Param4, Param5 ) >
// Inherit from FastDelegate5 so that it can be treated just like a FastDelegate5
: public FastDelegate5 < Param1, Param2, Param3, Param4, Param5, R >
{
public:
// Make using the base type a bit easier via typedef.
typedef FastDelegate5 < Param1, Param2, Param3, Param4, Param5, R > BaseType;
// Allow users access to the specific type of this delegate.
typedef FastDelegate SelfType;
// Mimic the base class constructors.
FastDelegate() : BaseType() { }
template < class X, class Y >
FastDelegate(Y * pthis,
R (X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5 ))
: BaseType(pthis, function_to_bind) { }
template < class X, class Y >
FastDelegate(const Y *pthis,
R (X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5 ) const)
: BaseType(pthis, function_to_bind)
{ }
FastDelegate(R (*function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5 ))
: BaseType(function_to_bind) { }
void operator = (const BaseType &x) {
*static_cast<BaseType*>(this) = x; }
};
//N=6
// Specialization to allow use of
// FastDelegate< R ( Param1, Param2, Param3, Param4, Param5, Param6 ) >
// instead of
// FastDelegate6 < Param1, Param2, Param3, Param4, Param5, Param6, R >
template<typename R, class Param1, class Param2, class Param3, class Param4, class Param5, class Param6>
class FastDelegate< R ( Param1, Param2, Param3, Param4, Param5, Param6 ) >
// Inherit from FastDelegate6 so that it can be treated just like a FastDelegate6
: public FastDelegate6 < Param1, Param2, Param3, Param4, Param5, Param6, R >
{
public:
// Make using the base type a bit easier via typedef.
typedef FastDelegate6 < Param1, Param2, Param3, Param4, Param5, Param6, R > BaseType;
// Allow users access to the specific type of this delegate.
typedef FastDelegate SelfType;
// Mimic the base class constructors.
FastDelegate() : BaseType() { }
template < class X, class Y >
FastDelegate(Y * pthis,
R (X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6 ))
: BaseType(pthis, function_to_bind) { }
template < class X, class Y >
FastDelegate(const Y *pthis,
R (X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6 ) const)
: BaseType(pthis, function_to_bind)
{ }
FastDelegate(R (*function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6 ))
: BaseType(function_to_bind) { }
void operator = (const BaseType &x) {
*static_cast<BaseType*>(this) = x; }
};
//N=7
// Specialization to allow use of
// FastDelegate< R ( Param1, Param2, Param3, Param4, Param5, Param6, Param7 ) >
// instead of
// FastDelegate7 < Param1, Param2, Param3, Param4, Param5, Param6, Param7, R >
template<typename R, class Param1, class Param2, class Param3, class Param4, class Param5, class Param6, class Param7>
class FastDelegate< R ( Param1, Param2, Param3, Param4, Param5, Param6, Param7 ) >
// Inherit from FastDelegate7 so that it can be treated just like a FastDelegate7
: public FastDelegate7 < Param1, Param2, Param3, Param4, Param5, Param6, Param7, R >
{
public:
// Make using the base type a bit easier via typedef.
typedef FastDelegate7 < Param1, Param2, Param3, Param4, Param5, Param6, Param7, R > BaseType;
// Allow users access to the specific type of this delegate.
typedef FastDelegate SelfType;
// Mimic the base class constructors.
FastDelegate() : BaseType() { }
template < class X, class Y >
FastDelegate(Y * pthis,
R (X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7 ))
: BaseType(pthis, function_to_bind) { }
template < class X, class Y >
FastDelegate(const Y *pthis,
R (X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7 ) const)
: BaseType(pthis, function_to_bind)
{ }
FastDelegate(R (*function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7 ))
: BaseType(function_to_bind) { }
void operator = (const BaseType &x) {
*static_cast<BaseType*>(this) = x; }
};
//N=8
// Specialization to allow use of
// FastDelegate< R ( Param1, Param2, Param3, Param4, Param5, Param6, Param7, Param8 ) >
// instead of
// FastDelegate8 < Param1, Param2, Param3, Param4, Param5, Param6, Param7, Param8, R >
template<typename R, class Param1, class Param2, class Param3, class Param4, class Param5, class Param6, class Param7, class Param8>
class FastDelegate< R ( Param1, Param2, Param3, Param4, Param5, Param6, Param7, Param8 ) >
// Inherit from FastDelegate8 so that it can be treated just like a FastDelegate8
: public FastDelegate8 < Param1, Param2, Param3, Param4, Param5, Param6, Param7, Param8, R >
{
public:
// Make using the base type a bit easier via typedef.
typedef FastDelegate8 < Param1, Param2, Param3, Param4, Param5, Param6, Param7, Param8, R > BaseType;
// Allow users access to the specific type of this delegate.
typedef FastDelegate SelfType;
// Mimic the base class constructors.
FastDelegate() : BaseType() { }
template < class X, class Y >
FastDelegate(Y * pthis,
R (X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8 ))
: BaseType(pthis, function_to_bind) { }
template < class X, class Y >
FastDelegate(const Y *pthis,
R (X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8 ) const)
: BaseType(pthis, function_to_bind)
{ }
FastDelegate(R (*function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8 ))
: BaseType(function_to_bind) { }
void operator = (const BaseType &x) {
*static_cast<BaseType*>(this) = x; }
};
#endif //FASTDELEGATE_ALLOW_FUNCTION_TYPE_SYNTAX
////////////////////////////////////////////////////////////////////////////////
// Fast Delegates, part 5:
//
// MakeDelegate() helper function
//
// MakeDelegate(&x, &X::func) returns a fastdelegate of the type
// necessary for calling x.func() with the correct number of arguments.
// This makes it possible to eliminate many typedefs from user code.
//
////////////////////////////////////////////////////////////////////////////////
// Also declare overloads of a MakeDelegate() global function to
// reduce the need for typedefs.
// We need seperate overloads for const and non-const member functions.
// Also, because of the weird rule about the class of derived member function pointers,
// implicit downcasts may need to be applied later to the 'this' pointer.
// That's why two classes (X and Y) appear in the definitions. Y must be implicitly
// castable to X.
// Workaround for VC6. VC6 needs void return types converted into DefaultVoid.
// GCC 3.2 and later won't compile this unless it's preceded by 'typename',
// but VC6 doesn't allow 'typename' in this context.
// So, I have to use a macro.
#ifdef FASTDLGT_VC6
#define FASTDLGT_RETTYPE detail::VoidToDefaultVoid<RetType>::type
#else
#define FASTDLGT_RETTYPE RetType
#endif
//N=0
template <class X, class Y, class RetType>
FastDelegate0<FASTDLGT_RETTYPE> MakeDelegate(Y* x, RetType (X::*func)()) {
return FastDelegate0<FASTDLGT_RETTYPE>(x, func);
}
template <class X, class Y, class RetType>
FastDelegate0<FASTDLGT_RETTYPE> MakeDelegate(Y* x, RetType (X::*func)() const) {
return FastDelegate0<FASTDLGT_RETTYPE>(x, func);
}
//N=1
template <class X, class Y, class Param1, class RetType>
FastDelegate1<Param1, FASTDLGT_RETTYPE> MakeDelegate(Y* x, RetType (X::*func)(Param1 p1)) {
return FastDelegate1<Param1, FASTDLGT_RETTYPE>(x, func);
}
template <class X, class Y, class Param1, class RetType>
FastDelegate1<Param1, FASTDLGT_RETTYPE> MakeDelegate(Y* x, RetType (X::*func)(Param1 p1) const) {
return FastDelegate1<Param1, FASTDLGT_RETTYPE>(x, func);
}
//N=2
template <class X, class Y, class Param1, class Param2, class RetType>
FastDelegate2<Param1, Param2, FASTDLGT_RETTYPE> MakeDelegate(Y* x, RetType (X::*func)(Param1 p1, Param2 p2)) {
return FastDelegate2<Param1, Param2, FASTDLGT_RETTYPE>(x, func);
}
template <class X, class Y, class Param1, class Param2, class RetType>
FastDelegate2<Param1, Param2, FASTDLGT_RETTYPE> MakeDelegate(Y* x, RetType (X::*func)(Param1 p1, Param2 p2) const) {
return FastDelegate2<Param1, Param2, FASTDLGT_RETTYPE>(x, func);
}
//N=3
template <class X, class Y, class Param1, class Param2, class Param3, class RetType>
FastDelegate3<Param1, Param2, Param3, FASTDLGT_RETTYPE> MakeDelegate(Y* x, RetType (X::*func)(Param1 p1, Param2 p2, Param3 p3)) {
return FastDelegate3<Param1, Param2, Param3, FASTDLGT_RETTYPE>(x, func);
}
template <class X, class Y, class Param1, class Param2, class Param3, class RetType>
FastDelegate3<Param1, Param2, Param3, FASTDLGT_RETTYPE> MakeDelegate(Y* x, RetType (X::*func)(Param1 p1, Param2 p2, Param3 p3) const) {
return FastDelegate3<Param1, Param2, Param3, FASTDLGT_RETTYPE>(x, func);
}
//N=4
template <class X, class Y, class Param1, class Param2, class Param3, class Param4, class RetType>
FastDelegate4<Param1, Param2, Param3, Param4, FASTDLGT_RETTYPE> MakeDelegate(Y* x, RetType (X::*func)(Param1 p1, Param2 p2, Param3 p3, Param4 p4)) {
return FastDelegate4<Param1, Param2, Param3, Param4, FASTDLGT_RETTYPE>(x, func);
}
template <class X, class Y, class Param1, class Param2, class Param3, class Param4, class RetType>
FastDelegate4<Param1, Param2, Param3, Param4, FASTDLGT_RETTYPE> MakeDelegate(Y* x, RetType (X::*func)(Param1 p1, Param2 p2, Param3 p3, Param4 p4) const) {
return FastDelegate4<Param1, Param2, Param3, Param4, FASTDLGT_RETTYPE>(x, func);
}
//N=5
template <class X, class Y, class Param1, class Param2, class Param3, class Param4, class Param5, class RetType>
FastDelegate5<Param1, Param2, Param3, Param4, Param5, FASTDLGT_RETTYPE> MakeDelegate(Y* x, RetType (X::*func)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5)) {
return FastDelegate5<Param1, Param2, Param3, Param4, Param5, FASTDLGT_RETTYPE>(x, func);
}
template <class X, class Y, class Param1, class Param2, class Param3, class Param4, class Param5, class RetType>
FastDelegate5<Param1, Param2, Param3, Param4, Param5, FASTDLGT_RETTYPE> MakeDelegate(Y* x, RetType (X::*func)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5) const) {
return FastDelegate5<Param1, Param2, Param3, Param4, Param5, FASTDLGT_RETTYPE>(x, func);
}
//N=6
template <class X, class Y, class Param1, class Param2, class Param3, class Param4, class Param5, class Param6, class RetType>
FastDelegate6<Param1, Param2, Param3, Param4, Param5, Param6, FASTDLGT_RETTYPE> MakeDelegate(Y* x, RetType (X::*func)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6)) {
return FastDelegate6<Param1, Param2, Param3, Param4, Param5, Param6, FASTDLGT_RETTYPE>(x, func);
}
template <class X, class Y, class Param1, class Param2, class Param3, class Param4, class Param5, class Param6, class RetType>
FastDelegate6<Param1, Param2, Param3, Param4, Param5, Param6, FASTDLGT_RETTYPE> MakeDelegate(Y* x, RetType (X::*func)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6) const) {
return FastDelegate6<Param1, Param2, Param3, Param4, Param5, Param6, FASTDLGT_RETTYPE>(x, func);
}
//N=7
template <class X, class Y, class Param1, class Param2, class Param3, class Param4, class Param5, class Param6, class Param7, class RetType>
FastDelegate7<Param1, Param2, Param3, Param4, Param5, Param6, Param7, FASTDLGT_RETTYPE> MakeDelegate(Y* x, RetType (X::*func)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7)) {
return FastDelegate7<Param1, Param2, Param3, Param4, Param5, Param6, Param7, FASTDLGT_RETTYPE>(x, func);
}
template <class X, class Y, class Param1, class Param2, class Param3, class Param4, class Param5, class Param6, class Param7, class RetType>
FastDelegate7<Param1, Param2, Param3, Param4, Param5, Param6, Param7, FASTDLGT_RETTYPE> MakeDelegate(Y* x, RetType (X::*func)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7) const) {
return FastDelegate7<Param1, Param2, Param3, Param4, Param5, Param6, Param7, FASTDLGT_RETTYPE>(x, func);
}
//N=8
template <class X, class Y, class Param1, class Param2, class Param3, class Param4, class Param5, class Param6, class Param7, class Param8, class RetType>
FastDelegate8<Param1, Param2, Param3, Param4, Param5, Param6, Param7, Param8, FASTDLGT_RETTYPE> MakeDelegate(Y* x, RetType (X::*func)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8)) {
return FastDelegate8<Param1, Param2, Param3, Param4, Param5, Param6, Param7, Param8, FASTDLGT_RETTYPE>(x, func);
}
template <class X, class Y, class Param1, class Param2, class Param3, class Param4, class Param5, class Param6, class Param7, class Param8, class RetType>
FastDelegate8<Param1, Param2, Param3, Param4, Param5, Param6, Param7, Param8, FASTDLGT_RETTYPE> MakeDelegate(Y* x, RetType (X::*func)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8) const) {
return FastDelegate8<Param1, Param2, Param3, Param4, Param5, Param6, Param7, Param8, FASTDLGT_RETTYPE>(x, func);
}
// clean up after ourselves...
#undef FASTDLGT_RETTYPE
} // namespace fastdelegate
#endif // !defined(FASTDELEGATE_H)
| [
"Jeroen.Dierckx@d8a2fbcc-2753-0410-82a0-8bc2cd85795f"
]
| [
[
[
1,
2110
]
]
]
|
be4ea1c16fbd6e7e04102374f5949f3566ddd7d7 | be3d7c318d79cd33d306aba58a1159147cac91fd | /modules/hyperfun/src/mainapp.h | eb640c903eea0f850463ba25f6f5202f687546c5 | []
| no_license | knicos/Cadence | 827149b53bb3e92fe532b0ad4234b7d0de11ca43 | 7e1e1cf1bae664f77afce63407b61c7b2b0a4fff | refs/heads/master | 2020-05-29T13:19:07.595099 | 2011-10-31T13:05:48 | 2011-10-31T13:05:48 | 1,238,039 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,076 | h | /*==============================================================================
Copyright 1999 Eric Fausett
Copyright 2003-2004 Pierre-Alain Fayolle, Benjamin Schmitt
This Work or file is part of the greater total Work, software or group of
files named HyperFun Polygonizer.
HyperFun Polygonizer can be redistributed and/or modified under the terms
of the CGPL, The Common Good Public License as published by and at CGPL.org
(http://CGPL.org). It is released under version 1.0 Beta of the License
until the 1.0 version is released after which either version 1.0 of the
License, or (at your option) any later version can be applied.
THIS WORK, OR SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED (See the
CGPL, The Common Good Public License for more information.)
You should have received a copy of the CGPL along with HyperFun Polygonizer;
if not, see - http://CGPL.org to get a copy of the License.
==============================================================================*/
// MainApp.h: interface for the CMainApp class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(MAINAPP_H)
#define MAINAPP_H
#pragma warning( disable : 4786 )
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
#include <iostream>
#include <fstream>
#ifdef WIN32
#include <windows.h>
#endif
#include <GL/gl.h>
#include <GL/glu.h>
#include "hftimer.h"
#include "hfpcommandline.h"
#include "hfpolymesh.h"
//DUAL_CONTOURING
#include "hfdc_dcgenerator.h"
#define MAX_FILE_SIZE 100000
#define PI 3.14159265
extern void SetMaterial(GLfloat *color);
class CMainApp
{
public:
CMainApp(int & argc, char ** argv);
virtual ~CMainApp();
int init ();
void createObject(double **** triangle,double **** normal);
void createGLTriangle(bool bNormal, bool bVertexNormal, bool bAttributes);
void CreateNormal();
double GetVertexFromTriangle(int,int,int);
double GetNormalFromTriangle(int,int,int);
double GetAttrFromTriangle(int,int,int);
bool getAttribute();
void getViewPos(double pos[],double look[]);
int getAttributes(double **** color);
int getNormalSegments(double ***);
int getFaceLineFill();
int getNormal();
int getNormalDisplay();
int getLightType();
int getFlat();
int getWindowSizeX();
int getWindowSizeY();
int getWireAndSurface();
void getFaceColor(float *);
void getLineColor(float *);
void getBoundingBox(float *,float *);
private:
void readFile();
void parseString();
void generateTriangles();
void vrmlOut();
void stlOut();
void stlBinaryOut();
void povrayMeshOut();
HFPCommandLine itsCL;
HFTimer itsTimer;
std::string itsString;
HFInterpreter itsInterpreter;
HFPolyMesh* itsPolyMesh_;
double Pos_[3];
double Look_[3];
float Min_[3];
float Max_[3];
};
#endif // !defined(MAINAPP_H)
| [
"nick@viglab-14.(none)"
]
| [
[
[
1,
127
]
]
]
|
8054ca986875f8f46c5bfa726e70fd2136e0bcad | 36bf908bb8423598bda91bd63c4bcbc02db67a9d | /Include/CShellFileOp.h | 5b25384fbd6e4fbc85dec267b51a74363ff03401 | []
| no_license | code4bones/crawlpaper | edbae18a8b099814a1eed5453607a2d66142b496 | f218be1947a9791b2438b438362bc66c0a505f99 | refs/heads/master | 2021-01-10T13:11:23.176481 | 2011-04-14T11:04:17 | 2011-04-14T11:04:17 | 44,686,513 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,034 | h | // ShellFileOp.h: interface for the CShellFileOp class.
//
// Tim Johnson [email protected]
// Written : July 1998
//
// Copyright 1998
//
//////////////////////////////////////////////////////////////////////
#ifndef _SHELLFILEOP_H
#define _SHELLFILEOP_H 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "strcpyn.h"
#include "window.h"
//constats for use in iSrcDest arguements
const int SH_SRC_FILE = 0;
const int SH_DEST_FILE = 1;
class CShellFileOp
{
public:
//
//simple constructor
//
CShellFileOp();
//
//complex constructor - performs the operation straight away
//
CShellFileOp( const HWND phWnd,
const UINT wFunc,
LPCSTR sFrom,
LPCSTR sTo,
const FILEOP_FLAGS fFlags,
LPCSTR sProgressTitle);
//
//destructor
//
virtual ~CShellFileOp();
public: //operations
//
// Function to perform copy operation
//
long CopyFiles();
//
// Function to perform delete operation
//
long DeleteFiles();
//
// Function to perform move operation
//
long MoveFiles();
//
// Function to perform rename operation
//
long RenameFiles();
//
// Adds another filename to the end of the current string
//
void AddFile(const int iSrcDest, LPCSTR sFile);
//
// Clears a list of files
//
void ClearFiles(const int iSrcDest);
//
// Function to pre-allocate string memory to prevent
// lots of re-allocations
//
void SetMaxCount(const int iSrcDest, const long lMax);
//
// Function to set the dialog title
// sTitle is a string to be used
// nTitle is a resource ID to get the string from
void SetTitle(LPCSTR sTitle);
void SetTitle(const int nTitle);
//
// Function to set the parent HWND of the dialog
//
void SetParent(const HWND phWnd);
//
// Function to get Abort flag
//
BOOL AnyOperationsAborted() const;
//
// Functions to get/set the operation flags
//
// Flags that control the file operation. This member can be a combination of the
// following values:
//
// FOF_ALLOWUNDO Preserves undo information, if possible.
//
// FOF_CONFIRMMOUSE Not implemented.
//
// FOF_FILESONLY Performs the operation only on files if a wildcard
// filename (*.*) is specified.
//
// FOF_MULTIDESTFILES Indicates that the pTo member specifies multiple destination
// files (one for each source file) rather than one directory
// where all source files are to be deposited.
//
// FOF_NOCONFIRMATION Responds with "yes to all" for any dialog box that is
// displayed.
//
// FOF_NOCONFIRMMKDIR Does not confirm the creation of a new directory if the
// operation requires one to be created.
//
// FOF_RENAMEONCOLLISION Gives the file being operated on a new name (such as
// "Copy #1 of...") in a move, copy, or rename operation if a
// file of the target name already exists.
//
// FOF_SILENT Does not display a progress dialog box.
//
// FOF_SIMPLEPROGRESS Displays a progress dialog box, but does not show the
// filenames.
FILEOP_FLAGS GetFlags() const;
void SetFlags(const FILEOP_FLAGS fNewFlags);
private: //operations
// function to grab some string space memory
void GrabMem(const int iSrcDest, const long lNum);
private: //attributes
//max no. char in source string
long m_lMaxSrcCount;
//max no. char in dest string
long m_lMaxDestCount;
//current no. char in source string
long m_lCurSrcCount;
//current no. char in dest string
long m_lCurDestCount;
//structure for shell call
SHFILEOPSTRUCT m_FileOp;
//pointer to start of source string
char * m_pTo;
//pointer to start of dest string
char * m_pFrom;
//current pointer in source string
char * m_pSrc;
//current pointer in dest string
char * m_pDest;
//title to be used on dialog
char * m_pTitle;
};
#endif // _SHELLFILEOP_H
| [
"[email protected]"
]
| [
[
[
1,
174
]
]
]
|
9252e0be72a44aa5884d5bf42e0c527da643bd5f | b84a38aad619acf34c22ed6e6caa0f7b00ebfa0a | /Code/TootleFilesys/TFilePng.cpp | 657b7db9376ea1d7cddfb3fa82a74c955aa1992a | []
| no_license | SoylentGraham/Tootle | 4ae4e8352f3e778e3743e9167e9b59664d83b9cb | 17002da0936a7af1f9b8d1699d6f3e41bab05137 | refs/heads/master | 2021-01-24T22:44:04.484538 | 2010-11-03T22:53:17 | 2010-11-03T22:53:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,433 | cpp | #include "TFilePng.h"
#include <TootleAsset/TTexture.h>
namespace libpng
{
#include <libpng/png.h>
}
namespace TLFilePng
{
void ReadData(libpng::png_structp png_ptr,libpng::png_bytep data, libpng::png_size_t length);
void OnReadRow(libpng::png_structp png_ptr,libpng::png_uint_32 row,int pass);
// wrappers for the PNG reading as it's stupid long jump system won't allow us to use returns properly
void PngReadHeader(libpng::png_structp png_ptr,libpng::png_infop info_ptr,Bool& Success);
void PngReadImage(libpng::png_structp png_ptr,TArray<u8*>& RowData,Bool& Success);
void PngReadEnd(libpng::png_structp png_ptr,Bool& Success);
void AllocRowData(TArray<u8*>& RowData,libpng::png_infop info_ptr,u32& RowDataSize,u32& TotalDataSize);
void DeleteRowData(TArray<u8*>& RowData);
}
void TLFilePng::AllocRowData(TArray<u8*>& RowData,libpng::png_infop info_ptr,u32& RowDataSize,u32& TotalDataSize)
{
RowDataSize = info_ptr->rowbytes;
// RowDataSize = info_ptr->width * info_ptr->channels;
TotalDataSize = 0;
// alloc rows of data
for ( u32 y=0; y<info_ptr->height; y++ )
{
RowData.Add( new u8[RowDataSize] );
// count data
TotalDataSize += RowDataSize;
}
}
void TLFilePng::DeleteRowData(TArray<u8*>& RowData)
{
for ( u32 i=0; i<RowData.GetSize(); i++ )
TLMemory::DeleteArray( RowData[i] );
RowData.Empty();
}
//-------------------------------------------------------
// read header info
//-------------------------------------------------------
void TLFilePng::PngReadHeader(libpng::png_structp png_ptr,libpng::png_infop info_ptr,Bool& Success)
{
if (libpng::setjmp(png_jmpbuf(png_ptr)))
return;
libpng::png_read_info(png_ptr, info_ptr);
// if we got here and the longjump shit didnt get used, the set success to true
Success = TRUE;
}
//-------------------------------------------------------
// read image data
//-------------------------------------------------------
void TLFilePng::PngReadImage(libpng::png_structp png_ptr,TArray<u8*>& RowData,Bool& Success)
{
if (libpng::setjmp(png_jmpbuf(png_ptr)))
return;
libpng::png_read_image(png_ptr, RowData.GetData() );
// if we got here and the longjump shit didnt get used, the set success to true
Success = TRUE;
}
//-------------------------------------------------------
// read end of file
//-------------------------------------------------------
void TLFilePng::PngReadEnd(libpng::png_structp png_ptr,Bool& Success)
{
if (libpng::setjmp(png_jmpbuf(png_ptr)))
return;
libpng::png_read_end(png_ptr, NULL );
// if we got here and the longjump shit didnt get used, the set success to true
Success = TRUE;
}
void TLFilePng::ReadData(libpng::png_structp png_ptr,libpng::png_bytep data, libpng::png_size_t length)
{
/*
// error
if (libpng::setjmp(png_jmpbuf(png_ptr)))
{
TLDebug_Break("errrrr");
}
*/
// get pointer back to our object
TLFileSys::TFilePng* pFilePng = (TLFileSys::TFilePng*)png_ptr->io_ptr;
// read X bytes of data out of the file
pFilePng->GetData().ReadData( data, length );
}
void TLFilePng::OnReadRow(libpng::png_structp png_ptr,libpng::png_uint_32 row,int pass)
{
/*
// error
if (libpng::setjmp(png_jmpbuf(png_ptr)))
{
TLDebug_Break("errrrr");
}
*/
TLDebug_Break("todo");
}
//---------------------------------------------------------
//
//---------------------------------------------------------
TLFileSys::TFilePng::TFilePng(TRefRef FileRef,TRefRef FileTypeRef) :
TFile ( FileRef, FileTypeRef )
{
}
//--------------------------------------------------------------
// parse PNG file and turn it into a texture asset
//--------------------------------------------------------------
SyncBool TLFileSys::TFilePng::ExportAsset(TPtr<TLAsset::TAsset>& pAsset,TRefRef ExportAssetType)
{
if ( pAsset )
{
TLDebug_Break("Async export not supported yet. asset should be NULL");
return SyncFalse;
}
// check first 8 bytes for validity
TFixedArray<u8,8> Header(8,0);
// gr: use the TBinary functions to move the read pos along
GetData().ResetReadPos();
GetData().ReadData( Header.GetData(), Header.GetSize() );
// png header check
Bool HeaderValid = libpng::png_sig_cmp( Header.GetData(), 0, Header.GetSize() ) == 0;
if ( !HeaderValid )
{
TLDebug_Break("png has invalid header - not a png?");
return SyncFalse;
}
// alloc some internal structures needed for processing - no custom error/warning handlers
libpng::png_structp png_ptr = libpng::png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL );
libpng::png_infop info_ptr = png_ptr ? libpng::png_create_info_struct(png_ptr) : NULL;
libpng::png_infop end_info = png_ptr ? libpng::png_create_info_struct(png_ptr) : NULL;
if ( !png_ptr || !info_ptr || !end_info )
{
TLDebug_Break("error allocating libpng structs");
libpng::png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
return SyncFalse;
}
// use our own i/o functions to read from our binary data
png_set_read_fn( png_ptr, this, &TLFilePng::ReadData );
if (libpng::setjmp(png_jmpbuf(png_ptr)))
{
TLDebug_Break("Error setting libpng jump");
libpng::png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
return SyncFalse;
}
// already read header so tell libpng how much we've read
png_set_sig_bytes(png_ptr, Header.GetSize() );
// wrapper for the PNG reading as it's stupid long jump system won't allow us to use returns properly
Bool ReadSuccess = FALSE;
TLFilePng::PngReadHeader( png_ptr, info_ptr, ReadSuccess );
if ( !ReadSuccess )
{
TLDebug_Break("error reading PNG header");
libpng::png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
return SyncFalse;
}
if (libpng::setjmp(png_jmpbuf(png_ptr)))
{
TLDebug_Break("Error setting libpng jump");
libpng::png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
return SyncFalse;
}
// palette -> rgb
if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
png_set_palette_to_rgb(png_ptr);
// less than 8 bit grey scale -> rgb
if (info_ptr->color_type == PNG_COLOR_TYPE_GRAY && info_ptr->bit_depth < 8)
png_set_gray_1_2_4_to_8(png_ptr);
// something about alpha channel
// if (png_get_valid(png_ptr, info_ptr,PNG_INFO_tRNS))
// png_set_tRNS_to_alpha(png_ptr);
// dont combine alpha with main image
// if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
// png_set_strip_alpha(png_ptr);
// expand small bit depths to 8bit
if (info_ptr->bit_depth < 8)
png_set_packing(png_ptr);
// reduce 16 bit colours to 8bit
if (info_ptr->bit_depth == 16)
png_set_strip_16(png_ptr);
// grey scale -> rgb
if (info_ptr->color_type == PNG_COLOR_TYPE_GRAY || info_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
png_set_gray_to_rgb(png_ptr);
// endian swap
//if (bit_depth == 16)
// png_set_swap(png_ptr);
// create new texture asset
TPtr<TLAsset::TTexture> pTexture = new TLAsset::TTexture( GetFileRef() );
if ( !pTexture )
{
TLDebug_Break("failed to alloc texture asset");
libpng::png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
return SyncFalse;
}
// check to see if it has an alpha channel or not
Bool HasAlphaChannel = (info_ptr->color_type & PNG_COLOR_MASK_ALPHA) != 0x0;
// setup texture
u16 width = (u16)info_ptr->width;
u16 height = (u16)info_ptr->height;
if ( !pTexture->SetSize( Type2<u16>( width, height ), HasAlphaChannel ) )
{
TLDebug_Break("failed to set texture size - non-square?");
libpng::png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
return SyncFalse;
}
// alloc data for image
TPointerArray<u8> RowData;
u32 RowDataSize = 0;
u32 TotalDataSize = 0;
TLFilePng::AllocRowData( RowData, info_ptr, RowDataSize, TotalDataSize );
// assume sizes should match...
if ( TotalDataSize != pTexture->GetPixelData().GetSize() )
{
if ( !TLDebug_Break("expected data sizes to match...") )
{
libpng::png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
return SyncFalse;
}
}
ReadSuccess = FALSE;
TLFilePng::PngReadImage( png_ptr, RowData, ReadSuccess );
if ( !ReadSuccess )
{
TLDebug_Break("error reading PNG image data");
TLFilePng::DeleteRowData( RowData );
libpng::png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
return SyncFalse;
}
ReadSuccess = FALSE;
TLFilePng::PngReadEnd(png_ptr, ReadSuccess );
if ( !ReadSuccess )
{
TLDebug_Break("error reading PNG end data");
TLFilePng::DeleteRowData( RowData );
libpng::png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
return SyncFalse;
}
// put row data into our texture data
TArray<u8>& PixelDataArray = pTexture->GetPixelData().GetDataArray();
PixelDataArray.SetSize(0);
pTexture->GetPixelData().GetDataArray().SetSize(0);
for ( u32 r=0; r<RowData.GetSize(); r++ )
{
// add data to texture data
PixelDataArray.Add( RowData[r], RowDataSize );
}
// assign texture to the output asset ptr to complete export
pTexture->SetLoadingState( TLAsset::LoadingState_Loaded );
pAsset = pTexture;
// cleanup
TLFilePng::DeleteRowData( RowData );
libpng::png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
return SyncTrue;
}
| [
"[email protected]"
]
| [
[
[
1,
318
]
]
]
|
51b12bfd1c11cf30e7a5e9a7363e452ebeb32bbc | 1cf1543cd5460621f530f730a4f3969cfa74197c | /Scanner.h | 6f631ad6f692fbc463ee2ad52820dd321625240c | []
| no_license | derpepe/sysprog | 042048d0c8f30fb26f0fb79a024530f67a852ca9 | 2fa6fb3b7c7f53b3fa8ff6aeb74d8d3e3331ba61 | refs/heads/master | 2021-01-18T14:01:45.742680 | 2010-02-23T22:23:25 | 2010-02-23T22:23:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 801 | h | #pragma once
#include <sstream>
#include "Buffer.h"
#include "Const.h"
#include "Token.h"
#include "SymTable.h"
#include "SymTableEntry.h"
class Scanner
{
public:
SymTable *mySymTable;
Scanner(char *inputFile, char *outputFile);
Token *nextToken();
void freeToken(Token);
void processFile();
private:
Buffer *myBuffer;
stateType currentState;
char tokenSoFar[SCANNER_INTERNAL_BUFFER_SIZE];
int internal_token_start;
int internal_pos;
int internal_filled_pos;
int column;
int line;
int startColumn;
int startLine;
std::string intToState(int state);
bool isPossibleEnding(int state);
stateType Automat(int state, char nextChar); // returns nextState
classType classOf(char theChar);
Token *doStep();
};
| [
"[email protected]"
]
| [
[
[
1,
43
]
]
]
|
85898419d28402ce9be853d6f9b2a2bcbf6e5321 | 4fdc157f7d6c5af784c3492909d848a0371e5877 | /code source/robot/Data.cpp | 287b6afec16d5262fc36c01a0c0624e4c7a3a92a | []
| no_license | moumen19/robotiquecartemere | d969e50aedc53844bb7c512ff15e6812b8b469de | 8333bb0b5c1b1396e1e99a870af2f60c9db149b0 | refs/heads/master | 2020-12-24T17:17:14.273869 | 2011-02-11T15:44:38 | 2011-02-11T15:44:38 | 34,446,411 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,707 | cpp | /*
*
* Bureau d'étude Robotique M2 ISEN 2010-2011
*
* DELBERGUE Julien
* JACQUEL Olivier
* PIETTE Ferdinand ([email protected])
*
* Fichier Data.cpp
*
*/
#include "Data.hpp"
/**
* Constructeur
*/
Data::Data()
{
_DEBUG("Initialisation du module de stockage de donnees", INFORMATION);
}
/**
* Destructeur
*/
Data::~Data()
{
_DEBUG("Destruction du module stockage de donnees", INFORMATION);
}
/**
* Recupere une donnee stockee
* @param nb - indice de la donnee (indice capteur par exemple)
* @param place - place de la donnee
* @param in - indice negatif si la place = LAST. Compte à partir de la fin de la liste
* @return La donnee telle qu'elle a ete stocke (a caster comme il se doit)
*/
boost::any Data::get(int nb, DataOption::Place place, int in)
{
if(place == DataOption::FIRST)
return this->get(nb, 0);
else
return this->get(nb, this->a_data[nb].size()-1-in);
}
/**
* Recupere une donnee stockee
* @param nb - indice de la donnee (indice capteur par exemple)
* @param index - numero de la donnee
* @return La donnee telle qu'elle a ete stocke (a caster comme il se doit)
*/
boost::any Data::get(int nb, int index)
{
if(this->a_data[nb].size() < (unsigned int)index+1 || index < 0)
throw std::out_of_range("ERREUR : Aucune donnée stocke...");
return this->a_data[nb][index];
}
/**
* Ajout en memoire d'une donnee
* @param nb - indice de la donnee (indice capteur par exemple)
* @param value - donnee a stocke
*/
void Data::set(int nb, boost::any value)
{
this->a_data[nb].push_back(value);
//_DEBUG("Ajout d'une donnee au module de stockage de donnees", INFORMATION);
}
| [
"ferdinand.piette@308fe9b9-b635-520e-12eb-2ef3f824b1b6",
"piette.ferdinand@308fe9b9-b635-520e-12eb-2ef3f824b1b6"
]
| [
[
[
1,
12
],
[
15,
17
],
[
20,
20
],
[
23,
25
],
[
28,
28
],
[
31,
38
],
[
40,
43
],
[
46,
51
],
[
54,
57
],
[
60,
64
],
[
67,
68
],
[
70,
70
]
],
[
[
13,
14
],
[
18,
19
],
[
21,
22
],
[
26,
27
],
[
29,
30
],
[
39,
39
],
[
44,
45
],
[
52,
53
],
[
58,
59
],
[
65,
66
],
[
69,
69
]
]
]
|
f8165bb3491e6b4d09e91a187c3cf97dca3e9984 | ddc9569f4950c83f98000a01dff485aa8fa67920 | /naikai/windowing/src/win32/nkMenu.h | fd74ea86d4e370b64188e7b6e011182d73449b25 | []
| no_license | chadaustin/naikai | 0a291ddabe725504cdd80c6e2c7ccb85dc5109da | 83b590b049a7e8a62faca2b0ca1d7d33e2013301 | refs/heads/master | 2021-01-10T13:28:48.743787 | 2003-02-19T19:56:24 | 2003-02-19T19:56:24 | 36,420,940 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 702 | h | #ifndef NK_MENU_H
#define NK_MENU_H
#include <utility>
#include <vector>
#include <windows.h>
#include "nkIPrivateMenu.h"
class nkICommand;
class nkWindowingService;
class nkWindow;
class nkMenu : public nkIPrivateMenu
{
private:
nkMenu(HMENU menu);
~nkMenu();
public:
NS_DECL_ISUPPORTS
NS_DECL_NKIMENU
NS_IMETHOD GetMenuHandle(HMENU& menu);
NS_IMETHOD Attach(nkWindow* window);
NS_IMETHOD Detach(nkWindow* window);
private:
bool m_packed;
HMENU m_menu;
std::vector<nkIPrivateMenu*> m_sub_menus;
std::vector<std::pair<int, nkICommand*> > m_menu_items;
friend nkWindowingService;
friend nkWindow;
};
#endif
| [
"aegis@ed5ae262-7be1-47e3-824f-6ab8bb33c1ce"
]
| [
[
[
1,
43
]
]
]
|
eb9566352c1cfae4770d1c538e7f36b6dd0d2d10 | 9df4b47eb2d37fd7f08b8e723e17f733fd21c92b | /plugintemplate/libs/lib_linuxutils.cpp | c3e2b8247fb2a02368a7b3881862835a3f9f39e3 | []
| no_license | sn4k3/sourcesdk-plugintemplate | d5a806f8793ad328b21cf8e7af81903c98b07143 | d89166b79a92b710d275c817be2fb723f6be64b5 | refs/heads/master | 2020-04-09T07:11:55.754168 | 2011-01-23T22:58:09 | 2011-01-23T22:58:09 | 32,112,282 | 1 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 11,903 | cpp | //========= Copyright © 2010-2011, Tiago Conceição, All rights reserved. ============
// Plugin Template
//
// Please Read (LICENSE.txt) and (README.txt)
// Dont Forget Visit:
// (http://www.sourceplugins.com) -> VPS Plugins
// (http://www.sourcemm.net) (http://forums.alliedmods.net/forumdisplay.php?f=52) - MMS Plugins
//
//===================================================================================
//
// Mani Admin Plugin
//
// Copyright (c) 2010 Giles Millward (Mani). All rights reserved.
//
// This file is part of ManiAdminPlugin.
//
// Mani Admin Plugin 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.
//
// Mani Admin Plugin 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 Mani Admin Plugin. If not, see <http://www.gnu.org/licenses/>.
//
#if !defined ( WIN32 )
/*#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <elf.h>
#include <fcntl.h>
#include <link.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dlfcn.h>
#include <demangle.h>*/
#define NO_INCLUDE_LIBRARIES
#include "includes/default.h"
#include "serverplugin/serverplugin_engine.h"
#include "lib_linuxutils.h"
static int sort_by_address ( const void *m1, const void *m2);
static int sort_by_mangled ( const void *m1, const void *m2);
static int sort_by_demangled ( const void *m1, const void *m2);
char linux_game_bin[256];
char linux_engine_bin[256];
static int sort_by_address ( const void *m1, const void *m2)
{
return ((long) (*(symbol_t *) m1).ptr - (long) (*(symbol_t *) m2).ptr);
}
static int sort_by_mangled ( const void *m1, const void *m2)
{
return strcmp((*(symbol_t *) m1).mangled_name, (*(symbol_t *) m2).mangled_name);
}
static int sort_by_demangled ( const void *m1, const void *m2)
{
return strcmp((*(symbol_t *) m1).demangled_name, (*(symbol_t *) m2).demangled_name);
}
// Used when the path is outside the VALVe game system.
bool UTIL_ScanFile ( char *path, char *text ) {
char buffer[2048];
bool found = false;
FILE *file = fopen(path, "rt");
if (!file) return false;
while (!feof(file)) {
fgets(buffer, sizeof(buffer)-1, file);
if ( strstr( buffer, text ) ) {
found = true;
break;
}
}
fclose(file);
return ( found );
}
LIB_LINUXUTILS_CLASS::LIB_LINUXUTILS_CLASS()
{
symbol_list_size = 0;
addr_list = mangled_list = demangled_list = NULL;
}
LIB_LINUXUTILS_CLASS::~LIB_LINUXUTILS_CLASS()
{
// Free up any lists
FreeSymbols();
}
void LIB_LINUXUTILS_CLASS::GetLinuxBins(char *game, char *engine)
{
//link_map *map;
pid_t pid = getpid();
char file[255];
snprintf(file, sizeof(file)-1, "/proc/%d/maps", pid);
char gamedir[256];
LIB_STRING_CLASS::UTIL_GetGamePath ( gamedir );
#if SOURCE_ENGINE <= SE_DARKMESSIAH
if ( UTIL_ScanFile ( file, "engine_i686.so" ) )
Q_strncpy ( engine, "./bin/engine_i686.so", 256 );
else if ( UTIL_ScanFile ( file, "engine_i486.so" ) )
Q_strncpy ( engine, "./bin/engine_i486.so", 256 );
else
Q_strncpy ( engine, "./bin/engine_amd.so", 256 );
Q_snprintf ( game, 256, "./%s/bin/server_i486.so", gamedir );
#else
Q_strncpy ( engine, "./bin/engine.so", 256 );
Q_snprintf ( game, 256, "./%s/bin/server.so", gamedir );
#endif
}
void LIB_LINUXUTILS_CLASS::GetLinuxBins()
{
GetLinuxBins(linux_game_bin, linux_engine_bin);
}
bool LIB_LINUXUTILS_CLASS::GetLib(const char *lib_name)
{
void *handle;
FreeSymbols();
handle = dlopen(lib_name, RTLD_NOW);
if (handle == NULL)
{
return false;
}
// Borrowed from SourceMod. Hidden symbols SUCK!!!!
// core/MemoryUtils.cpp
// void *MemoryUtils::ResolveSymbol(void *handle, const char *symbol)
int dlfile;
struct link_map *dlmap;
struct stat dlstat;
Elf32_Ehdr *file_hdr;
uintptr_t map_base;
Elf32_Shdr *sections, *shstrtab_hdr, *symtab_hdr, *strtab_hdr;
Elf32_Sym *symtab;
uint16_t section_count;
const char *shstrtab, *strtab;
uint32_t symbol_count;
bool free_string = true;
symtab_hdr = NULL;
strtab_hdr = NULL;
dlmap = (struct link_map *)handle;
dlfile = open(dlmap->l_name, O_RDONLY);
if (dlfile == -1 || fstat(dlfile, &dlstat) == -1)
{
close(dlfile);
return false;
}
/* Map library file into memory */
file_hdr = (Elf32_Ehdr *)mmap(NULL, dlstat.st_size, PROT_READ, MAP_PRIVATE, dlfile, 0);
map_base = (uintptr_t)file_hdr;
if (file_hdr == MAP_FAILED)
{
close(dlfile);
return false;
}
close(dlfile);
if (file_hdr->e_shoff == 0 || file_hdr->e_shstrndx == SHN_UNDEF)
{
munmap(file_hdr, dlstat.st_size);
return false;
}
sections = (Elf32_Shdr *)(map_base + file_hdr->e_shoff);
section_count = file_hdr->e_shnum;
/* Get ELF section header string table */
shstrtab_hdr = §ions[file_hdr->e_shstrndx];
shstrtab = (const char *)(map_base + shstrtab_hdr->sh_offset);
/* Iterate sections while looking for ELF symbol table and string table */
for (uint16_t i = 0; i < section_count; i++)
{
Elf32_Shdr &hdr = sections[i];
const char *section_name = shstrtab + hdr.sh_name;
if (strcmp(section_name, ".symtab") == 0)
{
symtab_hdr = &hdr;
}
else if (strcmp(section_name, ".strtab") == 0)
{
strtab_hdr = &hdr;
}
}
/* Uh oh, we don't have a symbol table or a string table */
if (symtab_hdr == NULL || strtab_hdr == NULL)
{
munmap(file_hdr, dlstat.st_size);
return false;
}
symtab = (Elf32_Sym *)(map_base + symtab_hdr->sh_offset);
strtab = (const char *)(map_base + strtab_hdr->sh_offset);
symbol_count = symtab_hdr->sh_size / symtab_hdr->sh_entsize;
for (uint32_t i = 0; i < symbol_count; i++)
{
Elf32_Sym &sym = symtab[i];
unsigned char sym_type = ELF32_ST_TYPE(sym.st_info);
const char *sym_name = strtab + sym.st_name;
// Skip symbols that are undefined or do not refer to functions or objects
if (sym.st_shndx == SHN_UNDEF || (sym_type != STT_FUNC && sym_type != STT_OBJECT))
{
continue;
}
char *demangled_name = cplus_demangle(sym_name, DMGL_PARAMS);
if (demangled_name == NULL)
{
free_string = false;
demangled_name = (char *) sym_name;
}
AddToList((void **) &addr_list, sizeof(symbol_t), &symbol_list_size);
addr_list[symbol_list_size - 1].ptr = (void *)(dlmap->l_addr + sym.st_value);
addr_list[symbol_list_size - 1].mangled_name = (char *) malloc(strlen(sym_name) + 1);
strcpy(addr_list[symbol_list_size - 1].mangled_name, sym_name);
addr_list[symbol_list_size - 1].demangled_name = (char *) malloc(strlen(demangled_name) + 1);
strcpy(addr_list[symbol_list_size - 1].demangled_name, demangled_name);
if (free_string)
{
free(demangled_name);
}
free_string = true;
}
munmap(file_hdr, dlstat.st_size);
// Populate sub lists and sort */
if (symbol_list_size != 0)
{
mangled_list = (symbol_t *)malloc(sizeof(symbol_t) * symbol_list_size);
demangled_list = (symbol_t *)malloc(sizeof(symbol_t) * symbol_list_size);
for (int i = 0; i < symbol_list_size; i++)
{
mangled_list[i].ptr = addr_list[i].ptr;
mangled_list[i].mangled_name = addr_list[i].mangled_name;
mangled_list[i].demangled_name = addr_list[i].demangled_name;
demangled_list[i].ptr = addr_list[i].ptr;
demangled_list[i].mangled_name = addr_list[i].mangled_name;
demangled_list[i].demangled_name = addr_list[i].demangled_name;
}
qsort(addr_list, symbol_list_size, sizeof(symbol_t), sort_by_address);
qsort(mangled_list, symbol_list_size, sizeof(symbol_t), sort_by_mangled);
qsort(demangled_list, symbol_list_size, sizeof(symbol_t), sort_by_demangled);
}
return true;
}
symbol_t *LIB_LINUXUTILS_CLASS::GetAddr(void *ptr)
{
symbol_t *symbol_ptr = NULL;
symbol_t search_term;
search_term.ptr = ptr;
symbol_ptr = (symbol_t *) bsearch (&search_term,
addr_list, symbol_list_size,
sizeof(symbol_t),
sort_by_address);
return symbol_ptr;
}
symbol_t *LIB_LINUXUTILS_CLASS::GetAddr(int index)
{
return &(addr_list[index]);
}
symbol_t *LIB_LINUXUTILS_CLASS::GetMangled(char *mangled_name)
{
symbol_t *symbol_ptr = NULL;
symbol_t search_term;
search_term.mangled_name = mangled_name;
symbol_ptr = (symbol_t *) bsearch (&search_term,
mangled_list, symbol_list_size,
sizeof(symbol_t),
sort_by_mangled);
return symbol_ptr;
}
symbol_t *LIB_LINUXUTILS_CLASS::GetMangled(int index)
{
return &(mangled_list[index]);
}
symbol_t *LIB_LINUXUTILS_CLASS::GetDeMangled(char *demangled_name)
{
symbol_t *symbol_ptr = NULL;
symbol_t search_term;
search_term.demangled_name = demangled_name;
symbol_ptr = (symbol_t *) bsearch (&search_term,
demangled_list, symbol_list_size,
sizeof(symbol_t),
sort_by_demangled);
return symbol_ptr;
}
symbol_t *LIB_LINUXUTILS_CLASS::GetDeMangled(int index)
{
return &(demangled_list[index]);
}
// Replacement helper function for the old FindAddress function from mani_sigscan.cpp
// This supports both mangled and non-mangled names being passed in
void *LIB_LINUXUTILS_CLASS::FindAddress(char *name_ptr)
{
// See if we can match against a mangled c++ symbol
symbol_t *ptr = this->GetMangled(name_ptr);
if (ptr == NULL)
{
// Nothing found so a demangled name may have been passed in
ptr = this->GetDeMangled(name_ptr);
if (ptr == NULL)
{
// Still can't find it so bail out
return NULL;
}
}
return ptr->ptr;
}
void LIB_LINUXUTILS_CLASS::FreeSymbols()
{
for (int i = 0; i < symbol_list_size; i++)
{
if (addr_list[i].mangled_name)
{
free(addr_list[i].mangled_name);
}
if (addr_list[i].demangled_name)
{
free(addr_list[i].demangled_name);
}
}
if (addr_list)
{
free(addr_list);
free(mangled_list);
free(demangled_list);
addr_list = NULL;
mangled_list = NULL;
demangled_list = NULL;
symbol_list_size = 0;
}
}
#endif
| [
"[email protected]@2dd402b7-31f5-573d-f87e-a7bc63fa017b"
]
| [
[
[
1,
390
]
]
]
|
29b46820e4faed77111354d73d19f2b9426eb536 | 68127d36b179fd5548a1e593e2c20791db6b48e3 | /cppBuilder/compilador/Unit1.~cpp | 01b7de76cad8f30e10fb61db3ddd90bf6962eab4 | []
| no_license | renatomb/engComp | fa50b962dbdf4f9387fd02a28b3dc130b683ed02 | b533c876b50427d44cfdb92c507a6e74b1b7fa79 | refs/heads/master | 2020-04-11T06:22:05.209022 | 2006-04-26T13:40:08 | 2018-12-13T04:25:08 | 161,578,821 | 1 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 7,315 | //---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::botao_abrirClick(TObject *Sender)
{
if (abrir->Execute()){
editor->Lines->LoadFromFile(abrir->FileName);
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::botao_salvarClick(TObject *Sender)
{
if (salvar->Execute()) {
editor->Lines->SaveToFile(salvar->FileName);
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::botao_processarClick(TObject *Sender)
{
botao_processar->Enabled=false;
botao_processar->Caption="Processando...";
limpa_arquivo();
for(int i=0;i<editor->Lines->Count;i++) {
AnsiString palavra;
int tam_linha, pos_ult_palavra=-1,j;
bool flag_string=false, flag_operador=false,flag_palavra=false;
tam_linha=editor->Lines->Strings[i].Length();
for (j=1;j<=tam_linha;j++){
int letra=editor->Lines->Strings[i][j];
if (!flag_string && !flag_operador && !flag_palavra) {
if (((letra >= 65) && (letra <= 90)) || ((letra >= 97) && (letra <= 122)) || ((letra >= 48) && (letra <= 57))) {
flag_palavra=true;
}
if (letra == 34) {
flag_string=true;
}
if (letra == 42 || letra == 43 || letra == 45 || letra == 47 || letra == 58 || letra == 94 || (letra >=60 && letra <=62)) {
flag_operador=true;
}
pos_ult_palavra=j;
}
else {
if (letra == 34 && flag_string) {
flag_string=false;
palavra=editor->Lines->Strings[i].SubString(pos_ult_palavra,(j+1)-pos_ult_palavra);
adiciona_palavra(palavra,i);
pos_ult_palavra=-1;
}
if (flag_operador && !(letra == 42 || letra == 43 || letra == 45 || letra == 47 || letra == 58 || letra == 94 || (letra >=60 && letra <=62))){
flag_operador=false;
palavra=editor->Lines->Strings[i].SubString(pos_ult_palavra,j-pos_ult_palavra);
adiciona_palavra(palavra,i);
j--;
}
if (flag_palavra && !(((letra >= 65) && (letra <= 90)) || ((letra >= 97) && (letra <= 122)) || ((letra >= 48) && (letra <= 57)))) {
flag_palavra=false;
palavra=editor->Lines->Strings[i].SubString(pos_ult_palavra,j-pos_ult_palavra);
adiciona_palavra(palavra,i);
j--;
}
}
}
if (pos_ult_palavra > 0) {
palavra=editor->Lines->Strings[i].SubString(pos_ult_palavra,j-pos_ult_palavra);
adiciona_palavra(palavra,i);
}
}
botao_processar->Caption="Processar";
botao_processar->Enabled=true;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::SpeedButton3Click(TObject *Sender)
{
editor->CopyToClipboard();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::SpeedButton4Click(TObject *Sender)
{
editor->PasteFromClipboard();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormCreate(TObject *Sender)
{
palavras->Cells[0][0]="Palavra";
palavras->Cells[1][0]="Identificador";
palavras->Cells[2][0]="Linha";
tab_toke->Cells[0][0]="Palavra";
tab_toke->Cells[1][0]="Identificador";
tab_toke->Cells[0][1]="BEGIN";
tab_toke->Cells[0][2]="IF";
tab_toke->Cells[0][3]="THEN";
tab_toke->Cells[0][4]="END";
tab_toke->Cells[0][5]="ELSE";
tab_toke->Cells[0][6]="FOR";
tab_toke->Cells[0][7]="TO";
tab_toke->Cells[0][8]="DO";
tab_toke->Cells[0][9]="WHILE";
tab_toke->Cells[0][10]="REPEAT";
tab_toke->Cells[0][11]="UNTIL";
tab_toke->Cells[0][12]="BREAK";
tab_toke->Cells[0][13]="VAR";
tab_toke->Cells[0][14]="WRITE";
tab_toke->Cells[0][15]="READ";
tab_toke->Cells[0][16]=">";
tab_toke->Cells[0][17]="<";
tab_toke->Cells[0][18]=">=";
tab_toke->Cells[0][19]="<=";
tab_toke->Cells[0][20]=":=";
tab_toke->Cells[0][21]="NOT";
tab_toke->Cells[0][22]="OR";
tab_toke->Cells[0][23]="AND";
tab_toke->Cells[0][24]="^";
tab_toke->Cells[0][25]="+";
tab_toke->Cells[0][26]="-";
tab_toke->Cells[0][27]="/";
tab_toke->Cells[0][28]="*";
tab_toke->Cells[1][1]="PALAVRA RESERVADA";
tab_toke->Cells[1][2]="PALAVRA RESERVADA";
tab_toke->Cells[1][3]="PALAVRA RESERVADA";
tab_toke->Cells[1][4]="PALAVRA RESERVADA";
tab_toke->Cells[1][5]="PALAVRA RESERVADA";
tab_toke->Cells[1][6]="PALAVRA RESERVADA";
tab_toke->Cells[1][7]="PALAVRA RESERVADA";
tab_toke->Cells[1][8]="PALAVRA RESERVADA";
tab_toke->Cells[1][9]="PALAVRA RESERVADA";
tab_toke->Cells[1][10]="PALAVRA RESERVADA";
tab_toke->Cells[1][11]="PALAVRA RESERVADA";
tab_toke->Cells[1][12]="PALAVRA RESERVADA";
tab_toke->Cells[1][13]="PALAVRA RESERVADA";
tab_toke->Cells[1][14]="PALAVRA RESERVADA";
tab_toke->Cells[1][15]="PALAVRA RESERVADA";
tab_toke->Cells[1][16]="OPERADOR RELACIONAL";
tab_toke->Cells[1][17]="OPERADOR RELACIONAL";
tab_toke->Cells[1][18]="OPERADOR RELACIONAL";
tab_toke->Cells[1][19]="OPERADOR RELACIONAL";
tab_toke->Cells[1][20]="OPERADOR DE ATRIBUIÇÃO";
tab_toke->Cells[1][21]="OPERADOR LÓGICO";
tab_toke->Cells[1][22]="OPERADOR LÓGICO";
tab_toke->Cells[1][23]="OPERADOR LÓGICO";
tab_toke->Cells[1][24]="OPERADOR MATEMÁTICO";
tab_toke->Cells[1][25]="OPERADOR MATEMÁTICO";
tab_toke->Cells[1][26]="OPERADOR MATEMÁTICO";
tab_toke->Cells[1][27]="OPERADOR MATEMÁTICO";
tab_toke->Cells[1][28]="OPERADOR MATEMÁTICO";
}
//---------------------------------------------------------------------------
void __fastcall TForm1::alternarClick(TObject *Sender)
{
if (editor->Visible == true) {
editor->Visible=false;
tab_toke->Visible=true;
alternar->Caption="Editor";
btok1->Visible=true;
btok2->Visible=true;
palavras->Visible=true;
}
else {
tab_toke->Visible=false;
editor->Visible=true;
alternar->Caption="Tokes";
btok1->Visible=false;
btok2->Visible=false;
palavras->Visible=false;
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::btok1Click(TObject *Sender)
{
tab_toke->RowCount++;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::btok2Click(TObject *Sender)
{
tab_toke->RowCount--;
}
//---------------------------------------------------------------------------
| [
"[email protected]"
]
| [
[
[
1,
198
]
]
]
|
|
984784c9baea0061ff40000886f6ee24df771fc7 | 6581dacb25182f7f5d7afb39975dc622914defc7 | /easyMule/easyMule/src/UILayer/DlgMainTabResource.cpp | 36280af9a322fc5ab87fa50a9a823e54c74be7b3 | []
| no_license | dice2019/alexlabonline | caeccad28bf803afb9f30b9e3cc663bb2909cc4f | 4c433839965ed0cff99dad82f0ba1757366be671 | refs/heads/master | 2021-01-16T19:37:24.002905 | 2011-09-21T15:20:16 | 2011-09-21T15:20:16 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 21,874 | cpp | /*
* $Id: DlgMainTabResource.cpp 18513 2010-03-24 09:41:45Z huby $
*
* this file is part of easyMule
* Copyright (C)2002-2008 VeryCD Dev Team ( strEmail.Format("%s@%s", "emuledev", "verycd.com") / http: * www.easymule.org )
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
// DlgMainTabResource.cpp : 实现文件
//
#include "stdafx.h"
#include "DlgMainTabResource.h"
#include "TabItem_Normal.h"
#include "TabItem_NormalCloseable.h"
#include "emule.h"
#include "emuleDlg.h"
#include "WebBrowserWnd.h"
#include "SearchListCtrl.h"
#include "SearchDlg.h"
#include "SearchResultsWnd.h"
#include "HelpIDs.h"
#include "UserMsgs.h"
#include "CmdFuncs.h"
#include "TabItem_Wnd.h"
#include "PageTabBkDraw.h"
#include "TabItem_WebBrowser.h"
#include "kademlia/kademlia/kademlia.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
//#define UM_RESTAB_EM_DESTROY UM_END + 1
SSearchParams* GetParameters(CString expression)
{
CString strExpression = expression;
CString strExtension;
UINT uAvailability = 0;
UINT uComplete = 0;
CString strCodec;
ULONG ulMinBitrate = 0;
ULONG ulMinLength = 0;
SSearchParams* pParams = new SSearchParams;
pParams->strExpression = strExpression;
pParams->eType = SearchTypeEasyMuleFile;//SearchTypeEd2kGlobal;
pParams->strFileType = _T("");
pParams->strMinSize = _T("");
pParams->ullMinSize = 0;
pParams->strMaxSize = _T("");
pParams->ullMaxSize = 0;
pParams->uAvailability = uAvailability;
pParams->strExtension = strExtension;
pParams->uComplete = uComplete;
pParams->strCodec = strCodec;
pParams->ulMinBitrate = ulMinBitrate;
pParams->ulMinLength = ulMinLength;
return pParams;
}
// CDlgMainTabResource 对话框
IMPLEMENT_DYNAMIC(CDlgMainTabResource, CDialog)
CDlgMainTabResource::CDlgMainTabResource(CWnd* pParent /*=NULL*/)
: CResizableDialog(CDlgMainTabResource::IDD, pParent)
{
m_dwCounter = 0;
m_SearchMap.InitHashTable(1031);
m_dwTotalCount = 0;
}
CDlgMainTabResource::~CDlgMainTabResource()
{
// {begin} 09/27/2007 Added by Soar Chin to resolve memory leaking
POSITION pos = m_SearchMap.GetStartPosition();
while (pos != NULL)
{
int key;
SSearchParams * params;
m_SearchMap.GetNextAssoc(pos, key, params);
if(params != NULL)
delete params;
}
m_SearchMap.RemoveAll();
// {end} 09/27/2007 Added by Soar Chin to resolve memory leaking
}
void CDlgMainTabResource::DoDataExchange(CDataExchange* pDX)
{
CResizableDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CDlgMainTabResource, CResizableDialog)
ON_NOTIFY(NMC_TW_ACTIVE_TAB_CHANDED, IDC_RESOURCE_TAB_WND, OnNMActiveTabChanged)
ON_NOTIFY(NMC_TW_TAB_DESTROY, IDC_RESOURCE_TAB_WND, OnNMTabDestroy)
ON_NOTIFY(NMC_TW_TAB_CREATE, IDC_RESOURCE_TAB_WND, OnNMTabCreate)
ON_MESSAGE(UM_RESTAB_WB_DESTROY, OnWbTabDestroy)
//ON_MESSAGE(UM_RESTAB_EM_DESTROY,OnEMTabDestroy)
END_MESSAGE_MAP()
CWebBrowserWnd* CDlgMainTabResource::OpenNewUrl(LPCTSTR lpszUrl, LPCTSTR lpszCaption, BOOL bSetActive, BOOL bClosable)
{
if (m_dwTotalCount > MAX_OPENED_TABS)
{
MessageBox(GetResString(IDS_ERR_MAXTABS),GetResString(IDS_CAPTION),MB_ICONWARNING);
return NULL;
}
CmdFuncs::SetMainActiveTab(CMainTabWnd::TI_RESOURCE);
CWebBrowserWnd *pwbw = new CWebBrowserWnd;
if (pwbw == NULL)
return NULL;
if (NULL != lpszUrl)
{
pwbw->SetOpenUrl(lpszUrl);
// VC-dgkang 2008年7月10日
m_strSearchUrl.AddTail(lpszUrl);
}
pwbw->Create(IDD_WEBBROWSER);
//CmdFuncs::TabWnd_AddCloseTab(&m_tabWnd, lpszCaption, pwbw->GetSafeHwnd(), TRUE, pwbw, bSetActive);
POSITION pos;
CTabItem_WebBrowser *pWbItem = NULL;
pWbItem = new CTabItem_WebBrowser;
pWbItem->SetCaption(lpszCaption);
pWbItem->SetRelativeWnd(pwbw->GetSafeHwnd(), NULL, TRUE, pwbw);
pWbItem->SetWbWnd(pwbw);
pWbItem->SetCustomData(TCD_WEB_BROWSER);
pWbItem->EnableClose(bClosable);
pwbw->SetAssocItem(pWbItem);
POSITION Pos = m_tabWnd.GetActiveTab();
pos = m_tabWnd.AddTab(pWbItem,TRUE,Pos);
pWbItem = NULL;
if (bSetActive)
m_tabWnd.SetActiveTab(pos);
m_dwTotalCount++;
return pwbw;
}
//{begin}VC-dgkang 2008年7月11日
BOOL CDlgMainTabResource::CreateNewShareFileTab(SSearchParams *pSS)
{
if (!pSS)
return FALSE;
if (m_dwTotalCount > MAX_OPENED_TABS)
{
MessageBox(GetResString(IDS_ERR_MAXTABS),GetResString(IDS_CAPTION),MB_ICONWARNING);
return FALSE;
}
POSITION Pos = m_SearchMap.GetStartPosition();
SSearchParams * pNextSS;
int i = 0;
while(Pos != NULL)
{
m_SearchMap.GetNextAssoc(Pos,i,pNextSS);
if (pNextSS->dwSearchID == pSS->dwSearchID)
{
return FALSE;
}
}
CmdFuncs::SetMainActiveTab(CMainTabWnd::TI_RESOURCE);
DWORD iCounter = 0;
DWORD CustomData = 0xF0F00000;
CustomData += m_dwCounter;
theApp.emuledlg->searchwnd->m_pwndResults->m_iCurSearchIndexInRes = m_dwCounter;
iCounter = m_dwCounter;
m_dwCounter++;
m_SearchMap.SetAt(iCounter,pSS);
pSS->strSearchTitle = (pSS->strSpecialTitle.IsEmpty() ? pSS->strExpression : pSS->strSpecialTitle);
CString strDisplayText = pSS->strSearchTitle;
CTabItem_NormalCloseable *pTi = NULL;
pTi = new CTabItem_NormalCloseable;
pTi->SetCaption(strDisplayText);
pTi->SetRelativeWnd(theApp.emuledlg->searchwnd->m_pwndResults->GetSafeHwnd());
pTi->SetCustomData(CustomData);
pTi->SetDesireLength(150);
Pos = m_tabWnd.GetActiveTab();
m_tabWnd.AddTab(pTi,TRUE,Pos);
m_dwTotalCount++;
return TRUE;
}
void CDlgMainTabResource::CreateNewSearch(LPCTSTR lpszCaption,ESearchType * pSearchType/* = NULL*/)
{
DWORD iCounter;
DWORD CustomData = 0xF0F00000;
SSearchParams * pSearchParams = GetParameters(lpszCaption);
if(pSearchType)
pSearchParams->eType = *pSearchType;
else
pSearchParams->eType = SearchTypeEasyMuleFile;
CustomData += m_dwCounter;
theApp.emuledlg->searchwnd->m_pwndResults->m_iCurSearchIndexInRes = m_dwCounter;
iCounter = m_dwCounter;
m_dwCounter++;
m_SearchMap.SetAt(iCounter, pSearchParams);
CString strDisplayText;
strDisplayText = GetResString(IDS_TABTITLE_SEARCH_RESULT);
strDisplayText += lpszCaption;
CTabItem_NormalCloseable *pTi = NULL;
pTi = new CTabItem_NormalCloseable;
pTi->SetCaption(strDisplayText);
pTi->SetRelativeWnd(theApp.emuledlg->searchwnd->m_pwndResults->GetSafeHwnd());
pTi->SetCustomData(CustomData);
pTi->SetDesireLength(150);
POSITION Pos = m_tabWnd.GetActiveTab();
m_tabWnd.AddTab(pTi,TRUE,Pos);
if (!theApp.emuledlg->searchwnd->m_pwndResults->StartSearch(pSearchParams))
m_SearchMap.RemoveKey(iCounter);
m_dwTotalCount++;
}
void CDlgMainTabResource::OpenNewSearchResult(LPCTSTR lpszCaption,ESearchType * pSearchType/* = NULL */)
{
if (m_dwTotalCount > MAX_OPENED_TABS)
{
MessageBox(GetResString(IDS_ERR_MAXTABS),GetResString(IDS_CAPTION),MB_ICONWARNING);
return;
}
CmdFuncs::SetMainActiveTab(CMainTabWnd::TI_SEARCH);
if( !pSearchType || *pSearchType==SearchTypeEasyMuleFile )
{
CreateNewSearch(lpszCaption,pSearchType);
}
else if ( *pSearchType == SearchTypeEd2kGlobal )
{
if( CGlobalVariable::serverconnect->IsConnected() )
CreateNewSearch(lpszCaption,pSearchType);
else
MessageBox(GetResString(IDS_ERR_NOTCONNECTED),GetResString(IDS_CAPTION),MB_ICONWARNING);
}
else if( *pSearchType == SearchTypeKademlia )
{
if( Kademlia::CKademlia::IsConnected() )
{
DWORD iCounter;
DWORD CustomData = 0xF0F00000;
if (m_dwCounter > 0x20)
{
return;
}
SSearchParams * pSearchParams = GetParameters(lpszCaption);
pSearchParams->eType = SearchTypeKademlia;
CustomData += m_dwCounter;
theApp.emuledlg->searchwnd->m_pwndResults->m_iCurSearchIndexInRes = m_dwCounter;
iCounter = m_dwCounter;
m_dwCounter++;
m_SearchMap.SetAt(iCounter, pSearchParams);
CString strDisplayText;
strDisplayText = GetResString(IDS_TABTITLE_SEARCH_RESULT);
strDisplayText += lpszCaption;
CTabItem_NormalCloseable *pTi = NULL;
pTi = new CTabItem_NormalCloseable;
pTi->SetCaption(strDisplayText);
pTi->SetRelativeWnd(theApp.emuledlg->searchwnd->m_pwndResults->GetSafeHwnd());
pTi->SetCustomData(CustomData);
pTi->SetDesireLength(150);
POSITION Pos = m_tabWnd.GetActiveTab();
m_tabWnd.AddTab(pTi,TRUE,Pos);
/* VC-dgkang 2008年7月17日
//Kademlia 返回错误,但不Delete pParams也不RemoveKey从m_SearchMap中,而是在删除标签页一起删除.
//这是为多标签页操作修改的。
if (!theApp.emuledlg->searchwnd->m_pwndResults->StartSearch(pSearchParams))
m_SearchMap.RemoveKey(iCounter);
*/
theApp.emuledlg->searchwnd->m_pwndResults->StartSearch(pSearchParams);
m_dwTotalCount++;
}
else
{
MessageBox(GetResString(IDS_ERR_NOTCONNECTEDKAD),GetResString(IDS_CAPTION),MB_ICONWARNING);
}
}
}
void CDlgMainTabResource::ShowVerycdPage()
{
OpenNewUrl(NULL, GetResString(IDS_VERYCD), TRUE, FALSE);
}
/*
void CDlgMainTabResource::ShowEmuleSearch()
{
DWORD CustomData = 0xF0F00000;
CString strDisplayText;
strDisplayText = GetResString(IDS_SEARCHEMULE);
SSearchParams * pSearchParams = GetParameters(_T(""));
CustomData += m_dwCounter;
theApp.emuledlg->searchwnd->m_pwndResults->m_iCurSearchIndexInRes = m_dwCounter;
int iCounter = m_dwCounter;
m_dwCounter++;
m_SearchMap.SetAt(iCounter, pSearchParams);
CTabItem_NormalCloseable *pTi = NULL;
pTi = new CTabItem_NormalCloseable;
pTi->SetCaption(strDisplayText);
pTi->SetRelativeWnd(theApp.emuledlg->searchwnd->m_pwndResults->GetSafeHwnd());
pTi->SetCustomData(CustomData);
pTi->EnableClose(FALSE);
pTi->SetDesireLength(150);
m_tabWnd.AddTab(pTi,TRUE);
m_dwTotalCount++;
}
*/
// CDlgMainTabResource 消息处理程序
BOOL CDlgMainTabResource::OnInitDialog()
{
CResizableDialog::OnInitDialog();
// TODO: 在此添加额外的初始化
ModifyStyle(0, WS_CLIPCHILDREN, 0);
CRect rect;
GetDlgItem(IDC_TAB1)->GetWindowRect(&rect);
ScreenToClient(&rect);
m_tabWnd.Create(WS_VISIBLE | WS_CHILD | WS_CLIPCHILDREN, rect, this, IDC_RESOURCE_TAB_WND);
//m_tabWnd.SetBkColor(GetSysColor(COLOR_3DFACE), FALSE);
//m_tabWnd.SetJointColor(RGB(121, 138, 169), RGB(255, 255, 255));
CPageTabBkDraw *pBarBkDraw = new CPageTabBkDraw;
m_tabWnd.SetBarBkDraw(pBarBkDraw);
// add WebBrowser Toolbar <begin>
m_browserToolbar.Create(WS_CHILD | WS_VISIBLE, CRect(0, 0, 0, 0), this, IDC_CUSTOM_BAR);
m_browserToolbar.Init();
//m_browserToolbar.SetOwner(theApp.emuledlg->webbrowser);
m_browserToolbar.SetIndent(8);
theApp.m_BrowserToolbarInfo.SetBrowserToolbarCtrl(&m_browserToolbar);
//CSize size;
//m_browserToolbar.GetMaxSize(&size);
CTabItem_Wnd *pTabItemWnd = new CTabItem_Wnd;
pTabItemWnd->SetItemWnd(&m_browserToolbar, FALSE);
// pTabItemWnd->SetWindowLength(size.cx + 8);
pTabItemWnd->SetDynDesireLength(TRUE);
m_tabWnd.AddTab(pTabItemWnd);
pTabItemWnd = NULL;
// add WebBrowser Toolbar <end>
// {begin} VC-dgkang 2008-7-10
if(thePrefs.m_bStartShowHomePage)
ShowVerycdPage();
//ShowEmuleSearch();
//Set Active Tab for verycd.com
POSITION pos =m_tabWnd.GetFirstTab();
if (pos)
{
m_tabWnd.GetNextTab(pos);
if (pos)
m_tabWnd.SetActiveTab(pos);
}
//{end}
AddAnchor(m_tabWnd,TOP_LEFT,BOTTOM_RIGHT);
return TRUE; // return TRUE unless you set the focus to a control
// 异常: OCX 属性页应返回 FALSE
}
BOOL CDlgMainTabResource::PreTranslateMessage(MSG* pMsg)
{
// TODO: 在此添加专用代码和/或调用基类
if (pMsg->message == WM_KEYDOWN)
{
// Don't handle Ctrl+Tab in this window. It will be handled by main window.
if (pMsg->wParam == VK_TAB && GetAsyncKeyState(VK_CONTROL) < 0)
return FALSE;
if (VK_RETURN == pMsg->wParam || VK_ESCAPE == pMsg->wParam)
return FALSE;
}
return CResizableDialog::PreTranslateMessage(pMsg);
}
void CDlgMainTabResource::OnNMActiveTabChanged(NMHDR* pNMHDR, LRESULT *pResult)
{
NMTW_TABOP *pTabOp = reinterpret_cast<NMTW_TABOP*>(pNMHDR);
//pTabOp->posOld;
//pTabOp->posTab;
DWORD CustomData = m_tabWnd.GetTabData(pTabOp->posTab);
DWORD LowData = CustomData & 0x0000FFFF;
DWORD HighData = CustomData & 0xFFFF0000;
if( CustomData >= 0xF0F00000 )
{
CTabItem* pTabItem = m_tabWnd.GetTabItem(pTabOp->posTab);
if (pTabItem)
pTabItem->SetRelativeWnd(theApp.emuledlg->searchwnd->m_pwndResults->GetSafeHwnd());
}
if (HighData ^ 0x0F0FFFFF)
{
SSearchParams *pSearchParams=NULL;
BOOL bSearch = m_SearchMap.Lookup(LowData, pSearchParams);
if ( bSearch && pSearchParams )
{
theApp.emuledlg->searchwnd->m_pwndResults->searchlistctrl.ShowResults(pSearchParams->dwSearchID);
theApp.emuledlg->searchwnd->m_pwndResults->UpdateParamDisplay(pSearchParams);
theApp.emuledlg->searchwnd->m_pwndResults->m_iCurSearchIndexInRes = LowData;
}
}
if (TCD_WEB_BROWSER == CustomData)
{
//m_browserToolbar.EnableAllButtons(TRUE);
CTabItem_WebBrowser *pItem = (CTabItem_WebBrowser*) m_tabWnd.GetTabItem(pTabOp->posTab);
if (NULL != pItem)
m_browserToolbar.SetOwner(pItem->GetAssocWbw());
BOOL bForwordEnable = pItem->GetAssocWbw()->m_pExplorer->bForwordEnable;
BOOL bBackEnable = pItem->GetAssocWbw()->m_pExplorer->bBackEnable;
theApp.m_BrowserToolbarInfo.GetBrowserToolbarCtrl()->EnableButton(TB_FORWARD,bForwordEnable);
theApp.m_BrowserToolbarInfo.GetBrowserToolbarCtrl()->EnableButton(TB_BACK, bBackEnable);
theApp.m_BrowserToolbarInfo.GetBrowserToolbarCtrl()->EnableButton(TB_REFRESH, TRUE);
theApp.m_BrowserToolbarInfo.GetBrowserToolbarCtrl()->EnableButton(TB_HOME, TRUE);
}
else
m_browserToolbar.EnableAllButtons(FALSE);
*pResult = 0;
}
void CDlgMainTabResource::OnNMTabDestroy(NMHDR* pNMHDR, LRESULT *pResult)
{
theApp.emuledlg->searchwnd->m_pwndResults->SetPos(0);
NMTW_TABOP *pTabOp = reinterpret_cast<NMTW_TABOP*>(pNMHDR);
//pTabOp->posTab;
DWORD CustomData = m_tabWnd.GetTabData(pTabOp->posTab);
DWORD LowData = CustomData & 0x0000FFFF;
DWORD HighData = CustomData & 0xFFFF0000;
if (HighData ^ 0x0F0FFFFF)
{
SSearchParams *pSearchParams=NULL;
BOOL bSearch = m_SearchMap.Lookup(LowData, pSearchParams);
if ( bSearch && pSearchParams)
{
theApp.emuledlg->searchwnd->m_pwndResults->searchlistctrl.RemoveResults(pSearchParams->dwSearchID);
m_SearchMap.RemoveKey(LowData);
}
delete pSearchParams;
}
if (TCD_WEB_BROWSER == CustomData)
{
PostMessage(UM_RESTAB_WB_DESTROY);
}
// else if (CustomData >= 0xF0F00000)
// {
// PostMessage(UM_RESTAB_EM_DESTROY);
// }
if (m_dwTotalCount > 0)
m_dwTotalCount--;
*pResult = 0;
}
void CDlgMainTabResource::OnNMTabCreate(NMHDR* pNMHDR, LRESULT *pResult)
{
NMTW_TABOP *pTabOp = reinterpret_cast<NMTW_TABOP*>(pNMHDR);
DWORD dwCustomData = m_tabWnd.GetTabData(pTabOp->posTab);
if (TCD_WEB_BROWSER == dwCustomData)
UpdateWbsClosableStatus();
/*
else if(dwCustomData >= 0xF0F00000)
UpdateEMsClosableStatus();
*/
*pResult = 0;
}
//{begin} VC-dgkang 2008年7月8日
CString GetNoParamUrl(LPCTSTR lpszText)
{
CString tcs = lpszText;
int n = tcs.Find(_T("#"));
if (n == -1)
n = tcs.Find(_T("?"));
if (n != -1)
tcs = tcs.Left(n);
return tcs;
}
BOOL CDlgMainTabResource::CreateNewWbTabSearch(WPARAM wParam, LPCTSTR lpszText)
{
CString tcs = lpszText;
BOOL bValid = FALSE,bHome = FALSE;
CTabItem_WebBrowser *pWbItem = NULL;
POSITION Pos = m_tabWnd.GetActiveTab();
if(Pos)
{
CTabItem *pItem = m_tabWnd.GetTabItem(Pos);
if (pItem->m_dwCustomData == TCD_WEB_BROWSER)
pWbItem = (CTabItem_WebBrowser *)pItem;
}
if (tcs.Find(_T("#")) != -1 || tcs.Find(_T("?")) != -1)
{
if (pWbItem)
{
if (GetNoParamUrl(lpszText) == GetNoParamUrl(pWbItem->GetRealUrl()))
return FALSE;
}
}
if (wParam == 1)
{
OpenNewUrl(lpszText,NULL,TRUE,FALSE);
return TRUE; //这个返回无任何意义
}
#ifdef _FOREIGN_VERSION
bHome = tcs.CompareNoCase(thePrefs.m_strHomePage) == 0;
if (!bHome)
{
bValid = tcs.Find(thePrefs.m_strSearchPage) != -1;
}
#else
bHome = tcs.CompareNoCase(_T("http://www.verycd.com/start/")) == 0;
if (!bHome)
{
bValid = tcs.Find(_T("http://www.verycd.com/search/folders/")) != -1;
}
#endif
if (!bHome && bValid)
{
#ifdef _FOREIGN_VERSION
if (pWbItem && !pWbItem->GetRealUrl().CompareNoCase(thePrefs.m_strHomePage))
return FALSE;
#else
if (pWbItem && !pWbItem->GetRealUrl().CompareNoCase(_T("http://www.verycd.com/start/")))
return FALSE;
#endif
//m_strSerchUrl 只是简单作为一个状态变量来使用。
if (m_strSearchUrl.IsEmpty())
{
OpenNewUrl(lpszText,NULL,TRUE,FALSE);
return TRUE; //将不在本标签页显示.
}
else
{
m_strSearchUrl.RemoveAll();
return FALSE;
}
}
return FALSE;
}
//{begin} VC-dgkang 2008年7月17日
void CDlgMainTabResource::Localize()
{
const CString tcsEN = _T("easyMule Search"),tcsTW = _T("搜索電驢網路"), tcsCN = _T("搜索电驴网络");
const CString szEN = _T("Search:"),szTW = _T("搜索:"), szCN = _T("搜索:");
CString tcs;
CTabItem_NormalCloseable * pEMItem = NULL;
int nLen = -1;
POSITION pos = m_tabWnd.GetFirstTab();
CTabItem *pItem = NULL;
while (NULL != pos)
{
pItem = m_tabWnd.GetNextTab(pos);
if (NULL != pItem)
{
if (pItem->m_dwCustomData >= 0xF0F00000)
{
pEMItem = (CTabItem_NormalCloseable *)pItem;
CString tcs = pEMItem->GetCaption();
if (tcs == tcsEN || tcs == tcsTW || tcs == tcsCN)
pEMItem->SetCaption(GetResString(IDS_SEARCHEMULE));
else
{
if (tcs.Find(szEN) == 0) nLen = szEN.GetLength();
else if(tcs.Find(szTW) == 0) nLen = szTW.GetLength();
else if(tcs.Find(szCN) == 0) nLen = szCN.GetLength();
else nLen = -1;
if (nLen != -1)
{
tcs.Replace(tcs.Left(nLen),GetResString(IDS_TABTITLE_SEARCH_RESULT));
pEMItem->SetCaption(tcs);
}
}
}
}
}
}
//{end}
/*
void CDlgMainTabResource::UpdateEMsClosableStatus()
{
int iEMCount = 0;
CTabItem_NormalCloseable * pEMItem = NULL;
POSITION pos =m_tabWnd.GetFirstTab();
CTabItem *pItem = NULL;
while (NULL != pos)
{
pItem = m_tabWnd.GetNextTab(pos);
if (NULL != pItem)
{
if (pItem->m_dwCustomData >= 0xF0F00000)
{
pEMItem = (CTabItem_NormalCloseable *)pItem;
pEMItem->EnableClose(TRUE);
iEMCount ++;
}
}
}
if (1 == iEMCount && NULL != pEMItem &&
pEMItem->GetCaption() == GetResString(IDS_SEARCHEMULE))
{
pEMItem->EnableClose(FALSE);
}
if ( 0 == iEMCount)
ShowEmuleSearch();
}
*/
void CDlgMainTabResource::UpdateWbsClosableStatus()
{
int iWbCount = 0;
CTabItem_WebBrowser *pWbItem = NULL;
POSITION pos =m_tabWnd.GetFirstTab();
CTabItem *pItem;
while (NULL != pos)
{
pItem = m_tabWnd.GetNextTab(pos);
if (NULL != pItem)
{
if (TCD_WEB_BROWSER == pItem->m_dwCustomData)
{
pWbItem = (CTabItem_WebBrowser*)pItem;
pWbItem->EnableClose(TRUE);
iWbCount++;
}
}
}
// VC-Dgkang 2008年7月7日
if (1 == iWbCount && NULL != pWbItem &&
#ifdef _FOREIGN_VERSION
thePrefs.m_strHomePage == pWbItem->GetRealUrl())
#else
_T("http://www.verycd.com/start/")== pWbItem->GetRealUrl())
#endif
{
pWbItem->EnableClose(FALSE);
}
if (0 == iWbCount)
ShowVerycdPage();
//{end}
}
LRESULT CDlgMainTabResource::OnWbTabDestroy(WPARAM /*wParam*/, LPARAM /*lParam*/)
{
UpdateWbsClosableStatus();
return 0;
}
/*
LRESULT CDlgMainTabResource::OnEMTabDestroy(WPARAM wParam , LPARAM lParam )
{
UpdateEMsClosableStatus();
return 0;
}
*/
void CDlgMainTabResource::UpdateSearchParam(int iIndex, SSearchParams *pSearchParams)
{
SSearchParams *psp;
if (m_SearchMap.Lookup(iIndex, psp))
{
delete psp;
m_SearchMap.SetAt(iIndex, pSearchParams);
}
}
void CDlgMainTabResource::OnMainTabChanged()
{
POSITION Pos = m_tabWnd.GetActiveTab();
if (Pos == NULL)
return;
m_tabWnd.ShowActiveTab();
DWORD CustomData = m_tabWnd.GetTabData(Pos);
DWORD LowData = CustomData & 0x0000FFFF;
DWORD HighData = CustomData & 0xFFFF0000;
if( CustomData >= 0xF0F00000 )
{
CTabItem* pTabItem = m_tabWnd.GetTabItem(Pos);
if (pTabItem)
pTabItem->SetRelativeWnd(theApp.emuledlg->searchwnd->m_pwndResults->GetSafeHwnd());
}
if (HighData ^ 0x0F0FFFFF)
{
SSearchParams *pSearchParams=NULL;
BOOL bSearch = m_SearchMap.Lookup(LowData, pSearchParams);
if ( bSearch && pSearchParams )
{
theApp.emuledlg->searchwnd->m_pwndResults->searchlistctrl.ShowResults(pSearchParams->dwSearchID);
theApp.emuledlg->searchwnd->m_pwndResults->UpdateParamDisplay(pSearchParams);
theApp.emuledlg->searchwnd->m_pwndResults->m_iCurSearchIndexInRes = LowData;
}
}
} | [
"damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838"
]
| [
[
[
1,
818
]
]
]
|
a4b50dfa5360f52c00a1f1663276da691fdf527d | c7120eeec717341240624c7b8a731553494ef439 | /src/cplusplus/freezone-samp/src/core/buffer/buffer.hpp | aaaeb4946e33addcc2683784a34efc848d89e695 | []
| no_license | neverm1ndo/gta-paradise-sa | d564c1ed661090336621af1dfd04879a9c7db62d | 730a89eaa6e8e4afc3395744227527748048c46d | refs/heads/master | 2020-04-27T22:00:22.221323 | 2010-09-04T19:02:28 | 2010-09-04T19:02:28 | 174,719,907 | 1 | 0 | null | 2019-03-09T16:44:43 | 2019-03-09T16:44:43 | null | WINDOWS-1251 | C++ | false | false | 2,051 | hpp | #ifndef BUFFER_HPP
#define BUFFER_HPP
#include "buffer_fwd.hpp"
#include <string>
#include <vector>
#include <memory>
#include <unordered_map>
class buffer: public std::tr1::enable_shared_from_this<buffer> {
public:
typedef std::tr1::shared_ptr<buffer> ptr;
typedef std::tr1::shared_ptr<buffer const> ptr_c;
typedef std::tr1::weak_ptr<buffer const> wptr;
typedef std::tr1::unordered_multimap<std::string, std::string> values_t;
typedef std::tr1::unordered_multimap<std::string, ptr> children_t;
typedef std::vector<std::string> values_vector_t;
typedef std::vector<ptr> children_vector_t;
values_t values;
children_t children;
wptr parent;
buffer();
~buffer();
void clear();
// Добавляет связный элемент, но не делает его потомком
ptr children_create_connected() const;
// Добавляет потомка, с заданным именем
ptr children_add(std::string const& name);
// Возращает потомка. Если потомка с заданным именем нет, то возращает нулевой указатель
bool children_is_exist(std::string const& name) const;
ptr children_get(std::string const& name) const;
children_vector_t children_get_all(std::string const& name) const;
void value_add(std::string const& name, std::string const& value);
void value_replace(std::string const& name, std::string const& value);
bool value_is_exist(std::string const& name) const;
std::string value_get(std::string const& name) const;
values_vector_t value_get_all(std::string const& name) const;
// Обрабатывает все замены переменных в строке, используя текущий буффер как базу
std::string process_all_vars(std::string const& str) const;
};
#endif // BUFFER_HPP
| [
"dimonml@19848965-7475-ded4-60a4-26152d85fbc5"
]
| [
[
[
1,
52
]
]
]
|
76f16eb1ab8908f74d891190921287137cde2970 | 5eabfcd54c3610a230068574fccaf47fdd40839d | /Cocos2dxSimpleGame/Classes/HelloWorldScene.cpp | 519ad75f87b1f266856446bf677e9788a027b785 | [
"MIT"
]
| permissive | quning19/cocos2d_study | 34d2b5dfd66ab530d4fd3e2d99a4932f1dda2bc8 | 44737348da7e98b92af1e61e4bae967a2347d587 | refs/heads/master | 2021-01-16T18:02:21.979906 | 2011-12-19T03:09:33 | 2011-12-19T03:09:33 | 3,009,477 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,432 | cpp | #include "HelloWorldScene.h"
#include "GameOverScene.h"
#include "SimpleAudioEngine.h"
using namespace cocos2d;
HelloWorld::~HelloWorld()
{
if (_targets)
{
_targets->release();
_targets = NULL;
}
if (_projectiles)
{
_projectiles->release();
_projectiles = NULL;
}
// cpp don't need to call super dealloc
// virtual destructor will do this
}
HelloWorld::HelloWorld()
:_targets(NULL)
,_projectiles(NULL)
,_projectilesDestroyed(0)
{
}
CCScene* HelloWorld::scene()
{
CCScene * scene = NULL;
do
{
// 'scene' is an autorelease object
scene = CCScene::node();
CC_BREAK_IF(! scene);
// 'layer' is an autorelease object
HelloWorld *layer = HelloWorld::node();
CC_BREAK_IF(! layer);
// add layer as a child to scene
scene->addChild(layer);
} while (0);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
bool bRet = false;
do
{
//////////////////////////////////////////////////////////////////////////
// super init first
//////////////////////////////////////////////////////////////////////////
CC_BREAK_IF(! CCLayerColor::initWithColor( ccc4(255,255,255,255) ) );
//////////////////////////////////////////////////////////////////////////
// add your codes below...
//////////////////////////////////////////////////////////////////////////
// 1. Add a menu item with "X" image, which is clicked to quit the program.
// Create a "close" menu item with close icon, it's an auto release object.
CCMenuItemImage *pCloseItem = CCMenuItemImage::itemFromNormalImage(
"CloseNormal.png",
"CloseSelected.png",
this,
menu_selector(HelloWorld::menuCloseCallback));
CC_BREAK_IF(! pCloseItem);
// Place the menu item bottom-right conner.
pCloseItem->setPosition(ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20));
// Create a menu with the "close" menu item, it's an auto release object.
CCMenu* pMenu = CCMenu::menuWithItems(pCloseItem, NULL);
pMenu->setPosition(CCPointZero);
CC_BREAK_IF(! pMenu);
// Add the menu to HelloWorld layer as a child layer.
this->addChild(pMenu, 1);
/////////////////////////////
// 2. add your codes below...
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
CCSprite *player = CCSprite::spriteWithFile("Player.png",
CCRectMake(0, 0, 27, 40) );
player->setPosition( ccp(player->getContentSize().width/2, winSize.height/2) );
this->addChild(player);
this->schedule( schedule_selector(HelloWorld::gameLogic), 1.0 );
this->setIsTouchEnabled(true);
_targets = new CCMutableArray<CCSprite*>;
_projectiles = new CCMutableArray<CCSprite*>;
// use updateGame instead of update, otherwise it will conflit with SelectorProtocol::update
// see http://www.cocos2d-x.org/boards/6/topics/1478
this->schedule( schedule_selector(HelloWorld::updateGame) );
CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic("background-music-aac.wav", true);
bRet = true;
} while (0);
return bRet;
}
void HelloWorld::menuCloseCallback(CCObject* pSender)
{
// "close" menu item clicked
CCDirector::sharedDirector()->end();
}
// cpp with cocos2d-x
void HelloWorld::addTarget()
{
CCSprite *target = CCSprite::spriteWithFile("Target.png",
CCRectMake(0,0,27,40) );
// Determine where to spawn the target along the Y axis
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
float minY = target->getContentSize().height/2;
float maxY = winSize.height - target->getContentSize().height/2;
int rangeY = (int)(maxY - minY);
// srand( TimGetTicks() );
int actualY = ( rand() % rangeY ) + (int)minY;
// Create the target slightly off-screen along the right edge,
// and along a random position along the Y axis as calculated
target->setPosition(
ccp(winSize.width + (target->getContentSize().width/2),
actualY) );
this->addChild(target);
// Determine speed of the target
int minDuration = (int)2.0;
int maxDuration = (int)4.0;
int rangeDuration = maxDuration - minDuration;
// srand( TimGetTicks() );
int actualDuration = ( rand() % rangeDuration ) + minDuration;
// Create the actions
CCFiniteTimeAction* actionMove =
CCMoveTo::actionWithDuration( (ccTime)actualDuration,
ccp(0 - target->getContentSize().width/2, actualY) );
CCFiniteTimeAction* actionMoveDone =
CCCallFuncN::actionWithTarget( this,
callfuncN_selector(HelloWorld::spriteMoveFinished));
target->runAction( CCSequence::actions(actionMove,
actionMoveDone, NULL) );
// Add to targets array
target->setTag(1);
_targets->addObject(target);
}
void HelloWorld::spriteMoveFinished(CCNode* sender)
{
CCSprite *sprite = (CCSprite *)sender;
this->removeChild(sprite, true);
if (sprite->getTag() == 1) // target
{
_targets->removeObject(sprite);
GameOverScene *gameOverScene = GameOverScene::node();
gameOverScene->getLayer()->getLabel()->setString("You Lose :[");
CCDirector::sharedDirector()->replaceScene(gameOverScene);
}
else if (sprite->getTag() == 2) // projectile
{
_projectiles->removeObject(sprite);
}
}
void HelloWorld::gameLogic(ccTime dt)
{
this->addTarget();
}
// cpp with cocos2d-x
void HelloWorld::ccTouchesEnded(CCSet* touches, CCEvent* event)
{
// Choose one of the touches to work with
CCTouch* touch = (CCTouch*)( touches->anyObject() );
CCPoint location = touch->locationInView(touch->view());
location = CCDirector::sharedDirector()->convertToGL(location);
// Set up initial location of projectile
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
CCSprite *projectile = CCSprite::spriteWithFile("Projectile.png",
CCRectMake(0, 0, 20, 20));
projectile->setPosition( ccp(20, winSize.height/2) );
// Determinie offset of location to projectile
float offX = location.x - projectile->getPosition().x;
float offY = location.y - projectile->getPosition().y;
// Bail out if we are shooting down or backwards
if (offX <= 0) return;
// Ok to add now - we've double checked position
this->addChild(projectile);
// Determine where we wish to shoot the projectile to
float realX = winSize.width + (projectile->getContentSize().width/2);
float ratio = offY / offX;
float realY = (realX * ratio) + projectile->getPosition().y;
CCPoint realDest = ccp(realX, realY);
// Determine the length of how far we're shooting
float offRealX = realX - projectile->getPosition().x;
float offRealY = realY - projectile->getPosition().y;
float length = sqrtf((offRealX * offRealX) + (offRealY*offRealY));
float velocity = 480/1; // 480pixels/1sec
float realMoveDuration = length/velocity;
// Move projectile to actual endpoint
projectile->runAction( CCSequence::actions(
CCMoveTo::actionWithDuration(realMoveDuration, realDest),
CCCallFuncN::actionWithTarget(this,
callfuncN_selector(HelloWorld::spriteMoveFinished)),
NULL) );
// Add to projectiles array
projectile->setTag(2);
_projectiles->addObject(projectile);
CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect("pew-pew-lei.wav");
}
void HelloWorld::updateGame(ccTime dt)
{
CCMutableArray<CCSprite*> *projectilesToDelete =
new CCMutableArray<CCSprite*>;
CCMutableArray<CCSprite*>::CCMutableArrayIterator it, jt;
for (it = _projectiles->begin(); it != _projectiles->end(); it++)
{
CCSprite *projectile =*it;
CCRect projectileRect = CCRectMake(
projectile->getPosition().x - (projectile->getContentSize().width/2),
projectile->getPosition().y - (projectile->getContentSize().height/2),
projectile->getContentSize().width,
projectile->getContentSize().height);
CCMutableArray<CCSprite*>*targetsToDelete =new CCMutableArray<CCSprite*>;
for (jt = _targets->begin(); jt != _targets->end(); jt++)
{
CCSprite *target =*jt;
CCRect targetRect = CCRectMake(
target->getPosition().x - (target->getContentSize().width/2),
target->getPosition().y - (target->getContentSize().height/2),
target->getContentSize().width,
target->getContentSize().height);
if (CCRect::CCRectIntersectsRect(projectileRect, targetRect))
{
targetsToDelete->addObject(target);
}
}
for (jt = targetsToDelete->begin(); jt != targetsToDelete->end(); jt++)
{
CCSprite *target =*jt;
_targets->removeObject(target);
this->removeChild(target, true);
_projectilesDestroyed++;
if (_projectilesDestroyed >= 5)
{
GameOverScene *gameOverScene = GameOverScene::node();
gameOverScene->getLayer()->getLabel()->setString("You Win!");
CCDirector::sharedDirector()->replaceScene(gameOverScene);
}
}
if (targetsToDelete->count() > 0)
{
projectilesToDelete->addObject(projectile);
}
targetsToDelete->release();
}
for (it = projectilesToDelete->begin(); it != projectilesToDelete->end(); it++)
{
CCSprite* projectile =*it;
_projectiles->removeObject(projectile);
this->removeChild(projectile, true);
}
projectilesToDelete->release();
}
void HelloWorld::registerWithTouchDispatcher()
{
// CCTouchDispatcher::sharedDispatcher()->addTargetedDelegate(this,0,true);
CCTouchDispatcher::sharedDispatcher()->addStandardDelegate(this,0);
}
| [
"[email protected]"
]
| [
[
[
1,
314
]
]
]
|
85f3ba8bb50225206add766f6dc3da1f972830bb | 3643bb671f78a0669c8e08935476551a297ce996 | /R_OpenGL.cpp | 6fc88e93f1d796b4de142a109a4bc0566c2b2535 | []
| no_license | mattfischer/3dportal | 44b3b9fb2331650fc406596b941f6228f37ff14b | e00f7d601138f5cf72aac35f4d15bdf230c518d9 | refs/heads/master | 2020-12-25T10:36:51.991814 | 2010-08-29T22:53:06 | 2010-08-29T22:53:06 | 65,869,788 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,355 | cpp | #include <windows.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include "R_OpenGL.h"
#include "R_Frame.h"
namespace Render
{
HDC hDC;
bool started=false;
HGLRC hRC;
bool OpenGl::Initialize(HWND hWnd)
{
int pixform;
PIXELFORMATDESCRIPTOR pfd=
{
sizeof(PIXELFORMATDESCRIPTOR),
1,
PFD_DRAW_TO_WINDOW |
PFD_SUPPORT_OPENGL |
PFD_DOUBLEBUFFER,
PFD_TYPE_RGBA,
32,
0, 0, 0, 0, 0, 0,
0,
0,
0,
0, 0, 0, 0,
16,
0,
0,
PFD_MAIN_PLANE,
0,
0, 0, 0
};
DEVMODE dm;
dm.dmSize=sizeof(DEVMODE);
dm.dmFields=DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL;
dm.dmPelsWidth=Frame::ScreenX;
dm.dmPelsHeight=Frame::ScreenY;
dm.dmBitsPerPel=16;
ChangeDisplaySettings(&dm,CDS_FULLSCREEN);
hDC=GetDC(hWnd);
pixform=ChoosePixelFormat(hDC,&pfd);
if(!SetPixelFormat(hDC,pixform,&pfd))
{
MessageBox(NULL,"InitializeOpenGL(): Could not set pixel format","Info",MB_OK);
return false;
}
hRC=wglCreateContext(hDC);
wglMakeCurrent(hDC,hRC);
glViewport(0,0,Frame::ScreenX,Frame::ScreenY);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(FOV,(GLfloat)Frame::ScreenX/(GLfloat)Frame::ScreenY,0.03f,400.f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glShadeModel(GL_SMOOTH);
glClearColor(0.5f,0.5f,0.5f,0.0f);
glClearDepth(1.0f);
glEnable(GL_DEPTH_TEST);
glEnable(GL_TEXTURE_2D);
glDepthFunc(GL_LESS);
glDisable(GL_LIGHTING);
//glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
glPointSize(5.0);
glLineWidth(1.0);
glCullFace(GL_BACK);
started=true;
return true;
}
void OpenGl::Shutdown(HWND hWnd)
{
started=false;
ChangeDisplaySettings(NULL,0);
wglMakeCurrent(NULL,NULL);
wglDeleteContext(hRC);
ReleaseDC(hWnd,hDC);
}
bool OpenGl::Started()
{
return started;
}
void OpenGl::SwapBuffers()
{
::SwapBuffers(hDC);
}
} | [
"devnull@localhost"
]
| [
[
[
1,
107
]
]
]
|
c93495788c543b29a3d573f6b82d8e1ec9257523 | ab41c2c63e554350ca5b93e41d7321ca127d8d3a | /glm/gtc/quaternion.inl | 5b05a07b1b35ee7ed9d75c5210c8ac08b6dfbb21 | []
| no_license | burner/e3rt | 2dc3bac2b7face3b1606ee1430e7ecfd4523bf2e | 775470cc9b912a8c1199dd1069d7e7d4fc997a52 | refs/heads/master | 2021-01-11T08:08:00.665300 | 2010-04-26T11:42:42 | 2010-04-26T11:42:42 | 337,021 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,533 | inl | ///////////////////////////////////////////////////////////////////////////////////////////////////
// OpenGL Mathematics Copyright (c) 2005 - 2009 G-Truc Creation (www.g-truc.net)
///////////////////////////////////////////////////////////////////////////////////////////////////
// Created : 2009-05-21
// Updated : 2009-06-04
// Licence : This source is under MIT License
// File : glm/gtc/quaternion.inl
///////////////////////////////////////////////////////////////////////////////////////////////////
#include <limits>
namespace glm{
namespace detail{
template <typename valType>
inline tquat<valType>::tquat() :
x(0),
y(0),
z(0),
w(1)
{}
template <typename valType>
inline tquat<valType>::tquat
(
valType const & s,
tvec3<valType> const & v
) :
x(v.x),
y(v.y),
z(v.z),
w(s)
{}
template <typename valType>
inline tquat<valType>::tquat
(
valType const & w,
valType const & x,
valType const & y,
valType const & z
) :
x(x),
y(y),
z(z),
w(w)
{}
//////////////////////////////////////////////////////////////
// tquat conversions
//template <typename valType>
//inline tquat<valType>::tquat
//(
// valType const & pitch,
// valType const & yaw,
// valType const & roll
//)
//{
// tvec3<valType> eulerAngle(pitch * valType(0.5), yaw * valType(0.5), roll * valType(0.5));
// tvec3<valType> c = glm::cos(eulerAngle * valType(0.5));
// tvec3<valType> s = glm::sin(eulerAngle * valType(0.5));
//
// this->w = c.x * c.y * c.z + s.x * s.y * s.z;
// this->x = s.x * c.y * c.z - c.x * s.y * s.z;
// this->y = c.x * s.y * c.z + s.x * c.y * s.z;
// this->z = c.x * c.y * s.z - s.x * s.y * c.z;
//}
template <typename valType>
inline tquat<valType>::tquat
(
tvec3<valType> const & eulerAngle
)
{
tvec3<valType> c = glm::cos(eulerAngle * valType(0.5));
tvec3<valType> s = glm::sin(eulerAngle * valType(0.5));
this->w = c.x * c.y * c.z + s.x * s.y * s.z;
this->x = s.x * c.y * c.z - c.x * s.y * s.z;
this->y = c.x * s.y * c.z + s.x * c.y * s.z;
this->z = c.x * c.y * s.z - s.x * s.y * c.z;
}
template <typename valType>
inline tquat<valType>::tquat
(
tmat3x3<valType> const & m
)
{
*this = toQuat(m);
}
template <typename valType>
inline tquat<valType>::tquat
(
tmat4x4<valType> const & m
)
{
*this = toQuat(m);
}
//////////////////////////////////////////////////////////////
// tquat<T> accesses
template <typename valType>
inline valType& tquat<valType>::operator [] (int i)
{
return (&x)[i];
}
template <typename valType>
inline valType tquat<valType>::operator [] (int i) const
{
return (&x)[i];
}
//////////////////////////////////////////////////////////////
// tquat<valType> operators
template <typename valType>
inline tquat<valType>& tquat<valType>::operator *=
(
valType const & s
)
{
this->w *= s;
this->x *= s;
this->y *= s;
this->z *= s;
return *this;
}
template <typename valType>
inline tquat<valType>& tquat<valType>::operator /=
(
valType const & s
)
{
this->w /= s;
this->x /= s;
this->y /= s;
this->z /= s;
return *this;
}
//////////////////////////////////////////////////////////////
// tquat<valType> external operators
template <typename valType>
inline detail::tquat<valType> operator-
(
detail::tquat<valType> const & q
)
{
return detail::tquat<valType>(-q.w, -q.x, -q.y, -q.z);
}
// Transformation
template <typename valType>
inline detail::tvec3<valType> operator*
(
detail::tquat<valType> const & q,
detail::tvec3<valType> const & v
)
{
detail::tvec3<valType> uv, uuv;
detail::tvec3<valType> QuatVector(q.x, q.y, q.z);
uv = glm::cross(QuatVector, v);
uuv = glm::cross(QuatVector, uv);
uv *= (valType(2) * q.w);
uuv *= valType(2);
return v + uv + uuv;
}
template <typename valType>
inline detail::tvec3<valType> operator*
(
detail::tvec3<valType> const & v,
detail::tquat<valType> const & q
)
{
return gtc::quaternion::inverse(q) * v;
}
template <typename valType>
inline detail::tvec4<valType> operator*
(
detail::tquat<valType> const & q,
detail::tvec4<valType> const & v
)
{
return detail::tvec4<valType>(q * detail::tvec3<valType>(v), v.w);
}
template <typename valType>
inline detail::tvec4<valType> operator*
(
detail::tvec4<valType> const & v,
detail::tquat<valType> const & q
)
{
return gtc::quaternion::inverse(q) * v;
}
template <typename valType>
inline detail::tquat<valType> operator*
(
detail::tquat<valType> const & q,
valType const & s
)
{
return detail::tquat<valType>(
q.w * s, q.x * s, q.y * s, q.z * s);
}
template <typename valType>
inline detail::tquat<valType> operator*
(
valType const & s,
detail::tquat<valType> const & q
)
{
return q * s;
}
template <typename valType>
inline detail::tquat<valType> operator/
(
detail::tquat<valType> const & q,
valType const & s
)
{
return detail::tquat<valType>(
q.w / s, q.x / s, q.y / s, q.z / s);
}
}//namespace detail
namespace gtc{
namespace quaternion{
////////////////////////////////////////////////////////
template <typename valType>
inline valType length
(
detail::tquat<valType> const & q
)
{
return static_cast<valType>(glm::sqrt(dot(q, q)));
}
template <typename T>
inline detail::tquat<T> normalize
(
detail::tquat<T> const & q
)
{
T len = static_cast<T>(length(q));
if(len <= 0) // Problem
return detail::tquat<T>(1, 0, 0, 0);
T oneOverLen = 1 / len;
return detail::tquat<T>(q.w * oneOverLen, q.x * oneOverLen, q.y * oneOverLen, q.z * oneOverLen);
}
template <typename valType>
inline valType dot
(
detail::tquat<valType> const & q1,
detail::tquat<valType> const & q2
)
{
return q1.x * q2.x + q1.y * q2.y + q1.z * q2.z + q1.w * q2.w;
}
template <typename valType>
inline detail::tquat<valType> cross
(
detail::tquat<valType> const & q1,
detail::tquat<valType> const & q2
)
{
return detail::tquat<valType>(
q1.w * q2.w - q1.x * q2.x - q1.y * q2.y - q1.z * q2.z,
q1.w * q2.x + q1.x * q2.w + q1.y * q2.z - q1.z * q2.y,
q1.w * q2.y + q1.y * q2.w + q1.z * q2.x - q1.x * q2.z,
q1.w * q2.z + q1.z * q2.w + q1.x * q2.y - q1.y * q2.x);
}
template <typename T>
inline detail::tquat<T> mix
(
detail::tquat<T> const & x,
detail::tquat<T> const & y,
T const & a
)
{
if(a <= T(0)) return x;
if(a >= T(1)) return y;
float fCos = dot(x, y);
detail::tquat<T> y2(y); //BUG!!! tquat<T> y2;
if(fCos < T(0))
{
y2 = -y;
fCos = -fCos;
}
//if(fCos > 1.0f) // problem
float k0, k1;
if(fCos > T(0.9999))
{
k0 = T(1) - a;
k1 = T(0) + a; //BUG!!! 1.0f + a;
}
else
{
T fSin = sqrt(T(1) - fCos * fCos);
T fAngle = atan(fSin, fCos);
T fOneOverSin = T(1) / fSin;
k0 = sin((T(1) - a) * fAngle) * fOneOverSin;
k1 = sin((T(0) + a) * fAngle) * fOneOverSin;
}
return detail::tquat<T>(
k0 * x.w + k1 * y2.w,
k0 * x.x + k1 * y2.x,
k0 * x.y + k1 * y2.y,
k0 * x.z + k1 * y2.z);
}
template <typename valType>
inline detail::tquat<valType> conjugate
(
detail::tquat<valType> const & q
)
{
return detail::tquat<valType>(q.w, -q.x, -q.y, -q.z);
}
template <typename valType>
inline detail::tquat<valType> inverse
(
detail::tquat<valType> const & q
)
{
return gtc::quaternion::conjugate(q) / gtc::quaternion::length(q);
}
template <typename valType>
inline detail::tquat<valType> rotate
(
detail::tquat<valType> const & q,
valType const & angle,
detail::tvec3<valType> const & v
)
{
detail::tvec3<valType> Tmp = v;
// Axis of rotation must be normalised
valType len = glm::core::function::geometric::length(Tmp);
if(abs(len - valType(1)) > valType(0.001))
{
valType oneOverLen = valType(1) / len;
Tmp.x *= oneOverLen;
Tmp.y *= oneOverLen;
Tmp.z *= oneOverLen;
}
valType AngleRad = radians(angle);
valType fSin = sin(AngleRad * valType(0.5));
return gtc::quaternion::cross(q, detail::tquat<valType>(cos(AngleRad * valType(0.5)), Tmp.x * fSin, Tmp.y * fSin, Tmp.z * fSin));
}
template <typename valType>
inline detail::tmat3x3<valType> mat3_cast
(
detail::tquat<valType> const & q
)
{
detail::tmat3x3<valType> Result(valType(1));
Result[0][0] = 1 - 2 * q.y * q.y - 2 * q.z * q.z;
Result[0][1] = 2 * q.x * q.y + 2 * q.w * q.z;
Result[0][2] = 2 * q.x * q.z - 2 * q.w * q.y;
Result[1][0] = 2 * q.x * q.y - 2 * q.w * q.z;
Result[1][1] = 1 - 2 * q.x * q.x - 2 * q.z * q.z;
Result[1][2] = 2 * q.y * q.z + 2 * q.w * q.x;
Result[2][0] = 2 * q.x * q.z + 2 * q.w * q.y;
Result[2][1] = 2 * q.y * q.z - 2 * q.w * q.x;
Result[2][2] = 1 - 2 * q.x * q.x - 2 * q.y * q.y;
return Result;
}
template <typename valType>
inline detail::tmat4x4<valType> mat4_cast
(
detail::tquat<valType> const & q
)
{
return detail::tmat4x4<valType>(mat3_cast(q));
}
template <typename T>
inline detail::tquat<T> quat_cast
(
detail::tmat3x3<T> const & m
)
{
T fourXSquaredMinus1 = m[0][0] - m[1][1] - m[2][2];
T fourYSquaredMinus1 = m[1][1] - m[0][0] - m[2][2];
T fourZSquaredMinus1 = m[2][2] - m[0][0] - m[1][1];
T fourWSquaredMinus1 = m[0][0] + m[1][1] + m[2][2];
int biggestIndex = 0;
T fourBiggestSquaredMinus1 = fourWSquaredMinus1;
if(fourXSquaredMinus1 > fourBiggestSquaredMinus1)
{
fourBiggestSquaredMinus1 = fourXSquaredMinus1;
biggestIndex = 1;
}
if(fourYSquaredMinus1 > fourBiggestSquaredMinus1)
{
fourBiggestSquaredMinus1 = fourYSquaredMinus1;
biggestIndex = 2;
}
if(fourZSquaredMinus1 > fourBiggestSquaredMinus1)
{
fourBiggestSquaredMinus1 = fourZSquaredMinus1;
biggestIndex = 3;
}
T biggestVal = sqrt(fourBiggestSquaredMinus1 + T(1)) * T(0.5);
T mult = T(0.25) / biggestVal;
detail::tquat<T> Result;
switch(biggestIndex)
{
case 0:
Result.w = biggestVal;
Result.x = (m[1][2] - m[2][1]) * mult;
Result.y = (m[2][0] - m[0][2]) * mult;
Result.z = (m[0][1] - m[1][0]) * mult;
break;
case 1:
Result.w = (m[1][2] - m[2][1]) * mult;
Result.x = biggestVal;
Result.y = (m[0][1] + m[1][0]) * mult;
Result.z = (m[2][1] + m[1][2]) * mult;
break;
case 2:
Result.w = (m[2][0] - m[0][2]) * mult;
Result.x = (m[0][1] + m[1][0]) * mult;
Result.y = biggestVal;
Result.z = (m[1][2] + m[2][1]) * mult;
break;
case 3:
Result.w = (m[0][1] - m[1][0]) * mult;
Result.x = (m[2][0] + m[0][2]) * mult;
Result.y = (m[1][2] + m[2][1]) * mult;
Result.z = biggestVal;
break;
}
return Result;
}
template <typename valType>
inline detail::tquat<valType> quat_cast
(
detail::tmat4x4<valType> const & m4
)
{
return quat_cast(detail::tmat3x3<valType>(m4));
}
}//namespace quaternion
}//namespace gtc
}//namespace glm
| [
"[email protected]"
]
| [
[
[
1,
481
]
]
]
|
8e25119d404f1f3015712a773cbdbea8ab576fb7 | 27c6eed99799f8398fe4c30df2088f30ae317aff | /rtt-tool/qdoc3/jambiapiparser.h | fb6770908fa0759d2392fd194117bf3454110df2 | []
| no_license | lit-uriy/ysoft | ae67cd174861e610f7e1519236e94ffb4d350249 | 6c3f077ff00c8332b162b4e82229879475fc8f97 | refs/heads/master | 2021-01-10T08:16:45.115964 | 2009-07-16T00:27:01 | 2009-07-16T00:27:01 | 51,699,806 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,464 | h | /****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the tools applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
/*
jambiapiparser.h
*/
#ifndef JAMBIAPIPARSER_H
#define JAMBIAPIPARSER_H
#include <QStack>
#include <QXmlDefaultHandler>
#include "codeparser.h"
QT_BEGIN_NAMESPACE
struct ClassOrEnumInfo
{
QString tag;
QString javaName;
QString cppName;
Node *javaNode;
Node *cppNode;
ClassOrEnumInfo() : javaNode(0), cppNode(0) {}
};
class JambiApiParser : public CodeParser, private QXmlDefaultHandler
{
public:
JambiApiParser(Tree *cppTree);
~JambiApiParser();
void initializeParser(const Config &config);
void terminateParser();
QString language();
QString sourceFileNameFilter();
void parseSourceFile(const Location &location, const QString &filePath, Tree *tree);
virtual void doneParsingSourceFiles(Tree *tree);
private:
bool startElement(const QString &namespaceURI, const QString &localName,
const QString &qName, const QXmlAttributes &attributes);
bool endElement(const QString &namespaceURI, const QString &localName,
const QString &qName);
bool fatalError(const QXmlParseException &exception);
void jambifyDocsPass2(Node *node);
bool makeFunctionNode(InnerNode *parent, const QString &synopsis, FunctionNode **funcPtr);
Tree *cppTre;
Tree *javaTre;
bool metJapiTag;
Location japiLocation;
QStack<ClassOrEnumInfo> classAndEnumStack;
};
QT_END_NAMESPACE
#endif
| [
"lit-uriy@d7ba3245-3e7b-42d0-9cd4-356c8b94b330"
]
| [
[
[
1,
99
]
]
]
|
f85c5bda70f9c81fa1bd4cdb60151b6a6e346ce9 | bdb8fc8eb5edc84cf92ba80b8541ba2b6c2b0918 | /TPs CPOO/Gareth & Maxime/Projet/CanonNoir_Moteur_C++/fichiers/AttenteDeplacement.cpp | 79da88196b973e9c87b0705b2df00795cf4c120a | []
| no_license | Issam-Engineer/tp4infoinsa | 3538644b40d19375b6bb25f030580004ed4a056d | 1576c31862ffbc048890e72a81efa11dba16338b | refs/heads/master | 2021-01-10T17:53:31.102683 | 2011-01-27T07:46:51 | 2011-01-27T07:46:51 | 55,446,817 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,547 | cpp | /**
*\file AttenteDeplacement.cpp
*\brief File containing the functionalities and the attributes of the AttenteDeplacement class
*\author Maxime HAVEZ
*\author Gareth THIVEUX
*\version 1.0
*/
#include "AttenteDeplacement.h"
#include "Joueur.h"
#include "Plateau.h"
AttenteDeplacement::AttenteDeplacement(MoteurJeu * m){
motor=m;
cout << "Constructeur : AttenteDeplacement" << endl;
}
void AttenteDeplacement::execute(){
cout<<"AttenteDeplacement.execute()"<<endl;
int x = motor->getFacade()->getX();
int y = motor->getFacade()->getY();
cout<<"x = "<<x<<endl;
cout<<"y = "<<y<<endl;
motor->getJoueurInd(motor->getJCourant())->getBateauCourant()->positionner(motor->getPlateau()->getCase(make_pair(x,y)));
motor->getFacade()->setCoulBateauCourant(motor->getJoueurInd(motor->getJCourant())->getBateauCourant()->getCouleur());
Bateau* boc = motor->getJoueurInd(motor->getJCourant())->getBateauCourant();
// QUEL EST L'ETAT SUIVANT ?
int ETAT_SUIVANT;
ETAT_SUIVANT = motor->getCase(x,y)->getEtat();
if(ETAT_SUIVANT != -1){
motor->modifCourant(ETAT_SUIVANT);
cout<<"ModifCourant(ETAT_SUIVANT) avec ETAT_SUIVANT = "<<ETAT_SUIVANT<<endl;
if(ETAT_SUIVANT != ATTENTECHOIXBATVISE && ETAT_SUIVANT != ETATTRESOR && ETAT_SUIVANT != ETATDEPOT){
motor->getFacade()->execute();
}
} else {
motor->setJCourant((motor->getJCourant()+1)%(motor->getNbJoueurs()));
motor->modifCourant(ATTENTELANCERDE);
motor->getFacade()->setEnableClicDe(true);
}
//boc->setCourant(false);
} | [
"havez.maxime.01@9f3b02c3-fd90-5378-97a3-836ae78947c6",
"garethiveux@9f3b02c3-fd90-5378-97a3-836ae78947c6"
]
| [
[
[
1,
1
],
[
3,
19
],
[
21,
26
],
[
30,
35
],
[
40,
41
],
[
49,
50
]
],
[
[
2,
2
],
[
20,
20
],
[
27,
29
],
[
36,
39
],
[
42,
48
]
]
]
|
9cacebe86d7745909c99fbf6287b26a70c3e658d | b7b58c5e83ae0e868414e8a6900b92fcfa87b4b1 | /Tools/FindSame/find.cpp | cde324c11f6bbb4d0cf9313018dbed6e138ca4c8 | []
| no_license | dailongao/cheat-fusion | 87df8bd58845f30808600b72167ff6c778a36245 | ab7cd0fe56df0edabb9064da70b93a2856df7fac | refs/heads/master | 2021-01-10T12:42:37.958692 | 2010-12-31T13:42:51 | 2010-12-31T13:42:51 | 51,513,373 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,939 | cpp | //将重复文本打上〓标记
//2s
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
#include <dirent.h>
#include <vector>
using namespace std;
#define ORGDIR "txt\\"
#define CONVDIR "checked\\%s"
typedef struct _block_attr{
char filename[32];
int num;
int poolpos;
}block_attr;
vector<block_attr> table[65536];
char *pool;
char buffer[1*1024*1024];
char write_buffer[1*1024*1024];
int findrepeat(char *s, char *repeatfilename, int *repeatnum)
{
block_attr block;
unsigned short byte=((unsigned short)s[0])*256+(unsigned short)s[1];
for( int lcv = 0; lcv < table[byte].size(); lcv++ ){
block=table[byte][lcv];
if(strcmp(pool+block.poolpos,s)==0){
strcpy(repeatfilename,block.filename);
*repeatnum=block.num;
return 0;
}
}
return -1;
}
int main(){
char *s,readtxt_buffer[1000],filename[100];
unsigned int i,j,number,flag;
int blknum,pos=0;
block_attr block;
FILE *txt_fp,*convert_fp;
DIR *dir;
struct dirent *p;
pool=(char*)malloc(20*1024*1024);
mkdir("checked\\");
time_t start,finish;
start=time(NULL);
dir=opendir(ORGDIR);
while( (p=readdir(dir))!=NULL )
{
if(p->d_name[0]=='.') continue;
strcpy(filename,ORGDIR);
strcat(filename,p->d_name);
if((txt_fp=fopen(filename,"rt"))==NULL){
printf("error on open %s!\n",p->d_name);
continue;
}
strcpy(block.filename,p->d_name);
*strrchr(block.filename,'.')=0;
block.poolpos=pos;
block.num=1;
blknum=1;
sprintf(filename,CONVDIR,p->d_name);
convert_fp=fopen(filename,"wt");
fgets(readtxt_buffer,990,txt_fp);
while(!feof(txt_fp)){
//遇到一个"#### "符号
if(strstr(readtxt_buffer,"#### ")){
strcpy(buffer,readtxt_buffer);
write_buffer[0]=0;
block.poolpos=pos;
block.num=blknum;
}
fgets(readtxt_buffer,990,txt_fp);
//读取文本直到遇上下一个"#### "符号或者文件结束,说明该段文本结束
while( !strstr(readtxt_buffer,"#### ") && !feof(txt_fp) ){
strcat(write_buffer,readtxt_buffer);
fgets(readtxt_buffer,990,txt_fp);
}
int testnum;
char testfile[32];
unsigned short byte=(unsigned short)write_buffer[0]*256+(unsigned short)write_buffer[1];
if(findrepeat(write_buffer,testfile,&testnum)==0){
sprintf(filename,"〓%s-%d\n",testfile,testnum);
strcat(buffer,filename);
}
else{
memcpy(pool+pos,write_buffer,strlen(write_buffer)+1);
pos+=strlen(write_buffer)+1;
table[byte].push_back(block);
}
strcat(buffer,write_buffer);
fputs(buffer,convert_fp);
blknum++;
}
fclose(txt_fp);
fclose(convert_fp);
printf("%s converted!\n",p->d_name);
}
closedir(dir);
free(pool);
finish=time(NULL);
printf("finish converting,%d bytes\n",pos);
printf(" %f Secs\n",difftime(finish,start));getch();
return 1;
}
| [
"forbbsneo@1e91e87a-c719-11dd-86c2-0f8696b7b6f9"
]
| [
[
[
1,
124
]
]
]
|
d3b7a10e26c3184caaeaf6dceca16aaa6923d0d1 | fb16850c6d70f89751d75413b9c16a7a72821c39 | /src/modules/graphics/opengl/wrap_Font.cpp | 5191f0b18a7ec76b9268c30ebd71a5b51cb9912c | [
"Zlib"
]
| permissive | tst2005/love | b5e852cc538c957e773cdf14f76d71263887f066 | bdec6facdf6054d24c89bea10b1f6146d89da11f | refs/heads/master | 2021-01-15T12:36:17.510573 | 2010-05-23T22:30:38 | 2010-05-23T22:30:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,140 | cpp | /**
* Copyright (c) 2006-2010 LOVE Development 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.
**/
// LOVE
#include "wrap_Font.h"
namespace love
{
namespace graphics
{
namespace opengl
{
Font * luax_checkfont(lua_State * L, int idx)
{
return luax_checktype<Font>(L, idx, "Font", GRAPHICS_FONT_T);
}
int w_Font_getHeight(lua_State * L)
{
Font * t = luax_checkfont(L, 1);
lua_pushnumber(L, t->getHeight());
return 1;
}
int w_Font_getWidth(lua_State * L)
{
Font * t = luax_checkfont(L, 1);
const char * str = luaL_checkstring(L, 2);
lua_pushinteger(L, t->getWidth(str));
return 1;
}
int w_Font_setLineHeight(lua_State * L)
{
Font * t = luax_checkfont(L, 1);
float h = (float)luaL_checknumber(L, 2);
t->setLineHeight(h);
return 0;
}
int w_Font_getLineHeight(lua_State * L)
{
Font * t = luax_checkfont(L, 1);
lua_pushnumber(L, t->getLineHeight());
return 1;
}
static const luaL_Reg functions[] = {
{ "getHeight", w_Font_getHeight },
{ "getWidth", w_Font_getWidth },
{ "setLineHeight", w_Font_setLineHeight },
{ "getLineHeight", w_Font_getLineHeight },
{ 0, 0 }
};
int luaopen_font(lua_State * L)
{
return luax_register_type(L, "Font", functions);
}
} // opengl
} // graphics
} // love
| [
"none@none",
"[email protected]"
]
| [
[
[
1,
45
],
[
47,
80
]
],
[
[
46,
46
]
]
]
|
1534bd9003d526c3b6b6a7f7695699b2e92682ab | 4d5ee0b6f7be0c3841c050ed1dda88ec128ae7b4 | /src/nvmesh/export/MeshExportOBJ.h | c85e077db320548db9cc51a70a0742db8a0611c7 | []
| no_license | saggita/nvidia-mesh-tools | 9df27d41b65b9742a9d45dc67af5f6835709f0c2 | a9b7fdd808e6719be88520e14bc60d58ea57e0bd | refs/heads/master | 2020-12-24T21:37:11.053752 | 2010-09-03T01:39:02 | 2010-09-03T01:39:02 | 56,893,300 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 421 | h | // This code is in the public domain -- [email protected]
#ifndef NV_MESH_EXPORTOBJ_H
#define NV_MESH_EXPORTOBJ_H
#include <nvmesh/nvmesh.h>
namespace nv
{
class Stream;
namespace HalfEdge { class Mesh; }
bool exportMesh(const HalfEdge::Mesh * mesh, const char * name);
bool exportMesh_OBJ(const HalfEdge::Mesh * mesh, Stream * stream);
} // nv namespace
#endif // NV_MESH_EXPORTOBJ_H
| [
"castano@0f2971b0-9fc2-11dd-b4aa-53559073bf4c"
]
| [
[
[
1,
19
]
]
]
|
d295dae2eafb80ea005b291cb03cfb817ed5c82b | fac8de123987842827a68da1b580f1361926ab67 | /inc/physics/Physics/Utilities/VisualDebugger/Viewer/hkpShapeDisplayBuilder.h | b2e3c001fd57fec5792267f5730ec7e581046e57 | []
| no_license | blockspacer/transporter-game | 23496e1651b3c19f6727712a5652f8e49c45c076 | 083ae2ee48fcab2c7d8a68670a71be4d09954428 | refs/heads/master | 2021-05-31T04:06:07.101459 | 2009-02-19T20:59:59 | 2009-02-19T20:59:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,292 | h | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#ifndef HK_COLLIDE2_SHAPE_DISPLAY_BUILDER_H
#define HK_COLLIDE2_SHAPE_DISPLAY_BUILDER_H
#include <Common/Base/hkBase.h>
#include <Physics/Collide/Shape/hkpShapeType.h>
class hkpCollidable;
class hkDisplayGeometry;
class hkpShape;
/// A utility class that creates hkDisplayGeometrys from hkCollidables and hkShapes.
/// This class is used by the hkpShapeDisplayViewer.
class hkpShapeDisplayBuilder: public hkReferencedObject
{
public:
HK_DECLARE_CLASS_ALLOCATOR(HK_MEMORY_CLASS_VDB);
struct hkpShapeDisplayBuilderEnvironment
{
HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_VDB, hkpShapeDisplayBuilder::hkpShapeDisplayBuilderEnvironment );
hkpShapeDisplayBuilderEnvironment();
int m_spherePhiRes;
int m_sphereThetaRes;
};
hkpShapeDisplayBuilder(const hkpShapeDisplayBuilderEnvironment& env);
/// Creates an array of display geometries from a given shape.
void buildDisplayGeometries( const hkpShape* shape,
hkArray<hkDisplayGeometry*>& displayGeometries);
/// Creates an array of display geometries from a given shape and a transform.
void buildShapeDisplay( const hkpShape* shape,
const hkTransform& transform,
hkArray<hkDisplayGeometry*>& displayGeometries);
/// Clears the current raw geometry. A temporary geometry is used to
/// create display geometries triangle by triangle from a MOPP for example.
void resetCurrentRawGeometry();
/// Convert a geometry and send it to the hkDebugDisplay
static void HK_CALL addObjectToDebugDisplay( const hkpShape* shape, hkTransform& t, hkUlong id );
protected:
hkDisplayGeometry* getCurrentRawGeometry(hkArray<hkDisplayGeometry*>& displayGeometries);
protected:
hkpShapeDisplayBuilderEnvironment m_environment;
hkDisplayGeometry* m_currentGeometry;
};
class hkpUserShapeDisplayBuilder : public hkReferencedObject, public hkSingleton< hkpUserShapeDisplayBuilder >
{
//+vtable(true)
public:
hkpUserShapeDisplayBuilder() {}
/// A function to build display geometries for user shapes. The function is expected to add hkDisplayGeometry objects
/// to the displayGeometries list. It may call back the hkpShapeDisplayBuilder::buildDisplayGeometries() method on the
/// builder object passed in to achieve this.
typedef void (HK_CALL *ShapeBuilderFunction)( const hkpShape* shape,
const hkTransform& transform,
hkArray<hkDisplayGeometry*>& displayGeometries,
hkpShapeDisplayBuilder* builder );
/// You can register functions to build display for your own user types with the shape display builder using this method
void registerUserShapeDisplayBuilder( ShapeBuilderFunction f, hkpShapeType type );
public:
struct UserShapeBuilder
{
HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_VDB, hkpUserShapeDisplayBuilder::UserShapeBuilder );
ShapeBuilderFunction f;
hkpShapeType type;
};
hkArray< UserShapeBuilder > m_userShapeBuilders;
};
#endif // HK_COLLIDE2_SHAPE_DISPLAY_BUILDER_H
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529)
*
* Confidential Information of Havok. (C) Copyright 1999-2008
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at
* www.havok.com/tryhavok
*
*/
| [
"uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4"
]
| [
[
[
1,
113
]
]
]
|
5ee884ea55bcba667cf2d11c563754c6101bfa59 | d54d8b1bbc9575f3c96853e0c67f17c1ad7ab546 | /hlsdk-2.3-p3/multiplayer/dlls/sound.cpp | e4cbc97d25632bf9e4722631f2ce21f91def002e | []
| no_license | joropito/amxxgroup | 637ee71e250ffd6a7e628f77893caef4c4b1af0a | f948042ee63ebac6ad0332f8a77393322157fa8f | refs/heads/master | 2021-01-10T09:21:31.449489 | 2010-04-11T21:34:27 | 2010-04-11T21:34:27 | 47,087,485 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 52,086 | cpp | /***
*
* Copyright (c) 1996-2002, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
//=========================================================
// sound.cpp
//=========================================================
#include "extdll.h"
#include "util.h"
#include "cbase.h"
#include "weapons.h"
#include "player.h"
#include "talkmonster.h"
#include "gamerules.h"
static char *memfgets( byte *pMemFile, int fileSize, int &filePos, char *pBuffer, int bufferSize );
// ==================== GENERIC AMBIENT SOUND ======================================
// runtime pitch shift and volume fadein/out structure
// NOTE: IF YOU CHANGE THIS STRUCT YOU MUST CHANGE THE SAVE/RESTORE VERSION NUMBER
// SEE BELOW (in the typedescription for the class)
typedef struct dynpitchvol
{
// NOTE: do not change the order of these parameters
// NOTE: unless you also change order of rgdpvpreset array elements!
int preset;
int pitchrun; // pitch shift % when sound is running 0 - 255
int pitchstart; // pitch shift % when sound stops or starts 0 - 255
int spinup; // spinup time 0 - 100
int spindown; // spindown time 0 - 100
int volrun; // volume change % when sound is running 0 - 10
int volstart; // volume change % when sound stops or starts 0 - 10
int fadein; // volume fade in time 0 - 100
int fadeout; // volume fade out time 0 - 100
// Low Frequency Oscillator
int lfotype; // 0) off 1) square 2) triangle 3) random
int lforate; // 0 - 1000, how fast lfo osciallates
int lfomodpitch; // 0-100 mod of current pitch. 0 is off.
int lfomodvol; // 0-100 mod of current volume. 0 is off.
int cspinup; // each trigger hit increments counter and spinup pitch
int cspincount;
int pitch;
int spinupsav;
int spindownsav;
int pitchfrac;
int vol;
int fadeinsav;
int fadeoutsav;
int volfrac;
int lfofrac;
int lfomult;
} dynpitchvol_t;
#define CDPVPRESETMAX 27
// presets for runtime pitch and vol modulation of ambient sounds
dynpitchvol_t rgdpvpreset[CDPVPRESETMAX] =
{
// pitch pstart spinup spindwn volrun volstrt fadein fadeout lfotype lforate modptch modvol cspnup
{1, 255, 75, 95, 95, 10, 1, 50, 95, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0},
{2, 255, 85, 70, 88, 10, 1, 20, 88, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0},
{3, 255, 100, 50, 75, 10, 1, 10, 75, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0},
{4, 100, 100, 0, 0, 10, 1, 90, 90, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0},
{5, 100, 100, 0, 0, 10, 1, 80, 80, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0},
{6, 100, 100, 0, 0, 10, 1, 50, 70, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0},
{7, 100, 100, 0, 0, 5, 1, 40, 50, 1, 50, 0, 10, 0, 0,0,0,0,0,0,0,0,0,0},
{8, 100, 100, 0, 0, 5, 1, 40, 50, 1, 150, 0, 10, 0, 0,0,0,0,0,0,0,0,0,0},
{9, 100, 100, 0, 0, 5, 1, 40, 50, 1, 750, 0, 10, 0, 0,0,0,0,0,0,0,0,0,0},
{10,128, 100, 50, 75, 10, 1, 30, 40, 2, 8, 20, 0, 0, 0,0,0,0,0,0,0,0,0,0},
{11,128, 100, 50, 75, 10, 1, 30, 40, 2, 25, 20, 0, 0, 0,0,0,0,0,0,0,0,0,0},
{12,128, 100, 50, 75, 10, 1, 30, 40, 2, 70, 20, 0, 0, 0,0,0,0,0,0,0,0,0,0},
{13,50, 50, 0, 0, 10, 1, 20, 50, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0},
{14,70, 70, 0, 0, 10, 1, 20, 50, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0},
{15,90, 90, 0, 0, 10, 1, 20, 50, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0},
{16,120, 120, 0, 0, 10, 1, 20, 50, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0},
{17,180, 180, 0, 0, 10, 1, 20, 50, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0},
{18,255, 255, 0, 0, 10, 1, 20, 50, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0},
{19,200, 75, 90, 90, 10, 1, 50, 90, 2, 100, 20, 0, 0, 0,0,0,0,0,0,0,0,0,0},
{20,255, 75, 97, 90, 10, 1, 50, 90, 1, 40, 50, 0, 0, 0,0,0,0,0,0,0,0,0,0},
{21,100, 100, 0, 0, 10, 1, 30, 50, 3, 15, 20, 0, 0, 0,0,0,0,0,0,0,0,0,0},
{22,160, 160, 0, 0, 10, 1, 50, 50, 3, 500, 25, 0, 0, 0,0,0,0,0,0,0,0,0,0},
{23,255, 75, 88, 0, 10, 1, 40, 0, 0, 0, 0, 0, 5, 0,0,0,0,0,0,0,0,0,0},
{24,200, 20, 95, 70, 10, 1, 70, 70, 3, 20, 50, 0, 0, 0,0,0,0,0,0,0,0,0,0},
{25,180, 100, 50, 60, 10, 1, 40, 60, 2, 90, 100, 100, 0, 0,0,0,0,0,0,0,0,0,0},
{26,60, 60, 0, 0, 10, 1, 40, 70, 3, 80, 20, 50, 0, 0,0,0,0,0,0,0,0,0,0},
{27,128, 90, 10, 10, 10, 1, 20, 40, 1, 5, 10, 20, 0, 0,0,0,0,0,0,0,0,0,0}
};
class CAmbientGeneric : public CBaseEntity
{
public:
void KeyValue( KeyValueData* pkvd);
void Spawn( void );
void Precache( void );
void EXPORT ToggleUse ( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value );
void EXPORT RampThink( void );
void InitModulationParms(void);
virtual int Save( CSave &save );
virtual int Restore( CRestore &restore );
static TYPEDESCRIPTION m_SaveData[];
virtual int ObjectCaps( void ) { return (CBaseEntity :: ObjectCaps() & ~FCAP_ACROSS_TRANSITION); }
float m_flAttenuation; // attenuation value
dynpitchvol_t m_dpv;
BOOL m_fActive; // only TRUE when the entity is playing a looping sound
BOOL m_fLooping; // TRUE when the sound played will loop
};
LINK_ENTITY_TO_CLASS( ambient_generic, CAmbientGeneric );
TYPEDESCRIPTION CAmbientGeneric::m_SaveData[] =
{
DEFINE_FIELD( CAmbientGeneric, m_flAttenuation, FIELD_FLOAT ),
DEFINE_FIELD( CAmbientGeneric, m_fActive, FIELD_BOOLEAN ),
DEFINE_FIELD( CAmbientGeneric, m_fLooping, FIELD_BOOLEAN ),
// HACKHACK - This is not really in the spirit of the save/restore design, but save this
// out as a binary data block. If the dynpitchvol_t is changed, old saved games will NOT
// load these correctly, so bump the save/restore version if you change the size of the struct
// The right way to do this is to split the input parms (read in keyvalue) into members and re-init this
// struct in Precache(), but it's unlikely that the struct will change, so it's not worth the time right now.
DEFINE_ARRAY( CAmbientGeneric, m_dpv, FIELD_CHARACTER, sizeof(dynpitchvol_t) ),
};
IMPLEMENT_SAVERESTORE( CAmbientGeneric, CBaseEntity );
//
// ambient_generic - general-purpose user-defined static sound
//
void CAmbientGeneric :: Spawn( void )
{
/*
-1 : "Default"
0 : "Everywhere"
200 : "Small Radius"
125 : "Medium Radius"
80 : "Large Radius"
*/
if ( FBitSet ( pev->spawnflags, AMBIENT_SOUND_EVERYWHERE) )
{
m_flAttenuation = ATTN_NONE;
}
else if ( FBitSet ( pev->spawnflags, AMBIENT_SOUND_SMALLRADIUS) )
{
m_flAttenuation = ATTN_IDLE;
}
else if ( FBitSet ( pev->spawnflags, AMBIENT_SOUND_MEDIUMRADIUS) )
{
m_flAttenuation = ATTN_STATIC;
}
else if ( FBitSet ( pev->spawnflags, AMBIENT_SOUND_LARGERADIUS) )
{
m_flAttenuation = ATTN_NORM;
}
else
{// if the designer didn't set a sound attenuation, default to one.
m_flAttenuation = ATTN_STATIC;
}
char* szSoundFile = (char*) STRING(pev->message);
if ( FStringNull( pev->message ) || strlen( szSoundFile ) < 1 )
{
ALERT( at_error, "EMPTY AMBIENT AT: %f, %f, %f\n", pev->origin.x, pev->origin.y, pev->origin.z );
pev->nextthink = gpGlobals->time + 0.1;
SetThink( SUB_Remove );
return;
}
pev->solid = SOLID_NOT;
pev->movetype = MOVETYPE_NONE;
// Set up think function for dynamic modification
// of ambient sound's pitch or volume. Don't
// start thinking yet.
SetThink(RampThink);
pev->nextthink = 0;
// allow on/off switching via 'use' function.
SetUse ( ToggleUse );
m_fActive = FALSE;
if ( FBitSet ( pev->spawnflags, AMBIENT_SOUND_NOT_LOOPING ) )
m_fLooping = FALSE;
else
m_fLooping = TRUE;
Precache( );
}
void CAmbientGeneric :: Precache( void )
{
char* szSoundFile = (char*) STRING(pev->message);
if ( !FStringNull( pev->message ) && strlen( szSoundFile ) > 1 )
{
if (*szSoundFile != '!')
PRECACHE_SOUND(szSoundFile);
}
// init all dynamic modulation parms
InitModulationParms();
if ( !FBitSet (pev->spawnflags, AMBIENT_SOUND_START_SILENT ) )
{
// start the sound ASAP
if (m_fLooping)
m_fActive = TRUE;
}
if ( m_fActive )
{
UTIL_EmitAmbientSound ( ENT(pev), pev->origin, szSoundFile,
(m_dpv.vol * 0.01), m_flAttenuation, SND_SPAWNING, m_dpv.pitch);
pev->nextthink = gpGlobals->time + 0.1;
}
}
// RampThink - Think at 5hz if we are dynamically modifying
// pitch or volume of the playing sound. This function will
// ramp pitch and/or volume up or down, modify pitch/volume
// with lfo if active.
void CAmbientGeneric :: RampThink( void )
{
char* szSoundFile = (char*) STRING(pev->message);
int pitch = m_dpv.pitch;
int vol = m_dpv.vol;
int flags = 0;
int fChanged = 0; // FALSE if pitch and vol remain unchanged this round
int prev;
if (!m_dpv.spinup && !m_dpv.spindown && !m_dpv.fadein && !m_dpv.fadeout && !m_dpv.lfotype)
return; // no ramps or lfo, stop thinking
// ==============
// pitch envelope
// ==============
if (m_dpv.spinup || m_dpv.spindown)
{
prev = m_dpv.pitchfrac >> 8;
if (m_dpv.spinup > 0)
m_dpv.pitchfrac += m_dpv.spinup;
else if (m_dpv.spindown > 0)
m_dpv.pitchfrac -= m_dpv.spindown;
pitch = m_dpv.pitchfrac >> 8;
if (pitch > m_dpv.pitchrun)
{
pitch = m_dpv.pitchrun;
m_dpv.spinup = 0; // done with ramp up
}
if (pitch < m_dpv.pitchstart)
{
pitch = m_dpv.pitchstart;
m_dpv.spindown = 0; // done with ramp down
// shut sound off
UTIL_EmitAmbientSound(ENT(pev), pev->origin, szSoundFile,
0, 0, SND_STOP, 0);
// return without setting nextthink
return;
}
if (pitch > 255) pitch = 255;
if (pitch < 1) pitch = 1;
m_dpv.pitch = pitch;
fChanged |= (prev != pitch);
flags |= SND_CHANGE_PITCH;
}
// ==================
// amplitude envelope
// ==================
if (m_dpv.fadein || m_dpv.fadeout)
{
prev = m_dpv.volfrac >> 8;
if (m_dpv.fadein > 0)
m_dpv.volfrac += m_dpv.fadein;
else if (m_dpv.fadeout > 0)
m_dpv.volfrac -= m_dpv.fadeout;
vol = m_dpv.volfrac >> 8;
if (vol > m_dpv.volrun)
{
vol = m_dpv.volrun;
m_dpv.fadein = 0; // done with ramp up
}
if (vol < m_dpv.volstart)
{
vol = m_dpv.volstart;
m_dpv.fadeout = 0; // done with ramp down
// shut sound off
UTIL_EmitAmbientSound(ENT(pev), pev->origin, szSoundFile,
0, 0, SND_STOP, 0);
// return without setting nextthink
return;
}
if (vol > 100) vol = 100;
if (vol < 1) vol = 1;
m_dpv.vol = vol;
fChanged |= (prev != vol);
flags |= SND_CHANGE_VOL;
}
// ===================
// pitch/amplitude LFO
// ===================
if (m_dpv.lfotype)
{
int pos;
if (m_dpv.lfofrac > 0x6fffffff)
m_dpv.lfofrac = 0;
// update lfo, lfofrac/255 makes a triangle wave 0-255
m_dpv.lfofrac += m_dpv.lforate;
pos = m_dpv.lfofrac >> 8;
if (m_dpv.lfofrac < 0)
{
m_dpv.lfofrac = 0;
m_dpv.lforate = abs(m_dpv.lforate);
pos = 0;
}
else if (pos > 255)
{
pos = 255;
m_dpv.lfofrac = (255 << 8);
m_dpv.lforate = -abs(m_dpv.lforate);
}
switch(m_dpv.lfotype)
{
case LFO_SQUARE:
if (pos < 128)
m_dpv.lfomult = 255;
else
m_dpv.lfomult = 0;
break;
case LFO_RANDOM:
if (pos == 255)
m_dpv.lfomult = RANDOM_LONG(0, 255);
break;
case LFO_TRIANGLE:
default:
m_dpv.lfomult = pos;
break;
}
if (m_dpv.lfomodpitch)
{
prev = pitch;
// pitch 0-255
pitch += ((m_dpv.lfomult - 128) * m_dpv.lfomodpitch) / 100;
if (pitch > 255) pitch = 255;
if (pitch < 1) pitch = 1;
fChanged |= (prev != pitch);
flags |= SND_CHANGE_PITCH;
}
if (m_dpv.lfomodvol)
{
// vol 0-100
prev = vol;
vol += ((m_dpv.lfomult - 128) * m_dpv.lfomodvol) / 100;
if (vol > 100) vol = 100;
if (vol < 0) vol = 0;
fChanged |= (prev != vol);
flags |= SND_CHANGE_VOL;
}
}
// Send update to playing sound only if we actually changed
// pitch or volume in this routine.
if (flags && fChanged)
{
if (pitch == PITCH_NORM)
pitch = PITCH_NORM + 1; // don't send 'no pitch' !
UTIL_EmitAmbientSound(ENT(pev), pev->origin, szSoundFile,
(vol * 0.01), m_flAttenuation, flags, pitch);
}
// update ramps at 5hz
pev->nextthink = gpGlobals->time + 0.2;
return;
}
// Init all ramp params in preparation to
// play a new sound
void CAmbientGeneric :: InitModulationParms(void)
{
int pitchinc;
m_dpv.volrun = pev->health * 10; // 0 - 100
if (m_dpv.volrun > 100) m_dpv.volrun = 100;
if (m_dpv.volrun < 0) m_dpv.volrun = 0;
// get presets
if (m_dpv.preset != 0 && m_dpv.preset <= CDPVPRESETMAX)
{
// load preset values
m_dpv = rgdpvpreset[m_dpv.preset - 1];
// fixup preset values, just like
// fixups in KeyValue routine.
if (m_dpv.spindown > 0)
m_dpv.spindown = (101 - m_dpv.spindown) * 64;
if (m_dpv.spinup > 0)
m_dpv.spinup = (101 - m_dpv.spinup) * 64;
m_dpv.volstart *= 10;
m_dpv.volrun *= 10;
if (m_dpv.fadein > 0)
m_dpv.fadein = (101 - m_dpv.fadein) * 64;
if (m_dpv.fadeout > 0)
m_dpv.fadeout = (101 - m_dpv.fadeout) * 64;
m_dpv.lforate *= 256;
m_dpv.fadeinsav = m_dpv.fadein;
m_dpv.fadeoutsav = m_dpv.fadeout;
m_dpv.spinupsav = m_dpv.spinup;
m_dpv.spindownsav = m_dpv.spindown;
}
m_dpv.fadein = m_dpv.fadeinsav;
m_dpv.fadeout = 0;
if (m_dpv.fadein)
m_dpv.vol = m_dpv.volstart;
else
m_dpv.vol = m_dpv.volrun;
m_dpv.spinup = m_dpv.spinupsav;
m_dpv.spindown = 0;
if (m_dpv.spinup)
m_dpv.pitch = m_dpv.pitchstart;
else
m_dpv.pitch = m_dpv.pitchrun;
if (m_dpv.pitch == 0)
m_dpv.pitch = PITCH_NORM;
m_dpv.pitchfrac = m_dpv.pitch << 8;
m_dpv.volfrac = m_dpv.vol << 8;
m_dpv.lfofrac = 0;
m_dpv.lforate = abs(m_dpv.lforate);
m_dpv.cspincount = 1;
if (m_dpv.cspinup)
{
pitchinc = (255 - m_dpv.pitchstart) / m_dpv.cspinup;
m_dpv.pitchrun = m_dpv.pitchstart + pitchinc;
if (m_dpv.pitchrun > 255) m_dpv.pitchrun = 255;
}
if ((m_dpv.spinupsav || m_dpv.spindownsav || (m_dpv.lfotype && m_dpv.lfomodpitch))
&& (m_dpv.pitch == PITCH_NORM))
m_dpv.pitch = PITCH_NORM + 1; // must never send 'no pitch' as first pitch
// if we intend to pitch shift later!
}
//
// ToggleUse - turns an ambient sound on or off. If the
// ambient is a looping sound, mark sound as active (m_fActive)
// if it's playing, innactive if not. If the sound is not
// a looping sound, never mark it as active.
//
void CAmbientGeneric :: ToggleUse ( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value )
{
char* szSoundFile = (char*) STRING(pev->message);
float fraction;
if ( useType != USE_TOGGLE )
{
if ( (m_fActive && useType == USE_ON) || (!m_fActive && useType == USE_OFF) )
return;
}
// Directly change pitch if arg passed. Only works if sound is already playing.
if (useType == USE_SET && m_fActive) // Momentary buttons will pass down a float in here
{
fraction = value;
if ( fraction > 1.0 )
fraction = 1.0;
if (fraction < 0.0)
fraction = 0.01;
m_dpv.pitch = fraction * 255;
UTIL_EmitAmbientSound(ENT(pev), pev->origin, szSoundFile,
0, 0, SND_CHANGE_PITCH, m_dpv.pitch);
return;
}
// Toggle
// m_fActive is TRUE only if a looping sound is playing.
if ( m_fActive )
{// turn sound off
if (m_dpv.cspinup)
{
// Don't actually shut off. Each toggle causes
// incremental spinup to max pitch
if (m_dpv.cspincount <= m_dpv.cspinup)
{
int pitchinc;
// start a new spinup
m_dpv.cspincount++;
pitchinc = (255 - m_dpv.pitchstart) / m_dpv.cspinup;
m_dpv.spinup = m_dpv.spinupsav;
m_dpv.spindown = 0;
m_dpv.pitchrun = m_dpv.pitchstart + pitchinc * m_dpv.cspincount;
if (m_dpv.pitchrun > 255) m_dpv.pitchrun = 255;
pev->nextthink = gpGlobals->time + 0.1;
}
}
else
{
m_fActive = FALSE;
// HACKHACK - this makes the code in Precache() work properly after a save/restore
pev->spawnflags |= AMBIENT_SOUND_START_SILENT;
if (m_dpv.spindownsav || m_dpv.fadeoutsav)
{
// spin it down (or fade it) before shutoff if spindown is set
m_dpv.spindown = m_dpv.spindownsav;
m_dpv.spinup = 0;
m_dpv.fadeout = m_dpv.fadeoutsav;
m_dpv.fadein = 0;
pev->nextthink = gpGlobals->time + 0.1;
}
else
UTIL_EmitAmbientSound(ENT(pev), pev->origin, szSoundFile,
0, 0, SND_STOP, 0);
}
}
else
{// turn sound on
// only toggle if this is a looping sound. If not looping, each
// trigger will cause the sound to play. If the sound is still
// playing from a previous trigger press, it will be shut off
// and then restarted.
if (m_fLooping)
m_fActive = TRUE;
else
// shut sound off now - may be interrupting a long non-looping sound
UTIL_EmitAmbientSound(ENT(pev), pev->origin, szSoundFile,
0, 0, SND_STOP, 0);
// init all ramp params for startup
InitModulationParms();
UTIL_EmitAmbientSound(ENT(pev), pev->origin, szSoundFile,
(m_dpv.vol * 0.01), m_flAttenuation, 0, m_dpv.pitch);
pev->nextthink = gpGlobals->time + 0.1;
}
}
// KeyValue - load keyvalue pairs into member data of the
// ambient generic. NOTE: called BEFORE spawn!
void CAmbientGeneric :: KeyValue( KeyValueData *pkvd )
{
// NOTE: changing any of the modifiers in this code
// NOTE: also requires changing InitModulationParms code.
// preset
if (FStrEq(pkvd->szKeyName, "preset"))
{
m_dpv.preset = atoi(pkvd->szValue);
pkvd->fHandled = TRUE;
}
// pitchrun
else if (FStrEq(pkvd->szKeyName, "pitch"))
{
m_dpv.pitchrun = atoi(pkvd->szValue);
pkvd->fHandled = TRUE;
if (m_dpv.pitchrun > 255) m_dpv.pitchrun = 255;
if (m_dpv.pitchrun < 0) m_dpv.pitchrun = 0;
}
// pitchstart
else if (FStrEq(pkvd->szKeyName, "pitchstart"))
{
m_dpv.pitchstart = atoi(pkvd->szValue);
pkvd->fHandled = TRUE;
if (m_dpv.pitchstart > 255) m_dpv.pitchstart = 255;
if (m_dpv.pitchstart < 0) m_dpv.pitchstart = 0;
}
// spinup
else if (FStrEq(pkvd->szKeyName, "spinup"))
{
m_dpv.spinup = atoi(pkvd->szValue);
if (m_dpv.spinup > 100) m_dpv.spinup = 100;
if (m_dpv.spinup < 0) m_dpv.spinup = 0;
if (m_dpv.spinup > 0)
m_dpv.spinup = (101 - m_dpv.spinup) * 64;
m_dpv.spinupsav = m_dpv.spinup;
pkvd->fHandled = TRUE;
}
// spindown
else if (FStrEq(pkvd->szKeyName, "spindown"))
{
m_dpv.spindown = atoi(pkvd->szValue);
if (m_dpv.spindown > 100) m_dpv.spindown = 100;
if (m_dpv.spindown < 0) m_dpv.spindown = 0;
if (m_dpv.spindown > 0)
m_dpv.spindown = (101 - m_dpv.spindown) * 64;
m_dpv.spindownsav = m_dpv.spindown;
pkvd->fHandled = TRUE;
}
// volstart
else if (FStrEq(pkvd->szKeyName, "volstart"))
{
m_dpv.volstart = atoi(pkvd->szValue);
if (m_dpv.volstart > 10) m_dpv.volstart = 10;
if (m_dpv.volstart < 0) m_dpv.volstart = 0;
m_dpv.volstart *= 10; // 0 - 100
pkvd->fHandled = TRUE;
}
// fadein
else if (FStrEq(pkvd->szKeyName, "fadein"))
{
m_dpv.fadein = atoi(pkvd->szValue);
if (m_dpv.fadein > 100) m_dpv.fadein = 100;
if (m_dpv.fadein < 0) m_dpv.fadein = 0;
if (m_dpv.fadein > 0)
m_dpv.fadein = (101 - m_dpv.fadein) * 64;
m_dpv.fadeinsav = m_dpv.fadein;
pkvd->fHandled = TRUE;
}
// fadeout
else if (FStrEq(pkvd->szKeyName, "fadeout"))
{
m_dpv.fadeout = atoi(pkvd->szValue);
if (m_dpv.fadeout > 100) m_dpv.fadeout = 100;
if (m_dpv.fadeout < 0) m_dpv.fadeout = 0;
if (m_dpv.fadeout > 0)
m_dpv.fadeout = (101 - m_dpv.fadeout) * 64;
m_dpv.fadeoutsav = m_dpv.fadeout;
pkvd->fHandled = TRUE;
}
// lfotype
else if (FStrEq(pkvd->szKeyName, "lfotype"))
{
m_dpv.lfotype = atoi(pkvd->szValue);
if (m_dpv.lfotype > 4) m_dpv.lfotype = LFO_TRIANGLE;
pkvd->fHandled = TRUE;
}
// lforate
else if (FStrEq(pkvd->szKeyName, "lforate"))
{
m_dpv.lforate = atoi(pkvd->szValue);
if (m_dpv.lforate > 1000) m_dpv.lforate = 1000;
if (m_dpv.lforate < 0) m_dpv.lforate = 0;
m_dpv.lforate *= 256;
pkvd->fHandled = TRUE;
}
// lfomodpitch
else if (FStrEq(pkvd->szKeyName, "lfomodpitch"))
{
m_dpv.lfomodpitch = atoi(pkvd->szValue);
if (m_dpv.lfomodpitch > 100) m_dpv.lfomodpitch = 100;
if (m_dpv.lfomodpitch < 0) m_dpv.lfomodpitch = 0;
pkvd->fHandled = TRUE;
}
// lfomodvol
else if (FStrEq(pkvd->szKeyName, "lfomodvol"))
{
m_dpv.lfomodvol = atoi(pkvd->szValue);
if (m_dpv.lfomodvol > 100) m_dpv.lfomodvol = 100;
if (m_dpv.lfomodvol < 0) m_dpv.lfomodvol = 0;
pkvd->fHandled = TRUE;
}
// cspinup
else if (FStrEq(pkvd->szKeyName, "cspinup"))
{
m_dpv.cspinup = atoi(pkvd->szValue);
if (m_dpv.cspinup > 100) m_dpv.cspinup = 100;
if (m_dpv.cspinup < 0) m_dpv.cspinup = 0;
pkvd->fHandled = TRUE;
}
else
CBaseEntity::KeyValue( pkvd );
}
// =================== ROOM SOUND FX ==========================================
class CEnvSound : public CPointEntity
{
public:
void KeyValue( KeyValueData* pkvd);
void Spawn( void );
void Think( void );
virtual int Save( CSave &save );
virtual int Restore( CRestore &restore );
static TYPEDESCRIPTION m_SaveData[];
float m_flRadius;
float m_flRoomtype;
};
LINK_ENTITY_TO_CLASS( env_sound, CEnvSound );
TYPEDESCRIPTION CEnvSound::m_SaveData[] =
{
DEFINE_FIELD( CEnvSound, m_flRadius, FIELD_FLOAT ),
DEFINE_FIELD( CEnvSound, m_flRoomtype, FIELD_FLOAT ),
};
IMPLEMENT_SAVERESTORE( CEnvSound, CBaseEntity );
void CEnvSound :: KeyValue( KeyValueData *pkvd )
{
if (FStrEq(pkvd->szKeyName, "radius"))
{
m_flRadius = atof(pkvd->szValue);
pkvd->fHandled = TRUE;
}
if (FStrEq(pkvd->szKeyName, "roomtype"))
{
m_flRoomtype = atof(pkvd->szValue);
pkvd->fHandled = TRUE;
}
}
// returns TRUE if the given sound entity (pev) is in range
// and can see the given player entity (pevTarget)
BOOL FEnvSoundInRange(entvars_t *pev, entvars_t *pevTarget, float *pflRange)
{
CEnvSound *pSound = GetClassPtr( (CEnvSound *)pev );
Vector vecSpot1 = pev->origin + pev->view_ofs;
Vector vecSpot2 = pevTarget->origin + pevTarget->view_ofs;
Vector vecRange;
float flRange;
TraceResult tr;
UTIL_TraceLine(vecSpot1, vecSpot2, ignore_monsters, ENT(pev), &tr);
// check if line of sight crosses water boundary, or is blocked
if ((tr.fInOpen && tr.fInWater) || tr.flFraction != 1)
return FALSE;
// calc range from sound entity to player
vecRange = tr.vecEndPos - vecSpot1;
flRange = vecRange.Length();
if (pSound->m_flRadius < flRange)
return FALSE;
if (pflRange)
*pflRange = flRange;
return TRUE;
}
//
// A client that is visible and in range of a sound entity will
// have its room_type set by that sound entity. If two or more
// sound entities are contending for a client, then the nearest
// sound entity to the client will set the client's room_type.
// A client's room_type will remain set to its prior value until
// a new in-range, visible sound entity resets a new room_type.
//
// CONSIDER: if player in water state, autoset roomtype to 14,15 or 16.
void CEnvSound :: Think( void )
{
// get pointer to client if visible; FIND_CLIENT_IN_PVS will
// cycle through visible clients on consecutive calls.
edict_t *pentPlayer = FIND_CLIENT_IN_PVS(edict());
CBasePlayer *pPlayer = NULL;
if (FNullEnt(pentPlayer))
goto env_sound_Think_slow; // no player in pvs of sound entity, slow it down
pPlayer = GetClassPtr( (CBasePlayer *)VARS(pentPlayer));
float flRange;
// check to see if this is the sound entity that is
// currently affecting this player
if(!FNullEnt(pPlayer->m_pentSndLast) && (pPlayer->m_pentSndLast == ENT(pev))) {
// this is the entity currently affecting player, check
// for validity
if (pPlayer->m_flSndRoomtype != 0 && pPlayer->m_flSndRange != 0) {
// we're looking at a valid sound entity affecting
// player, make sure it's still valid, update range
if (FEnvSoundInRange(pev, VARS(pentPlayer), &flRange)) {
pPlayer->m_flSndRange = flRange;
goto env_sound_Think_fast;
} else {
// current sound entity affecting player is no longer valid,
// flag this state by clearing room_type and range.
// NOTE: we do not actually change the player's room_type
// NOTE: until we have a new valid room_type to change it to.
pPlayer->m_flSndRange = 0;
pPlayer->m_flSndRoomtype = 0;
goto env_sound_Think_slow;
}
} else {
// entity is affecting player but is out of range,
// wait passively for another entity to usurp it...
goto env_sound_Think_slow;
}
}
// if we got this far, we're looking at an entity that is contending
// for current player sound. the closest entity to player wins.
if (FEnvSoundInRange(pev, VARS(pentPlayer), &flRange))
{
if (flRange < pPlayer->m_flSndRange || pPlayer->m_flSndRange == 0)
{
// new entity is closer to player, so it wins.
pPlayer->m_pentSndLast = ENT(pev);
pPlayer->m_flSndRoomtype = m_flRoomtype;
pPlayer->m_flSndRange = flRange;
// send room_type command to player's server.
// this should be a rare event - once per change of room_type
// only!
//CLIENT_COMMAND(pentPlayer, "room_type %f", m_flRoomtype);
MESSAGE_BEGIN( MSG_ONE, SVC_ROOMTYPE, NULL, pentPlayer ); // use the magic #1 for "one client"
WRITE_SHORT( (short)m_flRoomtype ); // sequence number
MESSAGE_END();
// crank up nextthink rate for new active sound entity
// by falling through to think_fast...
}
// player is not closer to the contending sound entity,
// just fall through to think_fast. this effectively
// cranks up the think_rate of entities near the player.
}
// player is in pvs of sound entity, but either not visible or
// not in range. do nothing, fall through to think_fast...
env_sound_Think_fast:
pev->nextthink = gpGlobals->time + 0.25;
return;
env_sound_Think_slow:
pev->nextthink = gpGlobals->time + 0.75;
return;
}
//
// env_sound - spawn a sound entity that will set player roomtype
// when player moves in range and sight.
//
//
void CEnvSound :: Spawn( )
{
// spread think times
pev->nextthink = gpGlobals->time + RANDOM_FLOAT(0.0, 0.5);
}
// ==================== SENTENCE GROUPS, UTILITY FUNCTIONS ======================================
#define CSENTENCE_LRU_MAX 32 // max number of elements per sentence group
// group of related sentences
typedef struct sentenceg
{
char szgroupname[CBSENTENCENAME_MAX];
int count;
unsigned char rgblru[CSENTENCE_LRU_MAX];
} SENTENCEG;
#define CSENTENCEG_MAX 200 // max number of sentence groups
// globals
SENTENCEG rgsentenceg[CSENTENCEG_MAX];
int fSentencesInit = FALSE;
char gszallsentencenames[CVOXFILESENTENCEMAX][CBSENTENCENAME_MAX];
int gcallsentences = 0;
// randomize list of sentence name indices
void USENTENCEG_InitLRU(unsigned char *plru, int count)
{
int i, j, k;
unsigned char temp;
if (!fSentencesInit)
return;
if (count > CSENTENCE_LRU_MAX)
count = CSENTENCE_LRU_MAX;
for (i = 0; i < count; i++)
plru[i] = (unsigned char) i;
// randomize array
for (i = 0; i < (count * 4); i++)
{
j = RANDOM_LONG(0,count-1);
k = RANDOM_LONG(0,count-1);
temp = plru[j];
plru[j] = plru[k];
plru[k] = temp;
}
}
// ignore lru. pick next sentence from sentence group. Go in order until we hit the last sentence,
// then repeat list if freset is true. If freset is false, then repeat last sentence.
// ipick is passed in as the requested sentence ordinal.
// ipick 'next' is returned.
// return of -1 indicates an error.
int USENTENCEG_PickSequential(int isentenceg, char *szfound, int ipick, int freset)
{
char *szgroupname;
unsigned char count;
char sznum[8];
if (!fSentencesInit)
return -1;
if (isentenceg < 0)
return -1;
szgroupname = rgsentenceg[isentenceg].szgroupname;
count = rgsentenceg[isentenceg].count;
if (count == 0)
return -1;
if (ipick >= count)
ipick = count-1;
strcpy(szfound, "!");
strcat(szfound, szgroupname);
sprintf(sznum, "%d", ipick);
strcat(szfound, sznum);
if (ipick >= count)
{
if (freset)
// reset at end of list
return 0;
else
return count;
}
return ipick + 1;
}
// pick a random sentence from rootname0 to rootnameX.
// picks from the rgsentenceg[isentenceg] least
// recently used, modifies lru array. returns the sentencename.
// note, lru must be seeded with 0-n randomized sentence numbers, with the
// rest of the lru filled with -1. The first integer in the lru is
// actually the size of the list. Returns ipick, the ordinal
// of the picked sentence within the group.
int USENTENCEG_Pick(int isentenceg, char *szfound)
{
char *szgroupname;
unsigned char *plru;
unsigned char i;
unsigned char count;
char sznum[8];
unsigned char ipick;
int ffound = FALSE;
if (!fSentencesInit)
return -1;
if (isentenceg < 0)
return -1;
szgroupname = rgsentenceg[isentenceg].szgroupname;
count = rgsentenceg[isentenceg].count;
plru = rgsentenceg[isentenceg].rgblru;
while (!ffound)
{
for (i = 0; i < count; i++)
if (plru[i] != 0xFF)
{
ipick = plru[i];
plru[i] = 0xFF;
ffound = TRUE;
break;
}
if (!ffound)
USENTENCEG_InitLRU(plru, count);
else
{
strcpy(szfound, "!");
strcat(szfound, szgroupname);
sprintf(sznum, "%d", ipick);
strcat(szfound, sznum);
return ipick;
}
}
return -1;
}
// ===================== SENTENCE GROUPS, MAIN ROUTINES ========================
// Given sentence group rootname (name without number suffix),
// get sentence group index (isentenceg). Returns -1 if no such name.
int SENTENCEG_GetIndex(const char *szgroupname)
{
int i;
if (!fSentencesInit || !szgroupname)
return -1;
// search rgsentenceg for match on szgroupname
i = 0;
while (rgsentenceg[i].count)
{
if (!strcmp(szgroupname, rgsentenceg[i].szgroupname))
return i;
i++;
}
return -1;
}
// given sentence group index, play random sentence for given entity.
// returns ipick - which sentence was picked to
// play from the group. Ipick is only needed if you plan on stopping
// the sound before playback is done (see SENTENCEG_Stop).
int SENTENCEG_PlayRndI(edict_t *entity, int isentenceg,
float volume, float attenuation, int flags, int pitch)
{
char name[64];
int ipick;
if (!fSentencesInit)
return -1;
name[0] = 0;
ipick = USENTENCEG_Pick(isentenceg, name);
if (ipick > 0 && name)
EMIT_SOUND_DYN(entity, CHAN_VOICE, name, volume, attenuation, flags, pitch);
return ipick;
}
// same as above, but takes sentence group name instead of index
int SENTENCEG_PlayRndSz(edict_t *entity, const char *szgroupname,
float volume, float attenuation, int flags, int pitch)
{
char name[64];
int ipick;
int isentenceg;
if (!fSentencesInit)
return -1;
name[0] = 0;
isentenceg = SENTENCEG_GetIndex(szgroupname);
if (isentenceg < 0)
{
ALERT( at_console, "No such sentence group %s\n", szgroupname );
return -1;
}
ipick = USENTENCEG_Pick(isentenceg, name);
if (ipick >= 0 && name[0])
EMIT_SOUND_DYN(entity, CHAN_VOICE, name, volume, attenuation, flags, pitch);
return ipick;
}
// play sentences in sequential order from sentence group. Reset after last sentence.
int SENTENCEG_PlaySequentialSz(edict_t *entity, const char *szgroupname,
float volume, float attenuation, int flags, int pitch, int ipick, int freset)
{
char name[64];
int ipicknext;
int isentenceg;
if (!fSentencesInit)
return -1;
name[0] = 0;
isentenceg = SENTENCEG_GetIndex(szgroupname);
if (isentenceg < 0)
return -1;
ipicknext = USENTENCEG_PickSequential(isentenceg, name, ipick, freset);
if (ipicknext >= 0 && name[0])
EMIT_SOUND_DYN(entity, CHAN_VOICE, name, volume, attenuation, flags, pitch);
return ipicknext;
}
// for this entity, for the given sentence within the sentence group, stop
// the sentence.
void SENTENCEG_Stop(edict_t *entity, int isentenceg, int ipick)
{
char buffer[64];
char sznum[8];
if (!fSentencesInit)
return;
if (isentenceg < 0 || ipick < 0)
return;
strcpy(buffer, "!");
strcat(buffer, rgsentenceg[isentenceg].szgroupname);
sprintf(sznum, "%d", ipick);
strcat(buffer, sznum);
STOP_SOUND(entity, CHAN_VOICE, buffer);
}
// open sentences.txt, scan for groups, build rgsentenceg
// Should be called from world spawn, only works on the
// first call and is ignored subsequently.
void SENTENCEG_Init()
{
char buffer[512];
char szgroup[64];
int i, j;
int isentencegs;
if (fSentencesInit)
return;
memset(gszallsentencenames, 0, CVOXFILESENTENCEMAX * CBSENTENCENAME_MAX);
gcallsentences = 0;
memset(rgsentenceg, 0, CSENTENCEG_MAX * sizeof(SENTENCEG));
memset(buffer, 0, 512);
memset(szgroup, 0, 64);
isentencegs = -1;
int filePos = 0, fileSize;
byte *pMemFile = g_engfuncs.pfnLoadFileForMe( "sound/sentences.txt", &fileSize );
if ( !pMemFile )
return;
// for each line in the file...
while ( memfgets(pMemFile, fileSize, filePos, buffer, 511) != NULL )
{
// skip whitespace
i = 0;
while(buffer[i] && buffer[i] == ' ')
i++;
if (!buffer[i])
continue;
if (buffer[i] == '/' || !isalpha(buffer[i]))
continue;
// get sentence name
j = i;
while (buffer[j] && buffer[j] != ' ')
j++;
if (!buffer[j])
continue;
if (gcallsentences > CVOXFILESENTENCEMAX)
{
ALERT (at_error, "Too many sentences in sentences.txt!\n");
break;
}
// null-terminate name and save in sentences array
buffer[j] = 0;
const char *pString = buffer + i;
if ( strlen( pString ) >= CBSENTENCENAME_MAX )
ALERT( at_warning, "Sentence %s longer than %d letters\n", pString, CBSENTENCENAME_MAX-1 );
strcpy( gszallsentencenames[gcallsentences++], pString );
j--;
if (j <= i)
continue;
if (!isdigit(buffer[j]))
continue;
// cut out suffix numbers
while (j > i && isdigit(buffer[j]))
j--;
if (j <= i)
continue;
buffer[j+1] = 0;
// if new name doesn't match previous group name,
// make a new group.
if (strcmp(szgroup, &(buffer[i])))
{
// name doesn't match with prev name,
// copy name into group, init count to 1
isentencegs++;
if (isentencegs >= CSENTENCEG_MAX)
{
ALERT (at_error, "Too many sentence groups in sentences.txt!\n");
break;
}
strcpy(rgsentenceg[isentencegs].szgroupname, &(buffer[i]));
rgsentenceg[isentencegs].count = 1;
strcpy(szgroup, &(buffer[i]));
continue;
}
else
{
//name matches with previous, increment group count
if (isentencegs >= 0)
rgsentenceg[isentencegs].count++;
}
}
g_engfuncs.pfnFreeFile( pMemFile );
fSentencesInit = TRUE;
// init lru lists
i = 0;
while (rgsentenceg[i].count && i < CSENTENCEG_MAX)
{
USENTENCEG_InitLRU(&(rgsentenceg[i].rgblru[0]), rgsentenceg[i].count);
i++;
}
}
// convert sentence (sample) name to !sentencenum, return !sentencenum
int SENTENCEG_Lookup(const char *sample, char *sentencenum)
{
char sznum[8];
int i;
// this is a sentence name; lookup sentence number
// and give to engine as string.
for (i = 0; i < gcallsentences; i++)
if (!stricmp(gszallsentencenames[i], sample+1))
{
if (sentencenum)
{
strcpy(sentencenum, "!");
sprintf(sznum, "%d", i);
strcat(sentencenum, sznum);
}
return i;
}
// sentence name not found!
return -1;
}
void EMIT_SOUND_DYN(edict_t *entity, int channel, const char *sample, float volume, float attenuation,
int flags, int pitch)
{
if (sample && *sample == '!')
{
char name[32];
if (SENTENCEG_Lookup(sample, name) >= 0)
EMIT_SOUND_DYN2(entity, channel, name, volume, attenuation, flags, pitch);
else
ALERT( at_aiconsole, "Unable to find %s in sentences.txt\n", sample );
}
else
EMIT_SOUND_DYN2(entity, channel, sample, volume, attenuation, flags, pitch);
}
// play a specific sentence over the HEV suit speaker - just pass player entity, and !sentencename
void EMIT_SOUND_SUIT(edict_t *entity, const char *sample)
{
float fvol;
int pitch = PITCH_NORM;
fvol = CVAR_GET_FLOAT("suitvolume");
if (RANDOM_LONG(0,1))
pitch = RANDOM_LONG(0,6) + 98;
if (fvol > 0.05)
EMIT_SOUND_DYN(entity, CHAN_STATIC, sample, fvol, ATTN_NORM, 0, pitch);
}
// play a sentence, randomly selected from the passed in group id, over the HEV suit speaker
void EMIT_GROUPID_SUIT(edict_t *entity, int isentenceg)
{
float fvol;
int pitch = PITCH_NORM;
fvol = CVAR_GET_FLOAT("suitvolume");
if (RANDOM_LONG(0,1))
pitch = RANDOM_LONG(0,6) + 98;
if (fvol > 0.05)
SENTENCEG_PlayRndI(entity, isentenceg, fvol, ATTN_NORM, 0, pitch);
}
// play a sentence, randomly selected from the passed in groupname
void EMIT_GROUPNAME_SUIT(edict_t *entity, const char *groupname)
{
float fvol;
int pitch = PITCH_NORM;
fvol = CVAR_GET_FLOAT("suitvolume");
if (RANDOM_LONG(0,1))
pitch = RANDOM_LONG(0,6) + 98;
if (fvol > 0.05)
SENTENCEG_PlayRndSz(entity, groupname, fvol, ATTN_NORM, 0, pitch);
}
// ===================== MATERIAL TYPE DETECTION, MAIN ROUTINES ========================
//
// Used to detect the texture the player is standing on, map the
// texture name to a material type. Play footstep sound based
// on material type.
int fTextureTypeInit = FALSE;
#define CTEXTURESMAX 512 // max number of textures loaded
int gcTextures = 0;
char grgszTextureName[CTEXTURESMAX][CBTEXTURENAMEMAX]; // texture names
char grgchTextureType[CTEXTURESMAX]; // parallel array of texture types
// open materials.txt, get size, alloc space,
// save in array. Only works first time called,
// ignored on subsequent calls.
static char *memfgets( byte *pMemFile, int fileSize, int &filePos, char *pBuffer, int bufferSize )
{
// Bullet-proofing
if ( !pMemFile || !pBuffer )
return NULL;
if ( filePos >= fileSize )
return NULL;
int i = filePos;
int last = fileSize;
// fgets always NULL terminates, so only read bufferSize-1 characters
if ( last - filePos > (bufferSize-1) )
last = filePos + (bufferSize-1);
int stop = 0;
// Stop at the next newline (inclusive) or end of buffer
while ( i < last && !stop )
{
if ( pMemFile[i] == '\n' )
stop = 1;
i++;
}
// If we actually advanced the pointer, copy it over
if ( i != filePos )
{
// We read in size bytes
int size = i - filePos;
// copy it out
memcpy( pBuffer, pMemFile + filePos, sizeof(byte)*size );
// If the buffer isn't full, terminate (this is always true)
if ( size < bufferSize )
pBuffer[size] = 0;
// Update file pointer
filePos = i;
return pBuffer;
}
// No data read, bail
return NULL;
}
void TEXTURETYPE_Init()
{
char buffer[512];
int i, j;
byte *pMemFile;
int fileSize, filePos;
if (fTextureTypeInit)
return;
memset(&(grgszTextureName[0][0]), 0, CTEXTURESMAX * CBTEXTURENAMEMAX);
memset(grgchTextureType, 0, CTEXTURESMAX);
gcTextures = 0;
memset(buffer, 0, 512);
pMemFile = g_engfuncs.pfnLoadFileForMe( "sound/materials.txt", &fileSize );
if ( !pMemFile )
return;
// for each line in the file...
while (memfgets(pMemFile, fileSize, filePos, buffer, 511) != NULL && (gcTextures < CTEXTURESMAX))
{
// skip whitespace
i = 0;
while(buffer[i] && isspace(buffer[i]))
i++;
if (!buffer[i])
continue;
// skip comment lines
if (buffer[i] == '/' || !isalpha(buffer[i]))
continue;
// get texture type
grgchTextureType[gcTextures] = toupper(buffer[i++]);
// skip whitespace
while(buffer[i] && isspace(buffer[i]))
i++;
if (!buffer[i])
continue;
// get sentence name
j = i;
while (buffer[j] && !isspace(buffer[j]))
j++;
if (!buffer[j])
continue;
// null-terminate name and save in sentences array
j = min (j, CBTEXTURENAMEMAX-1+i);
buffer[j] = 0;
strcpy(&(grgszTextureName[gcTextures++][0]), &(buffer[i]));
}
g_engfuncs.pfnFreeFile( pMemFile );
fTextureTypeInit = TRUE;
}
// given texture name, find texture type
// if not found, return type 'concrete'
// NOTE: this routine should ONLY be called if the
// current texture under the player changes!
char TEXTURETYPE_Find(char *name)
{
// CONSIDER: pre-sort texture names and perform faster binary search here
for (int i = 0; i < gcTextures; i++)
{
if (!strnicmp(name, &(grgszTextureName[i][0]), CBTEXTURENAMEMAX-1))
return (grgchTextureType[i]);
}
return CHAR_TEX_CONCRETE;
}
// play a strike sound based on the texture that was hit by the attack traceline. VecSrc/VecEnd are the
// original traceline endpoints used by the attacker, iBulletType is the type of bullet that hit the texture.
// returns volume of strike instrument (crowbar) to play
float TEXTURETYPE_PlaySound(TraceResult *ptr, Vector vecSrc, Vector vecEnd, int iBulletType)
{
// hit the world, try to play sound based on texture material type
char chTextureType;
float fvol;
float fvolbar;
char szbuffer[64];
const char *pTextureName;
float rgfl1[3];
float rgfl2[3];
char *rgsz[4];
int cnt;
float fattn = ATTN_NORM;
if ( !g_pGameRules->PlayTextureSounds() )
return 0.0;
CBaseEntity *pEntity = CBaseEntity::Instance(ptr->pHit);
chTextureType = 0;
if (pEntity && pEntity->Classify() != CLASS_NONE && pEntity->Classify() != CLASS_MACHINE)
// hit body
chTextureType = CHAR_TEX_FLESH;
else
{
// hit world
// find texture under strike, get material type
// copy trace vector into array for trace_texture
vecSrc.CopyToArray(rgfl1);
vecEnd.CopyToArray(rgfl2);
// get texture from entity or world (world is ent(0))
if (pEntity)
pTextureName = TRACE_TEXTURE( ENT(pEntity->pev), rgfl1, rgfl2 );
else
pTextureName = TRACE_TEXTURE( ENT(0), rgfl1, rgfl2 );
if ( pTextureName )
{
// strip leading '-0' or '+0~' or '{' or '!'
if (*pTextureName == '-' || *pTextureName == '+')
pTextureName += 2;
if (*pTextureName == '{' || *pTextureName == '!' || *pTextureName == '~' || *pTextureName == ' ')
pTextureName++;
// '}}'
strcpy(szbuffer, pTextureName);
szbuffer[CBTEXTURENAMEMAX - 1] = 0;
// ALERT ( at_console, "texture hit: %s\n", szbuffer);
// get texture type
chTextureType = TEXTURETYPE_Find(szbuffer);
}
}
switch (chTextureType)
{
default:
case CHAR_TEX_CONCRETE: fvol = 0.9; fvolbar = 0.6;
rgsz[0] = "player/pl_step1.wav";
rgsz[1] = "player/pl_step2.wav";
cnt = 2;
break;
case CHAR_TEX_METAL: fvol = 0.9; fvolbar = 0.3;
rgsz[0] = "player/pl_metal1.wav";
rgsz[1] = "player/pl_metal2.wav";
cnt = 2;
break;
case CHAR_TEX_DIRT: fvol = 0.9; fvolbar = 0.1;
rgsz[0] = "player/pl_dirt1.wav";
rgsz[1] = "player/pl_dirt2.wav";
rgsz[2] = "player/pl_dirt3.wav";
cnt = 3;
break;
case CHAR_TEX_VENT: fvol = 0.5; fvolbar = 0.3;
rgsz[0] = "player/pl_duct1.wav";
rgsz[1] = "player/pl_duct1.wav";
cnt = 2;
break;
case CHAR_TEX_GRATE: fvol = 0.9; fvolbar = 0.5;
rgsz[0] = "player/pl_grate1.wav";
rgsz[1] = "player/pl_grate4.wav";
cnt = 2;
break;
case CHAR_TEX_TILE: fvol = 0.8; fvolbar = 0.2;
rgsz[0] = "player/pl_tile1.wav";
rgsz[1] = "player/pl_tile3.wav";
rgsz[2] = "player/pl_tile2.wav";
rgsz[3] = "player/pl_tile4.wav";
cnt = 4;
break;
case CHAR_TEX_SLOSH: fvol = 0.9; fvolbar = 0.0;
rgsz[0] = "player/pl_slosh1.wav";
rgsz[1] = "player/pl_slosh3.wav";
rgsz[2] = "player/pl_slosh2.wav";
rgsz[3] = "player/pl_slosh4.wav";
cnt = 4;
break;
case CHAR_TEX_WOOD: fvol = 0.9; fvolbar = 0.2;
rgsz[0] = "debris/wood1.wav";
rgsz[1] = "debris/wood2.wav";
rgsz[2] = "debris/wood3.wav";
cnt = 3;
break;
case CHAR_TEX_GLASS:
case CHAR_TEX_COMPUTER:
fvol = 0.8; fvolbar = 0.2;
rgsz[0] = "debris/glass1.wav";
rgsz[1] = "debris/glass2.wav";
rgsz[2] = "debris/glass3.wav";
cnt = 3;
break;
case CHAR_TEX_FLESH:
if (iBulletType == BULLET_PLAYER_CROWBAR)
return 0.0; // crowbar already makes this sound
fvol = 1.0; fvolbar = 0.2;
rgsz[0] = "weapons/bullet_hit1.wav";
rgsz[1] = "weapons/bullet_hit2.wav";
fattn = 1.0;
cnt = 2;
break;
}
// did we hit a breakable?
if (pEntity && FClassnameIs(pEntity->pev, "func_breakable"))
{
// drop volumes, the object will already play a damaged sound
fvol /= 1.5;
fvolbar /= 2.0;
}
else if (chTextureType == CHAR_TEX_COMPUTER)
{
// play random spark if computer
if ( ptr->flFraction != 1.0 && RANDOM_LONG(0,1))
{
UTIL_Sparks( ptr->vecEndPos );
float flVolume = RANDOM_FLOAT ( 0.7 , 1.0 );//random volume range
switch ( RANDOM_LONG(0,1) )
{
case 0: UTIL_EmitAmbientSound(ENT(0), ptr->vecEndPos, "buttons/spark5.wav", flVolume, ATTN_NORM, 0, 100); break;
case 1: UTIL_EmitAmbientSound(ENT(0), ptr->vecEndPos, "buttons/spark6.wav", flVolume, ATTN_NORM, 0, 100); break;
// case 0: EMIT_SOUND(ENT(pev), CHAN_VOICE, "buttons/spark5.wav", flVolume, ATTN_NORM); break;
// case 1: EMIT_SOUND(ENT(pev), CHAN_VOICE, "buttons/spark6.wav", flVolume, ATTN_NORM); break;
}
}
}
// play material hit sound
UTIL_EmitAmbientSound(ENT(0), ptr->vecEndPos, rgsz[RANDOM_LONG(0,cnt-1)], fvol, fattn, 0, 96 + RANDOM_LONG(0,0xf));
//EMIT_SOUND_DYN( ENT(m_pPlayer->pev), CHAN_WEAPON, rgsz[RANDOM_LONG(0,cnt-1)], fvol, ATTN_NORM, 0, 96 + RANDOM_LONG(0,0xf));
return fvolbar;
}
// ===================================================================================
//
// Speaker class. Used for announcements per level, for door lock/unlock spoken voice.
//
class CSpeaker : public CBaseEntity
{
public:
void KeyValue( KeyValueData* pkvd);
void Spawn( void );
void Precache( void );
void EXPORT ToggleUse ( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value );
void EXPORT SpeakerThink( void );
virtual int Save( CSave &save );
virtual int Restore( CRestore &restore );
static TYPEDESCRIPTION m_SaveData[];
virtual int ObjectCaps( void ) { return (CBaseEntity :: ObjectCaps() & ~FCAP_ACROSS_TRANSITION); }
int m_preset; // preset number
};
LINK_ENTITY_TO_CLASS( speaker, CSpeaker );
TYPEDESCRIPTION CSpeaker::m_SaveData[] =
{
DEFINE_FIELD( CSpeaker, m_preset, FIELD_INTEGER ),
};
IMPLEMENT_SAVERESTORE( CSpeaker, CBaseEntity );
//
// ambient_generic - general-purpose user-defined static sound
//
void CSpeaker :: Spawn( void )
{
char* szSoundFile = (char*) STRING(pev->message);
if ( !m_preset && (FStringNull( pev->message ) || strlen( szSoundFile ) < 1 ))
{
ALERT( at_error, "SPEAKER with no Level/Sentence! at: %f, %f, %f\n", pev->origin.x, pev->origin.y, pev->origin.z );
pev->nextthink = gpGlobals->time + 0.1;
SetThink( SUB_Remove );
return;
}
pev->solid = SOLID_NOT;
pev->movetype = MOVETYPE_NONE;
SetThink(SpeakerThink);
pev->nextthink = 0.0;
// allow on/off switching via 'use' function.
SetUse ( ToggleUse );
Precache( );
}
#define ANNOUNCE_MINUTES_MIN 0.25
#define ANNOUNCE_MINUTES_MAX 2.25
void CSpeaker :: Precache( void )
{
if ( !FBitSet (pev->spawnflags, SPEAKER_START_SILENT ) )
// set first announcement time for random n second
pev->nextthink = gpGlobals->time + RANDOM_FLOAT(5.0, 15.0);
}
void CSpeaker :: SpeakerThink( void )
{
char* szSoundFile;
float flvolume = pev->health * 0.1;
float flattenuation = 0.3;
int flags = 0;
int pitch = 100;
// Wait for the talkmonster to finish first.
if (gpGlobals->time <= CTalkMonster::g_talkWaitTime)
{
pev->nextthink = CTalkMonster::g_talkWaitTime + RANDOM_FLOAT( 5, 10 );
return;
}
if (m_preset)
{
// go lookup preset text, assign szSoundFile
switch (m_preset)
{
case 1: szSoundFile = "C1A0_"; break;
case 2: szSoundFile = "C1A1_"; break;
case 3: szSoundFile = "C1A2_"; break;
case 4: szSoundFile = "C1A3_"; break;
case 5: szSoundFile = "C1A4_"; break;
case 6: szSoundFile = "C2A1_"; break;
case 7: szSoundFile = "C2A2_"; break;
case 8: szSoundFile = "C2A3_"; break;
case 9: szSoundFile = "C2A4_"; break;
case 10: szSoundFile = "C2A5_"; break;
case 11: szSoundFile = "C3A1_"; break;
case 12: szSoundFile = "C3A2_"; break;
}
} else
szSoundFile = (char*) STRING(pev->message);
if (szSoundFile[0] == '!')
{
// play single sentence, one shot
UTIL_EmitAmbientSound ( ENT(pev), pev->origin, szSoundFile,
flvolume, flattenuation, flags, pitch);
// shut off and reset
pev->nextthink = 0.0;
}
else
{
// make random announcement from sentence group
if (SENTENCEG_PlayRndSz(ENT(pev), szSoundFile, flvolume, flattenuation, flags, pitch) < 0)
ALERT(at_console, "Level Design Error!\nSPEAKER has bad sentence group name: %s\n",szSoundFile);
// set next announcement time for random 5 to 10 minute delay
pev->nextthink = gpGlobals->time +
RANDOM_FLOAT(ANNOUNCE_MINUTES_MIN * 60.0, ANNOUNCE_MINUTES_MAX * 60.0);
CTalkMonster::g_talkWaitTime = gpGlobals->time + 5; // time delay until it's ok to speak: used so that two NPCs don't talk at once
}
return;
}
//
// ToggleUse - if an announcement is pending, cancel it. If no announcement is pending, start one.
//
void CSpeaker :: ToggleUse ( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value )
{
int fActive = (pev->nextthink > 0.0);
// fActive is TRUE only if an announcement is pending
if ( useType != USE_TOGGLE )
{
// ignore if we're just turning something on that's already on, or
// turning something off that's already off.
if ( (fActive && useType == USE_ON) || (!fActive && useType == USE_OFF) )
return;
}
if ( useType == USE_ON )
{
// turn on announcements
pev->nextthink = gpGlobals->time + 0.1;
return;
}
if ( useType == USE_OFF )
{
// turn off announcements
pev->nextthink = 0.0;
return;
}
// Toggle announcements
if ( fActive )
{
// turn off announcements
pev->nextthink = 0.0;
}
else
{
// turn on announcements
pev->nextthink = gpGlobals->time + 0.1;
}
}
// KeyValue - load keyvalue pairs into member data
// NOTE: called BEFORE spawn!
void CSpeaker :: KeyValue( KeyValueData *pkvd )
{
// preset
if (FStrEq(pkvd->szKeyName, "preset"))
{
m_preset = atoi(pkvd->szValue);
pkvd->fHandled = TRUE;
}
else
CBaseEntity::KeyValue( pkvd );
}
| [
"joropito@23c7d628-c96c-11de-a380-73d83ba7c083"
]
| [
[
[
1,
1978
]
]
]
|
f815eb10bb376d47196a900521d7bfcac604c4a9 | d112566843e130e29fa468f868682212a71f4f25 | /src/settings.cpp | 3877664a8df2522156743d7bd10f2131e9d689bc | []
| no_license | danieldaz/repsnapper | ffbb05b3fa3eae1d0e5418098de3feac42ffb6bb | 1bca689bed4ad57b5c8dd94b51eb9cadf86b8b9d | refs/heads/master | 2020-12-25T05:36:12.563953 | 2011-09-18T15:35:24 | 2011-09-18T15:35:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30,015 | cpp | /*
This file is a part of the RepSnapper project.
Copyright (C) 2010 Michael Meeks
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "config.h"
#include <cstdlib>
#include <gtkmm.h>
#include "settings.h"
#include <stdafx.h>
/*
* How settings are intended to work:
*
* The large table below provides pointers into a settings instance, and
* some simple (POD) type information for the common settings. It also
* provides the configuration name for each setting, and a Gtk::Builder
* XML widget name, with which the setting should be associated.
*/
// Allow passing as a pointer to something to
// avoid including glibmm in every header.
class Builder : public Glib::RefPtr<Gtk::Builder>
{
public:
Builder() {}
~Builder() {}
};
#ifdef WIN32
# define DEFAULT_COM_PORT "COM0"
#else
# define DEFAULT_COM_PORT "/dev/ttyUSB0"
#endif
#define OFFSET(field) offsetof (class Settings, field)
#define BOOL_MEMBER(field, config_name, def_value, redraw ) \
{ OFFSET (field), T_BOOL, config_name, #field, def_value, NULL, redraw }
#define INT_MEMBER(field, config_name, def_value, redraw) \
{ OFFSET (field), T_INT, config_name, #field, def_value, NULL, redraw }
#define FLOAT_MEMBER(field, config_name, def_value, redraw) \
{ OFFSET (field), T_FLOAT, config_name, #field, def_value, NULL, redraw }
#define STRING_MEMBER(field, config_name, def_value, redraw) \
{ OFFSET (field), T_STRING, config_name, #field, 0.0, def_value, redraw }
#define COLOUR_MEMBER(field, config_name, def_valueR, def_valueG, def_valueB, def_valueA, redraw) \
{ OFFSET (field.r), T_COLOUR_MEMBER, config_name "R", NULL, def_valueR, NULL, redraw }, \
{ OFFSET (field.g), T_COLOUR_MEMBER, config_name "G", NULL, def_valueG, NULL, redraw }, \
{ OFFSET (field.b), T_COLOUR_MEMBER, config_name "B", NULL, def_valueB, NULL, redraw }, \
{ OFFSET (field.a), T_COLOUR_MEMBER, config_name "A", NULL, def_valueA, NULL, redraw }
#define FLOAT_PHASE_MEMBER(phase, phasestd, member, def_value, redraw) \
{ OFFSET (Raft.Phase[Settings::RaftSettings::PHASE_##phase].member), T_FLOAT, \
#phasestd #member, #phasestd #member, def_value, NULL, redraw }
// converting our offsets into type pointers
#define PTR_OFFSET(obj, offset) (((guchar *)obj) + offset)
#define PTR_BOOL(obj, idx) ((bool *)PTR_OFFSET (obj, settings[idx].member_offset))
#define PTR_INT(obj, idx) ((int *)PTR_OFFSET (obj, settings[idx].member_offset))
#define PTR_UINT(obj, idx) ((uint *)PTR_OFFSET (obj, settings[idx].member_offset))
#define PTR_FLOAT(obj, idx) ((float *)PTR_OFFSET (obj, settings[idx].member_offset))
#define PTR_STRING(obj, idx) ((std::string *)PTR_OFFSET (obj, settings[idx].member_offset))
#define PTR_COLOUR(obj, idx) ((vmml::Vector4f *)PTR_OFFSET (obj, settings[idx].member_offset))
enum SettingType { T_BOOL, T_INT, T_FLOAT, T_STRING, T_COLOUR_MEMBER };
static struct {
uint member_offset;
SettingType type;
const char *config_name; // This is obsolete - we split and re-use the glade_name
const char *glade_name;
double def_double;
const char *def_string;
gboolean triggers_redraw;
} settings[] = {
// Raft:
BOOL_MEMBER (RaftEnable, "RaftEnable", false, false),
FLOAT_MEMBER (Raft.Size, "RaftSize", 1.33, false),
// Raft Base
{ OFFSET (Raft.Phase[Settings::RaftSettings::PHASE_BASE].LayerCount), T_INT,
"BaseLayerCount", "BaseLayerCount", 1, NULL, false},
FLOAT_PHASE_MEMBER(BASE, Base, MaterialDistanceRatio, 1.8, false),
FLOAT_PHASE_MEMBER(BASE, Base, Rotation, 0.0, false),
FLOAT_PHASE_MEMBER(BASE, Base, RotationPrLayer, 90.0, false),
FLOAT_PHASE_MEMBER(BASE, Base, Distance, 2.0, false),
FLOAT_PHASE_MEMBER(BASE, Base, Thickness, 1.0, false),
FLOAT_PHASE_MEMBER(BASE, Base, Temperature, 1.10, false),
// Raft Interface
{ OFFSET (Raft.Phase[Settings::RaftSettings::PHASE_INTERFACE].LayerCount), T_INT,
"InterfaceLayerCount", "InterfaceLayerCount", 2, false },
FLOAT_PHASE_MEMBER(INTERFACE, Interface, MaterialDistanceRatio, 1.0, false),
FLOAT_PHASE_MEMBER(INTERFACE, Interface, Rotation, 90.0, false),
FLOAT_PHASE_MEMBER(INTERFACE, Interface, RotationPrLayer, 90.0, false),
FLOAT_PHASE_MEMBER(INTERFACE, Interface, Distance, 2.0, false),
FLOAT_PHASE_MEMBER(INTERFACE, Interface, Thickness, 1.0, false),
FLOAT_PHASE_MEMBER(INTERFACE, Interface, Temperature, 1.0, false),
#undef FLOAT_PHASE_MEMBER
// Hardware
FLOAT_MEMBER (Hardware.MinPrintSpeedXY, "MinPrintSpeedXY", 1000, false),
FLOAT_MEMBER (Hardware.MaxPrintSpeedXY, "MaxPrintSpeedXY", 4000, false),
FLOAT_MEMBER (Hardware.MinPrintSpeedZ, "MinPrintSpeedZ", 50, false),
FLOAT_MEMBER (Hardware.MaxPrintSpeedZ, "MaxPrintSpeedZ", 150, false),
FLOAT_MEMBER (Hardware.DistanceToReachFullSpeed, "DistanceToReachFullSpeed", 1.5, false),
FLOAT_MEMBER (Hardware.ExtrusionFactor, "ExtrusionFactor", 1.0, false),
FLOAT_MEMBER (Hardware.LayerThickness, "LayerThickness", 0.4, false),
FLOAT_MEMBER (Hardware.DownstreamMultiplier, "DownstreamMultiplier", 1.0, false),
FLOAT_MEMBER (Hardware.DownstreamExtrusionMultiplier, "DownstreamExtrusionMultiplier", 1.0, false),
// Volume
{ OFFSET (Hardware.Volume.x), T_FLOAT, "mfVolumeX", "Hardware.Volume.X", 200, false },
{ OFFSET (Hardware.Volume.y), T_FLOAT, "mfVolumeY", "Hardware.Volume.Y", 200, false },
{ OFFSET (Hardware.Volume.z), T_FLOAT, "mfVolumeZ", "Hardware.Volume.Z", 140, false },
// PrintMargin
{ OFFSET (Hardware.PrintMargin.x), T_FLOAT, "PrintMarginX", "Hardware.PrintMargin.X", 10, false },
{ OFFSET (Hardware.PrintMargin.y), T_FLOAT, "PrintMarginY", "Hardware.PrintMargin.Y", 10, false },
{ OFFSET (Hardware.PrintMargin.z), T_FLOAT, "PrintMarginZ", "Hardware.PrintMargin.Z", 0, false },
FLOAT_MEMBER (Hardware.ExtrudedMaterialWidth, "ExtrudedMaterialWidth", 0.7, false),
{ OFFSET (Hardware.PortName), T_STRING, "Hardware.PortName", NULL, 0, DEFAULT_COM_PORT, false },
{ OFFSET (Hardware.SerialSpeed), T_INT, "Hardware.SerialSpeed", NULL, 19200, false }, /* 57600 ? */
BOOL_MEMBER (Hardware.ValidateConnection, "ValidateConnection", true, false),
INT_MEMBER (Hardware.KeepLines, "KeepLines", 1000, false),
INT_MEMBER (Hardware.ReceivingBufferSize, "ReceivingBufferSize", 4, false),
// Slicing
BOOL_MEMBER (Slicing.UseIncrementalEcode, "UseIncrementalEcode", true, false),
BOOL_MEMBER (Slicing.Use3DGcode, "Use3DGcode", false, false),
BOOL_MEMBER (Slicing.EnableAntiooze, "EnableAntiooze", false, false),
FLOAT_MEMBER (Slicing.AntioozeDistance, "AntioozeDistance", 4.5, false),
FLOAT_MEMBER (Slicing.AntioozeSpeed, "AntioozeSpeed", 1000.0, false),
FLOAT_MEMBER (Slicing.InfillDistance, "InfillDistance", 2.0, false),
FLOAT_MEMBER (Slicing.InfillRotation, "InfillRotation", 45.0, false),
FLOAT_MEMBER (Slicing.InfillRotationPrLayer, "InfillRotationPrLayer", 90.0, false),
FLOAT_MEMBER (Slicing.AltInfillDistance, "AltInfillDistance", 2.0, false),
STRING_MEMBER (Slicing.AltInfillLayersText, "AltInfillLayersText", "", false),
BOOL_MEMBER (Slicing.ShellOnly, "ShellOnly", false, true),
INT_MEMBER (Slicing.ShellCount, "ShellCount", 1, true),
BOOL_MEMBER (Slicing.EnableAcceleration, "EnableAcceleration", true, false),
// ShrinkQuality is a special enumeration ...
INT_MEMBER (Slicing.ShrinkQuality, "ShrinkQuality", 0, true),
FLOAT_MEMBER (Slicing.Optimization, "Optimization", 0.02, false),
// Misc.
BOOL_MEMBER (Misc.FileLoggingEnabled, "FileLoggingEnabled", true, false),
BOOL_MEMBER (Misc.TempReadingEnabled, "TempReadingEnabled", true, false),
BOOL_MEMBER (Misc.ClearLogfilesWhenPrintStarts, "ClearLogfilesWhenPrintStarts", true, false),
// GCode - handled by GCodeImpl
// Display - pending ...
BOOL_MEMBER (Display.DisplayGCode, "DisplayGCode", true, true),
FLOAT_MEMBER (Display.GCodeDrawStart, "GCodeDrawStart", 0.0, true),
FLOAT_MEMBER (Display.GCodeDrawEnd, "GCodeDrawEnd", 1.0, true),
BOOL_MEMBER (Display.DisplayEndpoints, "DisplayEndpoints", false, true),
BOOL_MEMBER (Display.DisplayNormals, "DisplayNormals", false, true),
BOOL_MEMBER (Display.DisplayBBox, "DisplayBBox", false, true),
BOOL_MEMBER (Display.DisplayWireframe, "DisplayWireframe", false, true),
BOOL_MEMBER (Display.DisplayWireframeShaded, "DisplayWireframeShaded", true, true),
BOOL_MEMBER (Display.DisplayPolygons, "DisplayPolygons", true, true),
BOOL_MEMBER (Display.DisplayAllLayers, "DisplayAllLayers", false, true),
BOOL_MEMBER (Display.DisplayinFill, "DisplayinFill", false, true),
BOOL_MEMBER (Display.DisplayDebuginFill, "DisplayDebuginFill", false, false),
BOOL_MEMBER (Display.DisplayDebug, "DisplayDebug", false, true),
BOOL_MEMBER (Display.DisplayCuttingPlane, "DisplayCuttingPlane", false, true),
BOOL_MEMBER (Display.DrawVertexNumbers, "DrawVertexNumbers", false, true),
BOOL_MEMBER (Display.DrawLineNumbers, "DrawLineNumbers", false, true),
BOOL_MEMBER (Display.DrawOutlineNumbers, "DrawOutlineNumbers", false, true),
BOOL_MEMBER (Display.DrawCPVertexNumbers, "DrawCPVertexNumbers", false, true),
BOOL_MEMBER (Display.DrawCPLineNumbers, "DrawCPLineNumbers", false, true),
BOOL_MEMBER (Display.DrawCPOutlineNumbers, "DrawCPOutlineNumbers", false, true),
FLOAT_MEMBER (Display.CuttingPlaneValue, "CuttingPlaneValue", 0, true),
BOOL_MEMBER (Display.LuminanceShowsSpeed, "LuminanceShowsSpeed", false, true),
FLOAT_MEMBER (Display.Highlight, "Highlight", 0.7, true),
FLOAT_MEMBER (Display.NormalsLength, "NormalsLength", 10, true),
FLOAT_MEMBER (Display.EndPointSize, "EndPointSize", 8, true),
FLOAT_MEMBER (Display.TempUpdateSpeed, "TempUpdateSpeed", 3, false),
// Colour selectors settings
COLOUR_MEMBER(Display.PolygonRGBA,
"Display.PolygonColour", 0, 1.0, 1.0, 0.5, true),
COLOUR_MEMBER(Display.WireframeRGBA,
"Display.WireframeColour", 1.0, 0.48, 0, 0.5, true),
COLOUR_MEMBER(Display.NormalsRGBA,
"Display.NormalsColour", 0.62, 1.0, 0, 1.0, true),
COLOUR_MEMBER(Display.EndpointsRGBA,
"Display.EndpointsColour", 0, 1.0, 0.7, 1.0, true),
COLOUR_MEMBER(Display.GCodeExtrudeRGBA,
"Display.GCodeExtrudeColour", 1.0, 1.0, 0.0, 1.0, true),
COLOUR_MEMBER(Display.GCodeMoveRGBA,
"Display.GCodeMoveColour", 1.0, 0.05, 1, 0.5, true),
};
// Add any GtkSpinButtons to this array:
static struct {
const char *widget;
double min, max;
double inc, inc_page;
} spin_ranges[] = {
// Raft
{ "Raft.Size", 0, 50, 1, 3 },
{ "BaseLayerCount", 0, 8, 1, 2 },
{ "InterfaceLayerCount", 0, 8, 1, 2 },
{ "BaseMaterialDistanceRatio", 0.1, 4.0, 0.1, 1 },
{ "InterfaceMaterialDistanceRatio", 0.1, 4.0, 0.1, 1 },
{ "BaseRotation", -360.0, 360.0, 45, 90 },
{ "InterfaceRotation", -360.0, 360.0, 45, 90 },
{ "BaseRotationPrLayer", -360.0, 360.0, 45, 90 },
{ "InterfaceRotationPrLayer", -360.0, 360.0, 45, 90 },
{ "BaseDistance", 0.1, 8.0, 0.1, 1 },
{ "InterfaceDistance", 0.1, 8.0, 0.1, 1 },
{ "BaseThickness", 0.1, 4.0, 0.1, 1 },
{ "InterfaceThickness", 0.1, 4.0, 0.1, 1 },
{ "BaseTemperature", 0.9, 1.2, 0.01, 0.1 },
{ "InterfaceTemperature", 0.9, 1.2, 0.01, 0.1 },
// Slicing
{ "Slicing.ShellCount", 0, 100, 1, 5 },
{ "Slicing.InfillRotation", -360, 360, 5, 45 },
{ "Slicing.InfillRotationPrLayer", -360, 360, 5, 90 },
{ "Slicing.InfillDistance", 0.1, 10, 0.1, 1 },
{ "Slicing.AltInfillDistance", 0.1, 10, 0.1, 2 },
{ "Slicing.Optimization", 0.0, 1.0, 0.01, 0.1 },
{ "Slicing.AntioozeDistance", 0.0, 25.0, 0.1, 1 },
{ "Slicing.AntioozeSpeed", 0.0, 10000.0, 25.0, 100.0 },
// Hardware
{ "Hardware.Volume.X", 0.0, 1000.0, 5.0, 25.0 },
{ "Hardware.Volume.Y", 0.0, 1000.0, 5.0, 25.0 },
{ "Hardware.Volume.Z", 0.0, 1000.0, 5.0, 25.0 },
{ "Hardware.PrintMargin.X", 0.0, 100.0, 1.0, 5.0 },
{ "Hardware.PrintMargin.Y", 0.0, 100.0, 1.0, 5.0 },
{ "Hardware.PrintMargin.Z", 0.0, 100.0, 1.0, 5.0 },
{ "Hardware.DistanceToReachFullSpeed", 0.0, 10.0, 0.1, 1.0 },
{ "Hardware.ExtrudedMaterialWidth", 0.0, 10.0, 0.01, 0.1 },
{ "Hardware.LayerThickness", 0.1, 3.0, 0.1, 0.2 },
{ "Hardware.ExtrusionFactor", 0.0, 2.0, 0.1, 0.2 },
{ "Hardware.MinPrintSpeedXY", 1.0, 8000.0, 10.0, 100.0 },
{ "Hardware.MaxPrintSpeedXY", 1.0, 8000.0, 10.0, 100.0 },
{ "Hardware.MinPrintSpeedZ", 1.0, 2500.0, 10.0, 100.0 },
{ "Hardware.MaxPrintSpeedZ", 1.0, 2500.0, 10.0, 100.0 },
{ "Hardware.ReceivingBufferSize", 1.0, 100.0, 1.0, 5.0 },
{ "Hardware.KeepLines", 100.0, 100000.0, 1.0, 500.0 },
{ "Hardware.DownstreamMultiplier", 0.01, 25.0, 0.01, 0.1 },
{ "Hardware.DownstreamExtrusionMultiplier", 0.01, 25.0, 0.01, 0.1 },
// Display pane
{ "Display.TempUpdateSpeed", 0.1, 10.0, 0.5, 1.0 },
};
// Add any [HV]Ranges to this array:
static struct {
const char *widget;
double min, max;
double inc, inc_page;
} ranges[] = {
// Display plane
{ "Display.CuttingPlaneValue", 0.0, 1.0, 0.0, 0.01 },
{ "Display.GCodeDrawStart", 0.0, 1.0, 0.0, 0.1 },
{ "Display.GCodeDrawEnd", 0.0, 1.0, 0.0, 0.1 },
};
static struct {
uint member_offset;
const char *glade_name;
}
colour_selectors[] = {
{ OFFSET(Display.PolygonRGBA), "Display.PolygonRGB" },
{ OFFSET(Display.WireframeRGBA), "Display.WireframeRGB" },
{ OFFSET(Display.NormalsRGBA), "Display.NormalsRGB" },
{ OFFSET(Display.EndpointsRGBA), "Display.EndpointsRGB" },
{ OFFSET(Display.GCodeExtrudeRGBA), "Display.GCodeExtrudeRGB" },
{ OFFSET(Display.GCodeMoveRGBA), "Display.GCodeMoveRGB" }
};
static const char *GCodeNames[] = { "Start", "Layer", "End" };
class Settings::GCodeImpl {
public:
Glib::RefPtr<Gtk::TextBuffer> m_GCode[GCODE_TEXT_TYPE_COUNT];
GCodeImpl()
{
for (guint i = 0; i < GCODE_TEXT_TYPE_COUNT; i++)
m_GCode[i] = Gtk::TextBuffer::create();
}
void loadSettings(Glib::KeyFile &cfg)
{
for (guint i = 0; i < GCODE_TEXT_TYPE_COUNT; i++)
{
if (cfg.has_key ("GCode", GCodeNames[i]))
m_GCode[i]->set_text(cfg.get_string ("GCode", GCodeNames[i]));
}
}
void saveSettings(Glib::KeyFile &cfg)
{
for (guint i = 0; i < GCODE_TEXT_TYPE_COUNT; i++)
cfg.set_string ("GCode", GCodeNames[i], m_GCode[i]->get_text());
}
void connectToUI(Builder &builder)
{
static const char *ui_names[] =
{ "txt_gcode_start", "txt_gcode_next_layer", "txt_gcode_end" };
for (guint i = 0; i < GCODE_TEXT_TYPE_COUNT; i++) {
Gtk::TextView *textv = NULL;
builder->get_widget (ui_names [i], textv);
if (textv)
textv->set_buffer (m_GCode[i]);
}
}
void setDefaults()
{
m_GCode[GCODE_TEXT_START]->set_text
("; GCode generated by RepSnapper:\n"
"; http://reprap.org/wiki/RepSnapper_Manual:Introduction\n"
"G21 ; metric is good!\n"
"G90 ; absolute positioning\n"
"T0 ; select new extruder\n"
"G28 ; go home\n"
"G92 E0 ; set extruder home\n"
"M104 S200.0 ; set temperature to 200.0\n"
"G1 X20 Y20 F500 ; move away from 0.0, to use the same reset for each layer\n\n");
m_GCode[GCODE_TEXT_LAYER]->set_text ("");
m_GCode[GCODE_TEXT_END]->set_text
("G1 X0 Y0 F2000.0 ; feed for start of next move\n"
"M104 S0.0 ; heater off\n");
}
};
std::string Settings::GCodeType::getText(GCodeTextType t)
{
return m_impl->m_GCode[t]->get_text();
}
void Settings::SlicingSettings::GetAltInfillLayers(std::vector<int>& layers, uint layerCount) const
{
size_t start = 0, end = AltInfillLayersText.find(',');
if (AltInfillLayersText == "")
return;
while(start != std::string::npos) {
int num = atoi(AltInfillLayersText.data() + start);
if(num < 0) {
num += layerCount;
}
layers.push_back (num);
start = end;
end = AltInfillLayersText.find(',', start+1);
}
}
Settings::Settings ()
{
GCode.m_impl = new GCodeImpl();
set_defaults();
}
Settings::~Settings()
{
}
void Settings::set_defaults ()
{
for (uint i = 0; i < G_N_ELEMENTS (settings); i++) {
switch (settings[i].type) {
case T_BOOL:
*PTR_BOOL(this, i) = settings[i].def_double != 0.0;
break;
case T_INT:
*PTR_INT(this, i) = settings[i].def_double;
break;
case T_FLOAT:
case T_COLOUR_MEMBER:
*PTR_FLOAT(this, i) = settings[i].def_double;
break;
case T_STRING:
*PTR_STRING(this, i) = std::string (settings[i].def_string);
break;
default:
std::cerr << "corrupt setting type\n";
break;
}
}
Slicing.ShrinkQuality = SHRINK_FAST;
GCode.m_impl->setDefaults();
// The vectors map each to 3 spin boxes, one per dimension
Hardware.Volume = vmml::Vector3f (200,200,140);
Hardware.PrintMargin = vmml::Vector3f (10,10,0);
}
bool Settings::get_group_and_key (int i, Glib::ustring &group, Glib::ustring &key)
{
const char *name = settings[i].config_name;
if (!name) {
std::cerr << "Odd - some useful use of this field for setting " << i << "\n";
return false;
}
// re-use the display name
char *field = g_strdup (settings[i].glade_name);
if (!field)
field = g_strdup (settings[i].config_name);
char *p = strchr (field, '.');
if (!p) {
group = "Global";
key = field;
} else {
*p = '\0';
group = field;
key = p + 1;
}
g_free (field);
return true;
}
void Settings::load_settings (Glib::RefPtr<Gio::File> file)
{
Glib::KeyFile cfg;
set_defaults();
try {
if (!cfg.load_from_file (file->get_path())) {
std::cout << "Failed to load settings from file '" << file->get_path() << "\n";
return;
}
} catch (const Glib::KeyFileError &err) {
std::cout << "Exception " << err.what() << " loading settings from file '" << file->get_path() << "\n";
return;
}
std::cout << "parsing config from '" << file->get_path() << "\n";
for (uint i = 0; i < G_N_ELEMENTS (settings); i++) {
Glib::ustring group, key;
if (!get_group_and_key (i, group, key))
continue;
if (!cfg.has_key (group, key))
continue;
// group & string ...
switch (settings[i].type) {
case T_BOOL:
*PTR_BOOL(this, i) = cfg.get_boolean (group, key);
break;
case T_INT:
*PTR_INT(this, i) = cfg.get_integer (group, key);
break;
case T_FLOAT:
case T_COLOUR_MEMBER:
*PTR_FLOAT(this, i) = cfg.get_double (group, key);
break;
case T_STRING:
*PTR_STRING(this, i) = cfg.get_string (group, key);
break;
default:
std::cerr << "corrupt setting type\n";
break;
}
}
GCode.m_impl->loadSettings (cfg);
m_signal_visual_settings_changed.emit();
m_signal_update_settings_gui.emit();
}
void Settings::save_settings(Glib::RefPtr<Gio::File> file)
{
Glib::KeyFile cfg;
for (uint i = 0; i < G_N_ELEMENTS (settings); i++) {
Glib::ustring group, key;
if (!get_group_and_key (i, group, key))
continue;
switch (settings[i].type) {
case T_BOOL:
cfg.set_boolean (group, key, *PTR_BOOL(this, i));
break;
case T_INT:
cfg.set_integer (group, key, *PTR_INT(this, i));
break;
case T_FLOAT:
case T_COLOUR_MEMBER:
cfg.set_double (group, key, *PTR_FLOAT(this, i));
break;
case T_STRING:
cfg.set_string (group, key, *PTR_STRING(this, i));
break;
default:
std::cerr << "Can't save setting of unknown type\n";
break;
};
}
GCode.m_impl->saveSettings (cfg);
Glib::ustring contents = cfg.to_data();
Glib::file_set_contents (file->get_path(), contents);
}
void Settings::set_to_gui (Builder &builder, int i)
{
const char *glade_name = settings[i].glade_name;
if (!glade_name)
return;
switch (settings[i].type) {
case T_BOOL: {
Gtk::CheckButton *check = NULL;
builder->get_widget (glade_name, check);
if (!check)
std::cerr << "Missing boolean config item " << glade_name << "\n";
else
check->set_active (*PTR_BOOL(this, i));
break;
}
case T_INT:
case T_FLOAT: {
Gtk::Widget *w = NULL;
builder->get_widget (glade_name, w);
if (!w) {
std::cerr << "Missing user interface item " << glade_name << "\n";
break;
}
Gtk::SpinButton *spin = dynamic_cast<Gtk::SpinButton *>(w);
if (spin) {
if (settings[i].type == T_INT)
spin->set_value (*PTR_INT(this, i));
else
spin->set_value (*PTR_FLOAT(this, i));
break;
}
Gtk::Range *range = dynamic_cast<Gtk::Range *>(w);
if (range) {
if (settings[i].type == T_INT)
range->set_value (*PTR_INT(this, i));
else
range->set_value (*PTR_FLOAT(this, i));
}
break;
}
case T_STRING: {
Gtk::Entry *e = NULL;
builder->get_widget (glade_name, e);
if (!e) {
std::cerr << "Missing user interface item " << glade_name << "\n";
break;
}
e->set_text(*PTR_STRING(this, i));
break;
}
case T_COLOUR_MEMBER:
break; // Ignore, Colour members are special
default:
std::cerr << "corrupt setting type\n";
break;
}
}
void Settings::set_shrink_to_gui (Builder &builder)
{
// Slicing.ShrinkQuality
Gtk::ComboBox *combo = NULL;
builder->get_widget ("Slicing.ShrinkQuality", combo);
if (combo)
combo->set_active (Slicing.ShrinkQuality);
}
void Settings::get_from_gui (Builder &builder, int i)
{
const char *glade_name = settings[i].glade_name;
if (glade_name == NULL)
return; /* Not an automatically connected setting */
switch (settings[i].type) {
case T_BOOL: {
Gtk::CheckButton *check = NULL;
builder->get_widget (glade_name, check);
if (!check)
std::cerr << "Missing boolean config item " << glade_name << "\n";
else
*PTR_BOOL(this, i) = check->get_active();
break;
}
case T_INT:
case T_FLOAT: {
Gtk::Widget *w = NULL;
builder->get_widget (glade_name, w);
if (!w) {
std::cerr << "Missing GUI element " << glade_name << "\n";
break;
}
Gtk::SpinButton *spin = dynamic_cast<Gtk::SpinButton *>(w);
if (spin) {
if (settings[i].type == T_INT)
*PTR_INT(this, i) = spin->get_value();
else
*PTR_FLOAT(this, i) = spin->get_value();
break;
}
Gtk::Range *range = dynamic_cast<Gtk::Range *>(w);
if (range) {
if (settings[i].type == T_INT)
*PTR_INT(this, i) = range->get_value();
else
*PTR_FLOAT(this, i) = range->get_value();
}
break;
}
case T_STRING: {
Gtk::Entry *e = NULL;
builder->get_widget (glade_name, e);
if (!e) {
std::cerr << "Missing user interface item " << glade_name << "\n";
break;
}
*PTR_STRING(this, i) = std::string(e->get_text());
break;
}
case T_COLOUR_MEMBER:
// Ignore, colour members are special
break;
default:
std::cerr << "corrupt setting type\n";
break;
}
if (settings[i].triggers_redraw)
m_signal_visual_settings_changed.emit();
}
void Settings::get_shrink_from_gui (Builder &builder)
{
// Slicing.ShrinkQuality
Gtk::ComboBox *combo = NULL;
builder->get_widget ("Slicing.ShrinkQuality", combo);
if (combo)
Slicing.ShrinkQuality = combo->get_active_row_number ();
}
void Settings::get_port_speed_from_gui (Builder &builder)
{
// Hardware.SerialSpeed
Gtk::ComboBoxEntry *combo = NULL;
builder->get_widget ("Hardware.SerialSpeed", combo);
if (combo)
Hardware.SerialSpeed = atoi(combo->get_active_text().c_str());
}
void Settings::get_colour_from_gui (Builder &builder, int i)
{
const char *glade_name = colour_selectors[i].glade_name;
vmml::Vector4f *dest =
(vmml::Vector4f *)PTR_OFFSET(this, colour_selectors[i].member_offset);
Gdk::Color c;
Gtk::ColorButton *w = NULL;
builder->get_widget (glade_name, w);
if (!w) return;
c = w->get_color();
dest->r = c.get_red_p();
dest->g = c.get_green_p();
dest->b = c.get_blue_p();
dest->a = (float) (w->get_alpha()) / 65535.0;
m_signal_visual_settings_changed.emit();
}
void Settings::set_to_gui (Builder &builder)
{
for (uint i = 0; i < G_N_ELEMENTS (settings); i++) {
const char *glade_name = settings[i].glade_name;
if (!glade_name)
continue;
set_to_gui (builder, i);
}
set_shrink_to_gui (builder);
for (uint i = 0; i < G_N_ELEMENTS (colour_selectors); i++) {
const char *glade_name = colour_selectors[i].glade_name;
vmml::Vector4f *src =
(vmml::Vector4f *) PTR_OFFSET(this, colour_selectors[i].member_offset);
Gdk::Color c;
Gtk::ColorButton *w = NULL;
builder->get_widget (glade_name, w);
if (w) {
w->set_use_alpha(true);
c.set_rgb_p(src->r, src->g, src->b);
w->set_color(c);
w->set_alpha(src->a * 65535.0);
}
}
// Set serial speed. Find the row that holds this value
Gtk::ComboBoxEntry *portspeed = NULL;
builder->get_widget ("Hardware.SerialSpeed", portspeed);
if (portspeed) {
std::ostringstream ostr;
ostr << Hardware.SerialSpeed;
Glib::ustring val(ostr.str());
portspeed->get_entry()->set_text(val);
}
}
void Settings::connect_to_ui (Builder &builder)
{
// connect gcode configurable text sections
GCode.m_impl->connectToUI (builder);
// first setup ranges on spinbuttons ...
for (uint i = 0; i < G_N_ELEMENTS (spin_ranges); i++) {
Gtk::SpinButton *spin = NULL;
builder->get_widget (spin_ranges[i].widget, spin);
if (!spin)
std::cerr << "missing spin button of name '" << spin_ranges[i].widget << "'\n";
else {
spin->set_range (spin_ranges[i].min, spin_ranges[i].max);
spin->set_increments (spin_ranges[i].inc, spin_ranges[i].inc_page);
}
}
// Ranges on [HV]Range widgets
for (uint i = 0; i < G_N_ELEMENTS (ranges); i++) {
Gtk::Range *range = NULL;
builder->get_widget (ranges[i].widget, range);
if (!range)
std::cerr << "missing range slider of name '" << ranges[i].widget << "'\n";
else {
range->set_range (ranges[i].min, ranges[i].max);
range->set_increments (ranges[i].inc, ranges[i].inc_page);
}
}
// connect widget / values from our table
for (uint i = 0; i < G_N_ELEMENTS (settings); i++) {
const char *glade_name = settings[i].glade_name;
if (!glade_name)
continue;
switch (settings[i].type) {
case T_BOOL: {
Gtk::CheckButton *check = NULL;
builder->get_widget (glade_name, check);
if (check)
check->signal_toggled().connect
(sigc::bind(sigc::bind(sigc::mem_fun(*this, &Settings::get_from_gui), i), builder));
break;
}
case T_INT:
case T_FLOAT: {
Gtk::Widget *w = NULL;
builder->get_widget (glade_name, w);
if (!w) {
std::cerr << "Missing user interface item " << glade_name << "\n";
break;
}
Gtk::SpinButton *spin = dynamic_cast<Gtk::SpinButton *>(w);
if (spin) {
spin->signal_value_changed().connect
(sigc::bind(sigc::bind(sigc::mem_fun(*this, &Settings::get_from_gui), i), builder));
break;
}
Gtk::Range *range = dynamic_cast<Gtk::Range *>(w);
if (range) {
range->signal_value_changed().connect
(sigc::bind(sigc::bind(sigc::mem_fun(*this, &Settings::get_from_gui), i), builder));
break;
}
break;
}
case T_STRING: // unimplemented
break;
default:
break;
}
}
// Slicing.ShrinkQuality
Gtk::ComboBox *combo = NULL;
builder->get_widget ("Slicing.ShrinkQuality", combo);
if (combo) {
Glib::RefPtr<Gtk::ListStore> model;
Gtk::TreeModelColumnRecord record;
Gtk::TreeModelColumn<Glib::ustring> column;
record.add (column);
model = Gtk::ListStore::create(record);
model->append()->set_value (0, Glib::ustring("Fast"));
model->append()->set_value (0, Glib::ustring("Logick"));
combo->set_model (model);
combo->pack_start (column);
combo->signal_changed().connect
(sigc::bind(sigc::mem_fun(*this, &Settings::get_shrink_from_gui), builder));
}
// Colour selectors
for (uint i = 0; i < G_N_ELEMENTS (colour_selectors); i++) {
const char *glade_name = colour_selectors[i].glade_name;
Gdk::Color c;
Gtk::ColorButton *w = NULL;
if (!glade_name)
continue;
builder->get_widget (glade_name, w);
if (!w) continue;
w->signal_color_set().connect
(sigc::bind(sigc::bind(sigc::mem_fun(*this,
&Settings::get_colour_from_gui), i), builder));
}
// Serial port speed
Gtk::ComboBoxEntry *portspeed = NULL;
builder->get_widget ("Hardware.SerialSpeed", portspeed);
if (portspeed) {
const guint32 speeds[] = {
9600, 19200, 38400, 57600, 115200, 230400, 576000
};
Glib::RefPtr<Gtk::ListStore> model;
Gtk::TreeModelColumnRecord record;
Gtk::TreeModelColumn<Glib::ustring> column;
record.add (column);
model = Gtk::ListStore::create(record);
for (guint i = 0; i < G_N_ELEMENTS(speeds); i++) {
std::ostringstream val;
val << speeds[i];
model->append()->set_value (0, Glib::ustring(val.str()));
}
portspeed->set_model (model);
portspeed->set_text_column (0);
portspeed->signal_changed().connect
(sigc::bind(sigc::mem_fun(*this, &Settings::get_port_speed_from_gui), builder));
}
/* Update UI with defaults */
m_signal_update_settings_gui.emit();
}
| [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
]
| [
[
[
1,
23
],
[
26,
50
],
[
59,
59
],
[
70,
76
],
[
78,
78
],
[
80,
82
],
[
84,
86
],
[
88,
90
],
[
93,
95
],
[
103,
105
],
[
113,
116
],
[
121,
121
],
[
127,
128
],
[
132,
132
],
[
136,
136
],
[
143,
144
],
[
160,
160
],
[
163,
164
],
[
168,
169
],
[
171,
171
],
[
213,
214
],
[
286,
286
],
[
302,
303
],
[
305,
307
],
[
351,
353
],
[
359,
361
],
[
366,
371
],
[
373,
398
],
[
400,
412
],
[
414,
414
],
[
416,
419
],
[
446,
446
],
[
448,
451
],
[
455,
455
],
[
459,
459
],
[
462,
463
],
[
465,
465
],
[
467,
468
],
[
473,
473
],
[
476,
477
],
[
479,
480
],
[
483,
484
],
[
486,
490
],
[
508,
510
],
[
512,
513
],
[
515,
516
],
[
519,
520
],
[
522,
523
],
[
525,
528
],
[
530,
530
],
[
533,
539
],
[
543,
554
],
[
577,
578
],
[
587,
587
],
[
591,
596
],
[
606,
609
],
[
613,
624
],
[
648,
649
],
[
658,
658
],
[
663,
666
],
[
670,
671
],
[
748,
748
],
[
751,
752
],
[
754,
754
],
[
756,
756
],
[
758,
758
],
[
772,
787
],
[
789,
792
],
[
812,
818
],
[
882,
882
]
],
[
[
24,
25
],
[
51,
58
],
[
60,
69
],
[
77,
77
],
[
79,
79
],
[
87,
87
],
[
91,
92
],
[
96,
102
],
[
106,
112
],
[
117,
120
],
[
122,
126
],
[
129,
131
],
[
133,
135
],
[
137,
138
],
[
140,
142
],
[
145,
156
],
[
159,
159
],
[
162,
162
],
[
165,
167
],
[
172,
182
],
[
184,
201
],
[
203,
209
],
[
211,
212
],
[
215,
271
],
[
273,
285
],
[
287,
299
],
[
301,
301
],
[
399,
399
],
[
415,
415
],
[
460,
460
],
[
481,
481
],
[
517,
517
],
[
540,
542
],
[
555,
576
],
[
579,
586
],
[
588,
590
],
[
610,
612
],
[
625,
647
],
[
650,
657
],
[
659,
662
],
[
667,
667
],
[
681,
708
],
[
720,
744
],
[
753,
753
],
[
755,
755
],
[
757,
757
],
[
759,
771
],
[
788,
788
],
[
793,
811
],
[
837,
878
],
[
880,
880
]
],
[
[
83,
83
],
[
139,
139
],
[
157,
158
],
[
161,
161
],
[
170,
170
],
[
183,
183
],
[
272,
272
],
[
300,
300
],
[
304,
304
],
[
308,
350
],
[
354,
358
],
[
362,
365
],
[
372,
372
],
[
413,
413
],
[
420,
445
],
[
447,
447
],
[
452,
454
],
[
456,
458
],
[
461,
461
],
[
464,
464
],
[
466,
466
],
[
469,
472
],
[
474,
475
],
[
478,
478
],
[
482,
482
],
[
485,
485
],
[
491,
507
],
[
511,
511
],
[
514,
514
],
[
518,
518
],
[
521,
521
],
[
524,
524
],
[
529,
529
],
[
531,
532
],
[
597,
605
],
[
668,
669
],
[
672,
680
],
[
709,
719
],
[
745,
747
],
[
749,
750
],
[
819,
836
],
[
879,
879
],
[
881,
881
]
],
[
[
202,
202
],
[
210,
210
]
]
]
|
4a02a3ad9e324da84b53369efe97199f187ae443 | b2b5c3694476d1631322a340c6ad9e5a9ec43688 | /Baluchon/RectangularFacet.cpp | 7c55d5d97e66d1506bbbb84d49f6da60be39f3fa | []
| no_license | jpmn/rough-albatross | 3c456ea23158e749b029b2112b2f82a7a5d1fb2b | eb2951062f6c954814f064a28ad7c7a4e7cc35b0 | refs/heads/master | 2016-09-05T12:18:01.227974 | 2010-12-19T08:03:25 | 2010-12-19T08:03:25 | 32,195,707 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,158 | cpp | #include "RectangularFacet.h"
#include "MathUtility.h"
using namespace baluchon::utilities;
namespace baluchon { namespace core { namespace datas { namespace detection {
RectangularFacet::RectangularFacet(void) {
}
RectangularFacet::~RectangularFacet(void) {
}
CvPoint RectangularFacet::getCenterPosition(void) {
return MathUtility::middle(this->getTopLeftVertex(), this->getBottomRightVertex());
}
void RectangularFacet::setTopLeftVertex(CvPoint vertex) {
mTopLeftVertex = vertex;
}
void RectangularFacet::setTopRightVertex(CvPoint vertex) {
mTopRightVertex = vertex;
}
void RectangularFacet::setBottomLeftVertex(CvPoint vertex) {
mBottomLeftVertex = vertex;
}
void RectangularFacet::setBottomRightVertex(CvPoint vertex) {
mBottomRightVertex = vertex;
}
CvPoint RectangularFacet::getTopLeftVertex(void) {
return mTopLeftVertex;
}
CvPoint RectangularFacet::getTopRightVertex(void) {
return mTopRightVertex;
}
CvPoint RectangularFacet::getBottomLeftVertex(void) {
return mBottomLeftVertex;
}
CvPoint RectangularFacet::getBottomRightVertex(void) {
return mBottomRightVertex;
}
}}}}; | [
"jpmorin196@bd4f47a5-da4e-a94a-6a47-2669d62bc1a5"
]
| [
[
[
1,
53
]
]
]
|
921c3567bc53db84d002e026bd42fb3c1ee67dff | 5236606f2e6fb870fa7c41492327f3f8b0fa38dc | /nsrpc/src/p2p/P2pSessionImpl.h | 58d57698589a7db81e297223109c4db0f44ec1cc | []
| no_license | jcloudpld/srpc | aa8ecf4ffc5391b7183b19d217f49fb2b1a67c88 | f2483c8177d03834552053e8ecbe788e15b92ac0 | refs/heads/master | 2021-01-10T08:54:57.140800 | 2010-02-08T07:03:00 | 2010-02-08T07:03:00 | 44,454,693 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,628 | h | #ifndef NSRPC_P2PSESSIONIMPL_H
#define NSRPC_P2PSESSIONIMPL_H
#ifdef _MSC_VER
# pragma once
#endif
#include "SystemServiceImpl.h"
#include "StunServiceImpl.h"
#include "RelayServiceImpl.h"
#include "PeerCandidate.h"
#include "PeerManager.h"
#include "GroupManager.h"
#include "PluginManager.h"
#include "PeerMessageHandler.h"
#include "RelayServiceHandler.h"
#include "StunServiceHandler.h"
#include "SystemServiceHandler.h"
#include "AnonymousMessageManager.h"
#include <nsrpc/p2p/detail/PeerCipherKeyCache.h>
#include <nsrpc/p2p/detail/P2pEndpoint.h>
#include <nsrpc/p2p/detail/P2pRpcNetwork.h>
#include <nsrpc/p2p/detail/PeerNetworkSender.h>
#include <nsrpc/p2p/detail/PeerNotifier.h>
#include <nsrpc/p2p/P2pEventHandler.h>
#include <nsrpc/p2p/P2pConfig.h>
#include <nsrpc/p2p/P2pSession.h>
#include <nsrpc/detail/PacketCoder.h>
#include <nsrpc/utility/MessageBlockManager.h>
namespace nsrpc
{
namespace detail
{
/** @addtogroup p2p
* @{
*/
/**
* @class P2pSessionImpl
* P2P Session Impl
*/
class P2pSessionImpl : public P2pSession,
private PeerNotifier,
private PeerNetworkSender,
private PeerMessageHandler,
private RelayServiceHandler,
private StunServiceHandler,
private SystemServiceHandler,
private P2pEventHandler
{
public:
P2pSessionImpl(PeerId peerId, P2pEventHandler& eventHandler,
const P2pConfig& p2pConfig, bool useBitPacking,
PacketCoder* packetCoder);
virtual ~P2pSessionImpl();
private: // information hiding
virtual void attach(PlugInPtr& plugIn);
virtual void detach(PlugInPtr& plugIn);
virtual bool open(srpc::UInt16 port, const srpc::String& password,
P2pOptions p2pOptions);
virtual void close();
virtual void addP2pOptions(P2pOptions p2pOptions);
virtual void host(size_t maxPeers, bool hostMigration,
const PeerIds& hostPrecedence);
virtual void connect(const PeerAddresses& hostAddresses);
virtual void disconnect();
virtual void disconnect(PeerId peerId);
virtual void setRelayServer(const PeerAddress& address,
const srpc::String& cipherKey);
virtual void setHost(PeerId newHostId);
virtual void tick();
virtual GroupId createGroup(const RGroupName& groupName);
virtual bool destroyGroup(GroupId groupId);
virtual bool joinGroup(GroupId groupId);
virtual bool leaveGroup(GroupId groupId);
virtual const RGroupMap& getGroups() const;
virtual bool isHost() const {
return peerManager_.isHost();
}
virtual size_t getPeerCount() const {
return peerManager_.getPeerCount();
}
virtual PeerId getPeerId() const {
return myPeerId_;
}
virtual PeerAddress getTargetAddress(PeerId peerId) const;
virtual PeerAddresses getAddresses(PeerId peerId) const;
virtual P2pOptions getP2pOptions(PeerId peerId) const;
virtual PeerStats getStats(PeerId peerId) const;
virtual srpc::String getStatsString(PeerId peerId) const;
virtual srpc::RpcNetwork& getRpcNetwork() {
return rpcNetwork_;
}
virtual PeerId getHostPeerId() const;
virtual bool isHostAlive() const;
private:
void connectToPeer(PeerId peerId, const Addresses& peerAddresses);
void makeHost(PeerId peerId);
void detectConnectionTimeout();
void addMyPeer(P2pOptions p2pOptions);
void flush();
void resolve();
void tryToConnect(PeerId peerId,
const ACE_INET_Addr& targetAddress, const ACE_INET_Addr& peerAddress);
bool encodeMessage(ACE_Message_Block& mblock,
const PeerIdPair& peerIdPair, srpc::RpcPacketType packetType,
SequenceNumber sequenceNumber, PeerTime sentTime);
bool decodeMessage(P2pPacketHeader& header,
const ACE_INET_Addr& peerAddress, ACE_Message_Block& mblock);
void disconnected(PeerId peerId);
void messageArrived(const P2pPacketHeader& header,
const ACE_INET_Addr& peerAddress, ACE_Message_Block* mblock);
void acknowledge(PeerId peerId, const Message& message);
void migrateHost();
bool canRelay(const ACE_INET_Addr& targetAddress) const;
bool isRelayServerAddress(const ACE_INET_Addr& address) const {
return address == relayServerAddress_;
}
bool isSelf(PeerId peerId) const {
return peerId == myPeerId_;
}
private:
// = PeerNotifier overriding
virtual void onMessageArrived(const ACE_INET_Addr& peerAddress);
// = PeerNetworkSender overriding
virtual bool sendNow(const PeerIdPair& peerIdPair,
const AddressPair& addressPair, const ACE_Message_Block& mblock,
srpc::RpcPacketType packetType, SequenceNumber sequenceNumber,
PeerTime sentTime);
virtual void marshalingErrorOccurred();
virtual void sendOutgoingMessage(srpc::RpcPacketType packetType,
ACE_Message_Block* mblock, const P2pPeerHint* peerHint);
virtual size_t getPacketHeaderSize() const;
// = PeerMessageHandler overriding
virtual bool handleIncomingMessage(PeerId peerId,
const Message& message);
virtual bool acknowledgedConnect(PeerId peerId);
virtual void peerDisconnecting(PeerId peerId);
virtual void sendPing(PeerId peerId);
virtual void sendAcknowledgement(PeerId peerId, const Message& message);
// = SystemServiceHandler overriding
virtual bool authenticate(PeerId peerId,
const srpc::String& sessionPassword, srpc::UInt32 sessionKey);
virtual bool peerConnected(PeerId peerId,
const ACE_INET_Addr& targetAddress, const RAddresses& peerAddresses,
P2pOptions p2pOptions);
virtual void peerDisconnected(PeerId peerId);
virtual void connectToNewPeer(PeerId peerId,
const Addresses& peerAddresses);
virtual void hostMigrated(PeerId peerId);
virtual void setGroups(const RGroupMap& groups);
virtual void groupCreated(const RGroupInfo& groupInfo);
virtual void groupDestroyed(GroupId groupId);
virtual void groupJoined(GroupId groupId, PeerId peerId);
virtual void groupLeft(GroupId groupId, PeerId peerId);
virtual void setP2pProperty(const RP2pProperty& p2pProperty) {
p2pProperty_ = p2pProperty;
}
virtual bool shouldConnectReversal(const ACE_INET_Addr& address) const {
return isRelayServerAddress(address);
}
virtual bool isHostConnected() const;
virtual const RGroupMap& getCurrentGroups() const;
// = StunServiceHandler overriding
virtual void resolved(const srpc::String& ipAddress, srpc::UInt16 port);
// = RelayServiceHandler overriding
virtual ACE_Message_Block* acquire(size_t blockSize);
virtual void relayed(PeerId peerId, const ACE_INET_Addr& peerAddress,
ACE_Message_Block* mblock, srpc::RpcPacketType packetType,
SequenceNumber sequenceNumber, srpc::UInt32 sentTime);
// = P2pEventHandler overriding
virtual void onPeerConnected(PeerId peerId);
virtual void onPeerDisconnected(PeerId peerId);
virtual void onConnectFailed(PeerId peerId);
virtual void onAddressResolved(const srpc::String& ipAddress,
srpc::UInt16 port);
virtual void onHostMigrated(PeerId peerId);
virtual void onGroupCreated(const RGroupInfo& groupInfo);
virtual void onGroupDestroyed(GroupId groupId);
virtual void onGroupJoined(GroupId groupId, PeerId peerId);
virtual void onGroupLeft(GroupId groupId, PeerId peerId);
private:
const PeerId myPeerId_; ///< my peer id
P2pEventHandler& eventHandler_;
const P2pConfig p2pConfig_;
boost::scoped_ptr<ACE_Reactor> reactor_;
boost::scoped_ptr<PacketCoder> packetCoder_;
NoSynchMessageBlockManager messageBlockManager_;
ACE_Message_Block* recvBlock_;
ACE_Message_Block* sendBlock_;
P2pRpcNetwork rpcNetwork_;
P2pEndpoint endpoint_;
RpcSystemServiceImpl systemService_;
RpcStunServiceImpl stunService_;
RpcRelayServiceImpl relayService_;
AnonymousMessageManager anonymousMessageManager_;
ACE_INET_Addr relayServerAddress_;
RP2pProperty p2pProperty_;
PacketCoder::Seed encryptSeed_;
PacketCoder::Seed decryptSeed_;
PeerCipherKeyCache peerCipherKeys_;
PeerCandidateManager peerCandidateManager_;
PeerManager peerManager_;
GroupManager groupManager_;
PluginManager plugInManager_;
};
/** @} */ // addtogroup p2p
} // namespace detail
} // namespace nsrpc
#endif // NSRPC_P2PSESSIONIMPL_H
| [
"kcando@6d7ccee0-1a3b-0410-bfa1-83648d9ec9a4"
]
| [
[
[
1,
257
]
]
]
|
ffba1c520d1df633a3771093646b4dcc504c75fd | 1c9f99b2b2e3835038aba7ec0abc3a228e24a558 | /Projects/elastix/elastix_sources_v4/src/Common/itkMeshFileReaderBase.h | c9f42d5a16f038cae29da47e25122a70de097be9 | []
| no_license | mijc/Diploma | 95fa1b04801ba9afb6493b24b53383d0fbd00b33 | bae131ed74f1b344b219c0ffe0fffcd90306aeb8 | refs/heads/master | 2021-01-18T13:57:42.223466 | 2011-02-15T14:19:49 | 2011-02-15T14:19:49 | 1,369,569 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,891 | h | /*======================================================================
This file is part of the elastix software.
Copyright (c) University Medical Center Utrecht. All rights reserved.
See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for
details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
======================================================================*/
#ifndef __itkMeshFileReaderBase_h
#define __itkMeshFileReaderBase_h
#include "itkMeshSource.h"
#include "itkExceptionObject.h"
namespace itk
{
/** \brief Base exception class for IO conflicts. */
class MeshFileReaderException : public ExceptionObject
{
public:
/** Run-time information. */
itkTypeMacro( MeshFileReaderException, ExceptionObject );
/** Constructor. */
MeshFileReaderException(const char *file, unsigned int line,
const char* message = "Error in IO",
const char* loc = "Unknown") :
ExceptionObject(file, line, message, loc)
{
}
/** Constructor. */
MeshFileReaderException(const std::string &file, unsigned int line,
const char* message = "Error in IO",
const char* loc = "Unknown") :
ExceptionObject(file, line, message, loc)
{
}
};
/** \class MeshFileReaderBase
*
* \brief Base class for mesh readers
*
* A base class for classes that read a file containing
* a mesh or a pointset.
*/
template <class TOutputMesh>
class MeshFileReaderBase : public MeshSource<TOutputMesh>
{
public:
/** Standard class typedefs. */
typedef MeshFileReaderBase Self;
typedef MeshSource<TOutputMesh> Superclass;
typedef SmartPointer<Self> Pointer;
typedef SmartPointer<const Self> ConstPointer;
/** Method for creation through the object factory. */
itkNewMacro(Self);
/** Run-time type information (and related methods). */
itkTypeMacro(MeshFileReaderBase, MeshSource);
/** Some convenient typedefs. */
typedef typename Superclass::DataObjectPointer DatabObjectPointer;
typedef typename Superclass::OutputMeshType OutputMeshType;
typedef typename Superclass::OutputMeshPointer OutputMeshPointer;
/** Set/Get the filename */
itkGetStringMacro(FileName);
itkSetStringMacro(FileName);
/** Prepare the allocation of the output mesh during the first back
* propagation of the pipeline. */
virtual void GenerateOutputInformation(void);
/** Give the reader a chance to indicate that it will produce more
* output than it was requested to produce. MeshFileReader cannot
* currently read a portion of a mesh, so the MeshFileReader must
* enlarge the RequestedRegion to the size of the mesh on disk. */
virtual void EnlargeOutputRequestedRegion(DataObject *output);
protected:
MeshFileReaderBase();
virtual ~MeshFileReaderBase(){};
/** Test whether the given filename exist and it is readable,
this is intended to be called before attempting to use
subclasses for actually reading the file. If the file
doesn't exist or it is not readable, and exception with an
approriate message will be thrown. */
virtual void TestFileExistanceAndReadability();
std::string m_FileName;
private:
MeshFileReaderBase(const Self&); //purposely not implemented
void operator=(const Self&); //purposely not implemented
}; // end class
} // end namespace itk
#ifndef ITK_MANUAL_INSTANTIATION
#include "itkMeshFileReaderBase.txx"
#endif
#endif
| [
"[email protected]"
]
| [
[
[
1,
120
]
]
]
|
601d4d74ec9cd7551d26b247cc4ddcfe1afe3415 | 3c38acb995e4782c7fef1cffb8dacf169507f335 | /wstock/wstockgeturl.h | 37091cece9fe853e3b6625f72c841897841c48a1 | []
| no_license | Sunwinds/wesleystock | e9878b5df3ce90aa07d6431f1ebc646e82c725c0 | d37888f874bb7b9de9b2229e91efc7480729d729 | refs/heads/master | 2021-01-10T15:51:25.532013 | 2007-08-07T05:51:29 | 2007-08-07T05:51:29 | 52,593,442 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,473 | h | #ifndef WSTOCKGETURL_H_INCLUDED
#define WSTOCKGETURL_H_INCLUDED
/*
这个类以多线程的方式从某个url中获取数据,在数据获取完毕以后向它的父控件中发送消息。
*/
#include "wx/wx.h"
#include "wx/datetime.h"
#include "wx/thread.h"
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xpath.h>
class wxUrlGetDoneEvent : public wxNotifyEvent
{
public:
wxUrlGetDoneEvent(wxEventType commandType = wxEVT_NULL, int id = 0, void*data=NULL): wxNotifyEvent(commandType, id){
UserData = data;
requestTime = wxDateTime::Now();
};
wxUrlGetDoneEvent(const wxUrlGetDoneEvent& event): wxNotifyEvent(event){
Result = event.Result;
RetCode = event.RetCode;
UserData = event.UserData;
doc = event.doc;
requestTime = event.requestTime;
};
virtual wxEvent *Clone() const {
return new wxUrlGetDoneEvent(*this);
}
wxString Result;
int RetCode;
void *UserData;
wxDateTime requestTime;
xmlDocPtr doc;//valid when want xml;
DECLARE_DYNAMIC_CLASS(wxUrlGetDoneEvent);
};
typedef void (wxEvtHandler::*wxUrlGetDoneEventFunction)(wxUrlGetDoneEvent&);
extern const wxEventType wxEVT_URL_GET_DONE;
#define EVT_URL_GET_DONE(id, fn) DECLARE_EVENT_TABLE_ENTRY( \
wxEVT_URL_GET_DONE, id, -1, (wxObjectEventFunction) (wxEventFunction) \
(wxUrlGetDoneEventFunction) & fn, \
(wxObject *) NULL ),
class WStockGetUrl:public wxThread
{
public:
WStockGetUrl(wxEvtHandler*parent, const wxString& url, void* data){
Parent = parent;
Url = url;
WantXml=false;
UserData = data;
PostData = wxT("");
requestTime = wxDateTime::Now();
};
void SetPostData(const wxString&data){
PostData = data;
};
virtual void *Entry();
void SetCustomCmd(const wxString& cmd){
CusCmd = cmd;
};
void AppendCustomHead(const wxString& h){
CustomHeads.Add(h);
};
void SetWantXml(bool v){WantXml=v;};
private:
wxString Url;
wxString Proxy;
wxString CusCmd;
wxArrayString CustomHeads;
wxString PostData;
bool WantXml; //We expect xmlDocPtr in the retrive done event.//user need to release this doc
void * UserData;
wxEvtHandler *Parent;
wxDateTime requestTime;
};
#endif // WSTOCKGETURL_H_INCLUDED
| [
"cnwesleywang@112e404b-7d29-0410-b807-2d38108adb52"
]
| [
[
[
1,
82
]
]
]
|
2f29536ef7090aed4ca81ded8a69bb22a9e20f4d | 7a4dfb986f5bd5fbee2186fcf37a0a0a74ef6033 | /SubtitleGrabber/SubtitleGrabberDlg.h | 5e5f77492fa2fa1bfc7c0b6152c8655e19dd1feb | []
| no_license | zsjoska/subtitle-grabber | cad96727e73d6d3ec58eb3ad5eb1dfbac0c646bd | 8de1a741b2b7fdd2e7899738839516e729d23430 | refs/heads/master | 2016-09-06T19:14:26.133224 | 2007-05-30T09:20:55 | 2007-05-30T09:20:55 | 32,320,106 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,215 | h | // SubtitleGrabberDlg.h : header file
//
#pragma once
#include "afxwin.h"
// CSubtitleGrabberDlg dialog
class CSubtitleGrabberDlg : public CDialog
{
// Construction
public:
CSubtitleGrabberDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
enum { IDD = IDD_SUBTITLEGRABBER_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
HICON m_hIcon;
// Generated message map functions
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
DECLARE_MESSAGE_MAP()
afx_msg void OnBnClickedFldselect();
afx_msg void OnBnClickedOk();
public:
// the path selected by the user
CString m_strPath;
CString m_strUser;
CString m_strPassword;
CListBox m_ListAvail;
CListBox m_ListSelected;
void FillListBox(CListBox & listBox, CString strTokens);
CString MakeLangString(CListBox & listBox);
public:
afx_msg void OnLbnDblclkListavail();
public:
afx_msg void OnLbnDblclkListselected();
afx_msg LRESULT OnThreadMessage(WPARAM wParam, LPARAM lParam);
public:
CStatic m_StaticStatus;
};
| [
"zsjoska@a99920ad-ab31-0410-9f62-6da89933afc0"
]
| [
[
[
1,
53
]
]
]
|
c68a01f7a59ab05738a8d2d7a92db8ba8b3d5462 | 06965c8bfe9274f24b961eaad95062051aaec1b2 | /UnitAI.cpp | 67465c3ea6d2afe6ca2015f5ba6d5fb9d68f9dc7 | []
| no_license | vinaybalhara/BaczekKPAI | 902f2a27c1f565e9bae11ace82125052a3364306 | 9550e0c5abc260efc47355031aebd7d1831dfb0c | refs/heads/master | 2021-01-16T19:14:52.776176 | 2010-12-07T15:43:48 | 2010-12-07T15:43:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,289 | cpp |
#include "Sim/Units/CommandAI/CommandQueue.h"
#include "BaczekKPAI.h"
#include "Log.h"
#include "Unit.h"
#include "UnitAI.h"
#include "Goal.h"
#include "RNG.h"
UnitAI::UnitAI(BaczekKPAI* ai, Unit* owner):
owner(owner),
ai(ai),
currentGoalId(-1),
stuckInBaseCnt(0)
{
}
UnitAI::~UnitAI(void)
{
}
////////////////////////////////////////////////////////////////////////////////
// operators
bool operator<(const UnitAI& a, const UnitAI& b)
{
assert(a.owner);
assert(b.owner);
return a.owner->id < b.owner->id;
}
bool operator==(const UnitAI& a, const UnitAI& b)
{
assert(a.owner);
assert(b.owner);
return a.owner->id == b.owner->id;
}
////////////////////////////////////////////////////////////////////////////////
// overloads
struct on_complete_clean_current_goal : std::unary_function<Goal&, void> {
UnitAI* ai;
on_complete_clean_current_goal(UnitAI* uai):ai(uai) {}
void operator()(Goal& goal) { ai->currentGoalId = -1; ailog->info() << "cleaning currentGoal on " << ai->owner->id << std::endl; }
};
struct on_complete_clean_producing : std::unary_function<Goal&, void> {
Unit* unit;
on_complete_clean_producing(Unit* u):unit(u) {}
void operator()(Goal& goal) { unit->is_producing = false; ailog->info() << "cleaning is_producing on " << unit->id << std::endl; }
};
GoalProcessor::goal_process_t UnitAI::ProcessGoal(Goal* goal)
{
if (!goal) {
return PROCESS_POP_CONTINUE;
}
if (goal->is_finished()) {
return PROCESS_POP_CONTINUE;
}
if (currentGoalId >= 0) {
Goal* current = Goal::GetGoal(currentGoalId);
if (current) {
if (current->is_executing() && current->priority >= goal->priority) {
return PROCESS_BREAK;
}
}
}
if (goal->is_executing()) {
return PROCESS_BREAK;
} else if (goal->is_restarted()) {
goal->do_continue();
} else if (goal->is_suspended()) {
return PROCESS_BREAK;
}
ailog->info() << "EXECUTE GOAL: Unit " << owner->id << " executing goal " << goal->id << " type " << goal->type << std::endl;
switch (goal->type) {
case BUILD_EXPANSION: {
if (!owner->is_constructor) {
ailog->error() << "BUILD_EXPANSION issued to non-constructor unit" << std::endl;
return PROCESS_POP_CONTINUE;
}
Command c;
c.id = -FindExpansionUnitDefId();
assert(c.id);
assert(!goal->params.empty());
const float3& param = boost::get<float3>(goal->params[0]);
c.params.push_back(param.x);
c.params.push_back(param.y);
c.params.push_back(param.z);
ai->cb->GiveOrder(owner->id, &c);
goal->OnComplete(on_complete_clean_current_goal(this));
goal->OnAbort(on_complete_clean_current_goal(this));
goal->OnComplete(on_complete_clean_producing(this->owner));
goal->OnAbort(on_complete_clean_producing(this->owner));
owner->is_producing = true;
goal->start();
currentGoalId = goal->id;
break;
}
case BUILD_CONSTRUCTOR: {
if (!owner->is_base) {
ailog->error() << "BUILD_CONSTRUCTOR issued to non-base unit" << std::endl;
return PROCESS_POP_CONTINUE;
}
if (goal->is_executing()) {
return PROCESS_BREAK;
}
Command c;
c.id = -FindConstructorUnitDefId();
ai->cb->GiveOrder(owner->id, &c);
// FIXME XXX no way to track goal progress!
goal->complete();
return PROCESS_BREAK;
}
case MOVE:
case RETREAT: {
if (goal->params.empty()) {
ailog->error() << "no params on RETREAT or MOVE goal" << std::endl;
return PROCESS_POP_CONTINUE;
}
float3* param = boost::get<float3>(&goal->params[0]);
if (!param) {
ailog->error() << "invalid param on RETREAT or MOVE goal" << std::endl;
return PROCESS_POP_CONTINUE;
}
Command c;
c.id = CMD_MOVE;
// TODO formation offset
c.AddParam(param->x);
c.AddParam(param->y);
c.AddParam(param->z);
ai->cb->GiveOrder(owner->id, &c);
goal->OnComplete(on_complete_clean_current_goal(this));
goal->OnAbort(on_complete_clean_current_goal(this));
goal->start();
currentGoalId = goal->id;
return PROCESS_BREAK;
}
case ATTACK: {
if (goal->params.empty()) {
ailog->error() << "no params on ATTACK goal" << std::endl;
return PROCESS_POP_CONTINUE;
}
float3* paramf = boost::get<float3>(&goal->params[0]);
int* parami = boost::get<int>(&goal->params[0]);
if (!paramf && !parami) {
ailog->error() << "invalid param on ATTACK goal" << std::endl;
return PROCESS_POP_CONTINUE;
}
Command c;
if (paramf) { // attack move
c.id = CMD_FIGHT;
c.AddParam(paramf->x);
c.AddParam(paramf->y);
c.AddParam(paramf->z);
// it's good to have some units move up close
if (randfloat() < ai->python->GetFloatValue("pr_MOVEOnAttack", 0.1))
c.id = CMD_MOVE;
} else { // attack unit
c.id = CMD_ATTACK;
c.AddParam(*parami);
}
ai->cb->GiveOrder(owner->id, &c);
currentGoalId = goal->id;
goal->OnComplete(on_complete_clean_current_goal(this));
goal->OnAbort(on_complete_clean_current_goal(this));
goal->start();
return PROCESS_BREAK;
}
default:
return PROCESS_POP_CONTINUE;
}
return PROCESS_BREAK;
}
void UnitAI::Update()
{
int frameNum = ai->cb->GetCurrentFrame();
int phase = frameNum % GAME_SPEED;
if (phase == (owner ? owner->id%GAME_SPEED : 0)) {
if (owner) {
const UnitDef* ud = ai->cb->GetUnitDef(owner->id);
if (ud && ud->name == "worm") {
// set firestate to fire at will till a better solution is available
Command c;
c.id = CMD_FIRE_STATE;
c.AddParam(2);
ai->cb->GiveOrder(owner->id, &c);
}
}
std::sort(goals.begin(), goals.end(), goal_priority_less());
//DumpGoalStack("Unit");
CheckContinueGoal();
ProcessGoalStack(frameNum);
} else if (phase == 1) {
CheckBuildValid();
}
if (frameNum % GAME_SPEED == owner->id % GAME_SPEED) {
CheckStandingInBase();
if (owner->is_spam)
CheckSpamTargets();
}
}
void UnitAI::CheckContinueGoal()
{
if (currentGoalId < 0) {
return;
}
Goal* current = Goal::GetGoal(currentGoalId);
if (!current) {
currentGoalId = -1;
return;
}
if (current->is_restarted()) {
ailog->info() << "restarting goal " << current->id << " in CheckContinueGoal" << std::endl;
ProcessGoal(current);
}
}
void UnitAI::OwnerKilled()
{
// signal listeners
onKilled(*this);
currentGoalId = -1;
BOOST_FOREACH(int gid, goals) {
Goal* g = Goal::GetGoal(gid);
if (g)
Goal::RemoveGoal(g);
}
owner = 0;
}
////////////////////////////////////////////////////////////////////////////////////////////////
// utils
// TODO move to a data file
int UnitAI::FindExpansionUnitDefId()
{
assert(owner);
const UnitDef *ud = ai->cb->GetUnitDef(owner->id);
assert(ud);
if (ud->name == "assembler") {
const UnitDef *tobuild = ai->cb->GetUnitDef("socket");
assert(tobuild);
return tobuild->id;
} else if (ud->name == "trojan") {
const UnitDef *tobuild = ai->cb->GetUnitDef("window");
assert(tobuild);
return tobuild->id;
} else if (ud->name == "gateway") {
const UnitDef *tobuild = ai->cb->GetUnitDef("port");
assert(tobuild);
return tobuild->id;
}
return 0;
}
// TODO move to a data file
int UnitAI::FindConstructorUnitDefId()
{
assert(owner);
const UnitDef *ud = ai->cb->GetUnitDef(owner->id);
assert(ud);
if (ud->name == "kernel") {
const UnitDef *tobuild = ai->cb->GetUnitDef("assembler");
assert(tobuild);
return tobuild->id;
} else if (ud->name == "hole") {
const UnitDef *tobuild = ai->cb->GetUnitDef("trojan");
assert(tobuild);
return tobuild->id;
} else if (ud->name == "carrier") {
const UnitDef *tobuild = ai->cb->GetUnitDef("gateway");
assert(tobuild);
return tobuild->id;
}
return 0;
}
// TODO move to a data file
int UnitAI::FindSpamUnitDefId()
{
assert(owner);
const UnitDef *ud = ai->cb->GetUnitDef(owner->id);
assert(ud);
if (ud->name == "kernel" || ud->name == "socket") {
const UnitDef *tobuild = ai->cb->GetUnitDef("bit");
assert(tobuild);
return tobuild->id;
} else if (ud->name == "hole" || ud->name == "window") {
const UnitDef *tobuild = ai->cb->GetUnitDef("bug");
assert(tobuild);
return tobuild->id;
} else if (ud->name == "carrier" || ud->name == "port") {
const UnitDef *tobuild = ai->cb->GetUnitDef("packet");
assert(tobuild);
return tobuild->id;
}
return 0;
}
void UnitAI::CompleteCurrentGoal()
{
if (currentGoalId >= 0) {
Goal* currentGoal = Goal::GetGoal(currentGoalId);
if (currentGoal && !currentGoal->is_finished()) {
currentGoal->complete();
}
}
currentGoalId = -1;
owner->is_producing = false;
}
void UnitAI::SuspendCurrentGoal()
{
if (currentGoalId >= 0) {
Goal* currentGoal = Goal::GetGoal(currentGoalId);
if (currentGoal && !currentGoal->is_finished()) {
currentGoal->suspend();
}
}
}
void UnitAI::ContinueCurrentGoal()
{
if (currentGoalId >= 0) {
Goal* currentGoal = Goal::GetGoal(currentGoalId);
if (currentGoal && currentGoal->is_suspended()) {
currentGoal->continue_();
}
}
}
void UnitAI::CheckBuildValid()
{
assert(owner);
const CCommandQueue* q = ai->cb->GetCurrentUnitCommands(owner->id);
if (q->empty())
return;
// is the first command a "build at pos" command
Command c = *q->begin();
if (c.id >= 0)
return;
if (c.params.size() != 3)
return;
float3 pos(c.params[0], c.params[1], c.params[2]);
const UnitDef* ud = ai->GetUnitDefById(-c.id);
assert(ud);
std::vector<int> enemies;
ai->GetEnemiesInRadius(pos, 96, enemies);
if (!enemies.empty()) {
// we shouldn't be building here, abort
// unless of course it wasn't our goal...
Goal* goal = Goal::GetGoal(currentGoalId);
if (goal && goal->params.size() >= 1 && goal->type == BUILD_EXPANSION) {
float3& param = boost::get<float3>(goal->params[0]);
if (param.SqDistance2D(pos) < 8*8) {
ailog->info() << "aborting construction goal at " << pos << " for builder "
<< owner->id << " (goal id " << goal->id << ")" << std::endl;
goal->abort();
Command stop;
stop.id = CMD_STOP;
ai->cb->GiveOrder(owner->id, &stop);
for (std::vector<int>::iterator it = enemies.begin(); it != enemies.end(); ++it) {
ailog->info() << " enemy at " << ai->cheatcb->GetUnitPos(*it) << std::endl;
ai->CreateLineFigure(pos+float3(0, 100, 0), ai->cheatcb->GetUnitPos(*it)+float3(0, 100, 0), 5, 20, 900, 0);
}
}
}
}
}
// check if there are important targets for spam units around
void UnitAI::CheckSpamTargets()
{
assert(owner);
const CCommandQueue* q = ai->cb->GetCurrentUnitCommands(owner->id);
if (!q->empty()) {
Command c = *q->begin();
if (c.id != CMD_FIGHT && c.id != CMD_MOVE)
return;
}
int num;
int enemies[MAX_UNITS];
float radius = ai->python->GetFloatValue("spam_radius", 384);
float3 pos = ai->cb->GetUnitPos(owner->id);
num = ai->cheatcb->GetEnemyUnits(enemies, pos, radius);
int found = -1;
for (int i = 0; i<num; ++i) {
const UnitDef* ud = ai->cheatcb->GetUnitDef(enemies[i]);
if (!ud)
continue;
if (Unit::IsConstructor(ud) || ud->name == "pointer" || ud->name == "dos" || ud->name == "flow") {
found = enemies[i];
break;
}
}
if (found != -1) {
Command c;
c.id = CMD_INSERT;
c.options = ALT_KEY;
c.AddParam(0);
c.AddParam(CMD_ATTACK);
c.AddParam(0);
c.AddParam(found);
ai->cb->GiveOrder(owner->id, &c);
}
}
// do not stand in base and block construction
void UnitAI::CheckStandingInBase()
{
assert(owner);
if (owner->is_base)
return;
const CCommandQueue* q = ai->cb->GetCurrentUnitCommands(owner->id);
if (q->empty()) {
return;
}
else {
Command c = *q->begin();
if (c.id == CMD_MOVE)
return;
}
int friends[MAX_UNITS];
int num;
float3 pos = ai->cb->GetUnitPos(owner->id);
num = ai->cb->GetFriendlyUnits(friends, pos, ai->python->GetFloatValue("baseSearchRadius", 16));
for (int i = 0; i<num; ++i) {
Unit* u = ai->GetUnit(friends[i]);
if (u && u->is_base) {
// unstuck after a bit of time has passed
if (stuckInBaseCnt < ai->python->GetIntValue("maxBaseStuckCount", 3)) {
++stuckInBaseCnt;
break;
}
stuckInBaseCnt = 0;
float3 newpos;
// don't try to move back into the base
// also don't loop infinitely
int count = 50;
do {
newpos = random_offset_pos(pos, 48, 72);
--count;
} while (count && CheckPosInBase(newpos));
Command c;
c.id = CMD_INSERT;
c.options = ALT_KEY;
c.AddParam(0); // position in queue
c.AddParam(CMD_MOVE);
c.AddParam(0); // options
c.AddParam(newpos.x);
c.AddParam(newpos.y);
c.AddParam(newpos.z);
ai->cb->GiveOrder(owner->id, &c);
break;
}
}
}
bool UnitAI::CheckPosInBase(float3 pos)
{
int friends[MAX_UNITS];
int num;
num = ai->cb->GetFriendlyUnits(friends, pos, ai->python->GetFloatValue("baseSearchRadius", 16));
for (int i = 0; i<num; ++i) {
Unit* u = ai->GetUnit(friends[i]);
if (u && u->is_base) {
return true;
}
}
return false;
}
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
3
]
],
[
[
4,
520
]
]
]
|
1a24b7b6c46caca826b4d6065501dffa736d3700 | b4d726a0321649f907923cc57323942a1e45915b | /CODE/NETWORK/multiutil.cpp | bebfbf7f1ab1feb12b0803a541eedf8d700de330 | []
| 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 | 132,674 | cpp | /*
* Copyright (C) Volition, Inc. 1999. All rights reserved.
*
* All source code herein is the property of Volition, Inc. You may not sell
* or otherwise commercially exploit the source or things you created based on the
* source.
*
*/
/*
* $Logfile: /Freespace2/code/Network/MultiUtil.cpp $
* $Revision: 1.1.1.1 $
* $Date: 2004/08/13 22:47:42 $
* $Author: Spearhawk $
*
* C file that contains misc. functions to support multiplayer
*
* $Log: multiutil.cpp,v $
* Revision 1.1.1.1 2004/08/13 22:47:42 Spearhawk
* no message
*
* Revision 1.1.1.1 2004/08/13 21:26:48 Darkhill
* no message
*
* Revision 2.16 2004/03/31 05:42:27 Goober5000
* got rid of all those nasty warnings from xlocale and so forth; also added comments
* for #pragma warning disable to indicate the message being disabled
* --Goober5000
*
* Revision 2.15 2004/03/05 21:19:39 Kazan
* Fixed mission validation (was returning false positives)
*
* Revision 2.14 2004/03/05 09:02:02 Goober5000
* Uber pass at reducing #includes
* --Goober5000
*
* Revision 2.13 2003/11/11 02:15:45 Goober5000
* ubercommit - basically spelling and language fixes with some additional
* warnings disabled
* --Goober5000
*
* Revision 2.12 2003/11/09 04:09:18 Goober5000
* edited for language
* --Goober5000
*
* Revision 2.11 2003/11/06 20:22:13 Kazan
* slight change to .dsp - leave the release target as fs2_open_r.exe already
* added myself to credit
* killed some of the stupid warnings (including doing some casting and commenting out unused vars in the graphics modules)
* Release builds should have warning level set no higher than 2 (default is 1)
* Why are we getting warning's about function selected for inline expansion... (killing them with warning disables)
* FS2_SPEECH was not defined (source file doesn't appear to capture preproc defines correctly either)
*
* Revision 2.10 2003/10/30 15:30:23 Kazan
* lil update
*
* Revision 2.9 2003/10/15 22:03:26 Kazan
* Da Species Update :D
*
* Revision 2.8 2003/10/13 05:57:50 Kazan
* Removed a bunch of Useless *_printf()s in the rendering pipeline that were just slowing stuff down
* Commented out the "warning null vector in vector normalize" crap since we don't give a rats arse
* Added "beam no whack" flag for beams - said beams NEVER whack
* Some reliability updates in FS2NetD
*
* Revision 2.7 2003/10/04 22:42:23 Kazan
* fs2netd now TCP
*
* Revision 2.6 2003/09/25 21:12:24 Kazan
* ##Kazan## FS2NetD Completed! Just needs some thorough bug checking (i don't think there are any serious bugs)
* Also D3D8 Screenshots work now.
*
* Revision 2.5 2003/09/24 19:35:59 Kazan
* ##KAZAN## FS2 Open PXO --- W00t! Stats Storage, everything but table verification completed!
*
* Revision 2.4 2003/09/23 02:42:54 Kazan
* ##KAZAN## - FS2NetD Support! (FS2 Open PXO) -- Game Server Listing, and mission validation completed - stats storing to come - needs fs2open_pxo.cfg file [VP-able]
*
* Revision 2.3 2002/08/01 01:41:08 penguin
* The big include file move
*
* Revision 2.2 2002/07/22 01:22:26 penguin
* Linux port -- added NO_STANDALONE ifdefs
*
* Revision 2.1 2002/07/07 19:55:59 penguin
* Back-port to MSVC
*
* Revision 2.0 2002/06/03 04:02:26 penguin
* Warpcore CVS sync
*
* Revision 1.2 2002/05/13 21:09:28 mharris
* I think the last of the networking code has ifndef NO_NETWORK...
*
* Revision 1.1 2002/05/02 18:03:11 mharris
* Initial checkin - converted filenames and includes to lower case
*
*
* 47 9/15/99 1:45a Dave
* Don't init joystick on standalone. Fixed campaign mode on standalone.
* Fixed no-score-report problem in TvT
*
* 46 9/09/99 8:53p Dave
* Fixed multiplayer degenerate orientation case problem. Make sure warp
* effect never goes lower than LOD 1.
*
* 45 8/24/99 1:50a Dave
* Fixed client-side afterburner stuttering. Added checkbox for no version
* checking on PXO join. Made button info passing more friendly between
* client and server.
*
* 44 8/23/99 10:30a Dave
* Make sure a kill limit of 0 really means "no kill limit"
*
* 43 8/22/99 5:53p Dave
* Scoring fixes. Added self destruct key. Put callsigns in the logfile
* instead of ship designations for multiplayer players.
*
* 42 8/22/99 1:19p Dave
* Fixed up http proxy code. Cleaned up scoring code. Reverse the order in
* which d3d cards are detected.
*
* 41 8/19/99 10:59a Dave
* Packet loss detection.
*
* 40 8/06/99 2:44a Dave
* Make sure dead players who leave respawn AI.
*
* 39 8/06/99 12:29a Dave
* Multiple bug fixes.
*
* 38 8/03/99 11:02p Dave
* Maybe fixed sync problems in multiplayer.
*
* 37 7/30/99 7:01p Dave
* Dogfight escort gauge. Fixed up laser rendering in Glide.
*
* 36 7/26/99 5:50p Dave
* Revised ingame join. Better? We'll see....
*
* 35 7/15/99 9:20a Andsager
* FS2_DEMO initial checkin
*
* 34 7/08/99 10:53a Dave
* New multiplayer interpolation scheme. Not 100% done yet, but still
* better than the old way.
*
* 33 6/25/99 5:04p Jasenw
* Added some debug line stuff.
*
* 32 6/16/99 4:06p Dave
* New pilot info popup. Added new draw-bitmap-as-poly function.
*
* 31 5/18/99 11:50a Andsager
* Remove unused object type OBJ_GHOST_SAVE
*
* 30 5/04/99 5:20p Dave
* Fixed up multiplayer join screen and host options screen. Should both
* be at 100% now.
*
* 29 5/03/99 8:33p Dave
* New version of multi host options screen.
*
* 28 4/27/99 12:16a Dave
* Fixed beam weapon muzzle glow problem. Fixed premature timeout on the
* pxo server list screen. Fixed secondary firing for hosts on a
* standalone. Fixed wacky multiplayer weapon "shuddering" problem.
*
* 27 4/25/99 7:43p Dave
* Misc small bug fixes. Made sun draw properly.
*
* 26 4/25/99 3:02p Dave
* Build defines for the E3 build.
*
* 25 4/09/99 2:21p Dave
* Multiplayer beta stuff. CD checking.
*
* 24 4/08/99 2:10a Dave
* Numerous bug fixes for the beta. Added builtin mission info for the
* beta.
*
* 23 3/10/99 6:50p Dave
* Changed the way we buffer packets for all clients. Optimized turret
* fired packets. Did some weapon firing optimizations.
*
* 22 3/09/99 6:24p Dave
* More work on object update revamping. Identified several sources of
* unnecessary bandwidth.
*
* 21 3/08/99 7:03p Dave
* First run of new object update system. Looks very promising.
*
* 20 3/01/99 10:00a Dave
* Fxied several dogfight related stats bugs.
*
* 19 2/24/99 2:25p Dave
* Fixed up chatbox bugs. Made squad war reporting better. Fixed a respawn
* bug for dogfight more.
*
* 18 2/23/99 2:29p Dave
* First run of oldschool dogfight mode.
*
* 17 2/12/99 6:16p Dave
* Pre-mission Squad War code is 95% done.
*
* 16 2/11/99 3:08p Dave
* PXO refresh button. Very preliminary squad war support.
*
* 15 2/08/99 5:07p Dave
* FS2 chat server support. FS2 specific validated missions.
*
* 14 1/30/99 1:29a Dave
* Fixed nebula thumbnail problem. Full support for 1024x768 choose pilot
* screen. Fixed beam weapon death messages.
*
* 13 1/14/99 6:06p Dave
* 100% full squad logo support for single player and multiplayer.
*
* 12 1/12/99 4:07a Dave
* Put in barracks code support for selecting squad logos. Properly
* distribute squad logos in a multiplayer game.
*
* 11 12/14/98 4:01p Dave
* Got multi_data stuff working well with new xfer stuff.
*
* 10 12/14/98 12:13p Dave
* Spiffed up xfer system a bit. Put in support for squad logo file xfer.
* Need to test now.
*
* 9 11/19/98 4:19p Dave
* Put IPX sockets back in psnet. Consolidated all multiplayer config
* files into one.
*
* 8 11/19/98 8:04a Dave
* Full support for D3-style reliable sockets. Revamped packet lag/loss
* system, made it receiver side and at the lowest possible level.
*
* 7 11/17/98 11:12a Dave
* Removed player identification by address. Now assign explicit id #'s.
*
* 6 11/05/98 5:55p Dave
* Big pass at reducing #includes
*
* 5 10/13/98 9:29a Dave
* Started neatening up freespace.h. Many variables renamed and
* reorganized. Added AlphaColors.[h,cpp]
*
* 4 10/09/98 2:57p Dave
* Starting splitting up OS stuff.
*
* 3 10/07/98 6:27p Dave
* Globalized mission and campaign file extensions. Removed Silent Threat
* special code. Moved \cache \players and \multidata into the \data
* directory.
*
* 2 10/07/98 10:53a Dave
* Initial checkin.
*
* 1 10/07/98 10:50a Dave
*
* 283 9/28/98 1:54p Dave
* Make sure French and German don't xfer builtin files they don't have
* (to themselves)
*
* 282 9/28/98 1:41p Dave
* Properly detect "builtin" missions.
*
* 281 9/21/98 11:46p Dave
* Flag mission disk players in the right spot.
*
* 280 9/15/98 7:24p Dave
* Minor UI changes. Localized bunch of new text.
*
* $NoKeywords: $
*/
#if defined _WIN32
#include <winsock.h>
#elif defined unix
#include <arpa/inet.h>
#include <errno.h>
#endif
#include <ctype.h>
#include "network/multiutil.h"
#include "globalincs/linklist.h"
#include "gamesequence/gamesequence.h"
#include "hud/hudmessage.h"
#include "freespace2/freespace.h"
#include "io/key.h"
#include "io/timer.h"
#include "ship/ship.h"
#include "globalincs/alphacolors.h"
#include "graphics/font.h"
#include "gamesnd/gamesnd.h"
#include "playerman/player.h"
#include "mission/missionparse.h"
#include "missionui/missionshipchoice.h"
#include "network/stand_gui.h"
#include "ship/shipfx.h"
#include "object/object.h"
#include "playerman/managepilot.h"
#include "missionui/missiondebrief.h"
#include "observer/observer.h"
#include "mission/missionmessage.h"
#include "popup/popup.h"
#include "popup/popupdead.h"
#include "hud/hudconfig.h"
#include "menuui/optionsmenu.h"
#include "mission/missionhotkey.h"
#include "mission/missiongoals.h"
#include "ship/afterburner.h"
#include "missionui/chatbox.h"
#include "osapi/osregistry.h"
#include "hud/hudescort.h"
#include "network/multi.h"
#include "cmdline/cmdline.h"
#include "cfile/cfile.h"
#pragma warning(push)
// 4018 = signed/unsigned mismatch
// 4663 = new template specification syntax
// 4245 = signed/unsigned mismatch in conversion of const value
#pragma warning(disable: 4663 4018 4663 4245)
#include "fs2open_pxo/Client.h"
#pragma warning(pop)
#ifndef NO_NETWORK
#include "network/multimsgs.h"
#include "network/multi_xfer.h"
#include "network/multiteamselect.h"
#include "network/multiui.h"
#include "network/multi_kick.h"
#include "network/multi_data.h"
#include "network/multi_voice.h"
#include "network/multi_team.h"
#include "network/multi_respawn.h"
#include "network/multi_ingame.h"
#include "network/multi_observer.h"
#include "network/multi_pinfo.h"
#include "network/multi_endgame.h"
#include "network/multi_pmsg.h"
#include "network/multi_pause.h"
#include "network/multi_log.h"
#include "network/multi_rate.h"
#endif
extern int MSG_WINDOW_X_START; // used to position multiplayer text messages
extern int MSG_WINDOW_Y_START;
extern int MSG_WINDOW_HEIGHT;
extern int ascii_table[];
extern int shifted_ascii_table[];
#if !defined(PXO_TCP)
extern UDP_Socket FS2OpenPXO_Socket; // obvious :D - Kazan
#else
extern TCP_Socket FS2OpenPXO_Socket; // obvious :D - Kazan
#endif
// network object management
ushort Next_ship_signature; // next permanent network signature to assign to an object
ushort Next_asteroid_signature; // next signature for an asteroid
ushort Next_non_perm_signature; // next non-permanent network signature to assign to an object
ushort Next_debris_signature; // next debris signature
// if a client doesn't receive an update for an object after this many seconds, query server
// as to the objects status.
#define MULTI_CLIENT_OBJ_TIMEOUT 10
#define MAX_SHIPS_PER_QUERY 10
// this function assignes the given object with the given signature. If the signature is 0, then we choose
// the next signature number from the correct pool. I thought that it might be desireable
// to not always have to take the next signature on the list. what_kind is used to assign either a
// permanent or non-permanent signature to an object. permanent signatures are used for ships, non_permanent
// signatures are used for everything else.
ushort multi_assign_network_signature( int what_kind )
{
ushort sig;
// do limit checking on the permanent and non_permanent signatures. Ships are considered "permanent"
// as are debris and asteroids since they don't die very often. It would be vary rare for this
// value (the permanent signature) to wrap. For now, this condition is an error condition
if ( what_kind == MULTI_SIG_SHIP ) {
if ( Next_ship_signature == 0 ){
Next_ship_signature = SHIP_SIG_MIN;
}
sig = Next_ship_signature++;
if ( Next_ship_signature == SHIP_SIG_MAX ) {
Int3(); // get Allender -- signature stuff wrapped.
Next_ship_signature = SHIP_SIG_MIN;
}
// signature stuff for asteroids.
} else if ( what_kind == MULTI_SIG_ASTEROID ) {
if ( Next_asteroid_signature == 0 ){
Next_asteroid_signature = ASTEROID_SIG_MIN;
}
sig = Next_asteroid_signature++;
if ( Next_asteroid_signature == ASTEROID_SIG_MAX ) {
Int3(); // get Allender -- signature stuff wrapped.
Next_asteroid_signature = ASTEROID_SIG_MIN;
}
// signatures for debris
} else if ( what_kind == MULTI_SIG_DEBRIS ) {
if ( Next_debris_signature == 0 ){
Next_debris_signature = DEBRIS_SIG_MIN;
}
sig = Next_debris_signature++;
if ( Next_debris_signature == DEBRIS_SIG_MAX ) {
Int3(); // get Allender -- signature stuff wrapped.
Next_debris_signature = DEBRIS_SIG_MIN;
}
// signature stuff for weapons and other expendable things.
} else if ( what_kind == MULTI_SIG_NON_PERMANENT ) {
if ( Next_non_perm_signature == 0 ){
Next_non_perm_signature = NPERM_SIG_MIN;
}
sig = Next_non_perm_signature++;
if ( Next_non_perm_signature == NPERM_SIG_MAX ){
Next_non_perm_signature = NPERM_SIG_MIN;
}
} else {
Int3(); // get allender - Illegal signature type requested
sig = 0;
}
return sig;
}
// this function returns the next network signature that will be used for a newly created object
// what_kind parameter tells us what kind of signature to get -- permanent or non-permanent
ushort multi_get_next_network_signature( int what_kind )
{
if ( what_kind == MULTI_SIG_SHIP ) {
if ( Next_ship_signature == 0 )
Next_ship_signature = SHIP_SIG_MIN;
return Next_ship_signature;
} else if ( what_kind == MULTI_SIG_DEBRIS ) {
if ( Next_debris_signature == 0 )
Next_debris_signature = DEBRIS_SIG_MIN;
return Next_debris_signature;
} else if ( what_kind == MULTI_SIG_ASTEROID ) {
if ( Next_asteroid_signature == 0 )
Next_asteroid_signature = ASTEROID_SIG_MIN;
return Next_asteroid_signature;
} else if ( what_kind == MULTI_SIG_NON_PERMANENT ) {
if ( Next_non_perm_signature == 0 )
Next_non_perm_signature = NPERM_SIG_MIN;
return Next_non_perm_signature;
} else {
Int3(); // get allender
return 0;
}
}
// this routine sets the network signature to the given value. Should be called from client only
// and is used mainly for firing weapons. what_kind tells us permanent or non-permanent signature
void multi_set_network_signature( ushort signature, int what_kind )
{
Assert( signature != 0 );
if ( what_kind == MULTI_SIG_SHIP ) {
Assert( (signature >= SHIP_SIG_MIN) && (signature <= SHIP_SIG_MAX) );
Next_ship_signature = signature;
} else if ( what_kind == MULTI_SIG_DEBRIS ) {
Assert( (signature >= DEBRIS_SIG_MIN) && (signature <= DEBRIS_SIG_MAX) );
Next_debris_signature = signature;
} else if ( what_kind == MULTI_SIG_ASTEROID ) {
Assert( (signature >= ASTEROID_SIG_MIN) && (signature <= ASTEROID_SIG_MAX) );
Next_asteroid_signature = signature;
} else if ( what_kind == MULTI_SIG_NON_PERMANENT ) {
Assert( (signature >= NPERM_SIG_MIN) && (signature <= NPERM_SIG_MAX) );
Next_non_perm_signature = signature;
} else
Int3(); // get Allender
}
// multi_get_network_object() takes a net_signature and tries to locate the object in the object list
// with that network signature. Returns NULL if the object cannot be found
object *multi_get_network_object( ushort net_signature )
{
object *objp;
if ( net_signature == 0 )
return NULL;
if(GET_FIRST(&obj_used_list) == NULL)
return NULL;
for ( objp = GET_FIRST(&obj_used_list); objp != END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) )
if ( objp->net_signature == net_signature )
break;
// if not found on used list, check create list
if ( objp == END_OF_LIST(&obj_used_list) ) {
for ( objp = GET_FIRST(&obj_create_list); objp != END_OF_LIST(&obj_create_list); objp = GET_NEXT(objp) )
if ( objp->net_signature == net_signature )
break;
if ( objp == END_OF_LIST(&obj_create_list) )
objp = NULL;
}
return objp;
}
// -------------------------------------------------------------------------------------------------
// netmisc_calc_checksum() calculates the checksum of a block of memory.
//
//
ushort netmisc_calc_checksum( void * vptr, int len )
{
ubyte * ptr = (ubyte *)vptr;
unsigned int sum1,sum2;
sum1 = sum2 = 0;
while(len--) {
sum1 += *ptr++;
if (sum1 >= 255 ) sum1 -= 255;
sum2 += sum1;
}
sum2 %= 255;
return (unsigned short)((sum1<<8)+ sum2);
}
// -------------remainder of file is not used if NO_NETWORK is on
#ifndef NO_NETWORK
// -------------------------------------------------------------------------------------------------
// multi_random_death_word() will return a word from the below list at random.
//
// Note: Keep words grouped into sections of 10
#define NUM_DEATH_WORDS 40
char *multi_random_death_word()
{
int index;
index = rand() % NUM_DEATH_WORDS;
switch (index) {
case 0:
return XSTR("zapped",853);
case 1:
return XSTR("caulked",854);
case 2:
return XSTR("killed",855);
case 3:
return XSTR("waxed",856);
case 4:
return XSTR("popped",857);
case 5:
return XSTR("murdered",858);
case 6:
return XSTR("bludgeoned",859);
case 7:
return XSTR("destroyed",860);
case 8:
return XSTR("iced",861);
case 9:
return XSTR("obliterated",862);
case 10:
return XSTR("toasted",863);
case 11:
return XSTR("roasted",864);
case 12:
return XSTR("turned into anti-matter",865);
case 13:
return XSTR("killed like a pig",866);
case 14:
return XSTR("taught a lesson",867);
case 15:
return XSTR("slaughtered with impunity",868);
case 16:
return XSTR("spanked like a naughty boy",869);
case 17:
return XSTR("skunked",870);
case 18:
return XSTR("beat senseless",871);
case 19:
return XSTR("shot up",872);
case 20:
return XSTR("spaced",873);
case 21:
return XSTR("hosed",874);
case 22:
return XSTR("capped",875);
case 23:
return XSTR("beat down",876);
case 24:
return XSTR("hit wit da shizzo",877);
case 25:
return XSTR("sk00led",878);
case 26:
return XSTR("whooped up",879);
case 27:
return XSTR("brought to the all-you-can-take whoop ass buffet",880);
case 28:
return XSTR("served up a whoop ass sandwich...hold the mercy",881);
case 29:
return XSTR("gibbed by Kayser Sozay's rocket",882);
case 30:
return XSTR("shot down",883);
case 31:
return XSTR("given early retirement",884);
case 32:
return XSTR("instructed",885);
case 33:
return XSTR("eviscerated",886);
case 34:
return XSTR("pummelled",887);
case 35:
return XSTR("eradicated",888);
case 36:
return XSTR("cleansed",889);
case 37:
return XSTR("perforated",890);
case 38:
return XSTR("canned",891);
case 39:
return XSTR("decompressed",892);
}
return NOX("Error");
}
// -------------------------------------------------------------------------------------------------
// multi_random_chat_start() will return a word from the below list at random.
//
//
#define NUM_CHAT_START_WORDS 8
#define MAX_CHAT_PHRASE_LEN 25 // be careful not to exceed (or update if exceeded)
char *multi_random_chat_start()
{
int index;
index = rand() % NUM_CHAT_START_WORDS;
switch (index) {
case 0:
return XSTR("says",893);
case 1:
return XSTR("bleats",894);
case 2:
return XSTR("opines",895);
case 3:
return XSTR("postulates",896);
case 4:
return XSTR("declares",897);
case 5:
return XSTR("vomits out",898);
case 6:
return XSTR("whines",899);
case 7:
return XSTR("barks",900);
}
return NOX("Error");
}
// -------------------------------------------------------------------------------------------------
// multi_ship_class_lookup() will return the Ship_info[] index for the ship specified as a
// parameter.
//
//
int multi_ship_class_lookup(char* ship_name)
{
int i, player_ship_class;
// find the ship_info index for the ship_name
player_ship_class = -1;
for (i = 0; i < Num_ship_types; i++) {
if ( !stricmp(Ship_info[i].name, ship_name) ) {
player_ship_class = i;
break;
}
} // end for
if (i == Num_ship_types){
return -1;
}
return player_ship_class;
}
// -------------------------------------------------------------------------------------------------
// find_player() is called when a packet arrives, and we need to know which net player to update.
// The matching is done based on the address and port. Port checking is done in case multiple
// instances of FreeSpace are running on the same box.
//
//
int find_player( net_addr* addr )
{
int i;
for (i = 0; i < MAX_PLAYERS; i++ ) {
if ( !MULTI_CONNECTED(Net_players[i])){
continue;
}
if ( psnet_same( addr, &(Net_players[i].p_info.addr)) ){
return i;
}
}
return -1;
}
// so that we can lookup on the admin port transparently
int find_player_no_port(net_addr *addr)
{
int i;
int len;
for (i = 0; i < MAX_PLAYERS; i++ ) {
if ( !MULTI_CONNECTED(Net_players[i])){
continue;
}
if(addr->type == NET_IPX){
len = 6;
} else {
len = 4;
}
if ( memcmp(&addr->addr,&Net_players[i].p_info.addr.addr,len)== 0){
return i;
}
}
return -1;
}
int find_player_id(short player_id)
{
int i;
for (i = 0; i < MAX_PLAYERS; i++ ) {
if ( !MULTI_CONNECTED(Net_players[i])){
continue;
}
if(player_id == Net_players[i].player_id){
return i;
}
}
// couldn't find the player
return -1;
}
// note this is only valid to do on a server!
int find_player_socket(PSNET_SOCKET_RELIABLE sock)
{
int i;
for (i = 0; i < MAX_PLAYERS; i++ ) {
if ( !MULTI_CONNECTED(Net_players[i])){
continue;
}
if(sock == Net_players[i].reliable_socket){
return i;
}
}
// couldn't find the player
return -1;
}
// multi_find_player_by_object returns a player num (reference by Net_players[x]) when given a object *.
// used to find netplayers in game when only the object is known
int multi_find_player_by_object( object *objp )
{
int i, objnum;
objnum = OBJ_INDEX(objp);
for (i = 0; i < MAX_PLAYERS; i++ ) {
if ( !MULTI_CONNECTED(Net_players[i])){
continue;
}
if ( objnum == Net_players[i].player->objnum ){
return i;
}
}
// return -1 if the object is not found -- this is a bad situation, but we will handle it in higher
// level code
return -1;
}
// returns a player num based upon player object signature
int multi_find_player_by_signature( int signature )
{
int idx;
for(idx=0;idx<MAX_PLAYERS;idx++){
// compare against each player's object signature
if(MULTI_CONNECTED(Net_players[idx]) && (Objects[Net_players[idx].player->objnum].signature == signature)){
// found the player
return idx;
}
}
// didn't find the player
return -1;
}
// returns a player num based upon object net signature
int multi_find_player_by_net_signature(ushort net_signature)
{
int idx;
for(idx=0;idx<MAX_PLAYERS;idx++){
// compare against each player's object signature
if(MULTI_CONNECTED(Net_players[idx]) && (Objects[Net_players[idx].player->objnum].net_signature == net_signature)){
// found the player
return idx;
}
}
// didn't find the player
return -1;
}
int multi_find_player_by_ship_name(char *ship_name)
{
int idx;
// bogus
if(ship_name == NULL){
return -1;
}
for(idx=0; idx<MAX_PLAYERS; idx++){
if(MULTI_CONNECTED(Net_players[idx]) && !MULTI_OBSERVER(Net_players[idx]) && (Net_players[idx].player != NULL) && (Net_players[idx].player->objnum >= 0) && (Net_players[idx].player->objnum < MAX_OBJECTS) && (Objects[Net_players[idx].player->objnum].type == OBJ_SHIP) &&
(Objects[Net_players[idx].player->objnum].instance >= 0) && (Objects[Net_players[idx].player->objnum].instance < MAX_SHIPS) && !stricmp(ship_name, Ships[Objects[Net_players[idx].player->objnum].instance].ship_name) ){
return idx;
}
}
// didn't find the player
return -1;
}
int multi_get_player_ship(int np_index)
{
// bogus
if((np_index < 0) || (np_index >= MAX_PLAYERS)){
return -1;
}
// cool?
if(MULTI_CONNECTED(Net_players[np_index]) && !MULTI_OBSERVER(Net_players[np_index]) && !MULTI_STANDALONE(Net_players[np_index]) &&
(Net_players[np_index].player != NULL) && (Net_players[np_index].player->objnum >= 0) && (Net_players[np_index].player->objnum < MAX_OBJECTS) && (Objects[Net_players[np_index].player->objnum].type == OBJ_SHIP) &&
(Objects[Net_players[np_index].player->objnum].instance >= 0) && (Objects[Net_players[np_index].player->objnum].instance < MAX_SHIPS) ){
return Objects[Net_players[np_index].player->objnum].instance;
}
// nope
return -1;
}
// find_open_netplayer_slot() attempts to find a free slot in the Net_players structure for a new player.
// it returns -1 if there is no new slot, and the slot number if one is found
// NOTE : this attempts to preserve a player object as long as possible for him to come back to
int multi_find_open_netplayer_slot()
{
int i;
int found_first;
found_first = -1;
for (i = 0; i < MAX_PLAYERS; i++)
if ( !MULTI_CONNECTED(Net_players[i]) ){
if(found_first == -1) {
found_first = i;
break;
}
}
if(i == MAX_PLAYERS){
if(found_first == -1)
return -1;
else
return found_first;
}
return i;
}
// find_open_player_slot() attempts to find an open player array slot. The 0th element of the array
// should always be taken by the console player's pilot. All other slots are up for grab though.
int multi_find_open_player_slot()
{
int i;
for (i = 0; i < MAX_PLAYERS; i++)
if ( !(Players[i].flags & PLAYER_FLAGS_STRUCTURE_IN_USE) )
break;
if ( i == MAX_PLAYERS )
return -1;
return i;
}
// stuff_netplayer_info stuffs information into the given Net_player structure. It is called when
// a new person is entering the game. The state of the Net_player is set to it's basic starting
// state
void stuff_netplayer_info( net_player *nplayer, net_addr *addr, int ship_class, player *pplayer )
{
nplayer->p_info.addr = *addr;
nplayer->flags |= NETINFO_FLAG_CONNECTED;
nplayer->state = NETPLAYER_STATE_JOINING;
nplayer->p_info.ship_class = ship_class;
nplayer->player = pplayer;
nplayer->p_info.options.obj_update_level = OBJ_UPDATE_HIGH;
// if setting up my net flags, then set the flag to say I can do networking.
if ( nplayer == Net_player ){
nplayer->flags |= NETINFO_FLAG_DO_NETWORKING;
}
}
// multi_assign_player_ship takes a Net_player index and an object * and assigned that player to
// that object
void multi_assign_player_ship( int net_player, object *objp,int ship_class )
{
ship *shipp;
int idx;
Assert ( MULTI_CONNECTED(Net_players[net_player]) );
shipp = &Ships[objp->instance];
Net_players[net_player].player->objnum = OBJ_INDEX(objp);
Net_players[net_player].p_info.ship_class = ship_class;
// check to see if we are assigning my player -- if so, then set Player_ship and Player_ai
if ( Net_player == &Net_players[net_player] ) {
Player_obj = objp;
Player_ship = shipp;
Player_ai = &Ai_info[Player_ship->ai_index];
}
// find the parse object for this ship. Also, set the wingman status stuff so wingman status gauge
// works properly.
Net_players[net_player].p_info.p_objp = mission_parse_get_arrival_ship( shipp->ship_name );
Assert( Net_players[net_player].p_info.p_objp != NULL ); // get allender -- ship should be on list
Net_players[net_player].p_info.p_objp->ship_class = ship_class; // be sure this gets set so respawns work
// game server and this client need to initialize this information so object updating
// works properly.
if ( MULTIPLAYER_MASTER || (Net_player == &Net_players[net_player]) ) {
Net_players[net_player].s_info.eye_pos = objp->pos;
Net_players[net_player].s_info.eye_orient = objp->orient;
}
// zero update info
for(idx=0; idx<MAX_PLAYERS; idx++){
shipp->np_updates[idx].orient_chksum = 0;
shipp->np_updates[idx].pos_chksum = 0;
shipp->np_updates[idx].seq = 0;
shipp->np_updates[idx].status_update_stamp = -1;
shipp->np_updates[idx].subsys_update_stamp = -1;
shipp->np_updates[idx].update_stamp = -1;
}
}
// -------------------------------------------------------------------------------------------------
// create_player() is called when a net player needs to be instantiated. The ship that is created
// depends on the parameter ship_class. Note that if ship_class is invalid, the ship default_player_ship
// is used. Returns 1 on success, 0 otherwise
int multi_create_player( int net_player_num, player *pl, char* name, net_addr* addr, int ship_class, short id)
{
int player_ship_class = ship_class;
int i,current_player_count;
Assert ( net_player_num < MAX_PLAYERS ); // probably shoudln't be able to even get into this routine if no room
// blast _any_ old data
memset(&Net_players[net_player_num],0,sizeof(net_player));
// get the current # of players
current_player_count = multi_num_players();
// DOH!!! The lack of this caused many bugs.
Net_players[net_player_num].flags = (NETINFO_FLAG_DO_NETWORKING);
if ( ship_class == -1 ) {
nprintf(("Network","Network ==> ship class is -1, creating a default ship for multiplayer\n"));
// find the ship that matches the string stored in default_player_ship
for (i = 0; i < Num_ship_types; i++) {
if ( !stricmp(Ship_info[i].name, default_player_ship) ) {
player_ship_class = i;
break;
}
}
if (i == Num_ship_types)
Assert(0);
}
if ( player_ship_class >= Num_ship_types ) {
player_ship_class = multi_ship_class_lookup(default_player_ship);
nprintf(("Network","Network ==> Ship class was %d Creating a default ship for multiplayer\n", player_ship_class));
}
// blast the old player data
memset(pl,0,sizeof(player));
// set up the net_player structure
stuff_netplayer_info( &Net_players[net_player_num], addr, player_ship_class, pl );
Net_players[net_player_num].s_info.num_last_buttons = 0;
// Net_players[net_player_num].respawn_count = 0;
Net_players[net_player_num].last_heard_time = timer_get_fixed_seconds();
Net_players[net_player_num].reliable_socket = INVALID_SOCKET;
Net_players[net_player_num].s_info.kick_timestamp = -1;
Net_players[net_player_num].s_info.voice_token_timestamp = -1;
Net_players[net_player_num].s_info.tracker_security_last = -1;
Net_players[net_player_num].s_info.target_objnum = -1;
Net_players[net_player_num].s_info.accum_buttons = 0;
// zero out this players ping times data
multi_ping_reset(&Net_players[net_player_num].s_info.ping);
// zero out his object update and control info sequencing data
Net_players[net_player_num].client_cinfo_seq = 0;
Net_players[net_player_num].client_server_seq = 0;
// timestamp his last_full_update_time
Net_players[net_player_num].s_info.last_full_update_time = timestamp(0);
// nil his file xfer handle
Net_players[net_player_num].s_info.xfer_handle = -1;
// nil his data rate timestamp stuff
Net_players[net_player_num].s_info.rate_stamp = -1;
Net_players[net_player_num].s_info.rate_bytes = 0;
// nil packet buffer stuff
Net_players[net_player_num].s_info.unreliable_buffer_size = 0;
Net_players[net_player_num].s_info.reliable_buffer_size = 0;
// various ack handles
strcpy(pl->callsign, name);
pilot_set_short_callsign(pl, SHORT_CALLSIGN_PIXEL_W); // calculate the short callsign
pl->flags |= PLAYER_FLAGS_STRUCTURE_IN_USE;
pl->objnum = -1;
#ifndef NO_STANDALONE
// if we're the standalone server and this is the first guy to join, mark him as the host
// and give him all host priveleges
if((Game_mode & GM_STANDALONE_SERVER) && (current_player_count == 0)){
Net_players[net_player_num].flags |= NETINFO_FLAG_GAME_HOST;
}
#endif
Net_players[net_player_num].player_id = id;
Net_player->sv_bytes_sent = 0;
Net_player->sv_last_pl = -1;
Net_player->cl_bytes_recvd = 0;
Net_player->cl_last_pl = -1;
// add to the escort list
if(MULTI_IN_MISSION){
hud_escort_add_player(id);
}
return 1;
}
// next function makes a player object an ai object (also decrementing the num_players in the
// netgame). It appropiately sets the object flags and other interesting AI information which
// ought to get set in order to make this new ai object behave correctly.
void multi_make_player_ai( object *pobj )
{
Assert ( pobj != NULL );
if ( pobj->type != OBJ_SHIP )
return;
pobj->flags &= ~(OF_PLAYER_SHIP);
obj_set_flags( pobj, pobj->flags | OF_COULD_BE_PLAYER );
// target_objnum must be -1 or else new AI ship will fire on whatever this player
// had targeted.
set_target_objnum( &(Ai_info[Ships[pobj->instance].ai_index]), -1 );
}
// delete_player takes an index into the Net_players array to delete. Deletion of a player might happen
// because of the player leaving the game on his own, or no net activity from the player after X seconds
void delete_player(int player_num,int kicked_reason)
{
char notify_string[256] = "";
int idx;
if(!MULTI_CONNECTED(Net_players[player_num])){
return;
}
// NETLOG
ml_printf(NOX("Deleting player %s"), Net_players[player_num].player->callsign);
psnet_rel_close_socket( &(Net_players[player_num].reliable_socket) ); // close out the reliable socket
// if this guy was ingame joining, the remove my netgame flag so others may join
if ( Net_players[player_num].flags & NETINFO_FLAG_INGAME_JOIN ) {
Netgame.flags &= ~NG_FLAG_INGAME_JOINING;
Netgame.flags &= ~NG_FLAG_INGAME_JOINING_CRITICAL;
}
Net_players[player_num].flags &= ~NETINFO_FLAG_CONNECTED; // person not connected anymore
Net_players[player_num].player->flags &= ~(PLAYER_FLAGS_STRUCTURE_IN_USE); // free up his player structure
Net_players[player_num].s_info.reliable_connect_time = -1;
// add to the escort list
hud_escort_remove_player(Net_players[player_num].player_id);
// is this guy the server
if(Net_players[player_num].flags & NETINFO_FLAG_AM_MASTER){
// if the server leaves in the debriefing state, we should still wait until the player selects accept before we quit
if ((gameseq_get_state() != GS_STATE_DEBRIEF) && (gameseq_get_state() != GS_STATE_MULTI_DOGFIGHT_DEBRIEF)){
multi_quit_game(PROMPT_NONE, MULTI_END_NOTIFY_SERVER_LEFT);
}
}
// if he was just the host
else if(Net_players[player_num].flags & NETINFO_FLAG_GAME_HOST){
Net_players[player_num].flags &= ~(NETINFO_FLAG_GAME_HOST);
// am I the server
if((Net_player != NULL) && (Net_player->flags & NETINFO_FLAG_AM_MASTER)){
#ifndef NO_STANDALONE
// are we a standalone server and in a mission?
if((Game_mode & GM_STANDALONE_SERVER) && MULTI_IN_MISSION){
// choose a new host
int found_new_host = 0;
for(idx=0; idx<MAX_PLAYERS; idx++){
if(MULTI_CONNECTED(Net_players[idx]) && (Net_player != &Net_players[idx])){
// make this guy the host
Net_players[idx].flags |= NETINFO_FLAG_GAME_HOST;
// send a packet
send_host_captain_change_packet(Net_players[idx].player_id, 0);
found_new_host = 1;
break;
}
}
// end the game
if(!found_new_host){
multi_quit_game(PROMPT_NONE, MULTI_END_NOTIFY_NONE, MULTI_END_ERROR_HOST_LEFT);
}
} else
#endif // #ifndef NO_STANDALONE
{
multi_quit_game(PROMPT_NONE, MULTI_END_NOTIFY_NONE, MULTI_END_ERROR_HOST_LEFT);
}
}
}
// if we're the server of the game, notify everyone else that this guy has left
// if he's marked as being kicked, then other players know about it already, so don't send again
if(Net_player->flags & NETINFO_FLAG_AM_MASTER){
if(Net_players[player_num].flags & NETINFO_FLAG_KICKED){
char str[512];
memset(str, 0, 512);
multi_kick_get_text(&Net_players[player_num], Net_players[player_num].s_info.kick_reason, str);
multi_display_chat_msg(str, player_num, 0);
} else {
send_leave_game_packet(Net_players[player_num].player_id, kicked_reason);
}
}
// if this guy is an observer, we have to make sure we delete his observer object (only if we're the server however)
if( (Net_player->flags & NETINFO_FLAG_AM_MASTER) && (Net_players[player_num].flags & NETINFO_FLAG_OBSERVER) ) {
if ( Net_players[player_num].player->objnum != -1 ){
obj_delete(Net_players[player_num].player->objnum); // maybe change this to set flag instead
}
} else {
// otherwise mark it so that he can return to it later if possible
if ( (Net_players[player_num].player->objnum >= 0) && (Net_players[player_num].player->objnum < MAX_OBJECTS) && (Objects[Net_players[player_num].player->objnum].type == OBJ_SHIP) && (Objects[Net_players[player_num].player->objnum].instance >= 0) && (Objects[Net_players[player_num].player->objnum].instance < MAX_SHIPS)) {
multi_make_player_ai( &Objects[Net_players[player_num].player->objnum] );
} else {
multi_respawn_player_leave(&Net_players[player_num]);
}
}
// if we're in the team select, and we're the host, we have to make sure all team select data is correctly updated
// MWA 7/28/98. Don't do this for a standalone server. Since he doesn't go through the team selection
// screens, his data structures are not 100% accurate. Doing so on a standalone resulted in the wrong
// ships getting marked as COULD_BE_PLAYER. On the standalone, these flags will get properly set
// in the multi_make_player_ai code above.
if( (Netgame.game_state == NETGAME_STATE_BRIEFING) && !(Game_mode & GM_STANDALONE_SERVER) ) {
multi_ts_handle_player_drop();
}
if (gameseq_get_state() == GS_STATE_DEBRIEF){
debrief_handle_player_drop();
}
// handle any specific dropping conditions
if(Net_player->flags & NETINFO_FLAG_AM_MASTER){
multi_team_handle_drop();
}
multi_data_handle_drop(player_num);
// tell the pinfo popup that a player has left
multi_pinfo_notify_drop(&Net_players[player_num]);
// tell the datarate stuff that the player has dropped
multi_rate_reset(player_num);
// display a message that this guy has left
if(Net_players[player_num].player->callsign){
sprintf(notify_string,XSTR("<%s has left>",901),Net_players[player_num].player->callsign);
multi_display_chat_msg(notify_string,0,0);
}
#ifndef NO_STANDALONE
// standalone gui type stuff
if (Game_mode & GM_STANDALONE_SERVER) {
std_remove_player(&Net_players[player_num]);
std_connect_set_connect_count();
}
#endif
// blast this memory clean
memset(&Net_players[player_num], 0, sizeof(net_player));
Net_players[player_num].reliable_socket = INVALID_SOCKET;
extern int Multi_client_update_times[MAX_PLAYERS];
Multi_client_update_times[player_num] = -1;
}
#define INACTIVE_LIMIT_NORMAL (15 * F1_0)
#define INACTIVE_LIMIT_WAIT (20 * F1_0)
// -------------------------------------------------------------------------------------------------
// multi_cull_zombies() will check if there has been any net players or observers that have been inactive for
// INACTIVE_LIMIT milliseconds since last check. If so, they are taken out of the net game.
//
//
void multi_cull_zombies()
{
#if 0
fix current_time;
int inactive_limit;
int i;
if(gameseq_get_state() == GS_STATE_MULTI_WAIT)
inactive_limit = INACTIVE_LIMIT_WAIT;
else
inactive_limit = INACTIVE_LIMIT_NORMAL;
current_time = timer_get_fixed_seconds();
for (i = 0; i < MAX_PLAYERS; i++) {
if ( !MULTI_CONNECTED(&Net_players[i])){
continue;
}
// server will(should) cull out players based on their sockets dying.
if ( Net_players[i].flags & NETINFO_FLAG_MASTER ){
continue;
}
if ( (current_time - Net_players[i].last_heard_time) > inactive_limit) {
HUD_printf(XSTR("Dumping %s after prolonged inactivity",902),Net_players[i].player->callsign);
nprintf(("Network", "Assuming %s is a zombie, removing from game\n", Net_players[i].player->callsign));
multi_kick_player(i,0);
}
}
#endif
}
// -------------------------------------------------------------------------------------------------
// fill_net_addr() calculates the checksum of a block of memory.
//
//
void fill_net_addr(net_addr* addr, ubyte* address, ubyte* net_id, ushort port)
{
Assert(addr != NULL);
Assert(address != NULL);
Assert(net_id != NULL);
addr->type = Multi_options_g.protocol;
memset( addr->addr, 0x00, 6);
memcpy( addr->addr, address, ADDRESS_LENGTH);
memcpy( addr->net_id, net_id, 4);
addr->port = port;
}
// -------------------------------------------------------------------------------------------------
// get_text_address()
//
//
char* get_text_address( char * text, ubyte * address )
{
in_addr temp_addr;
switch ( Multi_options_g.protocol ) {
case NET_IPX:
strcpy( text, XSTR("[ipx address here]",903) ); // TODO: find equiv to inet_ntoa() for IPX
sprintf(text, "%x %x %x %x %x %x", address[0],
address[1],
address[2],
address[3],
address[4],
address[5]);
break;
case NET_TCP:
memcpy(&temp_addr.s_addr, address, 4);
strcpy( text, inet_ntoa(temp_addr) );
break;
default:
Assert(0);
break;
} // end switch
return text;
}
// non-16byte version of matrix packing
// return size of packed matrix
void multi_pack_orient_matrix(ubyte *data,matrix *m)
{
data[16]=0;
if(m->vec.rvec.xyz.z < 0) data[16] |= (1<<0); // X
if(m->vec.uvec.xyz.z < 0) data[16] |= (1<<1); // Y
if(m->vec.fvec.xyz.z < 0) data[16] |= (1<<2); // V
if(m->vec.fvec.xyz.x < 0) data[16] |= (1<<3); // Z
if(m->vec.fvec.xyz.y < 0) data[16] |= (1<<4); // W
memcpy(&data[0],&m->vec.rvec.xyz.x,4); // a
memcpy(&data[4],&m->vec.rvec.xyz.y,4); // b
memcpy(&data[8],&m->vec.uvec.xyz.x,4); // c
memcpy(&data[12],&m->vec.uvec.xyz.y,4); // d
}
// return bytes processed
// non-16 byte version of unpack matrix code
void multi_unpack_orient_matrix(ubyte *data,matrix *m)
{
memcpy(&m->vec.rvec.xyz.x, &data[0], 4);
memcpy(&m->vec.rvec.xyz.y, &data[4], 4);
memcpy(&m->vec.uvec.xyz.x, &data[8], 4);
memcpy(&m->vec.uvec.xyz.y, &data[12],4);
m->vec.rvec.xyz.z = fl_sqrt(fl_abs(1 - (m->vec.rvec.xyz.x * m->vec.rvec.xyz.x) - (m->vec.rvec.xyz.y * m->vec.rvec.xyz.y))); // X
m->vec.uvec.xyz.z = fl_sqrt(fl_abs(1 - (m->vec.uvec.xyz.x * m->vec.uvec.xyz.x) - (m->vec.uvec.xyz.y * m->vec.uvec.xyz.y))); // Y
m->vec.fvec.xyz.z = fl_sqrt(fl_abs(1 - (m->vec.rvec.xyz.z * m->vec.rvec.xyz.z) - (m->vec.uvec.xyz.z * m->vec.uvec.xyz.z))); // V
m->vec.fvec.xyz.x = fl_sqrt(fl_abs(1 - (m->vec.rvec.xyz.x * m->vec.rvec.xyz.x) - (m->vec.uvec.xyz.x * m->vec.uvec.xyz.x))); // Z
m->vec.fvec.xyz.y = fl_sqrt(fl_abs(1 - (m->vec.rvec.xyz.y * m->vec.rvec.xyz.y) - (m->vec.uvec.xyz.y * m->vec.uvec.xyz.y))); // W
m->vec.rvec.xyz.z *= (data[16] & (1<<0)) ? -1.0f : 1.0f;
m->vec.uvec.xyz.z *= (data[16] & (1<<1)) ? -1.0f : 1.0f;
m->vec.fvec.xyz.z *= (data[16] & (1<<2)) ? -1.0f : 1.0f;
m->vec.fvec.xyz.x *= (data[16] & (1<<3)) ? -1.0f : 1.0f;
m->vec.fvec.xyz.y *= (data[16] & (1<<4)) ? -1.0f : 1.0f;
}
void multi_do_client_warp(float flFrametime)
{
ship_obj *moveup;
moveup = GET_FIRST(&Ship_obj_list);
while(moveup!=END_OF_LIST(&Ship_obj_list)){
// do all _necessary_ ship warp in (arrival) processing
if ( Ships[Objects[moveup->objnum].instance].flags & SF_ARRIVING )
shipfx_warpin_frame( &Objects[moveup->objnum], flFrametime );
moveup = GET_NEXT(moveup);
}
}
// ------------------------------------------------------------------------------------
// ship status change stuff
int lookup_ship_status(net_player *p,int unique_id,int remove)
{
int idx;
for(idx=0;idx<p->s_info.num_last_buttons;idx++){
if(p->s_info.last_buttons_id[idx] == unique_id){
if(remove){
remove_ship_status_item(p,idx);
p->s_info.num_last_buttons--;
}
return 1;
}
}
return 0;
}
void remove_ship_status_item(net_player *p,int id)
{
int idx;
for(idx=id;idx<BUTTON_INFO_SAVE_COUNT-1;idx++){
p->s_info.last_buttons[idx] = p->s_info.last_buttons[idx+1];
p->s_info.last_buttons_id[idx] = p->s_info.last_buttons_id[idx+1];
p->s_info.last_buttons_time[idx] = p->s_info.last_buttons_time[idx+1];
}
}
//
void add_net_button_info(net_player *p,button_info *bi,int unique_id)
{
int lookup,idx;
fix earliest;
// if the list is full, put it in the oldest slot since it's probably a lost packet anyway
if(p->s_info.num_last_buttons < BUTTON_INFO_SAVE_COUNT-1){
p->s_info.last_buttons[p->s_info.num_last_buttons] = *bi;
p->s_info.last_buttons_id[p->s_info.num_last_buttons] = unique_id;
p->s_info.last_buttons_time[p->s_info.num_last_buttons] = timer_get_fixed_seconds();
p->s_info.num_last_buttons++;
} else {
earliest = 0;
lookup = -1;
for(idx=0;idx<BUTTON_INFO_SAVE_COUNT;idx++){
if((p->s_info.last_buttons_time[idx] < earliest) || (earliest == 0)){
earliest = p->s_info.last_buttons_time[idx];
lookup = idx;
}
}
if(lookup != -1){
p->s_info.last_buttons[lookup] = *bi;
p->s_info.last_buttons_id[lookup] = unique_id;
p->s_info.last_buttons_time[lookup] = timer_get_fixed_seconds();
}
}
}
extern int button_function_critical(int n,net_player *p = NULL);
void multi_apply_ship_status(net_player *p,button_info *bi,int locally)
{
int i, j;
Multi_button_info_ok=1;
for ( i = 0; i < NUM_BUTTON_FIELDS; i++ ) {
if ( bi->status[i] == 0 )
continue;
// at least one bit is set in the status integer
for ( j = 0; j < 32; j++ ) {
// check if the bit is set. If button_function returns 1 (implying the action was taken), then unset the bit
if ( bi->status[i] & (1<<j) ) {
if(locally){
if(button_function_critical(32*i + j,NULL)) // will apply to this console
bi->status[i] &= ~(1<<j);
} else {
if(button_function_critical(32*i + j,p)) // will only apply to a net-player
bi->status[i] &= ~(1<<j);
}
}
}
}
Multi_button_info_ok=0;
}
// send 10x a second MAX
#define MULTI_SHIP_STATUS_TIME 350
int Multi_ship_status_stamp = -1;
button_info Multi_ship_status_bi;
void multi_maybe_send_ship_status()
{
int idx;
button_info *bi = &Player->bi;
// strip out noncritical button presses
button_strip_noncritical_keys(bi);
// xor all fields into the accum button info
for(idx=0; idx<NUM_BUTTON_FIELDS; idx++){
Multi_ship_status_bi.status[idx] |= bi->status[idx];
}
// check timestamp
if((Multi_ship_status_stamp < 0) || timestamp_elapsed_safe(Multi_ship_status_stamp, MULTI_SHIP_STATUS_TIME*2)){
int should_send = 0;
for(idx=0; idx<NUM_BUTTON_FIELDS; idx++){
// we have at least something to send
if(Multi_ship_status_bi.status[idx] != 0){
should_send = 1;
}
}
// do we have something to send
if(should_send){
// add_net_button_info(Net_player, &Multi_ship_status_bi, Multi_button_info_id);
send_ship_status_packet(Net_player, &Multi_ship_status_bi, Multi_button_info_id++);
}
// zero it out
memset(&Multi_ship_status_bi, 0, sizeof(button_info));
// reset timestamp
Multi_ship_status_stamp = timestamp(MULTI_SHIP_STATUS_TIME);
}
}
void multi_subsys_update_all()
{
/*
int idx;
Assert(Net_player->flags & NETINFO_FLAG_AM_MASTER);
for(idx=0;idx<MAX_PLAYERS;idx++){
if((Net_players[idx].flags & NETINFO_FLAG_CONNECTED) && !psnet_same(&My_addr,&Net_players[idx].addr) && !(Net_players[idx].flags & NETINFO_FLAG_OBSERVER))
send_subsys_update_packet(&Net_players[idx]);
}
*/
}
int multi_find_player_by_callsign(char *callsign)
{
int idx;
for(idx=0;idx<MAX_PLAYERS;idx++){
if(MULTI_CONNECTED(Net_players[idx]) && (strcmp(callsign,Net_players[idx].player->callsign)==0)){
return idx;
}
}
return -1;
}
// if Game_current_mission_filename is a builtin multiplayer mission
int multi_is_builtin_mission()
{
// int idx;
char name[512];
// get the full filename
memset(name,0,512);
strcpy(name,Game_current_mission_filename);
cf_add_ext(name, FS_MISSION_FILE_EXT);
// if this mission is builtin
if(game_find_builtin_mission(name) != NULL){
return 1;
}
// not builtin
return 0;
}
// verify that the player has a valid mission file and do 1 of 3 things
void server_verify_filesig(short player_id, ushort sum_sig, int length_sig)
{
#if defined(MULTIPLAYER_BETA_BUILD) || defined(FS2_DEMO)
net_player *pl;
int player;
player = find_player_id(player_id);
Assert(player >= 0);
if(player < 0){
return;
}
pl = &Net_players[player];
// all missions should be builtin, so if we don't have a match, kick the player
if((sum_sig != Multi_current_file_checksum) || (length_sig != Multi_current_file_length)){
multi_kick_player(player, 0, KICK_REASON_CANT_XFER);
} else {
pl->flags |= NETINFO_FLAG_MISSION_OK;
}
#else
net_player *pl;
int player;
int ok;
int is_builtin;
player = find_player_id(player_id);
Assert(player >= 0);
if(player < 0){
return;
}
pl = &Net_players[player];
// if the current mission is a builtin mission, check stuff out
is_builtin = multi_is_builtin_mission();
if(is_builtin){
// if the player doesn't have it, kick him
if((sum_sig == 0xffff) && (length_sig == -1)){
multi_kick_player(player, 0, KICK_REASON_CANT_XFER);
} else {
pl->flags |= NETINFO_FLAG_MISSION_OK;
}
// done
return;
}
if( (length_sig != Multi_current_file_length) || (sum_sig != Multi_current_file_checksum)){
ok = 0;
} else {
ok = 1;
}
// in an ingame join situation
if(pl->flags & NETINFO_FLAG_INGAME_JOIN){
if(!ok){
// if the netgame settings allow in-mission file xfers
if(Netgame.options.flags & MSO_FLAG_INGAME_XFER){
pl->s_info.ingame_join_flags |= INGAME_JOIN_FLAG_FILE_XFER;
pl->s_info.xfer_handle = multi_xfer_send_file(pl->reliable_socket, Netgame.mission_name, CF_TYPE_MISSIONS);
}
// otherwise send him a nak and tell him to get away
else {
send_ingame_nak(ACK_FILE_ACCEPTED,pl);
}
} else {
pl->flags |= NETINFO_FLAG_MISSION_OK;
}
}
// in a normal join situation
else {
// if the file does not check out, send it to him
if(!ok){
pl->s_info.xfer_handle = multi_xfer_send_file(pl->reliable_socket, Netgame.mission_name, CF_TYPE_MISSIONS);
}
// otherwise mark him as having a valid mission
else {
pl->flags |= NETINFO_FLAG_MISSION_OK;
}
}
#endif
}
// check to see if every client has NETINFO_FLAG_MISSION_OK
int server_all_filesigs_ok()
{
int idx;
int ok = 1;
for(idx=0;idx<MAX_PLAYERS;idx++){
if(MULTI_CONNECTED(Net_players[idx]) && !(Net_players[idx].flags & NETINFO_FLAG_MISSION_OK)){
ok = 0;
break;
}
}
return ok;
}
void multi_untag_player_ships()
{
ship_obj *moveup;
moveup = GET_FIRST(&Ship_obj_list);
while(moveup != END_OF_LIST(&Ship_obj_list)){
if(Objects[moveup->objnum].flags & OF_PLAYER_SHIP){
Objects[moveup->objnum].flags &= ~(OF_PLAYER_SHIP);
obj_set_flags( &Objects[moveup->objnum], Objects[moveup->objnum].flags | OF_COULD_BE_PLAYER );
}
moveup = GET_NEXT(moveup);
}
}
// broadcast alltime stats to everyone in the game
void multi_broadcast_stats(int stats_code)
{
int idx;
// broadcast everyone's stats to everyone else
for(idx=0;idx<MAX_PLAYERS;idx++){
if(MULTI_CONNECTED(Net_players[idx]) && !MULTI_PERM_OBSERVER(Net_players[idx]) && !MULTI_STANDALONE(Net_players[idx])){
send_player_stats_block_packet(&Net_players[idx], stats_code);
}
}
}
// check to see if all players other than the local player are in a given NETPLAYER_ state
// this is _EXTREMELY_ useful when doing network sequencing with the reliable sockets
int multi_netplayer_state_check(int state,int ignore_standalone)
{
int idx;
for(idx=0;idx<MAX_PLAYERS;idx++){
if(MULTI_CONNECTED(Net_players[idx]) && (Net_player->player_id != Net_players[idx].player_id)){
if(ignore_standalone && ((Net_players[idx].flags & NETINFO_FLAG_AM_MASTER) && !(Net_players[idx].flags & NETINFO_FLAG_GAME_HOST)) ){
continue;
}
if(Net_players[idx].state != state){
return 0;
}
}
}
return 1;
}
int multi_netplayer_state_check2(int state, int state2, int ignore_standalone)
{
int idx;
for(idx=0;idx<MAX_PLAYERS;idx++){
if(MULTI_CONNECTED(Net_players[idx]) && (Net_player->player_id != Net_players[idx].player_id)){
if(ignore_standalone && ((Net_players[idx].flags & NETINFO_FLAG_AM_MASTER) && !(Net_players[idx].flags & NETINFO_FLAG_GAME_HOST)) ){
continue;
}
if((Net_players[idx].state != state) && (Net_players[idx].state != state2)){
return 0;
}
}
}
return 1;
}
int multi_netplayer_state_check3(int state, int state2, int state3, int ignore_standalone)
{
int idx;
for(idx=0;idx<MAX_PLAYERS;idx++){
if(MULTI_CONNECTED(Net_players[idx]) && (Net_player->player_id != Net_players[idx].player_id)){
if(ignore_standalone && ((Net_players[idx].flags & NETINFO_FLAG_AM_MASTER) && !(Net_players[idx].flags & NETINFO_FLAG_GAME_HOST)) ){
continue;
}
if((Net_players[idx].state != state) && (Net_players[idx].state != state2) && (Net_players[idx].state != state3)){
return 0;
}
}
}
return 1;
}
// check to see if all players other than the local player are in a given NETPLAYER_ state
// this is _EXTREMELY_ useful when doing network sequencing with the reliable sockets
int multi_netplayer_flag_check(int flags,int ignore_standalone)
{
int idx;
for(idx=0;idx<MAX_PLAYERS;idx++){
if(MULTI_CONNECTED(Net_players[idx]) && (Net_player->player_id != Net_players[idx].player_id)){
if(ignore_standalone && ((Net_players[idx].flags & NETINFO_FLAG_AM_MASTER) && !(Net_players[idx].flags & NETINFO_FLAG_GAME_HOST)) ){
continue;
}
if(!(Net_players[idx].flags & flags)){
return 0;
}
}
}
return 1;
}
// function which gets called from psnet_* code to evaluate an error received on a reliable
// socket. In general, we only want to do drastic measures if the error indicates that the client
// is no longer there.
void multi_eval_socket_error(PSNET_SOCKET sock, int error)
{
if ( error == WSAENOTSOCK ){
nprintf(("Network","Socket connection terminated and/or nonexistent, bailing..\n"));
// mwa -- don't go back to main menu. You don't want host to do this. Maybe we can ignore it
// because of a leaving player.
return;
//gameseq_post_event(GS_EVENT_MAIN_MENU);
// Int3(); // get allender -- something happened to socket connection!!!
}
if ( (error != WSAECONNRESET) && (error != WSAECONNABORTED) && (error != WSAESHUTDOWN) ) {
nprintf(("Network", "Error %d received on reliable socket -- ignoring\n", error));
return;
}
if(error == WSAESHUTDOWN){
nprintf(("Network","Received WSAESHUTDOWN on client socket. Cool.\n"));
}
// mwa -- always return for now because debugging with the stuff below is a real pain.
// in essence, you can't do it!
//return;
if( Net_player->flags & NETINFO_FLAG_AM_MASTER ) {
int idx;
nprintf(("Network", "pitching player because drop on reliable socket\n"));
// find the netplayer whose socket we have an error on. Dump the player when we find him.
// NOTE : make sure not to ban him
for(idx=0;idx<MAX_PLAYERS;idx++){
if(Net_players[idx].reliable_socket == sock){
delete_player(idx);
return;
}
}
} else {
nprintf(("Network", "Communications to server lost -- quitting game\n"));
multi_quit_game(PROMPT_NONE, MULTI_END_NOTIFY_NONE, MULTI_END_ERROR_CONTACT_LOST);
}
}
// send a repair info packet with code == code to a player if his object is the one being acted upon
// dest_objp is the player object (or possible player object). source_objp is the object pointer
// of the repair ship that is the source of the action. code means what is happening -- queueing up
// for repair, getting repaired, aborted, complete, etc.
void multi_maybe_send_repair_info(object *dest_objp, object *source_objp, int code )
{
// only send information on player objects
if ( !MULTIPLAYER_MASTER )
return;
Assert( dest_objp->type == OBJ_SHIP );
Assert( dest_objp != source_objp );
send_repair_info_packet( dest_objp, source_objp, code );
}
int multi_is_valid_unknown_packet(ubyte type){
return (type == GAME_QUERY) || (type == JOIN) || (type == PING) || (type == PONG) || (type == GAME_INFO)
|| (type == ACCEPT) || (type == GAME_ACTIVE) || (type == INGAME_NAK) || (type == DENY)
|| (type == UPDATE_DESCRIPT) || (type == ACCEPT_PLAYER_DATA) ? 1 : 0;
}
void multi_create_standalone_object()
{
// now create a dummy ship for the standalone
matrix m = IDENTITY_MATRIX;
vector v;
int objnum, pobj_num;
vm_vec_zero(&v);
objnum = observer_create(&m,&v);
Player_obj = &Objects[objnum];
obj_set_flags(Player_obj, Player_obj->flags & (~OF_COLLIDES) );
//obj_set_flags(Player_obj, Player_obj->flags | OF_SHOULD_BE_DEAD);
obj_set_flags(Player_obj, Player_obj->flags & (~OF_PLAYER_SHIP));
Net_player->player->objnum = objnum;
// create the default player ship object and use that as my default virtual "ship", and make it "invisible"
pobj_num = parse_create_object(&Player_start_pobject);
Assert(pobj_num != -1);
obj_set_flags(&Objects[pobj_num],OF_PLAYER_SHIP);
Objects[pobj_num].net_signature = STANDALONE_SHIP_SIG;
Player_ship = &Ships[Objects[pobj_num].instance];
// make ship hidden from sensors so that this observer cannot target it. Observers really have two ships
// one observer, and one "Player_ship". Observer needs to ignore the Player_ship.
Player_ship->flags |= SF_HIDDEN_FROM_SENSORS;
strcpy(Player_ship->ship_name, XSTR("Standalone Ship",904));
Player_ai = &Ai_info[Ships[Objects[pobj_num].instance].ai_index];
}
int multi_message_should_broadcast(int type)
{
return (type == MESSAGE_ARRIVE_ENEMY) || (type == MESSAGE_BETA_ARRIVED) ||
(type == MESSAGE_GAMMA_ARRIVED) || (type == MESSAGE_HELP) || (type == MESSAGE_REINFORCEMENTS) ? 1 : 0;
}
// active game list handling functions
active_game *multi_new_active_game( void )
{
active_game *new_game;
new_game = (active_game *)malloc(sizeof(active_game));
if ( new_game == NULL ) {
nprintf(("Network", "Cannot allocate space for new active game structure\n"));
return NULL;
}
if ( Active_game_head != NULL ) {
new_game->next = Active_game_head->next;
new_game->next->prev = new_game;
Active_game_head->next = new_game;
new_game->prev = Active_game_head;
} else {
Active_game_head = new_game;
Active_game_head->next = Active_game_head->prev = Active_game_head;
}
Active_game_count++;
// notify the join game screen of this new item
multi_join_notify_new_game();
return new_game;
}
active_game *multi_update_active_games(active_game *ag)
{
active_game *gp = NULL;
active_game *stop = NULL;
// see if we have a game from this address already -- if not, create one. In either case, get a pointer
// to an active_game structure
if ( Active_game_head != NULL ) { // no games on list at all
int on_list;
gp = Active_game_head;
stop = Active_game_head;
on_list = 0;
do {
if ( psnet_same(&gp->server_addr, &ag->server_addr) /*&& (gp->game.security == game->security)*/ ) {
on_list = 1;
break;
}
gp = gp->next;
} while (gp != stop);
// insert in the list
if (!on_list){
gp = multi_new_active_game();
// gp->ping_time = -1.0f;
// copy in the game information
memcpy(&gp->server_addr,&ag->server_addr,sizeof(net_addr));
strcpy(gp->name,ag->name);
strcpy(gp->mission_name,ag->mission_name);
strcpy(gp->title,ag->title);
gp->num_players = ag->num_players;
gp->flags = ag->flags;
// ping him
/*
gp->ping_start = timer_get_fixed_seconds();
gp->ping_end = -1;
send_ping(&gp->server_addr);
*/
multi_ping_reset(&gp->ping);
multi_ping_send(&gp->server_addr,&gp->ping);
}
// otherwise update the netgame info we have for this guy
else {
memset(gp->name,0,MAX_GAMENAME_LEN+1);
strcpy(gp->name,ag->name);
memset(gp->mission_name,0,NAME_LENGTH+1);
strcpy(gp->mission_name,ag->mission_name);
memset(gp->title,0,NAME_LENGTH+1);
strcpy(gp->title,ag->title);
gp->num_players = ag->num_players;
gp->flags = ag->flags;
}
} else {
gp = multi_new_active_game();
// gp->ping_time = -1.0f;
// copy in the game information
memcpy(&gp->server_addr,&ag->server_addr,sizeof(net_addr));
strcpy(gp->name,ag->name);
strcpy(gp->mission_name,ag->mission_name);
strcpy(gp->title,ag->title);
gp->num_players = ag->num_players;
gp->flags = ag->flags;
// ping him
// gp->ping_start = timer_get_fixed_seconds();
// gp->ping_end = -1;
// send_ping(&gp->server_addr);
multi_ping_reset(&gp->ping);
multi_ping_send(&gp->server_addr,&gp->ping);
}
// don't do anything if we don't have a game entry
if(gp == NULL){
return NULL;
}
// update the last time we heard from him
if((Multi_options_g.protocol == NET_TCP) && (Net_player->p_info.options.flags & MLO_FLAG_LOCAL_BROADCAST)){
gp->heard_from_timer = timestamp(MULTI_JOIN_SERVER_TIMEOUT_LOCAL);
} else {
gp->heard_from_timer = timestamp(MULTI_JOIN_SERVER_TIMEOUT);
}
return gp;
}
void multi_free_active_games()
{
active_game *moveup,*backup;
moveup = Active_game_head;
backup = NULL;
if(moveup != NULL){
do {
backup = moveup;
moveup = moveup->next;
free(backup);
backup = NULL;
} while(moveup != Active_game_head);
Active_game_head = NULL;
}
Active_game_count = 0;
}
server_item *multi_new_server_item( void )
{
server_item *new_game;
new_game = (server_item *)malloc(sizeof(server_item));
if ( new_game == NULL ) {
nprintf(("Network", "Cannot allocate space for new server_item structure\n"));
return NULL;
}
if ( Game_server_head != NULL ) {
new_game->next = Game_server_head->next;
new_game->next->prev = new_game;
Game_server_head->next = new_game;
new_game->prev = Game_server_head;
} else {
Game_server_head = new_game;
Game_server_head->next = Game_server_head->prev = Game_server_head;
}
return new_game;
}
void multi_free_server_list()
{
server_item *moveup,*backup;
moveup = Game_server_head;
backup = NULL;
if(moveup != NULL){
do {
backup = moveup;
moveup = moveup->next;
free(backup);
backup = NULL;
} while(moveup != Game_server_head);
Game_server_head = NULL;
}
}
int multi_num_players()
{
int idx,count;
// count the players who are actively connected
count = 0;
for(idx=0;idx<MAX_PLAYERS;idx++){
// count all connected players except the standalone server (if any)
if(MULTI_CONNECTED(Net_players[idx]) && !MULTI_STANDALONE(Net_players[idx]) && !MULTI_PERM_OBSERVER(Net_players[idx])){
count++;
}
}
return count;
}
int multi_num_observers()
{
int idx,count;
// count the players who are actively connected
count = 0;
for(idx=0;idx<MAX_PLAYERS;idx++){
// count all connected players except the standalone server (if any)
if(MULTI_CONNECTED(Net_players[idx]) && MULTI_PERM_OBSERVER(Net_players[idx])){
count++;
}
}
return count;
}
int multi_num_connections()
{
int idx,count;
// count the players who are actively connected
count = 0;
for(idx=0;idx<MAX_PLAYERS;idx++){
// count all connected players except the standalone server (if any)
if(MULTI_CONNECTED(Net_players[idx]) && !MULTI_STANDALONE(Net_players[idx])){
count++;
}
}
return count;
}
int multi_can_message(net_player *p)
{
int max_rank;
ship *sp;
// if the player is an observer of any kind, he cannot message
if(p->flags & NETINFO_FLAG_OBSERVER){
return 0;
}
switch(Netgame.options.squad_set){
// only those of the highest rank can message
case MSO_SQUAD_RANK:
max_rank = multi_get_highest_rank();
if(p->player->stats.rank < max_rank){
return 0;
}
break;
// only wing/team leaders can message
case MSO_SQUAD_LEADER:
// if the player has an invalid object #
if(p->player->objnum < 0){
return 0;
}
// check to see if he's a wingleader
sp = &Ships[Objects[p->player->objnum].instance];
if(stricmp(sp->ship_name,NOX("alpha 1")) && stricmp(sp->ship_name,NOX("beta 1")) && stricmp(sp->ship_name,NOX("gamma 1")) && stricmp(sp->ship_name,NOX("zeta 1")) ){
return 0;
}
break;
// anyone can end message
case MSO_SQUAD_ANY:
break;
// only the host can message
case MSO_SQUAD_HOST:
if(!(p->flags & NETINFO_FLAG_GAME_HOST)){
return 0;
}
break;
}
return 1;
}
int multi_can_end_mission(net_player *p)
{
int max_rank;
ship *sp;
// the host can _always_ unpause a game
if(p->flags & NETINFO_FLAG_GAME_HOST){
return 1;
}
switch(Netgame.options.endgame_set){
// only those of the highest rank can end the mission
case MSO_END_RANK:
max_rank = multi_get_highest_rank();
if(p->player->stats.rank < max_rank){
return 0;
}
break;
// only wing/team leaders can end the mission
case MSO_END_LEADER:
// if the player has an invalid object #
if(p->player->objnum < 0){
return 0;
}
// check to see if he's a wingleader
sp = &Ships[Objects[p->player->objnum].instance];
if(stricmp(sp->ship_name,NOX("alpha 1")) && stricmp(sp->ship_name,NOX("beta 1")) && stricmp(sp->ship_name,NOX("gamma 1")) && stricmp(sp->ship_name,NOX("zeta 1")) ){
return 0;
}
break;
// anyone can end the mission
case MSO_END_ANY:
break;
// only the host can end the mission
case MSO_END_HOST:
if(!(p->flags & NETINFO_FLAG_GAME_HOST)){
return 0;
}
break;
}
return 1;
}
int multi_eval_join_request(join_request *jr,net_addr *addr)
{
int team0_avail,team1_avail;
// if the server versions are incompatible
if(jr->version != MULTI_FS_SERVER_COMPATIBLE_VERSION){
return JOIN_DENY_JR_BAD_VERSION;
}
// check to make sure we are otherwise in a state to accept
if(Netgame.game_state != NETGAME_STATE_FORMING){
return JOIN_DENY_JR_STATE;
}
#ifndef NO_STANDALONE
// the standalone has some oddball situations which we must handle seperately
if(Game_mode & GM_STANDALONE_SERVER){
// if this is the first connection, he will be the host so we must always accept him
if(multi_num_players() == 0){
// check to see if this is a tracker game, and if so make sure this is a valid MT player
// we probably eventually want to make sure he's not passing us a fake tracker id#
if (MULTI_IS_TRACKER_GAME) {
if(jr->tracker_id < 0){
// FS2 Open PXO doesn't use this
//return JOIN_DENY_JR_TRACKER_INVAL;
}
}
// if we're password protected
if(std_is_host_passwd() && strcmp(jr->passwd, Multi_options_g.std_passwd)){
return JOIN_DENY_JR_PASSWD;
}
// don't allow the host to join as an observer
if(jr->flags & JOIN_FLAG_AS_OBSERVER){
return JOIN_DENY_JR_NOOBS;
} else {
return -1;
}
}
}
#endif // #ifndef NO_STANDALONE
// first off check to see if we're violating any of our max players/observers/connections boundaries
// if we've already got the full 16 (MAX_PLAYERS) connections - yow
if( (multi_num_connections() >= MULTI_MAX_CONNECTIONS) ||
// if we're full of observers and this guy wants to be an observer
((multi_num_observers() >= MAX_OBSERVERS) && (jr->flags & JOIN_FLAG_AS_OBSERVER)) ||
// if we're up to MULTI_MAX_PLAYERS-1 and we're on the standalone
((multi_num_players() >= (MULTI_MAX_PLAYERS - 1)) && (Game_mode & GM_STANDALONE_SERVER)) ||
// if we're up to MULTI_MAX_PLAYERS
(multi_num_players() >= MULTI_MAX_PLAYERS) ||
// if the max players for a standalone was set
((Multi_options_g.std_max_players != -1) && (multi_num_players() >= Multi_options_g.std_max_players)) ){
// we're full buddy - sorry
return JOIN_DENY_JR_FULL;
}
// check to see if this is a tracker game, and if so make sure this is a valid MT player
// we probably eventually want to make sure he's not passing us a fake tracker id#
if (MULTI_IS_TRACKER_GAME) {
if(jr->tracker_id < 0){
// FS2Open PXO Doesn't use this
//return JOIN_DENY_JR_TRACKER_INVAL;
}
}
// check to see if the player is trying to ingame join in a closed game
if(MULTI_IN_MISSION && (Netgame.mode == NG_MODE_CLOSED)){
return JOIN_DENY_JR_CLOSED;
}
// check to see if the player has passed a valid password in a password protected game
if((Netgame.mode == NG_MODE_PASSWORD) && strcmp(Netgame.passwd,jr->passwd)){
return JOIN_DENY_JR_PASSWD;
}
// check to see if the netgame is forming and is temporarily marked as closed
if((Netgame.game_state == NETGAME_STATE_FORMING) && (Netgame.flags & NG_FLAG_TEMP_CLOSED)){
return JOIN_DENY_JR_TEMP_CLOSED;
}
// check to make sure he meets the rank requirement
if((Netgame.mode == NG_MODE_RANK_ABOVE) && (jr->player_rank < Netgame.rank_base)){
return JOIN_DENY_JR_RANK_LOW;
}
// check to make sure he meets the rank requirement
if((Netgame.mode == NG_MODE_RANK_BELOW) && (jr->player_rank > Netgame.rank_base)){
return JOIN_DENY_JR_RANK_HIGH;
}
// can't ingame join a non-dogfight game
if((Netgame.game_state != NETGAME_STATE_FORMING) && !(Netgame.type_flags & NG_TYPE_DOGFIGHT)){
return JOIN_DENY_JR_TYPE;
}
#ifndef NO_STANDALONE
// if the player was banned by the standalone
if((Game_mode & GM_STANDALONE_SERVER) && std_player_is_banned(jr->callsign)){
return JOIN_DENY_JR_BANNED;
}
#endif
// if the game is in-mission, make sure there are ships available
if(MULTI_IN_MISSION && !(jr->flags & JOIN_FLAG_AS_OBSERVER)){
team0_avail = 0;
team1_avail = 0;
multi_player_ships_available(&team0_avail,&team1_avail);
// if there are no ships available on either team
if((team0_avail == 0) && (team1_avail == 0)){
return JOIN_DENY_JR_FULL;
}
}
// if my ingame joining flag is set, then deny since we only allow one ingame joiner at a time
if ( Netgame.flags & NG_FLAG_INGAME_JOINING ){
return JOIN_DENY_JR_INGAME_JOIN;
}
// check to make sure the game is not full (of observers, or players, as appropriate)
if((jr->flags & JOIN_FLAG_AS_OBSERVER)){
if((multi_num_observers() + 1) > Netgame.options.max_observers){
return JOIN_DENY_JR_FULL;
}
}
// if the netgame is restricted or is team vs. team
if((Netgame.mode == NG_MODE_RESTRICTED) || (Netgame.type_flags & NG_TYPE_TEAM)){
// ingame, we must query the host to see if this guy is accepted
if(MULTI_IN_MISSION){
return JOIN_QUERY_RESTRICTED;
}
}
// check to make sure this player hasn't been kick/banned
if(multi_kick_is_banned(addr)){
return JOIN_DENY_JR_BANNED;
}
// check to make sure this player doesn't already exist
if ( find_player(addr) >= 0 ) {
return JOIN_DENY_JR_DUP;
}
return -1;
}
// called by any machine (client, host, server, standalone, etc), to begin warping out all player objects
void multi_warpout_all_players()
{
int idx;
// i'f i'm already marked as warping out, don't do this again
if(Net_player->flags & NETINFO_FLAG_WARPING_OUT){
return;
}
// stop my afterburners
if((Player_obj != NULL) && (Player_obj->type == OBJ_SHIP) && !(Game_mode & GM_STANDALONE_SERVER)){
afterburners_stop( Player_obj, 1 );
}
// traverse through each player
for(idx=0;idx<MAX_PLAYERS;idx++) {
object *objp;
// only warpout player _ships_ which are not mine
if(MULTI_CONNECTED(Net_players[idx]) && (Net_player != &Net_players[idx]) && (Objects[Net_players[idx].player->objnum].type == OBJ_SHIP)){
objp = &Objects[Net_players[idx].player->objnum];
obj_set_flags( objp, objp->flags & (~OF_COLLIDES) );
shipfx_warpout_start( objp );
}
}
// now, mark ourselves as needing to warp out
Net_player->flags |= NETINFO_FLAG_WARPING_OUT;
// if we're an observer, or we're respawning, or we can't warp out. so just jump into the debrief state
if((Net_player->flags & NETINFO_FLAG_OBSERVER) || (Net_player->flags & NETINFO_FLAG_RESPAWNING) ||
(Net_player->flags & NETINFO_FLAG_OBSERVER) || ((Player_obj->type == OBJ_SHIP) && (Player_ship->flags & SF_CANNOT_WARP)) ){
if(Netgame.type_flags & NG_TYPE_DOGFIGHT){
gameseq_post_event(GS_EVENT_MULTI_DOGFIGHT_DEBRIEF);
} else {
gameseq_post_event(GS_EVENT_DEBRIEF);
}
}
// if we're a ship, then begin the warpout process
else {
// turn off collision detection for my ship
obj_set_flags(Player_obj, Player_obj->flags & (~OF_COLLIDES) );
gameseq_post_event(GS_EVENT_PLAYER_WARPOUT_START_FORCED);
}
}
// determine the highest rank of any of the players in the game
int multi_get_highest_rank()
{
int idx;
int max_rank = -1;
// go through all the players
for(idx=0;idx<MAX_PLAYERS;idx++){
if(MULTI_CONNECTED(Net_players[idx]) && !MULTI_STANDALONE(Net_players[idx]) && !MULTI_PERM_OBSERVER(Net_players[idx]) && (Net_players[idx].player->stats.rank > max_rank)){
max_rank = Net_players[idx].player->stats.rank;
}
}
// return what we found
return max_rank;
}
// called on the machine of the player who hit alt+j
void multi_handle_end_mission_request()
{
int idx;
// all clients should send the request to the server. no exceptions
if(!(Net_player->flags & NETINFO_FLAG_AM_MASTER)){
send_endgame_packet();
}
// the server of the game does some further processing
else {
ml_string("Server received endgame request, proceeding...");
// first we should toss all ingame joiners
for(idx=0;idx<MAX_PLAYERS;idx++){
if(MULTI_CONNECTED(Net_players[idx]) && (Net_players[idx].flags & NETINFO_FLAG_INGAME_JOIN)){
multi_kick_player(idx,0,KICK_REASON_INGAME_ENDED);
}
}
// send the endgame packet to all clients, who will act on it immediately
send_endgame_packet();
Netgame.game_state = NETGAME_STATE_ENDGAME;
send_netgame_update_packet();
#ifndef NO_STANDALONE
if(Game_mode & GM_STANDALONE_SERVER){
// move to the standalone postgame (which is where we'll handle stats packets, etc)
gameseq_post_event(GS_EVENT_STANDALONE_POSTGAME);
}
#endif
// begin the warpout process for all players and myself
multi_warpout_all_players();
}
}
// called to handle any special cases where a player is in some submemu when the game is ended
void multi_handle_state_special()
{
int stack_depth,current_depth;
// first off - kill any active popups
popup_kill_any_active();
// kill any popupdeads
if(popupdead_is_active()){
popupdead_close();
}
// kill off the pilot info popup if its active
if(multi_pinfo_popup_active()){
multi_pinfo_popup_kill();
}
// now do any special processing for being in states other then the gameplay states
stack_depth = gameseq_get_depth();
// if we're not pushed on top of any states, do any special state case handling here
if(stack_depth == 0){
// currently there are no special cases, so return
return;
}
// if we are pushed on any states, post events to pop them off one by one
else {
current_depth = stack_depth;
do {
switch(gameseq_get_state(stack_depth - current_depth)){
// the hotkey screen
case GS_STATE_HOTKEY_SCREEN :
mission_hotkey_exit();
Game_do_state_should_skip = 1;
break;
// the options menu
case GS_STATE_OPTIONS_MENU:
options_cancel_exit();
Game_do_state_should_skip = 1;
break;
// the hud config (1 deeper in the options menu)
case GS_STATE_HUD_CONFIG:
hud_config_cancel();
Game_do_state_should_skip = 1;
break;
// controls config (1 deeper than the options menu)
case GS_STATE_CONTROL_CONFIG:
control_config_cancel_exit();
Game_do_state_should_skip = 1;
break;
// mission goals screen
case GS_STATE_SHOW_GOALS:
mission_goal_exit();
Game_do_state_should_skip = 1;
break;
// mission log scrollback
case GS_STATE_MISSION_LOG_SCROLLBACK:
hud_scrollback_exit();
Game_do_state_should_skip = 1;
break;
// pause screen
case GS_STATE_MULTI_PAUSED:
gameseq_pop_state();
Game_do_state_should_skip = 1;
break;
}
// next pushed state
current_depth--;
} while(current_depth > 0);
}
}
// called by the file xfer subsytem when we start receiving a file
void multi_file_xfer_notify(int handle)
{
char *filename;
int len,idx;
int force_dir;
int cf_type;
int is_mission = 0;
// get the filename of the file we are receiving
filename = NULL;
filename = multi_xfer_get_filename(handle);
// get the directory the file is forced into
force_dir = multi_xfer_get_force_dir(handle);
// something is messed up
if(filename == NULL){
return;
}
// convert the filename to all lowercase
len = strlen(filename);
for(idx=0;idx<len;idx++){
filename[idx] = (char)tolower(filename[idx]);
}
// if this is a mission file
is_mission = (strstr(filename, FS_MISSION_FILE_EXT) != NULL);
// determine where its going to go
if(is_mission){
cf_type = Net_player->p_info.options.flags & MLO_FLAG_XFER_MULTIDATA ? CF_TYPE_MULTI_CACHE : CF_TYPE_MISSIONS;
} else {
cf_type = CF_TYPE_MULTI_CACHE;
}
// QUICK FIX
// check to see if the file is read-only
if((strlen(filename) > 0) && !cf_access(filename, cf_type, 00) && (cf_access(filename, cf_type, 02) == -1)){
multi_xfer_xor_flags(handle, MULTI_XFER_FLAG_REJECT);
Net_player->flags &= ~(NETINFO_FLAG_DO_NETWORKING);
popup(PF_USE_AFFIRMATIVE_ICON, 1, XSTR("&Ok", 713), XSTR("An outdated copy of this file exists, but it cannot be overwritten by the server because it is set to be read-only. Change the permissions on this file next time.", 714));
multi_quit_game(PROMPT_NONE);
return;
}
// if the incoming filename is a freespace file, set my netplayer state to be "file xfer"
if(is_mission){
// we'd better not be xferring a file right now
Assert(Net_player->s_info.xfer_handle == -1);
// force into the multidata directory
multi_xfer_handle_force_dir(handle, cf_type);
// set my xfer handle
Net_player->s_info.xfer_handle = handle;
Net_player->state = NETPLAYER_STATE_MISSION_XFER;
send_netplayer_update_packet();
}
// otherwise always hand it off to the multi_data system
else {
multi_data_handle_incoming(handle);
}
}
// return the lag/disconnected status of the game
#define MULTI_LAG_VAL 400
int multi_query_lag_status()
{
// -1 == not lagged, 0 == lagged, 1 == disconnected
// if I'm the server of the game, I can't be lagged
if(Net_player->flags & NETINFO_FLAG_AM_MASTER){
return -1;
}
// if we've been disconnected for some reason or another
if(multi_client_server_dead()){
return 1;
}
// if our ping time to the server is over a certain time
if(Netgame.server->s_info.ping.ping_avg >= MULTI_LAG_VAL){
return 0;
}
// not lagged
return -1;
}
// process a valid join request
void multi_process_valid_join_request(join_request *jr, net_addr *who_from, int ingame_join_team)
{
int net_player_num,player_num;
short id_num;
// create netplayer and player objects for this guy
net_player_num = multi_find_open_netplayer_slot();
player_num = multi_find_open_player_slot();
id_num = multi_get_new_id();
Assert((net_player_num != -1) && (player_num != -1));
// if he is requesting to join as an observer
if(jr->flags & JOIN_FLAG_AS_OBSERVER){
// create the (permanently) observer player
if(!multi_obs_create_player(net_player_num, jr->callsign, who_from, &Players[player_num])){
Int3();
}
// copy his pilot image filename
if(strlen(jr->image_filename) > 0){
strcpy(Net_players[net_player_num].player->image_filename, jr->image_filename);
} else {
strcpy(Net_players[net_player_num].player->image_filename, "");
}
// copy his pilot squad filename
Net_players[net_player_num].player->insignia_texture = -1;
player_set_squad_bitmap(Net_players[net_player_num].player, jr->squad_filename);
// clear his multi_data info
multi_data_handle_join(net_player_num);
// set some extra flags for him as appropriate
if(MULTI_IN_MISSION){
Net_players[net_player_num].flags |= NETINFO_FLAG_INGAME_JOIN;
}
Net_players[net_player_num].flags |= NETINFO_FLAG_CONNECTED;
Net_players[net_player_num].player_id = id_num;
Net_players[net_player_num].tracker_player_id = jr->tracker_id;
// store pxo info
if(strlen(jr->pxo_squad_name) > 0){
strcpy(Net_players[net_player_num].p_info.pxo_squad_name, jr->pxo_squad_name);
} else {
strcpy(Net_players[net_player_num].p_info.pxo_squad_name, "");
}
// if he's using hacked data
if(jr->flags & JOIN_FLAG_HAXOR){
Net_players[net_player_num].flags |= NETINFO_FLAG_HAXOR;
}
// set his reliable connect time
Net_players[net_player_num].s_info.reliable_connect_time = time(NULL);
// send the accept packet here
send_accept_packet(net_player_num, (Net_players[net_player_num].flags & NETINFO_FLAG_INGAME_JOIN) ? ACCEPT_OBSERVER | ACCEPT_INGAME : ACCEPT_OBSERVER);
} else {
// create the player object
if(!multi_create_player( net_player_num, &Players[player_num], jr->callsign, who_from, -1, id_num )){
Int3();
}
// copy his pilot image filename
if(strlen(jr->image_filename) > 0){
strcpy(Net_players[net_player_num].player->image_filename, jr->image_filename);
} else {
strcpy(Net_players[net_player_num].player->image_filename, "");
}
// copy his pilot squad filename
Net_players[net_player_num].player->insignia_texture = -1;
player_set_squad_bitmap(Net_players[net_player_num].player, jr->squad_filename);
// clear his multi_data info
multi_data_handle_join(net_player_num);
// mark him as being connected
Net_players[net_player_num].flags |= NETINFO_FLAG_CONNECTED;
// set his tracker id correctly
Net_players[net_player_num].tracker_player_id = jr->tracker_id;
// set his player id#
Net_players[net_player_num].player_id = id_num;
// store pxo info
if(strlen(jr->pxo_squad_name) > 0){
strcpy(Net_players[net_player_num].p_info.pxo_squad_name, jr->pxo_squad_name);
} else {
strcpy(Net_players[net_player_num].p_info.pxo_squad_name, "");
}
// if he's using hacked data
if(jr->flags & JOIN_FLAG_HAXOR){
Net_players[net_player_num].flags |= NETINFO_FLAG_HAXOR;
}
// flag him appropriately if he's doing an ingame join
if(MULTI_IN_MISSION){
Int3();
Net_players[net_player_num].flags |= NETINFO_FLAG_INGAME_JOIN;
Net_players[net_player_num].s_info.ingame_join_flags = 0;
}
// set his reliable connect time
Net_players[net_player_num].s_info.reliable_connect_time = time(NULL);
// if he's joining as a host (on the standalone)
if(Net_players[net_player_num].flags & NETINFO_FLAG_GAME_HOST){
send_accept_packet(net_player_num, ACCEPT_HOST);
Netgame.host = &Net_players[net_player_num];
// set the game and player states appropriately
Netgame.game_state = NETGAME_STATE_STD_HOST_SETUP;
}
// if he's joining ingame
else if(Net_players[net_player_num].flags & NETINFO_FLAG_INGAME_JOIN){
// if we're in team vs. team mode
if(Netgame.type_flags & NG_TYPE_TEAM){
Assert(ingame_join_team != -1);
Net_players[net_player_num].p_info.team = ingame_join_team;
}
send_accept_packet(net_player_num, ACCEPT_INGAME, ingame_join_team);
// set his last full update time for updating him on ingame join ships
Net_players[net_player_num].s_info.last_full_update_time = timestamp(INGAME_SHIP_UPDATE_TIME);
}
// if he's joining as an otherwise ordinary client
else {
send_accept_packet(net_player_num, ACCEPT_CLIENT);
}
}
// set my ingame joining flag if the new guy is joining ingame
if ( Net_players[net_player_num].flags & NETINFO_FLAG_INGAME_JOIN ){
Int3();
Netgame.flags |= NG_FLAG_INGAME_JOINING;
}
// copy in his options
memcpy(&Net_players[net_player_num].p_info.options, &jr->player_options, sizeof(multi_local_options));
#ifndef NO_STANDALONE
// if on the standalone, then do any necessary gui updating
if(Game_mode & GM_STANDALONE_SERVER) {
std_add_player(&Net_players[net_player_num]);
std_connect_set_connect_count();
std_connect_set_host_connect_status();
} else
#endif
{
// let the create game screen know someone has joined
if(gameseq_get_state() == GS_STATE_MULTI_HOST_SETUP){
multi_create_handle_join(&Net_players[net_player_num]);
}
}
extern int Multi_client_update_times[MAX_PLAYERS];
Multi_client_update_times[net_player_num] = -1;
// notify datarate
multi_rate_reset(net_player_num);
}
// if a player is trying to join a restricted game, evaluate the keypress (accept or not, etc)
int multi_process_restricted_keys(int k)
{
int key1=-1,key2=-1; //JAS: Get rid of optimized warning
int team_val;
// if the query timestamp is not set, don't do anything
if(Multi_restr_query_timestamp == -1){
return 0;
}
// determine what keys to look for based upon the mode we're in
switch(Multi_join_restr_mode){
// normal restricted join, Y or N
case MULTI_JOIN_RESTR_MODE_1:
key1 = KEY_Y;
key2 = KEY_N;
break;
// team vs team, team 0 only has ships
case MULTI_JOIN_RESTR_MODE_2:
key1 = KEY_Y;
key2 = KEY_N;
break;
// team vs team, team 1 only has ships
case MULTI_JOIN_RESTR_MODE_3:
key1 = KEY_Y;
key2 = KEY_N;
break;
// team vs team, both teams have ships
case MULTI_JOIN_RESTR_MODE_4:
key1 = KEY_1;
key2 = KEY_2;
break;
// illegal mode
default :
Int3();
}
// check the keypress
if((k == key1) || (k == key2)){
// unset the timestamp
Multi_restr_query_timestamp = -1;
// MWA -- 5/26/98. Next line commented out. It should be cleared when the ingame joiner
// actually gets into the mission
//Netgame.flags &= ~(NG_FLAG_INGAME_JOINING);
// determine which team to put him on (if any)
switch(Multi_join_restr_mode){
// normal restricted join, Y or N
case MULTI_JOIN_RESTR_MODE_1:
team_val = (k == key1) ? 0 : -1;
break;
// team vs team, team 0 only has ships
case MULTI_JOIN_RESTR_MODE_2:
team_val = (k == key1) ? 0 : -1;
break;
// team vs team, team 1 only has ships
case MULTI_JOIN_RESTR_MODE_3:
team_val = (k == key1) ? 1 : -1;
break;
// team vs team, both teams have ships
case MULTI_JOIN_RESTR_MODE_4:
team_val = (k == key1) ? 0 : 1;
break;
// illegal mode
default :
team_val = -1; // JAS: Get rid of optimized warning
Int3();
}
// perform the proper response
if(Net_player->flags & NETINFO_FLAG_AM_MASTER){
if(team_val >= 0){
multi_process_valid_join_request(&Multi_restr_join_request,&Multi_restr_addr,team_val);
}
}
// otherwise tell the standalone to accept him
else {
if(team_val >= 0){
send_host_restr_packet("null",1,team_val);
} else {
send_host_restr_packet("null",2,-1);
}
}
// processed a key
return 1;
}
// didn't process any keys
return 0;
}
// determine the status of available player ships (use team_0 for non team vs. team situations)
void multi_player_ships_available(int *team_0,int *team_1)
{
ship_obj *moveup;
int mp_team_num;
*team_0 = 0;
*team_1 = 0;
moveup = GET_FIRST(&Ship_obj_list);
while(moveup!=END_OF_LIST(&Ship_obj_list)){
// if this ship is flagged as OF_COULD_BE_PLAYER
if(Objects[moveup->objnum].flags & OF_COULD_BE_PLAYER){
// get the team # for this ship
mp_team_num = multi_ts_get_team(Ships[Objects[moveup->objnum].instance].ship_name);
if(mp_team_num == 0){
(*team_0)++;
} else if(mp_team_num == 1){
(*team_1)++;
}
}
moveup = GET_NEXT(moveup);
}
}
// server should update the player's bank/link status with the data in the passed ship
void multi_server_update_player_weapons(net_player *pl,ship *shipp)
{
// don't process when the ship is dying.
if ( (shipp->flags & SF_DYING) || NETPLAYER_IS_DEAD(pl) )
return;
// primary bank status
pl->s_info.cur_primary_bank = (char)shipp->weapons.current_primary_bank;
// primary link status
pl->s_info.cur_link_status &= ~(1<<0);
if(shipp->flags & SF_PRIMARY_LINKED){
pl->s_info.cur_link_status |= (1<<0);
}
// barrel linking
for (int x=0; x<MAX_SHIP_PRIMARY_BANKS; x++)
pl->s_info.link_mode[x] = (char)shipp->primary_link_status[x];
// secondary bank status
if ( shipp->weapons.current_secondary_bank < 0 ) {
nprintf(("Network", "bashing %s's current sbank to 0\n", shipp->ship_name));
shipp->weapons.current_secondary_bank = 0;
}
pl->s_info.cur_secondary_bank = (char)shipp->weapons.current_secondary_bank;
// secondary link status
pl->s_info.cur_link_status &= ~(1<<1);
if(shipp->flags & SF_SECONDARY_DUAL_FIRE){
pl->s_info.cur_link_status |= (1<<1);
}
// ets values
pl->s_info.ship_ets = 0x0000;
// shield ets
pl->s_info.ship_ets |= ((ushort)shipp->shield_recharge_index << 8);
// weapon ets
pl->s_info.ship_ets |= ((ushort)shipp->weapon_recharge_index << 4);
// engine ets
pl->s_info.ship_ets |= ((ushort)shipp->engine_recharge_index);
Assert( pl->s_info.ship_ets != 0 );
}
void multi_server_update_player_sfoils(net_player *pl, ship *shipp)
{
// don't process when the ship is dying.
if ( (shipp->flags & SF_DYING) || NETPLAYER_IS_DEAD(pl) )
return;
int status;
if (!Ship_info[shipp->ship_info_index].sfoils)
status = SFOIL_CLOSED;
if (shipp->sfoil_status & (SFOIL_OPEN | SFOIL_OPENING))
status = SFOIL_OPEN;
else
status = SFOIL_CLOSED;
pl->s_info.sfoil_status = status;
}
// flush the multidata cache directory
void multi_flush_multidata_cache()
{
nprintf(("Network","FLUSHING MULTIDATA CACHE\n"));
// call the cfile function to flush the directory
cfile_flush_dir(CF_TYPE_MULTI_CACHE);
}
// flush all data from a previous mission before starting the next
void multi_flush_mission_stuff()
{
int idx;
for(idx=0;idx<MAX_PLAYERS;idx++){
if(MULTI_CONNECTED(Net_players[idx])){
// unset all unneeded status bits
Net_players[idx].flags &= ~(NETINFO_FLAG_MISSION_OK | NETINFO_FLAG_RESPAWNING | NETINFO_FLAG_WARPING_OUT);
// server is always "mission ok"
if(Net_players[idx].flags & NETINFO_FLAG_AM_MASTER){
Net_players[idx].flags |= NETINFO_FLAG_MISSION_OK;
}
// if this guy is a non-permanent observer, unset the appropriate flags
if(MULTI_TEMP_OBSERVER(Net_players[idx])){
Net_players[idx].flags &= ~(NETINFO_FLAG_OBSERVER | NETINFO_FLAG_OBS_PLAYER);
}
// misc
multi_ping_reset(&Net_players[idx].s_info.ping);
Net_players[idx].s_info.num_last_buttons = 0;
Net_players[idx].s_info.wing_index_backup = 0;
Net_players[idx].s_info.wing_index = 0;
Net_players[idx].p_info.ship_class = -1;
Net_players[idx].p_info.ship_index = -1;
Net_players[idx].s_info.xfer_handle = -1;
// ack handles
Net_players[idx].s_info.wing_index_backup = 0;
// objnum
Players[idx].objnum = -1;
}
}
// reset netgame stuff
Netgame.flags &= ~(NG_FLAG_TEMP_CLOSED);
multi_xfer_reset();
#ifndef NO_STANDALONE
// standalone servers should clear their goal trees now
if(Game_mode & GM_STANDALONE_SERVER){
std_multi_setup_goal_tree();
}
#endif
// object signatures
// this will eventually get reset to Netgame.security the next time an object gets its signature assigned.
// We do this to resynchronize the host/server and all clients
Next_ship_signature = SHIP_SIG_MIN;
Next_asteroid_signature = ASTEROID_SIG_MIN;
Next_non_perm_signature = NPERM_SIG_MIN;
// everyone will need to either reload the current mission, leave, or load the next mission, so in any case
Multi_mission_loaded = 0;
}
// should we ignore all controls and keypresses because of some multiplayer
int multi_ignore_controls(int key)
{
// if the multiplayer text messaging system is active, don't return any keys
if((key > 0) && multi_msg_text_process(key)){
return 1;
}
// if the host of the game is being prompted to accept or deny a player in a restricted game
if((key > 0) && multi_process_restricted_keys(key)){
return 1;
}
// if we're in text messaging mode, ignore controls
if(multi_msg_text_mode()){
return 1;
}
// if the pause system wants to eat keys for a while
if(multi_pause_eat_keys()){
return 1;
}
// multiplayer didn't eat the key
return 0;
}
// if the kill limit has been reached by any given player
int multi_kill_limit_reached()
{
int idx;
// is the kill limit <= 0 ?
// if so, consider it as _no_ kill limit
if(Netgame.options.kill_limit <= 0){
return 0;
}
// look through all active, non-observer players
for(idx=0;idx<MAX_PLAYERS;idx++){
if(MULTI_CONNECTED(Net_players[idx]) && !MULTI_STANDALONE(Net_players[idx]) && !MULTI_OBSERVER(Net_players[idx]) && (Net_players[idx].player->stats.m_kill_count_ok >= Netgame.options.kill_limit)){
// someone reached the limit
return 1;
}
}
// limit has not been reached yet
return 0;
}
// display a chat message (write to the correct spot - hud, standalone gui, chatbox, etc)
void multi_display_chat_msg(char *msg, int player_index, int add_id)
{
#ifndef NO_STANDALONE
// if i'm a standalone, always add to the gui
if(Game_mode & GM_STANDALONE_SERVER){
std_add_chat_text(msg,player_index,add_id);
return;
}
#endif
// in gameplay
if(Game_mode & GM_IN_MISSION){
// if we're paused, send it to the chatbox
if(Multi_pause_status){
chatbox_add_line(msg, player_index, add_id);
}
// otherwise print to the HUD
else {
multi_msg_display_mission_text(msg, player_index);
}
}
// otherwise add it to the chatbox
else {
chatbox_add_line(msg, player_index, add_id);
}
}
// fill in Current_file_checksum and Current_file_length
void multi_get_mission_checksum(char *filename)
{
CFILE *in;
Multi_current_file_checksum = 0xffff;
Multi_current_file_length = -1;
// get the filename
in = cfopen(filename,"rb");
if(in != NULL){
// get the length of the file
Multi_current_file_length = cfilelength(in);
cfclose(in);
in = cfopen(filename,"rb");
if(in != NULL){
// get the checksum of the file
cf_chksum_short(in,&Multi_current_file_checksum);
// close the file
cfclose(in);
in = NULL;
}
// if the file doesn't exist, setup some special values, so the server recognizes this
else {
Multi_current_file_checksum = 0xffff;
Multi_current_file_length = -1;
}
} else {
// don't transfew builtin missions
if(multi_is_builtin_mission()){
multi_quit_game(PROMPT_ALL, MULTI_END_NOTIFY_KICKED_CANT_XFER);
}
}
nprintf(("Network","NET FILE CHECKSUM : %d %d\n",Multi_current_file_checksum,Multi_current_file_length));
}
char multi_unit_to_char(float unit)
{
char ret;
if(unit > 1.0f){
Int3();
unit = 1.0f;
}
if(unit < -1.0f){
Int3();
unit = -1.0f;
}
ret = (char)(unit * 127.0f);
return ret;
}
float multi_char_to_unit(float val)
{
float ret;
ret = (float)val / 127.0f;
if(ret > 1.0f){
Int3();
ret = 1.0f;
}
if(ret < -1.0f){
Int3();
ret = -1.0f;
}
return ret;
}
// if we should render our ping time to the server in a multiplayer game
int multi_show_ingame_ping()
{
// always show it for now
return 1;
}
int multi_get_connection_speed()
{
int cspeed;
char *connection_speed;
#ifdef _WIN32
connection_speed = os_config_read_string(NULL, "ConnectionSpeed", "");
if ( !stricmp(connection_speed, NOX("Slow")) ) {
cspeed = CONNECTION_SPEED_288;
} else if ( !stricmp(connection_speed, NOX("56K")) ) {
cspeed = CONNECTION_SPEED_56K;
} else if ( !stricmp(connection_speed, NOX("ISDN")) ) {
cspeed = CONNECTION_SPEED_SISDN;
} else if ( !stricmp(connection_speed, NOX("Cable")) ) {
cspeed = CONNECTION_SPEED_CABLE;
} else if ( !stricmp(connection_speed, NOX("Fast")) ) {
cspeed = CONNECTION_SPEED_T1;
} else {
cspeed = CONNECTION_SPEED_NONE;
}
#else
// mua ha ha
cspeed = CONNECTION_SPEED_T1;
#endif
return cspeed;
}
// return a MVALID_STATUS_* define based upon the passed string
int multi_string_to_status(char *valid_string)
{
if (strstr(valid_string, "invalid"))
return MVALID_STATUS_INVALID;
if (strstr(valid_string, "valid"))
return MVALID_STATUS_VALID;
return MVALID_STATUS_UNKNOWN;
}
// if we're in tracker mode, do a validation update on all known missions
// **************************************** Changed for FS2NetD ***********************************
// Origional code for this function just became _BOGUS_
// ulgy hacking here..
extern char *Multi_create_loading_fname[];
extern int Multi_create_bitmap;
extern int Please_wait_coords[GR_NUM_RESOLUTIONS][4];
#define MC_X_COORD 0
#define MC_Y_COORD 1
void multi_update_validate_missions_DrawString(char *str)
{
gamesnd_play_iface(SND_SCROLL);
// --------- ripped from [V]'s "LOADING" screen code
int loading_bitmap;
loading_bitmap = bm_load(Multi_create_loading_fname[gr_screen.res]);
// draw the background, etc
gr_reset_clip();
GR_MAYBE_CLEAR_RES(Multi_create_bitmap);
if(Multi_create_bitmap != -1){
gr_set_bitmap(Multi_create_bitmap);
gr_bitmap(0, 0);
}
chatbox_render();
if ( loading_bitmap > -1 ){
gr_set_bitmap(loading_bitmap);
}
gr_bitmap( Please_wait_coords[gr_screen.res][MC_X_COORD], Please_wait_coords[gr_screen.res][MC_Y_COORD] );
// draw str on it
int str_w, str_h;
gr_set_color_fast(&Color_bright_white);
gr_set_font(FONT2);
gr_get_string_size(&str_w, &str_h, str);
gr_string((gr_screen.max_w - str_w) / 2, (gr_screen.max_h - str_h) / 2, str);
gr_set_font(FONT1);
gr_flip();
bm_release(loading_bitmap);
}
void multi_update_valid_missions()
{
// commented out from down below. if this file doesn't exist and try to get the mission load
// screen for MP the game chokes. only way before this file would get created is if user was
// try to connect using PXO. now no matter what we get the file created and people don't have
// crashing games.
// open the outfile
CFILE *mvalid_cfg = cfopen("mvalid.cfg", "wt", CFILE_NORMAL, CF_TYPE_DATA);
// if we're not on FS2NetD (PXO) then don't bother with this function
if (!Om_tracker_flag)
return;
static char Server[32];
static int port = -1;
if (port == -1)
{
CFILE *file = cfopen("MP.cfg","rt",CFILE_NORMAL,CF_TYPE_DATA);
if(file == NULL){
ml_printf("Network","Error loading fs2open_pxo.cfg file!\n");
return;
}
char Port[32];
if (cfgets(Server, 32, file) == NULL)
{
ml_printf("Network", "No Masterserver definition!\n");
return;
}
if (strstr(Server, "\n"))
*strstr(Server, "\n") = '\0';
if (cfgets(Port, 32, file) != NULL)
port = atoi(Port);
else
port = 12000;
if (!FS2OpenPXO_Socket.isInitialized())
{
#if !defined(PXO_TCP)
if (!FS2OpenPXO_Socket.InitSocket())
#else
if (!FS2OpenPXO_Socket.InitSocket(Server, port))
#endif
{
ml_printf("Network (FS2OpenPXO): Could not initialize UDP_Socket!!\n");
}
}
}
#ifndef NO_STANDALONE
// if we're a standalone, show a dialog saying "validating missions"
if(Game_mode & GM_STANDALONE_SERVER){
std_create_gen_dialog("Validating missions");
std_gen_set_text("Querying FS2NetD:",1);
}
#endif
multi_update_validate_missions_DrawString("Asking PXO Server for Mission CRCs");
// ----------- Get the CRCs from the server -------------
//FS2OpenPXO_Socket
int numFrecs;
file_record *frecs = GetMissionsList(numFrecs, Server, FS2OpenPXO_Socket, port);
#ifndef NO_STANDALONE
// if we're a standalone, show a dialog saying "validating missions"
if(Game_mode & GM_STANDALONE_SERVER){
std_gen_set_text("Got FS2NetD Reply:",1);
}
#endif
// this is a shameless splicing of [V]'s code from the pxo spew below and my code.
char **file_names;
char full_name[MAX_FILENAME_LEN+1];
char wild_card[256];
int count, idx, i;
bool Found;
uint checksum;
// FILE *out;
// allocate filename space
file_names = (char**)malloc(sizeof(char*) * 1024); // 1024 files should be safe!
if(file_names != NULL){
memset(wild_card, 0, 256);
strcpy(wild_card, NOX("*"));
strcat(wild_card, FS_MISSION_FILE_EXT);
count = cf_get_file_list(1024, file_names, CF_TYPE_MISSIONS, wild_card);
// open the outfile
//CFILE *mvalid_cfg = cfopen("mvalid.cfg", "wt", CFILE_NORMAL, CF_TYPE_DATA);
// do all the checksums
for(idx=0; idx<count; idx++){
memset(full_name, 0, MAX_FILENAME_LEN+1);
strcpy(full_name, cf_add_ext(file_names[idx], FS_MISSION_FILE_EXT));
std::string temp = "Validating ";
temp = temp + full_name;
#ifndef NO_STANDALONE
// if we're a standalone, show a dialog saying "validating missions"
if(Game_mode & GM_STANDALONE_SERVER)
{
std_gen_set_text((char *) temp.c_str(),1);
}
else
#endif
multi_update_validate_missions_DrawString((char *) temp.c_str());
cf_chksum_long(full_name, &checksum);
Found = false;
cfputs("'", mvalid_cfg);
cfputs(full_name, mvalid_cfg);
cfputs("'", mvalid_cfg);
for (i = 0; i < numFrecs; i++)
{
if (!strcmp(full_name, frecs[i].name))
{
// Found now becomes a valid/invalid specifier
if (checksum == frecs[i].crc32)
{
cfputs(" valid\n", mvalid_cfg);
Found = true;
}
break;
}
}
if (!Found)
{
cfputs(" invalid\n", mvalid_cfg);
}
}
cfclose(mvalid_cfg);
free(file_names);
}
delete[] frecs;
#ifndef NO_STANDALONE
// if we're a standalone, kill the validate dialog
if(Game_mode & GM_STANDALONE_SERVER){
std_destroy_gen_dialog();
}
#endif
}
void Kaz_NoBackGround_DrawString(char *str)
{
gamesnd_play_iface(SND_SCROLL);
// --------- ripped from [V]'s "LOADING" screen code
int loading_bitmap;
loading_bitmap = bm_load(Multi_create_loading_fname[gr_screen.res]);
// draw the background, etc
gr_reset_clip();
//GR_MAYBE_CLEAR_RES(Multi_create_bitmap);
gr_clear();
if ( loading_bitmap > -1 ){
gr_set_bitmap(loading_bitmap);
}
gr_bitmap( Please_wait_coords[gr_screen.res][MC_X_COORD], Please_wait_coords[gr_screen.res][MC_Y_COORD] );
// draw str on it
int str_w, str_h;
gr_set_color_fast(&Color_bright_white);
gr_set_font(FONT2);
gr_get_string_size(&str_w, &str_h, str);
gr_string((gr_screen.max_w - str_w) / 2, (gr_screen.max_h - str_h) / 2, str);
gr_set_font(FONT1);
gr_flip();
bm_release(loading_bitmap);
}
void multi_update_valid_tables()
{
static char Server[32];
static int port = -1;
if (port == -1)
{
CFILE *file = cfopen("MP.cfg","rt",CFILE_NORMAL,CF_TYPE_DATA);
if(file == NULL){
ml_printf("Network","Error loading fs2open_pxo.cfg file!\n");
return;
}
char Port[32];
if (cfgets(Server, 32, file) == NULL)
{
ml_printf("Network", "No Masterserver definition!\n");
return;
}
if (strstr(Server, "\n"))
*strstr(Server, "\n") = '\0';
if (cfgets(Port, 32, file) != NULL)
port = atoi(Port);
else
port = 12000;
if (!FS2OpenPXO_Socket.isInitialized())
{
#if !defined(PXO_TCP)
if (!FS2OpenPXO_Socket.InitSocket())
#else
if (!FS2OpenPXO_Socket.InitSocket(Server, port))
#endif
{
ml_printf("Network (FS2OpenPXO): Could not initialize UDP_Socket!!\n");
}
}
}
#ifndef NO_STANDALONE
// if we're a standalone, show a dialog saying "validating missions"
if(Game_mode & GM_STANDALONE_SERVER){
std_create_gen_dialog("Validating tables");
std_gen_set_text("Querying FS2NetD:",1);
}
#endif
//Kaz_NoBackGround_DrawString("Validating Tables");
// ----------- Get the CRCs from the server -------------
//FS2OpenPXO_Socket
int numFrecs;
file_record *frecs = GetTablesList(numFrecs, Server, FS2OpenPXO_Socket, port);
#ifndef NO_STANDALONE
// if we're a standalone, show a dialog saying "validating missions"
if(Game_mode & GM_STANDALONE_SERVER){
std_gen_set_text("Got FS2NetD Reply:",1);
}
#endif
// this is a shameless splicing of [V]'s code from the pxo spew below and my code.
char **file_names;
char full_name[MAX_FILENAME_LEN+1];
char wild_card[256];
int count, idx, i;
bool Found;
uint checksum = 0;
// FILE *out;
// allocate filename space
file_names = (char**)malloc(sizeof(char*) * 1024); // 1024 files should be safe!
if(file_names != NULL){
memset(wild_card, 0, 256);
strcpy(wild_card, NOX("*"));
strcat(wild_card, ".tbl");
count = cf_get_file_list(1024, file_names, CF_TYPE_TABLES, wild_card);
// open the outfile
CFILE *tvalid_cfg = cfopen("tvalid.cfg", "wt", CFILE_NORMAL, CF_TYPE_DATA);
// do all the checksums
for(idx=0; idx<count; idx++){
memset(full_name, 0, MAX_FILENAME_LEN+1);
strcpy(full_name, cf_add_ext(file_names[idx], ".tbl"));
std::string temp = "Validating ";
temp = temp + full_name;
#ifndef NO_STANDALONE
// if we're a standalone, show a dialog saying "validating missions"
if(Game_mode & GM_STANDALONE_SERVER)
{
std_gen_set_text((char *) temp.c_str(),1);
}
else
#endif
//multi_update_validate_tables_DrawString((char *) temp.c_str());
cf_chksum_long(full_name, &checksum);
Found = false;
cfputs(full_name, tvalid_cfg);
for (i = 0; i < numFrecs && !Found; i++)
{
if (!strcmp(full_name, frecs[i].name))
{
// Found now becomes a valid/invalid specifier
if (checksum == frecs[i].crc32)
{
cfputs(" valid\n", tvalid_cfg);
Found = true;
}
else
{
cfputs(" invalid\n", tvalid_cfg);
Found = true;
}
}
}
if (!Found)
{
cfputs(" valid\n", tvalid_cfg);
}
}
cfclose(tvalid_cfg);
free(file_names);
}
delete[] frecs;
#ifndef NO_STANDALONE
// if we're a standalone, kill the validate dialog
if(Game_mode & GM_STANDALONE_SERVER){
std_destroy_gen_dialog();
}
#endif
}
// get a new id# for a player
short multi_get_new_id()
{
if(Multi_id_num > 20000){
Multi_id_num = 0;
}
return Multi_id_num++;
}
// ------------------------------------
//XSTR:OFF
DCF(multi,"changes multiplayer settings")
{
if(Dc_command){
dc_get_arg(ARG_STRING);
if(strcmp(Dc_arg, "kick")==0){ // kick a player
multi_dcf_kick();
#ifndef NDEBUG
} else if(strcmp(Dc_arg, "stats")==0) {
// multi_toggle_stats();
} else if(strcmp(Dc_arg, "show_stats")==0) {
// multi_show_basic_stats(0);
} else if(strcmp(Dc_arg, "dump_stats")==0) {
// multi_show_basic_stats(1);
#endif
} else if(strcmp(Dc_arg, "voice")==0){ // settings for multiplayer voice
multi_voice_dcf();
} else if(strcmp(Dc_arg, "respawn_chump")==0){ // set a really large # of respawns
if((Net_player != NULL) && (Net_player->flags & NETINFO_FLAG_GAME_HOST)){
Netgame.respawn = 9999;
Netgame.options.respawn = 9999;
// if i'm the server, send a netgame update
if(Net_player->flags & NETINFO_FLAG_AM_MASTER){
send_netgame_update_packet();
}
}
} else if(strcmp(Dc_arg, "ss_leaders")==0){ // only host or team captains can modify ships
if((Net_player != NULL) && (Net_player->flags & NETINFO_FLAG_GAME_HOST)){
Netgame.options.flags |= MSO_FLAG_SS_LEADERS;
multi_options_update_netgame();
}
} else if(strcmp(Dc_arg, "make_players")==0){
#ifndef NDEBUG
multi_make_fake_players(MAX_PLAYERS);
#endif
} else if(strcmp(Dc_arg, "givecd")==0){
extern int Multi_has_cd;
Multi_has_cd = 1;
} else if(strcmp(Dc_arg, "oo")==0){
int new_flags = -1;
dc_get_arg(ARG_INT);
if(Dc_arg_type & ARG_INT){
new_flags = Dc_arg_int;
}
dc_printf("Interesting flags\nPos : %d\nVelocity : %d\nDesired vel : %d\nOrient : %d\nRotvel : %d\nDesired rotvel %d\n",
1<<0, 1<<7, 1<<8, 1<<1, 1<<9, 1<<10);
} else if(strcmp(Dc_arg, "oo_sort")==0){
extern int OO_sort;
OO_sort = !OO_sort;
if(OO_sort){
dc_printf("Network object sorting ENABLED\n");
} else {
dc_printf("Network object sorting DISABLED\n");
}
}
}
}
//XSTR:ON
// PXO crc checking stuff
void multi_spew_pxo_checksums(int max_files, char *outfile)
{
char **file_names;
char full_name[MAX_FILENAME_LEN+1];
char wild_card[256];
int count, idx;
uint checksum;
FILE *out;
char modname[128];
memset(modname, 0, 128);
if (Cmdline_mod)
if (Cmdline_mod[strlen(Cmdline_mod)-1] == '/' || Cmdline_mod[strlen(Cmdline_mod)-1] == '\\')
strncpy(modname, Cmdline_mod, strlen(Cmdline_mod)-1);
else
strcpy(modname, Cmdline_mod);
// allocate filename space
file_names = (char**)malloc(sizeof(char*) * max_files);
if(file_names != NULL){
memset(wild_card, 0, 256);
strcpy(wild_card, NOX("*"));
strcat(wild_card, FS_MISSION_FILE_EXT);
count = cf_get_file_list(max_files, file_names, CF_TYPE_MISSIONS, wild_card);
// open the outfile
out = fopen(outfile, "wt");
if(out == NULL){
return;
}
// do all the checksums
for(idx=0; idx<count; idx++){
memset(full_name, 0, MAX_FILENAME_LEN+1);
strcpy(full_name, cf_add_ext(file_names[idx], FS_MISSION_FILE_EXT));
if(cf_chksum_long(full_name, &checksum)){
fprintf(out, "# %s : %u\n", full_name, (unsigned int)checksum);
fprintf(out, "INSERT INTO Missions SET FileName=\"%s\", CRC32=\"%u\", Mod=\"%s\";\n\n", full_name, (unsigned int)checksum, modname);
}
}
fclose(out);
free(file_names);
}
}
void multi_spew_table_checksums(int max_files, char *outfile)
{
char **file_names;
char full_name[MAX_FILENAME_LEN+1];
char wild_card[256];
int count, idx;
uint checksum;
FILE *out;
char modname[128];
memset(modname, 0, 128);
if (Cmdline_mod)
if (Cmdline_mod[strlen(Cmdline_mod)-1] == '/' || Cmdline_mod[strlen(Cmdline_mod)-1] == '\\')
strncpy(modname, Cmdline_mod, strlen(Cmdline_mod)-1);
else
strcpy(modname, Cmdline_mod);
// allocate filename space
file_names = (char**)malloc(sizeof(char*) * max_files);
if(file_names != NULL){
memset(wild_card, 0, 256);
strcpy(wild_card, NOX("*"));
strcat(wild_card, ".tbl");
count = cf_get_file_list(max_files, file_names, CF_TYPE_TABLES, wild_card);
// open the outfile
out = fopen(outfile, "wt");
if(out == NULL){
return;
}
// do all the checksums
for(idx=0; idx<count; idx++){
memset(full_name, 0, MAX_FILENAME_LEN+1);
strcpy(full_name, cf_add_ext(file_names[idx], ".tbl"));
if(cf_chksum_long(full_name, &checksum)){
fprintf(out, "# %s : %u\n", full_name, (unsigned int)checksum);
fprintf(out, "INSERT INTO fstables SET FileName=\"%s\", CRC32=\"%u\", Mod=\"%s\";\n\n", full_name, (unsigned int)checksum, modname);
}
}
fclose(out);
free(file_names);
}
}
DCF(pxospew,"spew PXO 32 bit checksums for all visible mission files")
{
int max_files;
dc_get_arg(ARG_INT);
if(Dc_arg_type & ARG_INT){
max_files = Dc_arg_int;
dc_get_arg(ARG_STRING);
if(Dc_arg_type & ARG_STRING){
multi_spew_pxo_checksums(max_files, Dc_arg);
}
}
}
// make a bunch of fake players - don't rely on this to be very safe - its mostly used for interface testing
#ifndef NDEBUG
void multi_make_fake_players(int count)
{
int idx;
for(idx=0;idx<count;idx++){
if(!MULTI_CONNECTED(Net_players[idx])){
Net_players[idx].player = &Players[idx];
sprintf(Net_players[idx].player->callsign,"Player %d",idx);
Net_players[idx].flags |= NETINFO_FLAG_CONNECTED;
}
}
}
#endif
// ---------------------------------------------------------------------------------------------------------------------
// PACK UNPACK STUFF
//
#pragma optimize("", off)
typedef struct bitbuffer {
ubyte mask;
int rack;
ubyte *data;
ubyte *org_data;
} bitbuffer;
void bitbuffer_init( bitbuffer *bitbuf, ubyte *data )
{
bitbuf->rack = 0;
bitbuf->mask = 0x80;
bitbuf->data = data;
bitbuf->org_data = data;
}
int bitbuffer_write_flush( bitbuffer *bitbuf )
{
// Flush to next byte
if ( bitbuf->mask != 0x80 ) {
*bitbuf->data++ = (ubyte)bitbuf->rack;
}
return bitbuf->data-bitbuf->org_data;
}
int bitbuffer_read_flush( bitbuffer *bitbuf )
{
return bitbuf->data-bitbuf->org_data;
}
void bitbuffer_put( bitbuffer *bitbuf, uint data, int bit_count )
{
uint mask;
mask = 1L << ( bit_count - 1 );
while ( mask != 0) {
if ( mask & data ) {
bitbuf->rack |= bitbuf->mask;
}
bitbuf->mask >>= 1;
if ( bitbuf->mask == 0 ) {
*bitbuf->data++=(ubyte)bitbuf->rack;
bitbuf->rack = 0;
bitbuf->mask = 0x80;
}
mask >>= 1;
}
}
uint bitbuffer_get_unsigned( bitbuffer *bitbuf, int bit_count )
{
uint mask;
uint return_value;
mask = 1L << ( bit_count - 1 );
return_value = 0;
while ( mask != 0) {
if ( bitbuf->mask == 0x80 ) {
bitbuf->rack = *bitbuf->data++;
}
if ( bitbuf->rack & bitbuf->mask ) {
return_value |= mask;
}
mask >>= 1;
bitbuf->mask >>= 1;
if ( bitbuf->mask == 0 ) {
bitbuf->mask = 0x80;
}
}
return return_value;
}
int bitbuffer_get_signed( bitbuffer *bitbuf, int bit_count )
{
uint mask;
uint return_value;
mask = 1L << ( bit_count - 1 );
return_value = 0;
while ( mask != 0) {
if ( bitbuf->mask == 0x80 ) {
bitbuf->rack = *bitbuf->data++;
}
if ( bitbuf->rack & bitbuf->mask ) {
return_value |= mask;
}
mask >>= 1;
bitbuf->mask >>= 1;
if ( bitbuf->mask == 0 ) {
bitbuf->mask = 0x80;
}
}
// sign extend return value
return_value <<= (32-bit_count);
return ((int)return_value)>>(32-bit_count);
}
// Packs/unpacks an object position.
// Returns number of bytes read or written.
// #define OO_POS_RET_SIZE 9
int multi_pack_unpack_position( int write, ubyte *data, vector *pos)
{
bitbuffer buf;
bitbuffer_init(&buf,data);
int a, b, c;
if ( write ) {
// Output pos
a = fl2i(pos->xyz.x*105.0f+0.5f);
b = fl2i(pos->xyz.y*105.0f+0.5f);
c = fl2i(pos->xyz.z*105.0f+0.5f);
CAP(a,-8388608,8388607);
CAP(b,-8388608,8388607);
CAP(c,-8388608,8388607);
bitbuffer_put( &buf, (uint)a, 24 );
bitbuffer_put( &buf, (uint)b, 24 );
bitbuffer_put( &buf, (uint)c, 24 );
return bitbuffer_write_flush(&buf);
} else {
// unpack pos
a = bitbuffer_get_signed(&buf,24);
b = bitbuffer_get_signed(&buf,24);
c = bitbuffer_get_signed(&buf,24);
pos->xyz.x = i2fl(a)/105.0f;
pos->xyz.y = i2fl(b)/105.0f;
pos->xyz.z = i2fl(c)/105.0f;
return bitbuffer_read_flush(&buf);
}
}
int degenerate_count = 0;
int non_degenerate_count = 0;
/*
hack = ((ushort)orient->vec.fvec.x * 32767);
memcpy(&hack, &orient->vec.fvec.x, 4);
bitbuffer_put( &buf, hack, 32 );
memcpy(&hack, &orient->vec.fvec.y, 4);
bitbuffer_put( &buf, hack, 32 );
memcpy(&hack, &orient->vec.fvec.z, 4);
bitbuffer_put( &buf, hack, 32 );
memcpy(&hack, &orient->vec.uvec.x, 4);
bitbuffer_put( &buf, hack, 32 );
memcpy(&hack, &orient->vec.uvec.y, 4);
bitbuffer_put( &buf, hack, 32 );
memcpy(&hack, &orient->vec.uvec.z, 4);
bitbuffer_put( &buf, hack, 32 );
memcpy(&hack, &orient->vec.rvec.x, 4);
bitbuffer_put( &buf, hack, 32 );
memcpy(&hack, &orient->vec.rvec.y, 4);
bitbuffer_put( &buf, hack, 32 );
memcpy(&hack, &orient->vec.rvec.z, 4);
bitbuffer_put( &buf, hack, 32 );*/
/*
hack = bitbuffer_get_unsigned(&buf, 32);
memcpy(&orient->vec.fvec.x, &hack, 4);
hack = bitbuffer_get_unsigned(&buf, 32);
memcpy(&orient->vec.fvec.y, &hack, 4);
hack = bitbuffer_get_unsigned(&buf, 32);
memcpy(&orient->vec.fvec.z, &hack, 4);
hack = bitbuffer_get_unsigned(&buf, 32);
memcpy(&orient->vec.uvec.x, &hack, 4);
hack = bitbuffer_get_unsigned(&buf, 32);
memcpy(&orient->vec.uvec.y, &hack, 4);
hack = bitbuffer_get_unsigned(&buf, 32);
memcpy(&orient->vec.uvec.z, &hack, 4);
hack = bitbuffer_get_unsigned(&buf, 32);
memcpy(&orient->vec.rvec.x, &hack, 4);
hack = bitbuffer_get_unsigned(&buf, 32);
memcpy(&orient->vec.rvec.y, &hack, 4);
hack = bitbuffer_get_unsigned(&buf, 32);
memcpy(&orient->vec.rvec.z, &hack, 4);*/
// Packs/unpacks an orientation matrix.
// Returns number of bytes read or written.
// #define OO_ORIENT_RET_SIZE 6
int multi_pack_unpack_orient( int write, ubyte *data, matrix *orient)
{
bitbuffer buf;
bitbuffer_init(&buf, data + 1);
vector rot_axis;
float theta;
int a, b, c, d;
angles ang;
ubyte flag = 0x00;
#define D_SCALE 32768.0f
#define D_MAX_RANGE 32767
#define D_MIN_RANGE -32768
#define N_SCALE 2048.0f
#define N_MAX_RANGE 2047
#define N_MIN_RANGE -2048
if ( write ) {
// degenerate case - send the whole orient matrix
vm_extract_angles_matrix(&ang, orient);
if((ang.h > 3.130) && (ang.h < 3.150)){
degenerate_count++;
flag = 0xff;
// stuff it
a = fl2i(orient->vec.fvec.xyz.x * D_SCALE);
CAP(a, D_MIN_RANGE, D_MAX_RANGE);
bitbuffer_put( &buf, a, 16 );
a = fl2i(orient->vec.fvec.xyz.y * D_SCALE);
CAP(a, D_MIN_RANGE, D_MAX_RANGE);
bitbuffer_put( &buf, a, 16 );
a = fl2i(orient->vec.fvec.xyz.z * D_SCALE);
CAP(a, D_MIN_RANGE, D_MAX_RANGE);
bitbuffer_put( &buf, a, 16 );
a = fl2i(orient->vec.uvec.xyz.x * D_SCALE);
CAP(a, D_MIN_RANGE, D_MAX_RANGE);
bitbuffer_put( &buf, a, 16 );
a = fl2i(orient->vec.uvec.xyz.y * D_SCALE);
CAP(a, D_MIN_RANGE, D_MAX_RANGE);
bitbuffer_put( &buf, a, 16 );
a = fl2i(orient->vec.uvec.xyz.z * D_SCALE);
CAP(a, D_MIN_RANGE, D_MAX_RANGE);
bitbuffer_put( &buf, a, 16 );
a = fl2i(orient->vec.rvec.xyz.x * D_SCALE);
CAP(a, D_MIN_RANGE, D_MAX_RANGE);
bitbuffer_put( &buf, a, 16 );
a = fl2i(orient->vec.rvec.xyz.y * D_SCALE);
CAP(a, D_MIN_RANGE, D_MAX_RANGE);
bitbuffer_put( &buf, a, 16 );
a = fl2i(orient->vec.rvec.xyz.z * D_SCALE);
CAP(a, D_MIN_RANGE, D_MAX_RANGE);
bitbuffer_put( &buf, a, 16 );
} else {
non_degenerate_count++;
vm_matrix_to_rot_axis_and_angle(orient, &theta, &rot_axis);
// Have theta, which is an angle between 0 and PI.
// Convert it to be between -1.0f and 1.0f
theta = theta*2.0f/PI-1.0f;
// -1 to 1
a = fl2i(rot_axis.xyz.x*N_SCALE);
b = fl2i(rot_axis.xyz.y*N_SCALE);
c = fl2i(rot_axis.xyz.z*N_SCALE);
d = fl2i(theta*N_SCALE);
CAP(a, N_MIN_RANGE, N_MAX_RANGE);
CAP(b, N_MIN_RANGE, N_MAX_RANGE);
CAP(c, N_MIN_RANGE, N_MAX_RANGE);
CAP(d, N_MIN_RANGE, N_MAX_RANGE);
bitbuffer_put( &buf, (uint)a, 12 );
bitbuffer_put( &buf, (uint)b, 12 );
bitbuffer_put( &buf, (uint)c, 12 );
bitbuffer_put( &buf, (uint)d, 12 );
}
// flag for degenerate case
data[0] = flag;
return bitbuffer_write_flush(&buf) + 1;
} else {
flag = data[0];
// degenerate
if(flag){
a = bitbuffer_get_signed(&buf, 16);
orient->vec.fvec.xyz.x = i2fl(a) / D_SCALE;
a = bitbuffer_get_signed(&buf, 16);
orient->vec.fvec.xyz.y = i2fl(a) / D_SCALE;
a = bitbuffer_get_signed(&buf, 16);
orient->vec.fvec.xyz.z = i2fl(a) / D_SCALE;
a = bitbuffer_get_signed(&buf, 16);
orient->vec.uvec.xyz.x = i2fl(a) / D_SCALE;
a = bitbuffer_get_signed(&buf, 16);
orient->vec.uvec.xyz.y = i2fl(a) / D_SCALE;
a = bitbuffer_get_signed(&buf, 16);
orient->vec.uvec.xyz.z = i2fl(a) / D_SCALE;
a = bitbuffer_get_signed(&buf, 16);
orient->vec.rvec.xyz.x = i2fl(a) / D_SCALE;
a = bitbuffer_get_signed(&buf, 16);
orient->vec.rvec.xyz.y = i2fl(a) / D_SCALE;
a = bitbuffer_get_signed(&buf, 16);
orient->vec.rvec.xyz.z = i2fl(a) / D_SCALE;
} else {
a = bitbuffer_get_signed(&buf,12);
b = bitbuffer_get_signed(&buf,12);
c = bitbuffer_get_signed(&buf,12);
d = bitbuffer_get_signed(&buf,12);
// special case
rot_axis.xyz.x = i2fl(a)/N_SCALE;
rot_axis.xyz.y = i2fl(b)/N_SCALE;
rot_axis.xyz.z = i2fl(c)/N_SCALE;
theta = i2fl(d)/N_SCALE;
// Convert theta back to range 0-PI
theta = (theta+1.0f)*PI/2.0f;
vm_quaternion_rotate(orient, theta, &rot_axis);
vm_orthogonalize_matrix(orient);
}
return bitbuffer_read_flush(&buf) + 1;
}
}
// Packs/unpacks an orientation matrix.
// Returns number of bytes read or written.
// #define OO_ORIENT_RET_SIZE 6
/*
int multi_pack_unpack_orient( int write, ubyte *data, matrix *orient)
{
bitbuffer buf;
bitbuffer_init(&buf,data);
vector rot_axis;
float theta;
int a, b, c, d;
if ( write ) {
// if our heading is 3.14 radians
//angles ang;
//vm_extract_angles_matrix(&a, orient);
//if((ang.h > 3.1300) && (ang.h < 3.1500)){
//} else {
util_matrix_to_rot_axis_and_angle(orient, &theta, &rot_axis);
// Have theta, which is an angle between 0 and PI.
// Convert it to be between -1.0f and 1.0f
theta = theta*2.0f/PI-1.0f;
#define SCALE 2048.0f
#define MAX_RANGE 2047
#define MIN_RANGE -2048
// -1 to 1
a = fl2i(rot_axis.x*SCALE);
b = fl2i(rot_axis.y*SCALE);
c = fl2i(rot_axis.z*SCALE);
d = fl2i(theta*SCALE);
CAP(a,MIN_RANGE,MAX_RANGE);
CAP(b,MIN_RANGE,MAX_RANGE);
CAP(c,MIN_RANGE,MAX_RANGE);
CAP(d,MIN_RANGE,MAX_RANGE);
//}
bitbuffer_put( &buf, (uint)a, 12 );
bitbuffer_put( &buf, (uint)b, 12 );
bitbuffer_put( &buf, (uint)c, 12 );
bitbuffer_put( &buf, (uint)d, 12 );
return bitbuffer_write_flush(&buf);
} else {
a = bitbuffer_get_signed(&buf,12);
b = bitbuffer_get_signed(&buf,12);
c = bitbuffer_get_signed(&buf,12);
d = bitbuffer_get_signed(&buf,12);
// special case
rot_axis.x = i2fl(a)/SCALE;
rot_axis.y = i2fl(b)/SCALE;
rot_axis.z = i2fl(c)/SCALE;
theta = i2fl(d)/SCALE;
// Convert theta back to range 0-PI
theta = (theta+1.0f)*PI/2.0f;
vm_quaternion_rotate(orient, theta, &rot_axis);
vm_orthogonalize_matrix(orient);
return bitbuffer_read_flush(&buf);
}
}
*/
// Packs/unpacks velocity
// Returns number of bytes read or written.
// #define OO_VEL_RET_SIZE 4
int multi_pack_unpack_vel( int write, ubyte *data, matrix *orient, vector *pos, physics_info *pi)
{
bitbuffer buf;
bitbuffer_init(&buf,data);
int a, b, c;
float r, u, f;
if ( write ) {
// output velocity
r = vm_vec_dot( &orient->vec.rvec, &pi->vel );
u = vm_vec_dot( &orient->vec.uvec, &pi->vel );
f = vm_vec_dot( &orient->vec.fvec, &pi->vel );
a = fl2i(r * 0.5f);
b = fl2i(u * 0.5f);
c = fl2i(f * 0.5f);
CAP(a,-512,511);
CAP(b,-512,511);
CAP(c,-512,511);
bitbuffer_put( &buf, (uint)a, 10 );
bitbuffer_put( &buf, (uint)b, 10 );
bitbuffer_put( &buf, (uint)c, 10 );
return bitbuffer_write_flush(&buf);
} else {
// unpack velocity
float r, u, f;
a = bitbuffer_get_signed(&buf,10);
b = bitbuffer_get_signed(&buf,10);
c = bitbuffer_get_signed(&buf,10);
r = i2fl(a)/0.5f;
u = i2fl(b)/0.5f;
f = i2fl(c)/0.5f;
// Convert into world coordinates
vm_vec_zero(&pi->vel);
vm_vec_scale_add2( &pi->vel, &orient->vec.rvec, r );
vm_vec_scale_add2( &pi->vel, &orient->vec.uvec, u );
vm_vec_scale_add2( &pi->vel, &orient->vec.fvec, f );
return bitbuffer_read_flush(&buf);
}
}
// Packs/unpacks desired_velocity
// Returns number of bytes read or written.
// #define OO_DESIRED_VEL_RET_SIZE 3
int multi_pack_unpack_desired_vel( int write, ubyte *data, matrix *orient, vector *pos, physics_info *pi, ship_info *sip)
{
bitbuffer buf;
bitbuffer_init(&buf,data);
int a;
vector max_vel;
float r,u,f;
int fields = 0;
max_vel.xyz.x = max( sip->max_vel.xyz.x, sip->afterburner_max_vel.xyz.x );
max_vel.xyz.y = max( sip->max_vel.xyz.y, sip->afterburner_max_vel.xyz.y );
max_vel.xyz.z = max( sip->max_vel.xyz.z, sip->afterburner_max_vel.xyz.z );
if ( write ) {
// Find desired vel in local coordinates
// Velocity can be from -1024 to 1024
// bitfields for each value
if(max_vel.xyz.x > 0.0f){
fields |= (1<<0);
}
if(max_vel.xyz.y > 0.0f){
fields |= (1<<1);
}
if(max_vel.xyz.z > 0.0f){
fields |= (1<<2);
}
// fields = sip - Ship_info;
bitbuffer_put(&buf, (uint)fields, 8);
r = vm_vec_dot( &orient->vec.rvec, &pi->desired_vel );
u = vm_vec_dot( &orient->vec.uvec, &pi->desired_vel );
f = vm_vec_dot( &orient->vec.fvec, &pi->desired_vel );
if ( max_vel.xyz.x > 0.0f ) {
r = r / max_vel.xyz.x;
a = fl2i( r * 128.0f );
CAP(a,-128, 127 );
bitbuffer_put( &buf, (uint)a, 8 );
}
if ( max_vel.xyz.y > 0.0f ) {
u = u / max_vel.xyz.y;
a = fl2i( u * 128.0f );
CAP(a,-128, 127 );
bitbuffer_put( &buf, (uint)a, 8 );
}
if ( max_vel.xyz.z > 0.0f ) {
f = f / max_vel.xyz.z;
a = fl2i( f * 128.0f );
CAP(a,-128, 127 );
bitbuffer_put( &buf, (uint)a, 8 );
}
return bitbuffer_write_flush(&buf);
} else {
// Find desired vel in local coordinates
// Velocity can be from -1024 to 1024
// get the fields bitbuffer
fields = bitbuffer_get_signed(&buf, 8);
if ( fields & (1<<0) ) {
a = bitbuffer_get_signed(&buf,8);
r = i2fl(a)/128.0f;
} else {
r = 0.0f;
}
if ( fields & (1<<1) ) {
a = bitbuffer_get_signed(&buf,8);
u = i2fl(a)/128.0f;
} else {
u = 0.0f;
}
if ( fields & (1<<2) ) {
a = bitbuffer_get_signed(&buf,8);
f = i2fl(a)/128.0f;
} else {
f = 0.0f;
}
// Convert into world coordinates
vm_vec_zero(&pi->vel);
vm_vec_scale_add2( &pi->desired_vel, &orient->vec.rvec, r*max_vel.xyz.x );
vm_vec_scale_add2( &pi->desired_vel, &orient->vec.uvec, u*max_vel.xyz.y );
vm_vec_scale_add2( &pi->desired_vel, &orient->vec.fvec, f*max_vel.xyz.z );
return bitbuffer_read_flush(&buf);
}
}
// Packs/unpacks rotational velocity
// Returns number of bytes read or written.
// #define OO_ROTVEL_RET_SIZE 4
int multi_pack_unpack_rotvel( int write, ubyte *data, matrix *orient, vector *pos, physics_info *pi)
{
bitbuffer buf;
bitbuffer_init(&buf,data);
int a, b, c;
if ( write ) {
// output rotational velocity
a = fl2i(pi->rotvel.xyz.x*32.0f);
b = fl2i(pi->rotvel.xyz.y*32.0f);
c = fl2i(pi->rotvel.xyz.z*32.0f);
CAP(a,-512,511);
CAP(b,-512,511);
CAP(c,-512,511);
bitbuffer_put( &buf, (uint)a, 10 );
bitbuffer_put( &buf, (uint)b, 10 );
bitbuffer_put( &buf, (uint)c, 10 );
return bitbuffer_write_flush(&buf);
} else {
// unpack rotational velocity
a = bitbuffer_get_signed(&buf,10);
b = bitbuffer_get_signed(&buf,10);
c = bitbuffer_get_signed(&buf,10);
pi->rotvel.xyz.x = i2fl(a)/32.0f;
pi->rotvel.xyz.y = i2fl(b)/32.0f;
pi->rotvel.xyz.z = i2fl(c)/32.0f;
return bitbuffer_read_flush(&buf);
}
}
// Packs/unpacks desired rotvel
// Returns number of bytes read or written.
// #define OO_DESIRED_ROTVEL_RET_SIZE 3
int multi_pack_unpack_desired_rotvel( int write, ubyte *data, matrix *orient, vector *pos, physics_info *pi, ship_info *sip)
{
bitbuffer buf;
int fields = 0;
bitbuffer_init(&buf,data);
int a;
float r,u,f;
if ( write ) {
// use ship_info values for max_rotvel instead of taking it from physics info
// bitfields for each value
if(sip->max_rotvel.xyz.x > 0.0f){
fields |= (1<<0);
}
if(sip->max_rotvel.xyz.y > 0.0f){
fields |= (1<<1);
}
if(sip->max_rotvel.xyz.z > 0.0f){
fields |= (1<<2);
}
bitbuffer_put(&buf, (uint)fields, 8);
// output desired rotational velocity as a percent of max
if ( sip->max_rotvel.xyz.x > 0.0f ) {
a = fl2i( pi->desired_rotvel.xyz.x*128.0f / sip->max_rotvel.xyz.x );
CAP(a,-128, 127 );
bitbuffer_put( &buf, (uint)a, 8 );
}
if ( sip->max_rotvel.xyz.y > 0.0f ) {
a = fl2i( pi->desired_rotvel.xyz.y*128.0f / sip->max_rotvel.xyz.y );
CAP(a,-128, 127 );
bitbuffer_put( &buf, (uint)a, 8 );
}
if ( sip->max_rotvel.xyz.z > 0.0f ) {
a = fl2i( pi->desired_rotvel.xyz.z*128.0f / sip->max_rotvel.xyz.z );
CAP(a,-128, 127 );
bitbuffer_put( &buf, (uint)a, 8 );
}
return bitbuffer_write_flush(&buf);
} else {
fields = bitbuffer_get_signed(&buf, 8);
// unpack desired rotational velocity
if ( fields & (1<<0) ) {
a = bitbuffer_get_signed(&buf,8);
r = i2fl(a)/128.0f;
} else {
r = 0.0f;
}
if ( fields & (1<<1) ) {
a = bitbuffer_get_signed(&buf,8);
u = i2fl(a)/128.0f;
} else {
u = 0.0f;
}
if ( fields & (1<<2) ) {
a = bitbuffer_get_signed(&buf,8);
f = i2fl(a)/128.0f;
} else {
f = 0.0f;
}
pi->desired_rotvel.xyz.x = r*sip->max_rotvel.xyz.x;
pi->desired_rotvel.xyz.y = u*sip->max_rotvel.xyz.y;
pi->desired_rotvel.xyz.z = f*sip->max_rotvel.xyz.z;
return bitbuffer_read_flush(&buf);
}
}
#pragma optimize("", on)
#endif // ifndef NO_NETWORK
| [
"[email protected]"
]
| [
[
[
1,
4573
]
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.