blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
listlengths
0
7
license_type
stringclasses
2 values
repo_name
stringlengths
6
79
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
4 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.07k
426M
star_events_count
int64
0
27
fork_events_count
int64
0
12
gha_license_id
stringclasses
3 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
6 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
20
6.28M
extension
stringclasses
20 values
content
stringlengths
20
6.28M
authors
listlengths
1
16
author_lines
listlengths
1
16
3aab94ea4e342d55ebaa0700f41cdc2760d73992
e2e49023f5a82922cb9b134e93ae926ed69675a1
/tools/aoslcpp/include/aosl/navigation_forward.hpp
8c67cf68d4d64a4c472b2955ac96acc6c52a9cca
[]
no_license
invy/mjklaim-freewindows
c93c867e93f0e2fe1d33f207306c0b9538ac61d6
30de8e3dfcde4e81a57e9059dfaf54c98cc1135b
refs/heads/master
2021-01-10T10:21:51.579762
2011-12-12T18:56:43
2011-12-12T18:56:43
54,794,395
1
0
null
null
null
null
UTF-8
C++
false
false
14,577
hpp
// Copyright (C) 2005-2010 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema // to C++ data binding compiler, in the Proprietary License mode. // You should have received a proprietary license from Code Synthesis // Tools CC prior to generating this code. See the license text for // conditions. // #ifndef AOSLCPP_AOSL__NAVIGATION_FORWARD_HPP #define AOSLCPP_AOSL__NAVIGATION_FORWARD_HPP // Begin prologue. // // // End prologue. #include <xsd/cxx/version.hxx> #if (XSD_INT_VERSION != 3030000L) #error XSD runtime version mismatch #endif #include <xsd/cxx/pre.hxx> #ifndef XSD_USE_CHAR #define XSD_USE_CHAR #endif #ifndef XSD_CXX_TREE_USE_CHAR #define XSD_CXX_TREE_USE_CHAR #endif #include <xsd/cxx/xml/char-utf8.hxx> #include <xsd/cxx/tree/exceptions.hxx> #include <xsd/cxx/tree/elements.hxx> #include <xsd/cxx/tree/types.hxx> #include <xsd/cxx/xml/error-handler.hxx> #include <xsd/cxx/xml/dom/auto-ptr.hxx> #include <xsd/cxx/tree/parsing.hxx> #include <xsd/cxx/tree/parsing/byte.hxx> #include <xsd/cxx/tree/parsing/unsigned-byte.hxx> #include <xsd/cxx/tree/parsing/short.hxx> #include <xsd/cxx/tree/parsing/unsigned-short.hxx> #include <xsd/cxx/tree/parsing/int.hxx> #include <xsd/cxx/tree/parsing/unsigned-int.hxx> #include <xsd/cxx/tree/parsing/long.hxx> #include <xsd/cxx/tree/parsing/unsigned-long.hxx> #include <xsd/cxx/tree/parsing/boolean.hxx> #include <xsd/cxx/tree/parsing/float.hxx> #include <xsd/cxx/tree/parsing/double.hxx> #include <xsd/cxx/tree/parsing/decimal.hxx> #include <xsd/cxx/xml/dom/serialization-header.hxx> #include <xsd/cxx/tree/serialization.hxx> #include <xsd/cxx/tree/serialization/byte.hxx> #include <xsd/cxx/tree/serialization/unsigned-byte.hxx> #include <xsd/cxx/tree/serialization/short.hxx> #include <xsd/cxx/tree/serialization/unsigned-short.hxx> #include <xsd/cxx/tree/serialization/int.hxx> #include <xsd/cxx/tree/serialization/unsigned-int.hxx> #include <xsd/cxx/tree/serialization/long.hxx> #include <xsd/cxx/tree/serialization/unsigned-long.hxx> #include <xsd/cxx/tree/serialization/boolean.hxx> #include <xsd/cxx/tree/serialization/float.hxx> #include <xsd/cxx/tree/serialization/double.hxx> #include <xsd/cxx/tree/serialization/decimal.hxx> #include <xsd/cxx/tree/std-ostream-operators.hxx> /** * @brief C++ namespace for the %http://www.w3.org/2001/XMLSchema * schema namespace. */ namespace xml_schema { // anyType and anySimpleType. // /** * @brief C++ type corresponding to the anyType XML Schema * built-in type. */ typedef ::xsd::cxx::tree::type Type; /** * @brief C++ type corresponding to the anySimpleType XML Schema * built-in type. */ typedef ::xsd::cxx::tree::simple_type< Type > SimpleType; /** * @brief Alias for the anyType type. */ typedef ::xsd::cxx::tree::type Container; // 8-bit // /** * @brief C++ type corresponding to the byte XML Schema * built-in type. */ typedef signed char Byte; /** * @brief C++ type corresponding to the unsignedByte XML Schema * built-in type. */ typedef unsigned char UnsignedByte; // 16-bit // /** * @brief C++ type corresponding to the short XML Schema * built-in type. */ typedef short Short; /** * @brief C++ type corresponding to the unsignedShort XML Schema * built-in type. */ typedef unsigned short UnsignedShort; // 32-bit // /** * @brief C++ type corresponding to the int XML Schema * built-in type. */ typedef int Int; /** * @brief C++ type corresponding to the unsignedInt XML Schema * built-in type. */ typedef unsigned int UnsignedInt; // 64-bit // /** * @brief C++ type corresponding to the long XML Schema * built-in type. */ typedef long long Long; /** * @brief C++ type corresponding to the unsignedLong XML Schema * built-in type. */ typedef unsigned long long UnsignedLong; // Supposed to be arbitrary-length integral types. // /** * @brief C++ type corresponding to the integer XML Schema * built-in type. */ typedef long long Integer; /** * @brief C++ type corresponding to the nonPositiveInteger XML Schema * built-in type. */ typedef long long NonPositiveInteger; /** * @brief C++ type corresponding to the nonNegativeInteger XML Schema * built-in type. */ typedef unsigned long long NonNegativeInteger; /** * @brief C++ type corresponding to the positiveInteger XML Schema * built-in type. */ typedef unsigned long long PositiveInteger; /** * @brief C++ type corresponding to the negativeInteger XML Schema * built-in type. */ typedef long long NegativeInteger; // Boolean. // /** * @brief C++ type corresponding to the boolean XML Schema * built-in type. */ typedef bool Boolean; // Floating-point types. // /** * @brief C++ type corresponding to the float XML Schema * built-in type. */ typedef float Float; /** * @brief C++ type corresponding to the double XML Schema * built-in type. */ typedef double Double; /** * @brief C++ type corresponding to the decimal XML Schema * built-in type. */ typedef double Decimal; // String types. // /** * @brief C++ type corresponding to the string XML Schema * built-in type. */ typedef ::xsd::cxx::tree::string< char, SimpleType > String; /** * @brief C++ type corresponding to the normalizedString XML Schema * built-in type. */ typedef ::xsd::cxx::tree::normalized_string< char, String > NormalizedString; /** * @brief C++ type corresponding to the token XML Schema * built-in type. */ typedef ::xsd::cxx::tree::token< char, NormalizedString > Token; /** * @brief C++ type corresponding to the Name XML Schema * built-in type. */ typedef ::xsd::cxx::tree::name< char, Token > Name; /** * @brief C++ type corresponding to the NMTOKEN XML Schema * built-in type. */ typedef ::xsd::cxx::tree::nmtoken< char, Token > Nmtoken; /** * @brief C++ type corresponding to the NMTOKENS XML Schema * built-in type. */ typedef ::xsd::cxx::tree::nmtokens< char, SimpleType, Nmtoken > Nmtokens; /** * @brief C++ type corresponding to the NCName XML Schema * built-in type. */ typedef ::xsd::cxx::tree::ncname< char, Name > Ncname; /** * @brief C++ type corresponding to the language XML Schema * built-in type. */ typedef ::xsd::cxx::tree::language< char, Token > Language; // ID/IDREF. // /** * @brief C++ type corresponding to the ID XML Schema * built-in type. */ typedef ::xsd::cxx::tree::id< char, Ncname > Id; /** * @brief C++ type corresponding to the IDREF XML Schema * built-in type. */ typedef ::xsd::cxx::tree::idref< char, Ncname, Type > Idref; /** * @brief C++ type corresponding to the IDREFS XML Schema * built-in type. */ typedef ::xsd::cxx::tree::idrefs< char, SimpleType, Idref > Idrefs; // URI. // /** * @brief C++ type corresponding to the anyURI XML Schema * built-in type. */ typedef ::xsd::cxx::tree::uri< char, SimpleType > Uri; // Qualified name. // /** * @brief C++ type corresponding to the QName XML Schema * built-in type. */ typedef ::xsd::cxx::tree::qname< char, SimpleType, Uri, Ncname > Qname; // Binary. // /** * @brief Binary buffer type. */ typedef ::xsd::cxx::tree::buffer< char > Buffer; /** * @brief C++ type corresponding to the base64Binary XML Schema * built-in type. */ typedef ::xsd::cxx::tree::base64_binary< char, SimpleType > Base64Binary; /** * @brief C++ type corresponding to the hexBinary XML Schema * built-in type. */ typedef ::xsd::cxx::tree::hex_binary< char, SimpleType > HexBinary; // Date/time. // /** * @brief Time zone type. */ typedef ::xsd::cxx::tree::time_zone TimeZone; /** * @brief C++ type corresponding to the date XML Schema * built-in type. */ typedef ::xsd::cxx::tree::date< char, SimpleType > Date; /** * @brief C++ type corresponding to the dateTime XML Schema * built-in type. */ typedef ::xsd::cxx::tree::date_time< char, SimpleType > DateTime; /** * @brief C++ type corresponding to the duration XML Schema * built-in type. */ typedef ::xsd::cxx::tree::duration< char, SimpleType > Duration; /** * @brief C++ type corresponding to the gDay XML Schema * built-in type. */ typedef ::xsd::cxx::tree::gday< char, SimpleType > Gday; /** * @brief C++ type corresponding to the gMonth XML Schema * built-in type. */ typedef ::xsd::cxx::tree::gmonth< char, SimpleType > Gmonth; /** * @brief C++ type corresponding to the gMonthDay XML Schema * built-in type. */ typedef ::xsd::cxx::tree::gmonth_day< char, SimpleType > GmonthDay; /** * @brief C++ type corresponding to the gYear XML Schema * built-in type. */ typedef ::xsd::cxx::tree::gyear< char, SimpleType > Gyear; /** * @brief C++ type corresponding to the gYearMonth XML Schema * built-in type. */ typedef ::xsd::cxx::tree::gyear_month< char, SimpleType > GyearMonth; /** * @brief C++ type corresponding to the time XML Schema * built-in type. */ typedef ::xsd::cxx::tree::time< char, SimpleType > Time; // Entity. // /** * @brief C++ type corresponding to the ENTITY XML Schema * built-in type. */ typedef ::xsd::cxx::tree::entity< char, Ncname > Entity; /** * @brief C++ type corresponding to the ENTITIES XML Schema * built-in type. */ typedef ::xsd::cxx::tree::entities< char, SimpleType, Entity > Entities; // Namespace information and list stream. Used in // serialization functions. // /** * @brief Namespace serialization information. */ typedef ::xsd::cxx::xml::dom::namespace_info< char > NamespaceInfo; /** * @brief Namespace serialization information map. */ typedef ::xsd::cxx::xml::dom::namespace_infomap< char > NamespaceInfomap; /** * @brief List serialization stream. */ typedef ::xsd::cxx::tree::list_stream< char > ListStream; /** * @brief Serialization wrapper for the %double type. */ typedef ::xsd::cxx::tree::as_double< Double > AsDouble; /** * @brief Serialization wrapper for the %decimal type. */ typedef ::xsd::cxx::tree::as_decimal< Decimal > AsDecimal; /** * @brief Simple type facet. */ typedef ::xsd::cxx::tree::facet Facet; // Flags and properties. // /** * @brief Parsing and serialization flags. */ typedef ::xsd::cxx::tree::flags Flags; /** * @brief Parsing properties. */ typedef ::xsd::cxx::tree::properties< char > Properties; // Parsing/serialization diagnostics. // /** * @brief Error severity. */ typedef ::xsd::cxx::tree::severity Severity; /** * @brief Error condition. */ typedef ::xsd::cxx::tree::error< char > Error; /** * @brief List of %error conditions. */ typedef ::xsd::cxx::tree::diagnostics< char > Diagnostics; // Exceptions. // /** * @brief Root of the C++/Tree %exception hierarchy. */ typedef ::xsd::cxx::tree::exception< char > Exception; /** * @brief Exception indicating that the size argument exceeds * the capacity argument. */ typedef ::xsd::cxx::tree::bounds< char > Bounds; /** * @brief Exception indicating that a duplicate ID value * was encountered in the object model. */ typedef ::xsd::cxx::tree::duplicate_id< char > DuplicateId; /** * @brief Exception indicating a parsing failure. */ typedef ::xsd::cxx::tree::parsing< char > Parsing; /** * @brief Exception indicating that an expected element * was not encountered. */ typedef ::xsd::cxx::tree::expected_element< char > ExpectedElement; /** * @brief Exception indicating that an unexpected element * was encountered. */ typedef ::xsd::cxx::tree::unexpected_element< char > UnexpectedElement; /** * @brief Exception indicating that an expected attribute * was not encountered. */ typedef ::xsd::cxx::tree::expected_attribute< char > ExpectedAttribute; /** * @brief Exception indicating that an unexpected enumerator * was encountered. */ typedef ::xsd::cxx::tree::unexpected_enumerator< char > UnexpectedEnumerator; /** * @brief Exception indicating that the text content was * expected for an element. */ typedef ::xsd::cxx::tree::expected_text_content< char > ExpectedTextContent; /** * @brief Exception indicating that a prefix-namespace * mapping was not provided. */ typedef ::xsd::cxx::tree::no_prefix_mapping< char > NoPrefixMapping; /** * @brief Exception indicating that the type information * is not available for a type. */ typedef ::xsd::cxx::tree::no_type_info< char > NoTypeInfo; /** * @brief Exception indicating that the types are not * related by inheritance. */ typedef ::xsd::cxx::tree::not_derived< char > NotDerived; /** * @brief Exception indicating a serialization failure. */ typedef ::xsd::cxx::tree::serialization< char > Serialization; /** * @brief Error handler callback interface. */ typedef ::xsd::cxx::xml::error_handler< char > ErrorHandler; /** * @brief DOM interaction. */ namespace dom { /** * @brief Automatic pointer for DOMDocument. */ using ::xsd::cxx::xml::dom::auto_ptr; #ifndef XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA #define XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA /** * @brief DOM user data key for back pointers to tree nodes. */ const XMLCh* const tree_node_key = ::xsd::cxx::tree::user_data_keys::node; #endif } } #include "aosl/event_forward.hpp" // Forward declarations. // namespace aosl { class Navigation; } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue. #endif // AOSLCPP_AOSL__NAVIGATION_FORWARD_HPP
[ "klaim@localhost" ]
[ [ [ 1, 610 ] ] ]
988c91e1739aa4b473ec4199e098a78db45141fe
e03ee4538dce040fe16fc7bb48d495735ac324f4
/Stable/SteeringBehaviors/BehaviorsObs.cpp
705ddd6d770fcc46614aba263b44a8ba95b0bd3e
[]
no_license
vdelgadov/itcvideogame
dca6bcb084c5dde25ecf29ab1555dbe8b0a9a441
5eac60e901b29bff4d844f34cd52f97f4d1407b5
refs/heads/master
2020-05-16T23:43:48.956373
2009-12-01T02:09:08
2009-12-01T02:09:08
42,265,496
0
0
null
null
null
null
UTF-8
C++
false
false
2,933
cpp
#include "stdafx.h" #define _USE_MATH_DEFINES #include <math.h> #include <time.h> Vector2D SteeringBehaviors::seek(Vector2D t_pos, Vehicle* veh){ Vector2D steering_force = (t_pos - veh->getPos()); if(steering_force.magnitude() < veh->getMaxSpeed()) return Vector2D(); steering_force.normalize(); steering_force *= veh->getMaxSpeed() ; return steering_force; } Vector2D SteeringBehaviors::flee(Vector2D t_pos, Vehicle* veh){ Vector2D steering_force = (veh->getPos() - t_pos); if(steering_force.magnitude() > 10){ steering_force = Vector2D(); return steering_force; } steering_force.normalize(); steering_force *= veh->getMaxSpeed(); return steering_force; } Vector2D SteeringBehaviors::pursuit(Vehicle *veh, Vehicle *target){ Vector2D calcSpot = target->getHeading()*target->getMaxSpeed() + target->getPos(); return SteeringBehaviors::seek(calcSpot, veh); } Vector2D SteeringBehaviors::evade(Vehicle* veh, Vehicle* pursuer){ Vector2D calcSpot = pursuer->getHeading()*pursuer->getMaxSpeed() + pursuer->getPos(); return SteeringBehaviors::flee(calcSpot, veh); } Vector2D SteeringBehaviors::wander(Vehicle *veh, double wander_radius, double wander_distance){ double theta = (double(rand())/RAND_MAX)*2*M_PI; double y = wander_radius * sin(theta); double x = wander_radius * cos(theta); Vector2D wander_vec = Vector2D(x, y); Vector2D wander_offset = Vector2D(wander_distance/2, wander_distance/2); wander_vec += wander_offset; wander_vec.normalize(); return wander_vec * veh->getMaxSpeed();// - veh->getPos(); } Vector2D SteeringBehaviors::interpose(Vehicle *veh, Vehicle *to_int1, Vector2D point){ Vector2D calc_spot = to_int1->getCurrVel() + to_int1->getPos(); Vector2D new_spot = calc_spot - point; new_spot *= 0.5; return SteeringBehaviors::seek(new_spot, veh); } Vector2D SteeringBehaviors::interpose(Vehicle *veh, Vehicle *to_int1, Vehicle *to_int2){ Vector2D calc_spot1 = to_int1->getCurrVel() + to_int1->getPos(); Vector2D calc_spot2 = to_int2->getCurrVel() + to_int2->getPos(); Vector2D new_spot = calc_spot2 - calc_spot1; new_spot *= 0.5; new_spot += calc_spot1; return SteeringBehaviors::seek(new_spot, veh); } Vector2D SteeringBehaviors::interpose(Vehicle *veh, Vector2D point1, Vector2D point2){ Vector2D new_spot = point2 - point1; new_spot *= 0.5; new_spot += point1; return SteeringBehaviors::seek(new_spot, veh); } /*void SteeringBehaviors::align(std::list<Vehicle*> nbors){ std::list<Vehicle>::iterator it; Vector2D avg; double sum_x, sum_y; int ents = 0; for(it = nbors.begin(); it != nbors.end(); it++){ sum_x += (*it)->getPos().x; sum_y += (*it)->getPos().y; ++ents; } if(ents != 0){ avg = Vector2D(sum_x/ents, sum_y/ents); } for(it = nbors.begin(); it != nbors.end(); it++){ (*it)->setCurrVel(avg); } }*/
[ "victor.delgadov@972b8bf6-92a2-11de-b72a-e7346c8bff7a" ]
[ [ [ 1, 98 ] ] ]
91c64c1ea5a6fa3a789558ff596bca3866ce9f89
6520b2b1c45e5a9e5996a9205142de6e2e2cb7ea
/AHL/wolfilair/src/lib/tools/dialog/Dialog.cpp
2a7a8201df30bf1b0891a15be08839f37c436e90
[]
no_license
xpierro/ahl
6207bc2c309a7f2e4bf659e86fcbf4d889250d82
8efd98a6ecc32d794a1e957b0b91eb017546fdf1
refs/heads/master
2020-06-04T00:59:13.590942
2010-10-21T04:09:48
2010-10-21T04:09:48
41,411,324
0
0
null
null
null
null
ISO-8859-2
C++
false
false
724
cpp
/* * Dialog.cpp * * Created on: 13 oct. 2010 * Author: Pierre */ #include "Dialog.h" #include <stdio.h> #include <sysutil/sysutil_msgdialog.h> namespace PS3 { Dialog::Dialog() { type = 0; } Dialog::~Dialog() { // TODO Auto-generated destructor stub } /** * object sera casté en Dialog pour appeler la méthode executeCallback */ static void dialogCallback(int buttonType, void* object) { Dialog* dialog = static_cast<Dialog*>(object); dialog->executeCallback(buttonType); } /** * On affiche le message. */ void Dialog::show() { cellMsgDialogOpen2(type, msg.c_str(), dialogCallback, this, NULL); } void Dialog::closeDialogs() { cellMsgDialogAbort(); } }
[ [ [ 1, 41 ] ] ]
3afb68b14573775d9ef4cef41ec47550fe0b7959
11af1673bab82ca2329ef8b596d1f3d2f8b82481
/source/cgame/cg_draw_newhud.cpp
1d2392c368b44259df7a9686b98aa2af0694a689
[]
no_license
legacyrp/legacyojp
8b33ecf24fd973bee5e7adbd369748cfdd891202
d918151e917ea06e8698f423bbe2cf6ab9d7f180
refs/heads/master
2021-01-10T20:09:55.748893
2011-04-18T21:07:13
2011-04-18T21:07:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
215,673
cpp
// Copyright (C) 1999-2000 Id Software, Inc. // // cg_draw.c -- draw all of the graphical elements during // active (after loading) gameplay #include "cg_local.h" #include "bg_saga.h" #include "../ui/ui_shared.h" #include "../ui/ui_public.h" //[AddText] char atText[64][64] = {""}; int atYPos[64] = {0}; int atTime[64] = {0}; int atCount = 0; //[/AddText] extern float CG_RadiusForCent( centity_t *cent ); qboolean CG_WorldCoordToScreenCoordFloat(vec3_t worldCoord, float *x, float *y); qboolean CG_CalcMuzzlePoint( int entityNum, vec3_t muzzle ); static void CG_DrawSiegeTimer(int timeRemaining, qboolean isMyTeam); static void CG_DrawSiegeDeathTimer( int timeRemaining ); // nmckenzie: DUEL_HEALTH void CG_DrawDuelistHealth ( float x, float y, float w, float h, int duelist ); // used for scoreboard extern displayContextDef_t cgDC; menuDef_t *menuScoreboard = NULL; vec4_t bluehudtint = {0.5, 0.5, 1.0, 1.0}; vec4_t redhudtint = {1.0, 0.5, 0.5, 1.0}; float *hudTintColor; int sortedTeamPlayers[TEAM_MAXOVERLAY]; int numSortedTeamPlayers; int lastvalidlockdif; extern float zoomFov; //this has to be global client-side char systemChat[256]; char teamChat1[256]; char teamChat2[256]; // The time at which you died and the time it will take for you to rejoin game. int cg_siegeDeathTime = 0; //[LOLHUD] /* #define MAX_HUD_TICS 4 const char *armorTicName[MAX_HUD_TICS] = { "armor_tic1", "armor_tic2", "armor_tic3", "armor_tic4", }; const char *forceTicName[MAX_HUD_TICS] = { "force_tic1", "force_tic2", "force_tic3", "force_tic4", }; const char *ammoTicName[MAX_HUD_TICS] = { "ammo_tic1", "ammo_tic2", "ammo_tic3", "ammo_tic4", */ //[/LOLHUD] char *showPowersName[] = { "HEAL2",//FP_HEAL "JUMP2",//FP_LEVITATION "SPEED2",//FP_SPEED "PUSH2",//FP_PUSH "PULL2",//FP_PULL "MINDTRICK2",//FP_TELEPTAHY "GRIP2",//FP_GRIP "LIGHTNING2",//FP_LIGHTNING "DARK_RAGE2",//FP_RAGE "PROTECT2",//FP_MANIPULATE "ABSORB2",//FP_ABSORB "TEAM_HEAL2",//FP_TEAM_HEAL "TEAM_REPLENISH2",//FP_LIFT "DRAIN2",//FP_DRAIN "SEEING2",//FP_SEE "SABER_OFFENSE2",//FP_SABER_OFFENSE "SABER_DEFENSE2",//FP_SABER_DEFENSE "SABER_THROW2",//FP_SABERTHROW NULL }; //Called from UI shared code. For now we'll just redirect to the normal anim load function. #include "../namespace_begin.h" int UI_ParseAnimationFile(const char *filename, animation_t *animset, qboolean isHumanoid) { return BG_ParseAnimationFile(filename, animset, isHumanoid); } int MenuFontToHandle(int iMenuFont) { switch (iMenuFont) { case FONT_SMALL: return cgDC.Assets.qhSmallFont; case FONT_SMALL2: return cgDC.Assets.qhSmall2Font; case FONT_MEDIUM: return cgDC.Assets.qhMediumFont; case FONT_LARGE: return cgDC.Assets.qhMediumFont;//cgDC.Assets.qhBigFont; //fixme? Big fonr isn't registered...? } return cgDC.Assets.qhMediumFont; } #include "../namespace_end.h" int CG_Text_Width(const char *text, float scale, int iMenuFont) { int iFontIndex = MenuFontToHandle(iMenuFont); return trap_R_Font_StrLenPixels(text, iFontIndex, scale); } int CG_Text_Height(const char *text, float scale, int iMenuFont) { int iFontIndex = MenuFontToHandle(iMenuFont); return trap_R_Font_HeightPixels(iFontIndex, scale); } #include "../qcommon/qfiles.h" // for STYLE_BLINK etc void CG_Text_Paint(float x, float y, float scale, vec4_t color, const char *text, float adjust, int limit, int style, int iMenuFont) { int iStyleOR = 0; int iFontIndex = MenuFontToHandle(iMenuFont); switch (style) { case ITEM_TEXTSTYLE_NORMAL: iStyleOR = 0;break; // JK2 normal text case ITEM_TEXTSTYLE_BLINK: iStyleOR = STYLE_BLINK;break; // JK2 fast blinking case ITEM_TEXTSTYLE_PULSE: iStyleOR = STYLE_BLINK;break; // JK2 slow pulsing case ITEM_TEXTSTYLE_SHADOWED: iStyleOR = (int)STYLE_DROPSHADOW;break; // JK2 drop shadow ( need a color for this ) case ITEM_TEXTSTYLE_OUTLINED: iStyleOR = (int)STYLE_DROPSHADOW;break; // JK2 drop shadow ( need a color for this ) case ITEM_TEXTSTYLE_OUTLINESHADOWED: iStyleOR = (int)STYLE_DROPSHADOW;break; // JK2 drop shadow ( need a color for this ) case ITEM_TEXTSTYLE_SHADOWEDMORE: iStyleOR = (int)STYLE_DROPSHADOW;break; // JK2 drop shadow ( need a color for this ) } trap_R_Font_DrawString( x, // int ox y, // int oy text, // const char *text color, // paletteRGBA_c c iStyleOR | iFontIndex, // const int iFontHandle !limit?-1:limit, // iCharLimit (-1 = none) scale // const float scale = 1.0f ); } /* ================ CG_DrawZoomMask ================ */ static void CG_DrawZoomMask( void ) { vec4_t color1; float level; static qboolean flip = qtrue; // int ammo = cg_entities[0].gent->client->ps.ammo[weaponData[cent->currentState.weapon].ammoIndex]; float cx, cy; // int val[5]; float max, fi; // Check for Binocular specific zooming since we'll want to render different bits in each case if ( cg.predictedPlayerState.zoomMode == 2 ) { int val, i; float off; // zoom level level = (float)(80.0f - cg.predictedPlayerState.zoomFov) / 80.0f; // ...so we'll clamp it if ( level < 0.0f ) { level = 0.0f; } else if ( level > 1.0f ) { level = 1.0f; } // Using a magic number to convert the zoom level to scale amount level *= 162.0f; // draw blue tinted distortion mask, trying to make it as small as is necessary to fill in the viewable area trap_R_SetColor( colorTable[CT_WHITE] ); CG_DrawPic( 34, 48, 570, 362, cgs.media.binocularStatic ); // Black out the area behind the numbers trap_R_SetColor( colorTable[CT_BLACK]); CG_DrawPic( 212, 367, 200, 40, cgs.media.whiteShader ); // Numbers should be kind of greenish color1[0] = 0.2f; color1[1] = 0.4f; color1[2] = 0.2f; color1[3] = 0.3f; trap_R_SetColor( color1 ); // Draw scrolling numbers, use intervals 10 units apart--sorry, this section of code is just kind of hacked // up with a bunch of magic numbers..... val = ((int)((cg.refdef.viewangles[YAW] + 180) / 10)) * 10; off = (cg.refdef.viewangles[YAW] + 180) - val; for ( i = -10; i < 30; i += 10 ) { val -= 10; if ( val < 0 ) { val += 360; } // we only want to draw the very far left one some of the time, if it's too far to the left it will // poke outside the mask. if (( off > 3.0f && i == -10 ) || i > -10 ) { // draw the value, but add 200 just to bump the range up...arbitrary, so change it if you like CG_DrawNumField( 155 + i * 10 + off * 10, 374, 3, val + 200, 24, 14, NUM_FONT_CHUNKY, qtrue ); CG_DrawPic( 245 + (i-1) * 10 + off * 10, 376, 6, 6, cgs.media.whiteShader ); } } CG_DrawPic( 212, 367, 200, 28, cgs.media.binocularOverlay ); color1[0] = sin( cg.time * 0.01f ) * 0.5f + 0.5f; color1[0] = color1[0] * color1[0]; color1[1] = color1[0]; color1[2] = color1[0]; color1[3] = 1.0f; trap_R_SetColor( color1 ); CG_DrawPic( 82, 94, 16, 16, cgs.media.binocularCircle ); // Flickery color color1[0] = 0.7f + crandom() * 0.1f; color1[1] = 0.8f + crandom() * 0.1f; color1[2] = 0.7f + crandom() * 0.1f; color1[3] = 1.0f; trap_R_SetColor( color1 ); CG_DrawPic( 0, 0, 640, 480, cgs.media.binocularMask ); CG_DrawPic( 4, 282 - level, 16, 16, cgs.media.binocularArrow ); // The top triangle bit randomly flips if ( flip ) { CG_DrawPic( 330, 60, -26, -30, cgs.media.binocularTri ); } else { CG_DrawPic( 307, 40, 26, 30, cgs.media.binocularTri ); } if ( random() > 0.98f && ( cg.time & 1024 )) { flip = (qboolean)(!flip); } } else if ( cg.predictedPlayerState.zoomMode == 1 && cg.predictedPlayerState.weapon != WP_BOWCASTER) { // disruptor zoom mode level = (float)(50.0f - zoomFov) / 50.0f;//(float)(80.0f - zoomFov) / 80.0f; // ...so we'll clamp it if ( level < 0.0f ) { level = 0.0f; } else if ( level > 1.0f ) { level = 1.0f; } // Using a magic number to convert the zoom level to a rotation amount that correlates more or less with the zoom artwork. level *= 103.0f; // Draw target mask trap_R_SetColor( colorTable[CT_WHITE] ); CG_DrawPic( 0, 0, 640, 480, cgs.media.disruptorMask ); // apparently 99.0f is the full zoom level if ( level >= 96) { // Fully zoomed, so make the rotating insert pulse color1[0] = 1.0f; color1[1] = 1.0f; color1[2] = 1.0f; color1[3] = 0.7f + sin( cg.time * 0.01f ) * 0.3f; trap_R_SetColor( color1 ); } // Draw rotating insert CG_DrawRotatePic2( 320, 240, 640, 480, -level, cgs.media.disruptorInsert ); if ( (cg.snap->ps.eFlags & EF_DOUBLE_AMMO) ) { max = cg.snap->ps.ammo[weaponData[WP_DISRUPTOR].ammoIndex] / ((float)ammoData[weaponData[WP_DISRUPTOR].ammoIndex].max*2.0f); } else { max = cg.snap->ps.ammo[weaponData[WP_DISRUPTOR].ammoIndex] / (float)ammoData[weaponData[WP_DISRUPTOR].ammoIndex].max; } if ( max > 1.0f ) { max = 1.0f; } color1[0] = (1.0f - max) * 2.0f; color1[1] = max * 1.5f; color1[2] = 0.0f; color1[3] = 1.0f; // If we are low on health, make us flash if ( max < 0.15f && ( cg.time & 512 )) { VectorClear( color1 ); } if ( color1[0] > 1.0f ) { color1[0] = 1.0f; } if ( color1[1] > 1.0f ) { color1[1] = 1.0f; } trap_R_SetColor( color1 ); max *= 58.0f; for (fi = 18.5f; fi <= 18.5f + max; fi+= 3 ) // going from 15 to 45 degrees, with 5 degree increments { cx = 320 + sin( (fi+90.0f)/57.296f ) * 190; cy = 240 + cos( (fi+90.0f)/57.296f ) * 190; CG_DrawRotatePic2( cx, cy, 12, 24, 90 - fi, cgs.media.disruptorInsertTick ); } if ( cg.predictedPlayerState.weaponstate == WEAPON_CHARGING_ALT ) { trap_R_SetColor( colorTable[CT_WHITE] ); // draw the charge level max = ( cg.time - cg.predictedPlayerState.weaponChargeTime ) / ( 50.0f * 30.0f ); // bad hardcodedness 50 is disruptor charge unit and 30 is max charge units allowed. if ( max > 1.0f ) { max = 1.0f; } trap_R_DrawStretchPic(257, 435, 134*max, 34, 0, 0, max, 1, cgs.media.disruptorChargeShader); } // trap_R_SetColor( colorTable[CT_WHITE] ); // CG_DrawPic( 0, 0, 640, 480, cgs.media.disruptorMask ); } } /* ================ CG_Draw3DModel ================ */ void CG_Draw3DModel( float x, float y, float w, float h, qhandle_t model, void *ghoul2, int g2radius, qhandle_t skin, vec3_t origin, vec3_t angles ) { refdef_t refdef; refEntity_t ent; if ( !cg_draw3dIcons.integer || !cg_drawIcons.integer ) { return; } memset( &refdef, 0, sizeof( refdef ) ); memset( &ent, 0, sizeof( ent ) ); AnglesToAxis( angles, ent.axis ); VectorCopy( origin, ent.origin ); ent.hModel = model; ent.ghoul2 = ghoul2; ent.radius = g2radius; ent.customSkin = skin; ent.renderfx = RF_NOSHADOW; // no stencil shadows refdef.rdflags = RDF_NOWORLDMODEL; AxisClear( refdef.viewaxis ); refdef.fov_x = 30; refdef.fov_y = 30; refdef.x = x; refdef.y = y; refdef.width = w; refdef.height = h; refdef.time = cg.time; trap_R_ClearScene(); trap_R_AddRefEntityToScene( &ent ); trap_R_RenderScene( &refdef ); } /* ================ CG_DrawHead Used for both the status bar and the scoreboard ================ */ void CG_DrawHead( float x, float y, float w, float h, int clientNum, vec3_t headAngles ) { clientInfo_t *ci; if (clientNum >= MAX_CLIENTS) { //npc? return; } ci = &cgs.clientinfo[ clientNum ]; CG_DrawPic( x, y, w, h, ci->modelIcon ); // if they are deferred, draw a cross out if ( ci->deferred ) { CG_DrawPic( x, y, w, h, cgs.media.deferShader ); } } /* ================ CG_DrawFlagModel Used for both the status bar and the scoreboard ================ */ void CG_DrawFlagModel( float x, float y, float w, float h, int team, qboolean force2D ) { qhandle_t cm; float len; vec3_t origin, angles; vec3_t mins, maxs; qhandle_t handle; if ( !force2D && cg_draw3dIcons.integer ) { VectorClear( angles ); cm = cgs.media.redFlagModel; // offset the origin y and z to center the flag trap_R_ModelBounds( cm, mins, maxs ); origin[2] = -0.5 * ( mins[2] + maxs[2] ); origin[1] = 0.5 * ( mins[1] + maxs[1] ); // calculate distance so the flag nearly fills the box // assume heads are taller than wide len = 0.5 * ( maxs[2] - mins[2] ); origin[0] = len / 0.268; // len / tan( fov/2 ) angles[YAW] = 60 * sin( cg.time / 2000.0 );; if( team == TEAM_RED ) { handle = cgs.media.redFlagModel; } else if( team == TEAM_BLUE ) { handle = cgs.media.blueFlagModel; } else if( team == TEAM_FREE ) { handle = 0;//cgs.media.neutralFlagModel; } else { return; } CG_Draw3DModel( x, y, w, h, handle, NULL, 0, 0, origin, angles ); } else if ( cg_drawIcons.integer ) { gitem_t *item; if( team == TEAM_RED ) { item = BG_FindItemForPowerup( PW_REDFLAG ); } else if( team == TEAM_BLUE ) { item = BG_FindItemForPowerup( PW_BLUEFLAG ); } else if( team == TEAM_FREE ) { item = BG_FindItemForPowerup( PW_NEUTRALFLAG ); } else { return; } if (item) { CG_DrawPic( x, y, w, h, cg_items[ ITEM_INDEX(item) ].icon ); } } } /* ================ DrawAmmo ================ */ void DrawAmmo() { int x, y; x = SCREEN_WIDTH-80; y = SCREEN_HEIGHT-80; } //[LOLHUD] /* ================ CG_DrawHealth ================ *//* void CG_DrawHealth( menuDef_t *menuHUD ) { vec4_t calcColor; playerState_t *ps; int healthAmt; int i,currValue,inc; itemDef_t *focusItem; float percent; // Can we find the menu? if (!menuHUD) { return; } ps = &cg.snap->ps; // What's the health? healthAmt = ps->stats[STAT_HEALTH]; if (healthAmt > ps->stats[STAT_MAX_HEALTH]) { healthAmt = ps->stats[STAT_MAX_HEALTH]; } inc = (float) ps->stats[STAT_MAX_HEALTH] / MAX_HUD_TICS; currValue = healthAmt; // Print the health tics, fading out the one which is partial health for (i=(MAX_HUD_TICS-1);i>=0;i--) { focusItem = Menu_FindItemByName(menuHUD, healthTicName[i]); if (!focusItem) // This is bad { continue; } memcpy(calcColor, hudTintColor, sizeof(vec4_t)); if (currValue <= 0) // don't show tic { break; } else if (currValue < inc) // partial tic (alpha it out) { percent = (float) currValue / inc; calcColor[3] *= percent; // Fade it out } trap_R_SetColor( calcColor); CG_DrawPic( focusItem->window.rect.x, focusItem->window.rect.y, focusItem->window.rect.w, focusItem->window.rect.h, focusItem->window.background ); currValue -= inc; } // Print the mueric amount focusItem = Menu_FindItemByName(menuHUD, "healthamount"); if (focusItem) { // Print health amount trap_R_SetColor( focusItem->window.foreColor ); CG_DrawNumField ( focusItem->window.rect.x, focusItem->window.rect.y, 3, ps->stats[STAT_HEALTH], focusItem->window.rect.w, focusItem->window.rect.h, NUM_FONT_SMALL, qfalse); } } /* ================ CG_DrawArmor ================ *//* void CG_DrawArmor( menuDef_t *menuHUD ) { vec4_t calcColor; playerState_t *ps; int armor, maxArmor; itemDef_t *focusItem; float percent,quarterArmor; int i,currValue,inc; //ps = &cg.snap->ps; ps = &cg.predictedPlayerState; // Can we find the menu? if (!menuHUD) { return; } armor = ps->stats[STAT_ARMOR]; maxArmor = ps->stats[STAT_MAX_HEALTH]; if (armor> maxArmor) { armor = maxArmor; } currValue = armor; inc = (float) maxArmor / MAX_HUD_TICS; memcpy(calcColor, hudTintColor, sizeof(vec4_t)); for (i=(MAX_HUD_TICS-1);i>=0;i--) { focusItem = Menu_FindItemByName(menuHUD, armorTicName[i]); if (!focusItem) // This is bad { continue; } memcpy(calcColor, hudTintColor, sizeof(vec4_t)); if (currValue <= 0) // don't show tic { break; } else if (currValue < inc) // partial tic (alpha it out) { percent = (float) currValue / inc; calcColor[3] *= percent; } trap_R_SetColor( calcColor); if ((i==(MAX_HUD_TICS-1)) && (currValue < inc)) { if (cg.HUDArmorFlag) { CG_DrawPic( focusItem->window.rect.x, focusItem->window.rect.y, focusItem->window.rect.w, focusItem->window.rect.h, focusItem->window.background ); } } else { CG_DrawPic( focusItem->window.rect.x, focusItem->window.rect.y, focusItem->window.rect.w, focusItem->window.rect.h, focusItem->window.background ); } currValue -= inc; } focusItem = Menu_FindItemByName(menuHUD, "armoramount"); if (focusItem) { // Print armor amount trap_R_SetColor( focusItem->window.foreColor ); CG_DrawNumField ( focusItem->window.rect.x, focusItem->window.rect.y, 3, armor, focusItem->window.rect.w, focusItem->window.rect.h, NUM_FONT_SMALL, qfalse); } // If armor is low, flash a graphic to warn the player if (armor) // Is there armor? Draw the HUD Armor TIC { quarterArmor = (float) (ps->stats[STAT_MAX_HEALTH] / 4.0f); // Make tic flash if armor is at 25% of full armor if (ps->stats[STAT_ARMOR] < quarterArmor) // Do whatever the flash timer says { if (cg.HUDTickFlashTime < cg.time) // Flip at the same time { cg.HUDTickFlashTime = cg.time + 400; if (cg.HUDArmorFlag) { cg.HUDArmorFlag = qfalse; } else { cg.HUDArmorFlag = qtrue; } } } else { cg.HUDArmorFlag=qtrue; } } else // No armor? Don't show it. { cg.HUDArmorFlag=qfalse; } } */ /* ================ CG_DrawSaberStyle If the weapon is a light saber (which needs no ammo) then draw a graphic showing the saber style (fast, medium, strong) ================ *//* static void CG_DrawSaberStyle( centity_t *cent, menuDef_t *menuHUD) { itemDef_t *focusItem; if (!cent->currentState.weapon ) // We don't have a weapon right now { return; } if ( cent->currentState.weapon != WP_SABER ) { return; } // Can we find the menu? if (!menuHUD) { return; } // draw the current saber style in this window switch ( cg.predictedPlayerState.fd.saberDrawAnimLevel ) { case 1://FORCE_LEVEL_1: case 5://FORCE_LEVEL_5://Tavion focusItem = Menu_FindItemByName(menuHUD, "saberstyle_fast"); if (focusItem) { trap_R_SetColor( hudTintColor ); CG_DrawPic( focusItem->window.rect.x, focusItem->window.rect.y, focusItem->window.rect.w, focusItem->window.rect.h, focusItem->window.background ); } break; case 2://FORCE_LEVEL_2: case 6://SS_DUAL case 7://SS_STAFF focusItem = Menu_FindItemByName(menuHUD, "saberstyle_medium"); if (focusItem) { trap_R_SetColor( hudTintColor ); CG_DrawPic( focusItem->window.rect.x, focusItem->window.rect.y, focusItem->window.rect.w, focusItem->window.rect.h, focusItem->window.background ); } break; case 3://FORCE_LEVEL_3: case 4://FORCE_LEVEL_4://Desann focusItem = Menu_FindItemByName(menuHUD, "saberstyle_strong"); if (focusItem) { trap_R_SetColor( hudTintColor ); CG_DrawPic( focusItem->window.rect.x, focusItem->window.rect.y, focusItem->window.rect.w, focusItem->window.rect.h, focusItem->window.background ); } break; } } /* ================ CG_DrawAmmo ================ *//* static void CG_DrawAmmo( centity_t *cent,menuDef_t *menuHUD) { playerState_t *ps; int i; vec4_t calcColor; float value,inc = 0.0f,percent; itemDef_t *focusItem; ps = &cg.snap->ps; // Can we find the menu? if (!menuHUD) { return; } if (!cent->currentState.weapon ) // We don't have a weapon right now { return; } value = ps->ammo[weaponData[cent->currentState.weapon].ammoIndex]; if (value < 0) // No ammo { return; } focusItem = Menu_FindItemByName(menuHUD, "ammoamount"); trap_R_SetColor( hudTintColor ); if (weaponData[cent->currentState.weapon].energyPerShot == 0 && weaponData[cent->currentState.weapon].altEnergyPerShot == 0) { //just draw "infinite" inc = 8 / MAX_HUD_TICS; value = 8; focusItem = Menu_FindItemByName(menuHUD, "ammoinfinite"); trap_R_SetColor( hudTintColor ); if (focusItem) { UI_DrawProportionalString(focusItem->window.rect.x, focusItem->window.rect.y, "--", NUM_FONT_SMALL, focusItem->window.foreColor); } } else { focusItem = Menu_FindItemByName(menuHUD, "ammoamount"); trap_R_SetColor( hudTintColor ); if (focusItem) { if ( (cent->currentState.eFlags & EF_DOUBLE_AMMO) ) { inc = (float) (ammoData[weaponData[cent->currentState.weapon].ammoIndex].max*2.0f) / MAX_HUD_TICS; } else { inc = (float) ammoData[weaponData[cent->currentState.weapon].ammoIndex].max / MAX_HUD_TICS; } value =ps->ammo[weaponData[cent->currentState.weapon].ammoIndex]; CG_DrawNumField ( focusItem->window.rect.x, focusItem->window.rect.y, 3, value, focusItem->window.rect.w, focusItem->window.rect.h, NUM_FONT_SMALL, qfalse); } } // Draw tics for (i=MAX_HUD_TICS-1;i>=0;i--) { focusItem = Menu_FindItemByName(menuHUD, ammoTicName[i]); if (!focusItem) { continue; } memcpy(calcColor, hudTintColor, sizeof(vec4_t)); if ( value <= 0 ) // done { break; } else if (value < inc) // partial tic { percent = value / inc; calcColor[3] = percent; } trap_R_SetColor( calcColor); CG_DrawPic( focusItem->window.rect.x, focusItem->window.rect.y, focusItem->window.rect.w, focusItem->window.rect.h, focusItem->window.background ); value -= inc; } } /* ================ CG_DrawForcePower ================ *//* void CG_DrawForcePower( menuDef_t *menuHUD ) { int i; vec4_t calcColor; float value,inc,percent; itemDef_t *focusItem; const int maxForcePower = 100; qboolean flash=qfalse; // Can we find the menu? if (!menuHUD) { return; } // Make the hud flash by setting forceHUDTotalFlashTime above cg.time if (cg.forceHUDTotalFlashTime > cg.time ) { flash = qtrue; if (cg.forceHUDNextFlashTime < cg.time) { cg.forceHUDNextFlashTime = cg.time + 400; trap_S_StartSound (NULL, 0, CHAN_LOCAL, cgs.media.noforceSound ); if (cg.forceHUDActive) { cg.forceHUDActive = qfalse; } else { cg.forceHUDActive = qtrue; } } } else // turn HUD back on if it had just finished flashing time. { cg.forceHUDNextFlashTime = 0; cg.forceHUDActive = qtrue; } // if (!cg.forceHUDActive) // { // return; // } inc = (float) maxForcePower / MAX_HUD_TICS; value = cg.snap->ps.fd.forcePower; for (i=MAX_HUD_TICS-1;i>=0;i--) { focusItem = Menu_FindItemByName(menuHUD, forceTicName[i]); if (!focusItem) { continue; } // memcpy(calcColor, hudTintColor, sizeof(vec4_t)); if ( value <= 0 ) // done { break; } else if (value < inc) // partial tic { if (flash) { memcpy(calcColor, colorTable[CT_RED], sizeof(vec4_t)); } else { memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); } percent = value / inc; calcColor[3] = percent; } else { if (flash) { memcpy(calcColor, colorTable[CT_RED], sizeof(vec4_t)); } else { memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); } } trap_R_SetColor( calcColor); CG_DrawPic( focusItem->window.rect.x, focusItem->window.rect.y, focusItem->window.rect.w, focusItem->window.rect.h, focusItem->window.background ); value -= inc; } focusItem = Menu_FindItemByName(menuHUD, "forceamount"); if (focusItem) { // Print force amount trap_R_SetColor( focusItem->window.foreColor ); CG_DrawNumField ( focusItem->window.rect.x, focusItem->window.rect.y, 3, cg.snap->ps.fd.forcePower, focusItem->window.rect.w, focusItem->window.rect.h, NUM_FONT_SMALL, qfalse); } } */ //[/LOLHUD] //[AddText] void CG_AddToAddText(char *text) { if(strlen(text) >= 64) { CG_Printf("AddText ERROR: Text length is bigger then 64 characters!\n"); return; } if(atCount >= 64) { CG_Printf("AddText ERROR: Already have 64 items on AddText box! (And can't add anymoar currently)\n"); return; } strcpy(atText[atCount], text); if(atCount > 0) { for(int i = 0;i < atCount;i++) { atYPos[i] += 20; } } atTime[atCount] = cg.time + 5000; atCount++; } void CG_RemoveFromAddText() { //atText[0] = ""; //atPos[0] = 0; for(int i = 1;i < atCount; i++) { strcpy(atText[i-1],atText[i]); atYPos[i-1] = atYPos[i]; atTime[i-1] = atTime[i]; } strcpy(atText[atCount-1], ""); atCount--; } void CG_UpdateAddText() { if(atCount > 0 && atTime[0] <= cg.time) CG_RemoveFromAddText(); } float CG_DrawAddText(float y) { int i = 0; CG_UpdateAddText(); y += 10; for(i = 0;i < 20; i++) { if(atText[i] != NULL && Q_stricmp(atText[i],"")) { CG_Text_Paint(700 - CG_Text_Width(atText[i],1.0f,FONT_SMALL), y + atYPos[i], 1.0f, colorWhite, atText[i], 0, 0, 0, FONT_SMALL2); } } return y; } //[/AddText] /* ================ CG_DrawHUD ================ */ void CG_DrawHUD(centity_t *cent) { menuDef_t *menuHUD = NULL; //[LOLHUD] //itemDef_t *focusItem = NULL; int style = 0; //[/LOLHUD] const char *scoreStr = NULL; int scoreBias; char scoreBiasStr[16]; if (cg_hudFiles.integer) { int x = 0; int y = SCREEN_HEIGHT-80; char ammoString[64]; int weapX = x; UI_DrawProportionalString( x+16, y+40, va( "%i", cg.snap->ps.stats[STAT_HEALTH] ), UI_SMALLFONT|UI_DROPSHADOW, colorTable[CT_HUD_RED] ); UI_DrawProportionalString( x+18+14, y+40+14, va( "%i", cg.snap->ps.stats[STAT_ARMOR] ), UI_SMALLFONT|UI_DROPSHADOW, colorTable[CT_HUD_GREEN] ); if (cg.snap->ps.weapon == WP_SABER) { if (cg.snap->ps.fd.saberDrawAnimLevel == SS_DUAL) { Com_sprintf(ammoString, sizeof(ammoString), "AKIMBO"); weapX += 16; } else if (cg.snap->ps.fd.saberDrawAnimLevel == SS_STAFF) { Com_sprintf(ammoString, sizeof(ammoString), "STAFF"); weapX += 16; } else if (cg.snap->ps.fd.saberDrawAnimLevel == FORCE_LEVEL_3) { Com_sprintf(ammoString, sizeof(ammoString), "STRONG"); weapX += 16; } else if (cg.snap->ps.fd.saberDrawAnimLevel == FORCE_LEVEL_2) { Com_sprintf(ammoString, sizeof(ammoString), "MEDIUM"); weapX += 16; } else { Com_sprintf(ammoString, sizeof(ammoString), "FAST"); } } else { Com_sprintf(ammoString, sizeof(ammoString), "%i", cg.snap->ps.ammo[weaponData[cent->currentState.weapon].ammoIndex]); } UI_DrawProportionalString( SCREEN_WIDTH-(weapX+16+32), y+40, va( "%s", ammoString ), UI_SMALLFONT|UI_DROPSHADOW, colorTable[CT_HUD_ORANGE] ); UI_DrawProportionalString( SCREEN_WIDTH-(x+18+14+32), y+40+14, va( "%i", cg.snap->ps.fd.forcePower), UI_SMALLFONT|UI_DROPSHADOW, colorTable[CT_ICON_BLUE] ); return; } //[NewHud] //the new hud looks ugly if set with team colors. hudTintColor = colorTable[CT_WHITE]; //[/NewHud] //[LOLHUD] //LOLOL trap_R_SetColor( NULL ); //left frame //CG_DrawPic(0, 0, 160, 160, trap_R_RegisterShader( "gfx/hud/leftframe" )); menuHUD = Menus_FindByName("lefthud"); if (menuHUD) { // Print frame itemDef_t* focusItem = Menu_FindItemByName(menuHUD, "frame"); if (focusItem) { trap_R_SetColor( hudTintColor ); CG_DrawPic( focusItem->window.rect.x, focusItem->window.rect.y, focusItem->window.rect.w, focusItem->window.rect.h, focusItem->window.background ); } } menuHUD = Menus_FindByName("righthud"); if (menuHUD) { // Print frame itemDef_t* focusItem = Menu_FindItemByName(menuHUD, "frame"); if (focusItem) { trap_R_SetColor( hudTintColor ); CG_DrawPic( focusItem->window.rect.x, focusItem->window.rect.y, focusItem->window.rect.w, focusItem->window.rect.h, focusItem->window.background ); } } //right frame //CG_DrawPic(SCREEN_WIDTH-256, 0, 160, 160, trap_R_RegisterShader( "gfx/hud/rightframe" )); switch ( cg.predictedPlayerState.fd.saberDrawAnimLevel ) { case 1://SS_FAST: style = trap_R_RegisterShader( "gfx/hud/ss_fast" ); break; case 2://SS_MEDIUM: style = trap_R_RegisterShader( "gfx/hud/ss_medium" ); break; case 3://SS_STRONG: style = trap_R_RegisterShader( "gfx/hud/ss_strong" ); break; case 4://SS_DESANN style = trap_R_RegisterShader( "gfx/hud/ss_desann" ); break; case 5://SS_TAVION style = trap_R_RegisterShader( "gfx/hud/ss_tavion" ); break; case 6://SS_DUAL style = trap_R_RegisterShader( "gfx/hud/ss_dual" ); break; case 7://SS_STAFF style = trap_R_RegisterShader( "gfx/hud/ss_staff" ); break; } /* //health - numerical amount UI_OJPDrawColouredString( 40-20, 450, va("%i", cg.snap->ps.stats[STAT_HEALTH]), colorRed); //armor - numerical amount UI_OJPDrawColouredString( 72-20, 450, va("%i", cg.snap->ps.stats[STAT_ARMOR]), colorGreen); //defense - numerical amount UI_OJPDrawColouredString( 104-20, 450, va("%i", cg.snap->ps.stats[STAT_DODGE]), colorBlue); //force - numerical amount UI_OJPDrawColouredString( 136-20, 450, va("%i", cg.snap->ps.fd.forcePower), colorBlue); //balance - numerical amount UI_OJPDrawColouredString( 168-20, 450, va("%i", cg.snap->ps.fd.forcePower), colorBlue); */ if ( cent->currentState.weapon == WP_SABER ) {//it's a saber, draw the saberstyle CG_DrawPic( 136-20, 450, 128, 16, style); } else if (cent->currentState.weapon != WP_MELEE) {//ammo - numerical amount UI_OJPDrawColouredString( 136-20, 450, va("%i", cg.snap->ps.ammo[weaponData[cent->currentState.weapon].ammoIndex]), colorOrange); } /* // Draw the left HUD menuHUD = Menus_FindByName("lefthud"); if (menuHUD) { itemDef_t *focusItem; // Print scanline focusItem = Menu_FindItemByName(menuHUD, "scanline"); if (focusItem) { trap_R_SetColor( hudTintColor ); CG_DrawPic( focusItem->window.rect.x, focusItem->window.rect.y, focusItem->window.rect.w, focusItem->window.rect.h, focusItem->window.background ); } // Print frame focusItem = Menu_FindItemByName(menuHUD, "frame"); if (focusItem) { trap_R_SetColor( hudTintColor ); CG_DrawPic( focusItem->window.rect.x, focusItem->window.rect.y, focusItem->window.rect.w, focusItem->window.rect.h, focusItem->window.background ); } if (cg.predictedPlayerState.pm_type != PM_SPECTATOR) { CG_DrawArmor(menuHUD); CG_DrawHealth(menuHUD); } } else { //CG_Error("CG_ChatBox_ArrayInsert: unable to locate HUD menu file "); } */ //[/LOLHUD] //scoreStr = va("Score: %i", cgs.clientinfo[cg.snap->ps.clientNum].score); if ( cgs.gametype == GT_DUEL ) {//A duel that requires more than one kill to knock the current enemy back to the queue //show current kills out of how many needed scoreStr = va("%s: %i/%i", CG_GetStringEdString("MP_INGAME", "SCORE"), cg.snap->ps.persistant[PERS_SCORE], cgs.fraglimit); } else if (0 && cgs.gametype < GT_TEAM ) { // This is a teamless mode, draw the score bias. scoreBias = cg.snap->ps.persistant[PERS_SCORE] - cgs.scores1; if (scoreBias == 0) { // We are the leader! if (cgs.scores2 <= 0) { // Nobody to be ahead of yet. Com_sprintf(scoreBiasStr, sizeof(scoreBiasStr), ""); } else { scoreBias = cg.snap->ps.persistant[PERS_SCORE] - cgs.scores2; if (scoreBias == 0) { Com_sprintf(scoreBiasStr, sizeof(scoreBiasStr), " (Tie)"); } else { Com_sprintf(scoreBiasStr, sizeof(scoreBiasStr), " (+%d)", scoreBias); } } } else // if (scoreBias < 0) { // We are behind! Com_sprintf(scoreBiasStr, sizeof(scoreBiasStr), " (%d)", scoreBias); } scoreStr = va("%s: %i%s", CG_GetStringEdString("MP_INGAME", "SCORE"), cg.snap->ps.persistant[PERS_SCORE], scoreBiasStr); } else { // Don't draw a bias. scoreStr = va("%s: %i", CG_GetStringEdString("MP_INGAME", "SCORE"), cg.snap->ps.persistant[PERS_SCORE]); } menuHUD = Menus_FindByName("righthud"); if (menuHUD) { if (cgs.gametype != GT_POWERDUEL) { //[LOLHUD] /* focusItem = Menu_FindItemByName(menuHUD, "score_line"); if (focusItem) { UI_DrawScaledProportionalString( focusItem->window.rect.x, focusItem->window.rect.y, scoreStr, UI_RIGHT|UI_DROPSHADOW, focusItem->window.foreColor, 0.7); } */ //[/LOLHUD] } //[LOLHUD] /* // Print scanline focusItem = Menu_FindItemByName(menuHUD, "scanline"); if (focusItem) { trap_R_SetColor( hudTintColor ); CG_DrawPic( focusItem->window.rect.x, focusItem->window.rect.y, focusItem->window.rect.w, focusItem->window.rect.h, focusItem->window.background ); } focusItem = Menu_FindItemByName(menuHUD, "frame"); if (focusItem) { trap_R_SetColor( hudTintColor ); CG_DrawPic( focusItem->window.rect.x, focusItem->window.rect.y, focusItem->window.rect.w, focusItem->window.rect.h, focusItem->window.background ); } CG_DrawForcePower(menuHUD); // Draw ammo tics or saber style if ( cent->currentState.weapon == WP_SABER ) { CG_DrawSaberStyle(cent,menuHUD); } else { CG_DrawAmmo(cent,menuHUD); } */ //[/LOLHUD] } else { //CG_Error("CG_ChatBox_ArrayInsert: unable to locate HUD menu file "); } } #define MAX_SHOWPOWERS NUM_FORCE_POWERS qboolean ForcePower_Valid(int i) { //[SaberSys] //Added Saber Throw to hud selection menu. if (i == FP_LEVITATION || i == FP_SABER_OFFENSE || i == FP_SABER_DEFENSE) // i == FP_SABER_DEFENSE || // i == FP_SABERTHROW) //[/SaberSys] { return qfalse; } if (cg.snap->ps.fd.forcePowersKnown & (1 << i)) { return qtrue; } return qfalse; } /* =================== CG_DrawForceSelect =================== */ void CG_DrawForceSelect( void ) { int i; int count; int smallIconSize,bigIconSize; int holdX,x,y,x2,y2,pad,length; int sideLeftIconCnt,sideRightIconCnt; int sideMax,holdCount,iconCnt; int yOffset = 0; x2 = 0; y2 = 0; // don't display if dead if ( cg.snap->ps.stats[STAT_HEALTH] <= 0 ) { return; } if ((cg.forceSelectTime+WEAPON_SELECT_TIME)<cg.time) // Time is up for the HUD to display { cg.forceSelect = cg.snap->ps.fd.forcePowerSelected; return; } if (!cg.snap->ps.fd.forcePowersKnown) { return; } // count the number of powers owned count = 0; for (i=0;i < NUM_FORCE_POWERS;++i) { if (ForcePower_Valid(i)) { count++; } } if (count == 0) // If no force powers, don't display { return; } sideMax = 3; // Max number of icons on the side // Calculate how many icons will appear to either side of the center one holdCount = count - 1; // -1 for the center icon if (holdCount == 0) // No icons to either side { sideLeftIconCnt = 0; sideRightIconCnt = 0; } else if (count > (2*sideMax)) // Go to the max on each side { sideLeftIconCnt = sideMax; sideRightIconCnt = sideMax; } else // Less than max, so do the calc { sideLeftIconCnt = holdCount/2; sideRightIconCnt = holdCount - sideLeftIconCnt; } smallIconSize = 30; bigIconSize = 60; pad = 12; x = 320; y = 425; // Background length = (sideLeftIconCnt * smallIconSize) + (sideLeftIconCnt*pad) + bigIconSize + (sideRightIconCnt * smallIconSize) + (sideRightIconCnt*pad) + 12; i = BG_ProperForceIndex(cg.forceSelect) - 1; if (i < 0) { i = MAX_SHOWPOWERS; } trap_R_SetColor(NULL); // Work backwards from current icon holdX = x - ((bigIconSize/2) + pad + smallIconSize); for (iconCnt=1;iconCnt<(sideLeftIconCnt+1);i--) { if (i < 0) { i = MAX_SHOWPOWERS; } if (!ForcePower_Valid(forcePowerSorted[i])) // Does he have this power? { continue; } ++iconCnt; // Good icon if (cgs.media.forcePowerIcons[forcePowerSorted[i]]) { CG_DrawPic( holdX, y + yOffset, smallIconSize, smallIconSize, cgs.media.forcePowerIcons[forcePowerSorted[i]] ); holdX -= (smallIconSize+pad); } } if (ForcePower_Valid(cg.forceSelect)) { // Current Center Icon if (cgs.media.forcePowerIcons[cg.forceSelect]) { CG_DrawPic( x-(bigIconSize/2), (y-((bigIconSize-smallIconSize)/2)) + yOffset, bigIconSize, bigIconSize, cgs.media.forcePowerIcons[cg.forceSelect] ); //only cache the icon for display } } i = BG_ProperForceIndex(cg.forceSelect) + 1; if (i>MAX_SHOWPOWERS) { i = 0; } // Work forwards from current icon holdX = x + (bigIconSize/2) + pad; for (iconCnt=1;iconCnt<(sideRightIconCnt+1);i++) { if (i>MAX_SHOWPOWERS) { i = 0; } if (!ForcePower_Valid(forcePowerSorted[i])) // Does he have this power? { continue; } ++iconCnt; // Good icon if (cgs.media.forcePowerIcons[forcePowerSorted[i]]) { CG_DrawPic( holdX, y + yOffset, smallIconSize, smallIconSize, cgs.media.forcePowerIcons[forcePowerSorted[i]] ); //only cache the icon for display holdX += (smallIconSize+pad); } } if ( showPowersName[cg.forceSelect] ) { UI_DrawProportionalString(320, y + 30 + yOffset, CG_GetStringEdString("SP_INGAME", showPowersName[cg.forceSelect]), UI_CENTER | UI_SMALLFONT, colorTable[CT_ICON_BLUE]); } } /* =================== CG_DrawInventorySelect =================== */ void CG_DrawInvenSelect( void ) { int i; int sideMax,holdCount,iconCnt; int smallIconSize,bigIconSize; int sideLeftIconCnt,sideRightIconCnt; int count; int holdX,x,y,y2,pad; int height; float addX; // don't display if dead if ( cg.snap->ps.stats[STAT_HEALTH] <= 0 ) { return; } if ((cg.invenSelectTime+WEAPON_SELECT_TIME)<cg.time) // Time is up for the HUD to display { return; } if (!cg.snap->ps.stats[STAT_HOLDABLE_ITEM] || !cg.snap->ps.stats[STAT_HOLDABLE_ITEMS]) { return; } if (cg.itemSelect == -1) { cg.itemSelect = bg_itemlist[cg.snap->ps.stats[STAT_HOLDABLE_ITEM]].giTag; } //const int bits = cg.snap->ps.stats[ STAT_ITEMS ]; // count the number of items owned count = 0; for ( i = 0 ; i < HI_NUM_HOLDABLE ; i++ ) { if ((cg.snap->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << i)) ) { count++; } } if (!count) { y2 = 0; //err? UI_DrawProportionalString(320, y2 + 22, "EMPTY INVENTORY", UI_CENTER | UI_SMALLFONT, colorTable[CT_ICON_BLUE]); return; } sideMax = 3; // Max number of icons on the side // Calculate how many icons will appear to either side of the center one holdCount = count - 1; // -1 for the center icon if (holdCount == 0) // No icons to either side { sideLeftIconCnt = 0; sideRightIconCnt = 0; } else if (count > (2*sideMax)) // Go to the max on each side { sideLeftIconCnt = sideMax; sideRightIconCnt = sideMax; } else // Less than max, so do the calc { sideLeftIconCnt = holdCount/2; sideRightIconCnt = holdCount - sideLeftIconCnt; } i = cg.itemSelect - 1; if (i<0) { i = HI_NUM_HOLDABLE-1; } smallIconSize = 40; bigIconSize = 80; pad = 16; x = 320; y = 410; // Left side ICONS // Work backwards from current icon holdX = x - ((bigIconSize/2) + pad + smallIconSize); height = smallIconSize * cg.iconHUDPercent; addX = (float) smallIconSize * .75; for (iconCnt=0;iconCnt<sideLeftIconCnt;i--) { if (i<0) { i = HI_NUM_HOLDABLE-1; } if ( !(cg.snap->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << i)) || i == cg.itemSelect ) { continue; } ++iconCnt; // Good icon if (!BG_IsItemSelectable(&cg.predictedPlayerState, i)) { continue; } if (cgs.media.invenIcons[i]) { trap_R_SetColor(NULL); CG_DrawPic( holdX, y+10, smallIconSize, smallIconSize, cgs.media.invenIcons[i] ); trap_R_SetColor(colorTable[CT_ICON_BLUE]); holdX -= (smallIconSize+pad); } } // Current Center Icon height = bigIconSize * cg.iconHUDPercent; if (cgs.media.invenIcons[cg.itemSelect] && BG_IsItemSelectable(&cg.predictedPlayerState, cg.itemSelect)) { int itemNdex; trap_R_SetColor(NULL); CG_DrawPic( x-(bigIconSize/2), (y-((bigIconSize-smallIconSize)/2))+10, bigIconSize, bigIconSize, cgs.media.invenIcons[cg.itemSelect] ); addX = (float) bigIconSize * .75; trap_R_SetColor(colorTable[CT_ICON_BLUE]); itemNdex = BG_GetItemIndexByTag(cg.itemSelect, IT_HOLDABLE); if (bg_itemlist[itemNdex].classname) { vec4_t textColor = { .312f, .75f, .621f, 1.0f }; char text[1024]; char upperKey[1024]; strcpy(upperKey, bg_itemlist[itemNdex].classname); //[Flamethrower] if ( trap_SP_GetStringTextString( va("SP_INGAME_%s",Q_strupr(upperKey)), text, sizeof( text )) || trap_SP_GetStringTextString( va("OJP_MENUS_%s",Q_strupr(upperKey)), text, sizeof( text ))) //if ( trap_SP_GetStringTextString( va("SP_INGAME_%s",Q_strupr(upperKey)), text, sizeof( text ))) //[/Flamethrower] { UI_DrawProportionalString(320, y+45, text, UI_CENTER | UI_SMALLFONT, textColor); } else { UI_DrawProportionalString(320, y+45, bg_itemlist[itemNdex].classname, UI_CENTER | UI_SMALLFONT, textColor); } } } i = cg.itemSelect + 1; if (i> HI_NUM_HOLDABLE-1) { i = 0; } // Right side ICONS // Work forwards from current icon holdX = x + (bigIconSize/2) + pad; height = smallIconSize * cg.iconHUDPercent; addX = (float) smallIconSize * .75; for (iconCnt=0;iconCnt<sideRightIconCnt;i++) { if (i> HI_NUM_HOLDABLE-1) { i = 0; } if ( !(cg.snap->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << i)) || i == cg.itemSelect ) { continue; } ++iconCnt; // Good icon if (!BG_IsItemSelectable(&cg.predictedPlayerState, i)) { continue; } if (cgs.media.invenIcons[i]) { trap_R_SetColor(NULL); CG_DrawPic( holdX, y+10, smallIconSize, smallIconSize, cgs.media.invenIcons[i] ); trap_R_SetColor(colorTable[CT_ICON_BLUE]); holdX += (smallIconSize+pad); } } } int cg_targVeh = ENTITYNUM_NONE; int cg_targVehLastTime = 0; qboolean CG_CheckTargetVehicle( centity_t **pTargetVeh, float *alpha ) { int targetNum = ENTITYNUM_NONE; centity_t *targetVeh = NULL; if ( !pTargetVeh || !alpha ) {//hey, where are my pointers? return qfalse; } *alpha = 1.0f; //FIXME: need to clear all of these when you die? if ( cg.predictedPlayerState.rocketLockIndex < ENTITYNUM_WORLD ) { targetNum = cg.predictedPlayerState.rocketLockIndex; } else if ( cg.crosshairVehNum < ENTITYNUM_WORLD && cg.time - cg.crosshairVehTime < 3000 ) {//crosshair was on a vehicle in the last 3 seconds targetNum = cg.crosshairVehNum; } else if ( cg.crosshairClientNum < ENTITYNUM_WORLD ) { targetNum = cg.crosshairClientNum; } if ( targetNum < MAX_CLIENTS ) {//real client if ( cg_entities[targetNum].currentState.m_iVehicleNum >= MAX_CLIENTS ) {//in a vehicle targetNum = cg_entities[targetNum].currentState.m_iVehicleNum; } } if ( targetNum < ENTITYNUM_WORLD && targetNum >= MAX_CLIENTS ) { centity_t *targetVeh = &cg_entities[targetNum]; if ( targetVeh->currentState.NPC_class == CLASS_VEHICLE && targetVeh->m_pVehicle && targetVeh->m_pVehicle->m_pVehicleInfo && targetVeh->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER ) {//it's a vehicle cg_targVeh = targetNum; cg_targVehLastTime = cg.time; *alpha = 1.0f; } else { targetVeh = NULL; } } if ( !targetVeh ) { if ( cg_targVehLastTime && cg.time - cg_targVehLastTime < 3000 ) { targetVeh = &cg_entities[cg_targVeh];; if ( cg.time-cg_targVehLastTime < 1000 ) {//stay at full alpha for 1 sec after lose them from crosshair *alpha = 1.0f; } else {//fade out over 2 secs *alpha = 1.0f-((cg.time-cg_targVehLastTime-1000)/2000.0f); } } } if ( targetVeh ) { *pTargetVeh = targetVeh; return qtrue; } return qfalse; } #define MAX_VHUD_SHIELD_TICS 12 #define MAX_VHUD_SPEED_TICS 5 #define MAX_VHUD_ARMOR_TICS 5 #define MAX_VHUD_AMMO_TICS 5 float CG_DrawVehicleShields( const menuDef_t *menuHUD, const centity_t *veh ) { int i; char itemName[64]; float inc, currValue,maxShields; vec4_t calcColor; itemDef_t *item; float percShields; item = Menu_FindItemByName((menuDef_t *) menuHUD, "armorbackground"); if (item) { trap_R_SetColor( item->window.foreColor ); CG_DrawPic( item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->window.background ); } maxShields = veh->m_pVehicle->m_pVehicleInfo->shields; currValue = cg.predictedVehicleState.stats[STAT_ARMOR]; percShields = (float)currValue/(float)maxShields; // Print all the tics of the shield graphic // Look at the amount of health left and show only as much of the graphic as there is health. // Use alpha to fade out partial section of health inc = (float) maxShields / MAX_VHUD_ARMOR_TICS; for (i=1;i<=MAX_VHUD_ARMOR_TICS;i++) { sprintf( itemName, "armor_tic%d", i ); item = Menu_FindItemByName((menuDef_t *) menuHUD, itemName); if (!item) { continue; } memcpy(calcColor, item->window.foreColor, sizeof(vec4_t)); if (currValue <= 0) // don't show tic { break; } else if (currValue < inc) // partial tic (alpha it out) { float percent = currValue / inc; calcColor[3] *= percent; // Fade it out } trap_R_SetColor( calcColor); CG_DrawPic( item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->window.background ); currValue -= inc; } return percShields; } int cg_vehicleAmmoWarning = 0; int cg_vehicleAmmoWarningTime = 0; void CG_DrawVehicleAmmo( const menuDef_t *menuHUD, const centity_t *veh ) { int i; char itemName[64]; float inc, currValue,maxAmmo; vec4_t calcColor; itemDef_t *item; item = Menu_FindItemByName((menuDef_t *) menuHUD, "ammobackground"); if (item) { trap_R_SetColor( item->window.foreColor ); CG_DrawPic( item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->window.background ); } maxAmmo = veh->m_pVehicle->m_pVehicleInfo->weapon[0].ammoMax; currValue = cg.predictedVehicleState.ammo[0]; inc = (float) maxAmmo / MAX_VHUD_AMMO_TICS; for (i=1;i<=MAX_VHUD_AMMO_TICS;i++) { sprintf( itemName, "ammo_tic%d", i ); item = Menu_FindItemByName((menuDef_t *)menuHUD, itemName); if (!item) { continue; } if ( cg_vehicleAmmoWarningTime > cg.time && cg_vehicleAmmoWarning == 0 ) { memcpy(calcColor, g_color_table[ColorIndex(COLOR_RED)], sizeof(vec4_t)); calcColor[3] = sin(cg.time*0.005)*0.5f+0.5f; } else { memcpy(calcColor, item->window.foreColor, sizeof(vec4_t)); if (currValue <= 0) // don't show tic { break; } else if (currValue < inc) // partial tic (alpha it out) { float percent = currValue / inc; calcColor[3] *= percent; // Fade it out } } trap_R_SetColor( calcColor); CG_DrawPic( item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->window.background ); currValue -= inc; } } void CG_DrawVehicleAmmoUpper( const menuDef_t *menuHUD, const centity_t *veh ) { int i; char itemName[64]; float inc, currValue,maxAmmo; vec4_t calcColor; itemDef_t *item; item = Menu_FindItemByName((menuDef_t *)menuHUD, "ammoupperbackground"); if (item) { trap_R_SetColor( item->window.foreColor ); CG_DrawPic( item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->window.background ); } maxAmmo = veh->m_pVehicle->m_pVehicleInfo->weapon[0].ammoMax; currValue = cg.predictedVehicleState.ammo[0]; inc = (float) maxAmmo / MAX_VHUD_AMMO_TICS; for (i=1;i<MAX_VHUD_AMMO_TICS;i++) { sprintf( itemName, "ammoupper_tic%d", i ); item = Menu_FindItemByName((menuDef_t *)menuHUD, itemName); if (!item) { continue; } if ( cg_vehicleAmmoWarningTime > cg.time && cg_vehicleAmmoWarning == 0 ) { memcpy(calcColor, g_color_table[ColorIndex(COLOR_RED)], sizeof(vec4_t)); calcColor[3] = sin(cg.time*0.005)*0.5f+0.5f; } else { memcpy(calcColor, item->window.foreColor, sizeof(vec4_t)); if (currValue <= 0) // don't show tic { break; } else if (currValue < inc) // partial tic (alpha it out) { float percent = currValue / inc; calcColor[3] *= percent; // Fade it out } } trap_R_SetColor( calcColor); CG_DrawPic( item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->window.background ); currValue -= inc; } } void CG_DrawVehicleAmmoLower( const menuDef_t *menuHUD, const centity_t *veh ) { int i; char itemName[64]; float inc, currValue,maxAmmo; vec4_t calcColor; itemDef_t *item; item = Menu_FindItemByName((menuDef_t *)menuHUD, "ammolowerbackground"); if (item) { trap_R_SetColor( item->window.foreColor ); CG_DrawPic( item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->window.background ); } maxAmmo = veh->m_pVehicle->m_pVehicleInfo->weapon[1].ammoMax; currValue = cg.predictedVehicleState.ammo[1]; inc = (float) maxAmmo / MAX_VHUD_AMMO_TICS; for (i=1;i<MAX_VHUD_AMMO_TICS;i++) { sprintf( itemName, "ammolower_tic%d", i ); item = Menu_FindItemByName((menuDef_t *)menuHUD, itemName); if (!item) { continue; } if ( cg_vehicleAmmoWarningTime > cg.time && cg_vehicleAmmoWarning == 1 ) { memcpy(calcColor, g_color_table[ColorIndex(COLOR_RED)], sizeof(vec4_t)); calcColor[3] = sin(cg.time*0.005)*0.5f+0.5f; } else { memcpy(calcColor, item->window.foreColor, sizeof(vec4_t)); if (currValue <= 0) // don't show tic { break; } else if (currValue < inc) // partial tic (alpha it out) { float percent = currValue / inc; calcColor[3] *= percent; // Fade it out } } trap_R_SetColor( calcColor); CG_DrawPic( item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->window.background ); currValue -= inc; } } // The HUD.menu file has the graphic print with a negative height, so it will print from the bottom up. void CG_DrawVehicleTurboRecharge( const menuDef_t *menuHUD, const centity_t *veh ) { itemDef_t *item; int height; item = Menu_FindItemByName( (menuDef_t *) menuHUD, "turborecharge"); if (item) { float percent=0.0f; int diff = ( cg.time - veh->m_pVehicle->m_iTurboTime ); height = item->window.rect.h; if (diff > veh->m_pVehicle->m_pVehicleInfo->turboRecharge) { percent = 1.0f; trap_R_SetColor( colorTable[CT_GREEN] ); } else { percent = (float) diff / veh->m_pVehicle->m_pVehicleInfo->turboRecharge; if (percent < 0.0f) { percent = 0.0f; } trap_R_SetColor( colorTable[CT_RED] ); } height *= percent; CG_DrawPic( item->window.rect.x, item->window.rect.y, item->window.rect.w, height, cgs.media.whiteShader); } } qboolean cg_drawLink = qfalse; void CG_DrawVehicleWeaponsLinked( const menuDef_t *menuHUD, const centity_t *veh ) { qboolean drawLink = qfalse; if ( veh->m_pVehicle && veh->m_pVehicle->m_pVehicleInfo && (veh->m_pVehicle->m_pVehicleInfo->weapon[0].linkable == 2|| veh->m_pVehicle->m_pVehicleInfo->weapon[1].linkable == 2) ) {//weapon is always linked drawLink = qtrue; } else { //MP way: //must get sent over network if ( cg.predictedVehicleState.vehWeaponsLinked ) { drawLink = qtrue; } } if ( cg_drawLink != drawLink ) {//state changed, play sound cg_drawLink = drawLink; trap_S_StartSound (NULL, cg.predictedPlayerState.clientNum, CHAN_LOCAL, trap_S_RegisterSound( "sound/vehicles/common/linkweaps.wav" ) ); } if ( drawLink ) { itemDef_t *item; item = Menu_FindItemByName( (menuDef_t *) menuHUD, "weaponslinked"); if (item) { trap_R_SetColor( colorTable[CT_CYAN] ); CG_DrawPic( item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, cgs.media.whiteShader); } } } void CG_DrawVehicleSpeed( const menuDef_t *menuHUD, const centity_t *veh ) { int i; char itemName[64]; float inc, currValue,maxSpeed; vec4_t calcColor; itemDef_t *item; item = Menu_FindItemByName((menuDef_t *) menuHUD, "speedbackground"); if (item) { trap_R_SetColor( item->window.foreColor ); CG_DrawPic( item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->window.background ); } maxSpeed = veh->m_pVehicle->m_pVehicleInfo->speedMax; currValue = cg.predictedVehicleState.speed; // Print all the tics of the shield graphic // Look at the amount of health left and show only as much of the graphic as there is health. // Use alpha to fade out partial section of health inc = (float) maxSpeed / MAX_VHUD_SPEED_TICS; for (i=1;i<=MAX_VHUD_SPEED_TICS;i++) { sprintf( itemName, "speed_tic%d", i ); item = Menu_FindItemByName((menuDef_t *)menuHUD, itemName); if (!item) { continue; } if ( cg.time > veh->m_pVehicle->m_iTurboTime ) { memcpy(calcColor, item->window.foreColor, sizeof(vec4_t)); } else // In turbo mode { if (cg.VHUDFlashTime < cg.time) { cg.VHUDFlashTime = cg.time + 200; if (cg.VHUDTurboFlag) { cg.VHUDTurboFlag = qfalse; } else { cg.VHUDTurboFlag = qtrue; } } if (cg.VHUDTurboFlag) { memcpy(calcColor, colorTable[CT_LTRED1], sizeof(vec4_t)); } else { memcpy(calcColor, item->window.foreColor, sizeof(vec4_t)); } } if (currValue <= 0) // don't show tic { break; } else if (currValue < inc) // partial tic (alpha it out) { float percent = currValue / inc; calcColor[3] *= percent; // Fade it out } trap_R_SetColor( calcColor); CG_DrawPic( item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->window.background ); currValue -= inc; } } void CG_DrawVehicleArmor( const menuDef_t *menuHUD, const centity_t *veh ) { int i; vec4_t calcColor; char itemName[64]; float inc, currValue,maxArmor; itemDef_t *item; maxArmor = veh->m_pVehicle->m_pVehicleInfo->armor; currValue = cg.predictedVehicleState.stats[STAT_HEALTH]; item = Menu_FindItemByName( (menuDef_t *) menuHUD, "shieldbackground"); if (item) { trap_R_SetColor( item->window.foreColor ); CG_DrawPic( item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->window.background ); } // Print all the tics of the shield graphic // Look at the amount of health left and show only as much of the graphic as there is health. // Use alpha to fade out partial section of health inc = (float) maxArmor / MAX_VHUD_SHIELD_TICS; for (i=1;i <= MAX_VHUD_SHIELD_TICS;i++) { sprintf( itemName, "shield_tic%d", i ); item = Menu_FindItemByName((menuDef_t *) menuHUD, itemName); if (!item) { continue; } memcpy(calcColor, item->window.foreColor, sizeof(vec4_t)); if (currValue <= 0) // don't show tic { break; } else if (currValue < inc) // partial tic (alpha it out) { float percent = currValue / inc; calcColor[3] *= percent; // Fade it out } trap_R_SetColor( calcColor); CG_DrawPic( item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->window.background ); currValue -= inc; } } enum { VEH_DAMAGE_FRONT=0, VEH_DAMAGE_BACK, VEH_DAMAGE_LEFT, VEH_DAMAGE_RIGHT, }; typedef struct { char *itemName; short heavyDamage; short lightDamage; } veh_damage_t; veh_damage_t vehDamageData[4] = { "vehicle_front",SHIPSURF_DAMAGE_FRONT_HEAVY,SHIPSURF_DAMAGE_FRONT_LIGHT, "vehicle_back",SHIPSURF_DAMAGE_BACK_HEAVY,SHIPSURF_DAMAGE_BACK_LIGHT, "vehicle_left",SHIPSURF_DAMAGE_LEFT_HEAVY,SHIPSURF_DAMAGE_LEFT_LIGHT, "vehicle_right",SHIPSURF_DAMAGE_RIGHT_HEAVY,SHIPSURF_DAMAGE_RIGHT_LIGHT, }; // Draw health graphic for given part of vehicle void CG_DrawVehicleDamage(const centity_t *veh,int brokenLimbs,const menuDef_t *menuHUD,float alpha,int index) { itemDef_t *item; int colorI; vec4_t color; int graphicHandle=0; item = Menu_FindItemByName((menuDef_t *)menuHUD, vehDamageData[index].itemName); if (item) { if (brokenLimbs & (1<<vehDamageData[index].heavyDamage)) { colorI = CT_RED; if (brokenLimbs & (1<<vehDamageData[index].lightDamage)) { colorI = CT_DKGREY; } } else if (brokenLimbs & (1<<vehDamageData[index].lightDamage)) { colorI = CT_YELLOW; } else { colorI = CT_GREEN; } VectorCopy4 ( colorTable[colorI], color ); color[3] = alpha; trap_R_SetColor( color ); switch ( index ) { case VEH_DAMAGE_FRONT : graphicHandle = veh->m_pVehicle->m_pVehicleInfo->iconFrontHandle; break; case VEH_DAMAGE_BACK : graphicHandle = veh->m_pVehicle->m_pVehicleInfo->iconBackHandle; break; case VEH_DAMAGE_LEFT : graphicHandle = veh->m_pVehicle->m_pVehicleInfo->iconLeftHandle; break; case VEH_DAMAGE_RIGHT : graphicHandle = veh->m_pVehicle->m_pVehicleInfo->iconRightHandle; break; } if (graphicHandle) { CG_DrawPic( item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, graphicHandle ); } } } // Used on both damage indicators : player vehicle and the vehicle the player is locked on void CG_DrawVehicleDamageHUD(const centity_t *veh,int brokenLimbs,float percShields,char *menuName, float alpha) { menuDef_t *menuHUD; itemDef_t *item; vec4_t color; menuHUD = Menus_FindByName(menuName); if ( !menuHUD ) { return; } item = Menu_FindItemByName(menuHUD, "background"); if (item) { if (veh->m_pVehicle->m_pVehicleInfo->dmgIndicBackgroundHandle) { if ( veh->damageTime > cg.time ) {//ship shields currently taking damage //NOTE: cent->damageAngle can be accessed to get the direction from the ship origin to the impact point (in 3-D space) float perc = 1.0f - ((veh->damageTime - cg.time) / 2000.0f); if ( perc < 0.0f ) { perc = 0.0f; } else if ( perc > 1.0f ) { perc = 1.0f; } color[0] = item->window.foreColor[0];//flash red color[1] = item->window.foreColor[1]*perc;//fade other colors back in over time color[2] = item->window.foreColor[2]*perc;//fade other colors back in over time color[3] = item->window.foreColor[3];//always normal alpha trap_R_SetColor( color ); } else { trap_R_SetColor( item->window.foreColor ); } CG_DrawPic( item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, veh->m_pVehicle->m_pVehicleInfo->dmgIndicBackgroundHandle ); } } item = Menu_FindItemByName(menuHUD, "outer_frame"); if (item) { if (veh->m_pVehicle->m_pVehicleInfo->dmgIndicFrameHandle) { trap_R_SetColor( item->window.foreColor ); CG_DrawPic( item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, veh->m_pVehicle->m_pVehicleInfo->dmgIndicFrameHandle ); } } item = Menu_FindItemByName(menuHUD, "shields"); if (item) { if (veh->m_pVehicle->m_pVehicleInfo->dmgIndicShieldHandle) { VectorCopy4 ( colorTable[CT_HUD_GREEN], color ); color[3] = percShields; trap_R_SetColor( color ); CG_DrawPic( item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, veh->m_pVehicle->m_pVehicleInfo->dmgIndicShieldHandle ); } } //TODO: if we check nextState.brokenLimbs & prevState.brokenLimbs, we can tell when a damage flag has been added and flash that part of the ship //FIXME: when ship explodes, either stop drawing ship or draw all parts black CG_DrawVehicleDamage(veh,brokenLimbs,menuHUD,alpha,VEH_DAMAGE_FRONT); CG_DrawVehicleDamage(veh,brokenLimbs,menuHUD,alpha,VEH_DAMAGE_BACK); CG_DrawVehicleDamage(veh,brokenLimbs,menuHUD,alpha,VEH_DAMAGE_LEFT); CG_DrawVehicleDamage(veh,brokenLimbs,menuHUD,alpha,VEH_DAMAGE_RIGHT); } qboolean CG_DrawVehicleHud( const centity_t *cent ) { itemDef_t *item; menuDef_t *menuHUD; playerState_t *ps; centity_t *veh; float shieldPerc,alpha; menuHUD = Menus_FindByName("swoopvehiclehud"); if (!menuHUD) { return qtrue; // Draw player HUD } ps = &cg.predictedPlayerState; if (!ps || !(ps->m_iVehicleNum)) { return qtrue; // Draw player HUD } veh = &cg_entities[ps->m_iVehicleNum]; if ( !veh ) { return qtrue; // Draw player HUD } CG_DrawVehicleTurboRecharge( menuHUD, veh ); CG_DrawVehicleWeaponsLinked( menuHUD, veh ); item = Menu_FindItemByName(menuHUD, "leftframe"); // Draw frame if (item) { trap_R_SetColor( item->window.foreColor ); CG_DrawPic( item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->window.background ); } item = Menu_FindItemByName(menuHUD, "rightframe"); if (item) { trap_R_SetColor( item->window.foreColor ); CG_DrawPic( item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->window.background ); } CG_DrawVehicleArmor( menuHUD, veh ); // Get animal hud for speed // if (veh->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL) // { // menuHUD = Menus_FindByName("tauntaunhud"); // } CG_DrawVehicleSpeed( menuHUD, veh ); // Revert to swoophud // if (veh->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL) // { // menuHUD = Menus_FindByName("swoopvehiclehud"); // } // if (veh->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL) // { shieldPerc = CG_DrawVehicleShields( menuHUD, veh ); // } if (veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID && !veh->m_pVehicle->m_pVehicleInfo->weapon[1].ID) { CG_DrawVehicleAmmo( menuHUD, veh ); } else if (veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID && veh->m_pVehicle->m_pVehicleInfo->weapon[1].ID) { CG_DrawVehicleAmmoUpper( menuHUD, veh ); CG_DrawVehicleAmmoLower( menuHUD, veh ); } // If he's hidden, he must be in a vehicle if (veh->m_pVehicle->m_pVehicleInfo->hideRider) { CG_DrawVehicleDamageHUD(veh,cg.predictedVehicleState.brokenLimbs,shieldPerc,"vehicledamagehud",1.0f); // Has he targeted an enemy? if (CG_CheckTargetVehicle( &veh, &alpha )) { CG_DrawVehicleDamageHUD(veh,veh->currentState.brokenLimbs,((float)veh->currentState.activeForcePass/10.0f),"enemyvehicledamagehud",alpha); } return qfalse; // Don't draw player HUD } return qtrue; // Draw player HUD } /* ================ CG_DrawStats ================ */ static void CG_DrawStats( void ) { centity_t *cent; playerState_t *ps; qboolean drawHUD = qtrue; cent = &cg_entities[cg.snap->ps.clientNum]; if ( cent ) { ps = &cg.predictedPlayerState; if ( (ps->m_iVehicleNum ) ) // In a vehicle??? { drawHUD = CG_DrawVehicleHud( cent ); } } if (drawHUD) { CG_DrawHUD(cent); } } /* =================== CG_DrawPickupItem =================== */ static void CG_DrawPickupItem( void ) { int value; float *fadeColor; value = cg.itemPickup; if ( value && cg_items[ value ].icon != -1 ) { fadeColor = CG_FadeColor( cg.itemPickupTime, 3000 ); if ( fadeColor ) { CG_RegisterItemVisuals( value ); trap_R_SetColor( fadeColor ); CG_DrawPic( 573, 320, ICON_SIZE, ICON_SIZE, cg_items[ value ].icon ); trap_R_SetColor( NULL ); } } } /* ================ CG_DrawTeamBackground ================ */ void CG_DrawTeamBackground( int x, int y, int w, int h, float alpha, int team ) { vec4_t hcolor; hcolor[3] = alpha; if ( team == TEAM_RED ) { hcolor[0] = 1; hcolor[1] = .2f; hcolor[2] = .2f; } else if ( team == TEAM_BLUE ) { hcolor[0] = .2f; hcolor[1] = .2f; hcolor[2] = 1; } else { return; } // trap_R_SetColor( hcolor ); CG_FillRect ( x, y, w, h, hcolor ); // CG_DrawPic( x, y, w, h, cgs.media.teamStatusBar ); trap_R_SetColor( NULL ); } /* =========================================================================================== UPPER RIGHT CORNER =========================================================================================== */ /* ================ CG_DrawMiniScoreboard ================ */ static float CG_DrawMiniScoreboard ( float y ) { char temp[MAX_QPATH]; int xOffset = 0; if ( !cg_drawScores.integer ) { return y; } if (cgs.gametype == GT_SIEGE) { //don't bother with this in siege return y; } if ( cgs.gametype >= GT_TEAM ) { strcpy ( temp, va("%s: ", CG_GetStringEdString("MP_INGAME", "RED"))); Q_strcat ( temp, MAX_QPATH, cgs.scores1==SCORE_NOT_PRESENT?"-":(va("%i",cgs.scores1)) ); Q_strcat ( temp, MAX_QPATH, va(" %s: ", CG_GetStringEdString("MP_INGAME", "BLUE")) ); Q_strcat ( temp, MAX_QPATH, cgs.scores2==SCORE_NOT_PRESENT?"-":(va("%i",cgs.scores2)) ); CG_Text_Paint( 630 - CG_Text_Width ( temp, 0.7f, FONT_MEDIUM ) + xOffset, y, 0.7f, colorWhite, temp, 0, 0, ITEM_TEXTSTYLE_SHADOWEDMORE, FONT_MEDIUM ); y += 15; } return y; } /* ================ CG_DrawEnemyInfo ================ */ static float CG_DrawEnemyInfo ( float y ) { float size; int clientNum; const char *title; clientInfo_t *ci; int xOffset = 0; if (!cg.snap) { return y; } if ( !cg_drawEnemyInfo.integer ) { return y; } if ( cg.predictedPlayerState.stats[STAT_HEALTH] <= 0 ) { return y; } if (cgs.gametype == GT_POWERDUEL) { //just get out of here then return y; } if ( cgs.gametype == GT_JEDIMASTER ) { //title = "Jedi Master"; title = CG_GetStringEdString("MP_INGAME", "MASTERY7"); clientNum = cgs.jediMaster; if ( clientNum < 0 ) { title = CG_GetStringEdString("MP_INGAME", "GET_SABER"); size = ICON_SIZE * 1.25; y += 5; CG_DrawPic( 640 - size - 12 + xOffset, y, size, size, cgs.media.weaponIcons[WP_SABER] ); y += size; CG_Text_Paint( 630 - CG_Text_Width ( title, 0.7f, FONT_MEDIUM ) + xOffset, y, 0.7f, colorWhite, title, 0, 0, 0, FONT_MEDIUM ); return y + BIGCHAR_HEIGHT + 2; } } else if ( cg.snap->ps.duelInProgress ) { title = CG_GetStringEdString("MP_INGAME", "DUELING"); clientNum = cg.snap->ps.duelIndex; } else if ( cgs.gametype == GT_DUEL && cgs.clientinfo[cg.snap->ps.clientNum].team != TEAM_SPECTATOR) { title = CG_GetStringEdString("MP_INGAME", "DUELING"); if (cg.snap->ps.clientNum == cgs.duelist1) { clientNum = cgs.duelist2; //if power duel, should actually draw both duelists 2 and 3 I guess } else if (cg.snap->ps.clientNum == cgs.duelist2) { clientNum = cgs.duelist1; } else if (cg.snap->ps.clientNum == cgs.duelist3) { clientNum = cgs.duelist1; } else { return y; } } else { //As of current, we don't want to draw the attacker. Instead, draw whoever is in first place. if (cgs.duelWinner < 0 || cgs.duelWinner >= MAX_CLIENTS) { return y; } title = va("%s: %i",CG_GetStringEdString("MP_INGAME", "LEADER"), cgs.scores1); clientNum = cgs.duelWinner; } if ( clientNum >= MAX_CLIENTS || !(&cgs.clientinfo[ clientNum ]) ) { return y; } ci = &cgs.clientinfo[ clientNum ]; size = ICON_SIZE * 1.25; y += 5; if ( ci->modelIcon ) { CG_DrawPic( 640 - size - 5 + xOffset, y, size, size, ci->modelIcon ); } y += size; // CG_Text_Paint( 630 - CG_Text_Width ( ci->name, 0.7f, FONT_MEDIUM ) + xOffset, y, 0.7f, colorWhite, ci->name, 0, 0, 0, FONT_MEDIUM ); CG_Text_Paint( 630 - CG_Text_Width ( ci->name, 1.0f, FONT_SMALL2 ) + xOffset, y, 1.0f, colorWhite, ci->name, 0, 0, 0, FONT_SMALL2 ); y += 15; // CG_Text_Paint( 630 - CG_Text_Width ( title, 0.7f, FONT_MEDIUM ) + xOffset, y, 0.7f, colorWhite, title, 0, 0, 0, FONT_MEDIUM ); CG_Text_Paint( 630 - CG_Text_Width ( title, 1.0f, FONT_SMALL2 ) + xOffset, y, 1.0f, colorWhite, title, 0, 0, 0, FONT_SMALL2 ); if ( (cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL) && cgs.clientinfo[cg.snap->ps.clientNum].team != TEAM_SPECTATOR) {//also print their score char text[1024]; y += 15; Com_sprintf(text, sizeof(text), "%i/%i", cgs.clientinfo[clientNum].score, cgs.fraglimit ); CG_Text_Paint( 630 - CG_Text_Width ( text, 0.7f, FONT_MEDIUM ) + xOffset, y, 0.7f, colorWhite, text, 0, 0, 0, FONT_MEDIUM ); } // nmckenzie: DUEL_HEALTH - fixme - need checks and such here. And this is coded to duelist 1 right now, which is wrongly. if ( cgs.showDuelHealths >= 2) { y += 15; if ( cgs.duelist1 == clientNum ) { CG_DrawDuelistHealth ( 640 - size - 5 + xOffset, y, 64, 8, 1 ); } else if ( cgs.duelist2 == clientNum ) { CG_DrawDuelistHealth ( 640 - size - 5 + xOffset, y, 64, 8, 2 ); } } return y + BIGCHAR_HEIGHT + 2; } /* ================== CG_DrawSnapshot ================== */ static float CG_DrawSnapshot( float y ) { char *s; int w; int xOffset = 0; s = va( "time:%i snap:%i cmd:%i", cg.snap->serverTime, cg.latestSnapshotNum, cgs.serverCommandSequence ); w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH; CG_DrawBigString( 635 - w + xOffset, y + 2, s, 1.0F); return y + BIGCHAR_HEIGHT + 4; } /* ================== CG_DrawFPS ================== */ #define FPS_FRAMES 16 static float CG_DrawFPS( float y ) { char *s; int w; static unsigned short previousTimes[FPS_FRAMES]; static unsigned short index; static int previous, lastupdate; int t, i, fps, total; unsigned short frameTime; const int xOffset = 0; // don't use serverTime, because that will be drifting to // correct for internet lag changes, timescales, timedemos, etc t = trap_Milliseconds(); frameTime = t - previous; previous = t; if (t - lastupdate > 50) //don't sample faster than this { lastupdate = t; previousTimes[index % FPS_FRAMES] = frameTime; index++; } // average multiple frames together to smooth changes out a bit total = 0; for ( i = 0 ; i < FPS_FRAMES ; i++ ) { total += previousTimes[i]; } if ( !total ) { total = 1; } fps = 1000 * FPS_FRAMES / total; s = va( "%ifps", fps ); w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH; CG_DrawBigString( 635 - w + xOffset, y + 2, s, 1.0F); return y + BIGCHAR_HEIGHT + 4; } // nmckenzie: DUEL_HEALTH #define MAX_HEALTH_FOR_IFACE 100 void CG_DrawHealthBarRough (float x, float y, int width, int height, float ratio, const float *color1, const float *color2) { float midpoint, remainder; float color3[4] = {1, 0, 0, .7f}; midpoint = width * ratio - 1; remainder = width - midpoint; color3[0] = color1[0] * 0.5f; assert(!(height%4));//this won't line up otherwise. CG_DrawRect(x + 1, y + height/2-1, midpoint, 1, height/4+1, color1); // creme-y filling. CG_DrawRect(x + midpoint, y + height/2-1, remainder, 1, height/4+1, color3); // used-up-ness. CG_DrawRect(x, y, width, height, 1, color2); // hard crispy shell } void CG_DrawDuelistHealth ( float x, float y, float w, float h, int duelist ) { float duelHealthColor[4] = {1, 0, 0, 0.7f}; float healthSrc = 0.0f; float ratio; if ( duelist == 1 ) { healthSrc = cgs.duelist1health; } else if (duelist == 2 ) { healthSrc = cgs.duelist2health; } ratio = healthSrc / MAX_HEALTH_FOR_IFACE; if ( ratio > 1.0f ) { ratio = 1.0f; } if ( ratio < 0.0f ) { ratio = 0.0f; } duelHealthColor[0] = (ratio * 0.2f) + 0.5f; CG_DrawHealthBarRough (x, y, w, h, ratio, duelHealthColor, colorTable[CT_WHITE]); // new art for this? I'm not crazy about how this looks. } /* ===================== CG_DrawRadar ===================== */ float cg_radarRange = 2500.0f; #define RADAR_RADIUS 60 const int RADAR_X = (580 - RADAR_RADIUS); const int RADAR_CHAT_DURATION = 6000; static int radarLockSoundDebounceTime = 0; static int impactSoundDebounceTime = 0; const float RADAR_MISSILE_RANGE = 3000.0f; const float RADAR_ASTEROID_RANGE = 10000.0f; const float RADAR_MIN_ASTEROID_SURF_WARN_DIST = 1200.0f; float CG_DrawRadar ( float y ) { vec4_t color; vec4_t teamColor; float arrow_w; float arrow_h; clientInfo_t *cl; clientInfo_t *local; int i; float arrowBaseScale; float zScale; int xOffset = 0; if (!cg.snap) { return y; } // Make sure the radar should be showing if ( cg.snap->ps.stats[STAT_HEALTH] <= 0 ) { return y; } if ( (cg.predictedPlayerState.pm_flags & PMF_FOLLOW) || cg.predictedPlayerState.persistant[PERS_TEAM] == TEAM_SPECTATOR ) { return y; } local = &cgs.clientinfo[ cg.snap->ps.clientNum ]; if ( !local->infoValid ) { return y; } // Draw the radar background image color[0] = color[1] = color[2] = 1.0f; color[3] = 0.6f; trap_R_SetColor ( color ); CG_DrawPic( RADAR_X + xOffset, y, RADAR_RADIUS*2, RADAR_RADIUS*2, cgs.media.radarShader ); //Always green for your own team. VectorCopy ( g_color_table[ColorIndex(COLOR_GREEN)], teamColor ); teamColor[3] = 1.0f; // Draw all of the radar entities. Draw them backwards so players are drawn last for ( i = cg.radarEntityCount -1 ; i >= 0 ; i-- ) { vec3_t dirLook; vec3_t dirPlayer; float angleLook; float anglePlayer; float angle; float distance, actualDist; centity_t* cent; cent = &cg_entities[cg.radarEntities[i]]; // Get the distances first VectorSubtract ( cg.predictedPlayerState.origin, cent->lerpOrigin, dirPlayer ); dirPlayer[2] = 0; actualDist = distance = VectorNormalize ( dirPlayer ); if ( distance > cg_radarRange * 0.8f) { if ( (cent->currentState.eFlags & EF_RADAROBJECT)//still want to draw the direction || ( cent->currentState.eType==ET_NPC//FIXME: draw last, with players... && cent->currentState.NPC_class == CLASS_VEHICLE && cent->currentState.speed > 0 ) )//always draw vehicles { distance = cg_radarRange*0.8f; } else { continue; } } distance = distance / cg_radarRange; distance *= RADAR_RADIUS; AngleVectors ( cg.predictedPlayerState.viewangles, dirLook, NULL, NULL ); dirLook[2] = 0; anglePlayer = atan2(dirPlayer[0],dirPlayer[1]); VectorNormalize ( dirLook ); angleLook = atan2(dirLook[0],dirLook[1]); angle = angleLook - anglePlayer; switch ( cent->currentState.eType ) { default: { float x; float ly; qhandle_t shader; vec4_t color; x = (float)RADAR_X + (float)RADAR_RADIUS + (float)sin (angle) * distance; ly = y + (float)RADAR_RADIUS + (float)cos (angle) * distance; arrowBaseScale = 9.0f; shader = 0; zScale = 1.0f; //we want to scale the thing up/down based on the relative Z (up/down) positioning if (cent->lerpOrigin[2] > cg.predictedPlayerState.origin[2]) { //higher, scale up (between 16 and 24) float dif = (cent->lerpOrigin[2] - cg.predictedPlayerState.origin[2]); //max out to 1.5x scale at 512 units above local player's height dif /= 1024.0f; if (dif > 0.5f) { dif = 0.5f; } zScale += dif; } else if (cent->lerpOrigin[2] < cg.predictedPlayerState.origin[2]) { //lower, scale down (between 16 and 8) float dif = (cg.predictedPlayerState.origin[2] - cent->lerpOrigin[2]); //half scale at 512 units below local player's height dif /= 1024.0f; if (dif > 0.5f) { dif = 0.5f; } zScale -= dif; } arrowBaseScale *= zScale; if (cent->currentState.brokenLimbs) { //slightly misleading to use this value, but don't want to add more to entstate. //any ent with brokenLimbs non-0 and on radar is an objective ent. //brokenLimbs is literal team value. char objState[1024]; int complete; //we only want to draw it if the objective for it is not complete. //frame represents objective num. trap_Cvar_VariableStringBuffer(va("team%i_objective%i", cent->currentState.brokenLimbs, cent->currentState.frame), objState, 1024); complete = atoi(objState); if (!complete) { // generic enemy index specifies a shader to use for the radar entity. if ( cent->currentState.genericenemyindex ) { color[0] = color[1] = color[2] = color[3] = 1.0f; shader = cgs.gameIcons[cent->currentState.genericenemyindex]; } else { if (cg.snap && cent->currentState.brokenLimbs == cg.snap->ps.persistant[PERS_TEAM]) { VectorCopy ( g_color_table[ColorIndex(COLOR_RED)], color ); } else { VectorCopy ( g_color_table[ColorIndex(COLOR_GREEN)], color ); } shader = cgs.media.siegeItemShader; } } } else { color[0] = color[1] = color[2] = color[3] = 1.0f; // generic enemy index specifies a shader to use for the radar entity. if ( cent->currentState.genericenemyindex ) { shader = cgs.gameIcons[cent->currentState.genericenemyindex]; } else { shader = cgs.media.siegeItemShader; } } if ( shader ) { // Pulse the alpha if time2 is set. time2 gets set when the entity takes pain if ( (cent->currentState.time2 && cg.time - cent->currentState.time2 < 5000) || (cent->currentState.time2 == 0xFFFFFFFF) ) { if ( (cg.time / 200) & 1 ) { color[3] = 0.1f + 0.9f * (float) (cg.time % 200) / 200.0f; } else { color[3] = 1.0f - 0.9f * (float) (cg.time % 200) / 200.0f; } } trap_R_SetColor ( color ); CG_DrawPic ( x - 4 + xOffset, ly - 4, arrowBaseScale, arrowBaseScale, shader ); } } break; case ET_NPC://FIXME: draw last, with players... if ( cent->currentState.NPC_class == CLASS_VEHICLE && cent->currentState.speed > 0 ) { if ( cent->m_pVehicle && cent->m_pVehicle->m_pVehicleInfo->radarIconHandle ) { float x; float ly; x = (float)RADAR_X + (float)RADAR_RADIUS + (float)sin (angle) * distance; ly = y + (float)RADAR_RADIUS + (float)cos (angle) * distance; arrowBaseScale = 9.0f; zScale = 1.0f; //we want to scale the thing up/down based on the relative Z (up/down) positioning if (cent->lerpOrigin[2] > cg.predictedPlayerState.origin[2]) { //higher, scale up (between 16 and 24) float dif = (cent->lerpOrigin[2] - cg.predictedPlayerState.origin[2]); //max out to 1.5x scale at 512 units above local player's height dif /= 4096.0f; if (dif > 0.5f) { dif = 0.5f; } zScale += dif; } else if (cent->lerpOrigin[2] < cg.predictedPlayerState.origin[2]) { //lower, scale down (between 16 and 8) float dif = (cg.predictedPlayerState.origin[2] - cent->lerpOrigin[2]); //half scale at 512 units below local player's height dif /= 4096.0f; if (dif > 0.5f) { dif = 0.5f; } zScale -= dif; } arrowBaseScale *= zScale; if ( cent->currentState.m_iVehicleNum //vehicle has a driver && cgs.clientinfo[ cent->currentState.m_iVehicleNum-1 ].infoValid ) { if ( cgs.clientinfo[ cent->currentState.m_iVehicleNum-1 ].team == local->team ) { trap_R_SetColor ( teamColor ); } else { trap_R_SetColor ( g_color_table[ColorIndex(COLOR_RED)] ); } } else { trap_R_SetColor ( NULL ); } CG_DrawPic ( x - 4 + xOffset, ly - 4, arrowBaseScale, arrowBaseScale, cent->m_pVehicle->m_pVehicleInfo->radarIconHandle ); } } break; //maybe do something? case ET_MOVER: if ( cent->currentState.speed//the mover's size, actually && actualDist < (cent->currentState.speed+RADAR_ASTEROID_RANGE) && cg.predictedPlayerState.m_iVehicleNum ) {//a mover that's close to me and I'm in a vehicle qboolean mayImpact = qfalse; float surfaceDist = (actualDist-cent->currentState.speed); if ( surfaceDist < 0.0f ) { surfaceDist = 0.0f; } if ( surfaceDist < RADAR_MIN_ASTEROID_SURF_WARN_DIST ) {//always warn! mayImpact = qtrue; } else {//not close enough to always warn, yet, so check its direction vec3_t asteroidPos, myPos, moveDir; int predictTime, timeStep = 500; float newDist; for ( predictTime = timeStep; predictTime < 5000; predictTime+=timeStep ) { //asteroid dir, speed, size, + my dir & speed... BG_EvaluateTrajectory( &cent->currentState.pos, cg.time+predictTime, asteroidPos ); //FIXME: I don't think it's calcing "myPos" correctly AngleVectors( cg.predictedVehicleState.viewangles, moveDir, NULL, NULL ); VectorMA( cg.predictedVehicleState.origin, cg.predictedVehicleState.speed*predictTime/1000.0f, moveDir, myPos ); newDist = Distance( myPos, asteroidPos ); if ( (newDist-cent->currentState.speed) <= RADAR_MIN_ASTEROID_SURF_WARN_DIST )//200.0f ) {//heading for an impact within the next 5 seconds mayImpact = qtrue; break; } } } if ( mayImpact ) {//possible collision vec4_t asteroidColor = {0.5f,0.5f,0.5f,1.0f}; float x; float ly; float asteroidScale = (cent->currentState.speed/2000.0f);//average asteroid radius? if ( actualDist > RADAR_ASTEROID_RANGE ) { actualDist = RADAR_ASTEROID_RANGE; } distance = (actualDist/RADAR_ASTEROID_RANGE)*RADAR_RADIUS; x = (float)RADAR_X + (float)RADAR_RADIUS + (float)sin (angle) * distance; ly = y + (float)RADAR_RADIUS + (float)cos (angle) * distance; if ( asteroidScale > 3.0f ) { asteroidScale = 3.0f; } else if ( asteroidScale < 0.2f ) { asteroidScale = 0.2f; } arrowBaseScale = (9.0f*asteroidScale); if ( impactSoundDebounceTime < cg.time ) { vec3_t soundOrg; if ( surfaceDist > RADAR_ASTEROID_RANGE*0.66f ) { impactSoundDebounceTime = cg.time + 1000; } else if ( surfaceDist > RADAR_ASTEROID_RANGE/3.0f ) { impactSoundDebounceTime = cg.time + 400; } else { impactSoundDebounceTime = cg.time + 100; } VectorMA( cg.refdef.vieworg, -500.0f*(surfaceDist/RADAR_ASTEROID_RANGE), dirPlayer, soundOrg ); trap_S_StartSound( soundOrg, ENTITYNUM_WORLD, CHAN_AUTO, trap_S_RegisterSound( "sound/vehicles/common/impactalarm.wav" ) ); } //brighten it the closer it is if ( surfaceDist > RADAR_ASTEROID_RANGE*0.66f ) { asteroidColor[0] = asteroidColor[1] = asteroidColor[2] = 0.7f; } else if ( surfaceDist > RADAR_ASTEROID_RANGE/3.0f ) { asteroidColor[0] = asteroidColor[1] = asteroidColor[2] = 0.85f; } else { asteroidColor[0] = asteroidColor[1] = asteroidColor[2] = 1.0f; } //alpha out the longer it's been since it was considered dangerous if ( (cg.time-impactSoundDebounceTime) > 100 ) { asteroidColor[3] = (float)((cg.time-impactSoundDebounceTime)-100)/900.0f; } trap_R_SetColor ( asteroidColor ); CG_DrawPic ( x - 4 + xOffset, ly - 4, arrowBaseScale, arrowBaseScale, trap_R_RegisterShaderNoMip( "gfx/menus/radar/asteroid" ) ); } } break; case ET_MISSILE: if ( //cent->currentState.weapon == WP_ROCKET_LAUNCHER &&//a rocket cent->currentState.owner > MAX_CLIENTS //belongs to an NPC && cg_entities[cent->currentState.owner].currentState.NPC_class == CLASS_VEHICLE ) {//a rocket belonging to an NPC, FIXME: only tracking rockets! float x; float ly; x = (float)RADAR_X + (float)RADAR_RADIUS + (float)sin (angle) * distance; ly = y + (float)RADAR_RADIUS + (float)cos (angle) * distance; arrowBaseScale = 3.0f; if ( cg.predictedPlayerState.m_iVehicleNum ) {//I'm in a vehicle //if it's targetting me, then play an alarm sound if I'm in a vehicle if ( cent->currentState.otherEntityNum == cg.predictedPlayerState.clientNum || cent->currentState.otherEntityNum == cg.predictedPlayerState.m_iVehicleNum ) { if ( radarLockSoundDebounceTime < cg.time ) { vec3_t soundOrg; int alarmSound; if ( actualDist > RADAR_MISSILE_RANGE * 0.66f ) { radarLockSoundDebounceTime = cg.time + 1000; arrowBaseScale = 3.0f; alarmSound = trap_S_RegisterSound( "sound/vehicles/common/lockalarm1.wav" ); } else if ( actualDist > RADAR_MISSILE_RANGE/3.0f ) { radarLockSoundDebounceTime = cg.time + 500; arrowBaseScale = 6.0f; alarmSound = trap_S_RegisterSound( "sound/vehicles/common/lockalarm2.wav" ); } else { radarLockSoundDebounceTime = cg.time + 250; arrowBaseScale = 9.0f; alarmSound = trap_S_RegisterSound( "sound/vehicles/common/lockalarm3.wav" ); } if ( actualDist > RADAR_MISSILE_RANGE ) { actualDist = RADAR_MISSILE_RANGE; } VectorMA( cg.refdef.vieworg, -500.0f*(actualDist/RADAR_MISSILE_RANGE), dirPlayer, soundOrg ); trap_S_StartSound( soundOrg, ENTITYNUM_WORLD, CHAN_AUTO, alarmSound ); } } } zScale = 1.0f; //we want to scale the thing up/down based on the relative Z (up/down) positioning if (cent->lerpOrigin[2] > cg.predictedPlayerState.origin[2]) { //higher, scale up (between 16 and 24) float dif = (cent->lerpOrigin[2] - cg.predictedPlayerState.origin[2]); //max out to 1.5x scale at 512 units above local player's height dif /= 1024.0f; if (dif > 0.5f) { dif = 0.5f; } zScale += dif; } else if (cent->lerpOrigin[2] < cg.predictedPlayerState.origin[2]) { //lower, scale down (between 16 and 8) float dif = (cg.predictedPlayerState.origin[2] - cent->lerpOrigin[2]); //half scale at 512 units below local player's height dif /= 1024.0f; if (dif > 0.5f) { dif = 0.5f; } zScale -= dif; } arrowBaseScale *= zScale; if ( cent->currentState.owner >= MAX_CLIENTS//missile owned by an NPC && cg_entities[cent->currentState.owner].currentState.NPC_class == CLASS_VEHICLE//NPC is a vehicle && cg_entities[cent->currentState.owner].currentState.m_iVehicleNum <= MAX_CLIENTS//Vehicle has a player driver && cgs.clientinfo[cg_entities[cent->currentState.owner].currentState.m_iVehicleNum-1].infoValid ) //player driver is valid { cl = &cgs.clientinfo[cg_entities[cent->currentState.owner].currentState.m_iVehicleNum-1]; if ( cl->team == local->team ) { trap_R_SetColor ( teamColor ); } else { trap_R_SetColor ( g_color_table[ColorIndex(COLOR_RED)] ); } } else { trap_R_SetColor ( NULL ); } CG_DrawPic ( x - 4 + xOffset, ly - 4, arrowBaseScale, arrowBaseScale, cgs.media.mAutomapRocketIcon ); } break; case ET_PLAYER: { vec4_t color; cl = &cgs.clientinfo[ cent->currentState.number ]; // not valid then dont draw it if ( !cl->infoValid ) { continue; } VectorCopy4 ( teamColor, color ); arrowBaseScale = 16.0f; zScale = 1.0f; // Pulse the radar icon after a voice message if ( cent->vChatTime + 2000 > cg.time ) { float f = (cent->vChatTime + 2000 - cg.time) / 3000.0f; arrowBaseScale = 16.0f + 4.0f * f; color[0] = teamColor[0] + (1.0f - teamColor[0]) * f; color[1] = teamColor[1] + (1.0f - teamColor[1]) * f; color[2] = teamColor[2] + (1.0f - teamColor[2]) * f; } trap_R_SetColor ( color ); //we want to scale the thing up/down based on the relative Z (up/down) positioning if (cent->lerpOrigin[2] > cg.predictedPlayerState.origin[2]) { //higher, scale up (between 16 and 32) float dif = (cent->lerpOrigin[2] - cg.predictedPlayerState.origin[2]); //max out to 2x scale at 1024 units above local player's height dif /= 1024.0f; if (dif > 1.0f) { dif = 1.0f; } zScale += dif; } else if (cent->lerpOrigin[2] < cg.predictedPlayerState.origin[2]) { //lower, scale down (between 16 and 8) float dif = (cg.predictedPlayerState.origin[2] - cent->lerpOrigin[2]); //half scale at 512 units below local player's height dif /= 1024.0f; if (dif > 0.5f) { dif = 0.5f; } zScale -= dif; } arrowBaseScale *= zScale; arrow_w = arrowBaseScale * RADAR_RADIUS / 128; arrow_h = arrowBaseScale * RADAR_RADIUS / 128; CG_DrawRotatePic2( RADAR_X + RADAR_RADIUS + sin (angle) * distance + xOffset, y + RADAR_RADIUS + cos (angle) * distance, arrow_w, arrow_h, (360 - cent->lerpAngles[YAW]) + cg.predictedPlayerState.viewangles[YAW], cgs.media.mAutomapPlayerIcon ); break; } } } arrowBaseScale = 16.0f; arrow_w = arrowBaseScale * RADAR_RADIUS / 128; arrow_h = arrowBaseScale * RADAR_RADIUS / 128; trap_R_SetColor ( colorWhite ); CG_DrawRotatePic2( RADAR_X + RADAR_RADIUS + xOffset, y + RADAR_RADIUS, arrow_w, arrow_h, 0, cgs.media.mAutomapPlayerIcon ); return y+(RADAR_RADIUS*2); } /* ================= CG_DrawTimer ================= */ static float CG_DrawTimer( float y ) { char *s; int w; int mins, seconds, tens; int msec; int xOffset = 0; msec = cg.time - cgs.levelStartTime; seconds = msec / 1000; mins = seconds / 60; seconds -= mins * 60; tens = seconds / 10; seconds -= tens * 10; s = va( "%i:%i%i", mins, tens, seconds ); w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH; CG_DrawBigString( 635 - w + xOffset, y + 2, s, 1.0F); return y + BIGCHAR_HEIGHT + 4; } /* ================= CG_DrawTeamOverlay ================= */ extern const char *CG_GetLocationString(const char *loc); //cg_main.c static float CG_DrawTeamOverlay( float y, qboolean right, qboolean upper ) { int x, w, h, xx; int i, j, len; const char *p; vec4_t hcolor; int pwidth, lwidth; int plyrs; char st[16]; clientInfo_t *ci; gitem_t *item; int ret_y, count; int xOffset = 0; if ( !cg_drawTeamOverlay.integer ) { return y; } if ( cg.snap->ps.persistant[PERS_TEAM] != TEAM_RED && cg.snap->ps.persistant[PERS_TEAM] != TEAM_BLUE ) { return y; // Not on any team } plyrs = 0; // max player name width pwidth = 0; count = (numSortedTeamPlayers > 8) ? 8 : numSortedTeamPlayers; for (i = 0; i < count; i++) { ci = cgs.clientinfo + sortedTeamPlayers[i]; if ( ci->infoValid && ci->team == cg.snap->ps.persistant[PERS_TEAM]) { plyrs++; len = CG_DrawStrlen(ci->name); if (len > pwidth) pwidth = len; } } if (!plyrs) return y; if (pwidth > TEAM_OVERLAY_MAXNAME_WIDTH) pwidth = TEAM_OVERLAY_MAXNAME_WIDTH; // max location name width lwidth = 0; for (i = 1; i < MAX_LOCATIONS; i++) { p = CG_GetLocationString(CG_ConfigString(CS_LOCATIONS+i)); if (p && *p) { len = CG_DrawStrlen(p); if (len > lwidth) lwidth = len; } } if (lwidth > TEAM_OVERLAY_MAXLOCATION_WIDTH) lwidth = TEAM_OVERLAY_MAXLOCATION_WIDTH; w = (pwidth + lwidth + 4 + 7) * TINYCHAR_WIDTH; if ( right ) x = 640 - w; else x = 0; h = plyrs * TINYCHAR_HEIGHT; if ( upper ) { ret_y = y + h; } else { y -= h; ret_y = y; } if ( cg.snap->ps.persistant[PERS_TEAM] == TEAM_RED ) { hcolor[0] = 1.0f; hcolor[1] = 0.0f; hcolor[2] = 0.0f; hcolor[3] = 0.33f; } else { // if ( cg.snap->ps.persistant[PERS_TEAM] == TEAM_BLUE ) hcolor[0] = 0.0f; hcolor[1] = 0.0f; hcolor[2] = 1.0f; hcolor[3] = 0.33f; } trap_R_SetColor( hcolor ); CG_DrawPic( x + xOffset, y, w, h, cgs.media.teamStatusBar ); trap_R_SetColor( NULL ); for (i = 0; i < count; i++) { ci = cgs.clientinfo + sortedTeamPlayers[i]; if ( ci->infoValid && ci->team == cg.snap->ps.persistant[PERS_TEAM]) { hcolor[0] = hcolor[1] = hcolor[2] = hcolor[3] = 1.0; xx = x + TINYCHAR_WIDTH; CG_DrawStringExt( xx + xOffset, y, ci->name, hcolor, qfalse, qfalse, TINYCHAR_WIDTH, TINYCHAR_HEIGHT, TEAM_OVERLAY_MAXNAME_WIDTH); if (lwidth) { p = CG_GetLocationString(CG_ConfigString(CS_LOCATIONS+ci->location)); if (!p || !*p) p = "unknown"; len = CG_DrawStrlen(p); if (len > lwidth) len = lwidth; // xx = x + TINYCHAR_WIDTH * 2 + TINYCHAR_WIDTH * pwidth + // ((lwidth/2 - len/2) * TINYCHAR_WIDTH); xx = x + TINYCHAR_WIDTH * 2 + TINYCHAR_WIDTH * pwidth; CG_DrawStringExt( xx + xOffset, y, p, hcolor, qfalse, qfalse, TINYCHAR_WIDTH, TINYCHAR_HEIGHT, TEAM_OVERLAY_MAXLOCATION_WIDTH); } CG_GetColorForHealth( ci->health, ci->armor, hcolor ); Com_sprintf (st, sizeof(st), "%3i %3i", ci->health, ci->armor); xx = x + TINYCHAR_WIDTH * 3 + TINYCHAR_WIDTH * pwidth + TINYCHAR_WIDTH * lwidth; CG_DrawStringExt( xx + xOffset, y, st, hcolor, qfalse, qfalse, TINYCHAR_WIDTH, TINYCHAR_HEIGHT, 0 ); // draw weapon icon xx += TINYCHAR_WIDTH * 3; if ( cg_weapons[ci->curWeapon].weaponIcon ) { CG_DrawPic( xx + xOffset, y, TINYCHAR_WIDTH, TINYCHAR_HEIGHT, cg_weapons[ci->curWeapon].weaponIcon ); } else { CG_DrawPic( xx + xOffset, y, TINYCHAR_WIDTH, TINYCHAR_HEIGHT, cgs.media.deferShader ); } // Draw powerup icons if (right) { xx = x; } else { xx = x + w - TINYCHAR_WIDTH; } for (j = 0; j <= PW_NUM_POWERUPS; j++) { if (ci->powerups & (1 << j)) { item = BG_FindItemForPowerup( j ); if (item) { CG_DrawPic( xx + xOffset, y, TINYCHAR_WIDTH, TINYCHAR_HEIGHT, trap_R_RegisterShader( item->icon ) ); if (right) { xx -= TINYCHAR_WIDTH; } else { xx += TINYCHAR_WIDTH; } } } } y += TINYCHAR_HEIGHT; } } return ret_y; //#endif } static void CG_DrawPowerupIcons(int y) { int j; int ico_size = 64; //int y = ico_size/2; int xOffset = 0; gitem_t *item; if (!cg.snap) { return; } y += 16; for (j = 0; j <= PW_NUM_POWERUPS; j++) { if (cg.snap->ps.powerups[j] > cg.time) { int secondsleft = (cg.snap->ps.powerups[j] - cg.time)/1000; item = BG_FindItemForPowerup( j ); if (item) { int icoShader = 0; if (cgs.gametype == GT_CTY && (j == PW_REDFLAG || j == PW_BLUEFLAG)) { if (j == PW_REDFLAG) { icoShader = trap_R_RegisterShaderNoMip( "gfx/hud/mpi_rflag_ys" ); } else { icoShader = trap_R_RegisterShaderNoMip( "gfx/hud/mpi_bflag_ys" ); } } else { icoShader = trap_R_RegisterShader( item->icon ); } CG_DrawPic( (640-(ico_size*1.1)) + xOffset, y, ico_size, ico_size, icoShader ); y += ico_size; if (j != PW_REDFLAG && j != PW_BLUEFLAG && secondsleft < 999) { UI_DrawProportionalString((640-(ico_size*1.1))+(ico_size/2) + xOffset, y-8, va("%i", secondsleft), UI_CENTER | UI_BIGFONT | UI_DROPSHADOW, colorTable[CT_WHITE]); } y += (ico_size/3); } } } } /* ===================== CG_DrawUpperRight ===================== */ static void CG_DrawUpperRight( void ) { float y=0; trap_R_SetColor( colorTable[CT_WHITE] ); //[CoOp] //allow overlays in CoOp. if ( cgs.gametype >= GT_SINGLE_PLAYER && cg_drawTeamOverlay.integer == 1 ) { //if ( cgs.gametype >= GT_TEAM && cg_drawTeamOverlay.integer == 1 ) { //[/CoOp] y = CG_DrawTeamOverlay( y, qtrue, qtrue ); } if ( cg_drawSnapshot.integer ) { y = CG_DrawSnapshot( y ); } if ( cg_drawFPS.integer ) { y = CG_DrawFPS( y ); } if ( cg_drawTimer.integer ) { y = CG_DrawTimer( y ); } if ( ( cgs.gametype >= GT_TEAM || cg.predictedPlayerState.m_iVehicleNum ) && cg_drawRadar.integer ) {//draw Radar in Siege mode or when in a vehicle of any kind y = CG_DrawRadar ( y ); } y = CG_DrawEnemyInfo ( y ); y = CG_DrawMiniScoreboard ( y ); y = CG_DrawAddText(y); CG_DrawPowerupIcons(y); } /* =============================================================================== LAGOMETER =============================================================================== */ #define LAG_SAMPLES 128 typedef struct { int frameSamples[LAG_SAMPLES]; int frameCount; int snapshotFlags[LAG_SAMPLES]; int snapshotSamples[LAG_SAMPLES]; int snapshotCount; } lagometer_t; lagometer_t lagometer; /* ============== CG_AddLagometerFrameInfo Adds the current interpolate / extrapolate bar for this frame ============== */ void CG_AddLagometerFrameInfo( void ) { int offset; offset = cg.time - cg.latestSnapshotTime; lagometer.frameSamples[ lagometer.frameCount & ( LAG_SAMPLES - 1) ] = offset; lagometer.frameCount++; } /* ============== CG_AddLagometerSnapshotInfo Each time a snapshot is received, log its ping time and the number of snapshots that were dropped before it. Pass NULL for a dropped packet. ============== */ void CG_AddLagometerSnapshotInfo( snapshot_t *snap ) { // dropped packet if ( !snap ) { lagometer.snapshotSamples[ lagometer.snapshotCount & ( LAG_SAMPLES - 1) ] = -1; lagometer.snapshotCount++; return; } // add this snapshot's info lagometer.snapshotSamples[ lagometer.snapshotCount & ( LAG_SAMPLES - 1) ] = snap->ping; lagometer.snapshotFlags[ lagometer.snapshotCount & ( LAG_SAMPLES - 1) ] = snap->snapFlags; lagometer.snapshotCount++; } /* ============== CG_DrawDisconnect Should we draw something differnet for long lag vs no packets? ============== */ static void CG_DrawDisconnect( void ) { float x, y; int cmdNum; usercmd_t cmd; const char *s; int w; // bk010215 - FIXME char message[1024]; if (cg.mMapChange) { s = CG_GetStringEdString("MP_INGAME", "SERVER_CHANGING_MAPS"); // s = "Server Changing Maps"; w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH; CG_DrawBigString( 320 - w/2, 100, s, 1.0F); s = CG_GetStringEdString("MP_INGAME", "PLEASE_WAIT"); // s = "Please wait..."; w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH; CG_DrawBigString( 320 - w/2, 200, s, 1.0F); return; } // draw the phone jack if we are completely past our buffers cmdNum = trap_GetCurrentCmdNumber() - CMD_BACKUP + 1; trap_GetUserCmd( cmdNum, &cmd ); if ( cmd.serverTime <= cg.snap->ps.commandTime || cmd.serverTime > cg.time ) { // special check for map_restart // bk 0102165 - FIXME return; } // also add text in center of screen s = CG_GetStringEdString("MP_INGAME", "CONNECTION_INTERRUPTED"); // s = "Connection Interrupted"; // bk 010215 - FIXME w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH; CG_DrawBigString( 320 - w/2, 100, s, 1.0F); // blink the icon if ( ( cg.time >> 9 ) & 1 ) { return; } x = 640 - 48; y = 480 - 48; CG_DrawPic( x, y, 48, 48, trap_R_RegisterShader("gfx/2d/net.tga" ) ); } #define MAX_LAGOMETER_PING 900 #define MAX_LAGOMETER_RANGE 300 /* ============== CG_DrawLagometer ============== */ static void CG_DrawLagometer( void ) { int a, x, y, i; float v; float ax, ay, aw, ah, mid, range; int color; float vscale; if ( !cg_lagometer.integer || cgs.localServer ) { CG_DrawDisconnect(); return; } // // draw the graph // x = 640 - 48; y = 480 - 144; trap_R_SetColor( NULL ); CG_DrawPic( x, y, 48, 48, cgs.media.lagometerShader ); ax = x; ay = y; aw = 48; ah = 48; color = -1; range = ah / 3; mid = ay + range; vscale = range / MAX_LAGOMETER_RANGE; // draw the frame interpoalte / extrapolate graph for ( a = 0 ; a < aw ; a++ ) { i = ( lagometer.frameCount - 1 - a ) & (LAG_SAMPLES - 1); v = lagometer.frameSamples[i]; v *= vscale; if ( v > 0 ) { if ( color != 1 ) { color = 1; trap_R_SetColor( g_color_table[ColorIndex(COLOR_YELLOW)] ); } if ( v > range ) { v = range; } trap_R_DrawStretchPic ( ax + aw - a, mid - v, 1, v, 0, 0, 0, 0, cgs.media.whiteShader ); } else if ( v < 0 ) { if ( color != 2 ) { color = 2; trap_R_SetColor( g_color_table[ColorIndex(COLOR_BLUE)] ); } v = -v; if ( v > range ) { v = range; } trap_R_DrawStretchPic( ax + aw - a, mid, 1, v, 0, 0, 0, 0, cgs.media.whiteShader ); } } // draw the snapshot latency / drop graph range = ah / 2; vscale = range / MAX_LAGOMETER_PING; for ( a = 0 ; a < aw ; a++ ) { i = ( lagometer.snapshotCount - 1 - a ) & (LAG_SAMPLES - 1); v = lagometer.snapshotSamples[i]; if ( v > 0 ) { if ( lagometer.snapshotFlags[i] & SNAPFLAG_RATE_DELAYED ) { if ( color != 5 ) { color = 5; // YELLOW for rate delay trap_R_SetColor( g_color_table[ColorIndex(COLOR_YELLOW)] ); } } else { if ( color != 3 ) { color = 3; trap_R_SetColor( g_color_table[ColorIndex(COLOR_GREEN)] ); } } v = v * vscale; if ( v > range ) { v = range; } trap_R_DrawStretchPic( ax + aw - a, ay + ah - v, 1, v, 0, 0, 0, 0, cgs.media.whiteShader ); } else if ( v < 0 ) { if ( color != 4 ) { color = 4; // RED for dropped snapshots trap_R_SetColor( g_color_table[ColorIndex(COLOR_RED)] ); } trap_R_DrawStretchPic( ax + aw - a, ay + ah - range, 1, range, 0, 0, 0, 0, cgs.media.whiteShader ); } } trap_R_SetColor( NULL ); if ( cg_nopredict.integer || cg_synchronousClients.integer ) { CG_DrawBigString( ax, ay, "snc", 1.0 ); } CG_DrawDisconnect(); } void CG_DrawSiegeMessage( const char *str, int objectiveScreen ) { // if (!( trap_Key_GetCatcher() & KEYCATCH_UI )) { trap_OpenUIMenu(UIMENU_CLOSEALL); trap_Cvar_Set("cg_siegeMessage", str); if (objectiveScreen) { trap_OpenUIMenu(UIMENU_SIEGEOBJECTIVES); } else { trap_OpenUIMenu(UIMENU_SIEGEMESSAGE); } } } void CG_DrawSiegeMessageNonMenu( const char *str ) { char text[1024]; if (str[0]=='@') { trap_SP_GetStringTextString(str+1, text, sizeof(text)); str = text; } //[Asteroids] CG_CenterPrint(str, SCREEN_HEIGHT * 0.20, BIGCHAR_WIDTH); // CG_CenterPrint(str, SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH); //[/Asteroids] } /* =============================================================================== CENTER PRINTING =============================================================================== */ /* ============== CG_CenterPrint Called for important messages that should stay in the center of the screen for a few moments ============== */ void CG_CenterPrint( const char *str, int y, int charWidth ) { char *s; //[BugFix19] int i = 0; //[/BugFix19] Q_strncpyz( cg.centerPrint, str, sizeof(cg.centerPrint) ); cg.centerPrintTime = cg.time; cg.centerPrintY = y; cg.centerPrintCharWidth = charWidth; // count the number of lines for centering cg.centerPrintLines = 1; s = cg.centerPrint; while( *s ) { //[BugFix19] i++; if(i >= 50) {//maxed out a line of text, this will make the line spill over onto another line. i = 0; cg.centerPrintLines++; } else if (*s == '\n') //if (*s == '\n') //[/BugFix19] cg.centerPrintLines++; s++; } } /* =================== CG_DrawCenterString =================== */ static void CG_DrawCenterString( void ) { char *start; int l; int x, y, w; int h; float *color; const float scale = 1.0; //0.5 if ( !cg.centerPrintTime ) { return; } color = CG_FadeColor( cg.centerPrintTime, 1000 * cg_centertime.value ); if ( !color ) { return; } trap_R_SetColor( color ); start = cg.centerPrint; y = cg.centerPrintY - cg.centerPrintLines * BIGCHAR_HEIGHT / 2; while ( 1 ) { char linebuffer[1024]; for ( l = 0; l < 50; l++ ) { if ( !start[l] || start[l] == '\n' ) { break; } linebuffer[l] = start[l]; } linebuffer[l] = 0; //[BugFix19] if(!BG_IsWhiteSpace(start[l]) && !BG_IsWhiteSpace(linebuffer[l-1]) ) {//we might have cut a word off, attempt to find a spot where we won't cut words off at. int savedL = l; int counter = l-2; for(; counter >= 0; counter--) { if(BG_IsWhiteSpace(start[counter])) {//this location is whitespace, line break from this position linebuffer[counter] = 0; l = counter + 1; break; } } if(counter < 0) {//couldn't find a break in the text, just go ahead and cut off the word mid-word. l = savedL; } } //[/BugFix19] w = CG_Text_Width(linebuffer, scale, FONT_MEDIUM); h = CG_Text_Height(linebuffer, scale, FONT_MEDIUM); x = (SCREEN_WIDTH - w) / 2; CG_Text_Paint(x, y + h, scale, color, linebuffer, 0, 0, ITEM_TEXTSTYLE_SHADOWEDMORE, FONT_MEDIUM); y += h + 6; //[BugFix19] //this method of advancing to new line from the start of the array was causing long lines without //new lines to be totally truncated. if(start[l] && start[l] == '\n') {//next char is a newline, advance past l++; } if ( !start[l] ) {//end of string, we're done. break; } //advance pointer to the last character that we didn't read in. start = &start[l]; //[/BugFix19] } trap_R_SetColor( NULL ); } /* ================================================================================ CROSSHAIR ================================================================================ */ #define HEALTH_WIDTH 50.0f #define HEALTH_HEIGHT 5.0f //see if we can draw some extra info on this guy based on our class void CG_DrawSiegeInfo(centity_t *cent, float chX, float chY, float chW, float chH) { siegeExtended_t *se = &cg_siegeExtendedData[cent->currentState.number]; clientInfo_t *ci; const char *configstring, *v; siegeClass_t *siegeClass; vec4_t aColor; vec4_t bColor; vec4_t cColor; float x; float y; float percent; int ammoMax; assert(cent->currentState.number < MAX_CLIENTS); if (se->lastUpdated > cg.time) { //strange, shouldn't happen return; } if ((cg.time - se->lastUpdated) > 10000) { //if you haven't received a status update on this guy in 10 seconds, forget about it return; } if (cent->currentState.eFlags & EF_DEAD) { //he's dead, don't display info on him return; } if (cent->currentState.weapon != se->weapon) { //data is invalidated until it syncs back again return; } ci = &cgs.clientinfo[cent->currentState.number]; if (ci->team != cg.predictedPlayerState.persistant[PERS_TEAM]) { //not on the same team return; } configstring = CG_ConfigString( cg.predictedPlayerState.clientNum + CS_PLAYERS ); v = Info_ValueForKey( configstring, "siegeclass" ); if (!v || !v[0]) { //don't have siege class in info? return; } siegeClass = BG_SiegeFindClassByName(v); if (!siegeClass) { //invalid return; } if (!(siegeClass->classflags & (1<<CFL_STATVIEWER))) { //doesn't really have the ability to see others' stats return; } x = chX+((chW/2)-(HEALTH_WIDTH/2)); y = (chY+chH) + 8.0f; percent = ((float)se->health/(float)se->maxhealth)*HEALTH_WIDTH; //color of the bar aColor[0] = 0.0f; aColor[1] = 1.0f; aColor[2] = 0.0f; aColor[3] = 0.4f; //color of the border bColor[0] = 0.0f; bColor[1] = 0.0f; bColor[2] = 0.0f; bColor[3] = 0.3f; //color of greyed out "missing health" cColor[0] = 0.5f; cColor[1] = 0.5f; cColor[2] = 0.5f; cColor[3] = 0.4f; //draw the background (black) CG_DrawRect(x, y, HEALTH_WIDTH, HEALTH_HEIGHT, 1.0f, colorTable[CT_BLACK]); //now draw the part to show how much health there is in the color specified CG_FillRect(x+1.0f, y+1.0f, percent-1.0f, HEALTH_HEIGHT-1.0f, aColor); //then draw the other part greyed out CG_FillRect(x+percent, y+1.0f, HEALTH_WIDTH-percent-1.0f, HEALTH_HEIGHT-1.0f, cColor); //now draw his ammo ammoMax = ammoData[weaponData[cent->currentState.weapon].ammoIndex].max; if ( (cent->currentState.eFlags & EF_DOUBLE_AMMO) ) { ammoMax *= 2; } x = chX+((chW/2)-(HEALTH_WIDTH/2)); y = (chY+chH) + HEALTH_HEIGHT + 10.0f; if (!weaponData[cent->currentState.weapon].energyPerShot && !weaponData[cent->currentState.weapon].altEnergyPerShot) { //a weapon that takes no ammo, so show full percent = HEALTH_WIDTH; } else { percent = ((float)se->ammo/(float)ammoMax)*HEALTH_WIDTH; } //color of the bar aColor[0] = 1.0f; aColor[1] = 1.0f; aColor[2] = 0.0f; aColor[3] = 0.4f; //color of the border bColor[0] = 0.0f; bColor[1] = 0.0f; bColor[2] = 0.0f; bColor[3] = 0.3f; //color of greyed out "missing health" cColor[0] = 0.5f; cColor[1] = 0.5f; cColor[2] = 0.5f; cColor[3] = 0.4f; //draw the background (black) CG_DrawRect(x, y, HEALTH_WIDTH, HEALTH_HEIGHT, 1.0f, colorTable[CT_BLACK]); //now draw the part to show how much health there is in the color specified CG_FillRect(x+1.0f, y+1.0f, percent-1.0f, HEALTH_HEIGHT-1.0f, aColor); //then draw the other part greyed out CG_FillRect(x+percent, y+1.0f, HEALTH_WIDTH-percent-1.0f, HEALTH_HEIGHT-1.0f, cColor); } //draw the health bar based on current "health" and maxhealth void CG_DrawHealthBar(centity_t *cent, float chX, float chY, float chW, float chH) { vec4_t aColor; vec4_t bColor; vec4_t cColor; float x = chX+((chW/2)-(HEALTH_WIDTH/2)); float y = (chY+chH) + 8.0f; float percent = ((float)cent->currentState.health/(float)cent->currentState.maxhealth)*HEALTH_WIDTH; if (percent <= 0) { return; } //color of the bar if (!cent->currentState.teamowner || cgs.gametype < GT_TEAM) { //not owned by a team or teamplay aColor[0] = 1.0f; aColor[1] = 1.0f; aColor[2] = 0.0f; aColor[3] = 0.4f; } else if (cent->currentState.teamowner == cg.predictedPlayerState.persistant[PERS_TEAM]) { //owned by my team aColor[0] = 0.0f; aColor[1] = 1.0f; aColor[2] = 0.0f; aColor[3] = 0.4f; } else { //hostile aColor[0] = 1.0f; aColor[1] = 0.0f; aColor[2] = 0.0f; aColor[3] = 0.4f; } //color of the border bColor[0] = 0.0f; bColor[1] = 0.0f; bColor[2] = 0.0f; bColor[3] = 0.3f; //color of greyed out "missing health" cColor[0] = 0.5f; cColor[1] = 0.5f; cColor[2] = 0.5f; cColor[3] = 0.4f; //draw the background (black) CG_DrawRect(x, y, HEALTH_WIDTH, HEALTH_HEIGHT, 1.0f, colorTable[CT_BLACK]); //now draw the part to show how much health there is in the color specified CG_FillRect(x+1.0f, y+1.0f, percent-1.0f, HEALTH_HEIGHT-1.0f, aColor); //then draw the other part greyed out CG_FillRect(x+percent, y+1.0f, HEALTH_WIDTH-percent-1.0f, HEALTH_HEIGHT-1.0f, cColor); } //same routine (at least for now), draw progress of a "hack" or whatever void CG_DrawHaqrBar(float chX, float chY, float chW, float chH) { vec4_t aColor; vec4_t bColor; vec4_t cColor; float x = chX+((chW/2)-(HEALTH_WIDTH/2)); float y = (chY+chH) + 8.0f; float percent = (((float)cg.predictedPlayerState.hackingTime-(float)cg.time)/(float)cg.predictedPlayerState.hackingBaseTime)*HEALTH_WIDTH; if (percent > HEALTH_WIDTH || percent < 1.0f) { return; } //color of the bar aColor[0] = 1.0f; aColor[1] = 1.0f; aColor[2] = 0.0f; aColor[3] = 0.4f; //color of the border bColor[0] = 0.0f; bColor[1] = 0.0f; bColor[2] = 0.0f; bColor[3] = 0.3f; //color of greyed out done area cColor[0] = 0.5f; cColor[1] = 0.5f; cColor[2] = 0.5f; cColor[3] = 0.1f; //draw the background (black) CG_DrawRect(x, y, HEALTH_WIDTH, HEALTH_HEIGHT, 1.0f, colorTable[CT_BLACK]); //now draw the part to show how much health there is in the color specified CG_FillRect(x+1.0f, y+1.0f, percent-1.0f, HEALTH_HEIGHT-1.0f, aColor); //then draw the other part greyed out CG_FillRect(x+percent, y+1.0f, HEALTH_WIDTH-percent-1.0f, HEALTH_HEIGHT-1.0f, cColor); //draw the hacker icon CG_DrawPic(x, y-HEALTH_WIDTH, HEALTH_WIDTH, HEALTH_WIDTH, cgs.media.hackerIconShader); } //generic timing bar int cg_genericTimerBar = 0; int cg_genericTimerDur = 0; vec4_t cg_genericTimerColor; #define CGTIMERBAR_H 50.0f #define CGTIMERBAR_W 10.0f #define CGTIMERBAR_X (SCREEN_WIDTH-CGTIMERBAR_W-120.0f) #define CGTIMERBAR_Y (SCREEN_HEIGHT-CGTIMERBAR_H-20.0f) void CG_DrawGenericTimerBar(void) { vec4_t aColor; vec4_t bColor; vec4_t cColor; float x = CGTIMERBAR_X; float y = CGTIMERBAR_Y; float percent = ((float)(cg_genericTimerBar-cg.time)/(float)cg_genericTimerDur)*CGTIMERBAR_H; if (percent > CGTIMERBAR_H) { return; } if (percent < 0.1f) { percent = 0.1f; } //color of the bar aColor[0] = cg_genericTimerColor[0]; aColor[1] = cg_genericTimerColor[1]; aColor[2] = cg_genericTimerColor[2]; aColor[3] = cg_genericTimerColor[3]; //color of the border bColor[0] = 0.0f; bColor[1] = 0.0f; bColor[2] = 0.0f; bColor[3] = 0.3f; //color of greyed out "missing fuel" cColor[0] = 0.5f; cColor[1] = 0.5f; cColor[2] = 0.5f; cColor[3] = 0.1f; //draw the background (black) CG_DrawRect(x, y, CGTIMERBAR_W, CGTIMERBAR_H, 1.0f, colorTable[CT_BLACK]); //now draw the part to show how much health there is in the color specified CG_FillRect(x+1.0f, y+1.0f+(CGTIMERBAR_H-percent), CGTIMERBAR_W-2.0f, CGTIMERBAR_H-1.0f-(CGTIMERBAR_H-percent), aColor); //then draw the other part greyed out CG_FillRect(x+1.0f, y+1.0f, CGTIMERBAR_W-2.0f, CGTIMERBAR_H-percent, cColor); } /* ================= CG_DrawCrosshair ================= */ float cg_crosshairPrevPosX = 0; float cg_crosshairPrevPosY = 0; #define CRAZY_CROSSHAIR_MAX_ERROR_X (100.0f*640.0f/480.0f) #define CRAZY_CROSSHAIR_MAX_ERROR_Y (100.0f) void CG_LerpCrosshairPos( float *x, float *y ) { if ( cg_crosshairPrevPosX ) {//blend from old pos float maxMove = 30.0f * ((float)cg.frametime/500.0f) * 640.0f/480.0f; float xDiff = (*x - cg_crosshairPrevPosX); if ( fabs(xDiff) > CRAZY_CROSSHAIR_MAX_ERROR_X ) { maxMove = CRAZY_CROSSHAIR_MAX_ERROR_X; } if ( xDiff > maxMove ) { *x = cg_crosshairPrevPosX + maxMove; } else if ( xDiff < -maxMove ) { *x = cg_crosshairPrevPosX - maxMove; } } cg_crosshairPrevPosX = *x; if ( cg_crosshairPrevPosY ) {//blend from old pos float maxMove = 30.0f * ((float)cg.frametime/500.0f); float yDiff = (*y - cg_crosshairPrevPosY); if ( fabs(yDiff) > CRAZY_CROSSHAIR_MAX_ERROR_Y ) { maxMove = CRAZY_CROSSHAIR_MAX_ERROR_X; } if ( yDiff > maxMove ) { *y = cg_crosshairPrevPosY + maxMove; } else if ( yDiff < -maxMove ) { *y = cg_crosshairPrevPosY - maxMove; } } cg_crosshairPrevPosY = *y; } vec3_t cg_crosshairPos={0,0,0}; //[CoOp] extern qboolean in_camera; //[/CoOp] static void CG_DrawCrosshair( vec3_t worldPoint, int chEntValid ) { float w, h; qhandle_t hShader = 0; float f; float x, y; qboolean corona = qfalse; vec4_t ecolor = {0,0,0,0}; centity_t *crossEnt = NULL; float chX, chY; //[CoOp] if(in_camera) {//no crosshair while in cutscenes return; } //[/CoOp] if ( worldPoint ) { VectorCopy( worldPoint, cg_crosshairPos ); } if ( !cg_drawCrosshair.integer ) { return; } if (cg.snap->ps.fallingToDeath) { return; } if ( cg.predictedPlayerState.zoomMode != 0 && cg.predictedPlayerState.weapon != WP_BOWCASTER ) {//not while scoped return; } if ( cg_crosshairHealth.integer ) { vec4_t hcolor; CG_ColorForHealth( hcolor ); trap_R_SetColor( hcolor ); } else { //set color based on what kind of ent is under crosshair if ( cg.crosshairClientNum >= ENTITYNUM_WORLD ) { trap_R_SetColor( NULL ); } //rwwFIXMEFIXME: Write this a different way, it's getting a bit too sloppy looking else if (chEntValid && (cg_entities[cg.crosshairClientNum].currentState.number < MAX_CLIENTS || cg_entities[cg.crosshairClientNum].currentState.eType == ET_NPC || cg_entities[cg.crosshairClientNum].currentState.shouldtarget || cg_entities[cg.crosshairClientNum].currentState.health || //always show ents with health data under crosshair (cg_entities[cg.crosshairClientNum].currentState.eType == ET_MOVER && cg_entities[cg.crosshairClientNum].currentState.bolt1 && cg.predictedPlayerState.weapon == WP_SABER) || (cg_entities[cg.crosshairClientNum].currentState.eType == ET_MOVER && cg_entities[cg.crosshairClientNum].currentState.teamowner))) { crossEnt = &cg_entities[cg.crosshairClientNum]; if ( crossEnt->currentState.powerups & (1 <<PW_CLOAKED) ) { //don't show up for cloaked guys ecolor[0] = 1.0;//R ecolor[1] = 1.0;//G ecolor[2] = 1.0;//B } else if ( crossEnt->currentState.number < MAX_CLIENTS ) { //[CoOp] //make other players show as allies in CoOp //if (cgs.gametype >= GT_TEAM && if (cgs.gametype >= GT_SINGLE_PLAYER && //[/CoOp] cgs.clientinfo[crossEnt->currentState.number].team == cgs.clientinfo[cg.snap->ps.clientNum].team ) { //Allies are green ecolor[0] = 0.0;//R ecolor[1] = 1.0;//G ecolor[2] = 0.0;//B } else { if (cgs.gametype == GT_POWERDUEL && cgs.clientinfo[crossEnt->currentState.number].duelTeam == cgs.clientinfo[cg.snap->ps.clientNum].duelTeam) { //on the same duel team in powerduel, so he's a friend ecolor[0] = 0.0;//R ecolor[1] = 1.0;//G ecolor[2] = 0.0;//B } else { //Enemies are red ecolor[0] = 1.0;//R ecolor[1] = 0.0;//G ecolor[2] = 0.0;//B } } if (cg.snap->ps.duelInProgress) { if (crossEnt->currentState.number != cg.snap->ps.duelIndex) { //grey out crosshair for everyone but your foe if you're in a duel ecolor[0] = 0.4; ecolor[1] = 0.4; ecolor[2] = 0.4; } } else if (crossEnt->currentState.bolt1) { //this fellow is in a duel. We just checked if we were in a duel above, so //this means we aren't and he is. Which of course means our crosshair greys out over him. ecolor[0] = 0.4; ecolor[1] = 0.4; ecolor[2] = 0.4; } } else if (crossEnt->currentState.shouldtarget || crossEnt->currentState.eType == ET_NPC) { //VectorCopy( crossEnt->startRGBA, ecolor ); if ( !ecolor[0] && !ecolor[1] && !ecolor[2] ) { // We really don't want black, so set it to yellow ecolor[0] = 1.0F;//R ecolor[1] = 0.8F;//G ecolor[2] = 0.3F;//B } if (crossEnt->currentState.eType == ET_NPC) { int plTeam; if (cgs.gametype == GT_SIEGE) { plTeam = cg.predictedPlayerState.persistant[PERS_TEAM]; } else { plTeam = NPCTEAM_PLAYER; } if ( crossEnt->currentState.powerups & (1 <<PW_CLOAKED) ) { ecolor[0] = 1.0;//R ecolor[1] = 1.0;//G ecolor[2] = 1.0;//B } else if ( !crossEnt->currentState.teamowner ) { //not on a team if (!crossEnt->currentState.teamowner || crossEnt->currentState.NPC_class == CLASS_VEHICLE) { //neutral if (crossEnt->currentState.owner < MAX_CLIENTS) { //base color on who is pilotting this thing clientInfo_t *ci = &cgs.clientinfo[crossEnt->currentState.owner]; if (cgs.gametype >= GT_TEAM && ci->team == cg.predictedPlayerState.persistant[PERS_TEAM]) { //friendly ecolor[0] = 0.0;//R ecolor[1] = 1.0;//G ecolor[2] = 0.0;//B } else { //hostile ecolor[0] = 1.0;//R ecolor[1] = 0.0;//G ecolor[2] = 0.0;//B } } else { //unmanned ecolor[0] = 1.0;//R ecolor[1] = 1.0;//G ecolor[2] = 0.0;//B } } else { ecolor[0] = 1.0;//R ecolor[1] = 0.0;//G ecolor[2] = 0.0;//B } } else if ( crossEnt->currentState.teamowner != plTeam ) {// on enemy team ecolor[0] = 1.0;//R ecolor[1] = 0.0;//G ecolor[2] = 0.0;//B } else { //a friend ecolor[0] = 0.0;//R ecolor[1] = 1.0;//G ecolor[2] = 0.0;//B } } else if ( crossEnt->currentState.teamowner == TEAM_RED || crossEnt->currentState.teamowner == TEAM_BLUE ) { if (cgs.gametype < GT_TEAM) { //not teamplay, just neutral then ecolor[0] = 1.0;//R ecolor[1] = 1.0;//G ecolor[2] = 0.0;//B } else if ( crossEnt->currentState.teamowner != cgs.clientinfo[cg.snap->ps.clientNum].team ) { //on the enemy team ecolor[0] = 1.0;//R ecolor[1] = 0.0;//G ecolor[2] = 0.0;//B } else { //on my team ecolor[0] = 0.0;//R ecolor[1] = 1.0;//G ecolor[2] = 0.0;//B } } else if (crossEnt->currentState.owner == cg.snap->ps.clientNum || (cgs.gametype >= GT_TEAM && crossEnt->currentState.teamowner == cgs.clientinfo[cg.snap->ps.clientNum].team)) { ecolor[0] = 0.0;//R ecolor[1] = 1.0;//G ecolor[2] = 0.0;//B } else if (crossEnt->currentState.teamowner == 16 || (cgs.gametype >= GT_TEAM && crossEnt->currentState.teamowner && crossEnt->currentState.teamowner != cgs.clientinfo[cg.snap->ps.clientNum].team)) { ecolor[0] = 1.0;//R ecolor[1] = 0.0;//G ecolor[2] = 0.0;//B } } else if (crossEnt->currentState.eType == ET_MOVER && crossEnt->currentState.bolt1 && cg.predictedPlayerState.weapon == WP_SABER) { //can push/pull this mover. Only show it if we're using the saber. ecolor[0] = 0.2f; ecolor[1] = 0.5f; ecolor[2] = 1.0f; corona = qtrue; } else if (crossEnt->currentState.eType == ET_MOVER && crossEnt->currentState.teamowner) { //a team owns this - if it's my team green, if not red, if not teamplay then yellow if (cgs.gametype < GT_TEAM) { ecolor[0] = 1.0;//R ecolor[1] = 1.0;//G ecolor[2] = 0.0;//B } else if (cg.predictedPlayerState.persistant[PERS_TEAM] != crossEnt->currentState.teamowner) { //not my team ecolor[0] = 1.0;//R ecolor[1] = 0.0;//G ecolor[2] = 0.0;//B } else { //my team ecolor[0] = 0.0;//R ecolor[1] = 1.0;//G ecolor[2] = 0.0;//B } } else if (crossEnt->currentState.health) { if (!crossEnt->currentState.teamowner || cgs.gametype < GT_TEAM) { //not owned by a team or teamplay ecolor[0] = 1.0f; ecolor[1] = 1.0f; ecolor[2] = 0.0f; } else if (crossEnt->currentState.teamowner == cg.predictedPlayerState.persistant[PERS_TEAM]) { //owned by my team ecolor[0] = 0.0f; ecolor[1] = 1.0f; ecolor[2] = 0.0f; } else { //hostile ecolor[0] = 1.0f; ecolor[1] = 0.0f; ecolor[2] = 0.0f; } } ecolor[3] = 1.0; trap_R_SetColor( ecolor ); } } if ( cg.predictedPlayerState.m_iVehicleNum ) {//I'm in a vehicle centity_t *vehCent = &cg_entities[cg.predictedPlayerState.m_iVehicleNum]; if ( vehCent && vehCent->m_pVehicle && vehCent->m_pVehicle->m_pVehicleInfo && vehCent->m_pVehicle->m_pVehicleInfo->crosshairShaderHandle ) { hShader = vehCent->m_pVehicle->m_pVehicleInfo->crosshairShaderHandle; } //bigger by default w = cg_crosshairSize.value*2.0f; h = w; } else { w = h = cg_crosshairSize.value; } // pulse the size of the crosshair when picking up items f = cg.time - cg.itemPickupBlendTime; if ( f > 0 && f < ITEM_BLOB_TIME ) { f /= ITEM_BLOB_TIME; w *= ( 1 + f ); h *= ( 1 + f ); } if ( worldPoint && VectorLength( worldPoint ) ) { if ( !CG_WorldCoordToScreenCoordFloat( worldPoint, &x, &y ) ) {//off screen, don't draw it return; } //CG_LerpCrosshairPos( &x, &y ); x -= 320; y -= 240; } else { x = cg_crosshairX.integer; y = cg_crosshairY.integer; } if ( !hShader ) { hShader = cgs.media.crosshairShader[ cg_drawCrosshair.integer % NUM_CROSSHAIRS ]; } chX = x + cg.refdef.x + 0.5 * (640 - w); chY = y + cg.refdef.y + 0.5 * (480 - h); trap_R_DrawStretchPic( chX, chY, w, h, 0, 0, 1, 1, hShader ); //draw a health bar directly under the crosshair if we're looking at something //that takes damage if (crossEnt && crossEnt->currentState.maxhealth) { CG_DrawHealthBar(crossEnt, chX, chY, w, h); chY += HEALTH_HEIGHT*2; } else if (crossEnt && crossEnt->currentState.number < MAX_CLIENTS) { if (cgs.gametype == GT_SIEGE) { CG_DrawSiegeInfo(crossEnt, chX, chY, w, h); chY += HEALTH_HEIGHT*4; } if (cg.crosshairVehNum && cg.time == cg.crosshairVehTime) { //it was in the crosshair this frame centity_t *hisVeh = &cg_entities[cg.crosshairVehNum]; if (hisVeh->currentState.eType == ET_NPC && hisVeh->currentState.NPC_class == CLASS_VEHICLE && hisVeh->currentState.maxhealth && hisVeh->m_pVehicle) { //draw the health for this vehicle CG_DrawHealthBar(hisVeh, chX, chY, w, h); chY += HEALTH_HEIGHT*2; } } } if (cg.predictedPlayerState.hackingTime) { //hacking something CG_DrawHaqrBar(chX, chY, w, h); } if (cg_genericTimerBar > cg.time) { //draw generic timing bar, can be used for whatever CG_DrawGenericTimerBar(); } if ( corona ) // drawing extra bits { ecolor[3] = 0.5f; ecolor[0] = ecolor[1] = ecolor[2] = (1 - ecolor[3]) * ( sin( cg.time * 0.001f ) * 0.08f + 0.35f ); // don't draw full color ecolor[3] = 1.0f; trap_R_SetColor( ecolor ); w *= 2.0f; h *= 2.0f; trap_R_DrawStretchPic( x + cg.refdef.x + 0.5 * (640 - w), y + cg.refdef.y + 0.5 * (480 - h), w, h, 0, 0, 1, 1, cgs.media.forceCoronaShader ); } } qboolean CG_WorldCoordToScreenCoordFloat(vec3_t worldCoord, float *x, float *y) { float xcenter, ycenter; vec3_t local, transformed; vec3_t vfwd; vec3_t vright; vec3_t vup; float xzi; float yzi; // xcenter = cg.refdef.width / 2;//gives screen coords adjusted for resolution // ycenter = cg.refdef.height / 2;//gives screen coords adjusted for resolution //NOTE: did it this way because most draw functions expect virtual 640x480 coords // and adjust them for current resolution xcenter = 640.0f / 2.0f;//gives screen coords in virtual 640x480, to be adjusted when drawn ycenter = 480.0f / 2.0f;//gives screen coords in virtual 640x480, to be adjusted when drawn AngleVectors (cg.refdef.viewangles, vfwd, vright, vup); VectorSubtract (worldCoord, cg.refdef.vieworg, local); transformed[0] = DotProduct(local,vright); transformed[1] = DotProduct(local,vup); transformed[2] = DotProduct(local,vfwd); // Make sure Z is not negative. if(transformed[2] < 0.01f) { return qfalse; } xzi = xcenter / transformed[2] * (96.0f/cg.refdef.fov_x); yzi = ycenter / transformed[2] * (102.0f/cg.refdef.fov_y); *x = xcenter + xzi * transformed[0]; *y = ycenter - yzi * transformed[1]; return qtrue; } qboolean CG_WorldCoordToScreenCoord( vec3_t worldCoord, int *x, int *y ) { float xF, yF; qboolean retVal = CG_WorldCoordToScreenCoordFloat( worldCoord, &xF, &yF ); *x = (int)xF; *y = (int)yF; return retVal; } /* ==================== CG_SaberClashFlare ==================== */ int cg_saberFlashTime = 0; vec3_t cg_saberFlashPos = {0, 0, 0}; void CG_SaberClashFlare( void ) { int t, maxTime = 150; vec3_t dif; vec3_t color; int x,y; float v, len; trace_t tr; t = cg.time - cg_saberFlashTime; if ( t <= 0 || t >= maxTime ) { return; } // Don't do clashes for things that are behind us VectorSubtract( cg_saberFlashPos, cg.refdef.vieworg, dif ); if ( DotProduct( dif, cg.refdef.viewaxis[0] ) < 0.2 ) { return; } CG_Trace( &tr, cg.refdef.vieworg, NULL, NULL, cg_saberFlashPos, -1, CONTENTS_SOLID ); if ( tr.fraction < 1.0f ) { return; } len = VectorNormalize( dif ); // clamp to a known range if ( len > 1200 ) { return; } v = ( 1.0f - ((float)t / maxTime )) * ((1.0f - ( len / 800.0f )) * 2.0f + 0.35f); if (v < 0.001f) { v = 0.001f; } CG_WorldCoordToScreenCoord( cg_saberFlashPos, &x, &y ); VectorSet( color, 0.8f, 0.8f, 0.8f ); trap_R_SetColor( color ); CG_DrawPic( x - ( v * 300 ), y - ( v * 300 ), v * 600, v * 600, trap_R_RegisterShader( "gfx/effects/saberFlare" )); } void CG_DottedLine( float x1, float y1, float x2, float y2, float dotSize, int numDots, vec4_t color, float alpha ) { float x, y, xDiff, yDiff, xStep, yStep; vec4_t colorRGBA; int dotNum = 0; VectorCopy4( color, colorRGBA ); colorRGBA[3] = alpha; trap_R_SetColor( colorRGBA ); xDiff = x2-x1; yDiff = y2-y1; xStep = xDiff/(float)numDots; yStep = yDiff/(float)numDots; for ( dotNum = 0; dotNum < numDots; dotNum++ ) { x = x1 + (xStep*dotNum) - (dotSize*0.5f); y = y1 + (yStep*dotNum) - (dotSize*0.5f); CG_DrawPic( x, y, dotSize, dotSize, cgs.media.whiteShader ); } } void CG_BracketEntity( centity_t *cent, float radius ) { trace_t tr; vec3_t dif; float len, size, lineLength, lineWidth; float x, y; clientInfo_t *local; qboolean isEnemy = qfalse; VectorSubtract( cent->lerpOrigin, cg.refdef.vieworg, dif ); len = VectorNormalize( dif ); if ( cg.crosshairClientNum != cent->currentState.clientNum && (!cg.snap||cg.snap->ps.rocketLockIndex!= cent->currentState.clientNum) ) {//if they're the entity you're locking onto or under your crosshair, always draw bracket //Hmm... for now, if they're closer than 2000, don't bracket? if ( len < 2000.0f ) { return; } CG_Trace( &tr, cg.refdef.vieworg, NULL, NULL, cent->lerpOrigin, -1, CONTENTS_OPAQUE ); //don't bracket if can't see them if ( tr.fraction < 1.0f ) { return; } } if ( !CG_WorldCoordToScreenCoordFloat(cent->lerpOrigin, &x, &y) ) {//off-screen, don't draw it return; } //just to see if it's centered //CG_DrawPic( x-2, y-2, 4, 4, cgs.media.whiteShader ); local = &cgs.clientinfo[cg.snap->ps.clientNum]; if ( cent->currentState.m_iVehicleNum //vehicle has a driver && cgs.clientinfo[ cent->currentState.m_iVehicleNum-1 ].infoValid ) { if ( cgs.gametype < GT_TEAM ) {//ffa? isEnemy = qtrue; trap_R_SetColor ( g_color_table[ColorIndex(COLOR_RED)] ); } else if ( cgs.clientinfo[ cent->currentState.m_iVehicleNum-1 ].team == local->team ) { trap_R_SetColor ( g_color_table[ColorIndex(COLOR_GREEN)] ); } else { isEnemy = qtrue; trap_R_SetColor ( g_color_table[ColorIndex(COLOR_RED)] ); } } else if ( cent->currentState.teamowner ) { if ( cgs.gametype < GT_TEAM ) {//ffa? isEnemy = qtrue; trap_R_SetColor ( g_color_table[ColorIndex(COLOR_RED)] ); } else if ( cent->currentState.teamowner != cg.predictedPlayerState.persistant[PERS_TEAM] ) {// on enemy team isEnemy = qtrue; trap_R_SetColor ( g_color_table[ColorIndex(COLOR_RED)] ); } else { //a friend trap_R_SetColor ( g_color_table[ColorIndex(COLOR_GREEN)] ); } } else {//FIXME: if we want to ever bracket anything besides vehicles (like siege objectives we want to blow up), we should handle the coloring here trap_R_SetColor ( NULL ); } if ( len <= 1.0f ) {//super-close, max out at 400 times radius (which is HUGE) size = radius*400.0f; } else {//scale by dist size = radius*(400.0f/len); } if ( size < 1.0f ) { size = 1.0f; } //length scales with dist lineLength = (size*0.1f); if ( lineLength < 0.5f ) {//always visible lineLength = 0.5f; } //always visible width lineWidth = 1.0f; x -= (size*0.5f); y -= (size*0.5f); {//brackets would be drawn on the screen, so draw them //upper left corner //horz CG_DrawPic( x, y, lineLength, lineWidth, cgs.media.whiteShader ); //vert CG_DrawPic( x, y, lineWidth, lineLength, cgs.media.whiteShader ); //upper right corner //horz CG_DrawPic( x+size-lineLength, y, lineLength, lineWidth, cgs.media.whiteShader ); //vert CG_DrawPic( x+size-lineWidth, y, lineWidth, lineLength, cgs.media.whiteShader ); //lower left corner //horz CG_DrawPic( x, y+size-lineWidth, lineLength, lineWidth, cgs.media.whiteShader ); //vert CG_DrawPic( x, y+size-lineLength, lineWidth, lineLength, cgs.media.whiteShader ); //lower right corner //horz CG_DrawPic( x+size-lineLength, y+size-lineWidth, lineLength, lineWidth, cgs.media.whiteShader ); //vert CG_DrawPic( x+size-lineWidth, y+size-lineLength, lineWidth, lineLength, cgs.media.whiteShader ); } //Lead Indicator... if ( cg_drawVehLeadIndicator.integer ) {//draw the lead indicator if ( isEnemy ) {//an enemy object if ( cent->currentState.NPC_class == CLASS_VEHICLE ) {//enemy vehicle if ( !VectorCompare( cent->currentState.pos.trDelta, vec3_origin ) ) {//enemy vehicle is moving if ( cg.predictedPlayerState.m_iVehicleNum ) {//I'm in a vehicle centity_t *veh = &cg_entities[cg.predictedPlayerState.m_iVehicleNum]; if ( veh //vehicle cent && veh->m_pVehicle//vehicle && veh->m_pVehicle->m_pVehicleInfo//vehicle stats && veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID > VEH_WEAPON_BASE )//valid vehicle weapon { vehWeaponInfo_t *vehWeapon = &g_vehWeaponInfo[veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID]; if ( vehWeapon && vehWeapon->bIsProjectile//primary weapon's shot is a projectile && !vehWeapon->bHasGravity//primary weapon's shot is not affected by gravity && !vehWeapon->fHoming//primary weapon's shot is not homing && vehWeapon->fSpeed )//primary weapon's shot has speed {//our primary weapon's projectile has a speed vec3_t vehDiff, vehLeadPos; float vehDist, eta; float leadX, leadY; VectorSubtract( cent->lerpOrigin, cg.predictedVehicleState.origin, vehDiff ); vehDist = VectorNormalize( vehDiff ); eta = (vehDist/vehWeapon->fSpeed);//how many seconds it would take for my primary weapon's projectile to get from my ship to theirs //now extrapolate their position that number of seconds into the future based on their velocity VectorMA( cent->lerpOrigin, eta, cent->currentState.pos.trDelta, vehLeadPos ); //now we have where we should be aiming at, project that onto the screen at a 2D co-ord if ( !CG_WorldCoordToScreenCoordFloat(cent->lerpOrigin, &x, &y) ) {//off-screen, don't draw it return; } if ( !CG_WorldCoordToScreenCoordFloat(vehLeadPos, &leadX, &leadY) ) {//off-screen, don't draw it //just draw the line CG_DottedLine( x, y, leadX, leadY, 1, 10, g_color_table[ColorIndex(COLOR_RED)], 0.5f ); return; } //draw a line from the ship's cur pos to the lead pos CG_DottedLine( x, y, leadX, leadY, 1, 10, g_color_table[ColorIndex(COLOR_RED)], 0.5f ); //now draw the lead indicator trap_R_SetColor ( g_color_table[ColorIndex(COLOR_RED)] ); CG_DrawPic( leadX-8, leadY-8, 16, 16, trap_R_RegisterShader( "gfx/menus/radar/lead" ) ); } } } } } } } } qboolean CG_InFighter( void ) { if ( cg.predictedPlayerState.m_iVehicleNum ) {//I'm in a vehicle centity_t *vehCent = &cg_entities[cg.predictedPlayerState.m_iVehicleNum]; if ( vehCent && vehCent->m_pVehicle && vehCent->m_pVehicle->m_pVehicleInfo && vehCent->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER ) {//I'm in a fighter return qtrue; } } return qfalse; } qboolean CG_InATST( void ) { if ( cg.predictedPlayerState.m_iVehicleNum ) {//I'm in a vehicle centity_t *vehCent = &cg_entities[cg.predictedPlayerState.m_iVehicleNum]; if ( vehCent && vehCent->m_pVehicle && vehCent->m_pVehicle->m_pVehicleInfo && vehCent->m_pVehicle->m_pVehicleInfo->type == VH_WALKER ) {//I'm in an atst return qtrue; } } return qfalse; } void CG_DrawBracketedEntities( void ) { int i; for ( i = 0; i < cg.bracketedEntityCount; i++ ) { centity_t *cent = &cg_entities[cg.bracketedEntities[i]]; CG_BracketEntity( cent, CG_RadiusForCent( cent ) ); } } //-------------------------------------------------------------- static void CG_DrawHolocronIcons(void) //-------------------------------------------------------------- { int icon_size = 40; int i = 0; int startx = 10; int starty = 10;//SCREEN_HEIGHT - icon_size*3; int endx = icon_size; int endy = icon_size; if (cg.snap->ps.zoomMode) { //don't display over zoom mask return; } if (cgs.clientinfo[cg.snap->ps.clientNum].team == TEAM_SPECTATOR) { return; } while (i < NUM_FORCE_POWERS) { if (cg.snap->ps.holocronBits & (1 << forcePowerSorted[i])) { CG_DrawPic( startx, starty, endx, endy, cgs.media.forcePowerIcons[forcePowerSorted[i]]); starty += (icon_size+2); //+2 for spacing if ((starty+icon_size) >= SCREEN_HEIGHT-80) { starty = 10;//SCREEN_HEIGHT - icon_size*3; startx += (icon_size+2); } } i++; } } static qboolean CG_IsDurationPower(int power) { if (power == FP_HEAL || //[ForceSys] //power == FP_SPEED || //[/ForceSys] power == FP_MINDTRICK || power == FP_RAGE || power == FP_MANIPULATE || power == FP_ABSORB || power == FP_SEE) { return qtrue; } return qfalse; } //-------------------------------------------------------------- static void CG_DrawActivePowers(void) //-------------------------------------------------------------- { int icon_size = 40; int i = 0; int startx = icon_size*2+16; int starty = SCREEN_HEIGHT - icon_size*2; int endx = icon_size; int endy = icon_size; if (cg.snap->ps.zoomMode) { //don't display over zoom mask return; } if (cgs.clientinfo[cg.snap->ps.clientNum].team == TEAM_SPECTATOR) { return; } while (i < NUM_FORCE_POWERS) { if ((cg.snap->ps.fd.forcePowersActive & (1 << forcePowerSorted[i])) && CG_IsDurationPower(forcePowerSorted[i])) { CG_DrawPic( startx, starty, endx, endy, cgs.media.forcePowerIcons[forcePowerSorted[i]]); startx += (icon_size+2); //+2 for spacing if ((startx+icon_size) >= SCREEN_WIDTH-80) { startx = icon_size*2+16; starty += (icon_size+2); } } i++; } //additionally, draw an icon force force rage recovery if (cg.snap->ps.fd.forceRageRecoveryTime > cg.time) { CG_DrawPic( startx, starty, endx, endy, cgs.media.rageRecShader); } } //-------------------------------------------------------------- static void CG_DrawRocketLocking( int lockEntNum, int lockTime ) //-------------------------------------------------------------- { int cx, cy; vec3_t org; static int oldDif = 0; centity_t *cent = &cg_entities[lockEntNum]; vec4_t color={0.0f,0.0f,0.0f,0.0f}; float lockTimeInterval = ((cgs.gametype==GT_SIEGE)?2400.0f:1200.0f)/16.0f; //FIXME: if in a vehicle, use the vehicle's lockOnTime... int dif = (cg.time - cg.snap->ps.rocketLockTime)/lockTimeInterval; int i; if (!cg.snap->ps.rocketLockTime) { return; } if (cgs.clientinfo[cg.snap->ps.clientNum].team == TEAM_SPECTATOR) { return; } if ( cg.snap->ps.m_iVehicleNum ) {//driving a vehicle centity_t *veh = &cg_entities[cg.snap->ps.m_iVehicleNum]; if ( veh->m_pVehicle ) { vehWeaponInfo_t *vehWeapon = NULL; if ( cg.predictedVehicleState.weaponstate == WEAPON_CHARGING_ALT ) { if ( veh->m_pVehicle->m_pVehicleInfo->weapon[1].ID > VEH_WEAPON_BASE && veh->m_pVehicle->m_pVehicleInfo->weapon[1].ID < MAX_VEH_WEAPONS ) { vehWeapon = &g_vehWeaponInfo[veh->m_pVehicle->m_pVehicleInfo->weapon[1].ID]; } } else { if ( veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID > VEH_WEAPON_BASE && veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID < MAX_VEH_WEAPONS ) { vehWeapon = &g_vehWeaponInfo[veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID]; } } if ( vehWeapon != NULL ) {//we are trying to lock on with a valid vehicle weapon, so use *its* locktime, not the hard-coded one if ( !vehWeapon->iLockOnTime ) {//instant lock-on dif = 10.0f; } else {//use the custom vehicle lockOnTime lockTimeInterval = (vehWeapon->iLockOnTime/16.0f); dif = (cg.time - cg.snap->ps.rocketLockTime)/lockTimeInterval; } } } } //We can't check to see in pmove if players are on the same team, so we resort //to just not drawing the lock if a teammate is the locked on ent if (cg.snap->ps.rocketLockIndex >= 0 && cg.snap->ps.rocketLockIndex < ENTITYNUM_NONE) { clientInfo_t *ci = NULL; if (cg.snap->ps.rocketLockIndex < MAX_CLIENTS) { ci = &cgs.clientinfo[cg.snap->ps.rocketLockIndex]; } else { ci = cg_entities[cg.snap->ps.rocketLockIndex].npcClient; } if (ci) { if (ci->team == cgs.clientinfo[cg.snap->ps.clientNum].team) { if (cgs.gametype >= GT_TEAM) { return; } } else if (cgs.gametype >= GT_TEAM) { centity_t *hitEnt = &cg_entities[cg.snap->ps.rocketLockIndex]; if (hitEnt->currentState.eType == ET_NPC && hitEnt->currentState.NPC_class == CLASS_VEHICLE && hitEnt->currentState.owner < ENTITYNUM_WORLD) { //this is a vehicle, if it has a pilot and that pilot is on my team, then... if (hitEnt->currentState.owner < MAX_CLIENTS) { ci = &cgs.clientinfo[hitEnt->currentState.owner]; } else { ci = cg_entities[hitEnt->currentState.owner].npcClient; } if (ci && ci->team == cgs.clientinfo[cg.snap->ps.clientNum].team) { return; } } } } } if (cg.snap->ps.rocketLockTime != -1) { lastvalidlockdif = dif; } else { dif = lastvalidlockdif; } if ( !cent ) { return; } VectorCopy( cent->lerpOrigin, org ); if ( CG_WorldCoordToScreenCoord( org, &cx, &cy )) { // we care about distance from enemy to eye, so this is good enough float sz = Distance( cent->lerpOrigin, cg.refdef.vieworg ) / 1024.0f; if ( sz > 1.0f ) { sz = 1.0f; } else if ( sz < 0.0f ) { sz = 0.0f; } sz = (1.0f - sz) * (1.0f - sz) * 32 + 6; //[Asteroids] if ( cg.snap->ps.m_iVehicleNum ) { sz *= 2.0f; } //[/Asteroids] cy += sz * 0.5f; if ( dif < 0 ) { oldDif = 0; return; } else if ( dif > 8 ) { dif = 8; } // do sounds if ( oldDif != dif ) { if ( dif == 8 ) { if ( cg.snap->ps.m_iVehicleNum ) { trap_S_StartSound( org, 0, CHAN_AUTO, trap_S_RegisterSound( "sound/vehicles/weapons/common/lock.wav" )); } else { trap_S_StartSound( org, 0, CHAN_AUTO, trap_S_RegisterSound( "sound/weapons/rocket/lock.wav" )); } } else { if ( cg.snap->ps.m_iVehicleNum ) { trap_S_StartSound( org, 0, CHAN_AUTO, trap_S_RegisterSound( "sound/vehicles/weapons/common/tick.wav" )); } else { trap_S_StartSound( org, 0, CHAN_AUTO, trap_S_RegisterSound( "sound/weapons/rocket/tick.wav" )); } } } oldDif = dif; for ( i = 0; i < dif; i++ ) { color[0] = 1.0f; color[1] = 0.0f; color[2] = 0.0f; color[3] = 0.1f * i + 0.2f; trap_R_SetColor( color ); // our slices are offset by about 45 degrees. CG_DrawRotatePic( cx - sz, cy - sz, sz, sz, i * 45.0f, trap_R_RegisterShaderNoMip( "gfx/2d/wedge" )); } // we are locked and loaded baby if ( dif == 8 ) { color[0] = color[1] = color[2] = sin( cg.time * 0.05f ) * 0.5f + 0.5f; color[3] = 1.0f; // this art is additive, so the alpha value does nothing trap_R_SetColor( color ); CG_DrawPic( cx - sz, cy - sz * 2, sz * 2, sz * 2, trap_R_RegisterShaderNoMip( "gfx/2d/lock" )); } } } extern void CG_CalcVehMuzzle(Vehicle_t *pVeh, centity_t *ent, int muzzleNum); qboolean CG_CalcVehicleMuzzlePoint( int entityNum, vec3_t start, vec3_t d_f, vec3_t d_rt, vec3_t d_up) { centity_t *vehCent = &cg_entities[entityNum]; if ( vehCent->m_pVehicle && vehCent->m_pVehicle->m_pVehicleInfo->type == VH_WALKER ) {//draw from barrels VectorCopy( vehCent->lerpOrigin, start ); start[2] += vehCent->m_pVehicle->m_pVehicleInfo->height-DEFAULT_MINS_2-48; AngleVectors( vehCent->lerpAngles, d_f, d_rt, d_up ); } else { //check to see if we're a turret gunner on this vehicle if ( cg.predictedPlayerState.generic1 )//as a passenger {//passenger in a vehicle if ( vehCent->m_pVehicle && vehCent->m_pVehicle->m_pVehicleInfo && vehCent->m_pVehicle->m_pVehicleInfo->maxPassengers ) {//a vehicle capable of carrying passengers int turretNum; for ( turretNum = 0; turretNum < MAX_VEHICLE_TURRETS; turretNum++ ) { if ( vehCent->m_pVehicle->m_pVehicleInfo->turret[turretNum].iAmmoMax ) {// valid turret if ( vehCent->m_pVehicle->m_pVehicleInfo->turret[turretNum].passengerNum == cg.predictedPlayerState.generic1 ) {//I control this turret //Go through all muzzles, average their positions and directions and use the result for crosshair trace int vehMuzzle, numMuzzles = 0; vec3_t muzzlesAvgPos={0},muzzlesAvgDir={0}; int i; for ( i = 0; i < MAX_VEHICLE_TURRET_MUZZLES; i++ ) { vehMuzzle = vehCent->m_pVehicle->m_pVehicleInfo->turret[turretNum].iMuzzle[i]; if ( vehMuzzle ) { vehMuzzle -= 1; CG_CalcVehMuzzle( vehCent->m_pVehicle, vehCent, vehMuzzle ); VectorAdd( muzzlesAvgPos, vehCent->m_pVehicle->m_vMuzzlePos[vehMuzzle], muzzlesAvgPos ); VectorAdd( muzzlesAvgDir, vehCent->m_pVehicle->m_vMuzzleDir[vehMuzzle], muzzlesAvgDir ); numMuzzles++; } if ( numMuzzles ) { VectorScale( muzzlesAvgPos, 1.0f/(float)numMuzzles, start ); VectorScale( muzzlesAvgDir, 1.0f/(float)numMuzzles, d_f ); VectorClear( d_rt ); VectorClear( d_up ); return qtrue; } } } } } } } VectorCopy( vehCent->lerpOrigin, start ); AngleVectors( vehCent->lerpAngles, d_f, d_rt, d_up ); } return qfalse; } //calc the muzzle point from the e-web itself void CG_CalcEWebMuzzlePoint(centity_t *cent, vec3_t start, vec3_t d_f, vec3_t d_rt, vec3_t d_up) { int bolt = trap_G2API_AddBolt(cent->ghoul2, 0, "*cannonflash"); assert(bolt != -1); if (bolt != -1) { mdxaBone_t boltMatrix; trap_G2API_GetBoltMatrix_NoRecNoRot(cent->ghoul2, 0, bolt, &boltMatrix, cent->lerpAngles, cent->lerpOrigin, cg.time, NULL, cent->modelScale); BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, start); BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_X, d_f); //these things start the shot a little inside the bbox to assure not starting in something solid VectorMA(start, -16.0f, d_f, start); //I guess VectorClear( d_rt );//don't really need this, do we? VectorClear( d_up );//don't really need this, do we? } } /* ================= CG_`Entity ================= */ #define MAX_XHAIR_DIST_ACCURACY 20000.0f static void CG_ScanForCrosshairEntity( void ) { trace_t trace; vec3_t start, end; int content; int ignore; qboolean bVehCheckTraceFromCamPos = qfalse; ignore = cg.predictedPlayerState.clientNum; if ( cg_dynamicCrosshair.integer ) { vec3_t d_f, d_rt, d_up; //For now we still want to draw the crosshair in relation to the player's world coordinates //even if we have a melee weapon/no weapon. if ( cg.predictedPlayerState.m_iVehicleNum && (cg.predictedPlayerState.eFlags&EF_NODRAW) ) {//we're *inside* a vehicle //do the vehicle's crosshair instead centity_t *veh = &cg_entities[cg.predictedPlayerState.m_iVehicleNum]; qboolean gunner = qfalse; //if (veh->currentState.owner == cg.predictedPlayerState.clientNum) { //the pilot ignore = cg.predictedPlayerState.m_iVehicleNum; gunner = CG_CalcVehicleMuzzlePoint(cg.predictedPlayerState.m_iVehicleNum, start, d_f, d_rt, d_up); } if ( veh->m_pVehicle && veh->m_pVehicle->m_pVehicleInfo && veh->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER && cg.distanceCull > MAX_XHAIR_DIST_ACCURACY && !gunner ) { //NOTE: on huge maps, the crosshair gets inaccurate at close range, // so we'll do an extra G2 trace from the cg.refdef.vieworg // to see if we hit anything closer and auto-aim at it if so bVehCheckTraceFromCamPos = qtrue; } } else if (cg.snap && cg.snap->ps.weapon == WP_EMPLACED_GUN && cg.snap->ps.emplacedIndex && cg_entities[cg.snap->ps.emplacedIndex].ghoul2 && cg_entities[cg.snap->ps.emplacedIndex].currentState.weapon == WP_NONE) { //locked into our e-web, calc the muzzle from it CG_CalcEWebMuzzlePoint(&cg_entities[cg.snap->ps.emplacedIndex], start, d_f, d_rt, d_up); } else { if (cg.snap && cg.snap->ps.weapon == WP_EMPLACED_GUN && cg.snap->ps.emplacedIndex) { vec3_t pitchConstraint; ignore = cg.snap->ps.emplacedIndex; VectorCopy(cg.refdef.viewangles, pitchConstraint); if (cg.renderingThirdPerson) { VectorCopy(cg.predictedPlayerState.viewangles, pitchConstraint); } else { VectorCopy(cg.refdef.viewangles, pitchConstraint); } if (pitchConstraint[PITCH] > 40) { pitchConstraint[PITCH] = 40; } AngleVectors( pitchConstraint, d_f, d_rt, d_up ); } else { vec3_t pitchConstraint; if (cg.renderingThirdPerson) { VectorCopy(cg.predictedPlayerState.viewangles, pitchConstraint); } else { VectorCopy(cg.refdef.viewangles, pitchConstraint); } AngleVectors( pitchConstraint, d_f, d_rt, d_up ); } CG_CalcMuzzlePoint(cg.snap->ps.clientNum, start); } VectorMA( start, cg.distanceCull, d_f, end ); } else { VectorCopy( cg.refdef.vieworg, start ); VectorMA( start, 131072, cg.refdef.viewaxis[0], end ); } if ( cg_dynamicCrosshair.integer && cg_dynamicCrosshairPrecision.integer ) { //then do a trace with ghoul2 models in mind CG_G2Trace( &trace, start, vec3_origin, vec3_origin, end, ignore, CONTENTS_SOLID|CONTENTS_BODY ); if ( bVehCheckTraceFromCamPos ) { //NOTE: this MUST stay up to date with the method used in WP_VehCheckTraceFromCamPos centity_t *veh = &cg_entities[cg.predictedPlayerState.m_iVehicleNum]; trace_t extraTrace; vec3_t viewDir2End, extraEnd; float minAutoAimDist = Distance( veh->lerpOrigin, cg.refdef.vieworg ) + (veh->m_pVehicle->m_pVehicleInfo->length/2.0f) + 200.0f; VectorSubtract( end, cg.refdef.vieworg, viewDir2End ); VectorNormalize( viewDir2End ); VectorMA( cg.refdef.vieworg, MAX_XHAIR_DIST_ACCURACY, viewDir2End, extraEnd ); CG_G2Trace( &extraTrace, cg.refdef.vieworg, vec3_origin, vec3_origin, extraEnd, ignore, CONTENTS_SOLID|CONTENTS_BODY ); if ( !extraTrace.allsolid && !extraTrace.startsolid ) { if ( extraTrace.fraction < 1.0f ) { if ( (extraTrace.fraction*MAX_XHAIR_DIST_ACCURACY) > minAutoAimDist ) { if ( ((extraTrace.fraction*MAX_XHAIR_DIST_ACCURACY)-Distance( veh->lerpOrigin, cg.refdef.vieworg )) < (trace.fraction*cg.distanceCull) ) {//this trace hit *something* that's closer than the thing the main trace hit, so use this result instead memcpy( &trace, &extraTrace, sizeof( trace_t ) ); } } } } } } else { CG_Trace( &trace, start, vec3_origin, vec3_origin, end, ignore, CONTENTS_SOLID|CONTENTS_BODY ); } if (trace.entityNum < MAX_CLIENTS) { if (CG_IsMindTricked(cg_entities[trace.entityNum].currentState.trickedentindex, cg_entities[trace.entityNum].currentState.trickedentindex2, cg_entities[trace.entityNum].currentState.trickedentindex3, cg_entities[trace.entityNum].currentState.trickedentindex4, cg.snap->ps.clientNum)) { if (cg.crosshairClientNum == trace.entityNum) { cg.crosshairClientNum = ENTITYNUM_NONE; cg.crosshairClientTime = 0; } CG_DrawCrosshair(trace.endpos, 0); return; //this entity is mind-tricking the current client, so don't render it } } if (cg.snap->ps.persistant[PERS_TEAM] != TEAM_SPECTATOR) { if (trace.entityNum < ENTITYNUM_WORLD) { cg.crosshairClientNum = trace.entityNum; cg.crosshairClientTime = cg.time; if (cg.crosshairClientNum < ENTITYNUM_WORLD) { centity_t *veh = &cg_entities[cg.crosshairClientNum]; if (veh->currentState.eType == ET_NPC && veh->currentState.NPC_class == CLASS_VEHICLE && veh->currentState.owner < MAX_CLIENTS) { //draw the name of the pilot then cg.crosshairClientNum = veh->currentState.owner; cg.crosshairVehNum = veh->currentState.number; cg.crosshairVehTime = cg.time; } } CG_DrawCrosshair(trace.endpos, 1); } else { CG_DrawCrosshair(trace.endpos, 0); } } // if ( trace.entityNum >= MAX_CLIENTS ) { // return; // } // if the player is in fog, don't show it content = trap_CM_PointContents( trace.endpos, 0 ); if ( content & CONTENTS_FOG ) { return; } // update the fade timer cg.crosshairClientNum = trace.entityNum; cg.crosshairClientTime = cg.time; } void CG_SanitizeString( char *in, char *out ) { int i = 0; int r = 0; while (in[i]) { if (i >= 128-1) { //the ui truncates the name here.. break; } if (in[i] == '^') { if (in[i+1] >= 48 && //'0' in[i+1] <= 57) //'9' { //only skip it if there's a number after it for the color i += 2; continue; } else { //just skip the ^ i++; continue; } } if (in[i] < 32) { i++; continue; } out[r] = in[i]; r++; i++; } out[r] = 0; } /* ===================== CG_DrawCrosshairNames ===================== */ static void CG_DrawCrosshairNames( void ) { float *color; vec4_t tcolor; char *name; char sanitized[1024]; int baseColor; qboolean isVeh = qfalse; //[CoOp] if(in_camera) {//no crosshair while in cutscenes return; } //[/CoOp] if ( !cg_drawCrosshair.integer ) { return; } // scan the known entities to see if the crosshair is sighted on one CG_ScanForCrosshairEntity(); if ( !cg_drawCrosshairNames.integer ) { return; } //rww - still do the trace, our dynamic crosshair depends on it if (cg.crosshairClientNum < ENTITYNUM_WORLD) { centity_t *veh = &cg_entities[cg.crosshairClientNum]; if (veh->currentState.eType == ET_NPC && veh->currentState.NPC_class == CLASS_VEHICLE && veh->currentState.owner < MAX_CLIENTS) { //draw the name of the pilot then cg.crosshairClientNum = veh->currentState.owner; cg.crosshairVehNum = veh->currentState.number; cg.crosshairVehTime = cg.time; isVeh = qtrue; //so we know we're drawing the pilot's name } } if (cg.crosshairClientNum >= MAX_CLIENTS) { return; } if (cg_entities[cg.crosshairClientNum].currentState.powerups & (1 << PW_CLOAKED)) { return; } // draw the name of the player being looked at color = CG_FadeColor( cg.crosshairClientTime, 1000 ); if ( !color ) { trap_R_SetColor( NULL ); return; } name = cgs.clientinfo[ cg.crosshairClientNum ].name; //[CoOp] //make other players show as allies in CoOp //if (cgs.gametype >= GT_TEAM) if (cgs.gametype >= GT_SINGLE_PLAYER) //[/CoOp] { //if (cgs.gametype == GT_SIEGE) if (1) { //instead of team-based we'll make it oriented based on which team we're on if (cgs.clientinfo[cg.crosshairClientNum].team == cg.predictedPlayerState.persistant[PERS_TEAM]) { baseColor = CT_GREEN; } else { baseColor = CT_RED; } } else { if (cgs.clientinfo[cg.crosshairClientNum].team == TEAM_RED) { baseColor = CT_RED; } else { baseColor = CT_BLUE; } } } else { //baseColor = CT_WHITE; if (cgs.gametype == GT_POWERDUEL && cgs.clientinfo[cg.snap->ps.clientNum].team != TEAM_SPECTATOR && cgs.clientinfo[cg.crosshairClientNum].duelTeam == cgs.clientinfo[cg.predictedPlayerState.clientNum].duelTeam) { //on the same duel team in powerduel, so he's a friend baseColor = CT_GREEN; } else { baseColor = CT_RED; //just make it red in nonteam modes since everyone is hostile and crosshair will be red on them too } } if (cg.snap->ps.duelInProgress) { if (cg.crosshairClientNum != cg.snap->ps.duelIndex) { //grey out crosshair for everyone but your foe if you're in a duel baseColor = CT_BLACK; } } else if (cg_entities[cg.crosshairClientNum].currentState.bolt1) { //this fellow is in a duel. We just checked if we were in a duel above, so //this means we aren't and he is. Which of course means our crosshair greys out over him. baseColor = CT_BLACK; } tcolor[0] = colorTable[baseColor][0]; tcolor[1] = colorTable[baseColor][1]; tcolor[2] = colorTable[baseColor][2]; tcolor[3] = color[3]*0.5f; CG_SanitizeString(name, sanitized); if (isVeh) { char str[MAX_STRING_CHARS]; Com_sprintf(str, MAX_STRING_CHARS, "%s (pilot)", sanitized); UI_DrawProportionalString(320, 170, str, UI_CENTER, tcolor); } else { UI_DrawProportionalString(320, 170, sanitized, UI_CENTER, tcolor); } trap_R_SetColor( NULL ); } //============================================================================== /* ================= CG_DrawSpectator ================= */ static void CG_DrawSpectator(void) { const char* s; s = CG_GetStringEdString("MP_INGAME", "SPECTATOR"); if ((cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL) && cgs.duelist1 != -1 && cgs.duelist2 != -1) { char text[1024]; int size = 64; if (cgs.gametype == GT_POWERDUEL && cgs.duelist3 != -1) { Com_sprintf(text, sizeof(text), "%s^7 %s %s^7 %s %s", cgs.clientinfo[cgs.duelist1].name, CG_GetStringEdString("MP_INGAME", "SPECHUD_VERSUS"), cgs.clientinfo[cgs.duelist2].name, CG_GetStringEdString("MP_INGAME", "AND"), cgs.clientinfo[cgs.duelist3].name); } else { Com_sprintf(text, sizeof(text), "%s^7 %s %s", cgs.clientinfo[cgs.duelist1].name, CG_GetStringEdString("MP_INGAME", "SPECHUD_VERSUS"), cgs.clientinfo[cgs.duelist2].name); } CG_Text_Paint ( 320 - CG_Text_Width ( text, 1.0f, 3 ) / 2, 420, 1.0f, colorWhite, text, 0, 0, 0, 3 ); trap_R_SetColor( colorTable[CT_WHITE] ); if ( cgs.clientinfo[cgs.duelist1].modelIcon ) { CG_DrawPic( 10, SCREEN_HEIGHT-(size*1.5), size, size, cgs.clientinfo[cgs.duelist1].modelIcon ); } if ( cgs.clientinfo[cgs.duelist2].modelIcon ) { CG_DrawPic( SCREEN_WIDTH-size-10, SCREEN_HEIGHT-(size*1.5), size, size, cgs.clientinfo[cgs.duelist2].modelIcon ); } // nmckenzie: DUEL_HEALTH if (cgs.gametype == GT_DUEL) { if ( cgs.showDuelHealths >= 1) { // draw the healths on the two guys - how does this interact with power duel, though? CG_DrawDuelistHealth ( 10, SCREEN_HEIGHT-(size*1.5) - 12, 64, 8, 1 ); CG_DrawDuelistHealth ( SCREEN_WIDTH-size-10, SCREEN_HEIGHT-(size*1.5) - 12, 64, 8, 2 ); } } if (cgs.gametype != GT_POWERDUEL) { Com_sprintf(text, sizeof(text), "%i/%i", cgs.clientinfo[cgs.duelist1].score, cgs.fraglimit ); CG_Text_Paint( 42 - CG_Text_Width( text, 1.0f, 2 ) / 2, SCREEN_HEIGHT-(size*1.5) + 64, 1.0f, colorWhite, text, 0, 0, 0, 2 ); Com_sprintf(text, sizeof(text), "%i/%i", cgs.clientinfo[cgs.duelist2].score, cgs.fraglimit ); CG_Text_Paint( SCREEN_WIDTH-size+22 - CG_Text_Width( text, 1.0f, 2 ) / 2, SCREEN_HEIGHT-(size*1.5) + 64, 1.0f, colorWhite, text, 0, 0, 0, 2 ); } if (cgs.gametype == GT_POWERDUEL && cgs.duelist3 != -1) { if ( cgs.clientinfo[cgs.duelist3].modelIcon ) { CG_DrawPic( SCREEN_WIDTH-size-10, SCREEN_HEIGHT-(size*2.8), size, size, cgs.clientinfo[cgs.duelist3].modelIcon ); } } } else { CG_Text_Paint ( 320 - CG_Text_Width ( s, 1.0f, 3 ) / 2, 420, 1.0f, colorWhite, s, 0, 0, 0, 3 ); } if ( cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL ) { s = CG_GetStringEdString("MP_INGAME", "WAITING_TO_PLAY"); // "waiting to play"; CG_Text_Paint ( 320 - CG_Text_Width ( s, 1.0f, 3 ) / 2, 440, 1.0f, colorWhite, s, 0, 0, 0, 3 ); } else //if ( cgs.gametype >= GT_TEAM ) { //s = "press ESC and use the JOIN menu to play"; s = CG_GetStringEdString("MP_INGAME", "SPEC_CHOOSEJOIN"); CG_Text_Paint ( 320 - CG_Text_Width ( s, 1.0f, 3 ) / 2, 440, 1.0f, colorWhite, s, 0, 0, 0, 3 ); } } /* ================= CG_DrawVote ================= */ static void CG_DrawVote(void) { const char *s; int sec; char sYes[20]; char sNo[20]; char sVote[20]; char sCmd[100]; //[VoteSys] char sParm[100]; //const char* sParm = 0; //[/VoteSys] if ( !cgs.voteTime ) { return; } // play a talk beep whenever it is modified if ( cgs.voteModified ) { cgs.voteModified = qfalse; // trap_S_StartLocalSound( cgs.media.talkSound, CHAN_LOCAL_SOUND ); } sec = ( VOTE_TIME - ( cg.time - cgs.voteTime ) ) / 1000; if ( sec < 0 ) { sec = 0; } //[VoteSys] memset(sYes, 0, sizeof(sYes)); memset(sNo, 0, sizeof(sNo)); memset(sVote, 0, sizeof(sVote)); memset(sCmd, 0, sizeof(sCmd)); memset(sParm, 0, sizeof(sParm)); //[/VoteSys] if (strncmp(cgs.voteString, "map_restart", 11)==0) { //[VoteSys] Q_strncpyz(sCmd, CG_GetStringEdString("MENUS", "RESTART_MAP"), sizeof(sCmd)); //trap_SP_GetStringTextString("MENUS_RESTART_MAP", sCmd, sizeof(sCmd) ); //[/VoteSys] } else if (strncmp(cgs.voteString, "vstr nextmap", 12)==0) { //[VoteSys] Q_strncpyz(sCmd, CG_GetStringEdString("MENUS", "NEXT_MAP"), sizeof(sCmd)); //trap_SP_GetStringTextString("MENUS_NEXT_MAP", sCmd, sizeof(sCmd) ); //[/VoteSys] } else if (strncmp(cgs.voteString, "g_doWarmup", 10)==0) { //[VoteSys] Q_strncpyz(sCmd, CG_GetStringEdString("MENUS", "WARMUP"), sizeof(sCmd)); //trap_SP_GetStringTextString("MENUS_WARMUP", sCmd, sizeof(sCmd) ); //[/VoteSys] } else if (strncmp(cgs.voteString, "g_gametype", 10)==0) { //[VoteSys] Q_strncpyz(sCmd, CG_GetStringEdString("MENUS", "GAME_TYPE"), sizeof(sCmd)); //trap_SP_GetStringTextString("MENUS_GAME_TYPE", sCmd, sizeof(sCmd) ); //[/VoteSys] if ( stricmp("Free For All", cgs.voteString+11)==0 ) { //[VoteSys] Q_strncpyz(sParm, CG_GetStringEdString("MENUS", "FREE_FOR_ALL"), sizeof(sParm)); //sParm = CG_GetStringEdString("MENUS", "FREE_FOR_ALL"); //[/VoteSys] } else if ( stricmp("Duel", cgs.voteString+11)==0 ) { //[VoteSys] Q_strncpyz(sParm, CG_GetStringEdString("MENUS", "DUEL"), sizeof(sParm)); //sParm = CG_GetStringEdString("MENUS", "DUEL"); //[/VoteSys] } else if ( stricmp("Jedi Master", cgs.voteString+11)==0 ) { //[VoteSys] Q_strncpyz(sParm, CG_GetStringEdString("OJP_MENUS", "JEDIMASTER"), sizeof(sParm)); //sParm = CG_GetStringEdString("OJP_MENUS", "JEDIMASTER"); //[/VoteSys] } else if ( stricmp("Holocron FFA", cgs.voteString+11)==0 ) { //[VoteSys] Q_strncpyz(sParm, CG_GetStringEdString("MENUS", "HOLOCRON_FFA"), sizeof(sParm)); //sParm = CG_GetStringEdString("MENUS", "HOLOCRON_FFA"); //[/VoteSys] } else if ( stricmp("Power Duel", cgs.voteString+11)==0 ) { //[VoteSys] Q_strncpyz(sParm, CG_GetStringEdString("MENUS", "POWERDUEL"), sizeof(sParm)); //sParm = CG_GetStringEdString("MENUS", "POWERDUEL"); //[/VoteSys] } else if ( stricmp("Team FFA", cgs.voteString+11)==0 ) { //[VoteSys] Q_strncpyz(sParm, CG_GetStringEdString("MENUS", "TEAM_FFA"), sizeof(sParm)); //sParm = CG_GetStringEdString("MENUS", "TEAM_FFA"); //[/VoteSys] } else if ( stricmp("Siege", cgs.voteString+11)==0 ) { //[VoteSys] Q_strncpyz(sParm, CG_GetStringEdString("MENUS", "SIEGE"), sizeof(sParm)); //sParm = CG_GetStringEdString("MENUS", "SIEGE"); //[/VoteSys] } else if ( stricmp("Capture the Flag", cgs.voteString+11)==0 ) { //[VoteSys] Q_strncpyz(sParm, CG_GetStringEdString("MENUS", "CAPTURE_THE_FLAG"), sizeof(sParm)); //sParm = CG_GetStringEdString("MENUS", "CAPTURE_THE_FLAG"); //[/VoteSys] } else if ( stricmp("Capture the Ysalamiri", cgs.voteString+11)==0 ) { Q_strncpyz(sParm, CG_GetStringEdString("MENUS", "CAPTURE_THE_YSALIMARI"), sizeof(sParm)); //sParm = CG_GetStringEdString("MENUS", "CAPTURE_THE_YSALIMARI"); } //[CoOp] //[VoteSys] else if ( stricmp("Single Player", cgs.voteString+11)==0 ) { Q_strncpyz(sParm, CG_GetStringEdString("OJP_MENUS", "COOP"), sizeof(sParm)); //sParm = CG_GetStringEdString("OJP_MENUS", "COOP"); } //[/VoteSys] //[/CoOp] //[VoteSys] else { Q_strncpyz(sParm, CG_GetStringEdString("MENUS", "SAGA"), sizeof(sParm)); //sParm = CG_GetStringEdString("MENUS", "SAGA"); } //[/VoteSys] } else if (strncmp(cgs.voteString, "map", 3)==0) { //[VoteSys] Q_strncpyz(sCmd, CG_GetStringEdString("MENUS", "NEW_MAP"), sizeof(sCmd)); Q_strncpyz(sParm, cgs.voteString+4, sizeof(sParm)); //trap_SP_GetStringTextString("MENUS_NEW_MAP", sCmd, sizeof(sCmd) ); //sParm = cgs.voteString+4; //[/VoteSys] } else if (strncmp(cgs.voteString, "kick", 4)==0) { //[VoteSys] Q_strncpyz(sCmd, CG_GetStringEdString("MENUS", "KICK_PLAYER"), sizeof(sCmd)); Q_strncpyz(sParm, cgs.voteString+5, sizeof(sParm)); //trap_SP_GetStringTextString("MENUS_KICK_PLAYER", sCmd, sizeof(sCmd) ); //sParm = cgs.voteString+5; //[/VoteSys] } //[VoteSys] else if (strncmp(cgs.voteString, "timelimit", 9)==0) { Q_strncpyz(sCmd, CG_GetStringEdString("MP_INGAME", "TIMELIMIT"), sizeof(sCmd)); Q_strncpyz(sParm, cgs.voteString+10, sizeof(sParm)); } else if (strncmp(cgs.voteString, "fraglimit", 9)==0) { Q_strncpyz(sCmd, CG_GetStringEdString("MP_INGAME", "FRAGLIMIT"), sizeof(sCmd)); Q_strncpyz(sParm, cgs.voteString+10, sizeof(sParm)); } else if (strncmp(cgs.voteString, "capturelimit", 12)==0) { Q_strncpyz(sCmd, CG_GetStringEdString("MP_INGAME", "CAPTURELIMIT"), sizeof(sCmd)); Q_strncpyz(sParm, cgs.voteString+13, sizeof(sParm)); } else { Q_strncpyz(sCmd, cgs.voteString, sizeof(sCmd)); } Q_strncpyz(sVote, CG_GetStringEdString("MENUS", "VOTE"), sizeof(sVote)); Q_strncpyz(sYes, CG_GetStringEdString("MENUS", "YES"), sizeof(sYes)); Q_strncpyz(sNo, CG_GetStringEdString("MENUS", "NO"), sizeof(sNo)); //trap_SP_GetStringTextString("MENUS_VOTE", sVote, sizeof(sVote) ); //trap_SP_GetStringTextString("MENUS_YES", sYes, sizeof(sYes) ); //trap_SP_GetStringTextString("MENUS_NO", sNo, sizeof(sNo) ); if (*sParm && sParm[0]) //if (sParm && sParm[0]) //[/VoteSys] { s = va("%s(%i):<%s %s> %s:%i %s:%i", sVote, sec, sCmd, sParm, sYes, cgs.voteYes, sNo, cgs.voteNo); } else { s = va("%s(%i):<%s> %s:%i %s:%i", sVote, sec, sCmd, sYes, cgs.voteYes, sNo, cgs.voteNo); } CG_DrawSmallString( 4, 58, s, 1.0F ); s = CG_GetStringEdString("MP_INGAME", "OR_PRESS_ESC_THEN_CLICK_VOTE"); // s = "or press ESC then click Vote"; CG_DrawSmallString( 4, 58 + SMALLCHAR_HEIGHT + 2, s, 1.0F ); } /* ================= CG_DrawTeamVote ================= */ static void CG_DrawTeamVote(void) { char *s; int sec, cs_offset; if ( cgs.clientinfo->team == TEAM_RED ) cs_offset = 0; else if ( cgs.clientinfo->team == TEAM_BLUE ) cs_offset = 1; else return; if ( !cgs.teamVoteTime[cs_offset] ) { return; } // play a talk beep whenever it is modified if ( cgs.teamVoteModified[cs_offset] ) { cgs.teamVoteModified[cs_offset] = qfalse; // trap_S_StartLocalSound( cgs.media.talkSound, CHAN_LOCAL_SOUND ); } sec = ( VOTE_TIME - ( cg.time - cgs.teamVoteTime[cs_offset] ) ) / 1000; if ( sec < 0 ) { sec = 0; } if (strstr(cgs.teamVoteString[cs_offset], "leader")) { int i = 0; while (cgs.teamVoteString[cs_offset][i] && cgs.teamVoteString[cs_offset][i] != ' ') { i++; } if (cgs.teamVoteString[cs_offset][i] == ' ') { int voteIndex = 0; char voteIndexStr[256]; i++; while (cgs.teamVoteString[cs_offset][i]) { voteIndexStr[voteIndex] = cgs.teamVoteString[cs_offset][i]; voteIndex++; i++; } voteIndexStr[voteIndex] = 0; voteIndex = atoi(voteIndexStr); s = va("TEAMVOTE(%i):(Make %s the new team leader) yes:%i no:%i", sec, cgs.clientinfo[voteIndex].name, cgs.teamVoteYes[cs_offset], cgs.teamVoteNo[cs_offset] ); } else { s = va("TEAMVOTE(%i):%s yes:%i no:%i", sec, cgs.teamVoteString[cs_offset], cgs.teamVoteYes[cs_offset], cgs.teamVoteNo[cs_offset] ); } } else { s = va("TEAMVOTE(%i):%s yes:%i no:%i", sec, cgs.teamVoteString[cs_offset], cgs.teamVoteYes[cs_offset], cgs.teamVoteNo[cs_offset] ); } CG_DrawSmallString( 4, 90, s, 1.0F ); } static qboolean CG_DrawScoreboard() { return CG_DrawOldScoreboard(); } /* ================= CG_DrawIntermission ================= */ static void CG_DrawIntermission( void ) { // int key; //if (cg_singlePlayer.integer) { // CG_DrawCenterString(); // return; //} cg.scoreFadeTime = cg.time; cg.scoreBoardShowing = CG_DrawScoreboard(); } /* ================= CG_DrawFollow ================= */ static qboolean CG_DrawFollow( void ) { const char *s; if ( !(cg.snap->ps.pm_flags & PMF_FOLLOW) ) { return qfalse; } // s = "following"; if (cgs.gametype == GT_POWERDUEL) { clientInfo_t *ci = &cgs.clientinfo[ cg.snap->ps.clientNum ]; if (ci->duelTeam == DUELTEAM_LONE) { s = CG_GetStringEdString("MP_INGAME", "FOLLOWINGLONE"); } else if (ci->duelTeam == DUELTEAM_DOUBLE) { s = CG_GetStringEdString("MP_INGAME", "FOLLOWINGDOUBLE"); } else { s = CG_GetStringEdString("MP_INGAME", "FOLLOWING"); } } else { s = CG_GetStringEdString("MP_INGAME", "FOLLOWING"); } CG_Text_Paint ( 320 - CG_Text_Width ( s, 1.0f, FONT_MEDIUM ) / 2, 60, 1.0f, colorWhite, s, 0, 0, 0, FONT_MEDIUM ); s = cgs.clientinfo[ cg.snap->ps.clientNum ].name; CG_Text_Paint ( 320 - CG_Text_Width ( s, 2.0f, FONT_MEDIUM ) / 2, 80, 2.0f, colorWhite, s, 0, 0, 0, FONT_MEDIUM ); return qtrue; } /* ================= CG_DrawWarmup ================= */ static void CG_DrawWarmup( void ) { int w; int sec; int i; float scale; int cw; const char *s; sec = cg.warmup; if ( !sec ) { return; } if ( sec < 0 ) { // s = "Waiting for players"; s = CG_GetStringEdString("MP_INGAME", "WAITING_FOR_PLAYERS"); w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH; CG_DrawBigString(320 - w / 2, 24, s, 1.0F); cg.warmupCount = 0; return; } if (cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL) { // find the two active players clientInfo_t *ci1, *ci2, *ci3; ci1 = NULL; ci2 = NULL; ci3 = NULL; if (cgs.gametype == GT_POWERDUEL) { if (cgs.duelist1 != -1) { ci1 = &cgs.clientinfo[cgs.duelist1]; } if (cgs.duelist2 != -1) { ci2 = &cgs.clientinfo[cgs.duelist2]; } if (cgs.duelist3 != -1) { ci3 = &cgs.clientinfo[cgs.duelist3]; } } else { for ( i = 0 ; i < cgs.maxclients ; i++ ) { if ( cgs.clientinfo[i].infoValid && cgs.clientinfo[i].team == TEAM_FREE ) { if ( !ci1 ) { ci1 = &cgs.clientinfo[i]; } else { ci2 = &cgs.clientinfo[i]; } } } } if ( ci1 && ci2 ) { if (ci3) { s = va( "%s vs %s and %s", ci1->name, ci2->name, ci3->name ); } else { s = va( "%s vs %s", ci1->name, ci2->name ); } w = CG_Text_Width(s, 0.6f, FONT_MEDIUM); CG_Text_Paint(320 - w / 2, 60, 0.6f, colorWhite, s, 0, 0, ITEM_TEXTSTYLE_SHADOWEDMORE,FONT_MEDIUM); } } else { if ( cgs.gametype == GT_FFA ) { s = CG_GetStringEdString("MENUS", "FREE_FOR_ALL");//"Free For All"; } else if ( cgs.gametype == GT_HOLOCRON ) { s = CG_GetStringEdString("MENUS", "HOLOCRON_FFA");//"Holocron FFA"; } else if ( cgs.gametype == GT_JEDIMASTER ) { //[OLDGAMETYPES] //s = CG_GetStringEdString("MENUS", "POWERDUEL");//"Jedi Master";?? s = CG_GetStringEdString("OJP_MENUS", "JEDIMASTER");//"Jedi Master";?? //[/OLDGAMETYPES] } else if ( cgs.gametype == GT_TEAM ) { s = CG_GetStringEdString("MENUS", "TEAM_FFA");//"Team FFA"; } else if ( cgs.gametype == GT_SIEGE ) { s = CG_GetStringEdString("MENUS", "SIEGE");//"Siege"; } else if ( cgs.gametype == GT_CTF ) { s = CG_GetStringEdString("MENUS", "CAPTURE_THE_FLAG");//"Capture the Flag"; } else if ( cgs.gametype == GT_CTY ) { s = CG_GetStringEdString("MENUS", "CAPTURE_THE_YSALIMARI");//"Capture the Ysalamiri"; //[CoOp] } else if ( cgs.gametype == GT_SINGLE_PLAYER ) { s = CG_GetStringEdString("OJP_MENUS", "COOP");//"Cooperative"; //[/CoOp] } else { s = ""; } w = CG_Text_Width(s, 1.5f, FONT_MEDIUM); CG_Text_Paint(320 - w / 2, 90, 1.5f, colorWhite, s, 0, 0, ITEM_TEXTSTYLE_SHADOWEDMORE,FONT_MEDIUM); } sec = ( sec - cg.time ) / 1000; if ( sec < 0 ) { cg.warmup = 0; sec = 0; } // s = va( "Starts in: %i", sec + 1 ); s = va( "%s: %i",CG_GetStringEdString("MP_INGAME", "STARTS_IN"), sec + 1 ); if ( sec != cg.warmupCount ) { cg.warmupCount = sec; if (cgs.gametype != GT_SIEGE) { switch ( sec ) { case 0: trap_S_StartLocalSound( cgs.media.count1Sound, CHAN_ANNOUNCER ); break; case 1: trap_S_StartLocalSound( cgs.media.count2Sound, CHAN_ANNOUNCER ); break; case 2: trap_S_StartLocalSound( cgs.media.count3Sound, CHAN_ANNOUNCER ); break; default: break; } } } scale = 0.45f; switch ( cg.warmupCount ) { case 0: cw = 28; scale = 1.25f; break; case 1: cw = 24; scale = 1.15f; break; case 2: cw = 20; scale = 1.05f; break; default: cw = 16; scale = 0.9f; break; } w = CG_Text_Width(s, scale, FONT_MEDIUM); CG_Text_Paint(320 - w / 2, 125, scale, colorWhite, s, 0, 0, ITEM_TEXTSTYLE_SHADOWEDMORE, FONT_MEDIUM); } //================================================================================== /* ================= CG_DrawTimedMenus ================= */ void CG_DrawTimedMenus() { if (cg.voiceTime) { int t = cg.time - cg.voiceTime; if ( t > 2500 ) { Menus_CloseByName("voiceMenu"); trap_Cvar_Set("cl_conXOffset", "0"); cg.voiceTime = 0; } } } void CG_DrawFlagStatus() { int myFlagTakenShader = 0; int theirFlagShader = 0; int team = 0; int startDrawPos = 2; int ico_size = 32; if (!cg.snap) { return; } if (cgs.gametype != GT_CTF && cgs.gametype != GT_CTY) { return; } team = cg.snap->ps.persistant[PERS_TEAM]; if (cgs.gametype == GT_CTY) { if (team == TEAM_RED) { myFlagTakenShader = trap_R_RegisterShaderNoMip( "gfx/hud/mpi_rflag_x" ); theirFlagShader = trap_R_RegisterShaderNoMip( "gfx/hud/mpi_bflag_ys" ); } else { myFlagTakenShader = trap_R_RegisterShaderNoMip( "gfx/hud/mpi_bflag_x" ); theirFlagShader = trap_R_RegisterShaderNoMip( "gfx/hud/mpi_rflag_ys" ); } } else { if (team == TEAM_RED) { myFlagTakenShader = trap_R_RegisterShaderNoMip( "gfx/hud/mpi_rflag_x" ); theirFlagShader = trap_R_RegisterShaderNoMip( "gfx/hud/mpi_bflag" ); } else { myFlagTakenShader = trap_R_RegisterShaderNoMip( "gfx/hud/mpi_bflag_x" ); theirFlagShader = trap_R_RegisterShaderNoMip( "gfx/hud/mpi_rflag" ); } } if (CG_YourTeamHasFlag()) { //CG_DrawPic( startDrawPos, 330, ico_size, ico_size, theirFlagShader ); CG_DrawPic( 2, 330-startDrawPos, ico_size, ico_size, theirFlagShader ); startDrawPos += ico_size+2; } if (CG_OtherTeamHasFlag()) { //CG_DrawPic( startDrawPos, 330, ico_size, ico_size, myFlagTakenShader ); CG_DrawPic( 2, 330-startDrawPos, ico_size, ico_size, myFlagTakenShader ); } } //draw meter showing jetpack fuel when it's not full #define JPFUELBAR_H JETPACK_MAXFUEL #define JPFUELBAR_W 20.0f #define JPFUELBAR_X (SCREEN_WIDTH-JPFUELBAR_W-8.0f) //[NewHud] //moved the jetpack fuel bar a little since the new hud overlapped it. #define JPFUELBAR_Y 240.0f //#define JPFUELBAR_Y 260.0f //[/NewHud] void CG_DrawJetpackFuel(void) { vec4_t aColor; vec4_t bColor; vec4_t cColor; float x = JPFUELBAR_X; float y = JPFUELBAR_Y; float percent = ((float)cg.snap->ps.jetpackFuel/JETPACK_MAXFUEL)*JPFUELBAR_H; if (percent > JPFUELBAR_H) { return; } if (percent < 0.1f) { percent = 0.1f; } //color of the bar aColor[0] = 0.5f; aColor[1] = 0.0f; aColor[2] = 0.0f; aColor[3] = 0.8f; //color of the border bColor[0] = 0.0f; bColor[1] = 0.0f; bColor[2] = 0.0f; bColor[3] = 0.3f; //color of greyed out "missing fuel" cColor[0] = 0.5f; cColor[1] = 0.5f; cColor[2] = 0.5f; cColor[3] = 0.1f; //draw the background (black) CG_DrawRect(x, y, JPFUELBAR_W, JPFUELBAR_H, 1.0f, colorTable[CT_BLACK]); //now draw the part to show how much health there is in the color specified CG_FillRect(x+1.0f, y+1.0f+(JPFUELBAR_H-percent), JPFUELBAR_W-1.0f, JPFUELBAR_H-1.0f-(JPFUELBAR_H-percent), aColor); //then draw the other part greyed out CG_FillRect(x+1.0f, y+1.0f, JPFUELBAR_W-1.0f, JPFUELBAR_H-percent, cColor); } //draw meter showing e-web health when it is in use #define EWEBHEALTH_H 100.0f #define EWEBHEALTH_W 20.0f #define EWEBHEALTH_X (SCREEN_WIDTH-EWEBHEALTH_W-8.0f) //[NewHud] //moved to prevent overlap with new hud. #define EWEBHEALTH_Y 240.0f //#define EWEBHEALTH_Y 290.0f //[/NewHud] void CG_DrawEWebHealth(void) { vec4_t aColor; vec4_t bColor; vec4_t cColor; float x = EWEBHEALTH_X; float y = EWEBHEALTH_Y; centity_t *eweb = &cg_entities[cg.predictedPlayerState.emplacedIndex]; float percent = ((float)eweb->currentState.health/eweb->currentState.maxhealth)*EWEBHEALTH_H; if (percent > EWEBHEALTH_H) { return; } if (percent < 0.1f) { percent = 0.1f; } //kind of hacky, need to pass a coordinate in here if (cg.snap->ps.jetpackFuel < JETPACK_MAXFUEL) { x -= (JPFUELBAR_W+8.0f); } if (cg.snap->ps.cloakFuel < 100) { x -= (JPFUELBAR_W+8.0f); } //color of the bar aColor[0] = 0.5f; aColor[1] = 0.0f; aColor[2] = 0.0f; aColor[3] = 0.8f; //color of the border bColor[0] = 0.0f; bColor[1] = 0.0f; bColor[2] = 0.0f; bColor[3] = 0.3f; //color of greyed out "missing fuel" cColor[0] = 0.5f; cColor[1] = 0.5f; cColor[2] = 0.5f; cColor[3] = 0.1f; //draw the background (black) CG_DrawRect(x, y, EWEBHEALTH_W, EWEBHEALTH_H, 1.0f, colorTable[CT_BLACK]); //now draw the part to show how much health there is in the color specified CG_FillRect(x+1.0f, y+1.0f+(EWEBHEALTH_H-percent), EWEBHEALTH_W-1.0f, EWEBHEALTH_H-1.0f-(EWEBHEALTH_H-percent), aColor); //then draw the other part greyed out CG_FillRect(x+1.0f, y+1.0f, EWEBHEALTH_W-1.0f, EWEBHEALTH_H-percent, cColor); } //[LOLHUD] //LOLOL #define BAR_H 65.0f #define BAR_W 13.0f #define BAR_Y 375.0f #define HEALTH_X (32) #define ARMOR_X (32+32) #define DEFENSE_X (32+32+32) #define FORCE_X (32+32+32+32) #define BALANCE_X (32+32+32+32+32) void CG_DrawHealthLevel(void) { float x = HEALTH_X; float y = BAR_Y; float percent = ((float)cg.snap->ps.stats[STAT_HEALTH]/cg.snap->ps.stats[STAT_MAX_HEALTH])*BAR_H; vec4_t color; color[0] = 0.407843137254902; color[1] = 0; color[2] = 0.003921568627451; color[3] = 1;// 0.5f; float *hudTintColor = colorTable[CT_WHITE]; trap_R_SetColor( NULL ); menuDef_t* menuHUD = Menus_FindByName("lefthud"); if (menuHUD) { // Print frame itemDef_t* focusItem = Menu_FindItemByName(menuHUD, "health_triangle"); if (focusItem) { trap_R_SetColor( hudTintColor ); CG_DrawPic( focusItem->window.rect.x, focusItem->window.rect.y, focusItem->window.rect.w, focusItem->window.rect.h, focusItem->window.background ); } } CG_FillRect(x+25.0f, y-18, BAR_W+7, BAR_H-(BAR_H-percent),color); } void CG_DrawArmorLevel(void) { float x = ARMOR_X; float y = BAR_Y; float percent = ((float)cg.snap->ps.stats[STAT_ARMOR]/100)*BAR_H; vec4_t color; color[0] = 0.0549019607843137; color[1] = 0.3607843137254902; color[2] = 0.0549019607843137; color[3] = 1;//0.8352941176470588;// 0.5f; //[zomg] //CG_DrawPic(x+1.0f, y+(BAR_H-percent), BAR_W-2.0f, BAR_H-(BAR_H-percent)-1.0f,trap_R_RegisterShader( "gfx/hud/health.tga" )); //CG_DrawPic(x+17.6f, y+46.5, 20.5f, 22,trap_R_RegisterShader( "gfx/hud/armor_bottom.png" )); float *hudTintColor = colorTable[CT_WHITE]; //[/NewHud] //[LOLHUD] //LOLOL trap_R_SetColor( NULL ); menuDef_t* menuHUD = Menus_FindByName("lefthud"); if (menuHUD) { // Print frame itemDef_t* focusItem = Menu_FindItemByName(menuHUD, "armor_triangle"); if (focusItem) { trap_R_SetColor( hudTintColor ); CG_DrawPic( focusItem->window.rect.x, focusItem->window.rect.y, focusItem->window.rect.w, focusItem->window.rect.h, focusItem->window.background ); } } CG_FillRect(x+18.0f, y-18, BAR_W+7, BAR_H,color); //remaining armor //CG_DrawPic(x+1.0f, y+(BAR_H-percent), BAR_W-2.0f, BAR_H-(BAR_H-percent)-1.0f, cgs.media.boltShader/*trap_R_RegisterShader( "gfx/hud/health" )*/); } void CG_DrawDefenseLevel(void) { float x = DEFENSE_X; float y = BAR_Y; float percent = ((float)cg.snap->ps.stats[STAT_DODGE]/cg.snap->ps.stats[STAT_MAX_DODGE])*BAR_H; //remaining defense //CG_DrawPic(x+1.0f, y+(BAR_H-percent), BAR_W-2.0f, BAR_H-(BAR_H-percent)-1.0f, cgs.media.boltShader/*trap_R_RegisterShader( "gfx/hud/health" )*/); } void CG_DrawForceLevel(void) { float x = FORCE_X; float y = BAR_Y; float percent = ((float)cg.snap->ps.fd.forcePower/125)*BAR_H; //remaining force //CG_DrawPic(x+1.0f, y+(BAR_H-percent), BAR_W-2.0f, BAR_H-(BAR_H-percent)-1.0f, cgs.media.boltShader/*trap_R_RegisterShader( "gfx/hud/health" )*/); } void CG_DrawBalanceLevel(void) { float x = BALANCE_X; float y = BAR_Y; float percent = ((float)cg.snap->ps.saberAttackChainCount/MISHAPLEVEL_MAX)*BAR_H; //Com_Printf("%i/%i\n", cg.snap->ps.saberAttackChainCount, MISHAPLEVEL_MAX); //remaining balance //CG_DrawPic(x+1.0f, y+(BAR_H-percent), BAR_W-2.0f, BAR_H-(BAR_H-percent), cgs.media.boltShader/*trap_R_RegisterShader( "gfx/hud/health" )*/); } /* #define AMMO_X (136-20) void CG_DrawAmmoLevel(void) { float x = AMMO_X; float y = BAR_Y; int ammoindex = weaponData[cg_entities->currentState.weapon].ammoIndex; float percent = ((float)cg.snap->ps.ammo[weaponData[cg.snap->ps.weapon].ammoIndex]/ammoData[ammoindex].max)*BAR_H; if (cg.scoreBoardShowing || cg.snap->ps.weapon == WP_SABER) { return; } //border CG_DrawRect(x, y, BAR_W, BAR_H+1, 1.0f, meterBlack); //remaining ammo CG_FillRect(x+1.0f, y+(BAR_H-percent), BAR_W-2.0f, BAR_H-(BAR_H-percent), colorOrange); //missing ammo CG_FillRect(x+1.0f, y+1.0f, BAR_W-1.0f, BAR_H-percent, meterGrey); } */ //[/LOLHUD] //draw meter showing cloak fuel when it's not full #define CLFUELBAR_H 100.0f #define CLFUELBAR_W 20.0f #define CLFUELBAR_X (SCREEN_WIDTH-CLFUELBAR_W-8.0f) //[NewHud] //moved to prevent overlap with new hud. #define CLFUELBAR_Y 240.0f //#define CLFUELBAR_Y 260.0f //[/NewHud] void CG_DrawCloakFuel(void) { vec4_t aColor; vec4_t bColor; vec4_t cColor; float x = CLFUELBAR_X; float y = CLFUELBAR_Y; float percent = ((float)cg.snap->ps.cloakFuel/100.0f)*CLFUELBAR_H; if (percent > CLFUELBAR_H) { return; } if ( cg.snap->ps.jetpackFuel < JETPACK_MAXFUEL ) {//if drawing jetpack fuel bar too, then move this over...? x -= (JPFUELBAR_W+8.0f); } if (percent < 0.1f) { percent = 0.1f; } //color of the bar aColor[0] = 0.0f; aColor[1] = 0.0f; aColor[2] = 0.6f; aColor[3] = 0.8f; //color of the border bColor[0] = 0.0f; bColor[1] = 0.0f; bColor[2] = 0.0f; bColor[3] = 0.3f; //color of greyed out "missing fuel" cColor[0] = 0.1f; cColor[1] = 0.1f; cColor[2] = 0.3f; cColor[3] = 0.1f; //draw the background (black) CG_DrawRect(x, y, CLFUELBAR_W, CLFUELBAR_H, 1.0f, colorTable[CT_BLACK]); //now draw the part to show how much fuel there is in the color specified CG_FillRect(x+1.0f, y+1.0f+(CLFUELBAR_H-percent), CLFUELBAR_W-1.0f, CLFUELBAR_H-1.0f-(CLFUELBAR_H-percent), aColor); //then draw the other part greyed out CG_FillRect(x+1.0f, y+1.0f, CLFUELBAR_W-1.0f, CLFUELBAR_H-percent, cColor); } int cgRageTime = 0; int cgRageFadeTime = 0; float cgRageFadeVal = 0; int cgRageRecTime = 0; int cgRageRecFadeTime = 0; float cgRageRecFadeVal = 0; int cgAbsorbTime = 0; int cgAbsorbFadeTime = 0; float cgAbsorbFadeVal = 0; int cgProtectTime = 0; int cgProtectFadeTime = 0; float cgProtectFadeVal = 0; int cgYsalTime = 0; int cgYsalFadeTime = 0; float cgYsalFadeVal = 0; qboolean gCGHasFallVector = qfalse; vec3_t gCGFallVector; /* ================= CG_Draw2D ================= */ extern int cgSiegeRoundState; extern int cgSiegeRoundTime; extern int team1Timed; extern int team2Timed; int cg_beatingSiegeTime = 0; int cgSiegeRoundBeganTime = 0; int cgSiegeRoundCountTime = 0; static void CG_DrawSiegeTimer(int timeRemaining, qboolean isMyTeam) { //rwwFIXMEFIXME: Make someone make assets and use them. //this function is pretty much totally placeholder. // int x = 0; // int y = SCREEN_HEIGHT-160; int fColor = 0; int minutes = 0; int seconds = 0; char timeStr[1024]; menuDef_t *menuHUD = NULL; itemDef_t *item = NULL; menuHUD = Menus_FindByName("mp_timer"); if (!menuHUD) { return; } item = Menu_FindItemByName(menuHUD, "frame"); if (item) { trap_R_SetColor( item->window.foreColor ); CG_DrawPic( item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->window.background ); } seconds = timeRemaining; while (seconds >= 60) { minutes++; seconds -= 60; } strcpy(timeStr, va( "%i:%02i", minutes, seconds )); if (isMyTeam) { fColor = CT_HUD_RED; } else { fColor = CT_HUD_GREEN; } // trap_Cvar_Set("ui_siegeTimer", timeStr); // UI_DrawProportionalString( x+16, y+40, timeStr, // UI_SMALLFONT|UI_DROPSHADOW, colorTable[fColor] ); item = Menu_FindItemByName(menuHUD, "timer"); if (item) { UI_DrawProportionalString( item->window.rect.x, item->window.rect.y, timeStr, UI_SMALLFONT|UI_DROPSHADOW, colorTable[fColor] ); } } static void CG_DrawSiegeDeathTimer( int timeRemaining ) { int minutes = 0; int seconds = 0; char timeStr[1024]; menuDef_t *menuHUD = NULL; itemDef_t *item = NULL; menuHUD = Menus_FindByName("mp_timer"); if (!menuHUD) { return; } item = Menu_FindItemByName(menuHUD, "frame"); if (item) { trap_R_SetColor( item->window.foreColor ); CG_DrawPic( item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->window.background ); } seconds = timeRemaining; while (seconds >= 60) { minutes++; seconds -= 60; } if (seconds < 10) { strcpy(timeStr, va( "%i:0%i", minutes, seconds )); } else { strcpy(timeStr, va( "%i:%i", minutes, seconds )); } item = Menu_FindItemByName(menuHUD, "deathtimer"); if (item) { UI_DrawProportionalString( item->window.rect.x, item->window.rect.y, timeStr, UI_SMALLFONT|UI_DROPSHADOW, item->window.foreColor ); } } int cgSiegeEntityRender = 0; static void CG_DrawSiegeHUDItem(void) { void *g2; qhandle_t handle; vec3_t origin, angles; vec3_t mins, maxs; float len; centity_t *cent = &cg_entities[cgSiegeEntityRender]; if (cent->ghoul2) { g2 = cent->ghoul2; handle = 0; } else { handle = cgs.gameModels[cent->currentState.modelindex]; g2 = NULL; } if (handle) { trap_R_ModelBounds( handle, mins, maxs ); } else { VectorSet(mins, -16, -16, -20); VectorSet(maxs, 16, 16, 32); } origin[2] = -0.5 * ( mins[2] + maxs[2] ); origin[1] = 0.5 * ( mins[1] + maxs[1] ); len = 0.5 * ( maxs[2] - mins[2] ); origin[0] = len / 0.268; VectorClear(angles); angles[YAW] = cg.autoAngles[YAW]; CG_Draw3DModel( 8, 8, 64, 64, handle, g2, cent->currentState.g2radius, 0, origin, angles ); cgSiegeEntityRender = 0; //reset for next frame } /*==================================== chatbox functionality -rww ====================================*/ #define CHATBOX_CUTOFF_LEN 550 #define CHATBOX_FONT_HEIGHT 20 //utility func, insert a string into a string at the specified //place (assuming this will not overflow the buffer) void CG_ChatBox_StrInsert(char *buffer, int place, char *str) { int insLen = strlen(str); int i = strlen(buffer); int k = 0; buffer[i+insLen+1] = 0; //terminate the string at its new length while (i >= place) { buffer[i+insLen] = buffer[i]; i--; } i++; while (k < insLen) { buffer[i] = str[k]; i++; k++; } } //add chatbox string void CG_ChatBox_AddString(char *chatStr) { chatBoxItem_t *chat = &cg.chatItems[cg.chatItemActive]; float chatLen; if (cg_chatBox.integer<=0) { //don't bother then. return; } memset(chat, 0, sizeof(chatBoxItem_t)); if (strlen(chatStr) > sizeof(chat->string)) { //too long, terminate at proper len. chatStr[sizeof(chat->string)-1] = 0; } strcpy(chat->string, chatStr); chat->time = cg.time + cg_chatBox.integer; chat->lines = 1; chatLen = CG_Text_Width(chat->string, 1.0f, FONT_SMALL); if (chatLen > CHATBOX_CUTOFF_LEN) { //we have to break it into segments... int i = 0; int lastLinePt = 0; char s[2]; chatLen = 0; while (chat->string[i]) { s[0] = chat->string[i]; s[1] = 0; chatLen += CG_Text_Width(s, 0.65f, FONT_SMALL); if (chatLen >= CHATBOX_CUTOFF_LEN) { int j = i; while (j > 0 && j > lastLinePt) { if (chat->string[j] == ' ') { break; } j--; } if (chat->string[j] == ' ') { i = j; } chat->lines++; CG_ChatBox_StrInsert(chat->string, i, "\n"); i++; chatLen = 0; lastLinePt = i+1; } i++; } } cg.chatItemActive++; if (cg.chatItemActive >= MAX_CHATBOX_ITEMS) { cg.chatItemActive = 0; } } //insert item into array (rearranging the array if necessary) void CG_ChatBox_ArrayInsert(chatBoxItem_t **array, int insPoint, int maxNum, chatBoxItem_t *item) { if (array[insPoint]) { //recursively call, to move everything up to the top if (insPoint+1 >= maxNum) { CG_Error("CG_ChatBox_ArrayInsert: Exceeded array size"); } CG_ChatBox_ArrayInsert(array, insPoint+1, maxNum, array[insPoint]); } //now that we have moved anything that would be in this slot up, insert what we want into the slot array[insPoint] = item; } //go through all the chat strings and draw them if they are not yet expired static CGAME_INLINE void CG_ChatBox_DrawStrings(void) { chatBoxItem_t *drawThese[MAX_CHATBOX_ITEMS]; int numToDraw = 0; int linesToDraw = 0; int i = 0; int x = 30; int y = cg.scoreBoardShowing ? 475 : cg_chatBoxHeight.integer; float fontScale = 0.65f; if (!cg_chatBox.integer) { return; } memset(drawThese, 0, sizeof(drawThese)); while (i < MAX_CHATBOX_ITEMS) { if (cg.chatItems[i].time >= cg.time) { int check = numToDraw; int insertionPoint = numToDraw; while (check >= 0) { if (drawThese[check] && cg.chatItems[i].time < drawThese[check]->time) { //insert here insertionPoint = check; } check--; } CG_ChatBox_ArrayInsert(drawThese, insertionPoint, MAX_CHATBOX_ITEMS, &cg.chatItems[i]); numToDraw++; linesToDraw += cg.chatItems[i].lines; } i++; } if (!numToDraw) { //nothing, then, just get out of here now. return; } //move initial point up so we draw bottom-up (visually) y -= (CHATBOX_FONT_HEIGHT*fontScale)*linesToDraw; //we have the items we want to draw, just quickly loop through them now i = 0; while (i < numToDraw) { CG_Text_Paint(x, y, fontScale, colorWhite, drawThese[i]->string, 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_SMALL ); y += ((CHATBOX_FONT_HEIGHT*fontScale)*drawThese[i]->lines); i++; } } //[CoOp] void CGCam_DoFade(void); //[/CoOp] static void CG_Draw2DScreenTints( void ) { float rageTime, rageRecTime, absorbTime, protectTime, ysalTime; vec4_t hcolor; //[CoOp] //cutscene camera fade code CGCam_DoFade(); //[/CoOp] if (cgs.clientinfo[cg.snap->ps.clientNum].team != TEAM_SPECTATOR) { if (cg.snap->ps.fd.forcePowersActive & (1 << FP_RAGE)) { if (!cgRageTime) { cgRageTime = cg.time; } rageTime = (float)(cg.time - cgRageTime); rageTime /= 9000; if (rageTime < 0) { rageTime = 0; } if (rageTime > 0.15) { rageTime = 0.15; } hcolor[3] = rageTime; hcolor[0] = 0.7; hcolor[1] = 0; hcolor[2] = 0; if (!cg.renderingThirdPerson) { CG_DrawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH*SCREEN_HEIGHT, hcolor); } cgRageFadeTime = 0; cgRageFadeVal = 0; } else if (cgRageTime) { if (!cgRageFadeTime) { cgRageFadeTime = cg.time; cgRageFadeVal = 0.15; } rageTime = cgRageFadeVal; cgRageFadeVal -= (cg.time - cgRageFadeTime)*0.000005; if (rageTime < 0) { rageTime = 0; } if (rageTime > 0.15) { rageTime = 0.15; } if (cg.snap->ps.fd.forceRageRecoveryTime > cg.time) { float checkRageRecTime = rageTime; if (checkRageRecTime < 0.15) { checkRageRecTime = 0.15; } hcolor[3] = checkRageRecTime; hcolor[0] = rageTime*4; if (hcolor[0] < 0.2) { hcolor[0] = 0.2; } hcolor[1] = 0.2; hcolor[2] = 0.2; } else { hcolor[3] = rageTime; hcolor[0] = 0.7; hcolor[1] = 0; hcolor[2] = 0; } if (!cg.renderingThirdPerson && rageTime) { CG_DrawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH*SCREEN_HEIGHT, hcolor); } else { if (cg.snap->ps.fd.forceRageRecoveryTime > cg.time) { hcolor[3] = 0.15; hcolor[0] = 0.2; hcolor[1] = 0.2; hcolor[2] = 0.2; CG_DrawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH*SCREEN_HEIGHT, hcolor); } cgRageTime = 0; } } else if (cg.snap->ps.fd.forceRageRecoveryTime > cg.time) { if (!cgRageRecTime) { cgRageRecTime = cg.time; } rageRecTime = (float)(cg.time - cgRageRecTime); rageRecTime /= 9000; if (rageRecTime < 0.15)//0) { rageRecTime = 0.15;//0; } if (rageRecTime > 0.15) { rageRecTime = 0.15; } hcolor[3] = rageRecTime; hcolor[0] = 0.2; hcolor[1] = 0.2; hcolor[2] = 0.2; if (!cg.renderingThirdPerson) { CG_DrawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH*SCREEN_HEIGHT, hcolor); } cgRageRecFadeTime = 0; cgRageRecFadeVal = 0; } else if (cgRageRecTime) { if (!cgRageRecFadeTime) { cgRageRecFadeTime = cg.time; cgRageRecFadeVal = 0.15; } rageRecTime = cgRageRecFadeVal; cgRageRecFadeVal -= (cg.time - cgRageRecFadeTime)*0.000005; if (rageRecTime < 0) { rageRecTime = 0; } if (rageRecTime > 0.15) { rageRecTime = 0.15; } hcolor[3] = rageRecTime; hcolor[0] = 0.2; hcolor[1] = 0.2; hcolor[2] = 0.2; if (!cg.renderingThirdPerson && rageRecTime) { CG_DrawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH*SCREEN_HEIGHT, hcolor); } else { cgRageRecTime = 0; } } if (cg.snap->ps.fd.forcePowersActive & (1 << FP_ABSORB)) { if (!cgAbsorbTime) { cgAbsorbTime = cg.time; } absorbTime = (float)(cg.time - cgAbsorbTime); absorbTime /= 9000; if (absorbTime < 0) { absorbTime = 0; } if (absorbTime > 0.15) { absorbTime = 0.15; } hcolor[3] = absorbTime/2; hcolor[0] = 0; hcolor[1] = 0; hcolor[2] = 0.7; if (!cg.renderingThirdPerson) { CG_DrawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH*SCREEN_HEIGHT, hcolor); } cgAbsorbFadeTime = 0; cgAbsorbFadeVal = 0; } else if (cgAbsorbTime) { if (!cgAbsorbFadeTime) { cgAbsorbFadeTime = cg.time; cgAbsorbFadeVal = 0.15; } absorbTime = cgAbsorbFadeVal; cgAbsorbFadeVal -= (cg.time - cgAbsorbFadeTime)*0.000005; if (absorbTime < 0) { absorbTime = 0; } if (absorbTime > 0.15) { absorbTime = 0.15; } hcolor[3] = absorbTime/2; hcolor[0] = 0; hcolor[1] = 0; hcolor[2] = 0.7; if (!cg.renderingThirdPerson && absorbTime) { CG_DrawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH*SCREEN_HEIGHT, hcolor); } else { cgAbsorbTime = 0; } } if (cg.snap->ps.fd.forcePowersActive & (1 << FP_MANIPULATE)) { if (!cgProtectTime) { cgProtectTime = cg.time; } protectTime = (float)(cg.time - cgProtectTime); protectTime /= 9000; if (protectTime < 0) { protectTime = 0; } if (protectTime > 0.15) { protectTime = 0.15; } hcolor[3] = protectTime/2; hcolor[0] = 0; hcolor[1] = 0.7; hcolor[2] = 0; if (!cg.renderingThirdPerson) { CG_DrawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH*SCREEN_HEIGHT, hcolor); } cgProtectFadeTime = 0; cgProtectFadeVal = 0; } else if (cgProtectTime) { if (!cgProtectFadeTime) { cgProtectFadeTime = cg.time; cgProtectFadeVal = 0.15; } protectTime = cgProtectFadeVal; cgProtectFadeVal -= (cg.time - cgProtectFadeTime)*0.000005; if (protectTime < 0) { protectTime = 0; } if (protectTime > 0.15) { protectTime = 0.15; } hcolor[3] = protectTime/2; hcolor[0] = 0; hcolor[1] = 0.7; hcolor[2] = 0; if (!cg.renderingThirdPerson && protectTime) { CG_DrawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH*SCREEN_HEIGHT, hcolor); } else { cgProtectTime = 0; } } if (cg.snap->ps.rocketLockIndex != ENTITYNUM_NONE && (cg.time - cg.snap->ps.rocketLockTime) > 0) { CG_DrawRocketLocking( cg.snap->ps.rocketLockIndex, cg.snap->ps.rocketLockTime ); } if (BG_HasYsalamiri(cgs.gametype, &cg.snap->ps)) { if (!cgYsalTime) { cgYsalTime = cg.time; } ysalTime = (float)(cg.time - cgYsalTime); ysalTime /= 9000; if (ysalTime < 0) { ysalTime = 0; } if (ysalTime > 0.15) { ysalTime = 0.15; } hcolor[3] = ysalTime/2; hcolor[0] = 0.7; hcolor[1] = 0.7; hcolor[2] = 0; if (!cg.renderingThirdPerson) { CG_DrawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH*SCREEN_HEIGHT, hcolor); } cgYsalFadeTime = 0; cgYsalFadeVal = 0; } else if (cgYsalTime) { if (!cgYsalFadeTime) { cgYsalFadeTime = cg.time; cgYsalFadeVal = 0.15; } ysalTime = cgYsalFadeVal; cgYsalFadeVal -= (cg.time - cgYsalFadeTime)*0.000005; if (ysalTime < 0) { ysalTime = 0; } if (ysalTime > 0.15) { ysalTime = 0.15; } hcolor[3] = ysalTime/2; hcolor[0] = 0.7; hcolor[1] = 0.7; hcolor[2] = 0; if (!cg.renderingThirdPerson && ysalTime) { CG_DrawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH*SCREEN_HEIGHT, hcolor); } else { cgYsalTime = 0; } } } if ( (cg.refdef.viewContents&CONTENTS_LAVA) ) {//tint screen red float phase = cg.time / 1000.0 * WAVE_FREQUENCY * M_PI * 2; hcolor[3] = 0.5 + (0.15f*sin( phase )); hcolor[0] = 0.7f; hcolor[1] = 0; hcolor[2] = 0; CG_DrawRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH*SCREEN_HEIGHT, hcolor ); } else if ( (cg.refdef.viewContents&CONTENTS_SLIME) ) {//tint screen green float phase = cg.time / 1000.0 * WAVE_FREQUENCY * M_PI * 2; hcolor[3] = 0.4 + (0.1f*sin( phase )); hcolor[0] = 0; hcolor[1] = 0.7f; hcolor[2] = 0; CG_DrawRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH*SCREEN_HEIGHT, hcolor ); } else if ( (cg.refdef.viewContents&CONTENTS_WATER) ) {//tint screen light blue -- FIXME: don't do this if CONTENTS_FOG? (in case someone *does* make a water shader with fog in it?) float phase = cg.time / 1000.0 * WAVE_FREQUENCY * M_PI * 2; hcolor[3] = 0.3 + (0.05f*sin( phase )); hcolor[0] = 0; hcolor[1] = 0.2f; hcolor[2] = 0.8; CG_DrawRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH*SCREEN_HEIGHT, hcolor ); } } static void CG_Draw2D( void ) { float inTime = cg.invenSelectTime+WEAPON_SELECT_TIME; float wpTime = cg.weaponSelectTime+WEAPON_SELECT_TIME; float fallTime; float bestTime; int drawSelect = 0; // if we are taking a levelshot for the menu, don't draw anything if ( cg.levelShot ) { return; } if (cgs.clientinfo[cg.snap->ps.clientNum].team == TEAM_SPECTATOR) { cgRageTime = 0; cgRageFadeTime = 0; cgRageFadeVal = 0; cgRageRecTime = 0; cgRageRecFadeTime = 0; cgRageRecFadeVal = 0; cgAbsorbTime = 0; cgAbsorbFadeTime = 0; cgAbsorbFadeVal = 0; cgProtectTime = 0; cgProtectFadeTime = 0; cgProtectFadeVal = 0; cgYsalTime = 0; cgYsalFadeTime = 0; cgYsalFadeVal = 0; } if ( cg_draw2D.integer == 0 ) { return; } if ( cg.snap->ps.pm_type == PM_INTERMISSION ) { CG_DrawIntermission(); CG_ChatBox_DrawStrings(); return; } CG_Draw2DScreenTints(); if (cg.snap->ps.rocketLockIndex != ENTITYNUM_NONE && (cg.time - cg.snap->ps.rocketLockTime) > 0) { CG_DrawRocketLocking( cg.snap->ps.rocketLockIndex, cg.snap->ps.rocketLockTime ); } if (cg.snap->ps.holocronBits) { CG_DrawHolocronIcons(); } if (cg.snap->ps.fd.forcePowersActive || cg.snap->ps.fd.forceRageRecoveryTime > cg.time) { CG_DrawActivePowers(); } if (cg.snap->ps.jetpackFuel < JETPACK_MAXFUEL) { //draw it as long as it isn't full CG_DrawJetpackFuel(); } if (cg.snap->ps.cloakFuel < 100) { //draw it as long as it isn't full CG_DrawCloakFuel(); } if (cg.predictedPlayerState.emplacedIndex > 0) { centity_t *eweb = &cg_entities[cg.predictedPlayerState.emplacedIndex]; if (eweb->currentState.weapon == WP_NONE) { //using an e-web, draw its health CG_DrawEWebHealth(); } } //[LOLHUD] if (!cg.scoreBoardShowing) { //left CG_DrawHealthLevel(); CG_DrawArmorLevel(); //CG_DrawAmmoLevel(); //right CG_DrawDefenseLevel(); CG_DrawForceLevel(); CG_DrawBalanceLevel(); } //[/LOLHUD] // Draw this before the text so that any text won't get clipped off CG_DrawZoomMask(); if ( cg.snap->ps.persistant[PERS_TEAM] == TEAM_SPECTATOR ) { CG_DrawSpectator(); CG_DrawCrosshair(NULL, 0); CG_DrawCrosshairNames(); CG_SaberClashFlare(); } else { // don't draw any status if dead or the scoreboard is being explicitly shown if ( !cg.showScores && cg.snap->ps.stats[STAT_HEALTH] > 0 ) { if ( 0 ) { //Reenable if stats are drawn with menu system again Menu_PaintAll(); CG_DrawTimedMenus(); } //CG_DrawTemporaryStats(); CG_DrawCrosshairNames(); if (cg_drawStatus.integer) { CG_DrawIconBackground(); } if (inTime > wpTime) { drawSelect = 1; bestTime = cg.invenSelectTime; } else //only draw the most recent since they're drawn in the same place { drawSelect = 2; bestTime = cg.weaponSelectTime; } if (cg.forceSelectTime > bestTime) { drawSelect = 3; } switch(drawSelect) { case 1: CG_DrawInvenSelect(); break; case 2: CG_DrawWeaponSelect(); break; case 3: CG_DrawForceSelect(); break; default: break; } if (cg_drawStatus.integer) { //Powerups now done with upperright stuff //CG_DrawPowerupIcons(); CG_DrawFlagStatus(); } CG_SaberClashFlare(); if (cg_drawStatus.integer) { CG_DrawStats(); } CG_DrawPickupItem(); //Do we want to use this system again at some point? //CG_DrawReward(); } } if (cg.snap->ps.fallingToDeath) { vec4_t hcolor; fallTime = (float)(cg.time - cg.snap->ps.fallingToDeath); fallTime /= (FALL_FADE_TIME/2); if (fallTime < 0) { fallTime = 0; } if (fallTime > 1) { fallTime = 1; } hcolor[3] = fallTime; hcolor[0] = 0; hcolor[1] = 0; hcolor[2] = 0; CG_DrawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH*SCREEN_HEIGHT, hcolor); if (!gCGHasFallVector) { VectorCopy(cg.snap->ps.origin, gCGFallVector); gCGHasFallVector = qtrue; } } else { if (gCGHasFallVector) { gCGHasFallVector = qfalse; VectorClear(gCGFallVector); } } CG_DrawVote(); CG_DrawTeamVote(); CG_DrawLagometer(); if (!cg_paused.integer) { CG_DrawBracketedEntities(); CG_DrawUpperRight(); } if ( !CG_DrawFollow() ) { CG_DrawWarmup(); } if (cgSiegeRoundState) { char pStr[1024]; int rTime = 0; //cgSiegeRoundBeganTime = 0; switch (cgSiegeRoundState) { case 1: CG_CenterPrint(CG_GetStringEdString("MP_INGAME", "WAITING_FOR_PLAYERS"), SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH); break; case 2: rTime = (SIEGE_ROUND_BEGIN_TIME - (cg.time - cgSiegeRoundTime)); if (rTime < 0) { rTime = 0; } if (rTime > SIEGE_ROUND_BEGIN_TIME) { rTime = SIEGE_ROUND_BEGIN_TIME; } rTime /= 1000; rTime += 1; if (rTime < 1) { rTime = 1; } if (rTime <= 3 && rTime != cgSiegeRoundCountTime) { cgSiegeRoundCountTime = rTime; switch (rTime) { case 1: trap_S_StartLocalSound( cgs.media.count1Sound, CHAN_ANNOUNCER ); break; case 2: trap_S_StartLocalSound( cgs.media.count2Sound, CHAN_ANNOUNCER ); break; case 3: trap_S_StartLocalSound( cgs.media.count3Sound, CHAN_ANNOUNCER ); break; default: break; } } strcpy(pStr, va("%s %i...", CG_GetStringEdString("MP_INGAME", "ROUNDBEGINSIN"), rTime)); CG_CenterPrint(pStr, SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH); //same break; default: break; } cgSiegeEntityRender = 0; } else if (cgSiegeRoundTime) { CG_CenterPrint("", SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH); cgSiegeRoundTime = 0; //cgSiegeRoundBeganTime = cg.time; cgSiegeEntityRender = 0; } else if (cgSiegeRoundBeganTime) { //Draw how much time is left in the round based on local info. int timedTeam = TEAM_FREE; int timedValue = 0; if (cgSiegeEntityRender) { //render the objective item model since this client has it CG_DrawSiegeHUDItem(); } if (team1Timed) { timedTeam = TEAM_RED; //team 1 if (cg_beatingSiegeTime) { timedValue = cg_beatingSiegeTime; } else { timedValue = team1Timed; } } else if (team2Timed) { timedTeam = TEAM_BLUE; //team 2 if (cg_beatingSiegeTime) { timedValue = cg_beatingSiegeTime; } else { timedValue = team2Timed; } } if (timedTeam != TEAM_FREE) { //one of the teams has a timer int timeRemaining; qboolean isMyTeam = qfalse; if (cgs.siegeTeamSwitch && !cg_beatingSiegeTime) { //in switchy mode but not beating a time, so count up. timeRemaining = (cg.time-cgSiegeRoundBeganTime); if (timeRemaining < 0) { timeRemaining = 0; } } else { timeRemaining = (((cgSiegeRoundBeganTime)+timedValue) - cg.time); } if (timeRemaining > timedValue) { timeRemaining = timedValue; } else if (timeRemaining < 0) { timeRemaining = 0; } if (timeRemaining) { timeRemaining /= 1000; } if (cg.predictedPlayerState.persistant[PERS_TEAM] == timedTeam) { //the team that's timed is the one this client is on isMyTeam = qtrue; } CG_DrawSiegeTimer(timeRemaining, isMyTeam); } } else { cgSiegeEntityRender = 0; } if ( cg_siegeDeathTime ) { int timeRemaining = ( cg_siegeDeathTime - cg.time ); if ( timeRemaining < 0 ) { timeRemaining = 0; cg_siegeDeathTime = 0; } if ( timeRemaining ) { timeRemaining /= 1000; } CG_DrawSiegeDeathTimer( timeRemaining ); } // don't draw center string if scoreboard is up cg.scoreBoardShowing = CG_DrawScoreboard(); if ( !cg.scoreBoardShowing) { CG_DrawCenterString(); } // always draw chat CG_ChatBox_DrawStrings(); } static void CG_DrawTourneyScoreboard() { } /* ===================== CG_DrawActive Perform all drawing needed to completely fill the screen ===================== */ void CG_DrawActive( stereoFrame_t stereoView ) { float separation; vec3_t baseOrg; // optionally draw the info screen instead if ( !cg.snap ) { CG_DrawInformation(); return; } // optionally draw the tournement scoreboard instead if ( cg.snap->ps.persistant[PERS_TEAM] == TEAM_SPECTATOR && ( cg.snap->ps.pm_flags & PMF_SCOREBOARD ) ) { CG_DrawTourneyScoreboard(); return; } switch ( stereoView ) { case STEREO_CENTER: separation = 0; break; case STEREO_LEFT: separation = -cg_stereoSeparation.value / 2; break; case STEREO_RIGHT: separation = cg_stereoSeparation.value / 2; break; default: separation = 0; CG_Error( "CG_DrawActive: Undefined stereoView" ); } // clear around the rendered view if sized down CG_TileClear(); // offset vieworg appropriately if we're doing stereo separation VectorCopy( cg.refdef.vieworg, baseOrg ); if ( separation != 0 ) { VectorMA( cg.refdef.vieworg, -separation, cg.refdef.viewaxis[1], cg.refdef.vieworg ); } cg.refdef.rdflags |= RDF_DRAWSKYBOX; // draw 3D view trap_R_RenderScene( &cg.refdef ); // restore original viewpoint if running stereo if ( separation != 0 ) { VectorCopy( baseOrg, cg.refdef.vieworg ); } // draw status bar and other floating elements CG_Draw2D(); }
[ "[email protected]@5776d9f2-9662-11de-ad41-3fcdc5e0e42d" ]
[ [ [ 1, 8658 ] ] ]
f0bb5f73e8d0723ab69357f60b50fafe241362c6
50f94444677eb6363f2965bc2a29c09f8da7e20d
/Src/EmptyProject/TopStateManager.h
af1a9298ac07a0a3b48d90e1b68fa156fa28f250
[]
no_license
gasbank/poolg
efd426db847150536eaa176d17dcddcf35e74e5d
e73221494c4a9fd29c3d75fb823c6fb1983d30e5
refs/heads/master
2020-04-10T11:56:52.033568
2010-11-04T19:31:00
2010-11-04T19:31:00
1,051,621
1
0
null
null
null
null
UTF-8
C++
false
false
696
h
#pragma once #include "StateManager.h" class World; /** @brief 게임 내 최상위 레벨의 상태를 관리하는 클래스 */ class TopStateManager : public StateManager, public Singleton<TopStateManager> { public: TopStateManager(void); ~TopStateManager(void); virtual void init(); virtual HRESULT onCreateDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); HRESULT onResetDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); void onLostDevice(); }; inline TopStateManager& GetTopStateManager() { return TopStateManager::getSingleton(); }
[ [ [ 1, 1 ], [ 4, 8 ], [ 15, 22 ], [ 24, 24 ] ], [ [ 2, 3 ], [ 9, 14 ], [ 23, 23 ] ] ]
4e11ec670c7f35e4df81d3f4858ce5d7960f3b30
44d23a0a9240c3a622d36aab3106b1ce7db0736f
/ClassWizard/VFC_Core/page_wtl_font.h
b4eb445eed7b523dac00e9a38658396c8b84f8f1
[]
no_license
skyformat99/visualfc
238a8e479c98b861392ab4e61bc8e49bb61c9a04
a4e91fc45f33acbc06029b6a45d3d498116931b6
refs/heads/master
2021-07-20T03:43:23.819252
2009-05-18T05:29:32
2009-05-18T05:29:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,593
h
#ifndef _PAGE_WTL_FONT_H_ #define _PAGE_WTL_FONT_H_ struct page_wtl_font_peer : page_font_peer { virtual init_tag(tag_token & tag) { tag.kind = tkMapping; tag.bext = true; tag.add_body(_T("DLGFONT_DIALOG")); tag.add_body(_T("DLGFONT_DIALOG_EX")); tag.add_body(_T("DLGFONT_CONTROL")); tag.add_body(_T("DLGFONT_CONTROL_EX")); tag.add_head(_T("BEGIN_DLGFONT_MAP")); tag.tag.begin = _T("BEGIN_DLGFONT_MAP($CLS)"); tag.tag.end = _T("END_DLGFONT_MAP()"); } virtual Token * add_font_dlg(codeparser * pcode, Token * tkcls, ResControl * ctrl, bool bdlg) { HFONT hf = AtlGetDefaultGuiFont(); CLogFont lf(hf); CFontDialog dlg(&lf); if (dlg.DoModal() == IDOK) { CString font; font.Format(_T("%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,_T(\"%s\")"), lf.lfHeight, lf.lfWidth, lf.lfEscapement, lf.lfOrientation, lf.lfWeight, lf.lfItalic, lf.lfUnderline, lf.lfStrikeOut, lf.lfCharSet, lf.lfOutPrecision, lf.lfClipPrecision, lf.lfQuality, lf.lfPitchAndFamily, lf.lfFaceName); Token * tk = NULL; if (bdlg) { tk = pcode->AddTokenArgs2(tkcls,_T("DLGFONT_DIALOG_EX"),font,_T("")); } else { tk = pcode->AddTokenArgs2(tkcls,_T("DLGFONT_CONTROL_EX"),ctrl->m_ID,font); } return tk; } return NULL; } }; class page_wtl_font : public page_font_template { public: page_wtl_font() { m_peer = new page_wtl_font_peer(); m_peer->init_tag(m_tag); } const char * page_name() { return _T("WTL Font"); } }; #endif
[ "visualfc@5ba4977a-b047-0410-9b11-9d7bf4ba98c9" ]
[ [ [ 1, 71 ] ] ]
b96aab8bf2415b4d03e4dc9b7a1b0627ba9777bf
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/test/utils/callback.hpp
5c9b605135b770b624fc625fc5205854e310b423
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
10,843
hpp
// (C) Copyright Gennadiy Rozental 2005. // 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/test for the library home page. // // File : $RCSfile: callback.hpp,v $ // // Version : $Revision: 1.7 $ // // Description : // *************************************************************************** #ifndef BOOST_TEST_CALLBACK_020505GER #define BOOST_TEST_CALLBACK_020505GER // Boost #include <boost/config.hpp> #include <boost/detail/workaround.hpp> #include <boost/shared_ptr.hpp> #include <boost/test/detail/suppress_warnings.hpp> #if BOOST_WORKAROUND(BOOST_MSVC, < 1300) || BOOST_WORKAROUND(BOOST_INTEL, <= 700) # define BOOST_CALLBACK_EXPLICIT_COPY_CONSTRUCTOR #endif //____________________________________________________________________________// namespace boost { namespace unit_test { namespace ut_detail { struct unused {}; template<typename R> struct invoker { template<typename Functor> R invoke( Functor& f ) { return f(); } template<typename Functor, typename T1> R invoke( Functor& f, T1 t1 ) { return f( t1 ); } template<typename Functor, typename T1, typename T2> R invoke( Functor& f, T1 t1, T2 t2 ) { return f( t1, t2 ); } template<typename Functor, typename T1, typename T2, typename T3> R invoke( Functor& f, T1 t1, T2 t2, T3 t3 ) { return f( t1, t2, t3 ); } }; //____________________________________________________________________________// template<> struct invoker<unused> { template<typename Functor> unused invoke( Functor& f ) { f(); return unused(); } template<typename Functor, typename T1> unused invoke( Functor& f, T1 t1 ) { f( t1 ); return unused(); } template<typename Functor, typename T1, typename T2> unused invoke( Functor& f, T1 t1, T2 t2 ) { f( t1, t2 ); return unused(); } template<typename Functor, typename T1, typename T2, typename T3> unused invoke( Functor& f, T1 t1, T2 t2, T3 t3 ) { f( t1, t2, t3 ); return unused(); } }; //____________________________________________________________________________// } // namespace ut_detail // ************************************************************************** // // ************** unit_test::callback0 ************** // // ************************************************************************** // namespace ut_detail { template<typename R> struct callback0_impl { virtual ~callback0_impl() {} virtual R invoke() = 0; }; //____________________________________________________________________________// template<typename R, typename Functor> struct callback0_impl_t : callback0_impl<R> { // Constructor explicit callback0_impl_t( Functor f ) : m_f( f ) {} virtual R invoke() { return invoker<R>().invoke( m_f ); } private: // Data members Functor m_f; }; //____________________________________________________________________________// } // namespace ut_detail template<typename R = ut_detail::unused> class callback0 { public: // Constructors callback0() {} #ifdef BOOST_CALLBACK_EXPLICIT_COPY_CONSTRUCTOR callback0( callback0 const& rhs ) : m_impl( rhs.m_impl ) {} #endif template<typename Functor> callback0( Functor f ) : m_impl( new ut_detail::callback0_impl_t<R,Functor>( f ) ) {} void operator=( callback0 const& rhs ) { m_impl = rhs.m_impl; } template<typename Functor> void operator=( Functor f ) { m_impl.reset( new ut_detail::callback0_impl_t<R,Functor>( f ) ); } R operator()() const { return m_impl->invoke(); } bool operator!() const { return !m_impl; } private: // Data members boost::shared_ptr<ut_detail::callback0_impl<R> > m_impl; }; // ************************************************************************** // // ************** unit_test::callback1 ************** // // ************************************************************************** // namespace ut_detail { template<typename R, typename T1> struct callback1_impl { virtual ~callback1_impl() {} virtual R invoke( T1 t1 ) = 0; }; //____________________________________________________________________________// template<typename R, typename T1,typename Functor> struct callback1_impl_t : callback1_impl<R,T1> { // Constructor explicit callback1_impl_t( Functor f ) : m_f( f ) {} virtual R invoke( T1 t1 ) { return invoker<R>().invoke( m_f, t1 ); } private: // Data members Functor m_f; }; //____________________________________________________________________________// } // namespace ut_detail template<typename T1,typename R = ut_detail::unused> class callback1 { public: // Constructors callback1() {} #ifdef BOOST_CALLBACK_EXPLICIT_COPY_CONSTRUCTOR callback1( callback1 const& rhs ) : m_impl( rhs.m_impl ) {} #endif template<typename Functor> callback1( Functor f ) : m_impl( new ut_detail::callback1_impl_t<R,T1,Functor>( f ) ) {} void operator=( callback1 const& rhs ) { m_impl = rhs.m_impl; } template<typename Functor> void operator=( Functor f ) { m_impl.reset( new ut_detail::callback1_impl_t<R,T1,Functor>( f ) ); } R operator()( T1 t1 ) const { return m_impl->invoke( t1 ); } bool operator!() const { return !m_impl; } private: // Data members boost::shared_ptr<ut_detail::callback1_impl<R,T1> > m_impl; }; // ************************************************************************** // // ************** unit_test::callback2 ************** // // ************************************************************************** // namespace ut_detail { template<typename R, typename T1,typename T2> struct callback2_impl { virtual ~callback2_impl() {} virtual R invoke( T1 t1, T2 t2 ) = 0; }; //____________________________________________________________________________// template<typename R, typename T1, typename T2, typename Functor> struct callback2_impl_t : callback2_impl<R,T1,T2> { // Constructor explicit callback2_impl_t( Functor f ) : m_f( f ) {} virtual R invoke( T1 t1, T2 t2 ) { return invoker<R>().template invoke<Functor,T1,T2>( m_f, t1, t2 ); } private: // Data members Functor m_f; }; //____________________________________________________________________________// } // namespace ut_detail template<typename T1,typename T2, typename R = ut_detail::unused> class callback2 { public: // Constructors callback2() {} #ifdef BOOST_CALLBACK_EXPLICIT_COPY_CONSTRUCTOR callback2( callback2 const& rhs ) : m_impl( rhs.m_impl ) {} #endif template<typename Functor> callback2( Functor f ) : m_impl( new ut_detail::callback2_impl_t<R,T1,T2,Functor>( f ) ) {} void operator=( callback2 const& rhs ) { m_impl = rhs.m_impl; } template<typename Functor> void operator=( Functor f ) { m_impl.reset( new ut_detail::callback2_impl_t<R,T1,T2,Functor>( f ) ); } R operator()( T1 t1, T2 t2 ) const { return m_impl->invoke( t1, t2 ); } bool operator!() const { return !m_impl; } private: // Data members boost::shared_ptr<ut_detail::callback2_impl<R,T1,T2> > m_impl; }; // ************************************************************************** // // ************** unit_test::callback3 ************** // // ************************************************************************** // namespace ut_detail { template<typename R, typename T1, typename T2, typename T3> struct callback3_impl { virtual ~callback3_impl() {} virtual R invoke( T1 t1, T2 t2, T3 t3 ) = 0; }; //____________________________________________________________________________// template<typename R, typename T1, typename T2, typename T3, typename Functor> struct callback3_impl_t : callback3_impl<R,T1,T2,T3> { // Constructor explicit callback3_impl_t( Functor f ) : m_f( f ) {} virtual R invoke( T1 t1, T2 t2, T3 t3 ) { return invoker<R>().invoke( m_f, t1, t2, t3 ); } private: // Data members Functor m_f; }; //____________________________________________________________________________// } // namespace ut_detail template<typename T1,typename T2, typename T3, typename R = ut_detail::unused> class callback3 { public: // Constructors callback3() {} #ifdef BOOST_CALLBACK_EXPLICIT_COPY_CONSTRUCTOR callback3( callback3 const& rhs ) : m_impl( rhs.m_impl ) {} #endif template<typename Functor> callback3( Functor f ) : m_impl( new ut_detail::callback3_impl_t<R,T1,T2,T3,Functor>( f ) ) {} void operator=( callback3 const& rhs ) { m_impl = rhs.m_impl; } template<typename Functor> void operator=( Functor f ) { m_impl.reset( new ut_detail::callback3_impl_t<R,T1,T2,T3,Functor>( f ) ); } R operator()( T1 t1, T2 t2, T3 t3 ) const { return m_impl->invoke( t1, t2, t3 ); } bool operator!() const { return !m_impl; } private: // Data members boost::shared_ptr<ut_detail::callback3_impl<R,T1,T2,T3> > m_impl; }; } // namespace unit_test } // namespace boost #undef BOOST_CALLBACK_EXPLICIT_COPY_CONSTRUCTOR //____________________________________________________________________________// #include <boost/test/detail/enable_warnings.hpp> // ************************************************************************** // // Revision History: // // $Log: callback.hpp,v $ // Revision 1.7 2006/02/21 04:27:16 rogeeff // rev back // // Revision 1.6 2006/01/28 08:57:03 rogeeff // VC6.0 workaround removed // // Revision 1.5 2005/04/13 05:09:00 rogeeff // Intel 7.1 bug fix // // Revision 1.4 2005/04/12 06:50:06 rogeeff // suppress warnings // // Revision 1.3 2005/03/22 07:05:18 rogeeff // minor vc7.1 workaround // // Revision 1.2 2005/02/24 19:28:17 turkanis // removed redundant copy ctors, except for VC6 // // Revision 1.1 2005/02/20 08:27:08 rogeeff // This a major update for Boost.Test framework. See release docs for complete list of fixes/updates // // ************************************************************************** // #endif // BOOST_TEST_CALLBACK_020505GER
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 337 ] ] ]
caba940923c00a9623392c5ac2ca6540ec9ca6d1
49b6646167284329aa8644c8cf01abc3d92338bd
/SEP2_M6/Controller/StartThread.h
62c8e3276de4a4077ccd7b135c0ccc1c32fa7ec2
[]
no_license
StiggyB/javacodecollection
9d017b87b68f8d46e09dcf64650bd7034c442533
bdce3ddb7a56265b4df2202d24bf86a06ecfee2e
refs/heads/master
2020-08-08T22:45:47.779049
2011-10-24T12:10:08
2011-10-24T12:10:08
32,143,796
0
0
null
null
null
null
UTF-8
C++
false
false
2,617
h
#ifndef STARTTHREAD_H_ #define STARTTHREAD_H_ #include <stdlib.h> #include "Sensor.h" #include "InterruptController.h" #include "CommunicationServer.h" #include "../HAL/HALCore.h" #include "../HAL/Lampen.h" #include "../Timer/Timer.h" #include "../Tests/test.h" #include "../Tests/Test_M1.h" #include "../Tests/Test_HAL.h" #include "../Tests/Test_IRQ.h" #include "../Tests/Test_Serial.h" #include "../Tests/Test_Lights.h" #include "../Tests/Test_Functor.h" #include "../Tests/Test_Timer.h" /** * Functor Pattern. * * SE2 (+ SY and PL) Project SoSe 2011 * * Authors: Rico Flaegel, * Tell Mueller-Pettenpohl, * Torsten Krane, * Jan Quenzel * * This class starts all threads for the normal running. * Various defines include and start different tests. * */ class StartThread : public thread::HAWThread { public: StartThread(); virtual ~StartThread(); /** * This function deletes and stops some threads. */ void stopProcess(); protected: virtual void execute(void*); virtual void shutdown(); private: /** * pointer to the HAL */ HALCore *halCore; /** * pointer to the InterruptController */ InterruptController *interruptController; /** * pointer to the CommunicationServer */ CommunicationServer *communicationServer; /** * pointer to the lights */ Lampen * lampen; /** * pointer to the serial controller */ Serial * serial; /** * pointer to the sensor controller */ Sensor * sensor; /** * pointer to the timer instance */ Timer* timer; #ifdef TEST_M1 /** * Instance from the Test_M1 */ Test_M1 tm; #endif #ifdef TEST_HAL /** * Instance from the Test_HAL */ Test_HAL th; #endif #ifdef TEST_IRQ /** * Instance from the Test_IRQ */ Test_IRQ ti; #endif #ifdef TEST_SER /** * Instance from the Test_Serial */ Test_Serial ser; #endif #ifdef TEST_LIGHT /** * Instance from the timer instance */ Test_Lights tl; #endif #ifdef TEST_SEN /** * Instance from the Test_Sensor */ Test_Sensor ts; #endif #ifdef TEST_FSM /** * Instance from the Test_FSM */ Test_FSM tests_fsm; #endif #ifdef TEST_FUN /** * Instance from the Test_Functor */ Test_Functor tf; #endif #ifdef TEST_TIMER /** * Instance from the Test_Timer */ Test_Timer timer_test; #endif }; #endif /* STARTTHREAD_H_ */
[ "[email protected]@72d44fe2-11f0-84eb-49d3-ba3949d4c1b1", "[email protected]@72d44fe2-11f0-84eb-49d3-ba3949d4c1b1" ]
[ [ [ 1, 20 ], [ 36, 39 ], [ 43, 61 ], [ 63, 77 ], [ 81, 83 ], [ 87, 89 ], [ 93, 95 ], [ 99, 101 ], [ 105, 107 ], [ 111, 113 ], [ 117, 119 ], [ 123, 125 ], [ 129, 134 ] ], [ [ 21, 35 ], [ 40, 42 ], [ 62, 62 ], [ 78, 80 ], [ 84, 86 ], [ 90, 92 ], [ 96, 98 ], [ 102, 104 ], [ 108, 110 ], [ 114, 116 ], [ 120, 122 ], [ 126, 128 ] ] ]
da0cc75f93a87c6f3baedff520571a8d4ed253cc
801e9a21fbe0f68c18857334f9b86694938f5055
/Desktop-Windows/moc_GUIDesktop.cpp
017ab0f01de026dcee17731892b9a9a6360704f9
[]
no_license
vialrogo/pbx-viewer
d324cbec618fdbaee78f79a8466ebf64c54ffa34
b814668c46a2d0f85bffcfed0d06dd8e96a082b8
refs/heads/master
2016-09-05T11:57:26.787183
2010-09-16T16:34:49
2010-09-16T16:34:49
32,185,339
0
1
null
null
null
null
UTF-8
C++
false
false
4,095
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'GUIDesktop.h' ** ** Created: Fri 27. Aug 00:00:45 2010 ** by: The Qt Meta Object Compiler version 62 (Qt 4.6.3) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "GUIDesktop.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'GUIDesktop.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 62 #error "This file was generated using the moc from 4.6.3. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_GUIDesktop[] = { // content: 4, // revision 0, // classname 0, 0, // classinfo 18, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: signature, parameters, type, tag, flags 12, 11, 11, 11, 0x08, 27, 11, 11, 11, 0x08, 42, 11, 11, 11, 0x08, 57, 11, 11, 11, 0x08, 73, 11, 11, 11, 0x08, 91, 11, 11, 11, 0x08, 102, 11, 11, 11, 0x08, 110, 11, 11, 11, 0x08, 126, 11, 11, 11, 0x08, 147, 11, 11, 11, 0x08, 163, 11, 11, 11, 0x08, 180, 11, 11, 11, 0x08, 194, 11, 11, 11, 0x08, 209, 11, 11, 11, 0x08, 226, 11, 11, 11, 0x08, 240, 11, 11, 11, 0x08, 255, 11, 11, 11, 0x08, 282, 271, 11, 11, 0x08, 0 // eod }; static const char qt_meta_stringdata_GUIDesktop[] = { "GUIDesktop\0\0clickIniciar()\0clickDetener()\0" "idiomaIngles()\0idiomaEspanol()\0" "idiomaPortugues()\0acercaDe()\0ayuda()\0" "crearConexion()\0escucharClienteTcp()\0" "clickEliminar()\0actionEliminar()\0" "clickEditar()\0actionEditar()\0" "insertarPerfil()\0nuevoPerfil()\0" "botonAceptar()\0botonCancelar()\0" "pbx_nombre\0cambioCombo(QString)\0" }; const QMetaObject GUIDesktop::staticMetaObject = { { &QMainWindow::staticMetaObject, qt_meta_stringdata_GUIDesktop, qt_meta_data_GUIDesktop, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &GUIDesktop::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *GUIDesktop::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *GUIDesktop::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_GUIDesktop)) return static_cast<void*>(const_cast< GUIDesktop*>(this)); return QMainWindow::qt_metacast(_clname); } int GUIDesktop::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QMainWindow::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: clickIniciar(); break; case 1: clickDetener(); break; case 2: idiomaIngles(); break; case 3: idiomaEspanol(); break; case 4: idiomaPortugues(); break; case 5: acercaDe(); break; case 6: ayuda(); break; case 7: crearConexion(); break; case 8: escucharClienteTcp(); break; case 9: clickEliminar(); break; case 10: actionEliminar(); break; case 11: clickEditar(); break; case 12: actionEditar(); break; case 13: insertarPerfil(); break; case 14: nuevoPerfil(); break; case 15: botonAceptar(); break; case 16: botonCancelar(); break; case 17: cambioCombo((*reinterpret_cast< QString(*)>(_a[1]))); break; default: ; } _id -= 18; } return _id; } QT_END_MOC_NAMESPACE
[ "[email protected]@58e77f3c-66d3-2f76-d9f4-08142b3b8c59" ]
[ [ [ 1, 121 ] ] ]
9dca22205be3ffbd35dbea070eff0dffb8aa1b5c
0ee189afe953dc99825f55232cd52b94d2884a85
/mlog/Output.cpp
857c32bfd601fe5a1357ef715cb81a384c8214d5
[]
no_license
spolitov/lib
fed99fa046b84b575acc61919d4ef301daeed857
7dee91505a37a739c8568fdc597eebf1b3796cf9
refs/heads/master
2016-09-11T02:04:49.852151
2011-08-11T18:00:44
2011-08-11T18:00:44
2,192,752
0
0
null
null
null
null
UTF-8
C++
false
false
4,209
cpp
#include "pch.h" #include "Manager.h" #include "Output.h" #if !MLOG_NO_LOGGING namespace mlog { namespace detail { const size_t bufferSize = 0x100; struct Buffer { boost::array<char, bufferSize> data; Buffer * next; Buffer() : next(0) {} }; class StreamBuf : public std::streambuf { public: StreamBuf() : cur_(&buffer_) { char * begin = &cur_->data[0]; std::streambuf::setp(begin, begin + bufferSize); } ~StreamBuf() { reset(); } int_type overflow(int_type c) { cur_->next = new Buffer; cur_ = cur_->next; cur_->data[0] = c; char * begin = &cur_->data[0]; std::streambuf::setp(begin + 1, begin + bufferSize); return c; } std::streamsize xsputn(const char_type * s, std::streamsize n) { const char_type * end = s + n; size_t c = std::min<size_t>(end - s, epptr() - pptr()); memcpy(pptr(), s, c); pbump(static_cast<int>(c)); s += c; if(s != end) { size_t c; cur_->next = new Buffer; cur_ = cur_->next; for(;;) { c = std::min<size_t>(end - s, bufferSize); memcpy(&cur_->data[0], s, c); s += c; if(s == end) break; cur_->next = new Buffer; cur_ = cur_->next; } char * begin = &cur_->data[0]; std::streambuf::setp(begin + c, begin + bufferSize); } return n; } void reset() { cur_ = &buffer_; Buffer * c = buffer_.next; while(c) { Buffer * n = c->next; delete c; c = n; } buffer_.next = 0; char * begin = &cur_->data[0]; std::streambuf::setp(begin, begin + bufferSize); } mstd::pbuffer buffer(uint32_t group, mlog::LogLevel level) { size_t size = 0; for(Buffer * c = buffer_.next; c; c = c->next) ++size; size_t pos = pptr() - &cur_->data[0]; size = size * bufferSize + pos; mstd::pbuffer result = mstd::buffers::instance().take(size + sizeof(size_t) + sizeof(group) + sizeof(level)); char * p = result->ptr(); *mstd::pointer_cast<uint32_t*>(p) = group; p += sizeof(group); *mstd::pointer_cast<LogLevel*>(p) = level; p += sizeof(level); *mstd::pointer_cast<size_t*>(p) = size; p += sizeof(size); for(Buffer * c = &buffer_; ; c = c->next) { if(!c->next) { memcpy(p, &c->data[0], pos); break; } else { memcpy(p, &c->data[0], bufferSize); p += bufferSize; } } return result; } private: Buffer buffer_; Buffer * cur_; }; class StreamBase { protected: StreamBuf buf_; }; class Stream : private StreamBase, public std::ostream { public: Stream() : std::ostream(&buf_) {} }; class OStreamPool::Impl { public: boost::ptr_vector<Stream> streams; boost::mutex mutex; }; OStreamPool::OStreamPool() : impl_(new Impl) { } OStreamPool::~OStreamPool() { } std::ostream * OStreamPool::take() { boost::mutex::scoped_lock lock(impl_->mutex); if(impl_->streams.empty()) return new Stream; else return impl_->streams.pop_back().release(); } void OStreamPool::release(std::ostream * stream) { static_cast<StreamBuf*>(stream->rdbuf())->reset(); boost::lock_guard<boost::mutex> lock(impl_->mutex); impl_->streams.push_back(static_cast<Stream*>(stream)); } } void Output::send(uint32_t group, LogLevel level, const char * logger) { #if !defined(BOOST_WINDOWS) && !defined(__APPLE__) (*out_) << "\033[0m"; #endif (*out_) << '\n'; Manager::instance().output(logger, static_cast<detail::StreamBuf*>(out_->rdbuf())->buffer(group, level)); } } #endif
[ [ [ 1, 178 ] ] ]
3198abc907f4326774a37de7537e515f2b9ae019
c7120eeec717341240624c7b8a731553494ef439
/src/cplusplus/freezone-samp/src/objects.cpp
53ca5f6c35e901dc7b37580beade43574ea41533
[]
no_license
neverm1ndo/gta-paradise-sa
d564c1ed661090336621af1dfd04879a9c7db62d
730a89eaa6e8e4afc3395744227527748048c46d
refs/heads/master
2020-04-27T22:00:22.221323
2010-09-04T19:02:28
2010-09-04T19:02:28
174,719,907
1
0
null
2019-03-09T16:44:43
2019-03-09T16:44:43
null
WINDOWS-1251
C++
false
false
8,030
cpp
#include "config.hpp" #include "objects.hpp" #include <algorithm> #include <functional> #include <iterator> #include "core/module_c.hpp" #include "core/samp/samp_api.hpp" #include "mta10_loader.hpp" #include "ipl_loader.hpp" #include "server_paths.hpp" REGISTER_IN_APPLICATION(objects); objects::objects(): max_objects(0), max_objects_dynamic(0), is_debug(false) { streamer.delete_item_event = std::tr1::bind(&objects::streamer_item_deleter, this, std::tr1::placeholders::_1); } objects::~objects() { } void objects::configure_pre() { objects_static.update_begin(); objects_dynamic.update_begin(); object_def_default = object_def_t(500.0f, 0.0f); object_defs.clear(); is_debug = false; is_debug_config = false; max_objects = 150; } void objects::configure(buffer::ptr const& buff, def_t const& def) { SERIALIZE_NAMED_ITEM(objects_static.update_get_data(), "static_object"); SERIALIZE_NAMED_ITEM(objects_dynamic.update_get_data(), "dynamic_object"); SERIALIZE_ITEM(object_def_default); SERIALIZE_ITEM(object_defs); SERIALIZE_ITEM(is_debug); SERIALIZE_ITEM(is_debug_config); SERIALIZE_ITEM(max_objects); { // Загружаем объекты из файлов MTA-SA 1.0 mta10_loader_items_t loader_mta10; mta10_loader_items_t loader_mta10_static; SERIALIZE_ITEM(loader_mta10); SERIALIZE_ITEM(loader_mta10_static); mta10_loader loader(PATH_MTA10_DIR); loader.load_items(loader_mta10, objects_dynamic.update_get_data()); //loader.load_items(loader_mta10_static, objects_static.update_get_data()); } { // Загружаем объекты из файлов GTA ipl bool loader_ipl_dump = false; ipl_loader_items_t loader_ipl; ipl_loader_items_t loader_ipl_static; SERIALIZE_ITEM(loader_ipl); SERIALIZE_ITEM(loader_ipl_static); SERIALIZE_ITEM(loader_ipl_dump); ipl_loader loader(PATH_IPL_DIR, loader_ipl_dump); loader.load_items(loader_ipl, objects_dynamic.update_get_data()); loader.load_items(loader_ipl_static, objects_static.update_get_data()); } } void objects::configure_post() { if (max_objects < 0) { max_objects = 0; } // Работа со статическими объектами if (objects_static.update_get_data().size() > static_cast<std::size_t>(max_objects)) { // Отсекаем лишние объекты objects_static_t::update_t::iterator it = objects_static.update_get_data().begin(); for (int i = 0; i <= max_objects; ++i) ++it; objects_static.update_get_data().erase(it, objects_static.update_get_data().end()); } objects_static.update_end(std::tr1::bind(&objects::static_object_create, this, std::tr1::placeholders::_1), std::tr1::bind(&objects::static_object_destroy, this, std::tr1::placeholders::_1)); max_objects_dynamic = max_objects - objects_static.update_get_data().size(); // Работа с динамическими объектами { // Заполняем определения объектов objects_dynamic_t::update_t buff; std::transform(objects_dynamic.update_get_data().begin(), objects_dynamic.update_get_data().end(), std::inserter(buff, buff.begin()), std::tr1::bind(&objects::fill_defs, this, std::tr1::placeholders::_1)); objects_dynamic.update_get_data().swap(buff); } objects_dynamic.update_end(std::tr1::bind(&objects_streamer_t::item_add, std::tr1::ref(streamer), std::tr1::placeholders::_1), std::tr1::bind(&objects_streamer_t::item_delete, std::tr1::ref(streamer), std::tr1::placeholders::_1)); players_execute_handlers(&objects_item::reconfig_done_event); if (is_debug_config) { messages_item msg_item; msg_item.get_params() ("static_count", objects_static.get_size()) ("dynamic_count", objects_dynamic.get_size()); msg_item.get_sender()("<log_section objects/debug/configdone/>static=$(static_count), dynamic=$(dynamic_count)", msg_debug); } } void objects::on_gamemode_init(AMX* amx, samp::server_ver ver) { } void objects::on_connect(player_ptr_t const& player_ptr) { objects_item::ptr item(new objects_item(*this), &player_item::do_delete); player_ptr->add_item(item); } int objects::static_object_create(object_static_t const& object_static) { return samp::api::instance()->create_object(object_static.model_id, object_static.x, object_static.y, object_static.z, object_static.rx, object_static.ry, object_static.rz, 250.0f); } void objects::static_object_destroy(int id) { samp::api::instance()->destroy_object(id); } object_dynamic_t objects::fill_defs(object_dynamic_t const& obj_src) const { object_dynamic_t obj(obj_src); object_defs_t::const_iterator it = object_defs.find(obj.model_id); if (object_defs.end() == it) { // Не нашли в мапе кастомных описаний - берем стандартные obj.visibility = object_def_default.visibility; obj.radius = object_def_default.radius; } else { // Нашли и их используем obj.visibility = it->second.visibility; obj.radius = it->second.radius; } return obj; } void objects::streamer_item_deleter(int key) { players_execute_handlers(&objects_item::delete_event, key); } int objects::dynamic_object_create(object_dynamic_t const& object_dynamic) { return streamer.item_add(fill_defs(object_dynamic)); } void objects::dynamic_object_destroy(int id) { streamer.item_delete(id); } objects_item::objects_item(objects& manager) :manager(manager) ,samp_api(samp::api::instance()) ,checker(5.0f) { } objects_item::~objects_item() { } void objects_item::on_timer500() { pos4 pos = get_root()->get_item<player_position_item>()->pos_get(); if (manager.is_debug) { // Если отладка, то отключаем оптимизацию детектора перемещения checker.reset(); } update_player_pos(pos); } void objects_item::update_player_pos(pos3 const& pos) { if (checker(pos)) { objects_player.update_begin(); manager.streamer.items_get_by_pos(objects_player.update_get_data(), pos, manager.max_objects_dynamic); objects_player.update_end(std::tr1::bind(&objects_item::object_create, this, std::tr1::placeholders::_1), std::tr1::bind(&objects_item::object_destroy, this, std::tr1::placeholders::_1)); } } int objects_item::object_create(int object_key) { object_dynamic_t const& obj = manager.streamer.item_get(object_key); int id = samp_api->create_player_object(get_root()->get_id(), obj.model_id, obj.x, obj.y, obj.z, obj.rx, obj.ry, obj.rz, obj.visibility); if (manager.is_debug) { messages_item msg_item; msg_item.get_params() ("obj", boost::format("%1%") % obj) ("id", id) ("player_name", get_root()->name_get_full()); msg_item.get_sender()("<log_section objects/debug/player_create/>$(player_name) $(id) $(obj)", msg_debug); } return id; } void objects_item::object_destroy(int id) { samp_api->destroy_player_object(get_root()->get_id(), id); if (manager.is_debug) { messages_item msg_item; msg_item.get_params() ("id", id) ("player_name", get_root()->name_get_full()); msg_item.get_sender()("<log_section objects/debug/player_destroy/>$(player_name) $(id)", msg_debug); } } void objects_item::delete_event(int object_key) { objects_player.delete_obj_if_exist(object_key, std::tr1::bind(&objects_item::object_destroy, this, std::tr1::placeholders::_1)); } void objects_item::reconfig_done_event() { checker.reset(); }
[ "dimonml@19848965-7475-ded4-60a4-26152d85fbc5" ]
[ [ [ 1, 202 ] ] ]
d7820d1337a2b538c2c55caf806e8fea4b4345db
61a53fbb693ea0eece4747c249f8daa5c3d8c6f5
/om_incl.h
35127f39e9bf33505c43e82a45b35c54ad06e5ae
[]
no_license
agapow/omegamip
875341523642340e3e14c439f60b1340124be92e
6219da8b9869dfd2a6dfe2ab66686e5b420dfe6d
refs/heads/master
2021-01-25T08:43:11.396806
2010-05-14T16:16:45
2010-05-14T16:16:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,292
h
/* om_incl.h: global includes and definitions */ #ifndef _OM_INCL_ #define _OM_INCL_ // INCLUDES #include <cassert> // CONSTANTS & DEFINITIONS #ifdef OM_DEBUG #include <iostream> #include <stdlib.h> // in non-debug versions, these statements evaluate to nothing // call like "ASSERT(chain_id < 20, "my message");" #define ASSERT(t,m) if (!t) { cout << __FILE__ << ":" << __LINE__ << \ ": Assertion \" << "#t << "\" failed (" << m << ")" << std::endl; \ std::exit(1); } // call like "PRINTVAR(foo);" #define PRINTVAR(var) std::cout << __FILE__ << ":" << __LINE__ << \ ": '" << #var << "'=" << (var) << std::endl; // call like "MSG("here is my message");" #define MSG(msg) std::cout << __FILE__ << ":" << __LINE__ << \ ": " << msg << std::endl; // call like "MPI_MSG("here is my message");" #define MPI_MSG(msg) std::cout << "[" << proc_id << "," << \ chain_id << "] " << __FILE__ << ":" << __LINE__ << \ ": " << msg << std::endl; #else #define NDEBUG /* switch off asserts */ #define PRINTVAR(var) /* don't print vars */ #define MSG(msg) /* don't print messages */ #define MPI_MSG(msg) /* don't print messages */ #endif // OM_DEBUG #endif // _OM_INCL_
[ [ [ 1, 50 ] ] ]
5d9e27d67d383a04186f10430f0c470a6b36c49d
b63cad17af550bc7150431b7b0d639a46a129d82
/mcscript-script-handler.h
1a14d45b2c3aee91a301b8f45155898183b9a97e
[]
no_license
cjus/msgCourier
90463028b5e6222dd5c804215fa43bc518c4a539
075ff724316fd28c21d842726b694806d82bf53b
refs/heads/master
2021-01-10T19:41:02.306930
2010-09-05T18:47:24
2010-09-05T18:47:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,096
h
/* mcscript-script-handler.h Copyright (C) 2005 Carlos Justiniano mcscript-script-handler.h 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. mcscript-script-handler.h was developed by Carlos Justiniano for use on the ChessBrain Project (http://www.chessbrain.net) and is now distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with mcscript-script-handler.h; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /** @file mcscript-script-handler.h @brief Message Courier Script Handlers @author Carlos Justiniano @attention Copyright (C) 2005 Carlos Justiniano, GNU GPL Licence (see source file header) Message Courier Script Handlers. */ #ifndef _MCSCRIPT_SCRIPT_HANDLER_H #define _MCSCRIPT_SCRIPT_HANDLER_H #include <string> #include "mcscript.h" /****************** * Script Handler * ******************/ class cMCScriptHandler : public cMCScriptKeywordHandler { public: int Process(cMCScript *pMCScript, cXMLLiteParser *pXML, std::string *pOutputBuffer) { cXMLLiteElement *pElm = pXML->GetElement(); const char *pLanguage = pElm->GetAttributeValue("language"); if (strlen(pLanguage)==0) return HRC_MCSCRIPT_XMLDATA_SCRIPTCMD_MISSING_LANGUAGE_ATTRIBUTE; if (strcmp(pLanguage, "Tcl") != 0) return HRC_MCSCRIPT_XMLDATA_SCRIPTCMD_LANGUAGE_MUSTBE_TCL; if (pElm->hasCDATA() == false) return HRC_MCSCRIPT_XMLDATA_SCRIPTCMD_ISMISSING_CDATA_SECTION; pOutputBuffer->append("\n"); pOutputBuffer->append(pMCScript->GetIndentTabs()); pOutputBuffer->append(pElm->GetElementCDATA()); return 0; } }; #endif //_MCSCRIPT_SCRIPT_HANDLER_H
[ [ [ 1, 61 ] ] ]
41e7415954c4dcd2d0e858fbe79d03f1ac0956e5
7e68ef369eff945f581e22595adecb6b3faccd0e
/code/minifw/Guard.h
f95aecd769b1282d735aa4649a2cb1a82c9e50a1
[]
no_license
kimhmadsen/mini-framework
700bb1052227ba18eee374504ff90f41e98738d2
d1983a68c6b1d87e24ef55ca839814ed227b3956
refs/heads/master
2021-01-01T05:36:55.074091
2008-12-16T00:33:10
2008-12-16T00:33:10
32,415,758
0
0
null
null
null
null
UTF-8
C++
false
false
714
h
#pragma once /** @file */ #include "threadmutex.h" /** Implements The Scoped Locking C++ idiom which ensures that a lock is acquired when control enters a scope and released automatically when control leaves the scope, regardless of the return path from the scope. */ class Guard { public: Guard(ThreadMutex &lock_) :lock(&lock_), owner(false) { lock->Acquire(); owner = true ; } ~Guard(void) { if(owner) lock->Release(); } void Acquire() { lock->Acquire(); owner = true; } void Release() { lock->Release(); owner = false; } private: ThreadMutex *lock; bool owner; Guard(const Guard &); void operator=(const Guard &); };
[ "lasselorenzen@77f6bdef-6155-0410-8b08-fdea0229669f", "[email protected]@77f6bdef-6155-0410-8b08-fdea0229669f" ]
[ [ [ 1, 1 ], [ 5, 6 ], [ 13, 48 ] ], [ [ 2, 4 ], [ 7, 12 ] ] ]
47fb316c05f4b8dd9dda063eb936c5ea0cbe1aa1
b2ac2cc956c5b7dc8a38e7a44364d0282241ed8e
/branches/win-version-with-canvas/Sources/Windows/MWinControlsImpl.h
0e38bf72dca64e34f1ce0d4104a61fec3a5ea127
[ "BSL-1.0" ]
permissive
BackupTheBerlios/japi-svn
b2a9971644a4740d10aef614e09f3fdd49e8460d
f9a5b284e285442b485ef05824ed8e55499c8d61
refs/heads/master
2016-09-15T17:14:35.504291
2010-12-03T11:39:25
2010-12-03T11:39:25
40,801,061
0
0
null
null
null
null
UTF-8
C++
false
false
2,143
h
// Copyright Maarten L. Hekkelman 2006-2010 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef MWINCONTROLSIMPL_H #define MWINCONTROLSIMPL_H #include "MControlsImpl.h" #include "MWinProcMixin.h" class MWinControlImpl : public MControlImpl, public MWinProcMixin { public: MWinControlImpl(MView* inControl, const std::string& inLabel = ""); virtual ~MWinControlImpl(); virtual void GetParentAndBounds(MWinProcMixin*& outParent, MRect& outBounds); static MWinControlImpl* FetchControlImpl(HWND inHWND); virtual void AddedToWindow(); virtual void FrameResized(); virtual void Draw(MRect inBounds); virtual void ActivateSelf(); virtual void DeactivateSelf(); virtual void EnableSelf(); virtual void DisableSelf(); virtual void ShowSelf(); virtual void HideSelf(); virtual std::string GetText() const; virtual void SetText(const std::string& inText); virtual bool WMCommand(HWND inHWnd, UINT inUMsg, WPARAM inWParam, LPARAM inLParam, int& outResult); protected: std::string mLabel; }; // actual implementations class MButtonImpl : public MWinControlImpl { public: MButtonImpl(MControl* inControl, const std::string& inLabel); virtual void CreateParams(DWORD& outStyle, DWORD& outExStyle, std::wstring& outClassName, HMENU& outMenu); }; class MScrollbarImpl : public MWinControlImpl { public: MScrollbarImpl(MControl* inControl); virtual void CreateParams(DWORD& outStyle, DWORD& outExStyle, std::wstring& outClassName, HMENU& outMenu); virtual void ShowSelf(); virtual void HideSelf(); virtual long GetValue() const; virtual void SetValue(long inValue); virtual long GetMinValue() const; virtual void SetMinValue(long inValue); virtual long GetMaxValue() const; virtual void SetMaxValue(long inValue); virtual void SetViewSize(long inValue); virtual bool WMScroll(HWND inHWnd, UINT inUMsg, WPARAM inWParam, LPARAM inLParam, int& outResult); }; #endif
[ "maarten@6969af58-1542-49b8-b3af-dcaebf5f4018" ]
[ [ [ 1, 77 ] ] ]
d5ad8e48c041f9a334441051019c293c72c4efa3
1c9f99b2b2e3835038aba7ec0abc3a228e24a558
/Projects/elastix/elastix_sources_v4/src/Common/MevisDicomTiff/itkMevisDicomTiffImageIO.cxx
a4d96a707ede1708b01933a2770a16b69d7eeaef
[]
no_license
mijc/Diploma
95fa1b04801ba9afb6493b24b53383d0fbd00b33
bae131ed74f1b344b219c0ffe0fffcd90306aeb8
refs/heads/master
2021-01-18T13:57:42.223466
2011-02-15T14:19:49
2011-02-15T14:19:49
1,369,569
0
0
null
null
null
null
UTF-8
C++
false
false
62,889
cxx
/*====================================================================== 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. ======================================================================*/ /*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMevisDicomTiffImageIO.cxx,v $ Language: C++ Date: $Date: 2009/10/14 13:28:12 $ Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifdef _MSC_VER #pragma warning ( disable : 4786 ) #endif #include "itkMevisDicomTiffImageIO.h" #include "itkArray.h" #include "itkMetaDataObject.h" #include "itkVersion.h" #include "itkNumericTraits.h" // developed using gdcm 2.0 and libtiff 3.8.2 #include "gdcmAttribute.h" #include "gdcmByteValue.h" #include "gdcmDicts.h" #include "gdcmGlobal.h" #include "gdcmUIDGenerator.h" #include "gdcmImage.h" #include "gdcmImageReader.h" #include "gdcmWriter.h" #include "gdcmReader.h" #include "gdcmSequenceOfItems.h" #include "gdcmTag.h" #include "gdcmVL.h" #include "gdcmVR.h" #include "gdcmVersion.h" #include "gdcmPrinter.h" #include <sstream> #include <string> #include <vector> #include <fstream> #include <iostream> #include <vnl/vnl_vector.h> #include <vnl/vnl_cross.h> #include <itksys/SystemTools.hxx> namespace itk { // constructor MevisDicomTiffImageIO::MevisDicomTiffImageIO(): m_DcmFileName(""), m_TiffFileName(""), m_TIFFImage(NULL), m_TIFFDimension(2), m_IsOpen(false), m_Compression(0), m_BitsPerSample(0), m_Width(0), m_Length(0), m_Depth(0), m_IsTiled(true), // default ML m_TileWidth(0), m_TileLength(0), m_TileDepth(0), m_NumberOfTiles(0), m_RescaleSlope(NumericTraits<double>::One), m_RescaleIntercept(NumericTraits<double>::Zero), m_EstimatedMinimum(NumericTraits<double>::Zero), m_EstimatedMaximum(NumericTraits<double>::Zero) { this->SetNumberOfDimensions(3); this->SetFileType(Binary); this->AddSupportedWriteExtension(".dcm"); this->AddSupportedWriteExtension(".tif"); this->AddSupportedWriteExtension(".tiff"); this->AddSupportedWriteExtension(".DCM"); this->AddSupportedWriteExtension(".TIF"); this->AddSupportedWriteExtension(".TIFF"); this->AddSupportedReadExtension(".dcm"); this->AddSupportedReadExtension(".tif"); this->AddSupportedReadExtension(".tiff"); this->AddSupportedReadExtension(".DCM"); this->AddSupportedReadExtension(".TIF"); this->AddSupportedReadExtension(".TIFF"); } // destructor MevisDicomTiffImageIO::~MevisDicomTiffImageIO() { if (m_IsOpen) { TIFFClose(m_TIFFImage); } } // printself void MevisDicomTiffImageIO::PrintSelf(std::ostream& os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "DcmFileName : " << m_DcmFileName << std::endl; os << indent << "TiffFileName : " << m_TiffFileName << std::endl; os << indent << "TIFFDimension : " << m_TIFFDimension << std::endl; os << indent << "IsOpen : " << m_IsOpen << std::endl; os << indent << "Compression : " << m_Compression << std::endl; os << indent << "BitsPerSample : " << m_BitsPerSample << std::endl; os << indent << "Width : " << m_Width << std::endl; os << indent << "Length : " << m_Length << std::endl; os << indent << "Depth : " << m_Depth << std::endl; os << indent << "IsTiled : " << m_IsTiled << std::endl; os << indent << "TileWidth : " << m_TileWidth << std::endl; os << indent << "TileLength : " << m_TileLength << std::endl; os << indent << "TileDepth : " << m_TileDepth << std::endl; os << indent << "NumberOfTiles : " << m_NumberOfTiles << std::endl; os << indent << "RescaleIntercept : " << m_RescaleIntercept << std::endl; os << indent << "RescaleSlope : " << m_RescaleSlope << std::endl; } // canreadfile bool MevisDicomTiffImageIO::CanReadFile( const char* filename ) { // get names const std::string fn = filename; const std::string basename = itksys::SystemTools::GetFilenameWithoutLastExtension(fn); const std::string ext = itksys::SystemTools::GetFilenameLastExtension(fn); std::string pathname = itksys::SystemTools::GetFilenamePath(fn).c_str(); if (!pathname.empty()) { pathname = pathname + "/"; } if ( basename.empty() ) { std::cout << "mevisIO: no filename specified" << std::endl;; return false; } // prevent from reading same basenames in dir but with dcm/tiff // extension! if (ext != ".dcm" && ext != ".DCM" && ext != ".tif" && ext != ".TIF" && ext != ".tiff" && ext != ".TIFF" ) { return false; } // dcmfile present? const std::string dname = pathname + basename + ".dcm"; const std::string Dname = pathname + basename + ".DCM"; const std::string d = itksys::SystemTools::ConvertToOutputPath(dname.c_str()); const std::string D = itksys::SystemTools::ConvertToOutputPath(Dname.c_str()); std::ifstream f(d.c_str(), std::ios::in | std::ios::binary); std::ifstream F(D.c_str(), std::ios::in | std::ios::binary); if (!f.is_open() && !F.is_open()) { std::cout << "mevisIO: cannot read (corresponding) dcm file" << std::endl; return false; } if (f.is_open()) { m_DcmFileName = d; f.close(); } if (F.is_open()) { m_DcmFileName = D; F.close(); } // tiff file present? std::string tifname(""); const std::string t1name = pathname + basename + ".tif"; const std::string t2name = pathname + basename + ".tiff"; const std::string t3name = pathname + basename + ".TIF"; const std::string t4name = pathname + basename + ".TIFF"; std::ifstream t1(t1name.c_str(), std::ios::in | std::ios::binary); std::ifstream t2(t2name.c_str(), std::ios::in | std::ios::binary); std::ifstream t3(t3name.c_str(), std::ios::in | std::ios::binary); std::ifstream t4(t4name.c_str(), std::ios::in | std::ios::binary); if (!t1.is_open() && !t2.is_open() && !t3.is_open() && !t4.is_open()) { std::cout << "mevisIO: cannot read (corresponding) tif file" << std::endl; return false; } if (t1.is_open()) { m_TiffFileName = t1name; t1.close(); } if (t2.is_open()) { m_TiffFileName = t2name; t2.close(); } if (t3.is_open()) { m_TiffFileName = t3name; t3.close(); } if (t4.is_open()) { m_TiffFileName = t4name; t4.close(); } // checking if dcm is valid dcm gdcm::Reader reader; reader.SetFileName(m_DcmFileName.c_str()); if (! reader.Read()) { std::cout << "error opening dcm file " << m_DcmFileName << std::endl; return false; } // checking if tiff is valid tif m_TIFFImage = TIFFOpen(m_TiffFileName.c_str(), "rc"); // c is disable strip chopping if (m_TIFFImage == NULL) { std::cout << "mevisIO: error opening tif file " << m_TiffFileName << std::endl; return false; } else { m_IsOpen = true; if (!TIFFGetField(m_TIFFImage, TIFFTAG_IMAGEWIDTH, &m_Width)) { std::cout << "mevisIO: error getting IMAGEWIDTH " << std::endl; } if (!TIFFGetField(m_TIFFImage, TIFFTAG_IMAGELENGTH, &m_Length)) { std::cout << "mevisIO: error getting IMAGELENGTH " << std::endl; } if (!TIFFGetField(m_TIFFImage, TIFFTAG_IMAGEDEPTH, &m_Depth)) { m_TIFFDimension = 2; m_Depth = 0; } else { m_TIFFDimension = 3; } if (!TIFFGetField(m_TIFFImage, TIFFTAG_COMPRESSION, &m_Compression)) { std::cout << "mevisIO: error getting COMPRESSION" << std::endl; } m_IsTiled = TIFFIsTiled(m_TIFFImage); if (m_IsTiled) { m_NumberOfTiles = TIFFNumberOfTiles(m_TIFFImage); if (!TIFFGetField(m_TIFFImage,TIFFTAG_TILEWIDTH,&m_TileWidth)) { std::cout << "mevisIO: error getting TILEWIDTH " << std::endl; } if (!TIFFGetField(m_TIFFImage,TIFFTAG_TILELENGTH,&m_TileLength)) { std::cout << "mevisIO: error getting TILELength" << std::endl; } if (!TIFFGetField(m_TIFFImage, TIFFTAG_TILEDEPTH, &m_TileDepth)) { m_TileDepth = 0; } } } return true; } // readimageinformation void MevisDicomTiffImageIO::ReadImageInformation() { // INFO from DICOM // // note: position may need to be shifted since mevis uses corner // as position, while itk uses the center // // note: if a 3D image is provided, then we need to // read spacingbetweenslices // // spacing // position (origin) // direction // we DON'T trust info from the image (within the // dcm file), since somehow eg spacing does not // return the correct values. Also, in case of mevis, // the dcmfile does not contain an image, which causes // reader.Read() to return an error. // // We trust the dcm header information instead gdcm::ImageReader reader; reader.SetFileName(m_DcmFileName.c_str()); reader.Read(); const gdcm::DataSet header = reader.GetFile().GetDataSet(); // number of frames (we always assume 3D image, otherwise // spacing and orientation in third dimension is lost // Note that using SetNumberOfDimensions() reset all these // vars, but using member functions only set the corresponding // variable without side effect // If this variable does not exists or equals one then we // resize the numberofdimensions to two gdcm::Attribute<0x0028,0x0008> atnf; bool is2d(false); if (!header.GetDataElement(atnf.GetTag()).IsEmpty()) { atnf.SetFromDataElement(header.GetDataElement(atnf.GetTag())); if (atnf.GetValue() > 1) { m_Dimensions.resize(3); m_Dimensions[2] = atnf.GetValue(); } else { is2d = true; } } else { is2d = true; } if (is2d) { m_NumberOfDimensions = 2; } // dimenions - col gdcm::Attribute<0x0028,0x0011> atdc; if (!header.GetDataElement(atdc.GetTag()).IsEmpty()) { atdc.SetFromDataElement(header.GetDataElement(atdc.GetTag())); m_Dimensions[0] = atdc.GetValue(); } else { std::cout << "mevisIO: error reading dimensions-row from dcm-file" << std::endl; } // dimensions - row gdcm::Attribute<0x0028,0x0010> atdr; if (!header.GetDataElement(atdr.GetTag()).IsEmpty()) { atdr.SetFromDataElement(header.GetDataElement(atdr.GetTag())); m_Dimensions[1] = atdr.GetValue(); } else { std::cout << "mevisIO: error reading dimensions-row from dcm-file" << std::endl; } // spacing, always 3d vector m_Spacing.resize(3); gdcm::Attribute<0x0028,0x0030> atps; if (!header.GetDataElement(atps.GetTag()).IsEmpty()) { atps.SetFromDataElement(header.GetDataElement(atps.GetTag())); m_Spacing[0] = atps.GetValue(0); m_Spacing[1] = atps.GetValue(1); } else { std::cout << "mevisIO: error reading pixelspacing from dcm-file" << std::endl; } gdcm::Attribute<0x0018,0x0088> atss; if (!header.GetDataElement(atss.GetTag()).IsEmpty()) { atss.SetFromDataElement(header.GetDataElement(atss.GetTag())); m_Spacing[2] = atss.GetValue(); } else { m_Spacing[2] = 0; std::cout << "mevisIO: error reading slicespacing from dcm-file" << std::endl; } // patient position (origin), always 3d vector m_Origin.resize(3); gdcm::Attribute<0x0020,0x0032> atpp; if (!header.GetDataElement(atpp.GetTag()).IsEmpty()) { atpp.SetFromDataElement(header.GetDataElement(atpp.GetTag())); m_Origin[0] = atpp.GetValue(0); m_Origin[1] = atpp.GetValue(1); m_Origin[2] = atpp.GetValue(2); } else { std::cout << "mevisIO: error reading patient position (origin) from dcm-file" << std::endl; } // orientation (image orientation), always 3d vector m_Direction.resize(3); gdcm::Attribute<0x0020,0x0037> atio; if (!header.GetDataElement(atio.GetTag()).IsEmpty()) { atio.SetFromDataElement(header.GetDataElement(atio.GetTag())); vnl_vector<double> row(3), col(3); row[0] = atio.GetValue(0); row[1] = atio.GetValue(1); row[2] = atio.GetValue(2); col[0] = atio.GetValue(3); col[1] = atio.GetValue(4); col[2] = atio.GetValue(5); vnl_vector<double> slice = vnl_cross_3d(row, col); this->SetDirection(0, row); this->SetDirection(1, col); this->SetDirection(2, slice); } else { std::cout << "mevisIO: error reading image orientation from dcm-file" << std::endl; } // rescale gdcm::Attribute<0x0028,0x1052> atri; if (!header.GetDataElement(atri.GetTag()).IsEmpty()) { atri.SetFromDataElement(header.GetDataElement(atri.GetTag())); m_RescaleIntercept = atri.GetValue(); } else { m_RescaleIntercept = NumericTraits<double>::Zero ; // default } // slope gdcm::Attribute<0x0028,0x1053> atrs; if (!header.GetDataElement(atrs.GetTag()).IsEmpty()) { atrs.SetFromDataElement(header.GetDataElement(atrs.GetTag())); m_RescaleSlope = atrs.GetValue(); } else { m_RescaleSlope = NumericTraits<double>::One; // default } // HEADER in MetaDICT // copying the gdcm dictionary to the itk dictionary, organization // dcm header // // DataSet (==header) contains DataElements // DataElement an unit of information as defined by a single entry // in the data dictionary, contains // Tag (0x000,0x0000) // VL value length field // VR value representation field // Value the value itself // Value is either bytes array // sequence of items or sequence of fragments // SeqOfItems contains items, item contains again a // DataSet (!). // // We simply put the whole header as value in the meta // dictionary, then no interpretation is required MetaDataDictionary & dic = this->GetMetaDataDictionary(); const std::string tag("0"); EncapsulateMetaData<gdcm::DataSet>(dic, tag, header); // INFO from TIFF // determine size // numberofcomponents // data type if (m_TIFFImage == NULL) { std::cout << "mevisIO: error opening file " << m_TiffFileName << std::endl; return; } // sanity checks, dim and sizes if ((is2d && m_TIFFDimension != 2) || (!is2d && m_TIFFDimension != 3)) { std::cout << "mevisIO: dcm/tiff dimensions do not correspond!" << std::endl; } if ( (m_Width != m_Dimensions[0]) || (m_Length != m_Dimensions[1]) || (m_TIFFDimension == 3 && m_Depth != m_Dimensions[2] )) { std::cout << "mevisIO: dcm/tiff sizes do not correspond!" << std::endl; } // format 1 unsigned int // format 2 signed int // format 3 float // format 4 undefined // samplesperpixel : number of components per pixel (1 grayscale, 3 rgb) // bitspersample: number of bits per component uint16 format, pixel; if (!TIFFGetField(m_TIFFImage, TIFFTAG_SAMPLEFORMAT, &format)) { std::cout << "mevisIO: error getting SAMPLEFORMAT" << std::endl; } if (!TIFFGetField(m_TIFFImage, TIFFTAG_SAMPLESPERPIXEL, &pixel)) { std::cout << "mevisIO: error getting SAMPLESPERPIXEL" << std::endl; } if (!TIFFGetField(m_TIFFImage, TIFFTAG_BITSPERSAMPLE, &m_BitsPerSample)) { std::cout << "mevisIO: error getting BITSPERSAMPLE" << std::endl; } // currently we only support grayscale if (pixel == 1) { this->SetPixelType(SCALAR); this->SetNumberOfComponents(1); } else { std::cout << "mevisIO: currently only support grayscale" << std::endl; } bool typeassign(false); if (m_BitsPerSample <= 8) { if (format == 1) { this->SetComponentType(UCHAR); typeassign = true; } if (format == 2) { this->SetComponentType(CHAR); typeassign = true; } } if (m_BitsPerSample == 16) { if (format == 1) { this->SetComponentType(USHORT); typeassign = true; } if (format == 2) { this->SetComponentType(SHORT); typeassign = true; } } if (m_BitsPerSample == 32) { if (format == 1) { this->SetComponentType(UINT); typeassign = true; } if (format == 2) { this->SetComponentType(INT); typeassign = true; } if (format == 3) { this->SetComponentType(FLOAT); typeassign = true; } } if (!typeassign) { std::cout << "mevisIO: unsupported pixeltype " << std::endl; } // set compression // 1 none // 2 ccit // 5 lzw // 32773 packbits if (m_Compression == 2 || m_Compression == 5 || m_Compression == 32773) { m_UseCompression = true; } if (m_Compression == 1) { m_UseCompression = false; } } // read void MevisDicomTiffImageIO::Read(void* buffer) { // always assume contigous data (PLANARCONFIG =1) // image is either tiled or stripped // // TIFFTileSize returns size of one tile in bytes // TIFFReadTile reads one tile, returns number of bytes in decoded tile // // note *buffer goes in scanline order! // very inconvenient if the tiff image is tiled, which damned // is the case for mevislab images! // note buffer is already allocated, according to size! short int p; if (!TIFFGetField(m_TIFFImage,TIFFTAG_PLANARCONFIG,&p)) { std::cout << "mevisIO: error getting PLANARCONFIG" << std::endl; } else { if (p != 1) { std::cout << "mevisIO: non-contiguous data!" << std::endl; return; } } if (m_IsTiled) { // only works for tile depth == 1 (used by mevislab), // therefore in z-direction we do not need to do checking // if the volume is multiple of tile. if (m_TIFFDimension == 3 && m_TileDepth != 1) { std::cout << "mevisIO: unsupported tiledepth (should be one)! " << std::endl; return; } // buffer pointer is scanline based (one dimensional array) // tile is positioned on x,y,z; we read each tile, and fill // the corresponding positions in the onedimensional array unsigned char *vol = reinterpret_cast<unsigned char*>(buffer); const unsigned int tilesize = TIFFTileSize(m_TIFFImage); const unsigned int tilerowbytes = TIFFTileRowSize(m_TIFFImage); const unsigned int bytespersample = m_BitsPerSample/8; unsigned char *tilebuf = static_cast<unsigned char*>(_TIFFmalloc(tilesize)); // // special cases, if the tilexy is larger than or equal to the image // size itself, treat as three separate cases, both are larger/equal, // or only direction // bool tileoversized(false); if (m_TileLength >= m_Length || m_TileWidth >= m_Width) { tileoversized = true; // case one both x,y is larger if (m_TileLength >= m_Length && m_TileWidth >= m_Width) { for (unsigned int z0 = 0; z0< (m_TIFFDimension == 3 ? m_Depth :1); z0++) { if (TIFFReadTile(m_TIFFImage, tilebuf, 0, 0, z0, 0) < 0) { std::cout << "mevisIO: error reading tile (topleft)" << std::endl; _TIFFfree(tilebuf); return; } else { // do row based copy of tile into volume const unsigned lenx = m_Width; const unsigned leny = m_Length; const unsigned int tilexbytes = lenx * bytespersample; unsigned char * pv = vol; const unsigned int p = z0 * m_Length * m_Width; pv += p * bytespersample; unsigned char * pb = tilebuf; for (unsigned int r = 0; r<leny; ++r) { memcpy(pv,pb,tilexbytes); pv += tilexbytes; pb += tilerowbytes; } } } } // end case one // case two, larger x, smaller y if (m_TileWidth >= m_Width && m_TileLength < m_Length) { const unsigned lenx = m_Width; const unsigned int tilexbytes = lenx * bytespersample; const bool my = ( m_Length%m_TileLength == 0) ? true : false; for (unsigned int z0 = 0; z0 < (m_TIFFDimension == 3 ? m_Depth : 1); z0++) { for (unsigned int y0 = 0; y0 < (my ? m_Length : m_Length-m_TileLength); y0 += m_TileLength) { if (TIFFReadTile(m_TIFFImage, tilebuf, 0, y0, z0, 0) < 0) { std::cout << "mevisIO: error reading tile (top image)" << std::endl; _TIFFfree(tilebuf); return; } else { unsigned char * pb = tilebuf; unsigned char * pv = vol; const unsigned int p = z0 * m_Length * m_Width + y0 * m_Width; pv += p * bytespersample; for (unsigned int r = 0; r<m_TileLength; ++r) { memcpy(pv,pb,tilerowbytes); pv += tilexbytes; pb += tilerowbytes; } } } if (!my) { const unsigned leny = m_Length%m_TileLength; const unsigned int y0 = m_Length - leny; if (TIFFReadTile(m_TIFFImage, tilebuf, 0, y0, z0, 0) < 0) { std::cout << "mevisIO: error reading tile (strip bottom)" << std::endl; _TIFFfree(tilebuf); return; } else { unsigned char * pb = tilebuf; unsigned char * pv = vol; const unsigned int p = z0 * m_Length * m_Width + y0 * m_Width; pv += p * bytespersample; for (unsigned int r = 0; r<leny; ++r) { memcpy(pv,pb,tilexbytes); pv += tilexbytes; pb += tilerowbytes; } } } } } // end case two // case three, smaller x, larger y if (m_TileWidth < m_Width && m_TileLength >= m_Length) { const unsigned leny = m_Length; const bool mx = ( m_Width%m_TileWidth == 0) ? true: false; for (unsigned int z0 = 0; z0 < (m_TIFFDimension == 3 ? m_Depth : 1); z0++) { for (unsigned int x0 = 0; x0 < (mx ? m_Width : m_Width-m_TileWidth); x0 += m_TileWidth) { // read tile if (TIFFReadTile(m_TIFFImage, tilebuf, x0, 0, z0, 0) < 0) { std::cout << "mevisIO: error reading tile (top image)" << std::endl; _TIFFfree(tilebuf); return; } else { unsigned char * pb = tilebuf; unsigned char * pv = vol; const unsigned int p = z0 * m_Length * m_Width + x0; pv += p * bytespersample; for (unsigned int r = 0; r<leny; ++r) { memcpy(pv,pb,tilerowbytes); pv += m_Width * bytespersample; pb += tilerowbytes; } } } // fill strip right if (!mx) { const unsigned lenx = m_Width%m_TileWidth; const unsigned int x0 = m_Width - lenx; const unsigned int tilexbytes = lenx * bytespersample; if (TIFFReadTile(m_TIFFImage, tilebuf, x0, 0, z0, 0) < 0) { std::cout << "mevisIO: error reading tile (strip right)" << std::endl; _TIFFfree(tilebuf); return; } else { unsigned char * pb = tilebuf; unsigned char * pv = vol; const unsigned int p = z0 * m_Length * m_Width + x0; pv += p * bytespersample; for (unsigned int r = 0; r<leny; ++r) { memcpy(pv,pb,tilexbytes); pv += m_Width * bytespersample; pb += tilerowbytes; } } } } } // end case three } // end oversized tile // // normal case, tile is smaller than image // if (!tileoversized) { // is volume direction a multiple of tiledirection? const bool mx = ( m_Width%m_TileWidth == 0) ? true: false; const bool my = ( m_Length%m_TileLength == 0) ? true : false; // fill everything inside ie from topleft for (unsigned int z0 = 0; z0 < (m_TIFFDimension == 3 ? m_Depth : 1); z0++) { for (unsigned int y0 = 0; y0 < (my ? m_Length : m_Length-m_TileLength); y0 += m_TileLength) for (unsigned int x0 = 0; x0 < (mx ? m_Width : m_Width-m_TileWidth); x0 += m_TileWidth) { // x0,y0,z0 is position of tile in volume, top left corner // pointer to volume (at 0,0,0) unsigned char * pv = vol; // set pointer of volume to y0,x0,z0 position const unsigned int p = z0 * m_Length * m_Width + y0 * m_Width + x0; pv += p * bytespersample; // read tile if (TIFFReadTile(m_TIFFImage, tilebuf, x0, y0, z0, 0) < 0) { std::cout << "mevisIO: error reading tile (topleft image)" << std::endl; _TIFFfree(tilebuf); return; } else { // do row based copy of tile into volume unsigned char * pb = tilebuf; for (unsigned int r = 0; r<m_TileLength; ++r) { memcpy(pv,pb,tilerowbytes); // move pointers // x remain same, y is one complete vol line // (ie width of image) pv += m_Width * bytespersample; pb += tilerowbytes; } } } // fill boundaries if (!mx) { // x is fixed const unsigned lenx = m_Width%m_TileWidth; const unsigned int x0 = m_Width - lenx; const unsigned int tilexbytes = lenx * bytespersample; for (unsigned int y0 = 0; y0 < (my ? m_Length: m_Length - m_TileLength); y0 += m_TileLength) { unsigned char * pv = vol; const unsigned int p = z0 * m_Length * m_Width + y0 * m_Width + x0; pv += p * bytespersample; if (TIFFReadTile(m_TIFFImage, tilebuf, x0, y0, z0, 0) < 0) { std::cout << "mevisIO: error reading tile (ydirection)" << std::endl; _TIFFfree(tilebuf); return; } else { unsigned char * pb = tilebuf; for (unsigned int r = 0; r<m_TileLength; ++r) { memcpy(pv,pb,tilexbytes); pv += m_Width * bytespersample; pb += tilerowbytes; } } } } if (!my) { // y is fixed const unsigned leny = m_Length%m_TileLength; const unsigned int y0 = m_Length - leny; for (unsigned int x0 = 0; x0 < (mx ? m_Width : m_Width-m_TileWidth); x0 += m_TileWidth) { unsigned char * pv = vol; const unsigned int p = z0 * m_Length * m_Width + y0 * m_Width + x0; pv += p * bytespersample; if (TIFFReadTile(m_TIFFImage, tilebuf, x0, y0, z0, 0) < 0) { std::cout << "mevisIO: error reading tile (x-direction)" << std::endl; _TIFFfree(tilebuf); return; } else { unsigned char * pb = tilebuf; for (unsigned int r = 0; r<leny; ++r) { memcpy(pv,pb,tilerowbytes); pv += m_Width * bytespersample; pb += tilerowbytes; } } } } // fill corner bottom if (!mx && !my) { // x0,y0 is fixed const unsigned lenx = m_Width%m_TileWidth; const unsigned int x0 = m_Width - lenx; const unsigned int tilexbytes = lenx * bytespersample; const unsigned leny = m_Length%m_TileLength; const unsigned int y0 = m_Length - leny; unsigned char * pv = vol; const unsigned int p = z0 * m_Length * m_Width + y0 * m_Width + x0; pv += p * bytespersample; if (TIFFReadTile(m_TIFFImage, tilebuf, x0, y0, z0, 0) < 0) { std::cout << "mevisIO: error reading tile (corner bottom)" << std::endl; _TIFFfree(tilebuf); return; } else { unsigned char * pb = tilebuf; for (unsigned int r = 0; r<leny; ++r) { memcpy(pv,pb,tilexbytes); pv += m_Width * bytespersample; pb += tilerowbytes; } } } } } _TIFFfree(tilebuf); } else { // if not tiled then img is stripped std::cout << "mevisIO: non-tiled dcm/tiff reading not (yet) implemented" << std::endl; return; } return; } // canwritefile bool MevisDicomTiffImageIO::CanWriteFile( const char * name ) { std::string filename = name; if (filename == "") { return false; } // get basename/extension const std::string fn = filename; const std::string basename = itksys::SystemTools::GetFilenameWithoutLastExtension(fn); const std::string ext = itksys::SystemTools::GetFilenameLastExtension(fn); std::string pathname = itksys::SystemTools::GetFilenamePath(fn).c_str(); if (!pathname.empty()) { pathname = pathname + "/"; } if ( basename.empty() ) { std::cout << "mevisIO: no filename specified" << std::endl; return false; } // expect extension dcm or tif(f) if (ext == ".tif" || ext == ".tiff") { m_TiffFileName = pathname + basename + ext; m_DcmFileName = pathname + basename + ".dcm"; return true; } if (ext == ".TIF" || ext == ".TIFF") { m_TiffFileName = pathname + basename + ext; m_DcmFileName = pathname + basename + ".DCM"; return true; } if (ext == ".dcm") { m_TiffFileName = pathname + basename + ".tif"; m_DcmFileName = pathname + basename + ".dcm"; return true; } if (ext == ".DCM" ) { m_TiffFileName = pathname + basename + ".TIF"; m_DcmFileName = pathname + basename + ".DCM"; return true; } return false; } // writeimageinformation void MevisDicomTiffImageIO ::WriteImageInformation(void) { } // write void MevisDicomTiffImageIO ::Write( const void* buffer) { if (this->GetNumberOfDimensions() != 2 && this->GetNumberOfDimensions() != 3) { itkExceptionMacro(<< "mevisIO: dcm/tiff writer only supports 2D/3D"); } std::ofstream dcmfile(m_DcmFileName.c_str(), std::ios::out|std::ios::binary); if (!dcmfile.is_open()) { std::cout << "mevisIO: error opening dcm file for writing " << m_DcmFileName << std::endl; } dcmfile.close(); // DCM - HEADER // // // Always add everything that is available from the metaheader, // the following tags are not replaced if they are available // but they may have changed during image processing. Be warned! // - dicom rescale intercept/slope values // - min/max (code below is after setting bits) // - photometric (default min-is-black) // - sop imagetype (0008,0008) // - sop class uid (0008,0016) // - sop instance uid (0008,0018) // - study instance uid (0020,000d) // - series instance uid (0020,000e) // // The following are always replaced: // - comments // - rows, columns, frames // - pixelspacing, spacing between slices // - orientation, position // - samples per pixel (always 1) // - bits allocated // - bits stored (always nbits) // - high bit (always nbits-1) // - pixel representation (0 unsigned, 1 signed) gdcm::Writer writer; writer.SetCheckFileMetaInformation(false); gdcm::DataSet &header = writer.GetFile().GetDataSet(); MetaDataDictionary &dict = this->GetMetaDataDictionary(); const bool emptydict(dict.Begin()==dict.End()); itk::MetaDataDictionary::ConstIterator dictiter; for(dictiter = dict.Begin(); dictiter!= dict.End(); ++dictiter) { const std::string & key = dictiter->first; ExposeMetaData<gdcm::DataSet>(dict, key, header); } // copy from metaheader if exists otherwise replace // rescale gdcm::Attribute<0x0028,0x1052> atri; if (!emptydict && !header.GetDataElement(atri.GetTag()).IsEmpty()) { atri.SetFromDataElement(header.GetDataElement(atri.GetTag())); } else { atri.SetValue(m_RescaleIntercept); } header.Replace(atri.GetAsDataElement()); // intercept gdcm::Attribute<0x0028,0x1053> atrs; if (!emptydict && !header.GetDataElement(atrs.GetTag()).IsEmpty()) { atrs.SetFromDataElement(header.GetDataElement(atrs.GetTag())); } else { atrs.SetValue(m_RescaleSlope); } header.Replace(atrs.GetAsDataElement()); // photometric gdcm::Attribute<0x0028,0x0004> atphoto; if (!emptydict && !header.GetDataElement(atphoto.GetTag()).IsEmpty()) { atphoto.SetFromDataElement(header.GetDataElement(atphoto.GetTag())); } else { // monochrome2 -- low values dark, high values bright atphoto.SetValue("MONOCHROME2"); } header.Replace(atphoto.GetAsDataElement()); // imagetype gdcm::Attribute<0x0008,0x0008> atimagetype; if (!emptydict && !header.GetDataElement(atimagetype.GetTag()).IsEmpty()) { atimagetype.SetFromDataElement(header.GetDataElement(atimagetype.GetTag())); } else { static const gdcm::CSComp values[] = {"DERIVED","SECONDARY"}; atimagetype.SetValues(values,2); } header.Replace(atimagetype.GetAsDataElement()); // sop class uid gdcm::UIDGenerator uid; uid.SetRoot("1.2.840.10008.5.1.4.1.1.7"); gdcm::Attribute<0x0008,0x0016> atsopclass; if (!emptydict && !header.GetDataElement(atsopclass.GetTag()).IsEmpty()) { atsopclass.SetFromDataElement(header.GetDataElement(atsopclass.GetTag())); } else { atsopclass.SetValue(uid.GetRoot()); } header.Replace(atsopclass.GetAsDataElement()); // sop instance uid uid.SetRoot(uid.GetGDCMUID()); gdcm::Attribute<0x0008,0x0018> atsopinstance; if (!emptydict && !header.GetDataElement(atsopinstance.GetTag()).IsEmpty()) { atsopinstance.SetFromDataElement(header.GetDataElement(atsopinstance.GetTag())); } else { atsopinstance.SetValue(uid.Generate()); } header.Replace(atsopinstance.GetAsDataElement()); // study instance uid gdcm::Attribute<0x0020,0x000d> atstudy; if (!emptydict && !header.GetDataElement(atstudy.GetTag()).IsEmpty()) { atstudy.SetFromDataElement(header.GetDataElement(atstudy.GetTag())); } else { atstudy.SetValue(uid.Generate()); } header.Replace(atstudy.GetAsDataElement()); // series instance uid gdcm::Attribute<0x0020,0x000e> atserie; if (!emptydict && !header.GetDataElement(atserie.GetTag()).IsEmpty()) { atserie.SetFromDataElement(header.GetDataElement(atserie.GetTag())); } else { atserie.SetValue(uid.Generate()); } header.Replace(atserie.GetAsDataElement()); // following attributes are always replaced // comments gdcm::Attribute<0x0020,0x4000> atc; const std::string v(Version::GetITKVersion()); const std::string g(gdcm::Version::GetVersion()); const std::string c = "MevisIO: ITK " + v + " GDCM " + g; if (atc.GetValue().empty()) { atc.SetValue(c); header.Replace(atc.GetAsDataElement()); } // dimension - columns gdcm::Attribute<0x0028,0x0011> atdc; atdc.SetValue(m_Dimensions[0]); header.Replace(atdc.GetAsDataElement()); // dimension - row gdcm::Attribute<0x0028,0x0010> atdr; atdr.SetValue(m_Dimensions[1]); header.Replace(atdr.GetAsDataElement()); // number of frames gdcm::Attribute<0x0028,0x0008> atnf; if (this->GetNumberOfDimensions() == 2) { atnf.SetValue(1); } else if (this->GetNumberOfDimensions() == 3) { atnf.SetValue(m_Dimensions[2]); } header.Replace(atnf.GetAsDataElement()); // spacing gdcm::Attribute<0x0028,0x0030> atps; atps.SetValue(m_Spacing[0],0); atps.SetValue(m_Spacing[1],1); header.Replace(atps.GetAsDataElement()); // spacing between slices gdcm::Attribute<0x0018,0x0088> atss; if (m_Spacing.size() > 2) { atss.SetValue(m_Spacing[2]); } else { atss.SetValue(1.0); } header.Replace(atss.GetAsDataElement()); // samples per pixel switch(this->GetPixelType()) { case SCALAR: { // number of components should be one if (this->GetNumberOfComponents() != 1) { std::cout << "mevisIO: nr of Components should be 1 for SCALAR" << std::endl; return; } gdcm::Attribute<0x0028,0x0002> atsamples; atsamples.SetValue(1); header.Replace(atsamples.GetAsDataElement()); } break; default: std::cout << "mevisIO: only SCALAR pixeltypes supported" << std::endl; return; } // bits allocated, stored, high // default is always 16 bits, only for pixeltype with are shorter unsigned int nbits(16); bool sign(false); switch(this->GetComponentType()) { case UCHAR: { nbits = 8; sign = false; m_EstimatedMinimum = 0; m_EstimatedMaximum = 255; }break; case CHAR: { nbits = 8; sign = true; m_EstimatedMinimum = -128; m_EstimatedMaximum = 127; }break; case USHORT: { nbits = 16; sign = false; m_EstimatedMinimum = 0; m_EstimatedMaximum = 4095; }break; case SHORT: { nbits = 16; sign = true; m_EstimatedMinimum = -1024; m_EstimatedMaximum = 3095; }break; case UINT: { nbits = 16; sign = false; m_EstimatedMinimum = 0; m_EstimatedMaximum = 4095; }break; case INT: { nbits = 16; sign = true; m_EstimatedMinimum = -1024; m_EstimatedMaximum = 3095; }break; case FLOAT: { nbits = 16; sign = true; m_EstimatedMinimum = -1024; m_EstimatedMaximum = 3095; }break; default: { std::cout << "mevisIO: error writing dcm-file unsupported component type" << std::endl; return; } } // bits allocated gdcm::Attribute<0x0028,0x0100> atbitsalloc; atbitsalloc.SetValue(nbits); header.Replace(atbitsalloc.GetAsDataElement()); // bits stored gdcm::Attribute<0x0028,0x0101> atbitsstored; atbitsstored.SetValue(nbits); header.Replace(atbitsstored.GetAsDataElement()); // high bit gdcm::Attribute<0x0028,0x0102> atbitshigh; atbitshigh.SetValue(nbits-1); header.Replace(atbitshigh.GetAsDataElement()); // pixelrepresentation (sign) gdcm::Attribute<0x0028,0x0103> atpixel; if (sign) { atpixel.SetValue(1); } else { atpixel.SetValue(0); } header.Replace(atpixel.GetAsDataElement()); // min gdcm::Attribute<0x0028,0x0106, gdcm::VR::SS, gdcm::VM::VM1> atmin; if (!emptydict && !header.GetDataElement(atmin.GetTag()).IsEmpty()) { atmin.SetFromDataElement(header.GetDataElement(atmin.GetTag())); m_EstimatedMinimum = atmin.GetValue(); } else { atmin.SetValue(m_EstimatedMinimum); } header.Replace(atmin.GetAsDataElement()); // max gdcm::Attribute<0x0028,0x0107, gdcm::VR::SS, gdcm::VM::VM1> atmax; if (!emptydict && !header.GetDataElement(atmax.GetTag()).IsEmpty()) { atmax.SetFromDataElement(header.GetDataElement(atmax.GetTag())); m_EstimatedMaximum = atmax.GetValue(); } else { atmax.SetValue(m_EstimatedMaximum); } header.Replace(atmax.GetAsDataElement()); // position (origin) gdcm::Attribute<0x0020,0x0032> atpp; atpp.SetValue(m_Origin[0],0); atpp.SetValue(m_Origin[1],1); if (m_Origin.size() > 2) { atpp.SetValue(m_Origin[2],2); } else { atpp.SetValue(0,2); } header.Replace(atpp.GetAsDataElement()); // orientation gdcm::Attribute<0x0020,0x0037> atio; std::vector<double> row(3),col(3); row = this->GetDirection(0); col = this->GetDirection(1); atio.SetValue(row[0],0); atio.SetValue(row[1],1); if (row.size() > 2) { atio.SetValue(row[2],2); } else { atio.SetValue(0,2); } atio.SetValue(col[0],3); atio.SetValue(col[1],4); if (col.size() > 2) { atio.SetValue(col[2],5); } else { atio.SetValue( 0.0, 5); } header.Replace(atio.GetAsDataElement()); writer.SetFileName(m_DcmFileName.c_str()); if (!writer.Write()) { std::cout << "mevisIO: error writing dcm header file" << std::endl; } //TIFF // //default using compression (note that values from // reading an tiff image are not stored, like // dcm header is) //default minisblack //default tiled m_TIFFImage = TIFFOpen(m_TiffFileName.c_str(),"w"); if (!m_TIFFImage) { itkExceptionMacro(<< "mevisIO: error opening tiff file for writing"); } // software comment if (!TIFFSetField(m_TIFFImage, TIFFTAG_SOFTWARE,c.c_str())) { std::cout << "mevisIO: error setting SOFTWARE" << std::endl; } // set sizes m_Width = m_Dimensions[0]; if (!TIFFSetField(m_TIFFImage, TIFFTAG_IMAGEWIDTH, m_Width)) { std::cout << "mevisIO: error setting IMAGEWIDTH" << std::endl; } m_Length = m_Dimensions[1]; if (!TIFFSetField(m_TIFFImage, TIFFTAG_IMAGELENGTH, m_Length)) { std::cout << "mevisIO: error setting IMAGELENGTH" << std::endl; } // dimensions if (m_NumberOfDimensions == 2 || (m_NumberOfDimensions == 3 && m_Dimensions[2] == 1)) { m_TIFFDimension = 2; m_Depth = 0; } else if (m_NumberOfDimensions == 3) { m_TIFFDimension = 3; m_Depth = m_Dimensions[2]; if (!TIFFSetField(m_TIFFImage, TIFFTAG_IMAGEDEPTH, m_Depth)) { std::cout << "mevisIO: error setting IMAGEDEPTH" << std::endl; } } // photometric (default min-is-black) if (!TIFFSetField(m_TIFFImage, TIFFTAG_PHOTOMETRIC,PHOTOMETRIC_MINISBLACK)) { std::cout << "mevisIO: error setting PHOTOMETRIC" << std::endl; } // minimumn if (sign) { if (!TIFFSetField(m_TIFFImage, TIFFTAG_SMINSAMPLEVALUE,m_EstimatedMinimum)) { std::cout << "mevisIO: error setting SMINSAMPLEVALUE" << std::endl; } } else { if (!TIFFSetField(m_TIFFImage, TIFFTAG_MINSAMPLEVALUE,static_cast<unsigned int>(m_EstimatedMinimum))) { std::cout << "mevisIO: error setting MINSAMPLEVALUE" << std::endl; } } // maximum if (sign) { if (!TIFFSetField(m_TIFFImage, TIFFTAG_SMAXSAMPLEVALUE,m_EstimatedMaximum)) { std::cout << "mevisIO: error setting SMAXSAMPLEVALUE" << std::endl; } } else { if (!TIFFSetField(m_TIFFImage,TIFFTAG_MAXSAMPLEVALUE,static_cast<unsigned int>(m_EstimatedMaximum))) { std::cout << "mevisIO: error setting MAXSAMPLEVALUE" << std::endl; } } // pixeltype switch(this->GetPixelType()) { case SCALAR: { // number of components should be one if (this->GetNumberOfComponents() != 1) { std::cout << "mevisIO: nr of Components should be 1 for SCALAR" << std::endl; return; } if (!TIFFSetField(m_TIFFImage, TIFFTAG_SAMPLESPERPIXEL, 1)) { std::cout << "mevisIO: error setting SAMPLESPERPIXEL" << std::endl; } } break; default: std::cout << "mevisIO: only SCALAR pixeltypes supported" << std::endl; return; } // componenttype bool suc(false); switch(this->GetComponentType()) { case UCHAR: { m_BitsPerSample = 8; suc = TIFFSetField(m_TIFFImage, TIFFTAG_SAMPLEFORMAT, 1); }break; case CHAR: { m_BitsPerSample = 8; suc = TIFFSetField(m_TIFFImage, TIFFTAG_SAMPLEFORMAT, 2); }break; case USHORT: { m_BitsPerSample = 8 * sizeof(unsigned short); suc = TIFFSetField(m_TIFFImage, TIFFTAG_SAMPLEFORMAT, 1); }break; case SHORT: { m_BitsPerSample = 8 * sizeof(short); suc = TIFFSetField(m_TIFFImage, TIFFTAG_SAMPLEFORMAT, 2); }break; case UINT: { m_BitsPerSample = 8 * sizeof(unsigned int); suc = TIFFSetField(m_TIFFImage, TIFFTAG_SAMPLEFORMAT, 1); }break; case INT: { m_BitsPerSample = 8 * sizeof(int); suc = TIFFSetField(m_TIFFImage, TIFFTAG_SAMPLEFORMAT, 2); }break; case FLOAT: { m_BitsPerSample = 8 * sizeof(float); suc = TIFFSetField(m_TIFFImage, TIFFTAG_SAMPLEFORMAT, 3); }break; default: { std::cout << "mevisIO: unsupported component type" << std::endl; return; } } if (!suc) { std::cout << "mevisIO: error setting SAMPLEFORMAT" << std::endl; } if (!TIFFSetField(m_TIFFImage, TIFFTAG_BITSPERSAMPLE, m_BitsPerSample)) { std::cout << "mevisIO: error setting BITSPERSAMPLE " << std::endl; } // compression, default always using lzw (overriding // member values) // 1 none // 2 ccit // 5 lzw // 32773 packbits if (!TIFFSetField(m_TIFFImage, TIFFTAG_COMPRESSION, 5)) { std::cout << "mevisIO: error setting COMPRESSION" << std::endl; } // resolution (always assuming cm) if (!TIFFSetField(m_TIFFImage, TIFFTAG_RESOLUTIONUNIT, RESUNIT_CENTIMETER)) { std::cout << "mevisIO: error setting RESOLUTIONUNIT" << std::endl; } if (!TIFFSetField(m_TIFFImage, TIFFTAG_XRESOLUTION, 10.0/m_Spacing[0])) { std::cout << "mevisIO: error setting XRESOLUTION " << std::endl; } if (!TIFFSetField(m_TIFFImage, TIFFTAG_YRESOLUTION, 10.0/m_Spacing[1])) { std::cout << "mevisIO: error setting XRESOLUTION " << std::endl; } // setting tilespecs m_IsTiled = true; // default if (m_NumberOfDimensions == 2 || (m_NumberOfDimensions == 3 && m_Dimensions[2] == 1)) { m_TileDepth = 0; } else { m_TileDepth = 1; if (!TIFFSetField(m_TIFFImage,TIFFTAG_TILEDEPTH,m_TileDepth)) { std::cout << "mevisIO: error setting TILEDEPTH" << std::endl; } } // following function adjust tilesizes accordingly // always set the tile smaller than the image size // (which usually is a reasonable assumption, since // the images we're dealing with are usually large) // defaults (multiple of 16) m_TileWidth = 128; m_TileLength = 128; bool smallimg(false); if (m_Width < 16) { smallimg = true; m_TileWidth = 16; } else { while (m_TileWidth > m_Width) { m_TileWidth -= 16; } } if (m_Length < 16) { smallimg = true; m_TileLength = 16; } else { while (m_TileLength > m_Length) { m_TileLength -= 16; } } // function below makes the tile sizes a multiple of 16 // but does not consider imagelength/width, therefore skipped // TIFFDefaultTileSize(m_TIFFImage,&m_TileWidth,&m_TileLength); if (!TIFFSetField(m_TIFFImage, TIFFTAG_TILEWIDTH, m_TileWidth)) { std::cout << "mevisIO: error setting TILEWIDTH, m_TileWidth" << std::endl; } if (!TIFFSetField(m_TIFFImage, TIFFTAG_TILELENGTH, m_TileLength)) { std::cout << "mevisIO: error setting TILELENGTH, m_TileLength" << std::endl; } // now filling the image with buffer provided // the provided buffer is one dimensional array, // we apply the same routines as for reading the image // except, no boundary checking is required for writing // the tiles. Boundary checking on the input pointer to // prevent assessing memblocks outside the array if (smallimg) { // We consider images smaller than 16x16xz as a special // case, but selecting tile as layout is really not the best // choice! For robustness, should also be implemented, but for // now left open. std::cout << "mevisIO: image x,y smaller than tilesize (16)! Consider" << std::endl; std::cout << " different layout for tif (eg scanline layout)" << std::endl; TIFFClose(m_TIFFImage); return; } else { const unsigned int tilesize = TIFFTileSize(m_TIFFImage); const unsigned int tilerowbytes = TIFFTileRowSize(m_TIFFImage); const unsigned int bytespersample = m_BitsPerSample/8; const unsigned char *vol = reinterpret_cast<const unsigned char*>(buffer); unsigned char *tilebuf = static_cast<unsigned char*>(_TIFFmalloc(tilesize)); // is volume direction a multiple of tiledirection? const bool mx = ( m_Width%m_TileWidth == 0) ? true: false; const bool my = ( m_Length%m_TileLength == 0) ? true : false; for (unsigned int z0 = 0; z0 < (m_TIFFDimension == 3 ? m_Depth:1); z0++) { for (unsigned int y0 = 0; y0 < (my ? m_Length : m_Length-m_TileLength); y0 += m_TileLength) for (unsigned int x0 = 0; x0 < (mx ? m_Width : m_Width-m_TileWidth); x0 += m_TileWidth) { // set bufferpointer to begin of tile const unsigned char * pv = vol; const unsigned int p = z0 * m_Length * m_Width + y0 * m_Width + x0; pv += p * bytespersample; // fill tile unsigned char * pb = tilebuf; for (unsigned int r=0; r<m_TileLength; ++r) { memcpy(pb,pv,tilerowbytes); pv += m_Width * bytespersample; pb += tilerowbytes; } // write tile if (TIFFWriteTile(m_TIFFImage, tilebuf,x0,y0,z0,0)< 0) { std::cout << "mevisIO: error writing tile " << std::endl; _TIFFfree(tilebuf); TIFFClose(m_TIFFImage); return; } } // boundaries if (!mx) { // x is fixed const unsigned lenx = m_Width%m_TileWidth; const unsigned int x0 = m_Width - lenx; const unsigned int tilexbytes = lenx * bytespersample; for (unsigned int y0 = 0; y0 < (my ? m_Length: m_Length - m_TileLength); y0 += m_TileLength) { const unsigned char * pv = vol; const unsigned int p = z0 * m_Length * m_Width + y0 * m_Width + x0; pv += p * bytespersample; unsigned char * pb = tilebuf; memset (pb,0,tilesize); // fill tile for (unsigned int r = 0; r<m_TileLength; ++r) { memcpy(pb,pv,tilexbytes); pv += m_Width * bytespersample; pb += tilerowbytes; } if (TIFFWriteTile(m_TIFFImage, tilebuf, x0, y0, z0, 0) < 0) { std::cout << "mevisIO: error writing tile (ydirection)" << std::endl; _TIFFfree(tilebuf); TIFFClose(m_TIFFImage); return; } } } if (!my) { const unsigned leny = m_Length%m_TileLength; const unsigned int y0 = m_Length - leny; for (unsigned int x0 = 0; x0 < (mx ? m_Width : m_Width-m_TileWidth); x0 += m_TileWidth) { const unsigned char * pv = vol; const unsigned int p = z0 * m_Length * m_Width + y0 * m_Width + x0; pv += p * bytespersample; unsigned char * pb = tilebuf; memset (pb,0,tilesize); for (unsigned int r = 0; r<leny; ++r) { memcpy(pb,pv,tilerowbytes); pv += m_Width * bytespersample; pb += tilerowbytes; } if (TIFFWriteTile(m_TIFFImage, tilebuf, x0, y0, z0, 0) < 0) { std::cout << "mevisIO: error writing tile (x-direction)" << std::endl; _TIFFfree(tilebuf); TIFFClose(m_TIFFImage); return; } } } if (!mx && !my) { // x0,y0 is fixed const unsigned lenx = m_Width%m_TileWidth; const unsigned int x0 = m_Width - lenx; const unsigned int tilexbytes = lenx * bytespersample; const unsigned leny = m_Length%m_TileLength; const unsigned int y0 = m_Length - leny; const unsigned char * pv = vol; const unsigned int p = z0 * m_Length * m_Width + y0 * m_Width + x0; pv += p * bytespersample; unsigned char * pb = tilebuf; memset (pb,0,tilesize); for (unsigned int r = 0; r<leny; ++r) { memcpy(pb,pv,tilexbytes); pv += m_Width * bytespersample; pb += tilerowbytes; } if (TIFFWriteTile(m_TIFFImage, tilebuf, x0, y0, z0, 0) < 0) { std::cout << "mevisIO: error writing tile (corner bottom)" << std::endl; _TIFFfree(tilebuf); TIFFClose(m_TIFFImage); return; } } } // end z _TIFFfree(tilebuf); } TIFFClose(m_TIFFImage); return; } } // end namespace itk
[ [ [ 1, 1866 ] ] ]
5edbd44b6076e544fc449859dcbd4c8fbaca1efa
c0bd82eb640d8594f2d2b76262566288676b8395
/src/game/AddonMgr.cpp
c6f174837d69f59015c813956cad58d85d333ca8
[ "FSFUL" ]
permissive
vata/solution
4c6551b9253d8f23ad5e72f4a96fc80e55e583c9
774fca057d12a906128f9231831ae2e10a947da6
refs/heads/master
2021-01-10T02:08:50.032837
2007-11-13T22:01:17
2007-11-13T22:01:17
45,352,930
0
1
null
null
null
null
UTF-8
C++
false
false
9,593
cpp
// Copyright (C) 2004 WoW Daemon // Copyright (C) 2006 Burlex // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "StdAfx.h" initialiseSingleton( AddonMgr ); //#define DEBUG_PRINT_ADDON_PACKET // Prints out recieved addon packet when char logging in // Capt: hacky key static uint8 PublicKey[265] = { 0x02, 0x01, 0x01, 0xC3, 0x5B, 0x50, 0x84, 0xB9, 0x3E, 0x32, 0x42, 0x8C, 0xD0, 0xC7, 0x48, 0xFA, 0x0E, 0x5D, 0x54, 0x5A, 0xA3, 0x0E, 0x14, 0xBA, 0x9E, 0x0D, 0xB9, 0x5D, 0x8B, 0xEE, 0xB6, 0x84, 0x93, 0x45, 0x75, 0xFF, 0x31, 0xFE, 0x2F, 0x64, 0x3F, 0x3D, 0x6D, 0x07, 0xD9, 0x44, 0x9B, 0x40, 0x85, 0x59, 0x34, 0x4E, 0x10, 0xE1, 0xE7, 0x43, 0x69, 0xEF, 0x7C, 0x16, 0xFC, 0xB4, 0xED, 0x1B, 0x95, 0x28, 0xA8, 0x23, 0x76, 0x51, 0x31, 0x57, 0x30, 0x2B, 0x79, 0x08, 0x50, 0x10, 0x1C, 0x4A, 0x1A, 0x2C, 0xC8, 0x8B, 0x8F, 0x05, 0x2D, 0x22, 0x3D, 0xDB, 0x5A, 0x24, 0x7A, 0x0F, 0x13, 0x50, 0x37, 0x8F, 0x5A, 0xCC, 0x9E, 0x04, 0x44, 0x0E, 0x87, 0x01, 0xD4, 0xA3, 0x15, 0x94, 0x16, 0x34, 0xC6, 0xC2, 0xC3, 0xFB, 0x49, 0xFE, 0xE1, 0xF9, 0xDA, 0x8C, 0x50, 0x3C, 0xBE, 0x2C, 0xBB, 0x57, 0xED, 0x46, 0xB9, 0xAD, 0x8B, 0xC6, 0xDF, 0x0E, 0xD6, 0x0F, 0xBE, 0x80, 0xB3, 0x8B, 0x1E, 0x77, 0xCF, 0xAD, 0x22, 0xCF, 0xB7, 0x4B, 0xCF, 0xFB, 0xF0, 0x6B, 0x11, 0x45, 0x2D, 0x7A, 0x81, 0x18, 0xF2, 0x92, 0x7E, 0x98, 0x56, 0x5D, 0x5E, 0x69, 0x72, 0x0A, 0x0D, 0x03, 0x0A, 0x85, 0xA2, 0x85, 0x9C, 0xCB, 0xFB, 0x56, 0x6E, 0x8F, 0x44, 0xBB, 0x8F, 0x02, 0x22, 0x68, 0x63, 0x97, 0xBC, 0x85, 0xBA, 0xA8, 0xF7, 0xB5, 0x40, 0x68, 0x3C, 0x77, 0x86, 0x6F, 0x4B, 0xD7, 0x88, 0xCA, 0x8A, 0xD7, 0xCE, 0x36, 0xF0, 0x45, 0x6E, 0xD5, 0x64, 0x79, 0x0F, 0x17, 0xFC, 0x64, 0xDD, 0x10, 0x6F, 0xF3, 0xF5, 0xE0, 0xA6, 0xC3, 0xFB, 0x1B, 0x8C, 0x29, 0xEF, 0x8E, 0xE5, 0x34, 0xCB, 0xD1, 0x2A, 0xCE, 0x79, 0xC3, 0x9A, 0x0D, 0x36, 0xEA, 0x01, 0xE0, 0xAA, 0x91, 0x20, 0x54, 0xF0, 0x72, 0xD8, 0x1E, 0xC7, 0x89, 0xD2, 0x00, 0x00, 0x00, 0x00, 0x00}; AddonMgr::AddonMgr() { KnownAddons.clear(); } AddonMgr::~AddonMgr() { std::map<std::string, AddonEntry*>::iterator itr; for(itr = KnownAddons.begin(); itr!=KnownAddons.end(); ++itr) { delete itr->second; } KnownAddons.clear(); } bool AddonMgr::IsAddonBanned(uint64 crc, std::string name) { return false; // bleh needs work } bool AddonMgr::IsAddonBanned(std::string name, uint64 crc) { std::map<std::string,AddonEntry*>::iterator i = KnownAddons.find(name); if(i != KnownAddons.end()) { if(i->second->banned) { sLog.outDebug("Addon %s is banned.", name.c_str()); return true; } } else { // New addon. It'll be saved to db at server shutdown. AddonEntry *ent = new AddonEntry; ent->name = name; ent->crc = crc; ent->banned = false; // by default.. we can change this I guess.. ent->isNew = true; ent->showinlist = true; sLog.outDebug("Discovered new addon %s sent by client.", name.c_str()); KnownAddons[ent->name] = ent; } return false; } bool AddonMgr::ShouldShowInList(std::string name) { std::map<std::string,AddonEntry*>::iterator i = KnownAddons.find(name); if(i != KnownAddons.end()) { if(i->second->showinlist) return true; else return false; } else { // New addon. It'll be saved to db at server shutdown. AddonEntry *ent = new AddonEntry; ent->name = name; ent->crc = 0; ent->banned = false; // by default.. we can change this I guess.. ent->isNew = true; ent->showinlist = true; sLog.outDebug("Discovered new addon %s sent by client.", name.c_str()); KnownAddons[ent->name] = ent; } return true; } void AddonMgr::SendAddonInfoPacket(WorldPacket *source, uint32 pos, WorldSession *m_session) { WorldPacket returnpacket; returnpacket.Initialize(SMSG_ADDON_INFO); // SMSG_ADDON_INFO uint32 realsize; try { *source >> realsize; } catch (ByteBuffer::error &) { sLog.outDebug("Warning: Incomplete auth session sent."); return; } uint32 position = source->rpos(); ByteBuffer unpacked; unpacked.resize(realsize); if((position + 5) > source->size()) { // we shouldnt get here.. but just in case this will stop any crash here. sLog.outDebug("Warning: Incomplete auth session sent."); return; } int32 result; result = uncompress((uint8*)unpacked.contents(), &realsize, (uint8*)(*source).contents() + position, (*source).size() - position); if(result != Z_OK) { sLog.outError("Decompression of addon section of CMSG_AUTH_SESSION failed."); return; } sLog.outDetail("Decompression of addon section of CMSG_AUTH_SESSION succeeded."); uint8 Enable; // based on the parsed files from retool uint32 crc; uint32 unknown; std::string name; uint32 p = unpacked.rpos(); while(p != unpacked.size()) // make sure theres always room, otherwise *BAM* crash. { unpacked >> name; unpacked >> Enable; unpacked >> crc; unpacked >> unknown; // Capt: Hacky fix, Yea I know its a hacky fix I will make a proper handler one's I got the crc crap if (crc != 0x4C1C776D) // CRC of public key version 2.0.1 returnpacket.append(PublicKey,264); // part of the hacky fix else returnpacket << uint8(0x02) << uint8(0x01) << uint8(0x00) << uint32(0) << uint8(0); /*if(!AppendPublicKey(returnpacket, name, crc)) returnpacket << uint8(1) << uint8(0) << uint8(0);*/ p = unpacked.rpos(); } m_session->SendPacket(&returnpacket); } bool AddonMgr::AppendPublicKey(WorldPacket& data, string AddonName, uint32 CRC) { if(CRC == 0x4C1C776D) { // Open public key file with that addon map<string, ByteBuffer>::iterator itr = AddonData.find(AddonName); if(itr != AddonData.end()) data.append(itr->second); else { // open the file char path[500]; sprintf(path, "addons\\%s.pub", AddonName.c_str()); FILE * f = fopen(path, "rb"); if(f != 0) { // read the file into a bytebuffer ByteBuffer buf; fseek(f, 0, SEEK_END); uint32 length = 264/*ftell(f)*/; fseek(f, 0, SEEK_SET); buf.resize(length); fread((void*)buf.contents(), length, 1, f); fclose(f); AddonData[AddonName] = buf; data.append(buf); } else { ByteBuffer buf; buf.append(PublicKey, 264); AddonData[AddonName] = buf; data.append(buf); } } return true; } return false; } void AddonMgr::LoadFromDB() { QueryResult *result = sDatabase.Query("SELECT * FROM clientaddons"); if(!result) { sLog.outString("Query failed: SELECT * FROM clientaddons"); return; } uint32 total =(uint32) result->GetRowCount(); int num = 0; do { Field *field = result->Fetch(); AddonEntry *ent = new AddonEntry; ent->name = field[1].GetString(); ent->crc = field[2].GetUInt64(); ent->banned = field[3].GetUInt32(); ent->isNew = false; if(result->GetFieldCount() == 5) // To avoid crashes for stilly nubs who don't update table :P ent->showinlist = field[4].GetUInt32(); KnownAddons[ent->name] = ent; ++num; if(!(num % 5)) SetProgressBar(num, total, "Client Addon Data"); } while(result->NextRow()); delete result; ClearProgressBar(); } void AddonMgr::SaveToDB() { sLog.outString("AddonMgr: Saving any new addons discovered in this session to database."); for(std::map<std::string, AddonEntry*>::iterator itr = KnownAddons.begin();itr!=KnownAddons.end();++itr) { if(itr->second->isNew) { sLog.outDetail("Saving new addon %s", itr->second->name.c_str()); std::stringstream ss; ss << "INSERT INTO clientaddons (name, crc, banned, showinlist) VALUES(\"" << itr->second->name << "\",\"" << itr->second->crc << "\",\"" << itr->second->banned << "\",\"" << itr->second->showinlist << "\");"; sDatabase.Execute(ss.str().c_str()); } } }
[ [ [ 1, 259 ] ] ]
80173f346afbb4bd308c4ed14b8f4f666ac4be81
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Common/Scd/ScExec/SigFlw.h
e8eb1a6ae957f2d13ee26b4786f14e2980d0b8d2
[]
no_license
abcweizhuo/Test3
0f3379e528a543c0d43aad09489b2444a2e0f86d
128a4edcf9a93d36a45e5585b70dee75e4502db4
refs/heads/master
2021-01-17T01:59:39.357645
2008-08-20T00:00:29
2008-08-20T00:00:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,407
h
//================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // $Nokeywords: $ //=========================================================================== // SysCAD Copyright Kenwalt (Pty) Ltd 1992 #ifndef __SIGFLW_H #define __SIGFLW_H #ifndef __SC_DEFS_H #include "sc_defs.h" #endif #ifndef __VECTORS_H #include "vectors.h" #endif #ifndef __SCDTEMPL_H #include "scdtempl.h" #endif #ifndef __EQNSOLVE_H #include "eqnsolve.h" #endif #if defined(__SIGFLW_CPP) #define DllImportExport DllExport #elif !defined(SCEXEC) #define DllImportExport DllImport #else #define DllImportExport #endif // ========================================================================= // // // // ========================================================================= _FWDDEF(CSignalFlowGraph); _FWDDEF(CSFGNodeInfo); _FWDDEF(CSFGNode); _FWDDEF(CSFGEdge); class CSFGEdge { friend class CSignalFlowGraph; friend class CSFGNode; friend class CSFGEdgeList; protected: CSFGNode *pSrcNode, *pDstNode; public: CSFGEdge() { pSrcNode=pDstNode=NULL; }; ~CSFGEdge() { }; }; //------------------------------------------------------------------------- class CSFGEdgeList : public CSCDList<CSFGEdge*, CSFGEdge*> { }; typedef CSCDPtrListIter<CSFGEdgeList, CSFGEdge*> CSFGEdgeIter; typedef CSCDPtrListIterWithPos<CSFGEdgeList, CSFGEdge*> CSFGEdgeIterPos; //------------------------------------------------------------------------- class DllImportExport CSFGNodeInfo { friend class CSignalFlowGraph; protected: CSFGNode* m_pNode; public: CSFGNodeInfo() { m_pNode=NULL;}; virtual LPCTSTR SFGNodeTag(TaggedObject * pRefTo=NULL)=0; virtual CSFGNodeInfo * SFGNodePtr()=0; }; class CSFGNodeInfoList : public CSCDList<CSFGNodeInfo*, CSFGNodeInfo*> { }; typedef CSCDPtrListIter<CSFGNodeInfoList, CSFGNodeInfo*> CSFGNodeInfoIter; typedef CSCDPtrListIterWithPos<CSFGNodeInfoList, CSFGNodeInfo*> CSFGNodeInfoIterPos; //------------------------------------------------------------------------- class CSFGNode { friend class CSignalFlowGraph; friend class CSFGEdge; friend class CSFGEdgeList; protected: CSFGEdgeList EdgesIn, EdgesOut; CSFGNodeInfo *pInfo; byte iPriority; public: CSFGNode() { pInfo=NULL; }; CSFGNode(CSFGNodeInfo * Info) { pInfo=Info; }; virtual ~CSFGNode() { }; // turn this into a polymorphic class for TearVarPosBlk }; //------------------------------------------------------------------------- class CSFGNodeList : public CSCDList<CSFGNode*, CSFGNode*> { }; typedef CSCDPtrListIter<CSFGNodeList, CSFGNode*> CSFGNodeIter; typedef CSCDPtrListIterWithPos<CSFGNodeList, CSFGNode*> CSFGNodeIterPos; //------------------------------------------------------------------------- class DllImportExport CSignalFlowGraph { friend class CSFGNodeInfo; friend class CSFGNode; friend class CSFGEdge; protected: CSFGNodeList Nodes[TP_Last+1], FreeNodes; CSFGEdgeList Edges, FreeEdges; //CFlangeList TornNodes; CSFGNodeInfoList TornNodes; public: CSignalFlowGraph(); ~CSignalFlowGraph(); void AddNode(CSFGNodeInfo* pTObj, byte iPriority); void AddEdge(CSFGNodeInfo* pSrcObj, CSFGNodeInfo* pDstObj, char*pViaTag); void Clear(); int TearDirect(); // returns the Numbers of Tear CSFGNodeInfoList & TearNodeList() { return TornNodes; }; int TearCount() { return TornNodes.GetCount();}; protected: CSFGNode* AllocNode(); CSFGEdge* AllocEdge(); void FreeNode(CSFGNode* pNode); void FreeEdge(CSFGEdge* pEdge); void DelNode(CSFGNode* pNode); void DelEdge(CSFGEdge* pEdge); void AddEdge(CSFGNode* pSrcNd, CSFGNode* pDstNd, char*pViaTag); void CountEdges(CSFGNode* pNode, int &NIn, int &NOut); flag SelfLoop(CSFGNode* pNode); void ReduceEssen(CSFGNode* pNode); void ReduceNonEssen(CSFGNode* pNode); }; // ========================================================================= #undef DllImportExport #endif
[ [ [ 1, 23 ], [ 25, 151 ] ], [ [ 24, 24 ] ] ]
1cc7d3fd76acb4ffe9cece443001c4801b849514
12203ea9fe0801d613bbb2159d4f69cab3c84816
/Export/cpp/windows/obj/include/ApplicationMain.h
2e133d6d2ff676f00073754d5053ff12e01c6629
[]
no_license
alecmce/haxe_game_of_life
91b5557132043c6e9526254d17fdd9bcea9c5086
35ceb1565e06d12c89481451a7bedbbce20fa871
refs/heads/master
2016-09-16T00:47:24.032302
2011-10-10T12:38:14
2011-10-10T12:38:14
2,547,793
0
0
null
null
null
null
UTF-8
C++
false
false
877
h
#ifndef INCLUDED_ApplicationMain #define INCLUDED_ApplicationMain #ifndef HXCPP_H #include <hxcpp.h> #endif HX_DECLARE_CLASS0(ApplicationMain) class ApplicationMain_obj : public hx::Object{ public: typedef hx::Object super; typedef ApplicationMain_obj OBJ_; ApplicationMain_obj(); Void __construct(); public: static hx::ObjectPtr< ApplicationMain_obj > __new(); static Dynamic __CreateEmpty(); static Dynamic __Create(hx::DynamicArray inArgs); ~ApplicationMain_obj(); HX_DO_RTTI; static void __boot(); static void __register(); void __Mark(HX_MARK_PARAMS); ::String __ToString() const { return HX_CSTRING("ApplicationMain"); } static Void main( ); static Dynamic main_dyn(); static Dynamic getAsset( ::String inName); static Dynamic getAsset_dyn(); }; #endif /* INCLUDED_ApplicationMain */
[ [ [ 1, 39 ] ] ]
d8f6c4d083ecaaf3ac54f8c7a720a4a47e8102a1
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/spirit/test/for_tests.cpp
39a3b2ca40138d1b2f0f42c2f8593fab6f200572
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
4,701
cpp
/*============================================================================= Copyright (c) 2003 Martin Wille http://spirit.sourceforge.net/ Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ // vi:ts=4:sw=4:et // Tests for spirit::for_p // [13-Jan-2003] //////////////////////////////////////////////////////////////////////////////// #define qDebug 0 #include <iostream> #include <cstring> #if qDebug #define SPIRIT_DEBUG #endif #include <string> #include <boost/spirit/core.hpp> #include <boost/spirit/actor/assign_actor.hpp> #include <boost/spirit/dynamic/for.hpp> #include <boost/ref.hpp> #include "impl/string_length.hpp" namespace local { template <typename T> struct var_wrapper : public ::boost::reference_wrapper<T> { typedef ::boost::reference_wrapper<T> parent; explicit inline var_wrapper(T& t) : parent(t) {} inline T& operator()() const { return parent::get(); } }; template <typename T> inline var_wrapper<T> var(T& t) { return var_wrapper<T>(t); } } namespace { template <typename T> class add_actor { public: explicit add_actor(T &ref_) : ref(ref_) {} template <typename T2> void operator()(T2 const &val) const { ref += val; } private: T& ref; }; template <typename T> inline add_actor<T> const add(T& ref) { return add_actor<T>(ref); } } typedef ::boost::spirit::rule<> rule_t; unsigned int test_count = 0; unsigned int error_count = 0; unsigned int iterations_performed; unsigned int iterations_desired; std::string input_matched; //static const unsigned int kError = 999; static const bool good = true; static const bool bad = false; rule_t for_rule; rule_t for_rule2; void test_for ( char const *s, bool succeed, rule_t const &r, unsigned int iterations_expected ) { using namespace std; ++test_count; iterations_performed = 0; ::boost::spirit::parse_info<> m = ::boost::spirit::parse(s, s + test_impl::string_length(s), r); bool result = (succeed==m.full)?good:bad; if (m.full && (m.length != test_impl::string_length(s))) result = bad; result &= iterations_expected == iterations_performed; if (result==good) cout << "PASSED"; else { ++error_count; cout << "FAILED"; } cout << ": \"" << s << "\" ==> "; if (!m.full) cout << "<error>"; else cout << '"' << input_matched << '"'; cout << " " << iterations_performed << " of " << iterations_desired << " iterations\n"; } namespace { void zero() { iterations_performed = 0; } struct inc { inline void operator()() const { ++iterations_performed; } }; struct cmp { inline bool operator()() const { return iterations_performed<iterations_desired; } }; } int main() { using namespace std; using boost::spirit::uint_p; using boost::spirit::for_p; using boost::spirit::assign_a; #if qDebug SPIRIT_DEBUG_RULE(for_rule); SPIRIT_DEBUG_RULE(for_rule2); #endif for_rule = uint_p[assign_a(iterations_desired)] >> ':' >> for_p(&zero, cmp(), inc())["xy"] [assign_a(input_matched)] ; for_rule2 = for_p(&zero, '.', inc())["xy"] [assign_a(input_matched)] ; cout << "/////////////////////////////////////////////////////////\n"; cout << "\n"; cout << " for_p test\n"; cout << "\n"; cout << "/////////////////////////////////////////////////////////\n"; cout << "\n"; test_for("3:xyxyxy", true, for_rule, 3); test_for("3:", false, for_rule, 0); test_for("3:xyxy", false, for_rule, 2); test_for("3:xyxyxyxy", false, for_rule, 3); test_for(".xy.xy.xy", true, for_rule2, 3); test_for(".xy.xy.xy.", false, for_rule2, 3); std::cout << "\n "; if (error_count==0) cout << "All " << test_count << " for_p-tests passed.\n" << "Test concluded successfully\n"; else cout << error_count << " of " << test_count << " for_p-tests failed\n" << "Test failed\n"; return error_count!=0; }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 196 ] ] ]
787d77dfd31faeaab464c626d116fd5fdcb6848f
5dc6c87a7e6459ef8e832774faa4b5ae4363da99
/vis_avs/laser/rl_bren.cpp
60cff329d36a9fd44831b560a09fbc87164ed0f7
[]
no_license
aidinabedi/avs4unity
407603d2fc44bc8b075b54cd0a808250582ee077
9b6327db1d092218e96d8907bd14d68b741dcc4d
refs/heads/master
2021-01-20T15:27:32.449282
2010-12-24T03:28:09
2010-12-24T03:28:09
90,773,183
5
2
null
null
null
null
UTF-8
C++
false
false
5,035
cpp
/* LICENSE ------- Copyright 2005 Nullsoft, Inc. 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 Nullsoft nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "../config.h" #ifdef LASER #include <windows.h> #include <commctrl.h> #include "../r_defs.h" #include "../resource.h" #include <math.h> #define C_THISCLASS CLASER_BrenClass #define MOD_NAME "Render / Brennan\'s Effect" typedef struct { float x, y; } PT; typedef struct { PT pt[4]; } segment; #define BOUND (0.6f) #define NSEG 48 #define VISSEG 6 class C_THISCLASS : public C_RBASE { protected: public: C_THISCLASS(); virtual ~C_THISCLASS(); virtual int render(char visdata[2][2][SAMPLES], int isBeat, int *framebuffer, int *fbout, int w, int h); // returns 1 if fbout has dest virtual char *get_desc() { return MOD_NAME; } virtual HWND conf(HINSTANCE hInstance, HWND hwndParent); virtual void load_config(unsigned char *data, int len); virtual int save_config(unsigned char *data); segment seg[NSEG]; PT d[4]; float phase; int step; }; #define PUT_INT(y) data[pos]=(y)&255; data[pos+1]=(y>>8)&255; data[pos+2]=(y>>16)&255; data[pos+3]=(y>>24)&255 #define GET_INT() (data[pos]|(data[pos+1]<<8)|(data[pos+2]<<16)|(data[pos+3]<<24)) void C_THISCLASS::load_config(unsigned char *data, int len) { int pos=0; } int C_THISCLASS::save_config(unsigned char *data) { int pos=0,x=0; return pos; } float frandom() { return (float)rand() / (float)RAND_MAX; } C_THISCLASS::C_THISCLASS() { int i, j; for (j = 0; j < NSEG; j++) { for (i = 0; i < 4; i++) { // seg[j].pt[i].x = frandom() * 2.0 - 1.0; // seg[j].pt[i].y = frandom() * 2.0 - 1.0; seg[j].pt[i].x = 0.f; seg[j].pt[i].y = 0.f; } } for (i = 0; i < 4; i++) { d[i].x = frandom() * 0.015 + 0.005; d[i].y = frandom() * 0.015 + 0.005; } phase = 0.0; step = 0; } C_THISCLASS::~C_THISCLASS() { } #define PI 3.14159 int C_THISCLASS::render(char visdata[2][2][SAMPLES], int isBeat, int *framebuffer, int *fbout, int w, int h) // returns 1 if fbout has dest { if (isBeat&0x80000000) return 0; LineType l; int i, j; float s; s = sin(phase * 2 * PI)*0.10+0.9; //s = 1.0; //s = 0.8 + isBeat * 0.2; for (i = 0; i < 4; i++) { seg[0].pt[i].x += d[i].x * s; seg[0].pt[i].y += d[i].y * s; if (seg[0].pt[i].x < -BOUND || seg[0].pt[i].x > BOUND) d[i].x = -d[i].x; if (seg[0].pt[i].y < -BOUND || seg[0].pt[i].y > BOUND) d[i].y = -d[i].y; } for (j = 0; j < NSEG; j++) { static PT p; if ((step++ % (NSEG/VISSEG)) != 0) continue; for (i = 0; i < 4; i++) { l.mode=0; l.color=RGB(0, 0, 255); l.x1= seg[j].pt[i].x * s; l.y1= seg[j].pt[i].y * s; l.x2= (p.x)*s; l.y2= (p.y)*s; p = seg[j].pt[i]; g_laser_linelist->AddLine(&l); l.x1 = l.x2; l.y1 = l.y2; l.mode=1; l.color=RGB(0, 255, 0); g_laser_linelist->AddLine(&l); } } for (i = NSEG-1; i > 0; i--) { seg[i] = seg[i-1]; } phase += 0.005f; return 0; } C_RBASE *RLASER_Bren(char *desc) { if (desc) { strcpy(desc,MOD_NAME); return NULL; } return (C_RBASE *) new C_THISCLASS(); } static C_THISCLASS *g_this; static BOOL CALLBACK g_DlgProc(HWND hwndDlg, UINT uMsg, WPARAM wParam,LPARAM lParam) { return 0; } HWND C_THISCLASS::conf(HINSTANCE hInstance, HWND hwndParent) { g_this = this; return 0;//CreateDialog(hInstance,MAKEINTRESOURCE(IDD_CFG_LINE),hwndParent,g_DlgProc); } #endif
[ [ [ 1, 186 ] ] ]
cb3e93ba82a3a870206fada1ff2fde77371393e6
967868cbef4914f2bade9ef8f6c300eb5d14bc57
/Swap/VBlock.hpp
73a053ec06aa5db1b96906147eb07d343e175276
[]
no_license
saminigod/baseclasses-001
159c80d40f69954797f1c695682074b469027ac6
381c27f72583e0401e59eb19260c70ee68f9a64c
refs/heads/master
2023-04-29T13:34:02.754963
2009-10-29T11:22:46
2009-10-29T11:22:46
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
497
hpp
/* Simple Virtual Memory Implementation ================================================== part of the BASE C++ Classes © Vestris Inc., Geneva Switzerland http://www.vestris.com, 1998, All Rights Reserved __________________________________________________ written by Daniel Doubrovkine - [email protected] */ #ifndef BASE_VBLOCK_HPP #define BASE_VBLOCK_HPP #include <platform/include.hpp> #include <Swap/TBlock.hpp> typedef CTBlock<char> CVBlock; #endif
[ [ [ 1, 22 ] ] ]
64038c6c22ab0f4d48764ca5445c6c8806dc1813
f177993b13e97f9fecfc0e751602153824dfef7e
/ImPro/ImProFilters/GSARTagLayoutFilter/GSARTagLayoutFilter.cpp
dd7f45a3aeea823da1706ba66c527644923dea4b
[]
no_license
svn2github/imtophooksln
7bd7412947d6368ce394810f479ebab1557ef356
bacd7f29002135806d0f5047ae47cbad4c03f90e
refs/heads/master
2020-05-20T04:00:56.564124
2010-09-24T09:10:51
2010-09-24T09:10:51
11,787,598
1
0
null
null
null
null
UTF-8
C++
false
false
20,193
cpp
#include "stdafx.h" #include "GSARTagLayoutFilter.h" #include "GSD3DMediaType.h" #include "GSMacro.h" #include "GSMediaType.h" #include "MyMediaSample.h" #include "GSARTagLayoutDisplay.h" #include "highgui.h" extern HMODULE GetModule(); GSARTagLayoutFilter::GSARTagLayoutFilter(IUnknown * pOuter, HRESULT * phr, BOOL ModifiesData) : GSDXMuxFilter(NAME("GSSimpleDX Filter"), 0, CLSID_GSARTagLayoutFilter) { m_bufW = 800; m_bufH = 600; m_FPSLimit = 60; m_pStrategyData = NULL; m_bLayoutChange = TRUE; m_pROIImg = NULL; } GSARTagLayoutFilter::~GSARTagLayoutFilter() { SAFE_DELETE(m_pStrategyData); if (m_pROIImg != NULL) { cvReleaseImage(&m_pROIImg); m_pROIImg = NULL; } } CUnknown *WINAPI GSARTagLayoutFilter::CreateInstance(LPUNKNOWN punk, HRESULT *phr) { ASSERT(phr); // assuming we don't want to modify the data GSARTagLayoutFilter *pNewObject = new GSARTagLayoutFilter(punk, phr, FALSE); if(pNewObject == NULL) { if (phr) *phr = E_OUTOFMEMORY; } return pNewObject; } HRESULT GSARTagLayoutFilter::NonDelegatingQueryInterface(REFIID iid, void **ppv) { if (iid == IID_IGSARTagLayoutFilter) { return GetInterface(static_cast<IGSARTagLayoutFilter*>(this), ppv); } else if (iid == IID_ISpecifyPropertyPages) { return GetInterface( static_cast<ISpecifyPropertyPages*>(this), ppv); } else if (iid == IID_IGSPersist) { return GetInterface(static_cast<IGSPersist*>(this), ppv); } else { // Call the parent class. return __super::NonDelegatingQueryInterface(iid, ppv); } } HRESULT GSARTagLayoutFilter::InitFilter() { HRESULT hr = S_OK; hr = __super::InitFilter(); if (FAILED(hr)) return hr; WCHAR effectPath[MAX_PATH] = {0}; hr = GetEffectFilePath(effectPath, MAX_PATH); if (FAILED(hr)) return hr; hr = initD3D(effectPath, MAX_PATH, m_bufW, m_bufH, 0, 1, 1); if (FAILED(hr)) return hr; return hr; } float GSARTagLayoutFilter::GetFrameRateLimit(IPin* pPin) { CAutoLock lck(&m_csRenderPara); return m_FPSLimit; } HRESULT GSARTagLayoutFilter::CreatePins() { HRESULT hr = S_OK; GSPIN_ACCEPT_MEDIATYPE cfgAccType[] = { GSPIN_ACCEPT_MEDIATYPE(GSMEDIATYPE_FILTER_CONFIG, GSMEDIASUBTYPE_GSARTagLayoutStrategy_CONFIG_PTR, FALSE) }; GSOUTPIN_ACCEPT_MEDIATYPE outcfgAccType[] = { GSOUTPIN_ACCEPT_MEDIATYPE(GSMEDIATYPE_FILTER_CONFIG, GSMEDIASUBTYPE_GSARTagLayout_CONFIG, FALSE, GSREF_ACCEPT_MEDIATYPE, sizeof(GSARTagLayout), 0, 0), GSOUTPIN_ACCEPT_MEDIATYPE(GUID_IMPRO_FeedbackTYPE, GUID_ARLayoutConfigData, FALSE, GSREF_ACCEPT_MEDIATYPE, sizeof(ARLayoutConfigData), 0, 0) }; GSOUTPIN_ACCEPT_MEDIATYPE roiAccType[] = { GSOUTPIN_ACCEPT_MEDIATYPE(GUID_IMPRO_FeedbackTYPE, GUID_ROIData, FALSE, GSREF_ACCEPT_MEDIATYPE, sizeof(ROIData), 0, 0) }; GSOUTPIN_ACCEPT_MEDIATYPE outAccType[] = { GSOUTPIN_ACCEPT_MEDIATYPE(GSMEDIATYPE_GSDX11_SHAREDEVICE_MEDIATYPE, GSMEDIASUBTYPE_GSTEX2D_POINTER, GSFORMAT_DX11TEX2D_DESC, FALSE, GSREF_RENDERTARGET, 0, 0, 0), GSOUTPIN_ACCEPT_MEDIATYPE(GSMEDIATYPE_GSDX11_MEDIATYPE, GSMEDIASUBTYPE_GSTEX2D_POINTER, GSFORMAT_DX11TEX2D_DESC, FALSE, GSREF_RENDERTARGET, 0, 0, 0), GSOUTPIN_ACCEPT_MEDIATYPE(MEDIATYPE_Video, MEDIASUBTYPE_RGB32, FORMAT_VideoInfo, FALSE, GSREF_RENDERTARGET, 0, 0, 0), GSOUTPIN_ACCEPT_MEDIATYPE(MEDIATYPE_Video, MEDIASUBTYPE_RGB32, GUID_NULL, FALSE, GSREF_RENDERTARGET, 0, 0, 0), GSOUTPIN_ACCEPT_MEDIATYPE(MEDIATYPE_Video, MEDIASUBTYPE_ARGB32, FORMAT_VideoInfo, FALSE, GSREF_RENDERTARGET, 0, 0, 0), GSOUTPIN_ACCEPT_MEDIATYPE(MEDIATYPE_Video, MEDIASUBTYPE_ARGB32, GUID_NULL, FALSE, GSREF_RENDERTARGET, 0, 0, 0) }; GSFILTER_INPUTPIN_DESC inputPinDesc[] = { GSFILTER_INPUTPIN_DESC(L"config", 0, GSINPUT_PIN, GSPIN_ACCEPT_MEDIATYPE_GROUP(cfgAccType, ARRAYSIZE(cfgAccType)), GSFILTER_INPUTPIN_FUNCS(GSARTagLayoutFilter::PreReceive_ReceiveConfig, NULL, NULL, NULL, NULL)) }; GSFILTER_OUTPUTPIN_DESC outputPinDesc[] = { GSFILTER_OUTPUTPIN_DESC(L"layout", 0, GSOUTPUT_PIN, GSOUTPIN_ACCEPT_MEDIATYPE_GROUP(outcfgAccType, ARRAYSIZE(outcfgAccType)), GSFILTER_OUTPUTPIN_FUNCS(NULL, NULL)), GSFILTER_OUTPUTPIN_DESC(L"ROI", 0, GSOUTPUT_PIN, GSOUTPIN_ACCEPT_MEDIATYPE_GROUP(roiAccType, ARRAYSIZE(roiAccType)), GSFILTER_OUTPUTPIN_FUNCS(NULL, NULL)) }; GSFILTER_STREAMPIN_DESC streamPinDesc[] = { GSFILTER_STREAMPIN_DESC(L"output", 0, GSSTREAM_PIN, GSOUTPIN_ACCEPT_MEDIATYPE_GROUP(outAccType, ARRAYSIZE(outAccType)), GSFILTER_STREAMPIN_FUNCS(OnFillBuffer, NULL, NULL)) }; hr = _CreatePins(inputPinDesc, ARRAYSIZE(inputPinDesc),outputPinDesc, ARRAYSIZE(outputPinDesc), streamPinDesc, ARRAYSIZE(streamPinDesc)); return hr; } HRESULT GSARTagLayoutFilter::_CreatePins(GSFILTER_INPUTPIN_DESC* inDesc, UINT szIn, GSFILTER_OUTPUTPIN_DESC* outDesc, UINT szOut, GSFILTER_STREAMPIN_DESC* streamDesc, UINT szStream ) { _ClearPins(); HRESULT hr = S_OK; for (int i =0; i < szIn; i++) { GSMuxInputPin* pInputPin = new GSDXMuxInputPin(NAME("GSMuxInputPin"), this, &hr, inDesc[i].pinName); m_pInputPins.push_back(pInputPin); GSFILTER_INPUTPIN_DESC* pInputPinDesc = new GSFILTER_INPUTPIN_DESC(); *pInputPinDesc = inDesc[i]; m_pInputPinDesc.push_back(pInputPinDesc); } for (int i =0; i < szOut; i++) { GSMuxOutputPin* pOutputPin = new GSSourceOutputPin(NAME("GSSourceOutputPin"), this, &hr, outDesc[i].pinName); m_pOutputPins.push_back(pOutputPin); GSFILTER_OUTPUTPIN_DESC* pOutputPinDesc = new GSFILTER_OUTPUTPIN_DESC(); *pOutputPinDesc = outDesc[i]; m_pOutputPinDesc.push_back(pOutputPinDesc); } for (int i =0; i < szStream; i++) { GSMuxStream* pStreamPin = new GSDXMuxStream(NAME("GSMuxStream"), this, &hr, streamDesc[i].pinName); m_pStreamPins.push_back(pStreamPin); GSFILTER_STREAMPIN_DESC* pStreamPinDesc = new GSFILTER_STREAMPIN_DESC(); *pStreamPinDesc = streamDesc[i]; m_pStreamPinDesc.push_back(pStreamPinDesc); } return S_OK; } HRESULT GSARTagLayoutFilter::GetPages(CAUUID *pPages) { pPages->cElems = 1; pPages->pElems = (GUID*)CoTaskMemAlloc(sizeof(GUID)); if (pPages->pElems == NULL) { return E_OUTOFMEMORY; } pPages->pElems[0] = CLSID_GSARTagLayoutFilterProp; return S_OK; } HRESULT GSARTagLayoutFilter::GetName(WCHAR* name, UINT szName) { if (name == NULL) return S_FALSE; FILTER_INFO filterInfo; this->QueryFilterInfo(&filterInfo); wcscpy_s(name, szName, filterInfo.achName); if (filterInfo.pGraph != NULL) { filterInfo.pGraph->Release(); filterInfo.pGraph = NULL; } return S_OK; } HRESULT GSARTagLayoutFilter::SaveToFile(WCHAR* path) { CAutoLock lck(&m_csRenderPara); FILE* filestream = NULL; _wfopen_s(&filestream, path, L"w"); if (filestream == NULL) { return E_FAIL; } float fps = GetFrameRate(); fwprintf_s(filestream, L"%.0f \n", fps); float blackLevel = GetBlackLevel(); fwprintf_s(filestream, L"%.2f \n", blackLevel); fclose(filestream); return S_OK; } HRESULT GSARTagLayoutFilter::LoadFromFile(WCHAR* path) { CAutoLock lck(&m_csRenderPara); HRESULT hr = S_OK; FILE* filestream = NULL; _wfopen_s(&filestream, path, L"r"); if (filestream == NULL) { return E_FAIL; } double fps = 60; fwscanf_s(filestream, L"%lf \n", &fps); double blacklevel = 0.5; fwscanf_s(filestream, L"%lf \n", &blacklevel); fclose(filestream); hr = SetFrameRate(fps); hr = SetBlackLevel(blacklevel); return S_OK; } HRESULT GSARTagLayoutFilter::PreReceive_ReceiveConfig(void* self, IMediaSample *pSample, const IPin* pReceivePin, IMediaSample*& pOutSample) { if (self == NULL || pSample == NULL || pReceivePin == NULL) { return E_FAIL; } GSARTagLayoutFilter* pSelf = (GSARTagLayoutFilter*)(GSMuxFilter*)self; CAutoLock lck(&pSelf->m_csStrategyData); BYTE* pSampleBuf = NULL; pSample->GetPointer(&pSampleBuf); if (pSampleBuf == NULL) return E_FAIL; SAFE_DELETE(pSelf->m_pStrategyData); pSelf->m_pStrategyData = new GSARLayoutStartegyData(); GSARLayoutStartegyData* pSampleData = *(GSARLayoutStartegyData**)pSampleBuf; *pSelf->m_pStrategyData = *pSampleData; return S_OK; } HRESULT GSARTagLayoutFilter::OnFillBuffer(void* self, IMediaSample *pSample, IPin* pPin) { if (self == NULL ||pSample == NULL || pPin == NULL) return E_FAIL; GSARTagLayoutFilter* pSelf = (GSARTagLayoutFilter*)(GSMuxFilter*)self; if (pSelf->m_pD3DDisplay == NULL || pSelf->m_pRenderTargetList.size() <= 0) return E_FAIL; if (pSelf->m_pStreamPins.size() <= 0) return E_FAIL; HRESULT hr = S_OK; { CAutoLock lck(&pSelf->m_csStrategyData); if (pSelf->m_pStrategyData != NULL) { CAutoLock lck4(&pSelf->m_csLayoutChange); BOOL bLayoutChanged = TRUE; hr = ((GSARTagLayoutDisplay*)pSelf->m_pD3DDisplay)->DecideLayout(pSelf->m_pStrategyData->camViews, pSelf->m_pStrategyData->numCamView, pSelf->m_pStrategyData->fingerRects, pSelf->m_pStrategyData->numFingers, bLayoutChanged); pSelf->m_bLayoutChange = pSelf->m_bLayoutChange || bLayoutChanged; SAFE_DELETE(pSelf->m_pStrategyData); if (FAILED(hr)) return hr; } } CAutoLock lck3(&pSelf->m_csRenderPara); GSAutoLock lck0(pSelf->m_pD3DDisplay->GetGSCritSec()); GSAutoLock lck2(pSelf->m_pRenderTargetList.at(0)->GetGSCritSec()); ID3D11RenderTargetView* pRTView = NULL; ID3D11DeviceContext* pDeviceContext = NULL; pDeviceContext = pSelf->m_pD3DDisplay->GetDeviceContext(); hr = pSelf->m_pRenderTargetList.at(0)->GetRenderTargetView(pRTView); if (pRTView == NULL || pDeviceContext == NULL) { return E_FAIL; } hr = pSelf->m_pD3DDisplay->SetRenderTarget(pDeviceContext, pRTView); hr = pSelf->m_pD3DDisplay->Render(); hr = pSelf->m_pD3DDisplay->ResetRenderTarget(pDeviceContext); if (FAILED(hr)) return S_FALSE; CMediaType mt = pSelf->m_pStreamPins.at(0)->CurrentMediaType(); if (IsEqualGUID(*mt.Subtype(), MEDIASUBTYPE_RGB32) || IsEqualGUID(*mt.Subtype(), MEDIASUBTYPE_RGB32)) { hr = pSelf->CopyGSTexture(pSelf->m_pRenderTargetList.at(0), pSelf->m_pOutTextureList.at(0)); if (FAILED(hr)) return hr; hr = pSelf->CopyGSTexture2Sample(pSelf->m_pOutTextureList.at(0), pSample, &mt); } else { hr = pSelf->CopyGSTexture2Sample(pSelf->m_pRenderTargetList.at(0), pSample, &mt); } { CAutoLock lck(&pSelf->m_csStrategyData); if (pSelf->GetLayoutChanged()) { hr = pSelf->SendLayoutData(); if (FAILED(hr)) { return E_FAIL; } pSelf->ComputeROIs(); pSelf->sendROIData(); pSelf->SetLayoutChanged(FALSE); } } return hr; } GS3DDisplay* GSARTagLayoutFilter::Create3DDisplay(UINT bufW, UINT bufH) { HRESULT hr = S_OK; GSARTagLayoutDisplay* pDisplay = new GSARTagLayoutDisplay(bufW, bufH); hr = pDisplay->initARLayout(2, 8, 2, 80); return pDisplay; } GS3DDisplay* GSARTagLayoutFilter::Create3DDisplay(ID3D11Device* pDevice, ID3D11DeviceContext* pDeviceContext, IDXGISwapChain* pSwapChain) { HRESULT hr = S_OK; GSARTagLayoutDisplay* pDisplay = new GSARTagLayoutDisplay(pDevice, pDeviceContext, pSwapChain); hr = pDisplay->initARLayout(2, 8, 2, 80); return pDisplay; } HRESULT GSARTagLayoutFilter::GetEffectFilePath(WCHAR* szPath, UINT szSize) { if (szPath == NULL || szSize == 0) return E_FAIL; swprintf_s(szPath, szSize, L"../../fx/GSARTagLayout.fx"); return S_OK; } HRESULT GSARTagLayoutFilter::SetFrameRate(float fps) { if (fps <= 0) return E_FAIL; CAutoLock lck(&m_csRenderPara); m_FPSLimit = fps; return S_OK; } float GSARTagLayoutFilter::GetFrameRate() { return GetFrameRateLimit(NULL); } HRESULT GSARTagLayoutFilter::DecideLayout(GSBoundingBox2D* camRects, UINT numCamRect, GSBoundingBox2D* fingerRects, UINT numFingerRects, BOOL& bLayoutChanged, float fingerExtend) { if (m_pD3DDisplay == NULL) return E_FAIL; GSAutoLock lck(m_pD3DDisplay->GetGSCritSec()); return ((GSARTagLayoutDisplay*)m_pD3DDisplay)->DecideLayout(camRects, numCamRect, fingerRects, numFingerRects, bLayoutChanged, fingerExtend); } HRESULT GSARTagLayoutFilter::initARLayout(UINT numLevel, UINT intMarkerBits, UINT intBorderBits, float intWidthBits) { if (m_pD3DDisplay == NULL) return E_FAIL; GSAutoLock lck(m_pD3DDisplay->GetGSCritSec()); return ((GSARTagLayoutDisplay*)m_pD3DDisplay)->initARLayout(numLevel, intMarkerBits, intBorderBits, intWidthBits); } int GSARTagLayoutFilter::GetNumMarker() { if (m_pD3DDisplay == NULL) return E_FAIL; GSAutoLock lck(m_pD3DDisplay->GetGSCritSec()); return ((GSARTagLayoutDisplay*)m_pD3DDisplay)->GetNumMarker(); } HRESULT GSARTagLayoutFilter::SetMarkerVisible(int idx, BOOL bVisible) { if (m_pD3DDisplay == NULL) return E_FAIL; GSAutoLock lck(m_pD3DDisplay->GetGSCritSec()); return ((GSARTagLayoutDisplay*)m_pD3DDisplay)->SetMarkerVisible(idx, bVisible); } HRESULT GSARTagLayoutFilter::SetMarkerVisibleByID(int id, BOOL bVisible) { if (m_pD3DDisplay == NULL) return E_FAIL; GSAutoLock lck(m_pD3DDisplay->GetGSCritSec()); return ((GSARTagLayoutDisplay*)m_pD3DDisplay)->SetMarkerVisibleByID(id, bVisible); } int GSARTagLayoutFilter::GetMarkerID(int idx) { if (m_pD3DDisplay == NULL) return E_FAIL; GSAutoLock lck(m_pD3DDisplay->GetGSCritSec()); return ((GSARTagLayoutDisplay*)m_pD3DDisplay)->GetMarkerID(idx); } float GSARTagLayoutFilter::GetBlackLevel() { if (m_pD3DDisplay == NULL) return E_FAIL; GSAutoLock lck(m_pD3DDisplay->GetGSCritSec()); return ((GSARTagLayoutDisplay*)m_pD3DDisplay)->GetBlackLevel(); } HRESULT GSARTagLayoutFilter::SetBlackLevel(float level) { if (m_pD3DDisplay == NULL) return E_FAIL; GSAutoLock lck(m_pD3DDisplay->GetGSCritSec()); return ((GSARTagLayoutDisplay*)m_pD3DDisplay)->SetBlackLevel(level); } HRESULT GSARTagLayoutFilter::GetLayout(GSARTagLayout*& pLayout) { if (m_pD3DDisplay == NULL) return E_FAIL; GSAutoLock lck(m_pD3DDisplay->GetGSCritSec()); return ((GSARTagLayoutDisplay*)m_pD3DDisplay)->GetLayout(pLayout); } BOOL GSARTagLayoutFilter::GetLayoutChanged() { CAutoLock lck(&m_csLayoutChange); return m_bLayoutChange; } void GSARTagLayoutFilter::SetLayoutChanged(BOOL bChanged) { CAutoLock lck(&m_csLayoutChange); m_bLayoutChange = bChanged; } HRESULT GSARTagLayoutFilter::ComputeROIs() { HRESULT hr = S_OK; CAutoLock lck0(&m_csRenderPara); CAutoLock lck1(&m_csROIRects); if (m_pD3DDisplay == NULL) return E_FAIL; GSBoundingBox2D** pTagRects = ((GSARTagLayoutDisplay*)m_pD3DDisplay)->GetAllMarkerRects(); if (pTagRects == NULL) return E_FAIL; GSARTagLayout* pLayout = NULL; ((GSARTagLayoutDisplay*)m_pD3DDisplay)->GetLayout(pLayout); if (pLayout == NULL) return E_FAIL; if (m_pROIImg == NULL) { m_pROIImg = cvCreateImage(cvSize(320, 240), 8, 1); } int imgW = m_pROIImg->width; int imgH = m_pROIImg->height; if (imgW -1 <= 0 || imgH -1 <= 0 ) { SAFE_DELETE(pLayout); return E_FAIL; } cvDrawRect(m_pROIImg, cvPoint(0,0), cvPoint(m_pROIImg->width-1, m_pROIImg->height-1), cvScalar(255, 255, 255), -1); for (int i =0; i < pLayout->m_nARTag; i ++) { if (pLayout->m_pARTag[i].m_visible) { float w = (pTagRects[i]->RB.x - pTagRects[i]->LT.x); float h = (pTagRects[i]->RB.y - pTagRects[i]->LT.y); float p0X = max(0.0, pTagRects[i]->LT.x - w*0.13); float p0Y = max(0.0, pTagRects[i]->LT.y - h*0.13); float p1X = min(1.0, pTagRects[i]->RB.x + w*0.13); float p1Y = min(1.0, pTagRects[i]->RB.y + h*0.13); CvPoint p0 = cvPoint(p0X*(imgW-1), p0Y*(imgH-1)); CvPoint p1 = cvPoint(p1X*(imgW-1), p1Y*(imgH-1)); cvDrawRect(m_pROIImg, p0, p1, cvScalar(0,0,0), -1 ); } } cvThreshold(m_pROIImg, m_pROIImg, 128, 255, CV_THRESH_BINARY); CvMemStorage* storage = cvCreateMemStorage(0); CvSeq* cont = 0; cvFindContours(m_pROIImg, storage, &cont, sizeof(CvContour), CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE ); m_ROIRects.clear(); CvRect cvROIRect; fRECT fROIRect; for( ; cont != 0; cont = cont->h_next ) { int count = cont->total; // This is number point in contour cvROIRect = cvContourBoundingRect(cont); fROIRect.left = cvROIRect.x /(float)(imgW-1) ; fROIRect.top = cvROIRect.y /(float)(imgH -1); fROIRect.right = (cvROIRect.x + cvROIRect.width) / (float)(imgW-1); fROIRect.bottom = (cvROIRect.y + cvROIRect.height) / (float)(imgH-1); m_ROIRects.push_back(fROIRect); } cvReleaseMemStorage(&storage); storage = NULL; SAFE_DELETE(pLayout); return S_OK; } HRESULT GSARTagLayoutFilter::GetROIData(ROIData*& roiData) { CAutoLock lck(&m_csROIRects); if (roiData != NULL) { delete roiData; roiData = NULL; } roiData = new ROIData(); if (m_ROIRects.size() <= 0) { roiData->m_pRECTs = NULL; roiData->m_nRECTs = 0; } else { roiData->m_pRECTs = new fRECT[m_ROIRects.size()]; roiData->m_nRECTs = m_ROIRects.size(); for (int i=0; i < m_ROIRects.size(); i++) { memcpy((void*)&(roiData->m_pRECTs[i]), (void*)&(m_ROIRects.at(i)), sizeof(fRECT)); } } return S_OK; } HRESULT GSARTagLayoutFilter::SendLayoutData() { if (m_pD3DDisplay == NULL) return E_FAIL; GSARTagLayout* pLayout = NULL; ((GSARTagLayoutDisplay*)m_pD3DDisplay)->GetLayout(pLayout); if (pLayout == NULL) return E_FAIL; if (m_pOutputPins.size() <= 0 || !m_pOutputPins[0]->IsConnected()) { SAFE_DELETE(pLayout); return S_FALSE; } CMediaType mt = m_pOutputPins[0]->CurrentMediaType(); GSARTagLayout sendData0; ARLayoutConfigData* sendData1 = NULL; sendData0 = *pLayout; IMemAllocator* pAllocator = m_pOutputPins[0]->Allocator(); CMediaSample* pSendSample = NULL; pAllocator->GetBuffer((IMediaSample**)&pSendSample, NULL, NULL, 0); if (pSendSample == NULL) { SAFE_DELETE(pLayout); return E_FAIL; } if (IsEqualGUID(*mt.Type(), GUID_IMPRO_FeedbackTYPE) && IsEqualGUID(*mt.Subtype(), GUID_ARLayoutConfigData)) { sendData1 = GSARTagLayout2ARLayoutConfig(&sendData0); pSendSample->SetPointer((BYTE*)sendData1, sizeof(ARLayoutConfigData)); } else { pSendSample->SetPointer((BYTE*)&sendData0, sizeof(GSARTagLayout)); } m_pOutputPins[0]->Deliver(pSendSample); SAFE_RELEASE(pSendSample); SAFE_DELETE(sendData1); SAFE_DELETE(pLayout); return S_OK; } ARLayoutConfigData* GSARTagLayout2ARLayoutConfig(GSARTagLayout* inData) { if (inData == NULL) return NULL; ARLayoutConfigData* ret = new ARLayoutConfigData(); ret->m_numMarker = 0; ret->m_ARMarkers = NULL; if (inData->m_nARTag == 0) return ret; ret->m_numMarker = inData->m_nARTag; ret->m_ARMarkers = new ARMultiEachMarkerInfoT[ret->m_numMarker]; for (int i =0; i < ret->m_numMarker; i++) { ret->m_ARMarkers[i].patt_id = inData->m_pARTag[i].m_tagID; ret->m_ARMarkers[i].visible = inData->m_pARTag[i].m_visible; GSBoundingBox2D bbox; inData->m_pARTag[i].GetBoundingBox2D(bbox); ret->m_ARMarkers[i].width = abs(bbox.RB.x - bbox.LT.x); float markerWidth = ret->m_ARMarkers[i].width; ret->m_ARMarkers[i].center[0] = markerWidth*0.5; ret->m_ARMarkers[i].center[1] = -markerWidth*0.5; for (int row =0; row < 3; row++) { for (int col = 0; col < 4; col++) { ret->m_ARMarkers[i].trans[row][col] = inData->m_pARTag[i].m_matTran[col*4 + row]; } } } return ret; } bool GSARTagLayoutFilter::sendROIData() { if (m_pOutputPins.size() <= 1 || !m_pOutputPins[1]->IsConnected()) { return false; } ROIData* sendData = NULL; { CAutoLock lck(&m_csROIRects); GetROIData(sendData); if (sendData == NULL) return false; IMemAllocator* pAllocator = m_pOutputPins[1]->Allocator(); CMediaSample* pSendSample = NULL; pAllocator->GetBuffer((IMediaSample**)&pSendSample, NULL, NULL, 0); if (pSendSample == NULL) { SAFE_DELETE(sendData); return S_FALSE; } pSendSample->SetPointer((BYTE*)sendData, sizeof(ROIData)); m_pOutputPins[1]->Deliver(pSendSample); SAFE_DELETE(sendData); if (pSendSample != NULL) { pSendSample->Release(); pSendSample = NULL; } } return true; }
[ "ndhumuscle@fa729b96-8d43-11de-b54f-137c5e29c83a", "claire3kao@fa729b96-8d43-11de-b54f-137c5e29c83a" ]
[ [ [ 1, 313 ], [ 316, 316 ], [ 329, 329 ], [ 331, 431 ], [ 439, 659 ] ], [ [ 314, 315 ], [ 317, 328 ], [ 330, 330 ], [ 432, 438 ] ] ]
31938d670bc883052fe9a241b1102def59f045b0
56c17f756480a02c77aecc69b217c29294f4c180
/Src/Libs/Rastering/QbertEnemyObj.cpp
00eb7e5d744f607046448ee8192050fbe10527fc
[]
no_license
sangongs/qbert3d
5fd88b9720b68ca7617a8c5510568911b3dc34c5
296b78451b73032e16e64ae1cc4f0200ef7ca734
refs/heads/master
2021-01-10T04:02:37.685309
2008-09-12T16:13:04
2008-09-12T16:13:04
46,944,626
0
0
null
null
null
null
UTF-8
C++
false
false
508
cpp
#include "StdAfx.h" #include "Point3D.h" #include "QbertModel.h" #include "QbertEnemyObj.h" namespace BGComplete { std::map<std::string, VecOfAppearanceBox_ptr> QbertEnemyObj::_apperanceMap; bool QbertEnemyObj::IsQbertDies() { return TestCollision((static_cast<QbertModel*>(_model))->_objects->Qbert); } VecOfAppearanceBox_ptr QbertEnemyObj::GetAppearanceBoxes() { return _apperanceMap.find(_type)->second; } QbertEnemyObj::~QbertEnemyObj(void) {} } //namespace BGComplete
[ "iliagore@97581c8e-fe54-0410-aa42-dd6ba39e7182" ]
[ [ [ 1, 25 ] ] ]
10647c6257d07423bee825641c1cebcec2ed0174
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/CPP/Shared/symbian-r7/Selector.cpp
cfad16424097f46e76f94d84fe5b26dd75d679bb
[ "BSD-3-Clause" ]
permissive
ravustaja/Wayfinder-S60-Navigator
ef506c418b8c2e6498ece6dcae67e583fb8a4a95
14d1b729b2cea52f726874687e78f17492949585
refs/heads/master
2021-01-16T20:53:37.630909
2010-06-28T09:51:10
2010-06-28T09:51:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,580
cpp
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "../symbian-r6/Selector.cpp"
[ [ [ 1, 13 ] ] ]
38fe8a4d2ad30bc2b474113c53a0c71b8cbf7248
7ccf42cf95c94b3d18766451d5641c55cb37bc30
/src/nes.h
b40883df7843304f6105876f60cb3afa6928f5a8
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
yoshin4444/bjne
4b8846e69bb4b6735091296489183996fa80a844
d00e1e401a31e3f716453b267e531199071f63d6
refs/heads/master
2021-01-22T19:54:34.318633
2010-03-14T23:20:53
2010-03-14T23:20:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
958
h
#ifndef _NES_H #define _NES_H #include "types.h" #include "rom.h" #include "cpu.h" #include "ppu.h" #include "apu.h" #include "mbc.h" #include "regs.h" #include "mapper.h" #include "renderer.h" #include "serializer.h" class nes{ public: nes(renderer *r); ~nes(); bool load(const char *fname); bool check_mapper(); bool save_sram(const char *fname); bool load_sram(const char *fname); bool save_state(const char *fname); bool load_state(const char *fname); void reset(); void exec_frame(); rom *get_rom() { return _rom; } cpu *get_cpu() { return _cpu; } ppu *get_ppu() { return _ppu; } apu *get_apu() { return _apu; } mbc *get_mbc() { return _mbc; } regs *get_regs() { return _regs; } mapper *get_mapper() { return _mapper; } private: rom *_rom; cpu *_cpu; ppu *_ppu; apu *_apu; mbc *_mbc; regs *_regs; mapper *_mapper; renderer *_renderer; }; #endif
[ [ [ 1, 50 ] ] ]
b9c4dbc1275e2caf357f84b91db7436b8d03ce84
222bc22cb0330b694d2c3b0f4b866d726fd29c72
/src/nv38box/RaytracerRForce/KernelBVBuilder.h
60126115b5c9e0e45976281040e4ef1960716dfe
[ "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference" ]
permissive
darwin/inferno
02acd3d05ca4c092aa4006b028a843ac04b551b1
e87017763abae0cfe09d47987f5f6ac37c4f073d
refs/heads/master
2021-03-12T22:15:47.889580
2009-04-17T13:29:39
2009-04-17T13:29:39
178,477
2
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,398
h
// NV38Box (http://inferno.hildebrand.cz) // Copyright (c) 2004 Antonin Hildebrand // licensed under zlib/libpng license (see license.txt) // released in Shader Triathlon – Summer 2004 ("Contest") /*! \addtogroup RForce @{ \ingroup Raytracers */ /*! \file KernelBVBuilder.h \brief Declaration of KernelBVBuilder class. */ #ifndef _KERNELBVBUILDER_H_ #define _KERNELBVBUILDER_H_ #include "Kernel.h" //! Enum for BVBuilder kernel modes enum E_KERNEL_BVBUILDER_MODE { KERNEL_BVBUILDER_MODE_MINS = 0, KERNEL_BVBUILDER_MODE_MAXS, KERNEL_BVBUILDER_MODE_COUNT }; //! Class managing BVBuilder kernel. /*! BVBuilder kernel is responsible for building bounding volumes structure in GPU. Acceleration structure is AABB computed using reduction from transformed geometry with application MIN and MAX functions per components. <b>Mode KERNEL_BVBUILDER_MODE_MINS</b><br> Reduction program for points in world space. Result is minimum in all three axes. <b>Mode KERNEL_BVBUILDER_MODE_MAXS</b><br> Reduction program for points in world space. Result is maximum in all three axes. */ class KernelBVBuilder : public Kernel { public: //! KernelBVBuilder constructor. KernelBVBuilder (); //! Loads programs from disk and prepares kernel. virtual bool Prepare(); }; #endif //! @} //doxygen group
[ [ [ 1, 51 ] ] ]
7cc2a32f597b0ceabd8a2c507aec0a2baf37e5d1
ee2e06bda0a5a2c70a0b9bebdd4c45846f440208
/c++/Pattern/Source/ChainOfResponsibility/ChainOfResponsibility.h
bab1c0a769e25c12842f055068ca648e1cd1ef60
[]
no_license
RobinLiu/Test
0f53a376e6753ece70ba038573450f9c0fb053e5
360eca350691edd17744a2ea1b16c79e1a9ad117
refs/heads/master
2021-01-01T19:46:55.684640
2011-07-06T13:53:07
2011-07-06T13:53:07
1,617,721
2
0
null
null
null
null
GB18030
C++
false
false
1,087
h
/******************************************************************** created: 2006/07/20 filename: ChainOfResponsibility.h author: 李创 http://www.cppblog.com/converse/ purpose: ChainOfResponsibility模式的演示代码 *********************************************************************/ #ifndef CHAINOFRESPONSIBILITY_H #define CHAINOFRESPONSIBILITY_H #include <stdio.h> // 抽象基类,定义一个处理请求的接口 class Handler { public: Handler(Handler *pSuccessor = NULL); virtual ~Handler(); // 纯虚函数,由派生类实现 virtual void HandleRequset() = 0; protected: Handler* m_pSuccessor; }; class ConcreateHandler1 : public Handler { public: ConcreateHandler1(Handler *pSuccessor = NULL) : Handler(pSuccessor){} virtual ~ConcreateHandler1(){} virtual void HandleRequset(); }; class ConcreateHandler2 : public Handler { public: ConcreateHandler2(Handler *pSuccessor = NULL) : Handler(pSuccessor){} virtual ~ConcreateHandler2(){} virtual void HandleRequset(); }; #endif
[ "[email protected]@43938a50-64aa-11de-9867-89bd1bae666e" ]
[ [ [ 1, 49 ] ] ]
ec7050b701b59f9dcc12b65c1e43d98b6e95add5
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/nGENE Proj/PrefabTorus.h
a79d7555ceddc83893998505c04d01b59f32bd7d
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
2,328
h
/* --------------------------------------------------------------------------- This source file is part of nGENE Tech. Copyright (c) 2006- Wojciech Toman This program is free software. File: PrefabTorus.h Version: 0.01 --------------------------------------------------------------------------- */ #pragma once #ifndef __INC_PREFABTORUS_H_ #define __INC_PREFABTORUS_H_ #include "NodePrefab.h" #include "TypeInfo.h" namespace nGENE { /** Visualization of the torus. @par PrefabTorus is a donut-shaped mesh. */ class nGENEDLL PrefabTorus: public NodePrefab { EXPOSE_TYPE private: float m_fInnerRadius; ///< Inner radius float m_fOuterRadius; ///< Outer radius uint m_nRadialSlices; ///< Number of slices along radius uint m_nCircleSlices; ///< Number of slices along perimeter void updateGeometry(); public: PrefabTorus(uint _radialSlices, uint _circleSlices, float _innerRadius, float _outerRadius, const Vector2& _texCoordMul=Vector2::ONE_VECTOR); PrefabTorus(); ~PrefabTorus(); void init(); void cleanup(); /// Sets inner radius. void setInnerRadius(Real _radius); Real getInnerRadius() const; /// Sets outer radius. void setOuterRadius(Real _radius); Real getOuterRadius() const; /// Sets slices along perimeter. void setRadialSlices(uint _slices); uint getRadialSlices() const; /// Sets slices along radius. void setCircleSlices(uint _slices); uint getCircleSlices() const; void serialize(ISerializer* _serializer, bool _serializeType, bool _serializeChildren); void deserialize(ISerializer* _serializer); }; inline Real PrefabTorus::getInnerRadius() const { return m_fInnerRadius; } //---------------------------------------------------------------------- inline Real PrefabTorus::getOuterRadius() const { return m_fOuterRadius; } //---------------------------------------------------------------------- inline uint PrefabTorus::getRadialSlices() const { return m_nRadialSlices; } //---------------------------------------------------------------------- inline uint PrefabTorus::getCircleSlices() const { return m_nCircleSlices; } //---------------------------------------------------------------------- } #endif
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 96 ] ] ]
de94eb45871848526ed91d609ed0461d9aeed556
0f457762985248f4f6f06e29429955b3fd2c969a
/irrlicht/sdk/irr_bullet/CBulletObjectAnimator.cpp
9b4317b103c7e63d260165ee9fdef9e8aa8aaa0d
[]
no_license
tk8812/ukgtut
f19e14449c7e75a0aca89d194caedb9a6769bb2e
3146ac405794777e779c2bbb0b735b0acd9a3f1e
refs/heads/master
2021-01-01T16:55:07.417628
2010-11-15T16:02:53
2010-11-15T16:02:53
37,515,002
0
0
null
null
null
null
UHC
C++
false
false
24,101
cpp
#pragma warning (disable:4819) //for 1.4.1 version //update gbox3d 2008.8.13 , restitution bug patch //update gbox3d 2008.8.13 , getRotation() bug patch //for 1.6.x version //last update gbox3d 2009.8.11 modify CBPAGT_CONCAVE_LOD_TERRAIN_MESH for irrlicht 1.6.x #include "CBulletObjectAnimator.h" #include "btBulletDynamicsCommon.h" #include "BulletCollision/Gimpact/btGImpactShape.h" #include "BulletCollision/Gimpact/btGImpactCollisionAlgorithm.h" #include "CBulletAnimatorManager.h" #include "CBulletWorldAnimator.h" namespace irr { namespace scene { //! Names for alignments const c8* const CBulletObjectAnimatorGeometryTypesNames[] = { "none", "sphere", "box", "cylinder", "capsule", "cone", "plane", "convex", "concave", "concave_gimpact", "concave_Terrain", 0 }; const c8* const *CBulletObjectAnimator::getGeometryTypesNames() { return CBulletObjectAnimatorGeometryTypesNames; } //------------------------------------------------------------------------------ //! CreateInstance //! Creates CBulletObjectAnimator or returns NULL CBulletObjectAnimator* CBulletObjectAnimator::createInstance( ISceneManager* pSceneManager, ISceneNode* pSceneNode, CBulletAnimatorManager* pBulletMgr, CBulletObjectAnimatorGeometry* pGeom, CBulletObjectAnimatorParams* pPhysicsParam) { // 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; CBulletObjectAnimator* bulletAnimator = new CBulletObjectAnimator(); bulletAnimator->geometry = *pGeom; bulletAnimator->physicsParams = *pPhysicsParam; bulletAnimator->bulletMesh = triangleMesh; bulletAnimator->collisionShape = collisionShape; bulletAnimator->sceneNode = pSceneNode; bulletAnimator->sceneManager = pSceneManager; bulletAnimator->bulletMgr = pBulletMgr; bulletAnimator->InitPhysics(); return bulletAnimator; } //------------------------------------------------------------------------------ //! CreateEmptyInstance //! Creates empty CBulletObjectAnimator CBulletObjectAnimator* CBulletObjectAnimator::createEmptyInstance( ISceneManager* pSceneManager, ISceneNode* pSceneNode, CBulletAnimatorManager* pBulletMgr) { // create empty bullet animator CBulletObjectAnimator* bulletAnimator = new CBulletObjectAnimator(); bulletAnimator->sceneNode = pSceneNode; bulletAnimator->sceneManager = pSceneManager; bulletAnimator->bulletMgr = pBulletMgr; return bulletAnimator; } //------------------------------------------------------------------------------ //! Ctor //! CBulletObjectAnimator::CBulletObjectAnimator() : sceneManager(NULL), rigidBody(NULL), sceneNode(NULL), bulletMesh(NULL), collisionShape(NULL), motionState(NULL), bulletMgr(NULL), bulletWorldID(-1) { #ifdef _DEBUG setDebugName("CBulletObjectAnimator"); #endif } //------------------------------------------------------------------------------ //! Dtor //! CBulletObjectAnimator::~CBulletObjectAnimator() { RemoveFromWorld(); SAFE_DELETE(bulletMesh); SAFE_DELETE(collisionShape); SAFE_DELETE(motionState); SAFE_DELETE(rigidBody); } //------------------------------------------------------------------------------ //! getType //! Returns type of the scene node animator ESCENE_NODE_ANIMATOR_TYPE CBulletObjectAnimator::getType() const { return (ESCENE_NODE_ANIMATOR_TYPE)ESNAT_BULLET_OBJECT; } //------------------------------------------------------------------------------ //! InitializeEmptyInstance //! Initialize empty animator. Only to use with serialization. bool CBulletObjectAnimator::InitEmptyInstance() { // get node scaling core::vector3df scaling = sceneNode->getScale(); // prepare collision shape collisionShape = CreateBulletCollisionShape(sceneManager, &geometry, scaling, bulletMesh); if (collisionShape == NULL) return NULL; InitPhysics(); AddToWorld(bulletWorldID); return true; } //------------------------------------------------------------------------------ //! GetMeshFromGeom //! Helper function to extract mesh data from object geometry IMesh* CBulletObjectAnimator::GetMeshFromGeom(ISceneManager* pSceneManager, CBulletObjectAnimatorGeometry* pGeom) { IMesh* mesh = pGeom->mesh.irrMesh; if (mesh == NULL) { IAnimatedMesh* animMesh = pSceneManager->getMesh(pGeom->meshFile.c_str()); if (animMesh != NULL) mesh = animMesh->getMesh(0); } return mesh; } //------------------------------------------------------------------------------ //! CreateBulletCollisionShape //! Helper function to create bullet-compatible shape btCollisionShape* CBulletObjectAnimator::CreateBulletCollisionShape( ISceneManager* pSceneManager, CBulletObjectAnimatorGeometry* pGeom, const core::vector3df& pScaling, btStridingMeshInterface*& triangleMesh) { triangleMesh = NULL; // prepare collision shape btCollisionShape* collisionShape = NULL; switch (pGeom->type) { case CBPAGT_CAPSULE: { collisionShape = new btCapsuleShape(pGeom->Capsule.radius,pGeom->Capsule.hight); } break; case CBPAGT_SPHERE: { collisionShape = new btSphereShape(pGeom->sphere.radius); } break; case CBPAGT_BOX: { collisionShape = new btBoxShape(btVector3(pGeom->box.X, pGeom->box.Y, pGeom->box.Z)); } break; case CBPAGT_CYLINDER: { collisionShape = new btCylinderShape(btVector3(pGeom->box.X, pGeom->box.Y, pGeom->box.Z)); } break; case CBPAGT_CONVEX_MESH: { IMesh* mesh = GetMeshFromGeom(pSceneManager, pGeom); if (mesh != NULL) { triangleMesh = ConvertIrrMeshToBulletTriangleMesh(mesh, pScaling); //triangleMesh = ConvertIrrMeshToBulletTriangleArray(mesh, pScaling); collisionShape = new btConvexTriangleMeshShape(triangleMesh); //collisionShape = ConvertIrrMeshToBulletConvexHullShape(mesh); } } break; case CBPAGT_CONCAVE_MESH: { IMesh* mesh = GetMeshFromGeom(pSceneManager, pGeom); if (mesh != NULL) { triangleMesh = ConvertIrrMeshToBulletTriangleMesh(mesh, pScaling); bool useQuantizedAabbCompression = true; collisionShape = new btBvhTriangleMeshShape(triangleMesh, useQuantizedAabbCompression); } } break; case CBPAGT_CONCAVE_GIMPACT_MESH: { IMesh* mesh = GetMeshFromGeom(pSceneManager, pGeom); if (mesh != NULL) { triangleMesh = ConvertIrrMeshToBulletTriangleMesh(mesh, pScaling); //triangleMesh = ConvertIrrMeshToBulletTriangleArray(mesh, pScaling); btGImpactMeshShape* gimpactShape = new btGImpactMeshShape(triangleMesh); gimpactShape->updateBound(); collisionShape = gimpactShape; } } break; case CBPAGT_CONCAVE_LOD_TERRAIN_MESH: { //메쉬컨버팅 { btVector3 vertices[3]; irr::u32 j,k,index,numVertices,numIndices; irr::u16* mb_indices; irr::scene::ITerrainSceneNode *pTerrain = (irr::scene::ITerrainSceneNode *)pSceneManager->getSceneNodeFromName(pGeom->meshFile.c_str()); //irr::scene::SMeshBufferLightMap smb; irr::scene::CDynamicMeshBuffer smb( //irr::video::EVT_2TCOORDS, //irr::video::EIT_16BIT pTerrain->getMesh()->getMeshBuffer(0)->getVertexType(), pTerrain->getMesh()->getMeshBuffer(0)->getIndexType() ); pTerrain->getMeshBufferForLOD(smb,pGeom->terrain_mesh.meshLod); numVertices = smb.getVertexCount ();//mb->getVertexCount(); numIndices = smb.getIndexCount();//mb->getIndexCount(); mb_indices = smb.getIndices();// mb->getIndices(); irr::video::S3DVertex2TCoords* mb_vertices = (irr::video::S3DVertex2TCoords*)smb.getVertices();// ->getVertices(); { btTriangleMesh *pTriMesh = new btTriangleMesh(); irr::core::vector3df scaling = pScaling; for(j=0;j<numIndices;j+=3) { //index into irrlicht data for (k=0;k<3;k++) { index = mb_indices[j+k]; // we apply scaling factor directly to verticies vertices[k] = btVector3(mb_vertices[index].Pos.X*scaling.X, mb_vertices[index].Pos.Y*scaling.Y, mb_vertices[index].Pos.Z*scaling.Z); } //removeduplicatevertex를 false하면 속도가 빨라진다. pTriMesh->addTriangle(vertices[0], vertices[1], vertices[2],false); } triangleMesh = pTriMesh; } } bool useQuantizedAabbCompression = true; collisionShape = new btBvhTriangleMeshShape(triangleMesh, useQuantizedAabbCompression); } break; default: // unknown type break; } return collisionShape; } //------------------------------------------------------------------------------ //! InitPhysics //! Adds body to btDynamicsWorld //! tunneling방지를 위한 ccd값은 물체의 가장 큰축으로 만든 정육면체로 설정한다. void CBulletObjectAnimator::InitPhysics() { //rigidbody is dynamic if and only if mass is non zero, otherwise static bool isDynamic = (physicsParams.mass != 0.0f); // calculate inertia vector btVector3 localInertia(0,0,0); if (isDynamic) collisionShape->calculateLocalInertia(physicsParams.mass, localInertia); // calculate value for ccdThreshold core::aabbox3d<f32> box = sceneNode->getBoundingBox(); core::vector3df ext = box.getExtent(); f32 ret=0; if (ext.X>ret) ret=ext.X; if (ext.Y>ret) ret=ext.Y; if (ext.Z>ret) ret=ext.Z; physicsParams.ccdThreshold = ret/2; // evaluate start transform in terms of btTransform // and set offset of center of mass btTransform startTransform, centerOfMassOffset; GetNodeTransform(sceneNode, startTransform); centerOfMassOffset.setIdentity(); centerOfMassOffset.setOrigin(btVector3(physicsParams.centerOfMassOffset.X, physicsParams.centerOfMassOffset.Y, physicsParams.centerOfMassOffset.Z)); //using motionstate is recommended, it provides interpolation capabilities, //and only synchronizes 'active' objects motionState = new btDefaultMotionState(startTransform, centerOfMassOffset); // create body /* rigidBody = new btRigidBody( physicsParams.mass, motionState, collisionShape, localInertia, physicsParams.linearDamping, physicsParams.angularDamping, physicsParams.friction, physicsParams.restitution );*/ rigidBody = new btRigidBody( physicsParams.mass, motionState, collisionShape, localInertia); rigidBody->setDamping(physicsParams.linearDamping,physicsParams.angularDamping); rigidBody->setFriction(physicsParams.friction); rigidBody->setRestitution(physicsParams.restitution); // Only do CCD if motion in one timestep (1.f/60.f) exceeds half dims //rigidBody->setCcdMotionThreshold((btScalar)(physicsParams.ccdThreshold)); //Experimental: better estimation of CCD Time of Impact: //rigidBody->setCcdSweptSphereRadius((btScalar)(.2*physicsParams.ccdThreshold)); setCCD(0,0); } //------------------------------------------------------------------------------ //! AddToWorld //! Adds body to Bullet World void CBulletObjectAnimator::AddToWorld(s32 worldID) { bulletWorldID = worldID; if (bulletWorldID != -1 && rigidBody) { CBulletWorldAnimator* bulletWorld = bulletMgr->getBulletWorldByID(worldID); bulletWorld->RegisterBody(rigidBody); // apply additional constant force core::vector3df newGravity = bulletWorld->getGravity() + physicsParams.gravity; // set gravity rigidBody->setGravity(btVector3(newGravity.X, newGravity.Y, newGravity.Z)); bulletWorld->grab(); } } //------------------------------------------------------------------------------ //! RemoveFromWorld //! Remove body from btDynamicsWorld void CBulletObjectAnimator::RemoveFromWorld() { if (bulletWorldID != -1 && rigidBody) { CBulletWorldAnimator* bulletWorld = bulletMgr->getBulletWorldByID(bulletWorldID); bulletWorld->UnregisterBody(rigidBody); bulletWorld->drop(); } bulletWorldID = -1; } //------------------------------------------------------------------------------ //! setPosition //! Set animator position void CBulletObjectAnimator::setPosition(const core::vector3df& v) const { _IRR_DEBUG_BREAK_IF(rigidBody == NULL); btTransform t = rigidBody->getWorldTransform(); btVector3 btv(v.X, v.Y, v.Z); t.setOrigin(btv); rigidBody->setWorldTransform(t); } //------------------------------------------------------------------------------ //! setRotation //! Set animator rotation core::vector3df CBulletObjectAnimator::getPosition() const { _IRR_DEBUG_BREAK_IF(rigidBody == NULL); btVector3 p = rigidBody->getCenterOfMassPosition(); return core::vector3df(p.getX(), p.getY(), p.getZ()); } //------------------------------------------------------------------------------ //! setRotation //! Set animator rotation (v measured in radians) void CBulletObjectAnimator::setRotation(const core::vector3df& v) const { _IRR_DEBUG_BREAK_IF(rigidBody == NULL); btTransform t = rigidBody->getWorldTransform(); btQuaternion btq; EulerXYZToQuaternion(v, btq); t.setRotation(btq); rigidBody->setWorldTransform(t); } //------------------------------------------------------------------------------ //! getRotation //! Get animator rotation core::vector3df CBulletObjectAnimator::getRotation() const { _IRR_DEBUG_BREAK_IF(rigidBody == NULL); core::vector3df rot; btQuaternion btq=rigidBody->getOrientation(); QuaternionToEulerXYZ(btq, rot); //rot *= (f32)BPU_360_PI2; rot *= (f32)BPU_180_PI; //gbox patch 2008.8.13 return rot; } //------------------------------------------------------------------------------ //! setLinearVelocity //! Set animator linear vel void CBulletObjectAnimator::setLinearVelocity(const core::vector3df& vel) const { _IRR_DEBUG_BREAK_IF(rigidBody == NULL); //bullet hangs if attempt to set lin. or ang. velocity on static object if (physicsParams.mass != 0.0f) { rigidBody->setLinearVelocity(btVector3(vel.X, vel.Y, vel.Z)); } //note - apparently, need to use motion state on kinematic objects, and rigid body functions // on dynamic rigid bodies to change pos / rot etc. } //------------------------------------------------------------------------------ //! getLinearVelocity //! Get animator linear vel core::vector3df CBulletObjectAnimator::getLinearVelocity() const { _IRR_DEBUG_BREAK_IF(rigidBody == NULL); if (physicsParams.mass == 0.0f) return core::vector3df(0,0,0); btVector3 btV = rigidBody->getLinearVelocity(); return core::vector3df(btV.getX(), btV.getY(), btV.getZ()); } //------------------------------------------------------------------------------ //! setLinearVelocity //! Set animator linear vel void CBulletObjectAnimator::setAngularVelocity(const core::vector3df & vel) const { _IRR_DEBUG_BREAK_IF(rigidBody == NULL); //bullet hangs if attempt to set lin. or ang. velocity on static object if (physicsParams.mass != 0.0f) { rigidBody->setAngularVelocity(btVector3(vel.X, vel.Y, vel.Z)); } } //------------------------------------------------------------------------------ //! getAngularVelocity //! Get animator angular vel core::vector3df CBulletObjectAnimator::getAngularVelocity() const { _IRR_DEBUG_BREAK_IF(rigidBody == NULL); if (physicsParams.mass == 0.0f) return core::vector3df(0,0,0); btVector3 btV = rigidBody->getAngularVelocity(); return core::vector3df(btV.getX(), btV.getY(), btV.getZ()); } //------------------------------------------------------------------------------ //! applyImpulse //! Apply impulse to object void CBulletObjectAnimator::applyImpulse(const core::vector3df& force, const core::vector3df& rel_pos/* = core::vector3df(0,0,0)*/) const { _IRR_DEBUG_BREAK_IF(rigidBody == NULL); rigidBody->applyImpulse(btVector3(force.X, force.Y, force.Z), btVector3(rel_pos.X, rel_pos.Y, rel_pos.Z)); rigidBody->activate(); } //------------------------------------------------------------------------------ //! applyForce //! Apply force to object void CBulletObjectAnimator::applyForce(const core::vector3df& force, const core::vector3df& rel_pos/* = core::vector3df(0,0,0)*/) const { _IRR_DEBUG_BREAK_IF(rigidBody == NULL); rigidBody->applyForce(btVector3(force.X, force.Y, force.Z), btVector3(rel_pos.X, rel_pos.Y, rel_pos.Z)); rigidBody->activate(); } //------------------------------------------------------------------------------ //! zeroForces //! Zero all forces void CBulletObjectAnimator::zeroForces() const { _IRR_DEBUG_BREAK_IF(rigidBody == NULL); rigidBody->setLinearVelocity(btVector3(0,0,0)); rigidBody->setAngularVelocity(btVector3(0,0,0)); } //------------------------------------------------------------------------------ //! setActivationState //! Zero all forces void CBulletObjectAnimator::setActivationState(bool active) const { _IRR_DEBUG_BREAK_IF(rigidBody == NULL); rigidBody->setActivationState((active) ? 1 : 0); } //------------------------------------------------------------------------------ //! activate //! Zero all forces void CBulletObjectAnimator::activate(bool force) const { _IRR_DEBUG_BREAK_IF(rigidBody == NULL); rigidBody->activate(force); } //------------------------------------------------------------------------------ //! animateNode //! animates a scene node void CBulletObjectAnimator::animateNode(ISceneNode* node, u32 timeMs) { _IRR_DEBUG_BREAK_IF(node != sceneNode); if (physicsParams.mass != 0.0f && rigidBody && rigidBody->getMotionState()) { // set pos btVector3 p = rigidBody->getCenterOfMassPosition(); sceneNode->setPosition(core::vector3df(p.getX(), p.getY(), p.getZ())); // set rot core::vector3df rot; btQuaternion btq = rigidBody->getOrientation(); QuaternionToEulerXYZ(btq, rot); rot *= (f32)BPU_180_PI; //rot.Y = 0-rot.Y; sceneNode->setRotation(rot); } } //------------------------------------------------------------------------------ //! serializeAttributes //! Writes attributes of the scene node animator. void CBulletObjectAnimator::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options/*=0*/) { // store world's id out->addInt("worldID", bulletWorldID); core::vector3df ip; btVector3 bp; btQuaternion bq; // save rigid body position bp = rigidBody->getCenterOfMassPosition(); out->addVector3d("pos", core::vector3df(bp.getX(), bp.getY(), bp.getZ())); // save rigid body rotation bq = rigidBody->getOrientation(); QuaternionToEulerXYZ(bq, ip); ip *= (f32)BPU_180_PI; out->addVector3d("rot", ip); // linear velocity bp = rigidBody->getLinearVelocity(); out->addVector3d("lvel", core::vector3df(bp.getX(), bp.getY(), bp.getZ())); // angular velocity bp = rigidBody->getAngularVelocity(); out->addVector3d("avel", core::vector3df(bp.getX(), bp.getY(), bp.getZ())); // save physics parameters //out->addBinary("physics", &physicsParams, sizeof(physicsParams)); out->addFloat("m", physicsParams.mass); out->addFloat("ldamp", physicsParams.linearDamping); out->addFloat("adamp", physicsParams.angularDamping); out->addFloat("rest", physicsParams.restitution); out->addFloat("fric", physicsParams.friction); out->addVector3d("grav", physicsParams.gravity); out->addVector3d("cmof", physicsParams.centerOfMassOffset); // save geometry out->addEnum("geom_type", geometry.type, CBulletObjectAnimatorGeometryTypesNames); switch (geometry.type) { case CBPAGT_SPHERE: { out->addFloat("radius", geometry.sphere.radius); } break; case CBPAGT_BOX: { out->addVector3d("halfExtents", core::vector3df(geometry.box.X, geometry.box.Y, geometry.box.Z)); } break; case CBPAGT_CONVEX_MESH: case CBPAGT_CONCAVE_MESH: case CBPAGT_CONCAVE_GIMPACT_MESH: { if (geometry.mesh.irrMesh != NULL) { SerializeIrrMesh(out, options); } else { out->addString("meshFile", geometry.meshFile.c_str()); } } break; } } //------------------------------------------------------------------------------ //! deserializeAttributes //! Reads attributes of the scene node animator. void CBulletObjectAnimator::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options/*=0*/) { // get world's id bulletWorldID = in->getAttributeAsInt("worldID"); core::vector3df ip; // load physics parameters //in->getAttributeAsBinaryData("physics", &physicsParams, sizeof(physicsParams)); physicsParams.mass = in->getAttributeAsFloat("m"); physicsParams.linearDamping = in->getAttributeAsFloat("ldamp"); physicsParams.angularDamping = in->getAttributeAsFloat("adamp"); physicsParams.restitution = in->getAttributeAsFloat("rest"); physicsParams.friction = in->getAttributeAsFloat("fric"); physicsParams.gravity = in->getAttributeAsVector3d("grav"); physicsParams.centerOfMassOffset = in->getAttributeAsVector3d("cmof"); // detect geometry type geometry.type = (CBulletObjectAnimatorGeometryTypes)in->getAttributeAsEnumeration("geom_type", CBulletObjectAnimatorGeometryTypesNames); switch (geometry.type) { case CBPAGT_SPHERE: { geometry.sphere.radius = in->getAttributeAsFloat("radius"); } break; case CBPAGT_BOX: { ip = in->getAttributeAsVector3d("halfExtents"); geometry.box.X = ip.X; geometry.box.Y = ip.Y; geometry.box.Z = ip.Z; } break; case CBPAGT_CONVEX_MESH: case CBPAGT_CONCAVE_MESH: case CBPAGT_CONCAVE_GIMPACT_MESH: { geometry.meshFile = in->getAttributeAsString("meshFile"); if (geometry.meshFile == "") { DeserializeIrrMesh(in, options); } } break; } // get pos & rot ip = in->getAttributeAsVector3d("pos"); sceneNode->setPosition(ip); ip = in->getAttributeAsVector3d("rot"); sceneNode->setRotation(ip); InitEmptyInstance(); // set vels if (physicsParams.mass != 0.0) { ip = in->getAttributeAsVector3d("lvel"); rigidBody->setLinearVelocity(btVector3(ip.X, ip.Y, ip.Z)); ip = in->getAttributeAsVector3d("avel"); rigidBody->setAngularVelocity(btVector3(ip.X, ip.Y, ip.Z)); } } //------------------------------------------------------------------------------ //! setup continuous collision detection //! void CBulletObjectAnimator::setCCD(btScalar ccdThreshold, btScalar CcdSweptSphereRadius) { physicsParams.ccdThreshold = ccdThreshold; // Only do CCD if motion in one timestep (1.f/60.f) exceeds half dims rigidBody->setCcdMotionThreshold((btScalar)(physicsParams.ccdThreshold)); //Experimental: better estimation of CCD Time of Impact: rigidBody->setCcdSweptSphereRadius(CcdSweptSphereRadius); } //------------------------------------------------------------------------------ //! SerializeIrrMesh //! Helper function for irrlicht mesh data serialization void CBulletObjectAnimator::SerializeIrrMesh(io::IAttributes* out, io::SAttributeReadWriteOptions* options/*=0*/) { } //------------------------------------------------------------------------------ //! DeserializeIrrMesh //! Helper function for irrlicht mesh data serialization void CBulletObjectAnimator::DeserializeIrrMesh(io::IAttributes* in, io::SAttributeReadWriteOptions* options/*=0*/) { } } // end namespace scene } // end namespace irr
[ "gbox3d@58f0f68e-7603-11de-abb5-1d1887d8974b" ]
[ [ [ 1, 765 ] ] ]
3ea67a3929a44e2dffb7cbd3b45cc646c7a0ac2d
ea613c6a4d531be9b5d41ced98df1a91320c59cc
/7-Zip/CPP/7zip/Crypto/Sha1.cpp
b0f719b7aca8ea74acfdfa29d719afea1ba1310f
[]
no_license
f059074251/interested
939f938109853da83741ee03aca161bfa9ce0976
b5a26ad732f8ffdca64cbbadf9625dd35c9cdcb2
refs/heads/master
2021-01-15T14:49:45.217066
2010-09-16T10:42:30
2010-09-16T10:42:30
34,316,088
1
0
null
null
null
null
UTF-8
C++
false
false
5,563
cpp
// Crypto/Sha1.cpp // This file is based on public domain // Steve Reid and Wei Dai's code from Crypto++ #include "StdAfx.h" #include "../../../C/RotateDefs.h" #include "Sha1.h" namespace NCrypto { namespace NSha1 { // define it for speed optimization // #define _SHA1_UNROLL static const unsigned kNumW = #ifdef _SHA1_UNROLL 16; #else 80; #endif #define w0(i) (W[(i)] = data[(i)]) #ifdef _SHA1_UNROLL #define w1(i) (W[(i)&15] = rotlFixed(W[((i)-3)&15] ^ W[((i)-8)&15] ^ W[((i)-14)&15] ^ W[((i)-16)&15], 1)) #else #define w1(i) (W[(i)] = rotlFixed(W[(i)-3] ^ W[(i)-8] ^ W[(i)-14] ^ W[(i)-16], 1)) #endif #define f1(x,y,z) (z^(x&(y^z))) #define f2(x,y,z) (x^y^z) #define f3(x,y,z) ((x&y)|(z&(x|y))) #define f4(x,y,z) (x^y^z) #define RK1(a,b,c,d,e,i, f, w, k) e += f(b,c,d) + w(i) + k + rotlFixed(a,5); b = rotlFixed(b,30); #define R0(a,b,c,d,e,i) RK1(a,b,c,d,e,i, f1, w0, 0x5A827999) #define R1(a,b,c,d,e,i) RK1(a,b,c,d,e,i, f1, w1, 0x5A827999) #define R2(a,b,c,d,e,i) RK1(a,b,c,d,e,i, f2, w1, 0x6ED9EBA1) #define R3(a,b,c,d,e,i) RK1(a,b,c,d,e,i, f3, w1, 0x8F1BBCDC) #define R4(a,b,c,d,e,i) RK1(a,b,c,d,e,i, f4, w1, 0xCA62C1D6) #define RX_1_4(rx1, rx4, i) rx1(a,b,c,d,e,i); rx4(e,a,b,c,d,i+1); rx4(d,e,a,b,c,i+2); rx4(c,d,e,a,b,i+3); rx4(b,c,d,e,a,i+4); #define RX_5(rx, i) RX_1_4(rx, rx, i); void CContextBase::Init() { _state[0] = 0x67452301; _state[1] = 0xEFCDAB89; _state[2] = 0x98BADCFE; _state[3] = 0x10325476; _state[4] = 0xC3D2E1F0; _count = 0; } void CContextBase::GetBlockDigest(UInt32 *data, UInt32 *destDigest, bool returnRes) { UInt32 a, b, c, d, e; UInt32 W[kNumW]; a = _state[0]; b = _state[1]; c = _state[2]; d = _state[3]; e = _state[4]; #ifdef _SHA1_UNROLL RX_5(R0, 0); RX_5(R0, 5); RX_5(R0, 10); #else int i; for (i = 0; i < 15; i += 5) { RX_5(R0, i); } #endif RX_1_4(R0, R1, 15); #ifdef _SHA1_UNROLL RX_5(R2, 20); RX_5(R2, 25); RX_5(R2, 30); RX_5(R2, 35); RX_5(R3, 40); RX_5(R3, 45); RX_5(R3, 50); RX_5(R3, 55); RX_5(R4, 60); RX_5(R4, 65); RX_5(R4, 70); RX_5(R4, 75); #else i = 20; for (; i < 40; i += 5) { RX_5(R2, i); } for (; i < 60; i += 5) { RX_5(R3, i); } for (; i < 80; i += 5) { RX_5(R4, i); } #endif destDigest[0] = _state[0] + a; destDigest[1] = _state[1] + b; destDigest[2] = _state[2] + c; destDigest[3] = _state[3] + d; destDigest[4] = _state[4] + e; if (returnRes) for (int i = 0 ; i < 16; i++) data[i] = W[kNumW - 16 + i]; // Wipe variables // a = b = c = d = e = 0; } void CContextBase::PrepareBlock(UInt32 *block, unsigned size) const { unsigned curBufferPos = size & 0xF; block[curBufferPos++] = 0x80000000; while (curBufferPos != (16 - 2)) block[curBufferPos++] = 0; const UInt64 lenInBits = (_count << 9) + ((UInt64)size << 5); block[curBufferPos++] = (UInt32)(lenInBits >> 32); block[curBufferPos++] = (UInt32)(lenInBits); } void CContext::Update(Byte *data, size_t size, bool rar350Mode) { bool returnRes = false; unsigned curBufferPos = _count2; while (size-- > 0) { int pos = (int)(curBufferPos & 3); if (pos == 0) _buffer[curBufferPos >> 2] = 0; _buffer[curBufferPos >> 2] |= ((UInt32)*data++) << (8 * (3 - pos)); if (++curBufferPos == kBlockSize) { curBufferPos = 0; CContextBase::UpdateBlock(_buffer, returnRes); if (returnRes) for (int i = 0; i < kBlockSizeInWords; i++) { UInt32 d = _buffer[i]; data[i * 4 + 0 - kBlockSize] = (Byte)(d); data[i * 4 + 1 - kBlockSize] = (Byte)(d >> 8); data[i * 4 + 2 - kBlockSize] = (Byte)(d >> 16); data[i * 4 + 3 - kBlockSize] = (Byte)(d >> 24); } returnRes = rar350Mode; } } _count2 = curBufferPos; } void CContext::Final(Byte *digest) { const UInt64 lenInBits = (_count << 9) + ((UInt64)_count2 << 3); unsigned curBufferPos = _count2; int pos = (int)(curBufferPos & 3); curBufferPos >>= 2; if (pos == 0) _buffer[curBufferPos] = 0; _buffer[curBufferPos++] |= ((UInt32)0x80) << (8 * (3 - pos)); while (curBufferPos != (16 - 2)) { curBufferPos &= 0xF; if (curBufferPos == 0) UpdateBlock(); _buffer[curBufferPos++] = 0; } _buffer[curBufferPos++] = (UInt32)(lenInBits >> 32); _buffer[curBufferPos++] = (UInt32)(lenInBits); UpdateBlock(); int i; for (i = 0; i < kDigestSizeInWords; i++) { UInt32 state = _state[i] & 0xFFFFFFFF; *digest++ = (Byte)(state >> 24); *digest++ = (Byte)(state >> 16); *digest++ = (Byte)(state >> 8); *digest++ = (Byte)(state); } Init(); } /////////////////////////// // Words version void CContext32::Update(const UInt32 *data, size_t size) { while (size-- > 0) { _buffer[_count2++] = *data++; if (_count2 == kBlockSizeInWords) { _count2 = 0; UpdateBlock(); } } } void CContext32::Final(UInt32 *digest) { const UInt64 lenInBits = (_count << 9) + ((UInt64)_count2 << 5); unsigned curBufferPos = _count2; _buffer[curBufferPos++] = 0x80000000; while (curBufferPos != (16 - 2)) { curBufferPos &= 0xF; if (curBufferPos == 0) UpdateBlock(); _buffer[curBufferPos++] = 0; } _buffer[curBufferPos++] = (UInt32)(lenInBits >> 32); _buffer[curBufferPos++] = (UInt32)(lenInBits); GetBlockDigest(_buffer, digest); Init(); } }}
[ "[email protected]@8d1da77e-e9f6-11de-9c2a-cb0f5ba72f9d" ]
[ [ [ 1, 211 ] ] ]
54abc7eaa1527da03203514e9698577f3fe5fe2b
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Physics/Collide/Query/CastUtil/hkpWorldRayCaster.h
bfb24cde4e7a4b773037b1d1539afa5ba636a615
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
3,909
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_WORLD_RAY_CASTER_H #define HK_WORLD_RAY_CASTER_H #include <Physics/Collide/BroadPhase/hkpBroadPhaseCastCollector.h> #include <Physics/Collide/Shape/Query/hkpShapeRayCastInput.h> #include <Physics/Collide/Query/CastUtil/hkpWorldRayCastInput.h> struct hkpWorldRayCastInput; struct hkpWorldRayCastOutput; class hkpCollisionFilter; class hkpRayCollidableFilter; class hkpBroadPhase; typedef char hkpBroadPhaseAabbCache; /// This is a utility class, which connects the hkpBroadPhase::castRay() to the hkpShape::castRay /// This method uses the collector interface (instead of the structure interface ( see hkpSimpleWorldRayCaster ) ) /// This is called by hkpWorld::castRay(). Usually you should call hkpWorld::castRay instead of /// using this class directly. class hkpWorldRayCaster : public hkpBroadPhaseCastCollector { public: hkpWorldRayCaster(){} ~hkpWorldRayCaster(){} /// This function cast a ray through the world. /// For each narrowphase object the ray hits, the hkpWorldRayCastOutput receives a callback /// You can pass in an optional hkpBroadPhaseAabbCache: See hkpBroadPhase for Details. void castRay( const hkpBroadPhase& broadphase, const hkpWorldRayCastInput& input, const hkpCollisionFilter* filter, const hkpBroadPhaseAabbCache* cache, hkpRayHitCollector& collector ); /// Casts a group of rays in close proximity /// collectorBase points to an array of collectors of the same type (not pointers) and /// collectorStriding should be set to the size of the collector type.<br> /// Note: If you set collectorStriding to 0, than all hits will be reported to the first collector void castRayGroup( const hkpBroadPhase& broadphase, const hkpWorldRayCastInput* inputArray, int numRays, const hkpCollisionFilter* filter, hkpRayHitCollector* collectorBase, int collectorStriding ) ; /// Cast multiple rays having the same startpoint. /// Notes: /// - the startpoint is taken only from the first input /// - However filtering can be done separate for each ray. void castRaysFromSinglePoint( const hkpBroadPhase& broadphase, const hkpWorldRayCastInput* inputArray, int numRays, const hkpCollisionFilter* filter, const hkpBroadPhaseAabbCache* cache, hkpRayHitCollector* collectorBase, int collectorStriding ); protected: virtual hkReal addBroadPhaseHandle( const hkpBroadPhaseHandle* broadPhaseHandle, int castIndex ); protected: const hkpWorldRayCastInput* m_input; const hkpRayCollidableFilter* m_filter; hkpRayHitCollector* m_collectorBase; int m_collectorStriding; // used as a temporary storage hkpShapeRayCastInput m_shapeInput; }; #endif //HK_WORLD_RAY_CASTER_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222) * * Confidential Information of Havok. (C) Copyright 1999-2009 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ [ [ 1, 81 ] ] ]
502c8407d7827c4f981158a96f67540411728b8a
5236606f2e6fb870fa7c41492327f3f8b0fa38dc
/nsrpc/test/EchoTest/EchoServer.h
3cbcb5552ef840ca17593ad7cbedb36e5cfad106
[]
no_license
jcloudpld/srpc
aa8ecf4ffc5391b7183b19d217f49fb2b1a67c88
f2483c8177d03834552053e8ecbe788e15b92ac0
refs/heads/master
2021-01-10T08:54:57.140800
2010-02-08T07:03:00
2010-02-08T07:03:00
44,454,693
0
0
null
null
null
null
UTF-8
C++
false
false
3,482
h
#ifndef ECHOTEST_ECHOSERVER_H #define ECHOTEST_ECHOSERVER_H #ifdef _MSC_VER # pragma once #endif #include <nsrpc/nsrpc.h> #include <nsrpc/config/Proactor.h> #if defined(NSRPC_HAS_PROACTOR) #include "Config.h" #include "EchoInterface.h" #include <nsrpc/detail/SessionRpcNetwork.h> #include <nsrpc/detail/PacketCoderFactory.h> #include <nsrpc/utility/MessageBlockManager.h> #include <nsrpc/SessionFactory.h> #include <nsrpc/RpcProactorSession.h> #include <nsrpc/RpcSessionConfig.h> #include <nsrpc/PacketSeedExchangerFactory.h> #include <srpc/RpcForwarder.h> #include <srpc/RpcReceiver.h> /** * @class EchoServerSession */ class EchoServerSession : public nsrpc::ProactorSession { public: EchoServerSession(const nsrpc::SessionConfig& config) : nsrpc::ProactorSession(config) {} private: virtual bool onMessageArrived(nsrpc::CsMessageType /*messageType*/) { echo(); return true; } virtual void onDisconnected() {} private: void echo() { ACE_Message_Block& sblock = acquireSendBlock(); const ACE_Message_Block& rblock = acquireRecvBlock(); sblock.copy(rblock.rd_ptr(), rblock.length()); sendMessage(sblock); } }; /** * @class EchoServerRpcSession */ class EchoServerRpcSession : public nsrpc::RpcProactorSession, public Echo, protected srpc::RpcForwarder, protected srpc::RpcReceiver { DECLARE_SRPC_EVENT_DISPATCHER(EchoServerRpcSession); public: EchoServerRpcSession(const nsrpc::RpcSessionConfig& config); OVERRIDE_SRPC_METHOD_1(echo, srpc::RString, data); OVERRIDE_SRPC_METHOD_1(onEcho, srpc::RString, data); private: virtual void onDisconnected() {} }; /** * @class ServerSessionFactory */ class ServerSessionFactory : public nsrpc::SessionFactory { public: ServerSessionFactory(const Config& config, NSRPC_Proactor* proactor, bool useBitPacking) : config_(config), proactor_(proactor), useBitPacking_(useBitPacking), messageBlockManager_(100, 1024), sessionDestroyer_(0) {} virtual void setSessionDestroyer( nsrpc::SessionDestroyer& sessionDestroyer) { sessionDestroyer_ = &sessionDestroyer; } virtual nsrpc::Session* create() const { nsrpc::SynchMessageBlockManager& messageBlockManager = const_cast<ServerSessionFactory*>(this)->messageBlockManager_; if (config_.useRpc()) { return new EchoServerRpcSession( nsrpc::RpcSessionConfig(sessionDestroyer_, &messageBlockManager, nsrpc::PacketCoderFactory().create(), proactor_, nsrpc::SessionCapacity::getNoLimitedCapacity(), new nsrpc::SessionRpcNetwork(useBitPacking_), nsrpc::PacketSeedExchangerFactory::createForServer())); } return new EchoServerSession( nsrpc::SessionConfig(sessionDestroyer_, &messageBlockManager, nsrpc::PacketCoderFactory().create(), proactor_, nsrpc::SessionCapacity::getNoLimitedCapacity())); } private: const Config& config_; NSRPC_Proactor* proactor_; bool useBitPacking_; nsrpc::SynchMessageBlockManager messageBlockManager_; nsrpc::SessionDestroyer* sessionDestroyer_; }; #endif // #if defined(NSRPC_HAS_PROACTOR) #endif // ECHOTEST_ECHOSERVER_H
[ "kcando@6d7ccee0-1a3b-0410-bfa1-83648d9ec9a4" ]
[ [ [ 1, 113 ] ] ]
ccf8c8e089570a0f14505ad48b8496dc0c5a7d74
6253ab92ce2e85b4db9393aa630bde24655bd9b4
/Common/Velodyne/VelodyneReceiver.cpp
6a0650762a0fb8253c5150c0729c63da8e37d1f6
[]
no_license
Aand1/cornell-urban-challenge
94fd4df18fd4b6cc6e12d30ed8eed280826d4aed
779daae8703fe68e7c6256932883de32a309a119
refs/heads/master
2021-01-18T11:57:48.267384
2008-10-01T06:43:18
2008-10-01T06:43:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,827
cpp
#include "VelodyneReceiver.h" #define USE_MATH_DEFINES #include <math.h> #include <utility> #include "../Math/Angle.h" #include "../Time/Timing.h" extern HANDLE hStdout; VelodyneReceiver::VelodyneReceiver(car_timestamp_sync* vtsProvider, bool filter){ udp_params params = udp_params(); params.remote_ip = inet_addr(VELODYNE_REMOTE_IP); params.local_port = VELODYNE_PORT; params.reuse_addr = true; conn = new udp_connection (params); conn->set_callback (MakeDelegate(this,&VelodyneReceiver::UDPCallback),conn); scanSegmentCallback = NULL; this->vtsProvider = vtsProvider; filterPoints = filter; for(int i=0;i<64;i++){ VelodyneFactors f; const T_corr_factors* table = (i<32)?velodyne_bottom_block_laser_correction_factors:velodyne_top_block_laser_correction_factors; f.RCF = (float)asin(table[i%32][0]); f.VCF = (float)asin(table[i%32][1]); f.RCF_SIN = (float)table[i%32][0]; f.VCF_SIN = (float)table[i%32][1]; f.RCF_COS = (float)table[i%32][2]; f.VCF_COS = (float)table[i%32][3]; f.HCF = (float)table[i%32][4]/100.f; factors[i] = f; } timeSpentInUDPCallback=0; numUDPCallbacks=0; timeSpentInUserCallback=0; } VelodyneReceiver::~VelodyneReceiver(){ delete conn; } void VelodyneReceiver::UDPCallback(udp_message& msg, udp_connection* conn, void* arg){ if(msg.len != 1206){ printf("VELODYNE: incorrect packet size (%d)\n",msg.len); return; // incorrect packet size! } TIMER tmr=GetTime(); unsigned int nRead=0; unsigned short tmpUShort; unsigned char tmpUChar; VelodyneScan scan; scan.pts.reserve(12*32); if(vtsProvider!=NULL){ car_timestamp ct = vtsProvider->current_time(); if(ct.is_valid()) scan.vts = ct.total_secs(); else scan.vts = -1; } float maxRotation=-1000; #define RD(X) memcpy(&X,msg.data+nRead,sizeof(X)); nRead+=sizeof(X); for(unsigned int firing=0;firing<12;firing++){ RD(tmpUShort); unsigned short blockHeaderID = tmpUShort; RD(tmpUShort); float rotation = (float)tmpUShort / 100.f; rotation *= -(F_PI / 180.f); maxRotation = MAX(maxRotation,rotation); const T_corr_factors * corr_factors; unsigned char lno=0; if(blockHeaderID==0xEEFF){ // this is from 32 "upper" lasers corr_factors = velodyne_top_block_laser_correction_factors; lno=32; } else{ // should be 0xDDFF - lower 32 lasers. corr_factors = velodyne_bottom_block_laser_correction_factors; lno=0; } float rot_cos = cosf(rotation); float rot_sin = sinf(rotation); for(unsigned char laser=0;laser<32;laser++){ RD(tmpUShort); RD(tmpUChar); if(lno==0){ if(laser==17) continue; // for now, ignore laser 17... (#18, low block) if(laser==1 || laser==4 || laser==22|| laser==15|| laser==8) continue; // for now, ignore laser 17... (#18, low block) //DEBUG } VelodynePt vpt; vpt.range = (float)tmpUShort*.002f; // aho - I don't know why this is here if(vpt.range < 1.0) continue; vpt.range += .15f; vpt.intensity = (float)tmpUChar; /* float& cosVertAngle = factors[lno+laser].VCF_COS; float& sinVertAngle = factors[lno+laser].VCF_SIN; float& cosRotCorrection = factors[lno+laser].RCF_COS; float& sinRotCorrection = factors[lno+laser].RCF_SIN; float cosRotAngle = rot_cos*cosRotCorrection + rot_sin*sinRotCorrection; float sinRotAngle = rot_sin*cosRotCorrection - rot_cos*sinRotCorrection; float& distance = vpt.range; float hOffsetCorr = factors[lno+laser].HCF; float vOffsetCorr = 0; // top vs bottom block (everything is centered center of unit at bottom block height) float xyDistance = distance*cosVertAngle - vOffsetCorr*sinVertAngle; vpt.x = xyDistance * sinRotAngle - hOffsetCorr * cosRotAngle; vpt.y = xyDistance * cosRotAngle + hOffsetCorr * sinRotAngle; vpt.z = distance * sinVertAngle + vOffsetCorr * cosVertAngle; */ float x = vpt.range * factors[lno+laser].RCF_COS * factors[lno+laser].VCF_COS; float y = vpt.range * factors[lno+laser].RCF_SIN * factors[lno+laser].VCF_COS; float z = vpt.range * factors[lno+laser].VCF_SIN; vpt.x = (x * rot_cos) - (y * rot_sin); vpt.y = (x * rot_sin) + (y * rot_cos); vpt.z = z; if(lno!=0) vpt.z += VELODYNE_BOTTOM_TO_TOP_BLOCK_DIST; vpt.sensorTheta = factors[lno+laser].RCF + rotation; if(vpt.sensorTheta<0.f) vpt.sensorTheta += F_PI*2.f; if(vpt.sensorTheta>2.f*F_PI) vpt.sensorTheta -= F_PI*2.f; if (filterPoints) { if(vpt.sensorTheta > 5.f*F_PI/8.f && vpt.sensorTheta < 11.f*F_PI/8.f) continue; if(fabsf(vpt.y)>30.f) continue; if(vpt.x > 60) continue; if(vpt.x < -10) continue; } vpt.laserNum = lno+laser; vpt.blockTheta = rotation; scan.pts.push_back(vpt); } } char buf[5] = {0,0,0,0,0}; memcpy(buf,msg.data+nRead+2,4); //printf("%s\n",buf); // figure out the timestamps... for(unsigned int i=0;i<scan.pts.size();i++){ if(maxRotation==scan.pts[i].blockTheta){ scan.pts[i].vts = scan.vts; }else{ double dt = AngleDiff((float)maxRotation,(float)scan.pts[i].blockTheta)/(F_PI*2.f) * 1.f/15.f; scan.pts[i].vts = scan.vts + dt; } } #undef RD TIMER usrCallbackTmr = GetTime(); if(scanSegmentCallback!=NULL) scanSegmentCallback(scan,scanSegmentCallbackParam); timeSpentInUDPCallback+=TimeElapsed(tmr); timeSpentInUserCallback+=TimeElapsed(usrCallbackTmr); numUDPCallbacks++; }
[ "anathan@5031bdca-8e6f-11dd-8a4e-8714b3728bc5" ]
[ [ [ 1, 188 ] ] ]
482e4a447cdd6588731eee200393407e4cc2dc1f
be2e23022d2eadb59a3ac3932180a1d9c9dee9c2
/GameServer/MapGroupKernel/Enemy.cpp
0e0ae6d082900c308e3e4c5c2a3211cf97484ed8
[]
no_license
cronoszeu/revresyksgpr
78fa60d375718ef789042c452cca1c77c8fa098e
5a8f637e78f7d9e3e52acdd7abee63404de27e78
refs/heads/master
2020-04-16T17:33:10.793895
2010-06-16T12:52:45
2010-06-16T12:52:45
35,539,807
0
2
null
null
null
null
GB18030
C++
false
false
4,549
cpp
#include "windows.h" #include "define.h" #include "Enemy.h" #include "i_mydb.h" #include "User.h" #include "AllMsg.h" #include "MapGroup.h" MYHEAP_IMPLEMENTATION(CEnemy,s_heap) CEnemy::CEnemy() { } CEnemy::~CEnemy() { } bool CEnemy::Create(PROCESS_ID idProcess, CUser *pOwner, IDatabase* pDb) { m_idProcess = idProcess; m_pOwner = pOwner; SQLBUF szSQL; sprintf(szSQL, "SELECT * FROM %s WHERE userid=%d ORDER BY time", _TBL_ENEMY, m_pOwner->GetID()); IRecordset* pRes = pDb->CreateNewRecordset(szSQL, false); if(pRes) { for(int i = 0; i < pRes->RecordCount(); i++, pRes->MoveNext()) { NAMESTR szName; pRes->LoadString(szName, "enemyname", _MAX_NAMESIZE); Add(pRes->LoadDWord("enemy"), szName, SYNCHRO_FALSE, UPDATE_FALSE); } pRes->Release(); } return true; } bool CEnemy::Create(PROCESS_ID idProcess, CUser *pOwner) { m_idProcess = idProcess; m_pOwner = pOwner; return true; } bool CEnemy::GetInfo(CEnemyInfoStruct* pInfo) { CHECKF(pInfo); memset(pInfo, 0, sizeof(CEnemyInfoStruct)); for(int i = 0; i < MAX_ENEMYSIZE && i< m_set.Size(); i++) { pInfo->setEnemy[i] = m_set[i].first; SafeCopy(pInfo->setName[i], m_set[i].second.c_str(), _MAX_NAMESIZE); } return true; } bool CEnemy::AppendInfo(const CEnemyInfoStruct* pInfo) { CHECKF(pInfo); for(int i = 0; i < MAX_ENEMYSIZE; i++) { if(pInfo->setEnemy[i]) m_set.Push(make_pair(pInfo->setEnemy[i], String(pInfo->setName[i]))); } return true; } void CEnemy::Add(OBJID idEnemy, LPCTSTR szName, bool bSynchro, bool bUpdate) { bool bInsertNew = true; ENEMY_SET::Iterator pEnemy = m_set.NewEnum(); while(pEnemy.Next()) { if(pEnemy && pEnemy->first == idEnemy) { m_set.DelObj(pEnemy); bInsertNew = false; } } m_set.Push(make_pair(idEnemy, String(szName))); if(bSynchro) { CMsgFriend msg; IF_OK(msg.Create(_ENEMY_ADD, idEnemy, szName, true)) // true: online m_pOwner->SendMsg(&msg); } if(bUpdate) { if(bInsertNew) { SQLBUF szSQL; sprintf(szSQL, "INSERT %s VALUES(0, %u, %u, '%s', %u)", _TBL_ENEMY, m_pOwner->GetID(), idEnemy, szName, time(NULL)); Database()->ExecuteSQL(szSQL); } else { SQLBUF szSQL; sprintf(szSQL, "UPDATE %s SET time=%u WHERE userid=%u && enemy=%u LIMIT 1", _TBL_ENEMY, time(NULL), m_pOwner->GetID(), idEnemy); Database()->ExecuteSQL(szSQL); } } if(m_set.Size() > MAX_ENEMYSIZE) Del(m_set[0].first, UPDATE_TRUE); } void CEnemy::Del(OBJID idEnemy, bool bUpdate) { ENEMY_SET::Iterator pEnemy = m_set.NewEnum(); while(pEnemy.Next()) { if(pEnemy && pEnemy->first == idEnemy) { m_set.DelObj(pEnemy); // synchro { CMsgFriend msg; IF_OK_(msg.Create(_ENEMY_DEL, idEnemy, "")) m_pOwner->SendMsg(&msg); } if(bUpdate) { SQLBUF szSQL; sprintf(szSQL, "DELETE FROM %s WHERE userid=%u && enemy=%u LIMIT 1", _TBL_ENEMY, m_pOwner->GetID(), idEnemy); Database()->ExecuteSQL(szSQL); } return ; } } } LPCTSTR CEnemy::GetName(OBJID idEnemy) { ENEMY_SET::Iterator pEnemy = m_set.NewEnum(); while(pEnemy.Next()) { if(pEnemy && pEnemy->first == idEnemy) return pEnemy->second.c_str(); } return NULL; } void CEnemy::BeforeLogout() { CMsgFriend msg; IF_NOT(msg.Create(_ENEMY_OFFLINE, m_pOwner->GetID(), m_pOwner->GetName())) return; ENEMY_SET::Iterator pEnemy = m_set.NewEnum(); pEnemy.Reset(); while(pEnemy.Next()) { OBJID idEnemy = pEnemy->first; CUser* pUser = UserManager()->GetUser(idEnemy); if(pUser) { pUser->SendMsg(&msg); } else { MapGroup(PID)->QueryIntraMsg()->TransmitWorldMsgByUserID(&msg, idEnemy); } } } void CEnemy::SendToClient() { ENEMY_SET::Iterator pEnemy = m_set.NewEnum(); while(pEnemy.Next()) { OBJID idEnemy = pEnemy->first; bool bOnline = (UserManager()->GetUser(idEnemy) != NULL); CMsgFriend msg; if(msg.Create(_ENEMY_ADD, idEnemy, pEnemy->second, bOnline)) m_pOwner->SendMsg(&msg); if(!bOnline) MapGroup(PID)->QueryIntraMsg()->TransmitMsg(&msg, m_pOwner->GetSocketID(), m_pOwner->GetID()); // 通知其它地图组,下传给我好友在线的消息 } // broadcast self online to all enemy pEnemy.Reset(); while(pEnemy.Next()) { OBJID idFriend = pEnemy->first; CMsgFriend msg; IF_OK(msg.Create(_ENEMY_ONLINE, m_pOwner->GetID(), m_pOwner->GetName())) MapGroup(PID)->QueryIntraMsg()->TransmitWorldMsgByUserID(&msg, idFriend); } }
[ "rpgsky.com@cc92e6ba-efcf-11de-bf31-4dec8810c1c1" ]
[ [ [ 1, 203 ] ] ]
7dd190aff6161101104031c858319f594487a30f
1536bdbfb912d9bec8cea8c85d144033570bcb62
/agent/browser/ie/pagetest/SocketEvents.cpp
446638371b3e4e14f16e9d86470576f4d69104a7
[]
no_license
sdo-ops/WebPageTest-mirror-
ad6efec365471072ce62b6ecaa4c1eb4f2808794
16bcff6e67a49bc84611cedd3f2d7224893ef021
refs/heads/master
2020-12-24T13:28:49.940398
2011-02-20T16:37:45
2011-02-20T16:37:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,885
cpp
/* Copyright (c) 2005-2007, AOL, LLC. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the company nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "StdAfx.h" #include "SocketEvents.h" #include <wininet.h> /*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ CSocketEvents::CSocketEvents(void): nextSocketId(1) , simFlagged(0) , bwBytesIn(0) { } /*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ CSocketEvents::~CSocketEvents(void) { } /*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ void CSocketEvents::Reset(void) { __super::Reset(); EnterCriticalSection(&cs); nextSocketId = 1; simFlagged = 0; bwBytesIn = 0; LeaveCriticalSection(&cs); } #pragma warning(push) #pragma warning(disable:4244) /*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ void CSocketEvents::NewSocket(SOCKET s) { CheckStuff(); EnterCriticalSection(&cs); ATLTRACE(_T("[Pagetest] - (0x%08X) Socket %d assigned ID %d\n"), GetCurrentThreadId(), s, nextSocketId); // delete any old socket that was at the same position CSocketInfo * info = NULL; openSockets.Lookup(s, info); if( info ) { delete info; openSockets.RemoveKey(s); } // create a new socket for our list of open sockets info = new CSocketInfo(s, nextSocketId); socketID.SetAt((UINT_PTR)s, nextSocketId); nextSocketId++; openSockets.SetAt(s, info); LeaveCriticalSection(&cs); } /*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ void CSocketEvents::CloseSocket(SOCKET s) { EnterCriticalSection(&cs); ATLTRACE(_T("[Pagetest] - (0x%08X) CWatchDlg::CloseSocket - %d\n"), GetCurrentThreadId(), s); // close out any open requests on the socket POSITION pos = requests.GetHeadPosition(); CSocketRequest * socketRequest = NULL; while( pos ) { POSITION old = pos; CSocketRequest * r = requests.GetNext(pos); if( r && r->s == s ) { socketRequest = r; requests.RemoveAt(old); pos = 0; } } // see if we can line up a winInet request with this socket if( socketRequest ) { CWinInetRequest * linked = socketRequest->linkedRequest; if( linked && !linked->end ) linked->Done(false); } DWORD id = 0; socketID.Lookup(s, id); if( id ) requestSocketIds.RemoveKey(id); // remove the socket ID that was tied to this socket socketID.RemoveKey((UINT_PTR)s); // if it was a flagged connection, reduce the simultaneous count if( socketRequest && socketRequest->connect && socketRequest->connect->flaggedConnection && simFlagged > 0 ) simFlagged--; LeaveCriticalSection(&cs); } #pragma warning(pop) /*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ void CSocketEvents::SocketSend(SOCKET s, DWORD len, LPBYTE buff) { if( !active && available ) { if(!IsFakeSocket(s, len, buff) && CheckABM() ) { CString url(_T("Data Transmitted")); DoStartup(url); } } // make sure we are timing something if( active ) { CheckStuff(); if(!IsFakeSocket(s, len, buff) ) { ATLTRACE(_T("[Pagetest] - (0x%08X) CWatchDlg::SocketSend - socket %d, currentDoc = %d\n"), GetCurrentThreadId(), s, currentDoc); // figure out what the client port is struct sockaddr_in local; int localLen = sizeof(local); getsockname(s, (sockaddr *)&local, &localLen); // see if this socket had an existing connect. If so, end that now EnterCriticalSection(&cs); POSITION pos = connects.GetHeadPosition(); while( pos ) { POSITION old = pos; CSocketConnect * c = connects.GetNext(pos); if( c && !c->end && c->s == s) { c->Done(); // remove it from the pending connections list (will still be in the tracked events) connects.RemoveAt(old); pos = 0; } } // see if there is an existing request that this is part of CSocketRequest * request = NULL; pos = requests.GetHeadPosition(); POSITION requestPos = NULL; while( pos && !request ) { POSITION old = pos; CSocketRequest * r = requests.GetNext(pos); if( r && r->s == s ) { request = r; requestPos = old; } } if( request ) { bool cont = false; if( !request->in ) cont = true; else if( ((request->linkedRequest && request->linkedRequest->secure) || request->port == 443) && request->connect ) { // do some checking to see if we're past the SSL handshake if( !(request->connect->state % 2) ) request->connect->state++; if( request->connect->state <= 3 ) cont = true; } // Do we continue the existing request? if( cont ) { // store information about the request request->out += len; request->request.AddData(len, buff); request->firstByte = 0; } else { if( requestPos ) requests.RemoveAt(requestPos); request = NULL; } } // If we didn't have an existing request to work with, create a new one if( !request ) { // create the new request object (assume for now that every send will be a new request) request = new CSocketRequest(s, currentDoc); // store information about the request request->out = len; request->request.AddData(len, buff); // Get the IP address of the socket CSocketInfo * soc = NULL; openSockets.Lookup( s, soc ); if( soc ) { request->ipAddress[0] = soc->ipAddress[0]; request->ipAddress[1] = soc->ipAddress[1]; request->ipAddress[2] = soc->ipAddress[2]; request->ipAddress[3] = soc->ipAddress[3]; request->port = soc->port; request->socketId = soc->id; } // find the connection this is tied to POSITION pos = events.GetHeadPosition(); while( pos ) { CTrackedEvent * e = events.GetNext(pos); if( e && e->type == CTrackedEvent::etSocketConnect ) { CSocketConnect * c = (CSocketConnect *)e; if( c->socketId == request->socketId ) { request->host = c->host; if( !c->request ) { c->request = request; request->connect = c; } pos = 0; } } } // add the new request to the list requests.AddHead(request); request->request.Process(); AddEvent(request); } else request->request.Process(); // link this to the winInet request from the same thread if( request && !request->linkedRequest ) linkSocketRequestSend(request); requestSocketIds.SetAt(request->socketId, request); LeaveCriticalSection(&cs); } else { // pull it out of the connection list EnterCriticalSection(&cs); POSITION pos = connects.GetHeadPosition(); while( pos ) { POSITION old = pos; CSocketConnect * c = connects.GetNext(pos); if( c && !c->end && c->s == s) { // remove it from the pending connections list (will still be in the tracked events) connects.RemoveAt(old); pos = 0; } } LeaveCriticalSection(&cs); } } else if( !IsFakeSocket(s,0,0) ) { ATLTRACE(_T("[Pagetest] - CWatchDlg::SocketSend - outside of active request\n")); } } /*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ void CSocketEvents::SocketRecv(SOCKET s, DWORD len, LPBYTE buff) { if( active ) { CheckStuff(); if( !IsFakeSocket(s,0,0) ) { __int64 now; QueryPerformanceCounter((LARGE_INTEGER *)&now); ATLTRACE(_T("[Pagetest] - (0x%08X) CWatchDlg::SocketRecv - socket %d, %d bytes, open requests = %d\n"), GetCurrentThreadId(), s, len, openRequests); bool repaint = false; bwBytesIn += len; // update the bandwidth info EnterCriticalSection(&cs); // update the start and end of response on the request object POSITION pos = requests.GetHeadPosition(); while( pos ) { CSocketRequest * r = requests.GetNext(pos); if( r && r->s == s ) { requestSocketIds.SetAt(r->socketId, r); // see if we already recorded time to first byte on the response if( !r->firstByte ) r->firstByte = now; // increment the amount of incoming data r->in += len; r->response.AddData(len, buff); // toggle the ssl state if( ((r->linkedRequest && r->linkedRequest->secure) || r->port == 443) && r->connect && r->connect->state % 2 ) r->connect->state++; // update the end time of the linked request if( r->linkedRequest ) { r->linkedRequest->Done(); r->linkedRequest->in = r->in; } // update the end time (this can be done multiple times) r->Done(); now = r->end; } } LeaveCriticalSection(&cs); if( repaint ) RepaintWaterfall(); } } else if( !IsFakeSocket(s,0,0) ) { ATLTRACE(_T("[Pagetest] - CWatchDlg::SocketRecv - outside of active request\n")); } } /*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ void CSocketEvents::SocketConnect(SOCKET s, struct sockaddr_in * addr) { // if we're doing activity based measurement then start tracking if( !active && available && addr ) { // make sure it's not the loopback socket if( addr->sin_addr.S_un.S_addr != 0x0100007F && CheckABM() ) { ATLTRACE(_T("[Pagetest] - CWatchDlg::SocketConnect outside of active doc, doing startup")); CString url(_T("Socket Connected")); DoStartup(url); } } // create the new connect attempt CSocketConnect * c = new CSocketConnect(s, *addr, currentDoc); // update the IP address on the socket EnterCriticalSection(&cs); CSocketInfo * soc = NULL; openSockets.Lookup(s, soc); if( soc ) { soc->ipAddress[0] = c->addr[0]; soc->ipAddress[1] = c->addr[1]; soc->ipAddress[2] = c->addr[2]; soc->ipAddress[3] = c->addr[3]; soc->port = c->port; c->socketId = soc->id; memcpy( &soc->address, addr, sizeof(SOCKADDR_IN) ); } LeaveCriticalSection(&cs); // make sure we are timing something if( active ) { ATLTRACE(_T("[Pagetest] - (0x%08X) CWatchDlg::SocketConnect - socket %d, currentDoc = %d\n"), GetCurrentThreadId(), s, currentDoc); CheckStuff(); // see if we have to bind the socket to a particular interface // make sure it's not the loopback socket if( bindAddr && addr->sin_addr.S_un.S_addr != 0x0100007F ) { sockaddr_in name; name.sin_family = AF_INET; name.sin_addr.S_un.S_addr = bindAddr; name.sin_port = 0; if (!bind(s, (sockaddr *)&name, sizeof(name))) { ATLTRACE(_T("[Pagetest] - bind successful\n")); } else { ATLTRACE(_T("[Pagetest] - bind failed : %d\n"), WSAGetLastError()); } } EnterCriticalSection(&cs); // find which DNS entry this socket came from (only the first socket to claim a DNS entry wins) POSITION pos = dns.GetHeadPosition(); while( pos ) { CDnsLookup * d = dns.GetNext(pos); if( d && d->addressCount ) { for( int i = 0; i < d->addressCount; i++ ) { if( d->address[i].S_un.S_addr == addr->sin_addr.S_un.S_addr ) { pos = 0; c->host = d->name; if( !d->socket ) { d->socket = c; c->dns = d; } } } } } connects.AddHead(c); AddEvent(c); // link this to the winInet request from the same thread if( c ) linkSocketRequestConnect(c); // see if it is a flagged connection CheckFlaggedConnection(c, addr->sin_addr.S_un.S_addr); LeaveCriticalSection(&cs); // see if we know the local port (so we can add it to the traffic shaping rules) if( addr ) { SOCKADDR_IN local; int len = sizeof(local); if( !getsockname(s, (sockaddr *)&local, &len) ) { ATLTRACE(_T("[Pagetest] - Connecting: %d.%d.%d.%d : %d -> %d.%d.%d.%d : %d"), local.sin_addr.S_un.S_un_b.s_b1, local.sin_addr.S_un.S_un_b.s_b2, local.sin_addr.S_un.S_un_b.s_b3, local.sin_addr.S_un.S_un_b.s_b4, htons(local.sin_port), addr->sin_addr.S_un.S_un_b.s_b1, addr->sin_addr.S_un.S_un_b.s_b2, addr->sin_addr.S_un.S_un_b.s_b3, addr->sin_addr.S_un.S_un_b.s_b4, htons(addr->sin_port) ); } } } else delete c; } /*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ void CSocketEvents::SocketBind(SOCKET s, struct sockaddr_in * addr) { // make sure we are timing something if( active ) { // see if we have to bind the socket to a particular interface // make sure it's not the loopback socket if( bindAddr && addr && addr->sin_addr.S_un.S_addr != 0x0100007F ) { ATLTRACE(_T("[Pagetest] - changing bind address\n")); addr->sin_addr.S_un.S_addr = bindAddr; } } } /*----------------------------------------------------------------------------- Determine if the given socket is a fake socket -----------------------------------------------------------------------------*/ bool CSocketEvents::IsFakeSocket(SOCKET s, DWORD dataLen, LPBYTE buff) { bool ret = false; EnterCriticalSection(&cs); // find the socket info CSocketInfo * sock = NULL; openSockets.Lookup(s, sock); if( sock ) { if( sock->fake ) ret = true; else if( sock->dataSent ) ret = false; else { // ok, not clear cut, we need to figure it out if we haven't already if( dataLen == 1 && buff && *buff == '!' ) ret = sock->fake = sock->dataSent = true; else if( dataLen ) sock->dataSent = true; } } LeaveCriticalSection(&cs); return ret; } /*----------------------------------------------------------------------------- See if the connection falls within an address range we're flagging -----------------------------------------------------------------------------*/ bool CSocketEvents::CheckFlaggedConnection(CSocketConnect * c, DWORD hostAddr) { bool found = false; /* DWORD addr = htonl(hostAddr); for( int i = 0; i < _countof(flagConnections) && !found; i++ ) { DWORD ip = htonl(inet_addr(flagConnections[i].ip)); DWORD bits = flagConnections[i].bits; DWORD mask = 0xFFFFFFFF << (32 - bits); if( (ip & mask) == (addr & mask) ) found = true; } if( found && c ) { c->flaggedConnection = true; simFlagged++; totalFlagged++; if( simFlagged > maxSimFlagged ) maxSimFlagged = simFlagged; } */ return found; }
[ "[email protected]@aac4e670-4c05-fb8f-3594-08f7db841d5f" ]
[ [ [ 1, 585 ] ] ]
ac95732a972fb9de5e2ecce7fb8b2636aa72ee3e
ab2777854d7040cc4029edcd1eccc6d48ca55b29
/Algorithm/AutoFinder/NonCachedTextMgr/NonCachedTextArgMgr.cpp
aaf1358a6978475e476ebf5ff3b3e7d93c6811da
[]
no_license
adrix89/araltrans03
f9c79f8e5e62a23bbbd41f1cdbcaf43b3124719b
6aa944d1829006a59d0f7e4cf2fef83e3f256481
refs/heads/master
2021-01-10T19:56:34.730964
2009-12-21T16:21:45
2009-12-21T16:21:45
38,417,581
0
0
null
null
null
null
UHC
C++
false
false
20,984
cpp
#pragma warning(disable:4312) #pragma warning(disable:4996) #include "../stdafx.h" #include "NonCachedTextArgMgr.h" #include "NonCachedTextArg.h" #include "Misc.h" #define TEXT_ARG_POOL_SIZE 100 CNonCachedTextArgMgr* CNonCachedTextArgMgr::_inst = NULL; int MyWideCharToMultiByte( UINT CodePage, DWORD dwFlags, LPCWSTR lpWideCharStr, int cchWideChar, LPSTR lpMultiByteStr, int cbMultiByte, LPCSTR lpDefaultChar, LPBOOL lpUsedDefaultChar ); int MyMultiByteToWideChar( UINT CodePage, DWORD dwFlags, LPCSTR lpMultiByteStr, int cbMultiByte, LPWSTR lpWideCharStr, int cchWideChar ); CNonCachedTextArgMgr::CNonCachedTextArgMgr(void) : m_bMatchLen(FALSE) { _inst = this; } CNonCachedTextArgMgr::~CNonCachedTextArgMgr(void) { Close(); _inst = NULL; } // 초기화 BOOL CNonCachedTextArgMgr::Init() { // 옵션 체크 //if (!lstrcmpiA(m_pszOptionStringBuffer, "MATCHLEN")) // m_bMatchLen=TRUE; //else m_bMatchLen=FALSE; // 중복 카운트 테이블 초기화 ZeroMemory(m_aDupCntTable, sizeof(m_aDupCntTable)); // 텍스트 인자 풀 생성 for(int i=0; i<TEXT_ARG_POOL_SIZE; i++) { m_setInactivatedArgs.insert(new CNonCachedTextArg()); } return TRUE; } // 말기화 void CNonCachedTextArgMgr::Close() { // 활성화 텍스트 인스턴스 모두 삭제 for(CNonCachedTextArgSet::iterator iter = m_setActivatedArgs.begin(); iter != m_setActivatedArgs.end(); iter++) { CNonCachedTextArg* pNonCachedTextArg = *(iter); delete pNonCachedTextArg; } m_setActivatedArgs.clear(); // 비활성화 텍스트 인스턴스 모두 삭제 for(CNonCachedTextArgSet::iterator iter = m_setInactivatedArgs.begin(); iter != m_setInactivatedArgs.end(); iter++) { CNonCachedTextArg* pNonCachedTextArg = *(iter); delete pNonCachedTextArg; } m_setInactivatedArgs.clear(); // 중복 카운트 테이블 초기화 ZeroMemory(m_aDupCntTable, sizeof(m_aDupCntTable)); } // 새로운 문자열 후보를 추가한다 BOOL CNonCachedTextArgMgr::AddTextArg(LPCWSTR wszText) { BOOL bRetVal = FALSE; CNonCachedTextArg* pNonCachedTextArg = NULL; if(!m_setInactivatedArgs.empty()) { CNonCachedTextArgSet::iterator iter = m_setInactivatedArgs.begin(); pNonCachedTextArg = ( *iter ); m_setInactivatedArgs.erase(pNonCachedTextArg); m_setActivatedArgs.insert(pNonCachedTextArg); } else { // 활성화 텍스트 인스턴스 모두 순환 for(CNonCachedTextArgSet::iterator iter = m_setActivatedArgs.begin(); iter != m_setActivatedArgs.end(); iter++) { CNonCachedTextArg* pTmpNonCachedTextArg = *(iter); if( NULL == pNonCachedTextArg || (pNonCachedTextArg->m_nFaultCnt < pTmpNonCachedTextArg->m_nFaultCnt) ) { pNonCachedTextArg = pTmpNonCachedTextArg; } } } if( pNonCachedTextArg->SetNonCachedTextArg(wszText) ) { bRetVal = TRUE; } else { m_setActivatedArgs.erase(pNonCachedTextArg); m_setInactivatedArgs.insert(pNonCachedTextArg); } return bRetVal; } // 문자열 후보들 전체를 테스트한다. (더이상 일치하지 않는 후보는 바로 삭제) BOOL CNonCachedTextArgMgr::TestCharacter(wchar_t wch) { BOOL bRetVal = FALSE; // 활성화 텍스트 인스턴스를 모두 순회 for(CNonCachedTextArgSet::iterator iter = m_setActivatedArgs.begin(); iter != m_setActivatedArgs.end();) { CNonCachedTextArg* pNonCachedTextArg = (*iter); iter++; // 예상되는 중복 횟수 구하기 UINT nPreperedDupCnt = 0; for(UINT i=1; i<16; i++) { if( m_aDupCntTable[nPreperedDupCnt] < m_aDupCntTable[i] ) { nPreperedDupCnt = i; } } // 검사 수행 int nRes = pNonCachedTextArg->TestCharacter(wch, nPreperedDupCnt); // 유예시 if( 0 != nRes ) { if( nRes & 0x01 ) bRetVal = TRUE; if( (nRes & 0x03) != 0 ) { int idx = pNonCachedTextArg->m_nDupCnt; if(idx<16) m_aDupCntTable[idx]++; } } // 폐기시 else { m_setActivatedArgs.erase(pNonCachedTextArg); m_setInactivatedArgs.insert(pNonCachedTextArg); } } return bRetVal; } // 최고로 확률이 높은 번역 문자를 반환 BOOL CNonCachedTextArgMgr::GetBestTranslatedCharacter(wchar_t* pTransResultBuf) { //wchar_t wchRetVal = L'\0'; CNonCachedTextArg* pBestArg = NULL; if( NULL == pTransResultBuf ) return FALSE; BOOL bRetVal = FALSE; // 활성화 텍스트 인스턴스 모두 순환 for(CNonCachedTextArgSet::iterator iter = m_setActivatedArgs.begin(); iter != m_setActivatedArgs.end(); iter++) { CNonCachedTextArg* pNonCachedTextArg = *(iter); if( NULL == pBestArg ) { if( 0 < pNonCachedTextArg->m_nHitCnt ) pBestArg = pNonCachedTextArg; } else if( pBestArg->m_nHitCnt < pNonCachedTextArg->m_nHitCnt ) { pBestArg = pNonCachedTextArg; } else if(pBestArg->m_nHitCnt == pNonCachedTextArg->m_nHitCnt) { size_t nBestRemain = pBestArg->m_nJapaneseLen - pBestArg->m_nNextTestIdx; size_t nTempRemain = pNonCachedTextArg->m_nJapaneseLen - pNonCachedTextArg->m_nNextTestIdx; if( nBestRemain < nTempRemain ) { pBestArg = pNonCachedTextArg; } else if( nBestRemain == nTempRemain && pBestArg->m_nFaultCnt > pNonCachedTextArg->m_nFaultCnt ) { pBestArg = pNonCachedTextArg; } } } if(pBestArg) { // 마지막 문자인 경우 다 반환 if(pBestArg->m_nJapaneseLen == pBestArg->m_nNextTestIdx-1 && pBestArg->m_nKoreanLen) { wcscpy( pTransResultBuf, &pBestArg->m_wszKoreanText[pBestArg->m_nNextKorIdx] ); } // 한문자 else { pTransResultBuf[0] = pBestArg->GetTranslatedCharacter(); pTransResultBuf[1] = L'\0'; } if(pTransResultBuf[0]) bRetVal = TRUE; } return bRetVal; } CNonCachedTextArg* CNonCachedTextArgMgr::FindString(LPCWSTR pTestString, int nSize) { CNonCachedTextArg* pMatchArg=NULL; // 활성화 텍스트 인스턴스를 모두 순회 for(CNonCachedTextArgSet::iterator iter = m_setActivatedArgs.begin(); iter != m_setActivatedArgs.end();) { CNonCachedTextArg* pNonCachedTextArg = (*iter); iter++; // 검사 수행 int nRes = pNonCachedTextArg->TestString(pTestString, nSize); // 폐기시 if (nRes == 0) { m_setActivatedArgs.erase(pNonCachedTextArg); m_setInactivatedArgs.insert(pNonCachedTextArg); } // 찾거나 중복시 else if (nRes != 4) { if ( !pMatchArg || ( nSize == 1 && pMatchArg->m_nJapaneseLen == 1 && pNonCachedTextArg->m_nJapaneseLen > 1) ) pMatchArg = pNonCachedTextArg; } } return pMatchArg; } BOOL CNonCachedTextArgMgr::GetTranslatedStringA(INT_PTR ptrBegin, LPCSTR szOrigString, int nOrigSize, wchar_t *pTransResultBuf, int nBufSize, int &nTransSize) { CNonCachedTextArg* pBestArg = NULL; if( NULL == pTransResultBuf ) return FALSE; BOOL bRetVal = FALSE; wchar_t wszOrigString[1024] = { L'\0', }; int nLen=MyMultiByteToWideChar(932, 0, szOrigString, nOrigSize, wszOrigString, 1023 ); pBestArg = FindString(wszOrigString, nLen); if (!pBestArg) { int iRes = SearchStringA(ptrBegin, szOrigString[0], szOrigString[1]); pBestArg = FindString(wszOrigString, nLen); } if(pBestArg) { nTransSize= nTransSize / 2; pBestArg->GetTranslatedString(pTransResultBuf, nBufSize, nTransSize); if(pTransResultBuf[0]) bRetVal = TRUE; } return bRetVal; } BOOL CNonCachedTextArgMgr::GetTranslatedStringW(INT_PTR ptrBegin, LPCWSTR wszOrigString, int nOrigSize, wchar_t *pTransResultBuf, int nBufSize, int &nTransSize) { CNonCachedTextArg* pBestArg = NULL; if( NULL == pTransResultBuf ) return FALSE; BOOL bRetVal = FALSE; pBestArg = FindString(wszOrigString, nOrigSize); if (!pBestArg) { int iRes = SearchStringW(ptrBegin, wszOrigString[0]); pBestArg = FindString(wszOrigString, nOrigSize); } if(pBestArg) { pBestArg->GetTranslatedString(pTransResultBuf, nBufSize, nTransSize); if(pTransResultBuf[0]) bRetVal = TRUE; } return bRetVal; } // 현재 활성화 된 텍스트 인자들이 하나도 없는가? BOOL CNonCachedTextArgMgr::IsEmpty() { return m_setActivatedArgs.empty(); } int CNonCachedTextArgMgr::SearchStringA(INT_PTR ptrBegin, char ch1, char ch2) { int iRetVal = 0; size_t dist = 0; while( IsBadReadPtr((void*)(ptrBegin+dist), sizeof(void*)) == FALSE ) { LPSTR* ppText = (LPSTR*)(ptrBegin+dist); if( IsBadStringPtrA(*ppText, 1024)==FALSE && (*ppText)[0]==ch1 && ('\0'==ch2 || (*ppText)[1]==ch2) && strlen(*ppText) < 1024 ) { wchar_t wszTmp[1024]; MyMultiByteToWideChar(932, 0, *ppText, -1, wszTmp, 1023 ); AddTextArg(wszTmp); iRetVal++; } dist += sizeof(void*); } return iRetVal; } int CNonCachedTextArgMgr::SearchStringW(INT_PTR ptrBegin, wchar_t wch) { int iRetVal = 0; size_t dist = 0; while( IsBadReadPtr((void*)(ptrBegin+dist), sizeof(void*)) == FALSE ) { LPWSTR* ppText = (LPWSTR*)(ptrBegin+dist); if( IsBadStringPtrW(*ppText, 1024)==FALSE && **ppText == wch ) { AddTextArg(*ppText); iRetVal++; } dist += sizeof(void*); } return iRetVal; } ////////////////////////////////////////////////////////////////////////// // // GetGlyphOutlineA // ////////////////////////////////////////////////////////////////////////// DWORD CNonCachedTextArgMgr::NewGetGlyphOutlineA( HDC hdc, // handle to device context UINT uChar, // character to query UINT uFormat, // format of data to return LPGLYPHMETRICS lpgm, // pointer to structure for metrics DWORD cbBuffer, // size of buffer for data LPVOID lpvBuffer, // pointer to buffer for data CONST MAT2 *lpmat2 // pointer to transformation matrix structure ) { // 바로 앞 전 EBP를 구해서 INT_PTR _CUR_EBP = NULL; _asm { mov eax, [ebp]; mov _CUR_EBP, eax; } char chArray[5] = {0,}; wchar_t wchArray[10] = {0,}; size_t i,j; j = 0; for(i=sizeof(UINT); i>0; i--) { char one_ch = *( ((char*)&uChar) + i - 1 ); if(one_ch) { chArray[j] = one_ch; j++; } } MyMultiByteToWideChar(932, 0, chArray, sizeof(UINT), wchArray, 10 ); wchar_t wch = wchArray[0]; // 검사중인 텍스트 포인터들 모두 순회 BOOL bHitOnce = TestCharacter(wch); // 적중된 포인터가 없다면 검색 if( FALSE == bHitOnce ) { int iRes = SearchStringA(_CUR_EBP, chArray[0], chArray[1]); //iRes += SearchStringW(_CUR_EBP, wch); } // 최고의 번역 문자를 얻어옴 wchar_t wchNewChar[1024]; DWORD dwRetVal = 0; if( GetBestTranslatedCharacter(wchNewChar) ) { uChar = wchNewChar[0]; if(uChar<=0x20) { uFormat = GGO_NATIVE; } dwRetVal = GetGlyphOutlineW(hdc, uChar, uFormat, lpgm, cbBuffer, lpvBuffer, lpmat2); if(dwRetVal == GDI_ERROR) { TRACE("[ aral1 ] GetGlyphOutlineA(0x%x) failed (ErrCode:%d) \n", uChar, GetLastError()); } } else // 원래함수 호출 { dwRetVal = GetGlyphOutlineA(hdc, uChar, uFormat, lpgm, cbBuffer, lpvBuffer, lpmat2); } return dwRetVal; } ////////////////////////////////////////////////////////////////////////// // // GetGlyphOutlineW // ////////////////////////////////////////////////////////////////////////// DWORD CNonCachedTextArgMgr::NewGetGlyphOutlineW( HDC hdc, // handle to device context UINT uChar, // character to query UINT uFormat, // format of data to return LPGLYPHMETRICS lpgm, // pointer to structure for metrics DWORD cbBuffer, // size of buffer for data LPVOID lpvBuffer, // pointer to buffer for data CONST MAT2 *lpmat2 // pointer to transformation matrix structure ) { /* // 바로 앞 전 EBP를 구해서 INT_PTR _CUR_EBP = NULL; _asm { mov eax, [ebp]; mov _CUR_EBP, eax; } wchar_t wch = (wchar_t)uChar; // 검사중인 텍스트 포인터들 모두 순회 BOOL bHitOnce = TestCharacter(wch); // 적중된 포인터가 없다면 검색 if( FALSE == bHitOnce ) { int iRes = SearchStringW(_CUR_EBP, wch); } // 최고의 번역 문자를 얻어옴 wchar_t wchNewChar[1024]; if( GetBestTranslatedCharacter(wchNewChar) ) { uChar = wchNewChar[0]; } wchar_t dbg[MAX_PATH]; swprintf(dbg, L"[ aral1 ] MyGetGlyphOutlineW : '%c'->'%s' \n", wch, wchNewChar); OutputDebugStringW(dbg); // 원래함수 호출 DWORD dwRetVal = 0; if( m_sTextFunc.pfnGetGlyphOutlineW ) { dwRetVal = m_sTextFunc.pfnGetGlyphOutlineW(hdc, uChar, uFormat, lpgm, cbBuffer, lpvBuffer, lpmat2); } return dwRetVal; */ return GetGlyphOutlineW(hdc, uChar, uFormat, lpgm, cbBuffer, lpvBuffer, lpmat2); } BOOL CNonCachedTextArgMgr::NewTextOutA( HDC hdc, // handle to DC int nXStart, // x-coordinate of starting position int nYStart, // y-coordinate of starting position LPCSTR lpString, // character string int cbString // number of characters ) { BOOL bRetVal = 0; // 바로 앞 전 EBP를 구해서 INT_PTR _CUR_EBP = NULL; _asm { mov eax, [ebp]; mov _CUR_EBP, eax; } // 최고의 번역 문자를 얻어옴 wchar_t wszNewString[1024]; int nLen=cbString; if( GetTranslatedStringA(_CUR_EBP, lpString, nLen, wszNewString, 1024, nLen) ) { bRetVal = TextOutW(hdc, nXStart, nYStart, wszNewString, nLen); } else // 원래함수 호출 { bRetVal = TextOutA(hdc, nXStart, nYStart, lpString, cbString); } return bRetVal; } BOOL CNonCachedTextArgMgr::NewTextOutW( HDC hdc, // handle to DC int nXStart, // x-coordinate of starting position int nYStart, // y-coordinate of starting position LPCWSTR lpString, // character string int cbString // number of characters ) { /* BOOL bRetVal = 0; // 바로 앞 전 EBP를 구해서 INT_PTR _CUR_EBP = NULL; _asm { mov eax, [ebp]; mov _CUR_EBP, eax; } int nLen = cbString; if (IsJapaneseW(lpString, nLen)) { // 최고의 번역 문자를 얻어옴 wchar_t wszNewString[1024]; if( GetTranslatedStringW(_CUR_EBP, lpString, nLen, wszNewString, 1024, nLen) ) { bRetVal = m_sTextFunc.pfnTextOutW(hdc, nXStart, nYStart, wszNewString, nLen); return bRetVal; } } // 원래함수 호출 if( m_sTextFunc.pfnTextOutW ) { bRetVal = m_sTextFunc.pfnTextOutW(hdc, nXStart, nYStart, lpString, cbString); } return bRetVal; */ return TextOutW(hdc, nXStart, nYStart, lpString, cbString); } BOOL CNonCachedTextArgMgr::NewExtTextOutA( HDC hdc, // handle to DC int X, // x-coordinate of reference point int Y, // y-coordinate of reference point UINT fuOptions, // text-output options CONST RECT* lprc, // optional dimensions LPCSTR lpString, // string UINT cbCount, // number of characters in string CONST INT* lpDx // array of spacing values ) { BOOL bRetVal = 0; // 바로 앞 전 EBP를 구해서 INT_PTR _CUR_EBP = NULL; _asm { mov eax, [ebp]; mov _CUR_EBP, eax; } // 최고의 번역 문자를 얻어옴 wchar_t wszNewString[1024]; int nLen = (int)cbCount; if( GetTranslatedStringA(_CUR_EBP, lpString, nLen, wszNewString, 1024, nLen) ) { bRetVal = ExtTextOutW(hdc, X, Y, fuOptions, lprc, wszNewString, nLen, lpDx); } else // 원래함수 호출 { bRetVal = ExtTextOutA(hdc, X, Y, fuOptions, lprc, lpString, cbCount, lpDx); } return bRetVal; } BOOL CNonCachedTextArgMgr::NewExtTextOutW( HDC hdc, // handle to DC int X, // x-coordinate of reference point int Y, // y-coordinate of reference point UINT fuOptions, // text-output options CONST RECT* lprc, // optional dimensions LPCWSTR lpString, // string UINT cbCount, // number of characters in string CONST INT* lpDx // array of spacing values ) { /* BOOL bRetVal = 0; // 바로 앞 전 EBP를 구해서 INT_PTR _CUR_EBP = NULL; _asm { mov eax, [ebp]; mov _CUR_EBP, eax; } int nLen = (int)cbCount; if (IsJapaneseW(lpString, nLen)) { // 최고의 번역 문자를 얻어옴 wchar_t wszNewString[1024]; if( GetTranslatedStringW(_CUR_EBP, lpString, nLen, wszNewString, 1024, nLen) ) { bRetVal = m_sTextFunc.pfnExtTextOutW(hdc, X, Y, fuOptions, lprc, wszNewString, nLen, lpDx); return bRetVal; } } // 원래함수 호출 if( m_sTextFunc.pfnExtTextOutW ) { bRetVal = m_sTextFunc.pfnExtTextOutW(hdc, X, Y, fuOptions, lprc, lpString, cbCount, lpDx); } return bRetVal; */ return ExtTextOutW(hdc, X, Y, fuOptions, lprc, lpString, cbCount, lpDx); } int CNonCachedTextArgMgr::NewDrawTextA( HDC hDC, // handle to DC LPCSTR lpString, // text to draw int nCount, // text length LPRECT lpRect, // formatting dimensions UINT uFormat // text-drawing options ) { int nRetVal = 0; // 바로 앞 전 EBP를 구해서 INT_PTR _CUR_EBP = NULL; _asm { mov eax, [ebp]; mov _CUR_EBP, eax; } // 최고의 번역 문자를 얻어옴 wchar_t wszNewString[1024]; int nLen=nCount; if( GetTranslatedStringA(_CUR_EBP, lpString, nLen, wszNewString, 1024, nLen) ) { nRetVal = DrawTextW(hDC, wszNewString, nLen, lpRect, uFormat); return nRetVal; } else // 원래함수 호출 { nRetVal = DrawTextA(hDC, lpString, nCount, lpRect, uFormat); } return nRetVal; } int CNonCachedTextArgMgr::NewDrawTextW( HDC hDC, // handle to DC LPCWSTR lpString, // text to draw int nCount, // text length LPRECT lpRect, // formatting dimensions UINT uFormat // text-drawing options ) { /* int nRetVal = 0; CheckFont(hDC); // 바로 앞 전 EBP를 구해서 INT_PTR _CUR_EBP = NULL; _asm { mov eax, [ebp]; mov _CUR_EBP, eax; } int nLen=nCount; if (IsJapaneseW(lpString, nCount)) { // 최고의 번역 문자를 얻어옴 wchar_t wszNewString[1024]; if( GetTranslatedStringW(_CUR_EBP, lpString, nLen, wszNewString, 1024, nLen) ) { nRetVal = m_sTextFunc.pfnDrawTextW(hDC, wszNewString, nLen, lpRect, uFormat); return nRetVal; } } // 원래함수 호출 if( m_sTextFunc.pfnDrawTextW ) { nRetVal = m_sTextFunc.pfnDrawTextW(hDC, lpString, nLen, lpRect, uFormat); } return nRetVal; */ return DrawTextW(hDC, lpString, nCount, lpRect, uFormat); } int CNonCachedTextArgMgr::NewDrawTextExA( HDC hdc, // handle to DC LPSTR lpchText, // text to draw int cchText, // length of text to draw LPRECT lprc, // rectangle coordinates UINT dwDTFormat, // formatting options LPDRAWTEXTPARAMS lpDTParams // more formatting options ) { int nRetVal = 0; // 바로 앞 전 EBP를 구해서 INT_PTR _CUR_EBP = NULL; _asm { mov eax, [ebp]; mov _CUR_EBP, eax; } // 최고의 번역 문자를 얻어옴 wchar_t wszNewString[1024]; int nLen = cchText; if( GetTranslatedStringA(_CUR_EBP, lpchText, nLen, wszNewString, 1024, nLen) ) { nRetVal = DrawTextExW(hdc, wszNewString, nLen, lprc, dwDTFormat, lpDTParams); } else // 원래함수 호출 { nRetVal = DrawTextExA(hdc, lpchText, cchText, lprc, dwDTFormat, lpDTParams); } return nRetVal; } int CNonCachedTextArgMgr::NewDrawTextExW( HDC hdc, // handle to DC LPWSTR lpchText, // text to draw int cchText, // length of text to draw LPRECT lprc, // rectangle coordinates UINT dwDTFormat, // formatting options LPDRAWTEXTPARAMS lpDTParams // more formatting options ) { /* int nRetVal = 0; // 바로 앞 전 EBP를 구해서 INT_PTR _CUR_EBP = NULL; _asm { mov eax, [ebp]; mov _CUR_EBP, eax; } int nLen=cchText; if (IsJapaneseW(lpchText, nLen)) { // 최고의 번역 문자를 얻어옴 wchar_t wszNewString[1024]; if( GetTranslatedStringW(_CUR_EBP, lpchText, nLen, wszNewString, 1024, nLen) ) { nRetVal = m_sTextFunc.pfnDrawTextExW(hdc, wszNewString, nLen, lprc, dwDTFormat, lpDTParams); return nRetVal; } } // 원래함수 호출 if( m_sTextFunc.pfnDrawTextExW ) { nRetVal = m_sTextFunc.pfnDrawTextExW(hdc, lpchText, cchText, lprc, dwDTFormat, lpDTParams); } return nRetVal; */ return DrawTextExW(hdc, lpchText, cchText, lprc, dwDTFormat, lpDTParams); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
[ "arallab3@883913d8-bf2b-11de-8cd0-f941f5a20a08" ]
[ [ [ 1, 862 ] ] ]
81816ed7d147da1a72e010611a0b4a4d59fc1601
d249c8f9920b1267752342f77d6f12592cb32636
/moteurGraphique/src/Moteur2D/Objet2D/Objet2D.cpp
9617a8c4a94773519e1673c96ba9203b1e4325e2
[]
no_license
jgraulle/stage-animation-physique
4c9fb0f96b9f4626420046171ff60f23fe035d5d
f1b0c69c3ab48f256d5ac51b4ffdbd48b1c001ae
refs/heads/master
2021-12-23T13:46:07.677761
2011-03-08T22:47:53
2011-03-08T22:47:53
33,616,188
0
0
null
2021-10-05T10:41:29
2015-04-08T15:41:32
C++
ISO-8859-1
C++
false
false
2,932
cpp
/* * Objet2D.cpp * * Created on: 6 févr. 2009 * Author: jeremie GRAULLE */ #include "Objet2D.h" #include "../../Ressource/RessourceManager.h" #include <GL/gl.h> Objet2D::Objet2D(const Texture * texture, const Vecteur2 & position, const Vecteur2 & taille, f32 angle) : texture(texture), position(position), taille(taille), angle(angle), estDansMonde(true), debutCoordTexture(0.0f, 0.0f), finCoordTexture(1.0f, 1.0f) { if (taille==Vecteur2() && texture!=NULL) this->taille = texture->getTaille(); } Objet2D::Objet2D(const string & texture, const Vecteur2 & position, const Vecteur2 & taille, f32 angle) : texture(NULL), position(position), taille(taille), angle(angle), estDansMonde(true), debutCoordTexture(0.0f, 0.0f), finCoordTexture(1.0f, 1.0f) { setTexture(TexturesManager::getInstance()->get(texture)); if (taille==Vecteur2() && this->texture!=NULL) this->taille = this->texture->getTaille(); } Objet2D::~Objet2D() {} // deplacer l'objet void Objet2D::setPosition(const Vecteur2 & position) { this->position = position; } void Objet2D::setPosition(f32 x, f32 y) { position.setX(x); position.setY(y); } void Objet2D::translate(const Vecteur2 & v) { position += v; } void Objet2D::translate(f32 x, f32 y) { position += Vecteur2(x, y); } // tourner un objet void Objet2D::setRotation(f32 angle) { this->angle = angle; } void Objet2D::rotate(f32 angle) { this->angle += angle; } // definir si l'objet est afficher ou pas void Objet2D::setIsDisplay(bool b) { estDansMonde = b; } // afficher l'objet void Objet2D::display() { f32 x = position.getX(); f32 y = position.getY(); f32 width = taille.getX(); f32 height = taille.getY(); f32 xDebutCoordTexture = debutCoordTexture.getX(); f32 yDebutCoordTexture = debutCoordTexture.getY(); f32 xFinCoordTexture = finCoordTexture.getX(); f32 yFinCoordTexture = finCoordTexture.getY(); if (texture!=NULL) { // appliquer la texture texture->apply(); // TODO rotation objet2D // dessiner un rectangle glBegin(GL_QUADS); glNormal3f(0.0f, 0.0f, 1.0f); glTexCoord2f(xDebutCoordTexture, yDebutCoordTexture); glVertex3f(x, y, 0.0f); glNormal3f(0.0f, 0.0f, 1.0f); glTexCoord2f(xDebutCoordTexture, yFinCoordTexture); glVertex3f(x, y+height-1, 0.0f); glNormal3f(0.0f, 0.0f, 1.0f); glTexCoord2f(xFinCoordTexture, yFinCoordTexture); glVertex3f(x+width-1, y+height-1, 0.0f); glNormal3f(0.0f, 0.0f, 1.0f); glTexCoord2f(xFinCoordTexture, yDebutCoordTexture); glVertex3f(x+width-1, y, 0.0f); glEnd(); } } // changer la texture void Objet2D::setTexture(const Texture * texture) { this->texture = texture; } // changer la taille de l'objet void Objet2D::setTaille(const Vecteur2 & taille) { this->taille = taille; } void Objet2D::setTaille(f32 x, f32 y) { this->taille = Vecteur2(x, y); }
[ "jgraulle@74bb1adf-7843-2a67-e58d-b22fe9da3ebb" ]
[ [ [ 1, 112 ] ] ]
06f266a7f715e6d8dbd271e968a075984f96dd9d
037faae47a5b22d3e283555e6b5ac2a0197faf18
/plugins/gs/gsdx9/GSCaptureDlg.h
758493f904868ab3fcdea75c3b2306705a617388
[]
no_license
isabella232/pcsx2-sourceforge
6e5aac8d0b476601bfc8fa83ded66c1564b8c588
dbb2c3a010081b105a8cba0c588f1e8f4e4505c6
refs/heads/master
2023-03-18T22:23:15.102593
2008-11-17T20:10:17
2008-11-17T20:10:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,905
h
/* * Copyright (C) 2003-2005 Gabest * http://www.gabest.org * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, 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 #include "resource.h" #include "afxwin.h" // GSCaptureDlg dialog class GSCaptureDlg : public CDialog { DECLARE_DYNAMIC(GSCaptureDlg) private: struct Codec { CComPtr<IMoniker> pMoniker; CComPtr<IBaseFilter> pBF; CString FriendlyName; CComBSTR DisplayName; }; CList<Codec> m_codecs; int GetSelCodec(Codec& c); public: GSCaptureDlg(CWnd* pParent = NULL); // standard constructor virtual ~GSCaptureDlg(); CComPtr<IBaseFilter> m_pVidEnc; // Dialog Data enum { IDD = IDD_CAPTURE }; CString m_filename; CComboBox m_codeclist; protected: virtual LRESULT DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam); virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support virtual BOOL OnInitDialog(); DECLARE_MESSAGE_MAP() public: afx_msg void OnKickIdle(); afx_msg void OnBnClickedButton1(); afx_msg void OnBnClickedButton2(); afx_msg void OnUpdateButton2(CCmdUI* pCmdUI); afx_msg void OnBnClickedOk(); afx_msg void OnUpdateOK(CCmdUI* pCmdUI); };
[ "zerofrog@23c756db-88ba-2448-99d7-e6e4c676ec84" ]
[ [ [ 1, 70 ] ] ]
fe0a7f29f11533fbe7f288b37a83413e2249c52d
bd37f7b494990542d0d9d772368239a2d44e3b2d
/server/src/StartJugador.cpp
016d3eaf183ff302536e7fc5d9f6c9513abe2347
[]
no_license
nicosuarez/pacmantaller
b559a61355517383d704f313b8c7648c8674cb4c
0e0491538ba1f99b4420340238b09ce9a43a3ee5
refs/heads/master
2020-12-11T02:11:48.900544
2007-12-19T21:49:27
2007-12-19T21:49:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,122
cpp
/////////////////////////////////////////////////////////// // StartJugador.cpp // Implementation of the Class StartJugador // Created on: 21-Nov-2007 23:40:18 /////////////////////////////////////////////////////////// #include "StartJugador.h" StartJugador* StartJugador::pStartJugador = NULL; StartJugador* StartJugador::getInstance() { if (pStartJugador == NULL) { pStartJugador = new StartJugador(); pStartJugador->run(); } return pStartJugador; } /*----------------------------------------------------------------------------*/ StartJugador::StartJugador(){ } /*----------------------------------------------------------------------------*/ /** * Hilo que se encarga agregar un jugador al juego, dando tiempo para que * muestre el mapa. */ void StartJugador::main(){ this->esperarRecibirStart(); while(!this->startPlayers.empty()) { Play* play=getStart(); play->join(); delete play; this->desacolar(); /* Espera al proximo jugador para agregarlo al juego */ this->esperarRecibirStart(); } } /*----------------------------------------------------------------------------*/ void StartJugador::esperarRecibirStart() { if(startPlayers.empty() && !Modelo::getInstance()->seFinalizoElJuego()) { //Espera a recibir operaciones. this->getRecibiStartEvent().esperar(); } } /*----------------------------------------------------------------------------*/ Play* StartJugador::desacolar() { Play* play=this->startPlayers.front(); this->startPlayers.pop(); return play; } /*----------------------------------------------------------------------------*/ Play* StartJugador::getStart() { return this->startPlayers.front(); } /*----------------------------------------------------------------------------*/ /** * Coloca la jugador en la cola en la espera de ingresar al juego. */ void StartJugador::agregarStart(Play* play){ this->startPlayers.push(play); /* Avisa al hilo que llego un nuevo jugador a insertar al juego */ this->getRecibiStartEvent().activar(); }
[ "scamjayi@5682bcf5-5c3f-0410-a8fd-ab24993f6fe8" ]
[ [ [ 1, 76 ] ] ]
0432cee812991230eb3a388bd55290abf346a705
4aadb120c23f44519fbd5254e56fc91c0eb3772c
/Source/EduNetGames/ModCtf/NetCtfGameLogic.cpp
98b3b47567bda3b3e3c2c38aee44f04def03ec99
[]
no_license
janfietz/edunetgames
d06cfb021d8f24cdcf3848a59cab694fbfd9c0ba
04d787b0afca7c99b0f4c0692002b4abb8eea410
refs/heads/master
2016-09-10T19:24:04.051842
2011-04-17T11:00:09
2011-04-17T11:00:09
33,568,741
0
0
null
null
null
null
UTF-8
C++
false
false
4,363
cpp
//----------------------------------------------------------------------------- // Copyright (c) 2009, Jan Fietz, Cyrus Preuss // 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 EduNetGames nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------------------------- #include "NetCtfGameLogic.h" #include "NetCtfPlugin.h" #include "NetCtfVehicles.h" osVector3 NetCtfGameLogic::ms_kHomeBaseCenter(0, 0, 0); float NetCtfGameLogic::ms_fHomeBaseRadius = 1.5f; //----------------------------------------------------------------------------- NetCtfGameLogic::NetCtfGameLogic( osAbstractVehicle* pkVehicle ): BaseClass(pkVehicle), m_pkPlugin(NULL),m_bGameOver(false) { } //----------------------------------------------------------------------------- NetCtfGameLogic::~NetCtfGameLogic() { } #if ET_ACTIVE_CTF_HACK #include "EduNetApplication/EduNetGames.h" const float resetDelay = 4; const float resetTime = lastRunningTime + resetDelay; if( currentTime > resetTime ) { // xxx a royal hack(should do this internal to CTF): EduNet::GameDemo::queueDelayedResetPluginXXX(); } #endif //----------------------------------------------------------------------------- void NetCtfGameLogic::update( const float currentTime, const float elapsedTime ) { if( this->isVehicleUpdate() ) { osAbstractVehicle& kVehicle = this->vehicle(); kVehicle.update( currentTime, elapsedTime ); NetCtfSeekerVehicle* pkSeeker = dynamic_cast<NetCtfSeekerVehicle*>( &kVehicle ); if( NULL != pkSeeker ) { if( pkSeeker->state != NetCtfSeekerVehicle::running ) { this->m_bGameOver = true; } } else { } } else { // game logic update // query seeker vehicle NetCtfSeekerVehicle* pkSeeker = NULL; NetCtfEnemyVehicle* pkEnemy = NULL; osAVGroup kEnemies; const osAVGroup& kVehicles = this->m_pkPlugin->allVehicles(); { osAVCIterator kIter = kVehicles.begin(); osAVCIterator kEnd = kVehicles.end(); while( kIter != kEnd ) { osAbstractVehicle* pkVehicle = (*kIter); // right now only one seeker if( NULL == pkSeeker ) { pkSeeker = dynamic_cast<NetCtfSeekerVehicle*>( pkVehicle ); } pkEnemy = dynamic_cast<NetCtfEnemyVehicle*>( pkVehicle ); if( NULL != pkEnemy ) { kEnemies.push_back( pkEnemy ); } ++kIter; } } // pass seeker to enemies and enemies to seeker { osAVCIterator kIter = kEnemies.begin(); osAVCIterator kEnd = kEnemies.end(); while( kIter != kEnd ) { osAbstractVehicle* pkVehicle = (*kIter); pkEnemy = dynamic_cast<NetCtfEnemyVehicle*>( pkVehicle ); if( NULL != pkEnemy ) { pkEnemy->setSeeker( pkSeeker ); } ++kIter; } if( pkSeeker != NULL ) { pkSeeker->accessEnemies().swap( kEnemies ); } } } }
[ "janfietz@localhost" ]
[ [ [ 1, 133 ] ] ]
b67410259ef8c6e235c40957c36c8c22c46856c6
7b379862f58f587d9327db829ae4c6493b745bb1
/Source/Commands.cpp
0e55e47304e0b9c85eb4cae2dc7d91874b777e0a
[]
no_license
owenvallis/Nomestate
75e844e8ab68933d481640c12019f0d734c62065
7fe7c06c2893421a3c77b5180e5f27ab61dd0ffd
refs/heads/master
2021-01-19T07:35:14.301832
2011-12-28T07:42:50
2011-12-28T07:42:50
2,950,072
2
0
null
null
null
null
UTF-8
C++
false
false
651
cpp
/* ============================================================================== Commands.cpp Created: 10 Oct 2011 10:17:05pm Author: Dimitri Diakopoulos ============================================================================== */ #include "Commands.h" const String Commands::SEND_MIDI = "SEND_MIDI"; const String Commands::SIGNAL_MOD = "SIGNAL_MOD"; const String Commands::SEND_OSC = "SEND_OSC"; Commands::Commands() { } Commands::~Commands() { } void Commands::registerCommand(String name, Command *cmd) { COMMAND_LIST.insert( std::pair<String, Command*>(name, cmd) ); }
[ "ow3nskip" ]
[ [ [ 1, 26 ] ] ]
7f6cfc480454ff1035624133a4b37755f3550fc0
8b506bf34b36af04fa970f2749e0c8033f1a9d7a
/Code/Games/FencingGame/feMain.h
31d75507955219c6f08b46350a2f858ac51168aa
[]
no_license
gunstar/Prototype
a5155e25d7d54a1991425e7be85bfc7da42c634f
a4448b5f6d18048ecaedf26c71e2b107e021ea6e
refs/heads/master
2021-01-10T21:42:24.221750
2011-11-06T10:16:26
2011-11-06T10:16:26
2,708,481
0
0
null
null
null
null
UTF-8
C++
false
false
554
h
/* feMain */ #ifndef _feMain #define _feMain #include "gaCamera.h" class feMain: eiInput, eiTicker { public: feMain (eiEngine* engine) { Engine = engine; } void run (); private: void setCameraActive (int index); private: void eiInput_key (int key, bool down); private: void eiTicker_tick (float secs); private: gaCamera* CameraActive; gaCamera* Camera[2]; eiMesh* Mesh; eiEntity* Entity[100]; enMatrix EntityMatrix[100]; int EntityMax; private: eiEngine* Engine; }; #endif
[ [ [ 1, 40 ] ] ]
a0201eaf7c75d20cf524b1d6382afc0cca01b730
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/renaissance/rnsbasicactions/src/ngpclimbladder/ngpclimbladder.cc
fe456abcc3298fb1f787a6a93a4f4dadacebe740
[]
no_license
ugozapad/TheZombieEngine
832492930df28c28cd349673f79f3609b1fe7190
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
refs/heads/master
2020-04-30T11:35:36.258363
2011-02-24T14:18:43
2011-02-24T14:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,575
cc
#include "precompiled/pchrnsbasicactions.h" //------------------------------------------------------------------------------ // ngpclimbladder.cc // (C) 2005 Conjurer Services, S.A. //------------------------------------------------------------------------------ #include "ngpclimbladder/ngpclimbladder.h" #include "entity/nentityobject.h" nNebulaScriptClass(nGPClimbLadder, "ngpbasicaction"); //------------------------------------------------------------------------------ /** Nebula class scripting initialization */ NSCRIPT_INITCMDS_BEGIN (nGPClimbLadder) NSCRIPT_ADDCMD('INIT', bool, Init, 2, (nEntityObject*, nEntityObject*), 0, ()); NSCRIPT_INITCMDS_END() //------------------------------------------------------------------------------ /** Constructor */ nGPClimbLadder::nGPClimbLadder() : nGPBasicAction() { // empty } //------------------------------------------------------------------------------ /** Destructor */ nGPClimbLadder::~nGPClimbLadder() { this->ladder = 0; this->End(); } //------------------------------------------------------------------------------ /** Init */ bool nGPClimbLadder::Init (nEntityObject* entity, nEntityObject* ladder) { // @TODO: this->ladder = ladder; this->entity = entity; this->init = true; return true; } //------------------------------------------------------------------------------ /** IsDone */ bool nGPClimbLadder::IsDone() const { // @TODO: return nGPBasicAction::IsDone(); }
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 64 ] ] ]
7b89c873f58703a11141e00b2f78b76d9eb938c6
a5de878687ee2e72db865481785dafbeda373e2a
/trunck/OpenPR-0.0.2/sci_gateway/qdmatch/Keypoint.h
c722ea970250baca18bc91c2f1008b115dd4e3f1
[ "BSD-3-Clause" ]
permissive
Augertron/OpenPR
8f43102fd5811d26301ef75e0a1f2b6ba9cbdb73
e2b1ce89f020c1b25df8ac5d93f6a0014ed4f714
refs/heads/master
2020-05-15T09:31:08.385577
2011-03-21T02:51:40
2011-03-21T02:51:40
182,178,910
0
0
null
null
null
null
UTF-8
C++
false
false
3,350
h
////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2009 OpenPR // 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 OpenPR 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 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 HOLDER AND 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. //////////////////////////////////////////////////////////////////////////// // Keypoint.h -- Declaration of the class Keypoint. #ifndef KEYPOINT_H #define KEYPOINT_H /* #include <stdlib.h> #include <fstream.h> #include <iostream.h> #include <vector> using namespace std; */ #include <fstream> #include <iomanip> #include "SiftUtil.h" /*---------------------------------Keypoint----------------------------------*/ class Keypoint { public: Keypoint(void); Keypoint(double x, double y, double baseScale, double level); Keypoint(const Keypoint &other); ~Keypoint(void); Keypoint & operator =(const Keypoint &other); friend bool operator ==(const Keypoint &key1, const Keypoint &key2); int GetDescDim(void) const; int GetDesc(int i) const; void CreateDesc(int dim, const uchar *desc); void DeleteDesc(void); //friend ostream & operator <<(ostream &os, const Keypoint &key); //friend istream & operator >>(istream &is, Keypoint &key); public: double m_x; // x position of the keypoint. double m_y; // y position of the keypoint. double m_baseScale; // base scale of the keypoint. double m_level; // scale level of the keypoint. double m_scale; // scale value of the keypoint. double m_orien; // orientation of the keypoint. private: int m_descDim; // dimension of the keypoint descriptor. uchar *m_desc; // local image descriptor of the keypoint. }; int DistSquared(const Keypoint &key1, const Keypoint &key2); ostream & operator <<(ostream &os, const Keypoint &key); istream & operator >>(istream &is, Keypoint &key); bool WriteKeyFile(const string& fileName, const vector<Keypoint> &keys); bool ReadKeyFile(vector<Keypoint> &keys, const char *fileName); #endif
[ "openpr@9318c073-892e-421e-b8e5-d5f98a2b248e" ]
[ [ [ 1, 94 ] ] ]
1fad1a99cb985ccd5b1c1379fcdd50d97abeff17
36d0ddb69764f39c440089ecebd10d7df14f75f3
/プログラム/Game/Scene/GameSceneState.h
86d2c357329b8ec6feb12723e73060fcd094bb5b
[]
no_license
weimingtom/tanuki-mo-issyo
3f57518b4e59f684db642bf064a30fc5cc4715b3
ab57362f3228354179927f58b14fa76b3d334472
refs/heads/master
2021-01-10T01:36:32.162752
2009-04-19T10:37:37
2009-04-19T10:37:37
48,733,344
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,534
h
/*******************************************************************************/ /** * @file GameSceneState.h. * * @brief ゲームシーン状態クラス定義. * * @date 2008/11/27. * * @version 1.00. * * @author Kenji Iwata. */ /*******************************************************************************/ #ifndef _GAME_SCENE_STATE_H_ #define _GAME_SCENE_STATE_H_ /*===== インクルード ==========================================================*/ #include <vector> class Player; #include "Manager/Object/ObjectManager.h" /** * @brief GameSceneState. */ class GameSceneState { public: /*=========================================================================*/ /** * @brief コンストラクタ. * */ GameSceneState(ObjectManager& objectManager); /*=========================================================================*/ /** * @brief デストラクタ. * */ ~GameSceneState(); /*=========================================================================*/ /** * @brief プレーヤをリストに追加. * * @param[in] player 追加するプレーヤ. * @return 追加したプレーヤの番号. */ int AddPlayer(Player* player); /*=========================================================================*/ /** * @brief プレーヤをリストから削除. * * @param[in] player 削除するプレーヤ. */ void DelPlayer(Player* player); /*=========================================================================*/ /** * @brief プレーヤリストのクリア. * */ void ClearPlayer(); /*=========================================================================*/ /** * @brief プレーヤの取得. * * @param[in] num 取得するプレーヤの番号. * @return 取得したプレーヤ. */ Player* GetPlayer(int num); /*=========================================================================*/ /** * @brief 登録されたプレーヤの人数を取得. * * @return プレーヤ人数. */ int GetPlayerNum(); int GetGameState(); void SetGameState(int state); Player* GetTargetPlayer(Player* player); private: /** オブジェクトマネージャ */ ObjectManager& m_objectManager; /** プレーヤリスト */ std::vector<Player*> m_playerList; /** ゲームステート */ int m_gameState; }; #endif /*===== EOF ===================================================================*/
[ "rs.drip@aa49b5b2-a402-11dd-98aa-2b35b7097d33" ]
[ [ [ 1, 99 ] ] ]
9af3986573cb59307c182e26250c5d8b4e74f6d9
965bcb2cd3d377b03840ae3899bc1243d2b6203d
/engineTest/engineTest/gameHUD.h
1f84cb55babfd569c81c648aceb40e3ea90995d0
[]
no_license
VirtuosoChris/gameaiproject1
42cd6245a824e2a5c09384b1f756a31b4ec904e7
789a6a420559bf32e15fa56db64c7c063df668e7
refs/heads/master
2020-06-01T19:00:15.998072
2009-04-19T19:25:29
2009-04-19T19:25:29
32,121,286
0
0
null
null
null
null
UTF-8
C++
false
false
2,180
h
#ifndef GAME_HUD #define GAME_HUD #include "irrlicht.h" #include <string.h> using namespace irr; using namespace video; //Object that represents all Scene Nodes Assembled for in-game HUD and UI class gameHUD { private: video::IVideoDriver* driver; enum {PRE_PLAY,PLAY,PAUSE,BREAK,END_GAME}; int gameState; int x1Bar, y1Bar, x2Bar, y2Bar; int maxShotTimerBarValue; //size of the timer bar int roundTimer; //Current Round Time, updated by clock function double deltaShotTimerBar; //difference scalar double shotTimerBarValue; //current bar value double screenX, screenY; bool gunTimerReady; //current gun readiness bool showScore; //score display flag //Texture Storage for random GUI HUD elements //Assignments: // 0 : Gun Timer Bar // 1 : Crosshair video::ITexture* GUITextures[10]; //Texture Storage for character GUI HUD elements //Assignments: // 0-9 : Numbers zero through nine // 10 : Colon Character video::ITexture* CharTextures[11]; //Texture Storage for fixed position clock characters //Assignments: // 0 : Minutes (zero to nine) // 1 : Seconds (1x10^1) // 2 : Seconds (1x10^0) video::ITexture* ClockTextures[3]; //Texture Storage for score counters //Assignments: // 0 : Label // 1-5 : Player Identifiers // 6 : gun identifier video::ITexture* ScoreTextures[7]; gameHUD(); //constructor ~gameHUD(); //destructor :Opublic: static gameHUD* getInstance(); //returns an instance of the gameHUD void render(); //render the HUD, must be called AFTER the 3D draw, or it wont show void setShotTimerBarValue(int shotTimerValue); //change bar values void updateRoundTimer(irr::u32 numMins, irr::u32 numSecsOrder2, irr::u32 numSecsOrder1); //changes game timer value void setVideoDriver (video::IVideoDriver* videoDriver); //void setGameContext (ktcGame *game); void loadTextures(); //loads all relevant textures into private member variables void setGunReady(bool ready); //sets gun Readiness bool getGunReady(); //returns true if gun is ready to be fired, false otherwise inline void setGameState(int stateToSet) {gameState = stateToSet;} }; #endif
[ "cthomas.mail@be266342-eca9-11dd-a550-c997509ed985", "javidscool@be266342-eca9-11dd-a550-c997509ed985" ]
[ [ [ 1, 7 ], [ 9, 12 ], [ 17, 20 ], [ 22, 29 ] ], [ [ 8, 8 ], [ 13, 16 ], [ 21, 21 ] ] ]
b05fabdc6999449d1dc3c6a4146583e225abf944
31d36971c94cb81c58b9f0b2f991ee7fb1034a47
/Pekka Kana 2/PK2Sprite.cpp
436463f995c814fb2d2f81209bdeb96bf62680f4
[]
no_license
stt/pk2
e23a80f985fcb13ae57eb5cba8352be68291e3fe
8ca3fb99a21fdbf80ffda079051c5fb5c5b71341
refs/heads/master
2023-04-22T19:09:37.115934
2010-09-09T21:39:25
2010-09-09T21:39:25
897,109
11
4
null
null
null
null
ISO-8859-1
C++
false
false
56,444
cpp
#ifdef WIN32 #include <windows.h> #include <windowsx.h> #include <mmsystem.h> #include <io.h> #endif #include <stdlib.h> #include <stdio.h> #include <fstream> #include "PK2Sprite.h" #include "PisteDraw.h" #include "PisteSound.h" #define _MAX_PATH 128 using namespace std; /* -------- PK2Sprite Prototyyppi ------------------------------------------------------------------ */ PK2Sprite_Prototyyppi::PK2Sprite_Prototyyppi() { strcpy(versio,PK2SPRITE_VIIMEISIN_VERSIO); strcpy(tiedosto,""); strcpy(kuvatiedosto,""); strcpy(nimi, ""); strcpy(this->muutos_sprite,""); strcpy(this->bonus_sprite,""); strcpy(this->ammus1_sprite,""); strcpy(this->ammus2_sprite,""); for (int aani=0;aani<MAX_AANIA;aani++) { strcpy(aanitiedostot[aani], ""); aanet[aani] = -1; } aani_frq = 22050; ammus1 = -1; ammus2 = -1; animaatioita = 0; avain = false; bonus = -1; bonusten_lkm = 1; energia = 0; este = false; este_ylos = true; este_alas = true; este_oikealle = true; este_vasemmalle = true; frameja = 0; frame_rate = 0; hyokkays1_aika = 60; hyokkays2_aika = 60; indeksi = 0; kuva_x = 0; kuva_y = 0; kuva_frame_leveys = 0; kuva_frame_korkeus = 0; korkeus = 0; latausaika = 0; leveys = 0; max_hyppy = 0; max_nopeus = 3; muutos = -1; paino = 0; pallarx_kerroin = 0; pisteet = 0; random_frq = true; suojaus = VAHINKO_EI; tarisee = false; tiletarkistus = true; tuhoutuminen = TUHOUTUMINEN_ANIMAATIO; tyyppi = TYYPPI_EI_MIKAAN; vahinko = 0; vahinko_tyyppi = VAHINKO_ISKU; vari = VARI_NORMAALI; vihollinen = false; lapinakyvyys = false; hehkuu = false; tulitauko = 0; liitokyky = false; boss = false; bonus_aina = false; osaa_uida = false; for (int i=0;i<SPRITE_MAX_AI;i++) { AI[i] = AI_EI; } for (int i=0;i<SPRITE_MAX_FRAMEJA;i++) framet[i] = 0; for (int i=0;i<SPRITE_MAX_ANIMAATIOITA;i++) { for (int j=0;j<ANIMAATIO_MAX_SEKVENSSEJA;j++) animaatiot[i].sekvenssi[j] = 0; animaatiot[i].looppi = false; animaatiot[i].frameja = 0; } } PK2Sprite_Prototyyppi::~PK2Sprite_Prototyyppi() { for (int i=0;i<SPRITE_MAX_FRAMEJA;i++) { if (framet[i] > 0) PisteDraw_Buffer_Tuhoa(this->framet[i]); } } void PK2Sprite_Prototyyppi::Kopioi(const PK2Sprite_Prototyyppi &proto) { strcpy(versio,proto.versio); strcpy(tiedosto,proto.tiedosto); strcpy(kuvatiedosto,proto.kuvatiedosto); strcpy(nimi, proto.nimi); strcpy(this->muutos_sprite,proto.muutos_sprite); strcpy(this->bonus_sprite,proto.bonus_sprite); strcpy(this->ammus1_sprite,proto.ammus1_sprite); strcpy(this->ammus2_sprite,proto.ammus2_sprite); for (int aani=0;aani<MAX_AANIA;aani++) { strcpy(aanitiedostot[aani], proto.aanitiedostot[aani]); aanet[aani] = proto.aanet[aani]; } aani_frq = proto.aani_frq; ammus1 = proto.ammus1; ammus2 = proto.ammus2; animaatioita = proto.animaatioita; avain = proto.avain; bonus = proto.bonus; bonusten_lkm = proto.bonusten_lkm; energia = proto.energia; este = proto.este; este_ylos = proto.este_ylos; este_alas = proto.este_alas; este_oikealle = proto.este_oikealle; este_vasemmalle = proto.este_vasemmalle; frameja = proto.frameja; frame_rate = proto.frame_rate; hyokkays1_aika = proto.hyokkays1_aika; hyokkays2_aika = proto.hyokkays2_aika; indeksi = proto.indeksi; kuva_x = proto.kuva_x; kuva_y = proto.kuva_y; kuva_frame_leveys = proto.kuva_frame_leveys; kuva_frame_korkeus = proto.kuva_frame_korkeus; korkeus = proto.korkeus; latausaika = proto.latausaika; leveys = proto.leveys; max_hyppy = proto.max_hyppy; max_nopeus = proto.max_nopeus; muutos = proto.muutos; paino = proto.paino; pallarx_kerroin = proto.pallarx_kerroin; pisteet = proto.pisteet; random_frq = proto.random_frq; suojaus = proto.suojaus; tarisee = proto.tarisee; tiletarkistus = proto.tiletarkistus; tuhoutuminen = proto.tuhoutuminen; tyyppi = proto.tyyppi; vahinko = proto.vahinko; vahinko_tyyppi = proto.vahinko_tyyppi; vari = proto.vari; vihollinen = proto.vihollinen; lapinakyvyys = proto.lapinakyvyys; hehkuu = proto.hehkuu; tulitauko = proto.tulitauko; liitokyky = proto.liitokyky; boss = proto.boss; bonus_aina = proto.bonus_aina; osaa_uida = proto.osaa_uida; for (int i=0;i<SPRITE_MAX_AI;i++) { AI[i] = proto.AI[i]; } for (int i=0;i<SPRITE_MAX_FRAMEJA;i++) framet[i] = proto.framet[i]; for (int i=0;i<SPRITE_MAX_ANIMAATIOITA;i++) { for (int j=0;j<ANIMAATIO_MAX_SEKVENSSEJA;j++) animaatiot[i].sekvenssi[j] = proto.animaatiot[i].sekvenssi[j]; animaatiot[i].looppi = proto.animaatiot[i].looppi; animaatiot[i].frameja = proto.animaatiot[i].frameja; } } void PK2Sprite_Prototyyppi::Uusi() { strcpy(versio,PK2SPRITE_VIIMEISIN_VERSIO); strcpy(tiedosto,""); strcpy(kuvatiedosto,""); strcpy(nimi, ""); strcpy(muutos_sprite,""); strcpy(bonus_sprite,""); strcpy(ammus1_sprite,""); strcpy(ammus2_sprite,""); for (int aani=0;aani<MAX_AANIA;aani++) { strcpy(aanitiedostot[aani], ""); aanet[aani] = -1; } aani_frq = 22050; ammus1 = -1; ammus2 = -1; animaatioita = 0; avain = false; bonus = -1; bonusten_lkm = 1; energia = 0; este = false; este_ylos = true; este_alas = true; este_oikealle = true; este_vasemmalle = true; frameja = 0; frame_rate = 0; hyokkays1_aika = 60; hyokkays2_aika = 60; indeksi = 0; kuva_x = 0; kuva_y = 0; kuva_frame_leveys = 0; kuva_frame_korkeus = 0; korkeus = 0; latausaika = 0; leveys = 0; max_hyppy = 0; max_nopeus = 3; muutos = -1; paino = 0; pallarx_kerroin = 0; pisteet = 0; random_frq = true; suojaus = VAHINKO_EI; tarisee = false; tiletarkistus = true; tuhoutuminen = TUHOUTUMINEN_ANIMAATIO; tyyppi = TYYPPI_EI_MIKAAN; vahinko = 0; vahinko_tyyppi = VAHINKO_ISKU; vari = VARI_NORMAALI; vihollinen = false; lapinakyvyys = false; hehkuu = false; tulitauko = 0; liitokyky = false; boss = false; bonus_aina = false; osaa_uida = false; int i=0; for (i=0;i<SPRITE_MAX_AI;i++) { AI[i] = AI_EI; } for (i=0;i<SPRITE_MAX_FRAMEJA;i++) { if (framet[i] != 0) PisteDraw_Buffer_Tuhoa(this->framet[i]); if (this->framet_peilikuva[i] != 0) PisteDraw_Buffer_Tuhoa(this->framet_peilikuva[i]); } for (i=0;i<SPRITE_MAX_FRAMEJA;i++) { framet[i] = 0; framet_peilikuva[i] = 0; } for (i=0;i<SPRITE_MAX_ANIMAATIOITA;i++) { for (int j=0;j<ANIMAATIO_MAX_SEKVENSSEJA;j++) animaatiot[i].sekvenssi[j] = 0; animaatiot[i].looppi = false; animaatiot[i].frameja = 0; } } int PK2Sprite_Prototyyppi::Animaatio_Uusi(int anim_i, UCHAR *sekvenssi, bool looppi) { UCHAR frame_i = 0; if (anim_i < SPRITE_MAX_ANIMAATIOITA) { animaatiot[anim_i].frameja = 0; while (frame_i < ANIMAATIO_MAX_SEKVENSSEJA && sekvenssi[frame_i] != 0) { animaatiot[anim_i].sekvenssi[frame_i] = sekvenssi[frame_i]; animaatiot[anim_i].frameja++; frame_i++; } animaatiot[anim_i].looppi = looppi; } return 0; } PK2Sprite_Prototyyppi10 PK2Sprite_Prototyyppi::GetProto10() { PK2Sprite_Prototyyppi10 proto; strcpy(proto.kuvatiedosto,kuvatiedosto); strcpy(proto.nimi, nimi); strcpy(proto.muutos_sprite,muutos_sprite); strcpy(proto.bonus_sprite,bonus_sprite); strcpy(proto.ammus1_sprite,ammus1_sprite); strcpy(proto.ammus2_sprite,ammus2_sprite); for (int aani=0;aani<MAX_AANIA;aani++) { strcpy(proto.aanitiedostot[aani], aanitiedostot[aani]); proto.aanet[aani] = aanet[aani]; } proto.animaatioita = animaatioita; proto.avain = avain; proto.energia = energia; proto.este = este; proto.frameja = frameja; proto.frame_rate = frame_rate; proto.kuva_x = kuva_x; proto.kuva_y = kuva_y; proto.kuva_frame_leveys = kuva_frame_leveys; proto.kuva_frame_korkeus = kuva_frame_korkeus; proto.korkeus = korkeus; proto.latausaika = latausaika; proto.leveys = leveys; proto.max_hyppy = max_hyppy; proto.max_nopeus = (UCHAR)max_nopeus; proto.paino = paino; proto.pisteet = pisteet; proto.suojaus = suojaus; proto.tuhoutuminen = tuhoutuminen; proto.tyyppi = tyyppi; proto.vahinko = vahinko; proto.vari = vari; proto.vihollinen = vihollinen; for (int i=0;i<5;i++) { proto.AI[i] = AI[i]; } for (int i=0;i<SPRITE_MAX_ANIMAATIOITA;i++) { for (int j=0;j<ANIMAATIO_MAX_SEKVENSSEJA;j++) proto.animaatiot[i].sekvenssi[j] = animaatiot[i].sekvenssi[j]; proto.animaatiot[i].looppi = animaatiot[i].looppi; proto.animaatiot[i].frameja = animaatiot[i].frameja; } return proto; } PK2Sprite_Prototyyppi11 PK2Sprite_Prototyyppi::GetProto11() { PK2Sprite_Prototyyppi11 proto; strcpy(proto.kuvatiedosto,kuvatiedosto); strcpy(proto.nimi, nimi); strcpy(proto.muutos_sprite,muutos_sprite); strcpy(proto.bonus_sprite,bonus_sprite); strcpy(proto.ammus1_sprite,ammus1_sprite); strcpy(proto.ammus2_sprite,ammus2_sprite); for (int aani=0;aani<MAX_AANIA;aani++) { strcpy(proto.aanitiedostot[aani], aanitiedostot[aani]); proto.aanet[aani] = aanet[aani]; } proto.animaatioita = animaatioita; proto.avain = avain; proto.bonusten_lkm = bonusten_lkm; proto.energia = energia; proto.este = este; proto.frameja = frameja; proto.frame_rate = frame_rate; proto.hyokkays1_aika = hyokkays1_aika; proto.hyokkays2_aika = hyokkays2_aika; proto.kuva_x = kuva_x; proto.kuva_y = kuva_y; proto.kuva_frame_leveys = kuva_frame_leveys; proto.kuva_frame_korkeus= kuva_frame_korkeus; proto.korkeus = korkeus; proto.latausaika = latausaika; proto.leveys = leveys; proto.max_hyppy = max_hyppy; proto.max_nopeus = (UCHAR)max_nopeus; proto.paino = paino; proto.pallarx_kerroin = pallarx_kerroin; proto.pisteet = pisteet; proto.suojaus = suojaus; proto.tarisee = tarisee; proto.tuhoutuminen = tuhoutuminen; proto.tyyppi = tyyppi; proto.vahinko = vahinko; proto.vahinko_tyyppi = vahinko_tyyppi; proto.vari = vari; proto.vihollinen = vihollinen; for (int i=0;i<5;i++) { proto.AI[i] = AI[i]; } for (int i=0;i<SPRITE_MAX_ANIMAATIOITA;i++) { for (int j=0;j<ANIMAATIO_MAX_SEKVENSSEJA;j++) proto.animaatiot[i].sekvenssi[j] = animaatiot[i].sekvenssi[j]; proto.animaatiot[i].looppi = animaatiot[i].looppi; proto.animaatiot[i].frameja = animaatiot[i].frameja; } return proto; } PK2Sprite_Prototyyppi12 PK2Sprite_Prototyyppi::GetProto12() { PK2Sprite_Prototyyppi12 proto; strcpy(proto.kuvatiedosto,kuvatiedosto); strcpy(proto.nimi, nimi); strcpy(proto.muutos_sprite,muutos_sprite); strcpy(proto.bonus_sprite,bonus_sprite); strcpy(proto.ammus1_sprite,ammus1_sprite); strcpy(proto.ammus2_sprite,ammus2_sprite); for (int aani=0;aani<MAX_AANIA;aani++) { strcpy(proto.aanitiedostot[aani], aanitiedostot[aani]); proto.aanet[aani] = aanet[aani]; } proto.aani_frq = aani_frq; proto.animaatioita = animaatioita; proto.avain = avain; proto.bonusten_lkm = bonusten_lkm; proto.energia = energia; proto.este = este; proto.este_ylos = este_ylos; proto.este_alas = este_alas; proto.este_oikealle = este_oikealle; proto.este_vasemmalle = este_vasemmalle; proto.frameja = frameja; proto.frame_rate = frame_rate; proto.hyokkays1_aika = hyokkays1_aika; proto.hyokkays2_aika = hyokkays2_aika; proto.kuva_x = kuva_x; proto.kuva_y = kuva_y; proto.kuva_frame_leveys = kuva_frame_leveys; proto.kuva_frame_korkeus= kuva_frame_korkeus; proto.korkeus = korkeus; proto.latausaika = latausaika; proto.leveys = leveys; proto.max_hyppy = max_hyppy; proto.max_nopeus = (UCHAR)max_nopeus; proto.paino = paino; proto.pallarx_kerroin = pallarx_kerroin; proto.pisteet = pisteet; proto.random_frq = random_frq; proto.suojaus = suojaus; proto.tarisee = tarisee; proto.tiletarkistus = tiletarkistus; proto.tuhoutuminen = tuhoutuminen; proto.tyyppi = tyyppi; proto.vahinko = vahinko; proto.vahinko_tyyppi = vahinko_tyyppi; proto.vari = vari; proto.vihollinen = vihollinen; for (int i=0;i<5;i++) { proto.AI[i] = AI[i]; } for (int i=0;i<SPRITE_MAX_ANIMAATIOITA;i++) { for (int j=0;j<ANIMAATIO_MAX_SEKVENSSEJA;j++) proto.animaatiot[i].sekvenssi[j] = animaatiot[i].sekvenssi[j]; proto.animaatiot[i].looppi = animaatiot[i].looppi; proto.animaatiot[i].frameja = animaatiot[i].frameja; } return proto; } PK2Sprite_Prototyyppi13 PK2Sprite_Prototyyppi::GetProto13() { PK2Sprite_Prototyyppi13 proto; strcpy(proto.kuvatiedosto,kuvatiedosto); strcpy(proto.nimi, nimi); strcpy(proto.muutos_sprite,muutos_sprite); strcpy(proto.bonus_sprite,bonus_sprite); strcpy(proto.ammus1_sprite,ammus1_sprite); strcpy(proto.ammus2_sprite,ammus2_sprite); for (int aani=0;aani<MAX_AANIA;aani++) { strcpy(proto.aanitiedostot[aani], aanitiedostot[aani]); proto.aanet[aani] = aanet[aani]; } proto.aani_frq = aani_frq; proto.animaatioita = animaatioita; proto.avain = avain; proto.bonusten_lkm = bonusten_lkm; proto.energia = energia; proto.este = este; proto.este_ylos = este_ylos; proto.este_alas = este_alas; proto.este_oikealle = este_oikealle; proto.este_vasemmalle = este_vasemmalle; proto.frameja = frameja; proto.frame_rate = frame_rate; proto.hyokkays1_aika = hyokkays1_aika; proto.hyokkays2_aika = hyokkays2_aika; proto.kuva_x = kuva_x; proto.kuva_y = kuva_y; proto.kuva_frame_leveys = kuva_frame_leveys; proto.kuva_frame_korkeus= kuva_frame_korkeus; proto.korkeus = korkeus; proto.latausaika = latausaika; proto.leveys = leveys; proto.max_hyppy = max_hyppy; proto.max_nopeus = max_nopeus; proto.paino = paino; proto.pallarx_kerroin = pallarx_kerroin; proto.pisteet = pisteet; proto.random_frq = random_frq; proto.suojaus = suojaus; proto.tarisee = tarisee; proto.tiletarkistus = tiletarkistus; proto.tuhoutuminen = tuhoutuminen; proto.tyyppi = tyyppi; proto.vahinko = vahinko; proto.vahinko_tyyppi = vahinko_tyyppi; proto.vari = vari; proto.vihollinen = vihollinen; proto.lapinakyvyys = lapinakyvyys; proto.hehkuu = hehkuu; proto.tulitauko = tulitauko; proto.liitokyky = liitokyky; proto.boss = boss; proto.bonus_aina = bonus_aina; proto.osaa_uida = osaa_uida; for (int i=0;i<10;i++) { proto.AI[i] = AI[i]; } for (int i=0;i<SPRITE_MAX_ANIMAATIOITA;i++) { for (int j=0;j<ANIMAATIO_MAX_SEKVENSSEJA;j++) proto.animaatiot[i].sekvenssi[j] = animaatiot[i].sekvenssi[j]; proto.animaatiot[i].looppi = animaatiot[i].looppi; proto.animaatiot[i].frameja = animaatiot[i].frameja; } return proto; } void PK2Sprite_Prototyyppi::SetProto10(PK2Sprite_Prototyyppi10 &proto) { strcpy(kuvatiedosto, proto.kuvatiedosto); strcpy(nimi, proto.nimi); strcpy(muutos_sprite, proto.muutos_sprite); strcpy(bonus_sprite, proto.bonus_sprite); strcpy(ammus1_sprite, proto.ammus1_sprite); strcpy(ammus2_sprite, proto.ammus2_sprite); for (int aani=0;aani<MAX_AANIA;aani++) { strcpy(aanitiedostot[aani], proto.aanitiedostot[aani]); aanet[aani] = proto.aanet[aani]; } animaatioita = proto.animaatioita; avain = proto.avain; energia = proto.energia; este = proto.este; frameja = proto.frameja; frame_rate = proto.frame_rate; kuva_x = proto.kuva_x; kuva_y = proto.kuva_y; kuva_frame_leveys = proto.kuva_frame_leveys; kuva_frame_korkeus = proto.kuva_frame_korkeus; korkeus = proto.korkeus; latausaika = proto.latausaika; leveys = proto.leveys; max_hyppy = proto.max_hyppy; max_nopeus = proto.max_nopeus; paino = proto.paino; pisteet = proto.pisteet; suojaus = proto.suojaus; tuhoutuminen = proto.tuhoutuminen; tyyppi = proto.tyyppi; vahinko = proto.vahinko; vari = proto.vari; vihollinen = proto.vihollinen; for (int i=0;i<5;i++) { AI[i] = proto.AI[i]; } for (int i=0;i<SPRITE_MAX_ANIMAATIOITA;i++) { for (int j=0;j<ANIMAATIO_MAX_SEKVENSSEJA;j++) animaatiot[i].sekvenssi[j] = proto.animaatiot[i].sekvenssi[j]; animaatiot[i].looppi = proto.animaatiot[i].looppi; animaatiot[i].frameja = proto.animaatiot[i].frameja; } } void PK2Sprite_Prototyyppi::SetProto11(PK2Sprite_Prototyyppi11 &proto) { strcpy(kuvatiedosto, proto.kuvatiedosto); strcpy(nimi, proto.nimi); strcpy(muutos_sprite, proto.muutos_sprite); strcpy(bonus_sprite, proto.bonus_sprite); strcpy(ammus1_sprite, proto.ammus1_sprite); strcpy(ammus2_sprite, proto.ammus2_sprite); for (int aani=0;aani<MAX_AANIA;aani++) { strcpy(aanitiedostot[aani], proto.aanitiedostot[aani]); aanet[aani] = proto.aanet[aani]; } animaatioita = proto.animaatioita; avain = proto.avain; bonusten_lkm = proto.bonusten_lkm; energia = proto.energia; este = proto.este; frameja = proto.frameja; frame_rate = proto.frame_rate; hyokkays1_aika = proto.hyokkays1_aika; hyokkays2_aika = proto.hyokkays2_aika; kuva_x = proto.kuva_x; kuva_y = proto.kuva_y; kuva_frame_leveys = proto.kuva_frame_leveys; kuva_frame_korkeus = proto.kuva_frame_korkeus; korkeus = proto.korkeus; latausaika = proto.latausaika; leveys = proto.leveys; max_hyppy = proto.max_hyppy; max_nopeus = proto.max_nopeus; paino = proto.paino; pallarx_kerroin = proto.pallarx_kerroin; pisteet = proto.pisteet; suojaus = proto.suojaus; tarisee = proto.tarisee; tuhoutuminen = proto.tuhoutuminen; tyyppi = proto.tyyppi; vahinko = proto.vahinko; vahinko_tyyppi = proto.vahinko_tyyppi; vari = proto.vari; vihollinen = proto.vihollinen; for (int i=0;i<5;i++) { AI[i] = proto.AI[i]; } for (int i=0;i<SPRITE_MAX_ANIMAATIOITA;i++) { for (int j=0;j<ANIMAATIO_MAX_SEKVENSSEJA;j++) animaatiot[i].sekvenssi[j] = proto.animaatiot[i].sekvenssi[j]; animaatiot[i].looppi = proto.animaatiot[i].looppi; animaatiot[i].frameja = proto.animaatiot[i].frameja; } } void PK2Sprite_Prototyyppi::SetProto12(PK2Sprite_Prototyyppi12 &proto) { strcpy(kuvatiedosto, proto.kuvatiedosto); strcpy(nimi, proto.nimi); strcpy(muutos_sprite, proto.muutos_sprite); strcpy(bonus_sprite, proto.bonus_sprite); strcpy(ammus1_sprite, proto.ammus1_sprite); strcpy(ammus2_sprite, proto.ammus2_sprite); for (int aani=0;aani<MAX_AANIA;aani++) { strcpy(aanitiedostot[aani], proto.aanitiedostot[aani]); aanet[aani] = proto.aanet[aani]; } aani_frq = proto.aani_frq; animaatioita = proto.animaatioita; avain = proto.avain; bonusten_lkm = proto.bonusten_lkm; energia = proto.energia; este = proto.este; este_ylos = proto.este_ylos; este_alas = proto.este_alas; este_oikealle = proto.este_oikealle; este_vasemmalle = proto.este_vasemmalle; frameja = proto.frameja; frame_rate = proto.frame_rate; hyokkays1_aika = proto.hyokkays1_aika; hyokkays2_aika = proto.hyokkays2_aika; kuva_x = proto.kuva_x; kuva_y = proto.kuva_y; kuva_frame_leveys = proto.kuva_frame_leveys; kuva_frame_korkeus = proto.kuva_frame_korkeus; korkeus = proto.korkeus; latausaika = proto.latausaika; leveys = proto.leveys; max_hyppy = proto.max_hyppy; max_nopeus = proto.max_nopeus; paino = proto.paino; pallarx_kerroin = proto.pallarx_kerroin; pisteet = proto.pisteet; random_frq = proto.random_frq; suojaus = proto.suojaus; tarisee = proto.tarisee; tiletarkistus = proto.tiletarkistus; tuhoutuminen = proto.tuhoutuminen; tyyppi = proto.tyyppi; vahinko = proto.vahinko; vahinko_tyyppi = proto.vahinko_tyyppi; vari = proto.vari; vihollinen = proto.vihollinen; for (int i=0;i<5;i++) { AI[i] = proto.AI[i]; } for (int i=0;i<SPRITE_MAX_ANIMAATIOITA;i++) { for (int j=0;j<ANIMAATIO_MAX_SEKVENSSEJA;j++) animaatiot[i].sekvenssi[j] = proto.animaatiot[i].sekvenssi[j]; animaatiot[i].looppi = proto.animaatiot[i].looppi; animaatiot[i].frameja = proto.animaatiot[i].frameja; } } void PK2Sprite_Prototyyppi::SetProto13(PK2Sprite_Prototyyppi13 &proto) { strcpy(kuvatiedosto, proto.kuvatiedosto); strcpy(nimi, proto.nimi); strcpy(muutos_sprite, proto.muutos_sprite); strcpy(bonus_sprite, proto.bonus_sprite); strcpy(ammus1_sprite, proto.ammus1_sprite); strcpy(ammus2_sprite, proto.ammus2_sprite); for (int aani=0;aani<MAX_AANIA;aani++) { strcpy(aanitiedostot[aani], proto.aanitiedostot[aani]); aanet[aani] = proto.aanet[aani]; } aani_frq = proto.aani_frq; animaatioita = proto.animaatioita; avain = proto.avain; bonusten_lkm = proto.bonusten_lkm; energia = proto.energia; este = proto.este; este_ylos = proto.este_ylos; este_alas = proto.este_alas; este_oikealle = proto.este_oikealle; este_vasemmalle = proto.este_vasemmalle; frameja = proto.frameja; frame_rate = proto.frame_rate; hyokkays1_aika = proto.hyokkays1_aika; hyokkays2_aika = proto.hyokkays2_aika; kuva_x = proto.kuva_x; kuva_y = proto.kuva_y; kuva_frame_leveys = proto.kuva_frame_leveys; kuva_frame_korkeus = proto.kuva_frame_korkeus; korkeus = proto.korkeus; latausaika = proto.latausaika; leveys = proto.leveys; max_hyppy = proto.max_hyppy; max_nopeus = proto.max_nopeus; paino = proto.paino; pallarx_kerroin = proto.pallarx_kerroin; pisteet = proto.pisteet; random_frq = proto.random_frq; suojaus = proto.suojaus; tarisee = proto.tarisee; tiletarkistus = proto.tiletarkistus; tuhoutuminen = proto.tuhoutuminen; tyyppi = proto.tyyppi; vahinko = proto.vahinko; vahinko_tyyppi = proto.vahinko_tyyppi; vari = proto.vari; vihollinen = proto.vihollinen; lapinakyvyys = proto.lapinakyvyys; hehkuu = proto.hehkuu; tulitauko = proto.tulitauko; liitokyky = proto.liitokyky; boss = proto.boss; bonus_aina = proto.bonus_aina; osaa_uida = proto.osaa_uida; for (int i=0;i<10;i++) { AI[i] = proto.AI[i]; } for (int i=0;i<SPRITE_MAX_ANIMAATIOITA;i++) { for (int j=0;j<ANIMAATIO_MAX_SEKVENSSEJA;j++) animaatiot[i].sekvenssi[j] = proto.animaatiot[i].sekvenssi[j]; animaatiot[i].looppi = proto.animaatiot[i].looppi; animaatiot[i].frameja = proto.animaatiot[i].frameja; } } int PK2Sprite_Prototyyppi::Lataa(char *polku, char *tiedoston_nimi) { this->Uusi(); char kuva[_MAX_PATH]; strcpy(kuva,""); strcpy(kuva,polku); // Ladataan itse sprite-tiedosto if (strcmp(polku,"")!=0) strcat(polku,tiedoston_nimi); else { //strcpy(polku,"\\"); strcpy(polku,tiedoston_nimi); } ifstream *tiedosto = new ifstream(polku, ios::binary); char versio[4]; if (tiedosto->fail()) { delete (tiedosto); return 1; } tiedosto->read ((char *)versio, 4); if (strcmp(versio,"1.0") == 0) { this->Uusi(); PK2Sprite_Prototyyppi10 proto; tiedosto->read ((char *)&proto, sizeof (proto)); this->SetProto10(proto); strcpy(this->versio,versio); strcpy(this->tiedosto,tiedoston_nimi); } if (strcmp(versio,"1.1") == 0) { this->Uusi(); PK2Sprite_Prototyyppi11 proto; tiedosto->read ((char *)&proto, sizeof (proto)); this->SetProto11(proto); strcpy(this->versio,versio); strcpy(this->tiedosto,tiedoston_nimi); } if (strcmp(versio,"1.2") == 0) { this->Uusi(); PK2Sprite_Prototyyppi12 proto; tiedosto->read ((char *)&proto, sizeof (proto)); this->SetProto12(proto); strcpy(this->versio,versio); strcpy(this->tiedosto,tiedoston_nimi); } if (strcmp(versio,"1.3") == 0) { this->Uusi(); PK2Sprite_Prototyyppi13 proto; tiedosto->read ((char *)&proto, sizeof (proto)); this->SetProto13(proto); strcpy(this->versio,versio); strcpy(this->tiedosto,tiedoston_nimi); } //tiedosto->read ((char *)this, sizeof (*this)); if (tiedosto->fail()) { delete (tiedosto); return 1; } delete (tiedosto); // Ladataan kuva jossa spriten grafiikat ovat strcat(kuva,kuvatiedosto); int bufferi = PisteDraw_Buffer_Varaa(); //Uusi(640,480,false,255); if (PisteDraw_Lataa_Kuva(bufferi,kuva,false) == PD_VIRHE) return 1; /* if (this->vari != VARI_NORMAALI) { UCHAR *buffer = NULL; DWORD leveys; UCHAR vari; PisteDraw_Piirto_Aloita(bufferi,*&buffer,leveys); for (int x=0;x<640;x++) for (int y=0;y<480;y++) if ((vari = buffer[x+y*leveys]) != 255) { vari %= 32; vari += this->vari; buffer[x+y*leveys] = vari; } PisteDraw_Piirto_Lopeta(bufferi); } */ int frame_i = 0, frame_x = kuva_x, frame_y = kuva_y; for (frame_i=0; frame_i<frameja; frame_i++) { framet[frame_i] = PisteDraw_Buffer_Uusi(kuva_frame_leveys,kuva_frame_korkeus,bufferi); framet_peilikuva[frame_i] = PisteDraw_Buffer_Uusi(kuva_frame_leveys,kuva_frame_korkeus,bufferi); PisteDraw_Buffer_Tayta(framet[frame_i],255); PisteDraw_Buffer_Tayta(framet_peilikuva[frame_i],255); if (frame_x + kuva_frame_leveys > 640) { frame_y += this->kuva_frame_korkeus + 3; frame_x = kuva_x; } PisteDraw_Buffer_Flip_Nopea(bufferi,framet[frame_i],0,0, frame_x, frame_y, frame_x + kuva_frame_leveys, frame_y + kuva_frame_korkeus); PisteDraw_Buffer_Flip(framet[frame_i], framet_peilikuva[frame_i], 0, 0, true, false); frame_x += this->kuva_frame_leveys + 3; } PisteDraw_Buffer_Tuhoa(bufferi); return 0; } void PK2Sprite_Prototyyppi::Tallenna(char *tiedoston_nimi) { strcpy(this->tiedosto,tiedoston_nimi); PK2Sprite_Prototyyppi13 proto = GetProto13(); //strcpy(proto.versio ,PK2SPRITE_VIIMEISIN_VERSIO); ofstream *tiedosto = new ofstream(tiedoston_nimi, ios::binary); tiedosto->write (PK2SPRITE_VIIMEISIN_VERSIO, 4); tiedosto->write ((char *)&proto, sizeof (proto)); delete (tiedosto); } /* int PK2Sprite_Prototyyppi::Lataa(char *filename) { FILE *tiedosto; if ((tiedosto = fopen(filename, "r")) == NULL) { return 1; } char versio[4] = "\0"; fread(versio, sizeof(this->versio), 1, tiedosto); fclose(tiedosto); // Tutkitaan versionumeroa jos tarvitsee if ((tiedosto = fopen(filename, "r")) == NULL) { return(1); } fread(this, sizeof(PK2Sprite_Prototyyppi), 1, tiedosto); fclose(tiedosto); int bufferi = PisteDraw_Buffer_Uusi(640,480,false,255); PisteDraw_Lataa_Kuva(bufferi,kuvatiedosto,false); int frame_i = 0, frame_x = kuva_x; for (frame_i=0; frame_i<frameja; frame_i++) { framet[frame_i] = PisteDraw_Buffer_Uusi(kuva_frame_leveys,kuva_frame_korkeus,true,255); framet_peilikuva[frame_i] = PisteDraw_Buffer_Uusi(kuva_frame_leveys,kuva_frame_korkeus,true,255); PisteDraw_Buffer_Tayta(framet[frame_i],255); PisteDraw_Buffer_Tayta(framet_peilikuva[frame_i],255); PisteDraw_Buffer_Flip_Nopea(bufferi,framet[frame_i],0,0, frame_x, kuva_y, frame_x + kuva_frame_leveys, kuva_y + kuva_frame_korkeus); PisteDraw_Buffer_Flip(framet[frame_i], framet_peilikuva[frame_i], 0, 0, true, false); frame_x += 35; } PisteDraw_Buffer_Tuhoa(bufferi); return 0; } int PK2Sprite_Prototyyppi::Tallenna(char *filename) { FILE *tiedosto; if ((tiedosto = fopen(filename, "w")) == NULL) { return(1); } fwrite(this, sizeof(PK2Sprite_Prototyyppi), 1, tiedosto); fclose(tiedosto); return 0; } */ int PK2Sprite_Prototyyppi::Piirra(int x, int y, int frame) { PisteDraw_Buffer_Flip_Nopea(framet[frame], PD_TAUSTABUFFER, x, y); return 0; } bool PK2Sprite_Prototyyppi::Onko_AI(int ai) { for (int i=0;i<SPRITE_MAX_AI;i++) { if (AI[i] == ai) return true; } return false; } /* -------- PK2Sprite ------------------------------------------------------------------ */ PK2Sprite::PK2Sprite() { this->tyyppi = NULL; this->pelaaja = 0; this->piilota = true; this->x = 0; this->y = 0; this->alku_x = 0; this->alku_y = 0; this->a = 0; this->b = 0; this->hyppy_ajastin = 0; this->kyykky = false; this->energia = 0; this->alkupaino = 0; this->paino = 0; this->kytkinpaino = 0; this->flip_x = false; this->flip_y = false; this->animaatio_index = ANIMAATIO_PAIKALLA; this->alas = true; this->ylos = true; this->oikealle = true; this->vasemmalle = true; this->reuna_oikealla = false; this->reuna_vasemmalla = false; this->frame_aika = 0; this->sekvenssi_index = 0; this->isku = 0; this->lataus = 0; this->hyokkays1 = 0; this->hyokkays2 = 0; this->vedessa = false; this->piilossa = false; this->saatu_vahinko = 0; this->vihollinen = false; this->ammus1 = -1; this->ammus2 = -1; this->pelaaja_x = -1; this->pelaaja_y = -1; this->ajastin = 0; this->muutos_ajastin = 0; } PK2Sprite::PK2Sprite(PK2Sprite_Prototyyppi *tyyppi, int pelaaja, bool piilota, double x, double y) { if (tyyppi) { this->tyyppi = tyyppi; this->pelaaja = pelaaja; this->piilota = piilota; this->x = x; this->y = y; this->alku_x = x; this->alku_y = y; this->a = 0; this->b = 0; this->hyppy_ajastin = 0; this->energia = tyyppi->energia; this->alkupaino = tyyppi->paino; this->paino = this->alkupaino; this->kytkinpaino = 0; this->kyykky = false; this->flip_x = false; this->flip_y = false; this->animaatio_index = ANIMAATIO_PAIKALLA; this->alas = true; this->ylos = true; this->oikealle = true; this->vasemmalle = true; this->reuna_oikealla = false; this->reuna_vasemmalla = false; this->frame_aika = 0; this->sekvenssi_index = 0; this->isku = 0; this->lataus = 0; this->hyokkays1 = 0; this->hyokkays2 = 0; this->vedessa = false; this->piilossa = false; this->saatu_vahinko = 0; this->vihollinen = tyyppi->vihollinen; this->ammus1 = tyyppi->ammus1; this->ammus2 = tyyppi->ammus2; this->pelaaja_x = -1; this->pelaaja_y = -1; this->ajastin = 0; this->muutos_ajastin = 0; } } PK2Sprite::~PK2Sprite() {} bool PK2Sprite::Onko_AI(int ai) { for (int i=0;i<SPRITE_MAX_AI;i++) { if (tyyppi->AI[i] == ai) return true; } return false; } int PK2Sprite::Animaatio(int anim_i, bool nollaus) { if (anim_i != animaatio_index) { if (nollaus) sekvenssi_index = 0; animaatio_index = anim_i; } return 0; } int PK2Sprite::Animoi() { int frame = 0; switch (tyyppi->AI[0]) { case AI_KANA: Animaatio_Kana();break; case AI_PIKKUKANA: Animaatio_Kana();break; case AI_BONUS: Animaatio_Bonus();break; case AI_MUNA: Animaatio_Muna();break; case AI_AMMUS: Animaatio_Ammus();break; case AI_HYPPIJA: Animaatio_Kana();break; case AI_PERUS: Animaatio_Perus();break; case AI_TELEPORTTI: Animaatio_Perus();break; default: break; } PK2SPRITE_ANIMAATIO &animaatio = tyyppi->animaatiot[animaatio_index]; if (sekvenssi_index >= animaatio.frameja) sekvenssi_index = 0; frame = animaatio.sekvenssi[sekvenssi_index]-1; // Lasketaan kuinka paljon tällä hetkellä voimassa olevaa framea vielä näytetään if (frame_aika < tyyppi->frame_rate) frame_aika++; // Jos aika on kulunut loppuun, vaihdetaan seuraava frame tämänhetkisestä animaatiosta else { frame_aika = 0; // Onko animaatiossa enää frameja? if (sekvenssi_index < animaatio.frameja-1) sekvenssi_index++; // Jos ei ja animaatio on asetettu luuppaamaan, aloitetaan animaatio alusta. else { if (animaatio.looppi) sekvenssi_index = 0; } } if (frame > tyyppi->frameja) frame = tyyppi->frameja; return frame; } int PK2Sprite::Piirra(int kamera_x, int kamera_y) { // Tehdään apumuuttujia int l = (int)tyyppi->kuva_frame_leveys/2,//leveys h = (int)tyyppi->kuva_frame_korkeus/2, x = (int)this->x-(kamera_x), y = (int)this->y-(kamera_y), frame = 0; frame = Animoi(); if (tyyppi->tarisee) { x+= rand()%2 - rand()%2; y+= rand()%2 - rand()%2; } if (flip_x) { if (!flip_y) PisteDraw_Buffer_Flip_Nopea(tyyppi->framet_peilikuva[frame], PD_TAUSTABUFFER, x-l-1, y-h); else PisteDraw_Buffer_Flip(tyyppi->framet_peilikuva[frame], PD_TAUSTABUFFER, x-l-1, y-h, false, true); } else { if (!flip_y) PisteDraw_Buffer_Flip_Nopea(tyyppi->framet[frame], PD_TAUSTABUFFER, x-l-1, y-h); else PisteDraw_Buffer_Flip(tyyppi->framet[frame], PD_TAUSTABUFFER, x-l-1, y-h, false, true); } return 0; } int PK2Sprite::AI_Perus() { if (x < 10) { x = 10; vasemmalle = false; } if (x > 8192) { x = 8192; oikealle = false; } if (y > 9920) { y = 9920; } if (y < -32) { y = -32; } if (a < 0) flip_x = true; if (a > 0) flip_x = false; ajastin++; if (ajastin > 31320) // jaollinen 360:lla ajastin = 0; return 0; } int PK2Sprite::AI_Kaantyy_Esteesta_Hori() { if (energia > 0) { if (!oikealle) { a = this->tyyppi->max_nopeus / -3.5; return 1; } if (!vasemmalle) { a = this->tyyppi->max_nopeus / 3.5; return 1; } } return 0; } int PK2Sprite::AI_Kaantyy_Esteesta_Vert() { if (energia > 0) { if (!alas) { b = this->tyyppi->max_nopeus / -3.5; return 1; } if (!ylos) { b = this->tyyppi->max_nopeus / 3.5; return 1; } } return 0; } int PK2Sprite::AI_Kiipeilija() { if (energia > 0) { if (!alas && vasemmalle) { b = 0; a = this->tyyppi->max_nopeus / -3.5; //return 1; } if (!ylos && oikealle) { b = 0; a = this->tyyppi->max_nopeus / 3.5; //b = this->tyyppi->max_nopeus / 3.5; //return 1; } if (!oikealle && alas) { a = 0; b = this->tyyppi->max_nopeus / 3.5; //return 1; } if (!vasemmalle && ylos) { a = 0; b = this->tyyppi->max_nopeus / -3.5; //return 1; } } return 0; } int PK2Sprite::AI_Kiipeilija2() { if (energia > 0) { if (vasemmalle && oikealle && ylos && alas) { if (a < 0) { b = this->tyyppi->max_nopeus / 3.5; //a = 0; } else if (a > 0) { b = this->tyyppi->max_nopeus / -3.5; //a = 0; } else if (b < 0) { a = this->tyyppi->max_nopeus / -3.5; //b = 0; } else if (b > 0) { a = this->tyyppi->max_nopeus / 3.5; //b = 0; } /* if (a != 0) b = 0; */ if (b != 0) a = 0; } } return 0; } int PK2Sprite::AI_Varoo_Kuoppaa() { double max = tyyppi->max_nopeus / 3.5; if (energia > 0) { if (this->reuna_oikealla && this->a > -max) { this->a -= 0.13; } if (this->reuna_vasemmalla && this->a < max) { this->a += 0.13; } /* if (this->reuna_oikealla && this->a > 0) { this->a = this->a * -1; flip_x = true; } if (this->reuna_vasemmalla && this->a < 0) { this->a = this->a * -1; flip_x = false; } */ } return 0; } int PK2Sprite::AI_Random_Hyppy() { if (energia > 0) { if (rand()%150 == 10 && b == 0 && hyppy_ajastin == 0 && ylos) { hyppy_ajastin = 1; } } return 0; } int PK2Sprite::AI_Sammakko1() { if (energia > 0) { if (ajastin%100 == 0 && hyppy_ajastin == 0 && ylos) { hyppy_ajastin = 1; } } return 0; } int PK2Sprite::AI_Sammakko2() { if (energia > 0) { if (ajastin%100 == 0 && ylos) { hyppy_ajastin = 1; } if (hyppy_ajastin > 0) { if (!flip_x) a = this->tyyppi->max_nopeus / 3.5; else a = this->tyyppi->max_nopeus / -3.5; } } return 0; } int PK2Sprite::AI_Random_Suunnanvaihto_Hori() { if (energia > 0) { if (rand()%150 == 1) { int max = (int)tyyppi->max_nopeus / 4; while (a == 0 && max > 0) a = rand()%max+1 - rand()%max+1; } } return 0; } int PK2Sprite::AI_Random_Kaantyminen() { if (energia > 0) { if (ajastin%400 == 1 && a == 0) { flip_x = !flip_x; } } return 0; } int PK2Sprite::AI_Kaantyy_Jos_Osuttu() { if (isku == VAHINKO_AIKA/* saatu_vahinko*/ > 0 && energia > 0) { if (a != 0) a = -a; flip_x = !flip_x; } return 0; } int PK2Sprite::AI_Random_Liikahdus_Vert_Hori() { if (energia > 0) { if (rand()%150 == 1 || ajastin == 1) if ((int)a == 0 || (int)b == 0) { int max = (int)tyyppi->max_nopeus; if (max != 0) { while (a == 0) a = rand()%(max+1) - rand()%(max+1); while (b == 0) b = rand()%(max+1) - rand()%(max+1); //a /= 3.0; //b /= 3.0; } } } return 0; } int PK2Sprite::AI_Seuraa_Pelaajaa(PK2Sprite &pelaaja) { if (energia > 0 && pelaaja.energia > 0) { double max = tyyppi->max_nopeus / 3.5; if (a > -max && x > pelaaja.x) { a -= 0.1; } if (a < max && x < pelaaja.x) { a += 0.1; } pelaaja_x = (int)(pelaaja.x+pelaaja.a); pelaaja_y = (int)(pelaaja.y+pelaaja.b); if (tyyppi->max_nopeus == 0) { if (pelaaja.x < x) flip_x = true; else flip_x = false; } } return 0; } int PK2Sprite::AI_Pakenee_Pelaajaa_Jos_Nakee(PK2Sprite &pelaaja) { if (energia > 0 && pelaaja.energia > 0) { if ((pelaaja.x < x && flip_x && !pelaaja.flip_x) || (pelaaja.x > x && !flip_x && pelaaja.flip_x)) if ((pelaaja.x - x < 300 && pelaaja.x - x > -300) && (pelaaja.y - y < tyyppi->korkeus && pelaaja.y - y > -tyyppi->korkeus)) { double max = tyyppi->max_nopeus / 2.5; if (x > pelaaja.x) { a = max; flip_x = false; } if (x < pelaaja.x) { a = max * -1; flip_x = true; } } } return 0; } int PK2Sprite::AI_Seuraa_Pelaajaa_Jos_Nakee(PK2Sprite &pelaaja) { if (energia > 0 && pelaaja.energia > 0) { double max = tyyppi->max_nopeus / 3.5; if (pelaaja_x != -1) { if (a > -max && x > pelaaja_x) a -= 0.1; if (a < max && x < pelaaja_x) a += 0.1; } if ((pelaaja.x < x && flip_x) || (pelaaja.x > x && ! flip_x)) if ((pelaaja.x - x < 300 && pelaaja.x - x > -300) && (pelaaja.y - y < tyyppi->korkeus && pelaaja.y - y > -tyyppi->korkeus)) { pelaaja_x = (int)(pelaaja.x+pelaaja.a); pelaaja_y = (int)(pelaaja.y+pelaaja.b); } else { pelaaja_x = -1; pelaaja_y = -1; } } return 0; } int PK2Sprite::AI_Jahtaa_Pelaajaa(PK2Sprite &pelaaja) { if (energia > 0 && pelaaja.energia > 0) { double max = tyyppi->max_nopeus / 3.5; if (pelaaja_x != -1) { if (a > -max && x > pelaaja_x) a -= 0.1; if (a < max && x < pelaaja_x) a += 0.1; if (x - pelaaja_x > -8 && x - pelaaja_x < 8) // onko sprite saavuttanut pelaajan viime sijainnin pelaaja_x = -1; } if (pelaaja_y != -1 && paino == 0) { if (b > -max && y > pelaaja_y) b -= 0.1; if (b < max && y < pelaaja_y) b += 0.1; if (y - pelaaja_y > -8 && y - pelaaja_y < 8) // onko sprite saavuttanut pelaajan viime sijainnin pelaaja_y = -1; } if (((pelaaja.x < x && !flip_x) || (pelaaja.x > x && flip_x)) && pelaaja.hyokkays2 != pelaaja.tyyppi->latausaika) return 0; if ((pelaaja.x - x < 300 && pelaaja.x - x > -300) && (pelaaja.y - y < tyyppi->korkeus && pelaaja.y - y > -tyyppi->korkeus)) { pelaaja_x = (int)(pelaaja.x+pelaaja.a); pelaaja_y = (int)(pelaaja.y+pelaaja.b); } } return 0; } int PK2Sprite::AI_Seuraa_Pelaajaa_Vert_Hori(PK2Sprite &pelaaja) { if (energia > 0 && pelaaja.energia > 0) { double max = tyyppi->max_nopeus / 3.5; if (a > -max && x > pelaaja.x) { a -= 0.1; } if (a < max && x < pelaaja.x) { a += 0.1; } if (b > -max && y > pelaaja.y) { b -= 0.4; } if (b < max && y < pelaaja.y) { b += 0.4; } pelaaja_x = (int)(pelaaja.x+pelaaja.a); pelaaja_y = (int)(pelaaja.y+pelaaja.b); if (tyyppi->max_nopeus == 0) { if (pelaaja.x < x) flip_x = true; else flip_x = false; } } return 0; } int PK2Sprite::AI_Seuraa_Pelaajaa_Jos_Nakee_Vert_Hori(PK2Sprite &pelaaja) { if (energia > 0 && pelaaja.energia > 0) { double max = tyyppi->max_nopeus / 3.5; if (pelaaja_x != -1) { if (a > -max && x > pelaaja_x) a -= 0.1; if (a < max && x < pelaaja_x) a += 0.1; if (b > -max && y > pelaaja_y) b -= 0.4; if (b < max && y < pelaaja_y) b += 0.4; } if ((pelaaja.x < x && flip_x) || (pelaaja.x > x && ! flip_x)) if ((pelaaja.x - x < 300 && pelaaja.x - x > -300) && (pelaaja.y - y < 80 && pelaaja.y - y > -80)) { pelaaja_x = (int)(pelaaja.x+pelaaja.a); pelaaja_y = (int)(pelaaja.y+pelaaja.b); } else { pelaaja_x = -1; pelaaja_y = -1; } } return 0; } int PK2Sprite::AI_Muutos_Jos_Energiaa_Alle_2(PK2Sprite_Prototyyppi &muutos) { if (energia < 2 && muutos.indeksi != tyyppi->indeksi) { tyyppi = &muutos; alkupaino = tyyppi->paino; //ammus1 = tyyppi->ammus1; //ammus2 = tyyppi->ammus2; return 1; } return 0; } int PK2Sprite::AI_Muutos_Jos_Energiaa_Yli_1(PK2Sprite_Prototyyppi &muutos) { if (energia > 1 && muutos.indeksi != tyyppi->indeksi) { tyyppi = &muutos; alkupaino = tyyppi->paino; //ammus1 = tyyppi->ammus1; //ammus2 = tyyppi->ammus2; return 1; } return 0; } int PK2Sprite::AI_Muutos_Ajastin(PK2Sprite_Prototyyppi &muutos) { if (energia > 0 && muutos.indeksi != tyyppi->indeksi) { if (muutos_ajastin/*lataus*/ == 0) muutos_ajastin/*lataus*/ = tyyppi->latausaika; if (muutos_ajastin/*lataus*/ == 1) { tyyppi = &muutos; alkupaino = tyyppi->paino; ammus1 = tyyppi->ammus1; ammus2 = tyyppi->ammus2; animaatio_index = -1; Animaatio(ANIMAATIO_PAIKALLA,true); } return 1; } return 0; } int PK2Sprite::AI_Muutos_Jos_Osuttu(PK2Sprite_Prototyyppi &muutos) { if (energia > 0 && muutos.indeksi != tyyppi->indeksi) { if (saatu_vahinko > 0) { tyyppi = &muutos; alkupaino = tyyppi->paino; ammus1 = tyyppi->ammus1; ammus2 = tyyppi->ammus2; animaatio_index = -1; Animaatio(ANIMAATIO_PAIKALLA,true); return 1; } } return 0; } int PK2Sprite::AI_Tuhoutuu_Jos_Emo_Tuhoutuu(PK2Sprite *spritet) { if (emosprite > -1) { if (spritet[emosprite].energia < 1 && energia > 0) { saatu_vahinko = energia; this->saatu_vahinko_tyyppi = VAHINKO_KAIKKI; return 1; } } return 0; } int PK2Sprite::AI_Hyokkays_1_Jos_Osuttu() { if (saatu_vahinko > 0 && energia > 0) { this->hyokkays1 = this->tyyppi->hyokkays1_aika; this->lataus = 0; return 1; } return 0; } int PK2Sprite::AI_Hyokkays_2_Jos_Osuttu() { if (saatu_vahinko > 0 && energia > 0) { this->hyokkays2 = this->tyyppi->hyokkays2_aika; this->lataus = 0; return 1; } return 0; } int PK2Sprite::AI_Hyokkays_1_Nonstop() { if (this->lataus == 0 && energia > 0) { this->hyokkays1 = this->tyyppi->hyokkays1_aika; return 1; } return 0; } int PK2Sprite::AI_Hyokkays_2_Nonstop() { if (this->lataus == 0 && energia > 0) { this->hyokkays2 = this->tyyppi->hyokkays2_aika; return 1; } return 0; } int PK2Sprite::AI_Hyokkays_1_Jos_Pelaaja_Edessa(PK2Sprite &pelaaja) { if (energia > 0 && isku == 0 && pelaaja.energia > 0) { if ((pelaaja.x - x < 200 && pelaaja.x - x > -200) && (pelaaja.y - y < tyyppi->korkeus && pelaaja.y - y > -tyyppi->korkeus)) { if ((pelaaja.x < x && flip_x) || (pelaaja.x > x && !flip_x)) { this->hyokkays1 = this->tyyppi->hyokkays1_aika; return 1; } } } return 0; } int PK2Sprite::AI_Hyokkays_2_Jos_Pelaaja_Edessa(PK2Sprite &pelaaja) { if (energia > 0 && isku == 0 && pelaaja.energia > 0) { if ((pelaaja.x - x < 200 && pelaaja.x - x > -200) && (pelaaja.y - y < tyyppi->korkeus && pelaaja.y - y > -tyyppi->korkeus)) { if ((pelaaja.x < x && flip_x) || (pelaaja.x > x && !flip_x)) { this->hyokkays2 = this->tyyppi->hyokkays2_aika; return 1; } } } return 0; } int PK2Sprite::AI_Hyokkays_1_Jos_Pelaaja_Alapuolella(PK2Sprite &pelaaja) { if (energia > 0 && isku == 0 && pelaaja.energia > 0) { if ((pelaaja.x - x < tyyppi->leveys && pelaaja.x - x > -tyyppi->leveys) && (pelaaja.y > y && pelaaja.y - y < 350)) { this->hyokkays1 = this->tyyppi->hyokkays2_aika; return 1; } } return 0; } int PK2Sprite::AI_Hyppy_Jos_Pelaaja_Ylapuolella(PK2Sprite &pelaaja) { if (energia > 0 && hyppy_ajastin == 0 && pelaaja.energia > 0) { if ((pelaaja.x - x < tyyppi->leveys && pelaaja.x - x > -tyyppi->leveys) && (pelaaja.y < y && y - pelaaja.y < 350)) { hyppy_ajastin = 1; return 1; } } return 0; } int PK2Sprite::AI_NonStop() { if (energia > 0) { double max = tyyppi->max_nopeus / 3.5; if (flip_x) { if (a > -max) a -= 0.1; } else { if (a < max) a += 0.1; } } return 0; } int PK2Sprite::AI_Kitka_Vaikuttaa() { if (energia > 0) { if (!alas) a /= 1.07; else a /= 1.02; } return 0; } int PK2Sprite::AI_Piiloutuu() { if (energia > 0 && piilossa) { a /= 1.02; kyykky = true; } return 0; } int PK2Sprite::AI_Palaa_Alkuun_X() { if (energia < 1 || pelaaja_x != -1) return 0; double max = tyyppi->max_nopeus / 3.5; if (x < alku_x-16 && a < max) a += 0.05; if (x > alku_x+16 && a > -max) a -= 0.05; return 0; } int PK2Sprite::AI_Palaa_Alkuun_Y() { if (energia > 0 && pelaaja_x == -1) { double max = tyyppi->max_nopeus / 3.5; if (y < alku_y-16 && b < max) b += 0.04; if (y > alku_y+16 && b > -max) b -= 0.04; } return 0; } int PK2Sprite::AI_Tippuu_Tarinasta(int tarina) { if (energia > 0 && tarina > 0) { alkupaino = 0.5; } return 0; } int PK2Sprite::AI_Vahingoittuu_Vedesta() { if (energia > 0) if (this->vedessa) saatu_vahinko++; return 0; } int PK2Sprite::AI_Tapa_Kaikki() { if (energia > 0) this->vihollinen = !this->vihollinen; return 0; } int PK2Sprite::AI_Hyppija() { if (x < 10) { x = 10; } if (y > 9920) { y = 9920; } if (energia > 0) { if (!alas && b==0 && hyppy_ajastin == 0) { hyppy_ajastin = 1; } } if (a < 0) flip_x = true; if (a > 0) flip_x = false; return 0; } int PK2Sprite::AI_Liikkuu_X(double liike) { if (energia > 0) this->x = this->alku_x + liike; return 0; } int PK2Sprite::AI_Liikkuu_Y(double liike) { if (energia > 0) { this->y = this->alku_y + liike; } return 0; } int PK2Sprite::AI_Tippuu_Jos_Kytkin_Painettu(int kytkin) { if (kytkin > 0) { alkupaino = 1.5; } return 0; } int PK2Sprite::AI_Liikkuu_Jos_Kytkin_Painettu(int kytkin, int ak, int bk) { if (kytkin > 0) { if (a == 0 && ak != 0) { a = tyyppi->max_nopeus / 3.5 * ak; // ak = -1 / 1 } if (b == 0 && bk != 0) b = tyyppi->max_nopeus / 3.5 * bk; // bk = -1 / 1 } flip_x = false; return 0; } bool PK2Sprite::AI_Info(PK2Sprite &pelaaja) { if ((pelaaja.x - x < 10 && pelaaja.x - x > -10) && (pelaaja.y - y < tyyppi->korkeus && pelaaja.y - y > -tyyppi->korkeus)) { return true; } return false; } int PK2Sprite::AI_Kana() { if (x < 10) { x = 10; } if (y > 9920) { y = 9920; } if (energia > 0) { if (rand()%50 == 10 && a != 0) a /= 1.1; if (rand()%150 == 10 && b == 0 && hyppy_ajastin == 0 && ylos) { hyppy_ajastin = 1; while (a == 0) a = rand()%2 - rand()%2; } if (rand()%20 == 1 && b == 0 && hyppy_ajastin == 0 && !oikealle && !flip_x) { hyppy_ajastin = 1; while (a == 0) a = rand()%2; } if (rand()%20 == 1 && b == 0 && hyppy_ajastin == 0 && !vasemmalle && flip_x) { hyppy_ajastin = 1; while (a == 0) a = rand()%2 * -1; } if (rand()%200 == 10) a = rand()%2 - rand()%2; if (hyppy_ajastin == tyyppi->max_hyppy && a == 0) { while (a == 0) a = rand()%2 - rand()%2; } /* // reunatesti if (rand()%100 == 2) a = rand()%2-rand()%2; if (reuna_vasemmalla && a < 0) a = 0; if (reuna_oikealla && a > 0) a = 0;*/ if (a < 0) flip_x = true; if (a > 0) flip_x = false; } return 0; } int PK2Sprite::AI_Bonus() { if (x < 10) { x = 10; } if (y > 9920) { y = 9920; } return 0; } int PK2Sprite::AI_Muna() { if (x < 10) { x = 10; } if (y > 9920) { y = 9920; } if (!alas) energia = 0; //a /= 1.01; if (energia == 0 && lataus == 0) lataus = tyyppi->latausaika; if (this->lataus == 1) this->piilota = true; return 0; } int PK2Sprite::AI_Ammus() { if (x < 10) { x = 10; } if (y > 9920) { y = 9920; } if (a < 0) flip_x = true; if (a > 0) flip_x = false; if (this->lataus == 0) lataus = this->tyyppi->latausaika; if (this->lataus == 1) { this->saatu_vahinko = this->tyyppi->energia; this->saatu_vahinko_tyyppi = VAHINKO_KAIKKI; } if (energia < 1) piilota = true; return 0; } int PK2Sprite::AI_Pommi() { if (this->lataus == 0) lataus = this->tyyppi->latausaika; if (this->lataus == 1) { this->saatu_vahinko = this->energia; this->saatu_vahinko_tyyppi = VAHINKO_KAIKKI; } return 0; } int PK2Sprite::AI_Teleportti(int oma_i, PK2Sprite *spritet, int max, PK2Sprite &sprite) { int siirto = 0; if (energia > 0 && lataus == 0 && hyokkays1 == 0) { if (sprite.x <= x + tyyppi->leveys /2 && sprite.x >= x - tyyppi->leveys /2 && sprite.y <= y + tyyppi->korkeus/2 && sprite.y >= y - tyyppi->korkeus/2 ) { int portit[1200]; int portti_index = 0; int porttien_maara = 0; int i = 0; // alustetaan portit-taulukko, johon kerätään kaikkien teleportti spritejen indeksit for (i=0;i<max;i++) portit[i] = -1; // etsitään SAMANTYYPPISET teleportit for (i=0;i<max;i++) if (spritet[i].tyyppi != NULL) if (spritet[i].tyyppi->tyyppi == TYYPPI_TELEPORTTI && tyyppi->indeksi == spritet[i].tyyppi->indeksi) { portit[portti_index] = i; portti_index++; porttien_maara++; } // jos yhtään samantyyppistä ei löydy... if (porttien_maara == 0) { // ...etsitään KAIKKI teleportit portti_index = 0; porttien_maara = 0; for (i=0;i<max;i++) if (spritet[i].tyyppi != NULL) if (spritet[i].tyyppi->tyyppi == TYYPPI_TELEPORTTI) { portit[portti_index] = i; portti_index++; porttien_maara++; } } // jos vieläkään ei löydy yhtään teleporttia (poislukien teleportti itse), poistutaan. if (porttien_maara <= 1) return 0; if (porttien_maara > 1119/*599*/) porttien_maara = 1119/*599*/; // arvotaan kohdeportti i = portit[rand()%porttien_maara]; while(i == oma_i || i == -1) i = portit[rand()%porttien_maara]; if (spritet[i].tyyppi != NULL) { sprite.x = spritet[i].x; sprite.y = spritet[i].y; //lataus = tyyppi->latausaika; //hyokkays1 = tyyppi->hyokkays1_aika; //spritet[i].lataus = spritet[i].tyyppi->latausaika; spritet[i].hyokkays1 = spritet[i].tyyppi->hyokkays1_aika; lataus = 0; spritet[i].lataus = 0; siirto = 1; } } } return siirto; } /* int PK2Sprite::AI_Teleportti(int oma_i, PK2Sprite *spritet, int max, PK2Sprite &pelaaja) { int siirto = 0; if (energia > 0 && lataus == 0 && hyokkays1 == 0) { UCHAR todnak = 100; // todennäköisyys tulla valituksi kohdeteleportiksi if (pelaaja.x <= x + tyyppi->leveys /2 && pelaaja.x >= x - tyyppi->leveys /2 && pelaaja.y <= y + tyyppi->korkeus/2 && pelaaja.y >= y - tyyppi->korkeus/2 ) { for (int i=0;i<max;i++) { if (spritet[i].tyyppi != NULL) { if (spritet[i].tyyppi->tyyppi == TYYPPI_TELEPORTTI) { if (tyyppi->indeksi == spritet[i].tyyppi->indeksi && oma_i != i) { if (rand()%100 < todnak) { pelaaja.x = spritet[i].x; pelaaja.y = spritet[i].y; //lataus = tyyppi->latausaika; hyokkays1 = tyyppi->hyokkays1_aika; //spritet[i].lataus = spritet[i].tyyppi->latausaika; spritet[i].hyokkays1 = spritet[i].tyyppi->hyokkays1_aika; lataus = 0; spritet[i].lataus = 0; siirto = 1; } todnak /= 2; } } } } } } return siirto; } */ int PK2Sprite::Animaatio_Perus() { int uusi_animaatio = -1; bool alusta = false; if (energia < 1 && !alas) { uusi_animaatio = ANIMAATIO_KUOLEMA; alusta = true; } else { if (a > -0.2 && a < 0.2 && b == 0 && hyppy_ajastin <= 0) { uusi_animaatio = ANIMAATIO_PAIKALLA; alusta = true; } if ((a < -0.2 || a > 0.2) && hyppy_ajastin <= 0) { uusi_animaatio = ANIMAATIO_KAVELY; alusta = false; } if (b < 0)//-0.3 { uusi_animaatio = ANIMAATIO_HYPPY_YLOS; alusta = false; } if ((hyppy_ajastin > tyyppi->max_hyppy || b > 1.5) && alas) { uusi_animaatio = ANIMAATIO_HYPPY_ALAS; alusta = false; } if (kyykky) { uusi_animaatio = ANIMAATIO_KYYKKY; alusta = true; } if (hyokkays1 > 0) { uusi_animaatio = ANIMAATIO_HYOKKAYS1; alusta = true; } if (hyokkays2 > 0) { uusi_animaatio = ANIMAATIO_HYOKKAYS2; alusta = true; } if (isku > 0) { uusi_animaatio = ANIMAATIO_VAHINKO; alusta = false; } } if (uusi_animaatio != -1) Animaatio(uusi_animaatio,alusta); return 0; } int PK2Sprite::Animaatio_Kana() { int uusi_animaatio = -1; bool alusta = false; if (energia < 1 && !alas) { uusi_animaatio = ANIMAATIO_KUOLEMA; alusta = true; } else { if (a > -0.2 && a < 0.2 && b == 0 && hyppy_ajastin <= 0) { uusi_animaatio = ANIMAATIO_PAIKALLA; alusta = true; } if ((a < -0.2 || a > 0.2) && hyppy_ajastin <= 0) { uusi_animaatio = ANIMAATIO_KAVELY; alusta = false; } if (b < 0)//-0.3 { uusi_animaatio = ANIMAATIO_HYPPY_YLOS; alusta = false; } if ((hyppy_ajastin > 90+10/*tyyppi->max_hyppy || b > 1.5*/) && alas) { uusi_animaatio = ANIMAATIO_HYPPY_ALAS; alusta = false; } if (hyokkays1 > 0) { uusi_animaatio = ANIMAATIO_HYOKKAYS1; alusta = true; } if (hyokkays2 > 0) { uusi_animaatio = ANIMAATIO_HYOKKAYS2; alusta = true; } if (kyykky) { uusi_animaatio = ANIMAATIO_KYYKKY; alusta = true; } if (isku > 0) { uusi_animaatio = ANIMAATIO_VAHINKO; alusta = false; } } if (uusi_animaatio != -1) Animaatio(uusi_animaatio,alusta); return 0; } int PK2Sprite::Animaatio_Bonus() { Animaatio(ANIMAATIO_PAIKALLA, true); return 0; } int PK2Sprite::Animaatio_Ammus() { Animaatio(ANIMAATIO_PAIKALLA, true); return 0; } int PK2Sprite::Animaatio_Muna() { int uusi_animaatio = 0; bool alusta = false; uusi_animaatio = ANIMAATIO_PAIKALLA; alusta = true; if (energia < tyyppi->energia) { uusi_animaatio = ANIMAATIO_KUOLEMA; alusta = true; } Animaatio(uusi_animaatio,alusta); return 0; }
[ "samuli@samuli-laptop.(none)", "[email protected]" ]
[ [ [ 1, 925 ], [ 927, 955 ], [ 958, 2638 ] ], [ [ 926, 926 ], [ 956, 957 ] ] ]
dcbc59148d9e2b175cf17dfb2041f8389643399f
0dba4a3016f3ad5aa22b194137a72efbc92ab19e
/a2e/src/scene.h
bee0b53bf207979962c0f9f0f29fa551b8d488f0
[]
no_license
BackupTheBerlios/albion2
11e89586c3a2d93821b6a0d3332c1a7ef1af6abf
bc3d9ba9cf7b8f7579a58bc190a4abb32b30c716
refs/heads/master
2020-12-30T10:23:18.448750
2007-01-26T23:58:42
2007-01-26T23:58:42
39,515,887
0
0
null
null
null
null
UTF-8
C++
false
false
3,410
h
/* * 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 Library General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef __SCENE_H__ #define __SCENE_H__ #include <cmath> #include <iostream> #include <list> #include <SDL/SDL.h> #include "msg.h" #include "core.h" #include "engine.h" #include "a2emodel.h" #include "a2eanim.h" #include "light.h" #include "shader.h" #include "matrix4.h" #include "rtt.h" using namespace std; #include "win_dll_export.h" /*! @class scene * @brief a2e scene manager * @author flo * @todo implement a method to render all models in sequencing from far to near to the cameras pos, depending on their position * * the scene manager class */ class A2E_API scene { public: scene(engine* e, shader* s); ~scene(); a2eanim* create_a2eanim(); a2emodel* create_a2emodel(); void draw(); void start_draw(); void stop_draw(); void add_model(a2emodel* model); void add_model(a2eanim* model); void delete_model(a2emodel* model); void delete_model(a2eanim* model); void add_light(light* light); void set_position(float x, float y, float z); void set_mambient(float* mambient); void set_mdiffuse(float* mdiffuse); void set_mspecular(float* mspecular); //void set_mshininess(float* mshininess); void set_mshininess(int mshininess); void set_light(bool state); vertex3* get_position(); float* get_mambient(); float* get_mdiffuse(); float* get_mspecular(); //float* get_mshininess(); bool get_light(); void set_skybox_texture(unsigned int tex); unsigned int get_skybox_texture(); void set_render_skybox(bool state); bool get_render_skybox(); void preprocess(); void postprocess(); protected: msg* m; core* c; engine* e; shader* s; ext* exts; rtt* r; vertex3* position; //unsigned int cmodels; //a2emodel* models[256]; list<a2emodel*> models; //unsigned int camodels; //a2eanim* amodels[256]; list<a2eanim*> amodels; unsigned int clights; light* lights[8]; float* mambient; float* mdiffuse; float* mspecular; //float* mshininess; int mshininess; //! specifies if lighting is enabled in this scene bool is_light; unsigned int skybox_tex; float max_value; bool render_skybox; vertex3 sb_v0, sb_v1, sb_v2; matrix4* proj_mat; matrix4* mview_mat; // render and scene buffer rtt::fbo* render_buffer; // will be rendered to rtt::fbo* scene_buffer; // final output buffer // hdr buffer rtt::fbo* blur_buffer1; rtt::fbo* blur_buffer2; rtt::fbo* blur_buffer3; rtt::fbo* average_buffer; rtt::fbo* exposure_buffer[2]; int cur_exposure; float fframe_time; int iframe_time; float* tcs_line_h; float* tcs_line_v; bool flip; }; #endif
[ [ [ 1, 144 ] ] ]
311a169c3d8db419434bc0a07c982b04fcc9e882
25426133cf6405c5cebf4b51c48ff3dce2629ea9
/particle/particles.cpp
2ccc66a8e45a7b701b230a5749aac9806ab80dba
[]
no_license
tolhc1234/openglengine
456fd5a099b30544af1e338fab289402d2b81341
6ed525f9a74235605157e68728e36b8b5291b096
refs/heads/master
2021-01-10T02:38:58.457222
2010-01-12T20:28:21
2010-01-12T20:28:21
50,214,430
0
0
null
null
null
null
UTF-8
C++
false
false
3,040
cpp
#include "particles.h" #include <GL/glew.h> #include <GL/glext.h> #include <GL/gl.h> #include "../random.h" #include "../image/texture.h" texture* vuur; particles::particles() { } void particles::init(float size, int duration, float speed, int ammount, float* direction, float* color, float* posXYZ, float gravity) { Color[0] = color[0];Color[1] = color[1]; Color[2] = color[2]; Gravity = gravity; vuur = new texture("data/textures/vuur.jpg"); /////// Direction[0] = direction[0]; Direction[1] = direction[1]; Direction[2] = direction[2]; float tempPos[3] = {posXYZ[0],posXYZ[1],posXYZ[2]}; float tempColor[4] = {0.76,0,0.4,0.8}; theParticles = new particle[ammount]; for(int i = 0;i < ammount;i++) { theParticles[i].configure(tempPos,tempColor); theParticles[i].speed = random.gen(speed / 2, speed * 2); theParticles[i].orgSpeed = theParticles[i].speed; } Size = size; Duration = duration; Speed = speed; Ammount = ammount; Direction[0] = direction[0]; Direction[1] = direction[1]; Direction[2] = direction[2]; } particles::~particles() { delete[] theParticles; } particles::particles(float size, int duration, float speed, int ammount, float* direction, float* color, float* posXYZ, float gravity) { Color[0] = color[0];Color[1] = color[1]; Color[2] = color[2]; Gravity = gravity; vuur = new texture("data/textures/vuur.jpg"); /////// Direction[0] = direction[0]; Direction[1] = direction[1]; Direction[2] = direction[2]; float tempPos[3] = {posXYZ[0],posXYZ[1],posXYZ[2]}; float tempColor[4] = {0.76,0,0.4,0.8}; theParticles = new particle[ammount]; for(int i = 0;i < ammount;i++) { theParticles[i].configure(tempPos,tempColor); theParticles[i].speed = random.gen(speed / 2, speed * 2); theParticles[i].orgSpeed = theParticles[i].speed; } Size = size; Duration = duration; Speed = speed; Ammount = ammount; Direction[0] = direction[0]; Direction[1] = direction[1]; Direction[2] = direction[2]; } float quadratic[] = { 1.0f, 0.0f, 0.01f,0,0 }; void particles::render() { glBindTexture(GL_TEXTURE_2D, vuur->ID); //glPointParameterfv(GL_POINT_DISTANCE_ATTENUATION, quadratic); glEnable(GL_POINT_SPRITE); glEnable(GL_TEXTURE_2D); glTexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE); glPushAttrib(GL_COLOR_BUFFER_BIT); glColor4f(0,0,0,0.1); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE); glPointSize(16); glColor3fv(theParticles->color); glBegin(GL_POINTS); for(int i = 0;i < Ammount;i++) { glVertex3fv(theParticles[i].xyz); } glEnd(); glPointSize(1); glPopAttrib(); glDisable(GL_POINT_SPRITE); glDisable(GL_TEXTURE_2D); } void particles::update() { for(int i = 0; i < Ammount;i++) { if(theParticles[i].age > Duration) theParticles[i].reset(); else theParticles[i].xyz[0] += random.gen(-2,2); theParticles[i].xyz[1] += theParticles[i].speed; theParticles[i].xyz[2] += random.gen(-2,2); theParticles[i].age++; theParticles[i].speed -= Gravity / 100; } }
[ [ [ 1, 114 ] ] ]
d62493d9ac4cae91d43f963f80e133d6487453a9
49b6646167284329aa8644c8cf01abc3d92338bd
/SEP2_M6/FSM/Puck_FSM_2.h
e7521b8b80ca0728597ce4edf60304909414440c
[]
no_license
StiggyB/javacodecollection
9d017b87b68f8d46e09dcf64650bd7034c442533
bdce3ddb7a56265b4df2202d24bf86a06ecfee2e
refs/heads/master
2020-08-08T22:45:47.779049
2011-10-24T12:10:08
2011-10-24T12:10:08
32,143,796
0
0
null
null
null
null
UTF-8
C++
false
false
2,373
h
#ifndef PUCK_FSM_2_H_ #define PUCK_FSM_2_H_ #include <vector> #include <iostream.h> #include "Puck_FSM.h" #include "../HAL/HALCore.h" //#define PUCK_FSM_2_DEBUG /** * Puck_FSM_2 * * SE2 (+ SY and PL) Project SoSe 2011 * * Milestone 4: Automatenimplementierung * * Authors: Rico Flaegel, * Tell Mueller-Pettenpohl, * Torsten Krane, * Jan Quenzel * * class for machine 1 - sort out WP with with/without metal * * */ class Puck_FSM_2: public Puck_FSM { public: Puck_FSM_2(std::vector<Puck_FSM*>* puck_list); virtual ~Puck_FSM_2(); }; class FSM_2_start_state: public State { public: void entry(Puck_FSM * fsm); void ls_b0(Puck_FSM * fsm); void errorState(Puck_FSM * fsm); void exit(Puck_FSM * fsm); }; class FSM_2_after_ls_b0: public State { public: void entry(Puck_FSM * fsm); void ls_b1(Puck_FSM * fsm); void errorState(Puck_FSM * fsm); void exit(Puck_FSM * fsm); }; class FSM_2_after_ls_b1: public State { public: void entry(Puck_FSM * fsm); void ls_b3(Puck_FSM * fsm); void errorState(Puck_FSM * fsm); void exit(Puck_FSM * fsm); }; class FSM_2_in_metal_measure: public State { public: void entry(Puck_FSM * fsm); void errorState(Puck_FSM * fsm); void exit(Puck_FSM * fsm); }; class FSM_2_after_metal_measure_uncorrect_wp: public State { public: void entry(Puck_FSM * fsm); void ls_b6(Puck_FSM * fsm); void errorState(Puck_FSM * fsm); void exit(Puck_FSM * fsm); }; class FSM_2_wp_in_slide: public State { public: void entry(Puck_FSM * fsm); void errorState(Puck_FSM * fsm); void exit(Puck_FSM * fsm); }; class FSM_2_check_slide: public State { public: void entry(Puck_FSM * fsm); void errorState(Puck_FSM * fsm); void exit(Puck_FSM * fsm); }; class FSM_2_after_metal_measure_correct_wp: public State { public: void entry(Puck_FSM * fsm); void ls_b7_in(Puck_FSM * fsm); void errorState(Puck_FSM * fsm); void exit(Puck_FSM * fsm); }; class FSM_2_end_state: public State { public: void entry(Puck_FSM * fsm); void ls_b7_out(Puck_FSM * fsm); void errorState(Puck_FSM * fsm); void exit(Puck_FSM * fsm); }; class FSM_2_ErrorState: public State { public: void entry(Puck_FSM * fsm); void ls_b6(Puck_FSM * fsm); void reset(Puck_FSM * fsm); void exit(Puck_FSM * fsm); }; #endif /* PUCK_FSM_2_H_ */
[ "[email protected]@72d44fe2-11f0-84eb-49d3-ba3949d4c1b1", "[email protected]@72d44fe2-11f0-84eb-49d3-ba3949d4c1b1" ]
[ [ [ 1, 8 ], [ 10, 109 ] ], [ [ 9, 9 ] ] ]
1ffcc445fae37f62a3bb85910ae119b52e431bfa
bd89d3607e32d7ebb8898f5e2d3445d524010850
/connectivitylayer/usbphonetlink/usbpnserver_exe/inc/cusbpnserver.h
a83abd5519021b474bd83ac1685e21773ffc44c1
[]
no_license
wannaphong/symbian-incubation-projects.fcl-modemadaptation
9b9c61ba714ca8a786db01afda8f5a066420c0db
0e6894da14b3b096cffe0182cedecc9b6dac7b8d
refs/heads/master
2021-05-30T05:09:10.980036
2010-10-19T10:16:20
2010-10-19T10:16:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,527
h
/* * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of the License "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ #ifndef CUSBPNSERVER_H #define CUSBPNSERVER_H // INCLUDES #include <e32base.h> // For CServer2 #include "usbpndefinitions.h" // CONSTANTS // MACROS // DATA TYPES // FUNCTION PROTOTYPES // FORWARD DECLARATIONS class CUsbPnInterface; // CLASS DECLARATION /** * Server class */ class CUsbPnServer : public CServer2 { public: // Constructors and destructor /** * Two-phased constructor. */ static CUsbPnServer* NewL(); /** * Destructor. */ ~CUsbPnServer(); public: // New functions /** * Session will inform the server that the session has been opened * @return None */ void SessionOpened(); /** * Session will inform the server that the session has been closed * @return None */ void SessionClosed(); /** * Deletes interface so it's safe for class controller's Stop() to return * @return None */ void Detach(); public: // Functions from base classes /** * From CServer2. This function creates new server side session * @param aVersion Requested server version * @param aMessage * @return Pointer to created server side session */ CSession2* NewSessionL( const TVersion& aVersion, const RMessage2& aMessage ) const; private: /** * C++ default constructor. */ CUsbPnServer(); /** * By default Symbian 2nd phase constructor is private. */ void ConstructL(); private: // Data // Ownership. Instance of main class which handles events. CUsbPnInterface* iInterface; // The count of sessions TInt iSessionCount; }; #endif // CUSBPNSERVER_H // End of File
[ "dalarub@localhost" ]
[ [ [ 1, 109 ] ] ]
859e1ef04a315fedae06f55061161aa78bed0f45
36d0ddb69764f39c440089ecebd10d7df14f75f3
/プログラム/Ngllib/src/Bone.cpp
9b253762dd1609872e0cf954a41f78b89badfd18
[]
no_license
weimingtom/tanuki-mo-issyo
3f57518b4e59f684db642bf064a30fc5cc4715b3
ab57362f3228354179927f58b14fa76b3d334472
refs/heads/master
2021-01-10T01:36:32.162752
2009-04-19T10:37:37
2009-04-19T10:37:37
48,733,344
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
5,833
cpp
/*******************************************************************************/ /** * @file Bone.cpp. * * @brief ボーン情報クラスソースファイル. * * @date 2008/10/16. * * @version 1.00. * * @author Kentarou Nishimura. */ /******************************************************************************/ #include "Ngl/Bone.h" #include <cassert> using namespace Ngl; /*===========================================================================*/ /** * @brief コンストラクタ * * @param[in] なし. */ Bone::Bone(): boneID_( 0 ), parentBoneID_( 0 ), parent_( 0 ), sibling_( 0 ), child_( 0 ) { // ローカルの座標変換行列を単位行列にする matBoneOffset_.setIdentitiy(); } /*=========================================================================*/ /** * @brief ボーン情報を設定する * * @param[in] ID ボーンID. * @param[in] parentID 親ボーンID. * @param[in] parentOffset 親ボーンからの相対座標. * @param[in] matOffset ローカル座標変換行列. * @return なし. */ void Bone::create( unsigned int ID, unsigned int parentID, const Vector3& parentOffset, const Matrix4& matOffset ) { boneID_ = ID; parentBoneID_ = parentID; parentBoneOffset_ = parentOffset; matBoneOffset_ = matOffset; } /*=========================================================================*/ /** * @brief 親ボーンを設定する * * @param[in] parent 親ボーンのポインタ. * @return なし. */ void Bone::setParent( IBone* parent ) { parent_ = parent; // 兄弟ボーンを設定する sibling_ = parent->child(); } /*=========================================================================*/ /** * @brief 子ボーンを設定する * * @param[in] child 子ボーンのポインタ. * @return なし. */ void Bone::setChild( IBone* child ) { child_ = child; } /*===========================================================================*/ /** * @brief ボーンの変換行列の計算を行う * * @param[out] outMatrices 変換後の頂点配列. * @param[in] parentMatrix 親の変換行列へのポインタ, * @param[in] animMatrices アニメーション用変換行列. * @return なし. */ void Bone::calculateTransformMatrices( Matrix4* outMatrices, const Matrix4* parentMatrix, const Matrix4* animMatrices ) { // 変換先の行列を取得する Matrix4* outMatrix = &outMatrices[ boneID_ ]; // 行列を初期化する outMatrix->setIdentitiy(); // 親の行列が設定されているか if( parentMatrix != 0 ){ // アニメーション変換行列が設定されているか if( animMatrices != 0 ){ // アニメーション変換行列の取得 *outMatrix = animMatrices[ boneID_ ]; } // 親からの相対座標をモデリング変換行列に加算する outMatrix->m[3][0] += parentBoneOffset_.x; outMatrix->m[3][1] += parentBoneOffset_.y; outMatrix->m[3][2] += parentBoneOffset_.z; // 親の変換行列と合成 *outMatrix *= *parentMatrix; } // 兄弟を持っているか if( sibling_ != 0 ){ // 兄弟を計算させる sibling_->calculateTransformMatrices( outMatrices, parentMatrix, animMatrices ); } // 子供を持っているか if( child_ != 0 ){ child_->calculateTransformMatrices( outMatrices, outMatrix, animMatrices ); } } /*=========================================================================*/ /** * @brief ボーンを座標変換する * * @param[in] matrix 変換行列. * @return なし. */ void Bone::transform(const Matrix4 &matrix) { // 兄弟がいるか if( sibling_ != 0 ){ sibling_->transform( matrix ); } // 子供がいるか if( child_ != 0 ){ child_->transform( matrix ); } } /*=========================================================================*/ /** * @brief ボーンIDを取得する * * @param[in] なし. * @return ボーンID */ unsigned int Bone::getBoneID() const { return boneID_; } /*=========================================================================*/ /** * @brief 親ボーンIDを取得する * * @param[in] なし. * @return 親ボーンID */ unsigned int Bone::getParentBoneID() const { return parentBoneID_; } /*=========================================================================*/ /** * @brief 親ボーンからの相対距離を取得する * * @param[in] なし. * @return 親ボーンとの相対距離. */ const Ngl::Vector3& Bone::getParentBoneOffset() const { return parentBoneOffset_; } /*=========================================================================*/ /** * @brief ローカル座標変換行列を取得する * * @param[in] なし. * @return ローカル座標変換行列. */ const Ngl::Matrix4& Bone::getMatBoneOffset() const { return matBoneOffset_; } /*=========================================================================*/ /** * @brief 兄弟ボーンを取得する * * @param[in] なし. * @return 兄弟ボーン. */ IBone* Bone::sibling() { return sibling_; } /*=========================================================================*/ /** * @brief 親ボーンを取得する * * @param[in] なし. * @return 親ボーン. */ IBone* Bone::parent() { return parent_; } /*=========================================================================*/ /** * @brief 子ボーンを取得する * * @param[in] なし. * @return 子ボーン. */ IBone* Bone::child() { return child_; } /*========= EOF =============================================================*/
[ "rs.drip@aa49b5b2-a402-11dd-98aa-2b35b7097d33" ]
[ [ [ 1, 253 ] ] ]
2cb2dd2af21d9014638ee3f21575d7185d556d4b
904b92806d75601317f0158eb142d3565c0b0aba
/vstParameter.h
5c8a935e91f873214b4d4b807bc4e05cc9ea69c4
[]
no_license
alessandrostone/bitmangler
604735d457f9ef68004caf664695005c087d1b79
830e6e473a7aa0795385152cd4066c6d46e84cfd
refs/heads/master
2016-08-12T06:43:35.508327
2008-07-25T18:23:50
2008-07-25T18:23:50
45,255,449
0
0
null
null
null
null
UTF-8
C++
false
false
1,004
h
// vstParameter.h: interface for the vstParameter class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_VSTPARAMETER_H__495CF2F6_C20C_4CC3_94AE_9AAFA3170F10__INCLUDED_) #define AFX_VSTPARAMETER_H__495CF2F6_C20C_4CC3_94AE_9AAFA3170F10__INCLUDED_ #include <juce.h> class vstParameter { public: vstParameter(unsigned int i, String name); ~vstParameter(); void setValue (float newValue); void setRange (float _minValue, float _maxValue); void setMaxValue (float _maxValue); void setMinValue (float _minValue); void setName (String name); void setIndex (int index); int getValueAsInt (int max); float getValue (); float getLastValue (); String getParameterName (); private: unsigned int parameterIndex; String parameterName; float currentValue; float lastValue; float minValue; float maxValue; }; #endif // !defined(AFX_VSTPARAMETER_H__495CF2F6_C20C_4CC3_94AE_9AAFA3170F10__INCLUDED_)
[ "kubiak.roman@a8fb966b-8e52-0410-b8b9-d5648befe747" ]
[ [ [ 1, 35 ] ] ]
92e6dc9df10aa5edac8e36a72cb34cbf2d78df49
29c5bc6757634a26ac5103f87ed068292e418d74
/src/test/Tests/GameClient.cpp
a66e7665953d0750c860be6141ad8bbaa3dad95f
[]
no_license
drivehappy/tlapi
d10bb75f47773e381e3ba59206ff50889de7e66a
56607a0243bd9d2f0d6fb853cddc4fce3e7e0eb9
refs/heads/master
2021-03-19T07:10:57.343889
2011-04-18T22:58:29
2011-04-18T22:58:29
32,191,364
5
0
null
null
null
null
UTF-8
C++
false
false
1,700
cpp
#include "Test.h" #include "TestUserInterface.h" CGameClient *gameClient = NULL; void Test_GameClientLoadMap(PVOID retVal, CGameClient *client, u32 unk0, bool& calloriginal) { gameClient = client; testLogger.WriteLine(Info, L"GameClient(%p)::LoadMap( unk0(%x) ) returns Unk(%p)", client, unk0, retVal); } void Test_GameClientProcessObjects(CGameClient *client, float dTime, PVOID unk1, PVOID unk2) { gameClient = client; testLogger.WriteLine(Verbose, L"GameClient(%p)::ProcessObjects( dTime(%f), unk1(%x), unk2(%x) )", client, dTime, unk1, unk2); } void Test_GameClient_SaveGame(CGameClient *client, u32 unk0, u32 unk1, bool & callOriginal) { gameClient = client; testLogger.WriteLine(Info, L"GameClient(%p)::SaveGame( unk0(%x), unk1(%x) )", client, unk0, unk1); testLogger.WriteLine(Info, L"Save Game Suppressed", client, unk0, unk1); callOriginal = false; } void Test_GameClient_SetupUI(CGameClient *client, u32 unk0, u32 unk1) { client->pCGameUI->dumpGameUI(); } void Test_GameClient_CreateLevel(CGameClient* client, wstring unk0, wstring unk1, u32 unk2, u32 unk3, u32 unk4, wstring unk5, bool& calloriginal) { log("GameClient(%p) CreateLevel:", client); log(L" unk0: %s", unk0.c_str()); log(L" unk1: %s", unk1.c_str()); log(" unk2: %x", unk2); log(" unk3: %x", unk3); log(" unk4: %x", unk4); log(L" unk5: %s", unk5.c_str()); } void Test_GameClient_LoadLevel(CGameClient *client, bool& calloriginal) { log("GameClient LoadLevel (client = %p)", client); log(" LevelChange = %i", client->level); log(" LevelChangeUnk = %i", client->levelUnk); }
[ "drivehappy@53ea644a-42e2-1498-a4e7-6aa81ae25522" ]
[ [ [ 1, 62 ] ] ]
ebc1a3c635cb7384195656a6804663b33cc6cbe2
f6f211b3263e4bc12b263d481180aed044e7718a
/InnerActiveAd/InnerActiveAdWidget.h
bccf9734904c9e53f714e522ca9828cc8838dec2
[]
no_license
archerabi/ContactImage
e0468620540e86ac0b624f11990592cb1f387122
3167e97b431c44d5d1af8cea486d3061f7f2377a
refs/heads/master
2021-01-10T19:43:47.745836
2011-01-10T05:27:09
2011-01-10T05:27:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,246
h
#ifndef INNERACTIVEADWIDGET_H #define INNERACTIVEADWIDGET_H #include <QFrame> #include <QUrl> class QLabel; class QBuffer; /** * @brief InnerActiveAdWidget description. * * InnerActiveAdWidget (derived from QFrame) class object is created by InnerActiveAdModule::createAdBanner function. * */ class InnerActiveAdWidget : public QFrame { Q_OBJECT public: /** * @brief InnerActiveAdWidget constructor. * */ InnerActiveAdWidget(QWidget* pParent, const QByteArray& imageData, const QString& url = QString(), bool showAdText = false, const QString& text = QString()); void updateAdData(const QByteArray& imageData, const QString& url, const QString& text = QString()); signals: void adLinkActivated(const QUrl& adUrl); protected: bool eventFilter(QObject *obj, QEvent *ev); private slots: void onMovieFinished(); private: // functions void fitAdTextFont(int controlHeight); private: // class members QLabel* ipLabelImage; QLabel* ipLabelText; QMovie* ipMovie; QUrl iAdUrl; QString iAdText; QByteArray* ipImageByteArray; QBuffer* ipImageIoBuffer; }; #endif // INNERACTIVEADWIDGET_H
[ [ [ 1, 60 ] ] ]
8c00f2a6d10046808c91d6b7c9fc6378396174b0
ac559231a41a5833220a1319456073365f13d484
/src/sal/drivers/old/tests/auvgo.cpp
1d5b14bd1dcb6aaabe17a08038810be2616db9e1
[]
no_license
mtboswell/mtboswell-auvc2
6521002ca12f9f7e1ec5df781ed03419129b8f56
02bb0dd47936967a7b9fa7d091398812f441c1dc
refs/heads/master
2020-04-01T23:02:15.282160
2011-07-17T16:48:34
2011-07-17T16:48:34
32,832,956
0
0
null
null
null
null
UTF-8
C++
false
false
2,839
cpp
/* * File: auvgo.cpp * * Test the AUVstateflow simulink model * * See {modelname}/ert_main.cpp for code generation info * */ #include <stdio.h> /* This ert_main.c example uses printf/fflush */ #include <iostream> #include "AUVstateflow/AUVstateflow.h" /* Model's header file */ #include "AUVstateflow/rtwtypes.h" /* MathWorks types */ #include "auv.h" #include "alarm.h" using namespace std; static boolean_T OverrunFlag = 0; // check for overrun and step the simulink model void rt_OneStep(void) { /* Check for overrun */ if (OverrunFlag++) { rtmSetErrorStatus(AUVstateflow_M, "Overrun"); return; } /* Step the model */ AUVstateflow_step(); OverrunFlag--; } int main(int argc, const char *argv[]) { /* Initialize hardware */ AUV* auv = new AUV(); /* Data Vars */ imu_data orientation; real32_T depth; int8_T motorspeeds[3]; /* Initialize model */ AUVstateflow_initialize(); motorspeeds[0] = 0; motorspeeds[1] = 0; motorspeeds[2] = 0; auv->setThrusters(motorspeeds); int x = 0; // main loop counter // set up alarm for timing simulink step calls initalarm(); while (rtmGetErrorStatus(AUVstateflow_M) == (NULL)) { /* Wait for go */ auv->externalControl(motorspeeds); /* Get data from other devices */ depth = auv->getDepth(); orientation = auv->getOrientation(); /* Transfer sensor data to simulink input values */ AUVstateflow_U.CurrentDepth = depth; // real32_T AUVstateflow_U.CurrentHeading = orientation.yaw; // real_T /* Show inputs */ cout << "Current Depth: " << depth; cout << " Current Heading: " << AUVstateflow_U.CurrentHeading; /* Run Simulink model */ while(!checkalarm()) pause(); // wait for step period (change the timing in alarm.h) rt_OneStep(); // simulink! resetalarm(); // if you don't reset it won't wait next time around /* Get results from simulink */ motorspeeds[0] = AUVstateflow_Y.ChangetoLeft; motorspeeds[1] = AUVstateflow_Y.ChangetoRight; motorspeeds[2] = AUVstateflow_Y.ChangetoVertical; /* Show results of processing */ cout << " Left: " << (int) motorspeeds[0]; cout << " Right: " << (int) motorspeeds[1]; cout << " Vert: " << (int) motorspeeds[2]; cout << " Camera: " << (int) AUVstateflow_Y.CameraPosition << endl; /* Send data to other devices */ auv->setThrusters(motorspeeds); auv->look((cameraPosition) AUVstateflow_Y.CameraPosition); /* Increment loop counter */ x++; } // end loop cout << "Termination error: " << rtmGetErrorStatus(AUVstateflow_M) << endl; /* Terminate model */ AUVstateflow_terminate(); delete auv; return 0; } // end main
[ [ [ 1, 109 ] ] ]
22a610b0197894b21a8446b2eab50580435797cd
6060f9c92def1805578fe21068c193421e058278
/src/Context.cpp
34d318d494433b2bafafa28a3b5da0c2f434ce23
[]
no_license
MatthewNg3416/jaicam_test
134150cba552a17f9fa94d678ff8a66923a0b82a
8079fa66acde4b77023678b436891bcfe19ba8ca
refs/heads/master
2021-05-27T00:19:23.665817
2011-05-12T15:53:41
2011-05-12T15:53:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
239
cpp
/* * Stub of VS Context.cpp * */ #include "Context.h" Context::Context() { } Context::~Context() { } Context& Context::operator=(Context &rhs) { if (this != &rhs) _camera = rhs._camera; return *this; }
[ [ [ 1, 22 ] ] ]
db3786ca6d3a8e8ae51fc4ec1b61709ee254db42
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/functional/hash/test/hash_set_test.cpp
1e279707ba62e674766b4b9a443c384154539a98
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
862
cpp
// Copyright Daniel James 2005-2006. 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) #include "./config.hpp" #ifdef TEST_EXTENSIONS # ifdef TEST_STD_INCLUDES # include <functional> # else # include <boost/functional/hash.hpp> # endif #endif #include <boost/detail/lightweight_test.hpp> #ifdef TEST_EXTENSIONS #include <set> using std::set; #define CONTAINER_TYPE set #include "./hash_set_test.hpp" using std::multiset; #define CONTAINER_TYPE multiset #include "./hash_set_test.hpp" #endif int main() { #ifdef TEST_EXTENSIONS set_tests::set_hash_integer_tests(); multiset_tests::multiset_hash_integer_tests(); #endif return boost::report_errors(); }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 40 ] ] ]
df6bbc2eb73276d23c81511adc8fa40ec5f26a2d
fc4946d917dc2ea50798a03981b0274e403eb9b7
/gentleman/gentleman/WindowsAPICodePack/WindowsAPICodePack/DirectX/DirectX/DirectWrite/DWriteFontFamilyCollection.cpp
bca0a522b3ec7fc156affc714b6d5a41ffccb42e
[]
no_license
midnite8177/phever
f9a55a545322c9aff0c7d0c45be3d3ddd6088c97
45529e80ebf707e7299887165821ca360aa1907d
refs/heads/master
2020-05-16T21:59:24.201346
2010-07-12T23:51:53
2010-07-12T23:51:53
34,965,829
3
2
null
null
null
null
UTF-8
C++
false
false
5,387
cpp
// Copyright (c) Microsoft Corporation. All rights reserved. #include "stdafx.h" #include "DWriteFontFamilyCollection.h" #include "DWriteFontFamily.h" #include <msclr/lock.h> using namespace msclr; FontFamilyCollection::FontFamilyCollection(IDWriteFontCollection* pFontCollection) : DirectUnknown(pFontCollection) { UINT count = GetInterface<IDWriteFontCollection>()->GetFontFamilyCount(); if (count > 0) { m_families = gcnew array<FontFamily^>(count); } } FontFamilyCollection::~FontFamilyCollection() { if (m_families != nullptr) { for each (FontFamily^ family in m_families) { if (family != nullptr) { delete family; } } m_families = nullptr; } } FontFamily^ FontFamilyCollection::InitializeElement(int i) { lock l(this); // Make sure the array is not being modified on another thread, // otherwise we might get an exception if (m_families[i] == nullptr || m_families[i]->GetInterface<IUnknown>() == NULL) { IDWriteFontFamily* fontFamily = NULL; CommonUtils::VerifyResult( GetInterface<IDWriteFontCollection>()->GetFontFamily(i, &fontFamily)); m_families[i] = gcnew FontFamily(fontFamily); } return m_families[i]; } FontFamily^ FontFamilyCollection::default::get(int index) { if (index >= 0 && index < m_families->Length) { return InitializeElement(index); } else { throw gcnew IndexOutOfRangeException(); } } void FontFamilyCollection::default::set(int i, FontFamily^ feature) { throw gcnew NotSupportedException("This collection is readonly."); } void FontFamilyCollection::Add(FontFamily^ feature) { throw gcnew NotSupportedException("This collection is readonly."); } int FontFamilyCollection::Count::get() { return m_families->Length; } bool FontFamilyCollection::IsReadOnly::get() { return true; } System::Collections::Generic::IEnumerator<FontFamily^>^ FontFamilyCollection::GetGenericEnumerator() { return gcnew FontFamilyEnum(GetInterface<IDWriteFontCollection>(), this); } System::Collections::IEnumerator^ FontFamilyCollection::GetEnumerator() { throw gcnew NotImplementedException(); } int FontFamilyCollection::IndexOf(FontFamily^ item) { if (item == nullptr) { throw gcnew ArgumentNullException("item"); } for each (String^ value in item->FamilyNames->Values) { return this->IndexOf(value); } return false; } void FontFamilyCollection::Insert(int index, FontFamily^ item) { throw gcnew NotSupportedException("This collection is readonly."); } void FontFamilyCollection::RemoveAt(int index) { throw gcnew NotSupportedException("This collection is readonly."); } void FontFamilyCollection::Clear() { throw gcnew NotSupportedException("This collection is readonly."); } bool FontFamilyCollection::Contains(FontFamily^ item) { if (item == nullptr) { throw gcnew ArgumentNullException("item"); } for each (String^ value in item->FamilyNames->Values) { return this->Contains(value); } return false; } void FontFamilyCollection::CopyTo(array<FontFamily^>^, int arrayIndex) { throw gcnew NotSupportedException(); } bool FontFamilyCollection::Remove(FontFamily^ item) { throw gcnew NotSupportedException("This collection is readonly."); } bool FontFamilyCollection::Contains(String^ fontFamilyName) { if (String::IsNullOrEmpty(fontFamilyName)) { throw gcnew ArgumentNullException("fontFamilyName", "fontFamilyName cannot be null or empty."); } UINT32 index; BOOL exists; pin_ptr<const WCHAR> familyName = PtrToStringChars(fontFamilyName); CommonUtils::VerifyResult(GetInterface<IDWriteFontCollection>()->FindFamilyName(familyName, &index, &exists)); return exists ? true : false; } int FontFamilyCollection::IndexOf(String^ fontFamilyName) { if (String::IsNullOrEmpty(fontFamilyName)) { throw gcnew ArgumentNullException("fontFamilyName", "fontFamilyName cannot be null or empty."); } UINT32 index; BOOL exists; pin_ptr<const WCHAR> familyName = PtrToStringChars(fontFamilyName); CommonUtils::VerifyResult(GetInterface<IDWriteFontCollection>()->FindFamilyName(familyName, &index, &exists)); if (exists) { return index; } else { return -1; } } FontFamilyEnum::FontFamilyEnum(IDWriteFontCollection* pFontCollection, FontFamilyCollection^ familyCollection) : DirectUnknown(pFontCollection), m_current(-1), m_familyCollection(familyCollection) { GetInterface<IUnknown>()->AddRef(); } FontFamily^ FontFamilyEnum::Current::get() { return m_familyCollection[m_current]; } System::Object^ FontFamilyEnum::CurrentObject::get() { throw gcnew NotImplementedException(); } bool FontFamilyEnum::MoveNext() { if (m_current + 1 < static_cast<int>(m_familyCollection->Count)) { m_current++; return true; } return false; } void FontFamilyEnum::Reset() { m_current = -1; }
[ "lucemia@9e708c16-f4dd-11de-aa3c-59de0406b4f5" ]
[ [ [ 1, 218 ] ] ]
d0bb91c4eb015707128f7050636848b4c79f0dec
f8403b6b1005f80d2db7fad9ee208887cdca6aec
/JuceLibraryCode/modules/juce_graphics/contexts/juce_LowLevelGraphicsPostScriptRenderer.cpp
11c31deeec5591047b357415ce682bb5cc112ef7
[]
no_license
sonic59/JuceText
25544cb07e5b414f9d7109c0826a16fc1de2e0d4
5ac010ffe59c2025d25bc0f9c02fc829ada9a3d2
refs/heads/master
2021-01-15T13:18:11.670907
2011-10-29T19:03:25
2011-10-29T19:03:25
2,507,112
0
0
null
null
null
null
UTF-8
C++
false
false
17,351
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 // this will throw an assertion if you try to draw something that's not // possible in postscript #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0 //============================================================================== #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS #define notPossibleInPostscriptAssert jassertfalse #else #define notPossibleInPostscriptAssert #endif //============================================================================== LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript, const String& documentTitle, const int totalWidth_, const int totalHeight_) : out (resultingPostScript), totalWidth (totalWidth_), totalHeight (totalHeight_), needToClip (true) { stateStack.add (new SavedState()); stateStack.getLast()->clip = Rectangle<int> (totalWidth_, totalHeight_); const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight)); out << "%!PS-Adobe-3.0 EPSF-3.0" "\n%%BoundingBox: 0 0 600 824" "\n%%Pages: 0" "\n%%Creator: Raw Material Software JUCE" "\n%%Title: " << documentTitle << "\n%%CreationDate: none" "\n%%LanguageLevel: 2" "\n%%EndComments" "\n%%BeginProlog" "\n%%BeginResource: JRes" "\n/bd {bind def} bind def" "\n/c {setrgbcolor} bd" "\n/m {moveto} bd" "\n/l {lineto} bd" "\n/rl {rlineto} bd" "\n/ct {curveto} bd" "\n/cp {closepath} bd" "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd" "\n/doclip {initclip newpath} bd" "\n/endclip {clip newpath} bd" "\n%%EndResource" "\n%%EndProlog" "\n%%BeginSetup" "\n%%EndSetup" "\n%%Page: 1 1" "\n%%BeginPageSetup" "\n%%EndPageSetup\n\n" << "40 800 translate\n" << scale << ' ' << scale << " scale\n\n"; } LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer() { } //============================================================================== bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const { return true; } void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y) { if (x != 0 || y != 0) { stateStack.getLast()->xOffset += x; stateStack.getLast()->yOffset += y; needToClip = true; } } void LowLevelGraphicsPostScriptRenderer::addTransform (const AffineTransform& /*transform*/) { //xxx jassertfalse; } float LowLevelGraphicsPostScriptRenderer::getScaleFactor() { jassertfalse; //xxx return 1.0f; } bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r) { needToClip = true; return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset)); } bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion) { needToClip = true; return stateStack.getLast()->clip.clipTo (clipRegion); } void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r) { needToClip = true; stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset)); } void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform) { writeClip(); Path p (path); p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)); writePath (p); out << "clip\n"; } void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const AffineTransform& /*transform*/) { needToClip = true; jassertfalse; // xxx } bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r) { return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset)); } Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const { return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset, -stateStack.getLast()->yOffset); } bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const { return stateStack.getLast()->clip.isEmpty(); } //============================================================================== LowLevelGraphicsPostScriptRenderer::SavedState::SavedState() : xOffset (0), yOffset (0) { } LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState() { } void LowLevelGraphicsPostScriptRenderer::saveState() { stateStack.add (new SavedState (*stateStack.getLast())); } void LowLevelGraphicsPostScriptRenderer::restoreState() { jassert (stateStack.size() > 0); if (stateStack.size() > 0) stateStack.removeLast(); } void LowLevelGraphicsPostScriptRenderer::beginTransparencyLayer (float) { } void LowLevelGraphicsPostScriptRenderer::endTransparencyLayer() { } //============================================================================== void LowLevelGraphicsPostScriptRenderer::writeClip() { if (needToClip) { needToClip = false; out << "doclip "; int itemsOnLine = 0; for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();) { if (++itemsOnLine == 6) { itemsOnLine = 0; out << '\n'; } const Rectangle<int>& r = *i.getRectangle(); out << r.getX() << ' ' << -r.getY() << ' ' << r.getWidth() << ' ' << -r.getHeight() << " pr "; } out << "endclip\n"; } } void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour) { Colour c (Colours::white.overlaidWith (colour)); if (lastColour != c) { lastColour = c; out << String (c.getFloatRed(), 3) << ' ' << String (c.getFloatGreen(), 3) << ' ' << String (c.getFloatBlue(), 3) << " c\n"; } } void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const { out << String (x, 2) << ' ' << String (-y, 2) << ' '; } void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const { out << "newpath "; float lastX = 0.0f; float lastY = 0.0f; int itemsOnLine = 0; Path::Iterator i (path); while (i.next()) { if (++itemsOnLine == 4) { itemsOnLine = 0; out << '\n'; } switch (i.elementType) { case Path::Iterator::startNewSubPath: writeXY (i.x1, i.y1); lastX = i.x1; lastY = i.y1; out << "m "; break; case Path::Iterator::lineTo: writeXY (i.x1, i.y1); lastX = i.x1; lastY = i.y1; out << "l "; break; case Path::Iterator::quadraticTo: { const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f; const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f; const float cp2x = cp1x + (i.x2 - lastX) / 3.0f; const float cp2y = cp1y + (i.y2 - lastY) / 3.0f; writeXY (cp1x, cp1y); writeXY (cp2x, cp2y); writeXY (i.x2, i.y2); out << "ct "; lastX = i.x2; lastY = i.y2; } break; case Path::Iterator::cubicTo: writeXY (i.x1, i.y1); writeXY (i.x2, i.y2); writeXY (i.x3, i.y3); out << "ct "; lastX = i.x3; lastY = i.y3; break; case Path::Iterator::closePath: out << "cp "; break; default: jassertfalse; break; } } out << '\n'; } void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const { out << "[ " << trans.mat00 << ' ' << trans.mat10 << ' ' << trans.mat01 << ' ' << trans.mat11 << ' ' << trans.mat02 << ' ' << trans.mat12 << " ] concat "; } //============================================================================== void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType) { stateStack.getLast()->fillType = fillType; } void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/) { } void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/) { } //============================================================================== void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/) { if (stateStack.getLast()->fillType.isColour()) { writeClip(); writeColour (stateStack.getLast()->fillType.colour); Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset)); out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n"; } else { Path p; p.addRectangle (r); fillPath (p, AffineTransform::identity); } } //============================================================================== void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t) { if (stateStack.getLast()->fillType.isColour()) { writeClip(); Path p (path); p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)); writePath (p); writeColour (stateStack.getLast()->fillType.colour); out << "fill\n"; } else if (stateStack.getLast()->fillType.isGradient()) { // this doesn't work correctly yet - it could be improved to handle solid gradients, but // postscript can't do semi-transparent ones. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file writeClip(); out << "gsave "; { Path p (path); p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)); writePath (p); out << "clip\n"; } const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds()); // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the // time-being, this just fills it with the average colour.. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f)); out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n"; out << "grestore\n"; } } //============================================================================== void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im, const int sx, const int sy, const int maxW, const int maxH) const { out << "{<\n"; const int w = jmin (maxW, im.getWidth()); const int h = jmin (maxH, im.getHeight()); int charsOnLine = 0; const Image::BitmapData srcData (im, 0, 0, w, h); Colour pixel; for (int y = h; --y >= 0;) { for (int x = 0; x < w; ++x) { const uint8* pixelData = srcData.getPixelPointer (x, y); if (x >= sx && y >= sy) { if (im.isARGB()) { PixelARGB p (*(const PixelARGB*) pixelData); p.unpremultiply(); pixel = Colours::white.overlaidWith (Colour (p.getARGB())); } else if (im.isRGB()) { pixel = Colour (((const PixelRGB*) pixelData)->getARGB()); } else { pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData); } } else { pixel = Colours::transparentWhite; } const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() }; out << String::toHexString (pixelValues, 3, 0); charsOnLine += 3; if (charsOnLine > 100) { out << '\n'; charsOnLine = 0; } } } out << "\n>}\n"; } void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/) { const int w = sourceImage.getWidth(); const int h = sourceImage.getHeight(); writeClip(); out << "gsave "; writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset) .scaled (1.0f, -1.0f)); RectangleList imageClip; sourceImage.createSolidAreaMask (imageClip, 0.5f); out << "newpath "; int itemsOnLine = 0; for (RectangleList::Iterator i (imageClip); i.next();) { if (++itemsOnLine == 6) { out << '\n'; itemsOnLine = 0; } const Rectangle<int>& r = *i.getRectangle(); out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr "; } out << " clip newpath\n"; out << w << ' ' << h << " scale\n"; out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n"; writeImage (sourceImage, 0, 0, w, h); out << "false 3 colorimage grestore\n"; needToClip = true; } //============================================================================== void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line) { Path p; p.addLineSegment (line, 1.0f); fillPath (p, AffineTransform::identity); } void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom) { drawLine (Line<float> ((float) x, top, (float) x, bottom)); } void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right) { drawLine (Line<float> (left, (float) y, right, (float) y)); } //============================================================================== void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont) { stateStack.getLast()->font = newFont; } Font LowLevelGraphicsPostScriptRenderer::getFont() { return stateStack.getLast()->font; } void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform) { Path p; Font& font = stateStack.getLast()->font; font.getTypeface()->getOutlineForGlyph (glyphNumber, p); fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform)); } END_JUCE_NAMESPACE
[ [ [ 1, 546 ] ] ]
d6bea1f673063cd3bd84bdb03cca1c54d23cb104
fa134e5f64c51ccc1c2cac9b9cb0186036e41563
/GT/VerticalVelocityIndicator.h
771fb5c9651148eb7bffa838c2604d0fa7d68fc9
[]
no_license
dlsyaim/gradthes
70b626f08c5d64a1d19edc46d67637d9766437a6
db6ba305cca09f273e99febda4a8347816429700
refs/heads/master
2016-08-11T10:44:45.165199
2010-07-19T05:44:40
2010-07-19T05:44:40
36,058,688
0
1
null
null
null
null
UTF-8
C++
false
false
183
h
#pragma once #include "Instrument.h" class VerticalVelocityIndicator : public Instrument { public: VerticalVelocityIndicator(void); ~VerticalVelocityIndicator(void); };
[ "[email protected]@3a95c3f6-2b41-11df-be6c-f52728ce0ce6" ]
[ [ [ 1, 10 ] ] ]
bcd171850472f6c9370994f7a214b8a641813332
6114db1d18909e8d38365a81ab5f0b1221c6d479
/Sources/AsProfiled/Node.h
4f1228fa4e85e531312ff32c20f14372132aa94b
[]
no_license
bitmizone/asprofiled
c6bf81e89037b68d0a7c8a981be3cd9c8a4db7c7
b54cb47b1d3ee1ce6ad7077960394ddd5578c0ff
refs/heads/master
2021-01-10T14:14:42.048633
2011-06-21T11:38:26
2011-06-21T11:38:26
48,724,442
1
1
null
null
null
null
UTF-8
C++
false
false
376
h
#pragma once #include <vector> #include "Operator.h" enum NodeType { BaseNode, ParamNode }; class CNode { public: CNode(void); ~CNode(void); virtual NodeType GetType(); virtual std::wstring GetValue(); bool IsTerminal(); Operator::TokenTypeEnum tokenType; std::vector<CNode*>* children; bool result; std::wstring value; bool evaluated; };
[ "adamsonic@cf2cc628-70ab-11de-90d8-1fdda9445408" ]
[ [ [ 1, 22 ] ] ]
9525085f2b132495f888c290c7c99bd847008149
4797c7058b7157e3d942e82cf8ad94b58be488ae
/MyCamera.cpp
e4490200a39fff27235d50d86645d5b3a91bf3bd
[]
no_license
koguz/DirectX-Space-Game
2d1d8179439870fd1427beb9624f1c5452546c39
be672051fd0009cbd5851c92bd344d3b23645474
refs/heads/master
2020-05-18T02:11:47.963185
2011-05-25T14:35:26
2011-05-25T14:35:26
1,799,267
0
0
null
null
null
null
UTF-8
C++
false
false
1,053
cpp
/* MyCamera.cpp Kaya Oguz <0705907> */ #include "MyCamera.h" MyCamera::MyCamera() { Device = 0; position = D3DXVECTOR3(0.0f, 0.0f, 0.0f); look = D3DXVECTOR3(0.0f, 0.0f, 1000.0f); up = D3DXVECTOR3(0.0f, 1.0f, 0.0f); } MyCamera::MyCamera(IDirect3DDevice9 *d) { Device = d; position = D3DXVECTOR3(0.0f, 0.0f, 0.0f); look = D3DXVECTOR3(0.0f, 0.0f, 1.0f); up = D3DXVECTOR3(0.0f, 1.0f, 0.0f); } void MyCamera::Display() { D3DXMATRIX View; D3DXMatrixLookAtLH(&View, &position, &look, &up); Device->SetTransform(D3DTS_VIEW, &View); } void MyCamera::Update() { D3DXVECTOR3 desiredPosition = attachedObject->getPosition() - (2.4f*attachedObject->getLook()) + (1.2f*attachedObject->getUp()); D3DXVECTOR3 moveDirection = desiredPosition - position; FLOAT length = D3DXVec3Length(&moveDirection); FLOAT distanceToMove = length / 4; position += moveDirection * distanceToMove; up = attachedObject->getUp(); look = attachedObject->getPosition() + (attachedObject->getLook()*100); Display(); }
[ [ [ 1, 44 ] ] ]
68a070a60fa73c0e1109a754d1c314ac96261169
b5ad65ebe6a1148716115e1faab31b5f0de1b493
/src/AranGl/BasicObjects.cpp
26c1bf78d7070c01693e3edddb094483ff68737f
[]
no_license
gasbank/aran
4360e3536185dcc0b364d8de84b34ae3a5f0855c
01908cd36612379ade220cc09783bc7366c80961
refs/heads/master
2021-05-01T01:16:19.815088
2011-03-01T05:21:38
2011-03-01T05:21:38
1,051,010
1
0
null
null
null
null
UTF-8
C++
false
false
2,087
cpp
#include "AranGlPCH.h" #include "BasicObjects.h" static GLuint compileUnitBox() { GLuint listId = glGenLists(1); glNewList(listId, GL_COMPILE); glBegin(GL_QUADS); glNormal3f(0, 0, 1); glVertex3f( -0.5f, -0.5f, 0.5f); // Top glNormal3f(0, 0, 1); glVertex3f( 0.5f, -0.5f, 0.5f); // Top glNormal3f(0, 0, 1); glVertex3f( 0.5f, 0.5f, 0.5f); // Top glNormal3f(0, 0, 1); glVertex3f( -0.5f, 0.5f, 0.5f); // Top glNormal3f(0, 0, -1); glVertex3f( -0.5f, 0.5f, -0.5f); // Bottom glNormal3f(0, 0, -1); glVertex3f( 0.5f, 0.5f, -0.5f); // Bottom glNormal3f(0, 0, -1); glVertex3f( 0.5f, -0.5f, -0.5f); // Bottom glNormal3f(0, 0, -1); glVertex3f( -0.5f, -0.5f, -0.5f); // Bottom glNormal3f(0, -1, 0); glVertex3f( -0.5f, -0.5f, -0.5f); // Front glNormal3f(0, -1, 0); glVertex3f( 0.5f, -0.5f, -0.5f); // Front glNormal3f(0, -1, 0); glVertex3f( 0.5f, -0.5f, 0.5f); // Front glNormal3f(0, -1, 0); glVertex3f( -0.5f, -0.5f, 0.5f); // Front glNormal3f(0, 1, 0); glVertex3f( -0.5f, 0.5f, 0.5f); // Back glNormal3f(0, 1, 0); glVertex3f( 0.5f, 0.5f, 0.5f); // Back glNormal3f(0, 1, 0); glVertex3f( 0.5f, 0.5f, -0.5f); // Back glNormal3f(0, 1, 0); glVertex3f( -0.5f, 0.5f, -0.5f); // Back glNormal3f(-1, 0, 0); glVertex3f( -0.5f, -0.5f, -0.5f); // Left glNormal3f(-1, 0, 0); glVertex3f( -0.5f, 0.5f, -0.5f); // Left glNormal3f(-1, 0, 0); glVertex3f( -0.5f, 0.5f, 0.5f); // Left glNormal3f(-1, 0, 0); glVertex3f( -0.5f, -0.5f, 0.5f); // Left glNormal3f( 1, 0, 0); glVertex3f( 0.5f, -0.5f, -0.5f); // Right glNormal3f( 1, 0, 0); glVertex3f( 0.5f, 0.5f, -0.5f); // Right glNormal3f( 1, 0, 0); glVertex3f( 0.5f, 0.5f, 0.5f); // Right glNormal3f( 1, 0, 0); glVertex3f( 0.5f, -0.5f, 0.5f); // Right glEnd(); glEndList(); return listId; } void compileAllBasicObjects(BasicObjects* bo) { bo->unitBox = compileUnitBox(); }
[ [ [ 1, 52 ] ] ]
66c07a8a57b5106dbfc32d6143ff64bc4b71503b
8a47aa7c36fa2b9ea76cf2ef9fea8207d40a71a2
/devilheart/project_pin/library/xed2-ia32/examples/xed-enc-lang.cpp
dfb39d5acf2864718ff4f6819b4c1be2947ca710
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
iidx/devilheart
4eae52d7201149347d3f93fdf0202e2520313bf3
13a28efa9f9a37a133b52301642c7ebc264697d5
refs/heads/master
2021-01-10T10:17:58.686621
2010-03-16T03:16:18
2010-03-16T03:16:18
46,808,731
0
0
null
null
null
null
UTF-8
C++
false
false
22,485
cpp
/*BEGIN_LEGAL Intel Open Source License Copyright (c) 2002-2009 Intel 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 the Intel 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 THE INTEL OR ITS 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. END_LEGAL */ /// @file xed-enc-lang.cpp /// @author Mark Charney <[email protected]> // This is an example of how to use the encoder from scratch in the context // of parsing a string from the command line. #include <iostream> #include <iomanip> #include <vector> #include <sstream> #include <cassert> #include <cstring> #include <cstdlib> extern "C" { #include "xed-interface.h" #include "xed-portability.h" #include "xed-examples-util.h" } #include "xed-enc-lang.H" using namespace std; static char xed_enc_lang_toupper(char c) { if (c >= 'a' && c <= 'z') return c-'a'+'A'; return c; } static string upcase(string s) { string t = ""; xed_uint_t len = static_cast<xed_uint_t>(s.size()); xed_uint_t i; for(i=0 ; i < len ; i++ ) t = t + xed_enc_lang_toupper(s[i]); return t; } unsigned int xed_split_args(const string& sep, const string& input, vector<string>& output_array) { // returns the number of args // rip off the separator characters and split the src string based on separators. // find the string between last_pos and pos. pos is after last_pos string::size_type last_pos = input.find_first_not_of(sep, 0); string::size_type pos = input.find_first_of(sep, last_pos); if (CLIENT_VERBOSE3) printf("input %s\tlast_pos " XED_FMT_U " pos " XED_FMT_U "\n", input.c_str() , STATIC_CAST(xed_uint_t,last_pos), STATIC_CAST(xed_uint_t,pos)); int i=0; while( pos != string::npos && last_pos != string::npos ) { string a = input.substr(last_pos, pos-last_pos); output_array.push_back(a); if (CLIENT_VERBOSE3) printf("\t\tlast_pos " XED_FMT_U " pos " XED_FMT_U " i %d\n", STATIC_CAST(xed_uint_t,last_pos), STATIC_CAST(xed_uint_t,pos), i); last_pos = input.find_first_not_of(sep, pos); pos = input.find_first_of(sep, last_pos); i++; } if (last_pos != string::npos && pos == string::npos) { if (CLIENT_VERBOSE3) printf("\t\tGetting last substring at " XED_FMT_U "\n", STATIC_CAST(xed_uint_t,last_pos)); string a = input.substr(last_pos); // get the rest of the string output_array.push_back(a); i++; } if (CLIENT_VERBOSE3) printf("\t returning %d\n",i); return i; } vector<string> tokenize(const string& s, const string& delimiter) { vector<string> v; (void) xed_split_args(delimiter, s, v); return v; } void slash_split(const string& src, string& first, // output string& second) //output { string::size_type p = src.find("/"); if (p == string::npos) { first = src; second = ""; } else { first = src.substr(0,p); second = src.substr(p+1); } } class immed_parser_t { public: xed_bool_t valid; string immed; unsigned int width_bits; xed_uint64_t immed_val; string tok0; immed_parser_t(const string& s, const string& arg_tok0) //CONS : valid(false), tok0(arg_tok0) { vector<string> vs = tokenize(s,":"); if (vs.size() == 2) { if (vs[0] == tok0) { string immed_str = vs[1]; immed_val = convert_ascii_hex_to_int(immed_str.c_str()); width_bits = static_cast<unsigned int>(immed_str.size()*4); // nibbles to bits valid = true; } } } void print(ostream& o) const { o << tok0 << "(" ; if (valid) { // not printing immed_val directly because VC98 (MSVS6) cannot print uint64's xed_union64_t u; u.u64 = immed_val; o << std::hex; o << setfill('0'); o << std::setw(8); o << (int) u.s.hi32; o << std::setw(8); o << (int) u.s.lo32; o << setfill(' '); o << std::dec; } else o << "???"; o << ")"; } }; ostream& operator<<(ostream& o, const immed_parser_t& x) { x.print(o); return o; } class seg_parser_t { public: xed_bool_t valid; xed_reg_enum_t segment_reg; string segment; xed_uint_t segno; seg_parser_t(const string& s) // CONS : valid(false), segment_reg(XED_REG_INVALID), segno(0) { vector<string> vs = tokenize(s,":"); xed_uint_t ntokens = static_cast<xed_uint_t>(vs.size()); #if 0 cerr << "ntokens " << ntokens << ": " ; for(unsigned int i=0;i<ntokens;i++) cerr << '[' << vs[i] << "] "; cerr << endl; #endif if (ntokens == 2) { if (vs[0] == "SEG" || vs[0] == "SEG0") { segment = vs[1]; segno = 0; segment_reg = str2xed_reg_enum_t(segment.c_str()); if (segment_reg != XED_REG_INVALID && xed_reg_class(segment_reg) == XED_REG_CLASS_SR) { valid=true; } } if (vs[0] == "SEG1") { segment = vs[1]; segno = 1; segment_reg = str2xed_reg_enum_t(segment.c_str()); if (segment_reg != XED_REG_INVALID && xed_reg_class(segment_reg) == XED_REG_CLASS_SR) { valid=true; } } } } }; class mem_bis_parser_t { // parse: MEMlength:[segment:]base,index,scale[,displacement] // parse: AGEN:base,index,scale[,displacement] // The displacement is optional // split on colons first // MEM4:FS:EAX,EBX,4,223344 mem4 fs eax,ebx,4,22334455 -> 3 tokens // MEM4:FS:EAX,EBX,4 mem4 fs eax,ebx,4 -> 3 tokens // MEM4:EAX,EBX,4,223344 mem4 eax,ebx,4,223344.. -> 2 tokens // MEM4:FS:EAX,EBX,4 mem4 fs eas,ebx,4 -> 3 tokens public: xed_bool_t valid; xed_bool_t mem; xed_bool_t agen; xed_bool_t disp_valid; string segment; string base; string index; string scale; string disp; //displacement xed_reg_enum_t segment_reg; xed_reg_enum_t base_reg; xed_reg_enum_t index_reg; xed_uint8_t scale_val; xed_int64_t disp_val; unsigned int disp_width_bits; unsigned int mem_len; void print(ostream& o) const { if (agen) o << "AGEN"; if (mem) o << "MEM"; if (mem_len) o << setw(1) << mem_len; o << "("; if (segment_reg != XED_REG_INVALID) o << segment_reg << ":"; o << base_reg; o << "," << index_reg << "," << (unsigned int) scale_val; if (disp_valid) o << "," << disp; o << ")"; } mem_bis_parser_t(const string& s) //CONS : valid(false), mem(false), agen(false), disp_valid(false), base("INVALID"), index("INVALID"), scale("1"), segment_reg(XED_REG_INVALID), base_reg(XED_REG_INVALID), index_reg(XED_REG_INVALID), disp_val(0), disp_width_bits(0), mem_len(0) { string t = upcase(s); // split on colon first vector<string> vs = tokenize(t,":"); xed_uint_t ntokens = static_cast<xed_uint_t>(vs.size()); vector<string> astr; xed_uint_t n_addr_tokens; string main_token, addr_token; if (ntokens == 3) { /* has a segment base */ main_token = vs[0]; segment = vs[1]; addr_token = vs[2]; } else if (ntokens == 2) { main_token = vs[0]; segment = "INVALID"; addr_token = vs[1]; } else return; if (main_token == "AGEN") agen=true; else if (main_token.substr(0,3) == "MEM") { mem = true; if (main_token.size() > 3) { string len = main_token.substr(3); mem_len = strtol(len.c_str(),0,0); //printf("mem_len = " XED_FMT_U "\n", mem_len); } } else return; if (agen && segment != "INVALID") xedex_derror("AGENs cannot have segment overrides"); astr = tokenize(addr_token,","); n_addr_tokens = static_cast<xed_uint_t>(astr.size()); if (n_addr_tokens == 0 || n_addr_tokens > 4) xedex_derror("Bad addressing mode syntax for memop"); base = astr[0]; if (base == "-" || base == "NA") base = "INVALID"; if (n_addr_tokens > 2) index = astr[1]; if (index == "-" || index == "NA") index = "INVALID"; if (n_addr_tokens > 2) scale = astr[2]; if (scale == "-" || scale == "NA") scale = "1"; if (scale == "1" || scale == "2" || scale == "4" || scale == "8") { valid=true; scale_val = STATIC_CAST(xed_uint8_t,strtol(scale.c_str(), 0, 10)); segment_reg = str2xed_reg_enum_t(segment.c_str()); base_reg = str2xed_reg_enum_t(base.c_str()); index_reg = str2xed_reg_enum_t(index.c_str()); // look for a displacement if (n_addr_tokens == 4 && astr[3] != "-") { disp = astr[3]; disp_valid = true; unsigned int nibbles = STATIC_CAST(int,disp.size()); if (nibbles & 1) { // ensure an even number of nibbles string zero("0"); disp = zero + disp; nibbles++; } disp_val = convert_ascii_hex_to_int(disp.c_str()); disp_width_bits = nibbles*4; // nibbles to bits } } } }; ostream& operator<<(ostream& o, const mem_bis_parser_t& x) { x.print(o); return o; } xed_encoder_request_t parse_encode_request(ascii_encode_request_t& areq) { unsigned int i; xed_encoder_request_t req; xed_encoder_request_zero_set_mode(&req,&(areq.dstate)); // calls xed_encoder_request_zero() /* This is the important function here. This encodes an instruction from scratch. You must set: the machine mode (machine width, addressing widths) the iclass for some instructions you need to specify prefixes (like REP or LOCK). the operands: operand kind (XED_OPERAND_{AGEN,MEM0,MEM1,IMM0,IMM1,RELBR,PTR,REG0...REG15} operand order xed_encoder_request_set_operand_order(&req,operand_index, XED_OPERAND_*); where the operand_index is a sequential index starting at zero. operand details FOR MEMOPS: base,segment,index,scale,displacement for memops, FOR REGISTERS: register name FOR IMMEDIATES: immediate values */ vector<string> tokens = tokenize(areq.command," "); // first token has the operand and our temporary hack for the immediate string first, second; unsigned int token_index = 0; while(token_index < tokens.size()) { slash_split(tokens[token_index], first, second); if (CLIENT_VERBOSE3) printf( "[%s][%s][%s]\n", tokens[0].c_str(), first.c_str(), second.c_str()); if (token_index == 0 && first == "REP") { xed_encoder_request_set_rep(&req); token_index++; continue; } else if (token_index == 0 && first == "REPNE") { xed_encoder_request_set_repne(&req); token_index++; continue; } token_index++; break; } // we can attempt to override the mode if (second == "8") xed_encoder_request_set_effective_operand_width(&req, 8); else if (second == "16") xed_encoder_request_set_effective_operand_width(&req, 16); else if (second == "32") xed_encoder_request_set_effective_operand_width(&req, 32); else if (second == "64") xed_encoder_request_set_effective_operand_width(&req, 64); first = upcase(first); xed_iclass_enum_t iclass = str2xed_iclass_enum_t(first.c_str()); if (iclass == XED_ICLASS_INVALID) { ostringstream os; os << "Bad instruction name: " << first; xedex_derror(os.str().c_str()); } xed_encoder_request_set_iclass(&req, iclass ); xed_uint_t memop = 0; xed_uint_t regnum = 0; // put the operands in the request. Loop through tokens // (skip the opcode iclass, handled above) xed_uint_t operand_index = 0; for( i=token_index; i < tokens.size(); i++, operand_index++ ) { string str_res_reg, second_x; slash_split(tokens[i], str_res_reg, second_x); str_res_reg = upcase(str_res_reg); // prune the AGEN or MEM(base,index,scale[,displacement]) text from str_res_reg // FIXME: add MEM(immed) for the OC1_A and OC1_O types???? mem_bis_parser_t mem_bis(str_res_reg); if (mem_bis.valid) { if (mem_bis.mem) { if (memop == 0) { // Tell XED that we have a memory operand xed_encoder_request_set_mem0(&req); // Tell XED that the mem0 operand is the next operand: xed_encoder_request_set_operand_order(&req,operand_index, XED_OPERAND_MEM0); } else { xed_encoder_request_set_mem1(&req); // Tell XED that the mem1 operand is the next operand: xed_encoder_request_set_operand_order(&req,operand_index, XED_OPERAND_MEM1); } memop++; } else if (mem_bis.agen) { // Tell XED we have an AGEN xed_encoder_request_set_agen(&req); // The AGEN is the next operand xed_encoder_request_set_operand_order(&req,operand_index, XED_OPERAND_AGEN); } else assert(mem_bis.agen || mem_bis.mem); xed_reg_class_enum_t rc = xed_gpr_reg_class(mem_bis.base_reg); xed_reg_class_enum_t rci = xed_gpr_reg_class(mem_bis.index_reg); if (mem_bis.base_reg != XED_REG_INVALID && mem_bis.index_reg != XED_REG_INVALID) if (rc != rci) { ostringstream os; os << "The base and index regs do not agree on the address size" << endl; xedex_derror(os.str().c_str()); // dies } if (rc == XED_REG_CLASS_GPR32 || rci == XED_REG_CLASS_GPR32) xed_encoder_request_set_effective_address_size(&req, 32); if (rc == XED_REG_CLASS_GPR16 || rci == XED_REG_CLASS_GPR16) xed_encoder_request_set_effective_address_size(&req, 16); // fill in the memory fields xed_encoder_request_set_base0(&req, mem_bis.base_reg); xed_encoder_request_set_index(&req, mem_bis.index_reg); xed_encoder_request_set_scale(&req, mem_bis.scale_val); xed_encoder_request_set_seg0(&req, mem_bis.segment_reg); if (mem_bis.mem_len) xed_encoder_request_set_memory_operand_length(&req, mem_bis.mem_len ); // BYTES if (mem_bis.disp_valid) xed_encoder_request_set_memory_displacement(&req, mem_bis.disp_val, mem_bis.disp_width_bits/8); continue; } seg_parser_t seg_parser(str_res_reg); if (seg_parser.valid) { if (CLIENT_VERBOSE3) printf("Setting segment to %s\n", xed_reg_enum_t2str(seg_parser.segment_reg)); if (seg_parser.segno == 0) xed_encoder_request_set_seg0(&req, seg_parser.segment_reg); else /* need SEG1 for MOVS[BWDQ]*/ xed_encoder_request_set_seg1(&req, seg_parser.segment_reg); /* SEG/SEG0/SEG1 is NOT a normal operand. It is a setting, like * the lock prefix. Normally the segment will be specified with * normal memory operations. With memops without MODRM, or * impliclit memops, we need a way of specifying the segment * when it is not the default. This is the way. it does not * change encoding forms. (When segments are "moved", they are * REG operands, not SEG0/1, and are specified by name like EAX * is.) */ continue; } immed_parser_t imm(str_res_reg, "IMM"); if (imm.valid) { if (CLIENT_VERBOSE3) printf("Setting immediate value to " XED_FMT_LX "\n", imm.immed_val); xed_encoder_request_set_uimm0_bits(&req, imm.immed_val, imm.width_bits); xed_encoder_request_set_operand_order(&req,operand_index, XED_OPERAND_IMM0); continue; } immed_parser_t simm(str_res_reg, "SIMM"); if (simm.valid) { if (CLIENT_VERBOSE3) printf("Setting immediate value to " XED_FMT_LX "\n", simm.immed_val); xed_encoder_request_set_simm(&req, STATIC_CAST(xed_int32_t,simm.immed_val), simm.width_bits/8); //FIXME xed_encoder_request_set_operand_order(&req,operand_index, XED_OPERAND_IMM0); continue; } immed_parser_t imm2(str_res_reg, "IMM2"); if (imm2.valid) { if (imm2.width_bits != 8) xedex_derror("2nd immediate must be just 1 byte long"); xed_encoder_request_set_uimm1(&req, imm2.immed_val); xed_encoder_request_set_operand_order(&req,operand_index, XED_OPERAND_IMM1); continue; } immed_parser_t disp(str_res_reg, "BRDISP"); if (disp.valid) { if (CLIENT_VERBOSE3) printf("Setting displacement value to " XED_FMT_LX "\n", disp.immed_val); xed_encoder_request_set_branch_displacement(&req, STATIC_CAST(xed_uint32_t,disp.immed_val), disp.width_bits/8); //FIXME xed_encoder_request_set_operand_order(&req,operand_index, XED_OPERAND_RELBR); xed_encoder_request_set_relbr(&req); continue; } immed_parser_t ptr_disp(str_res_reg, "PTR"); if (ptr_disp.valid) { if (CLIENT_VERBOSE3) printf("Setting pointer displacement value to " XED_FMT_LX "\n", ptr_disp.immed_val); xed_encoder_request_set_branch_displacement(&req, STATIC_CAST(xed_uint32_t,ptr_disp.immed_val), ptr_disp.width_bits/8); //FIXME xed_encoder_request_set_operand_order(&req,operand_index, XED_OPERAND_PTR); xed_encoder_request_set_ptr(&req); continue; } xed_reg_enum_t reg = str2xed_reg_enum_t(str_res_reg.c_str()); if (reg == XED_REG_INVALID) { ostringstream os; os << "Bad register name: " << str_res_reg << " on operand " << i; xedex_derror(os.str().c_str()); // dies } // The registers operands aer numbered starting from the first one // as XED_OPERAND_REG0. We incremenet regnum (below) every time we add a // register operands. xed_operand_enum_t r = STATIC_CAST(xed_operand_enum_t,XED_OPERAND_REG0 + regnum); // store the register identifer in the operand storage field xed_encoder_request_set_reg(&req, r, reg); // store the operand storage field name in the encode-order array xed_encoder_request_set_operand_order(&req, operand_index, r); regnum++; } // for loop return req; }
[ "hsqfire@86a7f5e6-5eca-11de-8a4b-256bef446c6c" ]
[ [ [ 1, 616 ] ] ]
f7bb9aa9ed6c62fc39c6fd86337ce41f5308ad9d
bda7b365b5952dc48827a8e8d33d11abd458c5eb
/Runnable_PS3/tile.cpp
cb8e3ecdcf54f4af144421820a618253dd7fb2f4
[]
no_license
MrColdbird/gameservice
3bc4dc3906d16713050612c1890aa8820d90272e
009d28334bdd8f808914086e8367b1eb9497c56a
refs/heads/master
2021-01-25T09:59:24.143855
2011-01-31T07:12:24
2011-01-31T07:12:24
35,889,912
3
3
null
null
null
null
UTF-8
C++
false
false
2,765
cpp
/* SCE CONFIDENTIAL * PlayStation(R)3 Programmer Tool Runtime Library 330.001 * Copyright (C) 2009 Sony Computer Entertainment Inc. * All Rights Reserved. */ #define __CELL_ASSERT__ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> // libgcm #include <cell/gcm.h> #include <sysutil/sysutil_sysparam.h> // gcmutil #include "gcmutil.h" using namespace CellGcmUtil; using namespace cell::Gcm; namespace CellGcmUtil{ /* typedef struct CellGcmTileInfo{ uint32_t tile; = (location + 1) | (bank<<4) | ((offset/0x10000)<<16) | (location<<31); uint32_t limit; = (((offset+size-1)/0x10000)<<16) | (location<<31); uint32_t pitch; = (pitch/0x100)<<8; uint32_t format; = base | ((base + (size-1)/0x10000)<<13) | (comp<<26) | (1<<30); }CellGcmTileInfo; */ int cellGcmUtilUnpackTileInfo(int index, const CellGcmTileInfo *raw_tile_info, CellGcmUtilUnpackedTileInfo *outTileInfo) { assert(index < CELL_GCM_MAX_TILE_INDEX); assert(index >= 0); if(index < 0 || index >= CELL_GCM_MAX_TILE_INDEX) return CELL_GCM_ERROR_INVALID_VALUE; assert(raw_tile_info != 0); if(raw_tile_info == 0) return CELL_GCM_ERROR_INVALID_VALUE; assert(outTileInfo != 0); if(outTileInfo == 0) return CELL_GCM_ERROR_INVALID_VALUE; const uint32_t FORMAT_BASE_TAG_MASK = 0x00001FFF; const uint32_t FORMAT_LIMIT_TAG_MASK = 0x03FFE000; const uint32_t FORMAT_COMP_TAG_MASK = 0x3C000000; const uint32_t FORMAT_BASE_TAG_RSHIFT = 0; const uint32_t FORMAT_LIMIT_TAG_RSHIFT = 13; const uint32_t FORMAT_COMP_TAG_RSHIFT = 26; const uint32_t PITCH_PITCH_MASK = 0xFFFFFF00; const uint32_t TILE_BANK_MASK = 0x0000FFF0; const uint32_t TILE_BANK_RSHIFT = 4; const uint32_t TILE_REGION_MASK = 0x00000003; const uint32_t TILE_OFFSET_MASK = 0x7FFF0000; const uint32_t LIMIT_LIMIT_MASK = 0x7FFF0000; const CellGcmTileInfo *tile_info = raw_tile_info + index; uint32_t region = tile_info->tile & TILE_REGION_MASK; outTileInfo->enabled = (region != 0); outTileInfo->location = region - 1; outTileInfo->offset = (tile_info->tile & TILE_OFFSET_MASK); uint32_t limit = (tile_info->limit & LIMIT_LIMIT_MASK); outTileInfo->size = (limit - outTileInfo->offset) + 0x00010000; outTileInfo->pitch = tile_info->pitch & PITCH_PITCH_MASK; outTileInfo->comp = (tile_info->format & FORMAT_COMP_TAG_MASK) >> FORMAT_COMP_TAG_RSHIFT; outTileInfo->base = (tile_info->format & FORMAT_BASE_TAG_MASK ) >> FORMAT_BASE_TAG_RSHIFT; outTileInfo->limit = (tile_info->format & FORMAT_LIMIT_TAG_MASK) >> FORMAT_LIMIT_TAG_RSHIFT; outTileInfo->bank = (tile_info->tile & TILE_BANK_MASK ) >> TILE_BANK_RSHIFT; return CELL_OK; } } // namespace CellGcmUtil
[ "leavesmaple@383b229b-c81f-2bc2-fa3f-61d2d0c0fe69" ]
[ [ [ 1, 88 ] ] ]
ccbae94271a7f6980d08ee49d6aab5b1b1cb82b0
0bb573926a584973e63de0ea6ecfa627fcc54710
/Head_Tracking/main.cpp
3639b4b70d38d69ed058692481461ce960a3f994
[]
no_license
hadgiske/kinect-head-tracking
19157f9c3247e90f76975099b06a459642d5af7d
a9d0a76dc9274728e8404f91a4c91232065b7269
refs/heads/master
2021-01-20T02:15:24.608847
2011-01-07T01:31:27
2011-01-07T01:31:27
32,096,537
2
0
null
null
null
null
ISO-8859-3
C++
false
false
12,081
cpp
// Allgemein #include <iostream> #include <stdlib.h> #include <string> // Glut #include <GL/glut.h> // OpenNI #include <XnCppWrapper.h> #include <fstream> #include <cmath> #include "textures.h" using namespace std; /* Defines */ #define WINDOW_SIZE_X 1024 #define WINDOW_SIZE_Y 768 //#define DEBUGOUT //#define CONSOLEOUT #define ROOM_X 800 #define ROOM_Y 600 #define ROOM_Z 1000 /* Structs */ struct HeadTransformation { int x; int y; int z; double rotmat[16]; } headtrans = { 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; struct Mouse { int fx; /* First click position */ int fy; int cx; /* Current position */ int cy; int ox; /* Last click position */ int oy; bool left; bool right; } mouse = { 0, 0, 0, 0, 0, 0, false, false }; class WorldPos { public: WorldPos(float xk, float yk, float zk) { x = xk; y = yk; z = zk; offset_x = 0; offset_y = 0; offset_z = 0; } WorldPos(){ x = 0; y = 0; z = 0; offset_x = 0; offset_y = 0; offset_z = 0; } float x; float y; float z; WorldPos operator-(WorldPos first){ WorldPos retval; retval.x = x - first.x; retval.y = y - first.y; retval.z = z - first.z; return retval; } private: float offset_x, offset_y, offset_z; }; WorldPos wpos[4]; void init_wpos(){ wpos[0].x = -ROOM_X/2; wpos[0].y = -ROOM_Y/2; wpos[0].z = -ROOM_Z/2; wpos[1].x = +ROOM_X/2; wpos[1].y = -ROOM_Y/2; wpos[1].z = -ROOM_Z/2; wpos[2].x = +ROOM_X/2; wpos[2].y = +ROOM_Y/2; wpos[2].z = -ROOM_Z/2; wpos[3].x = -ROOM_X/2; wpos[3].y = +ROOM_Y/2; wpos[3].z = -ROOM_Z/2; } WorldPos getNormal(WorldPos first, WorldPos second){ WorldPos retval; retval.x = first.y*second.z - first.z*second.y; retval.y = -(first.x*second.z - first.z*second.x); retval.z = first.x*second.y - first.y*second.x; return retval; } /* Globals */ static int win; xn::Context context; xn::DepthGenerator depth; xn::ImageGenerator image; xn::UserGenerator user; XnStatus nRetVal; GLuint texture_rgb, texture_depth, texture_quads; GLubyte aDepthMap[640*480]; bool printFile = false; bool calibration = false; int maxdepth=-1; float light_lin = 0.0030; float light_quad = 0.002; float scalex=0.9, scaley=0.9, transx=41, transy=35; bool checkError(string message, XnStatus nRetVal) { if(nRetVal != XN_STATUS_OK) { cout << message << ": " << xnGetStatusString(nRetVal) << endl; return false; } return true; } void clearScreen() { #if defined(WIN32) system("cls"); #endif #if defined(LINUX) system("clear"); #endif } void glut_mouse_motion(int x, int y) { if(mouse.left) { mouse.cx = x-mouse.fx+mouse.ox; mouse.cy = mouse.fy-y+mouse.oy; } } void glut_keyboard(unsigned char key, int x, int y) { switch(key) { case 'q': scalex-=0.01; break; case 'a': scalex+=0.01; break; case 'w': scaley-=0.01; break; case 's': scaley+=0.01; break; case 'e': transx++; break; case 'd': transx--; break; case 'r': transy++; break; case 'f': transy--; break; case 'p': printFile = true; break; case 'c': calibration = true; break; case '1': light_lin += 0.0001; glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, light_lin); break; case '!': light_lin -= 0.0001; glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, light_lin); break; case '2': light_quad += 0.0001; glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, light_quad); break; case '\"': light_quad -= 0.0001; glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, light_quad); break; } cout << "Scale X: " << scalex << "\tScale Y: " << scaley << "\tTrans X: " << transx << "\tTrans Y: " << transy << endl << "Light_lin: " << light_lin << " \tLight_quad: " << light_quad << endl; } void glut_mouse(int button, int state, int x, int y) { if(button==GLUT_LEFT_BUTTON) { if(state==GLUT_DOWN) { mouse.left = true; mouse.fx = x; mouse.fy = y; } else { mouse.left = false; mouse.ox = mouse.cx; mouse.oy = mouse.cy; } } } void glut_idle() { glutPostRedisplay(); } int getMaxDepth(const XnDepthPixel* depthmap, int size=640*480) { int max_tmp=0; for(int i=0; i<size; i++) { if(depthmap[i]>max_tmp) max_tmp=depthmap[i]; } return max_tmp; } bool isCalStart=false; bool isCalEnd=false; void _stdcall skel_cal_start(xn::SkeletonCapability& skeleton, XnUserID user, void* pCookie) { if(isCalStart==false) { cout << "Pose wurde erkannt! Bitte warten, Kalibration wird durchgefuehrt!" << endl; isCalStart=true; } isCalEnd=false; } void _stdcall skel_cal_end(xn::SkeletonCapability& skeleton, XnUserID user, XnBool bSuccess, void* pCookie) { if(isCalEnd==false) { cout << "Kalibration abgeschlossen!" << endl; isCalEnd=true; } isCalStart=false; } void draw_room() { glBegin(GL_QUADS); glColor3f(1,1,1); glBindTexture(GL_TEXTURE_2D, texture_rgb); //Rückwand zeichen //Normale berechnen WorldPos normal = getNormal(wpos[1]-wpos[0],wpos[3]-wpos[0]); glNormal3f(normal.x,normal.y,normal.z); glTexCoord2f(0, 0);glVertex3f( wpos[0].x,wpos[0].y,wpos[0].z); glTexCoord2f(6, 0);glVertex3f( wpos[1].x,wpos[1].y,wpos[1].z); glTexCoord2f(6, 6);glVertex3f( wpos[2].x,wpos[2].y,wpos[2].z); glTexCoord2f(0, 6);glVertex3f( wpos[3].x,wpos[3].y,wpos[3].z); glEnd(); glColor3f(1,1,1); glBegin(GL_QUADS); //Boden zeichen normal = getNormal(wpos[0]-wpos[1],WorldPos(ROOM_X/2,-ROOM_Y/2,ROOM_Z/2)-wpos[1]); glNormal3f(normal.x,normal.y,normal.z); glTexCoord2f(0, 0);glVertex3f(-ROOM_X/2,-ROOM_Y/2,ROOM_Z/2); glTexCoord2f(6, 0);glVertex3f( ROOM_X/2,-ROOM_Y/2,ROOM_Z/2); glTexCoord2f(6, 6);glVertex3f(wpos[1].x,wpos[1].y,wpos[1].z); glTexCoord2f(0, 6);glVertex3f(wpos[0].x,wpos[0].y,wpos[0].z); glEnd(); glBegin(GL_QUADS); glColor3f(1,1,1); //Rechte Wand zeichnen normal = getNormal(WorldPos(ROOM_X/2, -ROOM_Y/2, ROOM_Z/2)-wpos[1], wpos[2]-wpos[1]); glNormal3f(normal.x,normal.y,normal.z); glTexCoord2f(0, 0);glVertex3f(ROOM_X/2,-ROOM_Y/2,ROOM_Z/2); glTexCoord2f(6, 0);glVertex3f(ROOM_X/2, ROOM_Y/2,ROOM_Z/2); glTexCoord2f(6, 6);glVertex3f(wpos[2].x, wpos[2].y,wpos[2].z); glTexCoord2f(0, 6);glVertex3f(wpos[1].x,wpos[1].y,wpos[1].z); glEnd(); glBegin(GL_QUADS); glColor3f(1,1,1); //Linke Wand normal = getNormal(wpos[3]-wpos[0], WorldPos(-ROOM_X/2,-ROOM_Y/2,ROOM_Z/2)-wpos[0]); glNormal3f(normal.x,normal.y,normal.z); glTexCoord2f(0, 0);glVertex3f(-ROOM_X/2,-ROOM_Y/2,ROOM_Z/2); glTexCoord2f(6, 0);glVertex3f( wpos[0].x,wpos[0].y,wpos[0].z); glTexCoord2f(6, 6);glVertex3f( wpos[3].x,wpos[3].y,wpos[3].z); glTexCoord2f(0, 6);glVertex3f(-ROOM_X/2, ROOM_Y/2,ROOM_Z/2); glEnd(); glBegin(GL_QUADS); glColor3f(1,1,1); //Decke normal = getNormal(WorldPos(ROOM_X/2, ROOM_Y/2, ROOM_Z/2)-wpos[2], wpos[3]-wpos[2]); glNormal3f(normal.x,normal.y,normal.z); glTexCoord2f(0, 0);glVertex3f(-ROOM_X/2,ROOM_Y/2,ROOM_Z/2); glTexCoord2f(6, 0);glVertex3f(wpos[3].x,wpos[3].y,wpos[3].z); glTexCoord2f(6, 6);glVertex3f( wpos[2].x,wpos[2].y,wpos[2].z); glTexCoord2f(0, 6);glVertex3f( ROOM_X/2,ROOM_Y/2,ROOM_Z/2); glEnd(); //glRotatef(mouse.cx,0,1,0); //glRotatef(-mouse.cy,1,0,0); glTranslatef(0,0,300); glPushMatrix(); glTranslatef(30,0,-130); glutSolidCube(80); glPopMatrix(); glutSolidCube(80); } float rot_angle=0; XnUInt16 pUserOld=0; void glut_display() { xn::DepthMetaData pDepthMapMD; xn::ImageMetaData pImageMapMD; XnUserID pUser[2]; XnUInt16 nUsers=2; #ifdef DEBUGOUT ofstream datei; #endif glEnable(GL_TEXTURE_2D); pUser[0] = 0; pUser[1] = 0; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); /*glFrustum( -ROOM_X/2+(1500.0/1750.0)*static_cast<int>(headtrans.x), ROOM_X/2+(1500.0/1750.0)*static_cast<int>(headtrans.x), -ROOM_Y/2-(1500.0/1750.0)*static_cast<int>(headtrans.y), ROOM_Y/2-(1500.0/1750.0)*static_cast<int>(headtrans.y), 1525, 2525);*/ float nearplane = 1525; float screenaspect = ROOM_X/ROOM_Y; glFrustum( nearplane*(-0.5 * screenaspect + headtrans.x)/headtrans.z, nearplane*( 0.5 * screenaspect + headtrans.x)/headtrans.z, nearplane*(-0.5 + headtrans.y)/headtrans.z, nearplane*( 0.5 + headtrans.y)/headtrans.z, nearplane, 2525); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); nRetVal = context.WaitAndUpdateAll(); checkError("Fehler beim Aktualisieren der Daten", nRetVal); /* Anzahl der User auslesen und in Objekten speichern */ user.GetUsers(pUser, nUsers); if(pUser[0]!=0 && pUserOld!=1) { cout << "User 1 erkannt" << endl; pUserOld=1; } xn::SkeletonCapability pSkeleton = user.GetSkeletonCap(); XnCallbackHandle hnd; pSkeleton.RegisterCalibrationCallbacks(skel_cal_start, skel_cal_end, 0,hnd); if(calibration){ } pSkeleton.SetSkeletonProfile(XN_SKEL_PROFILE_ALL); if(pSkeleton.IsCalibrated(pUser[0])) { XnSkeletonJointTransformation head; pSkeleton.StartTracking(pUser[0]); pSkeleton.GetSkeletonJoint(pUser[0], XN_SKEL_HEAD, head); if(head.position.fConfidence && head.orientation.fConfidence) { /* headtrans.rotmat[0] = head.orientation.orientation.elements[0]; headtrans.rotmat[1] = head.orientation.orientation.elements[1]; headtrans.rotmat[2] = head.orientation.orientation.elements[2]; headtrans.rotmat[3] = 0; headtrans.rotmat[4] = head.orientation.orientation.elements[3]; headtrans.rotmat[5] = head.orientation.orientation.elements[4]; headtrans.rotmat[6] = head.orientation.orientation.elements[5]; headtrans.rotmat[7] = 0; headtrans.rotmat[8] = -head.orientation.orientation.elements[6]; headtrans.rotmat[9] = -head.orientation.orientation.elements[7]; headtrans.rotmat[10] =-head.orientation.orientation.elements[8]; headtrans.rotmat[11] = 0; headtrans.rotmat[12] = 0; headtrans.rotmat[13] = 0; headtrans.rotmat[14] = 0; headtrans.rotmat[15] = 1;*/ headtrans.x = head.position.position.X; headtrans.y = head.position.position.Y; headtrans.z = head.position.position.Z; #ifdef CONSOLEOUT clearScreen(); cout << "Confidence Position: " << head.position.fConfidence << " X: " << head.position.position.X << " Y: " << head.position.position.Y << " Z: " << head.position.position.Z << endl << "Confidence Rotation: " << head.orientation.fConfidence << endl << "\t" << headtrans.rotmat[0] << "\t" << headtrans.rotmat[4] << "\t" << headtrans.rotmat[8] << endl << "\t" << headtrans.rotmat[1] << "\t" << headtrans.rotmat[5] << "\t" << headtrans.rotmat[9] << endl << "\t" << headtrans.rotmat[2] << "\t" << headtrans.rotmat[6] << "\t" << headtrans.rotmat[10] << endl << endl; #endif } } //------------------------------------------------------------------------------------------ //BEGIN: Kamera-Test //------------------------------------------------------------------------------------------ //glTranslatef(0,0,-2000); glTranslatef(headtrans.x,headtrans.y,1-headtrans.z); cout << headtrans.x << " " << headtrans.y << " " << headtrans.z << endl; cout << nearplane*(-0.5 * screenaspect + headtrans.x)/headtrans.z << " " << nearplane*( 0.5 * screenaspect + headtrans.x)/headtrans.z << " " << nearplane*(-0.5 + headtrans.y)/headtrans.z << " " << nearplane*( 0.5 + headtrans.y)/headtrans.z << " " << endl; draw_room(); //glPushAttrib(GL_ALL_ATTRIB_BITS); //glutSolidCube(5); //glPopAttrib(); //------------------------------------------------------------------------------------------ glDisable(GL_TEXTURE_2D); glutSwapBuffers(); #ifdef DEBUGOUT if(printFile) { printFile=false; datei.close(); } #endif } int main(int argc, char **argv) { return 0; }
[ "Sp3ssi@17e18ffd-2d5c-bf65-2f45-b884abe9fe7f" ]
[ [ [ 1, 478 ] ] ]
76d707f071b97668c0f5ec8cb3c6cbbe4b726ee3
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/CPP/Targets/WayFinder/symbian-r6/EditFavoriteView.h
84615af839cc5d179bc80bf5b7e66b75e8c1d266
[ "BSD-3-Clause" ]
permissive
ravustaja/Wayfinder-S60-Navigator
ef506c418b8c2e6498ece6dcae67e583fb8a4a95
14d1b729b2cea52f726874687e78f17492949585
refs/heads/master
2021-01-16T20:53:37.630909
2010-06-28T09:51:10
2010-06-28T09:51:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,466
h
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef EDIT_FAVORITE_VIEW_H #define EDIT_FAVORITE_VIEW_H #include <aknview.h> #include "WayFinderConstants.h" #include "ViewBase.h" namespace isab { class Favorite; } /** * */ class CEditFavoriteView : public CViewBase { public: /** * Symbian two-phase constructor. * This creates an instance then calls the second-phase constructor * without leaving the instance on the cleanup stack. * @return new instance of CEditFavoriteView */ static CEditFavoriteView* NewL(class CWayFinderAppUi* aAppUi); /** * Symbian two-phase constructor. * This creates an instance, pushes it on the cleanup stack, * then calls the second-phase constructor. * @return new instance of CEditFavoriteView */ static CEditFavoriteView* NewLC(class CWayFinderAppUi* aAppUi); /** * The view's destructor removes the container from the control * stack and destroys it. */ virtual ~CEditFavoriteView(); protected: /** * First phase of Symbian two-phase construction. Should not contain any * code that could leave. */ CEditFavoriteView(class CWayFinderAppUi* aAppUi); private: /** * Second-phase constructor for view. * Initialize contents from resource. */ void ConstructL(); public: /** * @return The UID for this view */ TUid Id() const; /** * Handle a command for this view (override). * @param aCommand Command id to be handled */ void HandleCommandL( TInt aCommand ); protected: /** * Handles user actions during activation of the view, * such as initializing the content. */ void DoActivateL(const TVwsViewId& aPrevViewId, TUid aCustomMessageId, const TDesC8& aCustomMessage); /** * Handles user de-activation of the view. */ void DoDeactivate(); public: /** * */ void SetFavoriteDataL(class Favorite* aFav); /** * */ TBool WaitingForFavoriteReply(); /** * */ void FavoriteReplyGot(); /** * */ void ShowConfirmationDialogL(); /** * Returns true if the guiFavorite is a wayfinder favorite. */ static TBool IsWayfinderFavorite(isab::GuiFavorite* aFav); /** * Returns true if the Favorite is a wayfinder favorite. */ static TBool IsWayfinderFavorite(isab::Favorite* aFav); private: /** * */ void UpdateFavoriteL(); /** * */ void AddFavoriteL(); private: /// The edit favorite (form) container class CEditFavoriteContainer* iContainer; /// Local copy of the favorite to be edited. class isab::Favorite* iFav; /// Flag to know if we have sent a change/add favorite mess to Nav2. TBool iWaitingForFavoriteReply; }; #endif // EDIT_FAVORITE_VIEW_H
[ [ [ 1, 147 ] ] ]
ca94f3a42bf279410597e8cc1232b9c9064aa0a4
3daaefb69e57941b3dee2a616f62121a3939455a
/mgllib-test/af2-test/tutorial/tutorial_7.cpp
27d295dce2fa919d418afe697aeb8424f52f0109
[]
no_license
myun2ext/open-mgl-legacy
21ccadab8b1569af8fc7e58cf494aaaceee32f1e
8faf07bad37a742f7174b454700066d53a384eae
refs/heads/master
2016-09-06T11:41:14.108963
2009-12-28T12:06:58
2009-12-28T12:06:58
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
739
cpp
#include "mglaugust2.h" class CMyFrame : public CAugustWindowFrame2 { private: CAugustText2 m_text; CAugustText2 m_text2; public: // 初期化時に呼ばれる bool OnGraphicInitEnded() { RegistControl(&m_text); RegistControl(&m_text2); m_text.SetText("これはテストなりー。"); m_text2.SetText("デカい文字なりー"); m_text2.SetFontSize(60); m_text2.SetPos(0,20); m_text2.SetColor(AGHCOLOR_RGB(40,100,200)); return true; } }; // WinMain int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { CMyFrame frame; frame.Start(); return 0; }
[ "myun2@6d62ff88-fa28-0410-b5a4-834eb811a934" ]
[ [ [ 1, 36 ] ] ]
cfe79152674282cdf08613acdec2eca7f0ec2b22
b5ad65ebe6a1148716115e1faab31b5f0de1b493
/src/ExampleParser/ExampleParser.cpp
cff3f9f004bec715f3f978847c0824aedf197fbe
[]
no_license
gasbank/aran
4360e3536185dcc0b364d8de84b34ae3a5f0855c
01908cd36612379ade220cc09783bc7366c80961
refs/heads/master
2021-05-01T01:16:19.815088
2011-03-01T05:21:38
2011-03-01T05:21:38
1,051,010
1
0
null
null
null
null
UTF-8
C++
false
false
2,174
cpp
// ExampleParser.cpp : Defines the entry point for the console application. // #include "stdafx.h" static void Cleanup() { ArnCleanupXmlParser(); ArnCleanupImageLibrary(); ArnCleanupPhysics(); } int main(int argc, const char* argv[]) { if (argc != 2) { printf("Please provide the input XML file name as the first argument.\n"); return -2; } const char *fileName = argv[1]; if (ArnInitializeXmlParser() < 0) { Cleanup(); return -1; } if (ArnInitializeImageLibrary() < 0) { Cleanup(); return -2; } if (ArnInitializePhysics() < 0) { Cleanup(); return -3; } ArnSceneGraph *sg = ArnSceneGraph::createFrom(fileName); if (!sg) { fprintf(stderr, " *** Scene graph file is not loaded correctly.\n", fileName); fprintf(stderr, " Check your input XML scene file.\n"); exit(-1); } sg->interconnect(sg); std::cout << " Scene file " << fileName << " loaded successfully." << std::endl; printf(" ================ [ Scene Graph ] ================\n"); sg->printNodeHierarchy(0); SimWorld *sw = SimWorld::createFrom(sg); printf(" ================ [ Rigid Bodies ] ================\n"); foreach (const GeneralBodyPtr &b, sw->getGeneralBodyPtrSet()) { printf ("Body: %s (%.2f kg, BB type %d)\n", b->getName(), b->getMass(), b->getBoundingBoxType()); printf (" > Bounding box size: "); b->getBoundingBoxSize().printFormatString(); printf (" > Mass dist size: "); b->getMassDistributionSize().printFormatString(); } printf(" ================ [ Joints ] ================\n"); foreach (const GeneralJointPtr &j, sw->getGeneralJointPtrSet()) { printf ("Joint: %s (%s)\n", j->getName(), j->getJointTypeName()); const ArnJointData &ajd = j->getJointData(); printf (" > Axis "); ajd.ax.printFormatString(); printf (" > Pivot "); ajd.pivot.printFormatString(); foreach (const ArnJointData::ArnJointLimit& ajl, ajd.limits) { printf(" > %s [%f ~ %f]\n", ajl.type.c_str(), ajl.minimum, ajl.maximum); } } delete sw; delete sg; ArnCleanupXmlParser(); ArnCleanupImageLibrary(); ArnCleanupPhysics(); return 0; }
[ [ [ 1, 83 ] ] ]
1667490bd0ff1c03119a38e527774438fc4f93e2
5155ce0bfd77ae28dbf671deef6692220ac71aba
/main/src/exe/Test_dx8.cpp
1ddecf6ae5e4bb5924ef21ebc0244f69f0c05e58
[]
no_license
OldRepoPreservation/taksi
1ffcfbb0a100520ba4a050f571a15389ee9e9098
631c9080c14cf80d028b841ba41f8e884d252c8a
refs/heads/master
2021-07-08T16:26:24.168833
2011-03-13T22:00:57
2011-03-13T22:00:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,660
cpp
// // Test_DX8.cpp // must be in seperate file from DX9 // #include "../stdafx.h" #include "Taksi.h" #ifdef USE_DIRECTX8 #include <d3d8types.h> #include <d3d8.h> typedef IDirect3D8* (STDMETHODCALLTYPE *DIRECT3DCREATE8)(UINT); bool Test_DirectX8( HWND hWnd ) { // get the offset from the start of the DLL to the interface element we want. // step 1: Load d3d8.dll CDllFile _DX8; HRESULT hRes = _DX8.LoadDll( TEXT("d3d8")); if (IS_ERROR(hRes)) { LOG_MSG(("Test_DirectX8 Failed to load d3d8.dll (0x%x)" LOG_CR, hRes )); return false; } // step 2: Get IDirect3D8 DIRECT3DCREATE8 pDirect3DCreate8 = (DIRECT3DCREATE8)_DX8.GetProcAddress("Direct3DCreate8"); if (pDirect3DCreate8 == NULL) { LOG_MSG(("Test_DirectX8 Unable to find Direct3DCreate8" LOG_CR)); return false; } IRefPtr<IDirect3D8> pD3D = pDirect3DCreate8(D3D_SDK_VERSION); if ( ! pD3D.IsValidRefObj()) { LOG_MSG(("Test_DirectX8 Failed to get IDirect3D8 %d=0%x" LOG_CR, D3D_SDK_VERSION, D3D_SDK_VERSION )); return false; } // step 3: Get IDirect3DDevice8 D3DDISPLAYMODE d3ddm; hRes = pD3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &d3ddm ); if (FAILED(hRes)) { LOG_MSG(("Test_DirectX8 GetAdapterDisplayMode failed. 0x%x" LOG_CR, hRes )); return false; } D3DPRESENT_PARAMETERS d3dpp; ZeroMemory( &d3dpp, sizeof(d3dpp)); d3dpp.Windowed = true; d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; d3dpp.BackBufferFormat = d3ddm.Format; IRefPtr<IDirect3DDevice8> pD3DDevice; hRes = pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, // the device we suppose any app would be using. hWnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_DISABLE_DRIVER_MANAGEMENT, &d3dpp, IREF_GETPPTR(pD3DDevice,IDirect3DDevice8)); if ( FAILED(hRes)) { // D3DERR_INVALIDCALL // -2005532292 = 0x8876017c = D3DERR_OUTOFVIDEOMEMORY = multiple opens of the device! // Docs say D3DCREATE_DISABLE_DRIVER_MANAGEMENT should prevent this! NOT TRUE LOG_MSG(("Test_DirectX8 CreateDevice failed. 0x%x" LOG_CR, hRes )); return false; } // step 4: store method addresses in out vars UINT_PTR* pVTable = (UINT_PTR*)(*((UINT_PTR*)pD3DDevice.get_RefObj())); ASSERT(pVTable); sg_Shared.m_nDX8_Present = ( pVTable[TAKSI_INTF_DX8_Present] - _DX8.get_DllInt()); sg_Shared.m_nDX8_Reset = ( pVTable[TAKSI_INTF_DX8_Reset] - _DX8.get_DllInt()); LOG_MSG(("Test_DirectX8: %08x, Present=0%x, Reset=0%x" LOG_CR, (UINT_PTR)pD3DDevice.get_RefObj(), sg_Shared.m_nDX8_Present, sg_Shared.m_nDX8_Reset )); return true; } #endif // USE_DIRECTX8
[ [ [ 1, 85 ] ] ]
668ef96e940875ecddde68730ee40b79d88f0631
5ff30d64df43c7438bbbcfda528b09bb8fec9e6b
/kcore/util/Random.h
9e1f5acfe238c0a13a9a102bd4eb2c3e17b64ac1
[]
no_license
lvtx/gamekernel
c80cdb4655f6d4930a7d035a5448b469ac9ae924
a84d9c268590a294a298a4c825d2dfe35e6eca21
refs/heads/master
2016-09-06T18:11:42.702216
2011-09-27T07:22:08
2011-09-27T07:22:08
38,255,025
3
1
null
null
null
null
UTF-8
C++
false
false
336
h
#pragma once #include <kcore/sys/Atomic.h> namespace gk { /** * @class Random * * Wraps system random function */ class Random { public: /** * A system rand wrapper * * @return Random value generated with time seed. */ static int Rand(); private: static Atomic<int> seed; }; } // gk
[ "darkface@localhost" ]
[ [ [ 1, 27 ] ] ]
751ca0511c2d63e3c217eca5c512c9a4ed30a1fc
3a53382dd8e6ea42b9347c4e505494efa808ef2e
/src/scale.cpp
8e256a5d2fa43d8ac6314a8d4897a4c89b1e7e02
[]
no_license
zed0/aeolus
ca5dc6f06dcd6b59bc5623d7e48a289ca25a3e87
37ae7a1bbdf7c7fbd4ea6de51fd59cf60be72287
refs/heads/master
2020-05-29T15:16:45.760231
2011-11-24T19:39:33
2011-11-24T19:39:33
2,845,641
1
0
null
null
null
null
UTF-8
C++
false
false
406
cpp
#include "scale.h" scale::scale(Mat& image_,float scaleValue):preprocessor(image_) { this->scaleValue = scaleValue; } void scale::run() { //scale the resolution of the image int width = image.rows*scaleValue; int height = image.cols*scaleValue; resize(image, image, Size(width,height), INTER_NEAREST); } void scale::setScale(float scaleValue) { this->scaleValue = scaleValue; }
[ [ [ 1, 19 ] ] ]
9e1fe9f864e05c4c4e7b596431503f43e8ff17f5
00b979f12f13ace4e98e75a9528033636dab021d
/branches/zfs/src/thr_server.cc
d811b2b5063f8df3d64dd146faa1e15cf20f7562
[]
no_license
BackupTheBerlios/ziahttpd-svn
812e4278555fdd346b643534d175546bef32afd5
8c0b930d3f4a86f0622987776b5220564e89b7c8
refs/heads/master
2016-09-09T20:39:16.760554
2006-04-13T08:44:28
2006-04-13T08:44:28
40,819,288
0
0
null
null
null
null
UTF-8
C++
false
false
7,010
cc
// // thr_server.cc for in // // Made by texane // Login <[email protected]> // // Started on Tue Feb 14 15:22:37 2006 texane // Last update Thu Feb 23 23:32:27 2006 texane // #include <iostream> #include <cstdio> #include <string> #include <ziafs.hh> // @info // There should be a ret_in_cache // flag, in case where there are no // more thread in the pool for doing // accept -> deadlock, since all threads // are in the wait function. // Thus, the thread doesn't return in cache using namespace sysapi; using namespace std; // session management void thr::pool::sess_reset_request(session_t& sess) { sess.done = false; sess.proto.reset(); sess.chunk_pos = net::http::CHUNK_FIRST; sess.target = 0; } void thr::pool::sess_release_request(session_t& sess) { core_t* core; core = sess.srv->core; if (sess.target) { core->res_manager.factory_destroy(sess.target); sess.target = 0; } } void thr::pool::sess_reset(session_t& sess) { // + sysapi::insock::reset_handle(sess.cli_sock); sess.done = false; sess.srv = 0; sess.thr_slot = 0; sess.ret_in_cache = true; sess_reset_request(sess); } void thr::pool::sess_release(session_t& sess) { core_t* core; core = sess.srv->core; sess_release_request(sess); if (sess.thr_slot->curr_io.timeouted == false) insock::close(sess.cli_sock); } // Basic processing stages bool thr::pool::sess_bind_server(session_t& sess) { error::handle_t herr; herr = error::SUCCESS; if (sess.srv->is_bound == false) { sess.srv->is_bound = true; herr = insock::create_listening(sess.srv->srv_sock, sess.srv->srv_addr, sess.srv->nr_bklog); } if (herr == error::SUCCESS) return true; return false; } bool thr::pool::sess_accept_connection(session_t& sess) { error::handle_t herr; // Accept a new connection, delegate accept herr = insock::accept(sess.cli_sock, sess.cli_addr, sess.srv->srv_sock); if (sess.thr_slot->pool->assign_task(server_entry, (void*)sess.srv) == false) sess.ret_in_cache = false; if (herr == error::SUCCESS) return true; return false; } bool thr::pool::sess_read_metadata(session_t& sess) { bool valid; bool end_of_metadata; error::handle_t herr; unsigned char buf[ZIAFS_STATIC_BUFSZ]; unsigned int nbytes; if (sess.done == true) return false; end_of_metadata = false; while (end_of_metadata == false) { herr = recv(*sess.thr_slot, sess.cli_sock, (unsigned char*)buf, sizeof(buf), nbytes); if (sess.thr_slot->curr_io.timeouted == true) { sess.done = true; return false; } else if (herr != error::SUCCESS) { sess.done = true; return false; } valid = sess.proto.consume(buf, nbytes, end_of_metadata); if (valid == false) { end_of_metadata = true; sess.done = true; } else if (end_of_metadata == true) { } } // Create the resource sess.proto.create_resource(sess.target, sess.srv->core->res_manager, *sess.srv->srv_config); return true; } bool thr::pool::sess_handle_predata(session_t& sess) { // handle pre data, such // as the expect code... buffer buf; bool done; unsigned int nr_sent; sysapi::error::handle_t sys_err; if (sess.proto.predata(buf) == true) { done = false; while (done == false) { if (buf.size() == 0) { done = true; } else { sys_err = insock::send(sess.cli_sock, buf.bufptr(), (unsigned int)buf.size(), nr_sent); if (sys_err != sysapi::error::SUCCESS) { done = true; } else { buf.remove_front(nr_sent); } } } } return true; } bool thr::pool::sess_handle_request(session_t& sess) { buffer raw_buf; buffer body_buf; buffer hdr_buf; unsigned int size; unsigned char buf[ZIAFS_STATIC_BUFSZ]; sysapi::error::handle_t herr; resource::e_error e_err; unsigned int nbytes; bool done; // Basic checks if (sess.done == true) return false; if (sess.target == 0) return false; done = false; // get / post method while (done == false) { if (sess.target->input_size()) { // Resources can be created with a // buffer as input prefetch. if (sess.target->is_prefetched_input() == true) { sess.target->get_prefetched_input(raw_buf); } else { herr = recv(*sess.thr_slot, sess.cli_sock, (unsigned char*)buf, sizeof(buf), nbytes); if (sess.thr_slot->curr_io.timeouted == true || herr != error::SUCCESS) { sess.done = true; return false; } raw_buf = buffer((unsigned char*)buf, nbytes); } // Then make http consum/process the buffer(it can be chunked) // +++ sess.proto.consume_body(raw_buf, &body_buf); body_buf = raw_buf; // Send the buffer as input to the resource sess.target->flush_input(*sess.thr_slot, raw_buf); } // generate the resource e_err = sess.target->generate(size); if (e_err == resource::E_SUCCESS) { // this is for non blocking mode // sess.target->alter(size); sess.proto.create_header(hdr_buf, size, sess.chunk_pos); sess.chunk_pos = net::http::CHUNK_MIDDLE; // sess.proto.modify_header(hdr_buf); sess.target->prepend_header(hdr_buf); if (sess.target->flush_network(*sess.thr_slot, sess.cli_sock) != resource::E_SUCCESS) { sess.done = true; return false; } } else if (e_err == resource::E_WOULDBLOCK) { } else if (e_err == resource::E_CONTINUE) { // sess.chunk_pos = net::http::CHUNK_MIDDLE; } else // if (e_err == resource::E_ALREADY_GEN) { // Send the last chunk if (sess.proto.response.is_chunk == true) { sess.chunk_pos = net::http::CHUNK_LAST; sess.proto.create_header(hdr_buf, 0, net::http::CHUNK_LAST); sess.target->prepend_header(hdr_buf); sess.target->flush_network(*sess.thr_slot, sess.cli_sock); } done = true; } } return true; } void* thr::pool::server_entry(thr::pool::slot_t* thr_slot) { // Server's main function // thr_slot->uparam contains // the server instance. // If the server is not yet // bound, bind it. session_t sess; serve_another: sess_reset(sess); sess.thr_slot = thr_slot; io_info_reset(sess.thr_slot->curr_io); sess.srv = (net::server*)thr_slot->uparam; // session pipeline sess_bind_server(sess); sess_accept_connection(sess); while (sess.done == false) { sess_reset_request(sess); sess_read_metadata(sess); sess_handle_predata(sess); sess_handle_request(sess); sess_release_request(sess); } sess_release(sess); if (sess.ret_in_cache == false) { goto serve_another; } return 0; }
[ "texane@754ce95b-6e01-0410-81d0-8774ba66fe44" ]
[ [ [ 1, 304 ] ] ]
09a1d78e656b50c98e8909f36acdc0ce4f590add
c8f467a4cee0b4067b93936574c884c9de0b36cf
/source/Irrlicht/CColladaFileLoader.cpp
e21ef0e260d2d8ad48ade3a80950d3dcef7e0aef
[ "LicenseRef-scancode-unknown-license-reference", "Zlib", "LicenseRef-scancode-other-permissive" ]
permissive
flaithbheartaigh/mirrlicht
1ff418d29017e55e5f4a27a70dcfd5a88cb244b5
ccc16e8f5465fb72e81ae986e56ef2e4c3e7654b
refs/heads/master
2021-01-10T11:29:49.569701
2009-01-12T21:08:31
2009-01-12T21:08:31
49,994,212
0
0
null
null
null
null
UTF-8
C++
false
false
36,377
cpp
// Copyright (C) 2002-2007 Nikolaus Gebhardt // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #include "CColladaFileLoader.h" #include "os.h" #include "IXMLReader.h" #include "IDummyTransformationSceneNode.h" #include "SAnimatedMesh.h" #include "fast_atof.h" #include "quaternion.h" #include "ILightSceneNode.h" #include "ICameraSceneNode.h" #include "IMeshManipulator.h" #include "IReadFile.h" #include "IAttributes.h" #include "IMeshCache.h" #include "IMeshSceneNode.h" #include "SMeshBufferLightMap.h" //#define COLLADA_READER_DEBUG namespace irr { namespace scene { const char* const inputSemanticNames[] = {"POSITION", "VERTEX", "NORMAL", "TEXCOORD", "UV", "TANGENT", 0}; //! following class is for holding and creating instances of library objects, //! named prefabs in this loader. class CPrefab : public IColladaPrefab { public: CPrefab(const char* id) { Id = id; } //! creates an instance of this prefab virtual scene::ISceneNode* addInstance(scene::ISceneNode* parent, scene::ISceneManager* mgr) { // empty implementation return 0; } //! returns id of this prefab virtual const c8* getId() { return Id.c_str(); } protected: core::stringc Id; }; //! prefab for a light scene node class CLightPrefab : public CPrefab { public: CLightPrefab(const char* id) : CPrefab(id) { #ifdef COLLADA_READER_DEBUG os::Printer::log("COLLADA: loaded light prefab:", Id.c_str()); #endif } video::SLight LightData; // publically accessible //! creates an instance of this prefab virtual scene::ISceneNode* addInstance(scene::ISceneNode* parent, scene::ISceneManager* mgr) { #ifdef COLLADA_READER_DEBUG os::Printer::log("COLLADA: Constructing light instance:", Id.c_str()); #endif scene::ILightSceneNode* l = mgr->addLightSceneNode(parent); l->setLightData ( LightData ); return l; } }; //! prefab for a mesh scene node class CGeometryPrefab : public CPrefab { public: CGeometryPrefab(const char* id) : CPrefab(id) { } scene::IMesh* Mesh; // public accessible //! creates an instance of this prefab virtual scene::ISceneNode* addInstance(scene::ISceneNode* parent, scene::ISceneManager* mgr) { #ifdef COLLADA_READER_DEBUG os::Printer::log("COLLADA: Constructing mesh instance:", Id.c_str()); #endif scene::ISceneNode* m = mgr->addMeshSceneNode(Mesh, parent); return m; } }; //! prefab for a camera scene node class CCameraPrefab : public CPrefab { public: CCameraPrefab(const char* id) : CPrefab(id), YFov(core::PI / 2.5f), ZNear(1.0f), ZFar(3000.0f) { #ifdef COLLADA_READER_DEBUG os::Printer::log("COLLADA: loaded camera prefab:", Id.c_str()); #endif } // public accessible data f32 YFov; f32 ZNear; f32 ZFar; //! creates an instance of this prefab virtual scene::ISceneNode* addInstance(scene::ISceneNode* parent, scene::ISceneManager* mgr) { #ifdef COLLADA_READER_DEBUG os::Printer::log("COLLADA: Constructing camera instance:", Id.c_str()); #endif scene::ICameraSceneNode* c = mgr->addCameraSceneNode(parent); c->setFOV(YFov); c->setNearValue(ZNear); c->setFarValue(ZFar); return c; } }; //! Constructor CColladaFileLoader::CColladaFileLoader(video::IVideoDriver* driver, scene::ISceneManager* smgr, io::IFileSystem* fs) : Driver(driver), SceneManager(smgr), FileSystem(fs), DummyMesh(0), FirstLoadedMesh(0), LoadedMeshCount(0), CreateInstances(false) { colladaSectionName = "COLLADA"; librarySectionName = "library"; assetSectionName = "asset"; sceneSectionName = "scene"; lightPrefabName = "light"; cameraPrefabName = "camera"; materialSectionName = "material"; geometrySectionName = "geometry"; meshSectionName = "mesh"; sourceSectionName = "source"; arraySectionName = "array"; accessorSectionName = "accessor"; verticesSectionName = "vertices"; inputTagName = "input"; polygonsSectionName = "polygons"; polygonName = "p"; nodeSectionName = "node"; lookatNodeName = "lookat"; matrixNodeName = "matrix"; perspectiveNodeName = "perspective"; rotateNodeName = "rotate"; scaleNodeName = "scale"; translateNodeName = "translate"; skewNodeName = "skew"; instanceNodeName = "instance"; paramTagName = "param"; } //! destructor CColladaFileLoader::~CColladaFileLoader() { if (DummyMesh) DummyMesh->drop(); if (FirstLoadedMesh) FirstLoadedMesh->drop(); } //! Returns true if the file maybe is able to be loaded by this class. /** This decision should be based only on the file extension (e.g. ".cob") */ bool CColladaFileLoader::isALoadableFileExtension(const c8* fileName) { return strstr(fileName, ".xml") || strstr(fileName, ".dae"); } //! creates/loads an animated mesh from the file. //! \return Pointer to the created mesh. Returns 0 if loading failed. //! If you no longer need the mesh, you should call IAnimatedMesh::drop(). //! See IUnknown::drop() for more information. IAnimatedMesh* CColladaFileLoader::createMesh(irr::io::IReadFile* file) { io::IXMLReaderUTF8* reader = FileSystem->createXMLReaderUTF8(file); if (!reader) return 0; CurrentlyLoadingMesh = file->getFileName(); CreateInstances = SceneManager->getParameters()->getAttributeAsBool( scene::COLLADA_CREATE_SCENE_INSTANCES); // read until COLLADA section, skip other parts while(reader->read()) { if (reader->getNodeType() == io::EXN_ELEMENT) { if (colladaSectionName == reader->getNodeName()) readColladaSection(reader); else skipSection(reader, true); // unknown section } } reader->drop(); scene::IAnimatedMesh* returnMesh = DummyMesh; // because this loader loads and creates a complete scene instead of // a single mesh, return an empty dummy mesh to make the scene manager // know that everything went well. if (!DummyMesh) { DummyMesh = new SAnimatedMesh(); returnMesh = DummyMesh; } // add the first loaded mesh into the mesh cache too, if more than one // meshes have been loaded from the file if (LoadedMeshCount>1 && FirstLoadedMesh) { os::Printer::log("Added COLLADA mesh", FirstLoadedMeshName.c_str()); SceneManager->getMeshCache()->addMesh(FirstLoadedMeshName.c_str(), FirstLoadedMesh); } // clean up temporary loaded data clearData(); returnMesh->grab(); // store until this loader is destroyed DummyMesh->drop(); DummyMesh = 0; if (FirstLoadedMesh) FirstLoadedMesh->drop(); FirstLoadedMesh = 0; LoadedMeshCount = 0; return returnMesh; } //! skips an (unknown) section in the collada document void CColladaFileLoader::skipSection(io::IXMLReaderUTF8* reader, bool reportSkipping) { #ifndef COLLADA_READER_DEBUG if (reportSkipping) // always report in COLLADA_READER_DEBUG mode #endif os::Printer::log("COLLADA skipping section", core::stringc(reader->getNodeName()).c_str()); // skip if this element is empty anyway. if (reader->isEmptyElement()) return; // read until we've reached the last element in this section int tagCounter = 1; while(tagCounter && reader->read()) { if (reader->getNodeType() == io::EXN_ELEMENT && !reader->isEmptyElement()) { #ifdef COLLADA_READER_DEBUG if (reportSkipping) os::Printer::log("COLLADA unknown element:", core::stringc(reader->getNodeName()).c_str()); #endif // COLLADA_READER_DEBUG ++tagCounter; } else if (reader->getNodeType() == io::EXN_ELEMENT_END) --tagCounter; } } //! reads the <COLLADA> section and its content void CColladaFileLoader::readColladaSection(io::IXMLReaderUTF8* reader) { if (reader->isEmptyElement()) return; // I ignore version information here. Keep on reading content: while(reader->read()) if (reader->getNodeType() == io::EXN_ELEMENT) { if (librarySectionName == reader->getNodeName()) readLibrarySection(reader); else if (assetSectionName == reader->getNodeName()) readAssetSection(reader); else if (sceneSectionName == reader->getNodeName()) readSceneSection(reader); else skipSection(reader, true); // unknown section } } //! reads a <library> section and its content void CColladaFileLoader::readLibrarySection(io::IXMLReaderUTF8* reader) { while(reader->read()) if (reader->getNodeType() == io::EXN_ELEMENT) { if (lightPrefabName == reader->getNodeName()) readLightPrefab(reader); else if (materialSectionName == reader->getNodeName()) readMaterial(reader); else if (cameraPrefabName == reader->getNodeName()) readCameraPrefab(reader); else if (geometrySectionName == reader->getNodeName()) readGeometry(reader); else skipSection(reader, true); // unknown section } else if (reader->getNodeType() == io::EXN_ELEMENT_END) { if (librarySectionName == reader->getNodeName()) break; // end reading. } } //! reads a <scene> section and its content void CColladaFileLoader::readSceneSection(io::IXMLReaderUTF8* reader) { #ifdef COLLADA_READER_DEBUG os::Printer::log("COLLADA reading scene"); #endif if (reader->isEmptyElement()) return; // read the scene while(reader->read()) if (reader->getNodeType() == io::EXN_ELEMENT) { if (nodeSectionName == reader->getNodeName()) readNodeSection(reader, SceneManager->getRootSceneNode()); else skipSection(reader, true); // ignore all other sections } } //! reads a <asset> section and its content void CColladaFileLoader::readAssetSection(io::IXMLReaderUTF8* reader) { #ifdef COLLADA_READER_DEBUG os::Printer::log("COLLADA reading asset"); #endif // don't need asset data so far, so skip it skipSection(reader, false); } //! reads a <node> section and its content void CColladaFileLoader::readNodeSection(io::IXMLReaderUTF8* reader, scene::ISceneNode* parent) { #ifdef COLLADA_READER_DEBUG os::Printer::log("COLLADA reading node"); #endif if (reader->isEmptyElement()) return; core::stringc name = reader->getAttributeValue("name"); // name of the node core::matrix4 transform; // transformation of this node scene::ISceneNode* node = 0; // instance // read the node while(reader->read()) if (reader->getNodeType() == io::EXN_ELEMENT) { if (lookatNodeName == reader->getNodeName()) transform *= readLookAtNode(reader); else if (matrixNodeName == reader->getNodeName()) transform *= readMatrixNode(reader); else if (perspectiveNodeName == reader->getNodeName()) transform *= readPerspectiveNode(reader); else if (rotateNodeName == reader->getNodeName()) transform *= readRotateNode(reader); else if (scaleNodeName == reader->getNodeName()) transform *= readScaleNode(reader); else if (translateNodeName == reader->getNodeName()) transform *= readTranslateNode(reader); else if (skewNodeName == reader->getNodeName()) transform *= readSkewNode(reader); else if (instanceNodeName == reader->getNodeName()) { scene::ISceneNode* newnode = 0; readInstanceNode(reader, parent, &newnode); if (node && newnode) { // move children from dummy to new node core::list<ISceneNode*>::Iterator it = node->getChildren().begin(); for (; it != node->getChildren().end(); it = node->getChildren().begin()) (*it)->setParent(newnode); // remove previous dummy node node->remove(); } node = newnode; } else if (nodeSectionName == reader->getNodeName()) { // create dummy node if there is none yet. if (!node) { scene::IDummyTransformationSceneNode* dummy = SceneManager->addDummyTransformationSceneNode(parent); dummy->getRelativeTransformationMatrix() = transform; node = dummy; } // read and add child readNodeSection(reader, node); } else skipSection(reader, true); // ignore all other sections } // end if node else if (reader->getNodeType() == io::EXN_ELEMENT_END) { if (nodeSectionName == reader->getNodeName()) break; } if (node) { // TODO: set transformation correctly into node. // currently this isn't done correctly. Need to get transformation, // rotation and scale from the matrix. core::vector3df trans = transform.getTranslation(); core::vector3df rot = transform.getRotationDegrees(); node->setPosition(trans); node->setRotation(rot); node->updateAbsolutePosition(); node->setName(name.c_str()); } } //! reads a <lookat> element and its content and creates a matrix from it core::matrix4 CColladaFileLoader::readLookAtNode(io::IXMLReaderUTF8* reader) { core::matrix4 mat; if (reader->isEmptyElement()) return mat; #ifdef COLLADA_READER_DEBUG os::Printer::log("COLLADA reading look at node"); #endif f32 floats[9]; readFloatsInsideElement(reader, floats, 9); mat.buildCameraLookAtMatrixLH( core::vector3df(floats[0], floats[1], floats[2]), core::vector3df(floats[3], floats[4], floats[5]), core::vector3df(floats[6], floats[7], floats[8])); return mat; } //! reads a <skew> element and its content and creates a matrix from it core::matrix4 CColladaFileLoader::readSkewNode(io::IXMLReaderUTF8* reader) { core::matrix4 mat; if (reader->isEmptyElement()) return mat; f32 floats[7]; readFloatsInsideElement(reader, floats, 7); // TODO: build skew matrix from these 7 floats os::Printer::log("COLLADA loader warning: <skew> not implemented yet.", ELL_WARNING); return mat; } //! reads a <matrix> element and its content and creates a matrix from it core::matrix4 CColladaFileLoader::readMatrixNode(io::IXMLReaderUTF8* reader) { core::matrix4 mat; if (reader->isEmptyElement()) return mat; readFloatsInsideElement(reader, mat.pointer(), 16); return mat; } //! reads a <perspective> element and its content and creates a matrix from it core::matrix4 CColladaFileLoader::readPerspectiveNode(io::IXMLReaderUTF8* reader) { core::matrix4 mat; if (reader->isEmptyElement()) return mat; f32 floats[1]; readFloatsInsideElement(reader, floats, 1); // TODO: build perspecitve matrix from this float os::Printer::log("COLLADA loader warning: <perspective> not implemented yet.", ELL_WARNING); return mat; } //! reads a <rotate> element and its content and creates a matrix from it core::matrix4 CColladaFileLoader::readRotateNode(io::IXMLReaderUTF8* reader) { core::matrix4 mat; if (reader->isEmptyElement()) return mat; f32 floats[4]; readFloatsInsideElement(reader, floats, 4); core::quaternion q(floats[0], floats[1], floats[2], floats[3]); mat = q.getMatrix(); return mat; } //! reads a <scale> element and its content and creates a matrix from it core::matrix4 CColladaFileLoader::readScaleNode(io::IXMLReaderUTF8* reader) { core::matrix4 mat; if (reader->isEmptyElement()) return mat; f32 floats[3]; readFloatsInsideElement(reader, floats, 3); mat.setScale(core::vector3df(floats[0], floats[1], floats[2])); return mat; } //! reads a <translate> element and its content and creates a matrix from it core::matrix4 CColladaFileLoader::readTranslateNode(io::IXMLReaderUTF8* reader) { core::matrix4 mat; if (reader->isEmptyElement()) return mat; f32 floats[3]; readFloatsInsideElement(reader, floats, 3); mat.setTranslation(core::vector3df(floats[0], floats[1], floats[2])); return mat; } //! reads a <instance> node and creates a scene node from it void CColladaFileLoader::readInstanceNode(io::IXMLReaderUTF8* reader, scene::ISceneNode* parent, scene::ISceneNode** outNode) { #ifdef COLLADA_READER_DEBUG os::Printer::log("COLLADA reading instance"); #endif // find prefab of the specified id core::stringc url = reader->getAttributeValue("url"); uriToId(url); if (CreateInstances) for (int i=0; i<(int)Prefabs.size(); ++i) if (url == Prefabs[i]->getId()) { *outNode = Prefabs[i]->addInstance(parent, SceneManager); if (*outNode) (*outNode)->setName(reader->getAttributeValue("id")); return; } } //! reads a <camera> element and stores it as prefab void CColladaFileLoader::readCameraPrefab(io::IXMLReaderUTF8* reader) { CCameraPrefab* prefab = new CCameraPrefab(reader->getAttributeValue("id")); if (!reader->isEmptyElement()) { readColladaParameters(reader, cameraPrefabName); SColladaParam* p; p = getColladaParameter(ECPN_YFOV); if (p && p->Type == ECPT_FLOAT) prefab->YFov = p->Floats[0]; p = getColladaParameter(ECPN_ZNEAR); if (p && p->Type == ECPT_FLOAT) prefab->ZNear = p->Floats[0]; p = getColladaParameter(ECPN_ZFAR); if (p && p->Type == ECPT_FLOAT) prefab->ZFar = p->Floats[0]; } Prefabs.push_back(prefab); } //! reads a <material> element and stores it in the material section void CColladaFileLoader::readMaterial(io::IXMLReaderUTF8* reader) { SColladaMaterial material; material.Id = reader->getAttributeValue("id"); if (!reader->isEmptyElement()) { // TODO: implement material parsing later. // for now we only read and discard then all <param> tags. readColladaParameters(reader, materialSectionName); } // add material to list of loaded materials. Materials.push_back(material); } //! reads a <geometry> element and stores it as mesh if possible void CColladaFileLoader::readGeometry(io::IXMLReaderUTF8* reader) { core::stringc id = reader->getAttributeValue("id"); core::stringc VertexPositionSource; // each mesh has exactly one <vertex> member, containing // a POSITION input. This string stores the source of this input. core::array<SSource> sources; bool okToReadArray = false; SAnimatedMesh* amesh = new SAnimatedMesh(); scene::SMesh* mesh = new SMesh(); amesh->addMesh(mesh); // read sources with arrays and accessor for each mesh if (!reader->isEmptyElement()) while(reader->read()) { if (reader->getNodeType() == io::EXN_ELEMENT) { const char* nodeName = reader->getNodeName(); if (meshSectionName == nodeName) { // inside a mesh section. Don't have to do anything here. } else if (sourceSectionName == nodeName) { // create a new source sources.push_back(SSource()); sources.getLast().Id = reader->getAttributeValue("id"); #ifdef COLLADA_READER_DEBUG os::Printer::log("Loaded source", sources.getLast().Id.c_str()); #endif } else if (arraySectionName == nodeName) { // create a new array and read it. if (!sources.empty()) { sources.getLast().Array.Name = reader->getAttributeValue("id"); int count = reader->getAttributeValueAsInt("count"); sources.getLast().Array.Data.set_used(count); // pre allocate // check if type of array is ok const char* type = reader->getAttributeValue("type"); okToReadArray = (!strcmp("float", type) || !strcmp("int", type)); #ifdef COLLADA_READER_DEBUG os::Printer::log("Read array", sources.getLast().Array.Name.c_str()); #endif } #ifdef COLLADA_READER_DEBUG else os::Printer::log("Warning, array found, but no source", reader->getAttributeValue("id")); #endif } else if (accessorSectionName == nodeName) { SAccessor accessor; accessor.Count = reader->getAttributeValueAsInt("count"); accessor.Offset = reader->getAttributeValueAsInt("offset"); accessor.Stride = reader->getAttributeValueAsInt("stride"); if (accessor.Stride == 0) accessor.Stride = 1; // the accessor contains some information on how to access (boi!) the array, // the info is stored in collada style parameters, so just read them. readColladaParameters(reader, accessorSectionName); if (!sources.empty()) { sources.getLast().Accessors.push_back(accessor); sources.getLast().Accessors.getLast().Parameters = Parameters; } } else if (verticesSectionName == nodeName) { // read vertex input position source readColladaInputs(reader, verticesSectionName); SColladaInput* input = getColladaInput(ECIS_POSITION); if (input) VertexPositionSource = input->Source; } else if (polygonsSectionName == nodeName) { // read polygons section readPolygonSection(reader, VertexPositionSource, sources, mesh); } } // end if node type is element else if (reader->getNodeType() == io::EXN_TEXT) { // read array data if (okToReadArray && !sources.empty()) { core::array<f32>& a = sources.getLast().Array.Data; core::stringc data = reader->getNodeData(); const c8* p = &data[0]; for (int i=0; i<(int)a.size(); ++i) { findNextNoneWhiteSpace(&p); a[i] = readFloat(&p); } } // end reading array okToReadArray = false; } // end if node type is text else if (reader->getNodeType() == io::EXN_ELEMENT_END) { if (geometrySectionName == reader->getNodeName()) { // end of geometry section reached, cancel out break; } } } // end while reader->read(); // add mesh as geometry mesh->recalculateBoundingBox(); // create virtual file name core::stringc filename = CurrentlyLoadingMesh; filename += '#'; filename += id; // add to scene manager if (LoadedMeshCount) { SceneManager->getMeshCache()->addMesh(filename.c_str(), amesh); os::Printer::log("Added COLLADA mesh", filename.c_str()); } else { FirstLoadedMeshName = filename; FirstLoadedMesh = amesh; FirstLoadedMesh->grab(); } ++LoadedMeshCount; mesh->drop(); amesh->drop(); // create geometry prefab CGeometryPrefab* prefab = new CGeometryPrefab(id.c_str()); prefab->Mesh = mesh; Prefabs.push_back(prefab); // store as dummy mesh if no instances will be created if (!CreateInstances && !DummyMesh) { DummyMesh = amesh; DummyMesh->grab(); } } struct SInputSlot { f32* Data; // Pointer to source data ECOLLADA_INPUT_SEMANTIC Semantic; }; struct SPolygon { core::array<int> Indices; }; //! reads a polygons section and creates a mesh from it void CColladaFileLoader::readPolygonSection(io::IXMLReaderUTF8* reader, core::stringc vertexPositionSource, core::array<SSource>& sources, scene::SMesh* mesh) { core::stringc material = reader->getAttributeValue("material"); // int polygonCount = reader->getAttributeValueAsInt("count"); core::array<SInputSlot> slots; core::array<SPolygon> polygons; bool parsePolygonOK = false; int inputSemanticCount = 0; // read all <input> and if (!reader->isEmptyElement()) while(reader->read()) { const char* nodeName = reader->getNodeName(); if (reader->getNodeType() == io::EXN_ELEMENT) { if (inputTagName == nodeName) { // read input tag readColladaInput(reader); // create new input slot if (!Inputs.empty()) { SInputSlot slot; slot.Semantic = Inputs.getLast().Semantic; core::stringc sourceArrayURI; // get input source array id, if it is a vertex input, take // the <vertex><input>-source attribute. if (slot.Semantic == ECIS_VERTEX) sourceArrayURI = vertexPositionSource; else sourceArrayURI = Inputs.getLast().Source; uriToId(sourceArrayURI); // find source array (we'll ignore acessors for this implementation) int s; for (s=0; s<(int)sources.size(); ++s) if (sources[s].Id == sourceArrayURI) { // slot found slot.Data = sources[s].Array.Data.pointer(); break; } if (s == (int)sources.size()) os::Printer::log("COLLADA Warning, polygon input source not found", sourceArrayURI.c_str()); else slots.push_back(slot); #ifdef COLLADA_READER_DEBUG // print slot // core::stringc tmp = "Added slot "; // tmp += inputSemanticNames[Inputs.getLast().Semantic]; // tmp += " sourceArray:"; // tmp += sourceArrayURI; // os::Printer::log(tmp.c_str()); #endif ++inputSemanticCount; } } // end is input node else if (polygonName == nodeName) { parsePolygonOK = true; polygons.push_back(SPolygon()); } // end is polygon node } // end is element node else if (reader->getNodeType() == io::EXN_ELEMENT_END) { if (polygonName == nodeName) parsePolygonOK = false; // end parsing a polygon else if (polygonsSectionName == nodeName) break; // cancel out and create mesh } // end is element end else if (reader->getNodeType() == io::EXN_TEXT) { if (parsePolygonOK && polygons.size()) { // parse this text and add it to the last polygon data core::stringc data = reader->getNodeData(); const c8* p = &data[0]; SPolygon& poly = polygons.getLast(); while(*p) { findNextNoneWhiteSpace(&p); poly.Indices.push_back(readInt(&p)); } parsePolygonOK = false; } } } // end while reader->read() if (inputSemanticCount == 0 || inputSemanticCount != (int)slots.size()) return; // we cannot create the mesh if one of the input semantics wasn't found. if (!polygons.size()) return; // cancel if there are no polygons anyway. // analyze content of slots to create a fitting mesh buffer int i; int textureCoordSetCount = 0; int normalSlotCount = 0; int secondTexCoordSetIndex = -1; for (i=0; i<(int)slots.size(); ++i) { if (slots[i].Semantic == ECIS_TEXCOORD || slots[i].Semantic == ECIS_UV ) { ++textureCoordSetCount; if (textureCoordSetCount==2) secondTexCoordSetIndex = i; } else if (slots[i].Semantic == ECIS_NORMAL) ++normalSlotCount; } // if there is more than one texture coordinate set, create a lightmap mesh buffer, // otherwise use a standard mesh buffer scene::IMeshBuffer* buffer = 0; if ( textureCoordSetCount <= 1 ) { // standard mesh buffer scene::SMeshBuffer* mbuffer = new SMeshBuffer(); buffer = mbuffer; for (i=0; i<(int)polygons.size(); ++i) { int vertexCount = polygons[i].Indices.size() / inputSemanticCount; // for all vertices in array for (int v=0; v<(int)polygons[i].Indices.size(); v+=inputSemanticCount) { video::S3DVertex vtx; vtx.Color.set(100,255,255,255); // for all input semantics for (int k=0; k<(int)slots.size(); ++k) { // build vertex from input semantics. int idx = polygons[i].Indices[v+k]; switch(slots[k].Semantic) { case ECIS_POSITION: case ECIS_VERTEX: vtx.Pos.X = slots[k].Data[(idx*3)+0]; vtx.Pos.Y = slots[k].Data[(idx*3)+1]; vtx.Pos.Z = slots[k].Data[(idx*3)+2]; break; case ECIS_NORMAL: vtx.Normal.X = slots[k].Data[(idx*3)+0]; vtx.Normal.Y = slots[k].Data[(idx*3)+1]; vtx.Normal.Z = slots[k].Data[(idx*3)+2]; break; case ECIS_TEXCOORD: case ECIS_UV: vtx.TCoords.X = slots[k].Data[(idx*2)+0]; vtx.TCoords.Y = slots[k].Data[(idx*2)+1]; break; case ECIS_TANGENT: break; default: break; } } mbuffer->Vertices.push_back(vtx); } // end for all vertices // add vertex indices int currentVertexCount = mbuffer->Vertices.size(); int oldVertexCount = currentVertexCount - vertexCount; for (int face=0; face<vertexCount-2; ++face) { mbuffer->Indices.push_back(oldVertexCount + 0); mbuffer->Indices.push_back(oldVertexCount + 1 + face); mbuffer->Indices.push_back(oldVertexCount + 2 + face); } } // end for all polygons } else { // lightmap mesh buffer scene::SMeshBufferLightMap* mbuffer = new SMeshBufferLightMap(); buffer = mbuffer; for (i=0; i<(int)polygons.size(); ++i) { int vertexCount = polygons[i].Indices.size() / inputSemanticCount; // for all vertices in array for (int v=0; v<(int)polygons[i].Indices.size(); v+=inputSemanticCount) { video::S3DVertex2TCoords vtx; vtx.Color.set(100,255,255,255); // for all input semantics for (int k=0; k<(int)slots.size(); ++k) { // build vertex from input semantics. int idx = polygons[i].Indices[v+k]; switch(slots[k].Semantic) { case ECIS_POSITION: case ECIS_VERTEX: vtx.Pos.X = slots[k].Data[(idx*3)+0]; vtx.Pos.Y = slots[k].Data[(idx*3)+1]; vtx.Pos.Z = slots[k].Data[(idx*3)+2]; break; case ECIS_NORMAL: vtx.Normal.X = slots[k].Data[(idx*3)+0]; vtx.Normal.Y = slots[k].Data[(idx*3)+1]; vtx.Normal.Z = slots[k].Data[(idx*3)+2]; break; case ECIS_TEXCOORD: case ECIS_UV: if (k==secondTexCoordSetIndex) { vtx.TCoords2.X = slots[k].Data[(idx*2)+0]; vtx.TCoords2.Y = slots[k].Data[(idx*2)+1]; } else { vtx.TCoords.X = slots[k].Data[(idx*2)+0]; vtx.TCoords.Y = slots[k].Data[(idx*2)+1]; } break; case ECIS_TANGENT: break; default: break; } } mbuffer->Vertices.push_back(vtx); } // end for all vertices // add vertex indices int currentVertexCount = mbuffer->Vertices.size(); int oldVertexCount = currentVertexCount - vertexCount; for (int face=0; face<vertexCount-2; ++face) { mbuffer->Indices.push_back(oldVertexCount + 0); mbuffer->Indices.push_back(oldVertexCount + 1 + face); mbuffer->Indices.push_back(oldVertexCount + 2 + face); } } // end for all polygons } // calculate normals if there is no slot for it if (!normalSlotCount) SceneManager->getMeshManipulator()->recalculateNormals(buffer); // recalculate bounding box SceneManager->getMeshManipulator()->recalculateBoundingBox(buffer); // add mesh buffer mesh->addMeshBuffer(buffer); buffer->drop(); } //! reads a <light> element and stores it as prefab void CColladaFileLoader::readLightPrefab(io::IXMLReaderUTF8* reader) { CLightPrefab* prefab = new CLightPrefab(reader->getAttributeValue("id")); if (!reader->isEmptyElement()) { readColladaParameters(reader, lightPrefabName); SColladaParam* p = getColladaParameter(ECPN_COLOR); if (p && p->Type == ECPT_FLOAT3) prefab->LightData.DiffuseColor.set(p->Floats[0], p->Floats[1], p->Floats[2]); } Prefabs.push_back(prefab); } //! returns a collada parameter or none if not found SColladaParam* CColladaFileLoader::getColladaParameter(ECOLLADA_PARAM_NAME name) { for (int i=0; i<(int)Parameters.size(); ++i) if (Parameters[i].Name == name) return &Parameters[i]; return 0; } //! returns a collada input or none if not found SColladaInput* CColladaFileLoader::getColladaInput(ECOLLADA_INPUT_SEMANTIC input) { for (int i=0; i<(int)Inputs.size(); ++i) if (Inputs[i].Semantic == input) return &Inputs[i]; return 0; } //! reads a collada input tag and adds it to the input parameter void CColladaFileLoader::readColladaInput(io::IXMLReaderUTF8* reader) { // parse param SColladaInput p; // get type int i; core::stringc semanticName = reader->getAttributeValue("semantic"); for (i=0; inputSemanticNames[i]; ++i) if (semanticName == inputSemanticNames[i]) { p.Semantic = (ECOLLADA_INPUT_SEMANTIC)i; break; } // get source p.Source = reader->getAttributeValue("source"); // add input Inputs.push_back(p); } //! parses all collada inuts inside an element and stores them in Parameters void CColladaFileLoader::readColladaInputs(io::IXMLReaderUTF8* reader, const core::stringc& parentName) { Inputs.clear(); while(reader->read()) { if (reader->getNodeType() == io::EXN_ELEMENT && inputTagName == reader->getNodeName()) { readColladaInput(reader); } else if (reader->getNodeType() == io::EXN_ELEMENT_END) { if (parentName == reader->getNodeName()) return; // end of parent reached } } // end while reader->read(); } //! parses all collada parameters inside an element and stores them in Parameters void CColladaFileLoader::readColladaParameters(io::IXMLReaderUTF8* reader, const core::stringc& parentName) { Parameters.clear(); const char* const paramNames[] = {"COLOR", "AMBIENT", "DIFFUSE", "SPECULAR", "SHININESS", "YFOV", "ZNEAR", "ZFAR", 0}; const char* const typeNames[] = {"float", "float2", "float3", 0}; while(reader->read()) { const char* nodeName = reader->getNodeName(); if (reader->getNodeType() == io::EXN_ELEMENT && paramTagName == nodeName) { // parse param SColladaParam p; // get type int i; core::stringc typeName = reader->getAttributeValue("type"); for (i=0; typeNames[i]; ++i) if (typeName == typeNames[i]) { p.Type = (ECOLLADA_PARAM_TYPE)i; break; } // get name core::stringc nameName = reader->getAttributeValue("name"); for (i=0; typeNames[i]; ++i) if (nameName == paramNames[i]) { p.Name = (ECOLLADA_PARAM_NAME)i; break; } // read parameter data inside parameter tags switch(p.Type) { case ECPT_FLOAT: case ECPT_FLOAT2: case ECPT_FLOAT3: case ECPT_FLOAT4: readFloatsInsideElement(reader, p.Floats, p.Type - ECPT_FLOAT + 1); break; // TODO: other types of data (ints, bools or whatever) default: break; } // add param Parameters.push_back(p); } else if (reader->getNodeType() == io::EXN_ELEMENT_END) { if (parentName == reader->getNodeName()) return; // end of parent reached } } // end while reader->read(); } //! parses a float from a char pointer and moves the pointer //! to the end of the parsed float inline f32 CColladaFileLoader::readFloat(const c8** p) { f32 ftmp; *p = core::fast_atof_move(*p, ftmp); return ftmp; } //! parses an int from a char pointer and moves the pointer to //! the end of the parsed float inline s32 CColladaFileLoader::readInt(const c8** p) { return (s32)readFloat(p); } //! places pointer to next begin of a token void CColladaFileLoader::findNextNoneWhiteSpace(const c8** start) { const c8* p = *start; while(*p && (*p==' ' || *p=='\n' || *p=='\r' || *p=='\t')) ++p; // TODO: skip comments <!-- --> *start = p; } //! reads floats from inside of xml element until end of xml element void CColladaFileLoader::readFloatsInsideElement(io::IXMLReaderUTF8* reader, f32* floats, s32 count) { if (reader->isEmptyElement()) return; while(reader->read()) { // TODO: check for comments inside the element // and ignore them. if (reader->getNodeType() == io::EXN_TEXT) { // parse float data core::stringc data = reader->getNodeData(); const c8* p = &data[0]; for (int i=0; i<count; ++i) { findNextNoneWhiteSpace(&p); floats[i] = readFloat(&p); } } else if (reader->getNodeType() == io::EXN_ELEMENT_END) break; // end parsing text } } //! clears all loaded data void CColladaFileLoader::clearData() { // delete all prefabs for (int i=0; i<(int)Prefabs.size(); ++i) Prefabs[i]->drop(); Prefabs.clear(); // clear all parameters Parameters.clear(); // clear all materials Materials.clear(); // clear all inputs Inputs.clear(); } //! changes the XML URI into an internal id void CColladaFileLoader::uriToId(core::stringc& str) { // currently, we only remove the # from the begin if there // because we simply don't support referencing other files. if (!str.size()) return; if (str[0] == '#') str.erase(0); } } // end namespace scene } // end namespace irr
[ "limingchina@c8d24273-d621-0410-9a95-1b5ff033c8bf" ]
[ [ [ 1, 1406 ] ] ]
8b91a7d2352a4eb3ac56d5a19e4925479a2f9a24
2fdbf2ba994ba3ed64f0e2dc75cd2dfce4936583
/spectre/dom/domelement.cpp
6f0ad4796ea211243d9ef2a95d081eee9fb73d5a
[]
no_license
TERRANZ/terragraph
36219a4e512e15a925769512a6b60637d39830bf
ea8c36070f532ad0a4af08e46b19f4ee1b85f279
refs/heads/master
2020-05-25T10:31:26.994233
2011-01-29T21:23:04
2011-01-29T21:23:04
1,047,237
0
0
null
null
null
null
UTF-8
C++
false
false
2,601
cpp
#include "domelement.h" DomElement::DomElement() : DomNode(QDomElement()) { } DomElement::DomElement(const QDomNode &qDomNode) : DomNode(qDomNode) { } string DomElement::tagName() const { return m_QDomNode.toElement().tagName().toStdString(); } string DomElement::attribute(const string &name, const string &defaultValue) const { return m_QDomNode.toElement().attribute(QString::fromStdString(name), QString::fromStdString(defaultValue)).toStdString(); } void DomElement::clearAttributes() { QDomNamedNodeMap attributes = m_QDomNode.attributes(); for(int i = 0; i <= attributes.count(); i++) { m_QDomNode.removeChild(attributes.item(i)); } } void DomElement::setTagName(const string &tagName) { m_QDomNode.toElement().setTagName(QString::fromStdString(tagName)); } void DomElement::setAttribute(const string &name, const string &value) { m_QDomNode.toElement().setAttribute(QString::fromStdString(name), QString::fromStdString(value)); } void DomElement::setAttribute(const string &name, int value) { m_QDomNode.toElement().setAttribute(QString::fromStdString(name), value); } void DomElement::setAttribute(const string &name, float value) { m_QDomNode.toElement().setAttribute(QString::fromStdString(name), value); } DomElement DomElement::elementByTagNameAndIndex(const string &tagName, int index) const { if(index < 0) return DomElement(); int i = 0; QString qTagName = QString::fromStdString(tagName); QDomElement domElement = m_QDomNode.toElement().firstChildElement(qTagName); while(!domElement.isNull() && i < index) { domElement = domElement.nextSiblingElement(qTagName); i++; } return DomElement(domElement); } list<DomElement> DomElement::elementsByTagName(const string &tagName) const { list<DomElement> listResult; QString qTagName = QString::fromStdString(tagName); QDomElement domElement = m_QDomNode.toElement().firstChildElement(qTagName); while(!domElement.isNull()) { listResult.push_back(DomElement(domElement)); domElement = domElement.nextSiblingElement(qTagName); } return listResult; } DomElement DomElement::nextElement(const string &tagName) { return DomElement(m_QDomNode.toElement().nextSiblingElement(QString::fromStdString(tagName))); } DomElement DomElement::previousElement(const string &tagName) { return DomElement(m_QDomNode.toElement().previousSiblingElement(QString::fromStdString(tagName))); }
[ [ [ 1, 90 ] ] ]
27c1d134c107e76a3ec2f923361c7d77367f398c
cd69369374074a7b4c4f42e970ee95847558e9f0
/AEDA_parta2/Manutencao.cpp
d46b12a3eb07478624c74fa86aff9a4113b7bdab
[]
no_license
miaosun/aeda-trab1
4e6b8ce3de8bb7e85e13670595012a5977258a2a
1ec5e2edec383572c452545ed52e45fb26df6097
refs/heads/master
2021-01-25T03:40:21.146657
2010-12-25T03:35:28
2010-12-25T03:35:28
33,734,306
0
0
null
null
null
null
UTF-8
C++
false
false
39,876
cpp
/////////////////////////////////////////////////////////// // Manutencao.cpp // Implementation of the Class Manutencao // Created on: 24-Out-2010 20:04:12 // Original author: Answer /////////////////////////////////////////////////////////// #include "Manutencao.h" #include "Excepcoes.h" #include "funcoes.h" #include <iostream> #include <stdlib.h> #include "Consulta.h" #include "Exame.h" #include <fstream> using namespace std; Manutencao::Manutencao() { this->Mdata = "23/08/2020"; especialidades.push_back("Dentaria"); especialidades.push_back("Ortopedia"); especialidades.push_back("Oftaumonologia"); especialidades.push_back("Psiquiatria"); especialidades.push_back("Cirurgia"); especialidades.push_back("Imagiologia"); } Manutencao::~Manutencao(){} void Manutencao::welcome() { stringstream o; for(unsigned int i=0; i<79; i++) o<<"*"; o<<endl; for (unsigned int i=0; i<3; i++) { o<<"*"; for(unsigned int j=0; j<77; j++) o<<" "; o<<"*"<<endl; } o<<"* ***** * * ***** * ***** *\n"; o<<"* * * * * * * * *\n"; o<<"* * * * * * * * *\n"; o<<"* * * * * * * * *\n"; o<<"* * * * * * * * * * * *\n"; o<<"* ***** * * * * * * ***** *\n"; for (unsigned int i=0; i<3; i++) { o<<"*"; for(unsigned int j=0; j<77; j++) o<<" "; o<<"*"<<endl; } o<<"* **** **** *** ***** *** ***** ******* ***** *\n"; o<<"* * * * * * * * * * * * * * * *\n"; o<<"* * * * * * * * * * * * * * *\n"; o<<"* * * * * * * * * * * ***** ******* ****** *\n"; o<<"* * * * * *** * * * * *** * * * * * * * *\n"; o<<"* * * * * * * * * * ***** ******* * * *\n"; for (unsigned int i=0; i<3; i++) { o<<"*"; for(unsigned int j=0; j<77; j++) o<<" "; o<<"*"<<endl; } for(unsigned int i=0; i<79; i++) o<<"*"; cout<<o.str()<<endl<<endl; system("pause"); } void Manutencao::showMenu(string titulo, vector<string> opcoes) { //clear(); unsigned int aux; for(unsigned int i=0; i<79; i++) cout<<"*"; cout<<endl<<"*****"; for(unsigned int i=0; i<69; i++) cout<<" "; cout<<"*****"<<endl<<"*****"; for(unsigned int i=0; i<26; i++) cout<<" "; cout<<"-Clinic Manager- "; for(unsigned int i=0; i<26; i++) cout<<" "; cout<<"*****"<<endl<<"*****"; for(unsigned int i=0; i<69; i++) cout<<" "; cout<<"*****"<<endl<<"*****"; aux=69-titulo.length(); if(aux%2==0) { for(unsigned int i=0; i<aux/2; i++) cout<<" "; cout<<titulo; for(unsigned int i=0; i<aux/2; i++) cout<<" "; cout<<"*****"<<endl; } else { aux=68-titulo.length(); for(unsigned int i=0; i<aux/2; i++) cout<<" "; cout<<titulo; for(unsigned int i=0; i<aux/2+1; i++) cout<<" "; cout<<"*****"<<endl; } cout<<"*****"; for(unsigned int i=0; i<69; i++) cout<<" "; cout<<"*****"<<endl; for(unsigned int i=0; i<79; i++) cout<<"*"; cout<<endl<<"*"; for(unsigned int i=0; i<77; i++) cout<<" "; cout<<"*"<<endl; for(unsigned int i=1; i<=opcoes.size(); i++) { cout<<"* "<<opcoes.at(i-1); aux=74-opcoes.at(i-1).length(); for (unsigned int j=0; j<aux; j++) cout<<" "; cout<<"*"<<endl; } aux=14-opcoes.size(); for (unsigned int i=0; i<aux; i++) { cout<<"*"; for(unsigned int j=0; j<77; j++) cout<<" "; cout<<"*"<<endl; } for(unsigned int i=0; i<79; i++) cout<<"*"; cout<<endl<<endl; } void Manutencao::menuPrincipal() { int op; vector<string> opcoes; opcoes.push_back("Escolha uma das seguintes opcoes:"); opcoes.push_back(""); opcoes.push_back("1 - Gestao de Pessoas"); opcoes.push_back("2 - Gestao de Marcacoes"); opcoes.push_back("3 - Gestao de Especialidades"); opcoes.push_back("4 - Hospitais e Centros de Saude"); opcoes.push_back(""); opcoes.push_back("0 - Gravar e sair"); showMenu("Menu Principal", opcoes); cout<<" Opcao: "; op=intinput(); switch(op) { case 1: menuPessoas(); //vai para menu pessoas menuPrincipal(); //volta ao menu principal break; case 2: menuMarcacoes(); //vai para menu marcacoes menuPrincipal(); //volta ao menu principal break; case 3: menuEspecialidades(); menuPrincipal(); case 4: menuHospitais(); menuPrincipal(); case 0: saveManutencao(); break; default: cout<<"Opcao invalida! Insira uma das opcoes disponiveis"<<endl; system("pause"); menuPrincipal(); } } void Manutencao::menuPessoas() { int op, id; Pessoa *p; vector<string> opcoes; string filename; opcoes.push_back("Escolha uma das seguintes opcoes:"); opcoes.push_back(""); opcoes.push_back("1 - Nova Pessoa");//opcao 1 if(pessoas.size()>0) { opcoes.push_back("2 - Ver detalhes de uma Pessoa");//opcao 2 opcoes.push_back("3 - Editar uma Pessoa");//opcao 3 opcoes.push_back("4 - Apagar uma Pessoa");//opcao 4 opcoes.push_back("5 - Importar Pessoas dum ficheiro");//opcao 5 opcoes.push_back("6 - Exportar Pessoas para ficheiro");//opcao 6 } else opcoes.push_back("2 - Importar Pessoas do ficheiro"); opcoes.push_back(""); opcoes.push_back("0 - Voltar atras");//opcao 7 showMenu("Gestao de Pessoas", opcoes); cout<<" Opcao: "; op=intinput(); system("cls"); if(pessoas.size()>0) { switch(op) { case 1: addPessoa(); menuPessoas(); break; case 2://ver detalhes Pessoas listaPessoas(); cout<<endl<<"Introduza o ID da Pessoa que pretende ver os detalhes: "; id=intinput(); try { showMenu("Detalhes da Pessoa", find(&pessoas, id)->imprime()); } catch (NotFound) { cout<<endl<<"Pessoa nao encontrada!"<<endl; } system("pause"); menuPessoas();//volta ao menu pessoas break; case 3://editar Pessoa listaPessoas(); cout<<endl<<"Introduza o ID da Pessoa que pretende editar: "; id=intinput(); try { p=find(&pessoas, id); editPessoas(p); } catch (NotFound) { cout<<endl<<"Pessoa nao encontrada!"<<endl; system("pause"); } menuPessoas(); break; case 4://apagar Pessoa listaPessoas(); cout<<endl<<"Introduza o ID da Pessoa que pretende apagar: "; id=intinput(); try { p=find(&pessoas, id); showMenu("Detalhes da Pessoa", p->imprime()); removePessoa(id); } catch (NotFound) { cout<<endl<<"Pessoa nao encontrada!"<<endl; system("pause"); } menuPessoas(); break; case 5://importar pessoas system("cls"); cout<<" --Importar Pessoas--"<<endl<<endl; cout<<"Nome do ficheiro: "; getline(cin, filename); loadPessoas(filename); system("pause"); menuPessoas(); break; case 6://exportar pessoas system("cls"); cout<<" --Exportar Pessoas--"<<endl<<endl; cout<<"Nome do ficheiro para onde vai exportar: "; getline(cin, filename); savePessoas(filename); system("pause"); menuPessoas(); break; case 0: break; default: cout<<"Opcao invalida! Insira uma das opcoes disponiveis"<<endl; system("pause"); menuPessoas(); } } else { switch(op) { case 1://criar Pessoa addPessoa(); menuPessoas(); break; case 2://importar Pessoas system("cls"); cout<<" --Importar Pessoas--"<<endl<<endl; cout<<"Nome do ficheiro: "; getline(cin, filename); loadPessoas(filename); system("pause"); menuPessoas(); break; case 0://voltar ao menu anterior break; default: cout<<"Opcao invalida! Insira uma das opcoes disponiveis"<<endl; system("pause"); menuPessoas(); } } } void Manutencao::menuMarcacoes() { Marcacao *m; int op; vector<string> opcoes; string filename; opcoes.push_back("Escolha uma das seguintes opcoes:"); opcoes.push_back(""); opcoes.push_back("1 - Nova Marcacao");//opcao 1 if(marcacoes.size()>0) { opcoes.push_back("2 - Ver detalhes de uma Marcacao");//opcao 2 opcoes.push_back("3 - Editar uma Marcacao");//opcao 3 opcoes.push_back("4 - Apagar uma Marcacao");//opcao 4 opcoes.push_back("5 - Importar Marcacao dum ficheiro");//opcao 5 opcoes.push_back("6 - Exportar Marcacao para ficheiro");//opcao 6 } else opcoes.push_back("2 - Importar Marcacao do ficheiro"); opcoes.push_back(""); opcoes.push_back("0 - Voltar atras"); showMenu("Gestao de Marcacao", opcoes); cout<<" Opcao: "; op=intinput(); system("cls"); if(marcacoes.size()>0) { switch(op) { case 1: addMarcacao(); menuMarcacoes(); break; case 2://ver detalhes marcacoes listaMarcacoes(); cout<<endl<<"Introduza o ID da Marcacao que pretende ver os detalhes: "; int id; id=intinput(); try { m=find(&marcacoes, id); showMenu("Detalhes da Marcacao", m->imprime()); } catch (NotFound) { cout<<endl<<"Marcacao nao encontrada!"<<endl; } system("pause"); menuMarcacoes();//volta ao menu marcacoes break; case 3://editar Marcacao listaMarcacoes(); cout<<endl<<"Introduza o ID da Marcacao que pretende editar: "; id=intinput(); try { m=find(&marcacoes, id); editMarcacoes(m); } catch (NotFound) { cout<<endl<<"Marcacao nao encontrada!"<<endl; system("pause"); } menuMarcacoes(); break; case 4://apagar marcacao listaMarcacoes(); cout<<endl<<"Introduza o ID da Marcacao que pretende apagar: "; id=intinput(); try { m=find(&marcacoes, id); showMenu("Detalhes da Marcacao", m->imprime()); system("pause"); removeMarcacao(id); } catch (NotFound) { cout<<endl<<"Marcacao nao encontrada!"<<endl; system("pause"); } menuMarcacoes(); break; case 5://importar marcacoes system("cls"); cout<<" --Importar Marcacoes--"<<endl<<endl; cout<<"Nome do ficheiro: "; getline(cin, filename); loadMarcacoes(filename); system("pause"); menuMarcacoes(); break; case 6://exportar marcacoes system("cls"); cout<<" --Exportar Marcacoes--"<<endl<<endl; cout<<"Nome do ficheiro para onde vai exportar: "; getline(cin, filename); saveMarcacoes(filename); system("pause"); menuMarcacoes(); break; case 0://voltar ao menu anterior break; default: cout<<"Opcao invalida! Insira uma das opcoes disponiveis"<<endl; system("pause"); menuMarcacoes(); } } else { switch(op) { case 1: addMarcacao(); menuMarcacoes(); break; case 2://importar Pessoas system("cls"); cout<<" --Importar Marcacoes--"<<endl<<endl; cout<<"Nome do ficheiro: "; getline(cin, filename); loadMarcacoes(filename); cout<<"marcacao size: "<<marcacoes.size()<<endl; system("pause"); menuMarcacoes(); break; case 0://voltar ao menu anterior break; default: cout<<"Opcao invalida! Insira uma das opcoes disponiveis"<<endl; system("pause"); menuMarcacoes(); } } } void Manutencao::menuEspecialidades() { vector<string> opcoes; int op; opcoes.push_back("Escolha uma das seguintes opcoes:"); opcoes.push_back(""); opcoes.push_back("1 - Ver Especialidades"); opcoes.push_back("2 - Nova Especialidade"); opcoes.push_back(""); opcoes.push_back("0 - Voltar atras"); showMenu("Gestao de especialidades", opcoes); cout<<" Opcao: "; op=intinput(); system("cls"); switch (op) { case 1: listaEspecialidades(); system("pause"); menuEspecialidades(); break; case 2: addEspecialidade(); menuEspecialidades(); break; case 0: break; default: menuEspecialidades(); } } void Manutencao::menuDoentesAntigos() { vector<string> opcoes; int op; opcoes.push_back("Escolha uma das seguintes opcoes:"); opcoes.push_back(""); opcoes.push_back("1 - Adicionar um Doente antigo"); opcoes.push_back("2 - Apagar um Doente antigo"); opcoes.push_back("3 - Ver Doentes Antigos"); opcoes.push_back(""); opcoes.push_back("0 - Voltar atras"); showMenu("Doentes Antigos", opcoes); cout<<" Opcao: "; op=intinput(); system("cls"); switch (op) { case 1: addDoenteAntigo(); menuDoentesAntigos(); break; case 2: apagaDoenteAntigo(); menuDoentesAntigos(); break; case 3: listaDoentesAntigos(); system("pause"); menuDoentesAntigos(); break; case 0: break; default: menuHospitais(); } } vector<Marcacao *> Manutencao::findDoeMarc(Pessoa * doente) { vector<Marcacao *> d_Marc; vector<Marcacao *>::iterator it; for(it=marcacoes.begin(); it!=marcacoes.end(); it++) { if((*it)->getDoente() == doente) d_Marc.push_back(*it); } return d_Marc; } bool Manutencao::tem_mais2Anos(vector<Marcacao *> d_Marc) { return false; } void Manutencao::addDoenteAntigo() { Pessoa *p; Pessoa *d; string data; int op, id; vector<Marcacao *> d_doeMar; cout<<"Como quer adicionar doente antigo? (0 para voltar)\n"; cout<<"1. Insere o ID do doente\n2. Insere a data da ultima marcacao do doente\n"; op=intinput(); switch(op) { case 0: return; break; case 1: listaDoentes(); cout<<"\nID do doente: "; id=intinput(); p = find(&pessoas, id); while(p->getTipo() != "Doente") { cout<<"Nao tem nenhum doente com esse ID, tenta novamente: "; id = intinput(); p = find(&pessoas, id); } d = p; d_doeMar = findDoeMarc(d); if(d_doeMar.size()==0) cout<<"O doente ainda nao realizou nenhuma marcacao!\n"; else { cout<<"As marcacoes o doente tem: \n"; for(unsigned int i=0; i<d_doeMar.size(); i++) cout<<"\t"<<i<<" "<<d_doeMar[i]->getTipo()<<" "<<d_doeMar[i]->getData()<<endl; } break; case 2: cout<<"Insere a data da ultima marcacao o doente fez:\n"; data=inserirData(); break; default: addDoenteAntigo(); } } void Manutencao::apagaDoenteAntigo() { } void Manutencao::listaDoentesAntigos() { } bool Manutencao::mais2Anos(string data) { string Mano_s = Mdata.substr(Mdata.find_last_of('/')); string Mmes_s = Mdata.substr(Mdata.find_first_of('/'), Mdata.find_last_of('/')); string Mdia_s = Mdata.substr(0, Mdata.find_first_of('/')); string ano_s = data.substr(data.find_last_of('/')); string mes_s = data.substr(data.find_first_of('/'), data.find_last_of('/')); string dia_s = data.substr(0, data.find_first_of('/')); int Mano = atoi(Mano_s.c_str()); int Mmes = atoi(Mmes_s.c_str()); int Mdia = atoi(Mdia_s.c_str()); int ano = atoi(ano_s.c_str()); int mes = atoi(mes_s.c_str()); int dia = atoi(dia_s.c_str()); if(Mano-ano > 2) return true; else if(Mano-ano==2 && Mmes > mes) return true; else if(Mano-ano==2 && Mmes==mes && Mdia > dia) return true; else return false; } void Manutencao::menuHospitais() { vector<string> opcoes; int op; opcoes.push_back("Escolha uma das seguintes opcoes:"); opcoes.push_back(""); opcoes.push_back("1 - Novo Hospital ou Centro de Saude"); opcoes.push_back("2 - Adicionar Especialidade para Hospital ou Centro de Saude"); opcoes.push_back("3 - Ver Hospital ou Centro de Saude"); opcoes.push_back(""); opcoes.push_back("0 - Voltar atras"); showMenu("Hospitais e Centros de Saude", opcoes); cout<<" Opcao: "; op=intinput(); system("cls"); switch (op) { case 1: addHospital(); menuHospitais(); break; case 2: addEsp_Hosp(); break; case 3: listaHospitais(); system("pause"); menuHospitais(); break; case 0: break; default: menuHospitais(); } } void Manutencao::addHospital() { string nome, morada, tipo; int distancia, op; cout<<"Hospital ou Centro de saude pretende de registar?(1 ou 2, 0 para sair)\n1.Hospital\n2.Centro de Saude\n"; op=intinput(); switch(op) { case 0: return; break; case 1: tipo = "Hospital"; break; case 2: tipo = "Centro de Saude"; break; default: cout<<"A opcao nao e valida, escolhe um das opcoes disponivies!\n"; system("pause"); cout<<endl; addHospital(); } cout<<"Nome do "<<tipo<<": "; getline(cin, nome); cout<<"Morada do "<<tipo<<": "; getline(cin, morada); cout<<"Distancia: "; distancia = intinput(); Hospitais hps(nome, morada, distancia, tipo); if(hospitais.empty()) { hospitais.push(hps); return; } else //////////////////////nao ta a funcionar { //estrutura temporaria para guardar hospitais retiradas da fila vector<Hospitais> temp; while(!hospitais.empty()) { Hospitais hpt = hospitais.top(); if(hpt < hps) hospitais.push(hps); else { temp.push_back(hpt); hospitais.pop(); } } vector<Hospitais>::iterator it; for(it=temp.end(); it!=temp.begin(); it--) hospitais.push(*it); } } void Manutencao::addEsp_Hosp() { int op, op2; vector<Hospitais> h_temp; listaHospitais(); op = intinput(); for(int i=0; i<op-1; i++) { Hospitais hsp = hospitais.top(); hospitais.pop(); h_temp.push_back(hsp); } string esp; cout<<"Novo Especialidade vai ser disponivel: (uma so por vez)\n"; cout<<"1. Escolhe do base do bados do sistema\n"; cout<<"2. Adicionar uma nova especialidade\n"; cout<<"0. Sair daqui."; op=intinput(); switch(op) { case 0: return; break; case 1: listaEspecialidades(); esp = escolheEspecialidade(); h_temp.back().esp_hps.push_back(esp); break; case 2: cout<<"Especialidade: (uma so por vez)\n"; getline(cin, esp); h_temp.back().esp_hps.push_back(esp); } for(unsigned int i=0; i<h_temp.size(); i++) { hospitais.push(h_temp[i]); } system("pause"); } void Manutencao::listaHospitais() { stringstream ss; int i=0; priority_queue<Hospitais> temp = hospitais; if(hospitais.empty()) { cout<<"Nao existe nenhum hospital ou centro de saude registado!\n"; return; } while(!temp.empty()) { ss<<i+1<<". "<<temp.top().getName()<<endl; temp.pop(); } cout<<ss.str(); } string Manutencao::escolheEspecialidade() { int op; listaEspecialidades(); do { cout<<"Especialidade: "; op=intinput(); }while(op<0||op>especialidades.size()-1); return especialidades.at(op); } void Manutencao::listaEspecialidades() { system("cls"); for(unsigned int i=0; i<especialidades.size(); i++) cout<<i<<" - "<<especialidades.at(i)<<endl; cout<<endl; } void Manutencao::addEspecialidade() { string esp; listaEspecialidades(); cout<<"Nome da nova especialidade: "; cin>>esp; especialidades.push_back(esp); } void Manutencao::addPessoa() { string nome, dataNas, tipo, esp, hor, mor, car, s; vector<string> opcoes; double venc; int op; Medico * m; Funcionario * f; Doente * d; opcoes.push_back("Escolha uma das seguintes opcoes:"); opcoes.push_back(""); opcoes.push_back("1 - Novo Medico"); opcoes.push_back("2 - Novo Funcionario"); opcoes.push_back("3 - Novo Doente"); opcoes.push_back(""); opcoes.push_back("0 - Voltar atras"); showMenu("Adicionar Pessoa", opcoes); cout<<" Opcao: "; op=intinput(); system("cls"); switch(op) { case 1: //medico tipo = "Medico"; cout<<"Nome da Pessoa: "; getline(cin, nome); cout<<"Data de Nascimento(dia, mes, ano) (separado com espaco, ex: 23 08 2010):\n"; dataNas=inserirData(); esp=escolheEspecialidade(); hor=inserirHorario(); venc = inserirVencimento(); m = new Medico(nome, dataNas, tipo, esp, hor, venc); pessoas.push_back(m); cout<<"Pretende de associar um Funcionario agora(s/n)? "; getline(cin, s); if(s=="s") associarFuncionario(m); else return; break; case 2: //funcionario tipo = "Funcionario"; cout<<"Nome da Pessoa: "; getline(cin, nome); cout<<"Data de Nascimento(dia, mes, ano) (separado com espaco, ex: 23 08 2010):\n"; dataNas=inserirData(); cout<<"Cargo: "; getline(cin, car); venc = inserirVencimento(); f = new Funcionario(nome, dataNas, tipo, car, venc); pessoas.push_back(f); break; case 3: //doente tipo = "Doente"; cout<<"Nome da Pessoa: "; getline(cin, nome); cout<<"Data de Nascimento(dia, mes, ano) (separado com espaco, ex: 23 08 2010):\n"; dataNas=inserirData(); cout<<"Morada: "; getline(cin, mor); d = new Doente(nome, dataNas, tipo, mor); pessoas.push_back(d); break; case 0: //sair default: break; } if(op==1||op==2||op==3) { showMenu("Nova Pessoa", pessoas.back()->imprime()); system("pause"); } } void Manutencao::removePessoa(int id) { int indice; for(unsigned int i=0; i<pessoas.size(); i++) if(id == pessoas[i]->getId()) indice = i; int op; vector<string> opcoes; opcoes.push_back("Tem a certeza que quer apagar a Pessoa?"); opcoes.push_back(""); opcoes.push_back("1 - Nao"); opcoes.push_back("2 - Sim"); showMenu("Apagar Pessoa", opcoes); cout<<" Opcao: "; op=intinput(); switch(op) { case 1: break; case 2: pessoas.erase(pessoas.begin()+indice); break; default: cout<<"Opcao invalida! Insira uma das opcoes disponiveis"<<endl; system("pause"); removePessoa(id); } } void Manutencao::addMarcacao() { vector<string> opcoes; int op, id; stringstream s; vector<string> v; string tipo, data, hora, sala, especialidade; Consulta * c; Exame * e; Pessoa * p; Pessoa * m; Pessoa * d; try { system("cls"); listaDoentes(); cout<<"Qual o doente que vai ter a Marcacao (ID): "; id=intinput(); p = find(&pessoas, id); while(p->getTipo() != "Doente") { cout<<"Nao tem nenhum doente com esse ID, tenta novamente: "; id = intinput(); p = find(&pessoas, id); } d = p; } catch (NotFound) { cout<<"Nao existe esse ID no sistema!"<<endl; system("pause"); return; } opcoes.push_back("Escolha um dos seguintes tipos de marcacao:"); opcoes.push_back(""); opcoes.push_back("1 - Consulta"); opcoes.push_back("2 - Exame"); opcoes.push_back(""); opcoes.push_back("0 - Voltar atras"); showMenu("Adicionar Marcacao", opcoes); cout<<" Opcao: "; op=intinput(); system("cls"); switch(op) { case 1: try { cout<<"Quer associar medico de qual area?\n "; system("pause"); listaEspecialidades(); especialidade = escolheEspecialidade(); d->addEspec(especialidade); d->showMedicos(); cout<<endl<<"Qual o medico que vai dar a consulta (ID): "; id=intinput(); p = find(d->getMedicos(especialidade), id); m=p; tipo = "Consulta"; cout<<"Data da Consulta: "; data=inserirData(); cout<<"Hora da Consulta: "; getline(cin, hora); c = new Consulta(data, hora, tipo, m, d); marcacoes.push_back(c); } catch (NotFound) { cout<<"Nao existe esse ID no sistema!"<<endl; system("pause"); return; } break; case 2: try { cout<<"Quer associar medico de qual area?\n "; system("pause"); listaEspecialidades(); especialidade = escolheEspecialidade(); d->addEspec(especialidade); d->showMedicos(); cout<<endl<<"Qual o medico que vai fazer o exame (ID): "; id=intinput(); p = find(d->getMedicos(especialidade), id); m=p; tipo = "Exame"; cout<<"Data do Exame: "; data=inserirData(); cout<<"Hora do Exame: "; getline(cin, hora); cout<<"Sala do Exame: "; getline(cin, sala); e = new Exame(data, hora, tipo, m, d, sala); marcacoes.push_back(e); } catch (NotFound) { cout<<"Nao existe esse ID no sistema!"<<endl; system("pause"); return; } break; case 0: return; break; default: addMarcacao(); break; } if(op==1||op==2) { system("pause"); showMenu("Nova Marcacao", marcacoes.back()->imprime()); system("pause"); } } void Manutencao::removeMarcacao(int id) { int indice; for(unsigned int i=0; i<marcacoes.size(); i++) if(id == marcacoes[i]->getId()) indice = i; int op; vector<string> opcoes; opcoes.push_back("Tem a certeza que quer apagar a Marcacao?"); opcoes.push_back(""); opcoes.push_back("1 - Nao"); opcoes.push_back("2 - Sim"); showMenu("Apagar Marcacao", opcoes); cout<<" Opcao: "; op=intinput(); switch(op) { case 1: break; case 2: marcacoes.erase(marcacoes.begin()+indice); break; default: cout<<"Opcao invalida! Insira uma das opcoes disponiveis"<<endl; system("pause"); removeMarcacao(id); } } void Manutencao::listaMedicos(string especialidade) { vector<Pessoa *>::iterator it=pessoas.begin(); cout<<especialidade<<endl; cout<<"\tMedicos: "<<endl; while(it!=pessoas.end()) { if((*it)->getTipo() == "Medico") { if((*it)->getEspecialidade() == especialidade) cout<<"\t\t"<<(*it)->toList()<<endl; } it++; } } void Manutencao::listaMedicos() { vector<Pessoa *>::iterator it=pessoas.begin(); cout<<"Medicos: "<<endl; while(it!=pessoas.end()) { if((*it)->getTipo() == "Medico") { cout<<"\t"<<(*it)->toList()<<endl; } it++; } } void Manutencao::listaFuncionarios() { vector<Pessoa *>::iterator it=pessoas.begin(); cout<<"\nFuncionario: "<<endl; it=pessoas.begin(); while(it!=pessoas.end()) { if((*it)->getTipo() == "Funcionario") { cout<<"\t"<<(*it)->toList()<<endl; } it++; } } void Manutencao::listaDoentes() { vector<Pessoa *>::iterator it=pessoas.begin(); cout<<"\nDoente: "<<endl; it=pessoas.begin(); while(it!=pessoas.end()) { if((*it)->getTipo() == "Doente") { cout<<"\t"<<(*it)->toList()<<endl; } it++; } } void Manutencao::listaPessoas() { system("cls"); cout<<" --Pessoas no sistema--"<<endl<<endl; vector<Pessoa *>::iterator it=pessoas.begin(); cout<<"\t|ID| Nome |\n\n"; listaMedicos(); listaFuncionarios(); listaDoentes(); cout<<endl; } void Manutencao::listaMarcacoes() { system("cls"); cout<<" --Marcacoes no sistema--"<<endl<<endl; vector<Marcacao *>::iterator it=marcacoes.begin(); cout<<"\t|ID|\n\n"; cout<<"Consulta: "<<endl; while(it!=marcacoes.end()) { if((*it)->getTipo() == "Consulta") { cout<<"\t"<<(*it)->toList()<<endl; } it++; } cout<<"\nExame: "<<endl; it=marcacoes.begin(); while(it!=marcacoes.end()) { if((*it)->getTipo() == "Exame") { cout<<"\t"<<(*it)->toList()<<endl; } it++; } cout<<endl; } void Manutencao::editPessoas(Pessoa *p) { Medico *m; vector<string> opcoes; string nome, dataNas, tipo, esp, hor, morada, cargo; double venc; int op, id; Pessoa * p2; opcoes = p->editPessoa(); opcoes.push_back(""); opcoes.push_back("0 - Voltar atras"); showMenu("Editar Pessoa", opcoes); cout<<" Opcao: "; op=intinput(); system("cls"); if(p->getTipo()=="Medico") { switch(op) { case 1://nome cout<<"Novo nome de Medico: "; getline(cin, nome); p->setName(nome); break; case 2:// data nasc cout<<"Novo Data de Nascimento de Medico: "; dataNas=inserirData(); p->setDataNascimento(dataNas); break; case 3://especialidade cout<<"Novo Especialidade de Medico: "; getline(cin, esp); p->setEspecialidade(esp); break; case 4://horario hor=inserirHorario(); p->setHorario(hor); break; case 5://vencimento venc=inserirVencimento(); p->setVencimento(venc); break; case 6: associarFuncionario(p); break; case 0: return; break; default: editPessoas(p); } } else if(p->getTipo()=="Doente") { string especialidade; switch(op) { case 1://nome cout<<"Nome de Doente: "<<p->getName()<<endl; cout<<"Novo nome de Doente: "; getline(cin, nome); p->setName(nome); break; case 2://data nasc cout<<"Novo Data de Nascimento de Doente: "; dataNas = inserirData(); p->setDataNascimento(dataNas); break; case 3://morada cout<<"Novo Morada de Doente: "; getline(cin, morada); p->setMorada(morada); break; case 4://add medico try { cout<<"Quer associar medico de qual area?\n "; system("pause"); listaEspecialidades(); especialidade = escolheEspecialidade(); p->addEspec(especialidade); listaMedicos(especialidade); cout<<"Qual o medico que quer associar (ID): "; id=intinput(); p2 = find(&pessoas, id); while(p2->getTipo() != "Medico") { cout<<"Nao tem nenhum medico com esse ID, tenta novamente: "; id = intinput(); p2 = find(&pessoas, id); } p->addMedico(p2, especialidade); } catch(NotFound) { cout<<"Nao existe esse ID no sistema!"<<endl; system("pause"); } break; case 5://ver medicos p->showMedicos(); system("pause"); editPessoas(p); break; case 0: return; break; default: editPessoas(p); } } else if(p->getTipo()=="Funcionario") { switch(op) { case 1: cout<<"Novo nome de Funcinario: "; getline(cin, nome); p->setName(nome); break; case 2: cout<<"Novo Data de Nascimento de Funcionario: "; dataNas=inserirData(); p->setDataNascimento(dataNas); break; case 3://cargo cout<<"Novo cargo de Funcionario: "; getline(cin, cargo); p->setCargo(cargo); break; case 4://vencimento venc=inserirVencimento(); p->setVencimento(venc); break; case 0: return; break; default: editPessoas(p); } } if(op>0) { showMenu("Pessoa", p->imprime()); system("pause"); } } void Manutencao::editMarcacoes(Marcacao * m) { vector<string> opcoes; string data, hora, tipo, sala, especialidade; int op, id; Pessoa * p; opcoes = m->editMarcacao(); opcoes.push_back(""); opcoes.push_back("0 - Voltar atras"); showMenu("Editar Marcacao", opcoes); cout<<" Opcao: "; op=intinput(); system("cls"); if(m->getTipo()=="Consulta") { switch(op) { case 1: //data cout<<"Novo data de Consulta: "; data=inserirData(); m->setData(data); break; case 2: //hora cout<<"Novo Hora de Consulta: "; getline(cin, hora); m->setHora(hora); break; case 3: //medico try { m->getDoente()->showMedicos(); cout<<endl<<"Qual o medico que vai dar a consulta (ID): "; id=intinput(); p = find(m->getDoente()->getMedicos(especialidade), id); m->setMedico(p); } catch (NotFound) { cout<<"Nao existe esse ID no sistema!"<<endl; system("pause"); } break; case 0: return; break; default: editMarcacoes(m); } } else if(m->getTipo()=="Exame") { switch(op) { case 1://data cout<<"Nova data de Exame: "; data=inserirData(); m->setData(data); break; case 2://hora cout<<"Nova hora de Exame: "; data=inserirData(); m->setHora(hora); break; case 3: //medico try { m->getDoente()->showMedicos(); cout<<endl<<"Qual o medico que vai fazer o exame (ID): "; id=intinput(); p = find(m->getDoente()->getMedicos(especialidade), id); m->setMedico(p); } catch (NotFound) { cout<<"Nao existe esse ID no sistema!"<<endl; system("pause"); } break; case 4://sala cout<<"Nova Sala de Exame: "; getline(cin, sala); m->setSala(sala); break; case 0: return; break; default: editMarcacoes(m); } } if(op>0&&op<5) { showMenu("Marcacao", m->imprime()); system("pause"); } } void Manutencao::loadPessoas(string filename) { Pessoa *p; Funcionario *f; stringstream s; unsigned int size; string linha; vector<string> v; ifstream myfile (filename.c_str()); if(myfile.is_open()) { getline(myfile, linha); s<<linha; s>>size;//primeira linha com numero de pessoas /* * falta implementar a excepcao */ try { if(size>0) { for(unsigned int i=0; i<size; i++) { getline(myfile, linha); v=split('|', linha); if(v[3]=="Medico") { double venc = atof(v[6].c_str()); Medico *m = new Medico(v[1].c_str(),v[2].c_str(),v[3].c_str(),v[4].c_str(),v[5].c_str(),venc); if(atoi(v[7].c_str())==0) m->setFuncionario(0); else { p=find(&pessoas,atoi(v[7].c_str())); m->setFuncionario(p); } pessoas.push_back(m); } else if(v[3]=="Doente") { int n_medicos = atoi(v[5].c_str()); Doente *d = new Doente(v[1].c_str(),v[2].c_str(),v[3].c_str(),v[4].c_str()); Pessoa *med; if(n_medicos != 0) { for(unsigned int i=0; i<n_medicos; i++) { med = find(&pessoas, atoi(v[6+i].c_str())); d->addEspec(med->getEspecialidade()); d->addMedico(med); } } pessoas.push_back(d); } else if(v[3]=="Funcionario") { double venc = atof(v[5].c_str()); Funcionario *f = new Funcionario(v[1].c_str(),v[2].c_str(),v[3].c_str(),v[4].c_str(), venc); pessoas.push_back(f); } } cout<<endl<<endl<<"Pessoas importadas com sucesso!"<<endl<<endl; } myfile.close(); } catch (NotFound) { cout<<"nao fiz load corretamente, tem possiblidade de perder dados!\n"; system("pause"); } } else { cout<<"Nao foi possivel abrir o ficheiro "<<filename<<"!"<<endl<<endl; } } void Manutencao::savePessoas(string filename) { vector<Pessoa *>::iterator it; ofstream myfile (filename.c_str()); if(myfile.is_open()) { myfile<<pessoas.size()<<endl; /*myfile<<"Medico:\n"; for(it=pessoas.begin(); it!=pessoas.end(); it++) if((*it)->getTipo()=="Medico") myfile<<(*it)->toString()<<endl; myfile<<"\nDoente:\n"; for(it=pessoas.begin(); it!=pessoas.end(); it++) if((*it)->getTipo()=="Doente") myfile<<(*it)->toString()<<endl; myfile<<"\nFuncionario:\n"; for(it=pessoas.begin(); it!=pessoas.end(); it++) if((*it)->getTipo()=="Funcionario") myfile<<(*it)->toString()<<endl;*/ for(it=pessoas.begin(); it!=pessoas.end(); it++) myfile<<(*it)->toString()<<endl; myfile.close(); cout<<endl<<endl<<"Pessoas exportadas com sucesso!"<<endl; } else { cout<<"Nao foi possivel abrir o ficheiro!"<<endl<<endl; system("pause"); } } void Manutencao::saveHospitais(string filename) { priority_queue<Hospitais> temp = hospitais; ofstream myfile (filename.c_str()); if(myfile.is_open()) { myfile<<hospitais.size()<<endl; while(!temp.empty()) { cout<<"|"; myfile<<temp.top().toString(); for(unsigned int i=0; i<temp.top().esp_hps.size(); i++) { myfile<<temp.top().esp_hps[i]<<"|"; } myfile<<endl; temp.pop(); } myfile.close(); cout<<endl<<endl<<"Hospitais exportadas com sucesso!"<<endl; } else { cout<<"Nao foi possivel abrir o ficheiro!"<<endl<<endl; system("pause"); } } void Manutencao::loadHospitais(string filename) { stringstream s; unsigned int size; string linha; vector<string> v; ifstream myfile (filename.c_str()); if(myfile.is_open()) { getline(myfile, linha); s<<linha; s>>size; if(size>0) { for(unsigned int i=0; i<size; i++) { getline(myfile, linha); v=split('|', linha); Hospitais hsp(v[0].c_str(),v[1].c_str(),atoi(v[2].c_str()),v[3].c_str()); //isto aqui tem erro hospitais.push(hsp); for(unsigned int i=4; i<v.size(); i++) { hsp.esp_hps.push_back(v[i]); } } cout<<endl<<endl<<"Hospitais importadas com sucesso!"<<endl<<endl; } myfile.close(); } else { cout<<"Nao foi possivel abrir o ficheiro "<<filename<<"!"<<endl<<endl; } } void Manutencao::loadMarcacoes(string filename) { Pessoa *m; Pessoa *d; stringstream s; unsigned int size; string linha; vector<string> v; ifstream myfile (filename.c_str()); if(myfile.is_open()) { getline(myfile, linha); s<<linha; s>>size;//primeira linha com numero de pessoas /* * falta implementar a excepcao */ try { if(size>0) { for(unsigned int i=0; i<size; i++) { getline(myfile, linha); v=split('|', linha); if(v[3]=="Consulta") { int id_med = atoi(v[4].c_str()); int id_doe = atoi(v[5].c_str()); m = find(&pessoas, id_med); d = find(&pessoas, id_doe); Consulta *c = new Consulta(v[1].c_str(),v[2].c_str(),v[3].c_str(),m,d); marcacoes.push_back(c); } else if(v[3]=="Exame") { int id_med = atoi(v[4].c_str()); int id_doe = atoi(v[5].c_str()); m = find(&pessoas, id_med); d = find(&pessoas, id_doe); Exame *e = new Exame(v[1].c_str(),v[2].c_str(),v[3].c_str(),m,d,v[6].c_str()); marcacoes.push_back(e); } } cout<<endl<<endl<<"Marcacoes importadas com sucesso!"<<endl<<endl; } } catch (NotFound) { cout<<"nao fiz load corretamente, tem possiblidade de perder dados!\n"; system("pause"); } myfile.close(); } else { cout<<"Nao foi possivel abrir o ficheiro "<<filename<<"!"<<endl<<endl; } } void Manutencao::saveMarcacoes(string filename) { vector<Marcacao *>::iterator it; ofstream myfile (filename.c_str()); if(myfile.is_open()) { myfile<<marcacoes.size()<<endl; for(it=marcacoes.begin(); it!=marcacoes.end(); it++) myfile<<(*it)->toString()<<endl; myfile.close(); cout<<endl<<endl<<"Marcacoes exportadas com sucesso!"<<endl; } else { cout<<"Nao foi possivel abrir o ficheiro!"<<endl<<endl; system("pause"); } } void Manutencao::saveManutencao() { savePessoas("pessoas.dll"); saveMarcacoes("marcacoes.dll"); saveHospitais("hospitais.dll"); } void Manutencao::startManutencao() { loadPessoas("pessoas.dll"); loadMarcacoes("marcacoes.dll"); loadHospitais("hospitais.dll"); welcome(); menuPrincipal(); } void Manutencao::associarFuncionario(Pessoa * medico) { Pessoa * p; int id; system("cls"); cout<<" --Funcionarios no sistema--"<<endl<<endl; listaFuncionarios(); cout<<"Insere o ID do funcionario que pretende de associar: "; id = intinput(); try { p = find(&pessoas, id); while(p->getTipo() != "Funcionario") { cout<<"Nao tem nenhum funcionario com esse ID, tenta novamente: "; id = intinput(); p = find(&pessoas, id); } medico->setFuncionario(p); } catch (NotFound) { cout<<"Nao existe o ID no sistema\n"; system("pause"); } } /*string Manutencao::imprime(){ return NULL; }*/
[ "miaosun88@9ca0f86a-2074-76d8-43a5-19cf18205b40", "gasparlafurtado@9ca0f86a-2074-76d8-43a5-19cf18205b40" ]
[ [ [ 1, 1316 ], [ 1318, 1821 ] ], [ [ 1317, 1317 ] ] ]
3c5bd7f98c64e48f48bfbe7fba20d1891f58fd83
a01b67b20207e2d31404262146763d3839ee833d
/trunk/Projet/trunk/Ui/mainwindow.cpp
773a90a7ba19661302d9d6bf16f447e64e6fc899
[]
no_license
BackupTheBerlios/qtfin-svn
49b59747b6753c72a035bf1e2e95601f91f5992c
ee18d9eb4f80a57a9121ba32dade96971196a3a2
refs/heads/master
2016-09-05T09:42:14.189410
2010-09-21T17:34:43
2010-09-21T17:34:43
40,801,620
0
0
null
null
null
null
UTF-8
C++
false
false
26,337
cpp
#include "mainwindow.h" #include "monofin.h" #include "startupdialog.h" #include "lib/qtwindowlistmenu.h" #include "Drawing/paintingscene.h" #include "Ui/graphic.h" #include <QtCore/QDebug> #include <QtCore/QDir> #include <QtCore/QRect> #include <QtCore/QSettings> #include <QtGui/QAction> #include <QtGui/QActionGroup> #include <QtGui/QButtonGroup> #include <QtGui/QDockWidget> #include <QtGui/QFileDialog> #include <QtGui/QMenu> #include <QtGui/QMenuBar> #include <QtGui/QMessageBox> #include <QtGui/QMdiArea> #include <QtGui/QMdiSubWindow> #include <QtGui/QStatusBar> #include <QtGui/QToolBar> // PUBLIC MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { if (objectName().isEmpty()) setObjectName(QString::fromUtf8("MainWindow")); // set the user interface _mdiArea = new QMdiArea(this); _mdiArea->setViewMode(QMdiArea::TabbedView); _mdiArea->setTabShape(QTabWidget::Triangular); setCentralWidget(_mdiArea); connect(_mdiArea, SIGNAL(subWindowActivated(QMdiSubWindow*)), this, SLOT(updateMenus())); connect(_mdiArea, SIGNAL(subWindowActivated(QMdiSubWindow*)), this, SLOT(updateToolBars())); connect(_mdiArea, SIGNAL(subWindowActivated(QMdiSubWindow*)), this, SLOT(updateWindowTitle())); _startupDialog = new StartupDialog(this); #ifdef Q_OS_MAC _qmPath = ":/translations"; _libraryPath = ":/library"; #else _qmPath = qApp->applicationDirPath() + "/translations"; _libraryPath = qApp->applicationDirPath() + "/library"; #endif // Q_OS_MAC _appTranslator.load("monofin_" + QLocale::system().name(), _qmPath); _currentLanguage = _appTranslator.translate("MainWindow", "English"); qApp->installTranslator(&_appTranslator); createActions(); createMenus(); createDocks(); updateLibrary(); createStatusBar(); createToolBars(); setConnections(); readSettings(); retranslateUi(); setWindowTitle(tr("Monofin")); setWindowIcon(QIcon(":/icons/general/logo.png")); } #include "layerparameters.h" void MainWindow::configurate() { if (activeMonofin()) activeMonofin()->configurate(); } // PROTECTED void MainWindow::changeEvent(QEvent *e) { switch (e->type()) { case QEvent::LanguageChange: retranslateUi(); break; default: break; } } void MainWindow::closeEvent(QCloseEvent *event) { _mdiArea->closeAllSubWindows(); if (activeMonofin()) event->ignore(); else { event->accept(); writeSettings(); } } // PRIVATE SLOTS void MainWindow::about() { QMessageBox::about(this, tr("About %1").arg(QApplication::applicationName()), tr("<h2>Monofin %1</h2>" "<p>Copyright &copy; 2009 %2</p>" "<p>" "Chaudet Yoann <br/>" "Garcia Paul <br/>" "Gautier Quentin <br/>" "Le Squer Nicolas <br/>" "Musset Nicolas <br/>" "Villoing Xavier <br/>" "</p>") .arg(QApplication::applicationVersion()).arg(QApplication::organizationName())); } void MainWindow::addFormToLibrary() { if(this->activeMonofin() != NULL){ if(!this->activeMonofin()->isEmpty()){ QString name = QInputDialog::getText(this, tr("Choose form name"), tr("Enter a name for the form:")); QString path(_libraryPath); path.append("/"); path.append(name); path.append(".finf"); if(!name.isEmpty()){ QDir dir(_libraryPath); if(!dir.exists()){ qDebug("Directory not existing"); dir.mkpath(_libraryPath); } if(QFile::exists(path)){ QMessageBox msg; msg.setText(tr("File already existing")); msg.setIcon(QMessageBox::Question); msg.setInformativeText(("Overwrite the file ?")); msg.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msg.setDefaultButton(QMessageBox::No); int ret = msg.exec(); if(ret == QMessageBox::Yes){ this->activeMonofin()->saveForm(path); } }else{ this->activeMonofin()->saveForm(path); } } } } this->updateLibrary();} void MainWindow::launch() { if (activeMonofin()) { activeMonofin()->launch(); } } void MainWindow::loadForm(QListWidgetItem *item){ if(this->activeMonofin() == NULL){ this->newEmptyProject(); } if(this->activeMonofin() != NULL){ if(item->type() == FormItem::Type){ this->activeMonofin()->loadForm(((FormItem*)item)->path()); } } } void MainWindow::preview3D() { if (activeMonofin()) { activeMonofin()->preview3D(); } } void MainWindow::newEmptyProject() { QMdiSubWindow *msw = createMonofin(); Monofin *monofin = static_cast<Monofin *>(msw->widget()); monofin->newFile(); monofin->show(); } void MainWindow::newFile() { int res = 0; if (res = _startupDialog->exec()) { switch (res) { case StartupDialog::empty: newEmptyProject(); break; case StartupDialog::image: newProjectFromImage(); break; case StartupDialog::open: open(); break; default: break; } } } void MainWindow::newProjectFromImage() { qDebug("MainWindow::newProjectFromImage()"); Data::ProjectFile *projectFile = new Data::ProjectFile; if (_graphicView.isNull()) { qDebug("graphicview not existing, creating a new one."); _graphicView = new Graphic(this, projectFile, 1024, 768); } else { qDebug("existing graphicview."); _graphicView->setProjectFile(projectFile); } //projectFile->startHistory(Data::MonofinSurface); //projectFile->clearSurface(); //projectFile->stopHistory(Data::MonofinSurface); QMdiSubWindow *msw = createMonofin(projectFile); Monofin *monofin = static_cast<Monofin *>(msw->widget()); monofin->show(); monofin->newFileFromImage(); connect(_graphicView, SIGNAL(kept()), this, SIGNAL(updateMonofinScene())); _graphicView->show(); } void MainWindow::open() { qDebug("MainWindow::open()"); QMdiSubWindow *msw = createMonofin(); Monofin *monofin = static_cast<Monofin *>(msw->widget()); monofin->show(); if(monofin->open()) { updateToolBars(); } else { msw->close(); } } void MainWindow::openRecentFile() { QAction *action = qobject_cast<QAction *>(sender()); if (action) loadFile(action->data().toString()); } void MainWindow::removeForm(){ QListWidgetItem* item = _listWidgetForms->currentItem(); if(item != NULL){ if(item->type() == FormItem::Type){ QString path(((FormItem*)item)->path()); QFile file(path); if(file.exists()){ QMessageBox msg; msg.setText(tr("Remove file")); msg.setIcon(QMessageBox::Question); msg.setInformativeText(tr("Are you sure ?")); msg.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msg.setDefaultButton(QMessageBox::No); int ret = msg.exec(); if(ret == QMessageBox::Yes){ file.remove(); this->updateLibrary(); } } } } } bool MainWindow::save() { if (activeMonofin()) return activeMonofin()->save(); else return false; } bool MainWindow::saveAs() { if (activeMonofin()) return activeMonofin()->saveAs(); else return false; } void MainWindow::setFullScreenMode(bool enabled) { if (enabled) setWindowState(windowState() ^ Qt::WindowFullScreen); else setWindowState(windowState() & ~Qt::WindowFullScreen); } void MainWindow::showGrid(bool a) { if(activeMonofin() != 0){ this->activeMonofin()->showGrid(a); } } void MainWindow::switchLanguage(QAction *action) { QString locale = action->data().toString(); _appTranslator.load("monofin_" + locale, _qmPath); _currentLanguage = _appTranslator.translate("MainWindow", "English"); retranslateUi(); } void MainWindow::updateMenus() { bool hasMonofin = (activeMonofin() != 0); _actionSave->setEnabled(hasMonofin); _actionSaveAs->setEnabled(hasMonofin); // MENU DRAW && VIEW if (hasMonofin) { _menuDraw->clear(); _menuView->clear(); QList<QToolBar*> l = activeMonofin()->toolBar(); if(l.size() >= 1){ _menuDraw->addActions(l.first()->actions()); if(l.size() >= 2){ _menuView->addActions(l.at(1)->actions()); } } _menuDraw->addAction(_actionShowGrid); _menuDraw->addSeparator(); _menuDraw->addAction(_action3DPreview); _menuDraw->setEnabled(true); _menuView->setEnabled(true); } else{ _menuDraw->setEnabled(false); _menuView->setEnabled(false); } } void MainWindow::updateRecentFileActions() { if (activeMonofin()) { QString curFile = activeMonofin()->currentFile(); _recentFiles.removeAll(curFile); _recentFiles.prepend(curFile); } QMutableStringListIterator i(_recentFiles); while(i.hasNext()) { QString recentFile = i.next(); qDebug("recentFiles[] := %s", recentFile.toStdString().c_str()); if (!QFile::exists(recentFile)) i.remove(); } for (int j=0; j<MaxRecentFiles; ++j) { if (j<_recentFiles.count()) { QString text = tr("&%1 %2") .arg(j+1) .arg(strippedName(_recentFiles[j])); _recentFileActions[j]->setText(text); _recentFileActions[j]->setData(_recentFiles[j]); _recentFileActions[j]->setVisible(true); } else _recentFileActions[j]->setVisible(false); } _separatorAction->setVisible(!_recentFiles.isEmpty()); } void MainWindow::updateToolBars() { if(_mainToolBar) { removeToolBar(_mainToolBar); } if(_viewToolBar) { removeToolBar(_viewToolBar); } if (activeMonofin()) { QList<QToolBar*> l = activeMonofin()->toolBar(); if(l.size() >= 1){ _mainToolBar = l.first(); addToolBar(activeMonofin()->toolBarDrawArea(), _mainToolBar); _mainToolBar->setVisible(true); if(l.size() >= 2){ _viewToolBar = l.at(1); addToolBar(activeMonofin()->toolBarViewArea(), _viewToolBar); _viewToolBar->setVisible(true); }else{ qDebug("No view toolbar to show"); } }else{ qDebug("No toolBar to show"); } } } void MainWindow::updateWindowTitle() { if (activeMonofin()) { setWindowTitle(tr("%1[*] - %2").arg(strippedName(activeMonofin()->currentFile())).arg(tr("Monofin"))); } else setWindowTitle(tr("Monofin")); } // PRIVATE Monofin *MainWindow::activeMonofin() { if (QMdiSubWindow *activeSubWindow = _mdiArea->activeSubWindow()) return static_cast<Monofin *>(activeSubWindow->widget()); else return 0; } void MainWindow::createActions() { // MENU FILE _actionNew = new QAction(this); _actionNew->setObjectName(QString::fromUtf8("actionNew")); _actionOpen = new QAction(this); _actionOpen->setObjectName(QString::fromUtf8("actionOpen")); _actionSave = new QAction(this); _actionSave->setObjectName(QString::fromUtf8("actionSave")); _actionSaveAs = new QAction(this); _actionSaveAs->setObjectName(QString::fromUtf8("actionSaveAs")); _actionExit = new QAction(this); _actionExit->setObjectName(QString::fromUtf8("actionExit")); // recent files for (int i=0; i<MaxRecentFiles; ++i) { _recentFileActions[i] = new QAction(this); _recentFileActions[i]->setVisible(false); connect(_recentFileActions[i], SIGNAL(triggered()), this, SLOT(openRecentFile())); } // MENU DRAW _actionShowGrid = new QAction(this); _actionShowGrid->setObjectName(QString::fromUtf8("actionShowGrid")); _actionShowGrid->setCheckable(true); _actionShowGrid->setChecked(true); _actionProperties = new QAction(this); _actionProperties->setObjectName(QString::fromUtf8("actionProperties")); _action3DPreview = new QAction(this); _action3DPreview->setObjectName(QString::fromUtf8("action3DPreview")); // MENU SIMULATION _actionConfigurate = new QAction(this); _actionConfigurate->setObjectName(QString::fromUtf8("actionConfigurate")); _actionLaunch = new QAction(this); _actionLaunch->setObjectName(QString::fromUtf8("actionLaunch")); // MENU WINDOW _actionFullScreen = new QAction(this); _actionFullScreen->setObjectName(QString::fromUtf8("actionFullScreen")); _actionFullScreen->setCheckable(true); _actionFullScreen->setChecked(false); // MENU HELP _actionAbout = new QAction(this); _actionAbout->setObjectName(QString::fromUtf8("actionAbout")); _actionAboutQt = new QAction(this); _actionAboutQt->setObjectName(QString::fromUtf8("actionAboutQt")); //FORM LIBRARY _buttonAddToFormLibrary = new QPushButton(this); _buttonAddToFormLibrary->setObjectName(QString::fromUtf8("actionAddToFormLibrary")); _buttonRemoveForm = new QPushButton(this); _buttonRemoveForm->setObjectName(QString::fromUtf8("buttonRemoveForm"));} void MainWindow::createDocks() { _dockFormLibrary = new QDockWidget(this); _dockFormLibrary->setObjectName(QString::fromUtf8("dockFormLibrary")); _dockFormLibrary->setFloating(false); _dockFormLibrary->setFeatures(QDockWidget::AllDockWidgetFeatures); _dockFormLibrary->setAllowedAreas(Qt::AllDockWidgetAreas); _listWidgetForms = new QListWidget(); _layoutLibrary = new QGridLayout(); _layoutLibrary->setObjectName(QString::fromUtf8("layoutLibrary")); _layoutLibrary->addWidget(_buttonAddToFormLibrary, 1,0); _layoutLibrary->addWidget(_buttonRemoveForm, 1, 1); _layoutLibrary->addWidget(_listWidgetForms, 0, 0, 1, 0); _dockWidgetContents = new QWidget(); _dockWidgetContents->setObjectName(QString::fromUtf8("dockWidgetContents")); _dockWidgetContents->setLayout(_layoutLibrary); _dockFormLibrary->setWidget(_dockWidgetContents); addDockWidget(Qt::RightDockWidgetArea, _dockFormLibrary); } void MainWindow::createLanguageMenu() { _menuLanguage = new QMenu(_menuBar); _actionGroupLanguage = new QActionGroup(this); connect(_actionGroupLanguage, SIGNAL(triggered(QAction*)), this, SLOT(switchLanguage(QAction*))); QDir dir(_qmPath); QStringList fileNames = dir.entryList(QStringList("monofin_*.qm")); for (int i=0; i<fileNames.size(); ++i) { QString locale = fileNames[i]; locale.remove(0, locale.indexOf('_')+1); locale.truncate(locale.indexOf('.')); QTranslator translator; translator.load(fileNames[i], _qmPath); QString language = translator.translate("MainWindow", "English"); QAction *action = new QAction(tr("&%1 %2") .arg(i+1).arg(language), this); action->setCheckable(true); action->setData(locale); _menuLanguage->addAction(action); _actionGroupLanguage->addAction(action); if (language == _currentLanguage) action->setChecked(true); } } void MainWindow::createMenus() { _menuBar = new QMenuBar(this); _menuBar->setObjectName(QString::fromUtf8("menuBar")); setMenuBar(_menuBar); // MENU FILE _menuFile = new QMenu(_menuBar); _menuFile->setObjectName(QString::fromUtf8("menuFile")); _menuFile->addAction(_actionNew); _menuFile->addAction(_actionOpen); _menuFile->addSeparator(); _menuFile->addAction(_actionSave); _menuFile->addAction(_actionSaveAs); _menuFile->addSeparator(); _menuFile->addAction(_actionExit); // recent files _separatorAction = _menuFile->insertSeparator(_actionExit); for (int i=0; i<MaxRecentFiles; ++i) _menuFile->insertAction(_actionExit, _recentFileActions[i]); _menuFile->insertSeparator(_actionExit); // MENU DRAW _menuDraw = new QMenu(_menuBar); _menuDraw->setObjectName(QString::fromUtf8("menuDraw")); _menuDraw->setDisabled(true); // MENU SIMULATION _menuSimulation = new QMenu(_menuBar); _menuSimulation->setObjectName(QString::fromUtf8("menuSimulation")); _menuSimulation->addAction(_actionConfigurate); _menuSimulation->addAction(_actionLaunch); // MENU WINDOW _menuWin = new QtWindowListMenu(_menuBar); _menuWin->attachToMdiArea(_mdiArea); _menuWin->addAction(_actionFullScreen); _menuWin->addSeparator(); //MENU VIEW _menuView = new QMenu(_menuBar); _menuView->setObjectName(QString::fromUtf8("menuView")); _menuView->setDisabled(true); // MENU LANGUAGE createLanguageMenu(); // MENU HELP _menuHelp = new QMenu(_menuBar); _menuHelp->setObjectName(QString::fromUtf8("menuHelp")); _menuHelp->addAction(_actionAbout); _menuHelp->addAction(_actionAboutQt); // MENUBAR _menuBar->addAction(_menuFile->menuAction()); _menuBar->addAction(_menuDraw->menuAction()); _menuBar->addAction(_menuView->menuAction()); _menuBar->addAction(_menuSimulation->menuAction()); _menuBar->addAction(_menuWin->menuAction()); _menuBar->addAction(_menuLanguage->menuAction()); _menuBar->addAction(_menuHelp->menuAction()); } QMdiSubWindow *MainWindow::createMonofin(Data::ProjectFile *projectFile) { qDebug("MainWindow::createMonofin()"); Monofin *monofin = new Monofin(projectFile); connect(monofin, SIGNAL(currentFileChanged()), this, SLOT(updateRecentFileActions())); connect(this, SIGNAL(updateMonofinScene()), monofin, SLOT(updateScene())); QMdiSubWindow *msw = _mdiArea->addSubWindow(monofin); msw->setAttribute(Qt::WA_DeleteOnClose); return msw; } void MainWindow::createStatusBar() { _statusBar = new QStatusBar(this); _statusBar->setObjectName(QString::fromUtf8("statusBar")); setStatusBar(_statusBar); } void MainWindow::createToolBars() { _mainToolBar = NULL; _viewToolBar = NULL; } bool MainWindow::loadFile(const QString &fileName) { QMdiSubWindow *msw = createMonofin(); Monofin *monofin = static_cast<Monofin *>(msw->widget()); if(monofin->openFile(fileName)) { monofin->show(); updateToolBars(); return true; } else { msw->close(); return false; } } void MainWindow::readSettings() { QSettings settings(QApplication::organizationName(), QApplication::applicationName()); QRect rect = settings.value("geometry", QRect(100, 100, 900, 700)).toRect(); move(rect.topLeft()); resize(rect.size()); _recentFiles = settings.value("recentFiles").toStringList(); updateRecentFileActions(); setFullScreenMode(settings.value("fullScreen").toBool()); settings.setValue("geometry", geometry()); settings.setValue("recentFiles", _recentFiles); settings.setValue("fullScreen", _actionFullScreen->isChecked()); } void MainWindow::retranslateUi() { // actions _actionExit->setText(QApplication::translate("MainWindow", "E&xit", 0, QApplication::UnicodeUTF8)); _actionExit->setShortcut(QApplication::translate("MainWindow", "Ctrl+Q", 0, QApplication::UnicodeUTF8)); _actionNew->setText(QApplication::translate("MainWindow", "&New...", 0, QApplication::UnicodeUTF8)); _actionNew->setShortcut(QApplication::translate("MainWindow", "Ctrl+N", 0, QApplication::UnicodeUTF8)); _actionOpen->setText(QApplication::translate("MainWindow", "&Open...", 0, QApplication::UnicodeUTF8)); _actionOpen->setShortcut(QApplication::translate("MainWindow", "Ctrl+O", 0, QApplication::UnicodeUTF8)); _actionSave->setText(QApplication::translate("MainWindow", "&Save", 0, QApplication::UnicodeUTF8)); _actionSave->setShortcut(QApplication::translate("MainWindow", "Ctrl+S", 0, QApplication::UnicodeUTF8)); _actionSaveAs->setText(QApplication::translate("MainWindow", "&Save As...", 0, QApplication::UnicodeUTF8)); _actionShowGrid->setText(QApplication::translate("Monofin", "&Show Grid", 0, QApplication::UnicodeUTF8)); _actionShowGrid->setShortcut(QApplication::translate("Monofin", "Ctrl+Shift+G", 0, QApplication::UnicodeUTF8)); _actionConfigurate->setText(QApplication::translate("Monofin", "&Configurate...", 0, QApplication::UnicodeUTF8)); _action3DPreview->setText(QApplication::translate("MainWindow", "&3D Preview", 0, QApplication::UnicodeUTF8)); _actionLaunch->setText(QApplication::translate("Monofin", "&Launch", 0, QApplication::UnicodeUTF8)); _actionLaunch->setShortcut(QApplication::translate("Monofin", "Ctrl+L", 0, QApplication::UnicodeUTF8)); _actionFullScreen->setText(QApplication::translate("MainWindow", "&Fullscreen", 0, QApplication::UnicodeUTF8)); _actionFullScreen->setShortcut(QApplication::translate("MainWindow", "F12", 0, QApplication::UnicodeUTF8)); _actionProperties->setText(QApplication::translate("MainWindow", "&Properties...", 0, QApplication::UnicodeUTF8)); _actionAbout->setText(QApplication::translate("MainWindow", "&About", 0, QApplication::UnicodeUTF8)); _actionAboutQt->setText(QApplication::translate("MainWindow", "About &Qt", 0, QApplication::UnicodeUTF8)); _buttonAddToFormLibrary->setText(QApplication::translate("MainWindow", "&Add form", 0, QApplication::UnicodeUTF8)); _buttonRemoveForm->setText(QApplication::translate("MainWindow", "&Remove form", 0, QApplication::UnicodeUTF8)); // menus _menuFile->setTitle(QApplication::translate("MainWindow", "&File", 0, QApplication::UnicodeUTF8)); _menuDraw->setTitle(QApplication::translate("MainWindow", "&Draw", 0, QApplication::UnicodeUTF8)); _menuSimulation->setTitle(QApplication::translate("MainWindow", "&Simulation", 0, QApplication::UnicodeUTF8)); _menuView->setTitle(QApplication::translate("MainWindow", "&View", 0, QApplication::UnicodeUTF8)); _menuLanguage->setTitle(QApplication::translate("MainWindow", "&Language", 0, QApplication::UnicodeUTF8)); _menuHelp->setTitle(QApplication::translate("MainWindow", "&Help", 0, QApplication::UnicodeUTF8)); // docks _dockFormLibrary->setWindowTitle(QApplication::translate("MainWindow", "Form library", 0, QApplication::UnicodeUTF8)); } void MainWindow::setConnections() { // MENU connect(_actionNew, SIGNAL(triggered()), this, SLOT(newFile())); connect(_actionOpen, SIGNAL(triggered()), this, SLOT(open())); connect(_actionSave, SIGNAL(triggered()), this, SLOT(save())); connect(_actionSaveAs, SIGNAL(triggered()), this, SLOT(saveAs())); connect(_actionExit, SIGNAL(triggered()), this, SLOT(close())); connect(_actionConfigurate, SIGNAL(triggered()), this, SLOT(configurate())); connect(_action3DPreview, SIGNAL(triggered()), this, SLOT(preview3D())); connect(_actionLaunch, SIGNAL(triggered()), this, SLOT(launch())); connect(_actionFullScreen, SIGNAL(toggled(bool)), this, SLOT(setFullScreenMode(bool))); connect(_actionAbout, SIGNAL(triggered()), this, SLOT(about())); connect(_actionAboutQt, SIGNAL(triggered()), qApp, SLOT(aboutQt())); connect(_actionShowGrid, SIGNAL(toggled(bool)), this, SLOT(showGrid(bool))); connect(_buttonAddToFormLibrary, SIGNAL(clicked()), this, SLOT(addFormToLibrary())); connect(_listWidgetForms, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(loadForm(QListWidgetItem*))); connect(_buttonRemoveForm, SIGNAL(clicked()), this, SLOT(removeForm())); QMetaObject::connectSlotsByName(this); } QString MainWindow::strippedName(const QString &fullFileName) { return QFileInfo(fullFileName).fileName(); } void MainWindow::updateLibrary() { _listWidgetForms->clear(); QDir dir(_libraryPath); QStringList fileNames = dir.entryList(QStringList("*.finf")); for (int i=0; i<fileNames.size(); ++i) { QString locale; locale.append(_libraryPath); locale.append("/"); locale.append(fileNames[i]); QListWidgetItem* item = new FormItem( QIcon(QPixmap::fromImage(Data::ProjectFile::getImage(locale))), fileNames[i].left(fileNames[i].size()-5), locale); if(Data::ProjectFile::getImage(locale).isNull()){ qDebug("image null"); } _listWidgetForms->setIconSize(QSize(64,64)); _listWidgetForms->addItem(item); } } void MainWindow::writeSettings() { QSettings settings(QApplication::organizationName(), QApplication::applicationName()); setWindowState(windowState() & ~Qt::WindowFullScreen); settings.setValue("geometry", geometry()); settings.setValue("recentFiles", _recentFiles); settings.setValue("fullScreen", _actionFullScreen->isChecked()); }
[ "kryptos@314bda93-af5c-0410-b653-d297496769b1", "nikos56@314bda93-af5c-0410-b653-d297496769b1", "nostrodon@314bda93-af5c-0410-b653-d297496769b1", "cyoann@314bda93-af5c-0410-b653-d297496769b1" ]
[ [ [ 1, 6 ], [ 8, 52 ], [ 54, 63 ], [ 65, 124 ], [ 130, 133 ], [ 135, 143 ], [ 146, 146 ], [ 148, 150 ], [ 152, 154 ], [ 167, 207 ], [ 209, 246 ], [ 271, 293 ], [ 301, 308 ], [ 310, 318 ], [ 322, 322 ], [ 327, 331 ], [ 333, 333 ], [ 335, 335 ], [ 338, 374 ], [ 380, 380 ], [ 397, 467 ], [ 472, 482 ], [ 488, 489 ], [ 491, 492 ], [ 495, 571 ], [ 575, 575 ], [ 577, 618 ], [ 620, 669 ], [ 671, 677 ], [ 679, 683 ], [ 685, 705 ], [ 708, 716 ], [ 727, 731 ], [ 733, 734 ], [ 740, 741 ], [ 747, 755 ] ], [ [ 7, 7 ], [ 151, 151 ], [ 208, 208 ], [ 737, 737 ], [ 739, 739 ] ], [ [ 53, 53 ], [ 64, 64 ], [ 125, 129 ], [ 134, 134 ], [ 144, 145 ], [ 147, 147 ], [ 155, 166 ], [ 247, 270 ], [ 294, 300 ], [ 309, 309 ], [ 319, 321 ], [ 323, 326 ], [ 332, 332 ], [ 334, 334 ], [ 336, 337 ], [ 375, 379 ], [ 381, 396 ], [ 468, 471 ], [ 483, 487 ], [ 490, 490 ], [ 493, 494 ], [ 572, 574 ], [ 576, 576 ], [ 619, 619 ], [ 678, 678 ], [ 684, 684 ], [ 706, 707 ], [ 717, 726 ], [ 732, 732 ], [ 735, 736 ], [ 738, 738 ], [ 742, 746 ] ], [ [ 670, 670 ] ] ]
1daa3ac67eea91798c7b228dadd0fd2c89ea9531
b505ef7eb1a6c58ebcb73267eaa1bad60efb1cb2
/sample/0060Fill2D/main.cpp
e85ff207bed4a2be3cfb990f1dbba2daed6bbd08
[]
no_license
roxygen/maid2
230319e05d6d6e2f345eda4c4d9d430fae574422
455b6b57c4e08f3678948827d074385dbc6c3f58
refs/heads/master
2021-01-23T17:19:44.876818
2010-07-02T02:43:45
2010-07-02T02:43:45
38,671,921
0
0
null
null
null
null
UTF-8
C++
false
false
2,659
cpp
/* 矩形塗りつぶしのサンプル */ #include"../../source/framework/gameframework.h" #include"../../source/graphics/graphics2drender.h" #include"../../source/graphics/graphicscommandcontrol.h" #include"startupdialog.h" using namespace Maid; class MyApp : public IGameThread { public: MyApp() :m_Render(m_Command) { } protected: bool SelectDevice( const DEVICELIST& DeviceList, DEFAULTCONFIG& conf ) { const RETURNCODE ret = BeginStartupInfo( DeviceList, conf ); return ret==GAMESTART; } void Initialize() { m_Command.Initialize(); m_Render.Initialize(); } void UpdateFrame() { // フレーム毎に呼ばれるとこ // 終了する場合は OnExitGame() を呼ぶ } void UpdateDraw() { // 定期的に描画するとこ m_Command.ClearRenderTarget( Maid::COLOR_A32B32G32R32F(1,0.5f,0,0) ); if( m_Render.IsInitializing() ) { return ; } m_Command.Begin(); { m_Render.SetVirtualScreenSize( SIZE2DI(800,600) ); m_Render.SetDefaultSetting(); m_Render.SetBlendState( Graphics2DRender::BLENDSTATE_ALPHA ); // 普通に青い四角を塗る m_Render.Fill( POINT2DI(600,300), Maid::COLOR_R32G32B32A32F(0,0,1,1), SIZE2DI(100,50), POINT2DI(50,25) ); // 赤い四角を横に伸ばして塗る m_Render.FillS( POINT2DI(200,300), Maid::COLOR_R32G32B32A32F(1,0,0,1), SIZE2DI(100,50), POINT2DI(50,25), SIZE2DF(1.5f,1.0f) ); { // 緑の四角を回転させて塗る(加算合成) m_Render.SetBlendState( Graphics2DRender::BLENDSTATE_ADD ); const POINT2DI pos(400,300); const SIZE2DI size(200,200); const POINT2DI center(size.w/2,size.h/2); static int rot; rot++; rot %= 360; m_Render.FillR( pos, Maid::COLOR_R32G32B32A32F(0,1,0,1), size, center, DEGtoRAD(rot), Maid::VECTOR3DF(0,0,1) ); // 青の四角を回転させて塗る(加算合成) m_Render.FillSR( pos, Maid::COLOR_R32G32B32A32F(0,0,1,1), size, center, SIZE2DF(2,0.3f), DEGtoRAD(-rot), Maid::VECTOR3DF(0,0,1) ); } } m_Command.End(); } void LocalFinalize() { // OnExitGame() を呼んだあとの処理 } private: GraphicsCommandControl m_Command; Graphics2DRender m_Render; }; int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { GameFrameWork app( SPGAMETHREAD(new MyApp) ); return app.Run(hInstance,hPrevInstance,lpCmdLine,nCmdShow); }
[ "[email protected]", "renji2000@471aaf9e-aa7b-11dd-9b86-41075523de00" ]
[ [ [ 1, 46 ], [ 48, 79 ], [ 81, 109 ] ], [ [ 47, 47 ], [ 80, 80 ] ] ]
d22780ac49cb731f9c22f82e3b3ba193332f06d2
51574a600a87ecfaaec8ea0e46b3809884859680
/MotionPlanTests/FieldNavRectMapViewTest.cpp
2be4d3d197ba75a293790816acf6c9806e88d189
[]
no_license
suilevap/motion-plan
b5ad60a8448b118c3742c8c9c42b29fd5e41ef3e
d9f5693938287f2179ca2cb4eb75bda51b97bbb0
refs/heads/master
2021-01-10T03:29:50.373970
2011-12-20T22:39:55
2011-12-20T22:39:55
49,495,165
0
0
null
null
null
null
UTF-8
C++
false
false
2,725
cpp
#include "gtest/gtest.h" #include "GridMapView.h" #include "FieldNavRectMapView.h" #include "Point.h" #include "FastVector.h" #include "EdgeInfo.h" #include "BasePathFinder.h" TEST(FieldNavRectMapView, Create) { GridMapView<int>* map = new GridMapView<int>(14, 14); //map->SetCellRegion(Point<float>(2,2), 12, Point<float>(2.5, 2.5)); map->SetCellPoint(Point<float>(0,0), 1); map->SetCellPoint(Point<float>(4,5), 1); FieldNavRectMapView<int>* navMap = NULL; navMap = FieldNavRectMapView<int>::Create(map); //quadMap //.111122 //5111122 //4444.22 //3333322 //3333322 ASSERT_TRUE(navMap != NULL); EXPECT_EQ(navMap->GetMaxNode(), 12); //FastVector<AStar::EdgeInfo<int, float>> neighbors; //quadMap->GetNeighbors(1, neighbors); //EXPECT_EQ(neighbors.size(), 3); //quadMap->GetNeighbors(2, neighbors); //EXPECT_EQ(neighbors.size(), 3); //quadMap->GetNeighbors(3, neighbors); //EXPECT_EQ(neighbors.size(), 5); //quadMap->GetNeighbors(4, neighbors); //EXPECT_EQ(neighbors.size(), 4); //quadMap->GetNeighbors(5, neighbors); //EXPECT_EQ(neighbors.size(), 4); //quadMap->GetNeighbors(6, neighbors); //EXPECT_EQ(neighbors.size(), 3); //map->ToOutput(); //navMap->ToOutput(); delete map; delete navMap; } TEST(FieldNavRectMapView, Corridor2) { GridMapView<int>* map = new GridMapView<int>(4, 2); //map->SetCellRegion(Point<float>(2,2), 12, Point<float>(2.5, 2.5)); map->SetCellPoint(Point<float>(0,1), 1); map->SetCellPoint(Point<float>(3,0), 1); FieldNavRectMapView<int>* navMap = NULL; navMap = FieldNavRectMapView<int>::Create(map); ASSERT_TRUE(navMap != NULL); //map->ToOutput(); navMap->ToOutput(); delete map; delete navMap; } TEST(FieldNavRectMapView, FindPath) { GridMapView<int>* map = new GridMapView<int>(5, 4); //map->SetCellRegion(Point<float>(2,2), 12, Point<float>(2.5, 2.5)); //11.11 //11.11 //22222 //22222 map->SetCellPoint(Point<float>(2,0), 1); map->SetCellPoint(Point<float>(2,1), 1); FieldNavRectMapView<int>* navMap = NULL; navMap = FieldNavRectMapView<int>::Create(map); ASSERT_TRUE(navMap != NULL); navMap->ToOutput(); AStar::BasePathFinder<Point<float>, int, float>* pathFinder = new AStar::BasePathFinder<Point<float>, int, float>(navMap); AStar::Path<Point<float>>* path; path = pathFinder->Find(Point<float>(0,0), Point<float>(4,0)); ASSERT_EQ(4, path->Count()); delete path; delete pathFinder; //map->ToOutput(); navMap->ToOutput(); delete map; delete navMap; }
[ [ [ 1, 102 ] ] ]
81a77373dbbfc8d1290841d74953ffcc1398f7c6
347fdd4d3b75c3ab0ecca61cf3671d2e6888e0d1
/addons/vaOpenal/src/AudioResource.cpp
0e4369b0f15f786ca0967f74111c482f597e8da1
[]
no_license
sanyaade/VirtualAwesome
29688648aa3f191cdd756c826b5c84f6f841b93f
05f3db98500366be1e79da16f5e353e366aed01f
refs/heads/master
2020-12-01T03:03:51.561884
2010-11-08T00:17:44
2010-11-08T00:17:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,057
cpp
//////////////////////////////////////////////////////////// // // SFML - Simple and Fast Multimedia Library // Copyright (C) 2007-2009 Laurent Gomila ([email protected]) // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it freely, // subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <vaOpenal/AudioResource.h> #include <vaOpenal/AudioDevice.h> using namespace vaOpenal; //////////////////////////////////////////////////////////// /// Default constructor //////////////////////////////////////////////////////////// AudioResource::AudioResource() { AudioDevice::AddReference(); } //////////////////////////////////////////////////////////// /// Copy constructor //////////////////////////////////////////////////////////// AudioResource::AudioResource(const AudioResource&) { AudioDevice::AddReference(); } //////////////////////////////////////////////////////////// /// Destructor //////////////////////////////////////////////////////////// AudioResource::~AudioResource() { AudioDevice::RemoveReference(); }
[ [ [ 1, 59 ] ] ]
fb3473df22fdd2930ed3cb0b65e7c6a5090d44cd
1724fb22a0b715c4597c5056ce571f0fbdb1cc46
/opengta2/anim.cpp
8bbc13fe9658f17166e2e5d9db9477636a944cde
[]
no_license
basecq/OpenGTA2
71127e333b7b6c6a60388ad8b4fb5c4408aa5bdd
2266c354a638397b84ca4766c69e3a50f4e367de
refs/heads/master
2020-04-06T05:25:34.926813
2010-01-27T02:35:09
2010-01-27T02:35:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,725
cpp
#include "opengta_cl.h" Animation_Manager Animations; void Animation_Manager::Initialize() { Entries.Preallocate(1024); //FIXME: another static allocation.. make convar when we have console! } void Animation_Manager::Deinitialize() { for (uint i = 0; i < Entries.Count; i++) { if (Entries[i]->Sprites) mem.free(Entries[i]->Sprites); } Entries.Release(); } Animation Animation_Manager::GetAnimation(const char* name) { return GetAnimation(GetAnimationSeq(name)); } Animation Animation_Manager::GetAnimation(AnimSeqID animseq) { Animation anim; anim.animSeq = animseq; anim.currentFrameTex = BAD_ID; anim.currentFrame = 0; anim.startTime = -1.0f; return anim; } AnimSeqID Animation_Manager::GetAnimationSeq(const char* name) { int nameLen = strlen(name); for (uint i = 0; i < Entries.Count; i++) { if (strncmp(Entries[i]->Name,name,nameLen) == 0) return i; } logWritem("Animation not found: %s",name); return BAD_ID; } AnimSeqID Animation_Manager::GetAnimationSeq(TexID texture) { for (uint i = 0; i < Entries.Count; i++) { if ((Entries[i]->Sprites) && (Entries[i]->Sprites[0] == texture)) return i; } return BAD_ID; } void Animation_Manager::LoadFromChunk(Chunk_Loader* TEX) { if (!TEX->IsChunk("ANIM")) return; if (!TEX->IsEndOfChunk()) { logWritem("Loading animations..."); } else { logWritem("Warning: animation chunk is empty"); } while (!TEX->IsEndOfChunk()) { char sprStartName[256]; char sprEndName[256]; char animName[256]; float animFPS; char animType; TEX->ReadString(animName); TEX->Read(&animType,1); logWritem("\t%s [type: %.2x]",animName,animType); animation_entry* anim = Animations.Entries.Add(); anim->Type = animType; anim->Name = mem.alloc_string(strlen(animName)+1); strcpy(anim->Name,animName); switch (animType) { // case ANIMTYPE_FORWARDLOOP: case ANIMTYPE_FORWARDONCE: TEX->ReadString(sprStartName); TEX->ReadString(sprEndName); TEX->Read(&animFPS,4); anim->FPS = animFPS; anim->Sprites = (TexID*)mem.alloc(2*sizeof(TexID)); anim->Sprites[0] = Graphics.GetTextureID(sprStartName); anim->Sprites[1] = Graphics.GetTextureID(sprEndName); anim->numSprites = 2; break; default: logError("Animation: unsupported type %d",animType); return; } } } void Animation::Start() { startTime = ServerTimer.Time(); } void Animation::Update() { float Time = ServerTimer.Time() - startTime; int NumFrames = Animations[animSeq]->numSprites; if (Animations[animSeq]->Type < 2) { //FIXME: use define constant NumFrames = Animations[animSeq]->Sprites[1] - Animations[animSeq]->Sprites[0] + 1; } switch (Animations[animSeq]->Type) { case ANIMTYPE_FORWARDLOOP: currentFrame = (int)floor(Time * Animations[animSeq]->FPS) % (NumFrames); break; case ANIMTYPE_FORWARDONCE: currentFrame = min((int)floor(Time * Animations[animSeq]->FPS),NumFrames-1); break; } } TexID Animation::GetTexID() { if (startTime <= 0.0f) { Update(); //FIXME } int Frames; switch (Animations[animSeq]->Type) { case ANIMTYPE_FORWARDLOOP: case ANIMTYPE_FORWARDONCE: Frames = Animations[animSeq]->Sprites[1] - Animations[animSeq]->Sprites[0] + 1; if ((currentFrame >= 0) && (currentFrame < Frames)) return Animations[animSeq]->Sprites[0] + currentFrame; break; default: if ((currentFrame >= 0) && (currentFrame < Animations[animSeq]->numSprites)) return Animations[animSeq]->Sprites[currentFrame]; break; } return BAD_ID; } float Animation::RemainingTime() { return 1.0f / Animations.Entries[animSeq]->FPS; }
[ [ [ 1, 140 ] ] ]
1887a6315673776a3ad70bcc2a0a3f8f65f16eb2
3ea8b8900d21d0113209fd02bd462310bd0fce83
/config.cpp
6d65337cad54ed66e4ae426f12e821b14ace2ec0
[]
no_license
LazurasLong/bgmlib
56958b7dffd98d78f99466ce37c4abaddc7da5b1
a9d557ea76a383fae54dc3729aaea455c258777a
refs/heads/master
2022-12-04T02:58:36.450986
2011-08-16T17:44:46
2011-08-16T17:44:46
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
13,884
cpp
// Legacy Engine // ------------- // config.cpp - Parsing structures for simple cross-platform reading and writing of configuration files // ------------- // "©" Nmlgc, 2008-2011 #include "platform.h" #include <FXSystem.h> #include <FXFile.h> #include "list.h" #include "config.h" #ifdef WIN32 #include <ctype.h> #endif // Utils // ----- // Returns [Str]'s number base and removes 0x if necessary FXint BaseCheck(FXString* Str) { FXint Base = 10; if(Str->left(2) == "0x") { Str->erase(0, 2); Base = 16; } return Base; } // Transforms a string to lowercase static bool LowerString(char* Str) { if(!Str) return false; bool Lock = false; size_t Len = strlen(Str) + 1; for(size_t c = 0; c < Len; c++) { if(Str[c] == '"') Lock = !Lock; // This function isn't used for any other purpose, so we can safely do this... if(Str[c] == '=' || Str[c] == '#') { return true; } Str[c] = tolower(Str[c]); } return true; } // ----- // ConfigKey // --------- ConfigKey::ConfigKey() { Data = NULL; DataType = 0; Saved = false; } ConfigKey::ConfigKey(FXString& _Key_, const ushort& _DataType_, void* _Data_) { SetInfo(_Key_, _DataType_, _Data_); } bool ConfigKey::Link(const ushort& _DataType_, void* _Data_, bool Get) { Data = _Data_; DataType = _DataType_; if(Get) return GetData(DataType, Data); else return true; } void ConfigKey::SetInfo(FXString& _Key_, const ushort& _DataType_, void* _Data_) { if(!_Key_ || !_Data_) return; Key = _Key_.lower(); Data = _Data_; DataType = _DataType_; } bool ConfigKey::GetData(const ushort& pd, void* p, FXString* NewLine) { if(!p || pd == 0) return false; FXString* L = NewLine ? NewLine : &Line; switch(pd) { case TYPE_BOOL: if(*L == "true") *(bool*)p = true; else if(*L == "false") *(bool*)p = false; else *(bool*)p = atoi(L->text()) != 0; break; case TYPE_SHORT: *(short*)p = (short)L->toInt(BaseCheck(L)); break; case TYPE_USHORT: *(ushort*)p = (ushort)L->toUInt(BaseCheck(L)); break; case TYPE_INT: *(int*)p = L->toInt(BaseCheck(L)); break; case TYPE_UINT: *(uint*)p = L->toUInt(BaseCheck(L)); break; case TYPE_LONG: *(long*)p = L->toLong(BaseCheck(L)); break; case TYPE_ULONG: *(ulong*)p = L->toULong(BaseCheck(L)); break; case TYPE_FLOAT: *(float*)p = (float)L->toFloat(); break; case TYPE_DOUBLE: *(double*)p = (double)L->toDouble(); break; case TYPE_UCHAR: *(uchar*)p = (uchar)L->toUInt(BaseCheck(L)); break; case TYPE_STRING: FXString* s = (FXString*)p; L->substitute("\\n", 2, &LineBreak[1], 1, true); // Translate line breaks L->substitute("\\\"", 2, "\"", 1, true); // Remove quotation marks FXint len = L->length() - 1; if(L->at(0) == '"') { len = L->rfind('"'); s->assign(L->text() + 1, len - 1); } else s->assign(*L); break; } return true; } bool ConfigKey::SaveData(FXString* FileLine) { if(!Data || DataType == 0 || !FileLine) return false; switch(DataType) { case TYPE_BOOL: if(*(bool*)Data) FileLine->format("%s = true", Key); else FileLine->format("%s = false", Key); break; case TYPE_SHORT: FileLine->format("%s = %d", Key, *(short*)Data); break; case TYPE_USHORT: FileLine->format("%s = %d", Key, *(ushort*)Data); break; case TYPE_INT: FileLine->format("%s = %d", Key, *(int*)Data); break; case TYPE_UINT: FileLine->format("%s = %d", Key, *(uint*)Data); break; case TYPE_LONG: FileLine->format("%s = %ld",Key, *(long*)Data); break; case TYPE_ULONG: FileLine->format("%s = %lu",Key, *(ulong*)Data); break; case TYPE_FLOAT: FileLine->format("%s = %f", Key, *(float*)Data); break; case TYPE_DOUBLE: FileLine->format("%s = %f", Key, *(double*)Data); break; case TYPE_UCHAR: FileLine->format("%s = %d", Key, *(uchar*)Data); break; case TYPE_STRING: *FileLine = *(FXString*)Data; if(FileLine->empty()) break; FileLine->substitute("\"", 1, "\\\"", 2, true); // Enquote FileLine->append('\"'); FileLine->substitute(&LineBreak[1], 1, "\\n", 2, true); // Translate line breaks FileLine->prepend(Key + " = \""); break; } return Saved = true; } // ConfigParser // ------------ ConfigParser::ConfigParser() { } void ConfigParser::SetCaption(FXString& New) { Caption = New.lower(); } #define ADD_KEY_IMP(tn, tc) ConfigKey* ConfigParser::AddKey(FXString& Key, tn* Data) {ConfigKey NewKey; NewKey.SetInfo(Key, tc, (void*)Data); return &Keys.Add(&NewKey)->Data;} ADD_KEY_IMP(bool, TYPE_BOOL) ADD_KEY_IMP(short, TYPE_SHORT) ADD_KEY_IMP(ushort, TYPE_USHORT) ADD_KEY_IMP(int, TYPE_INT) ADD_KEY_IMP(uint, TYPE_UINT) ADD_KEY_IMP(long, TYPE_LONG) ADD_KEY_IMP(ulong, TYPE_ULONG) ADD_KEY_IMP(float, TYPE_FLOAT) ADD_KEY_IMP(double, TYPE_DOUBLE) ADD_KEY_IMP(FXString, TYPE_STRING) ConfigKey* ConfigParser::CreateKey(const FXString& Name) { ConfigKey* New = &(Keys.Add()->Data); New->Key = Name; return New; } ConfigKey* ConfigParser::FindKey(const FXString& Name) { ListEntry<ConfigKey>* CurKey = Keys.First(); while(CurKey) { if(CurKey->Data.Key == Name) return &CurKey->Data; CurKey = CurKey->Next(); } return NULL; } bool ConfigParser::GetValue(const FXString& KeyStr, const ushort& DataType, void* Value) { ConfigKey* Key = FindKey(KeyStr); if(!Key) return false; else return Key->GetData(DataType, Value); } bool ConfigParser::LinkValue(const FXString& KeyStr, const ushort& DataType, void* Value, bool GetData) { ConfigKey* Key = FindKey(KeyStr); if(!Key) Key = CreateKey(KeyStr); return Key->Link(DataType, Value, GetData); } void ConfigParser::Clear() { Keys.Clear(); } ConfigParser::~ConfigParser() { Clear(); } // ------------ // ConfigFile // ---------- void ConfigFile::SetFN(const FXString& FN) { ConfigFN.clear(); ConfigFN = FN; } bool ConfigFile::BufferFile() { char bom[3]; long Len = 0; FXlong Size; FXFile Config; if(!Config.open(ConfigFN, FXIO::Reading)) return false;//Log.Error("Config file not found!"); // Skip byte order mark, if necessary Config.readBlock(bom, 3); if(memcmp(bom, utf8bom, 3)) Config.position(0); Size = Config.size() - Config.position(); char* Buf = (char*)malloc(Size + 1); Config.readBlock(Buf, Size); Buf[Size] = LineBreak[1]; Size += 1; Config.close(); char* Line = Buf; for(long c = 0; c < Size; c++) { if(Line[c] == LineBreak[0]) { Line[c] = '\0'; Len = ++c; } if(Line[c] == LineBreak[1]) { Line[c] = '\0'; Len = c + 1; } if(Len > 0) { if(Line[0] == '\0') FileBuffer.Add(Line, 0); else if(Line[0] != '#') { LowerString(Line); FileBuffer.Add(Line, Len); } else FileBuffer.Add(Line, Len); Line += Len; Size -= Len; Len = c = -1; } } free(Buf); Config.close(); return true; } // (Old version, new one is a bit faster) /* bool ConfigFile::BufferFile() { char CurLine[2048]; while( (Len = ReadLineFromFile(CurLine, 2048 * sizeof(char), Config)) != -1) { if(CurLine[0] == '\0') FileBuffer.Add(CurLine, 0); else if(CurLine[0] != '#') { LowerString(CurLine); FileBuffer.Add(CurLine, Len); } else FileBuffer.Add(CurLine, Len); CurLine[0] = '\0'; } }*/ PListEntry<char>* ConfigFile::InsertLine(PListEntry<char>* PrevLine, char* NewLine) { if(PrevLine) { PrevLine = FileBuffer.Insert(PrevLine, NewLine, 256); } else FileBuffer.Add(NewLine, strlen(NewLine + 1)); return PrevLine; } ConfigParser* ConfigFile::FindSection(const FXString& Name) { ListEntry<ConfigParser>* Cur = Sect.First(); while(Cur) { if(Cur->Data.Caption == Name) return &Cur->Data; Cur = Cur->Next(); } return NULL; } ConfigParser* ConfigFile::CheckSection(const FXString& Line) { ConfigParser* New = FindSection(Line); if(!New) { // Create new section New = &(Sect.Add()->Data); New->Caption.assign(Line); FXString Name; Name.format("[%s]", Line); New->LastLine = FileBuffer.Add(Name.text(), Name.length() + 1); } return New; } bool ConfigFile::Load(const FXString& FN) { SetFN(FN); if(!BufferFile()) return false; Load(); return true; } bool ConfigFile::Load() { // LARGE_INTEGER Time[2], Diff[3], TimeTotal, SubDiff[3]; char* CurLine = NULL; ConfigParser* CurSection = NULL; FXString Key; FXString Value; ConfigKey* TrgKey; int CurLineNum = -1; LineLink* NewLL; PListEntry<char>* BufferLine = FileBuffer.First(); if(!BufferLine) return false; do { // QueryPerformanceCounter(&Time[0]); CurLineNum++; CurLine = BufferLine->Data; if(!CurLine) continue; // Comments if(CurLine[0] == '#') continue; else if(CurLine[0] == '[') // Section Name { Key.assign(CurLine + 1); Key.tail() = '\0'; CurSection = FindSection(Key); if(!CurSection) { // Create new section CurSection = &(Sect.Add()->Data); CurSection->Caption.assign(Key); } continue; } // QueryPerformanceCounter(&Diff[0]); if(!CurSection) continue; // Scanning... uint c; for(c = 0; c < BufferLine->Size; c++) { if(CurLine[c] == '=') { Key.assign(CurLine, c); Key.trim(); Value.assign(CurLine + c + 1); Value.trim(); break; } } // QueryPerformanceCounter(&Diff[1]); if(c < BufferLine->Size) { TrgKey = CurSection->FindKey(Key); // QueryPerformanceCounter(&SubDiff[0]); if(!TrgKey) { TrgKey = CurSection->CreateKey(Key); TrgKey->Line = Value; } else TrgKey->GetData(TrgKey->DataType, TrgKey->Data); // QueryPerformanceCounter(&SubDiff[1]); NewLL = &(Link.Add()->Data); NewLL->Key = TrgKey; NewLL->Line = CurLineNum; CurSection->LastLine = BufferLine; // QueryPerformanceCounter(&SubDiff[2]); } /*QueryPerformanceCounter(&Diff[2]); QueryPerformanceCounter(&Time[1]); SubDiff[2] = SubDiff[2] - SubDiff[1]; SubDiff[1] = SubDiff[1] - SubDiff[0]; SubDiff[0] = SubDiff[0] - Diff[1]; Diff[2] = Diff[2] - Diff[1]; Diff[1] = Diff[1] - Diff[0]; Diff[0] = Diff[0] - Time[0]; TimeTotal = Time[1] - Time[0];*/ } while(BufferLine = BufferLine->Next()); return true; } // Why wasn't I implementing something like this in the first place? // Simple, fast and bullshit-free saving at the cost of 16 bytes per key. bool ConfigFile::Save() { PListEntry<char>* BufferLine = FileBuffer.First(); if(!BufferLine) return false; ListEntry<LineLink>* CurLL = Link.First(); char* CurLine = NULL; LineLink* LL; ConfigKey* Key; int CurLineNum = 0; bool Changed = false; FXString Save; while(BufferLine && ( BufferLine = BufferLine->Next()) && CurLL) { CurLineNum++; if(CurLL->Data.Line != CurLineNum) continue; LL = &CurLL->Data; CurLL = CurLL->Next(); CurLine = BufferLine->Data; if(!CurLine) continue; if(LL->Key->SaveData(&Save)) { if(Save.empty()) { BufferLine = FileBuffer.Delete(BufferLine); CurLineNum++; Changed = true; } else if(Save != BufferLine->Data) { BufferLine->SetData(Save.text(), Save.length() + 1); Changed = true; } } } // Check for keys not present in the file yet ListEntry<ConfigKey>* CurKey; ListEntry<ConfigParser>* CurSect = Sect.First(); while(CurSect) { CurKey = CurSect->Data.Keys.First(); while(CurKey) { Key = &CurKey->Data; if(!Key->Saved && Key->SaveData(&Save) && !Save.empty()) { FileBuffer.Insert(CurSect->Data.LastLine, Save.text(), Save.length() + 1); Changed = true; } CurKey = CurKey->Next(); } CurSect = CurSect->Next(); } if(Changed) return WriteBuffer(); // No changes, no save. return Changed; } ConfigKey* ConfigFile::FindKey(const FXString& SectStr, const FXString& KeyStr) { ConfigParser* Section = FindSection(SectStr); if(!Section) return NULL; return Section->FindKey(KeyStr); } bool ConfigFile::GetValue(const FXString& SectStr, const FXString& KeyStr, const ushort& DataType, void* Value) { ConfigParser* Section = FindSection(SectStr); if(!Section) return false; else return Section->GetValue(KeyStr, DataType, Value); return true; } bool ConfigFile::LinkValue(const FXString& SectStr, const FXString& KeyStr, const ushort& DataType, void* Value, bool GetData) { ConfigParser* Section = FindSection(SectStr); if(!Section) return false; else return Section->LinkValue(KeyStr, DataType, Value, GetData); } bool ConfigFile::WriteBuffer() { static const FXString TmpFN = FXSystem::getTempDirectory() + SlashString + "legacy_tmp.cfg"; PListEntry<char>* CurLine = FileBuffer.First(); if(!CurLine) return false; FXFile Config; if(!Config.open(TmpFN, FXIO::Writing)) return false; // Always write UTF8 Config.writeBlock(utf8bom, 3); // We have to do it this way, unless we want to append a line each time we save the file. if(CurLine->Data) Config.writeBlock(CurLine->Data, strlen(CurLine->Data)); CurLine = CurLine->Next(); while(CurLine) { Config.writeBlock(LineBreak, sizeof(LineBreak)); if(CurLine->Data) Config.writeBlock(CurLine->Data, strlen(CurLine->Data)); CurLine = CurLine->Next(); } Config.close(); bool Ret = FXFile::moveFiles(TmpFN, ConfigFN, true); if(!Ret) FXFile::removeFiles(TmpFN); return Ret; } void ConfigFile::Clear() { FileBuffer.Clear(); Sect.Clear(); ConfigFN.clear(); } ConfigFile::ConfigFile() { } ConfigFile::ConfigFile(const FXString& FN) { SetFN(FN); BufferFile(); } ConfigFile::~ConfigFile() { Clear(); } // ----------
[ [ [ 1, 598 ] ] ]
aebffb7aee42361d4ecd5b7a9246c5be7bc51b3d
0ac07f6ce192d04485b494ade03577f3abaf145a
/test/sample.cpp
3a3d141fc29560e584e6f3387c5b7c757ac44483
[]
no_license
pabloc11/CS249A-Assign2
7b22136a78db09b34f86eb3e44423675b29ed46b
3d29e53daa7f00027f75ad445327c01218189947
refs/heads/master
2021-01-10T20:59:22.131949
2011-12-09T07:43:31
2011-12-09T07:43:31
2,668,931
0
0
null
null
null
null
UTF-8
C++
false
false
7,557
cpp
#include <string> #include <ostream> #include <iostream> #include <string> #include "Instance.h" using std::cout; using std::cerr; using std::endl; using std::string; int main(int argc, char *argv[]) { Ptr<Instance::Manager> manager = shippingInstanceManager(); if (manager == NULL) { cerr << "Unexpected NULL manager." << endl; return 1; } Ptr<Instance> stats = manager->instanceNew("myStats", "Stats"); if (stats == NULL) { cerr << "Unexpected NULL stats." << endl; return 1; } Ptr<Instance> fleet = manager->instanceNew("myFleet", "Fleet"); if (fleet == NULL) { cerr << "Unexpected NULL." << endl; return 1; } fleet->attributeIs("Boat, speed", "30"); fleet->attributeIs("Truck, speed", "70"); fleet->attributeIs("Plane, speed", "300"); fleet->attributeIs("Boat, cost", "20"); fleet->attributeIs("Truck, cost", "10"); fleet->attributeIs("Plane, cost", "100"); // --- Create instances // -- Locations // customers Ptr<Instance> customer1 = manager->instanceNew("customer1", "Customer"); Ptr<Instance> customer2 = manager->instanceNew("customer2", "Customer"); // Truck Terminal Ptr<Instance> truckTerminal1 = manager->instanceNew("truckterminal1", "Truck terminal"); // Boat Terminal Ptr<Instance> boatTerminal1 = manager->instanceNew("boatterminal1", "Boat terminal"); // Plane Terminal Ptr<Instance> planeTerminal1 = manager->instanceNew("planeterminal1", "Plane terminal"); if (customer1 == NULL || customer2 == NULL || truckTerminal1 == NULL || boatTerminal1 == NULL || planeTerminal1 == NULL) { cerr << "Unexpected NULL customer or port." << endl; return 1; } // -- Segments // boat Ptr<Instance> boatSeg1 = manager->instanceNew("boatSeg1", "Boat segment"); Ptr<Instance> boatSeg2 = manager->instanceNew("boatSeg2", "Boat segment"); Ptr<Instance> boatSeg3 = manager->instanceNew("boatSeg3", "Boat segment"); Ptr<Instance> boatSeg4 = manager->instanceNew("boatSeg4", "Boat segment"); // truck Ptr<Instance> truckSeg1 = manager->instanceNew("truckSeg1", "Truck segment"); Ptr<Instance> truckSeg2 = manager->instanceNew("truckSeg2", "Truck segment"); Ptr<Instance> truckSeg3 = manager->instanceNew("truckSeg3", "Truck segment"); Ptr<Instance> truckSeg4 = manager->instanceNew("truckSeg4", "Truck segment"); // plane Ptr<Instance> planeSeg1 = manager->instanceNew("planeSeg1", "Plane segment"); Ptr<Instance> planeSeg2 = manager->instanceNew("planeSeg2", "Plane segment"); Ptr<Instance> planeSeg3 = manager->instanceNew("planeSeg3", "Plane segment"); Ptr<Instance> planeSeg4 = manager->instanceNew("planeSeg4", "Plane segment"); // connections // customer1 <---> truck terminal 1 truckSeg1->attributeIs("source", "customer1"); truckSeg2->attributeIs("source", "truckterminal1"); truckSeg1->attributeIs("return segment", "truckSeg2"); // customer2 <---> truck terminal 1 truckSeg3->attributeIs("source", "customer2"); truckSeg4->attributeIs("source", "truckterminal1"); truckSeg3->attributeIs("return segment", "truckSeg4"); // boat terminal 1 <---> customer1 boatSeg1->attributeIs("source", "boatterminal1"); boatSeg2->attributeIs("source", "customer1"); boatSeg1->attributeIs("return segment", "boatSeg2"); // boat terminal 1 <---> customer 2 boatSeg3->attributeIs("source", "boatterminal1"); boatSeg4->attributeIs("source", "customer2"); boatSeg3->attributeIs("return segment", "boatSeg4"); // plane terminal 1 <---> customer1 planeSeg1->attributeIs("source", "planeterminal1"); planeSeg2->attributeIs("source", "customer1"); planeSeg1->attributeIs("return segment", "planeSeg2"); // plane terminal 1 <---> customer2 planeSeg3->attributeIs("source", "planeterminal1"); planeSeg4->attributeIs("source", "customer2"); planeSeg3->attributeIs("return segment", "planeSeg4"); // -- Segment lengths boatSeg1->attributeIs("length", "400"); boatSeg2->attributeIs("length", "300"); boatSeg3->attributeIs("length", "200"); boatSeg4->attributeIs("length", "500"); truckSeg1->attributeIs("length", "800"); truckSeg2->attributeIs("length", "900"); truckSeg3->attributeIs("length", "200"); truckSeg4->attributeIs("length", "400"); planeSeg1->attributeIs("length", "500"); planeSeg2->attributeIs("length", "600"); planeSeg3->attributeIs("length", "800"); planeSeg4->attributeIs("length", "1000"); // -- Segment difficulties boatSeg1->attributeIs("difficulty", "1"); boatSeg2->attributeIs("difficulty", "1.4"); boatSeg3->attributeIs("difficulty", "1.8"); boatSeg4->attributeIs("difficulty", "2"); truckSeg1->attributeIs("difficulty", "2"); truckSeg2->attributeIs("difficulty", "3"); truckSeg3->attributeIs("difficulty", "4.5"); truckSeg4->attributeIs("difficulty", "5"); planeSeg1->attributeIs("difficulty", "1"); planeSeg2->attributeIs("difficulty", "1.5"); planeSeg3->attributeIs("difficulty", "1.5"); planeSeg4->attributeIs("difficulty", "1.7"); // -- Segment expedite support boatSeg1->attributeIs("expedite support", "yes"); boatSeg2->attributeIs("expedite support", "yes"); boatSeg3->attributeIs("expedite support", "yes"); boatSeg4->attributeIs("expedite support", "yes"); truckSeg1->attributeIs("expedite support", "yes"); truckSeg2->attributeIs("expedite support", "yes"); truckSeg3->attributeIs("expedite support", "yes"); truckSeg4->attributeIs("expedite support", "yes"); planeSeg1->attributeIs("expedite support", "yes"); planeSeg2->attributeIs("expedite support", "yes"); planeSeg3->attributeIs("expedite support", "yes"); planeSeg4->attributeIs("expedite support", "yes"); // -- Connectivity queries Ptr<Instance> conn = manager->instanceNew("myConn", "Conn"); if (conn == NULL) { cerr << "Unexpected NULL conn." << endl; return 1; } cout << "**** explore customer1 : expedited****" << endl; cout << conn->attribute("explore customer1 : expedited distance 10000 time 1000") << endl; cout << endl; cout << "*** connect costomer2 : truckterminal1 ****" << endl; cout << conn->attribute("connect customer2 : truckterminal1") << endl; cout << endl; // -- Statistics queries cout << "===== Stats attributes =====" << endl; cout << " --- Segments --- " << endl; cout << "# Truck segments : " << stats->attribute("Truck segment") << endl; cout << "# Boat segments : " << stats->attribute("Boat segment") << endl; cout << "Expediting % : " << stats->attribute("expedite percentage") << endl; cout << " --- Terminals --- " << endl; cout << "# Plane terminals: " << stats->attribute("Plane terminal") << endl; cout << "# Truck terminals: " << stats->attribute("Truck terminal") << endl; cout << "# Boat terminals: " << stats->attribute("Boat terminal") << endl; cout << " --- Ports and customers --- " << endl; cout << "# Ports : " << stats->attribute("Port") << endl; cout << "# Customer : " << stats->attribute("Customer") << endl; cerr << "Done!" << endl; return 0; }
[ [ [ 1, 193 ] ] ]
dc4baac114a0a7cb20ca0fc50865e628d3d77fbe
f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0
/Depend/MyGUI/Tools/SkinEditor/Application.cpp
941a4d1ccac88b6e6edef044ffc28d608b729275
[]
no_license
lxinhcn/starworld
79ed06ca49d4064307ae73156574932d6185dbab
86eb0fb8bd268994454b0cfe6419ffef3fc0fc80
refs/heads/master
2021-01-10T07:43:51.858394
2010-09-15T02:38:48
2010-09-15T02:38:48
47,859,019
2
1
null
null
null
null
UTF-8
C++
false
false
8,806
cpp
/*! @file @author Albert Semenov @date 08/2010 */ #include "precompiled.h" #include "Application.h" #include "Base/Main.h" #include "SkinManager.h" #include "ActionManager.h" #include "CommandManager.h" #include "ExportManager.h" #include "MyGUI_FilterNoneSkin.h" #include "MessageBoxManager.h" #include "DialogManager.h" #include "HotKeyManager.h" #include "StateManager.h" #include "RecentFilesManager.h" #include "SettingsManager.h" template <> tools::Application* MyGUI::Singleton<tools::Application>::msInstance = nullptr; template <> const char* MyGUI::Singleton<tools::Application>::mClassTypeName("Application"); namespace tools { Application::Application() : mEditorState(nullptr), mTestState(nullptr) { } Application::~Application() { } void Application::setupResources() { base::BaseManager::setupResources(); addResourceLocation(getRootMedia() + "/Tools/SkinEditor"); setResourceFilename("editor.xml"); } void Application::createScene() { getStatisticInfo()->setVisible(false); if (!mLocale.empty()) MyGUI::LanguageManager::getInstance().setCurrentLanguage(mLocale); MyGUI::FactoryManager::getInstance().registerFactory<MyGUI::FilterNone>("BasisSkin"); new SettingsManager(); SettingsManager::getInstance().initialise("se_user_settings.xml"); new RecentFilesManager(); RecentFilesManager::getInstance().initialise(); new CommandManager(); CommandManager::getInstance().initialise(); new SkinManager(); SkinManager::getInstance().initialise(); new ActionManager(); ActionManager::getInstance().initialise(); new ExportManager(); ExportManager::getInstance().initialise(); new MessageBoxManager(); MessageBoxManager::getInstance().initialise(); new DialogManager(); DialogManager::getInstance().initialise(); new HotKeyManager(); HotKeyManager::getInstance().initialise(); new StateManager(); StateManager::getInstance().initialise(); MyGUI::ResourceManager::getInstance().load("initialise.xml"); const SettingsSector::VectorUString& additionalPaths = SettingsManager::getInstance().getSector("Settings")->getPropertyValueList("AdditionalPaths"); for (SettingsSector::VectorUString::const_iterator iter = additionalPaths.begin(); iter != additionalPaths.end(); ++iter) addResourceLocation(*iter); CommandManager::getInstance().registerCommand("Command_QuitApp", MyGUI::newDelegate(this, &Application::commandQuitApp)); mEditorState = new EditorState(); mTestState = new TestState(); StateManager::getInstance().registerState(this, "Application"); StateManager::getInstance().registerState(mEditorState, "EditorState"); StateManager::getInstance().registerState(mTestState, "TestState"); StateManager::getInstance().registerEventState("Application", "Start", "EditorState"); StateManager::getInstance().registerEventState("EditorState", "Test", "TestState"); StateManager::getInstance().registerEventState("EditorState", "Exit", "Application"); StateManager::getInstance().registerEventState("TestState", "Exit", "EditorState"); StateManager::getInstance().pushState(this); StateManager::getInstance().stateEvent(this, "Start"); } void Application::destroyScene() { StateManager::getInstance().rollbackToState(nullptr); delete mEditorState; mEditorState = nullptr; delete mTestState; mTestState = nullptr; StateManager::getInstance().shutdown(); delete StateManager::getInstancePtr(); HotKeyManager::getInstance().shutdown(); delete HotKeyManager::getInstancePtr(); DialogManager::getInstance().shutdown(); delete DialogManager::getInstancePtr(); MessageBoxManager::getInstance().shutdown(); delete MessageBoxManager::getInstancePtr(); ExportManager::getInstance().shutdown(); delete ExportManager::getInstancePtr(); ActionManager::getInstance().shutdown(); delete ActionManager::getInstancePtr(); SkinManager::getInstance().shutdown(); delete SkinManager::getInstancePtr(); CommandManager::getInstance().shutdown(); delete CommandManager::getInstancePtr(); RecentFilesManager::getInstance().shutdown(); delete RecentFilesManager::getInstancePtr(); SettingsManager::getInstance().shutdown(); delete SettingsManager::getInstancePtr(); MyGUI::FactoryManager::getInstance().unregisterFactory<MyGUI::FilterNone>("BasisSkin"); } void Application::prepare() { // устанавливаем локаль из переменной окружения // без этого не будут открываться наши файлы mLocale = ::setlocale( LC_ALL, "" ); // erase everything after '_' to get language name mLocale.erase(std::find(mLocale.begin(), mLocale.end(), '_'), mLocale.end()); if (mLocale == "ru") mLocale = "Russian"; else if (mLocale == "en") mLocale = "English"; #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 // при дропе файл может быть запущен в любой дирректории wchar_t buff[MAX_PATH]; ::GetModuleFileNameW(0, buff, MAX_PATH); std::wstring dir = buff; size_t pos = dir.find_last_of(L"\\/"); if (pos != dir.npos) { // устанавливаем правильную дирректорию ::SetCurrentDirectoryW(dir.substr(0, pos + 1).c_str()); } // имена могут содержать пробелы, необходимо //склеивать и проверять файлы на существование std::wifstream stream; std::wstring tmp; std::wstring delims = L" "; std::wstring source = GetCommandLineW(); size_t start = source.find_first_not_of(delims); while (start != source.npos) { size_t end = source.find_first_of(delims, start); if (end != source.npos) { tmp += source.substr(start, end - start); // имена могут быть в ковычках if (tmp.size() > 2) { if ((tmp[0] == L'"') && (tmp[tmp.size()-1] == L'"')) { tmp = tmp.substr(1, tmp.size() - 2); } } #if MYGUI_COMPILER == MYGUI_COMPILER_MSVC && !defined(STLPORT) stream.open(tmp.c_str()); #else stream.open(MyGUI::UString(tmp).asUTF8_c_str()); #endif if (stream.is_open()) { if (tmp.size() > 4 && tmp.substr(tmp.size() - 4) != L".exe") mParams.push_back(tmp); tmp.clear(); stream.close(); } else tmp += delims; } else { tmp += source.substr(start); // имена могут быть в ковычках if (tmp.size() > 2) { if ((tmp[0] == L'"') && (tmp[tmp.size()-1] == L'"')) { tmp = tmp.substr(1, tmp.size() - 2); } } #if MYGUI_COMPILER == MYGUI_COMPILER_MSVC && !defined(STLPORT) stream.open(tmp.c_str()); #else stream.open(MyGUI::UString(tmp).asUTF8_c_str()); #endif if (stream.is_open()) { if (tmp.size() > 4 && tmp.substr(tmp.size() - 4) != L".exe") mParams.push_back(tmp); tmp.clear(); stream.close(); } else tmp += delims; break; } start = source.find_first_not_of(delims, end + 1); }; #else #endif } void Application::onFileDrop(const std::wstring& _fileName) { CommandManager::getInstance().setCommandData(_fileName); CommandManager::getInstance().executeCommand("Command_FileDrop"); } bool Application::onWinodwClose(size_t _handle) { #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 if (::IsIconic((HWND)_handle)) ShowWindow((HWND)_handle, SW_SHOWNORMAL); #endif CommandManager::getInstance().executeCommand("Command_QuitApp"); return false; } void Application::injectKeyPress(MyGUI::KeyCode _key, MyGUI::Char _text) { if (MyGUI::Gui::getInstancePtr() == nullptr) return; MyGUI::InputManager& input = MyGUI::InputManager::getInstance(); if (!HotKeyManager::getInstance().onKeyEvent(true, input.isShiftPressed(), input.isControlPressed(), _key)) input.injectKeyPress(_key, _text); } void Application::setCaption(const MyGUI::UString& _value) { setWindowCaption(_value); } void Application::commandQuitApp(const MyGUI::UString& _commandName) { if (DialogManager::getInstance().getAnyDialog()) { DialogManager::getInstance().endTopDialog(); } else { if (MessageBoxManager::getInstance().hasAny()) { MessageBoxManager::getInstance().endTop(MyGUI::MessageBoxStyle::Cancel); } else { CommandManager::getInstance().executeCommand("Command_Quit"); } } } void Application::resumeState() { quit(); } } // namespace tools MYGUI_APP(tools::Application)
[ "albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c" ]
[ [ [ 1, 311 ] ] ]
a68facf51733f6d6aced2265719a225ef49c1229
4aadb120c23f44519fbd5254e56fc91c0eb3772c
/Source/EduNetGames/obsolete/Tutorial_02/ClientServerPlugin.cpp
19a139e8197af12763c039afe6d3e98f18811642
[]
no_license
janfietz/edunetgames
d06cfb021d8f24cdcf3848a59cab694fbfd9c0ba
04d787b0afca7c99b0f4c0692002b4abb8eea410
refs/heads/master
2016-09-10T19:24:04.051842
2011-04-17T11:00:09
2011-04-17T11:00:09
33,568,741
0
0
null
null
null
null
UTF-8
C++
false
false
959
cpp
#include "EduNetConnect/ClientServerPlugin.h" //----------------------------------------------------------------------------- void EduNetConnect::queryConnectionsSettings( ConnectSettings& kSettings ) { kSettings.uiClientStartPort = CLIENT_PORT; kSettings.uiServerStartPort = SERVER_PORT; kSettings.sessionPassword = "Tutorial2"; kSettings.uiPortPongCount = 10; } ClientServerPlugin* clientServerPlugin = NULL; EmptyServerPlugin* peerPlugin = NULL; EmptyClientPlugin* clientPlugin = NULL; //----------------------------------------------------------------------------- namespace EduNet { void initializeDynamicPlugins( ) { clientServerPlugin = ET_NEW ClientServerPlugin(); peerPlugin = ET_NEW EmptyServerPlugin(); clientPlugin = ET_NEW EmptyClientPlugin(); } void shutdownDynamicPlugins( ) { ET_SAFE_DELETE( clientServerPlugin ); ET_SAFE_DELETE( peerPlugin ); ET_SAFE_DELETE( clientPlugin ); } }
[ "janfietz@localhost" ]
[ [ [ 1, 34 ] ] ]
501330e24b8461579372f2270e64161f42aef3ec
fc4946d917dc2ea50798a03981b0274e403eb9b7
/gentleman/gentleman/WindowsAPICodePack/WindowsAPICodePack/DirectX/DirectX/DirectHelpers.cpp
df8a37f92e286f0ea8a51532708eb96da6b56f98
[]
no_license
midnite8177/phever
f9a55a545322c9aff0c7d0c45be3d3ddd6088c97
45529e80ebf707e7299887165821ca360aa1907d
refs/heads/master
2020-05-16T21:59:24.201346
2010-07-12T23:51:53
2010-07-12T23:51:53
34,965,829
3
2
null
null
null
null
UTF-8
C++
false
false
1,712
cpp
//Copyright (c) Microsoft Corporation. All rights reserved. #include "StdAfx.h" #include "DirectObject.h" #include "DirectUnknown.h" #include "DirectHelpers.h" #include "CommonUtils.h" using namespace Microsoft::WindowsAPICodePack::DirectX; using namespace Microsoft::WindowsAPICodePack::DirectX::DXGI; using namespace Microsoft::WindowsAPICodePack::DirectX::Direct2D1; using namespace Microsoft::WindowsAPICodePack::DirectX::Direct3D; generic <typename T> where T : DirectUnknown T DirectHelpers::CreateIUnknown(System::IntPtr nativePointer) { return safe_cast<T>(CommonUtils::CreateIUnknownWrapper<T>(static_cast<IUnknown*>(nativePointer.ToPointer()))); } generic <typename T> where T : DirectObject T DirectHelpers::CreateInterface(System::IntPtr nativePointer) { T wrapper = safe_cast<T>( Activator::CreateInstance(T::typeid, true) ); (safe_cast<DirectObject^>(wrapper))->Attach(nativePointer.ToPointer()); return wrapper; } Exception^ DirectHelpers::GetExceptionForHResult(int hr) { return CommonUtils::GetExceptionForHR(static_cast<HRESULT>(hr)); } Exception^ DirectHelpers::GetExceptionForErrorCode(ErrorCode errorCode) { return CommonUtils::GetExceptionForHR(static_cast<HRESULT>(errorCode)); } void DirectHelpers::ThrowExceptionForHResult(int hr) { int val = static_cast<HRESULT>(hr); if (SUCCEEDED(val)) return; else throw CommonUtils::GetExceptionForHR(val); } void DirectHelpers::ThrowExceptionForErrorCode(ErrorCode errorCode) { int val = static_cast<HRESULT>(errorCode); if (SUCCEEDED(val)) return; else throw CommonUtils::GetExceptionForHR(val); }
[ "lucemia@9e708c16-f4dd-11de-aa3c-59de0406b4f5" ]
[ [ [ 1, 59 ] ] ]
0baf14637b0da8b5fec50a0f01b0f4a15dabb7f8
9340e21ef492eec9f19d1e4ef2ef33a19354ca6e
/cing/src/graphics/BaseLight.h
c2fc7040e826a06998c667fb439950421068ebe3
[]
no_license
jamessqr/Cing
e236c38fe729fd9d49ccd1584358eaad475f7686
c46045d9d0c2b4d9e569466971bbff1662be4e7a
refs/heads/master
2021-01-17T22:55:17.935520
2011-05-14T18:35:30
2011-05-14T18:35:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,264
h
/* This source file is part of the Cing project For the latest info, see http://www.cing.cc Copyright (c) 2006-2009 Julio Obelleiro and Jorge Cano This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef _BaseLight_H_ #define _BaseLight_H_ // Precompiled headers #include "Cing-Precompiled.h" #include "SceneGraphElement.h" #include "GraphicsPrereqs.h" #include "graphics/Color.h" // Common #include "common/CommonTypes.h" namespace Cing { /** * @internal * Base class for all the lights */ class BaseLight: public SceneGraphElement { public: // Constructor / Destructor BaseLight(); virtual ~BaseLight(); // Init / Release / Update bool init ( float r, float g, float b, float x, float y, float z ); void end (); // Set methods void setPosition ( float x, float y, float z ); void setPosition ( float x, float y ); void setPosition ( const Vector& pos ); void setDirection ( float x, float y, float z ); void setDirection ( float x, float y ); void setDirection ( const Vector& dir ); void setDiffuseColor ( float r, float g, float b ); void setDiffuseColor ( const Color& color ); void setSpecularColor ( float r, float g, float b ); void setSpecularColor ( const Color& color ); void setLightType ( Light::LightTypes type ); void setAttenuation ( float range, float constant, float linear, float quadratic ); // Shadows void castShadows ( bool cast ); // Debug methods void drawDebug ( bool draw = true); // Query methods bool isValid () const { return m_bIsValid; } const Vector& getPosition () const; Ogre::Light* getOgreLight() { return m_pLight; } private: // Constant / static attributes static const std::string DEFAUTL_LIGHT_NAME; ///< Default name of the lights static long m_lightCounter; ///< Used to generate unique names for the lights // Attributes std::string m_lightName; ///< Name of this light Ogre::Light* m_pLight; ///< Pointer to the light object // Debugging purposes Ogre::BillboardSet* m_lightFlareSet; ///< Used to draw a billboard where the light is (to debug its position) Ogre::Billboard* m_lightFlare; ///< Used to draw a billboard where the light is (to debug its position) bool m_bIsValid; ///< Indicates whether the class is valid or not. If invalid none of its methods except init should be called. }; } // namespace Cing #endif // _BaseLight_H_
[ [ [ 1, 31 ], [ 33, 107 ] ], [ [ 32, 32 ] ] ]
aaa7734db72c8b8ff125192b90e13507caa723c5
14e30c5f520f0ed28117914101d9bdf2f3d5dac7
/project/source/mesh/face.h
f00f097cace654917b92dc23641ab11030c7dc2b
[]
no_license
danielePiracci/arlight
f356eb5a162d0cd62a759720cbc6da41a820642f
15a68c4c80c97f2fe7458e7ddf03f3e1063e25a4
refs/heads/master
2016-08-11T13:45:35.252916
2011-01-24T20:22:50
2011-01-24T20:22:50
44,962,821
0
0
null
null
null
null
UTF-8
C++
false
false
770
h
/// \file mesh/face.h /// \author Juan Carlos De Abreu ([email protected]) /// \date 2009/11/20 /// \version 1.0 /// /// \brief This file declares the DissertationProject::face /// class, which implement the basic functionalities of a triangle face. #ifndef MESH_FACE_H__ #define MESH_FACE_H__ #include "global.h" #include "math/vector.h" BEGIN_PROJECT_NAMESPACE(); class Face { public: // Face constructor and destructor. Face(vec3i vertex_ = vec3i(), vec3i normal_ = vec3i(), vec3i texture_ = vec3i()); ~Face(); // Attributes vec3i vertex; // Vextex indexes of the face vec3i normal; // Normals indexes of the face vec3i texture; // Texture indexes of the face }; END_PROJECT_NAMESPACE(); #endif // MESH_FACE_H__
[ "jcabreur@db05138c-34b8-7cfb-67b9-2db12d2e1ab0" ]
[ [ [ 1, 30 ] ] ]
20be84a863d96fa5c34b642819e5d6d8f9b2c181
9399383d7e227c4812e19f08a2d2c20cf66a0031
/Point.h
18dbeb7069e32e71b0d19878ea43596755da5e6f
[]
no_license
mattttttttsu/Edit-Engine-Test
bf5bf22c2b1a8937bc4ed062616d422153b7cb65
e3f74ba821a7ddb2f235c0cc519f899cc0b045ae
refs/heads/master
2021-01-10T19:11:27.119238
2011-11-29T18:52:40
2011-11-29T18:52:40
2,877,257
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,594
h
#ifndef _POINT_H_ #define _POINT_H_ namespace EditTest { /** * バッファ上のキャレット。 * 文字単位で座標を管理する。 */ class LogicalPoint { private: /** * X座標 */ int xPosition; /** * Y座標 */ int yPosition; public: /** * コンストラクタ */ LogicalPoint() { xPosition = 0; yPosition = 0; } /** * X座標をセットする * @param int x X座標。 */ void SetX(int x) { xPosition = x; } /** * Y座標をセットする * @param int y Y座標 */ void SetY(int y) { yPosition = y; } /** * X座標を返す * @return int X座標 */ int GetX() { return xPosition; } /** * Y座標を返す * @return y座標 */ int GetY() { return yPosition; } /** * 他のLogicalPointの値を直接セットする。 * @param LogicalPoint* source 元になるオブジェクト */ void SetPoint(LogicalPoint* source) { xPosition = source->GetX(); yPosition = source->GetY(); } /** * デストラクタ */ ~LogicalPoint() { } }; /** * ビュー上のキャレット。 * ピクセル単位で座標を管理する。 */ class PhysicalPoint { private: /** * X座標(ピクセル) */ int xPosition; /** * Y座標(ピクセル) */ int yPosition; public: /** * コンストラクタ */ PhysicalPoint() { } /** * X座標をセットする * @param int x X座標。 */ void SetX(int x) { xPosition = x; } /** * Y座標をセットする * @param int y Y座標 */ void SetY(int y) { yPosition = y; } /** * X座標を返す * @return int X座標 */ int GetX() { return xPosition; } /** * Y座標を返す * @return y座標 */ int GetY() { return yPosition; } /** * 他のPhysicalPointの値を直接セットする。 * @param PhysicalPoint* source 元になるオブジェクト */ void SetPoint(PhysicalPoint* source) { xPosition = source->GetX(); yPosition = source->GetY(); } /** * デストラクタ */ ~PhysicalPoint() { } }; }; #endif
[ [ [ 1, 170 ] ] ]
4f09cd788c4c9ec9a557e4a3c5878aaf0873663d
0b66a94448cb545504692eafa3a32f435cdf92fa
/branches/nn/cbear.berlios.de/range/size_type.hpp
7c20ab5f6ee9e30ee6f32f17be0c06f2a182a288
[ "MIT" ]
permissive
BackupTheBerlios/cbear-svn
e6629dfa5175776fbc41510e2f46ff4ff4280f08
0109296039b505d71dc215a0b256f73b1a60b3af
refs/heads/master
2021-03-12T22:51:43.491728
2007-09-28T01:13:48
2007-09-28T01:13:48
40,608,034
0
0
null
null
null
null
UTF-8
C++
false
false
333
hpp
#ifndef CBEAR_BERLIOS_DE_RANGE_SIZE_TYPE_HPP_INCLUDED #define CBEAR_BERLIOS_DE_RANGE_SIZE_TYPE_HPP_INCLUDED #include <cbear.berlios.de/range/traits.hpp> namespace cbear_berlios_de { namespace range { template<class Container> struct size_type { typedef typename traits<Container>::size_type type; }; } } #endif
[ "nn0@e6e9985e-9100-0410-869a-e199dc1b6838" ]
[ [ [ 1, 17 ] ] ]
399e06d1170dddfdb173ef9cff0ee9e3d7bed7d9
208475bcab65438eed5d8380f26eacd25eb58f70
/ComuExe/PhoneWcdma.h
fb62bd498a8ef2c330164fd4e4fbc75afae0d2cd
[]
no_license
awzhang/MyWork
83b3f0b9df5ff37330c0e976310d75593f806ec4
075ad5d0726c793a0c08f9158080a144e0bb5ea5
refs/heads/master
2021-01-18T07:57:03.219372
2011-07-05T02:41:55
2011-07-05T02:46:30
15,523,223
1
2
null
null
null
null
GB18030
C++
false
false
15,651
h
#ifndef _PHONEWCDMA_H_ #define _PHONEWCDMA_H_ #define WCDMA_FILE "/mnt/Flash/part3/WcdmaLog" #define QUEUE_WCDMABUF_SIZE 1100000 // 1M的缓冲区区 #define QUEUE_WCDMABUF_PERIOD 0xfffffff8 #if RESET_ENABLE_ALL == 1 #define WCDMA_WRITE_FILE_CNT 200 //队列里面有多少个数据的时候才去写文件。 #else #define WCDMA_WRITE_FILE_CNT 10 //队列里面有多少个数据的时候才去写文件。 #endif // #define WCDMA_FILE_VER "20100119" // typedef STRUCT_1 atAck // { // INT8U numEC; /* number of END'S characters */ // INT16U bufsize; /* ack buffer size */ // INT8U ackbuf[512]; /* ack buffer */ // INT8U cb_index; /* cmd data cb index */ // // atAck() // { // memset(this,0,sizeof(*this)); // } // }ATCMDACK_T; enum WCDMA_ATANS { WCDMA_ATANS_OK = 1, WCDMA_ATANS_ERROR, WCDMA_ATANS_CMEERR, WCDMA_ATANS_NOANS, WCDMA_ATANS_RCVNOTALL, // { 仅用于呼入呼出 WCDMA_ATANS_NOANSWER, WCDMA_ATANS_NOCARRIER, WCDMA_ATANS_NODIALTONE, WCDMA_ATANS_BUSY, WCDMA_ATANS_NOCALL, // 不在通话中 // } 仅用于呼入呼出 WCDMA_ATANS_OTHER }; enum WCDMA_PHONESTA { WCDMA_PST_INIT = 1, WCDMA_PST_IDLE, WCDMA_PST_DIALNET, WCDMA_PST_WAITDIALNET, WCDMA_PST_CUTNET, WCDMA_PST_RESET, WCDMA_PST_DIALLSN, WCDMA_PST_WAITLSNPICK, WCDMA_PST_LSNING, WCDMA_PST_DIAL, WCDMA_PST_WAITPICK, WCDMA_PST_HOLD, WCDMA_PST_HANGUP, WCDMA_PST_RCVRING }; // enum WCDMA_PINGSTA // { // WCDMA_PINGST_IDLE = 666, // WCDMA_PINGST_DOING, // WCDMA_PINGST_SUCC, // WCDMA_PINGST_FAIL, // WCDMA_PINGST_CANCEL // }; enum WCDMA_AUDIOMODE { WCDMA_AUDIOMODE_HANDFREE = 1, //免提// 不要太大,有的结构体里只用1个字节保存 WCDMA_AUDIOMODE_EARPHONE, //耳机 WCDMA_AUDIOMODE_LSN, //监听 WCDMA_AUDIOMODE_DIAL, //拨号模式(非监听拨号) WCDMA_AUDIOMODE_CLOSE //通话关闭模式 }; // 任务指令定义(可或起来) const DWORD WCDMA_PHTASK_DIALSN = 0X00000001; const DWORD WCDMA_PHTASK_DIAL = 0X00000002; const DWORD WCDMA_PHTASK_RING = 0X00000004; const DWORD WCDMA_PHTASK_SETSMSCENT = 0X00000008; const DWORD WCDMA_PHTASK_SNDDTMF = 0X00000010; const DWORD WCDMA_PHTASK_PICKUP = 0X00000020; const DWORD WCDMA_PHTASK_HANGUP = 0X00000040; const DWORD WCDMA_PHTASK_CHGAUDIO = 0X00000080; //免提耳机切换 const DWORD WCDMA_PHTASK_CHGVOL = 0X00000100; //调节音量 const DWORD WCDMA_PHTASK_PING = 0x00000200; const DWORD WCDMA_PHTASK_PINGRPT = 0x00000400; const DWORD WCDMA_PHTASK_CUTNET = 0x00000800; const DWORD WCDMA_PHTASK_ALERM = 0x00001000; //报警 const DWORD WCDMA_PHTASK_RESET = 0x00002000; // 任务数据定义 (多线程访问,需要互斥) struct tagWcdmaPhoneTask { DWORD m_dwTaskSymb; // 取值见上面的定义 // bool m_bDialLsn; char m_szDialLsnTel[20]; // bool m_bDial; char m_szDialTel[20]; DWORD m_dwHoldLmtPrid; // bool m_bRing; // char m_szRingTel[20]; // bool m_bSetSmsCent; // char m_szSmsCent[19]; // bool m_bSndDTMF; char m_szDTMF[60]; // bool m_bSndSms; // bool m_bHangUp; // 用户操作主动挂机 BYTE m_bytChgAudio; // WCDMA_AUDIOMODE_HANDFREE,切换到免提; WCDMA_AUDIOMODE_EARPHONE,切换到耳机 int m_iChgVol; // 1,增大; -1,减小 // bool m_bPing; BYTE m_bytPingSrc; // 1,QianExe; 2,StreamMedia (或的关系 ) BYTE m_bytPingRptSrc; BYTE m_bytPingResult; // 0,成功; 1,失败; 2,异常; 3,被取消 // bool m_bCutNet; // DWORD m_dwAlertBegin; DWORD m_dwAlertPrid; tagWcdmaPhoneTask() { memset(this, 0, sizeof(*this)); } }; /// { 状态机中每一个状态对应的状态值 (仅在状态机线程中使用,无需互斥访问) struct tagWcdmaPhoneStaDial { DWORD m_dwDialBeginTm; DWORD m_dwHoldLmtPrid; char m_szDialTel[20]; void Init() { memset(this, 0, sizeof(*this)); } tagWcdmaPhoneStaDial() { Init(); } }; struct tagWcdmaPhoneStaHold { DWORD m_dwHoldBeginTm; DWORD m_dwHoldLmtPrid; DWORD m_dwCallChkTm; void Init() { memset(this, 0, sizeof(*this)); } tagWcdmaPhoneStaHold() { Init(); } }; struct tagWcdmaPhoneStaDialLsn { DWORD m_dwDialBeginTm; char m_szDialLsnTel[20]; void Init() { memset(this, 0, sizeof(*this)); } tagWcdmaPhoneStaDialLsn() { Init(); } }; struct tagWcdmaPhoneStaLsning { DWORD m_dwCallChkTm; void Init() { memset(this, 0, sizeof(*this)); } tagWcdmaPhoneStaLsning() { Init(); } }; struct tagWcdmaPhoneStaRing { DWORD m_dwHoldLmtPrid; BYTE m_bytCallInType; // 呼入类型:0,允许呼入 1,中心主动监听号码 2,禁止呼入号码 3,中心服务电话号码 4,UDP激活号码 char m_szRingTel[20]; DWORD m_dwLstChkRingTm; void Init() { memset(this, 0, sizeof(*this)); m_dwLstChkRingTm = GetTickCount(); } tagWcdmaPhoneStaRing() { Init(); } }; /// } 状态机中每一个状态对应的状态值 // 通用状态处理标记 (按位定义) const DWORD WCDMA_PHSTVAR_IMEI = 0X00000001; const DWORD WCDMA_PHSTVAR_SING = 0X00000002; const DWORD WCDMA_PHSTVAR_ALERT = 0X00000004; const DWORD WCDMA_PHSTVAR_NET = 0X00000008; const DWORD WCDMA_PHSTVAR_PING = 0X00000010; const DWORD WCDMA_PHSTVAR_AUDIOMODE = 0X00000020; const DWORD WCDMA_PHSTVAR_AUDIOOUTLVL = 0x00000040; /// { 状态机中多个状态下需要使用的状态值 (可能多线程访问,需要互斥) struct tagWcdmaPhoneStaCommon { char m_szGsmIMEI[128]; int m_iSignal; DWORD m_dwAlertBegin; DWORD m_dwAlertPrid; int m_iAudioOutVol; // 通话时音量输出增益: 0~5 BYTE m_bytCurAudioMode; bool m_bNetConnected; BYTE m_bytPingSrc; // 1,QianExe; 2,StreamMedia (或的关系 ) void Init() { memset(this, 0, sizeof(*this)); m_iAudioOutVol = 4; } tagWcdmaPhoneStaCommon() { Init(); } }; /// } 状态机中多个状态下需要使用的状态值 typedef int ( *PCHKATRES) (char* v_szAtRes, void* v_pResult, size_t v_sizResult ); class CPhoneWcdma { public: CPhoneWcdma(); virtual ~CPhoneWcdma(); void ResetPhone(); void ReDialNet(); BYTE GetPhoneState(); int GetPhoneHdlSta(); int GetPhoneSignal(); void GetPhoneIMEI( char* v_szImei, size_t v_sizImei ); int GetPhoneVolume(); int InitPhone(); void ReleasePhone(); int _PppSigHandler(); protected: unsigned long P_PhoneHdl(); friend unsigned long G_WCDMA_PhoneHdl(void* v_pPar); unsigned long P_ComRcv(); friend unsigned long G_WCDMA_ComRcv(void* v_pPar); unsigned long P_OtherHdl(); friend unsigned long G_WCDMA_OtherHdl(void* v_pPar); // unsigned long P_Ping(); friend unsigned long G_WCDMA_Ping(void* v_pPar); private: void _GsmHardReset(); void _GsmReset(); void _GsmPowOn(); void _GsmPowOff(); int _InitCom(); int _CloseCom(); int _OtherHdl(); // { 仅被状态机线程调用 int _ComSnd(void* v_pSnd, DWORD v_dwSndLen ); int _SetAT( DWORD v_dwWaitPerTime, BYTE v_bytTryTimes, void* v_pResult, size_t v_sizResult, PCHKATRES v_pChkRes, DWORD v_dwSndLen, char* v_szATCmd, ... ); int _ReadAT( DWORD v_dwWait, void* v_pResult, size_t v_sizResult, PCHKATRES v_pChkRes ); int _PhoneDataDeal(char* v_szAtData); int _PhoneHdl(); int _PhoneStaHdl_Init(); int _PhoneStaHdl_Idle( int& v_iNextSta ); int _PhoneStaHdl_DialLsn( int& v_iNextSta ); int _PhoneStaHdl_WaitLsnPick( int &v_iNextSta ); int _PhoneStaHdl_Lsning(int &v_iNextSta ); int _PhoneStaHdl_Dial( int &v_iNextSta ); int _PhoneStaHdl_WaitPick( int &v_iNextSta ); int _PhoneStaHdl_Hold( int &v_iNextSta ); int _PhoneStaHdl_RcvRing( int& v_iNextSta ); int _PhoneStaHdl_Hangup( int &v_iNextSta ); int _PhoneStaHdl_Reset(); int _PhoneStaHdl_DialNet( int &v_iNextSta ); int _PhoneStaHdl_WaitDialNet( int &v_iNextSta ); void _PhoneStaHdl_CutNet( int &v_iNextSta ); void _PhoneJugSmsSnd(); int _PhoneJugSmsRcv(); void _PhoneJugSmsCentSet(); void _PhoneJugSmsPingRpt(); void _PhoneJugAlerm(); BOOL _PhoneJugReset(); BOOL _PhoneJugCutNet(); int _PhoneAudioModeSet(int v_iChgToMode); int _PhoneAudioOutVolSet(int v_iChgDegree); int _PhoneSmsSnd( SM_PARAM& v_objSmPar ); int _PushSndSms(char *to, byte tolen, char *msg, byte msglen, BYTE v_bytSrcType); bool sms_deal(SM_PARAM *psm); int _QueryRcvSMS(); int _PhoneDialNet(); void _PhoneCutNet(); int _ForkPppd(); int convert6to7(char *sptr, char *dptr, int len); int convert6to8(const char* strOldBuf, char* strNewBuf, const int iOldLen); bool check_crc1(const byte *buf, const int len); // 查表 byte get_crc1(const byte *buf, const int len); // 查表 bool check_crc2(const byte *buf, const int len); // 直接取累加和 byte get_crc2(const byte *buf, const int len); // 直接取累加和 // } 仅被状态机线程调用 tagWcdmaPhoneTask _PhoneTaskGet( DWORD v_dwToGetTaskSymb ); void _PhoneTaskSet( const tagWcdmaPhoneTask& v_objPhoneTask, DWORD v_dwToSetTaskSymb ); void _PhoneTaskClr(DWORD v_dwToGetTaskSymb); void _ClearPhoneTask( DWORD v_dwToGetTaskSymb, tagWcdmaPhoneTask& v_objPhoneTask ); tagWcdmaPhoneStaCommon _PhoneStaCommonGet( DWORD v_dwToClrStaSymb ); void _PhoneStaCommonSet( const tagWcdmaPhoneStaCommon& v_objPhoneStaCommon, DWORD v_dwToSetStaSymb ); void _PhoneStaCommonClr(DWORD v_dwToClrStaSymb); void _ClearPhoneStaCommon(tagWcdmaPhoneStaCommon& v_objPhoneStaCommon, DWORD v_dwToClrStaSymb); byte tel_type(bool callout, char *tel, byte len, ushort *holdtime); int JugTelType( char* v_szTel, unsigned char v_ucTelLen, unsigned char* v_p_cTelType ); int JugTelType2( char* v_szTel, unsigned char v_ucTelLen, unsigned char* v_p_cTelType, WORD* v_p_wLmtOutPeriod, WORD* v_p_wLmtInPeriod ); int JugTelType3(char* v_szTel, unsigned char v_ucTelLen, unsigned char* v_p_cTelType, WORD* v_p_wLmtOutPeriod, WORD* v_p_wLmtInPeriod); private: //基站采集添加 bool m_bSaveExitFlag; volatile bool m_bSaveThRunSta;//非线程安全 int m_iPhonePort; //手机模块串口设备文件句柄 pthread_t m_hThdComRcv; //串口接收线程句柄 pthread_t m_hThdPhoneHdl; pthread_t m_hThdOtherHdl; // pthread_t m_hThdPing; //多线程访问互斥量 pthread_mutex_t m_crisecRcv; pthread_mutex_t m_crisecPhoneTask; pthread_mutex_t m_crisecSta; pthread_mutex_t m_crisecDog; CInnerDataMng m_objDataMngRcv; CInnerDataMng m_objDataMngSmsSnd; CInnerDataMng m_objDataMngSmsRcv; tagWcdmaPhoneTask m_objPhoneTask; // 状态机中单一状态使用的状态值 tagWcdmaPhoneStaDial m_objPhoneStaDial; tagWcdmaPhoneStaDialLsn m_objPhoneStaDialLsn; tagWcdmaPhoneStaHold m_objPhoneStaHold; tagWcdmaPhoneStaLsning m_objPhoneStaLsning; tagWcdmaPhoneStaRing m_objPhoneStaRing; // 多个状态及多线程要使用的状态值 tagWcdmaPhoneStaCommon m_objPhoneStaCommon; DWORD m_dwClrDogTm; volatile int m_iPhoneHdlSta; volatile bool m_bPhoneNetReady; volatile bool m_bToClosePhone; volatile bool m_bNeedDialNet; DWORD m_dwDialNetTm; // private://基站采集添加 // long m_GpsChangeBuf[64]; // bool m_bGpsChangeInitFlag;//gps形变初始化标志,在gps无效后重新定位的情况下,最好重新置wg_flag0初始化,再进行形变 // int m_ucCurCltCyc; // unsigned long m_ulWcdmaIndex; // INT16U s_sqm; // ATDATA_CPSI_T s_cpsi_t; // ATDATA_CRUS_T s_crus_t; // // CInnerDataMng m_objWcdmaBaseQue; // WCDMAFILE_HEAD m_objWcdmaFileHead; // byte m_bytServeType; // ATCltCyc m_objWcdmaCltCyc; // void _KillTimer(UINT v_uiTmID); // UINT _SetTimer(UINT v_uiTmID, UINT v_uiInterval); // bool InitWcdmaFile(); //public: // void P_QueryWcdmaBase(); // void P_SaveWcdmaData(); // void SaveWcdmaDataRst(); // bool g_bNeedUpLine; // bool query_CPSI(); // bool query_CRUS(); // bool Handler_AT_CPSI(INT8U *recvbuf, INT16U len, ATCMDACK_T *ATCmdAck); // bool Handler_AT_CRUS(INT8U *recvbuf, INT16U len, ATCMDACK_T *ATCmdAck); // // INT8U CharToHex(INT8U schar) // { // if (schar >= '0' && schar <= '9') // return (schar - '0'); // else if (schar>='A' && schar<='F') // return (schar - 'A' + 0x0A); // else if (schar>='a' && schar<='f') // return (schar - 'a' + 0x0A); // else // return 0; // } // // BOOLEAN SearchKeyWord(INT8U *ptr, INT16U maxlen, char *sptr) // { // char *tmpptr = NULL; // // if (*sptr == 0) return FALSE; // tmpptr = sptr; // while(maxlen > 0) // { // if (*ptr == *tmpptr) // { // if (*(tmpptr+1) == 0) // return TRUE; // } // else // { // if(tmpptr != sptr) // { // tmpptr = sptr; // continue; // } // tmpptr = sptr-1; //-1是为tmpptr++做调整 // } // ptr++; // tmpptr++; // maxlen--; // } // return FALSE; // } // // INT32U SearchDigitalString(INT8U *ptr, INT16U maxlen, INT8U flagchar, INT8U numflag, INT8U base) // { // BOOLEAN find = FALSE; // INT32U result; // INT8U *bptr = NULL, *eptr = NULL; // // for(;;) // { // if (maxlen == 0) // { // find = FALSE; // break; // } // if (*ptr == flagchar) // { // numflag--; // if (numflag == 0) // { // eptr = ptr; // break; // } // } // if((*ptr>='0'&&*ptr<='9')||(*ptr>='A'&&*ptr<='F')||(*ptr>='a'&&*ptr<='f')) // { // if (!find) // { // find = TRUE; // bptr = ptr; // } // } // else // { // find = FALSE; // } // ptr++; // maxlen--; // } // // if (find) // { // result = 0; // for(;;) // { // result = result*base + CharToHex(*bptr++); // if (bptr == eptr) // break; // } // } // else // { // result = 0xffff; // } // return result; // } // // // INT16U FindCharPos(INT8U *sptr, char findchar, INT8U numchar, INT16U maxlen) // { // INT16U pos; // // if (maxlen == 0) // return 0; // pos = 0; // for (;;) // { // if (*sptr++ == findchar) // { // if (numchar == 0) // break; // else // numchar--; // } // maxlen--; // pos++; // if (maxlen == 0) // break; // } // return pos; // } // // void Prase_DecimalandPoint(INT8U *ptr, INT16U maxlen, INT8U amply, INT16S *eptr) // { // BOOLEAN find_d, find_p, decimal; // INT16S result; // // find_d = FALSE; // find_p = FALSE; // decimal = FALSE; // result = 0; // // for (;;) // { // if ((0 == maxlen) || (0 == amply)) break; // 字符串结束, 或放大结束 // // if ('-' == *ptr) // { // if (FALSE == decimal) // { // decimal = TRUE; // ptr++; // maxlen--; // continue; // } // else // break; // } // // if ('0' <= *ptr && '9' >= *ptr) // { // if (FALSE == find_d) // find_d = TRUE; // else if (TRUE == find_p) // amply--; // result = result*10 + CharToHex(*ptr); // } // else if ('.' == *ptr) // { // if ((TRUE == find_d) && (FALSE == find_p)) // find_p = TRUE; // else // break; // } // ptr++; // maxlen--; // } // if (FALSE == decimal) // *eptr = result; // else // *eptr = 0 - result; // return; // } }; #endif //#ifndef _PHONEWCDMA_H_
[ [ [ 1, 584 ] ] ]
9637d897f800a0e38074afd579d853a92f3756de
4f89f1c71575c7a5871b2a00de68ebd61f443dac
/lib/boost/gil/extension/opencv/edge_detection.hpp
4a61d06c571adb906d133463266b5e5e76147acc
[]
no_license
inayatkh/uniclop
1386494231276c63eb6cdbe83296cdfd0692a47c
487a5aa50987f9406b3efb6cdc656d76f15957cb
refs/heads/master
2021-01-10T09:43:09.416338
2009-09-03T16:26:15
2009-09-03T16:26:15
50,645,836
0
0
null
null
null
null
UTF-8
C++
false
false
8,346
hpp
/* Copyright 2008 Christian Henning 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). */ /*************************************************************************************************/ #ifndef BOOST_GIL_EXTENSION_OPENCV_EDGE_DETECTION_HPP_INCLUDED #define BOOST_GIL_EXTENSION_OPENCV_EDGE_DETECTION_HPP_INCLUDED //////////////////////////////////////////////////////////////////////////////////////// /// \file /// \brief /// \author Christian Henning \n /// /// \date 2008 \n /// //////////////////////////////////////////////////////////////////////////////////////// #include <boost/type_traits/is_base_of.hpp> #include <boost/utility/enable_if.hpp> #include "ipl_image_wrapper.hpp" namespace boost { namespace gil { namespace opencv { struct aperture_base {}; struct aperture1 : aperture_base, boost::mpl::int_< 1 > {}; struct aperture3 : aperture_base, boost::mpl::int_< 3 > {}; struct aperture5 : aperture_base, boost::mpl::int_< 5 > {}; struct aperture7 : aperture_base, boost::mpl::int_< 7 > {}; struct aperture_scharr : aperture_base, boost::mpl::int_< CV_SCHARR > {}; // default template parameter for function, only for classes template< typename Aperture > inline void sobel( const ipl_image_wrapper& src , ipl_image_wrapper& dst , const Aperture& , size_t x_order = 1 , size_t y_order = 0 , typename boost::enable_if< typename boost::is_base_of< aperture_base , Aperture >::type >::type* ptr = 0 ) { cvSobel( src.get() , dst.get() , x_order , y_order , Aperture::type::value ); } template< typename View , typename Aperture > inline void sobel( View src , View dst , const Aperture& aperture , std::size_t x_order = 1 , std::size_t y_order = 0 , typename boost::enable_if< typename boost::is_base_of< aperture_base , Aperture >::type >::type* ptr = 0 ) { ipl_image_wrapper src_ipl = create_ipl_image( src ); ipl_image_wrapper dst_ipl = create_ipl_image( dst ); sobel( src_ipl , dst_ipl , aperture , x_order , y_order ); } template< typename Aperture > inline void laplace( const ipl_image_wrapper& src , ipl_image_wrapper& dst , const Aperture& , typename boost::enable_if< typename boost::is_base_of< aperture_base , Aperture >::type >::type* ptr = 0 ) { cvLaplace( src.get() , dst.get() , Aperture::type::value ); } template< typename View_Src , typename View_Dst , typename Aperture > inline void laplace( View_Src src , View_Dst dst , const Aperture& aperture , typename boost::enable_if< typename boost::is_base_of< aperture_base , Aperture >::type >::type* ptr = 0 ) { ipl_image_wrapper src_ipl = create_ipl_image( src ); ipl_image_wrapper dst_ipl = create_ipl_image( dst ); laplace( src_ipl , dst_ipl , aperture ); } template< typename Aperture > inline void canny( const ipl_image_wrapper& src , ipl_image_wrapper& dst , double threshold1 , double threshold2 , const Aperture& , typename boost::enable_if< typename boost::is_base_of< aperture_base , Aperture >::type >::type* ptr = 0 ) { cvCanny( src.get() , dst.get() , threshold1 , threshold2 , Aperture::type::value ); } template< typename View , typename Aperture > inline void canny( View src , View dst , double threshold1 , double threshold2 , const Aperture& aperture , typename boost::enable_if< typename boost::is_base_of< aperture_base , Aperture >::type >::type* ptr = 0 ) { ipl_image_wrapper src_ipl = create_ipl_image( src ); ipl_image_wrapper dst_ipl = create_ipl_image( dst ); canny( src_ipl , dst_ipl , threshold1 , threshold2 , aperture ); } template< typename Aperture > inline void precorner_detect( const ipl_image_wrapper& src , ipl_image_wrapper& dst , const Aperture& , typename boost::enable_if< typename boost::is_base_of< aperture_base , Aperture >::type >::type* ptr = 0 ) { cvPreCornerDetect( src.get() , dst.get() , Aperture::type::value ); } template< typename View_Src , typename View_Dst , typename Aperture > inline void precorner_detect( View_Src src , View_Dst dst , const Aperture& aperture , typename boost::enable_if< typename boost::is_base_of< aperture_base , Aperture >::type >::type* ptr = 0 ) { ipl_image_wrapper src_ipl = create_ipl_image( src ); ipl_image_wrapper dst_ipl = create_ipl_image( dst ); precorner_detect( src_ipl , dst_ipl , aperture ); } template< typename Aperture > inline void corner_eigen_vals_and_vecs( const ipl_image_wrapper& src , ipl_image_wrapper& dst , const std::size_t block_size , const Aperture& , typename boost::enable_if< typename boost::is_base_of< aperture_base , Aperture >::type >::type* ptr = 0 ) { if ( src.get()->width * 6 != dst.get()->width ) { throw std::runtime_error( "Destination image must be 6 times wider." ); } cvCornerEigenValsAndVecs( src.get() , dst.get() , block_size , Aperture::type::value ); } template< typename View_Src , typename View_Dst , typename Aperture > inline void corner_eigen_vals_and_vecs( View_Src src , View_Dst dst , const std::size_t block_size , const Aperture& aperture , typename boost::enable_if< typename boost::is_base_of< aperture_base , Aperture >::type >::type* ptr = 0 ) { ipl_image_wrapper src_ipl = create_ipl_image( src ); ipl_image_wrapper dst_ipl = create_ipl_image( dst ); corner_eigen_vals_and_vecs( src_ipl , dst_ipl , block_size , aperture ); } } // namespace opencv } // namespace gil } // namespace boost #endif // BOOST_GIL_EXTENSION_OPENCV_EDGE_DETECTION_HPP_INCLUDED
[ "rodrigo.benenson@gmailcom" ]
[ [ [ 1, 271 ] ] ]
89e4148a3a4e029c4e28d4732a7989fa405cbfb9
6e563096253fe45a51956dde69e96c73c5ed3c18
/dhnetsdk/dvr/dvrdevice/dvrconfigchannel.h
559c84a86fba32a5a35fb4088c6af49d782d4c75
[]
no_license
15831944/phoebemail
0931b76a5c52324669f902176c8477e3bd69f9b1
e10140c36153aa00d0251f94bde576c16cab61bd
refs/heads/master
2023-03-16T00:47:40.484758
2010-10-11T02:31:02
2010-10-11T02:31:02
null
0
0
null
null
null
null
GB18030
C++
false
false
1,119
h
/* * Copyright (c) 2009, 浙江亿蛙技术股份有限公司 * All rights reserved. * * 类名称:配置功能交互类 * 摘 要:配置功能数据交互。 * */ ////////////////////////////////////////////////////////////////////////// #ifndef _DVRCONFIGCHANNEL_H_ #define _DVRCONFIGCHANNEL_H_ #include "dvrchannel.h" class CDvrDevice; class CDvrConfigChannel : public CDvrChannel { public: CDvrConfigChannel(CDvrDevice *pDvrDevice, int nMainCommand, void *pParam); virtual ~CDvrConfigChannel(); public: /* 关闭通道 */ virtual BOOL channel_close(); /* 暂停通道 */ virtual BOOL channel_pause(BOOL pause); /* 获取信息 */ virtual int channel_get_info(int type, void *parm); /* 设置信息 */ virtual int channel_set_info(int type, void *parm); /* 处理命令 */ virtual int OnRespond(unsigned char *pBuf, int nLen); public: unsigned int GetConfigType() { return m_config_channel_parm.type; } private: afk_config_channel_param_s m_config_channel_parm; }; #endif // _DVRCONFIGCHANNEL_H_
[ "guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd" ]
[ [ [ 1, 52 ] ] ]
ea4c4638f9080e4979b6dc213662bc5dfbaa5bf2
bc4919e48aa47e9f8866dcfc368a14e8bbabbfe2
/Open GL Basic Engine/source/glutFramework/glutFramework/LogicInterface.cpp
6d2fc31daa156cccab025916f1f6af343795be14
[]
no_license
CorwinJV/rvbgame
0f2723ed3a4c1a368fc3bac69052091d2d87de77
a4fc13ed95bd3e5a03e3c6ecff633fe37718314b
refs/heads/master
2021-01-01T06:49:33.445550
2009-11-03T23:14:39
2009-11-03T23:14:39
32,131,378
0
0
null
null
null
null
UTF-8
C++
false
false
51,386
cpp
#include "LogicInterface.h" #include "oglTexture2D.h" #include <sstream> LogicInterface::LogicInterface() : myMenu(NULL), isButtonBeingClicked(false), sideBarBox(), bottomBarBox(), sideBarColumnCount(3), instructionBlockW(140 / 3), instructionBlockH(140 / 3), instructionSpacing(2), logicBankBox(), instructionListBox(), logicBankNumColumns(4), logicBankNumRowsOnScreen(3), instructionListNumColumns(8), instructionListNumRowsOnScreen(3), mouseX(0), mouseY(0), currentHoverBlockIndex(-1), curInstrTab(TAB_MAIN), isExecuting(false), resetMenu(NULL), curExecutionListYOffset(NULL), executionListYOffset(0), executionListSub1YOffset(0), executionListSub2YOffset(0), scrollBar(NULL), mapByteLimit(0), usedBytes(0), drawInsertionLine(false), insertionLineColumn(0), insertionLineRow(0), insertionLine(NULL), draggedBlockMouseX(0), draggedBlockMouseY(0), logicBankScrollbarXOffset(5), isProcessingSub(false) { //sideBarBox.width = 150; //sideBarBox.height = 618; //sideBarBox.x = 874; //sideBarBox.y = 0; bottomBarBox.width = 1024 + 13; bottomBarBox.height = 190; bottomBarBox.x = -10; bottomBarBox.y = 618 - 40; logicBankBox.width = instructionSpacing + ((instructionSpacing + instructionBlockW)* logicBankNumColumns); logicBankBox.height = bottomBarBox.height - 20; //logicBankBox.x = bottomBarBox.x + 40; //logicBankBox.y = bottomBarBox.y + 25; logicBankBox.x = 34; logicBankBox.y = 768-190+15; instructionListBox.width = instructionSpacing + ((instructionSpacing + instructionBlockW) * instructionListNumColumns); instructionListBox.height = logicBankBox.height; //instructionListBox.x = logicBankBox.x + logicBankBox.width + 50; //instructionListBox.y = logicBankBox.y; instructionListBox.x = 345; instructionListBox.y = 600; //============================================= // Menu buttons (scrolling the instruction lists) alwaysActiveMenu = new MenuSys(0, 0, "blank.png", None); alwaysActiveMenu->addButton("scrollbarUp.png", "scrollbarUp.png", "scrollbarUpLit.png", BE::CreateFunctionPointer0R(this, &LogicInterface::LogicBankUpArrowButtonClick)); alwaysActiveMenu->setLastButtonDimensions(25, 25); alwaysActiveMenu->setLastButtonPosition(logicBankBox.x + logicBankBox.width + logicBankScrollbarXOffset, logicBankBox.y); alwaysActiveMenu->addButton("scrollbarDown.png", "scrollbarDown.png", "scrollbarDownLit.png", BE::CreateFunctionPointer0R(this, &LogicInterface::LogicBankDownArrowButtonClick)); alwaysActiveMenu->setLastButtonDimensions(25, 25); alwaysActiveMenu->setLastButtonPosition(logicBankBox.x + logicBankBox.width + logicBankScrollbarXOffset, logicBankBox.y + logicBankBox.height - 45); alwaysActiveMenu->addButton("scrollbarUp.png", "scrollbarUp.png", "scrollbarUpLit.png", BE::CreateFunctionPointer0R(this, &LogicInterface::ExecutionListUpArrowButtonClick)); alwaysActiveMenu->setLastButtonDimensions(25, 25); alwaysActiveMenu->setLastButtonPosition(instructionListBox.x + instructionListBox.width, instructionListBox.y); alwaysActiveMenu->addButton("scrollbarDown.png", "scrollbarDown.png", "scrollbarDownLit.png", BE::CreateFunctionPointer0R(this, &LogicInterface::ExecutionListDownArrowButtonClick)); alwaysActiveMenu->setLastButtonDimensions(25, 25); alwaysActiveMenu->setLastButtonPosition(instructionListBox.x + instructionListBox.width, instructionListBox.y + instructionListBox.height - 45); // help button // visual location is kinda sorta hard coded, don't expect any automagical stuff on this one // and since i'm hacking this to hell and back i'm using the compass menu system alwaysActiveMenu->addButton("buttons\\help.png", "buttons\\helphover.png", "buttons\\helphover.png", BE::CreateFunctionPointer0R(this, &LogicInterface::launchHelpState)); alwaysActiveMenu->setLastButtonDimensions(75, 30); alwaysActiveMenu->setLastButtonPosition(925, 725); // speed up alwaysActiveMenu->addButton("compass\\greaterthan.png", "compass\\greaterthanhover.png", "compass\\greaterthanhover.png", CreateFunctionPointer0R(this, &LogicInterface::speedUpButtonClick)); alwaysActiveMenu->setLastButtonDimensions(32, 32); alwaysActiveMenu->setLastButtonPosition(302+2, 600); // slow down alwaysActiveMenu->addButton("compass\\lessthan.png", "compass\\lessthanhover.png", "compass\\lessthanhover.png", CreateFunctionPointer0R(this, &LogicInterface::slowDownButtonClick)); alwaysActiveMenu->setLastButtonDimensions(32, 32); alwaysActiveMenu->setLastButtonPosition(262+2, 600); myMenu = new MenuSys(0, 0, "blank.png", None); myMenu->addButton("scrollbarUp.png", "scrollbarUp.png", "scrollbarUpLit.png", BE::CreateFunctionPointer0R(this, &LogicInterface::LogicBankUpArrowButtonClick)); myMenu->setLastButtonDimensions(25, 25); myMenu->setLastButtonPosition(logicBankBox.x + logicBankBox.width + logicBankScrollbarXOffset, logicBankBox.y); myMenu->addButton("scrollbarDown.png", "scrollbarDown.png", "scrollbarDownLit.png", BE::CreateFunctionPointer0R(this, &LogicInterface::LogicBankDownArrowButtonClick)); myMenu->setLastButtonDimensions(25, 25); myMenu->setLastButtonPosition(logicBankBox.x + logicBankBox.width + logicBankScrollbarXOffset, logicBankBox.y + logicBankBox.height - 45); myMenu->addButton("scrollbarUp.png", "scrollbarUp.png", "scrollbarUpLit.png", BE::CreateFunctionPointer0R(this, &LogicInterface::ExecutionListUpArrowButtonClick)); myMenu->setLastButtonDimensions(25, 25); myMenu->setLastButtonPosition(instructionListBox.x + instructionListBox.width, instructionListBox.y); myMenu->addButton("scrollbarDown.png", "scrollbarDown.png", "scrollbarDownLit.png", BE::CreateFunctionPointer0R(this, &LogicInterface::ExecutionListDownArrowButtonClick)); myMenu->setLastButtonDimensions(25, 25); myMenu->setLastButtonPosition(instructionListBox.x + instructionListBox.width, instructionListBox.y + instructionListBox.height - 45); myMenu->addButton("buttons\\execute.png", "buttons\\executehover.png", "buttons\\executehover.png", BE::CreateFunctionPointer0R(this, &LogicInterface::ExecuteButtonClick)); myMenu->setLastButtonDimensions(75, 30); myMenu->setLastButtonPosition(instructionListBox.x+45 + instructionListBox.width + 100+50, logicBankBox.y+25); myMenu->addButton("blank.png", "blank.png", "blank.png", BE::CreateFunctionPointer0R(this, &LogicInterface::MainTabButtonClick)); myMenu->setLastButtonDimensions(50, 20); myMenu->setLastButtonPosition(instructionListBox.x + 25 + 3, instructionListBox.y - 25); myMenu->addButton("blank.png", "blank.png", "blank.png", BE::CreateFunctionPointer0R(this, &LogicInterface::Sub1TabButtonClick)); myMenu->setLastButtonDimensions(50, 20); myMenu->setLastButtonPosition(419,575); myMenu->addButton("blank.png", "blank.png", "blank.png", BE::CreateFunctionPointer0R(this, &LogicInterface::Sub2TabButtonClick)); myMenu->setLastButtonDimensions(50, 20); myMenu->setLastButtonPosition(469,575); myMenu->addButton("buttons\\clear.png", "buttons\\clearhover.png", "buttons\\clearhover.png", BE::CreateFunctionPointer0R(this, &LogicInterface::ClearButtonClick)); myMenu->setLastButtonDimensions(75, 30); myMenu->setLastButtonPosition(instructionListBox.x+45 + instructionListBox.width + 100+50, logicBankBox.y+25+35+35); resetMenu = new MenuSys(0, 0, "blank.png", None); resetMenu->addButton("buttons\\reset.png", "buttons\\resethover.png", "buttons\\resethover.png", BE::CreateFunctionPointer0R(this, &LogicInterface::ResetButtonClick)); resetMenu->setLastButtonDimensions(75, 30); resetMenu->setLastButtonPosition(instructionListBox.x+45 + instructionListBox.width + 100+50, logicBankBox.y+25+35); executingMenu = new MenuSys(0, 0, "blank.png", None); executingMenu->addButton("buttons\\abort.png", "buttons\\aborthover.png", "buttons\\aborthover.png", BE::CreateFunctionPointer0R(this, &LogicInterface::AbortButtonClick)); executingMenu->setLastButtonDimensions(75, 30); executingMenu->setLastButtonPosition(instructionListBox.x +45 + instructionListBox.width + 100+50, logicBankBox.y+25); panelArt = new oglTexture2D(); panelArt->loadImage("Panel.png", 1024, 190); panelArt->mX = 0; panelArt->mY = 768-190; commandBackdrop = new oglTexture2D(); commandBackdrop->loadImage("CommandList.png", 228, 181); commandBackdrop2 = new oglTexture2D(); commandBackdrop2->loadImage("logicinterface.png", 228, 181); insertionLine = new oglTexture2D(); insertionLine->loadImage("black.png", 3, instructionBlockH - 4); //============================================= // All other initialization menuBar = new oglTexture2D(); menuBar->loadImage("CommandList.png", 1024, 768); //menuBar->loadImage("blank.png", 1024, 768); scrollBar = new oglTexture2D(); scrollBar->loadImage("scrollbarBG.png", 100, 100); logicBank = GameVars->GetCurrentMapLogicBank(); //GameVars->getAllLogicBlocks(); executionList.push_back(new logicBlock((*GameVars->getPlaceInstructionBlock()))); executionList.back()->curButtonState = BS_ACTIVE; executionListSub1.push_back(new logicBlock((*GameVars->getPlaceInstructionBlock()))); executionListSub1.back()->curButtonState = BS_ACTIVE; executionListSub2.push_back(new logicBlock((*GameVars->getPlaceInstructionBlock()))); executionListSub2.back()->curButtonState = BS_ACTIVE; draggedBlock = NULL; logicBankYOffset = 0; executionListYOffset = 0; isMouseDragging = false; bytesLeftBackground = new oglTexture2D; bytesLeftBackground->loadImage("CommandList.png", 285, 145); bytesLeftBackground->mX = 725; bytesLeftBackground->mY = logicBankBox.y - 70; executionListScrolled = 0; executionListSub1Scrolled = 0; executionListSub2Scrolled = 0; } LogicInterface::~LogicInterface() { delete myMenu; myMenu = NULL; delete executingMenu; executingMenu = NULL; delete resetMenu; resetMenu = NULL; delete menuBar; menuBar = NULL; delete panelArt; panelArt = NULL; delete commandBackdrop; commandBackdrop = NULL; delete commandBackdrop2; commandBackdrop2 = NULL; delete scrollBar; scrollBar = NULL; delete insertionLine; insertionLine = NULL; delete bytesLeftBackground; bytesLeftBackground = NULL; delete draggedBlock; draggedBlock = NULL; delete curExecutionListYOffset; curExecutionListYOffset = NULL; // Don't destroy the contents of logicBank because they're stored on the singleton... delete logicBank; logicBank = NULL; // Destroy the contents of the executionLists because they're new copies for(unsigned int i = 0; i < executionList.size(); i++) { delete executionList[i]; executionList[i] = NULL; } for(unsigned int i = 0; i < executionListSub1.size(); i++) { delete executionListSub1[i]; executionListSub1[i] = NULL; } for(unsigned int i = 0; i < executionListSub2.size(); i++) { delete executionListSub2[i]; executionListSub2[i] = NULL; } } void LogicInterface::Update() { alwaysActiveMenu->Update(); resetMenu->Update(); myMenu->Update(); executingMenu->Update(); // Toggle whether or not a logic instruction is usable // based on whether or not bytes are available for it std::vector<logicBlock*>::iterator dItr = logicBank->begin(); for(; dItr != logicBank->end(); dItr++) { int bytesLeft = mapByteLimit - usedBytes; if((*dItr)->byteCost > bytesLeft) { (*dItr)->isCurrentlyUsable = false; } else if(curInstrTab == TAB_SUB1 && ((*dItr)->enumInstruction == SUBR1 || (*dItr)->enumInstruction == SUBR2)) { (*dItr)->isCurrentlyUsable = false; } else if(curInstrTab == TAB_SUB2 && ((*dItr)->enumInstruction == SUBR1 || (*dItr)->enumInstruction == SUBR2)) { (*dItr)->isCurrentlyUsable = false; } else { (*dItr)->isCurrentlyUsable = true; } } // Hover Over Stuff currentHoverBlockIndex = -1; if(logicBank != NULL) { std::vector<logicBlock*>::iterator itr = logicBank->begin(); for(; itr != logicBank->end(); itr++) { if((*itr)->checkInBounds(mouseX, mouseY, instructionBlockW, instructionBlockH)) { // You're hovering over, YAY! LOLZ currentHoverBlockIndex = std::distance(logicBank->begin(), itr); } } } // Calculating the bytes left // I think there's a loop deficiency // Nothin' sexier than algorithmic efficiency // I want you to iterate // Cus when I see i++, I salivate! // -Corwin VanHook, March 09, 2009 int tmpByteCount = 0; std::vector<logicBlock*>::iterator itr = executionList.begin(); for(; itr != executionList.end(); itr++) { tmpByteCount += (*itr)->byteCost; } itr = executionListSub1.begin(); for(; itr != executionListSub1.end(); itr++) { tmpByteCount += (*itr)->byteCost; } itr = executionListSub2.begin(); for(; itr != executionListSub2.end(); itr++) { tmpByteCount += (*itr)->byteCost; } usedBytes = tmpByteCount; GameVars->setBytesUsed(usedBytes); itr = executionList.begin(); for(; itr != executionList.end(); itr++) { if((*itr)->enumInstruction == DO_NOT_PROCESS) { if(usedBytes == mapByteLimit) { (*itr)->curButtonState = BS_INACTIVE; } else { (*itr)->curButtonState = BS_ACTIVE; } } } itr = executionListSub1.begin(); for(; itr != executionListSub1.end(); itr++) { if((*itr)->enumInstruction == DO_NOT_PROCESS) { if(usedBytes == mapByteLimit) { (*itr)->curButtonState = BS_INACTIVE; } else { (*itr)->curButtonState = BS_ACTIVE; } } } itr = executionListSub2.begin(); for(; itr != executionListSub2.end(); itr++) { if((*itr)->enumInstruction == DO_NOT_PROCESS) { if(usedBytes == mapByteLimit) { (*itr)->curButtonState = BS_INACTIVE; } else { (*itr)->curButtonState = BS_ACTIVE; } } } } void LogicInterface::Draw() { //oglTexture2D tempBlackThing; /*tempBlackThing.loadImage("black.png", 225, 75); tempBlackThing.mX = 760; tempBlackThing.mY = logicBankBox.y - 60; tempBlackThing.drawImageFaded(0.75);*/ bytesLeftBackground->drawImage(); // draw panel background panelArt->drawImage(); // draw left commands background commandBackdrop->dX = 200; commandBackdrop->dY = 165; commandBackdrop->mX = 30; commandBackdrop->mY = 768-190+12; commandBackdrop->drawImage(); // draw center commands background //commandBackdrop->dX = 390; //commandBackdrop->dY = 161; //commandBackdrop->mX = 340; //commandBackdrop->mY = instructionListBox.y; //commandBackdrop->drawImage(); commandBackdrop2->dX = 390; commandBackdrop2->dY = 161 + 25; commandBackdrop2->mX = 340; commandBackdrop2->mY = instructionListBox.y - 25; if(curInstrTab == TAB_MAIN) commandBackdrop2->drawImageSegment(0.0, 0.0, 1.0, 0.0, 0.0, (double)1/3, 1.0, (double)1/3, 1.0); else if(curInstrTab == TAB_SUB1) commandBackdrop2->drawImageSegment(0.0, (double)1/3, 1.0, (double)1/3, 0.0, (double)2/3, 1.0, (double)2/3, 1.0); else if(curInstrTab == TAB_SUB2) commandBackdrop2->drawImageSegment(0.0, (double)2/3, 1.0, (double)2/3, 0.0, 1.0, 1.0, 1.0, 1.0); std::vector<logicBlock*>::iterator itr = executionList.begin(); //============================================= // Menu Bars /*menuBar->mX = bottomBarBox.x; menuBar->mY = bottomBarBox.y; menuBar->drawImage(bottomBarBox.width, bottomBarBox.height); menuBar->mX = instructionListBox.x - 7; menuBar->mY = instructionListBox.y; menuBar->drawImage(instructionListBox.width + 7, instructionListBox.height - 18); menuBar->mX = logicBankBox.x - 7; menuBar->mY = logicBankBox.y; menuBar->drawImage(logicBankBox.width + 7, logicBankBox.height - 18);*/ //============================================= // Robot Instructions int rowCount = 0; int columnIndex = 0; if(this->curInstrTab == TAB_MAIN) { itr = executionList.begin(); for(; itr != executionList.end(); itr++) { int i = std::distance(executionList.begin(), itr); if(((i % instructionListNumColumns) == 0) && (i > 0)) { rowCount++; } (*itr)->blockTexture->mX = instructionListBox.x + (instructionSpacing * columnIndex) + (instructionBlockW * columnIndex); (*itr)->blockTexture->mY = executionListYOffset + ((instructionListBox.y + instructionSpacing) + (rowCount * instructionBlockH) + (rowCount * instructionSpacing)); if((*itr)->blockTexture->mY >= instructionListBox.y && (*itr)->blockTexture->mY <= instructionListBox.y + instructionListBox.height - (instructionSpacing + instructionBlockH)) { if((*itr)->curButtonState == BS_ACTIVE) { (*itr)->blockTexture->drawImageSegment(0.0, 0.0, (double)1/3, 0.0, 0.0, 1.0, (double)1/3, 1.0, 1, instructionBlockW, instructionBlockH); } else if((*itr)->curButtonState == BS_HIGHLIGHTED) { (*itr)->blockTexture->drawImageSegment((double)1/3, 0.0, (double)2/3, 0.0, (double)1/3, 1.0, (double)2/3, 1.0, 1, instructionBlockW, instructionBlockH); } else if((*itr)->curButtonState == BS_INACTIVE) { (*itr)->blockTexture->drawImageSegment((double)2/3, 0.0, (double)3/3, 0.0, (double)2/3, 1.0, (double)3/3, 1.0, 1, instructionBlockW, instructionBlockH); } } columnIndex++; if(columnIndex >= instructionListNumColumns) columnIndex = 0; } } //============================================= // Robot Instructions (Sub1) if(this->curInstrTab == TAB_SUB1) { itr = executionListSub1.begin(); for(; itr != executionListSub1.end(); itr++) { int i = std::distance(executionListSub1.begin(), itr); if(((i % instructionListNumColumns) == 0) && (i > 0)) { rowCount++; } (*itr)->blockTexture->mX = instructionListBox.x + (instructionSpacing * columnIndex) + (instructionBlockW * columnIndex); (*itr)->blockTexture->mY = executionListSub1YOffset + ((instructionListBox.y + instructionSpacing) + (rowCount * instructionBlockH) + (rowCount * instructionSpacing)); if((*itr)->blockTexture->mY >= instructionListBox.y && (*itr)->blockTexture->mY <= instructionListBox.y + instructionListBox.height - (instructionSpacing + instructionBlockH)) { if((*itr)->curButtonState == BS_ACTIVE) { (*itr)->blockTexture->drawImageSegment(0.0, 0.0, (double)1/3, 0.0, 0.0, 1.0, (double)1/3, 1.0, 1, instructionBlockW, instructionBlockH); } else if((*itr)->curButtonState == BS_HIGHLIGHTED) { (*itr)->blockTexture->drawImageSegment((double)1/3, 0.0, (double)2/3, 0.0, (double)1/3, 1.0, (double)2/3, 1.0, 1, instructionBlockW, instructionBlockH); } else if((*itr)->curButtonState == BS_INACTIVE) { (*itr)->blockTexture->drawImageSegment((double)2/3, 0.0, (double)3/3, 0.0, (double)2/3, 1.0, (double)3/3, 1.0, 1, instructionBlockW, instructionBlockH); } } columnIndex++; if(columnIndex >= instructionListNumColumns) columnIndex = 0; } } //============================================= // Robot Instructions (Sub2) if(this->curInstrTab == TAB_SUB2) { itr = executionListSub2.begin(); for(; itr != executionListSub2.end(); itr++) { int i = std::distance(executionListSub2.begin(), itr); if(((i % instructionListNumColumns) == 0) && (i > 0)) { rowCount++; } (*itr)->blockTexture->mX = instructionListBox.x + (instructionSpacing * columnIndex) + (instructionBlockW * columnIndex); (*itr)->blockTexture->mY = executionListSub2YOffset + ((instructionListBox.y + instructionSpacing) + (rowCount * instructionBlockH) + (rowCount * instructionSpacing)); if((*itr)->blockTexture->mY >= instructionListBox.y && (*itr)->blockTexture->mY <= instructionListBox.y + instructionListBox.height - (instructionSpacing + instructionBlockH)) { if((*itr)->curButtonState == BS_ACTIVE) { (*itr)->blockTexture->drawImageSegment(0.0, 0.0, (double)1/3, 0.0, 0.0, 1.0, (double)1/3, 1.0, 1, instructionBlockW, instructionBlockH); } else if((*itr)->curButtonState == BS_HIGHLIGHTED) { (*itr)->blockTexture->drawImageSegment((double)1/3, 0.0, (double)2/3, 0.0, (double)1/3, 1.0, (double)2/3, 1.0, 1, instructionBlockW, instructionBlockH); } else if((*itr)->curButtonState == BS_INACTIVE) { (*itr)->blockTexture->drawImageSegment((double)2/3, 0.0, (double)3/3, 0.0, (double)2/3, 1.0, (double)3/3, 1.0, 1, instructionBlockW, instructionBlockH); } } columnIndex++; if(columnIndex >= instructionListNumColumns) columnIndex = 0; } } //============================================= // LogicBank Instructions (bottom bar) rowCount = 0; columnIndex = 0; if(logicBank != NULL) { itr = logicBank->begin(); for(; itr != logicBank->end(); itr++) { int i = std::distance(logicBank->begin(), itr); if(((i % logicBankNumColumns) == 0) && (i > 0)) { rowCount++; } (*itr)->blockTexture->mX = logicBankBox.x + + (instructionSpacing * columnIndex) + (instructionBlockW * columnIndex); (*itr)->blockTexture->mY = logicBankYOffset + ((logicBankBox.y + instructionSpacing) + (rowCount * instructionBlockH) + (rowCount * instructionSpacing)); if((*itr)->curButtonState == BS_ACTIVE) { (*itr)->blockTexture->drawImageSegment(0.0, 0.0, (double)1/3, 0.0, 0.0, 1.0, (double)1/3, 1.0, 1, instructionBlockW, instructionBlockH); } else if((*itr)->curButtonState == BS_HIGHLIGHTED) { (*itr)->blockTexture->drawImageSegment((double)1/3, 0.0, (double)2/3, 0.0, (double)1/3, 1.0, (double)2/3, 1.0, 1, instructionBlockW, instructionBlockH); } else if((*itr)->curButtonState == BS_INACTIVE) { (*itr)->blockTexture->drawImageSegment((double)2/3, 0.0, (double)3/3, 0.0, (double)2/3, 1.0, (double)3/3, 1.0, 1, instructionBlockW, instructionBlockH); } // If an instruction is not usable, draw a box over it if(!((*itr)->isUsable) || !((*itr)->isCurrentlyUsable)) { insertionLine->mX = (*itr)->blockTexture->mX; insertionLine->mY = (*itr)->blockTexture->mY; insertionLine->drawImageFaded(0.5, instructionBlockW, instructionBlockH); } columnIndex++; if(columnIndex >= logicBankNumColumns) columnIndex = 0; } } //============================================= // Menu Bars (Behind Scroll Buttons) scrollBar->mX = logicBankBox.x + logicBankBox.width + logicBankScrollbarXOffset; scrollBar->mY = logicBankBox.y; scrollBar->drawImage(25, logicBankBox.height - 20); scrollBar->mX = instructionListBox.x + instructionListBox.width; scrollBar->mY = instructionListBox.y; scrollBar->drawImage(25, instructionListBox.height - 20); //============================================= // Menu Buttons (For scrolling and shizz) resetMenu->Draw(); alwaysActiveMenu->Draw(); myMenu->Draw(); if(isExecuting == true) executingMenu->Draw(); //============================================= // Byte Limit Stuff glColor3ub(0, 0, 0); std::stringstream ss; std::string s; ss << usedBytes; ss << " of "; ss << mapByteLimit; ss << " BYTES used."; s = ss.str(); GameVars->fontDigital16.drawText(740, logicBankBox.y - 60, s.c_str()); std::stringstream ss2; ss2 << mapByteLimit - usedBytes; ss2 << " BYTES remaining."; s = ss2.str(); GameVars->fontDigital16.drawText(740, logicBankBox.y - 60 + 16, s.c_str()); if(drawInsertionLine == true) { std::vector<logicBlock*>* curExecutionList = NULL; if(curInstrTab == TAB_MAIN) { curExecutionListYOffset = &executionListYOffset; curExecutionList = &executionList; } else if(curInstrTab == TAB_SUB1) { curExecutionListYOffset = &executionListSub1YOffset; curExecutionList = &executionListSub1; } else if(curInstrTab == TAB_SUB2) { curExecutionListYOffset = &executionListSub2YOffset; curExecutionList = &executionListSub2; } // CJV2 int rowOffset = ((*curExecutionListYOffset) / (instructionSpacing + instructionBlockH)); int vectorSize = curExecutionList->size(); int lastBlockRow = vectorSize / instructionListNumColumns; int lastBlockColumn = vectorSize % instructionListNumColumns; lastBlockRow += rowOffset; if(lastBlockColumn != 0) lastBlockColumn--; else { lastBlockColumn = instructionListNumColumns - 1; lastBlockRow--; } if(((insertionLineColumn > lastBlockColumn) && (insertionLineRow > lastBlockRow)) || ((insertionLineColumn > lastBlockColumn) && (insertionLineRow == lastBlockRow)) || ((insertionLineRow > lastBlockRow))) { insertionLine->mX = instructionListBox.x + (lastBlockColumn * (instructionSpacing + instructionBlockW)) - 2; insertionLine->mY = instructionListBox.y + (lastBlockRow * (instructionSpacing + instructionBlockH)) + 4; insertionLine->drawImage(); } else { insertionLine->mX = instructionListBox.x + (insertionLineColumn * (instructionSpacing + instructionBlockW)) - 2; insertionLine->mY = instructionListBox.y + (insertionLineRow * (instructionSpacing + instructionBlockH)) + 4; insertionLine->drawImage(); } } //============================================= // Dragged Block if(draggedBlock != NULL) { //draggedBlock->blockTexture->drawImage(instructionBlockW, instructionBlockH); draggedBlock->blockTexture->drawImageSegment((double)0/3, 0, (double)1/3, 0, (double)0/3, 1, (double)1/3, 1, 1, instructionBlockW, instructionBlockH); } //============================================= // Hover Over Screen Tipz0rz // If the currentHoverBlockIndex is -1 that // means no block is being hovered over if(currentHoverBlockIndex != -1) { if(logicBank != NULL) { logicBlock* tmpBlock = (*logicBank)[currentHoverBlockIndex]; // Draw the background menuBar->mX = tmpBlock->blockTexture->mX + 20; menuBar->mY = tmpBlock->blockTexture->mY - 170; menuBar->drawImageFaded(1.0, 210, 140); int MAX_CHARS_PER_LINE = 16; int currentLine = 1; bool endOfText = false; int extraYSpacing = 0; glColor3ub(255, 0, 0); // done adding new red font if(tmpBlock->isUsable != true) { GameVars->fontArialRed12.drawText(menuBar->mX + 10, menuBar->mY + 12, "[Unavailable on"); GameVars->fontArialRed12.drawText(menuBar->mX + 10, menuBar->mY + 24, "Current Level]"); extraYSpacing = 24; } glColor3ub(0, 0, 0); while(!endOfText) { if((int)(tmpBlock->blockDescription.length()) > currentLine * MAX_CHARS_PER_LINE) { GameVars->fontArial12.drawText(menuBar->mX + 10, menuBar->mY + (currentLine * 12) + extraYSpacing, tmpBlock->blockDescription.substr((currentLine - 1) * MAX_CHARS_PER_LINE, MAX_CHARS_PER_LINE)); currentLine++; } else { GameVars->fontArial12.drawText( menuBar->mX + 10, menuBar->mY + (currentLine * 12) + extraYSpacing, tmpBlock->blockDescription.substr( (currentLine - 1) * MAX_CHARS_PER_LINE, tmpBlock->blockDescription.length() % (currentLine -1 * MAX_CHARS_PER_LINE)) ); endOfText = true; } } currentLine++; glColor3ub(255, 0, 0); // done adding new red font if(tmpBlock->isCurrentlyUsable != true && (tmpBlock->isUsable == true)) { if((tmpBlock->enumInstruction == SUBR1 || tmpBlock->enumInstruction == SUBR2) && (curInstrTab == TAB_SUB1 || curInstrTab == TAB_SUB2)) { GameVars->fontArialRed12.drawText(menuBar->mX + 10, menuBar->mY + (currentLine * 13) + extraYSpacing, "[You can't place"); currentLine++; GameVars->fontArialRed12.drawText(menuBar->mX + 10, menuBar->mY + (currentLine * 13) + extraYSpacing, "SubRoutines Here]"); currentLine++; } else { GameVars->fontArialRed12.drawText(menuBar->mX + 10, menuBar->mY + (currentLine * 13) + extraYSpacing, "[Not Enough Memory"); currentLine++; GameVars->fontArialRed12.drawText(menuBar->mX + 10, menuBar->mY + (currentLine * 13) + extraYSpacing, "Available]"); currentLine++; } } glColor3ub(0, 0, 0); // now that we're at the end of the text... // lets bump up current line once more // and lets draw the byte information for this block! std::stringstream byteCost; byteCost << "(Uses "; byteCost << tmpBlock->byteCost; byteCost << " Bytes)"; GameVars->fontArial12.drawText(menuBar->mX+10, menuBar->mY + (currentLine * 13) + extraYSpacing, byteCost.str()); } } } void LogicInterface::processMouse(int x, int y) { // Internal mouse position for hover over stuff mouseX = x; mouseY = y; // Menu buttons alwaysActiveMenu->processMouse(x, y); resetMenu->processMouse(x, y); myMenu->processMouse(x, y); if(isExecuting == true) executingMenu->processMouse(x, y); // Dragging the block if(isMouseDragging == true && draggedBlock != NULL) { draggedBlock->blockTexture->mX = x - (instructionBlockW / 2); draggedBlock->blockTexture->mY = y - (instructionBlockH / 2); } // Dragging & Insertion into the middle of the list if(isMouseDragging == true && draggedBlock != NULL) { int localX = x - instructionListBox.x; int localY = y - instructionListBox.y; int columnPosition = localX / (instructionSpacing + instructionBlockW); int rowPosition = localY / (instructionSpacing + instructionBlockH); if((columnPosition >= 0) && (columnPosition < instructionListNumColumns) && (rowPosition >= 0) && (rowPosition < instructionListNumRowsOnScreen)) { insertionLineColumn = columnPosition; insertionLineRow = rowPosition; drawInsertionLine = true; // CJV1 } else { insertionLineColumn = 0; insertionLineRow = 0; drawInsertionLine = false; } //instructionListNumColumns //instructionListNumRowsOnScreen // Figure out which column & row the mouse is hovering over // is that coord beyond the processInstructionHere instruction block // If so, it doesn't really mean shit // else // Determine which blocks it's in between and shit } else { insertionLineColumn = 0; insertionLineRow = 0; drawInsertionLine = false; } } // Add in KeyboardInput functions for TAB (DEC: 9 ASCII value) void LogicInterface::processMouseClick(int button, int state, int x, int y) { // Menu buttons alwaysActiveMenu->processMouseClick(button, state, x, y); resetMenu->processMouseClick(button, state, x, y); if(isExecuting == true) executingMenu->processMouseClick(button, state, x, y); else if(isExecuting == false) myMenu->processMouseClick(button, state, x, y); // Click & Drag // When the user clicks, we want them to be able to select an // instruction to drag over into the robot's instruction list. // Loop through the list of bank instructions and check x/y if(!isExecuting) { if(button == GLUT_LEFT && state == GLUT_DOWN) { if(isButtonBeingClicked == false) { // If the left mouse button is down if(logicBank != NULL) { std::vector<logicBlock*>::iterator itr = logicBank->begin(); for(; itr != logicBank->end(); itr++) { if((*itr)->checkInBounds(x, y, instructionBlockW, instructionBlockH)) { if((*itr)->isUsable && (*itr)->isCurrentlyUsable) { draggedBlock = new logicBlock(*(*itr)); draggedBlock->curButtonState = BS_ACTIVE; isMouseDragging = true; draggedBlockMouseX = x; draggedBlockMouseY = y; } } } } } } } //===================================== // If the player clicks an instruction // from the logicBank it should add it // to the current list if(!isExecuting) { if(button == GLUT_LEFT && state == GLUT_UP) { if(isMouseDragging == true && draggedBlock != NULL) { // should have a buffer of 5 in each direction if( (draggedBlockMouseX <= x+5) && (draggedBlockMouseX >= x-5) && (draggedBlockMouseY <= y+5) && (draggedBlockMouseY >= y-5)) { std::vector<logicBlock*>* curExecutionList = NULL; if(curInstrTab == TAB_MAIN) { curExecutionList = &executionList; curExecutionListYOffset = &(executionListYOffset); } else if(curInstrTab == TAB_SUB1) { curExecutionList = &executionListSub1; curExecutionListYOffset = &(executionListSub1YOffset); } else if(curInstrTab == TAB_SUB2) { curExecutionList = &executionListSub2; curExecutionListYOffset = &(executionListSub2YOffset); } // Add block to the end of the list int bytesLeft = mapByteLimit - usedBytes; if(bytesLeft >= draggedBlock->byteCost) { curExecutionList->pop_back(); curExecutionList->push_back(new logicBlock(*(draggedBlock))); curExecutionList->push_back(new logicBlock((*GameVars->getPlaceInstructionBlock()))); curExecutionList->back()->curButtonState = BS_ACTIVE; } delete draggedBlock; draggedBlock = NULL; isMouseDragging = false; draggedBlockMouseX = 0; draggedBlockMouseY = 0; //========================= // Scrolling To The Bottom int curBlockIndex = curExecutionList->size(); int curBlockRowCount = curBlockIndex / instructionListNumColumns; (*curExecutionListYOffset) = 0; if(curBlockRowCount > instructionListNumRowsOnScreen - 1) { for(int i = 0; i < curBlockRowCount - (instructionListNumRowsOnScreen - 1); i++) { ExecutionListDownArrowButtonClick(); } } } } } } //===================================== // Dropping the instruction block into // the correct tabbed execution list if(!isExecuting) { if(button == GLUT_LEFT && state == GLUT_UP) { if(isMouseDragging == true && draggedBlock != NULL) { if(drawInsertionLine == true) { std::vector<logicBlock*>* curExecutionList = NULL; if(curInstrTab == TAB_MAIN) { curExecutionListYOffset = &executionListYOffset; curExecutionList = &executionList; curExecutionListScrolled = &executionListScrolled; } else if(curInstrTab == TAB_SUB1) { curExecutionListYOffset = &executionListSub1YOffset; curExecutionList = &executionListSub1; curExecutionListScrolled = &executionListSub1Scrolled; } else if(curInstrTab == TAB_SUB2) { curExecutionListYOffset = &executionListSub2YOffset; curExecutionList = &executionListSub2; curExecutionListScrolled = &executionListSub2Scrolled; } // CJV3 int rowOffset = ((*curExecutionListYOffset) / (instructionSpacing + instructionBlockH)); int vectorSize = curExecutionList->size(); int lastBlockRow = vectorSize / instructionListNumColumns; int lastBlockColumn = vectorSize % instructionListNumColumns; lastBlockRow += rowOffset; if(lastBlockColumn != 0) lastBlockColumn--; else { lastBlockColumn = instructionListNumColumns - 1; lastBlockRow--; } if(((insertionLineColumn > lastBlockColumn) && (insertionLineRow > lastBlockRow)) || ((insertionLineColumn > lastBlockColumn) && (insertionLineRow == lastBlockRow)) || ((insertionLineRow > lastBlockRow))) { // Add block to the end of the list int bytesLeft = mapByteLimit - usedBytes; if(bytesLeft >= draggedBlock->byteCost) { curExecutionList->pop_back(); curExecutionList->push_back(new logicBlock(*(draggedBlock))); curExecutionList->push_back(new logicBlock((*GameVars->getPlaceInstructionBlock()))); curExecutionList->back()->curButtonState = BS_ACTIVE; } delete draggedBlock; draggedBlock = NULL; isMouseDragging = false; } else { // Insert block within the current list. int bytesLeft = mapByteLimit - usedBytes; if(bytesLeft >= draggedBlock->byteCost) { std::vector<logicBlock*>::iterator insertionPosition = curExecutionList->begin(); // insertion fix based on scroll amount insertionPosition += (insertionLineRow * 8) + (insertionLineColumn) + ((*curExecutionListScrolled) * 8); curExecutionList->insert(insertionPosition, new logicBlock(*(draggedBlock))); } delete draggedBlock; draggedBlock = NULL; isMouseDragging = false; } } else { delete draggedBlock; draggedBlock = NULL; isMouseDragging = false; } } } } //=============================== // Pulling an instruction block // out of one of the execution // lists. if(!isExecuting) { if(button == GLUT_LEFT && state == GLUT_DOWN) { if(curInstrTab == TAB_MAIN) { if(isButtonBeingClicked == false) { // If the left mouse button is down std::vector<logicBlock*>::reverse_iterator itr = executionList.rbegin(); for(; itr != executionList.rend(); itr++) { if((*itr)->enumInstruction != DO_NOT_PROCESS) { if((*itr)->checkInBounds(x, y, instructionBlockW, instructionBlockH)) { if((*itr)->blockTexture->mY >= instructionListBox.y && (*itr)->blockTexture->mY <= instructionListBox.y + instructionListBox.height - (instructionSpacing + instructionBlockH)) { draggedBlock = new logicBlock(*(*itr)); isMouseDragging = true; delete (*itr); executionList.erase(itr.base() - 1); break; } } } } } } else if(curInstrTab == TAB_SUB1) { if(isButtonBeingClicked == false) { // If the left mouse button is down std::vector<logicBlock*>::reverse_iterator itr = executionListSub1.rbegin(); for(; itr != executionListSub1.rend(); itr++) { if((*itr)->enumInstruction != DO_NOT_PROCESS) { if((*itr)->checkInBounds(x, y, instructionBlockW, instructionBlockH)) { if((*itr)->blockTexture->mY >= instructionListBox.y && (*itr)->blockTexture->mY <= instructionListBox.y + instructionListBox.height - (instructionSpacing + instructionBlockH)) { draggedBlock = new logicBlock(*(*itr)); isMouseDragging = true; delete (*itr); executionListSub1.erase(itr.base() - 1); break; } } } } } } else if(curInstrTab == TAB_SUB2) { if(isButtonBeingClicked == false) { // If the left mouse button is down std::vector<logicBlock*>::reverse_iterator itr = executionListSub2.rbegin(); for(; itr != executionListSub2.rend(); itr++) { if((*itr)->enumInstruction != DO_NOT_PROCESS) { if((*itr)->checkInBounds(x, y, instructionBlockW, instructionBlockH)) { if((*itr)->blockTexture->mY >= instructionListBox.y && (*itr)->blockTexture->mY <= instructionListBox.y + instructionListBox.height - (instructionSpacing + instructionBlockH)) { draggedBlock = new logicBlock(*(*itr)); isMouseDragging = true; delete (*itr); executionListSub2.erase(itr.base() - 1); break; } } } } } } } } isButtonBeingClicked = false; } void LogicInterface::SetExecuteHandler(CFunctionPointer3R<bool, std::vector<logicBlock*>, std::vector<logicBlock*>, std::vector<logicBlock*>> clickHandler) { mExecuteHandler = clickHandler; } void LogicInterface::SetAbortHandler(CFunctionPointer0R<bool> clickHandler) { mAbortHandler = clickHandler; } void LogicInterface::SetResetHandler(CFunctionPointer0R<bool> resetHandler) { mResetHandler = resetHandler; } void LogicInterface::SetHelpHandler(CFunctionPointer0R<bool> helpHandler) { mHelpHandler = helpHandler; } void LogicInterface::SetSpeedUpHandler(CFunctionPointer0R<bool> speedUpHandler) { mSpeedUpHandler = speedUpHandler; } void LogicInterface::SetSlowDownHandler(CFunctionPointer0R<bool> slowDownHandler) { mSlowDownHandler = slowDownHandler; } void LogicInterface::GetCurrentMapLogicBank() { logicBank = GameVars->GetCurrentMapLogicBank(); } void LogicInterface::GetCurrentLevelBytes() { mapByteLimit = GameVars->getCurrentLevelBytes(); } //============================================ // LogicBank Arrow Callback bool LogicInterface::LogicBankUpArrowButtonClick() { //isButtonBeingClicked = true; //executionListYOffset += 50; //if(executionListYOffset > 0) // executionListYOffset = 0; return true; } //============================================ // LogicBank Down Arrow Callback bool LogicInterface::LogicBankDownArrowButtonClick() { //int i = executionList.size(); //int overallHeight = (logicBankBox.y + instructionSpacing) + ((i / logicBankNumRowsOnScreen) * instructionBlockH) + ((i / logicBankNumRowsOnScreen) * instructionSpacing); //isButtonBeingClicked = true; //if(executionList.size() > 3) //{ // executionListYOffset -= 50; // if(executionListYOffset + overallHeight < 768 - 130) // { // executionListYOffset = 768 - 150 - overallHeight; // } //} return true; } //============================================ // ExecutionList Up Arrow Callback bool LogicInterface::ExecutionListUpArrowButtonClick() { if(curInstrTab == TAB_MAIN) { curExecutionListYOffset = &executionListYOffset; curExecutionListScrolled = &executionListScrolled; } else if(curInstrTab == TAB_SUB1) { curExecutionListYOffset = &executionListSub1YOffset; curExecutionListScrolled = &executionListSub1Scrolled; } else if(curInstrTab == TAB_SUB2) { curExecutionListYOffset = &executionListSub2YOffset; curExecutionListScrolled = &executionListSub2Scrolled; } isButtonBeingClicked = true; (*curExecutionListYOffset) += (instructionSpacing + instructionBlockH); if((*curExecutionListYOffset) > 0) { (*curExecutionListYOffset) = 0; } // insertion fix based on scroll amount *curExecutionListScrolled -= 1;; if(*curExecutionListScrolled < 0) { *curExecutionListScrolled = 0; } return true; } //============================================ // ExecutionList Down Arrow Callback bool LogicInterface::ExecutionListDownArrowButtonClick() { std::vector<logicBlock*>* curExecutionList = NULL; if(curInstrTab == TAB_MAIN) { curExecutionListYOffset = &executionListYOffset; curExecutionList = &executionList; curExecutionListScrolled = &executionListScrolled; } else if(curInstrTab == TAB_SUB1) { curExecutionListYOffset = &executionListSub1YOffset; curExecutionList = &executionListSub1; curExecutionListScrolled = &executionListSub1Scrolled; } else if(curInstrTab == TAB_SUB2) { curExecutionListYOffset = &executionListSub2YOffset; curExecutionList = &executionListSub2; curExecutionListScrolled = &executionListSub2Scrolled; } int i = (*curExecutionList).size(); int numRows = i / instructionListNumColumns; if((i % instructionListNumColumns) > 0) numRows++; //int overallHeight = (instructionSpacing) + ((i / instructionListNumRowsOnScreen) * instructionBlockH) + ((i / instructionListNumRowsOnScreen) * instructionSpacing); int overallHeight = instructionSpacing + (numRows * instructionBlockH) + (numRows * instructionSpacing); isButtonBeingClicked = true; (*curExecutionListYOffset) -= (instructionSpacing + instructionBlockH); int cmp1 = (*curExecutionListYOffset) + overallHeight; int cmp2 = instructionListBox.height; if((*curExecutionListYOffset) + overallHeight < instructionListBox.height - 50) { (*curExecutionListYOffset) += (instructionSpacing + instructionBlockH); } // insertion fix based on scroll amount *curExecutionListScrolled += 1; if(*curExecutionListScrolled > numRows - 3) { *curExecutionListScrolled = numRows - 3; if(*curExecutionListScrolled < 0) { *curExecutionListScrolled = 0; } } return true; } //============================================ // Execute Button Callback bool LogicInterface::ExecuteButtonClick() { if(executionList.size() > 1) { if(mExecuteHandler) { isExecuting = true; return mExecuteHandler(executionList, executionListSub1, executionListSub2); } } return false; } bool LogicInterface::MainTabButtonClick() { curInstrTab = TAB_MAIN; return false; } bool LogicInterface::Sub1TabButtonClick() { // Check and see if Sub1 is available to use // in this level. If not, don't let the player select this tabs std::vector<logicBlock*>::iterator itr = logicBank->begin(); for(; itr != logicBank->end(); itr++) { if((*itr)->enumInstruction == SUBR1) { if((*itr)->isUsable == true) { curInstrTab = TAB_SUB1; return false; } } } return false; } bool LogicInterface::Sub2TabButtonClick() { // Check and see if Sub2 is available to use // in this level. If not, don't let the player select this tabs std::vector<logicBlock*>::iterator itr = logicBank->begin(); for(; itr != logicBank->end(); itr++) { if((*itr)->enumInstruction == SUBR2) { if((*itr)->isUsable == true) { curInstrTab = TAB_SUB2; return false; } } } return false; } bool LogicInterface::ClearExecutionList() { executionListYOffset = 0; executionListSub1YOffset = 0; executionListSub2YOffset = 0; curInstrTab = TAB_MAIN; executionList.clear(); executionList.push_back(new logicBlock((*GameVars->getPlaceInstructionBlock()))); executionList.back()->curButtonState = BS_ACTIVE; executionListSub1.clear(); executionListSub1.push_back(new logicBlock((*GameVars->getPlaceInstructionBlock()))); executionListSub1.back()->curButtonState = BS_ACTIVE; executionListSub2.clear(); executionListSub2.push_back(new logicBlock((*GameVars->getPlaceInstructionBlock()))); executionListSub2.back()->curButtonState = BS_ACTIVE; return true; } void LogicInterface::ResetExecutionMode() { isExecuting = false; } bool LogicInterface::CommandAdvanced(instructionTab instrTab, logicBlock* curBlock) { //================================= // NOTE & WARNING // 4/7/09 // Corwin // Added in some tweaks to the way commands are highlighted, // so that the main list properly updates when subroutines // are being processed. // // WARNING: This code is being written reflecting the fact // that sub-routines can't be placed in sub-routines // which was a recent design decision. // If we reverse this design decision, this code WILL BREAK! // To make sure the subs are highlighting correctly // in the main tab.. use a bool flag to track whether // or not we're executing a subroutine. curInstrTab = instrTab; std::vector<logicBlock*>* curExecutionList = NULL; if(curInstrTab == TAB_MAIN) { curExecutionList = &executionList; curExecutionListYOffset = &executionListYOffset; isProcessingSub = false; } else if(curInstrTab == TAB_SUB1) { if(isProcessingSub == false) { // First command in a sub routine.. advance the main highlight bool activateNextCommand = false; std::vector<logicBlock*>::iterator itr = executionList.begin(); for(; itr != executionList.end(); itr++) { if((*itr)->curButtonState == BS_HIGHLIGHTED) { activateNextCommand = true; (*itr)->curButtonState = BS_ACTIVE; } else if(activateNextCommand == true) { (*itr)->curButtonState = BS_HIGHLIGHTED; activateNextCommand = false; } } isProcessingSub = true; } curExecutionList = &executionListSub1; curExecutionListYOffset = &executionListSub1YOffset; } else if(curInstrTab == TAB_SUB2) { if(isProcessingSub == false) { // First command in a sub routine.. advance the main highlight bool activateNextCommand = false; std::vector<logicBlock*>::iterator itr = executionList.begin(); for(; itr != executionList.end(); itr++) { if((*itr)->curButtonState == BS_HIGHLIGHTED) { activateNextCommand = true; (*itr)->curButtonState = BS_ACTIVE; } else if(activateNextCommand == true) { (*itr)->curButtonState = BS_HIGHLIGHTED; activateNextCommand = false; } } isProcessingSub = true; } curExecutionList = &executionListSub2; curExecutionListYOffset = &executionListSub2YOffset; } int curBlockIndex = 0; std::vector<logicBlock*>::iterator itr = (*curExecutionList).begin(); for(; itr != (*curExecutionList).end(); itr++) { (*itr)->curButtonState = BS_ACTIVE; if((*itr) == curBlock) { curBlockIndex = std::distance((*curExecutionList).begin(), itr); } } curBlock->curButtonState = BS_HIGHLIGHTED; // Auto-Scroll to follow the currently highlighted instruction // 1) Figure out how many rows down the current block is int curBlockRowCount = curBlockIndex / instructionListNumColumns; // 2) Figure out if scrolling is needed to display that row (*curExecutionListYOffset) = 0; if(curBlockRowCount > instructionListNumRowsOnScreen - 1) { // 3) If so.. scroll however many times is needed for(int i = 0; i < curBlockRowCount - (instructionListNumRowsOnScreen - 1); i++) { ExecutionListDownArrowButtonClick(); } } return true; } bool LogicInterface::ReprogramReached() { //cout << "Oh snap dawg, you done reached a reprogrammable tile!"; isExecuting = false; return true; } bool LogicInterface::launchHelpState() { if(mHelpHandler) { return mHelpHandler(); } return true; } bool LogicInterface::speedUpButtonClick() { if(mSpeedUpHandler) { return mSpeedUpHandler(); } return true; } bool LogicInterface::slowDownButtonClick() { if(mSlowDownHandler) { return mSlowDownHandler(); } return true; } //============================================ // Abort Button Callback bool LogicInterface::AbortButtonClick() { isExecuting = false; if(mAbortHandler) { return mAbortHandler(); } return false; } //============================================ // Reset Button Callback bool LogicInterface::ResetButtonClick() { //ClearExecutionList(); // Clear the status of the instructions so there // is no highlighted square. std::vector<logicBlock*>::iterator itr = executionList.begin(); for(; itr != executionList.end(); itr++) { (*itr)->curButtonState = BS_ACTIVE; } itr = executionListSub1.begin(); for(; itr != executionListSub1.end(); itr++) { (*itr)->curButtonState = BS_ACTIVE; } itr = executionListSub2.begin(); for(; itr != executionListSub2.end(); itr++) { (*itr)->curButtonState = BS_ACTIVE; } isExecuting = false; if(mResetHandler) { return mResetHandler(); } return false; } //============================================ // Clear Button Callback bool LogicInterface::ClearButtonClick() { ClearExecutionList(); return true; }
[ "corwin.j@5457d560-9b84-11de-b17c-2fd642447241" ]
[ [ [ 1, 1570 ] ] ]
8691061dcdb2e8de6cef0dcbf19b88f251c3bfa7
15732b8e4190ae526dcf99e9ffcee5171ed9bd7e
/INC/application.h
7dc7a067d90ac50484e241a340d8761866695840
[]
no_license
clovermwliu/whutnetsim
d95c07f77330af8cefe50a04b19a2d5cca23e0ae
924f2625898c4f00147e473a05704f7b91dac0c4
refs/heads/master
2021-01-10T13:10:00.678815
2010-04-14T08:38:01
2010-04-14T08:38:01
48,568,805
0
0
null
null
null
null
GB18030
C++
false
false
10,640
h
//Copyright (c) 2010, Information Security Institute of Wuhan Universtiy(ISIWhu) //All rights reserved. // //PLEASE READ THIS DOCUMENT CAREFULLY BEFORE UTILIZING THE PROGRAM //BY UTILIZING THIS PROGRAM, YOU AGREE TO BECOME BOUND BY THE TERMS OF //THIS LICENSE. IF YOU DO NOT AGREE TO THE TERMS OF THIS LICENSE, DO //NOT USE THIS PROGRAM OR ANY PORTION THEREOF IN ANY FORM OR MANNER. // //This License allows you to: //1. Make copies and distribute copies of the Program's source code provide that any such copy // clearly displays any and all appropriate copyright notices and disclaimer of warranty as set // forth in this License. //2. Modify the original copy or copies of the Program or any portion thereof ("Modification(s)"). // Modifications may be copied and distributed under the terms and conditions as set forth above. // Any and all modified files must be affixed with prominent notices that you have changed the // files and the date that the changes occurred. //Termination: // If at anytime you are unable to comply with any portion of this License you must immediately // cease use of the Program and all distribution activities involving the Program or any portion // thereof. //Statement: // In this program, part of the code is from the GTNetS project, The Georgia Tech Network // Simulator (GTNetS) is a full-featured network simulation environment that allows researchers in // computer networks to study the behavior of moderate to large scale networks, under a variety of // conditions. Our work have great advance due to this project, Thanks to Dr. George F. Riley from // Georgia Tech Research Corporation. Anyone who wants to study the GTNetS can come to its homepage: // http://www.ece.gatech.edu/research/labs/MANIACS/GTNetS/ // //File Information: // // //File Name: //File Purpose: //Original Author: //Author Organization: //Construct Data: //Modify Author: //Author Organization: //Modify Data: // Georgia Tech Network Simulator - Layer 5 Application base class // George F. Riley. Georgia Tech, Spring 2002 // Define the layer 5 application interface //2010.01.04 modified by 张笑盈 #ifndef __application_h__ #define __application_h__ #include "G_common_defs.h" #include "handler.h" #include "l4protocol.h" #include "AppModel.h" // Define the start/stop events class BasicAppEvent : public Event { /* 描述:定义应用对应的事件类,实现启动或暂停应用 */ public: typedef enum { START, STOP } BasicAppEvent_t; BasicAppEvent() { } //构造函数 BasicAppEvent(Event_t ev) : Event(ev) { } //构造函数 }; //Doc:ClassXRef class Application : public Handler, public Object { /* Application类是所有应用类的基类。定义各种应用类和与此相关的第4层协议的接口。 Application类可以利用多种第4层协议来实现某种应用。 */ //Doc:Class Class {\tt Application} is the base class for all //Doc:Class \GTNS\ applications. //Doc:Class It defines the interface between the application class and //Doc:Class the associated layer 4 protocols. Applications can have one //Doc:Class or more layer 4 protocols assigned, to allow (for example) //Doc:Class a web browser model with multiple simulataneous connections. public: //Doc:Method Application() : deleteOnComplete(false), copyOnConnect(true) { }; /* 描述:默认构造函数 */ //Doc:Desc The default constructor for the {\tt Application} class. //Doc:Method Application(const Application&); //Doc:Desc Copy constructor, used bt the {\tt Copy()} method for all //Doc:Desc applications. //Doc:Arg1 Application object to copy. virtual ~Application(); // Starting, Stoping //Doc:Method void Start(Time_t); //Doc:Desc Schedule a {\tt Start} event for this application at the //Doc:Desc specified time. //Doc:Arg1 The simulation time to start the application. //Doc:Arg1 The {\t StartApp} method of the application will be called //Doc:Arg1 at the specified time. //Doc:Method void Stop(Time_t); //Doc:Desc Schedule a {\tt Stop} event for this application at the //Doc:Desc specified time. //Doc:Arg1 The simulation time to stop the application. //Doc:Arg1 The {\t StopApp} method of the application will be called //Doc:Arg1 at the specified time. // Handler functions void Handle(Event*, Time_t); // Upcalls from L4 protocol //Doc:Method virtual void Receive(Packet*,L4Protocol*, Seq_t = 0); // Data received //Doc:Desc Called by an associated layer 4 protocol when data //Doc:Desc is received. //Doc:Arg1 The packet received, with the layer 4 PDU removed. //Doc:Arg2 A pointer to the layer 4 protocol object that recieved the data. //Doc:Arg3 Optional sequence number for this data (TCP protocols only) //Doc:Method virtual void Sent(Count_t, L4Protocol*); // Data has been sent //Doc:Desc Called by an associated layer 4 protocol when all some part //Doc:Desc of the outstanding data has been sent. For TCP protocols, //Doc:Desc this occurs when the acknowledgement is received from the peer. //Doc:Arg1 Count of number of bytes successfully sent. //Doc:Arg2 A pointer to the layer 4 protocol object that sent the data. //Doc:Method virtual void CloseRequest(L4Protocol*); // Close request from peer //Doc:Desc Called by an associated layer 4 protocol when a connection //Doc:Desc close request has been receivd from a peer. Applications should //Doc:Desc respond by calling the corresponding layer 4 ::Close() routine. //Doc:Arg1 A pointer to the layer 4 protocol object that closed. //Doc:Method virtual void Closed(L4Protocol*); // Connection has closed //Doc:Desc Called by an associated layer 4 protocol when a connection //Doc:Desc has completely closed. //Doc:Arg1 A pointer to the layer 4 protocol object that closed. //Doc:Method virtual void ConnectionComplete(L4Protocol*);// Connection request succeeded //Doc:Desc Called by an associated layer 4 protocol when a previous //Doc:Desc connection request has successfully completed. //Doc:Arg1 A pointer to the layer 4 protocol object that connected. //Doc:Method virtual void ServConnectionComplete(L4Protocol*);// Connection request succeeded //Doc:Desc Called by an associated layer 4 protocol when a connection //Doc:Desc that the TCP server agent accepted has successfully completed. //Doc:Arg1 A pointer to the layer 4 protocol object that connected. //Doc:Method virtual void ConnectionFailed(L4Protocol*, bool);// Connection request failed //Doc:Desc Called by an associated layer 4 protocol when a previous //Doc:Desc connection request has failed. //Doc:Arg1 A pointer to the layer 4 protocol object that failed. //Doc:Arg2 True if aborted, false if timed out // Listener has cn rq from peer //Doc:Method virtual bool ConnectionFromPeer(L4Protocol*, IPAddr_t, PortId_t); //Doc:Desc Called by an associated layer 4 protocol when a listening //Doc:Desc TCP protocol has received a connection request. //Doc:Arg1 A pointer to the listening TCP protocol object. //Doc:Arg2 \IPA\ of remote peer. //Doc:Arg3 Port number of report peer. //Doc:Return Return true if able to accept a new connection, false if not. // Manage the application //Doc:Method void DeleteOnComplete(bool doc = true) { deleteOnComplete = doc;} //Doc:Desc Specifies that this application object should automatically //Doc:Desc be deleted when the application has finished. //Doc:Arg1 True if delete on complete desired. ////指定应用完成后是否需要自动删除该应用对象 //Doc:Method void CopyOnConnect(bool coc) { copyOnConnect = coc;} //Doc:Desc Specifies that this application object should be copied //Doc:Desc when connection requests are processed. //Doc:Arg1 True if delete on copy on connect desired. //指定是否需要拷贝连接 //Doc:Method bool CopyOnConnect() { return copyOnConnect;} //Doc:Desc Return current status of copy on connect flag. //Doc:Return True if copy on connect, false if not. //如果需要拷贝连接,则返回true,否则为false //Doc:Method virtual void StartApp() { }; // Called at time specified by Start //Doc:Desc Called at the specified applcation start time. //描述:启动当前应用,由Start方法调用 //Doc:Method virtual void StopApp() { }; // Called at time specified by Stop //Doc:Desc Called at the specified applcation stop time. //描述:停止当前应用,由Stop方法调用 //Doc:Method virtual void AttachNode(Node*); // Note which node attached to //Doc:Desc Specify which node to which this application is attached. //Doc:Arg1 Node pointer to attached node. //Doc:Method virtual Application* Copy() const = 0;// Make a copy of the application //描述:返回当前应用对象的拷贝 //Doc:Desc Return a copy of this application. \purev //Doc:Return A pointer to a new copy of this application. // If the application has a single layer4 protocol, return it //Doc:Method virtual L4Protocol* GetL4() const { return l4proto;} //返回当前应用所使用的第四层协议对象的指针 //Doc:Desc Returns a pointer to the layer 4 protocol object, //Doc:Desc if this application has a single associated l4 protocol. //Doc:Return Pointer to the single layer 4 object, or {\tt nil} if //Doc:Return none, or {\tt nil} if more than one. void DelL4proto() { // if ( l4proto!= nil ) //delete l4proto; } public: //Doc:Member bool deleteOnComplete;//应用完成后,如果需要自动删除该连接对象则为true //Doc:Desc True if delete on complete requested. //Doc:Member bool copyOnConnect; // True if application copied需要拷贝连接时为true //Doc:Desc True if copy on connect requested. //////////////////////////////////////////////////////////////////////////// //////新增 //////////////////////////////////////////////////////////////////////////// public: void SetAppModel(const AppModel &);//设置当前应用所用的模型 protected: AppModel * pModel; Node *node; L4Protocol *l4proto; }; #endif
[ "pengelmer@f37e807c-cba8-11de-937e-2741d7931076" ]
[ [ [ 1, 268 ] ] ]
e51a5e8793e990b7bba7e1e61099e5e7eec948d1
619941b532c6d2987c0f4e92b73549c6c945c7e5
/Source/ZipPlugin/ZipPlugin.cpp
86dd0889d0936179d95eba29ee76011de8fe001a
[]
no_license
dzw/stellarengine
2b70ddefc2827be4f44ec6082201c955788a8a16
2a0a7db2e43c7c3519e79afa56db247f9708bc26
refs/heads/master
2016-09-01T21:12:36.888921
2008-12-12T12:40:37
2008-12-12T12:40:37
36,939,169
0
0
null
null
null
null
UTF-8
C++
false
false
2,945
cpp
//  // // # # ### # # -= Nuclex Library =-  // // ## # # # ## ## ZipPlugin.cpp - Zip archive reader plugin  // // ### # # ###  // // # ### # ### Provides the required dll function to register the  // // # ## # # ## ## zip archive reader plugin to nuclex  // // # # ### # # R1 (C)2002-2004 Markus Ewald -> License.txt  // //  // #include "ZipPlugin/ZipPlugin.h" #include "ZipPlugin/Storage/ZipArchive.h" #include "Nuclex/Kernel.h" using namespace Nuclex; namespace ZipPlugin { // ############################################################################################# // // # NuclexVersion() # // // ############################################################################################# // /** Retrieve the version number of the nuclex framework the plugin was compiled against @return The framework version against which the plugin was compiled */ /*extern "C" NUCLEXZIP_API*/ int nuclexPluginVersion() { return NUCLEX_VERSION; } // ############################################################################################# // // # NuclexRegister() # // // ############################################################################################# // /** Register the plugin to a nuclex kernel instance @param pKernel Kernel to register to */ /*extern "C" NUCLEXZIP_API*/ void nuclexPluginRegister() { Kernel::getInstance().getStorageServer()->addArchiveFactory( "Zip", shared_ptr<Storage::StorageServer::ArchiveFactory>(new Storage::ZipArchiveFactory()) ); } // ############################################################################################# // // # NuclexUnregister() # // // ############################################################################################# // /** Unregister the plugin from a nuclex kernel instance @param pKernel Kernel to unregister from */ /*extern "C" NUCLEXZIP_API*/ void nuclexPluginUnregister() { try { Kernel::getInstance().getStorageServer()->removeArchiveFactory("Zip"); } catch(...) { Kernel::logMessage( Kernel::MT_ERROR, "An exception occured while removing the Zip codec" ); } } void InitPlugin() { } IMPLEMENTPACKAGE(ZipPlugin); }
[ [ [ 1, 69 ] ] ]
1d3435eb5a1766f7b5cebd74f5f463b64eb30b04
b22c254d7670522ec2caa61c998f8741b1da9388
/shared/ZoidSerializer.h
e8079fb66729eb272e833e13b37e6cea8b9e21e7
[]
no_license
ldaehler/lbanet
341ddc4b62ef2df0a167caff46c2075fdfc85f5c
ecb54fc6fd691f1be3bae03681e355a225f92418
refs/heads/master
2021-01-23T13:17:19.963262
2011-03-22T21:49:52
2011-03-22T21:49:52
39,529,945
0
1
null
null
null
null
UTF-8
C++
false
false
3,521
h
/* ------------------------[ Lbanet Source ]------------------------- Copyright (C) 2009 Author: Vivien Delage [Rincevent_123] Email : [email protected] -------------------------------[ GNU License ]------------------------------- This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ----------------------------------------------------------------------------- */ #ifndef __LBA_NET_ZOID_SERIALIZER_H__ #define __LBA_NET_ZOID_SERIALIZER_H__ #include "SerializerBase.h" class ZCom_BitStream; /*********************************************************************** Base serialization of object beofre sending it over the network using zoidcom ***********************************************************************/ class ZoidSerializer : public SerializerBase { public: //! constructor ZoidSerializer(ZCom_BitStream * stream) : _stream(stream) {} //! destructor ~ZoidSerializer(){} // function using to build tree structures virtual void startChildObjectList(const std::string &name){} virtual void nextChildObject(const std::string &name){} virtual void finishChildObjectList(const std::string &name){} // data will be stored as a bool on 1bit virtual void addBool(bool data, const std::string &id); virtual void getBool(const std::string &id, bool & res); // data will be stored as a unsigned short using 8bits virtual void addUShort(unsigned short data, const std::string &id); virtual void getUShort(const std::string &id, unsigned short & res); // data will be stored as a unsigned int using 16bits virtual void addUInt(unsigned int data, const std::string &id); virtual void getUInt(const std::string &id, unsigned int & res); // data will be stored as a unsigned long using 32bits virtual void addULong(unsigned long data, const std::string &id); virtual void getULong(const std::string &id, unsigned long & res); // data will be stored as a signed short using 8bits virtual void addShort(short data, const std::string &id); virtual void getShort(const std::string &id, short & res); // data will be stored as a signed int using 16bits virtual void addInt(int data, const std::string &id); virtual void getInt(const std::string &id, int & res); // data will be stored as a signed long using 32bits virtual void addLong(long data, const std::string &id); virtual void getLong(const std::string &id, long & res); // data will be stored as a float using 32bits virtual void addFloat(float data, const std::string &id); virtual void getFloat(const std::string &id, float & res); // data will be stored as a string of dynamic dimension // however the size of the string should not be larger than 250 characters virtual void addString(const std::string &data, const std::string &id); virtual void getString(const std::string &id, std::string & res); private: ZCom_BitStream * _stream; }; #endif
[ "vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13" ]
[ [ [ 1, 98 ] ] ]
85aaab046f3e8d210aee0354df797b099c90b3f6
d425cf21f2066a0cce2d6e804bf3efbf6dd00c00
/Tactical/XML_Explosive.cpp
2ff644b2a91b84eb385555845376b6bca3600e08
[]
no_license
infernuslord/ja2
d5ac783931044e9b9311fc61629eb671f376d064
91f88d470e48e60ebfdb584c23cc9814f620ccee
refs/heads/master
2021-01-02T23:07:58.941216
2011-10-18T09:22:53
2011-10-18T09:22:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,766
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" #endif struct { PARSE_STAGE curElement; CHAR8 szCharData[MAX_CHAR_DATA_LENGTH+1]; EXPLOSIVETYPE curExplosive; EXPLOSIVETYPE * curArray; UINT32 maxArraySize; UINT32 currentDepth; UINT32 maxReadDepth; } typedef explosiveParseData; static void XMLCALL explosiveStartElementHandle(void *userData, const XML_Char *name, const XML_Char **atts) { explosiveParseData * pData = (explosiveParseData *)userData; if(pData->currentDepth <= pData->maxReadDepth) //are we reading this element? { if(strcmp(name, "EXPLOSIVELIST") == 0 && pData->curElement == ELEMENT_NONE) { pData->curElement = ELEMENT_LIST; memset(pData->curArray,0,sizeof(EXPLOSIVETYPE)*pData->maxArraySize); pData->maxReadDepth++; //we are not skipping this element } else if(strcmp(name, "EXPLOSIVE") == 0 && pData->curElement == ELEMENT_LIST) { pData->curElement = ELEMENT; memset(&pData->curExplosive,0,sizeof(EXPLOSIVETYPE)); pData->maxReadDepth++; //we are not skipping this element } else if(pData->curElement == ELEMENT && (strcmp(name, "uiIndex") == 0 || strcmp(name, "ubType") == 0 || strcmp(name, "ubDamage") == 0 || strcmp(name, "ubStunDamage") == 0 || strcmp(name, "ubRadius") == 0 || strcmp(name, "ubVolume") == 0 || strcmp(name, "ubVolatility") == 0 || strcmp(name, "ubStartRadius") == 0 || strcmp(name, "ubMagSize") == 0 || strcmp(name, "ubDuration") == 0 || strcmp(name, "ubAnimationID") == 0 )) { pData->curElement = ELEMENT_PROPERTY; pData->maxReadDepth++; //we are not skipping this element } pData->szCharData[0] = '\0'; } pData->currentDepth++; } static void XMLCALL explosiveCharacterDataHandle(void *userData, const XML_Char *str, int len) { explosiveParseData * pData = (explosiveParseData *)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 explosiveEndElementHandle(void *userData, const XML_Char *name) { explosiveParseData * pData = (explosiveParseData *)userData; if(pData->currentDepth <= pData->maxReadDepth) //we're at the end of an element that we've been reading { if(strcmp(name, "EXPLOSIVELIST") == 0) { pData->curElement = ELEMENT_NONE; } else if(strcmp(name, "EXPLOSIVE") == 0) { pData->curElement = ELEMENT_LIST; if(pData->curExplosive.uiIndex < pData->maxArraySize) { pData->curArray[pData->curExplosive.uiIndex] = pData->curExplosive; //write the explosive into the table } } else if(strcmp(name, "uiIndex") == 0) { pData->curElement = ELEMENT; pData->curExplosive.uiIndex = (UINT32) atol(pData->szCharData); } else if(strcmp(name, "ubType") == 0) { pData->curElement = ELEMENT; pData->curExplosive.ubType = (UINT8) atol(pData->szCharData); } else if(strcmp(name, "ubDamage") == 0) { pData->curElement = ELEMENT; pData->curExplosive.ubDamage = (UINT8) atol(pData->szCharData); } else if(strcmp(name, "ubStunDamage") == 0) { pData->curElement = ELEMENT; pData->curExplosive.ubStunDamage = (UINT8) atol(pData->szCharData); } else if(strcmp(name, "ubRadius") == 0) { pData->curElement = ELEMENT; pData->curExplosive.ubRadius = (UINT8) atol(pData->szCharData); } else if(strcmp(name, "ubVolume") == 0) { pData->curElement = ELEMENT; pData->curExplosive.ubVolume = (UINT8) atol(pData->szCharData); } else if(strcmp(name, "ubVolatility") == 0) { pData->curElement = ELEMENT; pData->curExplosive.ubVolatility = (UINT8) atol(pData->szCharData); } else if(strcmp(name, "ubAnimationID") == 0) { pData->curElement = ELEMENT; pData->curExplosive.ubAnimationID = (UINT8) atol(pData->szCharData); } else if(strcmp(name, "ubStartRadius") == 0) { pData->curElement = ELEMENT; pData->curExplosive.ubStartRadius = (UINT8) atol(pData->szCharData); } else if(strcmp(name, "ubMagSize") == 0) { pData->curElement = ELEMENT; pData->curExplosive.ubMagSize = (UINT8) atol(pData->szCharData); } else if(strcmp(name, "ubDuration") == 0) { pData->curElement = ELEMENT; pData->curExplosive.ubDuration = (UINT8) atol(pData->szCharData); } pData->maxReadDepth--; } pData->currentDepth--; } BOOLEAN ReadInExplosiveStats(STR fileName) { HWFILE hFile; UINT32 uiBytesRead; UINT32 uiFSize; CHAR8 * lpcBuffer; XML_Parser parser = XML_ParserCreate(NULL); explosiveParseData pData; DebugMsg(TOPIC_JA2, DBG_LEVEL_3, "Loading Explosives.xml" ); // Open explosive 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, explosiveStartElementHandle, explosiveEndElementHandle); XML_SetCharacterDataHandler(parser, explosiveCharacterDataHandle); memset(&pData,0,sizeof(pData)); pData.curArray = Explosive; pData.maxArraySize = MAXITEMS; XML_SetUserData(parser, &pData); if(!XML_Parse(parser, lpcBuffer, uiFSize, TRUE)) { CHAR8 errorBuf[511]; sprintf(errorBuf, "XML Parser Error in Explosives.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 WriteExplosiveStats() { //DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"writeexplosivestats"); 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\\Explosives out.xml", FILE_ACCESS_WRITE | FILE_CREATE_ALWAYS, FALSE ); if ( !hFile ) return( FALSE ); { UINT32 cnt; FilePrintf(hFile,"<EXPLOSIVELIST>\r\n"); for(cnt = 0;cnt < MAXITEMS;cnt++) { FilePrintf(hFile,"\t<EXPLOSIVE>\r\n"); FilePrintf(hFile,"\t\t<uiIndex>%d</uiIndex>\r\n", cnt ); FilePrintf(hFile,"\t\t<ubType>%d</ubType>\r\n", Explosive[cnt].ubType ); FilePrintf(hFile,"\t\t<ubDamage>%d</ubDamage>\r\n", Explosive[cnt].ubDamage ); FilePrintf(hFile,"\t\t<ubStunDamage>%d</ubStunDamage>\r\n", Explosive[cnt].ubStunDamage ); FilePrintf(hFile,"\t\t<ubRadius>%d</ubRadius>\r\n", Explosive[cnt].ubRadius ); FilePrintf(hFile,"\t\t<ubVolume>%d</ubVolume>\r\n", Explosive[cnt].ubVolume ); FilePrintf(hFile,"\t\t<ubVolatility>%d</ubVolatility>\r\n", Explosive[cnt].ubVolatility ); FilePrintf(hFile,"\t\t<ubAnimationID>%d</ubAnimationID>\r\n", Explosive[cnt].ubAnimationID ); FilePrintf(hFile,"\t\t<ubDuration>%d</ubDuration>\r\n", Explosive[cnt].ubDuration ); FilePrintf(hFile,"\t\t<ubStartRadius>%d</ubStartRadius>\r\n", Explosive[cnt].ubStartRadius ); FilePrintf(hFile,"\t\t<ubMagSize>%d</ubMagSize>\r\n", Explosive[cnt].ubMagSize ); FilePrintf(hFile,"\t</EXPLOSIVE>\r\n"); } FilePrintf(hFile,"</EXPLOSIVELIST>\r\n"); } FileClose( hFile ); return( TRUE ); }
[ "jazz_ja@b41f55df-6250-4c49-8e33-4aa727ad62a1" ]
[ [ [ 1, 273 ] ] ]