blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 9
125
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
4
| license_type
stringclasses 2
values | repo_name
stringlengths 12
47
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 1
value | visit_date
stringlengths 19
19
| revision_date
stringlengths 19
19
| committer_date
stringlengths 19
19
| github_id
int64 178k
175M
⌀ | star_events_count
int64 0
27
| fork_events_count
int64 0
9
| gha_license_id
null | gha_event_created_at
stringclasses 1
value | gha_created_at
stringclasses 1
value | gha_language
null | src_encoding
stringclasses 5
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 165
115k
| extension
stringclasses 7
values | content
stringlengths 165
115k
| authors
sequencelengths 1
4
| author_lines
sequencelengths 1
4
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ee314adc625320f5d9816b1570c675c1fe31b614 | 47f89380f778b6ee8311678e48970ea710e8c1a8 | /atask/Repair.h | 6b911bd6b6c802d679fbd160e8cb3032f8f21c47 | [] | no_license | hoijui/E323AI | f53a0fb388b67557fc92f38835343a85ef01135a | c4fcac72b77cff352350326c01ecab2d0ba9b388 | refs/heads/master | 2021-01-17 23:26:30 | 2010-12-17 00:35:34 | 2010-12-17 00:35:34 | 358,032 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 595 | h | #ifndef E323_TASKREPAIR_H
#define E323_TASKREPAIR_H
#include "../ATask.h"
class UnitType;
struct RepairTask: public ATask {
RepairTask(AIClasses* _ai): ATask(_ai) { t = TASK_REPAIR; }
RepairTask(AIClasses* _ai, int target, CGroup& group);
/* build type to string */
static std::map<buildType, std::string> buildStr;
bool repairing;
int target;
/* overloaded */
void onUpdate();
/* overloaded */
bool onValidate();
/* overloaded */
void toStream(std::ostream& out) const;
/* overloaded */
void onUnitDestroyed(int uid, int attacker);
};
#endif
| [
"slspam@land.ru"
] | [
[
[
1,
29
]
]
] |
549af41db9a65d7fe1acf52e5054a2bf629b70d4 | 21da454a8f032d6ad63ca9460656c1e04440310e | /test/utest/StringTest.cpp | 85fb41c510728e6ec167722582db6d8c20583906 | [] | no_license | merezhang/wcpp | d9879ffb103513a6b58560102ec565b9dc5855dd | e22eb48ea2dd9eda5cd437960dd95074774b70b0 | refs/heads/master | 2021-01-10 06:29:42 | 2009-08-31 09:20:31 | 2009-08-31 09:20:31 | 46,339,619 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,030 | cpp | #include "StringTest.h"
#include <wcpp/lang/wscUUID.h>
#include <wcpp/lang/wscSystem.h>
#include <wcpp/lang/wscLong.h>
#include <wcpp/lang/wscThrowable.h>
StringTest::StringTest(void)
{
}
StringTest::~StringTest(void)
{
}
ws_result StringTest::doTest(void)
{
trace( "========================================\n" );
trace( "case:StringTest - begin\n" );
test_wsString();
test_wsLong_ToString();
test_wscUUID_ToString();
trace( "case:StringTest - end\n" );
trace( "========================================\n" );
return ws_result( WS_RLT_SUCCESS );
}
void StringTest::test_wscUUID_ToString(void)
{
trace( " -------------------------------- \n" );
trace( "func:test_wscUUID_ToString - begin\n" );
{
ws_ptr<wsiString> str1, str2;
wscUUID::ToString( wsiObject::sIID.uuid, &str1 );
ws_uuid uuid;
wscUUID::ParseUUID( str1, uuid );
wscUUID::ToString( uuid, &str2 );
trace( "wsiObject::sIID : " ); trace( "{3F45A92B-A7D5-4d93-946C-373E56A8C17B}" ); trace( "\n" );
trace( "wsiObject::sIID ToString : " ); trace( str1->GetBuffer() ); trace( "\n" );
trace( "wsiObject::sIID ParseUUID : " ); trace( str2->GetBuffer() ); trace( "\n" );
}
ws_ptr<wsiString> str1,str2;
wscUUID::ToString( wsiSystem::sIID.uuid, &str1 );
ws_uuid uuid;
wscUUID::ParseUUID( str2, uuid );
wscUUID::ToString( uuid, &str2 );
trace( "wsiSystem::sIID : " ); trace( "{FAC4AD98-7554-4561-AF17-9A5ADB66AD30}" ); trace( "\n" );
trace( "wsiSystem::sIID ToString : " ); trace( str1->GetBuffer() ); trace( "\n" );
trace( "wsiSystem::sIID ParseUUID : " ); trace( str2->GetBuffer() ); trace( "\n" );
trace( "func:test_wscUUID_ToString - end\n" );
trace( " -------------------------------- \n" );
}
void StringTest::test_wsLong_ToString(void)
{
trace( " -------------------------------- \n" );
trace( "func:test_wsLong_ToString - begin\n" );
const int len = 8;
ws_long values[len] =
{
-1,
0,
1,
2147483647,
-2147483647,
2147483647,
// -2147483648,
};
ws_ptr<wsiString> str;
trace( "ws_long [wsString]\n" );
for (int i=0; i<len; i++) {
wscLong::ToString( values[i], &str );
trace( values[i] );
trace( " [" );
trace( str->GetBuffer() );
trace( "]\n" );
}
trace( "func:test_wsLong_ToString - end\n" );
trace( " -------------------------------- \n" );
}
void StringTest::test_wsString(void)
{
trace( " -------------------------------- \n" );
trace( "func:test_wsString - begin\n" );
ws_str str1;
ws_str str2( static_cast<wsiString*>(WS_NULL) );
ws_str str3( "" );
ws_str str4( "hello" );
str1 = str4;
str2 = str4;
str3 = str4;
str4 = "";
str3 = str4;
str4.SetString( 0, 0 );
str3 = "abcdefg hijk lmn opq rst uvw xyz";
str4 = "hp";
trace( "func:test_wsString - end\n" );
trace( " -------------------------------- \n" );
}
| [
"xukun0217@98f29a9a-77f1-11de-91f8-ab615253d9e8"
] | [
[
[
1,
132
]
]
] |
ca0c3b13465618bea0dfd72c097003afb2d6d543 | dae66863ac441ab98adbd2d6dc2cabece7ba90be | /examples/flexrun/ASWorkFlexRun.h | aad3385447c35be6ad42d6653b4001fb392c9140 | [] | no_license | bitcrystal/flexcppbridge | 2485e360f47f8d8d124e1d7af5237f7e30dd1980 | 474c17cfa271a9d260be6afb2496785e69e72ead | refs/heads/master | 2021-01-10 14:14:30 | 2008-11-11 06:11:34 | 2008-11-11 06:11:34 | 48,993,836 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,045 | h | /*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the Flex C++ Bridge.
*
* The Initial Developer of the Original Code is
* Anirudh Sasikumar (http://anirudhs.chaosnet.org/).
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
*/
#pragma once
#include "aswork.h"
class CASWorkFlexRun :
public CASWork
{
protected:
virtual void Worker();
public:
CASWorkFlexRun(void);
virtual ~CASWorkFlexRun(void);
virtual CASWork* Clone();
};
| [
"anirudhsasikumar@1c1c0844-4f48-0410-9872-0bebc774e022"
] | [
[
[
1,
37
]
]
] |
c4ab3dfaef1a8239e53b2ee0d4b5f79eeff19733 | 4e8581b6eaaabdd58b1151201d64b45c7147dac7 | /src/Direction.h | 4222efa696a82a056182af970d0fbd7670521d4c | [] | no_license | charmingbrew/bioinformatics-mscd-2011 | c4a390bf25d2197d4e912d7976619cb02c666587 | 04d81d0f05001d3ed82911459cff6dddb3c7f252 | refs/heads/master | 2020-05-09 12:56:08 | 2011-05-17 05:55:14 | 2011-05-17 05:55:14 | 33,334,714 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,025 | h | class Node;
/**
* @file Direction.h
* @class Direction
* @brief Directions in a guide tree node.
* A direction contains a direction (as in left
* or right) OR a direction.
* A direction can only have three states:
* -# Empty: A node or a sequence can be placed.
* -# Sequence: Only A sequence can be contained.
* -# Node: Only a branch down the tree.
* Never can it have both a sequence and a branch.
* These should members should be called from the
* Node Object.
*/
#ifndef _DIRECTION_H
#define _DIRECTION_H
#include "Sequence.h"
class Direction
{
private:
Node * next;
Sequence * seq;
public:
Direction();
Direction(Sequence *seq);
Direction(Node *n);
Sequence *GetSequence();
void SetSequence(Sequence *s);
Node *GetNode();
void SetNextNode(Node *next);
void SetScore();
/// Checks for an empty Direction Object
bool isOpen();
};
#endif // _DIRECTION_H
| [
"jnnyboy570@gmail.com@e9cc6749-363d-4b58-5071-845f21bc09f4",
"millardfillmoreesquire@e9cc6749-363d-4b58-5071-845f21bc09f4"
] | [
[
[
1,
2
],
[
4,
39
]
],
[
[
3,
3
]
]
] |
e3d9c3f1e076ae554af9d032aa9628c1aa5df376 | 0f40e36dc65b58cc3c04022cf215c77ae31965a8 | /src/apps/vis/writer/vis_writer_factory.cpp | f17a2d9662492c70428061ca51440dccfd7d2525 | [
"MIT",
"BSD-3-Clause"
] | permissive | venkatarajasekhar/shawn-1 | 08e6cd4cf9f39a8962c1514aa17b294565e849f8 | d36c90dd88f8460e89731c873bb71fb97da85e82 | refs/heads/master | 2020-06-26 18:19:01 | 2010-10-26 17:40:48 | 2010-10-26 17:40:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,323 | cpp | /************************************************************************
** This file is part of the network simulator Shawn. **
** Copyright (C) 2004-2007 by the SwarmNet (www.swarmnet.de) project **
** Shawn is free software; you can redistribute it and/or modify it **
** under the terms of the BSD License. Refer to the shawn-licence.txt **
** file in the root of the Shawn source tree for further details. **
************************************************************************/
#include "../buildfiles/_apps_enable_cmake.h"
#ifdef ENABLE_VIS
#include "apps/vis/writer/vis_writer_factory.h"
#include "apps/vis/writer/vis_writer_keeper.h"
#include "apps/vis/writer/vis_png_writer.h"
#include "apps/vis/writer/vis_pdf_writer.h"
namespace vis
{
WriterFactory::
WriterFactory( void )
{}
WriterFactory::~WriterFactory()
{}
// ----------------------------------------------------------------------
std::string
WriterFactory::
name( void )
const throw()
{
return "vis_writer";
}
// ----------------------------------------------------------------------
std::string
WriterFactory::
description( void )
const throw()
{
return "Vis filewriter objects";
}
}
#endif
| [
"csinger08@users.sourceforge.net"
] | [
[
[
1,
44
]
]
] |
59cfee9693984396770fc2f0acd89767985b10b0 | 188058ec6dbe8b1a74bf584ecfa7843be560d2e5 | /GodDK/io/InputStream.cxx | e9fb7b8a2f429b4ea12c964b1cf68b8ad74d9c23 | [] | no_license | mason105/red5cpp | 636e82c660942e2b39c4bfebc63175c8539f7df0 | fcf1152cb0a31560af397f24a46b8402e854536e | refs/heads/master | 2021-01-10 07:21:31 | 2007-08-23 06:29:17 | 2007-08-23 06:29:17 | 36,223,621 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,429 | cxx |
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "io/InputStream.h"
#include "lang/String.h"
using goddk::lang::String;
#include "lang/NullPointerException.h"
using goddk::lang::NullPointerException;
using namespace goddk::io;
jint InputStream::available() throw (IOExceptionPtr)
{
return 0;
}
void InputStream::close() throw (IOExceptionPtr)
{
}
void InputStream::mark(jint readlimit) throw ()
{
}
bool InputStream::markSupported() throw ()
{
return false;
}
jint InputStream::read(bytearray& b) throw (IOExceptionPtr)
{
return read(b.data(), 0, b.size());
}
jint InputStream::read(byte* data, jint offset, jint length) throw (IOExceptionPtr)
{
if (!data)
THROWEXCEPTIONPTR(NullPointerException)
jint b = read();
if (b < 0)
return -1;
data[offset] = (byte) b;
jint i = 1;
try
{
while (i < length)
{
b = read();
if (b < 0)
break;
data[offset+i++] = (byte) b;
}
}
catch (IOException&)
{
// ignore
}
return i;
}
jint InputStream::skip(jint n) throw (IOExceptionPtr)
{
jint remaining = n;
byte skip[2048];
while (remaining > 0)
{
jint rc = read(skip, 0, remaining > 2048 ? 2048 : remaining);
if (rc < 0)
break;
remaining -= rc;
}
return n - remaining;
}
void InputStream::reset() throw (IOExceptionPtr)
{
THROWEXCEPTIONPTR1(IOException,"reset not supported");
}
| [
"soaris@46205fef-a337-0410-8429-7db05d171fc8"
] | [
[
[
1,
87
]
]
] |
785a2968acee3a5b3ac23300a3b0314227b2f999 | 61fc00b53ce93f09a6a586a48ae9e484b74b6655 | /src/tool/src/wrapper/chemical/wrapper_chemicalcmd_to_avoaction.cpp | c37769e8310891c503fa776faf653c6aa0dbd82b | [] | no_license | mickaelgadroy/wmavo | 4162c5c7c8d9082060be91e774893e9b2b23099b | db4a986d345d0792991d0e3a3d728a4905362a26 | refs/heads/master | 2021-01-04 22:33:25 | 2011-11-04 10:44:50 | 2011-11-04 10:44:50 | 1,381,704 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 59,177 | cpp |
/*******************************************************************************
Copyright (C) 2010,2011 Mickael Gadroy, University of Reims Champagne-Ardenne (Fr)
Project managers: Eric Henon and Michael Krajecki
Financial support: Region Champagne-Ardenne (Fr)
Some portions :
Copyright (C) 2007-2009 Marcus D. Hanwell
Copyright (C) 2006,2008,2009 Geoffrey R. Hutchison
Copyright (C) 2006,2007 Donald Ephraim Curtis
Copyright (C) 2008,2009 Tim Vandermeersch
This file is part of WmAvo (WiiChem project)
WmAvo - Integrate the Wiimote and the Nunchuk in Avogadro software for the
handling of the atoms and the camera.
For more informations, see the README file.
WmAvo 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.
WmAvo 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 WmAvo. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/
#include "wrapper_chemicalcmd_to_avoaction.h"
#include "wmtool.h"
#include "moleculemanipulation.h"
#include "contextmenu_to_avoaction.h"
namespace Avogadro
{
const Eigen::Vector3d WrapperChemicalCmdToAvoAction::m_vect3d0(Eigen::Vector3d(0., 0., 0.)) ;
Eigen::Transform3d WrapperChemicalCmdToAvoAction::m_transf3d0 ;
const QPoint WrapperChemicalCmdToAvoAction::m_qpoint0(QPoint(0,0)) ;
const double WrapperChemicalCmdToAvoAction::m_PI180=M_PI/180.0 ;
const double WrapperChemicalCmdToAvoAction::m_180PI=180.0/M_PI ;
WrapperChemicalCmdToAvoAction::WrapperChemicalCmdToAvoAction
( GLWidget *widget, WITD::ChemicalWrap *chemWrap, InputDevice::WmDevice *wmdev )
: m_widget(widget), m_moleculeManip(NULL),
m_wmDev(wmdev),
m_isCalculDistDiedre(false),
m_isMoveAtom(false), m_tmpBarycenter(m_vect3d0),
m_isRenderRect(false), m_rectP1(m_qpoint0), m_rectP2(m_qpoint0),
m_needAnUpdateMore(false),
m_isAtomDraw(false), m_isBondOrder(false),
m_drawBeginAtom(false), m_drawCurrentAtom(false), m_drawBond(false),
m_hasAddedBeginAtom(false), m_hasAddedCurAtom(false), m_hasAddedBond(false),
m_beginPosDraw(m_vect3d0), m_curPosDraw(m_vect3d0),
m_lastCursor(m_qpoint0),
m_beginAtomDraw(NULL), m_curAtomDraw(NULL), m_bondDraw(NULL),
m_timeFirst(0), m_timeSecond(0), m_canDrawOther(false)
{
/// Initiate the objects.
m_moleculeManip = new MoleculeManipulation( widget->molecule() ) ;
m_contextMenu = new ContextMenuToAvoAction( widget, m_moleculeManip, chemWrap ) ;
m_transf3d0.matrix().setIdentity() ;
/// Initiate some attributs to realize mouse simulations.
m_testEventPress = false ;
m_p = new QPoint(1,1) ;
m_me1 = new QMouseEvent(QEvent::MouseButtonPress, *m_p, Qt::LeftButton, Qt::NoButton, Qt::NoModifier) ;
m_me2 = new QMouseEvent(QEvent::MouseMove, *m_p, Qt::NoButton, Qt::LeftButton, Qt::NoModifier) ;
m_me3 = new QMouseEvent(QEvent::MouseButtonRelease, *m_p, Qt::LeftButton, Qt::NoButton, Qt::NoModifier) ;
m_time.start() ;
m_nbUpdate1 = new WIWO<unsigned int>(20) ;
m_nbUpdate2 = new WIWO<unsigned int>(20) ;
m_nbUpdate3 = new WIWO<unsigned int>(20) ;
}
WrapperChemicalCmdToAvoAction::~WrapperChemicalCmdToAvoAction()
{
if( m_me1 != NULL ){ delete( m_me1 ) ; m_me1=NULL ; }
if( m_me2 != NULL ){ delete( m_me2 ) ; m_me2=NULL ; }
if( m_me3 != NULL ){ delete( m_me3 ) ; m_me3=NULL ; }
if( m_p != NULL ){ delete( m_p ) ; m_p=NULL ; }
if( m_nbUpdate1 != NULL ){ delete( m_nbUpdate1 ) ; m_nbUpdate1=NULL ; }
if( m_nbUpdate2 != NULL ){ delete( m_nbUpdate2 ) ; m_nbUpdate2=NULL ; }
if( m_nbUpdate3 != NULL ){ delete( m_nbUpdate3 ) ; m_nbUpdate3=NULL ; }
}
MoleculeManipulation* WrapperChemicalCmdToAvoAction::getMoleculeManip()
{
return m_moleculeManip ;
}
ContextMenuToAvoAction* WrapperChemicalCmdToAvoAction::getContextMenu()
{
return m_contextMenu ;
}
/**
* Transform a wrapper action to an Avogadro action.
* @param wmData All Wiimote data get.
*/
void WrapperChemicalCmdToAvoAction::transformWrapperActionToAvoAction( WITD::ChemicalWrapData_from *data )
{
WITD::ChemicalWrapData_from::wrapperActions_t wa ;
WITD::ChemicalWrapData_from::positionCamera_t pc ;
WITD::ChemicalWrapData_from::positionPointed_t pp ;
//bool upWa=data->getWrapperAction( wa ) ;
//bool upPc=data->getPositionCamera( pc ) ;
//bool upPp=data->getPositionPointed( pp ) ;
wa = data->getWrapperAction() ;
pc = data->getPositionCamera() ;
pp = data->getPositionPointed() ;
QPoint posCursor=pp.posCursor ;
int state=wa.actionsWrapper ;
Eigen::Vector3d pos3dCurrent=pp.pos3dCur ;
Eigen::Vector3d pos3dLast=pp.pos3dLast ;
double rotCamAxeXDeg=pc.angleRotateDegree[0] ;
double rotCamAxeYDeg=pc.angleRotateDegree[1] ;
double distCamXTranslate=pc.distanceTranslate[0] ;
double distCamYTranslate=pc.distanceTranslate[1] ;
double distCamZoom=pc.distanceTranslate[2] ;
//cout << nbDotsDetected << " " << nbSourcesDetected << " " << distBetweenSource << endl ;
// Adjustment for the rotation of atoms.
if( WMAVO_IS2(state,WMAVO_CAM_ROTATE_BYWM) && m_widget->selectedPrimitives().size()>=2 )
{ // Disable the context menu action.
WMAVO_SETOFF2( state, WMAVO_CAM_ROTATE_BYWM ) ;
WMAVO_SETON2( state, WMAVO_ATOM_MOVE ) ;
WMAVO_SETON2( state, WMAVO_ATOM_ROTATE ) ;
}
const Eigen::Vector3d pointRef=m_moleculeManip->getBarycenterMolecule() ;
transformWrapperActionToMoveAtom( state, pointRef, pos3dCurrent, pos3dLast, rotCamAxeXDeg, rotCamAxeYDeg ) ;
transformWrapperActionToMoveMouse( state, posCursor ) ;
transformWrapperActionToSelectAtom( state, posCursor ) ;
transformWrapperActionToCreateAtomBond( state, pointRef, posCursor ) ;
transformWrapperActionToDeleteAllAtomBond( state ) ;
transformWrapperActionToRemoveAtomBond( state, posCursor ) ;
transformWrapperActionToRotateCamera( state, pointRef, rotCamAxeXDeg, rotCamAxeYDeg ) ;
transformWrapperActionToTranslateCamera( state, pointRef, distCamXTranslate, distCamYTranslate ) ;
transformWrapperActionToZoomCamera( state, pointRef, distCamZoom ) ;
transformWrapperActionToInitiateCamera( state, pointRef ) ;
transformWrapperActionToSaturateAtoms( state ) ;
transformWrapperActionToUseContextMenu( state, posCursor ) ;
transformWrapperActionToAvoUpdate( state ) ;
}
void WrapperChemicalCmdToAvoAction::transformWrapperActionToAvoUpdate( int state )
{
//
// Update Avogadro to see modification.
updateForAvoActions1( state ) ;
updateForAvoActions2( state ) ;
updateForAvoActions3( state ) ;
}
/**
* Transform a wrapper action to an Avogadro action : move the mouse cursor.
* @param wmavoAction All actions ask by the wrapper
* @param posCursor The new position of the mouse cursor
*/
void WrapperChemicalCmdToAvoAction::transformWrapperActionToMoveMouse( int wmavoAction, const QPoint& posCursor )
{
if( WMAVO_IS2(wmavoAction,WMAVO_CURSOR_MOVE) || WMAVO_IS2(wmavoAction,WMAVO_CREATE) )
{
//cout << "WrapperChemicalCmdToAvoAction::transformWrapperActionToMoveMouse" << endl ;
QCursor::setPos(posCursor) ;
}
}
/**
* Transform a wrapper action to an Avogadro action : select an atom,
* (or a bond to initiate a rotation axe).
* @param wmavoAction All actions ask by the wrapper
* @param posCursor The position where a "click" is realised
*/
void WrapperChemicalCmdToAvoAction::transformWrapperActionToSelectAtom( int wmavoAction, const QPoint& posCursor )
{
if( WMAVO_IS2(wmavoAction,WMAVO_SELECT) || WMAVO_IS2(wmavoAction,WMAVO_SELECT_MULTI) )
{
//cout << "WrapperChemicalCmdToAvoAction::transformWrapperActionToSelectAtom" << endl ;
if( WMAVO_IS2(wmavoAction,WMAVO_SELECT) )
{ // Select only 1 object.
/*
{ // Test to add a real mouse click
// - Code occurs crash.
// - It can't access to the menu pull-down.
QPoint p=QCursor::pos() ;
//QCoreApplication *app=QCoreApplication::instance() ;
//QWidget *widget=app->widgetAt( p ) ;
QWidget *widget=QApplication::widgetAt( p ) ;
//QWidget *widget=QApplication::activeWindow() ;
if( widget!=NULL )
{
mytoolbox::dbgMsg( widget->accessibleName() ) ;
QPoint p2=widget->mapFromGlobal(p) ;
QEvent *me1 = new QMouseEvent( QEvent::MouseButtonPress, p2,
Qt::LeftButton, Qt::NoButton, Qt::NoModifier ) ;
QEvent *me3 = new QMouseEvent( QEvent::MouseButtonRelease, p2,
Qt::LeftButton, Qt::NoButton, Qt::NoModifier ) ;
QApplication::postEvent( widget, me1 ) ;
QApplication::postEvent( widget, me3 ) ;
}
else
{
mytoolbox::dbgMsg( "nada" ) ;
}
}
*/
// Just one rumble.
InputDevice::RumbleSettings rumble( false, false, 10 ) ;
rumble.setStart( true ) ;
rumble.setDistance( 0 ) ;
InputDevice::WmDeviceData_to wmDevDataTo ;
wmDevDataTo.setRumble( rumble ) ;
m_wmDev->setDeviceDataTo( wmDevDataTo ) ;
QPoint p=m_widget->mapFromGlobal(posCursor) ;
bool hasAddHydrogen=m_moleculeManip->hasAddedHydrogen() ;
Atom *atom=NULL ;
Bond *bond=NULL ;
// One method:
// Not adapted here: atom = m_widget->computeClickedAtom( p ) ;
// OR,
// use the method below :
QList<GLHit> hits=m_widget->hits( p.x()-5, p.y()-5, 10, 10 ) ;
// Search the 1st primitive which is interesting.
foreach( const GLHit& hit, hits )
{
if( hit.type() == Primitive::AtomType )
{
atom = m_widget->molecule()->atom( hit.name() ) ;
break ;
}
if( hit.type() == Primitive::BondType )
{
bond = m_widget->molecule()->bond( hit.name() ) ;
break ;
}
}
if( atom==NULL && bond==NULL )
{ // No selection.
m_widget->clearSelected() ;
m_moleculeManip->resetRotationAxe() ;
}
else if( bond != NULL )
{ // Bond selection.
// Get the previous bond.
Bond *oldBond=m_moleculeManip->getRotationAxeBond() ;
// Check if identical with the new.
if( oldBond!=NULL && oldBond==bond )
{ // Disable it.
m_moleculeManip->resetRotationAxe() ;
PrimitiveList pl ;
pl.append( oldBond ) ;
m_widget->setSelected( pl, false ) ;
}
else
{ // Enable the new, and disable the old.
m_moleculeManip->setRotationAxe( bond ) ;
if( oldBond != NULL )
{ // Unselect the previous bond used to the rotation axe.
PrimitiveList pl ;
pl.append( oldBond ) ;
m_widget->setSelected( pl, false ) ;
}
// Select the new bond used to the rotation axe.
PrimitiveList pl ;
pl.append( bond ) ;
m_widget->setSelected( pl, true ) ;
}
}
else if( atom != NULL )
{ // Atom seletion.
m_moleculeManip->resetRotationAxe() ;
if( m_isCalculDistDiedre )
{ // Manage the selection of atom for the calculation of distance & Co.
// It works with an association of the WmTool class.
// Put the "calcul distance" mode of the WrapperChemicalCmdToAvoAction class to off.
m_isCalculDistDiedre = false ;
// Inform the WmTool class of the selected atom.
emit sendAtomToCalculDistDiedre( atom ) ; // To wmTool.
// Nota Bene : it is the WmTool class which infoms the WrapperChemicalCmdToAvoAction class when
// it is necessary to select an atom for the "calcul distance" mode.
}
else
{ // Manage the selection of one atom.
QList<Primitive*> hitList ;
hitList.append(atom) ;
m_widget->toggleSelected(hitList) ;
//m_widget->setSelected(hitList, true) ;
// Select H-neighbors.
if( hasAddHydrogen
&& m_widget->isSelected(static_cast<Primitive*>(atom))
&& !atom->isHydrogen() )
{
Atom *a=NULL ;
PrimitiveList pl ;
foreach( unsigned long ai, atom->neighbors() )
{
a = m_widget->molecule()->atomById(ai) ;
if( a!=NULL && a->isHydrogen() )
pl.append( a ) ;
}
m_widget->setSelected( pl, true) ;
}
}
}
}
else //if( WMAVO_IS2(wmavoAction,WMAVO_SELECT_MULTI) )
{ // Multiple selection.
// For the display of the selection rectangle.
if( !m_isRenderRect )
{ // Save the 1st point of the rectangle.
m_isRenderRect = true ;
m_rectP1 = posCursor ;
}
// Save the 2nd point of the rectangle.
m_rectP2 = posCursor ;
QPoint p1=m_widget->mapFromGlobal(m_rectP1) ;
QPoint p2=m_widget->mapFromGlobal(m_rectP2) ;
// Adjust the 1st point always at bottom/left,
// the 2nd point always at up/right.
int x1=( p1.x()<p2.x() ? p1.x() : p2.x() ) ;
int y1=( p1.y()<p2.y() ? p1.y() : p2.y() ) ;
int x2=( p1.x()>p2.x() ? p1.x() : p2.x() ) - 1 ;
int y2=( p1.y()>p2.y() ? p1.y() : p2.y() ) - 1 ;
// Inform the WmTool class of the 2 points of the selection rectangle for the display.
emit renderedSelectRect( true, QPoint(x1,y1), QPoint(x2,y2) ) ;
}
}
else
{
if( m_isRenderRect )
{
//
// 1. Realize the selection
QList<GLHit> hitList ;
PrimitiveList pList ;
Primitive *p=NULL ;
Atom *a=NULL ;
QPoint p1=m_widget->mapFromGlobal(m_rectP1) ;
QPoint p2=m_widget->mapFromGlobal(m_rectP2) ;
int x1=( p1.x()<p2.x() ? p1.x() : p2.x() ) ;
int y1=( p1.y()<p2.y() ? p1.y() : p2.y() ) ;
int x2=( p1.x()>p2.x() ? p1.x() : p2.x() ) ; // - 1 ;
int y2=( p1.y()>p2.y() ? p1.y() : p2.y() ) ; // - 1 ;
// Perform an OpenGL selection and retrieve the list of hits.
hitList = m_widget->hits( x1, y1, x2-x1, y2-y1 ) ;
if( hitList.empty() )
{
m_widget->clearSelected() ;
}
else
{
// Build a primitiveList for toggleSelected() method.
foreach( const GLHit& hit, hitList )
{
if( hit.type() == Primitive::AtomType )
{
a = m_widget->molecule()->atom( hit.name() ) ;
p = static_cast<Primitive *>( a ) ;
if( p != NULL )
pList.append( p ) ;
else
mytoolbox::dbgMsg( "Bug in WrapperChemicalCmdToAvoAction::transformWrapperActionToSelectAtom : a NULL-object not expected." ) ;
}
}
// Toggle the selection.
m_widget->toggleSelected( pList ) ; // or setSelected()
//cout << "toggle primitive" << endl ;
}
//
// 2. Finish the action.
m_isRenderRect = false ;
m_needAnUpdateMore = true ;
m_rectP1 = QPoint( 0, 0 ) ;
m_rectP2 = QPoint( 0, 0 ) ;
p1 = m_widget->mapFromGlobal(m_rectP1) ;
p2 = m_widget->mapFromGlobal(m_rectP2) ;
emit renderedSelectRect( false, p1, p2) ;
}
}
}
/**
* Transform a wrapper action to an Avogadro action : move the selected atoms.
* @param wmavoAction All actions ask by the wrapper
* @param pointRef The position of the reference point
* @param pos3dCurrent The current position calculate by the Wiimote
* @param pos3dLast The last position calculate by the Wiimote
* @param rotAtomDegX The desired X-axis angle
* @param rotAtomDegY The desired Y-axis angle
*/
void WrapperChemicalCmdToAvoAction::transformWrapperActionToMoveAtom
( int wmavoAction,
const Eigen::Vector3d& pointRef,
const Eigen::Vector3d& pos3dCurrent,
const Eigen::Vector3d& pos3dLast,
double rotAtomDegX,
double rotAtomDegY )
{
if( WMAVO_IS2(wmavoAction,WMAVO_ATOM_MOVE) )
{ // Object is in "travel mode", but just in the mode.
// It is necessary to know what is the movement.
if( WMAVO_IS2(wmavoAction,WMAVO_ATOM_TRANSLATE) || WMAVO_IS2(wmavoAction,WMAVO_ATOM_ROTATE) )
{ // Work when an atom is moving. If no movement, do not pass here.
//cout << "WrapperChemicalCmdToAvoAction::transformWrapperActionToMoveAtom" << endl ;
Eigen::Vector3d vectAtomTranslate ;
Eigen::Transform3d transfAtomRotate ;
bool isMoved=calculateTransformationMatrix
( wmavoAction, pos3dCurrent, pos3dLast,
pointRef,
rotAtomDegX, rotAtomDegY,
vectAtomTranslate, transfAtomRotate
) ;
if( isMoved )
{
if( !m_isMoveAtom )
m_isMoveAtom = true ;
QList<Primitive*> pList=m_widget->selectedPrimitives().subList(Primitive::AtomType) ;
if( WMAVO_IS2(wmavoAction,WMAVO_ATOM_TRANSLATE) )
m_moleculeManip->tranlateAtomBegin( pList, vectAtomTranslate ) ;
else if( WMAVO_IS2(wmavoAction,WMAVO_ATOM_ROTATE) )
m_moleculeManip->rotateAtomBegin( pList, transfAtomRotate ) ;
// Active rumble in the Wiimote only if one atom is selected.
if( pList.size() == 1 )
{
Atom *a=static_cast<Atom*>(pList.at(0)) ;
if( a != NULL )
{
Atom *an=m_moleculeManip->calculateNearestAtom( a->pos(), a ) ;
Eigen::Vector3d dist = *(a->pos()) - *(an->pos()) ;
double act = dist.norm() ;
InputDevice::RumbleSettings rumble( false, true ) ;
rumble.setStart( true ) ;
rumble.setDistance( act, WMRUMBLE_MIN_DISTANCE, WMRUMBLE_MAX_DISTANCE ) ;
InputDevice::WmDeviceData_to wmDevDataTo ;
wmDevDataTo.setRumble( rumble ) ;
m_wmDev->setDeviceDataTo( wmDevDataTo ) ;
}
}
}
}
}
else
{ // Finish the action.
if( m_isMoveAtom ) // Caution, this attribut is initialised/used in moveAtom*() methods.
{
m_isMoveAtom = false ;
QList<Primitive*> pList=m_widget->selectedPrimitives().subList(Primitive::AtomType) ;
m_moleculeManip->moveAtomEnd( pList ) ;
InputDevice::RumbleSettings rumble( false, false ) ;
rumble.setStart( false ) ;
rumble.setDistance( 0 ) ;
InputDevice::WmDeviceData_to wmDevDataTo ;
wmDevDataTo.setRumble( rumble ) ;
m_wmDev->setDeviceDataTo( wmDevDataTo ) ;
m_tmpBarycenter = m_vect3d0 ;
}
}
}
/**
* Transform a wrapper action to an Avogadro action : create atom(s) and bond(s).
* @param wmavoAction All actions ask by the wrapper
* @param pointRef The position of the reference point
* @param posCursor The position of the cursor
*/
void WrapperChemicalCmdToAvoAction::transformWrapperActionToCreateAtomBond
( int wmavoAction, const Eigen::Vector3d& pointRef, const QPoint &posCursor )
{
if( WMAVO_IS2(wmavoAction,WMAVO_CREATE) || m_isAtomDraw )
// for m_isAtomDraw : Necessary for the action of "isCreateAtom".
{
//mytoolbox::dbgMsg( "WrapperChemicalCmdToAvoAction::transformWrapperActionToCreateAtomBond" ;
Molecule *mol=m_widget->molecule() ;
// molecule->lock()->tryLockForWrite() :
// GLWidget::render(): Could not get read lock on molecule.
// Lock the write on the molecule => so it locks the render too ...
// This means the possibility that the Avogadro software can be really multi-thread
// (or in anticipation).
// The lock justifies it by the array used to store a new atom, and with the search
// of a new id for this new atom y tutti quanti ...
//if( molecule->lock()->tryLockForWrite() )
//{
// Add an atom.
QPoint p=m_widget->mapFromGlobal(posCursor) ;
if( !m_isAtomDraw )
{ // The 1st action : a request of creation
m_lastCursor = p ;
Primitive* prim=m_widget->computeClickedPrimitive( p ) ;
m_timeFirst = m_time.elapsed() ;
if( prim == NULL )
{
m_isAtomDraw = true ;
m_drawBeginAtom = true ;
m_drawCurrentAtom = false ;
m_drawBond = false ;
//cout << "cursor position:" << p.x() << "," << p.y() << endl ;
//cout << "ref position:" << pointRef[0] << "," << pointRef[1] << "," << pointRef[2] << endl ;
m_beginPosDraw = m_widget->camera()->unProject( p, pointRef ) ;
m_curPosDraw = m_beginPosDraw ;
}
else if( prim->type() == Primitive::AtomType )
{
m_isAtomDraw = true ;
m_drawBeginAtom = false ;
m_drawCurrentAtom = false ;
m_drawBond = false ;
m_beginAtomDraw = static_cast<Atom*>(prim) ;
m_beginPosDraw = *(m_beginAtomDraw->pos()) ;
m_curPosDraw = m_beginPosDraw ;
}
else if( prim->type() == Primitive::BondType )
{
m_isBondOrder = true ;
m_isAtomDraw = true ;
m_drawBeginAtom = false ;
m_drawCurrentAtom = false ;
m_drawBond = false ;
m_bondDraw = static_cast<Bond*>(prim) ;
}
//else
// Nothing to do.
// Request the temporary display of the 1st atom(by the WmTool class).
if( m_isAtomDraw || m_isBondOrder )
emit renderedAtomBond( m_beginPosDraw, m_curPosDraw, m_drawBeginAtom, m_drawCurrentAtom, m_drawBond ) ;
}
else if( m_isAtomDraw && WMAVO_IS2(wmavoAction,WMAVO_CREATE) && !m_isBondOrder )
{ // The 2nd action.
// That means, the 1st atom has been "selected/created" and
// the mouse is moving to create/select an 2nd atom with (new) bond.
// Timeout before to create a 2nd atom.
if( !m_canDrawOther )
{
m_timeSecond = m_time.elapsed() ;
if( (m_timeSecond-m_timeFirst) > 1000 )
m_canDrawOther = true ;
}
if( m_canDrawOther )
{
m_curPosDraw = m_widget->camera()->unProject(p, pointRef) ;
Atom *an = m_moleculeManip->calculateNearestAtom( &m_curPosDraw, NULL ) ;
if( an != NULL )
{
Eigen::Vector3d dist=m_curPosDraw - *(an->pos()) ;
double act=dist.norm() ;
// Activate rumble.
InputDevice::RumbleSettings rumble( false, true ) ;
rumble.setStart( true ) ;
rumble.setDistance( act, WMRUMBLE_MIN_DISTANCE, WMRUMBLE_MAX_DISTANCE ) ;
InputDevice::WmDeviceData_to wmDevDataTo ;
wmDevDataTo.setRumble( rumble ) ;
m_wmDev->setDeviceDataTo( wmDevDataTo ) ;
}
// Methode0 : SPEED !!
Atom* a=NULL ;
// Methode1 : SLOW !!
//a = m_widget->computeClickedAtom( p ) ;
// Methode2 : SLOW !!
/*
QList<GLHit> hits=m_widget->hits( p.x()-5, p.y()-5, 10, 10 ) ;
foreach( const GLHit& hit, hits )
{
if( hit.type() == Primitive::AtomType )
{ // Le 1er element est le plus proche.
a = m_widget->molecule()->atom( hit.name() ) ;
break ;
}
}*/
if( a == NULL )
{
double var1=m_beginPosDraw[0]-m_curPosDraw[0] ;
double var2=m_beginPosDraw[1]-m_curPosDraw[1] ;
double var3=m_beginPosDraw[2]-m_curPosDraw[2] ;
double distVect=sqrt( var1*var1 + var2*var2 + var3*var3 ) ;
// Draw a 2nd atom only if the distance is bigger than ...
if( distVect > WMEX_DISTBEFORE_CREATE )
{
//cout << "Display current atom & bond" << endl ;
m_drawCurrentAtom = true ;
if( m_beginAtomDraw!=NULL && m_beginAtomDraw->isHydrogen()
&& m_beginAtomDraw->bonds().count()>0 )
m_drawBond = false ;
else
m_drawBond = true ;
m_curAtomDraw = a ;
}
else
{
m_drawCurrentAtom = false ;
m_drawBond = false ;
m_curAtomDraw = NULL ;
}
}
else if( *(a->pos()) == m_beginPosDraw )
{
//cout << "Display nothing" << endl ;
m_drawCurrentAtom = false ;
m_drawBond = false ;
m_curAtomDraw = NULL ;
}
else //if( a )
{
//cout << "Display Bond" << endl ;
m_drawCurrentAtom = false ;
m_drawBond = true ;
// Limit the number of bond if Hydrogen Atom.
if( a->isHydrogen() && a->bonds().count() > 0 )
m_drawBond = false ;
if( m_drawBond && m_beginAtomDraw!=NULL
&& m_beginAtomDraw->isHydrogen() && m_beginAtomDraw->bonds().count() > 0 )
m_drawBond = false ;
m_curAtomDraw = a ;
m_curPosDraw = *(a->pos()) ;
}
// Request the temporary display of the atoms and bond (by the WmTool class).
emit renderedAtomBond( m_beginPosDraw, m_curPosDraw, m_drawBeginAtom, m_drawCurrentAtom, m_drawBond ) ;
}
}
else if( m_isAtomDraw && !WMAVO_IS2(wmavoAction,WMAVO_CREATE) )
{ // The 3rd and last action : creation
// - either adjust number of bond ;
// - or create atoms(s) and bond.
bool addSmth=false ;
//QUndoCommand *undo=NULL ;
if( m_isBondOrder )
{
//int oldBondOrder = m_bondDraw->order() ;
#if !AVO_DEPRECATED_FCT
// 1.
m_moleculeManip->changeOrderBondBy1( m_bondDraw ) ;
#else
// 2.
undo = new ChangeBondOrderDrawCommand( m_bondDraw, oldBondOrder, m_addHydrogens ) ;
m_widget->undoStack()->push( undo ) ;
#endif
}
else //if( m_isAtomDraw && !m_isBondOrder )
{
//cout << "End of the creation of atom/bond" << endl ;
Atom* a=NULL ;
Eigen::Vector3d addAtomPos ;
InputDevice::RumbleSettings rumble( false, false ) ;
rumble.setStart( false ) ;
rumble.setDistance( 0 ) ;
InputDevice::WmDeviceData_to wmDevDataTo ;
wmDevDataTo.setRumble( rumble ) ;
m_wmDev->setDeviceDataTo( wmDevDataTo ) ;
if( m_beginAtomDraw == NULL )
{
addSmth = true ;
m_hasAddedBeginAtom = true ;
}
// Timeout before to create a 2nd atom.
if( !m_canDrawOther )
{
m_timeSecond = m_time.elapsed() ;
if( (m_timeSecond-m_timeFirst) > 1000 )
m_canDrawOther = true ;
}
// Add 2nd atom & bond.
if( m_canDrawOther )
{
a = m_widget->computeClickedAtom( p ) ;
if( a == NULL )
{ // Create atome/bond.
double var1=m_beginPosDraw[0]-m_curPosDraw[0] ;
double var2=m_beginPosDraw[1]-m_curPosDraw[1] ;
double var3=m_beginPosDraw[2]-m_curPosDraw[2] ;
double distVect=sqrt( var1*var1 + var2*var2 + var3*var3 ) ;
// Draw a 2nd atom only if the distance is bigger than ...
if( distVect > 0.6 )
{
addAtomPos = m_widget->camera()->unProject( p, pointRef ) ;
addSmth = true ;
m_hasAddedCurAtom = true ;
if( m_drawBond
/* !(m_curAtomDraw->isHydrogen() && m_curAtomDraw->bonds().count()>0)
&& !(m_beginAtomDraw->isHydrogen() && m_beginAtomDraw->bonds().count()>0)
*/
)
m_hasAddedBond = true ;
}
}
else
{ // Create bond.
if( *(a->pos()) != m_beginPosDraw
&& mol->bond(a,m_beginAtomDraw) == NULL
&& m_drawBond
/* !(a->isHydrogen() && a->bonds().count()>0)
&& !(m_beginAtomDraw->isHydrogen() && m_beginAtomDraw->bonds().count()>0)
*/
)
{
m_curAtomDraw = a ;
addSmth = true ;
m_hasAddedBond = true ;
}
}
}
if( mol->lock()->tryLockForWrite() )
{
int atomicNumber=m_moleculeManip->getAtomicNumberCurrent() ;
// Create just the 1st atom.
if( m_hasAddedBeginAtom && !m_hasAddedCurAtom && !m_hasAddedBond )
m_beginAtomDraw = m_moleculeManip->addAtom( &m_beginPosDraw, atomicNumber ) ;
// Create just the 2nd atom.
if( !m_hasAddedBeginAtom && m_hasAddedCurAtom && !m_hasAddedBond )
m_curAtomDraw = m_moleculeManip->addAtom( &addAtomPos, atomicNumber ) ;
// Create just the bond.
if( !m_hasAddedBeginAtom && !m_hasAddedCurAtom && m_hasAddedBond )
m_bondDraw = m_moleculeManip->addBond( m_beginAtomDraw, a, 1 ) ;
// Create the 2nd atom bonded at 1st.
if( !m_hasAddedBeginAtom && m_hasAddedCurAtom && m_hasAddedBond )
m_curAtomDraw = m_moleculeManip->addAtom
( &addAtomPos, atomicNumber,
m_beginAtomDraw, 1 ) ;
// Create the 1st atom bonded at 2nd.
if( m_hasAddedBeginAtom && !m_hasAddedCurAtom && m_hasAddedBond )
m_beginAtomDraw = m_moleculeManip->addAtom
( &m_beginPosDraw, atomicNumber,
m_curAtomDraw, 1 ) ;
// Create 2 atoms.
if( m_hasAddedBeginAtom && m_hasAddedCurAtom )
{
int order=0 ;
PrimitiveList *pl=NULL ;
if( m_hasAddedBond )
order = 1 ;
pl = m_moleculeManip->addAtoms
( &m_beginPosDraw, atomicNumber,
&addAtomPos, atomicNumber, order ) ;
if( pl!=NULL && pl->size()>=2 )
{
PrimitiveList::const_iterator ipl=pl->begin() ;
m_beginAtomDraw = static_cast<Atom*>(*ipl) ;
ipl++ ;
m_curAtomDraw = static_cast<Atom*>(*ipl) ;
}
if( pl != NULL )
delete pl ;
}
// Substitute atom by atom.
if( !m_hasAddedBeginAtom && !m_hasAddedCurAtom && !m_hasAddedBond && !m_canDrawOther )
m_moleculeManip->changeAtomicNumber( m_beginAtomDraw, atomicNumber ) ;
GLfloat projectionMatrix[16] ;
glGetFloatv( GL_PROJECTION_MATRIX, projectionMatrix ) ;
//cout << "Projection Matrix:" << endl ;
//cout<<" "<<projectionMatrix[0]<<" "<<projectionMatrix[4]<<" "<<projectionMatrix[8]<<" "<<projectionMatrix[12]<<endl;
//cout<<" "<<projectionMatrix[1]<<" "<<projectionMatrix[5]<<" "<<projectionMatrix[9]<<" "<<projectionMatrix[13]<<endl;
//cout<<" "<<projectionMatrix[2]<<" "<<projectionMatrix[6]<<" "<<projectionMatrix[10]<<" "<<projectionMatrix[14]<<endl;
//cout<<" "<<projectionMatrix[3]<<" "<<projectionMatrix[7]<<" "<<projectionMatrix[11]<<" "<<projectionMatrix[15]<<endl;
}
mol->lock()->unlock() ;
}
mol->update() ;
if( addSmth )
{
InputDevice::RumbleSettings rumble( false, false, 10 ) ;
rumble.setStart( true ) ;
rumble.setDistance( 0 ) ;
InputDevice::WmDeviceData_to wmDevDataTo ;
wmDevDataTo.setRumble( rumble ) ;
m_wmDev->setDeviceDataTo( wmDevDataTo ) ;
}
//addAdjustHydrogenRedoUndo( molecule ) ;
// Initialization before next use.
m_isBondOrder=false ; m_isAtomDraw=false ;
m_drawBeginAtom=false ; m_drawCurrentAtom=false ; m_drawBond=false ;
m_hasAddedBeginAtom=false ; m_hasAddedCurAtom=false ; m_hasAddedBond=false ;
m_beginAtomDraw=NULL ; m_curAtomDraw=NULL ; m_bondDraw=NULL ;
m_timeFirst=0 ; m_timeSecond=0 ;
m_canDrawOther = false ;
// "Push" all modifications & redraw of the molecule.
emit renderedAtomBond( m_vect3d0, m_vect3d0, false, false, false ) ;
}
//}
}
}
/**
* Transform a wrapper action to an Avogadro action : delete all atom.
* @param wmavoAction All actions ask by the wrapper
*/
void WrapperChemicalCmdToAvoAction::transformWrapperActionToDeleteAllAtomBond( int wmavoAction )
{
if( WMAVO_IS2(wmavoAction,WMAVO_DELETEALL) )
{
//mytoolbox::dbgMsg( "WrapperChemicalCmdToAvoAction::transformWrapperActionToDeleteAllAtomBond" ;
m_moleculeManip->deleteAllElement() ;
}
}
/**
* Transform a wrapper action to an Avogadro action : delete atom(s).
* @param wmavoAction All actions ask by the wrapper
* @param posCursor The position of the cursor
*/
void WrapperChemicalCmdToAvoAction::transformWrapperActionToRemoveAtomBond( int wmavoAction, const QPoint &posCursor )
{
if( WMAVO_IS2(wmavoAction,WMAVO_DELETE) )
{
//mytoolbox::dbgMsg( "WrapperChemicalCmdToAvoAction::transformWrapperActionToRemoveAtomBond" ;
Molecule *mol=m_widget->molecule() ;
if( mol->lock()->tryLockForWrite() )
{
QPoint p=m_widget->mapFromGlobal(posCursor) ;
Primitive* prim=m_widget->computeClickedPrimitive( p ) ;
PrimitiveList pl=m_widget->selectedPrimitives() ;
if( prim == NULL )
{ // Remove the selected atoms.
#if !AVO_DEPRECATED_FCT
m_moleculeManip->removeAtoms( &pl ) ;
#else
// 2. with undo/redo, not adjust hydrogen ...
deleteSelectedElementUndoRedo( mol ) ;
#endif
}
else
{
if( prim->type() == Primitive::AtomType )
{ // Remove atom.
Atom *atom = static_cast<Atom*>(prim) ;
m_moleculeManip->removeAtom( atom ) ;
}
if( prim->type() == Primitive::BondType )
{ // Remove bond.
Bond *bond = static_cast<Bond*>(prim) ;
#if !AVO_DEPRECATED_FCT
// 1.
m_moleculeManip->removeBond( bond ) ;
#else
// 2.
deleteBondWithUndoRedo( bond ) ;
#endif
}
}
mol->lock()->unlock() ;
}
}
}
/**
* Transform a wrapper action to an Avogadro action : rotate the camera.
* @param wmavoAction All actions ask by the wrapper
* @param pointRef The position of the reference point
* @param rotCamAxeXDeg The desired angle on the X-axis of the screen
* @param rotCamAxeYDeg The desired angle on the Y-axis of the screen
*/
void WrapperChemicalCmdToAvoAction::transformWrapperActionToRotateCamera
( int wmavoAction,
const Eigen::Vector3d &pointRef,
double rotCamAxeXDeg, double rotCamAxeYDeg )
{
if( WMAVO_IS2(wmavoAction,WMAVO_CAM_ROTATE) )
{
//mytoolbox::dbgMsg( "WrapperChemicalCmdToAvoAction::transformWrapperActionToRotateCamera" ;
if( WMAVO_IS2(wmavoAction,WMAVO_CAM_ROTATE_BYWM) )
{ // If use the cross of the Wiimote.
// Use this method to get the wanted angle of rotation.
// Value in (radian / Avogadro::ROTATION_SPEED) == the desired angle.
double rotCamAxeXRad = (rotCamAxeXDeg*m_PI180) / Avogadro::ROTATION_SPEED ;
double rotCamAxeYRad = (rotCamAxeYDeg*m_PI180) / Avogadro::ROTATION_SPEED ;
Navigate::rotate( m_widget, pointRef, rotCamAxeXRad, rotCamAxeYRad ) ;
}
else if( WMAVO_IS2(wmavoAction,WMAVO_CAM_ROTATE_BYNC) )
{ // Turn in a direction.
// Do not search an unit speed or other, just a direction.
Navigate::rotate( m_widget, pointRef, rotCamAxeXDeg, rotCamAxeYDeg ) ;
}
}
}
/**
* Transform a wrapper action to an Avogadro action : translate the camera.
* @param wmavoAction All actions ask by the wrapper
* @param pointRef The position of the reference point
* @param distCamXTranslate Desired distance on the X-axis of the screen
* @param distCamYTranslate Desired distance on the Y-axis of the screen
*/
void WrapperChemicalCmdToAvoAction::transformWrapperActionToTranslateCamera
( int wmavoAction, const Eigen::Vector3d &pointRef, double distCamXTranslate, double distCamYTranslate )
{
if( WMAVO_IS2(wmavoAction,WMAVO_CAM_TRANSLATE) )
{
//mytoolbox::dbgMsg( "WrapperChemicalCmdToAvoAction::transformWrapperActionToTranslateCamera" ;
Navigate::translate( m_widget, pointRef, distCamXTranslate, distCamYTranslate ) ;
}
}
/**
* Transform a wrapper action to an Avogadro action : zoom the camera.
* @param wmavoAction All actions ask by the wrapper
* @param pointRef The position of the reference point
* @param distCamZoom Desired distance for the zoom on the Z-axis of the screen
*/
void WrapperChemicalCmdToAvoAction::transformWrapperActionToZoomCamera
( int wmavoAction, const Eigen::Vector3d &pointRef, double distCamZoom )
{
if( WMAVO_IS2(wmavoAction,WMAVO_CAM_ZOOM) )
{
//mytoolbox::dbgMsg( "WrapperChemicalCmdToAvoAction::transformWrapperActionToZoomCamera" ;
Navigate::zoom( m_widget, pointRef, distCamZoom ) ;
}
}
/**
* Transform a wrapper action to an Avogadro action : initiate the camera.
* @param wmavoAction All actions ask by the wrapper
* @param pointRef The position of the reference point.
*/
void WrapperChemicalCmdToAvoAction::transformWrapperActionToInitiateCamera
( int wmavoAction, const Eigen::Vector3d &pointRef )
{
if( WMAVO_IS2(wmavoAction,WMAVO_CAM_INITIAT) )
{
//mytoolbox::dbgMsg( "WrapperChemicalCmdToAvoAction::transformWrapperActionToInitiateCamera" ;
#if 0
// 1
//m_widget->camera()->setModelview( m_cameraInitialViewPoint ) ;
if( !(
((rotCamAxeXDeg==90.0 || rotCamAxeXDeg==-90.0) && rotCamAxeYDeg==0.0)
|| ((rotCamAxeYDeg==90.0 || rotCamAxeYDeg==-90.0) && rotCamAxeXDeg==0.0)
)
)
{ // If not use the cross of the Wiimote.
// 2
//mytoolbox::dbgMsg( "pointRefRot:" << pointRefRot[0] << pointRefRot[1] << pointRefRot[2] ;
//Navigate::translate( m_widget, pointRefRot, -pointRefRot[0], -pointRefRot[1] ) ;
// 3
Eigen::Vector3d barycenterScreen=m_widget->camera()->project(pointRefRot) ;
QPoint barycenterScreen2(barycenterScreen[0], barycenterScreen[1]) ;
//mytoolbox::dbgMsg( "pointRefRot:" << barycenterScreen[0] << barycenterScreen[1] << barycenterScreen[2] ;
//Navigate::translate( m_widget, pointRefRot, -barycentreEcran[0], -barycentreEcran[1] ) ;
// 4
//Navigate::zoom( m_widget, pointRefRot, m_widget->cam_beginPosDrawmera()->distance(pointRefRot)/*+10*/ ) ;
//mytoolbox::dbgMsg( " distance:" << m_widget->camera()->distance(pointRefRot) ;
// 5
Eigen::Vector3d transformedGoal = m_widget->camera()->modelview() * pointRefRot ;
double distance=m_widget->camera()->distance(pointRefRot) ;
double distanceToGoal = transformedGoal.norm() ;
//mytoolbox::dbgMsg( " distance:" << distance ;
//mytoolbox::dbgMsg( " distanceToGoal:" << distanceToGoal ;
/*
double distanceToGoal = transformedGoal.norm();m_beginPosDraw
double t = ZOOM_SPEED * delta;
const double minDistanceToGoal = 2.0 * CAMERA_NEAR_DISTANCE;
double u = minDistanceToGoal / distanceToGoal - 1.0;
if( t < u )
{
t = u;
Navigate::rotate( m_widget, pointRefRot, rotCamAxeXDeg, rotCamAxeYDeg ) ;
}
widget->camera()->modelview().pretranslate(transformedGoal * t);
*/
// 6
//m_widget->camera()->modelview().pretranslate(-transformedGoal /*+ (camBackTransformedZAxis*-40)*/ ) ;
//m_widget->camera()->modelview().translate(-transformedGoal /*+ (camBackTransformedZAxis*-10)*/ ) ;
// 7
//Eigen::Vector3d camBackTransformedZAxis=m_widget->camera()->transformedZAxis() ;
//m_widget->camera()->modelview().translate( camBackTransformedZAxis*-10.0 ) ;
distance=m_widget->camera()->distance(pointRefRot) ;
distanceToGoal = transformedGoal.norm();
//mytoolbox::dbgMsg( " distance:" << distance ;
//mytoolbox::dbgMsg( " distanceToGoal:" << distanceToGoal ;
#endif
//Eigen::Vector3d barycenterScreen=m_widget->camera()->project(pointRefRot) ;
//QPoint barycenterScreen2(barycenterScreen[0], barycenterScreen[1]) ;
//mytoolbox::dbgMsg( "pointRefRot:" << barycenterScreen[0] << barycenterScreen[1] << barycenterScreen[2] ;
//Eigen::Transform3d cam=m_widget->camera()->modelview() ;
/* OK
Eigen::Vector3d right(cam(0,0), cam(1,0), cam(2,0)) ;
Eigen::Vector3d up(cam(0,1), cam(1,1), cam(2,1)) ;
Eigen::Vector3d dir(cam(0,2), cam(1,2), cam(2,2)) ;
Eigen::Vector3d pos(cam(0,3), cam(1,3), cam(2,3)) ;
cout << "right:" << right << endl ;
cout << "dir:" << dir << endl ;
cout << "up:" << up << endl ;
cout << "pos:" << pos << endl ;
*/
/* OK
cam(0,3) = 0 ;
cam(1,3) = 0 ;
cam(2,3) = -20 ;
*/
/* Oui, et non, apres quelques rotations de camera, le barycentre n'est plus centre.
mytoolbox::dbgMsg( "pointRefRot:" << pointRefRot[0] << pointRefRot[1] ;
cam(0,3) = -pointRefRot[0] ;
cam(1,3) = -pointRefRot[1] ;
cam(2,3) = -25 ;
m_widget->camera()->setModelview(cam) ;
*/
Eigen::Vector3d barycenterScreen=m_widget->camera()->project( pointRef ) ;
QPoint barycenterScreen2((int)barycenterScreen[0], (int)barycenterScreen[1]) ;
GLint params[4] ;
// Do not work (with .h and compilation flag, the final error is : ~"impossible to use without a first call of glinit"~).
//int screen_pos_x = glutGet((GLenum)GLUT_WINDOW_X);
//int screen_pos_y = glutGet((GLenum)GLUT_WINDOW_Y);
//mytoolbox::dbgMsg( " :" << screen_pos_x << screen_pos_y ;
glGetIntegerv( GL_VIEWPORT, params ) ;
GLenum errCode ;
const GLubyte *errString ;
if( (errCode=glGetError()) != GL_NO_ERROR )
{
errString = gluErrorString( errCode ) ;
fprintf (stderr, "OpenGL Error: %s\n", errString);
}
GLdouble x=params[0] ;
GLdouble y=params[1] ;
GLdouble width=params[2] ;
GLdouble height=params[3] ;
QPoint widgetCenter( (int)((x+width)/2.0), (int)((y+height)/2.0) ) ;
Navigate::translate( m_widget, pointRef, barycenterScreen2, widgetCenter ) ;
Eigen::Transform3d cam=m_widget->camera()->modelview() ;
cam(2,3) = -25 ;
m_widget->camera()->setModelview(cam) ;
}
}
/**
* Transform a wrapper action to an Avogadro action : enable/disable the atom saturation.
* @param wmavoAction All actions ask by the wrapper
*/
void WrapperChemicalCmdToAvoAction::transformWrapperActionToSaturateAtoms
( int wmavoAction )
{
if( WMAVO_IS2(wmavoAction,WMAVO_SATURATE_ATOMS) )
{
m_moleculeManip->invertHasAddHydrogen() ;
}
}
/**
* Transform a wrapper action to an context menu action.
* @param wmavoAction All actions ask by the wrapper
* @param posCursor The position of the cursor
*/
void WrapperChemicalCmdToAvoAction::transformWrapperActionToUseContextMenu( int &wmavoAction, const QPoint &posCursor )
{
m_contextMenu->manageAction( wmavoAction, posCursor ) ;
}
/**
* Update Avogadro according to the Avogadro actions realized.
* Here, the update is for the Avogadro delete actions.
* @param wmavoAction All actions ask by the wrapper
*/
void WrapperChemicalCmdToAvoAction::updateForAvoActions1( int wmavoAction )
{
if( WMAVO_IS2(wmavoAction,WMAVO_DELETE)
|| WMAVO_IS2(wmavoAction,WMAVO_DELETEALL)
/*|| WMAVO_IS2(wmavoAction,WMAVO_CREATE)*/
// Put in the transformWrapperActionToCreateAtomBond() method to
// gain update during multiple creation.
)
{
//mytoolbox::dbgMsg( "WrapperChemicalCmdToAvoAction::updateForAvoActions1" ;
// Update
// If we have done stuff then trigger a redraw of the molecule
m_widget->molecule()->update() ;
/*
// Not resolve an update problem ...
m_widget->molecule()->update() ;
m_widget->update() ; // update( &Region ), update( int, int, int, int ) ...
m_widget->updateGeometry() ;
m_widget->updateGL() ;
m_widget->updateOverlayGL() ;
m_widget->updatesEnabled() ;
//m_widget->molecule()->updateAtom() ;
m_widget->molecule()->updateMolecule() ;
m_widget->molecule()->calculateGroupIndices() ;
*/
}
}
/**
* Update Avogadro according to the Avogadro actions realized.
* Here, the update is for a lot of Avogadro actions.
* This is a special update, because it simulates a mouse click to realize update.
* In fact, some optimization are available only when some Avogadro class realize
* update.
* <br/>To activate the quick render (the previous optimization) , it is necessary to simulate a mouse click.
* Explanation, the quick render is activated when :
* - Check the quick render option
* Set (allowQuickRender) attribut to enable. Now Avogadro MAY accept
* quick render.
* - While a mouse movement, if the mouse is down
* The call of GLWidget::mouseMoveEvent(), and only this method sets
* the (quickRender) attribut at true.
*
* @param wmavoAction All actions ask by the wrapper
*/
void WrapperChemicalCmdToAvoAction::updateForAvoActions2( int wmavoAction )
{
if( //(WMAVO_IS2(wmavoAction, WMAVO_MENU_ACTIVE) ? 0 // To update wmInfo in wmTool class
// : 1 ) // To avoid a bug with periodic table.
//||
WMAVO_IS2(wmavoAction,WMAVO_SELECT)
|| WMAVO_IS2(wmavoAction,WMAVO_SELECT_MULTI)
|| WMAVO_IS2(wmavoAction,WMAVO_CREATE)
|| WMAVO_IS2(wmavoAction,WMAVO_CAM_ROTATE)
|| WMAVO_IS2(wmavoAction,WMAVO_CAM_ZOOM)
|| WMAVO_IS2(wmavoAction,WMAVO_CAM_TRANSLATE)
|| WMAVO_IS2(wmavoAction,WMAVO_CAM_INITIAT)
|| m_needAnUpdateMore
)
{
//mytoolbox::dbgMsg( "WrapperChemicalCmdToAvoAction::updateForAvoActions2" ;
if( m_needAnUpdateMore ) m_needAnUpdateMore = false ;
if( !m_widget->quickRender() )
{
// 1. No quick render.
m_widget->update() ;
}
else
{
// 2. No compile : mouseMove is protected.
// Call directly GLWidget->mouseMove signal.
//emit m_widget->mouseMove(&me) ;
// 3. Call directly Tool->mouseMouseEvent. No quick render.
//m_widget->tool()->mouseMoveEvent( m_widget, &me) ;
//m_widget->tool()->mouseMoveEvent( m_widget->current(), &me) ;
// 4. Try Fake mouse event. WORKS !!!
if( !m_testEventPress )
{
m_testEventPress = true ;
QApplication::sendEvent( m_widget->m_current, m_me1 ) ;
}
QApplication::sendEvent( m_widget->m_current, m_me2 ) ;
// Test, but be carefull, you must allocate the event each time
// it put in a queue, and delete the object after use.
//QApplication::postEvent( app, me1 ) ;
//QApplication::postEvent( app, me3 ) ;
// Install something else.
// 5. Try Fake mouse event.
//qTestEventList events;
//events.addMouseMove(p,1);
//events.simulate(m_widget);
}
}
else
{
// 4. Finish fake mouse event.
if( m_widget->quickRender() && m_testEventPress )
{
m_testEventPress = false ;
QApplication::sendEvent( m_widget->m_current, m_me3 ) ;
}
}
}
/**
* Update Avogadro according to the Avogadro actions realized.
* Here, the update is for the Avogadro move actions.
* @param wmavoAction All actions ask by the wrapper
*/
void WrapperChemicalCmdToAvoAction::updateForAvoActions3( int wmavoAction )
{
if( WMAVO_IS2(wmavoAction,WMAVO_ATOM_MOVE) )
{ // Object is in "travel mode", but just in the mode.
// It is necessary to know what is the movement.
if( (WMAVO_IS2(wmavoAction,WMAVO_ATOM_TRANSLATE) || WMAVO_IS2(wmavoAction,WMAVO_ATOM_ROTATE))
&& m_widget->selectedPrimitives().size()>0
)
{
//mytoolbox::dbgMsg( "WrapperChemicalCmdToAvoAction::updateForAvoActions3" ;
// 1. No Quick Render.
//m_widget->molecule()->update() ; // Update & Redraw (without quick Render)
// 2. Quick Render seems activated, but it lags ...
m_widget->molecule()->updateMolecule() ; // Update & Redraw.
}
}
}
/**
* Calculate the transformation vector and/or matrix according to the need.
* "Convert" the wiimote coordinate system to the Avogadro coordinate system.
* @return TRUE if the transformation matrix is different to null ; FALSE else.
* @param wmactions All actions ask by the wrapper
* @param curPos The current position calculate by the Wiimote
* @param lastPos The last position calculate by the Wiimote
* @param refPoint_in The position of the reference point.
* @param rotAtomdegX_in The desired X-axis angle
* @param rotAtomdegY_in The desired Y-axis angle
*/
bool WrapperChemicalCmdToAvoAction::calculateTransformationMatrix
( int wmactions_in,
const Eigen::Vector3d& curPos_in,
const Eigen::Vector3d& lastPos_in,
const Eigen::Vector3d& refPoint_in,
double rotAtomdegX_in,
double rotAtomdegY_in,
Eigen::Vector3d &vectAtomTranslate_out,
Eigen::Transform3d &transfAtomRotate_out )
{
bool isMoved=false ;
if( WMAVO_IS2(wmactions_in,WMAVO_ATOM_TRANSLATE) || WMAVO_IS2(wmactions_in,WMAVO_ATOM_ROTATE) )
{
QPoint currentPoint((int)curPos_in[0], (int)curPos_in[1]) ;
QPoint lastPoint((int)lastPos_in[0], (int)lastPos_in[1]) ;
Eigen::Vector3d fromPos=m_widget->camera()->unProject( lastPoint, refPoint_in ) ;
Eigen::Vector3d toPos=m_widget->camera()->unProject( currentPoint, refPoint_in ) ;
Eigen::Vector3d camBackTransformedXAxis=m_widget->camera()->backTransformedXAxis() ;
Eigen::Vector3d camBackTransformedYAxis=m_widget->camera()->backTransformedYAxis() ;
Eigen::Vector3d camBackTransformedZAxis=m_widget->camera()->backTransformedZAxis() ;
if( WMAVO_IS2(wmactions_in,WMAVO_ATOM_TRANSLATE)
&& !(curPos_in[0]==lastPos_in[0] && curPos_in[1]==lastPos_in[1]) )
{
vectAtomTranslate_out = (toPos - fromPos) / WMAVO_ATOM_SMOOTHED_MOVE_XY ;
//cout << "currentWmPos.x():" << currentWmPos.x() << " currentWmPos.y():" << currentWmPos.y() << endl ;
//cout << " lastWmPos.x():" << lastWmPos.x() << " lastWmPos.y():" << lastWmPos.y() << endl ;
//cout << " fromPos[0]:" << fromPos[0] << " fromPos[1]:" << fromPos[1] << " fromPos[2]:" << fromPos[2] << endl ;
//cout << " toPos[0]:" << toPos[0] << " toPos[1]:" << toPos[1] << " fromPos[2]:" << fromPos[2] << endl ;
//cout << " newVectAtomTranslate:" << m_vectAtomTranslate[0] << " " << m_vectAtomTranslate[1] << " " << m_vectAtomTranslate[2] << endl ;
if( WMAVO_IS2(wmactions_in,WMAVO_ATOM_TRANSLATE) )
{
// Z-movement.
if( (curPos_in[2]-lastPos_in[2]) <= -WMAVO_WM_Z_MINPOINTING_MOVEALLOWED )
vectAtomTranslate_out += (camBackTransformedZAxis*WMAVO_ATOM_MAX_MOVE_Z) ;
if( (curPos_in[2]-lastPos_in[2]) >= WMAVO_WM_Z_MINPOINTING_MOVEALLOWED )
vectAtomTranslate_out -= (camBackTransformedZAxis*WMAVO_ATOM_MAX_MOVE_Z) ;
}
isMoved = true ;
//cout << " m_vectAtomTranslate:" << m_vectAtomTranslate[0] << " " << m_vectAtomTranslate[1] << " " << m_vectAtomTranslate[2] << endl ;
}
else if( WMAVO_IS2(wmactions_in,WMAVO_ATOM_ROTATE) )
{
Eigen::Vector3d rotAxe=m_moleculeManip->getRotationAxe() ;
if( m_tmpBarycenter == m_vect3d0 )
{ // Calculate the barycenter of selected atoms.
Eigen::Vector3d tmp=m_vect3d0 ;
int i=0 ;
Atom *a=NULL ;
foreach( Primitive *p, m_widget->selectedPrimitives() )
{
if( p->type() == Primitive::AtomType )
{
a = static_cast<Atom*>(p) ;
tmp += *(a->pos()) ;
i++ ;
}
}
m_tmpBarycenter = tmp / i ;
}
if( rotAxe != m_vect3d0 )
{
Eigen::Vector3d rotAxePoint=m_moleculeManip->getRotationAxePoint() ;
// Rotate the selected atoms about the center
// rotate only selected primitives
transfAtomRotate_out.matrix().setIdentity();
// Return to the center of the 3D-space.
transfAtomRotate_out.translation() = rotAxePoint ;
// Apply rotations.
transfAtomRotate_out.rotate(
Eigen::AngleAxisd( (rotAtomdegX_in/90.0)* 0.1, rotAxe) ) ;
// /90.0 => Eliminate the initial 90° rotation by the Wiimote,
// then to apply a step (in unknown metric).
transfAtomRotate_out.rotate(
Eigen::AngleAxisd( (rotAtomdegY_in/90.0)*-0.1, rotAxe ) ) ;
// Return to the object.
transfAtomRotate_out.translate( -rotAxePoint ) ;
}
else
{ // Rotation around the barycenter.
// Rotate the selected atoms about the center
// rotate only selected primitives
transfAtomRotate_out.matrix().setIdentity();
// Return to the center of the 3D-space.
transfAtomRotate_out.translation() = m_tmpBarycenter ;
// Apply rotations.
transfAtomRotate_out.rotate(
Eigen::AngleAxisd( (rotAtomdegX_in/90.0)* 0.1, camBackTransformedYAxis) ) ;
// /90.0 => Eliminate the initial 90° rotation by the Wiimote,
// then to apply a step (in unknown metric).
transfAtomRotate_out.rotate(
Eigen::AngleAxisd( (rotAtomdegY_in/90.0)*-0.1, camBackTransformedXAxis) ) ;
// Return to the object.
transfAtomRotate_out.translate( -m_tmpBarycenter ) ;
}
isMoved = true ;
}
else
{ // Put all transformation "at zero".
transfAtomRotate_out.matrix().setIdentity();
transfAtomRotate_out.translation() = m_vect3d0 ;
vectAtomTranslate_out[0] = 0.0 ;
vectAtomTranslate_out[1] = 0.0 ;
vectAtomTranslate_out[2] = 0.0 ;
isMoved = false ;
}
}
return isMoved ;
}
/**
* Receive the "calcul distance" feature from the WmTool class..
*/
void WrapperChemicalCmdToAvoAction::receiveRequestToCalculDistance()
{
m_isCalculDistDiedre = true ;
}
}
| [
"mickael.gadroy@gmail.com",
"myck@myck-debian-i386.univ-reims.fr"
] | [
[
[
1,
141
],
[
144,
253
],
[
256,
256
],
[
259,
262
],
[
264,
267
],
[
276,
278
],
[
280,
282
],
[
284,
288
],
[
291,
295
],
[
301,
302
],
[
304,
322
],
[
325,
325
],
[
328,
338
],
[
342,
1483
],
[
1486,
1504
],
[
1508,
1509
],
[
1513,
1513
],
[
1515,
1515
],
[
1527,
1527
],
[
1552,
1579
]
],
[
[
142,
143
],
[
254,
255
],
[
257,
258
],
[
263,
263
],
[
268,
275
],
[
279,
279
],
[
283,
283
],
[
289,
290
],
[
296,
300
],
[
303,
303
],
[
323,
324
],
[
326,
327
],
[
339,
341
],
[
1484,
1485
],
[
1505,
1507
],
[
1510,
1512
],
[
1514,
1514
],
[
1516,
1526
],
[
1528,
1551
]
]
] |
a7c2d371a8662864421098ac237ce6d3c4331ef9 | a96b15c6a02225d27ac68a7ed5f8a46bddb67544 | /SetGame/Application.hpp | 76fef5eec3e63653410a8dbaf3329aa344342995 | [] | no_license | joelverhagen/Gaza-2D-Game-Engine | 0dca1549664ff644f61fe0ca45ea6efcbad54591 | a3fe5a93e5d21a93adcbd57c67c888388b402938 | refs/heads/master | 2020-05-15 05:08:38 | 2011-04-03 22:22:01 | 2011-04-03 22:22:01 | 1,519,417 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 511 | hpp | #ifndef APPLICATION_HPP
#define APPLICATION_HPP
#include "Common.hpp"
#include "GazaApplication.hpp"
#include "GazaFrameSheet.hpp"
#include "GazaImageManager.hpp"
#include "GazaLogger.hpp"
#include "GameState.hpp"
#include "CardFrameSheetGenerator.hpp"
class Application : public Gaza::Application
{
public:
Application();
~Application();
Gaza::ImageManager * getImageManager();
private:
Gaza::ImageManager imageManager;
Gaza::FrameSheetCollection * cardFrames;
};
#endif | [
"joel.verhagen@gmail.com"
] | [
[
[
1,
28
]
]
] |
cf2a06f81eb7045b31dd1a84c6a824280a9ec8aa | ea72aac3344f9474a0ba52c90ed35e24321b025d | /PathFinding/PathFinding/PathFinding.cpp | ee86e175b6437840cdb4904cdd62c789f72b837e | [] | no_license | nlelouche/ia-2009 | 3bd7f1e42280001024eaf7433462b2949858b1c2 | 44c07567c3b74044e59313532b5829f3a3466a32 | refs/heads/master | 2020-05-17 02:21:02 | 2009-03-31 01:12:44 | 2009-03-31 01:12:44 | 32,657,337 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,208 | cpp | #include "PathFinding.h"
//--------------------------------------------------------------
PathFind::PathFind(int * _map[],int _rows,int _cols)
:
m_pkPath(NULL),
m_pkClosedNodes(NULL),
m_pkOpenNodes(NULL),
m_CurrentNode(NULL),
m_pkiPathIT(0),
m_pkOpenNodesIT(0),
m_pkClosedNodesIT(0)
{
// Copiamos el mapa pasado a un mapa fijo.
for (int i = 0; i > LARGO_MAPA; i++){
m_Map[i] = (int)_map[i];
}
/***/
}
//--------------------------------------------------------------
PathFind::~PathFind(){
/***/
}
//--------------------------------------------------------------
void PathFind::OpenNodes(Node * _node){
// m_pkOpenNodes.insert(_node); // Insertar nodo en la lista
/***/
}
//--------------------------------------------------------------
void PathFind::CloseNode(Node * _node){
/***/
}
//--------------------------------------------------------------
bool PathFind::ExistOpenNodes(){
/***/
return false;
}
//--------------------------------------------------------------
bool PathFind::IsExitNode(Node *_node){
/***/
return false;
}
//--------------------------------------------------------------
Node * PathFind::LessValueNode(){
/***/
return m_CurrentNode;
}
//--------------------------------------------------------------
list<Node*> PathFind::GenerarCamino(){
/***/
return m_pkPath;
}
//--------------------------------------------------------------
bool PathFind::IsEndingNode(Node * _node){
return false;
}
//--------------------------------------------------------------
void PathFind::CalculateMap(Node * _initialNode, Node * _endingNode){
// Copiamos Posicion X,Y de nodos inicial y destino.
//m_InitialPosition.Initial_X = _initial.Initial_X;
//m_InitialPosition.Initial_Y = _initial.Initial_Y;
//m_EndingPosition.Ending_X = _ending.Ending_X;
//m_EndingPosition.Ending_Y = _ending.Ending_Y;
OpenNodes(_initialNode);
while (ExistOpenNodes()){
m_CurrentNode = LessValueNode();
if (IsEndingNode(m_CurrentNode)){
//GenerarCamino();
}
else {
CloseNode(m_CurrentNode);
OpenNodes(m_CurrentNode);
}
}
}
//-------------------------------------------------------------- | [
"calaverax@bb2752b8-1d7e-11de-9d52-39b120432c5d"
] | [
[
[
1,
84
]
]
] |
e26d12af72425b08369187d42732ce82d4a10cea | 709cd826da3ae55945fd7036ecf872ee7cdbd82a | /Term/WildMagic2/Source/Intersection/WmlIntrTri3Con3.cpp | a0d5a7f4353d6bec1785653a15cf4f674bd4a8f5 | [] | no_license | argapratama/kucgbowling | 20dbaefe1596358156691e81ccceb9151b15efb0 | 65e40b6f33c5511bddf0fa350c1eefc647ace48a | refs/heads/master | 2018-01-08 15:27:44 | 2011-06-19 15:23:39 | 2011-06-19 15:23:39 | 36,738,655 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,534 | cpp | // Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2003. All Rights Reserved
//
// The Wild Magic Library (WML) source code is supplied under the terms of
// the license agreement http://www.magic-software.com/License/WildMagic.pdf
// and may not be copied or disclosed except in accordance with the terms of
// that agreement.
#include "WmlIntrTri3Con3.h"
using namespace Wml;
//----------------------------------------------------------------------------
template <class Real>
bool Wml::TestIntersection (const Triangle3<Real>& rkTri,
const Cone3<Real>& rkCone)
{
// NOTE. The following quantities computed in this function can be
// precomputed and stored in the cone and triangle classes as an
// optimization.
// 1. The cone squared cosine.
// 2. The triangle squared edge lengths |E0|^2 and |E1|^2.
// 3. The third triangle edge E2 = E1 - E0 and squared length |E2|^2.
// 4. The triangle normal N = Cross(E0,E1) or unitized normal
// N = Cross(E0,E1)/Length(Cross(E0,E1)).
// triangle is <P0,P1,P2>, edges are E0 = P1-P0, E1=P2-P0
int iOnConeSide = 0;
Real fP0Test, fP1Test, fP2Test, fAdE, fEdE, fEdD, fC1, fC2;
Real fCosSqr = rkCone.CosAngle()*rkCone.CosAngle();
// test vertex P0
Vector3<Real> kDiff0 = rkTri.Origin() - rkCone.Vertex();
Real fAdD0 = rkCone.Axis().Dot(kDiff0);
if ( fAdD0 >= (Real)0.0 )
{
// P0 is on cone side of plane
fP0Test = fAdD0*fAdD0 - fCosSqr*(kDiff0.Dot(kDiff0));
if ( fP0Test >= (Real)0.0 )
{
// P0 is inside the cone
return true;
}
else
{
// P0 is outside the cone, but on cone side of plane
iOnConeSide |= 1;
}
}
// else P0 is not on cone side of plane
// test vertex P1
Vector3<Real> kDiff1 = kDiff0 + rkTri.Edge0();
Real fAdD1 = rkCone.Axis().Dot(kDiff1);
if ( fAdD1 >= (Real)0.0 )
{
// P1 is on cone side of plane
fP1Test = fAdD1*fAdD1 - fCosSqr*(kDiff1.Dot(kDiff1));
if ( fP1Test >= (Real)0.0 )
{
// P1 is inside the cone
return true;
}
else
{
// P1 is outside the cone, but on cone side of plane
iOnConeSide |= 2;
}
}
// else P1 is not on cone side of plane
// test vertex P2
Vector3<Real> kDiff2 = kDiff0 + rkTri.Edge1();
Real fAdD2 = rkCone.Axis().Dot(kDiff2);
if ( fAdD2 >= (Real)0.0 )
{
// P2 is on cone side of plane
fP2Test = fAdD2*fAdD2 - fCosSqr*(kDiff2.Dot(kDiff2));
if ( fP2Test >= (Real)0.0 )
{
// P2 is inside the cone
return true;
}
else
{
// P2 is outside the cone, but on cone side of plane
iOnConeSide |= 4;
}
}
// else P2 is not on cone side of plane
// test edge <P0,P1> = E0
if ( iOnConeSide & 3 )
{
fAdE = fAdD1 - fAdD0;
fEdE = rkTri.Edge0().Dot(rkTri.Edge0());
fC2 = fAdE*fAdE - fCosSqr*fEdE;
if ( fC2 < (Real)0.0 )
{
fEdD = rkTri.Edge0().Dot(kDiff0);
fC1 = fAdE*fAdD0 - fCosSqr*fEdD;
if ( iOnConeSide & 1 )
{
if ( iOnConeSide & 2 )
{
// <P0,P1> fully on cone side of plane, fC0 = fP0Test
if ( (Real)0.0 <= fC1 && fC1 <= -fC2
&& fC1*fC1 >= fP0Test*fC2 )
{
return true;
}
}
else
{
// P0 on cone side (Dot(A,P0-V) >= 0),
// P1 on opposite side (Dot(A,P1-V) <= 0)
// (Dot(A,E0) <= 0), fC0 = fP0Test
if ( (Real)0.0 <= fC1 && fC2*fAdD0 <= fC1*fAdE
&& fC1*fC1 >= fP0Test*fC2 )
{
return true;
}
}
}
else
{
// P1 on cone side (Dot(A,P1-V) >= 0),
// P0 on opposite side (Dot(A,P0-V) <= 0)
// (Dot(A,E0) >= 0), fC0 = fP0Test (needs calculating)
if ( fC1 <= -fC2 && fC2*fAdD0 <= fC1*fAdE )
{
fP0Test = fAdD0*fAdD0 - fCosSqr*(kDiff0.Dot(kDiff0));
if ( fC1*fC1 >= fP0Test*fC2 )
return true;
}
}
}
}
// else <P0,P1> does not intersect cone half space
// test edge <P0,P2> = E1
if ( iOnConeSide & 5 )
{
fAdE = fAdD2 - fAdD0;
fEdE = rkTri.Edge1().Dot(rkTri.Edge1());
fC2 = fAdE*fAdE - fCosSqr*fEdE;
if ( fC2 < (Real)0.0 )
{
fEdD = rkTri.Edge1().Dot(kDiff0);
fC1 = fAdE*fAdD0 - fCosSqr*fEdD;
if ( iOnConeSide & 1 )
{
if ( iOnConeSide & 4 )
{
// <P0,P2> fully on cone side of plane, fC0 = fP0Test
if ( (Real)0.0 <= fC1 && fC1 <= -fC2
&& fC1*fC1 >= fP0Test*fC2 )
{
return true;
}
}
else
{
// P0 on cone side (Dot(A,P0-V) >= 0),
// P2 on opposite side (Dot(A,P2-V) <= 0)
// (Dot(A,E1) <= 0), fC0 = fP0Test
if ( (Real)0.0 <= fC1 && fC2*fAdD0 <= fC1*fAdE
&& fC1*fC1 >= fP0Test*fC2 )
{
return true;
}
}
}
else
{
// P2 on cone side (Dot(A,P2-V) >= 0),
// P0 on opposite side (Dot(A,P0-V) <= 0)
// (Dot(A,E1) >= 0), fC0 = fP0Test (needs calculating)
if ( fC1 <= -fC2 && fC2*fAdD0 <= fC1*fAdE )
{
fP0Test = fAdD0*fAdD0 - fCosSqr*(kDiff0.Dot(kDiff0));
if ( fC1*fC1 >= fP0Test*fC2 )
return true;
}
}
}
}
// else <P0,P2> does not intersect cone half space
// test edge <P1,P2> = E1-E0 = E2
if ( iOnConeSide & 6 )
{
Vector3<Real> kE2 = rkTri.Edge1() - rkTri.Edge0();
fAdE = fAdD2 - fAdD1;
fEdE = kE2.Dot(kE2);
fC2 = fAdE*fAdE - fCosSqr*fEdE;
if ( fC2 < (Real)0.0 )
{
fEdD = kE2.Dot(kDiff1);
fC1 = fAdE*fAdD1 - fCosSqr*fEdD;
if ( iOnConeSide & 2 )
{
if ( iOnConeSide & 4 )
{
// <P1,P2> fully on cone side of plane, fC0 = fP1Test
if ( (Real)0.0 <= fC1 && fC1 <= -fC2
&& fC1*fC1 >= fP1Test*fC2 )
{
return true;
}
}
else
{
// P1 on cone side (Dot(A,P1-V) >= 0),
// P2 on opposite side (Dot(A,P2-V) <= 0)
// (Dot(A,E2) <= 0), fC0 = fP1Test
if ( (Real)0.0 <= fC1 && fC2*fAdD1 <= fC1*fAdE
&& fC1*fC1 >= fP1Test*fC2 )
{
return true;
}
}
}
else
{
// P2 on cone side (Dot(A,P2-V) >= 0),
// P1 on opposite side (Dot(A,P1-V) <= 0)
// (Dot(A,E2) >= 0), fC0 = fP1Test (needs calculating)
if ( fC1 <= -fC2 && fC2*fAdD1 <= fC1*fAdE )
{
fP1Test = fAdD1*fAdD1 - fCosSqr*(kDiff1.Dot(kDiff1));
if ( fC1*fC1 >= fP1Test*fC2 )
return true;
}
}
}
}
// else <P1,P2> does not intersect cone half space
// Test triangle <P0,P1,P2>. It is enough to handle only the case when
// at least one Pi is on the cone side of the plane. In this case and
// after the previous testing, if the triangle intersects the cone, the
// set of intersection must contain the point of intersection between
// the cone axis and the triangle.
if ( iOnConeSide > 0 )
{
Vector3<Real> kN = rkTri.Edge0().Cross(rkTri.Edge1());
Real fNdA = kN.Dot(rkCone.Axis());
Real fNdD = kN.Dot(kDiff0);
Vector3<Real> kU = fNdD*rkCone.Axis() - fNdA*kDiff0;
Vector3<Real> kNcU = kN.Cross(kU);
Real fNcUdE0 = kNcU.Dot(rkTri.Edge0()), fNcUdE1, fNcUdE2, fNdN;
if ( fNdA >= (Real)0.0 )
{
if ( fNcUdE0 <= (Real)0.0 )
{
fNcUdE1 = kNcU.Dot(rkTri.Edge1());
if ( fNcUdE1 >= (Real)0.0 )
{
fNcUdE2 = fNcUdE1 - fNcUdE0;
fNdN = kN.SquaredLength();
if ( fNcUdE2 <= fNdA*fNdN )
return true;
}
}
}
else
{
if ( fNcUdE0 >= (Real)0.0 )
{
fNcUdE1 = kNcU.Dot(rkTri.Edge1());
if ( fNcUdE1 <= (Real)0.0 )
{
fNcUdE2 = fNcUdE1 - fNcUdE0;
fNdN = kN.SquaredLength();
if ( fNcUdE2 >= fNdA*fNdN )
return true;
}
}
}
}
return false;
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// explicit instantiation
//----------------------------------------------------------------------------
namespace Wml
{
template WML_ITEM bool TestIntersection<float> (
const Triangle3<float>&, const Cone3<float>&);
template WML_ITEM bool TestIntersection<double> (
const Triangle3<double>&, const Cone3<double>&);
}
//----------------------------------------------------------------------------
| [
"pocatnas@gmail.com"
] | [
[
[
1,
301
]
]
] |
c7e21c79ce487e3bac74a8bd5a338c49635898f6 | 9df55ed98688ff13caec3061237a2a0895914577 | /main.cpp | bd29e05649bceeeba97307229ac0bcc781176516 | [] | no_license | tiashaun/sdl_tetris | f625ee0f06e642411f7a04b18b470aa0df61c1ca | 4799cfa4b28cd21b8431f8b6a00bacfb89e794f0 | refs/heads/master | 2020-11-30 23:32:43 | 2009-12-06 20:33:43 | 2009-12-06 20:33:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 165 | cpp | #include <iostream>
#include <SDL/SDL.h>
#include "Game.h"
int main(int argc, char* argv[]) {
Game *game = new Game();
game->startGame();
return 0;
}
| [
"jarod.luebbert@gmail.com"
] | [
[
[
1,
10
]
]
] |
c6ae62bae17c0ec324ca0aa0d67cbb08a72dce4d | b08e948c33317a0a67487e497a9afbaf17b0fc4c | /Display/Font.h | 03d4940ce4ff0bfd662810249e01fff5b4dea7da | [] | no_license | 15831944/bastionlandscape | e1acc932f6b5a452a3bd94471748b0436a96de5d | c8008384cf4e790400f9979b5818a5a3806bd1af | refs/heads/master | 2023-03-16 03:28:55 | 2010-05-21 15:00:07 | 2010-05-21 15:00:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,208 | h | #ifndef __FONT_H__
#define __FONT_H__
#include "../Display/Display.h"
namespace ElixirEngine
{
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
class DisplayFontText : public DisplayObject
{
public:
DisplayFontText();
virtual ~DisplayFontText();
virtual void SetText(const wstring& _wstrText) = 0;
virtual void SetColor(const Vector4& _f4Color) = 0;
};
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
class DisplayFont : public CoreObject
{
public:
DisplayFont(DisplayFontManagerRef _rFontManager);
virtual ~DisplayFont();
virtual DisplayFontTextPtr CreateText() = 0;
virtual void ReleaseText(DisplayFontTextPtr _pText) = 0;
virtual DisplayRef GetDisplay() = 0;
protected:
DisplayFontManagerRef m_rFontManager;
};
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
class DisplayFontLoader : public CoreObject
{
public:
DisplayFontLoader(DisplayFontManagerRef _rFontManager);
virtual ~DisplayFontLoader();
virtual DisplayFontPtr Load(const string& _strFileName) = 0;
virtual void Unload(DisplayFontPtr _pFont) = 0;
protected:
DisplayFontManagerRef m_rFontManager;
};
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
class DisplayFontManager : public CoreObject
{
public:
DisplayFontManager(DisplayRef _rDisplay);
virtual ~DisplayFontManager();
virtual bool Create(const boost::any& _rConfig);
virtual void Update();
virtual void Release();
bool Load(const Key& _uNameKey, const string& _strFileName);
void Unload(const Key& _uNameKey);
DisplayFontPtr Get(const Key& _uNameKey);
DisplayRef GetDisplay();
protected:
struct Link
{
Link();
Link(DisplayFontPtr _pFont, DisplayFontLoaderPtr _pLoader);
DisplayFontPtr m_pFont;
DisplayFontLoaderPtr m_pLoader;
};
typedef map<Key, Link> LinkMap;
protected:
bool RegisterLoader(const Key& _uExtensionKey, DisplayFontLoaderPtr _pLoader);
void UnregisterLoader(const Key& _uExtensionKey);
DisplayFontLoaderPtr GetLoader(const Key& _uExtensionKey);
protected:
DisplayRef m_rDisplay;
LinkMap m_mFonts;
DisplayFontLoaderPtrMap m_mLoaders;
};
}
#endif
| [
"voodoohaust@97c0069c-804f-11de-81da-11cc53ed4329"
] | [
[
[
1,
100
]
]
] |
83184b7823427dbb500e80b21cc18d05f9552848 | 406b4b18f5c58c689d2324f49db972377fe8feb6 | /ANE/Include/Memory/IMemoryPool.h | cd118b1a3cd79d2f003a329221fb47c1e0b00b8c | [] | no_license | Mobiwoom/ane | e17167de36699c451ed92eab7bf733e7d41fe847 | ec20667c556a99351024f3ae9c8880e944c5bfbd | refs/heads/master | 2021-01-17 13:09:57 | 2010-03-23 16:30:17 | 2010-03-23 16:30:17 | 33,132,357 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 258 | h | #pragma once
namespace Ane
{
class IMemoryPool
{
public:
IMemoryPool(){}
virtual ~IMemoryPool(){}
virtual void* Alloc() = 0;
virtual void* Alloc(unsigned int Size) = 0;
virtual void Free(void* pMemory) = 0;
};
} | [
"inthejm@5abed23c-1faa-11df-9e62-c93c6248c2ac"
] | [
[
[
1,
14
]
]
] |
01e8ec44b80deffdd92d33706685a9deabbffac3 | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/zombie/nscene/src/nscene/nsurfacenode_main.cc | 74d5e83ef12b4c20b501095b24518e59c6cfe3b1 | [] | no_license | ugozapad/TheZombieEngine | 832492930df28c28cd349673f79f3609b1fe7190 | 8e8c3e6225c2ed93e07287356def9fbdeacf3d6a | refs/heads/master | 2020-04-30 11:35:36 | 2011-02-24 14:18:43 | 2011-02-24 14:18:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,575 | cc | #include "precompiled/pchnscene.h"
//------------------------------------------------------------------------------
// nsurfacenode_main.cc
// (C) 2002 RadonLabs GmbH
//------------------------------------------------------------------------------
#include "nscene/nsurfacenode.h"
#include "nscene/nsceneshader.h"
#include "nscene/nscenegraph.h"
#include "nscene/nshadertree.h"
#include "gfx2/ngfxserver2.h"
#include "gfx2/nshader2.h"
#include "gfx2/ntexture2.h"
#include "kernel/ntimeserver.h"
#include "nscene/ncscene.h"
#include "entity/nentity.h"
#include "kernel/ndebug.h"
#include "nscene/nanimator.h"
nNebulaScriptClass(nSurfaceNode, "nabstractshadernode");
//------------------------------------------------------------------------------
/**
*/
nSurfaceNode::nSurfaceNode() :
shaderArray(4, 4)
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
nSurfaceNode::~nSurfaceNode()
{
this->UnloadResources();
}
//------------------------------------------------------------------------------
/**
Unload all shaders.
*/
void
nSurfaceNode::UnloadShaders()
{
int i;
for (i = 0; i < this->shaderArray.Size(); i++)
{
if (this->shaderArray[i].IsShaderValid())
{
this->shaderArray[i].GetShader()->Release();
this->shaderArray[i].Invalidate();
}
}
for (i = 0; i < this->shaderTreeArray.Size(); ++i)
{
if (this->shaderTreeArray[i].isvalid())
{
this->shaderTreeArray[i]->Release();
this->shaderTreeArray[i].invalidate();
}
}
}
//------------------------------------------------------------------------------
/**
Load shader resources.
*/
bool
nSurfaceNode::LoadShaders()
{
// load shaders
int i;
for (i = 0; i < this->shaderArray.Size(); i++)
{
ShaderEntry& shaderEntry = this->shaderArray[i];
if (!shaderEntry.IsShaderValid() && shaderEntry.GetName())
{
#if 0 // keep this commented while the shader database is not used
// try to get shader by name from shader repository
int shaderIndex = nSceneServer::Instance()->FindShader(shaderEntry.GetName());
if (shaderIndex != -1)
{
nSceneShader& sceneShader = nSceneServer::Instance()->GetShaderAt(shaderIndex);
if (!sceneShader.IsValid())
{
sceneShader.Validate();
n_assert(sceneShader.IsValid());
}
sceneShader.GetShaderObject()->AddRef();
shaderEntry.SetShaderIndex(shaderIndex);
shaderEntry.SetShader(sceneShader.GetShaderObject());
}
else
#endif
{
// create a new empty shader object
nShader2* shd = nGfxServer2::Instance()->NewShader(shaderEntry.GetName());
n_assert(shd);
if (!shd->IsLoaded())
{
// load shader resource file
shd->SetFilename(shaderEntry.GetName());
}
if (shd)
{
// register shader object in scene shader database
nSceneShader sceneShader;
sceneShader.SetShader(shaderEntry.GetName());// filename
sceneShader.SetShaderName(shaderEntry.GetName());// shader name
int shaderIndex = nSceneServer::Instance()->FindShader(shaderEntry.GetName());
if (shaderIndex == -1)
{
shaderIndex = nSceneServer::Instance()->AddShader(sceneShader);
n_assert(shaderIndex != -1);
}
// set shader object and index for local entry
shaderEntry.SetShader(shd);
shaderEntry.shaderIndex = shaderIndex;
// create a degenerate decision tree for use in the render path
nShaderTree* shaderTree = static_cast<nShaderTree*>( kernelServer->New("nshadertree") );
n_assert( shaderTree );
shaderTree->BeginNode( nVariable::InvalidHandle, 0 );
shaderTree->SetShaderObject( shd );
shaderTree->SetShaderIndexAt( 0, shaderIndex );
shaderTree->EndNode();
this->shaderTreeArray.Set( shaderEntry.GetPassIndex(), shaderTree );
}
}
}
}
return true;
}
//------------------------------------------------------------------------------
/**
Load the resources needed by this object.
*/
bool
nSurfaceNode::LoadResources()
{
if (this->LoadShaders())
{
if (nAbstractShaderNode::LoadResources())
{
return true;
}
}
return false;
}
//------------------------------------------------------------------------------
/**
Unload the resources if refcount has reached zero.
*/
void
nSurfaceNode::UnloadResources()
{
nAbstractShaderNode::UnloadResources();
this->UnloadShaders();
}
//------------------------------------------------------------------------------
/**
Find shader object associated with fourcc code.
*/
nSurfaceNode::ShaderEntry*
nSurfaceNode::FindShaderEntry(nFourCC fourcc) const
{
int i;
int numShaders = this->shaderArray.Size();
for (i = 0; i < numShaders; i++)
{
ShaderEntry& shaderEntry = this->shaderArray[i];
if (shaderEntry.GetFourCC() == fourcc)
{
return &shaderEntry;
}
}
// fallthrough: no loaded shader matches this fourcc code
return 0;
}
//------------------------------------------------------------------------------
/**
Return number of levels.
*/
int
nSurfaceNode::GetNumLevels()
{
return (this->shaderArray.Size() > 0) ? 1 : 0;
}
//------------------------------------------------------------------------------
/**
Return number of passes for a level
*/
int
nSurfaceNode::GetNumLevelPasses(int /*level*/)
{
return this->shaderArray.Size();
}
//------------------------------------------------------------------------------
/**
Return number of passes for a level
*/
int
nSurfaceNode::GetLevelPassIndex(int level, int pass)
{
n_assert_return((level == 0) && (pass < this->shaderArray.Size()), -1);
return this->shaderArray[pass].GetPassIndex();
}
//------------------------------------------------------------------------------
/**
*/
nShaderTree*
nSurfaceNode::GetShaderTree(int /*level*/, int passIndex)
{
n_assert(passIndex < this->shaderTreeArray.Size());
return this->shaderTreeArray[passIndex];
}
//------------------------------------------------------------------------------
/**
*/
void
nSurfaceNode::SetShader(nFourCC fourcc, const char* name)
{
n_assert(name);
ShaderEntry* shaderEntry = this->FindShaderEntry(fourcc);
if (shaderEntry)
{
shaderEntry->Invalidate();
shaderEntry->SetName(name);
}
else
{
ShaderEntry newShaderEntry(fourcc, name);
this->shaderArray.Append(newShaderEntry);
}
}
//------------------------------------------------------------------------------
/**
*/
const char*
nSurfaceNode::GetShader(nFourCC fourcc) const
{
ShaderEntry* shaderEntry = this->FindShaderEntry(fourcc);
if (shaderEntry)
{
return shaderEntry->GetName();
}
else
{
return 0;
}
}
//------------------------------------------------------------------------------
/**
*/
bool
nSurfaceNode::IsTextureUsed(nShaderState::Param /*param*/)
{
#if 0
// check in all shaders if anywhere the texture specified by param is used
int i;
int numShaders = this->shaderArray.Size();
for (i = 0; i < numShaders; i++)
{
const ShaderEntry& shaderEntry = this->shaderArray[i];
// first be sure that the shader entry could be loaded
if (shaderEntry.IsShaderValid())
{
nShader2* shader = shaderEntry.GetShader();
if (shader->IsParameterUsed(param))
{
return true;
}
}
}
// fallthrough: texture not used by any shader
return false;
#else
return true;
#endif
}
//------------------------------------------------------------------------------
/**
Setup shader attributes before rendering instances of this scene node.
FIXME
*/
bool
nSurfaceNode::Apply(nSceneGraph* sceneGraph)
{
n_assert(sceneGraph);
int shaderIndex = sceneGraph->GetShaderIndex();
if (shaderIndex != -1)
{
nSceneShader& sceneShader = nSceneServer::Instance()->GetShaderAt(shaderIndex);
nGfxServer2::Instance()->SetShader(sceneShader.GetShaderObject());
nAbstractShaderNode::Apply(sceneGraph);
return true;
}
return false;
}
//------------------------------------------------------------------------------
/**
Update shader and set as current shader in the gfx server.
- 15-Jan-04 floh AreResourcesValid()/LoadResources() moved to scene server
*/
bool
nSurfaceNode::Render(nSceneGraph* sceneGraph, nEntityObject* entityObject)
{
n_assert(sceneGraph);
n_assert(entityObject);
//nShader2* shader = nSceneServer::Instance()->GetShaderAt(sceneGraph->GetShaderIndex()).GetShaderObject();
// invoke shader manipulators
this->InvokeAnimators(entityObject);
/*
//nGfxServer2* gfxServer = nGfxServer2::Instance();
// set texture transforms (that can be animated)
//n_assert(nGfxServer2::MaxTextureStages >= 4);
static matrix44 m;
this->textureTransform[0].getmatrix44(m);
gfxServer->SetTransform(nGfxServer2::Texture0, m);
this->textureTransform[1].getmatrix44(m);
gfxServer->SetTransform(nGfxServer2::Texture1, m);
*/
// transfer the rest of per-instance (animated, overriden) parameters
// per instance-set parameters are handled at Apply()
// also, shader overrides are handled at nGeometryNode::Render()
nAbstractShaderNode::Render(sceneGraph, entityObject);
return true;
}
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
] | [
[
[
1,
353
]
]
] |
4bd2d3863e213b995ce4c797f69651b760fb6ceb | be0db8bf2276da4b71a67723bbe8fb75e689bacb | /Src/App/init.cpp | d888c01b5df8390fb58162ef1efbd36db997300d | [] | no_license | jy02140486/cellwarfare | 21a8eb793b94b8472905d793f4b806041baf57bb | 85f026efd03f12dd828817159b9821eff4e4aff0 | refs/heads/master | 2020-12-24 15:22:58 | 2011-07-24 12:36:45 | 2011-07-24 12:36:45 | 32,970,508 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,030 | cpp | #include "app.h"
#include "event.h"
#include <time.h>
bool T_App::init()
{
try
{
//initail window description
mWinDesc.set_title("CellWarfare");
mWinDesc.set_allow_resize(true);
mWinDesc.set_size(CL_Size (800, 600), false);
CL_String resource("../Res/GUITheme/resources.xml");
CL_String theme("../Res/GUITheme/theme.css");
//initail resource manager
mResManager.load(resource);
////initail gui theme
mGUITheme.set_resources(mResManager);
//initail gui
mpDisplayWindow = new CL_DisplayWindow(mWinDesc);
mpWinManager = new CL_GUIWindowManagerTexture(*mpDisplayWindow);
mGui.set_window_manager(*mpWinManager);
mGui.set_theme(mGUITheme);
mGui.set_css_document(theme);
mpWinManager->func_repaint().set(this, &T_App::render);
//initail GUIComponet window
CL_DisplayWindowDescription comWindowDesc;
comWindowDesc.show_border(false);
comWindowDesc.set_allow_resize(true);
comWindowDesc.set_title("settings");
comWindowDesc.set_size(CL_Size(300, 570),false);
comWindowDesc.set_allow_resize(true);
comWindowDesc.set_layered(true);
mpComWindow = new CL_Window(&mGui, comWindowDesc);
mpComWindow->set_draggable(false);
//initail events
mInput = mpDisplayWindow->get_ic();
mKeyboard = mInput.get_keyboard();
mMouse = mInput.get_mouse();
//mJoystick = mInput.get_joystick();
mpConsole = new CL_ConsoleWindow("Console", 80, 100);
entites=new EM();
entites->iniLVs();
words=new CL_Font(mpComWindow->get_gc(),"Tahoma",20);
offset.x=320;
offset.y=420;
entites->initScrObjs();
body=new CL_Image(mpDisplayWindow->get_gc(),"../res/body.png");
stage_clear=new CL_Image(mpDisplayWindow->get_gc(),"../res/stage clear.png");
if(RandomVal::randombool())
gameover=new CL_Image(mpDisplayWindow->get_gc(),"../res/gameover2.png");
else
gameover=new CL_Image(mpDisplayWindow->get_gc(),"../res/gameover.png");
all_clear=new CL_Image(mpDisplayWindow->get_gc(),"../res/allclear.png");
//init menu items
mx=new CL_LineEdit(mpComWindow);
mx->set_geometry(CL_Rect(40,40, CL_Size(80, 20)));
my=new CL_LineEdit(mpComWindow);
my->set_geometry(CL_Rect(40,80, CL_Size(80, 20)));
cirfirm=new CL_PushButton(mpComWindow);
cirfirm->set_text("enter");
cirfirm->set_geometry(CL_Rect(40,500, CL_Size(150, 30)));
cirfirm->func_clicked().set(this,&T_App::ButtonClick);
PainKiller=new CL_PushButton(mpComWindow);
PainKiller->set_text("PainKiller");
PainKiller->set_geometry(CL_Rect(40,540, CL_Size(100, 20)));
PainKiller->func_clicked().set(this,&T_App::takePill);
CL_Point lboffset(10,10);
CL_Size sspin(80,20);
CL_Size slb(80,20);
infoBF=new CL_Label(mpComWindow);
infoBF->set_geometry(CL_Rect(10,110, CL_Size(290, 300)));
infoBF->set_text("infobf");
infoBF->set_visible(false);
lbcellsdeployed=new CL_Label(infoBF);
lbcellsdeployed->set_geometry(CL_Rect(lboffset.x,lboffset.y+5, slb));
lbcellsdeployed->set_text("Cells deployed");
cellsdeployed=new CL_Spin(infoBF);
cellsdeployed->set_geometry(CL_Rect(lboffset.x+80,lboffset.y, sspin));
cellsdeployed->set_step_size(1);
cellsdeployed->set_ranges(0,100);
cellsdeployed->set_value(entites->curLV->defbfs[0].ImmunityPoints);
lbintruders=new CL_Label(infoBF);
lbintruders->set_geometry(CL_Rect(lboffset.x,lboffset.y+35, slb));
lbintruders->set_text("Intruders");
intruders=new CL_Spin(infoBF);
intruders->set_geometry(CL_Rect(lboffset.x+80,lboffset.y+30, sspin));
lbtimeleft=new CL_Label(infoBF);
lbtimeleft->set_geometry(CL_Rect(lboffset.x,lboffset.y+65, slb));
lbtimeleft->set_text("Time left");
timeleft=new CL_ProgressBar(infoBF);
timeleft->set_geometry(CL_Rect(lboffset.x+80,lboffset.y+65, slb));
timeleft->set_min(0);
timeleft->set_max(40);
timeleft->set_position(20);
SendingCirfirm=new CL_PushButton(infoBF);
SendingCirfirm->set_geometry(CL_Rect(lboffset.x,lboffset.y+95, slb));
SendingCirfirm->set_text("Send");
SendingCirfirm->func_clicked().set(this,&T_App::OnSendingCirfirmClick);
//tatical layer
TaticalBoard=new CL_Label(mpComWindow);
TaticalBoard->set_geometry(CL_Rect(10,310, CL_Size(290, 200)));
TaticalBoard->set_text("TaticalBoard");
TaticalBoard->set_visible(true);
// TaticalBoard->set_constant_repaint(true);
lbTcellsdeployed=new CL_Label(TaticalBoard);
lbTcellsdeployed->set_geometry(CL_Rect(lboffset.x,lboffset.y+5, slb));
lbTcellsdeployed->set_text("Cells deployed");
lbTcellsdeployed->set_visible(true);
Tcellsdeployed=new CL_Label(TaticalBoard);
Tcellsdeployed->set_geometry(CL_Rect(lboffset.x+100,lboffset.y+5, slb));
Tcellsdeployed->set_text("Cells deployed");
Tcellsdeployed->set_visible(true);
lbTintruders=new CL_Label(TaticalBoard);
lbTintruders->set_geometry(CL_Rect(lboffset.x,lboffset.y+15, slb));
lbTintruders->set_text("Itruders");
lbTintruders->set_visible(true);
Tintruders=new CL_Label(TaticalBoard);
Tintruders->set_geometry(CL_Rect(lboffset.x+100,lboffset.y+15, slb));
Tintruders->set_text("Itruders");
Tintruders->set_visible(true);
entites->hero->eventTimer->func_expired().set(this,&T_App::invading_LogicLayer_Failure);
entites->hero->eventTimer->begin(true);
//LibDebugOnConsole();
time(&Atime);
}
catch (CL_Exception &exception)
{
CL_Console::write_line("Exception:Init error",
exception.get_message_and_stack_trace());
// mpConsole->display_close_message();
CL_Console::write_line(exception.get_message_and_stack_trace());
return true;
}
running=true;
T_Event::eventInit();
T_App::eventInit();
// slotMouseDown = mMouse.sig_key_down().connect(this,
// &T_App::onMouseDown);
return true;
}
void T_App::OnSendingCirfirmClick()
{
if (entites->SOselected!=NULL)
{
entites->SOselected->datas->ImmunityPoints+=cellsdeployed->get_value();
if (entites->hero->ImmunityPoints->minusable(cellsdeployed->get_value()))
{
entites->hero->ImmunityPoints->minus(cellsdeployed->get_value());
}
}
} | [
"jy02140486@gmail.com@7e182df5-b8f1-272d-db4e-b61a9d634eb1"
] | [
[
[
1,
198
]
]
] |
c94152890c940b22bdb79f243c4f1585d5936f63 | 024d621c20595be82b4622f534278009a684e9b7 | /SupportPosCalculator.h | a5e6a26a02bc832a3e52b38065da83d11c7d94e0 | [] | no_license | tj10200/Simple-Soccer | 98a224c20b5e0b66f0e420d7c312a6cf6527069b | 486a4231ddf66ae5984713a177297b0f9c83015f | refs/heads/master | 2021-01-19 09:02:02 | 2011-03-15 01:38:15 | 2011-03-15 01:38:15 | 1,480,980 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,396 | h | #ifndef SUPPORTING_POS_CALCULATOR_H
#define SUPPORTING_POS_CALCULATOR_H
#include "GameHeaders.h"
#include "Player.h"
class SupportPosCalculator
{
private:
D3DXVECTOR2 **regions,
goal,
RegSize;
Player *teammate,
*oppTeam,
*ballCarrier;
int rows,
cols,
numPlayers,
homeTeamIdxOffset;
double **passPotential,
**goalPotential,
**supportRegions,
**distValue;
bool regionsAvail;
void passPotentialCalc ();
void goalPotentialCalc ();
void distFromAttackerCalc();
void setBallCarrier ();
public:
SupportPosCalculator (D3DXVECTOR2 **Regs, D3DXVECTOR2 Goal, Player *sameTeam,
Player *opposing, int RegRows, int RegCols,
int players, bool isHomeTeam, int regOffset){
regions = Regs;
goal = Goal;
teammate = sameTeam;
oppTeam = opposing;
passPotential = new double *[RegRows];
goalPotential = new double *[RegRows];
supportRegions = new double *[RegRows];
distValue = new double *[RegRows];
for (int x = 0; x < RegRows; x++)
{
passPotential[x] = new double [RegCols];
goalPotential[x] = new double [RegCols];
supportRegions[x]= new double [RegCols];
distValue[x] = new double [RegCols];
}
rows = RegRows;
cols = RegCols;
numPlayers = players;
homeTeamIdxOffset = regOffset;
regionsAvail = false;
}
D3DXVECTOR2 getBestSupportPos ();
double getPassPotential ( int regX,
int regY);
double getGoalPotential ( int regX,
int regY);
Player *getClosestTeammate ( Player p,
Player *team);
Player *getClosestToTgt ( Player *team,
D3DXVECTOR2 tgt);
D3DXVECTOR2 getGoalShot ( Player *p);
D3DXVECTOR2 getPassShot ( Player *p,
Player *team);
void calcSupportingRegions ( Player *ballCarrier);
D3DXVECTOR2 getSupportPos ( Player *p,
Player *ball);
bool isShotSafe ( D3DXVECTOR2 startLoc,
D3DXVECTOR2 endLoc);
};
#endif
| [
"tjjohnson10200@gmail.com"
] | [
[
[
1,
84
]
]
] |
a895c5eb6bec1153d70cf30ce6fc9a001a90652b | 1e976ee65d326c2d9ed11c3235a9f4e2693557cf | /CommonSources/TransmitterPattern/Transmitter.h | a7656b3abfc3434e8609eb6ac9d03591993fcc53 | [] | no_license | outcast1000/Jaangle | 062c7d8d06e058186cb65bdade68a2ad8d5e7e65 | 18feb537068f1f3be6ecaa8a4b663b917c429e3d | refs/heads/master | 2020-04-08 20:04:56 | 2010-12-25 10:44:38 | 2010-12-25 10:44:38 | 19,334,292 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,349 | h | // /*
// *
// * Copyright (C) 2003-2010 Alexandros Economou
// *
// * This file is part of Jaangle (http://www.jaangle.com)
// *
// * This Program is free software; you can redistribute it and/or modify
// * it under the terms of the GNU General Public License as published by
// * the Free Software Foundation; either version 2, or (at your option)
// * any later version.
// *
// * This Program is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU General Public License for more details.
// *
// * You should have received a copy of the GNU General Public License
// * along with GNU Make; see the file COPYING. If not, write to
// * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
// * http://www.gnu.org/copyleft/gpl.html
// *
// */
#pragma once
#define MSG_TRANSMITTER_QUIT 0
class MessageDetails
{
public:
virtual ~MessageDetails() {}
};
class Receiver
{
public:
virtual void OnMessage(UINT msgID, LPVOID sender, MessageDetails* detail) = 0;
#ifdef _DEBUG
virtual LPCTSTR GetReceiverName() = 0;
#endif
};
class Transmitter
{
public:
virtual ~Transmitter() {}
virtual void RegisterReceiver(Receiver& receiver) = 0;
virtual void UnRegisterReceiver(Receiver& receiver) = 0;
//===SendMessage
//Sends a message directly to the Registered Receivers
//- msgID: The App-Defined Identification of the message. *value 0 is reserved
//- sender: [Optional]The sender of the message.
//- detail: [Optional] Details for the message.
// The receiver must be able to cast the derived MessageDetain through the ID
virtual void SendMessage(UINT msgID,
LPVOID sender = NULL, MessageDetails* detail = NULL) = 0;
//===PostMessage
//Queues the message in a storage. The message is being send in the next Heartbeat.
//Extra options
//- bGroupSimilar. Similar msgIDs may be grouped in one.
virtual void PostMessage(UINT msgID,
LPVOID sender = NULL, MessageDetails* detail = NULL,
BOOL bGroupSimilar = FALSE) = 0;
//===HeartBeat
//- Posted Messages are send when HeartBeat is called
virtual void HeartBeat() = 0;
};
| [
"outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678"
] | [
[
[
1,
68
]
]
] |
64ceb84bfde0c56e82627a9bac15d50b077eed63 | da32684647cac4dcdbb60db49496eb8d10a8ea6d | /Deadbeef/Classes/Box2D/Dynamics/b2Fixture.cpp | bb4ea5470d16a4bdaf17bc5606c94777b0d6c807 | [] | no_license | jweinberg/deadbeef | a1f10bc37de3aee5ac6b5953d740be9990083246 | 8126802454ff5815a7a55feae82e80d026a89726 | refs/heads/master | 2016-09-06 06:13:46 | 2010-06-18 21:51:07 | 2010-06-18 21:51:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,173 | cpp | /*
* Copyright (c) 2006-2009 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.
*/
#include "b2Fixture.h"
#include "Contacts/b2Contact.h"
#include "../Collision/Shapes/b2CircleShape.h"
#include "../Collision/Shapes/b2PolygonShape.h"
#include "../Collision/b2BroadPhase.h"
#include "../Collision/b2Collision.h"
#include "../Common/b2BlockAllocator.h"
b2Fixture::b2Fixture()
{
m_userData = NULL;
m_body = NULL;
m_next = NULL;
m_proxyId = b2BroadPhase::e_nullProxy;
m_shape = NULL;
m_density = 0.0f;
m_physicsSprite = NULL;
}
b2Fixture::~b2Fixture()
{
b2Assert(m_shape == NULL);
b2Assert(m_proxyId == b2BroadPhase::e_nullProxy);
}
void b2Fixture::Create(b2BlockAllocator* allocator, b2Body* body, const b2FixtureDef* def)
{
m_userData = def->userData;
m_friction = def->friction;
m_restitution = def->restitution;
m_body = body;
m_next = NULL;
m_filter = def->filter;
m_isSensor = def->isSensor;
m_isMagnetic = def->isMagnetic;
m_shape = def->shape->Clone(allocator);
m_density = def->density;
}
void b2Fixture::Destroy(b2BlockAllocator* allocator)
{
// The proxy must be destroyed before calling this.
b2Assert(m_proxyId == b2BroadPhase::e_nullProxy);
// Free the child shape.
switch (m_shape->m_type)
{
case b2Shape::e_circle:
{
b2CircleShape* s = (b2CircleShape*)m_shape;
s->~b2CircleShape();
allocator->Free(s, sizeof(b2CircleShape));
}
break;
case b2Shape::e_polygon:
{
b2PolygonShape* s = (b2PolygonShape*)m_shape;
s->~b2PolygonShape();
allocator->Free(s, sizeof(b2PolygonShape));
}
break;
default:
b2Assert(false);
break;
}
m_shape = NULL;
}
void b2Fixture::CreateProxy(b2BroadPhase* broadPhase, const b2Transform& xf)
{
b2Assert(m_proxyId == b2BroadPhase::e_nullProxy);
// Create proxy in the broad-phase.
m_shape->ComputeAABB(&m_aabb, xf);
m_proxyId = broadPhase->CreateProxy(m_aabb, this);
}
void b2Fixture::DestroyProxy(b2BroadPhase* broadPhase)
{
if (m_proxyId == b2BroadPhase::e_nullProxy)
{
return;
}
// Destroy proxy in the broad-phase.
broadPhase->DestroyProxy(m_proxyId);
m_proxyId = b2BroadPhase::e_nullProxy;
}
void b2Fixture::Synchronize(b2BroadPhase* broadPhase, const b2Transform& transform1, const b2Transform& transform2)
{
if (m_proxyId == b2BroadPhase::e_nullProxy)
{
return;
}
// Compute an AABB that covers the swept shape (may miss some rotation effect).
b2AABB aabb1, aabb2;
m_shape->ComputeAABB(&aabb1, transform1);
m_shape->ComputeAABB(&aabb2, transform2);
m_aabb.Combine(aabb1, aabb2);
b2Vec2 displacement = transform2.position - transform1.position;
broadPhase->MoveProxy(m_proxyId, m_aabb, displacement);
}
void b2Fixture::SetFilterData(const b2Filter& filter)
{
m_filter = filter;
if (m_body == NULL)
{
return;
}
// Flag associated contacts for filtering.
b2ContactEdge* edge = m_body->GetContactList();
while (edge)
{
b2Contact* contact = edge->contact;
b2Fixture* fixtureA = contact->GetFixtureA();
b2Fixture* fixtureB = contact->GetFixtureB();
if (fixtureA == this || fixtureB == this)
{
contact->FlagForFiltering();
}
edge = edge->next;
}
}
void b2Fixture::SetSensor(bool sensor)
{
m_isSensor = sensor;
}
| [
"bhelgeland@9c1d8119-421d-44e4-8328-69b580a11e1d"
] | [
[
[
1,
165
]
]
] |
1b4652ce09bd2c88b5d27ad38a58c0cb9df76eec | 59166d9d1eea9b034ac331d9c5590362ab942a8f | /ParticlePlayer/MainNode/UpdClbkMainNode.cpp | 2c608e342c584f67905f27aeec17af4b43872bf5 | [] | no_license | seafengl/osgtraining | 5915f7b3a3c78334b9029ee58e6c1cb54de5c220 | fbfb29e5ae8cab6fa13900e417b6cba3a8c559df | refs/heads/master | 2020-04-09 07:32:31 | 2010-09-03 15:10:30 | 2010-09-03 15:10:30 | 40,032,354 | 0 | 3 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 3,004 | cpp | #include "UpdClbkMainNode.h"
#include "KeyboardState.h"
#include "CameraState.h"
#include <osg/Math>
#include <iostream>
UpdClbkMainNode::UpdClbkMainNode() : m_fMoveSpeed( 0.0 )
{
}
void UpdClbkMainNode::operator()( osg::Node* node, osg::NodeVisitor* nv )
{
//обработать вращения
ProcessRotate();
//обработать перемещение
ProcessMove();
// first update subgraph to make sure objects are all moved into position
traverse(node,nv);
}
void UpdClbkMainNode::ProcessRotate()
{
//обработать вращения
//получить доступ к состоянию клавиатуры
binEvents &mEvents = KeyboardState::Instance().GetEvents();
//получить доступ к состоянию камеры
binCameraState &mCamState = CameraState::Instance().GetCameraState();
mCamState.m_dR = mCamState.m_dR + mEvents.m_dX * 0.5;
mCamState.m_dH = mCamState.m_dH + mEvents.m_dY * 0.5;
//ограничение диапазона углов
if ( mCamState.m_dH > 360.0 )
mCamState.m_dH -= 360.0;
else
if ( mCamState.m_dH < -360.0 )
mCamState.m_dH += 360.0;
if ( mCamState.m_dR > 360.0 )
mCamState.m_dR -= 360.0;
else
if ( mCamState.m_dR < -360.0 )
mCamState.m_dR += 360.0;
}
void UpdClbkMainNode::ProcessMove()
{
//обработать перемещение
//получить доступ к состоянию клавиатуры
binEvents &mEvents = KeyboardState::Instance().GetEvents();
if ( mEvents.m_bLeft )
//перемещение камеры вперед
MoveForward();
else
if ( mEvents.m_bRight )
//перемещение камеры назад
MoveBackward();
}
void UpdClbkMainNode::MoveForward()
{
//перемещение камеры вперед
//получить доступ к состоянию камеры
binCameraState &mCamState = CameraState::Instance().GetCameraState();
double dZ = cos( osg::DegreesToRadians( -mCamState.m_dH + 90.0 ) );
double nD = sqrt( 1.0 - dZ * dZ );
double dX = -nD * sin( osg::DegreesToRadians( mCamState.m_dR ) );
double dY = -nD * cos( osg::DegreesToRadians( mCamState.m_dR ) );
mCamState.m_dX += dX * 0.01;
mCamState.m_dY += dY * 0.01;
mCamState.m_dZ += dZ * 0.01;
std::cout << mCamState.m_dY << " ";
}
void UpdClbkMainNode::MoveBackward()
{
//перемещение камеры назад
//получить доступ к состоянию камеры
binCameraState &mCamState = CameraState::Instance().GetCameraState();
double dZ = -cos( osg::DegreesToRadians( -mCamState.m_dH + 90.0 ) );
double nD = sqrt( 1.0 - dZ * dZ );
double dX = nD * sin( osg::DegreesToRadians( mCamState.m_dR ) );
double dY = nD * cos( osg::DegreesToRadians( mCamState.m_dR ) );
mCamState.m_dX += dX * 0.01;
mCamState.m_dY += dY * 0.01;
mCamState.m_dZ += dZ * 0.01;
std::cout << mCamState.m_dY << " ";
}
| [
"asmzx79@3290fc28-3049-11de-8daa-cfecb5f7ff5b"
] | [
[
[
1,
108
]
]
] |
cb40a5319f9a5c372afccc7dfbd3157cea518a56 | 075043812c30c1914e012b52c60bc3be2cfe49cc | /src/SDLGUIlibTests/SDL_Fixture.h | b7fee6cd1013f277ad13175a51caadc584545e0f | [] | no_license | Luke-Vulpa/Shoko-Rocket | 8a916d70bf777032e945c711716123f692004829 | 6f727a2cf2f072db11493b739cc3736aec40d4cb | refs/heads/master | 2020-12-28 12:03:14 | 2010-02-28 11:58:26 | 2010-02-28 11:58:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 746 | h | #pragma once
#include <sdl.h>
#include <iostream>
#include <Widget.h>
struct SDL_fixture
{
bool SDL_init_ok;
SDL_Surface* screen;
SDL_fixture()
{
SDL_init_ok = true;
int init_result;
if((init_result = SDL_Init(SDL_INIT_VIDEO)) != 0)
{
SDL_init_ok = false;
std::cout << "Error starting SDL\n" << init_result << "\n";
}
else
{
screen = SDL_SetVideoMode(640, 480, 32, SDL_DOUBLEBUF | SDL_HWSURFACE);
if(!screen)
{
SDL_init_ok = false;
std::cout << "Error starting SDL\n";
}else
{
// std::cout << "Starting SDL\n";
}
}
}
~SDL_fixture()
{
if(SDL_init_ok)
{
SDL_Quit();
//std::cout << "Shutting down SDL\n";
}
Widget::ClearRoot();
}
}; | [
"danishcake@hotmail.com"
] | [
[
[
1,
42
]
]
] |
ca47830e3446012cd8c35fb4140f006594e89045 | 3ac8c943b13d943fbd3b92787e40aa5519460a32 | /Source/IPC/Semaphore.cpp | 902ca06f146c6ecf022dfd6531720f5a1c7010ff | [
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | locosoft1986/Microkernel-1 | 8069bd2be390d6d8ad10f73e8a944112a764a401 | c9dfeec4581d4dd8b1e9020adb3778ad78b3e525 | refs/heads/master | 2021-01-24 04:54:08 | 2010-09-23 19:38:01 | 2010-09-23 19:38:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,142 | cpp | #include <IPC/Semaphore.h>
Semaphore::Semaphore(unsigned int atom)
{
atomic = atom;
}
Semaphore::~Semaphore()
{
}
Semaphore &Semaphore::operator =(const Semaphore &x)
{
atomic = x.atomic;
return *this;
}
unsigned int Semaphore::operator +=(unsigned int x)
{
return __sync_add_and_fetch(&atomic, x);
}
unsigned int Semaphore::operator -=(unsigned int x)
{
return __sync_sub_and_fetch(&atomic, x);
}
unsigned int Semaphore::operator |=(unsigned int x)
{
return __sync_or_and_fetch(&atomic, x);
}
unsigned int Semaphore::operator &=(unsigned int x)
{
return __sync_and_and_fetch(&atomic, x);
}
unsigned int Semaphore::operator ^=(unsigned int x)
{
return __sync_xor_and_fetch(&atomic, x);
}
bool Semaphore::operator ==(const Semaphore &x)
{
return (x.atomic == this->atomic);
}
bool Semaphore::operator !=(const Semaphore &x)
{
return !(*this == x);
}
Semaphore::operator unsigned int () const
{
return atomic;
}
bool Semaphore::CompareAndSwap(unsigned int oldValue, unsigned int newValue)
{
return __sync_bool_compare_and_swap(&atomic, oldValue, newValue);
}
| [
"edward.neal@gmail.com"
] | [
[
[
1,
61
]
]
] |
63601d52d33c9d54071905905b58be453a896972 | 992d3f90ab0f41ca157000c4b18d071087d14d85 | /draw/CPPCODER.CPP | df1cbad125fdc62a8c9606dc67eae4e1c7b1039d | [] | no_license | axemclion/visionizzer | cabc53c9be41c07c04436a4733697e4ca35104e3 | 5b0158f8a3614e519183055e50c27349328677e7 | refs/heads/master | 2020-12-25 19:04:17 | 2009-05-22 14:44:53 | 2009-05-22 14:44:53 | 29,331,323 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,855 | cpp | # include <process.h>
# include <graphics.h>
# include <dos.h>
# include <stdio.h>
# include <ctype.h>
# include <stdlib.h>
# include <string.h>
# include <dir.h>
# include <conio.h>
# include <mouse.h>
int fc(char *file1,char *file2,char *dest);
void ccoder(char *);
int main(int argc,char *argv[])
{
if (argc < 1)
return 1;
ccoder(argv[1]);
char path[100],path1[100];
strcpy(path,argv[1]);
strcpy(path1,path);
strcat(path1,"prog.java");
fc("code.cpp",NULL,path1);
strcpy(path1,path);
strcat(path1,"code.h");
remove(path1);
remove("head");
fc("head","code.tmp",path1);
remove("head");
FILE *fp = fopen("end.bat","wt");
fprintf(fp,"cls");
fclose(fp);
strcpy(path1,path);
return 0;
}
void ccoder(char *path)
{
char object[100];
remove("code.cpp");
strcat(path,"\\");
char *path1 =(char *)calloc(1,100);
#ifdef AXE
printf("%s",path);
getch();getch();
click();
# endif
char *name;
if (!path1)
return;
strcpy(path1,path);
FILE *fp,*prog,*draw;
strcat(path1,"code.cpp");
prog=fopen("code.cpp","wt");
if (prog == NULL)
return ;
strcpy(path1,path);
/**********writing to file ***********/
fprintf(prog,"import java.awt.*;\n");
fprintf(prog,"import javax.swing.*;\n");
fprintf(prog,"import java.applet.*;\n");
fp = fopen ("object.tmp","rt");
if (fp != NULL)
{
fprintf(prog,"\n\nvoid redraw();\n\n");
draw = fopen("draw.ini","rt");
int type=0,c=0;
fgets(object,100,fp);
if (object[strlen(object)-1] == '\n')
object[strlen(object)-1] = NULL;
fgets(path1,100,fp);
do
{
rewind(draw);
while (path1[c] != '=' && path1[c]!= NULL)
c++;
type = atoi(path1+c+1);
c = 0;
fscanf(draw,"%d %s",&c,path1);
do{
char ss[100];
fscanf(draw,"%s\n",ss);
if (type == c)
break;
fscanf(draw,"%d %s",&c,path1);
}while(!feof(draw));
fprintf(prog,"%s %s(",path1,object);
{
FILE *head;
head = fopen("head","at");
fprintf(head,"extern %s %s;\n",path1,object);
fclose(head);
}
//fist arguement
fgets(path1,100,fp);
c=0;
while (path1[c] != '=' && path1[c]!= NULL)
c++;
name = path1+c+1;
if (name[strlen(name)-1] == '\n')
name[strlen(name)-1] = NULL;
if (isdigit(name[0])) fprintf(prog,"%d",atoi(name));
else fprintf(prog,"\"%s\"",name);
fgets(path1,100,fp);c=0;
do{
while (path1[c] != '=' && path1[c]!= NULL)
c++;
name = path1+c+1;
if (name[strlen(name)-1] == '\n')
name[strlen(name)-1] = NULL;
if (isdigit(name[0]))
fprintf(prog,",%d",atoi(name));
else
fprintf(prog,",\"%s\"",name);
fgets(path1,100,fp);c=0;
}while (strcmp(path1,"**********\n") != 0 && !(feof(fp)));
fprintf(prog,");\n");
fgets(object,100,fp);fgets(path1,100,fp);
object[strlen(object)-1] = NULL;
}while (!feof(fp));
fclose(draw);
fclose(fp);
}
fprintf(prog,"\n\nint main()\n{\n");
fprintf(prog,"\tint gdriver = VGA, gmode=VGAMED, errorcode;\n");fprintf(prog,"\tinitgraph(&gdriver, &gmode,\"\");\n");
fprintf(prog,"\terrorcode = graphresult();");fprintf(prog,"\n\tif (errorcode != grOk) // an error occurred \n");fprintf(prog,"\t\t{\n");
fprintf(prog,"\t\tprintf(\"Graphics error:\");\n");fprintf(prog,"\t\tprintf(\"Press any key to halt:\");\n");fprintf(prog,"\t\tgetch();\n");fprintf(prog,"\t\texit(1);\n\t\t}\n");
fprintf(prog,"\nredraw();");
fprintf(prog,"\nmouse_present();\nshow_mouse();");
fprintf(prog,"\nwhile(1)\n{\nfocus = -1;key = 0;\n");
fprintf(prog,"\tmouse1 = mouse;\n\tmouse = status();");
fprintf(prog,"\tif (kbhit()) \n\t\tkey = getch();\n");
//start of events
fp = fopen("object.tmp","rt");
draw = fopen("code.tmp","rt");
if (fp != NULL && draw != NULL)
{
fgets(object,100,fp);
do{
object[strlen(object)-1] = NULL;
fprintf(prog,"\tif (inarea(mouse.x,mouse.y,%s.x1,%s.y1,%s.x2,%s.y2))\n\t{\n\t\tfocus = %s.action();\n",
object,object,object,object,object);
//events are writen here
rewind(draw);
fgets(path1,100,draw);
do{
int op = 0;
while (path1[op++] != ' ');
name=path1+op;
if (path1[strlen(path1) -1] == '\n')
path1[strlen(path1) -1] = NULL;
if (strncmp(object,name,strlen(object)) == 0)
fprintf(prog,"\t\t%s;\n",name);
op = 1;fgetc(draw);
while (op != 0)
{
if (path1[0] == '\"')
while (fgetc(draw) == '\"');
else if (path1[0] == '\'')
while (fgetc(draw) == '\'');
else if (path1[0] =='{') op++;
else if (path1[0] =='}') op--;
path1[0] = fgetc(draw);
}//read till end of function
fgets(path1,100,draw);
}while (!feof(draw));
//events are completed here
fprintf(prog,"\t}//end of %s\n\n",object);
while (strcmp(object,"**********\n") != 0)
fgets(object,100,fp);
fgets(object,100,fp);
fgets(path1,100,fp);
}while(!feof(fp));
fclose(fp);
}
fclose(draw);
//end of events
fprintf(prog,"\n}//end of main program execution loop");
fprintf(prog,"\n}//end of function main");
fprintf(prog,"\n\nvoid redraw()\n\t{\n");
fprintf(prog,"char pattern[8];\n");
fp = fopen("draw.tmp","rt");
while (!feof(fp) && fp != NULL)
{
fscanf(fp,"%s ",&object);
int sx,sy,ex,ey,thk,ls,col,fs,fc;
unsigned int fonts,fontn,fontdir;
char cp[8];
sx=sy=ex=ey=thk=ls=col=fs=fc=fonts=fontn=fontdir=0;
if (strcmp(object,"object") == 0)
{
fgets(object,100,fp);
*(object + strlen(object) -1 ) = NULL;
fprintf(prog,"%s.draw();\n",object);
}//end of drawing objects
else if (strcmp(object,"print") == 0)
{
fscanf(fp,"%03d,%03d,",
&sx,&sy);
fgets(object,100,fp);
*(object + strlen(object) -1 ) = NULL;
fprintf(prog,"gotoxy(%d,%d);\n",sx,sy);
fprintf(prog,"printf(\"%s\");\n",object);
}//end of text
else if (strcmp(object,"line") == 0 || strcmp(object,"rectangle") == 0)
{
fscanf(fp,"%03d,%03d,%03d,%03d,%03d,%03d,%03d,%07d\n",
&sx,&sy,&ex,&ey,&col,&thk,&ls,&fontn);
fprintf(prog,"setcolor(%d);setlinestyle(%d,%d,%d);\n",col,ls,fontn,thk);
if (strcmp(object,"rectangle") == 0)
fprintf(prog,"rectangle(%d,%d,%d,%d);\n",sx,sy,ex,ey);
else
fprintf(prog,"line(%d,%d,%d,%d);\n",sx,sy,ex,ey);
}//end of drawing a line
else if (strcmp(object,"bar") == 0)
{
fscanf(fp,"%03d,%03d,%03d,%03d,%03d,%03d\n",
&sx,&sy,&ex,&ey,&fc,&fs);
fprintf(prog,"setfillstyle(%d,%d);\n",fs,fc);
fprintf(prog,"bar(%d,%d,%d,%d);\n",sx,sy,ex,ey);
}//end of drawing a rectangle
else if (strcmp(object,"barp") == 0)
{
fscanf(fp,"%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d\n",
&sx,&sy,&ex,&ey,&fc,
&cp[0],&cp[1],&cp[2],&cp[3],&cp[4],&cp[5],&cp[6],&cp[7]);
fprintf(prog,"\npattern[0] = %d;",cp[0]);fprintf(prog,"\npattern[1] = %d;",cp[1]);fprintf(prog,"\npattern[2] = %d;",cp[2]);fprintf(prog,"\npattern[3] = %d;",cp[3]);
fprintf(prog,"\npattern[4] = %d;",cp[4]);fprintf(prog,"\npattern[5] = %d;",cp[5]);fprintf(prog,"\npattern[6] = %d;",cp[6]);fprintf(prog,"\npattern[7] = %d;",cp[7]);
fprintf(prog,"\nsetfillpattern(pattern,%d);\n",fc);
fprintf(prog,"bar(%d,%d,%d,%d);\n",sx,sy,ex,ey);
}
else if (strcmp(object,"text") == 0)
{
fscanf(fp,"%02d,%03d,%03d,%02d,%02d,%02d,",
&col,&sx,&sy,
&fontn,&fontdir,&fonts);
fgets(object,100,fp);
*(object + strlen(object) -1 ) = NULL;
fprintf(prog,"setcolor(%d);\n",col);
fprintf(prog,"settextstyle(%d,%d,%d);\n",fontn,fontdir,fonts);
fprintf(prog,"outtextxy(%d,%d,\"%s\");\n",sx,sy,object);
}//end of text
else if (strcmp(object,"ellipse") == 0)
{
fscanf(fp,"%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d\n",
&sx,&sy,&ex,&ey,&fonts,&fontn,&col,&thk);
fprintf(prog,"setcolor(%d);\n",col);
fprintf(prog,"setlinestyle(0,0,%d);\n",thk);
fprintf(prog,"ellipse(%d,%d,%d,%d,%d,%d);\n",sx,sy,ex,ey,fonts,fontn);
}//end of ellipse
else if (strcmp(object,"pie") == 0)
{
fscanf(fp,"%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d\n",
&sx,&sy,&ex,&ey,&fonts,&fontn,
&col,&thk,&fc,&fs);
fprintf(prog,"setcolor(%d);\n",col);
fprintf(prog,"setlinestyle(0,0,%d);\n",thk);
fprintf(prog,"setfillstyle(%d,%d);\n",fs,fc);
fprintf(prog,"sector(%d,%d,%d,%d,%d,%d);\n",sx,sy,ex,ey,fonts,fontn);
}//end of drawing simple piechart
else if (strcmp(object,"piepattern") == 0)
{
int xradius,yradius;
fscanf(fp,"%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d\n",
&sx,&sy,
&ex,&ey,
&xradius,&yradius,
&col,&thk,&fc,
&cp[0],&cp[1],&cp[2],&cp[3],&cp[4],&cp[5],&cp[6],&cp[7]);
fprintf(prog,"setcolor(%d);\n",col);
fprintf(prog,"setlinestyle(0,0,%d);\n",thk);
fprintf(prog,"\npattern[0] = %d;",cp[0]);fprintf(prog,"\npattern[1] = %d;",cp[1]);fprintf(prog,"\npattern[2] = %d;",cp[2]);fprintf(prog,"\npattern[3] = %d;",cp[3]);
fprintf(prog,"\npattern[4] = %d;",cp[4]);fprintf(prog,"\npattern[5] = %d;",cp[5]);fprintf(prog,"\npattern[6] = %d;",cp[6]);fprintf(prog,"\npattern[7] = %d;",cp[7]);
fprintf(prog,"setfillpattern(pattern,%d);\n",fc);
fprintf(prog,"sector(%d,%d,%d,%d,%d,%d);\n",sx,sy,ex,ey,fonts,fontn);
}//end of complex pie chart
else if (strcmp(object,"fillellipse") == 0)
{
fscanf(fp,"%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d\n",
&sx,&sy,&ex,&ey,
&col,&thk,&fc,&fs);
fprintf(prog,"setcolor(%d);\n",col);
fprintf(prog,"setlinestyle(0,0,%d);\n",thk);
fprintf(prog,"setfillstyle(%d,%d);\n",fs,fc);
fprintf(prog,"fillellipse(%d,%d,%d,%d);\n",sx,sy,ex,ey);
}//end of fillellipse simple
else if (strcmp(object,"fillellipsep") == 0)
{
fscanf(fp,"%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d\n",
&sx,&sy,&ex,&ey,
&col,&thk,&fc,
&cp[0],&cp[1],&cp[2],&cp[3],&cp[4],&cp[5],&cp[6],&cp[7]);
fprintf(prog,"setcolor(%d);\n",col);
fprintf(prog,"setlinestyle(0,0,%d);\n",thk);
fprintf(prog,"\npattern[0] = %d;",cp[0]);fprintf(prog,"\npattern[1] = %d;",cp[1]);fprintf(prog,"\npattern[2] = %d;",cp[2]);fprintf(prog,"\npattern[3] = %d;",cp[3]);
fprintf(prog,"\npattern[4] = %d;",cp[4]);fprintf(prog,"\npattern[5] = %d;",cp[5]);fprintf(prog,"\npattern[6] = %d;",cp[6]);fprintf(prog,"\npattern[7] = %d;",cp[7]);
fprintf(prog,"setfillpattern(pattern,%d);\n",fc);
fprintf(prog,"fillellipse(%d,%d,%d,%d);\n",sx,sy,ex,ey);
}//end of complex ellipse filler
else if (strcmp(object,"fillstyle") == 0)
{
fscanf(fp,"%03d,%03d,%02d,%02d,%02d\n",
&sx,&sy,&col,&fc,&fs);
fprintf(prog,"setfillstyle(%d,%d);\n",fs,fc);
fprintf(prog,"floodfill(%d,%d,%d);\n",sx,sy,col);
}//end of floodfilling
else if (strcmp(object,"fillpattern") == 0)
{
fscanf(fp,"%03d,%03d,%02d,%02d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d\n",
&sx,&sy,&col,&fc,
&cp[0],&cp[1],&cp[2],&cp[3],&cp[4],&cp[5],&cp[6],&cp[7]);
fprintf(prog,"\npattern[0] = %d;",cp[0]);fprintf(prog,"\npattern[1] = %d;",cp[1]);fprintf(prog,"\npattern[2] = %d;",cp[2]);fprintf(prog,"\npattern[3] = %d;",cp[3]);
fprintf(prog,"\npattern[4] = %d;",cp[4]);fprintf(prog,"\npattern[5] = %d;",cp[5]);fprintf(prog,"\npattern[6] = %d;",cp[6]);fprintf(prog,"\npattern[7] = %d;",cp[7]);
fprintf(prog,"setfillpattern(pattern,%d);\n",fc);
fprintf(prog,"floodfill(%d,%d,%d);\n",sx,sy,col);
}//end of fill pattern
else if (strcmp(object,"polygon") == 0)
{
fscanf(fp,"%03d,%03d,%03d,%03d,%07d\n",
&fontdir,&col,&ls,&thk,&fontn);
int points[30];
fprintf(prog,"{\nint poly[] = {");
for (int i = 0; i < fontdir*2 && i < 30;i+=2)
{
fscanf(fp,"%03d,%03d",&points[i],&points[i+1]);
fprintf(prog,"%3d,%3d,",points[i],points[i+1]);
}//end of for next loop
fprintf(prog,"0};\nsetcolor(%d);\n",col);
fprintf(prog,"setlinestyle(%d,%d,%d);\n",ls,fontn,thk);
fprintf(prog,"drawpoly(%d,poly);}\n",fontdir);
}//end of simple polygon
else if (strcmp(object,"fillpolygon") == 0)
{
fscanf(fp,"%03d,%03d,%03d,%03d,%03d,%03d,%07d\n",
&fontdir,&col,&ls,&thk,&fc,&fs,&fontn);
int points[30];
fprintf(prog,"{\nint poly[] = {");
for (int i = 0; i < fontdir*2 && i < 30;i+=2)
{
fscanf(fp,"%03d,%03d",&points[i],&points[i+1]);
fprintf(prog,"%3d,%3d,",points[i],points[i+1]);
}//end of for next loop
fprintf(prog,"0};\nsetcolor(%d);\n",col);
fprintf(prog,"setlinestyle(%d,0,%d);\n",ls,fontn,thk);
fprintf(prog,"setfillstyle(%d,%d);\n",fs,fc);
fprintf(prog,"fillpoly(%d,poly);}\n",fontdir);
}//end of simple polygon filling simple
else if (strcmp(object,"fillpolygonp") == 0)
{
fscanf(fp,"%03d,%03d,%03d,%03d,%03d,%07d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d\n",
&fontdir,&col,&ls,&thk,&fc,&fontn,
&cp[0],&cp[1],&cp[2],&cp[3],&cp[4],&cp[5],&cp[6],&cp[7]);
int points[30];
fprintf(prog,"{\nint poly[] = {");
for (int i = 0; i < fonts*2 && i < 30;i+=2)
{
fscanf(fp,"%03d,%03d",&points[i],&points[i+1]);
fprintf(prog,"%3d,%3d,",points[i],points[i+1]);
}//end of for next loop
fprintf(prog,"0};\nsetcolor(%d);\n",col);
fprintf(prog,"setlinestyle(%d,%d,%d);\n",ls,fontn,thk);
fprintf(prog,"\npattern[0] = %d;",cp[0]);fprintf(prog,"\npattern[1] = %d;",cp[1]);fprintf(prog,"\npattern[2] = %d;",cp[2]);fprintf(prog,"\npattern[3] = %d;",cp[3]);
fprintf(prog,"\npattern[4] = %d;",cp[4]);fprintf(prog,"\npattern[5] = %d;",cp[5]);fprintf(prog,"\npattern[6] = %d;",cp[6]);fprintf(prog,"\npattern[7] = %d;",cp[7]);
fprintf(prog,"setfillpattern(pattern,%d);\n",fc);
fprintf(prog,"fillpoly(%d,poly);}\n",fontdir);
}//end of simple polygon filling simple
else if (strcmp(object,"bmp") == 0)
{
int sx,sy,ex,ey;
fscanf(fp,"%03d,%03d,%03d,%03d,%s\n",
&sx,&sy,&ex,&ey,&object);
fprintf(prog,"loadbmp(\"%s\",%d,%d,%d,%d);\n",object,sx,sy,ex,ey);
}//end of loading bitmaps
}//end of parsing all values
fclose(fp);
fprintf(prog,"\n\t}//end of redrawing all objects\n\n");
fclose(prog);
free(path);
free(path1);
}//end of function
int fc(char *file1,char *file2,char *dest)
{
FILE *src,*dst;
src = fopen(file1,"rt");
dst = fopen(dest,"at");
if (dst == NULL)
return 1;
char *buffer = (char *)calloc(1,100);
if (src != NULL)
{
fgets(buffer,100,src);
do{
fprintf(dst,"%s",buffer);
fgets(buffer,100,src);
}while (!feof(src));
fclose(src);
}
src = fopen(file2,"rt");
if (src != NULL)
{
fgets(buffer,100,src);
do{
fprintf(dst,"%s",buffer);
fgets(buffer,100,src);
}while (!feof(src));
fclose(src);
}
free(buffer);
fclose(dst);
return 0;
}
| [
"github@nparashuram.com"
] | [
[
[
1,
448
]
]
] |
0a505a8e0020e100e1a0d83f1d5470ebe0dfaf00 | 4ab592fb354f75b42181d5375d485031960aaa7d | /DES_GOBSTG/DES_GOBSTG/Class/Player.cpp | 2a59e185a0d1e2d558f110407142b35f07c87400 | [] | no_license | CBE7F1F65/cca610e2e115c51cef211fafb0f66662 | 806ced886ed61762220b43300cb993ead00949dc | b3cdff63d689e2b1748e9cd93cedd7e8389a7057 | refs/heads/master | 2020-12-24 14:55:56 | 2010-07-23 04:24:59 | 2010-07-23 04:24:59 | 32,192,699 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 36,505 | cpp | #include "../header/Player.h"
#include "../header/Process.h"
#include "../header/BGLayer.h"
#include "../header/SE.h"
#include "../header/PlayerBullet.h"
#include "../header/Item.h"
#include "../header/Enemy.h"
#include "../header/Bullet.h"
#include "../header/Chat.h"
#include "../header/BossInfo.h"
#include "../header/EffectIDDefine.h"
#include "../header/SpriteItemManager.h"
#include "../header/FrontDisplayName.h"
#include "../header/FrontDisplay.h"
#include "../header/EventZone.h"
#include "../header/BResource.h"
#include "../header/Scripter.h"
#include "../header/GameInput.h"
#include "../header/GameAI.h"
#define _GAMERANK_MIN 8
#define _GAMERANK_MAX 22
#define _GAMERANK_ADDINTERVAL 9000
#define _GAMERANK_STAGEOVERADD -8
#define _PL_SHOOTCHARGEINFI_1 8
#define _PL_SHOOTCHARGEINFI_2 47
#define _PL_SHOOTCHARGEINFI_3 63
#define _PL_SHOOTCHARGEINFI_4 127
#define _PLAYER_DEFAULETCARDLEVEL_(X) (X?9:8)
#define _PLAYER_DEFAULETBOSSLEVEL_(X) (X?9:8)
#define _CARDLEVEL_ADDINTERVAL 3600
#define _BOSSLEVEL_ADDINTERVAL 3600
#define _CARDLEVEL_MAX 16
#define _BOSSLEVEL_MAX 16
#define _PLAYER_LIFECOSTMAX 2880
#define _PLAYER_COMBOHITMAX 999
#define _PLAYER_SHOOTPUSHOVER 9
#define _PLAYER_SHOOTNOTPUSHOVER 9
#define _PL_SPELLBONUS_BOSS_1 100000
#define _PL_SPELLBONUS_BOSS_2 300000
#define _PL_SPELLBONUS_BOSS_3 500000
Player Player::p[M_PL_MATCHMAXPLAYER];
float Player::lostStack = 0;
bool Player::able = false;
BYTE Player::rank = _GAMERANK_MIN;
int Player::lilycount = 0;
DWORD Player::alltime = 0;
BYTE Player::raisespellstopplayerindex = 0;
BYTE Player::round = 0;
#define _PL_MERGETOPOS_X_(X) (M_GAMESQUARE_CENTER_X_(X))
#define _PL_MERGETOPOS_Y (M_GAMESQUARE_BOTTOM - 64)
#define _PL_SHOOTINGCHARGE_1 0x01
#define _PL_SHOOTINGCHARGE_2 0x02
#define _PL_SHOOTINGCHARGE_3 0x04
#define _PL_SHOOTINGCHARGE_4 0x08
#define _PL_CHARGEZONE_R_2 188.0f
#define _PL_CHARGEZONE_R_3 252.0f
#define _PL_CHARGEZONE_R_4 444.5f
#define _PL_CHARGEZONE_MAXTIME_2 49
#define _PL_CHARGEZONE_MAXTIME_3 65
#define _PL_CHARGEZONE_MAXTIME_4 129
Player::Player()
{
effGraze.exist = false;
effChange.exist = false;
effInfi.exist = false;
effCollapse.exist = false;
effMerge.exist = false;
effBorder.exist = false;
effBorderOn.exist = false;
effBorderOff.exist = false;
sprite = NULL;
spdrain = NULL;
nowID = 0;
ID_sub_1 = 0;
ID_sub_2 = 0;
}
Player::~Player()
{
SpriteItemManager::FreeSprite(&sprite);
SpriteItemManager::FreeSprite(&spdrain);
}
void Player::ClearSet(BYTE _round)
{
x = PL_MERGEPOS_X_(playerindex);
y = PL_MERGEPOS_Y;
round = _round;
for(int i=0;i<PL_SAVELASTMAX;i++)
{
lastx[i] = x;
lasty[i] = y;
lastmx[i] = x;
lastmy[i] = y;
}
timer = 0;
angle = 0;
flag = PLAYER_MERGE;
bSlow = false;
bCharge = false;
bDrain = false;
bInfi = true;
hscale = 1.0f;
vscale = 1.0f;
alpha = 0xff;
diffuse = 0xffffff;
mergetimer = 0;
shottimer = 0;
collapsetimer = 0;
shoottimer = 0;
draintimer = 0;
chargetimer = 0;
slowtimer = 0;
fasttimer = 0;
playerchangetimer = 0;
costlifetimer = 0;
shootchargetimer = 0;
shootingchargeflag = 0;
nowshootingcharge = 0;
fExPoint = 0;
nGhostPoint = 0;
nBulletPoint = 0;
nSpellPoint = 0;
nLifeCost = 0;
fCharge = 0;
if (_round == 0)
{
fChargeMax = PLAYER_CHARGEONE;
winflag = 0;
}
cardlevel = _PLAYER_DEFAULETCARDLEVEL_(_round);
bosslevel = _PLAYER_DEFAULETBOSSLEVEL_(_round);
nowcardlevel = cardlevel;
nowbosslevel = bosslevel;
infitimer = 0;
rechargedelaytimer = 0;
infireasonflag = 0;
shootpushtimer = 0;
shootnotpushtimer = 0;
spellstoptimer = 0;
speedfactor = 1.0f;
// add
// initlife = PLAYER_DEFAULTINITLIFE;
exist = true;
nComboHit = 0;
nComboHitOri = 0;
nComboGage = 0;
nBounceAngle = 0;
drainx = x;
drainy = y;
drainheadangle = 0;
draintimer = 0;
drainhscale = 1;
drainvscale = 0;
draincopyspriteangle = 0;
if (effGraze.exist)
{
effGraze.Stop(true);
effGraze.MoveTo(x, y, 0, true);
}
if (effChange.exist)
{
effChange.Stop(true);
effChange.MoveTo(x, y, 0, true);
}
if (effInfi.exist)
{
effInfi.Stop(true);
effInfi.MoveTo(x, y, 0, true);
}
if (effCollapse.exist)
{
effCollapse.Stop(true);
effCollapse.MoveTo(x, y, 0, true);
}
if (effMerge.exist)
{
effMerge.Stop(true);
effMerge.MoveTo(x, y, 0, true);
}
if (effBorder.exist)
{
effBorder.Stop(true);
effBorder.MoveTo(x, y, 0, true);
}
if (effBorderOn.exist)
{
effBorderOn.Stop(true);
effBorderOn.MoveTo(x, y, 0, true);
}
if (effBorderOff.exist)
{
effBorderOff.Stop(true);
effBorderOff.MoveTo(x, y, 0, true);
}
changePlayerID(nowID, true);
setShootingCharge(0);
esChange.valueSet(EFFSPSET_PLAYERUSE, EFFSP_PLAYERCHANGE, SpriteItemManager::GetIndexByName(SI_PLAYER_SHOTITEM), x, y, 0, 3.0f);
esChange.colorSet(0x7fffffff, BLEND_ALPHAADD);
esChange.chaseSet(EFFSP_CHASE_PLAYER_(playerindex), 0, 0);
esShot.valueSet(EFFSPSET_PLAYERUSE, EFFSP_PLAYERSHOT, SpriteItemManager::GetIndexByName(SI_PLAYER_SHOTITEM), x, y, 0, 1.2f);
esShot.colorSet(0xccff0000);
esShot.chaseSet(EFFSP_CHASE_PLAYER_(playerindex), 0, 0);
esPoint.valueSet(EFFSPSET_PLAYERUSE, EFFSP_PLAYERPOINT, SpriteItemManager::GetIndexByName(SI_PLAYER_POINT), x, y);
esPoint.chaseSet(EFFSP_CHASE_PLAYER_(playerindex), 0, 0);
esCollapse.valueSet(EFFSPSET_PLAYERUSE, EFFSP_PLAYERCOLLAPSE, SpriteItemManager::GetIndexByName(SI_PLAYER_SHOTITEM), x, y);
esCollapse.actionSet(0, 0, 160);
esCollapse.colorSet(0x80ffffff);
}
void Player::ClearRound(BYTE round/* =0 */)
{
raisespellstopplayerindex = 0xff;
if (round)
{
rank += _GAMERANK_STAGEOVERADD;
if (rank < _GAMERANK_MIN)
{
rank = _GAMERANK_MIN;
}
AddLilyCount(-1000);
for (int i=0; i<M_PL_MATCHMAXPLAYER; i++)
{
p[i].valueSet(i, round);
}
}
else
{
rank = _GAMERANK_MIN;
lilycount = 0;
alltime = 0;
}
}
//add
void Player::valueSet(BYTE _playerindex, BYTE round)
{
playerindex = _playerindex;
nowID = ID;
ClearSet(round);
initFrameIndex();
UpdatePlayerData();
SetDrainSpriteInfo(x, y);
nLife = initlife;
if (round == 0)
{
lostStack = 0;
}
setFrame(PLAYER_FRAME_STAND);
effGraze.valueSet(EFF_PL_GRAZE, playerindex, *this);
effGraze.Stop();
effChange.valueSet(EFF_PL_CHANGE, playerindex, *this);
effChange.Stop();
effInfi.valueSet(EFF_PL_INFI, playerindex, *this);
effInfi.Stop();
effCollapse.valueSet(EFF_PL_COLLAPSE, playerindex, *this);
effCollapse.Stop();
effMerge.valueSet(EFF_PL_MERGE, playerindex, *this);
effMerge.Stop();
effBorder.valueSet(EFF_PL_BORDER, playerindex, *this);
effBorder.Stop();
effBorderOn.valueSet(EFF_PL_BORDERON, playerindex, *this);
effBorderOn.Stop();
effBorderOff.valueSet(EFF_PL_BORDEROFF, playerindex, *this);
effBorderOff.Stop();
SetAble(true);
}
bool Player::Action()
{
alltime++;
AddLostStack();
for (int i=0; i<M_PL_MATCHMAXPLAYER; i++)
{
if (gametime % _CARDLEVEL_ADDINTERVAL == 0)
{
p[i].AddCardBossLevel(1, 0);
}
if (gametime % _BOSSLEVEL_ADDINTERVAL == 0)
{
p[i].AddCardBossLevel(0, 1);
}
DWORD stopflag = Process::mp.GetStopFlag();
bool binstop = FRAME_STOPFLAGCHECK_PLAYERINDEX_(stopflag, i, FRAME_STOPFLAG_PLAYER);
bool binspellstop = FRAME_STOPFLAGCHECK_PLAYERINDEX_(stopflag, i, FRAME_STOPFLAG_PLAYERSPELL);
GameInput::gameinput[i].updateActiveInput(binspellstop);
if (p[i].exist)
{
if (!binstop && !binspellstop)
{
p[i].action();
}
else if (binspellstop)
{
p[i].actionInSpellStop();
}
else
{
p[i].actionInStop();
}
if (!p[i].exist)
{
return false;
}
}
}
if (gametime % _GAMERANK_ADDINTERVAL == 0)
{
rank++;
if (rank > _GAMERANK_MAX)
{
rank = _GAMERANK_MAX;
}
}
AddLilyCount(0, true);
return true;
}
void Player::action()
{
float nowspeed = 0;
timer++;
alpha = 0xff;
if(timer == 1)
flag |= PLAYER_MERGE;
//savelast
if(lastmx[0] != x || lastmy[0] != y)
{
for(int i=PL_SAVELASTMAX-1;i>0;i--)
{
lastmx[i] = lastmx[i-1];
lastmy[i] = lastmy[i-1];
}
lastmx[0] = x;
lastmy[0] = y;
}
for(int i=PL_SAVELASTMAX-1;i>0;i--)
{
lastx[i] = lastx[i-1];
lasty[i] = lasty[i-1];
}
lastx[0] = x;
lasty[0] = y;
//AI
// GameAI::ai[playerindex].UpdateBasicInfo(x, y, speed, slowspeed, BResource::bres.playerdata[nowID].collision_r);
GameAI::ai[playerindex].SetMove();
//
if(flag & PLAYER_MERGE)
{
if(Merge())
{
flag &= ~PLAYER_MERGE;
}
}
if(flag & PLAYER_SHOT)
{
if(Shot())
{
flag &= ~PLAYER_SHOT;
}
}
if (flag & PLAYER_COSTLIFE)
{
if (CostLife())
{
flag &= ~PLAYER_COSTLIFE;
}
}
if(flag & PLAYER_COLLAPSE)
{
if(Collapse())
{
flag &= ~PLAYER_COLLAPSE;
return;
}
}
if(flag & PLAYER_SLOWCHANGE)
{
if(SlowChange())
{
flag &= ~PLAYER_SLOWCHANGE;
}
}
if(flag & PLAYER_FASTCHANGE)
{
if(FastChange())
{
flag &= ~PLAYER_FASTCHANGE;
}
}
if(flag & PLAYER_PLAYERCHANGE)
{
if(PlayerChange())
{
flag &= ~PLAYER_PLAYERCHANGE;
}
}
if(flag & PLAYER_SHOOT)
{
if(Shoot())
{
flag &= ~PLAYER_SHOOT;
}
}
if(flag & PLAYER_BOMB)
{
if(Bomb())
{
flag &= ~PLAYER_BOMB;
}
}
if(flag & PLAYER_DRAIN)
{
if(Drain())
{
flag &= ~PLAYER_DRAIN;
}
}
if (flag & PLAYER_CHARGE)
{
if (Charge())
{
flag &= ~PLAYER_CHARGE;
}
}
if(flag & PLAYER_GRAZE)
{
if(Graze())
{
flag &= ~PLAYER_GRAZE;
}
}
nLifeCost++;
if (nLifeCost > _PLAYER_LIFECOSTMAX)
{
nLifeCost = _PLAYER_LIFECOSTMAX;
}
if (rechargedelaytimer)
{
rechargedelaytimer--;
}
if (shootchargetimer)
{
Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERSHOOTCHARGEONE, playerindex);
PlayerBullet::BuildShoot(playerindex, nowID, shootchargetimer, true);
shootchargetimer--;
}
if (infitimer > 0)
{
infitimer--;
bInfi = true;
}
else if (infitimer == PLAYER_INFIMAX)
{
bInfi = true;
}
else
{
bInfi = false;
}
if (nComboGage)
{
nComboGage--;
if (nComboGage == PLAYER_COMBORESET)
{
AddComboHit(-1, true);
}
else if (!nComboGage)
{
AddSpellPoint(-1);
}
}
for (list<EventZone>::iterator it=EventZone::ezone[playerindex].begin(); it!=EventZone::ezone[playerindex].end(); it++)
{
if (it->timer < 0)
{
continue;
}
if ((it->type) & EVENTZONE_TYPEMASK_PLAYER)
{
if (it->isInRect(x, y, r))
{
if (it->type & EVENTZONE_TYPE_PLAYERDAMAGE)
{
DoShot();
}
if (it->type & EVENTZONE_TYPE_PLAYEREVENT)
{
}
if (it->type & EVENTZONE_TYPE_PLAYERSPEED)
{
speedfactor = it->power;
}
}
}
}
//input
if(!(flag & PLAYER_SHOT || flag & PLAYER_COLLAPSE))
{
if (GameInput::GetKey(playerindex, KSI_SLOW))
{
bSlow = true;
flag &= ~PLAYER_FASTCHANGE;
if (GameInput::GetKey(playerindex, KSI_SLOW, DIKEY_DOWN))
{
if (!(flag & PLAYER_SLOWCHANGE))
{
slowtimer = 0;
flag |= PLAYER_SLOWCHANGE;
}
}
}
else
{
bSlow = false;
flag &= ~PLAYER_SLOWCHANGE;
if (GameInput::GetKey(playerindex, KSI_SLOW, DIKEY_UP))
{
if (!(flag & PLAYER_FASTCHANGE))
{
fasttimer = 0;
flag |= PLAYER_FASTCHANGE;
}
}
}
if(bSlow)
{
nowspeed = slowspeed;
}
else
{
nowspeed = speed;
}
nowspeed *= speedfactor;
if(GameInput::GetKey(playerindex, KSI_FIRE))
{
if (!Chat::chatitem.IsChatting())
{
flag |= PLAYER_SHOOT;
}
shootnotpushtimer = 0;
}
else
{
if (shootnotpushtimer < 0xff)
{
shootnotpushtimer++;
}
}
if (shootpushtimer < _PLAYER_SHOOTPUSHOVER)
{
if (GameInput::GetKey(playerindex, KSI_FIRE))
{
shootpushtimer++;
}
else
{
shootpushtimer = 0;
}
}
else
{
if (!GameInput::GetKey(playerindex, KSI_FIRE))
{
bCharge = false;
flag &= ~PLAYER_CHARGE;
shootpushtimer = 0;
}
else
{
if (!rechargedelaytimer)
{
flag &= ~PLAYER_SHOOT;
bCharge = true;
if (shootpushtimer >= _PLAYER_SHOOTPUSHOVER && !(flag & PLAYER_CHARGE))
{
chargetimer = 0;
flag |= PLAYER_CHARGE;
shootpushtimer = 0xff;
}
}
}
}
if (GameInput::GetKey(playerindex, KSI_DRAIN))
{
bDrain = true;
if (GameInput::GetKey(playerindex, KSI_DRAIN, DIKEY_DOWN))
{
if (!(flag & PLAYER_DRAIN))
{
draintimer = 0;
SetDrainSpriteInfo(x, y, 0, 0);
}
}
flag |= PLAYER_DRAIN;
}
else
{
bDrain = false;
flag &= ~PLAYER_DRAIN;
}
if((GameInput::GetKey(playerindex, KSI_UP) ^ GameInput::GetKey(playerindex, KSI_DOWN)) &&
GameInput::GetKey(playerindex, KSI_LEFT) ^ GameInput::GetKey(playerindex, KSI_RIGHT))
nowspeed *= M_SQUARE_2;
if(GameInput::GetKey(playerindex, KSI_UP))
y -= nowspeed;
if(GameInput::GetKey(playerindex, KSI_DOWN))
y += nowspeed;
if(GameInput::GetKey(playerindex, KSI_LEFT))
{
updateFrame(PLAYER_FRAME_LEFTPRE);
x -= nowspeed;
}
if(GameInput::GetKey(playerindex, KSI_RIGHT))
{
if (!GameInput::GetKey(playerindex, KSI_LEFT))
{
updateFrame(PLAYER_FRAME_RIGHTPRE);
}
else
{
updateFrame(PLAYER_FRAME_STAND);
}
x += nowspeed;
}
if (!GameInput::GetKey(playerindex, KSI_LEFT) && !GameInput::GetKey(playerindex, KSI_RIGHT))
{
updateFrame(PLAYER_FRAME_STAND);
}
}
if(GameInput::GetKey(playerindex, KSI_QUICK) && !(flag & PLAYER_MERGE))
{
callBomb();
}
if (!(flag & PLAYER_MERGE) || mergetimer >= 32)
{
if(x > PL_MOVABLE_RIGHT_(playerindex))
x = PL_MOVABLE_RIGHT_(playerindex);
else if(x < PL_MOVABLE_LEFT_(playerindex))
x = PL_MOVABLE_LEFT_(playerindex);
if(y > PL_MOVABLE_BOTTOM)
y = PL_MOVABLE_BOTTOM;
else if(y < PL_MOVABLE_TOP)
y = PL_MOVABLE_TOP;
}
//AI
GameAI::ai[playerindex].UpdateBasicInfo(x, y, speed*speedfactor, slowspeed*speedfactor, r, BResource::bres.playerdata[nowID].aidraintime);
float aiaimx = _PL_MERGETOPOS_X_(playerindex);
float aiaimy = _PL_MERGETOPOS_Y;
bool tobelow = false;
if (PlayerBullet::activelocked[playerindex] != PBLOCK_LOST)
{
aiaimx = Enemy::en[playerindex][PlayerBullet::activelocked[playerindex]].x;
aiaimy = Enemy::en[playerindex][PlayerBullet::activelocked[playerindex]].y + 120;
tobelow = true;
}
else if (PlayerBullet::locked[playerindex] != PBLOCK_LOST)
{
aiaimx = Enemy::en[playerindex][PlayerBullet::locked[playerindex]].x;
aiaimy = Enemy::en[playerindex][PlayerBullet::locked[playerindex]].y;
}
GameAI::ai[playerindex].SetAim(aiaimx, aiaimy, tobelow);
//
//
speedfactor = 1.0f;
if (bInfi && timer % 8 < 4)
{
diffuse = 0xff99ff;
}
else
diffuse = 0xffffff;
esChange.action();
esShot.action();
esPoint.action();
effGraze.MoveTo(x, y);
effGraze.action();
effCollapse.action();
effBorderOn.action();
effBorderOff.action();
if(!(flag & PLAYER_GRAZE))
effGraze.Stop();
for(int i=0;i<PLAYERGHOSTMAX;i++)
{
if (pg[i].exist)
{
pg[i].action();
}
}
}
void Player::actionInSpellStop()
{
spellstoptimer++;
Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERINSPELLSTOP, playerindex);
}
void Player::actionInStop()
{
// Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERINSTOP, playerindex);
}
bool Player::Merge()
{
mergetimer++;
if(mergetimer == 1)
{
SetInfi(PLAYERINFI_MERGE, 60);
if(GameInput::GetKey(playerindex, KSI_SLOW))
{
flag |= PLAYER_SLOWCHANGE;
slowtimer = 0;
flag &= ~PLAYER_FASTCHANGE;
}
else
{
flag |= PLAYER_FASTCHANGE;
fasttimer = 0;
flag &= ~PLAYER_SLOWCHANGE;
}
}
else if (mergetimer <= 24)
{
float interval = mergetimer / 24.0f;
x = INTER(PL_MERGEPOS_X_(playerindex), _PL_MERGETOPOS_X_(playerindex), interval);
y = INTER(PL_MERGEPOS_Y, _PL_MERGETOPOS_Y, interval);
flag &= ~PLAYER_SHOOT;
alpha = INTER(0, 0xff, interval);
}
else if(mergetimer < 60)
{
alpha = 0xff;
}
else if(mergetimer == 60)
{
mergetimer = 0;
return true;
}
return false;
}
bool Player::Shot()
{
shottimer++;
// TODO:
if(bInfi)
{
shottimer = 0;
return true;
}
if(shottimer == 1)
{
// Item::undrainAll();
SE::push(SE_PLAYER_SHOT, x);
}
else if(shottimer == shotdelay)
{
shottimer = 0;
flag |= PLAYER_COSTLIFE;
return true;
}
esShot.hscale = (shotdelay - shottimer) * 4.0f / shotdelay;
Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERSHOT, playerindex);
return false;
}
bool Player::CostLife()
{
costlifetimer++;
if (costlifetimer == 1)
{
AddLilyCount(-1500);
if (nLife == 1)
{
nLife = 0;
flag |= PLAYER_COLLAPSE;
costlifetimer = 0;
return true;
}
int nLifeCostNum = nLifeCost / 720 + 2;
if (nLife > nLifeCostNum+1)
{
nLife -= nLifeCostNum;
}
else
{
FrontDisplay::fdisp.gameinfodisplay.lastlifecountdown[playerindex] = FDISP_COUNTDOWNTIME;
SE::push(SE_PLAYER_ALERT, x);
nLife = 1;
}
nLifeCost -= 1440;
if (nLifeCost < 0)
{
nLifeCost = 0;
}
SetInfi(PLAYERINFI_COSTLIFE, 120);
if (nLife == 1)
{
AddCharge(0, PLAYER_CHARGEMAX);
}
else
{
AddCharge(0, 130-nLife * 10);
}
nBounceAngle = randt();
}
else if (costlifetimer == 50)
{
EventZone::Build(EVENTZONE_TYPE_BULLETFADEOUT|EVENTZONE_TYPE_ENEMYDAMAGE|EVENTZONE_TYPE_NOSEND|EVENTZONE_CHECKTYPE_CIRCLE, playerindex, x, y, 10, 0, 0, 10, EVENTZONE_EVENT_NULL, 15.6);
}
else if (costlifetimer == 60)
{
costlifetimer = 0;
return true;
}
else
{
GameInput::SetKey(playerindex, KSI_UP, false);
GameInput::SetKey(playerindex, KSI_DOWN, false);
GameInput::SetKey(playerindex, KSI_LEFT, false);
GameInput::SetKey(playerindex, KSI_RIGHT, false);
// GameInput::SetKey(playerindex, KSI_FIRE, false);
GameInput::SetKey(playerindex, KSI_QUICK, false);
GameInput::SetKey(playerindex, KSI_SLOW, false);
GameInput::SetKey(playerindex, KSI_DRAIN, false);
x += cost(nBounceAngle) * ((60-costlifetimer) / 20.0f);
y += sint(nBounceAngle) * ((60-costlifetimer) / 20.0f);
}
return false;
}
bool Player::Collapse()
{
collapsetimer++;
if(collapsetimer == 1)
{
for (int i=0; i<M_PL_MATCHMAXPLAYER; i++)
{
EventZone::Build(EVENTZONE_TYPE_BULLETFADEOUT|EVENTZONE_TYPE_ENEMYDAMAGE|EVENTZONE_TYPE_NOSEND|EVENTZONE_CHECKTYPE_CIRCLE, i, p[i].x, p[i].y, 64, EVENTZONE_OVERZONE, 0, 1000, EVENTZONE_EVENT_NULL, 16);
p[i].SetInfi(PLAYERINFI_COLLAPSE, 64);
}
esCollapse.x = x;
esCollapse.y = y;
SE::push(SE_PLAYER_DEAD, x);
effCollapse.MoveTo(x, y , 0, true);
effCollapse.Fire();
p[1-playerindex].winflag |= 1<<round;
}
else if(collapsetimer == 64)
{
x = PL_MERGEPOS_X_(playerindex);
y = PL_MERGEPOS_Y;
for(int i=0;i<PL_SAVELASTMAX;i++)
{
lastx[i] = x;
lasty[i] = y;
lastmx[i] = x;
lastmy[i] = y;
}
timer = 0;
collapsetimer = 0;
vscale = 1.0f;
flag |= PLAYER_MERGE;
AddCharge(0, 130);
// SetInfi(PLAYERINFI_COLLAPSE);
exist = false;
if(GameInput::GetKey(playerindex, KSI_SLOW))
{
flag |= PLAYER_SLOWCHANGE;
slowtimer = 0;
flag &= ~PLAYER_FASTCHANGE;
}
else
{
flag |= PLAYER_FASTCHANGE;
fasttimer = 0;
flag &= ~PLAYER_SLOWCHANGE;
}
effCollapse.Stop();
return true;
}
esCollapse.hscale = collapsetimer / 1.5f;
esCollapse.alpha = (BYTE)((WORD)(0xff * collapsetimer) / 0x3f);
esCollapse.colorSet(0xff0000);
alpha = (0xff - collapsetimer * 4);
vscale = (float)(collapsetimer)/40.0f + 1.0f;
return false;
}
bool Player::Shoot()
{
if(Chat::chatitem.IsChatting())
{
shoottimer = 0;
return true;
}
if (!(flag & PLAYER_SHOT) && !(flag & PLAYER_COSTLIFE))
{
PlayerBullet::BuildShoot(playerindex, nowID, shoottimer);
}
shoottimer++;
//
if(shootnotpushtimer > _PLAYER_SHOOTNOTPUSHOVER)
{
shoottimer = 0;
return true;
}
return false;
}
bool Player::Drain()
{
draintimer++;
bDrain = true;
Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERDRAIN, playerindex);
return false;
}
bool Player::Bomb()
{
BYTE ncharge;
BYTE nchargemax;
GetNCharge(&ncharge, &nchargemax);
if (nchargemax > 1)
{
BYTE nChargeLevel = shootCharge(nchargemax, true);
if (nChargeLevel == nchargemax)
{
AddCharge(-PLAYER_CHARGEMAX, -PLAYER_CHARGEMAX);
}
else
{
AddCharge((nChargeLevel-nchargemax)*PLAYER_CHARGEONE, (nChargeLevel-nchargemax)*PLAYER_CHARGEONE);
}
}
return true;
}
bool Player::SlowChange()
{
if(GameInput::GetKey(playerindex, KSI_SLOW, DIKEY_DOWN))
slowtimer = 0;
bSlow = true;
slowtimer++;
if(slowtimer == 1)
{
ResetPlayerGhost();
SE::push(SE_PLAYER_SLOWON, x);
for(int i=0;i<PLAYERGHOSTMAX;i++)
{
pg[i].timer = 0;
}
}
else if(slowtimer == 16)
{
esPoint.colorSet(0xffffffff);
slowtimer = 0;
return true;
}
esPoint.actionSet(0, 0, (24 - slowtimer) * 25);
esPoint.colorSet(((slowtimer*16)<<24)+0xffffff);
return false;
}
bool Player::FastChange()
{
if(GameInput::GetKey(playerindex, KSI_SLOW, DIKEY_UP))
fasttimer = 0;
bSlow = false;
fasttimer++;
if(fasttimer == 1)
{
ResetPlayerGhost();
SE::push(SE_PLAYER_SLOWOFF, x);
for(int i=0;i<PLAYERGHOSTMAX;i++)
{
pg[i].timer = 0;
}
}
else if(fasttimer == 16)
{
esPoint.colorSet(0x00ffffff);
fasttimer = 0;
return true;
}
esPoint.colorSet(((0xff-fasttimer*16)<<24)+0xffffff);
return false;
}
bool Player::Charge()
{
chargetimer++;
if (chargetimer == 1)
{
SE::push(SE_PLAYER_CHARGEON, x);
}
BYTE nChargeLevel = AddCharge(chargespeed);
if (!GameInput::GetKey(playerindex, KSI_FIRE))
{
shootCharge(nChargeLevel);
chargetimer = 0;
fCharge = 0;
if (nChargeLevel > 0)
{
rechargedelaytimer = rechargedelay;
}
return true;
}
bCharge = true;
return false;
}
bool Player::PlayerChange()
{
if(GameInput::GetKey(playerindex, KSI_DRAIN, DIKEY_DOWN))
playerchangetimer = 0;
playerchangetimer++;
if(playerchangetimer == 1)
{
}
else if(playerchangetimer == 16)
{
playerchangetimer = 0;
return true;
}
esChange.colorSet(0x3030ff | (((16-playerchangetimer) * 16)<<16));
return false;
}
void Player::changePlayerID(WORD toID, bool moveghost/* =false */)
{
nowID = toID;
ResetPlayerGhost(moveghost);
UpdatePlayerData();
}
bool Player::Graze()
{
effGraze.Fire();
SE::push(SE_PLAYER_GRAZE, x);
return true;
}
void Player::DoEnemyCollapse(float x, float y, BYTE type)
{
float addcharge = nComboHitOri / 128.0f + 1.0f;
if (addcharge > 2.0f)
{
addcharge = 2.0f;
}
AddComboHit(1, true);
AddCharge(0, addcharge);
enemyData * edata = &(BResource::bres.enemydata[type]);
AddExPoint(edata->expoint, x, y);
int addghostpoint;
if (edata->ghostpoint < 0)
{
addghostpoint = nComboHitOri + 3;
if (addghostpoint > 28)
{
addghostpoint = 28;
}
}
else
{
addghostpoint = edata->ghostpoint;
}
AddGhostPoint(addghostpoint, x, y);
int addbulletpoint;
float _x = x + randtf(-4.0f, 4.0f);
float _y = y + randtf(-4.0f, 4.0f);
if (edata->bulletpoint < 0)
{
addbulletpoint = nComboHitOri * 3 + 27;
if (addbulletpoint > 60)
{
addbulletpoint = 60;
}
}
else
{
addbulletpoint = edata->bulletpoint;
}
AddBulletPoint(addbulletpoint, _x, _y);
int addspellpoint;
if (edata->spellpoint == -1)
{
if (nComboHitOri == 1)
{
addspellpoint = 20;
}
else
{
addspellpoint = nComboHitOri * 30 - 20;
if (addspellpoint > 3000)
{
addspellpoint = 3000;
}
}
}
else if (edata->spellpoint == -2)
{
if (nComboHitOri == 1)
{
addspellpoint = 2000;
}
else
{
addspellpoint = (nComboHitOri + 4) * 200;
if (addspellpoint > 11000)
{
addspellpoint = 11000;
}
}
}
else
{
addspellpoint = edata->spellpoint;
}
AddSpellPoint(addspellpoint);
}
void Player::DoGraze(float x, float y)
{
if(!(flag & (PLAYER_MERGE | PLAYER_SHOT | PLAYER_COLLAPSE)))
{
flag |= PLAYER_GRAZE;
}
}
void Player::DoPlayerBulletHit(int hitonfactor)
{
if (hitonfactor < 0)
{
AddComboHit(-1, true);
}
}
void Player::DoSendBullet(float x, float y, int sendbonus)
{
for (int i=0; i<sendbonus; i++)
{
AddComboHit(1, false);
AddGhostPoint(2, x, y);
AddBulletPoint(3, x, y);
int addspellpoint = nComboHitOri * 9;
if (addspellpoint > 1000)
{
addspellpoint = 1000;
}
AddSpellPoint(addspellpoint);
}
}
void Player::DoShot()
{
if (!bInfi && !(flag & (PLAYER_SHOT | PLAYER_COLLAPSE)))
{
flag |= PLAYER_SHOT;
AddComboHit(-1, true);
AddSpellPoint(-1);
}
}
void Player::DoItemGet(WORD itemtype, float _x, float _y)
{
switch (itemtype)
{
case ITEM_GAUGE:
AddCharge(0, PLAYER_CHARGEMAX);
break;
case ITEM_BULLET:
Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERSENDITEMBULLET, playerindex);
// Item::SendBullet(1-playerindex, _x, _y, EFFSPSET_SYSTEM_SENDITEMBULLET);
break;
case ITEM_EX:
AddBulletPoint(1, _x, _y);
AddExPoint(100, _x, _y);
break;
case ITEM_POINT:
AddSpellPoint(70000+rank*7000);
break;
}
}
void Player::GetNCharge(BYTE * ncharge, BYTE * nchargemax)
{
if (ncharge)
{
*ncharge = (BYTE)(fCharge/PLAYER_CHARGEONE);
}
if (nchargemax)
{
*nchargemax = (BYTE)(fChargeMax/PLAYER_CHARGEONE);
}
}
void Player::GetSpellClassAndLevel(BYTE * spellclass, BYTE * spelllevel, int _shootingchargeflag)
{
BYTE usingshootingchargeflag = shootingchargeflag;
if (_shootingchargeflag > 0)
{
usingshootingchargeflag = _shootingchargeflag;
}
if (spellclass)
{
if (usingshootingchargeflag & _PL_SHOOTINGCHARGE_4)
{
if ((usingshootingchargeflag & _PL_SHOOTINGCHARGE_3) || (usingshootingchargeflag & _PL_SHOOTINGCHARGE_2))
{
*spellclass = 4;
}
else
{
*spellclass = 3;
}
}
else if (usingshootingchargeflag & _PL_SHOOTINGCHARGE_3)
{
*spellclass = 2;
}
else if (usingshootingchargeflag & _PL_SHOOTINGCHARGE_2)
{
*spellclass = 1;
}
else
{
*spellclass = 0;
}
}
if (spelllevel)
{
if (usingshootingchargeflag & _PL_SHOOTINGCHARGE_4)
{
*spelllevel = nowbosslevel;
}
else if(usingshootingchargeflag)
{
*spelllevel = nowcardlevel;
}
else
{
*spelllevel = 0;
}
}
}
void Player::ResetPlayerGhost(bool move /* = false */)
{
int tid = nowID;
tid *= PLAYERGHOSTMAX * 2;
if (bSlow)
{
tid += PLAYERGHOSTMAX;
}
for (int i=0; i<PLAYERGHOSTMAX; i++)
{
pg[i].valueSet(playerindex, tid+i, move);
}
}
void Player::Render()
{
if (spdrain && bDrain)
{
SpriteItemManager::RenderSpriteEx(spdrain, drainx, drainy, ARC(drainheadangle), drainhscale, drainvscale);
if (draincopyspriteangle)
{
SpriteItemManager::RenderSpriteEx(spdrain, drainx, drainy, ARC(drainheadangle+draincopyspriteangle), drainhscale, drainvscale);
}
}
if (sprite)
{
sprite->SetColor(alpha<<24|diffuse);
SpriteItemManager::RenderSpriteEx(sprite, x, y, 0, hscale, vscale);
}
}
void Player::RenderEffect()
{
effGraze.Render();
for(int i=0;i<PLAYERGHOSTMAX;i++)
{
if (pg[i].exist)
{
pg[i].Render();
}
}
if(flag & PLAYER_PLAYERCHANGE)
{
esChange.Render();
}
if(flag & PLAYER_SHOT)
esShot.Render();
effBorderOff.Render();
if(bSlow || flag & PLAYER_FASTCHANGE)
{
esPoint.Render();
esPoint.headangle = -esPoint.headangle;
esPoint.Render();
esPoint.headangle = -esPoint.headangle;
}
if(flag & PLAYER_COLLAPSE)
esCollapse.Render();
effCollapse.Render();
}
void Player::callCollapse()
{
if (flag & PLAYER_COLLAPSE)
{
return;
}
flag |= PLAYER_COLLAPSE;
collapsetimer = 0;
}
bool Player::callBomb()
{
if (Chat::chatitem.IsChatting() || (flag & PLAYER_COLLAPSE))
{
return false;
}
return Bomb();
}
void Player::callSlowFastChange(bool toslow)
{
if (toslow)
{
GameInput::SetKey(playerindex, KSI_SLOW);
}
else
{
GameInput::SetKey(playerindex, KSI_SLOW, false);
}
}
void Player::callPlayerChange()
{
flag |= PLAYER_PLAYERCHANGE;
playerchangetimer = 0;
}
void Player::setShootingCharge(BYTE _shootingchargeflag)
{
if (!_shootingchargeflag)
{
shootingchargeflag = 0;
}
else
{
shootingchargeflag |= _shootingchargeflag;
if (shootingchargeflag & _PL_SHOOTINGCHARGE_1)
{
shootchargetimer = BResource::bres.playerdata[nowID].shootchargetime;
}
if (_shootingchargeflag & ~_PL_SHOOTINGCHARGE_1)
{
nowshootingcharge = _shootingchargeflag;
if (_shootingchargeflag & _PL_SHOOTINGCHARGE_4)
{
nowbosslevel = bosslevel;
}
else
{
nowcardlevel = cardlevel;
}
Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERSHOOTCHARGE, playerindex);
}
}
}
BYTE Player::shootCharge(BYTE nChargeLevel, bool nodelete)
{
if (flag & PLAYER_COLLAPSE)
{
return 0;
}
if (!nChargeLevel)
{
return 0;
}
if (nChargeLevel > 3 && nChargeLevel < 7 && Enemy::bossindex[1-playerindex] != 0xff)
{
if (nChargeLevel == 4)
{
return shootCharge(3, nodelete);
}
else if (nChargeLevel == 6)
{
return shootCharge(7, nodelete);
}
return 0;
}
setShootingCharge(0);
int chargezonemaxtime=1;
float chargezoner=0;
switch (nChargeLevel)
{
case 1:
SetInfi(PLAYERINFI_SHOOTCHARGE, _PL_SHOOTCHARGEINFI_1);
setShootingCharge(_PL_SHOOTINGCHARGE_1);
// AddCardBossLevel(1, 0);
break;
case 2:
SetInfi(PLAYERINFI_SHOOTCHARGE, _PL_SHOOTCHARGEINFI_2);
if (!nodelete)
{
setShootingCharge(_PL_SHOOTINGCHARGE_1);
}
setShootingCharge(_PL_SHOOTINGCHARGE_2);
AddCardBossLevel(1, 0);
chargezonemaxtime = _PL_CHARGEZONE_MAXTIME_2;
chargezoner = _PL_CHARGEZONE_R_2;
break;
case 3:
SetInfi(PLAYERINFI_SHOOTCHARGE, _PL_SHOOTCHARGEINFI_3);
if (!nodelete)
{
setShootingCharge(_PL_SHOOTINGCHARGE_1);
}
setShootingCharge(_PL_SHOOTINGCHARGE_3);
AddCardBossLevel(1, 0);
chargezonemaxtime = _PL_CHARGEZONE_MAXTIME_3;
chargezoner = _PL_CHARGEZONE_R_3;
break;
case 4:
SetInfi(PLAYERINFI_SHOOTCHARGE, _PL_SHOOTCHARGEINFI_4);
if (!nodelete)
{
setShootingCharge(_PL_SHOOTINGCHARGE_1);
}
setShootingCharge(_PL_SHOOTINGCHARGE_4);
AddCardBossLevel(0, 1);
chargezonemaxtime = _PL_CHARGEZONE_MAXTIME_4;
chargezoner = _PL_CHARGEZONE_R_4;
break;
case 5:
setShootingCharge(_PL_SHOOTINGCHARGE_4);
AddCardBossLevel(0, 1);
break;
case 6:
setShootingCharge(_PL_SHOOTINGCHARGE_3);
setShootingCharge(_PL_SHOOTINGCHARGE_4);
AddCardBossLevel(1, 1);
break;
case 7:
setShootingCharge(_PL_SHOOTINGCHARGE_3);
AddCardBossLevel(1, 0);
break;
}
if (nChargeLevel > 1)
{
raisespellstopplayerindex = playerindex;
spellstoptimer = 0;
Process::mp.SetStop(FRAME_STOPFLAG_SPELLSET|FRAME_STOPFLAG_PLAYERINDEX_0|FRAME_STOPFLAG_PLAYERINDEX_1, PL_SHOOTINGCHARGE_STOPTIME);
if (chargezoner)
{
EventZone::Build(EVENTZONE_TYPE_BULLETFADEOUT|EVENTZONE_TYPE_ENEMYDAMAGE|EVENTZONE_TYPE_NOSEND|EVENTZONE_CHECKTYPE_CIRCLE, playerindex, x, y, chargezonemaxtime, 0, 0, 10, EVENTZONE_EVENT_NULL, chargezoner/chargezonemaxtime, -2, SpriteItemManager::GetIndexByName(SI_PLAYER_CHARGEZONE), 400);
}
if (nChargeLevel < 5)
{
AddCharge(-PLAYER_CHARGEONE*(nChargeLevel-1), -PLAYER_CHARGEONE*(nChargeLevel-1));
}
AddLilyCount(-500);
FrontDisplay::fdisp.OnShootCharge(playerindex, nowshootingcharge);
}
return nChargeLevel;
}
void Player::SendEx(BYTE playerindex, float x, float y)
{
int _esindex = EffectSp::Build(EFFSPSET_SYSTEM_SENDEXATTACK, playerindex, EffectSp::senditemexsiid, x, y);
if (_esindex >= 0)
{
Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERSENDEX, playerindex);
SE::push(SE_BULLET_SENDEX, x);
}
}
void Player::AddExPoint(float expoint, float x, float y)
{
fExPoint += expoint;
float fexsend = fExSendParaB + fExSendParaA * rank;
if (fexsend < fExSendMax)
{
fexsend = fExSendMax;
}
if (fExPoint >= fexsend)
{
AddExPoint(-fexsend, x, y);
SendEx(1-playerindex, x, y);
}
}
void Player::AddGhostPoint(int ghostpoint, float x, float y)
{
nGhostPoint += ghostpoint;
if (nGhostPoint >= 60-rank*1.5f)
{
if (nBulletPoint >= 10)
{
AddGhostPoint(-(60-rank*2), x, y);
AddBulletPoint(-10, x, y);
Enemy::SendGhost(1-playerindex, x, y, EFFSPSET_SYSTEM_SENDGHOST);
}
}
}
void Player::AddBulletPoint(int bulletpoint, float x, float y)
{
nBulletPoint += bulletpoint * 4 / 3;
if (nBulletPoint >= 120-rank*4)
{
AddBulletPoint(-(120-rank*4), x, y);
BYTE setID = EFFSPSET_SYSTEM_SENDBLUEBULLET;
if (randt(0, 2) == 0)
{
setID = EFFSPSET_SYSTEM_SENDREDBULLET;
}
Bullet::SendBullet(1-playerindex, x, y, setID);
}
}
void Player::AddSpellPoint(int spellpoint)
{
if (spellpoint < 0)
{
nSpellPoint = 0;
return;
}
spellpoint = spellpoint * rank / 10 + spellpoint;
int spellpointone = spellpoint % 10;
if (spellpointone)
{
spellpoint += 10-spellpointone;
}
if (nSpellPoint < _PL_SPELLBONUS_BOSS_1 && nSpellPoint + spellpoint >= _PL_SPELLBONUS_BOSS_1 ||
nSpellPoint < _PL_SPELLBONUS_BOSS_2 && nSpellPoint + spellpoint >= _PL_SPELLBONUS_BOSS_2)
{
shootCharge(5);
}
else if (nSpellPoint < _PL_SPELLBONUS_BOSS_3 && nSpellPoint + spellpoint >= _PL_SPELLBONUS_BOSS_3)
{
shootCharge(6);
}
nSpellPoint += spellpoint;
if (nSpellPoint > PLAYER_NSPELLPOINTMAX)
{
nSpellPoint = PLAYER_NSPELLPOINTMAX;
}
}
void Player::AddComboHit(int combo, bool ori)
{
if (combo < 0)
{
nComboHit = 0;
nComboHitOri = 0;
return;
}
nComboHit += combo;
if (nComboHit > PLAYER_NCOMBOHITMAX)
{
nComboHit = PLAYER_NCOMBOHITMAX;
}
if (ori)
{
nComboHitOri += combo;
if (nComboHitOri > PLAYER_NCOMBOHITMAX)
{
nComboHitOri = PLAYER_NCOMBOHITMAX;
}
}
if (nComboGage < 74)
{
nComboGage += 30;
if (nComboGage < 74)
{
nComboGage = 74;
}
}
else if (nComboGage < 94)
{
nComboGage += 5;
}
else
{
nComboGage += 2;
}
if (nComboGage > PLAYER_COMBOGAGEMAX)
{
nComboGage = PLAYER_COMBOGAGEMAX;
}
}
BYTE Player::AddCharge(float addcharge, float addchargemax)
{
BYTE ncharge;
BYTE nchargemax;
GetNCharge(&ncharge, &nchargemax);
float addchargemaxval = addchargemax;
if (addchargemax > 0)
{
addchargemaxval = addchargemax * BResource::bres.playerdata[nowID].addchargerate;
}
fChargeMax += addchargemaxval;
if (fChargeMax > PLAYER_CHARGEMAX)
{
fChargeMax = PLAYER_CHARGEMAX;
}
if (fChargeMax < 0)
{
fChargeMax = 0;
}
fCharge += addcharge;
if (fCharge > fChargeMax)
{
fCharge = fChargeMax;
}
if (fCharge < 0)
{
fCharge = 0;
}
BYTE nchargenow;
BYTE nchargemaxnow;
GetNCharge(&nchargenow, &nchargemaxnow);
if (nchargenow > ncharge)
{
SE::push(SE_PLAYER_CHARGEUP);
}
if (nchargemaxnow > nchargemax)
{
FrontDisplay::fdisp.gameinfodisplay.gaugefilledcountdown[playerindex] = FDISP_COUNTDOWNTIME;
}
return nchargenow;
}
void Player::AddLilyCount(int addval, bool bytime/* =false */)
{
if (bytime)
{
if (gametime < 5400)
{
AddLilyCount(gametime/1800+3);
}
else
{
AddLilyCount(7);
}
}
lilycount += addval;
if (lilycount > 10000)
{
Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERSENDLILY, rank);
AddLilyCount(-10000);
}
else if (lilycount < 0)
{
lilycount = 0;
}
}
void Player::AddCardBossLevel(int cardleveladd, int bossleveladd)
{
cardlevel += cardleveladd;
bosslevel += bossleveladd;
if (cardlevel > _CARDLEVEL_MAX)
{
cardlevel = _CARDLEVEL_MAX;
}
if (bosslevel > _BOSSLEVEL_MAX)
{
bosslevel = _BOSSLEVEL_MAX;
}
}
| [
"CBE7F1F65@4a173d03-4959-223b-e14c-e2eaa5fc8a8b"
] | [
[
[
1,
1759
]
]
] |
fefc953311bbdd7ec91f1d0047afbc4eb01ce354 | 10c14a95421b63a71c7c99adf73e305608c391bf | /gui/core/qsize.cpp | a55b26ea65d32ffc8b573f00f2e2391ec6a953df | [] | no_license | eaglezzb/wtlcontrols | 73fccea541c6ef1f6db5600f5f7349f5c5236daa | 61b7fce28df1efe4a1d90c0678ec863b1fd7c81c | refs/heads/master | 2021-01-22 13:47:19 | 2009-05-19 10:58:42 | 2009-05-19 10:58:42 | 33,811,815 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,576 | cpp | /****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** 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 qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qsize.h"
// #include "qdatastream.h"
// #include "qdebug.h"
QT_BEGIN_NAMESPACE
/*!
\class QSize
\ingroup multimedia
\brief The QSize class defines the size of a two-dimensional
object using integer point precision.
A size is specified by a width() and a height(). It can be set in
the constructor and changed using the setWidth(), setHeight(), or
scale() functions, or using arithmetic operators. A size can also
be manipulated directly by retrieving references to the width and
height using the rwidth() and rheight() functions. Finally, the
width and height can be swapped using the transpose() function.
The isValid() function determines if a size is valid (a valid size
has both width and height greater than zero). The isEmpty()
function returns true if either of the width and height is less
than, or equal to, zero, while the isNull() function returns true
only if both the width and the height is zero.
Use the expandedTo() function to retrieve a size which holds the
maximum height and width of \e this size and a given
size. Similarly, the boundedTo() function returns a size which
holds the minimum height and width of \e this size and a given
size.
QSize objects can be streamed as well as compared.
\sa QSizeF, QPoint, QRect
*/
/*****************************************************************************
QSize member functions
*****************************************************************************/
/*!
\fn QSize::QSize()
Constructs a size with an invalid width and height (i.e., isValid()
returns false).
\sa isValid()
*/
/*!
\fn QSize::QSize(int width, int height)
Constructs a size with the given \a width and \a height.
\sa setWidth(), setHeight()
*/
/*!
\fn bool QSize::isNull() const
Returns true if both the width and height is 0; otherwise returns
false.
\sa isValid(), isEmpty()
*/
/*!
\fn bool QSize::isEmpty() const
Returns true if either of the width and height is less than or
equal to 0; otherwise returns false.
\sa isNull(), isValid()
*/
/*!
\fn bool QSize::isValid() const
Returns true if both the width and height is equal to or greater
than 0; otherwise returns false.
\sa isNull(), isEmpty()
*/
/*!
\fn int QSize::width() const
Returns the width.
\sa height(), setWidth()
*/
/*!
\fn int QSize::height() const
Returns the height.
\sa width(), setHeight()
*/
/*!
\fn void QSize::setWidth(int width)
Sets the width to the given \a width.
\sa rwidth(), width(), setHeight()
*/
/*!
\fn void QSize::setHeight(int height)
Sets the height to the given \a height.
\sa rheight(), height(), setWidth()
*/
/*!
Swaps the width and height values.
\sa setWidth(), setHeight()
*/
void QSize::transpose()
{
int tmp = wd;
wd = ht;
ht = tmp;
}
/*!
\fn void QSize::scale(int width, int height, Qt::AspectRatioMode mode)
Scales the size to a rectangle with the given \a width and \a
height, according to the specified \a mode:
\list
\i If \a mode is Qt::IgnoreAspectRatio, the size is set to (\a width, \a height).
\i If \a mode is Qt::KeepAspectRatio, the current size is scaled to a rectangle
as large as possible inside (\a width, \a height), preserving the aspect ratio.
\i If \a mode is Qt::KeepAspectRatioByExpanding, the current size is scaled to a rectangle
as small as possible outside (\a width, \a height), preserving the aspect ratio.
\endlist
Example:
\snippet doc/src/snippets/code/src_corelib_tools_qsize.cpp 0
\sa setWidth(), setHeight()
*/
/*!
\fn void QSize::scale(const QSize &size, Qt::AspectRatioMode mode)
\overload
Scales the size to a rectangle with the given \a size, according to
the specified \a mode.
*/
void QSize::scale(const QSize &s, Qt::AspectRatioMode mode)
{
if (mode == Qt::IgnoreAspectRatio || wd == 0 || ht == 0) {
wd = s.wd;
ht = s.ht;
} else {
bool useHeight;
qint64 rw = qint64(s.ht) * qint64(wd) / qint64(ht);
if (mode == Qt::KeepAspectRatio) {
useHeight = (rw <= s.wd);
} else { // mode == Qt::KeepAspectRatioByExpanding
useHeight = (rw >= s.wd);
}
if (useHeight) {
wd = rw;
ht = s.ht;
} else {
ht = qint32(qint64(s.wd) * qint64(ht) / qint64(wd));
wd = s.wd;
}
}
}
/*!
\fn int &QSize::rwidth()
Returns a reference to the width.
Using a reference makes it possible to manipulate the width
directly. For example:
\snippet doc/src/snippets/code/src_corelib_tools_qsize.cpp 1
\sa rheight(), setWidth()
*/
/*!
\fn int &QSize::rheight()
Returns a reference to the height.
Using a reference makes it possible to manipulate the height
directly. For example:
\snippet doc/src/snippets/code/src_corelib_tools_qsize.cpp 2
\sa rwidth(), setHeight()
*/
/*!
\fn QSize &QSize::operator+=(const QSize &size)
Adds the given \a size to \e this size, and returns a reference to
this size. For example:
\snippet doc/src/snippets/code/src_corelib_tools_qsize.cpp 3
*/
/*!
\fn QSize &QSize::operator-=(const QSize &size)
Subtracts the given \a size from \e this size, and returns a
reference to this size. For example:
\snippet doc/src/snippets/code/src_corelib_tools_qsize.cpp 4
*/
/*!
\fn QSize &QSize::operator*=(qreal factor)
\overload
Multiplies both the width and height by the given \a factor, and
returns a reference to the size.
Note that the result is rounded to the nearest integer.
\sa scale()
*/
/*!
\fn bool operator==(const QSize &s1, const QSize &s2)
\relates QSize
Returns true if \a s1 and \a s2 are equal; otherwise returns false.
*/
/*!
\fn bool operator!=(const QSize &s1, const QSize &s2)
\relates QSize
Returns true if \a s1 and \a s2 are different; otherwise returns false.
*/
/*!
\fn const QSize operator+(const QSize &s1, const QSize &s2)
\relates QSize
Returns the sum of \a s1 and \a s2; each component is added separately.
*/
/*!
\fn const QSize operator-(const QSize &s1, const QSize &s2)
\relates QSize
Returns \a s2 subtracted from \a s1; each component is subtracted
separately.
*/
/*!
\fn const QSize operator*(const QSize &size, qreal factor)
\relates QSize
Multiplies the given \a size by the given \a factor, and returns
the result rounded to the nearest integer.
\sa QSize::scale()
*/
/*!
\fn const QSize operator*(qreal factor, const QSize &size)
\overload
\relates QSize
Multiplies the given \a size by the given \a factor, and returns
the result rounded to the nearest integer.
*/
/*!
\fn QSize &QSize::operator/=(qreal divisor)
\overload
Divides both the width and height by the given \a divisor, and
returns a reference to the size.
Note that the result is rounded to the nearest integer.
\sa QSize::scale()
*/
/*!
\fn const QSize operator/(const QSize &size, qreal divisor)
\relates QSize
\overload
Divides the given \a size by the given \a divisor, and returns the
result rounded to the nearest integer.
\sa QSize::scale()
*/
/*!
\fn QSize QSize::expandedTo(const QSize & otherSize) const
Returns a size holding the maximum width and height of this size
and the given \a otherSize.
\sa boundedTo(), scale()
*/
/*!
\fn QSize QSize::boundedTo(const QSize & otherSize) const
Returns a size holding the minimum width and height of this size
and the given \a otherSize.
\sa expandedTo(), scale()
*/
/*****************************************************************************
QSize stream functions
*****************************************************************************/
// #ifndef QT_NO_DATASTREAM
// /*!
// \fn QDataStream &operator<<(QDataStream &stream, const QSize &size)
// \relates QSize
//
// Writes the given \a size to the given \a stream, and returns a
// reference to the stream.
//
// \sa {Format of the QDataStream Operators}
// */
//
// QDataStream &operator<<(QDataStream &s, const QSize &sz)
// {
// if (s.version() == 1)
// s << (qint16)sz.width() << (qint16)sz.height();
// else
// s << (qint32)sz.width() << (qint32)sz.height();
// return s;
// }
//
// /*!
// \fn QDataStream &operator>>(QDataStream &stream, QSize &size)
// \relates QSize
//
// Reads a size from the given \a stream into the given \a size, and
// returns a reference to the stream.
//
// \sa {Format of the QDataStream Operators}
// */
//
// QDataStream &operator>>(QDataStream &s, QSize &sz)
// {
// if (s.version() == 1) {
// qint16 w, h;
// s >> w; sz.rwidth() = w;
// s >> h; sz.rheight() = h;
// }
// else {
// qint32 w, h;
// s >> w; sz.rwidth() = w;
// s >> h; sz.rheight() = h;
// }
// return s;
// }
// #endif // QT_NO_DATASTREAM
//
// #ifndef QT_NO_DEBUG_STREAM
// QDebug operator<<(QDebug dbg, const QSize &s) {
// dbg.nospace() << "QSize(" << s.width() << ", " << s.height() << ')';
// return dbg.space();
// }
// #endif
/*!
\class QSizeF
\brief The QSizeF class defines the size of a two-dimensional object
using floating point precision.
\ingroup multimedia
A size is specified by a width() and a height(). It can be set in
the constructor and changed using the setWidth(), setHeight(), or
scale() functions, or using arithmetic operators. A size can also
be manipulated directly by retrieving references to the width and
height using the rwidth() and rheight() functions. Finally, the
width and height can be swapped using the transpose() function.
The isValid() function determines if a size is valid. A valid size
has both width and height greater than or equal to zero. The
isEmpty() function returns true if either of the width and height
is \e less than (or equal to) zero, while the isNull() function
returns true only if both the width and the height is zero.
Use the expandedTo() function to retrieve a size which holds the
maximum height and width of this size and a given
size. Similarly, the boundedTo() function returns a size which
holds the minimum height and width of this size and a given size.
The QSizeF class also provides the toSize() function returning a
QSize copy of this size, constructed by rounding the width and
height to the nearest integers.
QSizeF objects can be streamed as well as compared.
\sa QSize, QPointF, QRectF
*/
/*****************************************************************************
QSizeF member functions
*****************************************************************************/
/*!
\fn QSizeF::QSizeF()
Constructs an invalid size.
\sa isValid()
*/
/*!
\fn QSizeF::QSizeF(const QSize &size)
Constructs a size with floating point accuracy from the given \a
size.
\sa toSize()
*/
/*!
\fn QSizeF::QSizeF(qreal width, qreal height)
Constructs a size with the given \a width and \a height.
*/
/*!
\fn bool QSizeF::isNull() const
Returns true if both the width and height is 0; otherwise returns
false.
\sa isValid(), isEmpty()
*/
/*!
\fn bool QSizeF::isEmpty() const
Returns true if either of the width and height is less than or
equal to 0; otherwise returns false.
\sa isNull(), isValid()
*/
/*!
\fn bool QSizeF::isValid() const
Returns true if both the width and height is equal to or greater
than 0; otherwise returns false.
\sa isNull(), isEmpty()
*/
/*!
\fn int QSizeF::width() const
Returns the width.
\sa height(), setWidth()
*/
/*!
\fn int QSizeF::height() const
Returns the height.
\sa width(), setHeight()
*/
/*!
\fn void QSizeF::setWidth(qreal width)
Sets the width to the given \a width.
\sa width(), rwidth(), setHeight()
*/
/*!
\fn void QSizeF::setHeight(qreal height)
Sets the height to the given \a height.
\sa height(), rheight(), setWidth()
*/
/*!
\fn QSize QSizeF::toSize() const
Returns an integer based copy of this size.
Note that the coordinates in the returned size will be rounded to
the nearest integer.
\sa QSizeF()
*/
/*!
Swaps the width and height values.
\sa setWidth(), setHeight()
*/
void QSizeF::transpose()
{
qreal tmp = wd;
wd = ht;
ht = tmp;
}
/*!
\fn void QSizeF::scale(qreal width, qreal height, Qt::AspectRatioMode mode)
Scales the size to a rectangle with the given \a width and \a
height, according to the specified \a mode.
\list
\i If \a mode is Qt::IgnoreAspectRatio, the size is set to (\a width, \a height).
\i If \a mode is Qt::KeepAspectRatio, the current size is scaled to a rectangle
as large as possible inside (\a width, \a height), preserving the aspect ratio.
\i If \a mode is Qt::KeepAspectRatioByExpanding, the current size is scaled to a rectangle
as small as possible outside (\a width, \a height), preserving the aspect ratio.
\endlist
Example:
\snippet doc/src/snippets/code/src_corelib_tools_qsize.cpp 5
\sa setWidth(), setHeight()
*/
/*!
\fn void QSizeF::scale(const QSizeF &size, Qt::AspectRatioMode mode)
\overload
Scales the size to a rectangle with the given \a size, according to
the specified \a mode.
*/
void QSizeF::scale(const QSizeF &s, Qt::AspectRatioMode mode)
{
if (mode == Qt::IgnoreAspectRatio || qIsNull(wd) || qIsNull(ht)) {
wd = s.wd;
ht = s.ht;
} else {
bool useHeight;
qreal rw = s.ht * wd / ht;
if (mode == Qt::KeepAspectRatio) {
useHeight = (rw <= s.wd);
} else { // mode == Qt::KeepAspectRatioByExpanding
useHeight = (rw >= s.wd);
}
if (useHeight) {
wd = rw;
ht = s.ht;
} else {
ht = s.wd * ht / wd;
wd = s.wd;
}
}
}
/*!
\fn int &QSizeF::rwidth()
Returns a reference to the width.
Using a reference makes it possible to manipulate the width
directly. For example:
\snippet doc/src/snippets/code/src_corelib_tools_qsize.cpp 6
\sa rheight(), setWidth()
*/
/*!
\fn int &QSizeF::rheight()
Returns a reference to the height.
Using a reference makes it possible to manipulate the height
directly. For example:
\snippet doc/src/snippets/code/src_corelib_tools_qsize.cpp 7
\sa rwidth(), setHeight()
*/
/*!
\fn QSizeF &QSizeF::operator+=(const QSizeF &size)
Adds the given \a size to this size and returns a reference to
this size. For example:
\snippet doc/src/snippets/code/src_corelib_tools_qsize.cpp 8
*/
/*!
\fn QSizeF &QSizeF::operator-=(const QSizeF &size)
Subtracts the given \a size from this size and returns a reference
to this size. For example:
\snippet doc/src/snippets/code/src_corelib_tools_qsize.cpp 9
*/
/*!
\fn QSizeF &QSizeF::operator*=(qreal factor)
\overload
Multiplies both the width and height by the given \a factor and
returns a reference to the size.
\sa scale()
*/
/*!
\fn bool operator==(const QSizeF &s1, const QSizeF &s2)
\relates QSizeF
Returns true if \a s1 and \a s2 are equal; otherwise returns
false.
*/
/*!
\fn bool operator!=(const QSizeF &s1, const QSizeF &s2)
\relates QSizeF
Returns true if \a s1 and \a s2 are different; otherwise returns false.
*/
/*!
\fn const QSizeF operator+(const QSizeF &s1, const QSizeF &s2)
\relates QSizeF
Returns the sum of \a s1 and \a s2; each component is added separately.
*/
/*!
\fn const QSizeF operator-(const QSizeF &s1, const QSizeF &s2)
\relates QSizeF
Returns \a s2 subtracted from \a s1; each component is subtracted
separately.
*/
/*!
\fn const QSizeF operator*(const QSizeF &size, qreal factor)
\overload
\relates QSizeF
Multiplies the given \a size by the given \a factor and returns
the result.
\sa QSizeF::scale()
*/
/*!
\fn const QSizeF operator*(qreal factor, const QSizeF &size)
\overload
\relates QSizeF
Multiplies the given \a size by the given \a factor and returns
the result.
*/
/*!
\fn QSizeF &QSizeF::operator/=(qreal divisor)
\overload
Divides both the width and height by the given \a divisor and
returns a reference to the size.
\sa scale()
*/
/*!
\fn const QSizeF operator/(const QSizeF &size, qreal divisor)
\relates QSizeF
\overload
Divides the given \a size by the given \a divisor and returns the
result.
\sa QSizeF::scale()
*/
/*!
\fn QSizeF QSizeF::expandedTo(const QSizeF & otherSize) const
Returns a size holding the maximum width and height of this size
and the given \a otherSize.
\sa boundedTo(), scale()
*/
/*!
\fn QSizeF QSizeF::boundedTo(const QSizeF & otherSize) const
Returns a size holding the minimum width and height of this size
and the given \a otherSize.
\sa expandedTo(), scale()
*/
/*****************************************************************************
QSizeF stream functions
*****************************************************************************/
// #ifndef QT_NO_DATASTREAM
// /*!
// \fn QDataStream &operator<<(QDataStream &stream, const QSizeF &size)
// \relates QSizeF
//
// Writes the the given \a size to the given \a stream and returns a
// reference to the stream.
//
// \sa {Format of the QDataStream Operators}
// */
//
// QDataStream &operator<<(QDataStream &s, const QSizeF &sz)
// {
// s << double(sz.width()) << double(sz.height());
// return s;
// }
//
// /*!
// \fn QDataStream &operator>>(QDataStream &stream, QSizeF &size)
// \relates QSizeF
//
// Reads a size from the given \a stream into the given \a size and
// returns a reference to the stream.
//
// \sa {Format of the QDataStream Operators}
// */
//
// QDataStream &operator>>(QDataStream &s, QSizeF &sz)
// {
// double w, h;
// s >> w;
// s >> h;
// sz.setWidth(qreal(w));
// sz.setHeight(qreal(h));
// return s;
// }
// #endif // QT_NO_DATASTREAM
//
// #ifndef QT_NO_DEBUG_STREAM
// QDebug operator<<(QDebug dbg, const QSizeF &s) {
// dbg.nospace() << "QSizeF(" << s.width() << ", " << s.height() << ')';
// return dbg.space();
// }
// #endif
QT_END_NAMESPACE
| [
"zhangyinquan@0feb242a-2539-11de-a0d7-251e5865a1c7"
] | [
[
[
1,
824
]
]
] |
218f5b663bbe8a76eff436d9cdcaf8678003e023 | d425cf21f2066a0cce2d6e804bf3efbf6dd00c00 | /Tactical/XML_EnemyItemChoice.cpp | ef2331f40fceb091d4ba797af11a1af0c38fc3f7 | [] | no_license | infernuslord/ja2 | d5ac783931044e9b9311fc61629eb671f376d064 | 91f88d470e48e60ebfdb584c23cc9814f620ccee | refs/heads/master | 2021-01-02 23:07:58 | 2011-10-18 09:22:53 | 2011-10-18 09:22:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,653 | cpp | #ifdef PRECOMPILEDHEADERS
#include "Tactical All.h"
#else
#include "sgp.h"
#include "overhead.h"
#include "weapons.h"
#include "Debug Control.h"
#include "expat.h"
#include "XML.h"
#include "Inventory Choosing.h"
#endif
struct
{
PARSE_STAGE curElement;
CHAR8 szCharData[MAX_CHAR_DATA_LENGTH+1];
ARMY_GUN_CHOICE_TYPE curArmyItemChoices;
ARMY_GUN_CHOICE_TYPE * curArray;
UINT32 maxArraySize;
UINT32 currentDepth;
UINT32 maxReadDepth;
}
typedef armyitemchoicesParseData;
static void XMLCALL
armyitemchoicesStartElementHandle(void *userData, const XML_Char *name, const XML_Char **atts)
{
armyitemchoicesParseData * pData = (armyitemchoicesParseData *)userData;
if(pData->currentDepth <= pData->maxReadDepth) //are we reading this element?
{
if(strcmp(name, "ENEMYITEMCHOICESLIST") == 0 && pData->curElement == ELEMENT_NONE)
{
pData->curElement = ELEMENT_LIST;
memset(pData->curArray,0,sizeof(ARMY_GUN_CHOICE_TYPE)*pData->maxArraySize);
pData->maxReadDepth++; //we are not skipping this element
}
else if(strcmp(name, "ENEMYITEMCHOICES") == 0 && pData->curElement == ELEMENT_LIST)
{
pData->curElement = ELEMENT;
memset(&pData->curArmyItemChoices,0,sizeof(ARMY_GUN_CHOICE_TYPE));
pData->maxReadDepth++; //we are not skipping this element
}
else if(pData->curElement == ELEMENT &&
(strcmp(name, "uiIndex") == 0 ||
strcmp(name, "ubChoices") == 0 ||
strcmp(name, "bItemNo1") == 0 ||
strcmp(name, "bItemNo2") == 0 ||
strcmp(name, "bItemNo3") == 0 ||
strcmp(name, "bItemNo4") == 0 ||
strcmp(name, "bItemNo5") == 0 ||
strcmp(name, "bItemNo6") == 0 ||
strcmp(name, "bItemNo7") == 0 ||
strcmp(name, "bItemNo8") == 0 ||
strcmp(name, "bItemNo9") == 0 ||
strcmp(name, "bItemNo10") == 0 ||
strcmp(name, "bItemNo11") == 0 ||
strcmp(name, "bItemNo12") == 0 ||
strcmp(name, "bItemNo13") == 0 ||
strcmp(name, "bItemNo14") == 0 ||
strcmp(name, "bItemNo15") == 0 ||
strcmp(name, "bItemNo16") == 0 ||
strcmp(name, "bItemNo17") == 0 ||
strcmp(name, "bItemNo18") == 0 ||
strcmp(name, "bItemNo19") == 0 ||
strcmp(name, "bItemNo20") == 0 ||
strcmp(name, "bItemNo21") == 0 ||
strcmp(name, "bItemNo22") == 0 ||
strcmp(name, "bItemNo23") == 0 ||
strcmp(name, "bItemNo24") == 0 ||
strcmp(name, "bItemNo25") == 0 ||
strcmp(name, "bItemNo26") == 0 ||
strcmp(name, "bItemNo27") == 0 ||
strcmp(name, "bItemNo28") == 0 ||
strcmp(name, "bItemNo29") == 0 ||
strcmp(name, "bItemNo30") == 0 ||
strcmp(name, "bItemNo31") == 0 ||
strcmp(name, "bItemNo32") == 0 ||
strcmp(name, "bItemNo33") == 0 ||
strcmp(name, "bItemNo34") == 0 ||
strcmp(name, "bItemNo35") == 0 ||
strcmp(name, "bItemNo36") == 0 ||
strcmp(name, "bItemNo37") == 0 ||
strcmp(name, "bItemNo38") == 0 ||
strcmp(name, "bItemNo39") == 0 ||
strcmp(name, "bItemNo40") == 0 ||
strcmp(name, "bItemNo41") == 0 ||
strcmp(name, "bItemNo42") == 0 ||
strcmp(name, "bItemNo43") == 0 ||
strcmp(name, "bItemNo44") == 0 ||
strcmp(name, "bItemNo45") == 0 ||
strcmp(name, "bItemNo46") == 0 ||
strcmp(name, "bItemNo47") == 0 ||
strcmp(name, "bItemNo48") == 0 ||
strcmp(name, "bItemNo49") == 0 ||
strcmp(name, "bItemNo50") == 0 ))
{
pData->curElement = ELEMENT_PROPERTY;
pData->maxReadDepth++; //we are not skipping this element
}
pData->szCharData[0] = '\0';
}
pData->currentDepth++;
}
static void XMLCALL
armyitemchoicesCharacterDataHandle(void *userData, const XML_Char *str, int len)
{
armyitemchoicesParseData * pData = (armyitemchoicesParseData *)userData;
if( (pData->currentDepth <= pData->maxReadDepth) &&
(strlen(pData->szCharData) < MAX_CHAR_DATA_LENGTH)
){
strncat(pData->szCharData,str,__min((unsigned int)len,MAX_CHAR_DATA_LENGTH-strlen(pData->szCharData)));
}
}
static void XMLCALL
armyitemchoicesEndElementHandle(void *userData, const XML_Char *name)
{
armyitemchoicesParseData * pData = (armyitemchoicesParseData *)userData;
if(pData->currentDepth <= pData->maxReadDepth) //we're at the end of an element that we've been reading
{
if(strcmp(name, "ENEMYITEMCHOICESLIST") == 0)
{
pData->curElement = ELEMENT_NONE;
}
else if(strcmp(name, "ENEMYITEMCHOICES") == 0)
{
pData->curElement = ELEMENT_LIST;
if(pData->curArmyItemChoices.uiIndex < pData->maxArraySize)
{
pData->curArray[pData->curArmyItemChoices.uiIndex] = pData->curArmyItemChoices; //write the armyitemchoices into the table
}
}
else if(strcmp(name, "uiIndex") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.uiIndex = (UINT32) atol(pData->szCharData);
}
else if(strcmp(name, "ubChoices") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.ubChoices = (UINT8) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo1") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[0] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo2") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[1] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo3") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[2] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo4") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[3] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo5") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[4] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo6") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[5] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo7") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[6] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo8") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[7] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo9") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[8] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo10") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[9] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo11") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[10] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo12") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[11] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo13") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[12] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo14") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[13] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo15") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[14] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo16") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[15] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo17") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[16] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo18") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[17] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo19") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[18] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo20") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[19] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo21") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[20] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo22") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[21] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo23") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[22] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo24") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[23] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo25") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[24] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo26") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[25] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo27") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[26] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo28") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[27] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo29") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[28] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo30") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[29] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo31") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[30] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo32") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[31] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo33") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[32] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo34") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[33] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo35") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[34] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo36") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[35] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo37") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[36] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo38") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[37] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo39") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[38] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo40") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[39] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo41") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[40] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo42") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[41] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo43") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[42] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo44") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[43] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo45") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[44] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo46") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[45] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo47") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[46] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo48") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[47] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo49") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[48] = (INT16) atol(pData->szCharData);
}
else if(strcmp(name, "bItemNo50") == 0)
{
pData->curElement = ELEMENT;
pData->curArmyItemChoices.bItemNo[49] = (INT16) atol(pData->szCharData);
}
pData->maxReadDepth--;
}
pData->currentDepth--;
}
BOOLEAN ReadInArmyItemChoicesStats(STR fileName)
{
HWFILE hFile;
UINT32 uiBytesRead;
UINT32 uiFSize;
CHAR8 * lpcBuffer;
XML_Parser parser = XML_ParserCreate(NULL);
armyitemchoicesParseData pData;
DebugMsg(TOPIC_JA2, DBG_LEVEL_3, "Loading EnemyItemChoicess.xml" );
// Open armyitemchoices file
hFile = FileOpen( fileName, FILE_ACCESS_READ, FALSE );
if ( !hFile )
return( FALSE );
uiFSize = FileGetSize(hFile);
lpcBuffer = (CHAR8 *) MemAlloc(uiFSize+1);
//Read in block
if ( !FileRead( hFile, lpcBuffer, uiFSize, &uiBytesRead ) )
{
MemFree(lpcBuffer);
return( FALSE );
}
lpcBuffer[uiFSize] = 0; //add a null terminator
FileClose( hFile );
XML_SetElementHandler(parser, armyitemchoicesStartElementHandle, armyitemchoicesEndElementHandle);
XML_SetCharacterDataHandler(parser, armyitemchoicesCharacterDataHandle);
memset(&pData,0,sizeof(pData));
pData.curArray = gArmyItemChoices;
pData.maxArraySize = MAX_ITEM_TYPES;
XML_SetUserData(parser, &pData);
if(!XML_Parse(parser, lpcBuffer, uiFSize, TRUE))
{
CHAR8 errorBuf[511];
sprintf(errorBuf, "XML Parser Error in EnemyItemChoicess.xml: %s at line %d", XML_ErrorString(XML_GetErrorCode(parser)), XML_GetCurrentLineNumber(parser));
LiveMessage(errorBuf);
MemFree(lpcBuffer);
return FALSE;
}
MemFree(lpcBuffer);
XML_ParserFree(parser);
return( TRUE );
}
BOOLEAN WriteArmyItemChoicesStats()
{
//DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"writearmyitemchoicesstats");
HWFILE hFile;
//Debug code; make sure that what we got from the file is the same as what's there
// Open a new file
hFile = FileOpen( "TABLEDATA\\EnemyItemChoices out.xml", FILE_ACCESS_WRITE | FILE_CREATE_ALWAYS, FALSE );
if ( !hFile )
return( FALSE );
{
UINT32 cnt;
FilePrintf(hFile,"<ENEMYITEMCHOICESLIST>\r\n");
for(cnt = 0;cnt < ARMY_GUN_LEVELS;cnt++)
{
FilePrintf(hFile,"\t<ENEMYITEMCHOICES>\r\n");
FilePrintf(hFile,"\t\t<uiIndex>%d</uiIndex>\r\n", cnt );
FilePrintf(hFile,"\t\t<ubChoices>%d</ubChoices>\r\n", gArmyItemChoices[cnt].ubChoices );
for (int i=0;i<50;i++)
FilePrintf(hFile,"\t\t<bItemNo%d>%d</bItemNo%d>\r\n",i+1,gArmyItemChoices[cnt].bItemNo[i],i+1 );
FilePrintf(hFile,"\t</ENEMYITEMCHOICES>\r\n");
}
FilePrintf(hFile,"</ENEMYITEMCHOICESLIST>\r\n");
}
FileClose( hFile );
return( TRUE );
}
| [
"jazz_ja@b41f55df-6250-4c49-8e33-4aa727ad62a1"
] | [
[
[
1,
514
]
]
] |
c720aac13d9977afcd42b98c62af3e23a7cf99f8 | 39f9ae6bdbda7f3b42cf4a006fb2a469fb44e4cf | /Farol/AssemblyInfo.cpp | 4b46aa567e0d2ef8993d1f2dc527747d40b59ecd | [] | no_license | maochy/farol | 30b2af11cf951d128797ec79c0d419883b7bbc11 | 486928695c3658e7646606d14c3bf6b8bc9d8933 | refs/heads/master | 2021-01-10 01:17:40 | 2010-03-12 04:10:39 | 2010-03-12 04:10:39 | 38,855,832 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,326 | cpp | #include "stdafx.h"
using namespace System;
using namespace System::Reflection;
using namespace System::Runtime::CompilerServices;
using namespace System::Runtime::InteropServices;
using namespace System::Security::Permissions;
//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly:AssemblyTitleAttribute("Farol")];
[assembly:AssemblyDescriptionAttribute("")];
[assembly:AssemblyConfigurationAttribute("")];
[assembly:AssemblyCompanyAttribute("")];
[assembly:AssemblyProductAttribute("Farol")];
[assembly:AssemblyCopyrightAttribute("Copyright (c) 2009")];
[assembly:AssemblyTrademarkAttribute("")];
[assembly:AssemblyCultureAttribute("")];
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the value or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly:AssemblyVersionAttribute("1.0.*")];
[assembly:ComVisible(false)];
[assembly:CLSCompliantAttribute(true)];
[assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)];
| [
"renanrv@5a151274-b240-11de-8e13-c326f17d7b4c"
] | [
[
[
1,
40
]
]
] |
fcf5c0a3f82b704b3266ded483a7d5d8eae8d7cd | 74e7667ad65cbdaa869c6e384fdd8dc7e94aca34 | /MicroFrameworkPK_v4_1/BuildOutput/public/debug/Client/stubs/spot_net_security_native_Microsoft_SPOT_Net_Security_SslNative.h | 0767fe1527105eabf5fcfb4f2a0f65bd3dcbed2c | [
"BSD-3-Clause",
"OpenSSL",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | gezidan/NETMF-LPC | 5093ab223eb9d7f42396344ea316cbe50a2f784b | db1880a03108db6c7f611e6de6dbc45ce9b9adce | refs/heads/master | 2021-01-18 10:59:42 | 2011-06-28 08:11:24 | 2011-06-28 08:11:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,534 | h | //-----------------------------------------------------------------------------
//
// ** WARNING! **
// This file was generated automatically by a tool.
// Re-running the tool will overwrite this file.
// You should copy this file to a custom location
// before adding any customization in the copy to
// prevent loss of your changes when the tool is
// re-run.
//
//-----------------------------------------------------------------------------
#ifndef _SPOT_NET_SECURITY_NATIVE_MICROSOFT_SPOT_NET_SECURITY_SSLNATIVE_H_
#define _SPOT_NET_SECURITY_NATIVE_MICROSOFT_SPOT_NET_SECURITY_SSLNATIVE_H_
namespace Microsoft
{
namespace SPOT
{
namespace Net
{
namespace Security
{
struct SslNative
{
// Helper Functions to access fields of managed object
// Declaration of stubs. These functions are implemented by Interop code developers
static INT32 SecureServerInit( INT32 param0, INT32 param1, UNSUPPORTED_TYPE param2, double param3, HRESULT &hr );
static INT32 SecureClientInit( INT32 param0, INT32 param1, UNSUPPORTED_TYPE param2, double param3, HRESULT &hr );
static void UpdateCertificates( INT32 param0, UNSUPPORTED_TYPE param1, double param2, HRESULT &hr );
static void SecureAccept( INT32 param0, UNSUPPORTED_TYPE param1, HRESULT &hr );
static void SecureConnect( INT32 param0, LPCSTR param1, UNSUPPORTED_TYPE param2, HRESULT &hr );
static INT32 SecureRead( UNSUPPORTED_TYPE param0, CLR_RT_TypedArray_UINT8 param1, INT32 param2, INT32 param3, INT32 param4, HRESULT &hr );
static INT32 SecureWrite( UNSUPPORTED_TYPE param0, CLR_RT_TypedArray_UINT8 param1, INT32 param2, INT32 param3, INT32 param4, HRESULT &hr );
static INT32 SecureCloseSocket( UNSUPPORTED_TYPE param0, HRESULT &hr );
static INT32 ExitSecureContext( INT32 param0, HRESULT &hr );
static void ParseCertificate( CLR_RT_TypedArray_UINT8 param0, LPCSTR param1, LPCSTR * param2, LPCSTR * param3, UNSUPPORTED_TYPE * param4, float param5, HRESULT &hr );
static INT32 DataAvailable( UNSUPPORTED_TYPE param0, HRESULT &hr );
};
}
}
}
}
#endif //_SPOT_NET_SECURITY_NATIVE_MICROSOFT_SPOT_NET_SECURITY_SSLNATIVE_H_
| [
"psampaio.isel@gmail.com"
] | [
[
[
1,
45
]
]
] |
c1cf7984f64e984f30cb9feda9b202a2765f95e2 | 9a48be80edc7692df4918c0222a1640545384dbb | /Libraries/Boost1.40/tools/inspect/unnamed_namespace_check.cpp | 149bb0c654b05c768fd33b3e3508a2886fd7780b | [
"BSL-1.0"
] | permissive | fcrick/RepSnapper | 05e4fb1157f634acad575fffa2029f7f655b7940 | a5809843f37b7162f19765e852b968648b33b694 | refs/heads/master | 2021-01-17 21:42:29 | 2010-06-07 05:38:05 | 2010-06-07 05:38:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,751 | cpp | // unnamed_namespace_check -----------------------------------------//
// Copyright Gennaro Prota 2006.
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include "boost/regex.hpp"
#include "boost/lexical_cast.hpp"
#include "unnamed_namespace_check.hpp"
namespace
{
boost::regex unnamed_namespace_regex(
"\\<namespace\\s(\\?\\?<|\\{)" // trigraph ??< or {
);
} // unnamed namespace (ironical? :-)
namespace boost
{
namespace inspect
{
unnamed_namespace_check::unnamed_namespace_check() : m_errors(0)
{
register_signature( ".h" );
register_signature( ".hh" ); // just in case
register_signature( ".hpp" );
register_signature( ".hxx" ); // just in case
register_signature( ".inc" );
register_signature( ".ipp" );
register_signature( ".inl" );
}
void unnamed_namespace_check::inspect(
const string & library_name,
const path & full_path, // example: c:/foo/boost/filesystem/path.hpp
const string & contents ) // contents of file to be inspected
{
if (contents.find( "boostinspect:" "nounnamed" ) != string::npos) return;
boost::sregex_iterator cur(contents.begin(), contents.end(), unnamed_namespace_regex), end;
for( ; cur != end; ++cur, ++m_errors )
{
const string::size_type
ln = std::count( contents.begin(), (*cur)[0].first, '\n' ) + 1;
error( library_name, full_path, string(name()) + " unnamed namespace at line "
+ lexical_cast<string>(ln) );
}
}
} // namespace inspect
} // namespace boost
| [
"metrix@Blended.(none)"
] | [
[
[
1,
63
]
]
] |
1d85ff6b8381657612e73a532d2c8f91e8382c63 | 331e63f76403f347bf45d52b2b72e999a15d26a7 | /SIN/SIN_CORE/SINCommon/Src/SINNamer.cpp | 89e9c945833e317b197f5151430ba5f13581eb82 | [] | no_license | koutsop/sinmetalanguage | 64c9dd10d65c89b169aa0d1dec3bd14cf14165f6 | 7ef17948ae3a6fd4c3589429e9862d1cbfbec80c | refs/heads/master | 2021-01-10 20:08:40 | 2010-05-23 17:42:04 | 2010-05-23 17:42:04 | 33,115,739 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,322 | cpp | #include "SINNamer.h"
#include <cstdio>
#include <cstring>
namespace SIN {
//----------------------------------------------------------------
Namer::Namer(char const _base[SINNAMER_BASELEN]):
counter(0x00ul),
base_offset(min<size_t>(strlen(_base), SINNAMER_BASELEN)),
number_maximun_length(ULONG_MAX_STR_LEN)
{
strncpy(base, _base, SINNAMER_BASELEN);
}
//----------------------------------------------------------------
Namer::Namer(Namer const &_other):
counter(_other.counter),
base_offset(_other.base_offset),
number_maximun_length(_other.number_maximun_length)
{
strncpy(base, _other.base, SINNAMER_BASELEN);
}
//----------------------------------------------------------------
Namer::~Namer(void) {}
//----------------------------------------------------------------
char const *Namer::operator ++(void) {
sprintf(base + base_offset, "%0*lu", number_maximun_length, ++counter);
return base;
}
//----------------------------------------------------------------
char const *Namer::operator ++(int) {
sprintf(base + base_offset, "%0*lu", number_maximun_length, counter++);
return base;
}
} // namespace SIN
| [
"koutsop@6a7033b6-9ebc-11de-a8ff-c955b97a4a10"
] | [
[
[
1,
47
]
]
] |
f1d55defd6b2afd7ac4fafaf7985dd34be2f1b5a | 0b66a94448cb545504692eafa3a32f435cdf92fa | /tags/0.8/cbear.berlios.de/windows/int_ptr.hpp | 99b3b1f1769f9193b4ef825c7c4951f66e9407bd | [
"MIT"
] | permissive | BackupTheBerlios/cbear-svn | e6629dfa5175776fbc41510e2f46ff4ff4280f08 | 0109296039b505d71dc215a0b256f73b1a60b3af | refs/heads/master | 2021-03-12 22:51:43 | 2007-09-28 01:13:48 | 2007-09-28 01:13:48 | 40,608,034 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 386 | hpp | #ifndef CBEAR_BERLIOS_DE_WINDOWS_INT_PTR_HPP_INCLUDED
#define CBEAR_BERLIOS_DE_WINDOWS_INT_PTR_HPP_INCLUDED
#include <cbear.berlios.de/windows/basetsd.h>
namespace cbear_berlios_de
{
namespace windows
{
// Signed integral type for pointer precision. Use when casting a pointer to an
// integer to perform pointer arithmetic.
typedef INT_PTR int_ptr_t;
}
}
#endif
| [
"sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838"
] | [
[
[
1,
18
]
]
] |
d2af5dd5cc4a3cc9c26152b5e879de0ba86e106e | 8f1601062c4a5452f2bdd0f75f3d12a79b98ba62 | /examples/tankwars/Terrain.cpp | 15ae0280d1a8d6ef494aa43ef8bcb26bb69a81c9 | [] | no_license | chadaustin/isugamedev | 200a54f55a2581cd2c62c94eb96b9e238abcf3dd | d3008ada042d2dd98c6e05711773badf6f1fd85c | refs/heads/master | 2016-08-11 17:59:38 | 2005-01-25 23:17:11 | 2005-01-25 23:17:11 | 36,483,500 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,262 | cpp | // Terrain.cpp: implementation of the Terrain class.
//
//////////////////////////////////////////////////////////////////////
#include "Terrain.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
Terrain::Terrain()
{
xsize = 5.0f;
zsize = 5.0f;
xPos = 0.0;
zPos = 0.0;
extents = 28.0;
}
Terrain::~Terrain()
{
}
void Terrain::draw()
{
glTranslatef(-3.0f, 0.0f, -11.0f*zsize);
glRotatef(-45.0f, 0.0f, 1.0f, 0.0f);
glBindTexture(GL_TEXTURE_2D, terrainTex[0]);
for (int x = 0; x<13; x++)
{
glTranslatef(xsize, 0.0f, 0.0f);
for (int z = 0; z<13; z++)
{
glTranslatef(0.0f, 0.0f, zsize);
glBegin(GL_QUADS); // coordinates for the square
//glNormal3f(0.0f, 1.0f, 0.0f);
glTexCoord2f(0.02f, 0.02f); glVertex3f(0.0f, 0.0f, 0.0f);
glTexCoord2f(.98f, 0.02f); glVertex3f(xsize, 0.0f, 0.0f);
glTexCoord2f(0.98f, 0.98f); glVertex3f(xsize, 0.0f, zsize);
glTexCoord2f(0.02f, 0.98f); glVertex3f(0.0f, 0.0f, zsize);
glEnd();
}
glTranslatef(0.0f, 0.0f, -13*zsize);
}
return;
}
void Terrain::setx(GLfloat x)
{
xsize = x;
return;
}
void Terrain::setz(GLfloat z)
{
zsize = z;
return;
} | [
"viperscum@84b32ba4-53c3-423c-be69-77cca6335494"
] | [
[
[
1,
65
]
]
] |
5cb5c6cb2115921762d45783fe442358086be288 | b22c254d7670522ec2caa61c998f8741b1da9388 | /dependencies/OpenSceneGraph/include/osgUtil/LineSegmentIntersector | e43e4ed86ebe181f7d5562de1bc68aeaff18dd0e | [] | no_license | ldaehler/lbanet | 341ddc4b62ef2df0a167caff46c2075fdfc85f5c | ecb54fc6fd691f1be3bae03681e355a225f92418 | refs/heads/master | 2021-01-23 13:17:19 | 2011-03-22 21:49:52 | 2011-03-22 21:49:52 | 39,529,945 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,993 | /* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
#ifndef OSGUTIL_LINESEGMENTINTERSECTOR
#define OSGUTIL_LINESEGMENTINTERSECTOR 1
#include <osgUtil/IntersectionVisitor>
namespace osgUtil
{
/** Concrete class for implementing line intersections with the scene graph.
* To be used in conjunction with IntersectionVisitor. */
class OSGUTIL_EXPORT LineSegmentIntersector : public Intersector
{
public:
/** Construct a LineSegmentIntersector the runs between the specified start and end points in MODEL coordinates. */
LineSegmentIntersector(const osg::Vec3d& start, const osg::Vec3d& end);
/** Construct a LineSegmentIntersector the runs between the specified start and end points in the specified coordinate frame. */
LineSegmentIntersector(CoordinateFrame cf, const osg::Vec3d& start, const osg::Vec3d& end);
/** Convenience constructor for supporting picking in WINDOW, or PROJECTION coordinates
* In WINDOW coordinates creates a start value of (x,y,0) and end value of (x,y,1).
* In PROJECTION coordinates (clip space cube) creates a start value of (x,y,-1) and end value of (x,y,1).
* In VIEW and MODEL coordinates creates a start value of (x,y,0) and end value of (x,y,1).*/
LineSegmentIntersector(CoordinateFrame cf, double x, double y);
struct Intersection
{
Intersection():
ratio(-1.0),
primitiveIndex(0) {}
bool operator < (const Intersection& rhs) const { return ratio < rhs.ratio; }
typedef std::vector<unsigned int> IndexList;
typedef std::vector<double> RatioList;
double ratio;
osg::NodePath nodePath;
osg::ref_ptr<osg::Drawable> drawable;
osg::ref_ptr<osg::RefMatrix> matrix;
osg::Vec3d localIntersectionPoint;
osg::Vec3 localIntersectionNormal;
IndexList indexList;
RatioList ratioList;
unsigned int primitiveIndex;
const osg::Vec3d& getLocalIntersectPoint() const { return localIntersectionPoint; }
osg::Vec3d getWorldIntersectPoint() const { return matrix.valid() ? localIntersectionPoint * (*matrix) : localIntersectionPoint; }
const osg::Vec3& getLocalIntersectNormal() const { return localIntersectionNormal; }
osg::Vec3 getWorldIntersectNormal() const { return matrix.valid() ? osg::Matrix::transform3x3(osg::Matrix::inverse(*matrix),localIntersectionNormal) : localIntersectionNormal; }
};
typedef std::multiset<Intersection> Intersections;
inline void insertIntersection(const Intersection& intersection) { getIntersections().insert(intersection); }
inline Intersections& getIntersections() { return _parent ? _parent->_intersections : _intersections; }
inline Intersection getFirstIntersection() { Intersections& intersections = getIntersections(); return intersections.empty() ? Intersection() : *(intersections.begin()); }
inline void setStart(const osg::Vec3d& start) { _start = start; }
inline const osg::Vec3d& getStart() const { return _start; }
inline void setEnd(const osg::Vec3d& end) { _end = end; }
inline const osg::Vec3d& getEnd() const { return _end; }
public:
virtual Intersector* clone(osgUtil::IntersectionVisitor& iv);
virtual bool enter(const osg::Node& node);
virtual void leave();
virtual void intersect(osgUtil::IntersectionVisitor& iv, osg::Drawable* drawable);
virtual void reset();
virtual bool containsIntersections() { return !_intersections.empty(); }
protected:
bool intersects(const osg::BoundingSphere& bs);
bool intersectAndClip(osg::Vec3d& s, osg::Vec3d& e,const osg::BoundingBox& bb);
LineSegmentIntersector* _parent;
osg::Vec3d _start;
osg::Vec3d _end;
Intersections _intersections;
};
}
#endif
| [
"vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13"
] | [
[
[
1,
113
]
]
] |
|
d97aa36e36fb812d4f7e70d1d6e32c9d5b85a952 | 3d0021b222ddd65b36e61207a8382e841d13e3df | /adpcm.cpp | d6f3f0672247e4dfbbfcf3a6b9cefed8f550a0a5 | [] | no_license | default0/zeldablackmagic | 1273f5793c4d5bbb594b6da07cf70b52de499392 | f12078b4c3b22d80077e485657538398e8db3b0f | refs/heads/master | 2021-01-10 11:54:31 | 2010-02-10 19:23:04 | 2010-02-10 19:23:04 | 51,330,005 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,127 | cpp |
/*
#include "common.h"
#include "adpcm.h"
// <pSXAuthor> you use the decoder class like:
// <pSXAuthor> adpcm::decoder d;
// <pSXAuthor> signed short buffer[...number of pcm bytes....];
// <pSXAuthor> packet *p=... pointer to start of adpcm data ...;
// <pSXAuthor> signed short *ptr=buffer; while ((p->flags&flag_end)==0) ptr=d.decode_packet(p++,ptr);
//
//
//
const int adpcm::filter_coef[5][2]=
{
{ 0,0 },
{ 60,0 },
{ 115,-52 },
{ 98,-55 },
{ 122,-60 },
};
//
//
//
signed short *adpcm::decoder::decode_packet(adpcm::packet *ap, signed short *dp)
{
int shift=ap->info&0xf,
filter=ap->info>>4,
f0=filter_coef[filter][0],
f1=filter_coef[filter][1];
for (int i=0; i<14; i++)
{
unsigned char b=ap->data[i];
short bl=(b&0xf)<<12,
bh=(b>>4)<<12;
bl=(bl>>shift)+(((l0*f0)+(l1*f1)+32)>>6);
if (bl<-32768) bl=-32768; else if (bl>32767) bl=32767;
*dp++=bl;
l1=l0;
l0=bl;
bh=(bh>>shift)+(((l0*f0)+(l1*f1)+32)>>6);
if (bh<-32768) bh=-32768; else if (bh>32767) bh=32767;
*dp++=bh;
l1=l0;
l0=bh;
}
return dp;
} */ | [
"MathOnNapkins@99ff0a3e-ee68-11de-8de6-035db03795fd"
] | [
[
[
1,
57
]
]
] |
d2cfa947fd9fed9c7fdc3dba2846f80e32fcce1d | a37df219b4a30e684db85b00dd76d4c36140f3c2 | /1.7.1/rox/rox.cpp | 40febebd3045eee129d7f5b4e54ef23d056bd8f8 | [] | no_license | BlackMoon/bm-net | 0f79278f8709cd5d0738a6c3a27369726b0bb793 | eb6414bc412a8cfc5c24622977e7fa7203618269 | refs/heads/master | 2020-12-25 20:20:44 | 2011-11-29 10:33:17 | 2011-11-29 10:33:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 44,009 | cpp | // rox.cpp
#pragma comment(lib, "../ext/release/ext")
#include "../dx/obj.h"
#include "../ext/ext.h"
#define WIN32_LEAN_AND_MEAN
#define STOCK_CONST 4
struct mperiod
{
char mon[4];
float pmin, pmax, smin, smax;
ULONG destp, dests;
USHORT date, month, year;
inline void fillDate()
{
if (strcmp(mon, "Jan") == 0) month = 1;
else if (strcmp(mon, "Feb") == 0) month = 2;
else if (strcmp(mon, "Mar") == 0) month = 3;
else if (strcmp(mon, "Apr") == 0) month = 4;
else if (strcmp(mon, "May") == 0) month = 5;
else if (strcmp(mon, "Jun") == 0) month = 6;
else if (strcmp(mon, "Jul") == 0) month = 7;
else if (strcmp(mon, "Aug") == 0) month = 8;
else if (strcmp(mon, "Sep") == 0) month = 9;
else if (strcmp(mon, "Oct") == 0) month = 10;
else if (strcmp(mon, "Nov") == 0) month = 11;
else if (strcmp(mon, "Dec") == 0) month = 12;
}
};
struct param
{
char filename[MAX_PATH], shortname[16];
float min, max;
inline param()
{
min = 0.0f;
max = 1.0f;
}
inline void makeShort()
{
memset(shortname, 0, 16);
getName(shortname, filename);
}
};
struct wline
{
UINT x, y;
float z0, z1;
};
struct dens
{
float oil, watr, gas, kper;
};
typedef vector<float> floatvector;
typedef vector<floatvector> floatmatrix;
bool dporo = 0;
char din[MAX_PATH], dout[MAX_PATH], symb;
float zmin, zmax;
SPACE space;
bool paramConvert(param* ppm)
{
printf("[%s]\n", ppm->shortname);
char header[16],
file[MAX_PATH];
memset(file, 0, MAX_PATH);
strcpy(file, din);
strcat(file, ppm->shortname);
FILE *istream = fopen(file, "r"),
*ostream;
if (!istream) return 0;
float fvalue0;
floatvector fvector;
floatmatrix fmatrix;
int i, j, k;
fscanf(istream, "%s\n", header);
if (strcmp(header, "COOR") == 0)
{
// read xmin
UINT x, y;
// first line
fscanf(istream, "%u %u %f", &space.xMin, &space.yMax, &fvalue0);
zmin = zmax = -fvalue0;
fscanf(istream, "%u %u %f", &x, &y, &fvalue0);
if (-fvalue0 < zmin) zmin = -fvalue0;
if (-fvalue0 > zmax) zmax = -fvalue0;
for (i = 1; i < space.square() - 1; i++)
{
fscanf(istream, "%u %u %f", &x, &y, &fvalue0);
if (-fvalue0 < zmin) zmin = -fvalue0;
if (-fvalue0 > zmax) zmax = -fvalue0;
fscanf(istream, "%u %u %f", &x, &y, &fvalue0);
if (-fvalue0 < zmin) zmin = -fvalue0;
if (-fvalue0 > zmax) zmax = -fvalue0;
}
// last line
fscanf(istream, "%u %u %f", &space.xMax, &space.yMin, &fvalue0);
space.xStep = space.xLen() / space.nX + 1;
space.yStep = space.yLen() / space.nY + 1;
if (-fvalue0 < zmin) zmin = -fvalue0;
if (-fvalue0 > zmax) zmax = -fvalue0;
fscanf(istream, "%u %u %f", &x, &y, &fvalue0);
if (-fvalue0 < zmin) zmin = -fvalue0;
if (-fvalue0 > zmax) zmax = -fvalue0;
printf("\tSTEP %u %u\n", space.xStep, space.yStep);
printf("\tX %u %u\n", space.xMin, space.xMax);
printf("\tY %u %u\n", space.yMin, space.yMax);
printf("\tZ %.2f %.2f\n", zmin, zmax);
strcpy(file, dout);
strcat(file, "grid.txt");
ostream = fopen(file, "w");
if (!ostream) return 0;
fprintf(ostream, "SIZE %u %u %u\n", space.nX, space.nY, space.nZ);
fprintf(ostream, "STEP %u %u\n", space.xStep, space.yStep);
fprintf(ostream, "X %u %u\n", space.xMin, space.xMax);
fprintf(ostream, "Y %u %u\n", space.yMin, space.yMax);
fprintf(ostream, "Z %.2f %.2f\n", zmin, zmax);
fclose(ostream);
}
else if (strcmp(header, "ZCORN") == 0)
{
strcpy(file, dout);
strcat(file, ppm->shortname);
ostream = fopen(file, "w");
if (!ostream) return 0;
fprintf(ostream, "%.3f %.3f\n", zmin, zmax);
float fvalue1;
for (i = 0; i < space.nZ; i++)
{
printf("\tlayer%u", i + 1);
// roof
for (j = 0; j < ((space.nY - 1) << 1); j++)
{
for (k = 0; k < space.nX - 1; k++)
{
fscanf(istream, "%f %f", &fvalue0, &fvalue1);
fvector.push_back(-fvalue0);
}
fvector.push_back(-fvalue1); // last value
fmatrix.push_back(fvector);
fvector.clear();
}
for (--j; j > 0; j -= 2)
{
fvector = fmatrix[j];
for (k = 0; k < space.nX; k++)
{
fvalue0 = fvector[k];
fprintf(ostream, "%.3f ", fvalue0);
}
fprintf(ostream, "\n");
}
// last row
fvector = fmatrix[0];
for (k = 0; k < space.nX; k++)
{
fvalue0 = fvector[k];
fprintf(ostream, "%.3f ", fvalue0);
}
fprintf(ostream, "\n");
fmatrix.clear();
fvector.clear();
// sole
for (j = 0; j < ((space.nY - 1) << 1); j++)
{
for (k = 0; k < space.nX - 1; k++)
{
fscanf(istream, "%f %f", &fvalue0, &fvalue1);
fvector.push_back(-fvalue0);
}
fvector.push_back(-fvalue1); // last value
fmatrix.push_back(fvector);
fvector.clear();
}
for (--j; j > 0; j -= 2)
{
fvector = fmatrix[j];
for (k = 0; k < space.nX; k++)
{
fvalue0 = fvector[k];
fprintf(ostream, "%.3f ", fvalue0);
}
fprintf(ostream, "\n");
}
// last row
fvector = fmatrix[0];
for (k = 0; k < space.nX; k++)
{
fvalue0 = fvector[k];
fprintf(ostream, "%.3f ", fvalue0);
}
fprintf(ostream, "\n");
fmatrix.clear();
fvector.clear();
printf("\t\tok\n");
}
fclose(ostream);
}
else if (strcmp(header, "K_X") == 0)
{
if (symb != 'a')
{
printf("convert X_Permeability (y/n/a)?");
cin >> symb;
}
if ((symb == 0x61) || (symb == 0x79))
{
strcpy(file, dout);
strcat(file, ppm->shortname);
ostream = fopen(file, "w");
if (!ostream) return 0;
fprintf(ostream, "%.3f %.3f\n", ppm->min, ppm->max);
fscanf(istream, "VARI\n");
for (i = 0; i < space.nZ; i++)
{
printf("\tlayer%u", i + 1);
for (j = 0; j < space.nY - 1; j++)
{
for (k = 0; k < space.nX - 1; k++)
{
fscanf(istream, "%f", &fvalue0);
fvector.push_back(fvalue0);
}
fvector.push_back(fvalue0); // last value
fmatrix.push_back(fvector);
fvector.clear();
}
for (--j; j >= 0; j--)
{
fvector = fmatrix[j];
for (k = 0; k < space.nX; k++)
{
fvalue0 = fvector[k];
if (fvalue0 < ppm->min) fvalue0 = ppm->min;
if (fvalue0 > ppm->max) fvalue0 = ppm->max;
fprintf(ostream, "%.3f ", fvalue0);
}
fprintf(ostream, "\n");
}
// last row
fvector = fmatrix[0];
for (k = 0; k < space.nX; k++)
{
fvalue0 = fvector[k];
if (fvalue0 < ppm->min) fvalue0 = ppm->min;
if (fvalue0 > ppm->max) fvalue0 = ppm->max;
fprintf(ostream, "%.3f ", fvalue0);
}
fprintf(ostream, "\n");
fmatrix.clear();
fvector.clear();
printf("\t\tok\n");
}
fclose(ostream);
}
}
else if (strcmp(header, "K_Z") == 0)
{
if (symb != 'a')
{
printf("convert Z_Permeability (y/n/a)?");
cin >> symb;
}
if ((symb == 0x61) || (symb == 0x79))
{
strcpy(file, dout);
strcat(file, ppm->shortname);
ostream = fopen(file, "w");
if (!ostream) return 0;
fprintf(ostream, "%.3f %.3f\n", ppm->min, ppm->max);
fscanf(istream, "VARI\n");
for (i = 0; i < space.nZ; i++)
{
printf("\tlayer%u", i + 1);
for (j = 0; j < space.nY - 1; j++)
{
for (k = 0; k < space.nX - 1; k++)
{
fscanf(istream, "%f", &fvalue0);
fvector.push_back(fvalue0);
}
fvector.push_back(fvalue0); // last value
fmatrix.push_back(fvector);
fvector.clear();
}
for (--j; j >= 0; j--)
{
fvector = fmatrix[j];
for (k = 0; k < space.nX; k++)
{
fvalue0 = fvector[k];
if (fvalue0 < ppm->min) fvalue0 = ppm->min;
if (fvalue0 > ppm->max) fvalue0 = ppm->max;
fprintf(ostream, "%.3f ", fvalue0);
}
fprintf(ostream, "\n");
}
// last row
fvector = fmatrix[0];
for (k = 0; k < space.nX; k++)
{
fvalue0 = fvector[k];
if (fvalue0 < ppm->min) fvalue0 = ppm->min;
if (fvalue0 > ppm->max) fvalue0 = ppm->max;
fprintf(ostream, "%.3f ", fvalue0);
}
fprintf(ostream, "\n");
fmatrix.clear();
fvector.clear();
printf("\t\tok\n");
}
fclose(ostream);
}
}
else if (strcmp(header, "PORO") == 0)
{
if (symb != 'a')
{
printf("convert Porosity (y/n/a)?");
cin >> symb;
}
if ((symb == 0x61) || (symb == 0x79))
{
strcpy(file, dout);
strcat(file, ppm->shortname);
ostream = fopen(file, "w");
if (!ostream) return 0;
fprintf(ostream, "%.3f %.3f\n", ppm->min, ppm->max);
fscanf(istream,"VARI\n");
for (i = 0; i < space.nZ; i++)
{
printf("\tlayer%u", i + 1);
for (j = 0; j < space.nY - 1; j++)
{
for (k = 0; k < space.nX - 1; k++)
{
fscanf(istream, "%f", &fvalue0);
fvector.push_back(fvalue0);
}
fvector.push_back(fvalue0); // last value
fmatrix.push_back(fvector);
fvector.clear();
}
for (--j; j >= 0; j--)
{
fvector = fmatrix[j];
for (k = 0; k < space.nX; k++)
{
fvalue0 = fvector[k];
if (fvalue0 < ppm->min) fvalue0 = ppm->min;
if (fvalue0 > ppm->max) fvalue0 = ppm->max;
fprintf(ostream, "%.3f ", fvalue0);
}
fprintf(ostream, "\n");
}
// last row
fvector = fmatrix[0];
for (k = 0; k < space.nX; k++)
{
fvalue0 = fvector[k];
if (fvalue0 < ppm->min) fvalue0 = ppm->min;
if (fvalue0 > ppm->max) fvalue0 = ppm->max;
fprintf(ostream, "%.3f ", fvalue0);
}
fprintf(ostream, "\n");
fmatrix.clear();
fvector.clear();
printf("\t\tok\n");
}
fclose(ostream);
}
}
else if (strcmp(header, "NTOG") == 0)
{
if (symb != 'a')
{
printf("convert NTG (y/n/a)?");
cin >> symb;
}
if ((symb == 0x61) || (symb == 0x79))
{
strcpy(file, dout);
strcat(file, ppm->shortname);
ostream = fopen(file, "w");
if (!ostream) return 0;
fprintf(ostream, "%.3f %.3f\n", ppm->min, ppm->max);
fscanf(istream, "VARI\n");
for (i = 0; i < space.nZ; i++)
{
printf("\tlayer%u", i + 1);
for (j = 0; j < space.nY - 1; j++)
{
for (k = 0; k < space.nX - 1; k++)
{
fscanf(istream, "%f", &fvalue0);
fvector.push_back(fvalue0);
}
fvector.push_back(fvalue0); // last value
fmatrix.push_back(fvector);
fvector.clear();
}
for (--j; j >= 0; j--)
{
fvector = fmatrix[j];
for (k = 0; k < space.nX; k++)
{
fvalue0 = fvector[k];
if (fvalue0 < ppm->min) fvalue0 = ppm->min;
if (fvalue0 > ppm->max) fvalue0 = ppm->max;
fprintf(ostream, "%.3f ", fvalue0);
}
fprintf(ostream, "\n");
}
// last row
fvector = fmatrix[0];
for (k = 0; k < space.nX; k++)
{
fvalue0 = fvector[k];
if (fvalue0 < ppm->min) fvalue0 = ppm->min;
if (fvalue0 > ppm->max) fvalue0 = ppm->max;
fprintf(ostream, "%.3f ", fvalue0);
}
fprintf(ostream, "\n");
fmatrix.clear();
fvector.clear();
printf("\t\tok\n");
}
fclose(ostream);
}
}
else if (strcmp(header, "SWAT") == 0)
{
if (symb != 'a')
{
printf("convert SWAT (y/n/a)?");
cin >> symb;
}
if ((symb == 0x61) || (symb == 0x79))
{
strcpy(file, dout);
strcat(file, ppm->shortname);
ostream = fopen(file, "w");
if (!ostream) return 0;
fprintf(ostream, " \n"); // place for min & max
fscanf(istream, "VARI\n");
for (i = 0; i < space.nZ; i++)
{
printf("\tlayer%u", i + 1);
for (j = 0; j < space.nY - 1; j++)
{
for (k = 0; k < space.nX - 1; k++)
{
fscanf(istream, "%f", &fvalue0);
fvector.push_back(1 - fvalue0);
}
fvector.push_back(1 - fvalue0); // last value
fmatrix.push_back(fvector);
fvector.clear();
}
for (--j; j >= 0; j--)
{
fvector = fmatrix[j];
for (k = 0; k < space.nX; k++)
{
fvalue0 = fvector[k];
if (fvalue0 < ppm->min) ppm->min = fvalue0;
if (fvalue0 > ppm->max) ppm->max = fvalue0;
fprintf(ostream, "%.3f ", fvalue0);
}
fprintf(ostream, "\n");
}
// last row
fvector = fmatrix[0];
for (k = 0; k < space.nX; k++)
{
fvalue0 = fvector[k];
if (fvalue0 < ppm->min) ppm->min = fvalue0;
if (fvalue0 > ppm->max) ppm->max = fvalue0;
fprintf(ostream, "%.3f ", fvalue0);
}
fprintf(ostream, "\n");
fmatrix.clear();
fvector.clear();
printf("\t\tok\n");
}
fseek(ostream, 0, SEEK_SET);
fprintf(ostream, "%.3f %.3f", ppm->min, ppm->max);
fclose(ostream);
}
}
fclose(istream);
printf("\n");
return 1;
}
bool outConvert(const char* filename, const HANDLE hfile)
{
bool bres = 1;
HANDLE hmap = CreateFileMapping(hfile, 0, PAGE_READONLY, 0, 0, "fileMapping");
LONG rest, size = GetFileSize(hfile, 0);
void* pbase = MapViewOfFile(hmap, FILE_MAP_READ, 0, 0, 0);
char buf[USHRT_MAX];
char* pdest;
float fvalue, pmin, pmax, smin, smax;
mperiod mp;
vector<mperiod> mperiods0;
int i = 0;
for (i; i < size / USHRT_MAX; i++)
{
memset(buf, 0, USHRT_MAX);
memcpy(buf, (LPTSTR)pbase + i * USHRT_MAX, USHRT_MAX);
if (pdest = strstr(buf, "Map of PRES"))
{
memset(&mp, 0, 36);
mp.destp = (long)(pdest - buf) + i * USHRT_MAX;
if (sscanf(pdest, "Map of PRES at %u %s %u\n", &mp.date, mp.mon, &mp.year) == 0)
sscanf(pdest, "Map of PRESSURE at %u %s %u\n", &mp.date, mp.mon, &mp.year);
mp.fillDate();
pdest -= 375;
sscanf(pdest, "Pressure %f %f %f barsa\n", &mp.pmin, &mp.pmax, &fvalue);
pdest += 51;
sscanf(pdest, "Soil %f %f %f frac\n", &mp.smin, &mp.smax, &fvalue);
}
if (pdest = strstr(buf, "Map of soil"))
{
mp.dests = (long)(pdest - buf) + i * USHRT_MAX;
mperiods0.push_back(mp);
}
}
rest = size - i * USHRT_MAX;
memset(buf, 0, USHRT_MAX);
memcpy(buf, (LPTSTR)pbase + i * USHRT_MAX, rest);
if (!(pdest = strstr(buf, "Run finished successfully")))
mperiods0.erase(&mperiods0.back());
UnmapViewOfFile(pbase);
CloseHandle(hmap);
CloseHandle(hfile);
size = (long)mperiods0.size();
if (size != 0)
{
mp = mperiods0[0];
pmin = mp.pmin;
pmax = mp.pmax;
smin = mp.smin;
smax = mp.smax;
printf("\t[1]\t %u %s %u\n", mp.date, mp.mon, mp.year);
for (i = 1; i < size; i++)
{
mp = mperiods0[i];
if (pmin > mp.pmin) pmin = mp.pmin;
if (pmax < mp.pmax) pmax = mp.pmax;
if (smin > mp.smin) smin = mp.smin;
if (smax < mp.smax) smax = mp.smax;
printf("\t[%u]\t %u %s %u\n", i + 1, mp.date, mp.mon, mp.year);
}
int index = 0;
vector<int> indices;
printf("\nchoose dates (0 - end):\n");
do
{
printf("\t");
scanf("%d", &index);
if ((index < 0) || (index > (int)mperiods0.size()))
{
printf("error\n");
continue;
}
indices.push_back(index);
}
while (index != 0);
indices.erase(&indices.back());
// sort
sort(indices.begin(), indices.end());
vector<mperiod> mperiods1;
if (indices.size() == 0) mperiods1.swap(mperiods0);
else
{
index = indices[0];
mp = mperiods0[--index];
mperiods1.push_back(mp);
pmin = mp.pmin;
pmax = mp.pmax;
smin = mp.smin;
smax = mp.smax;
for (i = 1; i < (int)indices.size(); i++)
{
index = indices[i];
mp = mperiods0[--index];
mperiods1.push_back(mp);
if (pmin > mp.pmin) pmin = mp.pmin;
if (pmax < mp.pmax) pmax = mp.pmax;
if (smin > mp.smin) smin = mp.smin;
if (smax < mp.smax) smax = mp.smax;
}
}
indices.clear();
mperiods0.clear();
char* pfile = new char[MAX_PATH];
FILE *istream = fopen(filename, "r"),
*pstream, *rstream, *sstream; // actn;
// input stream
if (!istream) return 0;
memset(pfile, 0, MAX_PATH);
strcpy(pfile, dout);
strcat(pfile, "p.txt");
// pres stream
pstream = fopen(pfile, "w");
if (!pstream) return 0;
fprintf(pstream, "%.3f %.3f\n", pmin, pmax);
memset(pfile, 0, MAX_PATH);
strcpy(pfile, dout);
strcat(pfile, "actn.bin");
// actn stream
size = (space.nX - 1) * (space.nY - 1) * space.nZ;
bool* pbarr = new bool[size]; // active cells
memset(pbarr, 0, size);
rstream = fopen(pfile, "wb");
if (!rstream) return 0;
memset(pfile, 0, MAX_PATH);
strcpy(pfile, dout);
strcat(pfile, "soil.txt");
// soil stream
sstream = fopen(pfile, "w");
if (!sstream) return 0;
fprintf(sstream, "%.3f %.3f\n", smin, smax);
floatvector fvector;
floatmatrix fmatrix;
int ix, jy, kz, n, mpsize, value;
mp = mperiods1[0]; // first reading inactive cells
i = n = 0;
mpsize = (int)mperiods1.size();
if (dporo) // double poro
{
FILE *sstreamD;
memset(pfile, 0, MAX_PATH);
strcpy(pfile, dout);
strcat(pfile, "soild.txt");
// dporo soil stream
sstreamD = fopen(pfile, "w");
delete pfile;
if (!sstreamD) return 0;
fprintf(sstreamD, "%.3f %.3f\n", smin, smax);
// Map of PRESSURE
printf("\nMap of PRESSURE at %u %s %u:\n", mp.date, mp.mon, mp.year);
fprintf(pstream, "%.3f %.3f\n", mp.pmin, mp.pmax);
fseek(istream, mp.destp + 138, SEEK_SET);
for (kz = 0; kz < space.nZ; kz++)
{
printf("\tlayer%u", kz + 1);
fscanf(istream, "\nLayer iz=%u\nix= :", &value);
// read data
if (fscanf(istream, "All values are %f", &fvalue) > 0)
{
for (jy = 0; jy < space.nY - 1; jy++)
{
for (ix = 0; ix < space.nX - 1; ix++)
{
fvector.push_back(fvalue);
}
fvector.push_back(fvalue);
fmatrix.push_back(fvector);
fvector.clear();
}
}
else
{
for (ix = 0; ix < space.nX - 1; ix++)
fscanf(istream, "%u", &value);
for (jy = 0; jy < space.nY - 1; jy++)
{
fscanf(istream, "\nRow iy=%u:", &value);
for (ix = 0; ix < space.nX - 1; ix++)
{
fscanf(istream, "%f", &fvalue);
fvector.push_back(fvalue);
}
// last value
fvector.push_back(fvalue);
fmatrix.push_back(fvector);
fvector.clear();
}
}
// save data
for (--jy; jy >= 0; jy--)
{
fvector = fmatrix[jy];
for (ix = 0; ix < space.nX - 1; ix++)
{
fvalue = fvector[ix];
// inactive cells
if (fvalue >= mp.pmin - 1e-2)
{
pbarr[i] = 1;
n++;
}
i++;
fprintf(pstream, "%.3f\t", fvalue);
}
fprintf(pstream, "%.3f\t", fvalue);
fprintf(pstream, "\n");
}
// last row
fvector = fmatrix[0];
for (ix = 0; ix < space.nX; ix++)
{
fvalue = fvector[ix];
fprintf(pstream, "%.3f\t", fvalue);
}
fprintf(pstream, "\n");
fmatrix.clear();
fvector.clear();
printf("\t\tok\n");
}
fwrite(pbarr, 1, size, rstream);
SAFE_DELETE_ARRAY(pbarr);
fclose(rstream);
// Map of soil
printf("\nMap of soil at %u %s %u:\n", mp.date, mp.mon, mp.year);
fprintf(sstream, "%.3f %.3f\n", mp.smin, mp.smax);
fseek(istream, mp.dests + 134, SEEK_SET);
for (kz = 0; kz < space.nZ; kz++)
{
fscanf(istream, "\nLayer iz=%u\nix= :", &value);
// read data
if (fscanf(istream, "All values are %f", &fvalue) > 0)
{
for (jy = 0; jy < space.nY - 1; jy++)
{
for (ix = 0; ix < space.nX - 1; ix++)
{
fvector.push_back(fvalue);
}
fvector.push_back(fvalue);
fmatrix.push_back(fvector);
fvector.clear();
}
}
else
{
for (ix = 0; ix < space.nX - 1; ix++)
fscanf(istream, "%u", &value);
for (jy = 0; jy < space.nY - 1; jy++)
{
fscanf(istream, "\nRow iy=%u:", &value);
for (ix = 0; ix < space.nX - 1; ix++)
{
fscanf(istream, "%f", &fvalue);
fvector.push_back(fvalue);
}
// last value
fvector.push_back(fvalue);
fmatrix.push_back(fvector);
fvector.clear();
}
}
// save data
for (--jy; jy >= 0; jy--)
{
fvector = fmatrix[jy];
for (ix = 0; ix < space.nX; ix++)
{
fvalue = fvector[ix];
fprintf(sstream, "%.3f\t", fvalue);
}
fprintf(sstream, "\n");
}
// last row
fvector = fmatrix[0];
for (ix = 0; ix < space.nX; ix++)
{
fvalue = fvector[ix];
fprintf(sstream, "%.3f\t", fvalue);
}
fprintf(sstream, "\n");
fmatrix.clear();
fvector.clear();
}
// dporo soil layers
fprintf(sstreamD, "%.3f %.3f\n", mp.smin, mp.smax);
for (kz = 0; kz < space.nZ; kz++)
{
printf("\tlayer%u", kz + 1);
fscanf(istream, "\nLayer iz=%u\nix= :", &value);
// read data
if (fscanf(istream, "All values are %f", &fvalue) > 0)
{
for (jy = 0; jy < space.nY - 1; jy++)
{
for (ix = 0; ix < space.nX - 1; ix++)
{
fvector.push_back(fvalue);
}
fvector.push_back(fvalue);
fmatrix.push_back(fvector);
fvector.clear();
}
}
else
{
for (ix = 0; ix < space.nX - 1; ix++)
fscanf(istream, "%u", &value);
for (jy = 0; jy < space.nY - 1; jy++)
{
fscanf(istream, "\nRow iy=%u:", &value);
for (ix = 0; ix < space.nX - 1; ix++)
{
fscanf(istream, "%f", &fvalue);
fvector.push_back(fvalue);
}
// last value
fvector.push_back(fvalue);
fmatrix.push_back(fvector);
fvector.clear();
}
}
// save data
for (--jy; jy >= 0; jy--)
{
fvector = fmatrix[jy];
for (ix = 0; ix < space.nX; ix++)
{
fvalue = fvector[ix];
fprintf(sstreamD, "%.3f\t", fvalue);
}
fprintf(sstreamD, "\n");
}
// last row
fvector = fmatrix[0];
for (ix = 0; ix < space.nX; ix++)
{
fvalue = fvector[ix];
fprintf(sstreamD, "%.3f\t", fvalue);
}
fprintf(sstreamD, "\n");
fmatrix.clear();
fvector.clear();
printf("\t\tok\n");
}
// second period
for (i = 1; i < mpsize; i++)
{
mp = mperiods1[i];
// Map of PRESSURE
printf("\nMap of PRESSURE at %u %s %u:\n", mp.date, mp.mon, mp.year);
fprintf(pstream, "%.3f %.3f\n", mp.pmin, mp.pmax);
fseek(istream, mp.destp + 138, SEEK_SET);
for (kz = 0; kz < space.nZ; kz++)
{
printf("\tlayer%u", kz + 1);
fscanf(istream, "\nLayer iz=%u\nix= :", &value);
// read data
for (ix = 0; ix < space.nX - 1; ix++)
fscanf(istream, "%u", &value);
for (jy = 0; jy < space.nY - 1; jy++)
{
fscanf(istream, "\nRow iy=%u:", &value);
for (ix = 0; ix < space.nX - 1; ix++)
{
fscanf(istream, "%f", &fvalue);
fvector.push_back(fvalue);
}
// last value
fvector.push_back(fvalue);
fmatrix.push_back(fvector);
fvector.clear();
}
// save data
for (--jy; jy >= 0; jy--)
{
fvector = fmatrix[jy];
for (ix = 0; ix < space.nX; ix++)
{
fvalue = fvector[ix];
fprintf(pstream, "%.3f\t", fvalue);
}
fprintf(pstream, "\n");
}
// last row
fvector = fmatrix[0];
for (ix = 0; ix < space.nX; ix++)
{
fvalue = fvector[ix];
fprintf(pstream, "%.3f\t", fvalue);
}
fprintf(pstream, "\n");
fmatrix.clear();
fvector.clear();
printf("\t\tok\n");
}
// Map of soil
printf("\nMap of soil at %u %s %u:\n", mp.date, mp.mon, mp.year);
fprintf(sstream, "%.3f %.3f\n", mp.smin, mp.smax);
fseek(istream, mp.dests + 134, SEEK_SET);
for (kz = 0; kz < space.nZ; kz++)
{
fscanf(istream, "\nLayer iz=%u\nix= :", &value);
// read data
for (ix = 0; ix < space.nX - 1; ix++)
fscanf(istream, "%u", &value);
for (jy = 0; jy < space.nY - 1; jy++)
{
fscanf(istream, "\nRow iy=%u:", &value);
for (ix = 0; ix < space.nX - 1; ix++)
{
fscanf(istream, "%f", &fvalue);
fvector.push_back(fvalue);
}
fvector.push_back(fvalue);
fmatrix.push_back(fvector);
fvector.clear();
}
// save data
for (--jy; jy >= 0; jy--)
{
fvector = fmatrix[jy];
for (ix = 0; ix < space.nX; ix++)
{
fvalue = fvector[ix];
fprintf(sstream, "%.3f\t", fvalue);
}
fprintf(sstream, "\n");
}
// last row
fvector = fmatrix[0];
for (ix = 0; ix < space.nX; ix++)
{
fvalue = fvector[ix];
fprintf(sstream, "%.3f\t", fvalue);
}
fprintf(sstream, "\n");
fmatrix.clear();
fvector.clear();
}
// dporo soil layers
fprintf(sstreamD, "%.3f %.3f\n", mp.smin, mp.smax);
for (kz = 0; kz < space.nZ; kz++)
{
printf("\tlayer%u", kz + 1);
fscanf(istream, "\nLayer iz=%u\nix= :", &value);
// read data
for (ix = 0; ix < space.nX - 1; ix++)
fscanf(istream, "%u", &value);
for (jy = 0; jy < space.nY - 1; jy++)
{
fscanf(istream, "\nRow iy=%u:", &value);
for (ix = 0; ix < space.nX - 1; ix++)
{
fscanf(istream, "%f", &fvalue);
fvector.push_back(fvalue);
}
fvector.push_back(fvalue);
fmatrix.push_back(fvector);
fvector.clear();
}
// save data
for (--jy; jy >= 0; jy--)
{
fvector = fmatrix[jy];
for (ix = 0; ix < space.nX; ix++)
{
fvalue = fvector[ix];
fprintf(sstreamD, "%.3f\t", fvalue);
}
fprintf(sstreamD, "\n");
}
// last row
fvector = fmatrix[0];
for (ix = 0; ix < space.nX; ix++)
{
fvalue = fvector[ix];
fprintf(sstreamD, "%.3f\t", fvalue);
}
fprintf(sstreamD, "\n");
fmatrix.clear();
fvector.clear();
printf("\t\tok\n");
}
}
fclose(sstreamD);
}
else
{ // Map of PRESSURE
printf("\nMap of PRESSURE at %u %s %u:\n", mp.date, mp.mon, mp.year);
fprintf(pstream, "%.3f %.3f\n", mp.pmin, mp.pmax);
fseek(istream, mp.destp + 138, SEEK_SET);
for (kz = 0; kz < space.nZ; kz++)
{
printf("\tlayer%u", kz + 1);
fscanf(istream, "\nLayer iz=%u\nix= :", &value);
// read data
if (fscanf(istream, "All values are %f", &fvalue) > 0)
{
for (jy = 0; jy < space.nY - 1; jy++)
{
for (ix = 0; ix < space.nX - 1; ix++)
{
fvector.push_back(fvalue);
}
fvector.push_back(fvalue);
fmatrix.push_back(fvector);
fvector.clear();
}
}
else
{
for (ix = 0; ix < space.nX - 1; ix++)
fscanf(istream, "%u", &value);
for (jy = 0; jy < space.nY - 1; jy++)
{
fscanf(istream, "\nRow iy=%u:", &value);
for (ix = 0; ix < space.nX - 1; ix++)
{
fscanf(istream, "%f", &fvalue);
fvector.push_back(fvalue);
}
// last value
fvector.push_back(fvalue);
fmatrix.push_back(fvector);
fvector.clear();
}
}
// save data
for (--jy; jy >= 0; jy--)
{
fvector = fmatrix[jy];
for (ix = 0; ix < space.nX - 1; ix++)
{
fvalue = fvector[ix];
// inactive cells
if (fvalue >= mp.pmin - 1e-2)
{
pbarr[i] = 1;
n++;
}
i++;
fprintf(pstream, "%.3f\t", fvalue);
}
fprintf(pstream, "%.3f\t", fvalue);
fprintf(pstream, "\n");
}
// last row
fvector = fmatrix[0];
for (ix = 0; ix < space.nX; ix++)
{
fvalue = fvector[ix];
fprintf(pstream, "%.3f\t", fvalue);
}
fprintf(pstream, "\n");
fmatrix.clear();
fvector.clear();
printf("\t\tok\n");
}
fwrite(pbarr, 1, size, rstream);
delete [] pbarr;
fclose(rstream);
// Map of soil
printf("\nMap of soil at %u %s %u:\n", mp.date, mp.mon, mp.year);
fprintf(sstream, "%.3f %.3f\n", mp.smin, mp.smax);
fseek(istream, mp.dests + 134, SEEK_SET);
for (kz = 0; kz < space.nZ; kz++)
{
printf("\tlayer%u", kz + 1);
fscanf(istream, "\nLayer iz=%u\nix= :", &value);
//
if (fscanf(istream, "All values are %f", &fvalue) > 0)
{
for (jy = 0; jy < space.nY - 1; jy++)
{
for (ix = 0; ix < space.nX - 1; ix++)
{
fvector.push_back(fvalue);
}
fvector.push_back(fvalue);
fmatrix.push_back(fvector);
fvector.clear();
}
}
else
{
for (ix = 0; ix < space.nX - 1; ix++)
fscanf(istream, "%u", &value);
for (jy = 0; jy < space.nY - 1; jy++)
{
fscanf(istream, "\nRow iy=%u:", &value);
for (ix = 0; ix < space.nX - 1; ix++)
{
fscanf(istream, "%f", &fvalue);
fvector.push_back(fvalue);
}
// last value
fvector.push_back(fvalue);
fmatrix.push_back(fvector);
fvector.clear();
}
}
// save data
for (--jy; jy >= 0; jy--)
{
fvector = fmatrix[jy];
for (ix = 0; ix < space.nX; ix++)
{
fvalue = fvector[ix];
fprintf(sstream, "%.3f\t", fvalue);
}
fprintf(sstream, "\n");
}
// last row
fvector = fmatrix[0];
for (ix = 0; ix < space.nX; ix++)
{
fvalue = fvector[ix];
fprintf(sstream, "%.3f\t", fvalue);
}
fprintf(sstream, "\n");
fmatrix.clear();
fvector.clear();
printf("\t\tok\n");
}
// second period
for (i = 1; i < mpsize; i++)
{
mp = mperiods1[i];
// Map of PRESSURE
printf("\nMap of PRESSURE at %u %s %u:\n", mp.date, mp.mon, mp.year);
fprintf(pstream, "%.3f %.3f\n", mp.pmin, mp.pmax);
fseek(istream, mp.destp + 138, SEEK_SET);
for (kz = 0; kz < space.nZ; kz++)
{
printf("\tlayer%u", kz + 1);
fscanf(istream, "\nLayer iz=%u\nix= :", &value);
// read data
for (ix = 0; ix < space.nX - 1; ix++)
fscanf(istream, "%u", &value);
for (jy = 0; jy < space.nY - 1; jy++)
{
fscanf(istream, "\nRow iy=%u:", &value);
for (ix = 0; ix < space.nX - 1; ix++)
{
fscanf(istream, "%f", &fvalue);
fvector.push_back(fvalue);
}
// last value
fvector.push_back(fvalue);
fmatrix.push_back(fvector);
fvector.clear();
}
// save data
for (--jy; jy >= 0; jy--)
{
fvector = fmatrix[jy];
for (ix = 0; ix < space.nX; ix++)
{
fvalue = fvector[ix];
fprintf(pstream, "%.3f\t", fvalue);
}
fprintf(pstream, "\n");
}
// last row
fvector = fmatrix[0];
for (ix = 0; ix < space.nX; ix++)
{
fvalue = fvector[ix];
fprintf(pstream, "%.3f\t", fvalue);
}
fprintf(pstream, "\n");
fmatrix.clear();
fvector.clear();
printf("\t\tok\n");
}
// Map of soil
printf("\nMap of soil at %u %s %u:\n", mp.date, mp.mon, mp.year);
fprintf(sstream, "%.3f %.3f\n", mp.smin, mp.smax);
fseek(istream, mp.dests + 134, SEEK_SET);
for (kz = 0; kz < space.nZ; kz++)
{
printf("\tlayer%u", kz + 1);
fscanf(istream, "\nLayer iz=%u\nix= :", &value);
for (ix = 0; ix < space.nX - 1; ix++)
fscanf(istream, "%u", &value);
for (jy = 0; jy < space.nY - 1; jy++)
{
fscanf(istream, "\nRow iy=%u:", &value);
for (ix = 0; ix < space.nX - 1; ix++)
{
fscanf(istream, "%f", &fvalue);
fvector.push_back(fvalue);
}
fvector.push_back(fvalue);
fmatrix.push_back(fvector);
fvector.clear();
}
// save data
for (--jy; jy >= 0; jy--)
{
fvector = fmatrix[jy];
for (ix = 0; ix < space.nX; ix++)
{
fvalue = fvector[ix];
fprintf(sstream, "%.3f\t", fvalue);
}
fprintf(sstream, "\n");
}
// last row
fvector = fmatrix[0];
for (ix = 0; ix < space.nX; ix++)
{
fvalue = fvector[ix];
fprintf(sstream, "%.3f\t", fvalue);
}
fprintf(sstream, "\n");
fmatrix.clear();
fvector.clear();
printf("\t\tok\n");
}
}
}
fclose(istream);
fclose(pstream);
fclose(sstream);
printf("\nnumber of active cells\t%u", n);
printf("\nnumber of periods\t%u\n\n", mpsize);
}
return bres;
}
bool wellConvert(const char* filename)
{
printf("[%s]\n", "trackwell.txt");
char name[9],
file[MAX_PATH];
memset(file, 0, MAX_PATH);
size_t len = strlen(filename);
strcpy(file, din);
strncat(file, filename, --len);
FILE *istream = fopen(file, "r"),
*ostream;
if (!istream) return 0;
strcpy(file, dout);
strcat(file, "\\well.txt");
ostream = fopen(file, "w");
if (!ostream) return 0;
bool bvalid;
size_t i;
wline _wline;
vector <wline> wlines;
while (fscanf(istream, "%s\n", name) == 1)
{
bvalid = 0;
while (fscanf(istream, "%u %u %f %f\n", &_wline.x, &_wline.y, &_wline.z0, &_wline.z1) == 4)
{
if (BOUNDS(space).ptBelong(_wline.x, _wline.y))
{
bvalid = 1;
wlines.push_back(_wline);
}
}
fscanf(istream, "/\n");
if (bvalid)
{
printf("\twell %s\n", name);
fprintf(ostream, " %s\n", name);
for (i = 0; i < wlines.size(); i++)
{
fprintf(ostream, "%u %u %.2f\n", wlines[i].x, wlines[i].y, -wlines[i].z0);
}
wlines.clear();
fprintf(ostream, "/\n");
}
}
fclose(ostream);
fclose(istream);
printf("\n");
return 1;
}
bool stockConvert(vector<param> *pvec, dens* pdens)
{
printf("[%s]\n", "stock");
bool bres = 1,
bm = 0, bn = 0, bs = 0, bz = 0; // can close streams
FILE *streamM, *streamN, *streamS, *streamZ;
try
{
char file[MAX_PATH];
int i;
param pm;
for (i = 0; i < STOCK_CONST; i++)
{
pm = pvec->at(i);
memset(file, 0, MAX_PATH);
strcpy(file, dout);
strcat(file, pm.shortname);
if (strcmp(pm.shortname, "M.txt") == 0)
{
streamM = fopen(file, "r");
if (!streamM) throw 0;
bm = 1;
}
if (strcmp(pm.shortname, "NTOG.txt") == 0)
{
streamN = fopen(file, "r");
if (!streamN) throw 0;
bn = 1;
}
if (strcmp(pm.shortname, "SWAT.txt") == 0)
{
streamS = fopen(file, "r");
if (!streamS) throw 0;
bs = 1;
}
if (strcmp(pm.shortname, "ZCORN.txt") == 0)
{
streamZ = fopen(file, "r");
if (!streamZ) throw 0;
bz = 1;
}
}
memset(file, 0, MAX_PATH);
strcpy(file, dout);
strcat(file, "stock.txt");
FILE *ostream = fopen(file, "w");
if (!ostream) throw 0;
fprintf(ostream, " \n"); // place for min & max
float fvalue, fmin = 10.0f, fmax = 0.0f,
fvalueM, fvalueN, fvalueS, fvalueZ;
floatvector fvector, fvectorh;
floatmatrix fmatrix, fmatrixh;
fscanf(streamM, "%f %f", &fvalueS, &fvalueS);
fscanf(streamN, "%f %f", &fvalueN, &fvalueN);
fscanf(streamS, "%f %f", &fvalueS, &fvalueS);
fscanf(streamZ, "%f %f", &fvalueZ, &fvalueZ);
int j, k;
for (i = 0; i < space.nZ; i++)
{
printf("\tlayer%u", i + 1);
// m, ntog, s, roof
for (j = 0; j < space.nY; j++)
{
for (k = 0; k < space.nX; k++)
{
fscanf(streamM, "%f", &fvalueM);
fscanf(streamN, "%f", &fvalueN);
fscanf(streamS, "%f", &fvalueS);
fscanf(streamZ, "%f", &fvalueZ);
fvalue = fvalueM * fvalueN * fvalueS;
fvector.push_back(fvalue);
fvectorh.push_back(fvalueZ);
}
fmatrix.push_back(fvector);
fmatrixh.push_back(fvectorh);
fvector.clear();
fvectorh.clear();
}
// sole
for (j = 0; j < space.nY; j++)
{
fvectorh = fmatrixh[j];
for (k = 0; k < space.nX; k++)
{
fscanf(streamZ, "%f", &fvalueZ);
float f0 = fmatrix[j][k], f1 = fvectorh[k];
fvalue = fmatrix[j][k] * (fvectorh[k] - fvalueZ);
fmatrix[j][k] = fvalue;
}
fvectorh.clear();
}
fmatrixh.clear();
// save
for (j = 0; j < space.nY; j++)
{
fvector = fmatrix[j];
for (k = 0; k < space.nX; k++)
{
fvalue = fvector[k] * pdens->kper * pdens->oil / 1000.0f;
if (fvalue < fmin) fmin = fvalue;
if (fvalue > fmax) fmax = fvalue;
fprintf(ostream, "%.3f ", fvalue);
}
fprintf(ostream, "\n");
fvector.clear();
}
fmatrix.clear();
printf("\t\tok\n");
}
fseek(ostream, 0, SEEK_SET);
fprintf(ostream, "%.3f %.3f", fmin, fmax);
fclose(ostream);
}
catch (int)
{
bres = 0;
}
// close streams
if (bm) fclose(streamM);
if (bn) fclose(streamN);
if (bs) fclose(streamS);
if (bz) fclose(streamZ);
printf("\n");
return bres;
}
bool roxConvert(const char* filename)
{
char file[MAX_PATH];
WIN32_FIND_DATA find;
memset(file, 0, MAX_PATH);
strcpy(file, din);
strcat(file, "\\*.out");
HANDLE hfile0 = FindFirstFile(file, &find);
if (hfile0 == INVALID_HANDLE_VALUE)
{
printf("error: %s files not found\n", file);
return 0;
}
FindClose(hfile0);
memset(file, 0, MAX_PATH);
strcpy(file, din);
strcat(file, find.cFileName);
hfile0 = CreateFile(file, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0);
char buf[USHRT_MAX];
memset(buf, 0, USHRT_MAX);
ULONG nbytes;
ReadFile(hfile0, buf, USHRT_MAX, &nbytes, 0);
//
HANDLE hfile1 = CreateFile(filename, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0);
if (hfile1 == INVALID_HANDLE_VALUE)
{
printf("error: %s opening failed\n", filename);
return 0;
}
LONG size = GetFileSize(hfile1, 0);
char* pbuf = new char[size];
memset(pbuf, 0, size);
ReadFile(hfile1, pbuf, size, &nbytes, 0);
CloseHandle(hfile1);
// dim
memset(&space, 0, sizeof(space));
char* pdest0 = 0;
if (pdest0 = strstr(pbuf, "DPORO")) dporo = 1;
if (pdest0 = strstr(pbuf, "SIZE"))
{
sscanf(pdest0, "SIZE %u %u %u", &space.nX, &space.nY, &space.nZ);
space.nX++;
space.nY++;
if (dporo) space.nZ /= 2;
printf("SIZE %u %u %u\n\n", space.nX, space.nY, space.nZ);
}
if (!outConvert(file, hfile0)) return 0;
// density & kper
dens _dens;
if (pdest0 = strstr(pbuf, "FLUID BLACKOIL"))
{ // water
if (pdest0 = strstr(pdest0, "WATR"))
{
float watr;
sscanf(pdest0, "WATR\n %f %f", &watr, &_dens.watr);
}
// oil
if (pdest0 = strstr(pdest0, "BASIC")) sscanf(pdest0, "BASIC\n %f", &_dens.oil);
// gas, kper
if (pdest0 = strstr(pdest0, "OPVT"))
{
float p, visc;
sscanf(pdest0, "OPVT\n %f %f %f %f", &p, &_dens.kper, &visc, &_dens.gas);
}
}
// params
if (pdest0 = strstr(pbuf, "include"))
{
char *pdest1 = 0;
char line[MAX_PATH];
size_t len;
param pm;
vector<param> params;
do
{
memset(line, 0, MAX_PATH);
memset(pm.filename, 0, MAX_PATH);
sscanf(pdest0, "include '%s", line);
len = strlen(line);
strncpy(pm.filename, line, --len);
pm.makeShort();
if (strlen(pm.shortname) > 0)
{
if (strcmp(pm.shortname, "K.txt") == 0)
{
pdest1 = strstr(buf, "Permx");
sscanf(pdest1, "Permx %f %f", &pm.min, &pm.max);
}
else if (strcmp(pm.shortname, "KZ.txt") == 0)
{
pdest1 = strstr(buf, "Permz");
sscanf(pdest1, "Permz %f %f", &pm.min, &pm.max);
}
else if (strcmp(pm.shortname, "M.txt") == 0)
{
pdest1 = strstr(buf, "Porosity");
sscanf(pdest1, "Porosity %f %f", &pm.min, &pm.max);
params.push_back(pm);
}
else if (strcmp(pm.shortname, "NTOG.txt") == 0)
{
pdest1 = strstr(buf, "NTG");
sscanf(pdest1, "NTG %f %f", &pm.min, &pm.max);
params.push_back(pm);
}
else if (strcmp(pm.shortname, "SWAT.txt") == 0)
{
pm.min = 1.0f;
pm.max = 0.0f;
params.push_back(pm);
}
else if (strcmp(pm.shortname, "ZCORN.txt") == 0)
{
params.push_back(pm);
}
paramConvert(&pm);
}
pdest0++;
pdest0 = strstr(pdest0, "include");
}
while (pdest0);
// stock
if (params.size() == STOCK_CONST) stockConvert(¶ms, &_dens);
params.clear();
}
// wells
if (pdest0 = strstr(pbuf, "TFIL"))
{
sscanf(pdest0, "TFIL\n'%s", file);
wellConvert(file);
}
SAFE_DELETE_ARRAY(pbuf);
return 1;
}
int main(int argc, char* argv[])
{
if (argc == 1)
{
printf("usage: rox [filename]\n");
return 0;
}
// head
printf("\n");
printf("\t\t\t--------------------\n");
printf("\t\t\tRoxar Data Convertor\n");
printf("\t\t\t--------------------\n");
printf("\n");
char dat[MAX_PATH];
memset(dat, 0, MAX_PATH);
memset(din, 0, MAX_PATH);
getDir(din, argv[1]);
if (strlen(din) == 0)
{
getDir(din, argv[0]);
strcpy(dat, din);
strcat(dat, argv[1]);
}
else strcpy(dat, argv[1]);
memset(dout, 0, MAX_PATH);
strcpy(dout, din);
strcat(dout, "out");
CreateDirectory(dout, 0);
strcat(dout, "\\");
printf("%s\n\n", dat);
if (!roxConvert(dat)) return 1;
printf("Press any key to continue\n");
getch();
return 0;
} | [
"rrv.kazan@gmail.com@b6168ec3-97fc-df6f-cbe5-288b4f99fbbd"
] | [
[
[
1,
1691
]
]
] |
ff2a51e7654fda9efa2d73057908c0789cb54ad4 | 9c99641d20454681792481c25cd93503449b174d | /WEBGL_lesson7/src/testApp.h | 05ec2e26c864f3e8f6cf45cee925c5fefb43d660 | [] | no_license | fazeaction/OF_LearningWebGL_Examples | a8befc8c65dd2f9ffc0c45a3c54548f5a05295aa | b608e252b58129bab844c32cc6a7929f3643e145 | refs/heads/master | 2021-03-12 23:58:57 | 2010-05-17 22:35:15 | 2010-05-17 22:35:15 | 665,483 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,529 | h | #ifndef _TEST_APP
#define _TEST_APP
#include "ofMain.h"
#include "ofxShader.h"
#include "ofxVectorMath.h"
class testApp : public ofBaseApp{
public:
void setup();
void update();
void draw();
void keyPressed (int key);
void keyReleased(int key);
void mouseMoved(int x, int y );
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased(int x, int y, int button);
void windowResized(int w, int h);
void setupScreenForLesson();
void setMatrixUniforms();
void checkForKeys();
void setAmbientLightColor();
void setDirectLightColor();
void setPositionLight();
GLuint vboId[2];
GLint locationID[6];
GLfloat pMatrix[16];
GLfloat mvMatrix[16];
float xRot;
float xSpeed;
float yRot;
float ySpeed;
float xRotLight;
float yRotLight;
float z;
//AMBIENT COLOR VALUES
float ambient_red_value;
float ambient_green_value;
float ambient_blue_value;
//DIRECT LIGHT COLOR VALUES
float direct_red_value;
float direct_green_value;
float direct_blue_value;
//POSITION LIGTH
float xpos;
float ypos;
float zpos;
bool of_key_backspace_pressed;
bool of_key_page_up_pressed;
bool of_key_page_down_pressed;
bool of_key_left_pressed;
bool of_key_right_pressed;
bool of_key_up_pressed;
bool of_key_down_pressed;
bool use_lighting;
ofImage neheTexture;
ofTrueTypeFont verdana;
ofxShader shader;
ofxVec3f lightDirection;
};
#endif
| [
"tribadelics@gmail.com"
] | [
[
[
1,
85
]
]
] |
b998bb618b8fdc5202d1eade78f7576bd24c77ff | 4797c7058b7157e3d942e82cf8ad94b58be488ae | /PlayerShip.cpp | f70fc2002f2cfb0b6a7261c671bdf0ac7d214a00 | [] | no_license | koguz/DirectX-Space-Game | 2d1d8179439870fd1427beb9624f1c5452546c39 | be672051fd0009cbd5851c92bd344d3b23645474 | refs/heads/master | 2020-05-18 02:11:47 | 2011-05-25 14:35:26 | 2011-05-25 14:35:26 | 1,799,267 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,804 | cpp | #include "PlayerShip.h"
PlayerShip::PlayerShip():BaseObject()
{
speed = 0.0f;
lastShot = 0;
}
bool PlayerShip::Init(IDirect3DDevice9 *d, IDirectSound8 *s)
{
((MyMesh*)(this))->Init(d, "ship01.x");
Sound = s;
Engine.Init(Sound, "PSEngine.wav");
Fire.Init(Sound, "PSFire.wav");
Fire.SetLoop(false);
Scratch.Init(Sound, "Scratch.wav");
Scratch.SetLoop(false);
HitSound.Init(Sound, "hitship.wav");
HitSound.SetLoop(false);
/*
Mission1.Init(Sound, "mission01.wav");
Mission1.SetLoop(false);
Mission1.Play();
*/
Engine.SetVolume(-800);
Engine.Play();
maxSpeed = 6.0f;
minSpeed = 0.6f;
casSpeed = 2.0f;
laserInterval = 500;
health = 2000;
return true;
}
void PlayerShip::Scratched()
{
Scratch.setPosition(position);
Scratch.Play();
health -= 5;
}
void PlayerShip::Hit(int d)
{
health -= d;
HitSound.Play();
}
void PlayerShip::Update(float deltaTime)
{
if (health < 2000 && GetTickCount() - lastGen > 100 )
{
health++;
lastGen = GetTickCount();
}
time = deltaTime;
TranslateV(speed * look * deltaTime);
Engine.setPosition(position);
Fire.setPosition(position);
HitSound.setPosition(position);
// Mission1.setPosition(position);
std::vector<Laser>::iterator temp;
std::vector<Laser>::iterator toDel;
bool d = false;
for(temp = lasers.begin(); temp != lasers.end(); temp++)
{
(*temp).Update(time);
// (*temp).Draw();
if (abs((*temp).getPosition().x) > 200 || abs((*temp).getPosition().y) > 200 || abs((*temp).getPosition().z) > 200 )
{
toDel = temp;
d = true;
}
if ((*temp).getHit())
{
toDel = temp;
d = true;
}
}
if (d)
lasers.erase(toDel);
}
void PlayerShip::SpeedUp()
{
SetSpeed(maxSpeed);
}
void PlayerShip::SpeedDown()
{
SetSpeed(minSpeed);
}
void PlayerShip::SpeedNormal()
{
SetSpeed(casSpeed);
}
void PlayerShip::SetSpeed(float s)
{
if (s == speed) return;
if (s >= casSpeed && s < maxSpeed && speed != s)
Engine.setFrequency(0);
else if (s >= maxSpeed && speed != s)
Engine.setFrequency(24000);
else if (s >= minSpeed && s < casSpeed && speed != s)
Engine.setFrequency(20000);
speed = s;
}
void PlayerShip::FireLaser()
{
if (health < 0) return;
if (GetTickCount() - lastShot > laserInterval)
{
Laser laser1(Device, Laser::RED);
Laser laser2(Device, Laser::RED);
laser1.SetRotation(rotationMatrix);
laser1.TranslateV(position + (right * 0.6f));
laser1.SetOrientation(up, right, look);
laser2.SetRotation(rotationMatrix);
laser2.TranslateV(position - (right * 0.6f));
laser2.SetOrientation(up, right, look);
lasers.push_back(laser1);
lasers.push_back(laser2);
Fire.Play();
lastShot = GetTickCount();
}
else return;
}
| [
"kayaoguz@gmail.com"
] | [
[
[
1,
142
]
]
] |
6f7086c09ff33638bfa90d058efb7f50396a5350 | e02fa80eef98834bf8a042a09d7cb7fe6bf768ba | /TEST_MyGUI_Source/MyGUIEngine/include/MyGUI_Instance.h | 9d50505893548012b5efd58c18987888bca84ee0 | [] | no_license | MyGUI/mygui-historical | fcd3edede9f6cb694c544b402149abb68c538673 | 4886073fd4813de80c22eded0b2033a5ba7f425f | refs/heads/master | 2021-01-23 16:40:19 | 2008-03-06 22:19:12 | 2008-03-06 22:19:12 | 22,805,225 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 843 | h | /*!
@file
@author Albert Semenov
@date 11/2007
@module
*/
#ifndef __MYGUI_INSTANCE_H__
#define __MYGUI_INSTANCE_H__
#define INSTANCE_HEADER(type) \
private: \
static type* msInstance; \
bool mIsInitialise; \
public: \
type();\
~type();\
static type& getInstance(void); \
static type* getInstancePtr(void);
#define INSTANCE_IMPLEMENT(type) \
type* type::msInstance = 0; \
type* type::getInstancePtr(void) {return msInstance;} \
type& type::getInstance(void) {MYGUI_ASSERT(0 != msInstance, "instance " << #type << " was not created");return (*msInstance);} \
type::type() : mIsInitialise(false) {MYGUI_ASSERT(0 == msInstance, "instance " << #type << " is exsist");msInstance=this;} \
type::~type() {msInstance=0;} \
const std::string INSTANCE_TYPE_NAME(#type);
#endif // __MYGUI_INSTANCE_H__
| [
"my.name.post@gmail.com"
] | [
[
[
1,
29
]
]
] |
205fdf74194b31b1aa0b71d63e744b615671e35c | 09dfc0e039143673380a3d490c84b6c0d3d6ee6c | /surf_object_recognition/src/fasthessian.cpp | 2721a0a80358176dc44f71a4d0ec48675cd9adc0 | [] | no_license | vishu2287/ucsb-ros-pkg | 8642a78ddbe352fcb544658fb23737cb3ce86f04 | b2e34c76b362a69b6c2f3c34c9f5cee419aa9839 | refs/heads/master | 2016-09-10 04:40:42 | 2011-03-16 07:40:18 | 2011-03-16 07:40:18 | 34,023,815 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,292 | cpp | /***********************************************************
* --- OpenSURF --- *
* This library is distributed under the GNU GPL. Please *
* use the contact form at http://www.chrisevansdev.com *
* for more information. *
* *
* C. Evans, Research Into Robust Visual Features, *
* MSc University of Bristol, 2008. *
* *
************************************************************/
#include "integral.h"
#include "ipoint.h"
#include "utils.h"
#include <vector>
#include "responselayer.h"
#include "fasthessian.h"
using namespace std;
//-------------------------------------------------------
//! Constructor without image
FastHessian::FastHessian(std::vector<Ipoint> &ipts,
const int octaves, const int intervals, const int init_sample,
const float thresh)
: ipts(ipts), i_width(0), i_height(0)
{
// Save parameter set
saveParameters(octaves, intervals, init_sample, thresh);
}
//-------------------------------------------------------
//! Constructor with image
FastHessian::FastHessian(IplImage *img, std::vector<Ipoint> &ipts,
const int octaves, const int intervals, const int init_sample,
const float thresh)
: ipts(ipts), i_width(0), i_height(0)
{
// Save parameter set
saveParameters(octaves, intervals, init_sample, thresh);
// Set the current image
setIntImage(img);
}
//-------------------------------------------------------
FastHessian::~FastHessian()
{
for (unsigned int i = 0; i < responseMap.size(); ++i)
{
delete responseMap[i];
}
}
//-------------------------------------------------------
//! Save the parameters
void FastHessian::saveParameters(const int octaves, const int intervals,
const int init_sample, const float thresh)
{
// Initialise variables with bounds-checked values
this->octaves =
(octaves > 0 && octaves <= 4 ? octaves : OCTAVES);
this->intervals =
(intervals > 0 && intervals <= 4 ? intervals : INTERVALS);
this->init_sample =
(init_sample > 0 && init_sample <= 6 ? init_sample : INIT_SAMPLE);
this->thresh = (thresh >= 0 ? thresh : THRES);
}
//-------------------------------------------------------
//! Set or re-set the integral image source
void FastHessian::setIntImage(IplImage *img)
{
// Change the source image
this->img = img;
i_height = img->height;
i_width = img->width;
}
//-------------------------------------------------------
//! Find the image features and write into vector of features
void FastHessian::getIpoints()
{
// filter index map
static const int filter_map [OCTAVES][INTERVALS] = {{0,1,2,3}, {1,3,4,5}, {3,5,6,7}, {5,7,8,9}, {7,9,10,11}};
// Clear the vector of exisiting ipts
ipts.clear();
// Build the response map
buildResponseMap();
// Get the response layers
ResponseLayer *b, *m, *t;
for (int o = 0; o < octaves; ++o) for (int i = 0; i <= 1; ++i)
{
b = responseMap.at(filter_map[o][i]);
m = responseMap.at(filter_map[o][i+1]);
t = responseMap.at(filter_map[o][i+2]);
// loop over middle response layer at density of the most
// sparse layer (always top), to find maxima across scale and space
for (int r = 0; r < t->height; ++r)
{
for (int c = 0; c < t->width; ++c)
{
if (isExtremum(r, c, t, m, b))
{
interpolateExtremum(r, c, t, m, b);
}
}
}
}
}
//-------------------------------------------------------
//! Build map of DoH responses
void FastHessian::buildResponseMap()
{
// Calculate responses for the first 4 octaves:
// Oct1: 9, 15, 21, 27
// Oct2: 15, 27, 39, 51
// Oct3: 27, 51, 75, 99
// Oct4: 51, 99, 147,195
// Oct5: 99, 195,291,387
// Deallocate memory and clear any existing response layers
for(unsigned int i = 0; i < responseMap.size(); ++i)
delete responseMap[i];
responseMap.clear();
// Get image attributes
int w = (i_width / init_sample);
int h = (i_height / init_sample);
int s = (init_sample);
// Calculate approximated determinant of hessian values
if (octaves >= 1)
{
responseMap.push_back(new ResponseLayer(w, h, s, 9));
responseMap.push_back(new ResponseLayer(w, h, s, 15));
responseMap.push_back(new ResponseLayer(w, h, s, 21));
responseMap.push_back(new ResponseLayer(w, h, s, 27));
}
if (octaves >= 2)
{
responseMap.push_back(new ResponseLayer(w/2, h/2, s*2, 39));
responseMap.push_back(new ResponseLayer(w/2, h/2, s*2, 51));
}
if (octaves >= 3)
{
responseMap.push_back(new ResponseLayer(w/4, h/4, s*4, 75));
responseMap.push_back(new ResponseLayer(w/4, h/4, s*4, 99));
}
if (octaves >= 4)
{
responseMap.push_back(new ResponseLayer(w/8, h/8, s*8, 147));
responseMap.push_back(new ResponseLayer(w/8, h/8, s*8, 195));
}
if (octaves >= 5)
{
responseMap.push_back(new ResponseLayer(w/16, h/16, s*16, 291));
responseMap.push_back(new ResponseLayer(w/16, h/16, s*16, 387));
}
// Extract responses from the image
for (unsigned int i = 0; i < responseMap.size(); ++i)
{
buildResponseLayer(responseMap[i]);
}
}
//-------------------------------------------------------
//! Calculate DoH responses for supplied layer
void FastHessian::buildResponseLayer(ResponseLayer *rl)
{
float *responses = rl->responses; // response storage
unsigned char *laplacian = rl->laplacian; // laplacian sign storage
int step = rl->step; // step size for this filter
int b = (rl->filter - 1) / 2 + 1; // border for this filter
int l = rl->filter / 3; // lobe for this filter (filter size / 3)
int w = rl->filter; // filter size
float inverse_area = 1.f/(w*w); // normalisation factor
float Dxx, Dyy, Dxy;
for(int r, c, ar = 0, index = 0; ar < rl->height; ++ar)
{
for(int ac = 0; ac < rl->width; ++ac, index++)
{
// get the image coordinates
r = ar * step;
c = ac * step;
// Compute response components
Dxx = BoxIntegral(img, r - l + 1, c - b, 2*l - 1, w)
- BoxIntegral(img, r - l + 1, c - l / 2, 2*l - 1, l)*3;
Dyy = BoxIntegral(img, r - b, c - l + 1, w, 2*l - 1)
- BoxIntegral(img, r - l / 2, c - l + 1, l, 2*l - 1)*3;
Dxy = + BoxIntegral(img, r - l, c + 1, l, l)
+ BoxIntegral(img, r + 1, c - l, l, l)
- BoxIntegral(img, r - l, c - l, l, l)
- BoxIntegral(img, r + 1, c + 1, l, l);
// Normalise the filter responses with respect to their size
Dxx *= inverse_area;
Dyy *= inverse_area;
Dxy *= inverse_area;
// Get the determinant of hessian response & laplacian sign
responses[index] = (Dxx * Dyy - 0.81f * Dxy * Dxy);
laplacian[index] = (Dxx + Dyy >= 0 ? 1 : 0);
#ifdef RL_DEBUG
// create list of the image coords for each response
rl->coords.push_back(std::make_pair<int,int>(r,c));
#endif
}
}
}
//-------------------------------------------------------
//! Non Maximal Suppression function
int FastHessian::isExtremum(int r, int c, ResponseLayer *t, ResponseLayer *m, ResponseLayer *b)
{
// bounds check
int layerBorder = (t->filter + 1) / (2 * t->step);
if (r <= layerBorder || r >= t->height - layerBorder || c <= layerBorder || c >= t->width - layerBorder)
return 0;
// check the candidate point in the middle layer is above thresh
float candidate = m->getResponse(r, c, t);
if (candidate < thresh)
return 0;
for (int rr = -1; rr <=1; ++rr)
{
for (int cc = -1; cc <=1; ++cc)
{
// if any response in 3x3x3 is greater candidate not maximum
if (
t->getResponse(r+rr, c+cc) >= candidate ||
((rr != 0 && cc != 0) && m->getResponse(r+rr, c+cc, t) >= candidate) ||
b->getResponse(r+rr, c+cc, t) >= candidate
)
return 0;
}
}
return 1;
}
//-------------------------------------------------------
//! Interpolate scale-space extrema to subpixel accuracy to form an image feature.
void FastHessian::interpolateExtremum(int r, int c, ResponseLayer *t, ResponseLayer *m, ResponseLayer *b)
{
// get the step distance between filters
// check the middle filter is mid way between top and bottom
int filterStep = (m->filter - b->filter);
assert(filterStep > 0 && t->filter - m->filter == m->filter - b->filter);
// Get the offsets to the actual location of the extremum
double xi = 0, xr = 0, xc = 0;
interpolateStep(r, c, t, m, b, &xi, &xr, &xc );
// If point is sufficiently close to the actual extremum
if( fabs( xi ) < 0.5f && fabs( xr ) < 0.5f && fabs( xc ) < 0.5f )
{
Ipoint ipt;
ipt.x = static_cast<float>((c + xc) * t->step);
ipt.y = static_cast<float>((r + xr) * t->step);
ipt.scale = static_cast<float>((0.1333f) * (m->filter + xi * filterStep));
ipt.laplacian = static_cast<int>(m->getLaplacian(r,c,t));
ipts.push_back(ipt);
}
}
//-------------------------------------------------------
//! Performs one step of extremum interpolation.
void FastHessian::interpolateStep(int r, int c, ResponseLayer *t, ResponseLayer *m, ResponseLayer *b,
double* xi, double* xr, double* xc )
{
CvMat* dD, * H, * H_inv, X;
double x[3] = { 0 };
dD = deriv3D( r, c, t, m, b );
H = hessian3D( r, c, t, m, b );
H_inv = cvCreateMat( 3, 3, CV_64FC1 );
cvInvert( H, H_inv, CV_SVD );
cvInitMatHeader( &X, 3, 1, CV_64FC1, x, CV_AUTOSTEP );
cvGEMM( H_inv, dD, -1, NULL, 0, &X, 0 );
cvReleaseMat( &dD );
cvReleaseMat( &H );
cvReleaseMat( &H_inv );
*xi = x[2];
*xr = x[1];
*xc = x[0];
}
//-------------------------------------------------------
//! Computes the partial derivatives in x, y, and scale of a pixel.
CvMat* FastHessian::deriv3D(int r, int c, ResponseLayer *t, ResponseLayer *m, ResponseLayer *b)
{
CvMat* dI;
double dx, dy, ds;
dx = (m->getResponse(r, c + 1, t) - m->getResponse(r, c - 1, t)) / 2.0;
dy = (m->getResponse(r + 1, c, t) - m->getResponse(r - 1, c, t)) / 2.0;
ds = (t->getResponse(r, c) - b->getResponse(r, c, t)) / 2.0;
dI = cvCreateMat( 3, 1, CV_64FC1 );
cvmSet( dI, 0, 0, dx );
cvmSet( dI, 1, 0, dy );
cvmSet( dI, 2, 0, ds );
return dI;
}
//-------------------------------------------------------
//! Computes the 3D Hessian matrix for a pixel.
CvMat* FastHessian::hessian3D(int r, int c, ResponseLayer *t, ResponseLayer *m, ResponseLayer *b)
{
CvMat* H;
double v, dxx, dyy, dss, dxy, dxs, dys;
v = m->getResponse(r, c, t);
dxx = m->getResponse(r, c + 1, t) + m->getResponse(r, c - 1, t) - 2 * v;
dyy = m->getResponse(r + 1, c, t) + m->getResponse(r - 1, c, t) - 2 * v;
dss = t->getResponse(r, c) + b->getResponse(r, c, t) - 2 * v;
dxy = ( m->getResponse(r + 1, c + 1, t) - m->getResponse(r + 1, c - 1, t) -
m->getResponse(r - 1, c + 1, t) + m->getResponse(r - 1, c - 1, t) ) / 4.0;
dxs = ( t->getResponse(r, c + 1) - t->getResponse(r, c - 1) -
b->getResponse(r, c + 1, t) + b->getResponse(r, c - 1, t) ) / 4.0;
dys = ( t->getResponse(r + 1, c) - t->getResponse(r - 1, c) -
b->getResponse(r + 1, c, t) + b->getResponse(r - 1, c, t) ) / 4.0;
H = cvCreateMat( 3, 3, CV_64FC1 );
cvmSet( H, 0, 0, dxx );
cvmSet( H, 0, 1, dxy );
cvmSet( H, 0, 2, dxs );
cvmSet( H, 1, 0, dxy );
cvmSet( H, 1, 1, dyy );
cvmSet( H, 1, 2, dys );
cvmSet( H, 2, 0, dxs );
cvmSet( H, 2, 1, dys );
cvmSet( H, 2, 2, dss );
return H;
}
//------------------------------------------------------- | [
"filitchp@gmail.com@0b0f7875-c668-5978-e4a7-07162229f4fe"
] | [
[
[
1,
375
]
]
] |
6929ab2ce015d8087bd1e6a8b18d15dd25dcdb5f | fac8de123987842827a68da1b580f1361926ab67 | /inc/physics/Physics/Collide/Query/Collector/PointCollector/hkpSimpleClosestContactCollector.inl | e5b9288656aa310cae9ee885add001b95c22fb69 | [] | no_license | blockspacer/transporter-game | 23496e1651b3c19f6727712a5652f8e49c45c076 | 083ae2ee48fcab2c7d8a68670a71be4d09954428 | refs/heads/master | 2021-05-31 04:06:07 | 2009-02-19 20:59:59 | 2009-02-19 20:59:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,687 | inl | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-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.
*
*/
void hkpSimpleClosestContactCollector::reset()
{
m_hasHit = false;
m_hitPoint.setDistance( HK_REAL_MAX );
hkpCdPointCollector::reset();
}
hkpSimpleClosestContactCollector::hkpSimpleClosestContactCollector()
{
reset();
}
hkpSimpleClosestContactCollector::~hkpSimpleClosestContactCollector()
{
}
hkBool hkpSimpleClosestContactCollector::hasHit( ) const
{
return m_hasHit;
}
const hkContactPoint& hkpSimpleClosestContactCollector::getHitContact() const
{
return m_hitPoint;
}
/*
* 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,
52
]
]
] |
c5f1c2d4b8eebe4f6260f6520600568be54b1942 | 00c36cc82b03bbf1af30606706891373d01b8dca | /OpenGUI/OpenGUI_Brush_Caching.cpp | eb83d7a2624ce94f01d85b066026eba79ba61970 | [
"BSD-3-Clause"
] | permissive | VB6Hobbyst7/opengui | 8fb84206b419399153e03223e59625757180702f | 640be732a25129a1709873bd528866787476fa1a | refs/heads/master | 2021-12-24 01:29:10 | 2007-01-22 08:00:22 | 2007-01-22 08:00:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,589 | cpp | // OpenGUI (http://opengui.sourceforge.net)
// This source code is released under the BSD License
// See LICENSE.TXT for details
#include "OpenGUI_Brush_Caching.h"
#include "OpenGUI_Exception.h"
#include "OpenGUI_Screen.h"
#include "OpenGUI_Renderer.h"
#include "OpenGUI_TextureManager.h"
namespace OpenGUI {
//############################################################################
Brush_Caching::Brush_Caching( Screen* parentScreen, const FVector2& size ): mScreen( parentScreen ), mDrawSize( size ) {
if ( !mScreen )
OG_THROW( Exception::ERR_INVALIDPARAMS, "Constructor requires a valid pointer to destination Screen", __FUNCTION__ );
if ( !initRTT() )
initMemory();
mHasContent = false;
}
//############################################################################
Brush_Caching::~Brush_Caching() {
if ( isRTT() )
cleanupRTT();
else
cleanupMemory();
}
//############################################################################
void Brush_Caching::emerge( Brush& targetBrush ) {
if ( isRTT() )
emergeRTT( targetBrush );
else
emergeMemory( targetBrush );
}
//############################################################################
const FVector2& Brush_Caching::getPPU_Raw() const {
if ( isRTT() ) {
static FVector2 retVal;
const IVector2& texsize = mRenderTexture->getSize();
retVal.x = ( float )texsize.x / mDrawSize.x;
retVal.y = ( float )texsize.y / mDrawSize.y;
return retVal;
} else {
return mScreen->getPPU();
}
}
//############################################################################
const FVector2& Brush_Caching::getUPI_Raw() const {
return mScreen->getUPI();
}
//############################################################################
void Brush_Caching::appendRenderOperation( RenderOperation &renderOp ) {
mHasContent = true;
if ( isRTT() )
appendRTT( renderOp );
else
appendMemory( renderOp );
}
//############################################################################
void Brush_Caching::onActivate() {
if ( isRTT() )
activateRTT();
else
activateMemory();
}
//############################################################################
void Brush_Caching::onClear() {
mHasContent = false;
if ( isRTT() )
clearRTT();
else
clearMemory();
}
//############################################################################
//############################################################################
//############################################################################
void Brush_Caching::initMemory() {
pushClippingRect( FRect( 0, 0, mDrawSize.x, mDrawSize.y ) );
_pushMarker( this );
}
//############################################################################
void Brush_Caching::cleanupMemory() {
_popMarker( this );
pop();
}
//############################################################################
void Brush_Caching::clearMemory() {
mRenderOpList.clear();
}
//############################################################################
void Brush_Caching::activateMemory() {
/* No special action required */
}
//############################################################################
void Brush_Caching::appendMemory( RenderOperation &renderOp ) {
//!\todo fix me to perform triangle list appending when renderOps are equal
mRenderOpList.push_back( renderOp );
RenderOperation& newRop = mRenderOpList.back();
newRop.triangleList = new TriangleList;
TriangleList& inList = *( renderOp.triangleList );
TriangleList& outList = *( newRop.triangleList );
outList = inList;
}
//############################################################################
void Brush_Caching::emergeMemory( Brush& targetBrush ) {
RenderOperationList::iterator iter, iterend = mRenderOpList.end();
for ( iter = mRenderOpList.begin(); iter != iterend; iter++ ) {
//!\todo Having a copy operation here makes this incredibly slow! This should be removed as part of Brush optimization
// we need to make a copy because addrenderOperation modifies the input directly
RenderOperation &thisRop = ( *iter );
RenderOperation tmp = thisRop;
tmp.triangleList = new TriangleList;
*( tmp.triangleList ) = *( thisRop.triangleList );
targetBrush._addRenderOperation( tmp );
}
}
//############################################################################
//############################################################################
//############################################################################
bool Brush_Caching::initRTT() {
if ( !TextureManager::getSingleton().supportsRenderToTexture() )
return false;
IVector2 texSize;
float xTexSize, yTexSize, xPixelSize, yPixelSize;
xPixelSize = mDrawSize.x * getPPU_Raw().x;
yPixelSize = mDrawSize.y * getPPU_Raw().y;
xTexSize = Math::Ceil( xPixelSize );
yTexSize = Math::Ceil( yPixelSize );
mMaxUV.x = xPixelSize / xTexSize;
mMaxUV.y = yPixelSize / yTexSize;
texSize.x = ( int )( xTexSize );
texSize.y = ( int )( yTexSize );
mRenderTexture = TextureManager::getSingleton().createRenderTexture( texSize );
if ( !mRenderTexture )
return false;
_clear();
return true;
}
//############################################################################
void Brush_Caching::cleanupRTT() {
/* No special action required */
}
//############################################################################
void Brush_Caching::clearRTT() {
Renderer::getSingleton().clearContents();
}
//############################################################################
void Brush_Caching::activateRTT() {
Renderer::getSingleton().selectRenderContext( mRenderTexture.get() );
}
//############################################################################
void Brush_Caching::appendRTT( RenderOperation &renderOp ) {
TriangleList::iterator iter, iterend = renderOp.triangleList->end();
for ( iter = renderOp.triangleList->begin(); iter != iterend; iter++ ) {
Triangle& t = ( *iter );
for ( int i = 0; i < 3; i++ ) {
t.vertex[i].position.x /= mDrawSize.x;
t.vertex[i].position.y /= mDrawSize.y;
}
}
Renderer::getSingleton().doRenderOperation( renderOp );
}
//############################################################################
void Brush_Caching::emergeRTT( Brush& targetBrush ) {
RenderOperation rop;
rop.texture = mRenderTexture.get();
rop.triangleList = new TriangleList;
Triangle tri;
//ul
tri.vertex[0].textureUV = FVector2( 0.0f, mMaxUV.y );
tri.vertex[0].position = FVector2( 0.0f, 0.0f );
//ll
tri.vertex[1].textureUV = FVector2( 0.0f, 0.0f );
tri.vertex[1].position = FVector2( 0.0f, mDrawSize.y );
//ur
tri.vertex[2].textureUV = FVector2( mMaxUV.x, mMaxUV.y );
tri.vertex[2].position = FVector2( mDrawSize.x, 0.0f );
rop.triangleList->push_back( tri );
//ur
tri.vertex[0] = tri.vertex[2];
//ll
// tri.vertex[1].textureUV = FVector2(0.0f,0.0f);
// tri.vertex[1].position = FVector2(0.0f,1.0f);
//lr
tri.vertex[2].textureUV = FVector2( mMaxUV.x, 0.0f );
tri.vertex[2].position = FVector2( mDrawSize.x, mDrawSize.y );
rop.triangleList->push_back( tri );
targetBrush.pushPixelAlignment();
targetBrush._addRenderOperation( rop );
targetBrush.pop();
}
//############################################################################
} // namespace OpenGUI{ | [
"zeroskill@2828181b-9a0d-0410-a8fe-e25cbdd05f59"
] | [
[
[
1,
199
]
]
] |
bb82519d6db8208156b47ccda0dc52529e2e2828 | 2ca3ad74c1b5416b2748353d23710eed63539bb0 | /Src/Lokapala/Operator/UserDataDTO.h | 27a1e4aa4580bd841a0a396e3b67916832cb8aa5 | [] | no_license | sjp38/lokapala | 5ced19e534bd7067aeace0b38ee80b87dfc7faed | dfa51d28845815cfccd39941c802faaec9233a6e | refs/heads/master | 2021-01-15 16:10:23 | 2009-06-03 14:56:50 | 2009-06-03 14:56:50 | 32,124,140 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,097 | h | /**@file UserDataDTO.h
* @brief 유저 개인의 정보를 담는 DTO를 정의한다.
* @author siva
*/
#ifndef USER_DATA_DTO_H
#define USER_DATA_DTO_H
/**@ingroup GroupDAM
* @class CUserDataDTO
* @brief 유저 개인의 정보를 담는다.\n
* @remarks 비밀번호는 모두 단방향 해싱을 거친 값들을 갖는다.\n
* 유저 id는 당방향 해싱 후의 로우레벨 패스워드(학번)다.
*/
class CUserDataDTO
{
public :
/**@brief 여기선 단순히 해당 유저의 low level password를 사용한다. */
CString m_userId;
CString m_name;
CString m_lowLevelPassword;
/**@brief sha1으로 해싱된 digest message를 갖는다. */
CString m_highLevelPassword;
int m_level;
CUserDataDTO(CString a_userId, CString a_name, CString a_lowLevelPassword, CString a_highLevelPassword, int a_level);
CUserDataDTO(CString a_userId, CString a_name, CString a_lowLevelPassword, int a_level, CString a_hashedHighLevelPassword);
CUserDataDTO(){}
~CUserDataDTO(){}
private :
CString HashMessage(CString a_message);
};
#endif
| [
"nilakantha38@b9e76448-5c52-0410-ae0e-a5aea8c5d16c"
] | [
[
[
1,
36
]
]
] |
f66302954c68dfcac6bd6680f9dcdefe7bdfc94b | c2d3b2484afb98a6447dfacfe733b98e8778e0a9 | /src/Images/SEJpegImage.h | 2ce53a7151a7ea711af123fabeb522671c11f25d | [] | no_license | soniccat/3dEngine | cfb73af5c9b25d61dd77e882a31f4a62fbd3f036 | abf1d49a1756fb0217862f829b1ec7877a59eaf4 | refs/heads/master | 2020-05-15 07:07:22 | 2010-03-27 13:05:38 | 2010-03-27 13:05:38 | 469,267 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 285 | h |
#ifndef SEJpegImage_H
#define SEJpegImage_H
#include "SEIncludeLibrary.h"
#include "SEDefinition.h"
#include "SEImage.h"
class SEJpegImage: public SEImage
{
public:
SEJpegImage(void);
~SEJpegImage(void);
void Load( const sechar* file );
};
#endif SEJpegImage_H | [
"soniccat@list.ru",
"ALEX@.(none)"
] | [
[
[
1,
17
]
],
[
[
18,
18
]
]
] |
da615f41049a5a84931e1703b1b602c5156ded62 | 8d2ef01bfa0b7ed29cf840da33e8fa10f2a69076 | /code/Materials/fxLayer.cpp | 8bf0783777201b76a2ea4b918f8295aaf50cc6fe | [] | no_license | BackupTheBerlios/insane | fb4c5c6a933164630352295692bcb3e5163fc4bc | 7dc07a4eb873d39917da61e0a21e6c4c843b2105 | refs/heads/master | 2016-09-05 11:28:43 | 2001-01-31 20:46:38 | 2001-01-31 20:46:38 | 40,043,333 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 372 | cpp | //---------------------------------------------------------------------------
#include "fxLayer.h"
#include "fxTextureMng.h"
//---------------------------------------------------------------------------
fxLayer::~fxLayer(void)
{
fxTextureMng * tm;
for (int i=0; i<nummaps; i++)
{
tm = (fxTextureMng*)maps[i]->TextureMng;
tm->DeleteTexture(maps[i]);
}
}
| [
"josef"
] | [
[
[
1,
14
]
]
] |
fcbbebb87d94c4c85a18ea12cc14967a0b5881db | faacd0003e0c749daea18398b064e16363ea8340 | /3rdparty/phonon/globalconfig.cpp | 52339f06f35301b63da205b122b0d05cbbc0d30c | [] | no_license | yjfcool/lyxcar | 355f7a4df7e4f19fea733d2cd4fee968ffdf65af | 750be6c984de694d7c60b5a515c4eb02c3e8c723 | refs/heads/master | 2016-09-10 10:18:56 | 2009-09-29 06:03:19 | 2009-09-29 06:03:19 | 42,575,701 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,781 | cpp | /* This file is part of the KDE project
Copyright (C) 2006-2008 Matthias Kretz <kretz@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) version 3, or any
later version accepted by the membership of KDE e.V. (or its
successor approved by the membership of KDE e.V.), Trolltech ASA
(or its successors, if any) and the KDE Free Qt Foundation, which shall
act as a proxy defined in Section 6 of version 3 of the license.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "globalconfig_p.h"
#include "factory_p.h"
#include "objectdescription.h"
#include "phonondefs_p.h"
#include "platformplugin.h"
#include "backendinterface.h"
#include "qsettingsgroup_p.h"
#include "phononnamespace_p.h"
#include <QtCore/QList>
#include <QtCore/QVariant>
QT_BEGIN_NAMESPACE
namespace Phonon
{
GlobalConfig::GlobalConfig() : m_config(QLatin1String("kde.org"), QLatin1String("libphonon"))
{
}
GlobalConfig::~GlobalConfig()
{
}
enum WhatToFilter {
FilterAdvancedDevices = 1,
FilterHardwareDevices = 2,
FilterUnavailableDevices = 4
};
static void filter(ObjectDescriptionType type, BackendInterface *backendIface, QList<int> *list, int whatToFilter)
{
QMutableListIterator<int> it(*list);
while (it.hasNext()) {
const QHash<QByteArray, QVariant> properties = backendIface->objectDescriptionProperties(type, it.next());
QVariant var;
if (whatToFilter & FilterAdvancedDevices) {
var = properties.value("isAdvanced");
if (var.isValid() && var.toBool()) {
it.remove();
continue;
}
}
if (whatToFilter & FilterHardwareDevices) {
var = properties.value("isHardwareDevice");
if (var.isValid() && var.toBool()) {
it.remove();
continue;
}
}
if (whatToFilter & FilterUnavailableDevices) {
var = properties.value("available");
if (var.isValid() && !var.toBool()) {
it.remove();
continue;
}
}
}
}
static QList<int> listSortedByConfig(const QSettingsGroup &backendConfig, Phonon::Category category, QList<int> &defaultList)
{
if (defaultList.size() <= 1) {
// nothing to sort
return defaultList;
} else {
// make entries unique
QSet<int> seen;
QMutableListIterator<int> it(defaultList);
while (it.hasNext()) {
if (seen.contains(it.next())) {
it.remove();
} else {
seen.insert(it.value());
}
}
}
QString categoryKey = QLatin1String("Category_") + QString::number(static_cast<int>(category));
if (!backendConfig.hasKey(categoryKey)) {
// no list in config for the given category
categoryKey = QLatin1String("Category_") + QString::number(static_cast<int>(Phonon::NoCategory));
if (!backendConfig.hasKey(categoryKey)) {
// no list in config for NoCategory
return defaultList;
}
}
//Now the list from m_config
QList<int> deviceList = backendConfig.value(categoryKey, QList<int>());
//if there are devices in m_config that the backend doesn't report, remove them from the list
QMutableListIterator<int> i(deviceList);
while (i.hasNext()) {
if (0 == defaultList.removeAll(i.next())) {
i.remove();
}
}
//if the backend reports more devices that are not in m_config append them to the list
deviceList += defaultList;
return deviceList;
}
QList<int> GlobalConfig::audioOutputDeviceListFor(Phonon::Category category, int override) const
{
//The devices need to be stored independently for every backend
const QSettingsGroup backendConfig(&m_config, QLatin1String("AudioOutputDevice")); // + Factory::identifier());
const QSettingsGroup generalGroup(&m_config, QLatin1String("General"));
const bool hideAdvancedDevices = ((override & AdvancedDevicesFromSettings)
? generalGroup.value(QLatin1String("HideAdvancedDevices"), true)
: static_cast<bool>(override & HideAdvancedDevices));
QList<int> defaultList;
#ifndef QT_NO_PHONON_PLATFORMPLUGIN
if (PlatformPlugin *platformPlugin = Factory::platformPlugin()) {
// the platform plugin lists the audio devices for the platform
// this list already is in default order (as defined by the platform plugin)
defaultList = platformPlugin->objectDescriptionIndexes(Phonon::AudioOutputDeviceType);
if (hideAdvancedDevices) {
QMutableListIterator<int> it(defaultList);
while (it.hasNext()) {
AudioOutputDevice objDesc = AudioOutputDevice::fromIndex(it.next());
const QVariant var = objDesc.property("isAdvanced");
if (var.isValid() && var.toBool()) {
it.remove();
}
}
}
}
#endif //QT_NO_PHONON_PLATFORMPLUGIN
// lookup the available devices directly from the backend (mostly for virtual devices)
if (BackendInterface *backendIface = qobject_cast<BackendInterface *>(Factory::backend())) {
// this list already is in default order (as defined by the backend)
QList<int> list = backendIface->objectDescriptionIndexes(Phonon::AudioOutputDeviceType);
if (hideAdvancedDevices || !defaultList.isEmpty() || (override & HideUnavailableDevices)) {
filter(AudioOutputDeviceType, backendIface, &list,
(hideAdvancedDevices ? FilterAdvancedDevices : 0)
// the platform plugin already provided the hardware devices
| (defaultList.isEmpty() ? 0 : FilterHardwareDevices)
| ((override & HideUnavailableDevices) ? FilterUnavailableDevices : 0)
);
}
defaultList += list;
}
return listSortedByConfig(backendConfig, category, defaultList);
}
int GlobalConfig::audioOutputDeviceFor(Phonon::Category category, int override) const
{
QList<int> ret = audioOutputDeviceListFor(category, override);
if (ret.isEmpty())
return -1;
return ret.first();
}
#ifndef QT_NO_PHONON_AUDIOCAPTURE
QList<int> GlobalConfig::audioCaptureDeviceListFor(Phonon::Category category, int override) const
{
//The devices need to be stored independently for every backend
const QSettingsGroup backendConfig(&m_config, QLatin1String("AudioCaptureDevice")); // + Factory::identifier());
const QSettingsGroup generalGroup(&m_config, QLatin1String("General"));
const bool hideAdvancedDevices = ((override & AdvancedDevicesFromSettings)
? generalGroup.value(QLatin1String("HideAdvancedDevices"), true)
: static_cast<bool>(override & HideAdvancedDevices));
QList<int> defaultList;
#ifndef QT_NO_PHONON_PLATFORMPLUGIN
if (PlatformPlugin *platformPlugin = Factory::platformPlugin()) {
// the platform plugin lists the audio devices for the platform
// this list already is in default order (as defined by the platform plugin)
defaultList = platformPlugin->objectDescriptionIndexes(Phonon::AudioCaptureDeviceType);
if (hideAdvancedDevices) {
QMutableListIterator<int> it(defaultList);
while (it.hasNext()) {
AudioCaptureDevice objDesc = AudioCaptureDevice::fromIndex(it.next());
const QVariant var = objDesc.property("isAdvanced");
if (var.isValid() && var.toBool()) {
it.remove();
}
}
}
}
#endif //QT_NO_PHONON_PLATFORMPLUGIN
// lookup the available devices directly from the backend (mostly for virtual devices)
if (BackendInterface *backendIface = qobject_cast<BackendInterface *>(Factory::backend())) {
// this list already is in default order (as defined by the backend)
QList<int> list = backendIface->objectDescriptionIndexes(Phonon::AudioCaptureDeviceType);
if (hideAdvancedDevices || !defaultList.isEmpty() || (override & HideUnavailableDevices)) {
filter(AudioCaptureDeviceType, backendIface, &list,
(hideAdvancedDevices ? FilterAdvancedDevices : 0)
// the platform plugin already provided the hardware devices
| (defaultList.isEmpty() ? 0 : FilterHardwareDevices)
| ((override & HideUnavailableDevices) ? FilterUnavailableDevices : 0)
);
}
defaultList += list;
}
return listSortedByConfig(backendConfig, category, defaultList);
}
int GlobalConfig::audioCaptureDeviceFor(Phonon::Category category, int override) const
{
QList<int> ret = audioCaptureDeviceListFor(category, override);
if (ret.isEmpty())
return -1;
return ret.first();
}
#endif //QT_NO_PHONON_AUDIOCAPTURE
} // namespace Phonon
QT_END_NAMESPACE
| [
"futurelink.vl@9e60f810-e830-11dd-9b7c-bbba4c9295f9"
] | [
[
[
1,
243
]
]
] |
f9bf834195002699dc24cacded70a6d88316b36e | 463c3b62132d215e245a097a921859ecb498f723 | /lib/dlib/sockstreambuf/sockstreambuf_kernel_abstract.h | 04c337e5cfc4677ca8bd1bcda5f70a487012d426 | [
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
] | permissive | athulan/cppagent | 58f078cee55b68c08297acdf04a5424c2308cfdc | 9027ec4e32647e10c38276e12bcfed526a7e27dd | refs/heads/master | 2021-01-18 23:34:34 | 2009-05-05 00:19:54 | 2009-05-05 00:19:54 | 197,038 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,545 | h | // Copyright (C) 2003 Davis E. King (davisking@users.sourceforge.net)
// License: Boost Software License See LICENSE.txt for the full license.
#undef DLIB_SOCKSTREAMBUF_KERNEl_ABSTRACT_
#ifdef DLIB_SOCKSTREAMBUF_KERNEl_ABSTRACT_
#include <iosfwd>
#include <streambuf>
#include "../sockets/sockets_kernel_abstract.h"
namespace dlib
{
// ----------------------------------------------------------------------------------------
class sockstreambuf : public std::streambuf
{
/*!
WHAT THIS OBJECT REPRESENTS
This object represents a stream buffer capable of writing to and
reading from TCP connections.
NOTE:
For a sockstreambuf EOF is when the connection has closed or otherwise
returned some kind of error.
Also note that any data written to the streambuf may be buffered
internally. So if you need to ensure that data is actually sent then you
should flush the stream.
A read operation is guaranteed to block until the number of bytes
requested has arrived on the connection. It will never keep blocking
once enough data has arrived.
THREADING
generally speaking, this object has the same kind of threading
restrictions as a connection object. those being:
- do not try to write to a sockstreambuf from more than one thread
- do not try to read from a sockstreambuf from more than one thread
- you may call shutdown() on the connection object and this will
cause any reading or writing calls to end. To the sockstreambuf it
will appear the same as hitting EOF. (note that EOF for a sockstreambuf
means that the connection has closed)
- it is safe to read from and write to the sockstreambuf at the same time
- it is not safe to try to putback a char and read from the stream from
different threads
!*/
public:
sockstreambuf (
connection* con
);
/*!
requires
- con == a valid connection object
ensures
- *this will read from and write to con
throws
- std::bad_alloc
!*/
sockstreambuf (
const scoped_ptr<connection>& con
);
/*!
requires
- con == a valid connection object
ensures
- *this will read from and write to con
throws
- std::bad_alloc
!*/
~sockstreambuf (
);
/*!
requires
- get_connection() object has not been deleted
ensures
- sockstream buffer is destructed but the connection object will
NOT be closed.
- Any buffered data is flushed to the connection.
!*/
connection* get_connection (
);
/*!
ensures
- returns a pointer to the connection object which this buffer
reads from and writes to
!*/
};
// ----------------------------------------------------------------------------------------
}
#endif // DLIB_SOCKSTREAMBUF_KERNEl_ABSTRACT_
| [
"jimmy@DGJ3X3B1.(none)"
] | [
[
[
1,
98
]
]
] |
edd401d32889e3862267797b16e95a837164fe51 | 547a31c6d098df866be58befd8642ab773b32226 | /vc/DataLogger/PDFLib/except.cpp | 27cc6a57375c6a083714494715dce488274d5291 | [] | no_license | neirons/pythondatalogger | 64634d97eaa724a04707e4837dced51bcf750146 | f1cd1aea4d63407c3d4156ddccd02339dc96dcec | refs/heads/master | 2020-05-17 07:48:33 | 2010-08-08 13:37:33 | 2010-08-08 13:37:33 | 41,642,510 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,555 | cpp | /*---------------------------------------------------------------------------*
| PDFlib - A library for generating PDF on the fly |
+---------------------------------------------------------------------------+
| Copyright (c) 1997-2002 PDFlib GmbH and Thomas Merz. All rights reserved. |
+---------------------------------------------------------------------------+
| This software is NOT in the public domain. It can be used under two |
| substantially different licensing terms: |
| |
| The commercial license is available for a fee, and allows you to |
| - ship a commercial product based on PDFlib |
| - implement commercial Web services with PDFlib |
| - distribute (free or commercial) software when the source code is |
| not made available |
| Details can be found in the file PDFlib-license.pdf. |
| |
| The "Aladdin Free Public License" doesn't require any license fee, |
| and allows you to |
| - develop and distribute PDFlib-based software for which the complete |
| source code is made available |
| - redistribute PDFlib non-commercially under certain conditions |
| - redistribute PDFlib on digital media for a fee if the complete |
| contents of the media are freely redistributable |
| Details can be found in the file aladdin-license.pdf. |
| |
| These conditions extend to ports to other programming languages. |
| PDFlib is distributed with no warranty of any kind. Commercial users, |
| however, will receive warranty and support statements in writing. |
*---------------------------------------------------------------------------*/
/* $Id: except.c,v 1.1.2.6 2002/01/07 18:26:29 tm Exp $ */
#include "stdafx.h"
#include <string.h>
#include "pdflib.h"
#include "except.h"
void pdf_cpp_errorhandler(PDF *p, int type, const char *msg)
{
pdf_err_info *ei = (pdf_err_info *) PDF_get_opaque(p);
ei->type = type;
strcpy(ei->msg, msg);
longjmp(ei->jbuf, 1);
}
| [
"shixiaoping79@5c1c4db6-e7b1-408c-73c2-e61316242a6a"
] | [
[
[
1,
45
]
]
] |
04b93cc58e056ea3f5743b3ceca2fb2fd70adb3c | bd37f7b494990542d0d9d772368239a2d44e3b2d | /server/src/Fantasma.h | 058c49f9c8e55715f19fcf940bd78e53b6eaba8f | [] | no_license | nicosuarez/pacmantaller | b559a61355517383d704f313b8c7648c8674cb4c | 0e0491538ba1f99b4420340238b09ce9a43a3ee5 | refs/heads/master | 2020-12-11 02:11:48 | 2007-12-19 21:49:27 | 2007-12-19 21:49:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,418 | h | ///////////////////////////////////////////////////////////
// Fantasma.h
// Implementation of the Class Fantasma
// Created on: 21-Nov-2007 23:40:19
///////////////////////////////////////////////////////////
#if !defined(EA_E4309321_8E59_4003_BC67_09BA7FB5090B__INCLUDED_)
#define EA_E4309321_8E59_4003_BC67_09BA7FB5090B__INCLUDED_
#include "Personaje.h"
#include "AgregarJugadorOp.h"
/**
* Clase que modela el personaje Fantasma
*/
class Fantasma : public Personaje
{
public:
Fantasma();
Fantasma(Posicion& posicion);
virtual ~Fantasma();
static const int FANTASMA_TYPE = 1;
int GetRol()const;
virtual int GetVelocidad();
bool IsVisible();
void SetVisible(bool visible);
bool operator==( int tipo )const;
double getRadio()const;
int getPuntaje(){return puntaje;};
void irACasa();
/**
* Velocidad inicial constante del fantasma
*/
static const int velocidadInicial=4;
private:
/**
* Radio constante del fantasma
*/
static const double radio=0.25;
/**
* Determina si el fantasma esta en estado invisible que ocurre cuando un pacman
* en estado powerUp como el fantasma. Cuando el mismo se encuentra invisible no
* puede volver entrar en juego hasta que no haya pasado por la casa.
*/
bool visible;
static const int puntaje=10;
};
#endif // !defined(EA_E4309321_8E59_4003_BC67_09BA7FB5090B__INCLUDED_)
| [
"scamjayi@5682bcf5-5c3f-0410-a8fd-ab24993f6fe8",
"nicolas.suarez@5682bcf5-5c3f-0410-a8fd-ab24993f6fe8"
] | [
[
[
1,
23
],
[
25,
28
],
[
30,
56
]
],
[
[
24,
24
],
[
29,
29
]
]
] |
7d1a53817f9bdde4275f829aa08769751d4937fa | 1e976ee65d326c2d9ed11c3235a9f4e2693557cf | /CommonSources/SimpleBrowser.h | 4c83399ebedde3cb723d4a4c779421e1071ce3ff | [] | no_license | outcast1000/Jaangle | 062c7d8d06e058186cb65bdade68a2ad8d5e7e65 | 18feb537068f1f3be6ecaa8a4b663b917c429e3d | refs/heads/master | 2020-04-08 20:04:56 | 2010-12-25 10:44:38 | 2010-12-25 10:44:38 | 19,334,292 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,169 | h | // /*
// *
// * Copyright (C) 2003-2010 Alexandros Economou
// *
// * This file is part of Jaangle (http://www.jaangle.com)
// *
// * This Program is free software; you can redistribute it and/or modify
// * it under the terms of the GNU General Public License as published by
// * the Free Software Foundation; either version 2, or (at your option)
// * any later version.
// *
// * This Program is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU General Public License for more details.
// *
// * You should have received a copy of the GNU General Public License
// * along with GNU Make; see the file COPYING. If not, write to
// * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
// * http://www.gnu.org/copyleft/gpl.html
// *
// */
//
// Change History:
//
// April 6, 2003 - Original release, and article posted at
// http://www.codeproject.com/useritems/SimpleBrowserForMFC.asp
//
// April 12, 2003 - Replaced NavigateString() with Write() and Clear().
// - Added logic to Create() to wait for document ready.
// - Added GetDocument() method.
// - Added notification support.
// - Added post data and headers to BeforeNavigate2 handling.
//
#if !defined(SimpleBrowser_defined)
#define SimpleBrowser_defined
#include "mshtml.h"
class SimpleBrowserNotifier
{
public:
virtual void OnBeforeNavigate(LPCTSTR url) = 0;
virtual void OnDocumentComplete(LPCTSTR url) = 0;
virtual void OnDownloadBegin() = 0;
virtual void OnProgressChange(long progress,long progress_max) = 0;
virtual void OnDownloadComplete() = 0;
virtual void OnNavigateComplete(LPCTSTR url) = 0;
virtual void OnStatusTextChange(LPCTSTR text) = 0;
virtual void OnTitleChange(LPCTSTR text) = 0;
virtual void EnableBackButton(BOOL bEnable) = 0;
virtual void EnableNextButton(BOOL bEnable) = 0;
};
class SimpleBrowser : public CWnd
{
public:
// construction and creation
SimpleBrowser();
virtual ~SimpleBrowser();
// create browser directly
BOOL Create(DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID);
// controls
BOOL Navigate(LPCTSTR URL);
BOOL LoadHTML(LPCTSTR html);
BOOL LoadFromResource(INT resID);
// append string to current document; note that the WebBrowser control tolerates
void Write(LPCTSTR string);
// clear current document
void Clear();
void GoBack();
void GoForward();
void GoHome();
void Refresh();
void Stop();
// start printing contents; uses same 'metacharacters' for header and
// footer as Internet Explorer; see IE Page Setup dialog
void Print(LPCTSTR header = _T("&w&b&b&p"), LPCTSTR footer = _T("&d &t"));
bool GetBusy();
READYSTATE GetReadyState();
CString GetLocationName();
CString GetLocationURL();
// get/set silent property (if true, dialog and message boxes may not be shown)
bool GetSilent();
void PutSilent(bool silent = false);
void SetNotifier(SimpleBrowserNotifier* pNotifier) {m_pNotifier = pNotifier;}
BOOL ExecuteJavascript(LPCTSTR script);
BOOL GetElementText(LPCTSTR elementName, LPTSTR bf, UINT bfLen);
// get document interface; returns NULL
// if interface is not available
// (which is the case if you've navigated to
// something that's NOT an HTML document,
// like an Excel spreadsheet, which the
// WebBrowser control is perfectly willing
// to host)
IWebBrowser2* GetBrowser() {return m_pBrowser;}
IHTMLDocument2* GetDocument();
protected:
virtual void PostNcDestroy();
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
DECLARE_MESSAGE_MAP()
DECLARE_EVENTSINK_MAP()
//-----------------Events
// called before navigation begins; URL is destination, frame
// is frame name ("" if none), post_data is HTTP POST data (NULL if none),
// and headers are HTTP headers sent to server;
// return true to cancel navigation, false to continue
// navigation to document complete; URL is location
private:
void OnBeforeNavigate2(LPDISPATCH lpDisp,
VARIANT FAR *URL,
VARIANT FAR *Flags,
VARIANT FAR *TargetFrameName,
VARIANT FAR *PostData,
VARIANT FAR *Headers,
VARIANT_BOOL *Cancel);
void ReleaseObjects();
void OnDocumentComplete(LPDISPATCH lpDisp,VARIANT FAR* URL);
void OnDownloadBegin();
void OnProgressChange(long progress,long progress_max);
void OnDownloadComplete();
void OnNavigateComplete2(LPDISPATCH lpDisp,VARIANT FAR* URL);
void OnStatusTextChange(BSTR text);
void OnTitleChange(BSTR bstrText);
void OnCommandStateChange(long command, VARIANT_BOOL Enable);
public:
IHTMLDocument3* GetDocument3();
private:
CWnd* m_pBrowserWnd; // browser window
IWebBrowser2* m_pBrowser; // browser control
IDispatch* m_pBrowserDispatch; // browser control dispatch interface
SimpleBrowserNotifier* m_pNotifier;
};
#endif
| [
"outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678"
] | [
[
[
1,
151
]
]
] |
1a597863f74aa33411a21e97db5230875db23c5d | b14d5833a79518a40d302e5eb40ed5da193cf1b2 | /cpp/extern/xercesc++/2.6.0/src/xercesc/framework/XMLAttDef.cpp | 533a48828a27e1f929042899622394b44ba848ac | [
"Apache-2.0"
] | permissive | andyburke/bitflood | dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf | fca6c0b635d07da4e6c7fbfa032921c827a981d6 | refs/heads/master | 2016-09-10 02:14:35 | 2011-11-17 09:51:49 | 2011-11-17 09:51:49 | 2,794,411 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,781 | cpp | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* $Id: XMLAttDef.cpp,v 1.9 2004/09/08 13:55:58 peiyongz Exp $
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/framework/XMLAttDef.hpp>
#include <xercesc/util/ArrayIndexOutOfBoundsException.hpp>
#include <xercesc/util/XMLUni.hpp>
#include <xercesc/util/OutOfMemoryException.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Local const data
//
// gAttTypeStrings
// A list of strings which are used to map attribute type numbers to
// attribute type names.
//
// gDefAttTypesStrings
// A list of strings which are used to map default attribute type
// numbers to default attribute type names.
// ---------------------------------------------------------------------------
const XMLCh* const gAttTypeStrings[XMLAttDef::AttTypes_Count] =
{
XMLUni::fgCDATAString
, XMLUni::fgIDString
, XMLUni::fgIDRefString
, XMLUni::fgIDRefsString
, XMLUni::fgEntityString
, XMLUni::fgEntitiesString
, XMLUni::fgNmTokenString
, XMLUni::fgNmTokensString
, XMLUni::fgNotationString
, XMLUni::fgEnumerationString
, XMLUni::fgCDATAString
, XMLUni::fgCDATAString
, XMLUni::fgCDATAString
, XMLUni::fgCDATAString
};
const XMLCh* const gDefAttTypeStrings[XMLAttDef::DefAttTypes_Count] =
{
XMLUni::fgDefaultString
, XMLUni::fgFixedString
, XMLUni::fgRequiredString
, XMLUni::fgImpliedString
, XMLUni::fgImpliedString
, XMLUni::fgImpliedString
, XMLUni::fgImpliedString
, XMLUni::fgImpliedString
, XMLUni::fgImpliedString
};
// ---------------------------------------------------------------------------
// XMLAttDef: Public, static data members
// ---------------------------------------------------------------------------
const unsigned int XMLAttDef::fgInvalidAttrId = 0xFFFFFFFE;
// ---------------------------------------------------------------------------
// XMLAttDef: Public, static methods
// ---------------------------------------------------------------------------
const XMLCh* XMLAttDef::getAttTypeString(const XMLAttDef::AttTypes attrType
, MemoryManager* const manager)
{
// Check for an invalid attribute type and return a null
if ((attrType < AttTypes_Min) || (attrType > AttTypes_Max))
ThrowXMLwithMemMgr(ArrayIndexOutOfBoundsException, XMLExcepts::AttDef_BadAttType, manager);
return gAttTypeStrings[attrType];
}
const XMLCh* XMLAttDef::getDefAttTypeString(const XMLAttDef::DefAttTypes attrType
, MemoryManager* const manager)
{
// Check for an invalid attribute type and return a null
if ((attrType < DefAttTypes_Min) || (attrType > DefAttTypes_Max))
ThrowXMLwithMemMgr(ArrayIndexOutOfBoundsException, XMLExcepts::AttDef_BadDefAttType, manager);
return gDefAttTypeStrings[attrType];
}
// ---------------------------------------------------------------------------
// XMLAttDef: Destructor
// ---------------------------------------------------------------------------
XMLAttDef::~XMLAttDef()
{
cleanUp();
}
// ---------------------------------------------------------------------------
// XMLAttDef: Hidden constructors
// ---------------------------------------------------------------------------
XMLAttDef::XMLAttDef( const XMLAttDef::AttTypes type
, const XMLAttDef::DefAttTypes defType
, MemoryManager* const manager) :
fDefaultType(defType)
, fType(type)
, fCreateReason(XMLAttDef::NoReason)
, fProvided(false)
, fExternalAttribute(false)
, fId(XMLAttDef::fgInvalidAttrId)
, fValue(0)
, fEnumeration(0)
, fMemoryManager(manager)
{
}
XMLAttDef::XMLAttDef( const XMLCh* const attrValue
, const XMLAttDef::AttTypes type
, const XMLAttDef::DefAttTypes defType
, const XMLCh* const enumValues
, MemoryManager* const manager) :
fDefaultType(defType)
, fType(type)
, fCreateReason(XMLAttDef::NoReason)
, fProvided(false)
, fExternalAttribute(false)
, fId(XMLAttDef::fgInvalidAttrId)
, fValue(0)
, fEnumeration(0)
, fMemoryManager(manager)
{
try
{
fValue = XMLString::replicate(attrValue, fMemoryManager);
fEnumeration = XMLString::replicate(enumValues, fMemoryManager);
}
catch(const OutOfMemoryException&)
{
throw;
}
catch(...)
{
cleanUp();
}
}
// ---------------------------------------------------------------------------
// XMLAttDef: Private helper methods
// ---------------------------------------------------------------------------
void XMLAttDef::cleanUp()
{
if (fEnumeration)
fMemoryManager->deallocate(fEnumeration);
if (fValue)
fMemoryManager->deallocate(fValue);
}
/***
* Support for Serialization/De-serialization
***/
IMPL_XSERIALIZABLE_NOCREATE(XMLAttDef)
void XMLAttDef::serialize(XSerializeEngine& serEng)
{
if (serEng.isStoring())
{
serEng<<(int)fDefaultType;
serEng<<(int)fType;
serEng<<(int)fCreateReason;
serEng<<fProvided;
serEng<<fExternalAttribute;
serEng<<fId;
serEng.writeString(fValue);
serEng.writeString(fEnumeration);
}
else
{
int i;
serEng>>i;
fDefaultType = (DefAttTypes) i;
serEng>>i;
fType = (AttTypes)i;
serEng>>i;
fCreateReason = (CreateReasons)i;
serEng>>fProvided;
serEng>>fExternalAttribute;
serEng>>fId;
serEng.readString(fValue);
serEng.readString(fEnumeration);
}
}
XERCES_CPP_NAMESPACE_END
| [
"aburke@bitflood.org"
] | [
[
[
1,
220
]
]
] |
e93382f17a8e406e8c729429843d13889ed5c290 | 259319e5fe06036972de9036f0078b8f5faba86e | /records/StudentRecord.cpp | 9b9eb617920366a7c7d62e8a3f5d9ba327189155 | [] | no_license | ferromera/sancus | 652d05fc2a28987ac37309b9293cbd7f92448186 | 0f5d9b2e0bf1b6e099ade36edcf75e9640788589 | refs/heads/master | 2021-01-01 16:56:39 | 2011-12-04 01:01:55 | 2011-12-04 01:01:55 | 32,414,828 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,683 | cpp | #include "StudentRecord.h"
#include <cstring>
using namespace std;
StudentRecord::StudentRecord():idNumber_(0),name_(string()){
key_=new Key;
buffer= new char[260];
}
StudentRecord::StudentRecord(const StudentRecord & sr):
idNumber_(sr.idNumber_),name_(sr.name_){
key_=new Key((uint16_t) idNumber_);
buffer= new char[260];
}
StudentRecord::StudentRecord(char ** input){
key_= new Key();
buffer= new char[260];
read(input);
}
StudentRecord::StudentRecord(uint16_t idNumber,const string & name)
:idNumber_(idNumber),name_(name){
key_= new Key(idNumber);
buffer= new char[260];
}
const StudentRecord::Key & StudentRecord::getKey()const{
//Key * k= dynamic_cast<Key *>(key_);
//return (*k);
return * ( (StudentRecord::Key *) key_ );
}
void StudentRecord::setKey(const StudentRecord::Key & k){
//const Key & ak=dynamic_cast<const Key &>(k);
delete key_;
key_=new Key(k);
idNumber_=k.getKey();
}
void StudentRecord::setKey(int16_t k){
delete key_;
key_=new Key(k);
idNumber_=k;
}
void StudentRecord::read(char ** input){
char * buffCurr=buffer;
memcpy(buffCurr,*input,2);
memcpy(&idNumber_,*input,2);
delete key_;
key_=new Key(idNumber_);
(*input)+=2;
buffCurr+=2;
uint8_t nameSize;
memcpy(buffCurr,*input,1);
memcpy(&nameSize,*input,1);
buffCurr++;
(*input)++;
char * c_str=new char[nameSize+1];
memcpy(buffCurr,*input,nameSize);
memcpy(c_str,*input,nameSize);
(*input)+=nameSize;
c_str[nameSize]='\0';
name_=c_str;
delete c_str;
}
void StudentRecord::write(char ** output){
update();
memcpy(*output,buffer,size());
(*output)+=size();
}
void StudentRecord::update(){
//write back to the buffer
char * buffCurr=buffer;
memcpy(buffCurr,&idNumber_,2);
buffCurr+=2;
uint8_t nameSize=name_.size();
memcpy(buffCurr,&nameSize,1);
buffCurr++;
memcpy(buffCurr,name_.c_str(),nameSize);
}
unsigned int StudentRecord::size()const{
return sizeof(idNumber_)+1+name_.size();
}
uint16_t StudentRecord::idNumber()const{
return idNumber_;
}
const string & StudentRecord::name()const{
return name_;
}
void StudentRecord::idNumber(uint16_t p){
setKey(p);
}
void StudentRecord::name(const string & n){
name_=n;
}
StudentRecord& StudentRecord::operator=(const StudentRecord& rec){
if(this==&rec)
return *this;
idNumber_=rec.idNumber_;
name_=rec.name_;
key_=new Key((uint16_t) idNumber_);
buffer= new char[260];
return *this;
}
StudentRecord::~StudentRecord(){
delete buffer;
}
| [
"FernandoRomeraFerrio@gmail.com@b06ae71c-7d8b-23a7-3f8b-8cb8ce3c93c2"
] | [
[
[
1,
118
]
]
] |
4d0b53a482c90dd265b437118ba4418b10d65bdf | 10c14a95421b63a71c7c99adf73e305608c391bf | /gui/painting/qdrawhelper_sse3dnow.cpp | 325071e7a296c7ba53ffb82c3cae7beafa0c42b8 | [] | no_license | eaglezzb/wtlcontrols | 73fccea541c6ef1f6db5600f5f7349f5c5236daa | 61b7fce28df1efe4a1d90c0678ec863b1fd7c81c | refs/heads/master | 2021-01-22 13:47:19 | 2009-05-19 10:58:42 | 2009-05-19 10:58:42 | 33,811,815 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,216 | cpp | /****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include <private/qdrawhelper_x86_p.h>
#if defined(QT_HAVE_3DNOW) && defined(QT_HAVE_SSE)
#include <private/qdrawhelper_sse_p.h>
#include <mm3dnow.h>
QT_BEGIN_NAMESPACE
struct QSSE3DNOWIntrinsics : public QSSEIntrinsics
{
static inline void end() {
_m_femms();
}
};
CompositionFunctionSolid qt_functionForModeSolid_SSE3DNOW[numCompositionFunctions] = {
comp_func_solid_SourceOver<QSSE3DNOWIntrinsics>,
comp_func_solid_DestinationOver<QSSE3DNOWIntrinsics>,
comp_func_solid_Clear<QSSE3DNOWIntrinsics>,
comp_func_solid_Source<QSSE3DNOWIntrinsics>,
0,
comp_func_solid_SourceIn<QSSE3DNOWIntrinsics>,
comp_func_solid_DestinationIn<QSSE3DNOWIntrinsics>,
comp_func_solid_SourceOut<QSSE3DNOWIntrinsics>,
comp_func_solid_DestinationOut<QSSE3DNOWIntrinsics>,
comp_func_solid_SourceAtop<QSSE3DNOWIntrinsics>,
comp_func_solid_DestinationAtop<QSSE3DNOWIntrinsics>,
comp_func_solid_XOR<QSSE3DNOWIntrinsics>,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // svg 1.2 modes
rasterop_solid_SourceOrDestination<QSSE3DNOWIntrinsics>,
rasterop_solid_SourceAndDestination<QSSE3DNOWIntrinsics>,
rasterop_solid_SourceXorDestination<QSSE3DNOWIntrinsics>,
rasterop_solid_NotSourceAndNotDestination<QSSE3DNOWIntrinsics>,
rasterop_solid_NotSourceOrNotDestination<QSSE3DNOWIntrinsics>,
rasterop_solid_NotSourceXorDestination<QSSE3DNOWIntrinsics>,
rasterop_solid_NotSource<QSSE3DNOWIntrinsics>,
rasterop_solid_NotSourceAndDestination<QSSE3DNOWIntrinsics>,
rasterop_solid_SourceAndNotDestination<QSSE3DNOWIntrinsics>
};
CompositionFunction qt_functionForMode_SSE3DNOW[numCompositionFunctions] = {
comp_func_SourceOver<QSSE3DNOWIntrinsics>,
comp_func_DestinationOver<QSSE3DNOWIntrinsics>,
comp_func_Clear<QSSE3DNOWIntrinsics>,
comp_func_Source<QSSE3DNOWIntrinsics>,
0,
comp_func_SourceIn<QSSE3DNOWIntrinsics>,
comp_func_DestinationIn<QSSE3DNOWIntrinsics>,
comp_func_SourceOut<QSSE3DNOWIntrinsics>,
comp_func_DestinationOut<QSSE3DNOWIntrinsics>,
comp_func_SourceAtop<QSSE3DNOWIntrinsics>,
comp_func_DestinationAtop<QSSE3DNOWIntrinsics>,
comp_func_XOR<QSSE3DNOWIntrinsics>
};
void qt_blend_color_argb_sse3dnow(int count, const QSpan *spans, void *userData)
{
qt_blend_color_argb_x86<QSSE3DNOWIntrinsics>(count, spans, userData,
(CompositionFunctionSolid*)qt_functionForModeSolid_SSE3DNOW);
}
void qt_memfill32_sse3dnow(quint32 *dest, quint32 value, int count)
{
return qt_memfill32_sse_template<QSSE3DNOWIntrinsics>(dest, value, count);
}
void qt_bitmapblit16_sse3dnow(QRasterBuffer *rasterBuffer, int x, int y,
quint32 color,
const uchar *src,
int width, int height, int stride)
{
return qt_bitmapblit16_sse_template<QSSE3DNOWIntrinsics>(rasterBuffer, x,y,
color, src, width,
height, stride);
}
QT_END_NAMESPACE
#endif // QT_HAVE_3DNOW && QT_HAVE_SSE
| [
"zhangyinquan@0feb242a-2539-11de-a0d7-251e5865a1c7"
] | [
[
[
1,
122
]
]
] |
df1cd67a6aed169bac0c2437f708188d8e88f2fc | fcf03ead74f6dc103ec3b07ffe3bce81c820660d | /Base/FileServer/Attributes/Attributes.cpp | f3ab61e8876a8658c67a48fd3bf89d02c2a184ec | [] | no_license | huellif/symbian-example | 72097c9aec6d45d555a79a30d576dddc04a65a16 | 56f6c5e67a3d37961408fc51188d46d49bddcfdc | refs/heads/master | 2016-09-06 12:49:32 | 2010-10-14 06:31:20 | 2010-10-14 06:31:20 | 38,062,421 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,396 | cpp | // Attributes.cpp
//
// Copyright (C) Symbian Software Ltd 2000-2005. All rights reserved.
// This code creates several files and directories inside
// the private directory on drive C:
// i.e. the directory "C:\private\0FFFFF03."
//
// Note that no special capabilities are needed provided all file
// operations are directed at files that lie within
// the private directory. This is the case with this example.
//
// Before the program terminates,
// all files and directories created will be deleted.
#include <f32file.h>
#include "CommonFramework.h"
LOCAL_D RFs fsSession;
// example functions
void DoDirectoryAttribsL();
void PrintDirectoryLists();
void DeleteAll();
// utility functions
void FormatEntry(TDes& aBuffer, const TEntry& aEntry);
void FormatAtt(TDes& aBuffer, const TUint aValue);
void MakeSmallFile(const TDesC& aFileName);
void WaitForKey()
{
_LIT(KMessage,"Press any key to continue\n");
console->Printf(KMessage);
console->Getch();
}
LOCAL_C void doExampleL()
{
// connect to file server
User::LeaveIfError(fsSession.Connect());
// create the private directory
// on drive C:
// i.e. "C:\private\0FFFFF03\"
// Note that the number 0FFFFF03 is the
// process security id taken from the 2nd UID
// specified in the mmp file.
fsSession.CreatePrivatePath(EDriveC);
// Set the session path to
// this private directory on drive C:
fsSession.SetSessionToPrivate(EDriveC);
DoDirectoryAttribsL();
WaitForKey();
PrintDirectoryLists();
WaitForKey();
DeleteAll();
// close session with file server
fsSession.Close();
}
void DoDirectoryAttribsL()
{
// Define text to be used for display at the console.
_LIT(KAttsMsg,"\nAttributes and entry details\n");
_LIT(KDateString,"%D%M%Y%/0%1%/1%2%/2%3%/3 %-B%:0%J%:1%T%:2%S%:3%+B");
_LIT(KDateMsg,"Using Entry():\nModification time of %S is %S\n");
_LIT(KSizeMsg,"Size = %d bytes\n");
_LIT(KBuffer,"%S");
_LIT(KEntryMsg,"Using Modified():\nModification time of %S is %S\n");
_LIT(KAttMsg,"Using Att():\n%S");
// Define subdirectory name and the file name to be used.
_LIT(KSubDirName,"f32examp\\");
_LIT(KFileName,"tmpfile.txt");
// Create a file.
// Display its entry details, its modification time
// and its attributes.
// Then change some attributes and print them again.
console->Printf(KAttsMsg);
// When referring to a directory rather than a file,
// a backslash must be appended to the path.
TFileName thePath;
fsSession.PrivatePath(thePath);
thePath.Append(KSubDirName);
// Make the directory
TInt err=fsSession.MkDir(thePath);
if (err!=KErrAlreadyExists) // Don't leave if it already exists
User::LeaveIfError(err);
// Create a file in "private\0ffffff03\f32examp\ "
thePath.Append(KFileName);
MakeSmallFile(thePath);
// Get entry details for file and print them
TEntry entry;
User::LeaveIfError(fsSession.Entry(thePath,entry));
TBuf<30> dateString;
entry.iModified.FormatL(dateString,KDateString);
// Modification date and time = time of file's creation
console->Printf(KDateMsg,&entry.iName,&dateString);
// Print size of file
console->Printf(KSizeMsg,entry.iSize);
TBuf<80> buffer;
FormatEntry(buffer,entry); // Archive attribute should be set
console->Printf(KBuffer,&buffer);
buffer.Zero();
// get the entry details using Att() and Modified()
TTime time;
User::LeaveIfError(fsSession.Modified(thePath,time));
time.FormatL(dateString,KDateString);
// Modification date and time = time of file's creation
console->Printf(KEntryMsg,&entry.iName,&dateString);
TUint value;
User::LeaveIfError(fsSession.Att(thePath,value));
FormatAtt(buffer,value); // get and print file attributes
console->Printf(KAttMsg,&buffer);
buffer.Zero();
// Change entry details using SetEntry() to clear archive
User::LeaveIfError(fsSession.SetEntry(thePath,time,
NULL,KEntryAttArchive));
}
void PrintDirectoryLists()
{
// Define text to be used for display at the console.
_LIT(KListMsg,"\nDirectory listings\n");
_LIT(KListMsg2,"\nDirectories and files:\n");
_LIT(KDirList,"%S\n");
_LIT(KDirs,"\nDirectories:\n");
_LIT(KFilesSizes,"\nFiles and sizes:\n");
_LIT(KBytes," %d bytes\n");
_LIT(KNewLine,"\n");
// Define subdirectory names and the file names to be used here.
_LIT(KDir1,"f32examp\\tmpdir1\\");
_LIT(KDir2,"f32examp\\tmpdir2\\");
_LIT(KFile2,"f32examp\\tmpfile2.txt");
_LIT(KDirName,"f32examp\\*");
// Create some directories and files
// in private"\f32examp\."
// List them using GetDir(), then list files and
// directories in separate lists.
console->Printf(KListMsg);
TFileName thePrivatePath;
fsSession.PrivatePath(thePrivatePath);
TFileName thePath;
TInt err;
// Create private\0fffff03\f32examp\tmpdir1
thePath = thePrivatePath;
thePath.Append(KDir1);
err=fsSession.MkDir(thePath);
if (err!=KErrAlreadyExists)
User::LeaveIfError(err); // Don't leave if it already exists
// Create "private\0fffff03\f32examp\tmpdir2"
thePath = thePrivatePath;
thePath.Append(KDir2);
err=fsSession.MkDir(thePath);
if (err!=KErrAlreadyExists)
User::LeaveIfError(err); // Don't leave if it already exists
// Create "private\0ffffff03\f32examp\tmpfile2.txt"
thePath = thePrivatePath;
thePath.Append(KFile2);
MakeSmallFile(thePath);
// Now list all files and directories in "\f32examp\"
//
// in alphabetical order.
thePath = thePrivatePath;
thePath.Append(KDirName);
CDir* dirList;
//err = fsSession.GetDir(thePath,KEntryAttMaskSupported,ESortByName,dirList);
User::LeaveIfError(fsSession.GetDir(thePath,KEntryAttMaskSupported,ESortByName,dirList));
console->Printf(KListMsg2);
TInt i;
for (i=0;i<dirList->Count();i++)
console->Printf(KDirList,&(*dirList)[i].iName);
delete dirList;
// List the files and directories in \f32examp\ separately
CDir* fileList;
User::LeaveIfError(fsSession.GetDir(thePath,KEntryAttNormal,ESortByName,fileList,dirList));
console->Printf(KDirs);
for (i=0;i<dirList->Count();i++)
console->Printf(KDirList,&(*dirList)[i].iName);
console->Printf(KFilesSizes);
for (i=0;i<fileList->Count();i++)
{
console->Printf(KDirList,&(*fileList)[i].iName);
console->Printf(KBytes,(*fileList)[i].iSize);
}
console->Printf(KNewLine);
delete dirList;
delete fileList;
}
void DeleteAll()
// Delete all the files and directories which have been created
{
// Define descriptor constants using the _LIT macro
_LIT(KDeleteMsg,"\nDeleteAll()\n");
_LIT(KFile2,"f32examp\\tmpfile2.txt");
_LIT(KDir1,"f32examp\\tmpdir1\\");
_LIT(KDir2,"f32examp\\tmpdir2\\");
_LIT(KFile1,"f32examp\\tmpfile.txt");
_LIT(KTopDir,"f32examp\\");
console->Printf(KDeleteMsg);
TFileName thePrivatePath;
fsSession.PrivatePath(thePrivatePath);
TFileName thePath;
thePath = thePrivatePath;
thePath.Append(KFile2);
User::LeaveIfError(fsSession.Delete(thePath));
thePath = thePrivatePath;
thePath.Append(KDir1);
User::LeaveIfError(fsSession.RmDir(thePath));
thePath = thePrivatePath;
thePath.Append(KDir2);
User::LeaveIfError(fsSession.RmDir(thePath));
thePath = thePrivatePath;
thePath.Append(KFile1);
User::LeaveIfError(fsSession.Delete(thePath));
thePath = thePrivatePath;
thePath.Append(KTopDir);
User::LeaveIfError(fsSession.RmDir(thePath));
}
void MakeSmallFile(const TDesC& aFileName)
{
_LIT8(KFileData,"Some data");
RFile file;
User::LeaveIfError(file.Replace(fsSession,aFileName,EFileWrite));
User::LeaveIfError(file.Write(KFileData));
User::LeaveIfError(file.Flush()); // Commit data
file.Close(); // close file having finished with it
}
void FormatEntry(TDes& aBuffer, const TEntry& aEntry)
{
_LIT(KEntryDetails,"Entry details: ");
_LIT(KReadOnly," Read-only");
_LIT(KHidden," Hidden");
_LIT(KSystem," System");
_LIT(KDirectory," Directory");
_LIT(KArchive," Archive");
_LIT(KNewLIne,"\n");
aBuffer.Append(KEntryDetails);
if(aEntry.IsReadOnly())
aBuffer.Append(KReadOnly);
if(aEntry.IsHidden())
aBuffer.Append(KHidden);
if(aEntry.IsSystem())
aBuffer.Append(KSystem);
if(aEntry.IsDir())
aBuffer.Append(KDirectory);
if(aEntry.IsArchive())
aBuffer.Append(KArchive);
aBuffer.Append(KNewLIne);
}
void FormatAtt(TDes& aBuffer, const TUint aValue)
{
_LIT(KAttsMsg,"Attributes set are:");
_LIT(KNormal," Normal");
_LIT(KReadOnly," Read-only");
_LIT(KHidden," Hidden");
_LIT(KSystem," System");
_LIT(KVolume," Volume");
_LIT(KDir," Directory");
_LIT(KArchive," Archive");
_LIT(KNewLine,"\n");
aBuffer.Append(KAttsMsg);
if (aValue & KEntryAttNormal)
{
aBuffer.Append(KNormal);
return;
}
if (aValue & KEntryAttReadOnly)
aBuffer.Append(KReadOnly);
if (aValue & KEntryAttHidden)
aBuffer.Append(KHidden);
if (aValue & KEntryAttSystem)
aBuffer.Append(KSystem);
if (aValue & KEntryAttVolume)
aBuffer.Append(KVolume);
if (aValue & KEntryAttDir)
aBuffer.Append(KDir);
if (aValue & KEntryAttArchive)
aBuffer.Append(KArchive);
aBuffer.Append(KNewLine);
}
| [
"liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca"
] | [
[
[
1,
321
]
]
] |
3b23f675a82d35706ba8b2400b39b40fee517ab6 | 2112057af069a78e75adfd244a3f5b224fbab321 | /branches/ref1/src-root/src/common/world/client_zone.cpp | 0f6076b8fb3308af47100ffb40c7b2d1bfa35067 | [] | no_license | blockspacer/ireon | 120bde79e39fb107c961697985a1fe4cb309bd81 | a89fa30b369a0b21661c992da2c4ec1087aac312 | refs/heads/master | 2023-04-15 00:22:02 | 2010-01-07 20:31:07 | 2010-01-07 20:31:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,274 | cpp | /**
* @file client_zone.cpp
* Client-side zone class
*/
/* Copyright (C) 2005 ireon.org developers council
* $Id$
* 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., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include "stdafx.h"
#include "world/client_zone.h"
#include "world/client_static.h"
#include "resource/resource_manager.h"
CClientZone::CClientZone()
{
};
CClientZone::~CClientZone()
{
};
bool CClientZone::load(const String& resourceName)
{
CLog::instance()->log(CLog::msgFlagResources,CLog::msgLvlInfo,"Loading zone from '%s'.\n",resourceName.c_str());
DataPtr dPtr = CResourceManager::instance()->load(resourceName);
if( !dPtr )
{
CLog::instance()->log(CLog::msgLvlError,"Error loading zone: resource not found.\n",resourceName.c_str());
return false;
}
TiXmlDocument doc;
std::stringstream buf;
buf.write(dPtr->data(),dPtr->size());
buf >> doc;
if (doc.Error())
{
CLog::instance()->log(CLog::msgFlagResources, CLog::msgLvlError, _("Error loading zone: XML parser returned an error: %s\n"), doc.ErrorDesc());
return false;
}
TiXmlNode* root = doc.FirstChild();
while( root && root->Type() == TiXmlNode::DECLARATION )
root = root->NextSibling();
if( !root || root->Type() != TiXmlNode::ELEMENT || strcmp(root->ToElement()->Value(),"Zone") )
{
CLog::instance()->log(CLog::msgFlagResources, CLog::msgLvlError, _("Error loading zone: resource isn't zone. %s\n"),root->Value());
return false;
};
TiXmlNode* option;
for( option = root->FirstChild(); option; option = option->NextSibling() )
if( !processOption(option) )
{
CLog::instance()->log(CLog::msgFlagResources, CLog::msgLvlError, _("Error loading zone: error in file near '%s'.\n"),option->Value());
return false;
};
return true;
};
bool CClientZone::processOption(TiXmlNode* option)
{
if( !option )
return false;
if( !option->Type() == TiXmlNode::ELEMENT )
return true;
const char* name = option->Value();
if( !strcmp(name,"Static") )
{
if( !processStatic(option) )
return false;
}
else
{
return false;
}
return true;
};
bool CClientZone::processStatic(TiXmlNode *node)
{
TiXmlAttribute* attr = node->ToElement()->FirstAttribute();
StaticPtr st;
while( attr )
{
if( !attr || !attr->Name() || !attr->Value() )
return false;
if( !st )
{
if( !strcmp(attr->Name(),"Name") )
{
StaticPrototypePtr prot = I_WORLD->getStaticPrototype(attr->Value());
if( prot )
st.reset( new CClientStaticObject(prot) );
} else if( !strcmp(attr->Name(),"Id") )
{
StaticPrototypePtr prot = I_WORLD->getStaticPrototype(StringConverter::parseLong(attr->Value()));
if( prot )
st.reset( new CClientStaticObject(prot) );
}
} else
{
if( !strcmp(attr->Name(),"Position") )
{
StringVector vec = StringConverter::parseStringVector(attr->Value());
if( vec.size() < 3 )
return false;
Vector3 pos;
pos.x = StringConverter::parseReal(vec[0]);
pos.y = StringConverter::parseReal(vec[1]);
pos.z = StringConverter::parseReal(vec[2]);
st->setPosition(pos);
} else if( !strcmp(attr->Name(),"Rotation") )
{
Radian rot;
rot = Radian(StringConverter::parseReal(attr->Value()));
st->setRotation(rot);
}
}
attr = attr->Next();
}
if( st)
{
m_statics.push_back(st);
I_WORLD->addStatic(st);
}
return true;
};
void CClientZone::unload()
{
for( std::vector<StaticPtr>::iterator it = m_statics.begin(); it != m_statics.end(); ++it )
I_WORLD->removeStatic(*it);
}; | [
"psavichev@gmail.com"
] | [
[
[
1,
153
]
]
] |
d2dbc4eff802e6133b9134acea2263f9d13b7d11 | 7b4c786d4258ce4421b1e7bcca9011d4eeb50083 | /_统计专用/C++Primer中文版(第4版)/第一次-代码集合-20090414/第四章 数组和指针/20090321_习题4.33_把int型vector对象复制给int型数组.cpp | 34d2f7c15f3d670793fbd37093933f52a6fc303f | [] | no_license | lzq123218/guoyishi-works | dbfa42a3e2d3bd4a984a5681e4335814657551ef | 4e78c8f2e902589c3f06387374024225f52e5a92 | refs/heads/master | 2021-12-04 11:11:32 | 2011-05-30 14:12:43 | 2011-05-30 14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 570 | cpp | //20090321 Care of DELETE
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int ival;
vector<int> ivec;
cout << "Enter some integers(Ctrl+Z to end):" << endl;
while (cin >> ival) {
ivec.push_back(ival);
}
cin.clear();
int *parr = new int[ivec.size()];
size_t ix;
vector<int>::iterator iter = ivec.begin();
for (ix = 0; ix != ivec.size(); ++ix) {
parr[ix] = *iter++;
cout << parr[ix] << " ";
if ((ix + 1) % 10 == 0)
cout << endl;
}
cout << endl;
delete [] parr; //IMPORTANT
return 0;
}
| [
"baicaibang@70501136-4834-11de-8855-c187e5f49513"
] | [
[
[
1,
32
]
]
] |
fdb80b0ba63efa6ef34f0e160a899dbbb67b1370 | 69aab86a56c78cdfb51ab19b8f6a71274fb69fba | /Code/inc/HUD/GameLabel.h | c02b1a30360757d07577132c67accdb068352cba | [
"BSD-3-Clause"
] | permissive | zc5872061/wonderland | 89882b6062b4a2d467553fc9d6da790f4df59a18 | b6e0153eaa65a53abdee2b97e1289a3252b966f1 | refs/heads/master | 2021-01-25 10:44:13 | 2011-08-11 20:12:36 | 2011-08-11 20:12:36 | 38,088,714 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,847 | h | /*
* GameLabel.h
*
* Created on: 2011-01-10
* Author: artur.m
*/
#ifndef GAMELABEL_H_
#define GAMELABEL_H_
#include "GameControl.h"
#include "GamePanel.h"
#include "MathHelper.h"
#include "GameBitmap.h"
#include "GameCommon.h"
#include <string>
#include <vector>
#include <memory>
class GamePanel;
class GameLabel : public GameControl
{
public:
virtual std::string getType() const { return "GameLabel"; }
static shared_ptr<GameLabel> spawn(const Rectangle& rect);
virtual ~GameLabel();
void setText(const std::string& text);
const std::string& getText() const;
void setTextVerticalAlignment(Common::VerticalAlignment align);
Common::VerticalAlignment getTextVerticalAlignment() const { return m_vAlign; }
void setTextHorizontalAlignment(Common::HorizontalAlignment align);
Common::HorizontalAlignment getTextHorizontalAlignment() const { return m_hAlign; }
void setTextAlignment(Common::HorizontalAlignment hAlign, Common::VerticalAlignment vAlign);
void setTextColor(unsigned char r, unsigned char g, unsigned char b);
Common::Color getTextColor() const { return m_color; }
int getTextSize() const { return m_fontSize; }
void setFontSize(int size);
private:
GameLabel(const Rectangle& bounds);
void initialize();
void cleanOldText();
// Creates the bitmap which holds the rendered by FreeType text
void createBitmap();
// Updates the color of the text in the rendered bitmap
void updateColor();
private:
static int s_instances;
std::string m_text;
std::string m_bitmapId;
Common::HorizontalAlignment m_hAlign;
Common::VerticalAlignment m_vAlign;
Common::Color m_color;
int m_fontSize;
};
#endif /* GAMELABEL_H_ */
| [
"Artur.S.Mazurek@gmail.com"
] | [
[
[
1,
71
]
]
] |
de9eb9dd125bc1464592f2ac90125446b7ae25c2 | 1c9f99b2b2e3835038aba7ec0abc3a228e24a558 | /Projects/elastix/elastix_sources_v4/src/Core/ComponentBaseClasses/elxOptimizerBase.h | f5617047dcd070e9ab57a8abe062058b756ed5f5 | [] | no_license | mijc/Diploma | 95fa1b04801ba9afb6493b24b53383d0fbd00b33 | bae131ed74f1b344b219c0ffe0fffcd90306aeb8 | refs/heads/master | 2021-01-18 13:57:42 | 2011-02-15 14:19:49 | 2011-02-15 14:19:49 | 1,369,569 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,880 | 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 __elxOptimizerBase_h
#define __elxOptimizerBase_h
/** Needed for the macros */
#include "elxMacro.h"
#include "elxBaseComponentSE.h"
#include "itkOptimizer.h"
namespace elastix
{
using namespace itk;
/**
* \class OptimizerBase
* \brief This class is the elastix base class for all Optimizers.
*
* This class contains all the common functionality for Optimizers.
*
* The parameters used in this class are:
* \parameter NewSamplesEveryIteration: if this flag is set to "true" some
* optimizers ask the metric to select a new set of spatial samples in
* every iteration. This, if used in combination with the correct optimizer (such as the
* StandardGradientDescent), and ImageSampler (Random, RandomCoordinate, or RandomSparseMask),
* allows for a very low number of spatial samples (around 2000), even with large images
* and transforms with a large number of parameters.\n
* Choose one from {"true", "false"} for every resolution.\n
* example: <tt>(NewSamplesEveryIteration "true" "true" "true")</tt> \n
* Default is "false" for every resolution.\n
*
* \ingroup Optimizers
* \ingroup ComponentBaseClasses
*/
template <class TElastix>
class OptimizerBase : public BaseComponentSE<TElastix>
{
public:
/** Standard ITK-stuff. */
typedef OptimizerBase Self;
typedef BaseComponentSE<TElastix> Superclass;
/** Run-time type information (and related methods). */
itkTypeMacro( OptimizerBase, BaseComponentSE );
/** Typedefs inherited from Elastix. */
typedef typename Superclass::ElastixType ElastixType;
typedef typename Superclass::ElastixPointer ElastixPointer;
typedef typename Superclass::ConfigurationType ConfigurationType;
typedef typename Superclass::ConfigurationPointer ConfigurationPointer;
typedef typename Superclass::RegistrationType RegistrationType;
typedef typename Superclass::RegistrationPointer RegistrationPointer;
/** ITKBaseType. */
typedef itk::Optimizer ITKBaseType;
/** Typedef needed for the SetCurrentPositionPublic function. */
typedef typename ITKBaseType::ParametersType ParametersType;
/** Cast to ITKBaseType. */
virtual ITKBaseType * GetAsITKBaseType(void)
{
return dynamic_cast<ITKBaseType *>(this);
}
/** Cast to ITKBaseType, to use in const functions. */
virtual const ITKBaseType * GetAsITKBaseType(void) const
{
return dynamic_cast<const ITKBaseType *>(this);
}
/** Add empty SetCurrentPositionPublic, so this function is known in every inherited class. */
virtual void SetCurrentPositionPublic( const ParametersType ¶m );
/** Execute stuff before each new pyramid resolution:
* \li Find out if new samples are used every new iteration in this resolution.
*/
virtual void BeforeEachResolutionBase();
/** Method that sets the scales defined by a sinus
* scale[i] = amplitude^( sin(i/nrofparam*2pi*frequency) )
*/
virtual void SetSinusScales(double amplitude, double frequency,
unsigned long numberOfParameters);
protected:
/** The constructor. */
OptimizerBase();
/** The destructor. */
virtual ~OptimizerBase() {}
/** Force the metric to base its computation on a new subset of image samples.
* Not every metric may have implemented this.
*/
virtual void SelectNewSamples(void);
/** Check whether the user asked to select new samples every iteration. */
virtual const bool GetNewSamplesEveryIteration(void) const;
private:
/** The private constructor. */
OptimizerBase( const Self& ); // purposely not implemented
/** The private copy constructor. */
void operator=( const Self& ); // purposely not implemented
/** Member variable to store the user preference for using new
* samples each iteration.
*/
bool m_NewSamplesEveryIteration;
}; // end class OptimizerBase
} // end namespace elastix
#ifndef ITK_MANUAL_INSTANTIATION
#include "elxOptimizerBase.hxx"
#endif
#endif // end #ifndef __elxOptimizerBase_h
| [
"maik.stille@gmail.com"
] | [
[
[
1,
140
]
]
] |
9cb4f059ed372a0a4f3041cea31f267f1da36885 | a4bb94cfe9c0bee937a6ec584e10f6fe126372ff | /Drivers/Video/Console/Console.cpp | 61c3ebf8a02b2cd6a3ad948192fecf6816fce2aa | [] | no_license | MatiasNAmendola/magneto | 564d0bdb3534d4b7118e74cc8b50601afaad10a0 | 33bc34a49a34923908883775f94eb266be5af0f9 | refs/heads/master | 2020-04-05 23:36:22 | 2009-07-04 09:14:01 | 2009-07-04 09:14:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 48,172 | cpp | /*
* Module Name: Console
* File: Silver\Console\Console.cpp
*
*/
#include "Drivers\Video\Console\Console.h"
#if !defined ( __CONSOLE_CPP_ )
#define __CONSOLE_CPP_
char Console::is_console;
unsigned int Console::last_result;
unsigned char * Console::vid_mem;
unsigned int Console::curr_x, Console::curr_y, Console::c_maxx, Console::c_maxy, Console::textattrib, Console::fgcolor, Console::bgcolor;
const char * CONSOLE_ID = "CONSOLE";
Console console;
unsigned char _40x25_text[] =
{
/* MISC */
0x67,
/* SEQ */
0x03, 0x08, 0x03, 0x00, 0x02,
/* CRTC */
0x2D, 0x27, 0x28, 0x90, 0x2B, 0xA0, 0xBF, 0x1F,
0x00, 0x4F, 0x0D, 0x0E, 0x00, 0x00, 0x00, 0xA0,
0x9C, 0x8E, 0x8F, 0x14, 0x1F, 0x96, 0xB9, 0xA3,
0xFF,
/* GC */
0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0E, 0x00,
0xFF,
/* AC */
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x14, 0x07,
0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
0x0C, 0x00, 0x0F, 0x08, 0x00,
};
unsigned char _40x50_text[] =
{
/* MISC */
0x67,
/* SEQ */
0x03, 0x08, 0x03, 0x00, 0x02,
/* CRTC */
0x2D, 0x27, 0x28, 0x90, 0x2B, 0xA0, 0xBF, 0x1F,
0x00, 0x47, 0x06, 0x07, 0x00, 0x00, 0x04, 0x60,
0x9C, 0x8E, 0x8F, 0x14, 0x1F, 0x96, 0xB9, 0xA3,
0xFF,
/* GC */
0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0E, 0x00,
0xFF,
/* AC */
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x14, 0x07,
0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
0x0C, 0x00, 0x0F, 0x08, 0x00,
};
unsigned char _80x25_text[] =
{
/* MISC */
0x67,
/* SEQ */
0x03, 0x00, 0x03, 0x00, 0x02,
/* CRTC */
0x5F, 0x4F, 0x50, 0x82, 0x55, 0x81, 0xBF, 0x1F,
0x00, 0x4F, 0x0D, 0x0E, 0x00, 0x00, 0x00, 0x50,
0x9C, 0x0E, 0x8F, 0x28, 0x1F, 0x96, 0xB9, 0xA3,
0xFF,
/* GC */
0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0E, 0x00,
0xFF,
/* AC */
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x14, 0x07,
0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
0x0C, 0x00, 0x0F, 0x08, 0x00
};
unsigned char _80x50_text[] =
{
/* MISC */
0x67,
/* SEQ */
0x03, 0x00, 0x03, 0x00, 0x02,
/* CRTC */
0x5F, 0x4F, 0x50, 0x82, 0x55, 0x81, 0xBF, 0x1F,
0x00, 0x47, 0x06, 0x07, 0x00, 0x00, 0x01, 0x40,
0x9C, 0x8E, 0x8F, 0x28, 0x1F, 0x96, 0xB9, 0xA3,
0xFF,
/* GC */
0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0E, 0x00,
0xFF,
/* AC */
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x14, 0x07,
0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
0x0C, 0x00, 0x0F, 0x08, 0x00,
};
unsigned char _90x30_text[] =
{
/* MISC */
0xE7,
/* SEQ */
0x03, 0x01, 0x03, 0x00, 0x02,
/* CRTC */
0x6B, 0x59, 0x5A, 0x82, 0x60, 0x8D, 0x0B, 0x3E,
0x00, 0x4F, 0x0D, 0x0E, 0x00, 0x00, 0x00, 0x00,
0xEA, 0x0C, 0xDF, 0x2D, 0x10, 0xE8, 0x05, 0xA3,
0xFF,
/* GC */
0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0E, 0x00,
0xFF,
/* AC */
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x14, 0x07,
0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
0x0C, 0x00, 0x0F, 0x08, 0x00,
};
unsigned char _90x60_text[] =
{
/* MISC */
0xE7,
/* SEQ */
0x03, 0x01, 0x03, 0x00, 0x02,
/* CRTC */
0x6B, 0x59, 0x5A, 0x82, 0x60, 0x8D, 0x0B, 0x3E,
0x00, 0x47, 0x06, 0x07, 0x00, 0x00, 0x00, 0x00,
0xEA, 0x0C, 0xDF, 0x2D, 0x08, 0xE8, 0x05, 0xA3,
0xFF,
/* GC */
0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0E, 0x00,
0xFF,
/* AC */
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x14, 0x07,
0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
0x0C, 0x00, 0x0F, 0x08, 0x00,
};
unsigned char g_8x8_font[2048] =
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x7E, 0x81, 0xA5, 0x81, 0xBD, 0x99, 0x81, 0x7E,
0x7E, 0xFF, 0xDB, 0xFF, 0xC3, 0xE7, 0xFF, 0x7E,
0x6C, 0xFE, 0xFE, 0xFE, 0x7C, 0x38, 0x10, 0x00,
0x10, 0x38, 0x7C, 0xFE, 0x7C, 0x38, 0x10, 0x00,
0x38, 0x7C, 0x38, 0xFE, 0xFE, 0x92, 0x10, 0x7C,
0x00, 0x10, 0x38, 0x7C, 0xFE, 0x7C, 0x38, 0x7C,
0x00, 0x00, 0x18, 0x3C, 0x3C, 0x18, 0x00, 0x00,
0xFF, 0xFF, 0xE7, 0xC3, 0xC3, 0xE7, 0xFF, 0xFF,
0x00, 0x3C, 0x66, 0x42, 0x42, 0x66, 0x3C, 0x00,
0xFF, 0xC3, 0x99, 0xBD, 0xBD, 0x99, 0xC3, 0xFF,
0x0F, 0x07, 0x0F, 0x7D, 0xCC, 0xCC, 0xCC, 0x78,
0x3C, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x7E, 0x18,
0x3F, 0x33, 0x3F, 0x30, 0x30, 0x70, 0xF0, 0xE0,
0x7F, 0x63, 0x7F, 0x63, 0x63, 0x67, 0xE6, 0xC0,
0x99, 0x5A, 0x3C, 0xE7, 0xE7, 0x3C, 0x5A, 0x99,
0x80, 0xE0, 0xF8, 0xFE, 0xF8, 0xE0, 0x80, 0x00,
0x02, 0x0E, 0x3E, 0xFE, 0x3E, 0x0E, 0x02, 0x00,
0x18, 0x3C, 0x7E, 0x18, 0x18, 0x7E, 0x3C, 0x18,
0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x66, 0x00,
0x7F, 0xDB, 0xDB, 0x7B, 0x1B, 0x1B, 0x1B, 0x00,
0x3E, 0x63, 0x38, 0x6C, 0x6C, 0x38, 0x86, 0xFC,
0x00, 0x00, 0x00, 0x00, 0x7E, 0x7E, 0x7E, 0x00,
0x18, 0x3C, 0x7E, 0x18, 0x7E, 0x3C, 0x18, 0xFF,
0x18, 0x3C, 0x7E, 0x18, 0x18, 0x18, 0x18, 0x00,
0x18, 0x18, 0x18, 0x18, 0x7E, 0x3C, 0x18, 0x00,
0x00, 0x18, 0x0C, 0xFE, 0x0C, 0x18, 0x00, 0x00,
0x00, 0x30, 0x60, 0xFE, 0x60, 0x30, 0x00, 0x00,
0x00, 0x00, 0xC0, 0xC0, 0xC0, 0xFE, 0x00, 0x00,
0x00, 0x24, 0x66, 0xFF, 0x66, 0x24, 0x00, 0x00,
0x00, 0x18, 0x3C, 0x7E, 0xFF, 0xFF, 0x00, 0x00,
0x00, 0xFF, 0xFF, 0x7E, 0x3C, 0x18, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x18, 0x3C, 0x3C, 0x18, 0x18, 0x00, 0x18, 0x00,
0x6C, 0x6C, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00,
0x6C, 0x6C, 0xFE, 0x6C, 0xFE, 0x6C, 0x6C, 0x00,
0x18, 0x7E, 0xC0, 0x7C, 0x06, 0xFC, 0x18, 0x00,
0x00, 0xC6, 0xCC, 0x18, 0x30, 0x66, 0xC6, 0x00,
0x38, 0x6C, 0x38, 0x76, 0xDC, 0xCC, 0x76, 0x00,
0x30, 0x30, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00,
0x18, 0x30, 0x60, 0x60, 0x60, 0x30, 0x18, 0x00,
0x60, 0x30, 0x18, 0x18, 0x18, 0x30, 0x60, 0x00,
0x00, 0x66, 0x3C, 0xFF, 0x3C, 0x66, 0x00, 0x00,
0x00, 0x18, 0x18, 0x7E, 0x18, 0x18, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x30,
0x00, 0x00, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00,
0x06, 0x0C, 0x18, 0x30, 0x60, 0xC0, 0x80, 0x00,
0x7C, 0xCE, 0xDE, 0xF6, 0xE6, 0xC6, 0x7C, 0x00,
0x30, 0x70, 0x30, 0x30, 0x30, 0x30, 0xFC, 0x00,
0x78, 0xCC, 0x0C, 0x38, 0x60, 0xCC, 0xFC, 0x00,
0x78, 0xCC, 0x0C, 0x38, 0x0C, 0xCC, 0x78, 0x00,
0x1C, 0x3C, 0x6C, 0xCC, 0xFE, 0x0C, 0x1E, 0x00,
0xFC, 0xC0, 0xF8, 0x0C, 0x0C, 0xCC, 0x78, 0x00,
0x38, 0x60, 0xC0, 0xF8, 0xCC, 0xCC, 0x78, 0x00,
0xFC, 0xCC, 0x0C, 0x18, 0x30, 0x30, 0x30, 0x00,
0x78, 0xCC, 0xCC, 0x78, 0xCC, 0xCC, 0x78, 0x00,
0x78, 0xCC, 0xCC, 0x7C, 0x0C, 0x18, 0x70, 0x00,
0x00, 0x18, 0x18, 0x00, 0x00, 0x18, 0x18, 0x00,
0x00, 0x18, 0x18, 0x00, 0x00, 0x18, 0x18, 0x30,
0x18, 0x30, 0x60, 0xC0, 0x60, 0x30, 0x18, 0x00,
0x00, 0x00, 0x7E, 0x00, 0x7E, 0x00, 0x00, 0x00,
0x60, 0x30, 0x18, 0x0C, 0x18, 0x30, 0x60, 0x00,
0x3C, 0x66, 0x0C, 0x18, 0x18, 0x00, 0x18, 0x00,
0x7C, 0xC6, 0xDE, 0xDE, 0xDC, 0xC0, 0x7C, 0x00,
0x30, 0x78, 0xCC, 0xCC, 0xFC, 0xCC, 0xCC, 0x00,
0xFC, 0x66, 0x66, 0x7C, 0x66, 0x66, 0xFC, 0x00,
0x3C, 0x66, 0xC0, 0xC0, 0xC0, 0x66, 0x3C, 0x00,
0xF8, 0x6C, 0x66, 0x66, 0x66, 0x6C, 0xF8, 0x00,
0xFE, 0x62, 0x68, 0x78, 0x68, 0x62, 0xFE, 0x00,
0xFE, 0x62, 0x68, 0x78, 0x68, 0x60, 0xF0, 0x00,
0x3C, 0x66, 0xC0, 0xC0, 0xCE, 0x66, 0x3A, 0x00,
0xCC, 0xCC, 0xCC, 0xFC, 0xCC, 0xCC, 0xCC, 0x00,
0x78, 0x30, 0x30, 0x30, 0x30, 0x30, 0x78, 0x00,
0x1E, 0x0C, 0x0C, 0x0C, 0xCC, 0xCC, 0x78, 0x00,
0xE6, 0x66, 0x6C, 0x78, 0x6C, 0x66, 0xE6, 0x00,
0xF0, 0x60, 0x60, 0x60, 0x62, 0x66, 0xFE, 0x00,
0xC6, 0xEE, 0xFE, 0xFE, 0xD6, 0xC6, 0xC6, 0x00,
0xC6, 0xE6, 0xF6, 0xDE, 0xCE, 0xC6, 0xC6, 0x00,
0x38, 0x6C, 0xC6, 0xC6, 0xC6, 0x6C, 0x38, 0x00,
0xFC, 0x66, 0x66, 0x7C, 0x60, 0x60, 0xF0, 0x00,
0x7C, 0xC6, 0xC6, 0xC6, 0xD6, 0x7C, 0x0E, 0x00,
0xFC, 0x66, 0x66, 0x7C, 0x6C, 0x66, 0xE6, 0x00,
0x7C, 0xC6, 0xE0, 0x78, 0x0E, 0xC6, 0x7C, 0x00,
0xFC, 0xB4, 0x30, 0x30, 0x30, 0x30, 0x78, 0x00,
0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xFC, 0x00,
0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x78, 0x30, 0x00,
0xC6, 0xC6, 0xC6, 0xC6, 0xD6, 0xFE, 0x6C, 0x00,
0xC6, 0xC6, 0x6C, 0x38, 0x6C, 0xC6, 0xC6, 0x00,
0xCC, 0xCC, 0xCC, 0x78, 0x30, 0x30, 0x78, 0x00,
0xFE, 0xC6, 0x8C, 0x18, 0x32, 0x66, 0xFE, 0x00,
0x78, 0x60, 0x60, 0x60, 0x60, 0x60, 0x78, 0x00,
0xC0, 0x60, 0x30, 0x18, 0x0C, 0x06, 0x02, 0x00,
0x78, 0x18, 0x18, 0x18, 0x18, 0x18, 0x78, 0x00,
0x10, 0x38, 0x6C, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF,
0x30, 0x30, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0x76, 0x00,
0xE0, 0x60, 0x60, 0x7C, 0x66, 0x66, 0xDC, 0x00,
0x00, 0x00, 0x78, 0xCC, 0xC0, 0xCC, 0x78, 0x00,
0x1C, 0x0C, 0x0C, 0x7C, 0xCC, 0xCC, 0x76, 0x00,
0x00, 0x00, 0x78, 0xCC, 0xFC, 0xC0, 0x78, 0x00,
0x38, 0x6C, 0x64, 0xF0, 0x60, 0x60, 0xF0, 0x00,
0x00, 0x00, 0x76, 0xCC, 0xCC, 0x7C, 0x0C, 0xF8,
0xE0, 0x60, 0x6C, 0x76, 0x66, 0x66, 0xE6, 0x00,
0x30, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00,
0x0C, 0x00, 0x1C, 0x0C, 0x0C, 0xCC, 0xCC, 0x78,
0xE0, 0x60, 0x66, 0x6C, 0x78, 0x6C, 0xE6, 0x00,
0x70, 0x30, 0x30, 0x30, 0x30, 0x30, 0x78, 0x00,
0x00, 0x00, 0xCC, 0xFE, 0xFE, 0xD6, 0xD6, 0x00,
0x00, 0x00, 0xB8, 0xCC, 0xCC, 0xCC, 0xCC, 0x00,
0x00, 0x00, 0x78, 0xCC, 0xCC, 0xCC, 0x78, 0x00,
0x00, 0x00, 0xDC, 0x66, 0x66, 0x7C, 0x60, 0xF0,
0x00, 0x00, 0x76, 0xCC, 0xCC, 0x7C, 0x0C, 0x1E,
0x00, 0x00, 0xDC, 0x76, 0x62, 0x60, 0xF0, 0x00,
0x00, 0x00, 0x7C, 0xC0, 0x70, 0x1C, 0xF8, 0x00,
0x10, 0x30, 0xFC, 0x30, 0x30, 0x34, 0x18, 0x00,
0x00, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00,
0x00, 0x00, 0xCC, 0xCC, 0xCC, 0x78, 0x30, 0x00,
0x00, 0x00, 0xC6, 0xC6, 0xD6, 0xFE, 0x6C, 0x00,
0x00, 0x00, 0xC6, 0x6C, 0x38, 0x6C, 0xC6, 0x00,
0x00, 0x00, 0xCC, 0xCC, 0xCC, 0x7C, 0x0C, 0xF8,
0x00, 0x00, 0xFC, 0x98, 0x30, 0x64, 0xFC, 0x00,
0x1C, 0x30, 0x30, 0xE0, 0x30, 0x30, 0x1C, 0x00,
0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x00,
0xE0, 0x30, 0x30, 0x1C, 0x30, 0x30, 0xE0, 0x00,
0x76, 0xDC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x10, 0x38, 0x6C, 0xC6, 0xC6, 0xFE, 0x00,
0x7C, 0xC6, 0xC0, 0xC6, 0x7C, 0x0C, 0x06, 0x7C,
0x00, 0xCC, 0x00, 0xCC, 0xCC, 0xCC, 0x76, 0x00,
0x1C, 0x00, 0x78, 0xCC, 0xFC, 0xC0, 0x78, 0x00,
0x7E, 0x81, 0x3C, 0x06, 0x3E, 0x66, 0x3B, 0x00,
0xCC, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0x76, 0x00,
0xE0, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0x76, 0x00,
0x30, 0x30, 0x78, 0x0C, 0x7C, 0xCC, 0x76, 0x00,
0x00, 0x00, 0x7C, 0xC6, 0xC0, 0x78, 0x0C, 0x38,
0x7E, 0x81, 0x3C, 0x66, 0x7E, 0x60, 0x3C, 0x00,
0xCC, 0x00, 0x78, 0xCC, 0xFC, 0xC0, 0x78, 0x00,
0xE0, 0x00, 0x78, 0xCC, 0xFC, 0xC0, 0x78, 0x00,
0xCC, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00,
0x7C, 0x82, 0x38, 0x18, 0x18, 0x18, 0x3C, 0x00,
0xE0, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00,
0xC6, 0x10, 0x7C, 0xC6, 0xFE, 0xC6, 0xC6, 0x00,
0x30, 0x30, 0x00, 0x78, 0xCC, 0xFC, 0xCC, 0x00,
0x1C, 0x00, 0xFC, 0x60, 0x78, 0x60, 0xFC, 0x00,
0x00, 0x00, 0x7F, 0x0C, 0x7F, 0xCC, 0x7F, 0x00,
0x3E, 0x6C, 0xCC, 0xFE, 0xCC, 0xCC, 0xCE, 0x00,
0x78, 0x84, 0x00, 0x78, 0xCC, 0xCC, 0x78, 0x00,
0x00, 0xCC, 0x00, 0x78, 0xCC, 0xCC, 0x78, 0x00,
0x00, 0xE0, 0x00, 0x78, 0xCC, 0xCC, 0x78, 0x00,
0x78, 0x84, 0x00, 0xCC, 0xCC, 0xCC, 0x76, 0x00,
0x00, 0xE0, 0x00, 0xCC, 0xCC, 0xCC, 0x76, 0x00,
0x00, 0xCC, 0x00, 0xCC, 0xCC, 0x7C, 0x0C, 0xF8,
0xC3, 0x18, 0x3C, 0x66, 0x66, 0x3C, 0x18, 0x00,
0xCC, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0x78, 0x00,
0x18, 0x18, 0x7E, 0xC0, 0xC0, 0x7E, 0x18, 0x18,
0x38, 0x6C, 0x64, 0xF0, 0x60, 0xE6, 0xFC, 0x00,
0xCC, 0xCC, 0x78, 0x30, 0xFC, 0x30, 0xFC, 0x30,
0xF8, 0xCC, 0xCC, 0xFA, 0xC6, 0xCF, 0xC6, 0xC3,
0x0E, 0x1B, 0x18, 0x3C, 0x18, 0x18, 0xD8, 0x70,
0x1C, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0x76, 0x00,
0x38, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00,
0x00, 0x1C, 0x00, 0x78, 0xCC, 0xCC, 0x78, 0x00,
0x00, 0x1C, 0x00, 0xCC, 0xCC, 0xCC, 0x76, 0x00,
0x00, 0xF8, 0x00, 0xB8, 0xCC, 0xCC, 0xCC, 0x00,
0xFC, 0x00, 0xCC, 0xEC, 0xFC, 0xDC, 0xCC, 0x00,
0x3C, 0x6C, 0x6C, 0x3E, 0x00, 0x7E, 0x00, 0x00,
0x38, 0x6C, 0x6C, 0x38, 0x00, 0x7C, 0x00, 0x00,
0x18, 0x00, 0x18, 0x18, 0x30, 0x66, 0x3C, 0x00,
0x00, 0x00, 0x00, 0xFC, 0xC0, 0xC0, 0x00, 0x00,
0x00, 0x00, 0x00, 0xFC, 0x0C, 0x0C, 0x00, 0x00,
0xC6, 0xCC, 0xD8, 0x36, 0x6B, 0xC2, 0x84, 0x0F,
0xC3, 0xC6, 0xCC, 0xDB, 0x37, 0x6D, 0xCF, 0x03,
0x18, 0x00, 0x18, 0x18, 0x3C, 0x3C, 0x18, 0x00,
0x00, 0x33, 0x66, 0xCC, 0x66, 0x33, 0x00, 0x00,
0x00, 0xCC, 0x66, 0x33, 0x66, 0xCC, 0x00, 0x00,
0x22, 0x88, 0x22, 0x88, 0x22, 0x88, 0x22, 0x88,
0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA,
0xDB, 0xF6, 0xDB, 0x6F, 0xDB, 0x7E, 0xD7, 0xED,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0xF8, 0x18, 0x18, 0x18,
0x18, 0x18, 0xF8, 0x18, 0xF8, 0x18, 0x18, 0x18,
0x36, 0x36, 0x36, 0x36, 0xF6, 0x36, 0x36, 0x36,
0x00, 0x00, 0x00, 0x00, 0xFE, 0x36, 0x36, 0x36,
0x00, 0x00, 0xF8, 0x18, 0xF8, 0x18, 0x18, 0x18,
0x36, 0x36, 0xF6, 0x06, 0xF6, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x00, 0x00, 0xFE, 0x06, 0xF6, 0x36, 0x36, 0x36,
0x36, 0x36, 0xF6, 0x06, 0xFE, 0x00, 0x00, 0x00,
0x36, 0x36, 0x36, 0x36, 0xFE, 0x00, 0x00, 0x00,
0x18, 0x18, 0xF8, 0x18, 0xF8, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xF8, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x1F, 0x00, 0x00, 0x00,
0x18, 0x18, 0x18, 0x18, 0xFF, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xFF, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x1F, 0x18, 0x18, 0x18,
0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00,
0x18, 0x18, 0x18, 0x18, 0xFF, 0x18, 0x18, 0x18,
0x18, 0x18, 0x1F, 0x18, 0x1F, 0x18, 0x18, 0x18,
0x36, 0x36, 0x36, 0x36, 0x37, 0x36, 0x36, 0x36,
0x36, 0x36, 0x37, 0x30, 0x3F, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3F, 0x30, 0x37, 0x36, 0x36, 0x36,
0x36, 0x36, 0xF7, 0x00, 0xFF, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFF, 0x00, 0xF7, 0x36, 0x36, 0x36,
0x36, 0x36, 0x37, 0x30, 0x37, 0x36, 0x36, 0x36,
0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00,
0x36, 0x36, 0xF7, 0x00, 0xF7, 0x36, 0x36, 0x36,
0x18, 0x18, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00,
0x36, 0x36, 0x36, 0x36, 0xFF, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFF, 0x00, 0xFF, 0x18, 0x18, 0x18,
0x00, 0x00, 0x00, 0x00, 0xFF, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x3F, 0x00, 0x00, 0x00,
0x18, 0x18, 0x1F, 0x18, 0x1F, 0x00, 0x00, 0x00,
0x00, 0x00, 0x1F, 0x18, 0x1F, 0x18, 0x18, 0x18,
0x00, 0x00, 0x00, 0x00, 0x3F, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0xFF, 0x36, 0x36, 0x36,
0x18, 0x18, 0xFF, 0x18, 0xFF, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0xF8, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x1F, 0x18, 0x18, 0x18,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F,
0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x76, 0xDC, 0xC8, 0xDC, 0x76, 0x00,
0x00, 0x78, 0xCC, 0xF8, 0xCC, 0xF8, 0xC0, 0xC0,
0x00, 0xFC, 0xCC, 0xC0, 0xC0, 0xC0, 0xC0, 0x00,
0x00, 0x00, 0xFE, 0x6C, 0x6C, 0x6C, 0x6C, 0x00,
0xFC, 0xCC, 0x60, 0x30, 0x60, 0xCC, 0xFC, 0x00,
0x00, 0x00, 0x7E, 0xD8, 0xD8, 0xD8, 0x70, 0x00,
0x00, 0x66, 0x66, 0x66, 0x66, 0x7C, 0x60, 0xC0,
0x00, 0x76, 0xDC, 0x18, 0x18, 0x18, 0x18, 0x00,
0xFC, 0x30, 0x78, 0xCC, 0xCC, 0x78, 0x30, 0xFC,
0x38, 0x6C, 0xC6, 0xFE, 0xC6, 0x6C, 0x38, 0x00,
0x38, 0x6C, 0xC6, 0xC6, 0x6C, 0x6C, 0xEE, 0x00,
0x1C, 0x30, 0x18, 0x7C, 0xCC, 0xCC, 0x78, 0x00,
0x00, 0x00, 0x7E, 0xDB, 0xDB, 0x7E, 0x00, 0x00,
0x06, 0x0C, 0x7E, 0xDB, 0xDB, 0x7E, 0x60, 0xC0,
0x38, 0x60, 0xC0, 0xF8, 0xC0, 0x60, 0x38, 0x00,
0x78, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x00,
0x00, 0x7E, 0x00, 0x7E, 0x00, 0x7E, 0x00, 0x00,
0x18, 0x18, 0x7E, 0x18, 0x18, 0x00, 0x7E, 0x00,
0x60, 0x30, 0x18, 0x30, 0x60, 0x00, 0xFC, 0x00,
0x18, 0x30, 0x60, 0x30, 0x18, 0x00, 0xFC, 0x00,
0x0E, 0x1B, 0x1B, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0xD8, 0xD8, 0x70,
0x18, 0x18, 0x00, 0x7E, 0x00, 0x18, 0x18, 0x00,
0x00, 0x76, 0xDC, 0x00, 0x76, 0xDC, 0x00, 0x00,
0x38, 0x6C, 0x6C, 0x38, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00,
0x0F, 0x0C, 0x0C, 0x0C, 0xEC, 0x6C, 0x3C, 0x1C,
0x58, 0x6C, 0x6C, 0x6C, 0x6C, 0x00, 0x00, 0x00,
0x70, 0x98, 0x30, 0x60, 0xF8, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3C, 0x3C, 0x3C, 0x3C, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
unsigned char g_8x16_font[4096] =
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7E, 0x81, 0xA5, 0x81, 0x81, 0xBD, 0x99, 0x81, 0x81, 0x7E, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7E, 0xFF, 0xDB, 0xFF, 0xFF, 0xC3, 0xE7, 0xFF, 0xFF, 0x7E, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x6C, 0xFE, 0xFE, 0xFE, 0xFE, 0x7C, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x7C, 0xFE, 0x7C, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x18, 0x3C, 0x3C, 0xE7, 0xE7, 0xE7, 0x99, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x18, 0x3C, 0x7E, 0xFF, 0xFF, 0x7E, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3C, 0x3C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE7, 0xC3, 0xC3, 0xE7, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x66, 0x42, 0x42, 0x66, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC3, 0x99, 0xBD, 0xBD, 0x99, 0xC3, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x1E, 0x0E, 0x1A, 0x32, 0x78, 0xCC, 0xCC, 0xCC, 0xCC, 0x78, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3C, 0x66, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x7E, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3F, 0x33, 0x3F, 0x30, 0x30, 0x30, 0x30, 0x70, 0xF0, 0xE0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7F, 0x63, 0x7F, 0x63, 0x63, 0x63, 0x63, 0x67, 0xE7, 0xE6, 0xC0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x18, 0x18, 0xDB, 0x3C, 0xE7, 0x3C, 0xDB, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x80, 0xC0, 0xE0, 0xF0, 0xF8, 0xFE, 0xF8, 0xF0, 0xE0, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00,
0x00, 0x02, 0x06, 0x0E, 0x1E, 0x3E, 0xFE, 0x3E, 0x1E, 0x0E, 0x06, 0x02, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x18, 0x3C, 0x7E, 0x18, 0x18, 0x18, 0x18, 0x7E, 0x3C, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x66, 0x66, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7F, 0xDB, 0xDB, 0xDB, 0x7B, 0x1B, 0x1B, 0x1B, 0x1B, 0x1B, 0x00, 0x00, 0x00, 0x00,
0x00, 0x7C, 0xC6, 0x60, 0x38, 0x6C, 0xC6, 0xC6, 0x6C, 0x38, 0x0C, 0xC6, 0x7C, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFE, 0xFE, 0xFE, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x18, 0x3C, 0x7E, 0x18, 0x18, 0x18, 0x18, 0x7E, 0x3C, 0x18, 0x7E, 0x00, 0x00, 0x00,
0x00, 0x00, 0x18, 0x3C, 0x7E, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x7E, 0x3C, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x0C, 0xFE, 0x0C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x60, 0xFE, 0x60, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xC0, 0xC0, 0xC0, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x28, 0x6C, 0xFE, 0x6C, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x38, 0x7C, 0x7C, 0xFE, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xFE, 0xFE, 0x7C, 0x7C, 0x38, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x18, 0x3C, 0x3C, 0x3C, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x66, 0x66, 0x66, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x6C, 0x6C, 0xFE, 0x6C, 0x6C, 0x6C, 0xFE, 0x6C, 0x6C, 0x00, 0x00, 0x00, 0x00,
0x18, 0x18, 0x7C, 0xC6, 0xC2, 0xC0, 0x7C, 0x06, 0x86, 0xC6, 0x7C, 0x18, 0x18, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xC2, 0xC6, 0x0C, 0x18, 0x30, 0x60, 0xC6, 0x86, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x38, 0x6C, 0x6C, 0x38, 0x76, 0xDC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x30, 0x30, 0x30, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0C, 0x18, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x18, 0x0C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x30, 0x18, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x18, 0x30, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x3C, 0xFF, 0x3C, 0x66, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x7E, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x30, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x02, 0x06, 0x0C, 0x18, 0x30, 0x60, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xCE, 0xD6, 0xD6, 0xE6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x18, 0x38, 0x78, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x7E, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7C, 0xC6, 0x06, 0x0C, 0x18, 0x30, 0x60, 0xC0, 0xC6, 0xFE, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7C, 0xC6, 0x06, 0x06, 0x3C, 0x06, 0x06, 0x06, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0C, 0x1C, 0x3C, 0x6C, 0xCC, 0xFE, 0x0C, 0x0C, 0x0C, 0x1E, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFE, 0xC0, 0xC0, 0xC0, 0xFC, 0x0E, 0x06, 0x06, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x38, 0x60, 0xC0, 0xC0, 0xFC, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFE, 0xC6, 0x06, 0x06, 0x0C, 0x18, 0x30, 0x30, 0x30, 0x30, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0x7E, 0x06, 0x06, 0x06, 0x0C, 0x78, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x18, 0x18, 0x30, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x06, 0x0C, 0x18, 0x30, 0x60, 0x30, 0x18, 0x0C, 0x06, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x00, 0x00, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x60, 0x30, 0x18, 0x0C, 0x06, 0x0C, 0x18, 0x30, 0x60, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7C, 0xC6, 0xC6, 0x0C, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xDE, 0xDE, 0xDE, 0xDC, 0xC0, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x10, 0x38, 0x6C, 0xC6, 0xC6, 0xFE, 0xC6, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFC, 0x66, 0x66, 0x66, 0x7C, 0x66, 0x66, 0x66, 0x66, 0xFC, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3C, 0x66, 0xC2, 0xC0, 0xC0, 0xC0, 0xC0, 0xC2, 0x66, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xF8, 0x6C, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x6C, 0xF8, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFE, 0x66, 0x62, 0x68, 0x78, 0x68, 0x60, 0x62, 0x66, 0xFE, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFE, 0x66, 0x62, 0x68, 0x78, 0x68, 0x60, 0x60, 0x60, 0xF0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3C, 0x66, 0xC2, 0xC0, 0xC0, 0xDE, 0xC6, 0xC6, 0x66, 0x3A, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xFE, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3C, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x1E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0xCC, 0xCC, 0xCC, 0x78, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xE6, 0x66, 0x6C, 0x6C, 0x78, 0x78, 0x6C, 0x66, 0x66, 0xE6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xF0, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x62, 0x66, 0xFE, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC6, 0xEE, 0xFE, 0xFE, 0xD6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC6, 0xE6, 0xF6, 0xFE, 0xDE, 0xCE, 0xC6, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x38, 0x6C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x6C, 0x38, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFC, 0x66, 0x66, 0x66, 0x7C, 0x60, 0x60, 0x60, 0x60, 0xF0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xD6, 0xDE, 0x7C, 0x0C, 0x0E, 0x00, 0x00,
0x00, 0x00, 0xFC, 0x66, 0x66, 0x66, 0x7C, 0x6C, 0x66, 0x66, 0x66, 0xE6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7C, 0xC6, 0xC6, 0x60, 0x38, 0x0C, 0x06, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7E, 0x7E, 0x5A, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x6C, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xD6, 0xD6, 0xFE, 0x6C, 0x6C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC6, 0xC6, 0x6C, 0x6C, 0x38, 0x38, 0x6C, 0x6C, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFE, 0xC6, 0x86, 0x0C, 0x18, 0x30, 0x60, 0xC2, 0xC6, 0xFE, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3C, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0x70, 0x38, 0x1C, 0x0E, 0x06, 0x02, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x10, 0x38, 0x6C, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00,
0x30, 0x30, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xE0, 0x60, 0x60, 0x78, 0x6C, 0x66, 0x66, 0x66, 0x66, 0xDC, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC0, 0xC0, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x1C, 0x0C, 0x0C, 0x3C, 0x6C, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xFE, 0xC0, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x38, 0x6C, 0x64, 0x60, 0xF0, 0x60, 0x60, 0x60, 0x60, 0xF0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x7C, 0x0C, 0xCC, 0x78, 0x00,
0x00, 0x00, 0xE0, 0x60, 0x60, 0x6C, 0x76, 0x66, 0x66, 0x66, 0x66, 0xE6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x18, 0x18, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x06, 0x00, 0x0E, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x66, 0x66, 0x3C, 0x00,
0x00, 0x00, 0xE0, 0x60, 0x60, 0x66, 0x6C, 0x78, 0x78, 0x6C, 0x66, 0xE6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xEC, 0xFE, 0xD6, 0xD6, 0xD6, 0xD6, 0xD6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xDC, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xDC, 0x66, 0x66, 0x66, 0x66, 0x66, 0x7C, 0x60, 0x60, 0xF0, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x7C, 0x0C, 0x0C, 0x1E, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xDC, 0x76, 0x62, 0x60, 0x60, 0x60, 0xF0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0x60, 0x38, 0x0C, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x10, 0x30, 0x30, 0xFC, 0x30, 0x30, 0x30, 0x30, 0x36, 0x1C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xC6, 0xC6, 0xD6, 0xD6, 0xFE, 0x6C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0x6C, 0x38, 0x38, 0x38, 0x6C, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7E, 0x06, 0x0C, 0xF8, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xCC, 0x18, 0x30, 0x60, 0xC6, 0xFE, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0E, 0x18, 0x18, 0x18, 0x70, 0x18, 0x18, 0x18, 0x18, 0x0E, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x70, 0x18, 0x18, 0x18, 0x0E, 0x18, 0x18, 0x18, 0x18, 0x70, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x76, 0xDC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x6C, 0xC6, 0xC6, 0xC6, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3C, 0x66, 0xC2, 0xC0, 0xC0, 0xC0, 0xC2, 0x66, 0x3C, 0x0C, 0x06, 0x7C, 0x00, 0x00,
0x00, 0x00, 0xCC, 0xCC, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x0C, 0x18, 0x30, 0x00, 0x7C, 0xC6, 0xFE, 0xC0, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x10, 0x38, 0x6C, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xCC, 0xCC, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x60, 0x30, 0x18, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x38, 0x6C, 0x38, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x3C, 0x66, 0x60, 0x60, 0x66, 0x3C, 0x0C, 0x06, 0x3C, 0x00, 0x00, 0x00,
0x00, 0x10, 0x38, 0x6C, 0x00, 0x7C, 0xC6, 0xFE, 0xC0, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC6, 0xC6, 0x00, 0x7C, 0xC6, 0xFE, 0xC0, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x60, 0x30, 0x18, 0x00, 0x7C, 0xC6, 0xFE, 0xC0, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x66, 0x66, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x18, 0x3C, 0x66, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x60, 0x30, 0x18, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0xC6, 0xC6, 0x10, 0x38, 0x6C, 0xC6, 0xC6, 0xFE, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x38, 0x6C, 0x38, 0x00, 0x38, 0x6C, 0xC6, 0xC6, 0xFE, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x18, 0x30, 0x60, 0x00, 0xFE, 0x66, 0x60, 0x7C, 0x60, 0x60, 0x66, 0xFE, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xCC, 0x76, 0x36, 0x7E, 0xD8, 0xD8, 0x6E, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3E, 0x6C, 0xCC, 0xCC, 0xFE, 0xCC, 0xCC, 0xCC, 0xCC, 0xCE, 0x00, 0x00, 0x00, 0x00,
0x00, 0x10, 0x38, 0x6C, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC6, 0xC6, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x60, 0x30, 0x18, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x30, 0x78, 0xCC, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x60, 0x30, 0x18, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC6, 0xC6, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7E, 0x06, 0x0C, 0x78, 0x00,
0x00, 0xC6, 0xC6, 0x00, 0x38, 0x6C, 0xC6, 0xC6, 0xC6, 0xC6, 0x6C, 0x38, 0x00, 0x00, 0x00, 0x00,
0x00, 0xC6, 0xC6, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x18, 0x18, 0x3C, 0x66, 0x60, 0x60, 0x60, 0x66, 0x3C, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x38, 0x6C, 0x64, 0x60, 0xF0, 0x60, 0x60, 0x60, 0x60, 0xE6, 0xFC, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x66, 0x66, 0x3C, 0x18, 0x7E, 0x18, 0x7E, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0xF8, 0xCC, 0xCC, 0xF8, 0xC4, 0xCC, 0xDE, 0xCC, 0xCC, 0xCC, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x0E, 0x1B, 0x18, 0x18, 0x18, 0x7E, 0x18, 0x18, 0x18, 0x18, 0x18, 0xD8, 0x70, 0x00, 0x00,
0x00, 0x18, 0x30, 0x60, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x0C, 0x18, 0x30, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x18, 0x30, 0x60, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x18, 0x30, 0x60, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x76, 0xDC, 0x00, 0xDC, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x00, 0x00, 0x00,
0x76, 0xDC, 0x00, 0xC6, 0xE6, 0xF6, 0xFE, 0xDE, 0xCE, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x3C, 0x6C, 0x6C, 0x3E, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x38, 0x6C, 0x6C, 0x38, 0x00, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x30, 0x30, 0x00, 0x30, 0x30, 0x60, 0xC0, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xC0, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x06, 0x06, 0x06, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0xC0, 0xC0, 0xC2, 0xC6, 0xCC, 0x18, 0x30, 0x60, 0xCE, 0x93, 0x06, 0x0C, 0x1F, 0x00, 0x00,
0x00, 0xC0, 0xC0, 0xC2, 0xC6, 0xCC, 0x18, 0x30, 0x66, 0xCE, 0x9A, 0x3F, 0x06, 0x0F, 0x00, 0x00,
0x00, 0x00, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x3C, 0x3C, 0x3C, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x33, 0x66, 0xCC, 0x66, 0x33, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xCC, 0x66, 0x33, 0x66, 0xCC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44,
0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA,
0xDD, 0x77, 0xDD, 0x77, 0xDD, 0x77, 0xDD, 0x77, 0xDD, 0x77, 0xDD, 0x77, 0xDD, 0x77, 0xDD, 0x77,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xF8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0xF8, 0x18, 0xF8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xF6, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x18, 0xF8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x36, 0x36, 0x36, 0x36, 0x36, 0xF6, 0x06, 0xF6, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x06, 0xF6, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0xF6, 0x06, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x18, 0x18, 0x18, 0x18, 0x18, 0xF8, 0x18, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1F, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xFF, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x1F, 0x18, 0x1F, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x37, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0x37, 0x30, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0x30, 0x37, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0xF7, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xF7, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0x37, 0x30, 0x37, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x36, 0x36, 0x36, 0x36, 0x36, 0xF7, 0x00, 0xF7, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x18, 0x18, 0x18, 0x18, 0x18, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x18, 0x18, 0x18, 0x18, 0x18, 0x1F, 0x18, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0x18, 0x1F, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xFF, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x18, 0x18, 0x18, 0x18, 0x18, 0xFF, 0x18, 0xFF, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xDC, 0xD8, 0xD8, 0xD8, 0xDC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xC6, 0xFC, 0xC6, 0xC6, 0xFC, 0xC0, 0xC0, 0xC0, 0x00, 0x00,
0x00, 0x00, 0xFE, 0xC6, 0xC6, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x80, 0xFE, 0x6C, 0x6C, 0x6C, 0x6C, 0x6C, 0x6C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xFE, 0xC6, 0x60, 0x30, 0x18, 0x30, 0x60, 0xC6, 0xFE, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0xD8, 0xD8, 0xD8, 0xD8, 0xD8, 0x70, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x7C, 0x60, 0x60, 0xC0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x76, 0xDC, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x7E, 0x18, 0x3C, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x7E, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x38, 0x6C, 0xC6, 0xC6, 0xFE, 0xC6, 0xC6, 0x6C, 0x38, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x38, 0x6C, 0xC6, 0xC6, 0xC6, 0x6C, 0x6C, 0x6C, 0x6C, 0xEE, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x1E, 0x30, 0x18, 0x0C, 0x3E, 0x66, 0x66, 0x66, 0x66, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0xDB, 0xDB, 0xDB, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x03, 0x06, 0x7E, 0xCF, 0xDB, 0xF3, 0x7E, 0x60, 0xC0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x1C, 0x30, 0x60, 0x60, 0x7C, 0x60, 0x60, 0x60, 0x30, 0x1C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xFE, 0x00, 0x00, 0xFE, 0x00, 0x00, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x7E, 0x18, 0x18, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x30, 0x18, 0x0C, 0x06, 0x0C, 0x18, 0x30, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0C, 0x18, 0x30, 0x60, 0x30, 0x18, 0x0C, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0E, 0x1B, 0x1B, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xD8, 0xD8, 0xD8, 0x70, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x7E, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xDC, 0x00, 0x76, 0xDC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x38, 0x6C, 0x6C, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x0F, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0xEC, 0x6C, 0x6C, 0x3C, 0x1C, 0x00, 0x00, 0x00, 0x00,
0x00, 0xD8, 0x6C, 0x6C, 0x6C, 0x6C, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x70, 0x98, 0x30, 0x60, 0xC8, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x7C, 0x7C, 0x7C, 0x7C, 0x7C, 0x7C, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
Console::Console()
{
is_console = 0;
if(detect_card_type()==COLOR_CARD) vid_mem = (unsigned char*) 0xB8000;
else if(detect_card_type()==MONO_CARD) vid_mem = (unsigned char*) 0xB0000;
curr_x = curr_y = 0;
c_maxx = 79;
c_maxy = 24;
last_result = 0;
textattrib = WHITE;
bgcolor = BLACK;
fgcolor = WHITE;
set_res(TEXT_90x30);
clrscr();
}
Console::~Console()
{
;
}
int Console::detect_card_type()
{
/* check for monochrome or color VGA emulation */
if((inportb(VGA_MISC_READ) & 0x01) == 1) return COLOR_CARD;
else return MONO_CARD;
}
void Console::update_cursor()
{
unsigned int position = (curr_y * (c_maxx + 1) + curr_x);
outportb(0x3D4, 0x0F);
outportb(0x3D5, (unsigned char)(position&0xFF));
outportb(0x3D4, 0x0E);
outportb(0x3D5, (unsigned char)((position>>8)&0xFF));
}
void Console::scroll_line_up(void)
{
memcpy(vid_mem, vid_mem + (c_maxx+1)*2, (c_maxy*(c_maxx+1)*2));
memsetb(vid_mem + (c_maxx+1) * (c_maxy)*2, NULL, (c_maxx+1)*2);
}
void Console::write_regs(unsigned char *regs)
{
unsigned i;
/* write MISCELLANEOUS reg */
outportb(VGA_MISC_WRITE, *regs);
regs++;
outportb(VGA_INSTAT_READ, 0x00);
/* write SEQUENCER regs */
for(i = 0; i < VGA_NUM_SEQ_REGS; i++)
{
outportb(VGA_SEQ_INDEX, i);
outportb(VGA_SEQ_DATA, *regs);
regs++;
}
/* unlock CRTC registers */
outportb(VGA_CRTC_INDEX, 0x03);
outportb(VGA_CRTC_DATA, inportb(VGA_CRTC_DATA) | 0x80);
outportb(VGA_CRTC_INDEX, 0x11);
outportb(VGA_CRTC_DATA, inportb(VGA_CRTC_DATA) & ~0x80);
/* make sure they remain unlocked */
regs[0x03] |= 0x80;
regs[0x11] &= ~0x80;
/* write CRTC regs */
for(i = 0; i < VGA_NUM_CRTC_REGS; i++)
{
outportb(VGA_CRTC_INDEX, i);
outportb(VGA_CRTC_DATA, *regs);
regs++;
}
/* write GRAPHICS CONTROLLER regs */
for(i = 0; i < VGA_NUM_GC_REGS; i++)
{
outportb(VGA_GC_INDEX, i);
outportb(VGA_GC_DATA, *regs);
regs++;
}
/* write ATTRIBUTE CONTROLLER regs */
for(i = 0; i < VGA_NUM_AC_REGS; i++)
{
(void)inportb(VGA_INSTAT_READ);
outportb(VGA_AC_INDEX, i);
outportb(VGA_AC_WRITE, *regs);
regs++;
}
/* lock 16-color palette and unblank display */
(void)inportb(VGA_INSTAT_READ);
outportb(VGA_AC_INDEX, 0x20);
}
int Console::init()
{
if(is_console == 1)
{
last_result = CONSOLE_ALREADY_INITIALIZED;
return KMSG_FALIURE;
}
else
{
is_console = 1;
cout<<"\nConsole:";
cout<<"\n\tColor Emulation Detected";
cout<<"\n\tVGA+ ";
cout<<c_maxx + 1<<" x "<<c_maxy + 1;
cout<<"\n\tUsing WHITE on BLACK";
return KMSG_SUCCESS;
}
return last_result;
}
int Console::set_res(unsigned int mode)
{
switch(mode)
{
case TEXT_40x25: write_regs(_40x25_text);
c_maxx = 39; c_maxy = 24;
break;
case TEXT_40x50: write_regs(_40x50_text);
c_maxx = 39; c_maxy = 49;
break;
case TEXT_80x25: write_regs(_80x25_text);
c_maxx = 79; c_maxy = 24;
break;
case TEXT_80x50: write_regs(_80x50_text);
c_maxx = 79; c_maxy = 49;
break;
case TEXT_90x30: write_regs(_90x30_text);
c_maxx = 89; c_maxy = 29;
break;
case TEXT_90x60: write_regs(_90x60_text);
c_maxx = 89; c_maxy = 59;
break;
default: last_result = MODE_NOT_SUPPORTED;
break;
};
clrscr();
return last_result;
}
void Console::settextbackground(int col)
{
if(col>7);
else
if(col<0);
else
bgcolor=col;
textattrib=(bgcolor*16)+fgcolor;
}
void Console::settextcolor(int col)
{
if(col > 15);
else
if(col < 0);
else
fgcolor = col;
textattrib = (bgcolor*16) + fgcolor;
}
void Console::settextattrib(int col)
{
textattrib = col;
}
int Console::gettextcolor()
{
return fgcolor;
}
int Console::gettextbgcolor()
{
return bgcolor;
}
int Console::gettextattrib()
{
return textattrib;
}
int Console::wherex(void)
{
return curr_x + 1;
}
int Console::wherey(void)
{
return curr_y + 1;
}
int Console::getmaxx()
{
return c_maxx + 1;
}
int Console::getmaxy()
{
return c_maxy + 1;
}
void Console::gotoxy(unsigned int x, unsigned int y)
{
if((y < 1)&&(x < 1));
else if((y>c_maxy)&&(x>c_maxx));
else
{
curr_x = x - 1; curr_y = y - 1;
update_cursor();
}
}
void Console::clrscr()
{
unsigned int i;
for (i=0; i != (c_maxx * c_maxy); i=i+1) putch(' ');
curr_x = 0; curr_y = 0;
update_cursor();
}
void Console::putch(const unsigned char ch)
{
int i;
switch(ch)
{
case BUFFER_UNDERFLOW: break;
case BUFFER_OVERFLOW: break;
case '\r':
case '\n': curr_x = 0; curr_y = curr_y + 1;
if(curr_y > c_maxy)
{
curr_x = 0; curr_y = c_maxy;
scroll_line_up();
}
break;
case '\t': for(i=0; i!=TAB; i=i+1)
{
putch(' ');
}
break;
case '\b': curr_x = curr_x - 1; //Bug at pos 0,0
if(curr_x < 0)
{
curr_x = c_maxx; curr_y = curr_y - 1;
}
if(curr_y < 0) { curr_x = 0; curr_y = 0; }
vid_mem[(((curr_y * (c_maxx + 1)) + curr_x) * 2)] = ' ';
vid_mem[(((curr_y * (c_maxx + 1)) + curr_x) * 2) + 1] = textattrib;
break;
default: if(ch >= ' ')
{
vid_mem[(((curr_y * (c_maxx + 1)) + curr_x) * 2)] = ch;
vid_mem[(((curr_y * (c_maxx + 1)) + curr_x) * 2) + 1] = textattrib;
curr_x = curr_x + 1;
if(curr_x > c_maxx)
{
putch('\n');
}
}
break;
}
update_cursor();
}
int Console::writeln(const char *buf)
{
while(*buf != '\0')
{
putch(*buf);
buf++;
}
}
void Console::writeint(const unsigned int num)
{
unsigned _num = num;
char _tnum[6];
int _i=0;
while(_num!=0)
{
_tnum[_i]=itoa(_num%10);
_num=_num/10;
_i=_i+1;
}
_tnum[_i]='\0';
for(_i=0;_tnum[_i]!='\0';_i=_i+1);
for(_i=_i-1;_i>=0;_i=_i-1)
{
putch(_tnum[_i]);
}
}
void Console::writeint(const int num)
{
int _num = num;
if(_num < 0)
{
_num = _num * -1;
putch('-');
}
char _tnum[10];
int _i=0;
while(_num!=0)
{
_tnum[_i]=itoa(_num%10);
_num=_num/10;
_i=_i+1;
}
_tnum[_i]='\0';
for(_i=0;_tnum[_i]!='\0';_i=_i+1);
for(_i=_i-1;_i>=0;_i=_i-1)
{
putch(_tnum[_i]);
}
}
#endif
| [
"codemaster.snake@gmail.com"
] | [
[
[
1,
985
]
]
] |
46effb3436023cf959a0f5963ce426d612f7f0c5 | 138a353006eb1376668037fcdfbafc05450aa413 | /source/ArenaCamera.cpp | 48b047fa6f49144f1cdf706b0241410033d51e0e | [] | no_license | sonicma7/choreopower | 107ed0a5f2eb5fa9e47378702469b77554e44746 | 1480a8f9512531665695b46dcfdde3f689888053 | refs/heads/master | 2020-05-16 20:53:11 | 2009-11-18 03:10:12 | 2009-11-18 03:10:12 | 32,246,184 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,002 | cpp | #include "ArenaCamera.h"
ArenaCamera::ArenaCamera(Ogre::SceneNode *target1, Ogre::SceneNode *target2, Ogre::Camera *cam) {
mTarget1 = target1;
mTarget2 = target2;
mCamera = cam;
mMinDist = 0.0f;
}
ArenaCamera::~ArenaCamera() {
}
void ArenaCamera::setMinDistanceAway(float dist) {
mMinDist = dist;
}
void ArenaCamera::update() {
Ogre::Vector3 lookAt;
Ogre::Vector3 camPos(mCamera->getPosition());
float distance;
float idealDistance;
float fov = mCamera->getFOVy().valueRadians();
float xDist;
float otherAngle = 90 - fov;
lookAt = (mTarget1->getPosition() + mTarget2->getPosition()) * 0.5f;
xDist = fabs(mTarget1->getPosition().x - mTarget2->getPosition().x);
distance = camPos.z - lookAt.z;
idealDistance = 0.5f * xDist * Ogre::Math::Sin(otherAngle) / Ogre::Math::Sin(0.5f * fov);
if(idealDistance > mMinDist) {
camPos.z = idealDistance;
} else {
camPos.z = mMinDist;
}
mCamera->setPosition(camPos);
mCamera->lookAt(lookAt);
} | [
"Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e"
] | [
[
[
1,
41
]
]
] |
a4101e9ddd6e6c57339a72de808c10e8f121fcfe | 38926bfe477f933a307f51376dd3c356e7893ffc | /Source/SDKs/STLPORT/stlport/stl/_tempbuf.h | 0f3cda35b5fd4cfbed5044797cf6036a4e7ff8a0 | [
"LicenseRef-scancode-stlport-4.5"
] | permissive | richmondx/dead6 | b0e9dd94a0ebb297c0c6e9c4f24c6482ef4d5161 | 955f76f35d94ed5f991871407f3d3ad83f06a530 | refs/heads/master | 2021-12-05 14:32:01 | 2008-01-01 13:13:39 | 2008-01-01 13:13:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,832 | h | /*
*
* Copyright (c) 1994
* Hewlett-Packard Company
*
* Copyright (c) 1996,1997
* Silicon Graphics Computer Systems, Inc.
*
* Copyright (c) 1997
* Moscow Center for SPARC Technology
*
* Copyright (c) 1999
* Boris Fomitchev
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*/
/* NOTE: This is an internal header file, included by other STL headers.
* You should not attempt to use it directly.
*/
#ifndef _STLP_INTERNAL_TEMPBUF_H
#define _STLP_INTERNAL_TEMPBUF_H
#ifndef _STLP_CLIMITS
# include <climits>
#endif
#ifndef _STLP_CSTDLIB
# include <cstdlib>
#endif
#ifndef _STLP_INTERNAL_UNINITIALIZED_H
# include <stl/_uninitialized.h>
#endif
_STLP_BEGIN_NAMESPACE
template <class _Tp>
pair<_Tp*, ptrdiff_t> _STLP_CALL
__get_temporary_buffer(ptrdiff_t __len, _Tp*);
#ifndef _STLP_NO_EXPLICIT_FUNCTION_TMPL_ARGS
template <class _Tp>
inline pair<_Tp*, ptrdiff_t> _STLP_CALL get_temporary_buffer(ptrdiff_t __len) {
return __get_temporary_buffer(__len, (_Tp*) 0);
}
# if ! defined(_STLP_NO_EXTENSIONS)
// This overload is not required by the standard; it is an extension.
// It is supported for backward compatibility with the HP STL, and
// because not all compilers support the language feature (explicit
// function template arguments) that is required for the standard
// version of get_temporary_buffer.
template <class _Tp>
inline pair<_Tp*, ptrdiff_t> _STLP_CALL
get_temporary_buffer(ptrdiff_t __len, _Tp*) {
return __get_temporary_buffer(__len, (_Tp*) 0);
}
# endif
#endif
template <class _Tp>
inline void _STLP_CALL return_temporary_buffer(_Tp* __p) {
// SunPro brain damage
free((char*)__p);
}
template <class _ForwardIterator, class _Tp>
class _Temporary_buffer {
private:
ptrdiff_t _M_original_len;
ptrdiff_t _M_len;
_Tp* _M_buffer;
void _M_allocate_buffer() {
_M_original_len = _M_len;
_M_buffer = 0;
if (_M_len > (ptrdiff_t)(INT_MAX / sizeof(_Tp)))
_M_len = INT_MAX / sizeof(_Tp);
while (_M_len > 0) {
_M_buffer = (_Tp*) malloc(_M_len * sizeof(_Tp));
if (_M_buffer)
break;
_M_len /= 2;
}
}
void _M_initialize_buffer(const _Tp&, const __true_type&) {}
void _M_initialize_buffer(const _Tp& val, const __false_type&) {
uninitialized_fill_n(_M_buffer, _M_len, val);
}
public:
ptrdiff_t size() const { return _M_len; }
ptrdiff_t requested_size() const { return _M_original_len; }
_Tp* begin() { return _M_buffer; }
_Tp* end() { return _M_buffer + _M_len; }
_Temporary_buffer(_ForwardIterator __first, _ForwardIterator __last) {
// Workaround for a __type_traits bug in the pre-7.3 compiler.
# if defined(__sgi) && !defined(__GNUC__) && _COMPILER_VERSION < 730
typedef typename __type_traits<_Tp>::is_POD_type _Trivial;
# else
typedef typename __type_traits<_Tp>::has_trivial_default_constructor _Trivial;
# endif
_STLP_TRY {
_M_len = distance(__first, __last);
_M_allocate_buffer();
if (_M_len > 0)
_M_initialize_buffer(*__first, _Trivial());
}
_STLP_UNWIND(free(_M_buffer); _M_buffer = 0; _M_len = 0)
}
~_Temporary_buffer() {
_STLP_STD::_Destroy_Range(_M_buffer, _M_buffer + _M_len);
free(_M_buffer);
}
private:
// Disable copy constructor and assignment operator.
_Temporary_buffer(const _Temporary_buffer<_ForwardIterator, _Tp>&) {}
void operator=(const _Temporary_buffer<_ForwardIterator, _Tp>&) {}
};
# ifndef _STLP_NO_EXTENSIONS
// Class temporary_buffer is not part of the standard. It is an extension.
template <class _ForwardIterator,
class _Tp
#ifdef _STLP_CLASS_PARTIAL_SPECIALIZATION
= typename iterator_traits<_ForwardIterator>::value_type
#endif /* _STLP_CLASS_PARTIAL_SPECIALIZATION */
>
struct temporary_buffer : public _Temporary_buffer<_ForwardIterator, _Tp>
{
temporary_buffer(_ForwardIterator __first, _ForwardIterator __last)
: _Temporary_buffer<_ForwardIterator, _Tp>(__first, __last) {}
~temporary_buffer() {}
};
# endif /* _STLP_NO_EXTENSIONS */
_STLP_END_NAMESPACE
# ifndef _STLP_LINK_TIME_INSTANTIATION
# include <stl/_tempbuf.c>
# endif
#endif /* _STLP_INTERNAL_TEMPBUF_H */
// Local Variables:
// mode:C++
// End:
| [
"dante.renevo@gmail.com"
] | [
[
[
1,
167
]
]
] |
9c909bfb34de3f32da76a9c2671b793b41a928e9 | 2982a765bb21c5396587c86ecef8ca5eb100811f | /util/wm5/LibCore/Assert/Wm5Assert.h | 4ed90d6848b8e952aba09ac5a664fc2b522f5839 | [] | no_license | evanw/cs224final | 1a68c6be4cf66a82c991c145bcf140d96af847aa | af2af32732535f2f58bf49ecb4615c80f141ea5b | refs/heads/master | 2023-05-30 19:48:26 | 2011-05-10 16:21:37 | 2011-05-10 16:21:37 | 1,653,696 | 27 | 9 | null | null | null | null | UTF-8 | C++ | false | false | 1,604 | h | // Geometric Tools, LLC
// Copyright (c) 1998-2010
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
//
// File Version: 5.0.1 (2010/10/01)
#ifndef WM5ASSERT_H
#define WM5ASSERT_H
#include "Wm5CoreLIB.h"
#ifdef WM5_USE_ASSERT
//----------------------------------------------------------------------------
// Use WM5 asserts with file/line tracking.
//----------------------------------------------------------------------------
namespace Wm5
{
class WM5_CORE_ITEM Assert
{
public:
// Construction and destruction.
Assert (bool condition, const char* file, int line, const char* format,
...);
~Assert ();
private:
enum { MAX_MESSAGE_BYTES = 1024 };
static const char* msDebugPrompt;
static const size_t msDebugPromptLength;
static const char* msMessagePrefix;
#ifdef WM5_USE_ASSERT_WRITE_TO_MESSAGE_BOX
static const char* msMessageBoxTitle;
#endif
};
}
#define assertion(condition, format, ...) \
Wm5::Assert(condition, __FILE__, __LINE__, format, __VA_ARGS__)
//----------------------------------------------------------------------------
#else
//----------------------------------------------------------------------------
// Use standard asserts.
//----------------------------------------------------------------------------
#define assertion(condition, format, ...) assert(condition)
//----------------------------------------------------------------------------
#endif
#endif
| [
"evan_wallace@brown.edu"
] | [
[
[
1,
54
]
]
] |
a37b60dbc706ca304a302392b4d360cd980ac515 | 2e613efc5a3b330f440a2d90bb758dafbdf8f6b1 | /src/rect.cpp | 1e2e8cb79aa9c6fb72964a03eedb82f0bbdf6cb9 | [] | no_license | zhaoweisonake/qfplot | 4a76d446aebfddce4bf8a51c709a815f35ca76d2 | e30d851261f3987a42319ff98def23771adb24bd | refs/heads/master | 2021-01-18 12:31:07 | 2010-05-17 09:29:11 | 2010-05-17 09:29:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 239 | cpp | #include "rect.h"
void Rect::expand( const QPoint& point )
{
setLeft ( qMin(point.x(), left() ) );
setRight ( qMax(point.x(), right() ) );
setTop ( qMax(point.y(), top() ) );
setBottom( qMin(point.y(), bottom()) );
};
| [
"akhokhlov@localhost"
] | [
[
[
1,
9
]
]
] |
0f80f8f22afb8a18bf6c8fec5f53894097cf9a23 | 2dbbca065b62a24f47aeb7ec5cd7a4fd82083dd4 | /OUAN/OUAN/Src/Game/GameObject/GameObjectParticleSystem.h | c936081eb51d6aab1d9510ea47b5df4eb717d937 | [] | no_license | juanjmostazo/once-upon-a-night | 9651dc4dcebef80f0475e2e61865193ad61edaaa | f8d5d3a62952c45093a94c8b073cbb70f8146a53 | refs/heads/master | 2020-05-28 05:45:17 | 2010-10-06 12:49:50 | 2010-10-06 12:49:50 | 38,101,059 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,870 | h | #ifndef GameObjectParticleSystemH_H
#define GameObjectParticleSystemH_H
#include "GameObject.h"
#include "../../Graphics/RenderComponent/RenderComponentInitial.h"
#include "../../Graphics/RenderComponent/RenderComponentPositional.h"
#include "../../Graphics/RenderComponent/RenderComponentParticleSystem.h"
#include "../../Logic/LogicComponent/LogicComponent.h"
namespace OUAN
{
/// Models a light source object
class GameObjectParticleSystem : public GameObject, public boost::enable_shared_from_this<GameObjectParticleSystem>
{
private:
/// Holds the information related to visual rendering
RenderComponentParticleSystemPtr mRenderComponentParticleSystem;
/// Holds information related to the object's position in space
RenderComponentInitialPtr mRenderComponentInitial;
RenderComponentPositionalPtr mRenderComponentPositional;
/// Logic component: it'll represent the 'brains' of the game object
/// containing information on its current state, its life and health(if applicable),
/// or the world(s) the object belongs to
LogicComponentPtr mLogicComponent;
public:
//Constructor
GameObjectParticleSystem(const std::string& name);
//Destructor
~GameObjectParticleSystem();
/// Set logic component
void setLogicComponent(LogicComponentPtr logicComponent);
/// return logic component
LogicComponentPtr getLogicComponent();
/// Get light component
/// @return light component
RenderComponentParticleSystemPtr getRenderComponentParticleSystem() const;
/// Set light component
/// @param pRenderComponentLight the light component to set
void setRenderComponentParticleSystem(RenderComponentParticleSystemPtr pRenderComponentParticleSystem);
/// Set positional component
/// @param pRenderComponentPositional the component containing the positional information
void setRenderComponentPositional(RenderComponentPositionalPtr pRenderComponentPositional);
/// Set initial component
void setRenderComponentInitial(RenderComponentInitialPtr pRenderComponentInitial);
void setVisible(bool visible);
/// Return positional component
/// @return positional component
RenderComponentPositionalPtr getRenderComponentPositional() const;
/// Return initial component
/// @return initial component
RenderComponentInitialPtr getRenderComponentInitial() const;
void changeToWorld(int newWorld, double perc);
void changeWorldFinished(int newWorld);
void changeWorldStarted(int newWorld);
/// Reset object
virtual void reset();
bool hasPositionalComponent() const;
RenderComponentPositionalPtr getPositionalComponent() const;
/// Process collision event
/// @param gameObject which has collision with
void processCollision(GameObjectPtr pGameObject, Ogre::Vector3 pNormal);
/// Process collision event
/// @param gameObject which has collision with
void processEnterTrigger(GameObjectPtr pGameObject);
/// Process collision event
/// @param gameObject which has collision with
void processExitTrigger(GameObjectPtr pGameObject);
bool hasLogicComponent() const;
LogicComponentPtr getLogicComponent() const;
};
/// Transport object carrying around data from the level loader
/// to the ParticleSystem object
class TGameObjectParticleSystemParameters: public TGameObjectParameters
{
public:
/// Default constructor
TGameObjectParticleSystemParameters();
/// Default destructor
~TGameObjectParticleSystemParameters();
/// Light-specific parameters
TRenderComponentParticleSystemParameters tRenderComponentParticleSystemParameters;
/// Positional parameters
TRenderComponentPositionalParameters tRenderComponentPositionalParameters;
///Logic parameters
TLogicComponentParameters tLogicComponentParameters;
};
}
#endif | [
"wyern1@1610d384-d83c-11de-a027-019ae363d039",
"juanj.mostazo@1610d384-d83c-11de-a027-019ae363d039",
"ithiliel@1610d384-d83c-11de-a027-019ae363d039"
] | [
[
[
1,
2
],
[
4,
4
],
[
6,
8
],
[
10,
12
],
[
14,
18
],
[
20,
47
],
[
51,
56
],
[
61,
64
],
[
71,
73
],
[
75,
83
],
[
88,
111
]
],
[
[
3,
3
],
[
5,
5
],
[
9,
9
],
[
19,
19
],
[
48,
50
],
[
57,
60
],
[
66,
68
],
[
74,
74
]
],
[
[
13,
13
],
[
65,
65
],
[
69,
70
],
[
84,
87
]
]
] |
31568d0f836d137f63967072d2469027147ae9b3 | ff5313a6e6c9f9353f7505a37a57255c367ff6af | /wtl_hello/stdafx.h | e18df8bf55c9af71f7658ce5cb6d1d00bf5297aa | [] | no_license | badcodes/vc6 | 467d6d513549ac4d435e947927d619abf93ee399 | 0c11d7a81197793e1106c8dd3e7ec6b097a68248 | refs/heads/master | 2016-08-07 19:14:15 | 2011-07-09 18:05:18 | 2011-07-09 18:05:18 | 1,220,419 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,454 | h | // stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#if !defined(AFX_STDAFX_H__19DE612F_4674_42AE_B6FB_36E8EA9BB2D5__INCLUDED_)
#define AFX_STDAFX_H__19DE612F_4674_42AE_B6FB_36E8EA9BB2D5__INCLUDED_
// Change these values to use different versions
#define WINVER 0x0400
//#define _WIN32_WINNT 0x0400
#define _WIN32_IE 0x0400
#define _RICHEDIT_VER 0x0100
#include <atlbase.h>
#include <atlapp.h>
extern CAppModule _Module;
/*
#define _WTL_SUPPORT_SDK_ATL3
// Support for VS2005 Express & SDK ATL
#ifdef _WTL_SUPPORT_SDK_ATL3
#define _CRT_SECURE_NO_DEPRECATE
#pragma conform(forScope, off)
#pragma comment(linker, "/NODEFAULTLIB:atlthunk.lib")
#endif // _WTL_SUPPORT_SDK_ATL3
#include <atlbase.h>
// Support for VS2005 Express & SDK ATL
#ifdef _WTL_SUPPORT_SDK_ATL3
namespace ATL
{
inline void * __stdcall __AllocStdCallThunk()
{
return ::HeapAlloc(::GetProcessHeap(), 0, sizeof(_stdcallthunk));
}
inline void __stdcall __FreeStdCallThunk(void *p)
{
::HeapFree(::GetProcessHeap(), 0, p);
}
};
#endif // _WTL_SUPPORT_SDK_ATL3
*/
#include <atlwin.h>
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_STDAFX_H__19DE612F_4674_42AE_B6FB_36E8EA9BB2D5__INCLUDED_)
| [
"eotect@gmail.com"
] | [
[
[
1,
54
]
]
] |
4c8a716bfba9cc8e25b3041c6201fa18e90e6596 | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/exporter/3dsplugin/src/n3dsmaterial/nabstractpropbuilder.cc | 2bee889a35355417bed7fdde40b22ce9b3110114 | [] | no_license | ugozapad/TheZombieEngine | 832492930df28c28cd349673f79f3609b1fe7190 | 8e8c3e6225c2ed93e07287356def9fbdeacf3d6a | refs/heads/master | 2020-04-30 11:35:36 | 2011-02-24 14:18:43 | 2011-02-24 14:18:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,605 | cc | #include "precompiled/pchn3dsmaxexport.h"
#pragma warning( push, 3 )
#include "Max.h"
#pragma warning( pop )
#include "n3dsmaterial/nabstractpropbuilder.h"
#include "kernel/nkernelserver.h"
#include "nscene/nscenenode.h"
#include "nmaterial/nmaterialnode.h"
nClass* nAbstractPropBuilder::nmaterialnode = 0;
nClass* nAbstractPropBuilder::nsurfacenode = 0;
nAbstractPropBuilder::nAbstractPropBuilder() :
thisType(nAbstractPropBuilder::NONE),
stringValid(false),
matTypeIsValid(false)
{
n_assert(nKernelServer::ks);
nmaterialnode = nKernelServer::ks->FindClass("nmaterialnode");
n_assert(nmaterialnode);
nsurfacenode = nKernelServer::ks->FindClass("nsurfacenode");
n_assert(nsurfacenode);
}
int
__cdecl
nAbstractPropBuilder::TextureSorter(const varTexture* elm0, const varTexture* elm1)
{
return strcmp(elm0->varName.Get(), elm1->varName.Get() );
}
int
__cdecl
nAbstractPropBuilder::AnimSorter( const nString* elm0, const nString* elm1)
{
n_assert(elm0);
n_assert(elm1);
return strcmp( elm0->Get(), elm1->Get() );
}
int
__cdecl
nAbstractPropBuilder::FloatSorter(const varFloat* elm0, const varFloat* elm1)
{
return strcmp(elm0->varName.Get(), elm1->varName.Get() );
}
int
__cdecl
nAbstractPropBuilder::IntSorter(const varInt* elm0, const varInt* elm1)
{
return strcmp(elm0->varName.Get(), elm1->varName.Get() );
}
int
__cdecl
nAbstractPropBuilder::VectorSorter(const varVector* elm0, const varVector* elm1)
{
return strcmp(elm0->varName.Get(), elm1->varName.Get() );
}
int
__cdecl
nAbstractPropBuilder::ShaderSorter(const varShader* elm0, const varShader* elm1)
{
return strcmp(elm0->varName.Get(), elm1->varName.Get() );
}
void
nAbstractPropBuilder::SetTexture ( const varTexture& var)
{
this->stringValid = false;
varTexture var2(var);
var2.texName.ToLower();
this->textures.Append ( var );
}
const nAbstractPropBuilder::nSortedTextures&
nAbstractPropBuilder::GetTextureArray() const
{
return this->textures;
}
nAbstractPropBuilder::nSortedTextures&
nAbstractPropBuilder::GetTextureArray()
{
return this->textures;
}
void
nAbstractPropBuilder::SetInt ( const varInt& var)
{
this->stringValid = false;
this->integers.Append( var );
}
void
nAbstractPropBuilder::SetFloat ( const varFloat& var)
{
this->stringValid = false;
this->floats.Append( var );
}
void
nAbstractPropBuilder::SetVector ( const varVector& var)
{
this->stringValid = false;
this->vectors.Append( var );
}
void
nAbstractPropBuilder::SetAnim ( const nString& pathAnim)
{
this->stringValid = false;
this->anims.Append(pathAnim);
}
void
nAbstractPropBuilder::SetShader ( const varShader& var)
{
n_assert( this->thisType == NONE || this->thisType == NSURFACE);
this->stringValid = false;
this->thisType = NSURFACE;
this->shaders.Append( var );
}
void
nAbstractPropBuilder::SetMaterial( const nMatTypePropBuilder& val)
{
n_assert( this->thisType == NONE || this->thisType == NMATERIAL );
this->stringValid = false;
this->thisType = NMATERIAL;
this->matType = val;
this->matTypeIsValid = true;
}
//------------------------------------------------------------------------------
/**
Set type Libaray.
@parama val. The original material type for future conversion
*/
void
nAbstractPropBuilder::SetMatType( const nMatTypePropBuilder& val)
{
n_assert( this->thisType == NONE || this->thisType == NMATERIAL || this->thisType == SHADERTYPELIBRARY );
this->stringValid = false;
this->matType = val;
this->matTypeIsValid = true;
}
//------------------------------------------------------------------------------
/**
Set type Libaray.
@param name The name's material in Library
@parama val. The original material type for future conversion
*/
void
nAbstractPropBuilder::SetMaterialTypeFromLibrary( const char* name , const nMatTypePropBuilder& val)
{
n_assert( this->thisType == NONE || this->thisType == SHADERTYPELIBRARY );
this->stringValid = false;
this->thisType = SHADERTYPELIBRARY;
this->matType = val;
this->matTypeIsValid = true;
this->materialTypeNameInLibrary = name;
}
//------------------------------------------------------------------------------
/**
Set type Libaray.
@param name The name's material in Library
@parama val. The original material type for future conversion
*/
void
nAbstractPropBuilder::SetMaterialTypeFromLibrary( const char* name)
{
n_assert( this->thisType == NONE || this->thisType == SHADERTYPELIBRARY );
this->stringValid = false;
this->thisType = SHADERTYPELIBRARY;
this->materialTypeNameInLibrary = name;
}
//------------------------------------------------------------------------------
/**
*/
const char*
nAbstractPropBuilder::GetMaterialTypeName() const
{
return this->materialTypeNameInLibrary.Get();
}
//------------------------------------------------------------------------------
/**
*/
bool
nAbstractPropBuilder::IsInvalidShader() const
{
n_assert ( this->thisType == SHADERTYPELIBRARY );
return (this->materialTypeNameInLibrary.IsEmpty()) || (this->materialTypeNameInLibrary == "invalid" );
}
//------------------------------------------------------------------------------
/**
*/
bool
nAbstractPropBuilder::IsCustomShader() const
{
return (this->materialTypeNameInLibrary == "custom" );
}
const char*
nAbstractPropBuilder::GetUniqueString()
{
int idx;
if (! this->stringValid )
{
char buf[255];
stringKey="";
switch (thisType)
{
case NONE:
stringKey+="NONE#";
break;
case NMATERIAL:
stringKey+="NMATERIAL#";//+material+"/";
if (this->matTypeIsValid)
{
stringKey += this->matType.GetUniqueString();
stringKey +="/";
}
break;
case NSURFACE:
stringKey+="NSURFACE#";
for (idx = 0; idx < shaders.Size() ; idx ++)
{
varShader& shader = shaders[idx];
stringKey+= shader.varName + "." + shader.val+"/";
}
break;
case SHADERTYPELIBRARY:
stringKey+="SHADERLIBRARY#";
stringKey+=this->materialTypeNameInLibrary;
// If the material is custom get the matType properties
if (this->matTypeIsValid && (this->IsInvalidShader() || this->IsCustomShader() ) )
{
stringKey += this->matType.GetUniqueString();
stringKey +="/";
}
}
stringKey+="TEX#";
for (idx=0; idx < textures.Size() ; idx++)
{
varTexture& texture = textures[idx];
stringKey += texture.varName +"." + texture.texName + "/";
}
stringKey+="INT#";
for ( idx=0; idx < integers.Size(); idx++)
{
varInt& integer = integers[idx];
sprintf(buf,".%i#", integer.val);
stringKey += integer.varName + buf;
}
stringKey+="FLOAT#";
for (idx=0; idx < floats.Size(); idx ++)
{
varFloat& var = floats[idx];
sprintf(buf,".%f#", var.val );
stringKey += var.varName + buf;
}
stringKey+="VECTOR#";
for (idx = 0; idx< vectors.Size(); idx ++)
{
varVector& var = vectors[idx];
sprintf(buf,".%f_%f_%f_%f#", var.val.x, var.val.y, var.val.z, var.val.w);
stringKey += var.varName + buf;
}
stringKey+="ANIMS$";
for (idx = 0 ; idx < anims.Size() ; idx ++)
{
stringKey += anims[idx] + "$";
}
this->stringValid = true;
}
return this->stringKey.Get();
}
void
nAbstractPropBuilder::SetTo( nAbstractShaderNode* node)
{
n_assert(nKernelServer::ks);
int idx;
switch (thisType)
{
case NONE:
break;
case NMATERIAL:
if ( node->IsA(nmaterialnode))
{
//nMaterialNode* MaterialNode = (nMaterialNode*) node;
//MaterialNode->SetMaterial( this->material.Get() );
}
break;
case NSURFACE:
if ( node->IsA(nsurfacenode) )
{
nSurfaceNode* SurfaceNode = (nSurfaceNode*) node;
for (idx = 0; idx < shaders.Size() ; idx ++)
{
varShader& var = shaders[idx];
SurfaceNode->SetShader( nVariableServer::StringToFourCC(var.varName.Get()) , var.val.Get() );
}
}
break;
case SHADERTYPELIBRARY:
break;
}
for (idx = 0; idx < textures.Size() ; idx ++)
{
varTexture& var = textures[idx];
node->SetTexture( nShaderState::StringToParam( var.varName.Get()),
var.texName.Get() );
}
for (idx = 0; idx < floats.Size(); idx ++)
{
varFloat& var = floats[idx];
node->SetFloat( nShaderState::StringToParam( var.varName.Get()),
var.val);
}
for (idx = 0; idx < integers.Size(); idx++)
{
varInt& var = integers[idx];
node->SetInt( nShaderState::StringToParam( var.varName.Get())
, var.val);
}
for (idx = 0; idx < vectors.Size(); idx++)
{
varVector& var = vectors[idx];
node->SetVector( nShaderState::StringToParam( var.varName.Get() ),
var.val);
}
for (idx = 0 ; idx < anims.Size() ; idx ++)
{
node->AddAnimator( anims[idx].Get() );
}
}
void
nAbstractPropBuilder::operator +=(const nAbstractPropBuilder& rhs)
{
switch (rhs.thisType)
{
case NONE:
break;
case NMATERIAL:
if (this->thisType == NONE || this->thisType == NMATERIAL)
{
this->thisType = NMATERIAL;
if (rhs.matTypeIsValid)
{
this->matTypeIsValid = true;
this->matType += rhs.matType;
}
}
break;
case NSURFACE:
if (this->thisType == NONE || this->thisType == NSURFACE)
{
this->thisType = NSURFACE;
this->shaders += rhs.shaders;
}
break;
case SHADERTYPELIBRARY:
if (this->thisType == NONE || this->thisType == SHADERTYPELIBRARY)
{
this->thisType = SHADERTYPELIBRARY;
this->matTypeIsValid = true;
this->matType += rhs.matType;
if ( this->thisType == NONE )
{
this->materialTypeNameInLibrary = rhs.materialTypeNameInLibrary;
}
}
}
this->textures+= rhs.textures;
this->integers+= rhs.integers;
this->floats+= rhs.floats;
this->vectors+= rhs.vectors;
this->stringValid = false;
}
const char*
nAbstractPropBuilder::GetNameClass()
{
switch (thisType )
{
case nAbstractPropBuilder::NONE:
return "nabstractshadernode";
break;
case nAbstractPropBuilder::NMATERIAL :
return "nmaterialnode";
break;
case nAbstractPropBuilder::NSURFACE :
return "nsurfacenode";
break;
case nAbstractPropBuilder::SHADERTYPELIBRARY :
return "nmaterialnode";
break;
}
return "";
}
void
nAbstractPropBuilder::Reduce()
{
//@ todo remove unnecesary variables, textures , etc.... by material properties
} | [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
] | [
[
[
1,
460
]
]
] |
6319bd5e84e837fa93b3dc619ff1697c01676085 | b2d46af9c6152323ce240374afc998c1574db71f | /cursovideojuegos/theflostiproject/3rdParty/boost/libs/config/test/no_sfinae_pass.cpp | ec36a0ed667d4f6a44444dc4e30acc5cea2e5a42 | [] | no_license | bugbit/cipsaoscar | 601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4 | 52aa8b4b67d48f59e46cb43527480f8b3552e96d | refs/heads/master | 2021-01-10 21:31:18 | 2011-09-28 16:39:12 | 2011-09-28 16:39:12 | 33,032,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,146 | cpp |
// This file was automatically generated on Sun Jul 25 11:47:49 GMTDT 2004,
// by libs/config/tools/generate
// Copyright John Maddock 2002-4.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/config for the most recent version.
// Test file for macro BOOST_NO_SFINAE
// This file should compile, if it does not then
// BOOST_NO_SFINAE needs to be defined.
// see boost_no_sfinae.ipp for more details
// Do not edit this file, it was generated automatically by
// ../tools/generate from boost_no_sfinae.ipp on
// Sun Jul 25 11:47:49 GMTDT 2004
// Must not have BOOST_ASSERT_CONFIG set; it defeats
// the objective of this file:
#ifdef BOOST_ASSERT_CONFIG
# undef BOOST_ASSERT_CONFIG
#endif
#include <boost/config.hpp>
#include "test.hpp"
#ifndef BOOST_NO_SFINAE
#include "boost_no_sfinae.ipp"
#else
namespace boost_no_sfinae = empty_boost;
#endif
int main( int, char *[] )
{
return boost_no_sfinae::test();
}
| [
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
] | [
[
[
1,
39
]
]
] |
3823dc465196493bc1313f97a5040440f620e3ba | 6253ab92ce2e85b4db9393aa630bde24655bd9b4 | /Common/Ibeo/IbeoTahoeCalibration.h | e58f3b0ab7b8d6fe16ec041401df1c40bacbd649 | [] | no_license | Aand1/cornell-urban-challenge | 94fd4df18fd4b6cc6e12d30ed8eed280826d4aed | 779daae8703fe68e7c6256932883de32a309a119 | refs/heads/master | 2021-01-18 11:57:48 | 2008-10-01 06:43:18 | 2008-10-01 06:43:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,468 | h | #ifndef IBEO_TAHOE_CALIBRATION_H_SEPT_28_2007_SVL5
#define IBEO_TAHOE_CALIBRATION_H_SEPT_28_2007_SVL5
#include "../Math/Angle.h"
#include "../Fusion/Sensor.h"
#define __IBEO_SENSOR_CALIBRATION_CHEAT\
inline Sensor SensorCalibration(){\
Sensor ret;\
ret.SensorX = x;\
ret.SensorY = y;\
ret.SensorZ = z;\
ret.SensorYaw = yaw;\
ret.SensorPitch = pitch;\
ret.SensorRoll = roll;\
return ret;\
}
#define __IBEO_CALIBRATION_XYZ_YPR_RAD(X,Y,Z,YAW,PITCH,ROLL)\
const float x=(float)X),y=(float)(Y),z=(float)(Z),yaw=(float)(YAW),pitch=(float)(PITCH),roll=(float)(ROLL);\
__IBEO_SENSOR_CALIBRATION_CHEAT;
#define __IBEO_CALIBRATION_XYZ_YPR_DEG(X,Y,Z,YAW,PITCH,ROLL)\
const float x=(float)(X),y=(float)(Y),z=(float)(Z),yaw=Deg2Rad((float)(YAW)),pitch=Deg2Rad((float)(PITCH)),roll=Deg2Rad((float)(ROLL));\
__IBEO_SENSOR_CALIBRATION_CHEAT;
// all parameters IMU-relative
namespace IBEO_CALIBRATION{
namespace AUG_2007{
namespace FRONT_LEFT{
__IBEO_CALIBRATION_XYZ_YPR_DEG(3.5306,0.8,-0.5118,37.05,-1.1,-0.9);
}
namespace FRONT_CENTER{
__IBEO_CALIBRATION_XYZ_YPR_DEG(3.6449,0.0f,-0.0508,0,0,0);
}
namespace FRONT_RIGHT{
__IBEO_CALIBRATION_XYZ_YPR_DEG(3.5306,-0.8,-0.5118,-41.5,-.7,1);
}
}
namespace SEPT_21_2007{
namespace FRONT_LEFT{
__IBEO_CALIBRATION_XYZ_YPR_DEG(3.5306,0.8,-0.4118,-37.05,1.1,0.4);
}
namespace FRONT_CENTER{
__IBEO_CALIBRATION_XYZ_YPR_DEG(3.6449,0.0f,-0.0508,0,0,0);
}
namespace FRONT_RIGHT{
__IBEO_CALIBRATION_XYZ_YPR_DEG(3.5306,-0.8,-0.4118,41.5,.7,-.2);
}
}
namespace OCT_2_2007{
namespace FRONT_LEFT{
__IBEO_CALIBRATION_XYZ_YPR_DEG(3.5306,0.8,-0.4118,-37.05,1.1,0.4);
}
namespace FRONT_CENTER{
__IBEO_CALIBRATION_XYZ_YPR_DEG(3.6449,0.0f,-0.0508,0,0,0);
}
namespace FRONT_RIGHT{
__IBEO_CALIBRATION_XYZ_YPR_DEG(3.5306,-0.8,-0.4118,41.5,.9,-.3);
}
}
//OCT_2_2007
namespace CURRENT{
namespace FRONT_LEFT{
__IBEO_CALIBRATION_XYZ_YPR_DEG(3.5306,0.8,-0.4118,-37.05,1.1,0.4);
}
namespace FRONT_CENTER{
__IBEO_CALIBRATION_XYZ_YPR_DEG(3.6449,0.0f,-0.0508,0,0,0);
}
namespace FRONT_RIGHT{
__IBEO_CALIBRATION_XYZ_YPR_DEG(3.5306,-0.8,-0.4118,41.5,1,-.4);
}
}
};
#endif //IBEO_TAHOE_CALIBRATION_H_SEPT_28_2007_SVL5
| [
"anathan@5031bdca-8e6f-11dd-8a4e-8714b3728bc5"
] | [
[
[
1,
88
]
]
] |
1b8f3a25c8c5d2964f98b77819d83d1a653fd099 | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/nebula2/src/gui/nguihorisliderboxed_main.cc | 9cc715fba8a8b0bb24098504c8b93d1f9d188079 | [] | no_license | ugozapad/TheZombieEngine | 832492930df28c28cd349673f79f3609b1fe7190 | 8e8c3e6225c2ed93e07287356def9fbdeacf3d6a | refs/heads/master | 2020-04-30 11:35:36 | 2011-02-24 14:18:43 | 2011-02-24 14:18:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,355 | cc | #include "precompiled/pchngui.h"
//------------------------------------------------------------------------------
// nGuiHoriSliderBoxed_main.cc
// (C) 2004 RadonLabs GmbH
//------------------------------------------------------------------------------
#include "gui/nGuiHoriSliderBoxed.h"
#include "gui/nguiserver.h"
#include "gui/nguiskin.h"
nNebulaClass(nGuiHoriSliderBoxed, "nguiformlayout");
//--- MetaInfo ---------------------------------------------------------------
/**
@scriptclass
nGuiHoriSliderBoxed
@cppclass
nGuiHoriSliderBoxed
@superclass
nguiformlayout
@classinfo
Docs needed.
*/
//------------------------------------------------------------------------------
/**
*/
nGuiHoriSliderBoxed::nGuiHoriSliderBoxed() :
labelFont("GuiSmall"),
minValue(0),
maxValue(10),
curValue(0),
knobSize(1),
leftWidth(0.2f),
rightWidth(0.1f)
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
nGuiHoriSliderBoxed::~nGuiHoriSliderBoxed()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
void
nGuiHoriSliderBoxed::OnShow()
{
nGuiSkin* skin = nGuiServer::Instance()->GetSkin();
n_assert(skin);
nGuiFormLayout::OnShow();
kernelServer->PushCwd(this);
// text entry sizes
vector2 textSize = nGuiServer::Instance()->ComputeScreenSpaceBrushSize("textentry_n");
vector2 textMinSize(0.0f, textSize.y);
vector2 textMaxSize(1.0f, textSize.y);
// create slider widget
nGuiSlider2* slider = (nGuiSlider2*) kernelServer->New("nguislider2", "Slider");
n_assert(slider);
slider->SetRangeSize(float((this->maxValue - this->minValue) + this->knobSize));
slider->SetVisibleRangeStart(float(this->curValue - this->minValue));
slider->SetVisibleRangeSize(float(this->knobSize));
slider->SetHorizontal(true);
this->AttachForm(slider, Top, 0.0f);
this->AttachPos(slider, Left, this->leftWidth);
this->AttachPos(slider, Right, 1.0f - this->rightWidth);
slider->OnShow();
this->refSlider = slider;
const vector2& sliderMinSize = slider->GetMinSize();
const vector2& sliderMaxSize = slider->GetMaxSize();
// create left text label
nGuiTextLabel* leftLabel = (nGuiTextLabel*) kernelServer->New("nguitextlabel", "LeftLabel");
n_assert(leftLabel);
leftLabel->SetText(this->leftText.Get());
leftLabel->SetFont(this->GetLabelFont());
leftLabel->SetAlignment(nGuiTextLabel::Right);
leftLabel->SetColor(skin->GetLabelTextColor());
leftLabel->SetMinSize(vector2(0.0f, sliderMinSize.y));
leftLabel->SetMaxSize(vector2(1.0f, sliderMaxSize.y));
this->AttachForm(leftLabel, Top, 0.0f);
this->AttachForm(leftLabel, Left, 0.0f);
this->AttachPos(leftLabel, Right, this->leftWidth);
leftLabel->OnShow();
this->refLeftLabel = leftLabel;
// create right text entry
nGuiTextEntry* textEntry = (nGuiTextEntry*) kernelServer->New("nguitextentry", "RightEntry");
n_assert(textEntry);
textEntry->SetText("0");
textEntry->SetFont("GuiSmall");
textEntry->SetAlignment(nGuiTextLabel::Left);
textEntry->SetColor(vector4(0.0f, 0.0f, 0.0f, 1.0f));
textEntry->SetMinSize(textMinSize);
textEntry->SetMaxSize(textMaxSize);
textEntry->SetDefaultBrush("textentry_n");
textEntry->SetPressedBrush("textentry_p");
textEntry->SetHighlightBrush("textentry_h");
textEntry->SetDisabledBrush("textentry_d");
textEntry->SetCursorBrush("textcursor");
textEntry->SetColor(vector4(0.85f, 0.85f, 0.85f, 1.0f));
this->AttachForm(textEntry, Top, 0.0f);
this->AttachForm(textEntry, Right, 0.005f);
this->AttachPos(textEntry, Left, 1.0f - this->rightWidth);
textEntry->OnShow();
this->refTextEntry = textEntry;
kernelServer->PopCwd();
this->SetMinSize(sliderMinSize);
this->SetMaxSize(sliderMaxSize);
this->UpdateLayout(this->rect);
nGuiServer::Instance()->RegisterEventListener(this);
}
//------------------------------------------------------------------------------
/**
*/
void
nGuiHoriSliderBoxed::SetMaxLength(int l)
{
this->refTextEntry->SetMaxLength(l);
}
//------------------------------------------------------------------------------
/**
*/
void
nGuiHoriSliderBoxed::OnHide()
{
nGuiServer::Instance()->UnregisterEventListener(this);
this->ClearAttachRules();
if (this->refSlider.isvalid())
{
this->refSlider->Release();
n_assert(!this->refSlider.isvalid());
}
if (this->refLeftLabel.isvalid())
{
this->refLeftLabel->Release();
n_assert(!this->refLeftLabel.isvalid());
}
if (this->refTextEntry.isvalid())
{
this->refTextEntry->Release();
n_assert(!this->refTextEntry.isvalid());
}
nGuiFormLayout::OnHide();
}
//------------------------------------------------------------------------------
/**
*/
void
nGuiHoriSliderBoxed::OnFrame()
{
if (this->refSlider.isvalid())
{
this->curValue = this->minValue + int(this->refSlider->GetVisibleRangeStart());
// update left and right label formatted strings
char buf[1024];
snprintf(buf, sizeof(buf), this->leftText.Get(), this->curValue);
this->refLeftLabel->SetText(buf);
snprintf(buf, sizeof(buf), this->rightText.Get(), this->curValue);
if (! this->refTextEntry->GetActive())
{
this->refTextEntry->SetText(buf);
this->refTextEntry->SetInitialCursorPos(nGuiTextLabel::Right);
}
}
nGuiFormLayout::OnFrame();
}
// juanga (from Nebula2SDK_2004)
// added 29sept04: replicates the event, allowing handle values WHILE dragging the slider knob
void
nGuiHoriSliderBoxed::OnEvent(const nGuiEvent& event)
{
switch(event.GetType())
{
case nGuiEvent::Char:
case nGuiEvent::KeyUp:
{
if (this->refTextEntry.isvalid() && (event.GetWidget() == this->refTextEntry))
{
// update slider
this->SetValue(atoi(this->refTextEntry->GetText()));
// replicate event, to process some other changes if needed on derivated classes
nGuiEvent event(this, nGuiEvent::SliderChanged);
nGuiServer::Instance()->PutEvent(event);
}
}
break;
case nGuiEvent::SliderChanged:
{
if (this->refSlider.isvalid() && (event.GetWidget() == this->refSlider))
{
// replicate event
nGuiEvent event(this, nGuiEvent::SliderChanged);
nGuiServer::Instance()->PutEvent(event);
// if the user touches the slider, disable cursor on textentry, so the value will be updated
//this->refTextEntry->SetActive(false);
}
}
break;
default:
{
if (event.GetWidget() == this->refTextEntry)
{
//this->SetValue(atoi(this->refTextEntry->GetText()));
}
}
break;
}
}
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
] | [
[
[
1,
234
]
]
] |
cc5ac3f7415b74200f0e7b1365b958e5f617cae9 | 36bf908bb8423598bda91bd63c4bcbc02db67a9d | /Include/CPaintLib.h | 12371931de4b91215b0ef83d8351b8a048d16b7c | [] | no_license | code4bones/crawlpaper | edbae18a8b099814a1eed5453607a2d66142b496 | f218be1947a9791b2438b438362bc66c0a505f99 | refs/heads/master | 2021-01-10 13:11:23 | 2011-04-14 11:04:17 | 2011-04-14 11:04:17 | 44,686,513 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,358 | h | /*
CPaintLib.h
Classe derivata per interfaccia con paintlib.
Luca Piergentili, 01/09/00
lpiergentili@yahoo.com
Ad memoriam - Nemo me impune lacessit.
*/
#ifndef _CPAINTLIB_H
#define _CPAINTLIB_H 1
#include "window.h"
#include "ImageConfig.h"
#ifdef HAVE_PAINTLIB_LIBRARY
#include "ImageLibraryName.h"
#include "CImage.h"
#include "CImageParams.h"
#include "paintlib.h"
/*
CPaintLib
*/
class CPaintLib : public CImage
{
public:
CPaintLib();
virtual ~CPaintLib() {}
LPCSTR GetLibraryName (void);
UINT GetWidth (void);
UINT GetHeight (void);
float GetXRes (void);
float GetYRes (void);
void SetXRes (float nXRes);
void SetYRes (float nYRes);
int GetURes (void);
void SetURes (UINT);
void GetDPI (float&,float&);
int GetCompression (void);
void SetCompression (int);
UINT GetNumColors (void);
UINT GetBPP (void);
UINT ConvertToBPP (UINT nBitsPerPixel,UINT nFlags,RGBQUAD *pPalette,UINT nColors);
COLORREF GetPixel (UINT x,UINT y);
void SetPixel (UINT x,UINT y,COLORREF colorref);
void* GetPixels (void);
LPBITMAPINFO GetBMI (void);
HBITMAP GetBitmap (void);
UINT GetMemUsed (void);
HDIB GetDIB (DIBINFO* pDibInfo = NULL);
BOOL SetDIB (HDIB hDib,DIBINFO* pDibInfo = NULL);
int GetDIBOrder (void);
BOOL SetPalette (UINT nIndex,UINT nColors,RGBQUAD* pPalette);
BOOL Create (BITMAPINFO* pBitmapInfo,void *pData = NULL);
BOOL Load (LPCSTR lpcszFileName);
BOOL Save (void);
BOOL Save (LPCSTR lpcszFileName,LPCSTR lpcszFormat,DWORD dwFlags);
BOOL Stretch (RECT& drawRect,BOOL bAspectRatio = TRUE);
BOOL SetImageParamsDefaultValues(CImageParams*);
BOOL SetImageParamsMinMax(CImageParams*);
UINT Grayscale (CImageParams*);
UINT Halftone (CImageParams*);
UINT Invert (CImageParams*);
UINT Rotate90Left (CImageParams*);
UINT Rotate90Right (CImageParams*);
UINT Rotate180 (CImageParams*);
UINT Size (CImageParams*);
protected:
BOOL _Load (LPCSTR lpcszFileName);
BOOL _Save (LPCSTR lpcszFileName,LPCSTR lpcszFormat,DWORD dwFlags);
void Rotate (double);
BOOL ConvertToBPP (UINT nBPP);
CWinBmp m_Image;
};
#endif // HAVE_PAINTLIB_LIBRARY
#endif // _CPAINTLIB_H
| [
"luca.pierge@gmail.com"
] | [
[
[
1,
90
]
]
] |
616f2accd7c6424a06ccf79f90725a26496e61c4 | 1ad310fc8abf44dbcb99add43f6c6b4c97a3767c | /samples_c++/cc/sprite_anime/App.cc | 38349b73dbc2e97f10ca3d59a78e2db2ddd4a7e1 | [] | no_license | Jazzinghen/spamOSEK | fed44979b86149809f0fe70355f2117e9cb954f3 | 7223a2fb78401e1d9fa96ecaa2323564c765c970 | refs/heads/master | 2020-06-01 03:55:48 | 2010-05-19 14:37:30 | 2010-05-19 14:37:30 | 580,640 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,717 | cc | #include "App.h"
//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[];
//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,
};
//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};
//the set of all animations for shiki since we'll be chaining them together
const char* shikiAnimset[] =
{
shikiAppearAnim,
shikiWalkAnim,
shikiTauntAnim,
shikiBreatheAnim
};
App::App()
: mCurrentAnim(0)
, mShiki(shikiDataSet[0], shikiAnimset[0])
{
mShiki.setScriptInterface(this);
mShiki.setID(eSprite_Shiki);
}
void App::init()
{
mScreen.newSprite(&mShiki);
}
//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;
}
}
void App::runShikiAnim(Sprite *sprite, int command)
{
if(++mCurrentAnim == 4)
{
mCurrentAnim = 0;
}
sprite->changeGfx(shikiDataSet[mCurrentAnim], shikiAnimset[mCurrentAnim]);
}
void App::update()
{
mScreen.update();
}
| [
"jazzinghen@Jehuty.(none)"
] | [
[
[
1,
71
]
]
] |
8e4c0d4294df29f5caee21d5b4a854052565a0ec | ef432f1b63535630ba472d82e40b0ff216cb517a | /NFS2Prog.cpp | f5770be889c1364abdccfc72b4b139ba3438e8a4 | [] | no_license | noodle1983/winnfsd-nd | 53e258f9b85d65e0c20cbfece4f22e19fb8d257f | c49277be0ad013d408898320dd2bcc456199f373 | refs/heads/master | 2016-09-06 02:50:16 | 2010-08-14 10:10:53 | 2010-08-14 10:10:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,149 | cpp | #include "NFSProg.h"
#include "FileTable.h"
#include <string.h>
#include <io.h>
#include <direct.h>
#include <sys/stat.h>
#include <windows.h>
enum
{
NFSPROC_NULL = 0,
NFSPROC_GETATTR = 1,
NFSPROC_SETATTR = 2,
NFSPROC_ROOT = 3,
NFSPROC_LOOKUP = 4,
NFSPROC_READLINK = 5,
NFSPROC_READ = 6,
NFSPROC_WRITECACHE = 7,
NFSPROC_WRITE = 8,
NFSPROC_CREATE = 9,
NFSPROC_REMOVE = 10,
NFSPROC_RENAME = 11,
NFSPROC_LINK = 12,
NFSPROC_SYMLINK = 13,
NFSPROC_MKDIR = 14,
NFSPROC_RMDIR = 15,
NFSPROC_READDIR = 16,
NFSPROC_STATFS = 17
};
enum
{
NFS_OK = 0,
NFSERR_PERM = 1,
NFSERR_NOENT = 2,
NFSERR_IO = 5,
NFSERR_NXIO = 6,
NFSERR_ACCES = 13,
NFSERR_EXIST = 17,
NFSERR_NODEV = 19,
NFSERR_NOTDIR = 20,
NFSERR_ISDIR = 21,
NFSERR_FBIG = 27,
NFSERR_NOSPC = 28,
NFSERR_ROFS = 30,
NFSERR_NAMETOOLONG = 63,
NFSERR_NOTEMPTY = 66,
NFSERR_DQUOT = 69,
NFSERR_STALE = 70,
NFSERR_WFLUSH = 99,
};
enum
{
NFNON = 0,
NFREG = 1,
NFDIR = 2,
NFBLK = 3,
NFCHR = 4,
NFLNK = 5,
};
typedef void(CNFS2Prog::*PPROC)(void);
CNFS2Prog::CNFS2Prog() : CRPCProg()
{
m_nUID = m_nGID = 0;
}
CNFS2Prog::~CNFS2Prog()
{
}
void CNFS2Prog::SetUserID(unsigned int nUID, unsigned int nGID)
{
m_nUID = nUID;
m_nGID = nGID;
}
int CNFS2Prog::Process(IInputStream *pInStream, IOutputStream *pOutStream, ProcessParam *pParam)
{
static PPROC pf[] = {&CNFS2Prog::ProcedureNULL, &CNFS2Prog::ProcedureGETATTR, &CNFS2Prog::ProcedureSETATTR, &CNFS2Prog::ProcedureNOTIMP, &CNFS2Prog::ProcedureLOOKUP, &CNFS2Prog::ProcedureNOTIMP, &CNFS2Prog::ProcedureREAD, &CNFS2Prog::ProcedureNOTIMP, &CNFS2Prog::ProcedureWRITE, &CNFS2Prog::ProcedureCREATE, &CNFS2Prog::ProcedureREMOVE, &CNFS2Prog::ProcedureRENAME, &CNFS2Prog::ProcedureNOTIMP, &CNFS2Prog::ProcedureNOTIMP, &CNFS2Prog::ProcedureMKDIR, &CNFS2Prog::ProcedureRMDIR, &CNFS2Prog::ProcedureREADDIR, &CNFS2Prog::ProcedureSTATFS};
PrintLog("NFS ");
if (pParam->nProc >= sizeof(pf) / sizeof(PPROC))
{
ProcedureNOTIMP();
PrintLog("\n");
return PRC_NOTIMP;
}
m_pInStream = pInStream;
m_pOutStream = pOutStream;
m_nResult = PRC_OK;
(this->*pf[pParam->nProc])();
PrintLog("\n");
return m_nResult;
}
void CNFS2Prog::ProcedureNULL(void)
{
PrintLog("NULL");
}
void CNFS2Prog::ProcedureGETATTR(void)
{
char *path;
PrintLog("GETATTR");
path = GetPath();
if (!CheckFile(path))
return;
m_pOutStream->Write(NFS_OK);
WriteFileAttributes(path);
}
void CNFS2Prog::ProcedureSETATTR(void)
{
char *path;
unsigned long nMode, nAttr;
PrintLog("SETATTR");
path = GetPath();
if (!CheckFile(path))
return;
m_pInStream->Read(&nMode);
nAttr = 0;
if ((nMode & 0x100) != 0)
nAttr |= S_IREAD;
if ((nMode & 0x80) != 0)
nAttr |= S_IWRITE;
_chmod(path, nAttr);
m_pOutStream->Write(NFS_OK);
WriteFileAttributes(path);
}
void CNFS2Prog::ProcedureLOOKUP(void)
{
char *path;
PrintLog("LOOKUP");
path = GetFullPath();
if (!CheckFile(path))
return;
m_pOutStream->Write(NFS_OK);
m_pOutStream->Write(GetFileHandle(path), FHSIZE);
WriteFileAttributes(path);
}
void CNFS2Prog::ProcedureREAD(void)
{
char *path;
unsigned long nOffset, nCount, nTotalCount;
FILE *file;
char *pBuffer;
unsigned char opaque[3] = {0, 0, 0};
PrintLog("READ");
path = GetPath();
if (!CheckFile(path))
return;
m_pInStream->Read(&nOffset);
m_pInStream->Read(&nCount);
m_pInStream->Read(&nTotalCount);
file = fopen(path, "rb");
fseek(file, nOffset, SEEK_SET);
pBuffer = new char[nCount];
nCount = fread(pBuffer, sizeof(char), nCount, file);
fclose(file);
m_pOutStream->Write(NFS_OK);
WriteFileAttributes(path);
m_pOutStream->Write(nCount); //length
m_pOutStream->Write(pBuffer, nCount); //contents
nCount &= 3;
if (nCount != 0)
m_pOutStream->Write(opaque, 4 - nCount); //opaque bytes
delete[] pBuffer;
}
void CNFS2Prog::ProcedureWRITE(void)
{
char *path;
unsigned long nBeginOffset, nOffset, nTotalCount, nCount;
FILE *file;
char *pBuffer;
PrintLog("WRITE");
path = GetPath();
if (!CheckFile(path))
return;
m_pInStream->Read(&nBeginOffset);
m_pInStream->Read(&nOffset);
m_pInStream->Read(&nTotalCount);
m_pInStream->Read(&nCount);
pBuffer = new char[nCount];
m_pInStream->Read(pBuffer, nCount);
file = fopen(path, "r+b");
fseek(file, nOffset, SEEK_SET);
nCount = fwrite(pBuffer, sizeof(char), nCount, file);
fclose(file);
delete[] pBuffer;
m_pOutStream->Write(NFS_OK);
WriteFileAttributes(path);
}
void CNFS2Prog::ProcedureCREATE(void)
{
char *path;
FILE *file;
PrintLog("CREATE");
path = GetFullPath();
if (path == NULL)
return;
file = fopen(path, "wb");
fclose(file);
m_pOutStream->Write(NFS_OK);
m_pOutStream->Write(GetFileHandle(path), FHSIZE);
WriteFileAttributes(path);
}
void CNFS2Prog::ProcedureREMOVE(void)
{
char *path;
PrintLog("REMOVE");
path = GetFullPath();
if (!CheckFile(path))
return;
remove(path);
m_pOutStream->Write(NFS_OK);
}
void CNFS2Prog::ProcedureRENAME(void)
{
char *path;
char pathFrom[MAXPATHLEN], *pathTo;
PrintLog("RENAME");
path = GetFullPath();
if (!CheckFile(path))
return;
strcpy(pathFrom, path);
pathTo = GetFullPath();
RenameFile(pathFrom, pathTo);
m_pOutStream->Write(NFS_OK);
}
void CNFS2Prog::ProcedureMKDIR(void)
{
char *path;
PrintLog("MKDIR");
path = GetFullPath();
if (path == NULL)
return;
_mkdir(path);
m_pOutStream->Write(NFS_OK);
m_pOutStream->Write(GetFileHandle(path), FHSIZE);
WriteFileAttributes(path);
}
void CNFS2Prog::ProcedureRMDIR(void)
{
char *path;
PrintLog("RMDIR");
path = GetFullPath();
if (!CheckFile(path))
return;
_rmdir(path);
m_pOutStream->Write(NFS_OK);
}
void CNFS2Prog::ProcedureREADDIR(void)
{
unsigned char opaque[3] = {0, 0, 0};
char *path, filePath[MAXPATHLEN + 1];
int handle;
struct _finddata_t fileinfo;
unsigned long count;
unsigned int nLen;
PrintLog("READDIR");
path = GetPath();
if (!CheckFile(path))
return;
m_pOutStream->Write(NFS_OK);
sprintf(filePath, "%s\\*", path);
count = 0;
handle = _findfirst(filePath, &fileinfo);
if (handle)
{
do
{
m_pOutStream->Write(1); //value follows
sprintf(filePath, "%s\\%s", path, fileinfo.name);
m_pOutStream->Write(GetFileID(filePath)); //file id
m_pOutStream->Write(nLen = strlen(fileinfo.name));
m_pOutStream->Write(fileinfo.name, nLen);
nLen &= 3;
if (nLen != 0)
m_pOutStream->Write(opaque, 4 - nLen); //opaque bytes
m_pOutStream->Write(++count); //cookie
} while (_findnext(handle, &fileinfo) == 0);
_findclose(handle);
}
m_pOutStream->Write(0); //no value follows
m_pOutStream->Write(1); //EOF
}
void CNFS2Prog::ProcedureSTATFS(void)
{
char *path;
int nDrive;
struct _diskfree_t data;
PrintLog("STATFS");
path = GetPath();
if (!CheckFile(path))
return;
if (path[0] >= 'a' && path[0] <= 'z')
nDrive = path[0] - 'a' + 1;
else if (path[0] >= 'A' && path[0] <= 'Z')
nDrive = path[0] - 'A' + 1;
else
{
m_pOutStream->Write(NFSERR_NOENT);
return;
}
_getdiskfree(nDrive, &data);
m_pOutStream->Write(NFS_OK);
m_pOutStream->Write(data.sectors_per_cluster * data.bytes_per_sector); //transfer size
m_pOutStream->Write(data.sectors_per_cluster * data.bytes_per_sector); //block size
m_pOutStream->Write(data.total_clusters); //total blocks
m_pOutStream->Write(data.avail_clusters); //free blocks
m_pOutStream->Write(data.avail_clusters); //available blocks
}
void CNFS2Prog::ProcedureNOTIMP(void)
{
PrintLog("NOTIMP");
m_nResult = PRC_NOTIMP;
}
char *CNFS2Prog::GetPath(void)
{
unsigned char fhandle[FHSIZE];
char *path;
m_pInStream->Read(fhandle, FHSIZE);
path = GetFilePath(fhandle);
if (path == NULL)
return NULL;
PrintLog(" %s", path);
return path;
}
char *CNFS2Prog::GetFullPath(void)
{
char *path;
static char filePath[MAXPATHLEN + 1];
unsigned int nLen1, nBytes;
unsigned long nLen2;
path = GetPath();
if (path == NULL)
return NULL;
nLen1 = strlen(path);
m_pInStream->Read(&nLen2);
sprintf(filePath, "%s\\", path);
m_pInStream->Read(filePath + nLen1 + 1, nLen2);
filePath[nLen1 + 1 + nLen2] = '\0';
PrintLog("%s", filePath + nLen1);
if ((nLen2 & 3) != 0)
m_pInStream->Read(&nBytes, 4 - (nLen2 & 3));
return filePath;
}
bool CNFS2Prog::CheckFile(char *path)
{
if (path == NULL)
{
m_pOutStream->Write(NFSERR_STALE);
return false;
}
if (!FileExists(path))
{
m_pOutStream->Write(NFSERR_NOENT);
return false;
}
return true;
}
bool CNFS2Prog::WriteFileAttributes(char *path)
{
struct stat data;
unsigned long nValue;
if (stat(path, &data) != 0)
return false;
switch (data.st_mode & S_IFMT)
{
case S_IFREG:
nValue = NFREG;
break;
case S_IFDIR:
nValue = NFDIR;
break;
case S_IFCHR:
nValue = NFCHR;
break;
default:
nValue = NFNON;
break;
}
m_pOutStream->Write(nValue); //type
if (nValue == NFREG)
nValue = 0x8000;
else if (nValue == NFDIR)
nValue = 0x4000;
else
nValue = 0;
if ((data.st_mode & S_IREAD) != 0)
nValue |= 0x124;
if ((data.st_mode & S_IWRITE) != 0)
nValue |= 0x92;
//if ((data.st_mode & S_IEXEC) != 0)
nValue |= 0x49;
m_pOutStream->Write(nValue); //mode
m_pOutStream->Write(data.st_nlink); //nlink
m_pOutStream->Write(m_nUID); //uid
m_pOutStream->Write(m_nGID); //gid
m_pOutStream->Write(data.st_size); //size
m_pOutStream->Write(8192); //blocksize
m_pOutStream->Write(0); //rdev
m_pOutStream->Write((data.st_size + 8191) / 8192); //blocks
m_pOutStream->Write(4); //fsid
m_pOutStream->Write(GetFileID(path)); //fileid
m_pOutStream->Write(data.st_atime); //atime
m_pOutStream->Write(0); //atime
m_pOutStream->Write(data.st_mtime); //mtime
m_pOutStream->Write(0); //mtime
m_pOutStream->Write(data.st_ctime); //ctime
m_pOutStream->Write(0); //ctime
return true;
}
| [
"noodle1983@126.com"
] | [
[
[
1,
466
]
]
] |
e640252cbe72e57d898dbfa08d22087d7b03eb62 | 61c263eb77eb64cf8ab42d2262fc553ac51a6399 | /src/Command.cpp | 159a8add0c9b9be9607029b56d9a413ea0dd41b2 | [] | no_license | ycaihua/fingermania | 20760830f6fe7c48aa2332b67f455eef8f9246a3 | daaa470caf02169ea6533669aa511bf59f896805 | refs/heads/master | 2021-01-20 09:36:38 | 2011-01-23 12:31:19 | 2011-01-23 12:31:19 | 40,102,565 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,118 | cpp | #include "global.h"
#include "Command.h"
#include "RageUtil.h"
#include "RageLog.h"
#include "arch/Dialog/Dialog.h"
#include "Foreach.h"
RString Command::GetName() const
{
if (m_vsArgs.empty())
return RString();
RString s = m_vArgs[0];
Trim(s);
return s;
}
Command::Arg Command::GetArg(unsigned index) const
{
Arg a;
if (index < m_vsArgs.size())
a.s = m_vsArgs[index];
return a;
}
void Command::Load(const RString& sCommand)
{
m_vsArgs.clear();
split(sCommand, ",", m_vsArgs, false);
}
RString Command::GetOriginalCommandString() const
{
return join(",", m_vsArgs);
}
static void SplitWithQuotes(const RString sSource, const char Delimitor, vector<RString>& asOut, const bool bIgnoreEmpty)
{
if (sSource.empty())
return;
size_t startpos = 0;
do
{
size_t pos = startpos;
while (pos < sSource.size())
{
if (sSource[pos] == Delimitor)
break;
if (sSource[pos] == '"' || sSource[pos] == '\'')
{
pos = sSource.find(sSource[pos], pos + 1);
if (pos == string::npos)
pos = sSource.size();
else
++pos;
}
else
++pos;
}
if (pos - startpos > 0 || !bIgnoreEmpty)
{
if (startpos == 0 && pos - startpos == sSource.size())
asOut.push_back(sSource);
else
{
const RString AddCString = sSource.substr( startpos, pos-startpos );
asOut.push_back( AddCString );
}
}
startpos = pos + 1;
} while (startpos <= sSource.size());
}
RString Commands::GetOriginalCommandString() const
{
RString s;
FOREACH_CONST(Command, v, c)
s += c->GetOriginalCommandString();
return s;
}
void ParseCommands(const RString& sCommands, Commands& vCommandOut)
{
vector<RString> vsCommands;
SplitWithQuotes(sCommands, ";", vsCommands, true);
vCommandsOut.resize(vsCommands.size());
for (unsigned i = 0; i < vsCommands.size(); i++)
{
Command& cmd = vCommandOut.v[i];
cmd.Load(vsCommands[i]);
}
}
Commands ParseCommands(const RString& sCommands)
{
Commands vCommands;
ParseCommands(sCommands, vCommands);
return vCommands;
}
| [
"davidleee121@gmail.com"
] | [
[
[
1,
105
]
]
] |
62388e66d8a045655077cbf90e914fab071b3740 | 2ca3ad74c1b5416b2748353d23710eed63539bb0 | /Src/DharaniDev/DharaniDev/DharaniDev.h | 8d114c6a318efe41a8c56d2e19f6a44f16716d0c | [] | no_license | sjp38/lokapala | 5ced19e534bd7067aeace0b38ee80b87dfc7faed | dfa51d28845815cfccd39941c802faaec9233a6e | refs/heads/master | 2021-01-15 16:10:23 | 2009-06-03 14:56:50 | 2009-06-03 14:56:50 | 32,124,140 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 528 | h | // DharaniDev.h : main header file for the PROJECT_NAME application
//
#pragma once
#ifndef __AFXWIN_H__
#error "include 'stdafx.h' before including this file for PCH"
#endif
#include "resource.h" // main symbols
// CDharaniDevApp:
// See DharaniDev.cpp for the implementation of this class
//
class CDharaniDevApp : public CWinApp
{
public:
CDharaniDevApp();
// Overrides
public:
virtual BOOL InitInstance();
// Implementation
DECLARE_MESSAGE_MAP()
};
extern CDharaniDevApp theApp; | [
"nilakantha38@b9e76448-5c52-0410-ae0e-a5aea8c5d16c"
] | [
[
[
1,
31
]
]
] |
1c5acf49becbe5d98c5509a3fc63b7ae0e10815b | ca99bc050dbc58be61a92e04f2a80a4b83cb6000 | /Game/src/Entities/Tux.cpp | 150fd862b5c7e381ea3cbf05b110ecb526a79f82 | [] | no_license | NicolasBeaudrot/angry-tux | e26c619346c63a468ad3711de786e94f5b78a2f1 | 5a8259f57ba59db9071158a775948d06e424a9a8 | refs/heads/master | 2021-01-06 20:41:23 | 2011-04-14 18:28:04 | 2011-04-14 18:28:04 | 32,141,181 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,196 | cpp | #include "Tux.h"
Tux::Tux(sf::RenderWindow* app
,sf::Vector2i& position
,std::string& path
,int type
,b2World* world) : Entity(app, position, path = "tuxs/" + path, 0){
_type = type;
_fire = false;
//Physics definition
b2BodyDef bd;
bd.position.Set(_position.x, _position.y);
bd.type = b2_dynamicBody;
bd.angularDamping = 0.01f;
b2CircleShape circle;
circle.m_radius = _image->GetWidth() / 2.0f;
b2FixtureDef fixtureDef;
fixtureDef.shape = &circle;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.3f;
fixtureDef.restitution = 0.3f;
fixtureDef.filter.groupIndex = -type;
_tuxBody = world->CreateBody(&bd);
_tuxBody->CreateFixture(&fixtureDef);
b2MassData mass_data;
mass_data.center = b2Vec2(0,0);
mass_data.mass = 250.0f;
mass_data.I = 600.0f;
_tuxBody->SetMassData(&mass_data);
_sprite.SetCenter(_image->GetWidth()/2, _image->GetHeight()/2);
}
Tux::~Tux() {
}
void Tux::mouseReleased(sf::Vector2f firstPosition, sf::Vector2f secondPosition, float time_elapse) {
firstPosition = Conversion::to_sfmlcoord(firstPosition);
secondPosition = Conversion::to_sfmlcoord(secondPosition);
int K = 1000000;
float angle = Algorithm::getAngle(firstPosition, secondPosition);
std::cout << "Angle: " << angle << std::endl;
_force = b2Vec2(cos(Conversion::to_radian(angle)) * K, sin(Conversion::to_radian(angle)) * K);
_tuxBody->ApplyForce(_force, _tuxBody->GetWorldCenter());
_fire = true;
cpt=0;
}
void Tux::render() {
if (_fire) {
if (_timer.GetElapsedTime() > 0.5) {
if (cpt < 3) {
_tuxBody->ApplyForce(_force, _tuxBody->GetWorldCenter());
cpt++;
} else {
_fire = false;
}
_timer.Reset();
}
}
sf::Vector2i position_sfml = Conversion::to_sfmlcoord(_tuxBody->GetPosition().x, _tuxBody->GetPosition().y);
_sprite.SetPosition(position_sfml.x, position_sfml.y);
_sprite.SetRotation(Conversion::to_degres(_tuxBody->GetAngle()));
_app->Draw(_sprite);
}
| [
"nicolas.beaudrot@43db0318-7ac6-f280-19a0-2e79116859ad"
] | [
[
[
1,
74
]
]
] |
b4e1ed7293aadfee796e885c8849da09913d34be | 9433cf978aa6b010903c134d77c74719f22efdeb | /src/svl/Mat.cpp | 7ad818ded478cf117e5f7ab58ec65a95a5986625 | [] | no_license | brandonagr/gpstracktime | 4666575cb913db2c9b3b8aa6b40a3ba1a3defb2f | 842bfd9698ec48debb6756a9acb2f40fd6041f9c | refs/heads/master | 2021-01-20 07:10:58 | 2008-09-24 05:44:56 | 2008-09-24 05:44:56 | 32,090,265 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,309 | cpp | /*
File: Mat.cpp
Function: Implements Mat.h
Author(s): Andrew Willmott
Copyright: (c) 1995-2001, Andrew Willmott
*/
#include "svl/Mat.h"
#include <cctype>
#include <cstring>
#include <cstdarg>
#include <iomanip>
// --- Mat Constructors & Destructors -----------------------------------------
Mat::Mat(Int rows, Int cols, ZeroOrOne k) : rows(rows), cols(cols)
{
Assert(rows > 0 && cols > 0, "(Mat) illegal matrix size");
data = new Real[rows * cols];
MakeDiag(k);
}
Mat::Mat(Int rows, Int cols, Block k) : rows(rows), cols(cols)
{
Assert(rows > 0 && cols > 0, "(Mat) illegal matrix size");
data = new Real[rows * cols];
MakeBlock(k);
}
Mat::Mat(Int rows, Int cols, double elt0, ...) : rows(rows), cols(cols)
// The double is hardwired here because it is the only type that will work
// with var args and C++ real numbers.
{
Assert(rows > 0 && cols > 0, "(Mat) illegal matrix size");
va_list ap;
Int i, j;
data = new Real[rows * cols];
va_start(ap, elt0);
SetReal(data[0], elt0);
for (i = 1; i < cols; i++)
SetReal(Elt(0, i), va_arg(ap, double));
for (i = 1; i < rows; i++)
for (j = 0; j < cols; j++)
SetReal(Elt(i, j), va_arg(ap, double));
va_end(ap);
}
Mat::Mat(const Mat &m) : cols(m.cols)
{
Assert(m.data != 0, "(Mat) Can't construct from null matrix");
rows = m.Rows();
UInt elts = rows * cols;
data = new Real[elts];
#ifdef VL_USE_MEMCPY
memcpy(data, m.data, elts * sizeof(Real));
#else
for (UInt i = 0; i < elts; i++)
data[i] = m.data[i];
#endif
}
Mat::Mat(const Mat2 &m) : data(m.Ref()), rows(2 | VL_REF_FLAG), cols(2)
{
}
Mat::Mat(const Mat3 &m) : data(m.Ref()), rows(3 | VL_REF_FLAG), cols(3)
{
}
Mat::Mat(const Mat4 &m) : data(m.Ref()), rows(4 | VL_REF_FLAG), cols(4)
{
}
// --- Mat Assignment Operators -----------------------------------------------
Mat &Mat::operator = (const Mat &m)
{
if (!IsRef())
SetSize(m.Rows(), m.Cols());
else
Assert(Rows() == m.Rows(), "(Mat::=) Matrix rows don't match");
for (Int i = 0; i < Rows(); i++)
SELF[i] = m[i];
return(SELF);
}
Mat &Mat::operator = (const Mat2 &m)
{
if (!IsRef())
SetSize(m.Rows(), m.Cols());
else
Assert(Rows() == m.Rows(), "(Mat::=) Matrix rows don't match");
for (Int i = 0; i < Rows(); i++)
SELF[i] = m[i];
return(SELF);
}
Mat &Mat::operator = (const Mat3 &m)
{
if (!IsRef())
SetSize(m.Rows(), m.Cols());
else
Assert(Rows() == m.Rows(), "(Mat::=) Matrix rows don't match");
for (Int i = 0; i < Rows(); i++)
SELF[i] = m[i];
return(SELF);
}
Mat &Mat::operator = (const Mat4 &m)
{
if (!IsRef())
SetSize(m.Rows(), m.Cols());
else
Assert(Rows() == m.Rows(), "(Mat::=) Matrix rows don't match");
for (Int i = 0; i < Rows(); i++)
SELF[i] = m[i];
return(SELF);
}
Void Mat::SetSize(Int nrows, Int ncols)
{
UInt elts = nrows * ncols;
Assert(nrows > 0 && ncols > 0, "(Mat::SetSize) Illegal matrix size.");
UInt oldElts = Rows() * Cols();
if (IsRef())
{
// Abort! We don't allow this operation on references.
_Error("(Mat::SetSize) Trying to resize a matrix reference");
}
rows = nrows;
cols = ncols;
// Don't reallocate if we already have enough storage
if (elts <= oldElts)
return;
// Otherwise, delete old storage and reallocate
delete[] data;
data = 0;
data = new Real[elts]; // may throw an exception
}
Void Mat::SetSize(const Mat &m)
{
SetSize(m.Rows(), m.Cols());
}
Void Mat::MakeZero()
{
#ifdef VL_USE_MEMCPY
memset(data, 0, sizeof(Real) * Rows() * Cols());
#else
Int i;
for (i = 0; i < Rows(); i++)
SELF[i] = vl_zero;
#endif
}
Void Mat::MakeDiag(Real k)
{
Int i, j;
for (i = 0; i < Rows(); i++)
for (j = 0; j < Cols(); j++)
if (i == j)
Elt(i,j) = k;
else
Elt(i,j) = vl_zero;
}
Void Mat::MakeDiag()
{
Int i, j;
for (i = 0; i < Rows(); i++)
for (j = 0; j < Cols(); j++)
Elt(i,j) = (i == j) ? vl_one : vl_zero;
}
Void Mat::MakeBlock(Real k)
{
Int i;
for (i = 0; i < Rows(); i++)
SELF[i].MakeBlock(k);
}
Void Mat::MakeBlock()
{
Int i, j;
for (i = 0; i < Rows(); i++)
for (j = 0; j < Cols(); j++)
Elt(i,j) = vl_one;
}
// --- Mat Assignment Operators -----------------------------------------------
Mat &Mat::operator += (const Mat &m)
{
Assert(Rows() == m.Rows(), "(Mat::+=) matrix rows don't match");
Int i;
for (i = 0; i < Rows(); i++)
SELF[i] += m[i];
return(SELF);
}
Mat &Mat::operator -= (const Mat &m)
{
Assert(Rows() == m.Rows(), "(Mat::-=) matrix rows don't match");
Int i;
for (i = 0; i < Rows(); i++)
SELF[i] -= m[i];
return(SELF);
}
Mat &Mat::operator *= (const Mat &m)
{
Assert(Cols() == m.Cols(), "(Mat::*=) matrix columns don't match");
Int i;
for (i = 0; i < Rows(); i++)
SELF[i] = SELF[i] * m;
return(SELF);
}
Mat &Mat::operator *= (Real s)
{
Int i;
for (i = 0; i < Rows(); i++)
SELF[i] *= s;
return(SELF);
}
Mat &Mat::operator /= (Real s)
{
Int i;
for (i = 0; i < Rows(); i++)
SELF[i] /= s;
return(SELF);
}
// --- Mat Comparison Operators -----------------------------------------------
Bool operator == (const Mat &m, const Mat &n)
{
Assert(n.Rows() == m.Rows(), "(Mat::==) matrix rows don't match");
Int i;
for (i = 0; i < m.Rows(); i++)
if (m[i] != n[i])
return(0);
return(1);
}
Bool operator != (const Mat &m, const Mat &n)
{
Assert(n.Rows() == m.Rows(), "(Mat::!=) matrix rows don't match");
Int i;
for (i = 0; i < m.Rows(); i++)
if (m[i] != n[i])
return(1);
return(0);
}
// --- Mat Arithmetic Operators -----------------------------------------------
Mat operator + (const Mat &m, const Mat &n)
{
Assert(n.Rows() == m.Rows(), "(Mat::+) matrix rows don't match");
Mat result(m.Rows(), m.Cols());
Int i;
for (i = 0; i < m.Rows(); i++)
result[i] = m[i] + n[i];
return(result);
}
Mat operator - (const Mat &m, const Mat &n)
{
Assert(n.Rows() == m.Rows(), "(Mat::-) matrix rows don't match");
Mat result(m.Rows(), m.Cols());
Int i;
for (i = 0; i < m.Rows(); i++)
result[i] = m[i] - n[i];
return(result);
}
Mat operator - (const Mat &m)
{
Mat result(m.Rows(), m.Cols());
Int i;
for (i = 0; i < m.Rows(); i++)
result[i] = -m[i];
return(result);
}
Mat operator * (const Mat &m, const Mat &n)
{
Assert(m.Cols() == n.Rows(), "(Mat::*m) matrix cols don't match");
Mat result(m.Rows(), n.Cols());
Int i;
for (i = 0; i < m.Rows(); i++)
result[i] = m[i] * n;
return(result);
}
Vec operator * (const Mat &m, const Vec &v)
{
Assert(m.Cols() == v.Elts(), "(Mat::*v) matrix and vector sizes don't match");
Int i;
Vec result(m.Rows());
for (i = 0; i < m.Rows(); i++)
result[i] = dot(v, m[i]);
return(result);
}
Mat operator * (const Mat &m, Real s)
{
Int i;
Mat result(m.Rows(), m.Cols());
for (i = 0; i < m.Rows(); i++)
result[i] = m[i] * s;
return(result);
}
Mat operator / (const Mat &m, Real s)
{
Int i;
Mat result(m.Rows(), m.Cols());
for (i = 0; i < m.Rows(); i++)
result[i] = m[i] / s;
return(result);
}
// --- Mat Mat-Vec Functions --------------------------------------------------
Vec operator * (const Vec &v, const Mat &m) // v * m
{
Assert(v.Elts() == m.Rows(), "(Mat::v*m) vector/matrix sizes don't match");
Vec result(m.Cols(), vl_zero);
Int i;
for (i = 0; i < m.Rows(); i++)
result += m[i] * v[i];
return(result);
}
// --- Mat Special Functions --------------------------------------------------
Mat trans(const Mat &m)
{
Int i,j;
Mat result(m.Cols(), m.Rows());
for (i = 0; i < m.Rows(); i++)
for (j = 0; j < m.Cols(); j++)
result.Elt(j,i) = m.Elt(i,j);
return(result);
}
Real trace(const Mat &m)
{
Int i;
Real result = vl_0;
for (i = 0; i < m.Rows(); i++)
result += m.Elt(i,i);
return(result);
}
Mat &Mat::Clamp(Real fuzz)
// clamps all values of the matrix with a magnitude
// smaller than fuzz to zero.
{
Int i;
for (i = 0; i < Rows(); i++)
SELF[i].Clamp(fuzz);
return(SELF);
}
Mat &Mat::Clamp()
{
return(Clamp(1e-7));
}
Mat clamped(const Mat &m, Real fuzz)
// clamps all values of the matrix with a magnitude
// smaller than fuzz to zero.
{
Mat result(m);
return(result.Clamp(fuzz));
}
Mat clamped(const Mat &m)
{
return(clamped(m, 1e-7));
}
Mat oprod(const Vec &a, const Vec &b)
// returns outerproduct of a and b: a * trans(b)
{
Mat result;
Int i;
result.SetSize(a.Elts(), b.Elts());
for (i = 0; i < a.Elts(); i++)
result[i] = a[i] * b;
return(result);
}
// --- Mat Input & Output -----------------------------------------------------
ostream &operator << (ostream &s, const Mat &m)
{
Int i, w = s.width();
s << '[';
for (i = 0; i < m.Rows() - 1; i++)
s << setw(w) << m[i] << endl;
s << setw(w) << m[i] << ']' << endl;
return(s);
}
inline Void CopyPartialMat(const Mat &m, Mat &n, Int numRows)
{
for (Int i = 0; i < numRows; i++)
n[i] = m[i];
}
istream &operator >> (istream &s, Mat &m)
{
Int size = 1;
Char c;
Mat inMat;
// Expected format: [row0 row1 row2 ...]
while (isspace(s.peek())) // chomp white space
s.get(c);
if (s.peek() == '[')
{
Vec row;
s.get(c);
s >> row;
inMat.SetSize(2 * row.Elts(), row.Elts());
inMat[0] = row;
while (isspace(s.peek())) // chomp white space
s.get(c);
while (s.peek() != ']') // resize if needed
{
if (size == inMat.Rows())
{
Mat holdMat(inMat);
inMat.SetSize(size * 2, inMat.Cols());
CopyPartialMat(holdMat, inMat, size);
}
s >> row; // read a row
inMat[size++] = row;
if (!s)
{
_Warning("Couldn't read matrix row");
return(s);
}
while (isspace(s.peek())) // chomp white space
s.get(c);
}
s.get(c);
}
else
{
s.clear(ios::failbit);
_Warning("Error: Expected '[' while reading matrix");
return(s);
}
m.SetSize(size, inMat.Cols());
CopyPartialMat(inMat, m, size);
return(s);
}
// --- Matrix Inversion -------------------------------------------------------
#if !defined(CL_CHECKING) && !defined(VL_CHECKING)
// we #define away pAssertEps if it is not used, to avoid
// compiler warnings.
#define pAssertEps
#endif
Mat inv(const Mat &m, Real *determinant, Real pAssertEps)
// matrix inversion using Gaussian pivoting
{
Assert(m.IsSquare(), "(inv) Matrix not square");
Int i, j, k;
Int n = m.Rows();
Real t, pivot, det;
Real max;
Mat A(m);
Mat B(n, n, vl_I);
// ---------- Forward elimination ---------- ------------------------------
det = vl_1;
for (i = 0; i < n; i++) // Eliminate in column i, below diag
{
max = -1.0;
for (k = i; k < n; k++) // Find a pivot for column i
if (len(A[k][i]) > max)
{
max = len(A[k][i]);
j = k;
}
Assert(max > pAssertEps, "(inv) Matrix not invertible");
if (j != i) // Swap rows i and j
{
for (k = i; k < n; k++)
Swap(A.Elt(i, k), A.Elt(j, k));
for (k = 0; k < n; k++)
Swap(B.Elt(i, k), B.Elt(j, k));
det = -det;
}
pivot = A.Elt(i, i);
Assert(abs(pivot) > pAssertEps, "(inv) Matrix not invertible");
det *= pivot;
for (k = i + 1; k < n; k++) // Only do elements to the right of the pivot
A.Elt(i, k) /= pivot;
for (k = 0; k < n; k++)
B.Elt(i, k) /= pivot;
// We know that A(i, i) will be set to 1, so don't bother to do it
for (j = i + 1; j < n; j++)
{ // Eliminate in rows below i
t = A.Elt(j, i); // We're gonna zero this guy
for (k = i + 1; k < n; k++) // Subtract scaled row i from row j
A.Elt(j, k) -= A.Elt(i, k) * t; // (Ignore k <= i, we know they're 0)
for (k = 0; k < n; k++)
B.Elt(j, k) -= B.Elt(i, k) * t;
}
}
// ---------- Backward elimination ---------- -----------------------------
for (i = n - 1; i > 0; i--) // Eliminate in column i, above diag
{
for (j = 0; j < i; j++) // Eliminate in rows above i
{
t = A.Elt(j, i); // We're gonna zero this guy
for (k = 0; k < n; k++) // Subtract scaled row i from row j
B.Elt(j, k) -= B.Elt(i, k) * t;
}
}
if (determinant)
*determinant = det;
return(B);
}
| [
"BrandonAGr@0fd8bb18-9850-0410-888e-21b4c4172e3e"
] | [
[
[
1,
659
]
]
] |
3acc19fe483a1635b582df3acbe03132fd3140fc | 61c263eb77eb64cf8ab42d2262fc553ac51a6399 | /src/RandomSample.cpp | b234c63cee74e231c5525b905a24d76cf6b0f92e | [] | no_license | ycaihua/fingermania | 20760830f6fe7c48aa2332b67f455eef8f9246a3 | daaa470caf02169ea6533669aa511bf59f896805 | refs/heads/master | 2021-01-20 09:36:38 | 2011-01-23 12:31:19 | 2011-01-23 12:31:19 | 40,102,565 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,432 | cpp | #include "global.h"
#include "RandomSample.h"
#include "RageSound.h"
#include "RageUtil.h"
#include "RageLog.h"
RandomSample::RandomSample()
{
m_iIndexLastPlayed = -1;
}
RandomSample::~RandomSample()
{
UnloadAll();
}
bool RandomSample::Load( RString sFilePath, int iMaxToLoad )
{
if( GetExtension(sFilePath) == "" )
return LoadSoundDir( sFilePath, iMaxToLoad );
else
return LoadSound( sFilePath );
}
void RandomSample::UnloadAll()
{
for( unsigned i=0; i<m_pSamples.size(); i++ )
delete m_pSamples[i];
m_pSamples.clear();
}
bool RandomSample::LoadSoundDir( RString sDir, int iMaxToLoad )
{
if( sDir == "" )
return true;
#if 0
if(IsADirectory(sDir) && sDir[sDir.size()-1] != "/" )
sDir += "/";
#else
if( sDir.Right(1) != "/" )
sDir += "/";
#endif
vector<RString> arraySoundFiles;
GetDirListing( sDir + "*.mp3", arraySoundFiles );
GetDirListing( sDir + "*.ogg", arraySoundFiles );
GetDirListing( sDir + "*.wav", arraySoundFiles );
random_shuffle( arraySoundFiles.begin(), arraySoundFiles.end() );
arraySoundFiles.resize( min( arraySoundFiles.size(), (unsigned)iMaxToLoad ) );
for( unsigned i=0; i<arraySoundFiles.size(); i++ )
LoadSound( sDir + arraySoundFiles[i] );
return true;
}
bool RandomSample::LoadSound( RString sSoundFilePath )
{
LOG->Trace( "RandomSample::LoadSound( %s )", sSoundFilePath.c_str() );
RageSound *pSS = new RageSound;
if( !pSS->Load(sSoundFilePath) )
{
LOG->Trace( "Error loading \"%s\": %s", sSoundFilePath.c_str(), pSS->GetError().c_str() );
delete pSS;
return false;
}
m_pSamples.push_back( pSS );
return true;
}
int RandomSample::GetNextToPlay()
{
if( m_pSamples.empty() )
return -1;
int iIndexToPlay = 0;
for( int i=0; i<5; i++ )
{
iIndexToPlay = RandomInt( m_pSamples.size() );
if( iIndexToPlay != m_iIndexLastPlayed )
break;
}
m_iIndexLastPlayed = iIndexToPlay;
return iIndexToPlay;
}
void RandomSample::PlayRandom()
{
int iIndexToPlay = GetNextToPlay();
if( iIndexToPlay == -1 )
return;
m_pSamples[iIndexToPlay]->Play();
}
void RandomSample::PlayCopyOfRandom()
{
int iIndexToPlay = GetNextToPlay();
if( iIndexToPlay == -1 )
return;
m_pSamples[iIndexToPlay]->PlayCopy();
}
void RandomSample::Stop()
{
if( m_iIndexLastPlayed == -1 )
return;
m_pSamples[m_iIndexLastPlayed]->Stop();
}
| [
"davidleee121@gmail.com"
] | [
[
[
1,
120
]
]
] |
9b35b10a742c90d1abcc1a5b50e21f288c34caf4 | 3affbb81deebe2f45e2efa4582cb45b2fb142303 | /cob_driver/cob_camera_sensors/common/include/cob_camera_sensors/AVTPikeCam.h | 7dec163d8643a7eb1cca22a4c8e902168b1e07cc | [] | no_license | cool-breeze/care-o-bot | 38ad558e14f400a28bc0e0a788aff62ac0b89e05 | bb6999df19f717574113fc75ffb1c5ec5b8e83a6 | refs/heads/master | 2021-01-16 19:12:30 | 2010-04-29 06:58:50 | 2010-04-29 06:58:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,527 | h | /****************************************************************
*
* Copyright (c) 2010
*
* Fraunhofer Institute for Manufacturing Engineering
* and Automation (IPA)
*
* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* Project name: care-o-bot
* ROS stack name: cob3_driver
* ROS package name: cob_camera_sensors
* Description: Interface to AVTPikeCam Firewire Camera.
*
* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* Author: Jan Fischer, email:jan.fischer@ipa.fhg.de
* Supervised by: Jan Fischer, email:jan.fischer@ipa.fhg.de
*
* Date of creation: Nov 2008
* ToDo:
*
* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* 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 Fraunhofer Institute for Manufacturing
* Engineering and Automation (IPA) nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License LGPL 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 Lesser General Public License LGPL for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License LGPL along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*
****************************************************************/
/// @file AVTPikeCam.h
/// Interface to AVTPikeCam Firewire Camera.
/// @author Jan Fischer
/// @date Novemeber, 2008
#ifndef __AVT_PIKE_CAM_H__
#define __AVT_PIKE_CAM_H__
#ifdef __COB_ROS__
#include "cob_camera_sensors/AbstractColorCamera.h"
#else
#include "cob_driver/cob_camera_sensors/common/include/cob_camera_sensors/AbstractColorCamera.h"
#endif
#include <vector>
#include <iostream>
#include <cstdlib>
using namespace std;
#ifndef __LINUX__
#include <fgcamera.h>
#ifdef __MINGW__
typedef unsigned char UINT8;
#endif
#endif
#define UINT8P_CAST(x) reinterpret_cast<UINT8*>(x)
#ifdef __LINUX__
#include <dc1394/dc1394.h>
typedef struct
{
unsigned long Low;
unsigned long High;
}UINT32HL;
#define UINT32 unsigned long
#define _UINT32HL
#endif
#ifdef SWIG
%module Sensors
%include "Source/Vision/CameraSensors/AbstractColorCamera.h"
%{
#include "AVTPikeCam.h"
%}
#endif
namespace ipa_CameraSensors {
/// @ingroup CameraSensorDriver
/// Interface developed for AVT PIKE 145C camera.
/// Interface should also fit to other IEEE 1394 cameras.
class AVTPikeCam : public AbstractColorCamera
{
private:
/// Camera specific parameters
bool m_operationMode_B; ///< FireWire A (400Mbit/s) or FireWire B (800Mbit/s).
UINT32HL m_GUID; ///< GUID (worldwide unique identifier) of the IEEE1395 camera
static bool m_CloseExecuted; ///< Trigger takes care, that AVT library is closed only once
static bool m_OpenExecuted; ///< Trigger takes care, that AVT library is opend only once
#ifdef __LINUX__
dc1394video_frame_t* m_Frame;
dc1394_t* m_IEEE1394Info; ///< Hold information about IEEE1394 nodes, connected cameras and camera properties
dc1394camera_list_t* m_IEEE1394Cameras; ///< List holds all available firewire cameras
dc1394camera_t* m_cam; ///< Opened camera instance.
dc1394video_modes_t m_availableVideoModes; ///< Struct holds all available video modes for the opened camera
dc1394speed_t m_IsoSpeed; ///< ISO speed.
dc1394framerate_t m_FrameRate; ///< Frame rate.
dc1394video_mode_t m_VideoMode; ///< Comprise format and mode (i.e. DC1394_VIDEO_MODE_1280x960_RGB8 or DC1394_VIDEO_MODE_FORMAT7_0)
dc1394color_coding_t m_ColorCoding; ///< Necessary for Format 7 video mode. Here the color coding is not specified through the video mode
#endif
#ifndef __LINUX__
CFGCamera m_cam; ///< The camera object for AVT FireGrab (part of AVT FirePackage)
FGNODEINFO m_nodeInfo[5]; ///< Array holds information about all detected firewire nodes
UINT32 m_NodeCnt; ///< Number of detected IEEE1394 nodes
FGFRAME m_Frame; ///< The acquired latest frame from the camera
#endif
/// Parses the XML configuration file, that holds the camera settings
/// @param filename The file name and path of the configuration file
/// @param cameraIndex The index of the camera within the configuration file
/// i.e. AVT_PIKE_CAM_0 or AVT_PIKE_CAM_1
/// @return Return value
unsigned long LoadParameters(const char* filename, int cameraIndex);
/// Parses the data extracted by <code>LoadParameters</code> and calls the
/// corresponding <code>SetProperty</code> functions.
/// @return Return code
unsigned long SetParameters();
public:
/// Constructor
AVTPikeCam ();
/// Destructor
~AVTPikeCam ();
//*******************************************************************************
// AbstractColorCamera interface implementation
//*******************************************************************************
unsigned long Init(std::string directory, int cameraIndex = 0);
unsigned long Open();
unsigned long Close();
unsigned long GetColorImage(char* colorImageData, bool getLatestFrame);
unsigned long GetColorImage(IplImage * Img, bool getLatestFrame);
unsigned long GetColorImage2(IplImage ** Img, bool getLatestFrame);
unsigned long SaveParameters(const char* filename); //speichert die Parameter in das File
/// Sets the camera properties.
/// The following parameters are admitted:
///<ol>
/// <li> PROP_BRIGHTNESS: 0..1023 </li>
/// <li> PROP_SHUTTER: 0..4095, VALUE_AUTO</li>
/// <li> PROP_AUTO_EXPOSURE: 50..205</li>
/// <li> PROP_WHITE_BALANCE_U: 0..568, VALUE_AUTO</li>
/// <li> PROP_WHITE_BALANCE_V: 0..568, VALUE_AUTO</li>
/// <li> PROP_HUE: 0..80</li>
/// <li> PROP_SATURATION: 0..511</li>
/// <li> PROP_GAMMA: 0..2</li>
/// <li> PROP_GAIN: 0..680</li>
/// <li> PROP_FRAME_RATE: 0..60</li>
/// <li> PROP_FW_OPERATION_MODE: A / B</li>
///</ol>
unsigned long SetProperty(t_cameraProperty* cameraProperty);
unsigned long SetPropertyDefaults();
unsigned long GetProperty(t_cameraProperty* cameraProperty);
/// Shows the camera's parameters information.
/// Shows actual value, max and min value and auto mode for each parameter
unsigned long PrintCameraInformation();
unsigned long TestCamera(const char* filename);
//*******************************************************************************
// Camera specific functions
//*******************************************************************************
};
} // end namespace ipa_CameraSensors
#endif //__AVT_PIKE_CAM_H__
| [
"jsf@jsf-laptop.(none)",
"mmb-weisshardtf@ipa.fhg.de",
"jsf@ipa.fhg.de"
] | [
[
[
1,
58
],
[
63,
65
],
[
67,
67
],
[
96,
96
]
],
[
[
59,
62
],
[
68,
95
],
[
97,
205
]
],
[
[
66,
66
]
]
] |
cc46adbbddc0d30f0d9c0ac6541108aafee955fb | a6f42311df3830117e9590e446b105db78fdbd3a | /src/framework/gui/Window.hpp | 4386fce6b57184b359ba1899e1e22aac488d6762 | [] | no_license | wellsoftware/temporal-lightfield-reconstruction | a4009b9da01b93d6d77a4d0d6830c49e0d4e225f | 8d0988b5660ba0e53d65e887a51e220dcbc985ca | refs/heads/master | 2021-01-17 23:49:05 | 2011-09-25 10:47:49 | 2011-09-25 10:47:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,902 | hpp | /*
* Copyright (c) 2009-2011, NVIDIA Corporation
* 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 NVIDIA Corporation 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 <COPYRIGHT HOLDER> 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 "base/Array.hpp"
#include "base/String.hpp"
#include "base/Math.hpp"
#include "base/Hash.hpp"
#include "gui/Keys.hpp"
#include "base/DLLImports.hpp"
#include "gpu/GLContext.hpp"
namespace FW
{
//------------------------------------------------------------------------
class Window
{
public:
//------------------------------------------------------------------------
enum EventType
{
EventType_AddListener, /* Listener has been added to a window. */
EventType_RemoveListener, /* Listener has been removed from a window. */
EventType_Close, /* User has tried to close the window. */
EventType_Resize, /* The window has been resized. */
EventType_KeyDown, /* User has pressed a key (or mouse button). */
EventType_KeyUp, /* User has released a key (or mouse button). */
EventType_Char, /* User has typed a character. */
EventType_Mouse, /* User has moved the mouse. */
EventType_Paint, /* Window contents need to be painted. */
EventType_PrePaint, /* Before processing EventType_Paint. */
EventType_PostPaint, /* After processing EventType_Paint. */
};
//------------------------------------------------------------------------
struct Event
{
EventType type;
String key; /* Empty unless EventType_KeyDown or EventType_KeyUp. */
S32 keyUnicode; /* 0 unless EventType_KeyDown or EventType_KeyUp or if special key. */
S32 chr; /* Zero unless EventType_Text. */
bool mouseKnown; /* Unchanged unless EventType_Mouse. */
Vec2i mousePos; /* Unchanged unless EventType_Mouse. */
Vec2i mouseDelta; /* Zero unless EventType_Mouse. */
bool mouseDragging; /* One or more mouse buttons are down. */
Window* window;
};
//------------------------------------------------------------------------
class Listener
{
public:
Listener (void) {}
virtual ~Listener (void) {}
virtual bool handleEvent (const Event& ev) = 0;
};
//------------------------------------------------------------------------
public:
Window (void);
~Window (void);
void setTitle (const String& title);
void setSize (const Vec2i& size);
Vec2i getSize (void) const;
void setVisible (bool visible);
bool isVisible (void) const { return m_isVisible; }
void setFullScreen (bool isFull);
bool isFullScreen (void) const { return m_isFullScreen; }
void toggleFullScreen (void) { setFullScreen(!isFullScreen()); }
void realize (void);
void setGLConfig (const GLContext::Config& config);
const GLContext::Config& getGLConfig (void) const { return m_glConfig; }
GLContext* getGL (void); // also makes the context current
void repaint (void);
void repaintNow (void);
void requestClose (void);
void addListener (Listener* listener);
void removeListener (Listener* listener);
void removeListeners (void);
bool isKeyDown (const String& key) const { return m_keysDown.contains(key); }
bool isMouseKnown (void) const { return m_mouseKnown; }
bool isMouseDragging (void) const { return (m_mouseDragCount != 0); }
const Vec2i& getMousePos (void) const { return m_mousePos; }
void showMessageDialog (const String& title, const String& text);
String showFileDialog (const String& title, bool save, const String& filters = "", const String& initialDir = "", bool forceInitialDir = false); // filters = "ext:Title,foo;bar:Title"
String showFileLoadDialog (const String& title, const String& filters = "", const String& initialDir = "", bool forceInitialDir = false) { return showFileDialog(title, false, filters, initialDir, forceInitialDir); }
String showFileSaveDialog (const String& title, const String& filters = "", const String& initialDir = "", bool forceInitialDir = false) { return showFileDialog(title, true, filters, initialDir, forceInitialDir); }
void showModalMessage (const String& msg);
static void staticInit (void);
static void staticDeinit (void);
static HWND createHWND (void);
static UPTR setWindowLong (HWND hwnd, int idx, UPTR value);
static int getNumOpen (void) { return (s_inited) ? s_open->getSize() : 0; }
static void realizeAll (void);
static void pollMessages (void);
private:
Event createSimpleEvent (EventType type) { return createGenericEvent(type, "", 0, m_mouseKnown, m_mousePos); }
Event createKeyEvent (bool down, const String& key) { return createGenericEvent((down) ? EventType_KeyDown : EventType_KeyUp, key, 0, m_mouseKnown, m_mousePos); }
Event createCharEvent (S32 chr) { return createGenericEvent(EventType_Char, "", chr, m_mouseKnown, m_mousePos); }
Event createMouseEvent (bool mouseKnown, const Vec2i& mousePos) { return createGenericEvent(EventType_Mouse, "", 0, mouseKnown, mousePos); }
Event createGenericEvent (EventType type, const String& key, S32 chr, bool mouseKnown, const Vec2i& mousePos);
void postEvent (const Event& ev);
void create (void);
void destroy (void);
void recreate (void);
static LRESULT CALLBACK staticWindowProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
LRESULT windowProc (UINT uMsg, WPARAM wParam, LPARAM lParam);
private:
Window (const Window&); // forbidden
Window& operator= (const Window&); // forbidden
private:
static bool s_inited;
static Array<Window*>* s_open;
static bool s_ignoreRepaint; // Prevents re-entering repaintNow() on Win32 or OpenGL failure.
HWND m_hwnd;
HDC m_hdc;
GLContext::Config m_glConfig;
bool m_glConfigDirty;
GLContext* m_gl;
bool m_isRealized;
bool m_isVisible;
Array<Listener*> m_listeners;
String m_title;
bool m_isFullScreen;
Vec2i m_pendingSize;
DWORD m_origStyle;
RECT m_origRect;
Set<String> m_keysDown;
bool m_pendingKeyFlush;
bool m_mouseKnown;
Vec2i m_mousePos;
S32 m_mouseDragCount;
S32 m_mouseWheelAcc;
Vec2i m_prevSize;
};
//------------------------------------------------------------------------
}
| [
"jiawen@csail.mit.edu"
] | [
[
[
1,
191
]
]
] |
5b768536b37c2b868d088cd8cbad8229576bec41 | 222bc22cb0330b694d2c3b0f4b866d726fd29c72 | /src/brookbox/wm2/WmlEdgeKey.inl | d3e371ffdaab0f0a5e09896fdfda61919afca952 | [
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | darwin/inferno | 02acd3d05ca4c092aa4006b028a843ac04b551b1 | e87017763abae0cfe09d47987f5f6ac37c4f073d | refs/heads/master | 2021-03-12 22:15:47 | 2009-04-17 13:29:39 | 2009-04-17 13:29:39 | 178,477 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,081 | inl | // Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2003. All Rights Reserved
//
// The Wild Magic Library (WML) source code is supplied under the terms of
// the license agreement http://www.magic-software.com/License/WildMagic.pdf
// and may not be copied or disclosed except in accordance with the terms of
// that agreement.
//----------------------------------------------------------------------------
inline EdgeKey::EdgeKey (int iV0, int iV1)
{
if ( iV0 < iV1 )
{
// v0 is minimum
V[0] = iV0;
V[1] = iV1;
}
else
{
// v1 is minimum
V[0] = iV1;
V[1] = iV0;
}
}
//----------------------------------------------------------------------------
inline bool EdgeKey::operator< (const EdgeKey& rkKey) const
{
if ( V[1] < rkKey.V[1] )
return true;
if ( V[1] > rkKey.V[1] )
return false;
return V[0] < rkKey.V[0];
}
//----------------------------------------------------------------------------
| [
"antonin@hildebrand.cz"
] | [
[
[
1,
36
]
]
] |
a59360fcf81c53b3316b720901fda7ee24465ddb | 6be1c51c980e8906406762fe3c7b59ca6c09faaf | /SimpleKBot/KBotDrive.cpp | a086b75458bb2ac738955e38cad84771b0f2bb35 | [] | no_license | woodk/SimpleKBot | 4aed0122fa8a8e4b49bff3a966c31af85a6cd87f | 4433bd1ca71c3b39460032279dea4c089aa1eb04 | refs/heads/master | 2021-01-01 18:07:55 | 2011-01-07 19:37:40 | 2011-01-07 19:37:40 | 1,035,746 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,724 | cpp | /*----------------------------------------------------------------------------*/
/* Copyright (c) KBotics 2010. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. */
/*----------------------------------------------------------------------------*/
#include "KBotDrive.h"
#include "GenericHID.h"
KBotDrive::KBotDrive(UINT32 leftMotorChannel, UINT32 rightMotorChannel) : RobotDrive(leftMotorChannel, rightMotorChannel){;}
KBotDrive::KBotDrive(UINT32 frontLeftMotorChannel, UINT32 rearLeftMotorChannel,
UINT32 frontRightMotorChannel, UINT32 rearRightMotorChannel) : RobotDrive(frontLeftMotorChannel, rearLeftMotorChannel, frontRightMotorChannel, rearRightMotorChannel){;}
KBotDrive::KBotDrive(SpeedController *leftMotor, SpeedController *rightMotor) : RobotDrive(leftMotor, rightMotor){;}
KBotDrive::KBotDrive(SpeedController &leftMotor, SpeedController &rightMotor) : RobotDrive(leftMotor, rightMotor){;}
KBotDrive::KBotDrive(SpeedController *frontLeftMotor, SpeedController *rearLeftMotor,
SpeedController *frontRightMotor, SpeedController *rearRightMotor)
: RobotDrive(frontLeftMotor, rearLeftMotor, frontRightMotor, rearRightMotor){;}
KBotDrive::KBotDrive(SpeedController &frontLeftMotor, SpeedController &rearLeftMotor,
SpeedController &frontRightMotor, SpeedController &rearRightMotor)
: RobotDrive(frontLeftMotor, rearLeftMotor, frontRightMotor, rearRightMotor){;}
/**
* Arcade drive implements single stick driving.
* Given a single Joystick, the class assumes the Y axis for the move value and the X axis
* for the rotate value.
* (Should add more information here regarding the way that arcade drive works.)
* @param stick The joystick to use for Arcade single-stick driving. The Y-axis will be selected
* for forwards/backwards and the X-axis will be selected for rotation rate.
* @param squaredInputs If true, the sensitivity will be increased for small values
*/
void KBotDrive::ArcadeDrive(GenericHID *stick, bool squaredInputs)
{
// simply call the full-featured ArcadeDrive with the appropriate values
ArcadeDrive(stick->GetY(), stick->GetX(), stick->GetTrigger());
}
/**
* Arcade drive implements single stick driving.
* Given a single Joystick, the class assumes the Y axis for the move value and the X axis
* for the rotate value.
* (Should add more information here regarding the way that arcade drive works.)
* @param stick The joystick to use for Arcade single-stick driving. The Y-axis will be selected
* for forwards/backwards and the X-axis will be selected for rotation rate.
* @param squaredInputs If true, the sensitivity will be increased for small values
*/
void KBotDrive::ArcadeDrive(GenericHID &stick, bool squaredInputs)
{
// simply call the full-featured ArcadeDrive with the appropriate values
ArcadeDrive(stick.GetY(), stick.GetX(), stick.GetTrigger());
}
/**
* Arcade drive implements single stick driving.
* Given two joystick instances and two axis, compute the values to send to either two
* or four motors.
* @param moveStick The Joystick object that represents the forward/backward direction
* @param moveAxis The axis on the moveStick object to use for fowards/backwards (typically Y_AXIS)
* @param rotateStick The Joystick object that represents the rotation value
* @param rotateAxis The axis on the rotation object to use for the rotate right/left (typically X_AXIS)
* @param squaredInputs Setting this parameter to true increases the sensitivity at lower speeds
*/
void KBotDrive::ArcadeDrive(GenericHID* moveStick, UINT32 moveAxis,
GenericHID* rotateStick, UINT32 rotateAxis,
bool squaredInputs)
{
float moveValue = moveStick->GetRawAxis(moveAxis);
float rotateValue = rotateStick->GetRawAxis(rotateAxis);
ArcadeDrive(moveValue, rotateValue, squaredInputs);
}
/**
* Arcade drive implements single stick driving.
* Given two joystick instances and two axis, compute the values to send to either two
* or four motors.
* @param moveStick The Joystick object that represents the forward/backward direction
* @param moveAxis The axis on the moveStick object to use for fowards/backwards (typically Y_AXIS)
* @param rotateStick The Joystick object that represents the rotation value
* @param rotateAxis The axis on the rotation object to use for the rotate right/left (typically X_AXIS)
* @param squaredInputs Setting this parameter to true increases the sensitivity at lower speeds
*/
void KBotDrive::ArcadeDrive(GenericHID &moveStick, UINT32 moveAxis,
GenericHID &rotateStick, UINT32 rotateAxis,
bool squaredInputs)
{
float moveValue = moveStick.GetRawAxis(moveAxis);
float rotateValue = rotateStick.GetRawAxis(rotateAxis);
ArcadeDrive(moveValue, rotateValue, squaredInputs);
}
/**
* Arcade drive implements single stick driving.
* This function lets you directly provide joystick values from any source.
* @param moveValue The value to use for fowards/backwards
* @param rotateValue The value to use for the rotate right/left
* @param squaredInputs If set, increases the sensitivity at low speeds
*/
void KBotDrive::ArcadeDrive(float moveValue, float rotateValue, bool squaredInputs)
{
// local variables to hold the computed PWM values for the motors
float leftMotorSpeed;
float rightMotorSpeed;
moveValue = Limit(moveValue);
rotateValue = Limit(rotateValue);
if (squaredInputs)
{
// square the inputs (while preserving the sign) to increase fine control while permitting full power
if (moveValue >= 0.0)
{
moveValue = (moveValue * moveValue);
}
else
{
moveValue = -(moveValue * moveValue);
}
if (rotateValue >= 0.0)
{
rotateValue = (rotateValue * rotateValue);
}
else
{
rotateValue = -(rotateValue * rotateValue);
}
}
leftMotorSpeed = moveValue - rotateValue;
rightMotorSpeed = moveValue + rotateValue;
// Modify reverse so that back-left goes back-left and back-right goes back-right
if (moveValue<0) { // Joystick backwards (NOTE: < not > for new robot)
leftMotorSpeed += 2*moveValue*rotateValue;
rightMotorSpeed -= 2*moveValue*rotateValue;
}
if (leftMotorSpeed>0.95)
leftMotorSpeed=1.0;
if (leftMotorSpeed<-0.95)
leftMotorSpeed=-1.0;
if (rightMotorSpeed>0.95)
rightMotorSpeed=1.0;
if (rightMotorSpeed<-0.95)
rightMotorSpeed=-1.0;
SetLeftRightMotorOutputs(leftMotorSpeed, rightMotorSpeed);
m_fLeftSpeed = leftMotorSpeed;
m_fRightSpeed = rightMotorSpeed;
}
| [
"woodk@limestone.on.ca"
] | [
[
[
1,
149
]
]
] |
eb481c4bc3c811826fe377121a4763d6f3c1bc8f | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/Dependencies/Xerces/include/xercesc/internal/VecAttributesImpl.cpp | 421153a8851b0024e40bf368a251d425551fae51 | [] | no_license | svn2github/ngene | b2cddacf7ec035aa681d5b8989feab3383dac012 | 61850134a354816161859fe86c2907c8e73dc113 | refs/heads/master | 2023-09-03 12:34:18 | 2011-07-27 19:26:04 | 2011-07-27 19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,083 | cpp | /*
* Copyright 1999-2001,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: VecAttributesImpl.cpp 191054 2005-06-17 02:56:35Z jberry $
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/Janitor.hpp>
#include <xercesc/internal/VecAttributesImpl.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Constructors and Destructor
// ---------------------------------------------------------------------------
VecAttributesImpl::VecAttributesImpl() :
fAdopt(false)
, fCount(0)
, fVector(0)
, fScanner(0)
{
}
VecAttributesImpl::~VecAttributesImpl()
{
//
// Note that some compilers can't deal with the fact that the pointer
// is to a const object, so we have to cast off the const'ness here!
//
if (fAdopt)
delete (RefVectorOf<XMLAttr>*)fVector;
}
// ---------------------------------------------------------------------------
// Implementation of the attribute list interface
// ---------------------------------------------------------------------------
unsigned int VecAttributesImpl::getLength() const
{
return fCount;
}
const XMLCh* VecAttributesImpl::getURI(const unsigned int index) const
{
// since this func really needs to be const, like the rest, not sure how we
// make it const and re-use the fURIBuffer member variable. we're currently
// creating a buffer each time you need a URI. there has to be a better
// way to do this...
//XMLBuffer tempBuf;
if (index >= fCount) {
return 0;
}
//fValidator->getURIText(fVector->elementAt(index)->getURIId(), tempBuf) ;
//return tempBuf.getRawBuffer() ;
return fScanner->getURIText(fVector->elementAt(index)->getURIId());
}
const XMLCh* VecAttributesImpl::getLocalName(const unsigned int index) const
{
if (index >= fCount) {
return 0;
}
return fVector->elementAt(index)->getName();
}
const XMLCh* VecAttributesImpl::getQName(const unsigned int index) const
{
if (index >= fCount) {
return 0;
}
return fVector->elementAt(index)->getQName();
}
const XMLCh* VecAttributesImpl::getType(const unsigned int index) const
{
if (index >= fCount) {
return 0;
}
return XMLAttDef::getAttTypeString(fVector->elementAt(index)->getType(), fVector->getMemoryManager());
}
const XMLCh* VecAttributesImpl::getValue(const unsigned int index) const
{
if (index >= fCount) {
return 0;
}
return fVector->elementAt(index)->getValue();
}
int VecAttributesImpl::getIndex(const XMLCh* const uri, const XMLCh* const localPart ) const
{
//
// Search the vector for the attribute with the given name and return
// its type.
//
XMLBuffer uriBuffer(1023, fVector->getMemoryManager()) ;
for (unsigned int index = 0; index < fCount; index++)
{
const XMLAttr* curElem = fVector->elementAt(index);
fScanner->getURIText(curElem->getURIId(), uriBuffer) ;
if ( (XMLString::equals(curElem->getName(), localPart)) &&
(XMLString::equals(uriBuffer.getRawBuffer(), uri)) )
return index ;
}
return -1;
}
int VecAttributesImpl::getIndex(const XMLCh* const qName ) const
{
//
// Search the vector for the attribute with the given name and return
// its type.
//
for (unsigned int index = 0; index < fCount; index++)
{
const XMLAttr* curElem = fVector->elementAt(index);
if (XMLString::equals(curElem->getQName(), qName))
return index ;
}
return -1;
}
const XMLCh* VecAttributesImpl::getType(const XMLCh* const uri, const XMLCh* const localPart ) const
{
int retVal = getIndex(uri, localPart);
return ((retVal < 0) ? 0 : getType(retVal));
}
const XMLCh* VecAttributesImpl::getType(const XMLCh* const qName) const
{
int retVal = getIndex(qName);
return ((retVal < 0) ? 0 : getType(retVal));
}
const XMLCh* VecAttributesImpl::getValue(const XMLCh* const uri, const XMLCh* const localPart ) const
{
int retVal = getIndex(uri, localPart);
return ((retVal < 0) ? 0 : getValue(retVal));
}
const XMLCh* VecAttributesImpl::getValue(const XMLCh* const qName) const
{
int retVal = getIndex(qName);
return ((retVal < 0) ? 0 : getValue(retVal));
}
// ---------------------------------------------------------------------------
// Setter methods
// ---------------------------------------------------------------------------
void VecAttributesImpl::setVector(const RefVectorOf<XMLAttr>* const srcVec
, const unsigned int count
, const XMLScanner * const scanner
, const bool adopt)
{
//
// Delete the previous vector (if any) if we are adopting. Note that some
// compilers can't deal with the fact that the pointer is to a const
// object, so we have to cast off the const'ness here!
//
if (fAdopt)
delete (RefVectorOf<XMLAttr>*)fVector;
fAdopt = adopt;
fCount = count;
fVector = srcVec;
fScanner = scanner ;
}
XERCES_CPP_NAMESPACE_END
| [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
] | [
[
[
1,
193
]
]
] |
ad9b21017a47f197801482d82b3f0ae22887270f | c7120eeec717341240624c7b8a731553494ef439 | /src/cplusplus/freezone-samp/src/npc_dev.cpp | 82131045a610163017c7ffb65507a1f5fabfeaad | [] | no_license | neverm1ndo/gta-paradise-sa | d564c1ed661090336621af1dfd04879a9c7db62d | 730a89eaa6e8e4afc3395744227527748048c46d | refs/heads/master | 2020-04-27 22:00:22 | 2010-09-04 19:02:28 | 2010-09-04 19:02:28 | 174,719,907 | 1 | 0 | null | 2019-03-09 16:44:43 | 2019-03-09 16:44:43 | null | WINDOWS-1251 | C++ | false | false | 16,350 | cpp | #include "config.hpp"
#include "npc_dev.hpp"
#include "core/module_c.hpp"
#include "core/npcs.hpp"
#include "vehicles.hpp"
#include "weapons.hpp"
#include "player_money.hpp"
#include <fstream>
#include <boost/filesystem.hpp>
REGISTER_IN_APPLICATION(npc_dev);
npc_dev::npc_dev()
:play_npc_name("npc_dev_play")
,play_record_vehicle_id(0)
{
}
npc_dev::~npc_dev() {
}
void npc_dev::create() {
command_add("npc_dev_record", std::tr1::bind(&npc_dev::cmd_record, this, std::tr1::placeholders::_1, std::tr1::placeholders::_2, std::tr1::placeholders::_3, std::tr1::placeholders::_4, std::tr1::placeholders::_5), cmd_game, std::tr1::bind(&npc_dev::access_checker, this, std::tr1::placeholders::_1, std::tr1::placeholders::_2));
command_add("npc_dev_play", std::tr1::bind(&npc_dev::cmd_play, this, std::tr1::placeholders::_1, std::tr1::placeholders::_2, std::tr1::placeholders::_3, std::tr1::placeholders::_4, std::tr1::placeholders::_5), cmd_game, std::tr1::bind(&npc_dev::access_checker, this, std::tr1::placeholders::_1, std::tr1::placeholders::_2));
command_add("npc_dev_create_vehicle", std::tr1::bind(&npc_dev::cmd_create_vehicle, this, std::tr1::placeholders::_1, std::tr1::placeholders::_2, std::tr1::placeholders::_3, std::tr1::placeholders::_4, std::tr1::placeholders::_5), cmd_game, std::tr1::bind(&npc_dev::access_checker, this, std::tr1::placeholders::_1, std::tr1::placeholders::_2));
}
void npc_dev::configure_pre() {
is_enable = false;
recording_vehicle_health = 1000.0f;
acceleration_multiplier = 1.2f;
deceleration_multiplier = 0.8f;
}
void npc_dev::configure(buffer::ptr const& buff, def_t const& def) {
SERIALIZE_ITEM(is_enable);
SERIALIZE_ITEM(recording_vehicle_health);
SERIALIZE_ITEM(acceleration_multiplier);
SERIALIZE_ITEM(deceleration_multiplier);
}
void npc_dev::configure_post() {
}
void npc_dev::on_connect(player_ptr_t const& player_ptr) {
npc_dev_player_item::ptr item(new npc_dev_player_item(*this), &player_item::do_delete);
player_ptr->add_item(item);
}
void npc_dev::on_npc_connect(npc_ptr_t const& npc_ptr) {
if (play_npc_name == npc_ptr->name_get()) {
// Это наш бот для проигрования :)
npc_dev_npc_item::ptr item(new npc_dev_npc_item(*this), &npc_item::do_delete);
npc_ptr->add_item(item);
}
}
bool npc_dev::access_checker(player_ptr_t const& player_ptr, std::string const& cmd_name) {
return is_enable;
}
command_arguments_rezult npc_dev::cmd_record(player_ptr_t const& player_ptr, std::string const& arguments, messages_pager& pager, messages_sender const& sender, messages_params& params) {
npc_dev_player_item::ptr npc_dev_player_item_ptr = player_ptr->get_item<npc_dev_player_item>();
npc_dev_player_item_ptr->is_wait_recording = !npc_dev_player_item_ptr->is_wait_recording;
if (npc_dev_player_item_ptr->is_wait_recording) {
if (arguments.empty()) {
npc_dev_player_item_ptr->recording_prefix = "record";
}
else {
npc_dev_player_item_ptr->recording_prefix = arguments;
}
player_ptr->get_item<weapons_item>()->weapon_reset();
player_ptr->get_item<player_money_item>()->reset();
params("prefix", npc_dev_player_item_ptr->recording_prefix);
pager("$(cmd_npc_dev_record_on_player)");
sender("$(cmd_npc_dev_record_on_log)", msg_log);
}
else {
if (npc_dev_player_item_ptr->is_recording) {
npc_dev_player_item_ptr->recording_stop();
}
pager("$(cmd_npc_dev_record_off_player)");
sender("$(cmd_npc_dev_record_off_log)", msg_log);
}
return cmd_arg_ok;
}
command_arguments_rezult npc_dev::cmd_play(player_ptr_t const& player_ptr, std::string const& arguments, messages_pager& pager, messages_sender const& sender, messages_params& params) {
if (arguments.empty()) {
return cmd_arg_syntax_error;
}
{
int vehicle_id;
int model_id;
bool is_driver;
if (player_ptr->get_vehicle(vehicle_id, model_id, is_driver)) {
play_record_vehicle_id = vehicle_id;
}
else {
play_record_vehicle_id = 0;
}
}
play_record_name = arguments;
npcs::instance()->add_npc(play_npc_name);
params("record_name", play_record_name);
pager("$(cmd_npc_dev_play_player)");
sender("$(cmd_npc_dev_play_log)", msg_log);
return cmd_arg_ok;
}
command_arguments_rezult npc_dev::cmd_create_vehicle(player_ptr_t const& player_ptr, std::string const& arguments, messages_pager& pager, messages_sender const& sender, messages_params& params) {
int model_id;
{ // Парсинг
if (!vehicles::instance()->get_model_id_by_name(arguments, model_id)) {
std::istringstream iss(arguments);
iss>>model_id;
if (iss.fail() || !iss.eof()) {
return cmd_arg_syntax_error;
}
}
}
{ // Проверяем, находится ли игрок в транспорте
int vehicle_id = samp::api::instance()->get_player_vehicle_id(player_ptr->get_id());
int model_id = samp::api::instance()->get_vehicle_model(vehicle_id);
if (0 != model_id) {
pager("$(npc_dev_create_vehicle_error_invehicle)");
return cmd_arg_process_error;
}
}
pos4 pos = player_ptr->get_item<player_position_item>()->pos_get();
int vehicle_id = vehicles::instance()->vehicle_create(pos_vehicle(model_id, pos.x, pos.y, pos.z + 1.5f, pos.interior, pos.world, pos.rz, -1, -1));
samp::api::instance()->put_player_in_vehicle(player_ptr->get_id(), vehicle_id, 0);
params
("model_id", model_id)
("vehicle_id", vehicle_id)
;
pager("$(npc_dev_create_vehicle_done_player)");
sender("$(npc_dev_create_vehicle_done_log)", msg_log);
return cmd_arg_ok;
}
npc_dev_player_item::npc_dev_player_item(npc_dev& manager)
:manager(manager)
,is_wait_recording(false)
,is_recording(false)
,recording_vehicle_id(-1)
,recording_time_start(0)
,is_accelerate(false)
{
}
npc_dev_player_item::~npc_dev_player_item() {
}
void npc_dev_player_item::on_timer250() {
if (!is_recording || 0 == recording_vehicle_id || !is_accelerate) {
return;
}
int vehicle_id;
int model_id;
bool is_driver;
if (get_root()->get_vehicle(vehicle_id, model_id, is_driver) && is_driver) {
samp::api::ptr api_ptr = samp::api::instance();
float x, y, z;
int keys;
int updown;
int leftright;
api_ptr->get_vehicle_velocity(vehicle_id, x, y, z);
api_ptr->get_player_keys(get_root()->get_id(), keys, updown, leftright);
if (keys & vehicle_accelerate) {
api_ptr->set_vehicle_velocity(vehicle_id, accelerate(x), accelerate(y), accelerate(z));
}
else if (keys & vehicle_decelerate) {
api_ptr->set_vehicle_velocity(vehicle_id, decelerate(x), decelerate(y), decelerate(z));
}
}
}
void npc_dev_player_item::on_keystate_change(int keys_new, int keys_old) {
if (!is_wait_recording) {
return;
}
if (is_recording && 0 != recording_vehicle_id) {
if (recording_is_can_use_nitro) {
if (is_key_just_down(mouse_lbutton, keys_new, keys_old)) {
if (vehicle_ptr_t vehicle_ptr = vehicles::instance()->get_vehicle(recording_vehicle_id)) {
// Можем поставить нитро :)
vehicle_ptr->add_component("nto_b_tw");
}
}
else if (is_key_just_down(KEY_SUBMISSION, keys_new, keys_old)) {
if (vehicle_ptr_t vehicle_ptr = vehicles::instance()->get_vehicle(recording_vehicle_id)) {
// Убираем нитро
vehicle_ptr->remove_component("nto_b_tw");
}
}
}
if (is_key_just_down(KEY_ACTION, keys_new, keys_old)) {
is_accelerate = true;
}
else if (is_key_just_up(KEY_ACTION, keys_new, keys_old)) {
is_accelerate = false;
}
}
if (is_key_just_down(KEY_LOOK_BEHIND, keys_new, keys_old) && !get_root()->vehicle_is_driver()) {
// Запуск/остановка записи пешком
if (is_recording) {
recording_stop();
}
else {
recording_start(false);
}
}
else if (is_key_just_down(KEY_LOOK_RIGHT | KEY_LOOK_LEFT, keys_new, keys_old) && get_root()->vehicle_is_driver()) {
// Запуск/остановка записи на транспорте
if (is_recording) {
recording_stop();
}
else {
recording_start(true);
}
}
}
bool npc_dev_player_item::on_update() {
if (is_recording) {
samp::api::ptr api_ptr = samp::api::instance();
int vehicle_id;
int model_id;
bool is_driver;
if (get_root()->get_vehicle(vehicle_id, model_id, is_driver) && is_driver) {
if (manager.recording_vehicle_health != api_ptr->get_vehicle_health(vehicle_id)) {
//api_ptr->set_vehicle_health(vehicle_id, manager.recording_vehicle_health);
api_ptr->repair_vehicle(vehicle_id);
}
}
else {
}
}
return true;
}
void npc_dev_player_item::recording_start(bool is_vehicle) {
if (is_recording) {
assert(false);
return;
}
recording_name = get_next_recording_filename();
recording_desc = npc_recording_desc_t();
recording_vehicle_id = 0;
recording_is_can_use_nitro = false;
is_accelerate = false;
samp::api::ptr api_ptr = samp::api::instance();
recording_desc.skin_id = api_ptr->get_player_skin(get_root()->get_id());
if (is_vehicle) {
bool is_driver;
int model_id;
get_root()->get_vehicle(recording_vehicle_id, model_id, is_driver);
api_ptr->get_vehicle_pos(recording_vehicle_id, recording_desc.point_begin.x, recording_desc.point_begin.y, recording_desc.point_begin.z);
recording_desc.point_begin.rz = api_ptr->get_vehicle_zangle(recording_vehicle_id);
if (vehicle_ptr_t vehicle_ptr = vehicles::instance()->get_vehicle(recording_vehicle_id)) {
if (vehicle_def_cptr_t vehicle_def_cptr = vehicle_ptr->get_def()) {
recording_desc.model_name = vehicle_def_cptr->sys_name;
}
recording_is_can_use_nitro = vehicle_ptr->is_valid_component("nto_b_tw");
}
api_ptr->repair_vehicle(recording_vehicle_id);
}
else {
int player_id = get_root()->get_id();
api_ptr->get_player_pos(player_id, recording_desc.point_begin.x, recording_desc.point_begin.y, recording_desc.point_begin.z);
recording_desc.point_begin.rz = api_ptr->get_player_facing_angle(player_id);
}
recording_desc.point_begin.interior = api_ptr->get_player_interior(get_root()->get_id());
messages_item msg_item;
msg_item.get_params()
("player_name", get_root()->name_get_full())
("recording_name", recording_name)
;
if (is_vehicle) {
if (recording_is_can_use_nitro) {
msg_item.get_sender()
("$(npc_dev_recordind_vehicle_nitro_start_player)", msg_player(get_root()))
("$(npc_dev_recordind_vehicle_nitro_start_log)", msg_log);
}
else {
msg_item.get_sender()
("$(npc_dev_recordind_vehicle_start_player)", msg_player(get_root()))
("$(npc_dev_recordind_vehicle_start_log)", msg_log);
}
api_ptr->start_recording_player_data(get_root()->get_id(), samp::api::PLAYER_RECORDING_TYPE_DRIVER, recording_name);
}
else {
msg_item.get_sender()
("$(npc_dev_recordind_onfoot_start_player)", msg_player(get_root()))
("$(npc_dev_recordind_onfoot_start_log)", msg_log);
api_ptr->start_recording_player_data(get_root()->get_id(), samp::api::PLAYER_RECORDING_TYPE_ONFOOT, recording_name);
}
recording_time_start = time_base::tick_count_milliseconds();
is_recording = true;
}
void npc_dev_player_item::recording_stop() {
if (!is_recording) {
assert(false);
return;
}
samp::api::ptr api_ptr = samp::api::instance();
time_base::millisecond_t recording_time_stop = time_base::tick_count_milliseconds();
api_ptr->stop_recording_player_data(get_root()->get_id());
is_recording = false;
if (recording_desc.is_on_vehicle()) {
api_ptr->get_vehicle_pos(recording_vehicle_id, recording_desc.point_end.x, recording_desc.point_end.y, recording_desc.point_end.z);
recording_desc.point_end.rz = api_ptr->get_vehicle_zangle(recording_vehicle_id);
}
else {
int player_id = get_root()->get_id();
api_ptr->get_player_pos(player_id, recording_desc.point_end.x, recording_desc.point_end.y, recording_desc.point_end.z);
recording_desc.point_end.rz = api_ptr->get_player_facing_angle(player_id);
}
recording_desc.duration = (recording_time_stop - recording_time_start);
{ // Сохраняем файл с методанными
std::ofstream meta_file(recording_get_meta_filename(recording_name).c_str());
if (meta_file) {
meta_file << recording_desc;
}
}
messages_item msg_item;
msg_item.get_params()
("player_name", get_root()->name_get_full())
("recording_name", recording_name)
("recording_desc", boost::format("%1%") % recording_desc)
;
msg_item.get_sender()
("$(npc_dev_recordind_stop_player)", msg_player(get_root()))
("$(npc_dev_recordind_stop_log)", msg_log);
}
std::string npc_dev_player_item::get_next_recording_filename() const {
/*
if (!boost::filesystem::exists(recording_get_rec_filename(recording_prefix))) {
// В начале пытаемся имя без цифрового суфикса
return recording_prefix;
}
*/
for (int i = 0; i < 1000; ++i) {
std::string name = (boost::format("%1%%2$02d") % recording_prefix % i).str();
if (!boost::filesystem::exists(recording_get_rec_filename(name))) {
return name;
}
}
assert(false);
return "fuck";
}
std::string npc_dev_player_item::recording_get_meta_filename(std::string const& recording_name) {
return "scriptfiles/" + recording_name + ".meta";
}
std::string npc_dev_player_item::recording_get_rec_filename(std::string const& recording_name) {
return "scriptfiles/" + recording_name + ".rec";
}
float npc_dev_player_item::accelerate(float val) const {
return val * manager.acceleration_multiplier;
}
float npc_dev_player_item::decelerate(float val) const {
return val * manager.deceleration_multiplier;
}
npc_dev_npc_item::npc_dev_npc_item(npc_dev& manager)
:manager(manager)
{
}
npc_dev_npc_item::~npc_dev_npc_item() {
}
void npc_dev_npc_item::on_connect() {
get_root()->set_spawn_info(11, pos4(1958.3783f, 1343.1572f, 15.3746f, 0, 0, 90.0f));
get_root()->set_color(0xff000020);
}
void npc_dev_npc_item::on_spawn() {
if (manager.play_record_vehicle_id) {
// Сажаем в транспорт
get_root()->put_to_vehicle(manager.play_record_vehicle_id);
}
else {
// Включаем запись просто
get_root()->playback_start(npc::playback_type_onfoot, manager.play_record_name);
}
}
void npc_dev_npc_item::on_enter_vehicle(int vehicle_id) {
if (manager.play_record_vehicle_id) {
get_root()->playback_start(npc::playback_type_driver, manager.play_record_name);
}
}
void npc_dev_npc_item::on_playback_end() {
get_root()->kick();
}
void npc_dev_npc_item::on_disconnect(samp::player_disconnect_reason reason) {
}
| [
"dimonml@19848965-7475-ded4-60a4-26152d85fbc5"
] | [
[
[
1,
434
]
]
] |
7dfc3145167ecfdeadb54aa63784479fad808693 | 5ac13fa1746046451f1989b5b8734f40d6445322 | /minimangalore/Nebula2/code/contrib/nrubyserver/src/ruby/nrubyrun.cc | ac6268db5006208e762eca4832e1217480b1aa8e | [] | no_license | moltenguy1/minimangalore | 9f2edf7901e7392490cc22486a7cf13c1790008d | 4d849672a6f25d8e441245d374b6bde4b59cbd48 | refs/heads/master | 2020-04-23 08:57:16 | 2009-08-01 09:13:33 | 2009-08-01 09:13:33 | 35,933,330 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,316 | cc | #define N_IMPLEMENTS nRubyServer
//--------------------------------------------------------------------
// nrubyrun.cc -- Command evaluation and passing to ruby
//
// (C) 2003/4 Thomas Miskiewicz tom@3d-inferno.com
//--------------------------------------------------------------------
#include <stdlib.h>
#include <stdio.h>
#include "ruby.h"
#include "ruby/nrubyserver.h"
#include "kernel/nfileserver2.h"
#include "kernel/narg.h"
extern "C" void free_d(VALUE);
extern "C" VALUE cNRoot;
//--------------------------------------------------------------------
/**
Prompt
Pass a prompt string to the interactive shell.
Will be called each frame so I omitted any fancy stuff
- 02-01-04 tom created
*/
//--------------------------------------------------------------------
nString nRubyServer::Prompt()
{
// no custom prompt as Prompt will be called every frame :-(
nString prompt;
prompt.Append("> ");
return prompt;
}
//--------------------------------------------------------------------
/**
Run
Evaluate a ruby command string
Result will be empty, as any errors get printed out by ruby itself for
ease of use.
- 02-01-04 Tom created
- 11-02-04 Tom error printing for N2
*/
//--------------------------------------------------------------------
bool nRubyServer::Run(const char *cmd_str, nString& result)
{
result.Clear();
int ret = 0;
rb_p(rb_eval_string_protect((char *)cmd_str, &ret));
if (ret)
{
//same as rb_p but without rb_default_rs
if (this->GetFailOnError())
{
n_error(RSTRING(rb_obj_as_string(rb_inspect(ruby_errinfo)))->ptr);
}
else
{
n_printf(RSTRING(rb_obj_as_string(rb_inspect(ruby_errinfo)))->ptr);
//n_printf(rb_default_rs);
}
return false;
}
return true;
}
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------
/**
NArg2RubyObj
Converts a nebula argument into an ruby native object.
TODO implement LIST Type for nebula 2
- 02-01-04 Tom created
- 11-02-04 Tom N2 args
*/
//--------------------------------------------------------------------
VALUE NArg2RubyObj(nArg *a)
{
switch (a->GetType()) {
case nArg::Void:
return Qnil;
case nArg::Int:
return INT2NUM(a->GetI());
case nArg::Float:
return rb_float_new(a->GetF());
case nArg::String:
return rb_str_new2(a->GetS());
case nArg::Bool:
return (a->GetB()==true?Qtrue:Qfalse);
case nArg::Object:
{
nRoot* o = (nRoot *) a->GetO();
if(o)
{
VALUE tst = Data_Wrap_Struct(cNRoot, 0, free_d, (void *)o);
return tst;
}
else
{
return Qnil;
}
}
//case nArg::ARGTYPE_CODE:
// return rb_str_new2(a->GetC());
case nArg::List:
{
nArg *args;
int num_args = a->GetL(args);
VALUE result = rb_ary_new2(num_args);
for(int i = 0; i < num_args; i++)
{
rb_ary_push(result, NArg2RubyObj(&args[i]));
}
return result;
}
default:
return Qundef;
}
return Qundef;
}
#ifdef __cplusplus
}
#endif
//--------------------------------------------------------------------
/**
RunCommand
Execute a nebula command in ruby
- 02-01-04 Tom created not tested to be done
- 11-02-04 Tom error printing for N2
*/
//--------------------------------------------------------------------
bool nRubyServer::RunCommand(nCmd *c)
{
//TODO
nArg *arg;
int num_args = c->GetNumInArgs();
c->Rewind();
VALUE rargs = Qfalse;
// handle single return args (no need to create list)
if (1 == num_args)
{
arg = c->In();
rargs = NArg2RubyObj(arg);
}
else
{
// rargs = rb_ary_new();
// more then one in arg, create an Array
int i;
for (i=0; i<num_args; i++)
{
arg = c->In();
rb_ary_push(rargs, NArg2RubyObj(arg));
//rargs[i] = NArg2RubyObj(arg);
}
}
//rb_str_new2(c->In()->GetS());
rb_p(rb_funcall2(rb_mKernel,rb_intern(c->In()->GetS()), num_args, &rargs));
if (NIL_P(ruby_errinfo))
{
//same as rb_p but without rb_default_rs
if (this->GetFailOnError())
{
n_error(RSTRING(rb_obj_as_string(rb_inspect(ruby_errinfo)))->ptr);
}
else
{
n_printf(RSTRING(rb_obj_as_string(rb_inspect(ruby_errinfo)))->ptr);
//n_printf(rb_default_rs);
}
return false;
}
return true;
}
//--------------------------------------------------------------------
/**
RunScript
Load and evaluate a ruby script then switches over to interactive mode
Result is left empty as errors get printed out by nebula itself for
ease of use.
- 18-12-03 Tom created
- 11-02-04 Tom error printing for N2
*/
//--------------------------------------------------------------------
bool nRubyServer::RunScript(const char *fname, nString& result)
{
char buf[N_MAXPATH];
result.Clear();
strcpy(buf,(kernelServer->GetFileServer()->ManglePath(fname).Get()));
this->print_error = true;
ruby_script(buf);
//rb_load_file(buf);
int ret =0;
rb_load_protect(rb_str_new2(buf), 0, &ret);
if (ret)
{
//rb_p(ruby_errinfo);
//same as rb_p but without rb_default_rs
if (this->GetFailOnError())
{
n_error(RSTRING(rb_obj_as_string(rb_inspect(ruby_errinfo)))->ptr);
}
else
{
n_printf(RSTRING(rb_obj_as_string(rb_inspect(ruby_errinfo)))->ptr);
//n_printf(rb_default_rs);
}
return false;
}
return true;
}
//--------------------------------------------------------------------
/**
@brief Invoke a Ruby function.
*/
bool nRubyServer::RunFunction(const char *funcName, nString& result)
{
nString cmdStr = funcName;
cmdStr.Append("()");
return this->Run(cmdStr.Get(), result);
}
//--------------------------------------------------------------------
/**
Trigger
Check for shutdown flag
- 18-12-03 Tom created
- 01-05-04 Tom cleaned up
*/
//--------------------------------------------------------------------
bool nRubyServer::Trigger(void)
{
if(!GetQuitRequested() && !finished)
{
return true;
}
else
{
return false;
}
}
//--------------------------------------------------------------------
// EOF
//--------------------------------------------------------------------
| [
"BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c"
] | [
[
[
1,
267
]
]
] |
529d27d51381dafc81e45d876cdddb9c74cb56d4 | ef23e388061a637f82b815d32f7af8cb60c5bb1f | /src/emu/cpu/sh4/sh4comn.h | 546468de860a577af428f1943de8fa266b407d59 | [] | no_license | marcellodash/psmame | 76fd877a210d50d34f23e50d338e65a17deff066 | 09f52313bd3b06311b910ed67a0e7c70c2dd2535 | refs/heads/master | 2021-05-29 23:57:23 | 2011-06-23 20:11:22 | 2011-06-23 20:11:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,775 | h | /*****************************************************************************
*
* sh4comn.h
*
* SH-4 non-specific components
*
*****************************************************************************/
#pragma once
#ifndef __SH4COMN_H__
#define __SH4COMN_H__
//#define USE_SH4DRC
/* speed up delay loops, bail out of tight loops */
#define BUSY_LOOP_HACKS 0
#define VERBOSE 0
#ifdef USE_SH4DRC
#include "cpu/drcfe.h"
#include "cpu/drcuml.h"
#include "cpu/drcumlsh.h"
class sh4_frontend;
#endif
#define CPU_TYPE_SH3 (2)
#define CPU_TYPE_SH4 (3)
#define LOG(x) do { if (VERBOSE) logerror x; } while (0)
#define EXPPRI(pl,po,p,n) (((4-(pl)) << 24) | ((15-(po)) << 16) | ((p) << 8) | (255-(n)))
#define NMIPRI() EXPPRI(3,0,16,SH4_INTC_NMI)
#define INTPRI(p,n) EXPPRI(4,2,p,n)
#define FP_RS(r) sh4->fr[(r)] // binary representation of single precision floating point register r
#define FP_RFS(r) *( (float *)(sh4->fr+(r)) ) // single precision floating point register r
#define FP_RFD(r) *( (double *)(sh4->fr+(r)) ) // double precision floating point register r
#define FP_XS(r) sh4->xf[(r)] // binary representation of extended single precision floating point register r
#define FP_XFS(r) *( (float *)(sh4->xf+(r)) ) // single precision extended floating point register r
#define FP_XFD(r) *( (double *)(sh4->xf+(r)) ) // double precision extended floating point register r
#ifdef LSB_FIRST
#define FP_RS2(r) sh4->fr[(r) ^ sh4->fpu_pr]
#define FP_RFS2(r) *( (float *)(sh4->fr+((r) ^ sh4->fpu_pr)) )
#define FP_XS2(r) sh4->xf[(r) ^ sh4->fpu_pr]
#define FP_XFS2(r) *( (float *)(sh4->xf+((r) ^ sh4->fpu_pr)) )
#endif
typedef struct
{
UINT32 ppc;
UINT32 pc, spc;
UINT32 pr;
UINT32 sr, ssr;
UINT32 gbr, vbr;
UINT32 mach, macl;
UINT32 r[16], rbnk[2][8], sgr;
UINT32 fr[16], xf[16];
UINT32 ea;
UINT32 delay;
UINT32 cpu_off;
UINT32 pending_irq;
UINT32 test_irq;
UINT32 fpscr;
UINT32 fpul;
UINT32 dbr;
UINT32 exception_priority[128];
int exception_requesting[128];
INT8 irq_line_state[17];
device_irq_callback irq_callback;
legacy_cpu_device *device;
address_space *internal;
address_space *program;
direct_read_data *direct;
address_space *io;
UINT32 *m;
INT8 nmi_line_state;
UINT8 sleep_mode;
int frt_input;
int irln;
int internal_irq_level;
int internal_irq_vector;
emu_timer *dma_timer[4];
emu_timer *refresh_timer;
emu_timer *rtc_timer;
emu_timer *timer[3];
UINT32 refresh_timer_base;
int dma_timer_active[4];
int sh4_icount;
int is_slave;
int cpu_clock, bus_clock, pm_clock;
int fpu_sz, fpu_pr;
int ioport16_pullup, ioport16_direction;
int ioport4_pullup, ioport4_direction;
void (*ftcsr_read_callback)(UINT32 data);
/* This MMU simulation is good for the simple remap used on Naomi GD-ROM SQ access *ONLY* */
UINT32 sh4_tlb_address[64];
UINT32 sh4_tlb_data[64];
UINT8 sh4_mmu_enabled;
int cpu_type;
#ifdef USE_SH4DRC
int icount;
int pcfsel; // last pcflush entry set
int maxpcfsel; // highest valid pcflush entry
UINT32 pcflushes[16]; // pcflush entries
drc_cache * cache; /* pointer to the DRC code cache */
drcuml_state * drcuml; /* DRC UML generator state */
sh4_frontend * drcfe; /* pointer to the DRC front-end class */
UINT32 drcoptions; /* configurable DRC options */
/* internal stuff */
UINT8 cache_dirty; /* true if we need to flush the cache */
/* parameters for subroutines */
UINT64 numcycles; /* return value from gettotalcycles */
UINT32 arg0; /* print_debug argument 1 */
UINT32 arg1; /* print_debug argument 2 */
UINT32 irq; /* irq we're taking */
/* register mappings */
drcuml_parameter regmap[16]; /* parameter to register mappings for all 16 integer registers */
drcuml_codehandle * entry; /* entry point */
drcuml_codehandle * read8; /* read byte */
drcuml_codehandle * write8; /* write byte */
drcuml_codehandle * read16; /* read half */
drcuml_codehandle * write16; /* write half */
drcuml_codehandle * read32; /* read word */
drcuml_codehandle * write32; /* write word */
drcuml_codehandle * interrupt; /* interrupt */
drcuml_codehandle * nocode; /* nocode */
drcuml_codehandle * out_of_cycles; /* out of cycles exception handler */
UINT32 prefadr;
UINT32 target;
#endif
} sh4_state;
#ifdef USE_SH4DRC
class sh4_frontend : public drc_frontend
{
public:
sh4_frontend(sh4_state &state, UINT32 window_start, UINT32 window_end, UINT32 max_sequence);
protected:
virtual bool describe(opcode_desc &desc, const opcode_desc *prev);
private:
bool describe_group_0(opcode_desc &desc, const opcode_desc *prev, UINT16 opcode);
bool describe_group_2(opcode_desc &desc, const opcode_desc *prev, UINT16 opcode);
bool describe_group_3(opcode_desc &desc, const opcode_desc *prev, UINT16 opcode);
bool describe_group_4(opcode_desc &desc, const opcode_desc *prev, UINT16 opcode);
bool describe_group_6(opcode_desc &desc, const opcode_desc *prev, UINT16 opcode);
bool describe_group_8(opcode_desc &desc, const opcode_desc *prev, UINT16 opcode);
bool describe_group_12(opcode_desc &desc, const opcode_desc *prev, UINT16 opcode);
bool describe_group_15(opcode_desc &desc, const opcode_desc *prev, UINT16 opcode);
sh4_state &m_context;
};
INLINE sh4_state *get_safe_token(device_t *device)
{
assert(device != NULL);
assert(device->type() == SH3 ||
device->type() == SH4);
return *(sh4_state **)downcast<legacy_cpu_device *>(device)->token();
}
#else
INLINE sh4_state *get_safe_token(device_t *device)
{
assert(device != NULL);
assert(device->type() == SH3 ||
device->type() == SH4);
return (sh4_state *)downcast<legacy_cpu_device *>(device)->token();
}
#endif
enum
{
ICF = 0x00800000,
OCFA = 0x00080000,
OCFB = 0x00040000,
OVF = 0x00020000
};
/* Bits in SR */
#define T 0x00000001
#define S 0x00000002
#define I 0x000000f0
#define Q 0x00000100
#define M 0x00000200
#define FD 0x00008000
#define BL 0x10000000
#define sRB 0x20000000
#define MD 0x40000000
/* 29 bits */
#define AM 0x1fffffff
#define FLAGS (MD|sRB|BL|FD|M|Q|I|S|T)
/* Bits in FPSCR */
#define RM 0x00000003
#define DN 0x00040000
#define PR 0x00080000
#define SZ 0x00100000
#define FR 0x00200000
#define Rn ((opcode>>8)&15)
#define Rm ((opcode>>4)&15)
#define REGFLAG_R(n) (1 << (n))
#define REGFLAG_FR(n) (1 << (n))
#define REGFLAG_XR(n) (1 << (n))
/* register flags 1 */
#define REGFLAG_PR (1 << 0)
#define REGFLAG_MACL (1 << 1)
#define REGFLAG_MACH (1 << 2)
#define REGFLAG_GBR (1 << 3)
#define REGFLAG_VBR (1 << 4)
#define REGFLAG_SR (1 << 5)
#define REGFLAG_SGR (1 << 6)
#define REGFLAG_FPUL (1 << 7)
#define REGFLAG_FPSCR (1 << 8)
#define REGFLAG_DBR (1 << 9)
#define REGFLAG_SSR (1 << 10)
#define REGFLAG_SPC (1 << 11)
void sh4_exception_recompute(sh4_state *sh4); // checks if there is any interrupt with high enough priority
void sh4_exception_request(sh4_state *sh4, int exception); // start requesting an exception
void sh4_exception_unrequest(sh4_state *sh4, int exception); // stop requesting an exception
void sh4_exception_checkunrequest(sh4_state *sh4, int exception);
void sh4_exception(sh4_state *sh4, const char *message, int exception); // handle exception
void sh4_change_register_bank(sh4_state *sh4, int to);
void sh4_syncronize_register_bank(sh4_state *sh4, int to);
void sh4_swap_fp_registers(sh4_state *sh4);
void sh4_default_exception_priorities(sh4_state *sh4); // setup default priorities for exceptions
void sh4_parse_configuration(sh4_state *sh4, const struct sh4_config *conf);
void sh4_set_irq_line(sh4_state *sh4, int irqline, int state); // set state of external interrupt line
#ifdef LSB_FIRST
void sh4_swap_fp_couples(sh4_state *sh4);
#endif
void sh4_common_init(device_t *device);
UINT32 sh4_getsqremap(sh4_state *sh4, UINT32 address);
READ64_HANDLER( sh4_tlb_r );
WRITE64_HANDLER( sh4_tlb_w );
INLINE void sh4_check_pending_irq(sh4_state *sh4, const char *message) // look for highest priority active exception and handle it
{
int a,irq,z;
irq = 0;
z = -1;
for (a=0;a <= SH4_INTC_ROVI;a++)
{
if (sh4->exception_requesting[a])
{
if ((int)sh4->exception_priority[a] > z)
{
z = sh4->exception_priority[a];
irq = a;
}
}
}
if (z >= 0)
{
sh4_exception(sh4, message, irq);
}
}
#endif /* __SH4COMN_H__ */
| [
"Mike@localhost"
] | [
[
[
1,
292
]
]
] |
36c97aeab9931cd36f199faa08e1b22971602a8f | 9738ebb36adfaa6f06fe2ba452aec6fcb8a06a5e | /heimdall-frontend/Source/main.cpp | 78336663e2410bdcbff28aee00cb5fc02b27cef7 | [] | no_license | superweapons/Heimdall-fc | 9f4ea33e4da6ffd209a7fb7afa51616eb2007832 | 73d77ddbf2f26c2d416b0ef4a57040e64ad86df2 | refs/heads/master | 2021-01-15 19:39:54 | 2011-11-16 02:54:26 | 2011-11-16 02:54:26 | 2,785,073 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,403 | cpp | /* Copyright (c) 2010-2011 Benjamin Dobell, Glass Echidna
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.*/
// Qt
#include <QtGui/QApplication>
// Heimdall Frontend
#include "mainwindow.h"
using namespace HeimdallFrontend;
int main(int argc, char *argv[])
{
QApplication application(argc, argv);
MainWindow window;
window.show();
return (application.exec());
}
| [
"benjamin.dobell@glassechidna.com.au",
"benjamin.dobell+github@glassechidna.com.au"
] | [
[
[
1,
1
],
[
24,
26
],
[
31,
31
],
[
33,
34
],
[
36,
36
]
],
[
[
2,
23
],
[
27,
30
],
[
32,
32
],
[
35,
35
],
[
37,
37
]
]
] |
968aed9d9d736e2591314d2929e18e3fc1aa2103 | b2d46af9c6152323ce240374afc998c1574db71f | /cursovideojuegos/theflostiproject/3rdParty/boost/libs/iterator/test/filter_iterator_test.cpp | 8f84f1a221111a02e20fd0d8a083aaa3a71ae2cc | [] | no_license | bugbit/cipsaoscar | 601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4 | 52aa8b4b67d48f59e46cb43527480f8b3552e96d | refs/heads/master | 2021-01-10 21:31:18 | 2011-09-28 16:39:12 | 2011-09-28 16:39:12 | 33,032,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,203 | cpp | // Copyright David Abrahams 2003, Jeremy Siek 2004.
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/iterator/filter_iterator.hpp>
#include <boost/iterator/reverse_iterator.hpp>
#include <boost/iterator/new_iterator_tests.hpp>
#include <boost/type_traits/is_convertible.hpp>
#include <boost/concept_check.hpp>
#include <boost/concept_archetype.hpp>
#include <boost/iterator/iterator_concepts.hpp>
#include <boost/iterator/iterator_archetypes.hpp>
#include <boost/cstdlib.hpp>
#include <deque>
#include <iostream>
using boost::dummyT;
struct one_or_four
{
bool operator()(dummyT x) const
{
return x.foo() == 1 || x.foo() == 4;
}
};
template <class T> struct undefined;
template <class T> struct see_type;
// Test filter iterator
int main()
{
// Concept checks
// Adapting old-style iterators
{
typedef boost::filter_iterator<one_or_four, boost::input_iterator_archetype<dummyT> > Iter;
boost::function_requires< boost::InputIteratorConcept<Iter> >();
boost::function_requires< boost_concepts::ReadableIteratorConcept<Iter> >();
boost::function_requires< boost_concepts::SinglePassIteratorConcept<Iter> >();
}
{
typedef boost::filter_iterator<one_or_four, boost::input_output_iterator_archetype<dummyT> > Iter;
boost::function_requires< boost::InputIteratorConcept<Iter> >();
boost::function_requires< boost::OutputIteratorConcept<Iter, dummyT> >();
boost::function_requires< boost_concepts::ReadableIteratorConcept<Iter> >();
boost::function_requires< boost_concepts::WritableIteratorConcept<Iter> >();
boost::function_requires< boost_concepts::SinglePassIteratorConcept<Iter> >();
}
{
typedef boost::filter_iterator<one_or_four, boost::forward_iterator_archetype<dummyT> > Iter;
boost::function_requires< boost::ForwardIteratorConcept<Iter> >();
boost::function_requires< boost_concepts::ReadableIteratorConcept<Iter> >();
boost::function_requires< boost_concepts::ForwardTraversalConcept<Iter> >();
}
{
typedef boost::filter_iterator<one_or_four, boost::mutable_forward_iterator_archetype<dummyT> > Iter;
boost::function_requires< boost::Mutable_ForwardIteratorConcept<Iter> >();
boost::function_requires< boost_concepts::ReadableIteratorConcept<Iter> >();
boost::function_requires< boost_concepts::WritableIteratorConcept<Iter> >();
boost::function_requires< boost_concepts::ForwardTraversalConcept<Iter> >();
}
// Adapting new-style iterators
{
typedef boost::iterator_archetype<
const dummyT
, boost::iterator_archetypes::readable_iterator_t
, boost::single_pass_traversal_tag
> BaseIter;
typedef boost::filter_iterator<one_or_four, BaseIter> Iter;
boost::function_requires< boost::InputIteratorConcept<Iter> >();
boost::function_requires< boost_concepts::ReadableIteratorConcept<Iter> >();
boost::function_requires< boost_concepts::SinglePassIteratorConcept<Iter> >();
}
#if !BOOST_WORKAROUND(BOOST_MSVC, == 1200) // Causes Internal Error in linker.
{
typedef boost::iterator_archetype<
dummyT
, boost::iterator_archetypes::readable_writable_iterator_t
, boost::single_pass_traversal_tag
> BaseIter;
typedef boost::filter_iterator<one_or_four, BaseIter> Iter;
boost::function_requires< boost::InputIteratorConcept<Iter> >();
boost::function_requires< boost::OutputIteratorConcept<Iter, dummyT> >();
boost::function_requires< boost_concepts::ReadableIteratorConcept<Iter> >();
boost::function_requires< boost_concepts::WritableIteratorConcept<Iter> >();
boost::function_requires< boost_concepts::SinglePassIteratorConcept<Iter> >();
}
#endif
{
typedef boost::iterator_archetype<
const dummyT
, boost::iterator_archetypes::readable_iterator_t
, boost::forward_traversal_tag
> BaseIter;
typedef boost::filter_iterator<one_or_four, BaseIter> Iter;
boost::function_requires< boost::InputIteratorConcept<Iter> >();
boost::function_requires< boost_concepts::ReadableIteratorConcept<Iter> >();
boost::function_requires< boost_concepts::ForwardTraversalConcept<Iter> >();
}
#if !BOOST_WORKAROUND(BOOST_MSVC, == 1200) // Causes Internal Error in linker.
{
typedef boost::iterator_archetype<
dummyT
, boost::iterator_archetypes::readable_writable_iterator_t
, boost::forward_traversal_tag
> BaseIter;
typedef boost::filter_iterator<one_or_four, BaseIter> Iter;
boost::function_requires< boost_concepts::ReadableIteratorConcept<Iter> >();
boost::function_requires< boost_concepts::WritableIteratorConcept<Iter> >();
boost::function_requires< boost_concepts::ForwardTraversalConcept<Iter> >();
}
{
typedef boost::iterator_archetype<
const dummyT
, boost::iterator_archetypes::readable_lvalue_iterator_t
, boost::forward_traversal_tag
> BaseIter;
typedef boost::filter_iterator<one_or_four, BaseIter> Iter;
boost::function_requires< boost::ForwardIteratorConcept<Iter> >();
boost::function_requires< boost_concepts::ReadableIteratorConcept<Iter> >();
boost::function_requires< boost_concepts::LvalueIteratorConcept<Iter> >();
boost::function_requires< boost_concepts::ForwardTraversalConcept<Iter> >();
}
{
typedef boost::iterator_archetype<
dummyT
, boost::iterator_archetypes::writable_lvalue_iterator_t
, boost::forward_traversal_tag
> BaseIter;
typedef boost::filter_iterator<one_or_four, BaseIter> Iter;
boost::function_requires< boost::Mutable_ForwardIteratorConcept<Iter> >();
boost::function_requires< boost_concepts::WritableIteratorConcept<Iter> >();
boost::function_requires< boost_concepts::LvalueIteratorConcept<Iter> >();
boost::function_requires< boost_concepts::ForwardTraversalConcept<Iter> >();
}
#endif
// Run-time tests
dummyT array[] = { dummyT(0), dummyT(1), dummyT(2),
dummyT(3), dummyT(4), dummyT(5) };
const int N = sizeof(array)/sizeof(dummyT);
typedef boost::filter_iterator<one_or_four, dummyT*> filter_iter;
boost::bidirectional_readable_iterator_test(
filter_iter(one_or_four(), array, array+N)
, dummyT(1), dummyT(4));
BOOST_STATIC_ASSERT(
(!boost::is_convertible<
boost::iterator_traversal<filter_iter>::type
, boost::random_access_traversal_tag
>::value
));
//# endif
// On compilers not supporting partial specialization, we can do more type
// deduction with deque iterators than with pointers... unless the library
// is broken ;-(
std::deque<dummyT> array2;
std::copy(array+0, array+N, std::back_inserter(array2));
boost::bidirectional_readable_iterator_test(
boost::make_filter_iterator(one_or_four(), array2.begin(), array2.end()),
dummyT(1), dummyT(4));
boost::bidirectional_readable_iterator_test(
boost::make_filter_iterator(one_or_four(), array2.begin(), array2.end()),
dummyT(1), dummyT(4));
boost::bidirectional_readable_iterator_test(
boost::make_filter_iterator(
one_or_four()
, boost::make_reverse_iterator(array2.end())
, boost::make_reverse_iterator(array2.begin())
),
dummyT(4), dummyT(1));
boost::bidirectional_readable_iterator_test(
filter_iter(array+0, array+N),
dummyT(1), dummyT(4));
boost::bidirectional_readable_iterator_test(
filter_iter(one_or_four(), array, array + N),
dummyT(1), dummyT(4));
std::cout << "test successful " << std::endl;
return boost::exit_success;
}
| [
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
] | [
[
[
1,
197
]
]
] |
fbe7793051ae6840f181903ca0b7fac51ae5c8b0 | 74388fdac3615e98665c61031afe602829bb95f9 | /tags/MainProject/widget/glwidget.h | fcae8d34fac849147a433314fd550ca045cae5f0 | [] | no_license | mvm9289/vig-qp2010 | 4bc78bce61970e1f67a53ca1a98ba7e10871615d | 2005d0870f53a0a8c78bafad711a3b7f7e11ba4b | refs/heads/master | 2020-03-27 22:55:51 | 2010-09-23 21:15:11 | 2010-09-23 21:15:11 | 32,334,738 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 4,575 | h | #ifndef _GLWIDGET_H_
#define _GLWIDGET_H_
#include <QtOpenGL/qgl.h>
#include <QKeyEvent>
#include <iostream>
#include <qstring.h>
#include <qfiledialog.h>
#include <qtimer.h>
#include <QtDesigner/QDesignerExportWidget>
#include "material_lib.h"
#include "point.h"
#include "scene.h"
#include "llum.h"
#include "finestraLlums.h"
#include <list>
#define ROTATION_FACTOR 0.2
#define ZOOM_FACTOR 0.1
#define PAN_FACTOR 0.03
#define DEFAULT_FOVY 60.0
#define FPV_FOVY 90.0
class QDESIGNER_WIDGET_EXPORT GLWidget : public QGLWidget
{
Q_OBJECT
public:
GLWidget(QWidget * parent);
signals:
void carOpened(bool);
void dialValueChanged(int);
void activateAnimation(QString);
void activateFirstPersonView(bool);
public slots:
// help - Ajuda per la terminal des de la que hem engegat el programa.
void help(void);
// Afegiu aquí la declaració dels slots que necessiteu
// Reestablir la camera per defecte
void setDefaultCamera();
// Obrir un dialeg per seleccionar un model pel vehicle i carregar-lo
void openCar();
// Establir una novia orientación pel vehicle
void orientCar(int alpha);
void timerDone();
void setCarSpeed(int speed);
void configureLight(llum* light);
void showLightsWindow();
void activeSmooth(bool active);
void activeLocalViewer(bool active);
void activeCullFace(bool active);
void activeFirstPersonView(bool active);
void setFPVzFar(int value);
void activeCarLampposts(bool active);
protected:
// initializeGL() - Aqui incluim les inicialitzacions del contexte grafic.
virtual void initializeGL();
// paintGL - Mètode cridat cada cop que cal refrescar la finestra.
// Tot el que es dibuixa es dibuixa aqui.
virtual void paintGL( void );
// resizeGL() - Es cridat quan canvi la mida del widget
virtual void resizeGL (int width, int height);
// keyPressEvent() - Cridat quan es prem una tecla
virtual void keyPressEvent(QKeyEvent *e);
// mousePressEvent() i mouseReleaseEvent()
virtual void mousePressEvent( QMouseEvent *e);
virtual void mouseReleaseEvent( QMouseEvent *);
// mouseMoveEvent() - Cridat quan s'arrosega el ratoli amb algun botó premut.
virtual void mouseMoveEvent(QMouseEvent *e);
// Calcular el parametres de la camera per defecte
void computeDefaultCamera();
// Configurar la matriu modelview segons els parametres de la camera
void setModelview();
// Configurar la matriu de projecció segons els parametres de la camera
void setProjection();
// Recalcular els plans de retallat de l'escena
void computeCuttingPlanes();
void saveCurrentCamera();
void restoreOldCamera();
// Configuracio dels llums
void initializeLights();
void configure(llum* light);
void updateLightsPosition();
void onOffLamppost(int xClick, int yClick); // Realitza el proces de seleccio i tractament del fanal seleccionat per l'usuari
int getSelectedLamppost(int xClick, int yClick); // Retorna el fanal seleccionat per l'usuari mes proper al obs
void onOffCarLampposts(); // Realitza el proces de seleccio i tractament dels fanals visibles pel vehicle
list<int> getVisibleLampposts(); // Retorna com a maxim 4 fanals, els mes propers i visibles pel vehicle
void updateModelView();
private:
// interaccio
typedef enum {NONE, ROTATE, ZOOM, PAN} InteractiveAction;
InteractiveAction DoingInteractive;
int xClick, yClick;
Scene scene; // Escena a representar en el widget
// Afegiu els atributs que necessiteu
QTimer* timer;
llum* L[8];
finestraLlums lightsWindow;
double fovy;
double aspect;
double initialZNear;
double initialZNearLast;
double zNear;
double zNearLast;
double zNearAux;
double zNearAuxLast;
double initialZFar;
double initialZFarLast;
double zFar;
double zFarLast;
double zFarAux;
double zFarAuxLast;
double maxFPVzFar;
double zFarFPV;
Point VRP;
Point VRPLast;
Point OBS;
Point OBSLast;
Vector UP;
Vector UPLast;
double distOBS;
double distOBSLast;
bool carLoaded;
bool firstPersonView;
int NLampposts;
list<int> onLampposts; // Llista amb els fanals encesos per l'usuario en el moment actual
list<int> onCarLampposts; // Llista amb els fanals encesos davant del vehicle (no inclou els encesos manualment)
bool carLampposts; // Indica si cal o no activar els fanals automatics davant del vehicle
};
#endif
| [
"mvm9289@58588aa8-722a-b9c2-831f-873cbd2be5b1"
] | [
[
[
1,
166
]
]
] |
cb4bcf7c7e17563488cd7e7342112f6a976ce79f | 974a20e0f85d6ac74c6d7e16be463565c637d135 | /trunk/coreLibrary_200/source/physics/dgCollisionEllipse.cpp | 4f8730570a353594e86370dbc6ad03ed1267a836 | [] | no_license | Naddiseo/Newton-Dynamics-fork | cb0b8429943b9faca9a83126280aa4f2e6944f7f | 91ac59c9687258c3e653f592c32a57b61dc62fb6 | refs/heads/master | 2021-01-15 13:45:04 | 2011-11-12 04:02:33 | 2011-11-12 04:02:33 | 2,759,246 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,212 | cpp | /* Copyright (c) <2003-2011> <Julio Jerez, Newton Game Dynamics>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "dgPhysicsStdafx.h"
#include "dgBody.h"
#include "dgContact.h"
#include "dgCollisionEllipse.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
dgCollisionEllipse::dgCollisionEllipse(dgMemoryAllocator* const allocator,
dgUnsigned32 signature, dgFloat32 rx, dgFloat32 ry, dgFloat32 rz,
const dgMatrix& offsetMatrix) :
dgCollisionSphere(allocator, signature, dgFloat32(1.0f), offsetMatrix), m_scale(
rx, ry, rz, dgFloat32(0.0f)), m_invScale(dgFloat32(1.0f) / rx,
dgFloat32(1.0f) / ry, dgFloat32(1.0f) / rz, dgFloat32(0.0f))
{
m_rtti |= dgCollisionEllipse_RTTI;
m_collsionId = m_ellipseCollision;
}
dgCollisionEllipse::dgCollisionEllipse(dgWorld* const world,
dgDeserialize deserialization, void* const userData) :
dgCollisionSphere(world, deserialization, userData)
{
dgVector size;
m_rtti |= dgCollisionEllipse_RTTI;
deserialization(userData, &m_scale, sizeof(dgVector));
m_invScale.m_x = dgFloat32(1.0f) / m_scale.m_x;
m_invScale.m_y = dgFloat32(1.0f) / m_scale.m_y;
m_invScale.m_z = dgFloat32(1.0f) / m_scale.m_z;
m_invScale.m_w = dgFloat32(0.0f);
}
dgCollisionEllipse::~dgCollisionEllipse()
{
}
dgInt32 dgCollisionEllipse::CalculateSignature() const
{
dgUnsigned32 buffer[2 * sizeof(dgMatrix) / sizeof(dgInt32)];
memset(buffer, 0, sizeof(buffer));
buffer[0] = m_ellipseCollision;
buffer[1] = Quantize(m_scale.m_x);
buffer[2] = Quantize(m_scale.m_y);
buffer[3] = Quantize(m_scale.m_z);
memcpy(&buffer[4], &m_offset, sizeof(dgMatrix));
return dgInt32(MakeCRC(buffer, sizeof(buffer)));
}
void dgCollisionEllipse::SetCollisionBBox(const dgVector& p0__,
const dgVector& p1__)
{
_ASSERTE(0);
}
void dgCollisionEllipse::CalcAABB(const dgMatrix &matrix, dgVector &p0,
dgVector &p1) const
{
dgMatrix mat(matrix);
mat.m_front = mat.m_front.Scale(m_scale.m_x);
mat.m_up = mat.m_up.Scale(m_scale.m_y);
mat.m_right = mat.m_right.Scale(m_scale.m_z);
dgCollisionConvex::CalcAABB(mat, p0, p1);
}
void dgCollisionEllipse::CalcAABBSimd(const dgMatrix &matrix, dgVector& p0,
dgVector& p1) const
{
dgMatrix mat(matrix);
mat.m_front = mat.m_front.Scale(m_scale.m_x);
mat.m_up = mat.m_up.Scale(m_scale.m_y);
mat.m_right = mat.m_right.Scale(m_scale.m_z);
dgCollisionConvex::CalcAABBSimd(mat, p0, p1);
#if 0
dgVector xxx0;
dgVector xxx1;
CalcAABB (matrix, xxx0, xxx1);
_ASSERTE (dgAbsf(xxx0.m_x - p0.m_x) < 1.0e-3f);
_ASSERTE (dgAbsf(xxx0.m_y - p0.m_y) < 1.0e-3f);
_ASSERTE (dgAbsf(xxx0.m_z - p0.m_z) < 1.0e-3f);
_ASSERTE (dgAbsf(xxx1.m_x - p1.m_x) < 1.0e-3f);
_ASSERTE (dgAbsf(xxx1.m_y - p1.m_y) < 1.0e-3f);
_ASSERTE (dgAbsf(xxx1.m_z - p1.m_z) < 1.0e-3f);
#endif
}
dgVector dgCollisionEllipse::SupportVertex(const dgVector& dir) const
{
_ASSERTE((dir % dir) > dgFloat32 (0.999f));
dgVector dir1(dir.m_x * m_scale.m_x, dir.m_y * m_scale.m_y,
dir.m_z * m_scale.m_z, dgFloat32(0.0f));
dir1 = dir1.Scale(dgRsqrt (dir1 % dir1));
dgVector p(dgCollisionSphere::SupportVertex(dir1));
return dgVector(p.m_x * m_scale.m_x, p.m_y * m_scale.m_y, p.m_z * m_scale.m_z,
dgFloat32(0.0f));
}
dgVector dgCollisionEllipse::SupportVertexSimd(const dgVector& dir) const
{
#ifdef DG_BUILD_SIMD_CODE
_ASSERTE((dir % dir) > dgFloat32 (0.999f));
_ASSERTE((dgUnsigned64(&dir) & 0x0f) == 0);
_ASSERTE((dgUnsigned64(&m_scale) & 0x0f) == 0);
dgVector dir1;
simd_type n;
simd_type tmp;
simd_type mag2;
// dir1 = dgVector (dir.m_x * m_scale.m_x, dir.m_y * m_scale.m_y, dir.m_z * m_scale.m_z, dgFloat32 (0.0f));
n = simd_mul_v (*(simd_type*)&dir, *(simd_type*)&m_scale);
// dir1 = dir1.Scale (dgRsqrt (dir1 % dir1));
mag2 = simd_mul_v (n, n);
mag2 =
simd_add_s (simd_add_v (mag2, simd_move_hl_v (mag2, mag2)), simd_permut_v (mag2, mag2, PURMUT_MASK (3,3,3,1)));
tmp = simd_rsqrt_s(mag2);
mag2 =
simd_mul_s (simd_mul_s(*(simd_type*)&m_nrh0p5, tmp), simd_mul_sub_s (*(simd_type*)&m_nrh3p0, simd_mul_s (mag2, tmp), tmp));
(*(simd_type*) &dir1) =
simd_mul_v (n, simd_permut_v (mag2, mag2, PURMUT_MASK (3,0,0,0)));
dgVector p(dgCollisionSphere::SupportVertexSimd(dir1));
return dgVector(p.m_x * m_scale.m_x, p.m_y * m_scale.m_y, p.m_z * m_scale.m_z,
dgFloat32(0.0f));
#else
return dgVector (dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f));
#endif
}
dgInt32 dgCollisionEllipse::CalculatePlaneIntersection(const dgVector& normal,
const dgVector& point, dgVector* const contactsOut) const
{
_ASSERTE((normal % normal) > dgFloat32 (0.999f));
// contactsOut[0] = point;
dgVector n(normal.m_x * m_scale.m_x, normal.m_y * m_scale.m_y,
normal.m_z * m_scale.m_z, dgFloat32(0.0f));
n = n.Scale((normal % point) / (n % n));
contactsOut[0] = dgVector(n.m_x * m_scale.m_x, n.m_y * m_scale.m_y,
n.m_z * m_scale.m_z, dgFloat32(0.0f));
return 1;
}
dgInt32 dgCollisionEllipse::CalculatePlaneIntersectionSimd(
const dgVector& normal, const dgVector& point,
dgVector* const contactsOut) const
{
#ifdef DG_BUILD_SIMD_CODE
_ASSERTE((normal % normal) > dgFloat32 (0.999f));
dgVector n(normal.m_x * m_scale.m_x, normal.m_y * m_scale.m_y,
normal.m_z * m_scale.m_z, dgFloat32(0.0f));
n = n.Scale((normal % point) / (n % n));
contactsOut[0] = dgVector(n.m_x * m_scale.m_x, n.m_y * m_scale.m_y,
n.m_z * m_scale.m_z, dgFloat32(0.0f));
return 1;
#else
return 0;
#endif
}
void dgCollisionEllipse::DebugCollision(const dgMatrix& matrixPtr,
OnDebugCollisionMeshCallback callback, void* const userData) const
{
dgMatrix mat(GetOffsetMatrix() * matrixPtr);
mat.m_front = mat.m_front.Scale(m_scale.m_x);
mat.m_up = mat.m_up.Scale(m_scale.m_y);
mat.m_right = mat.m_right.Scale(m_scale.m_z);
mat = GetOffsetMatrix().Inverse() * mat;
dgCollisionSphere::DebugCollision(mat, callback, userData);
}
dgFloat32 dgCollisionEllipse::RayCast(const dgVector& p0, const dgVector& p1,
dgContactPoint& contactOut, OnRayPrecastAction preFilter,
const dgBody* const body, void* const userData) const
{
dgFloat32 t;
if (PREFILTER_RAYCAST (preFilter, body, this, userData))
{
return dgFloat32(1.2f);
}
dgVector q0(p0.m_x * m_invScale.m_x, p0.m_y * m_invScale.m_y,
p0.m_z * m_invScale.m_z, dgFloat32(0.0f));
dgVector q1(p1.m_x * m_invScale.m_x, p1.m_y * m_invScale.m_y,
p1.m_z * m_invScale.m_z, dgFloat32(0.0f));
t = dgCollisionSphere::RayCast(q0, q1, contactOut, NULL, NULL, NULL);
return t;
}
dgFloat32 dgCollisionEllipse::RayCastSimd(const dgVector& p0,
const dgVector& p1, dgContactPoint& contactOut,
OnRayPrecastAction preFilter, const dgBody* const body,
void* const userData) const
{
dgFloat32 t;
if (PREFILTER_RAYCAST (preFilter, body, this, userData))
{
return dgFloat32(1.2f);
}
dgVector q0(p0.m_x * m_invScale.m_x, p0.m_y * m_invScale.m_y,
p0.m_z * m_invScale.m_z, dgFloat32(0.0f));
dgVector q1(p1.m_x * m_invScale.m_x, p1.m_y * m_invScale.m_y,
p1.m_z * m_invScale.m_z, dgFloat32(0.0f));
t = dgCollisionSphere::RayCastSimd(q0, q1, contactOut, NULL, NULL, NULL);
return t;
}
dgFloat32 dgCollisionEllipse::CalculateMassProperties(dgVector& inertia,
dgVector& crossInertia, dgVector& centerOfMass) const
{
return dgCollisionConvex::CalculateMassProperties(inertia, crossInertia,
centerOfMass);
}
void dgCollisionEllipse::GetCollisionInfo(dgCollisionInfo* info) const
{
dgCollisionConvex::GetCollisionInfo(info);
info->m_sphere.m_r0 = m_scale.m_x;
info->m_sphere.m_r1 = m_scale.m_y;
info->m_sphere.m_r2 = m_scale.m_z;
info->m_offsetMatrix = GetOffsetMatrix();
// strcpy (info->m_collisionType, "sphere");
info->m_collisionType = m_sphereCollision;
}
void dgCollisionEllipse::Serialize(dgSerialize callback,
void* const userData) const
{
dgCollisionSphere::Serialize(callback, userData);
callback(userData, &m_scale, sizeof(dgVector));
}
| [
"jerezjulio@sbcglobal.net@b7a2f1d6-d59d-a8fe-1e9e-8d4888b32692"
] | [
[
[
1,
266
]
]
] |
045cdc4d005f6463cce4337a7bb5570a9b0792c2 | f744f8897adce6654cdfe6466eaf4d0fad4ba661 | /src/view/glInfo.cpp | 955c600a947a7252b597af37988b42c06095e5ba | [] | no_license | pizibing/bones-animation | 37919ab3750683a5da0cc849f80d1e0f5b37c89c | 92ce438e28e3020c0e8987299c11c4b74ff98ed5 | refs/heads/master | 2016-08-03 05:34:19 | 2009-09-16 14:59:32 | 2009-09-16 14:59:32 | 33,969,248 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,549 | cpp | ///////////////////////////////////////////////////////////////////////////////
// glInfo.cpp
// ==========
// get GL vendor, version, supported extensions and other states using glGet*
// functions and store them glInfo struct variable
//
// To get valid OpenGL infos, OpenGL rendering context (RC) must be opened
// before calling glInfo::getInfo(). Otherwise it returns false.
//
///////////////////////////////////////////////////////////////////////////////
#include <GL/glut.h>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <algorithm>
#include "glInfo.h"
using std::string;
using std::stringstream;
using std::vector;
using std::cout;
using std::endl;
///////////////////////////////////////////////////////////////////////////////
// extract openGL info
// This function must be called after GL rendering context opened.
///////////////////////////////////////////////////////////////////////////////
bool glInfo::getInfo()
{
char* str = 0;
char* tok = 0;
// get vendor string
str = (char*)glGetString(GL_VENDOR);
if(str) this->vendor = str; // check NULL return value
else return false;
// get renderer string
str = (char*)glGetString(GL_RENDERER);
if(str) this->renderer = str; // check NULL return value
else return false;
// get version string
str = (char*)glGetString(GL_VERSION);
if(str) this->version = str; // check NULL return value
else return false;
// get all extensions as a string
str = (char*)glGetString(GL_EXTENSIONS);
// split extensions
if(str)
{
tok = strtok((char*)str, " ");
while(tok)
{
this->extensions.push_back(tok); // put a extension into struct
tok = strtok(0, " "); // next token
}
}
else
{
return false;
}
// sort extension by alphabetical order
std::sort(this->extensions.begin(), this->extensions.end());
// get number of color bits
glGetIntegerv(GL_RED_BITS, &this->redBits);
glGetIntegerv(GL_GREEN_BITS, &this->greenBits);
glGetIntegerv(GL_BLUE_BITS, &this->blueBits);
glGetIntegerv(GL_ALPHA_BITS, &this->alphaBits);
// get depth bits
glGetIntegerv(GL_DEPTH_BITS, &this->depthBits);
// get stecil bits
glGetIntegerv(GL_STENCIL_BITS, &this->stencilBits);
// get max number of lights allowed
glGetIntegerv(GL_MAX_LIGHTS, &this->maxLights);
// get max texture resolution
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &this->maxTextureSize);
// get max number of clipping planes
glGetIntegerv(GL_MAX_CLIP_PLANES, &this->maxClipPlanes);
// get max modelview and projection matrix stacks
glGetIntegerv(GL_MAX_MODELVIEW_STACK_DEPTH, &this->maxModelViewStacks);
glGetIntegerv(GL_MAX_PROJECTION_STACK_DEPTH, &this->maxProjectionStacks);
glGetIntegerv(GL_MAX_ATTRIB_STACK_DEPTH, &this->maxAttribStacks);
// get max texture stacks
glGetIntegerv(GL_MAX_TEXTURE_STACK_DEPTH, &this->maxTextureStacks);
return true;
}
///////////////////////////////////////////////////////////////////////////////
// check if the video card support a certain extension
///////////////////////////////////////////////////////////////////////////////
bool glInfo::isExtensionSupported(const char* ext)
{
// search corresponding extension
std::vector< string >::const_iterator iter = this->extensions.begin();
std::vector< string >::const_iterator endIter = this->extensions.end();
while(iter != endIter)
{
if(ext == *iter)
return true;
else
++iter;
}
return false;
}
///////////////////////////////////////////////////////////////////////////////
// print OpenGL info to screen and save to a file
///////////////////////////////////////////////////////////////////////////////
void glInfo::printSelf()
{
stringstream ss;
ss << endl; // blank line
ss << "OpenGL Driver Info" << endl;
ss << "==================" << endl;
ss << "Vendor: " << this->vendor << endl;
ss << "Version: " << this->version << endl;
ss << "Renderer: " << this->renderer << endl;
ss << endl;
ss << "Color Bits(R,G,B,A): (" << this->redBits << ", " << this->greenBits
<< ", " << this->blueBits << ", " << this->alphaBits << ")\n";
ss << "Depth Bits: " << this->depthBits << endl;
ss << "Stencil Bits: " << this->stencilBits << endl;
ss << endl;
ss << "Max Texture Size: " << this->maxTextureSize << "x" << this->maxTextureSize << endl;
ss << "Max Lights: " << this->maxLights << endl;
ss << "Max Clip Planes: " << this->maxClipPlanes << endl;
ss << "Max Modelview Matrix Stacks: " << this->maxModelViewStacks << endl;
ss << "Max Projection Matrix Stacks: " << this->maxProjectionStacks << endl;
ss << "Max Attribute Stacks: " << this->maxAttribStacks << endl;
ss << "Max Texture Stacks: " << this->maxTextureStacks << endl;
ss << endl;
ss << "Total Number of Extensions: " << this->extensions.size() << endl;
ss << "==============================" << endl;
for(unsigned int i = 0; i < this->extensions.size(); ++i)
ss << this->extensions.at(i) << endl;
ss << "======================================================================" << endl;
cout << ss.str() << endl;
}
| [
"xljacwy@yahoo.com.cn"
] | [
[
[
1,
164
]
]
] |
e505a888c6713576dfa94878c7b265ceb4e3d3ef | ef99cef8dc1995c6535a131e46cd89dda30fcecd | /InitDialog.cpp | b7e6ee26745da36f1fd8800034b02cce2d768270 | [] | no_license | sundapeng/snlcomplier | 37b738db9631355621d872e4156c971927a6d7ce | 13a5318454dcb9c405b0cfc29a3371df6274ee24 | refs/heads/master | 2016-09-05 15:44:33 | 2010-07-02 04:56:09 | 2010-07-02 04:56:09 | 32,118,730 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 10,616 | cpp | // InitDialog.cpp : implementation file
//
#include "stdafx.h"
#include "AI3.h"
#include "InitDialog.h"
/////////////////////////////////////////////////////////////////////////////
// CInitDialog dialog
CInitDialog::CInitDialog(CWnd* pParent /*=NULL*/)
: CDialog(CInitDialog::IDD, pParent)
{
}
void CInitDialog::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_ED1, m_ED1);
DDX_Control(pDX, IDC_ED2, m_ED2);
DDX_Control(pDX, IDC_ED3, m_ED3);
DDX_Control(pDX, IDC_ED4, m_ED4);
DDX_Control(pDX, IDC_ED5, m_ED5);
DDX_Control(pDX, IDC_ED6, m_ED6);
DDX_Control(pDX, IDC_ED7, m_ED7);
DDX_Control(pDX, IDC_ED8, m_ED8);
DDX_Control(pDX, IDC_ED9, m_ED9);
DDX_Control(pDX, IDC_ST1, m_ST1);
DDX_Control(pDX, IDC_ST2, m_ST2);
DDX_Control(pDX, IDC_ST3, m_ST3);
DDX_Control(pDX, IDC_ST4, m_ST4);
DDX_Control(pDX, IDC_ST5, m_ST5);
DDX_Control(pDX, IDC_ST6, m_ST6);
DDX_Control(pDX, IDC_ST7, m_ST7);
DDX_Control(pDX, IDC_ST8, m_ST8);
DDX_Control(pDX, IDC_ST9, m_ST9);
}
BEGIN_MESSAGE_MAP(CInitDialog, CDialog)
ON_BN_CLICKED(IDC_ST1, OnSrcButton1)
ON_BN_CLICKED(IDC_ST2, OnSrcButton2)
ON_BN_CLICKED(IDC_ST3, OnSrcButton3)
ON_BN_CLICKED(IDC_ST4, OnSrcButton4)
ON_BN_CLICKED(IDC_ST5, OnSrcButton5)
ON_BN_CLICKED(IDC_ST6, OnSrcButton6)
ON_BN_CLICKED(IDC_ST7, OnSrcButton7)
ON_BN_CLICKED(IDC_ST8, OnSrcButton8)
ON_BN_CLICKED(IDC_ST9, OnSrcButton9)
ON_BN_CLICKED(IDC_ED1, OnDescButton1)
ON_BN_CLICKED(IDC_ED2, OnDescButton2)
ON_BN_CLICKED(IDC_ED3, OnDescButton3)
ON_BN_CLICKED(IDC_ED4, OnDescButton4)
ON_BN_CLICKED(IDC_ED5, OnDescButton5)
ON_BN_CLICKED(IDC_ED6, OnDescButton6)
ON_BN_CLICKED(IDC_ED7, OnDescButton7)
ON_BN_CLICKED(IDC_ED8, OnDescButton8)
ON_BN_CLICKED(IDC_ED9, OnDescButton9)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CInitDialog message handlers
BOOL CInitDialog::OnInitDialog()
{
CDialog::OnInitDialog();
int k=1;
for(int i=0;i<MaxItem;i++)
for(int j=0;j<MaxItem;j++)
{
m_Src[i][j] = k;
m_Desc[i][j] = k++;
}
m_Src[MaxItem-1][MaxItem-1] = 0;
m_Desc[MaxItem-1][MaxItem-1] = 0;
UpdateSrcRadio();
UpdateDescRadio();
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
int CInitDialog::GetSrcData(int i,int j)
{
return m_Src[i][j];
}
DataType CInitDialog::GetDescData(int i,int j)
{
return m_Desc[i][j];
}
void CInitDialog::OnSrcButton1()
{
if(m_Src[0][1] ==0 )
{
m_Src[0][1] = m_Src[0][0];
m_Src[0][0] = 0;
}
else if(m_Src[1][0] == 0)
{
m_Src[1][0] = m_Src[0][0];
m_Src[0][0] = 0;
}
else m_ST1.SetCheck(false);
UpdateSrcRadio();
}
void CInitDialog::OnSrcButton2()
{
if(m_Src[0][0] ==0 )
{
m_Src[0][0] = m_Src[0][1];
m_Src[0][1] = 0;
}
else if(m_Src[1][1] == 0)
{
m_Src[1][1] = m_Src[0][1];
m_Src[0][1] = 0;
}
else if(m_Src[0][2] == 0)
{
m_Src[0][2] = m_Src[0][1];
m_Src[0][1] = 0;
}
else m_ST2.SetCheck(false);
UpdateSrcRadio();
}
void CInitDialog::OnSrcButton3()
{
if(m_Src[0][1] ==0 )
{
m_Src[0][1] = m_Src[0][2];
m_Src[0][2] = 0;
}
else if(m_Src[1][2] == 0)
{
m_Src[1][2] = m_Src[0][2];
m_Src[0][2] = 0;
}
else m_ST3.SetCheck(false);
UpdateSrcRadio();
}
void CInitDialog::OnSrcButton4()
{
if(m_Src[1][1] == 0)
{
m_Src[1][1] = m_Src[1][0];
m_Src[1][0] = 0;
}
else if(m_Src[0][0] == 0)
{
m_Src[0][0] = m_Src[1][0];
m_Src[1][0] = 0;
}
else if(m_Src[2][0] == 0)
{
m_Src[2][0] = m_Src[1][0];
m_Src[1][0] = 0;
}
else m_ST4.SetCheck(false);
UpdateSrcRadio();
}
void CInitDialog::OnSrcButton5()
{
if(m_Src[1][2] ==0 )
{
m_Src[1][2] = m_Src[1][1];
m_Src[1][1] = 0;
}
else if(m_Src[1][0] == 0)
{
m_Src[1][0] = m_Src[1][1];
m_Src[1][1] = 0;
}
else if(m_Src[0][1] == 0)
{
m_Src[0][1] = m_Src[1][1];
m_Src[1][1] = 0;
}
else if(m_Src[2][1] == 0)
{
m_Src[2][1] = m_Src[1][1];
m_Src[1][1] = 0;
}
else m_ST5.SetCheck(false);
UpdateSrcRadio();
}
void CInitDialog::OnSrcButton6()
{
if(m_Src[2][2] ==0 )
{
m_Src[2][2] = m_Src[1][2];
m_Src[1][2] = 0;
}
else if(m_Src[0][2] == 0)
{
m_Src[0][2] = m_Src[1][2];
m_Src[1][2] = 0;
}
else if(m_Src[1][1] == 0)
{
m_Src[1][1] = m_Src[1][2];
m_Src[1][2] = 0;
}
else m_ST6.SetCheck(false);
UpdateSrcRadio();
}
void CInitDialog::OnSrcButton7()
{
if(m_Src[1][0] ==0 )
{
m_Src[1][0] = m_Src[2][0];
m_Src[2][0] = 0;
}
else if(m_Src[2][1] == 0)
{
m_Src[2][1] = m_Src[2][0];
m_Src[2][0] = 0;
}
else m_ST7.SetCheck(false);
UpdateSrcRadio();
}
void CInitDialog::OnSrcButton8()
{
if(m_Src[2][0] ==0 )
{
m_Src[2][0] = m_Src[2][1];
m_Src[2][1] = 0;
}
else if(m_Src[2][2] == 0)
{
m_Src[2][2] = m_Src[2][1];
m_Src[2][1] = 0;
}
else if(m_Src[1][1] == 0)
{
m_Src[1][1] = m_Src[2][1];
m_Src[2][1] = 0;
}
else m_ST8.SetCheck(false);
UpdateSrcRadio();
}
void CInitDialog::OnSrcButton9()
{
if(m_Src[2][1] ==0 )
{
m_Src[2][1] = m_Src[2][2];
m_Src[2][2] = 0;
}
else if(m_Src[1][2] == 0)
{
m_Src[1][2] = m_Src[2][2];
m_Src[2][2] = 0;
}
else m_ST9.SetCheck(false);
UpdateSrcRadio();
}
void CInitDialog::OnDescButton1()
{
if(m_Desc[0][1] ==0 )
{
m_Desc[0][1] = m_Desc[0][0];
m_Desc[0][0] = 0;
}
else if(m_Desc[1][0] == 0)
{
m_Desc[1][0] = m_Desc[0][0];
m_Desc[0][0] = 0;
}
else m_ED1.SetCheck(false);
UpdateDescRadio();
}
void CInitDialog::OnDescButton2()
{
if(m_Desc[0][0] ==0 )
{
m_Desc[0][0] = m_Desc[0][1];
m_Desc[0][1] = 0;
}
else if(m_Desc[1][1] == 0)
{
m_Desc[1][1] = m_Desc[0][1];
m_Desc[0][1] = 0;
}
else if(m_Desc[0][2] == 0)
{
m_Desc[0][2] = m_Desc[0][1];
m_Desc[0][1] = 0;
}
else m_ED2.SetCheck(false);
UpdateDescRadio();
}
void CInitDialog::OnDescButton3()
{
if(m_Desc[0][1] ==0 )
{
m_Desc[0][1] = m_Desc[0][2];
m_Desc[0][2] = 0;
}
else if(m_Desc[1][2] == 0)
{
m_Desc[1][2] = m_Desc[0][2];
m_Desc[0][2] = 0;
}
else m_ED3.SetCheck(false);
UpdateDescRadio();
}
void CInitDialog::OnDescButton4()
{
if(m_Desc[1][1] == 0)
{
m_Desc[1][1] = m_Desc[1][0];
m_Desc[1][0] = 0;
}
else if(m_Desc[0][0] == 0)
{
m_Desc[0][0] = m_Desc[1][0];
m_Desc[1][0] = 0;
}
else if(m_Desc[2][0] == 0)
{
m_Desc[2][0] = m_Desc[1][0];
m_Desc[1][0] = 0;
}
else m_ED4.SetCheck(false);
UpdateDescRadio();
}
void CInitDialog::OnDescButton5()
{
if(m_Desc[1][2] ==0 )
{
m_Desc[1][2] = m_Desc[1][1];
m_Desc[1][1] = 0;
}
else if(m_Desc[1][0] == 0)
{
m_Desc[1][0] = m_Desc[1][1];
m_Desc[1][1] = 0;
}
else if(m_Desc[0][1] == 0)
{
m_Desc[0][1] = m_Desc[1][1];
m_Desc[1][1] = 0;
}
else if(m_Desc[2][1] == 0)
{
m_Desc[2][1] = m_Desc[1][1];
m_Desc[1][1] = 0;
}
else m_ED5.SetCheck(false);
UpdateDescRadio();
}
void CInitDialog::OnDescButton6()
{
if(m_Desc[2][2] ==0 )
{
m_Desc[2][2] = m_Desc[1][2];
m_Desc[1][2] = 0;
}
else if(m_Desc[0][2] == 0)
{
m_Desc[0][2] = m_Desc[1][2];
m_Desc[1][2] = 0;
}
else if(m_Desc[1][1] == 0)
{
m_Desc[1][1] = m_Desc[1][2];
m_Desc[1][2] = 0;
}
else m_ED6.SetCheck(false);
UpdateDescRadio();
}
void CInitDialog::OnDescButton7()
{
if(m_Desc[1][0] ==0 )
{
m_Desc[1][0] = m_Desc[2][0];
m_Desc[2][0] = 0;
}
else if(m_Desc[2][1] == 0)
{
m_Desc[2][1] = m_Desc[2][0];
m_Desc[2][0] = 0;
}
else m_ED7.SetCheck(false);
UpdateDescRadio();
}
void CInitDialog::OnDescButton8()
{
if(m_Desc[2][0] ==0 )
{
m_Desc[2][0] = m_Desc[2][1];
m_Desc[2][1] = 0;
}
else if(m_Desc[2][2] == 0)
{
m_Desc[2][2] = m_Desc[2][1];
m_Desc[2][1] = 0;
}
else if(m_Desc[1][1] == 0)
{
m_Desc[1][1] = m_Desc[2][1];
m_Desc[2][1] = 0;
}
else m_ED8.SetCheck(false);
UpdateDescRadio();
}
void CInitDialog::OnDescButton9()
{
if(m_Desc[2][1] ==0 )
{
m_Desc[2][1] = m_Desc[2][2];
m_Desc[2][2] = 0;
}
else if(m_Desc[1][2] == 0)
{
m_Desc[1][2] = m_Desc[2][2];
m_Desc[2][2] = 0;
}
else m_ED9.SetCheck(false);
UpdateDescRadio();
}
void CInitDialog::UpdateSrcRadio()
{
CString Msg;
if(m_Src[0][0] == 0) {Msg = "";m_ST1.SetCheck(1);}
else Msg.Format("%d",m_Src[0][0]);
m_ST1.SetWindowText(Msg);
if(m_Src[0][1] == 0) {Msg = "";m_ST2.SetCheck(1);}
else Msg.Format("%d",m_Src[0][1]);
m_ST2.SetWindowText(Msg);
if(m_Src[0][2] == 0) {Msg = "";m_ST3.SetCheck(1);}
else Msg.Format("%d",m_Src[0][2]);
m_ST3.SetWindowText(Msg);
if(m_Src[1][0] == 0) {Msg = "";m_ST4.SetCheck(1);}
else Msg.Format("%d",m_Src[1][0]);
m_ST4.SetWindowText(Msg);
if(m_Src[1][1] == 0) {Msg = "";m_ST5.SetCheck(1);}
else Msg.Format("%d",m_Src[1][1]);
m_ST5.SetWindowText(Msg);
if(m_Src[1][2] == 0) {Msg = "";m_ST6.SetCheck(1);}
else Msg.Format("%d",m_Src[1][2]);
m_ST6.SetWindowText(Msg);
if(m_Src[2][0] == 0) {Msg = "";m_ST7.SetCheck(1);}
else Msg.Format("%d",m_Src[2][0]);
m_ST7.SetWindowText(Msg);
if(m_Src[2][1] == 0) {Msg = "";m_ST8.SetCheck(1);}
else Msg.Format("%d",m_Src[2][1]);
m_ST8.SetWindowText(Msg);
if(m_Src[2][2] == 0) {Msg = "";m_ST9.SetCheck(1);}
else Msg.Format("%d",m_Src[2][2]);
m_ST9.SetWindowText(Msg);
}
void CInitDialog::UpdateDescRadio()
{
CString Msg;
if(m_Desc[0][0] == 0) {Msg = "";m_ED1.SetCheck(1);}
else Msg.Format("%d",m_Desc[0][0]);
m_ED1.SetWindowText(Msg);
if(m_Desc[0][1] == 0) {Msg = "";m_ED2.SetCheck(1);}
else Msg.Format("%d",m_Desc[0][1]);
m_ED2.SetWindowText(Msg);
if(m_Desc[0][2] == 0) {Msg = "";m_ED3.SetCheck(1);}
else Msg.Format("%d",m_Desc[0][2]);
m_ED3.SetWindowText(Msg);
if(m_Desc[1][0] == 0) {Msg = "";m_ED4.SetCheck(1);}
else Msg.Format("%d",m_Desc[1][0]);
m_ED4.SetWindowText(Msg);
if(m_Desc[1][1] == 0) {Msg = "";m_ED5.SetCheck(1);}
else Msg.Format("%d",m_Desc[1][1]);
m_ED5.SetWindowText(Msg);
if(m_Desc[1][2] == 0) {Msg = "";m_ED6.SetCheck(1);}
else Msg.Format("%d",m_Desc[1][2]);
m_ED6.SetWindowText(Msg);
if(m_Desc[2][0] == 0) {Msg = "";m_ED7.SetCheck(1);}
else Msg.Format("%d",m_Desc[2][0]);
m_ED7.SetWindowText(Msg);
if(m_Desc[2][1] == 0) {Msg = "";m_ED8.SetCheck(1);}
else Msg.Format("%d",m_Desc[2][1]);
m_ED8.SetWindowText(Msg);
if(m_Desc[2][2] == 0) {Msg = "";m_ED9.SetCheck(1);}
else Msg.Format("%d",m_Desc[2][2]);
m_ED9.SetWindowText(Msg);
}
| [
"starzacharystar@gmail.com@a7bbafab-dc4b-51e6-8110-5f81b14c7997"
] | [
[
[
1,
505
]
]
] |
c13d0fdd0fc12ddd2667bf113ab6515fbe7fa5ce | 0f457762985248f4f6f06e29429955b3fd2c969a | /irrlicht/sdk/irr_bullet/BulletFpsCamAnimator.cpp | cb032f3e69ff87eca1975d828ecc7cfaf75b60b1 | [] | no_license | tk8812/ukgtut | f19e14449c7e75a0aca89d194caedb9a6769bb2e | 3146ac405794777e779c2bbb0b735b0acd9a3f1e | refs/heads/master | 2021-01-01 16:55:07 | 2010-11-15 16:02:53 | 2010-11-15 16:02:53 | 37,515,002 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 13,440 | cpp | //저작권:
//물리 fps 애니메이터
//수정 2008.8.12
//미구현 사항 : 점푸구현
//
//수정 2009.8.6
#pragma warning (disable:4819)
#include "CBulletAnimatorManager.h"
#include "BulletFpsCamAnimator.h"
#include "IVideoDriver.h"
#include "ISceneManager.h"
#include "Keycodes.h"
#include "ICursorControl.h"
#include "ICameraSceneNode.h"
#include "btBulletDynamicsCommon.h"
#include "BulletCollision/Gimpact/btGImpactShape.h"
#include "BulletCollision/Gimpact/btGImpactCollisionAlgorithm.h"
namespace irr
{
namespace scene
{
//! constructor
CBulletFpsCamAnimator::CBulletFpsCamAnimator(gui::ICursorControl* cursorControl,
f32 rotateSpeed, f32 moveSpeed, f32 jumpSpeed,
SKeyMap* keyMapArray, u32 keyMapSize, bool noVerticalMovement)
: CursorControl(cursorControl), MaxVerticalAngle(88.0f),
MoveSpeed(moveSpeed/1000.0f), RotateSpeed(rotateSpeed), JumpSpeed(jumpSpeed),
LastAnimationTime(0), firstUpdate(true), NoVerticalMovement(noVerticalMovement)
{
#ifdef _DEBUG
setDebugName("CCameraSceneNodeAnimatorFPS");
#endif
if (CursorControl)
CursorControl->grab();
allKeysUp();
// create key map
if (!keyMapArray || !keyMapSize)
{
// create default key map
KeyMap.push_back(SCamKeyMap(0, irr::KEY_UP));
KeyMap.push_back(SCamKeyMap(1, irr::KEY_DOWN));
KeyMap.push_back(SCamKeyMap(2, irr::KEY_LEFT));
KeyMap.push_back(SCamKeyMap(3, irr::KEY_RIGHT));
KeyMap.push_back(SCamKeyMap(4, irr::KEY_KEY_J));
}
else
{
// create custom key map
setKeyMap(keyMapArray, keyMapSize);
}
m_LocalPos = irr::core::vector3df(0,0,0);
}
//! destructor
CBulletFpsCamAnimator::~CBulletFpsCamAnimator()
{
if (CursorControl)
CursorControl->drop();
}
//! It is possible to send mouse and key events to the camera. Most cameras
//! may ignore this input, but camera scene nodes which are created for
//! example with scene::ISceneManager::addMayaCameraSceneNode or
//! scene::ISceneManager::addFPSCameraSceneNode, may want to get this input
//! for changing their position, look at target or whatever.
//! 아래의이벤트핸들러가 호출되는 이유는 현재활성화된 카메라노드에 자식으로 붙어있는 애니매이터는
//! 무조건 이밴트핸들러가 호출이된다.
bool CBulletFpsCamAnimator::OnEvent(const SEvent& evt)
{
switch(evt.EventType)
{
case EET_KEY_INPUT_EVENT:
for (u32 i=0; i<KeyMap.size(); ++i)
{
if (KeyMap[i].keycode == evt.KeyInput.Key)
{
CursorKeys[KeyMap[i].action] = evt.KeyInput.PressedDown;
return true;
}
}
break;
case EET_MOUSE_INPUT_EVENT:
if (evt.MouseInput.Event == EMIE_MOUSE_MOVED)
{
CursorPos = CursorControl->getRelativePosition();
return true;
}
break;
default:
break;
}
return false;
}
//------------------------------------------------------------------------------
//! CreateInstance
//! Creates CBulletChracterAnimator or returns NULL
//! CBulletObjectAnimator와 달리 각회전을 제한(서있는상태를 유지하기위해서는 쓰러짐을 제어하기위해서...)
CBulletFpsCamAnimator* CBulletFpsCamAnimator::createInstance(
ISceneManager* pSceneManager,
ISceneNode* pSceneNode,
gui::ICursorControl *CursorControl,
CBulletAnimatorManager* pBulletMgr,
CBulletObjectAnimatorGeometry* pGeom,
CBulletObjectAnimatorParams* pPhysicsParam)
{
//CursorControl = CursorControl;
// get node scaling
core::vector3df scaling = pSceneNode->getScale();
btStridingMeshInterface* triangleMesh = NULL;
// prepare collision shape
btCollisionShape* collisionShape =
CreateBulletCollisionShape(pSceneManager, pGeom, scaling, triangleMesh);
if (collisionShape == NULL)
return NULL;
CBulletFpsCamAnimator* bulletAnimator = new CBulletFpsCamAnimator(CursorControl,100.f,50.f);
bulletAnimator->geometry = *pGeom;
bulletAnimator->physicsParams = *pPhysicsParam;
bulletAnimator->bulletMesh = triangleMesh;
bulletAnimator->collisionShape = collisionShape;
bulletAnimator->sceneNode = pSceneNode;
bulletAnimator->sceneManager = pSceneManager;
bulletAnimator->bulletMgr = pBulletMgr;
bulletAnimator->CursorControl = CursorControl;
bulletAnimator->InitPhysics();
//추가 물리 속성
//쓰러짐 제어를 위해 각회전 제한
bulletAnimator->getRigidBody()->setAngularFactor(0.0f);
bulletAnimator->getRigidBody()->setSleepingThresholds (0.0, 0.0);
return bulletAnimator;
}
void CBulletFpsCamAnimator::animateNode(ISceneNode* node, u32 timeMs)
{
if (node->getType() != ESNT_CAMERA)
return;
ICameraSceneNode* camera = static_cast<ICameraSceneNode*>(node);
if (firstUpdate)
{
if (CursorControl && camera)
{
CursorControl->setPosition(0.5f, 0.5f);
CursorPos = CenterCursor = CursorControl->getRelativePosition();
}
LastAnimationTime = timeMs;
firstUpdate = false;
}
// get time
f32 timeDiff = (f32) ( timeMs - LastAnimationTime );
LastAnimationTime = timeMs;
// update position
core::vector3df pos = camera->getPosition();
// Update rotation
core::vector3df target = (camera->getTarget() - camera->getAbsolutePosition());
core::vector3df relativeRotation = target.getHorizontalAngle();
if (CursorControl)
{
if (CursorPos != CenterCursor)
{
relativeRotation.Y -= (0.5f - CursorPos.X) * RotateSpeed;
relativeRotation.X -= (0.5f - CursorPos.Y) * RotateSpeed;
// X < MaxVerticalAngle or X > 360-MaxVerticalAngle
if (relativeRotation.X > MaxVerticalAngle*2 &&
relativeRotation.X < 360.0f-MaxVerticalAngle)
{
relativeRotation.X = 360.0f-MaxVerticalAngle;
}
else
if (relativeRotation.X > MaxVerticalAngle &&
relativeRotation.X < 360.0f-MaxVerticalAngle)
{
relativeRotation.X = MaxVerticalAngle;
}
// reset cursor position
CursorControl->setPosition(0.5f, 0.5f);
CenterCursor = CursorControl->getRelativePosition();
//ggf::irr_util::DebugOutputFmt(NULL,"test %f \n",relativeRotation.Y);
}
}
// set target
target.set(0,0,100);
core::vector3df movedir = target;
core::matrix4 mat;
mat.setRotationDegrees(core::vector3df(relativeRotation.X, relativeRotation.Y, 0));
mat.transformVect(target);
if (NoVerticalMovement)
{
mat.setRotationDegrees(core::vector3df(0, relativeRotation.Y, 0));
mat.transformVect(movedir);
}
else
{
movedir = target;
}
movedir.normalize();
//if (CursorKeys[0])
//pos += movedir * timeDiff * MoveSpeed;
//if (CursorKeys[1])
//pos -= movedir * timeDiff * MoveSpeed;
// strafing
//core::vector3df strafevect = target;
//strafevect = strafevect.crossProduct(camera->getUpVector());
//if (NoVerticalMovement)
// strafevect.Y = 0.0f;
//strafevect.normalize();
if (CursorKeys[2])
{
//pos += strafevect * timeDiff * MoveSpeed;
//ggf::irr_util::DebugOutputFmt(NULL,"test %f \n",relativeRotation.Y);
}
if (CursorKeys[3])
//pos -= strafevect * timeDiff * MoveSpeed;
// jumping ( need's a gravity , else it's a fly to the World-UpVector )
if (CursorKeys[4])
{
//pos += camera->getUpVector() * timeDiff * JumpSpeed;
}
// write translation
//camera->setPosition(pos);
/////////////////////////gbox/////////////////////////
//gbox patch 08.07.27 rotation bug fix
camera->setRotation(mat.getRotationDegrees());
/////////////////////////gbox/////////////////////////
// write right target
TargetVector = target;
//target += pos;
//camera->setTarget(target);
irr::f32 Speed = 0;// = timeDiff * MoveSpeed;
irr::f32 Strife_Speed = 0;
irr::f32 Angle = relativeRotation.Y;
if (CursorKeys[0])
{
//Speed = timeDiff * MoveSpeed;
Speed = MoveSpeed;
}
if (CursorKeys[1])
{
//Speed = -(timeDiff * MoveSpeed);
Speed = -MoveSpeed;
}
if (CursorKeys[2])
{
Strife_Speed = MoveSpeed;
//Strife_Speed = (timeDiff * MoveSpeed);
}
if (CursorKeys[3])
{
Strife_Speed = -MoveSpeed;
//Strife_Speed = -(timeDiff * MoveSpeed);
}
//전처리 스탭(충돌 처리)
{
btTransform xform;
rigidBody->getMotionState()->getWorldTransform (xform);
btVector3 down = -xform.getBasis()[1]; //Y축 정보
btVector3 forward = xform.getBasis()[2]; //Z축 정보
down.normalize ();
forward.normalize();
forward.setX(-forward.getX()); //오른손좌표계롤 왼손좌표계로...
m_raySource[0] = xform.getOrigin();
m_raySource[1] = xform.getOrigin();
m_rayTarget[0] = m_raySource[0] + down * ((geometry.Capsule.hight * 0.5f) + geometry.Capsule.radius ) * btScalar(1.1);
m_rayTarget[1] = m_raySource[1] + forward * (geometry.Capsule.radius ) * btScalar(1.1);
class ClosestNotMe : public btCollisionWorld::ClosestRayResultCallback
{
public:
ClosestNotMe (btRigidBody* me) : btCollisionWorld::ClosestRayResultCallback(btVector3(0.0, 0.0, 0.0), btVector3(0.0, 0.0, 0.0))
{
m_me = me;
}
virtual btScalar AddSingleResult(btCollisionWorld::LocalRayResult& rayResult,bool normalInWorldSpace)
{
if (rayResult.m_collisionObject == m_me)
return 1.0;
return ClosestRayResultCallback::addSingleResult (rayResult, normalInWorldSpace
);
}
protected:
btRigidBody* m_me;
};
ClosestNotMe rayCallback(rigidBody);
{
btDynamicsWorld* dynamicsWorld = bulletMgr->getBulletWorldByID(bulletWorldID)->getWorld();
int i = 0;
for (i = 0; i < 2; i++)
{
rayCallback.m_closestHitFraction = 1.0;
dynamicsWorld->rayTest (m_raySource[i], m_rayTarget[i], rayCallback);
if (rayCallback.hasHit())
{
m_rayLambda[i] = rayCallback.m_closestHitFraction; //충돌비율값
} else {
m_rayLambda[i] = 1.0; //충돌하지않음
}
}
}
}
//후처리
{
btTransform xform;
rigidBody->getMotionState()->getWorldTransform (xform);
xform.setRotation (btQuaternion (btVector3(0.0, 1.0, 0.0), Angle * irr::core::DEGTORAD));
btVector3 linearVelocity = rigidBody->getLinearVelocity();
if(m_rayLambda[0] < 1.0)
{
linearVelocity.setY(0);
}
btVector3 forwardDir = xform.getBasis()[2];
btVector3 SideDir = xform.getBasis()[0];
//축변환 및 정규화
forwardDir.normalize ();
forwardDir.setX(-forwardDir.getX());
SideDir.normalize();
SideDir.setX(-SideDir.getX());
btVector3 velocity = (forwardDir * Speed);
velocity += (SideDir * Strife_Speed);
irr::core::vector3df fowardvec = irr::core::vector3df(forwardDir.getX(),forwardDir.getY(),forwardDir.getZ());
irr::core::vector3df sidevec = irr::core::vector3df(-SideDir.getX(),SideDir.getY(),SideDir.getZ());
//ggf::irr_util::DebugOutputFmt(NULL,"%f %f, %f, %f\n",Angle,velocity.getX(),velocity.getY(),velocity.getZ());
//ggf::irr_util::DebugOutputFmt(NULL,"%f/%f %f, %f, %f\n",fowardvec.getHorizontalAngle().Y, sidevec.getHorizontalAngle().Y,SideDir.getX(),SideDir.getY(),SideDir.getZ());
velocity.setY(linearVelocity.getY());
rigidBody->setLinearVelocity (velocity);
rigidBody->getMotionState()->setWorldTransform (xform);
rigidBody->setCenterOfMassTransform (xform);
//camera->setTarget(target);
}
//물리엔진 변환적용
if (physicsParams.mass != 0.0f && rigidBody && rigidBody->getMotionState())
{
btTransform xform;
rigidBody->getMotionState()->getWorldTransform (xform);
btVector3 forwardDir = xform.getBasis()[2];
forwardDir.normalize ();
// set pos
btVector3 p = rigidBody->getCenterOfMassPosition();
irr::core::vector3df vforward = irr::core::vector3df(-forwardDir.getX(),forwardDir.getY(),forwardDir.getZ());
irr::core::vector3df eye_pos = core::vector3df(p.getX(), p.getY(), p.getZ()) + m_LocalPos;
sceneNode->setPosition(eye_pos);
camera->setTarget(eye_pos + TargetVector);
}
}
void CBulletFpsCamAnimator::allKeysUp()
{
for (u32 i=0; i<6; ++i)
CursorKeys[i] = false;
}
//! Sets the rotation speed
void CBulletFpsCamAnimator::setRotateSpeed(f32 speed)
{
RotateSpeed = speed;
}
//! Sets the movement speed
void CBulletFpsCamAnimator::setMoveSpeed(f32 speed)
{
MoveSpeed = speed;
}
//! Gets the rotation speed
f32 CBulletFpsCamAnimator::getRotateSpeed() const
{
return RotateSpeed;
}
// Gets the movement speed
f32 CBulletFpsCamAnimator::getMoveSpeed() const
{
return MoveSpeed;
}
//! Sets the keyboard mapping for this animator
void CBulletFpsCamAnimator::setKeyMap(SKeyMap *map, u32 count)
{
// clear the keymap
KeyMap.clear();
// add actions
for (u32 i=0; i<count; ++i)
{
switch(map[i].Action)
{
case EKA_MOVE_FORWARD: KeyMap.push_back(SCamKeyMap(0, map[i].KeyCode));
break;
case EKA_MOVE_BACKWARD: KeyMap.push_back(SCamKeyMap(1, map[i].KeyCode));
break;
case EKA_STRAFE_LEFT: KeyMap.push_back(SCamKeyMap(2, map[i].KeyCode));
break;
case EKA_STRAFE_RIGHT: KeyMap.push_back(SCamKeyMap(3, map[i].KeyCode));
break;
case EKA_JUMP_UP: KeyMap.push_back(SCamKeyMap(4, map[i].KeyCode));
break;
default:
break;
}
}
}
//! Sets whether vertical movement should be allowed.
void CBulletFpsCamAnimator::setVerticalMovement(bool allow)
{
NoVerticalMovement = !allow;
}
} // namespace scene
} // namespace irr
| [
"gbox3d@58f0f68e-7603-11de-abb5-1d1887d8974b"
] | [
[
[
1,
505
]
]
] |
dd842364998f741a3b13fac4c1d240b0589da5f5 | 8f1601062c4a5452f2bdd0f75f3d12a79b98ba62 | /examples/aegis/me519/paint/wpaint.cpp | 84a74199fe49cc97f1869cd481eba245e92daba9 | [] | no_license | chadaustin/isugamedev | 200a54f55a2581cd2c62c94eb96b9e238abcf3dd | d3008ada042d2dd98c6e05711773badf6f1fd85c | refs/heads/master | 2016-08-11 17:59:38 | 2005-01-25 23:17:11 | 2005-01-25 23:17:11 | 36,483,500 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,692 | cpp | #include <algorithm>
#include <functional>
#include <list>
#include <stdlib.h>
#include <GL/glut.h>
using namespace std;
struct Point {
Point(int x_ = 0, int y_ = 0) {
x = x_;
y = y_;
}
int x;
int y;
};
struct Color {
float red, green, blue, alpha;
};
static const Color white = { 1, 1, 1 };
static const Color black = { 0, 0, 0 };
static const Color red = { 1, 0, 0 };
static const Color green = { 0, 1, 0 };
static const Color blue = { 0, 0, 1 };
static const Color cyan = { 0, 1, 1 };
static const Color magenta = { 1, 0, 1 };
static const Color yellow = { 1, 1, 0 };
inline void glColor(const Color& c) {
glColor4f(c.red, c.green, c.blue, c.alpha);
}
inline void glVertex(const Point& p) {
glVertex2i(p.x, p.y);
}
struct Command {
virtual ~Command() {}
void destroy() { delete this; }
virtual void draw() = 0;
};
struct PointCommand : Command {
PointCommand(Point p_, Color c_, int size_) {
p = p_;
c = c_;
size = size_;
}
void draw() {
glPointSize(size);
glBegin(GL_POINTS);
glColor(c);
glVertex(p);
glEnd();
}
private:
Point p;
Color c;
int size;
};
struct LineCommand : Command {
LineCommand(Point p1_, Point p2_, Color c_, int width_) {
p1 = p1_;
p2 = p2_;
c = c_;
width = width_;
}
void draw() {
glLineWidth(width);
glColor(c);
glBegin(GL_LINES);
glVertex(p1);
glVertex(p2);
glEnd();
}
private:
Point p1;
Point p2;
Color c;
int width;
};
struct RectangleCommand : Command {
RectangleCommand(Point p1_, Point p2_, Color c_, int width_) {
p1 = p1_;
p2 = p2_;
c = c_;
width = width_;
}
void draw() {
glLineWidth(width);
glColor(c);
glBegin(GL_LINE_STRIP);
glVertex(p1);
glVertex2i(p2.x, p1.y);
glVertex(p2);
glVertex2i(p1.x, p2.y);
glVertex(p1);
glEnd();
}
private:
Point p1;
Point p2;
Color c;
int width;
};
struct FilledRectangleCommand : Command {
FilledRectangleCommand(Point p1_, Point p2_, Color c_) {
p1 = p1_;
p2 = p2_;
c = c_;
}
void draw() {
glColor(c);
glBegin(GL_QUADS);
glVertex(p1);
glVertex2i(p2.x, p1.y);
glVertex(p2);
glVertex2i(p1.x, p2.y);
glEnd();
}
private:
Point p1;
Point p2;
Color c;
};
struct CommandList {
void add(Command* c) {
for_each(redos.begin(), redos.end(), mem_fun(&Command::destroy));
redos.clear();
commands.push_back(c);
glutPostRedisplay();
}
void undo() {
if (commands.size()) {
redos.push_back(commands.back());
commands.pop_back();
glutPostRedisplay();
}
}
void redo() {
if (redos.size()) {
commands.push_back(redos.back());
redos.pop_back();
glutPostRedisplay();
}
}
void clear() {
for_each(commands.begin(), commands.end(), mem_fun(&Command::destroy));
commands.clear();
for_each(redos.begin(), redos.end(), mem_fun(&Command::destroy));
redos.clear();
glutPostRedisplay();
}
void draw() {
for_each(commands.begin(), commands.end(), mem_fun(&Command::draw));
}
private:
list<Command*> commands;
list<Command*> redos;
};
// since all tools use the same color...
Color g_color = white;
float g_alpha = 1;
int g_line_width = 1;
int g_point_size = 1;
CommandList g_commands;
Color CreateColor() {
Color c = g_color;
c.alpha = g_alpha;
return c;
}
struct Tool {
virtual void onMouseDown(Point p) { }
virtual void onMouseMove(Point p) { }
static void pushCommand(Command* c) {
g_commands.add(c);
}
static void popCommand() {
g_commands.undo();
}
};
struct PointToolClass : Tool {
void onMouseDown(Point p) {
pushCommand(new PointCommand(p, CreateColor(), g_point_size));
}
} PointTool;
struct ScribbleToolClass : Tool {
void onMouseDown(Point p) {
m_last_point = p;
}
void onMouseMove(Point p) {
pushCommand(new LineCommand(m_last_point, p, CreateColor(), g_line_width));
m_last_point = p;
}
private:
Point m_last_point;
} ScribbleTool;
struct LineToolClass : Tool {
void onMouseDown(Point p) {
m_start = p;
pushCommand(getCommand(p));
}
void onMouseMove(Point p) {
popCommand();
pushCommand(getCommand(p));
}
private:
Command* getCommand(Point p) {
return new LineCommand(m_start, p, CreateColor(), g_line_width);
}
Point m_start;
} LineTool;
struct RectangleToolClass : Tool {
RectangleToolClass() {
m_filled = false;
}
void onMouseDown(Point p) {
m_start = p;
pushCommand(getCommand(p));
}
void onMouseMove(Point p) {
popCommand();
pushCommand(getCommand(p));
}
void setFill(bool filled) {
m_filled = filled;
}
private:
Command* getCommand(Point p) {
if (m_filled) {
return new FilledRectangleCommand(m_start, p, CreateColor());
} else {
return new RectangleCommand(m_start, p, CreateColor(), g_line_width);
}
}
private:
Point m_start;
bool m_filled;
} RectangleTool;
int g_width;
int g_height;
Tool* g_tool = &PointTool;
void display() {
glViewport(0, 0, g_width, g_height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, g_width, g_height, 0, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT);
g_commands.draw();
glutSwapBuffers();
}
void reshape(int x, int y) {
g_width = x;
g_height = y;
glutPostRedisplay();
}
void mouse(int button, int state, int x, int y) {
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {
g_tool->onMouseDown(Point(x, y));
}
}
void motion(int x, int y) {
g_tool->onMouseMove(Point(x, y));
}
// menu commands
enum {
TOOL_POINT,
TOOL_SCRIBBLE,
TOOL_LINE,
TOOL_RECTANGLE,
COLOR_WHITE,
COLOR_BLACK,
COLOR_RED,
COLOR_GREEN,
COLOR_BLUE,
COLOR_CYAN,
COLOR_MAGENTA,
COLOR_YELLOW,
TRANSPARENCY_0,
TRANSPARENCY_10,
TRANSPARENCY_20,
TRANSPARENCY_30,
TRANSPARENCY_40,
TRANSPARENCY_50,
TRANSPARENCY_60,
TRANSPARENCY_70,
TRANSPARENCY_80,
TRANSPARENCY_90,
TRANSPARENCY_100,
POINT_SIZE_1,
POINT_SIZE_2,
POINT_SIZE_4,
POINT_SIZE_8,
LINE_WIDTH_1,
LINE_WIDTH_2,
LINE_WIDTH_4,
LINE_WIDTH_8,
FILL_ON,
FILL_OFF,
COMMAND_REDO,
COMMAND_UNDO,
COMMAND_CLEAR,
COMMAND_QUIT,
};
void main_menu(int value) {
switch (value) {
case COMMAND_UNDO: g_commands.undo(); break;
case COMMAND_REDO: g_commands.redo(); break;
case COMMAND_CLEAR: g_commands.clear(); break;
case COMMAND_QUIT: exit(EXIT_SUCCESS);
}
}
void tool_menu(int value) {
switch (value) {
case TOOL_POINT: g_tool = &PointTool; break;
case TOOL_SCRIBBLE: g_tool = &ScribbleTool; break;
case TOOL_LINE: g_tool = &LineTool; break;
case TOOL_RECTANGLE: g_tool = &RectangleTool; break;
}
}
void color_menu(int value) {
switch (value) {
case COLOR_WHITE: g_color = white; break;
case COLOR_BLACK: g_color = black; break;
case COLOR_RED: g_color = red; break;
case COLOR_GREEN: g_color = green; break;
case COLOR_BLUE: g_color = blue; break;
case COLOR_CYAN: g_color = cyan; break;
case COLOR_MAGENTA: g_color = magenta; break;
case COLOR_YELLOW: g_color = yellow; break;
}
}
void transparency_menu(int value) {
switch (value) {
case TRANSPARENCY_0: g_alpha = 0.0f; break;
case TRANSPARENCY_10: g_alpha = 0.1f; break;
case TRANSPARENCY_20: g_alpha = 0.2f; break;
case TRANSPARENCY_30: g_alpha = 0.3f; break;
case TRANSPARENCY_40: g_alpha = 0.4f; break;
case TRANSPARENCY_50: g_alpha = 0.5f; break;
case TRANSPARENCY_60: g_alpha = 0.6f; break;
case TRANSPARENCY_70: g_alpha = 0.7f; break;
case TRANSPARENCY_80: g_alpha = 0.8f; break;
case TRANSPARENCY_90: g_alpha = 0.9f; break;
case TRANSPARENCY_100: g_alpha = 1.0f; break;
}
}
void point_size_menu(int value) {
switch (value) {
case POINT_SIZE_1: g_point_size = 1; break;
case POINT_SIZE_2: g_point_size = 2; break;
case POINT_SIZE_4: g_point_size = 4; break;
case POINT_SIZE_8: g_point_size = 8; break;
}
}
void line_width_menu(int value) {
switch (value) {
case LINE_WIDTH_1: g_line_width = 1; break;
case LINE_WIDTH_2: g_line_width = 2; break;
case LINE_WIDTH_4: g_line_width = 4; break;
case LINE_WIDTH_8: g_line_width = 8; break;
}
}
void fill_menu(int value) {
RectangleTool.setFill(value == FILL_ON);
}
void create_menu() {
int tool = glutCreateMenu(tool_menu);
glutAddMenuEntry("Point", TOOL_POINT);
glutAddMenuEntry("Scribble", TOOL_SCRIBBLE);
glutAddMenuEntry("Line", TOOL_LINE);
glutAddMenuEntry("Rectangle", TOOL_RECTANGLE);
int color = glutCreateMenu(color_menu);
glutAddMenuEntry("White", COLOR_WHITE);
glutAddMenuEntry("Black", COLOR_BLACK);
glutAddMenuEntry("Red", COLOR_RED);
glutAddMenuEntry("Green", COLOR_GREEN);
glutAddMenuEntry("Blue", COLOR_BLUE);
glutAddMenuEntry("Cyan", COLOR_CYAN);
glutAddMenuEntry("Magenta", COLOR_MAGENTA);
glutAddMenuEntry("Yellow", COLOR_YELLOW);
int transparency = glutCreateMenu(transparency_menu);
glutAddMenuEntry("0%", TRANSPARENCY_0);
glutAddMenuEntry("10%", TRANSPARENCY_10);
glutAddMenuEntry("20%", TRANSPARENCY_20);
glutAddMenuEntry("30%", TRANSPARENCY_30);
glutAddMenuEntry("40%", TRANSPARENCY_40);
glutAddMenuEntry("50%", TRANSPARENCY_50);
glutAddMenuEntry("60%", TRANSPARENCY_60);
glutAddMenuEntry("70%", TRANSPARENCY_70);
glutAddMenuEntry("80%", TRANSPARENCY_80);
glutAddMenuEntry("90%", TRANSPARENCY_90);
glutAddMenuEntry("100%", TRANSPARENCY_100);
int point_size = glutCreateMenu(point_size_menu);
glutAddMenuEntry("1", POINT_SIZE_1);
glutAddMenuEntry("2", POINT_SIZE_2);
glutAddMenuEntry("4", POINT_SIZE_4);
glutAddMenuEntry("8", POINT_SIZE_8);
int line_width = glutCreateMenu(line_width_menu);
glutAddMenuEntry("1", LINE_WIDTH_1);
glutAddMenuEntry("2", LINE_WIDTH_2);
glutAddMenuEntry("4", LINE_WIDTH_4);
glutAddMenuEntry("8", LINE_WIDTH_8);
int fill = glutCreateMenu(fill_menu);
glutAddMenuEntry("On", FILL_ON);
glutAddMenuEntry("Off", FILL_OFF);
glutCreateMenu(main_menu);
glutAddMenuEntry("Undo", COMMAND_UNDO);
glutAddMenuEntry("Redo", COMMAND_REDO);
glutAddSubMenu("Tool", tool);
glutAddSubMenu("Color", color);
glutAddSubMenu("Transparency", transparency);
glutAddSubMenu("Point Size", point_size);
glutAddSubMenu("Line Width", line_width);
glutAddSubMenu("Fill", fill);
glutAddMenuEntry("Clear", COMMAND_CLEAR);
glutAddMenuEntry("Quit", COMMAND_QUIT);
glutAttachMenu(GLUT_RIGHT_BUTTON);
}
void initialize() {
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_POINT_SMOOTH);
}
int main(int argc, char** argv) {
// initialize GLUT
glutInit(&argc, argv);
glutInitWindowSize(640, 480);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
// create primary window
glutCreateWindow("Paint");
// callbacks
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMouseFunc(mouse);
glutMotionFunc(motion);
create_menu();
initialize();
glutMainLoop();
}
| [
"aegis@84b32ba4-53c3-423c-be69-77cca6335494"
] | [
[
[
1,
526
]
]
] |
41f6ecd3bfaef72f42112035587219a8b689dd62 | 7b379862f58f587d9327db829ae4c6493b745bb1 | /JuceLibraryCode/modules/juce_graphics/fonts/juce_TextLayout.cpp | be3a8ac66be9d6a05e9f52ad505853fbc05b11d6 | [] | no_license | owenvallis/Nomestate | 75e844e8ab68933d481640c12019f0d734c62065 | 7fe7c06c2893421a3c77b5180e5f27ab61dd0ffd | refs/heads/master | 2021-01-19 07:35:14 | 2011-12-28 07:42:50 | 2011-12-28 07:42:50 | 2,950,072 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,576 | cpp | /*
==============================================================================
This file is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright 2004-11 by Raw Material Software Ltd.
------------------------------------------------------------------------------
JUCE can be redistributed and/or modified under the terms of the GNU General
Public License (Version 2), as published by the Free Software Foundation.
A copy of the license is included in the JUCE distribution, or can be found
online at www.gnu.org/licenses.
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.rawmaterialsoftware.com/juce for more information.
==============================================================================
*/
BEGIN_JUCE_NAMESPACE
TextLayout::Glyph::Glyph (const int glyphCode_, const Point<float>& anchor_, float width_) noexcept
: glyphCode (glyphCode_), anchor (anchor_), width (width_)
{
}
TextLayout::Glyph::Glyph (const Glyph& other) noexcept
: glyphCode (other.glyphCode), anchor (other.anchor), width (other.width)
{
}
TextLayout::Glyph& TextLayout::Glyph::operator= (const Glyph& other) noexcept
{
glyphCode = other.glyphCode;
anchor = other.anchor;
width = other.width;
return *this;
}
TextLayout::Glyph::~Glyph() noexcept {}
//==============================================================================
TextLayout::Run::Run() noexcept
: colour (0xff000000)
{
}
TextLayout::Run::Run (const Range<int>& range, const int numGlyphsToPreallocate)
: colour (0xff000000), stringRange (range)
{
glyphs.ensureStorageAllocated (numGlyphsToPreallocate);
}
TextLayout::Run::Run (const Run& other)
: font (other.font),
colour (other.colour),
glyphs (other.glyphs),
stringRange (other.stringRange)
{
}
TextLayout::Run::~Run() noexcept {}
//==============================================================================
TextLayout::Line::Line() noexcept
: ascent (0.0f), descent (0.0f), leading (0.0f)
{
}
TextLayout::Line::Line (const Range<int>& stringRange_, const Point<float>& lineOrigin_,
const float ascent_, const float descent_, const float leading_,
const int numRunsToPreallocate)
: stringRange (stringRange_), lineOrigin (lineOrigin_),
ascent (ascent_), descent (descent_), leading (leading_)
{
runs.ensureStorageAllocated (numRunsToPreallocate);
}
TextLayout::Line::Line (const Line& other)
: stringRange (other.stringRange), lineOrigin (other.lineOrigin),
ascent (other.ascent), descent (other.descent), leading (other.leading)
{
runs.addCopiesOf (other.runs);
}
TextLayout::Line::~Line() noexcept
{
}
Range<float> TextLayout::Line::getLineBoundsX() const noexcept
{
Range<float> range;
bool isFirst = true;
for (int i = runs.size(); --i >= 0;)
{
const Run* run = runs.getUnchecked(i);
jassert (run != nullptr);
if (run->glyphs.size() > 0)
{
float minX = run->glyphs.getReference(0).anchor.x;
float maxX = minX;
for (int j = run->glyphs.size(); --j > 0;)
{
const Glyph& glyph = run->glyphs.getReference (j);
const float x = glyph.anchor.x;
minX = jmin (minX, x);
maxX = jmax (maxX, x + glyph.width);
}
if (isFirst)
{
isFirst = false;
range = Range<float> (minX, maxX);
}
else
{
range = range.getUnionWith (Range<float> (minX, maxX));
}
}
}
return range + lineOrigin.x;
}
//==============================================================================
TextLayout::TextLayout()
: width (0), justification (Justification::topLeft)
{
}
TextLayout::TextLayout (const TextLayout& other)
: width (other.width),
justification (other.justification)
{
lines.addCopiesOf (other.lines);
}
#if JUCE_COMPILER_SUPPORTS_MOVE_SEMANTICS
TextLayout::TextLayout (TextLayout&& other) noexcept
: lines (static_cast <OwnedArray<Line>&&> (other.lines)),
width (other.width),
justification (other.justification)
{
}
TextLayout& TextLayout::operator= (TextLayout&& other) noexcept
{
lines = static_cast <OwnedArray<Line>&&> (other.lines);
width = other.width;
justification = other.justification;
return *this;
}
#endif
TextLayout& TextLayout::operator= (const TextLayout& other)
{
width = other.width;
justification = other.justification;
lines.clear();
lines.addCopiesOf (other.lines);
return *this;
}
TextLayout::~TextLayout()
{
}
float TextLayout::getHeight() const noexcept
{
const Line* const lastLine = lines.getLast();
return lastLine != nullptr ? lastLine->lineOrigin.y + lastLine->descent
: 0;
}
TextLayout::Line& TextLayout::getLine (const int index) const
{
return *lines[index];
}
void TextLayout::ensureStorageAllocated (int numLinesNeeded)
{
lines.ensureStorageAllocated (numLinesNeeded);
}
void TextLayout::addLine (Line* line)
{
lines.add (line);
}
void TextLayout::draw (Graphics& g, const Rectangle<float>& area) const
{
const Point<float> origin (justification.appliedToRectangle (Rectangle<float> (0, 0, width, getHeight()), area).getPosition());
LowLevelGraphicsContext& context = *g.getInternalContext();
for (int i = 0; i < getNumLines(); ++i)
{
const Line& line = getLine (i);
const Point<float> lineOrigin (origin + line.lineOrigin);
for (int j = 0; j < line.runs.size(); ++j)
{
const Run* const run = line.runs.getUnchecked (j);
jassert (run != nullptr);
context.setFont (run->font);
context.setFill (run->colour);
for (int k = 0; k < run->glyphs.size(); ++k)
{
const Glyph& glyph = run->glyphs.getReference (k);
context.drawGlyph (glyph.glyphCode, AffineTransform::translation (lineOrigin.x + glyph.anchor.x,
lineOrigin.y + glyph.anchor.y));
}
}
}
}
void TextLayout::createLayout (const AttributedString& text, float maxWidth)
{
lines.clear();
width = maxWidth;
justification = text.getJustification();
if (! createNativeLayout (text))
createStandardLayout (text);
recalculateWidth();
}
//==============================================================================
namespace TextLayoutHelpers
{
struct FontAndColour
{
FontAndColour (const Font* font_) noexcept : font (font_), colour (0xff000000) {}
const Font* font;
Colour colour;
bool operator!= (const FontAndColour& other) const noexcept
{
return (font != other.font && *font != *other.font) || colour != other.colour;
}
};
struct RunAttribute
{
RunAttribute (const FontAndColour& fontAndColour_, const Range<int>& range_) noexcept
: fontAndColour (fontAndColour_), range (range_)
{}
FontAndColour fontAndColour;
Range<int> range;
};
struct Token
{
Token (const String& t, const Font& f, const Colour& c, const bool isWhitespace_)
: text (t), font (f), colour (c),
area (font.getStringWidth (t), roundToInt (f.getHeight())),
isWhitespace (isWhitespace_),
isNewLine (t.containsChar ('\n') || t.containsChar ('\r'))
{}
const String text;
const Font font;
const Colour colour;
Rectangle<int> area;
int line, lineHeight;
const bool isWhitespace, isNewLine;
private:
Token& operator= (const Token&);
};
class TokenList
{
public:
TokenList() noexcept : totalLines (0) {}
void createLayout (const AttributedString& text, TextLayout& layout)
{
tokens.ensureStorageAllocated (64);
layout.ensureStorageAllocated (totalLines);
addTextRuns (text);
layoutRuns ((int) layout.getWidth());
int charPosition = 0;
int lineStartPosition = 0;
int runStartPosition = 0;
TextLayout::Line* glyphLine = new TextLayout::Line();
TextLayout::Run* glyphRun = new TextLayout::Run();
for (int i = 0; i < tokens.size(); ++i)
{
const Token* const t = tokens.getUnchecked (i);
const Point<float> tokenPos (t->area.getPosition().toFloat());
Array <int> newGlyphs;
Array <float> xOffsets;
t->font.getGlyphPositions (t->text.trimEnd(), newGlyphs, xOffsets);
glyphRun->glyphs.ensureStorageAllocated (glyphRun->glyphs.size() + newGlyphs.size());
for (int j = 0; j < newGlyphs.size(); ++j)
{
if (charPosition == lineStartPosition)
glyphLine->lineOrigin = tokenPos.translated (0, t->font.getAscent());
const float x = xOffsets.getUnchecked (j);
glyphRun->glyphs.add (TextLayout::Glyph (newGlyphs.getUnchecked(j),
Point<float> (tokenPos.getX() + x, 0),
xOffsets.getUnchecked (j + 1) - x));
++charPosition;
}
if (t->isWhitespace || t->isNewLine)
++charPosition;
const Token* const nextToken = tokens [i + 1];
if (nextToken == nullptr) // this is the last token
{
addRun (glyphLine, glyphRun, t, runStartPosition, charPosition);
glyphLine->stringRange = Range<int> (lineStartPosition, charPosition);
layout.addLine (glyphLine);
}
else
{
if (t->font != nextToken->font || t->colour != nextToken->colour)
{
addRun (glyphLine, glyphRun, t, runStartPosition, charPosition);
runStartPosition = charPosition;
glyphRun = new TextLayout::Run();
}
if (t->line != nextToken->line)
{
addRun (glyphLine, glyphRun, t, runStartPosition, charPosition);
glyphLine->stringRange = Range<int> (lineStartPosition, charPosition);
layout.addLine (glyphLine);
runStartPosition = charPosition;
lineStartPosition = charPosition;
glyphLine = new TextLayout::Line();
glyphRun = new TextLayout::Run();
}
}
}
if ((text.getJustification().getFlags() & (Justification::right | Justification::horizontallyCentred)) != 0)
{
const int totalW = (int) layout.getWidth();
for (int i = 0; i < layout.getNumLines(); ++i)
{
const int lineW = getLineWidth (i);
float dx = 0;
if ((text.getJustification().getFlags() & Justification::right) != 0)
dx = (float) (totalW - lineW);
else
dx = (totalW - lineW) / 2.0f;
TextLayout::Line& glyphLine = layout.getLine (i);
glyphLine.lineOrigin.x += dx;
}
}
}
private:
static void addRun (TextLayout::Line* glyphLine, TextLayout::Run* glyphRun,
const Token* const t, const int start, const int end)
{
glyphRun->stringRange = Range<int> (start, end);
glyphRun->font = t->font;
glyphRun->colour = t->colour;
glyphLine->ascent = jmax (glyphLine->ascent, t->font.getAscent());
glyphLine->descent = jmax (glyphLine->descent, t->font.getDescent());
glyphLine->runs.add (glyphRun);
}
void appendText (const AttributedString& text, const Range<int>& stringRange,
const Font& font, const Colour& colour)
{
String stringText (text.getText().substring (stringRange.getStart(), stringRange.getEnd()));
String::CharPointerType t (stringText.getCharPointer());
String currentString;
int lastCharType = 0;
for (;;)
{
const juce_wchar c = t.getAndAdvance();
if (c == 0)
break;
int charType;
if (c == '\r' || c == '\n')
charType = 0;
else if (CharacterFunctions::isWhitespace (c))
charType = 2;
else
charType = 1;
if (charType == 0 || charType != lastCharType)
{
if (currentString.isNotEmpty())
tokens.add (new Token (currentString, font, colour,
lastCharType == 2 || lastCharType == 0));
currentString = String::charToString (c);
if (c == '\r' && *t == '\n')
currentString += t.getAndAdvance();
}
else
{
currentString += c;
}
lastCharType = charType;
}
if (currentString.isNotEmpty())
tokens.add (new Token (currentString, font, colour, lastCharType == 2));
}
void layoutRuns (const int maxWidth)
{
int x = 0, y = 0, h = 0;
int i;
for (i = 0; i < tokens.size(); ++i)
{
Token* const t = tokens.getUnchecked(i);
t->area.setPosition (x, y);
t->line = totalLines;
x += t->area.getWidth();
h = jmax (h, t->area.getHeight());
const Token* nextTok = tokens[i + 1];
if (nextTok == 0)
break;
if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->area.getWidth() > maxWidth))
{
setLastLineHeight (i + 1, h);
x = 0;
y += h;
h = 0;
++totalLines;
}
}
setLastLineHeight (jmin (i + 1, tokens.size()), h);
++totalLines;
}
void setLastLineHeight (int i, const int height) noexcept
{
while (--i >= 0)
{
Token* const tok = tokens.getUnchecked (i);
if (tok->line == totalLines)
tok->lineHeight = height;
else
break;
}
}
int getLineWidth (const int lineNumber) const noexcept
{
int maxW = 0;
for (int i = tokens.size(); --i >= 0;)
{
const Token* const t = tokens.getUnchecked (i);
if (t->line == lineNumber && ! t->isWhitespace)
maxW = jmax (maxW, t->area.getRight());
}
return maxW;
}
void addTextRuns (const AttributedString& text)
{
Font defaultFont;
Array<RunAttribute> runAttributes;
{
const int stringLength = text.getText().length();
int rangeStart = 0;
FontAndColour lastFontAndColour (nullptr);
// Iterate through every character in the string
for (int i = 0; i < stringLength; ++i)
{
FontAndColour newFontAndColour (&defaultFont);
const int numCharacterAttributes = text.getNumAttributes();
for (int j = 0; j < numCharacterAttributes; ++j)
{
const AttributedString::Attribute* const attr = text.getAttribute (j);
// Check if the current character falls within the range of a font attribute
if (attr->getFont() != nullptr && (i >= attr->range.getStart()) && (i < attr->range.getEnd()))
newFontAndColour.font = attr->getFont();
// Check if the current character falls within the range of a foreground colour attribute
if (attr->getColour() != nullptr && (i >= attr->range.getStart()) && (i < attr->range.getEnd()))
newFontAndColour.colour = *attr->getColour();
}
if (i > 0 && (newFontAndColour != lastFontAndColour || i == stringLength - 1))
{
runAttributes.add (RunAttribute (lastFontAndColour,
Range<int> (rangeStart, (i < stringLength - 1) ? i : (i + 1))));
rangeStart = i;
}
lastFontAndColour = newFontAndColour;
}
}
for (int i = 0; i < runAttributes.size(); ++i)
{
const RunAttribute& r = runAttributes.getReference(i);
appendText (text, r.range, *(r.fontAndColour.font), r.fontAndColour.colour);
}
}
OwnedArray<Token> tokens;
int totalLines;
JUCE_DECLARE_NON_COPYABLE (TokenList);
};
}
//==============================================================================
void TextLayout::createLayoutWithBalancedLineLengths (const AttributedString& text, float maxWidth)
{
const float minimumWidth = maxWidth / 2.0f;
float bestWidth = maxWidth;
float bestLineProportion = 0.0f;
while (maxWidth > minimumWidth)
{
createLayout (text, maxWidth);
if (getNumLines() < 2)
return;
const float line1 = lines.getUnchecked (lines.size() - 1)->getLineBoundsX().getLength();
const float line2 = lines.getUnchecked (lines.size() - 2)->getLineBoundsX().getLength();
const float prop = jmax (line1, line2) / jmin (line1, line2);
if (prop > 0.9f)
return;
if (prop > bestLineProportion)
{
bestLineProportion = prop;
bestWidth = maxWidth;
}
maxWidth -= 10.0f;
}
if (bestWidth != maxWidth)
createLayout (text, bestWidth);
}
//==============================================================================
void TextLayout::createStandardLayout (const AttributedString& text)
{
TextLayoutHelpers::TokenList l;
l.createLayout (text, *this);
}
void TextLayout::recalculateWidth()
{
if (lines.size() > 0)
{
Range<float> range (lines.getFirst()->getLineBoundsX());
int i;
for (i = lines.size(); --i > 0;)
range = range.getUnionWith (lines.getUnchecked(i)->getLineBoundsX());
for (i = lines.size(); --i >= 0;)
lines.getUnchecked(i)->lineOrigin.x -= range.getStart();
width = range.getLength();
}
}
END_JUCE_NAMESPACE
| [
"ow3nskip"
] | [
[
[
1,
613
]
]
] |
b987180329d41ee02414b6c18e708504f59cb719 | 2c1e5a69ca68fe185cc04c5904aa104b0ba42e32 | /src/game/ASpriteInstance.cpp | d240eec7d3ac2e166123b0f83621607827ce3db0 | [] | no_license | dogtwelve/newsiderpg | e3f8284a7cd9938156ef8d683dca7bcbd928c593 | 303566a034dca3e66cf0f29cf9eaea1d54d63e4a | refs/heads/master | 2021-01-10 13:03:31 | 2010-06-27 05:36:33 | 2010-06-27 05:36:33 | 46,550,247 | 0 | 1 | null | null | null | null | UHC | C++ | false | false | 19,519 | cpp | #include "ASpriteInstance.h"
#include "ASprite.h"
/*int ASpriteInstance::x;
int ASpriteInstance::y;
int ASpriteInstance::_posX;
int ASpriteInstance::_posY;*/
#include "Macro.h"
ASpriteInstance::ASpriteInstance(ASprite* spr, int posX, int posY, ASpriteInstance* parent)
{
CameraX=0;
CameraY=0;
m_lastX = m_posX = posX;
m_lastY = m_posY = posY;
// m_flags = 0;
m_pal = 0;
m_sprite = spr;
m_nState = 0;
m_nCrtModule = 0;
m_nCrtFrame = 0;
m_nCrtAnimation = 0;
m_rect = GL_NEW int[4];
m_bLoop = true;
// m_parent = parent;
}
ASpriteInstance::~ASpriteInstance()
{
SAFE_DEL_ARRAY(m_rect);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void ASpriteInstance::SetModule(int id)
{//SangHo - 그리기 속성을 Module로 바꿔준다
//행동이 바뀌면 기존의 마지막 좌표는 초기화 시켜준다
m_lastAniX=0;
m_lastAniZ=0;
m_nState = 2;
m_nCrtAnimation = -2;//SangHo - -2 일 경우 Animation 작동하지않는다
m_nCrtModule = id;
//m_nCrtFrame = -1;//SangHo - -1 일 경우 Frame 작동하지않는다
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void ASpriteInstance::SetFrame(int id)
{//SangHo - 그리기 속성을 Frame로 바꿔준다
//행동이 바뀌면 기존의 마지막 좌표는 초기화 시켜준다
m_lastAniX=0;
m_lastAniZ=0;
m_nState = 1;
m_nCrtAnimation = -2;//SangHo - -2 일 경우 Animation 작동하지않는다
m_nCrtModule = -1;//SangHo - -1 일 경우 Module 작동하지않는다
m_nCrtFrame = id;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
bool ASpriteInstance::SetAnim(int id)
{//SangHo - 그리기 속성을 Animation로 바꿔준다
//if(!m_bLoop)
//{
//m_bAnimIsOver = false;
//행동이 바뀌면 기존의 마지막 좌표는 초기화 시켜준다
m_lastAniX=0;
m_lastAniZ=0;
m_nState = 0;
m_nCrtModule = id;
m_nCrtFrame = 0;
m_nCrtAnimation = -1;//SangHo - 0대신 -1인 이유는 Paint 전에 항상 키값에 대한 업데이트를 수행해야 하므로 첫프레임을 못찍는 구조적 한계때문
is_aniDone = false;
return true;
//}
//else
//{
// if (id != m_nCrtModule)
// {
// //m_bAnimIsOver = false;
// m_nCrtModule = id;
// m_nCrtFrame = 0;
// m_nCrtAnimation = 0;
// is_aniDone = false;
// return true;
// }
//}
//return false;
}
//void ASpriteInstance::SetAniLoop(bool _loop)
void ASpriteInstance::RewindAnim(int id)
{//SangHo - id Anim 으로 교체후 초기화
//m_bAnimIsOver = false;
m_nCrtModule = id;
m_nCrtFrame = 0;
m_nCrtAnimation = 0;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void ASpriteInstance::SetToLastFrame()
{//SangHo - Anim의 마지막 인덱스값으로 이동
m_nCrtFrame = m_sprite->GetAFrames(m_nCrtModule) - 1;
m_nCrtAnimation = m_sprite->GetAFrameTime(m_nCrtModule, m_nCrtFrame) - 1;
}
void ASpriteInstance::setAnimStop( )
{//SangHo - Anim을 재생중단후 인덱스 초기화
is_aniDone = true;
m_nCrtFrame = 0;
}
void ASpriteInstance::setCamera(int _CameraX, int _CameraY)
{//SangHo - Anim을 재생중단후 인덱스 초기화
CameraX = _CameraX;
CameraY = _CameraY;
}
bool ASpriteInstance::IsAnimEnded()
{//SangHo - Anim가 현재 재생중인지 아닌지를 알려준다
if(is_aniDone)
{
return true;
}
//if (m_bReverse)
//{
// if (m_nCrtFrame != 0)
// {
// return false;
// }
//}
else if (m_nCrtFrame != m_sprite->GetAFrames(m_nCrtModule) - 1)
{
return false;
}
int time = m_sprite->GetAFrameTime(m_nCrtModule, m_nCrtFrame);
return ((time == 0) || (m_nCrtAnimation == time - 1));
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void ASpriteInstance::Get_AFrameXZ(int* tmpXZ){//그리기 전에 좌표 확인이 필요할때
m_sprite->Get_AFrameXY(tmpXZ , m_nCrtModule, m_nCrtFrame, m_posX + m_lastAniX, 0, m_flags, 0, 0);
}
void ASpriteInstance::PaintSprite(CGraphics* g,int flags)//SangHo - flags값을 넣지않을경우 0으로 간주한다
{
m_flags = flags;
PaintSprite(g);
}
void ASpriteInstance::PaintSprite(CGraphics* g,int posX,int posY,int flags)//SangHo - flags값을 넣지않을경우 0으로 간주한다
{
m_posX = posX;
m_posY = posY;
m_flags = flags;
PaintSprite(g);
}
void ASpriteInstance::PaintSprite(CGraphics* g)//SangHo - flags값에 따라 좌우상하반전 또는 90도 회전을 지원한다
{//CameraX,CameraY 는 맵 배경 스크롤에 따른 보정 수치
//const static byte FLAG_FLIP_X = 0x01;
//const static byte FLAG_FLIP_Y = 0x02;
//const static byte FLAG_ROT_90 = 0x04;
// m_flags = flags;
//m_bAnimIsOver = false;
if (m_sprite == NULL)
return;
//if ((m_flags & FLAG_DONTDRAW) != 0)
//{
// return;
//}
//if ((m_layer & 4) != 0)
//{
// return;
//}
m_sprite->changePal(m_pal);
m_sprite->SetBlendCustom(s_Blend.blendCustom,s_Blend.overWrite,s_Blend.Blend_Kind,s_Blend.Blend_Percent);
if (m_nCrtAnimation >= -1)//-2 일 경우에 에니메이션이 아닌 프레임또는 모듈을 그린다
{
m_sprite->PaintAFrame(g, m_nCrtModule, m_nCrtFrame,CameraX+ m_posX + m_lastAniX, CameraY+ (m_posY + m_posZ) + m_lastAniZ, m_flags, 0, 0);
if(!b_MoveLock){
m_posX-=m_sprite->m_nowAniX - m_lastAniX;
m_posZ-=m_sprite->m_nowAniZ - m_lastAniZ;
//갱신이 끝난 좌표에 전프레임 좌표를 뺀값만큼을 더해준다
m_lastAniX = m_sprite->m_nowAniX;
m_lastAniZ = m_sprite->m_nowAniZ;
m_stopFlag = m_sprite->m_nowFlag;
}
}
else if (m_nCrtModule >= 0) // m_nCrtModule --> module
{
// 앵커는 임시로 쓰임
m_sprite->PaintModule(g, m_nCrtModule, CameraX+ m_posX, CameraY+ (m_posY + m_posZ), m_flags, g->BOTTOM | g->HCENTER );
}
else if (m_nCrtFrame >= 0) // m_nCrtFrame --> frame
{
m_sprite->PaintFrame(g, m_nCrtFrame,CameraX+ m_posX, CameraY+ (m_posY + m_posZ), m_flags, 0, 0);
}
//m_bAnimIsOver = IsAnimEnded();
m_lastX =m_posX; //SangHo - 인스턴스의 현 좌표를 반영한다. - 몸통체크를 위해서(전좌표로 쓰인다)
m_lastY =m_posY; //SangHo - 인스턴스의 현 좌표를 반영한다. - 몸통체크를 위해서(전좌표로 쓰인다)
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//SangHo - 구조적 문제 해결위해 다시제작 (2008.12.19)
bool ASpriteInstance::UpdateSpriteAnim()
{//SangHo - Animation의 현재값을 1증가시킨다.
//return true - 애니메이션 재생중
//return false - 애니메이션 종료
int _m_time = 0;//총 Time 값 (딜레이수치 디폴값은 0)
int _m_frame = 0;//총 프레임값 (프레임 맥스값)
_m_time = m_sprite->GetAFrameTime(m_nCrtModule, m_nCrtFrame); // 해당 프레임의 Time값
_m_frame = m_sprite->GetAFrames(m_nCrtModule);//m_nCrtModule 는 애니메이션 넘버
{//무결성 체크
if (m_sprite == NULL) return true;
if (m_nCrtAnimation < -1) return true;//업데이트 수행시 time 값을 무조건 ++ 시키므로 초기값은 -1, 루프후는 0으로 돌아간다
if ((m_flags & FLAG_PAUSED) != 0) return true;//일시정지시 무조건 return
}
//{//예외값 통일화 처리
// if (m_nCrtAnimation < 0)
// m_nCrtAnimation=0;
//}
{//프레임의 Time 값을 체크한다 ----- Time 값만큼 딜레이 후에 다음 프레임으로 넘어간다
m_nCrtAnimation++; //인스턴스의 time 값 1증가
if (m_nCrtAnimation < _m_time) //프레임의 타임값보다 작다면 1증가 하고 한번더 그림
if (m_nCrtAnimation == (_m_time-1) && m_nCrtFrame == (_m_frame -1) ){//&&!m_bLoop) //마지막Time 일때 다음으로 증가할 프레임이 없다면 false 가 되야한다
return false;
}else
return true;
}
{//애니의 프레임 값을 체크한다 ----- 마지막 프레임일 경우 (드로잉종료, 루프) 여부 판단
if (m_nCrtFrame < (_m_frame -1)){ //프레임 갯수(-1) 보다 현재 프레임인덱스가 작다면 프레임인덱스를 1증가 시킨다
m_nCrtAnimation=0;//프레임의 타임값 초기화
m_nCrtFrame++;//다음프레임으로
{//만약 넘어간 프레임이 마지막 프레임 & time 1 이면 미리 체크를 해줘야 한다-안그러면 마지막 프레임을 한번더 그린다
_m_time = m_sprite->GetAFrameTime(m_nCrtModule, m_nCrtFrame); // 해당 프레임의 Time값
if((m_nCrtFrame == (_m_frame -1) && _m_time == 1 )&&!m_bLoop)
return false;
else
return true;
}
}else{//업데이트 마지막 값 도달
if(m_bLoop){//루프애니메이션일 경우
m_nCrtAnimation=0;//프레임의 타임값 초기화
m_nCrtFrame = 0;//첫프레임으로
m_lastAniX=0;
m_lastAniZ=0;
//if(Move)UpdateTempXZ(APPLY_X|APPLY_Z);//루프가 돌면 최종좌표를 반영해야한다
return true;
}else{//1회성 애니메이션일 경우
return false;//////////////////////////// 에니메이션 종료 ////////////////////////////
}
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
int ASpriteInstance::GetCurrentAFrameOff(bool bY)
{//SangHo - 현재 Off값 구하는 부분이긴하나 활용예상부분을 모르겠음
int off = (m_sprite->_anims_af_start[m_nCrtModule] + m_nCrtFrame) * 5;
if (bY)
{
return m_sprite->_aframes[off + 3];
}
return m_sprite->_aframes[off + 2];
}
int ASpriteInstance::GetLastAFrameOff(bool bY)
{//SangHo - 마지막 Off값 구하는 부분이긴하나 활용예상부분을 모르겠음
int lastAFrame = m_sprite->GetAFrames(m_nCrtModule) - 1;
int off = (m_sprite->_anims_af_start[m_nCrtModule] + lastAFrame) * 5;
if (bY)
{
return m_sprite->_aframes[off + 3];
}
return m_sprite->_aframes[off + 2];
}
////////////////////////////////////////////////////////////////////////////////////////////////////
int* ASpriteInstance::GetRect(bool bColRect)
{//SangHo - LCD기준의 좌,상,너비,높이 4개인자값을 리턴한다.
if (m_rect == NULL)
{
m_rect = GL_NEW int[4];
}
int posX = m_posX;
int posY = m_posY;
if (m_sprite != NULL)
{
if (m_nCrtModule >= 0)
{
if (m_nCrtAnimation >= 0)
{
m_sprite->GetAFrameRect(m_rect, m_nCrtModule, m_nCrtFrame, posX, posY, m_flags, 0, 0);//bColRect
}
else
{
m_sprite->GetModuleRect(m_rect, m_nCrtModule, posX, posY);
}
}
else if (m_nCrtFrame >= 0)
{
m_sprite->GetFrameRect(m_rect, m_nCrtFrame, posX, posY, m_flags, 0, 0);//bColRect
}
}
return m_rect;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
int* ASpriteInstance::GetAbsoluteRect(bool bColRect)
{//SangHo - 원점기준의 좌,상,너비,높이 4개인자값을 리턴한다.
if (m_rect == NULL)
{
m_rect = GL_NEW int[4];
}
if (m_sprite != NULL)
{
/*if (bColRect && m_sprite->_frames_coll == NULL)
{
return NULL;
}*/
if (m_nCrtAnimation >= 0)
{
m_sprite->GetAFrameRect(m_rect, m_nCrtModule, m_nCrtFrame, 0, 0, m_flags, 0, 0);//bColRect
}
else if (m_nCrtModule >= 0)
{
m_sprite->GetModuleRect(m_rect, m_nCrtModule, 0, 0);
}
else if (m_nCrtFrame >= 0)
{
m_sprite->GetFrameRect(m_rect, m_nCrtFrame, 0, 0, m_flags, 0, 0);//bColRect
}
}
return m_rect;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
int* ASpriteInstance::GetFModuleRect(int module,int posX, int posY, int flags, int hx, int hy)
{//SangHo - 현재 인스턴스가 그리고있는 Animation Frame 의 module번째 모듈의 좌표를 리턴한다(원점기준, 하이퍼 프레임은 해당되지않음)
if (m_rect == NULL)
{
m_rect = GL_NEW int[4];
}
//System.out.println("m_nCrtFrame::::::::::"+m_nCrtFrame);
//System.out.println("GetAnimFrame(m_nCrtModule,m_nCrtFrame):"+m_sprite->GetAnimFrame(m_nCrtModule,m_nCrtFrame));
if(m_sprite != NULL)
{
m_sprite->GetFModuleRect(m_rect,GetAnimFrame(),module,posX,posY,flags,hx,hy);
return m_rect;
}
return NULL;
}
int ASpriteInstance::GetAnimFrame()
{//SangHo - 현재 인스턴스가 그리고있는 Animation Frame 의 고유Index 값을 리턴한다(Ani off값 아님)
if(m_sprite != NULL)
{
return m_sprite->GetAnimFrame(m_nCrtModule,m_nCrtFrame);
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
bool ASpriteInstance::IsRectCrossing(int rect1[], int rect2[])
{//SangHo - 두 면적이 충돌하였는지를 판단한다
if (rect1[0] > rect2[2]) return false;
if (rect1[2] < rect2[0]) return false;
if (rect1[1] > rect2[3]) return false;
if (rect1[3] < rect2[1]) return false;
return true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
bool ASpriteInstance::IsPointInRect(int x, int y, int rect[])
{//SangHo - 한지점이 면적 안에 들어가있는지 아닌지를 체크한다
if (x < rect[0]) return false;
if (x > rect[2]) return false;
if (y < rect[1]) return false;
if (y > rect[3]) return false;
return true;
}
bool ASpriteInstance::SetBlendCustom(bool blendCustom, bool overWrite, int Blend_Kind,int Blend_Percent){
//SangHo - 블랜드를 지정하자마자 그리는것이 아니라 List 에 넣은뒤 정렬후에 한꺼번에 그리기때문에 값을 저장할 필요성이 있음
s_Blend.blendCustom = blendCustom;
s_Blend.overWrite = overWrite;
s_Blend.Blend_Kind = Blend_Kind;
s_Blend.Blend_Percent = Blend_Percent;
return true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// static int ZOOM_IN_X(int x) { return (((x)*ZOOM_X)/ZOOM_X_DIV); }
// static int ZOOM_IN_Y(int y) { return (((y)*ZOOM_Y)/ZOOM_Y_DIV); }
// static int ZOOM_OUT_X(int x) { return (((x)*ZOOM_X_DIV)/ZOOM_X); }
// static int ZOOM_OUT_Y(int y) { return (((y)*ZOOM_Y_DIV)/ZOOM_Y); }
//static int ZOOM_IN_FIXED_X(int x) { return ((((x)>>FIXED_PRECISION)*ZOOM_X)/ZOOM_X_DIV); }
//static int ZOOM_IN_FIXED_Y(int y) { return ((((y)>>FIXED_PRECISION)*ZOOM_Y)/ZOOM_Y_DIV); }
// [Sinh.2007/02/22] optimize for Triplets
// static int ZOOM_OUT_FIXED_X(int x) { return ((((x)<<FIXED_PRECISION)*ZOOM_X_DIV)/ZOOM_X); }
// static int ZOOM_OUT_FIXED_Y(int y) { return ((((y)<<FIXED_PRECISION)*ZOOM_Y_DIV)/ZOOM_Y); }
////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////▽폐소스 - SangHo/////////////////////////////////////////
///////////////////////////////////////////▽폐소스 - SangHo/////////////////////////////////////////
/*
int* ASpriteInstance::GetSpriteRect(int _m_posX, int _m_posY)
{//SangHo - _m_posX,_m_posY 을 기준점으로 가정된 좌,상,너비,높이 4개인자값을 리턴한다.
if (m_rect == NULL)
{
m_rect = GL_NEW int[4];
}
if (m_sprite != NULL)
{
if (m_nCrtAnimation >= 0)
m_sprite->GetAFrameRect(m_rect, m_nCrtModule, m_nCrtFrame, _m_posX, _m_posY, m_flags, 0, 0);
else if (m_nCrtModule >= 0)
m_sprite->GetModuleRect(m_rect, m_nCrtModule, _m_posX, _m_posY);
else if (m_nCrtFrame >= 0)
m_sprite->GetFrameRect(m_rect, m_nCrtFrame, _m_posX, _m_posY, m_flags, 0, 0);
//m_rect[1] -= m_posZ;
//m_rect[3] -= m_posZ;
return m_rect;
}
return NULL;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void ASpriteInstance::PaintSprite_NO_ZOOM(CGraphics* g)
{//SangHo - PaintSprite로 대체
if (m_sprite == NULL)
return;
int posX = m_posX,
posY = m_posY;
for (ASpriteInstance* o = m_parent; o != NULL; o = o->m_parent)
{
posX += o->m_posX;
posY += o->m_posY;
}
posX = ( posX >>FIXED_PRECISION ) + SV_X;
posY = ( posY >>FIXED_PRECISION ) + SV_Y;
// System.out.println("PaintSprite("+posX+", "+posY+")...");
m_sprite->SetCurrentPalette(m_pal);
if (m_nCrtAnimation >= 0)
m_sprite->PaintAFrame(g, m_nCrtModule, m_nCrtFrame, posX, posY, m_flags, 0, 0);
else if (m_nCrtModule >= 0) // m_nCrtModule --> module
m_sprite->PaintModule(g, m_nCrtModule, posX, posY, m_flags);
else if (m_nCrtFrame >= 0) // m_nCrtFrame --> frame
m_sprite->PaintFrame(g, m_nCrtFrame, posX, posY, m_flags, 0, 0);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void ASpriteInstance::ApplyAnimOff()//좌표에 가중치 계산을 하는부분 쓸모없어보임
{
// if (bASSERT) DBG.ASSERT(m_sprite != NULL);
m_posX -= m_posOffX;
m_posY -= m_posOffY;
//////////
// m_sprite->GetAFrameOffset(&m_posOffX, &m_posOffY);
int off = (m_sprite->_anims_af_start[m_nCrtModule] + m_nCrtFrame) * 5;
// m_posOffX = ZOOM_OUT_FIXED_X(m_sprite->_aframes[off+2] << FIXED_PRECISION);
m_posOffX = (m_sprite->_aframes[off+2] << FIXED_PRECISION) * ZOOM_X_DIV / ZOOM_X;
if ((m_flags & FLAG_FLIP_X) != 0) m_posOffX = -m_posOffX;
// m_posOffY = ZOOM_OUT_FIXED_Y(m_sprite->_aframes[off+3] << FIXED_PRECISION);
m_posOffY = (m_sprite->_aframes[off+3] << FIXED_PRECISION) * ZOOM_Y_DIV / ZOOM_Y;
if ((m_flags & FLAG_FLIP_Y) != 0) m_posOffY = -m_posOffY;
//////////
m_posX += m_posOffX;
m_posY += m_posOffY;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void ASpriteInstance::OnScreenTest()
{//SangHo - 사용하지 않음
// _vis = 1 + 2 + 4 + 8;
int ox = 0, oy = 0;
for (ASpriteInstance* o = m_parent; o != NULL; o = o->m_parent)
{
ox += o->m_posX;
oy += o->m_posY;
}
int* rect = GetRect(false);
rect[0] += ox - (GV_W << FIXED_PRECISION);
rect[1] += oy - (GV_H << FIXED_PRECISION);
rect[2] += ox;
rect[3] += oy;
_vis = 0;
if (rect[0] < 0 && rect[2] >= 0 && rect[1] < 0 && rect[3] >= 0)
{
_vis = 1 + 2 + 4 + 8;
}
else
{
//...
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
bool ASpriteInstance::IsOnScreen(int style)
{//SangHo - 사용하지 않음
return ((_vis & style) != 0);
}
int ASpriteInstance::getAniFrameOffY(){
int off = (m_sprite->_anims_af_start[m_nCrtModule] + m_nCrtFrame) * 5;
int m_posOffY = (m_sprite->_aframes[off+3] << FIXED_PRECISION) * ZOOM_Y_DIV / ZOOM_Y;
if ((m_flags & FLAG_FLIP_Y) != 0) m_posOffY = -m_posOffY;
return m_posOffY;
}
*/ | [
"secret5374@hotmail.com"
] | [
[
[
1,
635
]
]
] |
ebc6fb20e89828f29706f62aee1b4cffece75874 | 36bf908bb8423598bda91bd63c4bcbc02db67a9d | /Library/CHotkeyHandler.cpp | 15febe39e79e820d09d62728a8f847983dbeed2d | [] | no_license | code4bones/crawlpaper | edbae18a8b099814a1eed5453607a2d66142b496 | f218be1947a9791b2438b438362bc66c0a505f99 | refs/heads/master | 2021-01-10 13:11:23 | 2011-04-14 11:04:17 | 2011-04-14 11:04:17 | 44,686,513 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 18,886 | cpp | #include "env.h"
#include "pragma.h"
#include "macro.h"
#include "window.h"
#include "traceexpr.h"
//#define _TRACE_FLAG _TRFLAG_TRACEOUTPUT
//#define _TRACE_FLAG _TRFLAG_NOTRACE
#define _TRACE_FLAG_INFO _TRFLAG_NOTRACE
#define _TRACE_FLAG_WARN _TRFLAG_NOTRACE
#define _TRACE_FLAG_ERR _TRFLAG_NOTRACE
/*
History
----------
Monday, April 21, 2003
* Initial version
Tuesday, April 22, 2003
* Added list entries recycling into RemoveHandler(). Now removing works correctly.
* Added utility functions: HotkeyFlagsToModifiers() and HotkeyModifiersToFlags()
Wednesday, April 23, 2003
* Added checks on Start() to prevent starting if already started.
Thursday, April 24, 2003
* Fixed CreateThread() in Start() calling so that it works on Win9x.
Thursday, May 01, 2003
* Fixed code in MakeWindow() and now CHotkeyHandler works under Win9x very well.
Monday, Oct 20, 2003
* Removed 'using std::vector' from header file
* Fixed a minor bug in RemoveHandler()
*/
/* -----------------------------------------------------------------------------
* Copyright (c) 2003 Lallous <lallousx86@yahoo.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
* -----------------------------------------------------------------------------
*/
/*
CHotkeyHandler() is a class that wrappes the RegisterHotkey() and its
UnregisterHotkey() Windows APIs.
This class provides a simple method to implement and handle multiple hotkeys at the same time.
* Debug Flag:
--------------
bool bDebug;
This flag is used to turn debugging on/off. Useful when you're developing.
* Constructor
---------------
CHotkeyHandler(bool Debug = false);
This constructor initializes internal variables and sets debug info on/off
If you call Start() and do not call Stop() the destructor will automatically Stop() for you.
* Start()
-----------
int Start(LPVOID Param=NULL);
This method is asynchronous; It starts the hotkey listener.
You must have at least one handler inserted before calling this method, otherwise hkheNoEntry
would be returned.
It returns an hkhe error code.
'Param' is a user supplied pointer used when calling the hotkey callbacks.
* Stop()
-----------
int Stop();
After you've started the hotkey listener, you can stop it w/ Stop().
Stop() will return success if it was stopped successfully or if it was not started at all.
* InsertHandler()
--------------------
int InsertHandler(WORD mod, WORD virt, tHotkeyCB cb, int &index);
This function will return an error code.
'index' will be filled by the index of where the hotkey is stored (1 based).
If you attempt to insert a hotkey that already exists then 'index' will be the index value
of that previously inserted hotkey.
'mod' is any of the MOD_XXXX constants.
'virt' is the virtual key code.
'cb' is the handler that will be called. The prototype is: void Callback(void *param)
The 'param' of 'cb' will be the one that you passed when you called Start()
* RemoveHandler()
--------------------
int RemoveHandler(const int index);
Removes a hotkey definition. This function has effects only when called before Start()
or after Stop().
* HotkeyModifiersToFlags()
----------------------------
WORD HotkeyModifiersToFlags(WORD modf);
Converts from MOD_XXX modifiers into HOTKEYF_XXXX to be used by HOTKEYFLAGS.
This method is static.
* HotkeyFlagsToModifiers()
-----------------------------
WORD HotkeyFlagsToModifiers(WORD hkf);
Converts HOTKEYFLAGS used by CHotKeyCtrl into MOD_XXX used by windows API
This method is static.
Error codes
-------------
CHotkeyHandler::hkheXXXXX
hkheOk - Success
hkheClassError - Window class registration error
hkheWindowError - Window creation error
hkheNoEntry - No entry found at given index
hkheRegHotkeyError - Could not register hotkey
hkheMessageLoop - Could not create message loop thread
hkheInternal - Internal error
*/
#include "chotkeyhandler.h"
//-------------------------------------------------------------------------------------
// Initializes internal variables
CHotkeyHandler::CHotkeyHandler(bool Debug)
{
bDebug = Debug;
m_bStarted = false;
m_hWnd = NULL;
m_hMessageLoopThread = m_hPollingError = m_hRaceProtection = NULL;
}
//-------------------------------------------------------------------------------------
// Initializes internal variables
CHotkeyHandler::~CHotkeyHandler()
{
if (m_bStarted)
Stop();
}
//-------------------------------------------------------------------------------------
// Releases and deletes the protection mutex
void CHotkeyHandler::EndRaceProtection()
{
if (m_hRaceProtection)
{
::ReleaseMutex(m_hRaceProtection);
::CloseHandle(m_hRaceProtection);
// invalidate handle
m_hRaceProtection = NULL;
}
}
//-------------------------------------------------------------------------------------
// Creates and acquires protection mutex
bool CHotkeyHandler::BeginRaceProtection()
{
LPCTSTR szMutex = _T("{97B7C451-2467-4C3C-BB91-25AC918C2430}");
// failed to create a mutex ? to open ?
if (
// failed to create and the object does not exist?
(
!(m_hRaceProtection = ::CreateMutex(NULL, FALSE, szMutex)) &&
(::GetLastError() != ERROR_ALREADY_EXISTS)
) ||
!(m_hRaceProtection = ::OpenMutex(MUTEX_ALL_ACCESS, FALSE, szMutex))
)
return false;
::WaitForSingleObject(m_hRaceProtection, INFINITE);
return true;
}
//-------------------------------------------------------------------------------------
// removes a disabled hotkey from the internal list
// If this function is of use only before a Start() call or after a Stop()
int CHotkeyHandler::RemoveHandler(const int index)
{
// index out of range ?
if (m_listHk.size() <= index)
return hkheNoEntry;
// mark handler as deleted
m_listHk.at(index).deleted = true;
return hkheOk;
}
//-------------------------------------------------------------------------------------
// Generates a unique atom and then registers a hotkey
//
int CHotkeyHandler::EnableHotkey(const int index)
{
TCHAR atomname[MAX_PATH];
ATOM a;
// get hotkey definition
tHotkeyDef *def = &m_listHk.at(index);
// If entry does not exist then return Ok
if (def->deleted)
return hkheOk;
// compose atom name
wsprintf(atomname, _T("ED7D65EB-B139-44BB-B455-7BB83FE361DE-%08lX"), MAKELONG(def->virt, def->mod));
// Try to create an atom
a = ::GlobalAddAtom(atomname);
// could not create? probably already there
if (!a)
a = ::GlobalFindAtom(atomname); // try to locate atom
if (!a || !::RegisterHotKey(m_hWnd, a, def->mod, def->virt))
{
if (a)
::GlobalDeleteAtom(a);
return hkheRegHotkeyError;
}
// store atom into definition too
def->id = a;
return hkheOk;
}
//-------------------------------------------------------------------------------------
// Unregisters a hotkey and deletes the atom
int CHotkeyHandler::DisableHotkey(const int index)
{
// get hotkey definition
tHotkeyDef *def = &m_listHk.at(index);
// skip deleted entry
if (def->deleted)
return hkheOk;
// already registered
if (def->id)
{
UnregisterHotKey(m_hWnd, def->id);
GlobalDeleteAtom(def->id);
return hkheOk;
}
else
return hkheNoEntry;
}
//-------------------------------------------------------------------------------------
// Locates a hotkey definition given its ID
int CHotkeyHandler::FindHandlerById(const ATOM id, tHotkeyDef *&def)
{
tHotkeyList::iterator i;
for (i=m_listHk.begin(); i != m_listHk.end(); i++)
{
def = &*i;
if ((def->id == id) && !def->deleted)
return hkheOk;
}
return hkheNoEntry;
}
//-------------------------------------------------------------------------------------
// Finds a deleted entry
int CHotkeyHandler::FindDeletedHandler(int &idx)
{
tHotkeyDef *def;
int i, c = m_listHk.size();
for (i=0; i< c; i++)
{
def = &m_listHk[i];
if (def->deleted)
{
idx = i;
return hkheOk;
}
}
return hkheNoEntry;
}
//-------------------------------------------------------------------------------------
// Finds a hotkeydef given it's modifier 'mod' and virtuak key 'virt'
// If return value is hkheOk then 'idx' is filled with the found index
// Otherwise 'idx' is left untouched.
int CHotkeyHandler::FindHandler(WORD mod, WORD virt, int &idx)
{
tHotkeyDef *def;
int i, c = m_listHk.size();
for (i=0; i < c; i++)
{
def = &m_listHk[i];
// found anything in the list ?
if ( (def->mod == mod) && (def->virt == virt) && !def->deleted)
{
// return its id
idx = i;
return hkheOk;
}
}
return hkheNoEntry;
}
//-------------------------------------------------------------------------------------
// Inserts a hotkey into the list
// Returns into 'idx' the index of where the definition is added
// You may use the returned idx to modify/delete this definition
int CHotkeyHandler::InsertHandler(WORD mod, WORD virt, tHotkeyCB cb, int &idx)
{
tHotkeyDef def;
// Try to find a deleted entry and use it
if (FindDeletedHandler(idx) == hkheOk)
{
tHotkeyDef *d = &m_listHk.at(idx);
d->deleted = false;
d->id = NULL;
d->callback = cb;
d->virt = virt;
d->mod = mod;
}
// Add a new entry
else if (FindHandler(mod, virt, idx) == hkheNoEntry)
{
def.mod = mod;
def.virt = virt;
def.callback = cb;
def.id = NULL;
def.deleted = false;
idx = m_listHk.size();
m_listHk.push_back(def);
}
return hkheOk;
}
//-------------------------------------------------------------------------------------
// Window Procedure
// Almost empty; it responds to the WM_DESTROY message only
LRESULT CALLBACK CHotkeyHandler::WindowProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
switch (Msg)
{
case WM_DESTROY:
::PostQuitMessage(0);
break;
default:
return ::DefWindowProc(hWnd, Msg, wParam, lParam);
}
return 0;
}
//-------------------------------------------------------------------------------------
// This function is run from a new thread, it:
// 1) Create our hidden window to process hotkeys
// 2) Enables (registers) all defined hotkeys
// 3) Starts the message loop
DWORD WINAPI CHotkeyHandler::MessageLoop(LPVOID Param)
{
int rc;
CHotkeyHandler *_this = reinterpret_cast<CHotkeyHandler *>(Param);
// create window
if ((rc = _this->MakeWindow()) != hkheOk)
{
_this->m_PollingError = rc;
::SetEvent(_this->m_hPollingError);
return rc;
}
// register all hotkeys
for (int i=0; i<_this->m_listHk.size(); i++)
{
// try to register
if ((rc = _this->EnableHotkey(i)) != hkheOk)
{
// disable hotkeys enabled so far
for (int j=0;j<i;j++)
_this->DisableHotkey(j);
// uninit window
_this->MakeWindow(true);
// signal that error is ready
_this->m_PollingError = rc;
::SetEvent(_this->m_hPollingError);
return rc;
}
}
_this->m_PollingError = hkheOk;
::SetEvent(_this->m_hPollingError);
MSG msg;
BOOL bRet;
while ( ((bRet = ::GetMessage(&msg, _this->m_hWnd, 0, 0)) != 0) )
{
if (bRet == -1)
break;
// hotkey received ?
if (msg.message == WM_HOTKEY)
{
tHotkeyDef *def;
// try to find handler (wParam == id (ATOM)
if (_this->FindHandlerById( (ATOM) msg.wParam, def) == hkheOk)
{
// call the registered handler
if (def->callback)
def->callback(_this->m_lpCallbackParam);
}
}
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
return hkheOk;
}
//-------------------------------------------------------------------------------------
// This asynchronous function will register all hotkeys and starts the window message
// loop into its own thread. You would have to call Stop() to unroll everything
//
int CHotkeyHandler::Start(LPVOID cbParam)
{
int rc;
// avoid starting again if already started
if (m_bStarted)
return hkheOk;
// Do not start if no entries are there!
if (m_listHk.empty())
return hkheNoEntry;
if (!BeginRaceProtection())
return hkheInternal;
if (!(m_hPollingError = ::CreateEvent(NULL, FALSE, FALSE, NULL)))
{
rc = hkheMessageLoop;
goto cleanup;
}
m_lpCallbackParam = cbParam;
// create message loop thread
DWORD dwThreadId;
m_hMessageLoopThread =
::CreateThread(NULL,
NULL,
MessageLoop,
static_cast<LPVOID>(this),
NULL,
&dwThreadId);
if (!m_hMessageLoopThread)
{
rc = hkheMessageLoop;
goto cleanup;
}
// wait until we get an error code from the message loop thread
::WaitForSingleObject(m_hPollingError, INFINITE);
if (m_PollingError != hkheOk)
{
::CloseHandle(m_hMessageLoopThread);
m_hMessageLoopThread = NULL;
}
rc = m_PollingError;
m_bStarted = true;
cleanup:
EndRaceProtection();
return rc;
}
//-------------------------------------------------------------------------------------
// Disables all hotkeys then kills the hidden window that processed the hotkeys
// The return code is the one returned from the MessageLoop()
//
int CHotkeyHandler::Stop()
{
// not started? return Success
if (!m_bStarted || !m_hMessageLoopThread)
return hkheOk;
if (!BeginRaceProtection())
return hkheInternal;
// disable all hotkeys
for (int i=0;i<m_listHk.size();i++)
DisableHotkey(i);
// tell message loop to terminate
::SendMessage(m_hWnd, WM_DESTROY, 0, 0);
// wait for the thread to exit by itself
if (::WaitForSingleObject(m_hMessageLoopThread, 3000) == WAIT_TIMEOUT)
::TerminateThread(m_hMessageLoopThread, 0); // kill thread
DWORD exitCode;
::GetExitCodeThread(m_hMessageLoopThread, &exitCode);
// close handle of thread
::CloseHandle(m_hMessageLoopThread);
// reset this variable
m_hMessageLoopThread = NULL;
// unregister window class
MakeWindow(true);
// kill error polling event
::CloseHandle(m_hPollingError);
m_bStarted = false;
EndRaceProtection();
return exitCode;
}
//-------------------------------------------------------------------------------------
// Creates the hidden window that will receive hotkeys notification
// When bUnmake, it will Unregister the window class
int CHotkeyHandler::MakeWindow(bool bUnmake)
{
HWND hwnd;
WNDCLASSEX wcl;
HINSTANCE hInstance = ::GetModuleHandle(NULL);
// Our hotkey processing window class
LPTSTR szClassName = _T("HKWND-CLS-BC090410-3872-49E5-BDF7-1BB8056BF696");
if (bUnmake)
{
UnregisterClass(szClassName, hInstance);
m_hWnd = NULL;
return hkheOk;
}
// Set the window class
wcl.cbSize = sizeof(WNDCLASSEX);
wcl.cbClsExtra = 0;
wcl.cbWndExtra = 0;
wcl.hbrBackground = NULL;//(HBRUSH) GetStockObject(WHITE_BRUSH);
wcl.lpszClassName = szClassName;
wcl.lpszMenuName = NULL;
wcl.hCursor = NULL;//LoadCursor(NULL, IDC_ARROW);
wcl.hIcon = NULL;//LoadIcon(NULL, IDI_APPLICATION);
wcl.hIconSm = NULL;//LoadIcon(NULL, IDI_WINLOGO);
wcl.hInstance = hInstance;
wcl.lpfnWndProc = WindowProc;
wcl.style = 0;
// Failed to register class other than that the class already exists?
if (!::RegisterClassEx(&wcl) && (::GetLastError() != ERROR_CLASS_ALREADY_EXISTS))
return hkheClassError;
// Create the window
hwnd = ::CreateWindowEx(
0,
szClassName,
_T("CHotkeyHandlerWindow"),
WS_OVERLAPPEDWINDOW,
0,
0,
100,
100,
HWND_DESKTOP,
NULL,
hInstance,
NULL);
// Window creation failed ?
if (!hwnd)
return hkheWindowError;
// hide window
::ShowWindow(hwnd, bDebug ? SW_SHOW : SW_HIDE);
m_hWnd = hwnd;
return hkheOk;
}
//---------------------------------------------------------------------------------
// Converts HOTKEYFLAGS used by CHotKeyCtrl into MOD_XXX used by windows API
//
WORD CHotkeyHandler::HotkeyFlagsToModifiers(WORD hkf)
{
WORD r;
r = ((hkf & HOTKEYF_CONTROL) ? MOD_CONTROL : 0) |
((hkf & HOTKEYF_ALT) ? MOD_ALT : 0) |
((hkf & HOTKEYF_SHIFT) ? MOD_SHIFT : 0);
return r;
}
//---------------------------------------------------------------------------------
// Converts from MOD_XXX modifiers into HOTKEYF_XXXX
//
WORD CHotkeyHandler::HotkeyModifiersToFlags(WORD modf)
{
WORD r;
r = ((modf & MOD_CONTROL) ? HOTKEYF_CONTROL : 0) |
((modf & MOD_ALT) ? HOTKEYF_ALT : 0) |
((modf & MOD_SHIFT) ? HOTKEYF_SHIFT : 0);
return r;
} | [
"luca.pierge@gmail.com"
] | [
[
[
1,
635
]
]
] |
16129e84615c3d39c7f6b894dcfe634fc4c54412 | 0466568120485fcabdba5aa22a4b0fea13068b8b | /opencv/samples/gpu/cascadeclassifier_nvidia_api.cpp | b33b447fec1513652f6d4ab25865d08ee2419b4c | [] | no_license | coapp-packages/opencv | be25a9aec58d9ac890fc764932ba67914add078d | c78981e0d8f602fde523a82c3a7e2c3fef1f39bc | refs/heads/master | 2020-05-17 12:11:25 | 2011-07-14 17:13:01 | 2011-07-14 17:13:01 | 2,048,483 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,943 | cpp | #if _MSC_VER >= 1400
#pragma warning( disable : 4201 4408 4127 4100)
#endif
#include "cvconfig.h"
#include <iostream>
#include <iomanip>
#include "opencv2/opencv.hpp"
#include "opencv2/gpu/gpu.hpp"
#ifdef HAVE_CUDA
#include "NCVHaarObjectDetection.hpp"
#endif
using namespace std;
using namespace cv;
#if !defined(HAVE_CUDA)
int main( int argc, const char** argv )
{
cout << "Please compile the library with CUDA support" << endl;
return -1;
}
#else
const Size2i preferredVideoFrameSize(640, 480);
const string wndTitle = "NVIDIA Computer Vision :: Haar Classifiers Cascade";
void matPrint(Mat &img, int lineOffsY, Scalar fontColor, const string &ss)
{
int fontFace = FONT_HERSHEY_DUPLEX;
double fontScale = 0.8;
int fontThickness = 2;
Size fontSize = cv::getTextSize("T[]", fontFace, fontScale, fontThickness, 0);
Point org;
org.x = 1;
org.y = 3 * fontSize.height * (lineOffsY + 1) / 2;
putText(img, ss, org, fontFace, fontScale, CV_RGB(0,0,0), 5*fontThickness/2, 16);
putText(img, ss, org, fontFace, fontScale, fontColor, fontThickness, 16);
}
void displayState(Mat &canvas, bool bHelp, bool bGpu, bool bLargestFace, bool bFilter, double fps)
{
Scalar fontColorRed = CV_RGB(255,0,0);
Scalar fontColorNV = CV_RGB(118,185,0);
ostringstream ss;
ss << "FPS = " << setprecision(1) << fixed << fps;
matPrint(canvas, 0, fontColorRed, ss.str());
ss.str("");
ss << "[" << canvas.cols << "x" << canvas.rows << "], " <<
(bGpu ? "GPU, " : "CPU, ") <<
(bLargestFace ? "OneFace, " : "MultiFace, ") <<
(bFilter ? "Filter:ON" : "Filter:OFF");
matPrint(canvas, 1, fontColorRed, ss.str());
if (bHelp)
{
matPrint(canvas, 2, fontColorNV, "Space - switch GPU / CPU");
matPrint(canvas, 3, fontColorNV, "M - switch OneFace / MultiFace");
matPrint(canvas, 4, fontColorNV, "F - toggle rectangles Filter");
matPrint(canvas, 5, fontColorNV, "H - toggle hotkeys help");
}
else
{
matPrint(canvas, 2, fontColorNV, "H - toggle hotkeys help");
}
}
NCVStatus process(Mat *srcdst,
Ncv32u width, Ncv32u height,
NcvBool bFilterRects, NcvBool bLargestFace,
HaarClassifierCascadeDescriptor &haar,
NCVVector<HaarStage64> &d_haarStages, NCVVector<HaarClassifierNode128> &d_haarNodes,
NCVVector<HaarFeature64> &d_haarFeatures, NCVVector<HaarStage64> &h_haarStages,
INCVMemAllocator &gpuAllocator,
INCVMemAllocator &cpuAllocator,
cudaDeviceProp &devProp)
{
ncvAssertReturn(!((srcdst == NULL) ^ gpuAllocator.isCounting()), NCV_NULL_PTR);
NCVStatus ncvStat;
NCV_SET_SKIP_COND(gpuAllocator.isCounting());
NCVMatrixAlloc<Ncv8u> d_src(gpuAllocator, width, height);
ncvAssertReturn(d_src.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC);
NCVMatrixAlloc<Ncv8u> h_src(cpuAllocator, width, height);
ncvAssertReturn(h_src.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC);
NCVVectorAlloc<NcvRect32u> d_rects(gpuAllocator, 100);
ncvAssertReturn(d_rects.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC);
NCV_SKIP_COND_BEGIN
for (Ncv32u i=0; i<(Ncv32u)srcdst->rows; i++)
{
memcpy(h_src.ptr() + i * h_src.stride(), srcdst->ptr(i), srcdst->cols);
}
ncvStat = h_src.copySolid(d_src, 0);
ncvAssertReturnNcvStat(ncvStat);
ncvAssertCUDAReturn(cudaStreamSynchronize(0), NCV_CUDA_ERROR);
NCV_SKIP_COND_END
NcvSize32u roi;
roi.width = d_src.width();
roi.height = d_src.height();
Ncv32u numDetections;
ncvStat = ncvDetectObjectsMultiScale_device(
d_src, roi, d_rects, numDetections, haar, h_haarStages,
d_haarStages, d_haarNodes, d_haarFeatures,
haar.ClassifierSize,
(bFilterRects || bLargestFace) ? 4 : 0,
1.2f, 1,
(bLargestFace ? NCVPipeObjDet_FindLargestObject : 0)
| NCVPipeObjDet_VisualizeInPlace,
gpuAllocator, cpuAllocator, devProp, 0);
ncvAssertReturnNcvStat(ncvStat);
ncvAssertCUDAReturn(cudaStreamSynchronize(0), NCV_CUDA_ERROR);
NCV_SKIP_COND_BEGIN
ncvStat = d_src.copySolid(h_src, 0);
ncvAssertReturnNcvStat(ncvStat);
ncvAssertCUDAReturn(cudaStreamSynchronize(0), NCV_CUDA_ERROR);
for (Ncv32u i=0; i<(Ncv32u)srcdst->rows; i++)
{
memcpy(srcdst->ptr(i), h_src.ptr() + i * h_src.stride(), srcdst->cols);
}
NCV_SKIP_COND_END
return NCV_SUCCESS;
}
int main(int argc, const char** argv)
{
cout << "OpenCV / NVIDIA Computer Vision" << endl;
cout << "Face Detection in video and live feed" << endl;
cout << "Syntax: exename <cascade_file> <image_or_video_or_cameraid>" << endl;
cout << "=========================================" << endl;
ncvAssertPrintReturn(cv::gpu::getCudaEnabledDeviceCount() != 0, "No GPU found or the library is compiled without GPU support", -1);
ncvAssertPrintReturn(argc == 3, "Invalid number of arguments", -1);
string cascadeName = argv[1];
string inputName = argv[2];
NCVStatus ncvStat;
NcvBool bQuit = false;
VideoCapture capture;
Size2i frameSize;
//open content source
Mat image = imread(inputName);
Mat frame;
if (!image.empty())
{
frameSize.width = image.cols;
frameSize.height = image.rows;
}
else
{
if (!capture.open(inputName))
{
int camid = -1;
istringstream ss(inputName);
int x = 0;
ss >> x;
ncvAssertPrintReturn(capture.open(camid) != 0, "Can't open source", -1);
}
capture >> frame;
ncvAssertPrintReturn(!frame.empty(), "Empty video source", -1);
frameSize.width = frame.cols;
frameSize.height = frame.rows;
}
NcvBool bUseGPU = true;
NcvBool bLargestObject = false;
NcvBool bFilterRects = true;
NcvBool bHelpScreen = false;
CascadeClassifier classifierOpenCV;
ncvAssertPrintReturn(classifierOpenCV.load(cascadeName) != 0, "Error (in OpenCV) opening classifier", -1);
int devId;
ncvAssertCUDAReturn(cudaGetDevice(&devId), -1);
cudaDeviceProp devProp;
ncvAssertCUDAReturn(cudaGetDeviceProperties(&devProp, devId), -1);
cout << "Using GPU: " << devId << "(" << devProp.name <<
"), arch=" << devProp.major << "." << devProp.minor << endl;
//==============================================================================
//
// Load the classifier from file (assuming its size is about 1 mb)
// using a simple allocator
//
//==============================================================================
NCVMemNativeAllocator gpuCascadeAllocator(NCVMemoryTypeDevice, devProp.textureAlignment);
ncvAssertPrintReturn(gpuCascadeAllocator.isInitialized(), "Error creating cascade GPU allocator", -1);
NCVMemNativeAllocator cpuCascadeAllocator(NCVMemoryTypeHostPinned, devProp.textureAlignment);
ncvAssertPrintReturn(cpuCascadeAllocator.isInitialized(), "Error creating cascade CPU allocator", -1);
Ncv32u haarNumStages, haarNumNodes, haarNumFeatures;
ncvStat = ncvHaarGetClassifierSize(cascadeName, haarNumStages, haarNumNodes, haarNumFeatures);
ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error reading classifier size (check the file)", -1);
NCVVectorAlloc<HaarStage64> h_haarStages(cpuCascadeAllocator, haarNumStages);
ncvAssertPrintReturn(h_haarStages.isMemAllocated(), "Error in cascade CPU allocator", -1);
NCVVectorAlloc<HaarClassifierNode128> h_haarNodes(cpuCascadeAllocator, haarNumNodes);
ncvAssertPrintReturn(h_haarNodes.isMemAllocated(), "Error in cascade CPU allocator", -1);
NCVVectorAlloc<HaarFeature64> h_haarFeatures(cpuCascadeAllocator, haarNumFeatures);
ncvAssertPrintReturn(h_haarFeatures.isMemAllocated(), "Error in cascade CPU allocator", -1);
HaarClassifierCascadeDescriptor haar;
ncvStat = ncvHaarLoadFromFile_host(cascadeName, haar, h_haarStages, h_haarNodes, h_haarFeatures);
ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error loading classifier", -1);
NCVVectorAlloc<HaarStage64> d_haarStages(gpuCascadeAllocator, haarNumStages);
ncvAssertPrintReturn(d_haarStages.isMemAllocated(), "Error in cascade GPU allocator", -1);
NCVVectorAlloc<HaarClassifierNode128> d_haarNodes(gpuCascadeAllocator, haarNumNodes);
ncvAssertPrintReturn(d_haarNodes.isMemAllocated(), "Error in cascade GPU allocator", -1);
NCVVectorAlloc<HaarFeature64> d_haarFeatures(gpuCascadeAllocator, haarNumFeatures);
ncvAssertPrintReturn(d_haarFeatures.isMemAllocated(), "Error in cascade GPU allocator", -1);
ncvStat = h_haarStages.copySolid(d_haarStages, 0);
ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error copying cascade to GPU", -1);
ncvStat = h_haarNodes.copySolid(d_haarNodes, 0);
ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error copying cascade to GPU", -1);
ncvStat = h_haarFeatures.copySolid(d_haarFeatures, 0);
ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error copying cascade to GPU", -1);
//==============================================================================
//
// Calculate memory requirements and create real allocators
//
//==============================================================================
NCVMemStackAllocator gpuCounter(devProp.textureAlignment);
ncvAssertPrintReturn(gpuCounter.isInitialized(), "Error creating GPU memory counter", -1);
NCVMemStackAllocator cpuCounter(devProp.textureAlignment);
ncvAssertPrintReturn(cpuCounter.isInitialized(), "Error creating CPU memory counter", -1);
ncvStat = process(NULL, frameSize.width, frameSize.height,
false, false, haar,
d_haarStages, d_haarNodes,
d_haarFeatures, h_haarStages,
gpuCounter, cpuCounter, devProp);
ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error in memory counting pass", -1);
NCVMemStackAllocator gpuAllocator(NCVMemoryTypeDevice, gpuCounter.maxSize(), devProp.textureAlignment);
ncvAssertPrintReturn(gpuAllocator.isInitialized(), "Error creating GPU memory allocator", -1);
NCVMemStackAllocator cpuAllocator(NCVMemoryTypeHostPinned, cpuCounter.maxSize(), devProp.textureAlignment);
ncvAssertPrintReturn(cpuAllocator.isInitialized(), "Error creating CPU memory allocator", -1);
printf("Initialized for frame size [%dx%d]\n", frameSize.width, frameSize.height);
//==============================================================================
//
// Main processing loop
//
//==============================================================================
namedWindow(wndTitle, 1);
Mat gray, frameDisp;
do
{
Mat gray;
cvtColor((image.empty() ? frame : image), gray, CV_BGR2GRAY);
//
// process
//
NcvSize32u minSize = haar.ClassifierSize;
if (bLargestObject)
{
Ncv32u ratioX = preferredVideoFrameSize.width / minSize.width;
Ncv32u ratioY = preferredVideoFrameSize.height / minSize.height;
Ncv32u ratioSmallest = min(ratioX, ratioY);
ratioSmallest = max((Ncv32u)(ratioSmallest / 2.5f), (Ncv32u)1);
minSize.width *= ratioSmallest;
minSize.height *= ratioSmallest;
}
Ncv32f avgTime;
NcvTimer timer = ncvStartTimer();
if (bUseGPU)
{
ncvStat = process(&gray, frameSize.width, frameSize.height,
bFilterRects, bLargestObject, haar,
d_haarStages, d_haarNodes,
d_haarFeatures, h_haarStages,
gpuAllocator, cpuAllocator, devProp);
ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error in memory counting pass", -1);
}
else
{
vector<Rect> rectsOpenCV;
classifierOpenCV.detectMultiScale(
gray,
rectsOpenCV,
1.2f,
bFilterRects ? 4 : 0,
(bLargestObject ? CV_HAAR_FIND_BIGGEST_OBJECT : 0)
| CV_HAAR_SCALE_IMAGE,
Size(minSize.width, minSize.height));
for (size_t rt = 0; rt < rectsOpenCV.size(); ++rt)
rectangle(gray, rectsOpenCV[rt], Scalar(255));
}
avgTime = (Ncv32f)ncvEndQueryTimerMs(timer);
cvtColor(gray, frameDisp, CV_GRAY2BGR);
displayState(frameDisp, bHelpScreen, bUseGPU, bLargestObject, bFilterRects, 1000.0f / avgTime);
imshow(wndTitle, frameDisp);
//handle input
switch (cvWaitKey(3))
{
case ' ':
bUseGPU = !bUseGPU;
break;
case 'm':
case 'M':
bLargestObject = !bLargestObject;
break;
case 'f':
case 'F':
bFilterRects = !bFilterRects;
break;
case 'h':
case 'H':
bHelpScreen = !bHelpScreen;
break;
case 27:
bQuit = true;
break;
}
// For camera and video file, capture the next image
if (capture.isOpened())
{
capture >> frame;
if (frame.empty())
{
break;
}
}
} while (!bQuit);
cvDestroyWindow(wndTitle.c_str());
return 0;
}
#endif //!defined(HAVE_CUDA)
| [
"vp153@73c94f0f-984f-4a5f-82bc-2d8db8d8ee08",
"anatoly@73c94f0f-984f-4a5f-82bc-2d8db8d8ee08",
"anton@73c94f0f-984f-4a5f-82bc-2d8db8d8ee08",
"alexeys@73c94f0f-984f-4a5f-82bc-2d8db8d8ee08"
] | [
[
[
1,
1
],
[
3,
3
],
[
8,
9
]
],
[
[
2,
2
],
[
4,
5
],
[
12,
12
],
[
14,
14
],
[
16,
18
],
[
21,
21
],
[
24,
24
],
[
26,
27
],
[
30,
32
],
[
42,
45
],
[
54,
54
],
[
60,
60
],
[
64,
67
],
[
71,
71
],
[
76,
77
],
[
79,
120
],
[
122,
144
],
[
147,
147
],
[
152,
152
],
[
155,
155
],
[
158,
158
],
[
163,
163
],
[
168,
168
],
[
171,
171
],
[
173,
173
],
[
177,
177
],
[
181,
181
],
[
184,
184
],
[
187,
187
],
[
190,
191
],
[
200,
203
],
[
206,
219
],
[
221,
230
],
[
232,
278
],
[
281,
284
],
[
286,
291
],
[
293,
295
],
[
298,
304
],
[
306,
307
],
[
309,
321
],
[
324,
333
],
[
336,
336
],
[
339,
340
],
[
346,
346
],
[
350,
350
],
[
354,
359
],
[
369,
375
]
],
[
[
6,
7
],
[
15,
15
],
[
19,
20
],
[
22,
23
],
[
25,
25
],
[
28,
29
],
[
33,
41
],
[
46,
53
],
[
55,
59
],
[
61,
63
],
[
68,
70
],
[
72,
75
],
[
78,
78
],
[
121,
121
],
[
145,
146
],
[
148,
151
],
[
153,
154
],
[
156,
157
],
[
159,
162
],
[
164,
167
],
[
169,
170
],
[
172,
172
],
[
174,
176
],
[
178,
180
],
[
182,
183
],
[
185,
186
],
[
188,
189
],
[
192,
199
],
[
204,
205
],
[
220,
220
],
[
231,
231
],
[
279,
280
],
[
285,
285
],
[
292,
292
],
[
296,
297
],
[
305,
305
],
[
308,
308
],
[
322,
323
],
[
334,
335
],
[
337,
337
],
[
341,
345
],
[
347,
349
],
[
351,
353
],
[
360,
368
],
[
376,
376
]
],
[
[
10,
11
],
[
13,
13
],
[
338,
338
]
]
] |
3823170ca2526b7b1618b236d6bca0edf090a2d9 | 3e69b159d352a57a48bc483cb8ca802b49679d65 | /tags/release-2005-10-27/pcbnew/netlist.cpp | 7707b586004638238f618260d1327606a22517e2 | [] | no_license | BackupTheBerlios/kicad-svn | 4b79bc0af39d6e5cb0f07556eb781a83e8a464b9 | 4c97bbde4b1b12ec5616a57c17298c77a9790398 | refs/heads/master | 2021-01-01 19:38:40 | 2006-06-19 20:01:24 | 2006-06-19 20:01:24 | 40,799,911 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 31,012 | cpp | /************************************/
/* PCBNEW: traitement des netlistes */
/************************************/
/* Fichier NETLIST.CPP */
/*
Fonction de lecture de la netliste pour:
- Chargement modules et nouvelles connexions
- Test des modules (modules manquants ou en trop
- Recalcul du chevelu
Remarque importante:
Lors de la lecture de la netliste pour Chargement modules
et nouvelles connexions, l'identification des modules peut se faire selon
2 criteres:
- la reference (U2, R5 ..): c'est le mode normal
- le Time Stamp (Signature Temporelle), a utiliser apres reannotation
d'un schema, donc apres modification des references sans pourtant
avoir reellement modifie le schema
*/
#include "fctsys.h"
#include "gr_basic.h"
#include "common.h"
#include "pcbnew.h"
#include "autorout.h"
#include "protos.h"
#define TESTONLY 1 /* ctes utilisees lors de l'appel a */
#define READMODULE 0 /* ReadNetModuleORCADPCB */
/* Structures locales */
class MODULEtoLOAD : public EDA_BaseStruct
{
public:
wxString m_LibName;
wxString m_CmpName;
public:
MODULEtoLOAD(const wxString & libname, const wxString & cmpname, int timestamp);
~MODULEtoLOAD(void){};
MODULEtoLOAD * Next(void) { return (MODULEtoLOAD *) Pnext; }
};
/* Fonctions locales : */
static void SortListModulesToLoadByLibname(int NbModules);
/* Variables locales */
static int s_NbNewModules;
static MODULEtoLOAD * s_ModuleToLoad_List;
FILE * source;
static bool ChangeExistantModule;
static bool DisplayWarning = TRUE;
static int DisplayWarningCount ;
/*****************************/
/* class WinEDA_NetlistFrame */
/*****************************/
enum id_netlist_functions
{
ID_READ_NETLIST_FILE = 1900,
ID_TEST_NETLIST,
ID_CLOSE_NETLIST,
ID_COMPILE_RATSNEST,
ID_OPEN_NELIST
};
class WinEDA_NetlistFrame: public wxDialog
{
private:
WinEDA_PcbFrame * m_Parent;
wxDC * m_DC;
wxRadioBox * m_Select_By_Timestamp;
wxRadioBox * m_DeleteBadTracks;
wxRadioBox * m_ChangeExistantModuleCtrl;
wxCheckBox * m_DisplayWarningCtrl;
wxTextCtrl * m_MessageWindow;
public:
// Constructor and destructor
WinEDA_NetlistFrame(WinEDA_PcbFrame *parent, wxDC * DC, const wxPoint & pos);
~WinEDA_NetlistFrame(void)
{
}
private:
void OnQuit(wxCommandEvent& event);
void ReadPcbNetlist(wxCommandEvent& event);
void Set_NetlisteName(wxCommandEvent& event);
bool OpenNetlistFile(wxCommandEvent& event);
int BuildListeNetModules(wxCommandEvent& event, char * BufName);
void ModulesControle(wxCommandEvent& event);
void RecompileRatsnest(wxCommandEvent& event);
int ReadListeModules(const char * RefCmp, int TimeStamp, char * NameModule);
int SetPadNetName( char * Line, MODULE * Module);
MODULE * ReadNetModule( char * Text,
int * UseFichCmp, int TstOnly);
void AddToList(const char * NameLibCmp, const char * NameCmp,int TimeStamp );
void LoadListeModules(wxDC *DC);
DECLARE_EVENT_TABLE()
};
BEGIN_EVENT_TABLE(WinEDA_NetlistFrame, wxDialog)
EVT_BUTTON(ID_READ_NETLIST_FILE, WinEDA_NetlistFrame::ReadPcbNetlist)
EVT_BUTTON(ID_CLOSE_NETLIST, WinEDA_NetlistFrame::OnQuit)
EVT_BUTTON(ID_OPEN_NELIST, WinEDA_NetlistFrame::Set_NetlisteName)
EVT_BUTTON(ID_TEST_NETLIST, WinEDA_NetlistFrame::ModulesControle)
EVT_BUTTON(ID_COMPILE_RATSNEST, WinEDA_NetlistFrame::RecompileRatsnest)
END_EVENT_TABLE()
/*************************************************************************/
void WinEDA_PcbFrame::InstallNetlistFrame( wxDC * DC, const wxPoint & pos)
/*************************************************************************/
{
WinEDA_NetlistFrame * frame = new WinEDA_NetlistFrame(this, DC, pos);
frame->ShowModal(); frame->Destroy();
}
/******************************************************************/
WinEDA_NetlistFrame::WinEDA_NetlistFrame(WinEDA_PcbFrame *parent,
wxDC * DC, const wxPoint & framepos):
wxDialog(parent, -1, "", framepos, wxSize(-1, -1),
DIALOG_STYLE)
/******************************************************************/
{
wxPoint pos;
wxString number;
wxString title;
wxButton * Button;
m_Parent = parent;
SetFont(*g_DialogFont);
m_DC = DC;
Centre();
/* Mise a jour du Nom du fichier NETLISTE correspondant */
NetNameBuffer = m_Parent->m_CurrentScreen->m_FileName;
ChangeFileNameExt(NetNameBuffer, NetExtBuffer);
title = _("Netlist: ") + NetNameBuffer;
SetTitle(title);
/* Creation des boutons de commande */
pos.x = 170; pos.y = 10;
Button = new wxButton(this, ID_OPEN_NELIST,
_("Select"), pos);
Button->SetForegroundColour(*wxRED);
pos.y += Button->GetDefaultSize().y + 10;
Button = new wxButton(this, ID_READ_NETLIST_FILE,
_("Read"), pos);
Button->SetForegroundColour(wxColor(0,80,0) );
pos.y += Button->GetDefaultSize().y + 10;
Button = new wxButton(this, ID_TEST_NETLIST,
_("Module Test"), pos);
Button->SetForegroundColour(wxColor(0,80,80) );
pos.y += Button->GetDefaultSize().y + 10;
Button = new wxButton(this, ID_COMPILE_RATSNEST,
_("Compile"), pos);
Button->SetForegroundColour(wxColor(0,0,80) );
pos.y += Button->GetDefaultSize().y + 10;
Button = new wxButton(this, ID_CLOSE_NETLIST,
_("Close"), pos);
Button->SetForegroundColour(*wxBLUE);
// Options:
wxString opt_select[2] = { _("Reference"), _("Timestamp") };
pos.x = 15; pos.y = 10;
m_Select_By_Timestamp = new wxRadioBox( this, -1, _("Module Selection:"),
pos, wxDefaultSize, 2, opt_select, 1);
wxString track_select[2] = { _("Keep"), _("Delete") };
int x, y;
m_Select_By_Timestamp->GetSize(&x, &y);
pos.y += 5 + y;
m_DeleteBadTracks = new wxRadioBox(this, -1, _("Bad Tracks Deletion:"),
pos, wxDefaultSize, 2, track_select, 1);
m_DeleteBadTracks->GetSize(&x, &y);
pos.y += 5 + y;
wxString change_module_select[2] = { _("Keep"), _("Change") };
m_ChangeExistantModuleCtrl = new wxRadioBox(this, -1, _("Exchange Module:"),
pos, wxDefaultSize, 2, change_module_select, 1);
m_ChangeExistantModuleCtrl->GetSize(&x, &y);
pos.y += 15 + y;
m_DisplayWarningCtrl = new wxCheckBox(this, -1, _("Display Warnings"), pos);
m_DisplayWarningCtrl->SetValue(DisplayWarning);
m_DisplayWarningCtrl->GetSize(&x, &y);
pos.x = 5; pos.y += 10 + y;
m_MessageWindow = new wxTextCtrl(this, -1, "",
pos, wxSize(265, 120),wxTE_READONLY|wxTE_MULTILINE);
m_MessageWindow->GetSize(&x, &y);
pos.y += 10 + y;
SetClientSize(280, pos.y);
}
/**********************************************************************/
void WinEDA_NetlistFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
/**********************************************************************/
{
// true is to force the frame to close
Close(true);
}
/*****************************************************************/
void WinEDA_NetlistFrame::RecompileRatsnest(wxCommandEvent& event)
/*****************************************************************/
{
m_Parent->Compile_Ratsnest(m_DC, TRUE);
}
/***************************************************************/
bool WinEDA_NetlistFrame::OpenNetlistFile(wxCommandEvent& event)
/***************************************************************/
/*
routine de selection et d'ouverture du fichier Netlist
*/
{
wxString FullFileName;
wxString msg;
if( NetNameBuffer == "" ) /* Pas de nom specifie */
Set_NetlisteName(event);
if( NetNameBuffer == "" ) return(FALSE); /* toujours Pas de nom specifie */
FullFileName = NetNameBuffer;
source = fopen(FullFileName.GetData(),"rt");
if (source == 0)
{
msg.Printf(_("Netlist file %s not found"),FullFileName.GetData()) ;
DisplayError(this, msg) ;
return FALSE ;
}
msg.Printf("Netlist %s",FullFileName.GetData());
SetTitle(msg);
return TRUE;
}
/**************************************************************/
void WinEDA_NetlistFrame::ReadPcbNetlist(wxCommandEvent& event)
/**************************************************************/
/* mise a jour des empreintes :
corrige les Net Names, les textes, les "TIME STAMP"
Analyse les lignes:
# EESchema Netlist Version 1.0 generee le 18/5/2005-12:30:22
(
( 40C08647 $noname R20 4,7K {Lib=R}
( 1 VCC )
( 2 MODB_1 )
)
( 40C0863F $noname R18 4,7_k {Lib=R}
( 1 VCC )
( 2 MODA_1 )
)
}
#End
*/
{
int LineNum, State, Comment;
MODULE * Module = NULL;
D_PAD * PtPad;
char Line[256], *Text;
int UseFichCmp = 1;
wxString msg;
ChangeExistantModule = m_ChangeExistantModuleCtrl->GetSelection() == 1 ? TRUE : FALSE;
DisplayWarning = m_DisplayWarningCtrl->GetValue();
if ( DisplayWarning ) DisplayWarningCount = 8;
else DisplayWarningCount = 0;
if( ! OpenNetlistFile(event) ) return;
msg = _("Read Netlist ") + NetNameBuffer;
m_MessageWindow->AppendText(msg);
m_Parent->m_CurrentScreen->SetModify();
m_Parent->m_Pcb->m_Status_Pcb = 0 ; State = 0; LineNum = 0; Comment = 0;
s_NbNewModules = 0;
/* Premiere lecture de la netliste: etablissement de la liste
des modules a charger
*/
while( GetLine( source, Line, &LineNum) )
{
Text = StrPurge(Line);
if ( Comment ) /* Commentaires en cours */
{
if( (Text = strchr(Text,'}') ) == NULL )continue;
Comment = 0;
}
if ( *Text == '{' ) /* Commentaires */
{
Comment = 1;
if( (Text = strchr(Text,'}') ) == NULL ) continue;
}
if ( *Text == '(' ) State++;
if ( *Text == ')' ) State--;
if( State == 2 )
{
Module = ReadNetModule(Text, & UseFichCmp, TESTONLY);
continue;
}
if( State >= 3 ) /* la ligne de description d'un pad est ici non analysee */
{
State--;
}
}
/* Chargement des nouveaux modules */
if( s_NbNewModules )
{
LoadListeModules(m_DC);
// Free module list:
MODULEtoLOAD * item, *next_item;
for ( item = s_ModuleToLoad_List; item != NULL; item = next_item )
{
next_item = item->Next();
delete item;
}
s_ModuleToLoad_List = NULL;
}
/* Relecture de la netliste, tous les modules sont ici charges */
fseek(source, 0, SEEK_SET); LineNum = 0;
while( GetLine( source, Line, &LineNum) )
{
Text = StrPurge(Line);
if ( Comment ) /* Commentaires en cours */
{
if( (Text = strchr(Text,'}') ) == NULL )continue;
Comment = 0;
}
if ( *Text == '{' ) /* Commentaires */
{
Comment = 1;
if( (Text = strchr(Text,'}') ) == NULL ) continue;
}
if ( *Text == '(' ) State++;
if ( *Text == ')' ) State--;
if( State == 2 )
{
Module = ReadNetModule(Text, & UseFichCmp, READMODULE );
if( Module == NULL )
{ /* empreinte non trouvee dans la netliste */
continue ;
}
else /* Raz netnames sur pads */
{
PtPad = Module->m_Pads;
for( ; PtPad != NULL; PtPad = (D_PAD *)PtPad->Pnext )
{
PtPad->m_Netname = "";
}
}
continue;
}
if( State >= 3 )
{
if ( Module )
{
SetPadNetName( Text, Module);
}
State--;
}
}
fclose(source);
/* Mise a jour et Cleanup du circuit imprime: */
m_Parent->Compile_Ratsnest(m_DC, TRUE);
if( m_Parent->m_Pcb->m_Track )
{
if( m_DeleteBadTracks->GetSelection() == 1 )
{
wxBeginBusyCursor();;
Netliste_Controle_piste(m_Parent, m_DC, TRUE);
m_Parent->Compile_Ratsnest(m_DC, TRUE);
wxEndBusyCursor();;
}
}
Affiche_Infos_Status_Pcb(m_Parent);
}
/****************************************************************************/
MODULE * WinEDA_NetlistFrame::ReadNetModule(char * Text, int * UseFichCmp,
int TstOnly)
/****************************************************************************/
/* charge la description d'une empreinte ,netliste type PCBNEW
et met a jour le module correspondant
Si TstOnly == 0 si le module n'existe pas, il est charge
Si TstOnly != 0 si le module n'existe pas, il est ajoute a la liste des
modules a charger
Text contient la premiere ligne de la description
* UseFichCmp est un flag
si != 0, le fichier des composants .CMP sera utilise
est remis a 0 si le fichier n'existe pas
Analyse les lignes type:
( 40C08647 $noname R20 4,7K {Lib=R}
( 1 VCC )
( 2 MODB_1 )
*/
{
MODULE * Module;
char *TextTimeStamp;
char *TextNameLibMod;
char *TextValeur;
char *TextCmpName;
int TimeStamp = -1, Error = 0;
char Line[1024], NameLibCmp[256];
bool Found;
strcpy(Line,Text);
if( (TextTimeStamp = strtok(Line, " ()\t\n")) == NULL ) Error = 1;
if( (TextNameLibMod = strtok(NULL, " ()\t\n")) == NULL ) Error = 1;
if( (TextCmpName = strtok(NULL, " ()\t\n")) == NULL ) Error = 1;
if( (TextValeur = strtok(NULL, " ()\t\n")) == NULL ) Error = 1;
if( Error ) return( NULL );
sscanf(TextTimeStamp,"%X", &TimeStamp);
/* Tst si composant deja charge */
Module = (MODULE*) m_Parent->m_Pcb->m_Modules;
MODULE * NextModule;
for( Found = FALSE; Module != NULL; Module = NextModule )
{
NextModule = (MODULE*)Module->Pnext;
if( m_Select_By_Timestamp->GetSelection() == 1 ) /* Reconnaissance par signature temporelle */
{
if( TimeStamp == Module->m_TimeStamp) Found = TRUE;
}
else /* Reconnaissance par Reference */
{
if( stricmp(TextCmpName,Module->m_Reference->GetText()) == 0 )
Found = TRUE;
}
if ( Found ) // Test si module (m_LibRef) et module specifie en netlist concordent
{
if( TstOnly != TESTONLY )
{
strcpy(NameLibCmp, TextNameLibMod);
if( *UseFichCmp )
{
if( m_Select_By_Timestamp->GetSelection() == 1 )
{ /* Reconnaissance par signature temporelle */
*UseFichCmp = ReadListeModules(NULL, TimeStamp, NameLibCmp);
}
else /* Reconnaissance par Reference */
{
*UseFichCmp = ReadListeModules(TextCmpName, 0, NameLibCmp);
}
}
if ( stricmp(Module->m_LibRef.GetData(), NameLibCmp) != 0 )
{// Module Mismatch: Current module and module specified in netlist are diff.
if ( ChangeExistantModule )
{
MODULE * NewModule =
m_Parent->Get_Librairie_Module(this, "", NameLibCmp, TRUE);
if( NewModule ) /* Nouveau module trouve : changement de module */
Module = m_Parent->Exchange_Module(this, Module, NewModule);
}
else
{
wxString msg;
msg.Printf(
_("Cmp %s: Mismatch! module is [%s] and netlist said [%s]\n"),
TextCmpName, Module->m_LibRef.GetData(), NameLibCmp);
m_MessageWindow->AppendText(msg);
if ( DisplayWarningCount > 0)
{
DisplayError(this, msg, 2);
DisplayWarningCount--;
}
}
}
}
break;
}
}
if( Module == NULL ) /* Module a charger */
{
strcpy(NameLibCmp, TextNameLibMod);
if( *UseFichCmp )
{
if( m_Select_By_Timestamp->GetSelection() == 1)
{ /* Reconnaissance par signature temporelle */
*UseFichCmp = ReadListeModules(NULL, TimeStamp, NameLibCmp);
}
else /* Reconnaissance par Reference */
{
*UseFichCmp = ReadListeModules(TextCmpName, 0, NameLibCmp);
}
}
if( TstOnly == TESTONLY)
AddToList(NameLibCmp, TextCmpName, TimeStamp);
else
{
wxString msg;
msg.Printf(_("Componant [%s] not found"), TextCmpName);
m_MessageWindow->AppendText(msg+"\n");
if (DisplayWarningCount> 0)
{
DisplayError(this, msg, 2);
DisplayWarningCount--;
}
}
return(NULL); /* Le module n'avait pas pu etre charge */
}
/* mise a jour des reperes ( nom et ref "Time Stamp") si module charge */
Module->m_Reference->m_Text = TextCmpName;
Module->m_Value->m_Text = TextValeur;
Module->m_TimeStamp = TimeStamp;
return(Module) ; /* composant trouve */
}
/********************************************************************/
int WinEDA_NetlistFrame::SetPadNetName( char * Text, MODULE * Module)
/********************************************************************/
/*
Met a jour le netname de 1 pastille, Netliste ORCADPCB
entree :
Text = ligne de netliste lue ( (pad = net) )
Module = adresse de la structure MODULE a qui appartient les pads
*/
{
D_PAD * pad;
char * TextPinName, * TextNetName;
int Error = 0;
bool trouve;
char Line[256], Msg[80];
if( Module == NULL ) return ( 0 );
strcpy( Line, Text);
if( (TextPinName = strtok(Line, " ()\t\n")) == NULL ) Error = 1;
if( (TextNetName = strtok(NULL, " ()\t\n")) == NULL ) Error = 1;
if(Error) return(0);
/* recherche du pad */
pad = Module->m_Pads; trouve = FALSE;
for( ; pad != NULL; pad = (D_PAD *)pad->Pnext )
{
if( strnicmp( TextPinName, pad->m_Padname, 4) == 0 )
{ /* trouve */
trouve = TRUE;
if( *TextNetName != '?' ) pad->m_Netname = TextNetName;
else pad->m_Netname = "";
}
}
if( !trouve && (DisplayWarningCount > 0) )
{
sprintf(Msg,_("Module [%s]: Pad [%s] not found"),
Module->m_Reference->GetText(), TextPinName);
DisplayError(this, Msg, 1);
DisplayWarningCount--;
}
return(trouve);
}
/*****************************************************/
MODULE * WinEDA_PcbFrame::ListAndSelectModuleName(void)
/*****************************************************/
/* liste les noms des modules du PCB
Retourne:
un pointeur sur le module selectionne
NULL si pas de selection
*/
{
int ii, jj, nb_empr;
MODULE * Module;
WinEDAListBox * ListBox;
const char ** ListNames = NULL;
if( m_Pcb->m_Modules == NULL )
{
DisplayError(this, _("No Modules") ) ; return(0);
}
/* Calcul du nombre des modules */
nb_empr = 0; Module = (MODULE*)m_Pcb->m_Modules;
for( ;Module != NULL; Module = (MODULE*)Module->Pnext) nb_empr++;
ListNames = (const char**) MyZMalloc( (nb_empr + 1) * sizeof(char*) );
Module = (MODULE*) m_Pcb->m_Modules;
for( ii = 0; Module != NULL; Module = (MODULE*)Module->Pnext, ii++)
{
ListNames[ii] = Module->m_Reference->GetText();
}
ListBox = new WinEDAListBox(this, _("Componants"),
ListNames, "");
ii = ListBox->ShowModal(); ListBox->Destroy();
if( ii < 0 ) /* Pas de selection */
{
Module = NULL;
}
else /* Recherche du module selectionne */
{
Module = (MODULE*) m_Pcb->m_Modules;
for( jj = 0; Module != NULL; Module = (MODULE*)Module->Pnext, jj++)
{
if( Module->m_Reference->GetText() == ListNames[ii] ) break;
}
}
free(ListNames);
return(Module);
}
/***************************************************************/
void WinEDA_NetlistFrame::ModulesControle(wxCommandEvent& event)
/***************************************************************/
/* donne la liste :
1 - des empreintes doublées sur le PCB
2 - des empreintes manquantes par rapport a la netliste
3 - des empreintes supplémentaires par rapport a la netliste
*/
#define MAX_LEN_TXT 32
{
int ii, NbModulesPcb;
MODULE * Module, * pt_aux;
int NbModulesNetListe ,nberr = 0 ;
char *ListeNetModules, * NameNetMod;
WinEDA_TextFrame * List;
/* determination du nombre des modules du PCB*/
NbModulesPcb = 0; Module = (MODULE*) m_Parent->m_Pcb->m_Modules;
for( ;Module != NULL; Module = (MODULE*)Module->Pnext)
{
NbModulesPcb++;
}
if( NbModulesPcb == 0 )
{
DisplayError(this, _("No modules"), 10); return;
}
/* Construction de la liste des references des modules de la netliste */
NbModulesNetListe = BuildListeNetModules(event, NULL);
if( NbModulesNetListe < 0 ) return; /* fichier non trouve */
if( NbModulesNetListe == 0 )
{
DisplayError(this, _("No modules in NetList"), 10); return;
}
ii = NbModulesNetListe * (MAX_LEN_TXT + 1);
ListeNetModules = (char*)MyZMalloc ( ii );
if( NbModulesNetListe ) BuildListeNetModules(event, ListeNetModules);
List = new WinEDA_TextFrame(this, _("Check Modules"));
/* recherche des doubles */
List->Append(_("Duplicates"));
Module = (MODULE*) m_Parent->m_Pcb->m_Modules;
for( ;Module != NULL; Module = (MODULE*)Module->Pnext)
{
pt_aux = (MODULE*)Module->Pnext;
for( ; pt_aux != NULL; pt_aux = (MODULE*)pt_aux->Pnext)
{
if( strnicmp(Module->m_Reference->GetText(),
pt_aux->m_Reference->GetText(),MAX_LEN_TXT) == 0 )
{
List->Append(Module->m_Reference->GetText());
nberr++ ;
break;
}
}
}
/* recherche des manquants par rapport a la netliste*/
List->Append(_("Lack:") );
NameNetMod = ListeNetModules;
for ( ii = 0 ; ii < NbModulesNetListe ; ii++, NameNetMod += MAX_LEN_TXT+1 )
{
Module = (MODULE*) m_Parent->m_Pcb->m_Modules;
for( ;Module != NULL; Module = (MODULE*)Module->Pnext)
{
if( strnicmp(Module->m_Reference->GetText(), NameNetMod, MAX_LEN_TXT)
== 0 )
{
break;
}
}
if( Module == NULL )
{
List->Append(NameNetMod);
nberr++ ;
}
}
/* recherche des modules supplementaires (i.e. Non en Netliste) */
List->Append(_("Not in Netlist:") );
Module = (MODULE*) m_Parent->m_Pcb->m_Modules;
for( ;Module != NULL; Module = Module->Next())
{
NameNetMod = ListeNetModules;
for (ii = 0; ii < NbModulesNetListe ; ii++, NameNetMod += MAX_LEN_TXT+1 )
{
if( strnicmp(Module->m_Reference->GetText(), NameNetMod, MAX_LEN_TXT)
== 0 )
{
break ;/* Module trouve en netliste */
}
}
if( ii == NbModulesNetListe ) /* Module en trop */
{
List->Append(Module->m_Reference->GetText());
nberr++ ;
}
}
sprintf(cbuf, _("%d Errors"), nberr);
List->ShowModal(); List->Destroy();
MyFree(ListeNetModules);
}
/***********************************************************************************/
int WinEDA_NetlistFrame::BuildListeNetModules(wxCommandEvent& event, char * BufName)
/***********************************************************************************/
/*
charge en BufName la liste des noms des modules de la netliste,
( chaque nom est en longueur fixe, sizeof(pt_texte_ref->name) + code 0 )
retourne le nombre des modules cités dans la netliste
Si BufName == NULL: determination du nombre des Module uniquement
*/
{
int textlen;
int nb_modules_lus ;
int State, LineNum, Comment;
char Line[256], *Text, * LibModName;
if( ! OpenNetlistFile(event) ) return -1;
State = 0; LineNum = 0; Comment = 0;
nb_modules_lus = 0;
textlen = MAX_LEN_TXT;
while( GetLine( source, Line, &LineNum) )
{
Text = StrPurge(Line);
if ( Comment ) /* Commentaires en cours */
{
if( (Text = strchr(Text,'}') ) == NULL )continue;
Comment = 0;
}
if ( *Text == '{' ) /* Commentaires */
{
Comment = 1;
if( (Text = strchr(Text,'}') ) == NULL ) continue;
}
if ( *Text == '(' ) State++;
if ( *Text == ')' ) State--;
if( State == 2 )
{
int Error = 0;
if( strtok(Line, " ()\t\n") == NULL ) Error = 1; /* TimeStamp */
if( ( LibModName = strtok(NULL, " ()\t\n")) == NULL ) Error = 1; /* nom Lib */
/* Lecture du nom (reference) du composant: */
if( (Text = strtok(NULL, " ()\t\n")) == NULL ) Error = 1;
nb_modules_lus++;
if( BufName )
{
strncpy( BufName, Text, textlen ); BufName[textlen] = 0;
BufName += textlen+1;
}
continue;
}
if( State >= 3 )
{
State--; /* Lecture 1 ligne relative au Pad */
}
}
fclose(source);
return(nb_modules_lus);
}
/*****************************************************************************************/
int WinEDA_NetlistFrame::ReadListeModules(const char * RefCmp, int TimeStamp, char * NameModule)
/*****************************************************************************************/
/*
Lit le fichier .CMP donnant l'equivalence Modules / Composants
Retourne:
Si ce fichier existe:
1 et le nom module dans NameModule
-1 si module non trouve en fichier
sinon 0;
parametres d'appel:
RefCmp (NULL si selection par TimeStamp)
TimeStamp (signature temporelle si elle existe, NULL sinon)
pointeur sur le buffer recevant le nom du module
Exemple de fichier:
Cmp-Mod V01 Genere par PcbNew le 29/10/2003-13:11:6
BeginCmp
TimeStamp = 322D3011;
Reference = BUS1;
ValeurCmp = BUSPC;
IdModule = BUS_PC;
EndCmp
BeginCmp
TimeStamp = 32307DE2;
Reference = C1;
ValeurCmp = 47uF;
IdModule = CP6;
EndCmp
*/
{
wxString CmpFullFileName;
char refcurrcmp[512], idmod[512], ia[1024];
int timestamp;
char *ptcar;
FILE * FichCmp;
if( (RefCmp == NULL) && (TimeStamp == 0) ) return(0);
CmpFullFileName = NetNameBuffer;
ChangeFileNameExt(CmpFullFileName,NetCmpExtBuffer) ;
FichCmp = fopen(CmpFullFileName.GetData(),"rt");
if (FichCmp == NULL)
{
wxString msg;
msg.Printf( _("File <%s> not found, use Netlist for lib module selection"),
CmpFullFileName.GetData()) ;
DisplayError(this, cbuf, 20) ;
return(0);
}
while( fgets(ia,sizeof(ia),FichCmp) != NULL )
{
if( strnicmp(ia,"BeginCmp",8) != 0 ) continue;
/* Ici une description de 1 composant commence */
*refcurrcmp = *idmod = 0;
timestamp = -1;
while( fgets(ia,sizeof(ia),FichCmp) != NULL )
{
if( strnicmp(ia,"EndCmp",6) == 0 ) break;
if( strnicmp(ia,"Reference =",11) == 0 )
{
ptcar = ia+11;
ptcar = strtok(ptcar," =;\t\n");
if( ptcar ) strcpy(refcurrcmp,ptcar);
continue;
}
if( strnicmp(ia,"IdModule =",11) == 0 )
{
ptcar = ia+11;
ptcar = strtok(ptcar," =;\t\n");
if( ptcar ) strcpy(idmod,ptcar);
continue;
}
if( strnicmp(ia,"TimeStamp =",11) == 0 )
{
ptcar = ia+11;
ptcar = strtok(ptcar," =;\t\n");
if( ptcar ) sscanf(ptcar, "%X", ×tamp);
}
}/* Fin lecture 1 descr composant */
/* Test du Composant lu en fichier: est-il le bon */
if( RefCmp )
{
if( stricmp(RefCmp, refcurrcmp) == 0 )
{
fclose(FichCmp);
strcpy(NameModule, idmod);
return(1);
}
}
else if( TimeStamp != -1 )
{
if( TimeStamp == timestamp )
{
fclose(FichCmp);
strcpy(NameModule, idmod);
return(1);
}
}
}
fclose(FichCmp);
return(-1);
}
/***************************************************************/
void WinEDA_NetlistFrame::Set_NetlisteName(wxCommandEvent& event)
/***************************************************************/
/* Selection un nouveau nom de netliste
Affiche la liste des fichiers netlistes pour selection sur liste
*/
{
wxString fullfilename, mask("*");
mask += NetExtBuffer;
fullfilename = EDA_FileSelector( _("Netlist Selection:"),
"", /* Chemin par defaut */
NetNameBuffer, /* nom fichier par defaut */
NetExtBuffer, /* extension par defaut */
mask, /* Masque d'affichage */
this,
0,
TRUE
);
if ( fullfilename == "" ) return;
NetNameBuffer = fullfilename;
SetTitle(fullfilename);
}
/***********************************************************************************/
void WinEDA_NetlistFrame::AddToList(const char * NameLibCmp, const char * CmpName,int TimeStamp )
/************************************************************************************/
/* Fontion copiant en memoire de travail les caracteristiques
des nouveaux modules
*/
{
MODULEtoLOAD * NewMod;
NewMod = new MODULEtoLOAD(NameLibCmp, CmpName, TimeStamp);
NewMod->Pnext = s_ModuleToLoad_List;
s_ModuleToLoad_List = NewMod;
s_NbNewModules++;
}
/***************************************************************/
void WinEDA_NetlistFrame::LoadListeModules(wxDC * DC)
/***************************************************************/
/* Routine de chargement des nouveaux modules en une seule lecture des
librairies
Si un module vient d'etre charge il est duplique, ce qui evite une lecture
inutile de la librairie
*/
{
MODULEtoLOAD * ref, *cmp;
int ii;
MODULE * Module = NULL;
wxPoint OldPos = m_Parent->m_CurrentScreen->m_Curseur;
if( s_NbNewModules == 0 ) return;
SortListModulesToLoadByLibname(s_NbNewModules);
ref = cmp = s_ModuleToLoad_List;
// Calcul de la coordonnée de placement des modules:
if ( m_Parent->SetBoardBoundaryBoxFromEdgesOnly() )
{
m_Parent->m_CurrentScreen->m_Curseur.x = m_Parent->m_Pcb->m_BoundaryBox.GetRight() + 5000;
m_Parent->m_CurrentScreen->m_Curseur.y = m_Parent->m_Pcb->m_BoundaryBox.GetBottom() + 10000;
}
else
{
m_Parent->m_CurrentScreen->m_Curseur = wxPoint(0,0);
}
for( ii = 0; ii < s_NbNewModules; ii++, cmp = cmp->Next() )
{
if( (ii == 0) || ( ref->m_LibName != cmp->m_LibName) )
{ /* Nouveau Module a charger */
Module = m_Parent->Get_Librairie_Module(this, "", cmp->m_LibName, TRUE );
ref = cmp;
if ( Module == NULL ) continue;
m_Parent->Place_Module(Module, DC);
/* mise a jour des reperes ( nom et ref "Time Stamp")
si module charge */
Module->m_Reference->m_Text = cmp->m_CmpName;
Module->m_TimeStamp = cmp->m_TimeStamp;
}
else
{ /* module deja charge, on peut le dupliquer */
MODULE * newmodule;
if ( Module == NULL ) continue; /* module non existant en libr */
newmodule = new MODULE(m_Parent->m_Pcb);
newmodule->Copy(Module);
newmodule->AddToChain(Module);
Module = newmodule;
Module->m_Reference->m_Text = cmp->m_CmpName;
Module->m_TimeStamp = cmp->m_TimeStamp;
}
}
m_Parent->m_CurrentScreen->m_Curseur = OldPos;
}
/* Routine utilisee par qsort pour le tri des modules a charger
*/
static int SortByLibName( MODULEtoLOAD ** ref, MODULEtoLOAD ** cmp )
{
return (strcmp( (*ref)->m_LibName.GetData(), (*cmp)->m_LibName.GetData() ) );
}
/*************************************************/
void SortListModulesToLoadByLibname(int NbModules)
/**************************************************/
/* Rearrage la liste des modules List par ordre alphabetique des noms lib des modules
*/
{
MODULEtoLOAD ** base_list, * item;
int ii;
base_list = (MODULEtoLOAD **) MyMalloc( NbModules * sizeof(MODULEtoLOAD *) );
for ( ii = 0, item = s_ModuleToLoad_List; ii < NbModules; ii++ )
{
base_list[ii] = item;
item = item->Next();
}
qsort( base_list, NbModules, sizeof(MODULEtoLOAD*),
(int(*)(const void *, const void *) )SortByLibName);
// Reconstruction du chainage:
s_ModuleToLoad_List = *base_list;
for ( ii = 0; ii < NbModules-1; ii++ )
{
item = base_list[ii];
item->Pnext = base_list[ii + 1];
}
// Dernier item: Pnext = NULL:
item = base_list[ii];
item->Pnext = NULL;
free(base_list);
}
/*****************************************************************************/
MODULEtoLOAD::MODULEtoLOAD(const wxString & libname, const wxString & cmpname,
int timestamp) : EDA_BaseStruct(TYPE_NOT_INIT)
/*****************************************************************************/
{
m_LibName = libname;
m_CmpName = cmpname;
m_TimeStamp = timestamp;
}
| [
"bokeoa@244deca0-f506-0410-ab94-f4f3571dea26"
] | [
[
[
1,
1103
]
]
] |
b755dcb847a8df33e9ccf667971f8800ae0df6c8 | 57574cc7192ea8564bd630dbc2a1f1c4806e4e69 | /Poker/Servidor/ContextoJuego.cpp | 8d18e4e88ca733d3f2587520c1721fcedcb952bb | [] | no_license | natlehmann/taller-2010-2c-poker | 3c6821faacccd5afa526b36026b2b153a2e471f9 | d07384873b3705d1cd37448a65b04b4105060f19 | refs/heads/master | 2016-09-05 23:43:54 | 2010-11-17 11:48:00 | 2010-11-17 11:48:00 | 32,321,142 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,119 | cpp | #include "ContextoJuego.h"
#include "PokerException.h"
#include "Repartidor.h"
#include "Jugada.h"
#include "RecursosServidor.h"
#include "UtilTiposDatos.h"
#include "IteradorRonda.h"
#include "IteradorRondaActivos.h"
#include "AccesoDatos.h"
ContextoJuego* ContextoJuego::instancia = NULL;
int ContextoJuego::segsTimeoutJugadores = UtilTiposDatos::getEntero(
RecursosServidor::getConfig()->get("servidor.logica.timeout.jugadorInactivo"));
ContextoJuego::ContextoJuego(void)
{
this->mutex = CreateMutexA(NULL, false, "MutexContexto");
this->admJugadores = new AdministradorJugadores();
this->mesa = new MesaModelo(10,
UtilTiposDatos::getEntero(
RecursosServidor::getConfig()->get("servidor.mesa.smallBlind")),
RecursosServidor::getConfig()->get("servidor.mesa.fondo"));
this->mesa->setApuestaMaxima(UtilTiposDatos::getEntero(
RecursosServidor::getConfig()->get("servidor.mesa.apuestaMaxima")));
this->bote = new BoteModelo(11);
this->mensaje = new MensajeModelo(12);
this->cartasComunitarias = new CartasComunitariasModelo(13);
this->montoAIgualar = 0;
this->cantidadJugadoresRonda = 0;
this->repartidor = new Repartidor();
this->rondaTerminada = false;
this->mostrandoCartas = false;
this->sePuedePasar = false;
this->rondaAllIn = false;
this->esperandoJugadores = new EstadoEsperandoJugadores();
this->evaluandoGanador = new EstadoEvaluandoGanador();
this->rondaRiver = new EstadoRondaRiver(this->evaluandoGanador);
this->rondaTurn = new EstadoRondaTurn(this->rondaRiver);
this->rondaFlop = new EstadoRondaFlop(this->rondaTurn);
this->rondaCiega = new EstadoRondaCiega(this->rondaFlop);
this->esperandoJugadores->setEstadoRondaCiega(this->rondaCiega);
this->evaluandoGanador->setEstadoRondaCiega(this->rondaCiega);
this->evaluandoGanador->setEstadoEsperandoJugadores(this->esperandoJugadores);
this->estado = this->esperandoJugadores;
this->timerEsperandoJugadores.iniciar();
}
ContextoJuego::~ContextoJuego(void)
{
//if (instancia) {
// delete instancia;
// instancia = NULL;
//}
}
void ContextoJuego::finalizar() {
if(this->admJugadores != NULL) {
delete (this->admJugadores);
this->admJugadores = NULL;
}
if (this->mesa) {
delete this->mesa;
this->mesa = NULL;
}
if (this->bote) {
delete this->bote;
this->bote = NULL;
}
if (this->mensaje) {
delete this->mensaje;
this->mensaje = NULL;
}
if (this->cartasComunitarias) {
delete this->cartasComunitarias;
this->cartasComunitarias = NULL;
}
if (this->repartidor) {
delete this->repartidor;
this->repartidor = NULL;
}
delete(this->esperandoJugadores);
delete(this->rondaCiega);
delete(this->rondaFlop);
delete(this->rondaTurn);
delete(this->rondaRiver);
delete(this->evaluandoGanador);
CloseHandle(this->mutex);
}
HANDLE ContextoJuego::getMutex(){
return this->mutex;
}
ContextoJuego* ContextoJuego::getInstancia(){
if (instancia == NULL) {
instancia = new ContextoJuego();
}
return instancia;
}
int ContextoJuego::getTiempoEsperandoJugadores(){
return this->timerEsperandoJugadores.getSegundos();
}
void ContextoJuego::resetTimerEsperandoJugadores(){
this->timerEsperandoJugadores.iniciar();
}
bool ContextoJuego::isTiempoMostrandoGanadorCumplido() {
return (this->timerMostrandoGanador.getSegundos() >= UtilTiposDatos::getEntero(
RecursosServidor::getConfig()->get("servidor.logica.timeout.mostrandoGanador")));
}
MesaModelo* ContextoJuego::getMesa(){
return this->mesa;
}
BoteModelo* ContextoJuego::getBote() {
return this->bote;
}
MensajeModelo* ContextoJuego::getMensaje(){
return this->mensaje;
}
CartasComunitariasModelo* ContextoJuego::getCartasComunitarias(){
return this->cartasComunitarias;
}
int ContextoJuego::getCantidadJugadoresJugandoRonda(){
return this->cantidadJugadoresRonda;
}
void ContextoJuego::igualarApuesta(int idCliente)
{
JugadorModelo* jugador = this->admJugadores->getJugador(idCliente);
int montoApuesta = this->montoAIgualar - jugador->getApuesta();
if (jugador->getFichas() < montoApuesta) {
montoApuesta = jugador->getFichas();
}
jugador->apostar(montoApuesta);
this->bote->incrementar(montoApuesta);
this->admJugadores->incrementarTurno();
chequearRondaTerminada();
}
void ContextoJuego::pasar(int idCliente){
if (this->sePuedePasar) {
this->admJugadores->incrementarTurno();
chequearRondaTerminada();
} else {
throw PokerException("Se solicito 'pasar' cuando esta no era una jugada permitida.");
}
}
void ContextoJuego::subirApuesta(int idCliente, int fichas)
{
JugadorModelo* jugador = this->admJugadores->getJugador(idCliente);
jugador->apostar(fichas);
this->bote->incrementar(fichas);
this->montoAIgualar = jugador->getApuesta();
this->admJugadores->setJugadorQueCierra(jugador->getId());
this->admJugadores->incrementarTurno();
this->sePuedePasar = false;
chequearRondaTerminada();
}
bool ContextoJuego::puedeSubirApuesta(int idCliente, int fichas){
JugadorModelo* jugador = this->admJugadores->getJugador(idCliente);
return (fichas <= jugador->getFichas() && fichas <= this->mesa->getApuestaMaxima());
}
bool ContextoJuego::puedeSubirApuesta(int idJugador){
int idCliente = this->idJugadorToIdCliente(idJugador);
JugadorModelo* jugador = this->admJugadores->getJugador(idCliente);
if (jugador) {
return (jugador->getFichas() + jugador->getApuesta() > this->montoAIgualar);
} else {
return true;
}
}
bool ContextoJuego::esApuestaValida(int idCliente, int fichas){
JugadorModelo* jugador = this->admJugadores->getJugador(idCliente);
return ((jugador->getApuesta() + fichas) >= this->montoAIgualar);
}
void ContextoJuego::noIr(int idCliente)
{
JugadorModelo* jugador = this->admJugadores->getJugador(idCliente);
jugador->setApuesta(0);
jugador->setCarta1(NULL);
jugador->setCarta2(NULL);
this->cantidadJugadoresRonda--;
if (this->cantidadJugadoresRonda > 1) {
if (this->admJugadores->isDealerJugador(jugador->getId())) {
this->admJugadores->incrementarDealerTemp();
}
if (this->admJugadores->isJugadorQueCierra(jugador->getId())){
this->admJugadores->decrementarJugadorQueCierra();
}
this->admJugadores->incrementarTurno();
jugador->setJugandoRonda(false);
chequearRondaTerminada();
if (!this->rondaTerminada) {
chequearRondaAllIn();
}
} else {
jugador->setJugandoRonda(false);
this->finalizarRonda();
this->estado = this->evaluandoGanador;
}
}
void ContextoJuego::chequearRondaTerminada() {
if (this->cantidadJugadoresRonda > 1) {
this->rondaTerminada = this->admJugadores->isRondaTerminada();
} else {
this->rondaTerminada = false; // TODO: NO ES TRUE???
}
}
void ContextoJuego::chequearRondaAllIn() {
bool rondaAllIn = true;
int jugadoresNoAllIn = 0;
for (int i = 0; i < MAX_CANTIDAD_JUGADORES; i++) {
JugadorModelo* jugador = this->admJugadores->getJugadores()[i];
if (jugador->isJugandoRonda() && !jugador->isAllIn()) {
jugadoresNoAllIn++;
if (jugadoresNoAllIn > 1 || jugador->getApuesta() < this->montoAIgualar) {
rondaAllIn = false;
break;
}
}
}
this->rondaAllIn = rondaAllIn;
if (this->rondaAllIn) {
this->rondaTerminada = true;
}
}
bool ContextoJuego::isRondaTerminada(){
return this->rondaTerminada || this->rondaAllIn;
}
bool ContextoJuego::isRondaAllIn(){
return this->rondaAllIn;
}
void ContextoJuego::iniciarJuego() {
int cantidadJugadoresActivos = getCantidadJugadoresActivos();
if (cantidadJugadoresActivos < 2) {
throw PokerException("No hay suficientes jugadores para iniciar la ronda.");
}
this->cartasComunitarias->limpiar();
repartidor->mezclar();
this->bote->vaciar();
this->mostrandoCartas = false;
this->sePuedePasar = false;
for (int i = 0; i < MAX_CANTIDAD_JUGADORES; i++) {
if (this->admJugadores->getJugadores()[i]->isActivo()) {
this->admJugadores->getJugadores()[i]->setJugandoRonda(true);
}
this->admJugadores->getJugadores()[i]->setApuesta(0);
this->admJugadores->getJugadores()[i]->setDealer(false);
this->admJugadores->getJugadores()[i]->setAllIn(false);
}
this->admJugadores->resetearDealer();
this->admJugadores->incrementarDealer();
this->admJugadores->resetearJugadorTurno();
int blind = 1;
IteradorRondaActivos* it = this->admJugadores->getIteradorRondaActivos();
while (!it->esUltimo()) {
JugadorModelo* jugador = it->getSiguiente();
jugador->setCarta1(repartidor->getCarta());
jugador->setCarta2(repartidor->getCarta());
if (blind <= 2) {
if (cantidadJugadoresActivos == 2) {
if (blind == 1) {
jugador->apostar(mesa->getSmallBlind() * 2);
} else {
jugador->apostar(mesa->getSmallBlind());
}
} else {
jugador->apostar(mesa->getSmallBlind() * blind);
}
this->bote->incrementar(mesa->getSmallBlind() * blind);
this->admJugadores->incrementarTurno();
blind++;
}
}
if (cantidadJugadoresActivos == 2) {
this->admJugadores->incrementarTurno();
}
this->admJugadores->setJugadorQueCierraActual();
if (blind >= 2) {
blind--;
this->montoAIgualar = mesa->getSmallBlind() * blind;
}
this->cantidadJugadoresRonda = cantidadJugadoresActivos;
this->rondaTerminada = false;
this->rondaAllIn = false;
this->nombresGanadores.clear();
delete(it);
}
void ContextoJuego::iniciarRonda() {
if (!this->rondaAllIn) {
this->admJugadores->resetearJugadorTurno();
this->sePuedePasar = true;
chequearRondaAllIn();
}
}
void ContextoJuego::mostrarFlop()
{
for (int i=0 ; i<3 ; ++i) {
this->cartasComunitarias->agregarCarta(repartidor->getCarta());
}
this->rondaTerminada = false;
}
void ContextoJuego::mostrarTurn()
{
this->cartasComunitarias->agregarCarta(repartidor->getCarta());
this->rondaTerminada = false;
}
void ContextoJuego::mostrarRiver()
{
this->cartasComunitarias->agregarCarta(repartidor->getCarta());
this->rondaTerminada = false;
}
void ContextoJuego::evaluarGanador()
{
list<JugadorModelo*> ganadores;
if (this->cantidadJugadoresRonda < 2) {
for (int i = 0; i < MAX_CANTIDAD_JUGADORES; i++) {
JugadorModelo* jugador = this->admJugadores->getJugadores()[i];
if (jugador->isJugandoRonda()) {
ganadores.push_back(jugador);
break;
}
}
} else {
double valorJugadaMasAlta = 0;
for (int i = 0; i < MAX_CANTIDAD_JUGADORES; i++) {
JugadorModelo* jugador = this->admJugadores->getJugadores()[i];
if (jugador->isJugandoRonda()) {
Jugada* jugada = new Jugada();
jugada->agregarCartas(this->cartasComunitarias->getCartas());
jugada->agregarCarta(jugador->getCarta1());
jugada->agregarCarta(jugador->getCarta2());
double valorJugada = jugada->getValorJugada();
if (valorJugada > valorJugadaMasAlta) {
valorJugadaMasAlta = valorJugada;
ganadores.clear();
ganadores.push_back(jugador);
} else {
if (valorJugada == valorJugadaMasAlta) {
ganadores.push_back(jugador);
}
}
}
}
}
if (ganadores.size() == 0) {
throw PokerException("Ocurrio un error evaluando al ganador.");
}
int fichasQueNoSeReparten = 0;
int apuestaMaxGanador = 0;
for (list<JugadorModelo*>::iterator it = ganadores.begin(); it != ganadores.end(); ++it) {
JugadorModelo* ganador = *it;
fichasQueNoSeReparten += ganador->getApuesta();
if (ganador->getApuesta() > apuestaMaxGanador) {
apuestaMaxGanador = ganador->getApuesta();
}
}
for (int i = 0; i < MAX_CANTIDAD_JUGADORES; i++) {
JugadorModelo* jugador = this->admJugadores->getJugadores()[i];
if (jugador->isJugandoRonda() && jugador->getApuesta() > apuestaMaxGanador) {
int diferencia = jugador->getApuesta() - apuestaMaxGanador;
jugador->incrementarFichas(diferencia);
bote->incrementar(-diferencia);
}
}
for (list<JugadorModelo*>::iterator it = ganadores.begin(); it != ganadores.end(); ++it) {
JugadorModelo* ganador = *it;
ganador->incrementarFichas(bote->getCantidad() * ganador->getApuesta() / fichasQueNoSeReparten);
nombresGanadores.push_back(ganador->getNombre());
}
}
void ContextoJuego::finalizarRonda()
{
if (this->cantidadJugadoresRonda > 1) {
this->mostrandoCartas = true;
}
if (this->cantidadJugadoresRonda > 0) {
this->evaluarGanador();
this->timerMostrandoGanador.iniciar();
}
for (int i = 0; i < MAX_CANTIDAD_JUGADORES; i++) {
JugadorModelo* jugador = this->admJugadores->getJugadores()[i];
if (!jugador->isActivo()) {
this->admJugadores->quitarJugador(this->idJugadorToIdCliente(jugador->getId()));
if (this->admJugadores->isDealerJugador(jugador->getId())
&& this->admJugadores->getCantidadJugadoresActivos() > 0) {
this->admJugadores->resetearDealer();
this->admJugadores->incrementarDealer();
}
}
}
AccesoDatos dao;
for (int i = 0; i < MAX_CANTIDAD_JUGADORES; i++) {
JugadorModelo* jugador = this->admJugadores->getJugadores()[i];
jugador->setApuesta(0);
dao.actualizarFichas(jugador->getNombre(), jugador->getFichas());
if (jugador->isJugandoRonda() && jugador->getFichas() <= this->mesa->getSmallBlind() * 2) {
jugador->setJugandoRonda(false);
jugador->setCarta1(NULL);
jugador->setCarta2(NULL);
jugador->setActivo(false);
}
}
}
string ContextoJuego::getEscenarioJuego(int idCliente){
int idJugador = this->admJugadores->idClienteToIdJugador(idCliente);
this->estado = this->estado->getSiguienteEstado();
return this->estado->getEscenarioJuego(idJugador);
}
string ContextoJuego::getEscenarioJuego(int idCliente, string mensaje){
int idJugador = this->admJugadores->idClienteToIdJugador(idCliente);
this->estado = this->estado->getSiguienteEstado();
return this->estado->getEscenarioJuego(idJugador, mensaje);
}
JugadorModelo** ContextoJuego::getJugadores() {
return this->admJugadores->getJugadores();
}
JugadorModelo* ContextoJuego::getJugador(int idJugador){
return this->admJugadores->getJugadorPorPosicion(idJugador + 1);
}
void ContextoJuego::setMostrandoCartas(bool mostrandoCartas){
this->mostrandoCartas = mostrandoCartas;
}
bool ContextoJuego::getMostrandoCartas(){
return this->mostrandoCartas;
}
bool ContextoJuego::hayLugar(){
return this->admJugadores->hayLugar();
}
JugadorModelo* ContextoJuego::agregarJugador(int idCliente, string nombreJugador,
string nombreImagen, int fichas, bool esVirtual, bool esObservador){
return this->admJugadores->agregarJugador(idCliente, nombreJugador,
nombreImagen, fichas, esVirtual, esObservador);
}
void ContextoJuego::quitarJugador(int idCliente){
AccesoDatos dao;
JugadorModelo* jugador = this->admJugadores->getJugador(idCliente);
if (this->isTurnoCliente(idCliente) && !this->mostrandoCartas) {
this->noIr(idCliente);
} else {
if (jugador != NULL && jugador->isJugandoRonda() && !this->mostrandoCartas) {
if (this->cantidadJugadoresRonda > 0) {
this->cantidadJugadoresRonda--;
}
if (this->cantidadJugadoresRonda > 1) {
if (this->admJugadores->isDealerJugador(jugador->getId())) {
this->admJugadores->incrementarDealerTemp();
}
if (this->admJugadores->isJugadorQueCierra(jugador->getId())){
this->admJugadores->decrementarJugadorQueCierra();
}
jugador->setJugandoRonda(false);
if (!(this->rondaAllIn || this->rondaTerminada)) {
chequearRondaAllIn();
}
} else {
jugador->setJugandoRonda(false);
this->finalizarRonda();
this->estado = this->evaluandoGanador;
}
}
}
if (jugador != NULL) {
dao.actualizarFichas(jugador->getNombre(), jugador->getFichas());
}
this->admJugadores->quitarJugador(idCliente);
}
int ContextoJuego::getCantidadJugadoresActivos(){
//return this->admJugadores->getCantidadJugadoresActivos();
int jugadoresActivos = 0;
for (int i = 0; i < MAX_CANTIDAD_JUGADORES; i++) {
JugadorModelo* jugador = this->admJugadores->getJugadores()[i];
if (jugador->isActivo() && jugador->getFichas() > this->mesa->getSmallBlind() * 2) {
jugadoresActivos++;
}
}
return jugadoresActivos;
}
bool ContextoJuego::isTurnoJugador(int idJugador){
if (this->estado != this->esperandoJugadores && this->estado != this->evaluandoGanador) {
this->chequearTimeoutJugador(idJugador);
}
return this->admJugadores->isTurnoJugador(idJugador);
}
void ContextoJuego::chequearTimeoutJugador(int idJugador) {
JugadorModelo* jugador = this->admJugadores->getJugadorTurno();
if (jugador != NULL && jugador->isActivo() && !jugador->isVirtual()
&& jugador->getSegundosTurno() > ContextoJuego::segsTimeoutJugadores) {
this->noIr(this->idJugadorToIdCliente(jugador->getId()));
jugador->setActivo(false);
}
}
bool ContextoJuego::isTurnoCliente(int idCliente){
if (this->estado != this->esperandoJugadores && this->estado != this->evaluandoGanador) {
this->chequearTimeoutJugador(this->idClienteToIdJugador(idCliente));
}
return this->admJugadores->isTurnoCliente(idCliente);
}
list<string> ContextoJuego::getNombresGanadores(){
return this->nombresGanadores;
}
int ContextoJuego::idClienteToIdJugador(int idCliente){
return this->admJugadores->idClienteToIdJugador(idCliente);
}
int ContextoJuego::idJugadorToIdCliente(int idJugador){
return this->admJugadores->idJugadorToIdCliente(idJugador);
}
int ContextoJuego::getMontoAIgualar(){
return this->montoAIgualar;
}
void ContextoJuego::chequearJugadorVirtual(int idCliente) {
JugadorModelo* jugador = this->admJugadores->getJugador(idCliente);
if (jugador != NULL && jugador->isVirtual()
&& this->estado != this->esperandoJugadores
&& this->estado != this->evaluandoGanador
&& this->isTurnoJugador(jugador->getId())) {
jugador->jugar();
}
}
bool ContextoJuego::puedePasar(){
return this->sePuedePasar;
}
| [
"natlehmann@gmail.com@a9434d28-8610-e991-b0d0-89a272e3a296",
"marianofl85@a9434d28-8610-e991-b0d0-89a272e3a296",
"luchopal@a9434d28-8610-e991-b0d0-89a272e3a296"
] | [
[
[
1,
1
],
[
5,
10
],
[
12,
31
],
[
36,
38
],
[
40,
57
],
[
62,
70
],
[
91,
94
],
[
98,
106
],
[
111,
125
],
[
128,
129
],
[
132,
133
],
[
136,
137
],
[
142,
142
],
[
147,
147
],
[
149,
149
],
[
156,
157
],
[
160,
163
],
[
165,
170
],
[
172,
172
],
[
177,
179
],
[
182,
186
],
[
197,
202
],
[
204,
204
],
[
209,
222
],
[
226,
231
],
[
233,
237
],
[
240,
243
],
[
264,
264
],
[
272,
290
],
[
292,
301
],
[
303,
308
],
[
316,
316
],
[
328,
334
],
[
336,
336
],
[
339,
344
],
[
357,
357
],
[
363,
363
],
[
369,
369
],
[
376,
376
],
[
378,
379
],
[
385,
385
],
[
387,
387
],
[
389,
392
],
[
445,
448
],
[
454,
469
],
[
472,
474
],
[
483,
518
],
[
520,
523
],
[
525,
528
],
[
531,
531
],
[
533,
533
],
[
536,
538
],
[
540,
540
],
[
542,
544
],
[
549,
549
],
[
554,
554
],
[
556,
558
],
[
562,
566
],
[
570,
570
],
[
580,
608
],
[
611,
637
]
],
[
[
2,
4
],
[
11,
11
],
[
32,
35
],
[
39,
39
],
[
58,
61
],
[
71,
90
],
[
95,
97
],
[
107,
110
],
[
126,
127
],
[
130,
131
],
[
134,
135
],
[
138,
141
],
[
143,
146
],
[
148,
148
],
[
150,
155
],
[
158,
159
],
[
164,
164
],
[
171,
171
],
[
173,
176
],
[
180,
181
],
[
187,
196
],
[
203,
203
],
[
205,
208
],
[
223,
225
],
[
232,
232
],
[
238,
239
],
[
244,
263
],
[
265,
271
],
[
291,
291
],
[
302,
302
],
[
309,
315
],
[
317,
327
],
[
335,
335
],
[
337,
338
],
[
345,
356
],
[
358,
362
],
[
364,
368
],
[
370,
375
],
[
377,
377
],
[
380,
384
],
[
386,
386
],
[
388,
388
],
[
393,
444
],
[
449,
453
],
[
470,
471
],
[
475,
482
],
[
519,
519
],
[
524,
524
],
[
529,
530
],
[
532,
532
],
[
534,
535
],
[
539,
539
],
[
541,
541
],
[
545,
548
],
[
550,
553
],
[
555,
555
],
[
559,
561
],
[
567,
569
],
[
571,
579
],
[
609,
610
]
],
[
[
638,
638
]
]
] |
7734e933e1d53b4df824c9485dea02fc78fe6368 | 0033659a033b4afac9b93c0ac80b8918a5ff9779 | /game/server/hl2/hl2_player.cpp | 0418912d710f678c8d6b94b9e83dcda5e07f28fc | [] | no_license | jonnyboy0719/situation-outbreak-two | d03151dc7a12a97094fffadacf4a8f7ee6ec7729 | 50037e27e738ff78115faea84e235f865c61a68f | refs/heads/master | 2021-01-10 09:59:39 | 2011-01-11 01:15:33 | 2011-01-11 01:15:33 | 53,858,955 | 1 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 114,976 | cpp | //========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose: Player for HL2.
//
//=============================================================================//
#include "cbase.h"
#include "hl2_player.h"
#include "globalstate.h"
#include "game.h"
#include "gamerules.h"
#include "trains.h"
#include "basehlcombatweapon_shared.h"
#include "vcollide_parse.h"
#include "in_buttons.h"
#include "ai_interactions.h"
#include "ai_squad.h"
#include "igamemovement.h"
#include "ai_hull.h"
#include "hl2_shareddefs.h"
#include "info_camera_link.h"
#include "point_camera.h"
#include "engine/IEngineSound.h"
#include "ndebugoverlay.h"
#include "iservervehicle.h"
#include "IVehicle.h"
#include "globals.h"
#include "collisionutils.h"
#include "coordsize.h"
#include "effect_color_tables.h"
#include "vphysics/player_controller.h"
#include "player_pickup.h"
#include "weapon_physcannon.h"
#include "script_intro.h"
#include "effect_dispatch_data.h"
#include "te_effect_dispatch.h"
#include "ai_basenpc.h"
#include "AI_Criteria.h"
#include "npc_barnacle.h"
#include "entitylist.h"
#include "env_zoom.h"
#include "hl2_gamerules.h"
#include "prop_combine_ball.h"
#include "datacache/imdlcache.h"
#include "eventqueue.h"
#include "GameStats.h"
#include "filters.h"
#include "tier0/icommandline.h"
#ifdef HL2_EPISODIC
#include "npc_alyx_episodic.h"
#endif
/////
// SO2 - James
// Do not allow players to fire weapons while sprinting
// Base each player's speed on their health
#include "so_player.h"
/////
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
extern ConVar weapon_showproficiency;
extern ConVar autoaim_max_dist;
// Do not touch with without seeing me, please! (sjb)
// For consistency's sake, enemy gunfire is traced against a scaled down
// version of the player's hull, not the hitboxes for the player's model
// because the player isn't aware of his model, and can't do anything about
// preventing headshots and other such things. Also, game difficulty will
// not change if the model changes. This is the value by which to scale
// the X/Y of the player's hull to get the volume to trace bullets against.
#define PLAYER_HULL_REDUCTION 0.70
// This switches between the single primary weapon, and multiple weapons with buckets approach (jdw)
#define HL2_SINGLE_PRIMARY_WEAPON_MODE 0
#define TIME_IGNORE_FALL_DAMAGE 10.0
extern int gEvilImpulse101;
ConVar sv_autojump( "sv_autojump", "0" );
ConVar hl2_walkspeed( "hl2_walkspeed", "150" );
ConVar hl2_normspeed( "hl2_normspeed", "190" );
ConVar hl2_sprintspeed( "hl2_sprintspeed", "320" );
ConVar hl2_darkness_flashlight_factor ( "hl2_darkness_flashlight_factor", "1" );
#ifdef HL2MP
/////
// SO2 - James
// Base each player's speed on their health
/*#define HL2_WALK_SPEED 150
#define HL2_NORM_SPEED 190
#define HL2_SPRINT_SPEED 320*/
#define HL2_WALK_SPEED SO_WALK_SPEED
#define HL2_NORM_SPEED SO_NORM_SPEED
#define HL2_SPRINT_SPEED SO_SPRINT_SPEED
/////
#else
#define HL2_WALK_SPEED hl2_walkspeed.GetFloat()
#define HL2_NORM_SPEED hl2_normspeed.GetFloat()
#define HL2_SPRINT_SPEED hl2_sprintspeed.GetFloat()
#endif
ConVar player_showpredictedposition( "player_showpredictedposition", "0" );
ConVar player_showpredictedposition_timestep( "player_showpredictedposition_timestep", "1.0" );
ConVar player_squad_transient_commands( "player_squad_transient_commands", "1", FCVAR_REPLICATED );
ConVar player_squad_double_tap_time( "player_squad_double_tap_time", "0.25" );
ConVar sv_infinite_aux_power( "sv_infinite_aux_power", "0", FCVAR_CHEAT );
ConVar autoaim_unlock_target( "autoaim_unlock_target", "0.8666" );
ConVar sv_stickysprint("sv_stickysprint", "0", FCVAR_ARCHIVE | FCVAR_ARCHIVE_XBOX);
#define FLASH_DRAIN_TIME 1.1111 // 100 units / 90 secs
#define FLASH_CHARGE_TIME 50.0f // 100 units / 2 secs
//==============================================================================================
// CAPPED PLAYER PHYSICS DAMAGE TABLE
//==============================================================================================
static impactentry_t cappedPlayerLinearTable[] =
{
{ 150*150, 5 },
{ 250*250, 10 },
{ 450*450, 20 },
{ 550*550, 30 },
//{ 700*700, 100 },
//{ 1000*1000, 500 },
};
static impactentry_t cappedPlayerAngularTable[] =
{
{ 100*100, 10 },
{ 150*150, 20 },
{ 200*200, 30 },
//{ 300*300, 500 },
};
static impactdamagetable_t gCappedPlayerImpactDamageTable =
{
cappedPlayerLinearTable,
cappedPlayerAngularTable,
ARRAYSIZE(cappedPlayerLinearTable),
ARRAYSIZE(cappedPlayerAngularTable),
24*24.0f, // minimum linear speed
360*360.0f, // minimum angular speed
2.0f, // can't take damage from anything under 2kg
5.0f, // anything less than 5kg is "small"
5.0f, // never take more than 5 pts of damage from anything under 5kg
36*36.0f, // <5kg objects must go faster than 36 in/s to do damage
0.0f, // large mass in kg (no large mass effects)
1.0f, // large mass scale
2.0f, // large mass falling scale
320.0f, // min velocity for player speed to cause damage
};
// Flashlight utility
bool g_bCacheLegacyFlashlightStatus = true;
bool g_bUseLegacyFlashlight;
bool Flashlight_UseLegacyVersion( void )
{
// If this is the first run through, cache off what the answer should be (cannot change during a session)
if ( g_bCacheLegacyFlashlightStatus )
{
char modDir[MAX_PATH];
if ( UTIL_GetModDir( modDir, sizeof(modDir) ) == false )
return false;
g_bUseLegacyFlashlight = ( !Q_strcmp( modDir, "hl2" ) || !Q_strcmp( modDir, "episodic" ) );
g_bCacheLegacyFlashlightStatus = false;
}
// Return the results
return g_bUseLegacyFlashlight;
}
//-----------------------------------------------------------------------------
// Purpose: Used to relay outputs/inputs from the player to the world and viceversa
//-----------------------------------------------------------------------------
class CLogicPlayerProxy : public CLogicalEntity
{
DECLARE_CLASS( CLogicPlayerProxy, CLogicalEntity );
private:
DECLARE_DATADESC();
public:
COutputEvent m_OnFlashlightOn;
COutputEvent m_OnFlashlightOff;
COutputEvent m_PlayerHasAmmo;
COutputEvent m_PlayerHasNoAmmo;
COutputEvent m_PlayerDied;
COutputEvent m_PlayerMissedAR2AltFire; // Player fired a combine ball which did not dissolve any enemies.
COutputInt m_RequestedPlayerHealth;
void InputRequestPlayerHealth( inputdata_t &inputdata );
void InputSetFlashlightSlowDrain( inputdata_t &inputdata );
void InputSetFlashlightNormalDrain( inputdata_t &inputdata );
void InputSetPlayerHealth( inputdata_t &inputdata );
void InputRequestAmmoState( inputdata_t &inputdata );
void InputLowerWeapon( inputdata_t &inputdata );
void InputEnableCappedPhysicsDamage( inputdata_t &inputdata );
void InputDisableCappedPhysicsDamage( inputdata_t &inputdata );
void InputSetLocatorTargetEntity( inputdata_t &inputdata );
void Activate ( void );
bool PassesDamageFilter( const CTakeDamageInfo &info );
EHANDLE m_hPlayer;
};
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void CC_ToggleZoom( void )
{
CBasePlayer* pPlayer = UTIL_GetCommandClient();
if( pPlayer )
{
CHL2_Player *pHL2Player = dynamic_cast<CHL2_Player*>(pPlayer);
if( pHL2Player && pHL2Player->IsSuitEquipped() )
{
pHL2Player->ToggleZoom();
}
}
}
static ConCommand toggle_zoom("toggle_zoom", CC_ToggleZoom, "Toggles zoom display" );
// ConVar cl_forwardspeed( "cl_forwardspeed", "400", FCVAR_CHEAT ); // Links us to the client's version
ConVar xc_crouch_range( "xc_crouch_range", "0.85", FCVAR_ARCHIVE, "Percentarge [1..0] of joystick range to allow ducking within" ); // Only 1/2 of the range is used
ConVar xc_use_crouch_limiter( "xc_use_crouch_limiter", "0", FCVAR_ARCHIVE, "Use the crouch limiting logic on the controller" );
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void CC_ToggleDuck( void )
{
CBasePlayer* pPlayer = UTIL_GetCommandClient();
if ( pPlayer == NULL )
return;
// Cannot be frozen
if ( pPlayer->GetFlags() & FL_FROZEN )
return;
static bool bChecked = false;
static ConVar *pCVcl_forwardspeed = NULL;
if ( !bChecked )
{
bChecked = true;
pCVcl_forwardspeed = ( ConVar * )cvar->FindVar( "cl_forwardspeed" );
}
// If we're not ducked, do extra checking
if ( xc_use_crouch_limiter.GetBool() )
{
if ( pPlayer->GetToggledDuckState() == false )
{
float flForwardSpeed = 400.0f;
if ( pCVcl_forwardspeed )
{
flForwardSpeed = pCVcl_forwardspeed->GetFloat();
}
flForwardSpeed = max( 1.0f, flForwardSpeed );
// Make sure we're not in the blindspot on the crouch detection
float flStickDistPerc = ( pPlayer->GetStickDist() / flForwardSpeed ); // Speed is the magnitude
if ( flStickDistPerc > xc_crouch_range.GetFloat() )
return;
}
}
// Toggle the duck
pPlayer->ToggleDuck();
}
static ConCommand toggle_duck("toggle_duck", CC_ToggleDuck, "Toggles duck" );
#ifndef HL2MP
#ifndef PORTAL
LINK_ENTITY_TO_CLASS( player, CHL2_Player );
#endif
#endif
PRECACHE_REGISTER(player);
CBaseEntity *FindEntityForward( CBasePlayer *pMe, bool fHull );
BEGIN_SIMPLE_DATADESC( LadderMove_t )
DEFINE_FIELD( m_bForceLadderMove, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bForceMount, FIELD_BOOLEAN ),
DEFINE_FIELD( m_flStartTime, FIELD_TIME ),
DEFINE_FIELD( m_flArrivalTime, FIELD_TIME ),
DEFINE_FIELD( m_vecGoalPosition, FIELD_POSITION_VECTOR ),
DEFINE_FIELD( m_vecStartPosition, FIELD_POSITION_VECTOR ),
DEFINE_FIELD( m_hForceLadder, FIELD_EHANDLE ),
DEFINE_FIELD( m_hReservedSpot, FIELD_EHANDLE ),
END_DATADESC()
// Global Savedata for HL2 player
BEGIN_DATADESC( CHL2_Player )
DEFINE_FIELD( m_nControlClass, FIELD_INTEGER ),
DEFINE_EMBEDDED( m_HL2Local ),
DEFINE_FIELD( m_bSprintEnabled, FIELD_BOOLEAN ),
DEFINE_FIELD( m_flTimeAllSuitDevicesOff, FIELD_TIME ),
DEFINE_FIELD( m_fIsSprinting, FIELD_BOOLEAN ),
DEFINE_FIELD( m_fIsWalking, FIELD_BOOLEAN ),
/*
// These are initialized every time the player calls Activate()
DEFINE_FIELD( m_bIsAutoSprinting, FIELD_BOOLEAN ),
DEFINE_FIELD( m_fAutoSprintMinTime, FIELD_TIME ),
*/
// Field is used within a single tick, no need to save restore
// DEFINE_FIELD( m_bPlayUseDenySound, FIELD_BOOLEAN ),
// m_pPlayerAISquad reacquired on load
DEFINE_AUTO_ARRAY( m_vecMissPositions, FIELD_POSITION_VECTOR ),
DEFINE_FIELD( m_nNumMissPositions, FIELD_INTEGER ),
// m_pPlayerAISquad
DEFINE_EMBEDDED( m_CommanderUpdateTimer ),
// m_RealTimeLastSquadCommand
DEFINE_FIELD( m_QueuedCommand, FIELD_INTEGER ),
DEFINE_FIELD( m_flTimeIgnoreFallDamage, FIELD_TIME ),
DEFINE_FIELD( m_bIgnoreFallDamageResetAfterImpact, FIELD_BOOLEAN ),
// Suit power fields
DEFINE_FIELD( m_flSuitPowerLoad, FIELD_FLOAT ),
DEFINE_FIELD( m_flIdleTime, FIELD_TIME ),
DEFINE_FIELD( m_flMoveTime, FIELD_TIME ),
DEFINE_FIELD( m_flLastDamageTime, FIELD_TIME ),
DEFINE_FIELD( m_flTargetFindTime, FIELD_TIME ),
DEFINE_FIELD( m_flAdmireGlovesAnimTime, FIELD_TIME ),
DEFINE_FIELD( m_flNextFlashlightCheckTime, FIELD_TIME ),
DEFINE_FIELD( m_flFlashlightPowerDrainScale, FIELD_FLOAT ),
DEFINE_FIELD( m_bFlashlightDisabled, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bUseCappedPhysicsDamageTable, FIELD_BOOLEAN ),
DEFINE_FIELD( m_hLockedAutoAimEntity, FIELD_EHANDLE ),
DEFINE_EMBEDDED( m_LowerWeaponTimer ),
DEFINE_EMBEDDED( m_AutoaimTimer ),
DEFINE_INPUTFUNC( FIELD_FLOAT, "IgnoreFallDamage", InputIgnoreFallDamage ),
DEFINE_INPUTFUNC( FIELD_FLOAT, "IgnoreFallDamageWithoutReset", InputIgnoreFallDamageWithoutReset ),
DEFINE_INPUTFUNC( FIELD_VOID, "OnSquadMemberKilled", OnSquadMemberKilled ),
DEFINE_INPUTFUNC( FIELD_VOID, "DisableFlashlight", InputDisableFlashlight ),
DEFINE_INPUTFUNC( FIELD_VOID, "EnableFlashlight", InputEnableFlashlight ),
DEFINE_INPUTFUNC( FIELD_VOID, "ForceDropPhysObjects", InputForceDropPhysObjects ),
DEFINE_SOUNDPATCH( m_sndLeeches ),
DEFINE_SOUNDPATCH( m_sndWaterSplashes ),
DEFINE_FIELD( m_flArmorReductionTime, FIELD_TIME ),
DEFINE_FIELD( m_iArmorReductionFrom, FIELD_INTEGER ),
DEFINE_FIELD( m_flTimeUseSuspended, FIELD_TIME ),
DEFINE_FIELD( m_hLocatorTargetEntity, FIELD_EHANDLE ),
DEFINE_FIELD( m_flTimeNextLadderHint, FIELD_TIME ),
//DEFINE_FIELD( m_hPlayerProxy, FIELD_EHANDLE ), //Shut up class check!
END_DATADESC()
CHL2_Player::CHL2_Player()
{
m_nNumMissPositions = 0;
m_pPlayerAISquad = 0;
m_bSprintEnabled = true;
m_flArmorReductionTime = 0.0f;
m_iArmorReductionFrom = 0;
}
//
// SUIT POWER DEVICES
//
/////
// SO2 - James
// Change how quickly suit power (stamina) recharges
//#define SUITPOWER_CHARGE_RATE 12.5 // 100 units in 8 seconds
#define SUITPOWER_CHARGE_RATE 6.25 // 100 units in 16 seconds
/////
#ifdef HL2MP
CSuitPowerDevice SuitDeviceSprint( bits_SUIT_DEVICE_SPRINT, 25.0f ); // 100 units in 4 seconds
#else
CSuitPowerDevice SuitDeviceSprint( bits_SUIT_DEVICE_SPRINT, 12.5f ); // 100 units in 8 seconds
#endif
#ifdef HL2_EPISODIC
CSuitPowerDevice SuitDeviceFlashlight( bits_SUIT_DEVICE_FLASHLIGHT, 1.111 ); // 100 units in 90 second
#else
CSuitPowerDevice SuitDeviceFlashlight( bits_SUIT_DEVICE_FLASHLIGHT, 2.222 ); // 100 units in 45 second
#endif
CSuitPowerDevice SuitDeviceBreather( bits_SUIT_DEVICE_BREATHER, 6.7f ); // 100 units in 15 seconds (plus three padded seconds)
IMPLEMENT_SERVERCLASS_ST(CHL2_Player, DT_HL2_Player)
SendPropDataTable(SENDINFO_DT(m_HL2Local), &REFERENCE_SEND_TABLE(DT_HL2Local), SendProxy_SendLocalDataTable),
SendPropBool( SENDINFO(m_fIsSprinting) ),
END_SEND_TABLE()
void CHL2_Player::Precache( void )
{
BaseClass::Precache();
PrecacheScriptSound( "HL2Player.SprintNoPower" );
PrecacheScriptSound( "HL2Player.SprintStart" );
PrecacheScriptSound( "HL2Player.UseDeny" );
PrecacheScriptSound( "HL2Player.FlashLightOn" );
PrecacheScriptSound( "HL2Player.FlashLightOff" );
PrecacheScriptSound( "HL2Player.PickupWeapon" );
PrecacheScriptSound( "HL2Player.TrainUse" );
PrecacheScriptSound( "HL2Player.Use" );
PrecacheScriptSound( "HL2Player.BurnPain" );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHL2_Player::CheckSuitZoom( void )
{
//#ifndef _XBOX
//Adrian - No zooming without a suit!
if ( IsSuitEquipped() )
{
if ( m_afButtonReleased & IN_ZOOM )
{
StopZooming();
}
else if ( m_afButtonPressed & IN_ZOOM )
{
StartZooming();
}
}
//#endif//_XBOX
}
void CHL2_Player::EquipSuit( bool bPlayEffects )
{
MDLCACHE_CRITICAL_SECTION();
BaseClass::EquipSuit();
m_HL2Local.m_bDisplayReticle = true;
if ( bPlayEffects == true )
{
StartAdmireGlovesAnimation();
}
}
void CHL2_Player::RemoveSuit( void )
{
BaseClass::RemoveSuit();
m_HL2Local.m_bDisplayReticle = false;
}
void CHL2_Player::HandleSpeedChanges( void )
{
int buttonsChanged = m_afButtonPressed | m_afButtonReleased;
bool bCanSprint = CanSprint();
bool bIsSprinting = IsSprinting();
bool bWantSprint = ( bCanSprint && IsSuitEquipped() && (m_nButtons & IN_SPEED) );
if ( bIsSprinting != bWantSprint && (buttonsChanged & IN_SPEED) )
{
// If someone wants to sprint, make sure they've pressed the button to do so. We want to prevent the
// case where a player can hold down the sprint key and burn tiny bursts of sprint as the suit recharges
// We want a full debounce of the key to resume sprinting after the suit is completely drained
if ( bWantSprint )
{
if ( sv_stickysprint.GetBool() )
{
StartAutoSprint();
}
else
{
StartSprinting();
}
}
else
{
if ( !sv_stickysprint.GetBool() )
{
StopSprinting();
}
// Reset key, so it will be activated post whatever is suppressing it.
m_nButtons &= ~IN_SPEED;
}
}
bool bIsWalking = IsWalking();
// have suit, pressing button, not sprinting or ducking
bool bWantWalking;
if( IsSuitEquipped() )
{
bWantWalking = (m_nButtons & IN_WALK) && !IsSprinting() && !(m_nButtons & IN_DUCK);
}
else
{
bWantWalking = true;
}
if( bIsWalking != bWantWalking )
{
if ( bWantWalking )
{
StartWalking();
}
else
{
StopWalking();
}
}
}
//-----------------------------------------------------------------------------
// This happens when we powerdown from the mega physcannon to the regular one
//-----------------------------------------------------------------------------
void CHL2_Player::HandleArmorReduction( void )
{
if ( m_flArmorReductionTime < gpGlobals->curtime )
return;
if ( ArmorValue() <= 0 )
return;
float flPercent = 1.0f - (( m_flArmorReductionTime - gpGlobals->curtime ) / ARMOR_DECAY_TIME );
int iArmor = Lerp( flPercent, m_iArmorReductionFrom, 0 );
SetArmorValue( iArmor );
}
//-----------------------------------------------------------------------------
// Purpose: Allow pre-frame adjustments on the player
//-----------------------------------------------------------------------------
void CHL2_Player::PreThink(void)
{
if ( player_showpredictedposition.GetBool() )
{
Vector predPos;
UTIL_PredictedPosition( this, player_showpredictedposition_timestep.GetFloat(), &predPos );
NDebugOverlay::Box( predPos, NAI_Hull::Mins( GetHullType() ), NAI_Hull::Maxs( GetHullType() ), 0, 255, 0, 0, 0.01f );
NDebugOverlay::Line( GetAbsOrigin(), predPos, 0, 255, 0, 0, 0.01f );
}
#ifdef HL2_EPISODIC
if( m_hLocatorTargetEntity != NULL )
{
// Keep track of the entity here, the client will pick up the rest of the work
m_HL2Local.m_vecLocatorOrigin = m_hLocatorTargetEntity->WorldSpaceCenter();
}
else
{
m_HL2Local.m_vecLocatorOrigin = vec3_invalid; // This tells the client we have no locator target.
}
#endif//HL2_EPISODIC
// Riding a vehicle?
if ( IsInAVehicle() )
{
VPROF( "CHL2_Player::PreThink-Vehicle" );
// make sure we update the client, check for timed damage and update suit even if we are in a vehicle
UpdateClientData();
CheckTimeBasedDamage();
// Allow the suit to recharge when in the vehicle.
SuitPower_Update();
CheckSuitUpdate();
CheckSuitZoom();
WaterMove();
return;
}
// This is an experiment of mine- autojumping!
// only affects you if sv_autojump is nonzero.
if( (GetFlags() & FL_ONGROUND) && sv_autojump.GetFloat() != 0 )
{
VPROF( "CHL2_Player::PreThink-Autojump" );
// check autojump
Vector vecCheckDir;
vecCheckDir = GetAbsVelocity();
float flVelocity = VectorNormalize( vecCheckDir );
if( flVelocity > 200 )
{
// Going fast enough to autojump
vecCheckDir = WorldSpaceCenter() + vecCheckDir * 34 - Vector( 0, 0, 16 );
trace_t tr;
UTIL_TraceHull( WorldSpaceCenter() - Vector( 0, 0, 16 ), vecCheckDir, NAI_Hull::Mins(HULL_TINY_CENTERED),NAI_Hull::Maxs(HULL_TINY_CENTERED), MASK_PLAYERSOLID, this, COLLISION_GROUP_PLAYER, &tr );
//NDebugOverlay::Line( tr.startpos, tr.endpos, 0,255,0, true, 10 );
if( tr.fraction == 1.0 && !tr.startsolid )
{
// Now trace down!
UTIL_TraceLine( vecCheckDir, vecCheckDir - Vector( 0, 0, 64 ), MASK_PLAYERSOLID, this, COLLISION_GROUP_NONE, &tr );
//NDebugOverlay::Line( tr.startpos, tr.endpos, 0,255,0, true, 10 );
if( tr.fraction == 1.0 && !tr.startsolid )
{
// !!!HACKHACK
// I KNOW, I KNOW, this is definitely not the right way to do this,
// but I'm prototyping! (sjb)
Vector vecNewVelocity = GetAbsVelocity();
vecNewVelocity.z += 250;
SetAbsVelocity( vecNewVelocity );
}
}
}
}
VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-Speed" );
HandleSpeedChanges();
#ifdef HL2_EPISODIC
HandleArmorReduction();
#endif
if( sv_stickysprint.GetBool() && m_bIsAutoSprinting )
{
// If we're ducked and not in the air
if( IsDucked() && GetGroundEntity() != NULL )
{
StopSprinting();
}
// Stop sprinting if the player lets off the stick for a moment.
else if( GetStickDist() == 0.0f )
{
if( gpGlobals->curtime > m_fAutoSprintMinTime )
{
StopSprinting();
}
}
else
{
// Stop sprinting one half second after the player stops inputting with the move stick.
m_fAutoSprintMinTime = gpGlobals->curtime + 0.5f;
}
}
else if ( IsSprinting() )
{
// Disable sprint while ducked unless we're in the air (jumping)
if ( IsDucked() && ( GetGroundEntity() != NULL ) )
{
StopSprinting();
}
}
VPROF_SCOPE_END();
if ( g_fGameOver || IsPlayerLockedInPlace() )
return; // finale
VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-ItemPreFrame" );
ItemPreFrame( );
VPROF_SCOPE_END();
VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-WaterMove" );
WaterMove();
VPROF_SCOPE_END();
if ( g_pGameRules && g_pGameRules->FAllowFlashlight() )
m_Local.m_iHideHUD &= ~HIDEHUD_FLASHLIGHT;
else
m_Local.m_iHideHUD |= HIDEHUD_FLASHLIGHT;
VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-CommanderUpdate" );
CommanderUpdate();
VPROF_SCOPE_END();
// Operate suit accessories and manage power consumption/charge
VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-SuitPower_Update" );
SuitPower_Update();
VPROF_SCOPE_END();
// checks if new client data (for HUD and view control) needs to be sent to the client
VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-UpdateClientData" );
UpdateClientData();
VPROF_SCOPE_END();
VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-CheckTimeBasedDamage" );
CheckTimeBasedDamage();
VPROF_SCOPE_END();
VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-CheckSuitUpdate" );
CheckSuitUpdate();
VPROF_SCOPE_END();
VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-CheckSuitZoom" );
CheckSuitZoom();
VPROF_SCOPE_END();
if (m_lifeState >= LIFE_DYING)
{
PlayerDeathThink();
return;
}
#ifdef HL2_EPISODIC
CheckFlashlight();
#endif // HL2_EPISODIC
// So the correct flags get sent to client asap.
//
if ( m_afPhysicsFlags & PFLAG_DIROVERRIDE )
AddFlag( FL_ONTRAIN );
else
RemoveFlag( FL_ONTRAIN );
// Train speed control
if ( m_afPhysicsFlags & PFLAG_DIROVERRIDE )
{
CBaseEntity *pTrain = GetGroundEntity();
float vel;
if ( pTrain )
{
if ( !(pTrain->ObjectCaps() & FCAP_DIRECTIONAL_USE) )
pTrain = NULL;
}
if ( !pTrain )
{
if ( GetActiveWeapon() && (GetActiveWeapon()->ObjectCaps() & FCAP_DIRECTIONAL_USE) )
{
m_iTrain = TRAIN_ACTIVE | TRAIN_NEW;
if ( m_nButtons & IN_FORWARD )
{
m_iTrain |= TRAIN_FAST;
}
else if ( m_nButtons & IN_BACK )
{
m_iTrain |= TRAIN_BACK;
}
else
{
m_iTrain |= TRAIN_NEUTRAL;
}
return;
}
else
{
trace_t trainTrace;
// Maybe this is on the other side of a level transition
UTIL_TraceLine( GetAbsOrigin(), GetAbsOrigin() + Vector(0,0,-38),
MASK_PLAYERSOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, &trainTrace );
if ( trainTrace.fraction != 1.0 && trainTrace.m_pEnt )
pTrain = trainTrace.m_pEnt;
if ( !pTrain || !(pTrain->ObjectCaps() & FCAP_DIRECTIONAL_USE) || !pTrain->OnControls(this) )
{
// Warning( "In train mode with no train!\n" );
m_afPhysicsFlags &= ~PFLAG_DIROVERRIDE;
m_iTrain = TRAIN_NEW|TRAIN_OFF;
return;
}
}
}
else if ( !( GetFlags() & FL_ONGROUND ) || pTrain->HasSpawnFlags( SF_TRACKTRAIN_NOCONTROL ) || (m_nButtons & (IN_MOVELEFT|IN_MOVERIGHT) ) )
{
// Turn off the train if you jump, strafe, or the train controls go dead
m_afPhysicsFlags &= ~PFLAG_DIROVERRIDE;
m_iTrain = TRAIN_NEW|TRAIN_OFF;
return;
}
SetAbsVelocity( vec3_origin );
vel = 0;
if ( m_afButtonPressed & IN_FORWARD )
{
vel = 1;
pTrain->Use( this, this, USE_SET, (float)vel );
}
else if ( m_afButtonPressed & IN_BACK )
{
vel = -1;
pTrain->Use( this, this, USE_SET, (float)vel );
}
if (vel)
{
m_iTrain = TrainSpeed(pTrain->m_flSpeed, ((CFuncTrackTrain*)pTrain)->GetMaxSpeed());
m_iTrain |= TRAIN_ACTIVE|TRAIN_NEW;
}
}
else if (m_iTrain & TRAIN_ACTIVE)
{
m_iTrain = TRAIN_NEW; // turn off train
}
//
// If we're not on the ground, we're falling. Update our falling velocity.
//
if ( !( GetFlags() & FL_ONGROUND ) )
{
m_Local.m_flFallVelocity = -GetAbsVelocity().z;
}
if ( m_afPhysicsFlags & PFLAG_ONBARNACLE )
{
bool bOnBarnacle = false;
CNPC_Barnacle *pBarnacle = NULL;
do
{
// FIXME: Not a good or fast solution, but maybe it will catch the bug!
pBarnacle = (CNPC_Barnacle*)gEntList.FindEntityByClassname( pBarnacle, "npc_barnacle" );
if ( pBarnacle )
{
if ( pBarnacle->GetEnemy() == this )
{
bOnBarnacle = true;
}
}
} while ( pBarnacle );
if ( !bOnBarnacle )
{
Warning( "Attached to barnacle?\n" );
Assert( 0 );
m_afPhysicsFlags &= ~PFLAG_ONBARNACLE;
}
else
{
SetAbsVelocity( vec3_origin );
}
}
// StudioFrameAdvance( );//!!!HACKHACK!!! Can't be hit by traceline when not animating?
// Update weapon's ready status
UpdateWeaponPosture();
/////
// SO2 - James
// Disable suit zooming functionality
/*// Disallow shooting while zooming
if ( IsX360() )
{
if ( IsZooming() )
{
if( GetActiveWeapon() && !GetActiveWeapon()->IsWeaponZoomed() )
{
// If not zoomed because of the weapon itself, do not attack.
m_nButtons &= ~(IN_ATTACK|IN_ATTACK2);
}
}
}
else
{
if ( m_nButtons & IN_ZOOM )
{
//FIXME: Held weapons like the grenade get sad when this happens
#ifdef HL2_EPISODIC
// Episodic allows players to zoom while using a func_tank
CBaseCombatWeapon* pWep = GetActiveWeapon();
if ( !m_hUseEntity || ( pWep && pWep->IsWeaponVisible() ) )
#endif
m_nButtons &= ~(IN_ATTACK|IN_ATTACK2);
}
}*/
/////
}
void CHL2_Player::PostThink( void )
{
BaseClass::PostThink();
if ( !g_fGameOver && !IsPlayerLockedInPlace() && IsAlive() )
{
HandleAdmireGlovesAnimation();
}
}
void CHL2_Player::StartAdmireGlovesAnimation( void )
{
MDLCACHE_CRITICAL_SECTION();
CBaseViewModel *vm = GetViewModel( 0 );
if ( vm && !GetActiveWeapon() )
{
vm->SetWeaponModel( "models/weapons/v_hands.mdl", NULL );
ShowViewModel( true );
int idealSequence = vm->SelectWeightedSequence( ACT_VM_IDLE );
if ( idealSequence >= 0 )
{
vm->SendViewModelMatchingSequence( idealSequence );
m_flAdmireGlovesAnimTime = gpGlobals->curtime + vm->SequenceDuration( idealSequence );
}
}
}
void CHL2_Player::HandleAdmireGlovesAnimation( void )
{
CBaseViewModel *pVM = GetViewModel();
if ( pVM && pVM->GetOwningWeapon() == NULL )
{
if ( m_flAdmireGlovesAnimTime != 0.0 )
{
if ( m_flAdmireGlovesAnimTime > gpGlobals->curtime )
{
pVM->m_flPlaybackRate = 1.0f;
pVM->StudioFrameAdvance( );
}
else if ( m_flAdmireGlovesAnimTime < gpGlobals->curtime )
{
m_flAdmireGlovesAnimTime = 0.0f;
pVM->SetWeaponModel( NULL, NULL );
}
}
}
else
m_flAdmireGlovesAnimTime = 0.0f;
}
#define HL2PLAYER_RELOADGAME_ATTACK_DELAY 1.0f
void CHL2_Player::Activate( void )
{
BaseClass::Activate();
InitSprinting();
#ifdef HL2_EPISODIC
// Delay attacks by 1 second after loading a game.
if ( GetActiveWeapon() )
{
float flRemaining = GetActiveWeapon()->m_flNextPrimaryAttack - gpGlobals->curtime;
if ( flRemaining < HL2PLAYER_RELOADGAME_ATTACK_DELAY )
{
GetActiveWeapon()->m_flNextPrimaryAttack = gpGlobals->curtime + HL2PLAYER_RELOADGAME_ATTACK_DELAY;
}
flRemaining = GetActiveWeapon()->m_flNextSecondaryAttack - gpGlobals->curtime;
if ( flRemaining < HL2PLAYER_RELOADGAME_ATTACK_DELAY )
{
GetActiveWeapon()->m_flNextSecondaryAttack = gpGlobals->curtime + HL2PLAYER_RELOADGAME_ATTACK_DELAY;
}
}
#endif
GetPlayerProxy();
}
//------------------------------------------------------------------------------
// Purpose :
// Input :
// Output :
//------------------------------------------------------------------------------
Class_T CHL2_Player::Classify ( void )
{
// If player controlling another entity? If so, return this class
if (m_nControlClass != CLASS_NONE)
{
return m_nControlClass;
}
else
{
if(IsInAVehicle())
{
IServerVehicle *pVehicle = GetVehicle();
return pVehicle->ClassifyPassenger( this, CLASS_PLAYER );
}
else
{
return CLASS_PLAYER;
}
}
}
//-----------------------------------------------------------------------------
// Purpose: This is a generic function (to be implemented by sub-classes) to
// handle specific interactions between different types of characters
// (For example the barnacle grabbing an NPC)
// Input : Constant for the type of interaction
// Output : true - if sub-class has a response for the interaction
// false - if sub-class has no response
//-----------------------------------------------------------------------------
bool CHL2_Player::HandleInteraction(int interactionType, void *data, CBaseCombatCharacter* sourceEnt)
{
if ( interactionType == g_interactionBarnacleVictimDangle )
return false;
if (interactionType == g_interactionBarnacleVictimReleased)
{
m_afPhysicsFlags &= ~PFLAG_ONBARNACLE;
SetMoveType( MOVETYPE_WALK );
return true;
}
else if (interactionType == g_interactionBarnacleVictimGrab)
{
#ifdef HL2_EPISODIC
CNPC_Alyx *pAlyx = CNPC_Alyx::GetAlyx();
if ( pAlyx )
{
// Make Alyx totally hate this barnacle so that she saves the player.
int priority;
priority = pAlyx->IRelationPriority(sourceEnt);
pAlyx->AddEntityRelationship( sourceEnt, D_HT, priority + 5 );
}
#endif//HL2_EPISODIC
m_afPhysicsFlags |= PFLAG_ONBARNACLE;
ClearUseEntity();
return true;
}
return false;
}
void CHL2_Player::PlayerRunCommand(CUserCmd *ucmd, IMoveHelper *moveHelper)
{
// Handle FL_FROZEN.
if ( m_afPhysicsFlags & PFLAG_ONBARNACLE )
{
ucmd->forwardmove = 0;
ucmd->sidemove = 0;
ucmd->upmove = 0;
ucmd->buttons &= ~IN_USE;
}
// Can't use stuff while dead
if ( IsDead() )
{
ucmd->buttons &= ~IN_USE;
}
//Update our movement information
if ( ( ucmd->forwardmove != 0 ) || ( ucmd->sidemove != 0 ) || ( ucmd->upmove != 0 ) )
{
m_flIdleTime -= TICK_INTERVAL * 2.0f;
if ( m_flIdleTime < 0.0f )
{
m_flIdleTime = 0.0f;
}
m_flMoveTime += TICK_INTERVAL;
if ( m_flMoveTime > 4.0f )
{
m_flMoveTime = 4.0f;
}
}
else
{
m_flIdleTime += TICK_INTERVAL;
if ( m_flIdleTime > 4.0f )
{
m_flIdleTime = 4.0f;
}
m_flMoveTime -= TICK_INTERVAL * 2.0f;
if ( m_flMoveTime < 0.0f )
{
m_flMoveTime = 0.0f;
}
}
//Msg("Player time: [ACTIVE: %f]\t[IDLE: %f]\n", m_flMoveTime, m_flIdleTime );
BaseClass::PlayerRunCommand( ucmd, moveHelper );
}
//-----------------------------------------------------------------------------
// Purpose: Sets HL2 specific defaults.
//-----------------------------------------------------------------------------
void CHL2_Player::Spawn(void)
{
#ifndef HL2MP
#ifndef PORTAL
SetModel( "models/player.mdl" );
#endif
#endif
BaseClass::Spawn();
//
// Our player movement speed is set once here. This will override the cl_xxxx
// cvars unless they are set to be lower than this.
//
//m_flMaxspeed = 320;
if ( !IsSuitEquipped() )
StartWalking();
SuitPower_SetCharge( 100 );
m_Local.m_iHideHUD |= HIDEHUD_CHAT;
m_pPlayerAISquad = g_AI_SquadManager.FindCreateSquad(AllocPooledString(PLAYER_SQUADNAME));
InitSprinting();
// Setup our flashlight values
#ifdef HL2_EPISODIC
m_HL2Local.m_flFlashBattery = 100.0f;
#endif
GetPlayerProxy();
SetFlashlightPowerDrainScale( 1.0f );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::UpdateLocatorPosition( const Vector &vecPosition )
{
#ifdef HL2_EPISODIC
m_HL2Local.m_vecLocatorOrigin = vecPosition;
#endif//HL2_EPISODIC
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::InitSprinting( void )
{
StopSprinting();
}
//-----------------------------------------------------------------------------
// Purpose: Returns whether or not we are allowed to sprint now.
//-----------------------------------------------------------------------------
bool CHL2_Player::CanSprint()
{
return ( m_bSprintEnabled && // Only if sprint is enabled
!IsWalking() && // Not if we're walking
!( m_Local.m_bDucked && !m_Local.m_bDucking ) && // Nor if we're ducking
(GetWaterLevel() != 3) && // Certainly not underwater
(GlobalEntity_GetState("suit_no_sprint") != GLOBAL_ON) ); // Out of the question without the sprint module
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::StartAutoSprint()
{
if( IsSprinting() )
{
StopSprinting();
}
else
{
StartSprinting();
m_bIsAutoSprinting = true;
m_fAutoSprintMinTime = gpGlobals->curtime + 1.5f;
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::StartSprinting( void )
{
if( m_HL2Local.m_flSuitPower < 10 )
{
// Don't sprint unless there's a reasonable
// amount of suit power.
// debounce the button for sound playing
if ( m_afButtonPressed & IN_SPEED )
{
CPASAttenuationFilter filter( this );
filter.UsePredictionRules();
EmitSound( filter, entindex(), "HL2Player.SprintNoPower" );
}
return;
}
if( !SuitPower_AddDevice( SuitDeviceSprint ) )
return;
CPASAttenuationFilter filter( this );
filter.UsePredictionRules();
EmitSound( filter, entindex(), "HL2Player.SprintStart" );
/////
// SO2 - James
// Do not allow players to fire weapons while sprinting
CSO_Player *pSOPlayer = ToSOPlayer( this );
if ( pSOPlayer )
{
pSOPlayer->SetHolsteredWeapon( pSOPlayer->GetActiveWeapon() );
CBaseCombatWeapon *pHolsteredWeapon = pSOPlayer->GetHolsteredWeapon();
if ( pHolsteredWeapon )
pHolsteredWeapon->Holster();
}
/////
SetMaxSpeed( HL2_SPRINT_SPEED );
m_fIsSprinting = true;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::StopSprinting( void )
{
if ( m_HL2Local.m_bitsActiveDevices & SuitDeviceSprint.GetDeviceID() )
{
SuitPower_RemoveDevice( SuitDeviceSprint );
}
/////
// SO2 - James
// Do not allow players to fire weapons while sprinting
CSO_Player *pSOPlayer = ToSOPlayer( this );
if ( pSOPlayer )
{
CBaseCombatWeapon *pHolsteredWeapon = pSOPlayer->GetHolsteredWeapon();
if ( pHolsteredWeapon )
{
pHolsteredWeapon->Deploy();
pSOPlayer->SetHolsteredWeapon( NULL ); // weapon is no longer holstered; reset variable
}
}
/////
if( IsSuitEquipped() )
{
SetMaxSpeed( HL2_NORM_SPEED );
}
else
{
SetMaxSpeed( HL2_WALK_SPEED );
}
m_fIsSprinting = false;
if ( sv_stickysprint.GetBool() )
{
m_bIsAutoSprinting = false;
m_fAutoSprintMinTime = 0.0f;
}
}
//-----------------------------------------------------------------------------
// Purpose: Called to disable and enable sprint due to temporary circumstances:
// - Carrying a heavy object with the physcannon
//-----------------------------------------------------------------------------
void CHL2_Player::EnableSprint( bool bEnable )
{
if ( !bEnable && IsSprinting() )
{
StopSprinting();
}
m_bSprintEnabled = bEnable;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::StartWalking( void )
{
SetMaxSpeed( HL2_WALK_SPEED );
m_fIsWalking = true;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::StopWalking( void )
{
SetMaxSpeed( HL2_NORM_SPEED );
m_fIsWalking = false;
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CHL2_Player::CanZoom( CBaseEntity *pRequester )
{
if ( IsZooming() )
return false;
//Check our weapon
return true;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::ToggleZoom(void)
{
if( IsZooming() )
{
StopZooming();
}
else
{
StartZooming();
}
}
//-----------------------------------------------------------------------------
// Purpose: +zoom suit zoom
//-----------------------------------------------------------------------------
void CHL2_Player::StartZooming( void )
{
/////
// SO2 - James
// Disable suit zooming functionality
/*int iFOV = 25;
if ( SetFOV( this, iFOV, 0.4f ) )
{
m_HL2Local.m_bZooming = true;
}*/
/////
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHL2_Player::StopZooming( void )
{
/////
// SO2 - James
// Disable suit zooming functionality
/*int iFOV = GetZoomOwnerDesiredFOV( m_hZoomOwner );
if ( SetFOV( this, iFOV, 0.2f ) )
{
m_HL2Local.m_bZooming = false;
}*/
/////
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CHL2_Player::IsZooming( void )
{
if ( m_hZoomOwner != NULL )
return true;
return false;
}
class CPhysicsPlayerCallback : public IPhysicsPlayerControllerEvent
{
public:
int ShouldMoveTo( IPhysicsObject *pObject, const Vector &position )
{
CHL2_Player *pPlayer = (CHL2_Player *)pObject->GetGameData();
if ( pPlayer )
{
if ( pPlayer->TouchedPhysics() )
{
return 0;
}
}
return 1;
}
};
static CPhysicsPlayerCallback playerCallback;
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHL2_Player::InitVCollision( const Vector &vecAbsOrigin, const Vector &vecAbsVelocity )
{
BaseClass::InitVCollision( vecAbsOrigin, vecAbsVelocity );
// Setup the HL2 specific callback.
IPhysicsPlayerController *pPlayerController = GetPhysicsController();
if ( pPlayerController )
{
pPlayerController->SetEventHandler( &playerCallback );
}
}
CHL2_Player::~CHL2_Player( void )
{
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CHL2_Player::CommanderFindGoal( commandgoal_t *pGoal )
{
CAI_BaseNPC *pAllyNpc;
trace_t tr;
Vector vecTarget;
Vector forward;
EyeVectors( &forward );
//---------------------------------
// MASK_SHOT on purpose! So that you don't hit the invisible hulls of the NPCs.
CTraceFilterSkipTwoEntities filter( this, PhysCannonGetHeldEntity( GetActiveWeapon() ), COLLISION_GROUP_INTERACTIVE_DEBRIS );
UTIL_TraceLine( EyePosition(), EyePosition() + forward * MAX_COORD_RANGE, MASK_SHOT, &filter, &tr );
if( !tr.DidHitWorld() )
{
CUtlVector<CAI_BaseNPC *> Allies;
AISquadIter_t iter;
for ( pAllyNpc = m_pPlayerAISquad->GetFirstMember(&iter); pAllyNpc; pAllyNpc = m_pPlayerAISquad->GetNextMember(&iter) )
{
if ( pAllyNpc->IsCommandable() )
Allies.AddToTail( pAllyNpc );
}
for( int i = 0 ; i < Allies.Count() ; i++ )
{
if( Allies[ i ]->IsValidCommandTarget( tr.m_pEnt ) )
{
pGoal->m_pGoalEntity = tr.m_pEnt;
return true;
}
}
}
if( tr.fraction == 1.0 || (tr.surface.flags & SURF_SKY) )
{
// Move commands invalid against skybox.
pGoal->m_vecGoalLocation = tr.endpos;
return false;
}
if ( tr.m_pEnt->IsNPC() && ((CAI_BaseNPC *)(tr.m_pEnt))->IsCommandable() )
{
pGoal->m_vecGoalLocation = tr.m_pEnt->GetAbsOrigin();
}
else
{
vecTarget = tr.endpos;
Vector mins( -16, -16, 0 );
Vector maxs( 16, 16, 0 );
// Back up from whatever we hit so that there's enough space at the
// target location for a bounding box.
// Now trace down.
//UTIL_TraceLine( vecTarget, vecTarget - Vector( 0, 0, 8192 ), MASK_SOLID, this, COLLISION_GROUP_NONE, &tr );
UTIL_TraceHull( vecTarget + tr.plane.normal * 24,
vecTarget - Vector( 0, 0, 8192 ),
mins,
maxs,
MASK_SOLID_BRUSHONLY,
this,
COLLISION_GROUP_NONE,
&tr );
if ( !tr.startsolid )
pGoal->m_vecGoalLocation = tr.endpos;
else
pGoal->m_vecGoalLocation = vecTarget;
}
pAllyNpc = GetSquadCommandRepresentative();
if ( !pAllyNpc )
return false;
vecTarget = pGoal->m_vecGoalLocation;
if ( !pAllyNpc->FindNearestValidGoalPos( vecTarget, &pGoal->m_vecGoalLocation ) )
return false;
return ( ( vecTarget - pGoal->m_vecGoalLocation ).LengthSqr() < Square( 15*12 ) );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
CAI_BaseNPC *CHL2_Player::GetSquadCommandRepresentative()
{
if ( m_pPlayerAISquad != NULL )
{
CAI_BaseNPC *pAllyNpc = m_pPlayerAISquad->GetFirstMember();
if ( pAllyNpc )
{
return pAllyNpc->GetSquadCommandRepresentative();
}
}
return NULL;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
int CHL2_Player::GetNumSquadCommandables()
{
AISquadIter_t iter;
int c = 0;
for ( CAI_BaseNPC *pAllyNpc = m_pPlayerAISquad->GetFirstMember(&iter); pAllyNpc; pAllyNpc = m_pPlayerAISquad->GetNextMember(&iter) )
{
if ( pAllyNpc->IsCommandable() )
c++;
}
return c;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
int CHL2_Player::GetNumSquadCommandableMedics()
{
AISquadIter_t iter;
int c = 0;
for ( CAI_BaseNPC *pAllyNpc = m_pPlayerAISquad->GetFirstMember(&iter); pAllyNpc; pAllyNpc = m_pPlayerAISquad->GetNextMember(&iter) )
{
if ( pAllyNpc->IsCommandable() && pAllyNpc->IsMedic() )
c++;
}
return c;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::CommanderUpdate()
{
CAI_BaseNPC *pCommandRepresentative = GetSquadCommandRepresentative();
bool bFollowMode = false;
if ( pCommandRepresentative )
{
bFollowMode = ( pCommandRepresentative->GetCommandGoal() == vec3_invalid );
// set the variables for network transmission (to show on the hud)
m_HL2Local.m_iSquadMemberCount = GetNumSquadCommandables();
m_HL2Local.m_iSquadMedicCount = GetNumSquadCommandableMedics();
m_HL2Local.m_fSquadInFollowMode = bFollowMode;
// debugging code for displaying extra squad indicators
/*
char *pszMoving = "";
AISquadIter_t iter;
for ( CAI_BaseNPC *pAllyNpc = m_pPlayerAISquad->GetFirstMember(&iter); pAllyNpc; pAllyNpc = m_pPlayerAISquad->GetNextMember(&iter) )
{
if ( pAllyNpc->IsCommandMoving() )
{
pszMoving = "<-";
break;
}
}
NDebugOverlay::ScreenText(
0.932, 0.919,
CFmtStr( "%d|%c%s", GetNumSquadCommandables(), ( bFollowMode ) ? 'F' : 'S', pszMoving ),
255, 128, 0, 128,
0 );
*/
}
else
{
m_HL2Local.m_iSquadMemberCount = 0;
m_HL2Local.m_iSquadMedicCount = 0;
m_HL2Local.m_fSquadInFollowMode = true;
}
if ( m_QueuedCommand != CC_NONE && ( m_QueuedCommand == CC_FOLLOW || gpGlobals->realtime - m_RealTimeLastSquadCommand >= player_squad_double_tap_time.GetFloat() ) )
{
CommanderExecute( m_QueuedCommand );
m_QueuedCommand = CC_NONE;
}
else if ( !bFollowMode && pCommandRepresentative && m_CommanderUpdateTimer.Expired() && player_squad_transient_commands.GetBool() )
{
m_CommanderUpdateTimer.Set(2.5);
if ( pCommandRepresentative->ShouldAutoSummon() )
CommanderExecute( CC_FOLLOW );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//
// bHandled - indicates whether to continue delivering this order to
// all allies. Allows us to stop delivering certain types of orders once we find
// a suitable candidate. (like picking up a single weapon. We don't wish for
// all allies to respond and try to pick up one weapon).
//-----------------------------------------------------------------------------
bool CHL2_Player::CommanderExecuteOne( CAI_BaseNPC *pNpc, const commandgoal_t &goal, CAI_BaseNPC **Allies, int numAllies )
{
if ( goal.m_pGoalEntity )
{
return pNpc->TargetOrder( goal.m_pGoalEntity, Allies, numAllies );
}
else if ( pNpc->IsInPlayerSquad() )
{
pNpc->MoveOrder( goal.m_vecGoalLocation, Allies, numAllies );
}
return true;
}
//---------------------------------------------------------
//---------------------------------------------------------
void CHL2_Player::CommanderExecute( CommanderCommand_t command )
{
CAI_BaseNPC *pPlayerSquadLeader = GetSquadCommandRepresentative();
if ( !pPlayerSquadLeader )
{
EmitSound( "HL2Player.UseDeny" );
return;
}
int i;
CUtlVector<CAI_BaseNPC *> Allies;
commandgoal_t goal;
if ( command == CC_TOGGLE )
{
if ( pPlayerSquadLeader->GetCommandGoal() != vec3_invalid )
command = CC_FOLLOW;
else
command = CC_SEND;
}
else
{
if ( command == CC_FOLLOW && pPlayerSquadLeader->GetCommandGoal() == vec3_invalid )
return;
}
if ( command == CC_FOLLOW )
{
goal.m_pGoalEntity = this;
goal.m_vecGoalLocation = vec3_invalid;
}
else
{
goal.m_pGoalEntity = NULL;
goal.m_vecGoalLocation = vec3_invalid;
// Find a goal for ourselves.
if( !CommanderFindGoal( &goal ) )
{
EmitSound( "HL2Player.UseDeny" );
return; // just keep following
}
}
#ifdef _DEBUG
if( goal.m_pGoalEntity == NULL && goal.m_vecGoalLocation == vec3_invalid )
{
DevMsg( 1, "**ERROR: Someone sent an invalid goal to CommanderExecute!\n" );
}
#endif // _DEBUG
AISquadIter_t iter;
for ( CAI_BaseNPC *pAllyNpc = m_pPlayerAISquad->GetFirstMember(&iter); pAllyNpc; pAllyNpc = m_pPlayerAISquad->GetNextMember(&iter) )
{
if ( pAllyNpc->IsCommandable() )
Allies.AddToTail( pAllyNpc );
}
//---------------------------------
// If the trace hits an NPC, send all ally NPCs a "target" order. Always
// goes to targeted one first
#ifdef DEBUG
int nAIs = g_AI_Manager.NumAIs();
#endif
CAI_BaseNPC * pTargetNpc = (goal.m_pGoalEntity) ? goal.m_pGoalEntity->MyNPCPointer() : NULL;
bool bHandled = false;
if( pTargetNpc )
{
bHandled = !CommanderExecuteOne( pTargetNpc, goal, Allies.Base(), Allies.Count() );
}
for ( i = 0; !bHandled && i < Allies.Count(); i++ )
{
if ( Allies[i] != pTargetNpc && Allies[i]->IsPlayerAlly() )
{
bHandled = !CommanderExecuteOne( Allies[i], goal, Allies.Base(), Allies.Count() );
}
Assert( nAIs == g_AI_Manager.NumAIs() ); // not coded to support mutating set of NPCs
}
}
//-----------------------------------------------------------------------------
// Enter/exit commander mode, manage ally selection.
//-----------------------------------------------------------------------------
void CHL2_Player::CommanderMode()
{
float commandInterval = gpGlobals->realtime - m_RealTimeLastSquadCommand;
m_RealTimeLastSquadCommand = gpGlobals->realtime;
if ( commandInterval < player_squad_double_tap_time.GetFloat() )
{
m_QueuedCommand = CC_FOLLOW;
}
else
{
m_QueuedCommand = (player_squad_transient_commands.GetBool()) ? CC_SEND : CC_TOGGLE;
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : iImpulse -
//-----------------------------------------------------------------------------
void CHL2_Player::CheatImpulseCommands( int iImpulse )
{
switch( iImpulse )
{
case 50:
{
CommanderMode();
break;
}
case 51:
{
// Cheat to create a dynamic resupply item
Vector vecForward;
AngleVectors( EyeAngles(), &vecForward );
CBaseEntity *pItem = (CBaseEntity *)CreateEntityByName( "item_dynamic_resupply" );
if ( pItem )
{
Vector vecOrigin = GetAbsOrigin() + vecForward * 256 + Vector(0,0,64);
QAngle vecAngles( 0, GetAbsAngles().y - 90, 0 );
pItem->SetAbsOrigin( vecOrigin );
pItem->SetAbsAngles( vecAngles );
pItem->KeyValue( "targetname", "resupply" );
pItem->Spawn();
pItem->Activate();
}
break;
}
case 52:
{
// Rangefinder
trace_t tr;
UTIL_TraceLine( EyePosition(), EyePosition() + EyeDirection3D() * MAX_COORD_RANGE, MASK_SHOT, this, COLLISION_GROUP_NONE, &tr );
if( tr.fraction != 1.0 )
{
float flDist = (tr.startpos - tr.endpos).Length();
float flDist2D = (tr.startpos - tr.endpos).Length2D();
DevMsg( 1,"\nStartPos: %.4f %.4f %.4f --- EndPos: %.4f %.4f %.4f\n", tr.startpos.x,tr.startpos.y,tr.startpos.z,tr.endpos.x,tr.endpos.y,tr.endpos.z );
DevMsg( 1,"3D Distance: %.4f units (%.2f feet) --- 2D Distance: %.4f units (%.2f feet)\n", flDist, flDist / 12.0, flDist2D, flDist2D / 12.0 );
}
break;
}
default:
BaseClass::CheatImpulseCommands( iImpulse );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHL2_Player::SetupVisibility( CBaseEntity *pViewEntity, unsigned char *pvs, int pvssize )
{
BaseClass::SetupVisibility( pViewEntity, pvs, pvssize );
int area = pViewEntity ? pViewEntity->NetworkProp()->AreaNum() : NetworkProp()->AreaNum();
PointCameraSetupVisibility( this, area, pvs, pvssize );
// If the intro script is playing, we want to get it's visibility points
if ( g_hIntroScript )
{
Vector vecOrigin;
CBaseEntity *pCamera;
if ( g_hIntroScript->GetIncludedPVSOrigin( &vecOrigin, &pCamera ) )
{
// If it's a point camera, turn it on
CPointCamera *pPointCamera = dynamic_cast< CPointCamera* >(pCamera);
if ( pPointCamera )
{
pPointCamera->SetActive( true );
}
engine->AddOriginToPVS( vecOrigin );
}
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::SuitPower_Update( void )
{
if( SuitPower_ShouldRecharge() )
{
SuitPower_Charge( SUITPOWER_CHARGE_RATE * gpGlobals->frametime );
}
else if( m_HL2Local.m_bitsActiveDevices )
{
float flPowerLoad = m_flSuitPowerLoad;
//Since stickysprint quickly shuts off sprint if it isn't being used, this isn't an issue.
if ( !sv_stickysprint.GetBool() )
{
if( SuitPower_IsDeviceActive(SuitDeviceSprint) )
{
if( !fabs(GetAbsVelocity().x) && !fabs(GetAbsVelocity().y) )
{
// If player's not moving, don't drain sprint juice.
flPowerLoad -= SuitDeviceSprint.GetDeviceDrainRate();
}
}
}
if( SuitPower_IsDeviceActive(SuitDeviceFlashlight) )
{
float factor;
factor = 1.0f / m_flFlashlightPowerDrainScale;
flPowerLoad -= ( SuitDeviceFlashlight.GetDeviceDrainRate() * (1.0f - factor) );
}
if( !SuitPower_Drain( flPowerLoad * gpGlobals->frametime ) )
{
// TURN OFF ALL DEVICES!!
if( IsSprinting() )
{
StopSprinting();
}
if ( Flashlight_UseLegacyVersion() )
{
if( FlashlightIsOn() )
{
#ifndef HL2MP
FlashlightTurnOff();
#endif
}
}
}
if ( Flashlight_UseLegacyVersion() )
{
// turn off flashlight a little bit after it hits below one aux power notch (5%)
if( m_HL2Local.m_flSuitPower < 4.8f && FlashlightIsOn() )
{
#ifndef HL2MP
FlashlightTurnOff();
#endif
}
}
}
}
//-----------------------------------------------------------------------------
// Charge battery fully, turn off all devices.
//-----------------------------------------------------------------------------
void CHL2_Player::SuitPower_Initialize( void )
{
m_HL2Local.m_bitsActiveDevices = 0x00000000;
m_HL2Local.m_flSuitPower = 100.0;
m_flSuitPowerLoad = 0.0;
}
//-----------------------------------------------------------------------------
// Purpose: Interface to drain power from the suit's power supply.
// Input: Amount of charge to remove (expressed as percentage of full charge)
// Output: Returns TRUE if successful, FALSE if not enough power available.
//-----------------------------------------------------------------------------
bool CHL2_Player::SuitPower_Drain( float flPower )
{
// Suitpower cheat on?
if ( sv_infinite_aux_power.GetBool() )
return true;
m_HL2Local.m_flSuitPower -= flPower;
if( m_HL2Local.m_flSuitPower < 0.0 )
{
// Power is depleted!
// Clamp and fail
m_HL2Local.m_flSuitPower = 0.0;
return false;
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Interface to add power to the suit's power supply
// Input: Amount of charge to add
//-----------------------------------------------------------------------------
void CHL2_Player::SuitPower_Charge( float flPower )
{
m_HL2Local.m_flSuitPower += flPower;
if( m_HL2Local.m_flSuitPower > 100.0 )
{
// Full charge, clamp.
m_HL2Local.m_flSuitPower = 100.0;
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CHL2_Player::SuitPower_IsDeviceActive( const CSuitPowerDevice &device )
{
return (m_HL2Local.m_bitsActiveDevices & device.GetDeviceID()) != 0;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CHL2_Player::SuitPower_AddDevice( const CSuitPowerDevice &device )
{
// Make sure this device is NOT active!!
if( m_HL2Local.m_bitsActiveDevices & device.GetDeviceID() )
return false;
if( !IsSuitEquipped() )
return false;
m_HL2Local.m_bitsActiveDevices |= device.GetDeviceID();
m_flSuitPowerLoad += device.GetDeviceDrainRate();
return true;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CHL2_Player::SuitPower_RemoveDevice( const CSuitPowerDevice &device )
{
// Make sure this device is active!!
if( ! (m_HL2Local.m_bitsActiveDevices & device.GetDeviceID()) )
return false;
if( !IsSuitEquipped() )
return false;
// Take a little bit of suit power when you disable a device. If the device is shutting off
// because the battery is drained, no harm done, the battery charge cannot go below 0.
// This code in combination with the delay before the suit can start recharging are a defense
// against exploits where the player could rapidly tap sprint and never run out of power.
SuitPower_Drain( device.GetDeviceDrainRate() * 0.1f );
m_HL2Local.m_bitsActiveDevices &= ~device.GetDeviceID();
m_flSuitPowerLoad -= device.GetDeviceDrainRate();
if( m_HL2Local.m_bitsActiveDevices == 0x00000000 )
{
// With this device turned off, we can set this timer which tells us when the
// suit power system entered a no-load state.
m_flTimeAllSuitDevicesOff = gpGlobals->curtime;
}
return true;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
#define SUITPOWER_BEGIN_RECHARGE_DELAY 0.5f
bool CHL2_Player::SuitPower_ShouldRecharge( void )
{
// Make sure all devices are off.
if( m_HL2Local.m_bitsActiveDevices != 0x00000000 )
return false;
// Is the system fully charged?
if( m_HL2Local.m_flSuitPower >= 100.0f )
return false;
// Has the system been in a no-load state for long enough
// to begin recharging?
if( gpGlobals->curtime < m_flTimeAllSuitDevicesOff + SUITPOWER_BEGIN_RECHARGE_DELAY )
return false;
return true;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
ConVar sk_battery( "sk_battery","0" );
bool CHL2_Player::ApplyBattery( float powerMultiplier )
{
const float MAX_NORMAL_BATTERY = 100;
if ((ArmorValue() < MAX_NORMAL_BATTERY) && IsSuitEquipped())
{
int pct;
char szcharge[64];
IncrementArmorValue( sk_battery.GetFloat() * powerMultiplier, MAX_NORMAL_BATTERY );
CPASAttenuationFilter filter( this, "ItemBattery.Touch" );
EmitSound( filter, entindex(), "ItemBattery.Touch" );
CSingleUserRecipientFilter user( this );
user.MakeReliable();
UserMessageBegin( user, "ItemPickup" );
WRITE_STRING( "item_battery" );
MessageEnd();
// Suit reports new power level
// For some reason this wasn't working in release build -- round it.
pct = (int)( (float)(ArmorValue() * 100.0) * (1.0/MAX_NORMAL_BATTERY) + 0.5);
pct = (pct / 5);
if (pct > 0)
pct--;
Q_snprintf( szcharge,sizeof(szcharge),"!HEV_%1dP", pct );
//UTIL_EmitSoundSuit(edict(), szcharge);
//SetSuitUpdate(szcharge, FALSE, SUIT_NEXT_IN_30SEC);
return true;
}
return false;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
int CHL2_Player::FlashlightIsOn( void )
{
return IsEffectActive( EF_DIMLIGHT );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::FlashlightTurnOn( void )
{
if( m_bFlashlightDisabled )
return;
if ( Flashlight_UseLegacyVersion() )
{
if( !SuitPower_AddDevice( SuitDeviceFlashlight ) )
return;
}
#ifdef HL2_DLL
if( !IsSuitEquipped() )
return;
#endif
AddEffects( EF_DIMLIGHT );
EmitSound( "HL2Player.FlashLightOn" );
variant_t flashlighton;
flashlighton.SetFloat( m_HL2Local.m_flSuitPower / 100.0f );
FirePlayerProxyOutput( "OnFlashlightOn", flashlighton, this, this );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::FlashlightTurnOff( void )
{
if ( Flashlight_UseLegacyVersion() )
{
if( !SuitPower_RemoveDevice( SuitDeviceFlashlight ) )
return;
}
RemoveEffects( EF_DIMLIGHT );
EmitSound( "HL2Player.FlashLightOff" );
variant_t flashlightoff;
flashlightoff.SetFloat( m_HL2Local.m_flSuitPower / 100.0f );
FirePlayerProxyOutput( "OnFlashlightOff", flashlightoff, this, this );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
#define FLASHLIGHT_RANGE Square(600)
bool CHL2_Player::IsIlluminatedByFlashlight( CBaseEntity *pEntity, float *flReturnDot )
{
if( !FlashlightIsOn() )
return false;
if( pEntity->Classify() == CLASS_BARNACLE && pEntity->GetEnemy() == this )
{
// As long as my flashlight is on, the barnacle that's pulling me in is considered illuminated.
// This is because players often shine their flashlights at Alyx when they are in a barnacle's
// grasp, and wonder why Alyx isn't helping. Alyx isn't helping because the light isn't pointed
// at the barnacle. This will allow Alyx to see the barnacle no matter which way the light is pointed.
return true;
}
// Within 50 feet?
float flDistSqr = GetAbsOrigin().DistToSqr(pEntity->GetAbsOrigin());
if( flDistSqr > FLASHLIGHT_RANGE )
return false;
// Within 45 degrees?
Vector vecSpot = pEntity->WorldSpaceCenter();
Vector los;
// If the eyeposition is too close, move it back. Solves problems
// caused by the player being too close the target.
if ( flDistSqr < (128 * 128) )
{
Vector vecForward;
EyeVectors( &vecForward );
Vector vecMovedEyePos = EyePosition() - (vecForward * 128);
los = ( vecSpot - vecMovedEyePos );
}
else
{
los = ( vecSpot - EyePosition() );
}
VectorNormalize( los );
Vector facingDir = EyeDirection3D( );
float flDot = DotProduct( los, facingDir );
if ( flReturnDot )
{
*flReturnDot = flDot;
}
if ( flDot < 0.92387f )
return false;
if( !FVisible(pEntity) )
return false;
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Let NPCs know when the flashlight is trained on them
//-----------------------------------------------------------------------------
void CHL2_Player::CheckFlashlight( void )
{
if ( !FlashlightIsOn() )
return;
if ( m_flNextFlashlightCheckTime > gpGlobals->curtime )
return;
m_flNextFlashlightCheckTime = gpGlobals->curtime + FLASHLIGHT_NPC_CHECK_INTERVAL;
// Loop through NPCs looking for illuminated ones
for ( int i = 0; i < g_AI_Manager.NumAIs(); i++ )
{
CAI_BaseNPC *pNPC = g_AI_Manager.AccessAIs()[i];
float flDot;
if ( IsIlluminatedByFlashlight( pNPC, &flDot ) )
{
pNPC->PlayerHasIlluminatedNPC( this, flDot );
}
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::SetPlayerUnderwater( bool state )
{
if ( state )
{
SuitPower_AddDevice( SuitDeviceBreather );
}
else
{
SuitPower_RemoveDevice( SuitDeviceBreather );
}
BaseClass::SetPlayerUnderwater( state );
}
//-----------------------------------------------------------------------------
bool CHL2_Player::PassesDamageFilter( const CTakeDamageInfo &info )
{
CBaseEntity *pAttacker = info.GetAttacker();
if( pAttacker && pAttacker->MyNPCPointer() && pAttacker->MyNPCPointer()->IsPlayerAlly() )
{
return false;
}
if( m_hPlayerProxy && !m_hPlayerProxy->PassesDamageFilter( info ) )
{
return false;
}
return BaseClass::PassesDamageFilter( info );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHL2_Player::SetFlashlightEnabled( bool bState )
{
m_bFlashlightDisabled = !bState;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::InputDisableFlashlight( inputdata_t &inputdata )
{
if( FlashlightIsOn() )
FlashlightTurnOff();
SetFlashlightEnabled( false );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::InputEnableFlashlight( inputdata_t &inputdata )
{
SetFlashlightEnabled( true );
}
//-----------------------------------------------------------------------------
// Purpose: Prevent the player from taking fall damage for [n] seconds, but
// reset back to taking fall damage after the first impact (so players will be
// hurt if they bounce off what they hit). This is the original behavior.
//-----------------------------------------------------------------------------
void CHL2_Player::InputIgnoreFallDamage( inputdata_t &inputdata )
{
float timeToIgnore = inputdata.value.Float();
if ( timeToIgnore <= 0.0 )
timeToIgnore = TIME_IGNORE_FALL_DAMAGE;
m_flTimeIgnoreFallDamage = gpGlobals->curtime + timeToIgnore;
m_bIgnoreFallDamageResetAfterImpact = true;
}
//-----------------------------------------------------------------------------
// Purpose: Absolutely prevent the player from taking fall damage for [n] seconds.
//-----------------------------------------------------------------------------
void CHL2_Player::InputIgnoreFallDamageWithoutReset( inputdata_t &inputdata )
{
float timeToIgnore = inputdata.value.Float();
if ( timeToIgnore <= 0.0 )
timeToIgnore = TIME_IGNORE_FALL_DAMAGE;
m_flTimeIgnoreFallDamage = gpGlobals->curtime + timeToIgnore;
m_bIgnoreFallDamageResetAfterImpact = false;
}
//-----------------------------------------------------------------------------
// Purpose: Notification of a player's npc ally in the players squad being killed
//-----------------------------------------------------------------------------
void CHL2_Player::OnSquadMemberKilled( inputdata_t &data )
{
// send a message to the client, to notify the hud of the loss
CSingleUserRecipientFilter user( this );
user.MakeReliable();
UserMessageBegin( user, "SquadMemberDied" );
MessageEnd();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHL2_Player::NotifyFriendsOfDamage( CBaseEntity *pAttackerEntity )
{
CAI_BaseNPC *pAttacker = pAttackerEntity->MyNPCPointer();
if ( pAttacker )
{
const Vector &origin = GetAbsOrigin();
for ( int i = 0; i < g_AI_Manager.NumAIs(); i++ )
{
const float NEAR_Z = 12*12;
const float NEAR_XY_SQ = Square( 50*12 );
CAI_BaseNPC *pNpc = g_AI_Manager.AccessAIs()[i];
if ( pNpc->IsPlayerAlly() )
{
const Vector &originNpc = pNpc->GetAbsOrigin();
if ( fabsf( originNpc.z - origin.z ) < NEAR_Z )
{
if ( (originNpc.AsVector2D() - origin.AsVector2D()).LengthSqr() < NEAR_XY_SQ )
{
pNpc->OnFriendDamaged( this, pAttacker );
}
}
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
ConVar test_massive_dmg("test_massive_dmg", "30" );
ConVar test_massive_dmg_clip("test_massive_dmg_clip", "0.5" );
int CHL2_Player::OnTakeDamage( const CTakeDamageInfo &info )
{
if ( GlobalEntity_GetState( "gordon_invulnerable" ) == GLOBAL_ON )
return 0;
// ignore fall damage if instructed to do so by input
if ( ( info.GetDamageType() & DMG_FALL ) && m_flTimeIgnoreFallDamage > gpGlobals->curtime )
{
// usually, we will reset the input flag after the first impact. However there is another input that
// prevents this behavior.
if ( m_bIgnoreFallDamageResetAfterImpact )
{
m_flTimeIgnoreFallDamage = 0;
}
return 0;
}
if( info.GetDamageType() & DMG_BLAST_SURFACE )
{
if( GetWaterLevel() > 2 )
{
// Don't take blast damage from anything above the surface.
if( info.GetInflictor()->GetWaterLevel() == 0 )
{
return 0;
}
}
}
if ( info.GetDamage() > 0.0f )
{
m_flLastDamageTime = gpGlobals->curtime;
if ( info.GetAttacker() )
NotifyFriendsOfDamage( info.GetAttacker() );
}
// Modify the amount of damage the player takes, based on skill.
CTakeDamageInfo playerDamage = info;
// Should we run this damage through the skill level adjustment?
bool bAdjustForSkillLevel = true;
if( info.GetDamageType() == DMG_GENERIC && info.GetAttacker() == this && info.GetInflictor() == this )
{
// Only do a skill level adjustment if the player isn't his own attacker AND inflictor.
// This prevents damage from SetHealth() inputs from being adjusted for skill level.
bAdjustForSkillLevel = false;
}
if ( GetVehicleEntity() != NULL && GlobalEntity_GetState("gordon_protect_driver") == GLOBAL_ON )
{
if( playerDamage.GetDamage() > test_massive_dmg.GetFloat() && playerDamage.GetInflictor() == GetVehicleEntity() && (playerDamage.GetDamageType() & DMG_CRUSH) )
{
playerDamage.ScaleDamage( test_massive_dmg_clip.GetFloat() / playerDamage.GetDamage() );
}
}
if( bAdjustForSkillLevel )
{
playerDamage.AdjustPlayerDamageTakenForSkillLevel();
}
gamestats->Event_PlayerDamage( this, info );
return BaseClass::OnTakeDamage( playerDamage );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &info -
//-----------------------------------------------------------------------------
int CHL2_Player::OnTakeDamage_Alive( const CTakeDamageInfo &info )
{
// Drown
if( info.GetDamageType() & DMG_DROWN )
{
if( m_idrowndmg == m_idrownrestored )
{
EmitSound( "Player.DrownStart" );
}
else
{
EmitSound( "Player.DrownContinue" );
}
}
// Burnt
if ( info.GetDamageType() & DMG_BURN )
{
EmitSound( "HL2Player.BurnPain" );
}
if( (info.GetDamageType() & DMG_SLASH) && hl2_episodic.GetBool() )
{
if( m_afPhysicsFlags & PFLAG_USING )
{
// Stop the player using a rotating button for a short time if hit by a creature's melee attack.
// This is for the antlion burrow-corking training in EP1 (sjb).
SuspendUse( 0.5f );
}
}
// Call the base class implementation
return BaseClass::OnTakeDamage_Alive( info );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::OnDamagedByExplosion( const CTakeDamageInfo &info )
{
if ( info.GetInflictor() && info.GetInflictor()->ClassMatches( "mortarshell" ) )
{
// No ear ringing for mortar
UTIL_ScreenShake( info.GetInflictor()->GetAbsOrigin(), 4.0, 1.0, 0.5, 1000, SHAKE_START, false );
return;
}
BaseClass::OnDamagedByExplosion( info );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CHL2_Player::ShouldShootMissTarget( CBaseCombatCharacter *pAttacker )
{
if( gpGlobals->curtime > m_flTargetFindTime )
{
// Put this off into the future again.
m_flTargetFindTime = gpGlobals->curtime + random->RandomFloat( 3, 5 );
return true;
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose: Notifies Alyx that player has put a combine ball into a socket so she can comment on it.
// Input : pCombineBall - ball the was socketed
//-----------------------------------------------------------------------------
void CHL2_Player::CombineBallSocketed( CPropCombineBall *pCombineBall )
{
#ifdef HL2_EPISODIC
CNPC_Alyx *pAlyx = CNPC_Alyx::GetAlyx();
if ( pAlyx )
{
pAlyx->CombineBallSocketed( pCombineBall->NumBounces() );
}
#endif
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::Event_KilledOther( CBaseEntity *pVictim, const CTakeDamageInfo &info )
{
BaseClass::Event_KilledOther( pVictim, info );
#ifdef HL2_EPISODIC
CAI_BaseNPC **ppAIs = g_AI_Manager.AccessAIs();
for ( int i = 0; i < g_AI_Manager.NumAIs(); i++ )
{
if ( ppAIs[i] && ppAIs[i]->IRelationType(this) == D_LI )
{
ppAIs[i]->OnPlayerKilledOther( pVictim, info );
}
}
#endif
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::Event_Killed( const CTakeDamageInfo &info )
{
BaseClass::Event_Killed( info );
FirePlayerProxyOutput( "PlayerDied", variant_t(), this, this );
NotifyScriptsOfDeath();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::NotifyScriptsOfDeath( void )
{
CBaseEntity *pEnt = gEntList.FindEntityByClassname( NULL, "scripted_sequence" );
while( pEnt )
{
variant_t emptyVariant;
pEnt->AcceptInput( "ScriptPlayerDeath", NULL, NULL, emptyVariant, 0 );
pEnt = gEntList.FindEntityByClassname( pEnt, "scripted_sequence" );
}
pEnt = gEntList.FindEntityByClassname( NULL, "logic_choreographed_scene" );
while( pEnt )
{
variant_t emptyVariant;
pEnt->AcceptInput( "ScriptPlayerDeath", NULL, NULL, emptyVariant, 0 );
pEnt = gEntList.FindEntityByClassname( pEnt, "logic_choreographed_scene" );
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::GetAutoaimVector( autoaim_params_t ¶ms )
{
BaseClass::GetAutoaimVector( params );
if ( IsX360() )
{
if( IsInAVehicle() )
{
if( m_hLockedAutoAimEntity && m_hLockedAutoAimEntity->IsAlive() && ShouldKeepLockedAutoaimTarget(m_hLockedAutoAimEntity) )
{
if( params.m_hAutoAimEntity && params.m_hAutoAimEntity != m_hLockedAutoAimEntity )
{
// Autoaim has picked a new target. Switch.
m_hLockedAutoAimEntity = params.m_hAutoAimEntity;
}
// Ignore autoaim and just keep aiming at this target.
params.m_hAutoAimEntity = m_hLockedAutoAimEntity;
Vector vecTarget = m_hLockedAutoAimEntity->BodyTarget( EyePosition(), false );
Vector vecDir = vecTarget - EyePosition();
VectorNormalize( vecDir );
params.m_vecAutoAimDir = vecDir;
params.m_vecAutoAimPoint = vecTarget;
return;
}
else
{
m_hLockedAutoAimEntity = NULL;
}
}
// If the player manually gets his crosshair onto a target, make that target sticky
if( params.m_fScale != AUTOAIM_SCALE_DIRECT_ONLY )
{
// Only affect this for 'real' queries
//if( params.m_hAutoAimEntity && params.m_bOnTargetNatural )
if( params.m_hAutoAimEntity )
{
// Turn on sticky.
m_HL2Local.m_bStickyAutoAim = true;
if( IsInAVehicle() )
{
m_hLockedAutoAimEntity = params.m_hAutoAimEntity;
}
}
else if( !params.m_hAutoAimEntity )
{
// Turn off sticky only if there's no target at all.
m_HL2Local.m_bStickyAutoAim = false;
m_hLockedAutoAimEntity = NULL;
}
}
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CHL2_Player::ShouldKeepLockedAutoaimTarget( EHANDLE hLockedTarget )
{
Vector vecLooking;
Vector vecToTarget;
vecToTarget = hLockedTarget->WorldSpaceCenter() - EyePosition();
float flDist = vecToTarget.Length2D();
VectorNormalize( vecToTarget );
if( flDist > autoaim_max_dist.GetFloat() )
return false;
float flDot;
vecLooking = EyeDirection3D();
flDot = DotProduct( vecLooking, vecToTarget );
if( flDot < autoaim_unlock_target.GetFloat() )
return false;
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : iCount -
// iAmmoIndex -
// bSuppressSound -
// Output : int
//-----------------------------------------------------------------------------
int CHL2_Player::GiveAmmo( int nCount, int nAmmoIndex, bool bSuppressSound)
{
// Don't try to give the player invalid ammo indices.
if (nAmmoIndex < 0)
return 0;
bool bCheckAutoSwitch = false;
if (!HasAnyAmmoOfType(nAmmoIndex))
{
bCheckAutoSwitch = true;
}
int nAdd = BaseClass::GiveAmmo(nCount, nAmmoIndex, bSuppressSound);
if ( nCount > 0 && nAdd == 0 )
{
// we've been denied the pickup, display a hud icon to show that
CSingleUserRecipientFilter user( this );
user.MakeReliable();
UserMessageBegin( user, "AmmoDenied" );
WRITE_SHORT( nAmmoIndex );
MessageEnd();
}
//
// If I was dry on ammo for my best weapon and justed picked up ammo for it,
// autoswitch to my best weapon now.
//
if (bCheckAutoSwitch)
{
CBaseCombatWeapon *pWeapon = g_pGameRules->GetNextBestWeapon(this, GetActiveWeapon());
if ( pWeapon && pWeapon->GetPrimaryAmmoType() == nAmmoIndex )
{
SwitchToNextBestWeapon(GetActiveWeapon());
}
}
return nAdd;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CHL2_Player::Weapon_CanUse( CBaseCombatWeapon *pWeapon )
{
#ifndef HL2MP
if ( pWeapon->ClassMatches( "weapon_stunstick" ) )
{
if ( ApplyBattery( 0.5 ) )
UTIL_Remove( pWeapon );
return false;
}
#endif
return BaseClass::Weapon_CanUse( pWeapon );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pWeapon -
//-----------------------------------------------------------------------------
void CHL2_Player::Weapon_Equip( CBaseCombatWeapon *pWeapon )
{
#if HL2_SINGLE_PRIMARY_WEAPON_MODE
if ( pWeapon->GetSlot() == WEAPON_PRIMARY_SLOT )
{
Weapon_DropSlot( WEAPON_PRIMARY_SLOT );
}
#endif
if( GetActiveWeapon() == NULL )
{
m_HL2Local.m_bWeaponLowered = false;
}
BaseClass::Weapon_Equip( pWeapon );
}
//-----------------------------------------------------------------------------
// Purpose: Player reacts to bumping a weapon.
// Input : pWeapon - the weapon that the player bumped into.
// Output : Returns true if player picked up the weapon
//-----------------------------------------------------------------------------
bool CHL2_Player::BumpWeapon( CBaseCombatWeapon *pWeapon )
{
#if HL2_SINGLE_PRIMARY_WEAPON_MODE
CBaseCombatCharacter *pOwner = pWeapon->GetOwner();
// Can I have this weapon type?
if ( pOwner || !Weapon_CanUse( pWeapon ) || !g_pGameRules->CanHavePlayerItem( this, pWeapon ) )
{
if ( gEvilImpulse101 )
{
UTIL_Remove( pWeapon );
}
return false;
}
// ----------------------------------------
// If I already have it just take the ammo
// ----------------------------------------
if (Weapon_OwnsThisType( pWeapon->GetClassname(), pWeapon->GetSubType()))
{
//Only remove the weapon if we attained ammo from it
if ( Weapon_EquipAmmoOnly( pWeapon ) == false )
return false;
// Only remove me if I have no ammo left
// Can't just check HasAnyAmmo because if I don't use clips, I want to be removed,
if ( pWeapon->UsesClipsForAmmo1() && pWeapon->HasPrimaryAmmo() )
return false;
UTIL_Remove( pWeapon );
return false;
}
// -------------------------
// Otherwise take the weapon
// -------------------------
else
{
//Make sure we're not trying to take a new weapon type we already have
if ( Weapon_SlotOccupied( pWeapon ) )
{
CBaseCombatWeapon *pActiveWeapon = Weapon_GetSlot( WEAPON_PRIMARY_SLOT );
if ( pActiveWeapon != NULL && pActiveWeapon->HasAnyAmmo() == false && Weapon_CanSwitchTo( pWeapon ) )
{
Weapon_Equip( pWeapon );
return true;
}
//Attempt to take ammo if this is the gun we're holding already
if ( Weapon_OwnsThisType( pWeapon->GetClassname(), pWeapon->GetSubType() ) )
{
Weapon_EquipAmmoOnly( pWeapon );
}
return false;
}
pWeapon->CheckRespawn();
pWeapon->AddSolidFlags( FSOLID_NOT_SOLID );
pWeapon->AddEffects( EF_NODRAW );
Weapon_Equip( pWeapon );
EmitSound( "HL2Player.PickupWeapon" );
return true;
}
#else
return BaseClass::BumpWeapon( pWeapon );
#endif
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *cmd -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CHL2_Player::ClientCommand( const CCommand &args )
{
#if HL2_SINGLE_PRIMARY_WEAPON_MODE
//Drop primary weapon
if ( !Q_stricmp( args[0], "DropPrimary" ) )
{
Weapon_DropSlot( WEAPON_PRIMARY_SLOT );
return true;
}
#endif
if ( !Q_stricmp( args[0], "emit" ) )
{
CSingleUserRecipientFilter filter( this );
if ( args.ArgC() > 1 )
{
EmitSound( filter, entindex(), args[ 1 ] );
}
else
{
EmitSound( filter, entindex(), "Test.Sound" );
}
return true;
}
return BaseClass::ClientCommand( args );
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : void CBasePlayer::PlayerUse
//-----------------------------------------------------------------------------
void CHL2_Player::PlayerUse ( void )
{
// Was use pressed or released?
if ( ! ((m_nButtons | m_afButtonPressed | m_afButtonReleased) & IN_USE) )
return;
if ( m_afButtonPressed & IN_USE )
{
// Currently using a latched entity?
if ( ClearUseEntity() )
{
return;
}
else
{
if ( m_afPhysicsFlags & PFLAG_DIROVERRIDE )
{
m_afPhysicsFlags &= ~PFLAG_DIROVERRIDE;
m_iTrain = TRAIN_NEW|TRAIN_OFF;
return;
}
else
{ // Start controlling the train!
CBaseEntity *pTrain = GetGroundEntity();
if ( pTrain && !(m_nButtons & IN_JUMP) && (GetFlags() & FL_ONGROUND) && (pTrain->ObjectCaps() & FCAP_DIRECTIONAL_USE) && pTrain->OnControls(this) )
{
m_afPhysicsFlags |= PFLAG_DIROVERRIDE;
m_iTrain = TrainSpeed(pTrain->m_flSpeed, ((CFuncTrackTrain*)pTrain)->GetMaxSpeed());
m_iTrain |= TRAIN_NEW;
EmitSound( "HL2Player.TrainUse" );
return;
}
}
}
// Tracker 3926: We can't +USE something if we're climbing a ladder
if ( GetMoveType() == MOVETYPE_LADDER )
{
return;
}
}
if( m_flTimeUseSuspended > gpGlobals->curtime )
{
// Something has temporarily stopped us being able to USE things.
// Obviously, this should be used very carefully.(sjb)
return;
}
CBaseEntity *pUseEntity = FindUseEntity();
bool usedSomething = false;
// Found an object
if ( pUseEntity )
{
//!!!UNDONE: traceline here to prevent +USEing buttons through walls
int caps = pUseEntity->ObjectCaps();
variant_t emptyVariant;
if ( m_afButtonPressed & IN_USE )
{
// Robin: Don't play sounds for NPCs, because NPCs will allow respond with speech.
if ( !pUseEntity->MyNPCPointer() )
{
EmitSound( "HL2Player.Use" );
}
}
if ( ( (m_nButtons & IN_USE) && (caps & FCAP_CONTINUOUS_USE) ) ||
( (m_afButtonPressed & IN_USE) && (caps & (FCAP_IMPULSE_USE|FCAP_ONOFF_USE)) ) )
{
if ( caps & FCAP_CONTINUOUS_USE )
m_afPhysicsFlags |= PFLAG_USING;
pUseEntity->AcceptInput( "Use", this, this, emptyVariant, USE_TOGGLE );
usedSomething = true;
}
// UNDONE: Send different USE codes for ON/OFF. Cache last ONOFF_USE object to send 'off' if you turn away
else if ( (m_afButtonReleased & IN_USE) && (pUseEntity->ObjectCaps() & FCAP_ONOFF_USE) ) // BUGBUG This is an "off" use
{
pUseEntity->AcceptInput( "Use", this, this, emptyVariant, USE_TOGGLE );
usedSomething = true;
}
#if HL2_SINGLE_PRIMARY_WEAPON_MODE
//Check for weapon pick-up
if ( m_afButtonPressed & IN_USE )
{
CBaseCombatWeapon *pWeapon = dynamic_cast<CBaseCombatWeapon *>(pUseEntity);
if ( ( pWeapon != NULL ) && ( Weapon_CanSwitchTo( pWeapon ) ) )
{
//Try to take ammo or swap the weapon
if ( Weapon_OwnsThisType( pWeapon->GetClassname(), pWeapon->GetSubType() ) )
{
Weapon_EquipAmmoOnly( pWeapon );
}
else
{
Weapon_DropSlot( pWeapon->GetSlot() );
Weapon_Equip( pWeapon );
}
usedSomething = true;
}
}
#endif
}
else if ( m_afButtonPressed & IN_USE )
{
// Signal that we want to play the deny sound, unless the user is +USEing on a ladder!
// The sound is emitted in ItemPostFrame, since that occurs after GameMovement::ProcessMove which
// lets the ladder code unset this flag.
m_bPlayUseDenySound = true;
}
// Debounce the use key
if ( usedSomething && pUseEntity )
{
m_Local.m_nOldButtons |= IN_USE;
m_afButtonPressed &= ~IN_USE;
}
}
ConVar sv_show_crosshair_target( "sv_show_crosshair_target", "0" );
//-----------------------------------------------------------------------------
// Purpose: Updates the posture of the weapon from lowered to ready
//-----------------------------------------------------------------------------
void CHL2_Player::UpdateWeaponPosture( void )
{
CBaseCombatWeapon *pWeapon = dynamic_cast<CBaseCombatWeapon *>(GetActiveWeapon());
if ( pWeapon && m_LowerWeaponTimer.Expired() && pWeapon->CanLower() )
{
m_LowerWeaponTimer.Set( .3 );
VPROF( "CHL2_Player::UpdateWeaponPosture-CheckLower" );
Vector vecAim = BaseClass::GetAutoaimVector( AUTOAIM_SCALE_DIRECT_ONLY );
const float CHECK_FRIENDLY_RANGE = 50 * 12;
trace_t tr;
UTIL_TraceLine( EyePosition(), EyePosition() + vecAim * CHECK_FRIENDLY_RANGE, MASK_SHOT, this, COLLISION_GROUP_NONE, &tr );
CBaseEntity *aimTarget = tr.m_pEnt;
//If we're over something
if ( aimTarget && !tr.DidHitWorld() )
{
if ( !aimTarget->IsNPC() || aimTarget->MyNPCPointer()->GetState() != NPC_STATE_COMBAT )
{
Disposition_t dis = IRelationType( aimTarget );
//Debug info for seeing what an object "cons" as
if ( sv_show_crosshair_target.GetBool() )
{
int text_offset = BaseClass::DrawDebugTextOverlays();
char tempstr[255];
switch ( dis )
{
case D_LI:
Q_snprintf( tempstr, sizeof(tempstr), "Disposition: Like" );
break;
case D_HT:
Q_snprintf( tempstr, sizeof(tempstr), "Disposition: Hate" );
break;
case D_FR:
Q_snprintf( tempstr, sizeof(tempstr), "Disposition: Fear" );
break;
case D_NU:
Q_snprintf( tempstr, sizeof(tempstr), "Disposition: Neutral" );
break;
default:
case D_ER:
Q_snprintf( tempstr, sizeof(tempstr), "Disposition: !!!ERROR!!!" );
break;
}
//Draw the text
NDebugOverlay::EntityText( aimTarget->entindex(), text_offset, tempstr, 0 );
}
//See if we hates it
if ( dis == D_LI )
{
//We're over a friendly, drop our weapon
if ( Weapon_Lower() == false )
{
//FIXME: We couldn't lower our weapon!
}
return;
}
}
}
if ( Weapon_Ready() == false )
{
//FIXME: We couldn't raise our weapon!
}
}
if( g_pGameRules->GetAutoAimMode() != AUTOAIM_NONE )
{
if( !pWeapon )
{
// This tells the client to draw no crosshair
m_HL2Local.m_bWeaponLowered = true;
return;
}
else
{
if( !pWeapon->CanLower() && m_HL2Local.m_bWeaponLowered )
m_HL2Local.m_bWeaponLowered = false;
}
if( !m_AutoaimTimer.Expired() )
return;
m_AutoaimTimer.Set( .1 );
VPROF( "hl2_x360_aiming" );
// Call the autoaim code to update the local player data, which allows the client to update.
autoaim_params_t params;
params.m_vecAutoAimPoint.Init();
params.m_vecAutoAimDir.Init();
params.m_fScale = AUTOAIM_SCALE_DEFAULT;
params.m_fMaxDist = autoaim_max_dist.GetFloat();
GetAutoaimVector( params );
m_HL2Local.m_hAutoAimTarget.Set( params.m_hAutoAimEntity );
m_HL2Local.m_vecAutoAimPoint.Set( params.m_vecAutoAimPoint );
m_HL2Local.m_bAutoAimTarget = ( params.m_bAutoAimAssisting || params.m_bOnTargetNatural );
return;
}
else
{
// Make sure there's no residual autoaim target if the user changes the xbox_aiming convar on the fly.
m_HL2Local.m_hAutoAimTarget.Set(NULL);
}
}
//-----------------------------------------------------------------------------
// Purpose: Lowers the weapon posture (for hovering over friendlies)
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CHL2_Player::Weapon_Lower( void )
{
VPROF( "CHL2_Player::Weapon_Lower" );
// Already lowered?
if ( m_HL2Local.m_bWeaponLowered )
return true;
m_HL2Local.m_bWeaponLowered = true;
CBaseCombatWeapon *pWeapon = dynamic_cast<CBaseCombatWeapon *>(GetActiveWeapon());
if ( pWeapon == NULL )
return false;
return pWeapon->Lower();
}
//-----------------------------------------------------------------------------
// Purpose: Returns the weapon posture to normal
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CHL2_Player::Weapon_Ready( void )
{
VPROF( "CHL2_Player::Weapon_Ready" );
// Already ready?
if ( m_HL2Local.m_bWeaponLowered == false )
return true;
m_HL2Local.m_bWeaponLowered = false;
CBaseCombatWeapon *pWeapon = dynamic_cast<CBaseCombatWeapon *>(GetActiveWeapon());
if ( pWeapon == NULL )
return false;
return pWeapon->Ready();
}
//-----------------------------------------------------------------------------
// Purpose: Returns whether or not we can switch to the given weapon.
// Input : pWeapon -
//-----------------------------------------------------------------------------
bool CHL2_Player::Weapon_CanSwitchTo( CBaseCombatWeapon *pWeapon )
{
CBasePlayer *pPlayer = (CBasePlayer *)this;
#if !defined( CLIENT_DLL )
IServerVehicle *pVehicle = pPlayer->GetVehicle();
#else
IClientVehicle *pVehicle = pPlayer->GetVehicle();
#endif
if (pVehicle && !pPlayer->UsingStandardWeaponsInVehicle())
return false;
/////
// SO2 - James
// Allow players to switch to weapons that do not have any ammo
/*if ( !pWeapon->HasAnyAmmo() && !GetAmmoCount( pWeapon->m_iPrimaryAmmoType ) )
return false;*/
/////
if ( !pWeapon->CanDeploy() )
return false;
if ( GetActiveWeapon() )
{
if ( PhysCannonGetHeldEntity( GetActiveWeapon() ) == pWeapon &&
Weapon_OwnsThisType( pWeapon->GetClassname(), pWeapon->GetSubType()) )
{
return true;
}
if ( !GetActiveWeapon()->CanHolster() )
return false;
}
return true;
}
void CHL2_Player::PickupObject( CBaseEntity *pObject, bool bLimitMassAndSize )
{
// can't pick up what you're standing on
if ( GetGroundEntity() == pObject )
return;
if ( bLimitMassAndSize == true )
{
if ( CBasePlayer::CanPickupObject( pObject, 35, 128 ) == false )
return;
}
// Can't be picked up if NPCs are on me
if ( pObject->HasNPCsOnIt() )
return;
PlayerPickupObject( this, pObject );
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : CBaseEntity
//-----------------------------------------------------------------------------
bool CHL2_Player::IsHoldingEntity( CBaseEntity *pEnt )
{
return PlayerPickupControllerIsHoldingEntity( m_hUseEntity, pEnt );
}
float CHL2_Player::GetHeldObjectMass( IPhysicsObject *pHeldObject )
{
float mass = PlayerPickupGetHeldObjectMass( m_hUseEntity, pHeldObject );
if ( mass == 0.0f )
{
mass = PhysCannonGetHeldObjectMass( GetActiveWeapon(), pHeldObject );
}
return mass;
}
CBaseEntity *CHL2_Player::GetHeldObject( void )
{
return PhysCannonGetHeldEntity( GetActiveWeapon() );
}
//-----------------------------------------------------------------------------
// Purpose: Force the player to drop any physics objects he's carrying
//-----------------------------------------------------------------------------
void CHL2_Player::ForceDropOfCarriedPhysObjects( CBaseEntity *pOnlyIfHoldingThis )
{
if ( PhysIsInCallback() )
{
variant_t value;
g_EventQueue.AddEvent( this, "ForceDropPhysObjects", value, 0.01f, pOnlyIfHoldingThis, this );
return;
}
#ifdef HL2_EPISODIC
if ( hl2_episodic.GetBool() )
{
CBaseEntity *pHeldEntity = PhysCannonGetHeldEntity( GetActiveWeapon() );
if( pHeldEntity && pHeldEntity->ClassMatches( "grenade_helicopter" ) )
{
return;
}
}
#endif
// Drop any objects being handheld.
ClearUseEntity();
// Then force the physcannon to drop anything it's holding, if it's our active weapon
PhysCannonForceDrop( GetActiveWeapon(), NULL );
}
void CHL2_Player::InputForceDropPhysObjects( inputdata_t &data )
{
ForceDropOfCarriedPhysObjects( data.pActivator );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHL2_Player::UpdateClientData( void )
{
if (m_DmgTake || m_DmgSave || m_bitsHUDDamage != m_bitsDamageType)
{
// Comes from inside me if not set
Vector damageOrigin = GetLocalOrigin();
// send "damage" message
// causes screen to flash, and pain compass to show direction of damage
damageOrigin = m_DmgOrigin;
// only send down damage type that have hud art
int iShowHudDamage = g_pGameRules->Damage_GetShowOnHud();
int visibleDamageBits = m_bitsDamageType & iShowHudDamage;
m_DmgTake = clamp( m_DmgTake, 0, 255 );
m_DmgSave = clamp( m_DmgSave, 0, 255 );
// If we're poisoned, but it wasn't this frame, don't send the indicator
// Without this check, any damage that occured to the player while they were
// recovering from a poison bite would register as poisonous as well and flash
// the whole screen! -- jdw
if ( visibleDamageBits & DMG_POISON )
{
float flLastPoisonedDelta = gpGlobals->curtime - m_tbdPrev;
if ( flLastPoisonedDelta > 0.1f )
{
visibleDamageBits &= ~DMG_POISON;
}
}
CSingleUserRecipientFilter user( this );
user.MakeReliable();
UserMessageBegin( user, "Damage" );
WRITE_BYTE( m_DmgSave );
WRITE_BYTE( m_DmgTake );
WRITE_LONG( visibleDamageBits );
WRITE_FLOAT( damageOrigin.x ); //BUG: Should be fixed point (to hud) not floats
WRITE_FLOAT( damageOrigin.y ); //BUG: However, the HUD does _not_ implement bitfield messages (yet)
WRITE_FLOAT( damageOrigin.z ); //BUG: We use WRITE_VEC3COORD for everything else
MessageEnd();
m_DmgTake = 0;
m_DmgSave = 0;
m_bitsHUDDamage = m_bitsDamageType;
// Clear off non-time-based damage indicators
int iTimeBasedDamage = g_pGameRules->Damage_GetTimeBased();
m_bitsDamageType &= iTimeBasedDamage;
}
// Update Flashlight
#ifdef HL2_EPISODIC
if ( Flashlight_UseLegacyVersion() == false )
{
if ( FlashlightIsOn() && sv_infinite_aux_power.GetBool() == false )
{
m_HL2Local.m_flFlashBattery -= FLASH_DRAIN_TIME * gpGlobals->frametime;
if ( m_HL2Local.m_flFlashBattery < 0.0f )
{
FlashlightTurnOff();
m_HL2Local.m_flFlashBattery = 0.0f;
}
}
else
{
m_HL2Local.m_flFlashBattery += FLASH_CHARGE_TIME * gpGlobals->frametime;
if ( m_HL2Local.m_flFlashBattery > 100.0f )
{
m_HL2Local.m_flFlashBattery = 100.0f;
}
}
}
else
{
m_HL2Local.m_flFlashBattery = -1.0f;
}
#endif // HL2_EPISODIC
BaseClass::UpdateClientData();
}
//---------------------------------------------------------
//---------------------------------------------------------
void CHL2_Player::OnRestore()
{
BaseClass::OnRestore();
m_pPlayerAISquad = g_AI_SquadManager.FindCreateSquad(AllocPooledString(PLAYER_SQUADNAME));
}
//---------------------------------------------------------
//---------------------------------------------------------
Vector CHL2_Player::EyeDirection2D( void )
{
Vector vecReturn = EyeDirection3D();
vecReturn.z = 0;
vecReturn.AsVector2D().NormalizeInPlace();
return vecReturn;
}
//---------------------------------------------------------
//---------------------------------------------------------
Vector CHL2_Player::EyeDirection3D( void )
{
Vector vecForward;
// Return the vehicle angles if we request them
if ( GetVehicle() != NULL )
{
CacheVehicleView();
EyeVectors( &vecForward );
return vecForward;
}
AngleVectors( EyeAngles(), &vecForward );
return vecForward;
}
//---------------------------------------------------------
//---------------------------------------------------------
bool CHL2_Player::Weapon_Switch( CBaseCombatWeapon *pWeapon, int viewmodelindex )
{
MDLCACHE_CRITICAL_SECTION();
// Recalculate proficiency!
SetCurrentWeaponProficiency( CalcWeaponProficiency( pWeapon ) );
// Come out of suit zoom mode
if ( IsZooming() )
{
StopZooming();
}
return BaseClass::Weapon_Switch( pWeapon, viewmodelindex );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
WeaponProficiency_t CHL2_Player::CalcWeaponProficiency( CBaseCombatWeapon *pWeapon )
{
WeaponProficiency_t proficiency;
proficiency = WEAPON_PROFICIENCY_PERFECT;
if( weapon_showproficiency.GetBool() != 0 )
{
Msg("Player switched to %s, proficiency is %s\n", pWeapon->GetClassname(), GetWeaponProficiencyName( proficiency ) );
}
return proficiency;
}
//-----------------------------------------------------------------------------
// Purpose: override how single player rays hit the player
//-----------------------------------------------------------------------------
bool LineCircleIntersection(
const Vector2D ¢er,
const float radius,
const Vector2D &vLinePt,
const Vector2D &vLineDir,
float *fIntersection1,
float *fIntersection2)
{
// Line = P + Vt
// Sphere = r (assume we've translated to origin)
// (P + Vt)^2 = r^2
// VVt^2 + 2PVt + (PP - r^2)
// Solve as quadratic: (-b +/- sqrt(b^2 - 4ac)) / 2a
// If (b^2 - 4ac) is < 0 there is no solution.
// If (b^2 - 4ac) is = 0 there is one solution (a case this function doesn't support).
// If (b^2 - 4ac) is > 0 there are two solutions.
Vector2D P;
float a, b, c, sqr, insideSqr;
// Translate circle to origin.
P[0] = vLinePt[0] - center[0];
P[1] = vLinePt[1] - center[1];
a = vLineDir.Dot(vLineDir);
b = 2.0f * P.Dot(vLineDir);
c = P.Dot(P) - (radius * radius);
insideSqr = b*b - 4*a*c;
if(insideSqr <= 0.000001f)
return false;
// Ok, two solutions.
sqr = (float)FastSqrt(insideSqr);
float denom = 1.0 / (2.0f * a);
*fIntersection1 = (-b - sqr) * denom;
*fIntersection2 = (-b + sqr) * denom;
return true;
}
static void Collision_ClearTrace( const Vector &vecRayStart, const Vector &vecRayDelta, CBaseTrace *pTrace )
{
pTrace->startpos = vecRayStart;
pTrace->endpos = vecRayStart;
pTrace->endpos += vecRayDelta;
pTrace->startsolid = false;
pTrace->allsolid = false;
pTrace->fraction = 1.0f;
pTrace->contents = 0;
}
bool IntersectRayWithAACylinder( const Ray_t &ray,
const Vector ¢er, float radius, float height, CBaseTrace *pTrace )
{
Assert( ray.m_IsRay );
Collision_ClearTrace( ray.m_Start, ray.m_Delta, pTrace );
// First intersect the ray with the top + bottom planes
float halfHeight = height * 0.5;
// Handle parallel case
Vector vStart = ray.m_Start - center;
Vector vEnd = vStart + ray.m_Delta;
float flEnterFrac, flLeaveFrac;
if (FloatMakePositive(ray.m_Delta.z) < 1e-8)
{
if ( (vStart.z < -halfHeight) || (vStart.z > halfHeight) )
{
return false; // no hit
}
flEnterFrac = 0.0f; flLeaveFrac = 1.0f;
}
else
{
// Clip the ray to the top and bottom of box
flEnterFrac = IntersectRayWithAAPlane( vStart, vEnd, 2, 1, halfHeight);
flLeaveFrac = IntersectRayWithAAPlane( vStart, vEnd, 2, 1, -halfHeight);
if ( flLeaveFrac < flEnterFrac )
{
float temp = flLeaveFrac;
flLeaveFrac = flEnterFrac;
flEnterFrac = temp;
}
if ( flLeaveFrac < 0 || flEnterFrac > 1)
{
return false;
}
}
// Intersect with circle
float flCircleEnterFrac, flCircleLeaveFrac;
if ( !LineCircleIntersection( vec3_origin.AsVector2D(), radius,
vStart.AsVector2D(), ray.m_Delta.AsVector2D(), &flCircleEnterFrac, &flCircleLeaveFrac ) )
{
return false; // no hit
}
Assert( flCircleEnterFrac <= flCircleLeaveFrac );
if ( flCircleLeaveFrac < 0 || flCircleEnterFrac > 1)
{
return false;
}
if ( flEnterFrac < flCircleEnterFrac )
flEnterFrac = flCircleEnterFrac;
if ( flLeaveFrac > flCircleLeaveFrac )
flLeaveFrac = flCircleLeaveFrac;
if ( flLeaveFrac < flEnterFrac )
return false;
VectorMA( ray.m_Start, flEnterFrac , ray.m_Delta, pTrace->endpos );
pTrace->fraction = flEnterFrac;
pTrace->contents = CONTENTS_SOLID;
// Calculate the point on our center line where we're nearest the intersection point
Vector collisionCenter;
CalcClosestPointOnLineSegment( pTrace->endpos, center + Vector( 0, 0, halfHeight ), center - Vector( 0, 0, halfHeight ), collisionCenter );
// Our normal is the direction from that center point to the intersection point
pTrace->plane.normal = pTrace->endpos - collisionCenter;
VectorNormalize( pTrace->plane.normal );
return true;
}
bool CHL2_Player::TestHitboxes( const Ray_t &ray, unsigned int fContentsMask, trace_t& tr )
{
if( g_pGameRules->IsMultiplayer() )
{
return BaseClass::TestHitboxes( ray, fContentsMask, tr );
}
else
{
Assert( ray.m_IsRay );
Vector mins, maxs;
mins = WorldAlignMins();
maxs = WorldAlignMaxs();
if ( IntersectRayWithAACylinder( ray, WorldSpaceCenter(), maxs.x * PLAYER_HULL_REDUCTION, maxs.z - mins.z, &tr ) )
{
tr.hitbox = 0;
CStudioHdr *pStudioHdr = GetModelPtr( );
if (!pStudioHdr)
return false;
mstudiohitboxset_t *set = pStudioHdr->pHitboxSet( m_nHitboxSet );
if ( !set || !set->numhitboxes )
return false;
mstudiobbox_t *pbox = set->pHitbox( tr.hitbox );
mstudiobone_t *pBone = pStudioHdr->pBone(pbox->bone);
tr.surface.name = "**studio**";
tr.surface.flags = SURF_HITBOX;
tr.surface.surfaceProps = physprops->GetSurfaceIndex( pBone->pszSurfaceProp() );
}
return true;
}
}
//---------------------------------------------------------
// Show the player's scaled down bbox that we use for
// bullet impacts.
//---------------------------------------------------------
void CHL2_Player::DrawDebugGeometryOverlays(void)
{
BaseClass::DrawDebugGeometryOverlays();
if (m_debugOverlays & OVERLAY_BBOX_BIT)
{
Vector mins, maxs;
mins = WorldAlignMins();
maxs = WorldAlignMaxs();
mins.x *= PLAYER_HULL_REDUCTION;
mins.y *= PLAYER_HULL_REDUCTION;
maxs.x *= PLAYER_HULL_REDUCTION;
maxs.y *= PLAYER_HULL_REDUCTION;
NDebugOverlay::Box( GetAbsOrigin(), mins, maxs, 255, 0, 0, 100, 0 );
}
}
//-----------------------------------------------------------------------------
// Purpose: Helper to remove from ladder
//-----------------------------------------------------------------------------
void CHL2_Player::ExitLadder()
{
if ( MOVETYPE_LADDER != GetMoveType() )
return;
SetMoveType( MOVETYPE_WALK );
SetMoveCollide( MOVECOLLIDE_DEFAULT );
// Remove from ladder
m_HL2Local.m_hLadder.Set( NULL );
}
surfacedata_t *CHL2_Player::GetLadderSurface( const Vector &origin )
{
extern const char *FuncLadder_GetSurfaceprops(CBaseEntity *pLadderEntity);
CBaseEntity *pLadder = m_HL2Local.m_hLadder.Get();
if ( pLadder )
{
const char *pSurfaceprops = FuncLadder_GetSurfaceprops(pLadder);
// get ladder material from func_ladder
return physprops->GetSurfaceData( physprops->GetSurfaceIndex( pSurfaceprops ) );
}
return BaseClass::GetLadderSurface(origin);
}
//-----------------------------------------------------------------------------
// Purpose: Queues up a use deny sound, played in ItemPostFrame.
//-----------------------------------------------------------------------------
void CHL2_Player::PlayUseDenySound()
{
m_bPlayUseDenySound = true;
}
void CHL2_Player::ItemPostFrame()
{
BaseClass::ItemPostFrame();
if ( m_bPlayUseDenySound )
{
m_bPlayUseDenySound = false;
EmitSound( "HL2Player.UseDeny" );
}
}
void CHL2_Player::StartWaterDeathSounds( void )
{
CPASAttenuationFilter filter( this );
if ( m_sndLeeches == NULL )
{
m_sndLeeches = (CSoundEnvelopeController::GetController()).SoundCreate( filter, entindex(), CHAN_STATIC, "coast.leech_bites_loop" , ATTN_NORM );
}
if ( m_sndLeeches )
{
(CSoundEnvelopeController::GetController()).Play( m_sndLeeches, 1.0f, 100 );
}
if ( m_sndWaterSplashes == NULL )
{
m_sndWaterSplashes = (CSoundEnvelopeController::GetController()).SoundCreate( filter, entindex(), CHAN_STATIC, "coast.leech_water_churn_loop" , ATTN_NORM );
}
if ( m_sndWaterSplashes )
{
(CSoundEnvelopeController::GetController()).Play( m_sndWaterSplashes, 1.0f, 100 );
}
}
void CHL2_Player::StopWaterDeathSounds( void )
{
if ( m_sndLeeches )
{
(CSoundEnvelopeController::GetController()).SoundFadeOut( m_sndLeeches, 0.5f, true );
m_sndLeeches = NULL;
}
if ( m_sndWaterSplashes )
{
(CSoundEnvelopeController::GetController()).SoundFadeOut( m_sndWaterSplashes, 0.5f, true );
m_sndWaterSplashes = NULL;
}
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CHL2_Player::MissedAR2AltFire()
{
if( GetPlayerProxy() != NULL )
{
GetPlayerProxy()->m_PlayerMissedAR2AltFire.FireOutput( this, this );
}
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CHL2_Player::DisplayLadderHudHint()
{
#if !defined( CLIENT_DLL )
if( gpGlobals->curtime > m_flTimeNextLadderHint )
{
m_flTimeNextLadderHint = gpGlobals->curtime + 60.0f;
CFmtStr hint;
hint.sprintf( "#Valve_Hint_Ladder" );
UTIL_HudHintText( this, hint.Access() );
}
#endif//CLIENT_DLL
}
//-----------------------------------------------------------------------------
// Shuts down sounds
//-----------------------------------------------------------------------------
void CHL2_Player::StopLoopingSounds( void )
{
if ( m_sndLeeches != NULL )
{
(CSoundEnvelopeController::GetController()).SoundDestroy( m_sndLeeches );
m_sndLeeches = NULL;
}
if ( m_sndWaterSplashes != NULL )
{
(CSoundEnvelopeController::GetController()).SoundDestroy( m_sndWaterSplashes );
m_sndWaterSplashes = NULL;
}
BaseClass::StopLoopingSounds();
}
//-----------------------------------------------------------------------------
void CHL2_Player::ModifyOrAppendPlayerCriteria( AI_CriteriaSet& set )
{
BaseClass::ModifyOrAppendPlayerCriteria( set );
if ( GlobalEntity_GetIndex( "gordon_precriminal" ) == -1 )
{
set.AppendCriteria( "gordon_precriminal", "0" );
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
const impactdamagetable_t &CHL2_Player::GetPhysicsImpactDamageTable()
{
if ( m_bUseCappedPhysicsDamageTable )
return gCappedPlayerImpactDamageTable;
return BaseClass::GetPhysicsImpactDamageTable();
}
//-----------------------------------------------------------------------------
// Purpose: Makes a splash when the player transitions between water states
//-----------------------------------------------------------------------------
void CHL2_Player::Splash( void )
{
CEffectData data;
data.m_fFlags = 0;
data.m_vOrigin = GetAbsOrigin();
data.m_vNormal = Vector(0,0,1);
data.m_vAngles = QAngle( 0, 0, 0 );
if ( GetWaterType() & CONTENTS_SLIME )
{
data.m_fFlags |= FX_WATER_IN_SLIME;
}
float flSpeed = GetAbsVelocity().Length();
if ( flSpeed < 300 )
{
data.m_flScale = random->RandomFloat( 10, 12 );
DispatchEffect( "waterripple", data );
}
else
{
data.m_flScale = random->RandomFloat( 6, 8 );
DispatchEffect( "watersplash", data );
}
}
CLogicPlayerProxy *CHL2_Player::GetPlayerProxy( void )
{
CLogicPlayerProxy *pProxy = dynamic_cast< CLogicPlayerProxy* > ( m_hPlayerProxy.Get() );
if ( pProxy == NULL )
{
pProxy = (CLogicPlayerProxy*)gEntList.FindEntityByClassname(NULL, "logic_playerproxy" );
if ( pProxy == NULL )
return NULL;
pProxy->m_hPlayer = this;
m_hPlayerProxy = pProxy;
}
return pProxy;
}
void CHL2_Player::FirePlayerProxyOutput( const char *pszOutputName, variant_t variant, CBaseEntity *pActivator, CBaseEntity *pCaller )
{
if ( GetPlayerProxy() == NULL )
return;
GetPlayerProxy()->FireNamedOutput( pszOutputName, variant, pActivator, pCaller );
}
LINK_ENTITY_TO_CLASS( logic_playerproxy, CLogicPlayerProxy);
BEGIN_DATADESC( CLogicPlayerProxy )
DEFINE_OUTPUT( m_OnFlashlightOn, "OnFlashlightOn" ),
DEFINE_OUTPUT( m_OnFlashlightOff, "OnFlashlightOff" ),
DEFINE_OUTPUT( m_RequestedPlayerHealth, "PlayerHealth" ),
DEFINE_OUTPUT( m_PlayerHasAmmo, "PlayerHasAmmo" ),
DEFINE_OUTPUT( m_PlayerHasNoAmmo, "PlayerHasNoAmmo" ),
DEFINE_OUTPUT( m_PlayerDied, "PlayerDied" ),
DEFINE_OUTPUT( m_PlayerMissedAR2AltFire, "PlayerMissedAR2AltFire" ),
DEFINE_INPUTFUNC( FIELD_VOID, "RequestPlayerHealth", InputRequestPlayerHealth ),
DEFINE_INPUTFUNC( FIELD_VOID, "SetFlashlightSlowDrain", InputSetFlashlightSlowDrain ),
DEFINE_INPUTFUNC( FIELD_VOID, "SetFlashlightNormalDrain", InputSetFlashlightNormalDrain ),
DEFINE_INPUTFUNC( FIELD_INTEGER, "SetPlayerHealth", InputSetPlayerHealth ),
DEFINE_INPUTFUNC( FIELD_VOID, "RequestAmmoState", InputRequestAmmoState ),
DEFINE_INPUTFUNC( FIELD_VOID, "LowerWeapon", InputLowerWeapon ),
DEFINE_INPUTFUNC( FIELD_VOID, "EnableCappedPhysicsDamage", InputEnableCappedPhysicsDamage ),
DEFINE_INPUTFUNC( FIELD_VOID, "DisableCappedPhysicsDamage", InputDisableCappedPhysicsDamage ),
DEFINE_INPUTFUNC( FIELD_STRING, "SetLocatorTargetEntity", InputSetLocatorTargetEntity ),
DEFINE_FIELD( m_hPlayer, FIELD_EHANDLE ),
END_DATADESC()
void CLogicPlayerProxy::Activate( void )
{
BaseClass::Activate();
if ( m_hPlayer == NULL )
{
m_hPlayer = AI_GetSinglePlayer();
}
}
bool CLogicPlayerProxy::PassesDamageFilter( const CTakeDamageInfo &info )
{
if (m_hDamageFilter)
{
CBaseFilter *pFilter = (CBaseFilter *)(m_hDamageFilter.Get());
return pFilter->PassesDamageFilter(info);
}
return true;
}
void CLogicPlayerProxy::InputSetPlayerHealth( inputdata_t &inputdata )
{
if ( m_hPlayer == NULL )
return;
m_hPlayer->SetHealth( inputdata.value.Int() );
}
void CLogicPlayerProxy::InputRequestPlayerHealth( inputdata_t &inputdata )
{
if ( m_hPlayer == NULL )
return;
m_RequestedPlayerHealth.Set( m_hPlayer->GetHealth(), inputdata.pActivator, inputdata.pCaller );
}
void CLogicPlayerProxy::InputSetFlashlightSlowDrain( inputdata_t &inputdata )
{
if( m_hPlayer == NULL )
return;
CHL2_Player *pPlayer = dynamic_cast<CHL2_Player*>(m_hPlayer.Get());
if( pPlayer )
pPlayer->SetFlashlightPowerDrainScale( hl2_darkness_flashlight_factor.GetFloat() );
}
void CLogicPlayerProxy::InputSetFlashlightNormalDrain( inputdata_t &inputdata )
{
if( m_hPlayer == NULL )
return;
CHL2_Player *pPlayer = dynamic_cast<CHL2_Player*>(m_hPlayer.Get());
if( pPlayer )
pPlayer->SetFlashlightPowerDrainScale( 1.0f );
}
void CLogicPlayerProxy::InputRequestAmmoState( inputdata_t &inputdata )
{
if( m_hPlayer == NULL )
return;
CHL2_Player *pPlayer = dynamic_cast<CHL2_Player*>(m_hPlayer.Get());
for ( int i = 0 ; i < pPlayer->WeaponCount(); ++i )
{
CBaseCombatWeapon* pCheck = pPlayer->GetWeapon( i );
if ( pCheck )
{
if ( pCheck->HasAnyAmmo() && (pCheck->UsesPrimaryAmmo() || pCheck->UsesSecondaryAmmo()))
{
m_PlayerHasAmmo.FireOutput( this, this, 0 );
return;
}
}
}
m_PlayerHasNoAmmo.FireOutput( this, this, 0 );
}
void CLogicPlayerProxy::InputLowerWeapon( inputdata_t &inputdata )
{
if( m_hPlayer == NULL )
return;
CHL2_Player *pPlayer = dynamic_cast<CHL2_Player*>(m_hPlayer.Get());
pPlayer->Weapon_Lower();
}
void CLogicPlayerProxy::InputEnableCappedPhysicsDamage( inputdata_t &inputdata )
{
if( m_hPlayer == NULL )
return;
CHL2_Player *pPlayer = dynamic_cast<CHL2_Player*>(m_hPlayer.Get());
pPlayer->EnableCappedPhysicsDamage();
}
void CLogicPlayerProxy::InputDisableCappedPhysicsDamage( inputdata_t &inputdata )
{
if( m_hPlayer == NULL )
return;
CHL2_Player *pPlayer = dynamic_cast<CHL2_Player*>(m_hPlayer.Get());
pPlayer->DisableCappedPhysicsDamage();
}
void CLogicPlayerProxy::InputSetLocatorTargetEntity( inputdata_t &inputdata )
{
if( m_hPlayer == NULL )
return;
CBaseEntity *pTarget = NULL; // assume no target
string_t iszTarget = MAKE_STRING( inputdata.value.String() );
if( iszTarget != NULL_STRING )
{
pTarget = gEntList.FindEntityByName( NULL, iszTarget );
}
CHL2_Player *pPlayer = dynamic_cast<CHL2_Player*>(m_hPlayer.Get());
pPlayer->SetLocatorTargetEntity(pTarget);
}
| [
"MadKowa@ec9d42d2-91e1-33f0-ec5d-f2a905d45d61"
] | [
[
[
1,
4012
]
]
] |