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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f745db2705671e047fd444a835ae0a8025d5de65 | c7120eeec717341240624c7b8a731553494ef439 | /src/cplusplus/freezone-samp/src/mta10_loader.cpp | c27f3fb4e3ac224bb7c4792f9fb73cb39f845846 | []
| 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 | 15,986 | cpp | #include "config.hpp"
#include "mta10_loader.hpp"
#include <algorithm>
#include <functional>
#include <boost/filesystem/fstream.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/foreach.hpp>
#include "core/utility/directory.hpp"
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
namespace {
template <typename iterator>
struct object_parser_t: boost::spirit::qi::grammar<iterator, boost::spirit::ascii::space_type> {
object_parser_t(object_dynamic_t& object): object_parser_t::base_type(start), object(object) {
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
start = qi::lit("<object ") [boost::phoenix::ref(object.interior) = 0] >>
*( (qi::lit("model=\"") >> qi::int_ [boost::phoenix::ref(object.model_id) = qi::_1] >> '"')
| (qi::lit("interior=\"") >> qi::int_ [boost::phoenix::ref(object.interior) = qi::_1] >> '"')
| (qi::lit("posX=\"") >> qi::float_ [boost::phoenix::ref(object.x) = qi::_1] >> '"')
| (qi::lit("posY=\"") >> qi::float_ [boost::phoenix::ref(object.y) = qi::_1] >> '"')
| (qi::lit("posZ=\"") >> qi::float_ [boost::phoenix::ref(object.z) = qi::_1] >> '"')
| (qi::lit("rotX=\"") >> qi::float_ [boost::phoenix::ref(object.rx) = qi::_1] >> '"')
| (qi::lit("rotY=\"") >> qi::float_ [boost::phoenix::ref(object.ry) = qi::_1] >> '"')
| (qi::lit("rotZ=\"") >> qi::float_ [boost::phoenix::ref(object.rz) = qi::_1] >> '"')
| (qi::lexeme[+(ascii::char_ - '=')] >> qi::lit("=\"") >> qi::lexeme[+(ascii::char_ - '"')] >> '"')
) >> "/>";
}
boost::spirit::qi::rule<iterator, boost::spirit::ascii::space_type> start;
object_dynamic_t& object;
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct mta10_parser_objects_t {
objects_dynamic_t& objects;
mta10_loader_item_t const* item_ptr;
mta10_parser_objects_t(objects_dynamic_t& objects): objects(objects), item_ptr(0), object_dynamic_t_parser(object) {}
inline void parse_begin(mta10_loader_item_t const& item) {item_ptr = &item; object.world = item_ptr->world;}
inline void parse_next_line(std::string const& line);
inline void parse_end() {}
inline bool parse_next_line_impl(std::string const& line, object_dynamic_t& object);
object_dynamic_t object;
object_parser_t<std::string::const_iterator> object_dynamic_t_parser;
};
struct mta10_parser_spawn_points_t {
spawn_points_t& spawn_points;
mta10_loader_item_t const* item_ptr;
mta10_parser_spawn_points_t(spawn_points_t& spawn_points): spawn_points(spawn_points), item_ptr(0) {}
inline void parse_begin(mta10_loader_item_t const& item) {item_ptr = &item;}
inline void parse_next_line(std::string const& line);
inline void parse_end() {}
inline bool parse_next_line_impl(std::string const& line, pos4& pos);
};
struct mta10_parser_vehicles_t {
vehicles_dynamic_t& vehicles;
mta10_loader_vehicle_t const* item_ptr;
mta10_parser_vehicles_t(vehicles_dynamic_t& vehicles): vehicles(vehicles), item_ptr(0) {}
inline void parse_begin(mta10_loader_vehicle_t const& item) {item_ptr = &item;}
inline void parse_next_line(std::string const& line);
inline void parse_end() {}
inline bool parse_next_line_impl(std::string const& line, pos_vehicle& vehicle);
};
template <std::size_t left_n, std::size_t right_n>
inline bool get_text_between(std::string const& src, std::string::const_iterator src_begin, char const(&left)[left_n], char const(&right)[right_n], std::string::const_iterator& rezult_begin, std::string::const_iterator& rezult_end) {
std::size_t pos1 = src.find(left);
if (std::string::npos == pos1) {
return false;
}
std::size_t pos2 = src.find(right, pos1 + left_n - 1);
if (std::string::npos == pos2) {
return false;
}
rezult_begin = src_begin + pos1 + left_n - 1;
rezult_end = src_begin + pos2;
return true;
}
template <std::size_t left_n>
inline bool get_text_between(std::string const& src, std::string::const_iterator src_begin, char const(&left)[left_n], char right, std::string::const_iterator& rezult_begin, std::string::const_iterator& rezult_end) {
std::size_t pos1 = src.find(left);
if (std::string::npos == pos1) {
return false;
}
std::size_t pos2 = src.find(right, pos1 + left_n - 1);
if (std::string::npos == pos2) {
return false;
}
rezult_begin = src_begin + pos1 + left_n - 1;
rezult_end = src_begin + pos2;
return true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
inline void mta10_parser_objects_t::parse_next_line(std::string const& line) {
/*
// Разбор спиритом
std::string::const_iterator begin = line.begin(), end = line.end();
if (boost::spirit::qi::phrase_parse(begin, end, object_dynamic_t_parser, boost::spirit::ascii::space)) {
assert(end == begin && "Ошибка парсинга");
objects.insert(object);
}
*/
// Ручной разбор
if (parse_next_line_impl(line, object)) {
objects.insert(object);
}
// В коде оставлены оба варианта разбора, так как еще не решил, какой из них эффективней
}
inline bool mta10_parser_objects_t::parse_next_line_impl(std::string const& line, object_dynamic_t& object) {
if (std::string::npos == line.find("<object ")) {
return false;
}
std::string::const_iterator line_begin = line.begin(), begin, end;
if (!get_text_between(line, line_begin, "model=\"", '"', begin, end)) {assert(false); return false;}
if (!boost::spirit::qi::parse(begin, end, boost::spirit::qi::int_, object.model_id)) {assert(false); return false;}
assert(end == begin);
if (get_text_between(line, line_begin, "interior=\"", '"', begin, end)) {
if (!boost::spirit::qi::parse(begin, end, boost::spirit::qi::int_, object.interior)) {assert(false); return false;}
}
else {
object.interior = 0;
}
if (!get_text_between(line, line_begin, "posX=\"", '"', begin, end)) {assert(false); return false;}
if (!boost::spirit::qi::parse(begin, end, boost::spirit::qi::float_, object.x)) {assert(false); return false;}
assert(end == begin);
if (!get_text_between(line, line_begin, "posY=\"", '"', begin, end)) {assert(false); return false;}
if (!boost::spirit::qi::parse(begin, end, boost::spirit::qi::float_, object.y)) {assert(false); return false;}
assert(end == begin);
if (!get_text_between(line, line_begin, "posZ=\"", '"', begin, end)) {assert(false); return false;}
if (!boost::spirit::qi::parse(begin, end, boost::spirit::qi::float_, object.z)) {assert(false); return false;}
assert(end == begin);
if (!get_text_between(line, line_begin, "rotX=\"", '"', begin, end)) {assert(false); return false;}
if (!boost::spirit::qi::parse(begin, end, boost::spirit::qi::float_, object.rx)) {assert(false); return false;}
assert(end == begin);
if (!get_text_between(line, line_begin, "rotY=\"", '"', begin, end)) {assert(false); return false;}
if (!boost::spirit::qi::parse(begin, end, boost::spirit::qi::float_, object.ry)) {assert(false); return false;}
assert(end == begin);
if (!get_text_between(line, line_begin, "rotZ=\"", '"', begin, end)) {assert(false); return false;}
if (!boost::spirit::qi::parse(begin, end, boost::spirit::qi::float_, object.rz)) {assert(false); return false;}
assert(end == begin);
return true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
inline void mta10_parser_spawn_points_t::parse_next_line(std::string const& line) {
pos4 pos(.0f, .0f, .0f, 0, item_ptr->world, .0f);
if (parse_next_line_impl(line, pos)) {
spawn_points.push_back(pos);
}
}
inline bool mta10_parser_spawn_points_t::parse_next_line_impl(std::string const& line, pos4& pos) {
if (std::string::npos == line.find("<spawnpoint ")) {
return false;
}
std::string::const_iterator line_begin = line.begin(), begin, end;
if (get_text_between(line, line_begin, "interior=\"", '"', begin, end)) {
if (!boost::spirit::qi::parse(begin, end, boost::spirit::qi::int_, pos.interior)) {assert(false); return false;}
}
else {
pos.interior = 0;
}
if (!get_text_between(line, line_begin, "posX=\"", '"', begin, end)) {assert(false); return false;}
if (!boost::spirit::qi::parse(begin, end, boost::spirit::qi::float_, pos.x)) {assert(false); return false;}
assert(end == begin);
if (!get_text_between(line, line_begin, "posY=\"", '"', begin, end)) {assert(false); return false;}
if (!boost::spirit::qi::parse(begin, end, boost::spirit::qi::float_, pos.y)) {assert(false); return false;}
assert(end == begin);
if (!get_text_between(line, line_begin, "posZ=\"", '"', begin, end)) {assert(false); return false;}
if (!boost::spirit::qi::parse(begin, end, boost::spirit::qi::float_, pos.z)) {assert(false); return false;}
assert(end == begin);
if (!get_text_between(line, line_begin, "rotZ=\"", '"', begin, end)) {assert(false); return false;}
if (!boost::spirit::qi::parse(begin, end, boost::spirit::qi::float_, pos.rz)) {assert(false); return false;}
assert(end == begin);
return true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
inline void mta10_parser_vehicles_t::parse_next_line(std::string const& line) {
pos_vehicle vehicle(0, .0f, .0f, .0f, 0, item_ptr->world, .0f, -1, -1, item_ptr->respawn_delay);
if (parse_next_line_impl(line, vehicle)) {
vehicles.insert(vehicle);
}
}
inline bool mta10_parser_vehicles_t::parse_next_line_impl(std::string const& line, pos_vehicle& vehicle) {
if (std::string::npos == line.find("<vehicle ")) {
return false;
}
std::string::const_iterator line_begin = line.begin(), begin, end;
if (!get_text_between(line, line_begin, "model=\"", '"', begin, end)) {assert(false); return false;}
if (!boost::spirit::qi::parse(begin, end, boost::spirit::qi::int_, vehicle.model_id)) {assert(false); return false;}
assert(end == begin);
if (get_text_between(line, line_begin, "interior=\"", '"', begin, end)) {
if (!boost::spirit::qi::parse(begin, end, boost::spirit::qi::int_, vehicle.interior)) {assert(false); return false;}
}
else {
vehicle.interior = 0;
}
if (!get_text_between(line, line_begin, "posX=\"", '"', begin, end)) {assert(false); return false;}
if (!boost::spirit::qi::parse(begin, end, boost::spirit::qi::float_, vehicle.x)) {assert(false); return false;}
assert(end == begin);
if (!get_text_between(line, line_begin, "posY=\"", '"', begin, end)) {assert(false); return false;}
if (!boost::spirit::qi::parse(begin, end, boost::spirit::qi::float_, vehicle.y)) {assert(false); return false;}
assert(end == begin);
if (!get_text_between(line, line_begin, "posZ=\"", '"', begin, end)) {assert(false); return false;}
if (!boost::spirit::qi::parse(begin, end, boost::spirit::qi::float_, vehicle.z)) {assert(false); return false;}
assert(end == begin);
if (!get_text_between(line, line_begin, "rotZ=\"", '"', begin, end)) {assert(false); return false;}
if (!boost::spirit::qi::parse(begin, end, boost::spirit::qi::float_, vehicle.rz)) {assert(false); return false;}
assert(end == begin);
return true;
}
/* медленный вариант
template <typename item_t, typename parser_t>
inline void load_item_impl(item_t const& item, boost::filesystem::path const& file_name, parser_t& parser) {
boost::filesystem::ifstream file(file_name, std::ios_base::binary);
if (file) {
parser.parse_begin(item);
for (;;) {
std::string buffer;
std::getline(file, buffer);
parser.parse_next_line(buffer);
if (file.eof()) {
break;
}
}
parser.parse_end();
}
else {
assert(false && "не удалось открыть файл");
}
}
*/
template <typename item_t, typename parser_t>
inline void load_item_impl(item_t const& item, boost::filesystem::path const& file_name, parser_t& parser) {
boost::filesystem::ifstream file(file_name, std::ios_base::binary);
if (file) {
parser.parse_begin(item);
char file_buff[1024];
for (;!file.eof();) {
file.getline(file_buff, sizeof(file_buff) / sizeof(file_buff[0]));
parser.parse_next_line(std::string(file_buff));
}
parser.parse_end();
}
else {
assert(false && "не удалось открыть файл");
}
}
template <typename item_t, typename parser_t>
inline void load_items_impl(std::vector<item_t> const& items, boost::filesystem::path const& root_path, parser_t& parser) {
BOOST_FOREACH(item_t const& item, items) {
iterate_directory(root_path / item.file_name, ".*\\.map",
std::tr1::bind(
static_cast<void (*)(item_t const& item, boost::filesystem::path const& file_name, parser_t& parser)>(&load_item_impl)
,std::tr1::cref(item)
,std::tr1::placeholders::_1
,std::tr1::ref(parser)
)
);
}
}
}; // namespace {
mta10_loader::mta10_loader(boost::filesystem::path const& root_path): root_path(root_path) {
}
mta10_loader::~mta10_loader() {
}
void mta10_loader::load_items(mta10_loader_items_t const& items, objects_dynamic_t& objects) {
mta10_parser_objects_t parser(objects);
load_items_impl(items, root_path, parser);
}
void mta10_loader::load_items(mta10_loader_vehicles_t const& items, vehicles_dynamic_t& vehicles) {
mta10_parser_vehicles_t parser(vehicles);
load_items_impl(items, root_path, parser);
}
void mta10_loader::load_items(mta10_loader_items_t const& items, spawn_points_t& spawn_points) {
mta10_parser_spawn_points_t parser(spawn_points);
load_items_impl(items, root_path, parser);
}
| [
"dimonml@19848965-7475-ded4-60a4-26152d85fbc5"
]
| [
[
[
1,
325
]
]
]
|
af63caea8a8dd83181c51792e5c5fb368e11571e | 2b80036db6f86012afcc7bc55431355fc3234058 | /src/contrib/apedecoder/ape/MACLib.h | af0cbcd162c58fec2d1f574404d6d2aaacada4c4 | [
"BSD-3-Clause"
]
| permissive | leezhongshan/musikcube | d1e09cf263854bb16acbde707cb6c18b09a0189f | e7ca6a5515a5f5e8e499bbdd158e5cb406fda948 | refs/heads/master | 2021-01-15T11:45:29.512171 | 2011-02-25T14:09:21 | 2011-02-25T14:09:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,056 | h | /*****************************************************************************************
Monkey's Audio MACLib.h (include for using MACLib.lib in your projects)
Copyright (C) 2000-2003 by Matthew T. Ashland All Rights Reserved.
Overview:
There are two main interfaces... create one (using CreateIAPExxx) and go to town:
IAPECompress - for creating APE files
IAPEDecompress - for decompressing and analyzing APE files
Note(s):
Unless otherwise specified, functions return ERROR_SUCCESS (0) on success and an
error code on failure.
The terminology "Sample" refers to a single sample value, and "Block" refers
to a collection of "Channel" samples. For simplicity, MAC typically uses blocks
everywhere so that channel mis-alignment cannot happen. (i.e. on a CD, a sample is
2 bytes and a block is 4 bytes ([2 bytes per sample] * [2 channels] = 4 bytes))
Questions / Suggestions:
Please direct questions or comments to the Monkey's Audio developers board:
http://www.monkeysaudio.com/cgi-bin/YaBB/YaBB.cgi -> Developers
or, if necessary, matt @ monkeysaudio.com
*****************************************************************************************/
#ifndef APE_MACLIB_H
#define APE_MACLIB_H
/*************************************************************************************************
APE File Format Overview: (pieces in order -- only valid for the latest version APE files)
JUNK - any amount of "junk" before the APE_DESCRIPTOR (so people that put ID3v2 tags on the files aren't hosed)
APE_DESCRIPTOR - defines the sizes (and offsets) of all the pieces, as well as the MD5 checksum
APE_HEADER - describes all of the necessary information about the APE file
SEEK TABLE - the table that represents seek offsets [optional]
HEADER DATA - the pre-audio data from the original file [optional]
APE FRAMES - the actual compressed audio (broken into frames for seekability)
TERMINATING DATA - the post-audio data from the original file [optional]
TAG - describes all the properties of the file [optional]
Notes:
Junk:
This block may not be supported in the future, so don't write any software that adds meta data
before the APE_DESCRIPTOR. Please use the APE Tag for any meta data.
Seek Table:
A 32-bit unsigned integer array of offsets from the header to the frame data. May become "delta"
values someday to better suit huge files.
MD5 Hash:
Since the header is the last part written to an APE file, you must calculate the MD5 checksum out of order.
So, you first calculate from the tail of the seek table to the end of the terminating data.
Then, go back and do from the end of the descriptor to the tail of the seek table.
You may wish to just cache the header data when starting and run it last, so you don't
need to seek back in the I/O.
*************************************************************************************************/
/*****************************************************************************************
Defines
*****************************************************************************************/
#define COMPRESSION_LEVEL_FAST 1000
#define COMPRESSION_LEVEL_NORMAL 2000
#define COMPRESSION_LEVEL_HIGH 3000
#define COMPRESSION_LEVEL_EXTRA_HIGH 4000
#define COMPRESSION_LEVEL_INSANE 5000
#define MAC_FORMAT_FLAG_8_BIT 1 // is 8-bit [OBSOLETE]
#define MAC_FORMAT_FLAG_CRC 2 // uses the new CRC32 error detection [OBSOLETE]
#define MAC_FORMAT_FLAG_HAS_PEAK_LEVEL 4 // uint32 nPeakLevel after the header [OBSOLETE]
#define MAC_FORMAT_FLAG_24_BIT 8 // is 24-bit [OBSOLETE]
#define MAC_FORMAT_FLAG_HAS_SEEK_ELEMENTS 16 // has the number of seek elements after the peak level
#define MAC_FORMAT_FLAG_CREATE_WAV_HEADER 32 // create the wave header on decompression (not stored)
#define CREATE_WAV_HEADER_ON_DECOMPRESSION -1
#define MAX_AUDIO_BYTES_UNKNOWN -1
typedef void (__stdcall * APE_PROGRESS_CALLBACK) (int);
/*****************************************************************************************
WAV header structure
*****************************************************************************************/
struct WAVE_HEADER
{
// RIFF header
char cRIFFHeader[4];
unsigned int nRIFFBytes;
// data type
char cDataTypeID[4];
// wave format
char cFormatHeader[4];
unsigned int nFormatBytes;
unsigned short nFormatTag;
unsigned short nChannels;
unsigned int nSamplesPerSec;
unsigned int nAvgBytesPerSec;
unsigned short nBlockAlign;
unsigned short nBitsPerSample;
// data chunk header
char cDataHeader[4];
unsigned int nDataBytes;
};
/*****************************************************************************************
APE_DESCRIPTOR structure (file header that describes lengths, offsets, etc.)
*****************************************************************************************/
struct APE_DESCRIPTOR
{
char cID[4]; // should equal 'MAC '
uint16 nVersion; // version number * 1000 (3.81 = 3810)
uint32 nDescriptorBytes; // the number of descriptor bytes (allows later expansion of this header)
uint32 nHeaderBytes; // the number of header APE_HEADER bytes
uint32 nSeekTableBytes; // the number of bytes of the seek table
uint32 nHeaderDataBytes; // the number of header data bytes (from original file)
uint32 nAPEFrameDataBytes; // the number of bytes of APE frame data
uint32 nAPEFrameDataBytesHigh; // the high order number of APE frame data bytes
uint32 nTerminatingDataBytes; // the terminating data of the file (not including tag data)
uint8 cFileMD5[16]; // the MD5 hash of the file (see notes for usage... it's a littly tricky)
};
/*****************************************************************************************
APE_HEADER structure (describes the format, duration, etc. of the APE file)
*****************************************************************************************/
struct APE_HEADER
{
uint16 nCompressionLevel; // the compression level (see defines I.E. COMPRESSION_LEVEL_FAST)
uint16 nFormatFlags; // any format flags (for future use)
uint32 nBlocksPerFrame; // the number of audio blocks in one frame
uint32 nFinalFrameBlocks; // the number of audio blocks in the final frame
uint32 nTotalFrames; // the total number of frames
uint16 nBitsPerSample; // the bits per sample (typically 16)
uint16 nChannels; // the number of channels (1 or 2)
uint32 nSampleRate; // the sample rate (typically 44100)
};
/*************************************************************************************************
Classes (fully defined elsewhere)
*************************************************************************************************/
class CIO;
class CInputSource;
class CAPEInfo;
/*************************************************************************************************
IAPEDecompress fields - used when querying for information
Note(s):
-the distinction between APE_INFO_XXXX and APE_DECOMPRESS_XXXX is that the first is querying the APE
information engine, and the other is querying the decompressor, and since the decompressor can be
a range of an APE file (for APL), differences will arise. Typically, use the APE_DECOMPRESS_XXXX
fields when querying for info about the length, etc. so APL will work properly.
(i.e. (APE_INFO_TOTAL_BLOCKS != APE_DECOMPRESS_TOTAL_BLOCKS) for APL files)
*************************************************************************************************/
enum APE_DECOMPRESS_FIELDS
{
APE_INFO_FILE_VERSION = 1000, // version of the APE file * 1000 (3.93 = 3930) [ignored, ignored]
APE_INFO_COMPRESSION_LEVEL = 1001, // compression level of the APE file [ignored, ignored]
APE_INFO_FORMAT_FLAGS = 1002, // format flags of the APE file [ignored, ignored]
APE_INFO_SAMPLE_RATE = 1003, // sample rate (Hz) [ignored, ignored]
APE_INFO_BITS_PER_SAMPLE = 1004, // bits per sample [ignored, ignored]
APE_INFO_BYTES_PER_SAMPLE = 1005, // number of bytes per sample [ignored, ignored]
APE_INFO_CHANNELS = 1006, // channels [ignored, ignored]
APE_INFO_BLOCK_ALIGN = 1007, // block alignment [ignored, ignored]
APE_INFO_BLOCKS_PER_FRAME = 1008, // number of blocks in a frame (frames are used internally) [ignored, ignored]
APE_INFO_FINAL_FRAME_BLOCKS = 1009, // blocks in the final frame (frames are used internally) [ignored, ignored]
APE_INFO_TOTAL_FRAMES = 1010, // total number frames (frames are used internally) [ignored, ignored]
APE_INFO_WAV_HEADER_BYTES = 1011, // header bytes of the decompressed WAV [ignored, ignored]
APE_INFO_WAV_TERMINATING_BYTES = 1012, // terminating bytes of the decompressed WAV [ignored, ignored]
APE_INFO_WAV_DATA_BYTES = 1013, // data bytes of the decompressed WAV [ignored, ignored]
APE_INFO_WAV_TOTAL_BYTES = 1014, // total bytes of the decompressed WAV [ignored, ignored]
APE_INFO_APE_TOTAL_BYTES = 1015, // total bytes of the APE file [ignored, ignored]
APE_INFO_TOTAL_BLOCKS = 1016, // total blocks of audio data [ignored, ignored]
APE_INFO_LENGTH_MS = 1017, // length in ms (1 sec = 1000 ms) [ignored, ignored]
APE_INFO_AVERAGE_BITRATE = 1018, // average bitrate of the APE [ignored, ignored]
APE_INFO_FRAME_BITRATE = 1019, // bitrate of specified APE frame [frame index, ignored]
APE_INFO_DECOMPRESSED_BITRATE = 1020, // bitrate of the decompressed WAV [ignored, ignored]
APE_INFO_PEAK_LEVEL = 1021, // peak audio level (obsolete) (-1 is unknown) [ignored, ignored]
APE_INFO_SEEK_BIT = 1022, // bit offset [frame index, ignored]
APE_INFO_SEEK_BYTE = 1023, // byte offset [frame index, ignored]
APE_INFO_WAV_HEADER_DATA = 1024, // error code [buffer *, max bytes]
APE_INFO_WAV_TERMINATING_DATA = 1025, // error code [buffer *, max bytes]
APE_INFO_WAVEFORMATEX = 1026, // error code [waveformatex *, ignored]
APE_INFO_IO_SOURCE = 1027, // I/O source (CIO *) [ignored, ignored]
APE_INFO_FRAME_BYTES = 1028, // bytes (compressed) of the frame [frame index, ignored]
APE_INFO_FRAME_BLOCKS = 1029, // blocks in a given frame [frame index, ignored]
APE_INFO_TAG = 1030, // point to tag (CAPETag *) [ignored, ignored]
APE_DECOMPRESS_CURRENT_BLOCK = 2000, // current block location [ignored, ignored]
APE_DECOMPRESS_CURRENT_MS = 2001, // current millisecond location [ignored, ignored]
APE_DECOMPRESS_TOTAL_BLOCKS = 2002, // total blocks in the decompressors range [ignored, ignored]
APE_DECOMPRESS_LENGTH_MS = 2003, // total blocks in the decompressors range [ignored, ignored]
APE_DECOMPRESS_CURRENT_BITRATE = 2004, // current bitrate [ignored, ignored]
APE_DECOMPRESS_AVERAGE_BITRATE = 2005, // average bitrate (works with ranges) [ignored, ignored]
APE_INTERNAL_INFO = 3000, // for internal use -- don't use (returns APE_FILE_INFO *) [ignored, ignored]
};
/*************************************************************************************************
IAPEDecompress - interface for working with existing APE files (decoding, seeking, analyzing, etc.)
*************************************************************************************************/
class IAPEDecompress
{
public:
// destructor (needed so implementation's destructor will be called)
virtual ~IAPEDecompress() {}
/*********************************************************************************************
* Decompress / Seek
*********************************************************************************************/
//////////////////////////////////////////////////////////////////////////////////////////////
// GetData(...) - gets raw decompressed audio
//
// Parameters:
// char * pBuffer
// a pointer to a buffer to put the data into
// int nBlocks
// the number of audio blocks desired (see note at intro about blocks vs. samples)
// int * pBlocksRetrieved
// the number of blocks actually retrieved (could be less at end of file or on critical failure)
//////////////////////////////////////////////////////////////////////////////////////////////
virtual int GetData(char * pBuffer, int nBlocks, int * pBlocksRetrieved) = 0;
//////////////////////////////////////////////////////////////////////////////////////////////
// Seek(...) - seeks
//
// Parameters:
// int nBlockOffset
// the block to seek to (see note at intro about blocks vs. samples)
//////////////////////////////////////////////////////////////////////////////////////////////
virtual int Seek(int nBlockOffset) = 0;
/*********************************************************************************************
* Get Information
*********************************************************************************************/
//////////////////////////////////////////////////////////////////////////////////////////////
// GetInfo(...) - get information about the APE file or the state of the decompressor
//
// Parameters:
// APE_DECOMPRESS_FIELDS Field
// the field we're querying (see APE_DECOMPRESS_FIELDS above for more info)
// int nParam1
// generic parameter... usage is listed in APE_DECOMPRESS_FIELDS
// int nParam2
// generic parameter... usage is listed in APE_DECOMPRESS_FIELDS
//////////////////////////////////////////////////////////////////////////////////////////////
virtual int GetInfo(APE_DECOMPRESS_FIELDS Field, int nParam1 = 0, int nParam2 = 0) = 0;
};
/*************************************************************************************************
IAPECompress - interface for creating APE files
Usage:
To create an APE file, you Start(...), then add data (in a variety of ways), then Finish(...)
*************************************************************************************************/
class IAPECompress
{
public:
// destructor (needed so implementation's destructor will be called)
virtual ~IAPECompress() {}
/*********************************************************************************************
* Start
*********************************************************************************************/
//////////////////////////////////////////////////////////////////////////////////////////////
// Start(...) / StartEx(...) - starts encoding
//
// Parameters:
// CIO * pioOutput / const str_utf16 * pFilename
// the output... either a filename or an I/O source
// WAVEFORMATEX * pwfeInput
// format of the audio to encode (use FillWaveFormatEx() if necessary)
// int nMaxAudioBytes
// the absolute maximum audio bytes that will be encoded... encoding fails with a
// ERROR_APE_COMPRESS_TOO_MUCH_DATA if you attempt to encode more than specified here
// (if unknown, use MAX_AUDIO_BYTES_UNKNOWN to allocate as much storage in the seek table as
// possible... limit is then 2 GB of data (~4 hours of CD music)... this wastes around
// 30kb, so only do it if completely necessary)
// int nCompressionLevel
// the compression level for the APE file (fast - extra high)
// (note: extra-high is much slower for little gain)
// const void * pHeaderData
// a pointer to a buffer containing the WAV header (data before the data block in the WAV)
// (note: use NULL for on-the-fly encoding... see next parameter)
// int nHeaderBytes
// number of bytes in the header data buffer (use CREATE_WAV_HEADER_ON_DECOMPRESSION and
// NULL for the pHeaderData and MAC will automatically create the appropriate WAV header
// on decompression)
//////////////////////////////////////////////////////////////////////////////////////////////
virtual int Start(const str_utf16 * pOutputFilename, const WAVEFORMATEX * pwfeInput,
int nMaxAudioBytes = MAX_AUDIO_BYTES_UNKNOWN, int nCompressionLevel = COMPRESSION_LEVEL_NORMAL,
const void * pHeaderData = NULL, int nHeaderBytes = CREATE_WAV_HEADER_ON_DECOMPRESSION) = 0;
virtual int StartEx(CIO * pioOutput, const WAVEFORMATEX * pwfeInput,
int nMaxAudioBytes = MAX_AUDIO_BYTES_UNKNOWN, int nCompressionLevel = COMPRESSION_LEVEL_NORMAL,
const void * pHeaderData = NULL, int nHeaderBytes = CREATE_WAV_HEADER_ON_DECOMPRESSION) = 0;
/*********************************************************************************************
* Add / Compress Data
* - there are 3 ways to add data:
* 1) simple call AddData(...)
* 2) lock MAC's buffer, copy into it, and unlock (LockBuffer(...) / UnlockBuffer(...))
* 3) from an I/O source (AddDataFromInputSource(...))
*********************************************************************************************/
//////////////////////////////////////////////////////////////////////////////////////////////
// AddData(...) - adds data to the encoder
//
// Parameters:
// unsigned char * pData
// a pointer to a buffer containing the raw audio data
// int nBytes
// the number of bytes in the buffer
//////////////////////////////////////////////////////////////////////////////////////////////
virtual int AddData(unsigned char * pData, int nBytes) = 0;
//////////////////////////////////////////////////////////////////////////////////////////////
// GetBufferBytesAvailable(...) - returns the number of bytes available in the buffer
// (helpful when locking)
//////////////////////////////////////////////////////////////////////////////////////////////
virtual int GetBufferBytesAvailable() = 0;
//////////////////////////////////////////////////////////////////////////////////////////////
// LockBuffer(...) - locks MAC's buffer so we can copy into it
//
// Parameters:
// int * pBytesAvailable
// returns the number of bytes available in the buffer (DO NOT COPY MORE THAN THIS IN)
//
// Return:
// pointer to the buffer (add at that location)
//////////////////////////////////////////////////////////////////////////////////////////////
virtual unsigned char * LockBuffer(int * pBytesAvailable) = 0;
//////////////////////////////////////////////////////////////////////////////////////////////
// UnlockBuffer(...) - releases the buffer
//
// Parameters:
// int nBytesAdded
// the number of bytes copied into the buffer
// BOOL bProcess
// whether MAC should process as much as possible of the buffer
//////////////////////////////////////////////////////////////////////////////////////////////
virtual int UnlockBuffer(int nBytesAdded, BOOL bProcess = TRUE) = 0;
//////////////////////////////////////////////////////////////////////////////////////////////
// AddDataFromInputSource(...) - use a CInputSource (input source) to add data
//
// Parameters:
// CInputSource * pInputSource
// a pointer to the input source
// int nMaxBytes
// the maximum number of bytes to let MAC add (-1 if MAC can add any amount)
// int * pBytesAdded
// returns the number of bytes added from the I/O source
//////////////////////////////////////////////////////////////////////////////////////////////
virtual int AddDataFromInputSource(CInputSource * pInputSource, int nMaxBytes = -1, int * pBytesAdded = NULL) = 0;
/*********************************************************************************************
* Finish / Kill
*********************************************************************************************/
//////////////////////////////////////////////////////////////////////////////////////////////
// Finish(...) - ends encoding and finalizes the file
//
// Parameters:
// unsigned char * pTerminatingData
// a pointer to a buffer containing the information to place at the end of the APE file
// (comprised of the WAV terminating data (data after the data block in the WAV) followed
// by any tag information)
// int nTerminatingBytes
// number of bytes in the terminating data buffer
// int nWAVTerminatingBytes
// the number of bytes of the terminating data buffer that should be appended to a decoded
// WAV file (it's basically nTerminatingBytes - the bytes that make up the tag)
//////////////////////////////////////////////////////////////////////////////////////////////
virtual int Finish(unsigned char * pTerminatingData, int nTerminatingBytes, int nWAVTerminatingBytes) = 0;
//////////////////////////////////////////////////////////////////////////////////////////////
// Kill(...) - stops encoding and deletes the output file
// --- NOT CURRENTLY IMPLEMENTED ---
//////////////////////////////////////////////////////////////////////////////////////////////
virtual int Kill() = 0;
};
/*************************************************************************************************
Functions to create the interfaces
Usage:
Interface creation returns a NULL pointer on failure (and fills error code if it was passed in)
Usage example:
int nErrorCode;
IAPEDecompress * pAPEDecompress = CreateIAPEDecompress("c:\\1.ape", &nErrorCode);
if (pAPEDecompress == NULL)
{
// failure... nErrorCode will have specific code
}
*************************************************************************************************/
extern "C"
{
IAPEDecompress * __stdcall CreateIAPEDecompress(const str_utf16 * pFilename, int * pErrorCode = NULL);
IAPEDecompress * __stdcall CreateIAPEDecompressEx(CIO * pIO, int * pErrorCode = NULL);
IAPEDecompress * __stdcall CreateIAPEDecompressEx2(CAPEInfo * pAPEInfo, int nStartBlock = -1, int nFinishBlock = -1, int * pErrorCode = NULL);
IAPECompress * __stdcall CreateIAPECompress(int * pErrorCode = NULL);
}
/*************************************************************************************************
Simple functions - see the SDK sample projects for usage examples
*************************************************************************************************/
extern "C"
{
// process whole files
DLLEXPORT int __stdcall CompressFile(const str_ansi * pInputFilename, const str_ansi * pOutputFilename, int nCompressionLevel = COMPRESSION_LEVEL_NORMAL, int * pPercentageDone = NULL, APE_PROGRESS_CALLBACK ProgressCallback = 0, int * pKillFlag = NULL);
DLLEXPORT int __stdcall DecompressFile(const str_ansi * pInputFilename, const str_ansi * pOutputFilename, int * pPercentageDone, APE_PROGRESS_CALLBACK ProgressCallback, int * pKillFlag);
DLLEXPORT int __stdcall ConvertFile(const str_ansi * pInputFilename, const str_ansi * pOutputFilename, int nCompressionLevel, int * pPercentageDone, APE_PROGRESS_CALLBACK ProgressCallback, int * pKillFlag);
DLLEXPORT int __stdcall VerifyFile(const str_ansi * pInputFilename, int * pPercentageDone, APE_PROGRESS_CALLBACK ProgressCallback, int * pKillFlag);
DLLEXPORT int __stdcall CompressFileW(const str_utf16 * pInputFilename, const str_utf16 * pOutputFilename, int nCompressionLevel = COMPRESSION_LEVEL_NORMAL, int * pPercentageDone = NULL, APE_PROGRESS_CALLBACK ProgressCallback = 0, int * pKillFlag = NULL);
DLLEXPORT int __stdcall DecompressFileW(const str_utf16 * pInputFilename, const str_utf16 * pOutputFilename, int * pPercentageDone, APE_PROGRESS_CALLBACK ProgressCallback, int * pKillFlag);
DLLEXPORT int __stdcall ConvertFileW(const str_utf16 * pInputFilename, const str_utf16 * pOutputFilename, int nCompressionLevel, int * pPercentageDone, APE_PROGRESS_CALLBACK ProgressCallback, int * pKillFlag);
DLLEXPORT int __stdcall VerifyFileW(const str_utf16 * pInputFilename, int * pPercentageDone, APE_PROGRESS_CALLBACK ProgressCallback, int * pKillFlag, BOOL bQuickVerifyIfPossible = FALSE);
// helper functions
DLLEXPORT int __stdcall FillWaveFormatEx(WAVEFORMATEX * pWaveFormatEx, int nSampleRate = 44100, int nBitsPerSample = 16, int nChannels = 2);
DLLEXPORT int __stdcall FillWaveHeader(WAVE_HEADER * pWAVHeader, int nAudioBytes, WAVEFORMATEX * pWaveFormatEx, int nTerminatingBytes = 0);
}
#endif // #ifndef APE_MACLIB_H
| [
"onnerby@6a861d04-ae47-0410-a6da-2d49beace72e"
]
| [
[
[
1,
450
]
]
]
|
2aa2c58f24c2db9605d036d8579139a54cb6da9f | 29792c63c345f87474136c8df87beb771f0a20a8 | /server/player.cpp | 28bd5f61ed83c6b4791034c554ea5884cd10dc76 | []
| no_license | uvbs/jvcmp | 244ba6c2ab14ce0a757f3f6044b5982287b01fae | 57225e1c52085216a0a4a9c4e33ed324c1c92d39 | refs/heads/master | 2020-12-29T00:25:39.180996 | 2009-06-24T14:52:39 | 2009-06-24T14:52:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,766 | cpp | // File Author: kyeman
#include "netgame.h"
extern CNetGame *pNetGame;
void DecompressVector1(VECTOR_PAD * vec, C_VECTOR1 * c1)
{
vec->X = (float)c1->X;
vec->X = (float)((double)vec->X / 10000.0);
vec->Y = (float)c1->Y;
vec->Y = (float)((double)vec->Y / 10000.0);
vec->Z = (float)c1->Z;
vec->Z = (float)((double)vec->Z / 10000.0);
}
CPlayer::CPlayer()
{
m_byteUpdateFromNetwork = UPDATE_TYPE_NONE;
m_bytePlayerID = INVALID_PLAYER_ID;
m_bIsActive = FALSE;
m_bIsWasted = FALSE;
m_byteVehicleID = 0;
}
void CPlayer::Process()
{
if(m_bIsActive)
{
if(m_byteUpdateFromNetwork != UPDATE_TYPE_NONE)
{
if(ValidateSyncData()) {
BroadcastSyncData();
}
m_byteUpdateFromNetwork = UPDATE_TYPE_NONE;
}
}
}
BOOL CPlayer::ValidateSyncData()
{
if(m_vecPos.X > 2500.0f || m_vecPos.X < -2500.0f) {
return FALSE;
}
if(m_vecPos.Y > 2500.0f || m_vecPos.Y < -2500.0f) {
return FALSE;
}
if(m_vecPos.Z > 300.0f || m_vecPos.Z < 0.0f) {
return FALSE;
}
return TRUE;
}
void CPlayer::BroadcastSyncData()
{
RakNet::BitStream bsSync;
if(m_byteUpdateFromNetwork == UPDATE_TYPE_FULL_ONFOOT)
{
bsSync.Write((BYTE)ID_PLAYER_SYNC);
bsSync.Write(m_bytePlayerID);
bsSync.Write((WORD)m_wKeys);
bsSync.Write(m_vecPos.X);
bsSync.Write(m_vecPos.Y);
bsSync.Write(m_vecPos.Z);
bsSync.Write(m_fRotation);
bsSync.Write(m_byteAction);
bsSync.Write(m_byteHealth);
bsSync.Write(m_byteCurrentWeapon);
if(IS_FIRING(m_wKeys)) {
// aiming
bsSync.Write(m_Aiming.f1x);
bsSync.Write(m_Aiming.f1y);
bsSync.Write(m_Aiming.f1z);
bsSync.Write(m_Aiming.f2x);
bsSync.Write(m_Aiming.f2y);
bsSync.Write(m_Aiming.f2z);
bsSync.Write(m_Aiming.pos1x);
bsSync.Write(m_Aiming.pos1y);
bsSync.Write(m_Aiming.pos1z);
}
pNetGame->BroadcastData(&bsSync,HIGH_PRIORITY,UNRELIABLE,0,m_bytePlayerID);
}
else if(m_byteUpdateFromNetwork == UPDATE_TYPE_FULL_INCAR)
{
BYTE byteWriteVehicleHealth;
// packing
byteWriteVehicleHealth = PACK_VEHICLE_HEALTH(m_fVehicleHealth);
// storing
bsSync.Write((BYTE)ID_VEHICLE_SYNC);
bsSync.Write(m_bytePlayerID);
bsSync.Write(m_byteVehicleID);
bsSync.Write((WORD)m_wKeys);
bsSync.Write(m_cvecRoll.X);
bsSync.Write(m_cvecRoll.Y);
bsSync.Write(m_cvecRoll.Z);
bsSync.Write(m_cvecDirection.X);
bsSync.Write(m_cvecDirection.Y);
bsSync.Write(m_cvecDirection.Z);
bsSync.Write(m_vecPos.X);
bsSync.Write(m_vecPos.Y);
bsSync.Write(m_vecPos.Z);
// move + turn speed
bsSync.Write(m_vecMoveSpeed.X);
bsSync.Write(m_vecMoveSpeed.Y);
bsSync.Write(byteWriteVehicleHealth);
bsSync.Write(m_byteHealth);
// sending...
pNetGame->BroadcastData(&bsSync,HIGH_PRIORITY,UNRELIABLE,0,m_bytePlayerID);
}
}
void CPlayer::StoreOnFootFullSyncData(WORD wKeys,VECTOR * vecPos,
float fRotation,BYTE byteCurrentWeapon,
BYTE byteAction)
{
m_wKeys = wKeys;
memcpy(&m_vecPos,vecPos,sizeof(VECTOR));
m_fRotation = fRotation;
m_byteCurrentWeapon = byteCurrentWeapon;
m_byteAction = byteAction;
m_byteUpdateFromNetwork = UPDATE_TYPE_FULL_ONFOOT;
}
void CPlayer::StoreInCarFullSyncData(BYTE byteVehicleID, WORD wKeys,
C_VECTOR1 * cvecRoll, C_VECTOR1 * cvecDirection,
VECTOR * vecPos, VECTOR * vecMoveSpeed,float fVehicleHealth)
{
m_byteVehicleID = byteVehicleID;
m_bIsInVehicle = TRUE;
m_bIsAPassenger = FALSE;
m_wKeys = wKeys;
memcpy(&m_cvecRoll,cvecRoll,sizeof(C_VECTOR1));
memcpy(&m_cvecDirection,cvecDirection,sizeof(C_VECTOR1));
memcpy(&m_vecPos,vecPos,sizeof(VECTOR));
m_fVehicleHealth = fVehicleHealth;
m_byteUpdateFromNetwork = UPDATE_TYPE_FULL_INCAR;
MATRIX4X4 matWorld;
DecompressVector1(&matWorld.vLookRight,cvecRoll);
DecompressVector1(&matWorld.vLookUp,cvecDirection);
memcpy(&matWorld.vPos,vecPos,sizeof(VECTOR));
memcpy(&m_vecMoveSpeed,vecMoveSpeed,sizeof(VECTOR));
CVehicle *pVehicle = pNetGame->GetVehiclePool()->GetAt(byteVehicleID);
pVehicle->Update(m_bytePlayerID,&matWorld,vecMoveSpeed,fVehicleHealth);
}
void CPlayer::Say(PCHAR szText, BYTE byteTextLength)
{
}
void CPlayer::HandleDeath(BYTE byteReason, BYTE byteWhoWasResponsible)
{
RakNet::BitStream bsPlayerDeath;
PlayerID playerid = pNetGame->GetRakServer()->GetPlayerIDFromIndex(m_bytePlayerID);
m_bIsActive = FALSE;
m_bIsWasted = TRUE;
BYTE byteScoringModifier;
byteScoringModifier =
pNetGame->GetPlayerPool()->AddResponsibleDeath(byteWhoWasResponsible,m_bytePlayerID);
bsPlayerDeath.Write(m_bytePlayerID);
bsPlayerDeath.Write(byteReason);
bsPlayerDeath.Write(byteWhoWasResponsible);
bsPlayerDeath.Write(byteScoringModifier);
// Broadcast it
pNetGame->GetRakServer()->RPC("Death",&bsPlayerDeath,
HIGH_PRIORITY,RELIABLE,0,playerid,TRUE,FALSE);
// Now let the player who died know aswell.
pNetGame->GetRakServer()->RPC("OwnDeath",&bsPlayerDeath,
HIGH_PRIORITY,RELIABLE,0,playerid,FALSE,FALSE);
logprintf("%s died.",pNetGame->GetPlayerPool()->GetPlayerName(m_bytePlayerID));
}
void CPlayer::SetSpawnInfo(BYTE byteTeam, BYTE byteSkin, VECTOR * vecPos, float fRotation,
int iSpawnWeapon1, int iSpawnWeapon1Ammo, int iSpawnWeapon2, int iSpawnWeapon2Ammo,
int iSpawnWeapon3, int iSpawnWeapon3Ammo)
{
m_SpawnInfo.byteTeam = byteTeam;
m_SpawnInfo.byteSkin = byteSkin;
m_SpawnInfo.vecPos.X = vecPos->X;
m_SpawnInfo.vecPos.Y = vecPos->Y;
m_SpawnInfo.vecPos.Z = vecPos->Z;
m_SpawnInfo.fRotation = fRotation;
m_SpawnInfo.iSpawnWeapons[0] = iSpawnWeapon1;
m_SpawnInfo.iSpawnWeapons[1] = iSpawnWeapon2;
m_SpawnInfo.iSpawnWeapons[2] = iSpawnWeapon3;
m_SpawnInfo.iSpawnWeaponsAmmo[0] = iSpawnWeapon1Ammo;
m_SpawnInfo.iSpawnWeaponsAmmo[1] = iSpawnWeapon2Ammo;
m_SpawnInfo.iSpawnWeaponsAmmo[2] = iSpawnWeapon3Ammo;
m_bHasSpawnInfo = TRUE;
}
//----------------------------------------------------
void CPlayer::Spawn()
{
if(m_bHasSpawnInfo) {
// Reset all their sync attributes.
m_vecPos.X = m_SpawnInfo.vecPos.X;
m_vecPos.Y = m_SpawnInfo.vecPos.Y;
m_vecPos.Z = m_SpawnInfo.vecPos.Z;
m_fRotation = m_SpawnInfo.fRotation;
memset(&m_vecMoveSpeed,0,sizeof(VECTOR));
memset(&m_vecTurnSpeed,0,sizeof(VECTOR));
m_fRotation = 0.0f;
m_bIsInVehicle=FALSE;
m_bIsAPassenger=FALSE;
m_byteVehicleID=0;
SpawnForWorld(m_SpawnInfo.byteTeam,m_SpawnInfo.byteSkin,&m_SpawnInfo.vecPos,m_SpawnInfo.fRotation);
}
}
//----------------------------------------------------
// This is the method used for respawning.
void CPlayer::SpawnForWorld( BYTE byteTeam, BYTE byteSkin, VECTOR * vecPos,
float fRotation )
{
RakNet::BitStream bsPlayerSpawn;
PlayerID playerid = pNetGame->GetRakServer()->GetPlayerIDFromIndex(m_bytePlayerID);
bsPlayerSpawn.Write(m_bytePlayerID);
bsPlayerSpawn.Write(byteTeam);
bsPlayerSpawn.Write(byteSkin);
bsPlayerSpawn.Write(vecPos->X);
bsPlayerSpawn.Write(vecPos->Y);
bsPlayerSpawn.Write(vecPos->Z);
bsPlayerSpawn.Write(fRotation);
bsPlayerSpawn.Write(m_SpawnInfo.iSpawnWeapons[0]);
bsPlayerSpawn.Write(m_SpawnInfo.iSpawnWeaponsAmmo[0]);
bsPlayerSpawn.Write(m_SpawnInfo.iSpawnWeapons[1]);
bsPlayerSpawn.Write(m_SpawnInfo.iSpawnWeaponsAmmo[1]);
bsPlayerSpawn.Write(m_SpawnInfo.iSpawnWeapons[2]);
bsPlayerSpawn.Write(m_SpawnInfo.iSpawnWeaponsAmmo[2]);
pNetGame->GetRakServer()->RPC("Spawn",&bsPlayerSpawn,
HIGH_PRIORITY,RELIABLE_ORDERED,0,playerid,TRUE,FALSE);
m_bIsActive = TRUE;
m_bIsWasted = FALSE;
// Set their initial sync position to their spawn position.
m_vecPos.X = vecPos->X;
m_vecPos.Y = vecPos->Y;
m_vecPos.Z = vecPos->Z;
m_byteAction = 1;
}
//----------------------------------------------------
// This is the method used for spawning players that
// already exist in the world when the client connects.
void CPlayer::SpawnForPlayer(BYTE byteForPlayerID)
{
RakNet::BitStream bsPlayerSpawn;
bsPlayerSpawn.Write(m_bytePlayerID);
bsPlayerSpawn.Write(m_SpawnInfo.byteTeam);
bsPlayerSpawn.Write(m_SpawnInfo.byteSkin);
bsPlayerSpawn.Write(m_vecPos.X);
bsPlayerSpawn.Write(m_vecPos.Y);
bsPlayerSpawn.Write(m_vecPos.Z);
bsPlayerSpawn.Write(m_fRotation);
bsPlayerSpawn.Write(m_SpawnInfo.iSpawnWeapons[0]);
bsPlayerSpawn.Write(m_SpawnInfo.iSpawnWeaponsAmmo[0]);
bsPlayerSpawn.Write(m_SpawnInfo.iSpawnWeapons[1]);
bsPlayerSpawn.Write(m_SpawnInfo.iSpawnWeaponsAmmo[1]);
bsPlayerSpawn.Write(m_SpawnInfo.iSpawnWeapons[2]);
bsPlayerSpawn.Write(m_SpawnInfo.iSpawnWeaponsAmmo[2]);
pNetGame->GetRakServer()->RPC("Spawn",&bsPlayerSpawn,HIGH_PRIORITY,RELIABLE_ORDERED,
0,pNetGame->GetRakServer()->GetPlayerIDFromIndex(byteForPlayerID),FALSE,FALSE);
}
//----------------------------------------------------
void CPlayer::EnterVehicle(BYTE byteVehicleID, BYTE bytePassenger)
{
RakNet::BitStream bsVehicle;
PlayerID playerid = pNetGame->GetRakServer()->GetPlayerIDFromIndex(m_bytePlayerID);
bsVehicle.Write(m_bytePlayerID);
bsVehicle.Write(byteVehicleID);
bsVehicle.Write(bytePassenger);
pNetGame->GetRakServer()->RPC("EnterVehicle",&bsVehicle,HIGH_PRIORITY,RELIABLE_ORDERED,
0,playerid,TRUE,FALSE);
}
//----------------------------------------------------
void CPlayer::ExitVehicle(BYTE byteVehicleID)
{
RakNet::BitStream bsVehicle;
PlayerID playerid = pNetGame->GetRakServer()->GetPlayerIDFromIndex(m_bytePlayerID);
bsVehicle.Write(m_bytePlayerID);
bsVehicle.Write(byteVehicleID);
pNetGame->GetRakServer()->RPC("ExitVehicle",&bsVehicle,HIGH_PRIORITY,RELIABLE_ORDERED,
0,playerid,TRUE,FALSE);
}
//---------------------------------------------------- | [
"jacks.mini.net@43d76e2e-6035-11de-a55d-e76e375ae706"
]
| [
[
[
1,
328
]
]
]
|
6024d44ccbe3f652af361a5fc3c63df82ecfc402 | 65da00cc6f20a83dd89098bb22f8f93c2ff7419b | /HabuGraphics/Library/Include/Scene.hpp | 77487d2be24c3c362c5fa4dd2987ba20bb39586a | []
| no_license | skevy/CSC-350-Assignment-5 | 8b7c42257972d71e3d0cd3e9566e88a1fdcce73c | 8091a56694f4b5b8de7e278b64448d4f491aaef5 | refs/heads/master | 2021-01-23T11:49:35.653361 | 2011-04-20T02:20:06 | 2011-04-20T02:20:06 | 1,638,578 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,423 | hpp | //***************************************************************************//
// Scene Class Interface
//
// Created Sept 4, 2005
// By: Jeremy M Miller
//
// Copyright (c) 2005-2010 Jeremy M Miller. All rights reserved.
// This source code module, and all information, data, and algorithms
// associated with it, are part of BlueHabu technology (tm).
//
// Usage of HabuGraphics is subject to the appropriate license agreement.
// A proprietary/commercial licenses are available.
//
// HabuGraphics 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.
//
// HabuGraphics 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 HabuGraphics. If not, see <http://www.gnu.org/licenses/>.
//***************************************************************************//
#ifndef HABU_GRAPHICS_SCENE_HPP
#define HABU_GRAPHICS_SCENE_HPP
//***************************************************************************//
// System Includes
#include <fstream>
#include <vector>
//***************************************************************************//
//***************************************************************************//
namespace HabuTech
{
class GeometryBuffer
{
const class Graphics* mpGraphics;
unsigned int muiVertexBufferID;
unsigned int muiIndexBufferID;
unsigned long mulVertexFreeElements;
unsigned long mulIndexFreeElements;
unsigned int muiMaxVertexSize;
unsigned int muiMaxIndexSize;
void Create(const class Graphics* const pGraphics);
void Clone(const GeometryBuffer& rSource);
void Destroy();
public:
GeometryBuffer(const class Graphics* const pGraphics);
GeometryBuffer(const GeometryBuffer& rSource);
~GeometryBuffer();
unsigned long _cdecl VertexFreeElements() const;
unsigned long _cdecl IndexFreeElements() const;
unsigned long _cdecl MaxVertexElements() const;
unsigned long _cdecl MaxIndexElements() const;
unsigned long _cdecl UsedVertexElements() const;
unsigned long _cdecl UsedIndexElements() const;
unsigned long _cdecl Allocate(const class Vertex* const pVerticies, unsigned long ulVerticiesLength, const unsigned long* const pIndicies, unsigned long ulIndiciesLength);
void _cdecl Bind();
void _cdecl UnBind();
};
//*************************************************************************//
class Scene
{
private:
//***********************************************************************//
std::string mstrSceneName;
class Graphics* mpGraphics;
std::vector<class Mesh*> mvMeshes;
std::vector<class Light*> mvLights;
std::vector<class Camera*> mvCameras;
std::vector<class Material*> mvMaterials;
std::vector<class Texture*> mvTextures;
std::vector<class GeometryBuffer*> mvGeometryBuffers;
class Camera* mpActiveCamera;
//***********************************************************************//
public:
//***********************************************************************//
//-----------------------------------------------------------------------//
Scene(class Graphics* const pGraphics);
~Scene();
//-----------------------------------------------------------------------//
//-----------------------------------------------------------------------//
bool Load(std::ifstream& ifs);
//-----------------------------------------------------------------------//
//-----------------------------------------------------------------------//
void Render();
//-----------------------------------------------------------------------//
//-----------------------------------------------------------------------//
bool SetupCamera();
bool SetupLight();
//-----------------------------------------------------------------------//
//-----------------------------------------------------------------------//
class Mesh* const CreateMesh(const std::string& rstrName);
Mesh* const CloneMesh(const std::string& rstrSourceName, const std::string& rstrDestinationName);
void DestroyMesh(const std::string& rstrName);
void DestroyMesh(class Mesh** ppMesh);
class Mesh* const GetMesh(const std::string& rstrName);
//-----------------------------------------------------------------------//
//-----------------------------------------------------------------------//
class Camera* const CreateCamera(const std::string& rstrName);
void DestroyCamera(const std::string& rstrName);
void DestroyCamera(class Camera** ppCamera);
class Camera* const GetCamera(const std::string& rstrName);
class Camera* const GetActiveCamera();
//-----------------------------------------------------------------------//
//-----------------------------------------------------------------------//
class Light* const CreateLight( const std::string& rstrName, enum LightID eLightID);
void DestroyLight(const std::string& rstrName);
void DestroyLight(class Light** ppLight);
class Light* const GetLight(const std::string& rstrName);
//-----------------------------------------------------------------------//
class Material* const GetMaterial(const std::string& rstrName);
class Texture* const GetTexture(const std::string& rstrName);
//-----------------------------------------------------------------------//
class Graphics* const GetGraphics() const { return mpGraphics; }
//-----------------------------------------------------------------------//
//***********************************************************************//
}; // End of class Scene
//*************************************************************************//
} // End of namespace HabuTech
//***************************************************************************//
#endif HABU_GRAPHICS_SCENE_HPP | [
"[email protected]"
]
| [
[
[
1,
149
]
]
]
|
b89f00b63b59d5dde0ed7f7ce4bfcff020704214 | 58496be10ead81e2531e995f7d66017ffdfc6897 | /Include/Thread.h | 11ec983bdb26b091f3d34673d6261e6b07c23755 | []
| no_license | Diego160289/cross-fw | ba36fc6c3e3402b2fff940342315596e0365d9dd | 532286667b0fd05c9b7f990945f42279bac74543 | refs/heads/master | 2021-01-10T19:23:43.622578 | 2011-01-09T14:54:12 | 2011-01-09T14:54:12 | 38,457,864 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 763 | h | //============================================================================
// Date : 22.12.2010
// Author : Tkachenko Dmitry
// Copyright : (c) Tkachenko Dmitry ([email protected])
//============================================================================
#ifndef __THREAD_H__
#define __THREAD_H__
#include "NoCopyable.h"
#include "SimpleIFaces.h"
#include "Pointers.h"
#include "Exceptions.h"
namespace System
{
DECLARE_RUNTIME_EXCEPTION(Thread)
class Thread
: private Common::NoCopyable
{
public:
Thread(Common::ICallbackPtr callback);
~Thread();
private:
Common::ICallbackPtr Callback;
class ThreadImpl;
ThreadImpl *Impl;
};
}
#endif // !__THREAD_H__
| [
"TkachenkoDmitryV@d548627a-540d-11de-936b-e9512c4d2277"
]
| [
[
[
1,
34
]
]
]
|
f31d7b84c0b868b4b0bae5b8f1e4a43491d7c56c | d37a1d5e50105d82427e8bf3642ba6f3e56e06b8 | /DVR/HaohanITPlayer/public/Common/SysUtils/AutoCOMInit.h | 2bcfcbed7822686cd89e8232879f91382a3cfe4a | []
| no_license | 080278/dvrmd-filter | 176f4406dbb437fb5e67159b6cdce8c0f48fe0ca | b9461f3bf4a07b4c16e337e9c1d5683193498227 | refs/heads/master | 2016-09-10T21:14:44.669128 | 2011-10-17T09:18:09 | 2011-10-17T09:18:09 | 32,274,136 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 791 | h | //-----------------------------------------------------------------------------
// AutoCOMInit.h
// Copyright (c) 2003 - 2004, Haohanit. All rights reserved.
//-----------------------------------------------------------------------------
#if !defined(_AutoCOMInit_h_)
#define _AutoCOMInit_h_
//
// Use this class as an automatic and exception-safe mechanism for calling ::CoInitialize() and ::CoUninitialize(). See
// usage in most of the progress dialogs.
//
class AutoCOMInit
{
public:
explicit AutoCOMInit(bool inIsThread = true);
~AutoCOMInit();
private:
const bool mIsThread;
AutoCOMInit(const AutoCOMInit&); // No copying allowed
const AutoCOMInit& operator=(const AutoCOMInit&); // No assignment allowed
};
#endif // !defined(_AutoCOMInit_h_)
| [
"[email protected]@27769579-7047-b306-4d6f-d36f87483bb3"
]
| [
[
[
1,
26
]
]
]
|
877dc5bccab9c71a04a62dfd53394b5ece64aec1 | 1b3a26845c00ede008ea66d26f370c3542641f45 | /pymfclib/pymcom.h | 57b9ecf354e62575a5538566e20879a669e8a78e | []
| no_license | atsuoishimoto/pymfc | 26617fac259ed0ffd685a038b47702db0bdccd5f | 1341ef3be6ca85ea1fa284689edbba1ac29c72cb | refs/heads/master | 2021-01-01T05:50:51.613190 | 2010-12-29T07:38:01 | 2010-12-29T07:38:01 | 33,760,622 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,708 | h | // Copyright (c) 2001- Atsuo Ishimoto
// See LICENSE for details.
#ifndef PYMCOM_H
#define PYMCOM_H
#include "pymwin32funcs.h"
template <class T, class T_INTERFACE, REFIID T_IID=__uuidof(T_INTERFACE)>
class PyMFC_COMRef {
public:
struct TypeInstance {
PyObject_HEAD
T_INTERFACE *obj;
};
template <class DEFTYPE>
static void initBaseMethods(DEFTYPE &def) {
def.addObjArgMethod("queryInterface", queryInterface);
def.addObjArgMethod("queryFrom", queryFrom);
def.addKwdArgMethod("createInstance", createInstance);
def.addMethod("detach", detach);
def.addMethod("addRef", addRef);
def.addMethod("release", release);
def.addGetSet("ptr", getPtr, NULL);
}
static void checkObj(TypeInstance *obj) {
if (!obj->obj) {
throw PyDTExc_InvalidValue("COM object not specified");
}
}
static int initComObject(TypeInstance *obj, PyObject *args, PyObject *kwds) {
PyMFC_PROLOGUE("PyMFC_COMRef::initComObject");
PyDTObject ptrObj;
static char *kwlist[] = {"ptr", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwds,
"|O", kwlist, ptrObj.getBuf())) {
return -1;
}
if (ptrObj.get()) {
obj->obj = (T_INTERFACE*)PyMFCPtr::asPtr(ptrObj.get());
}
else {
obj->obj = NULL;
}
return 0;
PyMFC_EPILOGUE(-1);
}
static int onInitObj(TypeInstance *obj, PyObject *args, PyObject *kwds) {
PyMFC_PROLOGUE("PyMFC_COMRef::onInitObj");
obj->obj = NULL;
PyDTSequence seq(args, false);
PyDTDict dict(kwds, false);
if (seq.getSize() == 1 && dict.isNull()) {
obj->obj = (T_INTERFACE*)PyMFCPtr::asPtr(seq.getItem(0).get());
return 0;
}
else if (seq.getSize() == 0 && !dict.isNull() && dict.getSize() == 1) {
PyDTObject ptr(dict.getItem("ptr"));
if (!ptr.isNull()) {
obj->obj = (T_INTERFACE*)PyMFCPtr::asPtr(seq.getItem(0).get());
return 0;
}
}
else if (seq.getSize() == 0 || dict.getSize() == 0) {
return 0;
}
return T::initComObject(obj, args, kwds);
PyMFC_EPILOGUE(-1);
}
static int commonInitObj(TypeInstance *obj, PyObject *args, PyObject *kwds) {
PyMFC_PROLOGUE("PyMFC_COMRef::commonInitObj");
obj->obj = NULL;
PyDTObject ptrObj;
static char *kwlist[] = {"ptr", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwds,
"|O", kwlist, ptrObj.getBuf())) {
return -1;
}
if (ptrObj.get()) {
obj->obj = (T_INTERFACE*)PyMFCPtr_AsVoidPtr(ptrObj.get());
}
else {
obj->obj = NULL;
}
return 0;
PyMFC_EPILOGUE(-1);
}
static void onDeallocObj(TypeInstance *obj) {
clear(obj);
}
static int clear(TypeInstance *obj) {
if (obj->obj) {
obj->obj->Release();
obj->obj = NULL;
}
return 0;
}
static PyObject *getIID(TypeInstance *obj) {
PyMFC_PROLOGUE("PyMFC_COMRef::getIID");
return PyDTString((const char *)&(T_IID), sizeof(IID)).detach();
PyMFC_EPILOGUE(NULL);
}
static PyObject *getPtr(TypeInstance *obj, void *) {
PyMFC_PROLOGUE("PyMFC_COMRef::getPtr");
return PyMFCPtr(obj->obj).detach();
PyMFC_EPILOGUE(NULL);
}
static PyObject *createInstance(TypeInstance *obj, PyObject *args, PyObject *kwds) {
PyMFC_PROLOGUE("PyMFC_COMRef::createInstance");
static char *kwlist[] = {"clsid", "unkouter", "inproc", "local", NULL};
PyDTString clsidObj;
PyDTObject unkouterObj;
int inproc=0;
int local=0;
if (!PyArg_ParseTupleAndKeywords(args, kwds,
"O|Oii", kwlist, clsidObj.getBuf(), unkouterObj.getBuf(), &inproc, &local)) {
return NULL;
}
CLSID *clsid = (CLSID*)clsidObj.asString();
IUnknown *outer = NULL;
if (unkouterObj.get()) {
outer = (IUnknown *)outer;
}
CLSCTX ctx = CLSCTX_INPROC_SERVER;
if (local) {
ctx = CLSCTX_LOCAL_SERVER;
}
LPVOID ppv;
HRESULT hr = CoCreateInstance(*clsid, outer, ctx, T_IID, &ppv);
if (FAILED(hr)) {
throw PyMFC_WIN32ERRCODE(hr);
}
clear(obj);
obj->obj = (T_INTERFACE*)ppv;
PyMFC_RETNONE();
PyMFC_EPILOGUE(NULL);
}
static PyObject *detach(TypeInstance *obj) {
PyMFC_PROLOGUE("PyMFC_COMRef::detach");
PyDTObject ret = PyMFCPtr(obj->obj);
obj->obj = NULL;
return ret.detach();
PyMFC_EPILOGUE(NULL);
}
static PyObject *queryInterface(TypeInstance *obj, PyObject *arg) {
PyMFC_PROLOGUE("PyMFC_COMRef::queryInterface");
checkObj(obj);
PyDTString iidObj(arg, false);
IID *iid = (IID*)iidObj.asString();
void *p;
HRESULT hr = obj->obj->QueryInterface(*iid, &p);
if (FAILED(hr)) {
throw PyMFC_WIN32ERRCODE(hr);
}
return PyMFCPtr(p).detach();
PyMFC_EPILOGUE(NULL);
}
static PyObject *queryFrom(TypeInstance *obj, PyObject *arg) {
PyMFC_PROLOGUE("PyMFC_COMRef::queryFrom");
PyDTObject unk(arg, false);
void *p;
if (unk.isInt() || unk.isLong()) {
HRESULT hr = static_cast<IUnknown *>(PyMFCPtr::asPtr(unk.get()))->QueryInterface(T_IID, &p);
if (FAILED(hr)) {
throw PyMFC_WIN32ERRCODE(hr);
}
}
else {
PyDTString iid(getIID(obj), true);
p = PyMFCPtr::asPtr(unk.callMethod("queryInterface", "O", iid.get()).get());
}
clear(obj);
obj->obj = (T_INTERFACE*)p;
PyMFC_RETNONE();
PyMFC_EPILOGUE(NULL);
}
static PyObject *addRef(TypeInstance *obj) {
PyMFC_PROLOGUE("PyMFC_COMRef::addRef");
checkObj(obj);
ULONG ret = obj->obj->AddRef();
return PyDTInt(ret).detach();
PyMFC_EPILOGUE(NULL);
}
static PyObject *release(TypeInstance *obj) {
PyMFC_PROLOGUE("PyMFC_COMRef::release");
checkObj(obj);
obj->obj->Release();
obj->obj = NULL;
PyMFC_RETNONE();
PyMFC_EPILOGUE(NULL);
}
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
243
]
]
]
|
0453d7a44a543d54b7ebbbf184e180f1efaf4d0c | 6ee200c9dba87a5d622c2bd525b50680e92b8dab | /Walkyrie Dx9/Valkyrie/Moteur/Lumiere.cpp | 81948beb989ba12b7df280c5cae443b069fe4843 | []
| no_license | Ishoa/bizon | 4dbcbbe94d1b380f213115251e1caac5e3139f4d | d7820563ab6831d19e973a9ded259d9649e20e27 | refs/heads/master | 2016-09-05T11:44:00.831438 | 2010-03-10T23:14:22 | 2010-03-10T23:14:22 | 32,632,823 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 3,646 | cpp | #include "Lumiere.h"
CLumiere::CLumiere()
{
ZeroMemory(&m_Lumiere, sizeof(D3DLIGHT9));
D3DCOLORVALUE Couleur = {1.0f, 1.0f, 1.0f, 1.0f};
m_Lumiere.Type = D3DLIGHT_DIRECTIONAL;
m_Lumiere.Ambient = Couleur;
m_Lumiere.Diffuse = Couleur;
m_Lumiere.Specular = Couleur;
m_Lumiere.Direction = D3DXVECTOR3(0.0f, -1.0f, 0.0f);
}
CLumiere::~CLumiere()
{
}
// Lumière Directionnelle
void CLumiere::SetDirectionnelle(D3DXVECTOR3* Direction)
{
m_Lumiere.Type = D3DLIGHT_DIRECTIONAL;
D3DXVec3Normalize((D3DXVECTOR3*)&m_Lumiere.Direction, Direction);
m_Lumiere.Position = D3DXVECTOR3(0.0f, 0.0f, 0.0f);
}
// Lumière Ponctuelle
void CLumiere::SetPonctuelle(D3DXVECTOR3* Position, float Range, float Attenuation0, float Attenuation1, float Attenuation2)
{
m_Lumiere.Type = D3DLIGHT_POINT;
m_Lumiere.Position = *Position;
m_Lumiere.Range = Range;
m_Lumiere.Attenuation0 = Attenuation0;
m_Lumiere.Attenuation1 = Attenuation1;
m_Lumiere.Attenuation2 = Attenuation2;
}
// Spot lumineux
void CLumiere::SetSpot(D3DXVECTOR3* Position, D3DXVECTOR3* Direction, float Range, float ConeInterieur, float ConeExterieur, float Attenuation0, float Attenuation1, float Attenuation2, float Facteur)
{
m_Lumiere.Type = D3DLIGHT_SPOT;
m_Lumiere.Position = *Position;
D3DXVec3Normalize((D3DXVECTOR3*)&m_Lumiere.Direction, Direction);
m_Lumiere.Range = Range;
m_Lumiere.Phi = ConeInterieur;
m_Lumiere.Theta = ConeExterieur;
m_Lumiere.Attenuation0 = Attenuation0;
m_Lumiere.Attenuation1 = Attenuation1;
m_Lumiere.Attenuation2 = Attenuation2;
m_Lumiere.Falloff = Facteur;
}
void CLumiere::SetAmbiante(D3DCOLOR Couleur)
{
m_Lumiere.Ambient.r = D3DCOLOR_R(Couleur) / 255.0f;
m_Lumiere.Ambient.g = D3DCOLOR_G(Couleur) / 255.0f;
m_Lumiere.Ambient.b = D3DCOLOR_B(Couleur) / 255.0f;
m_Lumiere.Ambient.a = D3DCOLOR_A(Couleur) / 255.0f;
}
void CLumiere::SetAmbiante(D3DCOLORVALUE* Couleur)
{
m_Lumiere.Ambient = *Couleur;
}
void CLumiere::SetAmbiante(float r, float g, float b, float a)
{
m_Lumiere.Ambient.r = r;
m_Lumiere.Ambient.g = g;
m_Lumiere.Ambient.b = b;
m_Lumiere.Ambient.a = a;
}
void CLumiere::SetDiffuse(D3DCOLOR Couleur)
{
m_Lumiere.Diffuse.r = D3DCOLOR_R(Couleur) / 255.0f;
m_Lumiere.Diffuse.g = D3DCOLOR_G(Couleur) / 255.0f;
m_Lumiere.Diffuse.b = D3DCOLOR_B(Couleur) / 255.0f;
m_Lumiere.Diffuse.a = D3DCOLOR_A(Couleur) / 255.0f;
}
void CLumiere::SetDiffuse(D3DCOLORVALUE* Couleur)
{
m_Lumiere.Diffuse = *Couleur;
}
void CLumiere::SetDiffuse(float r, float g, float b, float a)
{
m_Lumiere.Diffuse.r = r;
m_Lumiere.Diffuse.g = g;
m_Lumiere.Diffuse.b = b;
m_Lumiere.Diffuse.a = a;
}
void CLumiere::SetAmbianteDiffuse(D3DCOLOR Couleur)
{
SetDiffuse(Couleur);
SetAmbiante(Couleur);
}
void CLumiere::SetAmbianteDiffuse(D3DCOLORVALUE* Couleur)
{
SetDiffuse(Couleur);
SetAmbiante(Couleur);
}
void CLumiere::SetAmbianteDiffuse(float r, float g, float b, float a)
{
SetDiffuse(r, g, b, a);
SetAmbiante(r, g, b, a);
}
void CLumiere::SetSpeculaire(D3DCOLOR Couleur)
{
m_Lumiere.Specular.r = D3DCOLOR_R(Couleur) / 255.0f;
m_Lumiere.Specular.g = D3DCOLOR_G(Couleur) / 255.0f;
m_Lumiere.Specular.b = D3DCOLOR_B(Couleur) / 255.0f;
m_Lumiere.Specular.a = D3DCOLOR_A(Couleur) / 255.0f;
}
void CLumiere::SetSpeculaire(D3DCOLORVALUE* Couleur)
{
m_Lumiere.Specular = *Couleur;
}
void CLumiere::SetSpeculaire(float r, float g, float b, float a)
{
m_Lumiere.Specular.r = r;
m_Lumiere.Specular.g = g;
m_Lumiere.Specular.b = b;
m_Lumiere.Specular.a = a;
}
| [
"Colas.Vincent@ab19582e-f48f-11de-8f43-4547254af6c6"
]
| [
[
[
1,
131
]
]
]
|
338797cae73e90471704bb188d2d8c1748f3a933 | fbe2cbeb947664ba278ba30ce713810676a2c412 | /iptv_root/iptv_media3/test_audio_encoder/Capture.cpp | 4dc4abb1377cfe70eb32151fabf8fd94f29d33e9 | []
| no_license | abhipr1/multitv | 0b3b863bfb61b83c30053b15688b070d4149ca0b | 6a93bf9122ddbcc1971dead3ab3be8faea5e53d8 | refs/heads/master | 2020-12-24T15:13:44.511555 | 2009-06-04T17:11:02 | 2009-06-04T17:11:02 | 41,107,043 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,232 | cpp | #include "compat.h"
#include "AudioCapture.h"
#include "AudioEncoder.h"
#include "log.h"
#include "global_error.h"
extern AudioEncoder *g_pAudioEncoder;
extern unsigned g_captureFmt;
#define BUF_LEN_MS 500
unsigned CaptureAudio(CAudioCapDevice *_pAudioCapDevice);
unsigned InitCapture()
{
CAudioCapture audioCapture;
std::deque<std::string> enumDevList;
audioCapture.EnumDevices(enumDevList);
for (unsigned index=0; index < enumDevList.size(); index++)
g_FileLog.SetLog(enumDevList[index].c_str());
unsigned devPos = 0;
CAudioCapDevice *pAudioCapDevice;
do
{
audioCapture.GetDevice(enumDevList[devPos],
(sampleFmt)g_captureFmt,
g_pAudioEncoder->GetSampleRate(),
BUF_LEN_MS,
&pAudioCapDevice);
devPos++;
} while( !pAudioCapDevice->DeviceOK() && (devPos < enumDevList.size()) );
if (!pAudioCapDevice->DeviceOK())
{
g_FileLog.SetLog("Could not find audio device!");
return RET_ERROR;
}
else
CaptureAudio(pAudioCapDevice);
return RET_OK;
} | [
"heineck@c016ff2c-3db2-11de-a81c-fde7d73ceb89"
]
| [
[
[
1,
47
]
]
]
|
a81e997ace7edda571fedda206dcad809090da31 | 0b66a94448cb545504692eafa3a32f435cdf92fa | /tags/0.6/cbear.berlios.de/windows/usb/device.hpp | db6947ee81039371c48c5e3901510ceaf989b8a4 | [
"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 | 3,123 | hpp | /*
The MIT License
Copyright (c) 2005 C Bear (http://cbear.berlios.de)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef CBEAR_BERLIOS_DE_WINDOWS_USB_DEVICE_HPP_INCLUDED
#define CBEAR_BERLIOS_DE_WINDOWS_USB_DEVICE_HPP_INCLUDED
#include <cbear.berlios.de/windows/dynamic.hpp>
extern "C"
{
#include <usbioctl.h>
}
namespace cbear_berlios_de
{
namespace windows
{
namespace usb
{
inline const com::uuid &device_uuid()
{
static const com::uuid Result(
0xA5DCBF10L,
0x6530,
0x11D2,
0x90,
0x1F,
0x00,
0xC0,
0x4F,
0xB9,
0x51,
0xED);
return Result;
}
inline const com::uuid &hub_uuid()
{
static const com::uuid Result(
0xf18a0e88,
0xc30c,
0x11d0,
0x88,
0x15,
0x00,
0xa0,
0xc9,
0x06,
0xbe,
0xd8);
return Result;
}
inline const com::uuid &host_controller_uuid()
{
static const com::uuid Result(
0x3abf6f2d,
0x71c4,
0x462a,
0x8a,
0x92,
0x1e,
0x68,
0x61,
0xe6,
0xaf,
0x27);
return Result;
}
typedef ::USB_NODE_INFORMATION node_information;
typedef ::USB_NODE_CONNECTION_INFORMATION node_connection_information;
typedef ioctl::const_<IOCTL_USB_GET_NODE_INFORMATION> get_node_information;
typedef ioctl::const_<IOCTL_USB_GET_NODE_CONNECTION_INFORMATION>
get_node_connection_information;
typedef ioctl::const_<IOCTL_USB_GET_NODE_CONNECTION_DRIVERKEY_NAME>
get_node_connection_driverkey_name;
class node_connection_driverkey_name:
public dynamic< ::USB_NODE_CONNECTION_DRIVERKEY_NAME>
{
public:
typedef dynamic< ::USB_NODE_CONNECTION_DRIVERKEY_NAME> wrap;
range::iterator_range<wchar_t *> DriverKeyName()
{
static const int remainder_size =
sizeof(internal_type) - sizeof(this->internal().DriverKeyName);
// Ask Microsoft about this constant.
static const int magic_size_correction = - 1;
return range::iterator_range<wchar_t *>(
this->internal().DriverKeyName,
(this->wrap::size() - remainder_size) / sizeof(wchar_t) -
1 + magic_size_correction);
}
};
}
}
}
#endif
| [
"sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838"
]
| [
[
[
1,
127
]
]
]
|
e25609933e07b1d482d8910e0abc3cf787ec3419 | b2d46af9c6152323ce240374afc998c1574db71f | /cursovideojuegos/theflostiproject/3rdParty/boost/libs/optional/test/optional_test.cpp | 258ddff144400eb332f0b51e6c4c9af66f84ba7f | []
| no_license | bugbit/cipsaoscar | 601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4 | 52aa8b4b67d48f59e46cb43527480f8b3552e96d | refs/heads/master | 2021-01-10T21:31:18.653163 | 2011-09-28T16:39:12 | 2011-09-28T16:39:12 | 33,032,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,829 | cpp | // Copyright (C) 2003, Fernando Luis Cacciola Carballal.
//
// Use, modification, and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/lib/optional for documentation.
//
// You are welcome to contact the author at:
// [email protected]
//
#include<iostream>
#include<stdexcept>
#include<string>
#define BOOST_ENABLE_ASSERT_HANDLER
#include "boost/optional.hpp"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#include "boost/none.hpp"
#include "boost/test/minimal.hpp"
#include "optional_test_common.cpp"
void test_implicit_construction ( optional<double> opt, double v, double z )
{
check_value(opt,v,z);
}
void test_implicit_construction ( optional<X> opt, X const& v, X const& z )
{
check_value(opt,v,z);
}
void test_default_implicit_construction ( double, optional<double> opt )
{
BOOST_CHECK(!opt);
}
void test_default_implicit_construction ( X const&, optional<X> opt )
{
BOOST_CHECK(!opt);
}
//
// Basic test.
// Check ordinary functionality:
// Initialization, assignment, comparison and value-accessing.
//
template<class T>
void test_basics( T const* )
{
TRACE( std::endl << BOOST_CURRENT_FUNCTION );
T z(0);
T a(1);
// Default construction.
// 'def' state is Uninitialized.
// T::T() is not called (and it is not even defined)
optional<T> def ;
check_uninitialized(def);
// Implicit construction
// The first parameter is implicitely converted to optional<T>(a);
test_implicit_construction(a,a,z);
// Direct initialization.
// 'oa' state is Initialized with 'a'
// T::T( T const& x ) is used.
set_pending_copy( ARG(T) ) ;
optional<T> oa ( a ) ;
check_is_not_pending_copy( ARG(T) );
check_initialized(oa);
check_value(oa,a,z);
T b(2);
optional<T> ob ;
// Value-Assignment upon Uninitialized optional.
// T::T ( T const& x ) is used.
set_pending_copy( ARG(T) ) ;
ob = a ;
check_is_not_pending_copy( ARG(T) ) ;
check_initialized(ob);
check_value(ob,a,z);
// Value-Assignment upon Initialized optional.
// T::T ( T const& x ) is used
set_pending_dtor( ARG(T) ) ;
set_pending_copy( ARG(T) ) ;
ob = b ;
check_is_not_pending_dtor( ARG(T) ) ;
check_is_not_pending_copy( ARG(T) ) ;
check_initialized(ob);
check_value(ob,b,z);
// Assignment initialization.
// T::T ( T const& x ) is used to copy new value.
set_pending_copy( ARG(T) ) ;
optional<T> const oa2 ( oa ) ;
check_is_not_pending_copy( ARG(T) ) ;
check_initialized_const(oa2);
check_value_const(oa2,a,z);
// Assignment
// T::~T() is used to destroy previous value in ob.
// T::T ( T const& x ) is used to copy new value.
set_pending_dtor( ARG(T) ) ;
set_pending_copy( ARG(T) ) ;
oa = ob ;
check_is_not_pending_dtor( ARG(T) ) ;
check_is_not_pending_copy( ARG(T) ) ;
check_initialized(oa);
check_value(oa,b,z);
// Uninitializing Assignment upon Initialized Optional
// T::~T() is used to destroy previous value in oa.
set_pending_dtor( ARG(T) ) ;
set_pending_copy( ARG(T) ) ;
oa = def ;
check_is_not_pending_dtor( ARG(T) ) ;
check_is_pending_copy ( ARG(T) ) ;
check_uninitialized(oa);
// Uninitializing Assignment upon Uninitialized Optional
// (Dtor is not called this time)
set_pending_dtor( ARG(T) ) ;
set_pending_copy( ARG(T) ) ;
oa = def ;
check_is_pending_dtor( ARG(T) ) ;
check_is_pending_copy( ARG(T) ) ;
check_uninitialized(oa);
// Deinitialization of Initialized Optional
// T::~T() is used to destroy previous value in ob.
set_pending_dtor( ARG(T) ) ;
ob.reset();
check_is_not_pending_dtor( ARG(T) ) ;
check_uninitialized(ob);
// Deinitialization of Uninitialized Optional
// (Dtor is not called this time)
set_pending_dtor( ARG(T) ) ;
ob.reset();
check_is_pending_dtor( ARG(T) ) ;
check_uninitialized(ob);
}
//
// Test Direct Value Manipulation
//
template<class T>
void test_direct_value_manip( T const* )
{
TRACE( std::endl << BOOST_CURRENT_FUNCTION );
T x(3);
optional<T> const c_opt0(x) ;
optional<T> opt0(x);
BOOST_CHECK( c_opt0.get().V() == x.V() ) ;
BOOST_CHECK( opt0.get().V() == x.V() ) ;
BOOST_CHECK( c_opt0->V() == x.V() ) ;
BOOST_CHECK( opt0->V() == x.V() ) ;
BOOST_CHECK( (*c_opt0).V() == x.V() ) ;
BOOST_CHECK( (* opt0).V() == x.V() ) ;
T y(4);
opt0 = y ;
BOOST_CHECK( get(opt0).V() == y.V() ) ;
}
//
// Test Uninitialized access assert
//
template<class T>
void test_uninitialized_access( T const* )
{
TRACE( std::endl << BOOST_CURRENT_FUNCTION );
optional<T> def ;
bool passed = false ;
try
{
// This should throw because 'def' is uninitialized
T const& n = def.get() ;
unused_variable(n);
passed = true ;
}
catch (...) {}
BOOST_CHECK(!passed);
passed = false ;
try
{
// This should throw because 'def' is uninitialized
T const& n = *def ;
unused_variable(n);
passed = true ;
}
catch (...) {}
BOOST_CHECK(!passed);
passed = false ;
try
{
T v(5) ;
unused_variable(v);
// This should throw because 'def' is uninitialized
*def = v ;
passed = true ;
}
catch (...) {}
BOOST_CHECK(!passed);
passed = false ;
try
{
// This should throw because 'def' is uninitialized
T v = *(def.operator->()) ;
unused_variable(v);
passed = true ;
}
catch (...) {}
BOOST_CHECK(!passed);
}
#if BOOST_WORKAROUND( BOOST_INTEL_CXX_VERSION, <= 700) // Intel C++ 7.0
void prevent_buggy_optimization( bool v ) {}
#endif
//
// Test Direct Initialization of optional for a T with throwing copy-ctor.
//
template<class T>
void test_throwing_direct_init( T const* )
{
TRACE( std::endl << BOOST_CURRENT_FUNCTION );
T a(6);
int count = get_instance_count( ARG(T) ) ;
set_throw_on_copy( ARG(T) ) ;
bool passed = false ;
try
{
// This should:
// Attempt to copy construct 'a' and throw.
// 'opt' won't be constructed.
set_pending_copy( ARG(T) ) ;
#if BOOST_WORKAROUND( BOOST_INTEL_CXX_VERSION, <= 700) // Intel C++ 7.0
// Intel C++ 7.0 specific:
// For some reason, when "check_is_not_pending_copy",
// after the exception block is reached,
// X::pending_copy==true even though X's copy ctor set it to false.
// I guessed there is some sort of optimization bug,
// and it seems to be the since the following additional line just
// solves the problem (!?)
prevent_buggy_optimization(X::pending_copy);
#endif
optional<T> opt(a) ;
passed = true ;
}
catch ( ... ){}
BOOST_CHECK(!passed);
check_is_not_pending_copy( ARG(T) );
check_instance_count(count, ARG(T) );
}
//
// Test Value Assignment to an Uninitialized optional for a T with a throwing copy-ctor
//
template<class T>
void test_throwing_val_assign_on_uninitialized( T const* )
{
TRACE( std::endl << BOOST_CURRENT_FUNCTION );
T a(7);
int count = get_instance_count( ARG(T) ) ;
set_throw_on_copy( ARG(T) ) ;
optional<T> opt ;
bool passed = false ;
try
{
// This should:
// Attempt to copy construct 'a' and throw.
// opt should be left uninitialized.
set_pending_copy( ARG(T) ) ;
opt.reset( a );
passed = true ;
}
catch ( ... ) {}
BOOST_CHECK(!passed);
check_is_not_pending_copy( ARG(T) );
check_instance_count(count, ARG(T) );
check_uninitialized(opt);
}
//
// Test Value Reset on an Initialized optional for a T with a throwing copy-ctor
//
template<class T>
void test_throwing_val_assign_on_initialized( T const* )
{
TRACE( std::endl << BOOST_CURRENT_FUNCTION );
T z(0);
T a(8);
T b(9);
int count = get_instance_count( ARG(T) ) ;
reset_throw_on_copy( ARG(T) ) ;
optional<T> opt ( b ) ;
++ count ;
check_instance_count(count, ARG(T) );
check_value(opt,b,z);
set_throw_on_copy( ARG(T) ) ;
bool passed = false ;
try
{
// This should:
// Attempt to copy construct 'a' and throw.
// opt should be left uninitialized (even though it was initialized)
set_pending_dtor( ARG(T) ) ;
set_pending_copy( ARG(T) ) ;
opt.reset ( a ) ;
passed = true ;
}
catch ( ... ) {}
BOOST_CHECK(!passed);
-- count ;
check_is_not_pending_dtor( ARG(T) );
check_is_not_pending_copy( ARG(T) );
check_instance_count(count, ARG(T) );
check_uninitialized(opt);
}
//
// Test Copy Initialization from an Initialized optional for a T with a throwing copy-ctor
//
template<class T>
void test_throwing_copy_initialization( T const* )
{
TRACE( std::endl << BOOST_CURRENT_FUNCTION );
T z(0);
T a(10);
reset_throw_on_copy( ARG(T) ) ;
optional<T> opt (a);
int count = get_instance_count( ARG(T) ) ;
set_throw_on_copy( ARG(T) ) ;
bool passed = false ;
try
{
// This should:
// Attempt to copy construct 'opt' and throw.
// opt1 won't be constructed.
set_pending_copy( ARG(T) ) ;
optional<T> opt1 = opt ;
passed = true ;
}
catch ( ... ) {}
BOOST_CHECK(!passed);
check_is_not_pending_copy( ARG(T) );
check_instance_count(count, ARG(T) );
// Nothing should have happened to the source optional.
check_initialized(opt);
check_value(opt,a,z);
}
//
// Test Assignment to an Uninitialized optional from an Initialized optional
// for a T with a throwing copy-ctor
//
template<class T>
void test_throwing_assign_to_uninitialized( T const* )
{
TRACE( std::endl << BOOST_CURRENT_FUNCTION );
T z(0);
T a(11);
reset_throw_on_copy( ARG(T) ) ;
optional<T> opt0 ;
optional<T> opt1(a) ;
int count = get_instance_count( ARG(T) ) ;
set_throw_on_copy( ARG(T) ) ;
bool passed = false ;
try
{
// This should:
// Attempt to copy construct 'opt1.value()' into opt0 and throw.
// opt0 should be left uninitialized.
set_pending_copy( ARG(T) ) ;
opt0 = opt1 ;
passed = true ;
}
catch ( ... ) {}
BOOST_CHECK(!passed);
check_is_not_pending_copy( ARG(T) );
check_instance_count(count, ARG(T) );
check_uninitialized(opt0);
}
//
// Test Assignment to an Initialized optional from an Initialized optional
// for a T with a throwing copy-ctor
//
template<class T>
void test_throwing_assign_to_initialized( T const* )
{
TRACE( std::endl << BOOST_CURRENT_FUNCTION );
T z(0);
T a(12);
T b(13);
reset_throw_on_copy( ARG(T) ) ;
optional<T> opt0(a) ;
optional<T> opt1(b) ;
int count = get_instance_count( ARG(T) ) ;
set_throw_on_copy( ARG(T) ) ;
bool passed = false ;
try
{
// This should:
// Attempt to copy construct 'opt1.value()' into opt0 and throw.
// opt0 should be left unmodified or uninitialized
set_pending_dtor( ARG(T) ) ;
set_pending_copy( ARG(T) ) ;
opt0 = opt1 ;
passed = true ;
}
catch ( ... ) {}
BOOST_CHECK(!passed);
// opt0 was left uninitialized
-- count ;
check_is_not_pending_dtor( ARG(T) );
check_is_not_pending_copy( ARG(T) );
check_instance_count(count, ARG(T) );
check_uninitialized(opt0);
}
//
// Test swap in a no-throwing case
//
template<class T>
void test_no_throwing_swap( T const* )
{
TRACE( std::endl << BOOST_CURRENT_FUNCTION );
T z(0);
T a(14);
T b(15);
reset_throw_on_copy( ARG(T) ) ;
optional<T> def0 ;
optional<T> def1 ;
optional<T> opt0(a) ;
optional<T> opt1(b) ;
int count = get_instance_count( ARG(T) ) ;
swap(def0,def1);
check_uninitialized(def0);
check_uninitialized(def1);
swap(def0,opt0);
check_uninitialized(opt0);
check_initialized(def0);
check_value(def0,a,z);
// restore def0 and opt0
swap(def0,opt0);
swap(opt0,opt1);
check_instance_count(count, ARG(T) );
check_initialized(opt0);
check_initialized(opt1);
check_value(opt0,b,z);
check_value(opt1,a,z);
}
//
// Test swap in a throwing case
//
template<class T>
void test_throwing_swap( T const* )
{
TRACE( std::endl << BOOST_CURRENT_FUNCTION );
T a(16);
T b(17);
reset_throw_on_copy( ARG(T) ) ;
optional<T> opt0(a) ;
optional<T> opt1(b) ;
set_throw_on_copy( ARG(T) ) ;
//
// Case 1: Both Initialized.
//
bool passed = false ;
try
{
// This should attempt to swap optionals and fail at swap(X&,X&).
swap(opt0,opt1);
passed = true ;
}
catch ( ... ) {}
BOOST_CHECK(!passed);
// Assuming swap(T&,T&) has at least the basic guarantee, these should hold.
BOOST_CHECK( ( !opt0 || ( !!opt0 && ( ( *opt0 == a ) || ( *opt0 == b ) ) ) ) ) ;
BOOST_CHECK( ( !opt1 || ( !!opt1 && ( ( *opt1 == a ) || ( *opt1 == b ) ) ) ) ) ;
//
// Case 2: Only one Initialized.
//
reset_throw_on_copy( ARG(T) ) ;
opt0.reset();
opt1.reset(a);
set_throw_on_copy( ARG(T) ) ;
passed = false ;
try
{
// This should attempt to swap optionals and fail at opt0.reset(*opt1)
// opt0 should be left uninitialized and opt1 unchanged.
swap(opt0,opt1);
passed = true ;
}
catch ( ... ) {}
BOOST_CHECK(!passed);
check_uninitialized(opt0);
check_initialized(opt1);
check_value(opt1,a,b);
}
//
// This verifies relational operators.
//
template<class T>
void test_relops( T const* )
{
TRACE( std::endl << BOOST_CURRENT_FUNCTION );
reset_throw_on_copy( ARG(T) ) ;
T v0(18);
T v1(19);
T v2(19);
optional<T> def0 ;
optional<T> def1 ;
optional<T> opt0(v0);
optional<T> opt1(v1);
optional<T> opt2(v2);
// Check identity
BOOST_CHECK ( def0 == def0 ) ;
BOOST_CHECK ( opt0 == opt0 ) ;
BOOST_CHECK ( !(def0 != def0) ) ;
BOOST_CHECK ( !(opt0 != opt0) ) ;
// Check when both are uininitalized.
BOOST_CHECK ( def0 == def1 ) ; // both uninitialized compare equal
BOOST_CHECK ( !(def0 < def1) ) ; // uninitialized is never less than uninitialized
BOOST_CHECK ( !(def0 > def1) ) ; // uninitialized is never greater than uninitialized
BOOST_CHECK ( !(def0 != def1) ) ;
BOOST_CHECK ( def0 <= def1 ) ;
BOOST_CHECK ( def0 >= def1 ) ;
// Check when only lhs is uninitialized.
BOOST_CHECK ( def0 != opt0 ) ; // uninitialized is never equal to initialized
BOOST_CHECK ( !(def0 == opt0) ) ;
BOOST_CHECK ( def0 < opt0 ) ; // uninitialized is always less than initialized
BOOST_CHECK ( !(def0 > opt0) ) ;
BOOST_CHECK ( def0 <= opt0 ) ;
BOOST_CHECK ( !(def0 >= opt0) ) ;
// Check when only rhs is uninitialized.
BOOST_CHECK ( opt0 != def0 ) ; // initialized is never equal to uninitialized
BOOST_CHECK ( !(opt0 == def0) ) ;
BOOST_CHECK ( !(opt0 < def0) ) ; // initialized is never less than uninitialized
BOOST_CHECK ( opt0 > def0 ) ;
BOOST_CHECK ( !(opt0 <= def0) ) ;
BOOST_CHECK ( opt0 >= opt0 ) ;
// If both are initialized, values are compared
BOOST_CHECK ( opt0 != opt1 ) ;
BOOST_CHECK ( opt1 == opt2 ) ;
BOOST_CHECK ( opt0 < opt1 ) ;
BOOST_CHECK ( opt1 > opt0 ) ;
BOOST_CHECK ( opt1 <= opt2 ) ;
BOOST_CHECK ( opt1 >= opt0 ) ;
}
template<class T>
void test_none( T const* )
{
TRACE( std::endl << BOOST_CURRENT_FUNCTION );
using boost::none ;
optional<T> def0 ;
optional<T> def1(none) ;
optional<T> non_def( T(1234) ) ;
BOOST_CHECK ( def0 == none ) ;
BOOST_CHECK ( non_def != none ) ;
BOOST_CHECK ( !def1 ) ;
non_def = none ;
BOOST_CHECK ( !non_def ) ;
test_default_implicit_construction(T(1),none);
}
void test_with_builtin_types()
{
TRACE( std::endl << BOOST_CURRENT_FUNCTION );
test_basics( ARG(double) );
test_uninitialized_access( ARG(double) );
test_no_throwing_swap( ARG(double) );
test_relops( ARG(double) ) ;
test_none( ARG(double) ) ;
}
void test_with_class_type()
{
TRACE( std::endl << BOOST_CURRENT_FUNCTION );
test_basics( ARG(X) );
test_direct_value_manip( ARG(X) );
test_uninitialized_access( ARG(X) );
test_throwing_direct_init( ARG(X) );
test_throwing_val_assign_on_uninitialized( ARG(X) );
test_throwing_val_assign_on_initialized( ARG(X) );
test_throwing_copy_initialization( ARG(X) );
test_throwing_assign_to_uninitialized( ARG(X) );
test_throwing_assign_to_initialized( ARG(X) );
test_no_throwing_swap( ARG(X) );
test_throwing_swap( ARG(X) );
test_relops( ARG(X) ) ;
test_none( ARG(X) ) ;
BOOST_CHECK ( X::count == 0 ) ;
}
int eat ( bool ) { return 1 ; }
int eat ( char ) { return 1 ; }
int eat ( int ) { return 1 ; }
int eat ( void const* ) { return 1 ; }
template<class T> int eat ( T ) { return 0 ; }
//
// This verifies that operator safe_bool() behaves properly.
//
template<class T>
void test_no_implicit_conversions_impl( T const& )
{
TRACE( std::endl << BOOST_CURRENT_FUNCTION );
optional<T> def ;
BOOST_CHECK ( eat(def) == 0 ) ;
}
void test_no_implicit_conversions()
{
TRACE( std::endl << BOOST_CURRENT_FUNCTION );
bool b = false ;
char c = 0 ;
int i = 0 ;
void const* p = 0 ;
test_no_implicit_conversions_impl(b);
test_no_implicit_conversions_impl(c);
test_no_implicit_conversions_impl(i);
test_no_implicit_conversions_impl(p);
}
struct A {} ;
void test_conversions1()
{
TRACE( std::endl << BOOST_CURRENT_FUNCTION );
#ifndef BOOST_OPTIONAL_NO_CONVERTING_COPY_CTOR
char c = 20 ;
optional<char> opt0(c);
optional<int> opt1(opt0);
BOOST_CHECK(*opt1 == static_cast<int>(c));
#endif
#ifndef BOOST_OPTIONAL_NO_CONVERTING_ASSIGNMENT
float f = 21.22f ;
double d = f ;
optional<float> opt2(f) ;
optional<double> opt3 ;
opt3 = opt2 ;
BOOST_CHECK(*opt3 == d);
#endif
}
void test_conversions2()
{
TRACE( std::endl << BOOST_CURRENT_FUNCTION );
char c = 20 ;
optional<int> opt(c);
BOOST_CHECK( get(opt) == static_cast<int>(c));
float f = 21.22f ;
optional<double> opt1;
opt1 = f ;
BOOST_CHECK(*get(&opt1) == static_cast<double>(f));
}
int test_main( int, char* [] )
{
try
{
test_with_class_type();
test_with_builtin_types();
test_no_implicit_conversions();
test_conversions1();
test_conversions2();
}
catch ( ... )
{
BOOST_ERROR("Unexpected Exception caught!");
}
return 0;
}
| [
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
]
| [
[
[
1,
801
]
]
]
|
25fefc3b9b1578f9bb31a77b1f5b8bf7c1819ca9 | 361c35690ed6cd92b6d165174f577d690e1ba50a | /CODE/CUDAWinApp1/CUDAWinApp1/Escena.cpp | 37fbd230a740bfcea4d194bcc8db13434d63481a | []
| no_license | gonchimaster/compgrafgpu | 658ddbf767cebc999a99625c5e9ff3c19d2ae404 | 9091a2f2e49bc12ad935bb5132dffc152636ee03 | refs/heads/master | 2021-01-15T14:36:15.766171 | 2011-01-04T21:37:18 | 2011-01-04T21:37:18 | 32,115,265 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,027 | cpp | #include <stdlib.h>
#include "obj_parser.h"
#include "Escena.h"
#include "UniformGrid.h"
#include <stdio.h>
#include <cuda_runtime.h>
#include <cutil.h>
#include <vector_types.h>
#include <vector_functions.h>
#include <cutil_math.h>
#define MAX_OBJETOS 10
#ifndef CUDA_ENABLED
void EscenaCrearUniformGrid(ObjetoEscena* escena, int topeEscena, UniformGrid* grilla){
UniformGridCrear(escena, topeEscena, grilla);
}
/* Crea la escena hardcodeada. */
void EscenaCrearDesdeHardcode(Escena* escena){
//Objetos
escena->objetos = (ObjetoEscena*) malloc(sizeof(ObjetoEscena) * MAX_OBJETOS);
escena->cant_objetos = 0;
escena->objetos[escena->cant_objetos].tipo = Triangle;
float4 v1, v2, v3;
v1 = make_float4(10, 10, 10, 0);
v2 = make_float4(11, 11, 11, 0);
v3 = make_float4(5, 5, 5, 0);
TrianguloSetVertices(&(escena->objetos[escena->cant_objetos].tri), v1, v2, v3);
escena->cant_objetos++;
escena->objetos[escena->cant_objetos].tipo = Triangle;
v1 = make_float4(8, 8, 8, 0);
v2 = make_float4(2, 2, 2, 0);
v3 = make_float4(7, 7, 7, 0);
TrianguloSetVertices(&(escena->objetos[escena->cant_objetos].tri), v1, v2, v3);
escena->cant_objetos++;
escena->objetos[escena->cant_objetos].tipo = Triangle;
v1 = make_float4(15, 15, 15, 0);
v2 = make_float4(8, 11, 9, 0);
v3 = make_float4(5, 5, 5, 0);
TrianguloSetVertices(&(escena->objetos[escena->cant_objetos].tri), v1, v2, v3);
escena->cant_objetos++;
escena->objetos[escena->cant_objetos].tipo = Triangle;
v1 = make_float4(2.1, 2.2, 2.3, 0);
v2 = make_float4(3.1, 3.1, 3.1, 0);
v3 = make_float4(2, 3, 2, 0);
TrianguloSetVertices(&(escena->objetos[escena->cant_objetos].tri), v1, v2, v3);
escena->cant_objetos++;
//Luces se cargan en escena->luces, por ahora no hay ninguna
escena->cant_luces = 0;
//Aca hay que setear la camara
//Aca hay que setear el plano de vista
//Grilla
EscenaCrearUniformGrid(escena->objetos, escena->cant_objetos, &(escena->grilla));
}
/* Crea la escena desde el archivo que la define. Retorna 0 en caso de error. */
int EscenaCrearDesdeArchivo(Escena* escena, char* filename){
obj_scene_data objData;
int result = parse_obj_scene(&objData, filename);
if(!result)
return 0;
//Objetos
escena->objetos = (ObjetoEscena*) malloc(sizeof(ObjetoEscena) * (objData.face_count + objData.sphere_count));
escena->cant_objetos = 0;
//Cargo los triangulos...
for(int indiceFace = 0;indiceFace < objData.face_count;indiceFace++){
escena->objetos[escena->cant_objetos].tipo = Triangle;
float4 v1, v2, v3;
v1 = make_float4(
(float)objData.vertex_list[objData.face_list[indiceFace]->vertex_index[0]]->e[0],
(float)objData.vertex_list[objData.face_list[indiceFace]->vertex_index[0]]->e[1],
(float)objData.vertex_list[objData.face_list[indiceFace]->vertex_index[0]]->e[2],
0);
v2 = make_float4(
(float)objData.vertex_list[objData.face_list[indiceFace]->vertex_index[1]]->e[0],
(float)objData.vertex_list[objData.face_list[indiceFace]->vertex_index[1]]->e[1],
(float)objData.vertex_list[objData.face_list[indiceFace]->vertex_index[1]]->e[2],
0);
v3 = make_float4(
(float)objData.vertex_list[objData.face_list[indiceFace]->vertex_index[2]]->e[0],
(float)objData.vertex_list[objData.face_list[indiceFace]->vertex_index[2]]->e[1],
(float)objData.vertex_list[objData.face_list[indiceFace]->vertex_index[2]]->e[2],
0);
TrianguloSetVertices(&(escena->objetos[escena->cant_objetos].tri), v1, v2, v3);
v1 = make_float4(
(float)objData.vertex_normal_list[objData.face_list[indiceFace]->normal_index[0]]->e[0],
(float)objData.vertex_normal_list[objData.face_list[indiceFace]->normal_index[0]]->e[1],
(float)objData.vertex_normal_list[objData.face_list[indiceFace]->normal_index[0]]->e[2],
0);
v2 = make_float4(
(float)objData.vertex_normal_list[objData.face_list[indiceFace]->normal_index[1]]->e[0],
(float)objData.vertex_normal_list[objData.face_list[indiceFace]->normal_index[1]]->e[1],
(float)objData.vertex_normal_list[objData.face_list[indiceFace]->normal_index[1]]->e[2],
0);
v3 = make_float4(
(float)objData.vertex_normal_list[objData.face_list[indiceFace]->normal_index[2]]->e[0],
(float)objData.vertex_normal_list[objData.face_list[indiceFace]->normal_index[2]]->e[1],
(float)objData.vertex_normal_list[objData.face_list[indiceFace]->normal_index[2]]->e[2],
0);
TrianguloSetVertices(&(escena->objetos[escena->cant_objetos].normales), v1, v2, v3);
escena->objetos[escena->cant_objetos].id_material = objData.face_list[indiceFace]->material_index;
escena->cant_objetos++;
}
//Cargo las esferas...
for(int indiceEsf = 0;indiceEsf < objData.sphere_count;indiceEsf++){
escena->objetos[escena->cant_objetos].tipo = Sphere;
//En el primer vertice del triangulo esta el centro de la esfera...
escena->objetos[escena->cant_objetos].tri.v1 = make_float4(
(float)objData.vertex_list[objData.sphere_list[indiceEsf]->pos_index]->e[0],
(float)objData.vertex_list[objData.sphere_list[indiceEsf]->pos_index]->e[1],
(float)objData.vertex_list[objData.sphere_list[indiceEsf]->pos_index]->e[2],
0);
//La componente X de del segundo vertice del triangulo es el radio de la esfera...
float3 upNormal;
upNormal = make_float3(
(float)objData.vertex_list[objData.sphere_list[indiceEsf]->up_normal_index]->e[0],
(float)objData.vertex_list[objData.sphere_list[indiceEsf]->up_normal_index]->e[1],
(float)objData.vertex_list[objData.sphere_list[indiceEsf]->up_normal_index]->e[2]);
escena->objetos[escena->cant_objetos].tri.v2.x = length(upNormal);
escena->objetos[escena->cant_objetos].id_material = objData.face_list[indiceEsf]->material_index;
escena->cant_objetos++;
}
//Aca hay que setear la camara
escena->camara.ojo = make_float3(
objData.vertex_list[objData.camera->camera_pos_index]->e[0],
objData.vertex_list[objData.camera->camera_pos_index]->e[1],
objData.vertex_list[objData.camera->camera_pos_index]->e[2]);
float3 target;
target = make_float3(
objData.vertex_list[objData.camera->camera_look_point_index]->e[0],
objData.vertex_list[objData.camera->camera_look_point_index]->e[1],
objData.vertex_list[objData.camera->camera_look_point_index]->e[2]);
escena->camara.direccion = target - escena->camara.ojo;
escena->camara.up = make_float3(
objData.vertex_normal_list[objData.camera->camera_up_norm_index]->e[0],
objData.vertex_normal_list[objData.camera->camera_up_norm_index]->e[1],
objData.vertex_normal_list[objData.camera->camera_up_norm_index]->e[2]);
//TODO: Aca hay que setear el plano de vista
escena->plano_de_vista.v1 = make_float4(
objData.vertex_list[objData.light_quad_list[0]->vertex_index[0]]->e[0],
objData.vertex_list[objData.light_quad_list[0]->vertex_index[0]]->e[1],
objData.vertex_list[objData.light_quad_list[0]->vertex_index[0]]->e[2],
0);
escena->plano_de_vista.v2 = make_float4(
objData.vertex_list[objData.light_quad_list[0]->vertex_index[1]]->e[0],
objData.vertex_list[objData.light_quad_list[0]->vertex_index[1]]->e[1],
objData.vertex_list[objData.light_quad_list[0]->vertex_index[1]]->e[2],
0);
escena->plano_de_vista.v3 = make_float4(
objData.vertex_list[objData.light_quad_list[0]->vertex_index[2]]->e[0],
objData.vertex_list[objData.light_quad_list[0]->vertex_index[2]]->e[1],
objData.vertex_list[objData.light_quad_list[0]->vertex_index[2]]->e[2],
0);
//Luces se cargan en escena->luces
escena->luces = (Luz*) malloc(sizeof(Luz) * objData.light_point_count);
escena->cant_luces = 0;
for(int indexLuz = 0;indexLuz < objData.light_point_count;indexLuz++){
escena->luces[indexLuz].posicion = make_float4(
objData.vertex_list[objData.light_point_list[indexLuz]->pos_index]->e[0],
objData.vertex_list[objData.light_point_list[indexLuz]->pos_index]->e[1],
objData.vertex_list[objData.light_point_list[indexLuz]->pos_index]->e[2],
0);
escena->luces[indexLuz].color = make_float4(
objData.material_list[objData.light_point_list[indexLuz]->material_index]->diff[0],
objData.material_list[objData.light_point_list[indexLuz]->material_index]->diff[1],
objData.material_list[objData.light_point_list[indexLuz]->material_index]->diff[2],
0);
escena->cant_luces++;
}
//Grilla
EscenaCrearUniformGrid(escena->objetos, escena->cant_objetos, &(escena->grilla));
//Materiales
escena->materiales = (Material*) malloc(sizeof(Material) * objData.material_count);
escena->cant_materiales = 0;
for(int indiceMat = 0;indiceMat < objData.material_count;indiceMat++){
escena->materiales[indiceMat].diffuse_color = make_float3(
objData.material_list[indiceMat]->diff[0],
objData.material_list[indiceMat]->diff[1],
objData.material_list[indiceMat]->diff[2]);
escena->materiales[indiceMat].ambient_color = make_float3(
objData.material_list[indiceMat]->amb[0],
objData.material_list[indiceMat]->amb[1],
objData.material_list[indiceMat]->amb[2]);
escena->materiales[indiceMat].specular_color = make_float3(
objData.material_list[indiceMat]->spec[0],
objData.material_list[indiceMat]->spec[1],
objData.material_list[indiceMat]->spec[2]);
escena->materiales[indiceMat].refraction = (float)objData.material_list[indiceMat]->refract;
escena->materiales[indiceMat].reflection = (float)objData.material_list[indiceMat]->reflect;
escena->materiales[indiceMat].transparency = 1.0-(float)objData.material_list[indiceMat]->trans;
escena->materiales[indiceMat].coef_at_especular = (float)objData.material_list[indiceMat]->shiny;
escena->materiales[indiceMat].index_of_refraction = (float)objData.material_list[indiceMat]->refract_index;
escena->cant_materiales++;
}
delete_obj_data(&objData);
return 1;
}
#else
void EscenaCrearUniformGrid(Triangulo* triangulos, int topeEscena, UniformGrid* grilla){
UniformGridCrear(triangulos, topeEscena, grilla);
}
/* Crea la escena desde el archivo que la define. Retorna 0 en caso de error. */
int EscenaCrearDesdeArchivo(Escena* escena, char* filename){
obj_scene_data objData;
int result = parse_obj_scene(&objData, filename);
if(!result)
return 0;
//Objetos
escena->triangulos = (Triangulo*) malloc(sizeof(Triangulo) * objData.face_count);
escena->normales = (Triangulo*) malloc(sizeof(Triangulo) * objData.face_count);
escena->cant_objetos = 0;
//Cargo los triangulos...
for(int indiceFace = 0;indiceFace < objData.face_count;indiceFace++){
float4 v1, v2, v3;
v1 = make_float4(
(float)objData.vertex_list[objData.face_list[indiceFace]->vertex_index[0]]->e[0],
(float)objData.vertex_list[objData.face_list[indiceFace]->vertex_index[0]]->e[1],
(float)objData.vertex_list[objData.face_list[indiceFace]->vertex_index[0]]->e[2],
(float)objData.face_list[indiceFace]->material_index);
v2 = make_float4(
(float)objData.vertex_list[objData.face_list[indiceFace]->vertex_index[1]]->e[0],
(float)objData.vertex_list[objData.face_list[indiceFace]->vertex_index[1]]->e[1],
(float)objData.vertex_list[objData.face_list[indiceFace]->vertex_index[1]]->e[2],
0);
v3 = make_float4(
(float)objData.vertex_list[objData.face_list[indiceFace]->vertex_index[2]]->e[0],
(float)objData.vertex_list[objData.face_list[indiceFace]->vertex_index[2]]->e[1],
(float)objData.vertex_list[objData.face_list[indiceFace]->vertex_index[2]]->e[2],
0);
TrianguloSetVertices(&(escena->triangulos[escena->cant_objetos]), v1, v2, v3);
v1 = make_float4(
(float)objData.vertex_normal_list[objData.face_list[indiceFace]->normal_index[0]]->e[0],
(float)objData.vertex_normal_list[objData.face_list[indiceFace]->normal_index[0]]->e[1],
(float)objData.vertex_normal_list[objData.face_list[indiceFace]->normal_index[0]]->e[2],
0);
v2 = make_float4(
(float)objData.vertex_normal_list[objData.face_list[indiceFace]->normal_index[1]]->e[0],
(float)objData.vertex_normal_list[objData.face_list[indiceFace]->normal_index[1]]->e[1],
(float)objData.vertex_normal_list[objData.face_list[indiceFace]->normal_index[1]]->e[2],
0);
v3 = make_float4(
(float)objData.vertex_normal_list[objData.face_list[indiceFace]->normal_index[2]]->e[0],
(float)objData.vertex_normal_list[objData.face_list[indiceFace]->normal_index[2]]->e[1],
(float)objData.vertex_normal_list[objData.face_list[indiceFace]->normal_index[2]]->e[2],
0);
TrianguloSetVertices(&(escena->normales[escena->cant_objetos]), v1, v2, v3);
escena->cant_objetos++;
}
//Aca hay que setear la camara
escena->camara.ojo = make_float3(
(float)objData.vertex_list[objData.camera->camera_pos_index]->e[0],
(float)objData.vertex_list[objData.camera->camera_pos_index]->e[1],
(float)objData.vertex_list[objData.camera->camera_pos_index]->e[2]);
float3 target;
target = make_float3(
(float)objData.vertex_list[objData.camera->camera_look_point_index]->e[0],
(float)objData.vertex_list[objData.camera->camera_look_point_index]->e[1],
(float)objData.vertex_list[objData.camera->camera_look_point_index]->e[2]);
escena->camara.target = target;
escena->camara.up = make_float3(
(float)objData.vertex_normal_list[objData.camera->camera_up_norm_index]->e[0],
(float)objData.vertex_normal_list[objData.camera->camera_up_norm_index]->e[1],
(float)objData.vertex_normal_list[objData.camera->camera_up_norm_index]->e[2]);
//TODO: Aca hay que setear el plano de vista
escena->plano_de_vista.v1 = make_float4(
(float)objData.vertex_list[objData.light_quad_list[0]->vertex_index[0]]->e[0],
(float)objData.vertex_list[objData.light_quad_list[0]->vertex_index[0]]->e[1],
(float)objData.vertex_list[objData.light_quad_list[0]->vertex_index[0]]->e[2],
0.f);
escena->plano_de_vista.v2 = make_float4(
(float)objData.vertex_list[objData.light_quad_list[0]->vertex_index[1]]->e[0],
(float)objData.vertex_list[objData.light_quad_list[0]->vertex_index[1]]->e[1],
(float)objData.vertex_list[objData.light_quad_list[0]->vertex_index[1]]->e[2],
0.f);
escena->plano_de_vista.v3 = make_float4(
(float)objData.vertex_list[objData.light_quad_list[0]->vertex_index[2]]->e[0],
(float)objData.vertex_list[objData.light_quad_list[0]->vertex_index[2]]->e[1],
(float)objData.vertex_list[objData.light_quad_list[0]->vertex_index[2]]->e[2],
0.f);
//Luces se cargan en escena->luces
escena->luces = (Luz*) malloc(sizeof(Luz) * objData.light_point_count);
escena->cant_luces = 0;
for(int indexLuz = 0;indexLuz < objData.light_point_count;indexLuz++){
escena->luces[indexLuz].posicion = make_float4(
(float)objData.vertex_list[objData.light_point_list[indexLuz]->pos_index]->e[0],
(float)objData.vertex_list[objData.light_point_list[indexLuz]->pos_index]->e[1],
(float)objData.vertex_list[objData.light_point_list[indexLuz]->pos_index]->e[2],0.f);
escena->luces[indexLuz].color = make_float4(
(float)objData.material_list[objData.light_point_list[indexLuz]->material_index]->diff[0],
(float)objData.material_list[objData.light_point_list[indexLuz]->material_index]->diff[1],
(float)objData.material_list[objData.light_point_list[indexLuz]->material_index]->diff[2],0.f);
escena->cant_luces++;
}
//Grilla
EscenaCrearUniformGrid(escena->triangulos, escena->cant_objetos, &(escena->grilla));
//Materiales
escena->materiales = (Material*) malloc(sizeof(Material) * objData.material_count);
escena->cant_materiales = 0;
for(int indiceMat = 0;indiceMat < objData.material_count;indiceMat++){
escena->materiales[indiceMat].diffuse_color = make_float4(
(float)objData.material_list[indiceMat]->diff[0],
(float)objData.material_list[indiceMat]->diff[1],
(float)objData.material_list[indiceMat]->diff[2],
(float)objData.material_list[indiceMat]->shiny);
escena->materiales[indiceMat].ambient_color = make_float4(
(float)objData.material_list[indiceMat]->amb[0],
(float)objData.material_list[indiceMat]->amb[1],
(float)objData.material_list[indiceMat]->amb[2],
0.f);
escena->materiales[indiceMat].specular_color = make_float4(
(float)objData.material_list[indiceMat]->spec[0],
(float)objData.material_list[indiceMat]->spec[1],
(float)objData.material_list[indiceMat]->spec[2],
0.f);
//(refraction, reflection, transparency, index_of_refraction)
escena->materiales[indiceMat].other = make_float4((float)objData.material_list[indiceMat]->refract,
(float)objData.material_list[indiceMat]->reflect,
1.0f - (float)objData.material_list[indiceMat]->trans,
(float)objData.material_list[indiceMat]->refract_index);
escena->cant_materiales++;
}
delete_obj_data(&objData);
return 1;
}
#endif | [
"gonchimaster@15aacbec-c7e9-11de-8bd7-25a952cf5249",
"sancioli@15aacbec-c7e9-11de-8bd7-25a952cf5249"
]
| [
[
[
1,
309
],
[
311,
388
]
],
[
[
310,
310
]
]
]
|
adc54e6b47fb325bbb6af29cc8b538de8ba6c13a | 4323418f83efdc8b9f8b8bb1cc15680ba66e1fa8 | /Trunk/Battle Cars/Battle Cars/Source/CWanderState.h | 9d2c014b58f21aaa2e574b290a3bc95a69709ea9 | []
| no_license | FiveFourFive/battle-cars | 5f2046e7afe5ac50eeeb9129b87fcb4b2893386c | 1809cce27a975376b0b087a96835347069fe2d4c | refs/heads/master | 2021-05-29T19:52:25.782568 | 2011-07-28T17:48:39 | 2011-07-28T17:48:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,062 | h | /////////////////////////////////////////////////
// File : "IAIBaseState.h"
//
// Author : Josh Fields
//
// Purpose : Pure virtual class which all AI
// states inheriet from
//
/////////////////////////////////////////////////
#ifndef _CWANDERSTATE_H_
#define _CWANDERSTATE_H_
//#include <Windows.h>
#include "IAIBaseState.h"
#include "SGD_Math.h"
#include "CPowerUp.h"
#include "CSpeedRamp.h"
class CEnemy;
class CPlayer;
class CCar;
class CWanderState : public IAIBaseState
{
private:
/*tVector2D m_vPredictMove1;
tVector2D m_vPredictMove2;
tVector2D m_vPredictMove3;
tVector2D m_vPredictMove4;*/
//RECT m_rtPredictMove;
//tVector2D m_vPredictCircle;
//float m_fPredictRadius;
//int m_nThreatDistance;
/*tVector2D m_vVelocity;
tVector2D m_vTurn;*/
//////float m_fMainCircleRadius;
//////float m_fNewPointRadius;
//////int m_nCounter;
//////tVector2D m_vDirectionCenter;
//////tVector2D m_vMainCenter;
bool m_bHasTargets;
float m_fTargetX;
float m_fTargetY;
float m_fRotationAngle;
float m_fturnLeftOrRight;
tVector2D m_vTargetWanderDirection;
CEnemy* m_Owner;
CCar* m_Target1;
CCar* m_Target2;
PowerUp* m_PowerUpTarget;
CSpeedRamp* m_SpeedRampTarget;
float m_fAggroRadius;
void Wander(float fElapsedTime);
bool FindThreat ();
bool FindPowerUps(float fElapsedTime);
void GrabPowerUp(float fElapsedTime);
void FindSpeedRamp(float fElapsedTime);
void UseSpeedRamp(float fElapsedTime);
CWanderState(const CWanderState&);
CWanderState& operator = (const CWanderState&);
public:
CWanderState(void){};
~CWanderState(void){};
void Update (float fElapsedTime);
void Render ();
void Enter ();
void Exit ();
void SetOwner (CEnemy* owner) {m_Owner = owner;}
void SetTarget1(CCar* pTarget) {m_Target1 = pTarget;}
void SetTarget2(CCar* pTarget) {m_Target2 = pTarget;}
CCar* GetTarget1() {return m_Target1;}
CCar* GetTarget2() {return m_Target2;}
void SetHasTarget (bool target) {m_bHasTargets = target;}
};
#endif | [
"[email protected]@598269ab-7e8a-4bc4-b06e-4a1e7ae79330",
"[email protected]@598269ab-7e8a-4bc4-b06e-4a1e7ae79330",
"[email protected]@598269ab-7e8a-4bc4-b06e-4a1e7ae79330"
]
| [
[
[
1,
13
],
[
15,
16
],
[
19,
19
],
[
22,
32
],
[
35,
35
],
[
37,
40
],
[
54,
54
],
[
66,
66
],
[
74,
75
],
[
77,
79
],
[
86,
88
]
],
[
[
14,
14
],
[
21,
21
],
[
33,
34
],
[
36,
36
],
[
43,
43
],
[
47,
47
],
[
55,
56
],
[
67,
73
],
[
76,
76
],
[
80,
84
]
],
[
[
17,
18
],
[
20,
20
],
[
41,
42
],
[
44,
46
],
[
48,
53
],
[
57,
65
],
[
85,
85
]
]
]
|
258c43ad2fdb5e2308094b54dca4cef17f893d11 | 2bdc85da8ec860be41ad14fceecedef1a8efc269 | /PythonWrapper/include/PWDLibLinux.h | 079c3ec65c528ce4d31b4a6a726af9cce7d4b380 | []
| no_license | BackupTheBerlios/pythonwrapper-svn | 5c41a03b23690c62693c7b29e81b240ee24f1a7f | 42879461c7302755f3c803cd1314e8da5a202c68 | refs/heads/master | 2016-09-05T09:53:14.554795 | 2005-12-26T07:52:41 | 2005-12-26T07:52:41 | 40,751,088 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,457 | h | #ifndef _PWDLibLinux_h_
#define _PWDLibLinux_h_
#include "PWCommon.h"
#include "PWDLib.h"
#include "PWString.h"
namespace pw
{
/**
* DLib implementation for Linux.
*/
class DLibLinux : public DLib
{
public:
/**
* Constructs this with the specified library name. Note that under
* linux you should not include the extension (.so).
* @param libraryName the library to load
*/
DLibLinux(const String &libraryName);
/**
* Destructor.
*/
virtual ~DLibLinux();
/**
* Loads the dynamic library. After the library is loaded symbols
* can be obtained by calling getSymbol.
*/
virtual void load();
/**
* Unload the dynamic library. After this is done you cannot call
* getSymbol or use the symbols that are obtained from the library.
*/
virtual void unload();
/**
* Returns true if the library is loaded, false otherwise.
* @returns whether the library is loaded or not
*/
virtual bool isLoaded();
/**
* Returns the symbol specified, or 0 if it does not exist.
* @returns the symbol specified or null
*/
virtual void *getSymbol(const String &symbol) const;
protected:
void *mLib;
};
}
#endif
| [
"cculver@827b5c2f-c6f0-0310-96fe-c05a662c181e"
]
| [
[
[
1,
60
]
]
]
|
4a795ccc8919f4f797f89d1860bc38d360716fc8 | 8f1601062c4a5452f2bdd0f75f3d12a79b98ba62 | /examples/midiplayer.example/midiplayer.example.cpp | 2cf3d1da5bc8a6b7f815fcfb4fa33700b3ad92b5 | []
| no_license | chadaustin/isugamedev | 200a54f55a2581cd2c62c94eb96b9e238abcf3dd | d3008ada042d2dd98c6e05711773badf6f1fd85c | refs/heads/master | 2016-08-11T17:59:38.504631 | 2005-01-25T23:17:11 | 2005-01-25T23:17:11 | 36,483,500 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,005 | cpp |
// MIDI player example (for Win32 and Linux)
//
// - demo by Kevin Meinert <[email protected]>
//
// - Demonstrates how to
// - abstract a MIDI output interface
// - control MIDI in Win32 or Linux through Win32Midi and OssMidi implementations
// - write a MIDI Sequencer using discrete events (synced on a MIDI clock)
// - read binary data from a midi file into the Sequencer
// - deal with endian issues
// - use these components to make a simple MIDI file player.
//
// - TODO:
// - Implement MIDI events for msgs other than progchange, and note
// Background: The only events actually queued are program change, and
// note messages other midi events cannot be ignored, and thus have dummy
// events queued for them to keep the timing sane. Omission of any event
// can throw off the timing of an entire piece, simply because every
// event is stored as a delta in the MIDI file.
// - add interface(s) for all events to the Midi classes
// - correctly implement timing in sequencer based on values read from
// midi file. (currently plays too fast)
//
#include <vector>
#include <fstream>
#include <iostream>
#include <map>
#include <list>
#include <string>
#include <stdio.h>
///////////////////////////////////////////////////////////////////////////////
// sleep abstraction
///////////////////////////////////////////////////////////////////////////////
#ifdef WIN32
#include <windows.h>
void msleep( float msec )
{
::Sleep( (int) msec );
}
#else
#include <unistd.h>
void msleep( float msec )
{
::usleep( (int)(msec * 1000.0f) );
}
#endif
///////////////////////////////////////////////////////////////////////////////
// Midi abstraction(s)
// If you need one for your platform, simply use the same interface,
// and type def your class to "Midi"
///////////////////////////////////////////////////////////////////////////////
#ifdef WIN32
#include <windows.h>
#include <mmsystem.h>
/* an implementation of the "Midi" type for Win32 platform
* (see below for the "typedef win32midi midi" line)
* Usage:
* Midi m;
* m.open();
* m.trigger();
* m.close();
*
* references:
* http://msdn.microsoft.com/library/default.asp?url=/library/en-us/multimed/midi_3fqr.asp
* http://www.borg.com/~jglatt/tech/lowmidi.htm
*/
class Win32Midi
{
public:
/* open the midi device
* this must be called prior to any other functions in this class
*/
virtual bool open()
{
unsigned long result;
/* Open the MIDI Mapper */
result = midiOutOpen(&mHandle, (UINT)-1, (DWORD)MidiOutProc, (DWORD)this, CALLBACK_FUNCTION);
if (result)
{
printf("There was an error opening MIDI Mapper!\r\n");
return false;
}
else
{
return true;
}
}
/* trigger the midi note, on channel, with velocity */
virtual void trigger( char note, char channel = 0x0, char velocity = 0x40 )
{
int chan_nibble = (0x0f & channel); // only lower nibble is recognized.
int trig_nibble = 0x90; // trigger is 9, where X is the chan
int status = trig_nibble | chan_nibble; //
int msg = (velocity << 16) | (note << 8) | status;
midiOutShortMsg( mHandle, msg );
}
/* release the midi note, velocity is ignored and should be 0 */
virtual void release( char note, char channel = 0x0, char velocity = 0x00 )
{
int chan_nibble = (0x0f & channel); // only lower nibble is recognized.
int trig_nibble = 0x80; // trigger is 9, where X is the chan
int status = trig_nibble | chan_nibble; //
velocity = 0;
int msg = (velocity << 16) | (note << 8) | status;
midiOutShortMsg(mHandle, msg);
}
/* just play a note, then release. */
virtual void playnote( char note, char channel = 0x0, char velocity = 0x40, int duration_millisec = 100 )
{
this->trigger( note, channel, velocity );
msleep( duration_millisec );
this->release( note, channel );
}
/* change the instrument on a given channel */
virtual void programchange( char program, char channel = 0x0 )
{
int chan_nibble = (0x0f & channel); // only lower nibble is recognized.
int progchange_nibble = 0xC0; // trigger is 9, where X is the chan
int status = progchange_nibble | chan_nibble; //
int msg = (program << 8) | status;
midiOutShortMsg( mHandle, msg );
}
/* close the midi device. */
virtual void close()
{
unsigned long result;
/* Open the MIDI Mapper */
result = midiOutClose( mHandle );
if (result)
{
printf("There was an error closing MIDI Mapper!\r\n");
}
}
virtual void midimsg( unsigned long msg )
{
midiOutShortMsg( mHandle, msg );
}
/* print to stdout the midi input devices on your win32 system.. */
virtual void printInDevices()
{
MIDIINCAPS mic;
unsigned long iNumDevs, i;
/* Get the number of MIDI In devices in this computer */
iNumDevs = midiInGetNumDevs();
/* Go through all of those devices, displaying their names */
for (i = 0; i < iNumDevs; i++)
{
/* Get info about the next device */
if (!midiInGetDevCaps(i, &mic, sizeof(MIDIINCAPS)))
{
/* Display its Device ID and name */
printf("Device ID #%u: %s\r\n", i, mic.szPname);
}
}
}
/* print to stdout the midi output devices on your win32 system.. */
virtual void printOutDevices()
{
MIDIOUTCAPS moc;
unsigned long iNumDevs, i;
/* Get the number of MIDI Out devices in this computer */
iNumDevs = midiOutGetNumDevs();
/* Go through all of those devices, displaying their names */
for (i = 0; i < iNumDevs; i++)
{
/* Get info about the next device */
if (!midiOutGetDevCaps(i, &moc, sizeof(MIDIOUTCAPS)))
{
/* Display its Device ID and name */
printf("Device ID #%u: %s\r\n", i, moc.szPname);
}
}
}
protected:
/* This function is called on all Win32 midi messages
*/
virtual void callback( UINT wMsg )
{
//printf("virtual Callback happened!\n");
}
private:
static void CALLBACK MidiOutProc(
HMIDIOUT hmo,
UINT wMsg,
DWORD dwInstance,
DWORD dwParam1,
DWORD dwParam2
)
{
Win32Midi* ths = reinterpret_cast<Win32Midi*>( dwInstance );
ths->callback( wMsg );
}
HMIDIOUT mHandle;
};
// under win32, our "Midi" class is the Win32Midi class...
typedef Win32Midi Midi;
#else
#include <unistd.h>
#include <fcntl.h>
#include <sys/soundcard.h>
#include <sys/ioctl.h>
#define BUFFSIZE 1024
// only define this once, otherwise use SEQ_DEFINEEXTBUF
SEQ_DEFINEBUF(BUFFSIZE);
/* an implementation of the "Midi" type for OSS api in linux
*
* references:
* sndkit - snd-util-3.8.tar.gz - found on the OSS web site.
*/
class OssMidi
{
public:
OssMidi() : mFile( -1 ), mDevice( 0 )
{
}
/* open the midi device
* this must be called prior to any other functions in this class
*/
virtual bool open()
{
// /dev/music and /dev/sequencer2 are the same
std::string filename = "/dev/music";
if ((mFile = ::open(filename.c_str(), O_WRONLY, 0)) == -1)
{
perror( filename.c_str() );
filename = "/dev/sequencer2";
if ((mFile = ::open(filename.c_str(), O_WRONLY, 0)) == -1)
{
perror( filename.c_str() );
return false;
}
}
// Check that the (synth) device to be used is available.
int ndevices = -1;
if (ioctl(mFile, SNDCTL_SEQ_NRSYNTHS, &ndevices)==-1)
{
perror("SNDCTL_SEQ_NRSYNTHS");
return false;
}
if (mDevice >= ndevices)
{
fprintf(stderr,
"Error: The requested playback device doesn't exist\n");
return false;
}
return true;
}
/* trigger the midi note, on channel, with velocity */
virtual void trigger( char note, char channel = 0x0, char velocity = 0x40 )
{
if (mFile == -1) return;
SEQ_START_NOTE( mDevice, channel, note, velocity );
SEQ_DUMPBUF(); // write immediately
}
/* release the midi note, velocity is ignored and should be 0 */
virtual void release( char note, char channel = 0x0, char velocity = 0x00 )
{
if (mFile == -1) return;
SEQ_STOP_NOTE( mDevice, channel, note, 0 );
SEQ_DUMPBUF(); // write immediately
}
/* just play a note, then release. */
virtual void playnote( char note, char channel = 0x0, char velocity = 0x40, int duration_millisec = 100 )
{
this->trigger( note, channel, velocity );
msleep( duration_millisec );
this->release( note, channel );
}
/* change the instrument on a given channel */
virtual void programchange( char program, char channel = 0x0 )
{
if (mFile == -1) return;
SEQ_PGM_CHANGE( mDevice, program, channel );
SEQ_SET_PATCH( mDevice, channel, program );
SEQ_DUMPBUF(); // write immediately
}
/* close the midi device. */
virtual void close()
{
if (mFile == -1) return;
::close( mFile );
}
virtual void midimsg( unsigned long msg )
{
if (mFile == -1) return;
// TODO: implement ME!
//
}
private:
// not needed if you have libOSS
void seqbuf_dump ()
{
if (mFile == -1) return;
if (_seqbufptr)
if (write (mFile, _seqbuf, _seqbufptr) == -1)
{
perror ("write /dev/music");
exit (-1);
}
_seqbufptr = 0;
}
int mDevice;
int mFile;
};
// under linux/OSS, our "Midi" class is the OssMidi class...
typedef OssMidi Midi;
#endif
///////////////////////////////////////////////////////////////////////////////
// MIDI Sequencer
///////////////////////////////////////////////////////////////////////////////
/* a generic sequencer event, does nothing, and
* serves as a base class for all events
*/
class Event
{
public:
Event()
{
}
virtual void exec( Midi& m ) {};
};
// Event sequencer
// TODO: the timing may not be calculated correctly (or even specifiable completely)
class Sequencer
{
public:
/* default constructor
*/
Sequencer() : mTickTime( 0.08232f ), mBpm( 120.0f ), mPPQN( 4.0f )
{
}
/* provide the absolute (not delta) time (in ticks) that the event is to be triggered
*/
void addEvent( int ticks, Event* event )
{
mEvents[ticks].push_back( event );
}
/* run the sequenced event list
* this function blocks until finished
*/
void run( Midi& m )
{
// as we iterate over each time slot, we then execute all the events for that slot.
int old_ticks = 0;
float msec_per_tick = mTickTime * 1000.0f;
// for each time slot
std::map<int, std::list<Event*> >::iterator map_itr;
for (map_itr = mEvents.begin(); map_itr != mEvents.end(); ++map_itr)
{
// execute the number of midi clock ticks between events.
int delta_ticks = (*map_itr).first - old_ticks;
old_ticks = (*map_itr).first;
msleep( msec_per_tick * delta_ticks );
// execute each event in current time slot (can be 1 to n).
std::list<Event*>& event_list = (*map_itr).second; // an alias to the list
std::list<Event*>::iterator list_itr;
for (list_itr = event_list.begin(); list_itr != event_list.end(); ++list_itr)
{
(*list_itr)->exec( m );
}
}
}
/* set explicitly the amount of time in one midi clock
*/
void setTickTime( float sec )
{
mTickTime = sec;
}
/* function that is called on each midi clock tick
* if you overload, make sure you sleep for dt, or call this function
*/
virtual void tick( float dt )
{
msleep( dt );
}
/* set the number of pulses per quarter note */
void setPPQN( float ppqn )
{
mPPQN = ppqn;
this->updateBpmPPQN();
}
/* set the tempo in beats per minute */
void setBpm( float bpm )
{
mBpm = bpm;
this->updateBpmPPQN();
}
/* fps is one of the 4 SMPTE standards representing frames per second 24, 25, 29, or 30
* resolution is the number of subframes (clock ticks) in each frame
*/
void setSMPTE( char fps, char resolution )
{
float tick_per_sec = (float)fps * (float)resolution;
float sec_per_tick = 1.0f / tick_per_sec;
this->setTickTime( sec_per_tick );
}
private:
/* called whenever bpm or ppqn is updated
*/
void updateBpmPPQN()
{
float beat_per_sec = mBpm * (1.0f/60.0f);
float tick_per_sec = beat_per_sec * mPPQN;
float sec_per_tick = 1.0f / tick_per_sec;
//float msec_per_tick = sec_per_tick * 1000.0f;
this->setTickTime( sec_per_tick );
//std::cout << "- time:" << sec_per_tick << " ppqn:" << mPPQN << " bpm:"
// << mBpm << "\n" << std::flush;
}
float mBpm, mPPQN, mTickTime;
// this gives the sequencer the ability for each time slot to have multiple events.
// as we iterate over each time slot, we then execute all the events for that slot.
std::map<int, std::list<Event*> > mEvents;
};
/* midi trigger or release
* sequencer event
*/
class NoteEvent : public Event
{
public:
NoteEvent() : note( 60 ), velocity( 0x40 ), channel( 0 )
{
}
virtual void exec( Midi& m )
{
if (trigger)
m.trigger( note, channel, velocity );
else
m.release( note, channel );
std::cout << "trigger: note(" << note
<< ") chan(" << channel << ") vel("
<< velocity << ")\n" << std::flush;
}
int note, velocity, channel;
bool trigger;
};
/* midi program (instrument) change
* sequencer event
*/
class ProgramChangeEvent : public Event
{
public:
ProgramChangeEvent() : prognum( 0 ), channel( 0 )
{
}
virtual void exec( Midi& m )
{
std::cout << "program change: prog(" << prognum
<< ") chan(" << channel << ")\n" << std::flush;
m.programchange( prognum, channel );
}
int prognum, channel;
};
/* generic midi event...
*/
class MidiEvent : public Event
{
public:
MidiEvent() : msg( 0 )
{
}
virtual void exec( Midi& m )
{
m.midimsg( msg );
}
long msg;
};
///////////////////////////////////////////////////////////////////////////////
// Endian support
// (MIDI uses a lot of big endian data,
// on Intel we need to reverse the bytes in that data)
///////////////////////////////////////////////////////////////////////////////
namespace kev
{
//: Swap the bytes in any data type.
// Motorola and Intel store their bytes in reversed formats <BR>
// ex: An SGI image is native to the SGI system, <BR>
// to be read on an intel machine, it's bytes need to be reversed <BR>
// NOTE: chars aren't affected by this since it only <BR>
// affects the order of bytes, not bits.
template< class Type >
inline void byteReverse(Type& bytes)
{
const int size = sizeof(Type);
Type buf = 0;
int x, y;
//we want to index the bytes in the buffer
unsigned char* buffer = (unsigned char*) &buf;
for ( x = 0, y = size-1;
x < size;
++x, --y )
{
buffer[x] |= ((unsigned char*)&bytes)[y];
}
bytes = buf;
}
//: check the system for endianess
inline bool isLittleEndian()
{
union
{
short val;
char ch[sizeof(short)];
} un;
// initialize the memory that we'll probe
un.val = 256; // 0x10
// If the 1 byte is in the low-order position (un.ch[1]), this is a
// little-endian system. Otherwise, it is a big-endian system.
return un.ch[1] == 1;
}
//: check the system for endianess
inline bool isBigEndian()
{
return !isLittleEndian();
}
}
///////////////////////////////////////////////////////////////////////////////
// MIDI file loader
///////////////////////////////////////////////////////////////////////////////
struct CHUNK_HEADER
{
char ID[4];
unsigned long Length;
};
struct MTHD_CHUNK
{
/* Here's the 8 byte header that all chunks must have */
char ID[4]; /* This will be 'M','T','h','d' */
unsigned long Length; /* This will be 6 */
/* Here are the 6 bytes */
unsigned short Format;
unsigned short NumTracks;
unsigned short Division;
};
// An MTrk chunk contains all of the midi data (with timing bytes),
// plus optional non-midi data for one track. Obviously, you should
// encounter as many MTrk chunks in the file as the MThd chunk's
// NumTracks field indicated.
struct MTRK_CHUNK
{
/* Here's the 8 byte header that all chunks must have */
char ID[4]; /* This will be 'M','T','r','k' */
unsigned long Length; /* This will be the actual size of Data[] */
/* Here are the data bytes */
unsigned char Data[1]; /* Its actual size is Data[Length] */
};
void WriteVarLen( std::ofstream& f, unsigned long value )
{
unsigned long buffer = 0;
buffer = value & 0x7F;
while ( (value >>= 7) )
{
buffer <<= 8;
buffer |= ((value & 0x7F) | 0x80);
}
while (true)
{
f.write( (const char*)&buffer, 1 );
//putc(buffer,outfile);
if (buffer & 0x80)
buffer >>= 8;
else
break;
}
}
unsigned long ReadVarLen( std::ifstream& f )
{
unsigned long value = 0;
unsigned char c = 0;
f.read( (char*)&value, 1 );
//value = getc(infile);
if ( value & 0x80 )
{
value &= 0x7F;
do
{
//c = getc(infile);
f.read( (char*)&c, 1 );
value = (value << 7) + (c & 0x7F);
} while (c & 0x80);
}
return(value);
}
/* load a midi file, into a Sequencer object
*
* References:
* http://www.borg.com/~jglatt/tech/midifile.htm
* http://www.borg.com/~jglatt/tech/midispec.htm
*/
void loadMidFile( Sequencer& s, const std::string& filename )
{
std::ifstream f;
f.open( filename.c_str(), std::ios::in | std::ios::binary );
int midi_tracks = 1;
unsigned short format, numtracks, division;
// in midi file, time stamps are relative (deltas)
// in the seq class (sequencer), time stamps are absolute
// use this array of 16 to accumulate the deltas read from the midi file.
// the accumulated delta on tick[x] is the absolute value we will give the seq class...
// the added benefit of this is that it will mix all channels in a midi file together for us.
int ticks[16];
for (int x = 0; x < 16; ++x)
ticks[x] = 0;
// while there is stuff to read...
while (!f.eof())
{
CHUNK_HEADER header;
f.read( (char*)&header, sizeof( CHUNK_HEADER ) );
// bail if we're at eof now, this happens sometimes
// if there is extra data in the file...
if (f.eof())
continue;
// get the number of bytes left in the chunk
if (kev::isLittleEndian())
kev::byteReverse( header.Length );
// debug output...
// std::cout << "type: " << header.ID[0] << " " << header.ID[1] << " " << header.ID[2]
// << " " << header.ID[3] << "\n" << std::flush;
// std::cout << "len: " << header.Length << "\n" << std::flush;
// header chunk, all midi files have this..
if (header.ID[0] == 'M' && header.ID[1] == 'T' &&
header.ID[2] == 'h' && header.ID[3] == 'd')
{
f.read( (char*)&format, sizeof( unsigned short ) );
f.read( (char*)&numtracks, sizeof( unsigned short ) );
f.read( (char*)&division, sizeof( unsigned short ) );
if (kev::isLittleEndian())
{
kev::byteReverse( format );
kev::byteReverse( numtracks );
kev::byteReverse( division );
}
std::cout << "Format: " << format << "\n" << std::flush;
std::cout << "Numtracks: " << numtracks << "\n" << std::flush;
std::cout << "Division (pulses per quarternote): " << division << " "
<< (int)((char*)&division)[0] << "," << (int)((char*)&division)[1]
<< "\n" << std::flush;
// set up seq
s.setPPQN( division );
}
// An MTrk chunk contains all of the midi data (with timing bytes),
// plus optional non-midi data for one track. Obviously, you should
// encounter as many MTrk chunks in the file as the MThd chunk's
// NumTracks field indicated.
else if (header.ID[0] == 'M' && header.ID[1] == 'T' &&
header.ID[2] == 'r' && header.ID[3] == 'k')
{
bool done = false;
unsigned char saved_status = 0;
while (done == false && !f.eof())
{
unsigned long delta_time = ReadVarLen( f );
//if (kev::isLittleEndian())
// kev::byteReverse( delta_time );
//std::cout<<"delta_time: " << delta_time << "\n"<<std::flush;
unsigned char midi_event = 0;
f.read( (char*)&midi_event, 1 );
//printf( "midi_event: %x\n", (char)midi_event );
running_status_jump_point:
// note on event (two data bytes follow the status)
if (((midi_event & 0xf0) == 0x90) || ((midi_event & 0xf0) == 0x80))
{
unsigned char note, velocity;
f.read( (char*)¬e, 1 );
f.read( (char*)&velocity, 1 );
NoteEvent* event = new NoteEvent;
event->note = note & 0x7f;
event->velocity = velocity & 0x7f;
event->trigger = ((midi_event & 0xf0) == 0x90) && (event->velocity > 0);
event->channel = midi_event & 0x0f;
ticks[event->channel] += delta_time;
s.addEvent( ticks[event->channel], event );
//std::cout<<"note ("<<event->trigger<<"): " << (int)note << " "
// << (int)velocity <<"\n"<<std::flush;
}
// aftertouch
else if ((midi_event & 0xf0) == 0xA0)
{
unsigned char note, velocity;
f.read( (char*)¬e, 1 );
f.read( (char*)&velocity, 1 );
// add (dummy) event to sequencer
int channel = midi_event & 0x0f;
ticks[channel] += delta_time;
s.addEvent( ticks[channel], new Event );
}
// control change
else if ((midi_event & 0xf0) == 0xb0)
{
unsigned char controller, value;
f.read( (char*)&controller, 1 );
f.read( (char*)&value, 1 );
// add (dummy) event to sequencer
int channel = midi_event & 0x0f;
ticks[channel] += delta_time;
s.addEvent( ticks[channel], new Event );
}
// program change
else if ((midi_event & 0xf0) == 0xC0)
{
unsigned char prog_num;
f.read( (char*)&prog_num, 1 );
// add (dummy) event to sequencer
ProgramChangeEvent* event = new ProgramChangeEvent;
event->channel = midi_event & 0x0f;
event->prognum = prog_num;
ticks[event->channel] += delta_time;
s.addEvent( ticks[event->channel], event );
//std::cout<<"progchange ("<<event->prognum<<"): chan (" << (int)event->channel
// << ") ticks("<<ticks[event->channel]<<")\n"<<std::flush;
}
// channel pressure
else if ((midi_event & 0xf0) == 0xD0)
{
unsigned char pressure_amount;
f.read( (char*)&pressure_amount, 1 );
// add (dummy) event to sequencer
int channel = midi_event & 0x0f;
ticks[channel] += delta_time;
s.addEvent( ticks[channel], new Event );
}
// pitch wheel
else if ((midi_event & 0xf0) == 0xE0)
{
unsigned char part1, part2;
f.read( (char*)&part1, 1 );
f.read( (char*)&part2, 1 );
// add (dummy) event to sequencer
int channel = midi_event & 0x0f;
ticks[channel] += delta_time;
s.addEvent( ticks[channel], new Event );
}
// system exclusive
else if (midi_event == 0xF0)
{
unsigned char note = 0xf0;
while (note != 0xf7) // throw away the data...
{
f.read( (char*)¬e, 1 );
}
// TODO: consider time here...
}
// MTC Quarter Frame Message
else if (midi_event == 0xf1)
{
unsigned char time_code;
f.read( (char*)&time_code, 1 );
}
// Song Position Pointer
else if (midi_event == 0xf2)
{
unsigned char part1, part2;
f.read( (char*)&part1, 1 );
f.read( (char*)&part2, 1 );
}
// Song Select
else if (midi_event == 0xf3)
{
unsigned char part1;
f.read( (char*)&part1, 1 );
}
// tune request (ask the device to tune itself)
else if (midi_event == 0xf6)
{
// no data.
}
// midi clock
else if (midi_event == 0xf8)
{
// no data.
}
// tick
else if (midi_event == 0xf9)
{
// no data.
}
// midi start
else if (midi_event == 0xfa)
{
// no data.
}
// midi continue
else if (midi_event == 0xfb)
{
// no data.
}
// midi stop
else if (midi_event == 0xfc)
{
// no data.
}
// active sense
else if (midi_event == 0xfe)
{
// no data.
}
// midi reset
//else if (midi_event == 0xff)
//{
// no data.
//}
// ignore these undefined msgs
else if (midi_event == 0xF4 ||
midi_event == 0xF5 ||
midi_event == 0xF9 ||
midi_event == 0xFD)
{
// no data.
}
// meta event
else if (midi_event == 0xFF)
{
unsigned char type = 0;
f.read( (char*)&type, 1 );
// end of track event
if (type == 0x2F)
{
done = true;
unsigned long data_len = ReadVarLen( f ); // should be 0, no data
}
// tempo
else if (type == 0x51)
{
unsigned long data_len = ReadVarLen( f );
unsigned long high = 0, med = 0, low = 0;
f.read( (char*)&high, 1 );
f.read( (char*)&med, 1 );
f.read( (char*)&low, 1 );
unsigned long microsecs_per_quarter_note = (high << 16) | (med << 8) | low;
}
else
{
unsigned long data_len = ReadVarLen( f );
// throw away the meta event data...
std::string data;
data.resize( data_len );
f.read( (char*)&data[0], data.size() );
//std::cout<<"meta event: "<<data_len<<"\n"<<std::flush;
}
}
// running staus case (use the last status message)
else
{
f.putback( midi_event );
midi_event = saved_status;
goto running_status_jump_point;
}
saved_status = midi_event;
}
}
// unknown chunk type, read the data and throw it out...
else
{
std::string data;
data.resize( header.Length );
f.read( (char*)&data[0], data.size() );
}
}
f.close();
}
///////////////////////////////////////////////////////////////////////////////
// Simple Midi File Player (executable)
///////////////////////////////////////////////////////////////////////////////
int main( int argc, char* argv[] )
{
std::string arg = "midiplayer.example.mid";
if (argc == 2)
arg = argv[1];
Midi m;
Sequencer seq;
m.open();
loadMidFile( seq, arg.c_str() );
seq.run( m );
m.close();
return 0;
}
| [
"subatomic@84b32ba4-53c3-423c-be69-77cca6335494"
]
| [
[
[
1,
1039
]
]
]
|
447fbf09ff3ed3ddebb01a6a0fa3d1b21dc24d96 | 3472e587cd1dff88c7a75ae2d5e1b1a353962d78 | /XMonitor/ui_ReportView.h | 1405daca9794305aebf03a940d1e436cfbd84fea | []
| no_license | yewberry/yewtic | 9624d05d65e71c78ddfb7bd586845e107b9a1126 | 2468669485b9f049d7498470c33a096e6accc540 | refs/heads/master | 2021-01-01T05:40:57.757112 | 2011-09-14T12:32:15 | 2011-09-14T12:32:15 | 32,363,059 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,650 | h | /********************************************************************************
** Form generated from reading UI file 'ReportView.ui'
**
** Created: Fri Apr 1 12:32:12 2011
** by: Qt User Interface Compiler version 4.7.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_REPORTVIEW_H
#define UI_REPORTVIEW_H
#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QHBoxLayout>
#include <QtGui/QHeaderView>
#include <QtGui/QTabWidget>
#include <QtGui/QWidget>
QT_BEGIN_NAMESPACE
class Ui_ReportViewClass
{
public:
QHBoxLayout *horizontalLayout;
QTabWidget *tabWidget;
QWidget *design;
QWidget *code;
void setupUi(QWidget *ReportViewClass)
{
if (ReportViewClass->objectName().isEmpty())
ReportViewClass->setObjectName(QString::fromUtf8("ReportViewClass"));
ReportViewClass->resize(400, 300);
horizontalLayout = new QHBoxLayout(ReportViewClass);
horizontalLayout->setSpacing(6);
horizontalLayout->setContentsMargins(11, 11, 11, 11);
horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout"));
tabWidget = new QTabWidget(ReportViewClass);
tabWidget->setObjectName(QString::fromUtf8("tabWidget"));
tabWidget->setTabPosition(QTabWidget::South);
design = new QWidget();
design->setObjectName(QString::fromUtf8("design"));
tabWidget->addTab(design, QString());
code = new QWidget();
code->setObjectName(QString::fromUtf8("code"));
tabWidget->addTab(code, QString());
horizontalLayout->addWidget(tabWidget);
retranslateUi(ReportViewClass);
tabWidget->setCurrentIndex(0);
QMetaObject::connectSlotsByName(ReportViewClass);
} // setupUi
void retranslateUi(QWidget *ReportViewClass)
{
ReportViewClass->setWindowTitle(QApplication::translate("ReportViewClass", "Report", 0, QApplication::UnicodeUTF8));
tabWidget->setTabText(tabWidget->indexOf(design), QApplication::translate("ReportViewClass", "Design", 0, QApplication::UnicodeUTF8));
tabWidget->setTabText(tabWidget->indexOf(code), QApplication::translate("ReportViewClass", "Code", 0, QApplication::UnicodeUTF8));
} // retranslateUi
};
namespace Ui {
class ReportViewClass: public Ui_ReportViewClass {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_REPORTVIEW_H
| [
"yew1998@5ddc4e96-dffd-11de-b4b3-6d349e4f6f86",
"[email protected]@5ddc4e96-dffd-11de-b4b3-6d349e4f6f86"
]
| [
[
[
1,
3
],
[
5,
77
]
],
[
[
4,
4
]
]
]
|
55b586b76628845f4b8d88ff02df5018329de45a | 1c80a726376d6134744d82eec3129456b0ab0cbf | /Project/C++/POJ/2054/2054.cpp | 059dbdf2b00cb70bf4e34e2d0fd4b606e27ecd4a | []
| no_license | dabaopku/project_pku | 338a8971586b6c4cdc52bf82cdd301d398ad909f | b97f3f15cdc3f85a9407e6bf35587116b5129334 | refs/heads/master | 2021-01-19T11:35:53.500533 | 2010-09-01T03:42:40 | 2010-09-01T03:42:40 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,807 | cpp | // 我真诚地保证:
// 我自己独立地完成了整个程序从分析、设计到编码的所有工作。
// 如果在上述过程中,我遇到了什么困难而求教于人,那么,我将在程序实习报告中
// 详细地列举我所遇到的问题,以及别人给我的提示。
// 在此,我感谢 XXX, …, XXX对我的启发和帮助。下面的报告中,我还会具体地提到
// 他们在各个方法对我的帮助。
// 我的程序里中凡是引用到其他程序或文档之处,
// 例如教材、课堂笔记、网上的源代码以及其他参考书上的代码段,
// 我都已经在程序的注释里很清楚地注明了引用的出处。
// 我从未抄袭过别人的程序,也没有盗用别人的程序,
// 不管是修改式的抄袭还是原封不动的抄袭。
// 我编写这个程序,从来没有想过要去破坏或妨碍其他计算机系统的正常运转。
// 郭聪
// 项目名:ACM1017
// 创建时间:2009-10-25
//文件名称:2054.cpp
//创建者: 郭聪
//创建时间:2009-10-25
//最后修改时间:2009-10-25
//功能: 求解ACM2054
//文件中的函数名称和简单功能描述:见具体注释
//文件中定义的全局变量和简单功能描述:见具体注释
//文件中用到的他处定义的全局变量及其出处:无
//与其他文件的依赖关系:无
// 运行结果
// Problem: 2054 User: 00846086
// Memory: 248K Time: 32MS
// Language: C++ Result: Accepted
#include "stdio.h"
#include "iostream"
#include "string.h"
#include "math.h"
#include "string"
#include "vector"
#include "set"
#include "map"
#include "queue"
#include "list"
#include "stack"
using namespace std;
class TreeNode
{
public:
int num;//记录结点是由几个节点合并而成
int sum; //结点的权值
bool used; //记录结点是否被合并
int par; //父亲的序号
vector<int> son;
}tree[1010]; //树结点类,以及儿子列表
int n,r; //结点个数和根的序号
bool init() //进行必要初始化和数据读入
{
cin>>n>>r;
if( n==0 && r==0 )
return false;
r--;
for(int i=0;i<n;i++){ //读取结点权值并清空儿子列表
cin>>tree[i].sum;
tree[i].num=1;
tree[i].son.clear();
tree[i].used=false;
}
for(int i=0;i<n-1;i++){ //读取边信息
int a,b;
cin>>a>>b;
tree[a-1].son.push_back(b-1);
tree[b-1].par=a-1;
}
return true;
}
void solve()
{
int total=0; //花费代价
for(int i=0;i<n-1;i++){ //需要合并n-1次
double maxi=0; //最大权值
int id; //最大权值结点的序号
for(int j=0;j<n;j++){ //枚举所有的结点,寻找权值最大的结点,因为只在儿子结点中寻找,所以不会找到根节点
if(tree[j].used) //结点已经被合并,相当于此节点已经不存在
continue;
if(tree[j].son.size()==0) //结点没有儿子
continue;
vector<int>::iterator vi;
for(vi=tree[j].son.begin();vi!=tree[j].son.end();vi++){
if(tree[*vi].used) //儿子已经不存在
continue;
if(tree[*vi].sum*1.0/tree[*vi].num>maxi){ //儿子的权值比最大值大,更新最大值
maxi=tree[*vi].sum*1.0/tree[*vi].num;
id=*vi;
}
}
}
//合并权值最大的点
total+=tree[id].sum*tree[tree[id].par].num;
tree[tree[id].par].num+=tree[id].num;
tree[tree[id].par].sum+=tree[id].sum;
vector<int>::iterator vi;
for(vi=tree[id].son.begin();vi!=tree[id].son.end();vi++){//将儿子的儿子放入父亲的儿子序列中
if(!tree[*vi].used){
tree[tree[id].par].son.push_back(*vi);
tree[*vi].par=tree[id].par;
}
}
tree[id].used=true;
}
total+=tree[r].sum;
cout<<total<<endl;
}
int main()
{
while(init()){
solve();
}
}
| [
"[email protected]@592586dc-1302-11df-8689-7786f20063ad"
]
| [
[
[
1,
129
]
]
]
|
e4a48327357a7a93d8165c54d5ac4d4f3bcfde62 | 47513f62271d11d9134c6998767149ee330a4e88 | /ACM_2_0_45_OSD/libraries/AP_GPS/AP_GPS_HIL.h | a5e793e55f4dadb41518bdde4555f2efd908131e | []
| no_license | MacDev240/ArduPilotMega_OSD-with-Ublox-3D-DGPS | 51e6a6b3678e0ef9b924e7ef664c4a94608041c0 | 2b7f6a8b01c70a2534bf4454bab5420f18389e29 | refs/heads/master | 2016-09-06T15:49:48.600420 | 2011-09-26T20:07:53 | 2011-09-26T20:07:53 | 2,436,975 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,264 | h | // -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: t -*-
//
// Hardware in the loop gps class.
// Code by James Goppert
//
// This library is free software; you can redistribute it and / or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
//
#ifndef AP_GPS_HIL_h
#define AP_GPS_HIL_h
#include "GPS.h"
class AP_GPS_HIL : public GPS {
public:
AP_GPS_HIL(Stream *s);
virtual void init(void);
virtual bool read(void);
/**
* Hardware in the loop set function
* @param latitude - latitude in deggrees
* @param longitude - longitude in degrees
* @param altitude - altitude in degrees
* @param ground_speed - ground speed in meters/second
* @param ground_course - ground course in degrees
* @param speed_3d - ground speed in meters/second
* @param altitude - altitude in meters
*/
virtual void setHIL(long time, float latitude, float longitude, float altitude,
float ground_speed, float ground_course, float speed_3d, uint8_t num_sats);
private:
bool _updated;
};
#endif // AP_GPS_HIL_H
| [
"[email protected]"
]
| [
[
[
1,
40
]
]
]
|
e22a3a69ed3ae6653b4a5cb5ca4586b4bc8a3ea6 | eb8a27a2cc7307f0bc9596faa4aa4a716676c5c5 | /WinEdition/browser-lcc/jscc/src/v8/v8/src/x64/.svn/text-base/simulator-x64.h.svn-base | d9bdd3595a5abc6643f1dbd0e8449b4e9277700f | [
"BSD-3-Clause",
"bzip2-1.0.6",
"LicenseRef-scancode-public-domain",
"Artistic-2.0",
"Artistic-1.0"
]
| permissive | baxtree/OKBuzzer | c46c7f271a26be13adcf874d77a7a6762a8dc6be | a16e2baad145f5c65052cdc7c767e78cdfee1181 | refs/heads/master | 2021-01-02T22:17:34.168564 | 2011-06-15T02:29:56 | 2011-06-15T02:29:56 | 1,790,181 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,134 | // Copyright 2011 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef V8_X64_SIMULATOR_X64_H_
#define V8_X64_SIMULATOR_X64_H_
#include "allocation.h"
namespace v8 {
namespace internal {
// Since there is no simulator for the x64 architecture the only thing we can
// do is to call the entry directly.
// TODO(X64): Don't pass p0, since it isn't used?
#define CALL_GENERATED_CODE(entry, p0, p1, p2, p3, p4) \
(entry(p0, p1, p2, p3, p4))
typedef int (*regexp_matcher)(String*, int, const byte*,
const byte*, int*, Address, int, Isolate*);
// Call the generated regexp code directly. The code at the entry address should
// expect eight int/pointer sized arguments and return an int.
#define CALL_GENERATED_REGEXP_CODE(entry, p0, p1, p2, p3, p4, p5, p6, p7) \
(FUNCTION_CAST<regexp_matcher>(entry)(p0, p1, p2, p3, p4, p5, p6, p7))
#define TRY_CATCH_FROM_ADDRESS(try_catch_address) \
(reinterpret_cast<TryCatch*>(try_catch_address))
// The stack limit beyond which we will throw stack overflow errors in
// generated code. Because generated code on x64 uses the C stack, we
// just use the C stack limit.
class SimulatorStack : public v8::internal::AllStatic {
public:
static inline uintptr_t JsLimitFromCLimit(uintptr_t c_limit) {
return c_limit;
}
static inline uintptr_t RegisterCTryCatch(uintptr_t try_catch_address) {
return try_catch_address;
}
static inline void UnregisterCTryCatch() { }
};
} } // namespace v8::internal
#endif // V8_X64_SIMULATOR_X64_H_
| [
"[email protected]"
]
| [
[
[
1,
71
]
]
]
|
|
c32142cc3cee8f37df4b1949ab17f686d19f03b9 | c95a83e1a741b8c0eb810dd018d91060e5872dd8 | /Game/ObjectDLL/ObjectShared/Speaker.h | f9f6d8a1b8fe70c97d60e3338bd32ba403e8851b | []
| no_license | rickyharis39/nolf2 | ba0b56e2abb076e60d97fc7a2a8ee7be4394266c | 0da0603dc961e73ac734ff365bfbfb8abb9b9b04 | refs/heads/master | 2021-01-01T17:21:00.678517 | 2011-07-23T12:11:19 | 2011-07-23T12:11:19 | 38,495,312 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 800 | h | // (c) 1997-2000 Monolith Productions, Inc. All Rights Reserved
#ifndef __SPEAKER_H__
#define __SPEAKER_H__
#include "Character.h"
LINKTO_MODULE( Speaker );
class Speaker : public CCharacter
{
public :
uint32 EngineMessageFn(uint32 messageID, void *pData, LTFLOAT fData);
protected :
void InitialUpdate();
void Save(ILTMessage_Write *pMsg, uint32 dwSaveFlags);
void Load(ILTMessage_Read *pMsg, uint32 dwLoadFlags);
LTBOOL ReadProp(ObjectCreateStruct *pInfo);
void PreCreateSpecialFX(CHARCREATESTRUCT& cs);
LTBOOL CanLipSync() { return LTFALSE; }
LTBOOL DoDialogueSubtitles() { return LTTRUE; }
virtual float GetVerticalThreshold() const { return 0.f; }
virtual float GetInfoVerticalThreshold() const { return 0.f; }
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
33
]
]
]
|
3c288d6d762258b417271311d067a9ed4f2ac8e2 | 205cdb795e7db08b3f0e50693e1f833c4675f4f4 | /addtional-libs/pvrtex/include/pvrtex/PVRException.h | 1a013528f662547f21185a380e03752fb45a0341 | []
| no_license | KageKirin/KaniTexTool | 156a6781e1f699144fb8544d36af1c2b1797aaa4 | b5431a82b4ea57682ee594a908dbbebd48d18ac8 | refs/heads/master | 2020-05-19T23:25:24.633660 | 2011-06-04T08:04:49 | 2011-06-04T08:04:49 | 1,720,340 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,810 | h | /******************************************************************************
@File PVRException.h
@Title
@Version
@Copyright Copyright (C) Imagination Technologies Limited. All Rights Reserved. Strictly Confidential.
@Platform ANSI
@Description Exception class and macros.
******************************************************************************/
#ifndef _PVREXCEPTION_H_
#define _PVREXCEPTION_H_
#ifndef PVR_DLL
#ifdef _WINDLL_EXPORT
#define PVR_DLL __declspec(dllexport)
#elif _WINDLL_IMPORT
#define PVR_DLL __declspec(dllimport)
#else
#define PVR_DLL
#endif
#endif
/*****************************************************************************
* Exception class and macros
* Use char* literals only for m_what.
*****************************************************************************/
class PVR_DLL PVRException
{
public:
PVRException(const char* const what)throw();
const char * const what() const;
~PVRException() throw();
private:
const char* const m_what;
const PVRException& operator =(const PVRException&); // don't copy exceptions
};
#define PVRTRY try
#define PVRTHROW(A) {PVRException myException(A); throw(myException);}
#define PVRCATCH(A) catch(PVRException& A)
#define PVRCATCHALL catch(...)
#ifdef PVR_ENABLE_LOG
#define PVRLOG {ConsoleLog::log}
#define PVRLOGTHROW(A) {ConsoleLog::log(A); PVRException myException(A); throw(myException);}
#else
#define PVRLOG
#define PVRLOGTHROW(A) {PVRException myException(A); throw(myException);}
#endif
#endif // _PVREXCEPTION_H_
/*****************************************************************************
* end of file
******************************************************************************/
| [
"[email protected]"
]
| [
[
[
1,
62
]
]
]
|
82fd103033d7bf3874bf43f79c79519a21091566 | b4f709ac9299fe7a1d3fa538eb0714ba4461c027 | /trunk/mainframemenutest.cpp | 5fb07f45d8981d7ecae473e117c1c8ffc15de80a | []
| no_license | BackupTheBerlios/ptparser-svn | d953f916eba2ae398cc124e6e83f42e5bc4558f0 | a18af9c39ed31ef5fd4c5e7b69c3768c5ebb7f0c | refs/heads/master | 2020-05-27T12:26:21.811820 | 2005-11-06T14:23:18 | 2005-11-06T14:23:18 | 40,801,514 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,456 | cpp | /////////////////////////////////////////////////////////////////////////////
// Name: mainframemenutest.cpp
// Purpose: Event handlers for the Test menu
// Author: Brad Larsen
// Modified by:
// Created: Dec 31, 2004
// RCS-ID:
// Copyright: (c) Brad Larsen
// License: wxWindows license
/////////////////////////////////////////////////////////////////////////////
#include "stdwx.h"
#include "mainframe.h"
#include "globaltestsuite.h"
#include "powertabdocumenttestsuite.h"
#include "fontsettingtestsuite.h"
#include "scoretestsuite.h"
#include "alternateendingtestsuite.h"
#include "barlinetestsuite.h"
#include "chordtexttestsuite.h"
#include "chordnametestsuite.h"
#include "chorddiagramtestsuite.h"
#include "directiontestsuite.h"
#include "systemsymboltestsuite.h"
#include "powertabfileheadertestsuite.h"
#include "floatingtexttestsuite.h"
#include "guitartestsuite.h"
#include "guitarintestsuite.h"
#include "tuningtestsuite.h"
#include "systemtestsuite.h"
#include "rhythmslashtestsuite.h"
#include "stafftestsuite.h"
#include "positiontestsuite.h"
#include "notetestsuite.h"
#include "chordtexttestsuite.h"
#include "dynamictestsuite.h"
#include "keysignaturetestsuite.h"
#include "timesignaturetestsuite.h"
#include "tempomarkertestsuite.h"
#include "rehearsalsigntestsuite.h"
#include "generalmiditestsuite.h"
#include "powertabobjecttestsuite.h"
#include "oldrehearsalsigntestsuite.h"
#include "oldtimesignaturetestsuite.h"
#include "powertabdocument.h"
#include <wx/dir.h>
#include <wx/dirdlg.h>
#include <wx/mstream.h>
#include <wx/progdlg.h>
#include <wx/textfile.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
void MainFrame::OnTestTestingFramework(wxCommandEvent& event)
{
// Menu Test -> Testing Framework
//------Last Checked------//
// - Jan 3, 2005
WXUNUSED(event);
// TODO: Add any future test suites here
TestingFramework* testingFramework = new TestingFramework;
testingFramework->AddTestSuite(new AlternateEndingTestSuite);
testingFramework->AddTestSuite(new BarlineTestSuite);
testingFramework->AddTestSuite(new ChordDiagramTestSuite);
testingFramework->AddTestSuite(new ChordNameTestSuite);
testingFramework->AddTestSuite(new ChordTextTestSuite);
testingFramework->AddTestSuite(new DirectionTestSuite);
testingFramework->AddTestSuite(new DynamicTestSuite);
testingFramework->AddTestSuite(new FloatingTextTestSuite);
testingFramework->AddTestSuite(new FontSettingTestSuite);
testingFramework->AddTestSuite(new GeneralMidiTestSuite);
testingFramework->AddTestSuite(new GlobalTestSuite);
testingFramework->AddTestSuite(new GuitarInTestSuite);
testingFramework->AddTestSuite(new GuitarTestSuite);
testingFramework->AddTestSuite(new KeySignatureTestSuite);
testingFramework->AddTestSuite(new NoteTestSuite);
testingFramework->AddTestSuite(new OldRehearsalSignTestSuite);
testingFramework->AddTestSuite(new OldTimeSignatureTestSuite);
testingFramework->AddTestSuite(new PositionTestSuite);
testingFramework->AddTestSuite(new PowerTabDocumentTestSuite);
testingFramework->AddTestSuite(new PowerTabFileHeaderTestSuite);
testingFramework->AddTestSuite(new PowerTabObjectTestSuite);
testingFramework->AddTestSuite(new RehearsalSignTestSuite);
testingFramework->AddTestSuite(new RhythmSlashTestSuite);
testingFramework->AddTestSuite(new ScoreTestSuite);
testingFramework->AddTestSuite(new StaffTestSuite);
testingFramework->AddTestSuite(new SystemSymbolTestSuite);
testingFramework->AddTestSuite(new SystemTestSuite);
testingFramework->AddTestSuite(new TempoMarkerTestSuite);
testingFramework->AddTestSuite(new TimeSignatureTestSuite);
testingFramework->AddTestSuite(new TuningTestSuite);
testingFramework->SortTestSuitesByName();
TestingFrameworkDialog dlg;
dlg.SetTestingFramework(testingFramework);
// Center craps on Linux
#ifdef __WXMSW__
dlg.Center();
#endif
dlg.ShowModal();
}
void MainFrame::OnTestBatchFileSerialization(wxCommandEvent& event)
{
// Menu Test -> Batch File Serialization
//------Last Checked------//
// - Dec 31, 2004
WXUNUSED(event);
// Display critical warning!!!
if (wxMessageBox(wxT("CRITICAL WARNING: Do NOT perform this test on your original Power Tab files. Make a copy of files, place them in a temporary folder, and perform the test on the copied files instead.\n\nProceed with the the test?"),
wxT("Batch File Serialization Test"),
wxYES_NO | wxICON_ERROR) == wxNO)
return;
// Notes: This function will load (individually) all .ptb files
// in a folder (and its subfolders), to ensure deserialization
// is working correctly. If a file is the most recent file
// format (v1.7), the file is saved to a memory stream, and
// then compared with the original file to ensure serialization
// is working correctly. If any errors occur, you will be prompted
// to save the errors to a text file.
wxArrayString errors;
const wxString& dir = wxDirSelector(wxT("Select the folder where your Power Tab files (.ptb) reside, and then click OK."));
if (!dir.empty())
{
const wxChar* errorMessageFormat = wxT("%s - [%s]");
// Get all .ptb files in the folder and its subfolders
// This can take some time if you have alot of files or a slow machine
wxArrayString files;
{
wxProgressDialog progressDialog(wxT("Scanning for Files"), wxT("Please wait. Scanning folders for Power Tab files..."), 0, this, wxPD_AUTO_HIDE | wxPD_APP_MODAL);
wxDir::GetAllFiles(dir, &files, wxT("*.ptb"));
progressDialog.Show(false);
}
// Process each file
size_t i = 0;
size_t fileCount = files.GetCount();
wxProgressDialog progressDialog(wxT("Batch File Serialization Test Progress"), wxT(""), fileCount, this, wxPD_AUTO_HIDE | wxPD_APP_MODAL | wxPD_CAN_ABORT | wxPD_ELAPSED_TIME | wxPD_ESTIMATED_TIME | wxPD_REMAINING_TIME);
bool cancelled = false; // If true, user pressed Cancel button
for (; i < fileCount; i++)
{
wxFileName fileName(files[i]);
// Update progress status
if (!progressDialog.Update(i, wxString::Format(wxT("Testing file %d of %d\n%s..."), i + 1, fileCount, fileName.GetFullName().c_str())))
{
cancelled = true;
break;
}
// Open the file
wxFileInputStream stream(files[i]);
if (stream.IsOk())
{
PowerTabInputStream input_stream(stream);
// Load the file
PowerTabDocument document;
if (!document.Load(input_stream))
{
errors.Add(wxString::Format(errorMessageFormat, files[i].c_str(), input_stream.GetLastErrorMessage().c_str()));
document.DeleteContents();
continue;
}
// If file version is the most current, we can perform a memory save test; if not, continue
if (document.GetHeaderRef().GetVersion() != PowerTabFileHeader::FILEVERSION_CURRENT)
{
document.DeleteContents();
continue;
}
// Save the document to memory
wxMemoryOutputStream memory_stream;
document.SaveObject(memory_stream);
// Size should be the same
if (stream.GetSize() != memory_stream.GetSize())
{
errors.Add(wxString::Format(errorMessageFormat, files[i].c_str(), wxT("Memory Save Test failure")));
document.DeleteContents();
continue;
}
// Compare each byte in the file to each byte of the saved memory data
wxStreamBuffer* streamBuffer = memory_stream.GetOutputStreamBuffer();
if ((stream.GetSize() > 0) && (streamBuffer != NULL))
{
// Set file position to start of file
stream.SeekI(0);
// Get a pointer to the memory stream buffer
wxUint8* ptr = (wxUint8*)streamBuffer->GetBufferStart();
// Get number of bytes left to read from the file
wxUint32 bytesLeft = stream.GetSize();
while (bytesLeft > 0)
{
// Read a chunk of data from the file
const wxUint32 bufferSize = 4096;
wxUint8 buffer[bufferSize];
wxUint32 bytesRead = min(bytesLeft, bufferSize);
stream.Read(buffer, bufferSize);
// Compare each byte in the chunk to the corresponding byte in the memory stream buffer
wxUint32 b = 0;
for (; b < bytesRead; b++)
{
if (buffer[b] != *ptr)
{
errors.Add(wxString::Format(errorMessageFormat, files[i].c_str(), wxT("Memory Save Test failure")));
document.DeleteContents();
// This line will force the while statement to fail
bytesRead = bytesLeft;
break;
}
ptr++;
}
bytesLeft -= bytesRead;
}
}
else
errors.Add(wxString::Format(errorMessageFormat, files[i].c_str(), wxT("Memory Save Test failure")));
document.DeleteContents();
}
else
errors.Add(wxString::Format(errorMessageFormat, files[i].c_str(), wxT("Could not open file")));
// Update progress
if (!progressDialog.Update(i + 1))
{
cancelled = true;
break;
}
}
// User didn't cancel
if (!cancelled)
{
wxString message = wxString::Format(wxT("Testing complete\n\nFiles tested: %d\nErrors: %d"), fileCount, errors.GetCount());
int style = wxICON_INFORMATION;
// Add text to allow user to save error messages
if (errors.GetCount() > 0)
{
message += wxT("\n\nThere were errors that occurred during the testing process. Would you like to save them to file?");
style |= wxYES_NO;
}
// Display results of test to user; If user clicks Yes, save errors to file
if (wxMessageBox(message, wxT("Batch File Serialization Test"), style) == wxYES)
{
wxFileDialog fileDialog(this, wxT("Save Results"), wxT(""), wxT("results.txt"), wxT("Text files (*.txt)|*.txt"), wxSAVE | wxHIDE_READONLY | wxOVERWRITE_PROMPT);
if (fileDialog.ShowModal() == wxID_OK)
{
wxString pathName = fileDialog.GetPath();
// Create a new file
wxTextFile file;
file.Create(pathName);
// Write the errors
size_t e = 0;
size_t count = errors.GetCount();
for (; e < count; e++)
file.AddLine(errors[e]);
file.Write();
file.Close();
}
}
}
}
}
| [
"blarsen@8c24db97-d402-0410-b267-f151a046c31a"
]
| [
[
[
1,
292
]
]
]
|
dd028832ed438daf3ee7a46642282f03df1aba06 | 36bf908bb8423598bda91bd63c4bcbc02db67a9d | /Library/CTitleMenu.cpp | a3ce9c9ab65cf48d7ac842843e1ef76b3c0a9869 | []
| no_license | code4bones/crawlpaper | edbae18a8b099814a1eed5453607a2d66142b496 | f218be1947a9791b2438b438362bc66c0a505f99 | refs/heads/master | 2021-01-10T13:11:23.176481 | 2011-04-14T11:04:17 | 2011-04-14T11:04:17 | 44,686,513 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,509 | cpp | /*
CTitleMenu.cpp
Based on the code of Per Fikse(1999/06/16) on codeguru.earthweb.com
Author: Arthur Westerman
Bug reports by : Brian Pearson
Luca Piergentili, 09/02/04 (modifiche minori)
*/
#include "env.h"
#include "pragma.h"
#include "macro.h"
#include "window.h"
#include "CTitleMenu.h"
#include "traceexpr.h"
//#define _TRACE_FLAG _TRFLAG_TRACEOUTPUT
//#define _TRACE_FLAG _TRFLAG_NOTRACE
#define _TRACE_FLAG _TRFLAG_NOTRACE
#define _TRACE_FLAG_INFO _TRFLAG_NOTRACE
#define _TRACE_FLAG_WARN _TRFLAG_NOTRACE
#define _TRACE_FLAG_ERR _TRFLAG_NOTRACE
#if (defined(_DEBUG) && defined(_WINDOWS)) && (defined(_AFX) || defined(_AFXDLL))
#ifdef PRAGMA_MESSAGE_VERBOSE
#pragma message("\t\t\t"__FILE__"("STR(__LINE__)"): using DEBUG_NEW macro")
#endif
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/*
CTitleMenu()
*/
CTitleMenu::CTitleMenu()
{
HFONT hFont = CreatePopupMenuTitleFont();
if(hFont)
m_Font.Attach(hFont);
m_lLeft = ::GetSysColor(COLOR_ACTIVECAPTION);
m_lRight = ::GetSysColor(COLOR_GRADIENTACTIVECAPTION);
//m_lRight = ::GetSysColor(27);
m_lText = ::GetSysColor(COLOR_CAPTIONTEXT);
m_bDrawEdge = FALSE;
m_nEdgeFlags = BDR_SUNKENINNER;
memset(m_szTitle,'\0',sizeof(m_szTitle));
m_bCanDoGradientFill = FALSE;
if((m_hMSImg32 = ::LoadLibrary("msimg32.dll"))!=(HMODULE)NULL)
if((m_lpfnGradientFill = (LPFNDLLFUNC1)::GetProcAddress(m_hMSImg32,"GradientFill"))!=(LPFNDLLFUNC1)NULL)
m_bCanDoGradientFill = TRUE;
}
/*
~CTitleMenu()
*/
CTitleMenu::~CTitleMenu()
{
m_Font.DeleteObject();
if(m_hMSImg32)
::FreeLibrary(m_hMSImg32);
}
/*
CreatePopupMenuTitleFont()
*/
HFONT CTitleMenu::CreatePopupMenuTitleFont(void)
{
// start by getting the stock menu font
HFONT hFont = (HFONT)::GetStockObject(ANSI_VAR_FONT);
if(hFont)
{
LOGFONT lf;
if(::GetObject(hFont,sizeof(LOGFONT),&lf)) //get the complete LOGFONT describing this font
{
lf.lfWeight = FW_BOLD; // set the weight to bold
return(::CreateFontIndirect(&lf)); // recreate this font with just the weight changed
}
}
return(NULL);
}
/*
AddTitle()
*/
void CTitleMenu::AddTitle(LPCSTR lpcszTitle,UINT nID/* = (UINT)-1L*/)
{
// insert an empty owner-draw item at top to serve as the title
int i = 0;
char* p = (char*)lpcszTitle;
while(i < sizeof(m_szTitle)-1 && *p)
{
m_szTitle[i] = *p;
if(*p=='&')
m_szTitle[++i] = '&';
i++,p++;
}
// elemento (titolo) selezionabile a seconda dell'id
InsertMenu(0,MF_BYPOSITION|MF_OWNERDRAW|MF_STRING,nID==(UINT)-1L ? 0 : nID);
}
/*
MeasureItem()
*/
void CTitleMenu::MeasureItem(LPMEASUREITEMSTRUCT mi)
{
// get the screen dc to use for retrieving size information
CDC dc;
dc.Attach(::GetDC(NULL));
// select the title font
HFONT hfontOld = (HFONT)SelectObject(dc.m_hDC,(HFONT)m_Font);
// compute the size of the title
CSize size = dc.GetTextExtent(m_szTitle,strlen(m_szTitle));
// deselect the title font
::SelectObject(dc.m_hDC,hfontOld);
// add in the left margin for the menu item - vedi sotto quando disegna il menu
//size.cx += ::GetSystemMetrics(SM_CXMENUCHECK)+8;
size.cy += 6;
//Return the width and height
//+ include space for border
const int nBorderSize = 2;
mi->itemWidth = size.cx + nBorderSize;
mi->itemHeight = size.cy + nBorderSize;
// cleanup
::ReleaseDC(NULL, dc.Detach());
}
/*
DrawItem()
*/
void CTitleMenu::DrawItem(LPDRAWITEMSTRUCT di)
{
COLORREF crOldBk = ::SetBkColor(di->hDC,m_lLeft);
if(m_bCanDoGradientFill&&(m_lLeft!=m_lRight))
{
TRIVERTEX rcVertex[2];
di->rcItem.right--; // exclude this point, like FillRect does
di->rcItem.bottom--;
rcVertex[0].x = di->rcItem.left;
rcVertex[0].y = di->rcItem.top;
rcVertex[0].Red = GetRValue(m_lLeft)<<8; // color values from 0x0000 to 0xff00 !!!!
rcVertex[0].Green = GetGValue(m_lLeft)<<8;
rcVertex[0].Blue = GetBValue(m_lLeft)<<8;
rcVertex[0].Alpha = 0x0000;
rcVertex[1].x = di->rcItem.right;
rcVertex[1].y = di->rcItem.bottom;
rcVertex[1].Red = GetRValue(m_lRight)<<8;
rcVertex[1].Green = GetGValue(m_lRight)<<8;
rcVertex[1].Blue = GetBValue(m_lRight)<<8;
rcVertex[1].Alpha = 0;
GRADIENT_RECT rect;
rect.UpperLeft = 0;
rect.LowerRight = 1;
// fill the area
::GradientFill(di->hDC,rcVertex,2,&rect,1,GRADIENT_FILL_RECT_H);
}
else
{
::ExtTextOut(di->hDC,0,0,ETO_OPAQUE,&di->rcItem,NULL,0,NULL);
}
if(m_bDrawEdge)
::DrawEdge(di->hDC,&di->rcItem,m_nEdgeFlags,BF_RECT);
int modeOld = ::SetBkMode(di->hDC,TRANSPARENT);
COLORREF crOld = ::SetTextColor(di->hDC,m_lText);
// select font into the dc
HFONT hfontOld = (HFONT)::SelectObject(di->hDC,(HFONT)m_Font);
// add the menu margin offset - eliminare se sotto si usa DT_CENTER
di->rcItem.left += ::GetSystemMetrics(SM_CXMENUCHECK)+2;
// draw the text
::DrawText(di->hDC,m_szTitle,-1,&di->rcItem,DT_SINGLELINE|DT_VCENTER|DT_LEFT/*DT_CENTER*/);
//Restore font and colors...
::SelectObject(di->hDC, hfontOld);
::SetBkMode(di->hDC, modeOld);
::SetBkColor(di->hDC, crOldBk);
::SetTextColor(di->hDC, crOld);
}
/*
GradientFill()
*/
BOOL CTitleMenu::GradientFill(HDC hdc,PTRIVERTEX pVertex,DWORD dwNumVertex,PVOID pMesh,DWORD dwNumMesh,DWORD dwMode)
{
return(m_bCanDoGradientFill ? m_lpfnGradientFill(hdc,pVertex,dwNumVertex,pMesh,dwNumMesh,dwMode) : FALSE);
}
| [
"[email protected]"
]
| [
[
[
1,
205
]
]
]
|
34d1b2ce78e2689656f4cd3bd81000aa3a6da7b6 | 6114db1d18909e8d38365a81ab5f0b1221c6d479 | /Sources/AsProfiled/profiler_helper.cpp | ec49a4a537ae514181da67cbf12eee1c85187f13 | []
| 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 | 3,599 | cpp | #include "stdafx.h" // wont compile without this
#include "profiler_helper.h"
#include "common.h"
CProfilerHelper::CProfilerHelper() { }
CProfilerHelper& CProfilerHelper::GetInstance() {
static CProfilerHelper instance;
return instance;
}
void CProfilerHelper::ParseCallingConvention(PCCOR_SIGNATURE& data) {
ULONG oredCallingConvetion = CorSigUncompressCallingConv(data); // PAGE 154 from part II
if ((oredCallingConvetion & IMAGE_CEE_CS_CALLCONV_DEFAULT_HASTHIS) == IMAGE_CEE_CS_CALLCONV_DEFAULT_HASTHIS)
{
std::cout << "DEFAULT_HASTHIS calling convetion" << std::endl;
}
if ((oredCallingConvetion & IMAGE_CEE_CS_CALLCONV_C) == IMAGE_CEE_CS_CALLCONV_C)
{
std::cout << "C calling convetion" << std::endl;
}
if ((oredCallingConvetion & IMAGE_CEE_CS_CALLCONV_DEFAULT) == IMAGE_CEE_CS_CALLCONV_DEFAULT)
{
std::cout << "DEFAULT calling convetion" << std::endl;
}
if ((oredCallingConvetion & IMAGE_CEE_CS_CALLCONV_EXPLICITTHIS) == IMAGE_CEE_CS_CALLCONV_EXPLICITTHIS)
{
std::cout << "EXPLICITTHIS calling convetion" << std::endl;
}
if ((oredCallingConvetion & IMAGE_CEE_CS_CALLCONV_FASTCALL) == IMAGE_CEE_CS_CALLCONV_FASTCALL)
{
std::cout << "FASTCALL calling convetion" << std::endl;
}
if ((oredCallingConvetion & IMAGE_CEE_CS_CALLCONV_HASTHIS) == IMAGE_CEE_CS_CALLCONV_HASTHIS)
{
std::cout << "HASTHIS calling convetion" << std::endl;
}
if ((oredCallingConvetion & IMAGE_CEE_CS_CALLCONV_STDCALL) == IMAGE_CEE_CS_CALLCONV_STDCALL)
{
std::cout << "STDCALL calling convetion" << std::endl;
}
if ((oredCallingConvetion & IMAGE_CEE_CS_CALLCONV_THISCALL) == IMAGE_CEE_CS_CALLCONV_THISCALL)
{
std::cout << "THISCALL calling convetion" << std::endl;
}
if ((oredCallingConvetion & IMAGE_CEE_CS_CALLCONV_VARARG) == IMAGE_CEE_CS_CALLCONV_VARARG)
{
std::cout << "VARARG calling convetion" << std::endl;
}
}
ULONG CProfilerHelper::GetArgumentsCount(PCCOR_SIGNATURE &data) {
ULONG argsCount = 0;
CorSigUncompressData(data, &argsCount);
return argsCount;
}
// only fixed string args for now
std::vector<WCHAR*>* CProfilerHelper::ParseAttributeMetaData(const void* attributeBlob, ULONG blobSize, ULONG argumentsCount) {
static UINT8 oneByteLengthUnicodeMarker = 0;
static UINT8 twoBytesLengthUnicodeMarker = 6;
static UINT8 threeBytesLengthUnicodeMarker = 14;
static UINT8 fourBytesLengthUnicodeMarker = 30;
UINT8* blob = (UINT8*) attributeBlob;
ULONG prolog = *((INT16*)blob);
// move forward
// skip prolog
blob += 2;
ULONG stringLength = 0;
std::vector<WCHAR*>* argumentsValues = new std::vector<WCHAR*>();
for (ULONG i = 0; i < argumentsCount; ++i) {
WCHAR* argument = NULL;
if (*blob == 0xFF) { // string is null
argument = new WCHAR[1];
argument[0] = '\0';
argumentsValues->push_back(argument);
continue;
}
ULONG packedLen = 0;
blob += CorSigUncompressData(blob, &packedLen);
argument = new WCHAR[packedLen + 1];
ULONG consumedBytes = 0;
UINT index=0;
while (consumedBytes < packedLen) {
UINT8 byte = *blob;
if ((byte >> 7) == oneByteLengthUnicodeMarker) {
argument[index++] = *blob;
blob++;
consumedBytes++;
}else if ((byte >> 5) == twoBytesLengthUnicodeMarker) {
argument[index++] = *((UINT16*) blob);
blob+=2;
consumedBytes+=2;
}else if ((byte >> 4) == threeBytesLengthUnicodeMarker) {
blob+=3;
}else{//four byte
blob+=4;
}
}
argument[index] = '\0';
argumentsValues->push_back(argument);
}
return argumentsValues;
} | [
"adamsonic@cf2cc628-70ab-11de-90d8-1fdda9445408"
]
| [
[
[
1,
115
]
]
]
|
b7a4567f88a49e8674aed606d19722f1f8cf4df4 | cfc9acc69752245f30ad3994cce0741120e54eac | /bikini/private/source/flash/shape.cpp | b62e2c1076f7a80bc2be559e917f8312dba4e24a | []
| no_license | Heartbroken/bikini-iii | 3b7852d1af722b380864ac87df57c37862eb759b | 93ffa5d43d9179b7c5e7f7c2df9df7dafd79a739 | refs/heads/master | 2020-03-28T00:41:36.281253 | 2009-04-30T14:58:10 | 2009-04-30T14:58:10 | 37,190,689 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,877 | cpp | /*---------------------------------------------------------------------------------------------*//*
Binary Kinematics 3 - C++ Game Programming Library
Copyright (C) 2008 Viktor Reutzky
[email protected]
*//*---------------------------------------------------------------------------------------------*/
#include "header.hpp"
namespace bk { /*--------------------------------------------------------------------------------*/
// triangulator
struct triangulator {
typedef real2 point;
typedef array_<point> points;
typedef array_<uint> poly;
struct vertex { uint p, e0, e1; bool n; };
typedef array_<vertex> vertices;
typedef array_<uint> point_map;
struct edge { uint v0, v1, ne, te; };
typedef array_<edge> edges;
typedef array_<uint> edge_list;
struct trapezoid { uint v0, v0c, v1, v1c, e0, e1; };
typedef array_<trapezoid> trapezoids;
inline uint tri_count() const { return m_tris.size() / 3; }
inline const uint* get_tris() const { return &m_tris[0]; }
bool build(const points &_points, const poly &_poly) {
if(_points.empty() || _poly.empty()) return false;
lines.resize(0);
m_create_edges(_points, _poly);
m_split_monotone();
m_triangulate_parts();
return true;
}
array_<point> lines;
private:
const point *m_points;
vertices m_vertices; point_map m_point_map;
edges m_edges; edge_list m_edge_list; trapezoids m_trapezoids;
array_<uint> m_monotone, m_tris;
void m_create_edges(const points &_points, const poly &_poly) {
m_edges.resize(0); m_edge_list.resize(0); m_trapezoids.resize(0);
m_monotone.resize(0); m_tris.resize(0);
m_vertices.resize(0);
m_points = &_points[0]; // @@@
assert(_poly.size() > 1 && _poly.size() % 2 == 0);
for(uint i = 1, s = _poly.size(); i < s; i += 2) {
vertex l_v; l_v.p = _poly[i]; l_v.e0 = l_v.e1 = bad_ID; l_v.n = false;
const real2 &l_p = _points[l_v.p];
uint l_i = m_vertices.size();
for(uint i = 0, s = m_vertices.size(); i < s; ++i) {
const real2 &l_p0 = _points[m_vertices[i].p];
if((l_p.x() < l_p0.x()) || (abs(l_p.x() - l_p0.x()) < eps && (l_p.y() < l_p0.y()))) {
l_i = i; break;
}
}
m_vertices.insert(m_vertices.begin() + l_i, l_v);
}
m_point_map.resize(_points.size());
for(uint i = 0, s = m_vertices.size(); i < s; ++i) {
m_point_map[m_vertices[i].p] = i;
}
for(uint i = 1, s = _poly.size(); i < s; i += 2) {
uint l_i0 = _poly[i - 1], l_i1 = _poly[i];
edge l_edge; l_edge.v0 = m_point_map[l_i0]; l_edge.v1 = m_point_map[l_i1]; l_edge.ne = l_edge.te = bad_ID;
vertex &l_v0 = m_vertices[l_edge.v0], &l_v1 = m_vertices[l_edge.v1];
assert(l_v0.e1 == bad_ID && l_v1.e0 == bad_ID);
l_v0.e1 = l_v1.e0 = m_edges.size();
if(l_v0.e0 != bad_ID) m_edges[l_v0.e0].ne = l_v0.e1;
if(l_v1.e1 != bad_ID) l_edge.ne = l_v1.e1;
m_edges.push_back(l_edge);
}
}
void m_split_monotone() {
for(uint i = 0, s = m_vertices.size(); i < s; ++i) {
uint l_vs = i, l_ve = i;
const real l_ps_x = m_points[m_vertices[l_vs].p].x();
for(uint s = m_vertices.size(); l_ve + 1 < s; ++l_ve) {
const real l_pe_x = m_points[m_vertices[l_ve + 1].p].x();
if(abs(l_ps_x - l_pe_x) > eps) break;
}
m_close_trapezoids(l_vs, l_ve);
m_remove_edges(l_vs, l_ve);
m_add_edges(l_vs, l_ve);
m_open_trapezoids(l_vs, l_ve);
i = l_ve;
}
}
void m_triangulate_parts() {
for(uint i = 0, s = m_edges.size(); i < s; ++i) {
edge &l_e = m_edges[i];
if(l_e.ne == bad_ID) continue;
m_monotone.resize(0);
uint l_ei = l_e.ne; l_e.ne = bad_ID;
while(l_ei != bad_ID) {
edge &l_e = m_edges[l_ei];
vertex &l_v0 = m_vertices[l_e.v0], &l_v1 = m_vertices[l_e.v1];
l_v0.e1 = l_v1.e0 = l_ei;
// @@@ // Optimize this. Do not do full sorting, but merge two monotone chains
array_<uint>::iterator l_insert = m_monotone.end();
for(uint i = 0, s = m_monotone.size(); i < s; ++i) {
if(l_e.v0 < m_monotone[i]) {
l_insert = m_monotone.begin() + i;
break;
}
}
m_monotone.insert(l_insert, l_e.v0);
// @@@
l_ei = l_e.ne; l_e.ne = bad_ID;
}
m_triangulate_monotone();
}
//// test
//for(uint i = 0, s = m_edges.size(); i < s; ++i) {
// const edge &l_e = m_edges[i];
// const vertex &l_v0 = m_vertices[l_e.v0], &l_v1 = m_vertices[l_e.v1];
// lines.push_back(m_points[l_v0.p]);
// lines.push_back(m_points[l_v1.p]);
//}
}
void m_triangulate_monotone() {
assert(m_monotone.size() > 2);
array_<uint> l_stack; l_stack.insert(l_stack.end(), m_monotone.begin(), m_monotone.begin() + 2);
for(uint i = 2, s = m_monotone.size(); i < s; ++i) {
uint l_vi = m_monotone[i];
if(m_adjacent_vertices(l_vi, l_stack.front())) {
const vertex &l_v0 = m_vertices[l_vi];
bool l_reverse = (m_vertices[l_stack[0]].e0 == l_v0.e1);
while(l_stack.size() > 1) {
uint l_v1i = l_stack[0], l_v2i = l_stack[1];
if(l_reverse) swap(l_v1i, l_v2i);
const vertex &l_v1 = m_vertices[l_v1i];
const vertex &l_v2 = m_vertices[l_v2i];
m_tris.push_back(l_v0.p); m_tris.push_back(l_v1.p); m_tris.push_back(l_v2.p);
l_stack.erase(l_stack.begin());
}
l_stack.push_back(l_vi);
} else if(m_adjacent_vertices(l_vi, l_stack.back())) {
const vertex &l_v0 = m_vertices[l_vi];
const point &l_p0 = m_points[l_v0.p];
bool l_reverse = (m_vertices[l_stack[l_stack.size() - 1]].e0 == l_v0.e1);
while(l_stack.size() > 1) {
uint l_v1i = l_stack[l_stack.size() - 1], l_v2i = l_stack[l_stack.size() - 2];
if(l_reverse) swap(l_v1i, l_v2i);
const vertex &l_v1 = m_vertices[l_v1i], &l_v2 = m_vertices[l_v2i];
const point &l_p1 = m_points[l_v1.p], &l_p2 = m_points[l_v2.p];
point l_d0 = l_p0 - l_p2, l_d1 = l_p1 - l_p2;
real l_a0 = atan2(l_d0.y(), l_d0.x()), l_a1 = atan2(l_d1.y(), l_d1.x()), l_a = l_a1 - l_a0;
while(l_a < 0) l_a += real(2) * pi;
if(l_a > pi) break;
m_tris.push_back(l_v0.p); m_tris.push_back(l_v1.p); m_tris.push_back(l_v2.p);
l_stack.erase(l_stack.end() - 1);
}
l_stack.push_back(l_vi);
} else {
assert(0);
}
}
}
bool m_adjacent_vertices(uint _v0, uint _v1) {
const vertex &l_v = m_vertices[_v0];
const edge &l_e0 = m_edges[l_v.e0], &l_e1 = m_edges[l_v.e1];
return l_e0.v0 == _v1 || l_e1.v1 == _v1;
}
bool m_vertical_edge(uint _e) {
const edge &l_e = m_edges[_e];
const vertex &l_v0 = m_vertices[l_e.v0], &l_v1 = m_vertices[l_e.v1];
const point &l_p0 = m_points[l_v0.p], &l_p1 = m_points[l_v1.p];
return abs(l_p0.x() - l_p1.x()) < eps;
}
void m_add_edges(uint _vs, uint _ve) {
for(uint i = _vs; i <= _ve; ++i) {
uint l_vi = i;
const vertex &l_v = m_vertices[i];
const edge &l_e0 = m_edges[l_v.e0];
const edge &l_e1 = m_edges[l_v.e1];
uint l_v0i = l_e0.v0, l_v1i = l_e1.v1;
if(l_vi < l_v0i) m_add_edge(l_v.e0);
if(l_vi < l_v1i) m_add_edge(l_v.e1);
}
}
void m_add_edge(uint _e) {
if(m_vertical_edge(_e)) return;
for(uint i = 0, s = m_edge_list.size(); i < s; ++i) {
if(m_edge_edge_compare(_e, m_edge_list[i]) < 0) {
m_edge_list.insert(m_edge_list.begin() + i, _e);
return;
}
}
m_edge_list.push_back(_e);
}
void m_remove_edges(uint _vs, uint _ve) {
for(uint i = _vs; i <= _ve; ++i) {
uint l_vi = i;
const vertex &l_v = m_vertices[i];
const edge &l_e0 = m_edges[l_v.e0];
const edge &l_e1 = m_edges[l_v.e1];
uint l_v0i = l_e0.v0, l_v1i = l_e1.v1;
if(l_vi > l_v0i) m_remove_edge(l_v.e0);
if(l_vi > l_v1i) m_remove_edge(l_v.e1);
}
}
void m_remove_edge(uint _e) {
if(m_vertical_edge(_e)) return;
for(uint i = 0, s = m_edge_list.size(); i < s; ++i) {
if(m_edge_list[i] == _e) {
m_edge_list.erase(m_edge_list.begin() + i);
break;
}
}
}
void m_open_trapezoids(uint _vs, uint _ve) {
for(uint i = _vs; i <= _ve; ++i) {
uint l_v = i;
for(uint i = 1, s = m_edge_list.size(); i < s; ++i) {
uint l_e0 = m_edge_list[i - 1], l_e1 = m_edge_list[i];
if(m_get_trapezoid(l_e0) != m_get_trapezoid(l_e1)) continue;
sint l_c0 = m_vertex_edge_compare(l_v, l_e0), l_c1 = m_vertex_edge_compare(l_v, l_e1);
if(l_c0 >= 0 && l_c1 <= 0) m_open_trapezoid(l_v, l_e0, l_e1);
if(l_c0 < 0) break;
}
}
}
void m_open_trapezoid(uint _v, uint _e0, uint _e1) {
uint l_i = m_get_trapezoid(_e0, _e1);
if(l_i == bad_ID) {
l_i = m_trapezoids.size(); m_trapezoids.resize(l_i + 1);
trapezoid &l_t = m_trapezoids[l_i];
l_t.v0 = l_t.v1 = bad_ID;
l_t.v0c = l_t.v1c = 1;
l_t.e0 = _e0; l_t.e1 = _e1;
}
trapezoid &l_t = m_trapezoids[l_i];
assert(l_t.v0 == bad_ID || l_t.v0 + l_t.v0c == _v);
if(l_t.v0 == bad_ID) l_t.v0 = _v;
else l_t.v0c++;
vertex &l_v = m_vertices[_v];
const edge &l_e0 = m_edges[l_v.e0], &l_e1 = m_edges[l_v.e1];
if(l_e0.v0 < _v && l_e1.v1 < _v) l_v.n = true;
}
void m_close_trapezoids(uint _vs, uint _ve) {
for(uint i = _vs; i <= _ve; ++i) {
uint l_v = i;
for(uint i = 1, s = m_edge_list.size(); i < s; ++i) {
uint l_e0 = m_edge_list[i - 1], l_e1 = m_edge_list[i];
sint l_c0 = m_vertex_edge_compare(l_v, l_e0), l_c1 = m_vertex_edge_compare(l_v, l_e1);
if(l_c0 >= 0 && l_c1 <= 0) m_close_trapezoid(l_v, l_e0, l_e1);
if(l_c0 < 0) break;
}
}
if(!m_trapezoids.empty()) {
for(uint i = m_trapezoids.size() - 1; ; --i) {
if(m_trapezoids[i].v1 != bad_ID) {
m_split_trapezoid(i);
m_trapezoids.erase(m_trapezoids.begin() + i);
}
if(i == 0) break;
}
}
}
void m_split_trapezoid(uint _t) {
const trapezoid &l_t = m_trapezoids[_t];
assert(l_t.v0 != bad_ID && l_t.v1 != bad_ID);
for(uint i = 0; i < l_t.v0c; ++i) {
uint l_v0i = l_t.v0 + i;
vertex &l_v0 = m_vertices[l_v0i];
if(!l_v0.n) continue;
const real l_p0_y = m_points[l_v0.p].y();
uint l_v1i = bad_ID; real l_diff = infinity;
for(uint i = 0; i < l_t.v1c; ++i) {
const vertex &l_v1 = m_vertices[l_t.v1 + i];
const real l_p1_y = m_points[l_v1.p].y();
real l_diff1 = abs(l_p1_y - l_p0_y);
if(l_diff1 < l_diff) l_diff = l_diff1;
else break;
l_v1i = l_t.v1 + i;
}
assert(l_v1i != bad_ID);
m_insert_edges(l_v0i, l_v1i);
}
for(uint i = 0; i < l_t.v1c; ++i) {
uint l_v0i = l_t.v1 + i;
vertex &l_v0 = m_vertices[l_v0i];
if(!l_v0.n) continue;
const real l_p0_y = m_points[l_v0.p].y();
uint l_v1i = bad_ID; real l_diff = infinity;
for(uint i = 0; i < l_t.v0c; ++i) {
const vertex &l_v1 = m_vertices[l_t.v0 + i];
const real l_p1_y = m_points[l_v1.p].y();
real l_diff1 = abs(l_p1_y - l_p0_y);
if(l_diff1 < l_diff) l_diff = l_diff1;
else break;
l_v1i = l_t.v0 + i;
}
assert(l_v1i != bad_ID);
m_insert_edges(l_v0i, l_v1i);
}
}
void m_insert_edges(uint _v0, uint _v1) {
vertex &l_v0 = m_vertices[_v0];
vertex &l_v1 = m_vertices[_v1];
uint l_e00i, l_e01i; m_vertex_edges(_v0, _v1, l_e00i, l_e01i);
uint l_e10i, l_e11i; m_vertex_edges(_v1, _v0, l_e10i, l_e11i);
edge &l_e00 = m_edges[l_e00i], &l_e10 = m_edges[l_e10i], l_ne0, l_ne1;
l_ne0.v0 = l_ne1.v1 = _v0; l_ne0.v1 = l_ne1.v0 = _v1;
l_ne0.ne = l_e11i; l_ne1.ne = l_e01i;
l_ne0.te = m_edges.size() + 1; l_ne1.te = m_edges.size();
l_e00.ne = m_edges.size(); l_e10.ne = m_edges.size() + 1;
m_edges.push_back(l_ne0); m_edges.push_back(l_ne1);
l_v0.n = l_v1.n = false;
}
void m_vertex_edges(uint _v0, uint _v1, uint &_e0, uint &_e1) {
const vertex &l_v0 = m_vertices[_v0];
if(m_edges[l_v0.e0].ne == l_v0.e1) {
_e0 = l_v0.e0; _e1 = l_v0.e1;
return;
}
const point &l_p0 = m_points[l_v0.p];
const vertex &l_v = m_vertices[_v1];
const point &l_p = m_points[l_v.p];
_e0 = l_v0.e0; _e1 = m_edges[_e0].ne;
while(true) {
const edge &l_e0 = m_edges[_e0], &l_e1 = m_edges[_e1];
const vertex &l_v1 = m_vertices[l_e0.v0], &l_v2 = m_vertices[l_e1.v1];
const point &l_p1 = m_points[l_v1.p], &l_p2 = m_points[l_v2.p];
point l_d = l_p - l_p0, l_d1 = l_p1 - l_p0, l_d2 = l_p2 - l_p0;
real l_a = atan2(l_d.y(), l_d.x()), l_a1 = atan2(l_d1.y(), l_d1.x()), l_a2 = atan2(l_d2.y(), l_d2.x());
real l_a01 = l_a - l_a1, l_a21 = l_a2 - l_a1;
while(l_a01 < 0) l_a01 += real(2) * pi;
while(l_a21 < 0) l_a21 += real(2) * pi;
if(l_a21 > l_a01) return;
assert(l_e1.te != bad_ID);
_e0 = l_e1.te; _e1 = m_edges[_e0].ne;
}
}
void m_close_trapezoid(uint _v, uint _e0, uint _e1) {
uint l_i = m_get_trapezoid(_e0, _e1);
if(l_i != bad_ID) {
trapezoid &l_t = m_trapezoids[l_i];
assert(l_t.v1 == bad_ID || l_t.v1 + l_t.v1c == _v);
if(l_t.v1 == bad_ID) l_t.v1 = _v;
else l_t.v1c++;
vertex &l_v = m_vertices[_v];
const edge &l_e0 = m_edges[l_v.e0], &l_e1 = m_edges[l_v.e1];
if(l_e0.v0 > _v && l_e1.v1 > _v) l_v.n = true;
}
}
uint m_get_trapezoid(uint _e0, uint _e1) const {
for(uint i = 0, s = m_trapezoids.size(); i < s; ++i) {
const trapezoid &l_t = m_trapezoids[i];
if(l_t.e0 == _e0 && l_t.e1 == _e1) return i;
}
return bad_ID;
}
uint m_get_trapezoid(uint _e) const {
for(uint i = 0, s = m_trapezoids.size(); i < s; ++i) {
const trapezoid &l_t = m_trapezoids[i];
if(l_t.e0 == _e || l_t.e1 == _e) return i;
}
return bad_ID;
}
sint m_vertex_edge_compare(uint _v, uint _e) const {
const vertex &l_v = m_vertices[_v];
const point &l_p = m_points[l_v.p];
const edge &l_e = m_edges[_e];
const vertex &l_v0 = m_vertices[l_e.v0];
const vertex &l_v1 = m_vertices[l_e.v1];
const point &l_p0 = l_e.v0 < l_e.v1 ? m_points[l_v0.p] : m_points[l_v1.p];
const point &l_p1 = l_e.v0 < l_e.v1 ? m_points[l_v1.p] : m_points[l_v0.p];
real l_cross = cross(l_p1 - l_p0, l_p - l_p0);
if(l_cross > eps) return 1;
if(l_cross < -eps) return -1;
return 0;
}
sint m_edge_edge_compare(uint _e0, uint _e1) const {
const edge &l_e0 = m_edges[_e0];
const edge &l_e1 = m_edges[_e1];
sint l_c001 = m_vertex_edge_compare(l_e0.v0, _e1);
sint l_c011 = m_vertex_edge_compare(l_e0.v1, _e1);
if(l_c001 == 0 && l_c011 == 0) return 0;
if(l_c001 <= 0 && l_c011 <= 0) return -1;
if(l_c001 >= 0 && l_c011 >= 0) return 1;
sint l_c100 = m_vertex_edge_compare(l_e1.v0, _e0);
sint l_c110 = m_vertex_edge_compare(l_e1.v1, _e0);
if(l_c100 == 0 && l_c110 == 0) return 0;
if(l_c100 <= 0 && l_c110 <= 0) return 1;
if(l_c100 >= 0 && l_c110 >= 0) return -1;
return 0;
}
};
namespace flash { /*-----------------------------------------------------------------------------*/
namespace po { /*--------------------------------------------------------------------------------*/
// shape
shape::shape(const info &_info, player &_player) :
_placed(_info, _player)
{}
shape::~shape() {
}
bool shape::render() const {
player &l_player = get_player();
renderer &l_renderer = l_player.get_renderer();
const info &l_info = get_info<info>();
static array_<real2> l_points; l_points.resize(0);
for(uint i = 0, s = l_info.point_count(); i < s; ++i) {
const real2 &l_p = l_info.get_point(i);
// l_points.push_back(l_p);
l_points.push_back(real3(l_p.x(), l_p.y(), 1) * position() * real(0.05));
}
for(uint i = 0, s = l_info.fillstyle_count(); i < s; ++i) {
const fillstyle &l_fillstyle = l_info.get_fillstyle(i);
const edges &l_edges = l_info.get_fillstyle_edges(i);
if(l_edges.empty()) continue;
triangulator::poly l_poly;
for(uint i = 0, s = l_edges.size(); i < s; ++i) {
const edge &l_edge = l_edges[i];
if(l_edge.c != bad_ID) {
struct _l { static void tesselate(const real2 &_s, const real2 &_c, const real2 &_e, array_<real2> &_points) {
const real l_tolerance = real(0.1);
real2 l_p0 = (_s + _e) * real(0.5), l_p = (l_p0 + _c) * real(0.5);
if(length2(l_p - l_p0) <= l_tolerance) { _points.push_back(_e); return; }
tesselate(_s, (_s + _c) * real(0.5), l_p, _points);
tesselate(l_p, (_c + _e) * real(0.5), _e, _points);
}};
const real2 &l_s = l_points[l_edge.s];
const real2 &l_c = l_points[l_edge.c];
const real2 &l_e = l_points[l_edge.e];
static array_<real2> l_edge_points; l_edge_points.resize(0);
_l::tesselate(l_s, l_c, l_e, l_edge_points);
l_poly.push_back(l_edge.s);
for(uint i = 0, s = l_edge_points.size() - 1; i < s; ++i) {
l_poly.push_back(l_points.size()); l_poly.push_back(l_points.size());
l_points.push_back(l_edge_points[i]);
}
l_poly.push_back(l_edge.e);
} else {
l_poly.push_back(l_edge.s); l_poly.push_back(l_edge.e);
}
}
triangulator l_triangulator;
l_triangulator.build(l_points, l_poly);
if(l_triangulator.tri_count() > 0) {
l_renderer.draw_tris(&l_points[0], l_triangulator.get_tris(), l_triangulator.tri_count(), l_fillstyle.c, r3x3_1 * real(1)/*real(0.05) * m_position*/);
}
//
for(uint i = 1, s = l_triangulator.lines.size(); i < s; i += 2) {
const real2 &l_s = l_triangulator.lines[i - 1], &l_e = l_triangulator.lines[i];
l_renderer.draw_line(l_s, l_e, l_fillstyle.c, real(0.5));
}
}
//for(uint i = 0, s = l_info.line_path_count(); i < s; ++i) {
// const path &l_path = l_info.get_line_path(i);
// const line_style &l_line_style = l_info.get_line_style(l_path.style);
// if(l_line_style.w == 0) continue;
// uint l_line_start = 0;
// std::vector<std::vector<uint> > l_polys;
// for(uint i = 0, s = l_path.edges.size(); i < s; ++i) {
// const edge &l_edge = l_path.edges[i];
// if(l_polys.empty() || l_polys.back().back() != l_edge.s) {
// l_polys.push_back(std::vector<uint>());
// l_polys.back().push_back(l_edge.s);
// }
// if(l_edge.c != bad_ID) {
// struct _l { static void tesselate(const real2 &_s, const real2 &_c, const real2 &_e, std::vector<real2> &_points) {
// const real l_tolerance = real(0.1);
// real2 l_p0 = (_s + _e) * real(0.5), l_p = (l_p0 + _c) * real(0.5);
// if(length2(l_p - l_p0) <= l_tolerance) { _points.push_back(_e); return; }
// tesselate(_s, (_s + _c) * real(0.5), l_p, _points);
// tesselate(l_p, (_c + _e) * real(0.5), _e, _points);
// }};
// const real2 &l_s = l_points[l_edge.s];
// const real2 &l_c = l_points[l_edge.c];
// const real2 &l_e = l_points[l_edge.e];
// static std::vector<real2> l_edge_points; l_edge_points.resize(0);
// _l::tesselate(l_s, l_c, l_e, l_edge_points);
// for(uint i = 0, s = l_edge_points.size() - 1; i < s; ++i) {
// l_polys.back().push_back(l_points.size());
// l_points.push_back(l_edge_points[i]);
// }
// }
// l_polys.back().push_back(l_edge.e);
// }
// triangulator l_triangulator;
// l_triangulator.build(l_points, l_polys);
// for(uint i = 0, s = l_polys.size(); i < s; ++i) {
// const std::vector<uint> &l_poly = l_polys[i];
// for(uint i = 1, s = l_poly.size(); i < s; ++i) {
// l_renderer.draw_line(l_points[l_poly[i - 1]], l_points[l_poly[i]], l_line_style.c, l_line_style.w * real(0.05));
// }
// }
//}
return true;
}
// shape::info
shape::info::info(swfstream &_s, tag::type _type) : _placed::info(ot::shape) {
fillstyle l_fillstyle; l_fillstyle.c = 0;
m_fillstyles.push_back(l_fillstyle);
m_filledges.push_back(edges());
//line_style l_line_style; l_line_style.c = 0; l_line_style.w = 0;
//m_line_styles.push_back(l_line_style);
m_rect = m_edge_rect = _s.RECT();
if(_type == tag::DefineShape4) {
m_edge_rect = _s.RECT();
uint l_reserved = _s.UB(6);
uint l_nonscalingstrokes = _s.UB(1);
uint l_scalingstrokes = _s.UB(1);
}
m_read_shape_records(_s, _type);
}
void shape::info::m_read_fill_styles(swfstream &_s, tag::type _type) {
uint l_count = _s.UI8();
if(l_count == 0xff) l_count = _s.UI16();
for(uint i = 0; i < l_count; ++i) {
fillstyle l_style;
uint l_type = _s.UI8();
switch(l_type) {
case 0x00 : {
l_style.c = (_type > tag::DefineShape2) ? _s.RGBA() : _s.RGB();
} break;
}
m_fillstyles.push_back(l_style);
m_filledges.push_back(edges());
assert(m_fillstyles.size() == m_filledges.size());
_s.align();
}
}
void shape::info::m_read_line_styles(swfstream &_s, tag::type _type) {
uint l_count = _s.UI8();
if(l_count == 0xff) l_count = _s.UI16();
for(uint i = 0; i < l_count; ++i) {
uint l_width = _s.UI16();
switch(_type) {
case tag::DefineShape :
case tag::DefineShape2 :
case tag::DefineShape3 : {
color l_color = (_type > tag::DefineShape2) ? _s.RGBA() : _s.RGB();
//line_style l_line_style; l_line_style.c = l_color; l_line_style.w = l_width;
//m_line_styles.push_back(l_line_style);
} break;
case tag::DefineShape4 : {
uint l_startcapstyle = _s.UB(2);
uint l_joinstyle = _s.UB(2);
uint l_hasfillflag = _s.UB(1);
uint l_nohscaleflag = _s.UB(1);
uint l_novscaleflag = _s.UB(1);
uint l_pixelhintingflag = _s.UB(1);
uint l_reservedflag = _s.UB(5);
uint l_noclose = _s.UB(1);
uint l_endcapstyle = _s.UB(2);
if(l_joinstyle == 2) {
uint l_miterlimitfactor = _s.UI16();
}
color l_color = l_hasfillflag == 0 ? _s.RGBA() : 0;
if(l_hasfillflag == 1) {
//
}
//line_style l_line_style; l_line_style.c = l_color; l_line_style.w = l_width;
//m_line_styles.push_back(l_line_style);
} break;
}
_s.align();
}
}
uint shape::info::m_add_point(const point &_p) {
points::iterator l_it = std::find(m_points.begin(), m_points.end(), _p);
if(l_it == m_points.end()) { m_points.push_back(_p); return m_points.size() - 1; }
return l_it - m_points.begin();
}
void shape::info::m_read_shape_records(swfstream &_s, tag::type _type) {
enum {
new_styles = 1<<4,
line_style = 1<<3,
fill_style1 = 1<<2,
fill_style0 = 1<<1,
move_to = 1<<0,
};
m_read_fill_styles(_s, _type);
m_read_line_styles(_s, _type);
uint l_fill_bits = _s.UB(4);
uint l_line_bits = _s.UB(4);
uint l_line = 0;
uint l_fill0 = 0;
uint l_fill1 = 0;
uint l_curr_point;
while(true) {
uint l_type = _s.UB(1);
if(l_type == 0) {
uint l_flags = _s.UB(5);
if(l_flags == 0) break;
if(l_flags & move_to) {
uint l_move_bits = _s.UB(5);
real l_move_x = (real)_s.SB(l_move_bits);
real l_move_y = (real)_s.SB(l_move_bits);
l_curr_point = m_add_point(real2(l_move_x, l_move_y));
}
if(l_flags & fill_style0) {
l_fill0 = _s.UB(l_fill_bits);
}
if(l_flags & fill_style1) {
l_fill1 = _s.UB(l_fill_bits);
}
if(l_flags & line_style) {
l_line = _s.UB(l_line_bits);
}
if(l_flags & new_styles) {
m_read_fill_styles(_s, _type);
m_read_line_styles(_s, _type);
l_fill_bits = _s.UB(4);
l_line_bits = _s.UB(4);
}
} else {
uint l_straight = _s.UB(1);
uint l_delta_bits = _s.UB(4) + 2;
edge l_edge; l_edge.s = l_curr_point;
if(l_straight) {
l_edge.c = bad_ID;
uint l_general_line = _s.UB(1);
uint l_vert_line = (l_general_line == 0) ? _s.UB(1) : 0;
real l_delta_x = (l_general_line == 1 || l_vert_line == 0) ? (real)_s.SB(l_delta_bits) : 0;
real l_delta_y = (l_general_line == 1 || l_vert_line == 1) ? (real)_s.SB(l_delta_bits) : 0;
l_curr_point = m_add_point(get_point(l_curr_point) + real2(l_delta_x, l_delta_y));
l_edge.e = l_curr_point;
} else {
real l_control_delta_x = (real)_s.SB(l_delta_bits);
real l_control_delta_y = (real)_s.SB(l_delta_bits);
l_curr_point = m_add_point(get_point(l_curr_point) + real2(l_control_delta_x, l_control_delta_y));
l_edge.c = l_curr_point;
real l_anchor_delta_x = (real)_s.SB(l_delta_bits);
real l_anchor_delta_y = (real)_s.SB(l_delta_bits);
l_curr_point = m_add_point(get_point(l_curr_point) + real2(l_anchor_delta_x, l_anchor_delta_y));
l_edge.e = l_curr_point;
}
assert(l_edge.s != l_edge.e);
if(l_fill0) {
m_filledges[l_fill0].push_back(l_edge);
}
if(l_fill1) {
swap(l_edge.s, l_edge.e);
m_filledges[l_fill1].push_back(l_edge);
}
//if(!m_line_paths.back().edges.empty()) {
// const real2 &l_s0 = m_points[m_line_paths.back().edges.front().s];
// const real2 &l_e0 = m_points.back();
// if(length2(l_e0 - l_s0) < eps) {
// l_edge.e = m_line_paths.back().edges.front().s;
// m_points.pop_back();
// }
//}
//m_line_paths.back().edges.push_back(l_edge);
}
}
}
} /* namespace po -------------------------------------------------------------------------------*/
} /* namespace flash ----------------------------------------------------------------------------*/
} /* namespace bk -------------------------------------------------------------------------------*/
| [
"my.mass.storage@f4697e32-284f-0410-9ba2-936c71724aef",
"[email protected]"
]
| [
[
[
1,
21
],
[
23,
34
],
[
36,
66
],
[
68,
112
],
[
114,
114
],
[
122,
131
],
[
136,
144
],
[
148,
148
],
[
153,
280
],
[
282,
297
],
[
299,
300
],
[
326,
327
],
[
333,
333
],
[
338,
423
],
[
425,
444
],
[
446,
447
],
[
449,
665
]
],
[
[
22,
22
],
[
35,
35
],
[
67,
67
],
[
113,
113
],
[
115,
121
],
[
132,
135
],
[
145,
147
],
[
149,
152
],
[
281,
281
],
[
298,
298
],
[
301,
325
],
[
328,
332
],
[
334,
337
],
[
424,
424
],
[
445,
445
],
[
448,
448
]
]
]
|
ccacfac1a5aab2184f3fd6732e3cda15fe0ad99a | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/zombie/nphysics/src/nphysics/nphytwohingejoint_main.cc | 2c203a3895a2040d91ea16635f521abace323b35 | []
| 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 | 3,697 | cc | //-----------------------------------------------------------------------------
// nphycontactjoint_main.cc
// (C) 2004 Conjurer Services, S.A.
//-----------------------------------------------------------------------------
#include "precompiled/pchnphysics.h"
#include "nphysics/nphytwohingejoint.h"
#include "nphysics/nphyjointgroup.h"
//-----------------------------------------------------------------------------
nNebulaScriptClass(nPhyTwoHingeJoint, "nphysicsjoint");
//-----------------------------------------------------------------------------
/**
Constructor.
history:
- 03-Nov-2004 Zombie created
*/
nPhyTwoHingeJoint::nPhyTwoHingeJoint()
{
this->type = TwoHinge;
}
//-----------------------------------------------------------------------------
/**
Destructor.
history:
- 03-Nov-2004 Zombie created
*/
nPhyTwoHingeJoint::~nPhyTwoHingeJoint()
{
// Empty
}
//-----------------------------------------------------------------------------
/**
Creates the join.
@param world world where the joint will exists
@param group joints group
history:
- 03-Nov-2004 Zombie created
*/
void nPhyTwoHingeJoint::CreateIn( nPhysicsWorld* world, nPhyJointGroup* group )
{
n_assert2( world, "Null pointer" );
n_assert2( group, "Null pointer" );
n_assert2( this->Id() == NoValidID, "It's already created" );
group->Add( this );
this->jointID = phyCreateTwoHingeJoint( world->Id(), group->Id() );
n_assert2( this->Id() != NoValidID, "Failed to create a contact joint" );
nPhysicsJoint::CreateIn( world, group );
}
//------------------------------------------------------------------------------
/**
Scales the object.
@param factor scale factor
history:
- 12-May-2005 Zombie created
*/
void nPhyTwoHingeJoint::Scale( const phyreal factor )
{
vector3 anchor;
this->GetFirstAnchor( anchor );
anchor *= factor;
this->SetAnchor( anchor );
}
#ifndef NGAME
//------------------------------------------------------------------------------
/**
Draws the joint.
history:
- 18-Aug-2005 Zombie created
*/
void nPhyTwoHingeJoint::Draw( nGfxServer2* server )
{
nPhysicsJoint::Draw( server );
// Drawing anchors
matrix44 model;
vector3 position;
model.scale( vector3( phy_radius_joint_anchor, phy_radius_joint_anchor, phy_radius_joint_anchor ) );
this->GetFirstAnchor( position );
model.translate( position );
server->BeginShapes();
server->DrawShape( nGfxServer2::Sphere, model, phy_color_joint_anchorA );
server->EndShapes();
this->GetSecondAnchor( position );
model.translate( position );
server->BeginShapes();
server->DrawShape( nGfxServer2::Sphere, model, phy_color_joint_anchorB );
server->EndShapes();
vector3 line[2];
this->GetFirstAnchor( line[0] );
this->GetFirstAxis( line[1] );
line[1] *= phy_length_joint_axis;
line[1] += position;
server->BeginLines();
server->DrawLines3d( line, 2, phy_color_joint_axisA );
server->EndLines();
this->GetSecondAxis( line[1] );
line[1] *= phy_length_joint_axis;
line[1] += position;
server->BeginLines();
server->DrawLines3d( line, 2, phy_color_joint_axisB );
server->EndLines();
}
#endif
//-----------------------------------------------------------------------------
// EOF
//----------------------------------------------------------------------------- | [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
]
| [
[
[
1,
156
]
]
]
|
909c22af6198b42f1836a40428f1cb5a4bfa2c9f | 71ffdff29137de6bda23f02c9e22a45fe94e7910 | /KillaCoptuz3000/src/glCallbacks.h | ee05f785bdf51f3c4cbe38192f0bfece18d0a8e9 | []
| no_license | anhoppe/killakoptuz3000 | f2b6ecca308c1d6ebee9f43a1632a2051f321272 | fbf2e77d16c11abdadf45a88e1c747fa86517c59 | refs/heads/master | 2021-01-02T22:19:10.695739 | 2009-03-15T21:22:31 | 2009-03-15T21:22:31 | 35,839,301 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,739 | h | // ***************************************************************
// glCallbacks version: 1.0 · date: 06/10/2007
// -------------------------------------------------------------
//
// -------------------------------------------------------------
// Copyright (C) 2007 - All Rights Reserved
// ***************************************************************
//
// ***************************************************************
#ifndef GL_CALLBACKS_H
#define GL_CALLBACKS_H
class CLevel;
//////////////////////////////////////////////////////////////////////////
// Help functions for the callbacks
//////////////////////////////////////////////////////////////////////////
void renderBitmapString(float t_x, float t_y, char *t_string, void *t_font);
//////////////////////////////////////////////////////////////////////////
// GL callbacks used while level is running
//////////////////////////////////////////////////////////////////////////
void setCallbackLevelPtr(CLevel* t_levelPtr);
void CLevel_timerCallback(int t_value);
void CLevel_renderScene();
void CLevel_pressKey(int t_key, int t_x, int t_y);
void CLevel_releaseKey(int t_key, int t_x, int t_y);
void CLevel_processNormalKeys(unsigned char t_key, int t_x, int t_y);
//////////////////////////////////////////////////////////////////////////
// GL callbacks used while menue is running
//////////////////////////////////////////////////////////////////////////
void CMenu_timerCallback(int t_value);
void CMenu_renderScene();
void CMenu_pressKey(int t_key, int t_x, int t_y);
void CMenu_releaseKey(int t_key, int t_x, int t_y);
void CMenu_processNormalKeys(unsigned char t_key, int t_x, int t_y);
#endif
| [
"anhoppe@9386d06f-8230-0410-af72-8d16ca8b68df",
"fabianheinemann@9386d06f-8230-0410-af72-8d16ca8b68df"
]
| [
[
[
1,
14
],
[
20,
29
],
[
33,
39
]
],
[
[
15,
19
],
[
30,
32
]
]
]
|
78bf52d7d53aac38cf885612f0f499d1ccaa55d2 | 6dac9369d44799e368d866638433fbd17873dcf7 | /src/trunk/include/network/IPacketManager.h | 99115e6b1753df82fd3a38493b1bb9239fb1e586 | []
| no_license | christhomas/fusionengine | 286b33f2c6a7df785398ffbe7eea1c367e512b8d | 95422685027bb19986ba64c612049faa5899690e | refs/heads/master | 2020-04-05T22:52:07.491706 | 2006-10-24T11:21:28 | 2006-10-24T11:21:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,099 | h | #ifndef _IPACKETMANAGER_H_
#define _IPACKETMANAGER_H_
#include <network/INetwork.h>
class ISocket;
class IPacketManager;
// A callback which can be setup to create a packet manager object
typedef IPacketManager * (*create_packet_manager_t)(void);
// A structure containing all the information
// needed to send data or recv data
struct NetworkPacket{
ISocket *socketobj; // The object who sent the data (if it's a send packet, otherwise NULL)
unsigned int length; // the length of the data segment in this packet
char data[MAX_RECV]; // the data that is being sent, or has been received
IPacketManager *manager;
NetworkPacket *prev, *next;
};
class IPacketManager{
protected:
// This method is relied upon to clear up all the allocated memory
virtual void deallocatePackets(void) = 0;
// Allocates a new cache of packets
virtual void allocatePacket(void) = 0;
// Finds the next empty packet
virtual NetworkPacket * findPacket(void) = 0;
// Copies the internal data from a another packet manager object
virtual IPacketManager & operator=(IPacketManager &pm) = 0;
public:
IPacketManager();
virtual ~IPacketManager();
// Locks access to the packet manager
virtual void lock(void) = 0;
// Unlocks access to the packet manager
virtual void unlock(void) = 0;
// Sets the amount of NetworkPackets allocated in one chunk
virtual void setCacheSize(unsigned int cache) = 0;
// Request a packet to use
virtual NetworkPacket * requestPacket(void) = 0;
// Requests the head of the linked list
virtual NetworkPacket * requestHead(void) = 0;
// Requests the tail of the linked list
virtual NetworkPacket * requestTail(void) = 0;
// Release a packet from the linked list to the app
virtual void releasePacket(NetworkPacket *packet) = 0;
// Returns control of a packet to the manager
virtual void returnPacket(NetworkPacket *packet) = 0;
// Clears the linked list and resets to a default state (all empty)
virtual void clear(void) = 0;
};
#endif // #ifndef _IPACKETMANAGER_H_ | [
"chris_a_thomas@1bf15c89-c11e-0410-aefd-b6ca7aeaabe7"
]
| [
[
[
1,
69
]
]
]
|
55d8d2be832b1cbb9c3be984e73a643a0ec91c9d | 9ef88cf6a334c82c92164c3f8d9f232d07c37fc3 | /Include/DebugLogic.h | efe8602c1653b55b1e14b1dacdc46151e2574b23 | []
| no_license | Gussoh/bismuthengine | eba4f1d6c2647d4b73d22512405da9d7f4bde88a | 4a35e7ae880cebde7c557bd8c8f853a9a96f5c53 | refs/heads/master | 2016-09-05T11:28:11.194130 | 2010-01-10T14:09:24 | 2010-01-10T14:09:24 | 33,263,368 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 590 | h | /**
* ___ _ __ __ _
* / _ )(_)__ __ _ __ __/ /_/ / ___ ___ ___ _(_)__ ___
* / _ / (_-</ ' \/ // / __/ _ \/ -_) _ \/ _ `/ / _ \/ -_)
* /____/_/___/_/_/_/\_,_/\__/_//_/\__/_//_/\_, /_/_//_/\__/
* /___/
*
* @file DebugLogic.h
*/
#pragma once
#include "NetworkManager.h"
namespace Bismuth {
/**
* Template class
*/
class DebugLogic {
public:
DebugLogic();
virtual ~DebugLogic();
Bismuth::Network::NetworkManager* createNetworkManager();
private:
};
} | [
"andreas.duchen@aefdbfa2-c794-11de-8410-e5b1e99fc78e"
]
| [
[
[
1,
30
]
]
]
|
5bfef40bb86d7c9e2df12cc2e5746dd160f7283e | 58943f35c5f6659879f41317666416c1216dbc28 | /chapter6.cpp | adfe18f9963dca5562f6e7c905213a864addf2ae | []
| no_license | abzaremba/nauka_cpp | 37c82a20acb98b62ae4bf01eb6f70c576b9aa3a4 | 1461647b3e4864bc219567e93134849029ff5cb5 | refs/heads/master | 2021-01-13T02:31:37.111733 | 2011-10-05T12:03:06 | 2011-10-05T12:03:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,142 | cpp | #include <string>
#include <iostream>
#include <vector>
#include <stdexcept>
#include "text_care.h"
#include "grade.h"
#include "Student_info.h"
#include "string_care.h"
#include <algorithm>
#include <iomanip>
using std::cin; using std::cout; using std::endl;
using std::string;
using std::getline;
using std::vector;
using std::setprecision;
using std::sort;
using std::streamsize;
using std::max;
using std::domain_error;
int main_OLD6()
{
// students who did and didn't do all their homework
vector<Student_info> did, didnt;
// read the students recods and partition them
Student_info student;
while (read(cin, student)) {
if (did_all_hw(student))
did.push_back(student);
else
didnt.push_back(student);
}
// verify that analyses will show us something
if (did.empty()) {
cout << "No student did all the homework!" << endl;
return 1;
}
if (didnt.empty()) {
cout << "Every student did all the homework!" << endl;
return 1;
}
// do the analyses
write_analysis(cout, "median", median_analysis, did, didnt);
write_analysis(cout, "average", average_analysis, did, didnt);
write_analysis(cout, "median of homework turned in", optimistic_median_analysis, did, didnt);
//string s;
//// read and store in vector of strings string_vec
//vector<string> string_vec;
//while (getline(cin, s))
// string_vec.push_back(s);
//vector<string> framed_string_vec = frame(string_vec);
//// print the concatenated vector of strings
//vector<string> concatenated_string_vec = hcat(string_vec, framed_string_vec);
// for (vector<string>::size_type i = 0; i != concatenated_string_vec.size(); ++i)
//{
// cout << concatenated_string_vec[i] << endl;
//}
//vector<Student_info> students;
//Student_info record;
//string::size_type maxlen = 0; // the length of the longest name
//// read and store all the student's data
//// invariant: students contains all the student records read so far
//// maxlen contains the length of the longest name in the students
//while (read(cin, record)) {
// // find length of the longest name
// maxlen = max (maxlen, record.name.size());
// students.push_back(record);
//}
//
//// delete records of those students who didn't pass
////std::list<Student_info> extract_fails(std::list<Student_info>& students);
//vector<Student_info> failed_students = extract_fails(students);
//// alphabetise the student records
//sort (students.begin(), students.end(), compare);
//// write the names and grades
//for (vector<Student_info>::size_type i = 0; i != students.size(); i++) {
// // write the name padded on the right to maxlen + 1 characters
// cout << students[i].name
// << string (maxlen + 1 - students[i].name.size(), ' ');
// //// compute and write the grade
// try {
// double final_grade = grade (students[i]);
// streamsize prec = cout.precision();
// cout << setprecision(3) << final_grade << setprecision(prec);
// } catch (domain_error e) {
// cout << e.what();
// }
// cout << endl;
//}
return 0;
} | [
"[email protected]"
]
| [
[
[
1,
115
]
]
]
|
c994567697739ad63950be858d5546fc9340de67 | d54d8b1bbc9575f3c96853e0c67f17c1ad7ab546 | /hlsdk-2.3-p3/singleplayer/dmc/dlls/world.cpp | 779b8d3da07b0124eada0a97a659356d8eb744b5 | []
| no_license | joropito/amxxgroup | 637ee71e250ffd6a7e628f77893caef4c4b1af0a | f948042ee63ebac6ad0332f8a77393322157fa8f | refs/heads/master | 2021-01-10T09:21:31.449489 | 2010-04-11T21:34:27 | 2010-04-11T21:34:27 | 47,087,485 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,381 | cpp | /***
*
* Copyright (c) 1996-2002, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
/*
===== world.cpp ========================================================
precaches and defs for entities and other data that must always be available.
*/
#include "extdll.h"
#include "util.h"
#include "cbase.h"
#include "nodes.h"
#include "client.h"
#include "decals.h"
#include "skill.h"
#include "effects.h"
#include "player.h"
#include "weapons.h"
#include "gamerules.h"
#include "teamplay_gamerules.h"
extern CGraph WorldGraph;
extern CBaseEntity *g_pLastSpawn;
DLL_GLOBAL edict_t *g_pBodyQueueHead;
CGlobalState gGlobalState;
extern DLL_GLOBAL int gDisplayTitle;
extern void W_Precache(void);
extern void QuakeClassicPrecache( void );
//
// This must match the list in util.h
//
DLL_DECALLIST gDecals[] = {
{ "{shot1", 0 }, // DECAL_GUNSHOT1
{ "{shot2", 0 }, // DECAL_GUNSHOT2
{ "{shot3",0 }, // DECAL_GUNSHOT3
{ "{shot4", 0 }, // DECAL_GUNSHOT4
{ "{shot5", 0 }, // DECAL_GUNSHOT5
{ "{lambda01", 0 }, // DECAL_LAMBDA1
{ "{lambda02", 0 }, // DECAL_LAMBDA2
{ "{lambda03", 0 }, // DECAL_LAMBDA3
{ "{lambda04", 0 }, // DECAL_LAMBDA4
{ "{lambda05", 0 }, // DECAL_LAMBDA5
{ "{lambda06", 0 }, // DECAL_LAMBDA6
{ "{scorch1", 0 }, // DECAL_SCORCH1
{ "{scorch2", 0 }, // DECAL_SCORCH2
{ "{blood1", 0 }, // DECAL_BLOOD1
{ "{blood2", 0 }, // DECAL_BLOOD2
{ "{blood3", 0 }, // DECAL_BLOOD3
{ "{blood4", 0 }, // DECAL_BLOOD4
{ "{blood5", 0 }, // DECAL_BLOOD5
{ "{blood6", 0 }, // DECAL_BLOOD6
{ "{yblood1", 0 }, // DECAL_YBLOOD1
{ "{yblood2", 0 }, // DECAL_YBLOOD2
{ "{yblood3", 0 }, // DECAL_YBLOOD3
{ "{yblood4", 0 }, // DECAL_YBLOOD4
{ "{yblood5", 0 }, // DECAL_YBLOOD5
{ "{yblood6", 0 }, // DECAL_YBLOOD6
{ "{break1", 0 }, // DECAL_GLASSBREAK1
{ "{break2", 0 }, // DECAL_GLASSBREAK2
{ "{break3", 0 }, // DECAL_GLASSBREAK3
{ "{bigshot1", 0 }, // DECAL_BIGSHOT1
{ "{bigshot2", 0 }, // DECAL_BIGSHOT2
{ "{bigshot3", 0 }, // DECAL_BIGSHOT3
{ "{bigshot4", 0 }, // DECAL_BIGSHOT4
{ "{bigshot5", 0 }, // DECAL_BIGSHOT5
{ "{spit1", 0 }, // DECAL_SPIT1
{ "{spit2", 0 }, // DECAL_SPIT2
{ "{bproof1", 0 }, // DECAL_BPROOF1
{ "{gargstomp", 0 }, // DECAL_GARGSTOMP1, // Gargantua stomp crack
{ "{smscorch1", 0 }, // DECAL_SMALLSCORCH1, // Small scorch mark
{ "{smscorch2", 0 }, // DECAL_SMALLSCORCH2, // Small scorch mark
{ "{smscorch3", 0 }, // DECAL_SMALLSCORCH3, // Small scorch mark
{ "{mommablob", 0 }, // DECAL_MOMMABIRTH // BM Birth spray
{ "{mommablob", 0 }, // DECAL_MOMMASPLAT // BM Mortar spray?? need decal
};
/*
==============================================================================
BODY QUE
==============================================================================
*/
#define SF_DECAL_NOTINDEATHMATCH 2048
class CDecal : public CBaseEntity
{
public:
void Spawn( void );
void KeyValue( KeyValueData *pkvd );
void EXPORT StaticDecal( void );
void EXPORT TriggerDecal( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value );
};
LINK_ENTITY_TO_CLASS( infodecal, CDecal );
// UNDONE: These won't get sent to joining players in multi-player
void CDecal :: Spawn( void )
{
if ( pev->skin < 0 || (gpGlobals->deathmatch && FBitSet( pev->spawnflags, SF_DECAL_NOTINDEATHMATCH )) )
{
REMOVE_ENTITY(ENT(pev));
return;
}
if ( FStringNull ( pev->targetname ) )
{
SetThink( StaticDecal );
// if there's no targetname, the decal will spray itself on as soon as the world is done spawning.
pev->nextthink = gpGlobals->time;
}
else
{
// if there IS a targetname, the decal sprays itself on when it is triggered.
SetThink ( SUB_DoNothing );
SetUse(TriggerDecal);
}
}
void CDecal :: TriggerDecal ( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value )
{
// this is set up as a USE function for infodecals that have targetnames, so that the
// decal doesn't get applied until it is fired. (usually by a scripted sequence)
TraceResult trace;
int entityIndex;
UTIL_TraceLine( pev->origin - Vector(5,5,5), pev->origin + Vector(5,5,5), ignore_monsters, ENT(pev), &trace );
MESSAGE_BEGIN( MSG_BROADCAST, SVC_TEMPENTITY);
WRITE_BYTE( TE_BSPDECAL );
WRITE_COORD( pev->origin.x );
WRITE_COORD( pev->origin.y );
WRITE_COORD( pev->origin.z );
WRITE_SHORT( (int)pev->skin );
entityIndex = (short)ENTINDEX(trace.pHit);
WRITE_SHORT( entityIndex );
if ( entityIndex )
WRITE_SHORT( (int)VARS(trace.pHit)->modelindex );
MESSAGE_END();
SetThink( SUB_Remove );
pev->nextthink = gpGlobals->time + 0.1;
}
void CDecal :: StaticDecal( void )
{
TraceResult trace;
int entityIndex, modelIndex;
UTIL_TraceLine( pev->origin - Vector(5,5,5), pev->origin + Vector(5,5,5), ignore_monsters, ENT(pev), &trace );
entityIndex = (short)ENTINDEX(trace.pHit);
if ( entityIndex )
modelIndex = (int)VARS(trace.pHit)->modelindex;
else
modelIndex = 0;
g_engfuncs.pfnStaticDecal( pev->origin, (int)pev->skin, entityIndex, modelIndex );
SUB_Remove();
}
void CDecal :: KeyValue( KeyValueData *pkvd )
{
if (FStrEq(pkvd->szKeyName, "texture"))
{
pev->skin = DECAL_INDEX( pkvd->szValue );
// Found
if ( pev->skin >= 0 )
return;
ALERT( at_console, "Can't find decal %s\n", pkvd->szValue );
}
else
CBaseEntity::KeyValue( pkvd );
}
// Body queue class here.... It's really just CBaseEntity
class CCorpse : public CBaseEntity
{
virtual int ObjectCaps( void ) { return FCAP_DONT_SAVE; }
};
LINK_ENTITY_TO_CLASS( bodyque, CCorpse );
static void InitBodyQue(void)
{
string_t istrClassname = MAKE_STRING("bodyque");
g_pBodyQueueHead = CREATE_NAMED_ENTITY( istrClassname );
entvars_t *pev = VARS(g_pBodyQueueHead);
// Reserve 3 more slots for dead bodies
for ( int i = 0; i < 3; i++ )
{
pev->owner = CREATE_NAMED_ENTITY( istrClassname );
pev = VARS(pev->owner);
}
pev->owner = g_pBodyQueueHead;
}
//
// make a body que entry for the given ent so the ent can be respawned elsewhere
//
// GLOBALS ASSUMED SET: g_eoBodyQueueHead
//
void CopyToBodyQue(entvars_t *pev)
{
if (pev->effects & EF_NODRAW)
return;
entvars_t *pevHead = VARS(g_pBodyQueueHead);
pevHead->angles = pev->angles;
pevHead->model = pev->model;
pevHead->modelindex = pev->modelindex;
pevHead->frame = pev->frame;
pevHead->colormap = pev->colormap;
pevHead->movetype = MOVETYPE_TOSS;
pevHead->velocity = pev->velocity;
pevHead->flags = 0;
pevHead->deadflag = pev->deadflag;
pevHead->renderfx = kRenderFxDeadPlayer;
pevHead->renderamt = ENTINDEX( ENT( pev ) );
pevHead->effects = pev->effects | EF_NOINTERP;
//pevHead->goalstarttime = pev->goalstarttime;
//pevHead->goalframe = pev->goalframe;
//pevHead->goalendtime = pev->goalendtime ;
pevHead->sequence = pev->sequence;
pevHead->animtime = pev->animtime;
UTIL_SetOrigin(pevHead, pev->origin);
UTIL_SetSize(pevHead, pev->mins, pev->maxs);
g_pBodyQueueHead = pevHead->owner;
}
CGlobalState::CGlobalState( void )
{
Reset();
}
void CGlobalState::Reset( void )
{
m_pList = NULL;
m_listCount = 0;
}
globalentity_t *CGlobalState :: Find( string_t globalname )
{
if ( !globalname )
return NULL;
globalentity_t *pTest;
const char *pEntityName = STRING(globalname);
pTest = m_pList;
while ( pTest )
{
if ( FStrEq( pEntityName, pTest->name ) )
break;
pTest = pTest->pNext;
}
return pTest;
}
// This is available all the time now on impulse 104, remove later
//#ifdef _DEBUG
void CGlobalState :: DumpGlobals( void )
{
static char *estates[] = { "Off", "On", "Dead" };
globalentity_t *pTest;
ALERT( at_console, "-- Globals --\n" );
pTest = m_pList;
while ( pTest )
{
ALERT( at_console, "%s: %s (%s)\n", pTest->name, pTest->levelName, estates[pTest->state] );
pTest = pTest->pNext;
}
}
//#endif
void CGlobalState :: EntityAdd( string_t globalname, string_t mapName, GLOBALESTATE state )
{
ASSERT( !Find(globalname) );
globalentity_t *pNewEntity = (globalentity_t *)calloc( sizeof( globalentity_t ), 1 );
ASSERT( pNewEntity != NULL );
pNewEntity->pNext = m_pList;
m_pList = pNewEntity;
strcpy( pNewEntity->name, STRING( globalname ) );
strcpy( pNewEntity->levelName, STRING(mapName) );
pNewEntity->state = state;
m_listCount++;
}
void CGlobalState :: EntitySetState( string_t globalname, GLOBALESTATE state )
{
globalentity_t *pEnt = Find( globalname );
if ( pEnt )
pEnt->state = state;
}
const globalentity_t *CGlobalState :: EntityFromTable( string_t globalname )
{
globalentity_t *pEnt = Find( globalname );
return pEnt;
}
GLOBALESTATE CGlobalState :: EntityGetState( string_t globalname )
{
globalentity_t *pEnt = Find( globalname );
if ( pEnt )
return pEnt->state;
return GLOBAL_OFF;
}
// Global Savedata for Delay
TYPEDESCRIPTION CGlobalState::m_SaveData[] =
{
DEFINE_FIELD( CGlobalState, m_listCount, FIELD_INTEGER ),
};
// Global Savedata for Delay
TYPEDESCRIPTION gGlobalEntitySaveData[] =
{
DEFINE_ARRAY( globalentity_t, name, FIELD_CHARACTER, 64 ),
DEFINE_ARRAY( globalentity_t, levelName, FIELD_CHARACTER, 32 ),
DEFINE_FIELD( globalentity_t, state, FIELD_INTEGER ),
};
int CGlobalState::Save( CSave &save )
{
int i;
globalentity_t *pEntity;
if ( !save.WriteFields( "GLOBAL", this, m_SaveData, ARRAYSIZE(m_SaveData) ) )
return 0;
pEntity = m_pList;
for ( i = 0; i < m_listCount && pEntity; i++ )
{
if ( !save.WriteFields( "GENT", pEntity, gGlobalEntitySaveData, ARRAYSIZE(gGlobalEntitySaveData) ) )
return 0;
pEntity = pEntity->pNext;
}
return 1;
}
int CGlobalState::Restore( CRestore &restore )
{
int i, listCount;
globalentity_t tmpEntity;
ClearStates();
if ( !restore.ReadFields( "GLOBAL", this, m_SaveData, ARRAYSIZE(m_SaveData) ) )
return 0;
listCount = m_listCount; // Get new list count
m_listCount = 0; // Clear loaded data
for ( i = 0; i < listCount; i++ )
{
if ( !restore.ReadFields( "GENT", &tmpEntity, gGlobalEntitySaveData, ARRAYSIZE(gGlobalEntitySaveData) ) )
return 0;
EntityAdd( MAKE_STRING(tmpEntity.name), MAKE_STRING(tmpEntity.levelName), tmpEntity.state );
}
return 1;
}
void CGlobalState::EntityUpdate( string_t globalname, string_t mapname )
{
globalentity_t *pEnt = Find( globalname );
if ( pEnt )
strcpy( pEnt->levelName, STRING(mapname) );
}
void CGlobalState::ClearStates( void )
{
globalentity_t *pFree = m_pList;
while ( pFree )
{
globalentity_t *pNext = pFree->pNext;
free( pFree );
pFree = pNext;
}
Reset();
}
void SaveGlobalState( SAVERESTOREDATA *pSaveData )
{
CSave saveHelper( pSaveData );
gGlobalState.Save( saveHelper );
}
void RestoreGlobalState( SAVERESTOREDATA *pSaveData )
{
CRestore restoreHelper( pSaveData );
gGlobalState.Restore( restoreHelper );
}
void ResetGlobalState( void )
{
gGlobalState.ClearStates();
gInitHUD = TRUE; // Init the HUD on a new game / load game
}
// moved CWorld class definition to cbase.h
//=======================
// CWorld
//
// This spawns first when each level begins.
//=======================
LINK_ENTITY_TO_CLASS( worldspawn, CWorld );
#define SF_WORLD_DARK 0x0001 // Fade from black at startup
#define SF_WORLD_TITLE 0x0002 // Display game title at startup
#define SF_WORLD_FORCETEAM 0x0004 // Force teams
extern DLL_GLOBAL BOOL g_fGameOver;
float g_flWeaponCheat;
void CWorld :: Spawn( void )
{
g_fGameOver = FALSE;
Precache( );
g_flWeaponCheat = CVAR_GET_FLOAT( "sv_cheats" ); // Is the impulse 101 command allowed?
}
void CWorld :: Precache( void )
{
g_pLastSpawn = NULL;
#if 1
CVAR_SET_STRING("sv_gravity", "800"); // 67ft/sec
CVAR_SET_STRING("sv_stepsize", "18");
#else
CVAR_SET_STRING("sv_gravity", "384"); // 32ft/sec
CVAR_SET_STRING("sv_stepsize", "24");
#endif
CVAR_SET_STRING("room_type", "0");// clear DSP
// QUAKECLASSIC
// Set various physics cvars to Quake's values
CVAR_SET_STRING("sv_friction", "4");
CVAR_SET_STRING("sv_maxspeed", "400");
CVAR_SET_STRING("sv_airaccelerate", "0.7");
// Set up game rules
if (g_pGameRules)
{
delete g_pGameRules;
}
g_pGameRules = InstallGameRules( );
//!!!UNDONE why is there so much Spawn code in the Precache function? I'll just keep it here
InitBodyQue();
// init sentence group playback stuff from sentences.txt.
// ok to call this multiple times, calls after first are ignored.
SENTENCEG_Init();
// init texture type array from materials.txt
TEXTURETYPE_Init();
// the area based ambient sounds MUST be the first precache_sounds
// player precaches
W_Precache (); // get weapon precaches
ClientPrecache();
// QUAKECLASSIC
QuakeClassicPrecache();
// sounds used from C physics code
PRECACHE_SOUND("common/null.wav"); // clears sound channels
PRECACHE_SOUND( "items/suitchargeok1.wav" );//!!! temporary sound for respawning weapons.
PRECACHE_SOUND( "items/gunpickup2.wav" );// player picks up a gun.
PRECACHE_SOUND( "common/bodydrop3.wav" );// dead bodies hitting the ground (animation events)
PRECACHE_SOUND( "common/bodydrop4.wav" );
g_Language = (int)CVAR_GET_FLOAT( "sv_language" );
if ( g_Language == LANGUAGE_GERMAN )
{
PRECACHE_MODEL( "models/germangibs.mdl" );
}
else
{
PRECACHE_MODEL( "models/hgibs.mdl" );
PRECACHE_MODEL( "models/agibs.mdl" );
}
PRECACHE_SOUND ("weapons/ric1.wav");
PRECACHE_SOUND ("weapons/ric2.wav");
PRECACHE_SOUND ("weapons/ric3.wav");
PRECACHE_SOUND ("weapons/ric4.wav");
PRECACHE_SOUND ("weapons/ric5.wav");
//
// Setup light animation tables. 'a' is total darkness, 'z' is maxbright.
//
// 0 normal
LIGHT_STYLE(0, "m");
// 1 FLICKER (first variety)
LIGHT_STYLE(1, "mmnmmommommnonmmonqnmmo");
// 2 SLOW STRONG PULSE
LIGHT_STYLE(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
// 3 CANDLE (first variety)
LIGHT_STYLE(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
// 4 FAST STROBE
LIGHT_STYLE(4, "mamamamamama");
// 5 GENTLE PULSE 1
LIGHT_STYLE(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
// 6 FLICKER (second variety)
LIGHT_STYLE(6, "nmonqnmomnmomomno");
// 7 CANDLE (second variety)
LIGHT_STYLE(7, "mmmaaaabcdefgmmmmaaaammmaamm");
// 8 CANDLE (third variety)
LIGHT_STYLE(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
// 9 SLOW STROBE (fourth variety)
LIGHT_STYLE(9, "aaaaaaaazzzzzzzz");
// 10 FLUORESCENT FLICKER
LIGHT_STYLE(10, "mmamammmmammamamaaamammma");
// 11 SLOW PULSE NOT FADE TO BLACK
LIGHT_STYLE(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
// 12 UNDERWATER LIGHT MUTATION
// this light only distorts the lightmap - no contribution
// is made to the brightness of affected surfaces
LIGHT_STYLE(12, "mmnnmmnnnmmnn");
// styles 32-62 are assigned by the light program for switchable lights
// 63 testing
LIGHT_STYLE(63, "a");
for ( int i = 0; i < ARRAYSIZE(gDecals); i++ )
gDecals[i].index = DECAL_INDEX( gDecals[i].name );
// init the WorldGraph.
WorldGraph.InitGraph();
// make sure the .NOD file is newer than the .BSP file.
if ( !WorldGraph.CheckNODFile ( ( char * )STRING( gpGlobals->mapname ) ) )
{// NOD file is not present, or is older than the BSP file.
WorldGraph.AllocNodes ();
}
else
{// Load the node graph for this level
if ( !WorldGraph.FLoadGraph ( (char *)STRING( gpGlobals->mapname ) ) )
{// couldn't load, so alloc and prepare to build a graph.
ALERT ( at_console, "*Error opening .NOD file\n" );
WorldGraph.AllocNodes ();
}
else
{
ALERT ( at_console, "\n*Graph Loaded!\n" );
}
}
if ( pev->speed > 0 )
CVAR_SET_FLOAT( "sv_zmax", pev->speed );
else
CVAR_SET_FLOAT( "sv_zmax", 4096 );
// QUAKECLASSIC: No Fades
/*
if ( pev->netname )
{
ALERT( at_aiconsole, "Chapter title: %s\n", STRING(pev->netname) );
CBaseEntity *pEntity = CBaseEntity::Create( "env_message", g_vecZero, g_vecZero, NULL );
if ( pEntity )
{
pEntity->SetThink( SUB_CallUseToggle );
pEntity->pev->message = pev->netname;
pev->netname = 0;
pEntity->pev->nextthink = gpGlobals->time + 0.3;
pEntity->pev->spawnflags = SF_MESSAGE_ONCE;
}
}
*/
// QUAKECLASSIC: No Darkness
/*
if ( pev->spawnflags & SF_WORLD_DARK )
CVAR_SET_FLOAT( "v_dark", 1.0 );
else
CVAR_SET_FLOAT( "v_dark", 0.0 );
*/
if ( pev->spawnflags & SF_WORLD_TITLE )
gDisplayTitle = TRUE; // display the game title if this key is set
else
gDisplayTitle = FALSE;
if ( pev->spawnflags & SF_WORLD_FORCETEAM )
{
CVAR_SET_FLOAT( "mp_defaultteam", 1 );
}
else
{
CVAR_SET_FLOAT( "mp_defaultteam", 0 );
}
}
//
// Just to ignore the "wad" field.
//
void CWorld :: KeyValue( KeyValueData *pkvd )
{
if ( FStrEq(pkvd->szKeyName, "skyname") )
{
// Sent over net now.
CVAR_SET_STRING( "sv_skyname", pkvd->szValue );
pkvd->fHandled = TRUE;
}
else if ( FStrEq(pkvd->szKeyName, "sounds") )
{
gpGlobals->cdAudioTrack = atoi(pkvd->szValue);
pkvd->fHandled = TRUE;
}
else if ( FStrEq(pkvd->szKeyName, "WaveHeight") )
{
// Sent over net now.
pev->scale = atof(pkvd->szValue) * (1.0/8.0);
pkvd->fHandled = TRUE;
CVAR_SET_FLOAT( "sv_wateramp", pev->scale );
}
else if ( FStrEq(pkvd->szKeyName, "MaxRange") )
{
pev->speed = atof(pkvd->szValue);
pkvd->fHandled = TRUE;
}
else if ( FStrEq(pkvd->szKeyName, "chaptertitle") )
{
pev->netname = ALLOC_STRING(pkvd->szValue);
pkvd->fHandled = TRUE;
}
else if ( FStrEq(pkvd->szKeyName, "startdark") )
{
// UNDONE: This is a gross hack!!! The CVAR is NOT sent over the client/sever link
// but it will work for single player
int flag = atoi(pkvd->szValue);
pkvd->fHandled = TRUE;
if ( flag )
pev->spawnflags |= SF_WORLD_DARK;
}
else if ( FStrEq(pkvd->szKeyName, "newunit") )
{
// Single player only. Clear save directory if set
if ( atoi(pkvd->szValue) )
CVAR_SET_FLOAT( "sv_newunit", 1 );
pkvd->fHandled = TRUE;
}
else if ( FStrEq(pkvd->szKeyName, "gametitle") )
{
if ( atoi(pkvd->szValue) )
pev->spawnflags |= SF_WORLD_TITLE;
pkvd->fHandled = TRUE;
}
else if ( FStrEq(pkvd->szKeyName, "mapteams") )
{
pev->team = ALLOC_STRING( pkvd->szValue );
pkvd->fHandled = TRUE;
}
else if ( FStrEq(pkvd->szKeyName, "defaultteam") )
{
if ( atoi(pkvd->szValue) )
{
pev->spawnflags |= SF_WORLD_FORCETEAM;
}
pkvd->fHandled = TRUE;
}
else
CBaseEntity::KeyValue( pkvd );
}
| [
"joropito@23c7d628-c96c-11de-a380-73d83ba7c083"
]
| [
[
[
1,
745
]
]
]
|
0574423461329cdf6cd0925c1a61f24248e7abd2 | 94c1c7459eb5b2826e81ad2750019939f334afc8 | /source/CTaiKlineWideNet.h | 4bb782c232b702e89bee14ce00ae8f565d7e4113 | []
| no_license | wgwang/yinhustock | 1c57275b4bca093e344a430eeef59386e7439d15 | 382ed2c324a0a657ddef269ebfcd84634bd03c3a | refs/heads/master | 2021-01-15T17:07:15.833611 | 2010-11-27T07:06:40 | 2010-11-27T07:06:40 | 37,531,026 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,900 | h | // CTaiKlineWideNet.h: interface for the CTaiKlineWideNet class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_TECHWIDENET_H__5FFBB872_DAB3_495F_82B2_93EDA6179B84__INCLUDED_)
#define AFX_TECHWIDENET_H__5FFBB872_DAB3_495F_82B2_93EDA6179B84__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CTaiShanKlineShowView;
class CTaiKlineWideNet
{
public:
void AddStockKlineDataAll(CString symbol,int stkKind, int nKlineType,bool bAll = false);
void AddStockHsFileDataAll(CString symbol,int stkKind,bool bAll = false);
void AddStockHsHistoryFileData(CString symbol,int stkKind,CString sDate);
void SetHsHistoryRequestFlag(bool bRequested);
void Request();
void ReleaseID();
void RegisterID();
int GetRequestKlineCount(CString symbol,int stkKind,bool bDay = true);
void AddStockFirst(CString symbol,int stkKind,bool m_bAutoDeletePre = true);
void AddStockHsFileData(CString symbol,int stkKind);
void AddStockKlineData(CString symbol,int stkKind,int nKlineType);
void AddStockHs(CString symbol,int stkKind,bool m_bAutoDeletePre = true);
CTaiKlineWideNet();
CTaiKlineWideNet(CTaiShanKlineShowView * pView);
virtual ~CTaiKlineWideNet();
private:
int GetRequestHsCount(CString symbol,int stkKind);
int GetRequestMin1Count(CString symbol,int stkKind);
int GetDaysToToday(Kline* pKline);
CTaiShanKlineShowView* m_pView;
CString m_symbolPre;
int m_stkKindPre;
bool m_bDayRequested;
bool m_bMin5Requested;
bool m_bMin1Requested;
bool m_bHsRequested;
bool m_bHsHistoryRequested;
CString m_sDateHistory;
static Kline* m_pKline1A0001;
static int m_nKline1A0001;
static int m_nKlineToToday;
SOCKET_ID g_socketID[3];
};
#endif // !defined(AFX_TECHWIDENET_H__5FFBB872_DAB3_495F_82B2_93EDA6179B84__INCLUDED_)
| [
"[email protected]"
]
| [
[
[
1,
62
]
]
]
|
373b6af6d61cfa72cdf9940ebdc2916810781d63 | 9420f67e448d4990326fd19841dd3266a96601c3 | / mcvr/mcvr/LookbackCall.cpp | 42fcfa43d60067fc259fbcfd09e2b714df00e029 | []
| no_license | xrr/mcvr | 4d8d7880c2fd50e41352fae1b9ede0231cf970a2 | b8d3b3c46cfddee281e099945cee8d844cea4e23 | refs/heads/master | 2020-06-05T11:59:27.857504 | 2010-02-24T19:32:21 | 2010-02-24T19:32:21 | 32,275,830 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 309 | cpp | #include "LookbackCall.h"
LookbackCall::LookbackCall(double K){
this->K = K;
}
LookbackCall::~LookbackCall(void) {}
double LookbackCall::operator ()(Trajectory* pT) {
double S = K;
for (unsigned i=0; i<pT->Size(); i++)
S = (S<pT->Get(i))?pT->Get(i):S; //update S?
return S-K>0?S-K:0;
}
| [
"romain.rousseau@fa0ec5f0-0fe6-11df-8179-3f26cfb4ba5f"
]
| [
[
[
1,
14
]
]
]
|
524b7311a8bbd10a61795ba283e3d5115797b92c | c6dca462f8e982b2a327285cf084d08fa7f27dd8 | /include/liblearning/core/train_test_pair.h | 7797146daf3f249f9d3dd7d738863bae1548b205 | []
| no_license | nagyistoce/liblearning | 2a7e94344f15c5af105974207ece68822102524b | ac0a77dce09ad72f32b2cae067f4616e49d60697 | refs/heads/master | 2021-01-01T16:59:44.689918 | 2010-08-20T12:07:22 | 2010-08-20T12:07:22 | 32,806,608 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,921 | h | #ifndef TRAIN_TEST_DATA_DESIGN_H
#define TRAIN_TEST_DATA_DESIGN_H
#include "dataset.h"
#include "cross_validation_pair.h"
class train_test_pair: public xml_seralizable
{
shared_ptr<dataset> test;
shared_ptr<dataset> train;
vector<cross_validation_pair > cross_validation_pairs;
public:
train_test_pair();
train_test_pair(const shared_ptr<dataset>& train, const shared_ptr<dataset>& test);
~train_test_pair(void);
const shared_ptr<dataset> & get_train_dataset() const;
const shared_ptr<dataset> & get_test_dataset() const;
int get_cv_folder_num() const ;
void make_cross_validation_pairs(const dataset_splitter & splitter, int folder_num);
const cross_validation_pair & get_cv_pair(int i) const ;
const vector<cross_validation_pair > & get_all_cv_pairs() const;
private:
friend class boost::serialization::access;
template<class Archive>
void save(Archive & ar, const unsigned int version) const
{
dataset * p_train = train.get();
dataset * p_test = test.get();
ar & boost::serialization::make_nvp("train_set",p_train);
ar & boost::serialization::make_nvp("test_set",p_test);
ar & boost::serialization::make_nvp("cross_validation_sets",cross_validation_pairs);
}
template<class Archive>
void load(Archive & ar, const unsigned int version)
{
dataset * p_train;
dataset * p_test;
ar & boost::serialization::make_nvp("train_set",p_train);
ar & boost::serialization::make_nvp("test_set",p_test);
train.reset(p_train);
test.reset(p_test);
ar & boost::serialization::make_nvp("cross_validation_sets",cross_validation_pairs);
}
BOOST_SERIALIZATION_SPLIT_MEMBER();
public:
virtual rapidxml::xml_node<> * encode_xml_node(rapidxml::xml_document<> & doc) const;
virtual void decode_xml_node(rapidxml::xml_node<> & node);
};
CAMP_TYPE(train_test_pair)
#endif | [
"[email protected]"
]
| [
[
[
1,
76
]
]
]
|
4cba3f06817d828c26ce643cdd91fc121acfe841 | de0881d85df3a3a01924510134feba2fbff5b7c3 | /addons/ofxGui/ofxGui.cpp | 217882129ec968f3f2bec3494f0a9b18bb3e74da | []
| no_license | peterkrenn/ofx-dev | 6091def69a1148c05354e55636887d11e29d6073 | e08e08a06be6ea080ecd252bc89c1662cf3e37f0 | refs/heads/master | 2021-01-21T00:32:49.065810 | 2009-06-26T19:13:29 | 2009-06-26T19:13:29 | 146,543 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,118 | cpp | /*
* ofxGui.cpp
* openFrameworks
*
* Created by Stefan Kirch on 18.06.08.
* Copyright 2008 alphakanal. All rights reserved.
*
*/
// ----------------------------------------------------------------------------------------------------
#include "ofxGui.h"
// ----------------------------------------------------------------------------------------------------
ofxGui* ofxGui::Instance(ofxGuiListener* listener)
{
static ofxGui gui(listener);
return &gui;
}
// ----------------------------------------------------------------------------------------------------
ofxGui::ofxGui(ofxGuiListener* listener)
{
mIsActive = false;
mDoUpdate = false;
mXmlDone = true;
mGlobals = ofxGuiGlobals::Instance();
mGlobals->mListener = listener;
}
// ----------------------------------------------------------------------------------------------------
void ofxGui::update(int parameterId, int type, void* data, int length)
{
if(mIsActive || mDoUpdate)
{
ofxGuiObject* tmpObj;
bool handled;
for(int i = 0; i < mObjects.size(); i++)
{
tmpObj = (ofxGuiObject*)mObjects.at(i);
handled = tmpObj->update(parameterId, type, data, length);
if(handled)
break;
}
}
}
// ----------------------------------------------------------------------------------------------------
void ofxGui::draw()
{
if(mIsActive)
{
ofEnableAlphaBlending();
ofxGuiObject* tmpObj;
for(int i = 0; i < mObjects.size(); i++)
{
tmpObj = (ofxGuiObject*)mObjects.at(i);
tmpObj->draw();
}
ofDisableAlphaBlending();
}
}
// ----------------------------------------------------------------------------------------------------
void ofxGui::activate(bool activate)
{
mIsActive = activate;
}
// ----------------------------------------------------------------------------------------------------
void ofxGui::forceUpdate(bool update)
{
mDoUpdate = update;
}
// ----------------------------------------------------------------------------------------------------
void ofxGui::keyPressed(int key)
{
}
// ----------------------------------------------------------------------------------------------------
void ofxGui::keyReleased(int key)
{
}
// ----------------------------------------------------------------------------------------------------
void ofxGui::mouseDragged(int x, int y, int button)
{
if(mIsActive)
{
ofxGuiObject* tmpObj;
bool handled;
for(int i = 0; i < mObjects.size(); i++)
{
tmpObj = (ofxGuiObject*)mObjects.at(i);
handled = tmpObj->mouseDragged(x, y, button);
if(handled)
break;
}
}
}
// ----------------------------------------------------------------------------------------------------
void ofxGui::mousePressed(int x, int y, int button)
{
if(mIsActive)
{
ofxGuiObject* tmpObj;
bool handled;
for(int i = 0; i < mObjects.size(); i++)
{
tmpObj = (ofxGuiObject*)mObjects.at(i);
handled = tmpObj->mousePressed(x, y, button);
if(handled)
break;
}
}
}
/*
void ofxGui::XmousePressed(int x, int y, int button)
{
if(mIsActive)
{
ofxGuiObject* tmpObj;
bool handled;
for(int i = 0; i < mObjects.size(); i++)
{
tmpObj = (ofxGuiObject*)mObjects.at(i);
handled = tmpObj->mousePressed(x, y, button);
if(handled)
break;
}
}
}
*/
// ----------------------------------------------------------------------------------------------------
void ofxGui::mouseReleased(int x, int y, int button)
{
if(mIsActive)
{
ofxGuiObject* tmpObj;
for(int i = 0; i < mObjects.size(); i++)
{
tmpObj = (ofxGuiObject*)mObjects.at(i);
tmpObj->mouseReleased(x, y, button);
}
}
}
// ----------------------------------------------------------------------------------------------------
ofxGuiPanel* ofxGui::addPanel(int id, string name, int x, int y, int border, int spacing)
{
ofxGuiPanel* newPanel = new ofxGuiPanel();
newPanel->init(id, name, x, y, border, spacing);
mObjects.push_back(newPanel);
return newPanel;
}
// ----------------------------------------------------------------------------------------------------
bool ofxGui::buildFromXml(string file)
{
if(!mXmlDone)
return false;
if(!mGlobals->mXml.loadFile(file))
return false;
int numberOfTags = mGlobals->mXml.getNumTags("UI");
if(numberOfTags != 1)
return false;
mObjects.clear();
mXmlDone = false;
mGlobals->mXmlfile = file;
mGlobals->mXml.pushTag("UI", 0);
mIsActive = mGlobals->mXml.getValue("ISACTIVE", 0);
mDoUpdate = mGlobals->mXml.getValue("DOUPDATE", 0);
mGlobals->buildFromXml();
numberOfTags = mGlobals->mXml.getNumTags("OBJECT");
if(numberOfTags > 0)
{
for(int i = 0; i < numberOfTags; i++)
{
mGlobals->mXml.pushTag("OBJECT", i);
int id = mGlobals->mXml.getValue("ID", 0);
string type = mGlobals->mXml.getValue("TYPE", "");
string name = mGlobals->mXml.getValue("NAME", "");
int x = mGlobals->mXml.getValue("LEFT", 0);
int y = mGlobals->mXml.getValue("TOP", 0);
int border = mGlobals->mXml.getValue("BORDER", 0);
int spacing = mGlobals->mXml.getValue("SPACING", 0);
if(type == "PANEL")
{
ofxGuiPanel* panel = addPanel(id, name, x, y, border, spacing);
panel->buildFromXml();
}
mGlobals->mXml.popTag();
}
}
mGlobals->mXml.popTag();
mXmlDone = true;
return true;
}
// ----------------------------------------------------------------------------------------------------
void ofxGui::saveToXml(string file)
{
if(!mXmlDone)
return;
mXmlDone = false;
mGlobals->mXml.clear();
int id = mGlobals->mXml.addTag("UI");
mGlobals->mXml.setValue("UI:VERSION", OFXGUI_VERSION, id);
mGlobals->mXml.setValue("UI:ISACTIVE", mIsActive, id);
mGlobals->mXml.setValue("UI:DOUPDATE", mDoUpdate, id);
mGlobals->mXml.pushTag("UI", id);
mGlobals->saveToXml();
ofxGuiObject* tmpObj;
for(int i = 0; i < mObjects.size(); i++)
{
tmpObj = (ofxGuiObject*)mObjects.at(i);
tmpObj->saveToXml();
}
mGlobals->mXml.popTag();
mGlobals->mXml.saveFile(file);
mXmlDone = true;
}
// ----------------------------------------------------------------------------------------------------
| [
"[email protected]"
]
| [
[
[
1,
289
]
]
]
|
34a05df59b58fc75cce01d4dc98740a8d95c3e20 | 7dd2dbb15df45024e4c3f555da6d9ca6fc2c4d8b | /maelstrom/Forms/textinputdialog.cpp | c12814a53d2bd62d6df30850e38a4d3da3bde103 | []
| no_license | wangscript/maelstrom-editor | c9f761e1f9e5f4e64d7e37834a7a63e04f57ae31 | 5bfab31bf444f44b9f8209f4deaed8715c305426 | refs/heads/master | 2021-01-10T01:37:00.619456 | 2011-11-21T23:17:08 | 2011-11-21T23:17:08 | 50,160,495 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 779 | cpp | #include "textinputdialog.h"
#include "ui_textinputdialog.h"
#include <QPushButton>
TextInputDialog::TextInputDialog(const QString title, const QString message, bool allowEmpty, QWidget *parent) :
QDialog(parent),
ui(new Ui::TextInputDialog)
{
ui->setupUi(this);
this->setWindowTitle(title);
this->ui->labelMessage->setText(message);
if(!allowEmpty)
connect(this->ui->lineEdit, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
}
TextInputDialog::~TextInputDialog()
{
delete ui;
}
void TextInputDialog::textChanged()
{
this->ui->buttonBox->buttons().at(0)->setEnabled(!this->ui->lineEdit->text().isEmpty());
}
QString TextInputDialog::getText() const
{
return this->ui->lineEdit->text();
}
| [
"[email protected]"
]
| [
[
[
1,
31
]
]
]
|
d1ff4a1ece3db81fece24ff90c99fc76c0bff901 | af260b99d9f045ac4202745a3c7a65ac74a5e53c | /trunk/engine/src/core/FixedStr.cpp | dab10a30fcb3c32670640d0109e1514044d92a9c | []
| no_license | BackupTheBerlios/snap-svn | 560813feabcf5d01f25bc960d474f7e218373da0 | a99b5c64384cc229e8628b22f3cf6a63a70ed46f | refs/heads/master | 2021-01-22T09:43:37.862180 | 2008-02-17T15:50:06 | 2008-02-17T15:50:06 | 40,819,397 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,392 | cpp | //
// File : $RCSfile: $
// $Workfile: FixedStr.cpp $
// Version : $Revision: 3 $
// $Author: Aviad $
// $Date: 2/12/04 7:54 $
// Description :
// The Core library contains contains basic definitions and classes
// which are useful to any highly-portable applications
//
// Author:
// Aviad Rozenhek (mailto:[email protected]) 2003-2004
//
// written for the SeedSearcher program.
// for details see www.huji.ac.il/~hoan
// and also http://www.cs.huji.ac.il/~nirf/Abstracts/BGF1.html
//
// this file and as well as its library are released for academic research
// only. the LESSER GENERAL PUBLIC LICENSE (LPGL) license
// as well as any other restrictions as posed by the computational biology lab
// and the library authors appliy.
//
#include "FixedStr.h"
#include <stdio.h>
#include <string.h>
const char FixedStr::suffix [] = "...";
FixedStr::FixedStr (char* inBuffer, Str::Size inCapacity, bool initialized)
: _length (0),
_capacity (inCapacity - 1), // we always end with a null
_buffer (inBuffer),
_onOverflow (FixedStr::onOverflow)
{
debug_mustbe (_buffer);
if (initialized) {
//
// the string is supposed to be NULL terminated
_length = strlen (_buffer);
debug_mustbe (_length <= _capacity);
}
}
void FixedStr::setEOS()
{
debug_mustbe(_length <= _capacity);
_buffer [_length] = 0;
}
void FixedStr::onOverflow(FixedStr& inStr)
{
int capacity = inStr.capacity();
debug_mustbe (inStr.length() == capacity);
if (capacity > 0) {
char* buffer = const_cast <char*>(inStr.getChars());
int suffixToCopy = tmin <int> (capacity, sizeof (suffix) - 1);
memcpy (buffer + capacity - suffixToCopy, suffix, suffixToCopy);
buffer [capacity] = 0;
}
}
void FixedStr::set (const Str& in)
{
if (in.length () <= _capacity) {
//
// the _buffer has enough space for the entire string
_length = in.length ();
memcpy (_buffer, in.getChars (), _length);
setEOS ();
}
else {
//
// not enough place in the _buffer for the entire string
memcpy (_buffer, in.getChars (), _capacity);
_length = _capacity;
_onOverflow(*this);
}
}
void FixedStr::set_va (const char* format, ...)
{
va_list marker;
va_start (marker, format);
set_va (VAList (marker), format);
va_end (marker);
}
#if (ENV_COMPILER==ENV_MICROSOFT)
# define VSNPRINT _vsnprintf
#else
# define VSNPRINT vsnprintf
#endif
void FixedStr::set_va (VAList marker, const char* format)
{
va_list vamarker;
marker.get (vamarker);
int written = VSNPRINT (_buffer, _capacity, format, vamarker);
if (written == -1) {
//
// not enough place in the _buffer for the entire string
_length = _capacity;
_onOverflow(*this);
}
else {
//
// the _buffer has enough space for the entire string
_length = written;
setEOS ();
}
}
void FixedStr::append (char c)
{
if (_length < _capacity) {
_buffer [_length++] = c;
setEOS ();
}
else {
debug_mustbe (_length == _capacity);
_onOverflow(*this);
}
}
void FixedStr::append (const Str& in)
{
debug_mustbe (_length >= 0);
debug_mustbe (in.length () >= 0);
int in_length = in.length ();
if ((_length + in_length) <= _capacity) {
//
// the _buffer has enough space for the entire string
memcpy (_buffer + _length, in.getChars (), in_length);
_length += in_length;
setEOS ();
}
else {
//
// not enough place in the _buffer for the entire string
int toCopy = tmax (_capacity - _length, 0);
memcpy (_buffer + _length, in.getChars (), toCopy);
_length += toCopy;
_onOverflow (*this);
}
}
void FixedStr::append_va (const char* format, ...)
{
va_list marker;
va_start (marker, format);
append_va (VAList (marker), format);
va_end (marker);
}
void FixedStr::append_va (VAList marker, const char* format)
{
va_list vamarker;
marker.get (vamarker);
int written = VSNPRINT(_buffer + _length, _capacity - _length, format, vamarker);
if (written == -1) {
//
// not enough place in the _buffer for the entire string
_length = _capacity;
_onOverflow(*this);
}
else {
//
// the _buffer has enough space for the entire string
_length += written;
setEOS ();
}
}
Str::Size FixedStr::length () const
{
return _length;
}
char FixedStr::getCharAt (Str::Index index) const
{
debug_mustbe (index >=0);
debug_mustbe (index <= _capacity);
return _buffer [index];
}
char& FixedStr::getCharAt (Str::Index index)
{
debug_mustbe (index >=0);
debug_mustbe (index <= _capacity);
return _buffer [index];
}
void FixedStr::setCharAt (Str::Index index, char c)
{
debug_mustbe (index >=0);
debug_mustbe (index <= _capacity);
_buffer [index] = c;
}
Str FixedStr::getStr () const
{
return Str (_buffer, 0, _length);
}
FixedStr& FixedStr::operator = (const Str& in)
{
set (in);
return *this;
}
| [
"aviadr1@1f8b7f26-7806-0410-ba70-a23862d07478"
]
| [
[
[
1,
222
]
]
]
|
e8a641bec6d93977ac012b93ee4c1da68885d86e | 15469da4f39e1632c21ac81c52f91fff572368fc | /OpenCL/src/oclGPUProcessor/src/tmp.cpp | 250cadc1760e77e20b92b829e17a9cd3bec2d797 | []
| no_license | mateuszpruchniak/gpuprocessor | b855d47fdeaa28f0a2b5270fe7cd4232f1f4fbf9 | 9bdaf28e307b375cee3677ea7d1210b9ead88553 | refs/heads/master | 2020-05-02T19:07:37.264631 | 2010-11-22T12:42:47 | 2010-11-22T12:42:47 | 709,566 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,569 | cpp |
//__kernel void ckRGB2HSV(__global uchar4* ucSource,
// __local uchar4* ucLocalData, int iLocalPixPitch,
// unsigned int uiImageWidth, unsigned int uiDevImageHeight)
//{
//
// int iImagePosX = get_global_id(0);
// int iDevYPrime = get_global_id(1) - 1; // Shift offset up 1 radius (1 row) for reads
// int iDevGMEMOffset = mul24(iDevYPrime, (int)get_global_size(0)) + iImagePosX;
//
// uchar4 pix = ucSource[iDevGMEMOffset];
// float r = (float)pix.z/255;
// float g = (float)pix.y/255;
// float b = (float)pix.x/255;
//
// float h;
// float s;
// float v;
//
// float max = b;
// if (max < g) max = g;
// if (max < r) max = r;
// float min = b;
// if (min > g) min = g;
// if (min > r) min = r;
//
// float delta;
// v = max; // v
// delta = max - min;
//
// if( max != 0 )
// s = delta / max; // s
// else {
// // r = g = b = 0 // s = 0, v is undefined
// s = 0;
// h = -1;
// return;
// }
// if( r == max )
// h = ( g - b ) / delta; // between yellow &magenta
// else if( g == max )
// h = 2 + ( b - r ) / delta; // between cyan & yellow
// else
// h = 4 + ( r - g ) / delta; // between magenta & cyan
// h = 60; // degrees
// if( h < 0 )
// h += 360;
//
// pix.z = h;
// pix.y = s;
// pix.x = v;
//
// // Write out to GMEM with restored offset
// if((iDevYPrime < uiDevImageHeight) && (iImagePosX < uiImageWidth))
// {
// setData(ucSource,pix.x ,pix.y, pix.z, iDevGMEMOffset );
// }
//}
| [
"mateusz@ubuntu.(none)"
]
| [
[
[
1,
59
]
]
]
|
387192496b4766a771e4738b5077370c5cd780e0 | df5277b77ad258cc5d3da348b5986294b055a2be | /GameEngineV0.35/Source/ConfigReader.hpp | 3f02495605401ac1acf85abdaedaee139cb53daa | []
| no_license | beentaken/cs260-last2 | 147eaeb1ab15d03c57ad7fdc5db2d4e0824c0c22 | 61b2f84d565cc94a0283cc14c40fb52189ec1ba5 | refs/heads/master | 2021-03-20T16:27:10.552333 | 2010-04-26T00:47:13 | 2010-04-26T00:47:13 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,052 | hpp | /**************************************************************************************************/
/*!
@file Main.cpp
@author Robert Onulak
@author Justin Keane
@par email: robert.onulak@@digipen.edu
@par email: justin.keane@@digipen.edu
@par Course: CS260
@par Assignment #3
----------------------------------------------------------------------------------------------------
@attention © Copyright 2010: DigiPen Institute of Technology (USA). All Rights Reserved.
*/
/**************************************************************************************************/
#pragma once
#include <string> // std::string
/// Reads in the config information
struct Config
{
explicit Config( const char *configname );
std::string username_; ///< Client's user name displayed for chat purposes.
std::string ip_; ///< Server IP address.
unsigned short port_; ///< Server Port address.
struct PortRange
{
unsigned short low_;
unsigned short high_;
} range_;
};
| [
"ProstheticMind43@af704e40-745a-32bd-e5ce-d8b418a3b9ef"
]
| [
[
[
1,
37
]
]
]
|
c4b56d12d573cec2043adccaaaaf558c461106fd | 7476d2c710c9a48373ce77f8e0113cb6fcc4c93b | /vaultserver/Script.h | 25924a6e1c08a552bcf02ff20798d846f8634e3d | []
| no_license | CmaThomas/Vault-Tec-Multiplayer-Mod | af23777ef39237df28545ee82aa852d687c75bc9 | 5c1294dad16edd00f796635edaf5348227c33933 | refs/heads/master | 2021-01-16T21:13:29.029937 | 2011-10-30T21:58:41 | 2011-10-30T22:00:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,763 | h | #ifndef SCRIPT_H
#define SCRIPT_H
#ifdef __WIN32__
#include <windows.h>
#else
#include <dlfcn.h>
#endif
#include <vector>
#include <string>
#include "boost/any.hpp"
#include "ScriptFunction.h"
#include "Public.h"
#include "PAWN.h"
#include "Dedicated.h"
#include "../API.h"
#include "../Utils.h"
#include "../vaultmp.h"
#include "../VaultException.h"
#ifdef __WIN32__
#define GetScriptCallback(a,b,c) c = (a) GetProcAddress((HINSTANCE)this->handle,b); \
if (!c) throw VaultException("Script callback not found: %s", b);
#define SetScriptFunction(a,b) *((unsigned int*)(GetProcAddress((HINSTANCE)this->handle,a)?GetProcAddress((HINSTANCE)this->handle,a):throw VaultException("Script function pointer not found: %s", a)))=(unsigned int)b;
#else
#define GetScriptCallback(a,b,c) c = (a) dlsym(this->handle,b); \
if (!c) throw VaultException("Script callback not found: %s", b);
#define SetScriptFunction(a,b) *((unsigned int*)(dlsym(this->handle,a)?dlsym(this->handle,a):throw VaultException("Script function pointer not found: %s", a)))=(unsigned int)b;
#endif
using namespace std;
using namespace Values;
typedef void ( *fexec )();
typedef bool ( *fOnClientAuthenticate )( string, string );
typedef void ( *fOnPlayerDisconnect )( NetworkID, unsigned char );
typedef unsigned int ( *fOnPlayerRequestGame )( NetworkID );
typedef void ( *fOnSpawn )( NetworkID );
typedef void ( *fOnCellChange )( NetworkID, unsigned int );
typedef void ( *fOnActorValueChange )( NetworkID, unsigned char, double );
typedef void ( *fOnActorBaseValueChange )( NetworkID, unsigned char, double );
typedef void ( *fOnActorAlert )( NetworkID, bool );
typedef void ( *fOnActorSneak )( NetworkID, bool );
typedef void ( *fOnActorDeath )( NetworkID );
/**
* \brief Maintains communication with a script
*
* A script can be either a C++ or PAWN script
*/
class Script
{
private:
Script( char* path );
~Script();
static vector<Script*> scripts;
static void GetArguments( vector<boost::any>& params, va_list args, string def );
void* handle;
bool cpp_script;
fexec exec;
fOnClientAuthenticate _OnClientAuthenticate;
fOnPlayerDisconnect _OnPlayerDisconnect;
fOnPlayerRequestGame _OnPlayerRequestGame;
fOnSpawn _OnSpawn;
fOnCellChange _OnCellChange;
fOnActorValueChange _OnActorValueChange;
fOnActorBaseValueChange _OnActorBaseValueChange;
fOnActorAlert _OnActorAlert;
fOnActorSneak _OnActorSneak;
fOnActorDeath _OnActorDeath;
Script( const Script& );
Script& operator=( const Script& );
public:
static void LoadScripts( char* scripts, char* base );
static void UnloadScripts();
static NetworkID CreateTimer( ScriptFunc timer, unsigned int interval );
static NetworkID CreateTimerEx( ScriptFunc timer, unsigned int interval, string def, ... );
static NetworkID CreateTimerPAWN( ScriptFuncPAWN timer, AMX* amx, unsigned int interval );
static NetworkID CreateTimerPAWNEx( ScriptFuncPAWN timer, AMX* amx, unsigned int interval, string def, const vector<boost::any>& args );
static void KillTimer( NetworkID id );
static void MakePublic( ScriptFunc _public, string name, string def );
static void MakePublicPAWN( ScriptFuncPAWN _public, AMX* amx, string name, string def );
static unsigned long long CallPublic( string name, ... );
static unsigned long long CallPublicPAWN( string name, const vector<boost::any>& args );
static bool OnClientAuthenticate( string name, string pwd );
static void OnPlayerDisconnect( FactoryObject reference, unsigned char reason );
static unsigned int OnPlayerRequestGame( FactoryObject reference );
static void OnCellChange( FactoryObject reference, unsigned int cell );
static void OnActorValueChange( FactoryObject reference, unsigned char index, bool base, double value );
static void OnActorAlert( FactoryObject reference, bool alerted );
static void OnActorSneak( FactoryObject reference, bool sneaking );
static unsigned int GetReference( NetworkID id );
static unsigned int GetBase( NetworkID id );
static string GetName( NetworkID id );
static void GetPos( NetworkID id, double& X, double& Y, double& Z );
static void GetAngle( NetworkID id, double& X, double& Y, double& Z );
static unsigned int GetCell( NetworkID id );
static double GetActorValue( NetworkID id, unsigned char index );
static double GetActorBaseValue( NetworkID id, unsigned char index );
static unsigned char GetActorMovingAnimation( NetworkID id );
static bool GetActorAlerted( NetworkID id );
static bool GetActorSneaking( NetworkID id );
static bool GetActorDead( NetworkID id );
static bool IsActorJumping( NetworkID id );
};
#endif
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
2
],
[
4,
4
],
[
8,
18
],
[
20,
24
],
[
26,
28
],
[
30,
35
],
[
47,
55
],
[
120,
123
]
],
[
[
3,
3
],
[
5,
7
],
[
19,
19
],
[
25,
25
],
[
29,
29
],
[
36,
46
],
[
56,
119
]
]
]
|
f1ca121767e7067e658fc257220eb368d9da63e9 | dbdd79d28ebe34de3aa6d2cedf0d24310b3d8f9a | /Dependencies/OgreMax/OgreMaxUtilities.cpp | 0eb9bae0c9e91ca04239ec769a869fa44d3d015d | [
"WTFPL"
]
| permissive | sevas/ogre-npr | 5ade1846ca26ed5d0f9a78eb7e7356d1c2a69543 | b3e1219ac4ec3ad63ae9c7e4b4118bfc59c72c2b | refs/heads/master | 2021-01-20T23:17:11.678766 | 2010-01-24T17:22:10 | 2010-01-24T17:22:10 | 400,949 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 45,019 | cpp | /*
* OgreMax Viewer and WinViewer - Ogre3D-based viewers for .scene and .mesh files
* Copyright 2009 AND Entertainment
*
* This code is available under the OgreMax Free License:
* -You may use this code for any purpose, commercial or non-commercial.
* -If distributing derived works (that use this source code) in binary or source code form,
* you must give the following credit in your work's end-user documentation:
* "Portions of this work provided by OgreMax (www.ogremax.com)"
*
* AND Entertainment assumes no responsibility for any harm caused by using this code.
*
* The OgreMax Viewer and WinViewer were released at www.ogremax.com
*/
//Includes---------------------------------------------------------------------
#include "OgreMaxUtilities.hpp"
#include "OgreMaxScene.hpp"
#include <OgreEntity.h>
#include <OgreSubEntity.h>
#include <OgrePlatform.h>
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#include <wtypes.h>
#undef min
#endif
using namespace Ogre;
using namespace OgreMax;
using namespace OgreMax::Types;
//Implementation---------------------------------------------------------------
void OgreMaxUtilities::LoadXmlDocument(const String& fileName, TiXmlDocument& document, const String& resourceGroupName)
{
//Open the file
DataStreamPtr stream = ResourceGroupManager::getSingleton().openResource(fileName, resourceGroupName);
if (stream.isNull())
{
StringUtil::StrStreamType errorMessage;
errorMessage << "Could not open XML file: " << fileName;
OGRE_EXCEPT
(
Exception::ERR_FILE_NOT_FOUND,
errorMessage.str(),
"OgreMaxUtilities::LoadXmlDocument"
);
}
//Get the file contents
String data = stream->getAsString();
//Parse the XML document
document.Parse(data.c_str());
stream.setNull();
if (document.Error())
{
StringUtil::StrStreamType errorMessage;
errorMessage << "There was an error with the XML file: " << fileName;
OGRE_EXCEPT
(
Exception::ERR_INVALID_STATE,
errorMessage.str(),
"OgreMaxUtilities::LoadXmlDocument"
);
}
}
void OgreMaxUtilities::LoadXYZ(const TiXmlElement* objectElement, Vector3& xyz)
{
xyz.x = GetRealAttribute(objectElement, "x", 0);
xyz.y = GetRealAttribute(objectElement, "y", 0);
xyz.z = GetRealAttribute(objectElement, "z", 0);
}
Vector3 OgreMaxUtilities::LoadXYZ(const TiXmlElement* objectElement)
{
Vector3 xyz;
LoadXYZ(objectElement, xyz);
return xyz;
}
ColourValue OgreMaxUtilities::LoadColor(const TiXmlElement* objectElement)
{
ColourValue color;
color.r = GetRealAttribute(objectElement, "r", 0);
color.g = GetRealAttribute(objectElement, "g", 0);
color.b = GetRealAttribute(objectElement, "b", 0);
color.a = GetRealAttribute(objectElement, "a", 1);
return color;
}
Plane OgreMaxUtilities::LoadPlane(const TiXmlElement* objectElement)
{
Plane plane;
plane.normal.x = GetRealAttribute(objectElement, "x", 0);
plane.normal.y = GetRealAttribute(objectElement, "y", 0);
plane.normal.z = GetRealAttribute(objectElement, "z", 0);
plane.d = GetRealAttribute(objectElement, "d", 0);
return plane;
}
Quaternion OgreMaxUtilities::LoadRotation(const TiXmlElement* objectElement)
{
Quaternion rotation = Quaternion::IDENTITY;
if (objectElement->Attribute("qx") != 0)
{
//The rotation is specified as a quaternion
rotation.x = GetRealAttribute(objectElement, "qx", 0);
rotation.y = GetRealAttribute(objectElement, "qy", 0);
rotation.z = GetRealAttribute(objectElement, "qz", 0);
rotation.w = GetRealAttribute(objectElement, "qw", 0);
}
else if (objectElement->Attribute("axisX") != 0)
{
//The rotation is specified as an axis and angle
Real angle = GetRealAttribute(objectElement, "angle", 0);
Vector3 axis;
axis.x = GetRealAttribute(objectElement, "axisX", 0);
axis.y = GetRealAttribute(objectElement, "axisY", 0);
axis.z = GetRealAttribute(objectElement, "axisZ", 0);
//Convert the angle and axis into the rotation quaternion
rotation.FromAngleAxis(Radian(angle), axis);
}
else if (objectElement->Attribute("angleX") != 0)
{
//Assume the rotation is specified as three Euler angles
Vector3 euler;
euler.x = GetRealAttribute(objectElement, "angleX", 0);
euler.y = GetRealAttribute(objectElement, "angleY", 0);
euler.z = GetRealAttribute(objectElement, "angleZ", 0);
String order = GetStringAttribute(objectElement, "order");
//Convert Euler angles to a matrix
Matrix3 rotationMatrix;
if (order.length() < 2)
rotationMatrix.FromEulerAnglesXYZ(Radian(euler.x), Radian(euler.y), Radian(euler.z));
else
{
if (order[0] == 'x')
{
if (order[1] == 'y')
rotationMatrix.FromEulerAnglesXYZ(Radian(euler.x), Radian(euler.y), Radian(euler.z));
else
rotationMatrix.FromEulerAnglesXZY(Radian(euler.x), Radian(euler.y), Radian(euler.z));
}
else if (order[0] == 'y')
{
if (order[1] == 'x')
rotationMatrix.FromEulerAnglesYXZ(Radian(euler.x), Radian(euler.y), Radian(euler.z));
else
rotationMatrix.FromEulerAnglesYZX(Radian(euler.x), Radian(euler.y), Radian(euler.z));
}
else
{
if (order[1] == 'x')
rotationMatrix.FromEulerAnglesZXY(Radian(euler.x), Radian(euler.y), Radian(euler.z));
else
rotationMatrix.FromEulerAnglesZYX(Radian(euler.x), Radian(euler.y), Radian(euler.z));
}
}
//Convert the matrix into the rotation quaternion
rotation.FromRotationMatrix(rotationMatrix);
}
return rotation;
}
FloatRect OgreMaxUtilities::LoadFloatRectangle(const TiXmlElement* objectElement)
{
FloatRect rect;
rect.left = GetRealAttribute(objectElement, "left", 0);
rect.top = GetRealAttribute(objectElement, "top", 0);
rect.right = GetRealAttribute(objectElement, "right", 0);
rect.bottom = GetRealAttribute(objectElement, "bottom", 0);
return rect;
}
void OgreMaxUtilities::LoadBufferUsage(const TiXmlElement* objectElement, HardwareBuffer::Usage& usage, bool& shadowed)
{
String usageText = GetStringAttribute(objectElement, "usage");
usage = usageText.empty() ? HardwareBuffer::HBU_STATIC_WRITE_ONLY : ParseHardwareBufferUsage(usageText);
shadowed = GetBoolAttribute(objectElement, "useShadow", true);
}
void OgreMaxUtilities::LoadBoundingVolume(const TiXmlElement* objectElement, BoundingVolume& volume)
{
String type = OgreMaxUtilities::GetStringAttribute(objectElement, "type");
volume.type = ParseBoundingVolumeType(type);
volume.sphereRadius = OgreMaxUtilities::GetRealAttribute(objectElement, "radius", 0);
int faceCount = OgreMaxUtilities::GetIntAttribute(objectElement, "faceCount", 0);
if (faceCount > 0)
volume.meshFaces.resize(faceCount);
//Parse child elements
String elementName;
const TiXmlElement* childElement = 0;
while (childElement = IterateChildElements(objectElement, childElement))
{
elementName = childElement->Value();
if (elementName == "size")
volume.boxSize = LoadXYZ(childElement);
else if (elementName == "faces")
LoadBoundingVolumeFaces(childElement, faceCount, volume.meshFaces);
}
}
void OgreMaxUtilities::LoadBoundingVolumeFaces(const TiXmlElement* objectElement, int faceCount, std::vector<BoundingVolume::Face>& faces)
{
//Parse child elements, treating them all as faces
int faceIndex = 0;
const TiXmlElement* childElement = 0;
while ((childElement = IterateChildElements(objectElement, childElement)) && faceIndex < faceCount)
{
BoundingVolume::Face& face = faces[faceIndex++];
//Load the vertices
int vertexIndex = 0;
const TiXmlElement* vertexElement = 0;
while ((vertexElement = IterateChildElements(childElement, vertexElement)) && vertexIndex < 3)
LoadXYZ(vertexElement, face.vertex[vertexIndex++]);
}
}
bool OgreMaxUtilities::ParseSceneManager(const String& sceneManager, SceneType& sceneType)
{
sceneType = (SceneType)0;
String sceneManagerLower = sceneManager;
StringUtil::toLowerCase(sceneManagerLower);
if (sceneManagerLower == "generic")
sceneType = ST_GENERIC;
else if (sceneManagerLower == "exteriorclose")
sceneType = ST_EXTERIOR_CLOSE;
else if (sceneManagerLower == "exteriorfar")
sceneType = ST_EXTERIOR_FAR;
else if (sceneManagerLower == "exteriorrealfar")
sceneType = ST_EXTERIOR_REAL_FAR;
else if (sceneManagerLower == "interior")
sceneType = ST_INTERIOR;
return sceneType != (SceneType)0;
}
bool OgreMaxUtilities::ParseBool(const String& value)
{
String valueLower = value;
StringUtil::toLowerCase(valueLower);
if (valueLower.empty() || valueLower == "false" || value == "no" || value == "0")
return false;
else
return true;
}
Light::LightTypes OgreMaxUtilities::ParseLightType(const String& type)
{
String typeLower = type;
StringUtil::toLowerCase(typeLower);
if (typeLower == "point")
return Light::LT_POINT;
else if (typeLower == "directional")
return Light::LT_DIRECTIONAL;
else if (typeLower == "spot")
return Light::LT_SPOTLIGHT;
StringUtil::StrStreamType errorMessage;
errorMessage << "Invalid light type specified: " << type;
OGRE_EXCEPT
(
Exception::ERR_INVALIDPARAMS,
errorMessage.str(),
"OgreMaxUtilities::ParseLightType"
);
}
ProjectionType OgreMaxUtilities::ParseProjectionType(const String& type)
{
String typeLower = type;
StringUtil::toLowerCase(typeLower);
if (typeLower == "perspective")
return PT_PERSPECTIVE;
else if (typeLower == "orthographic")
return PT_ORTHOGRAPHIC;
StringUtil::StrStreamType errorMessage;
errorMessage << "Invalid projection type specified: " << type;
OGRE_EXCEPT
(
Exception::ERR_INVALIDPARAMS,
errorMessage.str(),
"OgreMaxUtilities::ParseProjectionType"
);
}
BillboardType OgreMaxUtilities::ParseBillboardType(const String& type)
{
String typeLower = type;
StringUtil::toLowerCase(typeLower);
if (typeLower == "point")
return BBT_POINT;
else if (typeLower == "orientedcommon")
return BBT_ORIENTED_COMMON;
else if (typeLower == "orientedself")
return BBT_ORIENTED_SELF;
else if (typeLower == "perpendicularcommon")
return BBT_PERPENDICULAR_COMMON;
else if (typeLower == "perpendicularself")
return BBT_PERPENDICULAR_SELF;
StringUtil::StrStreamType errorMessage;
errorMessage << "Invalid billboard type specified: " << type;
OGRE_EXCEPT
(
Exception::ERR_INVALIDPARAMS,
errorMessage.str(),
"OgreMaxUtilities::ParseBillboardType"
);
}
BillboardOrigin OgreMaxUtilities::ParseBillboardOrigin(const String& origin)
{
String originLower = origin;
StringUtil::toLowerCase(originLower);
if (originLower == "topleft")
return BBO_TOP_LEFT;
else if (originLower == "topcenter")
return BBO_TOP_CENTER;
else if (originLower == "topright")
return BBO_TOP_RIGHT;
else if (originLower == "centerleft")
return BBO_CENTER_LEFT;
else if (originLower == "center")
return BBO_CENTER;
else if (originLower == "centerright")
return BBO_CENTER_RIGHT;
else if (originLower == "bottomleft")
return BBO_BOTTOM_LEFT;
else if (originLower == "bottomcenter")
return BBO_BOTTOM_CENTER;
else if (originLower == "bottomright")
return BBO_BOTTOM_RIGHT;
StringUtil::StrStreamType errorMessage;
errorMessage << "Invalid billboard origin specified: " << origin;
OGRE_EXCEPT
(
Exception::ERR_INVALIDPARAMS,
errorMessage.str(),
"OgreMaxUtilities::ParseBillboardOrigin"
);
}
BillboardRotationType OgreMaxUtilities::ParseBillboardRotationType(const String& rotationType)
{
String rotationTypeLower = rotationType;
StringUtil::toLowerCase(rotationTypeLower);
if (rotationTypeLower == "vertex")
return BBR_VERTEX;
else if (rotationTypeLower == "texcoord")
return BBR_TEXCOORD;
StringUtil::StrStreamType errorMessage;
errorMessage << "Invalid billboard rotation type specified: " << rotationType;
OGRE_EXCEPT
(
Exception::ERR_INVALIDPARAMS,
errorMessage.str(),
"OgreMaxUtilities::ParseBillboardRotationType"
);
}
FogMode OgreMaxUtilities::ParseFogMode(const String& mode)
{
String modeLower = mode;
StringUtil::toLowerCase(modeLower);
if (modeLower == "exp")
return FOG_EXP;
else if (modeLower == "exp2")
return FOG_EXP2;
else if (modeLower == "linear")
return FOG_LINEAR;
else
return FOG_NONE;
StringUtil::StrStreamType errorMessage;
errorMessage << "Invalid fog mode specified: " << mode;
OGRE_EXCEPT
(
Exception::ERR_INVALIDPARAMS,
errorMessage.str(),
"OgreMaxUtilities::ParseFogMode"
);
}
HardwareBuffer::Usage OgreMaxUtilities::ParseHardwareBufferUsage(const String& usage)
{
String usageLower = usage;
StringUtil::toLowerCase(usageLower);
if (usageLower == "static")
return HardwareBuffer::HBU_STATIC;
else if (usageLower == "dynamic")
return HardwareBuffer::HBU_DYNAMIC;
else if (usageLower == "writeonly")
return HardwareBuffer::HBU_WRITE_ONLY;
else if (usageLower == "staticwriteonly")
return HardwareBuffer::HBU_STATIC_WRITE_ONLY;
else if (usageLower == "dynamicwriteonly")
return HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY;
StringUtil::StrStreamType errorMessage;
errorMessage << "Invalid hardware buffer usage specified: " << usage;
OGRE_EXCEPT
(
Exception::ERR_INVALIDPARAMS,
errorMessage.str(),
"OgreMaxUtilities::ParseHardwareBufferUsage"
);
}
Node::TransformSpace OgreMaxUtilities::ParseTransformSpace(const String& space)
{
String spaceLower = space;
StringUtil::toLowerCase(spaceLower);
if (spaceLower == "local")
return Node::TS_LOCAL;
else if (spaceLower == "parent")
return Node::TS_PARENT;
else if (spaceLower == "world")
return Node::TS_WORLD;
StringUtil::StrStreamType errorMessage;
errorMessage << "Invalid transform space specified: " << space;
OGRE_EXCEPT
(
Exception::ERR_INVALIDPARAMS,
errorMessage.str(),
"OgreMaxUtilities::ParseTransformSpace"
);
}
BoundingVolume::Type OgreMaxUtilities::ParseBoundingVolumeType(const String& type)
{
String typeLower = type;
StringUtil::toLowerCase(typeLower);
if (typeLower == "sphere")
return BoundingVolume::SPHERE;
else if (typeLower == "box")
return BoundingVolume::BOX;
else if (typeLower == "mesh")
return BoundingVolume::MESH;
StringUtil::StrStreamType errorMessage;
errorMessage << "Invalid bounding volume type specified: " << type;
OGRE_EXCEPT
(
Exception::ERR_INVALIDPARAMS,
errorMessage.str(),
"OgreMaxUtilities::ParseBoundingVolumeType"
);
}
void OgreMaxUtilities::LoadCustomParameters(const TiXmlElement* objectElement, std::vector<CustomParameter>& customParameters)
{
customParameters.resize(GetElementCount(objectElement, "customParameter"));
size_t customParameterIndex = 0;
const TiXmlElement* childElement = 0;
while (childElement = IterateChildElements(objectElement, childElement))
{
customParameters[customParameterIndex].id = (size_t)GetIntAttribute(childElement, "id", 0);
customParameters[customParameterIndex].value = GetVector4Attributes(childElement);
customParameterIndex++;
}
}
void OgreMaxUtilities::LoadUserDataReference(const TiXmlElement* objectElement, String& userDataReference)
{
userDataReference = GetStringAttribute(objectElement, "id");
}
void OgreMaxUtilities::LoadSubentities(const TiXmlElement* objectElement, std::vector<EntityParameters::Subentity>& subentities)
{
subentities.resize(GetElementCount(objectElement, "subentity"));
const TiXmlElement* childElement = 0;
while (childElement = IterateChildElements(objectElement, childElement))
{
int index = GetIntAttribute(childElement, "index", 0);
subentities[index].materialName = GetStringAttribute(childElement, "materialName");
}
}
void OgreMaxUtilities::LoadNoteTracks(const TiXmlElement* objectElement, std::vector<NoteTrack>& noteTracks)
{
//Allocate note tracks
size_t noteTrackCount = GetChildElementCount(objectElement, "noteTrack");
noteTracks.resize(noteTrackCount);
//Parse child elements
size_t noteTrackIndex = 0;
String elementName;
const TiXmlElement* childElement = 0;
while (childElement = IterateChildElements(objectElement, childElement))
{
elementName = childElement->Value();
if (elementName == "noteTrack")
LoadNoteTrack(childElement, noteTracks[noteTrackIndex++]);
}
}
void OgreMaxUtilities::LoadNoteTrack(const TiXmlElement* objectElement, NoteTrack& noteTrack)
{
//Track name
noteTrack.name = OgreMaxUtilities::GetStringAttribute(objectElement, "name");
//Allocate notes
size_t noteCount = OgreMaxUtilities::GetChildElementCount(objectElement, "note");
noteTrack.notes.resize(noteCount);
//Load notes
size_t noteIndex = 0;
String elementName;
const TiXmlElement* childElement = 0;
while (childElement = IterateChildElements(objectElement, childElement))
{
elementName = childElement->Value();
if (elementName == "note")
LoadNote(childElement, noteTrack.notes[noteIndex++]);
}
}
void OgreMaxUtilities::LoadNote(const TiXmlElement* objectElement, Note& note)
{
//Note time
note.time = OgreMaxUtilities::GetRealAttribute(objectElement, "time", 0);
//Note text
GetChildText(objectElement, note.text);
}
ShadowTechnique OgreMaxUtilities::ParseShadowTechnique(const String& technique)
{
String techniqueLower = technique;
StringUtil::toLowerCase(techniqueLower);
if (techniqueLower == "none")
return SHADOWTYPE_NONE;
else if (techniqueLower == "stencilmodulative")
return SHADOWTYPE_STENCIL_MODULATIVE;
else if (techniqueLower == "stenciladditive")
return SHADOWTYPE_STENCIL_ADDITIVE;
else if (techniqueLower == "texturemodulative")
return SHADOWTYPE_TEXTURE_MODULATIVE;
else if (techniqueLower == "textureadditive")
return SHADOWTYPE_TEXTURE_ADDITIVE;
else if (techniqueLower == "texturemodulativeintegrated")
return SHADOWTYPE_TEXTURE_MODULATIVE_INTEGRATED;
else if (techniqueLower == "textureadditiveintegrated")
return SHADOWTYPE_TEXTURE_ADDITIVE_INTEGRATED;
StringUtil::StrStreamType errorMessage;
errorMessage << "Invalid shadow technique specified: " << technique;
OGRE_EXCEPT
(
Exception::ERR_INVALIDPARAMS,
errorMessage.str(),
"OgreMaxUtilities::ParseShadowTechnique"
);
}
UpAxis OgreMaxUtilities::ParseUpAxis(const String& upAxis)
{
String upAxisLower = upAxis;
StringUtil::toLowerCase(upAxisLower);
if (upAxisLower == "y")
return UP_AXIS_Y;
else if (upAxisLower == "z")
return UP_AXIS_Z;
StringUtil::StrStreamType errorMessage;
errorMessage << "Invalid up axis specified: " << upAxis;
OGRE_EXCEPT
(
Exception::ERR_INVALIDPARAMS,
errorMessage.str(),
"OgreMaxUtilities::ParseUpAxis"
);
}
Animation::InterpolationMode OgreMaxUtilities::ParseAnimationInterpolationMode(const String& mode)
{
String modeLower = mode;
StringUtil::toLowerCase(modeLower);
if (modeLower == "linear")
return Animation::IM_LINEAR;
else if (modeLower == "spline")
return Animation::IM_SPLINE;
StringUtil::StrStreamType errorMessage;
errorMessage << "Invalid animation interpolation mode specified: " << mode;
OGRE_EXCEPT
(
Exception::ERR_INVALIDPARAMS,
errorMessage.str(),
"OgreMaxUtilities::ParseAnimationInterpolationMode"
);
}
Animation::RotationInterpolationMode OgreMaxUtilities::ParseAnimationRotationInterpolationMode(const String& mode)
{
String modeLower = mode;
StringUtil::toLowerCase(modeLower);
if (modeLower == "linear")
return Animation::RIM_LINEAR;
else if (modeLower == "spherical")
return Animation::RIM_SPHERICAL;
StringUtil::StrStreamType errorMessage;
errorMessage << "Invalid animation rotation interpolation mode specified: " << mode;
OGRE_EXCEPT
(
Exception::ERR_INVALIDPARAMS,
errorMessage.str(),
"OgreMaxUtilities::ParseAnimationRotationInterpolationMode"
);
}
NodeVisibility OgreMaxUtilities::ParseNodeVisibility(const String& visibility)
{
String visibilityLower = visibility;
StringUtil::toLowerCase(visibilityLower);
if (visibilityLower == "visible")
return NODE_VISIBLE;
else if (visibilityLower == "hidden")
return NODE_HIDDEN;
else if (visibilityLower == "treevisible")
return NODE_TREE_VISIBLE;
else if (visibilityLower == "treehidden")
return NODE_TREE_HIDDEN;
else
return NODE_VISIBILITY_DEFAULT;
}
ObjectVisibility OgreMaxUtilities::ParseObjectVisibility(const String& visibility)
{
if (visibility.empty())
return OBJECT_VISIBILITY_DEFAULT;
else
return ParseBool(visibility) ? OBJECT_VISIBLE : OBJECT_HIDDEN;
}
uint8 OgreMaxUtilities::ParseRenderQueue(const String& renderQueue)
{
static std::map<String, uint8> nameToNumber;
if (nameToNumber.empty())
{
nameToNumber["background"] = RENDER_QUEUE_BACKGROUND;
nameToNumber["skiesearly"] = RENDER_QUEUE_SKIES_EARLY;
nameToNumber["queue1"] = RENDER_QUEUE_1;
nameToNumber["queue2"] = RENDER_QUEUE_2;
nameToNumber["worldgeometry1"] = RENDER_QUEUE_WORLD_GEOMETRY_1;
nameToNumber["queue3"] = RENDER_QUEUE_3;
nameToNumber["queue4"] = RENDER_QUEUE_4;
nameToNumber["main"] = RENDER_QUEUE_MAIN;
nameToNumber["queue6"] = RENDER_QUEUE_6;
nameToNumber["queue7"] = RENDER_QUEUE_7;
nameToNumber["worldgeometry2"] = RENDER_QUEUE_WORLD_GEOMETRY_2;
nameToNumber["queue8"] = RENDER_QUEUE_8;
nameToNumber["queue9"] = RENDER_QUEUE_9;
nameToNumber["skieslate"] = RENDER_QUEUE_SKIES_LATE;
nameToNumber["overlay"] = RENDER_QUEUE_OVERLAY;
nameToNumber["max"] = RENDER_QUEUE_MAX;
}
if (renderQueue.empty())
return RENDER_QUEUE_MAIN;
else if (AllDigits(renderQueue))
return (uint8)StringConverter::parseUnsignedInt(renderQueue);
else
{
//The render queue name, lowercase
String renderQueueLower;
//Get the offset that comes after the +, if any
uint8 offset = 0;
size_t plusFoundAt = renderQueue.find('+');
if (plusFoundAt != String::npos)
{
//Parse the number
String offsetText = renderQueue.substr(plusFoundAt + 1);
StringUtil::trim(offsetText);
offset = (uint8)StringConverter::parseUnsignedInt(offsetText);
//Remove the "+offset" substring from the render queue name
renderQueueLower = renderQueue.substr(0, plusFoundAt);
StringUtil::trim(renderQueueLower);
}
else
renderQueueLower = renderQueue;
StringUtil::toLowerCase(renderQueueLower);
//Look up the render queue and return it
std::map<String, uint8>::iterator item = nameToNumber.find(renderQueueLower);
if (item != nameToNumber.end())
{
//Don't let the render queue exceed the maximum
return std::min((uint8)(item->second + offset), (uint8)RENDER_QUEUE_MAX);
}
else
{
StringUtil::StrStreamType errorMessage;
errorMessage << "Invalid render queue specified: " << renderQueue;
OGRE_EXCEPT
(
Exception::ERR_INVALIDPARAMS,
errorMessage.str(),
"OgreMaxUtilities::ParseRenderQueue"
);
}
}
}
PixelFormat OgreMaxUtilities::ParsePixelFormat(const String& pixelFormat)
{
static bool initialized = false;
static std::map<String, PixelFormat> nameToFormat;
if (!initialized)
{
nameToFormat["L8"] = PF_L8;
nameToFormat["L16"] = PF_L16;
nameToFormat["A8"] = PF_A8;
nameToFormat["A4L4"] = PF_A4L4;
nameToFormat["BYTE_LA"] = PF_BYTE_LA;
nameToFormat["R5G6B5"] = PF_R5G6B5;
nameToFormat["B5G6R5"] = PF_B5G6R5;
nameToFormat["R3G3B2"] = PF_R3G3B2;
nameToFormat["A4R4G4B4"] = PF_A4R4G4B4;
nameToFormat["A1R5G5B5"] = PF_A1R5G5B5;
nameToFormat["R8G8B8"] = PF_R8G8B8;
nameToFormat["B8G8R8"] = PF_B8G8R8;
nameToFormat["A8R8G8B8"] = PF_A8R8G8B8;
nameToFormat["A8B8G8R8"] = PF_A8B8G8R8;
nameToFormat["B8G8R8A8"] = PF_B8G8R8A8;
nameToFormat["R8G8B8A8"] = PF_R8G8B8A8;
nameToFormat["X8R8G8B8"] = PF_X8R8G8B8;
nameToFormat["X8B8G8R8"] = PF_X8B8G8R8;
nameToFormat["A2R10G10B10"] = PF_A2R10G10B10;
nameToFormat["A2B10G10R10"] = PF_A2B10G10R10;
nameToFormat["FLOAT16_R"] = PF_FLOAT16_R;
nameToFormat["FLOAT16_RGB"] = PF_FLOAT16_RGB;
nameToFormat["FLOAT16_RGBA"] = PF_FLOAT16_RGBA;
nameToFormat["FLOAT32_R"] = PF_FLOAT32_R;
nameToFormat["FLOAT32_RGB"] = PF_FLOAT32_RGB;
nameToFormat["FLOAT32_RGBA"] = PF_FLOAT32_RGBA;
nameToFormat["FLOAT16_GR"] = PF_FLOAT16_GR;
nameToFormat["FLOAT32_GR"] = PF_FLOAT32_GR;
nameToFormat["DEPTH"] = PF_DEPTH;
nameToFormat["SHORT_RGBA"] = PF_SHORT_RGBA;
nameToFormat["SHORT_GR"] = PF_SHORT_GR;
nameToFormat["SHORT_RGB"] = PF_SHORT_RGB;
initialized = true;
}
std::map<String, PixelFormat>::iterator format = nameToFormat.find(pixelFormat);
if (format != nameToFormat.end())
return format->second;
StringUtil::StrStreamType errorMessage;
errorMessage << "Invalid pixel format specified: " << pixelFormat;
OGRE_EXCEPT
(
Exception::ERR_INVALIDPARAMS,
errorMessage.str(),
"OgreMaxUtilities::ParsePixelFormat"
);
}
TextureType OgreMaxUtilities::ParseTextureType(const String& textureType)
{
String textureTypeLower = textureType;
StringUtil::toLowerCase(textureTypeLower);
if (textureTypeLower == "1d")
return TEX_TYPE_1D;
else if (textureTypeLower == "2d")
return TEX_TYPE_2D;
else if (textureTypeLower == "3d")
return TEX_TYPE_3D;
else if (textureTypeLower == "cubic")
return TEX_TYPE_CUBE_MAP;
StringUtil::StrStreamType errorMessage;
errorMessage << "Invalid texture type specified: " << textureType;
OGRE_EXCEPT
(
Exception::ERR_INVALIDPARAMS,
errorMessage.str(),
"OgreMaxUtilities::ParseTextureType"
);
}
void OgreMaxUtilities::LoadClipping(const TiXmlElement* objectElement, Real& nearClip, Real& farClip)
{
nearClip = GetRealAttribute(objectElement, "near", 1);
farClip = GetRealAttribute(objectElement, "far", OgreMaxScene::DEFAULT_MAX_DISTANCE);
}
void OgreMaxUtilities::GetChildText(const TiXmlElement* xmlElement, String& text)
{
//Get the first element
const TiXmlNode* childNode = xmlElement->FirstChild();
while (childNode != 0)
{
if (childNode->Type() == TiXmlNode::TEXT)
{
const TiXmlText* textNode = childNode->ToText();
if (textNode != 0)
{
text = textNode->Value();
break;
}
}
childNode = xmlElement->NextSibling();
}
}
String OgreMaxUtilities::GetStringAttribute(const TiXmlElement* xmlElement, const char* name)
{
const char* value = xmlElement->Attribute(name);
if (value != 0)
return value;
else
return StringUtil::BLANK;
}
String OgreMaxUtilities::GetStringAttribute(const TiXmlElement* xmlElement, const char* name, const char* defaultValue)
{
String value = GetStringAttribute(xmlElement, name);
return value.empty() ? defaultValue : value;
}
Real OgreMaxUtilities::GetRealAttribute(const TiXmlElement* xmlElement, const char* name, Real defaultValue)
{
String value = GetStringAttribute(xmlElement, name);
return value.empty() ? defaultValue : StringConverter::parseReal(value);
}
int OgreMaxUtilities::GetIntAttribute(const TiXmlElement* xmlElement, const char* name, int defaultValue)
{
String value = GetStringAttribute(xmlElement, name);
return value.empty() ? defaultValue : StringConverter::parseInt(value);
}
int OgreMaxUtilities::GetUIntAttribute(const TiXmlElement* xmlElement, const char* name, unsigned int defaultValue)
{
String value = GetStringAttribute(xmlElement, name);
return value.empty() ? defaultValue : StringConverter::parseUnsignedInt(value);
}
bool OgreMaxUtilities::GetBoolAttribute(const TiXmlElement* xmlElement, const char* name, bool defaultValue)
{
String value = GetStringAttribute(xmlElement, name);
return value.empty() ? defaultValue : ParseBool(value);
}
Plane OgreMaxUtilities::GetPlaneAttributes(const TiXmlElement* xmlElement, Real defaultX, Real defaultY, Real defaultZ, Real defaultD)
{
Plane plane;
plane.normal.x = GetRealAttribute(xmlElement, "planeX", defaultX);
plane.normal.y = GetRealAttribute(xmlElement, "planeY", defaultY);
plane.normal.z = GetRealAttribute(xmlElement, "planeZ", defaultZ);
plane.d = GetRealAttribute(xmlElement, "planeD", defaultD);
return plane;
}
Vector4 OgreMaxUtilities::GetVector4Attributes(const TiXmlElement* xmlElement)
{
Vector4 v4;
v4.x = GetRealAttribute(xmlElement, "x", 0);
v4.y = GetRealAttribute(xmlElement, "y", 0);
v4.z = GetRealAttribute(xmlElement, "z", 0);
v4.w = GetRealAttribute(xmlElement, "w", 0);
return v4;
}
PixelFormat OgreMaxUtilities::GetPixelFormatAttribute(const TiXmlElement* xmlElement, const char* name, PixelFormat defaultValue)
{
String value = GetStringAttribute(xmlElement, name);
return value.empty() ? defaultValue : ParsePixelFormat(value);
}
TextureType OgreMaxUtilities::GetTextureTypeAttribute(const TiXmlElement* xmlElement, const char* name, TextureType defaultValue)
{
String value = GetStringAttribute(xmlElement, name);
return value.empty() ? defaultValue : ParseTextureType(value);
}
NodeVisibility OgreMaxUtilities::GetNodeVisibilityAttribute(const TiXmlElement* xmlElement, const char* name)
{
String visibility = OgreMaxUtilities::GetStringAttribute(xmlElement, name);
return ParseNodeVisibility(visibility);
}
ObjectVisibility OgreMaxUtilities::GetObjectVisibilityAttribute(const TiXmlElement* xmlElement, const char* name)
{
String visibility = OgreMaxUtilities::GetStringAttribute(xmlElement, name);
return ParseObjectVisibility(visibility);
}
size_t OgreMaxUtilities::GetElementCount(const TiXmlElement* xmlElement, const String& elementName)
{
size_t count = 0;
//Check name
if (elementName == xmlElement->Value())
count++;
//Recurse into children
const TiXmlElement* childElement = 0;
while (childElement = IterateChildElements(xmlElement, childElement))
count += GetElementCount(childElement, elementName);
return count;
}
size_t OgreMaxUtilities::GetChildElementCount(const TiXmlElement* xmlElement, const String& elementName)
{
size_t count = 0;
//Check children
const TiXmlElement* childElement = 0;
while (childElement = IterateChildElements(xmlElement, childElement))
{
if (elementName == childElement->Value())
count++;
}
return count;
}
const TiXmlElement* OgreMaxUtilities::IterateChildElements(const TiXmlElement* xmlElement, const TiXmlElement* childElement)
{
if (xmlElement != 0)
{
if (childElement == 0)
childElement = xmlElement->FirstChildElement();
else
childElement = childElement->NextSiblingElement();
return childElement;
}
return 0;
}
bool OgreMaxUtilities::AllDigits(const String& text)
{
for (size_t i = 0; i < text.length(); i++)
{
if (!isdigit(text[i]))
return false;
}
return true;
}
bool OgreMaxUtilities::IsPowerOfTwo(unsigned int value)
{
return (value & (value - 1)) == 0;
}
unsigned int OgreMaxUtilities::NextLargestPowerOfTwo(unsigned int value)
{
//From Ice/IceUtils.c in the ODE physics library
value |= (value >> 1);
value |= (value >> 2);
value |= (value >> 4);
value |= (value >> 8);
value |= (value >> 16);
return value + 1;
}
unsigned int OgreMaxUtilities::NextSmallestPowerOfTwo(unsigned int value)
{
if (!IsPowerOfTwo(value))
{
//Not a power of 2. Round value up to the next power of 2
value = NextLargestPowerOfTwo(value);
}
//The value is a power of 2. Shift downward to get the next smallest power of 2
return value >> 1;
}
void OgreMaxUtilities::SetNodeVisibility(SceneNode* node, NodeVisibility visibility)
{
switch (visibility)
{
case NODE_VISIBLE: node->setVisible(true, false); break;
case NODE_HIDDEN: node->setVisible(false, false); break;
case NODE_TREE_VISIBLE: node->setVisible(true, true); break;
case NODE_TREE_HIDDEN: node->setVisible(false, true); break;
}
}
void OgreMaxUtilities::SetCustomParameters(Renderable* renderable, const std::vector<CustomParameter>& customParameters)
{
for (size_t customParameterIndex = 0; customParameterIndex < customParameters.size(); customParameterIndex++)
renderable->setCustomParameter(customParameters[customParameterIndex].id, customParameters[customParameterIndex].value);
}
void OgreMaxUtilities::SetCustomParameters(Entity* entity, const std::vector<CustomParameter>& customParameters)
{
for (unsigned int subentityIndex = 0; subentityIndex < entity->getNumSubEntities(); subentityIndex++)
SetCustomParameters(entity->getSubEntity(subentityIndex), customParameters);
}
void OgreMaxUtilities::SetIdentityInitialState(SceneNode* node)
{
//Get the current state
Vector3 position = node->getPosition();
Quaternion orientation = node->getOrientation();
Vector3 scale = node->getScale();
//Set the initial state to be at identity
node->setPosition(Vector3::ZERO);
node->setOrientation(Quaternion::IDENTITY);
node->setScale(Vector3::UNIT_SCALE);
node->setInitialState();
//Set the current state so the node is in the correct position if the node has
//animations that are initially disabled
node->setPosition(position);
node->setOrientation(orientation);
node->setScale(scale);
}
void OgreMaxUtilities::CreateMovablePlaneName(String& createdName, const String& baseName)
{
createdName = baseName;
createdName += "_movable";
}
Entity* OgreMaxUtilities::CreateEntity
(
SceneManager* sceneManager,
const String& entityName,
const String& meshFile,
std::vector<EntityParameters::Subentity>& subentities
)
{
Entity* entity = sceneManager->createEntity(entityName, meshFile);
//Set subentity materials
size_t subentityCount = std::min(subentities.size(), (size_t)entity->getNumSubEntities());
for (size_t subentityIndex = 0; subentityIndex < subentityCount; subentityIndex++)
{
SubEntity* subentity = entity->getSubEntity((unsigned int)subentityIndex);
subentity->setMaterialName(subentities[subentityIndex].materialName);
}
return entity;
}
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
#include <CoreFoundation/CoreFoundation.h>
// This function will locate the path to our application on OS X,
// unlike windows you can not rely on the curent working directory
// for locating your configuration files and resources.
String OgreMaxUtilities::GetMacBundlePath()
{
char path[1024];
CFBundleRef mainBundle = CFBundleGetMainBundle();
assert(mainBundle);
CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
assert(mainBundleURL);
CFStringRef cfStringRef = CFURLCopyFileSystemPath( mainBundleURL, kCFURLPOSIXPathStyle);
assert(cfStringRef);
CFStringGetCString(cfStringRef, path, 1024, kCFStringEncodingASCII);
CFRelease(mainBundleURL);
CFRelease(cfStringRef);
return String(path);
}
#endif
String OgreMaxUtilities::GetApplicationResourcesPath()
{
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
return GetMacBundlePath() + "/Contents/Resources/";
#else
return GetApplicationDirectory();
#endif
}
String OgreMaxUtilities::GetApplicationDirectory()
{
String path;
const DWORD maxLength = MAX_PATH + 1;
char pathChars[maxLength];
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
GetModuleFileName(GetModuleHandle(0), pathChars, maxLength);
String baseName;
StringUtil::splitFilename(pathChars, baseName, path);
#else
getcwd(pathChars, maxLength);
path = pathChars;
#endif
EnsureTrailingPathSeparator(path);
return path;
}
bool OgreMaxUtilities::IsSeparator(char c)
{
return c == '\\' || c == '/';
}
void OgreMaxUtilities::EnsureTrailingPathSeparator(String& path)
{
if (path.length() > 0)
{
char lastChar = path[path.size() - 1];
if (!IsSeparator(lastChar))
path += "/";
}
}
void OgreMaxUtilities::MakeFullPath(String& path)
{
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
DWORD maxLength = MAX_PATH + 1;
std::vector<char> fullPath;
fullPath.resize(maxLength);
char* filePath;
DWORD result = GetFullPathName(path.c_str(), maxLength, &fullPath[0], &filePath);
if (result > maxLength)
{
fullPath.resize(result);
result = GetFullPathName(path.c_str(), result, &fullPath[0], &filePath);
}
path = &fullPath[0];
#endif
}
bool OgreMaxUtilities::IsAbsolutePath(const String& path)
{
if (path.empty())
return false;
else if (path.length() > 1)
{
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
if (path.length() == 1)
return IsSeparator(path[0]);
else
return path[1] == ':' || (IsSeparator(path[0]) && IsSeparator(path[1]));
#else
return IsSeparator(path[0]);
#endif
}
else
return false;
}
String OgreMaxUtilities::JoinPath(const String& path1, const String& path2)
{
//If path2 is an absolute path, it supercedes path1
if (IsAbsolutePath(path2))
return path2;
//Path2 is not absolute
String joined(path1);
EnsureTrailingPathSeparator(joined);
//Skip leading separators in path2
size_t charIndex = 0;
while (charIndex < path2.length() && IsSeparator(path2[charIndex]))
charIndex++;
//If not at the end of path2, append it
if (charIndex < path2.length())
joined += path2.substr(charIndex, path2.length() - charIndex);
//Remove relative components
MakeFullPath(joined);
return joined;
}
bool OgreMaxUtilities::IsFileReadable(const String& path)
{
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
return GetFileAttributes(path.c_str()) != INVALID_FILE_ATTRIBUTES;
#else
return access(path.c_str(), R_OK) == 0;
#endif
}
void OgreMaxUtilities::RemoveFile(const String& path)
{
remove(path.c_str());
}
bool OgreMaxUtilities::SetDefaultLighting(SceneManager* sceneManager, UpAxis upAxis)
{
static const String defaultLightName("__defaultDirectionalLight");
bool defaultLightingNeeded = !sceneManager->hasLight(defaultLightName);
if (defaultLightingNeeded)
{
//Create a directional light
Light* light = sceneManager->createLight(defaultLightName);
light->setType(Light::LT_DIRECTIONAL);
light->setDiffuseColour(ColourValue((Real).9, (Real).9, (Real).9));
light->setSpecularColour(ColourValue((Real).2, (Real).2, (Real).2));
//When the viewer faces down the forward axis, the light is angled to the lower right of the view
Vector3 upDirection = (upAxis == UP_AXIS_Y) ? Vector3::UNIT_Y : Vector3::UNIT_Z;
Vector3 position = upDirection + Vector3::NEGATIVE_UNIT_X;
light->setPosition(position);
light->setDirection(-position);
//Set the ambient light if necessary
if (sceneManager->getAmbientLight() == ColourValue::Black)
sceneManager->setAmbientLight(ColourValue((Real).2, (Real).2, (Real).2));
}
return defaultLightingNeeded;
}
bool OgreMaxUtilities::IsInternalResourceGroup(const String& resourceGroupName)
{
return
resourceGroupName == ResourceGroupManager::BOOTSTRAP_RESOURCE_GROUP_NAME ||
resourceGroupName == ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME ||
resourceGroupName == ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME;
}
void OgreMaxUtilities::ResetResourceGroups(const String& createResourceGroup)
{
StringVector resourceGroups = ResourceGroupManager::getSingleton().getResourceGroups();
for (size_t index = 0; index < resourceGroups.size(); index++)
{
if (!IsInternalResourceGroup(resourceGroups[index]))
ResourceGroupManager::getSingleton().destroyResourceGroup(resourceGroups[index]);
}
//Create the default resource group if necessary
if (!createResourceGroup.empty())
ResourceGroupManager::getSingleton().createResourceGroup(createResourceGroup);
}
bool OgreMaxUtilities::EndsWithNoCase(const String& text, const String& endsWith)
{
bool result = false;
size_t textLength = text.length();
size_t endsWithLength = endsWith.length();
if (endsWithLength <= textLength)
{
//Get the end string, lowercase
String end = text.substr(textLength - endsWithLength);
StringUtil::toLowerCase(end);
//Get the 'ends with' string, lowercase
String endsWithLower = endsWith;
StringUtil::toLowerCase(endsWithLower);
result = end == endsWithLower;
}
return result;
}
const Ogre::Quaternion& OgreMaxUtilities::GetOrientation(UpAxis upAxis)
{
static const Ogre::Quaternion Y_ORIENTATION = Ogre::Quaternion::IDENTITY;
static const Ogre::Quaternion Z_ORIENTATION(0.707107, 0.707107, 0, 0);
return upAxis == UP_AXIS_Y ? Y_ORIENTATION : Z_ORIENTATION;
}
bool OgreMaxUtilities::ImageCodecCanCode(const Ogre::String& name)
{
if (name == "dds" ||
name == "cut" ||
name == "g3" ||
name == "gif" ||
name == "hdr" ||
name == "ico" ||
name == "iff" ||
name == "jng" ||
name == "koa" ||
name == "lbm" ||
name == "mng" ||
name == "pcd" ||
name == "pcx" ||
name == "psd" ||
name == "ras" ||
name == "sgi" ||
name == "wap" ||
name == "wbm" ||
name == "wbmp" ||
name == "xbm")
{
return false;
}
else
return true;
} | [
"none@none"
]
| [
[
[
1,
1363
]
]
]
|
b7d73cf27c94322af11a5b57d49ea6006ed707f8 | ee065463a247fda9a1927e978143186204fefa23 | /Src/Engine/Script/WrapIGameState.h | aad57a9ff48c43b1f709b46c1acac828046064c5 | []
| no_license | ptrefall/hinsimviz | 32e9a679170eda9e552d69db6578369a3065f863 | 9caaacd39bf04bbe13ee1288d8578ece7949518f | refs/heads/master | 2021-01-22T09:03:52.503587 | 2010-09-26T17:29:20 | 2010-09-26T17:29:20 | 32,448,374 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 779 | h | #pragma once
#include <Lua/LuaPlus.h>
namespace Engine
{
namespace Core { class CoreManager; }
namespace GameState { class IGameState; }
namespace Script
{
class WrapGameStateManager;
class WrapIGameState
{
public:
WrapIGameState(Core::CoreManager *coreMgr, WrapGameStateManager *wGameStateMgr, GameState::IGameState *gameState);
~WrapIGameState();
int init();
GameState::IGameState *getGameState() const { return gameState; }
LuaPlus::LuaObject getLGameState() const { return lGameState; }
LuaPlus::LuaObject getLMeta() const { return lMeta; }
private:
Core::CoreManager *coreMgr;
Script::WrapGameStateManager *wGameStateMgr;
GameState::IGameState *gameState;
LuaPlus::LuaObject lGameState;
LuaPlus::LuaObject lMeta;
};
}
}
| [
"[email protected]@28a56cb3-1e7c-bc60-7718-65c159e1d2df"
]
| [
[
[
1,
35
]
]
]
|
29180910c6c6b4b09578ddbc4021530644ca9572 | f9774f8f3c727a0e03c170089096d0118198145e | /传奇mod/Mir2ExCode/Mir2/LoginProcess/New Account/NewAccount.cpp | 4f2c1534902442bacd586344d2c1907b25c23a60 | []
| no_license | sdfwds4/fjljfatchina | 62a3bcf8085f41d632fdf83ab1fc485abd98c445 | 0503d4aa1907cb9cf47d5d0b5c606df07217c8f6 | refs/heads/master | 2021-01-10T04:10:34.432964 | 2010-03-07T09:43:28 | 2010-03-07T09:43:28 | 48,106,882 | 1 | 1 | null | null | null | null | UHC | C++ | false | false | 7,331 | cpp | #include "stdafx.h"
#define LOGIN_BUTTON_COUNT 3
#define LOGIN_INPUT_COUNT 2
#define LOGIN_IMAGE_COUNT 4
CNewAccount::CNewAccount()
{
}
CNewAccount::~CNewAccount()
{
}
VOID CNewAccount::Create(CWHWilImageData* pxImage)
{
/* INT nLoop;
// Buttons
BUTTONINFO LoginProcBtnInfo[] = {
{ IMG_IDX_BTN_NEW, POS_BTN_NEW_X, POS_BTN_NEW_Y, LOGBTN_WIDTH, LOGBTN_HEIGHT}, // OK Button
{ IMG_IDX_BTN_CHGPASS, POS_BTN_CHG_X, POS_BTN_CHG_Y, LOGBTN_WIDTH, LOGBTN_HEIGHT}, // New Account
{ IMG_IDX_BTN_OK, POS_BTN_OK_X, POS_BTN_OK_Y, LOGBTN_WIDTH, LOGBTN_HEIGHT} // Change Password
};
// EditBox State
INPUTSTATE LoginInputState[] = {
{ LGM_INPUT_ID, POS_ID_INS_X, POS_ID_INS_Y, 126, 15, 0, 10, "\0"}, // Input ID in Login
{ LGM_INPUT_PASSWORD, POS_PASS_INS_X, POS_PASS_INS_Y, 126, 15, 0, 10, "\0"} // Input Password In Login
};
_LOGINIMAGEINFO LoginImageInfo[] = {
{IMG_IDX_ID, POS_ID_TITLE_X, POS_ID_TITLE_Y},
{IMG_IDX_PASS, POS_PASS_TITLE_X, POS_PASS_TITLE_Y},
{IMG_IDX_ID_INS, POS_ID_INS_X, POS_ID_INS_Y},
{IMG_IDX_PASS_INS, POS_PASS_INS_X, POS_PASS_INS_Y}
};
m_pxImage = pxImage;
for(nLoop = 0 ; nLoop < LOGIN_INPUT_COUNT ; nLoop ++)
memcpy(&m_xInputState[nLoop],&LoginInputState[nLoop],sizeof(INPUTSTATE));
for(nLoop = 0 ; nLoop < LOGIN_BUTTON_COUNT ; nLoop ++)
m_xButtons[nLoop].SetBtn(&LoginProcBtnInfo[nLoop]);
for(nLoop = 0 ; nLoop < LOGIN_IMAGE_COUNT ; nLoop ++)
m_xInputImg[nLoop] = LoginImageInfo[nLoop];*/
}
HRESULT CNewAccount::OnKeyDown(WPARAM wParam, LPARAM lParam)
{
/* if (wParam == VK_RETURN || wParam == VK_TAB)
{ SetFocusBefore();
switch(m_nUserState)
{ case LGM_INPUT_ID:
{ m_nUserState = LGM_INPUT_PASSWORD;
break;
}
case LGM_INPUT_PASSWORD:
{ if( ( lstrlen( m_xInputState[LGM_INPUT_ID-1].szData) >= LIMIT_USERID )
&& lstrlen( m_xInputState[LGM_INPUT_PASSWORD-1].szData ) )
{
g_xClientSocket.OnLogin(m_xInputState[LGM_INPUT_ID-1].szData,m_xInputState[LGM_INPUT_PASSWORD-1].szData);
return 0L;
}
m_nUserState = LGM_INPUT_ID;
break;
}
}
SetFocusAfter();
}*/
return 0;
}
HRESULT CNewAccount::OnButtonDown(WPARAM wParam, LPARAM lParam)
{
/* INT i;
RECT tRect;
m_fIsButtonDown = TRUE;
for( i = LGM_INPUT_ID-1 ; i < LGM_INPUT_PASSWORD; i ++)
{ SetRect(&tRect
,m_xInputState[i].Left,m_xInputState[i].Top
,m_xInputState[i].Left+m_xInputState[i].Width,m_xInputState[i].Top+m_xInputState[i].Height);
if( IsInRect( tRect, LOWORD( lParam ), HIWORD( lParam ) ) )
{ SetFocusBefore();
m_nUserState = i+1;
SetFocusAfter();
}
}
// Image Button Down Check
for ( i = BTN_NEW_ID; i <= BTN_OK_ID ; i++)
{ if (m_xButtons[i].CheckMouseOn( LOWORD( lParam ), HIWORD( lParam ) ) )
m_xButtons[i].m_nState = BUTTON_STATE_DOWN;
else
m_xButtons[i].m_nState = BUTTON_STATE_UP;
}*/
return 0;
}
HRESULT CNewAccount::OnButtonDown(POINT ptMouse)
{
m_fIsButtonDown = TRUE;
return 0;
}
HRESULT CNewAccount::OnButtonUp(WPARAM wParam, LPARAM lParam)
{
/* INT i;
m_fIsButtonDown = FALSE;
for(i = BTN_NEW_ID; i <= BTN_OK_ID; i++)
{ m_xButtons[i].m_nState = BUTTON_STATE_UP;
if( m_xButtons[i].CheckMouseOn( LOWORD( lParam ), HIWORD( lParam ) ) )
{ switch(m_xButtons[i].m_nButtonID)
{ case IMG_IDX_BTN_NEW:
{
//m_nProgress = PRG_NEW_ACCOUNT; - > New Account로 넘기는 함수
SetFocusBefore();
SetWindowText(g_xChatEditBox.GetSafehWnd(),NULL);
m_nUserState = LGM_INPUT_USER_ID;
SetFocusAfter();
break;
}
case IMG_IDX_BTN_CHGPASS:
{ // 임시로 종료버튼으로 이용
// Avi 관련 함수 종료 하는 코드
// break;
}
// case BTN_EXIT:
{
SendMessage(g_xMainWnd.GetSafehWnd(), WM_DESTROY, NULL, NULL);
return 0L;break;
}
case IMG_IDX_BTN_OK:
{
SendMessage(g_xChatEditBox.GetSafehWnd(),WM_CHAR,VK_RETURN,0);
g_xClientSocket.OnLogin(m_xInputState[LGM_INPUT_ID-1].szData,m_xInputState[LGM_INPUT_PASSWORD-1].szData);
break;
}
}// switch
}// if
}// for*/
return 0;
}
HRESULT CNewAccount::OnButtonUp(POINT ptMouse)
{
return 0;
}
LRESULT CNewAccount::OnMouseMove(WPARAM wParam, LPARAM lParam)
{
/* INT i;
if(!m_fIsButtonDown)
{
for( i = BTN_NEW_ID ; i <= BTN_OK_ID ; i ++)
{
if (m_xButtons[i].CheckMouseOn(LOWORD(lParam), HIWORD(lParam)))
m_xButtons[i].m_nState = BUTTON_STATE_ON;
else
m_xButtons[i].m_nState = BUTTON_STATE_UP;
}
}
*/
return 0;
}
VOID CNewAccount::Render(INT nLoopTime)
{
/* if(m_fIsActive)
{
int i;
char Pass[16]="";
MoveWindow(g_xChatEditBox.GetSafehWnd(),
g_xMainWnd.m_rcWindow.left + m_xInputState[m_nUserState-1].Left +5,
g_xMainWnd.m_rcWindow.top + m_xInputState[m_nUserState-1].Top + 5 , m_xInputState[m_nUserState-1].Width, m_xInputState[m_nUserState-1].Height, TRUE);
// Draw ID & Pass Image
for( i = IMG_IDX_ID-1 ; i < IMG_IDX_PASS_INS ; i ++)
{
m_pxImage->NewSetIndex(m_xInputImg[i].nImgIdx);
g_xMainWnd.DrawWithImageForComp(m_xInputImg[i].Left , m_xInputImg[i].Top,
m_pxImage->m_lpstNewCurrWilImageInfo->shWidth,
m_pxImage->m_lpstNewCurrWilImageInfo->shHeight,
(WORD*)(m_pxImage->m_pbCurrImage));
}
// Draw Button Image
for ( i = BTN_NEW_ID ; i <= BTN_OK_ID ; i++)
{
m_pxImage->NewSetIndex(m_xButtons[i].m_nButtonID + m_xButtons[i].m_nState - 1 );
g_xMainWnd.DrawWithImageForComp(m_xButtons[i].m_Rect.left, m_xButtons[i].m_Rect.top,
m_xButtons[i].m_Rect.right - m_xButtons[i].m_Rect.left,
m_xButtons[i].m_Rect.bottom - m_xButtons[i].m_Rect.top, (WORD*)(m_pxImage->m_pbCurrImage));
}
// Write ID & Password
memset(Pass,'*',strlen(m_xInputState[1].szData));
g_xMainWnd.PutsHan(NULL, m_xInputState[0].Left+7, m_xInputState[0].Top+6, RGB(5,5,5), RGB(0,0,0), m_xInputState[0].szData);
g_xMainWnd.PutsHan(NULL, m_xInputState[1].Left+7, m_xInputState[1].Top+6, RGB(5,5,5), RGB(0,0,0), Pass);
}*/
}
VOID CNewAccount::SetFocusBefore(VOID)
{
INT nTemp;
nTemp = m_nUserState - 1;
if(g_xChatEditBox.m_szInputMsg[0]!=NULL)
lstrcpy(m_xInputState[nTemp].szData , g_xChatEditBox.m_szInputMsg);
else
GetWindowText(g_xChatEditBox.GetSafehWnd(),m_xInputState[nTemp].szData ,m_xInputState[nTemp].nSize);
ZeroMemory(g_xChatEditBox.m_szInputMsg,sizeof(g_xChatEditBox.m_szInputMsg));
ShowWindow(g_xChatEditBox.GetSafehWnd(), SW_HIDE);
g_xChatEditBox.SetSelectAll();
}
VOID CNewAccount::SetFocusAfter(VOID)
{
CHAR cChr;
INT nTemp;
ShowWindow(g_xChatEditBox.GetSafehWnd(), SW_SHOW);
nTemp = m_nUserState - 1;
g_xChatEditBox.SetLimitText(m_xInputState[nTemp].nSize);
if( m_nUserState != LGM_INPUT_PASSWORD )
cChr = NULL;
else
cChr = '*';
SendMessage(g_xChatEditBox.GetSafehWnd(),EM_SETPASSWORDCHAR,(WPARAM)cChr,0);
SetWindowText(g_xChatEditBox.GetSafehWnd(), m_xInputState[nTemp].szData);
SetFocus(g_xChatEditBox.GetSafehWnd());
g_xChatEditBox.SetSelectAll();
} | [
"fjljfat@4a88d1ba-22b1-11df-8001-4f4b503b426e"
]
| [
[
[
1,
254
]
]
]
|
ed85ed39ce85b524f2be55202e32c5e7d5296f2f | ee2e06bda0a5a2c70a0b9bebdd4c45846f440208 | /test1/test 1/test 1Dlg.h | b27c80e8ed3272f9c10fdbd5a2f57fcff7308936 | []
| 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 | UTF-8 | C++ | false | false | 1,130 | h | // test 1Dlg.h : header file
//
#pragma once
// Ctest1Dlg dialog
using namespace std;
class Ctest1Dlg : public CDialog
{
// Construction
public:
Ctest1Dlg(CWnd* pParent = NULL); // standard constructor
//static Ctest1Dlg* Instance();
// Dialog Data
enum { IDD = IDD_TEST1_DIALOG };
virtual BOOL Ctest1Dlg::PreTranslateMessage(MSG* pMsg);
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//static Ctest1Dlg* __instance;
// Implementation
protected:
HICON m_hIcon;
// Generated message map functions
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnBnClickedButton1();
CString m_infileStr;
afx_msg void OnBnClickedButton2();
afx_msg void OnBnClickedOk();
afx_msg void OnBnClickedButton3();
afx_msg void OnBnClickedButton4();
afx_msg void OnBnClickedButton5();
afx_msg void OnBnClickedButton6();
afx_msg void OnBnClickedButton7();
afx_msg void OnBnClickedButton8();
};
| [
"RobinofChina@43938a50-64aa-11de-9867-89bd1bae666e"
]
| [
[
[
1,
44
]
]
]
|
a29f9de7a61c6822820f1e9c24e544ed0f690ef8 | baa53679794b11a5e99bc430149494e48e7c0d1e | /iplist.h | 1da46e1dd465b276fbd1429b64175fe3ab217456 | []
| no_license | BadPractice/twmailer2 | 34cf62cfc2249a8b30cf9f7e729d4713aaefaea1 | 76abd320acf4265cda7d5de19a46df7e805e51f0 | refs/heads/master | 2020-12-24T15:40:05.391935 | 2011-11-07T00:05:34 | 2011-11-07T00:05:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 644 | h | #ifndef IPLIST_H
#define IPLIST_H
#include <list>
#include <string>
#include "badguy.h"
using namespace std;
class iplist
{
public:
iplist();
void add(string);//add a Person
int check(string);//check if Person is blocked
void debug_msg();//messages used for debugging
void save();//save list to file
void read();//import lixst from file
//(includeing clearing current)
void clear();//delete all
void refresh();//remove old timestamps from list
virtual ~iplist();
protected:
private:
list<badguy> badguys;
};
#endif // IPLIST_H
| [
"[email protected]"
]
| [
[
[
1,
25
]
]
]
|
0f0ab2e90b2fcda1ba4b4a8951fa5b8a3629cc9f | 0813282678cb6bb52cd0001a760cfbc24663cfca | /Vector.h | 6c6bca99ca1a71db01e385e791692e810908d8e2 | []
| no_license | mannyzhou5/scbuildorder | e3850a86baaa33d1c549c7b89ddab7738b79b3c0 | 2396293ee483e40495590782b652320db8adf530 | refs/heads/master | 2020-04-29T01:01:04.504099 | 2011-04-12T10:00:54 | 2011-04-12T10:00:54 | 33,047,073 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,391 | h | #pragma once
#include "MemoryPool.h"
#include "MemoryPoolManager.h"
template<typename T>
class CVector : public CMemPoolNode<CVector<T>>
{
public:
CVector() : m_size(0), m_capacity(0), m_data(0) {}
CVector(const CVector<T> &vec);
~CVector();
size_t size() const { return m_size; }
size_t capacity() const { return m_capacity; }
void append(const CVector &vector) { append(vector.data(), vector.length()); }
void append(const T *vals, size_t count);
void push_back(const T &val);
void insert(size_t index, const T &val);
void erase(size_t index, size_t count = 1);
void capacity(size_t capacity);
void push(const T &val) { push_back(val); }
T &pop() { return m_data[--m_size]; }
void truncate(size_t size) { if(size >= m_size) return; m_size = size; }
const T &operator[](size_t index) const { return m_data[index]; }
T &operator[](size_t index) { return m_data[index]; }
const T *data() const { return m_data; }
bool operator==(const CVector<T> &vector) const;
bool operator!=(const CVector<T> &vector) const { return !(*this == vector); }
bool operator <(const CVector<T> &vector) const;
void operator =(const CVector<T> &vector);
protected:
size_t m_size;
size_t m_capacity;
T *m_data;
__declspec(thread) static CMemoryPoolManager *m_memoryPoolManager;
};
template<typename T>
CMemoryPoolManager *CVector<T>::m_memoryPoolManager = 0;
template<typename T>
CVector<T>::CVector(const CVector<T> &vector)
: m_size(0), m_capacity(0), m_data(0)
{
capacity(vector.size());
T *data = m_data;
const T *vecData = vector.data();
for(size_t index = 0; index < vector.size(); index++)
*(data++) = *(vecData++);
m_size = vector.size();
}
template<typename T>
CVector<T>::~CVector()
{
if(m_data)
m_memoryPoolManager->GetMemoryPool(m_capacity * sizeof(T))->Free(m_data);
}
template<typename T>
void CVector<T>::append(const T *vals, size_t count)
{
capacity(m_size + count);
T *data = &m_data[m_size];
for(size_t index = 0; index < count; index++)
*(data++) = *(vals++);
m_size += count;
}
template<typename T>
void CVector<T>::push_back(const T &val)
{
capacity(m_size + 1);
m_data[m_size++] = val;
}
template<typename T>
void CVector<T>::insert(size_t index, const T &val)
{
capacity(m_size + 1);
memmove(&m_data[index + 1], &m_data[index], (m_size - index) * sizeof(T));
m_data[index] = val;
m_size++;
}
template<typename T>
void CVector<T>::erase(size_t index, size_t count /* = 1 */)
{
memmove(&m_data[index], &m_data[index + count], (m_size - count - index) * sizeof(T));
m_size -= count;
}
template<typename T>
void CVector<T>::capacity(size_t capacity)
{
if(m_capacity > capacity)
return;
size_t newCapacity = m_capacity > 0 ? m_capacity : 128;
while(newCapacity < capacity + 1)
newCapacity <<= 1;
if(!m_memoryPoolManager)
m_memoryPoolManager = new CMemoryPoolManager();
T *newData = (T *)m_memoryPoolManager->GetMemoryPoolAddAsNeeded(newCapacity * sizeof(T))->Alloc();
if(m_data)
{
memcpy(newData, m_data, m_capacity * sizeof(T));
m_memoryPoolManager->GetMemoryPool(m_capacity * sizeof(T))->Free(m_data);
}
// Initialise values
T *init = &newData[m_capacity];
for(size_t index = m_capacity; index < newCapacity; index++)
new (init++) T();
m_data = newData;
m_capacity = newCapacity;
}
template<typename T>
bool CVector<T>::operator==(const CVector<T> &vector) const
{
if(m_size != vector.size())
return false;
const T *data = m_data;
const T *vecData = vector.data();
for(size_t index=0; index < m_size; index++, data++, vecData++)
{
if(*data != *vecData)
return false;
}
return true;
}
template<typename T>
bool CVector<T>::operator<(const CVector<T> &vector) const
{
const T *data = m_data;
const T *vecData = vector.data();
for(size_t index=0; index < m_size && index < vector.size(); index++, data++, vecData++)
{
if(*data < *vecData)
return true;
else if(*vecData < *data)
return false;
}
return m_size < vector.size();
}
template<typename T>
void CVector<T>::operator=(const CVector<T> &vector)
{
capacity(vector.size());
T *data = m_data;
const T *vecData = vector.data();
for(size_t index = 0; index < vector.size(); index++)
*(data++) = *(vecData++);
m_size = vector.size();
}
| [
"[email protected]@a0245358-5b9e-171e-63e1-2316ddff5996",
"CarbonTwelve.Developer@a0245358-5b9e-171e-63e1-2316ddff5996"
]
| [
[
[
1,
25
],
[
28,
32
],
[
34,
105
],
[
107,
171
]
],
[
[
26,
27
],
[
33,
33
],
[
106,
106
]
]
]
|
bd3f9d54049a1c048981254fd067565bc28aed84 | a1117d878cdcbd2756512ce29ad4dfd2b5709dac | /OneSnap/SnapperConfig.cpp | a9c8b66d85baa3aa8036749ca6d6fafb940c8f8b | []
| no_license | nicklepede/onesnap | e423f6565fcc557af10618dc74bcaa941057f1d9 | 95631cb208721c97e74488d4633afaf6f63e5c00 | refs/heads/master | 2021-01-13T01:48:01.401096 | 2006-06-27T16:30:12 | 2006-06-27T16:30:12 | 102,732 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,041 | cpp | #include "StdAfx.h"
#include "snapperconfig.h"
#include "FileFindEx.h"
#define ONESNAP_REGKEY_PATH _T("Software\\OneSnap")
#define ONESNAP_REGVAL_FILEPATH _T("Filepath")
#define ONESNAP_REGVAL_NOTEBOOKPATH _T("NotebookPath")
// options and their default values
#define OPT_LIMITPAGEWIDTH _T("limit_width")
#define DEF_LIMITPAGEWIDTH FALSE
#define OPT_MAXWIDTH _T("max_width_x100")
#define DEF_MAXWIDTH 12.0f
#define OPT_IMPORTASBACKGROUND _T("import_as_background")
#define DEF_IMPORTASBACKGROUND FALSE
#define OPT_NAVIGATETOPAGE _T("navigate_to_page")
#define DEF_NAVIGATETOPAGE FALSE
#define OPT_INCLUDESHAREDNOTEBOOKS _T("include_shared_notebooks")
#define DEF_INCLUDESHAREDNOTEBOOKS FALSE
#define OPT_AUTOSYNC _T("auto_sync")
#define DEF_AUTOSYNC TRUE
#define OPT_FOLDER_SEPARATOR _T("folder_separator")
#define DEF_FOLDER_SEPARATOR _T("\\")
#define OPT_MAX_DIR_DEPTH _T("max_dir_depth")
#define DEF_MAX_DIR_DEPTH 10
// load a value from OneSnap's registry key. If the value doesn't exist,
// then return the default value *and* save the default value to the registry
// (this isn't totally necessary, but it's convenient for manual regval tweaking).
// GetFileTitle is defined to be GetFileTitleW, but GetFileTitle is the name of a member function we must call
// below. Therefore we must undef GetFileTitle.
#undef GetFileTitle
CSnapperConfig::CSnapperConfig()
{
if (!Load())
{
CreateConfigFile(m_strFilepath, m_strNotebookPath);
}
else
{
if (GetAutoSync())
UpdateHotlists(FALSE);
}
}
CSnapperConfig::~CSnapperConfig(void)
{
}
BOOL CSnapperConfig::Load(void)
{
LoadRegSettings();
return CSnapperXml::Load(m_strFilepath);
}
#define REGVAL_MAXLEN 512
CString CSnapperConfig::LoadFromRegistry(LPCTSTR lpszValName, LPCTSTR lpszDefault)
{
CString strVal;
strVal.Preallocate(REGVAL_MAXLEN);
strVal = lpszDefault;
CRegKey rk;
if(rk.Create(HKEY_CURRENT_USER, ONESNAP_REGKEY_PATH) == ERROR_SUCCESS)
{
ULONG nChars = strVal.GetAllocLength();
if (ERROR_SUCCESS != rk.QueryStringValue(lpszValName, strVal.GetBuffer(), &nChars))
{
// wasn't successful at reading setting, so save the default settting.
rk.SetStringValue(lpszValName, strVal);
}
strVal.ReleaseBuffer();
rk.Close();
}
return strVal;
}
void CSnapperConfig::AddCategoryEntry(LPCTSTR lpszPath, LPCTSTR lpszCategory, BOOL bIsNetworkPath, BOOL bFollowShortcuts, BOOL bFollowNetworkPaths)
{
AddHotlist(lpszCategory, lpszPath, bIsNetworkPath);
// find all .one files and add them as targets
CFileIterator fi(lpszPath, L"*.one", bFollowShortcuts, bFollowNetworkPaths);
while (fi.Next())
{
CString strFilePath = fi.GetPath();
// CFileIterator does 8.3 pattern matches, so unfortunately it catches the
// *.onetoc files when we filter for *.one files. So let's filter them out
if (strFilePath.Find(_T(".onetoc"), strFilePath.GetLength() - 8) != -1)
continue;
AddTarget(lpszCategory, fi.GetTitle(), fi.GetPath(), fi.IsNetworkPath());
};
}
void CSnapperConfig::AddCategories(LPCTSTR lpszPath, LPCTSTR lpszName, BOOL bFollowShortcuts, BOOL bFollowNetworkPaths, BOOL bPrependNameToSubs, LPCTSTR pszSeparator, long nMaxDirDepth)
{
// if we've recursed to our max recurse depth, then quietly bail out. Otherwise, continue
// one w/ our max depth decremented...
if (nMaxDirDepth-- <= 0)
{
return;
}
AddCategoryEntry(lpszPath, lpszName, PathIsNetworkPath(lpszPath), bFollowShortcuts, bFollowNetworkPaths);
CFileIterator ff(lpszPath, _T("*.*"), bFollowShortcuts, bFollowNetworkPaths);
while (ff.Next())
{
if (ff.IsDir())
{
CString strDirName = ff.GetTitle();
if (bPrependNameToSubs)
strDirName = CString(lpszName) + pszSeparator + strDirName;
AddCategories(ff.GetPath(), strDirName, bFollowShortcuts, bFollowNetworkPaths, TRUE, pszSeparator, nMaxDirDepth);
}
};
}
void CSnapperConfig::UpdateHotlists(BOOL bFollowNetworkPaths)
{
// save the current hotlist & targets so we can reset them later
// CString strHotlist = GetCurrentHotlist();
// CString strTarget = GetCurrentTarget(strHotlist);
MarkRemoveHotlists(!bFollowNetworkPaths);
AddCategories(m_strNotebookPath, _T("My Notebook"),GetIncludeSharedNotebooks(), bFollowNetworkPaths, FALSE, GetFolderSeparator(), GetMaxDirDepth() );
// if the current hotlist/target no longer exist then
RemoveMarkedHotlists();
Save();
ReconcileCurrents();
}
void CSnapperConfig::CreateConfigFile(LPCTSTR lpszFilepath, LPCTSTR lpszNotebookPath)
{
Clear();
AddCategories(lpszNotebookPath, _T("My Notebook"), GetIncludeSharedNotebooks(), TRUE, TRUE, GetFolderSeparator(), GetMaxDirDepth());
ReconcileCurrents();
InitOptions();
Save();
}
void CSnapperConfig::Save(void)
{
SaveRegSettings();
CSnapperXml::Save(m_strFilepath);
}
// save value to OneSnap's registry key. Don't bother throwing if
// something goes wrong...
BOOL CSnapperConfig::SaveToRegistry(LPCTSTR lpszValName, LPCTSTR lpszVal)
{
long ns;
CRegKey rk;
ns = rk.Create(HKEY_CURRENT_USER, ONESNAP_REGKEY_PATH);
if(ns == ERROR_SUCCESS)
{
ns = rk.SetStringValue(lpszValName, lpszVal);
rk.Close();
}
return (ns == ERROR_SUCCESS);
}
// load XML filepath and notebook filepath from registry, or
// set to default values.
void CSnapperConfig::LoadRegSettings()
{
// preset settings to default values
m_strNotebookPath = LoadFromRegistry(ONESNAP_REGVAL_NOTEBOOKPATH, GetDefaultNotebookPath());
// verify path points to a directory. If it doesn't then just ask the user to select it.
if (!PathIsDirectory(m_strNotebookPath))
{
MessageBox(NULL, _T("OneSnap couldn't find your OneNote notebook. After clicking OK you'll get a directory browser. Please use it to find and select your notebook."), _T("Couldn't find notebook"), MB_OK);
BrowseForNotebook(m_strNotebookPath.GetBuffer());
}
m_strFilepath = LoadFromRegistry(ONESNAP_REGVAL_FILEPATH, GetDefaultFilepath(m_strNotebookPath));
}
void CSnapperConfig::SaveRegSettings()
{
SaveToRegistry(ONESNAP_REGVAL_NOTEBOOKPATH, m_strNotebookPath);
SaveToRegistry(ONESNAP_REGVAL_FILEPATH, m_strFilepath);
}
// get the default path to the config file. Default path is <NOTEBOOK PATH>\OneSnap.xml.
CString CSnapperConfig::GetDefaultFilepath(CString& strNotebookPath)
{
CString strFilePath;
PathCombine(strFilePath.GetBufferSetLength(MAX_PATH), strNotebookPath, _T("OneSnap.xml"));
strFilePath.ReleaseBuffer();
return strFilePath;
}
// get the default path to "My Notebook".
CString CSnapperConfig::GetDefaultNotebookPath()
{
CString strPath(_T(""), MAX_PATH);
// the relative path from My Documents to the root notebook is stored in
// a regkey.
CRegKey rkSave;
if (ERROR_SUCCESS == rkSave.Open(HKEY_CURRENT_USER, _T("Software\\Microsoft\\Office\\11.0\\OneNote\\Options\\Save"), KEY_READ))
{
CString strRelPath;
ULONG cch = MAX_PATH;
if (ERROR_SUCCESS == rkSave.QueryStringValue(_T("My Notebook path"), strRelPath.GetBufferSetLength(MAX_PATH), &cch))
{
strRelPath.ReleaseBuffer();
CString strPathMyDocs;
if (S_OK == SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, 0, strPathMyDocs.GetBufferSetLength(MAX_PATH)))
{
strPathMyDocs.ReleaseBuffer();
PathCombine(strPath.GetBuffer(), strPathMyDocs, strRelPath);
strPath.ReleaseBuffer();
}
}
}
return strPath;
}
bool CSnapperConfig::BrowseForNotebook(TCHAR* pszNotebookPath)
{
bool bGotit = false;
BROWSEINFO sBi = { 0 };
sBi.lpszTitle = _T("Select your notebook directory");
/*
sBi.lpszTitle = TEXT("Select Notebook(s)");
sBi.hwndOwner = m_hWndTop;
sBi.iImage =
*/
LPITEMIDLIST pIdl = SHBrowseForFolder ( &sBi );
if ( pIdl != NULL )
{
// get the name of the folder
if ( SHGetPathFromIDList ( pIdl, pszNotebookPath ) )
{
bGotit = true;
}
// free memory
IMalloc * piMalloc = NULL;
if ( SUCCEEDED( SHGetMalloc ( &piMalloc )) )
{
piMalloc->Free ( pIdl );
piMalloc->Release ( );
}
}
return bGotit;
}
#if 0
string notebookPath = "My Notebook";
// The Notebook Path is stored in the Save options in the registry:
string saveKey = "Software\\Microsoft\\Office\\11.0\\OneNote\\Options\\Save";
using (RegistryKey saveOptions = Registry.CurrentUser.OpenSubKey(saveKey))
{
if (saveOptions != null)
notebookPath = saveOptions.GetValue("My Notebook path", notebookPath).ToString();
}
// This path is relative to the user's My Documents folder
string documentsFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
return Path.Combine(documentsFolder, notebookPath);
#endif
void CSnapperConfig::SetConfigFilePath(LPCTSTR lpszFilepath)
{
m_strFilepath = lpszFilepath;
// load the config file if it exists, otherwise just save to the new filepath.
if (!CSnapperXml::Load(m_strFilepath))
CSnapperXml::Save(m_strFilepath);
SaveRegSettings();
}
void CSnapperConfig::SetNotebookPath(LPCTSTR lpszNotebookPath)
{
m_strNotebookPath = lpszNotebookPath;
}
// returns the path to the OneNote notebook
CString CSnapperConfig::GetNotebookPath(void)
{
return m_strNotebookPath;
}
CString CSnapperConfig::GetConfigFilePath(void)
{
return m_strFilepath;
}
CString CSnapperConfig::GetFolderSeparator()
{
CString strSep = GetOption(OPT_FOLDER_SEPARATOR, DEF_FOLDER_SEPARATOR);
// MSXML seems to clip leading and trailing whitespace.
// HACK: This is the one field where whitespace matters, so let's (sloppily) allow this field to use enclosing quotes
strSep.Replace(_T("\""), _T(""));
return strSep;
}
void CSnapperConfig::SetFolderSeparator(LPCTSTR pszSeparator)
{
SetOption(OPT_FOLDER_SEPARATOR, pszSeparator);
}
void CSnapperConfig::InitOptions()
{
SetImportAsBackground(DEF_IMPORTASBACKGROUND);
SetNavigateToPage(DEF_NAVIGATETOPAGE);
SetLimitPageWidth(DEF_LIMITPAGEWIDTH);
SetMaxPageWidth(DEF_MAXWIDTH);
SetFolderSeparator(DEF_FOLDER_SEPARATOR);
SetMaxDirDepth(DEF_MAX_DIR_DEPTH);
}
BOOL CSnapperConfig::GetImportAsBackground(void)
{
return GetBoolOption(OPT_IMPORTASBACKGROUND, DEF_IMPORTASBACKGROUND);
}
BOOL CSnapperConfig::GetNavigateToPage(void)
{
return GetBoolOption(OPT_NAVIGATETOPAGE, DEF_NAVIGATETOPAGE);
}
BOOL CSnapperConfig::GetIncludeSharedNotebooks(void)
{
return GetBoolOption(OPT_INCLUDESHAREDNOTEBOOKS, DEF_INCLUDESHAREDNOTEBOOKS);
}
BOOL CSnapperConfig::GetLimitPageWidth(void)
{
return GetBoolOption(OPT_LIMITPAGEWIDTH, DEF_LIMITPAGEWIDTH);
}
long CSnapperConfig::GetMaxDirDepth(void)
{
return GetLongOption(OPT_MAX_DIR_DEPTH, DEF_MAX_DIR_DEPTH);
}
void CSnapperConfig::SetMaxDirDepth(long lDepth)
{
return SetLongOption(OPT_MAX_DIR_DEPTH, lDepth);
}
float CSnapperConfig::GetMaxPageWidth(void)
{
return GetFloatOption(OPT_MAXWIDTH, DEF_MAXWIDTH);
}
void CSnapperConfig::SetImportAsBackground(BOOL bImportAsBackground)
{
SetBoolOption(OPT_IMPORTASBACKGROUND, bImportAsBackground);
}
void CSnapperConfig::SetNavigateToPage(BOOL bNavigateToPage)
{
SetBoolOption(OPT_NAVIGATETOPAGE, bNavigateToPage);
}
void CSnapperConfig::SetIncludeSharedNotebooks(BOOL bIncludeSharedNotebooks)
{
SetBoolOption(OPT_INCLUDESHAREDNOTEBOOKS, bIncludeSharedNotebooks);
}
void CSnapperConfig::SetLimitPageWidth(BOOL bLimitPageWidth)
{
SetBoolOption(OPT_LIMITPAGEWIDTH, bLimitPageWidth);
}
void CSnapperConfig::SetMaxPageWidth(float fMaxWidth)
{
SetFloatOption(OPT_MAXWIDTH, fMaxWidth);
}
// If this option is true, then we should rescan notebook each time user runs OneSnap.
BOOL CSnapperConfig::GetAutoSync(void)
{
return GetBoolOption(OPT_AUTOSYNC, DEF_AUTOSYNC);
}
void CSnapperConfig::SetAutoSync(BOOL bAutoSync)
{
SetBoolOption(OPT_AUTOSYNC, bAutoSync);
}
| [
"nicklepede@2c095272-fa16-0410-abf3-d1f1c5240653"
]
| [
[
[
1,
409
]
]
]
|
0da4011dc845a664981b8499a74d4440e944a25d | 5b3221bdc6edd8123287b2ace0a971eb979d8e2d | /Fiew/Core.h | 1530ea83c859db0915c7f0c1e3ed938d5fc93c0d | []
| no_license | jackiejohn/fedit-image-editor | 0a4b67b46b88362d45db6a2ba7fa94045ad301e2 | fd6a87ed042e8adf4bf88ddbd13f2e3b475d985a | refs/heads/master | 2021-05-29T23:32:39.749370 | 2009-02-25T21:01:11 | 2009-02-25T21:01:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,463 | h | #include <math.h>
#include "commctrl.h"
#include "FwCHAR.h"
#include "List.h"
#include "XUn.h"
#include "ChildCore.h"
#include "Workspace.h"
#include "History.h"
#include "Frame.h"
#include "Tool.h"
#include "Dialogs.h"
#include "Toolws.h"
#include "Interface.h"
#include "Explorer.h"
#include "Cacher.h"
#include "Layer.h"
#include "Drawer.h"
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK MdiProc(HWND, UINT, WPARAM, LPARAM);
class Core
{
protected:
HWND windowHandle; // application handle
HWND mdiclientHandle; // mdi client handle
HINSTANCE instance; // application instance
WNDPROC MDIWndProc; // original mdi window procedure
List<ChildCore> *children; // list of opened child windows
Dialogs *dialogs; // dialogs controler
Toolws *toolws; // tool windows controler
Interface *gui; // gui controler
Explorer *explorer; // unused
Cacher *cacher; // unused
Drawer *drawer; // unused
FwCHAR *commandLine; // command line data
HFONT hFontShell; // default interface font
bool initialized; // init flag
static HMODULE rarDll; // unrar.dll handle
static int chicounter; // child windows counter
public:
Core(WCHAR *cmdLine, HINSTANCE instance);
~Core();
static LRESULT CALLBACK processDialogs(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
static LRESULT CALLBACK processFakeDialogs(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
LRESULT processMessages(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
LRESULT processMdiMessages(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
HWND getWindowHandle();
HWND getMdiclientHandle();
HWND getActiveChildHandle();
ChildCore *getActiveChild();
HINSTANCE getInstance();
List<ChildCore> *getChildren();
Dialogs *getDialogs();
Toolws* getToolws();
Interface *getGui();
Explorer *getExplorer();
void setExplorer(Explorer *explorer);
Cacher *getCacher();
Drawer *getDrawer();
RECT getMdiClientSize();
RECT getClientSize();
void mdiArrange();
void mdiCascade();
void mdiTileVer();
void mdiTileHor();
bool neww(ChildCore *child);
bool openFolder(FwCHAR *path);
bool open(FwCHAR *path, bool save = true);
bool open(WCHAR *path, bool save = true);
void extract();
void setwall();
void close();
void redrawAll(RECT *rect);
int messageBox_Info(WCHAR *string);
int messageBox_Error(WCHAR *string);
int messageBox_Prompt(WCHAR *string);
HFONT CreateHFONT(WCHAR *fontFamily, UINT size, INT style = FontStyleRegular, Unit unit = UnitPoint);
HWND CreateWindowExSubstituteFont(
DWORD dwExStyle,
LPCTSTR lpClassName,
LPCTSTR lpWindowName,
DWORD dwStyle,
int x,
int y,
int nWidth,
int nHeight,
HWND hWndParent,
HMENU hMenu,
HINSTANCE hInstance,
LPVOID lpParam
);
static HMODULE getRarDll();
static void getLastError();
static int getEncoder(WCHAR* format, CLSID* pClsid);
static int tickChicounter();
static int getChicounter();
static int getPixelFormat();
static FwCHAR *getDlgItemString(HWND hDlg, int itemId);
static float getDlgItemNumber(HWND hDlg, int itemId, bool sign);
static Image *getImageResource(WORD id, LPCWSTR type);
static bool isInBmp(Bitmap *bmp, int x, int y);
static Color invClr(Color color, int grey = NULL);
static UINT RGBtoUINT(int r, int g, int b, int a = 255);
static UINT RGBtoUINT(Color rgb);
static Color UINTtoRGB(UINT uint);
static RGBCOLOR UINTtoRGBCOLOR(UINT uint);
static UINT RGBCOLORtoUINT(RGBCOLOR rgba);
static CMYKCOLOR RGBtoCMYK(Color rgb);
static Color CMYKtoRGB(CMYKCOLOR cmyk);
static HSVCOLOR RGBtoHSV(Color rgb);
static Color HSVtoRGB(HSVCOLOR hsv);
static LabCOLOR RGBtoLab(Color rgb);
static Color LabtoRGB(LabCOLOR lab);
static POINT makePoint(LPARAM lParam);
static void clearBitmap(Bitmap *bmp, Rect rect);
static Bitmap *getClipboardBitmap();
static void setClipboardBitmap(Bitmap *bmp);
static bool isClipboardBitmap();
static bool convertToDIB(HBITMAP &hBitmap, HPALETTE &hPalette);
static Core *self;
static Bitmap *clipboardBitmap;
private:
void initialize(HWND windowHandle);
void initializeMdi();
void initializeFonts();
void initializeToolws();
bool extractResource(WORD id, WCHAR *filename);
void loadDlls();
void freeDlls();
void destroy();
}; | [
"[email protected]"
]
| [
[
[
1,
171
]
]
]
|
c6dabbd3f550106738a03693e8e40c04b6a22ff2 | 4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61 | /CleanProject/ParticleUniverse/include/ParticleUniverseAffector.h | 713c2a1ce2ff3525af74482378de6345cc5ccde5 | []
| no_license | bahao247/apeengine2 | 56560dbf6d262364fbc0f9f96ba4231e5e4ed301 | f2617b2a42bdf2907c6d56e334c0d027fb62062d | refs/heads/master | 2021-01-10T14:04:02.319337 | 2009-08-26T08:23:33 | 2009-08-26T08:23:33 | 45,979,392 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,604 | h | /*
-----------------------------------------------------------------------------
This source file is part of the Particle Universe product.
Copyright (c) 2006-2008 Henry van Merode
Usage of this program is free for non-commercial use and licensed under the
the terms of the GNU Lesser General Public License.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.
-----------------------------------------------------------------------------
*/
#ifndef __PU_AFFECTOR_H__
#define __PU_AFFECTOR_H__
#include "ParticleUniversePrerequisites.h"
#include "ParticleUniverseParticle.h"
#include "ParticleUniverseIAlias.h"
#include "ParticleUniverseIElement.h"
namespace ParticleUniverse
{
/** Abstract class defining the interface to be implemented by particle affectors.
@remarks
Particle affectors modify particles in a particle system over their lifetime. This class defines
the interface, and provides a few implementations of some basic functions.
*/
class _ParticleUniverseExport ParticleAffector : public Particle, public IAlias, public IElement
{
public:
/**
The AffectSpecialisation enumeration is used to specialise the affector even more. This enumeration
isn't used by all affectors; in some cases it isn't even applicable.
*/
enum AffectSpecialisation
{
AFSP_DEFAULT,
AFSP_TTL_INCREASE,
AFSP_TTL_DECREASE
};
ParticleAffector(void);
virtual ~ParticleAffector(void) {};
/**
*/
const AffectSpecialisation& getAffectSpecialisation(void) const {return mAffectSpecialisation;};
void setAffectSpecialisation(const AffectSpecialisation& affectSpecialisation) {mAffectSpecialisation = affectSpecialisation;};
/**
*/
const Ogre::String& getAffectorType(void) const {return mAffectorType;};
void setAffectorType(const Ogre::String& affectorType) {mAffectorType = affectorType;};
/**
*/
const Ogre::String& getName(void) const {return mName;};
void setName(const Ogre::String& name) {mName = name;};
/**
*/
ParticleTechnique* getParentTechnique(void) const {return mParentTechnique;};
void setParentTechnique(ParticleTechnique* parentTechnique);
/** Perform initialisation actions.
@remarks
The _prepare() function is automatically called during initialisation (prepare) activities of a
ParticleTechnique. A subclass could implement this function to perform initialisation
actions.
*/
virtual void _prepare(ParticleTechnique* particleTechnique){/* Do nothing */};
/** Perform activities when a ParticleAffector is started.
*/
virtual void _notifyStart (void);
/** Perform activities when a ParticleAffector is stopped.
*/
virtual void _notifyStop (void){/* Do nothing */};
/** Perform activities when a ParticleAffector is paused.
*/
virtual void _notifyPause (void){/* Do nothing */};
/** Perform activities when a ParticleAffector is resumed.
*/
virtual void _notifyResume (void){/* Do nothing */};
/** Notify that the Particle System is rescaled.
*/
virtual void _notifyRescaled(const Ogre::Vector3& scale);
/** Perform activities before the individual particles are processed.
@remarks
This function is called before the ParticleTechnique update-loop where all particles are traversed.
the preProcess is typically used to perform calculations where the result must be used in
processing each individual particle.
*/
virtual void _preProcessParticles(ParticleTechnique* particleTechnique, Ogre::Real timeElapsed){/* Do nothing */};
/** Perform precalculations if the first Particle in the update-loop is processed.
*/
virtual void _firstParticle(ParticleTechnique* particleTechnique,
Particle* particle,
Ogre::Real timeElapsed) { /* by default do nothing */ }
/** Initialise the ParticleAffector before it is emitted itself.
*/
virtual void _initForEmission(void);
/** Initialise the ParticleAffector before it is expired itself.
*/
virtual void _initForExpiration(ParticleTechnique* technique, Ogre::Real timeElapsed);
/** Initialise a newly emitted particle.
@param
particle Pointer to a Particle to initialise.
*/
virtual void _initParticleForEmission(Particle* particle) { /* by default do nothing */ }
/** Entry point for affecting a Particle.
@remarks
Before the actual _affect() function is called, validations have to take place whether
affecting the Particle is really needed. Particles which are emitted by a ParticleEmitter
that has been excluded, will not be affected. This _affect() function is internally called.
@param
particle Pointer to a ParticleTechnique to which the particle belongs.
@param
particle Pointer to a Particle.
@param
timeElapsed The number of seconds which have elapsed since the last call.
@param
firstParticle Determines whether the ParticleAffector encounters the first particle of all active particles.
*/
void _processParticle(ParticleTechnique* particleTechnique,
Particle* particle,
Ogre::Real timeElapsed,
bool firstParticle);
/** Perform activities after the individual particles are processed.
@remarks
This function is called after the ParticleTechnique update-loop where all particles are traversed.
*/
virtual void _postProcessParticles(ParticleTechnique* technique, Ogre::Real timeElapsed){/* Do nothing */};
/** Affect a particle.
@param
particle Pointer to a ParticleTechnique to which the particle belongs.
@param
particle Pointer to a Particle.
@param
timeElapsed The number of seconds which have elapsed since the last call.
*/
virtual void _affect(ParticleTechnique* particleTechnique,
Particle* particle,
Ogre::Real timeElapsed) = 0;
/** Add a ParticleEmitter name that excludes Particles emitted by this ParticleEmitter from being
affected.
*/
void addEmitterToExclude(const Ogre::String& emitterName);
/** Remove a ParticleEmitter name that excludes Particles emitted by this ParticleEmitter.
*/
void removeEmitterToExclude(const Ogre::String& emitterName);
/** Remove all ParticleEmitter names that excludes Particles emitted by this ParticleEmitter.
*/
void removeAllEmittersToExclude(void);
/** Copy attributes to another affector.
*/
virtual void copyAttributesTo (ParticleAffector* affector);
/** Calculate the derived position of the affector.
@remarks
Note, that in script, the position is set as localspace, while if the affector is
emitted, its position is automatically transformed. This function always returns
the derived position.
*/
const Ogre::Vector3& getDerivedPosition(void);
/** If the mAffectSpecialisation is used to specialise the affector, a factor can be calculated and used
in a child class. This factor depends on the value of mAffectSpecialisation.
@remarks
This helper method assumes that the particle pointer is valid.
*/
Ogre::Real _calculateAffectSpecialisationFactor (const Particle* particle);
protected:
ParticleTechnique* mParentTechnique;
// Type of the affector
Ogre::String mAffectorType;
// Name of the affector (optional)
Ogre::String mName;
/** The mAffectSpecialisation is used to specialise the affector. This attribute is comparable with the
mAutoDirection of the ParticleEmitter, it is an optional attribute and used in some of the Particle
Affectors.
*/
AffectSpecialisation mAffectSpecialisation;
/** List of ParticleEmitter names that excludes particles emitted by ParticleEmitters with that name.
@remarks
Particles emitted by an ParticleEmitter with a name that is included in this list are not
affected by this ParticleAffector.
*/
std::list<Ogre::String> mExcludedEmitters;
/** Although the scale is on a Particle System level, it is stored here also, because this value is often
used. It is a derived value, so it has not get a get and set function.
*/
Ogre::Vector3 _mParticleSystemScale;
};
}
#endif
| [
"pablosn@06488772-1f9a-11de-8b5c-13accb87f508"
]
| [
[
[
1,
223
]
]
]
|
4be753188f89065693091fd9864a52f353d0fb57 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libc/testlocalsocket/inc/tlocalsocket.h | 8d55ece3948f20cdbfd727440d3857a90f8a7dbd | []
| no_license | SymbianSource/oss.FCL.sftools.ana.compatanamdw | a6a8abf9ef7ad71021d43b7f2b2076b504d4445e | 1169475bbf82ebb763de36686d144336fcf9d93b | refs/heads/master | 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,920 | h | /*
* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
#ifndef __TESTLOCALSOCKET_H__
#define __TESTLOCALSOCKET_H__
#include <test/TestExecuteStepBase.h>
// INCLUDE FILES
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <e32std.h>
#include <stdlib.h>
#include <string.h>
#include <e32svr.h>
#include <e32def.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <e32std.h>
#include <sys/unistd.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <pthread.h>
#include <net/if.h>
#include <sys/sockio.h>
_LIT(KTestBind, "TestBind");
_LIT(KTestLseek, "TestLseek");
_LIT(KTestFstat, "TestFstat");
_LIT(KTestThreadSocketRead, "TestThreadSocketRead");
_LIT(KTestThreadSocketWrite, "TestThreadSocketWrite");
_LIT(KTestMultProc, "TestMultProc");
_LIT(KTestMultThread, "TestMultThread");
_LIT(KTestListen, "TestListen");
_LIT(KTestSetGetSockOpt, "TestSetGetSockOpt");
_LIT(KTestSetSockOptNegative1, "TestSetSockOptNegative1");
_LIT(KTestSetSockOptNegative2, "TestSetSockOptNegative2");
_LIT(KTestSetSockOptNegative3, "TestSetSockOptNegative3");
_LIT(KTestSetSockOptNegative4, "TestSetSockOptNegative4");
_LIT(KTestGetSockOptNegative1, "TestGetSockOptNegative1");
_LIT(KTestGetSockOptNegative2, "TestGetSockOptNegative2");
_LIT(KTestGetSockOptNegative3, "TestGetSockOptNegative3");
_LIT(KTestGetSockOptNegative4, "TestGetSockOptNegative4");
_LIT(KTestLocalSockIoctl, "TestLocalSockIoctl");
_LIT(KTestLocalSockFcntl, "TestLocalSockFcntl");
_LIT(KTestLocalSockSelect, "TestLocalSockSelect");
class CTestLocalSocket : public CTestStep
{
public:
~CTestLocalSocket();
CTestLocalSocket(const TDesC& aStepName);
TVerdict doTestStepL();
TVerdict doTestStepPreambleL();
TVerdict doTestStepPostambleL();
private:
void GetParameters(char aParamets[10][256]);
TInt TestBind();
TInt TestLseek();
TInt TestFstat();
TInt TestThreadSocketRead();
TInt TestThreadSocketWrite();
TInt TestMultProc();
TInt TestMultThread();
TInt TestListen();
TInt TestSetGetSockOpt();
TInt TestSetSockOptNegative1();
TInt TestSetSockOptNegative2();
TInt TestSetSockOptNegative3();
TInt TestSetSockOptNegative4();
TInt TestGetSockOptNegative1();
TInt TestGetSockOptNegative2();
TInt TestGetSockOptNegative3();
TInt TestGetSockOptNegative4();
TInt TestLocalSockIoctl();
TInt TestLocalSockFcntl();
TInt TestLocalSockSelect();
};
#endif
| [
"none@none"
]
| [
[
[
1,
102
]
]
]
|
1f32eeda23e0a2e341a77c3e5a70387c82f63533 | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/nGENE Proj/MemoryManager.cpp | c7e857fe51117adf964a68f1101dd90c389797a4 | []
| no_license | svn2github/ngene | b2cddacf7ec035aa681d5b8989feab3383dac012 | 61850134a354816161859fe86c2907c8e73dc113 | refs/heads/master | 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,860 | cpp | /*
---------------------------------------------------------------------------
This source file is part of nGENE Tech.
Copyright (c) 2006- Wojciech Toman
This progm_pMemory is free software.
File: MemoryManager.cpp
Version: 0.01
---------------------------------------------------------------------------
*/
#include "PrecompiledHeaders.h"
#include "MemoryManager.h"
namespace nGENE
{
// Initialize static members
bool MemoryManager::m_bIsInitialized = false;
//HashTable <dword, MemoryAllocator*> MemoryManager::m_pAllocators;
SAllocList* MemoryManager::m_pList = NULL;
MemoryManager::MemoryManager()
{
init();
}
//----------------------------------------------------------------------
MemoryManager::~MemoryManager()
{
/*if(!m_pAllocators.empty())
{
HashTable <dword, MemoryAllocator*>::iterator iter;
for(iter = m_pAllocators.begin(); iter != m_pAllocators.end(); ++iter)
delete iter->second;
m_pAllocators.clear();
}*/
SAllocList* pAllocator = m_pList;
SAllocList* pTemp = NULL;
while(pAllocator)
{
pTemp = pAllocator;
pAllocator = pAllocator->pNext;
::free(pTemp->pAllocator);
::free(pTemp);
}
}
//----------------------------------------------------------------------
void MemoryManager::init()
{
m_pList = (SAllocList*)::malloc(sizeof(SAllocList));
m_pList->pAllocator = (MemoryAllocator*)::malloc(sizeof(MemoryAllocator));
m_pList->pAllocator->init(4 * 1000 * 50, 4);
m_pList->pNext = (SAllocList*)::malloc(sizeof(SAllocList));
SAllocList* pHead = m_pList;
m_pList = m_pList->pNext;
m_pList->pAllocator = (MemoryAllocator*)::malloc(sizeof(MemoryAllocator));
m_pList->pAllocator->init(8 * 1000 * 50, 8);
m_pList->pNext = (SAllocList*)::malloc(sizeof(SAllocList));
m_pList = m_pList->pNext;
m_pList->pAllocator = (MemoryAllocator*)::malloc(sizeof(MemoryAllocator));
m_pList->pAllocator->init(16 * 1000 * 50, 16);
m_pList->pNext = (SAllocList*)::malloc(sizeof(SAllocList));
m_pList = m_pList->pNext;
m_pList->pAllocator = (MemoryAllocator*)::malloc(sizeof(MemoryAllocator));
m_pList->pAllocator->init(32 * 100 * 50, 32);
m_pList->pNext = (SAllocList*)::malloc(sizeof(SAllocList));
m_pList = m_pList->pNext;
m_pList->pAllocator = (MemoryAllocator*)::malloc(sizeof(MemoryAllocator));
m_pList->pAllocator->init(64 * 100, 64);
m_pList->pNext = (SAllocList*)::malloc(sizeof(SAllocList));
m_pList = m_pList->pNext;
m_pList->pAllocator = (MemoryAllocator*)::malloc(sizeof(MemoryAllocator));
m_pList->pAllocator->init(128 * 100, 128);
m_pList->pNext = (SAllocList*)::malloc(sizeof(SAllocList));
m_pList = m_pList->pNext;
m_pList->pAllocator = (MemoryAllocator*)::malloc(sizeof(MemoryAllocator));
m_pList->pAllocator->init(256 * 100, 256);
m_pList->pNext = (SAllocList*)::malloc(sizeof(SAllocList));
m_pList = m_pList->pNext;
m_pList->pAllocator = (MemoryAllocator*)::malloc(sizeof(MemoryAllocator));
m_pList->pAllocator->init(512 * 100, 512);
m_pList->pNext = (SAllocList*)::malloc(sizeof(SAllocList));
m_pList = m_pList->pNext;
m_pList->pAllocator = (MemoryAllocator*)::malloc(sizeof(MemoryAllocator));
m_pList->pAllocator->init(1024 * 100, 1024);
m_pList->pNext = (SAllocList*)::malloc(sizeof(SAllocList));
m_pList = m_pList->pNext;
m_pList->pAllocator = (MemoryAllocator*)::malloc(sizeof(MemoryAllocator));
m_pList->pAllocator->init(2048 * 100, 2048);
m_pList->pNext = (SAllocList*)::malloc(sizeof(SAllocList));
m_pList = m_pList->pNext;
m_pList->pAllocator = (MemoryAllocator*)::malloc(sizeof(MemoryAllocator));
m_pList->pAllocator->init(4096 * 100, 4096);
m_pList->pNext = (SAllocList*)::malloc(sizeof(SAllocList));
m_pList = m_pList->pNext;
m_pList->pAllocator = (MemoryAllocator*)::malloc(sizeof(MemoryAllocator));
m_pList->pAllocator->init(65 * 100000, 65 * 100000);
m_pList->pNext = NULL;
m_pList = pHead;
m_bIsInitialized = true;
}
//----------------------------------------------------------------------
void* MemoryManager::malloc(uint _size)
{
if(!m_bIsInitialized)
init();
if(!_size)
return NULL;
void* pResult = NULL;
// if(m_pAllocators.find(_size) == m_pAllocators.end())
// m_pAllocators[_size] = new MemoryAllocator(_size * 100, _size);
SAllocList* pAllocator = m_pList;
while(pAllocator)
{
// @todo if there is no free space in allocator proceed to the next one.
if(_size <= pAllocator->pAllocator->getChunkSize())
break;
pAllocator = pAllocator->pNext;
}
Assert(pAllocator, "Appropriate allocator not found!");
pResult = pAllocator->pAllocator->malloc(_size);//m_pAllocators[_size]->malloc(_size);
Assert(pResult, "Failed to allocate memory!");
return pResult;
}
//----------------------------------------------------------------------
void MemoryManager::free(void* _ptr)
{
if(!_ptr)
return;
// We have to find out to which allocator the pointer belongs
dword addr = reinterpret_cast<int>(_ptr);
SAllocList* pDeallocator = m_pList;
while(pDeallocator)
{
if(addr >= pDeallocator->pAllocator->getBeginAddr() && addr <= pDeallocator->pAllocator->getEndAddr())
break;
pDeallocator = pDeallocator->pNext;
}
Assert(pDeallocator, "Memory could not be freed!");
pDeallocator->pAllocator->free(_ptr);
}
//----------------------------------------------------------------------
MemoryAllocator::MemoryAllocator(uint _size, uint _chunkSize):
m_dwSize(_size),
m_dwChunkSize(_chunkSize)
{
init(_size, _chunkSize);
}
//----------------------------------------------------------------------
void MemoryAllocator::init(uint _size, uint _chunkSize)
{
if(!_chunkSize || !_size || _size < _chunkSize)
exit(1);
m_dwSize = _size;
m_dwChunkSize = _chunkSize;
m_pMemory = (byte*)::malloc(m_dwSize);
memset(m_pMemory, 0xcc, m_dwSize);
m_dwRows = m_dwSize / m_dwChunkSize;
for(dword i = 1; i < m_dwSize; i += m_dwChunkSize + 1)
{
*getState(i) = MBS_FREE;
}
}
//----------------------------------------------------------------------
MemoryAllocator::~MemoryAllocator()
{
// Free any undeallocated memory
::free(m_pMemory);
}
//----------------------------------------------------------------------
byte* MemoryAllocator::getState(dword _index)
{
return (byte*)(&m_pMemory[--_index]);
}
//----------------------------------------------------------------------
void* MemoryAllocator::malloc(uint _size)
{
for(dword i = 1; i < m_dwSize - _size - 1; i += m_dwChunkSize + 1)
{
if(*getState(i) == MBS_FREE)
{
*getState(i) = MBS_OCCUPIED;
return (void*)(&m_pMemory[i]);
}
}
return NULL;
}
//----------------------------------------------------------------------
void MemoryAllocator::free(void* _ptr)
{
if(_ptr > (void*)&m_pMemory[m_dwSize - 1] || _ptr < (void*)&m_pMemory[0])
return;
dword free = (dword)(((byte*)_ptr) - &m_pMemory[0]);
Assert(free, "Address in first byte!");
Assert(*getState(free) == MBS_OCCUPIED, "Attempt to release invalid region!");
*getState(free) = MBS_FREE;
// _ptr = (void*)0x00000000;
}
//----------------------------------------------------------------------
dword MemoryAllocator::getBeginAddr() const
{
return (dword)(&m_pMemory[0]);
}
//----------------------------------------------------------------------
dword MemoryAllocator::getEndAddr() const
{
return (dword)(&m_pMemory[m_dwSize-1]);
}
//----------------------------------------------------------------------
dword MemoryAllocator::getChunkSize() const
{
return m_dwChunkSize;
}
//----------------------------------------------------------------------
} | [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
]
| [
[
[
1,
247
]
]
]
|
ec6d1c212d916c51cfae0ad430feab6878e4f62d | cb0268e95542374ff2abf2b9c770d1c106774624 | /modelLoader/fileHandler.cpp | 71d1fc08bb7ea1d897cbbe03542a7bc802c162f9 | []
| no_license | xXSingularityXx/Bomber-Rage-3D | a898e046cf93649a052d5c1ad019cc60dd5184ce | 7249c95055ca5df6c05775f8006f307dab5cc856 | refs/heads/master | 2021-01-10T21:20:31.343120 | 2009-12-17T07:54:42 | 2009-12-17T07:54:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,126 | cpp |
#include "fileHandler.h"
fileHandler::fileHandler()
{
m_objFile = new std::ifstream();
m_fileSize = 0;
m_fileData = NULL;
m_isOpen = FAILED;
}
void fileHandler::openFile(std::string _texPath)
{
//open the binary file for input/output operations
m_objFile->open(_texPath.c_str(), std::ios::binary|std::ios::ate);
// error opening the File
if (!m_objFile->is_open())
{
m_isOpen = FAILED;
std::cout << "ERROR: cannot open the file " << _texPath.c_str() << "! Press any key to exit";
return;
}
// get the file size
m_fileSize = m_objFile->tellg();
m_objFile->seekg(0, std::ios::beg);
// read all the file and get its data
m_fileData = new unsigned char[m_fileSize];
m_objFile->read(reinterpret_cast<char*>(m_fileData),m_fileSize);
// close the file
m_objFile->close();
m_isOpen = SUCCESS;
}
bool fileHandler::isOpen()
{
return m_isOpen;
}
unsigned char* fileHandler::getFileData()
{
return m_fileData;
}
int fileHandler::getFileSize()
{
return m_fileSize;
}
fileHandler::~fileHandler()
{
delete [] m_fileData;
delete m_objFile;
}
| [
"Samuel@matschulat.(none)"
]
| [
[
[
1,
58
]
]
]
|
9de4e514f3eac1e34fa73f8a8690d7f3eba1321c | 5095bbe94f3af8dc3b14a331519cfee887f4c07e | /Shared/data/apsim_depth_table.cpp | b2c0d6486acb3567252c46acf8bb06256eaf5113 | []
| no_license | sativa/apsim_development | efc2b584459b43c89e841abf93830db8d523b07a | a90ffef3b4ed8a7d0cce1c169c65364be6e93797 | refs/heads/master | 2020-12-24T06:53:59.364336 | 2008-09-17T05:31:07 | 2008-09-17T05:31:07 | 64,154,433 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,156 | cpp | #include <general\pch.h>
#include <vcl.h>
#pragma hdrstop
#include "apsim_depth_table.h"
#include <general\string_functions.h>
#include <general\stream_functions.h>
#include <general\stl_functions.h>
#include <general\math_functions.h>
#include <strstrea.h>
#include <stdio.h>
// ------------------------------------------------------------------
// Short description:
// constructor
// Notes:
// Changes:
// DPH 17/4/1997
// ------------------------------------------------------------------
APSIM_depth_table::APSIM_depth_table (void)
{
}
// ------------------------------------------------------------------
// Short description:
// constructor
// Notes:
// Changes:
// DPH 17/4/1997
// ------------------------------------------------------------------
APSIM_depth_table::APSIM_depth_table (const char* Fname)
: APSIM_table (Fname)
{
}
// ------------------------------------------------------------------
// Short description:
// goto first record.
// Notes:
// Changes:
// DPH 17/4/1997
// ------------------------------------------------------------------
void APSIM_depth_table::Read_field_names (void)
{
APSIM_table::Read_field_names();
Real_field_names = Field_names;
Num_layers = 0;
// Loop through all field names and copy all fields to our field list.
// Where array fields are encountered (eg dlayer(1), dlayer(2)) only
// copy one field name (dlayer) to the field list minus the array index.
vector <string> Our_list;
for (vector<string>::iterator Iter = Field_names.begin();
Iter != Field_names.end();
Iter++)
{
string This_field = *Iter;
if (This_field.find("(1)") != string::npos)
{
This_field.erase(This_field.find("(1)"));
Our_list.push_back (This_field);
}
else if (This_field.find("(") != string::npos)
{
// extract array specifier.
string Array_spec = This_field.substr(This_field.find("("));
istrstream Array_stream ((char*) Array_spec.c_str());
string Array_size_string;
Read_token (Array_stream, "( ", " )", Array_size_string);
// update number of layers for this table.
Num_layers = max(Num_layers, atoi (Array_size_string.c_str()));
}
else
Our_list.push_back (This_field);
}
Field_names = Our_list;
}
// ------------------------------------------------------------------
// Short description:
// return index of a field to caller. Returns -1 if not found.
// Notes:
// Changes:
// DPH 17/4/1997
// ------------------------------------------------------------------
int APSIM_depth_table::Get_field_index (const char* Field_name)
{
int Indx = Locate_string (Field_name, Real_field_names);
if (Indx < 0)
{
// must be a depth field - add (1)
string New_field = Field_name;
New_field += "(1)";
// Get index for field name.
Indx = Locate_string (New_field.c_str(), Real_field_names);
}
return Indx;
}
// ------------------------------------------------------------------
// Short description:
// return data to caller using an index into the field names list as lookup.
// Notes:
// Changes:
// DPH 17/4/1997
// ------------------------------------------------------------------
void APSIM_depth_table::Get_data_by_index (unsigned int Field_index, char* Value)
{
unsigned int Pos_array = Real_field_names[Field_index].find("(");
bool Is_depth_field = (Pos_array != string::npos);
if (Is_depth_field)
{
// create a base for array variable by striping off the array specifier.
string New_field = Real_field_names[Field_index].substr(0, Pos_array);
// work out if this variable is a cumulative one.
bool Is_cumulative = (Cumulative_variable_name == New_field);
// need to build up a field name.
char Field_name[100];
sprintf(Field_name, "%s(%i)", New_field.c_str(), Current_layer);
// Get index for field name.
Field_index = Get_field_index(Field_name);
// get value for this variable.
APSIM_table::Get_data_by_index (Field_index, Value);
// is this a cumulative variable? If so then add value to running total
if (Is_cumulative)
{
Cumulative_value += atof(Value);
char Cumulative_str[100];
sprintf (Cumulative_str, "%5.1f", Cumulative_value);
strcpy(Value, Cumulative_str);
}
}
else
APSIM_table::Get_data_by_index (Field_index, Value);
}
// ------------------------------------------------------------------
// Short description:
// position stream at beginning of first record.
// Notes:
// Changes:
// DPH 17/4/1997
// ------------------------------------------------------------------
void APSIM_depth_table::Position_at_first (void)
{
APSIM_table::Position_at_first ();
Current_layer = Num_layers + 2;
}
// ------------------------------------------------------------------
// Short description:
// position stream at beginning of last record.
// Notes:
// Changes:
// DPH 17/4/1997
// ------------------------------------------------------------------
void APSIM_depth_table::Position_at_last (void)
{
Current_layer = 0; // forces read_next_record to read in a line.
APSIM_table::Position_at_last ();
}
// ------------------------------------------------------------------
// Short description:
// position stream at beginning of next record.
// Notes:
// Changes:
// DPH 17/4/1997
// ------------------------------------------------------------------
void APSIM_depth_table::Position_at_next (void)
{
if (Current_layer < 1 || Current_layer > Num_layers)
APSIM_table::Position_at_next ();
Current_layer++;
}
// ------------------------------------------------------------------
// Short description:
// position stream at beginning of previous record.
// Notes:
// Changes:
// DPH 17/4/1997
// ------------------------------------------------------------------
void APSIM_depth_table::Position_at_prior (void)
{
if (Current_layer < 1 || Current_layer > Num_layers)
APSIM_table::Position_at_prior ();
Current_layer--;
}
// ------------------------------------------------------------------
// Short description:
// read next line from stream.
// Notes:
// Changes:
// DPH 17/4/1997
// ------------------------------------------------------------------
void APSIM_depth_table::Read_next_record (void)
{
if (Current_layer < 1 || Current_layer > Num_layers)
{
APSIM_table::Read_next_record();
if (Current_layer == 0)
Current_layer = Num_layers;
else
Current_layer = 1;
Cumulative_value = 0.0;
}
}
| [
"devoilp@8bb03f63-af10-0410-889a-a89e84ef1bc8"
]
| [
[
[
1,
253
]
]
]
|
30b74d4011f418d017759196039c4ea24e0a5712 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/os/xmlsrv/xml_engine_dom_api/src/DomBCTester.cpp | 885e3dca75353812fe77d5fb017e561ef17f5f9a | []
| no_license | SymbianSource/oss.FCL.sftools.ana.compatanamdw | a6a8abf9ef7ad71021d43b7f2b2076b504d4445e | 1169475bbf82ebb763de36686d144336fcf9d93b | refs/heads/master | 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,231 | cpp | /*
* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: ?Description
*
*/
// INCLUDE FILES
#include "DomBCTester.h"
#include "BCTesterDefs.h"
#include <Stiftestinterface.h>
// EXTERNAL DATA STRUCTURES
// EXTERNAL FUNCTION PROTOTYPES
// CONSTANTS
// MACROS
// LOCAL CONSTANTS AND MACROS
// MODULE DATA STRUCTURES
// LOCAL FUNCTION PROTOTYPES
// FORWARD DECLARATIONS
// ============================ MEMBER FUNCTIONS ===============================
// -----------------------------------------------------------------------------
// CDomBCTester::CDomBCTester
// C++ default constructor can NOT contain any code, that
// might leave.
// -----------------------------------------------------------------------------
//
CDomBCTester::CDomBCTester(CTestModuleIf& aTestModuleIf )
:CScriptBase( aTestModuleIf )
{
}
// -----------------------------------------------------------------------------
// CDomBCTester::ConstructL
// Symbian 2nd phase constructor can leave.
// -----------------------------------------------------------------------------
//
void CDomBCTester::ConstructL()
{
iLog = CStifLogger::NewL( KXML_TestLogPath,
KXML_TestLogFile,
CStifLogger::ETxt,
CStifLogger::EFile,
EFalse );
DOM_impl.OpenL( );
TInt err = parser.Open( DOM_impl );
if(KErrNone != err)
User::Leave(err);
infoNum = 0;
iLastError = KErrNone;
}
// -----------------------------------------------------------------------------
// CDomBCTester::NewL
// Two-phased constructor.
// -----------------------------------------------------------------------------
//
CDomBCTester* CDomBCTester::NewL(CTestModuleIf& aTestModuleIf )
{
CDomBCTester* self = new (ELeave) CDomBCTester( aTestModuleIf );
CleanupStack::PushL( self );
self->ConstructL();
CleanupStack::Pop( self );
return self;
}
// Destructor
CDomBCTester::~CDomBCTester()
{
if(iDoc.NotNull())
{
iDoc.Close();
}
parser.Close();
DOM_impl.Close();
// Delete resources allocated from test methods
Delete();
// Delete logger
delete iLog;
}
// ========================== OTHER EXPORTED FUNCTIONS =========================
// -----------------------------------------------------------------------------
// LibEntryL is a polymorphic Dll entry point.
// Returns: CScriptBase: New CScriptBase derived object
// -----------------------------------------------------------------------------
//
EXPORT_C CScriptBase* LibEntryL(CTestModuleIf& aTestModuleIf ) // Backpointer to STIF Test Framework
{
return ( CScriptBase* ) CDomBCTester::NewL( aTestModuleIf );
}
// End of File
| [
"none@none"
]
| [
[
[
1,
120
]
]
]
|
c5622a4c162858ef8519c62fcb74c46131b4bb82 | 61576c87f5a1c6a1e94ede4cba8ecf84978836ae | /src/callback_handler.hpp | 2f6f13e6c4a5ed7102e2b85d787f70314287c55e | []
| no_license | jdmichaud/newswatch | 183553c166860475e055f87c94ab783e1e0d0c11 | 97aac3d9b16e8160fd407bb3d07c4873291f0500 | refs/heads/master | 2021-01-21T19:27:53.853232 | 2008-04-27T19:39:41 | 2008-04-27T19:39:41 | 32,138,021 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,624 | hpp | #ifndef _CALLBACK_HANDLER_HPP_
#define _CALLBACK_HANDLER_HPP_
#include <string>
#include <vector>
#include <boost/function.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include "logging.hpp"
class handler_t
{
public:
virtual void operator()() { assert(0); }
};
class new_article_handler_t : public handler_t
{
public:
void add_uid(unsigned int uid) { m_uids.push_back(uid); }
std::vector<unsigned int> m_uids;
};
class new_newspaper_handler_t : public handler_t
{
public:
void set_name(const std::string &name) { m_newspaper_name = name; }
std::string m_newspaper_name;
};
class callback_handler;
class callback_handler
{
public:
callback_handler() {}
~callback_handler()
{
m_thread_group.join_all();
}
static callback_handler *get_instance()
{
static boost::mutex m_inst_mutex;
boost::mutex::scoped_lock scoped_lock(m_inst_mutex);
static callback_handler *c = NULL;
if (!c)
{
c = new callback_handler();
static boost::shared_ptr<callback_handler> s_ptr_c(c);
}
return c;
}
void new_article(unsigned int uid)
{
LOGLITE_LOG_(LOGLITE_LEVEL_1, "callback_handler::new_article called");
std::vector<new_article_handler_t *>::iterator it = m_new_article_callbacks.begin();
for (; it != m_new_article_callbacks.end(); ++it)
{
(*it)->add_uid(uid);
new_article_handler_t *ah = *it;
m_thread_vector.push_back(m_thread_group.create_thread(boost::bind(&new_article_handler_t::operator(), ah)));
}
}
void new_newspaper(const std::string &newspaper_name)
{
LOGLITE_LOG_(LOGLITE_LEVEL_1, "callback_handler::new_newspaper called");
std::vector<new_newspaper_handler_t *>::iterator it = m_new_newspaper_callbacks.begin();
for (; it != m_new_newspaper_callbacks.end(); ++it)
{
(*it)->set_name(newspaper_name);
m_thread_vector.push_back(m_thread_group.create_thread(**it));
}
}
void register_to_new_article(new_article_handler_t *f)
{
assert(f);
m_new_article_callbacks.push_back(f);
}
void register_to_new_newspaper(new_newspaper_handler_t *f)
{
assert(f);
m_new_newspaper_callbacks.push_back(f);
}
private:
std::vector<new_article_handler_t *> m_new_article_callbacks;
std::vector<new_newspaper_handler_t *> m_new_newspaper_callbacks;
boost::thread_group m_thread_group;
std::vector<boost::thread *> m_thread_vector;
};
#endif // ! _CALLBACK_HANDLER_HPP_
| [
"jean.daniel.michaud@750302d9-4032-0410-994c-055de1cff029"
]
| [
[
[
1,
104
]
]
]
|
c1ce441908dfa5e1f989e988d6a0910946ba9df3 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/os/kernelhwsrv/base/FileSystemPlugins/inc/T_TestFSY.h | c8065364ce42f82f905261c457bf43a84ba445b4 | []
| no_license | SymbianSource/oss.FCL.sftools.ana.compatanamdw | a6a8abf9ef7ad71021d43b7f2b2076b504d4445e | 1169475bbf82ebb763de36686d144336fcf9d93b | refs/heads/master | 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,741 | h | /*
* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
/**
@test
@internalComponent
This contains CTestFileSystem
*/
#if (!defined __T_TEST_FSY_H__)
#define __T_TEST_FSY_H__
// EPOC includes
#include <f32fsys.h>
class CTestMountCB : public CMountCB
{
public:
CTestMountCB() {}
~CTestMountCB() {}
virtual void MountL(TBool /*aForceMount*/) {}
virtual TInt ReMount() { return KErrNone; }
virtual void Dismounted() {}
virtual void VolumeL(TVolumeInfo& /*aVolume*/) const {}
virtual void SetVolumeL(TDes& /*aName*/) {}
virtual void MkDirL(const TDesC& /*aName*/) {}
virtual void RmDirL(const TDesC& /*aName*/) {}
virtual void DeleteL(const TDesC& /*aName*/) {}
virtual void RenameL(const TDesC& /*anOldName*/,const TDesC& /*anNewName*/) {}
virtual void ReplaceL(const TDesC& /*anOldName*/,const TDesC& /*anNewName*/) {}
virtual void EntryL(const TDesC& /*aName*/,TEntry& /*anEntry*/) const {}
virtual void SetEntryL(const TDesC& /*aName*/,const TTime& /*aTime*/,TUint /*aSetAttMask*/,TUint /*aClearAttMask*/) {}
virtual void FileOpenL(const TDesC& /*aName*/,TUint /*aMode*/,TFileOpen /*anOpen*/,CFileCB* /*aFile*/) {}
virtual void DirOpenL(const TDesC& /*aName*/,CDirCB* /*aDir*/) {}
virtual void RawReadL(TInt64 /*aPos*/,TInt /*aLength*/,const TAny* /*aTrg*/,TInt /*anOffset*/,const RMessagePtr2& /*aMessage*/) const {}
virtual void RawWriteL(TInt64 /*aPos*/,TInt /*aLength*/,const TAny* /*aSrc*/,TInt /*anOffset*/,const RMessagePtr2& /*aMessage*/) {}
virtual void ReadUidL(const TDesC& /*aName*/,TEntry& /*anEntry*/) const {}
virtual void GetShortNameL(const TDesC& /*aLongName*/,TDes& /*aShortName*/) {}
virtual void GetLongNameL(const TDesC& /*aShortName*/,TDes& /*aLongName*/) {}
virtual void IsFileInRom(const TDesC& /*aFileName*/,TUint8*& /*aFileStart*/) {}
virtual void ReadSectionL(const TDesC& /*aName*/,TInt /*aPos*/,TAny* /*aTrg*/,TInt /*aLength*/,const RMessagePtr2& /*aMessage*/) {}
};
class CTestFileCB : public CFileCB
{
public:
CTestFileCB() {}
~CTestFileCB() {}
virtual void RenameL(const TDesC& /*aNewName*/) {}
virtual void ReadL(TInt /*aPos*/,TInt& /*aLength*/,const TAny* /*aDes*/,const RMessagePtr2& /*aMessage*/) {}
virtual void WriteL(TInt /*aPos*/,TInt& /*aLength*/,const TAny* /*aDes*/,const RMessagePtr2& /*aMessage*/) {}
virtual TInt Address(TInt& /*aPos*/) const {return 0;}
virtual void SetSizeL(TInt /*aSize*/) {}
virtual void SetEntryL(const TTime& /*aTime*/,TUint /*aSetAttMask*/,TUint /*aClearAttMask*/) {}
virtual void FlushDataL() {}
virtual void FlushAllL() {}
virtual void CheckPos(TInt /*aPos*/) {}
};
class CTestDirCB : public CDirCB
{
public:
CTestDirCB() {}
~CTestDirCB() {}
virtual void ReadL(TEntry& /*anEntry*/) {}
};
class CTestFormatCB : public CFormatCB
{
public:
CTestFormatCB() {}
~CTestFormatCB() {}
virtual void DoFormatStepL() {}
};
class CTestFileSystem : public CFileSystem
{
public:
TInt DefaultPath(TDes& aPath) const;
void DriveInfo(TDriveInfo& anInfo, TInt aDriveNumber) const;
TBusLocalDrive& DriveNumberToLocalDrive(TInt aDriveNumber) const;
CMountCB* NewMountL() const;
CFileCB* NewFileL() const;
CDirCB* NewDirL() const;
CFormatCB* NewFormatL() const;
protected:
CTestFileSystem();
};
#endif /* __T_TEST_FSY_H__ */
| [
"none@none"
]
| [
[
[
1,
106
]
]
]
|
67bd8c1328ae0bc50f4e59da6ac3b3b70c0b2cb1 | b14d5833a79518a40d302e5eb40ed5da193cf1b2 | /cpp/extern/xercesc++/2.6.0/src/xercesc/util/BinInputStream.hpp | 6c06368a8ca0a610be9e0cf0720801a533b02be4 | [
"Apache-2.0"
]
| permissive | andyburke/bitflood | dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf | fca6c0b635d07da4e6c7fbfa032921c827a981d6 | refs/heads/master | 2016-09-10T02:14:35.564530 | 2011-11-17T09:51:49 | 2011-11-17T09:51:49 | 2,794,411 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,121 | hpp | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Log: BinInputStream.hpp,v $
* Revision 1.5 2004/09/08 13:56:21 peiyongz
* Apache License Version 2.0
*
* Revision 1.4 2003/05/15 19:04:35 knoaman
* Partial implementation of the configurable memory manager.
*
* Revision 1.3 2003/03/07 18:11:54 tng
* Return a reference instead of void for operator=
*
* Revision 1.2 2002/11/04 15:22:03 tng
* C++ Namespace Support.
*
* Revision 1.1.1.1 2002/02/01 22:22:10 peiyongz
* sane_include
*
* Revision 1.4 2000/03/02 19:54:38 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.3 2000/02/24 20:05:23 abagchi
* Swat for removing Log from API docs
*
* Revision 1.2 2000/02/06 07:48:01 rahulj
* Year 2K copyright swat.
*
* Revision 1.1.1.1 1999/11/09 01:04:03 twl
* Initial checkin
*
* Revision 1.3 1999/11/08 20:45:04 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
#if !defined(BININPUTSTREAM_HPP)
#define BININPUTSTREAM_HPP
#include <xercesc/util/XMemory.hpp>
XERCES_CPP_NAMESPACE_BEGIN
class XMLUTIL_EXPORT BinInputStream : public XMemory
{
public :
// -----------------------------------------------------------------------
// Virtual destructor for derived classes
// -----------------------------------------------------------------------
virtual ~BinInputStream();
// -----------------------------------------------------------------------
// The virtual input stream interface
// -----------------------------------------------------------------------
virtual unsigned int curPos() const = 0;
virtual unsigned int readBytes
(
XMLByte* const toFill
, const unsigned int maxToRead
) = 0;
protected :
// -----------------------------------------------------------------------
// Hidden Constructors
// -----------------------------------------------------------------------
BinInputStream();
private :
// -----------------------------------------------------------------------
// Unimplemented Constructors
// -----------------------------------------------------------------------
BinInputStream(const BinInputStream&);
BinInputStream& operator=(const BinInputStream&);
};
XERCES_CPP_NAMESPACE_END
#endif
| [
"[email protected]"
]
| [
[
[
1,
98
]
]
]
|
9199120011318a7b6fa5038e16f6fcfc025b5504 | 0454def9ffc8db9884871a7bccbd7baa4322343b | /src/plugins/albumartex/QUAlbumArtExRequestUrl.cpp | 1f2975d8511929b1b83398b6fc65e909881ae309 | []
| no_license | escaped/uman | e0187d1d78e2bb07dade7ef6ef041b6ed424a2d3 | bedc1c6c4fc464be4669f03abc9bac93e7e442b0 | refs/heads/master | 2016-09-05T19:26:36.679240 | 2010-07-26T07:55:31 | 2010-07-26T07:55:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,388 | cpp | #include "QUAlbumArtExRequestUrl.h"
#include "QU.h"
#include "QUStringSupport.h"
#include "QUSongSupport.h"
#include "QUSongInterface.h"
#include <QVariant>
#include <QSettings>
QUAlbumArtExRequestUrl::QUAlbumArtExRequestUrl(const QString &host, const QStringList &properties, QUSongInterface *song): QURequestUrl(host, properties, song) {
initQuery();
}
QString QUAlbumArtExRequestUrl::request() const {
QString result = QString("http://%1/covers.php?grid=4x5&%2")
.arg(host())
.arg(QString(fixedPercentageEncoding()));
song()->log(tr("[albumartex - search] ") + result, QU::Help);
return result;
}
void QUAlbumArtExRequestUrl::initQuery() {
QList<QPair<QString, QString> > query;
QStringList data;
foreach(QString property, properties()) {
if(QUSongSupport::availableCustomTags().contains(property, Qt::CaseInsensitive))
data << (QUStringSupport::withoutAnyUmlaut(song()->customTag(property)));
else
data << (QUStringSupport::withoutAnyUmlaut(song()->property(property.toLower().toLocal8Bit().data()).toString()));
}
QSettings settings;
query << QPair<QString, QString>("sort", settings.value("albumartex/sort by").toString());
query << QPair<QString, QString>("q", data.join(" ").trimmed());
query << QPair<QString, QString>("fltr", settings.value("albumartex/filter").toString());
setQueryItems(query);
}
| [
"[email protected]"
]
| [
[
[
1,
41
]
]
]
|
80469979d9f7e7a72f8d17aed3e7b3165e2bb193 | 9a33169387ec29286d82e6e0d5eb2a388734c969 | /3DBipedRobot/Camera.h | a0c060020946406968c5b217a60af20d79278cc4 | []
| no_license | cecilerap/3dbipedrobot | a62773a6db583d66c80f9b8ab78d932b163c8dd9 | 83c8f972e09ca8f16c89fc9064c55212d197d06a | refs/heads/master | 2021-01-10T13:28:09.532652 | 2009-04-24T03:03:13 | 2009-04-24T03:03:13 | 53,042,363 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 927 | h | //////////////////////////////////////////////////////////////////////////
// Camera.h
//////////////////////////////////////////////////////////////////////////
#pragma once
#include <d3d9.h>
#include <d3dx9.h>
class CCamera
{
public:
CCamera(LPDIRECT3DDEVICE9 pD3DDevice);
~CCamera(void);
void SetCamera();
void SetMousePos(int x, int y);
void Move(int x, int y);
void Zoom(int nWheel);
float GetTheta() { return m_posTheta; }
float GetPhi() { return m_posPhi; }
float GetRadius() { return m_radius; }
private:
LPDIRECT3DDEVICE9 m_pD3DDevice;
POINT m_curPt;
float m_posTheta; // 좌우
float m_posPhi; // 상하
float m_radius; // 확대/축소
D3DXMATRIX m_matView;
D3DXVECTOR3 m_vEye;
D3DXVECTOR3 m_vLookat;
D3DXVECTOR3 m_vUp;
D3DXVECTOR3 m_vView; // 카메라의 단위 방향 벡터
D3DXVECTOR3 m_vCross; // 카메라의 측면 벡터
}; | [
"t2wish@463fb1f2-0299-11de-9d1d-173cc1d06e3c"
]
| [
[
[
1,
41
]
]
]
|
46633d2ccaa4d7f16a79592506e39526880d20c9 | dadf8e6f3c1adef539a5ad409ce09726886182a7 | /airplay/h/toeSimpleMenuImage.h | fe603e0bf39e6ddbb8406da01d5a9f43b5d13113 | []
| no_license | sarthakpandit/toe | 63f59ea09f2c1454c1270d55b3b4534feedc7ae3 | 196aa1e71e9f22f2ecfded1c3da141e7a75b5c2b | refs/heads/master | 2021-01-10T04:04:45.575806 | 2011-06-09T12:56:05 | 2011-06-09T12:56:05 | 53,861,788 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,239 | h | #pragma once
#include <IwResManager.h>
#include <IwManagedList.h>
#include "toeSimpleMenuTerminalItem.h"
namespace TinyOpenEngine
{
class CtoeSimpleMenuImage : public CtoeSimpleMenuTerminalItem
{
private:
uint32 textureHash;
CIwTexture* texture;
CIwMaterial* material;
CIwSVec2 rectPos;
CIwSVec2 rectSize;
CIwColour rectColour;
uint32 styleSheetHash;
CtoeSimpleMenuStyleSheet* styleSheet;
public:
//Declare managed class
IW_MANAGED_DECLARE(CtoeSimpleMenuImage);
//Constructor
CtoeSimpleMenuImage();
//Constructor
CtoeSimpleMenuImage(uint32 hash);
//Desctructor
virtual ~CtoeSimpleMenuImage();
//Reads/writes a binary file using @a IwSerialise interface.
virtual void Serialise ();
virtual void Prepare(toeSimpleMenuItemContext* renderContext,int16 width);
//Render image on the screen surface
virtual void Render(toeSimpleMenuItemContext* renderContext);
virtual void RearrangeChildItems();
virtual uint32 GetElementNameHash();
#ifdef IW_BUILD_RESOURCES
//Parses from text file: parses attribute/value pair.
virtual bool ParseAttribute(CIwTextParserITX* pParser, const char* pAttrName);
#endif
protected:
void InitImage();
};
} | [
"[email protected]"
]
| [
[
[
1,
48
]
]
]
|
c5e34f3a3627f73856f65e87528f894d25283f77 | d8f64a24453c6f077426ea58aaa7313aafafc75c | /DKER/TestDLL/src/host/TargetDlg.cpp | 43f8e80d54e624f1a81b7180bd8b50e3967bbf55 | []
| no_license | dotted/wfto | 5b98591645f3ddd72cad33736da5def09484a339 | 6eebb66384e6eb519401bdd649ae986d94bcaf27 | refs/heads/master | 2021-01-20T06:25:20.468978 | 2010-11-04T21:01:51 | 2010-11-04T21:01:51 | 32,183,921 | 1 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 2,209 | cpp | // TargetDlg.cpp : インプリメンテーション ファイル
//
#include "stdafx.h"
#include "dxwndhost.h"
#include "TargetDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CTargetDlg ダイアログ
CTargetDlg::CTargetDlg(CWnd* pParent /*=NULL*/)
: CDialog(CTargetDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CTargetDlg)
m_DXVersion = -1;
m_EmulatePal = FALSE;
m_HookDI = FALSE;
m_ModifyMouse = FALSE;
m_OutTrace = FALSE;
m_UnNotify = FALSE;
m_FilePath = _T("");
m_SaveLoad = FALSE;
m_InitX = 0;
m_InitY = 0;
m_MaxX = 0;
m_MaxY = 0;
m_MinX = 0;
m_MinY = 0;
//}}AFX_DATA_INIT
}
void CTargetDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CTargetDlg)
DDX_Control(pDX, IDC_FILE, m_File);
DDX_Radio(pDX, IDC_AUTO, m_DXVersion);
DDX_Check(pDX, IDC_EMULATEPAL, m_EmulatePal);
DDX_Check(pDX, IDC_HOOKDI, m_HookDI);
DDX_Check(pDX, IDC_MODIFYMOUSE, m_ModifyMouse);
DDX_Check(pDX, IDC_OUTTRACE, m_OutTrace);
DDX_Check(pDX, IDC_UNNOTIFY, m_UnNotify);
DDX_Text(pDX, IDC_FILE, m_FilePath);
DDX_Check(pDX, IDC_SAVELOAD, m_SaveLoad);
DDX_Text(pDX, IDC_INITX, m_InitX);
DDX_Text(pDX, IDC_INITY, m_InitY);
DDX_Text(pDX, IDC_MAXX, m_MaxX);
DDX_Text(pDX, IDC_MAXY, m_MaxY);
DDX_Text(pDX, IDC_MINX, m_MinX);
DDX_Text(pDX, IDC_MINY, m_MinY);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CTargetDlg, CDialog)
//{{AFX_MSG_MAP(CTargetDlg)
ON_BN_CLICKED(IDC_OPEN, OnOpen)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CTargetDlg メッセージ ハンドラ
void CTargetDlg::OnOpen()
{
// TODO: この位置にコントロール通知ハンドラ用のコードを追加してください
char path[MAX_PATH];
m_File.GetWindowText(path, MAX_PATH);
CFileDialog dlg( TRUE, "*.*", path, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
"Program (*.exe)|*.exe|All Files (*.*)|*.*||", this);
if( dlg.DoModal() == IDOK) m_File.SetWindowText(dlg.GetPathName());
}
| [
"[email protected]"
]
| [
[
[
1,
80
]
]
]
|
330502eb2a9c2861fab98e2694d251cc245fd20e | 45c0d7927220c0607531d6a0d7ce49e6399c8785 | /GlobeFactory/src/ui/user_interface.hh | faa6884339ecc8e598bff45484e2c4f353731574 | []
| no_license | wavs/pfe-2011-scia | 74e0fc04e30764ffd34ee7cee3866a26d1beb7e2 | a4e1843239d9a65ecaa50bafe3c0c66b9c05d86a | refs/heads/master | 2021-01-25T07:08:36.552423 | 2011-01-17T20:23:43 | 2011-01-17T20:23:43 | 39,025,134 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 847 | hh | ////////////////////////////////////////////////////////////////////////////////
// Filename : user_interface.hh
// Authors : Creteur Clement
// Last edit : 05/02/10 - 17h26
// Comment :
////////////////////////////////////////////////////////////////////////////////
#ifndef UI_USER_INTERFACE_HH
#define UI_USER_INTERFACE_HH
#include "../useful/all.hh"
#include "ui_container.hh"
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
class UserInterface : public UIContainer
{
public:
UserInterface();
~UserInterface();
};
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
#endif
| [
"creteur.c@8e971d8e-9cf3-0c36-aa0f-a7c54ab41ffc"
]
| [
[
[
1,
26
]
]
]
|
0894202e2d06293a005094391d6f41ddf3f22169 | ed2a1c83681d8ed2d08f8a74707536791e5cd057 | /Extensions/Safe_Typer.DLL/HG_SDK Files/HG_SDK.cpp | 41186fc6d6ee3635366673fc8510846c9abdf9ba | [
"Apache-2.0"
]
| permissive | MartinMReed/XenDLL | e33d5c27187e58fd4401b2dbcaae3ebab8279bc2 | 51a05c3cec7b2142f704f2ea131202a72de843ec | refs/heads/master | 2021-01-10T19:10:40.492482 | 2007-10-31T16:38:00 | 2007-10-31T16:38:00 | 12,150,175 | 13 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 5,540 | cpp | #include "HG_SDK.h"
//-------------------------------------------------------
//
//-------------------------------------------------------
BOOL APIENTRY DllMain(HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
{
Loaded = false;
ConfigOn = false;
// do a version check to make sure users dont have older versions of HGooey
if (!HGVersionCheck(HGVersion))
return FALSE;
// load and create stuff here (ie load extensions, create textures/images/objects/etc)
// make sure the no one moved the extension
if (GetFileAttributes("HGooey Files/XenDLL/Extensions/Safe_Typer/HG_SDK.dll") == 0xFFFFFFFF) return FALSE;
const char* Data;
if (Data = ReadConfigItem("Chatmode", "HGooey Files/XenDLL/Common/Memory.xml"))
{
// check the chatmode memory address
try { Chatmode = (DWORD*)atoi(Data); }
catch (...) { return FALSE; }
}
else
{
return FALSE;
}
Loaded = true;
}
break;
case DLL_PROCESS_DETACH:
{
if (!Loaded) return TRUE;
Loaded = false;
// unload and destroy stuff here (ie unload extensions)
}
break;
}
return TRUE;
}
//-------------------------------------------------------
// the device was lost (ie ALT+TAB to minimize the game)
//-------------------------------------------------------
void LostDevice(void)
{
if (!Loaded) return;
// any textures created using CreateIDDTextureFromFile(float,float,char*,UINT)
// are automatically released by HGooey. this does not, however, cover
// textures created using CreateIDDTexture(float,float,IDirect3DTexture8*)
}
//-------------------------------------------------------
//
//-------------------------------------------------------
void ResetDevice(void)
{
if (!Loaded) return;
// any textures created using CreateIDDTextureFromFile(float,float,char*,UINT)
// are automatically restored by HGooey. this does not, however, cover
// textures created using CreateIDDTexture(float,float,IDirect3DTexture8*)
}
//-------------------------------------------------------
// called before any extensions draw on the screen
//-------------------------------------------------------
void PreRender(void)
{
if (!Loaded) return;
// DO NOT DRAW IN HERE, ALL DRAWING IS DISABLED.
// ONLY DRAW IN Render()
}
//-------------------------------------------------------
// do your drawing / call your main code in here
//-------------------------------------------------------
void Render(void)
{
if (!Loaded) return;
// draw text or execute/call main code
if (ConfigOn)
{
/**
if (Config window's 'close button' was pushed)
{
ConfigOn = false;
}
else
{
// draw your config window
}
/**/
}
}
//-------------------------------------------------------
// handle mouse input
//
// return true = send command to game
// return false = do not send the command to the game
//-------------------------------------------------------
bool HandleMouse()
{
if (!Loaded) return true;
MouseInfo xMouse = Mouse();
if (xMouse.cState == 0) // mouse move
{
}
else if (xMouse.cState == 1) // left button down
{
if (*Chatmode == 2)
*Chatmode = 0;
/**
// (optional) cancel click if other buttons are being pressed
if (xMouse.MButtonDown || xMouse.RButtonDown)
return false;
/**/
}
else if (xMouse.cState == 2) // left button up
{
}
else if (xMouse.cState == 3) // middle button down
{
/**
// (optional) cancel click if other buttons are being pressed
if (xMouse.LButtonDown || xMouse.RButtonDown)
return false;
/**/
}
else if (xMouse.cState == 4) // middle button up
{
}
else if (xMouse.cState == 5) // right button down
{
/**
// (optional) cancel click if other buttons are being pressed
if (xMouse.LButtonDown || xMouse.MButtonDown)
return false;
/**/
}
else if (xMouse.cState == 6) // right button up
{
}
else // mouse scroll
{
}
return true;
}
//-------------------------------------------------------
// handle keyboard input
//
// cKey = DIK_[Key]
// bDown = pressed down if true, released if false
//
// return true = send command to game
// return false = do not send the command to the game
//
// DirectInput Key-Identifier Table:
// http://calc.xentales.com/HGooey/DIK.html or
// http://www.xentales.com/calc/HGooey/DIK.html
//-------------------------------------------------------
bool HandleKeyboard()
{
if (!Loaded) return true;
KeyInfo xKey = Key();
if (xKey.bDown) // key is pressed down
{
}
else if (!xKey.bRepeat) // key has been released
{
}
return true;
}
//-------------------------------------------------------
// turn on the config window
//
// there is no reason to edit this, build your
// config window when the .dll is first loaded.
// however, there is nothing critical here, so
// you do what you want here.
//-------------------------------------------------------
void Config(void)
{
ConfigOn = true;
}
//-------------------------------------------------------
// version check called by XenDLL
//-------------------------------------------------------
UINT HGSDKVersionCheck(void)
{
// DO NOT EDIT THIS
return 61225;
}
| [
"[email protected]"
]
| [
[
[
1,
251
]
]
]
|
14e76b4dd0a04879717e846126c588196ef7f4a8 | 0f8559dad8e89d112362f9770a4551149d4e738f | /Wall_Destruction/Havok/Source/Common/Compat/Deprecated/Packfile/hkPackfileReader.h | 5f735552c64719f9e84a8ef5b4b4b0c4232b109d | []
| 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 | 5,774 | 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_PACKFILE_READER_H
#define HK_PACKFILE_READER_H
#include <Common/Serialize/Packfile/hkPackfileData.h>
class hkStreamReader;
class hkObjectUpdateTracker;
class hkClassNameRegistry;
class hkTypeInfoRegistry;
template <typename T, typename A> class hkStringMap;
template <typename K, typename V> class hkSerializeMultiMap;
/// Base interface to read in a packed file.
/// Reading is done two steps - first the file is read
/// and reconstructed in memory (loadEntireFile). Secondly
/// versioning, pointer fixups and finishing functions
/// are run (getContents).
class hkPackfileReader : public hkReferencedObject
{
public:
HK_DECLARE_CLASS_ALLOCATOR(HK_MEMORY_CLASS_SERIALIZE);
hkPackfileReader();
~hkPackfileReader();
/// Simple interface. Load the entire file, fixes up all pointers.
/// This method internally allocates memory for storing the packfile.
/// hkBinaryPackfileReader has finer grained loading operations, and
/// also a method which allows loading with no memory allocations.
/// hkXmlPackfile reader needs class descriptions to load the objects.
/// We look for class descriptions in two places : first the file itself
/// and secondly in the hkBuiltinTypeRegistry. See also
/// hkXmlPackfileReader::loadEntireFileWithRegistry.
virtual hkResult loadEntireFile( hkStreamReader* reader ) = 0;
/// Get the top level object in the file.
/// This function assumes that the packfile version matches the in-memory
/// version. You may use hkVersionUtil if this is not the case. See the
/// serialization section of the manual for more details.
/// Usually you will use getContents instead of this function.
/// If the packfile contents type do not match the expected class type
/// this method will return HK_NULL. You may pass HK_NULL as the expected
/// class to disable this check.
/// Some objects will require a finishing step. i.e. to initialize
/// members which have not been serialized or to initialize vtables.
/// If "finish" is not HK_NULL, apply these finishing steps.
virtual void* getContentsWithRegistry( const char* expectedClassName, const hkTypeInfoRegistry* finish ) = 0;
/// Get the top level object in the file.
/// Calls getContentsWithRegistry with the finish registry from hkBuiltinTypeRegistry.
virtual void* getContents( const char* expectedClassName );
/// Get the class name of contents, if available.
virtual const char* getContentsClassName() const = 0;
//
// Versioning access functions.
//
/// Get all objects in the packfile.
/// Used by the versioning code. Note that if a packfile has been
/// stripped of metadata, then this array may be empty.
virtual hkArray<hkVariant>& getLoadedObjects() const = 0;
/// Get top level object in the packfile.
/// Used by the versioning code.
virtual hkVariant getTopLevelObject() const = 0;
/// Get a tracker which knows about the internal structure of the packfile.
virtual hkObjectUpdateTracker& getUpdateTracker() const = 0;
/// Get a string representing the current version of objects within the file.
/// E.g. "Havok-4.1.0".
virtual const char* getContentsVersion() const;
/// Label the packfile as containing the given version.
virtual void setContentsVersion(const char* version );
virtual const hkClassNameRegistry* getClassNameRegistry() const = 0;
public:
/// Get a handle to memory allocations made during loading.
/// You can add a reference to this, and delete the pack file reader after loading.
/// Removing your reference will deallocate any loaded data.
/// IMPORTANT: Make sure that the pack file content is versioned before you call this function.
virtual hkPackfileData* getPackfileData() const = 0;
// compatibility
typedef hkPackfileData AllocatedData;
AllocatedData* getAllocatedData() const { return getPackfileData(); }
/// Return true if the sdk version matches the packfile version.
hkBool32 isVersionUpToDate() const;
void warnIfNotUpToDate() const;
public:
///
typedef const char* SectionTag;
typedef hkPointerMap<const hkClass*, hkInt32> UpdateFlagFromClassMap;
mutable UpdateFlagFromClassMap m_updateFlagFromClass;
// Current contents version.
char* m_contentsVersion;
///
static void HK_CALL updateMetaDataInplace( hkClass* classInOut, int fileVersion, const char* contentsVersion, UpdateFlagFromClassMap& updateFlagFromClass );
};
#endif // HK_PACKFILE_READER_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.
*
*/
| [
"[email protected]"
]
| [
[
[
1,
136
]
]
]
|
a9502df4ed7f593f3068a286e2c2855766389c1d | 0e844fb903a85e4193da8d4cd9d157c250996529 | /source_SpaceWireRMAPLibrary/SpaceWireCLI.cc | 70a3a236a4e12449e94faa6ac1b006e6d867b45f | []
| no_license | lzgjxh/SpaceWireRMAPLibrary | 0e3c87a72e911a7f957a22389a08d0b341fb2559 | 5b4340afb608b1be9c14f684587536f5a260d6f9 | refs/heads/master | 2021-01-18T11:41:09.729691 | 2011-08-04T03:25:28 | 2011-08-04T03:25:28 | 2,561,669 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,952 | cc | //spCLI.cpp
// 2007-02-03 Hirokazu Odaka
// 2007-06-11 Hirokazu Odaka addToken
// 2007-07-11 Hirokazu Odaka
/* Renamed from spCLI.cpp */
//#include "spCLI.h"
#include "SpaceWireCLI.hh"
#include <cstdlib>
#include <string.h>
SpaceWireCLI::SpaceWireCLI()
{
}
bool SpaceWireCLI::ask(std::istream& ist, std::string& str, std::ostream& ost, const char* question)
{
ost << question;
ost << "[ " << str << " ] ";
if (qtoken.empty()) {
getline(ist, line);
if (line.empty()) return false;
unsigned int i = 0;
unsigned int token_begin, token_end;
while (i < line.size()) {
std::string str_token;
while (line[i]==' ' || line[i]=='\t') {
i++;
if (i>=line.size()) return false;
}
token_begin = i;
while (line[i]!=' ' && line[i]!='\t' && i<line.size()) {
i++;
}
token_end = i;
str_token = line.substr(token_begin, (token_end-token_begin));
qtoken.push(str_token);
}
}
str = qtoken.front();
qtoken.pop();
return true;
}
bool SpaceWireCLI::ask_cstr(std::istream& ist, char* cstr, unsigned int size, std::ostream& ost, const char* question)
{
std::string str = cstr;
if ( ask(ist, str, ost, question) ) {
if (str.length() < size) {
strcpy(cstr, str.c_str());
}
else {
strncpy(cstr, str.c_str(), size-1);
cstr[size-1] = '\0';
}
return true;
}
return false;
}
bool SpaceWireCLI::ask_int(std::istream& ist, int& num, std::ostream& ost, const char* question)
{
char cstr[80];
sprintf(cstr, "%d", num);
std::string str = cstr;
if ( ask(ist, str, ost, question) ) {
num = atoi(str.c_str());
return true;
}
return false;
}
bool SpaceWireCLI::ask_hex(std::istream& ist, unsigned int& num, std::ostream& ost, const char* question)
{
char cstr[80];
sprintf(cstr, "%x", num);
std::string str = cstr;
if ( ask(ist, str, ost, question) ) {
unsigned int nDigit = str.length();
unsigned int tmp_num = 0;
unsigned int digit = 1;
try {
for (unsigned int i = 1; i <= nDigit; i++) {
tmp_num += digit * charToHex(str[nDigit-i]);
digit *= 16;
}
}
catch (char* errstr) {
std::cout << errstr << std::endl;
return false;
}
num = tmp_num;
return true;
}
return false;
}
bool SpaceWireCLI::ask_double(std::istream& ist, double& num, std::ostream& ost, const char* question)
{
char cstr[80];
sprintf(cstr, "%f", num);
std::string str = cstr;
if ( ask(ist, str, ost, question) ) {
num = atof(str.c_str());
return true;
}
return false;
}
void SpaceWireCLI::ask2(std::istream& ist, std::string& str, std::ostream& ost, const char* question)
{
start:
ost << question;
while (qtoken.empty()) {
getline(ist, line);
if (line.empty()) goto start;
unsigned int i = 0;
unsigned int token_begin, token_end;
while (i < line.size()) {
std::string str_token;
while (line[i]==' ' || line[i]=='\t') {
i++;
if (i>=line.size()) goto start;
}
token_begin = i;
while (line[i]!=' ' && line[i]!='\t' && i<line.size()) {
i++;
}
token_end = i;
str_token = line.substr(token_begin, (token_end-token_begin));
qtoken.push(str_token);
}
}
str = qtoken.front();
qtoken.pop();
}
void SpaceWireCLI::ask2_cstr(std::istream& ist, char* cstr, unsigned int size, std::ostream& ost, const char* question)
{
std::string str = cstr;
ask2(ist, str, ost, question);
if (str.length() < size) {
strcpy(cstr, str.c_str());
}
else {
strncpy(cstr, str.c_str(), size-1);
cstr[size-1] = '\0';
}
}
void SpaceWireCLI::ask2_int(std::istream& ist, int& num, std::ostream& ost, const char* question)
{
std::string str;
ask2(ist, str, ost, question);
num = atoi(str.c_str());
}
void SpaceWireCLI::ask2_hex(std::istream& ist, unsigned int& num, std::ostream& ost, const char* question)
{
std::string str;
unsigned int tmp_num;
ask2(ist, str, ost, question);
unsigned int nDigit = str.length();
tmp_num = 0;
unsigned int digit = 1;
try {
for (unsigned int i = 1; i <= nDigit; i++) {
tmp_num += digit * charToHex(str[nDigit-i]);
digit *= 16;
}
}
catch (char* errstr) {
std::cout << errstr << std::endl;
}
num = tmp_num;
}
void SpaceWireCLI::ask2_double(std::istream& ist, double& num, std::ostream& ost, const char* question)
{
std::string str;
ask2(ist, str, ost, question);
num = atof(str.c_str());
}
void SpaceWireCLI::addToken(const std::string& str)
{
qtoken.push(str);
}
void SpaceWireCLI::addToken(const char* cstr)
{
qtoken.push((std::string)cstr);
}
void SpaceWireCLI::clear()
{
while(!qtoken.empty()) {
qtoken.pop();
}
}
void SpaceWireCLI::load(std::ifstream& fin)
{
std::string str;
while (!fin.eof()) {
fin >> str;
addToken(str);
}
}
unsigned int SpaceWireCLI::charToHex(char c) throw (char*)
{
unsigned int n = 0;
switch (c) {
case '0':
n = 0;
break;
case '1':
n = 1;
break;
case '2':
n = 2;
break;
case '3':
n = 3;
break;
case '4':
n = 4;
break;
case '5':
n = 5;
break;
case '6':
n = 6;
break;
case '7':
n = 7;
break;
case '8':
n = 8;
break;
case '9':
n = 9;
break;
case 'a':
case 'A':
n = 10;
break;
case 'b':
case 'B':
n = 11;
break;
case 'c':
case 'C':
n = 12;
break;
case 'd':
case 'D':
n = 13;
break;
case 'e':
case 'E':
n = 14;
break;
case 'f':
case 'F':
n = 15;
break;
default:
throw "Not 0-f";
}
return n;
}
| [
"[email protected]"
]
| [
[
[
1,
303
]
]
]
|
99115d990ebfe67675c031c486e98d38cbb0f621 | f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0 | /GameSDK/GameCore/Include/XAction.h | 8bc319c0311d66a616e3be4cb29f82bbf1aff467 | []
| 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 | GB18030 | C++ | false | false | 6,210 | h | #pragma once
#ifdef CORE_EXPORTS
#define CORE_API __declspec(dllexport)
#else
#define CORE_API __declspec(dllimport)
#endif //CORE_EXPORTS
#pragma warning( disable:4251 )
#include "XObject.h"
#include <list>
/*********************************************************************/
/*
Create: 2006/01/041:2006 17:46
FileName: XEffectBase.h
Author: Albert xu
*/
/*********************************************************************/
/************************************************************************/
/* 实现了属性系统的作用系统,该类完成了对属性系统作用的底层代码。通过一组宏定义
/* 指定作用编号和属性编号的对应关系,以及作用的过程处理函数。底层提供了一个简单的
/* 过程处理函数,而其他过程处理函数可以由用户自由定义。同时,作用系统的影响链
/* 可以使两个作用具有相关性,即在某作用完成后触发另一作用继续对对象施加影响,例如
/* 增加HP的同时也增加HP最大值,即可以用作用链来触发。
/* 作用和属性的对应关系是多对一的,不同的作用效果可能都影响同一个属性值
/************************************************************************/
namespace XGC
{
// 定义指向函数的指针
class CORE_API CXAction;
typedef int (*DoActionFunc_c)( const CXAction*, CXObject*, CXVariant[3], int, bool );
typedef struct ACTION_ENTRY
{
unsigned int nID; // id 效果编号
unsigned int nDestType; // type 目标类型
CXVariant ConstParam[3]; // param 静态参数
DoActionFunc_c pDoAction; // func 动作执行函数
} action_entry, *action_entry_ptr;
// 消息映射表结构
typedef struct ACTION_MAP
{
const ACTION_MAP *pBaseMap;
action_entry_ptr lpMapEntry;
action_entry_ptr lpMapEntryLast;
} action_map, *action_map_ptr;
CORE_API const action_entry_ptr FindEffectEntry( const action_map_ptr lpEntryMap, int nActionID );
#define ACTION_PARAM_MAX 3
#define INVALID_ACTION_ID -1
class CORE_API CXAction : public CXObject
{
//DECLARE_EFFECT_MAP()
private:
_uint32 m_nActionID; // 效果ID
//_byte m_nLv; // 效果等级
//_byte m_nOwnerType; // 所有者类型 -对象, -状态,
const action_entry_ptr m_entry_ptr; // 模板入口
protected:
int m_bEffected; // 是否已经转移了作用
CXVariant m_Param[ACTION_PARAM_MAX]; // 效果参量
CXVariant m_ParamEx[ACTION_PARAM_MAX]; // 效果参量
CXAction();
public:
CXAction( int nActionID, const action_entry_ptr emap );
CXAction( const CXAction& rsh );
~CXAction(void);
DECLARE_DYNAMICTYPE( CXObject, TypeGameAction );
//////////////////////////////////////////////////////////////////////////
// 设置参数
// nIdx : 索引
// fValue : 值
// return : 是否设置成功
//////////////////////////////////////////////////////////////////////////
bool SetParam( int nIdx, CXVariant fValue );
//////////////////////////////////////////////////////////////////////////
// 设置参数
// nIdx : 索引
// fValue : 值
// return : 是否设置成功
//////////////////////////////////////////////////////////////////////////
bool SetOwnerParam( int nIdx, CXVariant fValue );
//////////////////////////////////////////////////////////////////////////
// 获取参数
// nIdx : 索引
// fValue : 值
// return : 是否设置成功
//////////////////////////////////////////////////////////////////////////
CXVariant GetParam( int nIdx )const{ ASSERT( nIdx >=0 && nIdx < ACTION_PARAM_MAX ); return m_Param[nIdx]; }
//////////////////////////////////////////////////////////////////////////
// 获取参数
// nIdx : 索引
// fValue : 值
// return : 是否设置成功
//////////////////////////////////////////////////////////////////////////
CXVariant GetOwnerParam( int nIdx )const{ ASSERT( nIdx >=0 && nIdx < ACTION_PARAM_MAX ); return m_ParamEx[nIdx]; }
//////////////////////////////////////////////////////////////////////////
// 设置参数
// fValue : 值数组指针
// nFirstIdx: 起始索引
// nEndIdx : 结束索引
// return : 是否设置成功
// remark : nFirstIdx 可以大于 nEndIdx 但是fValue的值将被倒序输入。
//////////////////////////////////////////////////////////////////////////
bool SetParam( const CXVariant *fValue, int nFirstIdx, int nEndIdx );
//////////////////////////////////////////////////////////////////////////
// 设置参数
// fValue : 值数组指针
// nFirstIdx: 起始索引
// nEndIdx : 结束索引
// return : 是否设置成功
// remark : nFirstIdx 可以大于 nEndIdx 但是fValue的值将被倒序输入。
//////////////////////////////////////////////////////////////////////////
bool SetOwnerParam( const CXVariant *fValue, int nFirstIdx, int nEndIdx );
//---------------------------------------------------//
// [9/19/2009 Albert]
// Description: 重置状态转移标志
//---------------------------------------------------//
void ResetFlag(){ m_bEffected = 0; }
// 执行作用
int DoAction( CXObject* pObj, bool bRemove = false );
protected:
const action_entry_ptr getActionEntry()const;
};
class CORE_API CXStatus : public CXAction
{
private:
_uint32 m_hTimerHandler;
public:
explicit CXStatus( int nActionID, const action_entry_ptr emap );
explicit CXStatus( const CXStatus& rsh );
~CXStatus();
DECLARE_DYNAMICTYPE( CXAction, TypeStatus );
//---------------------------------------------------//
// [9/13/2009 Albert]
// Description: 安装定时器
//---------------------------------------------------//
void InstallTimer( _uint32 nCount, float fInterval, float fDelay = 0 );
protected:
//---------------------------------------------------//
// [9/13/2009 Albert]
// Description: 定时器事件
//---------------------------------------------------//
bool OnTimer( unsigned int handle, unsigned short &repeat, unsigned int &timer );
};
} | [
"albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c"
]
| [
[
[
1,
165
]
]
]
|
37f2d39654f607b8f05ade1993ba4ba37feffe5b | 4275e8a25c389833c304317bdee5355ed85c7500 | /KylTek/CApplication.cpp | fd56909164f79e986e09f5e8854a532d4fc3282d | []
| no_license | kumorikarasu/KylTek | 482692298ef8ff501fd0846b5f41e9e411afe686 | be6a09d20159d0a320abc4d947d4329f82d379b9 | refs/heads/master | 2021-01-10T07:57:40.134888 | 2010-07-26T12:10:09 | 2010-07-26T12:10:09 | 55,943,006 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,139 | cpp | #include "Main.h"
#include "CDeviceHandler.h"
#include "CGraphicsHandler.h"
#include "GUI.h"
#include "CApplication.h"
#include "Debug.h"
#include "Functions.h"
#include "CGlobal.h"
#include "Sprite.h"
CApplication::CApplication(){
m_pDeviceHandler = NULL;
m_pGraphicsHandler = NULL;
m_pGUIWindow = NULL;
m_pCurrentLevel = NULL;
}
CApplication::~CApplication(){
SAFE_DELETE(m_pDeviceHandler);
SAFE_DELETE(m_pGraphicsHandler);
SAFE_DELETE(m_pGUIWindow);
SAFE_DELETE(m_pCurrentLevel);
}
void CApplication::Initialize(HWND hWnd, HINSTANCE hInstance){
m_pGraphicsHandler=new CGraphicsHandler(CGraphicsHandler::DirectX);
m_pGraphicsHandler->InitializeAPI(hWnd, hInstance);
m_pGraphicsHandler->Initialize2D();
m_pGraphicsHandler->SetupSprites();
m_pDeviceHandler = new CDeviceHandler(hInstance);
m_pDeviceHandler->InitializeKeyboard(hWnd);
m_pDeviceHandler->InitializeMouse(hWnd);
m_pCurrentLevel = new CLevel();
/*-----------------------------------------------------------------------------------------------------------------
- Main Menu
-----------------------------------------------------------------------------------------------------------------*/
GUI_COLORS Colors;
Colors.BG=ColorARGB(128,0,0,0);
GUI_PARAMS Params;
Params.pos=Vector2(0, 0);
Params.width=WINDOW_WIDTH;
Params.height=WINDOW_HEIGHT;
Params.enabled=true;
Params.visible=true;
Params.GUIEvent=OnGUIEvent;
m_pGUIWindow=new CGUIWindow(&Params, &Colors, NULL, false, "");
m_pGUIWindow->SetEventFunction( NULL );
m_pGUIWindow->Add(Debug->GetConsole());
Debug->GetConsole()->Close();
ZeroMemory(&Colors, sizeof(GUI_COLORS));
Colors.Text=ColorARGB(255,255,255,255);
ZeroMemory(&Params, sizeof(GUI_PARAMS));
Params.pos=Vector2(100, 500);
Params.width=96;
Params.height=24;
Params.enabled=true;
Params.visible=true;
Params.GUIEvent=OnGUIEvent;
m_pGUIWindow->Add(new CGUIButton(&Params, &Colors, NULL, EVENT_NEWGAME, m_pCurrentLevel, "New Game", false));
Params.pos=Vector2(100, 532);
m_pGUIWindow->Add(new CGUIButton(&Params, &Colors, NULL, EVENT_NETWORK, m_pCurrentLevel, "Online", false));
Params.pos=Vector2(100, 564);
//m_pGUIWindow->Add(new CGUIButton(&Params, &Colors, NULL, EVENT_OPENWINDOW, NULL, "Options"));
//Params.pos=Vector2(100, 596);
m_pGUIWindow->Add(new CGUIButton(&Params, &Colors, NULL, EVENT_EXITGAME, this, "Exit Game", false));
/*-----------------------------------------------------------------------------------------------------------------
- End of Menu
-----------------------------------------------------------------------------------------------------------------*/
/*-----------------------------------------------------------------------------------------------------------------
- Options Menu
-----------------------------------------------------------------------------------------------------------------*/
/*
ZeroMemory(&Params, sizeof(GUI_PARAMS));
Params.pos=Vector2(400, 200);
Params.width=600;
Params.height=400;
Params.enabled=true;
Params.visible=true;
Params.GUIEvent=OnGUIEvent;
ZeroMemory(&Colors, sizeof(GUI_COLORS));
Colors.BG=ColorARGB(255, 80, 80, 80);
Colors.Border=ColorARGB(255, 0, 0, 0);
Colors.Text=ColorARGB(255, 0,0,0);
CGUITabGroup* test = new CGUITabGroup(&Params, &Colors, NULL);
m_pGUIWindow->Add(test);
test->AddTab("Tab 1", Vector2(64, 24), &Colors, NULL, &Colors, NULL);
test->AddTab("Tab 2", Vector2(64, 24), &Colors, NULL, &Colors, NULL);
test->AddTab("Tab 3", Vector2(64, 24), &Colors, NULL, &Colors, NULL);
test->AddTab("Tab 4", Vector2(64, 24), &Colors, NULL, &Colors, NULL);
ZeroMemory(&Colors, sizeof(GUI_COLORS));
Colors.Text=ColorARGB(255,255,255,255);
ZeroMemory(&Params, sizeof(GUI_PARAMS));
Params.pos=Vector2(0, 0);
Params.width=96;
Params.height=24;
Params.enabled=true;
Params.visible=true;
Params.GUIEvent=OnGUIEvent;
test->AddToTabWindow(0, new CGUIButton(&Params, &Colors, NULL, EVENT_EXITGAME, this, "Exit Game", false));
test->AddToTabWindow(2, new CGUILabel(&Params, &Colors, NULL, "Label Test"));
Params.border=2;
Colors.BG=ColorARGB(255, 100,100,100);
Colors.Border=ColorARGB(255,0,0,0);
test->AddToTabWindow(1, new CGUICheckBox(&Params, &Colors, NULL, EVENT_TOGGLEFULLSCREEN, NULL, true));
Debug->ToConsole("Test Console Output");
Debug->ToConsole("Commands");
Debug->ToConsole("quadtree 0 - 1 : Show Quadtree");
Debug->ToConsole("hitboxes 0 - 1 : Show Hitboxes");
Debug->ToConsole("AddEntity 201 : Add Another AI to the level");
Debug->ToConsole("fill # : using for testing scroll bar, gunne be removed");
Params.pos=Vector2(0, 0);
Params.width=24;
Params.height=24;
Params.enabled=true;
Params.visible=true;
Params.GUIEvent=OnGUIEvent;
Colors.BG=ColorARGB(255, 255, 0, 0);
Colors.Border=ColorARGB(255, 0,0,0);
Colors.Text=ColorARGB(255, 0,0,0);
CGUIRadioGroup* rg = new CGUIRadioGroup();
rg->AddButton(&Params, &Colors, NULL, 0, NULL, false);
Params.pos=Vector2(24, 0);
rg->AddButton(&Params, &Colors, NULL, 0, NULL, false);
Params.pos=Vector2(48, 0);
rg->AddButton(&Params, &Colors, NULL, 0, NULL, false);
test->AddToTabWindow(3, rg->GetButton(0));
test->AddToTabWindow(3, rg->GetButton(1));
test->AddToTabWindow(3, rg->GetButton(2));
*/
/*-----------------------------------------------------------------------------------------------------------------
- End of Options Menu
-----------------------------------------------------------------------------------------------------------------*/
}
void CApplication::Step(){
m_pDeviceHandler->UpdateKeyboardState();
m_pDeviceHandler->UpdateMouseState();
Global->MousePos=m_pDeviceHandler->MousePos();
if(m_pDeviceHandler->KeyDown(DIK_F10))
Global->Exit=true;
if(m_pDeviceHandler->KeyPress(DIK_GRAVE))
if(Debug->GetConsole()->GetVisible()){
Debug->GetConsole()->Close();
if(m_pGUIWindow->GetVisible()){
m_pGUIWindow->Close();
}
}else{
Debug->GetConsole()->Open();
if(!m_pGUIWindow->GetVisible()){
m_pGUIWindow->Open();
m_pGUIWindow->OnFocusIn();
}
}
if(m_pDeviceHandler->KeyPress(DIK_ESCAPE)){
if(m_pGUIWindow->GetVisible()){
m_pGUIWindow->Close();
}else{
m_pGUIWindow->Open();
m_pGUIWindow->OnFocusIn();
}
}
m_pGUIWindow->Step();
m_pCurrentLevel->Step(m_pDeviceHandler);
}
void CApplication::Render(){
m_pGraphicsHandler->BeginRender();
m_pCurrentLevel->Draw(m_pGraphicsHandler);
Debug->Draw(m_pGraphicsHandler);
/*if(m_pGUIWindow->GetVisible())
if (Global->pPlayer!=NULL)
m_pGraphicsHandler->DrawRectTL(Vector2(0, 0), 1024, 768, ColorARGB(100, 0, 0, 0));
else
m_pGraphicsHandler->DrawSprite( m_pGraphicsHandler->SprList->Menu->menuBgk, 0, Vector2(512,384));
*/
m_pGUIWindow->Draw(m_pGraphicsHandler);
m_pGraphicsHandler->EndRender();
}
bool CApplication::WndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ){
if(m_pGUIWindow)
return m_pGUIWindow->WndProc(hWnd, uMsg, wParam, lParam);
return false;
} | [
"Sean Stacey@localhost"
]
| [
[
[
1,
210
]
]
]
|
193180ee2853f88d896cbe73da1f5bdf22285584 | 01b123189b5d09a0088721da1c5f11892d9d3ad0 | /mapview.cpp | a985727fb9e26c6a527bff0d374b959b91231663 | []
| no_license | love-rollercoaster/comp3004 | 0cc624c4200641237c2e10412c885363f72e582b | 2aeb48860fd4a35ff25923455c8d92efe41e8032 | refs/heads/master | 2021-01-25T12:19:48.641948 | 2011-03-02T08:01:32 | 2011-03-08T00:51:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,380 | cpp | #include <QtGui>
#include <math.h>
#include <QGraphicsPixmapItem>
#include <QtSvg/QGraphicsSvgItem>
#include "mapview.h"
#include "facilitymapnode.h"
#include "facility.h"
MapView::MapView(QWidget *parent) : QGraphicsView(parent)
{
image = new QGraphicsSvgItem(":/img/map.svg");
QGraphicsScene *scene = new QGraphicsScene(this);
scene->addItem(image);
scene->setItemIndexMethod(QGraphicsScene::NoIndex);
setScene(scene);
setRenderHint(QPainter::Antialiasing);
setRenderHint(QPainter::SmoothPixmapTransform);
setCacheMode(CacheBackground);
setViewportUpdateMode(BoundingRectViewportUpdate);
setResizeAnchor(NoAnchor);
}
void MapView::mousePressEvent(QMouseEvent *event)
{
FacilityMapNode *node;
if (event->button() == Qt::LeftButton)
node = new FacilityMapNode(this, FacilityMapNode::LOW, Facility::HOSPITAL);
else
node = new FacilityMapNode(this, FacilityMapNode::LOW, Facility::NURSING_HOME);
node->setPos(event->pos().x() - this->x(), event->pos().y() - this->y());
this->scene()->addItem(node);
qDebug("%d || %d", event->pos().x(), event->pos().y());
}
void MapView::addFacilityMapNode(FacilityMapNode *node)
{
this->scene()->addItem(node);
}
void MapView::resizeEvent(QResizeEvent *event)
{
fitInView(this->sceneRect());
}
| [
"[email protected]"
]
| [
[
[
1,
52
]
]
]
|
06e713bf1f4e4f9e21742625d31c19bcaaa94ad9 | 02c2e62bcb9a54738bfbd95693978b8709e88fdb | /opencv/cxjacobieigens.cpp | c05eb725b8aaed3b278c2277c6ba832ca54a0162 | []
| no_license | ThadeuFerreira/sift-coprojeto | 7ab823926e135f0ac388ae267c40e7069e39553a | bba43ef6fa37561621eb5f2126e5aa7d1c3f7024 | refs/heads/master | 2021-01-10T15:15:21.698124 | 2009-05-08T17:38:51 | 2009-05-08T17:38:51 | 45,042,655 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,923 | cpp | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation 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.
//
//M*/
#include "_cxcore.h"
/*F///////////////////////////////////////////////////////////////////////////////////////
// Names: icvJacobiEigens_32f, icvJacobiEigens_64d
// Purpose: Eigenvalues & eigenvectors calculation of a symmetric matrix:
// A Vi = Ei Vi
// Context:
// Parameters: A(n, n) - source symmetric matrix (n - rows & columns number),
// V(n, n) - matrix of its eigenvectors
// (i-th row is an eigenvector Vi),
// E(n) - vector of its eigenvalues
// (i-th element is an eigenvalue Ei),
// eps - accuracy of diagonalization.
//
// Returns:
// CV_NO_ERROR or error code
// Notes:
// 1. The functions destroy source matrix A, so if you need it further, you
// have to copy it before the processing.
// 2. Eigenvalies and eigenvectors are sorted in Ei absolute value descending.
// 3. Calculation time depends on eps value. If the time isn't very important,
// we recommend to set eps = 0.
//F*/
/*=========================== Single precision function ================================*/
static CvStatus CV_STDCALL
icvJacobiEigens_32f(float *A, float *V, float *E, int n, float eps)
{
int i, j, k, ind, iters = 0;
float *AA = A, *VV = V;
double Amax, anorm = 0, ax;
if( A == NULL || V == NULL || E == NULL )
return CV_NULLPTR_ERR;
if( n <= 0 )
return CV_BADSIZE_ERR;
if( eps < 1.0e-7f )
eps = 1.0e-7f;
/*-------- Prepare --------*/
for( i = 0; i < n; i++, VV += n, AA += n )
{
for( j = 0; j < i; j++ )
{
double Am = AA[j];
anorm += Am * Am;
}
for( j = 0; j < n; j++ )
VV[j] = 0.f;
VV[i] = 1.f;
}
anorm = sqrt( anorm + anorm );
ax = anorm * eps / n;
Amax = anorm;
while( Amax > ax && iters++ < 100 )
{
Amax /= n;
do /* while (ind) */
{
int p, q;
float *V1 = V, *A1 = A;
ind = 0;
for( p = 0; p < n - 1; p++, A1 += n, V1 += n )
{
float *A2 = A + n * (p + 1), *V2 = V + n * (p + 1);
for( q = p + 1; q < n; q++, A2 += n, V2 += n )
{
double x, y, c, s, c2, s2, a;
float *A3, Apq = A1[q], App, Aqq, Aip, Aiq, Vpi, Vqi;
if( fabs( Apq ) < Amax )
continue;
ind = 1;
/*---- Calculation of rotation angle's sine & cosine ----*/
App = A1[p];
Aqq = A2[q];
y = 5.0e-1 * (App - Aqq);
x = -Apq / sqrt( (double)Apq * Apq + (double)y * y );
if( y < 0.0 )
x = -x;
s = x / sqrt( 2.0 * (1.0 + sqrt( 1.0 - (double)x * x )));
s2 = s * s;
c = sqrt( 1.0 - s2 );
c2 = c * c;
a = 2.0 * Apq * c * s;
/*---- Apq annulation ----*/
A3 = A;
for( i = 0; i < p; i++, A3 += n )
{
Aip = A3[p];
Aiq = A3[q];
Vpi = V1[i];
Vqi = V2[i];
A3[p] = (float) (Aip * c - Aiq * s);
A3[q] = (float) (Aiq * c + Aip * s);
V1[i] = (float) (Vpi * c - Vqi * s);
V2[i] = (float) (Vqi * c + Vpi * s);
}
for( ; i < q; i++, A3 += n )
{
Aip = A1[i];
Aiq = A3[q];
Vpi = V1[i];
Vqi = V2[i];
A1[i] = (float) (Aip * c - Aiq * s);
A3[q] = (float) (Aiq * c + Aip * s);
V1[i] = (float) (Vpi * c - Vqi * s);
V2[i] = (float) (Vqi * c + Vpi * s);
}
for( ; i < n; i++ )
{
Aip = A1[i];
Aiq = A2[i];
Vpi = V1[i];
Vqi = V2[i];
A1[i] = (float) (Aip * c - Aiq * s);
A2[i] = (float) (Aiq * c + Aip * s);
V1[i] = (float) (Vpi * c - Vqi * s);
V2[i] = (float) (Vqi * c + Vpi * s);
}
A1[p] = (float) (App * c2 + Aqq * s2 - a);
A2[q] = (float) (App * s2 + Aqq * c2 + a);
A1[q] = A2[p] = 0.0f;
} /*q */
} /*p */
}
while( ind );
Amax /= n;
} /* while ( Amax > ax ) */
for( i = 0, k = 0; i < n; i++, k += n + 1 )
E[i] = A[k];
/*printf(" M = %d\n", M); */
/* -------- ordering -------- */
for( i = 0; i < n; i++ )
{
int m = i;
float Em = (float) fabs( E[i] );
for( j = i + 1; j < n; j++ )
{
float Ej = (float) fabs( E[j] );
m = (Em < Ej) ? j : m;
Em = (Em < Ej) ? Ej : Em;
}
if( m != i )
{
int l;
float b = E[i];
E[i] = E[m];
E[m] = b;
for( j = 0, k = i * n, l = m * n; j < n; j++, k++, l++ )
{
b = V[k];
V[k] = V[l];
V[l] = b;
}
}
}
return CV_NO_ERR;
}
/*=========================== Double precision function ================================*/
static CvStatus CV_STDCALL
icvJacobiEigens_64d(double *A, double *V, double *E, int n, double eps)
{
int i, j, k, p, q, ind, iters = 0;
double *A1 = A, *V1 = V, *A2 = A, *V2 = V;
double Amax = 0.0, anorm = 0.0, ax;
if( A == NULL || V == NULL || E == NULL )
return CV_NULLPTR_ERR;
if( n <= 0 )
return CV_BADSIZE_ERR;
if( eps < 1.0e-15 )
eps = 1.0e-15;
/*-------- Prepare --------*/
for( i = 0; i < n; i++, V1 += n, A1 += n )
{
for( j = 0; j < i; j++ )
{
double Am = A1[j];
anorm += Am * Am;
}
for( j = 0; j < n; j++ )
V1[j] = 0.0;
V1[i] = 1.0;
}
anorm = sqrt( anorm + anorm );
ax = anorm * eps / n;
Amax = anorm;
while( Amax > ax && iters++ < 100 )
{
Amax /= n;
do /* while (ind) */
{
ind = 0;
A1 = A;
V1 = V;
for( p = 0; p < n - 1; p++, A1 += n, V1 += n )
{
A2 = A + n * (p + 1);
V2 = V + n * (p + 1);
for( q = p + 1; q < n; q++, A2 += n, V2 += n )
{
double x, y, c, s, c2, s2, a;
double *A3, Apq, App, Aqq, App2, Aqq2, Aip, Aiq, Vpi, Vqi;
if( fabs( A1[q] ) < Amax )
continue;
Apq = A1[q];
ind = 1;
/*---- Calculation of rotation angle's sine & cosine ----*/
App = A1[p];
Aqq = A2[q];
y = 5.0e-1 * (App - Aqq);
x = -Apq / sqrt( Apq * Apq + (double)y * y );
if( y < 0.0 )
x = -x;
s = x / sqrt( 2.0 * (1.0 + sqrt( 1.0 - (double)x * x )));
s2 = s * s;
c = sqrt( 1.0 - s2 );
c2 = c * c;
a = 2.0 * Apq * c * s;
/*---- Apq annulation ----*/
A3 = A;
for( i = 0; i < p; i++, A3 += n )
{
Aip = A3[p];
Aiq = A3[q];
Vpi = V1[i];
Vqi = V2[i];
A3[p] = Aip * c - Aiq * s;
A3[q] = Aiq * c + Aip * s;
V1[i] = Vpi * c - Vqi * s;
V2[i] = Vqi * c + Vpi * s;
}
for( ; i < q; i++, A3 += n )
{
Aip = A1[i];
Aiq = A3[q];
Vpi = V1[i];
Vqi = V2[i];
A1[i] = Aip * c - Aiq * s;
A3[q] = Aiq * c + Aip * s;
V1[i] = Vpi * c - Vqi * s;
V2[i] = Vqi * c + Vpi * s;
}
for( ; i < n; i++ )
{
Aip = A1[i];
Aiq = A2[i];
Vpi = V1[i];
Vqi = V2[i];
A1[i] = Aip * c - Aiq * s;
A2[i] = Aiq * c + Aip * s;
V1[i] = Vpi * c - Vqi * s;
V2[i] = Vqi * c + Vpi * s;
}
App2 = App * c2 + Aqq * s2 - a;
Aqq2 = App * s2 + Aqq * c2 + a;
A1[p] = App2;
A2[q] = Aqq2;
A1[q] = A2[p] = 0.0;
} /*q */
} /*p */
}
while( ind );
} /* while ( Amax > ax ) */
for( i = 0, k = 0; i < n; i++, k += n + 1 )
E[i] = A[k];
/* -------- ordering -------- */
for( i = 0; i < n; i++ )
{
int m = i;
double Em = fabs( E[i] );
for( j = i + 1; j < n; j++ )
{
double Ej = fabs( E[j] );
m = (Em < Ej) ? j : m;
Em = (Em < Ej) ? Ej : Em;
}
if( m != i )
{
int l;
double b = E[i];
E[i] = E[m];
E[m] = b;
for( j = 0, k = i * n, l = m * n; j < n; j++, k++, l++ )
{
b = V[k];
V[k] = V[l];
V[l] = b;
}
}
}
return CV_NO_ERR;
}
CV_IMPL void
cvEigenVV( CvArr* srcarr, CvArr* evectsarr, CvArr* evalsarr, double eps )
{
CV_FUNCNAME( "cvEigenVV" );
__BEGIN__;
CvMat sstub, *src = (CvMat*)srcarr;
CvMat estub1, *evects = (CvMat*)evectsarr;
CvMat estub2, *evals = (CvMat*)evalsarr;
if( !CV_IS_MAT( src ))
CV_CALL( src = cvGetMat( src, &sstub ));
if( !CV_IS_MAT( evects ))
CV_CALL( evects = cvGetMat( evects, &estub1 ));
if( !CV_IS_MAT( evals ))
CV_CALL( evals = cvGetMat( evals, &estub2 ));
if( src->cols != src->rows )
CV_ERROR( CV_StsUnmatchedSizes, "source is not quadratic matrix" );
if( !CV_ARE_SIZES_EQ( src, evects) )
CV_ERROR( CV_StsUnmatchedSizes, "eigenvectors matrix has inappropriate size" );
if( (evals->rows != src->rows || evals->cols != 1) &&
(evals->cols != src->rows || evals->rows != 1))
CV_ERROR( CV_StsBadSize, "eigenvalues vector has inappropriate size" );
if( !CV_ARE_TYPES_EQ( src, evects ) || !CV_ARE_TYPES_EQ( src, evals ))
CV_ERROR( CV_StsUnmatchedFormats,
"input matrix, eigenvalues and eigenvectors must have the same type" );
if( !CV_IS_MAT_CONT( src->type & evals->type & evects->type ))
CV_ERROR( CV_BadStep, "all the matrices must be continuous" );
if( CV_MAT_TYPE(src->type) == CV_32FC1 )
{
IPPI_CALL( icvJacobiEigens_32f( src->data.fl,
evects->data.fl,
evals->data.fl, src->cols, (float)eps ));
}
else if( CV_MAT_TYPE(src->type) == CV_64FC1 )
{
IPPI_CALL( icvJacobiEigens_64d( src->data.db,
evects->data.db,
evals->data.db, src->cols, eps ));
}
else
{
CV_ERROR( CV_StsUnsupportedFormat, "Only 32fC1 and 64fC1 types are supported" );
}
CV_CHECK_NANS( evects );
CV_CHECK_NANS( evals );
__END__;
}
/* End of file */
| [
"[email protected]"
]
| [
[
[
1,
431
]
]
]
|
5732542d9098659131d2bebb107e67ebec967dc3 | 23e9e5636c692364688bc9e4df59cb68e2447a58 | /Dream/src/LuaGUI/YGELuaFunctor.cpp | 11632f350b2d5d8e4781871e6a2f3cdefde97ac7 | []
| no_license | yestein/dream-of-idle | e492af2a4758776958b43e4bf0e4db859a224c40 | 4e362ab98f232d68535ea26f2fab7b3cbf7bc867 | refs/heads/master | 2016-09-09T19:49:18.215943 | 2010-04-23T07:24:19 | 2010-04-23T07:24:19 | 34,108,886 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,327 | cpp | /************************************************************************
Copyright (c) Yu Lei. All rights reserved.
filename: YGELuaFunctor.cpp
created: 2010-04-20 15:31 PM
author: Yu Lei([email protected])
<change list>
1. create file (Yu Lei)
purpose: Package a Lua Function by Name to a Functor, make it can be
Call by C++ Directly
************************************************************************/
#include "YGELuaFunctor.h"
/*************************************************************************
Constructor
*************************************************************************/
YGELuaFunctor::YGELuaFunctor(lua_State* state, int func, int selfIndex):
L(state),
index(func),
self(selfIndex),
needs_lookup(false)
{
}
/*************************************************************************
Constructor
*************************************************************************/
YGELuaFunctor::YGELuaFunctor(lua_State* state, const String& func, int selfIndex, int EventType) :
L(state),
index(LUA_NOREF),
self(selfIndex),
needs_lookup(true),
function_name(func),
event_type(EventType)
{
}
/*************************************************************************
Constructor
*************************************************************************/
YGELuaFunctor::YGELuaFunctor(const YGELuaFunctor& cp) :
L(cp.L),
index(cp.index),
self(cp.self),
needs_lookup(cp.needs_lookup),
function_name(cp.function_name)
{
}
/*************************************************************************
Destructor
*************************************************************************/
YGELuaFunctor::~YGELuaFunctor()
{
if (self!=LUA_NOREF)
{
luaL_unref(L, LUA_REGISTRYINDEX, self);
}
if (index!=LUA_NOREF)
{
luaL_unref(L, LUA_REGISTRYINDEX, index);
}
}
/*************************************************************************
Call operator
*************************************************************************/
bool YGELuaFunctor::operator()(const EventArgs& args) const
{
switch ( event_type )
{
case em_NormalEvent:
{
lua_getglobal( L, function_name.c_str( ) );
lua_pcall( L, 0, 0, 0 );
}
break;
case em_MouseEvent:
break;
case em_KeyEvent:
break;
}
return true;
} | [
"yestein86@6bb0ce84-d3d1-71f5-47c4-2d9a3e80541b"
]
| [
[
[
1,
88
]
]
]
|
2b10dc967b73197fa10f6c0c9e580ccff798314b | 53ee90fbc1011cb17ba013d0a49812697d4e6130 | /MootoritePlaat/OmniMotion/VSPDE.h | ce1efcea9949982b6ecd724d09e093b9ea3d449f | []
| no_license | janoschtraumstunde/Robin | c3f68667c37c44e19473119b4b9b9be0fe2fb57f | bd691cbd2a0091e5100df5dfe1268d27c99b39f6 | refs/heads/master | 2021-01-12T14:06:44.095094 | 2010-12-09T14:34:27 | 2010-12-09T14:34:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,726 | h | //--------------------------------------------------------------------
// Arduino Console Stub
//--------------------------------------------------------------------
#if _MSC_VER
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable : 4996)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Add CPU hardware definitions
#define _AVR_IO_H_
#define _SFR_IO8(io_addr) ((io_addr))
#include "C:\Temp\Arduino IDE\hardware\tools\avr\avr\include\avr\iomxx0_1.h"
#define boolean bool
// From "c:\program files\arduino\hardware\cores\arduino\print.h"
#define DEC 10
#define HEX 16
#define OCT 8
#define BIN 2
#define BYTE 0
// From "c:\program files\arduino\hardware\cores\arduino\wiring.h"
#define HIGH 0x1
#define LOW 0x0
#define INPUT 0x0
#define OUTPUT 0x1
#define PI 3.14159265
#define HALF_PI 1.57079
#define TWO_PI 6.283185
#define DEG_TO_RAD 0.01745329
#define RAD_TO_DEG 57.2957786
#define SERIAL 0x0
#define DISPLAY 0x1
#define LSBFIRST 0
#define MSBFIRST 1
#define CHANGE 1
#define FALLING 2
#define RISING 3
#define INTERNAL 3
#define DEFAULT 1
#define EXTERNAL 0
class CSerial
{
public:
void begin(long);
void print(char*);
void print(int,int);
void println();
void println(char*);
void println(int,int);
void println(unsigned int,int);
void println(unsigned long,int);
int available();
char read();
// VSPDE
void _append(char c);
private:
char buffer[1024];
int buflen;
};
extern CSerial Serial;
extern unsigned long millis();
extern void delay(unsigned long);
extern void pinMode(int,int);
extern void digitalWrite(int,int);
extern bool digitalRead(int);
#endif
| [
"[email protected]"
]
| [
[
[
1,
91
]
]
]
|
301c78845e818154f79274fa5a422014b8ad78f6 | 9e4b72c504df07f6116b2016693abc1566b38310 | /stl.h | 9d66bebe32ad8da7c13682725b9415f2c2672d9e | [
"MIT"
]
| permissive | mmeeks/rep-snapper | 73311cadd3d8753462cf87a7e279937d284714aa | 3a91de735dc74358c0bd2259891f9feac7723f14 | refs/heads/master | 2016-08-04T08:56:55.355093 | 2010-12-05T19:03:03 | 2010-12-05T19:03:03 | 704,101 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,254 | h | /* -------------------------------------------------------- *
*
* stl.h
*
* Copyright 2009+ Michael Holm - www.kulitorum.com
*
* This file is part of RepSnapper and is made available under
* the terms of the GNU General Public License, version 2, or at your
* option, any later version, incorporated herein by reference.
*
* ------------------------------------------------------------------------- */
#pragma once
#include <vector>
#include <list>
#include "platform.h"
#include "math.h" // Needed for sqrtf
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <list>
#include <FL/Fl_Gl_Window.H>
#include <FL/gl.h>
#include <vmmlib/vmmlib.h>
#include <Polygon2f.h>
/*
Vector3f position, normal;
// fill vertices
glNormal3fv( normal.xyz );
glVertex3fv( position.xyz );
*/
using namespace std;
using namespace vmml;
using namespace PolyLib;
typedef vector<Vector2f> outline;
enum AXIS {NEGX, POSX, NEGY, POSY, NEGZ, POSZ, NOT_ALIGNED};
class Triangle
{
public:
Triangle(const Vector3f &Norml, const Vector3f &Point1, const Vector3f &Point2, const Vector3f &Point3){ Normal = Norml ; A=Point1;B=Point2;C=Point3;}
Triangle(){};
void SetPoints(const Vector3f &P1, const Vector3f &P2, const Vector3f &P3) { A=P1;B=P2;C=P3; }
void SetNormal(const Vector3f &Norml) { Normal=Norml;}
float area();
AXIS axis; // Used for auto-rotation
Vector3f A,B,C,Normal; // p1,p2,p3, Normal
};
struct InFillHit{
Vector2f p; // The intersection point
float d; // Distance from the infill-line start point, used for sorting hits
float t; // intersection point on first line
};
class Poly{
public:
Poly(){};
void cleanup(); // Removed vertices that are on a straight line
void calcHole(vector<Vector2f> &offsetVertices);
vector<uint> points; // points, indices into ..... a CuttingPlane or a GCode object
bool hole;
Vector2f center;
};
struct locator{
locator(int polygon, int vertex, float where){p=polygon; v=vertex; t=where;}
int p;
int v;
float t;
};
class CuttingPlaneOptimizer;
/* associates adjacent points with integers */
class PointHash {
struct Impl;
Impl *impl;
public:
PointHash();
~PointHash();
PointHash(const PointHash ©);
int IndexOfPoint (const Vector2f &p);
void InsertPoint (uint idx, const Vector2f &p);
void clear();
static const float mult;
static const float float_epsilon;
};
// A (set of) 2D polygon extracted from a 3D model
class CuttingPlane{
public:
CuttingPlane();
~CuttingPlane();
void ShrinkFast(float distance, float optimization, bool DisplayCuttingPlane, bool useFillets, int ShellCount); // Contracts polygons
void ShrinkLogick(float distance, float optimization, bool DisplayCuttingPlane, int ShellCount); // Contracts polygons
void ShrinkNice(float distance, float optimization, bool DisplayCuttingPlane, bool useFillets, int ShellCount); // Contracts polygons
void selfIntersectAndDivide();
uint selfIntersectAndDivideRecursive(float z, uint startPolygon, uint startVertex, vector<outline> &outlines, const Vector2f endVertex, uint &level);
void MakeContainedPlane(CuttingPlane& res)
{
res = *this;
res.polygons = res.offsetPolygons;
res.vertices = res.offsetVertices;
res.offsetPolygons.clear();
res.offsetVertices.clear();
}
void ClearShrink()
{
offsetPolygons.clear();
offsetVertices.clear();
}
void recurseSelfIntersectAndDivide(float z, vector<locator> &EndPointStack, vector<outline> &outlines, vector<locator> &visited);
void CalcInFill(vector<Vector2f> &infill, uint LayerNr, float InfillDistance, float InfillRotation, float InfillRotationPrLayer, bool DisplayDebuginFill); // Collide a infill-line with the polygons
void Draw(bool DrawVertexNumbers, bool DrawLineNumbers, bool DrawOutlineNumbers, bool DrawCPLineNumbers, bool DrawCPVertexNumbers);
bool LinkSegments(float z, float Optimization); // Link Segments to form polygons
bool CleanupConnectSegments(float z);
bool CleanupSharedSegments(float z);
void CleanupPolygons(float Optimization); // remove redudant points
void CleanupOffsetPolygons(float Optimization); // remove redudant points
void MakeGcode(const std::vector<Vector2f> &infill, GCode &code, float &E, float z, float MinPrintSpeedXY, float MaxPrintSpeedXY, float MinPrintSpeedZ, float MaxPrintSpeedZ, float DistanceToReachFullSpeed, float extrusionFactor, bool UseIncrementalEcode, bool Use3DGcode, bool EnableAcceleration); // Convert Cuttingplane to GCode
bool VertexIsOutsideOriginalPolygon( Vector2f point, float z);
Vector2f Min, Max; // Bounding box
void Clear()
{
lines.clear();
vertices.clear();
polygons.clear();
points.clear();
offsetPolygons.clear();
offsetVertices.clear();
}
void SetZ(float value)
{
Z = value;
}
float getZ() { return Z; }
int RegisterPoint(const Vector2f &p);
struct Segment {
Segment(uint s, uint e) { start = s; end = e; }
int start; // Vertex index of start point
int end; // Vertex index of end point
void Swap() {
int tmp = start;
start = end;
end = tmp;
}
};
void AddLine(const Segment &line);
vector<Poly>& GetPolygons() { return polygons; }
vector<Vector2f>& GetVertices() { return vertices; }
private:
PointHash points;
vector<CuttingPlaneOptimizer*> optimizers;
vector<Segment> lines; // Segments - 2 points pr. line-segment
vector<Poly> polygons; // Closed loops
vector<Vector2f> vertices; // points
float Z;
vector<Poly> offsetPolygons; // Shrinked closed loops
vector<Vector2f> offsetVertices;// points for shrinked closed loops
};
#define sqr(x) ((x)*(x))
class CuttingPlaneOptimizer
{
public:
float Z;
CuttingPlaneOptimizer(float z) { Z = z; }
CuttingPlaneOptimizer(CuttingPlane* cuttingPlane, float z);
list<Polygon2f*> positivePolygons;
void Shrink(float distance, list<Polygon2f*> &resPolygons);
void Draw();
void Dispose();
void MakeOffsetPolygons(vector<Poly>& polys, vector<Vector2f>& vectors);
void RetrieveLines(vector<Vector3f>& lines);
private:
void PushPoly(Polygon2f* poly);
void DoMakeOffsetPolygons(Polygon2f* pPoly, vector<Poly>& polys, vector<Vector2f>& vectors);
void DoRetrieveLines(Polygon2f* pPoly, vector<Vector3f>& lines);
};
class STL
{
public:
STL();
bool Read(string filename, bool force_binary = false );
void GetObjectsFromIvcon();
void clear(){triangles.clear();}
void displayInfillOld(const ProcessController &PC, CuttingPlane &plane, uint LayerNr, vector<int>& altInfillLayers);
void draw(const ProcessController &PC, float opasity = 1.0f);
void CenterAroundXY();
void CalcCuttingPlane(float where, CuttingPlane &plane, const Matrix4f &T); // Extract a 2D polygonset from a 3D model
void OptimizeRotation(); // Auto-Rotate object to have the largest area surface down for printing
void CalcBoundingBoxAndZoom();
void RotateObject(Vector3f axis, float angle); // Rotation for manual rotate and used by OptimizeRotation
vector<Triangle> triangles;
Vector3f Min, Max, Center;
};
| [
"repsnapper@686d4eb6-aa70-4f30-b8fa-ee57029aed71",
"Logick@686d4eb6-aa70-4f30-b8fa-ee57029aed71",
"mmeeks@686d4eb6-aa70-4f30-b8fa-ee57029aed71",
"Rick@686d4eb6-aa70-4f30-b8fa-ee57029aed71",
"joaz@686d4eb6-aa70-4f30-b8fa-ee57029aed71"
]
| [
[
[
1,
13
],
[
16,
22
],
[
24,
28
],
[
30,
39
],
[
41,
70
],
[
73,
73
],
[
75,
83
],
[
102,
102
],
[
104,
105
],
[
134,
136
],
[
180,
181
],
[
183,
184
],
[
208,
212
],
[
214,
215
],
[
217,
227
]
],
[
[
14,
14
],
[
40,
40
],
[
71,
72
],
[
74,
74
],
[
84,
85
],
[
106,
128
],
[
132,
133
],
[
138,
153
],
[
167,
171
],
[
173,
175
],
[
179,
179
],
[
182,
182
],
[
185,
207
],
[
216,
216
]
],
[
[
15,
15
],
[
86,
101
],
[
103,
103
],
[
129,
131
],
[
137,
137
],
[
154,
166
],
[
172,
172
],
[
176,
178
],
[
213,
213
]
],
[
[
23,
23
]
],
[
[
29,
29
]
]
]
|
bb35816091f6b21cbe6dac3dc168679b7275fa66 | b14d5833a79518a40d302e5eb40ed5da193cf1b2 | /cpp/extern/xercesc++/2.6.0/src/xercesc/framework/psvi/XSAttributeDeclaration.cpp | 170abd80a2b86e40bc85722aeb2c6c8ffd559e61 | [
"Apache-2.0"
]
| permissive | andyburke/bitflood | dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf | fca6c0b635d07da4e6c7fbfa032921c827a981d6 | refs/heads/master | 2016-09-10T02:14:35.564530 | 2011-11-17T09:51:49 | 2011-11-17T09:51:49 | 2,794,411 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,342 | cpp | /*
* Copyright 2003,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Log: XSAttributeDeclaration.cpp,v $
* Revision 1.15 2004/09/08 13:56:07 peiyongz
* Apache License Version 2.0
*
* Revision 1.14 2004/07/06 14:58:15 cargilld
* Rename VALUE_CONSTRAINT enumeration names to avoid naming conflict with AIX system header which already uses VC_DEFAULT as a macro. Will need to document that this fix breaks source code compatibility.
*
* Revision 1.13 2004/05/04 19:02:40 cargilld
* Enable IDs to work on all kinds of schema components
*
* Revision 1.12 2004/01/29 11:46:30 cargilld
* Code cleanup changes to get rid of various compiler diagnostic messages.
*
* Revision 1.11 2004/01/06 03:55:26 knoaman
* Various PSVI fixes.
*
* Revision 1.10 2003/12/30 20:41:06 neilg
* do not report anything about default/fixed values for non-global attribute declarations
*
* Revision 1.9 2003/12/29 17:06:31 knoaman
* PSVI: return value constraint only if global declaration
*
* Revision 1.8 2003/12/29 16:15:42 knoaman
* More PSVI updates
*
* Revision 1.7 2003/11/21 22:34:45 neilg
* More schema component model implementation, thanks to David Cargill.
* In particular, this cleans up and completes the XSModel, XSNamespaceItem,
* XSAttributeDeclaration and XSAttributeGroup implementations.
*
* Revision 1.6 2003/11/21 17:19:30 knoaman
* PSVI update.
*
* Revision 1.5 2003/11/14 22:47:53 neilg
* fix bogus log message from previous commit...
*
* Revision 1.4 2003/11/14 22:33:30 neilg
* Second phase of schema component model implementation.
* Implement XSModel, XSNamespaceItem, and the plumbing necessary
* to connect them to the other components.
* Thanks to David Cargill.
*
* Revision 1.3 2003/11/06 15:30:04 neilg
* first part of PSVI/schema component model implementation, thanks to David Cargill. This covers setting the PSVIHandler on parser objects, as well as implementing XSNotation, XSSimpleTypeDefinition, XSIDCDefinition, and most of XSWildcard, XSComplexTypeDefinition, XSElementDeclaration, XSAttributeDeclaration and XSAttributeUse.
*
* Revision 1.2 2003/09/17 17:45:37 neilg
* remove spurious inlines; hopefully this will make Solaris/AIX compilers happy.
*
* Revision 1.1 2003/09/16 14:33:36 neilg
* PSVI/schema component model classes, with Makefile/configuration changes necessary to build them
*
*/
#include <xercesc/framework/psvi/XSAttributeDeclaration.hpp>
#include <xercesc/framework/psvi/XSModel.hpp>
#include <xercesc/framework/psvi/XSNamespaceItem.hpp>
#include <xercesc/util/StringPool.hpp>
#include <xercesc/validators/schema/SchemaGrammar.hpp>
#include <xercesc/validators/schema/SchemaAttDef.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// XSAttributeDeclaration: Constructors and Destructor
// ---------------------------------------------------------------------------
XSAttributeDeclaration::XSAttributeDeclaration(SchemaAttDef* const attDef,
XSSimpleTypeDefinition* const typeDef,
XSAnnotation* const annot,
XSModel* const xsModel,
XSConstants::SCOPE scope,
XSComplexTypeDefinition* enclosingCTDefinition,
MemoryManager * const manager)
: XSObject(XSConstants::ATTRIBUTE_DECLARATION, xsModel, manager)
, fAttDef(attDef)
, fTypeDefinition(typeDef)
, fAnnotation(annot)
, fScope(scope)
, fEnclosingCTDefinition(enclosingCTDefinition)
{
}
XSAttributeDeclaration::~XSAttributeDeclaration()
{
// don't delete fTypeDefinition - deleted by XSModel
}
// ---------------------------------------------------------------------------
// XSAttributeDeclaration: XSObject virtual methods
// ---------------------------------------------------------------------------
const XMLCh *XSAttributeDeclaration::getName()
{
return fAttDef->getAttName()->getLocalPart();
}
const XMLCh *XSAttributeDeclaration::getNamespace()
{
return fXSModel->getURIStringPool()->getValueForId(fAttDef->getAttName()->getURI());
}
XSNamespaceItem *XSAttributeDeclaration::getNamespaceItem()
{
return fXSModel->getNamespaceItem(getNamespace());
}
// ---------------------------------------------------------------------------
// XSAttributeDeclaration: access methods
// ---------------------------------------------------------------------------
XSConstants::VALUE_CONSTRAINT XSAttributeDeclaration::getConstraintType() const
{
if (fScope != XSConstants::SCOPE_GLOBAL)
return XSConstants::VALUE_CONSTRAINT_NONE;
if (fAttDef->getDefaultType() == XMLAttDef::Default)
return XSConstants::VALUE_CONSTRAINT_DEFAULT;
if ((fAttDef->getDefaultType() == XMLAttDef::Fixed) ||
(fAttDef->getDefaultType() == XMLAttDef::Required_And_Fixed))
return XSConstants::VALUE_CONSTRAINT_FIXED;
return XSConstants::VALUE_CONSTRAINT_NONE;
}
const XMLCh *XSAttributeDeclaration::getConstraintValue()
{
if (fScope == XSConstants::SCOPE_GLOBAL)
return fAttDef->getValue();
return 0;
}
bool XSAttributeDeclaration::getRequired() const
{
if (fAttDef->getDefaultType() == XMLAttDef::Required ||
fAttDef->getDefaultType() == XMLAttDef::Required_And_Fixed)
return true;
return false;
}
XERCES_CPP_NAMESPACE_END
| [
"[email protected]"
]
| [
[
[
1,
160
]
]
]
|
96559a62bec65bf1790b697f951d2ec8ebc32b78 | bdb1e38df8bf74ac0df4209a77ddea841045349e | /CapsuleSortor/Version 1.0 -2.0/CapsuleSortor-10-11-11/ToolSrc/TMutex.cpp | 0ed87a9f5a96cd4301e3f053e9bb5e5b7779a1d2 | []
| no_license | Strongc/my001project | e0754f23c7818df964289dc07890e29144393432 | 07d6e31b9d4708d2ef691d9bedccbb818ea6b121 | refs/heads/master | 2021-01-19T07:02:29.673281 | 2010-12-17T03:10:52 | 2010-12-17T03:10:52 | 49,062,858 | 0 | 1 | null | 2016-01-05T11:53:07 | 2016-01-05T11:53:07 | null | UTF-8 | C++ | false | false | 992 | cpp | // TMutex.h : Implement of the TMutex class
//
// Copyright (c) 2007 PACS Group Zibo Creative Computor CO.,LTD
//////////////////////////////////////////////////////////////////////////
// Module : Common Tool
// Create Date : 2006.01.09
//
// A tool to use Mutex
#include "TMutex.h"
TMutex::TMutex(LPCTSTR pName, BOOL bInitialOwner, LPCTSTR pExtName)
: m_hMutex(NULL)
{
if(NULL == pExtName)
{
m_hMutex = ::CreateMutex(NULL, bInitialOwner, pName);
}
else
{
int nameLen = lstrlen(pName);
int extLen = lstrlen(pExtName);
TCHAR *pMutexName = new TCHAR[nameLen + extLen + 1];
*pMutexName = 0;
lstrcat(pMutexName, pName);
lstrcat(pMutexName, pExtName);
m_hMutex = ::CreateMutex(NULL, bInitialOwner, pMutexName);
delete []pMutexName;
}
}
TMutex::~TMutex()
{
if(m_hMutex)
::CloseHandle(m_hMutex);
}
void TMutex::Lock()
{
::WaitForSingleObject(m_hMutex, INFINITE);
}
void TMutex::Unlock()
{
::ReleaseMutex(m_hMutex);
}
| [
"vincen.cn@66f52ff4-a261-11de-b161-9f508301ba8e"
]
| [
[
[
1,
46
]
]
]
|
9123c3e1f05e28018b8ed5eb2e8084b79608b34b | ab2777854d7040cc4029edcd1eccc6d48ca55b29 | /Algorithm/AutoFinder/stdafx.cpp | 9cac3b175e3c9a5849a945c2bc7007795234ee9f | []
| 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 | 336 | cpp | // stdafx.cpp : 표준 포함 파일만 들어 있는 소스 파일입니다.
// AutoFinder.pch는 미리 컴파일된 헤더가 됩니다.
// stdafx.obj에는 미리 컴파일된 형식 정보가 포함됩니다.
#include "stdafx.h"
// TODO: 필요한 추가 헤더는
// 이 파일이 아닌 STDAFX.H에서 참조합니다.
| [
"arallab3@883913d8-bf2b-11de-8cd0-f941f5a20a08"
]
| [
[
[
1,
8
]
]
]
|
587c9059d9467cda9b5479923a0650128596f1c4 | 15fc90dea35740998f511319027d9971bae9251c | /UnINI/MSI_PatchINI/stdafx.h | 0ed8ae2e77c7e8c122ec14982852885f20d6dc2e | []
| no_license | ECToo/switch-soft | c35020249be233cf1e35dc18b5c097894d5efdb4 | 5edf2cc907259fb0a0905fc2c321f46e234e6263 | refs/heads/master | 2020-04-02T10:15:53.067883 | 2009-05-29T15:13:23 | 2009-05-29T15:13:23 | 32,216,312 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,675 | h | // stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
// Modify the following defines if you have to target a platform prior to the ones specified below.
// Refer to MSDN for the latest info on corresponding values for different platforms.
#ifndef WINVER // Allow use of features specific to Windows XP or later.
#define WINVER 0x0501 // Change this to the appropriate value to target other versions of Windows.
#endif
#ifndef _WIN32_WINNT // Allow use of features specific to Windows XP or later.
#define _WIN32_WINNT 0x0501 // Change this to the appropriate value to target other versions of Windows.
#endif
#ifndef _WIN32_WINDOWS // Allow use of features specific to Windows 98 or later.
#define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later.
#endif
#ifndef _WIN32_IE // Allow use of features specific to IE 6.0 or later.
#define _WIN32_IE 0x0600 // Change this to the appropriate value to target other versions of IE.
#endif
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>
// TODO: reference additional headers your program requires here
#include <shlwapi.h>
#pragma comment(lib, "shlwapi.lib")
#include <string>
using std::wstring;
//
// Include the MSI declarations etc
// - Also ensure the dll is linked with msi.lib
//
#include <msi.h>
#include <msiquery.h>
#pragma comment(lib, "msi.lib")
#include "PatchINI/PatchINIStatic.h" | [
"roman.dzieciol@e6f6c67e-47ec-11de-80ae-c1ff141340a0"
]
| [
[
[
1,
51
]
]
]
|
14eec978776ac44bbd0b53e8e5467f4efe9e5650 | 877bad5999a3eeab5d6d20b5b69a273b730c5fd8 | /TestKhoaLuan/DirectShowTVSample/Histogram/stdafx.cpp | 3d2892a1f03bc7bb844d9f6e9e9beceba819856b | []
| no_license | eaglezhao/tracnghiemweb | ebdca23cb820769303d27204156a2999b8381e03 | aaae7bb7b9393a8000d395c1d98dcfc389e3c4ed | refs/heads/master | 2021-01-10T12:26:27.694468 | 2010-10-06T01:15:35 | 2010-10-06T01:15:35 | 45,880,587 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 296 | cpp | // stdafx.cpp : source file that includes just the standard includes
// Histogram.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"[email protected]"
]
| [
[
[
1,
8
]
]
]
|
750d54f283ba52b92896d6c025c48f0545c4cbc9 | cf58ec40b7ea828aba01331ee3ab4c7f2195b6ca | /Nestopia/core/board/NstBoardBtlDragonNinja.cpp | b20a4d2e4b3e47b0342751a762bf5a9951d75f05 | []
| no_license | nicoya/OpenEmu | e2fd86254d45d7aa3d7ef6a757192e2f7df0da1e | dd5091414baaaddbb10b9d50000b43ee336ab52b | refs/heads/master | 2021-01-16T19:51:53.556272 | 2011-08-06T18:52:40 | 2011-08-06T18:52:40 | 2,131,312 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,240 | cpp | ////////////////////////////////////////////////////////////////////////////////////////
//
// Nestopia - NES/Famicom emulator written in C++
//
// Copyright (C) 2003-2008 Martin Freij
//
// This file is part of Nestopia.
//
// Nestopia 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.
//
// Nestopia 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 Nestopia; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
////////////////////////////////////////////////////////////////////////////////////////
#include "../NstClock.hpp"
#include "NstBoard.hpp"
#include "NstBoardBtlDragonNinja.hpp"
namespace Nes
{
namespace Core
{
namespace Boards
{
namespace Btl
{
#ifdef NST_MSVC_OPTIMIZE
#pragma optimize("s", on)
#endif
DragonNinja::DragonNinja(const Context& c)
: Board(c), irq(*c.cpu,*c.ppu) {}
void DragonNinja::Irq::Reset(bool)
{
count = 0;
}
void DragonNinja::SubReset(bool)
{
irq.Reset( true );
for (uint i=0x0000; i < 0x1000; i += 0x4)
{
Map( 0x8000 + i, PRG_SWAP_8K_0 );
Map( 0x9000 + i, NMT_SWAP_HV );
Map( 0xA000 + i, PRG_SWAP_8K_1 );
Map( 0xB000 + i, CHR_SWAP_1K_0 );
Map( 0xB002 + i, CHR_SWAP_1K_1 );
Map( 0xC000 + i, CHR_SWAP_1K_2 );
Map( 0xC002 + i, CHR_SWAP_1K_3 );
Map( 0xD000 + i, CHR_SWAP_1K_4 );
Map( 0xD002 + i, CHR_SWAP_1K_5 );
Map( 0xE000 + i, CHR_SWAP_1K_6 );
Map( 0xE002 + i, CHR_SWAP_1K_7 );
Map( 0xF000 + i, &DragonNinja::Poke_F000 );
}
}
void DragonNinja::SubLoad(State::Loader& state,const dword baseChunk)
{
NST_VERIFY( baseChunk == (AsciiId<'B','D','N'>::V) );
if (baseChunk == AsciiId<'B','D','N'>::V)
{
while (const dword chunk = state.Begin())
{
if (chunk == AsciiId<'I','R','Q'>::V)
irq.unit.count = state.Read8();
state.End();
}
}
}
void DragonNinja::SubSave(State::Saver& state) const
{
state.Begin( AsciiId<'B','D','N'>::V ).Begin( AsciiId<'I','R','Q'>::V ).Write8( irq.unit.count ).End().End();
}
#ifdef NST_MSVC_OPTIMIZE
#pragma optimize("", on)
#endif
bool DragonNinja::Irq::Clock()
{
if (!count || ++count < 240)
return false;
count = 0;
return true;
}
NES_POKE_D(DragonNinja,F000)
{
irq.Update();
irq.ClearIRQ();
irq.unit.count = data;
}
void DragonNinja::Sync(Event event,Input::Controllers* controllers)
{
if (event == EVENT_END_FRAME)
irq.VSync();
Board::Sync( event, controllers );
}
}
}
}
}
| [
"[email protected]"
]
| [
[
[
1,
122
]
]
]
|
49400d854d182728b7fc108c5927243397cc0b3f | 9534a57673ec895f75061a0ca0d8069e3ca7f084 | /samples/pstvalues/main.cpp | 3aa8ec1582d24e07c3fb40c380e3fd67c4a73774 | []
| no_license | emk/pstsdk | be9482348a26b331747da34b17212739cdc3e556 | 21c7d2d57bd09555afd0a08adc966f9b3779cb19 | refs/heads/master | 2016-08-05T18:18:02.261135 | 2010-07-16T02:58:43 | 2010-07-16T02:58:43 | 724,405 | 12 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 1,164 | cpp | #include "values.h"
#include <string>
#include <iostream>
#include <regex>
#include <stdexcept>
#ifdef USE_BOOST
namespace REGEX = boost;
#else
namespace REGEX = std::tr1;
#endif
void print_value(int i)
{
using namespace std;
wcout << values[i].name;
wcout << L": " << dec << values[i].v;
wcout << ", 0x" << hex << values[i].v << endl;
}
int main(int argc, const char* argv[])
{
try {
std::vector<REGEX::wregex> expressions;
for(int i = 1; i < argc; ++i)
{
std::string s(argv[i]);
std::wstring w(s.begin(), s.end());
expressions.push_back(REGEX::wregex(w));
}
for(unsigned int i = 0; i < sizeof(values)/sizeof(values[0]); ++i)
{
for(unsigned int j = 0; j < expressions.size(); ++j)
{
if(regex_search(std::wstring(values[i].name), expressions[j]))
{
print_value(i);
break;
}
}
}
} catch(std::exception& e) {
std::wcout << e.what() << std::endl;
}
}
| [
"SND\\terrymah_cp@c102de6d-fbcd-4082-88ef-c2bab1378b82"
]
| [
[
[
1,
48
]
]
]
|
08dbbad7a8478a2ecf863b34f429648b3b499215 | fbe2cbeb947664ba278ba30ce713810676a2c412 | /iptv_root/iptv_wboard/include/iptv_wboard/WBoardBridge.h | 915793ed7c4b34d53f4bb8fb3a774a10f972bf4b | []
| no_license | abhipr1/multitv | 0b3b863bfb61b83c30053b15688b070d4149ca0b | 6a93bf9122ddbcc1971dead3ab3be8faea5e53d8 | refs/heads/master | 2020-12-24T15:13:44.511555 | 2009-06-04T17:11:02 | 2009-06-04T17:11:02 | 41,107,043 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,784 | h | #if !defined _WBOARDBRIDGE_H
#define _WBOARDBRIDGE_H
#include "WBoardInfo.h"
class IWBInterface
{
public:
virtual void ToolBoxItemSel( int nId ) = 0;
virtual void ToolBoxItemEnable( int nId, bool bOp) = 0;
virtual void ToolBoxPenSizeSel( int nId ) = 0;
virtual void ToolBoxColorSel( ColorDef& color ) = 0;
virtual void ToolBoxFontSel( FontDef& font ) = 0;
virtual bool MenuBarNewExec( bool bChanged, bool bRepaint ) = 0;
virtual void MenuBarSaveExec( ) = 0;
virtual void MenuBarPrintExec( ) = 0;
virtual void MenuBarPageSetup( ) = 0;
virtual void MenuBarCutExec( ) = 0;
virtual void MenuBarUndoExec( ) = 0;
virtual void MenuBarImageStopExec( ) = 0;
virtual void MenuBarImageStopEnable( bool bOp ) = 0;
virtual void EdtSelArea( PtPos& pt1, PtPos& pt2 ) = 0;
virtual void EdtSelRect( PtPos& pt1, PtPos& pt2 ) = 0;
virtual void EdtSelEllipse( PtPos& pt1, PtPos& pt2 ) = 0;
virtual void EdtSelLine( PtPos& pt1, PtPos& pt2 ) = 0;
virtual void EdtDrawArea( PtPos& pt1, PtPos& pt2 ) = 0;
virtual void EdtKillArea( ) = 0;
virtual void EdtRepaint( ) = 0;
virtual void ScrScrollWindow( int dx, int dy ) = 0;
virtual void ScrSetScrollPos( int posx, int posy ) = 0;
virtual void CtlDrawRect( PtPos& pt1, PtPos& pt2, int nLin, ColorDef& color, bool bFull, WB_BYTE flags ) = 0;
virtual void CtlDrawEllipse( PtPos& pt1, PtPos& pt2, int nLin, ColorDef& color, bool bFull, WB_BYTE flags ) = 0;
virtual void CtlDrawLine( PtPos& pt1, PtPos& pt2, int nLin, ColorDef& color, bool bMask, WB_BYTE flags ) = 0;
virtual void CtlDrawIndicator( PtPos& pt, WB_BYTE flags ) = 0;
virtual void CtlDrawImage( WB_PCSTR szFile, PtPos& pt1, PtPos& pt2, WB_BYTE flags ) = 0;
virtual void CtlDrawTxt( WB_PCSTR szText, PtPos& pt1, PtPos& pt2, FontDef& font, ColorDef& color, WB_BYTE flags ) = 0;
virtual void CtlEditTxt( PtPos& pt1, PtPos& pt2, FontDef& font, ColorDef& color ) = 0;
virtual void CtlGetTxt( WB_PSTR szText ) = 0;
};
class IWBProcess
{
public:
virtual void OnWindowCreate( IWBInterface* pInterface ) = 0;
virtual void OnWindowClose( ) = 0;
virtual void OnWindowDestroy( ) = 0;
virtual void OnToolBoxItemClick( int nId ) = 0;
virtual void OnToolBoxPenSizeClick( int nId ) = 0;
virtual void OnToolBoxColorClick( ColorDef& color ) = 0;
virtual void OnToolBoxFontClick( FontDef& font ) = 0;
virtual void OnToolBoxImageSel( WB_PCSTR szFile ) = 0;
virtual void OnMenuBarNewClick( ) = 0;
virtual void OnMenuBarSaveClick( ) = 0;
virtual void OnMenuBarPrintClick( ) = 0;
virtual void OnMenuBarPageSetupClick( ) = 0;
virtual void OnMenuBarCutClick( ) = 0;
virtual void OnMenuBarUndoClick( ) = 0;
virtual void OnMenuBarImageStopClick( ) = 0;
virtual void OnMouseLButtonDown( MouseFlag flag, PtPos& point ) = 0;
virtual void OnMouseLButtonUp( MouseFlag flag, PtPos& point ) = 0;
virtual void OnMouseMove( MouseFlag flag, PtPos& point ) = 0;
virtual void OnEditRedraw( ) = 0;
virtual void OnEditCutArea( PtPos& pt1, PtPos& pt2 ) = 0;
virtual void OnScreenScrollWindow( int dx, int dy ) = 0;
virtual void OnScreenSetScrollPos( int posx, int posy ) = 0;
};
class WBInterfaceRef
{
public:
void SetInterfacePtr(IWBInterface* pInterface) { pINotify = pInterface; }
IWBInterface* GetInterfacePtr() { return pINotify; }
private:
IWBInterface* pINotify;
};
class WBProcessRef
{
public:
void SetProcessPtr(IWBProcess* pProcess) { pINotify = pProcess; }
IWBProcess* GetProcessPtr() { return pINotify; }
private:
IWBProcess* pINotify;
};
#endif //_WBOARDBRIDGE_H
| [
"heineck@c016ff2c-3db2-11de-a81c-fde7d73ceb89"
]
| [
[
[
1,
108
]
]
]
|
3027b59693280573da654e1be53e7e4d31214c85 | a0bc9908be9d42d58af7a1a8f8398c2f7dcfa561 | /SlonEngine/src/Graphics/Detail/Pass.cpp | 9b0d536e7aed384f1c89b9709da2984df0405ede | []
| no_license | BackupTheBerlios/slon | e0ca1137a84e8415798b5323bc7fd8f71fe1a9c6 | dc10b00c8499b5b3966492e3d2260fa658fee2f3 | refs/heads/master | 2016-08-05T09:45:23.467442 | 2011-10-28T16:19:31 | 2011-10-28T16:19:31 | 39,895,039 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,149 | cpp | #include "stdafx.h"
#include "Graphics/Common.h"
#include "Graphics/Detail/Pass.h"
#include "Graphics/ParameterBinding.h"
#include <boost/iterator/indirect_iterator.hpp>
#include <boost/bind.hpp>
DECLARE_AUTO_LOGGER("graphics.detail.Pass")
namespace {
using namespace slon;
sgl::ref_ptr<sgl::BlendState> defaultBlendState;
sgl::ref_ptr<sgl::DepthStencilState> defaultDepthStencilState;
sgl::ref_ptr<sgl::RasterizerState> defaultRasterizerState;
sgl::BlendState* createDefaultBlendState()
{
if (!defaultBlendState)
{
sgl::BlendState::DESC desc;
desc.blendEnable = false;
defaultBlendState.reset( graphics::currentDevice()->CreateBlendState(desc) );
}
return defaultBlendState.get();
}
sgl::DepthStencilState* createDefaultDepthStencilState()
{
if (!defaultDepthStencilState)
{
sgl::DepthStencilState::DESC desc;
desc.depthEnable = true;
desc.depthFunc = sgl::DepthStencilState::LEQUAL;
desc.depthWriteMask = true;
desc.stencilEnable = false;
defaultDepthStencilState.reset( graphics::currentDevice()->CreateDepthStencilState(desc) );
}
return defaultDepthStencilState.get();
}
sgl::RasterizerState* createDefaultRasterizerState()
{
if (!defaultRasterizerState)
{
sgl::RasterizerState::DESC desc;
desc.cullMode = sgl::RasterizerState::BACK;
desc.fillMode = sgl::RasterizerState::SOLID;
desc.colorMask = sgl::RasterizerState::RGBA;
defaultRasterizerState.reset( graphics::currentDevice()->CreateRasterizerState(desc) );
}
return defaultRasterizerState.get();
}
}
namespace slon {
namespace graphics {
namespace detail {
Pass::Pass()
{
}
Pass::Pass(const DESC& desc)
{
program.reset(desc.program);
blendState.reset(desc.blendState ? desc.blendState : createDefaultBlendState());
depthStencilState.reset(desc.depthStencilState ? desc.depthStencilState : createDefaultDepthStencilState());
rasterizerState.reset(desc.rasterizerState ? desc.rasterizerState : createDefaultRasterizerState());
for (size_t i = 0; i<desc.numUniforms; ++i)
{
// Not very good situation, notify may be
if (!desc.uniforms[i].uniformName && !desc.uniforms[i].uniform) {
continue;
}
if (!desc.uniforms[i].parameter && !desc.uniforms[i].parameterName) {
continue;
}
// find corresponding uniform <-> parameter pairs, check their types
sgl::AbstractUniform* uniform = desc.uniforms[i].uniform ?
desc.uniforms[i].uniform :
program->GetUniform(desc.uniforms[i].uniformName);
const abstract_parameter_binding* parameter = desc.uniforms[i].parameter ?
desc.uniforms[i].parameter :
currentParameterTable().getParameterBinding(desc.uniforms[i].parameterName).get();
bool compatible = false;
if (uniform && parameter)
{
switch ( uniform->Type() )
{
case sgl::AbstractUniform::INT:
{
const binding_int* typedParameter = dynamic_cast<const binding_int*>(parameter);
if ( (compatible = (typedParameter != 0)) ) {
linkUniform( static_cast<sgl::UniformI*>(uniform), typedParameter );
}
break;
}
case sgl::AbstractUniform::VEC2I:
{
const binding_vec2i* typedParameter = dynamic_cast<const binding_vec2i*>(parameter);
if ( (compatible = (typedParameter != 0)) ) {
linkUniform( static_cast<sgl::Uniform2I*>(uniform), typedParameter );
}
break;
}
case sgl::AbstractUniform::VEC3I:
{
const binding_vec3i* typedParameter = dynamic_cast<const binding_vec3i*>(parameter);
if ( (compatible = (typedParameter != 0)) ) {
linkUniform( static_cast<sgl::Uniform3I*>(uniform), typedParameter );
}
break;
}
case sgl::AbstractUniform::VEC4I:
{
const binding_vec4i* typedParameter = dynamic_cast<const binding_vec4i*>(parameter);
if ( (compatible = (typedParameter != 0)) ) {
linkUniform( static_cast<sgl::Uniform4I*>(uniform), typedParameter );
}
break;
}
case sgl::AbstractUniform::FLOAT:
{
const binding_float* typedParameter = dynamic_cast<const binding_float*>(parameter);
if ( (compatible = (typedParameter != 0)) ) {
linkUniform( static_cast<sgl::UniformF*>(uniform), typedParameter );
}
break;
}
case sgl::AbstractUniform::VEC2F:
{
const binding_vec2f* typedParameter = dynamic_cast<const binding_vec2f*>(parameter);
if ( (compatible = (typedParameter != 0)) ) {
linkUniform( static_cast<sgl::Uniform2F*>(uniform), typedParameter );
}
break;
}
case sgl::AbstractUniform::VEC3F:
{
const binding_vec3f* typedParameter = dynamic_cast<const binding_vec3f*>(parameter);
if ( (compatible = (typedParameter != 0)) ) {
linkUniform( static_cast<sgl::Uniform3F*>(uniform), typedParameter );
}
break;
}
case sgl::AbstractUniform::VEC4F:
{
const binding_vec4f* typedParameter = dynamic_cast<const binding_vec4f*>(parameter);
if ( (compatible = (typedParameter != 0)) ) {
linkUniform( static_cast<sgl::Uniform4F*>(uniform), typedParameter );
}
break;
}
case sgl::AbstractUniform::MAT2x2F:
{
const binding_mat2x2f* typedParameter = dynamic_cast<const binding_mat2x2f*>(parameter);
if ( (compatible = (typedParameter != 0)) ) {
linkUniform( static_cast<sgl::Uniform2x2F*>(uniform), typedParameter );
}
break;
}
case sgl::AbstractUniform::MAT3x3F:
{
const binding_mat3x3f* typedParameter = dynamic_cast<const binding_mat3x3f*>(parameter);
if ( (compatible = (typedParameter != 0)) ) {
linkUniform( static_cast<sgl::Uniform3x3F*>(uniform), typedParameter );
}
break;
}
case sgl::AbstractUniform::MAT4x4F:
{
const binding_mat4x4f* typedParameter = dynamic_cast<const binding_mat4x4f*>(parameter);
if ( (compatible = (typedParameter != 0)) ) {
linkUniform( static_cast<sgl::Uniform4x4F*>(uniform), typedParameter );
}
break;
}
case sgl::AbstractUniform::SAMPLER_2D:
{
const binding_tex_2d* typedParameter = dynamic_cast<const binding_tex_2d*>(parameter);
if ( (compatible = (typedParameter != 0)) ) {
linkSamplerUniform( static_cast<sgl::SamplerUniform2D*>(uniform), typedParameter );
}
break;
}
case sgl::AbstractUniform::SAMPLER_3D:
{
const binding_tex_3d* typedParameter = dynamic_cast<const binding_tex_3d*>(parameter);
if ( (compatible = (typedParameter != 0)) ) {
linkSamplerUniform( static_cast<sgl::SamplerUniform3D*>(uniform), typedParameter );
}
break;
}
case sgl::AbstractUniform::SAMPLER_CUBE:
{
const binding_tex_cube* typedParameter = dynamic_cast<const binding_tex_cube*>(parameter);
if ( (compatible = (typedParameter != 0)) ) {
linkSamplerUniform( static_cast<sgl::SamplerUniformCube*>(uniform), typedParameter );
}
break;
}
default:
AUTO_LOGGER_MESSAGE(log::S_WARNING, "Uniform '"
<< (desc.uniforms[i].uniform ? "..." : desc.uniforms[i].uniformName)
<< "' have unsupported type.\n");
break;
}
}
if (!uniform)
{
AUTO_LOGGER_MESSAGE(log::S_WARNING, "Uniform '"
<< (desc.uniforms[i].uniform ? "..." : desc.uniforms[i].uniformName)
<< "' was not loaded.\n");
}
else if (!parameter)
{
AUTO_LOGGER_MESSAGE(log::S_WARNING, "Parameter for uniform '"
<< (desc.uniforms[i].uniform ? "..." : desc.uniforms[i].uniformName)
<< "' not specified.\n");
}
else if (!compatible)
{
AUTO_LOGGER_MESSAGE(log::S_WARNING, "Parameter and uniform '"
<< (desc.uniforms[i].uniform ? "..." : desc.uniforms[i].uniformName)
<< "' have incompatible types.\n");
}
}
}
Pass::~Pass()
{
}
void Pass::begin() const
{
sgl::Device* device = currentDevice();
// bind program
if (program)
{
if ( device->CurrentProgram() != program ) {
program->Bind();
}
}
else
{
if ( device->CurrentProgram() ) {
device->CurrentProgram()->Unbind();
}
}
// bind uniforms
std::for_each( boost::make_indirect_iterator( uniformBinders.begin() ),
boost::make_indirect_iterator( uniformBinders.end() ),
boost::mem_fn(&AbstractUniformBinder::bind) );
// bind samplers
unsigned stage = 0;
for (sampler_binder_const_iterator iter = samplerBinders.begin();
iter != samplerBinders.end();
++iter)
{
(*iter)->bind(stage++);
}
// bind states
if ( device->CurrentBlendState() != blendState ) {
blendState->Bind();
}
if ( device->CurrentDepthStencilState() != depthStencilState ) {
depthStencilState->Bind();
}
if ( device->CurrentRasterizerState() != rasterizerState ) {
rasterizerState->Bind();
}
}
void Pass::end() const
{
}
void Pass::setBlendState(const sgl::BlendState* blendState_)
{
blendState.reset(blendState_);
}
void Pass::setDepthStencilState(const sgl::DepthStencilState* depthStencilState_)
{
depthStencilState.reset(depthStencilState_);
}
void Pass::setRasterizerState(const sgl::RasterizerState* rasterizerState_)
{
rasterizerState.reset(rasterizerState_);
}
template<typename T>
bool Pass::linkUniform(sgl::Uniform<T>* uniform,
const parameter_binding<T>* parameter)
{
typedef boost::intrusive_ptr< uniform_binding<T> > uniform_binding_ptr;
// find or create uniform binding
uniform_binding_ptr binding = detail::currentUniformTable().getUniformBinding(uniform);
if (!binding) {
binding = detail::currentUniformTable().addUniformBinding(uniform);
}
// add uniform binding
for (uniform_binder_iterator iter = uniformBinders.begin();
iter != uniformBinders.end();
++iter)
{
UniformBinder<T>* binder = dynamic_cast< UniformBinder<T>* >(iter->get());
if ( binder && binder->getBinding() == binding.get() )
{
binder->setParameter(parameter);
return true;
}
}
// create binder
UniformBinder<T>* binder = new UniformBinder<T>(binding.get(), parameter);
uniformBinders.push_back(binder);
return true;
}
template<typename T>
bool Pass::linkUniform(size_t uniform,
const parameter_binding<T>* parameter)
{
if ( uniform < uniformBinders.size() ) {
return false;
}
if ( UniformBinder<T>* binder = dynamic_cast< UniformBinder<T>* >(uniformBinders[uniform].get()) )
{
binder->setParameter(parameter);
return true;
}
return false;
}
template<typename T>
bool Pass::linkSamplerUniform(sgl::SamplerUniform<T>* uniform,
const parameter_binding<T>* parameter)
{
typedef boost::intrusive_ptr< sampler_uniform_binding<T> > uniform_binding_ptr;
// find or create uniform binding
uniform_binding_ptr binding = detail::currentUniformTable().getUniformBinding(uniform);
if (!binding) {
binding = detail::currentUniformTable().addUniformBinding(uniform);
}
// add uniform binding
for (sampler_binder_iterator iter = samplerBinders.begin();
iter != samplerBinders.end();
++iter)
{
SamplerUniformBinder<T>* binder = dynamic_cast< SamplerUniformBinder<T>* >(iter->get());
if ( binder && binder->getBinding() == binding.get() )
{
binder->setParameter(parameter);
return true;
}
}
// create binder
SamplerUniformBinder<T>* binder = new SamplerUniformBinder<T>(binding.get(), parameter);
samplerBinders.push_back(binder);
return true;
}
template<typename T>
bool Pass::linkSamplerUniform(size_t uniform,
const parameter_binding<T>* parameter)
{
if ( uniform < samplerBinders.size() ) {
return false;
}
if ( SamplerUniformBinder<T>* binder = dynamic_cast< SamplerUniformBinder<T>* >(samplerBinders[uniform].get()) )
{
binder->setParameter(parameter);
return true;
}
return false;
}
// explicit template instantiation
template bool Pass::linkUniform<float>(size_t, const parameter_binding<float>*);
template bool Pass::linkUniform<math::Vector2f>(size_t, const parameter_binding<math::Vector2f>*);
template bool Pass::linkUniform<math::Vector3f>(size_t, const parameter_binding<math::Vector3f>*);
template bool Pass::linkUniform<math::Vector4f>(size_t, const parameter_binding<math::Vector4f>*);
template bool Pass::linkUniform<math::Matrix2x2f>(size_t, const parameter_binding<math::Matrix2x2f>*);
template bool Pass::linkUniform<math::Matrix3x3f>(size_t, const parameter_binding<math::Matrix3x3f>*);
template bool Pass::linkUniform<math::Matrix4x4f>(size_t, const parameter_binding<math::Matrix4x4f>*);
template bool Pass::linkUniform<int>(size_t, const parameter_binding<int>*);
template bool Pass::linkUniform<math::Vector2i>(size_t, const parameter_binding<math::Vector2i>*);
template bool Pass::linkUniform<math::Vector3i>(size_t, const parameter_binding<math::Vector3i>*);
template bool Pass::linkUniform<math::Vector4i>(size_t, const parameter_binding<math::Vector4i>*);
template bool Pass::linkSamplerUniform<sgl::Texture2D>(size_t, const parameter_binding<sgl::Texture2D>*);
template bool Pass::linkSamplerUniform<sgl::Texture3D>(size_t, const parameter_binding<sgl::Texture3D>*);
template bool Pass::linkSamplerUniform<sgl::TextureCube>(size_t, const parameter_binding<sgl::TextureCube>*);
template bool Pass::linkUniform<float>(sgl::Uniform<float>*, const parameter_binding<float>*);
template bool Pass::linkUniform<math::Vector2f>(sgl::Uniform<math::Vector2f>*, const parameter_binding<math::Vector2f>*);
template bool Pass::linkUniform<math::Vector3f>(sgl::Uniform<math::Vector3f>*, const parameter_binding<math::Vector3f>*);
template bool Pass::linkUniform<math::Vector4f>(sgl::Uniform<math::Vector4f>*, const parameter_binding<math::Vector4f>*);
template bool Pass::linkUniform<math::Matrix2x2f>(sgl::Uniform<math::Matrix2x2f>*, const parameter_binding<math::Matrix2x2f>*);
template bool Pass::linkUniform<math::Matrix3x3f>(sgl::Uniform<math::Matrix3x3f>*, const parameter_binding<math::Matrix3x3f>*);
template bool Pass::linkUniform<math::Matrix4x4f>(sgl::Uniform<math::Matrix4x4f>*, const parameter_binding<math::Matrix4x4f>*);
template bool Pass::linkUniform<int>(sgl::Uniform<int>*, const parameter_binding<int>*);
template bool Pass::linkUniform<math::Vector2i>(sgl::Uniform<math::Vector2i>*, const parameter_binding<math::Vector2i>*);
template bool Pass::linkUniform<math::Vector3i>(sgl::Uniform<math::Vector3i>*, const parameter_binding<math::Vector3i>*);
template bool Pass::linkUniform<math::Vector4i>(sgl::Uniform<math::Vector4i>*, const parameter_binding<math::Vector4i>*);
template bool Pass::linkSamplerUniform<sgl::Texture2D>(sgl::SamplerUniform<sgl::Texture2D>*, const parameter_binding<sgl::Texture2D>*);
template bool Pass::linkSamplerUniform<sgl::Texture3D>(sgl::SamplerUniform<sgl::Texture3D>*, const parameter_binding<sgl::Texture3D>*);
template bool Pass::linkSamplerUniform<sgl::TextureCube>(sgl::SamplerUniform<sgl::TextureCube>*, const parameter_binding<sgl::TextureCube>*);
} // namespace detail
} // namespace graphics
} // namespace slon
| [
"devnull@localhost"
]
| [
[
[
1,
445
]
]
]
|
944c4cc376be7dc36d6effe5364597ae4900ebef | 74bc09bccf109de71fd3bdd36e5907d54a11dd2d | /Lixo/cTrash.h | ad69dadb4e6203d4f5f883bae190eae0b2cc12ec | []
| no_license | CrociDB/Lixo-no-Lixo | 881c25513f248dc5b81f8b947f2156be9a7f08fc | 1868c05a2c2752c7ec877cbc9bc67675067d97ef | refs/heads/master | 2016-09-06T07:45:21.184909 | 2009-10-12T18:15:24 | 2009-10-12T18:15:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,192 | h | #ifndef _CTRASH_H_
#define _CTRASH_H_
#include <gamespace.h>
#include <windows.h>
#include <math.h>
#include <iostream>
#include <string>
#include <sstream>
#define BAR_X_START 80
#define BAR_X_END 552
#define BAR_MAX_FORCE 12
#define BAR_MIN_FORCE 4
#include "cCan.h"
class cTrash
{
private:
GAMESPACE_VIDEO_HANDLER *gsVideo;
GAMESPACE_INPUT_HANDLER *gsInput;
GAMESPACE_AUDIO_HANDLER *gsAudio;
GS_SPRITE sprite;
GS_SPRITE arrow;
GS_SPRITE bar;
GS_SPRITE sForce;
GS_AUDIO_SAMPLE effect;
cCan *Can;
float x, y;
float sx, sy;
float angle;
int flag_angle;
float time;
float vel;
float velx;
float vely;
float gravity;
float rot_angle;
int side;
int barx;
int vel_force;
bool force;
bool walking;
bool ver;
bool flag_space;
int play;
int points;
public:
cTrash(GAMESPACE_VIDEO_HANDLER *video, GAMESPACE_INPUT_HANDLER *input, GAMESPACE_AUDIO_HANDLER *audio);
void run();
void restart();
int getBarForce(int x);
cCan *getCan() const;
int getX() const;
int getY() const;
int getPoints() const;
bool isWalking() const;
};
#endif | [
"[email protected]"
]
| [
[
[
1,
77
]
]
]
|
8669ca57174e0ecf926f9d905b8f27d144880222 | f12a33df3711392891e10b97ae18f687041e846b | /canon_noir/ModeleCpp/Moteur.cpp | 7708c7596081959836c7ee27560f7898d501ceda | []
| no_license | MilenaKasaka/poocanonnoir | 63e9cc68f0e560dece36f01f28df88a1bd46cbc6 | 04750469ac30fd9f59730c7b93154c3261a74f93 | refs/heads/master | 2020-05-18T06:34:07.996980 | 2011-01-26T18:39:29 | 2011-01-26T18:39:29 | 32,133,754 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,397 | cpp | /**
* \file Moteur.cpp
* \brief Fichier definissant les fonctions de la classe Moteur
* \author Sophie Le Corre
* \author Gregoire Lecourt
* \version 1.0
* \date 26/01/2011
*/
#include "Moteur.h"
Moteur::Moteur() : joueurCourant(0), resLancerDe(make_pair(0,0)), etatCourant(ATTENTE_NB_JOUEURS), premierInit(false), choixPremier(false), ramasseTresor(false), jeuFini(false)
{
initEtats();
}
Moteur::~Moteur()
{
vector<State*>::iterator it;
for(it=etats.begin() ; it!=etats.end(); it++){
delete (*it);
}
}
void Moteur::initEtats()
{
etats.resize(NB_ETATS);
etats[ATTENTE_NB_JOUEURS] = new AttenteNbJoueurs(this);
etats[CHOIX_COULEUR] = new AttenteNbJoueurs(this);
etats[LANCER_DE] = new LancerDe(this);
etats[DEPLACEMENT_BATEAU] = new DeplacementBateau(this);
etats[TIR_CASE_CANON] = new TirCaseCanon(this);
etats[TIR_BORDURE] = new TirBordure(this);
}
void Moteur::initPorts()
{
int i=0;
vector<Joueur>::iterator it;
for(it = joueurs.begin() ; it!=joueurs.end(); it++)
{
(*it).init_port(i);
i++;
}
}
bool Moteur::dispoLancerDe()
{
return (etatCourant == LANCER_DE);
}
bool Moteur::dispoNbJoueurs()
{
return (etatCourant == ATTENTE_NB_JOUEURS);
}
bool Moteur::dispoChoixCouleur()
{
return (etatCourant == CHOIX_COULEUR);
}
bool Moteur::dispoChoixCase()
{
return (etatCourant == DEPLACEMENT_BATEAU);
}
bool Moteur::dispoReglageTir()
{
return ((etatCourant == TIR_CASE_CANON) || (etatCourant == TIR_BORDURE));
}
void Moteur::setRamasseTresor(bool b)
{
ramasseTresor = b;
}
void Moteur::requete()
{
etats[etatCourant]->gerer();
}
void Moteur::setEtatCourant(int etat)
{
etatCourant = etat;
}
void Moteur::setLancerDe(pair<int,int> lancer)
{
resLancerDe = lancer;
}
void Moteur::setPremierInit()
{
premierInit = true;
choixPremier = true;
}
void Moteur::choixPremierFini()
{
choixPremier = false;
}
int Moteur::getNbJoueurs()
{
return joueurs.size();
}
void Moteur::initJoueurs(int size)
{
joueurs.resize(size);
initPorts();
for (int i=0 ; i<size ; i++)
{
joueurs[i].initBateaux(size);
}
this->setEtatCourant(LANCER_DE);
}
Joueur* Moteur::getJoueur(int i)
{
return (&joueurs[i]);
}
Joueur* Moteur::getJoueurCourant()
{
return (&joueurs[joueurCourant]);
}
int Moteur::getNumJoueurCourant()
{
return joueurCourant;
}
void Moteur::setNumJoueurCourant(int i)
{
joueurCourant = i;
}
void Moteur::joueurSuivant()
{
joueurCourant = (joueurCourant + 1) % joueurs.size();
}
vector<pair<int,int> > Moteur::getCooBateaux()
{
vector<pair<int,int> > coo;
vector<Joueur>::iterator it;
for (it = joueurs.begin() ; it!=joueurs.end(); it++)
{
coo.push_back((*it).getPosBateau());
}
return coo;
}
int Moteur::getNbTresors(int joueur)
{
return joueurs[joueur].getNbTresorPort();
}
bool Moteur::getTransporteTresor(int joueur)
{
return joueurs[joueur].getTransporteTresor();
}
pair<int,int> Moteur::getPosPort(int joueur)
{
return joueurs[joueur].getPosPort();
}
Map* Moteur::getMap()
{
return ↦
}
void Moteur::setCasesAccessibles(vector<Case> ca)
{
casesAccessibles = ca;
}
bool Moteur::estAccessible(int x, int y)
{
vector<Case>::iterator it;
/*for (it = casesAccessibles.begin() ; it!=casesAccessibles.end(); it++)
{
if (((*it). == x) && ((*it).second == y))
return true;
}*/
for (it = casesAccessibles.begin() ; it!=casesAccessibles.end(); it++)
{
if (((*it).getCoordonnees().first == x) && ((*it).getCoordonnees().second == y))
return true;
}
return false;
}
TypeBateau Moteur::getTypeBateau()
{
return joueurs[joueurCourant].getTypeBateau();
}
TypeBateau Moteur::getTypeBateau(int joueur)
{
return joueurs[joueur].getTypeBateau();
}
pair<int,int> Moteur::getPosJoueurCourant()
{
return joueurs[joueurCourant].getPosBateau();
}
pair<int,int> Moteur::getPosJoueur(int i)
{
return joueurs[i].getPosBateau();
}
TypeCase Moteur::getTypeCase(int x, int y)
{
return map.getTypeCase(x,y);
}
bool Moteur::contientBateau(Case c)
{
vector<Joueur>::iterator it;
for (it = joueurs.begin() ; it!=joueurs.end(); it++)
{
/*if ( ((*it).getPosBateau().first == x) || ((*it).getPosBateau().second == y) )
return true;*/
if ( (*it).getPosBateau() == c.getCoordonnees() )
return true;
}
return false;
}
void Moteur::deplacerBateau(int x, int y)
{
joueurs[joueurCourant].setPosBateau(x,y);
if (map.getCase(x,y)->getCoordonnees() == joueurs[joueurCourant].getPosPort())
{
if(joueurs[joueurCourant].ramenerTresor())
{
// JEU FINI
}
}
// CASE TRESOR
if ((map.getCase(x,y))->prendreTresor())
{
joueurs[joueurCourant].embarquerTresor();
ramasseTresor = true;
}
else
{
ramasseTresor = false;
}
// CASE CANON
if (map.getTypeCase(x,y) == CANON)
{
setEtatCourant(TIR_CASE_CANON);
}
else
{
joueurSuivant();
setEtatCourant(LANCER_DE);
}
}
void Moteur::reglerTir(int angle, int puissance, pair<int,int> direction)
{
if (etatCourant == TIR_CASE_CANON)
((TirCaseCanon*)etats[TIR_CASE_CANON])->reglerTir(angle,puissance,direction);
else if (etatCourant == TIR_BORDURE)
((TirBordure*)etats[TIR_BORDURE])->reglerTir(angle,puissance,direction);
}
void Moteur::setResTir(bool b)
{
resTir = b;
} | [
"[email protected]@c2238186-79af-eb75-5ca7-4ae61b27dd8b"
]
| [
[
[
1,
276
]
]
]
|
fe5969d1f29ee88fdf4fd207189a1ff9b292e9b1 | 6bdb3508ed5a220c0d11193df174d8c215eb1fce | /Codes/Halak/Internal/WindowsError.h | b18463502b6fe3fdb95b07073b2431880c4feaa7 | []
| no_license | halak/halak-plusplus | d09ba78640c36c42c30343fb10572c37197cfa46 | fea02a5ae52c09ff9da1a491059082a34191cd64 | refs/heads/master | 2020-07-14T09:57:49.519431 | 2011-07-09T14:48:07 | 2011-07-09T14:48:07 | 66,716,624 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 329 | h | #pragma once
#ifndef __HALAK_WINDOWSERROR_H__
#define __HALAK_WINDOWSERROR_H__
# include <Halak/Foundation.h>
# if (defined(HALAK_PLATFORM_WINDOWS))
# include <Halak/String.h>
namespace Halak
{
String GetWindowsErrorMessage(dword errorCode);
}
# endif
#endif | [
"[email protected]"
]
| [
[
[
1,
18
]
]
]
|
a4f55318de6f0e1528b3ed1e8095ea9bed087653 | 70edd0d9185d9ebbd45d1ade0a577b6b9031a6e4 | /GrabCut.cpp | f89f47c28c931becc6c7f11ec641f001a09ec658 | []
| no_license | kunalntpa/graphcut-qt | 67dce8ea44277b72239d80f119f91022a9ad2db7 | a564fee28a73ce16ed9e5bda82f72412bb85879c | refs/heads/master | 2020-12-25T02:30:51.699775 | 2011-11-24T15:48:05 | 2011-11-24T15:48:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,710 | cpp | /*
* GrabCut implementation source code Copyright(c) 2005-2006 Justin Talbot
*
* All Rights Reserved.
* For educational use only; commercial use expressly forbidden.
* NO WARRANTY, express or implied, for this software.
*/
#include "GrabCut.h"
#include <conio.h>
namespace GrabCutNS {
GrabCut::GrabCut( Image<Color>* image )
{
m_image = image;
m_w = m_image->width();
m_h = m_image->height();
m_trimap = new Image<TrimapValue>( m_w, m_h );
m_trimap->fill(TrimapUnknown);
m_GMMcomponent = new Image<unsigned int>( m_w, m_h );
m_hardSegmentation = new Image<SegmentationValue>( m_w, m_h );
m_hardSegmentation->fill(SegmentationBackground);
m_softSegmentation = 0; // Not yet implemented
m_TLinksImage = new Image<Color>(m_w, m_h);
m_TLinksImage->fill(Color(0,0,0));
m_NLinksImage = new Image<Real>(m_w, m_h);
m_NLinksImage->fill(0);
m_GMMImage = new Image<Color>(m_w, m_h);
m_GMMImage->fill(Color(0,0,0));
m_AlphaImage = new Image<Real>(m_w, m_h);
m_AlphaImage->fill(0);
m_foregroundGMM = new GMM(5);
m_backgroundGMM = new GMM(5);
//set some constants
m_lambda = 50;
computeL();
computeBeta();
m_NLinks = new Image<NLinks>( m_w, m_h );
computeNLinks();
m_graph = 0;
m_nodes = new Image<Graph::node_id>( m_w, m_h );
}
GrabCut::~GrabCut()
{
if (m_trimap)
delete m_trimap;
if (m_GMMcomponent)
delete m_GMMcomponent;
if (m_hardSegmentation)
delete m_hardSegmentation;
if (m_softSegmentation)
delete m_softSegmentation;
if (m_foregroundGMM)
delete m_foregroundGMM;
if (m_backgroundGMM)
delete m_backgroundGMM;
if (m_NLinks)
delete m_NLinks;
if (m_nodes)
delete m_nodes;
if (m_TLinksImage)
delete m_TLinksImage;
if (m_NLinksImage)
delete m_NLinksImage;
if (m_GMMImage)
delete m_GMMImage;
if (m_AlphaImage)
delete m_AlphaImage;
}
void GrabCut::initialize(unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2)
{
// Step 1: User creates inital Trimap with rectangle, Background outside, Unknown inside
m_trimap->fill(TrimapBackground);
m_trimap->fillRectangle(x1, y1, x2, y2, TrimapUnknown);
// Step 2: Initial segmentation, Background where Trimap is Background, Foreground where Trimap is Unknown.
m_hardSegmentation->fill(SegmentationBackground);
m_hardSegmentation->fillRectangle(x1, y1, x2, y2, SegmentationForeground);
}
void GrabCut::initializeWithMask(Image<Color>* mask) {
m_trimap->fill(TrimapBackground);
m_hardSegmentation->fill(SegmentationBackground);
for(unsigned int x=0;x<mask->width();x++) {
for(unsigned int y=0;y<mask->height();y++) {
if((*mask)(x,y).b > 0.0 || (*mask)(x,y).g > 0.0 || (*mask)(x,y).r > 0.0) {
(*m_trimap)(x,y) = TrimapUnknown;
(*m_hardSegmentation)(x,y) = SegmentationForeground;
}
}
}
}
void GrabCut::fitGMMs()
{
// Step 3: Build GMMs using Orchard-Bouman clustering algorithm
buildGMMs(*m_backgroundGMM, *m_foregroundGMM, *m_GMMcomponent, *m_image, *m_hardSegmentation);
// Initialize the graph for graphcut (do this here so that the T-Link debugging image will be initialized)
initGraph();
// Build debugging images
buildImages();
}
int GrabCut::refineOnce()
{
Real flow = 0;
// Steps 4 and 5: Learn new GMMs from current segmentation
learnGMMs(*m_backgroundGMM, *m_foregroundGMM, *m_GMMcomponent, *m_image, *m_hardSegmentation);
// Step 6: Run GraphCut and update segmentation
initGraph();
if (m_graph)
flow = m_graph->maxflow();
int changed = updateHardSegmentation();
printf("%d pixels changed segmentation (max flow = %f)\n", changed, flow );
// Build debugging images
buildImages();
return changed;
}
void GrabCut::refine()
{
int changed = m_w*m_h;
while (changed)
changed = refineOnce();
}
int GrabCut::updateHardSegmentation()
{
int changed = 0;
for (unsigned int y = 0; y < m_h; ++y)
{
for (unsigned int x = 0; x < m_w; ++x)
{
SegmentationValue oldValue = (*m_hardSegmentation)(x,y);
if ((*m_trimap)(x,y) == TrimapBackground)
(*m_hardSegmentation)(x,y) = SegmentationBackground;
else if ((*m_trimap)(x,y) == TrimapForeground)
(*m_hardSegmentation)(x,y) = SegmentationForeground;
else // TrimapUnknown
{
if (m_graph->what_segment((*m_nodes)(x,y)) == Graph::SOURCE)
(*m_hardSegmentation)(x,y) = SegmentationForeground;
else
(*m_hardSegmentation)(x,y) = SegmentationBackground;
}
if (oldValue != (*m_hardSegmentation)(x,y))
changed++;
}
}
return changed;
}
void GrabCut::setTrimap(int x1, int y1, int x2, int y2, const TrimapValue& t)
{
(*m_trimap).fillRectangle(x1, y1, x2, y2, t);
// Immediately set the segmentation as well so that the display will update.
if (t == TrimapForeground)
(*m_hardSegmentation).fillRectangle(x1, y1, x2, y2, SegmentationForeground);
else if (t == TrimapBackground)
(*m_hardSegmentation).fillRectangle(x1, y1, x2, y2, SegmentationBackground);
// Build debugging images
//buildImages();
}
//private functions
void GrabCut::initGraph()
{
// Set up the graph (it can only be used once, so we have to recreate it each time the graph is updated)
if (m_graph)
delete m_graph;
m_graph = new Graph();
for (unsigned int y = 0; y < m_h; ++y)
{
for(unsigned int x = 0; x < m_w; ++x)
{
(*m_nodes)(x,y) = m_graph->add_node();
}
}
// Set T-Link weights
for (unsigned int y = 0; y < m_h; ++y)
{
for(unsigned int x = 0; x < m_w; ++x)
{
Real back, fore;
if ((*m_trimap)(x,y) == TrimapUnknown )
{
fore = -log(m_backgroundGMM->p((*m_image)(x,y)));
back = -log(m_foregroundGMM->p((*m_image)(x,y)));
}
else if ((*m_trimap)(x,y) == TrimapBackground )
{
fore = 0;
back = m_L;
}
else // TrimapForeground
{
fore = m_L;
back = 0;
}
m_graph->set_tweights((*m_nodes)(x,y), fore, back);
(*m_TLinksImage)(x,y).r = pow((Real)fore/m_L, (Real)0.25);
(*m_TLinksImage)(x,y).g = pow((Real)back/m_L, (Real)0.25);
}
}
// Set N-Link weights from precomputed values
for (unsigned int y = 0; y < m_h; ++y)
{
for (unsigned int x = 0; x < m_w; ++x)
{
if( x > 0 && y < m_h-1 )
m_graph->add_edge((*m_nodes)(x,y), (*m_nodes)(x-1,y+1), (*m_NLinks)(x,y).upleft, (*m_NLinks)(x,y).upleft);
if( y < m_h-1 )
m_graph->add_edge((*m_nodes)(x,y), (*m_nodes)(x,y+1), (*m_NLinks)(x,y).up, (*m_NLinks)(x,y).up);
if( x < m_w-1 && y < m_h-1 )
m_graph->add_edge((*m_nodes)(x,y), (*m_nodes)(x+1,y+1), (*m_NLinks)(x,y).upright, (*m_NLinks)(x,y).upright);
if( x < m_w-1 )
m_graph->add_edge((*m_nodes)(x,y), (*m_nodes)(x+1,y), (*m_NLinks)(x,y).right, (*m_NLinks)(x,y).right);
}
}
}
void GrabCut::computeNLinks()
{
for( unsigned int y = 0; y < m_h; ++y )
{
for( unsigned int x = 0; x < m_w; ++x )
{
if( x > 0 && y < m_h-1 )
(*m_NLinks)(x,y).upleft = computeNLink( x, y, x-1, y+1 );
if( y < m_h-1 )
(*m_NLinks)(x,y).up = computeNLink( x, y, x, y+1 );
if( x < m_w-1 && y < m_h-1 )
(*m_NLinks)(x,y).upright = computeNLink( x, y, x+1, y+1 );
if( x < m_w-1 )
(*m_NLinks)(x,y).right = computeNLink( x, y, x+1, y );
}
}
}
Real GrabCut::computeNLink(unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2)
{
return m_lambda * exp( -m_beta * distance2((*m_image)(x1,y1),(*m_image)(x2,y2)) ) / distance(x1,y1,x2,y2);
}
void GrabCut::computeBeta()
{
Real result = 0;
int edges = 0;
for (unsigned int y = 0; y < m_h; ++y)
{
for (unsigned int x = 0; x < m_w; ++x)
{
if (x > 0 && y < m_h-1) // upleft
{
result += distance2( (*m_image)(x,y), (*m_image)(x-1,y+1) );
edges++;
}
if (y < m_h-1) // up
{
result += distance2( (*m_image)(x,y), (*m_image)(x,y+1) );
edges++;
}
if (x < m_w-1 && y < m_h-1) // upright
{
result += distance2( (*m_image)(x,y), (*m_image)(x+1,y+1) );
edges++;
}
if (x < m_w-1) // right
{
result += distance2( (*m_image)(x,y), (*m_image)(x+1,y) );
edges++;
}
}
}
m_beta = (Real)(1.0/(2*result/edges));
}
void GrabCut::computeL()
{
m_L = 8*m_lambda + 1;
}
void GrabCut::buildImages()
{
m_NLinksImage->fill(0);
for (unsigned int y = 0; y < m_h; ++y)
{
for (unsigned int x = 0; x < m_w; ++x)
{
// T-Links image is populated in initGraph since we have easy access to the link values there.
// N-Links image
if( x > 0 && y < m_h-1 )
{
(*m_NLinksImage)(x,y) += (*m_NLinks)(x,y).upleft/m_L;
(*m_NLinksImage)(x-1,y+1) += (*m_NLinks)(x,y).upleft/m_L;
}
if( y < m_h-1 )
{
(*m_NLinksImage)(x,y) += (*m_NLinks)(x,y).up/m_L;
(*m_NLinksImage)(x,y+1) += (*m_NLinks)(x,y).up/m_L;
}
if( x < m_w-1 && y < m_h-1 )
{
(*m_NLinksImage)(x,y) += (*m_NLinks)(x,y).upright/m_L;
(*m_NLinksImage)(x+1,y+1) += (*m_NLinks)(x,y).upright/m_L;
}
if( x < m_w-1 )
{
(*m_NLinksImage)(x,y) += (*m_NLinks)(x,y).right/m_L;
(*m_NLinksImage)(x+1,y) += (*m_NLinks)(x,y).right/m_L;
}
// GMM image
if ((*m_hardSegmentation)(x,y) == SegmentationForeground)
(*m_GMMImage)(x,y) = Color((Real)((*m_GMMcomponent)(x,y)+1)/m_foregroundGMM->K(),0,0);
else
(*m_GMMImage)(x,y) = Color(0,(Real)((*m_GMMcomponent)(x,y)+1)/m_backgroundGMM->K(),0);
//Alpha image
if ((*m_hardSegmentation)(x,y) == SegmentationForeground)
(*m_AlphaImage)(x,y) = 0.0;
else
(*m_AlphaImage)(x,y) = 0.75;
}
}
}
} | [
"[email protected]"
]
| [
[
[
1,
377
]
]
]
|
5daa54197591a3e7dcc601d81e7292a348053729 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/spirit/test/symbols_add_null.cpp | f0daca1d6a6445c6b9f44fd2e8dcacb4016faa25 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,841 | cpp | /*=============================================================================
Copyright (c) 2004 Joao Abecasis
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)
=============================================================================*/
#define BOOST_SPIRIT_ASSERT_EXCEPTION ::spirit_exception
struct spirit_exception
{
spirit_exception(char const * msg)
: message(msg)
{
}
char const * message;
};
#include <boost/spirit/core/scanner/scanner.hpp>
#include <boost/spirit/symbols/impl/tst.ipp>
#include <boost/utility/addressof.hpp>
#include <boost/detail/lightweight_test.hpp>
typedef char char_type;
typedef char const * iterator;
char_type data_[] = "whatever";
iterator begin = data_;
iterator end = data_
+ sizeof(data_)/sizeof(char_type); // Yes, this is an intentional bug ;)
char_type data2_[] = "\0something";
iterator begin2 = data2_;
iterator end2 = data2_ + sizeof(data2_)/sizeof(char_type) - 1;
int main()
{
typedef boost::spirit::scanner<> scanner;
typedef boost::spirit::impl::tst<void *, char_type> symbols;
symbols symbols_;
try
{
// It is not ok to add strings containing the null character.
symbols_.add(begin, end, (void*) boost::addressof(symbols_));
BOOST_TEST(0);
}
catch (spirit_exception &e)
{
}
try
{
// It is not ok to add strings containing the null character.
symbols_.add(begin2, end2, (void*) boost::addressof(symbols_));
BOOST_TEST(0);
}
catch (spirit_exception &e)
{
}
return boost::report_errors();
}
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
68
]
]
]
|
bcd3db4a5c4564e3cfc08aa5a7f0928d6f1028a5 | cfc9acc69752245f30ad3994cce0741120e54eac | /bikini/private/source/system/ticker.cpp | 77dabd274bef3db8f2bef7d5ea039c4e62ed661a | []
| no_license | Heartbroken/bikini-iii | 3b7852d1af722b380864ac87df57c37862eb759b | 93ffa5d43d9179b7c5e7f7c2df9df7dafd79a739 | refs/heads/master | 2020-03-28T00:41:36.281253 | 2009-04-30T14:58:10 | 2009-04-30T14:58:10 | 37,190,689 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,037 | cpp | /*---------------------------------------------------------------------------------------------*//*
Binary Kinematics 3 - C++ Game Programming Library
Copyright (C) 2008 Viktor Reutzky
[email protected]
*//*---------------------------------------------------------------------------------------------*/
#include "header.hpp"
namespace bk { /*--------------------------------------------------------------------------------*/
// ticker
ticker::ticker(real _period) : m_period(_period), m_run(true), m_sync(false, false), m_task(*this, &ticker::m_proc, THREAD_PRIORITY_TIME_CRITICAL) {
m_task.run();
}
ticker::~ticker() {
m_run = false;
m_task.wait();
}
real ticker::period() {
return m_period;
}
void ticker::set_period(real _period) {
m_period = _period;
}
void ticker::sync() {
m_sync.wait();
}
void ticker::m_proc() {
while(m_run) {
sleep(m_period);
m_sync.set();
}
}
} /* namespace bk -------------------------------------------------------------------------------*/
| [
"my.mass.storage@f4697e32-284f-0410-9ba2-936c71724aef"
]
| [
[
[
1,
38
]
]
]
|
0b80459079a35f1eb0abc5db0552f151376c101b | c2153dcfa8bcf5b6d7f187e5a337b904ad9f91ac | /depends/ClanLib/src/Core/CSS/css_selector.h | ffc0590899a9fd7298e5194724432a13e5fe0643 | []
| no_license | ptrefall/smn6200fluidmechanics | 841541a26023f72aa53d214fe4787ed7f5db88e1 | 77e5f919982116a6cdee59f58ca929313dfbb3f7 | refs/heads/master | 2020-08-09T17:03:59.726027 | 2011-01-13T22:39:03 | 2011-01-13T22:39:03 | 32,448,422 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,632 | h | /*
** ClanLib SDK
** Copyright (c) 1997-2010 The ClanLib Team
**
** This software is provided 'as-is', without any express or implied
** warranty. In no event will the authors be held liable for any damages
** arising from the use of this software.
**
** Permission is granted to anyone to use this software for any purpose,
** including commercial applications, and to alter it and redistribute it
** freely, subject to the following restrictions:
**
** 1. The origin of this software must not be misrepresented; you must not
** claim that you wrote the original software. If you use this software
** in a product, an acknowledgment in the product documentation would be
** appreciated but is not required.
** 2. Altered source versions must be plainly marked as such, and must not be
** misrepresented as being the original software.
** 3. This notice may not be removed or altered from any source distribution.
**
** Note: Some of the libraries ClanLib may link to may have additional
** requirements or restrictions.
**
** File Author(s):
**
** Magnus Norddahl
*/
#pragma once
class CL_CSSSelector
{
public:
std::vector<CL_String> path_elements;
bool select(const std::vector<CL_StringRef> &match_path, int &specificity) const;
bool operator ==(const CL_CSSSelector &other) const;
static CL_StringRef get_type(const CL_StringRef &path_element);
static CL_StringRef get_class(const CL_StringRef &path_element);
static CL_StringRef get_id(const CL_StringRef &path_element);
static CL_StringRef get_state(const CL_StringRef &path_element);
};
| [
"[email protected]@c628178a-a759-096a-d0f3-7c7507b30227"
]
| [
[
[
1,
43
]
]
]
|
5b100cfa9fdd23f4ef80d217657c16a982f9a95d | 2112057af069a78e75adfd244a3f5b224fbab321 | /branches/refactor/src_root/include/common/OgreTypes/asm_math.h | 8d56037c7bb0fecff7bb644486c8d30ed344e453 | []
| no_license | blockspacer/ireon | 120bde79e39fb107c961697985a1fe4cb309bd81 | a89fa30b369a0b21661c992da2c4ec1087aac312 | refs/heads/master | 2023-04-15T00:22:02.905112 | 2010-01-07T20:31:07 | 2010-01-07T20:31:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,705 | h | #ifndef __asm_math_H__
#define __asm_math_H__
#include "OgrePrerequisites.h"
/*=============================================================================
ASM math routines posted by davepermen et al on flipcode forums
=============================================================================*/
const float pi = 4.0 * atan( 1.0 );
const float half_pi = 0.5 * pi;
/*=============================================================================
NO EXPLICIT RETURN REQUIRED FROM THESE METHODS!!
=============================================================================*/
#if OGRE_COMPILER == OGRE_COMPILER_MSVC
# pragma warning( push )
# pragma warning( disable: 4035 )
#endif
float asm_arccos( float r ) {
// return half_pi + arctan( r / -sqr( 1.f - r * r ) );
#if OGRE_COMPILER == OGRE_COMPILER_MSVC
float asm_one = 1.f;
float asm_half_pi = half_pi;
__asm {
fld r // r0 = r
fld r // r1 = r0, r0 = r
fmul r // r0 = r0 * r
fsubr asm_one // r0 = r0 - 1.f
fsqrt // r0 = sqrtf( r0 )
fchs // r0 = - r0
fdiv // r0 = r1 / r0
fld1 // {{ r0 = atan( r0 )
fpatan // }}
fadd asm_half_pi // r0 = r0 + pi / 2
} // returns r0
#elif OGRE_COMPILER == OGRE_COMPILER_GNUC
return float( acos( r ) );
#endif
}
float asm_arcsin( float r ) {
// return arctan( r / sqr( 1.f - r * r ) );
#if OGRE_COMPILER == OGRE_COMPILER_MSVC
const float asm_one = 1.f;
__asm {
fld r // r0 = r
fld r // r1 = r0, r0 = r
fmul r // r0 = r0 * r
fsubr asm_one // r0 = r0 - 1.f
fsqrt // r0 = sqrtf( r0 )
fdiv // r0 = r1 / r0
fld1 // {{ r0 = atan( r0 )
fpatan // }}
} // returns r0
#elif OGRE_COMPILER == OGRE_COMPILER_GNUC
return float( asin( r ) );
#endif
}
float asm_arctan( float r ) {
#if OGRE_COMPILER == OGRE_COMPILER_MSVC
__asm {
fld r // r0 = r
fld1 // {{ r0 = atan( r0 )
fpatan // }}
} // returns r0
#elif OGRE_COMPILER == OGRE_COMPILER_GNUC
return float( atan( r ) );
#endif
}
float asm_sin( float r ) {
#if OGRE_COMPILER == OGRE_COMPILER_MSVC
__asm {
fld r // r0 = r
fsin // r0 = sinf( r0 )
} // returns r0
#elif OGRE_COMPILER == OGRE_COMPILER_GNUC
return sin( r );
#endif
}
float asm_cos( float r ) {
#if OGRE_COMPILER == OGRE_COMPILER_MSVC
__asm {
fld r // r0 = r
fcos // r0 = cosf( r0 )
} // returns r0
#elif OGRE_COMPILER == OGRE_COMPILER_GNUC
return cos( r );
#endif
}
float asm_tan( float r ) {
#if OGRE_COMPILER == OGRE_COMPILER_MSVC
// return sin( r ) / cos( r );
__asm {
fld r // r0 = r
fsin // r0 = sinf( r0 )
fld r // r1 = r0, r0 = r
fcos // r0 = cosf( r0 )
fdiv // r0 = r1 / r0
} // returns r0
#elif OGRE_COMPILER == OGRE_COMPILER_GNUC
return tan( r );
#endif
}
// returns a for a * a = r
float asm_sqrt( float r )
{
#if OGRE_COMPILER == OGRE_COMPILER_MSVC
__asm {
fld r // r0 = r
fsqrt // r0 = sqrtf( r0 )
} // returns r0
#elif OGRE_COMPILER == OGRE_COMPILER_GNUC
return sqrt( r );
#endif
}
// returns 1 / a for a * a = r
// -- Use this for Vector normalisation!!!
float asm_rsq( float r )
{
#if OGRE_COMPILER == OGRE_COMPILER_MSVC
__asm {
fld1 // r0 = 1.f
fld r // r1 = r0, r0 = r
fsqrt // r0 = sqrtf( r0 )
fdiv // r0 = r1 / r0
} // returns r0
#elif OGRE_COMPILER == OGRE_COMPILER_GNUC
return 1. / sqrt( r );
#endif
}
// returns 1 / a for a * a = r
// Another version
float apx_rsq( float r ) {
#if OGRE_COMPILER == OGRE_COMPILER_MSVC
const float asm_dot5 = 0.5f;
const float asm_1dot5 = 1.5f;
__asm {
fld r // r0 = r
fmul asm_dot5 // r0 = r0 * .5f
mov eax, r // eax = r
shr eax, 0x1 // eax = eax >> 1
neg eax // eax = -eax
add eax, 0x5F400000 // eax = eax & MAGICAL NUMBER
mov r, eax // r = eax
fmul r // r0 = r0 * r
fmul r // r0 = r0 * r
fsubr asm_1dot5 // r0 = 1.5f - r0
fmul r // r0 = r0 * r
} // returns r0
#elif OGRE_COMPILER == OGRE_COMPILER_GNUC
return 1. / sqrt( r );
#endif
}
/* very MS-specific, commented out for now
Finally the best InvSqrt implementation?
Use for vector normalisation instead of 1/length() * x,y,z
*/
#if OGRE_COMPILER == OGRE_COMPILER_MSVC
__declspec(naked) float __fastcall InvSqrt(float fValue)
{
__asm
{
mov eax, 0be6eb508h
mov dword ptr[esp-12],03fc00000h
sub eax, dword ptr[esp + 4]
sub dword ptr[esp+4], 800000h
shr eax, 1
mov dword ptr[esp - 8], eax
fld dword ptr[esp - 8]
fmul st, st
fld dword ptr[esp - 8]
fxch st(1)
fmul dword ptr[esp + 4]
fld dword ptr[esp - 12]
fld st(0)
fsub st,st(2)
fld st(1)
fxch st(1)
fmul st(3),st
fmul st(3),st
fmulp st(4),st
fsub st,st(2)
fmul st(2),st
fmul st(3),st
fmulp st(2),st
fxch st(1)
fsubp st(1),st
fmulp st(1), st
ret 4
}
}
#endif
// returns a random number
FORCEINLINE float asm_rand()
{
#if OGRE_COMPILER == OGRE_COMPILER_MSVC
#if 0
#if OGRE_COMP_VER >= 1300
static unsigned __int64 q = time( NULL );
_asm {
movq mm0, q
// do the magic MMX thing
pshufw mm1, mm0, 0x1E
paddd mm0, mm1
// move to integer memory location and free MMX
movq q, mm0
emms
}
return float( q );
#endif
#else
// VC6 does not support pshufw
return float( rand() );
#endif
#else
// GCC etc
return float( rand() );
#endif
}
// returns the maximum random number
FORCEINLINE float asm_rand_max()
{
#if OGRE_COMPILER == OGRE_COMPILER_MSVC
#if 0
#if OGRE_COMP_VER >= 1300
return std::numeric_limits< unsigned __int64 >::max();
return 9223372036854775807.0f;
#endif
#else
// VC6 does not support unsigned __int64
return float( RAND_MAX );
#endif
#else
// GCC etc
return float( RAND_MAX );
#endif
}
// returns log2( r ) / log2( e )
float asm_ln( float r ) {
#if OGRE_COMPILER == OGRE_COMPILER_MSVC
const float asm_e = 2.71828182846f;
const float asm_1_div_log2_e = .693147180559f;
const float asm_neg1_div_3 = -.33333333333333333333333333333f;
const float asm_neg2_div_3 = -.66666666666666666666666666667f;
const float asm_2 = 2.f;
int log_2 = 0;
__asm {
// log_2 = ( ( r >> 0x17 ) & 0xFF ) - 0x80;
mov eax, r
sar eax, 0x17
and eax, 0xFF
sub eax, 0x80
mov log_2, eax
// r = ( r & 0x807fffff ) + 0x3f800000;
mov ebx, r
and ebx, 0x807FFFFF
add ebx, 0x3F800000
mov r, ebx
// r = ( asm_neg1_div_3 * r + asm_2 ) * r + asm_neg2_div_3; // (1)
fld r
fmul asm_neg1_div_3
fadd asm_2
fmul r
fadd asm_neg2_div_3
fild log_2
fadd
fmul asm_1_div_log2_e
}
#elif OGRE_COMPILER == OGRE_COMPILER_GNUC
return log( r );
#endif
}
#if OGRE_COMPILER == OGRE_COMPILER_MSVC
# pragma warning( pop )
#endif
#endif
| [
"[email protected]"
]
| [
[
[
1,
365
]
]
]
|
0f5a0532337006cf373420ee36695489c912b26e | d425cf21f2066a0cce2d6e804bf3efbf6dd00c00 | /Tactical/Items.cpp | e4d71b66a5e90f04da985cfafca80c7764147ba7 | []
| 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 | 449,371 | cpp | #ifdef PRECOMPILEDHEADERS
#include "Tactical All.h"
#else
#include "items.h"
#include "Action Items.h"
#include "weapons.h"
#include "Interface Cursors.h"
#include "Soldier Control.h"
#include "overhead.h"
#include "Handle UI.h"
#include "Animation Control.h"
#include "points.h"
#include "Sound Control.h"
#include "Sys globals.h"
#include "Isometric Utils.h"
#include "Animation Data.h"
#include "worldman.h"
#include "Random.h"
#include "Campaign.h"
#include "interface.h"
#include "interface panels.h"
#include "explosion control.h"
#include "Keys.h"
#include "faces.h"
#include "wcheck.h"
#include "soldier profile.h"
#include "SkillCheck.h"
#include "los.h"
#include "message.h"
#include "text.h"
#include "fov.h"
#include "MessageBoxScreen.h"
#include "PathAIDebug.h"
#include "Interface Control.h"
#include "ShopKeeper Interface.h"
#include "Cursors.h"
#include "GameSettings.h"
#include "environment.h"
#include "Auto Resolve.h"
#include "Interface Items.h"
#include "Campaign Types.h"
#include "history.h"
#include "Game Clock.h"
#include "strategicmap.h"
#include "Inventory Choosing.h"
#include "Soldier macros.h"
#include "Smell.h"
#include "lighting.h"
#include "utilities.h"
#include "english.h"
#include "debug control.h"
#include "math.h"
#endif
#ifdef JA2UB
#include "Ja25_Tactical.h"
#include "Ja25 Strategic Ai.h"
#endif
//forward declarations of common classes to eliminate includes
class OBJECTTYPE;
class SOLDIERTYPE;
#define ANY_MAGSIZE 65535
void SetNewItem( SOLDIERTYPE *pSoldier, UINT8 ubInvPos, BOOLEAN fNewItem );
extern SOLDIERTYPE *gpItemDescSoldier;
extern BOOLEAN fShowMapInventoryPool;
extern UINT32 guiCurrentItemDescriptionScreen;
extern BOOLEAN AutoPlaceObjectInInventoryStash( OBJECTTYPE *pItemPtr, INT32 sGridNo );
UINT16 OldWayOfCalculatingScopeBonus(SOLDIERTYPE *pSoldier);
// weight units are 100g each
////////////////////////////////////////////////////////////////////////////
//ATE: When adding new items, make sure to update text.c with text description
///////////////////////////////////////////////////////////////////////////
INVTYPE Item[MAXITEMS]; //=
//{
//// CLASS SOUND GRPH GRA- PER
////CLASS INDEX CURSOR TYPE TYPE PHIC WT PCKT PRICE COOL DESCRIPTION REL REPAIR FLAGS
////--------- ----- ------- ------- ---- -- -- ---- ----- ---- ----------- --- ------ -----
//{ IC_PUNCH, 0, PUNCHCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, ITEM_NOT_BUYABLE , 0, "Nothing"},
////---WEAPONS---
//// NB For convenience, in accessing the Weapons table, the class index
//// of a weapon must be equal to its position in the Item table
//{ IC_GUN, 1, TARGETCURS, CONDBUL, 0, 1, 6, 1, 350, 2, /* Glock 17 */ +2, +2, IF_STANDARD_GUN },
//{ IC_GUN, 2, TARGETCURS, CONDBUL, 0, 2, 6, 1, 480, 2, /* Glock 18 */ +1, +1, IF_STANDARD_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 3, TARGETCURS, CONDBUL, 0, 3, 11, 1, 450, 2, /* Beretta 92F */ -1, -1, IF_STANDARD_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 4, TARGETCURS, CONDBUL, 0, 4, 11, 1, 470, 2, /* Beretta 93R */ -2, -2, IF_STANDARD_GUN },
//{ IC_GUN, 5, TARGETCURS, CONDBUL, 0, 5, 11, 1, 250, 1, /* .38 S&W Special */ +4, +4, IF_STANDARD_GUN },
//{ IC_GUN, 6, TARGETCURS, CONDBUL, 0, 6, 10, 1, 300, 1, /* .357 Barracuda */ +3, +3, IF_STANDARD_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 7, TARGETCURS, CONDBUL, 0, 7, 17, 1, 300, 1, /* .357 DesertEagle*/ -1, -1, IF_STANDARD_GUN },
//{ IC_GUN, 8, TARGETCURS, CONDBUL, 0, 8, 11, 1, 400, 2, /* .45 M1911 */ 0, 0, IF_STANDARD_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 9, TARGETCURS, CONDBUL, 0, 9, 21, 0, 980, 3, /* H&K MP5K */ -1, 0, IF_STANDARD_GUN},
//{ IC_GUN, 10, TARGETCURS, CONDBUL, 0, 10, 28, 0, 1170, 4, /* .45 MAC-10 */ -2, -1, IF_STANDARD_GUN },
//
//{ IC_GUN, 11, TARGETCURS, CONDBUL, 0, 11, 48, 0, 700, 3, /* Thompson M1A1 */ +3, -3, IF_TWOHANDED_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 12, TARGETCURS, CONDBUL, 0, 12, 26, 0, 1330, 5, /* Colt Commando */ 0, -1, IF_TWOHANDED_GUN },
//{ IC_GUN, 13, TARGETCURS, CONDBUL, 0, 13, 28, 0, 1000, 4, /* H&K MP53 */ -1, -1, IF_TWOHANDED_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 14, TARGETCURS, CONDBUL, 0, 14, 39, 0, 1180, 4, /* AKSU-74 */ -2, -1, IF_TWOHANDED_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 15, TARGETCURS, CONDBUL, 0, 15, 28, 0, 2750, 10, /* 5.7mm FN P90 */ -2, -4, IF_STANDARD_GUN },
//{ IC_GUN, 16, TARGETCURS, CONDBUL, 0, 16, 19, 0, 620, 3, /* Type-85 */ -4, +2, IF_TWOHANDED_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 17, TARGETCURS, CONDBUL, 0, 17, 39, 0, 1350, 5, /* SKS */ -4, -2, IF_TWOHANDED_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 18, TARGETCURS, CONDBUL, 0, 18, 43, 0, 1930, 6, /* Dragunov */ +2, +2, IF_TWOHANDED_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 19, TARGETCURS, CONDBUL, 0, 19, 55, 0, 1950, 6, /* M24 */ +4, +4, IF_TWOHANDED_GUN },
//{ IC_GUN, 20, TARGETCURS, CONDBUL, 0, 20, 36, 0, 2380, 8, /* Steyr AUG */ +1, -2, IF_TWOHANDED_GUN | ITEM_BIGGUNLIST },
//
//{ IC_GUN, 21, TARGETCURS, CONDBUL, 0, 21, 41, 0, 1620, 6, /* H&K G41 */ +1, -1, IF_TWOHANDED_GUN },
//{ IC_GUN, 22, TARGETCURS, CONDBUL, 0, 22, 29, 0, 1100, 4, /* Ruger Mini-14 */ 0, -1, IF_TWOHANDED_GUN },
//{ IC_GUN, 23, TARGETCURS, CONDBUL, 0, 23, 36, 0, 2680, 8, /* C-7 */ -1, -1, IF_TWOHANDED_GUN },
//{ IC_GUN, 24, TARGETCURS, CONDBUL, 0, 24, 36, 0, 1970, 7, /* FA-MAS */ -2, -2, IF_TWOHANDED_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 25, TARGETCURS, CONDBUL, 0, 25, 36, 0, 1830, 6, /* AK-74 */ -1, -2, IF_TWOHANDED_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 26, TARGETCURS, CONDBUL, 0, 26, 43, 0, 1450, 5, /* AKM */ +2, +2, IF_TWOHANDED_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 27, TARGETCURS, CONDBUL, 0, 27, 29, 0, 2120, 7, /* M-14 */ +1, -1, IF_TWOHANDED_GUN },
//{ IC_GUN, 28, TARGETCURS, CONDBUL, 0, 28, 43, 0, 2680, 8, /* FN-FAL */ 0, -1, IF_TWOHANDED_GUN },
//{ IC_GUN, 29, TARGETCURS, CONDBUL, 0, 29, 44, 0, 1570, 5, /* H&K G3A3 */ +1, -1, IF_TWOHANDED_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 30, TARGETCURS, CONDBUL, 0, 30, 38, 0, 2530, 8, /* H&K G11 */ +3, -4, IF_TWOHANDED_GUN },
//
//{ IC_GUN, 31, TARGETCURS, CONDBUL, 0, 31, 36, 0, 670, 3, /* Remington M870 */ +3, +3, IF_TWOHANDED_GUN },
//{ IC_GUN, 32, TARGETCURS, CONDBUL, 0, 32, 38, 0, 980, 4, /* SPAS-15 */ -2, -2, IF_TWOHANDED_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 33, TARGETCURS, CONDBUL, 0, 33, 41, 0, 2900, 9, /* CAWS */ -3, -3, IF_TWOHANDED_GUN },
//{ IC_GUN, 34, TARGETCURS, CONDBUL, 0, 34, 68, 0, 3100, 10, /* FN Minimi */ -1, -2, IF_TWOHANDED_GUN },
//{ IC_GUN, 35, TARGETCURS, CONDBUL, 0, 35, 48, 0, 3180, 10, /* RPK-74 */ -1, -2, IF_TWOHANDED_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 36, TARGETCURS, CONDBUL, 0, 36, 93, 0, 3420, 10, /* H&K 21E */ +2, +1, IF_TWOHANDED_GUN | ITEM_BIGGUNLIST },
//{ IC_BLADE, 37, KNIFECURS, 0, 1, 79, 9, 2, 100, 2, /* combat knife */ +2, +2, IF_STANDARD_BLADE},
//{ IC_THROWING_KNIFE,38, TARGETCURS, 0, 1, 53, 1, 4, 50, 3, /* throwing knife */ -1, -1, IF_STANDARD_BLADE},
//{ IC_THROWN, 39, TOSSCURS, 0, 1, 57, 5, 2, 0, 0, /* rock */ 0, 0, ITEM_NOT_BUYABLE},
//{ IC_LAUNCHER, 40, TRAJECTORYCURS, 0, 0, 37, 26, 0, 900, 7, /* grenade launcher*/ 0, -1, IF_TWOHANDED_GUN },
//
//{ IC_LAUNCHER, 41, TRAJECTORYCURS, 0, 0, 0, 77, 0, 1800, 10, /* mortar */ 0, -2, IF_TWOHANDED_GUN},
//{ IC_THROWN, 42, TOSSCURS, 0, 1, 60, 4, 3, 0, 0, /* another rock */ 0, 0, ITEM_NOT_BUYABLE},
//{ IC_BLADE, 43, KNIFECURS, 0, 0, 0, 0, 1, 0, 0, /* yng male claws */ 0, 0, ITEM_NOT_BUYABLE | ITEM_NOT_EDITOR | ITEM_DEFAULT_UNDROPPABLE },
//{ IC_BLADE, 44, KNIFECURS, 0, 0, 0, 0, 1, 0, 0, /* yng fem claws */ 0, 0, ITEM_NOT_BUYABLE | ITEM_NOT_EDITOR | ITEM_DEFAULT_UNDROPPABLE },
//{ IC_BLADE, 45, KNIFECURS, 0, 0, 0, 0, 1, 0, 0, /* old male claws */ 0, 0, ITEM_NOT_BUYABLE | ITEM_NOT_EDITOR | ITEM_DEFAULT_UNDROPPABLE },
//{ IC_BLADE, 46, KNIFECURS, 0, 0, 0, 0, 1, 0, 0, /* old fem claws */ 0, 0, ITEM_NOT_BUYABLE | ITEM_NOT_EDITOR | ITEM_DEFAULT_UNDROPPABLE },
//{ IC_TENTACLES, 47, KNIFECURS, 0, 0, 0, 0, 1, 0, 0, /* queen tentacles*/ 0, 0, ITEM_NOT_BUYABLE | ITEM_NOT_EDITOR | ITEM_DEFAULT_UNDROPPABLE },
//{ IC_GUN, 48, TARGETCURS, 0, 0, 0, 0, 1, 0, 0, /* queen spit */ 0, 0, ITEM_NOT_BUYABLE | ITEM_NOT_EDITOR | ITEM_DEFAULT_UNDROPPABLE },
//{ IC_PUNCH, 49, PUNCHCURS, 0, 1, 102, 1, 4, 20, 2, /* brass knuckles */ 0, 0, IF_STANDARD_BLADE },
//{ IC_LAUNCHER, 50, INVALIDCURS,0, 0, 39, 13, 0, 500, 8, /* underslung g.l.*/ 0, 0, IF_STANDARD_GUN},
//
//{ IC_GUN, 51, TARGETCURS, 0, 0, 38, 21, 0, 500, 9, /* rocket Launcher*/ 0, -3, IF_TWOHANDED_GUN }, // now repairable
//{ IC_BLADE, 52, KNIFECURS, 0, 0, 0, 0, 1, 0, 0, /* bloodcat claws*/ 0, 0, ITEM_NOT_BUYABLE | ITEM_NOT_EDITOR | ITEM_DEFAULT_UNDROPPABLE },
//{ IC_BLADE, 53, KNIFECURS, 0, 0, 0, 0, 1, 0, 0, /* bloodcat bite */ 0, 0, ITEM_NOT_BUYABLE | ITEM_NOT_EDITOR | ITEM_DEFAULT_UNDROPPABLE },
//{ IC_BLADE, 54, KNIFECURS, 0, 0, 41, 13, 0, 200, 3, /* machete */ 0, +3, IF_STANDARD_BLADE},
//{ IC_GUN, 55, TARGETCURS, 0, 0, 45, 40, 0, 5000, 10, /* rocket rifle */ 0, -5, IF_TWOHANDED_GUN | ITEM_ELECTRONIC },
//{ IC_GUN, 56, TARGETCURS, 0, 0, 40, 12, 0, 1000, 0, /* Automag III */ 0, -2, IF_STANDARD_GUN },
//{ IC_GUN, 57, TARGETCURS, 0, 0, 0, 0, 0, 0, 0, /* infant spit */ 0, 0, ITEM_NOT_BUYABLE | ITEM_NOT_EDITOR | ITEM_DEFAULT_UNDROPPABLE },
//{ IC_GUN, 58, TARGETCURS, 0, 0, 0, 0, 0, 0, 0, /* yng male spit */ 0, 0, ITEM_NOT_BUYABLE | ITEM_NOT_EDITOR | ITEM_DEFAULT_UNDROPPABLE },
//
//{ IC_GUN, 59, TARGETCURS, 0, 0, 0, 0, 0, 0, 0, /* old male spit */ 0, 0, ITEM_NOT_BUYABLE | ITEM_NOT_EDITOR | ITEM_DEFAULT_UNDROPPABLE },
//{ IC_GUN, 60, TARGETCURS, 0, 0, 37, 26, 0, 0, 0, /* tank cannon */ 0, 0, ITEM_NOT_BUYABLE },
//
//{ IC_GUN, 61, TARGETCURS, 0, 0, 46, 12, 1, 500, 5, /* dart gun */ 0, +3, IF_STANDARD_GUN },
//{ IC_THROWING_KNIFE,62, TARGETCURS, 0, 1, 95, 1, 4, 50, 0, /*bloody throw.knife*/0, +4, IF_STANDARD_BLADE | ITEM_NOT_BUYABLE },
//{ IC_GUN, 63, TARGETCURS, 0, 0, 48, 18, 0, 0, 0, /* flamethrower */ 0, 0, IF_STANDARD_GUN },
//{ IC_PUNCH, 64, PUNCHCURS, 0, 1, 85, 30, 0, 40, 1, /* Crowbar */ 0, -4, ITEM_METAL | ITEM_DAMAGEABLE },
//{ IC_GUN, 65, TARGETCURS, 0, 0, 45, 40, 0, 10000, 10, /* rocket rifle */ 0, -5, IF_TWOHANDED_GUN | ITEM_ELECTRONIC },
//// MADD MARKER
//{ IC_GUN, 66, TARGETCURS, CONDBUL, 0, 55, 122,0, 6200, 10, /* Barrett */ +1, -1, IF_TWOHANDED_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 67, TARGETCURS, CONDBUL, 0, 56, 25, 0, 4100, 9, /* VAL Silent */ -3, -3, IF_TWOHANDED_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 68, TARGETCURS, CONDBUL, 0, 57, 80, 0, 2700, 8, /* PSG */ +4, +4, IF_TWOHANDED_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 69, TARGETCURS, CONDBUL, 0, 58, 24, 0, 2100, 8, /* TAR 21 */ +3, -1, IF_TWOHANDED_GUN | ITEM_BIGGUNLIST },
////MAX WEAPONS spot
//{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
////---AMMO---
//{ IC_AMMO, 0, INVALIDCURS, 0, 1, 32, 2, 8, 15, 2, /* CLIP9_15 */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 1, INVALIDCURS, 0, 1, 35, 3, 4, 30, 4, /* CLIP9_30 */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 2, INVALIDCURS, 0, 1, 33, 2, 8, 45, 4, /* CLIP9_15_AP */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 3, INVALIDCURS, 0, 1, 36, 3, 4, 90, 6, /* CLIP9_30_AP */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 4, INVALIDCURS, 0, 1, 34, 2, 8, 30, 3, /* CLIP9_15_HP */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 5, INVALIDCURS, 0, 1, 37, 3, 4, 60, 5, /* CLIP9_30_HP */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 6, INVALIDCURS, 0, 1, 24, 1, 8, 5, 1, /* CLIP38_6 */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 7, INVALIDCURS, 0, 1, 25, 1, 8, 15, 3, /* CLIP38_6_AP */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 8, INVALIDCURS, 0, 1, 26, 1, 8, 10, 2, /* CLIP38_6_HP */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 9, INVALIDCURS, 0, 1, 14, 2, 8, 10, 2, /* CLIP45_7 */ 0, 0, IF_STANDARD_CLIP},
//
//{ IC_AMMO, 10, INVALIDCURS, 0, 1, 4, 10, 4, 45, 3, /* CLIP45_30 */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 11, INVALIDCURS, 0, 1, 15, 2, 8, 45, 4, /* CLIP45_7_AP */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 12, INVALIDCURS, 0, 1, 5, 10, 4, 135, 5, /* CLIP45_30_AP */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 13, INVALIDCURS, 0, 1, 16, 2, 8, 30, 3, /* CLIP45_7_HP */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 14, INVALIDCURS, 0, 1, 6, 10, 4, 90, 4, /* CLIP45_30_HP */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 15, INVALIDCURS, 0, 1, 11, 1, 8, 10, 1, /* CLIP357_6 */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 16, INVALIDCURS, 0, 1, 17, 3, 8, 15, 1, /* CLIP357_9 */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 17, INVALIDCURS, 0, 1, 12, 1, 8, 30, 3, /* CLIP357_6_AP */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 18, INVALIDCURS, 0, 1, 18, 3, 8, 45, 3, /* CLIP357_9_AP */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 19, INVALIDCURS, 0, 1, 13, 1, 8, 20, 2, /* CLIP357_6_HP */ 0, 0, IF_STANDARD_CLIP},
//
//{ IC_AMMO, 20, INVALIDCURS, 0, 1, 19, 3, 8, 30, 2, /* CLIP357_9_HP */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 21, INVALIDCURS, 0, 1, 9, 6, 4, 150, 5, /* CLIP545_30_AP */ 0, 0, IF_STANDARD_CLIP | ITEM_BIGGUNLIST },
//{ IC_AMMO, 22, INVALIDCURS, 0, 1, 10, 6, 4, 100, 4, /* CLIP545_30_HP */ 0, 0, IF_STANDARD_CLIP | ITEM_BIGGUNLIST },
//{ IC_AMMO, 23, INVALIDCURS, 0, 1, 7, 5, 4, 150, 4, /* CLIP556_30_AP */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 24, INVALIDCURS, 0, 1, 8, 5, 4, 100, 3, /* CLIP556_30_HP */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 25, INVALIDCURS, 0, 1, 22, 3, 6, 60, 6, /* CLIP762W_10_AP */ 0, 0, IF_STANDARD_CLIP | ITEM_BIGGUNLIST },
//{ IC_AMMO, 26, INVALIDCURS, 0, 1, 29, 8, 4, 180, 4, /* CLIP762W_30_AP */ 0, 0, IF_STANDARD_CLIP | ITEM_BIGGUNLIST },
//{ IC_AMMO, 27, INVALIDCURS, 0, 1, 23, 3, 6, 40, 5, /* CLIP762W_10_HP */ 0, 0, IF_STANDARD_CLIP | ITEM_BIGGUNLIST },
//{ IC_AMMO, 28, INVALIDCURS, 0, 1, 30, 8, 4, 120, 3, /* CLIP762W_30_HP */ 0, 0, IF_STANDARD_CLIP | ITEM_BIGGUNLIST },
//{ IC_AMMO, 29, INVALIDCURS, 0, 1, 3, 1, 6, 30, 7, /* CLIP762N_5_AP */ 0, 0, IF_STANDARD_CLIP},
//
//{ IC_AMMO, 30, INVALIDCURS, 0, 1, 27, 8, 4, 120, 6, /* CLIP762N_20_AP */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 31, INVALIDCURS, 0, 1, 2, 1, 6, 20, 6, /* CLIP762N_5_HP */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 32, INVALIDCURS, 0, 1, 28, 8, 4, 80, 5, /* CLIP762N_20_HP */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 33, INVALIDCURS, 0, 1, 31, 5, 4, 700, 8, /* CLIP47_50_SAP */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 34, INVALIDCURS, 0, 1, 20, 9 , 4, 750, 9, /* CLIP57_50_SAP */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 35, INVALIDCURS, 0, 1, 21, 9, 4, 500, 9, /* CLIP57_50_HP */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 36, INVALIDCURS, 0, 2, 22, 5, 6, 20, 3, /* CLIP12G_7 */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 37, INVALIDCURS, 0, 2, 4, 5, 6, 20, 3, /* CLIP12G_7_BUCKSHOT */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 38, INVALIDCURS, 0, 1, 0, 10, 6, 300, 9, /* CLIPCAWS_10_SAP */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 39, INVALIDCURS, 0, 1, 1, 10, 6, 300, 9, /* CLIPCAWS_10_FLECH */ 0, 0, IF_STANDARD_CLIP},
//
//{ IC_AMMO, 40, INVALIDCURS, 0, 1, 110, 10, 4, 500, 9, /* CLIPROCKET_AP */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 41, INVALIDCURS, 0, 1, 115, 10, 4, 500, 9, /* CLIPROCKET_HE */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 42, INVALIDCURS, 0, 1, 114, 10, 4, 500, 9, /* CLIPROCKET_HEAT */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 43, INVALIDCURS, 0, 1, 119, 1, 8, 10, 4, /* sleep dart */ 0, 0, IF_STANDARD_CLIP},
//{ IC_AMMO, 44, INVALIDCURS, 0, 0, 49, 8, 4, 0, 0, /* flameThrwr clip */ 0, 0, IF_STANDARD_CLIP },
//// MADD MARKER
//{ IC_AMMO, 45, INVALIDCURS, 0, 1, 138, 9, 4, 300, 10, /* CLIP50_11 */ 0, 0, IF_STANDARD_CLIP | ITEM_BIGGUNLIST },
//{ IC_AMMO, 46, INVALIDCURS, 0, 1, 139, 4, 4, 50, 9, /* CLIP9H_20 */ 0, 0, IF_STANDARD_CLIP | ITEM_BIGGUNLIST },
//{ IC_AMMO, 47, INVALIDCURS, 0, 1, 140, 8, 4, 50, 6, /* CLIP9_50 */ 0, 0, IF_STANDARD_CLIP | ITEM_BIGGUNLIST },
//{ IC_AMMO, 48, INVALIDCURS, 0, 1, 141, 8, 4, 50, 7, /* CLIP9_50_AP */ 0, 0, IF_STANDARD_CLIP | ITEM_BIGGUNLIST },
//{ IC_AMMO, 49, INVALIDCURS, 0, 1, 142, 8, 4, 60, 7, /* CLIP9_50_HP */ 0, 0, IF_STANDARD_CLIP | ITEM_BIGGUNLIST },
//
//{ IC_AMMO, 50, INVALIDCURS, 0, 1, 143, 15, 1, 375, 9, /* DRUM545_75_AP */ 0, 0, IF_STANDARD_CLIP | ITEM_BIGGUNLIST },
//{ IC_AMMO, 51, INVALIDCURS, 0, 1, 144, 15, 1, 250, 9, /* DRUM545_75_HP */ 0, 0, IF_STANDARD_CLIP | ITEM_BIGGUNLIST },
//{ IC_AMMO, 52, INVALIDCURS, 0, 1, 145, 30, 1, 1000,9, /* BELT556_200_AP */ 0, 0, IF_STANDARD_CLIP | ITEM_BIGGUNLIST },
//{ IC_AMMO, 53, INVALIDCURS, 0, 1, 146, 30, 1, 650, 9, /* BELT556_200_HP */ 0, 0, IF_STANDARD_CLIP | ITEM_BIGGUNLIST },
//{ IC_AMMO, 54, INVALIDCURS, 0, 1, 153, 40, 1, 600, 9, /* BELT762N_100_AP */ 0, 0, IF_STANDARD_CLIP | ITEM_BIGGUNLIST },
//{ IC_AMMO, 55, INVALIDCURS, 0, 1, 154, 40, 1, 400, 9, /* BELT762N_100_HP */ 0, 0, IF_STANDARD_CLIP | ITEM_BIGGUNLIST },
//{ IC_AMMO, 56, INVALIDCURS, 0, 1, 147, 3, 8, 300, 6, /* CLIP57_20_AP */ 0, 0, IF_STANDARD_CLIP | ITEM_BIGGUNLIST },
//{ IC_AMMO, 57, INVALIDCURS, 0, 1, 148, 3, 8, 200, 6, /* CLIP57_20_HP */ 0, 0, IF_STANDARD_CLIP | ITEM_BIGGUNLIST },
////{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
////{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
////{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
////{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
////{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
////{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
////{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
////{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
//{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
//{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
//
////---EXPLOSIVES---
//
//{ IC_GRENADE, 0, TOSSCURS, 0, 1, 38, 6, 4, 100, 5, /* stun grenade */ 0, -2, ITEM_DAMAGEABLE | ITEM_METAL | ITEM_REPAIRABLE },
//{ IC_GRENADE, 1, TOSSCURS, 0, 1, 48, 6, 4, 120, 4, /* tear gas grenade */ 0, -2, ITEM_DAMAGEABLE | ITEM_METAL | ITEM_REPAIRABLE},
//{ IC_GRENADE, 2, TOSSCURS, 0, 1, 41, 6, 4, 500, 7, /* mustard gas grenade*/ 0, -3, ITEM_DAMAGEABLE | ITEM_METAL | ITEM_REPAIRABLE},
//{ IC_GRENADE, 3, TOSSCURS, 0, 1, 50, 3, 6, 150, 5, /* mini hand grenade */ 0, -4, ITEM_DAMAGEABLE | ITEM_METAL | ITEM_REPAIRABLE},
//{ IC_GRENADE, 4, TOSSCURS, 0, 1, 49, 6, 4, 200, 6, /* reg hand grenade */ 0, -4, ITEM_DAMAGEABLE | ITEM_METAL | ITEM_REPAIRABLE},
//{ IC_BOMB, 5, INVALIDCURS, 0, 2, 3, 11, 2, 400, 7, /* RDX */ 0, -4, ITEM_DAMAGEABLE | ITEM_REPAIRABLE},
//{ IC_BOMB, 6, INVALIDCURS, 0, 2, 0, 11, 1, 500, 4, /* TNT (="explosives")*/ 0, -4, ITEM_DAMAGEABLE | ITEM_REPAIRABLE},
//{ IC_BOMB, 7, INVALIDCURS, 0, 2, 23, 11, 1, 1000, 8, /* HMX (=RDX+TNT) */ 0, -4, ITEM_DAMAGEABLE | ITEM_REPAIRABLE},
//{ IC_BOMB, 8, INVALIDCURS, 0, 1, 45, 11, 1, 750, 7, /* C1 (=RDX+min oil) */ 0, -4, ITEM_DAMAGEABLE | ITEM_REPAIRABLE},
//{ IC_BOMB, 9, INVALIDCURS, 0, 1, 40, 41, 2, 400, 9, /* mortar shell */ 0, -4, ITEM_DAMAGEABLE | ITEM_METAL | ITEM_REPAIRABLE},
//
//{ IC_BOMB, 10, BOMBCURS, 0, 1, 46, 8, 1, 300, 5, /* mine */ 0, -4, ITEM_DAMAGEABLE | ITEM_METAL | ITEM_REPAIRABLE },
//{ IC_BOMB, 11, INVALIDCURS, 0, 1, 44, 11, 1, 1500, 9, /* C4 ("plastique") */ 0, -4, ITEM_DAMAGEABLE | ITEM_REPAIRABLE},
//{ IC_BOMB, 12, BOMBCURS, 0, 1, 42, 4, 2, 0, 0, /* trip flare */ 0, -2, ITEM_DAMAGEABLE | ITEM_METAL | ITEM_NOT_BUYABLE | ITEM_REPAIRABLE },
//{ IC_BOMB, 13, BOMBCURS, 0, 1, 43, 4, 2, 0, 0, /* trip klaxon */ 0, -2, ITEM_DAMAGEABLE | ITEM_METAL | ITEM_NOT_BUYABLE | ITEM_REPAIRABLE },
//{ IC_BOMB, 14, INVALIDCURS, 0, 1, 107, 2, 4, 250, 5, /* shaped charge */ 0, -4, ITEM_DAMAGEABLE | ITEM_METAL | ITEM_REPAIRABLE},
//{ IC_GRENADE, 15, TOSSCURS, 0, 2, 24, 1, 6, 50, 3, /* break light (flare)*/ 0, 0, ITEM_DAMAGEABLE | ITEM_REPAIRABLE},
//{ IC_GRENADE, 16, INVALIDCURS, 0, 1, 97, 10, 4, 400, 8, /* 40mm HE grenade */ 0, -4, ITEM_DAMAGEABLE | ITEM_METAL | ITEM_REPAIRABLE},
//{ IC_GRENADE, 17, INVALIDCURS, 0, 1, 111, 10, 4, 250, 6, /* 40mm tear gas grnd */ 0, -2, ITEM_DAMAGEABLE | ITEM_METAL | ITEM_REPAIRABLE},
//{ IC_GRENADE, 18, INVALIDCURS, 0, 1, 113, 10, 4, 200, 5, /* 40mm stun grenade */ 0, -2, ITEM_DAMAGEABLE | ITEM_METAL | ITEM_REPAIRABLE},
//{ IC_GRENADE, 19, INVALIDCURS, 0, 1, 112, 10, 4, 100, 7, /* 40mm smoke grenade */ 0, -2, ITEM_DAMAGEABLE | ITEM_METAL | ITEM_REPAIRABLE},
//
//{ IC_GRENADE, 20, TOSSCURS, 0, 1, 98, 6, 4, 50, 3, /* smoke hand grenade */ 0, -2, ITEM_DAMAGEABLE | ITEM_METAL | ITEM_REPAIRABLE},
//{ IC_BOMB, 21, INVALIDCURS, 0, 1, 40, 41, 8, 450, 0, /* tank shell */ 0, -4, ITEM_DAMAGEABLE | ITEM_METAL | ITEM_NOT_BUYABLE | ITEM_NOT_EDITOR },
//{ IC_BOMB, 22, INVALIDCURS, 0, 1, 40, 41, 2, 450, 0, /* fake struct ignite*/ 0, -4, ITEM_DAMAGEABLE | ITEM_METAL | ITEM_NOT_BUYABLE },
//{ IC_GRENADE, 23, TOSSCURS, 0, 2, 37, 6, 4, 50, 0, /* creature cocktail*/ 0, 0, ITEM_DAMAGEABLE | ITEM_METAL },
//{ IC_BOMB, 24, INVALIDCURS, 0, 1, 40, 41, 2, 450, 0, /* fake struct xplod*/ 0, -4, ITEM_DAMAGEABLE | ITEM_METAL | ITEM_NOT_BUYABLE },
//{ IC_BOMB, 25, INVALIDCURS, 0, 1, 40, 41, 2, 450, 0, /* fake vehicle xplod*/ 0, -4, ITEM_DAMAGEABLE | ITEM_METAL | ITEM_NOT_BUYABLE },
//{ IC_GRENADE, 26, TOSSCURS, 0, 1, 48, 6, 4, 0, 0, /* BIG tear gas grenade*/ 0, -2, ITEM_DAMAGEABLE | ITEM_METAL | ITEM_REPAIRABLE | ITEM_NOT_BUYABLE },
//{ IC_GRENADE, 27, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* small creature gas */ 0, 0, 0},
//{ IC_GRENADE, 28, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* big creature gas */ 0, 0, 0},
//{ IC_GRENADE, 29, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* very sm creat gas */ 0, 0, 0},
//
////---ARMOUR---
//{ IC_ARMOUR, 0, INVALIDCURS, COND, 1, 66, 20, 0, 300, 2, /* Flak jacket */ 0, +2, IF_STANDARD_ARMOUR},
//{ IC_ARMOUR, 1, INVALIDCURS, COND, 2, 18, 22, 0, 350, 0, /* Flak jacket w X */ 0, +1, IF_STANDARD_ARMOUR | ITEM_NOT_BUYABLE },
//{ IC_ARMOUR, 2, INVALIDCURS, COND, 2, 11, 18, 0, 400, 0, /* Flak jacket w Y */ 0, +3, IF_STANDARD_ARMOUR | ITEM_NOT_BUYABLE },
//{ IC_ARMOUR, 3, INVALIDCURS, COND, 1, 64, 32, 0, 500, 4, /* Kevlar jacket */ 0, 0, IF_STANDARD_ARMOUR},
//{ IC_ARMOUR, 4, INVALIDCURS, COND, 2, 16, 35, 0, 600, 0, /* Kevlar jack w X */ 0, -1, IF_STANDARD_ARMOUR | ITEM_NOT_BUYABLE },
//{ IC_ARMOUR, 5, INVALIDCURS, COND, 2, 9, 29, 0, 700, 0, /* Kevlar jack w Y */ 0, +1, IF_STANDARD_ARMOUR | ITEM_NOT_BUYABLE },
//{ IC_ARMOUR, 6, INVALIDCURS, COND, 1, 65, 32, 0, 1000, 8, /* Spectra jacket */ 0, -2, IF_STANDARD_ARMOUR},
//{ IC_ARMOUR, 7, INVALIDCURS, COND, 2, 17, 35, 0, 1100, 0, /* Spectra jack w X*/ 0, -3, IF_STANDARD_ARMOUR | ITEM_NOT_BUYABLE },
//{ IC_ARMOUR, 8, INVALIDCURS, COND, 2, 10, 29, 0, 1200, 0, /* Spectra jack w Y*/ 0, -1, IF_STANDARD_ARMOUR | ITEM_NOT_BUYABLE },
//{ IC_ARMOUR, 9, INVALIDCURS, COND, 1, 67, 39, 0, 650, 5, /* Kevlar leggings */ 0, 0, IF_STANDARD_ARMOUR},
//
//{ IC_ARMOUR, 10, INVALIDCURS, COND, 2, 19, 43, 0, 800, 0, /* Kevlar legs w X */ 0, -1, IF_STANDARD_ARMOUR | ITEM_NOT_BUYABLE },
//{ IC_ARMOUR, 11, INVALIDCURS, COND, 2, 12, 35, 0, 950, 0, /* Kevlar legs w Y */ 0, +1, IF_STANDARD_ARMOUR | ITEM_NOT_BUYABLE },
//{ IC_ARMOUR, 12, INVALIDCURS, COND, 1, 68, 39, 0, 900, 8, /* Spectra leggings*/ 0, -2, IF_STANDARD_ARMOUR},
//{ IC_ARMOUR, 13, INVALIDCURS, COND, 2, 20, 43, 0, 1100, 0, /* Spectra legs w X*/ 0, -3, IF_STANDARD_ARMOUR | ITEM_NOT_BUYABLE },
//{ IC_ARMOUR, 14, INVALIDCURS, COND, 2, 13, 35, 0, 1300, 0, /* Spectra legs w Y*/ 0, -1, IF_STANDARD_ARMOUR | ITEM_NOT_BUYABLE },
//{ IC_ARMOUR, 15, INVALIDCURS, COND, 1, 61, 14, 0, 50, 2, /* Steel helmet */ 0, +2, IF_STANDARD_ARMOUR | ITEM_METAL},
//{ IC_ARMOUR, 16, INVALIDCURS, COND, 1, 63, 14, 0, 200, 4, /* Kevlar helmet */ 0, 0, IF_STANDARD_ARMOUR},
//{ IC_ARMOUR, 17, INVALIDCURS, COND, 2, 15, 15, 0, 250, 0, /* Kevlar helm w X */ 0, -1, IF_STANDARD_ARMOUR | ITEM_NOT_BUYABLE },
//{ IC_ARMOUR, 18, INVALIDCURS, COND, 2, 8, 13, 0, 300, 0, /* Kevlar helm w Y */ 0, +1, IF_STANDARD_ARMOUR | ITEM_NOT_BUYABLE },
//{ IC_ARMOUR, 19, INVALIDCURS, COND, 1, 62, 14, 0, 450, 7, /* Spectra helmet */ 0, -2, IF_STANDARD_ARMOUR},
//
//{ IC_ARMOUR, 20, INVALIDCURS, COND, 2, 14, 15, 0, 550, 0, /* Spectra helm w X*/ 0, -3, IF_STANDARD_ARMOUR | ITEM_NOT_BUYABLE },
//{ IC_ARMOUR, 21, INVALIDCURS, COND, 2, 7, 13, 0, 650, 0, /* Spectra helm w Y*/ 0, -1, IF_STANDARD_ARMOUR | ITEM_NOT_BUYABLE },
//{ IC_ARMOUR, 22, INVALIDCURS, COND, 1, 81, 12, 2, 250, 5, /* Ceramic plates */ 0, -4, (IF_STANDARD_ARMOUR | ITEM_ATTACHMENT) & (~ITEM_REPAIRABLE) },
//{ IC_ARMOUR, 23, INVALIDCURS, COND, 1, 0, 0, 0, 0, 0, /* Infant crt hide */ 0, 0, IF_STANDARD_ARMOUR | ITEM_NOT_BUYABLE | ITEM_NOT_EDITOR | ITEM_DEFAULT_UNDROPPABLE},
//{ IC_ARMOUR, 24, INVALIDCURS, COND, 1, 0, 0, 0, 0, 0, /* Yng male hide */ 0, 0, IF_STANDARD_ARMOUR | ITEM_NOT_BUYABLE | ITEM_NOT_EDITOR | ITEM_DEFAULT_UNDROPPABLE},
//{ IC_ARMOUR, 25, INVALIDCURS, COND, 1, 0, 0, 0, 0, 0, /* Old male hide */ 0, 0, IF_STANDARD_ARMOUR | ITEM_NOT_BUYABLE | ITEM_NOT_EDITOR | ITEM_DEFAULT_UNDROPPABLE},
//{ IC_ARMOUR, 26, INVALIDCURS, COND, 1, 0, 0, 0, 0, 0, /* Queen cret hide */ 0, 0, IF_STANDARD_ARMOUR | ITEM_NOT_BUYABLE | ITEM_NOT_EDITOR | ITEM_DEFAULT_UNDROPPABLE},
//{ IC_ARMOUR, 27, INVALIDCURS, COND, 1, 96, 20, 0, 200, 2, /* Leather jacket */ 0, +4, IF_STANDARD_ARMOUR },
//// NOTE: THE FOLLOWING ITEM'S PRICE VALUE IS IN DIALOGUE AND SHOULD NOT BE CHANGED
//{ IC_ARMOUR, 28, INVALIDCURS, COND, 1, 116, 20, 0, 950, 3, /* L jacket w kev */ 0, +2, IF_STANDARD_ARMOUR },
//{ IC_ARMOUR, 29, INVALIDCURS, COND, 1, 117, 20, 0, 1200, 0, /* L jacket w kev 18*/0, +1, IF_STANDARD_ARMOUR | ITEM_NOT_BUYABLE },
//
//{ IC_ARMOUR, 30, INVALIDCURS, COND, 1, 118, 20, 0, 1500, 0, /* L jacket w kev c*/ 0, +3, IF_STANDARD_ARMOUR | ITEM_NOT_BUYABLE },
//{ IC_ARMOUR, 31, INVALIDCURS, COND, 1, 0, 0, 0, 0, 0, /* yng fem hide */ 0, 0, IF_STANDARD_ARMOUR | ITEM_NOT_BUYABLE | ITEM_NOT_EDITOR | ITEM_DEFAULT_UNDROPPABLE},
//{ IC_ARMOUR, 32, INVALIDCURS, COND, 1, 0, 0, 0, 0, 0, /* old fem hide */ 0, 0, IF_STANDARD_ARMOUR | ITEM_NOT_BUYABLE | ITEM_NOT_EDITOR | ITEM_DEFAULT_UNDROPPABLE},
//{ IC_ARMOUR, 33, INVALIDCURS, COND, 2, 25, 3, 1, 10, 1, /* t-shirt */ 0, 0, ITEM_DAMAGEABLE | ITEM_SHOW_STATUS | ITEM_UNAERODYNAMIC},
//{ IC_ARMOUR, 33, INVALIDCURS, COND, 2, 34, 3, 1, 10, 1, /* t-shirt D. rules*/ 0, 0, ITEM_DAMAGEABLE | ITEM_SHOW_STATUS | ITEM_UNAERODYNAMIC},
//{ IC_ARMOUR, 34, INVALIDCURS, COND, 1, 137, 32, 0, 700, 6, /* Kevlar2 jacket */ 0, -1, IF_STANDARD_ARMOUR},
//{ IC_ARMOUR, 35, INVALIDCURS, COND, 2, 40, 35, 0, 800, 0, /* Kevlar2 jack w X*/ 0, -2, IF_STANDARD_ARMOUR | ITEM_NOT_BUYABLE },
//{ IC_ARMOUR, 36, INVALIDCURS, COND, 2, 41, 29, 0, 900, 0, /* Kevlar2 jack w Y*/ 0, 0, IF_STANDARD_ARMOUR | ITEM_NOT_BUYABLE },
//{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
//{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
//
////---MISC---
//{ IC_MEDKIT, 0, AIDCURS, USAGE, 1, 73, 5, 4, 100, 1, /* First aid kit */ 0, 0, IF_STANDARD_KIT},
//{ IC_MEDKIT, 0, AIDCURS, USAGE, 1, 86, 18, 0, 300, 1, /* Medical Kit */ 0, 0, IF_STANDARD_KIT | ITEM_METAL},
//{ IC_KIT, 0, REPAIRCURS, COND, 2, 21, 50, 0, 250, 1, /* Tool Kit */ 0, 0, IF_STANDARD_KIT | ITEM_METAL},
//{ IC_KIT, 0, INVALIDCURS, COND, 1, 78, 3, 1, 250, 3, /* Locksmith kit */ 0, -2, IF_STANDARD_KIT | ITEM_METAL | ITEM_REPAIRABLE},
//{ IC_KIT, 0, INVALIDCURS, COND, 1, 58, 1, 4, 250, 5, /* Camouflage kit*/ 0, 0, IF_STANDARD_KIT},
//{ IC_MISC, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 52, 5, 4, 300, 4, /* Silencer */ 0, 0, ITEM_DAMAGEABLE | ITEM_REPAIRABLE | ITEM_METAL | ITEM_ATTACHMENT},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 76, 9, 4, 500, 5, /* Sniper scope */ 0, 0, ITEM_DAMAGEABLE | ITEM_REPAIRABLE | ITEM_METAL | ITEM_ATTACHMENT},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 69, 5, 2, 50, 3, /* Bipod */ 0, +5, ITEM_DAMAGEABLE | ITEM_REPAIRABLE | ITEM_METAL | ITEM_ATTACHMENT},
//{ IC_FACE, 0, INVALIDCURS, 0, 1, 77, 9, 1, 400, 7, /* Extended ear */ 0, -3, ITEM_DAMAGEABLE | ITEM_REPAIRABLE | ITEM_METAL | ITEM_ELECTRONIC },
//
//{ IC_FACE, 0, INVALIDCURS, 0, 1, 74, 9, 1, 800, 7, /* Night goggles */ 0, -1, ITEM_DAMAGEABLE | ITEM_REPAIRABLE | ITEM_METAL | ITEM_ELECTRONIC },
//{ IC_FACE, 0, INVALIDCURS, 0, 1, 55, 2, 4, 150, 3, /* Sun goggles */ 0, +3, ITEM_DAMAGEABLE | ITEM_REPAIRABLE },
//{ IC_FACE, 0, INVALIDCURS, 0, 1, 75, 9, 1, 100, 4, /* Gas mask */ 0, +1, ITEM_DAMAGEABLE | ITEM_REPAIRABLE },
//{ IC_KIT, 0, INVALIDCURS, 0, 2, 5, 10, 4, 10, 1, /* Canteen */ 0, 0, ITEM_DAMAGEABLE},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 80, 10, 1, 200, 4, /* Metal detector*/ 0, -2, ITEM_DAMAGEABLE | ITEM_REPAIRABLE | ITEM_METAL | ITEM_ELECTRONIC },
//{ IC_MISC, 0, INVALIDCURS, 0, 2, 6, 1, 4, 900, 7, /* Compound 18 */ 0, 0, ITEM_DAMAGEABLE},
//{ IC_MISC, 0, INVALIDCURS, 0, 2, 42, 1, 4, 2500, 0, /* Jar/QueenBlood*/ 0, 0, ITEM_DAMAGEABLE | ITEM_NOT_BUYABLE},
//{ IC_MISC, 0, INVALIDCURS, 0, 2, 2, 1, 4, 500, 1, /* Jar/Elixir */ 0, 0, ITEM_DAMAGEABLE },
//{ IC_MONEY, 0, INVALIDCURS, 0, 2, 1, 1, 1, 0, 0, /* Money */ 0, 0, ITEM_NOT_BUYABLE | ITEM_UNAERODYNAMIC},
//{ IC_MISC, 0, JARCURS, COND, 1, 71, 1, 2, 10, 1, /* Glass jar */ 0, 0, ITEM_DAMAGEABLE},
//
//{ IC_MISC, 0, INVALIDCURS, COND, 1, 72, 5, 2, 50, 1, /* Jar/CreatureBlood*/0, 0, ITEM_DAMAGEABLE | ITEM_NOT_BUYABLE},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 70, 1, 8, 150, 4, /* Adren Booster */ 0, 0, ITEM_DAMAGEABLE | ITEM_UNAERODYNAMIC},
//{ IC_MISC, 0, INVALIDCURS, COND, 1, 47, 1, 4, 100, 3, /* Detonator */ 0, +1, ITEM_DAMAGEABLE | ITEM_REPAIRABLE | ITEM_ATTACHMENT | ITEM_METAL},
//{ IC_MISC, 0, INVALIDCURS, COND, 1, 47, 1, 4, 200, 6, /* Rem Detonator */ 0, -1, ITEM_DAMAGEABLE | ITEM_REPAIRABLE | ITEM_ATTACHMENT | ITEM_METAL | ITEM_ELECTRONIC },
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 93, 1, 8, 0, 0, /* Videotape */ 0, 0, ITEM_NOT_BUYABLE},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 94, 1, 8, 0, 0, /* Deed */ 0, 0, ITEM_NOT_BUYABLE | ITEM_UNAERODYNAMIC},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 56, 1, 1, 0, 0, /* Letter */ 0, 0, ITEM_NOT_BUYABLE | ITEM_UNAERODYNAMIC},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 59, 1, 1, 0, 0, /* Diskette */ 0, 0, ITEM_NOT_BUYABLE},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 124, 0, 1, 3000, 0, /* Chalice */ 0, 0, ITEM_NOT_BUYABLE},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 120, 1, 4, 50, 0, /* Bloodcat claws*/ 0, 0, ITEM_NOT_BUYABLE | ITEM_DAMAGEABLE},
//
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 121, 1, 4, 100, 0, /* Bloodcat teeth*/ 0, 0, ITEM_NOT_BUYABLE | ITEM_DAMAGEABLE},
//{ IC_MISC, 0, INVALIDCURS, 0, 3, 9, 60, 0, 400, 0, /* Bloodcat pelt */ 0, 0, ITEM_NOT_BUYABLE | ITEM_DAMAGEABLE},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 54, 0, 99, 0, 0, /* Switch */ 0, 0, ITEM_NOT_BUYABLE | ITEM_METAL},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 47, 0, 99, 0, 0, /* Action item */ 0, 0, ITEM_NOT_BUYABLE },
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 70, 1, 6, 300, 6, /* Regen Booster */ 0, 0, ITEM_DAMAGEABLE | ITEM_UNAERODYNAMIC},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 70, 0, 99, 0, 0, /* syringe 3 */ 0, 0, ITEM_NOT_BUYABLE | ITEM_UNAERODYNAMIC},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 70, 0, 99, 0, 0, /* syringe 4 */ 0, 0, ITEM_NOT_BUYABLE | ITEM_UNAERODYNAMIC},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 70, 0, 99, 0, 0, /* syringe 5 */ 0, 0, ITEM_NOT_BUYABLE | ITEM_UNAERODYNAMIC},
//{ IC_MISC, 0, INVALIDCURS, COND, 1, 72, 5, 2, 10, 1, /* Jar/Human Blood*/ 0, 0, ITEM_DAMAGEABLE},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 0, 0, 0, 0, 0, /* ownership */ 0, 0, ITEM_NOT_BUYABLE},
//
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 51, 4, 4, 750, 7, /* Laser scope */ 0, -1, ITEM_DAMAGEABLE | ITEM_REPAIRABLE | ITEM_METAL | ITEM_ATTACHMENT | ITEM_ELECTRONIC },
//{ IC_MISC, 0, REMOTECURS, 0, 1, 54, 9, 4, 400, 6, /* Remote bomb trig*/ 0, -2, ITEM_DAMAGEABLE | ITEM_REPAIRABLE | ITEM_METAL | ITEM_ELECTRONIC },
//{ IC_MISC, 0, WIRECUTCURS, 0, 1, 88, 4, 2, 20, 2, /* Wirecutters */ 0, -4, ITEM_DAMAGEABLE | ITEM_REPAIRABLE | ITEM_METAL},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 90, 9, 4, 30, 2, /* Duckbill */ 0, +5, ITEM_DAMAGEABLE | ITEM_REPAIRABLE | ITEM_METAL | ITEM_ATTACHMENT},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 106, 20, 1, 30, 1, /* Alcohol */ 0, 0, ITEM_DAMAGEABLE},
//{ IC_FACE, 0, INVALIDCURS, 0, 1, 74, 11, 1, 1500, 9, /* UV goggles */ 0, -1, ITEM_DAMAGEABLE | ITEM_REPAIRABLE | ITEM_METAL | ITEM_ELECTRONIC },
//{ IC_MISC, 0, INVALIDCURS, 0, 0, 44, 21, 0, 30, 0, /* discarded LAW*/ 0, 0, IF_TWOHANDED_GUN | ITEM_NOT_BUYABLE },
//{ IC_MISC, 0, INVALIDCURS, 0, 3, 0, 40, 0, 0, 0, /* head - generic */ 0, 0, ITEM_DAMAGEABLE},
//{ IC_MISC, 0, INVALIDCURS, 0, 3, 1, 40, 0, 0, 0, /* head - Imposter*/ 0, 0, ITEM_DAMAGEABLE},
//{ IC_MISC, 0, INVALIDCURS, 0, 3, 2, 40, 0, 0, 0, /* head - T-Rex */ 0, 0, ITEM_DAMAGEABLE},
//
//{ IC_MISC, 0, INVALIDCURS, 0, 3, 3, 40, 0, 0, 0, /* head - Slay */ 0, 0, ITEM_DAMAGEABLE},
//{ IC_MISC, 0, INVALIDCURS, 0, 3, 4, 40, 0, 0, 0, /* head - Druggist */ 0, 0, ITEM_DAMAGEABLE},
//{ IC_MISC, 0, INVALIDCURS, 0, 3, 5, 40, 0, 0, 0, /* head - Matron */ 0, 0, ITEM_DAMAGEABLE},
//{ IC_MISC, 0, INVALIDCURS, 0, 3, 6, 40, 0, 0, 0, /* head - Tiffany */ 0, 0, ITEM_DAMAGEABLE},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 100, 12, 1, 20, 1, /* wine */ 0, 0, ITEM_DAMAGEABLE},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 101, 4, 4, 10, 1, /* beer */ 0, 0, ITEM_DAMAGEABLE},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 99, 0, 2, 20, 3, /* pornos */ 0, 0, ITEM_DAMAGEABLE},
//{ IC_MISC, 0, INVALIDCURS, 0, 0, 43, 20, 0, 900, 6, /* video camera */ 0, -4, ITEM_DAMAGEABLE | ITEM_REPAIRABLE | ITEM_METAL | ITEM_ELECTRONIC },
//{ IC_FACE, 0, INVALIDCURS, 0, 0, 42, 5, 1, 2500, 0, /* robot remote */ 0, -5, ITEM_DAMAGEABLE | ITEM_REPAIRABLE | ITEM_METAL | ITEM_ELECTRONIC },
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 103, 20, 0, 500, 0, /* creature claws */ 0, 0, ITEM_NOT_BUYABLE | ITEM_DAMAGEABLE},
//
//{ IC_MISC, 0, INVALIDCURS, 0, 3, 7, 40, 0, 250, 0, /* creature flesh */ 0, 0, ITEM_NOT_BUYABLE | ITEM_DAMAGEABLE},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 104, 10, 0, 1000, 0, /* creature organ */ 0, 0, ITEM_NOT_BUYABLE | ITEM_DAMAGEABLE},
//{ IC_MISC, 0, REMOTECURS, 0, 1, 54, 9, 4, 400, 6, /* Remote trigger*/ 0, -2, ITEM_DAMAGEABLE | ITEM_REPAIRABLE | ITEM_METAL},
//{ IC_MISC, 0, INVALIDCURS, 0, 0, 47, 2, 8, 500, 2, /* gold watch */ 0, -4, ITEM_DAMAGEABLE | ITEM_REPAIRABLE | ITEM_METAL},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 136, 100, 0, 200, 2, /* golf clubs */ 0, 0, ITEM_DAMAGEABLE | ITEM_REPAIRABLE | ITEM_METAL},
//{ IC_FACE, 0, INVALIDCURS, 0, 3, 11, 5, 1, 100, 1, /* walkman */ 0, -4, ITEM_DAMAGEABLE | ITEM_REPAIRABLE | ITEM_METAL | ITEM_ELECTRONIC },
//{ IC_MISC, 0, INVALIDCURS, 0, 3, 8, 50, 0, 300, 2, /* portable tv */ 0, -3, ITEM_DAMAGEABLE | ITEM_REPAIRABLE | ITEM_ELECTRONIC },
//{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
//{ IC_MISC, 0, INVALIDCURS, 0, 3, 10, 10, 1, 30, 1, /* cigars */ 0, 0, ITEM_DAMAGEABLE },
//{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
//
//{ IC_KEY, 0, INVALIDCURS, 0, 1, 82, 1, 8, 0, 0, /* dull gold key */ 0, 0, ITEM_NOT_BUYABLE | ITEM_METAL},
//{ IC_KEY, 1, INVALIDCURS, 0, 1, 83, 1, 8, 0, 0, /* silver key */ 0, 0, ITEM_NOT_BUYABLE | ITEM_METAL},
//{ IC_KEY, 2, INVALIDCURS, 0, 1, 84, 1, 8, 0, 0, /* diamond-shpd key */0, 0, ITEM_NOT_BUYABLE | ITEM_METAL},
//{ IC_KEY, 3, INVALIDCURS, 0, 1, 87, 1, 8, 0, 0, /* bright gold key */ 0, 0, ITEM_NOT_BUYABLE | ITEM_METAL},
//{ IC_KEY, 4, INVALIDCURS, 0, 1, 91, 1, 8, 0, 0, /* gold key */ 0, 0, ITEM_NOT_BUYABLE | ITEM_METAL},
//{ IC_KEY, 5, INVALIDCURS, 0, 1, 92, 1, 8, 0, 0, /* small gold key */ 0, 0, ITEM_NOT_BUYABLE | ITEM_METAL},
//{ IC_KEY, 6, INVALIDCURS, 0, 1, 108, 1, 8, 0, 0, /* electronic */ 0, 0, ITEM_NOT_BUYABLE | ITEM_METAL | ITEM_ELECTRONIC },
//{ IC_KEY, 7, INVALIDCURS, 0, 1, 109, 1, 8, 0, 0, /* passcard */ 0, 0, ITEM_NOT_BUYABLE | ITEM_METAL},
//{ IC_KEY, 8, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* key */ 0, 0, ITEM_NOT_EDITOR | ITEM_METAL},
//{ IC_KEY, 9, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* key */ 0, 0, ITEM_NOT_EDITOR | ITEM_METAL},
//
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 149, 4, 4, 100, 3, /* Flash Suppressor */ 0, 0, ITEM_DAMAGEABLE | ITEM_REPAIRABLE | ITEM_METAL | ITEM_ATTACHMENT},
//{ IC_LAUNCHER, 282, TARGETCURS, 0, 0, 68, 79, 0, 1500, 10, /* rpg 7 */ 0, -3, IF_TWOHANDED_GUN },
//{ IC_GRENADE, 30, INVALIDCURS, 0, 1, 150, 21, 0, 1200, 10, /* HE rpg ammo */ 0, 0, ITEM_DAMAGEABLE | ITEM_METAL | ITEM_REPAIRABLE},
//{ IC_GRENADE, 31, INVALIDCURS, 0, 1, 152, 21, 0, 2000, 10, /* AP rpg ammo */ 0, 0, ITEM_DAMAGEABLE | ITEM_METAL | ITEM_REPAIRABLE},
//{ IC_GRENADE, 32, INVALIDCURS, 0, 1, 151, 21, 0, 1000, 10, /* Frag rpg ammo */ 0, 0, ITEM_DAMAGEABLE | ITEM_METAL | ITEM_REPAIRABLE},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 155, 4, 4, 1200, 6, /* Reflex scoped */ 0, 0, ITEM_DAMAGEABLE | ITEM_REPAIRABLE | ITEM_METAL | ITEM_ATTACHMENT},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 156, 2, 4, 1200, 6, /* Reflex unscoped */ 0, 0, ITEM_DAMAGEABLE | ITEM_REPAIRABLE | ITEM_METAL | ITEM_ATTACHMENT},
////{ IC_KEY, 10, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* key */ 0, 0, ITEM_NOT_EDITOR | ITEM_METAL},
////{ IC_KEY, 11, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* key */ 0, 0, ITEM_NOT_EDITOR | ITEM_METAL},
////{ IC_KEY, 12, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* key */ 0, 0, ITEM_NOT_EDITOR | ITEM_METAL},
////{ IC_KEY, 13, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* key */ 0, 0, ITEM_NOT_EDITOR | ITEM_METAL},
////{ IC_KEY, 14, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* key */ 0, 0, ITEM_NOT_EDITOR | ITEM_METAL},
////{ IC_KEY, 15, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* key */ 0, 0, ITEM_NOT_EDITOR | ITEM_METAL},
////{ IC_KEY, 16, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* key */ 0, 0, ITEM_NOT_EDITOR | ITEM_METAL},
//{ IC_KEY, 17, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* key */ 0, 0, ITEM_NOT_EDITOR | ITEM_METAL},
//{ IC_KEY, 18, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* key */ 0, 0, ITEM_NOT_EDITOR | ITEM_METAL},
//{ IC_KEY, 19, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* key */ 0, 0, ITEM_NOT_EDITOR | ITEM_METAL},
//
//{ IC_KEY, 20, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* key */ 0, 0, ITEM_NOT_EDITOR | ITEM_METAL},
//{ IC_KEY, 21, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* key */ 0, 0, ITEM_NOT_EDITOR | ITEM_METAL},
//{ IC_KEY, 22, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* key */ 0, 0, ITEM_NOT_EDITOR | ITEM_METAL},
//{ IC_KEY, 23, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* key */ 0, 0, ITEM_NOT_EDITOR | ITEM_METAL},
//{ IC_KEY, 24, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* key */ 0, 0, ITEM_NOT_EDITOR | ITEM_METAL},
//{ IC_KEY, 25, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* key */ 0, 0, ITEM_NOT_EDITOR | ITEM_METAL},
//{ IC_KEY, 26, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* key */ 0, 0, ITEM_NOT_EDITOR | ITEM_METAL},
//{ IC_KEY, 27, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* key */ 0, 0, ITEM_NOT_EDITOR | ITEM_METAL},
//{ IC_KEY, 28, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* key */ 0, 0, ITEM_NOT_EDITOR | ITEM_METAL},
//{ IC_KEY, 29, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* key */ 0, 0, ITEM_NOT_EDITOR | ITEM_METAL},
//
//{ IC_KEY, 30, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* key */ 0, 0, ITEM_NOT_EDITOR | ITEM_METAL},
//{ IC_KEY, 31, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* key */ 0, 0, ITEM_NOT_EDITOR | ITEM_METAL},
//{ IC_MISC, 0, INVALIDCURS, 0, 2, 31, 4, 0, 150, 2, /* silver platter */ 0, 0, ITEM_DAMAGEABLE | ITEM_METAL},
//{ IC_MISC, 0, INVALIDCURS, 0, 2, 30, 1, 6, 5, 1, /* duct tape */ 0, 0, ITEM_DAMAGEABLE | ITEM_HIDDEN_ADDON },
//{ IC_MISC, 0, INVALIDCURS, 0, 2, 28, 3, 1, 20, 0, /* aluminum rod */ 0, 0, ITEM_NOT_BUYABLE | ITEM_DAMAGEABLE | ITEM_METAL | ITEM_HIDDEN_ADDON},
//{ IC_MISC, 0, INVALIDCURS, 0, 2, 32, 1, 8, 0, 0, /* spring */ 0, 0, ITEM_NOT_BUYABLE | ITEM_DAMAGEABLE | ITEM_METAL | ITEM_UNAERODYNAMIC | ITEM_HIDDEN_ADDON},
//{ IC_MISC, 0, INVALIDCURS, 0, 2, 33, 4, 1, 25, 0, /* a. rod & spring */ 0, 0, ITEM_NOT_BUYABLE | ITEM_REPAIRABLE | ITEM_DAMAGEABLE | ITEM_METAL | ITEM_INSEPARABLE},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 133, 4, 1, 20, 0, /* steel rod */ 0, 0, ITEM_NOT_BUYABLE | ITEM_DAMAGEABLE | ITEM_METAL | ITEM_HIDDEN_ADDON},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 132, 2, 6, 5, 3, /* quick glue */ 0, 0, ITEM_DAMAGEABLE | ITEM_HIDDEN_ADDON},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 134, 6, 1, 150, 0, /* gun barrel xtndr */0, 0, ITEM_NOT_BUYABLE | ITEM_REPAIRABLE | ITEM_DAMAGEABLE | ITEM_METAL | ITEM_INSEPARABLE},
//
//{ IC_MISC, 0, INVALIDCURS, 0, 2, 35, 1, 8, 0, 0, /* string */ 0, 0, ITEM_NOT_BUYABLE | ITEM_UNAERODYNAMIC | ITEM_HIDDEN_ADDON},
//{ IC_MISC, 0, INVALIDCURS, 0, 2, 27, 1, 1, 0, 0, /* tin can */ 0, 0, ITEM_NOT_BUYABLE | ITEM_UNAERODYNAMIC | ITEM_HIDDEN_ADDON},
//{ IC_MISC, 0, TINCANCURS, 0, 2, 36, 2, 4, 0, 0, /* string & tin can */0, 0, ITEM_NOT_BUYABLE | ITEM_UNAERODYNAMIC},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 122, 3, 6, 5, 0, /* marbles */ 0, 0, ITEM_NOT_BUYABLE | ITEM_DAMAGEABLE },
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 127, 6, 1, 200, 6, /* lame boy */ 0, 0, ITEM_DAMAGEABLE | ITEM_REPAIRABLE | ITEM_ELECTRONIC | ITEM_HIDDEN_ADDON},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 128, 1, 8, 5, 1, /* copper wire */ 0, 0, ITEM_METAL | ITEM_HIDDEN_ADDON },
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 126, 7, 1, 50, 0, /* display unit */ 0, 0, ITEM_NOT_BUYABLE | ITEM_DAMAGEABLE | ITEM_REPAIRABLE | ITEM_ELECTRONIC | ITEM_HIDDEN_ADDON},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 130, 1, 1, 100, 5, /* fumble pak */ 0, 0, ITEM_DAMAGEABLE | ITEM_REPAIRABLE | ITEM_ELECTRONIC},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 131, 1, 2, 10, 5, /* xray bulb */ 0, 0, ITEM_DAMAGEABLE | ITEM_HIDDEN_ADDON},
//{ IC_MISC, 0, INVALIDCURS, 0, 2, 29, 1, 8, 1, 1, /* chewing gum */ 0, 0, ITEM_DAMAGEABLE | ITEM_HIDDEN_ADDON},
//
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 129, 3, 1, 100, 0, /* flash device */ 0, 0, ITEM_NOT_BUYABLE | ITEM_DAMAGEABLE | ITEM_REPAIRABLE | ITEM_METAL | ITEM_ELECTRONIC | ITEM_HIDDEN_ADDON},
//{ IC_MISC, 0, INVALIDCURS, 0, 2, 26, 1, 6, 5, 1, /* batteries */ 0, 0, ITEM_DAMAGEABLE},
//{ IC_MISC, 0, INVALIDCURS, 0, 1, 123, 1, 8, 0, 0, /* elastic */ 0, 0, ITEM_NOT_BUYABLE | ITEM_UNAERODYNAMIC},
//{ IC_MISC, 0, REMOTECURS, 0, 1, 125, 10, 1, 2500, 0, /* xray device */ 0, 0, ITEM_NOT_BUYABLE | ITEM_DAMAGEABLE | ITEM_REPAIRABLE | ITEM_METAL | ITEM_ELECTRONIC},
//{ IC_MONEY, 0, INVALIDCURS, 0, 2, 38, 2, 1, 100, 0, /* silver */ 0, 0, ITEM_NOT_BUYABLE | ITEM_DAMAGEABLE},
//{ IC_MONEY, 0, INVALIDCURS, 0, 1, 135, 2, 1, 300, 0, /* gold */ 0, 0, ITEM_NOT_BUYABLE | ITEM_DAMAGEABLE},
//{ IC_KIT, 0, REFUELCURS, 0, 2, 39, 20, 0, 250, 0, /* gas can */ 0, 0, ITEM_DAMAGEABLE},
//
//{ IC_GUN, 328, TARGETCURS, CONDBUL, 0, 50, 22, 0, 900, 8, /* M900 */ +1, -1, IF_TWOHANDED_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 329, TARGETCURS, CONDBUL, 0, 51, 10, 0, 400, 6, /* M950 */ +1, -1, IF_STANDARD_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 330, TARGETCURS, CONDBUL, 0, 52, 22, 0, 900, 7, /* M960A */ +1, -1, IF_TWOHANDED_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 331, TARGETCURS, CONDBUL, 0, 53, 19, 1, 300, 5, /* Micro Uzi */ +1, -1, IF_STANDARD_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 332, TARGETCURS, CONDBUL, 0, 54, 38, 0, 1300, 6, /* Enfield */ 0, +1, IF_TWOHANDED_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 333, TARGETCURS, CONDBUL, 0, 59, 25, 0, 900, 4, /* MP5A2 */ 0, +1, IF_TWOHANDED_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 334, TARGETCURS, CONDBUL, 0, 60, 29, 0, 1000, 4, /* MP5SD */ 0, 0, IF_TWOHANDED_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 335, TARGETCURS, CONDBUL, 0, 61, 29, 0, 1600, 7, /* MP5N */ +2, 0, IF_STANDARD_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 336, TARGETCURS, CONDBUL, 0, 62, 22, 0, 1300, 6, /* UMP45 */ 0, 0, IF_TWOHANDED_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 337, TARGETCURS, CONDBUL, 0, 63, 6, 1, 1000, 7, /* FIVE7 */ +1, 0, IF_STANDARD_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 338, TARGETCURS, CONDBUL, 0, 64, 7, 1, 400, 4, /* p7m8 */ +2, +1, IF_STANDARD_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 339, TARGETCURS, CONDBUL, 0, 65, 33, 0, 2500, 9, /* g36k */ +3, 0, IF_TWOHANDED_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 340, TARGETCURS, CONDBUL, 0, 66, 28, 0, 2400, 9, /* g36c */ +3, 0, IF_TWOHANDED_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 341, TARGETCURS, CONDBUL, 0, 67, 64, 0, 3000, 10, /* MSG90A1 */ +4, +4, IF_TWOHANDED_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 342, TARGETCURS, CONDBUL, 0, 69, 32, 0, 1400, 7, /* BENNELLI */ +2, +1, IF_TWOHANDED_GUN | ITEM_BIGGUNLIST },
//{ IC_GUN, 343, TARGETCURS, CONDBUL, 0, 70, 34, 0, 2200, 8, /* AK103 */ -1, -1, IF_TWOHANDED_GUN | ITEM_BIGGUNLIST },
//
////{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
////{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
////{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
//
////{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
////{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
////{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
////{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
////{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
////{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
//
////{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
////{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
////{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
////{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
//
////{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
////{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
////{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
//{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
//{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
//{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
//{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
//{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
//{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
//{ IC_NONE, 0, INVALIDCURS, 0, 0, 0, 0, 0, 0, 0, /* nothing! */ 0, 0, 0},
//
//};
// NB hack: if an item appears in this array with an item class of IC_MISC,
// it is a slot used for noting the skill check required for a merge or multi-item attachment
AttachmentInfoStruct AttachmentInfo[MAXITEMS+1];// =
//{
// { SILENCER, IC_GUN, NO_CHECK, 0 },
// { SNIPERSCOPE, IC_GUN, NO_CHECK, 0 },
// { LASERSCOPE, IC_GUN, NO_CHECK, 0 },
// { BIPOD, IC_GUN, NO_CHECK, 0 },
// { UNDER_GLAUNCHER, IC_GUN, NO_CHECK, 0 },
// { DUCKBILL, IC_GUN, NO_CHECK, 0 },
// { SPRING_AND_BOLT_UPGRADE, IC_GUN, ATTACHING_SPECIAL_ITEM_CHECK, 0 },
// { GUN_BARREL_EXTENDER, IC_GUN, ATTACHING_SPECIAL_ITEM_CHECK, 0 },
// { DETONATOR, IC_BOMB, ATTACHING_DETONATOR_CHECK, 0 },
// { REMDETONATOR, IC_BOMB, ATTACHING_REMOTE_DETONATOR_CHECK, -10 },
// { REMDETONATOR, IC_BOMB, ATTACHING_REMOTE_DETONATOR_CHECK, -10 },
// { XRAY_BULB, IC_NONE, ATTACHING_SPECIAL_ELECTRONIC_ITEM_CHECK, -15 },
// { COPPER_WIRE, IC_NONE, ATTACHING_SPECIAL_ELECTRONIC_ITEM_CHECK, +20 },
// { CERAMIC_PLATES, IC_ARMOUR, NO_CHECK, 0 },
// { FLASH_SUPPRESSOR, IC_GUN, NO_CHECK, 0 },
// { REFLEX_SCOPED, IC_GUN, NO_CHECK, 0 },
// { REFLEX_UNSCOPED, IC_GUN, NO_CHECK, 0 },
// { 0, 0 }
//};
//WarmSteel - For the New Attachment System
AttachmentSlotStruct AttachmentSlots[MAXITEMS+1];
ItemReplacementStruct ItemReplacement[MAXATTACHMENTS];
UINT16 Attachment[MAXATTACHMENTS][4];// =
//{
// {SILENCER, GLOCK_17},
// {SILENCER, GLOCK_18},
// {SILENCER, BERETTA_92F},
// {SILENCER, BERETTA_93R},
// {SILENCER, SW38},
// {SILENCER, BARRACUDA},
// {SILENCER, DESERTEAGLE},
// {SILENCER, M1911},
// {SILENCER, MP5K},
// {SILENCER, MAC10},
// {SILENCER, THOMPSON},
// {SILENCER, P90},
// {SILENCER, M960},
// {SILENCER, MICRO_UZI},
// {SILENCER, M950},
// {SILENCER, MP5},
// {SILENCER, MP5N},
// {SILENCER, FIVE7},
// {SILENCER, P7M8},
// {SILENCER, MSG90A1},
//
// {SNIPERSCOPE, COMMANDO},
// {SNIPERSCOPE, SKS},
// {SNIPERSCOPE, DRAGUNOV},
// {SNIPERSCOPE, M24},
// {SNIPERSCOPE, AUG},
// {SNIPERSCOPE, G41},
// {SNIPERSCOPE, MINI14},
// {SNIPERSCOPE, C7},
// {SNIPERSCOPE, FAMAS},
// {SNIPERSCOPE, AK74},
// {SNIPERSCOPE, AKM},
// {SNIPERSCOPE, M14},
// {SNIPERSCOPE, FNFAL},
// {SNIPERSCOPE, G3A3},
// {SNIPERSCOPE, G11},
// {SNIPERSCOPE, M900},
// {SNIPERSCOPE, BARRETT},
// {SNIPERSCOPE, PSG},
// {SNIPERSCOPE, VAL_SILENT},
// {SNIPERSCOPE, TAR21},
// {SNIPERSCOPE, ENFIELD},
// {SNIPERSCOPE, G36K},
// {SNIPERSCOPE, G36C},
// {SNIPERSCOPE, MSG90A1},
// {SNIPERSCOPE, AK103},
//
// {LASERSCOPE, GLOCK_17},
// {LASERSCOPE, GLOCK_18},
// {LASERSCOPE, BERETTA_92F},
// {LASERSCOPE, BERETTA_93R},
// {LASERSCOPE, SW38},
// {LASERSCOPE, BARRACUDA},
// {LASERSCOPE, DESERTEAGLE},
// {LASERSCOPE, M1911},
// {LASERSCOPE, MP5K},
// {LASERSCOPE, MAC10},
// {LASERSCOPE, THOMPSON},
// {LASERSCOPE, COMMANDO},
// {LASERSCOPE, MP53},
// {LASERSCOPE, AKSU74},
// {LASERSCOPE, P90},
// {LASERSCOPE, TYPE85},
// {LASERSCOPE, SKS},
// {LASERSCOPE, DRAGUNOV},
// {LASERSCOPE, M24},
// {LASERSCOPE, AUG},
// {LASERSCOPE, G41},
// {LASERSCOPE, MINI14},
// {LASERSCOPE, C7},
// {LASERSCOPE, FAMAS},
// {LASERSCOPE, AK74},
// {LASERSCOPE, AKM},
// {LASERSCOPE, M14},
// {LASERSCOPE, FNFAL},
// {LASERSCOPE, G3A3},
// {LASERSCOPE, G11},
// {LASERSCOPE, M870},
// {LASERSCOPE, SPAS15},
// {LASERSCOPE, CAWS},
// {LASERSCOPE, MINIMI},
// {LASERSCOPE, RPK74},
// {LASERSCOPE, HK21E},
// {LASERSCOPE, AUTOMAG_III},
// {LASERSCOPE, MICRO_UZI},
// {LASERSCOPE, M900},
// {LASERSCOPE, M950},
// {LASERSCOPE, M960},
// {LASERSCOPE, BARRETT},
// {LASERSCOPE, PSG},
// {LASERSCOPE, VAL_SILENT},
// {LASERSCOPE, TAR21},
// {LASERSCOPE, ENFIELD},
// {LASERSCOPE, MP5},
// {LASERSCOPE, MP5N},
// {LASERSCOPE, UMP45},
// {LASERSCOPE, MP5SD},
// {LASERSCOPE, FIVE7},
// {LASERSCOPE, P7M8},
// {LASERSCOPE, G36K},
// {LASERSCOPE, G36C},
// {LASERSCOPE, MSG90A1},
// {LASERSCOPE, BENNELLI},
// {LASERSCOPE, AK103},
//
// {BIPOD, SKS},
// {BIPOD, DRAGUNOV},
// {BIPOD, M24},
// {BIPOD, AUG},
// {BIPOD, G41},
// {BIPOD, MINI14},
// {BIPOD, C7},
// {BIPOD, FAMAS},
// {BIPOD, AK74},
// {BIPOD, AKM},
// {BIPOD, M14},
// {BIPOD, FNFAL},
// {BIPOD, G3A3},
// {BIPOD, G11},
// {BIPOD, CAWS},
// {BIPOD, MINIMI},
// {BIPOD, RPK74},
// {BIPOD, HK21E},
// {BIPOD, M900},
// {BIPOD, BARRETT},
// {BIPOD, PSG},
// {BIPOD, VAL_SILENT},
// {BIPOD, TAR21},
// {BIPOD, ENFIELD},
// {BIPOD, MSG90A1},
// {BIPOD, AK103},
//
// {DUCKBILL, M870},
// {DUCKBILL, SPAS15},
// {DUCKBILL, CAWS},
// {DUCKBILL, BENNELLI},
//
// {UNDER_GLAUNCHER, COMMANDO},
// {UNDER_GLAUNCHER, AKSU74},
// {UNDER_GLAUNCHER, AUG},
// {UNDER_GLAUNCHER, G41},
// {UNDER_GLAUNCHER, MINI14},
// {UNDER_GLAUNCHER, C7},
// {UNDER_GLAUNCHER, FAMAS},
// {UNDER_GLAUNCHER, AK74},
// {UNDER_GLAUNCHER, AKM},
// {UNDER_GLAUNCHER, M14},
// {UNDER_GLAUNCHER, FNFAL},
// {UNDER_GLAUNCHER, G3A3},
// {UNDER_GLAUNCHER, TAR21},
// {UNDER_GLAUNCHER, ENFIELD},
// {UNDER_GLAUNCHER, M900},
// {UNDER_GLAUNCHER, G11},
// {UNDER_GLAUNCHER, SKS},
// {UNDER_GLAUNCHER, G36K},
// {UNDER_GLAUNCHER, G36C},
// {UNDER_GLAUNCHER, AK103},
//
// {SPRING_AND_BOLT_UPGRADE, GLOCK_17},
// {SPRING_AND_BOLT_UPGRADE, GLOCK_18},
// {SPRING_AND_BOLT_UPGRADE, BERETTA_92F},
// {SPRING_AND_BOLT_UPGRADE, BERETTA_93R},
// {SPRING_AND_BOLT_UPGRADE, SW38},
// {SPRING_AND_BOLT_UPGRADE, BARRACUDA},
// {SPRING_AND_BOLT_UPGRADE, DESERTEAGLE},
// {SPRING_AND_BOLT_UPGRADE, M1911},
// {SPRING_AND_BOLT_UPGRADE, MP5K},
// {SPRING_AND_BOLT_UPGRADE, MAC10},
// {SPRING_AND_BOLT_UPGRADE, THOMPSON},
// {SPRING_AND_BOLT_UPGRADE, COMMANDO},
// {SPRING_AND_BOLT_UPGRADE, MP53},
// {SPRING_AND_BOLT_UPGRADE, AKSU74},
// {SPRING_AND_BOLT_UPGRADE, P90},
// {SPRING_AND_BOLT_UPGRADE, TYPE85},
// {SPRING_AND_BOLT_UPGRADE, SKS},
// {SPRING_AND_BOLT_UPGRADE, DRAGUNOV},
// {SPRING_AND_BOLT_UPGRADE, M24},
// {SPRING_AND_BOLT_UPGRADE, AUG},
// {SPRING_AND_BOLT_UPGRADE, G41},
// {SPRING_AND_BOLT_UPGRADE, MINI14},
// {SPRING_AND_BOLT_UPGRADE, C7},
// {SPRING_AND_BOLT_UPGRADE, FAMAS},
// {SPRING_AND_BOLT_UPGRADE, AK74},
// {SPRING_AND_BOLT_UPGRADE, AKM},
// {SPRING_AND_BOLT_UPGRADE, M14},
// {SPRING_AND_BOLT_UPGRADE, FNFAL},
// {SPRING_AND_BOLT_UPGRADE, G3A3},
// {SPRING_AND_BOLT_UPGRADE, G11},
// {SPRING_AND_BOLT_UPGRADE, M870},
// {SPRING_AND_BOLT_UPGRADE, SPAS15},
// {SPRING_AND_BOLT_UPGRADE, CAWS},
// {SPRING_AND_BOLT_UPGRADE, MINIMI},
// {SPRING_AND_BOLT_UPGRADE, RPK74},
// {SPRING_AND_BOLT_UPGRADE, HK21E},
// {SPRING_AND_BOLT_UPGRADE, AUTOMAG_III},
// {SPRING_AND_BOLT_UPGRADE, MICRO_UZI},
// {SPRING_AND_BOLT_UPGRADE, M900},
// {SPRING_AND_BOLT_UPGRADE, M950},
// {SPRING_AND_BOLT_UPGRADE, M960},
// {SPRING_AND_BOLT_UPGRADE, BARRETT},
// {SPRING_AND_BOLT_UPGRADE, PSG},
// {SPRING_AND_BOLT_UPGRADE, VAL_SILENT},
// {SPRING_AND_BOLT_UPGRADE, TAR21},
// {SPRING_AND_BOLT_UPGRADE, ENFIELD},
// {SPRING_AND_BOLT_UPGRADE, MP5},
// {SPRING_AND_BOLT_UPGRADE, MP5N},
// {SPRING_AND_BOLT_UPGRADE, UMP45},
// {SPRING_AND_BOLT_UPGRADE, MP5SD},
// {SPRING_AND_BOLT_UPGRADE, FIVE7},
// {SPRING_AND_BOLT_UPGRADE, P7M8},
// {SPRING_AND_BOLT_UPGRADE, G36K},
// {SPRING_AND_BOLT_UPGRADE, G36C},
// {SPRING_AND_BOLT_UPGRADE, MSG90A1},
// {SPRING_AND_BOLT_UPGRADE, BENNELLI},
// {SPRING_AND_BOLT_UPGRADE, AK103},
//
// {GUN_BARREL_EXTENDER, GLOCK_17},
// {GUN_BARREL_EXTENDER, GLOCK_18},
// {GUN_BARREL_EXTENDER, BERETTA_92F},
// {GUN_BARREL_EXTENDER, BERETTA_93R},
// {GUN_BARREL_EXTENDER, SW38},
// {GUN_BARREL_EXTENDER, BARRACUDA},
// {GUN_BARREL_EXTENDER, DESERTEAGLE},
// {GUN_BARREL_EXTENDER, M1911},
// {GUN_BARREL_EXTENDER, MP5K},
// {GUN_BARREL_EXTENDER, MAC10},
// {GUN_BARREL_EXTENDER, THOMPSON},
// {GUN_BARREL_EXTENDER, COMMANDO},
// {GUN_BARREL_EXTENDER, MP53},
// {GUN_BARREL_EXTENDER, AKSU74},
// {GUN_BARREL_EXTENDER, P90},
// {GUN_BARREL_EXTENDER, TYPE85},
// {GUN_BARREL_EXTENDER, SKS},
// {GUN_BARREL_EXTENDER, DRAGUNOV},
// {GUN_BARREL_EXTENDER, M24},
// {GUN_BARREL_EXTENDER, AUG},
// {GUN_BARREL_EXTENDER, G41},
// {GUN_BARREL_EXTENDER, MINI14},
// {GUN_BARREL_EXTENDER, C7},
// {GUN_BARREL_EXTENDER, FAMAS},
// {GUN_BARREL_EXTENDER, AK74},
// {GUN_BARREL_EXTENDER, AKM},
// {GUN_BARREL_EXTENDER, M14},
// {GUN_BARREL_EXTENDER, FNFAL},
// {GUN_BARREL_EXTENDER, G3A3},
// {GUN_BARREL_EXTENDER, G11},
// {GUN_BARREL_EXTENDER, M870},
// {GUN_BARREL_EXTENDER, SPAS15},
// {GUN_BARREL_EXTENDER, CAWS},
// {GUN_BARREL_EXTENDER, MINIMI},
// {GUN_BARREL_EXTENDER, RPK74},
// {GUN_BARREL_EXTENDER, HK21E},
// {GUN_BARREL_EXTENDER, AUTOMAG_III},
// {GUN_BARREL_EXTENDER, MICRO_UZI},
// {GUN_BARREL_EXTENDER, M900},
// {GUN_BARREL_EXTENDER, M950},
// {GUN_BARREL_EXTENDER, M960},
// {GUN_BARREL_EXTENDER, BARRETT},
// {GUN_BARREL_EXTENDER, PSG},
// {GUN_BARREL_EXTENDER, VAL_SILENT},
// {GUN_BARREL_EXTENDER, TAR21},
// {GUN_BARREL_EXTENDER, ENFIELD},
// {GUN_BARREL_EXTENDER, MP5},
// {GUN_BARREL_EXTENDER, MP5N},
// {GUN_BARREL_EXTENDER, UMP45},
// {GUN_BARREL_EXTENDER, MP5SD},
// {GUN_BARREL_EXTENDER, FIVE7},
// {GUN_BARREL_EXTENDER, P7M8},
// {GUN_BARREL_EXTENDER, G36K},
// {GUN_BARREL_EXTENDER, G36C},
// {GUN_BARREL_EXTENDER, MSG90A1},
// {GUN_BARREL_EXTENDER, BENNELLI},
// {GUN_BARREL_EXTENDER, AK103},
//
// {FLASH_SUPPRESSOR, MP5K},
// {FLASH_SUPPRESSOR, MAC10},
// {FLASH_SUPPRESSOR, THOMPSON},
// {FLASH_SUPPRESSOR, COMMANDO},
// {FLASH_SUPPRESSOR, MP53},
// {FLASH_SUPPRESSOR, AKSU74},
// {FLASH_SUPPRESSOR, P90},
// {FLASH_SUPPRESSOR, TYPE85},
// {FLASH_SUPPRESSOR, SKS},
// {FLASH_SUPPRESSOR, DRAGUNOV},
// {FLASH_SUPPRESSOR, M24},
// {FLASH_SUPPRESSOR, AUG},
// {FLASH_SUPPRESSOR, G41},
// {FLASH_SUPPRESSOR, MINI14},
// {FLASH_SUPPRESSOR, C7},
// {FLASH_SUPPRESSOR, FAMAS},
// {FLASH_SUPPRESSOR, AK74},
// {FLASH_SUPPRESSOR, AKM},
// {FLASH_SUPPRESSOR, M14},
// {FLASH_SUPPRESSOR, FNFAL},
// {FLASH_SUPPRESSOR, G3A3},
// {FLASH_SUPPRESSOR, G11},
// {FLASH_SUPPRESSOR, MINIMI},
// {FLASH_SUPPRESSOR, RPK74},
// {FLASH_SUPPRESSOR, HK21E},
// {FLASH_SUPPRESSOR, MICRO_UZI},
// {FLASH_SUPPRESSOR, M900},
// {FLASH_SUPPRESSOR, M950},
// {FLASH_SUPPRESSOR, M960},
// {FLASH_SUPPRESSOR, BARRETT},
// {FLASH_SUPPRESSOR, PSG},
// {FLASH_SUPPRESSOR, VAL_SILENT},
// {FLASH_SUPPRESSOR, TAR21},
// {FLASH_SUPPRESSOR, ENFIELD},
// {FLASH_SUPPRESSOR, MP5},
// {FLASH_SUPPRESSOR, MP5N},
// {FLASH_SUPPRESSOR, UMP45},
// {FLASH_SUPPRESSOR, MP5SD},
// {FLASH_SUPPRESSOR, G36K},
// {FLASH_SUPPRESSOR, G36C},
// {FLASH_SUPPRESSOR, MSG90A1},
// {FLASH_SUPPRESSOR, AK103},
//
// {REFLEX_SCOPED, GLOCK_17},
// {REFLEX_SCOPED, GLOCK_18},
// {REFLEX_SCOPED, BERETTA_92F},
// {REFLEX_SCOPED, BERETTA_93R},
// {REFLEX_SCOPED, SW38},
// {REFLEX_SCOPED, BARRACUDA},
// {REFLEX_SCOPED, DESERTEAGLE},
// {REFLEX_SCOPED, M1911},
// {REFLEX_SCOPED, MP5K},
// {REFLEX_SCOPED, MAC10},
// {REFLEX_SCOPED, THOMPSON},
// {REFLEX_SCOPED, COMMANDO},
// {REFLEX_SCOPED, MP53},
// {REFLEX_SCOPED, AKSU74},
// {REFLEX_SCOPED, P90},
// {REFLEX_SCOPED, TYPE85},
// {REFLEX_SCOPED, SKS},
// {REFLEX_SCOPED, AUG},
// {REFLEX_SCOPED, G41},
// {REFLEX_SCOPED, MINI14},
// {REFLEX_SCOPED, C7},
// {REFLEX_SCOPED, FAMAS},
// {REFLEX_SCOPED, AK74},
// {REFLEX_SCOPED, AKM},
// {REFLEX_SCOPED, M14},
// {REFLEX_SCOPED, FNFAL},
// {REFLEX_SCOPED, G3A3},
// {REFLEX_SCOPED, G11},
// {REFLEX_SCOPED, M870},
// {REFLEX_SCOPED, SPAS15},
// {REFLEX_SCOPED, CAWS},
// {REFLEX_SCOPED, MINIMI},
// {REFLEX_SCOPED, RPK74},
// {REFLEX_SCOPED, HK21E},
// {REFLEX_SCOPED, AUTOMAG_III},
// {REFLEX_SCOPED, MICRO_UZI},
// {REFLEX_SCOPED, M900},
// {REFLEX_SCOPED, M950},
// {REFLEX_SCOPED, M960},
// {REFLEX_SCOPED, TAR21},
// {REFLEX_SCOPED, ENFIELD},
// {REFLEX_SCOPED, MP5},
// {REFLEX_SCOPED, MP5N},
// {REFLEX_SCOPED, UMP45},
// {REFLEX_SCOPED, MP5SD},
// {REFLEX_SCOPED, FIVE7},
// {REFLEX_SCOPED, P7M8},
// {REFLEX_SCOPED, G36K},
// {REFLEX_SCOPED, G36C},
// {REFLEX_SCOPED, BENNELLI},
// {REFLEX_SCOPED, AK103},
//
// {REFLEX_UNSCOPED, GLOCK_17},
// {REFLEX_UNSCOPED, GLOCK_18},
// {REFLEX_UNSCOPED, BERETTA_92F},
// {REFLEX_UNSCOPED, BERETTA_93R},
// {REFLEX_UNSCOPED, SW38},
// {REFLEX_UNSCOPED, BARRACUDA},
// {REFLEX_UNSCOPED, DESERTEAGLE},
// {REFLEX_UNSCOPED, M1911},
// {REFLEX_UNSCOPED, MP5K},
// {REFLEX_UNSCOPED, MAC10},
// {REFLEX_UNSCOPED, THOMPSON},
// {REFLEX_UNSCOPED, COMMANDO},
// {REFLEX_UNSCOPED, MP53},
// {REFLEX_UNSCOPED, AKSU74},
// {REFLEX_UNSCOPED, P90},
// {REFLEX_UNSCOPED, TYPE85},
// {REFLEX_UNSCOPED, SKS},
// {REFLEX_UNSCOPED, DRAGUNOV},
// {REFLEX_UNSCOPED, M24},
// {REFLEX_UNSCOPED, AUG},
// {REFLEX_UNSCOPED, G41},
// {REFLEX_UNSCOPED, MINI14},
// {REFLEX_UNSCOPED, C7},
// {REFLEX_UNSCOPED, FAMAS},
// {REFLEX_UNSCOPED, AK74},
// {REFLEX_UNSCOPED, AKM},
// {REFLEX_UNSCOPED, M14},
// {REFLEX_UNSCOPED, FNFAL},
// {REFLEX_UNSCOPED, G3A3},
// {REFLEX_UNSCOPED, G11},
// {REFLEX_UNSCOPED, M870},
// {REFLEX_UNSCOPED, SPAS15},
// {REFLEX_UNSCOPED, CAWS},
// {REFLEX_UNSCOPED, MINIMI},
// {REFLEX_UNSCOPED, RPK74},
// {REFLEX_UNSCOPED, HK21E},
// {REFLEX_UNSCOPED, AUTOMAG_III},
// {REFLEX_UNSCOPED, MICRO_UZI},
// {REFLEX_UNSCOPED, M900},
// {REFLEX_UNSCOPED, M950},
// {REFLEX_UNSCOPED, M960},
// {REFLEX_UNSCOPED, BARRETT},
// {REFLEX_UNSCOPED, PSG},
// {REFLEX_UNSCOPED, VAL_SILENT},
// {REFLEX_UNSCOPED, TAR21},
// {REFLEX_UNSCOPED, ENFIELD},
// {REFLEX_UNSCOPED, MP5},
// {REFLEX_UNSCOPED, MP5N},
// {REFLEX_UNSCOPED, UMP45},
// {REFLEX_UNSCOPED, MP5SD},
// {REFLEX_UNSCOPED, FIVE7},
// {REFLEX_UNSCOPED, P7M8},
// {REFLEX_UNSCOPED, G36K},
// {REFLEX_UNSCOPED, G36C},
// {REFLEX_UNSCOPED, MSG90A1},
// {REFLEX_UNSCOPED, BENNELLI},
// {REFLEX_UNSCOPED, AK103},
//
// {DETONATOR, TNT},
// {DETONATOR, HMX},
// {DETONATOR, C1},
// {DETONATOR, C4},
//
// {REMDETONATOR, TNT},
// {REMDETONATOR, HMX},
// {REMDETONATOR, C1},
// {REMDETONATOR, C4},
//
// {CERAMIC_PLATES, FLAK_JACKET},
// {CERAMIC_PLATES, FLAK_JACKET_18},
// {CERAMIC_PLATES, FLAK_JACKET_Y},
// {CERAMIC_PLATES, KEVLAR_VEST},
// {CERAMIC_PLATES, KEVLAR_VEST_18},
// {CERAMIC_PLATES, KEVLAR_VEST_Y},
// {CERAMIC_PLATES, SPECTRA_VEST},
// {CERAMIC_PLATES, SPECTRA_VEST_18},
// {CERAMIC_PLATES, SPECTRA_VEST_Y},
// {CERAMIC_PLATES, KEVLAR2_VEST},
// {CERAMIC_PLATES, KEVLAR2_VEST_18},
// {CERAMIC_PLATES, KEVLAR2_VEST_Y},
//
// {SPRING, ALUMINUM_ROD},
// {QUICK_GLUE, STEEL_ROD},
// {DUCT_TAPE, STEEL_ROD},
// {XRAY_BULB, FUMBLE_PAK},
// {CHEWING_GUM, FUMBLE_PAK},
// {BATTERIES, XRAY_DEVICE},
// {COPPER_WIRE, LAME_BOY},
// {COPPER_WIRE, GOLDWATCH},
// {0, 0}
//};
UINT16 Launchable[MAXITEMS+1][2];// =
//{
// {GL_HE_GRENADE, GLAUNCHER},
// {GL_HE_GRENADE, UNDER_GLAUNCHER},
// {GL_TEARGAS_GRENADE, GLAUNCHER},
// {GL_TEARGAS_GRENADE, UNDER_GLAUNCHER},
// {GL_STUN_GRENADE, GLAUNCHER},
// {GL_STUN_GRENADE, UNDER_GLAUNCHER},
// {GL_SMOKE_GRENADE, GLAUNCHER},
// {GL_SMOKE_GRENADE, UNDER_GLAUNCHER},
// {MORTAR_SHELL, MORTAR},
// {TANK_SHELL, TANK_CANNON},
// {RPG_HE_ROCKET, RPG7},
// {RPG_AP_ROCKET, RPG7},
// {RPG_FRAG_ROCKET, RPG7},
// {0, 0}
//};
UINT16 CompatibleFaceItems[MAXITEMS+1][2];// =
//{
// {EXTENDEDEAR, NIGHTGOGGLES},
// {EXTENDEDEAR, UVGOGGLES},
// {EXTENDEDEAR, SUNGOGGLES},
// {EXTENDEDEAR, GASMASK},
// {EXTENDEDEAR, NOTHING},
// {WALKMAN, NIGHTGOGGLES},
// {WALKMAN, UVGOGGLES},
// {WALKMAN, SUNGOGGLES},
// {WALKMAN, GASMASK},
// {WALKMAN, NOTHING},
//
// {NIGHTGOGGLES, EXTENDEDEAR},
// {NIGHTGOGGLES, WALKMAN},
// {NIGHTGOGGLES, ROBOT_REMOTE_CONTROL},
// {NIGHTGOGGLES, GASMASK},
// {NIGHTGOGGLES, NOTHING},
// {SUNGOGGLES, EXTENDEDEAR},
// {SUNGOGGLES, WALKMAN},
// {SUNGOGGLES, GASMASK},
// {SUNGOGGLES, ROBOT_REMOTE_CONTROL},
// {SUNGOGGLES, NOTHING},
// {UVGOGGLES, EXTENDEDEAR},
// {UVGOGGLES, WALKMAN},
// {UVGOGGLES, GASMASK},
// {UVGOGGLES, ROBOT_REMOTE_CONTROL},
// {UVGOGGLES, NOTHING},
// {GASMASK, EXTENDEDEAR},
// {GASMASK, WALKMAN},
// {GASMASK, NIGHTGOGGLES},
// {GASMASK, UVGOGGLES},
// {GASMASK, SUNGOGGLES},
// {GASMASK, ROBOT_REMOTE_CONTROL},
// {GASMASK, NOTHING},
//
// {ROBOT_REMOTE_CONTROL, NIGHTGOGGLES},
// {ROBOT_REMOTE_CONTROL, UVGOGGLES},
// {ROBOT_REMOTE_CONTROL, SUNGOGGLES},
// {ROBOT_REMOTE_CONTROL, GASMASK},
// {ROBOT_REMOTE_CONTROL, NOTHING},
// {0, 0},
//};
UINT16 Merge[MAXITEMS+1][6];// =
//{ // first item second item resulting item, merge type
// {FIRSTAIDKIT, FIRSTAIDKIT, FIRSTAIDKIT, COMBINE_POINTS},
// {MEDICKIT, MEDICKIT, MEDICKIT, COMBINE_POINTS},
// {CANTEEN, CANTEEN, CANTEEN, COMBINE_POINTS},// Madd Combine canteens
// {LOCKSMITHKIT, LOCKSMITHKIT, LOCKSMITHKIT, COMBINE_POINTS},
// {TOOLKIT, TOOLKIT, TOOLKIT, COMBINE_POINTS},
// {GAS_CAN, GAS_CAN, GAS_CAN, COMBINE_POINTS},
// {CAMOUFLAGEKIT, CAMOUFLAGEKIT, CAMOUFLAGEKIT, COMBINE_POINTS},
// {BEER, BEER, BEER, COMBINE_POINTS},
// {WINE, WINE, WINE, COMBINE_POINTS},
// {ALCOHOL, ALCOHOL, ALCOHOL, COMBINE_POINTS},
//
// {COMPOUND18, FLAK_JACKET, FLAK_JACKET_18, TREAT_ARMOUR},
// {COMPOUND18, KEVLAR_VEST, KEVLAR_VEST_18, TREAT_ARMOUR},
// {COMPOUND18, KEVLAR2_VEST, KEVLAR2_VEST_18, TREAT_ARMOUR},
// {COMPOUND18, SPECTRA_VEST, SPECTRA_VEST_18, TREAT_ARMOUR},
// {COMPOUND18, LEATHER_JACKET_W_KEVLAR, LEATHER_JACKET_W_KEVLAR_18, TREAT_ARMOUR},
// {COMPOUND18, KEVLAR_LEGGINGS, KEVLAR_LEGGINGS_18, TREAT_ARMOUR},
// {COMPOUND18, SPECTRA_LEGGINGS, SPECTRA_LEGGINGS_18, TREAT_ARMOUR},
// {COMPOUND18, KEVLAR_HELMET, KEVLAR_HELMET_18, TREAT_ARMOUR},
// {COMPOUND18, SPECTRA_HELMET, SPECTRA_HELMET_18, TREAT_ARMOUR},
// {COMPOUND18, FLAK_JACKET_Y, NOTHING, DESTRUCTION},
// {COMPOUND18, KEVLAR_VEST_Y, NOTHING, DESTRUCTION},
// {COMPOUND18, SPECTRA_VEST_Y, NOTHING, DESTRUCTION},
// {COMPOUND18, LEATHER_JACKET_W_KEVLAR_Y,NOTHING, DESTRUCTION},
// {COMPOUND18, KEVLAR_LEGGINGS_Y, NOTHING, DESTRUCTION},
// {COMPOUND18, SPECTRA_LEGGINGS_Y, NOTHING, DESTRUCTION},
// {COMPOUND18, KEVLAR_HELMET_Y, NOTHING, DESTRUCTION},
// {COMPOUND18, SPECTRA_HELMET_Y, NOTHING, DESTRUCTION},
//
// {JAR_QUEEN_CREATURE_BLOOD, FLAK_JACKET, FLAK_JACKET_Y, TREAT_ARMOUR},
// {JAR_QUEEN_CREATURE_BLOOD, KEVLAR_VEST, KEVLAR_VEST_Y, TREAT_ARMOUR},
// {JAR_QUEEN_CREATURE_BLOOD, SPECTRA_VEST, SPECTRA_VEST_Y, TREAT_ARMOUR},
// {JAR_QUEEN_CREATURE_BLOOD, LEATHER_JACKET_W_KEVLAR, LEATHER_JACKET_W_KEVLAR_Y, TREAT_ARMOUR},
// {JAR_QUEEN_CREATURE_BLOOD, KEVLAR2_VEST, KEVLAR2_VEST_Y, TREAT_ARMOUR},
// {JAR_QUEEN_CREATURE_BLOOD, KEVLAR_LEGGINGS, KEVLAR_LEGGINGS_Y, TREAT_ARMOUR},
// {JAR_QUEEN_CREATURE_BLOOD, SPECTRA_LEGGINGS, SPECTRA_LEGGINGS_Y, TREAT_ARMOUR},
// {JAR_QUEEN_CREATURE_BLOOD, KEVLAR_HELMET, KEVLAR_HELMET_Y, TREAT_ARMOUR},
// {JAR_QUEEN_CREATURE_BLOOD, SPECTRA_HELMET, SPECTRA_HELMET_Y, TREAT_ARMOUR},
// {JAR_QUEEN_CREATURE_BLOOD, FLAK_JACKET_18, NOTHING, DESTRUCTION},
// {JAR_QUEEN_CREATURE_BLOOD, KEVLAR_VEST_18, NOTHING, DESTRUCTION},
// {JAR_QUEEN_CREATURE_BLOOD, KEVLAR2_VEST_18, NOTHING, DESTRUCTION},
// {JAR_QUEEN_CREATURE_BLOOD, SPECTRA_VEST_18, NOTHING, DESTRUCTION},
// {JAR_QUEEN_CREATURE_BLOOD, LEATHER_JACKET_W_KEVLAR_18, NOTHING, DESTRUCTION},
// {JAR_QUEEN_CREATURE_BLOOD, KEVLAR_LEGGINGS_18, NOTHING, DESTRUCTION},
// {JAR_QUEEN_CREATURE_BLOOD, SPECTRA_LEGGINGS_18, NOTHING, DESTRUCTION},
// {JAR_QUEEN_CREATURE_BLOOD, KEVLAR_HELMET_18, NOTHING, DESTRUCTION},
// {JAR_QUEEN_CREATURE_BLOOD, SPECTRA_HELMET_18, NOTHING, DESTRUCTION},
//
// {RDX, TNT, HMX, EXPLOSIVE},
// {RDX, C1, C4, EXPLOSIVE},
// {TNT, RDX, HMX, EXPLOSIVE},
// {C1, RDX, C4, EXPLOSIVE},
//
// {STRING, TIN_CAN, STRING_TIED_TO_TIN_CAN, EASY_MERGE},
// {TIN_CAN, STRING, STRING_TIED_TO_TIN_CAN, EASY_MERGE},
//
// {FLASH_DEVICE, DISPLAY_UNIT, XRAY_DEVICE, ELECTRONIC_MERGE},
// {DISPLAY_UNIT, FLASH_DEVICE, XRAY_DEVICE, ELECTRONIC_MERGE},
//
// {0, 0, 0, 0}
//};
ComboMergeInfoStruct AttachmentComboMerge[MAXITEMS+1];// =
//{
// // base item attach 1 attach 2 result
// {ALUMINUM_ROD, {SPRING, NOTHING}, SPRING_AND_BOLT_UPGRADE },
// {STEEL_ROD, {QUICK_GLUE, DUCT_TAPE}, GUN_BARREL_EXTENDER },
// {FUMBLE_PAK, {XRAY_BULB, CHEWING_GUM}, FLASH_DEVICE },
// {LAME_BOY, {COPPER_WIRE, NOTHING}, DISPLAY_UNIT },
// {GOLDWATCH, {COPPER_WIRE, NOTHING}, DETONATOR},
// {NOTHING, {NOTHING, NOTHING}, NOTHING },
//};
UINT16 IncompatibleAttachments[MAXATTACHMENTS][2];// =
//{
// {BIPOD,UNDER_GLAUNCHER},
// {UNDER_GLAUNCHER,BIPOD},
// {DETONATOR,REMDETONATOR},
// {REMDETONATOR,DETONATOR},
// {SNIPERSCOPE,REFLEX_SCOPED},
// {REFLEX_SCOPED,SNIPERSCOPE},
// {REFLEX_SCOPED,REFLEX_UNSCOPED},
// {REFLEX_UNSCOPED,REFLEX_SCOPED},
// {SILENCER,FLASH_SUPPRESSOR},
// {FLASH_SUPPRESSOR,SILENCER},
// {LASERSCOPE,REFLEX_UNSCOPED},
// {REFLEX_UNSCOPED,LASERSCOPE},
//};
UINT16 ReplacementGuns[][2] =
{
{ BARRACUDA, DESERTEAGLE },
{ M1911, GLOCK_17 },
{ GLOCK_18, BERETTA_93R },
{ BERETTA_92F, GLOCK_17 },
{ TYPE85, BERETTA_93R },
{ THOMPSON, MP5K },
{ MP53, MP5K },
{ SPAS15, M870 },
{ AKSU74, MAC10 },
{ SKS, MINI14 },
{ AKM, G41 },
{ G3A3, G41 },
{ AK74, G41 },
{ DRAGUNOV, M24 },
{ FAMAS, M14 },
{ AUG, C7 },
{ RPK74, MINIMI },
{ HK21E, MINIMI },
{ 0, 0 }
};
UINT16 ReplacementAmmo[][2] =
{
{ CLIP545_30_AP, CLIP556_30_AP },
{ CLIP545_30_HP, CLIP556_30_HP },
{ CLIP762W_10_AP, CLIP762N_5_AP },
{ CLIP762W_30_AP, CLIP762N_20_AP },
{ CLIP762W_10_HP, CLIP762N_5_HP },
{ CLIP762W_30_HP, CLIP762N_20_HP },
{ 0, 0 }
};
// CHRISL: Structure Definitions for new inventory system items.
std::vector<LBETYPE> LoadBearingEquipment;
//LBETYPE LoadBearingEquipment[MAXITEMS+1];
//LBETYPE LoadBearingEquipment[] =
//{
// // Index Class Pocket Types---------------------------------
// { 0, /*Blank Entry*/ 0, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} },
// { 1, /*Default Thigh Pack*/ 0, {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} },
// { 2, /*Default Vest Pack*/ 1, {1, 1, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0} },
// { 3, /*Default Combat Pack*/ 2, {1, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0} },
// { 4, /*Default Back Pack*/ 3, {1, 1, 0, 0, 0, 0, 0, 0, 3, 3, 0, 0} },
// { 5, /*6P Backpack*/ 3, {1, 1, 1, 1, 0, 0, 0, 0, 3, 3, 0, 0} },
// { 6, /*6P Combat Pack*/ 2, {1, 1, 1, 1, 2, 2, 0, 0, 0, 0, 0, 0} }
//};
std::vector<POCKETTYPE> LBEPocketType;
//TODO make the indices of this a define, because I do not know what is a large pocket (I guess 3)
//POCKETTYPE LBEPocketType[MAXITEMS+1]; //=
//{
// { /* Blank Entry */ 0, 0, 0, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} },
// { /* Small General Pocket */ 1, 0, 0, {4, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} },
// { /* Med General Pocket */ 2, 0, 0, {7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} },
// { /* Lg General Pocket */ 3, 0, 0, {10,9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} },
// { /* Gun Sling */ 4, 0, 1, {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} },
// { /* Knife Pocket */ 5, 0, 1, {0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} }
//};
BOOLEAN ItemIsLegal( UINT16 usItemIndex, BOOLEAN fIgnoreCoolness )
{
if ( Item[usItemIndex].ubCoolness == 0 && !fIgnoreCoolness )
return FALSE;
//if the user has selected the reduced gun list
if( !gGameOptions.fGunNut )
{
//if the item is a gun, or ammo
//if( (Item[ usItemIndex ].usItemClass == IC_GUN) || (Item[ usItemIndex ].usItemClass == IC_AMMO )) //Madd: restriction removed
{
// and the item is only available with the extended guns
if( Item[usItemIndex].biggunlist )
{
return(FALSE);
}
}
}
if ( gGameOptions.ubGameStyle != STYLE_SCIFI && Item[usItemIndex].scifi )
{
return FALSE;
}
// CHRISL: Restrict system specific items
if( (UsingNewInventorySystem() == true) )
{
if(Item[usItemIndex].ItemSize == 99)
return FALSE;
}
else
{
if(Item[usItemIndex].usItemClass == IC_LBEGEAR || Item[usItemIndex].newinv)
return FALSE;
}
if(UsingNewAttachmentSystem()==true && Item[usItemIndex].ubAttachmentSystem == 1){
return FALSE;
} else if(UsingNewAttachmentSystem()==false && Item[usItemIndex].ubAttachmentSystem == 2){
return FALSE;
}
return(TRUE);
}
// also used for ammo
BOOLEAN ExtendedGunListGun( UINT16 usGun )
{
// return( (Item[ usGun ].fFlags & ITEM_BIGGUNLIST) != 0 );
return( (Item[ usGun ].biggunlist ) != 0 );
}
UINT16 StandardGunListReplacement( UINT16 usGun )
{
UINT8 ubLoop;
if ( ExtendedGunListGun( usGun ) )
{
ubLoop = 0;
while ( ReplacementGuns[ ubLoop ][ 0 ] != 0 )
{
if ( ReplacementGuns[ ubLoop ][ 0 ] == usGun )
{
return( ReplacementGuns[ ubLoop ][ 1 ] );
}
ubLoop++;
}
// ERROR!
AssertMsg( 0, String( "Extended gun with no replacement %d, CC:0", usGun ) );
return( NOTHING );
}
else
{
return( NOTHING );
}
}
UINT16 StandardGunListAmmoReplacement( UINT16 usAmmo )
{
UINT8 ubLoop;
if ( ExtendedGunListGun( usAmmo ) )
{
ubLoop = 0;
while ( ReplacementAmmo[ ubLoop ][ 0 ] != 0 )
{
if ( ReplacementAmmo[ ubLoop ][ 0 ] == usAmmo )
{
return( ReplacementAmmo[ ubLoop ][ 1 ] );
}
ubLoop++;
}
// ERROR!
AssertMsg( 0, String( "Extended gun with no replacement %d, CC:0", usAmmo ) );
return( NOTHING );
}
else
{
return( NOTHING );
}
}
BOOLEAN WeaponInHand( SOLDIERTYPE * pSoldier )
{
if ( Item[pSoldier->inv[HANDPOS].usItem].usItemClass & (IC_WEAPON | IC_THROWN) && pSoldier->inv[HANDPOS].exists() == true)
{
if (Item[pSoldier->inv[HANDPOS].usItem].fingerprintid )
{
if (pSoldier->inv[HANDPOS][0]->data.ubImprintID != NO_PROFILE)
{
if (pSoldier->ubProfile != NO_PROFILE && pSoldier->ubProfile != MADLAB )
{
if (pSoldier->inv[HANDPOS][0]->data.ubImprintID != pSoldier->ubProfile)
{
return( FALSE );
}
}
else
{
if (pSoldier->inv[HANDPOS][0]->data.ubImprintID != (NO_PROFILE + 1) )
{
return( FALSE );
}
}
}
}
if (pSoldier->inv[HANDPOS][0]->data.gun.bGunStatus >= USABLE)
{
return( TRUE );
}
}
// return -1 or some "broken" value if weapon is broken?
return( FALSE );
}
bool FitsInSmallPocket(OBJECTTYPE* pObj)
{
if (UsingNewInventorySystem() == true) {
return true;
}
return Item[pObj->usItem].ubPerPocket != 0;
}
bool IsBackpackSlot(INT8 bSlot)
{
std::vector<INT8> pocketKey;
GetLBESlots(BPACKPOCKPOS, pocketKey);
for(UINT32 loop = 0; loop < pocketKey.size(); loop++)
{
if(pocketKey[loop] == bSlot)
return true;
}
return false;
}
// CHRISL: New definition for this function so that we can look at soldiers LBE pockets.
UINT8 ItemSlotLimit( OBJECTTYPE * pObject, INT16 bSlot, SOLDIERTYPE *pSoldier, BOOLEAN cntAttach )
{
UINT8 ubSlotLimit;
UINT8 pIndex;
UINT16 usItem, iSize;
UINT16 sSize = 0;
//doesn't matter what inventory method we are using
usItem = pObject->usItem;
// WANNE: This is the problem, why silver nuggets don't stuck, because it is not a MONEY item!!
// We have to check the item class (IC_MONEY) and not the item index!!!
//if (usItem == MONEY)
//{
// //need to have money "stackable" in all slots to trick it into merging
// return 2;
//}
// WANNE: This fixes the stacking problem of silver nuggets!!
if (Item[usItem].usItemClass == IC_MONEY)
{
//need to have money "stackable" in all slots to trick it into merging
return 2;
}
//doesn't matter what inventory method we are using, "body" slots always have a capacity of 1
if(bSlot < BODYPOSFINAL)
return 1;
ubSlotLimit = Item[usItem].ubPerPocket;
if ( ubSlotLimit > MAX_OBJECTS_PER_SLOT ) {
ubSlotLimit = MAX_OBJECTS_PER_SLOT;
}
if (bSlot == STACK_SIZE_LIMIT) {
//if it is stack size limit we want it to be a big slot or a vehicle slot
if (UsingNewInventorySystem() == false)
return (max(1, ubSlotLimit));
else if(pSoldier != NULL && (pSoldier->flags.uiStatusFlags & SOLDIER_VEHICLE))
return (max(1, LBEPocketType[VEHICLE_POCKET_TYPE].ItemCapacityPerSize[__min(34,Item[pObject->usItem].ItemSize)]));
else
return (max(1, min(255,LBEPocketType[VEHICLE_POCKET_TYPE].ItemCapacityPerSize[__min(34,Item[pObject->usItem].ItemSize)]*4)));
}
if (UsingNewInventorySystem() == false) {
if (ubSlotLimit == 0 && bSlot < BIGPOCKFINAL) {
return 1;
}
if (bSlot >= BIGPOCKFINAL && ubSlotLimit > 1)
{
ubSlotLimit /= 2;
}
return( ubSlotLimit );
}
//UsingNewInventorySystem == true
if (pSoldier != NULL && (pSoldier->flags.uiStatusFlags & SOLDIER_VEHICLE)) {
pIndex = VEHICLE_POCKET_TYPE;
}
// IC Group Slots
else if (bSlot == GUNSLINGPOCKPOS) {
pIndex = GUNSLING_POCKET_TYPE;
}
else if (bSlot == KNIFEPOCKPOS) {
pIndex = KNIFE_POCKET_TYPE;
}
else {
Assert(icLBE[bSlot] != -1 && icDefault[bSlot] != -1 && icPocket[bSlot] != -1);
//find the class of the LBE, then find what size the pocket of the slot in the LBE is
if (pSoldier == NULL || pSoldier->inv[icLBE[bSlot]].exists() == false) {
pIndex = LoadBearingEquipment[Item[icDefault[bSlot]].ubClassIndex].lbePocketIndex[icPocket[bSlot]];
}
else {
pIndex = LoadBearingEquipment[Item[pSoldier->inv[icLBE[bSlot]].usItem].ubClassIndex].lbePocketIndex[icPocket[bSlot]];
}
}
//We need to actually check the size of the largest stored item as well as the size of the current item
if(cntAttach == TRUE)
{
iSize = CalculateItemSize(pObject);
if(pSoldier != NULL && pSoldier->inv[bSlot].usItem == pObject->usItem)
{
sSize = CalculateItemSize(&pSoldier->inv[bSlot]);
if(LBEPocketType[pIndex].ItemCapacityPerSize[sSize] < LBEPocketType[pIndex].ItemCapacityPerSize[iSize])
iSize = sSize;
}
}
else
iSize = Item[pObject->usItem].ItemSize;
iSize = __min(iSize,34);
ubSlotLimit = LBEPocketType[pIndex].ItemCapacityPerSize[iSize];
//this could be changed, we know guns are physically able to stack
//if ( iSize < 10 && ubSlotLimit > 1)
// ubSlotLimit = 1;
if(LBEPocketType[pIndex].pRestriction != 0 && !(LBEPocketType[pIndex].pRestriction & Item[usItem].usItemClass)) {
return 0;
}
return( ubSlotLimit );
}
UINT32 MoneySlotLimit( INT8 bSlot )
{
if ( bSlot >= BIGPOCKFINAL ) /* CHRISL */
{
return( MAX_MONEY_PER_SLOT / 2 );
}
else
{
return( MAX_MONEY_PER_SLOT );
}
}
INT8 FindBestWeaponIfCurrentIsOutOfRange(SOLDIERTYPE * pSoldier, INT8 bCurrentWeaponIndex, UINT16 bWantedRange)
{
//assuming current weapon is in the handpos
if (GunRange(&pSoldier->inv[bCurrentWeaponIndex], pSoldier) >= bWantedRange) // SANDRO - added argument
{
//our current weapon is good enough
return( bCurrentWeaponIndex );
}
UINT16 range;
UINT16 bestRange = 0;
INT8 bestWeaponThatMeetsRange = 0;
INT8 secondBestWeapon = 0;
//search for weapons that meet the range, then sort by damage.
//if there are no weapons that meet the range, then use the longest range we can find
for (INT8 bLoop = 0; bLoop < (INT8) pSoldier->inv.size(); bLoop++)
{
//if this is a weapon
if (Item[pSoldier->inv[bLoop].usItem].usItemClass & (IC_WEAPON | IC_THROWN) && pSoldier->inv[bLoop].exists() == true)
{
range = GunRange(&pSoldier->inv[bLoop], pSoldier); // SANDRO - added argument
if (range >= bWantedRange)
{
if (bestWeaponThatMeetsRange == 0)
{
bestWeaponThatMeetsRange = bLoop;
}
else if (GetDamage(&pSoldier->inv[bLoop]) > GetDamage(&pSoldier->inv[bestWeaponThatMeetsRange]))
{
//does this weapon have more damage?
bestWeaponThatMeetsRange = bLoop;
}
}
else if (range > bestRange)
{
//weapon does not meet range, but it could be better anyways
bestRange = range;
secondBestWeapon = bLoop;
}
else if (range == bestRange)
{
//weapon ties with secondBestWeapon's range
if (secondBestWeapon == 0)
{
//this if can happen if range of bLoop is 0!
secondBestWeapon = bLoop;
}
else if (GetDamage(&pSoldier->inv[bLoop]) > GetDamage(&pSoldier->inv[secondBestWeapon]))
{
secondBestWeapon = bLoop;
}
}
}
}
if (bestWeaponThatMeetsRange)
{
return bestWeaponThatMeetsRange;
}
else if (secondBestWeapon)
{
return secondBestWeapon;
}
return( bCurrentWeaponIndex );
}
INT8 FindMetalDetector( SOLDIERTYPE * pSoldier )
{
INT8 bLoop;
for (bLoop = 0; bLoop < (INT8) pSoldier->inv.size(); bLoop++)
{
if (Item[pSoldier->inv[bLoop].usItem].metaldetector && pSoldier->inv[bLoop].exists() == true)
{
return( bLoop );
}
}
return( NO_SLOT );
}
INT8 FindLockBomb( SOLDIERTYPE * pSoldier )
{
INT8 bLoop;
for (bLoop = 0; bLoop < (INT8) pSoldier->inv.size(); bLoop++)
{
if (Item[pSoldier->inv[bLoop].usItem].lockbomb && pSoldier->inv[bLoop].exists() == true)
{
return( bLoop );
}
}
return( NO_SLOT );
}
INT8 FindUsableObj( SOLDIERTYPE * pSoldier, UINT16 usItem )
{
INT8 bLoop;
for (bLoop = 0; bLoop < (INT8) pSoldier->inv.size(); bLoop++)
{
if ( pSoldier->inv[bLoop].usItem == usItem
&& pSoldier->inv[bLoop].exists() == true
&& pSoldier->inv[bLoop][0]->data.objectStatus >= USABLE )
{
return( bLoop );
}
}
return( NO_SLOT );
}
INT8 FindObjExcludingSlot( SOLDIERTYPE * pSoldier, UINT16 usItem, INT8 bExcludeSlot )
{
INT8 bLoop;
for (bLoop = 0; bLoop < (INT8)pSoldier->inv.size(); bLoop++)
{
if (bLoop == bExcludeSlot)
{
continue;
}
if (pSoldier->inv[bLoop].usItem == usItem && pSoldier->inv[bLoop].exists() == true)
{
return( bLoop );
}
}
return( NO_SLOT );
}
INT8 FindObj( SOLDIERTYPE * pSoldier, UINT16 usItem, INT8 bLower, INT8 bUpper )
{
INT8 bLoop;
for (bLoop = bLower; bLoop < bUpper; bLoop++)
{
//CHRISL: If in NIV, in combat and backpack is closed, don't look inside
if(UsingNewAttachmentSystem() == true && (gTacticalStatus.uiFlags & INCOMBAT) && IsBackpackSlot(bLoop) == true && pSoldier->flags.ZipperFlag == FALSE)
continue;
//CHRISL: If we check exists() then we can't search for an empty pocket with this function, which is done.
if (pSoldier->inv[bLoop].usItem == usItem/* && pSoldier->inv[bLoop].exists() == true*/)
{
return( bLoop );
}
}
return( ITEM_NOT_FOUND );
}
INT8 FindObjInObjRange( SOLDIERTYPE * pSoldier, UINT16 usItem1, UINT16 usItem2 )
{
INT8 bLoop;
UINT16 usTemp;
if (usItem1 > usItem2 )
{
// swap the two...
usTemp = usItem2;
usItem2 = usItem1;
usItem1 = usTemp;
}
for (bLoop = 0; bLoop < (INT8) pSoldier->inv.size(); bLoop++)
{
usTemp = pSoldier->inv[bLoop].usItem;
if ( usTemp >= usItem1 && usTemp <= usItem2 && pSoldier->inv[bLoop].exists() == true)
{
return( bLoop );
}
}
return( ITEM_NOT_FOUND );
}
INT8 FindObjClass( SOLDIERTYPE * pSoldier, UINT32 usItemClass )
{
INT8 bLoop;
for (bLoop = 0; bLoop < (INT8)pSoldier->inv.size(); bLoop++)
{
if (Item[pSoldier->inv[bLoop].usItem].usItemClass & usItemClass && pSoldier->inv[bLoop].exists() == true)
{
return( bLoop );
}
}
return( NO_SLOT );
}
INT8 FindAIUsableObjClass( SOLDIERTYPE * pSoldier, UINT32 usItemClass )
{
// finds the first object of the specified class which does NOT have
// the "unusable by AI" flag set.
// uses & rather than == so that this function can search for any weapon
INT8 bLoop;
// This is for the AI only so:
// Do not consider tank cannons or rocket launchers to be "guns"
for (bLoop = 0; bLoop < (INT8) pSoldier->inv.size(); bLoop++)
{
if (pSoldier->inv[bLoop].exists() == true) {
if ( (Item[pSoldier->inv[bLoop].usItem].usItemClass & usItemClass) && !(pSoldier->inv[bLoop].fFlags & OBJECT_AI_UNUSABLE) && (pSoldier->inv[bLoop][0]->data.objectStatus >= USABLE ) )
{
if ( usItemClass == IC_GUN && EXPLOSIVE_GUN( pSoldier->inv[bLoop].usItem ) )
{
continue;
}
return( bLoop );
}
}
}
return( NO_SLOT );
}
INT8 FindAIUsableObjClassWithin( SOLDIERTYPE * pSoldier, UINT32 usItemClass, INT8 bLower, INT8 bUpper )
{
INT8 bLoop;
// This is for the AI only so:
// Do not consider tank cannons or rocket launchers to be "guns"
for (bLoop = bLower; bLoop < bUpper; bLoop++)
{
if (pSoldier->inv[bLoop].exists() == true) {
if ( (Item[pSoldier->inv[bLoop].usItem].usItemClass & usItemClass) && !(pSoldier->inv[bLoop].fFlags & OBJECT_AI_UNUSABLE) && (pSoldier->inv[bLoop][0]->data.objectStatus >= USABLE ) )
{
if ( usItemClass == IC_GUN && EXPLOSIVE_GUN( pSoldier->inv[bLoop].usItem ) )
{
continue;
}
return( bLoop );
}
}
}
return( NO_SLOT );
}
INT8 FindEmptySlotWithin( SOLDIERTYPE * pSoldier, INT8 bLower, INT8 bUpper )
{
INT8 bLoop;
for (bLoop = bLower; bLoop < bUpper; bLoop++)
{
// CHRISL: Only look at valid pockets
if((UsingNewInventorySystem() == false) && !oldInv[bLoop])
continue;
if((pSoldier->flags.uiStatusFlags & SOLDIER_VEHICLE) && !vehicleInv[bLoop])
continue;
if (pSoldier->inv[bLoop].exists() == false)
{
if (bLoop == SECONDHANDPOS && Item[pSoldier->inv[HANDPOS].usItem].twohanded )
{
continue;
}
else
{
return( bLoop );
}
}
}
return( ITEM_NOT_FOUND );
}
BOOLEAN GLGrenadeInSlot(SOLDIERTYPE *pSoldier, INT8 bSlot )
{
if (pSoldier->inv[bSlot].exists() == true) {
if (Item[pSoldier->inv[bSlot].usItem].glgrenade)
return TRUE;
}
//switch (pSoldier->inv[bSlot].usItem)
//{
// case GL_HE_GRENADE:
// case GL_TEARGAS_GRENADE:
// case GL_STUN_GRENADE:
// case GL_SMOKE_GRENADE:
// return(TRUE);
// default:
// return(FALSE);
//}
return FALSE;
}
// for grenade launchers
INT8 FindGLGrenade( SOLDIERTYPE * pSoldier )
{
INT8 bLoop;
for (bLoop = 0; bLoop < (INT8)pSoldier->inv.size(); bLoop++)
{
if (GLGrenadeInSlot( pSoldier, bLoop ))
{
return( bLoop );
}
}
return( NO_SLOT );
}
INT8 FindThrowableGrenade( SOLDIERTYPE * pSoldier )
{
INT8 bLoop;
BOOLEAN fCheckForFlares = FALSE;
// JA2Gold: give some priority to looking for flares when at night
// this is AI only so we can put in some customization for night
if (GetTimeOfDayAmbientLightLevel() == NORMAL_LIGHTLEVEL_NIGHT)
{
if (pSoldier->stats.bLife > (pSoldier->stats.bLifeMax / 2))
{
fCheckForFlares = TRUE;
}
}
if (fCheckForFlares)
{
// Do a priority check for flares first
for (bLoop = 0; bLoop < (INT8)pSoldier->inv.size(); bLoop++)
{
if (pSoldier->inv[bLoop].exists() == true) {
if ( Item[pSoldier->inv[ bLoop ].usItem].flare )
{
return( bLoop );
}
}
}
}
for (bLoop = 0; bLoop < (INT8)pSoldier->inv.size(); bLoop++)
{
if (pSoldier->inv[bLoop].exists() == true) {
if ( (Item[ pSoldier->inv[ bLoop ].usItem ].usItemClass & IC_GRENADE) && // Try this check instead, to avoid tossing RPG rounds !GLGrenadeInSlot( pSoldier, bLoop ) &&
GetLauncherFromLaunchable( pSoldier->inv[ bLoop ].usItem) == NOTHING )
{
return( bLoop );
}
}
}
return( NO_SLOT );
}
INT16 FindAttachmentSlot( OBJECTTYPE* pObj, UINT16 usItem, UINT8 subObject)
{
if(UsingNewAttachmentSystem()==false || pObj->exists() == false)
return -1;
UINT8 loop = 0;
for(attachmentList::iterator iter = (*pObj)[subObject]->attachments.begin(); iter != (*pObj)[subObject]->attachments.end(); iter++, loop++){
if(iter->exists() && iter->usItem == usItem)
return loop;
}
return -1;
}
OBJECTTYPE* FindAttachment( OBJECTTYPE * pObj, UINT16 usItem, UINT8 subObject )
{
if (pObj->exists() == true) {
for (attachmentList::iterator iter = (*pObj)[subObject]->attachments.begin(); iter != (*pObj)[subObject]->attachments.end(); ++iter) {
if (iter->usItem == usItem && iter->exists())
{
return &(*iter);
}
}
}
return( 0 );
}
OBJECTTYPE* FindAttachmentByClass( OBJECTTYPE * pObj, UINT32 uiItemClass, UINT8 subObject )
{
if (pObj->exists() == true) {
for (attachmentList::iterator iter = (*pObj)[subObject]->attachments.begin(); iter != (*pObj)[subObject]->attachments.end(); ++iter) {
if (Item[iter->usItem].usItemClass == uiItemClass && iter->exists())
{
return &(*iter);
}
}
}
return( 0 );
}
INT8 FindLaunchable( SOLDIERTYPE * pSoldier, UINT16 usWeapon )
{
INT8 bLoop;
DebugMsg(TOPIC_JA2, DBG_LEVEL_3, String("FindLaunchable: weapon=%d",usWeapon));
for (bLoop = 0; bLoop < (INT8)pSoldier->inv.size(); bLoop++)
{
if (pSoldier->inv[bLoop].exists() == true) {
if ( ValidLaunchable( pSoldier->inv[ bLoop ].usItem , usWeapon ) )
{
DebugMsg(TOPIC_JA2, DBG_LEVEL_3, String("FindLaunchable: returning slot %d",bLoop));
return( bLoop );
}
}
}
DebugMsg(TOPIC_JA2, DBG_LEVEL_3, String("FindLaunchable: item not found"));
return( ITEM_NOT_FOUND );
}
INT8 FindNonSmokeLaunchable( SOLDIERTYPE * pSoldier, UINT16 usWeapon )
{
INT8 bLoop;
DebugMsg(TOPIC_JA2, DBG_LEVEL_3, String("FindNonSmokeLaunchable: weapon=%d",usWeapon));
for (bLoop = 0; bLoop < (INT8)pSoldier->inv.size(); bLoop++)
{
if (pSoldier->inv[bLoop].exists() == true) {
if ( ValidLaunchable( pSoldier->inv[ bLoop ].usItem , usWeapon ) && Explosive[Item[pSoldier->inv[ bLoop ].usItem].ubClassIndex].ubType != EXPLOSV_SMOKE )
{
DebugMsg(TOPIC_JA2, DBG_LEVEL_3, String("FindNonSmokeLaunchable: returning slot %d",bLoop));
return( bLoop );
}
}
}
DebugMsg(TOPIC_JA2, DBG_LEVEL_3, String("FindNonSmokeLaunchable: item not found, so find items including smoke"));
return( FindLaunchable(pSoldier,usWeapon) );
}
OBJECTTYPE* FindLaunchableAttachment( OBJECTTYPE * pObj, UINT16 usWeapon )
{
if (pObj->exists() == true) {
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if (ValidLaunchable( iter->usItem, usWeapon) && iter->exists())
{
return &(*iter);
}
}
}
return( 0 );
}
//CHRISL: This function attempts to find a legal, single-shot grenade item based on the illegal, multi-shot one we send it
UINT16 FindLegalGrenade(UINT16 usItem)
{
UINT16 newItem = 0;
UINT16 usClass = Item[usItem].ubClassIndex;
if(UsingNewAttachmentSystem()==false)
return usItem;
for(UINT16 loop = 0; loop < MAXITEMS+1; loop++){
if(loop == usClass)
continue;
if(Explosive[usClass].ubType == Explosive[loop].ubType && Explosive[usClass].ubDamage == Explosive[loop].ubDamage
&& Explosive[usClass].ubStunDamage == Explosive[loop].ubStunDamage && Explosive[usClass].ubRadius == Explosive[loop].ubRadius
&& Explosive[usClass].ubVolume == Explosive[loop].ubVolume && Explosive[usClass].ubVolatility == Explosive[loop].ubVolatility
&& Explosive[usClass].ubAnimationID == Explosive[loop].ubAnimationID && Explosive[usClass].ubDuration == Explosive[loop].ubDuration
&& Explosive[usClass].ubStartRadius == Explosive[loop].ubStartRadius && Explosive[loop].ubMagSize == 1){
newItem = loop;
break;
}
if(Explosive[loop].uiIndex == 0 && loop > 0)
break;
}
if(newItem > 0){
for(UINT16 loop = 1; loop < MAXITEMS+1; loop++){
if(Item[loop].uiIndex == 0)
break;
if(Item[loop].usItemClass & IC_GRENADE && Item[loop].ubClassIndex == newItem){
return Item[loop].uiIndex;
}
}
}
return usItem;
}
OBJECTTYPE* FindNonSmokeLaunchableAttachment( OBJECTTYPE * pObj, UINT16 usWeapon )
{
if (pObj->exists() == true) {
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if (ValidLaunchable( iter->usItem, usWeapon) && Explosive[Item[iter->usItem].ubClassIndex].ubType != EXPLOSV_SMOKE && iter->exists())
{
return &(*iter);
}
}
}
return( FindLaunchableAttachment(pObj,usWeapon) );
}
//Simple check to see if the item has any attachments
BOOLEAN ItemHasAttachments( OBJECTTYPE * pObj, SOLDIERTYPE * pSoldier, UINT8 iter )
{
if (pObj->exists() == true) {
if(pSoldier != NULL){
for (iter = 0; iter != pObj->objectStack.size(); ++iter) {
if((*pObj)[iter]->AttachmentListSize() > 0){
return TRUE;
}
}
}
else{
if((*pObj)[iter]->AttachmentListSize() > 0){
return TRUE;
}
}
}
return FALSE;
}
// Determine if it is possible to add this attachment to the CLASS of this item
// (i.e. to any item in the class)
BOOLEAN ValidAttachmentClass( UINT16 usAttachment, UINT16 usItem )
{
INT32 iLoop = 0;
while( 1 )
{
// see comment for AttachmentInfo array for why we skip IC_NONE
if ( AttachmentInfo[ iLoop ].uiItemClass != IC_NONE )
{
if ( AttachmentInfo[ iLoop ].usItem == usAttachment )
{
if ( AttachmentInfo[ iLoop ].uiItemClass == Item[ usItem ].usItemClass )
{
return( TRUE );
}
}
}
iLoop++;
if (AttachmentInfo[iLoop].usItem == 0)
{
// end of the array
break;
}
}
return( FALSE );
}
INT8 GetAttachmentInfoIndex( UINT16 usItem )
{
INT32 iLoop = 0;
while( 1 )
{
if ( AttachmentInfo[ iLoop ].usItem == usItem )
{
return( (INT8) iLoop );
}
iLoop++;
if (AttachmentInfo[iLoop].usItem == 0)
{
// end of the array
break;
}
}
return( -1 );
}
//Determine if it is possible to add this attachment to the item.
BOOLEAN ValidAttachment( UINT16 usAttachment, UINT16 usItem, UINT8 * pubAPCost )
{
INT32 iLoop = 0;
if (pubAPCost) {
*pubAPCost = (UINT8)APBPConstants[AP_RELOAD_GUN]; //default value
}
// look for the section of the array pertaining to this attachment...
while( 1 )
{
if (Attachment[iLoop][0] == usAttachment)
{
break;
}
iLoop++;
if (Attachment[iLoop][0] == 0)
{
// the proposed item cannot be attached to anything!
return( FALSE );
}
}
// now look through this section for the item in question
while( 1 )
{
if (Attachment[iLoop][1] == usItem)
{
if((UsingNewAttachmentSystem()==false && Attachment[iLoop][3] != 1) || UsingNewAttachmentSystem()==true) {
if (pubAPCost) {
*pubAPCost = (UINT8)Attachment[iLoop][2]; //Madd: get ap cost of attaching items :)
}
break;
}
}
iLoop++;
if (Attachment[iLoop][0] != usAttachment)
{
// the proposed item cannot be attached to the item in question
return( FALSE );
}
}
return( TRUE );
}
BOOLEAN ValidAttachment( UINT16 usAttachment, OBJECTTYPE * pObj, UINT8 * pubAPCost, UINT8 subObject, std::vector<UINT16> usAttachmentSlotIndexVector )
{
if (pObj->exists() == false) {
return FALSE;
}
if(UsingNewAttachmentSystem()==true)
{
UINT16 usSlotIndex = 0;
BOOLEAN foundValidAttachment = FALSE;
UINT16 usLoop = 0;
//It's possible we've entered this function without being passed the usAttachmentSlotIndexVector parameter
if(usAttachmentSlotIndexVector.empty())
usAttachmentSlotIndexVector = GetItemSlots(pObj);
//Still no slots means nothing will ever be valid
if(usAttachmentSlotIndexVector.empty())
return FALSE;
//Check if the attachment is valid with the main item
foundValidAttachment = (ValidAttachment(usAttachment, pObj->usItem, pubAPCost) || ValidLaunchable(usAttachment, pObj->usItem));
//Loop through all attachment points on the main item
for(attachmentList::iterator iter = (*pObj)[subObject]->attachments.begin(); iter != (*pObj)[subObject]->attachments.end() && !foundValidAttachment; ++iter)
{
if(iter->exists())
foundValidAttachment = (ValidAttachment(usAttachment, iter->usItem, pubAPCost) || ValidLaunchable(usAttachment, iter->usItem));
}
return ( foundValidAttachment );
}
else
{
return( ValidAttachment(usAttachment, pObj->usItem, pubAPCost) );
}
}
UINT8 AttachmentAPCost( UINT16 usAttachment, UINT16 usItem, SOLDIERTYPE * pSoldier ) // SANDRO - added argument
{
UINT8 ubAPCost;
ValidAttachment( usAttachment, usItem, &ubAPCost);
// SANDRO - STOMP traits - Ambidextrous attaching objects speed bonus
if ( pSoldier != NULL )
{
if ( gGameOptions.fNewTraitSystem && HAS_SKILL_TRAIT( pSoldier, AMBIDEXTROUS_NT ) )
{
ubAPCost = (UINT8)((ubAPCost * (100 - gSkillTraitValues.ubAMAttachingItemsAPsReduction) / 100) + 0.5);
}
}
return ubAPCost;
}
//Also need one with pObj, for the one with usItem is not always correct.
UINT8 AttachmentAPCost( UINT16 usAttachment, OBJECTTYPE * pObj, SOLDIERTYPE * pSoldier, UINT8 subObject, std::vector<UINT16> usAttachmentSlotIndexVector )
{
UINT8 ubAPCost;
ValidAttachment(usAttachment, pObj, &ubAPCost, subObject, usAttachmentSlotIndexVector);
// SANDRO - STOMP traits - Ambidextrous attaching objects speed bonus
if ( pSoldier != NULL )
{
if ( gGameOptions.fNewTraitSystem && HAS_SKILL_TRAIT( pSoldier, AMBIDEXTROUS_NT ) )
{
ubAPCost = (UINT8)((ubAPCost * (100 - gSkillTraitValues.ubAMAttachingItemsAPsReduction) / 100) + 0.5);
}
}
return ubAPCost;
}
//Determine if this slot can receive this attachment. This is different, in that it may
//be possible to have this attachment on this item, but may already have an attachment
//in the slot we're trying to attach to.
BOOLEAN ValidItemAttachmentSlot( OBJECTTYPE * pObj, UINT16 usAttachment, BOOLEAN fAttemptingAttachment, BOOLEAN fDisplayMessage, UINT8 subObject, INT16 slotCount, BOOLEAN fIgnoreAttachmentInSlot, OBJECTTYPE ** ppAttachInSlot, std::vector<UINT16> usAttachmentSlotIndexVector)
{
BOOLEAN fSimilarItems = FALSE, fSameItem = FALSE;
UINT16 usSimilarItem = NOTHING;
INT16 ubSlotIndex = 0;
INT32 iLoop2 = 0;
INT16 sTimesToRun = 0;
UINT8 curSlot = 0;
BOOLEAN foundValidAttachment = FALSE;
if (pObj->exists() == false) {
return FALSE;
}
//It's possible we could get here without being sent the usAttachmentSlotIndexVector parameter
if(usAttachmentSlotIndexVector.empty())
usAttachmentSlotIndexVector = GetItemSlots(pObj, subObject);
//No slots means nothing will ever be valid, also a slotCount outside this vector will never be valid either.
if(usAttachmentSlotIndexVector.empty() || (INT16)usAttachmentSlotIndexVector.size() <= slotCount)
return FALSE;
//Search for incompatible attachments
for(int i = 0;i<sizeof(IncompatibleAttachments);i++)
{
if ( FindAttachment(pObj, usAttachment, subObject) != 0 && !(Item[usAttachment].nasAttachmentClass & AC_GRENADE) && !(Item[usAttachment].nasAttachmentClass & AC_ROCKET))
{//Search for identical attachments unless we're dealing with rifle grenades
fSameItem = TRUE;
break;
}
if ( IncompatibleAttachments[i][0] == NONE )
break;
if ( IncompatibleAttachments[i][0] == usAttachment && FindAttachment (pObj,IncompatibleAttachments[i][1],subObject) != 0 )
{
fSimilarItems = TRUE;
usSimilarItem = IncompatibleAttachments[i][1];
break;
}
}
//Do we want to check all attachment slots or just the one in slotcount?
if(slotCount == -1){
//Loop through slots
for(UINT8 curSlot = 0; curSlot < (*pObj)[subObject]->attachments.size() && !foundValidAttachment; curSlot++){
//Any attachment that is already in this slot will go here.
OBJECTTYPE * pAttachment;
//Get the current attachment in the slot we're looking at.
pAttachment = (*pObj)[subObject]->GetAttachmentAtIndex(curSlot);
ubSlotIndex = usAttachmentSlotIndexVector[curSlot];
//WarmSteel - does this particular slot already hold an item?
if(ppAttachInSlot && pAttachment->exists() )
*ppAttachInSlot = pAttachment;
//Search for any valid attachments in this slot
//CHRISL: Valid attachments are determined by the old "ValidItemAttachment" function and comparing the attachment class of the item and slot
if(AttachmentSlots[ubSlotIndex].nasAttachmentClass & Item[usAttachment].nasAttachmentClass &&
(ValidItemAttachment(pObj,usAttachment,fAttemptingAttachment,fDisplayMessage,subObject,usAttachmentSlotIndexVector) ||
ValidLaunchable(usAttachment, GetAttachedGrenadeLauncher(pObj)) ||
ValidLaunchable(usAttachment, pObj->usItem)))
{
foundValidAttachment = TRUE;
}
}
} else {
OBJECTTYPE * pAttachment;
pAttachment = (*pObj)[subObject]->GetAttachmentAtIndex((UINT8)slotCount);
ubSlotIndex = usAttachmentSlotIndexVector[slotCount];
//WarmSteel - does this particular slot already hold an item? :( If we have a pAttachInSlot we're trying to switch, so then it doesn't matter.
if(!fIgnoreAttachmentInSlot && pAttachment->exists() && fAttemptingAttachment && (!ppAttachInSlot || Item[pAttachment->usItem].inseparable)){
//If we have a parameter to return pAttachment to, store it, else the item does not attach to this slot.
fSimilarItems = TRUE;
usSimilarItem = pAttachment->usItem;
} else {
//CHRISL: This should allow attachment swapping even if our attachments can't normally be on the weapon at the same time.
if(slotCount != -1 && pAttachment->exists() && usSimilarItem == pAttachment->usItem && FindAttachmentSlot(pObj, pAttachment->usItem, subObject) == slotCount)
fSimilarItems = FALSE;
//If we have an item to return the existing attachment to.
if(ppAttachInSlot && pAttachment->exists())
*ppAttachInSlot = pAttachment;
//Search for any valid attachments in this slot
//CHRISL: Valid attachments are determined by the old "ValidItemAttachment" function and comparing the attachment class of the item and slot
if(AttachmentSlots[ubSlotIndex].nasAttachmentClass & Item[usAttachment].nasAttachmentClass &&
(ValidItemAttachment(pObj,usAttachment,FALSE,FALSE,subObject,usAttachmentSlotIndexVector) ||
ValidLaunchable(usAttachment, GetAttachedGrenadeLauncher(pObj)) ||
ValidLaunchable(usAttachment, pObj->usItem)))
{
foundValidAttachment = TRUE;
}
}
}
if(fAttemptingAttachment){
if (fSimilarItems)
{
if(fDisplayMessage) ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_UI_FEEDBACK, Message[ STR_CANT_USE_TWO_ITEMS ], ItemNames[ usSimilarItem ], ItemNames[ usAttachment ] );
return( FALSE );
}
else if (fSameItem)
{
if (fDisplayMessage) ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_UI_FEEDBACK, Message[ STR_ATTACHMENT_ALREADY ] );
return( FALSE );
}
else if ( !foundValidAttachment && fDisplayMessage && !ValidMerge( usAttachment, pObj->usItem ) )
{
//We don't want a message if we might be merging this little thingey later.
//well, maybe the player thought he could
CHAR16 zTemp[ 100 ];
swprintf( zTemp, Message[ STR_CANNOT_ATTACH_SLOT ], ItemNames[ usAttachment ] );
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_UI_FEEDBACK, zTemp );
}
}
return( foundValidAttachment );
}
//Determine if this item can receive this attachment. This is different, in that it may
//be possible to have this attachment on this item, but may already have an attachment on
//it which doesn't work simultaneously with the new attachment (like a silencer and duckbill).
BOOLEAN ValidItemAttachment( OBJECTTYPE * pObj, UINT16 usAttachment, BOOLEAN fAttemptingAttachment, BOOLEAN fDisplayMessage, UINT8 subObject, std::vector<UINT16> usAttachmentSlotIndexVector )
{
BOOLEAN fSameItem = FALSE, fSimilarItems = FALSE;
UINT16 usSimilarItem = NOTHING;
if (pObj->exists() == false) {
return FALSE;
}
if ( !ValidAttachment( usAttachment, pObj, NULL, subObject, usAttachmentSlotIndexVector ) )
{
// check for an underslung grenade launcher attached to the gun
if ( (IsGrenadeLauncherAttached ( pObj, subObject ) ) && ValidLaunchable( usAttachment, GetAttachedGrenadeLauncher( pObj ) ) )
{
return ( TRUE );
/*
if ( fAttemptingAttachment )
{
// if there is no other grenade attached already, then we can attach it
if (FindAttachmentByClass( pObj, IC_GRENADE) != ITEM_NOT_FOUND)
{
return( FALSE );
}
// keep going, it can be attached to the grenade launcher
}
else
{
// logically, can be added
return( TRUE );
}
*/
}
else
{
if ( fAttemptingAttachment && ValidAttachmentClass( usAttachment, pObj->usItem ) )
{
// well, maybe the player thought he could
CHAR16 zTemp[ 100 ];
swprintf( zTemp, Message[ STR_CANT_ATTACH ], ItemNames[ usAttachment ], ItemNames[ pObj->usItem ] );
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_UI_FEEDBACK, zTemp );
}
return( FALSE );
}
}
// special conditions go here
// can't have two of the same attachment on an item
/*
if (FindAttachment( pObj, usAttachment ) != 0)
{
fSameItem = TRUE;
}
*/
for(int i = 0;i<sizeof(IncompatibleAttachments);i++)
{
if ( FindAttachment(pObj, usAttachment, subObject) != 0 )
{
fSameItem = TRUE;
break;
}
if ( IncompatibleAttachments[i][0] == NONE )
break;
if ( IncompatibleAttachments[i][0] == usAttachment && FindAttachment (pObj,IncompatibleAttachments[i][1],subObject) != 0 )
{
fSimilarItems = TRUE;
usSimilarItem = IncompatibleAttachments[i][1];
break;
}
}
//// special code for items which won't attach if X is present
//switch( usAttachment )
//{
// case BIPOD:
// if ( FindAttachment( pObj, UNDER_GLAUNCHER) != 0 )
// {
// fSimilarItems = TRUE;
// usSimilarItem = UNDER_GLAUNCHER;
// }
// break;
// case UNDER_GLAUNCHER:
// if ( FindAttachment( pObj, BIPOD ) != 0 )
// {
// fSimilarItems = TRUE;
// usSimilarItem = BIPOD;
// }
// break;
///*
// case LASERSCOPE:
// if (FindAttachment( pObj, SNIPERSCOPE ) != 0)
// {
// return( FALSE );
// }
// break;
// case SNIPERSCOPE:
// if (FindAttachment( pObj, LASERSCOPE ) != 0)
// {
// return( FALSE );
// }
// break;
// */
// case DETONATOR:
// if( FindAttachment( pObj, REMDETONATOR ) != 0 )
// {
// fSameItem = TRUE;
// }
// break;
// case REMDETONATOR:
// if( FindAttachment( pObj, DETONATOR ) != 0 )
// {
// fSameItem = TRUE;
// }
// break;
// case SNIPERSCOPE:
// if( FindAttachment( pObj, REFLEX_SCOPED ) != 0 )
// {
// fSimilarItems = TRUE;
// usSimilarItem = REFLEX_SCOPED;
// }
// break;
// case REFLEX_SCOPED:
// if( FindAttachment( pObj, SNIPERSCOPE ) != 0 )
// {
// fSimilarItems = TRUE;
// usSimilarItem = SNIPERSCOPE;
// }
// if( FindAttachment( pObj, REFLEX_UNSCOPED ) != 0 )
// {
// fSimilarItems = TRUE;
// usSimilarItem = REFLEX_UNSCOPED;
// }
// break;
// case REFLEX_UNSCOPED:
// if( FindAttachment( pObj, REFLEX_SCOPED ) != 0 )
// {
// fSimilarItems = TRUE;
// usSimilarItem = REFLEX_SCOPED;
// }
// break;
// case SILENCER:
// if( FindAttachment( pObj, FLASH_SUPPRESSOR ) != 0 )
// {
// fSimilarItems = TRUE;
// usSimilarItem = FLASH_SUPPRESSOR;
// }
// break;
// case FLASH_SUPPRESSOR:
// if( FindAttachment( pObj, SILENCER ) != 0 )
// {
// fSimilarItems = TRUE;
// usSimilarItem = SILENCER;
// }
// break;
//}
if (fAttemptingAttachment)
{
if (fSameItem)
{
if (fDisplayMessage) ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_UI_FEEDBACK, Message[ STR_ATTACHMENT_ALREADY ] );
return( FALSE );
}
else if (fSimilarItems)
{
if (fDisplayMessage) ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_UI_FEEDBACK, Message[ STR_CANT_USE_TWO_ITEMS ], ItemNames[ usSimilarItem ], ItemNames[ usAttachment ] );
return( FALSE );
}
}
return( TRUE );
}
//Determines if it is possible to equip this weapon with this ammo.
BOOLEAN ValidAmmoType( UINT16 usItem, UINT16 usAmmoType )
{
if (Item[usItem].usItemClass == IC_GUN && Item[usAmmoType].usItemClass == IC_AMMO)
{
if (Weapon[usItem].ubCalibre == Magazine[Item[usAmmoType].ubClassIndex].ubCalibre)
{
return( TRUE );
}
}
return( FALSE );
}
BOOLEAN CompatibleFaceItem( UINT16 usItem1, UINT16 usItem2 )
{
INT32 iLoop = 0;
//Madd: skip this function if either item is nothing
//this will let us trim some lines from compatiblefaceitems.xml
if ( usItem1 == NONE || usItem2 == NONE )
return TRUE;
// look for the section of the array pertaining to this attachment...
while( 1 )
{
if (CompatibleFaceItems[iLoop][0] == usItem1)
{
break;
}
iLoop++;
if (CompatibleFaceItems[iLoop][0] == 0)
{
// the proposed item cannot fit with anything!
return( FALSE );
}
}
// now look through this section for the item in question
while( 1 )
{
if (CompatibleFaceItems[iLoop][1] == usItem2)
{
break;
}
iLoop++;
if (CompatibleFaceItems[iLoop][0] != usItem1)
{
// the proposed item cannot be attached to the item in question
return( FALSE );
}
}
return( TRUE );
}
//Determines if this item is a two handed item.
BOOLEAN TwoHandedItem( UINT16 usItem )
{
// if (Item[usItem].fFlags & ITEM_TWO_HANDED)
if (Item[usItem].twohanded )
{
return( TRUE );
}
return FALSE;
}
BOOLEAN ValidLaunchable( UINT16 usLaunchable, UINT16 usItem )
{
INT32 iLoop = 0;
//DebugMsg(TOPIC_JA2, DBG_LEVEL_3, String("ValidLaunchable: launchable=%d, item=%d",usLaunchable,usItem));
// look for the section of the array pertaining to this launchable item...
while( 1 )
{
if (Launchable[iLoop][0] == usLaunchable)
{
break;
}
iLoop++;
if (Launchable[iLoop][0] == 0)
{
// the proposed item cannot be attached to anything!
//DebugMsg(TOPIC_JA2, DBG_LEVEL_3, String("ValidLaunchable: launchable=%d, item=%d, return FALSE, launchable not found",usLaunchable,usItem));
return( FALSE );
}
}
// now look through this section for the item in question
while( 1 )
{
if (Launchable[iLoop][1] == usItem)
{
break;
}
iLoop++;
if (Launchable[iLoop][0] != usLaunchable)
{
// the proposed item cannot be attached to the item in question
//DebugMsg(TOPIC_JA2, DBG_LEVEL_3, String("ValidLaunchable: launchable=%d, item=%d, return FALSE, item not found",usLaunchable,usItem));
return( FALSE );
}
}
//DebugMsg(TOPIC_JA2, DBG_LEVEL_3, String("ValidLaunchable: launchable=%d, item=%d, return TRUE",usLaunchable,usItem));
return( TRUE );
}
BOOLEAN ValidItemLaunchable( OBJECTTYPE * pObj, UINT16 usAttachment )
{
if (pObj->exists() == false) {
return FALSE;
}
if ( !ValidLaunchable( usAttachment, pObj->usItem ) )
{
return( FALSE );
}
// if we can find another of the same class as the attachment, it's not possible
if ( FindAttachmentByClass( pObj, Item[ usAttachment ].usItemClass ) != 0 )
{
return( FALSE );
}
return( TRUE );
}
UINT16 GetLauncherFromLaunchable( UINT16 usLaunchable )
{
INT32 iLoop = 0;
// look for the section of the array pertaining to this launchable item...
while( 1 )
{
if (Launchable[iLoop][0] == usLaunchable)
{
break;
}
iLoop++;
if (Launchable[iLoop][0] == 0)
{
// the proposed item cannot be attached to anything!
return( NOTHING );
}
}
return( Launchable[iLoop][1] );
}
BOOLEAN EvaluateValidMerge( UINT16 usMerge, UINT16 usItem, UINT16 * pusResult, UINT16 * pusResult2, UINT8 * pubType, UINT8 * pubAPCost )
{
// NB "usMerge" is the object being merged with (e.g. compound 18)
// "usItem" is the item being merged "onto" (e.g. kevlar vest)
INT32 iLoop = 0;
//CHRISL: Update this so we can also merge IC_MONEY like wallets and nuggets.
if (usMerge == usItem && (Item[ usItem ].usItemClass == IC_AMMO || Item[ usItem ].usItemClass == IC_MONEY))
{
*pusResult = usItem;
*pubType = COMBINE_POINTS;
return( TRUE );
}
// look for the section of the array pertaining to this Merge...
while( 1 )
{
if (Merge[iLoop][0] == usMerge)
{
break;
}
iLoop++;
if (Merge[iLoop][0] == 0)
{
// the proposed item cannot be merged with anything!
return( FALSE );
}
}
// now look through this section for the item in question
while( 1 )
{
if (Merge[iLoop][1] == usItem)
{
break;
}
iLoop++;
if (Merge[iLoop][0] != usMerge)
{
// the proposed item cannot be merged with the item in question
return( FALSE );
}
}
//WarmSteel - Return false if the results aren't valid.
if( !ItemIsLegal(Merge[iLoop][2], TRUE) && !ItemIsLegal(Merge[iLoop][3], TRUE) ){
return( FALSE );
}
*pusResult = Merge[iLoop][2];
*pusResult2 = Merge[iLoop][3];
*pubType = (UINT8) Merge[iLoop][4];
*pubAPCost = (UINT8) Merge[iLoop][5];
return( TRUE );
}
BOOLEAN ValidMerge( UINT16 usMerge, UINT16 usItem )
{
UINT16 usIgnoreResult, usIgnoreResult2;
UINT8 ubIgnoreType, ubIgnoreAPCost;
return( EvaluateValidMerge( usMerge, usItem, &usIgnoreResult, &usIgnoreResult2, &ubIgnoreType, &ubIgnoreAPCost ) );
}
int GetPocketSizeByDimensions(int sizeX, int sizeY)
{
static const UINT8 cisPocketSize[6][4] =
{
11, 12, 13, 14,
15, 16, 17, 18,
19, 20, 21, 22,
23, 24, 25, 26,
27, 28, 29, 30,
31, 32, 33, 34
};
return cisPocketSize[sizeX][sizeY];
}
void GetPocketDimensionsBySize(int pocketSize, int& sizeX, int& sizeY)
{
static const UINT8 cisPocketSize[6][4] =
{
11, 12, 13, 14,
15, 16, 17, 18,
19, 20, 21, 22,
23, 24, 25, 26,
27, 28, 29, 30,
31, 32, 33, 34
};
for(sizeX=0; sizeX<6; sizeX++)
{
for(sizeY=0; sizeY<4; sizeY++)
{
if(pocketSize == cisPocketSize[sizeX][sizeY])
{
return;
}
}
}
}
// CHRISL: New function to dynamically modify ItemSize based on attachments, stack size, etc
UINT16 CalculateItemSize( OBJECTTYPE *pObject )
{
UINT16 iSize;
UINT16 currentSize = 0;
UINT32 cisIndex;
// Determine default ItemSize based on item and attachments
cisIndex = pObject->usItem;
iSize = Item[cisIndex].ItemSize;
if(iSize>34)
iSize = 34;
//for each object in the stack, hopefully there is only 1
for (int numStacked = 0; numStacked < pObject->ubNumberOfObjects; ++numStacked) {
//some weapon attachments can adjust the ItemSize of a weapon
if(iSize<10) {
for (attachmentList::iterator iter = (*pObject)[numStacked]->attachments.begin(); iter != (*pObject)[numStacked]->attachments.end(); ++iter) {
if (iter->exists() == true) {
iSize += Item[iter->usItem].itemsizebonus;
// CHRISL: This is to catch things if we try and reduce ItemSize when we're already at 0
if(iSize > 34 || iSize < 0)
iSize = 0;
if(iSize > 9)
iSize = 9;
}
}
}
// LBENODE has it's ItemSize adjusted based on what it's storing
if(pObject->IsActiveLBE(numStacked) == true) {
LBENODE* pLBE = pObject->GetLBEPointer(numStacked);
if(pLBE)
{
//start by determining the equivalent number of "small" pockets that this LBENODE has access to. This
// is based on the pType value in Pockets.xml with 1=Small, 2=Medium and 3=Large
UINT16 totalPocketValue = 0;
FLOAT percentOfItemUsed = 0;
UINT16 pIndex, testSize, maxSize;
UINT8 pocketCapacity, numberOfSizeIncrements;
FLOAT currentPocketPercent, currentPocketPartOfTotal;
for(unsigned int x = 0; x < pLBE->inv.size(); x++)
{
if(LoadBearingEquipment[Item[pObject->usItem].ubClassIndex].lbePocketIndex[x] != 0)
{
pIndex = LoadBearingEquipment[Item[pObject->usItem].ubClassIndex].lbePocketIndex[x];
totalPocketValue += LBEPocketType[pIndex].pType;
}
}
//Now, look through each active pocket
for(unsigned int x = 0; x < pLBE->inv.size(); x++)
{
if(pLBE->inv[x].exists() == true)
{
pIndex = LoadBearingEquipment[Item[pObject->usItem].ubClassIndex].lbePocketIndex[x];
testSize = CalculateItemSize(&pLBE->inv[x]);
pocketCapacity = LBEPocketType[pIndex].ItemCapacityPerSize[testSize];
currentPocketPercent = (FLOAT)pLBE->inv[x].ubNumberOfObjects / (FLOAT)pocketCapacity;
currentPocketPartOfTotal = (FLOAT)LBEPocketType[pIndex].pType / (FLOAT)totalPocketValue;
percentOfItemUsed += currentPocketPartOfTotal * currentPocketPercent;
}
}
maxSize = max(iSize, LoadBearingEquipment[Item[pObject->usItem].ubClassIndex].lbeFilledSize);
//Now, determine the increments between initial ItemSize and Filled Size, and adjust iSize by percentOfItemUsed
if(percentOfItemUsed != 0)
{
numberOfSizeIncrements = LoadBearingEquipment[Item[pObject->usItem].ubClassIndex].lbeFilledSize - Item[pObject->usItem].ItemSize;
testSize = (UINT16)((numberOfSizeIncrements * percentOfItemUsed) + .5);
currentSize = __max(iSize + testSize, currentSize);
currentSize = __min(currentSize, maxSize);
}
#if 0
//old method
UINT16 newSize, testSize, maxSize;
UINT8 cnt=0;
newSize = 0;
maxSize = max(iSize, LoadBearingEquipment[Item[pObject->usItem].ubClassIndex].lbeFilledSize);
// Look for the ItemSize of the largest item in this LBENODE
for(unsigned int x = 0; x < pLBE->inv.size(); ++x)
{
if(pLBE->inv[x].exists() == true)
{
testSize = CalculateItemSize(&(pLBE->inv[x]));
//Now that we have the size of one item, we want to factor in the number of items since two
// items take up more space then one.
testSize = testSize + pLBE->inv[x].ubNumberOfObjects - 1;
testSize = min(testSize,34);
//We also need to increase the size of guns so they'll fit with the rest of our calculations.
if(testSize < 5)
testSize += 10;
if(testSize < 10)
testSize += 18;
//Finally, we want to factor in multiple pockets. We'll do this by counting the number of filled
// pockets, then add this count total to our newSize when everything is finished.
cnt++;
newSize = max(testSize, newSize);
}
}
//Add the total number of filled pockets to our NewSize to account for multiple pockets being used
newSize += cnt;
newSize = min(newSize,34);
// If largest item is smaller then LBE, don't change ItemSize
if(newSize > 0 && newSize < iSize) {
iSize = iSize;
}
// if largest item is larget then LBE but smaller then max size, partially increase ItemSize
else if(newSize >= iSize && newSize < maxSize) {
iSize = newSize;
}
// if largest item is larger then max size, reset ItemSize to max size
else if(newSize >= maxSize) {
iSize = maxSize;
}
#endif
}
}
}
//Finally, set the new iSize value
iSize = __max(iSize, currentSize);
return(iSize);
}
UINT16 CalculateAmmoWeight( UINT16 usGunAmmoItem, UINT16 ubShotsLeft )
{
if( 0 == usGunAmmoItem ) /* Sergeant_Kolja: 2007-06-11, Fix for Creature Spit. This has no Ammo, so the old code calculated accidentally -1.6 resulting in 0xFFFF */
{
DebugMsg(TOPIC_JA2, DBG_LEVEL_3, "'no ammo weight' FIX for Creatures\r\n" );
return 0;
}
//Temporary calculation for minWeight. 0.2*ubWeight rounded correctly
UINT32 uiMinWeight = (UINT32)((Item[usGunAmmoItem].ubWeight / 5.0) + 0.5);
if( uiMinWeight < 1 || uiMinWeight > Item[usGunAmmoItem].ubWeight)
{
uiMinWeight = 1;
}
double weight = 0.0;
if(ubShotsLeft > 0)
{
if( uiMinWeight == Item[usGunAmmoItem].ubWeight )
{
weight += (double)uiMinWeight;
}
else
{
weight += (double)uiMinWeight + (( (double)ubShotsLeft / (double)Magazine[ Item[usGunAmmoItem].ubClassIndex ].ubMagSize) * ( (double)Item[usGunAmmoItem].ubWeight - (double)uiMinWeight ));
}
}
weight += 0.5; //Pulmu:To round correctly
return (UINT16)weight;
//Pulmu end
}
/*CHRISL: Change to a 16bit integer for a max weight of 6553.5kg. Also changed to account for
new inventory system. */
UINT16 CalculateObjectWeight( OBJECTTYPE *pObject )
{
if (pObject->exists() == false || pObject->ubNumberOfObjects == 0) {
return 0;
}
UINT16 weight = 0;
INVTYPE * pItem;
pItem = &(Item[ pObject->usItem ]);
//ADB it is much easier and faster to calculate ammo in a lump rather than accumulate a stack's weight
if ( pItem->usItemClass == IC_AMMO)//Pulmu: added weight allowance for ammo not being full
{
if ( gGameExternalOptions.fAmmoDynamicWeight == TRUE ) {
for( int cnt = 0; cnt < pObject->ubNumberOfObjects; cnt++ )
{
weight += CalculateAmmoWeight(pObject->usItem, (*pObject)[cnt]->data.ubShotsLeft);
}
}
else {
// Start with base weight
weight = pItem->ubWeight;
//multiply by the number of objects, can be 0
weight *= pObject->ubNumberOfObjects;
}
}
else {
for (int x = 0; x < pObject->ubNumberOfObjects; ++x) {
weight += pObject->GetWeightOfObjectInStack(x);
}
}
return( weight );
}
UINT16 OBJECTTYPE::GetWeightOfObjectInStack(unsigned int index)
{
//Item does not exist
if( index >= ubNumberOfObjects )
{
return 0;
}
INVTYPE * pItem = &(Item[ usItem ]);
// Start with base weight
UINT16 weight = pItem->ubWeight;
if ( pItem->usItemClass != IC_AMMO )
{
// Are we looking at an LBENODE item? New inventory only.
if(pItem->usItemClass == IC_LBEGEAR && IsActiveLBE(index) && (UsingNewInventorySystem() == true))
{
LBENODE* pLBE = GetLBEPointer(index);
if (pLBE) {
for ( unsigned int subObjects = 0; subObjects < pLBE->inv.size(); subObjects++)
{
if (pLBE->inv[subObjects].exists() == true)
{
weight += CalculateObjectWeight(&(pLBE->inv[subObjects]));
}
}
}
//do not search for attachments to an LBE
return weight;
}
// account for any attachments
for (attachmentList::iterator iter = (*this)[index]->attachments.begin(); iter != (*this)[index]->attachments.end(); ++iter) {
if(iter->exists()){
weight += CalculateObjectWeight(&(*iter));
}
}
// add in weight of ammo
if (Item[ usItem ].usItemClass == IC_GUN && (*this)[index]->data.gun.ubGunShotsLeft > 0)
{
if( gGameExternalOptions.fAmmoDynamicWeight == TRUE )
{
weight += CalculateAmmoWeight((*this)[index]->data.gun.usGunAmmoItem, (*this)[index]->data.gun.ubGunShotsLeft);
}
else
{
weight += Item[ (*this)[index]->data.gun.usGunAmmoItem ].ubWeight;
}
}
}
else if ( pItem->usItemClass == IC_AMMO && gGameExternalOptions.fAmmoDynamicWeight == TRUE )//Pulmu: added weight allowance for ammo not being full
{
weight = CalculateAmmoWeight(usItem, (*this)[index]->data.ubShotsLeft);
}
return weight;
}
UINT32 CalculateCarriedWeight( SOLDIERTYPE * pSoldier )
{
UINT32 uiTotalWeight = 0;
UINT32 uiPercent;
UINT8 ubLoop;
UINT8 ubStrengthForCarrying;
//Pulmu: Changes for dynamic ammo weight
for( ubLoop = 0; ubLoop < pSoldier->inv.size(); ubLoop++)
{
//ADB the weight of the object is already counting stacked objects, attachments, et al
uiTotalWeight += CalculateObjectWeight(&pSoldier->inv[ubLoop]);
}
// for now, assume soldiers can carry 1/2 their strength in KGs without penalty.
// instead of multiplying by 100 for percent, and then dividing by 10 to account
// for weight units being in 10ths of kilos, not kilos... we just start with 10 instead of 100!
ubStrengthForCarrying = EffectiveStrength( pSoldier );
if ( ubStrengthForCarrying > 80 )
{
ubStrengthForCarrying += (ubStrengthForCarrying - 80);
}
// SANDRO - STOMP traits - Bodybuilding carry weight bonus
if ( gGameOptions.fNewTraitSystem && HAS_SKILL_TRAIT( pSoldier, BODYBUILDING_NT ) )
{
ubStrengthForCarrying = (ubStrengthForCarrying * (100 + gSkillTraitValues.ubBBCarryWeightBonus) / 100); // plus one third
}
// for now, assume soldiers can carry 1/2 their strength in KGs without penalty.
// instead of multiplying by 100 for percent, and then dividing by 10 to account
// for weight units being in 10ths of kilos, not kilos... we just start with 10 instead of 100!
// HEADROCK HAM 3: STR required per 1/2 kilo has been externalized. Can someone tidy this up though? The
// formula works great, but it's damn ugly now.
uiPercent = (UINT32)(((FLOAT)10 * (FLOAT)gGameExternalOptions.iStrengthToLiftHalfKilo) * uiTotalWeight) / ( ubStrengthForCarrying / 2 );
return( uiPercent );
}
void DeleteObj(OBJECTTYPE * pObj )
{
pObj->initialize();
}
void SwapObjs( OBJECTTYPE * pObj1, OBJECTTYPE * pObj2 )
{
//cannot use gTempObject
OBJECTTYPE Temp (*pObj1 );
*pObj1 = *pObj2;
*pObj2 = Temp;
}
//ADB these 2 functions were created because the code calls SwapObjs all over the place
//but never handles the effects of that swap!
void SwapObjs(SOLDIERTYPE* pSoldier, int leftSlot, int rightSlot, BOOLEAN fPermanent)
{
SwapObjs(&pSoldier->inv[ leftSlot ], &pSoldier->inv[ rightSlot ]);
if (fPermanent)
{
//old usItem for the left slot is now stored in the right slot, and vice versa
HandleTacticalEffectsOfEquipmentChange(pSoldier, leftSlot, pSoldier->inv[ rightSlot ].usItem, pSoldier->inv[ leftSlot ].usItem);
HandleTacticalEffectsOfEquipmentChange(pSoldier, rightSlot, pSoldier->inv[ leftSlot ].usItem, pSoldier->inv[ rightSlot ].usItem);
}
}
void SwapObjs(SOLDIERTYPE* pSoldier, int slot, OBJECTTYPE* pObject, BOOLEAN fPermanent)
{
SwapObjs(&pSoldier->inv[ slot ], pObject);
if (fPermanent)
{
HandleTacticalEffectsOfEquipmentChange(pSoldier, slot, pObject->usItem, pSoldier->inv[ slot ].usItem);
}
}
void DamageObj( OBJECTTYPE * pObj, INT8 bAmount, UINT8 subObject )
{
//usually called from AttachObject, where the attachment is known to be a single item,
//and the attachment is only being attached to the top of the stack
if (bAmount >= (*pObj)[subObject]->data.objectStatus)
{
(*pObj)[subObject]->data.objectStatus = 1;
}
else
{
(*pObj)[subObject]->data.objectStatus -= bAmount;
}
}
void DistributeStatus(OBJECTTYPE* pSourceObject, OBJECTTYPE* pTargetObject, INT16 bMaxPoints)
{
INT16 bPointsToMove;
for ( int bLoop = pSourceObject->ubNumberOfObjects - 1; bLoop >= 0; bLoop-- )
{
StackedObjectData* pSource = (*pSourceObject)[ bLoop ];
if ( pSource->data.objectStatus > 0 )
{
// take the points here and distribute over the lower #d items
int bLoop2;
if (pSourceObject == pTargetObject) {
//we are averaging out the same object
bLoop2 = bLoop - 1;
}
else {
//we are moving from the cursor object to this one
bLoop2 = pTargetObject->ubNumberOfObjects - 1;
}
//for (; bLoop2 >= 0; bLoop2-- )
for(int i = 0; i<=bLoop2; i++)
{
StackedObjectData* pDest = (*pTargetObject)[ i ];
if ( pDest->data.objectStatus < bMaxPoints )
{
bPointsToMove = bMaxPoints - pDest->data.objectStatus;
bPointsToMove = __min( bPointsToMove, pSource->data.objectStatus );
pDest->data.objectStatus += bPointsToMove;
pSource->data.objectStatus -= bPointsToMove;
if ( pSource->data.objectStatus == 0 )
{
StackedObjects::iterator iter = pSourceObject->objectStack.begin();
for (int x = 0; x < bLoop; ++x) {
++iter;
}
pSourceObject->objectStack.erase(iter);
pSourceObject->ubNumberOfObjects--;
//ADB ubWeight has been removed, see comments in OBJECTTYPE
//pSourceObject->ubWeight = CalculateObjectWeight(pSourceObject);
// done!
break;
}
}
}
}
}
}
BOOLEAN PlaceObjectAtObjectIndex( OBJECTTYPE * pSourceObj, OBJECTTYPE * pTargetObj, UINT8 ubIndex, UINT32 ubCap )
{
if (pSourceObj->usItem != pTargetObj->usItem)
{
return( TRUE );
}
if (ubIndex < pTargetObj->ubNumberOfObjects)
{
// swap
//std::swap??
StackedObjectData data = *((*pSourceObj)[0]);
*((*pSourceObj)[0]) = *((*pTargetObj)[ubIndex]);
//ADB ubWeight has been removed, see comments in OBJECTTYPE
//pSourceObj->ubWeight = CalculateObjectWeight(pSourceObj);
*((*pTargetObj)[ubIndex]) = data;
//ADB ubWeight has been removed, see comments in OBJECTTYPE
//pTargetObj->ubWeight = CalculateObjectWeight(pTargetObj);
return( TRUE );
}
else
{
// add to end
pTargetObj->AddObjectsToStack( *pSourceObj, 1, NULL, NUM_INV_SLOTS, ubCap );
if (pSourceObj->exists() == true) {
return( TRUE );
}
else {
return FALSE;
}
}
}
#define RELOAD_NONE 0
#define RELOAD_PLACE 1
#define RELOAD_SWAP 2
#define RELOAD_TOPOFF 3
#define RELOAD_AUTOPLACE_OLD 4
BOOLEAN ReloadGun( SOLDIERTYPE * pSoldier, OBJECTTYPE * pGun, OBJECTTYPE * pAmmo, UINT32 subObject )
{
UINT16 ubBulletsToMove;
INT16 bAPs;
UINT16 usReloadSound;
BOOLEAN fSameAmmoType;
BOOLEAN fSameMagazineSize;
BOOLEAN fReloadingWithStack;
BOOLEAN fEmptyGun;
BOOLEAN fEnoughAPs;
INT8 bReloadType;
UINT16 usNewAmmoItem;
UINT16 usLargestMag;
UINT32 ammoObject = 0;
bAPs = 0;
if ( (gTacticalStatus.uiFlags & TURNBASED) && (gTacticalStatus.uiFlags & INCOMBAT) )
{
//CHRISL: Alter this so we treat clip fed weapons differently from weapons that load with loose rounds
bAPs = GetAPsToReloadGunWithAmmo( pSoldier, pGun, pAmmo );
if ( !EnoughPoints( pSoldier, bAPs, 0,TRUE ) )
{
return( FALSE );
}
}
if ( Item[ pGun->usItem ].usItemClass == IC_LAUNCHER || Item[pGun->usItem].cannon )
{
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, String("ReloadGun: Loading launcher - new ammo type = %d, weight = %d", pAmmo->usItem, CalculateObjectWeight(pAmmo) ) );
(*pGun)[subObject]->data.gun.usGunAmmoItem = pAmmo->usItem;
if ( pGun->AttachObject( pSoldier, pAmmo ) == FALSE )
{
(*pGun)[subObject]->data.gun.usGunAmmoItem = NONE;
// abort
return( FALSE );
}
}
else
{
fEmptyGun = ((*pGun)[subObject]->data.gun.ubGunShotsLeft == 0);
fReloadingWithStack = (pAmmo->ubNumberOfObjects > 1);
fSameAmmoType = ( (*pGun)[subObject]->data.gun.ubGunAmmoType == Magazine[Item[pAmmo->usItem].ubClassIndex].ubAmmoType );
fSameMagazineSize = ( Magazine[ Item[ pAmmo->usItem ].ubClassIndex ].ubMagSize == GetMagSize( pGun, subObject));
fEnoughAPs = EnoughPoints( pSoldier, GetAPsToReloadGunWithAmmo( pSoldier, pGun, pAmmo, FALSE ), 0,FALSE );
if (fEmptyGun)
{
bReloadType = RELOAD_PLACE;
}
else
{
// record old ammo
CreateAmmo((*pGun)[subObject]->data.gun.usGunAmmoItem, &gTempObject, (*pGun)[subObject]->data.gun.ubGunShotsLeft);
if (fSameMagazineSize)
{
if (fSameAmmoType)
{
if ( (gTacticalStatus.uiFlags & TURNBASED) && (gTacticalStatus.uiFlags & INCOMBAT) && Weapon[pGun->usItem].swapClips )
{
bReloadType = RELOAD_SWAP;
}
else
{
bReloadType = RELOAD_TOPOFF;
}
}
else
{
if (!fReloadingWithStack)
{
bReloadType = RELOAD_SWAP;
}
else
{
bReloadType = RELOAD_AUTOPLACE_OLD;
}
}
}
else // diff sized magazines
{
if (fSameAmmoType)
{
bReloadType = RELOAD_TOPOFF;
}
else
{
bReloadType = RELOAD_AUTOPLACE_OLD;
}
}
}
//CHRISL: We need to verify that the passed subObject actually exists. We could get passed an empty subObject if we
// reload a stack of weapons from the stack popup. If this is the case, reset subObject to the last item in the
// stack
if(subObject >= pGun->ubNumberOfObjects)
subObject = ammoObject = pGun->ubNumberOfObjects-1;
//CHRISL: If reloading with a stack, we probably want the item with the most ammo still in it
if (fReloadingWithStack)
{
usLargestMag = (*pAmmo)[ammoObject]->data.ubShotsLeft;
for(int i = 0; i<pAmmo->ubNumberOfObjects; i++)
{
if((*pAmmo)[i]->data.ubShotsLeft == Magazine[Item[pAmmo->usItem].ubClassIndex].ubMagSize)
{
ammoObject = i;
break;
}
else if((*pAmmo)[i]->data.ubShotsLeft > usLargestMag)
{
ammoObject = i;
}
}
}
if (fSameMagazineSize)
{
// record new ammo item for gun
usNewAmmoItem = pAmmo->usItem;
if (bReloadType == RELOAD_TOPOFF)
{
ubBulletsToMove = __min( (*pAmmo)[ammoObject]->data.ubShotsLeft, GetMagSize(pGun) - (*pGun)[subObject]->data.gun.ubGunShotsLeft );
}
else
{
ubBulletsToMove = (*pAmmo)[ammoObject]->data.ubShotsLeft;
}
}
else if (Magazine[Item[pAmmo->usItem].ubClassIndex].ubMagSize > GetMagSize(pGun, subObject))
{
//MADD MARKER
//usNewAmmoItem = pAmmo->usItem - 1;
usNewAmmoItem = FindReplacementMagazine(Weapon[pGun->usItem].ubCalibre ,GetMagSize(pGun, subObject),Magazine[Item[pAmmo->usItem].ubClassIndex].ubAmmoType);
if (bReloadType == RELOAD_TOPOFF)
{
ubBulletsToMove = __min( (*pAmmo)[ammoObject]->data.ubShotsLeft, GetMagSize(pGun, subObject) - (*pGun)[subObject]->data.gun.ubGunShotsLeft );
}
else
{
ubBulletsToMove = __min( (*pAmmo)[ammoObject]->data.ubShotsLeft, GetMagSize(pGun, subObject) );
}
}
else // mag is smaller than weapon mag
{
//MADD MARKER
//usNewAmmoItem = pAmmo->usItem + 1;
usNewAmmoItem = FindReplacementMagazine(Weapon[pGun->usItem].ubCalibre ,GetMagSize(pGun, subObject),Magazine[Item[pAmmo->usItem].ubClassIndex].ubAmmoType);
if (bReloadType == RELOAD_TOPOFF)
{
ubBulletsToMove = __min( (*pAmmo)[ammoObject]->data.ubShotsLeft, GetMagSize(pGun, subObject) - (*pGun)[subObject]->data.gun.ubGunShotsLeft );
}
else
{
ubBulletsToMove = __min( (*pAmmo)[ammoObject]->data.ubShotsLeft, GetMagSize(pGun, subObject));
}
}
//CHRIS: This should reset the number of bullest moved to what we can actually afford when loading loose rounds
if(Weapon[pGun->usItem].swapClips == 0 && (gTacticalStatus.uiFlags & TURNBASED) && (gTacticalStatus.uiFlags & INCOMBAT))
{
if(fEnoughAPs)
{
bAPs = GetAPsToReloadGunWithAmmo( pSoldier, pGun, pAmmo, FALSE );
}
else
{
//how many can we reload? remember, bAPs assumes 1 round at this stage
bAPs = GetAPsToReloadGunWithAmmo( pSoldier, pGun, pAmmo, 2 );
for(int i = 0; i<ubBulletsToMove; i++)
{
if(EnoughPoints(pSoldier, (bAPs+(i*APBPConstants[AP_RELOAD_LOOSE])), 0, FALSE) == FALSE)
{
ubBulletsToMove = i+1;
break;
}
}
bAPs = GetAPsToReloadGunWithAmmo( pSoldier, pGun, pAmmo );
}
}
switch( bReloadType )
{
case RELOAD_PLACE:
(*pGun)[subObject]->data.gun.ubGunShotsLeft = ubBulletsToMove;
(*pGun)[subObject]->data.gun.ubGunAmmoType = Magazine[Item[pAmmo->usItem].ubClassIndex].ubAmmoType;
(*pGun)[subObject]->data.gun.usGunAmmoItem = usNewAmmoItem;
break;
case RELOAD_SWAP:
(*pGun)[subObject]->data.gun.ubGunShotsLeft = ubBulletsToMove;
(*pGun)[subObject]->data.gun.ubGunAmmoType = Magazine[Item[pAmmo->usItem].ubClassIndex].ubAmmoType;
(*pGun)[subObject]->data.gun.usGunAmmoItem = usNewAmmoItem;
if (fReloadingWithStack)
{
// add to end of stack
pAmmo->AddObjectsToStack( gTempObject, 1 );
}
else
{
// Copying the old ammo to the cursor in turnbased could screw up for the player
// (suppose his inventory is full!)
//ADB copying the old ammo to the cursor at any time will screw it up if the cursor ammo is a stack!
if ( (gTacticalStatus.uiFlags & TURNBASED) && (gTacticalStatus.uiFlags & INCOMBAT) && !EnoughPoints( pSoldier, (INT8) (bAPs + GetBasicAPsToPickupItem( pSoldier )), 0, FALSE ) // SANDRO
|| pAmmo->ubNumberOfObjects > 1)
{
// try autoplace
if ( !AutoPlaceObject( pSoldier, &gTempObject, FALSE ) )
{
// put it on the ground
AddItemToPool( pSoldier->sGridNo, &gTempObject, 1, pSoldier->pathing.bLevel, 0 , -1 );
}
// delete the object now in the cursor
pAmmo->RemoveObjectsFromStack(1);
}
else
{
// copy the old ammo to the cursor
*pAmmo = gTempObject;
}
}
break;
case RELOAD_AUTOPLACE_OLD:
if ( !AutoPlaceObject( pSoldier, &gTempObject, TRUE ) )
{
// error msg!
return( FALSE );
}
// place first ammo in gun
(*pGun)[subObject]->data.gun.ubGunShotsLeft = ubBulletsToMove;
(*pGun)[subObject]->data.gun.ubGunAmmoType = Magazine[Item[pAmmo->usItem].ubClassIndex].ubAmmoType;
(*pGun)[subObject]->data.gun.usGunAmmoItem = usNewAmmoItem;
break;
case RELOAD_TOPOFF:
// ADD that many bullets to gun
(*pGun)[subObject]->data.gun.ubGunShotsLeft += ubBulletsToMove;
break;
}
// CHRISL: If we don't completely reload a SwapClips==0 weapon, set the "reload" flag
if(Weapon[pGun->usItem].swapClips == 0 && GetMagSize(pGun, subObject) != (*pGun)[0]->data.gun.ubGunShotsLeft)
{
(*pGun)[subObject]->data.gun.ubGunState |= GS_WEAPON_BEING_RELOADED;
(*pGun)[subObject]->data.gun.ubGunState &= ~GS_CARTRIDGE_IN_CHAMBER;
}
else
{
(*pGun)[subObject]->data.gun.ubGunState &= ~GS_WEAPON_BEING_RELOADED;
(*pGun)[subObject]->data.gun.ubGunState |= GS_CARTRIDGE_IN_CHAMBER;
}
if ( ! ( bReloadType == RELOAD_SWAP && !fReloadingWithStack ) )
{
// remove # of bullets, delete 1 object if necessary
(*pAmmo)[ammoObject]->data.ubShotsLeft -= ubBulletsToMove;
if ((*pAmmo)[ammoObject]->data.ubShotsLeft == 0)
{
pAmmo->RemoveObjectAtIndex(ammoObject);
//pAmmo->RemoveObjectsFromStack(1);
}
}
}
// OK, let's play a sound of reloading too...
// If this guy is visible...
if ( pSoldier->bVisible != -1 )
{
// Play some effects!
usReloadSound = Weapon[ pGun->usItem ].sReloadSound;
if ( usReloadSound != 0 && !IsAutoResolveActive() )
{
PlayJA2Sample( usReloadSound, RATE_11025, HIGHVOLUME, 1, MIDDLEPAN );
}
}
if (pSoldier->bTeam == gbPlayerNum)
{
// spit out a message if this is one of our folks reloading
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_INTERFACE, Message[STR_PLAYER_RELOADS], pSoldier->name );
}
DeductPoints( pSoldier, bAPs, 0 );
//ADB ubWeight has been removed, see comments in OBJECTTYPE
//pGun->ubWeight = CalculateObjectWeight( pGun );
if ( (*pGun)[subObject]->data.gun.bGunAmmoStatus >= 0 )
{
// make sure gun ammo status is 100, if gun isn't jammed
(*pGun)[subObject]->data.gun.bGunAmmoStatus = 100;
}
//CHRISL: Move this towards the top so that we can leave this flag off if we're in the middle of reloading
//(*pGun)[subObject]->data.gun.ubGunState |= GS_CARTRIDGE_IN_CHAMBER; // Madd: reloading should automatically put cartridge in chamber
return( TRUE );
}
BOOLEAN EmptyWeaponMagazine( OBJECTTYPE * pWeapon, OBJECTTYPE *pAmmo, UINT32 subObject )
{
UINT16 usReloadSound;
CHECKF( pAmmo != NULL );
if ( (*pWeapon)[subObject]->data.gun.ubGunShotsLeft > 0 )
{
CreateAmmo((*pWeapon)[subObject]->data.gun.usGunAmmoItem, pAmmo, (*pWeapon)[subObject]->data.gun.ubGunShotsLeft);
(*pWeapon)[subObject]->data.gun.ubGunShotsLeft = 0;
(*pWeapon)[subObject]->data.gun.ubGunAmmoType = 0;
// HEADROCK HAM 3.5: Leaving the ammo inside the gun causes EDB stats to display values as though the magazine
// still gives some effects (like autopen reduction, range bonus, etcetera). I'm going to try to work around
// this issue.
(*pWeapon)[subObject]->data.gun.usGunAmmoItem = 0; // leaving the ammo item the same for auto-reloading purposes
// Play some effects!
usReloadSound = Weapon[ pWeapon->usItem ].sReloadSound;
if ( usReloadSound != 0 )
{
PlayJA2Sample( usReloadSound, RATE_11025, HIGHVOLUME, 1, MIDDLEPAN );
}
//ADB ubWeight has been removed, see comments in OBJECTTYPE
//pWeapon->ubWeight = CalculateObjectWeight( pWeapon );
// Pulmu bugfix:
//ADB ubWeight has been removed, see comments in OBJECTTYPE
//pAmmo->ubWeight = CalculateObjectWeight( pAmmo );
// Pulmu end:
return( TRUE );
}
else
{
// HEADROCK HAM 3.5: Clear the ammo type and magazine on player command. This will remove all bonuses by
// the ammo and allow viewing the gun's normal stats. It will also change the weapon's ammocolor back to grey.
(*pWeapon)[subObject]->data.gun.ubGunAmmoType = 0;
(*pWeapon)[subObject]->data.gun.usGunAmmoItem = 0;
//CHRISL: Clear the contents of pAmmo just in case
pAmmo->initialize();
return( FALSE );
}
}
// HEADROCK HAM 3.3: Added an additional argument which helps the program pick a magazine
// that matches the ammotype currently used in the weapon. This makes for much smarter
// ammo selection.
INT8 FindAmmo( SOLDIERTYPE * pSoldier, UINT8 ubCalibre, UINT16 ubMagSize, UINT8 ubAmmoType, INT8 bExcludeSlot )
{
INT8 bLoop;
INT8 capLoop = 0;
UINT16 curCap = 0, stackCap = 0;
BOOLEAN found = FALSE;
INVTYPE * pItem;
//CHRISL: Update this to search for the largest appropriate mag if ubMagSize = ANY_MAGSIZE
for (bLoop = HANDPOS; bLoop < (INT8)pSoldier->inv.size(); bLoop++)
{
//CHRISL: If in NIV, in combat and backpack is closed, don't look inside
if(UsingNewAttachmentSystem() == true && (gTacticalStatus.uiFlags & INCOMBAT) && IsBackpackSlot(bLoop) == true && pSoldier->flags.ZipperFlag == FALSE)
continue;
if (pSoldier->inv[bLoop].exists() == true) {
if (bLoop == bExcludeSlot)
{
continue;
}
pItem = &(Item[pSoldier->inv[bLoop].usItem]);
if (pItem->usItemClass == IC_AMMO)
{
if (Magazine[pItem->ubClassIndex].ubCalibre == ubCalibre)
{
if(ubMagSize != ANY_MAGSIZE && Magazine[pItem->ubClassIndex].ubMagSize == ubMagSize)
{
found = TRUE;
// looking for specific size. return if found
// Find fullest mag
for(int i = 0; i<pSoldier->inv[bLoop].ubNumberOfObjects; i++)
{
stackCap = __max(stackCap, pSoldier->inv[bLoop][i]->data.ubShotsLeft);
}
// If found a similar-sized magazine to the best one found so far, but this new one
// has the same ammotype as specified in the arguments, then this is a better choice!
if(stackCap > curCap ||
(stackCap == curCap && Magazine[pItem->ubClassIndex].ubAmmoType == ubAmmoType))
{
curCap = stackCap;
capLoop = bLoop;
}
//return( bLoop );
}
else if(ubMagSize == ANY_MAGSIZE)
{
found = TRUE;
// looking for any mag size. find the largest
if(Magazine[pItem->ubClassIndex].ubMagSize > curCap)
{
curCap = Magazine[pItem->ubClassIndex].ubMagSize;
capLoop = bLoop;
}
}
}
}
}
}
if(found == TRUE)
return( capLoop );
return( NO_SLOT );
}
INT8 FindAmmoToReload( SOLDIERTYPE * pSoldier, INT8 bWeaponIn, INT8 bExcludeSlot )
{
OBJECTTYPE * pObj;
INT8 bSlot;
if (pSoldier == NULL)
{
return( NO_SLOT );
}
pObj = &(pSoldier->inv[bWeaponIn]);
//<SB> manual recharge
if ((*pObj)[0]->data.gun.ubGunShotsLeft && !((*pObj)[0]->data.gun.ubGunState & GS_CARTRIDGE_IN_CHAMBER) )
return bWeaponIn;
//</SB>
if ( Item[pObj->usItem].usItemClass == IC_GUN && !Item[pObj->usItem].cannon )
{
// look for same ammo as before
//bSlot = FindObjExcludingSlot( pSoldier, (*pObj)[0]->data.gun.usGunAmmoItem, bExcludeSlot );
//if (bSlot != NO_SLOT)
//{
// reload using this ammo!
// return( bSlot );
//}
// look for any ammo that matches which is of the same calibre and magazine size
bSlot = FindAmmo( pSoldier, Weapon[pObj->usItem].ubCalibre, GetMagSize(pObj), GetAmmoType(pObj), bExcludeSlot );
if (bSlot != NO_SLOT)
{
return( bSlot );
}
else
{
// look for any ammo that matches which is of the same calibre (different size okay)
return( FindAmmo( pSoldier, Weapon[pObj->usItem].ubCalibre, ANY_MAGSIZE, GetAmmoType(pObj), bExcludeSlot ) );
}
}
else
{
for(int i=0;i<MAXITEMS;i++)
{
if ( Launchable[i][0] == 0 && Launchable[i][1] == 0)
break;
if ( pObj->usItem == Launchable[i][1] )
{
bSlot = FindObj( pSoldier, Launchable[i][0] );
if ( bSlot != NO_SLOT )
return bSlot;
}
}
return NO_SLOT;
//switch( pObj->usItem )
//{
// case RPG7: // TODO: madd fix this
// return( FindObjInObjRange( pSoldier, RPG_HE_ROCKET, RPG_FRAG_ROCKET ) );
// case MORTAR:
// return( FindObj( pSoldier, MORTAR_SHELL ) );
// case TANK_CANNON:
// return( FindObj( pSoldier, TANK_SHELL ) );
// case GLAUNCHER:
// case UNDER_GLAUNCHER:
// return( FindObjInObjRange( pSoldier, GL_HE_GRENADE, GL_SMOKE_GRENADE ) );
// default:
// return( NO_SLOT );
//}
}
}
BOOLEAN AutoReload( SOLDIERTYPE * pSoldier )
{
OBJECTTYPE *pObj, *pObj2;
INT8 bSlot;
INT16 bAPCost;
BOOLEAN fRet;
CHECKF( pSoldier );
pObj = &(pSoldier->inv[HANDPOS]);
//<SB> manual recharge
if ((*pObj)[0]->data.gun.ubGunShotsLeft && !((*pObj)[0]->data.gun.ubGunState & GS_CARTRIDGE_IN_CHAMBER) )
{
(*pObj)[0]->data.gun.ubGunState |= GS_CARTRIDGE_IN_CHAMBER;
(*pObj)[0]->data.gun.ubGunState &= ~GS_WEAPON_BEING_RELOADED;
////////////////////////////////////////////////////////////////////////////////////////////////////////
// STOMP traits - SANDRO
if ( gGameOptions.fNewTraitSystem )
{
// Sniper trait makes chambering a round faster
if (( Weapon[Item[(pObj)->usItem].ubClassIndex].ubWeaponType == GUN_SN_RIFLE || Weapon[Item[(pObj)->usItem].ubClassIndex].ubWeaponType == GUN_RIFLE ) && HAS_SKILL_TRAIT( pSoldier, SNIPER_NT ))
DeductPoints(pSoldier, ((Weapon[Item[(pObj)->usItem].ubClassIndex].APsToReloadManually * (100 - gSkillTraitValues.ubSNChamberRoundAPsReduction * NUM_SKILL_TRAITS( pSoldier, SNIPER_NT )))/100), 0);
// Ranger trait makes pumping shotguns faster
else if (( Weapon[Item[(pObj)->usItem].ubClassIndex].ubWeaponType == GUN_SHOTGUN ) && HAS_SKILL_TRAIT( pSoldier, RANGER_NT ))
DeductPoints(pSoldier, ((Weapon[Item[(pObj)->usItem].ubClassIndex].APsToReloadManually * (100 - gSkillTraitValues.ubRAPumpShotgunsAPsReduction * NUM_SKILL_TRAITS( pSoldier, RANGER_NT )))/100), 0);
else
DeductPoints(pSoldier, Weapon[Item[(pObj)->usItem].ubClassIndex].APsToReloadManually, 0);
}
else
{
DeductPoints(pSoldier, Weapon[Item[(pObj)->usItem].ubClassIndex].APsToReloadManually, 0);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
PlayJA2Sample( Weapon[ Item[pObj->usItem].ubClassIndex ].ManualReloadSound, RATE_11025, SoundVolume( HIGHVOLUME, pSoldier->sGridNo ), 1, SoundDir( pSoldier->sGridNo ) );
if ( pSoldier->IsValidSecondHandShot( ) )
{
pObj2 = &(pSoldier->inv[SECONDHANDPOS]);
if ((*pObj2)[0]->data.gun.ubGunShotsLeft && !((*pObj2)[0]->data.gun.ubGunState & GS_CARTRIDGE_IN_CHAMBER) )
{
(*pObj2)[0]->data.gun.ubGunState |= GS_CARTRIDGE_IN_CHAMBER;
PlayJA2Sample( Weapon[ Item[pObj2->usItem].ubClassIndex ].ManualReloadSound, RATE_11025, SoundVolume( HIGHVOLUME, pSoldier->sGridNo ), 1, SoundDir( pSoldier->sGridNo ) );
}
}
return TRUE;
}
else
{
if ( pSoldier->IsValidSecondHandShot( ) )
{
pObj2 = &(pSoldier->inv[SECONDHANDPOS]);
if ((*pObj2)[0]->data.gun.ubGunShotsLeft && !((*pObj2)[0]->data.gun.ubGunState & GS_CARTRIDGE_IN_CHAMBER) )
{
(*pObj2)[0]->data.gun.ubGunState |= GS_CARTRIDGE_IN_CHAMBER;
////////////////////////////////////////////////////////////////////////////////////////////////////////
// STOMP traits - SANDRO
if ( gGameOptions.fNewTraitSystem )
{
// Sniper trait makes chambering a round faster
if (( Weapon[Item[(pObj2)->usItem].ubClassIndex].ubWeaponType == GUN_SN_RIFLE || Weapon[Item[(pObj2)->usItem].ubClassIndex].ubWeaponType == GUN_RIFLE ) && HAS_SKILL_TRAIT( pSoldier, SNIPER_NT ))
DeductPoints(pSoldier, ((Weapon[Item[(pObj2)->usItem].ubClassIndex].APsToReloadManually * (100 - gSkillTraitValues.ubSNChamberRoundAPsReduction * NUM_SKILL_TRAITS( pSoldier, SNIPER_NT )))/100), 0);
// Ranger trait makes pumping shotguns faster
else if (( Weapon[Item[(pObj2)->usItem].ubClassIndex].ubWeaponType == GUN_SHOTGUN ) && HAS_SKILL_TRAIT( pSoldier, RANGER_NT ))
DeductPoints(pSoldier, ((Weapon[Item[(pObj2)->usItem].ubClassIndex].APsToReloadManually * (100 - gSkillTraitValues.ubRAPumpShotgunsAPsReduction * NUM_SKILL_TRAITS( pSoldier, RANGER_NT )))/100), 0);
else
DeductPoints(pSoldier, Weapon[Item[(pObj2)->usItem].ubClassIndex].APsToReloadManually, 0);
}
else
{
DeductPoints(pSoldier, Weapon[Item[(pObj2)->usItem].ubClassIndex].APsToReloadManually, 0);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
PlayJA2Sample( Weapon[ Item[pObj2->usItem].ubClassIndex ].ManualReloadSound, RATE_11025, SoundVolume( HIGHVOLUME, pSoldier->sGridNo ), 1, SoundDir( pSoldier->sGridNo ) );
return TRUE;
}
}
}
//</SB>
if (Item[pObj->usItem].usItemClass == IC_GUN || Item[pObj->usItem].usItemClass == IC_LAUNCHER)
{
bSlot = FindAmmoToReload( pSoldier, HANDPOS, NO_SLOT );
if (bSlot != NO_SLOT)
{
// reload using this ammo!
fRet = ReloadGun( pSoldier, pObj, &(pSoldier->inv[bSlot]) );
// if we are valid for two-pistol shooting (reloading) and we have enough APs still
// then do a reload of both guns!
if ( (fRet == TRUE) && pSoldier->IsValidSecondHandShotForReloadingPurposes( ) )
{
pObj = &(pSoldier->inv[SECONDHANDPOS]);
bSlot = FindAmmoToReload( pSoldier, SECONDHANDPOS, NO_SLOT );
if (bSlot != NO_SLOT)
{
// ce would reload using this ammo!
bAPCost = GetAPsToReloadGunWithAmmo( pSoldier, pObj, &(pSoldier->inv[bSlot] ) );
if ( EnoughPoints( pSoldier, (INT16) bAPCost, 0, FALSE ) )
{
// reload the 2nd gun too
fRet = ReloadGun( pSoldier, pObj, &(pSoldier->inv[bSlot]) );
}
else
{
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_INTERFACE, Message[ STR_RELOAD_ONLY_ONE_GUN ], pSoldier->name );
}
}
}
DirtyMercPanelInterface( pSoldier, DIRTYLEVEL2 );
return( fRet );
}
}
// couldn't reload
return( FALSE );
}
INT8 GetAttachmentComboMerge( OBJECTTYPE * pObj, UINT8 subObject )
{
INT8 bIndex = 0;
INT8 bAttachLoop;
/* check the whole Array of possible Attachements, while there are still entries ... */
while( AttachmentComboMerge[ bIndex ].usItem != NOTHING )
{
/* if we found our current Object as "basic hand" item, then
* we have found at least ONE entry of our item (may be there are more)
*/
OBJECTTYPE* pAttachment = 0;
if ( pObj->usItem == AttachmentComboMerge[ bIndex ].usItem )
{
// search for all the appropriate attachments
/* every ComboMerge must have at least one attachments Field */
for ( bAttachLoop = 0; bAttachLoop < 2; bAttachLoop++ )
{
/* if the none of both Fields contains anything, do not merge */
if ( AttachmentComboMerge[ bIndex ].usAttachment[ bAttachLoop ] == NOTHING )
{
continue;
}
/* 2007-05-27, Sgt_Kolja:
* do not return, but break the inner loop moved away, otherwise
* we can only have ONE attachmentCombo per basic item. F.I. if we want
* to make a Dart gun from Dart pistol by adding (a buttstock and) wheter a
* steel tube /or/ a Gun Barrel Extender, the old code wouldn't work for
* the Gun Barel Extender, since it would never been tested.
*/
pAttachment = FindAttachment( pObj, AttachmentComboMerge[ bIndex ].usAttachment[ bAttachLoop ], subObject );
if ( pAttachment->exists() == false )
{
// didn't find something required
break;
}
}
// found everything required?
/* 2007-05-27, Sgt_Kolja: Not-found-condition moved from above, otherwise we can only have ONE attachmentCombo per basic item */
//WarmSteel - Added check to see if the resulting item is valid.
if ( pAttachment->exists() && ItemIsLegal(AttachmentComboMerge[bIndex].usResult, TRUE) )
{
return( bIndex );
}
} /* end-if-this-is-our-item */
/* try next Attachment Order */
bIndex++;
}
return( -1 );
}
void PerformAttachmentComboMerge( OBJECTTYPE * pObj, INT8 bAttachmentComboMerge )
{
INT8 bAttachLoop;
UINT32 uiStatusTotal = 0;
INT8 bNumStatusContributors = 0;
// This object has been validated as available for an attachment combo merge.
// - find all attachments in list and destroy them
// - status of new object should be average of items including attachments
// - change object
for ( bAttachLoop = 0; bAttachLoop < 2; bAttachLoop++ )
{
if ( AttachmentComboMerge[ bAttachmentComboMerge ].usAttachment[ bAttachLoop ] == NOTHING )
{
continue;
}
OBJECTTYPE* pAttachment = FindAttachment( pObj, AttachmentComboMerge[ bAttachmentComboMerge ].usAttachment[ bAttachLoop ] );
AssertMsg( pAttachment != 0, String( "Attachment combo merge couldn't find a necessary attachment" ) );
uiStatusTotal += (*pAttachment)[0]->data.objectStatus;
bNumStatusContributors++;
pObj->RemoveAttachment(pAttachment);
}
uiStatusTotal += (*pObj)[0]->data.objectStatus;
bNumStatusContributors++;
pObj->usItem = AttachmentComboMerge[ bAttachmentComboMerge ].usResult;
RemoveProhibitedAttachments(NULL, pObj, pObj->usItem);
(*pObj)[0]->data.objectStatus = (INT8) (uiStatusTotal / bNumStatusContributors );
}
BOOLEAN OBJECTTYPE::AttachObjectOAS( SOLDIERTYPE * pSoldier, OBJECTTYPE * pAttachment, BOOLEAN playSound, UINT8 subObject )
{
//CHRISL: This makes it impossible to add attachments to objects in a stack. Let's remove this and make this possible.
//if ( this->ubNumberOfObjects > 1 )
//{
// return( FALSE );
//}
if (pAttachment->exists() == false) {
return FALSE;
}
if ((*this)[subObject]->attachments.size() >= OLD_MAX_ATTACHMENTS_101) {
return FALSE;
}
//CHRISL: If we're adding a loaded UGL, then we have to make sure there are actually 2 open attachment slots instead of 1
if(Item[pAttachment->usItem].grenadelauncher && (*pAttachment)[0]->attachments.size() > 0) {
if ((*this)[subObject]->attachments.size() >= (OLD_MAX_ATTACHMENTS_101-1))
return FALSE;
}
static OBJECTTYPE attachmentObject;
UINT16 usResult, usResult2, ubLimit;
INT8 bLoop;
UINT8 ubType, ubAPCost;
INT32 iCheckResult;
INT8 bAttachInfoIndex = -1, bAttachComboMerge;
BOOLEAN fValidLaunchable = FALSE;
UINT16 oldMagSize = 0;
//CHRISL: This is so we can try to determine if the removed attachment altered our mag size.
if(Item[this->usItem].usItemClass == IC_GUN)
oldMagSize = GetMagSize(this);
bool canOnlyAttach1 = false;
//if this is an attachment or ammo for a launchable item
fValidLaunchable = ValidLaunchable( pAttachment->usItem, this->usItem );
//CHRISL: If we don't want to play the sound, it's a good bet we don't want to display any messages either
if ( fValidLaunchable || ValidItemAttachment( this, pAttachment->usItem, TRUE, playSound, subObject ) )
{
//if there is already an attachment of the same type, we want to try swapping / replacing it
OBJECTTYPE* pAttachmentPosition = 0;
// find an attachment position...
// second half of this 'if' is for attaching GL grenades to a gun w/attached GL
if ( fValidLaunchable || (Item[pAttachment->usItem].glgrenade && FindAttachmentByClass(this, IC_LAUNCHER, subObject) != 0 ) )
{
canOnlyAttach1 = true;
// try replacing if possible
pAttachmentPosition = FindAttachmentByClass( this, Item[ pAttachment->usItem ].usItemClass, subObject );
}
else
{
// try replacing if possible
pAttachmentPosition = FindAttachment( this, pAttachment->usItem, subObject );
}
if ( pSoldier )
{
//did the soldier damage it?
bAttachInfoIndex = GetAttachmentInfoIndex( pAttachment->usItem );
// in-game (not behind the scenes) attachment
if ( bAttachInfoIndex != -1 && AttachmentInfo[ bAttachInfoIndex ].bAttachmentSkillCheck != NO_CHECK )
{
iCheckResult = SkillCheck( pSoldier, AttachmentInfo[ bAttachInfoIndex ].bAttachmentSkillCheck, AttachmentInfo[ bAttachInfoIndex ].bAttachmentSkillCheckMod );
if (iCheckResult < 0)
{
// the attach failure damages both items
DamageObj( this, (INT8) -iCheckResult, subObject );
DamageObj( pAttachment, (INT8) -iCheckResult, subObject );
// there should be a quote here!
pSoldier->DoMercBattleSound( BATTLE_SOUND_CURSE1 );
if ( gfInItemDescBox )
{
DeleteItemDescriptionBox();
}
return( FALSE );
}
}
if ( ValidItemAttachment( this, pAttachment->usItem, TRUE, TRUE, subObject ) && playSound ) // not launchable
{
// attachment sounds
if ( Item[ this->usItem ].usItemClass & IC_WEAPON )
{
PlayJA2Sample( ATTACH_TO_GUN, RATE_11025, SoundVolume( MIDVOLUME, pSoldier->sGridNo ), 1, SoundDir( pSoldier->sGridNo ) );
}
else if ( Item[ this->usItem ].usItemClass & IC_ARMOUR )
{
PlayJA2Sample( ATTACH_CERAMIC_PLATES, RATE_11025, SoundVolume( MIDVOLUME, pSoldier->sGridNo ), 1, SoundDir( pSoldier->sGridNo ) );
}
else if ( Item[ this->usItem ].usItemClass & IC_BOMB )
{
PlayJA2Sample( ATTACH_DETONATOR, RATE_11025, SoundVolume( MIDVOLUME, pSoldier->sGridNo ), 1, SoundDir( pSoldier->sGridNo ) );
}
}
}
if (pAttachmentPosition) {
if (canOnlyAttach1 == true) {
if(pAttachment->ubNumberOfObjects > 1)
{
//We don't want to inadvertantly load two rounds during a swap so don't allow a swap if we're holding a stack
return(FALSE);
}
//we have requested to swap the attachment on the cursor with the current attachment
SwapObjs(pAttachmentPosition,pAttachment);
return(TRUE);
}
}
//ADB moved after skill check!
//lalien: added to make a GL/RL work when reloaded manually
// the AP costs for reloading GL/RL will be taken from weapons.xml ( wrong place!!! the AP's are deducted in DeleteItemDescriptionBox() )
//if (pAttachmentPosition) {
if(pAttachmentPosition || (pAttachmentPosition == NULL && (*this)[subObject]->attachments.size() < OLD_MAX_ATTACHMENTS_101)){
//we know we are replacing this attachment
if ( Item[ this->usItem ].usItemClass == IC_LAUNCHER || Item[this->usItem].cannon )
{
if ( fValidLaunchable )
{
(*this)[subObject]->data.gun.usGunAmmoItem = pAttachment->usItem;
//we have reloaded a launchable, so the ammo is gone from the original object
}
}
}
//unfortunately must come before possible attachment swap
if (Item[pAttachment->usItem].grenadelauncher )
{
// transfer any attachments from the grenade launcher to the gun
(*this)[subObject]->attachments.splice((*this)[subObject]->attachments.begin(), (*pAttachment)[0]->attachments,
(*pAttachment)[0]->attachments.begin(), (*pAttachment)[0]->attachments.end());
}
if (pAttachmentPosition) {
//we are swapping the attachments, and we know we do NOT need to worry about attachment stack size
//CHRISL: Actually, we do need to worry about attachment stack size since we might have a stack in our cursor.
// Rather then doing a simple swap, try moving the existing attachment to our cursor stack, then attach one item
// from the cursor stack.
pAttachment->AddObjectsToStack(*pAttachmentPosition,-1,pSoldier,NUM_INV_SLOTS,MAX_OBJECTS_PER_SLOT);
pAttachment->MoveThisObjectTo(attachmentObject,1,pSoldier,NUM_INV_SLOTS,1);
*pAttachmentPosition = attachmentObject;
//backup the original attachment
//attachmentObject = *pAttachmentPosition;
//place the new one
//*pAttachmentPosition = *pAttachment;
//whatever pAttachment pointed to is now the original attachment
//*pAttachment = attachmentObject;
}
else {
//it's a new attachment
if (canOnlyAttach1 == true) {
//we only placed one of the stack, pAttachment could have any number of objects
if (pAttachment->MoveThisObjectTo(attachmentObject,1,pSoldier,NUM_INV_SLOTS,1) == 0) {
(*this)[subObject]->attachments.push_back(attachmentObject);
}
}
else {
//pAttachment could have any number of objects, they have all been moved over
//CHRISL: This doesn't work. What if we have a stack of objects in the cursor? We don't want the whole
// stack to be attached
//(*this)[subObject]->attachments.push_back(*pAttachment);
//DeleteObj(pAttachment);
if (pAttachment->MoveThisObjectTo(attachmentObject,1,pSoldier,NUM_INV_SLOTS,1) == 0) {
(*this)[subObject]->attachments.push_back(attachmentObject);
}
}
}
//Ammo might have changed after adding an attachment.
if ( Item[this->usItem].usItemClass == IC_GUN && (*this)[subObject]->data.gun.usGunAmmoItem != NONE && (*this)[subObject]->data.gun.ubGunShotsLeft > 0 && oldMagSize != GetMagSize(this, subObject) )
{
if ( (*this)[subObject]->data.gun.ubGunShotsLeft > GetMagSize(this, subObject) )
{ //Too many rounds, eject ammo
EjectAmmoAndPlace(pSoldier, this, subObject);
}
//CHRISL: We should update the usGunAmmoItem if we've changed the ammo capacity
if((*this)[subObject]->data.gun.usGunAmmoItem != NONE){
UINT16 usNewAmmoItem;
usNewAmmoItem = FindReplacementMagazine(Weapon[this->usItem].ubCalibre ,GetMagSize(this, subObject),Magazine[Item[(*this)[subObject]->data.gun.usGunAmmoItem].ubClassIndex].ubAmmoType);
(*this)[subObject]->data.gun.usGunAmmoItem = usNewAmmoItem;
}
}
if(Item[this->usItem].usItemClass == IC_GUN && oldMagSize != GetMagSize(this, subObject)){
fInterfacePanelDirty = DIRTYLEVEL2;
RenderBulletIcon(this, subObject);
}
// Check for attachment merge combos here
//CHRISL: Only do this if we're looking at a single item. Don't try a combo merge when dealing with a stack
bAttachComboMerge = GetAttachmentComboMerge( this, subObject );
if ( bAttachComboMerge != -1 )
{
if(this->ubNumberOfObjects == 1)
{
PerformAttachmentComboMerge( this, bAttachComboMerge );
if ( bAttachInfoIndex != -1 && AttachmentInfo[ bAttachInfoIndex ].bAttachmentSkillCheckMod < 20 )
{
StatChange( pSoldier, MECHANAMT, (INT8) ( 20 - AttachmentInfo[ bAttachInfoIndex ].bAttachmentSkillCheckMod ), FALSE );
StatChange( pSoldier, WISDOMAMT, (INT8) ( 20 - AttachmentInfo[ bAttachInfoIndex ].bAttachmentSkillCheckMod ), FALSE );
}
}
//CHRISL: If we're looking at a stack, we need to unattach the object we just attached
else if(this->RemoveAttachment(&attachmentObject, pAttachmentPosition, subObject))
{
pAttachment->AddObjectsToStack(attachmentObject, -1, pSoldier, NUM_INV_SLOTS, MAX_OBJECTS_PER_SLOT);
}
}
//ADB ubWeight has been removed, see comments in OBJECTTYPE
//this->ubWeight = CalculateObjectWeight( this );
//ADB ubWeight has been removed, see comments in OBJECTTYPE
//pAttachment->ubWeight = CalculateObjectWeight(pAttachment);
if ( pSoldier != NULL )
ApplyEquipmentBonuses(pSoldier);
return( TRUE );
}
// check for merges
else if (EvaluateValidMerge( pAttachment->usItem, this->usItem, &usResult, &usResult2, &ubType, &ubAPCost ))
{
//CHRISL: we don't want to try to merge IC_LBEGEAR items that are currently storing items.
if(Item[this->usItem].usItemClass == IC_LBEGEAR)
{
if(this->IsActiveLBE(subObject) == true)
return( FALSE );
}
//CHRISL: We don't want to do any merges if we're looking at a stack of items, with the exception of combines.
if ( this->ubNumberOfObjects > 1 && ubType != COMBINE_POINTS )
{
return( FALSE );
}
if ( ubType != COMBINE_POINTS )
{
if ( pSoldier )
{
if ( !EnoughPoints( pSoldier, ubAPCost, 0, TRUE ) )
{
return( FALSE );
}
//lalien: don't charge AP's for reloading a GL/RL ( wrong place!!! the AP's are deducted in DeleteItemDescriptionBox() )
//if ( IsAGLorRL == FALSE )
//{
DeductPoints( pSoldier, ubAPCost, 0 );
//}
}
}
switch( ubType )
{
case USE_ITEM:
case USE_ITEM_HARD:
// the merge will combine the two items
if ( pSoldier )
{
if ( ubType == USE_ITEM_HARD )
{
// requires a skill check, and gives experience
iCheckResult = SkillCheck( pSoldier, ATTACHING_SPECIAL_ITEM_CHECK, -30 );
if (iCheckResult < 0)
{
// could have a chance of detonation
// for now, damage both objects
DamageObj( this, (INT8) -iCheckResult );
DamageObj( pAttachment, (INT8) -iCheckResult );
pSoldier->DoMercBattleSound( BATTLE_SOUND_CURSE1 );
return( FALSE );
}
StatChange( pSoldier, MECHANAMT, 25, FALSE );
StatChange( pSoldier, WISDOMAMT, 5, FALSE );
// SANDRO - merc records - merging items
if ( pSoldier->ubProfile != NO_PROFILE )
gMercProfiles[ pSoldier->ubProfile ].records.usItemsCombined++;
}
//Madd: note that use_item cannot produce two different items!!! so it doesn't use usResult2
//Madd: unload guns after merge if ammo caliber or mag size don't match
if ( Item[this->usItem].usItemClass == IC_GUN && (*this)[0]->data.gun.usGunAmmoItem != NONE && (*this)[0]->data.gun.ubGunShotsLeft > 0 )
{
if ( Item[usResult].usItemClass != IC_GUN || Weapon[Item[usResult].ubClassIndex].ubCalibre != Weapon[Item[this->usItem].ubClassIndex].ubCalibre || (*this)[0]->data.gun.ubGunShotsLeft > Weapon[Item[usResult].ubClassIndex].ubMagSize )
{ // item types/calibers/magazines don't match, spit out old ammo
EjectAmmoAndPlace(pSoldier, this);
}
}
RemoveProhibitedAttachments(pSoldier, this, usResult);
this->usItem = usResult;
//AutoPlaceObject( pAttachment );
//ADB ubWeight has been removed, see comments in OBJECTTYPE
//this->ubWeight = CalculateObjectWeight( this );
if (pSoldier->bTeam == gbPlayerNum)
{
pSoldier->DoMercBattleSound( BATTLE_SOUND_COOL1 );
}
ApplyEquipmentBonuses(pSoldier);
return TRUE;
}
else
return FALSE;
case COMBINE_POINTS:
// transfer points...
UINT32 combinedAmount;
UINT32 attachmentAmount;
//CHRISL: Treat differently if we're combining money items (other then MONEY)
if(Item[this->usItem].usItemClass != IC_MONEY)
{
if ( Item[ this->usItem ].usItemClass == IC_AMMO )
{
ubLimit = Magazine[ Item[ this->usItem ].ubClassIndex ].ubMagSize;
}
else
{
ubLimit = 100;
}
// count down through # of attaching items and add to status of item in position 0
for (bLoop = 0; bLoop < pAttachment->ubNumberOfObjects; )
{
//ADB need to watch for overflow here (thus UINT32), and need to cast to UINT8 before adding
combinedAmount = (UINT16)(*this)[subObject]->data.objectStatus + (UINT16)(*pAttachment)[0]->data.objectStatus;
if (combinedAmount <= ubLimit)
{
// consume this one totally and continue
(*this)[subObject]->data.objectStatus = combinedAmount;
pAttachment->RemoveObjectsFromStack(1);
}
else
{
// add part of this one and then we're done
attachmentAmount = (UINT16)(*pAttachment)[0]->data.objectStatus;
attachmentAmount -= (ubLimit - (UINT16)(*this)[subObject]->data.objectStatus);
(*pAttachment)[0]->data.objectStatus = attachmentAmount;
if ((*pAttachment)[0]->data.ubShotsLeft == 0) {
pAttachment->RemoveObjectsFromStack(1);
}
(*this)[subObject]->data.ubShotsLeft = ubLimit;
break;
}
}
}
else
{
ubLimit = MAX_MONEY_PER_SLOT;
combinedAmount = (*this)[subObject]->data.money.uiMoneyAmount + (*pAttachment)[0]->data.money.uiMoneyAmount;
if (combinedAmount <= ubLimit)
{
(*this)[subObject]->data.money.uiMoneyAmount = combinedAmount;
pAttachment->RemoveObjectsFromStack(1);
}
else
{
attachmentAmount = (*pAttachment)[0]->data.money.uiMoneyAmount;
attachmentAmount -= (ubLimit - (*this)[subObject]->data.money.uiMoneyAmount);
(*pAttachment)[0]->data.money.uiMoneyAmount = attachmentAmount;
if((*pAttachment)[0]->data.money.uiMoneyAmount == 0)
{
pAttachment->RemoveObjectsFromStack(1);
}
(*this)[subObject]->data.money.uiMoneyAmount = ubLimit;
break;
}
}
break;
case DESTRUCTION:
// the merge destroyed both items!
this->RemoveObjectsFromStack(1);
pAttachment->RemoveObjectsFromStack(1);
if ( pSoldier )
{
pSoldier->DoMercBattleSound( BATTLE_SOUND_CURSE1 );
}
break;
case ELECTRONIC_MERGE:
if ( pSoldier )
{
iCheckResult = SkillCheck( pSoldier, ATTACHING_SPECIAL_ELECTRONIC_ITEM_CHECK, -30 );
if ( iCheckResult < 0 )
{
DamageObj( this, (INT8) -iCheckResult );
DamageObj( pAttachment, (INT8) -iCheckResult );
pSoldier->DoMercBattleSound( BATTLE_SOUND_CURSE1 );
return( FALSE );
}
// grant experience! ... SANDRO - so what?! Grant them already!
StatChange( pSoldier, MECHANAMT, 30, FALSE );
StatChange( pSoldier, WISDOMAMT, 10, FALSE );
// SANDRO - merc records - merging items
if ( pSoldier->ubProfile != NO_PROFILE )
gMercProfiles[ pSoldier->ubProfile ].records.usItemsCombined++;
}
// fall through
case EXPLOSIVE:
if ( ubType == EXPLOSIVE ) /// coulda fallen through
{
if (pSoldier)
{
// requires a skill check, and gives experience
iCheckResult = SkillCheck( pSoldier, ATTACHING_DETONATOR_CHECK, -30 );
if (iCheckResult < 0)
{
// could have a chance of detonation
// for now, damage both objects
DamageObj( this, (INT8) -iCheckResult );
DamageObj( pAttachment, (INT8) -iCheckResult );
pSoldier->DoMercBattleSound( BATTLE_SOUND_CURSE1 );
return( FALSE );
}
StatChange( pSoldier, EXPLODEAMT, 25, FALSE );
StatChange( pSoldier, WISDOMAMT, 5, FALSE );
// SANDRO - merc records - merging items
if ( pSoldier->ubProfile != NO_PROFILE )
gMercProfiles[ pSoldier->ubProfile ].records.usItemsCombined++;
}
}
// fall through
default:
// the merge will combine the two items
//Madd: usResult2 only works for standard merges->item1 + item2 = item3 + item4
//Madd: unload guns after merge if ammo caliber or mag size don't match
if ( Item[this->usItem].usItemClass == IC_GUN && (*this)[subObject]->data.gun.usGunAmmoItem != NONE && (*this)[subObject]->data.gun.ubGunShotsLeft > 0 )
{
if ( Item[usResult].usItemClass != IC_GUN || Weapon[Item[usResult].ubClassIndex].ubCalibre != Weapon[Item[this->usItem].ubClassIndex].ubCalibre || (*this)[subObject]->data.gun.ubGunShotsLeft > Weapon[Item[usResult].ubClassIndex].ubMagSize )
{ // item types/calibers/magazines don't match, spit out old ammo
EjectAmmoAndPlace(pSoldier, this);
}
}
RemoveProhibitedAttachments(pSoldier, this, usResult);
this->usItem = usResult;
if ( ubType != TREAT_ARMOUR )
{
(*this)[subObject]->data.objectStatus = ((*this)[subObject]->data.objectStatus + (*pAttachment)[0]->data.objectStatus) / 2;
}
//ADB ubWeight has been removed, see comments in OBJECTTYPE
//this->ubWeight = CalculateObjectWeight( this );
if ( usResult2 != NOTHING )
{
//Madd: usResult2 is what the original attachment/source item turns into
//Madd: unload guns after merge if ammo caliber or mag size don't match
if ( Item[pAttachment->usItem].usItemClass == IC_GUN && (*pAttachment)[0]->data.gun.usGunAmmoItem != NONE && (*pAttachment)[0]->data.gun.ubGunShotsLeft > 0 )
{
if ( Item[usResult2].usItemClass != IC_GUN || Weapon[Item[usResult2].ubClassIndex].ubCalibre != Weapon[Item[pAttachment->usItem].ubClassIndex].ubCalibre || (*pAttachment)[0]->data.gun.ubGunShotsLeft > Weapon[Item[usResult2].ubClassIndex].ubMagSize )
{ // item types/calibers/magazines don't match, spit out old ammo
EjectAmmoAndPlace(pSoldier, pAttachment);
}
}
RemoveProhibitedAttachments(pSoldier, pAttachment, usResult2);
pAttachment->usItem = usResult2;
if ( ubType != TREAT_ARMOUR )
{
(*pAttachment)[0]->data.objectStatus = ((*pAttachment)[0]->data.objectStatus + (*this)[subObject]->data.objectStatus) / 2;
}
//ADB ubWeight has been removed, see comments in OBJECTTYPE
//pAttachment->ubWeight = CalculateObjectWeight( pAttachment );
}
else
pAttachment->RemoveObjectsFromStack(1);
if (pSoldier && pSoldier->bTeam == gbPlayerNum)
{
pSoldier->DoMercBattleSound( BATTLE_SOUND_COOL1 );
}
break;
}
if ( pSoldier != NULL )
ApplyEquipmentBonuses(pSoldier);
return( TRUE );
}
return( FALSE );
}
BOOLEAN OBJECTTYPE::AttachObject( SOLDIERTYPE * pSoldier, OBJECTTYPE * pAttachment, BOOLEAN playSound, UINT8 subObject, INT32 iItemPos, BOOLEAN fRemoveProhibited, std::vector<UINT16> usAttachmentSlotIndexVector )
{
if(UsingNewAttachmentSystem()==true){
return( this->AttachObjectNAS(pSoldier, pAttachment, playSound, subObject, iItemPos, fRemoveProhibited, usAttachmentSlotIndexVector ) );
} else {
return( this->AttachObjectOAS( pSoldier, pAttachment, playSound, subObject) );
}
}
BOOLEAN OBJECTTYPE::AttachObjectNAS( SOLDIERTYPE * pSoldier, OBJECTTYPE * pAttachment, BOOLEAN playSound, UINT8 subObject, INT32 iItemPos, BOOLEAN fRemoveProhibited, std::vector<UINT16> usAttachmentSlotIndexVector )
{
if (pAttachment->exists() == false) {
return FALSE;
}
UINT16 usResult, usResult2, ubLimit;
INT8 bLoop;
UINT8 ubType, ubAPCost;
INT32 iCheckResult;
INT8 bAttachInfoIndex = -1, bAttachComboMerge;
BOOLEAN fValidLaunchable = FALSE;
BOOLEAN fValidItemAttachment = FALSE;
INT32 curSlot = 0;
UINT16 oldMagSize = 0;
//if there is already an attachment of the same type, we want to try swapping / replacing it
OBJECTTYPE* pAttachmentPosition = 0;
//OBJECTTYPE* pAttachInSlot = 0;
static OBJECTTYPE attachmentObject;
//CHRISL: This is so we can try to determine if the removed attachment altered our mag size.
if(Item[this->usItem].usItemClass == IC_GUN)
oldMagSize = GetMagSize(this);
//if this is an attachment or ammo for a launchable item
fValidLaunchable = ValidLaunchable( pAttachment->usItem, this->usItem );
//WarmSteel - if uiItemPos is -1, we're not checking for a specific slot, but scrolling through them all.
if(iItemPos == -1){
//WarmSteel - repeat this for every slot
for(curSlot = 0; curSlot < (INT32)(*this)[0]->attachments.size(); curSlot++)
{
fValidItemAttachment = ValidItemAttachmentSlot( this, pAttachment->usItem, TRUE, FALSE, subObject, curSlot, 0, 0, usAttachmentSlotIndexVector);
if(fValidItemAttachment){
//WarmSteel - apparently we found a attachable slot, exiting here will remember the curSlot
break;
}
}
//WarmSteel - if we didn't find any good slot, always just attach to the first slot. (because some functions will overrule this one).
//It's basically just a general check so that we NEVER try to attach outside the attachment list range.
if(curSlot == (*this)[subObject]->attachments.size())
curSlot = 0;
} else {
//WarmSteel - We know in what slot we're trying to put this, so lets see if we can.
curSlot = iItemPos;
fValidItemAttachment = ValidItemAttachmentSlot( this, pAttachment->usItem, TRUE, playSound, subObject, curSlot, FALSE, &pAttachmentPosition, usAttachmentSlotIndexVector);
//pAttachmentPosition = pAttachInSlot;
// try replacing if possible
}
//CHRISL: If we don't want to play the sound, it's a good bet we don't want to display any messages either
if (/*fValidLaunchable ||*/ fValidItemAttachment )
{
if ( pSoldier )
{
//did the soldier damage it?
bAttachInfoIndex = GetAttachmentInfoIndex( pAttachment->usItem );
// in-game (not behind the scenes) attachment
if ( bAttachInfoIndex != -1 && AttachmentInfo[ bAttachInfoIndex ].bAttachmentSkillCheck != NO_CHECK )
{
iCheckResult = SkillCheck( pSoldier, AttachmentInfo[ bAttachInfoIndex ].bAttachmentSkillCheck, AttachmentInfo[ bAttachInfoIndex ].bAttachmentSkillCheckMod );
if (iCheckResult < 0)
{
// the attach failure damages both items
DamageObj( this, (INT8) -iCheckResult, subObject );
DamageObj( pAttachment, (INT8) -iCheckResult, subObject );
// there should be a quote here!
pSoldier->DoMercBattleSound( BATTLE_SOUND_CURSE1 );
if ( gfInItemDescBox )
{
//DeleteItemDescriptionBox();
}
return( FALSE );
}
}
if (fValidItemAttachment && playSound ) // not launchable
{
// attachment sounds
if ( Item[ this->usItem ].usItemClass & IC_WEAPON )
{
PlayJA2Sample( ATTACH_TO_GUN, RATE_11025, SoundVolume( MIDVOLUME, pSoldier->sGridNo ), 1, SoundDir( pSoldier->sGridNo ) );
}
else if ( Item[ this->usItem ].usItemClass & IC_ARMOUR )
{
PlayJA2Sample( ATTACH_CERAMIC_PLATES, RATE_11025, SoundVolume( MIDVOLUME, pSoldier->sGridNo ), 1, SoundDir( pSoldier->sGridNo ) );
}
else if ( Item[ this->usItem ].usItemClass & IC_BOMB )
{
PlayJA2Sample( ATTACH_DETONATOR, RATE_11025, SoundVolume( MIDVOLUME, pSoldier->sGridNo ), 1, SoundDir( pSoldier->sGridNo ) );
}
}
}
/* //NAS doesn't care about single attachments.
if (pAttachmentPosition) {
if (canOnlyAttach1 == true) {
if(pAttachment->ubNumberOfObjects > 1)
{
//We don't want to inadvertantly load two rounds during a swap so don't allow a swap if we're holding a stack
return(FALSE);
}
//we have requested to swap the attachment on the cursor with the current attachment
SwapObjs(pAttachmentPosition,pAttachment);
return(TRUE);
}
}*/
//ADB moved after skill check!
//lalien: added to make a GL/RL work when reloaded manually
// the AP costs for reloading GL/RL will be taken from weapons.xml ( wrong place!!! the AP's are deducted in DeleteItemDescriptionBox() )
//we know we are replacing this attachment
if ( Item[ this->usItem ].usItemClass == IC_LAUNCHER || Item[this->usItem].cannon )
{
if ( fValidLaunchable )
{
(*this)[subObject]->data.gun.usGunAmmoItem = pAttachment->usItem;
//we have reloaded a launchable, so the ammo is gone from the original object
}
}
/* //WarmSteel - splice won't work with attachments anymore, because of the null attachments. Replaced this function somewhere lower, because it needs to be done after the attaching of the GL.
//Unfortunately this must come before any attachment swap
if (Item[pAttachment->usItem].grenadelauncher && gGameOptions.ubAttachmentSystem == ATTACHMENT_OLD)
{
// transfer any attachments from the grenade launcher to the gun
(*this)[subObject]->attachments.splice((*this)[subObject]->attachments.begin(), (*pAttachment)[0]->attachments,
(*pAttachment)[0]->attachments.begin(), (*pAttachment)[0]->attachments.end());
}*/
//WarmSteel - Attachment swapping prevents multiple objects that are the same to be attached.
//This takes away freedom, which is bad. This is why I turned it off in NAS (If you want to turn it back on, it also doesn't work properly because it needs to swap xml slot indexes aswell).
if (pAttachmentPosition->exists()) {
//we are swapping the attachments, and we know we do NOT need to worry about attachment stack size
//CHRISL: Actually, we do need to worry about attachment stack size since we might have a stack in our cursor.
// Rather then doing a simple swap, try moving the existing attachment to our cursor stack, then attach one item
// from the cursor stack.
//CHRISL: Try to replace illegal IC_GRENADE items with legal ones
if(!ItemIsLegal(pAttachment->usItem) && Item[pAttachment->usItem].usItemClass & IC_GRENADE){
OBJECTTYPE* newAttachment = new OBJECTTYPE;
UINT16 newItem;
newItem = FindLegalGrenade(pAttachment->usItem);
if(newItem != pAttachment->usItem){
CreateItem(newItem, 100, newAttachment);
(*pAttachment)[0]->data.objectStatus -= (INT16)(100/Weapon[this->usItem].ubMagSize);
if((*pAttachment)[0]->data.objectStatus <= 0 )
pAttachment->RemoveObjectsFromStack(1);
newAttachment->MoveThisObjectTo(attachmentObject,1,pSoldier,NUM_INV_SLOTS,1);
} else {
pAttachment->MoveThisObjectTo(attachmentObject,1,pSoldier,NUM_INV_SLOTS,1);
}
} else {
pAttachment->MoveThisObjectTo(attachmentObject,1,pSoldier,NUM_INV_SLOTS,1);
}
if(pAttachment->ubNumberOfObjects > 0){
if (pSoldier) {
if ( !AutoPlaceObject( pSoldier, pAttachmentPosition, FALSE ) )
{ // put it on the ground
AddItemToPool( pSoldier->sGridNo, pAttachmentPosition, 1, pSoldier->pathing.bLevel, 0 , -1 );
}
}
} else {
pAttachment->AddObjectsToStack(*pAttachmentPosition,-1,pSoldier,NUM_INV_SLOTS,MAX_OBJECTS_PER_SLOT);
}
*pAttachmentPosition = attachmentObject;
(*this)[subObject]->AddAttachmentAtIndex(curSlot, attachmentObject);
//backup the original attachment
//attachmentObject = *pAttachmentPosition;
//place the new one
//*pAttachmentPosition = *pAttachment;
//whatever pAttachment pointed to is now the original attachment
//*pAttachment = attachmentObject;
}
else {
//it's a new attachment
//pAttachment could have any number of objects, they have all been moved over
//CHRISL: This doesn't work. What if we have a stack of objects in the cursor? We don't want the whole
// stack to be attached
//(*this)[subObject]->attachments.push_back(*pAttachment);
//DeleteObj(pAttachment);
//CHRISL: Try to replace illegal IC_GRENADE items with legal ones
if(!ItemIsLegal(pAttachment->usItem) && Item[pAttachment->usItem].usItemClass & IC_GRENADE){
OBJECTTYPE* newAttachment = new OBJECTTYPE;
UINT16 newItem;
newItem = FindLegalGrenade(pAttachment->usItem);
if(newItem != pAttachment->usItem){
CreateItem(newItem, 100, newAttachment);
(*pAttachment)[0]->data.objectStatus -= (INT16)(100/Weapon[this->usItem].ubMagSize);
if((*pAttachment)[0]->data.objectStatus <= 0 )
pAttachment->RemoveObjectsFromStack(1);
newAttachment->MoveThisObjectTo(attachmentObject,1,pSoldier,NUM_INV_SLOTS,1);
} else {
pAttachment->MoveThisObjectTo(attachmentObject,1,pSoldier,NUM_INV_SLOTS,1);
}
} else {
pAttachment->MoveThisObjectTo(attachmentObject,1,pSoldier,NUM_INV_SLOTS,1);
}
//WarmSteel - Because we want every attachment to stay in place in NAS, we must first delete the "null" attachment, then insert the new one.
//We know this attachment slot has a non-null object, otherwise ValidItemAttachmentSlot would not have returned true and we would not be here.
(*this)[subObject]->AddAttachmentAtIndex(curSlot, attachmentObject);
}
//Ammo might have changed after adding an attachment.
if ( Item[this->usItem].usItemClass == IC_GUN && (*this)[subObject]->data.gun.usGunAmmoItem != NONE && (*this)[subObject]->data.gun.ubGunShotsLeft > 0 && oldMagSize != GetMagSize(this, subObject) )
{
if ( (*this)[subObject]->data.gun.ubGunShotsLeft > GetMagSize(this, subObject) )
{ //Too many rounds, eject ammo
EjectAmmoAndPlace(pSoldier, this, subObject);
}
//CHRISL: We should update the usGunAmmoItem if we've changed the ammo capacity
if((*this)[subObject]->data.gun.usGunAmmoItem != NONE){
UINT16 usNewAmmoItem;
usNewAmmoItem = FindReplacementMagazine(Weapon[this->usItem].ubCalibre ,GetMagSize(this, subObject),Magazine[Item[(*this)[subObject]->data.gun.usGunAmmoItem].ubClassIndex].ubAmmoType);
(*this)[subObject]->data.gun.usGunAmmoItem = usNewAmmoItem;
}
}
if(Item[this->usItem].usItemClass == IC_GUN && oldMagSize != GetMagSize(this, subObject)){
fInterfacePanelDirty = DIRTYLEVEL2;
RenderBulletIcon(this, subObject);
}
//WarmSteel - If we have just attached a UGL, remove it's grenade and put it on the gun itself
//CHRISL: This section of code is also needed it we add any attachment that changes the valid attachments our item can use, so we should run it whenever we
// add an attachment in NAS
//if (FindAttachment_GrenadeLauncher(this)->exists() && attachmentObject.exists())
if (attachmentObject.exists() && attachmentObject[0]->attachments.size() > 0 && FindAttachment(this, attachmentObject.usItem, subObject)->exists())
{
//Make sure it's actually on that gun..
//if(FindAttachment_GrenadeLauncher(this)->usItem == attachmentObject.usItem){
if(FindAttachment(this, attachmentObject.usItem, subObject)->usItem == attachmentObject.usItem){
// transfer the grenade from the grenade launcher to the gun
//To know wether this grenade is valid, we need to correct the slots, because they may have changed when attaching the UGL
//Have to do it here, because from now on we don't need attachmentObject anymore.
//CHRISL: Because we want this function to be useful for more then just UGLs, and because there is the probability that the attaching item will
// give us more attachment points, we need to just remove all attachments, tack them to the end of the attachmentList, and then go through the
// RemoveProhibitedAttachments function to force everything to store in the correct slot
OBJECTTYPE * pGrenade = FindAttachment(this, attachmentObject.usItem, subObject);
for(attachmentList::iterator iter = (*pGrenade)[0]->attachments.begin(); iter != (*pGrenade)[0]->attachments.end(); ++iter){
if(iter->exists()){
(*this)[subObject]->attachments.push_back((*iter));
iter = (*pGrenade)[0]->RemoveAttachmentAtIter(iter);
fRemoveProhibited = TRUE;
}
}
// if(fRemoveProhibited){
// RemoveProhibitedAttachments(pSoldier, this, this->usItem);
// }
/* CHRISL: None of this is needed. Instead we strip any attachments from attachmentObject in the above loop.
for(INT16 sSlot = 0; sSlot < (INT16) (*this)[subObject]->attachments.size(); sSlot++){
OBJECTTYPE * pGrenade = FindAttachmentByClass(FindAttachment_GrenadeLauncher(this), IC_GRENADE, subObject);
if(pGrenade->exists()){
if(ValidItemAttachmentSlot(this, pGrenade->usItem, 1, 0, 0, sSlot)){
OBJECTTYPE tempObject;
FindAttachment_GrenadeLauncher(this)->RemoveAttachment(pGrenade,&tempObject,0,0,1,0);
(*this)[subObject]->AddAttachmentAtIndex((UINT8) sSlot, tempObject);
}
}
}*/
}
}
//Check if any of the attached items has changed the slots (including the UGL grenade we just added).
if(fRemoveProhibited){
RemoveProhibitedAttachments(pSoldier, this, this->usItem);
}
// Check for attachment merge combos here
//CHRISL: Only do this if we're looking at a single item. Don't try a combo merge when dealing with a stack
bAttachComboMerge = GetAttachmentComboMerge( this, subObject );
if ( bAttachComboMerge != -1 )
{
if(this->ubNumberOfObjects == 1)
{
PerformAttachmentComboMerge( this, bAttachComboMerge );
if ( bAttachInfoIndex != -1 && AttachmentInfo[ bAttachInfoIndex ].bAttachmentSkillCheckMod < 20 )
{
StatChange( pSoldier, MECHANAMT, (INT8) ( 20 - AttachmentInfo[ bAttachInfoIndex ].bAttachmentSkillCheckMod ), FALSE );
StatChange( pSoldier, WISDOMAMT, (INT8) ( 20 - AttachmentInfo[ bAttachInfoIndex ].bAttachmentSkillCheckMod ), FALSE );
}
}
//CHRISL: If we're looking at a stack, we need to unattach the object we just attached
else if(this->RemoveAttachment(&attachmentObject, pAttachmentPosition, subObject, pSoldier))
{
pAttachment->AddObjectsToStack(attachmentObject, -1, pSoldier, NUM_INV_SLOTS, MAX_OBJECTS_PER_SLOT);
}
}
//ADB ubWeight has been removed, see comments in OBJECTTYPE
//this->ubWeight = CalculateObjectWeight( this );
//ADB ubWeight has been removed, see comments in OBJECTTYPE
//pAttachment->ubWeight = CalculateObjectWeight(pAttachment);
if ( pSoldier != NULL )
ApplyEquipmentBonuses(pSoldier);
return( TRUE );
}
// check for merges
else if (EvaluateValidMerge( pAttachment->usItem, this->usItem, &usResult, &usResult2, &ubType, &ubAPCost ))
{
//CHRISL: we don't want to try to merge IC_LBEGEAR items that are currently storing items.
if(Item[this->usItem].usItemClass == IC_LBEGEAR)
{
if(this->IsActiveLBE(subObject) == true)
return( FALSE );
}
//CHRISL: We don't want to do any merges if we're looking at a stack of items, with the exception of combines.
if ( this->ubNumberOfObjects > 1 && ubType != COMBINE_POINTS )
{
return( FALSE );
}
if ( ubType != COMBINE_POINTS )
{
if ( pSoldier )
{
if ( !EnoughPoints( pSoldier, ubAPCost, 0, TRUE ) )
{
return( FALSE );
}
//lalien: don't charge AP's for reloading a GL/RL ( wrong place!!! the AP's are deducted in DeleteItemDescriptionBox() )
//if ( IsAGLorRL == FALSE )
//{
DeductPoints( pSoldier, ubAPCost, 0 );
//}
}
}
switch( ubType )
{
case USE_ITEM:
case USE_ITEM_HARD:
// the merge will combine the two items
if ( pSoldier )
{
if ( ubType == USE_ITEM_HARD )
{
// requires a skill check, and gives experience
iCheckResult = SkillCheck( pSoldier, ATTACHING_SPECIAL_ITEM_CHECK, -30 );
if (iCheckResult < 0)
{
// could have a chance of detonation
// for now, damage both objects
DamageObj( this, (INT8) -iCheckResult );
DamageObj( pAttachment, (INT8) -iCheckResult );
pSoldier->DoMercBattleSound( BATTLE_SOUND_CURSE1 );
return( FALSE );
}
StatChange( pSoldier, MECHANAMT, 25, FALSE );
StatChange( pSoldier, WISDOMAMT, 5, FALSE );
}
//Madd: note that use_item cannot produce two different items!!! so it doesn't use usResult2
//Madd: unload guns after merge if ammo caliber or mag size don't match
if ( Item[this->usItem].usItemClass == IC_GUN && (*this)[0]->data.gun.usGunAmmoItem != NONE && (*this)[0]->data.gun.ubGunShotsLeft > 0 )
{
if ( Item[usResult].usItemClass != IC_GUN || Weapon[Item[usResult].ubClassIndex].ubCalibre != Weapon[Item[this->usItem].ubClassIndex].ubCalibre || (*this)[0]->data.gun.ubGunShotsLeft > Weapon[Item[usResult].ubClassIndex].ubMagSize )
{ // item types/calibers/magazines don't match, spit out old ammo
EjectAmmoAndPlace(pSoldier, this);
}
}
UINT16 usOldItem = this->usItem;
this->usItem = usResult;
//WarmSteel - Replaced this with one that also checks default attachments, otherwise you could not replace built-in bonuses with default inseperable attachments.
//RemoveProhibitedAttachments(pSoldier, this, usResult);
ReInitMergedItem(pSoldier, this, usOldItem);
//AutoPlaceObject( pAttachment );
//ADB ubWeight has been removed, see comments in OBJECTTYPE
//this->ubWeight = CalculateObjectWeight( this );
if (pSoldier->bTeam == gbPlayerNum)
{
pSoldier->DoMercBattleSound( BATTLE_SOUND_COOL1 );
}
ApplyEquipmentBonuses(pSoldier);
return TRUE;
}
else
return FALSE;
case COMBINE_POINTS:
// transfer points...
UINT32 combinedAmount;
UINT32 attachmentAmount;
//CHRISL: Treat differently if we're combining money items (other then MONEY)
if(Item[this->usItem].usItemClass != IC_MONEY)
{
if ( Item[ this->usItem ].usItemClass == IC_AMMO )
{
ubLimit = Magazine[ Item[ this->usItem ].ubClassIndex ].ubMagSize;
}
else
{
ubLimit = 100;
}
// count down through # of attaching items and add to status of item in position 0
for (bLoop = 0; bLoop < pAttachment->ubNumberOfObjects; )
{
//ADB need to watch for overflow here (thus UINT32), and need to cast to UINT8 before adding
combinedAmount = (UINT16)(*this)[subObject]->data.objectStatus + (UINT16)(*pAttachment)[0]->data.objectStatus;
if (combinedAmount <= ubLimit)
{
// consume this one totally and continue
(*this)[subObject]->data.objectStatus = combinedAmount;
pAttachment->RemoveObjectsFromStack(1);
}
else
{
// add part of this one and then we're done
attachmentAmount = (UINT16)(*pAttachment)[0]->data.objectStatus;
attachmentAmount -= (ubLimit - (UINT16)(*this)[subObject]->data.objectStatus);
(*pAttachment)[0]->data.objectStatus = attachmentAmount;
if ((*pAttachment)[0]->data.ubShotsLeft == 0) {
pAttachment->RemoveObjectsFromStack(1);
}
(*this)[subObject]->data.ubShotsLeft = ubLimit;
break;
}
}
}
else
{
ubLimit = MAX_MONEY_PER_SLOT;
combinedAmount = (*this)[subObject]->data.money.uiMoneyAmount + (*pAttachment)[0]->data.money.uiMoneyAmount;
if (combinedAmount <= ubLimit)
{
(*this)[subObject]->data.money.uiMoneyAmount = combinedAmount;
pAttachment->RemoveObjectsFromStack(1);
}
else
{
attachmentAmount = (*pAttachment)[0]->data.money.uiMoneyAmount;
attachmentAmount -= (ubLimit - (*this)[subObject]->data.money.uiMoneyAmount);
(*pAttachment)[0]->data.money.uiMoneyAmount = attachmentAmount;
if((*pAttachment)[0]->data.money.uiMoneyAmount == 0)
{
pAttachment->RemoveObjectsFromStack(1);
}
(*this)[subObject]->data.money.uiMoneyAmount = ubLimit;
break;
}
}
break;
case DESTRUCTION:
// the merge destroyed both items!
this->RemoveObjectsFromStack(1);
pAttachment->RemoveObjectsFromStack(1);
if ( pSoldier )
{
pSoldier->DoMercBattleSound( BATTLE_SOUND_CURSE1 );
}
break;
case ELECTRONIC_MERGE:
if ( pSoldier )
{
iCheckResult = SkillCheck( pSoldier, ATTACHING_SPECIAL_ELECTRONIC_ITEM_CHECK, -30 );
if ( iCheckResult < 0 )
{
DamageObj( this, (INT8) -iCheckResult );
DamageObj( pAttachment, (INT8) -iCheckResult );
pSoldier->DoMercBattleSound( BATTLE_SOUND_CURSE1 );
return( FALSE );
}
// grant experience!
}
// fall through
case EXPLOSIVE:
if ( ubType == EXPLOSIVE ) /// coulda fallen through
{
if (pSoldier)
{
// requires a skill check, and gives experience
iCheckResult = SkillCheck( pSoldier, ATTACHING_DETONATOR_CHECK, -30 );
if (iCheckResult < 0)
{
// could have a chance of detonation
// for now, damage both objects
DamageObj( this, (INT8) -iCheckResult );
DamageObj( pAttachment, (INT8) -iCheckResult );
pSoldier->DoMercBattleSound( BATTLE_SOUND_CURSE1 );
return( FALSE );
}
StatChange( pSoldier, EXPLODEAMT, 25, FALSE );
StatChange( pSoldier, WISDOMAMT, 5, FALSE );
}
}
// fall through
default:
// the merge will combine the two items
//Madd: usResult2 only works for standard merges->item1 + item2 = item3 + item4
//Madd: unload guns after merge if ammo caliber or mag size don't match
if ( Item[this->usItem].usItemClass == IC_GUN && (*this)[subObject]->data.gun.usGunAmmoItem != NONE && (*this)[subObject]->data.gun.ubGunShotsLeft > 0 )
{
if ( Item[usResult].usItemClass != IC_GUN || Weapon[Item[usResult].ubClassIndex].ubCalibre != Weapon[Item[this->usItem].ubClassIndex].ubCalibre || (*this)[subObject]->data.gun.ubGunShotsLeft > Weapon[Item[usResult].ubClassIndex].ubMagSize )
{ // item types/calibers/magazines don't match, spit out old ammo
EjectAmmoAndPlace(pSoldier, this);
}
}
UINT16 usOldItem = this->usItem;
this->usItem = usResult;
//WarmSteel - Replaced this with one that also checks default attachments, otherwise you could not replace built-in bonuses with default inseperable attachments.
//RemoveProhibitedAttachments(pSoldier, this, usResult);
ReInitMergedItem(pSoldier, this, usOldItem);
if ( ubType != TREAT_ARMOUR )
{
(*this)[subObject]->data.objectStatus = ((*this)[subObject]->data.objectStatus + (*pAttachment)[0]->data.objectStatus) / 2;
}
//ADB ubWeight has been removed, see comments in OBJECTTYPE
//this->ubWeight = CalculateObjectWeight( this );
if ( usResult2 != NOTHING )
{
//Madd: usResult2 is what the original attachment/source item turns into
//Madd: unload guns after merge if ammo caliber or mag size don't match
if ( Item[pAttachment->usItem].usItemClass == IC_GUN && (*pAttachment)[0]->data.gun.usGunAmmoItem != NONE && (*pAttachment)[0]->data.gun.ubGunShotsLeft > 0 )
{
if ( Item[usResult2].usItemClass != IC_GUN || Weapon[Item[usResult2].ubClassIndex].ubCalibre != Weapon[Item[pAttachment->usItem].ubClassIndex].ubCalibre || (*pAttachment)[0]->data.gun.ubGunShotsLeft > Weapon[Item[usResult2].ubClassIndex].ubMagSize )
{ // item types/calibers/magazines don't match, spit out old ammo
EjectAmmoAndPlace(pSoldier, pAttachment);
}
}
pAttachment->usItem = usResult2;
RemoveProhibitedAttachments(pSoldier, pAttachment, usResult2);
if ( ubType != TREAT_ARMOUR )
{
(*pAttachment)[0]->data.objectStatus = ((*pAttachment)[0]->data.objectStatus + (*this)[subObject]->data.objectStatus) / 2;
}
//ADB ubWeight has been removed, see comments in OBJECTTYPE
//pAttachment->ubWeight = CalculateObjectWeight( pAttachment );
}
else
pAttachment->RemoveObjectsFromStack(1);
if (pSoldier && pSoldier->bTeam == gbPlayerNum)
{
pSoldier->DoMercBattleSound( BATTLE_SOUND_COOL1 );
}
break;
}
if ( pSoldier != NULL )
ApplyEquipmentBonuses(pSoldier);
return( TRUE );
}
return( FALSE );
}
//CHRISL: Use this function to sort through Attachments.xml and Launchables.xml
UINT32 SetAttachmentSlotsFlag(OBJECTTYPE* pObj){
UINT32 uiSlotFlag = 0;
UINT32 uiLoop = 0;
UINT32 fItem;
if(pObj->exists()==false)
return 0;
while(1)
{
fItem = 0;
if (Attachment[uiLoop][1] == pObj->usItem){
fItem = Attachment[uiLoop][0];
}
if (Launchable[uiLoop][1] == pObj->usItem ){
fItem = Launchable[uiLoop][0];
}
if(fItem && ItemIsLegal(fItem, TRUE)){ // We've found a valid attachment. Set the nasAttachmentSlots flag appropriately
uiSlotFlag |= Item[fItem].nasAttachmentClass;
}
uiLoop++;
if (Attachment[uiLoop][0] == 0 && Launchable[uiLoop][0] == 0){
// No more attachments to search
break;
}
}
return uiSlotFlag;
}
//WarmSteel - This function returns the available item slot indexes in a vector.
std::vector<UINT16> GetItemSlots(OBJECTTYPE* pObj, UINT8 subObject, BOOLEAN fAttachment){
std::vector<UINT16> tempItemSlots;
std::vector<UINT16> tempAttachmentSlots;
std::vector<UINT16> tempSlots;
UINT8 numSlots = 0;
UINT16 magSize = 0;
UINT32 fItemSlots = 0;
UINT128 fItemLayout = 0;
if(UsingNewAttachmentSystem()==false || !pObj->exists())
return tempItemSlots;
//CHRISL: We no longer need the ItemSlotAssign.xml file but we do still need to figure out which slots an item can have
//Start by searching Attachments.xml and Launchables.xml for valid attachments for the primary object
fItemSlots = SetAttachmentSlotsFlag(pObj);
fItemLayout = Item[pObj->usItem].nasLayoutClass;
if(Item[pObj->usItem].grenadelauncher || Item[pObj->usItem].rocketlauncher)
magSize = GetMagSize(pObj);
//Next, let's figure out which slots the item gives us access to
if(fItemSlots){ //We don't need to do anything if the item gets no slots
for(UINT8 sClass = 0; sClass < 32; sClass++){ //go through each attachment class and find the slots the item should have
UINT32 uiClass = (UINT32)pow((double)2, (int)sClass);
UINT32 slotSize = tempItemSlots.size();
if(fItemSlots & uiClass){ //don't bother with this slot if it's not a valid class
for(UINT32 sCount = 1; sCount < MAXITEMS+1; sCount++){
if(AttachmentSlots[sCount].uiSlotIndex == 0)
break;
if(AttachmentSlots[sCount].nasAttachmentClass & uiClass && AttachmentSlots[sCount].nasLayoutClass & fItemLayout){ //found a slot
if(magSize > 0 && AttachmentSlots[sCount].fMultiShot)
magSize--;
else if(AttachmentSlots[sCount].fMultiShot)
continue;
tempItemSlots.push_back(AttachmentSlots[sCount].uiSlotIndex);
}
}
if(slotSize == tempItemSlots.size()){ //we didn't find a layout specific slot so try to find a default layout slot
for(UINT32 sCount = 1; sCount < MAXITEMS+1; sCount++){
if(AttachmentSlots[sCount].uiSlotIndex == 0)
break;
if(AttachmentSlots[sCount].nasAttachmentClass & uiClass && AttachmentSlots[sCount].nasLayoutClass == 1){ //found a default slot
tempItemSlots.push_back(AttachmentSlots[sCount].uiSlotIndex);
}
}
}
}
}
}
//Now that we've setup tempItemSlots for the main item, let's look at the individual attachments
for(attachmentList::iterator iter = (*pObj)[subObject]->attachments.begin(); iter != (*pObj)[subObject]->attachments.end(); ++iter){
if(iter->exists() && (*iter)[0]->attachments.size() > 0){
OBJECTTYPE* pAttachment = &(*iter);
tempSlots = GetItemSlots(pAttachment,0,TRUE);
for(UINT8 x = 0; x < tempSlots.size(); x++)
tempAttachmentSlots.push_back(tempSlots[x]);
}
}
//Now that we have tempAttachmentSlots, put it all together, assuming we're woking on the main item
if(!fAttachment){
if(tempAttachmentSlots.size() > 0){ //Add attachmentSlots to itemSlots
for(UINT8 attachSlot = 0; attachSlot < tempAttachmentSlots.size(); attachSlot++){
tempItemSlots.push_back(tempAttachmentSlots[attachSlot]);
}
}
tempSlots = tempItemSlots;
for(std::vector<UINT16>::iterator iter1 = tempSlots.begin(); iter1 != tempSlots.end(); ++iter1){
BOOLEAN fSlotDuplicated = FALSE;
for(std::vector<UINT16>::iterator iter = tempItemSlots.begin(); iter != tempItemSlots.end();){
UINT16 i1 = *iter1;
UINT16 i = *iter;
if(i1 == i && !fSlotDuplicated){
fSlotDuplicated = TRUE;
++iter;
continue;
}
else if(i1 == i && fSlotDuplicated){
iter = tempItemSlots.erase(iter);
continue;
}
else
++iter;
}
}
//If we still have no attachment slots, look through Merges.xml to see if we have merges and use the 4 default slots if we do
//Should we throw on default slots regardless of whether there is an entry in Merges? Ammo doesn't have Merges entries but we still need slots for them.
if(tempItemSlots.size() == 0){
// INT32 iLoop = 0;
// while( 1 ){
// if (Merge[iLoop][1] == pObj->usItem)
{
tempItemSlots.push_back(1);
tempItemSlots.push_back(2);
tempItemSlots.push_back(3);
tempItemSlots.push_back(4);
// break;
}
// iLoop++;
// if (Merge[iLoop][1] == 0)
// {
// break;
// }
// }
}
}
return tempItemSlots;
}
void InitItemAttachments(OBJECTTYPE* pObj){
if(UsingNewAttachmentSystem()==false)
return;
//pObj->usAttachmentSlotIndexVector = GetItemSlots(pObj);
(*pObj)[0]->attachments.resize((GetItemSlots(pObj).size()));
}
/*
//WarmSteel - Changed this function for NAS, because when the slots change many items will become invalid IN THAT SLOT, but not on the weapon.
To fix this we re-attach all invalid attachments. It also checks the slots that are on the gun.
IMPORTANT: If you use AttachObject/RemoveAttachment with fRemoveProhibited TRUE in this function, I will hunt you down and smite you.
*/
void RemoveProhibitedAttachments(SOLDIERTYPE* pSoldier, OBJECTTYPE* pObj, UINT16 usItem, BOOLEAN fOnlyRemoveWhenSlotsChange)
{
if(!pObj->exists())
return;
if(UsingNewAttachmentSystem()==true){
UINT32 curSlot = 0;
BOOLEAN fCanAttach = FALSE;
BOOLEAN fRemoveProhibitedAttachments = FALSE;
BOOLEAN fDoneRemovingProhibited = FALSE;
attachmentList tempAttachList;
std::vector<UINT16> tempItemSlots;
std::vector<UINT16> usAttachmentSlotIndexVector = GetItemSlots(pObj);
//Get the item slots this item SHOULD have (but may not have right now), also counting any slots that were added or removed.
//tempItemSlots = GetItemSlots(pObj);
//Check if the slots have changed.
if(fOnlyRemoveWhenSlotsChange){
if(usAttachmentSlotIndexVector.size() != (*pObj)[0]->attachments.size()){
fRemoveProhibitedAttachments = TRUE;
} else {
for(attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end() && !fRemoveProhibitedAttachments; ++iter, ++curSlot){
if(iter->exists()){
UINT16 slotIndex = usAttachmentSlotIndexVector[curSlot];
UINT16 sItem = iter->usItem;
if(!(AttachmentSlots[slotIndex].nasAttachmentClass & Item[sItem].nasAttachmentClass)){
fRemoveProhibitedAttachments = TRUE;
}
}
}
}
}
if(fRemoveProhibitedAttachments){
UINT16 usInfiniteLoopCount = 0;
//CHRISL: There is the chance that we could have attachments in slots that are no longer valid, but if we arbitrarily resize the attachmentList
// we could actually lose attachments. So let's just remove all attachments and replace them in correct locations
for(attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists()){
tempAttachList.push_back((*iter));
iter = (*pObj)[0]->RemoveAttachmentAtIter(iter);
}
}
//pObj->usAttachmentSlotIndexVector = tempItemSlots;
//Keep checking till slots stop changing.
while(!fDoneRemovingProhibited){
//Surely 500 tries is enough to fix ANY item...
AssertMsg(usInfiniteLoopCount < 500, "There was an inifinite loop while removing prohibited attachments");
//Resize the object to the correct size
(*pObj)[0]->attachments.resize(usAttachmentSlotIndexVector.size());
//Start by trying to re-attach inseperable items. They take precedence over items that can normally be removed
for (attachmentList::iterator iter = tempAttachList.begin(); iter != tempAttachList.end();) {
if(Item[iter->usItem].inseparable && ValidItemAttachmentSlot(pObj, iter->usItem, TRUE, FALSE, 0, -1, 0, NULL, usAttachmentSlotIndexVector)){
//This seems to be rather valid. Can't be 100% sure though.
if(pObj->AttachObject(NULL, &(*iter), FALSE, 0, -1, FALSE, usAttachmentSlotIndexVector)){
//Ok now we can be sure, lets remove this object so we don't try to drop it later.
iter = tempAttachList.erase(iter);
} else {
++iter;
}
} else {
++iter;
}
}
//Try to attach all the other attachments that didn't fit their current slot.
for (attachmentList::iterator iter = tempAttachList.begin(); iter != tempAttachList.end();) {
if(ValidItemAttachmentSlot(pObj, iter->usItem, TRUE, FALSE, 0, -1, 0, NULL, usAttachmentSlotIndexVector)){
//This seems to be rather valid. Can't be 100% sure though.
if(pObj->AttachObject(NULL, &(*iter), FALSE, 0, -1, FALSE, usAttachmentSlotIndexVector)){
//Ok now we can be sure, lets remove this object so we don't try to drop it later.
iter = tempAttachList.erase(iter);
} else {
++iter;
}
} else {
++iter;
}
}
tempItemSlots = GetItemSlots(pObj);
//assume all attachments are replaced and we're good to break the look
fDoneRemovingProhibited = TRUE;
//Check if the slots have changed after possibly removing attachments.
if(tempItemSlots.size() != usAttachmentSlotIndexVector.size()){
//Changed, we need to correct again.
fDoneRemovingProhibited = FALSE;
} else if(!tempItemSlots.empty()){
for (UINT16 cnt = 0; cnt < tempItemSlots.size(); ++cnt) {
//If these slots don't match, something has changed, keep checking.
if(tempItemSlots[cnt] != usAttachmentSlotIndexVector[cnt]){
fDoneRemovingProhibited = FALSE;
break;
}
}
}
if(usInfiniteLoopCount > 10){ //run through the loop 10 times before we drop items.
//Anything that's still in our tempAttachList couldn't be attached, and should be dropped.
for (attachmentList::iterator iter = tempAttachList.begin(); iter != tempAttachList.end();) {
if (iter->exists()) {
if ( pSoldier && AutoPlaceObject( pSoldier, &(*iter), FALSE ) )
{
iter = tempAttachList.erase(iter);
} else { // put it on the ground
INT8 pathing = (pSoldier?pSoldier->pathing.bLevel:0);
INT32 sGridNo = (pSoldier?pSoldier->sGridNo:0);
AutoPlaceObjectToWorld(pSoldier, &(*iter), TRUE);
iter = tempAttachList.erase(iter);
/*if(guiCurrentItemDescriptionScreen == MAP_SCREEN && fShowMapInventoryPool){
AutoPlaceObjectInInventoryStash(&(*iter), sGridNo);
//AddItemToPool( sGridNo, &(*iter), 1, pathing, WORLD_ITEM_REACHABLE, 0 );
iter = tempAttachList.erase(iter);
} else {
AddItemToPool( sGridNo, &(*iter), 1, pathing, WORLD_ITEM_REACHABLE, 0 );
iter = tempAttachList.erase(iter);
}*/
}
} else {
++iter;
}
}
}
if(!tempAttachList.empty()){
fDoneRemovingProhibited = FALSE;
}
usAttachmentSlotIndexVector = GetItemSlots(pObj);
usInfiniteLoopCount++;
}
}
} else {
UINT16 x = 0;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end();) {
if(!iter->exists()){
//WarmSteel - erase null objects, we don't need them without the NAS.
iter = (*pObj)[0]->attachments.erase(iter);
} else {
if ( (!ValidAttachment(iter->usItem, pObj) && !ValidLaunchable(iter->usItem, usItem) && !ValidLaunchable(iter->usItem, GetAttachedGrenadeLauncher(pObj)) ) || x >= OLD_MAX_ATTACHMENTS_101)
{
if ( !Item[iter->usItem].inseparable )
{
if (pSoldier) {
if ( !AutoPlaceObject( pSoldier, &(*iter), FALSE ) )
{ // put it on the ground
AddItemToPool( pSoldier->sGridNo, &(*iter), 1, pSoldier->pathing.bLevel, 0 , -1 );
}
}
}
pObj->RemoveAttachment(&(*iter),0 ,0 , pSoldier, TRUE, FALSE);
iter = (*pObj)[0]->attachments.begin();
x = 0;
} else {
++x;
++iter;
}
}
}
}
return;
}
//WarmSteel - Needed for merges, because the new items don't get their new default attachments.
//This does the same as RemoveProhibitedAttachments but is a bit more thorough at it.
//This is at the risk that items move around if more than one slot is valid, but since this is used for "new" guns after merges, that's acceptable.
void ReInitMergedItem(SOLDIERTYPE* pSoldier, OBJECTTYPE* pObj, UINT16 usOldItem){
attachmentList tempAttachList;
attachmentList tempSlotChangingAttachList;
BOOLEAN fFoundDefaultAttachment = FALSE;
UINT8 slotCount;
std::vector<UINT16> usAttachmentSlotIndexVector = GetItemSlots(pObj);
if( !(*pObj)[0]->attachments.empty() ){
//Have to take all attachments off, because of possible incompatibilities with the default attachments (can't NOT attach a default attachment because some stupid item already attached is incompatible with it).
//Delete all default inseperable attachments from the old gun.
//This is safe UNLESS the inseparable default attachments is not the only attachment of the same kind on the gun.
//I can't think of any reason why this would happen, and if it does the worst that can happen is your attachment disappearing.
for(slotCount = 0; slotCount < (*pObj)[0]->attachments.size(); slotCount++){
UINT16 usAttach = (*pObj)[0]->GetAttachmentAtIndex(slotCount)->usItem;
if(Item[usAttach].inseparable){
for(UINT16 cnt = 0; cnt < MAX_DEFAULT_ATTACHMENTS && Item[usOldItem].defaultattachments[cnt] != 0; cnt++){
if(Item[usOldItem].defaultattachments[cnt] == usAttach){
(*pObj)[0]->RemoveAttachmentAtIndex(slotCount);
break;
}
}
}
}
slotCount = 0;
//Put all other attachments into a temporary storage, so we can try to re-attach later.
for(attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); iter++, slotCount++) {
if(iter->exists()){
UINT16 cnt = 0;
tempAttachList.push_back((*iter));
}
}
}
//clear the attachment list, we've saved the attachments somewhere safe now.
(*pObj)[0]->attachments.clear();
//Make sure the attachment slot data is correct.
//std::vector<UINT16> tempItemSlots = GetItemSlots(pObj);
(*pObj)[0]->attachments.resize(usAttachmentSlotIndexVector.size());
//pObj->usAttachmentSlotIndexVector = tempItemSlots;
//Now add all default attachments, but add them with the same status as the gun. We don't want to make repairing guns easy :)
for(UINT16 cnt = 0; cnt < MAX_DEFAULT_ATTACHMENTS && Item[pObj->usItem].defaultattachments[cnt] != 0; cnt++){
//Only add inseparable default attachments, because they are likely "part" of the gun.
if(Item[Item[pObj->usItem].defaultattachments[cnt]].inseparable){
static OBJECTTYPE defaultAttachment;
CreateItem(Item [ pObj->usItem ].defaultattachments[cnt],(*pObj)[0]->data.objectStatus,&defaultAttachment);
AssertMsg(pObj->AttachObject(NULL,&defaultAttachment, FALSE, 0, -1, FALSE), "A default attachment could not be attached after merging, this should not be possible.");
}
}
//First re-attach any slot-changing attachments.
for (attachmentList::iterator iter = tempSlotChangingAttachList.begin(); iter != tempSlotChangingAttachList.end();) {
if( ValidItemAttachmentSlot(pObj, iter->usItem, TRUE, FALSE )){
//This seems to be rather valid. Can't be 100% sure though.
if(pObj->AttachObject(NULL, &(*iter), FALSE)){
//Ok now we can be sure, lets remove this object so we don't try to drop it later.
iter = tempSlotChangingAttachList.erase(iter);
} else {
++iter;
}
} else {
++iter;
}
}
//Time to re-attach the other attachments, if we can. I am the king of copy pasta.
for (attachmentList::iterator iter = tempAttachList.begin(); iter != tempAttachList.end();) {
if( ValidItemAttachmentSlot(pObj, iter->usItem, TRUE, FALSE)){
//This seems to be rather valid. Can't be 100% sure though.
if(pObj->AttachObject(NULL, &(*iter), FALSE)){
//Ok now we can be sure, lets remove this object so we don't try to drop it later.
iter = tempAttachList.erase(iter);
} else {
++iter;
}
} else {
++iter;
}
}
//drop all items we couldn't re-attach.
for (attachmentList::iterator iter = tempSlotChangingAttachList.begin(); iter != tempSlotChangingAttachList.end(); ++iter) {
if ( !Item[iter->usItem].inseparable )
{//WarmSteel - Couldn't re-attach this item, try to drop it.
if (pSoldier) {
if ( !AutoPlaceObject( pSoldier, &(*iter), FALSE ) )
{ // put it on the ground
AddItemToPool( pSoldier->sGridNo, &(*iter), 1, pSoldier->pathing.bLevel, 0 , -1 );
}
}
}
}
//and the rest too
for (attachmentList::iterator iter = tempAttachList.begin(); iter != tempAttachList.end(); ++iter) {
if ( !Item[iter->usItem].inseparable )
{//WarmSteel - Couldn't re-attach this item, try to drop it.
if (pSoldier) {
if ( !AutoPlaceObject( pSoldier, &(*iter), FALSE ) )
{ // put it on the ground
AddItemToPool( pSoldier->sGridNo, &(*iter), 1, pSoldier->pathing.bLevel, 0 , -1 );
}
}
}
}
}
void EjectAmmoAndPlace(SOLDIERTYPE* pSoldier, OBJECTTYPE* pObj, UINT8 subObject)
{
CreateAmmo((*pObj)[subObject]->data.gun.usGunAmmoItem, &gTempObject, (*pObj)[subObject]->data.gun.ubGunShotsLeft);
(*pObj)[subObject]->data.gun.ubGunShotsLeft = 0;
(*pObj)[subObject]->data.gun.usGunAmmoItem = NONE;
// HEADROCK HAM 3.5: Clear ammo type
(*pObj)[subObject]->data.gun.ubGunAmmoType = NONE;
if ( pSoldier )
{
AutoPlaceObjectAnywhere( pSoldier, &gTempObject, FALSE );
// if ( !AutoPlaceObject( pSoldier, &gTempObject, FALSE ) )
// { // put it on the ground
// AddItemToPool( pSoldier->sGridNo, &gTempObject, 1, pSoldier->pathing.bLevel, 0 , -1 );
// }
}
return;
}
/* CHRISL: This function is edited to handle the new inventory system when we have an item in our cursor.
Not only do we have to hatch out pockets that the item won't fit in, we also have to hatch out pockets that
our current LBE gear haven't activated. We'll also need to display the number of items of the type currently
held in the cursor that each active pocket can hold.*/
extern BOOLEAN CompatibleAmmoForGun( OBJECTTYPE *pTryObject, OBJECTTYPE *pTestObject );
BOOLEAN CanItemFitInVehicle( SOLDIERTYPE *pSoldier, OBJECTTYPE *pObj, INT8 bPos, BOOLEAN fDoingPlacement )
{
if((UsingNewInventorySystem() == false) || !(pSoldier->flags.uiStatusFlags & SOLDIER_VEHICLE))
return(FALSE);
if(!vehicleInv[bPos])
return(FALSE);
UINT8 ubSlotLimit;
ubSlotLimit = ItemSlotLimit( pObj, bPos, pSoldier );
if ( ubSlotLimit == 0 )
return ( CompatibleAmmoForGun(pObj, &pSoldier->inv[bPos]) );
return( TRUE );
}
BOOLEAN CanItemFitInPosition( SOLDIERTYPE *pSoldier, OBJECTTYPE *pObj, INT8 bPos, BOOLEAN fDoingPlacement )
{
UINT8 ubSlotLimit, lbePocket=1;
INT8 bNewPos=ITEM_NOT_FOUND;
UINT32 pRestrict=0;
// CHRISL: Only check valid pockets
if((UsingNewInventorySystem() == false) && !oldInv[bPos])
return(FALSE);
if((pSoldier->flags.uiStatusFlags & SOLDIER_VEHICLE) && UsingNewInventorySystem() == true)
return(CanItemFitInVehicle(pSoldier, pObj, bPos, fDoingPlacement));
ubSlotLimit = ItemSlotLimit( pObj, bPos, pSoldier );
switch( bPos )
{
case SECONDHANDPOS:
if (Item[pSoldier->inv[HANDPOS].usItem].twohanded )
{
return( FALSE );
}
break;
case HANDPOS:
if (Item[ pObj->usItem ].twohanded )
{
if (pSoldier->inv[HANDPOS].exists() == true && pSoldier->inv[SECONDHANDPOS].exists() == true)
{
// two items in hands; try moving the second one so we can swap
if (FitsInSmallPocket(&pSoldier->inv[SECONDHANDPOS]) == true)
{
bNewPos = FindEmptySlotWithin( pSoldier, BIGPOCKSTART, NUM_INV_SLOTS );
}
else
{
bNewPos = FindEmptySlotWithin( pSoldier, BIGPOCKSTART, MEDPOCKFINAL );
}
if (bNewPos == NO_SLOT)
{
// nowhere to put second item
return( FALSE );
}
if ( fDoingPlacement )
{
// otherwise move it, forget about bNewPos!
PlaceInAnyPocket(pSoldier, &pSoldier->inv[SECONDHANDPOS], FALSE);
}
}
}
break;
case VESTPOS:
case HELMETPOS:
case LEGPOS:
if (Item[pObj->usItem].usItemClass != IC_ARMOUR)
{
return( FALSE );
}
switch (bPos)
{
case VESTPOS:
if (Armour[Item[pObj->usItem].ubClassIndex].ubArmourClass != ARMOURCLASS_VEST)
{
return( FALSE );
}
break;
case HELMETPOS:
if (Armour[Item[pObj->usItem].ubClassIndex].ubArmourClass != ARMOURCLASS_HELMET)
{
return( FALSE );
}
break;
case LEGPOS:
if (Armour[Item[pObj->usItem].ubClassIndex].ubArmourClass != ARMOURCLASS_LEGGINGS)
{
return( FALSE );
}
break;
default:
break;
}
break;
case HEAD1POS:
case HEAD2POS:
if (Item[pObj->usItem].usItemClass != IC_FACE)
{
return( FALSE );
}
break;
case VESTPOCKPOS:
if (Item[pObj->usItem].usItemClass != IC_LBEGEAR || LoadBearingEquipment[Item[pObj->usItem].ubClassIndex].lbeClass != VEST_PACK)
{
return( FALSE );
}
break;
case LTHIGHPOCKPOS:
case RTHIGHPOCKPOS:
if (Item[pObj->usItem].usItemClass != IC_LBEGEAR || LoadBearingEquipment[Item[pObj->usItem].ubClassIndex].lbeClass != THIGH_PACK)
{
return( FALSE );
}
break;
case CPACKPOCKPOS:
if (Item[pObj->usItem].usItemClass != IC_LBEGEAR || LoadBearingEquipment[Item[pObj->usItem].ubClassIndex].lbeClass != COMBAT_PACK)
{
return( FALSE );
}
if(pSoldier->inv[BPACKPOCKPOS].exists() == true)
{
//DBrot: changed to bitwise comparison
if(((LoadBearingEquipment[Item[pSoldier->inv[BPACKPOCKPOS].usItem].ubClassIndex].lbeCombo & LoadBearingEquipment[Item[pObj->usItem].ubClassIndex].lbeCombo) == 0) ||
LoadBearingEquipment[Item[pSoldier->inv[BPACKPOCKPOS].usItem].ubClassIndex].lbeCombo == 0)
{
return( FALSE );
}
}
break;
case BPACKPOCKPOS:
if (Item[pObj->usItem].usItemClass != IC_LBEGEAR || LoadBearingEquipment[Item[pObj->usItem].ubClassIndex].lbeClass != BACKPACK)
{
return( FALSE );
}
// Removed backpack/gunsling restrictions
//if(pSoldier->inv[GUNSLINGPOCKPOS].exists() == true)
// return( FALSE );
if(pSoldier->inv[CPACKPOCKPOS].exists() == true)
{
//DBrot: changed to bitwise comparison
if(((LoadBearingEquipment[Item[pSoldier->inv[CPACKPOCKPOS].usItem].ubClassIndex].lbeCombo & LoadBearingEquipment[Item[pObj->usItem].ubClassIndex].lbeCombo) ==0)||
LoadBearingEquipment[Item[pSoldier->inv[CPACKPOCKPOS].usItem].ubClassIndex].lbeCombo == 0)
{
return( FALSE );
}
}
break;
case GUNSLINGPOCKPOS: // Gun Sling
//if (Item[pObj->usItem].usItemClass != IC_GUN && Item[pObj->usItem].usItemClass != IC_BLADE && Item[pObj->usItem].usItemClass != IC_LAUNCHER)
if(pObj->usItem == MONEY)
return( FALSE );
if(Item[pObj->usItem].usItemClass == IC_AMMO || Item[pObj->usItem].usItemClass == IC_GRENADE)
return(CompatibleAmmoForGun(pObj, &pSoldier->inv[GUNSLINGPOCKPOS]) || ValidAttachment(pObj->usItem, &(pSoldier->inv[GUNSLINGPOCKPOS]) ) || ValidLaunchable(pObj->usItem, pSoldier->inv[GUNSLINGPOCKPOS].usItem));
//recalc slot limit to exclude ItemSize attachment modifiers
ubSlotLimit = ItemSlotLimit( pObj, bPos, pSoldier, FALSE );
// Removed backpack/gunsling restrictions
//if(pSoldier->inv[BPACKPOCKPOS].exists() == true)
// return(CompatibleAmmoForGun(pObj, &pSoldier->inv[GUNSLINGPOCKPOS]));
break;
case KNIFEPOCKPOS: // Knife sheath
if(pObj->usItem == MONEY)
return( FALSE );
if (Item[pObj->usItem].usItemClass != IC_BLADE && Item[pObj->usItem].usItemClass != IC_THROWING_KNIFE )
return(CompatibleAmmoForGun(pObj, &pSoldier->inv[KNIFEPOCKPOS]) || ValidAttachment(pObj->usItem, &(pSoldier->inv[KNIFEPOCKPOS]) ) || ValidLaunchable(pObj->usItem, pSoldier->inv[KNIFEPOCKPOS].usItem));
break;
// IC Pockets
case BIGPOCK1POS:
case BIGPOCK2POS:
case BIGPOCK3POS:
case BIGPOCK4POS:
case BIGPOCK5POS:
case BIGPOCK6POS:
case BIGPOCK7POS:
case MEDPOCK1POS:
case MEDPOCK2POS:
case MEDPOCK3POS:
case MEDPOCK4POS:
case SMALLPOCK2POS:
case SMALLPOCK3POS:
case SMALLPOCK4POS:
case SMALLPOCK5POS:
case SMALLPOCK6POS:
case SMALLPOCK7POS:
case SMALLPOCK8POS:
case SMALLPOCK9POS:
case SMALLPOCK10POS:
case SMALLPOCK11POS:
case SMALLPOCK12POS:
case SMALLPOCK13POS:
case SMALLPOCK14POS:
case SMALLPOCK15POS:
case SMALLPOCK16POS:
case SMALLPOCK17POS:
case SMALLPOCK18POS:
case SMALLPOCK19POS:
case SMALLPOCK20POS:
case SMALLPOCK21POS:
case SMALLPOCK22POS:
case SMALLPOCK23POS:
case SMALLPOCK24POS:
case SMALLPOCK25POS:
case SMALLPOCK26POS:
case SMALLPOCK27POS:
case SMALLPOCK28POS:
case SMALLPOCK29POS:
case SMALLPOCK30POS:
if((UsingNewInventorySystem() == true))
{
if(icLBE[bPos] == BPACKPOCKPOS && (!(pSoldier->flags.ZipperFlag) || (pSoldier->flags.ZipperFlag && gAnimControl[pSoldier->usAnimState].ubEndHeight == ANIM_STAND)) && (gTacticalStatus.uiFlags & INCOMBAT))
return( FALSE );
lbePocket = (pSoldier->inv[icLBE[bPos]].exists() == false) ? LoadBearingEquipment[Item[icDefault[bPos]].ubClassIndex].lbePocketIndex[icPocket[bPos]] : LoadBearingEquipment[Item[pSoldier->inv[icLBE[bPos]].usItem].ubClassIndex].lbePocketIndex[icPocket[bPos]];
pRestrict = LBEPocketType[lbePocket].pRestriction;
if(pRestrict != 0)
if(!(pRestrict & Item[pObj->usItem].usItemClass))
lbePocket = 0;
}
break;
default:
break;
}
if((UsingNewInventorySystem() == false))
{
if (ubSlotLimit == 0 && bPos >= SMALLPOCKSTART )
{
// doesn't fit!
return( FALSE );
}
}
else
{
// CHRISL: lbePocket==0 means pocket disabled. ubSlotLimit==0 means pocket can't hold item
if ( lbePocket == 0 || ubSlotLimit == 0 )
return ( CompatibleAmmoForGun(pObj, &pSoldier->inv[bPos]) || ValidAttachment(pObj->usItem, &(pSoldier->inv[bPos]) ) || ValidLaunchable(pObj->usItem, pSoldier->inv[bPos].usItem) );
// CHRISL: Adjust parameters to include the new inventory system
if (ubSlotLimit == 0 && bPos >= BIGPOCKFINAL )
return( CompatibleAmmoForGun(pObj, &pSoldier->inv[bPos]) || ValidAttachment(pObj->usItem, &(pSoldier->inv[bPos]) ) || ValidLaunchable(pObj->usItem, pSoldier->inv[bPos].usItem) );
}
return( TRUE );
}
//CHRISL: Wrote this function to try and clean up possible problems relating to the 16bit change for ammo capacity
void CleanUpItemStats( OBJECTTYPE * pObj )
{
UINT16 magSize;
if(Item[pObj->usItem].usItemClass == IC_GUN)
{
magSize = GetMagSize(pObj);
if((*pObj)[0]->data.gun.ubGunShotsLeft > magSize)
{
(*pObj)[0]->data.gun.ubGunShotsLeft = magSize;
}
return;
}
if(Item[pObj->usItem].usItemClass == IC_AMMO)
{
magSize = Magazine[Item[pObj->usItem].ubClassIndex].ubMagSize;
if((*pObj)[0]->data.ubShotsLeft > magSize)
{
(*pObj)[0]->data.ubShotsLeft = magSize;
}
return;
}
}
BOOLEAN FreeUpSlotIfPossibleThenPlaceObject( SOLDIERTYPE * pSoldier, INT8 bPos, OBJECTTYPE * pObj )
{
//this gets called if something doesn't fit in bPos, which can happen if something is there
//or if it simply doesn't fit, if it doesn't fit return false to prevent recursion
// try autoplacing item in bSlot elsewhere, excluding the slot it came from, then do a placement
if ( pSoldier->inv[bPos].exists() == true && AutoPlaceObject( pSoldier, &(pSoldier->inv[bPos]), FALSE , bPos) )
{
//the old object has been placed somewhere, it's safe to place this one
return( PlaceObject( pSoldier, bPos, pObj ) );
}
return( FALSE );
}
// CHRISL: Use to find best pocket to store item in. Could probably be merged with FitsInSmallPocket
INT32 PickPocket(SOLDIERTYPE *pSoldier, UINT8 ppStart, UINT8 ppStop, UINT16 usItem, UINT8 iNumber, UINT8 * cap, int bExcludeSlot)
{
UINT16 pIndex=0;
INT32 pocket=0;
UINT8 capacity=254;
for(UINT32 uiPos=ppStart; uiPos<ppStop; uiPos++){
if(pSoldier->inv[icLBE[uiPos]].exists() == false){
pIndex=LoadBearingEquipment[Item[icDefault[uiPos]].ubClassIndex].lbePocketIndex[icPocket[uiPos]];
}
else {
pIndex=LoadBearingEquipment[Item[pSoldier->inv[icLBE[uiPos]].usItem].ubClassIndex].lbePocketIndex[icPocket[uiPos]];
}
// Here's were we get complicated. We should look for the smallest pocket all items can fit in
if(LBEPocketType[pIndex].ItemCapacityPerSize[Item[usItem].ItemSize] >= iNumber &&
LBEPocketType[pIndex].ItemCapacityPerSize[Item[usItem].ItemSize] < capacity &&
pSoldier->inv[uiPos].exists() == false && uiPos != bExcludeSlot) {
if((LBEPocketType[pIndex].pRestriction != 0 && (LBEPocketType[pIndex].pRestriction & Item[usItem].usItemClass)) ||
LBEPocketType[pIndex].pRestriction == 0) {
capacity = LBEPocketType[pIndex].ItemCapacityPerSize[Item[usItem].ItemSize];
pocket = uiPos;
}
}
}
if(pocket!=0){
*cap=capacity;
return pocket;
}
else{
*cap=254;
return -1;
}
}
BOOLEAN PlaceObject( SOLDIERTYPE * pSoldier, INT8 bPos, OBJECTTYPE * pObj, BOOLEAN fNewItem )
{
if (PlaceObject(pSoldier, bPos, pObj) == TRUE) {
SetNewItem(pSoldier, bPos, fNewItem);
return TRUE;
}
return FALSE;
}
BOOLEAN PlaceObject( SOLDIERTYPE * pSoldier, INT8 bPos, OBJECTTYPE * pObj )
{
// returns object to have in hand after placement... same as original in the
// case of error
UINT8 ubSlotLimit;
OBJECTTYPE * pInSlot;
BOOLEAN fObjectWasRobotRemote = FALSE;
if ( Item[pObj->usItem].robotremotecontrol )
{
fObjectWasRobotRemote = TRUE;
}
//CHRISL: Failsafe to try and clean up ammo capacity problems
CleanUpItemStats(pObj);
if ( !CanItemFitInPosition( pSoldier, pObj, bPos, TRUE ) )
{
return( FALSE );
}
// If the position is either head slot, then the item must be IC_FACE (checked in
// CanItemFitInPosition).
if ( bPos == HEAD1POS )
{
if ( !CompatibleFaceItem( pObj->usItem, pSoldier->inv[ HEAD2POS ].usItem ) )
{
CHAR16 zTemp[ 150 ];
swprintf( zTemp, Message[ STR_CANT_USE_TWO_ITEMS ], ItemNames[ pObj->usItem ], ItemNames[ pSoldier->inv[ HEAD2POS ].usItem ] );
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_UI_FEEDBACK, zTemp );
return( FALSE );
}
}
else if ( bPos == HEAD2POS )
{
if ( !CompatibleFaceItem( pObj->usItem, pSoldier->inv[ HEAD1POS ].usItem ) )
{
CHAR16 zTemp[ 150 ];
swprintf( zTemp, Message[ STR_CANT_USE_TWO_ITEMS ], ItemNames[ pObj->usItem ], ItemNames[ pSoldier->inv[ HEAD1POS ].usItem ] );
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_UI_FEEDBACK, zTemp );
return( FALSE );
}
}
if ( Item[ pObj->usItem ].usItemClass == IC_KEY && pSoldier->flags.uiStatusFlags & SOLDIER_PC )
{
if ( KeyTable[ (*pObj)[0]->data.key.ubKeyID ].usDateFound == 0 )
{
KeyTable[ (*pObj)[0]->data.key.ubKeyID ].usDateFound = (UINT16) GetWorldDay();
KeyTable[ (*pObj)[0]->data.key.ubKeyID ].usSectorFound = SECTOR( pSoldier->sSectorX, pSoldier->sSectorY );
}
}
// Lesh: bugfix - replacing weapon in auto with another weapon w/o auto-mode
if (bPos == HANDPOS && Item[ pObj->usItem ].usItemClass == IC_GUN)
{
//Madd: added code for nosemiauto tag
if (!Weapon[ Item[pObj->usItem].ubClassIndex ].NoSemiAuto)
{
pSoldier->bWeaponMode = WM_NORMAL;
pSoldier->bDoBurst = FALSE;
pSoldier->bDoAutofire = FALSE;
}
else
{
pSoldier->bWeaponMode = WM_AUTOFIRE;
pSoldier->bDoBurst = TRUE;
pSoldier->bDoAutofire = TRUE;
}
}
// Lesh: end
#ifdef JA2UB
//handle the placing up of a new ja25 gun
HandleNewGunComment( pSoldier, pObj->usItem, FALSE );
#endif
pInSlot = &(pSoldier->inv[bPos]);
//we are placing an object, how we handle this depends on what is in the slot already
if (pInSlot->exists() == false)
{
//if the object in the slot does not exist it is easy
pObj->MoveThisObjectTo(*pInSlot, ALL_OBJECTS, pSoldier, bPos);
if (pObj->exists() == false)
{
// dropped everything
if (bPos == HANDPOS && Item[pInSlot->usItem].twohanded )
{
// We just performed a successful drop of a two-handed object into the
// main hand
if (pSoldier->inv[SECONDHANDPOS].exists() == true)
{
// swap what WAS in the second hand into the cursor
pSoldier->inv[SECONDHANDPOS].MoveThisObjectTo(*pObj);
}
}
}
}
else
{
// replacement/reloading/merging/stacking
//try to reload first
switch (Item[pInSlot->usItem].usItemClass)
{
case IC_GUN:
if (Item[pObj->usItem].usItemClass == IC_AMMO)
{
if (Weapon[pInSlot->usItem].ubCalibre == Magazine[Item[pObj->usItem].ubClassIndex].ubCalibre)
{
//CHRISL: Work differently with ammo crates but only when not in combat
if(Item[pObj->usItem].ammocrate == TRUE)
{
if(!(gTacticalStatus.uiFlags & INCOMBAT))
{
UINT16 magSize, ubShotsLeft;
OBJECTTYPE tempClip;
OBJECTTYPE tempStack;
bool clipCreated;
UINT32 newItem = 0;
INT32 pocket=-1;
UINT8 capacity=0;
UINT8 bLoop;
//find the ammo item we want to try and create
for(int loop = 0; loop < MAXITEMS; loop++)
{
if(Item[loop].usItemClass == IC_AMMO)
{
if(Magazine[Item[loop].ubClassIndex].ubCalibre == Weapon[pInSlot->usItem].ubCalibre && Magazine[Item[loop].ubClassIndex].ubAmmoType == Magazine[Item[pObj->usItem].ubClassIndex].ubAmmoType && Magazine[Item[loop].ubClassIndex].ubMagSize == GetMagSize(pInSlot))
newItem = loop;
}
}
//Create a stack of up to 5 "newItem" clips
tempStack.initialize();
clipCreated = false;
ubShotsLeft = (*pObj)[0]->data.ubShotsLeft;
for(UINT8 clip = 0; clip < 5; clip++)
{
magSize = GetMagSize(pInSlot);
if(ubShotsLeft < magSize)
magSize = ubShotsLeft;
if(CreateAmmo(newItem, &tempClip, magSize))
{
tempStack.AddObjectsToStack(tempClip, -1, pSoldier, NUM_INV_SLOTS, MAX_OBJECTS_PER_SLOT);
ubShotsLeft -= magSize;
clipCreated = true;
if(ubShotsLeft < 1)
break;
}
}
//Try to place the stack somewhere on the active merc
if(clipCreated == true)
{
clipCreated = false;
bLoop = tempStack.ubNumberOfObjects;
while(tempStack.ubNumberOfObjects > 0)
{
pocket = PickPocket(pSoldier, BIGPOCKSTART, SMALLPOCKFINAL, tempStack.usItem, bLoop, &capacity, -1);
if(pocket != -1)
{
pSoldier->inv[pocket].AddObjectsToStack(tempStack, bLoop, pSoldier, pocket);
}
else
{
bLoop--;
}
if(bLoop < 1)
break;
}
if(tempStack.ubNumberOfObjects < 1)
clipCreated = true;
else
{
//Try to place stack on ground
if( AutoPlaceObjectToWorld(pSoldier, &tempStack) )
{
clipCreated = true;
if(guiCurrentScreen == GAME_SCREEN)
NotifySoldiersToLookforItems( );
}
/*if(guiCurrentScreen == MAP_SCREEN && fShowMapInventoryPool == TRUE)
{
if(AutoPlaceObjectInInventoryStash(&tempStack, pSoldier->sGridNo))
clipCreated = true;
}
else
{
if(AddItemToPool(pSoldier->sGridNo, &tempStack, 1, pSoldier->pathing.bLevel, WORLD_ITEM_REACHABLE, -1))
{
NotifySoldiersToLookforItems( );
clipCreated = true;
}
}*/
}
}
if(clipCreated == true)
{
(*pObj)[0]->data.ubShotsLeft = ubShotsLeft;
}
if((*pObj)[0]->data.ubShotsLeft < 1)
pObj->RemoveObjectsFromStack(1);
return( TRUE );
}
else
{
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_INTERFACE, pMapInventoryErrorString[6] );
return( FALSE );
}
}
else
return( ReloadGun( pSoldier, pInSlot, pObj ) );
}
}
break;
case IC_LAUNCHER:
if ( ValidLaunchable( pObj->usItem, pInSlot->usItem ) ) {
return( ReloadGun( pSoldier, pInSlot, pObj ) );
}
break;
}
//if we didn't reload, then we know we are stacking or swapping!
if (IsSlotASmallPocket(bPos) == true && FitsInSmallPocket(pObj) == false) {
//there is nothing we can do, just return
return FALSE;
}
// CHRISL: When holding ammo and clicking on an appropriate ammo crate, add ammo to crate
if(Item[pInSlot->usItem].ammocrate == TRUE && Item[pObj->usItem].usItemClass == IC_AMMO)
{
if(Magazine[Item[pInSlot->usItem].ubClassIndex].ubCalibre == Magazine[Item[pObj->usItem].ubClassIndex].ubCalibre &&
Magazine[Item[pInSlot->usItem].ubClassIndex].ubAmmoType == Magazine[Item[pObj->usItem].ubClassIndex].ubAmmoType)
{
UINT16 magSpace = Magazine[Item[pInSlot->usItem].ubClassIndex].ubMagSize-(*pInSlot)[0]->data.ubShotsLeft;
while(pObj->ubNumberOfObjects > 0)
{
if(magSpace >= (*pObj)[0]->data.ubShotsLeft)
{
magSpace -= (*pObj)[0]->data.ubShotsLeft;
(*pInSlot)[0]->data.ubShotsLeft += (*pObj)[0]->data.ubShotsLeft;
pObj->RemoveObjectsFromStack(1);
}
else
{
(*pObj)[0]->data.ubShotsLeft -= magSpace;
(*pInSlot)[0]->data.ubShotsLeft += magSpace;
break;
}
}
if(pObj->ubNumberOfObjects > 0)
return( FALSE );
else
return( TRUE );
}
}
// CHRISL:
ubSlotLimit = ItemSlotLimit( pObj, bPos, pSoldier );
if (ubSlotLimit == 0)
{
//we have tried to stack but the stack is full, or we have tried to swap but the slot is wrong
return( FreeUpSlotIfPossibleThenPlaceObject( pSoldier, bPos, pObj ) );
}
if ( pObj->usItem == pInSlot->usItem && ubSlotLimit > 1 && IsSlotAnLBESlot(bPos) == false )
{
//we have tried to stack, but remember we can't stack 2 LBEs into 1 LBE slot, they get swapped instead
pInSlot->AddObjectsToStack( *pObj, ALL_OBJECTS, pSoldier, bPos );
}
else if ( (Item[pObj->usItem].twohanded ) && (bPos == HANDPOS) )
{
if (pSoldier->inv[SECONDHANDPOS].exists() == true) {
// both pockets have something in them, so we can't swap
return( FALSE );
}
else {
//we swapped a 2 handed object into the main hand
SwapObjs( pObj, pInSlot );
}
}
else if (IsSlotAnLBESlot(bPos) == true && Item[pObj->usItem].usItemClass == IC_LBEGEAR)
{
/*CHRISL: If we're trying to swap LBE items between IC pockets, we have to be careful that items are moved
into active pockets or that an LBENODE is properly created.*/
if(pObj->HasAnyActiveLBEs(pSoldier) == false && !(_KeyDown(SHIFT))){
std::vector<INT8> LBESlots;
GetLBESlots(bPos, LBESlots);
MoveItemsToActivePockets(pSoldier, LBESlots, bPos, pObj);
}
pInSlot->MoveThisObjectTo(gTempObject, -1, pSoldier, bPos);
pObj->MoveThisObjectTo(*pInSlot, -1, pSoldier, bPos);
//CHRISL: We need to make sure there are no items left in pObj or we'll lose them
if(pObj->ubNumberOfObjects == 0)
gTempObject.MoveThisObjectTo(*pObj, -1);
else
AutoPlaceObjectAnywhere(pSoldier, &gTempObject, FALSE);
}
else if (ubSlotLimit < pObj->ubNumberOfObjects)
{
//not enough room, so we free up some space
return( FreeUpSlotIfPossibleThenPlaceObject( pSoldier, bPos, pObj ) );
}
else
{
//item fits here, swapping
SwapObjs( pObj, pInSlot );
}
}
// ATE: Put this in to see if we should update the robot, if we were given a controller...
if ( pSoldier->bTeam == gbPlayerNum && fObjectWasRobotRemote )
{
pSoldier->UpdateRobotControllerGivenController( );
}
ApplyEquipmentBonuses(pSoldier);
//Pulmu bugfix
//ADB ubWeight has been removed, see comments in OBJECTTYPE
//pInSlot->ubWeight = CalculateObjectWeight(pInSlot);
//Pulmu end
return( TRUE );
}
bool TryToStackInSlot(SOLDIERTYPE* pSoldier, OBJECTTYPE* pObj, int bSlot)
{
// CHRISL: Use new ItemSlotLimit function if we're using the new inventory system
if (pSoldier->inv[bSlot].usItem == pObj->usItem && pSoldier->inv[bSlot].exists() == true)
{
if (pSoldier->inv[bSlot].ubNumberOfObjects < ItemSlotLimit( pObj, bSlot, pSoldier ) )
{
// NEW: If in SKI, don't auto-PLACE anything into a stackable slot that's currently hatched out! Such slots
// will disappear in their entirety if sold/moved, causing anything added through here to vanish also!
if( !( ( guiTacticalInterfaceFlags & INTERFACE_SHOPKEEP_INTERFACE ) && ShouldSoldierDisplayHatchOnItem( pSoldier->ubProfile, bSlot ) ) )
{
pSoldier->inv[bSlot].AddObjectsToStack(*pObj, -1, pSoldier, bSlot);
if (pObj->exists() == false) {
return true;
}
}
}
}
return false;
}
bool TryToPlaceInSlot(SOLDIERTYPE* pSoldier, OBJECTTYPE* pObj, bool fNewItem, int& bSlot, int endSlot)
{
//bSlot = FindEmptySlotWithin( pSoldier, bSlot, endSlot );
//CHRISL: If something already exists, we want to fail since we can't place an object in this slot
if (CanItemFitInPosition(pSoldier, pObj, bSlot, false) == false || pSoldier->inv[bSlot].exists() == true) {
//bSlot = endSlot;
return false;
}
if (bSlot == ITEM_NOT_FOUND) {
bSlot = endSlot;
return false;
}
if (bSlot == SECONDHANDPOS) {
if (pSoldier->inv[HANDPOS].exists() == true) {
return false;
}
}
PlaceObject( pSoldier, bSlot, pObj, fNewItem );
if (pObj->exists() == false) {
return( true );
}
return false;
}
bool PlaceInAnySlot(SOLDIERTYPE* pSoldier, OBJECTTYPE* pObj, bool fNewItem, int bExcludeSlot)
{
//first, try to STACK the item
//try to STACK in any slot
for(int bSlot = BODYPOSSTART; bSlot < BIGPOCKSTART; bSlot++) {
if (bSlot != bExcludeSlot && TryToStackInSlot(pSoldier, pObj, bSlot) == true) {
return true;
}
}
if (FitsInSmallPocket(pObj) == true) {
//try to STACK in small pockets
for(int bSlot = SMALLPOCKSTART; bSlot < SMALLPOCKFINAL; bSlot++) {
if (bSlot != bExcludeSlot && TryToStackInSlot(pSoldier, pObj, bSlot) == true) {
return true;
}
}
}
//try to STACK in big pockets, and possibly medium pockets
int bigPocketEnd = (UsingNewInventorySystem() == true) ? MEDPOCKFINAL : BIGPOCKFINAL;
for(int bSlot = BIGPOCKSTART; bSlot < bigPocketEnd; bSlot++) {
if (bSlot != bExcludeSlot && TryToStackInSlot(pSoldier, pObj, bSlot) == true) {
return true;
}
}
//now try to PLACE
//try to PLACE in any body slot
for(int bSlot = BODYPOSSTART; bSlot < BIGPOCKSTART; bSlot++) {
if (bSlot != bExcludeSlot && TryToPlaceInSlot(pSoldier, pObj, fNewItem, bSlot, BODYPOSFINAL) == true) {
return true;
}
}
if(UsingNewInventorySystem() == true)
{
//CHRISL: Rather then a simple slot search, use PickPocket to find the most appropriate pocket to use
INT32 sPocket=-1, mPocket=-1, lPocket=-1;
UINT8 sCapacity=0;
UINT8 mCapacity=0;
UINT8 lCapacity=0;
UINT8 capacity=0;
int bSlot;
//Start with active big pockets
sPocket=PickPocket(pSoldier, SMALLPOCKSTART, SMALLPOCKFINAL, pObj->usItem, pObj->ubNumberOfObjects, &sCapacity, bExcludeSlot);
//Next search active medium pockets
mPocket=PickPocket(pSoldier, MEDPOCKSTART, MEDPOCKFINAL, pObj->usItem, pObj->ubNumberOfObjects, &mCapacity, bExcludeSlot);
//Lastly search active small pockets
lPocket=PickPocket(pSoldier, BIGPOCKSTART, BIGPOCKFINAL, pObj->usItem, pObj->ubNumberOfObjects, &lCapacity, bExcludeSlot);
//Finally, compare the three pockets we've found and return the pocket that is most logical to use
capacity = min(sCapacity, mCapacity);
capacity = min(lCapacity, capacity);
if(capacity == 254) { //no pocket found
return false;
}
else if(capacity == sCapacity) {
bSlot = sPocket;
}
else if(capacity == mCapacity) {
bSlot = mPocket;
}
else if(capacity == lCapacity) {
bSlot = lPocket;
}
if(TryToPlaceInSlot(pSoldier, pObj, fNewItem, bSlot, NUM_INV_SLOTS) == true)
return true;
}
else
{
if (FitsInSmallPocket(pObj) == true) {
//try to PLACE in small pockets
for(int bSlot = SMALLPOCKSTART; bSlot < SMALLPOCKFINAL; bSlot++) {
if (bSlot != bExcludeSlot && TryToPlaceInSlot(pSoldier, pObj, fNewItem, bSlot, NUM_INV_SLOTS) == true) {
return true;
}
}
}
//try to PLACE in big pockets, and possibly medium pockets
for(int bSlot = BIGPOCKSTART; bSlot < bigPocketEnd; bSlot++) {
if (bSlot != bExcludeSlot && TryToPlaceInSlot(pSoldier, pObj, fNewItem, bSlot, bigPocketEnd) == true) {
return true;
}
}
}
return false;
}
bool PlaceInAnyPocket(SOLDIERTYPE* pSoldier, OBJECTTYPE* pObj, bool fNewItem, int bExcludeSlot)
{
//first, try to STACK the item
if (FitsInSmallPocket(pObj) == true) {
//try to STACK in small pockets
for(int bSlot = SMALLPOCKSTART; bSlot < SMALLPOCKFINAL; bSlot++) {
if (bSlot != bExcludeSlot && TryToStackInSlot(pSoldier, pObj, bSlot) == true) {
return true;
}
}
}
//try to STACK in big pockets, and possibly medium pockets
int bigPocketEnd = (UsingNewInventorySystem() == true) ? MEDPOCKFINAL : BIGPOCKFINAL;
for(int bSlot = BIGPOCKSTART; bSlot < bigPocketEnd; bSlot++) {
if (bSlot != bExcludeSlot && TryToStackInSlot(pSoldier, pObj, bSlot) == true) {
return true;
}
}
if (FitsInSmallPocket(pObj) == true) {
//try to PLACE in small pockets
for(int bSlot = SMALLPOCKSTART; bSlot < SMALLPOCKFINAL; bSlot++) {
if (bSlot != bExcludeSlot && TryToPlaceInSlot(pSoldier, pObj, fNewItem, bSlot, NUM_INV_SLOTS) == true) {
return true;
}
}
}
//try to PLACE in big pockets, and possibly medium pockets
for(int bSlot = BIGPOCKSTART; bSlot < bigPocketEnd; bSlot++) {
if (bSlot != bExcludeSlot && TryToPlaceInSlot(pSoldier, pObj, fNewItem, bSlot, bigPocketEnd) == true) {
return true;
}
}
return false;
}
bool PlaceInAnyBigOrMediumPocket(SOLDIERTYPE* pSoldier, OBJECTTYPE* pObj, bool fNewItem, int bExcludeSlot)
{
//a special note, although some items do not fit in small pockets, and under the old system are restricted to big pockets,
//under the new system they are intended to fit in medium pockets, if the item size and the pocket agree
//An example would be a SMG fitting in a gun holster, which is medium.
int bigPocketEnd = (UsingNewInventorySystem() == true) ? MEDPOCKFINAL : BIGPOCKFINAL;
//first, try to STACK the item
for(int bSlot = BIGPOCKSTART; bSlot < bigPocketEnd; bSlot++) {
if (bSlot != bExcludeSlot && TryToStackInSlot(pSoldier, pObj, bSlot) == true) {
return true;
}
}
//now try to PLACE
for(int bSlot = BIGPOCKSTART; bSlot < bigPocketEnd; bSlot++) {
if (bSlot != bExcludeSlot && TryToPlaceInSlot(pSoldier, pObj, fNewItem, bSlot, bigPocketEnd) == true) {
return true;
}
}
return false;
}
bool PlaceInAnySmallPocket(SOLDIERTYPE* pSoldier, OBJECTTYPE* pObj, bool fNewItem, int bExcludeSlot)
{
if (FitsInSmallPocket(pObj) == false) {
return false;
}
//first, try to STACK the item
for(int bSlot = SMALLPOCKSTART; bSlot < SMALLPOCKFINAL; bSlot++) {
if (bSlot != bExcludeSlot && TryToStackInSlot(pSoldier, pObj, bSlot) == true) {
return true;
}
}
//try to PLACE in small pockets
for(int bSlot = SMALLPOCKSTART; bSlot < SMALLPOCKFINAL; bSlot++) {
if (bSlot != bExcludeSlot && TryToPlaceInSlot(pSoldier, pObj, fNewItem, bSlot, NUM_INV_SLOTS) == true) {
return true;
}
}
return false;
}
BOOLEAN AutoPlaceObjectAnywhere(SOLDIERTYPE * pSoldier, OBJECTTYPE * pObj, BOOLEAN fNewItem, INT8 bExcludeSlot)
{
// This function will attempt to place an object into the soldier's inventory first. If that doesn't work, it'll add the object to sector inventory
if(pObj->exists() == false)
return FALSE;
if( AutoPlaceObject(pSoldier, pObj, fNewItem, bExcludeSlot) )
return TRUE;
else
return (AutoPlaceObjectToWorld(pSoldier, pObj, TRUE) );
return FALSE;
}
extern BOOLEAN IsMercInActiveSector(SOLDIERTYPE * pSoldier);
extern void CreateDestroyMapInventoryPoolButtons( BOOLEAN fExitFromMapScreen );
BOOLEAN AutoPlaceObjectToWorld(SOLDIERTYPE * pSoldier, OBJECTTYPE * pObj, INT8 bVisible)
{
if(pObj->exists() == false)
return FALSE;
INT32 sGridNo = pSoldier?pSoldier->sGridNo:0;
INT8 bLevel = pSoldier?pSoldier->pathing.bLevel:0;
if( guiCurrentScreen == MAP_SCREEN )
{
// the_bob : added the check for whether pSoldier actually points to something to handle calling this function with pSoldier = NULL
if (pSoldier){
if(fShowMapInventoryPool && !IsMercInActiveSector(pSoldier) )
{
fShowMapInventoryPool = FALSE;
CreateDestroyMapInventoryPoolButtons(FALSE);
}
ChangeSelectedMapSector(pSoldier->sSectorX, pSoldier->sSectorY, pSoldier->bSectorZ);
}
if(!fShowMapInventoryPool)
{
fShowMapInventoryPool = TRUE;
CreateDestroyMapInventoryPoolButtons(FALSE);
}
fMapPanelDirty = TRUE;
return( AutoPlaceObjectInInventoryStash(pObj, sGridNo) );
}
else
{
AddItemToPool(sGridNo, pObj, bVisible, bLevel, WORLD_ITEM_REACHABLE, 0);
return TRUE;
}
return FALSE;
}
// CHRISL: Function needed for LBENODE
BOOLEAN AutoPlaceObject( SOLDIERTYPE * pSoldier, OBJECTTYPE * pObj, BOOLEAN fNewItem, INT8 bExcludeSlot )
{
INVTYPE * pItem;
UINT32 packCombo, backCombo;
// statuses of extra objects would be 0 if the # exceeds the maximum
//Assert( pObj->ubNumberOfObjects <= MAX_OBJECTS_PER_SLOT);
//Pulmu bugfix
//ADB ubWeight has been removed, see comments in OBJECTTYPE
//pObj->ubWeight = CalculateObjectWeight( pObj);
pItem = &(Item[pObj->usItem]);
int lbeClass;
// Overrides to the standard system: put guns in hand, armour on body (if slot empty)
switch (pItem->usItemClass)
{
case IC_GUN:
case IC_THROWING_KNIFE:
case IC_BLADE:
case IC_LAUNCHER:
case IC_BOMB:
case IC_GRENADE:
if (pSoldier->inv[HANDPOS].exists() == false)
{
// put the one-handed weapon in the guy's hand...
PlaceObject( pSoldier, HANDPOS, pObj, fNewItem );
if ( pObj->exists() == false )
{
return( TRUE );
}
}
else if ( !(Item[pSoldier->inv[HANDPOS].usItem].twohanded ) && pSoldier->inv[SECONDHANDPOS].exists() == false)
{
// put the one-handed weapon in the guy's 2nd hand...
PlaceObject( pSoldier, SECONDHANDPOS, pObj, fNewItem );
if ( pObj->exists() == false )
{
return( TRUE );
}
}
// two-handed objects are best handled in the main loop for large objects,
// which checks the hands first anyhow
//CHRISL: New switch. Place items into Gunsling or Knife pocket is using NewInv, item is appropriate, and we
// didn't manage to place in hands.
if(UsingNewInventorySystem() == true)
{
switch (pItem->usItemClass)
{
case IC_GUN:
if(pSoldier->inv[GUNSLINGPOCKPOS].exists() == false) // Long Gun use Gun Sling
{
PlaceObject( pSoldier, GUNSLINGPOCKPOS, pObj, fNewItem );
if (pObj->exists() == false)
return( TRUE );
}
break;
case IC_THROWING_KNIFE:
case IC_BLADE:
if(pSoldier->inv[KNIFEPOCKPOS].exists() == false) // Knife
{
PlaceObject( pSoldier, KNIFEPOCKPOS, pObj, fNewItem );
if (pObj->exists() == false)
return( TRUE );
}
break;
}
}
break;
case IC_ARMOUR:
switch (Armour[Item[pObj->usItem].ubClassIndex].ubArmourClass)
{
case ARMOURCLASS_VEST:
if (pSoldier->inv[VESTPOS].exists() == false)
{
// put on the armour!
PlaceObject( pSoldier, VESTPOS, pObj, fNewItem );
if ( pObj->exists() == false )
{
return( TRUE );
}
}
break;
case ARMOURCLASS_LEGGINGS:
/* CHRISL: If we're wearing leg protectors and pick up leggings, we want to leggings to override.
This is only an issue during merc hiring when leggings will often be placed after leg protectors.
However, this isn't as big an issue at this point because of the redesigns in the profile item sorting
functions.*/
if(Item[pSoldier->inv[LEGPOS].usItem].attachment)
{
SwapObjs(pSoldier, LEGPOS, pObj, TRUE);
pSoldier->inv[LEGPOS].AttachObject(pSoldier, pObj, FALSE);
}
if (pSoldier->inv[LEGPOS].exists() == false)
{
// put on the armour!
PlaceObject( pSoldier, LEGPOS, pObj, fNewItem );
}
if ( pObj->exists() == false )
{
return( TRUE );
}
break;
case ARMOURCLASS_HELMET:
if (pSoldier->inv[HELMETPOS].exists() == false)
{
// put on the armour!
PlaceObject( pSoldier, HELMETPOS, pObj, fNewItem );
if ( pObj->exists() == false )
{
return( TRUE );
}
}
break;
default:
break;
}
// otherwise stuff it in a slot somewhere
break;
case IC_FACE:
if ( (pSoldier->inv[HEAD1POS].exists() == false) && CompatibleFaceItem( pObj->usItem, pSoldier->inv[HEAD2POS].usItem ) )
{
PlaceObject( pSoldier, HEAD1POS, pObj, fNewItem );
if ( pObj->exists() == false )
{
return( TRUE );
}
}
else if ( (pSoldier->inv[HEAD2POS].exists() == false) && CompatibleFaceItem( pObj->usItem, pSoldier->inv[HEAD1POS].usItem ) )
{
PlaceObject( pSoldier, HEAD2POS, pObj, fNewItem );
if ( pObj->exists() == false )
{
return( TRUE );
}
}
break;
// CHRISL:
case IC_LBEGEAR:
if(UsingNewInventorySystem() == false) {
break;
}
lbeClass = LoadBearingEquipment[pItem->ubClassIndex].lbeClass;
if(lbeClass == THIGH_PACK) // Thigh pack
{
if (pSoldier->inv[LTHIGHPOCKPOS].exists() == false) {
PlaceObject( pSoldier, LTHIGHPOCKPOS, pObj, fNewItem );
if(pObj->exists() == false)
return( TRUE );
}
if (pSoldier->inv[RTHIGHPOCKPOS].exists() == false) {
PlaceObject( pSoldier, RTHIGHPOCKPOS, pObj, fNewItem );
if(pObj->exists() == false)
return( TRUE );
}
}
else if(pSoldier->inv[VESTPOCKPOS].exists() == false && lbeClass == VEST_PACK) // Vest pack
{
PlaceObject( pSoldier, VESTPOCKPOS, pObj, fNewItem );
if(pObj->exists() == false)
return( TRUE );
}
else if(pSoldier->inv[CPACKPOCKPOS].exists() == false && lbeClass == COMBAT_PACK) // Combat pack
{
packCombo = LoadBearingEquipment[pItem->ubClassIndex].lbeCombo;
backCombo = LoadBearingEquipment[Item[pSoldier->inv[BPACKPOCKPOS].usItem].ubClassIndex].lbeCombo;
//DBrot: changed to bitwise comparison
if((pSoldier->inv[BPACKPOCKPOS].exists() == true && packCombo != 0 && (backCombo & packCombo)) || pSoldier->inv[BPACKPOCKPOS].exists() == false)
{
PlaceObject( pSoldier, CPACKPOCKPOS, pObj, fNewItem );
if(pObj->exists() == false)
return( TRUE );
}
}
else if(pSoldier->inv[BPACKPOCKPOS].exists() == false && lbeClass == BACKPACK) // Backpack
{
//CHRISL: We're no longer restricting backpacks and gunslings from being used together
//if(pSoldier->inv[GUNSLINGPOCKPOS].exists() == false)
//{
packCombo = LoadBearingEquipment[Item[pSoldier->inv[CPACKPOCKPOS].usItem].ubClassIndex].lbeCombo;
backCombo = LoadBearingEquipment[pItem->ubClassIndex].lbeCombo;
//DBrot: changed to bitwise comparison
if((pSoldier->inv[CPACKPOCKPOS].exists() == true && backCombo != 0 && (backCombo & packCombo)) || pSoldier->inv[CPACKPOCKPOS].exists() == false)
{
PlaceObject( pSoldier, BPACKPOCKPOS, pObj, fNewItem );
pSoldier->flags.DropPackFlag = FALSE;
pSoldier->flags.ZipperFlag = FALSE;
RenderBackpackButtons(ACTIVATE_BUTTON); /* CHRISL: Needed for new inventory backpack buttons */
if(pObj->exists() == false)
return( TRUE );
}
//}
}
break;
default:
break;
}
if (PlaceInAnySlot(pSoldier, pObj, (fNewItem == TRUE), bExcludeSlot) == true) {
return TRUE;
}
return( FALSE );
}
BOOLEAN RemoveKeyFromSlot( SOLDIERTYPE * pSoldier, INT8 bKeyRingPosition, OBJECTTYPE * pObj )
{
UINT8 ubItem = 0;
CHECKF( pObj );
if( ( pSoldier->pKeyRing[ bKeyRingPosition ].ubNumber == 0 ) || ( pSoldier->pKeyRing[ bKeyRingPosition ].ubKeyID == INVALID_KEY_NUMBER ) )
{
return( FALSE );
}
else
{
// create an object
ubItem = pSoldier->pKeyRing[ bKeyRingPosition ].ubKeyID;
if( pSoldier->pKeyRing[ bKeyRingPosition ].ubNumber > 1 )
{
pSoldier->pKeyRing[ bKeyRingPosition ].ubNumber--;
}
else
{
pSoldier->pKeyRing[ bKeyRingPosition ].ubNumber = 0;
pSoldier->pKeyRing[ bKeyRingPosition ].ubKeyID = INVALID_KEY_NUMBER;
}
return( CreateKeyObject( pObj, 1, ubItem ) );
}
return( FALSE );
}
BOOLEAN RemoveKeysFromSlot( SOLDIERTYPE * pSoldier, INT8 bKeyRingPosition, UINT8 ubNumberOfKeys ,OBJECTTYPE * pObj )
{
UINT8 ubItems = 0;
CHECKF( pObj );
if( ( pSoldier->pKeyRing[ bKeyRingPosition ].ubNumber == 0 ) || ( pSoldier->pKeyRing[ bKeyRingPosition ].ubKeyID == INVALID_KEY_NUMBER ) )
{
return( FALSE );
}
else
{
//*pObj = pSoldier->inv[bPos];
if( pSoldier->pKeyRing[ bKeyRingPosition ].ubNumber < ubNumberOfKeys )
{
ubNumberOfKeys = pSoldier->pKeyRing[ bKeyRingPosition ].ubNumber;
}
ubItems = pSoldier->pKeyRing[ bKeyRingPosition ].ubKeyID;
if( pSoldier->pKeyRing[ bKeyRingPosition ].ubNumber - ubNumberOfKeys > 0 )
{
pSoldier->pKeyRing[ bKeyRingPosition ].ubNumber--;
}
else
{
pSoldier->pKeyRing[ bKeyRingPosition ].ubNumber = 0;
pSoldier->pKeyRing[ bKeyRingPosition ].ubKeyID = INVALID_KEY_NUMBER;
}
// create an object
return( CreateKeyObject( pObj, ubNumberOfKeys, ubItems ) );
}
}
// return number added
UINT8 AddKeysToSlot( SOLDIERTYPE * pSoldier, INT8 bKeyRingPosition, OBJECTTYPE * pObj )
{
UINT8 ubNumberNotAdded = 0;
if ( pSoldier->flags.uiStatusFlags & SOLDIER_PC ) // redundant but what the hey
{
if ( KeyTable[ (*pObj)[0]->data.key.ubKeyID ].usDateFound == 0 )
{
KeyTable[ (*pObj)[0]->data.key.ubKeyID ].usDateFound = (UINT16) GetWorldDay();
KeyTable[ (*pObj)[0]->data.key.ubKeyID ].usSectorFound = SECTOR( pSoldier->sSectorX, pSoldier->sSectorY );
}
}
// check if we are going to far
if ( ( pSoldier->pKeyRing[ bKeyRingPosition ].ubNumber + pObj->ubNumberOfObjects ) > ItemSlotLimit(pObj, STACK_SIZE_LIMIT) )
{
// only take what we can
ubNumberNotAdded = pObj->ubNumberOfObjects - ( ItemSlotLimit(pObj, STACK_SIZE_LIMIT) - pSoldier->pKeyRing[ bKeyRingPosition ].ubNumber );
// set to max
pSoldier->pKeyRing[ bKeyRingPosition ].ubNumber = ItemSlotLimit(pObj, STACK_SIZE_LIMIT);
if( pSoldier->pKeyRing[ bKeyRingPosition ].ubNumber == 0 )
{
pSoldier->pKeyRing[ bKeyRingPosition ].ubKeyID = (*pObj)[0]->data.key.ubKeyID;
}
// return number used
return( pObj->ubNumberOfObjects - ubNumberNotAdded );
}
else
{
// check
if( pSoldier->pKeyRing[ bKeyRingPosition ].ubNumber == 0 )
{
pSoldier->pKeyRing[ bKeyRingPosition ].ubKeyID = (*pObj)[0]->data.key.ubKeyID;
}
pSoldier->pKeyRing[ bKeyRingPosition ].ubNumber += pObj->ubNumberOfObjects;
}
return( pObj->ubNumberOfObjects );
}
UINT8 SwapKeysToSlot( SOLDIERTYPE * pSoldier, INT8 bKeyRingPosition, OBJECTTYPE * pObj )
{
// swap keys in keyring slot and keys in pocket
// create temp object to hold keys currently in key ring slot
CreateKeyObject( &gTempObject, pSoldier->pKeyRing[ bKeyRingPosition ].ubNumber, pSoldier->pKeyRing[ bKeyRingPosition ].ubKeyID );
pSoldier->pKeyRing[ bKeyRingPosition ].ubNumber = pObj->ubNumberOfObjects;
pSoldier->pKeyRing[ bKeyRingPosition ].ubKeyID = (*pObj)[0]->data.key.ubKeyID;
// swap params?
*pObj = gTempObject;
return( 1 );
}
BOOLEAN CreateKeyObject( OBJECTTYPE * pObj , UINT8 ubNumberOfKeys, UINT8 ubKeyID )
{
BOOLEAN fRet;
pObj->initialize();
fRet = CreateItems( (UINT16) (FIRST_KEY + LockTable[ ubKeyID ].usKeyItem), 100, ubNumberOfKeys, pObj );
if (fRet)
{
(*pObj)[0]->data.key.ubKeyID = ubKeyID;
}
//fRet = CreateItems( (UINT16)(ubKeyIdValue + FIRST_KEY) , 100, ubNumberOfKeys, pObj )
//return( );
return( fRet );
}
BOOLEAN AllocateObject( OBJECTTYPE **pObj )
{
// create a key object
*pObj = new OBJECTTYPE;
Assert( pObj );
return( TRUE );
}
BOOLEAN DeleteKeyObject( OBJECTTYPE * pObj )
{
if( pObj == FALSE )
{
return( FALSE );
}
// free up space
delete( pObj );
return( TRUE );
}
UINT16 TotalPoints( OBJECTTYPE * pObj )
{
UINT16 usPoints = 0;
UINT8 ubLoop;
for (ubLoop = 0; ubLoop < pObj->ubNumberOfObjects; ubLoop++)
{
usPoints += (*pObj)[ubLoop]->data.objectStatus;
}
return( usPoints );
}
UINT16 UseKitPoints( OBJECTTYPE * pObj, UINT16 usPoints, SOLDIERTYPE *pSoldier )
{
// start consuming from the last kit in, so we end up with fewer fuller kits rather than
// lots of half-empty ones.
INT8 bLoop;
UINT16 usOriginalPoints = usPoints;
for (bLoop = pObj->ubNumberOfObjects - 1; bLoop >= 0; bLoop--)
{
// SANDRO - revisited this code, make the percentstatusdrainreduction count always
if( (usPoints * (max( 0, (100 - Item[pObj->usItem].percentstatusdrainreduction)))/100) < (*pObj)[bLoop]->data.objectStatus )
{
(*pObj)[bLoop]->data.objectStatus -= (INT8)(usPoints * (max( 0, (100 - Item[pObj->usItem].percentstatusdrainreduction) ) )/100);
return( usOriginalPoints );
}
else
{
// consume this kit totally
usPoints -= (((*pObj)[bLoop]->data.objectStatus) / (max( 0, (100 - Item[pObj->usItem].percentstatusdrainreduction))) /100);
(*pObj)[bLoop]->data.objectStatus = 0;
pObj->ubNumberOfObjects--;
}
/*
// SANDRO - heh, this is not very right solution.. in second case, the percentstatusdrainreduction should be taken into account too
if (Item[pObj->usItem].percentstatusdrainreduction > 0 && ((usPoints * (100 - Item[pObj->usItem].percentstatusdrainreduction))/100) < (*pObj)[bLoop]->data.objectStatus )
{
(*pObj)[bLoop]->data.objectStatus -= (INT8) ((usPoints * (100 - Item[pObj->usItem].percentstatusdrainreduction ) )/100);
return( usOriginalPoints );
}
else if (usPoints < (UINT16) (*pObj)[bLoop]->data.objectStatus)
{
(*pObj)[bLoop]->data.objectStatus -= (INT8) usPoints;
return( usOriginalPoints );
}
else
{
// consume this kit totally
usPoints -= (*pObj)[bLoop]->data.objectStatus;
(*pObj)[bLoop]->data.objectStatus = 0;
pObj->ubNumberOfObjects--;
}*/
}
// check if pocket/hand emptied..update inventory, then update panel
if( pObj->exists() == false )
{
// Delete object
DeleteObj( pObj );
// dirty interface panel
DirtyMercPanelInterface( pSoldier, DIRTYLEVEL2 );
}
return( usOriginalPoints - usPoints );
}
#ifdef PATHAI_VISIBLE_DEBUG
extern BOOLEAN gfDrawPathPoints;
#else
#ifdef AI_TIMING_TESTS
extern UINT32 guiGreenTimeTotal, guiYellowTimeTotal, guiRedTimeTotal, guiBlackTimeTotal;
extern UINT32 guiGreenCounter, guiYellowCounter, guiRedCounter, guiBlackCounter;
extern UINT32 guiRedSeekTimeTotal, guiRedHelpTimeTotal, guiRedHideTimeTotal;
extern UINT32 guiRedSeekCounter, guiRedHelpCounter; guiRedHideCounter;
#endif
#endif
UINT16 MagazineClassIndexToItemType(UINT16 usMagIndex)
{
UINT16 usLoop;
// Note: if any ammo items in the item table are separated from the main group,
// this function will have to be rewritten to scan the item table for an item
// with item class ammo, which has class index usMagIndex
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, String( "MagazineClassIndexToItemType" ) );
// WANNE: Now ammo can be inserted anywhere in Items.xml (before only on index > 70 [FIRST_AMMO] (fix by Realist)
//for (usLoop = FIRST_AMMO; usLoop < MAXITEMS; usLoop++)
for (usLoop = 0; usLoop < MAXITEMS; usLoop++)
{
if ( Item[usLoop].usItemClass == 0 )
{
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, String( "MagazineClassIndexToItemType: breaking at index %d", usLoop ) );
break;
}
if (Item[usLoop].ubClassIndex == usMagIndex && Item[usLoop].usItemClass == IC_AMMO )
{
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, String( "MagazineClassIndexToItemType: return %d", usLoop ) );
return( usLoop );
}
}
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, String( "MagazineClassIndexToItemType: return none, got to %d", usLoop ) );
return(NONE);
}
UINT16 DefaultMagazine( UINT16 usItem )
{
WEAPONTYPE * pWeapon;
UINT16 usLoop;
DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("DefaultMagazine: item = %d",usItem));
if (!(Item[usItem].usItemClass & IC_GUN))
{
return( 0 );
}
pWeapon = &(Weapon[usItem]);
usLoop = 0;
while ( Magazine[usLoop].ubCalibre != NOAMMO )
{
if (Magazine[usLoop].ubCalibre == pWeapon->ubCalibre &&
Magazine[usLoop].ubMagSize == pWeapon->ubMagSize &&
AmmoTypes[ Magazine[usLoop].ubAmmoType ].standardIssue )
{
DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("DefaultMagazine: found at index %d",usLoop));
return(MagazineClassIndexToItemType(usLoop));
}
usLoop++;
}
DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("DefaultMagazine: can't find any"));
return( 0 );
}
UINT16 FindReplacementMagazine( UINT8 ubCalibre, UINT16 ubMagSize, UINT8 ubAmmoType )
{
UINT16 usLoop;
UINT16 usDefault;
usLoop = 0;
usDefault = NOTHING;
DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("FindReplacementMagazine: calibre = %d, Mag size = %d, ammo type = %d",ubCalibre,ubMagSize,ubAmmoType));
while ( Magazine[usLoop].ubCalibre != NOAMMO )
{
if (Magazine[usLoop].ubCalibre == ubCalibre &&
Magazine[usLoop].ubMagSize == ubMagSize )
{
if ( Magazine[usLoop].ubAmmoType == ubAmmoType )
{
DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("FindReplacementMagazine: returning item = %d",MagazineClassIndexToItemType( usLoop )));
return( MagazineClassIndexToItemType( usLoop ) );
}
else if ( usDefault == NOTHING )
{
// store this one to use if all else fails
usDefault = MagazineClassIndexToItemType( usLoop );
}
}
usLoop++;
}
DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("FindReplacementMagazine: returning default item = %d",usDefault));
return( usDefault );
}
UINT16 FindReplacementMagazineIfNecessary( UINT16 usOldGun, UINT16 usOldAmmo, UINT16 usNewGun )
{
UINT16 usNewAmmo = NOTHING;
if ( (Magazine[ Item[ usOldAmmo ].ubClassIndex ].ubCalibre == Weapon[ usOldGun ].ubCalibre) &&
(Magazine[ Item[ usOldAmmo ].ubClassIndex ].ubMagSize == Weapon[ usOldGun ].ubMagSize) )
{
// must replace this!
usNewAmmo = FindReplacementMagazine( Weapon[ usNewGun ].ubCalibre, Weapon[ usNewGun ].ubMagSize, Magazine[ Item[ usOldAmmo ].ubClassIndex ].ubAmmoType );
}
return( usNewAmmo );
}
// increase this if any gun can have more types that this
#define MAX_AMMO_TYPES_PER_GUN 24 // MADD MARKER
UINT16 RandomMagazine( UINT16 usItem, UINT8 ubPercentStandard, UINT8 maxCoolness )
{
// Note: if any ammo items in the item table are separated from the main group,
// this function will have to be rewritten to scan the item table for an item
// with item class ammo, which has class index ubLoop
DebugMsg (TOPIC_JA2,DBG_LEVEL_3,String("RandomMagazine (by index)"));
WEAPONTYPE * pWeapon;
UINT16 usLoop;
UINT16 loopItem;
UINT16 usPossibleMagIndex[ MAX_AMMO_TYPES_PER_GUN ];
UINT16 usPossibleMagCnt = 0;
UINT8 ubMagChosen;
if (!(Item[usItem].usItemClass & IC_GUN))
{
return( 0 );
}
pWeapon = &(Weapon[usItem]);
// find & store all possible mag types that fit this gun
usLoop = 0;
while ( Magazine[ usLoop ].ubCalibre != NOAMMO )
{
loopItem = MagazineClassIndexToItemType(usLoop);
if (Magazine[usLoop].ubCalibre == pWeapon->ubCalibre &&
Magazine[usLoop].ubMagSize == pWeapon->ubMagSize && ItemIsLegal(loopItem)
&& maxCoolness >= Item[loopItem].ubCoolness )
{
// store it! (make sure array is big enough)
Assert(usPossibleMagCnt < MAX_AMMO_TYPES_PER_GUN);
// Madd: check to see if allowed by army
if ( gArmyItemChoices[ENEMYAMMOTYPES].ubChoices > 0 )
{
for ( int i=0;i<gArmyItemChoices[ENEMYAMMOTYPES].ubChoices;i++ )
{
if ( gArmyItemChoices[ENEMYAMMOTYPES].bItemNo[i] == Magazine[usLoop].ubAmmoType )
{
usPossibleMagIndex[usPossibleMagCnt++] = usLoop;
break;
}
}
}
else
{
usPossibleMagIndex[usPossibleMagCnt++] = usLoop;
}
}
usLoop++;
}
// no matches?
if (usPossibleMagCnt == 0)
{
return( 0 );
}
else
// only one match?
if (usPossibleMagCnt == 1)
{
// use that, no choice
return(MagazineClassIndexToItemType( usPossibleMagIndex[ 0 ] ));
}
else // multiple choices
{
// Pick one at random, using supplied probability to pick the default
if (Random(100) < ubPercentStandard)
{
ubMagChosen = 0;
DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("RandomMagazine: ubMagChosen = %d",ubMagChosen ));
return( DefaultMagazine(usItem) );
}
else
{
// pick a non-standard type instead
ubMagChosen = ( UINT8 ) (1 + Random(( UINT32 ) ( usPossibleMagCnt - 1 )));
}
DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("RandomMagazine: ubMagChosen = %d",ubMagChosen ));
return( MagazineClassIndexToItemType(usPossibleMagIndex[ ubMagChosen ] ) );
}
}
UINT16 RandomMagazine( OBJECTTYPE * pGun, UINT8 ubPercentStandard, UINT8 maxCoolness )
{
// Note: if any ammo items in the item table are separated from the main group,
// this function will have to be rewritten to scan the item table for an item
// with item class ammo, which has class index ubLoop
DebugMsg (TOPIC_JA2,DBG_LEVEL_3,String("RandomMagazine"));
WEAPONTYPE * pWeapon;
UINT16 usLoop;
UINT16 loopItem;
UINT16 usPossibleMagIndex[ MAX_AMMO_TYPES_PER_GUN ];
UINT16 usPossibleMagCnt = 0;
UINT8 ubMagChosen;
if (!(Item[pGun->usItem].usItemClass & IC_GUN))
{
return( 0 );
}
pWeapon = &(Weapon[pGun->usItem]);
// find & store all possible mag types that fit this gun
usLoop = 0;
while ( Magazine[ usLoop ].ubCalibre != NOAMMO )
{
loopItem = MagazineClassIndexToItemType(usLoop);
if (Magazine[usLoop].ubCalibre == pWeapon->ubCalibre &&
Magazine[usLoop].ubMagSize == GetMagSize(pGun) && ItemIsLegal(loopItem)
&& maxCoolness >= Item[loopItem].ubCoolness )
{
// store it! (make sure array is big enough)
Assert(usPossibleMagCnt < MAX_AMMO_TYPES_PER_GUN);
// Madd: check to see if allowed by army
if ( gArmyItemChoices[ENEMYAMMOTYPES].ubChoices > 0 )
{
for ( int i=0;i<gArmyItemChoices[ENEMYAMMOTYPES].ubChoices;i++ )
{
if ( gArmyItemChoices[ENEMYAMMOTYPES].bItemNo[i] == Magazine[usLoop].ubAmmoType )
{
usPossibleMagIndex[usPossibleMagCnt++] = usLoop;
break;
}
}
}
else
{
usPossibleMagIndex[usPossibleMagCnt++] = usLoop;
}
}
usLoop++;
}
// no matches?
if (usPossibleMagCnt == 0)
{
return( 0 );
}
else
// only one match?
if (usPossibleMagCnt == 1)
{
// use that, no choice
return(MagazineClassIndexToItemType(usPossibleMagIndex[ 0 ] ));
}
else // multiple choices
{
// Pick one at random, using supplied probability to pick the default
if (Random(100) < ubPercentStandard)
{
ubMagChosen = 0;
DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("RandomMagazine: ubMagChosen = %d",ubMagChosen ));
return( DefaultMagazine(pGun->usItem) );
}
else
{
// pick a non-standard type instead
ubMagChosen = ( UINT8 ) (1 + Random(( UINT32 ) ( usPossibleMagCnt - 1 )));
}
DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("RandomMagazine: ubMagChosen = %d",ubMagChosen ));
return( MagazineClassIndexToItemType(usPossibleMagIndex[ ubMagChosen ] ) );
}
}
BOOLEAN CreateGun( UINT16 usItem, INT16 bStatus, OBJECTTYPE * pObj )
{
UINT16 usAmmo;
DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("CreateGun: usItem = %d",usItem));
Assert( pObj != NULL);
if ( pObj == NULL )
{
return( FALSE );
}
pObj->initialize();
pObj->usItem = usItem;
pObj->ubNumberOfObjects = 1;
//pObj->objectStack.resize(1);//not necessary due to init, here for code commenting
StackedObjectData* pStackedObject = (*pObj)[0];
pStackedObject->data.gun.bGunStatus = bStatus;
pStackedObject->data.ubImprintID = NO_PROFILE;
if (Weapon[ usItem ].ubWeaponClass == MONSTERCLASS)
{
pStackedObject->data.gun.ubGunShotsLeft = GetMagSize(pObj);
pStackedObject->data.gun.ubGunAmmoType = AMMO_MONSTER;
pStackedObject->data.gun.ubGunState |= GS_CARTRIDGE_IN_CHAMBER; // 0verhaul: Monsters don't have to reload!
}
else if ( EXPLOSIVE_GUN( usItem ) )
{
if ( Item[usItem].singleshotrocketlauncher )
{
pStackedObject->data.gun.ubGunShotsLeft = 1;
}
else
{
// cannon
pStackedObject->data.gun.ubGunShotsLeft = 0;
}
pStackedObject->data.gun.bGunAmmoStatus = 100;
pStackedObject->data.gun.ubGunAmmoType = 0;
}
else
{
usAmmo = DefaultMagazine( usItem );
//CHRISL: Why do we have an assert here when the very next condition says to return a FALSE if usAmmo is 0?
//Assert( usAmmo != 0 );
if (usAmmo == 0)
{
// item's calibre & mag size not found in magazine list!
return( FALSE );
}
else
{
pStackedObject->data.gun.usGunAmmoItem = usAmmo;
pStackedObject->data.gun.ubGunAmmoType = Magazine[ Item[ usAmmo ].ubClassIndex].ubAmmoType;
pStackedObject->data.gun.bGunAmmoStatus = 100;
pStackedObject->data.gun.ubGunShotsLeft = Magazine[ Item[ usAmmo ].ubClassIndex ].ubMagSize;
pStackedObject->data.gun.ubGunState |= GS_CARTRIDGE_IN_CHAMBER; // Madd: new guns should have cartridge in chamber
}
}
//WarmSteel - Init item slots.
if(UsingNewAttachmentSystem()==true)
InitItemAttachments(pObj);
//ADB ubWeight has been removed, see comments in OBJECTTYPE
//pObj->ubWeight = CalculateObjectWeight( pObj );
DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("CreateGun: Done"));
// succesful
return( TRUE );
}
BOOLEAN CreateAmmo( UINT16 usItem, OBJECTTYPE * pObj, UINT16 ubShotsLeft )
{
if (pObj == NULL)
{
return( FALSE );
}
pObj->initialize();
pObj->usItem = usItem;
pObj->ubNumberOfObjects = 1;
//pObj->objectStack.resize(1);//not necessary due to init, here for code commenting
//if (ubShotsLeft == 0) {
// (*pObj)[0]->data.ubShotsLeft = Magazine[ Item[usItem].ubClassIndex ].ubMagSize;
//}
//else {
(*pObj)[0]->data.ubShotsLeft = ubShotsLeft;
//}
//WarmSteel - Init attachment slots.
if(UsingNewAttachmentSystem()==true)
InitItemAttachments(pObj);
//ADB ubWeight has been removed, see comments in OBJECTTYPE
//pObj->ubWeight = CalculateObjectWeight( pObj );
DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("CreateAmmo: done"));
return( TRUE );
}
BOOLEAN CreateItem( UINT16 usItem, INT16 bStatus, OBJECTTYPE * pObj )
{
DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("CreateItem: usItem = %d",usItem));
BOOLEAN fRet;
if (usItem >= MAXITEMS)
{
DebugBreakpoint();
return( FALSE );
}
if (Item[ usItem ].usItemClass == IC_GUN)
{
fRet = CreateGun( usItem, bStatus, pObj );
}
else if (Item[ usItem ].usItemClass == IC_AMMO)
{
fRet = CreateAmmo( usItem, pObj, Magazine[Item[usItem].ubClassIndex].ubMagSize );
}
else
{
pObj->initialize();
pObj->usItem = usItem;
pObj->ubNumberOfObjects = 1;
//pObj->objectStack.resize(1);//not necessary due to init, here for code commenting
if (usItem == MONEY || Item[usItem].usItemClass == IC_MONEY )
{
// special case... always set status to 100 when creating
// and use status value to determine amount!
(*pObj)[0]->data.objectStatus = 100;
(*pObj)[0]->data.money.uiMoneyAmount = bStatus * 50;
}
else
{
(*pObj)[0]->data.objectStatus = bStatus;
}
//ADB ubWeight has been removed, see comments in OBJECTTYPE
//pObj->ubWeight = CalculateObjectWeight( pObj );
fRet = TRUE;
//WarmSteel - Init attachment slots.
if(UsingNewAttachmentSystem()==true)
InitItemAttachments(pObj);
}
if (fRet)
{
// if (Item[ usItem ].fFlags & ITEM_DEFAULT_UNDROPPABLE)
if (Item[ usItem ].defaultundroppable )
{
(*pObj).fFlags |= OBJECT_UNDROPPABLE;
}
for(UINT8 cnt = 0; cnt < MAX_DEFAULT_ATTACHMENTS; cnt++){
if(Item [ usItem ].defaultattachments[cnt] == 0)
break;
//cannot use gTempObject
static OBJECTTYPE defaultAttachment;
CreateItem(Item [ usItem ].defaultattachments[cnt],100,&defaultAttachment);
pObj->AttachObject(NULL,&defaultAttachment, FALSE);
}
}
DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("CreateItem: return %d",fRet));
return( fRet );
}
BOOLEAN CreateItems( UINT16 usItem, INT8 bStatus, UINT8 ubNumber, OBJECTTYPE * pObj )
{
BOOLEAN fOk;
fOk = CreateItem( usItem, bStatus, pObj );
if (fOk)
{
if (ubNumber > 1) {
//no need to recalc weight if just 1, CreateItem did that.
for (int x = 1; x < ubNumber; ++x) {
pObj->objectStack.push_back(pObj->objectStack.front());
}
pObj->ubNumberOfObjects = ubNumber;
//ADB ubWeight has been removed, see comments in OBJECTTYPE
//pObj->ubWeight = CalculateObjectWeight(pObj);
}
return( TRUE );
}
return( FALSE );
}
BOOLEAN CreateMoney( UINT32 uiMoney, OBJECTTYPE * pObj )
{
BOOLEAN fOk;
fOk = CreateItem( MONEY, 100, pObj );
if (fOk)
{
(*pObj)[0]->data.money.uiMoneyAmount = uiMoney;
}
return( fOk );
}
BOOLEAN ArmBomb( OBJECTTYPE * pObj, INT8 bSetting )
{
BOOLEAN fRemote = FALSE;
BOOLEAN fPressure = FALSE;
BOOLEAN fTimed = FALSE;
BOOLEAN fSwitch = FALSE;
if (pObj->usItem == ACTION_ITEM)
{
switch( (*pObj)[0]->data.misc.bActionValue )
{
case ACTION_ITEM_SMALL_PIT:
case ACTION_ITEM_LARGE_PIT:
fPressure = TRUE;
break;
default:
fRemote = TRUE;
break;
}
}
else if ( IsDetonatorAttached( pObj ) )
{
fTimed = TRUE;
}
else if ( (IsRemoteDetonatorAttached( pObj ) ) || (pObj->usItem == ACTION_ITEM) )
{
fRemote = TRUE;
}
else if ( Item[pObj->usItem].mine || pObj->usItem == TRIP_FLARE || pObj->usItem == TRIP_KLAXON || pObj->usItem == ACTION_ITEM )
{
fPressure = TRUE;
}
else if ( pObj->usItem == SWITCH )
{
// this makes a remote detonator into a pressure-sensitive trigger
if ( bSetting == PANIC_FREQUENCY )
{
// panic trigger is only activated by expending APs, not by
// stepping on it... so don't define a detonator type
fSwitch = TRUE;
}
else
{
fPressure = TRUE;
}
}
else
{
// no sorta bomb at all!
return( FALSE );
}
if (fRemote)
{
(*pObj)[0]->data.misc.bDetonatorType = BOMB_REMOTE;
(*pObj)[0]->data.misc.bFrequency = bSetting;
}
else if (fPressure)
{
(*pObj)[0]->data.misc.bDetonatorType = BOMB_PRESSURE;
(*pObj)[0]->data.misc.bFrequency = 0;
}
else if (fTimed)
{
(*pObj)[0]->data.misc.bDetonatorType = BOMB_TIMED;
// In realtime the player could choose to put down a bomb right before a turn expires, SO
// add 1 to the setting in RT
(*pObj)[0]->data.misc.bDelay = bSetting;
if ( !(gTacticalStatus.uiFlags & TURNBASED && gTacticalStatus.uiFlags & INCOMBAT) )
{
(*pObj)[0]->data.misc.bDelay++;
}
}
else if (fSwitch)
{
(*pObj)[0]->data.misc.bDetonatorType = BOMB_SWITCH;
(*pObj)[0]->data.misc.bFrequency = bSetting;
}
else
{
return( FALSE );
}
(*pObj).fFlags |= OBJECT_ARMED_BOMB;
(*pObj)[0]->data.misc.usBombItem = pObj->usItem;
return( TRUE );
}
BOOLEAN OBJECTTYPE::RemoveAttachment( OBJECTTYPE* pAttachment, OBJECTTYPE * pNewObj, UINT8 subObject, SOLDIERTYPE * pSoldier, BOOLEAN fForceInseperable, BOOLEAN fRemoveProhibited )
{
BOOLEAN objDeleted = FALSE;
std::vector<UINT16> usAttachmentSlotIndexVector;
std::vector<UINT16> usRemAttachmentSlotIndexVector;
UINT16 oldMagSize = 0;
if ( pAttachment->exists() == false || this->exists() == false)
{
return( FALSE );
}
//Sometimes we have to force inseparable items off, sadly.
if ( Item[ pAttachment->usItem ].inseparable && !fForceInseperable )
{
return( FALSE );
}
//CHRISL: This is so we can try to determine if the removed attachment altered our mag size.
if(Item[this->usItem].usItemClass == IC_GUN)
oldMagSize = GetMagSize(this);
//CHRISL: I know this FOR loop is basically redundant to what the remove() function already does, but
// this setup includes a failsafe. Now we'll only copy the attachment to our cursor (pNewObj) if
// iter and pAttachment are the same. This should stop attachment duplication though it doesn't resolve
// the initial cause of the attachment duplication issue.
//First look for attachment with the exact same memory adress.
//This is so that you can click to remove an attachment and it will take off THAT attachment and not the first one that just "looks" like it.
for (std::list<OBJECTTYPE>::iterator iter = (*this)[subObject]->attachments.begin();
iter != (*this)[subObject]->attachments.end(); ++iter){
//Compare the adress
if(&(*iter) == pAttachment)
{
if(pNewObj != NULL)
{
*pNewObj = *pAttachment;
}
iter = (*this)[subObject]->RemoveAttachmentAtIter(iter);
objDeleted = TRUE;
break;
}
}
//It is possible that the previous loop did not find the EXACT attachment we wanted to delete, look if there is one that is at least equal in data.
if(!objDeleted){
for (std::list<OBJECTTYPE>::iterator iter = (*this)[subObject]->attachments.begin();
iter != (*this)[subObject]->attachments.end(); ++iter){
//This compares the internal data of the objects.
if(*iter == *pAttachment)
{
if(pNewObj != NULL)
{
*pNewObj = *pAttachment;
}
iter = (*this)[subObject]->RemoveAttachmentAtIter(iter);
objDeleted = TRUE;
break;
}
}
}
if(!objDeleted)
return( FALSE );
//After removing an attachment, the ammo capacity might have changed.
if ( Item[this->usItem].usItemClass == IC_GUN && (*this)[subObject]->data.gun.usGunAmmoItem != NONE && (*this)[subObject]->data.gun.ubGunShotsLeft > 0 && oldMagSize != GetMagSize(this, subObject) )
{
if ( (*this)[subObject]->data.gun.ubGunShotsLeft > GetMagSize(this, subObject) )
{ //Too many rounds, eject ammo
EjectAmmoAndPlace(pSoldier, this, subObject);
}
//CHRISL: We should update the usGunAmmoItem if we've changed the ammo capacity
if((*this)[subObject]->data.gun.usGunAmmoItem != NONE){
UINT16 usNewAmmoItem;
usNewAmmoItem = FindReplacementMagazine(Weapon[this->usItem].ubCalibre ,GetMagSize(this, subObject),Magazine[Item[(*this)[subObject]->data.gun.usGunAmmoItem].ubClassIndex].ubAmmoType);
(*this)[subObject]->data.gun.usGunAmmoItem = usNewAmmoItem;
}
}
if(Item[this->usItem].usItemClass == IC_GUN && oldMagSize != GetMagSize(this, subObject)){
fInterfacePanelDirty = DIRTYLEVEL2;
RenderBulletIcon(this, subObject);
}
//CHRISL: We need to know if the removed attachment could have altered the base items potential attachments
BOOLEAN removeAttachments = TRUE, cleanAttachments = FALSE;
INT8 loopCount = 0;
while(removeAttachments){
usRemAttachmentSlotIndexVector = GetItemSlots(pNewObj);
if(usRemAttachmentSlotIndexVector.empty()){
removeAttachments = FALSE;
} else {
cleanAttachments = TRUE;
usAttachmentSlotIndexVector = GetItemSlots(this, subObject);
for(attachmentList::iterator iter = (*this)[subObject]->attachments.begin(); iter != (*this)[subObject]->attachments.end(); ++iter){
removeAttachments = FALSE;
if(iter->exists()){
if(!ValidItemAttachment(this, iter->usItem, FALSE, FALSE, subObject, usAttachmentSlotIndexVector)){ //attachment is no longer valid
removeAttachments = TRUE;
OBJECTTYPE remObj;
remObj = *iter;
if(ValidItemAttachment(pNewObj, iter->usItem, FALSE, FALSE, 0, usRemAttachmentSlotIndexVector)){
(*pNewObj)[0]->attachments.push_back((*iter));
iter = (*this)[subObject]->RemoveAttachmentAtIter(iter);
continue;
}
if(loopCount > 5){ //try moving attachments to the removed attachment 5 times before we drop anything
if ( pSoldier && AutoPlaceObject( pSoldier, &remObj, FALSE ) )
{
iter = (*this)[subObject]->RemoveAttachmentAtIter(iter);
} else { // put it on the ground
INT8 pathing = (pSoldier?pSoldier->pathing.bLevel:0);
INT32 sGridNo = (pSoldier?pSoldier->sGridNo:0);
if( AutoPlaceObjectToWorld(pSoldier, &remObj) )
iter = (*this)[subObject]->RemoveAttachmentAtIter(iter);
/*if(guiCurrentItemDescriptionScreen == MAP_SCREEN && fShowMapInventoryPool){
if(AutoPlaceObjectInInventoryStash(&remObj, sGridNo)){
iter = (*this)[subObject]->RemoveAttachmentAtIter(iter);
}
} else {
AddItemToPool( sGridNo, &remObj, 1, pathing, WORLD_ITEM_REACHABLE, 0 );
iter = (*this)[subObject]->RemoveAttachmentAtIter(iter);
}*/
}
}
}
}
}
}
loopCount++;
}
if(cleanAttachments){
RemoveProhibitedAttachments(pSoldier, pNewObj, pNewObj->usItem);
RemoveProhibitedAttachments(pSoldier, this, this->usItem);
}
if (pNewObj->exists() && Item[pNewObj->usItem].grenadelauncher )//UNDER_GLAUNCHER)
{
// look for any grenade; if it exists, we must make it an
// attachment of the grenade launcher
OBJECTTYPE* pGrenade = FindAttachmentByClass( this, IC_GRENADE );
if (pGrenade->exists())
{
pNewObj->AttachObject(NULL, pGrenade, FALSE, 0, -1, 0);
//ADB ubWeight has been removed, see comments in OBJECTTYPE
//pNewObj->ubWeight = CalculateObjectWeight( pNewObj );
this->RemoveAttachment(pGrenade, NULL, 0, NULL, 1, 0);
}
}
//Removing an attachment can alter slots, check them.
if(UsingNewAttachmentSystem()==true && fRemoveProhibited){
RemoveProhibitedAttachments(pSoldier, this, this->usItem);
}
//ADB ubWeight has been removed, see comments in OBJECTTYPE
//this->ubWeight = CalculateObjectWeight( this );
return( TRUE );
}
void SetNewItem( SOLDIERTYPE *pSoldier, UINT8 ubInvPos, BOOLEAN fNewItem )
{
if( fNewItem )
{
pSoldier->inv.bNewItemCount[ ubInvPos ] = -1;
pSoldier->inv.bNewItemCycleCount[ ubInvPos ] = NEW_ITEM_CYCLE_COUNT;
pSoldier->flags.fCheckForNewlyAddedItems = TRUE;
}
}
BOOLEAN PlaceObjectInSoldierProfile( UINT8 ubProfile, OBJECTTYPE *pObject )
{
INT8 bLoop;
SOLDIERTYPE *pSoldier;
UINT16 usItem;
INT16 bStatus;
BOOLEAN fReturnVal = FALSE;
usItem = pObject->usItem;
Assert(pObject->ubNumberOfObjects == 1);
bStatus = (*pObject)[0]->data.objectStatus;
pSoldier = FindSoldierByProfileID( ubProfile, FALSE );
if ( Item[ usItem ].usItemClass == IC_MONEY && gMercProfiles[ ubProfile ].uiMoney > 0 )
{
gMercProfiles[ ubProfile ].uiMoney += (*pObject)[0]->data.money.uiMoneyAmount;
SetMoneyInSoldierProfile( ubProfile, gMercProfiles[ ubProfile ].uiMoney );
return( TRUE );
}
// CHRISL:
for (bLoop = BIGPOCKSTART; bLoop < NUM_INV_SLOTS; bLoop++)
{
if ( gMercProfiles[ ubProfile ].bInvNumber[ bLoop ] == 0 && (pSoldier == NULL || pSoldier->inv[ bLoop ].exists() == false ) )
{
// CJC: Deal with money by putting money into # stored in profile
if ( Item[ usItem ].usItemClass == IC_MONEY )
{
gMercProfiles[ ubProfile ].uiMoney += (*pObject)[0]->data.money.uiMoneyAmount;
// change any gold/silver to money
usItem = MONEY;
}
else
{
gMercProfiles[ ubProfile ].inv[ bLoop ] = usItem;
gMercProfiles[ ubProfile ].bInvStatus[ bLoop ] = bStatus;
gMercProfiles[ ubProfile ].bInvNumber[ bLoop ] = pObject->ubNumberOfObjects;
}
fReturnVal = TRUE;
break;
}
}
//uiMoneyAmount
if ( fReturnVal )
{
// ATE: Manage soldier pointer as well....
//pSoldier = FindSoldierByProfileID( ubProfile, FALSE );
// Do we have a valid profile?
if ( pSoldier != NULL )
{
// OK, place in soldier...
if ( usItem == MONEY )
{
CreateMoney( gMercProfiles[ ubProfile ].uiMoney, &(pSoldier->inv[ bLoop ] ) );
}
else
{
if ( pSoldier->ubProfile == MADLAB )
{
// remove ammo and drop
pSoldier->pTempObject = new OBJECTTYPE;
EmptyWeaponMagazine( pObject, pSoldier->pTempObject );
AddItemToPool( pSoldier->sGridNo, pSoldier->pTempObject, 1, 0, 0, 0 );
pSoldier->pTempObject = NULL;
// remove attachments and drop them
for (attachmentList::iterator iter = (*pObject)[0]->attachments.begin(); iter != (*pObject)[0]->attachments.end();) {
//CHRISL: Because MADLAB needs to remove all attachments, even inseparable ones, we need to temporarily
// make all attachments removable.
if(!iter->exists()){
++iter;
continue;
}
BOOLEAN old_inseparable = FALSE;
UINT32 old_item = iter->usItem;
// drop it in Madlab's tile
AddItemToPool( pSoldier->sGridNo, &(*iter), 1, 0, 0, 0 );
old_inseparable = Item[old_item].inseparable;
Item[old_item].inseparable = FALSE;
pObject->RemoveAttachment(&(*iter));
Item[old_item].inseparable = old_inseparable;
if ((*pObject)[0]->AttachmentListSize() == 0) {
break;
}
else{
iter = (*pObject)[0]->attachments.begin();
}
}
}
CreateItem( usItem, bStatus, &(pSoldier->inv[ bLoop ] ) );
}
}
}
return( fReturnVal );
}
BOOLEAN RemoveObjectFromSoldierProfile( UINT8 ubProfile, UINT16 usItem )
{
SOLDIERTYPE *pSoldier;
BOOLEAN fReturnVal = FALSE;
if ( usItem == NOTHING )
{
return( TRUE );
}
MERCPROFILESTRUCT* pProfile = &gMercProfiles[ ubProfile ];
for (unsigned int bLoop = 0; bLoop < pProfile->inv.size(); bLoop++)
{
if ( pProfile->inv[ bLoop ] == usItem )
{
pProfile->inv[ bLoop ] = NOTHING;
pProfile->bInvStatus[ bLoop ] = 0;
pProfile->bInvNumber[ bLoop ] = 0;
fReturnVal = TRUE;
break;
}
}
// ATE: Manage soldier pointer as well....
pSoldier = FindSoldierByProfileID( ubProfile, FALSE );
// Do we have a valid profile?
if ( pSoldier != NULL )
{
// Remove item...
RemoveInvObject( pSoldier, usItem );
}
return( fReturnVal );
}
void SetMoneyInSoldierProfile( UINT8 ubProfile, UINT32 uiMoney )
{
BOOLEAN fRet;
// remove all money from soldier
do
{
fRet = RemoveObjectFromSoldierProfile( ubProfile, MONEY );
}
while ( fRet == TRUE );
gMercProfiles[ ubProfile ].uiMoney = 0;
if (uiMoney > 0)
{
// now add the amount specified
CreateMoney( uiMoney, &gTempObject );
PlaceObjectInSoldierProfile( ubProfile, &gTempObject );
}
}
INT8 FindObjectInSoldierProfile( UINT8 ubProfile, UINT16 usItem )
{
MERCPROFILESTRUCT* pProfile = &gMercProfiles[ ubProfile ];
for (unsigned int bLoop = 0; bLoop < pProfile->inv.size(); bLoop++)
{
if ( pProfile->bInvNumber[ bLoop ] > 0 )
{
if ( pProfile->inv[ bLoop ] == usItem )
{
return( bLoop );
}
}
}
return( NO_SLOT );
}
BOOLEAN ObjectExistsInSoldierProfile( UINT8 ubProfile, UINT16 usItem )
{
INT8 bSlot;
bSlot = FindObjectInSoldierProfile( ubProfile, usItem );
return( bSlot != NO_SLOT );
}
void RemoveInvObject( SOLDIERTYPE *pSoldier, UINT16 usItem )
{
INT8 bInvPos;
// find object
bInvPos = FindObj( pSoldier, usItem );
if (bInvPos != NO_SLOT)
{
// Erase!
DeleteObj(&pSoldier->inv[ bInvPos ]);
//Dirty!
DirtyMercPanelInterface( pSoldier, DIRTYLEVEL2 );
}
}
INT8 CheckItemForDamage( UINT16 usItem, INT32 iMaxDamage )
{
INT8 bDamage = 0;
// if the item is protective armour, reduce the amount of damage
// by its armour value
if (Item[usItem].usItemClass == IC_ARMOUR)
{
iMaxDamage -= (iMaxDamage * Armour[Item[usItem].ubClassIndex].ubProtection) / 100;
}
// metal items are tough and will be damaged less
// if (Item[usItem].fFlags & ITEM_METAL)
if (Item[usItem].metal )
{
iMaxDamage /= 2;
}
else if ( usItem == BLOODCAT_PELT )
{
iMaxDamage *= 2;
}
if (iMaxDamage > 0)
{
bDamage = (INT8) PreRandom( iMaxDamage );
}
return( bDamage );
}
BOOLEAN CheckForChainReaction( UINT16 usItem, INT16 bStatus, INT16 bDamage, BOOLEAN fOnGround )
{
INT32 iChance;
iChance = Explosive[Item[usItem].ubClassIndex].ubVolatility;
if (iChance > 0)
{
// Scale the base chance by the damage caused to the item
// (bigger the shock, bigger chance) and the condition of
// the item after being hit!
if (fOnGround)
{
// improve chance to make it practical to blow up explosives on the ground
iChance = 50 + (iChance - 1) * 10;
}
// SANDRO - experimental - increased chance to chain reactions of carried explosives a bit
else
{
iChance = 3 + (iChance - 1) * 3;
}
iChance = iChance * ( 100 + ( (100 - bStatus) + bDamage ) / 2 ) / 100;
if ((INT32) PreRandom( 100 ) < iChance)
{
return( TRUE );
}
}
return( FALSE );
}
BOOLEAN DamageItem( OBJECTTYPE * pObject, INT32 iDamage, BOOLEAN fOnGround )
{
INT8 bLoop;
INT16 bDamage;
if ( (Item[pObject->usItem].damageable || Item[ pObject->usItem ].usItemClass == IC_AMMO) && pObject->exists() == true)
{
for (bLoop = 0; bLoop < pObject->ubNumberOfObjects; bLoop++)
{
bool removed = false;
// if the status of the item is negative then it's trapped/jammed;
// leave it alone
if (pObject->exists() == true && (*pObject)[bLoop]->data.objectStatus > 0)
{
bDamage = CheckItemForDamage( pObject->usItem, iDamage );
switch( pObject->usItem )
{
case JAR_CREATURE_BLOOD:
case JAR:
case JAR_HUMAN_BLOOD:
case JAR_ELIXIR:
if ( PreRandom( bDamage ) > 5 )
{
// smash!
bDamage = (*pObject)[bLoop]->data.objectStatus;
}
break;
default:
break;
}
if ( Item[ pObject->usItem ].usItemClass == IC_AMMO )
{
if ( PreRandom( 100 ) < (UINT32) bDamage )
{
// destroy clip completely
(*pObject)[bLoop]->data.objectStatus = 1;
}
}
else
{
(*pObject)[bLoop]->data.objectStatus -= bDamage;
if ((*pObject)[bLoop]->data.objectStatus < 1)
{
(*pObject)[bLoop]->data.objectStatus = 1;
}
}
// I don't think we increase viewrange based on items any more
// FUN STUFF! Check for explosives going off as a result!
if (Item[pObject->usItem].usItemClass & IC_EXPLOSV)
{
if (CheckForChainReaction( pObject->usItem, (*pObject)[bLoop]->data.objectStatus, bDamage, fOnGround ))
{
return( TRUE );
}
}
// remove item from index AFTER checking explosions because need item data for explosion!
if ( (*pObject)[bLoop]->data.objectStatus == 1 )
{
if ( pObject->ubNumberOfObjects > 1 )
{
removed = true;
pObject->RemoveObjectAtIndex( bLoop );
// since an item was just removed, the items above the current were all shifted down one;
// to process them properly, we have to back up 1 in the counter
--bLoop;
}
}
}
if (removed == false) {
for (attachmentList::iterator iter = (*pObject)[bLoop]->attachments.begin(); iter != (*pObject)[bLoop]->attachments.end();) {
DamageItem(&(*iter), iDamage, fOnGround);
//could have removed the object at iter
if (iter->exists() == true) {
++iter;
}
else {
iter = (*pObject)[bLoop]->RemoveAttachmentAtIter(iter);
if(UsingNewAttachmentSystem()==true)
++iter;
}
}
}
}
}
return( FALSE );
}
void CheckEquipmentForDamage( SOLDIERTYPE *pSoldier, INT32 iDamage )
{
INT8 bSlot;
BOOLEAN fBlowsUp;
UINT8 ubNumberOfObjects;
if ( TANK( pSoldier ) )
{
return;
}
for (bSlot = 0; bSlot < (INT8) pSoldier->inv.size(); bSlot++)
{
if (pSoldier->inv[bSlot].exists() == false) {
continue;
}
ubNumberOfObjects = pSoldier->inv[bSlot].ubNumberOfObjects;
fBlowsUp = DamageItem( &(pSoldier->inv[bSlot]), iDamage, FALSE );
if (fBlowsUp)
{
// blow it up!
if ( gTacticalStatus.ubAttackBusyCount )
{
IgniteExplosion( pSoldier->ubAttackerID, CenterX( pSoldier->sGridNo ), CenterY( pSoldier->sGridNo ), 0, pSoldier->sGridNo, pSoldier->inv[ bSlot ].usItem, pSoldier->pathing.bLevel );
}
else
{
IgniteExplosion( pSoldier->ubID, CenterX( pSoldier->sGridNo ), CenterY( pSoldier->sGridNo ), 0, pSoldier->sGridNo, pSoldier->inv[ bSlot ].usItem, pSoldier->pathing.bLevel );
}
//ADB when something in a stack blows up the whole stack goes, so no need to worry about number of items
// Remove item!
DeleteObj( &(pSoldier->inv[ bSlot ]) );
DirtyMercPanelInterface( pSoldier, DIRTYLEVEL2 );
}
else if ( ubNumberOfObjects != pSoldier->inv[bSlot].ubNumberOfObjects )
{
DirtyMercPanelInterface( pSoldier, DIRTYLEVEL2 );
}
}
}
void CheckEquipmentForFragileItemDamage( SOLDIERTYPE *pSoldier, INT32 iDamage )
{
// glass jars etc can be damaged by falling over
INT8 bSlot;
UINT8 ubNumberOfObjects;
BOOLEAN fPlayedGlassBreak = FALSE;
for (bSlot = 0; bSlot < (INT8) pSoldier->inv.size(); bSlot++)
{
if (pSoldier->inv[bSlot].exists() == false) {
continue;
}
switch( pSoldier->inv[bSlot].usItem )
{
case JAR_CREATURE_BLOOD:
case JAR:
case JAR_HUMAN_BLOOD:
case JAR_ELIXIR:
ubNumberOfObjects = pSoldier->inv[bSlot].ubNumberOfObjects;
DamageItem( &(pSoldier->inv[bSlot]), iDamage, FALSE );
if ( !fPlayedGlassBreak && (ubNumberOfObjects != pSoldier->inv[bSlot].ubNumberOfObjects) )
{
PlayJA2Sample( GLASS_CRACK, RATE_11025, SoundVolume( MIDVOLUME, pSoldier->sGridNo ), 1, SoundDir( pSoldier->sGridNo ) );
fPlayedGlassBreak = TRUE;
// only dirty once
DirtyMercPanelInterface( pSoldier, DIRTYLEVEL2 );
}
break;
default:
break;
}
}
}
BOOLEAN DamageItemOnGround( OBJECTTYPE * pObject, INT32 sGridNo, INT8 bLevel, INT32 iDamage, UINT8 ubOwner )
{
#ifdef JA2BETAVERSION
CHAR tmpMPDbgString[512];
sprintf(tmpMPDbgString,"DamageItemOnGround ( usItem : %i , sGridNo : %i , bLevel : %i , iDamage : %i , ubOwner : %i )\n",pObject->usItem, sGridNo , bLevel , iDamage , ubOwner );
MPDebugMsg(tmpMPDbgString);
#endif
BOOLEAN fBlowsUp;
fBlowsUp = DamageItem( pObject, iDamage, TRUE );
if ( fBlowsUp )
{
// OK, Ignite this explosion!
IgniteExplosion( ubOwner, CenterX( sGridNo ), CenterY( sGridNo ), 0, sGridNo, pObject->usItem, bLevel );
// SANDRO - merc records
if ( (pObject->fFlags & OBJECT_ARMED_BOMB) && ((*pObject)[0]->data.misc.ubBombOwner > 1) )
{
if ( MercPtrs[ ((*pObject)[0]->data.misc.ubBombOwner - 2) ]->ubProfile != NO_PROFILE && MercPtrs[ ((*pObject)[0]->data.misc.ubBombOwner - 2) ]->bTeam == gbPlayerNum )
gMercProfiles[ MercPtrs[ ((*pObject)[0]->data.misc.ubBombOwner - 2) ]->ubProfile ].records.usExpDetonated++;
}
// Remove item!
return( TRUE );
}
else if ( pObject->exists() == true && (pObject->ubNumberOfObjects < 2) && ((*pObject)[0]->data.objectStatus < USABLE) )
{
return( TRUE );
}
else
{
return( FALSE );
}
}
// is the item a medical kit/first aid kit item?
INT8 IsMedicalKitItem( OBJECTTYPE *pObject )
{
// check item id against current medical kits
if ( Item[pObject->usItem].medicalkit && pObject->exists() == true)
return 1;
//switch( pObject->usItem )
//{
// case( MEDICKIT ):
// // medical bag, return 1
// return ( 1 );
// break;
//}
return( 0 );
}
void SwapHandItems( SOLDIERTYPE * pSoldier )
{
BOOLEAN fOk;
CHECKV( pSoldier );
if (pSoldier->inv[HANDPOS].exists() == false || pSoldier->inv[SECONDHANDPOS].exists() == false)
{
// whatever is in the second hand can be swapped to the main hand!
SwapObjs( pSoldier, HANDPOS, SECONDHANDPOS, TRUE );
DirtyMercPanelInterface( pSoldier, DIRTYLEVEL2 );
}
else
{
if (TwoHandedItem( pSoldier->inv[SECONDHANDPOS].usItem ) )
{
// must move the item in the main hand elsewhere in the inventory
fOk = AutoPlaceObject( pSoldier, &(pSoldier->inv[HANDPOS]), FALSE, HANDPOS );
if (!fOk)
{
return;
}
// the main hand is now empty so a swap is going to work...
}
SwapObjs( pSoldier, HANDPOS, SECONDHANDPOS, TRUE );
DirtyMercPanelInterface( pSoldier, DIRTYLEVEL2 );
}
}
void SwapOutHandItem( SOLDIERTYPE * pSoldier )
{
BOOLEAN fOk;
CHECKV( pSoldier );
// puts away the item in the main hand
if (pSoldier->inv[HANDPOS].exists() == true )
{
if (pSoldier->inv[SECONDHANDPOS].exists() == false)
{
// just swap the hand item to the second hand
SwapObjs( pSoldier, HANDPOS, SECONDHANDPOS, TRUE );
DirtyMercPanelInterface( pSoldier, DIRTYLEVEL2 );
return;
}
else
{
// try placing it somewhere else in our inventory
fOk = AutoPlaceObject( pSoldier, &(pSoldier->inv[HANDPOS]), FALSE );
if (fOk)
{
DirtyMercPanelInterface( pSoldier, DIRTYLEVEL2 );
}
// otherwise there's no room for the item anywhere!
}
}
}
void WaterDamage( SOLDIERTYPE *pSoldier )
{
// damage guy's equipment and camouflage due to water
INT8 bLoop, bDamage, bDieSize;
UINT32 uiRoll;
if ( pSoldier->MercInDeepWater( ) )
{
for ( bLoop = 0; bLoop < (INT8) pSoldier->inv.size(); bLoop++ )
{
if (pSoldier->inv[bLoop].exists() == false) {
continue;
}
// if there's an item here that can get water damaged...
// if (pSoldier->inv[ bLoop ].usItem && Item[pSoldier->inv[ bLoop ].usItem].fFlags & ITEM_WATER_DAMAGES)
if (pSoldier->inv[ bLoop ].usItem && Item[pSoldier->inv[ bLoop ].usItem].waterdamages )
{
// roll the 'ol 100-sided dice
uiRoll = PreRandom(100);
// 10% chance of getting damage!
if (uiRoll < 10)
{
// lose between 1 and 10 status points each time
bDamage = (INT8) (10 - uiRoll);
// but don't let anything drop lower than 1%
pSoldier->inv[bLoop][0]->data.objectStatus -= bDamage;
if (pSoldier->inv[bLoop][0]->data.objectStatus < 1)
{
pSoldier->inv[bLoop][0]->data.objectStatus = 1;
}
}
}
}
}
BOOLEAN camoWoreOff = FALSE;
/////////////////////////////////////////////////////////////////////////////////////
// ADDED BY SANDRO - Ranger trait makes camouflage reduction lesser
// I've messed this part a little to be more clean, the different camouflaged traits have been merged into one
if ( gGameOptions.fNewTraitSystem)
{
// reduce camouflage by 2% per tile of deep water
// and 1% for medium water
if ( pSoldier->bCamo > 0 )
{
if ( HAS_SKILL_TRAIT( pSoldier, RANGER_NT ) )
{
if ( pSoldier->MercInDeepWater( ) )
{
pSoldier->bCamo -= (Chance(__max(0, 100 - gSkillTraitValues.ubRACamoWornountSpeedReduction * NUM_SKILL_TRAITS( pSoldier, RANGER_NT ))) ? 1 : 0 );
pSoldier->bCamo -= (Chance(__max(0, 100 - gSkillTraitValues.ubRACamoWornountSpeedReduction * NUM_SKILL_TRAITS( pSoldier, RANGER_NT ))) ? 1 : 0 );
}
else
{
pSoldier->bCamo -= (Chance(__max(0, 100 - gSkillTraitValues.ubRACamoWornountSpeedReduction * NUM_SKILL_TRAITS( pSoldier, RANGER_NT ))) ? 1 : 0 );
}
}
else
{
if ( pSoldier->MercInDeepWater( ) )
pSoldier->bCamo = __max( 0, pSoldier->bCamo - 2 );
else
pSoldier->bCamo = __max( 0, pSoldier->bCamo - 1 );
}
if ( pSoldier->bCamo <= 0 )
{
pSoldier->bCamo = 0;
camoWoreOff = TRUE;
}
}
if ( pSoldier->urbanCamo > 0 )
{
if ( HAS_SKILL_TRAIT( pSoldier, RANGER_NT ) )
{
if ( pSoldier->MercInDeepWater( ) )
{
pSoldier->urbanCamo -= (Chance(__max(0, 100 - gSkillTraitValues.ubRACamoWornountSpeedReduction * NUM_SKILL_TRAITS( pSoldier, RANGER_NT ))) ? 1 : 0 );
pSoldier->urbanCamo -= (Chance(__max(0, 100 - gSkillTraitValues.ubRACamoWornountSpeedReduction * NUM_SKILL_TRAITS( pSoldier, RANGER_NT ))) ? 1 : 0 );
}
else
{
pSoldier->urbanCamo -= (Chance(__max(0, 100 - gSkillTraitValues.ubRACamoWornountSpeedReduction * NUM_SKILL_TRAITS( pSoldier, RANGER_NT ))) ? 1 : 0 );
}
}
else
{
if ( pSoldier->MercInDeepWater( ) )
pSoldier->urbanCamo = __max( 0, pSoldier->urbanCamo - 2);
else
pSoldier->urbanCamo = __max( 0, pSoldier->urbanCamo - 1);
}
if ( pSoldier->urbanCamo <= 0 )
{
pSoldier->urbanCamo = 0;
camoWoreOff = TRUE;
}
}
if ( pSoldier->desertCamo > 0 )
{
if ( HAS_SKILL_TRAIT( pSoldier, RANGER_NT ) )
{
if ( pSoldier->MercInDeepWater( ) )
{
pSoldier->desertCamo -= (Chance(__max(0, 100 - gSkillTraitValues.ubRACamoWornountSpeedReduction * NUM_SKILL_TRAITS( pSoldier, RANGER_NT ))) ? 1 : 0 );
pSoldier->desertCamo -= (Chance(__max(0, 100 - gSkillTraitValues.ubRACamoWornountSpeedReduction * NUM_SKILL_TRAITS( pSoldier, RANGER_NT ))) ? 1 : 0 );
}
else
{
pSoldier->desertCamo -= (Chance(__max(0, 100 - gSkillTraitValues.ubRACamoWornountSpeedReduction * NUM_SKILL_TRAITS( pSoldier, RANGER_NT ))) ? 1 : 0 );
}
}
else
{
if ( pSoldier->MercInDeepWater( ) )
pSoldier->desertCamo = __max( 0, pSoldier->desertCamo - 2);
else
pSoldier->desertCamo = __max( 0, pSoldier->desertCamo - 1);
}
if ( pSoldier->desertCamo <= 0 )
{
pSoldier->desertCamo = 0;
camoWoreOff = TRUE;
}
}
if ( pSoldier->snowCamo > 0 )
{
if ( HAS_SKILL_TRAIT( pSoldier, RANGER_NT ) )
{
if ( pSoldier->MercInDeepWater( ) )
{
pSoldier->snowCamo -= (Chance(__max(0, 100 - gSkillTraitValues.ubRACamoWornountSpeedReduction * NUM_SKILL_TRAITS( pSoldier, RANGER_NT ))) ? 1 : 0 );
pSoldier->snowCamo -= (Chance(__max(0, 100 - gSkillTraitValues.ubRACamoWornountSpeedReduction * NUM_SKILL_TRAITS( pSoldier, RANGER_NT ))) ? 1 : 0 );
}
else
{
pSoldier->snowCamo -= (Chance(__max(0, 100 - gSkillTraitValues.ubRACamoWornountSpeedReduction * NUM_SKILL_TRAITS( pSoldier, RANGER_NT ))) ? 1 : 0 );
}
}
else
{
if ( pSoldier->MercInDeepWater( ) )
pSoldier->snowCamo = __max( 0, pSoldier->snowCamo - 2);
else
pSoldier->snowCamo = __max( 0, pSoldier->snowCamo - 1);
}
if ( pSoldier->snowCamo <= 0 )
{
pSoldier->snowCamo = 0;
camoWoreOff = TRUE;
}
}
}
else if ( !HAS_SKILL_TRAIT( pSoldier, CAMOUFLAGED_OT ) ) // Old Camouflaged trait
{
// reduce camouflage by 2% per tile of deep water
// and 1% for medium water
if ( pSoldier->bCamo > 0 )
{
if ( pSoldier->MercInDeepWater( ) )
pSoldier->bCamo = __max( 0, pSoldier->bCamo - 2 );
else
pSoldier->bCamo = __max( 0, pSoldier->bCamo - 1 );
if ( (pSoldier->bCamo)== 0)
camoWoreOff = TRUE;
}
if ( pSoldier->urbanCamo > 0 )
{
if ( pSoldier->MercInDeepWater( ) )
pSoldier->urbanCamo = __max( 0, pSoldier->urbanCamo - 2);
else
pSoldier->urbanCamo = __max( 0, pSoldier->urbanCamo - 1);
if ( (pSoldier->urbanCamo)== 0)
camoWoreOff = TRUE;
}
if ( pSoldier->desertCamo > 0 )
{
if ( pSoldier->MercInDeepWater( ) )
pSoldier->desertCamo = __max( 0, pSoldier->desertCamo - 2);
else
pSoldier->desertCamo = __max( 0, pSoldier->desertCamo - 1);
if ( (pSoldier->desertCamo)== 0)
camoWoreOff = TRUE;
}
if ( pSoldier->snowCamo > 0 )
{
if ( pSoldier->MercInDeepWater( ) )
pSoldier->snowCamo = __max( 0, pSoldier->snowCamo - 2);
else
pSoldier->snowCamo = __max( 0, pSoldier->snowCamo - 1);
if ( (pSoldier->snowCamo)== 0)
camoWoreOff = TRUE;
}
}
/////////////////////////////////////////////////////////////////////////////////////
if ( camoWoreOff )
{
// Reload palettes....
if ( pSoldier->bInSector )
{
pSoldier->CreateSoldierPalettes( );
}
// ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_INTERFACE, Message[STR_CAMMO_WASHED_OFF], pSoldier->name );
if ( pSoldier->bCamo <= 0 )
{
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_INTERFACE, Message[STR_JUNGLE_WASHED_OFF], pSoldier->name );
}
else if ( pSoldier->urbanCamo <= 0 )
{
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_INTERFACE, Message[STR_URBAN_WASHED_OFF], pSoldier->name );
}
else if ( pSoldier->snowCamo <= 0 )
{
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_INTERFACE, Message[STR_SNOW_WASHED_OFF], pSoldier->name );
}
else if ( pSoldier->desertCamo <= 0 )
{
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_INTERFACE, Message[STR_DESERT_WASHED_OFF], pSoldier->name );
}
}
if ( pSoldier->bTeam == gbPlayerNum && pSoldier->aiData.bMonsterSmell > 0 )
{
if ( pSoldier->MercInDeepWater( ) )
{
bDieSize = 10;
}
else
{
bDieSize = 20;
}
if ( Random( bDieSize ) == 0 )
{
pSoldier->aiData.bMonsterSmell--;
}
}
DirtyMercPanelInterface( pSoldier, DIRTYLEVEL2 );
}
BOOLEAN ApplyCammo( SOLDIERTYPE * pSoldier, OBJECTTYPE * pObj, BOOLEAN *pfGoodAPs )
{
// Added - SANDRO
INT8 bPointsToUse;
UINT16 usTotalKitPoints;
UINT16 iRemainingCamoAfterRemoving;
(*pfGoodAPs) = TRUE;
if (pObj->exists() == false)
return( FALSE );
//////////////////////////////////////////////////////////////////////////////
// added possibility to remove all camo by using a rag on self - SANDRO
if (pObj->usItem == 1022 && gGameExternalOptions.fCamoRemoving)
{
if (!EnoughPoints( pSoldier, (APBPConstants[AP_CAMOFLAGE]/2), 0, TRUE ) )
{
(*pfGoodAPs) = FALSE;
return( TRUE );
}
// 100 should be enough. The third value "0" means we will remove all types of camo
ReduceCamoFromSoldier( pSoldier, 100, 0 );
// damage the rag :) - actually you would need to flag it damagable in the items.XML
DamageItem( pObj, 22, FALSE );
DeductPoints( pSoldier, (APBPConstants[AP_CAMOFLAGE] / 2), 0 );
// Reload palettes....
if ( pSoldier->bInSector )
{
pSoldier->CreateSoldierPalettes( );
}
return( TRUE );
}
else if ( !Item[pObj->usItem].camouflagekit )
{
return( FALSE );
}
//////////////////////////////////////////////////////////////////////////////
if (!EnoughPoints( pSoldier, APBPConstants[AP_CAMOFLAGE], 0, TRUE ) )
{
(*pfGoodAPs) = FALSE;
return( TRUE );
}
usTotalKitPoints = TotalPoints( pObj );
if (usTotalKitPoints == 0)
{
// HUH???
return( FALSE );
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// SANDRO - Added a feature to determine which type of camo we use //
// and procedure able to reduce different type of camo //
// ******************************************************************************************** //
if (gGameExternalOptions.fCamoRemoving)
{
int iJungleCamoTotal = pSoldier->bCamo + pSoldier->wornCamo;
int iUrbanCamoTotal = pSoldier->urbanCamo + pSoldier->wornUrbanCamo;
int iDesertCamoTotal = pSoldier->desertCamo + pSoldier->wornDesertCamo;
int iSnowCamoTotal = pSoldier->snowCamo + pSoldier->wornSnowCamo;
int totalCamo = iJungleCamoTotal + iUrbanCamoTotal + iDesertCamoTotal + iSnowCamoTotal;
// First, check if we have an item with major JUNGLE camobonus
if ( (Item[pObj->usItem].camobonus > Item[pObj->usItem].urbanCamobonus) &&
(Item[pObj->usItem].camobonus > Item[pObj->usItem].desertCamobonus) &&
(Item[pObj->usItem].camobonus > Item[pObj->usItem].snowCamobonus) )
{
if (iJungleCamoTotal >= 100)
return( FALSE );
// determine how much we can add
bPointsToUse = (100 - (iJungleCamoTotal) + 1 ) / 2;
bPointsToUse = __min( bPointsToUse, usTotalKitPoints );
// determine how much we will add
int iJungleCamoAdded = (int)(Item[pObj->usItem].camobonus * bPointsToUse * 2 / 100 );
// if we have already too much different camo on ourselves, reduce some or all
if ( (totalCamo + iJungleCamoAdded) > 100 )
{
// first, determine how much we actually want to remove
int iCamoToRemove = (totalCamo + iJungleCamoAdded) - 100;
// reduce camo.. IMPORTANT - third value is type of camo to skip (0=skip-none, 1=jungle, 2=urban, 3=desert,4=snow)
iRemainingCamoAfterRemoving = ReduceCamoFromSoldier( pSoldier, iCamoToRemove, 1 ); // "1" - we want to keep the JUNGLE camo
// if some camo haven't been reduced from us, the camo to add will be lessened by that value
if (iRemainingCamoAfterRemoving > 0)
iJungleCamoAdded = max(0, (iJungleCamoAdded - iRemainingCamoAfterRemoving));
if (iJungleCamoAdded <= 0) // if we have nothing to add now, return
return( FALSE );
else // otherwise apply the camo
{
pSoldier->bCamo = __min( 100, pSoldier->bCamo + iJungleCamoAdded );
}
}
else // everything's fine, apply!!
{
pSoldier->bCamo = __min( 100, pSoldier->bCamo + iJungleCamoAdded );
}
}
// Second, check if we have an item with major URBAN camobonus
else if ( (Item[pObj->usItem].urbanCamobonus > Item[pObj->usItem].camobonus) &&
(Item[pObj->usItem].urbanCamobonus > Item[pObj->usItem].desertCamobonus) &&
(Item[pObj->usItem].urbanCamobonus > Item[pObj->usItem].snowCamobonus) )
{
if (iUrbanCamoTotal >= 100)
return( FALSE );
// determine how much we can add
bPointsToUse = (100 - (iUrbanCamoTotal) + 1 ) / 2;
bPointsToUse = __min( bPointsToUse, usTotalKitPoints );
// determine how much we will add
int iUrbanCamoAdded = (int)(Item[pObj->usItem].urbanCamobonus * bPointsToUse * 2 / 100 );
// if we have already too much different camo on ourselves, reduce some or all
if ( (totalCamo + iUrbanCamoAdded) > 100 )
{
// first, determine how much we actually want to remove
int iCamoToRemove = (totalCamo + iUrbanCamoAdded) - 100;
// reduce camo.. IMPORTANT - third value is type of camo to skip (0=skip-none, 1=jungle, 2=urban, 3=desert,4=snow)
iRemainingCamoAfterRemoving = ReduceCamoFromSoldier( pSoldier, iCamoToRemove, 2 ); // "2" - we want to keep the URBAN camo
// if some camo haven't been reduced from us, the camo to add will be lessened by that value
if (iRemainingCamoAfterRemoving > 0)
iUrbanCamoAdded = max(0, (iUrbanCamoAdded - iRemainingCamoAfterRemoving));
if (iUrbanCamoAdded <= 0) // if we have nothing to add now, return
return( FALSE );
else // otherwise apply the camo
{
pSoldier->urbanCamo = __min( 100, pSoldier->urbanCamo + iUrbanCamoAdded );
}
}
else // everything's fine, apply!!
{
pSoldier->urbanCamo = __min( 100, pSoldier->urbanCamo + iUrbanCamoAdded );
}
}
// Third, check if we have an item with major DESERT camobonus
else if ( (Item[pObj->usItem].desertCamobonus > Item[pObj->usItem].camobonus) &&
(Item[pObj->usItem].desertCamobonus > Item[pObj->usItem].urbanCamobonus) &&
(Item[pObj->usItem].desertCamobonus > Item[pObj->usItem].snowCamobonus) )
{
if (iDesertCamoTotal >= 100)
return( FALSE );
// determine how much we can add
bPointsToUse = (100 - (iDesertCamoTotal) + 1 ) / 2;
bPointsToUse = __min( bPointsToUse, usTotalKitPoints );
// determine how much we will add
int iDesertCamoAdded = (int)(Item[pObj->usItem].desertCamobonus * bPointsToUse * 2 / 100 );
// if we have already too much different camo on ourselves, reduce some or all
if ( (totalCamo + iDesertCamoAdded) > 100 )
{
// first, determine how much we actually want to remove
int iCamoToRemove = (totalCamo + iDesertCamoAdded) - 100;
// reduce camo.. IMPORTANT - third value is type of camo to skip (0=skip-none, 1=jungle, 2=urban, 3=desert,4=snow)
iRemainingCamoAfterRemoving = ReduceCamoFromSoldier( pSoldier, iCamoToRemove, 3 ); // "3" - we want to keep the DESERT camo
// if some camo haven't been reduced from us, the camo to add will be lessened by that value
if (iRemainingCamoAfterRemoving > 0)
iDesertCamoAdded = max(0, (iDesertCamoAdded - iRemainingCamoAfterRemoving));
if (iDesertCamoAdded <= 0) // if we have nothing to add now, return
return( FALSE );
else // otherwise apply the camo
{
pSoldier->desertCamo = __min( 100, pSoldier->desertCamo + iDesertCamoAdded );
}
}
else // everything's fine, apply!!
{
pSoldier->desertCamo = __min( 100, pSoldier->desertCamo + iDesertCamoAdded );
}
}
// Fourth, check if we have an item with major SNOW camobonus
else if ( (Item[pObj->usItem].snowCamobonus > Item[pObj->usItem].camobonus) &&
(Item[pObj->usItem].snowCamobonus > Item[pObj->usItem].urbanCamobonus) &&
(Item[pObj->usItem].snowCamobonus > Item[pObj->usItem].desertCamobonus) )
{
if (iSnowCamoTotal >= 100)
return( FALSE );
// determine how much we can add
bPointsToUse = (100 - (iSnowCamoTotal) + 1 ) / 2;
bPointsToUse = __min( bPointsToUse, usTotalKitPoints );
// determine how much we will add
int iSnowCamoAdded = (int)(Item[pObj->usItem].snowCamobonus * bPointsToUse * 2 / 100 );
// if we have already too much different camo on ourselves, reduce some or all
if ( (totalCamo + iSnowCamoAdded) > 100 )
{
// first, determine how much we actually want to remove
int iCamoToRemove = (totalCamo + iSnowCamoAdded) - 100;
// reduce camo.. IMPORTANT - third value is type of camo to skip (0=skip-none, 1=jungle, 2=urban, 3=desert,4=snow)
iRemainingCamoAfterRemoving = ReduceCamoFromSoldier( pSoldier, iCamoToRemove, 4 ); // "4" - we want to keep the SNOW camo
// if some camo haven't been reduced from us, the camo to add will be lessened by that value
if (iRemainingCamoAfterRemoving > 0)
iSnowCamoAdded = max(0, (iSnowCamoAdded - iRemainingCamoAfterRemoving));
if (iSnowCamoAdded <= 0) // if we have nothing to add now, return
return( FALSE );
else // otherwise apply the camo
{
pSoldier->snowCamo = __min( 100, pSoldier->snowCamo + iSnowCamoAdded );
}
}
else // everything's fine, apply!!
{
pSoldier->snowCamo = __min( 100, pSoldier->snowCamo + iSnowCamoAdded );
}
}
else // the item has no major camo, return
return( FALSE );
// ****************************************************************************************** //
////////////////////////////////////////////////////////////////////////////////////////////////
}
else
{
//get total camo bonus for kit -- note that camo kits now require the camobonus tag to be set
//int itemCamo = Item[pObj->usItem].camobonus + Item[pObj->usItem].urbanCamobonus + Item[pObj->usItem].desertCamobonus + Item[pObj->usItem].snowCamobonus;
int totalCamo = pSoldier->bCamo + pSoldier->wornCamo + pSoldier->urbanCamo+pSoldier->wornUrbanCamo+pSoldier->desertCamo+pSoldier->wornDesertCamo+pSoldier->snowCamo+pSoldier->wornSnowCamo;
if ((totalCamo) >= 100)
{
// nothing more to add
return( FALSE );
}
// points are used up at a rate of 50% kit = 100% cammo on guy
// add 1 to round off
bPointsToUse = (100 - (totalCamo) + 1 ) / 2;
bPointsToUse = __min( bPointsToUse, usTotalKitPoints );
//figure out proportions of each to be applied, one item can theoretically have more than one camouflage type this way
int urban = (int)(Item[pObj->usItem].urbanCamobonus * bPointsToUse * 2 / 100 );
int jungle = (int)(Item[pObj->usItem].camobonus * bPointsToUse * 2 / 100 );
int desert = (int)(Item[pObj->usItem].desertCamobonus * bPointsToUse * 2 / 100 );
int snow = (int)(Item[pObj->usItem].snowCamobonus * bPointsToUse * 2 / 100 );
pSoldier->bCamo = __min( 100, pSoldier->bCamo + jungle );
pSoldier->urbanCamo = __min( 100, pSoldier->urbanCamo + urban );
pSoldier->desertCamo = __min( 100, pSoldier->desertCamo + desert );
pSoldier->snowCamo = __min( 100, pSoldier->snowCamo + snow );
}
UseKitPoints( pObj, bPointsToUse, pSoldier );
DeductPoints( pSoldier, APBPConstants[AP_CAMOFLAGE], 0 );
// Reload palettes....
if ( pSoldier->bInSector )
{
pSoldier->CreateSoldierPalettes( );
}
return( TRUE );
}
BOOLEAN ApplyCanteen( SOLDIERTYPE * pSoldier, OBJECTTYPE * pObj, BOOLEAN *pfGoodAPs )
{
INT16 sPointsToUse;
UINT16 usTotalKitPoints;
(*pfGoodAPs) = TRUE;
if (!Item[pObj->usItem].canteen || pObj->exists() == false)
{
return( FALSE );
}
usTotalKitPoints = TotalPoints( pObj );
if (usTotalKitPoints == 0)
{
// HUH???
return( FALSE );
}
if (!EnoughPoints( pSoldier, APBPConstants[AP_DRINK], 0, TRUE ) )
{
(*pfGoodAPs) = FALSE;
return( TRUE );
}
if ( pSoldier->bTeam == gbPlayerNum )
{
if ( gMercProfiles[ pSoldier->ubProfile ].bSex == MALE )
{
PlayJA2Sample( DRINK_CANTEEN_MALE, RATE_11025, MIDVOLUME, 1, MIDDLEPAN );
}
else
{
PlayJA2Sample( DRINK_CANTEEN_FEMALE, RATE_11025, MIDVOLUME, 1, MIDDLEPAN );
}
}
sPointsToUse = __min( 20, usTotalKitPoints );
// CJC Feb 9. Canteens don't seem effective enough, so doubled return from them
DeductPoints( pSoldier, APBPConstants[AP_DRINK], (INT16) (2 * sPointsToUse * -(100 - pSoldier->bBreath) ) );
UseKitPoints( pObj, sPointsToUse, pSoldier );
return( TRUE );
}
#define MAX_HUMAN_CREATURE_SMELL (NORMAL_HUMAN_SMELL_STRENGTH - 1)
BOOLEAN ApplyElixir( SOLDIERTYPE * pSoldier, OBJECTTYPE * pObj, BOOLEAN *pfGoodAPs )
{
INT16 sPointsToUse;
UINT16 usTotalKitPoints;
(*pfGoodAPs) = TRUE;
if (pObj->usItem != JAR_ELIXIR || pObj->exists() == false)
{
return( FALSE );
}
usTotalKitPoints = TotalPoints( pObj );
if (usTotalKitPoints == 0)
{
// HUH???
return( FALSE );
}
if (!EnoughPoints( pSoldier, APBPConstants[AP_CAMOFLAGE], 0, TRUE ) )
{
(*pfGoodAPs) = FALSE;
return( TRUE );
}
DeductPoints( pSoldier, APBPConstants[AP_CAMOFLAGE], 0 );
sPointsToUse = ( MAX_HUMAN_CREATURE_SMELL - pSoldier->aiData.bMonsterSmell ) * 2;
sPointsToUse = __min( sPointsToUse, usTotalKitPoints );
UseKitPoints( pObj, sPointsToUse, pSoldier );
pSoldier->aiData.bMonsterSmell += sPointsToUse / 2;
return( TRUE );
}
UINT32 ConvertProfileMoneyValueToObjectTypeMoneyValue( UINT8 ubStatus )
{
return( ubStatus * 50 );
}
UINT8 ConvertObjectTypeMoneyValueToProfileMoneyValue( UINT32 uiMoneyAmount )
{
return( (UINT8)( uiMoneyAmount / 50 ) );
}
BOOLEAN ItemIsCool( OBJECTTYPE * pObj )
{
if (pObj->exists() == false) {
return FALSE;
}
if ((*pObj)[0]->data.objectStatus < 60)
{
return( FALSE );
}
if ( Item[ pObj->usItem ].usItemClass & IC_WEAPON )
{
if ( Weapon[ pObj->usItem ].ubDeadliness >= 30 )
{
return( TRUE );
}
}
else if ( Item[ pObj->usItem ].usItemClass & IC_ARMOUR )
{
if ( Armour[ Item[ pObj->usItem ].ubClassIndex ].ubProtection >= 20 )
{
return( TRUE );
}
}
return( FALSE );
}
void ActivateXRayDevice( SOLDIERTYPE * pSoldier )
{
SOLDIERTYPE * pSoldier2;
UINT32 uiSlot;
if ( Item[pSoldier->inv[ HANDPOS ].usItem].needsbatteries && pSoldier->inv[ HANDPOS ].exists() == true)
{
// check for batteries
OBJECTTYPE* pBatteries = FindAttachedBatteries( &(pSoldier->inv[HANDPOS]) );
if ( pBatteries == 0 )
{
// doesn't work without batteries!
return;
}
// use up 8-12 percent of batteries
if ( Item[pBatteries->usItem].percentstatusdrainreduction > 0 )
(*pBatteries)[0]->data.objectStatus -= (INT8)( (8 + Random( 5 )) * (100 - Item[(*pBatteries)[0]->data.objectStatus].percentstatusdrainreduction)/100 );
else
(*pBatteries)[0]->data.objectStatus -= (INT8)( (8 + Random( 5 )) );
if ( (*pBatteries)[0]->data.objectStatus <= 0 )
{
// destroy batteries
pBatteries->RemoveObjectsFromStack(1);
if (pBatteries->exists() == false) {
pSoldier->inv[HANDPOS].RemoveAttachment(pBatteries);
}
}
}
// first, scan through all mercs and turn off xrayed flag for anyone
// previously xrayed by this guy
for ( uiSlot = 0; uiSlot < guiNumMercSlots; uiSlot++ )
{
pSoldier2 = MercSlots[ uiSlot ];
if ( pSoldier2 )
{
if ( (pSoldier2->ubMiscSoldierFlags & SOLDIER_MISC_XRAYED) && (pSoldier2->aiData.ubXRayedBy == pSoldier->ubID) )
{
pSoldier2->ubMiscSoldierFlags &= (~SOLDIER_MISC_XRAYED);
pSoldier2->aiData.ubXRayedBy = NOBODY;
}
}
}
// now turn on xray for anyone within range
for ( uiSlot = 0; uiSlot < guiNumMercSlots; uiSlot++ )
{
pSoldier2 = MercSlots[ uiSlot ];
if ( pSoldier2 )
{
if ( pSoldier2->bTeam != pSoldier->bTeam && PythSpacesAway( pSoldier->sGridNo, pSoldier2->sGridNo ) < XRAY_RANGE )
{
pSoldier2->ubMiscSoldierFlags |= SOLDIER_MISC_XRAYED;
pSoldier2->aiData.ubXRayedBy = pSoldier->ubID;
}
}
}
pSoldier->uiXRayActivatedTime = GetWorldTotalSeconds();
}
void TurnOffXRayEffects( SOLDIERTYPE * pSoldier )
{
SOLDIERTYPE * pSoldier2;
UINT32 uiSlot;
if ( !pSoldier->uiXRayActivatedTime )
{
return;
}
// scan through all mercs and turn off xrayed flag for anyone
// xrayed by this guy
for ( uiSlot = 0; uiSlot < guiNumMercSlots; uiSlot++ )
{
pSoldier2 = MercSlots[ uiSlot ];
if ( pSoldier2 )
{
if ( (pSoldier2->ubMiscSoldierFlags & SOLDIER_MISC_XRAYED) && (pSoldier2->aiData.ubXRayedBy == pSoldier->ubID) )
{
pSoldier2->ubMiscSoldierFlags &= (~SOLDIER_MISC_XRAYED);
pSoldier2->aiData.ubXRayedBy = NOBODY;
}
}
}
pSoldier->uiXRayActivatedTime = 0;
}
#ifdef JA2TESTVERSION
void DumpItemsList( void )
{
CHAR8 zPrintFileName[60];
FILE *FDump;
UINT16 usItem;
INVTYPE *pItem;
// open output file
strcpy(zPrintFileName, "ItemDump.txt");
FDump = fopen(zPrintFileName, "wt");
if (FDump == NULL)
return;
// print headings
fprintf(FDump, " ITEM COOLNESS VALUE\n");
fprintf(FDump, "============================ ======== =====\n");
for( usItem = 0; usItem < MAXITEMS; usItem++ )
{
pItem= &( Item[ usItem ] );
if (pItem->ubCoolness > 0 )
{
fprintf(FDump, "%28ls %2d $%4d\n", ItemNames[ usItem ], pItem->ubCoolness, pItem->usPrice );
}
}
fclose(FDump);
}
#endif // JA2TESTVERSION
// Snap: status modifiers for various item bonuses:
// In JA Gold status above this limit does not affect item performance (for some items)
const INT8 STANDARD_STATUS_CUTOFF = 85;
// Scale bonus with item status
INT16 BonusReduce( INT16 bonus, INT16 status, INT16 statusCutoff = STANDARD_STATUS_CUTOFF )
{
if ( bonus > 0 && status < statusCutoff && statusCutoff > 0 && statusCutoff <= 100 )
return ( ( status * 100 ) / statusCutoff * bonus ) / 100;
else // A penalty can't be reduced by status!
return bonus;
}
// Scale bonus with item status. Status < 50% creates a penalty!
INT16 BonusReduceMore( INT16 bonus, INT16 status, INT16 statusCutoff = 100 )
{
if ( bonus > 0 && status < statusCutoff && statusCutoff > 0 && statusCutoff <= 100 )
return ( ( ( status * 100 ) / statusCutoff - 50 ) * bonus ) / 50;
else // A penalty can't be reduced by status!
return bonus;
}
// Some items either work or they don't...
INT16 BonusOnOff( INT16 bonus, INT16 status )
{
if ( bonus > 0 )
return (status >= 50) ? bonus : 0;
else // A penalty can't be reduced by status!
return bonus;
}
// HEADROCK HAM 4: Scopes now determined not by an aim bonus but by a magnification factor.
BOOLEAN NCTHIsScoped( OBJECTTYPE * pObj )
{
if (pObj->exists() == true && UsingNewCTHSystem() == true) {
if ( Item[pObj->usItem].scopemagfactor > 1.0 || Item[(*pObj)[0]->data.gun.usGunAmmoItem].scopemagfactor > 1.0 )
return TRUE;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if ( Item[iter->usItem].scopemagfactor > 1.0 && iter->exists() )
return TRUE;
}
}
return FALSE;
}
// Snap: a fast aimbonus check for AI
BOOLEAN IsScoped( OBJECTTYPE * pObj )
{
if(UsingNewCTHSystem() == true)
return NCTHIsScoped(pObj);
if (pObj->exists() == true) {
if ( Item[pObj->usItem].aimbonus > 0 || Item[(*pObj)[0]->data.gun.usGunAmmoItem].aimbonus > 0 )
return TRUE;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if ( Item[iter->usItem].aimbonus > 0 && iter->exists())
return TRUE;
}
}
return FALSE;
}
// Snap: get aim bonus for a single item
INT16 GetItemAimBonus( const INVTYPE* pItem, INT32 iRange, INT16 ubAimTime )
{
if ( iRange <= pItem->minrangeforaimbonus ) return 0;
// reduce effective sight range by aimbonus% per extra aiming time AP
// of the distance beyond minrangeforaimbonus.
if ( pItem->aimbonus < 0)
ubAimTime = 1;
//CHRISL: The old system basically allowed scopes to reduce sight range by AimBonus%/click. So a scope with an
// AimBonus 20, and 8 clicks, would reduce sight range by 160%. In other words, it would effectively reduce sight
// range to 0 just for using 8 APs to aim.
//return ( pItem->aimbonus * ubAimTime * ( iRange - pItem->minrangeforaimbonus ) ) / 100;
// Instead, let's have the bonus reduce each click seperately and base the percentage on the new range.
INT16 bonus = 0, stepBonus = 0;
for( UINT8 step = 0; step < ubAimTime; step++)
{
stepBonus = (pItem->aimbonus * iRange)/100;
iRange -= stepBonus;
bonus += stepBonus;
if(iRange < pItem->minrangeforaimbonus)
{
stepBonus = pItem->minrangeforaimbonus - iRange;
bonus -= stepBonus;
break;
}
}
return(bonus);
}
INT16 GetAimBonus( OBJECTTYPE * pObj, INT32 iRange, INT16 ubAimTime )
{
INT16 bonus = 0;
if (pObj->exists() == true) {
bonus = BonusReduceMore( GetItemAimBonus( &Item[pObj->usItem], iRange, ubAimTime ), (*pObj)[0]->data.objectStatus );
bonus += GetItemAimBonus( &Item[(*pObj)[0]->data.gun.usGunAmmoItem], iRange, ubAimTime );
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists()){
bonus += BonusReduceMore( GetItemAimBonus( &Item[iter->usItem], iRange, ubAimTime ), (*iter)[0]->data.objectStatus );
}
}
}
return( bonus );
}
//WarmSteel - This is used to determine the base aim bonus of the scope on this gun.
//It searched for the most powerful scope that is not targetting under it's minimum range.
INT16 GetBaseScopeAimBonus( OBJECTTYPE * pObj, INT32 iRange )
{
INT16 bonus = 0;
//Valid integrated scope?
if(Item[pObj->usItem].aimbonus > bonus && iRange >= Item[pObj->usItem].minrangeforaimbonus ){
bonus = Item[pObj->usItem].aimbonus;
}
//Search for the most powerful scope we can use.
for(attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); iter++)
{
if(Item[iter->usItem].aimbonus > bonus && iRange >= Item[iter->usItem].minrangeforaimbonus && iter->exists())
{
bonus = Item[iter->usItem].aimbonus;
}
}
return( bonus );
}
// Madd: check equipment for aim bonus (penalties)
INT16 GetGearAimBonus( SOLDIERTYPE * pSoldier, INT32 iRange, INT16 ubAimTime )
{
INT16 bonus=0;
for (int j = HELMETPOS; j <= HEAD2POS; j++)
{
OBJECTTYPE* pObj = &pSoldier->inv[j];
if (pObj->exists() == true) {
bonus += GetItemAimBonus( &Item[pSoldier->inv[j].usItem], iRange, ubAimTime );
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists()){
bonus += GetItemAimBonus(&Item[iter->usItem],iRange,ubAimTime);
}
}
}
}
return( bonus );
}
// Madd: check equipment for to hit bonus (penalties)
INT16 GetGearToHitBonus( SOLDIERTYPE * pSoldier )
{
INT16 bonus=0;
for (int j = HELMETPOS; j <= HEAD2POS; j++)
{
OBJECTTYPE* pObj = &pSoldier->inv[j];
if (pObj->exists() == true) {
bonus += Item[pSoldier->inv[j].usItem].tohitbonus;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists()){
bonus += Item[iter->usItem].tohitbonus;
}
}
}
}
return( bonus );
}
// Madd: check equipment for AP bonus (penalties)
INT16 GetGearAPBonus( SOLDIERTYPE * pSoldier )
{
INT16 bonus=0;
for (int j = HELMETPOS; j <= HEAD2POS; j++)
{
if (pSoldier->inv[j].exists() == true) {
bonus += Item[pSoldier->inv[j].usItem].APBonus;
OBJECTTYPE* pObj = &pSoldier->inv[j];
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists()){
bonus += Item[iter->usItem].APBonus;
}
}
}
}
return( bonus );
}
UINT32 FindRangeBonusAttachment( OBJECTTYPE * pObj )
{
if (pObj->exists() == true) {
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if (Item[iter->usItem].rangebonus > 0 && iter->exists())
{
return( Item[iter->usItem].uiIndex );
}
}
}
return( NONE );
}
INT16 GetRangeBonus( OBJECTTYPE * pObj )
{
INT16 bonus = 0;
if (pObj->exists() == true) {
if(Item[pObj->usItem].usItemClass == IC_AMMO)
return( Item[pObj->usItem].rangebonus );
bonus = BonusReduce( Item[pObj->usItem].rangebonus, (*pObj)[0]->data.objectStatus );
if ( (*pObj)[0]->data.gun.ubGunShotsLeft > 0 )
bonus += Item[(*pObj)[0]->data.gun.usGunAmmoItem].rangebonus;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if ( !Item[iter->usItem].duckbill || ( Item[iter->usItem].duckbill && (*pObj)[0]->data.gun.ubGunAmmoType == AMMO_BUCKSHOT ) && iter->exists())
bonus += BonusReduce( Item[iter->usItem].rangebonus, (*iter)[0]->data.objectStatus );
}
}
return( bonus );
}
INT16 LaserBonus( const INVTYPE * pItem, INT32 iRange, UINT8 bLightLevel )
{
// Snap: Reduce laser scope bonus at long ranges and high light levels
if ( pItem->bestlaserrange == 0 || iRange <= pItem->bestlaserrange ) {
// No penalty within this range
return pItem->tohitbonus;
}
else {
// Figure out max. visible distance for the laser dot:
// day: 1.5*bestlaserrange, night: 2.5*bestlaserrange
// iMaxLaserRange = bestlaserrange * ( 1.5 + ( bLightLevel - NORMAL_LIGHTLEVEL_DAY )
// / ( NORMAL_LIGHTLEVEL_NIGHT - NORMAL_LIGHTLEVEL_DAY ) )
INT32 iMaxLaserRange = ( pItem->bestlaserrange*( 2*bLightLevel + 3*NORMAL_LIGHTLEVEL_NIGHT - 5*NORMAL_LIGHTLEVEL_DAY ) )
/ ( 2 * ( NORMAL_LIGHTLEVEL_NIGHT - NORMAL_LIGHTLEVEL_DAY ) );
// Beyond bestlaserrange laser bonus drops linearly to 0
INT16 bonus = ( pItem->tohitbonus * (iMaxLaserRange - iRange) )
/ ( iMaxLaserRange - pItem->bestlaserrange );
return (bonus > 0 ? bonus : 0);
}
}
INT16 GetToHitBonus( OBJECTTYPE * pObj, INT32 iRange, UINT8 bLightLevel, BOOLEAN fProneStance )
{
INT16 bonus=0;
// Snap: bipod is effective only in the prone stance
if (pObj->exists() == true) {
if ( fProneStance )
bonus += Item[pObj->usItem].bipod;
bonus += BonusReduceMore( LaserBonus( &Item[pObj->usItem], iRange, bLightLevel), (*pObj)[0]->data.objectStatus );
bonus += Item[(*pObj)[0]->data.gun.usGunAmmoItem].tohitbonus;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists()){
if ( fProneStance )
bonus += Item[iter->usItem].bipod;
bonus += BonusReduceMore( LaserBonus( &Item[iter->usItem], iRange, bLightLevel), (*iter)[0]->data.objectStatus );
}
}
}
// Snap (TODO): add special treatment of laser scopes
return( bonus );
}
// HEADROCK HAM 4: The following functions return the value of new NCTH-related modifiers from an item and all its
// attachments. They are stance-based, meaning that the soldier's stance determines which modifier is referenced.
// For a "default" value, feed the function a value of ubStance=ANIM_STAND.
INT32 GetFlatBaseModifier( OBJECTTYPE *pObj, UINT8 ubStance )
{
INT32 iModifier=0;
UINT8 ubRef = GetStanceModifierRef( ubStance );
if (pObj->exists() == true && UsingNewCTHSystem() == true)
{
iModifier += Item[pObj->usItem].flatbasemodifier[ubRef];
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter)
{
if (iter->exists())
{
iModifier += BonusReduceMore( Item[iter->usItem].flatbasemodifier[ubRef], (*iter)[0]->data.objectStatus );
}
}
}
return (iModifier);
}
INT32 GetPercentBaseModifier( OBJECTTYPE *pObj, UINT8 ubStance )
{
INT32 iModifier=0;
UINT8 ubRef = GetStanceModifierRef( ubStance );
if (pObj->exists() == true && UsingNewCTHSystem() == true)
{
iModifier += Item[pObj->usItem].percentbasemodifier[ubRef];
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter)
{
if (iter->exists())
{
iModifier += BonusReduceMore( Item[iter->usItem].percentbasemodifier[ubRef], (*iter)[0]->data.objectStatus );
}
}
}
iModifier = __max(-100,iModifier);
return (iModifier);
}
INT32 GetFlatAimModifier( OBJECTTYPE *pObj, UINT8 ubStance )
{
INT32 iModifier=0;
UINT8 ubRef = GetStanceModifierRef( ubStance );
if (pObj->exists() == true && UsingNewCTHSystem() == true)
{
iModifier += Item[pObj->usItem].flataimmodifier[ubRef];
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter)
{
if (iter->exists())
{
iModifier += BonusReduceMore( Item[iter->usItem].flataimmodifier[ubRef], (*iter)[0]->data.objectStatus );
}
}
}
return (iModifier);
}
INT32 GetPercentAimModifier( OBJECTTYPE *pObj, UINT8 ubStance )
{
INT32 iModifier=0;
UINT8 ubRef = GetStanceModifierRef( ubStance );
if (pObj->exists() == true && UsingNewCTHSystem() == true)
{
iModifier += Item[pObj->usItem].percentaimmodifier[ubRef];
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter)
{
if (iter->exists())
{
iModifier += BonusReduceMore( Item[iter->usItem].percentaimmodifier[ubRef], (*iter)[0]->data.objectStatus );
}
}
}
iModifier = __max(-100,iModifier);
return (iModifier);
}
INT32 GetPercentCapModifier( OBJECTTYPE *pObj, UINT8 ubStance )
{
INT32 iModifier=0;
UINT8 ubRef = GetStanceModifierRef( ubStance );
if (pObj->exists() == true && UsingNewCTHSystem() == true)
{
iModifier += Item[pObj->usItem].percentcapmodifier[ubRef];
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter)
{
if (iter->exists())
{
iModifier += BonusReduceMore( Item[iter->usItem].percentcapmodifier[ubRef], (*iter)[0]->data.objectStatus );
}
}
}
iModifier = __max(-100,iModifier);
return (iModifier);
}
INT32 GetPercentHandlingModifier( OBJECTTYPE *pObj, UINT8 ubStance )
{
INT32 iModifier=0;
UINT8 ubRef = GetStanceModifierRef( ubStance );
if (pObj->exists() == true && UsingNewCTHSystem() == true)
{
iModifier += Item[pObj->usItem].percenthandlingmodifier[ubRef];
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter)
{
if (iter->exists())
{
iModifier += BonusReduceMore( Item[iter->usItem].percenthandlingmodifier[ubRef], (*iter)[0]->data.objectStatus );
}
}
}
iModifier = __max(-100,iModifier);
return ((UINT32)iModifier);
}
INT32 GetDropCompensationModifier( OBJECTTYPE *pObj, UINT8 ubStance )
{
INT32 iModifier=0;
UINT8 ubRef = GetStanceModifierRef( ubStance );
if (pObj->exists() == true && UsingNewCTHSystem() == true)
{
iModifier += Item[pObj->usItem].percentdropcompensationmodifier[ubRef];
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter)
{
if (iter->exists())
{
iModifier += BonusReduceMore( Item[iter->usItem].percentdropcompensationmodifier[ubRef], (*iter)[0]->data.objectStatus );
}
}
}
iModifier = __max(-100,iModifier);
return (iModifier);
}
// HEADROCK HAM 4: This function returns the Max Counter Force modifier given by the weapon
INT32 GetCounterForceMaxModifier( OBJECTTYPE *pObj, UINT8 ubStance )
{
INT32 iModifier=0;
UINT8 ubRef = GetStanceModifierRef( ubStance );
if (pObj->exists() == true && UsingNewCTHSystem() == true)
{
iModifier += Item[pObj->usItem].maxcounterforcemodifier[ubRef];
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter)
{
if (iter->exists())
{
iModifier += BonusReduceMore( Item[iter->usItem].maxcounterforcemodifier[ubRef], (*iter)[0]->data.objectStatus );
}
}
}
if(ubRef == 1)
iModifier += (INT32)gGameCTHConstants.RECOIL_MAX_COUNTER_CROUCH;
else if (ubRef == 2)
iModifier += (INT32)gGameCTHConstants.RECOIL_MAX_COUNTER_PRONE;
iModifier = __max(-100,iModifier);
return (iModifier);
}
// HEADROCK HAM 4: This function returns the Counter Force Accuracy modifier given by the weapon
INT32 GetCounterForceAccuracyModifier( OBJECTTYPE *pObj, UINT8 ubStance )
{
INT32 iModifier=0;
UINT8 ubRef = GetStanceModifierRef( ubStance );
if (pObj->exists() == true && UsingNewCTHSystem() == true)
{
iModifier += Item[pObj->usItem].counterforceaccuracymodifier[ubRef];
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter)
{
if (iter->exists())
{
iModifier += BonusReduceMore( Item[iter->usItem].counterforceaccuracymodifier[ubRef], (*iter)[0]->data.objectStatus );
}
}
}
iModifier = __max(-100,iModifier);
return (iModifier);
}
INT32 GetCounterForceFrequencyModifier( OBJECTTYPE *pObj, UINT8 ubStance )
{
INT32 iModifier=0;
UINT8 ubRef = GetStanceModifierRef( ubStance );
if (pObj->exists() == true && UsingNewCTHSystem() == true)
{
iModifier += Item[pObj->usItem].counterforcefrequencymodifier[ubRef];
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter)
{
if (iter->exists())
{
iModifier += BonusReduceMore( Item[iter->usItem].counterforcefrequencymodifier[ubRef], (*iter)[0]->data.objectStatus );
}
}
}
return (iModifier);
}
INT32 GetTargetTrackingModifier( OBJECTTYPE *pObj, UINT8 ubStance )
{
INT32 iModifier=0;
UINT8 ubRef = GetStanceModifierRef( ubStance );
if (pObj->exists() == true && UsingNewCTHSystem() == true)
{
iModifier += Item[pObj->usItem].targettrackingmodifier[ubRef];
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter)
{
if (iter->exists())
{
iModifier += BonusReduceMore( Item[iter->usItem].targettrackingmodifier[ubRef], (*iter)[0]->data.objectStatus );
}
}
}
iModifier = __max(-100,iModifier);
return (iModifier);
}
INT32 GetAimLevelsModifier( OBJECTTYPE *pObj, UINT8 ubStance )
{
INT32 iModifier=0;
UINT8 ubRef = GetStanceModifierRef( ubStance );
if (pObj->exists() == true && UsingNewCTHSystem() == true)
{
iModifier += Item[pObj->usItem].aimlevelsmodifier[ubRef];
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter)
{
if (iter->exists())
{
iModifier += Item[iter->usItem].aimlevelsmodifier[ubRef];
}
}
}
iModifier = __max(-100,iModifier);
return (iModifier);
}
INT32 GetAimLevelsTraitModifier( SOLDIERTYPE *pSoldier, OBJECTTYPE *pObj )
{
INT8 ubSkillModifier = 0;
if( gGameOptions.fNewTraitSystem )
{
if ( Weapon[Item[pObj->usItem].ubClassIndex].ubWeaponType == GUN_PISTOL || Weapon[Item[pObj->usItem].ubClassIndex].ubWeaponType == GUN_M_PISTOL )
ubSkillModifier -= NUM_SKILL_TRAITS( pSoldier, GUNSLINGER_NT );
else
ubSkillModifier -= NUM_SKILL_TRAITS( pSoldier, SNIPER_NT );
}
else
{
ubSkillModifier -= NUM_SKILL_TRAITS( pSoldier, PROF_SNIPER_OT );
}
return (INT32)ubSkillModifier;
}
INT16 GetBurstToHitBonus( OBJECTTYPE * pObj, BOOLEAN fProneStance )
{
INT16 bonus=0;
// Snap: bipod is effective only in the prone stance
// CHRISL: We don't want to count both bipod AND bursttohitbonus as some items get both bonuses
if (pObj->exists() == true) {
if ( fProneStance )
bonus += BonusReduceMore( Item[pObj->usItem].bipod, (*pObj)[0]->data.objectStatus );
else
bonus += BonusReduceMore( Item[pObj->usItem].bursttohitbonus, (*pObj)[0]->data.objectStatus );
// HEADROCK HAM B2.5: A certain setting in the New Tracer System can turn auto/burst penalties off
// entirely, to make up for "Tracer Bump".
if ( gGameExternalOptions.ubRealisticTracers != 1 )
bonus += Item[(*pObj)[0]->data.gun.usGunAmmoItem].bursttohitbonus ;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists()){
if ( fProneStance )
bonus += BonusReduceMore( Item[iter->usItem].bipod, (*iter)[0]->data.objectStatus );
else
bonus += BonusReduceMore( Item[iter->usItem].bursttohitbonus, (*iter)[0]->data.objectStatus );
}
}
}
return( bonus );
}
void GetRecoil( SOLDIERTYPE *pSoldier, OBJECTTYPE *pObj, INT8 *bRecoilX, INT8 *bRecoilY, UINT8 ubNumBullet )
{
*bRecoilX = 0;
*bRecoilY = 0;
//if (ubNumBullet < 2)
if (ubNumBullet < Weapon[pObj->usItem].ubRecoilDelay)
{
// The first bullet in a volley never has recoil - it hasn't "set in" yet. Only the second+ bullets
// will have any recoil.
*bRecoilX = 0;
*bRecoilY = 0;
return;
}
*bRecoilX = Weapon[pObj->usItem].bRecoilX;
*bRecoilY = Weapon[pObj->usItem].bRecoilY;
// Apply a percentage-based modifier. This can increase or decrease BOTH axes. At most, it can eliminate
// recoil on the gun.
INT16 sPercentRecoilModifier = GetPercentRecoilModifier( pObj );
*bRecoilX += (*bRecoilX * sPercentRecoilModifier ) / 100;
*bRecoilY += (*bRecoilY * sPercentRecoilModifier ) / 100;
// Apply a flat modifier. This acts on either axis, and if powerful enough can "reverse polarity" of either
// axis recoil. For instance, it can make a gun that normally pulls LEFT start pulling RIGHT instead.
INT8 bRecoilAdjustX = 0;
INT8 bRecoilAdjustY = 0;
GetFlatRecoilModifier( pObj, &bRecoilAdjustX, &bRecoilAdjustY );
*bRecoilX = __max(0, *bRecoilX + bRecoilAdjustX);
*bRecoilY = __max(0, *bRecoilY + bRecoilAdjustY);
return;
}
///////////////////////////////////////////////////////
// HEADROCK HAM 4: This function calculates the flat recoil adjustment for a gun. Flat adjustment increases
// or decreases recoil by a specific number of points in either the vertical or horizontal axes (or both).
// It can potentially cause a weapon it reverse its recoil direction.
void GetFlatRecoilModifier( OBJECTTYPE *pObj, INT8 *bRecoilModifierX, INT8 *bRecoilModifierY )
{
INT8 bRecoilAdjustX = 0;
INT8 bRecoilAdjustY = 0;
if (pObj->exists() == true && UsingNewCTHSystem() == true)
{
// Inherent item modifiers
bRecoilAdjustX += BonusReduceMore( Item[pObj->usItem].RecoilModifierX, (*pObj)[0]->data.objectStatus );
bRecoilAdjustY += BonusReduceMore( Item[pObj->usItem].RecoilModifierY, (*pObj)[0]->data.objectStatus );
// Ammo item modifiers
bRecoilAdjustX += Item[(*pObj)[0]->data.gun.usGunAmmoItem].RecoilModifierX;
bRecoilAdjustY += Item[(*pObj)[0]->data.gun.usGunAmmoItem].RecoilModifierY;
// Attachment item modifiers
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter)
{
if (iter->exists())
{
bRecoilAdjustX += BonusReduceMore( Item[iter->usItem].RecoilModifierX, (*iter)[0]->data.objectStatus );
bRecoilAdjustY += BonusReduceMore( Item[iter->usItem].RecoilModifierY, (*iter)[0]->data.objectStatus );
}
}
}
*bRecoilModifierX = bRecoilAdjustX;
*bRecoilModifierY = bRecoilAdjustY;
}
///////////////////////////////////////////////////////////////////
// HEADROCK HAM 4: This calculates the percentile recoil adjustment of a gun.
// This adjustment either increases or decreases the gun's vertical and horizontal recoil at the same time. Due to
// the percentage-based nature of this modifier, it cannot cause a gun to reverse its recoil - only diminish it to
// zero.
INT16 GetPercentRecoilModifier( OBJECTTYPE *pObj )
{
INT16 sRecoilAdjust = 0;
if (pObj->exists() == true && UsingNewCTHSystem() == true)
{
// Inherent item modifiers
sRecoilAdjust += BonusReduceMore( Item[pObj->usItem].PercentRecoilModifier, (*pObj)[0]->data.objectStatus );
// Ammo item modifiers
sRecoilAdjust += Item[(*pObj)[0]->data.gun.usGunAmmoItem].PercentRecoilModifier;
// Attachment item modifiers
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter)
{
if (iter->exists())
{
sRecoilAdjust += BonusReduceMore( Item[iter->usItem].PercentRecoilModifier, (*iter)[0]->data.objectStatus );
}
}
}
sRecoilAdjust = __max(-100, sRecoilAdjust);
return (sRecoilAdjust);
}
// HEADROCK HAM 4: This is used by functions that get stance-based modifiers from weapons. It turns a ubEndHeight variable
// as either 0, 1 or 2.
INT8 GetStanceModifierRef( INT8 ubStance )
{
switch (ubStance)
{
case ANIM_PRONE:
return(2);
case ANIM_CROUCH:
return(1);
default:
return(0);
}
}
INT16 GetDamageBonus( OBJECTTYPE * pObj )
{
INT16 bonus = 0;
if (pObj->exists() == true) {
bonus = BonusReduce( Item[pObj->usItem].damagebonus, (*pObj)[0]->data.objectStatus );
if ( (*pObj)[0]->data.gun.ubGunShotsLeft > 0 )
bonus += Item[(*pObj)[0]->data.gun.usGunAmmoItem].damagebonus ;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists()){
bonus += BonusReduce( Item[iter->usItem].damagebonus, (*iter)[0]->data.objectStatus );
}
}
}
return( bonus );
}
INT16 GetMeleeDamageBonus( OBJECTTYPE * pObj )
{
INT16 bonus = 0;
if (pObj->exists() == true) {
bonus = BonusReduce( Item[pObj->usItem].meleedamagebonus, (*pObj)[0]->data.objectStatus);
bonus += Item[(*pObj)[0]->data.gun.usGunAmmoItem].meleedamagebonus ;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists()){
bonus += BonusReduce( Item[iter->usItem].meleedamagebonus, (*iter)[0]->data.objectStatus );
}
}
}
return( bonus );
}
INT16 GetPercentAPReduction( OBJECTTYPE * pObj )
{
INT16 bonus = 0;
if (pObj->exists() == true) {
bonus = BonusReduceMore( Item[pObj->usItem].percentapreduction, (*pObj)[0]->data.objectStatus );
bonus += Item[(*pObj)[0]->data.gun.usGunAmmoItem].percentapreduction;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists()){
bonus += BonusReduceMore( Item[iter->usItem].percentapreduction,
(*iter)[0]->data.objectStatus );
}
}
}
return( bonus );
}
INT16 GetMagSizeBonus( OBJECTTYPE * pObj, UINT8 subObject )
{
INT16 bonus = 0;
if (pObj->exists() == true) {
bonus = BonusOnOff( Item[pObj->usItem].magsizebonus, (*pObj)[subObject]->data.objectStatus );
for (attachmentList::iterator iter = (*pObj)[subObject]->attachments.begin(); iter != (*pObj)[subObject]->attachments.end(); ++iter) {
if(iter->exists()){
bonus += BonusOnOff( Item[iter->usItem].magsizebonus, (*iter)[0]->data.objectStatus );
}
}
}
return( bonus );
}
INT16 GetBurstSizeBonus( OBJECTTYPE * pObj )
{
INT16 bonus = 0;
if (pObj->exists() == true) {
bonus = BonusOnOff( Item[pObj->usItem].burstsizebonus, (*pObj)[0]->data.objectStatus );
bonus += Item[(*pObj)[0]->data.gun.usGunAmmoItem].burstsizebonus ;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists()){
bonus += BonusOnOff( Item[iter->usItem].burstsizebonus, (*iter)[0]->data.objectStatus );
}
}
}
return( bonus );
}
INT16 GetRateOfFireBonus( OBJECTTYPE * pObj )
{
INT16 bonus=0;
if (pObj->exists() == true) {
if( (MAXITEMS <= pObj->usItem) || (MAXITEMS <= (*pObj)[0]->data.gun.usGunAmmoItem) )
{
DebugMsg(TOPIC_JA2, DBG_LEVEL_1, String("GetRateOfFireBonus would crash: pObj->usItem=%d or (*pObj)[0]->data.gun.usGunAmmoItem=%d ist higher than max %d", pObj->usItem, (*pObj)[0]->data.gun.usGunAmmoItem, MAXITEMS ));
ScreenMsg( MSG_FONT_RED, MSG_DEBUG, L"GetRateOfFireBonus would crash: pObj->usItem=%d or (*pObj)[0]->data.gun.usGunAmmoItem=%d ist higher than max %d", pObj->usItem, (*pObj)[0]->data.gun.usGunAmmoItem, MAXITEMS );
AssertMsg( 0, "GetRateOfFireBonus would crash" );
return 0; /* cannot calculate Bonus, this only happens sometimes in FULLSCREEN */
}
bonus = BonusReduceMore( Item[pObj->usItem].rateoffirebonus, (*pObj)[0]->data.objectStatus );
bonus += Item[(*pObj)[0]->data.gun.usGunAmmoItem].rateoffirebonus ;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists()){
bonus += BonusReduceMore( Item[iter->usItem].rateoffirebonus, (*iter)[0]->data.objectStatus );
}
}
}
return( bonus );
}
INT16 GetAutoToHitBonus( OBJECTTYPE * pObj, BOOLEAN fProneStance )
{
INT16 bonus=0;
// Snap: bipod is effective only in the prone stance
// CHRISL: We don't want to count both bipod AND bursttohitbonus as some items get both bonuses
if (pObj->exists() == true) {
if ( fProneStance )
bonus += BonusReduceMore( Item[pObj->usItem].bipod, (*pObj)[0]->data.objectStatus );
else
bonus += BonusReduceMore( Item[pObj->usItem].autofiretohitbonus, (*pObj)[0]->data.objectStatus );
// HEADROCK HAM B2.5: This external setting determines whether autofire penalty is affected by
// tracer ammo. At setting "1", it is disabled. This goes hand in hand with a new tracer effect that
// "bumps" CTH up after firing a tracer bullet.
if ( gGameExternalOptions.ubRealisticTracers != 1 )
bonus += Item[(*pObj)[0]->data.gun.usGunAmmoItem].autofiretohitbonus ;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists()){
if ( fProneStance )
bonus += BonusReduceMore( Item[iter->usItem].bipod, (*iter)[0]->data.objectStatus );
else
bonus += BonusReduceMore( Item[iter->usItem].autofiretohitbonus, (*iter)[0]->data.objectStatus );
}
}
}
return( bonus );
}
INT16 GetPercentReadyTimeAPReduction( OBJECTTYPE * pObj )
{
INT16 bonus = 0;
if (pObj->exists() == true) {
bonus = BonusReduceMore( Item[pObj->usItem].percentreadytimeapreduction, (*pObj)[0]->data.objectStatus );
bonus += Item[(*pObj)[0]->data.gun.usGunAmmoItem].percentreadytimeapreduction;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists()){
bonus += BonusReduceMore( Item[iter->usItem].percentreadytimeapreduction, (*iter)[0]->data.objectStatus );
}
}
}
return( bonus );
}
INT16 GetPercentAutofireAPReduction( OBJECTTYPE * pObj )
{
INT16 bonus = 0;
if (pObj->exists() == true) {
bonus = BonusReduceMore( Item[pObj->usItem].percentautofireapreduction, (*pObj)[0]->data.objectStatus );
bonus += Item[(*pObj)[0]->data.gun.usGunAmmoItem].percentautofireapreduction;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists()){
bonus += BonusReduceMore( Item[iter->usItem].percentautofireapreduction, (*iter)[0]->data.objectStatus );
}
}
}
return( bonus );
}
INT16 GetPercentReloadTimeAPReduction( OBJECTTYPE * pObj )
{
INT16 bonus = 0;
if (pObj->exists() == true) {
BonusReduceMore( Item[pObj->usItem].percentreloadtimeapreduction, (*pObj)[0]->data.objectStatus );
bonus += Item[(*pObj)[0]->data.gun.usGunAmmoItem].percentreloadtimeapreduction;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists()){
bonus += BonusReduceMore( Item[iter->usItem].percentreloadtimeapreduction, (*iter)[0]->data.objectStatus );
}
}
}
return( bonus );
}
INT16 GetPercentBurstFireAPReduction( OBJECTTYPE * pObj )
{
INT16 bonus = 0;
if (pObj->exists() == true) {
BonusReduceMore( Item[pObj->usItem].percentburstfireapreduction, (*pObj)[0]->data.objectStatus );
bonus += Item[(*pObj)[0]->data.gun.usGunAmmoItem].percentburstfireapreduction;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists()){
bonus += BonusReduceMore( Item[iter->usItem].percentburstfireapreduction, (*iter)[0]->data.objectStatus );
}
}
}
return( bonus );
}
INT16 GetVisionRangeBonus( SOLDIERTYPE * pSoldier )
{
INT16 bonus=0;
OBJECTTYPE *pObj;
UINT16 usItem;
INVTYPE *pItem;
//ADB and AXP 28.03.2007: CtH bug fix: We also want to check on a firing weapon, "raised" alone is not enough ;)
bool usingGunScope = WeaponReady(pSoldier);
// CHRISL:
for (int i = BODYPOSSTART; i < BODYPOSFINAL; i++)
{
// Okay, it's time for some optimization here too
pObj = &( pSoldier->inv[i]);
if (pObj->exists() == true) {
usItem = pObj->usItem;
pItem = &(Item[usItem]);
// Snap (TODO): binoculars and such should not be active by default
if ( (i == HANDPOS || i == SECONDHANDPOS) && (pItem->usItemClass & IC_ARMOUR || pItem->usItemClass & IC_FACE ))
{
continue;
}
//CHRISL: Binoculars can only be used in the primary hand
if(i == SECONDHANDPOS && pItem->usItemClass & IC_MISC && pItem->visionrangebonus > 0)
{
continue;
}
if (!IsWeapon(usItem) || (IsWeapon(usItem) && usingGunScope == true) )
{
bonus += BonusReduceMore( pItem->visionrangebonus, (*pObj)[0]->data.objectStatus );
}
}
}
// Snap: check only attachments on a readied weapon!
// 0verhaul: Moved this bug fix into WeaponReady so that all CTH modifier functions may benefit from this fix
//AXP 28.03.2007: CtH bug fix: We also want to check on a firing weapon, "raised" alone is not enough ;)
if ( usingGunScope == true )
{
// SANDRO - added scouting check
INT16 sScopebonus = 0;
pObj = &( pSoldier->inv[HANDPOS]);
if (pObj->exists() == true) {
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists()){
sScopebonus += BonusReduceMore( Item[iter->usItem].visionrangebonus, (*iter)[0]->data.objectStatus );
}
}
}
if( sScopebonus > 0 && HAS_SKILL_TRAIT( pSoldier, SCOUTING_NT ) && gGameOptions.fNewTraitSystem)
{
sScopebonus += gSkillTraitValues.ubSCSightRangebonusWithScopes;
}
bonus += sScopebonus;
}
return( bonus );
}
// Snap: Scale night vision bonus with light level
INT16 NightBonusScale( INT16 bonus, UINT8 bLightLevel )
{
if ( bLightLevel > NORMAL_LIGHTLEVEL_NIGHT ) {
return idiv( bonus * ( SHADE_MIN - bLightLevel ),
SHADE_MIN - NORMAL_LIGHTLEVEL_NIGHT );
}
else if ( bLightLevel > NORMAL_LIGHTLEVEL_DAY ) {
return idiv( bonus * (bLightLevel - NORMAL_LIGHTLEVEL_DAY),
NORMAL_LIGHTLEVEL_NIGHT - NORMAL_LIGHTLEVEL_DAY );
}
else return 0;
}
INT16 GetNightVisionRangeBonus( SOLDIERTYPE * pSoldier, UINT8 bLightLevel )
{
INT16 bonus=0;
OBJECTTYPE *pObj;
UINT16 usItem;
INVTYPE *pItem;
//ADB and AXP 28.03.2007: CtH bug fix: We also want to check on a firing weapon, "raised" alone is not enough ;)
bool usingGunScope = WeaponReady(pSoldier);
// CHRISL:
for (int i = BODYPOSSTART; i < BODYPOSFINAL; i++)
{
// More optimization
pObj = &( pSoldier->inv[i]);
if (pObj->exists() == true) {
usItem = pObj->usItem;
pItem = &(Item[usItem]);
// Snap (TODO): binoculars and such should not be active by default
if ( (i == HANDPOS || i == SECONDHANDPOS) && (pItem->usItemClass & IC_ARMOUR || pItem->usItemClass & IC_FACE ))
{
continue;
}
//CHRISL: Binoculars can only be used in the primary hand
if(i == SECONDHANDPOS && pItem->usItemClass & IC_MISC && pItem->nightvisionrangebonus > 0)
{
continue;
}
if (!IsWeapon(usItem) || (IsWeapon(usItem) && usingGunScope == true ) )
{
bonus += BonusReduceMore(
NightBonusScale( pItem->nightvisionrangebonus, bLightLevel ),
(*pObj)[0]->data.objectStatus );
}
}
}
// Snap: check only attachments on a raised weapon!
if ( usingGunScope == true )
{
// SANDRO - added scouting check
INT16 sScopebonus = 0;
pObj = &( pSoldier->inv[HANDPOS]);
if (pObj->exists() == true) {
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists()){
sScopebonus += BonusReduceMore(
NightBonusScale( Item[iter->usItem].nightvisionrangebonus, bLightLevel ),
(*iter)[0]->data.objectStatus );
}
}
}
if( sScopebonus > 0 && HAS_SKILL_TRAIT( pSoldier, SCOUTING_NT ) && gGameOptions.fNewTraitSystem)
{
sScopebonus += gSkillTraitValues.ubSCSightRangebonusWithScopes;
}
bonus += sScopebonus;
}
return( bonus );
}
INT16 GetCaveVisionRangeBonus( SOLDIERTYPE * pSoldier, UINT8 bLightLevel )
{
INT16 bonus=0;
OBJECTTYPE *pObj;
UINT16 usItem;
INVTYPE *pItem;
//ADB and AXP 28.03.2007: CtH bug fix: We also want to check on a firing weapon, "raised" alone is not enough ;)
bool usingGunScope = WeaponReady(pSoldier);
// CHRISL:
for (int i = BODYPOSSTART; i < BODYPOSFINAL; i++)
{
// More optimization
pObj = &( pSoldier->inv[i]);
if (pObj->exists() == true) {
usItem = pObj->usItem;
pItem = &(Item[usItem]);
// Snap (TODO): binoculars and such should not be active by default
if ( (i == HANDPOS || i == SECONDHANDPOS) &&
(pItem->usItemClass & IC_ARMOUR || pItem->usItemClass & IC_FACE ))
{
continue;
}
//CHRISL: Binoculars can only be used in the primary hand
if(i == SECONDHANDPOS && pItem->usItemClass & IC_MISC && pItem->cavevisionrangebonus > 0)
{
continue;
}
if (!IsWeapon(usItem) || (IsWeapon(usItem) && usingGunScope == true ) )
{
bonus += BonusReduceMore(
NightBonusScale( pItem->cavevisionrangebonus, bLightLevel ),
(*pObj)[0]->data.objectStatus );
}
}
}
// Snap: check only attachments on a raised weapon!
if ( usingGunScope == true )
{
// SANDRO - added scouting check
INT16 sScopebonus = 0;
pObj = &( pSoldier->inv[HANDPOS]);
if (pObj->exists() == true) {
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists()){
sScopebonus += BonusReduceMore(
NightBonusScale( Item[iter->usItem].cavevisionrangebonus, bLightLevel ),
(*iter)[0]->data.objectStatus );
}
}
}
if( sScopebonus > 0 && HAS_SKILL_TRAIT( pSoldier, SCOUTING_NT ) && gGameOptions.fNewTraitSystem)
{
sScopebonus += gSkillTraitValues.ubSCSightRangebonusWithScopes;
}
bonus += sScopebonus;
}
return( bonus );
}
INT16 GetDayVisionRangeBonus( SOLDIERTYPE * pSoldier, UINT8 bLightLevel )
{
INT16 bonus=0;
OBJECTTYPE *pObj;
UINT16 usItem;
INVTYPE *pItem;
// Snap: Scale the bonus with the light level
//ADB and AXP 28.03.2007: CtH bug fix: We also want to check on a firing weapon, "raised" alone is not enough ;)
bool usingGunScope = WeaponReady(pSoldier);
// CHRISL:
for (int i = BODYPOSSTART; i < BODYPOSFINAL; i++)
{
// More optimization
pObj = &( pSoldier->inv[i]);
if (pObj->exists() == true) {
usItem = pObj->usItem;
pItem = &(Item[usItem]);
// Snap (TODO): binoculars and such should not be active by default
if ( (i == HANDPOS || i == SECONDHANDPOS) &&
(pItem->usItemClass & IC_ARMOUR || pItem->usItemClass & IC_FACE ))
{
continue;
}
//CHRISL: Binoculars can only be used in the primary hand
if(i == SECONDHANDPOS && pItem->usItemClass & IC_MISC && pItem->dayvisionrangebonus > 0)
{
continue;
}
if (!IsWeapon(usItem) || (IsWeapon(usItem) && usingGunScope == true ) )
{
bonus += BonusReduceMore( idiv( pItem->dayvisionrangebonus
* (NORMAL_LIGHTLEVEL_NIGHT - bLightLevel), NORMAL_LIGHTLEVEL_NIGHT ),
(*pObj)[0]->data.objectStatus );
}
}
}
// Snap: check only attachments on a raised weapon!
//CHRISL: Since this is a daytime calculation, I think we want the difference between NORMAL_LIGHTLEVEL_NIGHT and
// NORMAL_LIGHTLEVEL_DAY. To just use NORMAL_LIGHTLEVEL_NIGHT is the same as basing the calculation off of the
// difference between NORMAL_LIGHTLEVEL_NIGHT and 0, which represent bright light.
if ( usingGunScope == true )
{
// SANDRO - added scouting check
INT16 sScopebonus = 0;
pObj = &( pSoldier->inv[HANDPOS]);
if (pObj->exists() == true) {
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists()){
sScopebonus += BonusReduceMore( idiv( Item[iter->usItem].dayvisionrangebonus
* (NORMAL_LIGHTLEVEL_NIGHT - __max(bLightLevel,NORMAL_LIGHTLEVEL_DAY)), (NORMAL_LIGHTLEVEL_NIGHT-NORMAL_LIGHTLEVEL_DAY) ),
(*iter)[0]->data.objectStatus );
}
}
}
if( sScopebonus > 0 && HAS_SKILL_TRAIT( pSoldier, SCOUTING_NT ) && gGameOptions.fNewTraitSystem)
{
sScopebonus += gSkillTraitValues.ubSCSightRangebonusWithScopes;
}
bonus += sScopebonus;
}
return( bonus );
}
INT16 GetBrightLightVisionRangeBonus( SOLDIERTYPE * pSoldier, UINT8 bLightLevel )
{
INT16 bonus=0;
OBJECTTYPE *pObj;
UINT16 usItem;
INVTYPE *pItem;
// Snap: Scale the bonus with the light level
//ADB and AXP 28.03.2007: CtH bug fix: We also want to check on a firing weapon, "raised" alone is not enough ;)
bool usingGunScope = WeaponReady(pSoldier);
// CHRISL:
for (int i = BODYPOSSTART; i < BODYPOSFINAL; i++)
{
// More optimization
pObj = &( pSoldier->inv[i]);
if (pObj->exists() == true) {
usItem = pObj->usItem;
pItem = &(Item[usItem]);
// Snap (TODO): binoculars and such should not be active by default
if ( (i == HANDPOS || i == SECONDHANDPOS) &&
(pItem->usItemClass & IC_ARMOUR || pItem->usItemClass & IC_FACE ))
{
continue;
}
//CHRISL: Binoculars can only be used in the primary hand
if(i == SECONDHANDPOS && pItem->usItemClass & IC_MISC && pItem->brightlightvisionrangebonus > 0)
{
continue;
}
if (!IsWeapon(usItem) || (IsWeapon(usItem) && usingGunScope == true ) )
{
bonus += BonusReduceMore( idiv( pItem->brightlightvisionrangebonus
* (NORMAL_LIGHTLEVEL_DAY - bLightLevel), NORMAL_LIGHTLEVEL_DAY ),
(*pObj)[0]->data.objectStatus );
}
}
}
// Snap: check only attachments on a raised weapon!
if ( usingGunScope == true )
{
// SANDRO - added scouting check
INT16 sScopebonus = 0;
pObj = &( pSoldier->inv[HANDPOS]);
if (pObj->exists() == true) {
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists()){
sScopebonus += BonusReduceMore( idiv( Item[iter->usItem].brightlightvisionrangebonus
* (NORMAL_LIGHTLEVEL_DAY - bLightLevel), NORMAL_LIGHTLEVEL_DAY ),
(*iter)[0]->data.objectStatus );
}
}
}
if( sScopebonus > 0 && HAS_SKILL_TRAIT( pSoldier, SCOUTING_NT ) && gGameOptions.fNewTraitSystem)
{
sScopebonus += gSkillTraitValues.ubSCSightRangebonusWithScopes;
}
bonus += sScopebonus;
}
return( bonus );
}
INT16 GetTotalVisionRangeBonus( SOLDIERTYPE * pSoldier, UINT8 bLightLevel )
{
INT16 bonus = GetVisionRangeBonus(pSoldier);
if ( bLightLevel > NORMAL_LIGHTLEVEL_DAY )
{
if ( pSoldier->pathing.bLevel == 0 )
{
bonus += GetNightVisionRangeBonus(pSoldier, bLightLevel);
}
else
{
bonus += GetCaveVisionRangeBonus(pSoldier, bLightLevel);
}
}
if ( bLightLevel < NORMAL_LIGHTLEVEL_NIGHT )
{
bonus += GetDayVisionRangeBonus(pSoldier, bLightLevel);
}
if ( bLightLevel < NORMAL_LIGHTLEVEL_DAY )
{
bonus += GetBrightLightVisionRangeBonus(pSoldier, bLightLevel);
}
// SANDRO - STOMP traits - Scouting bonus for sight range with binoculars and similar
if ( gGameOptions.fNewTraitSystem && HAS_SKILL_TRAIT( pSoldier, SCOUTING_NT ) && pSoldier->pathing.bLevel == 0 )
{
OBJECTTYPE *pObj = &( pSoldier->inv[HANDPOS]);
if (pObj->exists() == true)
{
// we have no pointer to binoculars, so just check any misc items in hands which have some vision bonus
if ( Item[pObj->usItem].usItemClass & IC_MISC && (Item[pObj->usItem].brightlightvisionrangebonus > 0 ||
Item[pObj->usItem].dayvisionrangebonus > 0 || Item[pObj->usItem].nightvisionrangebonus > 0 || Item[pObj->usItem].visionrangebonus > 0 ))
{
bonus += gSkillTraitValues.usSCSightRangebonusWithBinoculars;
}
}
}
return bonus;
}
UINT8 GetPercentTunnelVision( SOLDIERTYPE * pSoldier )
{
UINT8 bonus = 0;
UINT16 usItem;
INVTYPE *pItem;
//ADB and AXP 28.03.2007: CtH bug fix: We also want to check on a firing weapon, "raised" alone is not enough ;)
bool usingGunScope = WeaponReady(pSoldier);
// CHRISL:
for (int i = BODYPOSSTART; i < BODYPOSFINAL; i++)
{
// Okay, it's time for some optimization here
if (pSoldier->inv[i].exists() == true) {
usItem = pSoldier->inv[i].usItem;
pItem = &(Item[usItem]);
if ( (i == HANDPOS || i == SECONDHANDPOS) && (pItem->usItemClass & IC_ARMOUR || pItem->usItemClass & IC_FACE ))
{
continue;
}
//CHRISL: Binoculars can only be used in the primary hand
if(i == SECONDHANDPOS && pItem->usItemClass & IC_MISC && pItem->percenttunnelvision > 0)
{
continue;
}
if ( !IsWeapon(usItem) )
{
bonus = __max( bonus, pItem->percenttunnelvision );
}
}
}
// Snap: check only attachments on a raised weapon!
if ( usingGunScope == true )
{
OBJECTTYPE *pObj = &(pSoldier->inv[HANDPOS]);
if (pObj->exists() == true) {
usItem = pObj->usItem;
pItem = &(Item[usItem]);
if ( IsWeapon(usItem) ) //if not a weapon, then it was added already above
bonus += Item[usItem].percenttunnelvision;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists())
bonus += Item[iter->usItem].percenttunnelvision;
}
}
}
// SANDRO - STOMP traits - Scouting tunnel vision reduction with binoculars and similar
if ( gGameOptions.fNewTraitSystem && HAS_SKILL_TRAIT( pSoldier, SCOUTING_NT ) && pSoldier->pathing.bLevel == 0 )
{
OBJECTTYPE *pObj = &( pSoldier->inv[HANDPOS]);
if (pObj->exists() == true)
{
// we have no pointer to binoculars, so just check any misc items in hands which have some vision bonus
if ( Item[pObj->usItem].usItemClass & IC_MISC && (Item[pObj->usItem].brightlightvisionrangebonus > 0 ||
Item[pObj->usItem].dayvisionrangebonus > 0 || Item[pObj->usItem].nightvisionrangebonus > 0 || Item[pObj->usItem].visionrangebonus > 0 ))
{
bonus = max( 0, (bonus - gSkillTraitValues.ubSCTunnelVisionReducedWithBinoculars));
}
}
}
// HEADROCK HAM 3.2: Further increase tunnel-vision for cowering characters.
// SANDRO - this calls many sub-functions over and over, we should at least skip this for civilians and such
if ((gGameExternalOptions.ubCoweringReducesSightRange == 1 || gGameExternalOptions.ubCoweringReducesSightRange == 3) &&
IS_MERC_BODY_TYPE(pSoldier) && (pSoldier->bTeam == ENEMY_TEAM || pSoldier->bTeam == MILITIA_TEAM || pSoldier->bTeam == gbPlayerNum) )
{
INT8 bTolerance = CalcSuppressionTolerance( pSoldier );
// Make sure character is cowering.
if ( pSoldier->aiData.bShock >= bTolerance && gGameExternalOptions.ubMaxSuppressionShock > 0 &&
bonus < 100 )
{
// Calculates a "Flat" tunnel vision percentage
UINT8 ubNormalCoweringTunnelVision = (100 * pSoldier->aiData.bShock) / gGameExternalOptions.ubMaxSuppressionShock;
// Apply that percentage to the current tunnel vision
UINT16 usActualCoweringTunnelVision = bonus + (((100-bonus) * ubNormalCoweringTunnelVision) / 100);
// At shock 0, tunnel vision remains unchanged. At full shock, tunnel vision is full (100%)
bonus = __min(100,usActualCoweringTunnelVision);
}
}
if ( PTR_OURTEAM ) // Madd: adjust tunnel vision by difficulty level
return( bonus );
else
return bonus / gGameOptions.ubDifficultyLevel;
}
BOOLEAN HasThermalOptics( SOLDIERTYPE * pSoldier )
{
//ADB and AXP 28.03.2007: CtH bug fix: We also want to check on a firing weapon, "raised" alone is not enough ;)
bool usingGunScope = WeaponReady(pSoldier);
for (int i = BODYPOSSTART; i < BODYPOSFINAL; i++)
{
if (pSoldier->inv[i].exists() == true) {
if ( (i == HANDPOS || i == SECONDHANDPOS) &&
(Item[pSoldier->inv[i].usItem].usItemClass & IC_ARMOUR || Item[pSoldier->inv[i].usItem].usItemClass & IC_FACE ))
{
continue;
}
if (!IsWeapon(pSoldier->inv[i].usItem) || (IsWeapon(pSoldier->inv[i].usItem) && usingGunScope == true) )
{
if (Item[pSoldier->inv[i].usItem].thermaloptics)
return TRUE;
}
}
}
// Snap: check only attachments on a raised weapon!
if ( usingGunScope == true )
{
OBJECTTYPE* pObj = &pSoldier->inv[HANDPOS];
if (pObj->exists() == true) {
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if ( Item[iter->usItem].thermaloptics && iter->exists() )
return TRUE;
}
}
}
return( FALSE );
}
INT8 FindHearingAid( SOLDIERTYPE * pSoldier )
{
for (INT8 i = BODYPOSSTART; i < BODYPOSFINAL; i++)
{
if (pSoldier->inv[i].exists() == true) {
if ( (i == HANDPOS || i == SECONDHANDPOS) &&
(Item[pSoldier->inv[i].usItem].usItemClass & IC_ARMOUR || Item[pSoldier->inv[i].usItem].usItemClass & IC_FACE ))
{
continue;
}
if ( Item[pSoldier->inv[i].usItem].hearingrangebonus > 0 )
{
return( i );
}
}
}
return( NO_SLOT );
}
INT16 GetHearingRangeBonus( SOLDIERTYPE * pSoldier )
{
INT16 bonus = 0;
for (int i = BODYPOSSTART; i < BODYPOSFINAL; i++)
{
if (pSoldier->inv[i].exists() == true) {
if ( (i == HANDPOS || i == SECONDHANDPOS) &&
(Item[pSoldier->inv[i].usItem].usItemClass & IC_ARMOUR || Item[pSoldier->inv[i].usItem].usItemClass & IC_FACE ))
{
continue;
}
bonus += BonusReduceMore( Item[pSoldier->inv[i].usItem].hearingrangebonus, pSoldier->inv[i][0]->data.objectStatus );
}
}
return( bonus );
}
BOOLEAN IsDuckbill( OBJECTTYPE * pObj )
{
if (pObj->exists() == true) {
if (Item[pObj->usItem].duckbill || Item[(*pObj)[0]->data.gun.usGunAmmoItem].duckbill )
return TRUE;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if (Item[iter->usItem].duckbill && iter->exists() )
{
return( TRUE );
}
}
}
return( FALSE );
}
UINT16 GetPercentNoiseVolume( OBJECTTYPE * pObj )
{
UINT16 mod = 0;
if (pObj->exists() == true) {
mod = 100 - BonusReduce( Item[pObj->usItem].percentnoisereduction, (*pObj)[0]->data.objectStatus );
mod = mod * ( 100 - Item[(*pObj)[0]->data.gun.usGunAmmoItem].percentnoisereduction ) / 100;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists())
mod = mod * ( 100 - BonusReduce( Item[iter->usItem].percentnoisereduction, (*iter)[0]->data.objectStatus ) ) / 100;
}
}
return (mod > 0) ? mod : 0;
}
INT8 FindGasMask( SOLDIERTYPE * pSoldier )
{
INT8 bLoop;
for (bLoop = 0; bLoop < NUM_INV_SLOTS; bLoop++)//dnl ch40 041009
{
if (pSoldier->inv[bLoop].exists() == true) {
if ( Item[pSoldier->inv[bLoop].usItem].gasmask )
{
return( bLoop );
}
}
}
return( NO_SLOT );
}
BOOLEAN IsDetonatorAttached( OBJECTTYPE * pObj )
{
if (pObj->exists() == true) {
//if (Item[pObj->usItem].detonator)
// return TRUE;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if (Item[iter->usItem].detonator && iter->exists() )
{
return( TRUE );
}
}
}
return( FALSE );
}
BOOLEAN IsRemoteDetonatorAttached( OBJECTTYPE * pObj )
{
if (pObj->exists() == true) {
//if (Item[pObj->usItem].remotedetonator)
// return TRUE;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if (Item[iter->usItem].remotedetonator && iter->exists() )
{
return( TRUE );
}
}
}
return( FALSE );
}
BOOLEAN IsFlashSuppressor( OBJECTTYPE * pObj, SOLDIERTYPE * pSoldier )
{
if (pObj->exists() == true) {
//Madd: tracers automatically negate any muzzle flash suppression due to inherent lighting effects
if (Item[pObj->usItem].usItemClass == IC_GUN && AmmoTypes[(*pObj)[0]->data.gun.ubGunAmmoType].tracerEffect && pSoldier->bDoBurst )
return FALSE;
if (Item[pObj->usItem].hidemuzzleflash )
return TRUE;
if ( Item[(*pObj)[0]->data.gun.usGunAmmoItem].hidemuzzleflash )
return TRUE;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if (Item[iter->usItem].hidemuzzleflash && iter->exists() )
{
return( TRUE );
}
}
}
return( FALSE );
}
INT16 GetFlashSuppressorStatus( OBJECTTYPE * pObj )
{
INT16 p=100;
if (pObj->exists() == true) {
if (Item[pObj->usItem].hidemuzzleflash )
p=(*pObj)[0]->data.objectStatus;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if (Item[iter->usItem].hidemuzzleflash && iter->exists() )
{
p =p+ (*iter)[0]->data.objectStatus;
}
}
}
p = min(p,100);
return p;
}
BOOLEAN IsGrenadeLauncherAttached( OBJECTTYPE * pObj, UINT8 subObject )
{
if (pObj->exists() == true) {
if (Item[pObj->usItem].grenadelauncher )
return TRUE;
for (attachmentList::iterator iter = (*pObj)[subObject]->attachments.begin(); iter != (*pObj)[subObject]->attachments.end(); ++iter) {
if (Item[iter->usItem].grenadelauncher && iter->exists() )
{
return TRUE;
}
}
}
return FALSE;
}
OBJECTTYPE* FindAttachment_GrenadeLauncher( OBJECTTYPE * pObj )
{
if (pObj->exists() == true) {
if (Item[pObj->usItem].grenadelauncher )
return pObj;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if (Item[iter->usItem].grenadelauncher && iter->exists() )
{
return( &(*iter) );
}
}
}
return( 0 );
}
INT16 GetGrenadeLauncherStatus( OBJECTTYPE * pObj )
{
if (pObj->exists() == true) {
if (Item[pObj->usItem].grenadelauncher )
return (*pObj)[0]->data.objectStatus;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if (Item[iter->usItem].grenadelauncher && iter->exists())
{
return( (*iter)[0]->data.objectStatus );
}
}
}
return( ITEM_NOT_FOUND );
}
UINT16 GetAttachedGrenadeLauncher( OBJECTTYPE * pObj )
{
if (pObj->exists() == true) {
if (Item[pObj->usItem].grenadelauncher )
return pObj->usItem;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if (Item[iter->usItem].grenadelauncher && iter->exists())
{
return( (UINT16) Item[iter->usItem].uiIndex );
}
}
}
return( NONE );
}
INT16 GetAttachedArmourBonus( OBJECTTYPE * pObj )
{
INT16 bonus=0;
if (pObj->exists() == true) {
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists()){
bonus += BonusReduce( Armour[Item[iter->usItem].ubClassIndex].ubProtection,
(*iter)[0]->data.objectStatus );
}
}
}
return( bonus );
}
INT16 GetBulletSpeedBonus( OBJECTTYPE * pObj )
{
INT16 bonus = 0;
if (pObj->exists() == true) {
bonus = Item[pObj->usItem].bulletspeedbonus ;
bonus += Item[(*pObj)[0]->data.gun.usGunAmmoItem].bulletspeedbonus ;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists())
bonus = bonus +Item[iter->usItem].bulletspeedbonus ;
}
}
return( bonus );
}
BOOLEAN EXPLOSIVE_GUN ( UINT16 x)
{
//DebugMsg(TOPIC_JA2,DBG_LEVEL_3,String("EXPLOSIVE_GUN x = %d",x));
if ( Item[x].rocketlauncher || Item[x].cannon )
return TRUE;
else
return FALSE;
}
INT8 FindRocketLauncherOrCannon( SOLDIERTYPE * pSoldier )
{
INT8 bLoop;
for (bLoop = 0; bLoop < (INT8) pSoldier->inv.size(); bLoop++)
{
if (pSoldier->inv[bLoop].exists() == true) {
if (Item[pSoldier->inv[bLoop].usItem].rocketlauncher || Item[pSoldier->inv[bLoop].usItem].cannon )
{
return( bLoop );
}
}
}
return( NO_SLOT );
}
INT8 FindRocketLauncher( SOLDIERTYPE * pSoldier )
{
INT8 bLoop;
for (bLoop = 0; bLoop < (INT8) pSoldier->inv.size(); bLoop++)
{
if (pSoldier->inv[bLoop].exists() == true) {
if (Item[pSoldier->inv[bLoop].usItem].rocketlauncher )
{
return( bLoop );
}
}
}
return( NO_SLOT );
}
INT8 FindCannon( SOLDIERTYPE * pSoldier )
{
INT8 bLoop;
for (bLoop = 0; bLoop < (INT8) pSoldier->inv.size(); bLoop++)
{
if (pSoldier->inv[bLoop].exists() == true) {
if ( Item[pSoldier->inv[bLoop].usItem].cannon )
{
return( bLoop );
}
}
}
return( NO_SLOT );
}
INT8 FindUsableCrowbar( SOLDIERTYPE * pSoldier )
{
INT8 bLoop;
for (bLoop = 0; bLoop < (INT8) pSoldier->inv.size(); bLoop++)
{
if (pSoldier->inv[bLoop].exists() == true) {
if ( Item[pSoldier->inv[bLoop].usItem].crowbar && pSoldier->inv[bLoop][0]->data.objectStatus >= USABLE )
{
return( bLoop );
}
}
}
return( NO_SLOT );
}
OBJECTTYPE* FindAttachedBatteries( OBJECTTYPE * pObj )
{
if (pObj->exists() == true) {
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if (Item[iter->usItem].batteries && iter->exists())
{
return( &(*iter) );
}
}
}
return( 0 );
}
INT8 FindToolkit( SOLDIERTYPE * pSoldier )
{
INT8 bLoop;
for (bLoop = 0; bLoop < (INT8) pSoldier->inv.size(); bLoop++)
{
if (pSoldier->inv[bLoop].exists() == true) {
if (Item[pSoldier->inv[bLoop].usItem].toolkit )
{
return( bLoop );
}
}
}
return( NO_SLOT );
}
INT8 FindMedKit( SOLDIERTYPE * pSoldier )
{
INT8 bLoop;
for (bLoop = 0; bLoop < (INT8) pSoldier->inv.size(); bLoop++)
{
if (pSoldier->inv[bLoop].exists() == true) {
if (Item[pSoldier->inv[bLoop].usItem].medicalkit )
{
return( bLoop );
}
}
}
return( NO_SLOT );
}
INT8 FindFirstAidKit( SOLDIERTYPE * pSoldier )
{
INT8 bLoop;
for (bLoop = 0; bLoop < (INT8) pSoldier->inv.size(); bLoop++)
{
if (pSoldier->inv[bLoop].exists() == true) {
if (Item[pSoldier->inv[bLoop].usItem].firstaidkit )
{
return( bLoop );
}
}
}
return( NO_SLOT );
}
INT8 FindCamoKit( SOLDIERTYPE * pSoldier )
{
INT8 bLoop;
for (bLoop = 0; bLoop < (INT8) pSoldier->inv.size(); bLoop++)
{
if (pSoldier->inv[bLoop].exists() == true) {
if (Item[pSoldier->inv[bLoop].usItem].camouflagekit )
{
return( bLoop );
}
}
}
return( NO_SLOT );
}
INT8 FindLocksmithKit( SOLDIERTYPE * pSoldier )
{
INT8 bLoop;
for (bLoop = 0; bLoop < (INT8) pSoldier->inv.size(); bLoop++)
{
if (pSoldier->inv[bLoop].exists() == true) {
if (Item[pSoldier->inv[bLoop].usItem].locksmithkit )
{
return( bLoop );
}
}
}
return( NO_SLOT );
}
INT8 FindWalkman( SOLDIERTYPE * pSoldier )
{
INT8 bLoop;
for (bLoop = BODYPOSSTART; bLoop < BODYPOSFINAL; bLoop++)
{
if (pSoldier->inv[bLoop].exists() == true) {
if (Item[pSoldier->inv[bLoop].usItem].walkman )
{
return( bLoop );
}
}
}
return( NO_SLOT );
}
INT8 FindTrigger( SOLDIERTYPE * pSoldier )
{
INT8 bLoop;
for (bLoop = 0; bLoop < (INT8) pSoldier->inv.size(); bLoop++)
{
if (pSoldier->inv[bLoop].exists() == true) {
if (Item[pSoldier->inv[bLoop].usItem].remotetrigger )
{
return( bLoop );
}
}
}
return( NO_SLOT );
}
INT8 FindRemoteControl( SOLDIERTYPE * pSoldier )
{
INT8 bLoop;
for (bLoop = BODYPOSSTART; bLoop < BODYPOSFINAL; bLoop++)
{
if (pSoldier->inv[bLoop].exists() == true) {
if (Item[pSoldier->inv[bLoop].usItem].robotremotecontrol )
{
return( bLoop );
}
}
}
return( NO_SLOT );
}
UINT16 LowestLaunchableCoolness(UINT16 launcherIndex)
{
UINT16 i = 0;
UINT16 lowestCoolness = 999;
for( i = 0; i < MAXITEMS; i++ )
{
if ( Item[i].usItemClass == 0 )
break;
if( ValidLaunchable( i, launcherIndex ) && ItemIsLegal(i) && Item[i].ubCoolness <= lowestCoolness )
{
lowestCoolness = Item[i].ubCoolness;
}
}
return lowestCoolness;
}
UINT16 PickARandomLaunchable(UINT16 itemIndex)
{
UINT16 usNumMatches = 0;
UINT16 usRandom = 0;
UINT16 i = 0;
UINT16 lowestCoolness = LowestLaunchableCoolness(itemIndex);
//DebugMsg (TOPIC_JA2,DBG_LEVEL_3,String("PickARandomLaunchable: itemIndex = %d", itemIndex));
// WANNE: This should fix the hang on the merc positioning screen (fix by Razer)
//while( !usNumMatches )
{ //Count the number of valid launchables
for( i = 0; i < MAXITEMS; i++ )
{
if ( Item[i].usItemClass == 0 )
break;
//Madd: quickfix: make it not choose best grenades right away.
if( ValidLaunchable( i, itemIndex ) && ItemIsLegal(i) && Item[i].ubCoolness <= max(HighestPlayerProgressPercentage()/10,lowestCoolness) )
usNumMatches++;
}
}
if( usNumMatches )
{
usRandom = (UINT16)Random( usNumMatches );
for( i = 0; i < MAXITEMS; i++ )
{
if ( Item[i].usItemClass == 0 )
break;
if( ValidLaunchable( i, itemIndex ) && ItemIsLegal(i) && Item[i].ubCoolness <= max(HighestPlayerProgressPercentage()/10,lowestCoolness) )
{
if( usRandom )
usRandom--;
else
{
return i;
}
}
}
}
return 0;
}
INT16 GetCamoBonus( OBJECTTYPE * pObj )
{
INT16 bonus = 0;
if ( pObj->exists() == true ) {
bonus = (Item[pObj->usItem].camobonus);// * (WEAPON_STATUS_MOD((*pObj)[0]->data.objectStatus) / 100)) ;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if (!Item[iter->usItem].camouflagekit && iter->exists())
bonus += (INT16) (Item[iter->usItem].camobonus);// * (WEAPON_STATUS_MOD((*iter)[0]->data.objectStatus) / 100));
}
}
return( bonus );
}
INT16 GetUrbanCamoBonus( OBJECTTYPE * pObj )
{
INT16 bonus = 0;
if ( pObj->exists() == true ) {
bonus = (Item[pObj->usItem].urbanCamobonus);// * (WEAPON_STATUS_MOD((*pObj)[0]->data.objectStatus) / 100)) ;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if (!Item[iter->usItem].camouflagekit && iter->exists())
bonus += (INT16) (Item[iter->usItem].urbanCamobonus);// * (WEAPON_STATUS_MOD((*iter)[0]->data.objectStatus) / 100));
}
}
return( bonus );
}
INT16 GetDesertCamoBonus( OBJECTTYPE * pObj )
{
INT16 bonus = 0;
if ( pObj->exists() == true ) {
bonus = (Item[pObj->usItem].desertCamobonus);// * (WEAPON_STATUS_MOD((*pObj)[0]->data.objectStatus) / 100)) ;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if (!Item[iter->usItem].camouflagekit && iter->exists())
bonus += (INT16) (Item[iter->usItem].desertCamobonus);// * (WEAPON_STATUS_MOD((*iter)[0]->data.objectStatus) / 100));
}
}
return( bonus );
}
INT16 GetSnowCamoBonus( OBJECTTYPE * pObj )
{
INT16 bonus = 0;
if ( pObj->exists() == true ) {
bonus = (Item[pObj->usItem].snowCamobonus);// * (WEAPON_STATUS_MOD((*pObj)[0]->data.objectStatus) / 100)) ;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if (!Item[iter->usItem].camouflagekit && iter->exists())
bonus += (INT16) (Item[iter->usItem].snowCamobonus);// * (WEAPON_STATUS_MOD((*iter)[0]->data.objectStatus) / 100));
}
}
return( bonus );
}
INT16 GetWornCamo( SOLDIERTYPE * pSoldier )
{
INT8 bLoop;
INT16 ttl=0;
for (bLoop = HELMETPOS; bLoop <= LEGPOS; bLoop++)
{
if ( pSoldier->inv[bLoop].exists() == true )
{
ttl += GetCamoBonus(&pSoldier->inv[bLoop]);
}
}
// CHRISL: Add additional loop for LBE items while using new inventory system
if((UsingNewInventorySystem() == true))
{
for (bLoop = VESTPOCKPOS; bLoop <= BPACKPOCKPOS; bLoop++)
{
if ( pSoldier->inv[bLoop].exists() == true )
ttl += GetCamoBonus(&pSoldier->inv[bLoop]);
//CHRISL: to prevent camo overlap, don't count armor vest camo if we're weaing an LBE vest that grants a bonus
if(bLoop == VESTPOCKPOS && pSoldier->inv[VESTPOS].exists() == true && Item[pSoldier->inv[bLoop].usItem].camobonus > 0)
{
ttl -= Item[pSoldier->inv[VESTPOS].usItem].camobonus;
}
}
}
return __min( ttl, 100 );
}
INT16 GetWornUrbanCamo( SOLDIERTYPE * pSoldier )
{
INT8 bLoop;
INT16 ttl=0;
for (bLoop = HELMETPOS; bLoop <= LEGPOS; bLoop++)
{
if ( pSoldier->inv[bLoop].exists() == true )
ttl += GetUrbanCamoBonus(&pSoldier->inv[bLoop]);
}
// CHRISL: Add additional loop for LBE items while using new inventory system
if((UsingNewInventorySystem() == true))
{
for (bLoop = VESTPOCKPOS; bLoop <= BPACKPOCKPOS; bLoop++)
{
if ( pSoldier->inv[bLoop].exists() == true )
ttl += GetUrbanCamoBonus(&pSoldier->inv[bLoop]);
}
}
return __min( ttl, 100 );
}
INT16 GetWornDesertCamo( SOLDIERTYPE * pSoldier )
{
INT8 bLoop;
INT16 ttl=0;
for (bLoop = HELMETPOS; bLoop <= LEGPOS; bLoop++)
{
if ( pSoldier->inv[bLoop].exists() == true )
ttl += GetDesertCamoBonus(&pSoldier->inv[bLoop]);
}
// CHRISL: Add additional loop for LBE items while using new inventory system
if((UsingNewInventorySystem() == true))
{
for (bLoop = VESTPOCKPOS; bLoop <= BPACKPOCKPOS; bLoop++)
{
if ( pSoldier->inv[bLoop].exists() == true )
ttl += GetDesertCamoBonus(&pSoldier->inv[bLoop]);
}
}
return __min( ttl, 100 );
}
INT16 GetWornSnowCamo( SOLDIERTYPE * pSoldier )
{
INT8 bLoop;
INT16 ttl=0;
for (bLoop = HELMETPOS; bLoop <= LEGPOS; bLoop++)
{
if ( pSoldier->inv[bLoop].exists() == true )
ttl += GetSnowCamoBonus(&pSoldier->inv[bLoop]);
}
// CHRISL: Add additional loop for LBE items while using new inventory system
if((UsingNewInventorySystem() == true))
{
for (bLoop = VESTPOCKPOS; bLoop <= BPACKPOCKPOS; bLoop++)
{
if ( pSoldier->inv[bLoop].exists() == true )
ttl += GetSnowCamoBonus(&pSoldier->inv[bLoop]);
}
}
return __min( ttl, 100 );
}
void ApplyEquipmentBonuses(SOLDIERTYPE * pSoldier)
{
if ( pSoldier == NULL) return;
INT16 newCamo = GetWornCamo ( pSoldier );
INT16 oldCamo = pSoldier->wornCamo;
if ( oldCamo != newCamo )
pSoldier->wornCamo = (INT8)newCamo;
INT16 newUrbanCamo = GetWornUrbanCamo ( pSoldier );
INT16 oldUrbanCamo = pSoldier->wornUrbanCamo;
if ( oldUrbanCamo != newUrbanCamo )
pSoldier->wornUrbanCamo = (INT8)newUrbanCamo;
INT16 newDesertCamo = GetWornDesertCamo ( pSoldier );
INT16 oldDesertCamo = pSoldier->wornDesertCamo;
if ( oldDesertCamo != newDesertCamo )
pSoldier->wornDesertCamo = (INT8)newDesertCamo;
INT16 newSnowCamo = GetWornSnowCamo ( pSoldier );
INT16 oldSnowCamo = pSoldier->wornSnowCamo;
if ( oldSnowCamo != newSnowCamo )
pSoldier->wornSnowCamo = (INT8)newSnowCamo;
if ( (newCamo > oldCamo || newUrbanCamo > oldUrbanCamo || newDesertCamo > oldDesertCamo || newSnowCamo > oldSnowCamo )&& pSoldier->bTeam == OUR_TEAM )
{
//CHRISL: This sound interferes with some RPC hiring in NewInv because of the camo bonus some LBE Vests give
if(UsingNewInventorySystem() == false)
pSoldier->DoMercBattleSound( BATTLE_SOUND_COOL1 );
// WANNE: Only call the method if oldCame != newCamo
if ( pSoldier->bInSector)
pSoldier->CreateSoldierPalettes( );
}
else if ( (newCamo < oldCamo || newUrbanCamo < oldUrbanCamo || newDesertCamo < oldDesertCamo || newSnowCamo < oldSnowCamo )&& pSoldier->bTeam == OUR_TEAM )
{
// WANNE: Only call the method if oldCame != newCamo
if ( pSoldier->bInSector)
pSoldier->CreateSoldierPalettes( );
}
// WANNE: Madd, I commented this, because this leads to IRAs INVISIBLE BUG!
// We should only call the CreateSoldierPalettes if oldCamo != newCamo. See above!
//Madd: do this regardless of camo. This will need to be called to do custom part colours and new overlays anyway.
//if ( pSoldier->bInSector)
// pSoldier->CreateSoldierPalettes( );
// WANNE: I disabled the call, because it leeds to endless loop when examining doors with explosives!
/*
// This should fix the bug and crashes with missing faces
if (SetCamoFace( pSoldier ))
{
DeleteSoldierFace( pSoldier );// remove face
pSoldier->iFaceIndex = InitSoldierFace( pSoldier );// create new face
}
*/
fInterfacePanelDirty = DIRTYLEVEL2;
}
UINT16 GetFirstExplosiveOfType(UINT16 expType)
{
for (int i=0;i<MAXITEMS;i++)
{
if ( (Item[i].usItemClass == IC_EXPLOSV || Item[i].usItemClass == IC_GRENADE) && Explosive[Item[i].ubClassIndex].ubType == expType )
return i;
}
return 0;
}
// WDS - Smart goggle switching
OBJECTTYPE* FindSunGogglesInInv( SOLDIERTYPE * pSoldier, INT8 * bSlot, BOOLEAN * isAttach, BOOLEAN searchAllInventory )
{
INT8 bLoop;
INT16 bonusToBeat = 0;
OBJECTTYPE* pGoggles = 0;
// CHRISL:
// silversurfer: use the sum of day vision bonus and bright light bonus because both help at daytime
// but make sure that day vision bonus is > 0 because we are not always looking at bright lights
for (bLoop = (searchAllInventory ? HELMETPOS : HANDPOS); bLoop < NUM_INV_SLOTS; bLoop++) {
if ( pSoldier->inv[bLoop].exists() == true ) {
if ( Item[pSoldier->inv[bLoop].usItem].dayvisionrangebonus > 0 &&
( Item[pSoldier->inv[bLoop].usItem].dayvisionrangebonus + Item[pSoldier->inv[bLoop].usItem].brightlightvisionrangebonus ) > bonusToBeat &&
Item[pSoldier->inv[bLoop].usItem].usItemClass == IC_FACE ) {
pGoggles = &(pSoldier->inv[bLoop]);
*bSlot = bLoop;
*isAttach = FALSE;
bonusToBeat = Item[pSoldier->inv[bLoop].usItem].dayvisionrangebonus + Item[pSoldier->inv[bLoop].usItem].brightlightvisionrangebonus;
}
if (searchAllInventory) {
for (UINT8 loop = 0; loop < pSoldier->inv[bLoop].ubNumberOfObjects; loop ++){
for (attachmentList::iterator iter = pSoldier->inv[bLoop][loop]->attachments.begin(); iter != pSoldier->inv[bLoop][loop]->attachments.end(); ++iter) {
if ( iter->exists() && Item[ iter->usItem ].dayvisionrangebonus > 0 &&
( Item[ iter->usItem ].dayvisionrangebonus + Item[ iter->usItem ].brightlightvisionrangebonus ) > bonusToBeat &&
Item[ iter->usItem ].usItemClass == IC_FACE ) {
pGoggles = &(*iter);
*bSlot = bLoop;
*isAttach = TRUE;
bonusToBeat = Item[ iter->usItem ].dayvisionrangebonus + Item[ iter->usItem ].brightlightvisionrangebonus;
}
}
}
}
}
}
return( pGoggles );
}
OBJECTTYPE* FindNightGogglesInInv( SOLDIERTYPE * pSoldier, INT8 * bSlot, BOOLEAN * isAttach, BOOLEAN searchAllInventory )
{
INT8 bLoop;
INT16 bonusToBeat = 0;
OBJECTTYPE* pGoggles = 0;
// CHRISL:
// silversurfer: check if we are above ground, night vision is only useful there
if ( pSoldier->bSectorZ == 0 )
{
for (bLoop = (searchAllInventory ? HELMETPOS : HANDPOS); bLoop < NUM_INV_SLOTS; bLoop++) {
if ( pSoldier->inv[bLoop].exists() == true ) {
if (Item[pSoldier->inv[bLoop].usItem].nightvisionrangebonus > bonusToBeat && Item[pSoldier->inv[bLoop].usItem].usItemClass == IC_FACE ) {
pGoggles = &(pSoldier->inv[bLoop]);
*bSlot = bLoop;
*isAttach = FALSE;
bonusToBeat = Item[pSoldier->inv[bLoop].usItem].nightvisionrangebonus;
}
if (searchAllInventory) {
for (UINT8 loop = 0; loop < pSoldier->inv[bLoop].ubNumberOfObjects; loop ++){
for (attachmentList::iterator iter = pSoldier->inv[bLoop][loop]->attachments.begin(); iter != pSoldier->inv[bLoop][loop]->attachments.end(); ++iter) {
if ( iter->exists() && Item[ iter->usItem ].nightvisionrangebonus > bonusToBeat && Item[ iter->usItem ].usItemClass == IC_FACE ) {
pGoggles = &(*iter);
*bSlot = bLoop;
*isAttach = TRUE;
bonusToBeat = Item[ iter->usItem ].nightvisionrangebonus;
}
}
}
}
}
}
}
// below ground we need cave vision
else
{
for (bLoop = (searchAllInventory ? HELMETPOS : HANDPOS); bLoop < NUM_INV_SLOTS; bLoop++) {
if ( pSoldier->inv[bLoop].exists() == true ) {
if (Item[pSoldier->inv[bLoop].usItem].cavevisionrangebonus > bonusToBeat && Item[pSoldier->inv[bLoop].usItem].usItemClass == IC_FACE ) {
pGoggles = &(pSoldier->inv[bLoop]);
*bSlot = bLoop;
*isAttach = FALSE;
bonusToBeat = Item[pSoldier->inv[bLoop].usItem].cavevisionrangebonus;
}
if (searchAllInventory) {
for (UINT8 loop = 0; loop < pSoldier->inv[bLoop].ubNumberOfObjects; loop ++){
for (attachmentList::iterator iter = pSoldier->inv[bLoop][loop]->attachments.begin(); iter != pSoldier->inv[bLoop][loop]->attachments.end(); ++iter) {
if ( Item[ iter->usItem ].cavevisionrangebonus > bonusToBeat && Item[ iter->usItem ].usItemClass == IC_FACE && iter->exists() ) {
pGoggles = &(*iter);
*bSlot = bLoop;
*isAttach = TRUE;
bonusToBeat = Item[ iter->usItem ].cavevisionrangebonus;
}
}
}
}
}
}
}
return( pGoggles );
}
FLOAT GetHighestScopeMagnificationFactor( OBJECTTYPE * pObj )
{
FLOAT BestFactor = 1.0;
if ( pObj->exists() == true && UsingNewCTHSystem() == true ) {
BestFactor = Item[pObj->usItem].scopemagfactor;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter)
{
if (iter->exists())
{
BestFactor = __max(BestFactor, Item[iter->usItem].scopemagfactor);
}
}
}
return( BestFactor );
}
INT16 GetMinRangeForAimBonus( OBJECTTYPE * pObj )
{
INT16 bonus = 0;
if ( pObj->exists() == true ) {
bonus = Item[pObj->usItem].minrangeforaimbonus;
//bonus += Item[(*pObj)[0]->data.gun.usGunAmmoItem].minrangeforaimbonus;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
bonus += Item[iter->usItem].minrangeforaimbonus;
}
}
return( bonus );
}
FLOAT GetScopeMagnificationFactor( OBJECTTYPE * pObj, FLOAT uiRange )
{
FLOAT BestFactor = 1.0;
FLOAT CurrentFactor = 0.0;
FLOAT TargetMagFactor = __max(1.0f,(FLOAT)uiRange / (FLOAT)gGameCTHConstants.NORMAL_SHOOTING_DISTANCE);
FLOAT rangeModifier = gGameCTHConstants.SCOPE_RANGE_MULTIPLIER;
TargetMagFactor = TargetMagFactor / rangeModifier;
if(pObj->exists() == true && UsingNewCTHSystem() == true)
{
BestFactor = __max(1.0f, Item[pObj->usItem].scopemagfactor);
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter)
{
if(iter->exists() == true)
{
if(BestFactor == 1.0f)
BestFactor = __max(BestFactor, Item[iter->usItem].scopemagfactor);
else if(Item[iter->usItem].scopemagfactor >= TargetMagFactor)
BestFactor = Item[iter->usItem].scopemagfactor;
}
}
}
return __max(1.0f, BestFactor);
}
FLOAT GetBestScopeMagnificationFactor( SOLDIERTYPE *pSoldier, OBJECTTYPE * pObj, FLOAT uiRange )
{
FLOAT BestFactor = 1.0;
FLOAT TargetMagFactor = __max(1.0f,uiRange / (FLOAT)gGameCTHConstants.NORMAL_SHOOTING_DISTANCE);
FLOAT CurrentFactor = 0.0;
FLOAT ActualCurrentFactor = 0.0;
INT32 iCurrentTotalPenalty = 0;
INT32 iBestTotalPenalty = 0;
FLOAT rangeModifier = GetScopeRangeMultiplier(pSoldier, pObj, uiRange);
FLOAT iProjectionFactor = CalcProjectionFactor(pSoldier, pObj, uiRange, 1);
if (TargetMagFactor <= 1.0f)
{
// Target is at Iron Sights range. No scope is required.
return 1.0f;
}
if ( pObj->exists() == true && UsingNewCTHSystem() == true )
{
// Real Scope Magnification Factor from the item
CurrentFactor = __max(1.0f, Item[pObj->usItem].scopemagfactor);
if (CurrentFactor > 1.0f)
{
// Actual Scope Mag Factor is what we get at the distance the target's at.
ActualCurrentFactor = __min(CurrentFactor, (TargetMagFactor/rangeModifier));
if (ActualCurrentFactor >= CurrentFactor)
{
// This scope gives no penalty. Record this as the best factor found so far.
BestFactor = CurrentFactor;
iBestTotalPenalty = 0;
}
else
{
// This scopes gives a penalty for shooting under its range.
FLOAT dScopePenaltyRatio = (CurrentFactor * rangeModifier / TargetMagFactor);
INT32 iScopePenalty = (INT32)((dScopePenaltyRatio * gGameCTHConstants.AIM_TOO_CLOSE_SCOPE) * (CurrentFactor / 2));
// There's no previous scope to compare with so record this as the best factor for now.
BestFactor = CurrentFactor;
iBestTotalPenalty = iScopePenalty;
}
}
// Now perform the same process for each scope installed on the item. The difference is, we also compare to
// BestTotalPenalty to find the scope that gives the least penalty compared to its bonus.
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter)
{
if (iter->exists() && Item[iter->usItem].scopemagfactor > 1.0f)
{
// Real Scope Magnification Factor from the item
CurrentFactor = __max(1.0f, Item[iter->usItem].scopemagfactor);
// Actual Scope Mag Factor is what we get at the distance the target's at.
ActualCurrentFactor = __min(CurrentFactor, (TargetMagFactor/rangeModifier));
if (ActualCurrentFactor >= CurrentFactor)
{
// This scope gives no penalty. Is it any better than the ones we've already processed?
if (iBestTotalPenalty >= 0 && CurrentFactor > BestFactor)
{
// This is the best scope we've found so far. Record it.
BestFactor = CurrentFactor;
iBestTotalPenalty = 0;
}
}
else
{
// This scope will give a penalty if used. Is it worth using compared to other scopes found?
FLOAT dScopePenaltyRatio = (CurrentFactor * rangeModifier / TargetMagFactor);
INT32 iScopePenalty = (INT32)((dScopePenaltyRatio * gGameCTHConstants.AIM_TOO_CLOSE_SCOPE) * (CurrentFactor / 2));
// Is this scope any better than the ones we've already processed?
if (iScopePenalty < iBestTotalPenalty)
{
// This is the best scope we've found so far. Record it.
BestFactor = CurrentFactor;
iBestTotalPenalty = iScopePenalty;
}
}
}
}
}
// Now that we have selected the best available scope, don't use it if we get a penalty and have a functional laser
if(iBestTotalPenalty < 0 && iProjectionFactor > 1.0f)
BestFactor = 1.0f;
return( __max(1.0f, BestFactor) );
}
// HEADROCK HAM 4: This function finds the best projection equipment (laser/reflex) on the weapon for a given range.
FLOAT GetProjectionFactor( OBJECTTYPE * pObj )
{
FLOAT BestFactor = 1.0;
if ( pObj->exists() == true && UsingNewCTHSystem() == true ) {
BestFactor = __max((FLOAT)Item[pObj->usItem].projectionfactor, 1.0f);
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter)
{
if (iter->exists())
{
BestFactor = __max(BestFactor, Item[iter->usItem].projectionfactor);
}
}
}
return( BestFactor );
}
FLOAT GetScopeRangeMultiplier( SOLDIERTYPE *pSoldier, OBJECTTYPE *pObj, FLOAT d2DDistance )
{
FLOAT iScopeFactor = 0;
FLOAT rangeModifier = gGameCTHConstants.SCOPE_RANGE_MULTIPLIER;
iScopeFactor = GetScopeMagnificationFactor( pObj, d2DDistance );
if( gGameOptions.fNewTraitSystem )
{
if(iScopeFactor > 5.0f)
rangeModifier -= (NUM_SKILL_TRAITS( pSoldier, SNIPER_NT ) * 0.05f);
else
rangeModifier -= (NUM_SKILL_TRAITS( pSoldier, RANGER_NT ) * 0.05f);
}
else
rangeModifier -= (NUM_SKILL_TRAITS( pSoldier, PROF_SNIPER_OT ) * 0.05f);
return rangeModifier;
}
UINT8 AllowedAimingLevelsNCTH( SOLDIERTYPE *pSoldier, INT32 sGridNo )
{
UINT8 aimLevels = 4;
FLOAT iScopeMagFactor = 0.0, rangeMultiplier = 0.0;
BOOLEAN allowed = TRUE;
UINT16 weaponRange;
UINT8 weaponType;
BOOLEAN fTwoHanded, fUsingBipod;
UINT32 uiRange = GetRangeInCellCoordsFromGridNoDiff( pSoldier->sGridNo, sGridNo );
rangeMultiplier = GetScopeRangeMultiplier(pSoldier, &pSoldier->inv[pSoldier->ubAttackingHand], (FLOAT)uiRange);
// HEADROCK HAM 4: This function has been radically altered AGAIN for the NCTH project.
// Weapons can now have a tag that defines how many aim clicks they should have. Under the NCTH
// system, weapons with FEWER aiming clicks are faster to aim without being any less accurate.
//
// If the weapon lacks a ubAimLevels tag, the program uses the old HAM 3 algorithm to figure
// out how much it should have using its class and range.
// Read from item
aimLevels = Weapon[pSoldier->inv[pSoldier->ubAttackingHand].usItem].ubAimLevels;
fTwoHanded = Item[pSoldier->inv[pSoldier->ubAttackingHand].usItem].twohanded;
weaponRange = Weapon[pSoldier->inv[pSoldier->ubAttackingHand].usItem].usRange + GetRangeBonus(&pSoldier->inv[pSoldier->ubAttackingHand]);
weaponType = Weapon[pSoldier->inv[pSoldier->ubAttackingHand].usItem].ubWeaponType;
fUsingBipod = FALSE;
// If outside limits...
if (aimLevels < 1 ||
aimLevels > 8 )
{
// Probably uninitialized. Run an algorithm instead.
// Read weapon data
// Define basic (no attachments), and absolute maximums
if (weaponType == GUN_PISTOL || weaponType == GUN_M_PISTOL || fTwoHanded == 0)
{
aimLevels = 2;
}
else if (weaponType == GUN_SHOTGUN || weaponType == GUN_LMG || weaponType == GUN_SMG)
{
aimLevels = 3;
}
else if ((weaponType == GUN_AS_RIFLE || weaponType == GUN_RIFLE ) && weaponRange <= 500)
{
aimLevels = 4;
}
else if (((weaponType == GUN_AS_RIFLE || weaponType == GUN_RIFLE) && weaponRange > 500) ||
(weaponType == GUN_SN_RIFLE && weaponRange <= 500))
{
aimLevels = 6;
}
else if (weaponType == GUN_SN_RIFLE && weaponRange > 500)
{
aimLevels = 8;
}
else
{
aimLevels = 4;
}
}
// HEADROCK HAM 4: This modifier from the weapon and its attachments replaces the generic bipod bonus.
aimLevels += GetAimLevelsModifier( &pSoldier->inv[pSoldier->ubAttackingHand], gAnimControl[ pSoldier->usAnimState ].ubHeight );
aimLevels += GetAimLevelsTraitModifier( pSoldier, &pSoldier->inv[pSoldier->ubAttackingHand]);
aimLevels = __max(1, aimLevels);
aimLevels = __min(8, aimLevels);
return aimLevels;
}
UINT8 AllowedAimingLevels(SOLDIERTYPE * pSoldier, INT32 sGridNo)
{
if(UsingNewCTHSystem() == true)
return AllowedAimingLevelsNCTH(pSoldier, sGridNo);
// SANDRO was here - changed a few things around
UINT8 aimLevels = 4;
UINT16 sScopeBonus = 0;
BOOLEAN allowed = TRUE;
UINT8 weaponType;
INT32 uiRange = GetRangeInCellCoordsFromGridNoDiff( pSoldier->sGridNo, sGridNo );
weaponType = Weapon[pSoldier->inv[pSoldier->ubAttackingHand].usItem].ubWeaponType;
if ( gGameExternalOptions.fAimLevelRestriction ) // Extra aiming on/off
{
// HEADROCK HAM B2.6: Dynamic aiming level restrictions based on gun type and attachments.
// HEADROCK HAM 3.5: Revamped this - it was illogically constructed.
if ( gGameExternalOptions.fDynamicAimingTime )
{
// SANDRO - throwing knives are a special case, allow two aiming clicks for them
if( weaponType == NOT_GUN )
{
if ( Item[pSoldier->inv[pSoldier->ubAttackingHand].usItem].usItemClass == IC_THROWING_KNIFE )
{
aimLevels = 2;
if ( gGameOptions.fNewTraitSystem && HAS_SKILL_TRAIT( pSoldier, THROWING_NT ) )
{
aimLevels += gSkillTraitValues.ubTHBladesAimClicksAdded;
}
return ( min(6, aimLevels) );
}
else
{
return ( 2 );
}
}
UINT16 weaponRange;
UINT8 maxAimForType, maxAimWithoutBipod;
BOOLEAN fTwoHanded, fUsingBipod;
// Read weapon data
fTwoHanded = Item[pSoldier->inv[pSoldier->ubAttackingHand].usItem].twohanded;
UINT16 usRange = GetModifiedGunRange(pSoldier->inv[pSoldier->ubAttackingHand].usItem);
weaponRange = usRange + GetRangeBonus(&pSoldier->inv[pSoldier->ubAttackingHand]);
fUsingBipod = FALSE;
maxAimWithoutBipod = 4;
// Define basic (no attachments), and absolute maximums
if (weaponType == GUN_PISTOL || weaponType == GUN_M_PISTOL )
{
maxAimForType = 2;
aimLevels = 1;
maxAimWithoutBipod = 2;
// SANDRO - STOMP traits - Gunslinger bonus aim clicks
if ( gGameOptions.fNewTraitSystem && HAS_SKILL_TRAIT( pSoldier, GUNSLINGER_NT ) )
{
maxAimForType += (gSkillTraitValues.ubGSAimClicksAdded * NUM_SKILL_TRAITS( pSoldier, GUNSLINGER_NT ));
aimLevels += (gSkillTraitValues.ubGSAimClicksAdded * NUM_SKILL_TRAITS( pSoldier, GUNSLINGER_NT ));
maxAimWithoutBipod += (gSkillTraitValues.ubGSAimClicksAdded * NUM_SKILL_TRAITS( pSoldier, GUNSLINGER_NT ));
}
}
else if ((weaponType == GUN_SMG && fTwoHanded == 0) || fTwoHanded == 0)
{
maxAimForType = 2;
aimLevels = 1;
maxAimWithoutBipod = 2;
}
else if (weaponType == GUN_SHOTGUN || weaponType == GUN_LMG || (weaponType == GUN_SMG && fTwoHanded == 1))
{
maxAimForType = 3;
aimLevels = 2;
maxAimWithoutBipod = 3;
}
else if ((weaponType == GUN_AS_RIFLE || weaponType == GUN_RIFLE ) && weaponRange <= 500)
{
maxAimForType = 4;
aimLevels = 2;
maxAimWithoutBipod = 3;
// SANDRO - STOMP traits - Sniper bonus aim clicks
if ( gGameOptions.fNewTraitSystem && HAS_SKILL_TRAIT( pSoldier, SNIPER_NT ) )
{
maxAimForType += (gSkillTraitValues.ubSNAimClicksAdded * NUM_SKILL_TRAITS( pSoldier, SNIPER_NT ));
aimLevels += (gSkillTraitValues.ubSNAimClicksAdded * NUM_SKILL_TRAITS( pSoldier, SNIPER_NT ));
maxAimWithoutBipod += (gSkillTraitValues.ubSNAimClicksAdded * NUM_SKILL_TRAITS( pSoldier, SNIPER_NT ));
}
}
else if (((weaponType == GUN_AS_RIFLE || weaponType == GUN_RIFLE) && weaponRange > 500) ||
(weaponType == GUN_SN_RIFLE && weaponRange <= 500))
{
maxAimForType = 6;
aimLevels = 3;
maxAimWithoutBipod = 4;
// SANDRO - STOMP traits - Sniper bonus aim clicks
if ( gGameOptions.fNewTraitSystem && HAS_SKILL_TRAIT( pSoldier, SNIPER_NT ) )
{
maxAimForType += (gSkillTraitValues.ubSNAimClicksAdded * NUM_SKILL_TRAITS( pSoldier, SNIPER_NT ));
aimLevels += (gSkillTraitValues.ubSNAimClicksAdded * NUM_SKILL_TRAITS( pSoldier, SNIPER_NT ));
maxAimWithoutBipod += (gSkillTraitValues.ubSNAimClicksAdded * NUM_SKILL_TRAITS( pSoldier, SNIPER_NT ));
}
}
else if (weaponType == GUN_SN_RIFLE && weaponRange > 500)
{
maxAimForType = 8;
aimLevels = 4;
maxAimWithoutBipod = 3;
// SANDRO - STOMP traits - Sniper bonus aim clicks
if ( gGameOptions.fNewTraitSystem && HAS_SKILL_TRAIT( pSoldier, SNIPER_NT ) )
{
maxAimForType += (gSkillTraitValues.ubSNAimClicksAdded * NUM_SKILL_TRAITS( pSoldier, SNIPER_NT ));
aimLevels += (gSkillTraitValues.ubSNAimClicksAdded * NUM_SKILL_TRAITS( pSoldier, SNIPER_NT ));
maxAimWithoutBipod += (gSkillTraitValues.ubSNAimClicksAdded * NUM_SKILL_TRAITS( pSoldier, SNIPER_NT ));
}
}
else
{
return 4;
}
// Determine whether a bipod is being used (prone)
if (GetBipodBonus(&pSoldier->inv[pSoldier->ubAttackingHand])>0 && gAnimControl[ pSoldier->usAnimState ].ubEndHeight == ANIM_PRONE )
{
fUsingBipod = TRUE;
}
// don't break compatibility, let the users choose
if (gGameExternalOptions.iAimLevelsCompatibilityOption != 0)
sScopeBonus = OldWayOfCalculatingScopeBonus(pSoldier);
else
sScopeBonus = gGameExternalOptions.fAimLevelsDependOnDistance ?
//WarmSteel - Using scope aimbonus instead, as it is used elsewhere like this too.
//Also, you won't get extra aimclicks anymore if you're too close to use your scope.
//I've externalized the scope types.
GetBaseScopeAimBonus( &pSoldier->inv[pSoldier->ubAttackingHand], uiRange )
: GetMinRangeForAimBonus( &pSoldier->inv[pSoldier->ubAttackingHand]);
if ( sScopeBonus >= gGameExternalOptions.sVeryHighPowerScope )
{
aimLevels *= 2;
}
else if ( sScopeBonus >= gGameExternalOptions.sHighPowerScope )
{
aimLevels = (UINT8)((float)(aimLevels+1) * (float)1.5);
}
else if ( sScopeBonus >= gGameExternalOptions.sMediumPowerScope )
{
aimLevels = (UINT8)((float)(aimLevels+1) * (float)1.3);
}
// Smaller scopes increase by one.
else if ( sScopeBonus > 0 )
{
aimLevels++;
}
// Make sure not over maximum allowed for weapon type.
if (aimLevels > maxAimForType)
{
aimLevels = maxAimForType;
}
// Make sure not over maximum allowed without a bipod.
if (!fUsingBipod)
{
aimLevels = __min(aimLevels, maxAimWithoutBipod);
}
}
else // JA2 1.13 Basic aiming restrictions (8 levels for 10x scope, 6 levels for 7x scope)
{
OBJECTTYPE* pAttackingWeapon = &pSoldier->inv[pSoldier->ubAttackingHand];
if ( !IsScoped( pAttackingWeapon ) )
{
// No scope. 4 Allowed.
return (4);
}
//CHRRISL: yeah, this doesn't work. GetMinRangeForAimBonus returns a range value in units while GetBaseScopeAimBonus returns a small number.
// The result is that if fAimLevelsDependOnDistance is false, all scopes are going to grant +4 aim clicks which is definitely not what
// we want to happen. What we do want is simply to know whether we should send the range or use an extreme range value to guarantee that
// the scope is factored.
// sScopeBonus = gGameExternalOptions.fAimLevelsDependOnDistance ?
// GetBaseScopeAimBonus( pAttackingWeapon, iRange )
// : GetMinRangeForAimBonus( pAttackingWeapon );
if (gGameExternalOptions.iAimLevelsCompatibilityOption != 0)
sScopeBonus = OldWayOfCalculatingScopeBonus(pSoldier);
else
sScopeBonus = gGameExternalOptions.fAimLevelsDependOnDistance ? GetBaseScopeAimBonus( pAttackingWeapon, uiRange ) : GetBaseScopeAimBonus( pAttackingWeapon, 25000 );
if ( sScopeBonus >= gGameExternalOptions.sVeryHighPowerScope )
{
aimLevels += 2;
}
if ( sScopeBonus >= gGameExternalOptions.sHighPowerScope )
{
aimLevels += 2;
}
// SANDRO - STOMP traits - Sniper bonus aim clicks
if ((weaponType == GUN_AS_RIFLE || weaponType == GUN_RIFLE || weaponType == GUN_SN_RIFLE) &&
gGameOptions.fNewTraitSystem && HAS_SKILL_TRAIT( pSoldier, SNIPER_NT ) )
{
aimLevels += (gSkillTraitValues.ubSNAimClicksAdded * NUM_SKILL_TRAITS( pSoldier, SNIPER_NT ));
}
// SANDRO - STOMP traits - Gunslinger bonus aim clicks
if ((weaponType == GUN_PISTOL || weaponType == GUN_M_PISTOL) &&
gGameOptions.fNewTraitSystem && HAS_SKILL_TRAIT( pSoldier, GUNSLINGER_NT ) )
{
aimLevels += (gSkillTraitValues.ubGSAimClicksAdded * NUM_SKILL_TRAITS( pSoldier, GUNSLINGER_NT ));
}
//CHRISL: The system can't currently support more then 8 aim levels so make sure we can never have more then 8
aimLevels = min(8, aimLevels);
}
}
//CHRISL: Make sure we always limit to the proper number of aim clicks
aimLevels = __max(1, aimLevels);
aimLevels = __min(8, aimLevels);
return aimLevels;
}
UINT8 GetAllowedAimingLevelsForItem( SOLDIERTYPE *pSoldier, OBJECTTYPE *pObj, UINT8 ubStance )
{
if ( !(Item[pObj->usItem].usItemClass & (IC_GUN|IC_LAUNCHER|IC_THROWING_KNIFE)) )
{
return 1;
}
INT8 aimLevels = 4;
// HEADROCK HAM B2.6: Dynamic aiming level restrictions based on gun type and attachments.
// HEADROCK HAM 3.5: Revamped this - it was illogically constructed.
if ( gGameExternalOptions.fDynamicAimingTime )
{
UINT16 weaponRange;
UINT8 weaponType;
BOOLEAN fTwoHanded, fUsingBipod;
aimLevels = 0;
// Read weapon data
fTwoHanded = Item[pObj->usItem].twohanded;
weaponRange = Weapon[Item[pObj->usItem].ubClassIndex].usRange + GetRangeBonus(pObj);
weaponType = Weapon[Item[pObj->usItem].ubClassIndex].ubWeaponType;
fUsingBipod = FALSE;
if(UsingNewCTHSystem() == true)
aimLevels = Weapon[Item[pObj->usItem].ubClassIndex].ubAimLevels;
// Only use default values if we don't find a weapon specific value.
if(aimLevels == 0)
{
// Define basic (no attachments), and absolute maximums
if (weaponType == GUN_PISTOL || weaponType == GUN_M_PISTOL || fTwoHanded == 0)
{
aimLevels = 2;
}
else if (weaponType == GUN_SHOTGUN || weaponType == GUN_LMG || weaponType == GUN_SMG)
{
aimLevels = 3;
}
else if ((weaponType == GUN_AS_RIFLE || weaponType == GUN_RIFLE ) && weaponRange <= 500)
{
aimLevels = 4;
}
else if (((weaponType == GUN_AS_RIFLE || weaponType == GUN_RIFLE) && weaponRange > 500) ||
(weaponType == GUN_SN_RIFLE && weaponRange <= 500))
{
aimLevels = 6;
}
else if (weaponType == GUN_SN_RIFLE && weaponRange > 500)
{
aimLevels = 8;
}
else
{
return 4;
}
}
// HEADROCK HAM 4: This modifier from the weapon and its attachments replaces the generic bipod bonus.
aimLevels += GetAimLevelsModifier( pObj, ubStance );
aimLevels += GetAimLevelsTraitModifier( pSoldier, pObj );
aimLevels = __max(1, aimLevels);
aimLevels = __min(8, aimLevels);
}
return aimLevels;
}
//Madd: added
INT16 GetStealthBonus( OBJECTTYPE * pObj )
{
INT16 bonus = 0;
if ( pObj->exists() == true ) {
bonus = BonusReduce(Item[pObj->usItem].stealthbonus,(*pObj)[0]->data.objectStatus);
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists())
bonus += (INT16) BonusReduce(Item[iter->usItem].stealthbonus,(*iter)[0]->data.objectStatus);
}
}
return( bonus );
}
INT16 GetWornStealth( SOLDIERTYPE * pSoldier )
{
//note: Stealth bonus is capped at 100
//note: Stealth is not a perk! Stealth bonus only applies to equipment, and stacks with camouflage
//note: stealth bonus is not affected by terrain like the camo bonus, otherwise they're very similar
//note: stealth bonus also affects noise made by characters walking
INT8 bLoop;
INT16 ttl=0;
for (bLoop = HELMETPOS; bLoop <= LEGPOS; bLoop++)
{
if ( pSoldier->inv[bLoop].exists() == true )
ttl += GetStealthBonus(&pSoldier->inv[bLoop]);
}
// Add some default stealth ability to mercs with STEALTHY trait - SANDRO
if ( gGameOptions.fNewTraitSystem && HAS_SKILL_TRAIT( pSoldier, STEALTHY_NT ))
ttl += gSkillTraitValues.ubSTStealthBonus;
return __min( ttl, 100 );
}
/////////////////////////////
// HEADROCK: Several functions created for the Enhanced Description Box project, but may generally be useful some
// day. They calculate item bonuses, ammo bonuses and attachment bonuses, without requiring a SOLDIERTYPE or any
// other variable.
////////////////////////////
//WarmSteel - Function to get the total reliability from the gun and its attachments
INT16 GetReliability( OBJECTTYPE * pObj )
{
INT16 bonus = 0;
bonus += Item[pObj->usItem].bReliability;
//Ammo modifications need to be added aswell
if ( Item[ pObj->usItem ].usItemClass == IC_GUN && (*pObj)[0]->data.gun.ubGunShotsLeft > 0 )
{
bonus += Item[( *pObj )[0]->data.gun.usGunAmmoItem].bReliability;
}
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter)
{
if(iter->exists())
bonus += Item[iter->usItem].bReliability;
}
return( bonus );
}
// HEADROCK: Function to get the total aim-bonus from the gun and its attachments
INT16 GetFlatAimBonus( OBJECTTYPE * pObj )
{
INT16 bonus = 0;
bonus += Item[pObj->usItem].aimbonus;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter)
{
if(iter->exists())
bonus += Item[iter->usItem].aimbonus;
}
return( bonus );
}
// HEADROCK: Function to get the final Loudness value of a gun, after ammo and attachment reductions
INT16 GetFinalLoudness( OBJECTTYPE * pObj )
{
INT16 loudness = 0;
INT16 loudnessModifier = 0;
loudness = Weapon[Item[pObj->usItem].ubClassIndex].ubAttackVolume;
// WANNE: Fix by Headrock
// It seems that the game calculates noise reduction not by adding together the reduction from ammo and all attachments,
// but by applying them to the gun's loudness as percentages one by one.
// So instead of (60+20)% it does 60% and then 20%, giving completely different results.
loudness = ( loudness * GetPercentNoiseVolume( pObj ) ) / 100;
/*
loudnessModifier += Item[pObj->usItem].percentnoisereduction;
if ( (*pObj)[0]->data.gun.ubGunShotsLeft > 0 )
loudnessModifier += Item[(*pObj)[0]->data.gun.usGunAmmoItem].percentnoisereduction ;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter)
{
loudnessModifier += BonusReduce( Item[iter->usItem].percentnoisereduction, (*iter)[0]->data.objectStatus ) ;
}
loudness = loudness * ( 100 - loudnessModifier ) / 100;
*/
loudness = __max(loudness, 1);
return ( loudness );
}
// HEADROCK: Function to get AP bonus from an item rather than a soldier
INT16 GetAPBonus( OBJECTTYPE * pObj )
{
INT16 bonus=0;
bonus += Item[ pObj->usItem ].APBonus;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists())
bonus += Item[iter->usItem].APBonus;
}
return( bonus );
}
// HEADROCK: Alternative function to determine flat to-hit bonus of weapon
INT16 GetFlatToHitBonus( OBJECTTYPE * pObj )
{
INT16 bonus=0;
bonus = Item[pObj->usItem].tohitbonus;
bonus += Item[(*pObj)[0]->data.gun.usGunAmmoItem].tohitbonus;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter){
if(iter->exists())
bonus += Item[iter->usItem].tohitbonus;
}
return( bonus );
}
// HEADROCK: Function to get average of all "best laser range" attributes from weapon and attachments
INT16 GetAverageBestLaserRange( OBJECTTYPE * pObj )
{
INT16 bonus=0;
INT16 numModifiers=0;
if (Item[pObj->usItem].bestlaserrange > 0)
{
numModifiers++;
bonus += Item[pObj->usItem].bestlaserrange;
}
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter)
{
if (Item[iter->usItem].bestlaserrange > 0 && iter->exists())
{
numModifiers++;
bonus += Item[iter->usItem].bestlaserrange;
}
}
if (numModifiers>0)
{
bonus = bonus / numModifiers;
}
return( bonus );
}
// HEADROCK: This function determines the bipod bonii of the gun or its attachments
INT16 GetBipodBonus( OBJECTTYPE * pObj )
{
INT16 bonus=0;
bonus = Item[pObj->usItem].bipod;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter){
if(iter->exists())
bonus += Item[iter->usItem].bipod;
}
return( bonus );
}
// HEADROCK: Added a function to calculate the vision range bonus of an object and its attachments. Takes an argument which determines what type
// of vision range bonus we want to get:
// 0 - Regular
// 1 - Day
// 2 - Night
// 3 - Bright Light
// 4 - Cave
INT16 GetItemVisionRangeBonus( OBJECTTYPE * pObj, INT16 VisionType )
{
INT16 bonus = 0;
if (VisionType == 0)
{
bonus += Item[ pObj->usItem ].visionrangebonus;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists())
bonus += Item[iter->usItem].visionrangebonus;
}
}
else if (VisionType == 1)
{
bonus += Item[ pObj->usItem ].dayvisionrangebonus;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists())
bonus += Item[iter->usItem].dayvisionrangebonus;
}
}
else if (VisionType == 2)
{
bonus += Item[ pObj->usItem ].nightvisionrangebonus;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists())
bonus += Item[iter->usItem].nightvisionrangebonus;
}
}
else if (VisionType == 3)
{
bonus += Item[ pObj->usItem ].brightlightvisionrangebonus;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists())
bonus += Item[iter->usItem].brightlightvisionrangebonus;
}
}
else if (VisionType == 4)
{
bonus += Item[ pObj->usItem ].cavevisionrangebonus;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists())
bonus += Item[iter->usItem].cavevisionrangebonus;
}
}
return( bonus );
}
// HEADROCK: function to get Tunnel Vision percent from an item and its attachments
UINT8 GetItemPercentTunnelVision( OBJECTTYPE * pObj )
{
UINT8 bonus = 0;
bonus += Item[ pObj->usItem ].percenttunnelvision;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists())
bonus += Item[iter->usItem].percenttunnelvision;
}
bonus = __min(bonus, 100);
return( bonus );
}
// HEADROCK: Function to calculate hearing range bonus without SOLDIERTYPE, from an item and its attachments
INT16 GetItemHearingRangeBonus( OBJECTTYPE * pObj )
{
INT16 bonus = 0;
bonus += Item[ pObj->usItem ].hearingrangebonus;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists())
bonus += Item[ iter->usItem ].hearingrangebonus;
}
return( bonus );
}
// HEADROCK: Flash Suppression Detector function that does not use SOLDIERTYPE.
BOOLEAN IsFlashSuppressorAlt( OBJECTTYPE * pObj )
{
if ( AmmoTypes[(*pObj)[0]->data.gun.ubGunAmmoType].tracerEffect )
return FALSE;
if ( Item[pObj->usItem].hidemuzzleflash )
return TRUE;
if ( Item[(*pObj)[0]->data.gun.usGunAmmoItem].hidemuzzleflash )
return TRUE;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if (Item[iter->usItem].hidemuzzleflash && iter->exists() )
{
return( TRUE );
}
}
return( FALSE );
}
// HEADROCK: Calculate stealth not based on item status
INT16 GetBasicStealthBonus( OBJECTTYPE * pObj )
{
INT16 bonus = 0;
if ( pObj->exists() == true ) {
bonus = Item[pObj->usItem].stealthbonus;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter) {
if(iter->exists())
bonus += (INT16) Item[iter->usItem].stealthbonus;
}
}
return( bonus );
}
// HEADROCK HAM 4: Calculate a gun's accuracy, including bonuses from ammo and attachments.
INT32 GetGunAccuracy( OBJECTTYPE *pObj )
{
if(UsingNewCTHSystem() == false)
return(Weapon[pObj->usItem].bAccuracy);
INT32 bonus = 0;
if ( pObj->exists() == true )
{
bonus = Weapon[Item[pObj->usItem].uiIndex].nAccuracy;
bonus = (bonus * (*pObj)[0]->data.gun.bGunStatus) / 100;
INT32 iModifier = GetAccuracyModifier( pObj );
// Accuracy works in a very different way from most modifiers. At low levels, a small change is almost completely
// irrelevant. At high levels, every point of accuracy can potentially increase the gun's effective range by
// a large amount. Therefore, we apply this percentage in REVERSE - the higher our accuracy, the less change
// we receive.
// You can look at it a different way: We're actually adding/subtracting a percentage of the distance between
// the gun's accuracy and Max Accuracy (100).
// Examples:
// Modifier = +20%
// Initial Gun Accuracy = 90, Final Gun Accuracy = 90 + (20% of the gap = 20% of 100-90 = 20% of 10 = 2) = 92.
// Initial Gun Accuracy = 10, Final Gun Accuracy = 10 + (20% of the gap = 20% of 100-10 = 20% of 90 = 18) = 28.
bonus += ((100-bonus) * iModifier) / 100;
}
bonus = __max(0,bonus);
bonus = __min(100,bonus);
return( bonus );
}
// Get Accuracy Modifier from an item and its attachments
INT32 GetAccuracyModifier( OBJECTTYPE *pObj )
{
INT32 bonus = 0;
if ( pObj->exists() == true && UsingNewCTHSystem() == true )
{
bonus += Item[ pObj->usItem ].percentaccuracymodifier;
if ( (*pObj)[0]->data.gun.ubGunShotsLeft > 0 )
bonus += Item[(*pObj)[0]->data.gun.usGunAmmoItem].percentaccuracymodifier;
for (attachmentList::iterator iter = (*pObj)[0]->attachments.begin(); iter != (*pObj)[0]->attachments.end(); ++iter)
{
if (iter->exists())
{
bonus += BonusReduceMore( (INT32) Item[iter->usItem].percentaccuracymodifier, (*iter)[0]->data.objectStatus );
}
}
}
return bonus;
}
// HEADROCK HAM 3.6: This is meant to squash an exploit where a backpack can be moved to your hand to avoid AP penalties.
// CHRISL: Carrying an empty backpack in a none BACKPACKPOS location shoudln't be an issue.
INT8 FindBackpackOnSoldier( SOLDIERTYPE * pSoldier )
{
INT8 bLoop;
for (bLoop = 0; bLoop < NUM_INV_SLOTS ; bLoop++)
{
if (pSoldier->inv[bLoop].exists())
{
if( bLoop == BPACKPOCKPOS )
return( bLoop );
if (Item[pSoldier->inv[bLoop].usItem].usItemClass == IC_LBEGEAR &&
LoadBearingEquipment[Item[pSoldier->inv[bLoop].usItem].ubClassIndex].lbeClass == BACKPACK)
{
for (INT8 bLoop2 = 0; bLoop2 < pSoldier->inv[bLoop].ubNumberOfObjects; bLoop2++)
{
if(pSoldier->inv[bLoop].IsActiveLBE(bLoop2) == true)
return( bLoop );
}
}
}
}
return( ITEM_NOT_FOUND );
}
// HEADROCK HAM 3.6: This applies the INI modifier to explosives
UINT8 GetModifiedExplosiveDamage( UINT16 sDamage )
{
if (sDamage == 0)
{
return(0);
}
sDamage = (INT16)(( sDamage * gGameExternalOptions.iExplosivesDamageModifier ) / 100);
sDamage = __max(1, sDamage);
sDamage = __min(255, sDamage);
return (UINT8)sDamage;
}
UINT8 GetModifiedMeleeDamage( UINT16 sDamage )
{
if (sDamage == 0)
{
return(0);
}
sDamage = (INT16)(( sDamage * gGameExternalOptions.iMeleeDamageModifier ) / 100);
sDamage = __max(1, sDamage);
sDamage = __min(255, sDamage);
return (UINT8)sDamage;
}
UINT8 GetModifiedGunDamage( UINT16 sDamage )
{
if (sDamage == 0)
{
return(0);
}
sDamage = (INT16)(( sDamage * gGameExternalOptions.iGunDamageModifier ) / 100);
sDamage = __max(1, sDamage);
sDamage = __min(255, sDamage);
return (UINT8)sDamage;
}
UINT16 GetModifiedGunRange(UINT16 usWeaponIndex)
{
UINT16 ubRange = Weapon[usWeaponIndex].usRange;
if (ubRange == 0)
{
return(0);
}
// Only apply range modifier on "real" guns!
if (Item[Weapon[usWeaponIndex].uiIndex].usItemClass == IC_GUN ||
Item[Weapon[usWeaponIndex].uiIndex].usItemClass == IC_LAUNCHER)
{
ubRange = (INT16)(( ubRange * gGameExternalOptions.iGunRangeModifier ) / 100);
}
return (UINT16)ubRange;
}
/////////////////////////////////////////////////////////////////////////////////////////////
// SANDRO - Added a procedure to reduce camo on soldier, used when applying camo kit
INT16 ReduceCamoFromSoldier( SOLDIERTYPE * pSoldier, INT16 iCamoToRemove, INT16 iCamoToSkip )
{
INT32 i;
UINT16 iCamoToRemovePart = 3;
if( iCamoToSkip > 0 ) // iCamoToSkip determines what camo type should not be reduced
iCamoToRemovePart = 2;
if ( (pSoldier->bCamo == 0) && (iCamoToSkip != 1) )
iCamoToRemovePart -= 1;
if ( (pSoldier->urbanCamo == 0) && (iCamoToSkip != 2) )
iCamoToRemovePart -= 1;
if ( (pSoldier->desertCamo == 0) && (iCamoToSkip != 3) )
iCamoToRemovePart -= 1;
if ( (pSoldier->snowCamo == 0) && (iCamoToSkip != 4) )
iCamoToRemovePart -= 1;
// this should never happen, but if, we still might try to go through the procedure below
if ( iCamoToRemovePart < 0 )
iCamoToRemovePart = 0;
for (i = 0; i < 4; i++ ) // 4 times should be enough, a little paranoya here
{
// first, try to reduce jungle camo
if ( ((iCamoToRemove / (1 + iCamoToRemovePart)) <= pSoldier->bCamo) && (pSoldier->bCamo > 0) && (iCamoToSkip != 1) )
{
// jungle camo enough to reduce
pSoldier->bCamo -= max(1,(iCamoToRemove / (1 + iCamoToRemovePart)));
iCamoToRemove -= max(1,(iCamoToRemove / (1 + iCamoToRemovePart)));
iCamoToRemovePart = max( 0,(iCamoToRemovePart - 1));
if( iCamoToRemove <= 0 )
break;
}
else if ((pSoldier->bCamo > 0) && (iCamoToSkip != 1))
{
// jungle camo not enough to reduce by intended value, reduce only by what we have
iCamoToRemove -= pSoldier->bCamo;
pSoldier->bCamo = 0;
iCamoToRemovePart = max( 0,(iCamoToRemovePart - 1));
if( iCamoToRemove <= 0 )
break;
}
// second, try to reduce urban camo
if ( ((iCamoToRemove / (1 + iCamoToRemovePart)) <= pSoldier->urbanCamo) && (pSoldier->urbanCamo > 0) && (iCamoToSkip != 2) )
{
// urban camo enough to reduce
pSoldier->urbanCamo -= max(1,(iCamoToRemove / (1 + iCamoToRemovePart)));
iCamoToRemove -= max(1,(iCamoToRemove / (1 + iCamoToRemovePart)));
iCamoToRemovePart = max( 0,(iCamoToRemovePart - 1));
if( iCamoToRemove <= 0 )
break;
}
else if ((pSoldier->urbanCamo > 0) && (iCamoToSkip != 2))
{
// urban camo not enough to reduce by intended value, reduce only by what we have
iCamoToRemove -= pSoldier->urbanCamo;
pSoldier->urbanCamo = 0;
iCamoToRemovePart = max( 0,(iCamoToRemovePart - 1));
if( iCamoToRemove <= 0 )
break;
}
// third, try to reduce desert camo
if ( ((iCamoToRemove / (1 + iCamoToRemovePart)) <= pSoldier->desertCamo) && (pSoldier->desertCamo > 0) && (iCamoToSkip != 3) )
{
// desert camo enough to reduce
pSoldier->desertCamo -= max(1,(iCamoToRemove / (1 + iCamoToRemovePart)));
iCamoToRemove -= max(1,(iCamoToRemove / (1 + iCamoToRemovePart)));
iCamoToRemovePart = max( 0,(iCamoToRemovePart - 1));
if( iCamoToRemove <= 0 )
break;
}
else if ((pSoldier->desertCamo > 0) && (iCamoToSkip != 3))
{
// desert camo not enough to reduce by intended value, reduce only by what we have
iCamoToRemove -= pSoldier->desertCamo;
pSoldier->desertCamo = 0;
iCamoToRemovePart = max( 0,(iCamoToRemovePart - 1));
if( iCamoToRemove <= 0 )
break;
}
// fourth, try to reduce snow camo
if ( ((iCamoToRemove / (1 + iCamoToRemovePart)) <= pSoldier->snowCamo) && (pSoldier->snowCamo > 0) && (iCamoToSkip != 4) )
{
// snow camo enough to reduce
pSoldier->snowCamo -= max(1,(iCamoToRemove / (1 + iCamoToRemovePart)));
iCamoToRemove -= max(1,(iCamoToRemove / (1 + iCamoToRemovePart)));
iCamoToRemovePart = max( 0,(iCamoToRemovePart - 1));
if( iCamoToRemove <= 0 )
break;
}
else if ((pSoldier->snowCamo > 0) && (iCamoToSkip != 4))
{
// snow camo not enough to reduce by intended value, reduce only by what we have
iCamoToRemove -= pSoldier->snowCamo;
pSoldier->snowCamo = 0;
if( iCamoToRemove <= 0 )
break;
}
}
// return remaining value or zero
return( max( 0, iCamoToRemove));
}
// SANDRO - added function to determine if we have Extended Ear on
BOOLEAN HasExtendedEarOn( SOLDIERTYPE * pSoldier )
{
// optimistically assume, that anything electronic with hearing range bonus serves as extended ear as well
if ( pSoldier->inv[HEAD1POS].exists() && (pSoldier->inv[HEAD1POS].usItem == EXTENDEDEAR ||
(Item[pSoldier->inv[HEAD1POS].usItem].hearingrangebonus > 0 && Item[pSoldier->inv[HEAD1POS].usItem].electronic)) )
{
return( TRUE );
}
else if ( pSoldier->inv[HEAD2POS].exists() && (pSoldier->inv[HEAD2POS].usItem == EXTENDEDEAR ||
(Item[pSoldier->inv[HEAD2POS].usItem].hearingrangebonus > 0 && Item[pSoldier->inv[HEAD2POS].usItem].electronic)) )
{
return( TRUE );
}
return( FALSE );
}
BOOLEAN UseTotalMedicalKitPoints( SOLDIERTYPE * pSoldier, UINT16 usPointsToConsume )
{
OBJECTTYPE * pObj;
UINT8 ubPocket;
INT8 bLoop;
// add up kit points of all medkits
// CHRISL: Changed to dynamically determine max inventory locations.
for (ubPocket = HANDPOS; ubPocket < NUM_INV_SLOTS; ubPocket++)
{
if ( IsMedicalKitItem( &( pSoldier->inv[ ubPocket ] ) ) )
{
pObj = &(pSoldier->inv[ ubPocket ]);
// start consuming from the last kit in, so we end up with fewer fuller kits rather than
// lots of half-empty ones.
for (bLoop = pObj->ubNumberOfObjects - 1; bLoop >= 0; bLoop--)
{
if( (usPointsToConsume * (max( 0, (100 - Item[pObj->usItem].percentstatusdrainreduction)))/100) < (*pObj)[bLoop]->data.objectStatus )
{
(*pObj)[bLoop]->data.objectStatus -= (INT8)(usPointsToConsume * (max( 0, (100 - Item[pObj->usItem].percentstatusdrainreduction) ) )/100);
usPointsToConsume = 0;
break;
}
else
{
// consume this kit totally
usPointsToConsume -= (((*pObj)[bLoop]->data.objectStatus) / (max( 0, (100 - Item[pObj->usItem].percentstatusdrainreduction))) /100);
(*pObj)[bLoop]->data.objectStatus = 0;
pObj->ubNumberOfObjects--;
}
}
// check if pocket/hand emptied..update inventory, then update panel
if( pObj->exists() == false )
{
// Delete object
DeleteObj( pObj );
// dirty interface panel
DirtyMercPanelInterface( pSoldier, DIRTYLEVEL2 );
}
if( usPointsToConsume <= 0 )
break;
}
}
if (usPointsToConsume > 0)
return( FALSE );
else
return( TRUE );
}
static UINT16 OldWayOfCalculatingScopeBonus(SOLDIERTYPE *pSoldier)
{
// Yes, this may look stupid, maybe it IS stupid, but this is purely an option
// to use code that was checked in before.
// Please, do not trash it again.
return max(0, GetMinRangeForAimBonus(& pSoldier->inv[pSoldier->ubAttackingHand])
* gGameExternalOptions.iAimLevelsCompatibilityOption / gGameExternalOptions.ubStraightSightRange);
}
| [
"jazz_ja@b41f55df-6250-4c49-8e33-4aa727ad62a1"
]
| [
[
[
1,
12367
]
]
]
|
ad90079cd1060c2abeaf8f6bf9785e42eba17a28 | d76a67033e3abf492ff2f22d38fb80de804c4269 | /src/box2d/PrismaticJoint.h | ccf6a3a6efdfe8587735e415780952182fc55ada | [
"Zlib"
]
| permissive | truthwzl/lov8 | 869a6be317b7d963600f2f88edaefdf9b5996f2d | 579163941593bae481212148041e0db78270c21d | refs/heads/master | 2021-01-10T01:58:59.103256 | 2009-12-16T16:00:09 | 2009-12-16T16:00:09 | 36,340,451 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,668 | h | /*
* LOVE: Totally Awesome 2D Gaming.
* Website: http://love.sourceforge.net
* Licence: ZLIB/libpng
* Copyright (c) 2006-2008 LOVE Development Team
*
* @author Anders Ruud
* @date 2008-08-12
*/
#ifndef LOVE_BOX2D_PRISMATIC_JOINT_H
#define LOVE_BOX2D_PRISMATIC_JOINT_H
// Module
#include "Joint.h"
namespace love_box2d
{
/**
* PrismaticJoints allow shapes to move in relation to eachother
* along a defined axis.
**/
class PrismaticJoint : public Joint
{
private:
// The Box2D prismatic joint object.
b2PrismaticJoint * joint;
public:
/**
* Creates a new PrismaticJoint connecting body1 and body2.
**/
PrismaticJoint(boost::shared_ptr<Body> body1, boost::shared_ptr<Body> body2, b2PrismaticJointDef * def);
virtual ~PrismaticJoint();
/**
* Get the current joint translation, usually in meters.
**/
float getTranslation() const;
/**
* Get the current joint translation speed, usually in meters per second.
**/
float getSpeed() const;
/**
* Enable/disable the joint motor.
**/
void setMotorEnabled(bool motor);
/**
* Checks whether the motor is enabled.
**/
bool isMotorEnabled() const;
/**
* Set the maximum motor force, usually in N.
**/
void setMaxMotorForce(float force);
/**
* Get the current motor force, usually in N.
**/
float getMaxMotorForce() const;
/**
* Set the motor speed, usually in meters per second.
**/
void setMotorSpeed(float speed);
/**
* Get the motor speed, usually in meters per second.
**/
float getMotorSpeed() const;
/**
* Get the current motor force, usually in N.
**/
float getMotorForce() const;
/**
* Enable/disable the joint limit.
**/
void setLimitsEnabled(bool limit);
/**
* Checks whether limits are enabled.
**/
bool isLimitsEnabled() const;
/**
* Sets the upper limit, usually in meters.
**/
void setUpperLimit(float limit);
/**
* Sets the lower limit, usually in meters.
**/
void setLowerLimit(float limit);
/**
* Sets the limits, usually in meters.
**/
void setLimits(float lower, float upper);
/**
* Gets the lower limit, usually in meters.
**/
float getLowerLimit() const;
/**
* Gets the upper limit, usually in meters.
**/
float getUpperLimit() const;
/**
* Gets the limits, usually in meters.
* @returns The upper limit.
* @returns The lower limit.
**/
int getLimits(lua_State * L);
};
typedef boost::shared_ptr<PrismaticJoint> pPrismaticJoint;
} // love_box2d
#endif // LOVE_BOX2D_PRISMATIC_JOINT_H
| [
"m4rvin2005@8b5f54a0-8722-11de-9e21-49812d2d8162"
]
| [
[
[
1,
131
]
]
]
|
3dd5dfaa523011b12fe84caf7531be0f783f37e3 | c6dca462f8e982b2a327285cf084d08fa7f27dd8 | /include/liblearning/core/data_splitter.h | ce8062a34539975ce046bc6fbd155b7038e84bd5 | []
| no_license | nagyistoce/liblearning | 2a7e94344f15c5af105974207ece68822102524b | ac0a77dce09ad72f32b2cae067f4616e49d60697 | refs/heads/master | 2021-01-01T16:59:44.689918 | 2010-08-20T12:07:22 | 2010-08-20T12:07:22 | 32,806,608 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 902 | h | #ifndef BATCH_MAKER
#define BATCH_MAKER
#include <vector>
using namespace std;
class dataset;
class dataset_splitter
{
public:
dataset_splitter(void);
~dataset_splitter(void);
virtual vector<vector<int>> split(const dataset& data, int batch_num) const = 0;
};
class ordered_dataset_splitter :public dataset_splitter
{
public:
ordered_dataset_splitter();
virtual vector<vector<int>> split(const dataset& data,int batch_num) const;
};
class random_shuffer_dataset_splitter : public dataset_splitter
{
public:
random_shuffer_dataset_splitter();
virtual vector<vector<int>> split(const dataset& data,int batch_num) const;
};
class supervised_random_shuffer_dataset_splitter : public dataset_splitter
{
public:
supervised_random_shuffer_dataset_splitter();
virtual vector<vector<int>> split(const dataset& data,int batch_num) const ;
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
42
]
]
]
|
962b2e7f56df9583c69220ef0e349e54524572b7 | b22c254d7670522ec2caa61c998f8741b1da9388 | /NewClient/OSGHandler.h | 391e0ab7ae21c973af48524fa347454544bd0ab2 | []
| 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 | 5,589 | 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 _LBANET_OSG_HANDLER_H_
#define _LBANET_OSG_HANDLER_H_
#include <vector>
#include <string>
#include <osg/ref_ptr>
#include <boost/shared_ptr.hpp>
#include "CommonTypes.h"
#include "DisplayHandlerBase.h"
namespace osg
{
class Node;
class PositionAttitudeTransform;
class Group;
class MatrixTransform;
class LightSource;
class ClipNode;
}
namespace osgViewer
{
class Viewer;
class GraphicsWindowEmbedded;
}
namespace osgShadow
{
class ShadowedScene;
}
class EventHandler;
struct SDL_Surface;
class GuiHandler;
//*************************************************************************************************
//* class OsgHandler
//*************************************************************************************************
/**
* @brief Class takign care of the OSG 3D engine
*
*/
class OsgHandler : public DisplayHandlerBase
{
public:
// singleton pattern
static OsgHandler * getInstance();
//! destructor
~OsgHandler();
//! initialize
void Initialize(const std::string &WindowName, const std::string &DataPath,
boost::shared_ptr<EventHandler> evH, GuiHandler * GuiH);
//! finalize function
void Finalize();
//! change screen resolution
void Resize(int resX, int resY);
//! toggle fullscreen or windowed mode
void ToggleFullScreen();
//! set if the view is perspective or ortho
void TogglePerspectiveView(bool Perspective);
//! set camera distance
void SetCameraDistance(double distance);
//! delta update camera distance
void DeltaUpdateCameraDistance(double delta);
//! set camera zenit
void SetCameraZenit(double zenit);
//! delta update camera zenit
void DeltaUpdateCameraZenit(double delta);
//! set camera target
void SetCameraTarget(double TargetX, double TargetY, double TargetZ);
void GetCameraTarget(double &TargetX, double &TargetY, double &TargetZ);
//! clear all nodes of the display tree
//! typically called when changing map
//! set if new map uses lighning or not
void ResetDisplayTree();
//! update display - returns true if need to terminate
bool Update();
//! load osg files into a osg node
osg::ref_ptr<osg::Node> LoadOSGFile(const std::string & filename);
//! add a actor to the display list - return handler to actor position
osg::ref_ptr<osg::MatrixTransform> AddActorNode(osg::ref_ptr<osg::Node> node);
//! remove actor from the graph
void RemoveActorNode(osg::ref_ptr<osg::Node> node);
//! set light
void SetLight(const LbaMainLightInfo &LightInfo);
//! set clip plane cut layer
void SetClipPlane(float layer);
//! set screen attributes
void SetScreenAttributes(int resX, int resY, bool fullscreen);
//! set screen attributes
void GetScreenAttributes(int &resX, int &resY, bool &fullscreen);
//! check if the view is perspective or ortho
bool IsPerspectiveView()
{return _isPerspective;}
//! create simple display object
virtual boost::shared_ptr<DisplayObjectHandlerBase> CreateSimpleObject(const std::string & filename,
boost::shared_ptr<DisplayTransformation> Tr);
//! create capsule object
virtual boost::shared_ptr<DisplayObjectHandlerBase> CreateCapsuleObject(float radius, float height,
float colorR, float colorG, float colorB, float colorA,
boost::shared_ptr<DisplayTransformation> Tr);
protected:
//! constructor
OsgHandler();
//! set or reset screen
void ResetScreen();
//! set or reset camera projection matrix
void ResetCameraProjectiomMatrix();
//! set or reset camera transform
void ResetCameraTransform();
private:
// singleton
static OsgHandler * _singletonInstance;
// pointer to the SDL screen surface
SDL_Surface * m_screen;
osg::ref_ptr<osgViewer::GraphicsWindowEmbedded> _gw;
boost::shared_ptr<EventHandler> _evH;
GuiHandler * _GuiH;
// screen info
bool _isFullscreen;
int _resX;
int _resY;
int _viewportX;
int _viewportY;
bool _displayShadow;
// camera info
bool _isPerspective;
double _targetx;
double _targety;
double _targetz;
double _fov;
double _distance;
double _zenit;
float _current_clip_layer;
// osg handlers
osg::ref_ptr<osgViewer::Viewer> _viewer;
osg::ref_ptr<osg::PositionAttitudeTransform> _rootNode;
osg::ref_ptr<osg::PositionAttitudeTransform> _translNode;
osg::ref_ptr<osg::LightSource> _lightNode;
osg::ref_ptr<osg::Group> _sceneRootNode;
osg::ref_ptr<osg::ClipNode> _clipNode;
};
#endif
| [
"vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13"
]
| [
[
[
1,
214
]
]
]
|
c3f10f924d71df9ffaafa90c24bfec913fd928d1 | 9a48be80edc7692df4918c0222a1640545384dbb | /Libraries/Boost1.40/libs/interprocess/test/mapped_file_test.cpp | f41d8d3dd0ea3826e2137fbac228dc9ea1d0e9e9 | [
"BSL-1.0"
]
| permissive | fcrick/RepSnapper | 05e4fb1157f634acad575fffa2029f7f655b7940 | a5809843f37b7162f19765e852b968648b33b694 | refs/heads/master | 2021-01-17T21:42:29.537504 | 2010-06-07T05:38:05 | 2010-06-07T05:38:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,021 | cpp | //////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2004-2007. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/interprocess for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#include <boost/interprocess/detail/config_begin.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/detail/file_wrapper.hpp>
#include <boost/interprocess/file_mapping.hpp>
#include <boost/interprocess/detail/managed_open_or_create_impl.hpp>
#include "named_creation_template.hpp"
#include <cstdio>
#include <cstring>
#include <string>
#include "get_process_id_name.hpp"
using namespace boost::interprocess;
static const std::size_t FileSize = 1000;
static const char * FileName = test::get_process_id_name();
struct file_destroyer
{
~file_destroyer()
{
//The last destructor will destroy the file
file_mapping::remove(FileName);
}
};
//This wrapper is necessary to have a common constructor
//in generic named_creation_template functions
class mapped_file_creation_test_wrapper
: public file_destroyer
, public boost::interprocess::detail::managed_open_or_create_impl
<boost::interprocess::detail::file_wrapper>
{
typedef boost::interprocess::detail::managed_open_or_create_impl
<boost::interprocess::detail::file_wrapper> mapped_file;
public:
mapped_file_creation_test_wrapper(boost::interprocess::create_only_t)
: mapped_file(boost::interprocess::create_only, FileName, FileSize)
{}
mapped_file_creation_test_wrapper(boost::interprocess::open_only_t)
: mapped_file(boost::interprocess::open_only, FileName)
{}
mapped_file_creation_test_wrapper(boost::interprocess::open_or_create_t)
: mapped_file(boost::interprocess::open_or_create, FileName, FileSize)
{}
};
int main ()
{
typedef boost::interprocess::detail::managed_open_or_create_impl
<boost::interprocess::detail::file_wrapper> mapped_file;
file_mapping::remove(FileName);
test::test_named_creation<mapped_file_creation_test_wrapper>();
//Create and get name, size and address
{
mapped_file file1(create_only, FileName, FileSize);
//Compare name
if(std::strcmp(file1.get_name(), FileName) != 0){
return 1;
}
//Overwrite all memory
std::memset(file1.get_user_address(), 0, file1.get_user_size());
//Now test move semantics
mapped_file move_ctor(boost::interprocess::move(file1));
mapped_file move_assign;
move_assign = boost::interprocess::move(move_ctor);
}
file_mapping::remove(FileName);
return 0;
}
#include <boost/interprocess/detail/config_end.hpp>
| [
"metrix@Blended.(none)"
]
| [
[
[
1,
88
]
]
]
|
1303b118986180f5bd9aee9a6928c534b672f0cb | fe12fa9ecd2bff7d28d22b84561c27d1ce787fd8 | /critsect.cpp | c90603a3e0c86783e3fd4abf8d59518440ea8734 | []
| no_license | gunmetalbackupgooglecode/critsect | 959a109a36d5fc42e828062fb4e8b8e20b7c4053 | 511d9cfc3f72fe8c5ff81ab0d9c5b74dee1c9549 | refs/heads/master | 2021-01-25T08:59:59.450530 | 2008-11-28T03:26:16 | 2008-11-28T03:26:16 | 32,150,001 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,772 | cpp | extern "C"
{
#include <ntifs.h>
#include "critsect.h"
}
typedef struct RTL_CRITICAL_SECTION_DEBUG
{
USHORT Type;
USHORT CreatorBackTraceIndex;
RTL_CRITICAL_SECTION *CriticalSection;
LIST_ENTRY ProcessLocksList;
ULONG EntryCount;
ULONG ContentionCount;
ULONG Spare[2];
} *PRTL_CRITICAL_SECTION_DEBUG;
VOID _CreateCriticalSectionSemaphore(PRTL_CRITICAL_SECTION Section)
{
NTSTATUS st;
LARGE_INTEGER tmo = {(ULONG) -100000, -1}; // Start at 1/100th of a second
LONGLONG max_tmo = (LONGLONG) -10000000 * 60 * 3; // Wait for a max of 3 minutes
//
// Loop trying to create the event on failure.
//
while (TRUE)
{
st = ZwCreateEvent (
&Section->LockSemaphore,
EVENT_ALL_ACCESS,
NULL,
SynchronizationEvent,
FALSE
);
if (NT_SUCCESS(st))
break;
else
{
if ( tmo.QuadPart < max_tmo )
{
KdPrint(( "NTRTL: Warning. Unable to allocate lock semaphore for Cs %p. Status %x raising\n", Section,st ));
InterlockedDecrement(&Section->LockCount);
ExRaiseStatus(st);
}
KdPrint(( "NTRTL: Warning. Unable to allocate lock semaphore for Cs %p. Status %x retrying\n", Section,st ));
st = KeDelayExecutionThread (KernelMode, FALSE, &tmo);
if ( !NT_SUCCESS(st) )
{
InterlockedDecrement(&Section->LockCount);
ExRaiseStatus(st);
}
tmo.QuadPart *= 2;
}
}
}
VOID _CheckDeferedCriticalSection (PRTL_CRITICAL_SECTION Section);
BOOLEAN _CritSectInitialized = FALSE;
RTL_CRITICAL_SECTION CriticalSectionLock;
RTL_CRITICAL_SECTION DeferedCriticalSection;
LIST_ENTRY CriticalSectionList;
BOOLEAN TryEnterCriticalSection (PRTL_CRITICAL_SECTION Section)
{
HANDLE CurrentThread = PsGetCurrentThreadId();
if (InterlockedCompareExchange (&Section->LockCount,
0,
-1) == -1)
{
Section->OwningThread = CurrentThread;
Section->RecursionCount = 1;
return TRUE;
}
if (Section->OwningThread == CurrentThread)
{
InterlockedIncrement (&Section->LockCount);
Section->RecursionCount ++;
return TRUE;
}
return FALSE;
}
VOID _WaitForCriticalSection (PRTL_CRITICAL_SECTION Section)
{
NTSTATUS st;
LARGE_INTEGER Timeout = {-10000 * 10000, -1}; // 10 seconds
ULONG TimeoutCount = 0;
if (!Section->LockSemaphore)
{
//
// Section is deffered. Cannot wait for such section (semaphore should be created)
//
ASSERT (FALSE);
_CheckDeferedCriticalSection (Section);
}
Section->DebugInfo->EntryCount ++;
while (TRUE)
{
Section->DebugInfo->ContentionCount ++;
KdPrint(("NTRTL: Waiting for CritSect: %p owned by ThreadId: %X Count: %u Level: %u\n",
Section,
Section->OwningThread,
Section->LockCount,
Section->RecursionCount
));
st = ZwWaitForSingleObject (Section->LockSemaphore, FALSE, NULL);
if (st == STATUS_TIMEOUT)
{
KdPrint(("NTRTL: Enter Critical Section Timeout (10 seconds) %d\n",
TimeoutCount
));
KdPrint(("NTRTL: Pid.Tid %x.%x, owner tid %x Critical Section %p - ContentionCount == %lu\n",
PsGetCurrentProcessId(),
PsGetCurrentThreadId(),
Section->OwningThread,
Section,
Section->DebugInfo->ContentionCount
));
TimeoutCount ++;
if (TimeoutCount > 6)
{
EXCEPTION_RECORD Record = {0};
Record.ExceptionAddress = (PVOID) ExRaiseException;
Record.ExceptionCode = STATUS_POSSIBLE_DEADLOCK;
Record.ExceptionInformation[0] = (ULONG_PTR) Section;
Record.NumberParameters = 1;
ExRaiseException (&Record);
}
KdPrint(("NTRTL: Re-Waiting\n"));
}
else
{
if (NT_SUCCESS(st))
{
ASSERT (Section->OwningThread == NULL);
return;
}
else
{
ExRaiseStatus (st);
}
}
}
}
VOID _UnwaitCriticalSection (PRTL_CRITICAL_SECTION Section)
{
NTSTATUS st;
KdPrint(("NTRTL: Releasing CritSect: %p ThreadId: %X\n",
Section, Section->OwningThread
));
if (!Section->LockSemaphore)
{
//
// Section is deffered. Cannot unwait such section (semaphore should be created)
//
ASSERT (FALSE);
_CheckDeferedCriticalSection (Section);
}
st = ZwSetEvent (Section->LockSemaphore, NULL);
if (NT_SUCCESS(st))
return;
ExRaiseStatus (st);
}
NTSTATUS EnterCriticalSection (PRTL_CRITICAL_SECTION Section)
{
HANDLE CurrentThread = PsGetCurrentThreadId();
if (Section->SpinCount)
{
if (Section->OwningThread == CurrentThread)
{
// Section owned by current thread.
// Increment lock count and recursion count
InterlockedIncrement (&Section->LockCount);
Section->RecursionCount ++;
return STATUS_SUCCESS;
}
// Section owned by someone else. Wait
while (TRUE)
{
if (InterlockedCompareExchange (&Section->LockCount,
0,
-1) == -1)
{
// Got lock.
Section->OwningThread = CurrentThread;
Section->RecursionCount = 1;
return STATUS_SUCCESS;
}
//
// The critical section is currently owned. Spin until it is either unowned
// or the spin count has reached zero.
//
// If waiters are present, don't spin on the lock since we will never see it go free if (Section->LockCount >= 1)
//
if (Section->LockCount >= 1)
break; // Ent76
ULONG SpinCount = Section->SpinCount;
while (TRUE)
{
ZwYieldExecution (); // YIELD = REP: NOP
if (Section->LockCount == -1)
break;
SpinCount --;
if (!SpinCount)
goto _END_WHILE;
}
}
}
_END_WHILE:
// Attempt to acquire critical section
if (InterlockedIncrement (&Section->LockCount) == 0)
{
Section->OwningThread = CurrentThread;
Section->RecursionCount = 1;
return STATUS_SUCCESS;
}
// The critical section is already owned, but may be owned by the current thread.
if (Section->OwningThread != CurrentThread)
{
_WaitForCriticalSection (Section);
Section->OwningThread = CurrentThread;
Section->RecursionCount = 1;
return STATUS_SUCCESS;
}
Section->RecursionCount ++;
return STATUS_SUCCESS;
}
NTSTATUS LeaveCriticalSection (PRTL_CRITICAL_SECTION Section)
{
if (!(-- Section->RecursionCount))
{
Section->OwningThread = NULL;
if (InterlockedDecrement (&Section->LockCount) >= 0)
_UnwaitCriticalSection (Section);
}
else
{
InterlockedDecrement (&Section->LockCount);
}
return STATUS_SUCCESS;
}
VOID _CheckDeferedCriticalSection (PRTL_CRITICAL_SECTION Section)
{
if (!_CritSectInitialized)
{
ASSERT (FALSE);
return;
}
EnterCriticalSection (&DeferedCriticalSection);
__try
{
if (!Section->LockSemaphore)
_CreateCriticalSectionSemaphore (Section);
}
__finally
{
LeaveCriticalSection (&DeferedCriticalSection);
}
}
NTSTATUS InitializeCriticalSection (PRTL_CRITICAL_SECTION Section, ULONG SpinCount)
{
Section->LockCount = -1;
Section->OwningThread = NULL;
Section->RecursionCount = 0;
Section->SpinCount = SpinCount;
_CreateCriticalSectionSemaphore (Section);
Section->DebugInfo = (PRTL_CRITICAL_SECTION_DEBUG)
ExAllocatePool (PagedPool, sizeof(RTL_CRITICAL_SECTION_DEBUG));
if (Section->DebugInfo == NULL)
{
if (Section->LockSemaphore)
{
ZwClose (Section->LockSemaphore);
Section->LockSemaphore = NULL;
}
return STATUS_NO_MEMORY;
}
Section->DebugInfo->Type = 0;
Section->DebugInfo->ContentionCount = 0;
Section->DebugInfo->EntryCount = 0;
Section->DebugInfo->CriticalSection = Section;
if ((Section != &CriticalSectionLock) &&
(_CritSectInitialized != FALSE))
{
EnterCriticalSection (&CriticalSectionLock);
InsertTailList (&CriticalSectionList, &Section->DebugInfo->ProcessLocksList);
LeaveCriticalSection (&CriticalSectionLock);
}
else
{
InsertTailList (&CriticalSectionList, &Section->DebugInfo->ProcessLocksList);
}
return STATUS_SUCCESS;
}
VOID InitDeferedCriticalSection ()
{
InitializeListHead (&CriticalSectionList);
InitializeCriticalSection (&CriticalSectionLock, 1000);
InitializeCriticalSection (&DeferedCriticalSection, 1000);
_CreateCriticalSectionSemaphore (&DeferedCriticalSection);
_CritSectInitialized = TRUE;
}
VOID DeleteCriticalSection (PRTL_CRITICAL_SECTION Section)
{
NTSTATUS st;
if (Section->LockSemaphore)
{
st = ZwClose (Section->LockSemaphore);
if (!NT_SUCCESS(st))
ExRaiseStatus (st);
}
EnterCriticalSection (&CriticalSectionLock);
__try
{
RemoveEntryList (&Section->DebugInfo->ProcessLocksList);
}
__finally
{
LeaveCriticalSection (&CriticalSectionLock);
}
if (Section->DebugInfo)
ExFreePool (Section->DebugInfo);
memset (Section, 0, sizeof(RTL_CRITICAL_SECTION));
}
| [
"xgreatx@734ba020-bcf8-11dd-baed-41e496641fac"
]
| [
[
[
1,
380
]
]
]
|
6ea000f77ab872b4654bb3d14e189d0957fe0d08 | 021e8c48a44a56571c07dd9830d8bf86d68507cb | /build/vtk/vtkGL2PSExporter.h | 55026e5a3fde7ebdb88073a353e506a2ef669a4f | [
"BSD-3-Clause"
]
| permissive | Electrofire/QdevelopVset | c67ae1b30b0115d5c2045e3ca82199394081b733 | f88344d0d89beeec46f5dc72c20c0fdd9ef4c0b5 | refs/heads/master | 2021-01-18T10:44:01.451029 | 2011-05-01T23:52:15 | 2011-05-01T23:52:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,914 | h | /*=========================================================================
Program: Visualization Toolkit
Module: vtkGL2PSExporter.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .NAME vtkGL2PSExporter - export a scene as a PostScript file using GL2PS.
// .SECTION Description
// vtkGL2PSExporter is a concrete subclass of vtkExporter that writes
// high quality vector PostScript (PS/EPS), PDF or SVG files by using
// GL2PS. GL2PS can be obtained at: http://www.geuz.org/gl2ps/. This
// can be very useful when one requires publication quality pictures.
// This class works best with simple 3D scenes and most 2D plots.
// Please note that GL2PS has its limitations since PostScript is not
// an ideal language to represent complex 3D scenes. However, this
// class does allow one to write mixed vector/raster files by using
// the Write3DPropsAsRasterImage ivar. Please do read the caveats
// section of this documentation.
//
// By default vtkGL2PSExporter generates Encapsulated PostScript (EPS)
// output along with the text in portrait orientation with the
// background color of the window being drawn. The generated output
// is also compressed using zlib. The various other options are set to
// sensible defaults.
//
// The output file format (FileFormat) can be either PostScript (PS),
// Encapsulated PostScript (EPS), PDF, SVG or TeX. The file extension
// is generated automatically depending on the FileFormat. The
// default is EPS. When TeX output is chosen, only the text strings
// in the plot are generated and put into a picture environment. One
// can turn on and off the text when generating PS/EPS/PDF/SVG files
// by using the Text boolean variable. By default the text is drawn.
// The background color of the renderwindow is drawn by default. To
// make the background white instead use the DrawBackgroundOff
// function. Landscape figures can be generated by using the
// LandscapeOn function. Portrait orientation is used by default.
// Several of the GL2PS options can be set. The names of the ivars
// for these options are similar to the ones that GL2PS provides.
// Compress, SimpleLineOffset, Silent, BestRoot, PS3Shading and
// OcclusionCull are similar to the options provided by GL2PS. Please
// read the function documentation or the GL2PS documentation for more
// details. The ivar Write3DPropsAsRasterImage allows one to generate
// mixed vector/raster images. All the 3D props in the scene will be
// written as a raster image and all 2D actors will be written as
// vector graphic primitives. This makes it possible to handle
// transparency and complex 3D scenes. This ivar is set to Off by
// default. When drawing lines and points the OpenGL point size and
// line width are multiplied by a factor in order to generate
// PostScript lines and points of the right size. The
// Get/SetGlobalPointSizeFactor and Get/SetGlobalLineWidthFactor let
// one customize this ratio. The default value is such that the
// PostScript output looks close to what is seen on screen.
//
// To use this class you need to turn on VTK_USE_GL2PS when
// configuring VTK.
// .SECTION Caveats
// By default (with Write3DPropsAsRasterImage set to Off) exporting
// complex 3D scenes can take a long while and result in huge output
// files. Generating correct vector graphics output for scenes with
// transparency is almost impossible. However, one can set
// Write3DPropsAsRasterImageOn and generate mixed vector/raster files.
// This should work fine with complex scenes along with transparent
// actors.
// .SECTION See Also
// vtkExporter
// .SECTION Thanks
// Thanks to Goodwin Lawlor and Prabhu Ramachandran for this class.
#ifndef __vtkGL2PSExporter_h
#define __vtkGL2PSExporter_h
#include "vtkExporter.h"
class VTK_RENDERING_EXPORT vtkGL2PSExporter : public vtkExporter
{
public:
static vtkGL2PSExporter *New();
vtkTypeMacro(vtkGL2PSExporter,vtkExporter);
void PrintSelf(ostream& os, vtkIndent indent);
// Description:
// Specify the prefix of the files to write out. The resulting filenames
// will have .ps or .eps or .tex appended to them depending on the
// other options chosen.
vtkSetStringMacro(FilePrefix);
vtkGetStringMacro(FilePrefix);
//BTX
enum OutputFormat
{
PS_FILE,
EPS_FILE,
PDF_FILE,
TEX_FILE,
SVG_FILE
};
//ETX
// Description:
// Specify the format of file to write out. This can be one of:
// PS_FILE, EPS_FILE, PDF_FILE, TEX_FILE. Defaults to EPS_FILE.
// Depending on the option chosen it generates the appropriate file
// (with correct extension) when the Write function is called.
vtkSetClampMacro(FileFormat, int, PS_FILE, SVG_FILE);
vtkGetMacro(FileFormat, int);
void SetFileFormatToPS()
{this->SetFileFormat(PS_FILE);};
void SetFileFormatToEPS()
{this->SetFileFormat(EPS_FILE);};
void SetFileFormatToPDF()
{this->SetFileFormat(PDF_FILE);};
void SetFileFormatToTeX()
{this->SetFileFormat(TEX_FILE);};
void SetFileFormatToSVG()
{this->SetFileFormat(SVG_FILE);};
const char *GetFileFormatAsString();
//BTX
enum SortScheme
{
NO_SORT=0,
SIMPLE_SORT=1,
BSP_SORT=2
};
//ETX
// Description:
// Set the the type of sorting algorithm to order primitives from
// back to front. Successive algorithms are more memory
// intensive. Simple is the default but BSP is perhaps the best.
vtkSetClampMacro(Sort, int, NO_SORT, BSP_SORT);
vtkGetMacro(Sort,int);
void SetSortToOff()
{this->SetSort(NO_SORT);};
void SetSortToSimple()
{this->SetSort(SIMPLE_SORT);};
void SetSortToBSP()
{this->SetSort(BSP_SORT);};
const char *GetSortAsString();
// Description:
// Turn on/off compression when generating PostScript or PDF
// output. By default compression is on.
vtkSetMacro(Compress, int);
vtkGetMacro(Compress, int);
vtkBooleanMacro(Compress, int);
// Description:
// Turn on/off drawing the background frame. If off the background
// is treated as white. By default the background is drawn.
vtkSetMacro(DrawBackground, int);
vtkGetMacro(DrawBackground, int);
vtkBooleanMacro(DrawBackground, int);
// Description:
// Turn on/off the GL2PS_SIMPLE_LINE_OFFSET option. When enabled a
// small offset is added in the z-buffer to all the lines in the
// plot. This results in an anti-aliasing like solution. Defaults to
// on.
vtkSetMacro(SimpleLineOffset, int);
vtkGetMacro(SimpleLineOffset, int);
vtkBooleanMacro(SimpleLineOffset, int);
// Description:
// Turn on/off GL2PS messages sent to stderr (GL2PS_SILENT). When
// enabled GL2PS messages are suppressed. Defaults to off.
vtkSetMacro(Silent, int);
vtkGetMacro(Silent, int);
vtkBooleanMacro(Silent, int);
// Description:
// Turn on/off the GL2PS_BEST_ROOT option. When enabled the
// construction of the BSP tree is optimized by choosing the root
// primitives leading to the minimum number of splits. Defaults to
// on.
vtkSetMacro(BestRoot, int);
vtkGetMacro(BestRoot, int);
vtkBooleanMacro(BestRoot, int);
// Description:
// Turn on/off drawing the text. If on (default) the text is drawn.
// If the FileFormat is set to TeX output then a LaTeX picture is
// generated with the text strings. If off text output is
// suppressed.
vtkSetMacro(Text, int);
vtkGetMacro(Text, int);
vtkBooleanMacro(Text, int);
// Description:
// Turn on/off landscape orientation. If off (default) the
// orientation is set to portrait.
vtkSetMacro(Landscape, int);
vtkGetMacro(Landscape, int);
vtkBooleanMacro(Landscape, int);
// Description:
// Turn on/off the GL2PS_PS3_SHADING option. When enabled the
// shfill PostScript level 3 operator is used. Read the GL2PS
// documentation for more details. Defaults to on.
vtkSetMacro(PS3Shading, int);
vtkGetMacro(PS3Shading, int);
vtkBooleanMacro(PS3Shading, int);
// Description:
// Turn on/off culling of occluded polygons (GL2PS_OCCLUSION_CULL).
// When enabled hidden polygons are removed. This reduces file size
// considerably. Defaults to on.
vtkSetMacro(OcclusionCull, int);
vtkGetMacro(OcclusionCull, int);
vtkBooleanMacro(OcclusionCull, int);
// Description:
// Turn on/off writing 3D props as raster images. 2D props are
// rendered using vector graphics primitives. If you have hi-res
// actors and are using transparency you probably need to turn this
// on. Defaults to Off.
vtkSetMacro(Write3DPropsAsRasterImage, int);
vtkGetMacro(Write3DPropsAsRasterImage, int);
vtkBooleanMacro(Write3DPropsAsRasterImage, int);
// Description:
// Set the ratio between the OpenGL PointSize and that used by GL2PS
// to generate PostScript. Defaults to a ratio of 5/7.
static void SetGlobalPointSizeFactor(float val);
static float GetGlobalPointSizeFactor();
// Description:
// Set the ratio between the OpenGL LineWidth and that used by GL2PS
// to generate PostScript. Defaults to a ratio of 5/7.
static void SetGlobalLineWidthFactor(float val);
static float GetGlobalLineWidthFactor();
protected:
vtkGL2PSExporter();
~vtkGL2PSExporter();
void WriteData();
char *FilePrefix;
int FileFormat;
int Sort;
int Compress;
int DrawBackground;
int SimpleLineOffset;
int Silent;
int BestRoot;
int Text;
int Landscape;
int PS3Shading;
int OcclusionCull;
int Write3DPropsAsRasterImage;
private:
vtkGL2PSExporter(const vtkGL2PSExporter&); // Not implemented
void operator=(const vtkGL2PSExporter&); // Not implemented
};
inline const char *vtkGL2PSExporter::GetSortAsString(void)
{
if ( this->Sort == NO_SORT )
{
return "Off";
}
else if ( this->Sort == SIMPLE_SORT )
{
return "Simple";
}
else
{
return "BSP";
}
}
inline const char *vtkGL2PSExporter::GetFileFormatAsString(void)
{
if ( this->FileFormat == PS_FILE )
{
return "PS";
}
else if ( this->FileFormat == EPS_FILE )
{
return "EPS";
}
else if ( this->FileFormat == PDF_FILE )
{
return "PDF";
}
else if ( this->FileFormat == TEX_FILE )
{
return "TeX";
}
else
{
return "SVG";
}
}
#endif
| [
"ganondorf@ganondorf-VirtualBox.(none)"
]
| [
[
[
1,
310
]
]
]
|
63ca234279e3d2dd3dce829fad1d5f1cca48d804 | 00c36cc82b03bbf1af30606706891373d01b8dca | /Renderers/Ogre/Renderer_Ogre/Renderer_Ogre_Viewport.cpp | 0c37aa15a0e67ab925adf6d8f2e68e13ce514df8 | [
"BSD-3-Clause"
]
| permissive | VB6Hobbyst7/opengui | 8fb84206b419399153e03223e59625757180702f | 640be732a25129a1709873bd528866787476fa1a | refs/heads/master | 2021-12-24T01:29:10.296596 | 2007-01-22T08:00:22 | 2007-01-22T08:00:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,749 | cpp | // OpenGUI (http://opengui.sourceforge.net)
// This source code is released under the BSD License
// See LICENSE.TXT for details
#include "Renderer_Ogre_Viewport.h"
#include "OgreRenderTarget.h"
namespace OpenGUI {
//#####################################################################
OgreViewport::OgreViewport( Ogre::Viewport* ogreViewportPtr ) {
mOgreViewport = ogreViewportPtr;
if ( !mOgreViewport )
OG_THROW( Exception::ERR_INVALIDPARAMS, "Invalid pointer to Ogre Viewport", __FUNCTION__ );
mOgreRenderTarget = mOgreViewport->getTarget();
if ( !mOgreRenderTarget ) // this test is required until Ogre adds true Viewport listeners
OG_THROW( Exception::ERR_INVALIDPARAMS, "Cannot create OpenGUI::OgreViewport from Ogre::Viewport that has no RenderTarget", __FUNCTION__ );
mOgreRenderTarget->addListener( this );
}
//#####################################################################
OgreViewport::~OgreViewport() {
if ( mOgreRenderTarget )
mOgreRenderTarget->removeListener( this );
}
//#####################################################################
Ogre::Viewport* OgreViewport::getOgreViewport() {
return mOgreViewport;
}
//#####################################################################
//////////////////////////////////////////////////////////////////////////
// OpenGUI::Viewport methods //
//////////////////////////////////////////////////////////////////////////
const IVector2& OgreViewport::getSize() {
if ( !mOgreViewport )
OG_THROW( Exception::ERR_INTERNAL_ERROR, "No attached Viewport to obtain size information", __FUNCTION__ );
static IVector2 retval;
retval.x = mOgreViewport->getActualWidth();
retval.y = mOgreViewport->getActualHeight();
return retval;
}
//#####################################################################
void OgreViewport::preUpdate( Screen* updatingScreen ) {
/* no operation */
}
//#####################################################################
void OgreViewport::postUpdate( Screen* updatingScreen ) {
/* no operation */
}
//#####################################################################
void OgreViewport::screenAttached( Screen* attachingScreen ) {
/* no operation */
}
//#####################################################################
void OgreViewport::screenDetached( Screen* detachingScreen ) {
/* no operation */
}
//#####################################################################
//////////////////////////////////////////////////////////////////////////
// Ogre::RenderTargetListener methods //
//////////////////////////////////////////////////////////////////////////
void OgreViewport::preRenderTargetUpdate( const Ogre::RenderTargetEvent& evt ) {
/* no operation */
}
//#####################################################################
void OgreViewport::postRenderTargetUpdate( const Ogre::RenderTargetEvent& evt ) {
/* no operation */
}
//#####################################################################
void OgreViewport::preViewportUpdate( const Ogre::RenderTargetViewportEvent& evt ) {
/* no operation */
}
//#####################################################################
void OgreViewport::postViewportUpdate( const Ogre::RenderTargetViewportEvent& evt ) {
// we only care about our particular viewport
if ( mOgreViewport == evt.source && mOgreViewport->getOverlaysEnabled() ) {
// iterate screens in order and update them
const ScreenSet& screenSet = getScreenSet();
ScreenSet::const_iterator iter = screenSet.begin();
ScreenSet::const_iterator iterend = screenSet.end();
for ( ;iter != iterend;iter++ ) {
Screen* screen = ( *iter );
if ( screen->isAutoUpdating() ) // only update screens that are auto updating
screen->update();
}
}
}
//#####################################################################
void OgreViewport::viewportAdded( const Ogre::RenderTargetViewportEvent& evt ) {
/* no operation */
}
//#####################################################################
void OgreViewport::viewportRemoved( const Ogre::RenderTargetViewportEvent &evt ) {
// We need to warn against unlinking the target Viewport from its RenderTarget
if ( evt.source == mOgreViewport )
OG_THROW( Exception::ERR_INTERNAL_ERROR, "OpenGUI::OgreViewport cannot follow detached Ogre::Viewports", __FUNCTION__ );
// and just in case they fail to listen, do the right thing and detach
if ( mOgreRenderTarget )
mOgreRenderTarget->removeListener( this );
mOgreRenderTarget = 0;
mOgreViewport = 0;
}
//#####################################################################
}
| [
"zeroskill@2828181b-9a0d-0410-a8fe-e25cbdd05f59"
]
| [
[
[
1,
107
]
]
]
|
f7d5095b230ddc14f44e25bc3d287f74c9e1dd1a | ce262ae496ab3eeebfcbb337da86d34eb689c07b | /SEFoundation/SEEffects/SEBumpMapL1Effect.cpp | e821c4865526acf25e453e4e6278e83bad6e3227 | []
| no_license | pizibing/swingengine | d8d9208c00ec2944817e1aab51287a3c38103bea | e7109d7b3e28c4421c173712eaf872771550669e | refs/heads/master | 2021-01-16T18:29:10.689858 | 2011-06-23T04:27:46 | 2011-06-23T04:27:46 | 33,969,301 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,120 | cpp | // Swing Engine Version 1 Source Code
// Most of techniques in the engine are mainly based on David Eberly's
// Wild Magic 4 open-source code.The author of Swing Engine learned a lot
// from Eberly's experience of architecture and algorithm.
// Several sub-systems are totally new,and others are re-implimented or
// re-organized based on Wild Magic 4's sub-systems.
// Copyright (c) 2007-2010. All Rights Reserved
//
// Eberly's permission:
// Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or (at
// your option) any later version. The license is available for reading at
// the location:
// http://www.gnu.org/copyleft/lgpl.html
#include "SEFoundationPCH.h"
#include "SEBumpMapL1Effect.h"
using namespace Swing;
SE_IMPLEMENT_RTTI(Swing, SEBumpMapL1Effect, SEShaderEffect);
SE_IMPLEMENT_STREAM(SEBumpMapL1Effect);
SE_IMPLEMENT_DEFAULT_STREAM(SEBumpMapL1Effect, SEShaderEffect);
SE_IMPLEMENT_DEFAULT_NAME_ID(SEBumpMapL1Effect, SEShaderEffect);
//SE_REGISTER_STREAM(SEBumpMapL1Effect);
//----------------------------------------------------------------------------
SEBumpMapL1Effect::SEBumpMapL1Effect(const char* acBaseName,
const char* acNormalName)
:
SEShaderEffect(1)
{
m_VShader[0] = SE_NEW SEVertexShader("BumpMapL1.v_BumpMapL1");
m_PShader[0] = SE_NEW SEPixelShader("BumpMapL1.p_BumpMapL1");
m_PShader[0]->SetTextureCount(2);
m_PShader[0]->SetImageName(0, acBaseName);
m_PShader[0]->SetImageName(1, acNormalName);
}
//----------------------------------------------------------------------------
SEBumpMapL1Effect::SEBumpMapL1Effect()
{
}
//----------------------------------------------------------------------------
SEBumpMapL1Effect::~SEBumpMapL1Effect()
{
}
//---------------------------------------------------------------------------- | [
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
]
| [
[
[
1,
54
]
]
]
|
5f1b136a0e128ffdb3d3bb1a487255a958c5c3cf | c63685bfe2d1ecfdfebcda0eab70642f6fcf4634 | /HDRRendering/HDRRendering/Singleton.h | bb1f206aff6735c3a05e89be3c165ff332d1f6f0 | []
| no_license | Shell64/cgdemos | 8afa9272cef51e6d0544d672caa0142154e231fc | d34094d372fea0536a5b3a17a861bb1a1bfac8c4 | refs/heads/master | 2021-01-22T23:26:19.112999 | 2011-10-13T12:38:10 | 2011-10-13T12:38:10 | 35,008,078 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 688 | h | #ifndef __SINGLETON_H__
#define __SINGLETON_H__
//
// Derive this class to implement your singleton class
// Don't forget to add this class as FriendClass in your singleton class
// ex :
// class T : public Singleton<T>
// {
// friend class Singleton<T>;
// private:
// ...
// };
//
template <class T>
class Singleton
{
private:
// Copy prohibited
Singleton(Singleton&);
void operator =(Singleton&);
protected:
// Default constructor
Singleton() {}
// Destructor
virtual ~Singleton() {}
public:
// Get single class instance
static T* get()
{
static T inst;
return &inst;
}
};
#endif // __SINGLETON_H__
| [
"hpsoar@6e3944b4-cba9-11de-a8df-5d31f88aefc0"
]
| [
[
[
1,
44
]
]
]
|
df0f465301110382408048ecab50b7a8d01bbb88 | 3e6c84b21cfc7c9571ef06c202c735c875bd22c3 | /MainForm.h | 98aaba57d756606e0428123c7637b9814a46c3ed | []
| no_license | qkdreyer/neoxtrainer3 | 9a719eaf7bfc6a235ef100074d662c487ec55b24 | 7ea3027e22944cc4d47026beea4170028d27f034 | refs/heads/master | 2020-12-25T18:22:31.593790 | 2011-11-13T16:35:24 | 2011-11-13T16:35:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 771 | h | /*
* File: MainForm.h
* Author: Quentin
*
* Created on 11 novembre 2011, 23:05
*/
#ifndef _MAINFORM_H
#define _MAINFORM_H
#include "ui_MainForm.h"
#include <QMessageBox>
#include "CharacterDelegate.h"
#include "CharacterForm.h"
#include "DatabaseManager.h"
#include "AboutForm.h"
#include "MapleStory.h"
class MainForm : public QDialog {
Q_OBJECT
public:
MainForm();
virtual ~MainForm();
public slots:
void execCharacterForm(); // add or edit
void deleteCharacter();
void loginCharacter();
void aboutNeoxTrainer();
void saveCharacter(Character); // add and edit
void setButtonsStates(QModelIndex);
private:
Ui::MainForm widget;
DatabaseManager dbm;
};
#endif /* _MAINFORM_H */
| [
"[email protected]"
]
| [
[
[
1,
37
]
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.